Created
August 6, 2015 17:45
-
-
Save occ/bfbdbfa4e18b5c1c700c to your computer and use it in GitHub Desktop.
Dirty simulation to Monty Hall Problem
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
package me.occ.dealornodeal | |
import scala.util.Random | |
object Main extends App { | |
val rng = new Random() | |
def runTrial(changeMind: Boolean, showOutput: Boolean = false): Boolean = { | |
val prize = rng.nextInt(3) | |
var options = Seq.range(0, 3).map(_ == prize).zipWithIndex | |
if (showOutput) println(s"Stage: $options") | |
val initialGuess = options(rng.nextInt(3)) | |
if (showOutput) println(s"Guess: $initialGuess") | |
val toEliminate = options.find(t => !t._1 && t != initialGuess).get | |
options = options.filterNot(_ == toEliminate) | |
if (showOutput) println(s"Remaining: $options") | |
val nextGuess = if (!changeMind) initialGuess else options.find(_ != initialGuess).get | |
if (showOutput) { | |
print(s"Final guess: $nextGuess -- ") | |
if (nextGuess._1) println("Win") else println("Lose") | |
} | |
nextGuess._1 | |
} | |
def runNTrials(n: Int, changeMind: Boolean): Unit = { | |
val win: Int = Seq.range(0, n).map(x => runTrial(changeMind)).count(_ == true) | |
val lose = n - win | |
println(s"Win: $win, Lose: $lose. Total: ${win.toDouble/n}") | |
} | |
runNTrials(1000000, changeMind = true) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment