Sha256: a4d70f455751c8c6b57d64b4c22d4f669e06e79eb27b8511221da1756b7c0f2b

Contents?: true

Size: 976 Bytes

Versions: 47

Compression:

Stored size: 976 Bytes

Contents

unless Array.method_defined? :combination
  require 'backports/tools/arguments'
  require 'enumerator'

  class Array
    def combination(num)
      num = Backports.coerce_to_int(num)
      return to_enum(:combination, num) unless block_given?
      return self unless (0..size).include? num
      # Implementation note: slightly tricky.
                                               # Example: self = 1..7, num = 3
      picks = (0...num).to_a                   # picks start at 0, 1, 2
      max_index = ((size-num)...size).to_a           # max (index for a given pick) is [4, 5, 6]
      pick_max_pairs = picks.zip(max_index).reverse  # pick_max_pairs = [[2, 6], [1, 5], [0, 4]]
      leave = Proc.new{return self}
      loop do
        yield values_at(*picks)
        move = pick_max_pairs.find(leave){|pick, max| picks[pick] < max}.first
        new_index = picks[move] + 1
        picks[move...num] = (new_index...(new_index+num-move)).to_a
      end
    end
  end
end

Version data entries

47 entries across 47 versions & 4 rubygems

Version Path
backports-3.25.0 lib/backports/1.8.7/array/combination.rb
backports-3.24.1 lib/backports/1.8.7/array/combination.rb
backports-3.24.0 lib/backports/1.8.7/array/combination.rb
backports-3.23.0 lib/backports/1.8.7/array/combination.rb
backports-3.22.1 lib/backports/1.8.7/array/combination.rb
backports-3.22.0 lib/backports/1.8.7/array/combination.rb
backports-3.21.0 lib/backports/1.8.7/array/combination.rb
backports-3.20.2 lib/backports/1.8.7/array/combination.rb
backports-3.20.1 lib/backports/1.8.7/array/combination.rb
backports-3.20.0 lib/backports/1.8.7/array/combination.rb
backports-3.19.0 lib/backports/1.8.7/array/combination.rb
backports-3.18.2 lib/backports/1.8.7/array/combination.rb
backports-3.18.1 lib/backports/1.8.7/array/combination.rb
backports-3.18.0 lib/backports/1.8.7/array/combination.rb
files.com-1.0.55 docs/vendor/bundle/ruby/2.5.0/gems/backports-3.12.0/lib/backports/1.8.7/array/combination.rb
backports-3.17.2 lib/backports/1.8.7/array/combination.rb
backports-3.17.1 lib/backports/1.8.7/array/combination.rb
backports-3.17.0 lib/backports/1.8.7/array/combination.rb
backports-3.16.1 lib/backports/1.8.7/array/combination.rb
backports-3.16.0 lib/backports/1.8.7/array/combination.rb