Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simulating the solution the optimal stopping problem using the 37% rule.
fun main() {
val resultArray = IntArray(100) {
0
}
for (percent in 1..100) {
for (x in 1..1000000) {
if (simulateFindingBestSecretary(percent)) {
resultArray[percent - 1]++
}
}
println(resultArray.contentToString())
}
}
fun simulateFindingBestSecretary(percentageToLeap: Int): Boolean {
if (percentageToLeap <= 0 || percentageToLeap > 100) {
error("Percentage to leap must be between 1-100")
}
val numberOfSecretaries = 1000
val allSecretaries = (1..numberOfSecretaries).shuffled().map { value ->
Secretary(value)
}
val leapValue = percentageToLeap * (numberOfSecretaries / 100)
val bestSecretaryFromFirst37Percent =
allSecretaries.take(leapValue).maxByOrNull {
it.value
}!!
val selectedSecretary = allSecretaries.takeLast(numberOfSecretaries - leapValue).firstOrNull { secretary ->
secretary.value > bestSecretaryFromFirst37Percent.value
} ?: allSecretaries.last()
return selectedSecretary.value == numberOfSecretaries
}
data class Secretary(val value: Int)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment