Anonymous user
Power set: Difference between revisions
→{{header|D}}: Move content from subpage
(→{{header|D}}: Move content from subpage) |
|||
Line 662:
=={{header|D}}==
This implementation defines a range which *lazily* enumerates the power set.
<lang d>import std.algorithm;
auto powerSet(R)(R r)
{
return
(1L<<r.length)
.iota
.map!(i =>
r.enumerate
.filter!(t => (1<<t[0]) & i)
.map!(t => t[1])
);
}
void main(string[] args)
{
import std.stdio;
args[1..$].powerSet.each!writeln;
}</lang>
An alternative version, which implements the range construct from scratch:
<lang d>import std.range;
struct PowerSet(R)
if (isRandomAccessRange!R)
{
R r;
size_t position;
struct PowerSetItem
{
R r;
size_t position;
private void advance()
{
while (!(position & 1))
{
r.popFront();
position >>= 1;
}
}
@property bool empty() { return
@property auto front()
{
advance();
return r.front;
}
void popFront()
{
advance();
r.popFront();
position >>= 1;
}
}
@property bool empty() { return position == (1 << r.length); }
@property PowerSetItem front() { return PowerSetItem(r.save, position); }
void popFront() { position++; }
}
auto powerSet(R)(R r) { return PowerSet!R(r); }</lang>
{{out}}
<pre>$ rdmd powerset a b c
[]
["a"]
["b"]
["a", "b"]
["c"]
["a", "c"]
["b", "c"]
["a", "b", "c"]</pre>
=={{header|Déjà Vu}}==
|