Skip to content

Instantly share code, notes, and snippets.

@stephenjudkins
Created September 9, 2009 23:52
Show Gist options
  • Save stephenjudkins/184185 to your computer and use it in GitHub Desktop.
Save stephenjudkins/184185 to your computer and use it in GitHub Desktop.
module Enumerable
def permutations
Enumerable::Enumerator.new(self, :each_permutation)
end
def each_permutation
each do |item|
others = select {|other| item != other}
others.permutations.each do |other_permutation|
yield [item] + other_permutation
end
yield [item]
end
end
end
puts [1,2].permutations.to_a.inspect
puts [1,2,3,4].permutations.to_a.length.inspect
puts [1,2,3,4].permutations.to_a.uniq.length.inspect
puts ["foo", "bar"].permutations.to_a.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment