Sha256: eddc3b7bad7c09afba0f732e239d03e5f0e81abc524f8e29e220542412812fff

Contents?: true

Size: 692 Bytes

Versions: 1

Compression:

Stored size: 692 Bytes

Contents

class Array

  # Randomize the order of an array.
  #
  #   require 'facet/array/shuffle'
  #
  #   [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.
  #
  #   require 'facet/array/shuffle'
  #
  #   a = [1,2,3,4]
  #   a.shuffle!
  #   a  #=> [2,4,1,3]
  #
  #--
  # Credit goes to Niel Spring.
  #++
  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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
facets-0.6.3 lib/facet/array/shuffle.rb