How to optimize search of unasked questions?

67 Views Asked by At

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

There are 3 best solutions below

0
Naren Murali On

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

1
Thomas On

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

1
Akeel Ahmed Qureshi On

"You can try this code"

var questions = ['1', '2', '3', '4', ..., 'n'];
var qAsked = qAsked || [];

if (qAsked.length < questions.length) {

    var availableQuestions = questions.filter(function(_, index) {
        return qAsked.indexOf(index) === -1;
    });

    if (availableQuestions.length > 0) {
        var qIndex = Math.floor(Math.random() * availableQuestions.length);
        var selectedQuestionIndex = availableQuestions[qIndex];
        
        qAsked.push(selectedQuestionIndex);

        // Access the selected question
        var q = questions[selectedQuestionIndex];
    } else {
        console.log("All questions have been asked.");
    }
} else {
    console.log("All questions have been asked.");
}