I have multiple nested loops that is equal to amount of data. For example, find the bar cutting combinations of 3 given lengths.
so that the waste should not be longer than 1' after cutting in the 20' length rebar.
so, I used 3 nested loops because there are 3 bar cuts. If I have 50 bar Cuts, then I will use 50 nested loops. So, what is the solution to this problem so no need to edit the source code. maybe double recursion? or any other algorithm. Thanks.
Sample answer to given data below.
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}");
}
}
}
After reading some topics about multiple nested loops to recursive function. I got the final solution that I copied some lines from other thread but adding some condition of filtering data. below is the code and answer to bar combination cut to meet waste requirement of no longer by 1' but my final objective is https://en.wikipedia.org/wiki/Cutting_stock_problem.
private static double[] BarCuts = { 6.2, 5, 3, 4}; // List of Bar Cuttings.
static void Main(string[] args)
{
List<int[]> collection = new List<int[]>();
int[] limits = GetLimits(BarCuts);
printHading(BarCuts);
AddToCollectionRecursive(collection, limits);
foreach (var item in collection)
printResult(item);
Console.ReadLine();
}
static void AddToCollectionRecursive(List<int[]> collection, params int[] limits)
{
AddTo(collection, new List<int>(), limits, limits.Length - 1);
}
static void AddTo(List<int[]> collection, IEnumerable<int> value, IEnumerable<int> counts, int left)
{
for (var i = 0; i < counts.First(); i++)
{
var list = value.ToList();
list.Add(i);
if (left == 0)
{
double tl = Combination_Length(list);
if (tl > 20) { break; }
double waste = 20 - tl; // 20 = avlb bar length.
if (waste < 1)
collection.Add(list.ToArray());
}
else
{
AddTo(collection, list, counts.Skip(1), left - 1);
}
}
}
static double Combination_Length(List<int> CutsQty)
{
double tl = 0;
for (int j = 0; j < CutsQty.Count; j++)
tl += CutsQty[j] * BarCuts[j];
return tl;
}
5D => TL= 20, waste= 0.00
4C & 2D => TL= 20, waste= 0.00
1B & 1C & 3D => TL= 20, waste= 0.00
1B & 5C => TL= 20, waste= 0.00
2B & 2C & 1D => TL= 20, waste= 0.00
4B => TL= 20, waste= 0.00
1A & 3C & 1D => TL= 19.2, waste= 0.80
1A & 1B & 2D => TL= 19.2, waste= 0.80
1A & 2B & 1C => TL= 19.2, waste= 0.80
2A & 1C & 1D => TL= 19.4, waste= 0.60