How to resolve the algorithm Permutations by swapping step by step in the AutoHotkey programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Permutations by swapping step by step in the AutoHotkey programming language

Table of Contents

Problem Statement

Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Show the permutations and signs of three items, in order of generation here. Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind. Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Permutations by swapping step by step in the AutoHotkey programming language

Source code in the autohotkey programming language

Permutations_By_Swapping(str, list:=""){
	ch := SubStr(str, 1, 1)								; get left-most charachter of str
	for i, line in StrSplit(list, "`n")					; for each line in list
		loop % StrLen(line) + 1							; loop each possible position
			Newlist .= RegExReplace(line, mod(i,2) ? "(?=.{" A_Index-1 "}$)" : "^.{" A_Index-1 "}\K", ch) "`n"
	list := Newlist ? Trim(Newlist, "`n") : ch			; recreate list
	if !str := SubStr(str, 2)							; remove charachter from left hand side
		return list										; done if str is empty
	return Permutations_By_Swapping(str, list)			; else recurse
}


for each, line in StrSplit(Permutations_By_Swapping(1234), "`n")
	result .= line "`tSign: " (mod(A_Index,2)? 1 : -1) "`n"
MsgBox, 262144, , % result
return


  

You may also check:How to resolve the algorithm Perfect numbers step by step in the PicoLisp programming language
You may also check:How to resolve the algorithm Unicode strings step by step in the Locomotive Basic programming language
You may also check:How to resolve the algorithm Pick random element step by step in the PARI/GP programming language
You may also check:How to resolve the algorithm Hello world/Newline omission step by step in the EchoLisp programming language
You may also check:How to resolve the algorithm Averages/Mode step by step in the UNIX Shell programming language