-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdice-simulation.js
More file actions
59 lines (51 loc) · 2.16 KB
/
dice-simulation.js
File metadata and controls
59 lines (51 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Generate random dice rolls for each number of dice
const generateDiceRolls = (numDice) => {
const diceRolls = [];
for (let i = 0; i < numDice; i++) {
const currentRoll = Math.floor(Math.random() * 6) + 1;
diceRolls.push(currentRoll);
}
return diceRolls;
}
// Calculate the total score from one game with a specified number of dice
const calculateTotalScore = (numDice) => {
let totalScore = 0;
let diceRolls = generateDiceRolls(numDice);
// Keep rolling until all dice are removed based on constraints
while (diceRolls.length > 0) {
if (diceRolls.some(die => die === 3)) {
totalScore += 0; // just to be explicit
diceRolls = diceRolls.filter(die => die !== 3);
} else {
const lowestDieRoll = Math.min(...diceRolls);
totalScore += lowestDieRoll;
const diceIndexToRemove = diceRolls.indexOf(lowestDieRoll);
diceRolls.splice(diceIndexToRemove, 1);
}
if (diceRolls.length > 0) {
diceRolls = generateDiceRolls(diceRolls.length);
}
}
return totalScore;
}
// Simulate the dice game for a specific number of simulations and dice available
const simulateDiceGame = (numDice, numSimulations) => {
const scoreCounts = {};
const startTime = Date.now();
for (let i = 0; i < numSimulations; i++) {
const score = calculateTotalScore(numDice);
scoreCounts[score] = (scoreCounts[score] || 0) + 1;
}
const endTime = Date.now();
const totalTime = (endTime - startTime) / 1000;
console.log(`Number of simulations was ${numSimulations} using ${numDice} dice.`);
for (const [score, count] of Object.entries(scoreCounts)) {
const occurrenceRate = (count / numSimulations).toFixed(2);
console.log(`Total ${score} occurs ${occurrenceRate} occurred ${count} times.`);
}
console.log(`Total simulation took ${totalTime} seconds.`);
};
// You can run this with node dice-simulation.js <numDice> <numSimulations>
// For example: node dice-simulation.js 5 10000
// Otherwise it defaults to 5 dice and 10000 simulations
simulateDiceGame(process.argv[2] || 5, process.argv[3] || 10000);