Editor

Vote Percentages That Add Up

#621 · Math · Advanced · Review the AI's code · 130 XP · about 20 min

Someone asked an AI assistant: "Write a function that turns vote counts into whole-number percentages that add up to exactly 100, using the largest remainder method. Ties should go to the earlier option." This is its answer. It looks right, but it has a bug.

percentages(votes) takes a list of vote counts and returns a list of whole-number percentages, one per option, that add up to exactly 100. The largest remainder method works like this:

  • Work out each option's exact share, votes * 100 / total, and give it the whole-number part of that share.
  • That leaves a few points over. Hand them out one each to the options with the largest fractional parts.
  • When two options have exactly the same fractional part, the option earlier in the list gets its point first.

Examples

percentages([1, 1, 1])  # returns [34, 33, 33]
percentages([2, 1, 1])  # returns [50, 25, 25]
percentages([1, 2])     # returns [33, 67]

In the first example each option's share is 33 and one third, so all three fractional parts are equal. One point is left over, and it goes to the first option.

Constraints

  • votes has 1 to 50 whole numbers from 0 to 10**6, and at least one of them is above 0.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.