Sha256: 0e26fbb745b1e0bd270c04f2aa0e701d03bccfc06330ecbc52893648ced30756

Contents?: true

Size: 745 Bytes

Versions: 1

Compression:

Stored size: 745 Bytes

Contents

class Array

  # Applys a block to each possible permutation of an array/enumerable.
  #
  #   %w[a b c].each_permutation { |x| puts(x.join('')) }
  #
  # produces
  #
  #   abc
  #   acb
  #   bac
  #   bca
  #   cab
  #   cba
  #
  #--
  # Credit goes to Paul Battley.
  #++
  def each_permutation( prefixed=[] )
    s = self.to_a
    if (length < 2)
      # there are no elements left to permute
      yield(prefixed + self)
    else
      # recursively permute the remaining elements
      s.each_with_index do |e, i|
        (s[0,i]+s[(i+1)..-1]).each_permutation(prefixed+[e]) { |a| yield a }
      end
    end
  end

end


#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
# TODO

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
facets-0.9.0 lib/nano/enumerable/each_permutation.rb