-2

I need to poll users for election input and output the winner using only arrays and loops. We are not up to speed with hashes yet.

Input: Poll 10 people for their vote. Output: Print the total votes cast as well as the winner of the election and tie breakers.

Example: 
  Election candidates are: Tom, James, Anne

  Vote #1: <Anne>
  Vote #2: <Anne>
  Vote #3: <James>
  Vote #4: <Tom>
  Vote #5: <Tom>
  Vote #6: <Anne>
  Vote #7: <Anne>
  Vote #8: <James>
  Vote #9: <James>
  Vote #10: <Anne>

 RESULTS....

  Vote Summary:
  Anne - 5 vote(s)
  James - 3 vote(s)
  Tom - 2 vote(s)

  WINNER: Anne!

I am thinking about using the times method to fill all the Votes with users' inputs for candidates and an array to store the candidates.

candidates = "Iron Man", "Wonder Women", "Storm"

puts "Our Election Candidates this year are: #{candidates}"

10.times do |i|
print "Vote #{i+1}"
vote[i] = gets.chomp.upcase.to_i
end

But then, I don't know how to find the total votes for each candidate? Any suggestions will be appreciated.

Gambit
  • 1
  • 1

1 Answers1

0

I don't know how candidates are stored , but if I understood your question, maybe this can help.

candidates = [["Tom", 0], ["James", 0], ["Anne", 0]]

def update_votes(candidates, index)
  candidates[index][1] += 1
end

10.times do
  puts "Vote your candidate:"
  candidates.each_with_index {|c, i| puts "#{i}-#{c[0]}"}
  index = gets.to_i
  update_votes(candidates, index)
end

p results = candidates.sort_by{|_name, votes| -votes}
iGian
  • 11,023
  • 3
  • 21
  • 36