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

31
LINES

< > BotCompany Repo | #1017660 // shuffledIterator - iterate over list in random order

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

Libraryless. Click here for Pure Java version (3919L/23K).

// shuffledIterator()
//
// -iterates over a list in random order
// -each element is returned exactly once if you iterate to the end
// -efficient no matter how many elements you want
// -can handle null elements
// (whether it's very few, half of the list or almost all elements)

static <A> IterableIterator<A> shuffledIterator(L<A> l) {
  ret new IterableIterator<A>() {
    int n = l(l);
    int i = 0;
    new HashMap<Int, A> shuffled;
    
    public bool hasNext() { ret i < n; }
    
    public A next() {
      int j = random(i, n);
      A a = get(i), b = get(j);
      shuffled.put(j, a);
      shuffled.remove(i);
      ++i;
      ret b;
    }
    
    A get(int i) {
      // must call containsKey first because of possible null elements
      ret shuffled.containsKey(i) ? shuffled.get(i) : l.get(i);
    }
  };
}

download  show line numbers  debug dex  old transpilations   

Travelled to 16 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, irmadwmeruwu, ishqpsrjomds, iveijnkanddl, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt, whxojlpjdney

No comments. add comment

Snippet ID: #1017660
Snippet name: shuffledIterator - iterate over list in random order
Eternal ID of this version: #1017660/10
Text MD5: f44d51662e5be42ea1d2de19a4f2254f
Transpilation MD5: ec53ad0e1668778d847babc9f8d66805
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2021-09-22 20:19:07
Source code size: 858 bytes / 31 lines
Pitched / IR pitched: No / No
Views / Downloads: 394 / 505
Version history: 9 change(s)
Referenced in: [show references]