两组连续元素的匹配总和

发布于 2025-01-18 00:06:17 字数 504 浏览 5 评论 0原文

给定两组相同长度的整数 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

我需要判断上面两个和是否是唯一的!

Given two sets of integers P and C of the same length. How can I find ALL matching sums of consecutive elements at the same starting and ending positions in the two sets, including overlapping subsets?

C# is preferred but non-Linq please.

Example:

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

I need to find if the above two sums are the only ones or not!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

赴月观长安 2025-01-25 00:06:18

这是嵌套 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

Here's the brute force approach with nested for loops, ignoring the "overlapping" part which I don't understand yet:

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);
    }
  }
}

Output:

[2, 6] : Sum = 53
[3, 5] : Sum = 31
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文