Created
January 9, 2022 11:04
-
-
Save Oziomajnr/bb381f72946541c4059df8491ac4356a to your computer and use it in GitHub Desktop.
Simulating the solution the optimal stopping problem using the 37% rule.
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
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