Condorcet methods determine all candidates before tallying, in case of
[rubyvote] / lib / rubyvote / positional.rb
1 # election library -- a ruby library for elections
2 # copyright © 2005 MIT Media Lab and Benjamin Mako Hill
3
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 2 of the License, or
7 # (at your option) any later version.
8
9 # This program is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 # General Public License for more details.
13
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17 # 02110-1301, USA.
18
19 #################################################################
20 ## ==== positional.rb ====
21 ##
22 ## This file contains positional election methods. Currently only
23 ## includes an implementation of the Borda count election method.
24 #################################################################
25
26 ##################################################################
27 ## BordaVote and BordaResult Classes
28 ##
29 ## These classes inherit from and/or are modeled after the classes in
30 ## election.rb and condorcet.rb
31
32 class BordaVote < ElectionVote
33
34   def initialize(votes=nil)
35     @candidates = Array.new
36     votes.each do |vote|
37       @candidates = vote.uniq if vote.uniq.length > candidates.length
38     end
39     super(votes)
40   end
41
42   def tally_vote(vote)
43     points = candidates.length - 1
44     vote.each do |candidate|
45       @votes[candidate] = points
46       points -= 1
47     end
48   end
49
50   def verify_vote(vote=nil)
51     vote.instance_of?( Array ) and
52       vote == vote.uniq
53   end
54
55   def result
56     BordaResult.new(self)
57   end
58 end
59
60 class BordaResult < ElectionResult
61   def initialize(voteobj=nil)
62     super(voteobj)
63     votes = @election.votes
64
65     @ranked_candidates = votes.sort do |a, b|
66       b[1] <=> a[1]
67     end.collect {|i| i[0]}
68
69     @winners = @ranked_candidates.find_all do |i|
70       votes[i] == votes[@ranked_candidates[0]]
71     end
72   end
73
74 end

Benjamin Mako Hill || Want to submit a patch?