Example #1
0
        public void GetHashCode_ReturnsEqualHashCodes_ForEqualKnapsackItems()
        {
            var e1 = new KnapsackItem <char>('a', 1, 2);
            var e2 = new KnapsackItem <char>('a', 1, 2);

            Assert.AreEqual(e1.GetHashCode(), e2.GetHashCode());
        }
Example #2
0
        public void Equals_ReturnsTrue_ForEqualKnapsackItems()
        {
            var e1 = new KnapsackItem <char>('a', 1, 2);
            var e2 = new KnapsackItem <char>('a', 1, 2);

            Assert.IsTrue(e1.Equals(e2));
        }
Example #3
0
        public void GetHashCode_ReturnsDifferentHashCodes_ForDifferentValues()
        {
            var e1 = new KnapsackItem <char>('a', 1, 2);
            var e2 = new KnapsackItem <char>('a', 2, 2);

            Assert.AreNotEqual(e1.GetHashCode(), e2.GetHashCode());
        }
Example #4
0
        public void Equals_ReturnsFalse_ForNonEqualWeights()
        {
            var e1 = new KnapsackItem <char>('a', 1, 2);
            var e2 = new KnapsackItem <char>('a', 1, 3);

            Assert.IsFalse(e1.Equals(e2));
        }
Example #5
0
    public void OnInventoryClick(object[] array)  //当装备被点击的时候,显示装备信息面板
    {
        InventoryItem it     = (InventoryItem)array[0];
        bool          isLeft = (bool)array[1];

        if (it.Inventory.InvenType == InventoryType.Equip)
        {
            KnapsackItem  ki = null;
            KnapsackEquip ke = null;
            if (isLeft)
            {
                ki = (KnapsackItem)array[2];
            }
            else
            {
                ke = (KnapsackEquip)array[2];
            }
            inventory.OnCloseBtnClick();  //保证另一个窗口已经关闭
            equipment.ShowInfo(it, ki, ke, isLeft);
        }
        else
        {
            KnapsackItem ki = (KnapsackItem)array[2];
            equipment.OnCloseBtnClick();  //保证另一个窗口已经关闭
            inventory.ShowInfo(it, ki);
        }

        if ((it.Inventory.InvenType == InventoryType.Equip && isLeft == true) || it.Inventory.InvenType != InventoryType.Equip)
        {
            //在背包里点击装备出售或者点击其他物品 人物穿戴的装备不可出售
            ki = (KnapsackItem)array[2];
            ShowBtn();
            priceLabel.text = ki.it.Inventory.Price * ki.it.Num + "";
        }
    }
Example #6
0
    public void ShowInfo(InventoryItem it, KnapsackItem ki, KnapsackEquip ke, bool isLeft = true)
    {
        gameObject.SetActive(true);
        this.it     = it;
        this.ki     = ki;
        this.ke     = ke;
        this.isLeft = isLeft;
        Vector3 pos = transform.localPosition;

        if (isLeft)
        {
            transform.localPosition = new Vector3(-Mathf.Abs(pos.x), pos.y, pos.z);  //靠左显示
            equipLabel.text         = "装备";
        }
        else
        {
            transform.localPosition = new Vector3(Mathf.Abs(pos.x), pos.y, pos.z);  //靠右显示
            equipLabel.text         = "卸下";
        }
        icon.spriteName  = it.Inventory.Icon;
        nameLabel.text   = it.Inventory.Name;
        hpLabel.text     = it.Inventory.Hp + "";
        damageLabel.text = it.Inventory.Damage + "";
        levelLabel.text  = it.Level + "";
        powerLabel.text  = it.Inventory.Power + "";
        info.text        = it.Inventory.Info;
    }
