Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

62
LINES

< > BotCompany Repo | #1029046 // intersectMultipleSortedCollectionsI [iterator]

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (2583L/16K).

// null elements are not supported
static <A extends Comparable<A>, B extends Iterable<A>> ItIt<A> intersectMultipleSortedCollectionsI(L<B> collections) {
  if (empty(collections)) ret emptyItIt();
  
  ret iteratorFromFunction_if0(new IF0<A> {
    Iterator<A>[] iterators = makeIteratorArray(collections);
    int n = iterators.length;
    A[] objects = (A[]) new Comparable[n];
    bool done;
    
    {
      // Grab first round of objects
      for i to n:
        if (step(i)) break;
    }
    
    // returns true if done
    bool step(int i) {
      if (!iterators[i].hasNext())
        { set done; true; }
      else {
        objects[i] = iterators[i].next();
        ifdef intersectMultipleSortedCollectionsI_debug
          print("Stepped " + (i+1) + " => " + objects[i]);
        endifdef
      }
      false;
    }
    
    public A get() {
      while ping (true) {
        if (done) null;
        
        // get min & max
        
        A min = objects[0], max = objects[0];
        for (int i = 1; i < n; i++) {
          A o = objects[i];
          if (min.compareTo(o) > 0) min = o;
          if (max.compareTo(o) < 0) max = o;
        }
        
        // min = max? then return element
        
        ifdef intersectMultipleSortedCollectionsI_debug
          print("min=" + min + ", max=" + max);
        endifdef
        
        if (min == max) {
          for i to n: if (step(i)) break;
          ret min;
        }
        
        // advance all to max
        
        for i to n:
          while (objects[i].compareTo(max) < 0)
            if (step(i)) null;
      }
    }
  });
}

download  show line numbers  debug dex  old transpilations   

Travelled to 7 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tvejysmllsmz, vouqrxazstgt, xrpafgyirdlv

No comments. add comment

Snippet ID: #1029046
Snippet name: intersectMultipleSortedCollectionsI [iterator]
Eternal ID of this version: #1029046/10
Text MD5: 6c5a0680e4bd6b2982747c93ed7d588a
Transpilation MD5: 91daceac10cbd3df351d8251e8991de2
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2020-07-17 17:10:57
Source code size: 1675 bytes / 62 lines
Pitched / IR pitched: No / No
Views / Downloads: 216 / 335
Version history: 9 change(s)
Referenced in: [show references]