Skip to content

Instantly share code, notes, and snippets.

@yashap
Last active September 12, 2016 05:18
Show Gist options
  • Save yashap/ffb011da0bcc9bdad8e903d49bc2b755 to your computer and use it in GitHub Desktop.
Save yashap/ffb011da0bcc9bdad8e903d49bc2b755 to your computer and use it in GitHub Desktop.
#!/usr/bin/env scala
// This is my solution to http://fivethirtyeight.com/features/who-keeps-the-money-you-found-on-the-floor/
// To run it, just check out the script, make it executable (`chmod +x riddler_solution`), then execute it (`./riddler_solution`)
// You will need the Scala programming language first (if you're on a Mac with Homebrew installed, just `brew install scala`)
import scala.util.Random
import scala.collection.mutable.ListBuffer
class Statistician(val id: Int, rng: Random, winnerLog: ListBuffer[Int], left: => Statistician, right: => Statistician) {
def tick(): Unit = {
rng.nextInt(3) match {
case 0 => winnerLog += id
case 1 => left.tick()
case 2 => right.tick()
}
}
}
object Scenario extends App {
val winnerLog = ListBuffer.empty[Int]
val rng = new Random()
val me: Statistician = new Statistician(0, rng, winnerLog, colleague4, colleague1)
lazy val colleague1: Statistician = new Statistician(1, rng, winnerLog, me, colleague2)
lazy val colleague2: Statistician = new Statistician(2, rng, winnerLog, colleague1, colleague3)
lazy val colleague3: Statistician = new Statistician(3, rng, winnerLog, colleague2, colleague4)
lazy val colleague4: Statistician = new Statistician(4, rng, winnerLog, colleague3, me)
val iterations = 1000000
(0 until iterations).foreach(_ => me.tick())
val myWins = winnerLog.toList.count(_ == me.id)
println(f"I win ${myWins.toDouble / iterations * 100}%1.2f%% of the time")
}
Scenario.main(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment