المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Combination Algorithm



C# Programming
10-28-2013, 02:31 PM
I am trying to write a small code to find the possible combinations from a list of integer values which when added is equal to the input value or somewhat nearing. List comb = new List() { 618, 350, 308, 300, 250, 232, 200, 128 }; The above list contains the integer values from which the proper combination has to be generated The combination should have least number of values i.e., greatest number has to used most Example: If Input from User [Value = 2386] Combination 1 = 618 + 350 + 308 + 300 + 250 + 232 + 200 + 128 Combination 2 = 618 + 618 + 618 + 300 + 232 I have used the below code, but have missed some logic.

public static void Main(string[] args) { //subtotal list List totals = new List(new int[] { 618, 350, 308, 300, 250, 232, 200, 128 }); // get matches List results = KnapSack.MatchTotal(2682, totals); // print results foreach (var result in results) { Console.WriteLine(string.Join(",", result)); } Console.WriteLine("Done."); } internal static List MatchTotal(int theTotal, List subTotals) { List results = new List(); while (subTotals.Contains(theTotal)) { results.Add(new int[1] { theTotal }); subTotals.Remove(theTotal); } if (subTotals.Count == 0) return results; subTotals.Sort(); double mostNegativeNumber = subTotals[0]; if (mostNegativeNumber >
Is there any other way other than the above to get combinations