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.
相关问题
- Unity - Get Random Color at Spawning
- How to generate a random number, then display it o
- how to randomly loop over an array (shuffle) in ba
- How to fill an array with random numbers from 0 to
- Upper bound of random number generator
相关文章
- why 48 bit seed in util Random class?
- Need help generating discrete random numbers from
- Get random records with Doctrine
- Looking for a fast hash-function
- Oracle random row from table
- Generate a Random Number between 2 values to 2 dec
- What does Random(int seed) guarantee?
- What’s the best way to shuffle an array in Perl?
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)).
Here's a simple solution:
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).