Example #7
0
    public void PickUp()
    {
        int    index  = Random.Range(0, equipmentNames.Length);
        string name   = equipmentNames[index];
        bool   isFind = false;

        foreach (GameObject cell in cells)
        {
            if (cell.transform.childCount != 0)
            {
                KnapsackItem currentItem = cell.GetComponentInChildren <KnapsackItem>();
                string       currentName = currentItem.GetComponent <UISprite>().spriteName;
                if (currentName == name)
                {
                    isFind = true;
                    UILabel label = currentItem.GetComponentInChildren <UILabel>();
                    currentItem.AddCount(1);
                    return;
                }
            }
        }
        if (isFind == false)
        {
            foreach (GameObject item in cells)
            {
                if (item.transform.childCount == 0)
                {
                    GameObject go = NGUITools.AddChild(item, this.item);
                    go.GetComponent <UISprite>().spriteName = name;
                    go.transform.localPosition = Vector3.zero;
                    return;
                }
            }
        }
    }
Example #8
0
        bool DoesSolutionExist(int itemsRemaining, int currentPrice,
                               int currentWeight, int maxRemainingPrice, DecisionKnapsackInstance knapsackInstance)
        {
            numberOfSteps++;

            if (currentWeight > knapsackInstance.KnapsackSize)
            {
                return(false);
            }
            if (maxRemainingPrice < knapsackInstance.MinimalPrice)
            {
                return(false);
            }

            if (itemsRemaining == 0)
            {
                return(currentWeight <= knapsackInstance.KnapsackSize && currentPrice >= knapsackInstance.MinimalPrice);
            }

            KnapsackItem currentItem = knapsackInstance.Items[itemsRemaining - 1];

            //Put item in
            if (DoesSolutionExist(itemsRemaining - 1, currentPrice + currentItem.Price, currentWeight + currentItem.Weight, maxRemainingPrice, knapsackInstance))
            {
                return(true);
            }
            //Don't put item in
            if (DoesSolutionExist(itemsRemaining - 1, currentPrice, currentWeight, maxRemainingPrice - currentItem.Price, knapsackInstance))
            {
                return(true);
            }
            return(false);
        }
Example #9
0
    public void PutItem(KnapsackItem item, ItemGrid itemGrid, ItemGrid surfaceGrid)
    {
        if (!surfaceGrid)
        {
            return;
        }

        KnapsackItem newItem = surfaceGrid.NowItem;

        if (!newItem)
        {
            surfaceGrid.PutItem(item);
        }
        else
        {
            if (newItem.ItemID == item.ItemID)
            {
                newItem.UpdateItemCount(item.ItemCount);
                Destroy(item.gameObject);
            }
            else
            {
                surfaceGrid.PutItem(item);
                itemGrid.PutItem(newItem);
            }
        }
    }
    public void PutItem(KnapsackItem item)
    {
        NowItem      = item;
        item.NowGrid = this;
        var itemTS = item.transform;

        itemTS.SetParent(transform);
        itemTS.localPosition = Vector3.zero;
    }
Example #11
0
 public void ShowInfo(InventoryItem it, KnapsackItem ki)
 {
     gameObject.SetActive(true);
     this.it         = it;
     this.ki         = ki;
     icon.spriteName = it.Inventory.Icon;
     nameLabel.text  = it.Inventory.Name;
     info.text       = it.Inventory.Info;
     btnLabel.text   = "批量使用(" + it.Num + ")";
 }
Example #12
0
        private static int DoKnapsackProblem_Recursive(int knapsackCap, KnapsackItem[] itemsToPack, bool getListOfItemsPacked = true)
        {
            double dReturn = -1;
            List<KnapsackItem> packedItems = new List<KnapsackItem>();
            KnapsackClass sack = new KnapsackClass(knapsackCap);

            if (getListOfItemsPacked)
            {
                dReturn = sack.Pack_Recursive(itemsToPack, out packedItems);
                Console.WriteLine(string.Format("Total value of packed items: {0}{1}Packed {3} items:{1}{2}", dReturn, Environment.NewLine, Utilities.FormatPrintList<KnapsackItem>(packedItems, true), packedItems.Count));
            }
            else
            {
                dReturn = sack.Pack_Recursive(itemsToPack);
                Console.WriteLine(string.Format("Total value of packed items: {0}{1}", dReturn, Environment.NewLine));
            }
            return (int)dReturn;
        }
