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
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.
Why not just shuffle the questions (or create a shuffled copy) and then ask them one by one:
You can use this algorithm to shuffle your array and then iterate through it sequentially.