1

So it seems that count[whatever] returns NaN for some reason. Why?

  var i;
  var count = new Array(12);
  for( i = 0; i<999;i++)
   {
     var firstDice = Math.floor(Math.random() * 7);
     var secondDice= Math.floor(Math.random() * 7);
     var total = firstDice + secondDice;
     count[total]++;
   }

   console.log(count[3]);
   for(index=2; index<=12; index++)
   {
     console.log("EL NUMERO "+index+" SALIO "+ count[index]+" VECES MIVIVI");
   }
sanduniYW
  • 723
  • 11
  • 19
Pkochar
  • 21
  • 2

2 Answers2

2

You are not initializing the array, do:

var count = Array.from({ length: 13 }, () => 0);

or

var count = new Array(13).fill(0);

as suggested in the comments by @ibrahim-mahrir.

Also note that you need 13 elements, not 12 (0, 1, 2 ... 12).

const count = Array.from({ length: 12 }, () => 0);

for(let i = 0; i<999;i++) {
    const firstDice = Math.floor(Math.random() * 7);
    const secondDice= Math.floor(Math.random() * 7);
    const total = firstDice + secondDice;
    count[total]++;
}

console.log(count[3]);

for(let index=2; index<=12; index++) {
  console.log("EL NUMERO "+index+" SALIO "+ count[index]+" VECES MIVIVI");
}

This because when you use new Array(12); you are creating an array of undefined, so when you do ++ on an undefined value you still have an undefined value.

rpadovani
  • 7,101
  • 2
  • 31
  • 50
  • 2
    You can also use `fill` which is simpler: `new Array(12).fill(0);` – ibrahim mahrir Aug 25 '18 at 18:07
  • ... also `count.length` should be 13 not 12. – ibrahim mahrir Aug 25 '18 at 18:08
  • ... one last thing, there won't be a 1000 samples in the resulting array due to the loss of some of them as `0` and `1` sums due to the way OP is using `random`. In other words, `count[0]` and `count[1]` will have some samples reserved to them and OP doesn't even need them. Sorry for any annoyance caused by my comments! – ibrahim mahrir Aug 25 '18 at 18:15
2

You could take an array with 13 elements, because you have thirteen indices. Then you have to take the values 1 ... 6 as random number for a dice side.

var i,
    count = Array.from({ length: 13 }, _ => 0),
    firstDice, secondDice, total;

for (i = 0; i < 999; i++) {
    firstDice = Math.floor(Math.random() * 6 + 1);
    secondDice = Math.floor(Math.random() * 6 + 1);
    total = firstDice + secondDice;
    count[total]++;
}
console.log(count[3]);

for (i = 2; i <= 12; i++) {
    console.log("EL NUMERO " + i + " SALIO " + count[i] + " VECES MIVIVI");
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • The die roll calculation is the right way - note the `+ 1`. This accounts for the possibility of `Math.random()` generating zero and will never generate one.; random's range is from zero (inclusive) to one (not inclusive) - written as `[0,1)`. [see this SO](https://stackoverflow.com/a/4396303/463206) – radarbob Aug 25 '18 at 18:23