Example #13
0
        public void SearchTest()
        {
            var capacity = 14;
            var items    = new KnapsackItem[]
            {
                new KnapsackItem(weight: 1, value: 13),
                new KnapsackItem(weight: 6, value: 5),
                new KnapsackItem(weight: 6, value: 4),
                new KnapsackItem(weight: 5, value: 2)
            };

            var result    = KnapsackProblem.Search(items, capacity);
            var backTrack = KnapsackProblem.GetBackTrack(result, items, capacity, items.Length);

            const int expectedSumValue = 22;

            Assert.IsTrue(backTrack.Sum(i => i.Value) == expectedSumValue, "Incorrectly found the sum of the values");
        }
Example #14
0
        public List<KnapsackItem> GetItemsPacked(KnapsackItem[] allItems, double[,] subProblemValues)
        {
            List<KnapsackItem> packedItems = new List<KnapsackItem>();
            int i = allItems.Length, j = this.Capacity, shiftedIndex = i - 1;

            //Start at end and work backwards
            while (shiftedIndex >= 0 && j >= 0)
            {
                double itemValue = allItems[shiftedIndex].Value;
                int itemSize = allItems[shiftedIndex].Size;

                if (itemSize > j)
                {
                    i = i - 1;
                }
                else
                {
                    double case1 = subProblemValues[i - 1, j];                          //Case 1: i-th item is not in the optimal solution
                    double case2 = subProblemValues[i - 1, j - itemSize] + itemValue;   //Case 2: i-th item is in the optimal solution

                    if (subProblemValues[i, j] == case1)
                    {
                        //Case 1: i-th item is not in the optimal solution
                        i = i - 1;
                    }
                    else
                    {
                        //Case 2: i-th item is in the optimal solution
                        packedItems.Add(allItems[shiftedIndex]);
                        i = i - 1;
                        j = j - itemSize;
                    }
                }
                shiftedIndex = i - 1;
            }

            return packedItems;
        }
Example #15
0
        protected double Pack(KnapsackItem[] items, bool returnListOfItemsPacked, out List<KnapsackItem> packedItems)
        {
            double[,] subProblemValues = new double[items.Length + 1, this.Capacity + 1];
            packedItems = new List<KnapsackItem>();

            if (this.Capacity <= 0)
            {
                throw new Exception(string.Format("Knapsack capacity is currently {0} where it should be an int value greater than 0. " +
                                                   "Please set the capacity to a positive non-zero int before retrying", this.Capacity));
            }

            for (int i = 1; i <= items.Length; i++)
            {
                for (int j = 0; j <= this.Capacity; j++)
                {
                    int shiftedIndex = i - 1;
                    double valueAtIndex;

                    if (shiftedIndex < 0)
                    {
                        throw new IndexOutOfRangeException();
                    }

                    double itemValue = items[shiftedIndex].Value;
                    int itemSize = items[shiftedIndex].Size;

                    if (itemSize > j)
                    {
                        //Edge case, item is larger than remaining capacity
                        valueAtIndex = subProblemValues[i - 1, j];
                    }
                    else
                    {
                        //Use pre-computed sub problem answers
                        double case1 = subProblemValues[i - 1, j];                          //Case 1: i-th item is not in the optimal solution
                        double case2 = subProblemValues[i - 1, j - itemSize] + itemValue;   //Case 2: i-th item is in the optimal solution

                        valueAtIndex = Math.Max(case1, case2);
                    }

                    subProblemValues[i, j] = valueAtIndex;
                }
            }

            if (returnListOfItemsPacked)
            {
                packedItems = this.GetItemsPacked(items, subProblemValues);
            }

            return subProblemValues[items.Length, this.Capacity];
        }
Example #16
0
        public void ToString_ReturnsValidValue()
        {
            var item = new KnapsackItem <char>('a', 1.2, 3);

            Assert.AreEqual($"a ({1.20:N2}, 3)", item.ToString());
        }
Example #17
0
        public void Value_ReturnsValidValue()
        {
            var item = new KnapsackItem <char>('a', 10, 20);

            Assert.AreEqual(10, item.Value);
        }
Example #18
0
 void ClearItem()
 {
     it = null;
     ki = null;
 }
