Permutations by swapping: Difference between revisions

m
syntax highlighting fixup automation
(Permutations by swapping in various BASIC dialents (BASIC256, QBasic, Run BASIC and Yabasic))
m (syntax highlighting fixup automation)
Line 28:
{{trans|Python: Iterative version of the recursive}}
 
<langsyntaxhighlight lang="11l">F s_permutations(seq)
V items = [[Int]()]
L(j) seq
Line 45:
L(perm, sgn) s_permutations(Array(0 .< n))
print(‘Perm: #. Sign: #2’.format(perm, sgn))
print()</langsyntaxhighlight>
 
{{out}}
Line 86:
=={{header|ALGOL 68}}==
Based on the pseudo-code for the recursive version of Heap's algorithm.
<langsyntaxhighlight lang="algol68">BEGIN # Heap's algorithm for generating permutations - from the pseudo-code on the Wikipedia page #
# generate permutations of a #
PROC generate = ( INT k, REF[]INT a, REF INT swap count )VOID:
Line 127:
permute( a )
 
END</langsyntaxhighlight>
{{out}}
<pre>
Line 140:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">permutations: function [arr][
d: 1
c: array.of: size arr 0
Line 178:
 
loop permutations 0..3 'row ->
print [row\0 "-> sign:" row\1]</langsyntaxhighlight>
 
{{out}}
Line 215:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">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
Line 224:
return list ; done if str is empty
return Permutations_By_Swapping(str, list) ; else recurse
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">for each, line in StrSplit(Permutations_By_Swapping(1234), "`n")
result .= line "`tSign: " (mod(A_Index,2)? 1 : -1) "`n"
MsgBox, 262144, , % result
return</langsyntaxhighlight>
Outputs:<pre>1234 Sign: 1
1243 Sign: -1
Line 257:
==={{header|BASIC256}}===
{{trans|Free BASIC}}
<langsyntaxhighlight BASIC256lang="basic256">call perms(3)
print
call perms(4)
Line 294:
end if
until k = 0
end subroutine</langsyntaxhighlight>
 
==={{header|QBasic}}===
Line 300:
{{works with|QuickBasic|4.5}}
{{trans|Free BASIC}}
<langsyntaxhighlight lang="qbasic">SUB perms (n)
DIM p((n + 1) * 4)
FOR i = 1 TO n
Line 338:
perms (3)
PRINT
perms (4)</langsyntaxhighlight>
 
==={{header|Run BASIC}}===
{{trans|Free BASIC}}
<langsyntaxhighlight lang="runbasic">sub perms n
dim p((n+1)*4)
for i = 1 to n : p(i) = i*-1 : next i
Line 377:
call perms 3
print
call perms 4</langsyntaxhighlight>
 
==={{header|Yabasic}}===
{{trans|Free BASIC}}
<langsyntaxhighlight lang="freebasic">perms(3)
print
perms(4)
Line 418:
endif
until k = 0
end sub</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> PROCperms(3)
PRINT
PROCperms(4)
Line 456:
ENDIF
UNTIL k% = 0
ENDPROC</langsyntaxhighlight>
{{out}}
<pre>
Line 494:
=={{header|C}}==
Implementation of Heap's Algorithm, array length has to be passed as a parameter for non character arrays, as sizeof() will not give correct results when malloc is used. Prints usage on incorrect invocation.
<syntaxhighlight lang="c">
<lang C>
#include<stdlib.h>
#include<string.h>
Line 562:
return 0;
}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 577:
=={{header|C++}}==
Direct implementation of Johnson-Trotter algorithm from the reference link.
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <vector>
Line 640:
} while (!state.IsComplete());
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 669:
=={{header|Clojure}}==
===Recursive version===
<langsyntaxhighlight lang="clojure">
(defn permutation-swaps
"List of swap indexes to generate all permutations of n elements"
Line 707:
(doseq [n [2 3 4]]
(dorun (map println (permutations n))))
</syntaxhighlight>
</lang>
 
{{out}}
Line 748:
===Modeled After Python version===
{{trans|Python}}
<langsyntaxhighlight lang="clojure">
(ns test-p.core)
 
Line 811:
(println (format "Permutations and sign of %d items " n))
(doseq [q (spermutations n)] (println (format "Perm: %s Sign: %2d" (first q) (second q))))))
</syntaxhighlight>
</lang>
 
{{out}}
Line 856:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defstruct (directed-number (:conc-name dn-))
(number nil :type integer)
(direction nil :type (member :left :right)))
Line 914:
 
(permutations 3)
(permutations 4)</langsyntaxhighlight>
{{out}}
<pre>#(<1 <2 <3) sign: +1
Line 951:
This isn't a Range yet.
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.algorithm, std.array, std.typecons, std.range;
 
struct Spermutations(bool doCopy=true) {
Line 1,034:
}
}
}</langsyntaxhighlight>
Compile with version=permutations_by_swapping1 to see the demo output.
{{out}}
Line 1,074:
===Recursive Version===
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.algorithm, std.array, std.typecons, std.range;
 
auto sPermutations(in uint n) pure nothrow @safe {
Line 1,106:
writeln;
}
}</langsyntaxhighlight>
{{out}}
<pre>Permutations and sign of 2 items:
Line 1,149:
=={{header|EchoLisp}}==
The function '''(in-permutations n)''' returns a stream which delivers permutations according to the Steinhaus–Johnson–Trotter algorithm.
<langsyntaxhighlight lang="lisp">
(lib 'list)
 
Line 1,179:
perm: (1 0 3 2) count: 22 sign: 1
perm: (1 0 2 3) count: 23 sign: -1
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule Permutation do
def by_swap(n) do
p = Enum.to_list(0..-n) |> List.to_tuple
Line 1,222:
Permutation.by_swap(n)
IO.puts ""
end)</langsyntaxhighlight>
 
{{out}}
Line 1,261:
=={{header|F_Sharp|F#}}==
See [http://www.rosettacode.org/wiki/Zebra_puzzle#F.23] for an example using this module
<langsyntaxhighlight lang="fsharp">
(*Implement Johnson-Trotter algorithm
Nigel Galloway January 24th 2017*)
Line 1,280:
yield! _Ni gel 0 1
}
</syntaxhighlight>
</lang>
A little code for the purpose of this task demonstrating the algorithm
<langsyntaxhighlight lang="fsharp">
for n in Ring.PlainChanges [|1;2;3;4|] do printfn "%A" n
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,317:
{{works with|gforth|0.7.9_20170308}}
{{trans|BBC BASIC}}
<langsyntaxhighlight lang="forth">S" fsl-util.fs" REQUIRED
S" fsl/dynmem.seq" REQUIRED
 
Line 1,383:
 
3 ' .perm perms CR
4 ' .perm perms</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
{{trans|BBC BASIC}}
<langsyntaxhighlight lang="freebasic">' version 31-03-2017
' compile with: fbc -s console
 
Line 1,446:
Sleep
End
</syntaxhighlight>
</lang>
{{out}}
<pre>output is edited to show results side by side
Line 1,481:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package permute
 
// Iter takes a slice p and returns an iterator function. The iterator
Line 1,530:
}
}
}</langsyntaxhighlight>
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,544:
fmt.Println(p, sign)
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,556:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">sPermutations :: [a] -> [([a], Int)]
sPermutations = flip zip (cycle [-1, 1]) . foldr aux [[]]
where
Line 1,570:
mapM_ print $ sPermutations [1 .. 3]
putStrLn "\n4 items:"
mapM_ print $ sPermutations [1 .. 4]</langsyntaxhighlight>
{{Out}}
<pre>3 items:
Line 1,611:
{{trans|Python}}
 
<langsyntaxhighlight 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))
Line 1,640:
every (s := "[") ||:= image(!A)||", "
return s[1:-2]||"]"
end</langsyntaxhighlight>
 
Sample run:
Line 1,685:
Meanwhile, here's an inductive approach, using negative integers to look left and positive integers to look right:
 
<langsyntaxhighlight Jlang="j">bfsjt0=: _1 - i.
lookingat=: 0 >. <:@# <. i.@# + *
next=: | >./@:* | > | {~ lookingat
bfsjtn=: (((] <@, ] + *@{~) | i. next) C. ] * _1 ^ next < |)^:(*@next)</langsyntaxhighlight>
 
Here, bfsjt0 N gives the initial permutation of order N, and bfsjtn^:M bfsjt0 N gives the Mth Steinhaus–Johnson–Trotter permutation of order N. (bf stands for "brute force".)
Line 1,696:
Example use:
 
<langsyntaxhighlight Jlang="j"> bfsjtn^:(i.!3) bfjt0 3
_1 _2 _3
_1 _3 _2
Line 1,711:
1 0 2
A. <:@| bfsjtn^:(i.!3) bfjt0 3
0 1 4 5 3 2</langsyntaxhighlight>
 
Here's an example of the Steinhaus–Johnson–Trotter representation of 3 element permutation, with sign (sign is the first column):
 
<langsyntaxhighlight Jlang="j"> (_1^2|i.!3),. bfsjtn^:(i.!3) bfjt0 3
1 _1 _2 _3
_1 _1 _3 _2
Line 1,721:
_1 3 _2 _1
1 _2 3 _1
_1 _2 _1 3</langsyntaxhighlight>
 
Alternatively, J defines [http://www.jsoftware.com/help/dictionary/dccapdot.htm C.!.2] as the parity of a permutation:
 
<langsyntaxhighlight Jlang="j"> (,.~C.!.2)<:| bfsjtn^:(i.!3) bfjt0 3
1 0 1 2
_1 0 2 1
Line 1,731:
_1 2 1 0
1 1 2 0
_1 1 0 2</langsyntaxhighlight>
 
===Recursive Implementation===
Line 1,737:
This is based on the python recursive implementation:
 
<langsyntaxhighlight Jlang="j">rsjt=: 3 :0
if. 2>y do. i.2#y
else. ((!y)$(,~|.)-.=i.y)#inv!.(y-1)"1 y#rsjt y-1
end.
)</langsyntaxhighlight>
 
Example use (here, prefixing each row with its parity):
 
<langsyntaxhighlight Jlang="j"> (,.~ C.!.2) rsjt 3
1 0 1 2
_1 0 2 1
Line 1,751:
_1 2 1 0
1 1 2 0
_1 1 0 2</langsyntaxhighlight>
 
=={{header|Java}}==
Line 1,757:
Heap's Algorithm, recursive and looping implementations
 
<langsyntaxhighlight Javalang="java">package org.rosettacode.java;
 
import java.util.Arrays;
Line 1,824:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,885:
input array. This array may contain any JSON entities, which are regarded as distinct.
 
<langsyntaxhighlight lang="jq"># The helper function, _recurse, is tail-recursive and therefore in
# versions of jq with TCO (tail call optimization) there is no
# overhead associated with the recursion.
Line 1,929:
| .[1] = reduce range(0; $n) as $i ([]; . + [$in[$p[$i] - 1]]) ;
 
def count(stream): reduce stream as $x (0; .+1);</langsyntaxhighlight>
'''Examples:'''
<langsyntaxhighlight lang="jq">(["a", "b", "c"] | permutations),
"There are \(count( [range(1;6)] | permutations )) permutations of 5 items."</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -c -n -f Permutations_by_swapping.jq
[1,["a","b","c"]]
[-1,["a","c","b"]]
Line 1,942:
[-1,["b","a","c"]]
 
"There are 32 permutations of 5 items."</langsyntaxhighlight>
 
=={{header|Julia}}==
Nonrecursive (interative):
<langsyntaxhighlight lang="julia">
function johnsontrottermove!(ints, isleft)
len = length(ints)
Line 2,005:
end
johnsontrotter(1,4)
</syntaxhighlight>
</lang>
Recursive (note this uses memory of roughtly (n+1)! bytes, where n is the number of elements, in order to store the accumulated permutations in a list, and so the above, iterative solution is to be preferred for numbers of elements over 9 or so):
<langsyntaxhighlight lang="julia">
function johnsontrotter(low, high)
function permutelevel(vec)
Line 2,031:
println("""$sequence, $(i & 1 == 1 ? "+1" : "-1")""")
end
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
This is based on the recursive Java code found at http://introcs.cs.princeton.edu/java/23recursion/JohnsonTrotter.java.html
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun johnsonTrotter(n: Int): Pair<List<IntArray>, List<Int>> {
Line 2,080:
val (perms2, signs2) = johnsonTrotter(4)
printPermsAndSigns(perms2, signs2)
}</langsyntaxhighlight>
 
{{out}}
Line 2,119:
=={{header|Lua}}==
{{trans|C++}}
<langsyntaxhighlight Lualang="lua">_JT={}
function JT(dim)
local n={ values={}, positions={}, directions={}, sign=1 }
Line 2,159:
repeat
print(unpack(perm.values))
until not perm:next()</langsyntaxhighlight>
{{out}}
<pre>1 2 3 4
Line 2,187:
===Coroutine Implementation===
This is adapted from the [https://www.lua.org/pil/9.3.html Lua Book ].
<langsyntaxhighlight lang="lua">local wrap, yield = coroutine.wrap, coroutine.yield
local function perm(n)
local r = {}
Line 2,207:
end)
end
for sign,r in perm(3) do print(sign,table.unpack(r))end</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
=== Recursive ===
<syntaxhighlight lang="text">perms[0] = {{{}, 1}};
perms[n_] :=
Flatten[If[#2 == 1, Reverse, # &]@
Table[{Insert[#1, n, i], (-1)^(n + i) #2}, {i, n}] & @@@
perms[n - 1], 1];</langsyntaxhighlight>
Example:
<syntaxhighlight lang="text">Print["Perm: ", #[[1]], " Sign: ", #[[2]]] & /@ perms@4;</langsyntaxhighlight>
{{out}}
<pre>Perm: {1,2,3,4} Sign: 1
Line 2,245:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim"># iterative Boothroyd method
iterator permutations*[T](ys: openarray[T]): tuple[perm: seq[T], sign: int] =
var
Line 2,278:
 
for i in permutations([0,1,2,3]):
echo i</langsyntaxhighlight>
{{out}}
<pre>(perm: @[0, 1, 2], sign: 1)
Line 2,314:
=={{header|ooRexx}}==
===Recursive===
<langsyntaxhighlight lang="oorexx">/* REXX Compute permutations of things elements */
/* implementing Heap's algorithm nicely shown in */
/* https://en.wikipedia.org/wiki/Heap%27s_algorithm */
Line 2,383:
Say 'rexx permx 2 -> Permutations of 1 2 '
Say 'rexx permx a b c d -> Permutations of a b c d in 2 positions'
Exit</langsyntaxhighlight>
{{out}}
<pre>H:\>rexx permx ?
Line 2,404:
0 seconds</pre>
===Iterative===
<langsyntaxhighlight lang="oorexx">/* REXX Compute permutations of things elements */
/* implementing Heap's algorithm nicely shown in */
/* https://en.wikipedia.org/wiki/Heap%27s_algorithm */
Line 2,479:
Say 'rexx permxi 2 -> Permutations of 1 2 '
Say 'rexx permxi a b c d -> Permutations of a b c d in 2 positions'
Exit</langsyntaxhighlight>
 
=={{header|Perl}}==
 
===S-J-T Based===
<langsyntaxhighlight lang="perl">
#!perl
use strict;
Line 2,544:
print $sign < 0 ? " => -1\n" : " => +1\n";
} 1 .. $n;
</syntaxhighlight>
</lang>
{{out}}<pre>
[1, 2, 3, 4] => +1
Line 2,575:
This is based on the Raku recursive version, but without recursion.
 
<langsyntaxhighlight lang="perl">#!perl
use strict;
use warnings;
Line 2,600:
print "[", join(", ", @$_), "] => $s\n";
}
</syntaxhighlight>
</lang>
{{out}}
The output is the same as the first perl solution.
Line 2,608:
Only once finished did I properly grasp that odd/even permutation idea, and that it is very nearly the same algorithm.<br>
Only difference is my version directly calculates where to insert p, without using the parity (which I added in last).
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">spermutations</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">--
Line 2,634:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,677:
 
=={{header|PicoLisp}}==
<syntaxhighlight lang="picolisp">(let
<lang PicoLisp>(let
(N 4
L
Line 2,718:
(printsp (car I)) )
(prinl) ) )
(bye)</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function output([Object[]]$A, [Int]$k, [ref]$sign)
{
Line 2,759:
""
permutation @(0, 1, 2, 3)
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>Perm: [1, 0, 2] Sign: -1
Line 2,796:
When saved in a file called spermutations.py it is used in the Python example to the [[Matrix arithmetic#Python|Matrix arithmetic]] task and so any changes here should also be reflected and checked in that task example too.
 
<langsyntaxhighlight lang="python">from operator import itemgetter
DEBUG = False # like the built-in __debug__
Line 2,855:
# Test
p = set(permutations(range(n)))
assert sp == p, 'Two methods of generating permutations do not agree'</langsyntaxhighlight>
{{out}}
<pre>Permutations and sign of 3 items
Line 2,893:
===Python: recursive===
After spotting the pattern of highest number being inserted into each perm of lower numbers from right to left, then left to right, I developed this recursive function:
<langsyntaxhighlight lang="python">def s_permutations(seq):
def s_perm(seq):
if not seq:
Line 2,911:
 
return [(tuple(item), -1 if i % 2 else 1)
for i, item in enumerate(s_perm(seq))]</langsyntaxhighlight>
 
{{out|Sample output}}
Line 2,918:
===Python: Iterative version of the recursive===
Replacing the recursion in the example above produces this iterative version function:
<langsyntaxhighlight lang="python">def s_permutations(seq):
items = [[]]
for j in seq:
Line 2,934:
 
return [(tuple(item), -1 if i % 2 else 1)
for i, item in enumerate(items)]</langsyntaxhighlight>
 
{{out|Sample output}}
Line 2,940:
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 2,961:
 
(for ([n (in-range 3 5)]) (show-permutations (range n)))
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,004:
=== Recursive ===
{{works with|rakudo|2015-09-25}}
<syntaxhighlight lang="raku" perl6line>sub insert($x, @xs) { ([flat @xs[0 ..^ $_], $x, @xs[$_ .. *]] for 0 .. +@xs) }
sub order($sg, @xs) { $sg > 0 ?? @xs !! @xs.reverse }
Line 3,015:
}
.say for perms([0..2]);</langsyntaxhighlight>
 
{{out}}
Line 3,030:
and I can't get it working for 5 things. -:( --Walter Pachl 13:40, 25 January 2022 (UTC)
 
<langsyntaxhighlight lang="rexx">/*REXX program generates all permutations of N different objects by swapping. */
parse arg things bunch . /*obtain optional arguments from the CL*/
if things=='' | things=="," then things=4 /*Not specified? Then use the default.*/
Line 3,075:
end /*k*/
end /*$*/
return /*we're all finished with permutating. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 3,113:
=={{header|Ruby}}==
{{trans|BBC BASIC}}
<langsyntaxhighlight lang="ruby">def perms(n)
p = Array.new(n+1){|i| -i}
s = 1
Line 3,138:
perms(i){|perm, sign| puts "Perm: #{perm} Sign: #{sign}"}
puts
end</langsyntaxhighlight>
{{out}}
<pre>
Line 3,175:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">// Implementation of Heap's algorithm.
// See https://en.wikipedia.org/wiki/Heap%27s_algorithm#Details_of_the_algorithm
fn generate<T, F>(a: &mut [T], output: F)
Line 3,216:
let mut b = vec![0, 1, 2, 3];
generate(&mut b, print_permutation);
}</langsyntaxhighlight>
 
{{out}}
Line 3,255:
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">object JohnsonTrotter extends App {
 
private def perm(n: Int): Unit = {
Line 3,290:
perm(4)
 
}</langsyntaxhighlight>
{{Out}}See it in running in your browser by [https://scastie.scala-lang.org/DdM4xnUnQ2aNGP481zwcrw Scastie (JVM)].
 
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func perms(n) {
var perms = [[+1]]
for x in (1..n) {
Line 3,316:
s > 0 && (s = '+1')
say "#{p} => #{s}"
}</langsyntaxhighlight>
 
{{out}}
Line 3,347:
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">// Implementation of Heap's algorithm.
// See https://en.wikipedia.org/wiki/Heap%27s_algorithm#Details_of_the_algorithm
func generate<T>(array: inout [T], output: (_: [T], _: Int) -> Void) {
Line 3,383:
print("\nPermutations and signs for four items:")
var b = [0, 1, 2, 3]
generate(array: &b, output: printPermutation)</langsyntaxhighlight>
 
{{out}}
Line 3,423:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl"># A simple swap operation
proc swap {listvar i1 i2} {
upvar 1 $listvar l
Line 3,472:
}
}
}</langsyntaxhighlight>
Demonstrating:
<langsyntaxhighlight lang="tcl">permswap 4 p s {
puts "$s\t$p"
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,507:
=={{header|Wren}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="ecmascript">var johnsonTrotter = Fn.new { |n|
var p = List.filled(n, 0) // permutation
var q = List.filled(n, 0) // inverse permutation
Line 3,555:
perms = res[0]
signs = res[1]
printPermsAndSigns.call(perms, signs)</langsyntaxhighlight>
 
{{out}}
Line 3,594:
=={{header|XPL0}}==
Translation of BBC BASIC example, which uses the Johnson-Trotter algorithm.
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
 
proc PERMS(N);
Line 3,629:
CrLf(0);
PERMS(4);
]</langsyntaxhighlight>
 
{{out}}
Line 3,669:
{{trans|Python}}
{{trans|Haskell}}
<langsyntaxhighlight lang="zkl">fcn permute(seq)
{
insertEverywhere := fcn(x,list){ //(x,(a,b))-->((x,a,b),(a,x,b),(a,b,x))
Line 3,681:
T.fp(Void.Write,Void.Write));
},T(T));
}</langsyntaxhighlight>
A cycle of two "build list" functions is used to insert x forward or reverse. reduce loops over the items and retains the enlarging list of permuations. pump loops over the existing set of permutations and inserts/builds the next set (into a list sink). (Void.Write,Void.Write,list) is a sentinel that says to write the contents of the list to the sink (ie sink.extend(list)). T.fp is a partial application of ROList.create (read only list) and the parameters VW,VW. It will be called (by pump) with a list of lists --> T.create(VM,VM,list) --> list
<langsyntaxhighlight lang="zkl">p := permute(T(1,2,3));
p.println();
 
p := permute([1..4]);
p.len().println();
p.toString(*).println()</langsyntaxhighlight>
{{out}}
<pre>
Line 3,701:
</pre>
An iterative, lazy version, which is handy as the number of permutations is n!. Uses "Even's Speedup" as described in the Wikipedia article:
<langsyntaxhighlight lang="zkl"> fcn [private] _permuteW(seq){ // lazy version
N:=seq.len(); NM1:=N-1;
ds:=(0).pump(N,List,T(Void,-1)).copy(); ds[0]=0; // direction to move e: -1,0,1
Line 3,721:
}
 
fcn permuteW(seq) { Utils.Generator(_permuteW,seq) }</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">foreach p in (permuteW(T("a","b","c"))){ println(p) }</langsyntaxhighlight>
{{out}}
<pre>
10,333

edits