This is one way to accomplish the job with one call to rand and no
looping. It does limit the value of "n" to be less than 65536. If you
want to allow larger values of n, you can use two calls to rand, one
for a and the other for b.
Don
int custRand(int n)
{
int a = rand(n*n+n)-1;
@Prabhat
CustRand(n){
sum = n*(n+1)/2;
a = rand(sum);
for(i = 1; i <= n; i++){
h = i*(i+1)/2;
l = i*(i-1)/2;
if(a <= h && a > l)
return i;
}
}
Take an example of say 4
so sum = 10
and a =
therefore, if 0 < a <= 1 return 1 (only 1 case
Here is how to do it with a single call to rand and no looping.
int custRand(int n)
{
int a = rand(n*n+n);
int b = a / n;
a %= n;
return (b > a) ? n+a-b+1 : n-a+b;
}
On Aug 29, 10:48 am, Piyush Grover wrote:
> Given a function rand(n) which returns a random value
Since the complexity of the random number generator module is not given, I
don't think its a good idea to repeatedly call the function. Instead we can
try,
int sum = n*(n+1)/2;
int result = rand(sum);
int sub = n-1;
do
{
if(result<=n && result>0)
return result;
else
{
Total # of cases when a - b = 0; 5 return 5
Total # of cases when a-b = 1; 4 return 4
Total # of cases when a-b = 2; 3 return 3
Sorry, it is misleading...it should be
Total # of cases when a - b = 0; 5 return 5 is probable 5 times
Total # of cases when a-b = 1; 4 return 4 is probable 4 time
No, a+b-1 would return values outside of the desired range.
Don
On Aug 29, 12:26 pm, nishaanth wrote:
> @Don...Nice solution.. But the return statement should be a+b-1
>
>
>
> On Mon, Aug 29, 2011 at 10:33 PM, Don wrote:
> > If you draw the nxn grid and assign a value to each diagonal:
>
> > (Fo
No...if a = b = 5 then return 9 doesn't make any sense.
n - (a-b) is very much fine.
for n = 5
Total # of cases when a - b = 0; 5 return 5
Total # of cases when a-b = 1; 4 return 4
Total # of cases when a-b = 2; 3 return 3
and so on.
On Mon, Aug 29, 2011 at 10:56 PM, nishaanth wrote:
> @D
@Don...Nice solution.. But the return statement should be a+b-1
On Mon, Aug 29, 2011 at 10:33 PM, Don wrote:
> If you draw the nxn grid and assign a value to each diagonal:
>
> (For n = 5)
>
> --b
> | 12345
> | 2345
> | 345
> | 45
> | 5
> a
>
> You want the result to be the orthogo
If you draw the nxn grid and assign a value to each diagonal:
(For n = 5)
--b
| 12345
| 2345
| 345
| 45
| 5
a
You want the result to be the orthogonal distance from the diagonal.
That is what the formula computes.
Don
On Aug 29, 11:28 am, Piyush Grover wrote:
> I understand what
I understand what you are doing in the loop but return statement is not
clear to me. Can you explain.
On Mon, Aug 29, 2011 at 9:48 PM, Don wrote:
> int custRand(int n)
> {
>int a,b;
>do
>{
>a = rand(n);
>b = rand(n);
>} while(a < b)
int custRand(int n)
{
int a,b;
do
{
a = rand(n);
b = rand(n);
} while(a < b);
return n - a + b;
}
On Aug 29, 10:48 am, Piyush Grover wrote:
> Given a function rand(n) which returns a random value between 1...n assuming
> equa
11 matches
Mail list logo