为什么这些随机种子打印'Hello World'?

时间:2013-03-11 02:26:04

标签: ruby tree random-seed

使用这些随机种子值会生成'Hello Word',但为什么?

seeds = [685_995_739, 811_060_588]

tree = seeds.map do |seed|
    srand seed
    leafs = leaf = '' # seed grow, become leaf
    leafs += (leaf + 64).chr while (leaf = rand(27)) > 0
    next leafs
end

puts tree.join ' ' # Seed become tree =D

1 个答案:

答案 0 :(得分:0)

阅读srand的文档,这些种子是rand(27)将选择代表“Hello”和“World”的数字序列,以“0”结尾以“表示结束”的种子”

irb(main):042:0> srand 685_995_739
=> 0
irb(main):043:0> rand 27
=> 8
irb(main):044:0> rand 27
=> 5
irb(main):045:0> rand 27
=> 12
irb(main):046:0> rand 27
=> 12
irb(main):047:0> rand 27
=> 15
irb(main):048:0> rand 27
=> 0
irb(main):049:0> [8,5,12,12,15].map{ |n| (n+64).chr }
=> ["H", "E", "L", "L", "O"]

留给读者一个练习:编写一个脚本,找到给定结果字符串的正确种子,该字符串在适当的时间内运行; o)