Saturday, May 10, 2014

In this post, I want to include a puzzle I came across online.
Write a function to generate random numbers .
The problem talks about pseudo-random number generation since true  random number can be difficult. This can be done in many ways.
It is generally best to use built-in pseudo random number generators such as Math.Random
However, I want to describe the problem this way. Generate random numbers between 0 to 3 and print them. The only test I have is that calling the function three times doesn't result in same sequence more than half the number of times the function is called.
By restricting the size of the array, I'm going to use the index and the contents of the array.
for( int i = 0; i <= N; i++)
  {
     Swap(h[i], h[Math.Random(0,N-1)]);
  }
return h[n];
we could probably optimize this to just iterate over half the array.

Some languages implement random number as follows:
int next(int n)
{
seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1))
return (int)(seed >>> (48 - n));

or Mersenne Twister based such as in C documentation:
int rand(void)
{
 next  = next  * 1103515245  + 12345;
return (unsigned int )(next/2 * (RAND_MAX + 1L) % (RAND_MAX + 1L));
}

No comments:

Post a Comment