0-1 Knapsack algorithm

前端 未结 6 983
孤独总比滥情好
孤独总比滥情好 2021-02-09 12:37

Is the following 0-1 Knapsack problem solvable:

  • \'float\' positive values and
  • \'float\' weights (can be positive or negative)
  • \'float\' capacity
6条回答
  •  广开言路
    2021-02-09 13:07

    Yeah, brute force it. This is an NP-Complete problem, but that shouldn't matter because you will have less than 10 items. Brute forcing won't be problematic.

            var size = 10;
            var capacity = 0;
            var permutations = 1024;
            var repeat = 10000;
    
            // Generate items
            float[] items = new float[size];
            float[] weights = new float[size];
            Random rand = new Random();
            for (int i = 0; i < size; i++)
            {
                items[i] = (float)rand.NextDouble();
                weights[i] = (float)rand.NextDouble();
                if (rand.Next(2) == 1)
                {
                    weights[i] *= -1;
                }
            }
    
            // solution
            int bestPosition= -1;
    
            Stopwatch sw = new Stopwatch();            
            sw.Start();
    
            // for perf testing
            //for (int r = 0; r < repeat; r++)
            {
                var bestValue = 0d;
    
                // solve
                for (int i = 0; i < permutations; i++)
                {
                    var total = 0d;
                    var weight = 0d;
                    for (int j = 0; j < size; j++)
                    {
                        if (((i >> j) & 1) == 1)
                        {
                            total += items[j];
                            weight += weights[j];
                        }
                    }
    
                    if (weight <= capacity && total > bestValue)
                    {
                        bestPosition = i;
                        bestValue = total;
                    }
                }
            }
            sw.Stop();
            sw.Elapsed.ToString();
    

提交回复
热议问题