CC150 19.10

19.10 Write a method to generate a random number between 1 and 7, given a method that generates a random number between 1 and 5 (i.e., implement rand7() using rand5()). 

// Like a quickcheck
// To generate random 7, we need at least call random5() twice.
// All 25 possibilities.
// A easy solution is only taking results from 1 - 7.
// But to reduce a lot retries, we can take results from 1 - 21. And divide number by 3.


static int MAX_TRY = 1000;
for (int i = 0 ; i < MAX_TRY ; i ++)
{
  int raw = (rand5() - 1 ) * 5 + rand5();
  if (raw > 21)
    continue;
  
  return ((raw - 1) / 7) + 1;
}
throw Exception("Failed to generate");


你可能感兴趣的:(interview)