An election is held in school to elect a president for the student council. There are five candidates, each one represented by a number from
1 – 5. Their names are stored in a corresponding array NAMES.
The students vote electronically and the numbers are entered into the collection VOTES. If any candidate gets more than 50% of the votes, that person is elected, otherwise there is a second vote between the two candidates with the highest number of votes.
Write an algorithm in pseudo code to do the following:
- read the values from the collection VOTES
- count the number of votes for each candidate
- output the result
- state the name of the winner or of the two candidates in the next round.
You should use the data structures given and may introduce any others that you think are useful for an efficient solution.
// init array case some candidates receive no votes
Loop N from 0 to 5
RESULTS[N]=0
End loop
//main body
CALL FindWinningCount
CALL ProcessVotes
// output all votes
Loop N from 0 to 5
output NAMES[N] "received ": RESULTS[N]
end loop
If OVER50 then
Output "winner is : NAMES[HIGHSCOREPOS]
else
// output 2 with highest votes for next round
CALL FindOtherCandidate
Output NAMES[HIGHSCOREPOS] " and " NAMES[HIGHSCOREPOS2] " Will proceed to next round
end if
// end main body
// sub process votes and store highest and maybe winner
ProcessVotes
// HIGHSCORE=0
// HIGHSCOREPOS
// OVER50= 0
VOTES.resetNext() // start at beginning
loop while VOTES .hasNext() or OVER50 = 0
STUDENTVOTED = VOTES .getNext()
// store votes in array results need convert candidate number to pos in array so reduce by 1
RESULTS [STUDENTVOTED-1] = RESULTS [STUDENTVOTED-1] + 1
If RESULTS [STUDENTVOTED-1] > HIGHSCORE
HIGHSCOREPOS = STUDENTVOTED-1
HIGHSCORE = RESULTS [STUDENTVOTED-1]
end if
If RESULTS [STUDENTVOTED-1] > HALFVOTES then
OVEVER50 = 1
end if
end loop
// sub to count the total number of students that voted so can check for winner
FindWinningCount
VOTES.resetNext() // start at beginning
loop while VOTES .hasNext()
TOTALNUMVOTES = TOTALNUMVOTES +1
end loop
// find number to win
HALFVOTES = TOTALNUMVOTES / 2 // assume can we use standard operators
// find the second candidate
FindOtherCandidate
HIGHSCOREPOS2 = 0
Loop N from 0 to 5
SCORE = RESULTS[N]
If SCORE > HIGHSCOREPOS2 and N ≠ HIGHSCOREPOS then
HIGHSCOREPOS2 = N
HIGHSCORE2 = SCORE
end if
end loop