Skip to content

Instantly share code, notes, and snippets.

@sagivo
Last active August 29, 2015 14:09
Show Gist options
  • Save sagivo/b7d772d9b3b531f9996f to your computer and use it in GitHub Desktop.
Save sagivo/b7d772d9b3b531f9996f to your computer and use it in GitHub Desktop.
permutation in ruby
def perm arr, i=0
return p arr if i == arr.size
(i..arr.size-1).each do |j|
arr[i], arr[j] = arr[j], arr[i]
perm arr, i+1
arr[i], arr[j] = arr[j], arr[i]
end
end
perm 'ABC'
-------------
"ABC"
"ACB"
"BAC"
"BCA"
"CBA"
"CAB"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment