Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Seelengrab
Created June 24, 2021 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Seelengrab/2b9a963c25da7b56a4bb2548e8ec03eb to your computer and use it in GitHub Desktop.
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 :/
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