匹配两个集合的连续元素之和
Matching sums of consecutive elements of two sets
给定两组相同长度的整数P和C。如何找到两个集合中相同起始和结束位置的连续元素的所有匹配和,包括重叠子集?
首选 C#,但请使用非 Linq。
示例:
Let P and C be the sets of the first ten prime and composite numbers:
P = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }
C = { 4, 6, 8, 9, 10, 12, 14, 15, 16, 18 }
Match 1: [index starts at 0]
SumP[3..5] = 7 + 11 + 13 = 31
SumC[3..5] = 9 + 10 + 12 = 31
Match 2: [index starts at 0]
SumP[2, 6] = 5 + 7 + 11 + 13 + 17 = 53
SumC[2, 6] = 8 + 9 + 10 + 12 + 14 = 53
我要看看上面两个和是不是唯一的!
这是带有嵌套 for 循环的强力方法,忽略了我还不理解的“重叠”部分:
for(int indexA=0; indexA<P.Length; indexA++) {
for(int indexB=indexA; indexB<P.Length; indexB++) {
int sumA = 0, sumB = 0;
for(int i=indexA; i<=indexB; i++) {
sumA += P[i];
sumB += C[i];
}
if (sumA == sumB) {
Console.WriteLine("[" + indexA + ", " + indexB + "] : Sum = " + sumA);
}
}
}
输出:
[2, 6] : Sum = 53
[3, 5] : Sum = 31
给定两组相同长度的整数P和C。如何找到两个集合中相同起始和结束位置的连续元素的所有匹配和,包括重叠子集?
首选 C#,但请使用非 Linq。
示例:
Let P and C be the sets of the first ten prime and composite numbers:
P = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }
C = { 4, 6, 8, 9, 10, 12, 14, 15, 16, 18 }
Match 1: [index starts at 0]
SumP[3..5] = 7 + 11 + 13 = 31
SumC[3..5] = 9 + 10 + 12 = 31
Match 2: [index starts at 0]
SumP[2, 6] = 5 + 7 + 11 + 13 + 17 = 53
SumC[2, 6] = 8 + 9 + 10 + 12 + 14 = 53
我要看看上面两个和是不是唯一的!
这是带有嵌套 for 循环的强力方法,忽略了我还不理解的“重叠”部分:
for(int indexA=0; indexA<P.Length; indexA++) {
for(int indexB=indexA; indexB<P.Length; indexB++) {
int sumA = 0, sumB = 0;
for(int i=indexA; i<=indexB; i++) {
sumA += P[i];
sumB += C[i];
}
if (sumA == sumB) {
Console.WriteLine("[" + indexA + ", " + indexB + "] : Sum = " + sumA);
}
}
}
输出:
[2, 6] : Sum = 53
[3, 5] : Sum = 31