Sha256: 2bcce62c022e45b3d7691220833543cd7327a4bf0ca884a698364c497603bb29
Contents?: true
Size: 1 KB
Versions: 26
Compression:
Stored size: 1 KB
Contents
#-- # Credit goes to Niel Spring. #++ class Array # Randomize the order of an array. # # [1,2,3,4].shuffle #=> [2,4,1,3] # def shuffle dup.shuffle! #sort_by{Kernel.rand} end # As with #shuffle but modifies the array in place. # The algorithm used here is known as a Fisher-Yates shuffle. # # a = [1,2,3,4] # a.shuffle! # a #=> [2,4,1,3] # def shuffle! s = size each_index do |j| i = Kernel.rand(s-j) #self[j], self[j+i] = self[j+i], self[j] tmp = self[j] self[j] = self[j+i] self[j+i] = tmp end self end end # _____ _ # |_ _|__ ___| |_ # | |/ _ \/ __| __| # | | __/\__ \ |_ # |_|\___||___/\__| # =begin test require 'test/unit' class TCArray < Test::Unit::TestCase def test_shuffle a = [1,2,3,4,5] b = a.shuffle assert_equal( a, b.sort ) end def test_shuffle! a = [1,2,3,4,5] b = a.dup b.shuffle! assert_equal( a, b.sort ) end end =end
Version data entries
26 entries across 26 versions & 1 rubygems