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

29
LINES

< > BotCompany Repo | #1017663 // shuffledIterator, Java version

JavaX source code (desktop) [tags: use-pretranspiled] - run with: x30.jar

Download Jar. Libraryless. Click here for Pure Java version (6090L/43K).

1  
!7
2  
3  
p-exp {
4  
  pnl(iteratorToList(shuffledIterator(words("This is a very good test"))));
5  
}
6  
7  
static <A> Iterator<A> shuffledIterator(final List<A> l) {
8  
  return new Iterator<A>() {
9  
    Random randomizer = new Random();
10  
    int n = l.size();
11  
    int i = 0;
12  
    Map<Integer, A> shuffled = new HashMap();
13  
    
14  
    public boolean hasNext() { ret i < n; }
15  
    
16  
    public A next() {
17  
      int j = i+randomizer.nextInt(n-i);
18  
      A a = get(i), b = get(j);
19  
      shuffled.put(j, a);
20  
      shuffled.remove(i);
21  
      ++i;
22  
      return b;
23  
    }
24  
    
25  
    A get(int i) {
26  
      return shuffled.containsKey(i) ? shuffled.get(i) : l.get(i);
27  
    }
28  
  };
29  
}

Author comment

Began life as a copy of #1017662

download  show line numbers  debug dex  old transpilations   

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

No comments. add comment

Snippet ID: #1017663
Snippet name: shuffledIterator, Java version
Eternal ID of this version: #1017663/3
Text MD5: 6745fc37eca9a6aea80bb48ee99d8ecb
Transpilation MD5: 7874a5721a1d8a310ddccdfb733aef8b
Author: stefan
Category: javax
Type: JavaX source code (desktop)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2018-07-31 19:02:22
Source code size: 665 bytes / 29 lines
Pitched / IR pitched: No / No
Views / Downloads: 326 / 772
Version history: 2 change(s)
Referenced in: [show references]