Last active
April 19, 2020 01:30
-
-
Save DevSrSouza/973cf2c9f5f22c078c2e6aef5822a473 to your computer and use it in GitHub Desktop.
Fitness proportionate selection in Kotlin (RouletteWheel)
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
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