Skip to content

Instantly share code, notes, and snippets.

@heroqu
Created February 27, 2016 19:27
Show Gist options
  • Save heroqu/21593615ccfc821cd2c9 to your computer and use it in GitHub Desktop.
Save heroqu/21593615ccfc821cd2c9 to your computer and use it in GitHub Desktop.
Print out all unique permutations of first N natural numbers
def permutations(n)
_p n-1, (1..n).to_a, ''
end
def _p(n, arr, res)
if n == -1
puts res
return
end
(0..n).each do |m|
res2 = '' + res
arr2 = arr.clone
val = arr2.slice!(m)
res2 += ".#{val}"
_p(n - 1, arr2, res2)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment