skip to Main Content

im selecting a statement from a json file, but the one i get is done by a randome number, but i want to avoid getting the same one consecutive times, is there a way to limit this?

Right now this is the code i have for that part, it gives me a random question beetween the amounth of questions i have

        const json = JSON.parse(fs.readFileSync('quiz.json'));
        const quizNum =  Math.floor(Math.random() * 22);

i was thinking something to avoid getting the same question if it was given in the last 2 or 3 times

2

Answers


  1. I would do an array to keep track of the recent questions and adjust with a variable the length of that array

    const recentQuestions = []
    const maxRecentQuestions = 3
    

    and then do a function that will check if the new question is in the array of recentQuestions

    and if yes, proceed by doing a

    recentQuestions.shift()
    

    to remove the oldest question in recentQuestions

    and push the new question with a

    recentQuestions.push(newQuestion)
    
    Login or Signup to reply.
  2. Here is a working snippet, demonstrating how you can pick some random questions, based on a shuffled index array:

    function shfl(a){ // Durstenfeld shuffle
     for(let j,i=a.length;i>1;){
      j=Math.floor(Math.random()*i--);
      if (i!=j) [a[i],a[j]]=[a[j],a[i]]
     }
     return a
    }
    
    // define a questions array named quiz:
    const quiz=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q"]; // 17 elements ...
    // instead of shuffling the array itself I am generating
    // an index array which I will use for picking "random" questions:
    const idx=shfl(quiz.map((_,i)=>i));
    // ... and now I will pick some 5 non-repeating random questions:
    console.log(idx.slice(0,5).map(i=>quiz[i]));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search