Guest User

Untitled

a guest
Jun 20th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2. #
  3. # A simple parser for parsing King County, WA vote results
  4.  
  5. PARTIES = {
  6. "Dem" => "Democratic Party",
  7. "DPC" => "Democratic Party",
  8. "Rep" => "Republican Party",
  9. "RPC" => "Republican Party",
  10. "NOP" => "NOP",
  11. "Ref" => "Reform Party",
  12. "I" => "Independent",
  13. "INO" => "Independent",
  14. "IDM" => "Independent",
  15. "G" => "Green Party",
  16. "CTT" => "Centrist Party",
  17. "PFX" => "Problemfixer Party"
  18. }
  19.  
  20. class Candidate
  21. attr_accessor :id, :name, :votes
  22.  
  23. def initialize(id, name, party, votes)
  24. @id = id
  25. @name = name
  26. @party = party
  27. @votes = votes
  28. end
  29.  
  30. def party
  31. PARTIES[@party] || @party
  32. end
  33. end
  34.  
  35. class Measure
  36. attr_accessor :id, :name, :candidates
  37.  
  38. def initialize(id, name)
  39. @id = id
  40. @name = name
  41. @candidates = []
  42. end
  43.  
  44. def winner
  45. @winner ||= @candidates.sort{|a, b| a.votes <=> b.votes}.last
  46. end
  47.  
  48. def total_votes
  49. @total_votes ||= @candidates.inject(0) {|m, c| m + c.votes}
  50. end
  51. end
  52.  
  53. measures = []
  54. measure = nil
  55. ARGF.each do |line|
  56. # We're either reading a measure or votes
  57. if line =~ /^\d+/
  58. # We're reading a Measure
  59. id, name = line.scan(/^(\d+)\s+\d+\s+"(.+)"/)[0]
  60. if !id.nil? && !name.nil?
  61. measure = Measure.new(id, name)
  62. measures << measure
  63. end
  64.  
  65. elsif line =~ /^\s+/
  66. # We're reading a vote
  67. id, name, party, votes = line.scan(/\s+(\d+)\s+\d+\s+"(.*)"\s+"(.*)"\s+\d+\s+(\d+)/)[0]
  68. candidate = Candidate.new(id, name, party, votes.to_i)
  69. measure.candidates << candidate unless measure.nil?
  70. end
  71. end
  72.  
  73. puts "Measure ID\tMeasure Name\tTotal Votes\tCandidate ID\tCandidate Name\tCandidate Party\tCandidate Votes"
  74. measures.each do |m|
  75. m.candidates.sort{|a,b| a.votes <=> b.votes}.reverse.each do |c|
  76. puts "#{m.id}\t#{m.name}\t#{m.total_votes}\t#{c.id}\t#{c.name}\t#{c.party}\t#{c.votes}"
  77. end
  78. end
Add Comment
Please, Sign In to add comment