Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Created April 20, 2024 02:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JadenGeller/786203450ad49688f962866f3c4d2866 to your computer and use it in GitHub Desktop.
Save JadenGeller/786203450ad49688f962866f3c4d2866 to your computer and use it in GitHub Desktop.
func apportion(quota: Int, _ population: [Int]) -> [Int] {
var portions = population.map({ $0 / quota })
let errors = population.map({ $0 % quota })
let adjustments = (errors.reduce(0, +) + quota / 2) / quota
errors
.enumerated()
.sorted(by: { $0.element > $1.element })
.prefix(adjustments)
.forEach {
portions[$0.offset] += 1
}
return portions
}
@JadenGeller
Copy link
Author

print(apportion(quota: 100, [125, 25, 45])) // -> [1, 0, 1]
print(apportion(quota: 1000, [5555, 1110])) // -> [6, 1]
print(apportion(quota: 10, [1, 109]))       // -> [0, 11]
print(apportion(quota: 100, [33, 33, 33]))  // -> [1, 0, 0]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment