Within the provided program that generates an array of coin flips, there is a requirement to incorporate a function that calculates and prints the total number of heads and tails flipped. This particular function should receive the array of flips as input.
The original program is outlined below:
var NUM_FLIPS = 100;
function start(){
var flips = flipCoins();
printArray(flips);
countHeadsAndTails();
}
// The purpose of this function is to simulate flipping a coin
// for NUM_FLIPS times and storing the outcomes in an array.
// The ultimate result is then returned.
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]);
}
}
The task at hand is to implement the following function:
function countHeadsAndTails(flips) {
// Implement the logic here
}
Currently, here's what has been attempted, but the functioning of the program is not accurate. There seems to be confusion on what should be included within 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 existing code conducts random coin flips of either heads or tails a total of 100 times and displays the results. However, the current tallying mechanism fails to deliver expected results showing:
Total Heads: 100
Total Tails: 0