Created
October 23, 2021 03:53
-
-
Save retheviper/071a7addb53e97ec4b0032a7090d1225 to your computer and use it in GitHub Desktop.
Monty hall problem is kotlin
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
import kotlin.system.measureTimeMillis | |
const val GOAT = "goat" | |
const val CAR = "car" | |
const val OUT = "out" | |
val RANGE = (0..2) | |
/** | |
* put a car behind one door | |
*/ | |
fun populateDoors(): List<String> { | |
val car = RANGE.random() | |
return RANGE.map { | |
if (it == car) CAR else GOAT | |
} | |
} | |
fun playGame(firstChoice: Int): List<String> { | |
return populateDoors().mapIndexed { index, door -> | |
if ((door != CAR) and (index != firstChoice)) { | |
OUT | |
} else { | |
door | |
} | |
} | |
} | |
fun count(): () -> Int { | |
var counter = 0 | |
return { counter++ } | |
} | |
/** | |
* playing the game 100,000 times | |
*/ | |
fun main() { | |
val wins = count() | |
val losses = count() | |
val elapsed = measureTimeMillis { | |
(0 until 100000).forEach { _ -> | |
val firstChoice = RANGE.random() // choose a random door | |
val result = playGame(firstChoice) | |
if (result[firstChoice] == CAR) { | |
losses() // contestant switched to losing door | |
} else { | |
wins() // contestant switched to winning door | |
} | |
} | |
} | |
println( | |
""" | |
All choices were switched. | |
Wins: ${wins()} | |
Losses: ${losses()} | |
Elapsed time: $elapsed ms | |
""".trimIndent() | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment