Skip to content

Commit

Permalink
Simplify the Java Knapsack example, so it is easier for LLMs to solve
Browse files Browse the repository at this point in the history
Part of #230
  • Loading branch information
ruiAzevedo19 committed Jul 11, 2024
1 parent ca25797 commit 84d3052
Showing 1 changed file with 15 additions and 15 deletions.
30 changes: 15 additions & 15 deletions testdata/java/light/src/main/java/com/eval/Knapsack.java
Original file line number Diff line number Diff line change
@@ -1,33 +1,33 @@
package com.eval;

public class Knapsack {
static int maximumValue(int maximumWeight, Item[] items) {
int[][] knapsack = new int[items.length + 1][maximumWeight + 1];
for (int item = 0; item <= items.length; item++) {
static int maximumValue(int maximumWeight, int[] weights, int[] values) {
if (weights.length != values.length) {
throw new IllegalArgumentException("the arrays must have the same length");
}
int numberOfItems = weights.length;

int[][] knapsack = new int[numberOfItems + 1][maximumWeight + 1];
for (int item = 0; item <= numberOfItems; item++) {
for (int weight = 0; weight <= maximumWeight; weight++) {
knapsack[item][weight] = 0; // Return 0 if not filled
}
}
for (int item = 0; item <= items.length; item++) {
for (int item = 0; item <= numberOfItems; item++) {
for (int weight = 0; weight <= maximumWeight; weight++) {
if (item == 0 || weight == 0) {
knapsack[item][weight] = 0;
} else if (items[item - 1].weight > weight) {
} else if (weights[item - 1] > weight) {
knapsack[item][weight] = knapsack[item - 1][weight];
} else {
int itemValue = items[item - 1].value;
int itemWeight = items[item - 1].weight;
knapsack[item][weight] =
Math.max(itemValue + knapsack[item - 1][weight - itemWeight],
knapsack[item - 1][weight]);
int itemValue = values[item - 1];
int itemWeight = weights[item - 1];
knapsack[item][weight] = Math.max(itemValue + knapsack[item - 1][weight - itemWeight],
knapsack[item - 1][weight]);
}
}
}
return knapsack[items.length][maximumWeight];
}

class Item {
int weight;
int value;
return knapsack[numberOfItems][maximumWeight];
}
}

0 comments on commit 84d3052

Please sign in to comment.