public class RedOrBlack { def static final BLACK = 0 def static final RED = 1 def static final ZERO = 2 def m_rng = new Random() def spinWheel() { // Value range: [0..36]. def value = m_rng.nextInt(37) if (value == 0) { return ZERO } else if (value % 2 == 0) { return BLACK } return RED } def runSimulation(spinsLeft) { // 'withDefault' ensures that lookups with non-existent keys return a value of '0'. def seriesMapBlack = [:].withDefault { 0 } def seriesMapRed = [:].withDefault { 0 } def seriesMapZero = [:].withDefault { 0 } def seriesMaps = [seriesMapBlack, seriesMapRed, seriesMapZero] def prevColor def currentSeriesLength def initialized = false while (spinsLeft-- > 0) { def newColor = spinWheel() // Initialize upon first spin. if (!initialized) { prevColor = newColor currentSeriesLength = 0 initialized = true } // Current series continues. if (newColor == prevColor) { ++currentSeriesLength; // New color, series terminated. } else { // Keep track of how often a particular series length (of previous color) occurred. ++seriesMaps[prevColor][currentSeriesLength]; // Current series is over. currentSeriesLength = 0 } // Ensure that the final series is entered as well. if (spinsLeft == 0) { ++seriesMaps[newColor][currentSeriesLength] } prevColor = newColor } return seriesMaps } }