Search code examples
javascriptloopsassociative-arraycoin-flipping

JavaScript: How To Count Total Number Of Heads and Tails In Random Coin Flip Within Associative Array?


I have an array that has two other associative arrays within it:

 var coinToss = [];

 coinToss["FlipNumber"]; coinToss["Result"];

I already have the randomizer function working and everything. I just need help on totaling the sum of all 'heads' and 'tails'.

I tried doing:

 for (var i = 0; i < coinToss.length; i++)
 {
      var headCount = 0, tailCount = 0;

      if (coinToss["Result"] === 'heads')
            headCount++;
      else
            tailCount++;
 }
 document.getElementByID.innerHTML += "Heads: " + headCount + " " + "Tails: " + tailCount + "<br>";

But it only prints out each separate results such as, for example for 5 coin flips:

 //*Heads: 1   Tails: 0 *
 //*Heads: 1   Tails: 0 *
 //*Heads: 0   Tails: 1 *
 //*Heads: 1   Tails: 0 *
 //*Heads: 0   Tails: 0 *

What I want is to add up all the 'heads' and add up all the 'tails' separately. How come it resets back to 0 every time the loop reiterates?

EDIT as requested:

 function coinFlip() {
        return (Math.floor(Math.random() * 2) === 0) ? 'heads' : 'tails';
 }

 for (var x = 0; x < 6 (/*i.e. number of coin toss*/); x++)
 {
     var coinToss = [];
     coinToss["flipNumber"] = /*varies by user input*/;
     coinToss["Result"] = (coinFlip());

     /*a print code that prints Flip Number: () and Result: ()*/
 }

Solution

  • This should get you started:

    // Make sure you're declaring your variables outside of the for loop:
    
    // I'm not sure what your actual array looks like, but let's say it looks something like this:
    var arr = [0, 0, 1, 1, 1, 0, 1, 0, 1];
    arr["Result"] = "heads";
    var headCount = 0, tailCount = 0;
    
    for (var i = 0; i < arr.length; i++) {
        if (arr["Result"] === "heads")
            headCount += arr[i];
        else
            tailCount += arr[i];
    }
    console.log("Heads: " + headCount + " " + "Tails: " + tailCount);