Advertisement
Guest User

Untitled

a guest
Mar 13th, 2019
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 0.85 KB | None | 0 0
  1.  
  2. ///
  3. struct EachWithEachOtherRange(R) {
  4.   private R inputRange;
  5.  
  6.   this(R r) {
  7.     inputRange = r;
  8.   }
  9.  
  10.   private size_t y = 0;
  11.   private size_t x = 1;
  12.  
  13.   auto front() {
  14.     assert(!empty);
  15.  
  16.     return [inputRange[x], inputRange[y]];
  17.   }
  18.  
  19.   void popFront() {
  20.     x++;
  21.  
  22.     if(x >= inputRange.length) {
  23.       y++;
  24.       x = y+1;
  25.     }
  26.   }
  27.  
  28.   bool empty() const {
  29.     return x >= inputRange.length;
  30.   }
  31.  
  32.   size_t length() const {
  33.     const len = inputRange.length;
  34.  
  35.     return (len * len - len) / 2;
  36.   }
  37. }
  38.  
  39. ///
  40. auto eachWithOther(T)(T inputRange) {
  41.   return EachWithEachOtherRange!(T)(inputRange);
  42. }
  43.  
  44. unittest {
  45.   import std.algorithm.iteration: map;
  46.   import std.algorithm.searching: count;
  47.  
  48.   int[] arr = [0, 1, 2, 3];
  49.  
  50.   assert(arr.eachWithOther.map!(a => a).count == 6);
  51.   assert(arr.eachWithOther.length == 6);
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement