Libraryless. Click here for Pure Java version (3184L/20K).
1 | sclass RandomizerFromHistogram<A> implements IF0<A> { |
2 | new LPair<A, Long> list; |
3 | transient Random randomizer = defaultRandomizer(); |
4 | |
5 | *(MultiSet<A> ms) { |
6 | long sum = 0; |
7 | for (A a : keys(ms)) { |
8 | int val = ms.get(a); |
9 | if (val == 0) continue; |
10 | sum += val; |
11 | list.add(pair(a, sum)); |
12 | } |
13 | } |
14 | |
15 | public A get() { |
16 | if (empty(list)) null; |
17 | long val = randomLong(randomizer, sum()); |
18 | ret get(val); |
19 | } |
20 | |
21 | long sum() { ret empty(list) ? 0 : last(list).b; } |
22 | |
23 | // val must be between 0 and sum()-1 |
24 | A get(long val) { |
25 | int idx = generalizedBinarySearch2(list, p -> cmp((long) p.b, val+1)); |
26 | if (idx < 0) { |
27 | ifdef RandomizerFromHistogram_debug |
28 | print("idx1: " + idx); |
29 | endifdef |
30 | idx = -idx-1; |
31 | } |
32 | //print("idx: " + idx); |
33 | ret assertNotNull(pairA(_get(list, idx))); |
34 | } |
35 | } |
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: | 205 / 458 |
Version history: | 9 change(s) |
Referenced in: | [show references] |