
class Array

  # Returns a random subset of an Array. If a _number_
  # of elements is specified then returns that number of
  # elements, otherwise returns a random number of elements
  # upto the size of the Array.
  #
  # By defualt the returned values are exclusive of
  # each other, but if _exclusive_ is set to <tt>false</tt>,
  # the same values can be choosen more than once.
  #
  # When _exclusive_ is <tt>true</tt> (the default) and the
  # _number_ given is greater than the size of the array,
  # then all values are returned.
  #
  #   [1, 2, 3, 4].rand_subset(1)        #=> [2]
  #   [1, 2, 3, 4].rand_subset(4)        #=> [2, 1, 3, 4]
  #   [1, 2, 3, 4].rand_subset           #=> [1, 3, 4]
  #   [1, 2, 3, 4].rand_subset           #=> [2, 3]
  #
  def rand_subset( number=nil, exclusive=true )
    number = rand( size ) unless number
    number = number.to_int
    #return self.dup if (number >= size and exlusive)
    return sort_by{rand}.slice(0,number) if exclusive
    ri =[]; number.times { |n| ri << rand( size ) }
    return values_at(*ri)
  end

end



#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TCArray < Test::Unit::TestCase

    def test_rand_subset
      10.times {
        a = [1,2,3,4].rand_subset
        assert( a.size <= 4 )
      }
    end

  end

=end
