Google interview question: Given a function that generates integers 1 to 5 at random, write a function that generates integers 1 to 7 at random.

Source: Internet
Author: User

We know that a function f can obtain a random number ranging from 1 to 5 with equal probability. How can we obtain a random number ranging from 1 to 7 with equal probability?

Int rand7 ()
{
Int;
While (A = rand5 () * 5 + rand5 ()> 26 );
Return (A-3)/3;
}

AlgorithmThe idea is:
1. Use rand5 () * 5 + rand5 () to generate 6 7 8 9 10 11 ...... 26, 27, 28, 29, 30, and the occurrence rate of each number is equal.
2. Only the first 3*7 numbers are required, so the four numbers are discarded.
3. convert 6 7 8 to 1, 9 10 11 to 2 ,......, 24 25 26 to 7. Formula is (A-3)/3


As long as we can randomly select 1 to n numbers from N numbers, and perform this operation repeatedly until the last number is left.
We can call the given function n times to generate n random numbers between 1 and 5, and select the location of the maximum number to meet the above requirements.

For example
The initial number of 7 numbers [1, 2, 3, 4, 5, 6, 7].
7 random numbers from 1 to 5 [5, 3, 1, 4, 2, 5]
Then we reserve [, 7],
Three random numbers from 1 to 5 [2, 4, 1]
Then we keep the [6]
6 is the random number generated this time.

Compile a random function that generates 0 and 1:
Step1. call the given random function original_rand () to generate a number.
If = 3 goto Step1
If <3 return 0
If> 3 return 1

Compile a random function to generate 1 to 7
Call the Random Functions of 0 and 1 three times to generate 000 or 001 or 010 .......
If ??? Returns if the value is not equal to 0. Otherwise, it is generated again.CodeAs follows:

int rand_01 ()
{< br> int r = original_rand ();
If (r = 3) return rand_01 ();
If (r <3) return 0;
If (r> 3) return 1;
}int rand_17 ()
{< br> int I = 0;
I + = rand_01 ();
I + = rand_01 () <1;
I + = rand_01 () <2;
if (I = 0) return rand_17 ();
return I;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.