Skip to content

Instantly share code, notes, and snippets.

@kejadlen
Created May 29, 2018 01:56
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 kejadlen/f2f69e6c50a7cbf141c5717172210f78 to your computer and use it in GitHub Desktop.
Save kejadlen/f2f69e6c50a7cbf141c5717172210f78 to your computer and use it in GitHub Desktop.
❯ ruby irv.rb
{:rain=>7, :women=>5, :islands=>4, :trees=>6, :salmon=>9, :parks=>5}
Eliminating: [:islands]
{:rain=>8, :women=>5, :parks=>6, :trees=>6, :salmon=>11}
Eliminating: [:women]
{:rain=>9, :parks=>6, :trees=>7, :salmon=>14}
Eliminating: [:parks]
{:rain=>10, :trees=>10, :salmon=>16}
Eliminating: [:rain, :trees]
Winner: salmon
require "set"
class Election
def initialize(ballots)
@eliminated = Set.new
@ballots = ballots
end
def run
while winner.nil?
p count
eliminate!
end
puts "Winner: #{winner}"
end
private
def winner
count.find {|_,v| v > (0.5 * @ballots.size) }&.first
end
def eliminate!
min = count.map(&:last).min
last_place = count.select {|_,v| v == min }.map(&:first)
puts "Eliminating: #{last_place.inspect}"
@eliminated = @eliminated.merge(last_place)
end
def count
@ballots.map {|ballot| ballot - @eliminated.to_a }.map(&:first).each.with_object(Hash.new(0)) {|ballot, h| h[ballot] += 1 }
end
end
candidates = %i[ salmon islands rain trees parks women ]
ballots = DATA.read.split("\n").map {|row| row.split("\t").map(&:to_i).zip(candidates).sort.map(&:last) }
Election.new(ballots).run
__END__
3 5 1 2 6 4
5 4 2 6 3 1
5 3 1 2 4 6
5 1 6 4 2 3
2 3 5 1 4 6
6 3 2 1 5 4
1 2 6 4 3 5
1 3 6 4 2 5
2 6 4 1 5 3
5 3 6 4 1 2
1 2 4 5 3 6
2 6 4 5 3 1
2 1 6 3 4 5
4 3 1 2 5 6
6 5 1 2 4 3
1 4 2 5 6 3
1 5 6 2 3 4
3 5 1 4 2 6
1 3 6 5 4 2
4 5 2 1 6 3
1 4 6 2 5 3
2 4 5 3 1 6
5 3 4 6 1 2
2 4 6 5 3 1
1 2 6 4 3 5
6 3 4 2 1 5
5 4 6 1 3 2
5 3 1 6 2 4
2 1 5 3 4 6
3 4 6 2 5 1
2 3 5 4 6 1
1 3 6 4 2 5
2 3 4 1 6 5
4 2 1 3 6 5
3 2 6 4 1 5
4 1 2 5 3 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment