0-1 Knapsack algorithm

前端 未结 6 2090
花落未央
花落未央 2021-02-09 12:35

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:01

    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();
    

提交回复
热议问题