Recently, on a project, I was tasked with the responsibility of randomizing an array of questions and the array of answers available for each question. At first, this sounded like a fairly simple task, but I soon discovered that it was a bit more involved.
First, the content:
My first guess at dealing with this was to loop through the array of questions via a function along with applying some
Math.random() to each array index then assigning those to a new array. This was a step in the right direction but there was a key component I was missing. After some research, I discovered the extremely useful Fisher–Yates Shuffle which “is an algorithm for generating a random permutation of a finite set—in plain terms, the algorithm shuffles the set”. Using this algorithm, we can create this function
and pass in our array of questions to algorithmically shuffle them. This works really well, but we still have the problem of shuffling the answers associated with each question. To solve this, we can use a good ol’ for loop on our
shuffledQuestions and apply our shuffle function to the answers of each question.
This all makes for a great dynamic and unpredictable set of questions and answers useable for a quiz.