Last active
August 29, 2015 14:09
-
-
Save sagivo/b7d772d9b3b531f9996f to your computer and use it in GitHub Desktop.
permutation in 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
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