Sha256: eaba33b3d46e96de020b64760ab3b5df979f6c9f3de7dc1fbecaa6b31af0c599

Contents?: true

Size: 823 Bytes

Versions: 47

Compression:

Stored size: 823 Bytes

Contents

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

  class Array
    def permutation(num = Backports::Undefined)
      return to_enum(:permutation, num) unless block_given?
      num = num.equal?(Backports::Undefined) ?
            size :
            Backports.coerce_to_int(num)
      return self unless (0..size).include? num

      final_lambda = lambda do |partial, remain|
        yield partial
      end

      outer_lambda = (1..num).inject(final_lambda) do |proc, _|
        lambda do |partial, remain|
          remain.each_with_index do |val, i|
            new_remain = remain.dup
            new_remain.delete_at(i)
            proc.call(partial.dup << val, new_remain)
          end
        end
      end

      outer_lambda.call([], dup)
    end
  end
end

Version data entries

47 entries across 47 versions & 4 rubygems

Version Path
honeybadger-4.5.3 vendor/bundle/ruby/2.6.0/gems/backports-3.15.0/lib/backports/1.8.7/array/permutation.rb
backports-3.15.0 lib/backports/1.8.7/array/permutation.rb
backports-3.14.0 lib/backports/1.8.7/array/permutation.rb
backports-3.13.0 lib/backports/1.8.7/array/permutation.rb
backports-3.12.0 lib/backports/1.8.7/array/permutation.rb
backports-3.11.4 lib/backports/1.8.7/array/permutation.rb
backports-3.11.3 lib/backports/1.8.7/array/permutation.rb
backports-3.11.2 lib/backports/1.8.7/array/permutation.rb
backports-3.11.1 lib/backports/1.8.7/array/permutation.rb
backports-3.11.0 lib/backports/1.8.7/array/permutation.rb
backports-3.10.3 lib/backports/1.8.7/array/permutation.rb
backports-3.10.2 lib/backports/1.8.7/array/permutation.rb
backports-3.10.1 lib/backports/1.8.7/array/permutation.rb
backports-3.10.0 lib/backports/1.8.7/array/permutation.rb
backports-3.9.1 lib/backports/1.8.7/array/permutation.rb
backports-3.9.0 lib/backports/1.8.7/array/permutation.rb
backports-3.8.0 lib/backports/1.8.7/array/permutation.rb
backports-3.7.0 lib/backports/1.8.7/array/permutation.rb
mdg-1.0.1 vendor/bundle/ruby/2.3.0/gems/backports-3.6.8/lib/backports/1.8.7/array/permutation.rb
backports-3.6.8 lib/backports/1.8.7/array/permutation.rb