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

12
LINES

< > TinyBrain | #1002448 - selectRandom - select n random elements from list (in random order, no duplicates)

JavaX fragment (include)

static <A> L<A> selectRandom(L<A> list, int n) {
  if (l(list) < n) null;
  new L<A> l;
  list = cloneList(list);
  n = min(n, l(list));
  repeat n {
    int i = rand(l(list));
    l.add(list.get(i));
    list.remove(i);
  }
  ret l;
}

Author comment

returns less than n elements if list too small

download  show line numbers  debug dex   

No comments. add comment

Snippet ID: #1002448
Snippet name: selectRandom - select n random elements from list (in random order, no duplicates)
Eternal ID of this version: #1002448/2
Text MD5: 05dec1d1d44ba442ec866162107f190b
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2017-03-18 16:20:47
Source code size: 246 bytes / 12 lines
Pitched / IR pitched: No / No
Views / Downloads: 90 / 16
Version history: 1 change(s)
Referenced in: [show]