skip to Main Content

Currently I have the following code –

var questions = ['1', '2', '3', '4', ..., 'n'];
var qAsked = []; // array of indexes of already asked questions

//  the code below is executed multiple times
if (typeof $qAsked == "undefined") || ($qAsked.length < $questions.length) { // if not all questions asked

    // the code below looks for questions, which were NOT asked before
    var qCount = $questions.length-1;
    var qIndex = Math.floor(Math.random() * qCount);

    while ($qAsked[$category].indexOf(qIndex) > -1) { // avoid repeated questions
      qIndex = Math.floor(Math.random() * qCount);
    }
    qAsked.push(qIndex);
    q = $questions[qIndex];
 }

The array contains ~150 elements, but executions of the code takes a lot of time.
Is there any way to optimize this code?

3

Answers


  1. Splice the original array and get the desired output, if you dont want to touch the original array, just destructure it into a new array.

    var questions = ['1', '2', '3', '4', '5', 'n'];
    
    const askQuestion = () => {
      if(!questions.length) {
        return 'out of questions!';
      }
      const index = Math.floor(getRandomInt(0, questions.length));
      return questions.splice(index,1)[0];
    }
    
    function getRandomInt(min, max) {
      min = Math.ceil(min);
      max = Math.floor(max);
      return Math.floor(Math.random() * (max - min) + min); 
    }
    
    console.log(askQuestion());
    console.log(askQuestion());
    console.log(askQuestion());
    console.log(askQuestion());
    console.log(askQuestion());
    console.log(askQuestion());
    console.log(askQuestion());
    Login or Signup to reply.
  2. Why not just shuffle the questions (or create a shuffled copy) and then ask them one by one:

    var questions = ['1', '2', '3', '4', '5', 'n'];
    var shuffledQuerytions = shuffle(questions.slice());
    
    function shuffle(array) {
      for (let i = array.length, j, tmp; i > 1;) {
        j = Math.floor(Math.random() * i--);
        tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
      }
      return array;
    }
    
    for (const q of shuffledQuerytions) {
      console.log(q);
    }
    Login or Signup to reply.
  3. You can use this algorithm to shuffle your array and then iterate through it sequentially.

    function shuffleArray(array) {
        for (var i = array.length - 1; i > 0; i--) {
            var j = Math.floor(Math.random() * (i + 1));
            var temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
    }
    
    shuffleArray(questions);
    
    var qIndex = 0;
    var q = questions[qIndex];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search