generate rand(9) using rand(3)

2019-07-18 07:24发布

问题:

You have a function rand(3) which generates random integers from 1 to 3. Using this function, construct another function rand(9) which generates random integers from 1 to 9.

回答1:

Using rand(3) twice, one can generate 3^2 pairs of integers, i.e. (1,1), (1,2), ..., (3,3). Assigning each pair to one of the values [1,9] (e.g. (1,1) to 1, (1,2) to 2 etc.) will give you rand(9). Symbolically: rand(9):=(rand(3),rand(3)).



回答2:

Here's a simple solution:

rand(3) + 3*(rand(3) - 1)

The reason why you would want to do it like this is that it provides an even distribution over all of the possible values from 1 to 9.

Some people might be tempted to just do rand(3) * rand(3), but that doesn't actually generate some numbers - 7, for instance. It also unevenly distributes the numbers it does generate.

Similarly, some people might do rand(3) + rand(3) + rand(3), but this also doesn't generate all of the numbers (it'll never generate 1 or 2), and generates other numbers with disproportionate frequency (5 is generated much more often than 9).