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

11
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);
  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 2 computer(s): cfunsshuasjs, 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/3
Text MD5: 63cc5d3fd6f8eaaedb7956cff69f93b6
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2017-05-27 13:05:42
Source code size: 222 bytes / 11 lines
Pitched / IR pitched: No / No
Views / Downloads: 154 / 74
Version history: 2 change(s)
Referenced in: [show]