Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
"Android: Selecting A Weighted Random Item From A List" for GameDevAlgorithms.com
private static Visitor_Type selectVisitorType() {
Visitor_Type visitor = new Visitor_Type();
List<Visitor_Type> visitorTypes = Visitor_Type.findWithQuery(Visitor_Type.class,
"SELECT * FROM VisitorType WHERE visitor_id NOT IN (SELECT type FROM Visitor)");
// Work out the total weighting.
double totalWeighting = 0.0;
for (Visitor_Type type : visitorTypes) {
totalWeighting += type.getWeighting();
}
// Generate a number between 0 and total probability.
double randomNumber = Math.random() * totalWeighting;
// Use the random number to select a visitor type.
double probabilityIterator = 0.0;
for (Visitor_Type type : visitorTypes) {
probabilityIterator += type.getWeighting();
if (probabilityIterator >= randomNumber) {
visitor = type;
break;
}
}
return visitor;
}
@JakeSteam
Copy link
Author

JakeSteam commented Jul 27, 2021

5 years later, here's a Kotlin version!

    fun pickItemToGenerate(itemOptions: List<ItemGeneration>): ItemGeneration? {
        val randomNumber = Math.random() * itemOptions.sumOf { it.weighting }
        
        var probabilityIterator = 0
        itemOptions.forEach { 
            probabilityIterator += it.weighting
            if (probabilityIterator >= randomNumber) {
                return it
            }
        }
        return null
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment