Method: Array#random_subarray

Defined in:
lib/shenanigans/array/random_subarray.rb

#random_subarray(n = 1) ⇒ Object

Generates random subarrays. Uses random numbers and bit-fiddling to assure performant uniform distributions even for large arrays.

a = *1..5
a.random_subarray(3)
#=> [[1, 3, 5], [2, 4], [1, 3, 4, 5]]

Raises:

  • (ArgumentError)


9
10
11
12
13
14
15
# File 'lib/shenanigans/array/random_subarray.rb', line 9

def random_subarray(n=1)
  raise ArgumentError, "negative argument" if n < 0
  (1..n).map do
    r = rand(2**self.size)
    self.select.with_index { |_, i| r[i] == 1 }
  end
end