如何将种子随机sort_by {rand}的随机值保存到ruby中的列表中?

时间:2014-03-22 16:53:08

标签: ruby sorting

我是红宝石的新手。我希望将数组保存为rand使用以下字符串评估(假设为0.78346 ....)数字的值。

rows = ["hello", "nihao", "konnichiwa", "hallo"]
myrand = Random.new(100) # seed - 100
rows.sort_by!{myrand.rand } => result could be - ["nihao ", "hello", "konnichiwa", "hallo"]

例如:[[0.12232, "nihao"],[0.53434, "hello"],[0.333, "konnichiwa"],[0.99, "hallo"]]

如何从rows.sort_by!{myrand.rand }获取此数组?

1 个答案:

答案 0 :(得分:2)

您需要先将随机数保存到数组中:

rows = ["hello", "nihao", "konnichiwa", "hallo"]
myrand = Random.new(100) # seed - 100
rows.map { |x| [myrand.rand, x] }.sort! 
=> [[0.27836938509379616, "nihao"], [0.4245175907491331, "konnichiwa"], [0.5434049417909654, "hello"], [0.8447761323199037, "hallo"]] 

上面显示的结果应始终相同,尽管这是Random,因为种子已知 - 对于Random.new(100),这些将始终是生成的前四个数字。

从技术上讲,您可以完全按照您的要求行事:

rows = ["hello", "nihao", "konnichiwa", "hallo"]
myrand = Random.new(100) # seed - 100
rows = rows.map { |x| [myrand.rand, x] }
=>  [[0.5434049417909654, "hello"], [0.27836938509379616, "nihao"], [0.4245175907491331, "konnichiwa"], [0.8447761323199037, "hallo"]] 

myrand = Random.new(100) # resetting back to seed - 100

rows.sort_by!{ myrand.rand }
=> [[0.27836938509379616, "nihao"], [0.4245175907491331, "konnichiwa"], [0.5434049417909654, "hello"], [0.8447761323199037, "hallo"]]