# Sunday, May 03, 2009

I have played around and I write "testing environment" for this Rand(7) algorithm. For example if you want to try what distribution gives your algorithm or how much iterations takes to generate all distinct random values (for Rand(7) 1-7), you can use it.

My core algorithm is this:

return (Rand5() + Rand5()) % 7 + 1;

Well is no less uniformly distributed then Adam Rosenfield's one. (which I included in my snippet code)

private static int Rand7WithRand5()
{
   
//PUT YOU FAVOURITE ALGORITHM HERE//

   
//1. Stackoverflow winner
   
int i;
   
do
   
{
        i
= 5 * (Rand5() - 1) + Rand5(); // i is now uniformly random between 1 and 25
   
} while (i > 21);
   
// i is now uniformly random between 1 and 21
   
return i % 7 + 1;

   
//My 2 cents
   
//return (Rand5() + Rand5()) % 7 + 1;
}

This "testing environment" can take any Rand(n) algorithm and test and evaluate it (distribution and speed). Just put your code into the "Rand7WithRand5" method and run the snippet.

Few observations:

  • Adam Rosenfield's algorithm is no better distributed then, for example, mine. Anyway, both algorithms distribution is horrible.
  • Native Rand7 (random.Next(1, 8)) is completed as it generated all members in given interval in around 200+ iterations, Rand7WithRand5 algorithms take order of 10k (around 30-70k)
  • Real challenge is not to write a method to generate Rand(7) from Rand(5), but it generate values more or less uniformly distributed.
Discussion on this is on Stackoverflow.

posted on Sunday, May 03, 2009 1:21:22 PM (Central European Daylight Time, UTC+02:00)  #    Comments [0] Trackback