Created
January 24, 2017 19:11
-
-
Save JakeSteam/79dc987c2c46cf83b0883a1a749d9360 to your computer and use it in GitHub Desktop.
"Android: Selecting A Weighted Random Item From A List" for GameDevAlgorithms.com
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
5 years later, here's a Kotlin version!