Created
March 27, 2015 13:19
-
-
Save whaley/8ba80e337da7a9cf3437 to your computer and use it in GitHub Desktop.
Monty Hall Problem in Scala
This file contains hidden or 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 scala.util.Random | |
| sealed trait Prize | |
| case object Car extends Prize | |
| case object Goat extends Prize | |
| object Montyhall { | |
| def main(args: Array[String]) { | |
| val runs = 10000000 | |
| val (cars,_) = | |
| 1.to(runs).map(_ => play()).partition(_ == Car) | |
| val percentCarChosen: Double = cars.length.toDouble / runs | |
| println(f"Car selected $percentCarChosen of the time.") //This will be 0.6667'sh or so | |
| } | |
| def play(): Prize = { | |
| //Create three doors and assign car to a single random door | |
| val doors = List(Goat,Goat,Goat).updated(selection(),Car) | |
| //Allow user to pick a random door as selection | |
| val firstPickIndex = selection() | |
| //Take away a door that 1) contains a goat 2) is not a door the user picked | |
| val doorsNotEligibleToReveal = Set(firstPickIndex,doors.indexOf(Car)) | |
| val takeAwayIndex = selection(filter = doorsNotEligibleToReveal.toList) | |
| //Return the door that remains that the user did not select | |
| doors(selection(List(firstPickIndex,takeAwayIndex))) | |
| } | |
| def selection(filter: List[Int] = Nil): Int = { | |
| val indices: List[Int] = List(0,1,2).diff(filter) | |
| indices(Random.nextInt(indices.size)) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment