Rolling dice
by alexb
CSS
table {
margin: 0 auto;
max-width: 480px;
width: 100%;
}
th {
padding: 0 1em;
width: 0;
}
div {
background: red;
height: 1em;
}
JavaScript
const DICE = 10;
const SIDES = 6;
const SAMPLES = 1000000;
let max = 0;
const rolls = {};
for (let i = 0; i < SAMPLES; i++) {
let sum = 0;
for (let j = 0; j < DICE; j++) {
sum += Math.trunc(Math.random() * SIDES) + 1;
}
rolls[sum] = (rolls[sum] || 0) + 1;
if (rolls[sum] > max) {
max = rolls[sum];
}
}
const table = document.createElement('table');
for (let roll in rolls) {
const row = document.createElement('tr');
const th = document.createElement('th');
const td = document.createElement('td');
const bar = document.createElement('div');
th.innerText = roll;
bar.style.width = (rolls[roll] / max * 100).toFixed(6) + '%';
row.appendChild(th);
row.appendChild(td);
row.setAttribute('title', `${roll} was rolled ${rolls[roll]} times`);
td.appendChild(bar);
table.appendChild(row);
}
document.body.appendChild(table);