【问题标题】:Knapsack C# implementation task背包C#实现任务
【发布时间】:2018-10-27 20:13:22
【问题描述】:

我正在尝试编写具有给定条件的背包 c# 算法,但我总是遇到两个问题。我收到“索引超出数组范围”错误,或者我的结果只是 0。

我找到了几个 Knapsack 实现的代码示例,只是不知道我做错了什么。

代码示例: https://www.programmingalgorithms.com/algorithm/knapsack-problem

http://www.csharpstar.com/csharp-knapsack-problem/

我的代码:

static int Knapsack(int n, int w, int[] s, int[] v)
{
    int[,] G = new int[n+1,w+1];
    for (int k = 0; k <= n; k++)
    {
        for (int r = 0; r < w; r++)
        {
            if (r == 0 || k == 0)
                G[k, r] = 0;
            else if (s[k] <= r)
                G[k, r] = Math.Max(G[k- 1, r], v[k] + G[k - 1, r - s[k]]);
            else
                G[k, r] = G[k - 1, r]; 
        }
    }
    return G[n, w];
}
static void Main(string[] args)
{
    int[] s = { 60, 100, 120};
    int[] v = { 10, 20, 30 };
    int w = 50;
    int n = s.Length;
    Console.WriteLine(Knapsack(n, w, s, v));
}

在这种情况下,我的结果是 0。

【问题讨论】:

  • 如果您可以设置断点以确定在哪一行和哪个变量上引发超出范围的异常,这将有所帮助。
  • 如果ns 数组的大小,那么只需在您的方法中使用s.Length,而不是传入n。在 C# 中不需要像在 C++ 和 C 中那样传递数组大小。事实上,一个具有权重和值属性的简单类将把它降低到该类类型的一个数组和最大权重。
  • 使用给定的值(s[k] &lt;= r) 永远不会为真。
  • 在第一个示例中,第二个 for 循环为 for (int w = 0; w &lt;= capacity; ++w),在您的代码中为 for(int r = 0; r &lt;= w; r++)。注意它有&lt;= 而你有&lt;。这也说明了对更好的变量名的迫切需要。
  • 另外else ifK[i, w] = Math.Max(value[i - 1] + K[i - 1, w - weight[i - 1]], K[i - 1, w]);,在你的代码中应该是G[k,r] = Math.Max(s[k-1] + G[k-1, r - v[k-1]], G[k-1, r]),但是你有v[k] + G[k-1, r - s[k]] 而不是s[k-1] + G[k-1, r - v[k-1]]

标签: c# dynamic-programming knapsack-problem


【解决方案1】:

您的代码的问题是s 是权重,v 是值,您的权重 60、100 和 120 显然不适合 50 的容量,这就是为什么您会得到以下结果0. 从集合中提取这些值的示例将 60、100 和 120 作为值,将 10、20 和 30 作为权重,这就是为什么它得到 220 的结果。

我认为如果你创建一个类来处理物品的相关重量和价值,这会更好。

public class Item
{
    public int Weight { get; set; }
    public int Value { get; set; }
}

那么该方法只需要一个项目数组和所需的容量。此外,使用有意义的名称比一堆单字母名称更容易理解发生的事情。

public static int KnapSack(Item[] items, int capacity)
{
    int[,] matrix = new int[items.Length + 1, capacity + 1];
    for (int itemIndex = 0; itemIndex <= items.Length; itemIndex++)
    {
        // This adjusts the itemIndex to be 1 based instead of 0 based
        // and in this case 0 is the initial state before an item is
        // considered for the knapsack.
        var currentItem = itemIndex == 0 ? null : items[itemIndex - 1];
        for (int currentCapacity = 0; currentCapacity <= capacity; currentCapacity++)
        {
            // Set the first row and column of the matrix to all zeros
            // This is the state before any items are added and when the
            // potential capacity is zero the value would also be zero.
            if (currentItem == null || currentCapacity == 0)
            {
                matrix[itemIndex, currentCapacity] = 0;
            }
            // If the current items weight is less than the current capacity
            // then we should see if adding this item to the knapsack 
            // results in a greater value than what was determined for
            // the previous item at this potential capacity.
            else if (currentItem.Weight <= currentCapacity)
            {
                matrix[itemIndex, currentCapacity] = Math.Max(
                    currentItem.Value 
                        + matrix[itemIndex - 1, currentCapacity - currentItem.Weight],
                    matrix[itemIndex - 1, currentCapacity]);
            }
            // current item will not fit so just set the value to the 
            // what it was after handling the previous item.
            else
            {
                matrix[itemIndex, currentCapacity] = 
                    matrix[itemIndex - 1, currentCapacity];
            }
        }
    }

    // The solution should be the value determined after considering all
    // items at all the intermediate potential capacities.
    return matrix[items.Length, capacity];
}

然后运行这段代码

var items = new[]
{
    new Item {Value = 60, Weight = 10},
    new Item {Value = 100, Weight = 20},
    new Item {Value = 120, Weight = 30},
};

Console.WriteLine(KnapSack(items, 50));

结果为 220。

这是一个使用递归的解决方案。

public static int KnapSackRecursive(Item[] items, int capacity)
{
    // If there are no items or capacity is 0 then return 0
    if (items.Length == 0 || capacity == 0) return 0;

    // If there is one item and it fits then return it's value
    // otherwise return 0
    if (items.Length == 1)
    {
        return items[0].Weight < capacity ? items[0].Value : 0;
    }

    // keep track of the best value seen.
    int best = 0;
    for (int i = 0; i < items.Length; i++)
    {
        // This is an array of the other items.
        var otherItems = items.Take(i).Concat(items.Skip(i + 1)).ToArray();

        // Calculate the best value without using the current item.
        int without = KnapSackRecursive(otherItems, capacity);
        int with = 0;

        // If the current item fits then calculate the best value for
        // a capacity less it's weight and with it removed from contention
        // and add the current items value to that.
        if (items[i].Weight <= capacity)
        {
            with = KnapSackRecursive(otherItems, capacity - items[i].Weight) 
                + items[i].Value;
        }

        // The current best is the max of the with or without.
        int currentBest = Math.Max(without, with);

        // determine if the current best is the overall best.
        if (currentBest > best)
            best = currentBest;
    }

    return best;
}

【讨论】:

  • 谢谢!抱歉,如果难以理解。我真的不擅长编程。你能解释一下var currentItem = itemIndex == 0 ? null : items[itemIndex - 1]; 的语法吗?
  • 基本上检查itemIndex是否为零,如果为零,则将currentItem设置为null,否则将其设置为items[itemIndex - 1]。基本上x = condition ? this : that;if(condition) x = this; else x = that; 的简写,它被称为条件运算符,也有人称它为三元运算符,因为它是唯一需要三个操作数的运算符。
  • 最后一个问题,如果我用递归来做这件事,也许你知道或者可以提出一些例子?
  • @Ekli 我添加了递归解决方案。
  • 可以优化递归解决方案,将“best = currentBest”替换为简单的“return currentBest”;这应该避免在元素子集中寻找更好的解决方案,因为您已经找到了一个。您一直在寻找不考虑当前体重的最佳和不考虑当前体重的最佳;如果您只是找到了更好的解决方案,则无需继续。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-05
  • 2014-11-27
  • 2021-10-14
相关资源
最近更新 更多