我有多个嵌套循环,其数量等于数据量。例如,查找 3 个给定长度的钢筋切割组合。 因此,切割 20 英尺长的钢筋后,废料的长度不应超过 1 英尺。 所以,我使用了 3 个嵌套循环,因为有 3 个条形剪切。如果我有 50 个小节剪切,那么我将使用 50 个嵌套循环。那么,有什么办法可以解决这个问题,这样就不需要编辑源代码了。也许双重递归?或任何其他算法。谢谢。 以下给定数据的示例答案。
for (int a = 0; a < 50; a++){
for (int b = 0; b < 50; b++){
for (int c = 0; c < 50; c++){
double TL = a * BarCut[0] + b * BarCut[1] + c * BarCut[2];
double waste = 20 - TL;
//if (waste >= 0 && waste < 1 )
//Console.WriteLine($"{a}A, {b}B, {c}C, TL={TL}, waste = {waste:F2}");
}
}
}
下面的方法允许您在给定较长的条形 (
bars
) 的情况下计算任意数量的条形切割 (longBar
)。
using System.Collections.Generic;
using System.Linq;
public static double MinimumWaste(IEnumerable<double> bars, double longBar)
{
double minWaste = double.MaxValue;
for(int i = 0; i <= longBar; i++)
{
double curCut = bars.First();
double remainingBar = longBar - curCut * i;
if(remainingBar < 0)
{
//bar is to short to cut, skip
break;
}
double waste = remainingBar;
//we have additional bar cuts to consider,
//skip the current bar and recurse
if(bars.Count() > 1)
{
waste = MinimumWaste(bars.Skip(1), remainingBar);
}
if(waste < minWaste)
{
minWaste = waste;
}
}
return minWaste;
}
您可以这样调用该方法:
MinimumWaste(new List<double>(){3d, 4d}, 10d);
它将输出
0
作为最小浪费,因为我们可以将 10.0
条切成 两个 3.0
条和 a 4.0
条。
如果我在代码中的某个地方犯了错误,请告诉我。我相信有更有效的方法可以做到这一点,比如使用最小公倍数?