Example #19
0
        public void Weight_ReturnsValidValue()
        {
            var item = new KnapsackItem <char>('a', 10, 20);

            Assert.AreEqual(20, item.Weight);
        }
Example #20
0
        public void Equals_ReturnsFalse_ForNullObject()
        {
            var e1 = new KnapsackItem <char>('a', 1, 2);

            Assert.IsFalse(e1.Equals(null));
        }
Example #21
0
        protected override void TryAddCell(int currentIndexValue, int currentItemIndex, int maxWeight, Queue <int> toVisitNext, KnapsackItem item = null)
        {
            var currentCell = memoryTable[currentIndexValue, currentItemIndex];

            var newWeight = currentCell.Value;
            var newPrice  = currentIndexValue;

            if (item != null)
            {
                newPrice  += item.Price;
                newWeight += item.Weight;
            }
            //Weight limit reached
            if (newWeight > maxWeight)
            {
                return;
            }

            var nextCell = memoryTable[newPrice, currentItemIndex + 1];

            //Add the new cell into the table if it is better than the one previously placed there
            if (nextCell == null || nextCell.Value > newWeight)
            {
                memoryTable[newPrice, currentItemIndex + 1] = new DPCell
                {
                    AddedItem    = (item != null),
                    PreviousCell = currentCell,
                    Value        = newWeight
                };
                toVisitNext.Enqueue(newPrice);
            }
        }
Example #22
0
 public double Pack_Recursive(KnapsackItem[] items)
 {
     List<KnapsackItem> dummy = new List<KnapsackItem>();
     return this.Pack_Recursive(items, false, out dummy);
 }
Example #23
0
        public List<KnapsackItem> GetItemsPacked(KnapsackItem[] allItems, Dictionary<Tuple<double, int>, double> subProblemValues)
        {
            List<KnapsackItem> packedItems = new List<KnapsackItem>();
            int i = allItems.Length, j = this.Capacity, shiftedIndex = i - 1;

            //Start at end and work backwards
            while (i > 0 && j >= 0)
            {
                double itemValue = allItems[shiftedIndex].Value;
                int itemSize = allItems[shiftedIndex].Size;

                if (itemSize > j)
                {
                    i = i - 1;
                }
                else if (subProblemValues.Keys.Count == 1)
                {
                    packedItems.Add(allItems[shiftedIndex]);
                    i = i - 1;
                    j = j - itemSize;
                }
                else
                {
                    Tuple<double, int> case1key = new Tuple<double, int>(i - 1, j);
                    Tuple<double, int> case2Key = new Tuple<double, int>(i - 1, j - itemSize);

                    if (!subProblemValues.ContainsKey(case1key) && !subProblemValues.ContainsKey(case2Key))
                    {
                        throw new Exception("Something has gone wrong! Neither key is in the collection!");
                    }
                    else if (!subProblemValues.ContainsKey(case1key))
                    {
                        //Case 1 key not in collection, must be case 2
                        packedItems.Add(allItems[shiftedIndex]);
                        i = i - 1;
                        j = j - itemSize;
                    }
                    else if (!subProblemValues.ContainsKey(case2Key))
                    {
                        //Case 2 key not in collection, must be case 1
                        i = i - 1;
                    }
                    else  //Both keys present in dictionary
                    {
                        double case1 = subProblemValues[case1key];             //Case 1: i-th item is not in the optimal solution
                        double case2 = subProblemValues[case2Key] + itemValue; //Case 2: i-th item is in the optimal solution

                        if (subProblemValues[new Tuple<double, int>(i, j)] == case1)
                        {
                            //Case 1: i-th item is not in the optimal solution
                            i = i - 1;
                        }
                        else
                        {
                            //Case 2: i-th item is in the optimal solution
                            packedItems.Add(allItems[shiftedIndex]);
                            i = i - 1;
                            j = j - itemSize;
                        }
                    }
                }
                shiftedIndex = i - 1;
            }

            return packedItems;
        }
