How to make all possible sum combinations from array elements in VB

后端 未结 3 729
生来不讨喜
生来不讨喜 2021-01-24 06:51

If there is an array with elements: 1,2,3,4, the program should return another array with sum of all combinations:

1
2
3
4
3 (1+2)
4 (1+3) 
5 (1+4)
5 (2+3)
6 (2+4)
7 (         


        
3条回答
  •  清歌不尽
    2021-01-24 07:27

    Coding the algorithm you mentioned in your comment, in pseudo VB code:

    ReDim result(2 ^ (Length of Array) - 1)
    for index = 0 to 2 ^ (Length of Array) - 1
      sum = 0
      for counter = 0 to (Length of Array) - 1
        If ((2 ^ counter) And index) <> 0 Then
          sum += Array(counter+1)
    
      result(index) = sum
    

提交回复
热议问题