Skip to content

Instantly share code, notes, and snippets.

@EmmanuelOga
Created September 12, 2014 09:24
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 EmmanuelOga/666c5aa06fbc376a7f3b to your computer and use it in GitHub Desktop.
Save EmmanuelOga/666c5aa06fbc376a7f3b to your computer and use it in GitHub Desktop.
Permutations, this time with ruby.
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