Example #1
0
        /// <summary>
        /// Reads the input file and files the items list.
        /// </summary>
        /// <param name="filename">the name of the file to be read</param>
        /// <returns>the weight bound for the instance read</returns>
        public int ReadInput(string filename)
        {
            int bound;
            List <KnapsackItem> tmpList = new List <KnapsackItem>();

            using (StreamReader sr = new StreamReader(filename))
            {
                bound = Convert.ToInt32(sr.ReadLine());
                while (!sr.EndOfStream)
                {
                    string[]     pieces  = sr.ReadLine().Split(',');
                    KnapsackItem newItem = new KnapsackItem(Convert.ToInt32(pieces[0]), Convert.ToInt32(pieces[1]), Convert.ToInt32(pieces[2]));
                    tmpList.Add(newItem);
                }
                tmpList.Sort();
            }
            _items = tmpList;
            return(bound);
        }
Example #2
0
        /// <summary>
        /// Method to find the optimal solution
        /// </summary>
        /// <param name="filename">input file</param>
        public void Solve(string filename)
        {
            _weightLimit = ReadInput(filename);
            CandidateSolution candidate = new CandidateSolution(_items, -1, null);
            CandidateSolution best      = candidate;

            PriorityQueue <int, CandidateSolution> queue = new PriorityQueue <int, CandidateSolution>();

            queue.Add(candidate, ComputeBounds(candidate, ref best));

            while (queue.Count > 0 && queue.MaximumPriority >= best.Value)
            {
                CandidateSolution root = queue.RemoveMaximumPriority();
                int k = root.Index + 1;
                for (int j = k; j < _items.Count; j++)
                {
                    CandidateSolution child = new CandidateSolution(_items, j, root);
                    if (child.Weight <= _weightLimit)
                    {
                        int childBounds = ComputeBounds(child, ref best);
                        if (childBounds > best.Value)
                        {
                            queue.Add(child, childBounds);
                        }
                    }
                }
            }
            _totalValue  = best.Value;
            _totalWeight = best.Weight;
            while (best.Previous != null)
            {
                KnapsackItem tmp = _items[best.Index];
                tmp.SelectionText  = "X";
                _items[best.Index] = tmp;
                best = best.Previous;
            }
        }