46.1k views
1 vote
Consider the following scenario. Votes are being cast for a major election, but due to a lackof resources, only one computer is available to count the votes. Furthermore, this computeronly has enough space to store one vote at a time, plus a single extra integer. Each vote is asingle integer 0 or 1, denoting a vote for Candidate A and Candidate B respectively.(a) Come up with an algorithm to determine whether candidate A or B won, or if there wasa tie

1 Answer

6 votes

Step-by-step explanation:

Assuming that a simple majority is sufficient for a win, we can keep track of the difference in the number of votes for the two candidates.

__

1. set the integer to zero

2. while there are votes to count ...

3. increment the integer if the vote is 1, or decrement the integer if the vote is 0

4. end while

5. if the final value of the integer is positive, Candidate B won. If it is zero, there was a tie. If it is negative, Candidate A won.

User Andro Selva
by
6.3k points