numbers = [1, 2, 3, 4, 5]
for num in numbers
puts "insert q "
qanswer1 = gets.chomp.to_i
puts "insert 2nd q"
qanswer2 = gets.chomp.to_i
end
此代码将重复问题5次。如何检索用户输入的数据?我正在尝试计算所有10个响应的总和以及每个对的总和最高的索引。
答案 0 :(得分:0)
我试图提供一种尽可能接近您的解决方案,同时仍然产生预期的结果:
numbers = [0,1,2,3,4]
pairs = Array.new(numbers.size, [])
numbers.each do |number|
pairs[number] = []
puts "q 1:"
pairs[number] << gets.to_i
puts "q 2:"
pairs[number] << gets.to_i
end
要获得最大值的配对:
max_value = pairs.max_by(&:sum)
要获取所有对的总和:
sum_of_all_responses = pairs.flatten.sum
要获取具有最高值的对的索引:
pairs.index(max_value)
答案 1 :(得分:0)
nbr_pairs = 5
def ask(str)
print "#{str}: "
gets.to_i
end
arr = nbr_pairs.times.map { [ask("insert q"), ask("insert 2nd q")] }
#=> [[7, 3], [8, 6], [2, 9], [4, 6], [8, 3]]
所有10条回复的总和
arr.flatten.sum
#=> 56
最大对数的索引
nbr_pairs.times.max_by { |i| arr[i].sum }
#=> 1 (8+6 = 14)
答案 2 :(得分:0)
如果您不需要存储所有数据,则可以随时进行计算。
首先将输入请求移到一个方法,该方法将一个值对n返回一个数组:
def ask
puts "insert q "
qanswer1 = gets.to_i
puts "insert 2nd q"
qanswer2 = gets.to_i
[qanswer1, qanswer2]
end
然后设置变量
big_sum = 0
best_input = 0
best_input_q_number = nil
像做数学一样最后循环:
numbers = [1,2,3,4,5]
for n in numbers
# (1..5).each do |n| # this is more Ruby-ish
p qanswers = ask # p for debug
qanswers_sum = qanswers.sum
big_sum += qanswers_sum
if qanswers_sum > best_input
best_input = qanswers_sum # or qanswers if you want to keep the pairs
best_input_q_number = n
end
end