RosettaCodeData/Task/Power-set/D/power-set-2.d

43 lines
673 B
D
Raw Permalink Normal View History

2015-11-18 06:14:39 +00:00
import std.range;
2013-10-27 22:24:23 +00:00
2015-11-18 06:14:39 +00:00
struct PowerSet(R)
if (isRandomAccessRange!R)
{
R r;
size_t position;
2015-02-20 00:35:01 -05:00
2015-11-18 06:14:39 +00:00
struct PowerSetItem
{
R r;
size_t position;
2015-02-20 00:35:01 -05:00
2015-11-18 06:14:39 +00:00
private void advance()
{
while (!(position & 1))
{
r.popFront();
position >>= 1;
}
}
2015-02-20 00:35:01 -05:00
2015-11-18 06:14:39 +00:00
@property bool empty() { return position == 0; }
@property auto front()
{
advance();
return r.front;
}
void popFront()
{
advance();
r.popFront();
position >>= 1;
}
}
2013-10-27 22:24:23 +00:00
2015-11-18 06:14:39 +00:00
@property bool empty() { return position == (1 << r.length); }
@property PowerSetItem front() { return PowerSetItem(r.save, position); }
void popFront() { position++; }
2013-10-27 22:24:23 +00:00
}
2015-11-18 06:14:39 +00:00
auto powerSet(R)(R r) { return PowerSet!R(r); }