0
votes

Transformer des questions statiques dans des questions dynamiques

J'ai des questions statiques telles que ci-dessous. J'utilise ces questions pour mon quiz dans mon blog. XXX

Comment puis-je faire les questions et répondre dynamique? En d'autres termes, chacun des chiffres prendra une valeur comprise entre 1 et 20. La réponse sera calculée sur la base de la question.

merci


0 commentaires

3 Réponses :


1
votes

Vous pouvez utiliser modèle littéral code> et math.random code>

p>

// 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)
}


0 commentaires

1
votes

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);


0 commentaires

1
votes

Je trouve le EXPR-EVAL Paquet pour être très utile pour les cas d'utilisation tels que le vôtre .

Un exemple simplifié: p>

p>

<script src="https://cdnjs.cloudflare.com/ajax/libs/expr-eval/2.0.2/bundle.js"></script>


0 commentaires