Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby中的并行数组_Ruby - Fatal编程技术网

Ruby中的并行数组

Ruby中的并行数组,ruby,Ruby,我有两个数组,一个存储候选人姓名,另一个存储该候选人的投票数。我试图打印最大票数和相应候选人的姓名;不是像92,4(投票数,候选人索引)这样的输出,而是像92,John这样的输出 这是我要做的最接近的事情: 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 } v

我有两个数组,一个存储候选人姓名,另一个存储该候选人的投票数。我试图打印最大票数和相应候选人的姓名;不是像
92,4
(投票数,候选人索引)这样的输出,而是像
92,John
这样的输出

这是我要做的最接近的事情:

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 }
放置“候选项,索引顺序:0,1,2,3,4”
每个{x |放置x}
将“投票,索引顺序:0,1,2,3,4”
投票。每个{y{124;投y}
表决。删除(无)
puts“最大投票数,后跟候选人数组索引。”
使用_index.max{| x,y | x y}对每个_进行投票

我正在成功获取最大值所在的索引,但是如何使用该索引匹配候选数组的索引,以便打印名称而不是索引?

下面给出了另一种方法,如果您有多个具有相同投票权的候选,这将起作用

puts votes.zip(candidates).max_by(&:first)
indices = votes.collect.with_index {|ele, idx| idx if ele == votes.max}.compact
result = indices.map  do |m|
    [votes[m], candidates[m]]
end

下面给出了另一种方法,如果您有多个候选人拥有相同的选票,这将起作用

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

最后我花了太多时间想弄明白这一点。非常感谢。这并不一定意味着时间被浪费了。顺便说一句,当你可以使用两个大小相同的数组时,你可以选择使用:
[[10,23,6],“Bob”,“Betty”,“Bubba”].transpose.max_by(&:first)#=>[23,“Betty”]
。另一种不太像Ruby的方式是
mx=vows.max;[mx,candiates[Voces.index(mx)]
。最后!我花了太多时间试图弄明白这一点。谢谢!这并不一定意味着浪费了时间。顺便说一句,只要你可以使用两个大小相同的数组,你就可以选择使用:
[[10,23,6],“Bob”,“Betty”,“Bubba”]]。将max_转置为(&:first)=>[23,“Betty”]
。另一种不太像红宝石的方式是
mx=voces.max;[mx,candiates[voces.index(mx)]