Class: Schulze::Ballot
- Inherits:
-
Object
- Object
- Schulze::Ballot
- Defined in:
- lib/schulze/ballot.rb
Class Method Summary collapse
Instance Method Summary collapse
- #add_choice(ordering, name) ⇒ Object
- #candidates ⇒ Object
-
#initialize ⇒ Ballot
constructor
A new instance of Ballot.
- #preference_matrix(all_candidates) ⇒ Object
- #prefers?(a, b) ⇒ Boolean
- #to_s ⇒ Object
Constructor Details
#initialize ⇒ Ballot
Returns a new instance of Ballot.
16 17 18 |
# File 'lib/schulze/ballot.rb', line 16 def initialize @choices = Hash.new(1e9) end |
Class Method Details
.new_from_filename(filename) ⇒ Object
5 6 7 8 9 10 11 12 13 14 |
# File 'lib/schulze/ballot.rb', line 5 def self.new_from_filename filename new.tap do |ballot| File.open(filename, 'r') do |io| io.each_line do |line| chunks = line.split ballot.add_choice(chunks.first.to_i, chunks.last) end end end end |
Instance Method Details
#add_choice(ordering, name) ⇒ Object
20 21 22 |
# File 'lib/schulze/ballot.rb', line 20 def add_choice ordering, name @choices[name] = ordering end |
#candidates ⇒ Object
24 25 26 |
# File 'lib/schulze/ballot.rb', line 24 def candidates @choices.keys end |
#preference_matrix(all_candidates) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/schulze/ballot.rb', line 28 def preference_matrix all_candidates matrix = Matrix.zero(all_candidates.size) Matrix.build(all_candidates.size) do |row, col| if row == col 0 else a, b = all_candidates[row], all_candidates[col] prefers?(a, b) ? 1 : 0 end end end |
#prefers?(a, b) ⇒ Boolean
40 41 42 |
# File 'lib/schulze/ballot.rb', line 40 def prefers? a, b @choices[a] < @choices[b] end |
#to_s ⇒ Object
44 45 46 |
# File 'lib/schulze/ballot.rb', line 44 def to_s "Ballot:\n" + @choices.to_a.map(&:inspect).join("\n") end |