Last active
December 25, 2015 07:19
-
-
Save bioball/6938296 to your computer and use it in GitHub Desktop.
This is a function I wrote that takes an array, and returns all possible permutations of arrays of that same size.
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 permute(arr) | |
permutation(arr.sort) | |
end | |
def permutation(arr, result=[]) | |
k = nil | |
result += [arr.dup] | |
(arr.length-1).times do |i| | |
if arr[i] < arr[i+1] | |
k = i | |
end | |
end | |
if k.nil? | |
return result | |
else | |
l = nil | |
arr.length.times do |i| | |
if arr[k] < arr[i] | |
l = i | |
end | |
end | |
arr[k], arr[l] = arr[l], arr[k] | |
arr = arr[0..k] + arr[k+1..-1].reverse | |
return permutation(arr, result) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment