Last active
December 20, 2015 13:58
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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