如何从VB中的数组元素中创建所有可能的和组合

时间:2010-03-24 16:26:51

标签: vb.net arrays elements combinatorics

如果有一个包含元素的数组:1,2,3,4,程序应返回另一个包含所有组合之和的数组:

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)

3 个答案:

答案 0 :(得分:4)

这是我前一段时间写的一个函数,用于生成给定数组的所有可能子集。它是通用的,因此它支持整数,双精度,字符串等。

原创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;
}

我刚刚转换为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

可以这种方式消费

    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

答案 1 :(得分:0)

我的想法是:

(伪代码,我不知道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  
}

答案 2 :(得分:0)

使用伪VB代码编写您在评论中提到的算法:

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