Task

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.



References

 Steinhaus–Johnson–Trotter algorithm
 Johnson-Trotter Algorithm Listing All Permutations
 Heap's algorithm
 [1] Tintinnalogia


Related tasks

   Matrix arithmetic
   Gray code


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
}