fork(1) download
  1. import std.stdio : writeln;
  2. import std.algorithm.comparison: min;
  3. import std.algorithm.iteration: sum;
  4. import core.time: MonoTime, Duration;
  5.  
  6.  
  7. auto sum_subranges(T)(T input, uint range)
  8. {
  9. import std.range : chunks, ElementType, array;
  10. import std.algorithm : map;
  11.  
  12. if (range == 0)
  13. {
  14. return ElementType!(T)[].init;
  15. }
  16. return input.chunks(range).map!(sum).array;
  17. }
  18.  
  19. unittest
  20. {
  21. assert(sum_subranges([1,1,1], 2) == [2, 1]);
  22. assert(sum_subranges([1,1,1,2,3,3], 2) == [2, 3, 6]);
  23. assert(sum_subranges([], 2) == []);
  24. assert(sum_subranges([1], 2) == [1]);
  25. assert(sum_subranges([1], 0) == []);
  26. }
  27.  
  28.  
  29. void main()
  30. {
  31. import std.range : iota, array;
  32. auto v = iota(0,1000000).array;
  33. int sum;
  34. MonoTime beg = MonoTime.currTime;
  35. for (int i=0; i < 100; i++)
  36. sum += cast(int)sum_subranges(v,2).length;
  37. MonoTime end = MonoTime.currTime;
  38. writeln(end-beg);
  39. writeln(sum);
  40. }
Success #stdin #stdout 3.27s 15800KB
stdin
Standard input is empty
stdout
3 secs, 260 ms, 631 μs, and 3 hnsecs
50000000