// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; using System.Linq; namespace E { public class Optimizer { public struct Result { public double Value; public int NoBuckets; public int[] Buckets; } private static void BruteForce(double targetval, List bucketvals, int ix, int len, int[] work, ref Result res) { for(int i = ix; i < bucketvals.Count; i++) { work[len] = i; len++; double val = work.Take(len).Sum(v => bucketvals[v]); if(val < targetval) { if(i < bucketvals.Count - 1) { BruteForce(targetval, bucketvals, i + 1, len, work, ref res); } } else { if(val < res.Value) { res.Value = val; res.NoBuckets = len; res.Buckets = (int[])work.Clone(); } } len--; } } public static Result BruteForce(double targetval, List bucketvals) { Result res = new Result(); res.Value = double.MaxValue; res.NoBuckets = 0; res.Buckets = new int[bucketvals.Count]; BruteForce(targetval, bucketvals, 0, 0, new int[bucketvals.Count], ref res); return res; } } public class Program { private static void Test(double targetval, List bucketvals) { Optimizer.Result res = Optimizer.BruteForce(targetval, bucketvals); Console.WriteLine("{0} : {1}", res.Value, String.Join(",", res.Buckets.Take(res.NoBuckets).Select(v => v.ToString()).ToArray())); } public static void Main(string[] args) { List a = new List{ 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9 }; Test(5.0, a); Test(5.1, a); Test(5.2, a); Test(5.3, a); Test(5.325, a); Test(5.350, a); Test(5.4, a); Test(10.0, a); } } }