RosettaCodeData/Task/Permutations-by-swapping/D/permutations-by-swapping-2.d

34 lines
1.1 KiB
D
Raw Permalink Normal View History

2013-04-10 23:57:08 -07:00
import std.algorithm, std.array, std.typecons, std.range;
2015-02-20 00:35:01 -05:00
auto sPermutations(in uint n) pure nothrow @safe {
static immutable(int[])[] inner(in int items) pure nothrow @safe {
2013-04-10 23:57:08 -07:00
if (items <= 0)
return [[]];
typeof(return) r;
2015-02-20 00:35:01 -05:00
foreach (immutable i, immutable item; inner(items - 1)) {
//r.put((i % 2 ? iota(item.length.signed, -1, -1) :
2013-10-27 22:24:23 +00:00
// iota(item.length + 1))
2015-02-20 00:35:01 -05:00
// .map!(i => item[0 .. i] ~ (items - 1) ~ item[i .. $]));
immutable f = (in size_t i) pure nothrow @safe =>
item[0 .. i] ~ (items - 1) ~ item[i .. $];
2013-10-27 22:24:23 +00:00
r ~= (i % 2) ?
2015-02-20 00:35:01 -05:00
//iota(item.length.signed, -1, -1).map!f.array :
iota(item.length + 1).retro.map!f.array :
2013-10-27 22:24:23 +00:00
iota(item.length + 1).map!f.array;
2013-04-10 23:57:08 -07:00
}
return r;
}
2015-02-20 00:35:01 -05:00
return inner(n).zip([1, -1].cycle);
2013-04-10 23:57:08 -07:00
}
void main() {
import std.stdio;
2015-02-20 00:35:01 -05:00
foreach (immutable n; [2, 3, 4]) {
writefln("Permutations and sign of %d items:", n);
foreach (immutable tp; n.sPermutations)
writefln(" %s Sign: %2d", tp[]);
writeln;
2013-04-10 23:57:08 -07:00
}
}