在此代码中,如果用户键入 2,两次和 1,两次。然后有两个最大元素,应该打印 Kinder 和 Twix。但是怎么样?我可能可以使用 if 方法来做到这一点,但这会使我的代码更长。有没有很酷的版本?我可以只用一个 if 吗?
a = [0, 0, 0,]
b = ["Kinder", "Twix", "Mars"]
while true
input = gets.chomp.to_i
if input == 1
a[0] += 1
elsif input == 2
a[1] += 1
elsif input == 3
a[2] += 1
elsif input == 0
break
end
end
index = a.index(a.max)
chocolate = b[index] if index
print a.max,chocolate
Run Code Online (Sandbox Code Playgroud)
这个问题实际上与数组a的构造方式无关。
def select_all_max(a, b)
mx = a.max
b.values_at(*a.each_index.select { |i| a[i] == mx })
end
Run Code Online (Sandbox Code Playgroud)
b = ["Kinder", "Twix", "Mars"]
Run Code Online (Sandbox Code Playgroud)
p select_all_max [0, 2, 1], b
["Twix"]
p select_all_max [2, 2, 1], b
["Kinder", "Twix"]
Run Code Online (Sandbox Code Playgroud)
请参阅Array#values_at。
或者,这可以在单次通过中完成。
def select_all_max(a, b)
b.values_at(
*(1..a.size-1).each_with_object([0]) do |i,arr|
case a[i] <=> arr.last
when 0
arr << i
when 1
arr = [i]
end
end
)
end
Run Code Online (Sandbox Code Playgroud)
p select_all_max [0, 2, 1], b
["Twix"]
p select_all_max [2, 2, 1], b
["Kinder", "Twix"]
p select_all_max [1, 1, 1], b
["Kinder", "Twix", "Mars"]
Run Code Online (Sandbox Code Playgroud)