Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

243
Vistas
Cómo hacer un generador de ecuaciones básico en Javascript

Hola, en el pasado hice este código de python que genera aleatoriamente una ecuación, toma la entrada del usuario y lo hace por un minuto. Este es el pitón

 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)

Ahora quiero ponerlo en un sitio web en Javascript. Este es el código Javascript que tengo hasta ahora

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

Esto genera aleatoriamente una ecuación. Quisiera ayuda para hacer las otras partes porque no he encontrado la manera de hacer las otras partes Gracias.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Aquí hay un posible boceto para esto. Para mantenerlo simple, uso la consola (y le dejo la interfaz de usuario a usted) y me limito a números < 10. Aún así, debería dar una base.

Por cierto, esa fue una pregunta inesperada, ¡pero divertida de hacer!

 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)

about 4 years ago · Juan Pablo Isaza Denunciar

0

Puede utilizar el método de prompt incorporado del navegador para solicitar la entrada del usuario y luego compararla con la respuesta de la pregunta actual.

Para elegir una pregunta aleatoria, podemos implementar una función de ayuda simple que devuelve un número entre X e Y (inclusive) y luego obtener la pregunta en ese índice.

Aquí una demostración en vivo:

 /** * 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();

Documentos del método Math.random .

Documentos del método Array.prototype.splice .

Espero haberte empujado más lejos, siéntete libre de pedir más aclaraciones o ayuda.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda