Permutations by swapping: Difference between revisions
Content deleted Content added
No edit summary |
|||
Line 522: | Line 522: | ||
([1,0,3,2],1) |
([1,0,3,2],1) |
||
([1,0,2,3],-1) |
([1,0,2,3],-1) |
||
</pre> |
|||
=={{header|Icon}} and {{header|Unicon}}== |
|||
Works in both languages. |
|||
{{trans|Python}} |
|||
<lang unicon>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</lang> |
|||
Sample run: |
|||
<pre> |
|||
->pbs 3 4 |
|||
Permutations of length 3 |
|||
[1, 2, 3] -> -1 |
|||
[1, 3, 2] -> 1 |
|||
[3, 1, 2] -> -1 |
|||
[3, 2, 1] -> 1 |
|||
[2, 3, 1] -> -1 |
|||
[2, 1, 3] -> 1 |
|||
Permutations of length 4 |
|||
[1, 2, 3, 4] -> -1 |
|||
[1, 2, 4, 3] -> 1 |
|||
[1, 4, 2, 3] -> -1 |
|||
[4, 1, 2, 3] -> 1 |
|||
[4, 1, 3, 2] -> -1 |
|||
[1, 4, 3, 2] -> 1 |
|||
[1, 3, 4, 2] -> -1 |
|||
[1, 3, 2, 4] -> 1 |
|||
[3, 1, 2, 4] -> -1 |
|||
[3, 1, 4, 2] -> 1 |
|||
[3, 4, 1, 2] -> -1 |
|||
[4, 3, 1, 2] -> 1 |
|||
[4, 3, 2, 1] -> -1 |
|||
[3, 4, 2, 1] -> 1 |
|||
[3, 2, 4, 1] -> -1 |
|||
[3, 2, 1, 4] -> 1 |
|||
[2, 3, 1, 4] -> -1 |
|||
[2, 3, 4, 1] -> 1 |
|||
[2, 4, 3, 1] -> -1 |
|||
[4, 2, 3, 1] -> 1 |
|||
[4, 2, 1, 3] -> -1 |
|||
[2, 4, 1, 3] -> 1 |
|||
[2, 1, 4, 3] -> -1 |
|||
[2, 1, 3, 4] -> 1 |
|||
-> |
|||
</pre> |
</pre> |
||