Generate an array containing 20 randomly generated math equations stored as objects using JavaScript

Reference Image

My current task involves dynamically generating 20 math problems. These problems need to be stored as objects in an array before being displayed. I am facing a challenge in creating 20 unique random equations as objects and then calling them into a table. Below is the progress I have made so far.

<script>

    // Generate random numbers between 1-100
var randNum1 = Math.floor(Math.random() * 100) + 1;
var randNum2 = Math.floor(Math.random() * 100) + 1;

// Select a random operator
var op = ["*", "+", "/", "-"][Math.floor(Math.random() * 4)];

// Create an array of math problems objects
var problemList = [{number1: randNum1, operator: op, number2: randNum2}];

var problems, i;

// Function to display math problems in a table
var displayProblems = function (problems) {
    var str = "<table class=table>";

    for (i = 0; i < problems.length; i++) {
        str += "<tr>";
        str += "<td>" + problems[i].number1 + " " + problems[i].operator + " " + problems[i].number2 + " " + "<input type='text' class='answer' id='answer_" + i + "' /></td>";
        str += "</tr>";
    }

    str += "</table>";

    document.getElementById("mathGrid").innerHTML = str;
};

window.onload =function () {
    displayProblems(problemList);
};

</script>

I have spent hours trying to solve this problem but seem to be stuck. This assignment is challenging for me as it's only my second attempt at working with JavaScript. Any assistance or guidance would be highly appreciated.

To see an example of my work in action, you can visit this JS Fiddle link.

Answer №1

When faced with a problem like this, the first step would be to simplify it.

One way to approach this is by creating a function that generates a single random problem:

function createRandomProblem() {
    // generate random numbers from 1-100
    var num1 = Math.floor(Math.random() * 100) + 1;
    var num2 = Math.floor(Math.random() * 100) + 1;

    // choose a random operator
    var operator = ["*", "+", "/", "-"][Math.floor(Math.random() * 4)];

    return {number1: num1, operator: operator, number2: num2};
}

Once the function is in place, testing it to ensure functionality is crucial.

Creating multiple problems becomes easier afterwards - simply calling the function multiple times and storing the results in an array. This can be done manually:

var problems = [
    createRandomProblem(),
    createRandomProblem(),
    createRandomProblem()
    ...
];

Alternatively, a loop can be used for efficiency:

var problems = [];
while (problems.length < 20) {
    problems.push(createRandomProblem());
}

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

Enhancing Your Model with Additional Details using Angular Formly

I have been utilizing Angular Formly to display forms generated from the JSON response received from services. However, I have a few inquiries. Is it feasible to retrieve data in a field (templateOptions.label, for instance) to include in the model? ...

Utilize absolute positioning within Three.js to ensure that all objects are anchored at the 0,0,0 coordinate point

I am facing an issue where the solutions provided do not seem to work for me as I am new to Three.js. In my scene, I have several objects such as a map with each region represented by a separate object positioned on a plane. Here is an image of my setup: ...

Ways to incorporate encoded HTML text into string literals

When attempting to insert a HTML encoded special character within a string literal, I am encountering an issue where it does not display as intended in the final document. The approach I am taking is as follows: const head = { title: `${ApplicationName} ...

Using jQuery to trigger several setTimeout() functions in succession

I'm struggling to grasp the concept of jQuery promises. To delve into this topic, I have put together the following code snippet inspired by a discussion on StackOverflow. let functions = [ function () { setTimeout(function () { console.log("func ...

Node.js encountered an error: Address already in use. The specified port 8080 is currently being utilized by another application

My application was not functioning properly, and upon running the command "npm start", an error was thrown: Error: listen EADDRINUSE: address already in use :8080 Even after restarting my EC2 instance and attempting the command again, I encount ...

Use an Ajax call to "POST" and fetch the Jade layout for rendering

So, I have my own custom AJAX function. export function dynamicURL(obj) { $.ajax({ url: obj.url, type: 'post', data: obj.jade, dataType: 'JSON' }).done(function (ajaxReturn) { console.lo ...

Is the eval() function initially used to directly translate the evaluated string?

Try running this code snippet in your browser: eval("(function() { console.log(JSON.parse('" + JSON.stringify('THIS IS COOL') + "')); })()"); It will output THIS IS COOL, however, if you run the following: eval("(function() { console ...

Developing a function that can handle an array containing interface instances

Hey there, I've encountered a bit of a puzzle with this assignment. The first part was all good; creating an interface and using it in different classes. But now I'm stuck on the second part which seems to be throwing me off with its logic. It al ...

What is preventing access to the global scope in this particular situation?

Recently, I encountered a problem where I was able to pass through the issue but couldn't fully grasp the concept behind it. If you run the code snippet provided, you'll see what's happening. Can someone clarify this for me? function fu ...

Retrieving a collection of names from the properties of a specific type

Looking to replicate the properties and values of a custom type in an object: type MyType = { propA: string; propB: string; propC: string; } const obj = { propA: "propA", propB: "propB", propC: "propC", } A type ...

What is causing an empty box to appear due to padding? Is there a way to conceal it

There seems to be an issue with adding padding to the results id div box. The padding is causing a blank yellow box to appear at the bottom before any results are submitted. I've tried to hide this box without success by adding a displayResult() funct ...

Using JavaScript, reload the page once the data has been retrieved from an Excel spreadsheet

I'm facing an issue with my JavaScript code. Here's what I have: a = Excel.Workbooks.open("C:/work/ind12.xls").ActiveSheet.Cells.find("value"); if(a == null) document.getElementById('dateV ...

JavaScript JCrop feature that allows users to resize images without cropping

I'm currently attempting to utilize JCrop for image cropping, but I'm running into frustratingly incorrect results without understanding why. The process involves an image uploader where selecting an image triggers a JavaScript function that upda ...

unable to modify the content of a

I need assistance with a javascript function that dynamically creates panels using an ajax request. Once the request returns valid json data, I populate all the widgets as follows: function createAllWidgets() { var funcid = 'get_widget_info' ...

Creating visual representations of class, organization, flow, or state diagrams using Vega or Vega-lite

I'm struggling to find an example of a state, class, flow chart, or org chart diagram created with Vega. Are there any available online? Vega seems like the perfect tool for this type of visualization, although it may be a bit complex. Without a star ...

Creating a video game HUD effect using JavaScript and HTML5

In an attempt to recreate a video game HUD using HTML5, I have styled a div with CSS properties to resemble a game overlay. When a navigation link is clicked, the div should transition from a hidden state (display:none), then flash twice rapidly before fad ...

Issues encountered when trying to retrieve data from an Express server

I have set up a NodeJS server with Express.js and I am attempting to send a request to it using fetch. fetch("http://localhost:3001/api", { method: "POST", headers: { "Content-Type": "application/json", ...

What is the best way to use a regex to filter the user's input in a Vuetify combobox and generate a chip?

I am working on implementing a restriction for a specific regex pattern while the user types in a combobox to add new chips, such as allowing only phone number chips. Complete Vue Source code: https://codesandbox.io/s/chips-so-0gp7g?file=/src/domains/ex ...

Is it unnecessary to mention both JavaScript and AJAX together?

During a recent conversation I had, someone mentioned that it is inaccurate to state that since Ajax is JavaScript. The scenario was: "How can I perform an action on a webpage without requiring a page refresh?" My response: "Utilize JavaScript along wi ...

How can I create an array of pointers that are already set to point to specific strings?

Does anyone know how to initialize an array of pointers with predetermined pointers to strings? I would appreciate it if someone could help me with this and explain the logic behind it. Thank you in advance for your assistance. char *str1 = NULL, *str2 = ...