Search code examples
javascriptarraysparameterscountingcoin-flipping

How do I write a function that prints counts of values in an array, taking the array as a parameter?


Starting with the below program that creates an array of coin flips, I have to add a function that prints out the total number of heads and total number of tails flipped. The function must take the array of flips as a parameter.

This is the given program:

var NUM_FLIPS = 100;

function start(){
    var flips = flipCoins();
    printArray(flips);
    countHeadsAndTails();
}

// This function should flip a coin NUM_FLIPS
// times, and add the result to an array. We
// return the result to the caller.
function flipCoins(){
    var flips = [];
    for(var i = 0; i < NUM_FLIPS; i++){
        if(Randomizer.nextBoolean()){
            flips.push("Heads");
        }else{
            flips.push("Tails");
        }
    }
    return flips;
}

function printArray(arr){
    for(var i = 0; i < arr.length; i++){
        println(i + ": " + arr[i]);
    }
}

And I need to write this function:

function countHeadsAndTails(flips) {
    //Write the program here
}

This is what I have so far, but the function does not work as expected. I am stuck on what to put in the if statement.

function countHeadsAndTails(flips) {        
    var headCount = 0;
    var tailCount = 0;
    for (var i = 0; i < NUM_FLIPS; i++) {
        if (i == "Heads") {
            headCount += 1;
        }else {
            tailCount += 1;
        }
    }

    println("Total Heads: " + headCount);
    println("Total Tails: " + tailCount);
}

The program randomly flips heads or tails 100 times and prints out the results, but the counter does not work and I get this:

Total Heads: 100
Total Tails: 0

Solution

  • The reason if (i == "Heads") { doesn't work is because i is the current index (a number) and you're comparing it to a string "Heads". I suspect what you want is if (flips[i] == "Heads") {. Basically using the index i to grab the ith element in the array and comparing that with "Heads".

    Also the parameter flips is not being passed to countHeadsAndTails() in the start() function. Looks like that might be a problem with the provided problem itself. I assume the countHeadsAndTails stub function they provided already had the flips parameter?