Reputation: 85
I'm trying to figure out a method which as two arguments, one is a Object[] and the other a float[], both same size. the floats are the chances of the output being the corresponding object in the object list, object in index i has chance (0.0-1.0) stored in the float in index i. The values on the chance list all sum up to 1.0 if all summed up together.
The thing that I want this method to do is to return one of the objects from the list randomly, being the chance of each object of being picked inside the chance list. Example {banana, apple, orange} {0.1, 0.5, 0.4} Having 10% chance of returning banana, 50% apple and 40% orange.
Note: The method can't be for a fixed number of objects, so a hard-coded if chain won't work :/
Any help is much appreciated.
Upvotes: 1
Views: 1036
Reputation: 3592
My approach to use a a variable to store the adumulated chance of a position in the array.
public Object randomObject(Object[] objects, float[] chances){
//Implement here validations, about arrays size and chances values.
float random = (float) Math.random();
float acumulatedChance = 0f;
for (int i = 0; i < chances.length; i++) {
acumulatedChance += chances[i];
if (acumulatedChance >= random) {
return objects[i];
}
}
return objects[objects.length-1];
}
Upvotes: 3
Reputation: 974
All you need to do is count the number of appearances of each element in list.
Number of each appearances of an element in that list divided by the sum of all appearances equals the probability that element will randomly get picked from that list.
ArrayList can contain your elements. You can count appearances of each element in an hash map or another ArrayList provided you keep track which index counts which element.
You will need to loop once through the element list to gather count data, after that simply calculate probabilities from that count data.
Upvotes: 0