generate rand(9) using rand(3)

2019-07-18 07:51发布

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.

2条回答
地球回转人心会变
2楼-- · 2019-07-18 08:18

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)).

查看更多
ら.Afraid
3楼-- · 2019-07-18 08:19

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).

查看更多
登录 后发表回答