Превращение статических вопросов в динамические вопросы - PullRequest
0 голосов
/ 06 октября 2019

У меня есть статические вопросы, такие как ниже. Я использую эти вопросы для своей викторины в своем блоге.

var quiz = {
    "data": [
        {
            "question": "What is 10 + 5 ?",
            "answer": "15",
        },
        {
            "question": "What is 10 - 5 ?",
            "answer": "5",
        },
        {
            "question": "What is 10 + (- 5) ?",
            "answer": "5",
        },
        {
            "question": "What is -10 + 5 ?",
            "answer": "-5",
        },
        {
            "question": "What is -6 + (-6) ?",
            "answer": "-12",
        },
    ]
}

Как я могу сделать вопросы и ответы динамичными? Другими словами, каждое из чисел будет принимать значение от 1 до 20. Ответ будет рассчитываться на основе вопроса.

спасибо

Ответы [ 3 ]

1 голос
/ 06 октября 2019

function generateQuestion(template, min, max){
  // Generate first random number
  var numOne = Math.floor(Math.random() * (max - min) ) + min;
  // Generate second random number
  var numTwo = Math.floor(Math.random() * (max - min) ) + min;
  
  // append first question part
  var question = template[0];
  // check if first number is negative to put brackets around the string
  if(numOne < 0 )
    question += "(" + numOne + ")";
  else
    question +=  numOne;
   
  // append operator
  question += " + ";
  
  // check if second number is negative to put brackets around the string
   if(numTwo < 0 )
    question += "(" + numTwo + ")";
  else
    question +=  numTwo;
    
  // append last part of question
  question += template[1];
    
    
  // return your object
  return {
    question: question, 
    answer: numOne + numTwo
  };
}

var numberOfQuestions = 4;
var questions = [];
for(var i = 0; i < numberOfQuestions; i++)
  questions.push(generateQuestion(["What is ", "?"], -20, 20))
  
  
console.log(questions);
1 голос
/ 06 октября 2019

Я считаю пакет expr-eval весьма полезным для таких случаев использования, как ваш.

Упрощенный пример:

const { Parser } = exprEval;

const randomNumber = (min, max) => Math.floor(Math.random() * max) + min;

const quiz = {
  equation: `${randomNumber(1, 20)} + ${randomNumber(1, 20)}`,

  get question() {
    return `What is ${this.equation.toString()}`;
  },

  get answer() {
    return `The answer is: ${Parser.evaluate(this.equation)} ?‍?`;
  },
};

console.log(quiz.question);
console.log(quiz.answer)
<script src="https://cdnjs.cloudflare.com/ajax/libs/expr-eval/2.0.2/bundle.js"></script>
1 голос
/ 06 октября 2019

Вы можете использовать template literal и Math.random

// define all the airthmeatic operation

let operations = ["+","-","*","/"]

// map airthmeatic sign to related function
let funcs = {
  "+" : (a,b)=> a+b,
  "-" : (a,b)=> a-b,
  "*":  (a,b)=> a*b,
  "/" : (a,b)=> a/b
}

//  function to build random question

let randomQuizBuilder = (a,b,operation) =>{
  let val = prompt(`what is ${a} ${operation} ${b}`) 
  console.log(+val === funcs[operation](a,b))
}

let i=2

// a loop to build a fix number of question
while(i--){
  // get random value in range of 20
  let a = Math.floor(Math.random() * 20)
  let b = Math.floor(Math.random() * 20)
  
  // select a random operation
  let operation =operations[Math.floor(Math.random() * (operations.length))]
  
  // call quizBuilder to build a random question
  randomQuizBuilder(a,b, operation)
}
...