Probability and Computer science question

60 Views Asked by At

We are given a function rand() that returns a random number from the segment [0,1],
how can we use this function to create a size $100$ uniform array,
of exactly $50$ $0's$ and $50$ $1's$.

1

There are 1 best solutions below

0
On BEST ANSWER

First idea:

  1. Create an array $a$ with 100 zeroes. I'll assume that array index is zero based.
  2. Set counter to zero.
  3. Create integer $i$ in the following way: $i=(int)(100*rand())$. This returns a random index between 0 and 99 (inclusive).
  4. If $a(i)=1$, repeat step 3. If not, set $a(i)=1$ and increment the counter.
  5. Repeat steps 3 and 4 as long as counter < 50

Second idea:

  1. Create an array of 100 random values between 0.0 and 1.0
  2. Find $M$, the median value of the array (basically a value such that 50 generated values are smaller and 50 generated values are bigger than it). There are algorithms for that that run in linear time. Full explanation can be found here.
  3. Go through the list again and replace all values smaller than $M$ with 0 and the rest with $1$.