Libraryless. Click here for Pure Java version (3184L/20K).
sclass RandomizerFromHistogram<A> implements IF0<A> { new LPair<A, Long> list; transient Random randomizer = defaultRandomizer(); *(MultiSet<A> ms) { long sum = 0; for (A a : keys(ms)) { int val = ms.get(a); if (val == 0) continue; sum += val; list.add(pair(a, sum)); } } public A get() { if (empty(list)) null; long val = randomLong(randomizer, sum()); ret get(val); } long sum() { ret empty(list) ? 0 : last(list).b; } // val must be between 0 and sum()-1 A get(long val) { int idx = generalizedBinarySearch2(list, p -> cmp((long) p.b, val+1)); if (idx < 0) { ifdef RandomizerFromHistogram_debug print("idx1: " + idx); endifdef idx = -idx-1; } //print("idx: " + idx); ret assertNotNull(pairA(_get(list, idx))); } }
download show line numbers debug dex old transpilations
Travelled to 4 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx, vouqrxazstgt
No comments. add comment
Snippet ID: | #1030105 |
Snippet name: | RandomizerFromHistogram [OK] |
Eternal ID of this version: | #1030105/10 |
Text MD5: | 57871312abc8ef6a51b9d753ac29cc86 |
Transpilation MD5: | 78b9737d66b7af5286167a542bcadbf5 |
Author: | stefan |
Category: | javax |
Type: | JavaX fragment (include) |
Public (visible to everyone): | Yes |
Archived (hidden from active list): | No |
Created/modified: | 2020-11-09 11:48:40 |
Source code size: | 876 bytes / 35 lines |
Pitched / IR pitched: | No / No |
Views / Downloads: | 206 / 459 |
Version history: | 9 change(s) |
Referenced in: | #1034167 - Standard Classes + Interfaces (LIVE, continuation of #1003674) |