2
\$\begingroup\$

I'm looking for advice on coding practices in general.

 public class Knapsack {
 public static int getMaxBenefit(int[] weights, int[] benefits, int capacity) {
 int[][] maxbenefit = new int[weights.length + 1][capacity + 1];
 for (int i = 0; i <= weights.length; i++)
 maxbenefit[i][0] = 0;
 for (int i = 0; i <= capacity; i++)
 maxbenefit[0][i] = 0;
 for (int item = 1; item <= weights.length; item++) {
 for (int weight = 1; weight <= capacity; weight++) {
 if (weights[item - 1] <= weight) {
 int option1 = benefits[item - 1] + maxbenefit[item - 1][weight - weights[item - 1]];
 int option2 = maxbenefit[item - 1][weight];
 maxbenefit[item][weight] = Math.max(option1, option2);
 } else {
 maxbenefit[item][weight] = maxbenefit[item - 1][weight];
 }
 }
 // printMatrix(maxbenefit, weights.length, capacity);
 }
 printMatrix(maxbenefit, weights.length, capacity);
 return maxbenefit[weights.length][capacity];
 }
 public static void printMatrix(int[][] matrix, int R, int C) {
 for (int i = 0; i <= R; i++) {
 for (int j = 0; j <= C; j++) {
 System.out.print(matrix[i][j] + " | ");
 }
 System.out.println();
 }
 }
 public static void main(String[] args) {
 int[] weights = new int[] { 2, 3, 4, 5, 6 };
 int[] benefit = new int[] { 3, 4, 8, 9, 9 };
 getMaxBenefit(weights, benefit, 5);
 }
}
asked Feb 14, 2016 at 5:33
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$
 int[][] maxbenefit = new int[weights.length + 1][capacity + 1];
 for (int i = 0; i <= weights.length; i++)
 maxbenefit[i][0] = 0;
 for (int i = 0; i <= capacity; i++)
 maxbenefit[0][i] = 0;

There is no need to initialize part of the array as 0, because the entire array starts off as 0.

public static void printMatrix(int[][] matrix, int R, int C) {
 for (int i = 0; i <= R; i++) {
 for (int j = 0; j <= C; j++) {
 System.out.print(matrix[i][j] + " | ");
 }
 System.out.println();
 }
}

In here, you should check if R and C don't exceed matrix.length and matrix[i].length respectively. That way you can either limit the printing, or you could throw an error with explanation, rather than running into ArrayIndexOutOfBoundsException.

In the same way, you should check the size of int[] benefits in getMaxBenefit, because if the weights and the benefits are not the same size then you'll throw an error at some point, and failing fast is better.

answered Mar 25, 2016 at 9:39
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.