Class: Meekster::Election

Inherits:
Object
  • Object
show all
Defined in:
lib/meekster/election.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parameters = {}) ⇒ Election

Returns a new instance of Election.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/meekster/election.rb', line 7

def initialize(parameters={})
  if parameters[:ballot_file]
    bf = parameters[:ballot_file]
    bf.read! unless bf.read?
    self.ballots = bf.ballots
    self.candidates = bf.candidates
    self.seats = bf.seats
  end
  if parameters[:ballots]
    self.ballots = parameters[:ballots]
  end
  if parameters[:candidates]
    self.candidates = parameters[:candidates]
  end
  if parameters[:seats]
    self.seats = parameters[:seats]
  end
end

Instance Attribute Details

#ballotsObject

Returns the value of attribute ballots.



5
6
7
# File 'lib/meekster/election.rb', line 5

def ballots
  @ballots
end

#candidatesObject

Returns the value of attribute candidates.



5
6
7
# File 'lib/meekster/election.rb', line 5

def candidates
  @candidates
end

#seatsObject

Returns the value of attribute seats.



5
6
7
# File 'lib/meekster/election.rb', line 5

def seats
  @seats
end

Instance Method Details

#resultsObject



72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/meekster/election.rb', line 72

def results
  output = ""
  elected_candidates = candidates.select{|c| c.state == :elected}.sort{|a, b| a.votes <=> b.votes}
  defeated_candidates = candidates.select{|c| c.state == :defeated}.sort{|a, b| a.name <=> b.name}

  elected_candidates.each do |ec|
    output << "Elected: #{ec.name} (#{ec.votes.to_f})\n"
  end
  output << "Defeated: "
  output << defeated_candidates.map{|dc| dc.name}.join(', ')
  output << "\n"
  output
end

#run!Object

Raises:

  • (RuntimeError)


28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/meekster/election.rb', line 28

def run!
  raise RuntimeError, "ballots not found" unless ballots
  raise RuntimeError, "candidates not found" unless candidates
  raise RuntimeError, "seats not found" unless seats

  candidates.each do |candidate|
    candidate.state = :hopeful
  end

  @omega = BigDecimal("0.000001")

  @rounds = []

  while true do

    round = Meekster::Round.new(
      :ballots => ballots,
      :candidates => candidates,
      :seats => seats,
      :omega => @omega
    )

    round.run!

    break if round.count_complete?

    @rounds.push(round)
  end

  elected_candidates_count = candidates.select{|c| c.state == :elected}.length
  hopeful_candidates = candidates.select{|c| c.state == :hopeful}
  if elected_candidates_count < seats
    hopeful_candidates.each do |hopeful_candidate|
      hopeful_candidate.state = :elected
    end
  else
    hopeful_candidates.each do |hopeful_candidate|
      hopeful_candidate.state = :defeated
    end
  end

  candidates
end