-
Notifications
You must be signed in to change notification settings - Fork 3
/
RandomBucket.java
executable file
·70 lines (60 loc) · 1.39 KB
/
RandomBucket.java
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package benchmark.generator;
import java.util.Random;
public class RandomBucket {
private double[] cumulativePercentage;
private Object[] objects;
private int index;
private double totalPercentage;
private Random ranGen;
public RandomBucket(int size)
{
cumulativePercentage = new double[size];
objects = new Object[size];
index=0;
totalPercentage = 0.0;
ranGen = new Random();
}
public RandomBucket(int size, long seed)
{
cumulativePercentage = new double[size];
objects = new Object[size];
index=0;
totalPercentage = 0.0;
ranGen = new Random(seed);
}
public void add(double percentage, Object obj)
{
if(index==objects.length)
{
System.err.println("No more objects can be added into Bucket!");
return;
}
else
{
objects[index] = obj;
cumulativePercentage[index] = percentage;
totalPercentage+=percentage;
}
index++;
if(index==objects.length)
{
double cumul=0.0;
for(int i=0;i<objects.length;i++)
{
cumul += cumulativePercentage[i]/totalPercentage;
cumulativePercentage[i] = cumul;
}
}
}
public Object getRandom()
{
double randIndex = ranGen.nextDouble();
for(int i=0;i<objects.length;i++)
{
if(randIndex<=cumulativePercentage[i])
return objects[i];
}
//Should never happens, but...
return objects[objects.length-1];
}
}