I’m struggling with the edge cases of an algorithm for calculating the result of an A, B, C style quiz.
The quiz is made up of an arbitrary number of questions, each having exactly 3 answers corresponding to A, B and C. Each question is displayed on its own with a continue button, once all questions have been answered the result is displayed.
There are 3 possible results, corresponding to A, B and C.
The result displayed should be the answer chosen the most.
If two answers were chosen equally, the result should be which of those answers was chosen last.
It’s the final part that I’m struggling with, what’s the best way to calculate this and what do I need to store during the quiz to do so?
The initial calculation I have is:
if (countA > countB && countA > countC)
{
result = "A";
}
else if (countB > countA && countB > countC)
{
result = "B";
}
else if (countC > countA && countC > countB)
{
result = "C";
}
else
{
// two results are equal
}
What’s the best way to calculate the last case?
You could store all activity (selecting the answers) in a list-like data structure. If the answer is selected you add it to the list, otherwise, you simply remove it from the list. When calculating the last case, go from the back of the list and look for either one of the equally weighted results. The first that is found, was chosen last. Since it was chosen last, it is the result.
Using this method, you could also count all options (A, B and C) by simply counting the occurrences of the options in the list.