Practice: Dice Statistics
Simulating chance.
When you roll two dice, which total comes up most often? You could work it out on paper, or you could let JavaScript roll them sixty thousand times, and count. Simulation is a powerful way to answer questions about chance.

- Two dice
- Which total is most common?
- Roll 60,000 times
Counting totals
Roll gives a number from one to six. We roll two dice sixty thousand times, and count each total in an array. Then we print a text bar chart, with one block for every two hundred rolls. Seven comes up most, because more pairs add up to seven than to any other total. Run it.
const roll = () => Math.floor(Math.random() * 6) + 1;
const counts = Array(13).fill(0);
for (let i = 0; i < 60000; i++) {
counts[roll() + roll()]++;
}
for (let total = 2; total <= 12; total++) {
const bar = "#".repeat(Math.round(counts[total] / 200));
console.log(String(total).padStart(2), bar);
}2 ######### 3 ################# 4 ######################### 5 ################################# 6 ########################################## 7 ################################################## 8 ######################################### 9 ################################# 10 ######################### 11 ################# 12 ########
Reading the result
The chart makes a triangle. Two and twelve are the rarest, because only one pair makes each of them. Seven is the most common, because six different pairs make it. Each run gives slightly different counts, because the rolls are random, but the shape is always the same.
| key | value |
|---|---|
| Array(13).fill(0) | a counter per total |
| padStart | line up the labels |
| repeat | draw a bar |
| Shape | peaks at 7 |
Summary
Simulating many random rolls showed that seven is the most common total. Next, fetching data and showing it in a report.
Key takeaways- Simulate many times
- Count in an array
- Text bar chart