Skip to content

Instantly share code, notes, and snippets.

@BDF
Last active October 26, 2022 19:20
Show Gist options
  • Save BDF/73c6f512baeeafb13745be4760207996 to your computer and use it in GitHub Desktop.
Save BDF/73c6f512baeeafb13745be4760207996 to your computer and use it in GitHub Desktop.
Random Number Generator for 3d6 or any number of dice for a given sided dice.
// Random number from 1 to numberOfSides.
function dx(numberOfSides) {
return Math.floor(Math.random() * numberOfSides + 1);
}
let xDy = (n, f) => { let x = 0; while(n-- > 0) x += dx(f); return x};
// usage: numDiceSideDrop(4,6,1)
// examples:
// numDiceSideDrop(4,6,1) Roll four six sided dice and drop the lowest die:
// numDiceSideDrop(2,6,0,6) Roll 2 six sided dice and add 6. (2d6+6)
function numDiceSidesDrop(numberOfDice, sides, dropLowest = 0, flatAdd = 0) {
const arr = new Array(numberOfDice).fill(numberOfDice).map(() => dx(sides));
if (dropLowest > 0) {
arr.sort((a,b) => (b - a)).length = (numberOfDice - dropLowest);
}
const tot = arr.reduce( (a, b) => (a + b) );
return tot + flatAdd;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment