Skip to content

Instantly share code, notes, and snippets.

@mikewadhera
Last active December 20, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikewadhera/6142338 to your computer and use it in GitHub Desktop.
Save mikewadhera/6142338 to your computer and use it in GitHub Desktop.
Enumerable#combinations - returns an array of arrays with all permutations of enumerable (order doesn't matter)
module Enumerable
def combinations
case self.size
when 0 then []
when 1 then self.to_a
else
(1..self.size).reduce([]) { |combined, choose| combined + self.combination(choose).to_a }
end
end
end
ree-1.8.7-2011.03 :001 > ["A", "B", "C"].combinations
=> [["A"], ["B"], ["C"], ["A", "B"], ["A", "C"], ["B", "C"], ["A", "B", "C"]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment