Java Challenge - The Knapsack Problem

This community-built FAQ covers the “The Knapsack Problem” code challenge in Java. You can find that challenge here, or pick any challenge you like from our list.

Top Discussions on the Java challenge The Knapsack Problem

There are currently no frequently asked questions or top answers associated with this challenge – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this challenge. Ask a question or post a solution by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this challenge, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in Language Help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to Language Help and Tips and Resources. If you are wanting feedback or inspiration for a project, check out Projects.

Looking for motivation to keep learning? Join our wider discussions in Community

Learn more about how to use this guide.

Found a bug? Report it online, or post in Bug Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

private static int getArray(int array, int exceptIndex) {
int newArray = new int[array.length - 1];
for (int i = 0; i < array.length; i++) {
if (i < exceptIndex) {
newArray[i] = array[i];
} else if (i > exceptIndex) {
newArray[i - 1] = array[i];
}
}
return newArray;
}

private static int knapsack(int weightCap, int weights, int values, HashMap<Integer, Integer> record) {
if (weightCap == 0) {
return 0;
}
if (record.containsKey(weightCap)) {
return record.get(weightCap);
}
int largestSum = 0;
for (int i = 0; i < weights.length; i++) {
int weight = weights[i];
int newWeightCap = weightCap - weight;
if (newWeightCap < 0) {
continue;
}
int value = values[i];
int sum = value + knapsack(newWeightCap, getArray(weights, i), getArray(values, i));
if (largestSum < sum) {
largestSum = sum;
}
}
record.put(weightCap, largestSum);
return largestSum;
}

public static int knapsack(int weightCap, int weights, int values) {
return knapsack(weightCap, weights, values, new HashMap<Integer, Integer>());
}

public class Knapsack {
  public static void main(String[] args) {
    int values[] = new int[] {50, 60, 100};
    int weights[] = new int[] {3, 6, 8};
    int weightCap = 10;
    System.out.println(knapsack(weightCap, weights, values));
  }
 
  public static int knapsack(int weightCap, int weights[], int values[]) {
    return knapsackHelper(weightCap, weights, values, 0);
  }
  
  // Start from the beginning of the item's and for each item lets try to fit the current item in our bag
 // and then skipping the current item, and taking the condition that has the greatest value.
  public static int knapsackHelper(int weightCap, int weights[], int values[], int index) {
    // If we reached the end of all the items, return 0.
    if (index >= weights.length) {
      return 0;
    }
    // Value for taking the current item we are on.
    int takeItem = 0;
   // Value if we skip the current item.
    int skipItem = 0;
 
    // If we can fit the current item in our bag, lets try taking it and subtracting it's weight from out cap.
    if (weights[index] <= weightCap) {
      takeItem = knapsackHelper(weightCap - weights[index], weights, values, index + 1) + values[index];
    }

    // Let's see what values we can get if we skip this current item.
    skipItem = knapsackHelper(weightCap, weights, values, index + 1);
    
   // Return the condition with the greater value.
    return Math.max(takeItem, skipItem);
  }
}

import java.util.Arrays;

public class Knapsack{

public static void main(String[] args) {
	// TODO Auto-generated method stub
	int values[] = new int[]{50, 60, 100};
	int weights[] = new int[]{3, 6, 8};
	int weightCap = 10;

	// exemples to test the code :
	// int values[] = new int[]{15, 30, 150, 30, 5, 15, 30};
	// int weights[] = new int[]{2, 6, 1, 10, 1, 3, 4};
	// int values[] = new int[]{15, 30, 150, 30};
	// int weights[] = new int[]{2, 6, 1, 10};
	// int values[] = new int[]{100, 100, 100, 100};
	// int weights[] = new int[]{1, 10, 6, 2};
	// int values[] = new int[]{15, 30, 150, 30};
	// int weights[] = new int[]{2, 2, 2, 2};
	// int values[] = new int[]{150, 150, 150, 150};
	// int weights[] = new int[]{2, 6, 1, 10};

	// See the arrays before classifying them
	System.out.println(Arrays.toString(weights));
	System.out.println(Arrays.toString(values));
	System.out.println("------------");
	System.out.println(knapsack(weightCap, weights, values));

}

public static int knapsack(int weightCap, int weights[], int values[]) {
	int valueBegin = 0;
	int weightBegin = 0;
	int valueEnd = 0;
	int weightEnd = 0;
	// Classify the array of values from largest to smallest and match the array of weights
	classifyValuesAndWeights(weights, values);
	System.out.println(Arrays.toString(weights));
	System.out.println(Arrays.toString(values));
	System.out.println("------------");
	// We take the biggest possible value of take starting from the begin
	for (int i = 0; i < weights.length; i++) {
		if (weightBegin <= weightCap
				&& weightBegin + weights[i] <= weightCap) {
			weightBegin += weights[i];
			valueEnd += values[i];
		}
	}
	// We take the biggest possible value of take starting from the end
	for (int i = weights.length - 1; i >= 0; i--) {
		if (weightEnd <= weightCap && weightEnd + weights[i] <= weightCap) {
			weightEnd += weights[i];
			valueEnd += values[i];
		}
	}
	// We compare the values between valueBegin and valueEnd
	if (valueEnd > valueBegin) {
		return valueEnd;
	} else {
		return valueBegin;
	}
}

// Classify the array of values from largest to smallest and match the array of weights
public static int[] classifyValuesAndWeights(int weights[], int values[]) {
	int x, y;
	for (int i = 0; i < weights.length - 1; i++) {
		for (int j = 0; j < weights.length - 1; j++) {
			if (values[j] < values[j + 1]) {
				y = values[j + 1];
				values[j + 1] = values[j];
				values[j] = y;
				x = weights[j + 1];
				weights[j + 1] = weights[j];
				weights[j] = x;
			}
		}
	}
	return weights;
}

}

I just did a brute-force approach that goes through every possible combination (every subset in the power set) denoted by a long (using some binary operations to match it to the specific indices being used). I tried to use some object-oriented stuff a little.

my code
public class Knapsack {

  public int[] weights;
  public int[] values;
  public long combinationId;

  public Knapsack() {
    this.weights = new int[0];
    this.values = new int[0];
    //this.combinationId = 0;
  }
  public Knapsack(int[] weights, int[] values) {
    this.weights = weights;
    this.values = values;
    this.combinationId = this.values.length - 1;
  }

  public boolean[] getUsed(long x) {
    int length = values.length;
    boolean[] used = new boolean[length];
    for (int j = length - 1; j >= 0; j--) {
      if ((x & 1) == 1) {
        used[j] = true;
      }
      else {
        used[j] = false;
      }
      x = x >> 1;
    }
    return used;
  }
  public boolean[] getUsed() {
    return getUsed(this.combinationId);
  }

  public int getTotalValue(long x) {
    int length = values.length;
    int total = 0;
    for (int j = length - 1; j >= 0; j--) {
      if ((x & 1) == 1) {
        total += values[j];
      }
      x = x >> 1;
    }
    return total;
  }
  public int getTotalValue() {
    return getTotalValue(this.combinationId);
  }

  public int getTotalWeight(long x) {
    int length = values.length;
    int total = 0;
    for (int j = length - 1; j >= 0; j--) {
      if ((x & 1) == 1) {
        total += weights[j];
      }
      x = x >> 1;
    }
    return total;
  }
  public int getTotalWeight() {
    return getTotalWeight(this.combinationId);
  }

  public static int knapsack(int weightCap, int[] weights, int[] values) {
    if ((weights.length == 0) || (values.length == 0)) {
      return 0;
    }
    Knapsack sack = new Knapsack(weights, values);

    long twoToLengthPower = (long)1 << weights.length;
    long bestCombo = 0;
    int maxValue = 0;

    for (long i = 1; i < twoToLengthPower; i++) {
      int value = sack.getTotalValue(i);
      int weight = sack.getTotalWeight(i);
      if ((value > maxValue) && (weight <= weightCap)) {
        bestCombo = i;
        maxValue = value;
      }
    }
    return maxValue;
  }

  public static void main(String[] args) {
    int values[] = new int[] {50, 60, 100};
    int weights[] = new int[] {3, 6, 8};
    int weightCap = 10;
    System.out.println(knapsack(weightCap, weights, values));
  }
}

I probably could have combined those helper methods to be one method, if I had returned an array of 2 integers [totalWeight, totalValue] for that combination.

THIS is the solution… This goes below the placeholder // add code here
Maybe someone add this to the challengesite…

// add code here if (n == 0 || weightCap == 0) { matrix[index][weight] = 0; } else if (weights[index - 1] > weight) { matrix[index][weight] = matrix[index - 1][weight]; } else { matrix[index][weight] = Math.max( matrix[index - 1][weight], matrix[index - 1][weight - weights[index - 1]] + values[index - 1]); }