You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
2.3 KiB
C#

7 months ago
using Google.OrTools.Algorithms;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SlabHandle
{
public class OR_T
{
public static IDictionary<string, IList<string>> Main(string[] args)
{
KnapsackSolver solver = new KnapsackSolver(
KnapsackSolver.KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, "KnapsackExample");
long[] values = args[0].Replace("{", "").Replace("}", "").Split(new char[] { ',' }).ToList().ConvertAll(p => long.Parse(p)).ToArray();
long[] values2 = args[1].Replace("{", "").Replace("}", "").Split(new char[] { ',' }).ToList().ConvertAll(p => long.Parse(p)).ToArray();
long[,] weights = OneD_2(values2, 1);
long[] capacities = args[2].Replace("{", "").Replace("}", "").Split(new char[] { ',' }).ToList().ConvertAll(p => long.Parse(p)).ToArray();
List<string> result = new List<string>();
long strResult = 0;
Dictionary<string, IList<string>> dicResult = new Dictionary<string, IList<string>>();
solver.Init(values, weights, capacities);
long computedValue = solver.Solve();
string selectItems = $"Selected item indexs : ";
//strResult = computedValue.ToString();
for (int i = 0; i < values.Length; i++)
{
if (solver.BestSolutionContains(i))
{
result.Add(values[i].ToString());
strResult += weights[0, i];
}
}
dicResult.Add(strResult.ToString(), result);
return dicResult;
}
/// <summary>
/// 一维数组转2维数组(矩阵)
/// </summary>
/// <param name="obj"></param>
/// <param name="len">矩阵行数</param>
/// <returns></returns>
public static T[,] OneD_2<T>(T[] obj, int len)
{
if (obj.Length % len != 0)
return null;
int width = obj.Length / len;
T[,] obj2 = new T[len, width];
for (int i = 0; i < obj.Length; i++)
{
obj2[i / width, i % width] = obj[i];
}
return obj2;
}
}
}