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).

1  
// shuffledIterator()
2  
//
3  
// -iterates over a list in random order
4  
// -each element is returned exactly once if you iterate to the end
5  
// -efficient no matter how many elements you want
6  
// -can handle null elements
7  
// (whether it's very few, half of the list or almost all elements)
8  
9  
static <A> IterableIterator<A> shuffledIterator(L<A> l) {
10  
  ret new IterableIterator<A>() {
11  
    int n = l(l);
12  
    int i = 0;
13  
    new HashMap<Int, A> shuffled;
14  
    
15  
    public bool hasNext() { ret i < n; }
16  
    
17  
    public A next() {
18  
      int j = random(i, n);
19  
      A a = get(i), b = get(j);
20  
      shuffled.put(j, a);
21  
      shuffled.remove(i);
22  
      ++i;
23  
      ret b;
24  
    }
25  
    
26  
    A get(int i) {
27  
      // must call containsKey first because of possible null elements
28  
      ret shuffled.containsKey(i) ? shuffled.get(i) : l.get(i);
29  
    }
30  
  };
31  
}

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: 336 / 435
Version history: 9 change(s)
Referenced in: [show references]