Save function output to array of N?

The following code for a dice roller gets the correct number of dice that have been passed as input to rollTheDice().

What I would like to do from here is create an array of length N containing as many dice rolls as I need, get the sum of that array, and print it to the console.

I was thinking of initializing the array, then using a do/while loop to call randNum & store the result each time. Summing the array would seemingly involve using reduce.

Is there a better/simpler way? All I can say is that I’m really enjoying thinking in terms of functions.

// Roll a six-sided die const randNum = () => Math.floor(Math.random() * 6 + 1); // Return the correct number of items in an array of dice rolls const diceNum = array => array.pop(0) + 1; const rollTheDice = dice => { // Create an array of values up to the input value (representing the number of rolls needed) const diceInHand = Array.from(Array(dice).keys()); // Print the input value of rollTheDice console.log(diceNum(diceInHand)) } rollTheDice(2);

Are you only interested in the sum of N rolls? Are you using two dice or one die?

Are you only interested in the sum of N rolls? Are you using two dice or one die?

Yes – changing the argument for rollTheDice() should give me as many dice rolls as I want, but they are individual rolls, AFAIK.

(I should have said a for loop, though.)

After this, I’m thinking of changing randNum() to allow me to specify how many sides the dice have.

For rolling a single, six-sided die we can write a simple function to loop N times, and add the roll value to a count

const dieTally = function (n, sides=6) {
  tally = 0;
  for (let x of new Array(n)) {
    tally += Math.floor(Math.random() * sides + 1)
  }
  return tally
}

This uses no data structure but for an array with N undefined elements. It’s a cheat method for setting the number of iterations.

sides is defaulted to 6 (the second argument is optional) but could be any number from the set of Platonic Solids, being as they are the only uniform solids with identical sides. So the value would have to be one of, 4, 6, 8, 12, or, 20.

I like it! Certainly more elegant than my idea.

1 Like

Take what you can from it, but keep working on your ideas so they don’t get stifled.

1 Like