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


procedure main(A)
    every write("Permutations of length ",n := !A) do
       every p := permute(n) do write("\t",showList(p[1])," -> ",right(p[2],2))
end
 
procedure permute(n)
    items := [[]]
    every (j := 1 to n, new_items := []) do {
        every item := items[i := 1 to *items] do {
            if *item = 0 then put(new_items, [j])
            else if i%2 = 0 then
                every k := 1 to *item+1 do {
                    new_item := item[1:k] ||| [j] ||| item[k:0]
                    put(new_items, new_item)
                    }
            else
                every k := *item+1 to 1 by -1 do {
                    new_item := item[1:k] ||| [j] ||| item[k:0]
                    put(new_items, new_item)
                    }
            }
       items := new_items
       }
    suspend (i := 0, [!items, if (i+:=1)%2 = 0 then 1 else -1])
end
 
procedure showList(A)
    every (s := "[") ||:= image(!A)||", "
    return s[1:-2]||"]"
end