Find the next highest permutation of a number using the method described here: https://en.wikipedia.org/wiki/Permutati ... phic_order
Function and example:
Code: Select all
SetBatchLines, -1
n := 123456
while (n := NextLex(n))
MsgBox, % "The next permutation of n is " n "."
MsgBox, % "No more permutations."
return
NextLex(n)
{
a := []
Loop, Parse, n
a[A_Index] := A_LoopField
;Find the largest index k such that a[k] < a[k + 1].
;If no such index exists, the permutation is the last permutation.
Loop % a.MaxIndex() - 1
{
if (a[A_Index] < a[A_Index + 1])
k := A_Index
}
if (!k)
return, 0
;Find the largest index l such that a[k] < a[l].
Loop % a.MaxIndex() - k
{
if (a[k] < a[A_Index + k])
l := A_Index + k
}
;Swap the value of a[k] with that of a[l].
Temp := a[k]
a[k] := a[l]
a[l] := Temp
;Reverse the sequence from a[k + 1] up to and including the final element a[n].
Loop, % a.MaxIndex() - k
Temp%A_Index% := a[A_Index + k]
Loop, % a.MaxIndex() - k
a[a.MaxIndex() - A_Index + 1] := Temp%A_Index%
for key, val in a
r .= val
return, r
}