I altered some code I found on the web, but my version assigns the last lexicographic permutation in the set to all elements of the set. Can anyone tell me why that is? Here's my code:
$permutations = []
def perms(array)
$permutations.push array
#handle the case when the length of 'array' is one or less
if array.length <= 1
return $permuations
end
#find the first element less than the one following it
i = (array.length - 2)
until array[i] < array[i+1]
i = (i - 1)
end
#if the array is in descending order, we've finished
if i < 0
return $permutations
end
#identify the first element larger than 'i'
j = (array.length - 1)
until array[j] > array[i]
j = (j - 1)
end
#swap the 'ith' and 'jth' elements
array[i], array[j] = array[j], array[i]
#reverse the list from 'i + 1' to the end
i = (i + 1)
j = (array.length - 1)
until j < i
array[i], array[j] = array[j], array[i]
i += 1
j -= 1
end
#run the method again, with the newest permutation as the seed
perms(array)
end
#test the method
perms([0, 1, 2])
print $permutations
The output I'm getting is: [[2, 1, 0], [2, 1, 0], [2, 1, 0], [2, 1, 0], [2, 1, 0], [2, 1, 0]]
Thanks in advance for any help!