Iterate Array and add each consecutive array value

前端 未结 2 2120
终归单人心
终归单人心 2021-01-17 08:12

I have an amount. I want to iterate the array starting from the first value and if I add the next value and it equals amount then those two values in the array should be re

2条回答
  •  感动是毒
    2021-01-17 08:58

    Try this:

    array = [1,2,3,4,7]
    amount = 17
    
    master_array = (1..array.size).map { |i| array.each_slice(i).to_a }
    
    master_array.each.with_index do |e,i| 
      p e[0] if master_array[i][0].inject(:+) == amount
    end
    

提交回复
热议问题