roryf
roryf

Reputation: 30160

Algorithm for calculating result of multi-choice quiz

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

Answers (3)

Merlyn Morgan-Graham
Merlyn Morgan-Graham

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:

  • Number of answers, A (or correct A answers)
  • Number of answers, B
  • Number of answers, C
  • Current question index (for use in next three counters)
  • Index of last answer, A (or last correct A answer)
  • Index of last answer, B
  • Index of last answer, C

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

DarkDust
DarkDust

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

brozo
brozo

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

Related Questions