-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomAPI.java
More file actions
55 lines (45 loc) · 1.24 KB
/
RandomAPI.java
File metadata and controls
55 lines (45 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package de.salty.smp.gambling;
import java.util.NavigableMap;
import java.util.Random;
import java.util.TreeMap;
public class RandomAPI<E> {
public final NavigableMap<Double, E> map = new TreeMap<Double, E>();
private final Random random;
private double total = 0;
public RandomAPI() {
this(new Random());
}
public RandomAPI(Random random) {
this.random = random;
}
public void add(double weight, E result) {
if (weight <= 0) return;
total += weight;
map.put(total, result);
}
public WinningObject<E> next() {
double value = random.nextDouble() * total;
return new WinningObject<E>(map.ceilingEntry(value).getValue(), value);
}
@SuppressWarnings("unchecked")
public RandomAPI<E> clone(){
try {
return (RandomAPI<E>) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
public void clear(){
map.clear();
total = 0;
}
public static class WinningObject<E>{
public E entry;
public double ticket;
public WinningObject(E e, double d){
this.entry = e;
this.ticket = d;
}
}
}