Exemplo n.º 1
0
        public Solution Solve(Knapsack k)
        {
            bool[] usedItems = new bool[k.Items.Length];
            usedItems.Populate(false);
            int value             = 0;
            var sorted            = SortedItems(k);
            int remainingCapacity = k.Capacity;

            foreach (Knapsack.Item i in sorted)
            {
                if (i.Size <= remainingCapacity)
                {
                    usedItems[i.Index] = true;
                    value             += i.Value;
                    remainingCapacity -= i.Size;
                }
            }

            return(new Solution()
            {
                IsOptimal = false,
                Value = value,
                UsedItems = usedItems
            });
        }
Exemplo n.º 2
0
        public Solution Solve(Knapsack k)
        {
            int[][] table = new int[k.Items.Length][];

            //first column
            table[0] = new int[k.Capacity + 1];
            int iSize  = k.Items[0].Size;
            int iValue = k.Items[0].Value;

            for (int c = 0; c <= k.Capacity; c++)
            {
                table[0][c] = (iSize <= c) ? iValue : 0;
            }

            // the rest
            for (int i = 1; i < k.Items.Length; i++)
            {
                table[i] = new int[k.Capacity + 1];
                iSize    = k.Items[i].Size;
                iValue   = k.Items[i].Value;
                for (int c = 0; c <= k.Capacity; c++)
                {
                    if (iSize > c)
                    {
                        table[i][c] = table[i - 1][c];
                    }
                    else
                    {
                        table[i][c] = Math.Max(table[i - 1][c], table[i - 1][c - iSize] + iValue);
                    }
                }
            }

            // backtrack for optimal solution
            bool[] usedItems = new bool[k.Items.Length];
            int    row       = k.Capacity;

            for (int col = k.Items.Length - 1; col > 0; col--)
            {
                if (table[col][row] != table[col - 1][row])
                {
                    usedItems[col] = true;
                    row            = row - k.Items[col].Size;
                }
                else
                {
                    usedItems[col] = false;
                }
            }
            usedItems[0] = table[0][row] != 0;

            return(new Solution()
            {
                IsOptimal = true,
                Value = table[k.Items.Length - 1][k.Capacity],
                UsedItems = usedItems
            });
        }
Exemplo n.º 3
0
 public Solution Solve(Knapsack k)
 {
     return(new Solution()
     {
         IsOptimal = false,
         Value = 0,
         UsedItems = k.Items.Select(x => false).ToArray()
     });
 }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            ISolver  solver = new EmptySolver();
            Knapsack ks     = new Knapsack(new StreamReader(Console.OpenStandardInput()));

            OptionSet options = new OptionSet()
            {
                { "s=", "Solver to use", solverName => {
                      switch (solverName)
                      {
                      case "greedy":
                          solver = new GreedySolver();
                          break;

                      case "ratiogreedy":
                          solver = new RatioGreedySolver();
                          break;

                      case "dynamic":
                          solver = new DynamicSolver();
                          break;

                      case "hybrid":
                          solver = new HybridSolver();
                          break;

                      case "branch":
                          solver = new BranchBoundSolver();
                          break;

                      default:
                          throw new OptionException("Invalid solver name", "s");
                      }
                  } }
            };

            options.Parse(args);


            Solution solution = solver.Solve(ks);

            solution.Output(new StreamWriter(Console.OpenStandardOutput()));
        }
Exemplo n.º 5
0
        public Solution Solve(Knapsack k)
        {
            int itemCount   = k.Items.Length;
            var sortedItems = k.Items.OrderByDescending(x => ((double)x.Value) / x.Size);

            int[]    values  = sortedItems.Select(x => x.Value).ToArray();
            int[]    sizes   = sortedItems.Select(x => x.Size).ToArray();
            int[]    indices = sortedItems.Select(x => x.Index).ToArray();
            double[] ratios  = sortedItems.Select(x => ((double)x.Value) / x.Size).ToArray();
            bool[]   used    = new bool[itemCount];

            int top          = 0;
            int currentValue = 0;
            int currentSize  = 0;

            int bestValue = 0;

            bool[] bestSolution    = null;
            int    bestSolutionTop = 0;

            while (true)
            {
                // add items as long as possible
                while (top < itemCount && currentSize + sizes[top] <= k.Capacity)
                {
                    used[top]     = true;
                    currentSize  += sizes[top];
                    currentValue += values[top];
                    top++;
                }
                // a solution
                //Console.WriteLine(String.Format("Trying solution: {0} - {1}", top, string.Join(" ", used.Take(top).Select(x => x ? "1" : "0"))));
                if (currentValue > bestValue)
                {
                    bestValue       = currentValue;
                    bestSolution    = (bool[])used.Clone();
                    bestSolutionTop = top;
                }
                // find the place to start next branch - locate and change the topmost nonterminal 1
                if (top == itemCount)
                {
                    top--;
                    currentSize  -= sizes[top];
                    currentValue -= values[top];
                }
                if (top == itemCount - 1)
                {
                    do
                    {
                        top--;
                    }while (top >= 0 && !used[top]);
                    if (top < 0)
                    {
                        break;
                    }
                    currentSize  -= sizes[top];
                    currentValue -= values[top];
                }

                while (true)
                {
                    // check if branch can give any good solution
                    int estimateValue = currentValue;
                    int placeLeft     = k.Capacity - currentSize;
                    for (int i = top + 1; i < itemCount; i++)
                    {
                        if (placeLeft >= sizes[i])
                        {
                            placeLeft     -= sizes[i];
                            estimateValue += values[i];
                        }
                        else
                        {
                            estimateValue += (int)((double)placeLeft * values[i] / sizes[i]);
                            break;
                        }
                    }
                    if (estimateValue > bestValue)
                    {
                        break;
                    }
                    // continue up to find another
                    do
                    {
                        top--;
                    }while (top >= 0 && !used[top]);
                    if (top < 0)
                    {
                        break;
                    }
                    currentSize  -= sizes[top];
                    currentValue -= values[top];
                }

                if (top < 0)
                {
                    break;
                }

                used[top] = false;
                top++;
            }

            bool[] usedItems = new bool[itemCount];
            for (int i = 0; i < bestSolutionTop; i++)
            {
                usedItems[indices[i]] = bestSolution[i];
            }
            for (int i = bestSolutionTop; i < itemCount; i++)
            {
                usedItems[indices[i]] = false;
            }

            return(new Solution()
            {
                IsOptimal = true,
                Value = bestValue,
                UsedItems = usedItems
            });
        }
Exemplo n.º 6
0
        public virtual IOrderedEnumerable <Knapsack.Item> SortedItems(Knapsack k)
        {
            var sorted = k.Items.OrderByDescending(x => x.Value);

            return(sorted);
        }
Exemplo n.º 7
0
 public override IOrderedEnumerable <Knapsack.Item> SortedItems(Knapsack k)
 {
     return(k.Items.OrderByDescending(x => ((double)x.Value) / x.Size));
 }