Reputation: 23
Say I have a loop of 100 where every time I run it, 40% of the time I always have to do function A, 30% of the time I have to do function B and the remaining 30% I have to do C.
So far I have found this which doesn't exactly solve my problem as there is always the possibility of not performing the minimum amount required.
Is there something else I could use which could help me? Also these percentages have to calculated at runtime.
Upvotes: 1
Views: 70
Reputation: 522346
Create a list containing 1 to 100, shuffle it, then use those values drawn sequentially to determine which function to execute:
List<Integer> list = new ArrayList<>();
for (int i=0; i < 100; ++i) {
list.add(i);
}
long seed = System.nanoTime();
Collections.shuffle(list, new Random(seed));
// now here is your loop
for (int i=0; i < 100; ++i) {
if (list.get(i) < 40) {
A();
}
else if (list.get(i) < 70) {
B();
}
else {
C();
}
}
Upvotes: 4