Jeremy Stone
Jeremy Stone

Reputation: 350

Parallel arrays in Ruby

I have two arrays, one which stores candidate names, and another which stores the number of votes for said candidate. I'm trying to print the maximum amount of votes and the name of the corresponding candidate; instead of an output such as 92, 4 (number of votes, index of candidate), output something like 92, John.

This is as close as I've got to doing so:

puts "Candidates, index order: 0, 1, 2, 3, 4"
candidates.each { |x| puts x }
puts "Votes, index order: 0, 1, 2, 3, 4"
votes.each { |y| puts y }

votes.delete(nil)
puts "Maximum number of votes, followed by candidates array index."
puts votes.each_with_index.max { |x,y| x <=> y }

I'm successfully getting the index at which the max value is located, but how can I use that index to match the index of the candidates array in order to print a name rather than an index?

Upvotes: 1

Views: 279

Answers (2)

Wand Maker
Wand Maker

Reputation: 18762

A one more way to do this is given below, this will work if you had multiple candidates with same votes.

indices = votes.collect.with_index {|ele, idx| idx if ele == votes.max}.compact
result = indices.map  do |m|
    [votes[m], candidates[m]]
end

Upvotes: 0

sawa
sawa

Reputation: 168101

puts votes.zip(candidates).max_by(&:first)

Upvotes: 5

Related Questions