Created
September 12, 2014 09:24
-
-
Save EmmanuelOga/666c5aa06fbc376a7f3b to your computer and use it in GitHub Desktop.
Permutations, this time with ruby.
This file contains 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
class Array | |
def interleave(n) | |
(0...length).map do |i| | |
(0...length).map do |j| | |
i == j ? [n, self[j]] : self[j] | |
end.flatten | |
end.concat([self + [n]]) | |
end | |
def combine(n) | |
dup.reduce([]) { |a, e| a + e.interleave(n) } | |
end | |
def rest | |
self[1..-1] | |
end | |
def permutations | |
empty? ? [[]] : rest.permutations.combine(first) | |
end | |
end | |
puts [1,2,3].permutations.inspect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment