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

15
LINES

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

JavaX fragment (include)

static <A> L<A> selectRandom(int n, L<A> list) {
  ret selectRandom(list, n);
}

static <A> L<A> selectRandom(L<A> list, int n) {
  if (l(list) < n) null;
  new L<A> l;
  list = cloneList(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   

Travelled to 4 computer(s): cfunsshuasjs, gwrvuhgaqvyk, mqqgnosmbjvj, tvejysmllsmz

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/4
Text MD5: 111a81c4294e7f9e6e7a426fda4782e3
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2018-03-23 20:05:34
Source code size: 307 bytes / 15 lines
Pitched / IR pitched: No / No
Views / Downloads: 229 / 156
Version history: 3 change(s)
Referenced in: [show]