Created
December 16, 2015 16:53
-
-
Save mayonesa/6eb9fbb22fd0c4dd8d3d to your computer and use it in GitHub Desktop.
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 scala.util.Random.nextInt | |
/** | |
Simulate throwing two six-sided dice 200 times and create a histogram of the results like this: | |
2: XXXX | |
3: XXXXXXXXXX | |
4: XXXXXXXXXXXXXXXXXXXXXX | |
5: XXXXXXXXXXXXXXXXXXXXX | |
6: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX | |
7: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX | |
8: XXXXXXXXXXXXXXXXXXXXXXXXXX | |
9: XXXXXXXXXXXXXXXXXXXXX | |
10: XXXXXXXXXXXXXX | |
11: XXXXXXXXXXXX | |
12: XXXX | |
**/ | |
object SimpleDiceHistogrammer extends App { | |
println(DiceHist.roll(200)) | |
} | |
trait DiceHist { | |
def roll(): DiceHist | |
} | |
object DiceHist { | |
private val IndOffset = 2 | |
private val NRows = 11 | |
private def apply(rolls: IndexedSeq[String]) = new DiceHistImpl(rolls) | |
private def empty: DiceHist = | |
DiceHist(IndexedSeq.tabulate(NRows) { i => f"${i + IndOffset}%2d: " }) | |
def roll(times: Int): DiceHist = | |
(1 to times).foldLeft(empty) { (hist, _) => | |
hist.roll() | |
} | |
private class DiceHistImpl(rolls: IndexedSeq[String]) extends DiceHist { | |
def roll(): DiceHist = { | |
val rollRes = Dice.roll() + Dice.roll() | |
val i = rollRes - IndOffset | |
DiceHist(rolls updated (i, rolls(i) + 'X')) | |
} | |
override def toString = rolls mkString "\n" | |
} | |
} | |
object Dice { | |
def roll(): Int = nextInt(6) + 1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment