Anonymous user
Power set: Difference between revisions
Updated both D entries
(→{{header|Clojure}}: added alternate solution) |
(Updated both D entries) |
||
Line 607:
=={{header|D}}==
Version using just arrays (it assumes the input to contain distinct items):
<lang d>T[][] powerSet(T)(in T[] s) pure nothrow @safe {
auto r = new typeof(return)(1, 0);
foreach (e; s) {
Line 620:
void main() {
import std.stdio;
[1, 2, 3].powerSet.writeln;
}</lang>
Line 627 ⟶ 628:
===Lazy Version===
Compile with -version=power_set2_main to run the main.
<lang d>auto powerSet(T)(T[] xs) pure nothrow @safe {
static struct Result {▼
auto output = new T[xs.length];▼
size_t len;
▲ struct Result {
size_t bits;
@property empty() const pure nothrow { return bits == len; }▼
void popFront() pure nothrow { bits++; }▼
@property save() pure nothrow { return this; }▼
this(T[]
this.xsLocal = xs_;
this.len = 1U << xs_.length;
}
return bits == len;
}
▲ void popFront() pure nothrow @safe { bits++; }
▲ @property save() pure nothrow @safe { return this; }
T[] front() pure nothrow @safe {
size_t pos = 0;
foreach (immutable size_t i; 0 ..
if (bits & (1 << i))
output[pos++] =
return output[0 .. pos];
}
}
return Result(xs);
}
|