generate rand(9) using rand(3)

妖精的绣舞 提交于 2019-12-24 01:47:31

问题


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



来源:https://stackoverflow.com/questions/11919678/generate-rand9-using-rand3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!