Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- puts "\n"
- puts "Welcome to my election program. What a way to make a living!"
- puts "\n"
- # Specification (optional enhancement): handle write-in votes
- puts "The official candidates are Dolly, Jane, and Lily. You may also enter a write-in candidate of your choice."
- puts "\n"
- puts "Please enter one candidate name per line and press return."
- puts "\n"
- votes = Array.new
- i = 1
- while i <= 10
- print "Vote ##{i}: "
- votes << gets.chomp.upcase.strip
- i += 1
- end
- puts "\n"
- puts "Counting votes, beep boo beep beep ..."
- puts "\n"
- puts "The votes are counted! The results are"
- puts "\n"
- vote_counts_h = Hash.new(0)
- votes.each do |candidate| vote_counts_h [candidate] += 1
- end
- vote_counts_a = vote_counts_h.sort_by { | v, k | k }
- vote_counts_a.reverse!
- # Specification (optional enhancement): Handle grammar of vote summary saying vote or votes appropriately
- # Programmer note: Adding block to provide different output depending on
- # whether candidate receive one vote or more than one vote.
- vote_counts_a.each do |candidate, votes_received|
- if votes_received == 1
- puts candidate.capitalize + ": " + votes_received.to_s + " vote"
- else
- puts candidate.capitalize + ": " + votes_received.to_s + " votes"
- end
- end
- # Adding nifty code uncovered for Walk-A-Thon program that will create two variables
- # from my vote_counts hash: one with the highest value (max_votes) and one with the key or keys
- # associated with the highest value (max_candidate).
- # The code below is much shorter than my initial code for this project, plus it makes handling ties easy.
- max_votes = vote_counts_h.values.max
- max_candidate = vote_counts_h.select { |k, v| v == max_votes}.keys
- # Creating another variable to store the number of winners (winner_count):
- # 1 for a single winner, or 2 or more in case of a tie.
- # A variable isn't required here -- I could do it with some nested code
- # -- but creating a variable makes the program easier to understand.
- winner_count = max_candidate.count
- puts "\n"
- # Specification (optional enhancement): Handle ties for a winner appropriately
- # Adding code to provide different outputs for a single winner and a tie.
- # (Easy since I already did this in the Walk-A-Thon tracker program.)
- if winner_count == 1
- puts "And the winner is ... #{max_candidate[0].capitalize} with #{max_votes} votes!"
- else
- puts "And the winner is ... it's a tie! #{max_candidate[0..-2].join(', ').capitalize} and #{max_candidate[-1].capitalize} received #{max_votes} votes each."
- end
- puts "\n"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement