Iterate Array and add each consecutive array value

时间:2016-02-12 19:33:32

标签: arrays ruby

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 returned. If it doesn't equal the value, try to add the next one after that one and check if it equals the amount.

And then return the array of values that when added up equals the amount

example

Lets say I have an array of [1,2,3,4,7] and an amount 6

I know that I can make 6 by adding 1+2+3 so I want to return [1,2,3] back.

it's the iterating through the start of the array and then checking whether I add the next if it equals 6 and if not, try to add the next one also and see it equals 6...and so on till I get the values that when added together do equal 6.

On other words find the values in this array that when added together make up 6.

2 个答案:

答案 0 :(得分:2)

arr = [1,2,3,4,7]
tot = 6

案例1:要求和的元素是数组的第一个n元素

效率不高,但读得很好:

idx = arr.size.times.find { |i| arr[0..i].reduce(:+) == tot }
idx ? arr[0..idx] : nil
  #=> [1, 2, 3]

效率更高:

t = 0
idx = arr.size.times.find { |i| t += arr[i]; t == tot }
idx ? arr[0..idx] : nil
  #=> [1, 2, 3]

使用递归

def partial_sum(arr, remaining)
  return nil if arr.empty?
  first, *rest = arr
  if remaining == first
    [first]
  else
    ret = partial_sum(rest, remaining-first)
    ret ? [first, *ret] : nil
  end
end

partial_sum(arr, 6)
  #=> [1, 2, 3]
partial_sum(arr, 7)
  #=> nil

案例2:要求和的元素可以是数组的任何元素

def sum_subarrays(arr, tot)
  (0...arr.size).each do |n| 
    b = arr.combination(n).find { |a| a.reduce(:+) == tot }
    b ? (return b) : nil
  end
  nil
end

(1..17).each do |tot|
  v = sum_subarrays(arr, tot)
  puts "sum_subarrays(arr, #{tot}) = #{v ? v : 'nil'}"
end
sum_subarrays(arr, 1)  = [1]
sum_subarrays(arr, 2)  = [2]
sum_subarrays(arr, 3)  = [3]
sum_subarrays(arr, 4)  = [4]
sum_subarrays(arr, 5)  = [1, 4]
sum_subarrays(arr, 6)  = [2, 4]
sum_subarrays(arr, 7)  = [7]
sum_subarrays(arr, 8)  = [1, 7]
sum_subarrays(arr, 9)  = [2, 7]
sum_subarrays(arr, 10) = [3, 7]
sum_subarrays(arr, 11) = [4, 7]
sum_subarrays(arr, 12) = [1, 4, 7]
sum_subarrays(arr, 13) = [2, 4, 7]
sum_subarrays(arr, 14) = [3, 4, 7]
sum_subarrays(arr, 15) = [1, 3, 4, 7]
sum_subarrays(arr, 16) = [2, 3, 4, 7]
sum_subarrays(arr, 17) = nil

答案 1 :(得分:0)

Try this:

utils.processIdleEvents()