Method: Array#each_permutation

Defined in:
lib/nano/enumerable/each_permutation.rb

#each_permutation(prefixed = []) ⇒ Object

Applys a block to each possible permutation of an array.

%w[a b c].each_permutation { |x| puts(x.join('')) }

produces

abc
acb
bac
bca
cab
cba

– Credit goes to Paul Battley. ++



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/nano/enumerable/each_permutation.rb', line 20

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]).permute(prefixed+[e]) { |a| yield a }
    end
  end
end