Permutations: Difference between revisions

Content added Content deleted
(Updated first D entry)
Line 898: Line 898:


=={{header|D}}==
=={{header|D}}==
===Eager version===
===Simple Eager version===
Compile with -version=permutations1_main to see the output.
<lang d>import std.stdio: writeln;
<lang d>T[][] permutations(T)(T[] items) pure nothrow {

T[][] permutations(T)(T[] items) {
T[][] result;
T[][] result;


void perms(T[] s, T[] prefix=[]) {
void perms(T[] s, T[] prefix=[]) nothrow {
if (s.length)
if (s.length)
foreach (i, c; s)
foreach (immutable i, immutable c; s)
perms(s[0 .. i] ~ s[i+1 .. $], prefix ~ c);
perms(s[0 .. i] ~ s[i+1 .. $], prefix ~ c);
else
else
Line 916: Line 915:
}
}


version (permutations1_main) {
void main() {
void main() {
foreach (p; permutations([1, 2, 3]))
writeln(p);
import std.stdio;
writefln("%(%s\n%)", [1, 2, 3].permutations);
}
}</lang>
}</lang>
{{out}}
{{out}}
Line 927: Line 928:
[3, 1, 2]
[3, 1, 2]
[3, 2, 1]</pre>
[3, 2, 1]</pre>

===Fast Lazy Version===
===Fast Lazy Version===
Compiled with <code>-version=permutations2_main</code> produces the same output:
Compiled with <code>-version=permutations2_main</code> produces the same output: