AI Hints
Home›JavaScript Tutorial›Practice Projects 2
JavaScript · Lesson 120 of 138

Practice: Dice Statistics

Simulating chance.

⏱ 2 min read▶ Video at 2:24:14🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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.

Practice: Dice Statistics
From the video: Practice: Dice Statistics
  • 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.

app.jsjavascript
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);
}
Output
 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.

keyvalue
Array(13).fill(0)a counter per total
padStartline up the labels
repeatdraw a bar
Shapepeaks 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
Next up: Practice: Weather Report — fetch and format