-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Simplify the Java Knapsack example, so it is easier for LLMs to solve
Part of #230
- Loading branch information
1 parent
ca25797
commit 84d3052
Showing
1 changed file
with
15 additions
and
15 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; | ||
} | ||
} |