本帖最后由 RyanBern 于 2020-12-31 15:00 编辑
5 楼猫叔的代码总觉的哪里不对 。随机给比较赋值有可能根本定义不出来全序,虽然看起来也打乱了但是随机性就不知道是啥了。
应该用 sort_by 来完成。见 https://stackoverflow.com/questi ... le-an-array-in-ruby
下面这个实现也很不错,是 shuffle 的标准实现。如果是 sample 的话也只需要简单修改即可完成任务。
class Array # Standard in Ruby 1.8.7+. See official documentation[[url]http://ruby-doc.org/core-1.9/classes/Array.html[/url]] def shuffle dup.shuffle! end unless method_defined? :shuffle # Standard in Ruby 1.8.7+. See official documentation[[url]http://ruby-doc.org/core-1.9/classes/Array.html[/url]] def shuffle! size.times do |i| r = i + Kernel.rand(size - i) self[i], self[r] = self[r], self[i] end self end unless method_defined? :shuffle! def sample(n = 1) n = [n, size].min tmp = self.clone n.times do |i| r = i + Kernel.rand(size - i) tmp[i], tmp[r] = tmp[r], tmp[i] end tmp[(0...n)] end unless method_defined? :sample end
class Array
# Standard in Ruby 1.8.7+. See official documentation[[url]http://ruby-doc.org/core-1.9/classes/Array.html[/url]]
def shuffle
dup.shuffle!
end unless method_defined? :shuffle
# Standard in Ruby 1.8.7+. See official documentation[[url]http://ruby-doc.org/core-1.9/classes/Array.html[/url]]
def shuffle!
size.times do |i|
r = i + Kernel.rand(size - i)
self[i], self[r] = self[r], self[i]
end
self
end unless method_defined? :shuffle!
def sample(n = 1)
n = [n, size].min
tmp = self.clone
n.times do |i|
r = i + Kernel.rand(size - i)
tmp[i], tmp[r] = tmp[r], tmp[i]
end
tmp[(0...n)]
end unless method_defined? :sample
end
|