我有两个2D点阵列:
array1 = int[x][2]
array2 = int[y][2]
从这两个数组中我想生成4个点的组合。结果应列在清单中:
List<int[4][2]>
但是我需要为每个组合指定从array1中获取的点数(并从array2中获取剩余的点数)。点的顺序无关紧要。而且应该没有重复。
例如:
array1={ {0,0} , {0,1} , {1,0} }
array2= { {1,1} , {2,1} , {2,2} , ... , {9,9} }
(从array1取1点,从array2取3点)
res= { {0,0} , {1,1} , {2,1} , {2,2} }
{ {0,0} , {1,1} , {2,1} , {3,2} }
...
{ {0,0} , {1,1} , {2,1} , {9,9} }
...
{ {0,1} , {1,1} , {2,1} , {2,2} }
...
从不:
res = { {0,0} , {1,1} , {1,1} , {1,1} }
...
都不是:
res= { {0,0} , {1,1} , {2,1} , {2,2} }
{ {0,0} , {1,1} , {2,2} , {2,1} }
...
(从array1拿2分,从array2拿2分)
...
(从array1拿3分,从array2拿1分)
...
我希望有人可以帮助我,因为我花了很多时间阅读/测试很多答案,但找不到解决方案。
PS /编辑:如果你能用C#提供很棒的代码。
答案 0 :(得分:2)
您的规定简化了此问题,您只能按照原始数组中存储的顺序检索点。
编辑:您的规定已简化此问题,结果应包含组合,而非排列。因此,为了简化操作,我们可以按照原始数组中存储顺序检索点,这样可以避免对它们进行置换。
您提供翻译任何其他语言,因此我将使用JavaScript。请注意,JavaScript数组包含它们的长度,因此您需要单独传递长度(或者传递数组的末尾)。
function combinations(array1, count1, array2, count2)
{
var result = [];
combine(array1, 0, count1, array2, 0, count2, [], result);
return result;
}
function combine(array1, offset1, count1, array2, offset2, count2, chosen, result)
{
var i;
var temp;
if (count1) {
count1--;
for (i = offset1; i < array1.length - count1; i++) {
temp = chosen.concat([array1[i]]); // this copies the array and appends the item
combine(array1, i + 1, count1, array2, offset2, count2, temp, result);
}
} else if (count2) {
count2--;
for (i = offset2; i < array2.length - count2; i++) {
temp = chosen.concat([array2[i]]);
combine(null, 0, 0, array2, i, count2, temp, result);
}
} else {
result.push(chosen); // don't need to copy here, just accumulate results
}
}
答案 1 :(得分:1)
通过Nuget下载Combinatorics Library for .Net
。
我试了一下:
Dim a1 = {New Integer() {0, 0}, New Integer() {1, 1}, New Integer() {2, 2}}
Dim a2 = {New Integer() {3, 3}, New Integer() {4, 4}, New Integer() {5, 5}, New Integer() {6, 6}}
Dim combA1 = New Combinations(Of Integer())(a1, 1)
Dim combA2 = New Combinations(Of Integer())(a2, 3)
Dim l As New List(Of Integer()())
For Each i In combA1
For Each j In combA2
l.Add(i.Union(j).ToArray)
Next
Next
不要忘记导入Combinatorics.Collections命名空间。 结果对我来说没问题,但你可能想花更多的时间来检查它。 for循环看起来可以用简单的LINQ语句替换,但它可以工作。