Using the Ruby language, have the function ArrayAdditionI(arr) take the array of numbers stored in arr and return the string true if any combination of numbers in the array can be added up to equal the largest number in the array, otherwise return the string false. For example: if arr contains [4, 6, 23, 10, 1, 3] the output should return true because 4 + 6 + 10 + 3 = 23. The array will not be empty, will not contain all the same elements, and may contain negative numbers.
有人可以向我解释一下为什么这段代码以“i=2”而不是“i=0”开头吗?
def ArrayAdditionI(arr)
i = 2
while i < arr.length
return true if arr.combination(i).map{|comb| comb.inject(:+)}.include?(arr.max)
i += 1
end
false
end
ArrayAdditionI(STDIN.gets)
如果我错了,请纠正我,但当 i=2 时,while 循环将迭代 [2..4] 然后停止。但这是否允许所有潜在的组合?...=>代码可以工作,所以显然它可以,但我只是没有看到它。
最佳答案
i
不是数组的索引,而是用于创建组合的元素数量。因此,如果数组中的最大数量可以通过两个元素的总和得出,则它将停止,否则它会尝试三个,依此类推。
关于arrays - 数组加法,为什么从 'i = 2' 开始?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31107523/