Skip to content

Instantly share code, notes, and snippets.

@Oziomajnr
Created January 9, 2022 11:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Oziomajnr/bb381f72946541c4059df8491ac4356a to your computer and use it in GitHub Desktop.
Save Oziomajnr/bb381f72946541c4059df8491ac4356a to your computer and use it in GitHub Desktop.
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