JSFiddle - React, Tailwind, and code Playground

Dice Probability

by skibulk

JavaScript

console.clear()
// https://www.omnicalculator.com/statistics/dice

// https://observablehq.com/@kieranpringle/calculating-dice-probabilities-part-1
// Gen an array of all possible dice combinations
function bruteForceAllNdNCombinations(sides, quantity){    
  var rolls = []

  if (quantity > 1) { // if there is more than one dice to roll
    var nMinus1Rolls = bruteForceAllNdNCombinations(sides, quantity-1)
    nMinus1Rolls.forEach(roll => { 
      for (var i = 1; i <= sides; i++) {
        rolls.push(roll.concat(i))
      }
    })
  } else { // if we are only rolling 1 dice
    for (var i = 1; i <= sides; i++) {
      rolls.push([i])     
    }  
  }

  return rolls
}

// Fudge Like
// Some values = success, some = failure, one of each cancels eachother out
// Dict is an array with value meanings: [-1, -1, 0, 0, +1, +1]
function getFudgeLike(sides, quantity, dict){
  var combos = bruteForceAllNdNCombinations(sides, quantity);
	var results = {};

  for(var i=0; i<combos.length; i++) {
  
	  var result = 0;
    
	  for(var j=0; j<combos[i].length; j++) {
      var die = combos[i][j];
      result += dict[die-1]
    }
		
    if (results[result] == undefined) {
    	results[result] = 1;
    }
    else
    {
	    results[result]++;
    }
  }
  
  var print = [];
  for(var prop in results) {
  	print.push(prop + ":\t" + Math.round((results[prop]/combos.length)*100) + "\n");
  }
  console.log(quantity + "d" + sides + " | " + combos.length + " combinations\n" + print.join(""));
  // console.log(quantity + "d" + sides + " | " + (100 - Math.round(results[0] / combos.length * 100)) + "% | " + combos.length + " combinations");
}

// Excluding snake eyes, doubles mean success
function getDoublesRate(sides, quantity){
	var combos = bruteForceAllNdNCombinations(sides, quantity);
  
  var successes = 0;
  nextCombo: for(var i=0; i<combos.length; i++) {
    var combo = combos[i];
    
    combo.sort();
    for(var j=0; j<combo.length-1; j++) {
      var die1 = combo[j];
     ...