private static void Main(string[] args) { Action <object> write = Console.Write; const int N = 5; const int maxWeight = 8; var items = new List <Item>(); for (var i = 0; i < N; i++) { items.AddRange(new List <Item> { new Item { w = 1, v = 1 }, new Item { w = 2, v = 3 }, new Item { w = 3, v = 4 }, new Item { w = 4, v = 5 }, new Item { w = 5, v = 6 }, }); Knapsack.Init(items, maxWeight); Knapsack.Run(); Knapsack.Print(write); Console.ReadKey(); } }
public WikipediaProblemSet() { Knapsack = new Knapsack(67, 99, false); var items = InitialiseItems(); DataSet = SortByUnitProfitDescending(items); }
public MultiConstraintProblemSet() { Knapsack = new Knapsack(15, 3, false); var items = InitialiseItems(); DataSet = SortByUnitProfitDescending(items); }
/// <summary> /// Conventional 2-approximation algorithm for 0-1KP /// Result, r holds to outcome that optimal solution, z* is less than or equal to 2r /// i.e. 2r provides upper bound for profit /// </summary> /// <returns></returns> public static int Conventional2Approx_KP(List <Item> items, Knapsack knapsack) { ItemGroup group = new ItemGroup(); List <Item> sortedItems = UtilFunctions.SortByUnitProfitDescending(items); // Fill until we reach critical item foreach (Item item in sortedItems) { if (group.TotalWeight() + item.Weight <= knapsack.Capacity) { group.AddItem(item); } else // we have reached critical item { var criticalItem = item; // 2-approximation solution is one with higher profit value of group or criticalItem if (criticalItem.Value > group.TotalValue()) { group = (ItemGroup) new ItemGroup().Add(criticalItem); } break; } } return(group.TotalValue()); }
private static void SolveKnapSackProblem() { Knapsack kn = new Knapsack(); Random r = new Random(); kn.SolveKnapsack(r.Next(20), r.Next(1000)); }
public override void Ejecutar(Knapsack theProblem, Random myRandom) { var timeBegin = DateTime.Now; EFOs = 0; var s = new Solution(theProblem, this); s.RandomInitialization(myRandom); while (EFOs < MaxEFOs) { var r = new Solution(s); r.Tweak(myRandom); if (r.Fitness > s.Fitness) // Maximization { s = r; } if (s.IsOptimalKnown()) { break; } if ((DateTime.Now - timeBegin).TotalMilliseconds >= 700) { break; } } BestSolution = s; }
/// <summary> /// Uses greedy algorithm to get approximation of highest value for profit /// </summary> /// <returns></returns> public static double LPRelaxedApprox_KP(List <Item> items, Knapsack knapsack) { ItemGroup group = new ItemGroup(); List <Item> sortedItems = UtilFunctions.SortByUnitProfitDescending(items); Item criticalItem = new Item("", 0, 0); double criticalItemFraction = 0; // Fill until we reach critical item foreach (Item item in sortedItems) { if (group.TotalWeight() + item.Weight <= knapsack.Capacity) { group.AddItem(item); } else // we have reached critical item { criticalItem = item; criticalItemFraction = (knapsack.Capacity - group.TotalWeight()) / (double)criticalItem.Weight; break; } } // Add fractional value of next item double maxProfitValue = group.TotalValue() + criticalItem.Value * criticalItemFraction; return(maxProfitValue); }
public void KnapsackShouldReturnOptimizedValue(int[] itemValues, int[] itemWeights, int capacity, int expected) { var knapsack = new Knapsack(itemValues, itemWeights, capacity); var res = knapsack.MaximizedValue; Assert.Equal(expected, res); }
public void KnapsackShouldReturnOptimizedSet(int[] itemValues, int[] itemWeights, int capacity, int[] expected) { var knapsack = new Knapsack(itemValues, itemWeights, capacity); var res = knapsack.GetSelectedItems().OrderBy(x => x); Assert.Equal(expected, res); }
public void Execute(Knapsack theKnapsack, Random theAleatory, Solution s, double[] penalties, double regulationParam) { this.MyKnapsack = theKnapsack; this.MyAleatory = theAleatory; this.CurrentEFOs = 0; Curve = new List <double>(); s._myContainer = this; // Hill Climbing Curve.Add(s.Fitness); while (this.CurrentEFOs < MaxEFOs) { var r = new Solution(s); r.Tweak(); r.AlteredFunction(penalties, regulationParam); if (r.AlteredFitness > s.AlteredFitness) { s = new Solution(r); } Curve.Add(s.Fitness); if (Math.Abs(s.Fitness - MyKnapsack.OptimalKnown) < 1e-10) { break; } } MyBestSolution = s; }
public void TestSmall() { var ks = new Knapsack(); var items = new[] { new Item() { Value = 3, Weight = 4 }, new Item() { Value = 2, Weight = 3 }, new Item() { Value = 4, Weight = 2 }, new Item() { Value = 4, Weight = 2 }, }; var res = ks.Compute(items, 6); Assert.That(res, Is.EqualTo(8)); }
public void Knapsack() { var items = new List <Knapsack.Item> { new Knapsack.Item { size = 3, val = 4 }, new Knapsack.Item { size = 4, val = 5 }, new Knapsack.Item { size = 7, val = 10 }, new Knapsack.Item { size = 8, val = 11 }, new Knapsack.Item { size = 9, val = 13 } }; Knapsack kc = new Knapsack(items); var res = kc.KnapSimple(17); var res2 = kc.KnapSimple2(items.Count - 1, 17); }
public override void Execute(Knapsack theKnapsack, Random theAleatory, Solution s = null) { MyKnapsack = theKnapsack; MyAleatory = theAleatory; CurrentEFOs = 0; Curve = new List <double>(); s = new Solution(this); s.RandomInitialization(); Curve.Add(s.Fitness); while (CurrentEFOs < MaxEFOs) { var r = new Solution(this); r.RandomInitialization(); if (r.Fitness > s.Fitness) { s = new Solution(r); } Curve.Add(s.Fitness); if (Math.Abs(s.Fitness - MyKnapsack.OptimalKnown) < 1e-10) { break; } } MyBestSolution = s; }
static void Main() { var k = new Knapsack( new Category("Albums", new Element("Rattle And Hum", 300, 90) , new Element("A Hard Day's Night", 7, 60)), new Category("Books", new Element("1984", 4, 50) , new Element("Anna Karenina", 3, 50) , new Element("The Bourne Identity", 5, 40))); //var k = new Knapsack( // new Category("voce", new Element("jabuka", 3, 2), new Element("kruska", 7, 5)), // new Category("povrce", new Element("krumpir", 3, 3), new Element("kupus", 4, 4)), // new Category("mlijecni", new Element("jogurt", 10, 6), new Element("kefir", 6, 5), // new Element("mlijeko", 5, 4))); k.Run(90); k.PrintTable(20); Console.WriteLine(); Console.WriteLine("Max value that can be achieved: " + k.GetMaxValue()); var opt = k.GetOptimaElements(); if (opt != null) { Console.WriteLine("Optimal items: " + string.Join(", ", opt.Select(itm => itm.Name).ToList())); } }
public static void Show() { #region 找零问题 { double origAmount = 0.63;//原始总金额 double toChange = origAmount; double remainAmount = 0.0; int[] coins = new int[4];//4种面值 1-5-10-25 MakeChange(origAmount, remainAmount, coins); } #endregion #region 夫曼 { string input; Console.Write("请输入一个字符串: "); input = Console.ReadLine(); TreeList treeList = new TreeList(input); for (int i = 0; i < input.Length; i++) { treeList.AddSign(input[i].ToString()); } treeList.SortTree(); while (treeList.Length() > 1) { treeList.MergeTree(); } TreeList.MakeKey(treeList.RemoveTree(), ""); string newStr = TreeList.Translate(input); string[] signTable = treeList.GetSignTable(); string[] keyTable = treeList.GetKeyTable(); for (int i = 0; i <= signTable.Length - 1; i++) { Console.WriteLine(signTable[i] + ": " + keyTable[i]); } Console.WriteLine("The original string is " + input.Length * 16 + " bits long."); Console.WriteLine("The new string is " + newStr.Length + " bits long."); Console.WriteLine("The coded string looks like this:" + newStr); } #endregion #region MyRegion { Carpet c1 = new Carpet("Frieze", 1.75F, 12); Carpet c2 = new Carpet("Saxony", 1.82F, 9); Carpet c3 = new Carpet("Shag", 1.5F, 13); Carpet c4 = new Carpet("Loop", 1.77F, 10); ArrayList rugs = new ArrayList(); rugs.Add(c1); rugs.Add(c2); rugs.Add(c3); rugs.Add(c4); rugs.Sort(); Knapsack k = new Knapsack(25); k.FillSack(rugs); Console.WriteLine(k.GetItems()); } #endregion }
public void TestKnapsack7ItemsCapacity19() { var items = new Item[] { new Item { Weight = 5, Price = 30 }, new Item { Weight = 8, Price = 120 }, new Item { Weight = 7, Price = 10 }, new Item { Weight = 0, Price = 20 }, new Item { Weight = 4, Price = 50 }, new Item { Weight = 5, Price = 80 }, new Item { Weight = 2, Price = 10 }, }; var knapsackCapacity = 19; var itemsTaken = Knapsack.FillKnapsack(items, knapsackCapacity); var totalWeight = itemsTaken.Sum(i => i.Weight); var totalPrice = itemsTaken.Sum(i => i.Price); Assert.AreEqual(19, totalWeight); Assert.AreEqual(280, totalPrice); }
public KellererBookProblemSet() { Knapsack = new Knapsack(9, 3, false); var items = InitialiseItems(); DataSet = SortByUnitProfitDescending(items); }
public override void Ejecutar(Knapsack theProblem, Random myRandom) { EFOs = 0; var harmonyMemory = new List <Solution>(); for (var i = 0; i < HarmonyMemorySize; i++) { var s = new Solution(theProblem, this); s.RandomInitialization(myRandom); harmonyMemory.Add(s); } harmonyMemory.Sort((x, y) => - 1 * x.Fitness.CompareTo(y.Fitness)); while (EFOs < MaxEFOs) { var improvise = new Solution(theProblem, this); improvise.Improvisation(harmonyMemory, Hmcr, Par, myRandom); improvise.Repare(myRandom); improvise.Complete(myRandom, new List <int>()); improvise.Evaluate(); //replace the worst harmonyMemory.Add(improvise); harmonyMemory.Sort((x, y) => - 1 * x.Fitness.CompareTo(y.Fitness)); harmonyMemory.RemoveRange(HarmonyMemorySize, 1); if (harmonyMemory[0].IsOptimalKnown()) { break; } } BestSolution = harmonyMemory[0]; }
public NonConformingProblemSet() { Knapsack = new Knapsack(15, 3, false); var items = InitialiseItems(); DataSet = SortByUnitProfitDescending(items); }
private void Awake() { _instance = this; priceText = transform.Find("InventoryImage/JiaGeText").GetComponent <Text>(); chuosheButton = transform.Find("InventoryImage/ChuoSheImage").GetComponent <Button>(); equipPopup = GameObject.Find("EquipPopupImage").GetComponent <EquipPopup>(); inventoryPopup = GameObject.Find("InventoryPopupImage").GetComponent <InventoryPopup>(); }
override protected void Awake() { base.Awake(); if (null == _instance) { _instance = this; } }
public void mutateFuntion_shouldSwitchBoolean() { var item = new Knapsack("00011"); item.Mutate(1.0); Assert.AreNotEqual("00011", item.GetGenomes()); }
public Solution(Knapsack theProblem, Algorithm theAlgorithm) { MyProblem = theProblem; MyAlgorithm = theAlgorithm; Objects = new int[MyProblem.TotalItems]; Weight = 0; Fitness = 0; }
public void TestMethod1() { Knapsack knapsack = new Knapsack(); var val = knapsack.Input(new List <long> { 1, 6, 9, 13, 14 }, 12); Assert.Equal(1, 1); }
public void Init() { sack = new Knapsack(); generator = new KeyGenerator(new List <BigInteger>() { 2, 7, 11, 21, 42, 89, 180, 354 }, 881, 588); sack.generator = generator; }
public void TestEmpty() { var k = new Knapsack(); Assert.IsNotNull(k.Categories); Assert.IsNotNull(k.Table); Assert.AreEqual(0, k.Categories.Count); Assert.AreEqual(0, k.Table.Count); }
public void TestOverloadedConstructorEmpty() { var k = new Knapsack(new Category("c1"), new Category("c2")); Assert.IsNotNull(k.Categories); Assert.IsNotNull(k.Table); Assert.AreEqual(2, k.Categories.Count); Assert.AreEqual(0, k.Table.Count); }
public void KnapsackTest() { int result = 220; var testClient = new Knapsack(); var expectedResult = testClient.KnapsackSolution(maxCapacity, weights, values, itemCount); Assert.AreEqual(result, expectedResult); }
private void CryptoClientForm_Load(object sender, EventArgs e) { this.tbSrcPath.Text = ".\\" + this.defaultSrcPath; this.tbDstPath.Text = ".\\" + this.defaultDstPath; this.defaultSrcPath = AppDomain.CurrentDomain.BaseDirectory.ToString() + this.defaultSrcPath; this.defaultDstPath = AppDomain.CurrentDomain.BaseDirectory.ToString() + this.defaultDstPath; string[] srcDicFiles = Directory.GetFiles(this.defaultSrcPath); foreach (string f in srcDicFiles) { this.lbFilesToEncrypt.Items.Add(f); } string[] dstDicFiles = Directory.GetFiles(this.defaultDstPath); foreach (string f in dstDicFiles) { this.lbEncryptedFiles.Items.Add(f); } this.CreateNewFileWatcher(); ICryptoLibrary[] algorithams = new ICryptoLibrary[4]; algorithams[0] = new SimpleSubstitution(); algorithams[1] = new XXTEA(); algorithams[2] = new SHA2(); algorithams[3] = new Knapsack(); specs = new Dictionary <string, byte[]>(); // add algoritams in drop down ToolStripMenuItem menu = new ToolStripMenuItem("Algorithams"); ToolStripMenuItem item; for (int i = 0; i < algorithams.Length; i++) { item = new ToolStripMenuItem(algorithams[i].ToString()); item.Tag = algorithams[i]; menu.DropDownItems.Add(item); if (i == 0) { this.algoritham = algorithams[i]; } } menu.DropDownItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.OnClickedItem); this.msOptions.Items.Add(menu); this.Init(); tbN.KeyPress += this.tbKey_KeyPress; tbM.KeyPress += this.tbKey_KeyPress; tbIM.KeyPress += this.tbKey_KeyPress; lbHint.Visible = false; }
void Awake() { instance = this; tween = GetComponent <TweenPosition>(); equipment = transform.Find("equipment_info/equipment_bg").GetComponent <EquipmentInfo>(); inventory = transform.Find("inventory_info/inventory_bg").GetComponent <InventoryInfo>(); priceLabel = transform.Find("inventory/price_bg/price").GetComponent <UILabel>(); sellBtn = transform.Find("inventory/sell_btn").GetComponent <UIButton>(); closeBtn = transform.Find("close_btn").GetComponent <UIButton>(); }
private static void Main() { List<Item> knapsackItems = new List<Item>(); knapsackItems.Add(new Item { Name = "beer", Weight = 3, Value = 2, }); knapsackItems.Add(new Item { Name = "vodka", Weight = 8, Value = 12, }); knapsackItems.Add(new Item { Name = "cheese", Weight = 4, Value = 5, }); knapsackItems.Add(new Item { Name = "nuts", Weight = 1, Value = 4, }); knapsackItems.Add(new Item { Name = "ham", Weight = 2, Value = 3, }); knapsackItems.Add(new Item { Name = "whiskey", Weight = 8, Value = 13, }); var bag = new Knapsack(10); bag.Calculate(knapsackItems); bag.All(x => { Console.WriteLine(x); return true; }); Console.WriteLine("Max weight: " + bag.Sum(x => x.Weight)); Console.WriteLine("Max value: " + bag.Sum(x => x.Value)); }
void Awake() { _instance = this; equipPopup = transform.Find("EquipPopup").GetComponent<EquipPopup>(); inventoryPopup = transform.Find("InventoryPopup").GetComponent<InventoryPopup>(); saleButton = transform.Find("Inventory/ButtonSale").GetComponent<UIButton>(); priceLabel = transform.Find("Inventory/PriceBg/Label").GetComponent<UILabel>(); tween = this.GetComponent<TweenPosition>(); closeKnapsackButton = transform.Find("CloseButton").GetComponent<UIButton>(); DisableButton(); EventDelegate ed = new EventDelegate(this,"OnSale"); saleButton.onClick.Add(ed); EventDelegate ed2 = new EventDelegate(this,"OnKnapsackClose"); closeKnapsackButton.onClick.Add(ed2); }
public Configuration(Configuration configuration) { _knapsack = configuration._knapsack; _presence = new bool[configuration._presence.Length]; configuration._presence.CopyTo(_presence, 0); }
public Configuration(Knapsack knapsack) { _knapsack = knapsack; _presence = new bool[knapsack.ItemValues.Length / 2]; }
static void Main(string[] args) { Knapsack knap = new Knapsack(); knap.Run(); }