I've started building a super basic 'general knowledge quiz' using Javascript... but I am struggling to come up with an efficient way to get a random question excluding previously chosen questions.
At the moment what I have in place is an array called previous_questions which stores the index of questions that have been previous selected, and a while loop which continues to generate a random value for 'r' if the number already exists in the previous_questions array.
var r = Math.floor(Math.random() * questions.length);
while(previous_questions.indexOf(r) >= 0) {
r = Math.floor(Math.random() * questions.length);
}
Whilst this is working at the moment, I can't imagine it's an efficient way of doing it and could potentially cause an infinite loop when there are no questions left to select. What would be a more efficient way of doing this? Thanks in advance!
Aucun commentaire:
Enregistrer un commentaire