views:

781

answers:

4

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+4)
6 (1+2+3)
7 (1+2+4)
8 (1+3+4)
9 (2+3+4)
10 (1+2+3+4)
A: 

My idea is:

(pseudcode, I don;t know VB)

for(int i = 0; i < 4321; i++)
{
    i mod 10 + // first from right digit
    (int)((i mod 100)mod 10) // second, (?)
    // etc
    // sum up all 4 digit
    // add to array  
}
Rin
problem is that i need to make code for n, not just for 4 numbers
Elma
always u could sort ur digit and make biggest number instead 4321 :) Anyway, here is another problem because `1000` and `100` should appear only once?
Rin
A: 

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
Mark Hurd
I think index should start at 1.
Gabe
Yes, index should start at 1 to miss the empty combination, and my pseudo VB code has issues with array indicies and wasted entries too.
Mark Hurd
+1  A: 

This is a function I wrote some time ago to generate all possible subsets of a given array. It's generic, so it supports integers, doubles, strings, etc.

Original C#

public static List<T[]> CreateSubsets<T>(T[] originalArray)
{
    List<T[]> subsets = new List<T[]>();

    for (int i = 0; i < originalArray.Length; i++)
    {
        int subsetCount = subsets.Count;
        subsets.Add(new T[] { originalArray[i] });

        for (int j = 0; j < subsetCount; j++)
        {
            T[] newSubset = new T[subsets[j].Length + 1];
            subsets[j].CopyTo(newSubset, 0);
            newSubset[newSubset.Length - 1] = originalArray[i];
            subsets.Add(newSubset);
        }
    }

    return subsets;
}

And the version I just converted to VB.

Function CreateSubsets(Of T)(ByVal originalArray() As T) As List(Of T())

    Dim subsets As New List(Of T())

    For i As Integer = 0 To originalArray.Length - 1

        Dim subsetCount As Integer = subsets.Count
        subsets.Add(New T() {originalArray(i)})

        For j As Integer = 0 To subsetCount - 1
            Dim newSubset(subsets(j).Length) As T
            subsets(j).CopyTo(newSubset, 0)
            newSubset(newSubset.Length - 1) = originalArray(i)
            subsets.Add(newSubset)
        Next

    Next

    Return subsets

End Function

It can be consumed in this manner

    Dim array() As Integer = {1, 2, 3, 4, 5}
    Dim subsets As List(Of Integer()) = CreateSubsets(array)

    For Each subset As Integer() In subsets

        Dim sum As Integer = subset.Sum()

    Next
Anthony Pegram
+1 for the snippet - nice and clean and short. thx Anthony!
Mike
A: 

Guys, I'm using VB.NET 2003. I guess the previous code in VB6. How I cam convert it to .NET

Ayman