RosettaCodeData/Task/Hailstone-sequence/D/hailstone-sequence-2.d

21 lines
634 B
D
Raw Permalink Normal View History

2015-02-20 00:35:01 -05:00
import std.stdio, std.algorithm, std.typecons, std.range;
2013-04-10 21:29:02 -07:00
2015-02-20 00:35:01 -05:00
auto hailstone(uint m) pure nothrow @nogc {
return m
.recurrence!q{ a[n - 1] & 1 ? a[n - 1] * 3 + 1 : a[n - 1]/2}
.until!q{ a == 1 }(OpenRight.no);
2013-04-10 21:29:02 -07:00
}
void main() {
enum M = 27;
2015-02-20 00:35:01 -05:00
immutable h = M.hailstone.array;
2013-10-27 22:24:23 +00:00
writeln("hailstone(", M, ")= ", h[0 .. 4], " ... " , h[$ - 4 .. $]);
writeln("Length hailstone(", M, ")= ", h.length);
2013-04-10 21:29:02 -07:00
enum N = 100_000;
2013-10-27 22:24:23 +00:00
immutable p = iota(1, N)
2015-02-20 00:35:01 -05:00
.map!(i => tuple(i.hailstone.walkLength, i))
2013-10-27 22:24:23 +00:00
.reduce!max;
2013-04-10 21:29:02 -07:00
writeln("Longest sequence in [1,", N, "]= ",p[1]," with len ",p[0]);
}