You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

仅用数组与循环实现选举投票统计:求计票及获胜者判定方案

Solution for Vote Counting with Arrays & Loops in Ruby

Hey there! Let's work through this vote counting problem together, sticking strictly to arrays and loops as you asked. I'll break this down step by step so you can follow along easily.

First, Fix Your Initial Code

Let's start by tweaking the code you already have—there are a couple small issues to address first:

  1. Your candidates variable should be explicitly defined as an array (Ruby handles comma-separated values without brackets, but writing ["Iron Man", "Wonder Woman", "Storm"] is clearer).
  2. You forgot to initialize the array to store user inputs.
  3. Converting the vote input to an integer (to_i) doesn't make sense here—we need to keep the candidate name as a string.

Here's the corrected input collection code:

candidates = ["Iron Man", "Wonder Woman", "Storm"]
puts "Our Election Candidates this year are: #{candidates.join(', ')}"

# Initialize an array to store all votes
votes = []

10.times do |i|
  print "Vote ##{i+1}: "
  vote_input = gets.chomp.strip # Get input and remove extra spaces
  votes << vote_input # Add the vote to our array
end

Counting Votes with Arrays (No Hashes Allowed!)

Since we can't use hashes, we'll use two parallel arrays: one for candidates, and another to track their vote counts. Each index in the vote_counts array corresponds to the candidate at the same index in the candidates array.

Here's how to set up and populate the count array:

# Create a count array with 0s, one for each candidate
vote_counts = Array.new(candidates.size, 0)

# Loop through each vote to count matches
votes.each do |vote|
  # Check each candidate to see if the vote matches
  candidates.each_with_index do |candidate, index|
    # Compare in uppercase to make input case-insensitive (user can type "iron man" or "IRON MAN")
    if vote.upcase == candidate.upcase
      vote_counts[index] += 1 # Increment the count for this candidate
    end
  end
end

Calculating Total Votes & Determining the Winner

Now we can calculate total votes, display the summary, and figure out who won (or if there's a tie):

total_votes = vote_counts.sum # Sum all values in the count array

puts "\nRESULTS...."
puts "Total Votes Cast: #{total_votes}"
puts "Vote Summary:"

# Print each candidate and their vote count
candidates.each_with_index do |candidate, index|
  puts "#{candidate} - #{vote_counts[index]} vote(s)"
end

# Find the highest number of votes
max_votes = vote_counts.max

# Collect all candidates who have the maximum votes
winners = candidates.select.with_index { |_, index| vote_counts[index] == max_votes }

# Handle tie or single winner
if winners.size > 1
  puts "\nIT'S A TIE! The winners are: #{winners.join(', ')}"
else
  puts "\nWINNER: #{winners.first}!"
end

Full Working Code

Putting it all together, here's the complete program:

# Define election candidates
candidates = ["Iron Man", "Wonder Woman", "Storm"]
puts "Our Election Candidates this year are: #{candidates.join(', ')}"

# Collect 10 votes from users
votes = []
10.times do |i|
  print "Vote ##{i+1}: "
  vote_input = gets.chomp.strip
  votes << vote_input
end

# Count votes using parallel arrays
vote_counts = Array.new(candidates.size, 0)
votes.each do |vote|
  candidates.each_with_index do |candidate, index|
    if vote.upcase == candidate.upcase
      vote_counts[index] += 1
    end
  end
end

# Display results
total_votes = vote_counts.sum
puts "\nRESULTS...."
puts "Total Votes Cast: #{total_votes}"
puts "Vote Summary:"
candidates.each_with_index do |candidate, index|
  puts "#{candidate} - #{vote_counts[index]} vote(s)"
end

max_votes = vote_counts.max
winners = candidates.select.with_index { |_, index| vote_counts[index] == max_votes }

if winners.size > 1
  puts "\nIT'S A TIE! The winners are: #{winners.join(', ')}"
else
  puts "\nWINNER: #{winners.first}!"
end

Quick Explanation

  • Parallel Arrays: vote_counts and candidates share the same index positions, so we can easily map each candidate to their count.
  • Case Insensitivity: By converting both the input and candidate name to uppercase, we make the program more user-friendly (no need for exact capitalization).
  • Tie Handling: We collect all candidates with the highest vote count, so if multiple people have the same max votes, we display all of them.

内容的提问来源于stack exchange,提问作者Gambit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:52:45