Jump to content

Permutations by swapping: Difference between revisions

Updated both D entries
No edit summary
(Updated both D entries)
Line 238:
=={{header|D}}==
===Iterative Version===
This isn't a Range yet.
{{trans|Python}}
<lang d>import std.algorithm, std.array, std.typecons, std.range;
Line 246:
alias TResult = Tuple!(int[], int);
 
int opApply(in int delegate(in ref TResult) nothrow dg) nothrow {
int result;
 
Line 260:
goto END;
 
while (p.canFindany!q{ a[1] }) {
// Failed to use std.algorithm here, too much complex.
auto largest = Int2(-100, -100);
int i1 = -1;
foreach (immutable i, immutable pi; p) {
if (pi[1]) {
if (pi[0] > largest[0]) {
i1 = i;
largest = pi;
}
}
}
immutable n1 = largest[0],
d1 = largest[1];
Line 364 ⟶ 362:
 
===Recursive Version===
Same output.
{{trans|Python}}
<lang d>import std.algorithm, std.array, std.typecons, std.range;
 
auto sPermutations(in intuint n) /*pure nothrow*/ @safe {
static immutable(int[])[] sPermuinner(in int items) /*pure nothrow*/ @safe {
if (items <= 0)
return [[]];
typeof(return) r;
foreach (immutable i, immutable item; sPermuinner(items - 1)) {
//r.put((i % 2 ? iota(cast(int)item.length, -1, -1) :
// iota(item.length + 1))
// .map!(i => item[0 .. i] ~ (items - 1) ~ item[i .. $]));
immutable f = (in intsize_t i)=>item[0..i] ~pure (items-1)nothrow ~@safe item[i..$];=>
item[0 .. i] ~ (items - 1) ~ item[i .. $];
r ~= (i % 2) ?
//iota(cast(int)item.length, -1, -1).map!f.array :
iota(item.length + 1).retro.map!f.array :
iota(item.length + 1).map!f.array;
}
Line 385 ⟶ 384:
}
 
return sPermuinner(n).zip([1, -1].cycle);
}
 
void main() {
import std.stdio;
foreach (immutable n; [2, 3, 4]) {
writefln("\nPermutationsPermutations and sign of %d items:", n);
foreach (constimmutable tp; n.sPermutations)
writefln("Perm: %s Sign: %2d", tp[]);
}writeln;
}
}</lang>
{{out}}
<pre>Permutations and sign of 2 items:
[1, 0] Sign: 1
[0, 1] Sign: -1
 
Permutations and sign of 3 items:
[2, 1, 0] Sign: 1
[1, 2, 0] Sign: -1
[1, 0, 2] Sign: 1
[0, 1, 2] Sign: -1
[0, 2, 1] Sign: 1
[2, 0, 1] Sign: -1
 
Permutations and sign of 4 items:
[3, 2, 1, 0] Sign: 1
[2, 3, 1, 0] Sign: -1
[2, 1, 3, 0] Sign: 1
[2, 1, 0, 3] Sign: -1
[1, 2, 0, 3] Sign: 1
[1, 2, 3, 0] Sign: -1
[1, 3, 2, 0] Sign: 1
[3, 1, 2, 0] Sign: -1
[3, 1, 0, 2] Sign: 1
[1, 3, 0, 2] Sign: -1
[1, 0, 3, 2] Sign: 1
[1, 0, 2, 3] Sign: -1
[0, 1, 2, 3] Sign: 1
[0, 1, 3, 2] Sign: -1
[0, 3, 1, 2] Sign: 1
[3, 0, 1, 2] Sign: -1
[3, 0, 2, 1] Sign: 1
[0, 3, 2, 1] Sign: -1
[0, 2, 3, 1] Sign: 1
[0, 2, 1, 3] Sign: -1
[2, 0, 1, 3] Sign: 1
[2, 0, 3, 1] Sign: -1
[2, 3, 0, 1] Sign: 1
[3, 2, 0, 1] Sign: -1
</pre>
 
=={{header|Go}}==
Cookies help us deliver our services. By using our services, you agree to our use of cookies.