Skip to content

Instantly share code, notes, and snippets.

@JakeSteam
Created January 24, 2017 19:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JakeSteam/79dc987c2c46cf83b0883a1a749d9360 to your computer and use it in GitHub Desktop.
Save JakeSteam/79dc987c2c46cf83b0883a1a749d9360 to your computer and use it in GitHub Desktop.
"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

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