B
Bill Tillman
Guest
I'm about to get back into programming in C# and have some confusion about the STATIC keyword. In my previous incarnation as a C# developer I was told by some very good programmers, biased as they were, that one should never use static for variables, methods, properties, just never ever use it. I didn't fully understood, just did my best to comply with the team. So tonight I'm dusting off some code with the KnapSack algorithm in it. I recall this was a very useful tool for figuring out the lowest costs for some items to be included in pricing quotes. Won't bore you with details but as I said this tool works very good and my testing tonight with it proves it will most likely work for this upcoming project. But it contains the static keyword in the method in the class and thus I was wondering if it's absolutely necessary and if so were these previous team members giving me not so accurate information?
public class Knapsack
{
public static int KnapSack(int capacity, int[] weight, int[] value, int itemsCount)
{
int[,] K = new int[itemsCount + 1, capacity + 1];
for (int i = 0; i <= itemsCount; ++i)
{
for (int w = 0; w <= capacity; ++w)
{
if (i == 0 || w == 0)
K[i, w] = 0;
else if (weight[i - 1] <= w)
K[i, w] = Math.Max(value[i - 1] + K[i - 1, w - weight[i - 1]], K[i - 1, w]);
else
K[i, w] = K[i - 1, w];
}
}
return K[itemsCount, capacity];
}
}
Continue reading...
public class Knapsack
{
public static int KnapSack(int capacity, int[] weight, int[] value, int itemsCount)
{
int[,] K = new int[itemsCount + 1, capacity + 1];
for (int i = 0; i <= itemsCount; ++i)
{
for (int w = 0; w <= capacity; ++w)
{
if (i == 0 || w == 0)
K[i, w] = 0;
else if (weight[i - 1] <= w)
K[i, w] = Math.Max(value[i - 1] + K[i - 1, w - weight[i - 1]], K[i - 1, w]);
else
K[i, w] = K[i - 1, w];
}
}
return K[itemsCount, capacity];
}
}
Continue reading...