Majority voting: http://programmingpraxis.com/2011/12/16/majority-voting/
module: majority | |
define function winner (votes :: <collection>) | |
let winner | |
= reduce1(method (a, b) if (a.last > b.last) a else b end end, | |
map(method (candidate) | |
pair(candidate, size(choose(curry(\=, candidate), votes))); | |
end, | |
remove-duplicates(votes))); | |
unless (zero?(round/(winner.tail, votes.size))) | |
winner.head; | |
end unless; | |
end function winner; | |
define function print-winner (votes :: <collection>) | |
let winner = winner(votes); | |
if (winner) | |
format-out("The winner is: %s\n", winner); | |
else | |
format-out("There's no winner\n"); | |
end; | |
end function print-winner; | |
define function main() | |
print-winner(#['a', 'b', 'a', 'b', 'a']); | |
print-winner(#['a', 'a', 'a', 'c', 'c', 'b', 'b', 'c', 'c', 'c', 'b', 'c', 'c']); | |
print-winner(#['a', 'b', 'c', 'a', 'b', 'a']); | |
exit-application(0); | |
end function main; | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment