I have an array of 10 elements.
|1|2|3|4|5|6|7|8|9|10|
The idea is to randomly peek at a value from this array, but with some probabilistic quantity.
The probabilistic selection of the element is as follows:
|5%|10%|15%|30%|20%|4%|6%|1%|3%|6%|
This means that selecting the first element has a 5% chance, the second element has a 10% chance and so on.
My Solution:
import java.util.*;
public class Example {
public static void main( String[] args ) {
int [] values = {1,2,3,4,5,6,7,8,9,10};
double [] probabilities = {0.05,0.1,0.15,0.3,0.2,0.04,0.06,0.01,0.03,0.06};
double cumulativeSum = 0;
double r = new Random().nextDouble();//random number between 0 and 1
int index=0;// index of the chosen value
for (double prob:probabilities) {
cumulativeSum += prob;
if (cumulativeSum >= r) {
break;
}
index++;
}
System.out.println(index);
System.out.println("the value picked "+values[index]);
}
}
I'm looking for a faster solution than mine. The array i made is only a tiny example, normally I can have arrays with 10000 cells.