1

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?

2 Answers 2

5
puts votes.zip(candidates).max_by(&:first)
Sign up to request clarification or add additional context in comments.

2 Comments

FINALLY! I spent way too much time trying to figure this out. Thank you!
That doesn't necessarily mean the time was wasted. btw, whenever you can use Enumerable#zip with two arrays of equal size you can alternatively use Array#transpose: [[10,23,6],["Bob", "Betty", "Bubba"]].transpose.max_by(&:first) #=> [23, "Betty"]. Another, less Ruby-like, way is mx = votes.max; [mx, candiates[votes.index(mx)].
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.