algorithm to sum up a list of numbers for all combinations

前端 未结 15 2260
北荒
北荒 2020-12-04 22:34

I have a list of numbers and I want to add up all the different combinations. For example:

  • number as 1,4,7 and 13
  • the output would be:

15条回答
  •  -上瘾入骨i
    2020-12-04 23:29

    Here is a simple recursive Ruby implementation:

    a = [1, 4, 7, 13]
    
    def add(current, ary, idx, sum)
        (idx...ary.length).each do |i|
            add(current + [ary[i]], ary, i+1, sum + ary[i])
        end
        puts "#{current.join('+')} = #{sum}" if current.size > 1
    end    
    add([], a, 0, 0)
    

    Which prints

    1+4+7+13 = 25
    1+4+7 = 12
    1+4+13 = 18
    1+4 = 5
    1+7+13 = 21
    1+7 = 8
    1+13 = 14
    4+7+13 = 24
    4+7 = 11
    4+13 = 17
    7+13 = 20
    

    If you do not need to print the array at each step, the code can be made even simpler and much faster because no additional arrays are created:

    def add(ary, idx, sum)
        (idx...ary.length).each do |i|
            add(ary, i+1, sum + ary[i])
        end
        puts sum
    end
    add(a, 0, 0)
    

    I dont think you can have it much simpler than that.

提交回复
热议问题