What is the best way to create a function that displays the frequencies of values within an array, where the array is provided as an argument?

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

Answer №1

The issue with the if (i == "Heads") { statement is that it compares the index variable i, which is a number, to the string "Heads". To properly check if the element at position i in the array flips is equal to "Heads", you should use if (flips[i] == "Heads") {.

In addition, it seems like the flips parameter is not being passed to the countHeadsAndTails() function within the start() function. This discrepancy may stem from an oversight in the original problem description. It is assumed that the provided stub function countHeadsAndTails already includes the necessary flips parameter.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to looping through a map arraylist in JavaScript

Here is a sample map arraylist. How can I access this arraylist using JavaScript from within pure HTML? And how can I iterate over this list? <%@page import="org.json.simple.JSONObject"%> <%@page import="org.json.simple.JSONArray"%> <% JSON ...

JavaScript event array

I have a JavaScript array that looks like this: var fruits=['apple','orange','peach','strawberry','mango'] I would like to add an event to these elements that will retrieve varieties from my database. Fo ...

Injecting styles into an iframe using Javascript in a vue.js environment

When working within the admin area of a website builder, I aim to provide users with a visual preview of style changes before they save any updates. To achieve this, I use an iframe to display the user's website, allowing for visual adjustments to be ...

Error message: The specified file or directory named '-stylus' could not be found

Encountered an error message while using stylus with npm on my Linux machine. After installing nodejs from GitHub, I executed the command npm install -g stylus autoprefixer-stylus and received the following error log: npm ERR! Error: EACCES, unlink ' ...

Exploring the integration of Firebase with Next.js using getServerSideProps

I'm trying to retrieve the 'sample' document from Firestore using getServerSideProps only if a user is signed in. However, the current code I have isn't working and just returns 'can't read'. Is there a better solution or ...

I struggled to modify the image cropping code to specify a particular image

(I will attempt to explain my issue once again) I came across a script online which can be viewed at this link : Link However, I am having trouble modifying the code to suit my needs. The script currently starts working on image upload, but I want it t ...

Attempting to insert form information into a database by making an Ajax call with PHP

I am facing issues with adding data to a local database using my form. Here is my addproducts.php page: <?php $title = "Products"; include("Header.php"); include("PHPvalidate.php"); ?> <script src="AjaxProduct.js"></script> <art ...

The setState function in ReactJS seems to be failing to properly update the fields

I am having trouble resetting the value of my input type to empty after storing data from a controlled form element. The first method below is not working for me, even though I'm using setState to clear the input fields. Can someone help me understand ...

What is the best way to identify which JavaScript code is triggering or managing an event?

In the development of an HTML5 application framework designed for businesses to use on their intranet and extranet sites, a SAP JEE application server is utilized. The framework incorporates the grid system known as "Semantic UI" along with various JavaScr ...

TypeORM Error: Trying to access property 'findOne' of an undefined object

I've been working on implementing TypeORM with Typescript, and I have encountered an issue while trying to create a service that extends the TypeORM repository: export class UserService extends Repository<User> { // ... other service methods ...

The system detected a missing Required MultipartFile parameter in the post request

Can anyone explain to me why I am encountering the error mentioned above? I am unable to figure out the reason. Below is my code, please review it and suggest a solution for fixing this error. The objective is to upload multiple files to a specific locatio ...

Meteor powering the user interface, while Express handles the server-side operations on the backend with NodeJS

When designing a website that requires real-time reactivity like Meteor on the frontend, but also needs a job processing backend (such as Kue), it is clear that the frontend app will benefit from Meteor's capabilities. However, the backend processing ...

Creating an HTML layout or template directly within a JavaScript bookmarklet

Currently, I am using a bookmarklet that generates a user interface for interaction. The method I have been using involves creating elements using $('<element>').addClass().css({..});, but this approach is proving to be difficult to maintai ...

traverse a deeply nested object within an array

Currently facing an issue with mapping over an array containing multiple nested objects. The map function seems to only return the outer object when executed. https://i.stack.imgur.com/7JNsN.png const [moreDetails, setMoreDetails] = useState([]); const [d ...

data is currently being uploaded to the storage, however, the grid is not displaying any

After loading JSON data into the store, I am unable to see any data in the grid. Can someone please point out what I might be doing wrong? Here's the code snippet for the grid: { xtype: 'gridpanel', ...

Which is the better approach for performance: querying on parent selectors or appending selectors to all children?

I currently have 2 mirror sections within my DOM, one for delivery and another for pickup. Both of these sections contain identical content structures. Here's an example: <div class="main-section"> <div class="description-content"> ...

Is a referrer included in AJAX requests made from the background page of a Google Chrome Extension?

Can anyone confirm if AJAX requests sent from the background page of my Chrome Extension will include referrer information? I'm wondering about this. Appreciate any insights you can provide! ...

Retrieve the text inputted into a textfield within a dynamic tableview in Swift and store it within an array

Need help retrieving text from a textfield within a dynamic tableview. I have multiple textfields and tried the following code without success. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { ...

Click functionality being incorporated into Material UI

I need assistance with incorporating an onClick event handler in a material ui example, but it doesn't seem to be working as expected. <Tooltip title="Filter list"> <IconButton aria-label="Filter list"> <FilterListIcon/> </ ...

Angular 2 - synchronizing timer for all users

I have developed a timer that needs to function consistently for all users at the same time. To achieve this, I stored the start_time (timestamp when the timer begins) in my database and implemented the following code snippet to calculate the remaining ti ...