Example #24
0
        private double GetSubproblemSolution(int indexIntoSubProbAns, int weightIndex, ref KnapsackItem[] items, ref Dictionary<Tuple<double, int>, double> subProbs)
        {
            double dReturn = -1;
            Tuple<double, int> key;

            if (indexIntoSubProbAns < 0)
            {
                throw new IndexOutOfRangeException();
            }
            else if (indexIntoSubProbAns == 0)
            {
                key = new Tuple<double, int>(0, weightIndex);
                if (!subProbs.ContainsKey(key))
                {
                    subProbs.Add(key, 0);
                }
            }
            else
            {
                int indexIntoItemsList = indexIntoSubProbAns - 1;
                KnapsackItem item = items[indexIntoItemsList];
                key = new Tuple<double, int>(indexIntoSubProbAns, weightIndex);
                if (!subProbs.ContainsKey(key))
                {
                    if (item.Size > weightIndex)
                    {
                        //Recurse
                        double edgeCaseSubAns = this.GetSubproblemSolution(indexIntoSubProbAns - 1, weightIndex, ref items, ref subProbs);

                        if (!subProbs.ContainsKey(key))
                        {
                            subProbs.Add(key, edgeCaseSubAns);
                        }
                    }
                    else
                    {
                        //Recurse
                        double case1SubAns = this.GetSubproblemSolution(indexIntoSubProbAns - 1, weightIndex, ref items, ref subProbs);                           //Case 1: i-th item is not in the optimal solution
                        double case2SubAns = this.GetSubproblemSolution(indexIntoSubProbAns - 1, weightIndex - item.Size, ref items, ref subProbs) + item.Value;  //Case 2: i-th item is in the optimal solution
                        if (!subProbs.ContainsKey(key))
                        {
                            subProbs.Add(key, Math.Max(case1SubAns, case2SubAns));
                        }
                    }
                }
            }
            dReturn = subProbs[key];
            return dReturn;
        }
Example #25
0
 public double Pack_Recursive(KnapsackItem[] items, out List<KnapsackItem> packedItems)
 {
     return this.Pack_Recursive(items, true, out packedItems);
 }
Example #26
0
 protected abstract void TryAddCell(int currentIndexValue, int currentItemIndex, int maxWeight, Queue <int> toVisitNext, KnapsackItem item = null);
Example #27
0
        protected double Pack_Recursive(KnapsackItem[] items, bool returnListOfItemsPacked, out List<KnapsackItem> packedItems)
        {
            Dictionary<Tuple<double, int>, double> subProblemHashTable = new Dictionary<Tuple<double, int>, double>();
            packedItems = new List<KnapsackItem>();
            double dReturn = -1;
            Tuple<double, int> finalKey = new Tuple<double, int>(items.Length, this.Capacity);

            if (this.Capacity <= 0)
            {
                throw new Exception(string.Format("Knapsack capacity is currently {0} where it should be an int value greater than 0. " +
                                                   "Please set the capacity to a positive non-zero int before retrying", this.Capacity));
            }

            if (items.Length <= 0)
            {
                subProblemHashTable.Add(finalKey, 0);
            }
            else if (items.Length == 1)
            {
                if (items[0].Size <= this.Capacity)
                {
                    subProblemHashTable.Add(finalKey, items[0].Value);
                }
                else
                {
                    subProblemHashTable.Add(finalKey, 0);
                }
            }
            else
            {
                int shiftedItemIndex = items.Length - 1;
                KnapsackItem lastItem = items[shiftedItemIndex];
                double case1SubAns = this.GetSubproblemSolution(shiftedItemIndex, this.Capacity, ref items, ref subProblemHashTable);                                   //Case 1: i-th item is not in the optimal solution
                double case2SubAns = this.GetSubproblemSolution(shiftedItemIndex, this.Capacity - lastItem.Size, ref items, ref subProblemHashTable) + lastItem.Value;  //Case 2: i-th item is in the optimal solution
                subProblemHashTable.Add(finalKey, Math.Max(case1SubAns, case2SubAns));
            }

            dReturn = subProblemHashTable[finalKey];

            if (returnListOfItemsPacked)
            {
                packedItems = this.GetItemsPacked(items, subProblemHashTable);
            }

            return dReturn;
        }