Random number generator from binary input
This question is likely if you are dealing with quantum randomizers, etc. It’s irrelevant if there is an appropriate function in the language.
You are given a function that generates 0 and 1 with equal probability. Write a function that uses the above function to generate any n(1<=n<=1000) so that probability of producing any number between 1 to 1000 is equal and is 1/1000.
The solution is simple and fast using bit shifting (which gives performance, *2 could be used but that will raise flags with many interviewers)
- static Random _Ran = new Random();
- public static int ZeroOne()
- {
- return _Ran.Next(2);
- }
- /// <summary>
- /// We bitshift for optimal performance
- /// </summary>
- /// <returns></returns>
- public static int Random1to1000()
- {
- var num = 0;
- var outofrange = true;
- while (outofrange)
- {
- num = ZeroOne() << 1;
- for (int i = 0; i < 8; i++)
- {
- num = (num | ZeroOne()) << 1;
- }
- num = num | ZeroOne();
- outofrange = num > 1000 || num < 1;
- }
- return num;
- }
Often the ZeroOne would be put internal to the Random1to1000(). If this is done, then to ask for it to be moved to an external function ZeroOne() will usually reveal whether there is understanding of Random issues (i.e. initializing Random inside of ZeroOne will not only result in poorer performance, but will also loose randomness!).
The testing is simple:
- var cnt = new int[1002];
- for (var i = 1; i < 10000; i++)
- {
- var num = Questions.Random1to1000();
- cnt[num]++;
- }
- for (var i = 0; i < cnt.Length; i++)
- {
- Console.WriteLine(string.Format("{0}: {1}", i, cnt[i]));
- }
- Console.WriteLine(string.Format("{0}: {1}", 0, cnt[0]));
- Console.WriteLine(string.Format("{0}: {1}", 1, cnt[1]));
- Console.WriteLine(string.Format("{0}: {1}", 1000, cnt[1000]));
- Console.WriteLine(string.Format("{0}: {1}", 1001, cnt[1001]));
The results allows spot testing:
Often people will assume that zero(0) will not occur from the code (to see a lot of code that allows a zero to be returned, see this).
Comments
Post a Comment