gpt4 book ai didi

c# - 在列表中查找最近的 sumElement 组合

转载 作者:太空狗 更新时间:2023-10-29 17:49:10 25 4
gpt4 key购买 nike

我在查找列表中最近的 sumElement 组合时遇到了一些问题。

例子:

这是我的 list :

 list = {32183,15883,26917,25459,22757,25236,1657}
list.Sum = 150092

现在我要分开

 list.Sum / z
z = variable(user Input - in this example it's 3)

我明白了

50031

现在我想从 listElement 总和中找到最接近的数字。

最接近50031的是

 32183 + 15883 = 48066
or
32183 + 15883 + 26917 = 74983

所以我选择 48066,接下来我想找到下一个元素,但我们不得不跳过已经计数的元素(在这种情况下我不得不跳过 32183 + 15883)

所以现在我们只能使用这些元素26917,25459,22757,25236,1657(还未统计)

  26917 + 25459 = 52376
or
26917 + 25459 + 22757 = 75133

所以我选择52376

我们做了 z(变量)次

对于无法添加的示例,我们可以按此顺序对元素求和

 32183 + 15883 + 1657

因为这会跳过几个列表元素

我们可以用这种方式对元素求和,但不能对列表进行排序。我们不能这样做,因为这些数字是 .csv 文件中的行数,所以我必须按此顺序进行。

现在我有:

for (int i = 0; i < z; i++)
{
mid = suma/z ;

najbliższy = listSum.Aggregate((x, y) => Math.Abs(x - mid) < Math.Abs(y - mid) ? x : y);
}

它为我找到了第一个元素(正确地),但我不知道如何正确地循环它。所以我只得到了第一个元素,在这个例子中我需要 3 个。

谁能帮我完成这个?

最佳答案

以下代码的输出是:

Target = 50031

32183 15883 Total: 48066
26917 25459 Total: 52376
22757 25236 1657 Total: 49650

您只需调用 FindSubsetsForTotal() 来接收所有子集的序列,您可以对其进行迭代。

代码:

using System;
using System.Collections.Generic;

namespace Demo
{
public class Program
{
static void Main()
{
var numbers = new[] {32183, 15883, 26917, 25459, 22757, 25236, 1657};
int target = 50031;

foreach (var subset in FindSubsetsForTotal(numbers, target))
{
int subtotal = 0;

for (int i = subset.Item1; i <= subset.Item2; ++i)
{
Console.Write(numbers[i] + " ");
subtotal += numbers[i];
}

Console.WriteLine("Total: " + subtotal);
}
}

public static IEnumerable<Tuple<int, int>> FindSubsetsForTotal(IList<int> numbers, int target)
{
int i = 0;

while (i < numbers.Count)
{
int end = endIndexOfNearestSum(numbers, i, target);
yield return new Tuple<int, int>(i, end); // The subset is from i..end inclusive. Return it.
i = end + 1; // On to the next subset.
}
}

static int endIndexOfNearestSum(IList<int> numbers, int start, int target)
{
int sumSoFar = 0;
int previousSum = 0;

for (int i = start; i < numbers.Count; ++i)
{
sumSoFar += numbers[i];

if (sumSoFar > target)
{
if (Math.Abs(sumSoFar - target) < Math.Abs(previousSum - target))
return i;

return i - 1;
}

previousSum = sumSoFar;
}

return numbers.Count - 1;
}
}
}

关于c# - 在列表中查找最近的 sumElement 组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39786191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com