Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env ruby
- #
- # A simple parser for parsing King County, WA vote results
- PARTIES = {
- "Dem" => "Democratic Party",
- "DPC" => "Democratic Party",
- "Rep" => "Republican Party",
- "RPC" => "Republican Party",
- "NOP" => "NOP",
- "Ref" => "Reform Party",
- "I" => "Independent",
- "INO" => "Independent",
- "IDM" => "Independent",
- "G" => "Green Party",
- "CTT" => "Centrist Party",
- "PFX" => "Problemfixer Party"
- }
- class Candidate
- attr_accessor :id, :name, :votes
- def initialize(id, name, party, votes)
- @id = id
- @name = name
- @party = party
- @votes = votes
- end
- def party
- PARTIES[@party] || @party
- end
- end
- class Measure
- attr_accessor :id, :name, :candidates
- def initialize(id, name)
- @id = id
- @name = name
- @candidates = []
- end
- def winner
- @winner ||= @candidates.sort{|a, b| a.votes <=> b.votes}.last
- end
- def total_votes
- @total_votes ||= @candidates.inject(0) {|m, c| m + c.votes}
- end
- end
- measures = []
- measure = nil
- ARGF.each do |line|
- # We're either reading a measure or votes
- if line =~ /^\d+/
- # We're reading a Measure
- id, name = line.scan(/^(\d+)\s+\d+\s+"(.+)"/)[0]
- if !id.nil? && !name.nil?
- measure = Measure.new(id, name)
- measures << measure
- end
- elsif line =~ /^\s+/
- # We're reading a vote
- id, name, party, votes = line.scan(/\s+(\d+)\s+\d+\s+"(.*)"\s+"(.*)"\s+\d+\s+(\d+)/)[0]
- candidate = Candidate.new(id, name, party, votes.to_i)
- measure.candidates << candidate unless measure.nil?
- end
- end
- puts "Measure ID\tMeasure Name\tTotal Votes\tCandidate ID\tCandidate Name\tCandidate Party\tCandidate Votes"
- measures.each do |m|
- m.candidates.sort{|a,b| a.votes <=> b.votes}.reverse.each do |c|
- puts "#{m.id}\t#{m.name}\t#{m.total_votes}\t#{c.id}\t#{c.name}\t#{c.party}\t#{c.votes}"
- end
- end
Add Comment
Please, Sign In to add comment