Skip to content

Instantly share code, notes, and snippets.

@DevSrSouza
Last active April 19, 2020 01:30
Show Gist options
  • Save DevSrSouza/973cf2c9f5f22c078c2e6aef5822a473 to your computer and use it in GitHub Desktop.
Save DevSrSouza/973cf2c9f5f22c078c2e6aef5822a473 to your computer and use it in GitHub Desktop.
Fitness proportionate selection in Kotlin (RouletteWheel)
inline fun <T> List<T>.selectRouletteWheelWithMinimum(
min: Double = 100.0,
sum: (T) -> Double
): T? {
if(isEmpty()) return null
val total = reversed().sumByDouble(sum)
val random = (Math.random() * if(total > min) total else min)
if(random > total) return null
return rouletteWheelFirstGreaterThemRandom(random, sum)
}
inline fun <T> List<T>.selectRouletteWheel(
sum: (T) -> Double
): T {
val reversed = reversed()
val total = reversed.sumByDouble(sum)
val random = Math.random() * total
return reversed.rouletteWheelFirstGreaterThemRandom(random, sum)
}
inline fun <T> Iterable<T>.rouletteWheelFirstGreaterThemRandom(
random: Double,
sum: (T) -> Double
): T {
var partialSum = 0.0
return first { current ->
partialSum += sum(current)
partialSum >= random
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment