Permutations: Difference between revisions

+ second D entry (lazy)
(+ second D entry (lazy))
Line 792:
 
=={{header|D}}==
===Eager version===
<lang d>import std.stdio: writeln;
 
Line 820 ⟶ 821:
[3, 1, 2]
[3, 2, 1]</pre>
===Lazy version===
With same main function produces the same output.
<lang d>import std.range, std.algorithm, std.math, std.exception;
struct Permutations(T) {
private immutable size_t num;
private T[] items;
private ulong tot;
this (in T[] items) pure nothrow
in {
enforce(items.length > 0,
"Permutations: items.length must be > 0");
} body {
static ulong factorial(in uint n) pure nothrow {
ulong result = 1;
foreach (i; 2 .. n + 1)
result *= i;
return result;
}
this.num = items.length;
this.items = items.dup;
this.tot = factorial(this.num);
}
@property const(T[]) front() const pure nothrow {
return items;
}
@property bool empty() const pure nothrow {
return tot == 0;
}
void popFront() pure nothrow {
tot--;
if (tot > 0) {
size_t j = num - 2;
while (items[j] > items[j + 1])
j--;
size_t k = num - 1;
while (items[j] > items[k])
k--;
swap(items[k], items[j]);
size_t r = num - 1;
size_t s = j + 1;
while (r > s) {
swap(items[s], items[r]);
r--;
s++;
}
}
}
}
Permutations!T permutations(T)(in T[] items) pure nothrow {
return Permutations!T(items);
}</lang>
 
=={{header|Delphi}}==
Anonymous user