如何从VB中的数组元素的所有可能的组合总和 [英] How to make all possible sum combinations from array elements in VB
本文介绍了如何从VB中的数组元素的所有可能的组合总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果有一个与元素的数组: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)
解决方案
这是我写的,前一段时间,以产生一个给定的阵列的所有可能的子集的功能。它是通用的,所以它支持整数,双打,字符串,等等。
原来的C#
公共静态列表< T []> CreateSubsets< T>(T [] originalArray)
{
清单< T []>亚=新名单< T []>(); 的for(int i = 0; I< originalArray.Length;我++)
{
INT subsetCount = subsets.Count;
subsets.Add(新T [] {originalArray [I]}); 对于(INT J = 0; J< subsetCount; J ++)
{
T [] = newSubset新T [亚群的研究[J]。长度+ 1];
子集[J] .CopyTo(newSubset,0);
newSubset [newSubset.Length - 1] = originalArray [I]
subsets.Add(newSubset);
}
} 返回子集;
}
和版本我只是转换为VB。
功能CreateSubsets(共T)(BYVAL originalArray()作为T)方式列表(中T()) 昏暗的子集作为新的列表(中T()) 对于我作为整数= 0〜originalArray.Length - 1 昏暗subsetCount作为整数= subsets.Count
subsets.Add(新T(){originalArray(我)}) 对于j为整数= 0〜subsetCount - 1
昏暗newSubset(子集(J)。长度)作为T形
子集(J).CopyTo(newSubset,0)
newSubset(newSubset.Length - 1)= originalArray㈠
subsets.Add(newSubset)
下一个 下一个 返回子集结束功能
有可以以这种方式被消耗
维数组()作为整数= {1,2,3,4,5}
昏暗的子集作为列表(整数())= CreateSubsets(阵列) 对于每个子集作为整数()的子集 点心作为整数= subset.Sum() 下一个
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)
解决方案
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
这篇关于如何从VB中的数组元素的所有可能的组合总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文