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