重现随机数组排序 [英] Reproduce random array sort

查看:157
本文介绍了重现随机数组排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我想通过随机排序对象的数组。对于这种情况,我可以使用 array.shuffle 。但是,如果我想要的东西之后再现相同的阵列上的顺序?有没有办法,我可以提供一个种子,随机数,什么的,这样我以后可以重现此序列的任何方式?

I have an array of objects that I want to sort by random. For this case I can use array.shuffle. But what if I want to reproduce that order later on the same array? Is there any way that I can provide a seed, random number, whatever, so that I can reproduce this sequence later?

欲生成从(使用MongoID)MongoDB数据库对象的随机列表,该列表具有后再现。但据我所知,有没有真正的好办法,可以直接在MongoDB中实现随机排序。可能有很多对象(> 1,000,000),但计算时间是第一个尝试不是事实,事项。

I want to generate a random list of objects from a MongoDB database (using MongoID), and that list has to be reproduced later. But as far as I know, there is no really good way, to implement a random sort directly in MongoDB. There could be a lot of objects (>1,000,000), but computation time is for the first try not the fact that matters.

推荐答案

如果你看的红宝石文档为阵列#洗牌 你会看到你可以传递一个随机作为发电机;如果你通过一个新的随机洗牌使用相同的种子每一次,它会给出同样的结果。

If you look at the Ruby docs for Array#shuffle you'll see you can pass a Random as the generator; if you pass a new Random to shuffle using the same seed each time, it'll give the same results.

>> arr = %w{John Paul George Ringo}
=> ["John", "Paul", "George", "Ringo"]
>> arr.shuffle(random: Random.new(1))
=> ["Ringo", "John", "George", "Paul"]
>> arr.shuffle(random: Random.new(1))
=> ["Ringo", "John", "George", "Paul"]
>> arr.shuffle(random: Random.new(1))
=> ["Ringo", "John", "George", "Paul"]

编辑:这可以扩展到具有阵列#洗牌制作的多个的重复shufflings,让每一个人洗牌和shufflings的序列,同时可以重来,通过使用一个随机(而不是每次一个新的),并使用相同的种子更新它重复:

This can be extended to have Array#shuffle produce multiple repeatable shufflings, so that both each individual shuffle and the sequence of shufflings can be repeated, by using one Random (rather than a new one each time) and renewing it with the same seed to repeat:

>> arr = [1, 2, 3, 4] => [1, 2, 3, 4]
>> r = Random.new(17) => #<Random:0x000000017be4d0>
>> arr.shuffle(random: r) => [3, 1, 4, 2]
>> arr.shuffle(random: r) => [1, 3, 2, 4]
>> arr.shuffle(random: r) => [4, 3, 2, 1]
>> r = Random.new(17) => #<Random:0x00000001c60da8>
>> arr.shuffle(random: r) => [3, 1, 4, 2]
>> arr.shuffle(random: r) => [1, 3, 2, 4]
>> arr.shuffle(random: r) => [4, 3, 2, 1]
>> etc.
?> 

这篇关于重现随机数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