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
backports-3.25.0 lib/backports/1.8.7/array/permutation.rb
backports-3.24.1 lib/backports/1.8.7/array/permutation.rb
backports-3.24.0 lib/backports/1.8.7/array/permutation.rb
backports-3.23.0 lib/backports/1.8.7/array/permutation.rb
backports-3.22.1 lib/backports/1.8.7/array/permutation.rb
backports-3.22.0 lib/backports/1.8.7/array/permutation.rb
backports-3.21.0 lib/backports/1.8.7/array/permutation.rb
backports-3.20.2 lib/backports/1.8.7/array/permutation.rb
backports-3.20.1 lib/backports/1.8.7/array/permutation.rb
backports-3.20.0 lib/backports/1.8.7/array/permutation.rb
backports-3.19.0 lib/backports/1.8.7/array/permutation.rb
backports-3.18.2 lib/backports/1.8.7/array/permutation.rb
backports-3.18.1 lib/backports/1.8.7/array/permutation.rb
backports-3.18.0 lib/backports/1.8.7/array/permutation.rb
files.com-1.0.55 docs/vendor/bundle/ruby/2.5.0/gems/backports-3.12.0/lib/backports/1.8.7/array/permutation.rb
backports-3.17.2 lib/backports/1.8.7/array/permutation.rb
backports-3.17.1 lib/backports/1.8.7/array/permutation.rb
backports-3.17.0 lib/backports/1.8.7/array/permutation.rb
backports-3.16.1 lib/backports/1.8.7/array/permutation.rb
backports-3.16.0 lib/backports/1.8.7/array/permutation.rb