Permutations: Difference between revisions

Content added Content deleted
(+ tag in Faster Lazy Version)
(Fixed lazy D version)
Line 852:
[3, 2, 1]</pre>
===Faster Lazy Version===
{{incorrect|D|This version is designed to sort indexes only.}}
Compiled with <code>-version=permutations2_main</code> produces the same output:
<lang d>import std.algorithm, std.exceptionconv, std.traits;
 
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 {
enforcestatic immutable string L = text(itemsindexes.length); >// 0,impure
assert(items.length >= 0 "Permutations:&& items.length must<= be > 0");indexes.length,
"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 (itemsindexes[j] > itemsindexes[j + 1])
j--;
size_t k = num - 1;
while (itemsindexes[j] > itemsindexes[k])
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 {