# Elchanan Mossel’s Probability Problem in JavaScript

An interesting problem popped into my twitter feed this morning:

Here’s how I wrote the problem in JavaScript:

```function rollDie() {
return Math.floor(Math.random() * (7 - 1) + 1);
}

function allEven(arr) {
for (var i = 0; i < arr.length; i += 1) {
if (arr[i] % 2 !== 0) {
return false;
}
}

return true;
}

function rollsToSix() {
var rollResults = [];
var sixRolled = false;

while (sixRolled === false) {
var roll = rollDie();

if (roll === 6) {
rollResults.push(6);
sixRolled = true;
} else {
rollResults.push(roll);
}
}

console.log(rollResults);
return rollResults;
}

function howManyPositiveResults(attempts) {
var positiveResults = 0;

for (var i = 0; i < attempts; i += 1) {
var resultOfRoll = allEven(rollsToSix());

if (resultOfRoll === true) {
positiveResults += 1;
}
}

return positiveResults;
}

console.log(howManyPositiveResults(100));

```

The above program runs the results 100 times and returns the number of positive results. It also logs all the rolls even if the consecutive rolls included odd numbers.

It was fun to watch Mike Lawler do this problem with his children. I learned another approach to the problem from him. You can watch it here:

Exploring Elchanan Mossel’s fantastic probability problem with kids

This site uses Akismet to reduce spam. Learn how your comment data is processed.