Reputation: 30160
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?
Upvotes: 1
Views: 517
Reputation: 59111
The question you posed does not seem to take into account whether the answer is correct or not. Either way, you can keep 7 counters:
For each question, you increment the "Current question index". If you care if the answer is correct, only do the following steps when it is correct. If you don't care, always do the following steps.
If the answer A is given, increment the "Number of answers, A" counter, and set the value of "Index of last answer, A".
When you hit the end of your quiz, you will have plenty of data to construct the correct response.
Upvotes: 3
Reputation: 92336
An idea might be to introduce an array or 3 ints, each element corresponding to A, B or C. I assume each question has a number. Each time a question is answered you store the question number in that array. Then you just need to iterate over the array and look which element has the highest number, i.e. was given last.
Upvotes: 0
Reputation: 596
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.
Upvotes: 1