Home > database >  How to make a basic equation generator in Javascript
How to make a basic equation generator in Javascript

Time:04-03

Hello in the past I made this python code that randomly generates an equation takes the user's input and does it for a minute. This is the Python

import random 
import time 
correct=0 
wrong=0 
def random_problem(num_operations):
  eq = str(random.randint(1, 100))
  for _ in range(num_operations):
    eq  = random.choice([" "])
    eq  = str(random.randint(1, 100))
  return eq 
start = time.time()
while True:
  elapsed = time.time() - start
  if elapsed > 60: 
    total_questions=correct wrong
    print(correct,"Correct",wrong,"Wrong,",total_questions," total questions") 
    break
  problem = random_problem(1) 
  ask=int(input(problem  ": ")) 
  solution = eval(problem)
  if ask == solution: 
    correct=correct 1
    print("Correct")
  else:
    wrong=wrong 1
    print("Wrong, the correct answer is",solution)

Now I want to put it on a website in Javascript. This is the Javascript code the I have so far

function getRandomInt(max) {
  return Math.floor(Math.random() * max);
}

return(getRandomInt(10));

This randomly generates an equation. I would like help doing the other parts because I have not found a way to do the other parts Thanks.

CodePudding user response:

Here is a possible sketch for this. To keep it simple, I use the console (and leave the UI to you) and I limit to numbers < 10. Still, it should give a base.

By the way, that was an unexpected question, but fun to do!

const duration = 60000
const end = Date.now() duration

let correct = 0
let error = 0
let result=-1

function ask() {
  const op1 = Math.floor(Math.random()*5)
  const op2 = Math.floor(Math.random()*5)
  result = op1   op2
  
  console.log(`${op1}   ${op2} = ?`);
}

function handler(evt) {
  response = Number(evt.key)
  if(isNaN(response)) return;
  
  if (response == result) {
    correct  
    console.log("correct!")
    if (Date.now()<end) ask()
  }
  
  else {
    error  
    console.log("wrong :(")
  }
}

document.addEventListener("keyup", handler)

ask()

setTimeout(()=>{
  console.log(`${correct} correct and ${error} error`)
  document.removeEventListener("keyup", handler)
}, duration)

CodePudding user response:

You may use the browser's built-in prompt method to ask for user input and then check it against the current question's answer.

To pick a random question, we can implement a simple helper function that returns a number between X and Y (inclusive) and then get the question at that index.

Here a live demo:

/** 
 * an array containing some samples of questions.
 * a question is an Object composed of : 
 *   - a "text" attribute: holds the text that should be shown to the user.
 *   - an "answer" attribute: holds the correct answer of the question (btw, JavaScript has an "eval" method but its use is really not recommended).
 */
const questions = [{
      text: "5   3 = ?",
      answer: 8
    },
    {
      text: "(5   3) * 4 / 2 = ?",
      answer: 16
    },
    {
      text: "1   1 = ?",
      answer: 2
    }
  ],
  // generates a random number betwen "min" and "max" (inclusive).
  randomBetween = (min, max) => {
    // if min is greater than max, just swap "min" and "max" values. 
    min > max && ((min  = max), (max = min - max), (min -= max));
    // return a random number.
    return Math.floor(Math.random() * (max - min   1)   min);
  },
  // the "game" function is where the code related to the guessing game will be executed.
  game = () => {
    // clone the questions so we keep the original copy of the questions as we'll remove every asked question along the way.
    const questionsClone = questions.map(q => ({ ...q
      })),
      // an Object that tracks the correct and wrong user choices.
      answers = {
        correct: 0,
        wrong: 0
      },
      // the game start timestamp (in milliseconds)
      start = Date.now();

    // holds the current question on each loop iteration
    let q;

    while (questionsClone.length) {
      // if a minute has passed since the game start, end the game
      if (Date.now() - start > 60000) break;
      
      // pick a random question and remove it from the cloned question array.
      q = questionsClone.splice(
        randomBetween(0, questionsClone.length - 1),
        1
      )[0];

      // track correct and wrong answers
      if (q.answer == prompt(q.text)) {
        answers.correct  ;
        alert("Correct!");
      } else {
        answers.wrong  ;
        alert("Wrong, the correct answer is "   q.answer);
      }
    }

    // display the game result
    alert(
      "Correct: "  
      answers.correct  
      ", Wrong: "  
      answers.wrong  
      ", Total questions: "  
      (answers.correct   answers.wrong)
    );
  };

// start the game
game();

Math.random method docs.

Array.prototype.splice method docs.

Hope i have pushed you further, feel free to ask for more clarifications or assistance.

  • Related