arrays - 数组加法,为什么从 'i = 2' 开始?

标签 arrays ruby sum subset

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/

相关文章:

c - qsort 结构中的结构数组

ruby - 如何使用 RSpec 断言一个类将响应一个类方法?

ruby-on-rails - 在 Ruby 中更改文件的权限

mysql - 如何总结日期和时间?

sql - 按最大总和选择,但结果中没有总和

python - 从 numpy 结构化数组(数组中的元组列表)中删除列?

java - 复制构造函数帮助,试图复制一个 boolean 数组。 java

php - 选择数组中的值,分离并查询数据库laravel

ruby-on-rails - 在 Rails 3 中为所有目的继承模型和更改表

mysql - 按值计算多行的数学 SUM