#--
# 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
