-
-
Save Seelengrab/2b9a963c25da7b56a4bb2548e8ec03eb to your computer and use it in GitHub Desktop.
Julia version of C++ next_perm -- GPL Licensed since it's a direct translation :/
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
function next_perm!(itr) | |
isempty(itr) && return false | |
length(itr) == 1 && return false | |
i = lastindex(itr) | |
while true | |
old_i = i | |
i -= 1 | |
if itr[i] < itr[old_i] # find an element that's less than our last checked element | |
j = lastindex(itr) | |
while itr[i] >= itr[j]; j -= 1 end # find the last element smaller than our current one | |
itr[i], itr[j] = itr[j], itr[i] # swap them | |
reverse!(itr, old_i, lastindex(itr)) # reverse all elements from our last element to the end for the next permutation | |
return true | |
end | |
if i == firstindex(itr) | |
reverse!(itr) | |
return false | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment