@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 = <any number b/w 1...10>
therefore, if 0 < a <= 1 return 1 (only 1 case possible)
if 1 < a <= 3 return 2 (only 2 cases are possible)
if 3 < a <= 6 return 3 (only 3 cases are possible)
if 6 < a <= 10 return 4 (only 4 cases are possible)


On Tue, Aug 30, 2011 at 3:17 AM, Don <[email protected]> wrote:

> 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 <[email protected]> wrote:
> > Given a function rand(n) which returns a random value between 1...n
> assuming
> > equal probability.
> > Write a function CustRand(n) using rand(n) which returns a value between
> > 1...n such that
> > the probability of occurrence of each number is proportional to its
> value.
> >
> > I have a solution but wondering if I can get better than this or some
> other
> > approaches:
> >
> > 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;
> >     }
> >
> > }
>
> --
> You received this message because you are subscribed to the Google Groups
> "Algorithm Geeks" group.
> To post to this group, send email to [email protected].
> To unsubscribe from this group, send email to
> [email protected].
> For more options, visit this group at
> http://groups.google.com/group/algogeeks?hl=en.
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Algorithm Geeks" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/algogeeks?hl=en.

Reply via email to