RosettaCodeData/Task/Non-continuous-subsequences/D/non-continuous-subsequences-2.d

44 lines
1.1 KiB
D
Raw Permalink Normal View History

2013-04-10 23:57:08 -07:00
struct Ncsub(T) {
T[] seq;
2015-02-20 00:35:01 -05:00
int opApply(int delegate(ref T[]) dg) const {
immutable n = seq.length;
2013-04-10 23:57:08 -07:00
int result;
2015-02-20 00:35:01 -05:00
auto S = new T[n];
2013-04-10 23:57:08 -07:00
2015-02-20 00:35:01 -05:00
OUTER: foreach (immutable i; 1 .. 1 << n) {
uint lenS;
2013-04-10 23:57:08 -07:00
bool nc = false;
2015-02-20 00:35:01 -05:00
foreach (immutable j; 0 .. n + 1) {
immutable k = i >> j;
2013-04-10 23:57:08 -07:00
if (k == 0) {
if (nc) {
2015-02-20 00:35:01 -05:00
auto auxS = S[0 .. lenS];
2013-04-10 23:57:08 -07:00
result = dg(auxS);
if (result)
2015-02-20 00:35:01 -05:00
break OUTER;
2013-04-10 23:57:08 -07:00
}
break;
} else if (k % 2) {
2015-02-20 00:35:01 -05:00
S[lenS] = seq[j];
lenS++;
} else if (lenS)
2013-04-10 23:57:08 -07:00
nc = true;
}
}
return result;
}
}
void main() {
import std.array, std.range;
2015-02-20 00:35:01 -05:00
//assert(24.iota.array.Ncsub!int.walkLength == 16_776_915);
auto r = 24.iota.array;
uint counter = 0;
2013-04-10 23:57:08 -07:00
foreach (s; Ncsub!int(r))
counter++;
assert(counter == 16_776_915);
}