Permutations: Difference between revisions
Content deleted Content added
+ tag in Faster Lazy Version |
Fixed lazy D version |
||
Line 852:
[3, 2, 1]</pre>
===Faster Lazy Version===
Compiled with <code>-version=permutations2_main</code> produces the same output:
<lang d>import std.algorithm, std.
struct Permutations(bool doCopy=true, T) if (isMutable!T) {
private immutable size_t num;
private T[] items;
private uint[31] indexes;
private ulong tot;
this (/*in*/ T[] items) /*pure*/ nothrow
in {
assert(items.length >= 0
"Permutations: items.length must be >= 0 && < " ~ L);
} body {
static ulong factorial(in uint n) pure nothrow {
Line 875 ⟶ 876:
this.num = items.length;
this.items = items.dup;
foreach (i; 0 .. cast(typeof(indexes[0]))this.num)
this.indexes[i] = i;
this.tot = factorial(this.num);
}
Line 893 ⟶ 896:
if (tot > 0) {
size_t j = num - 2;
while (
j--;
size_t k = num - 1;
while (
k--;
swap(indexes[k], indexes[j]);
swap(items[k], items[j]);
Line 903 ⟶ 908:
size_t s = j + 1;
while (r > s) {
swap(indexes[s], indexes[r]);
swap(items[s], items[r]);
r--;
Line 913 ⟶ 919:
Permutations!(doCopy,T) permutations(bool doCopy=true, T)
(/*in*/ T[] items)
/*pure*/ nothrow if (isMutable!T) {
return Permutations!(doCopy, T)(items);
} unittest {
|