Skip to content

Instantly share code, notes, and snippets.

@Yorgg
Created March 10, 2018 02:31
Show Gist options
  • Save Yorgg/cf244d401b1e1b4f5796f15011706836 to your computer and use it in GitHub Desktop.
Save Yorgg/cf244d401b1e1b4f5796f15011706836 to your computer and use it in GitHub Desktop.
#Permutations Recursive
def _add_head(head, res)
out = []
res.each do |permutation|
0.upto(permutation.length) do |i|
_insert!(i, head, permutation, out)
end
end
out
end
def _insert!(i, head, permutation, out)
if i == 0
out << [head, *permutation[0..-1]]
elsif permutation[i] == nil
out << [*permutation[0..-1], head]
else
out << [*permutation[0...i], head, *permutation[i..-1]]
end
end
def permutations(res)
return [res] if res.length == 1
_add_head(res[0], permutations(res[1..-1]))
end
print permutations([1,2,3,4])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment