Skip to content

Instantly share code, notes, and snippets.

@bioball
Last active December 25, 2015 07:19
Show Gist options
  • Save bioball/6938296 to your computer and use it in GitHub Desktop.
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.
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