Skip to content

Commit ae8fe33

Browse files
sonapraneeth-alemoncurry
authored andcommitted
Implement knapsack exercise (exercism#1765)
1 parent f9bf9d6 commit ae8fe33

10 files changed

Lines changed: 249 additions & 0 deletions

File tree

‎config.json‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1384,6 +1384,18 @@
13841384
"math"
13851385
]
13861386
},
1387+
{
1388+
"slug": "knapsack",
1389+
"uuid": "ac179b77-98a5-4daf-9773-3d68b6cd8548",
1390+
"core": false,
1391+
"unlocked_by": "saddle-points",
1392+
"difficulty": 5,
1393+
"topics": [
1394+
"algorithms",
1395+
"arrays",
1396+
"conditionals"
1397+
]
1398+
},
13871399
{
13881400
"slug": "pythagorean-triplet",
13891401
"uuid": "88505f95-89e5-4a08-8ed2-208eb818cdf1",

‎exercises/knapsack/.meta/hints.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
- Use recursion
2+
- Check if there are any overlapping subproblems whose results can be cached
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Item {
2+
3+
// Weight of the item
4+
int weight;
5+
// Value of the item
6+
int value;
7+
8+
Item(int itemWeight, int itemValue) {
9+
this.weight = itemWeight;
10+
this.value = itemValue;
11+
}
12+
13+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import java.util.ArrayList;
2+
3+
class Knapsack {
4+
5+
int maximumValue(int maximumWeight, ArrayList<Item> items) {
6+
return maximumValueHelperBottomUp(maximumWeight, items);
7+
}
8+
9+
private int maximumValueHelperBottomUp(
10+
int maximumWeight, ArrayList<Item> items) {
11+
int[][] knapsack = new int[items.size() + 1][maximumWeight + 1];
12+
for (int item = 0; item <= items.size(); item++) {
13+
for (int weight = 0; weight <= maximumWeight; weight++) {
14+
knapsack[item][weight] = 0; // Return 0 if not filled
15+
}
16+
}
17+
for (int item = 0; item <= items.size(); item++) {
18+
for (int weight = 0; weight <= maximumWeight; weight++) {
19+
if (item == 0 || weight == 0) {
20+
knapsack[item][weight] = 0;
21+
} else if (items.get(item - 1).weight > weight) {
22+
knapsack[item][weight] = knapsack[item - 1][weight];
23+
} else {
24+
int itemValue = items.get(item - 1).value;
25+
int itemWeight = items.get(item - 1).weight;
26+
knapsack[item][weight] =
27+
Math.max(
28+
itemValue + knapsack[item - 1][weight - itemWeight],
29+
knapsack[item - 1][weight]
30+
);
31+
}
32+
}
33+
}
34+
return knapsack[items.size()][maximumWeight];
35+
}
36+
37+
}

‎exercises/knapsack/.meta/version‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
1.0.0

‎exercises/knapsack/README.md‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Knapsack
2+
3+
In this exercise, let's try to solve a classic problem.
4+
5+
Bob is a thief. After months of careful planning, he finally manages to crack the security systems of a high-class apartment.
6+
7+
In front of him are many items, each with a value (v) and weight (w). Bob, of course, wants to maximize the total value he can get; he would gladly take all of the items if he could. However, to his horror, he realizes that the knapsack he carries with him can only hold so much weight (W).
8+
9+
Given a knapsack with a specific carrying capacity (W), help Bob determine the maximum value he can get from the items in the house. Note that Bob can take only one of each item.
10+
11+
All values given will be strictly positive. Items will be represented as a list of pairs, wi and vi, where the first element wi is the weight of the ith item and vi is the value for that item.
12+
13+
## Notes
14+
15+
For example:
16+
17+
Items: [ { "weight": 5, "value": 10 }, { "weight": 4, "value": 40 }, { "weight": 6, "value": 30 }, { "weight": 4, "value": 50 } ]
18+
19+
Knapsack Limit: 10
20+
21+
For the above, the first item has weight 5 and value 10, the second item has weight 4 and value 40, and so on.
22+
23+
In this example, Bob should take the second and fourth item to maximize his value, which, in this case, is 90. He cannot get more than 90 as his knapsack has a weight limit of 10.
24+
25+
## Setup
26+
27+
Go through the setup instructions for Java to install the necessary
28+
dependencies:
29+
30+
[https://exercism.io/tracks/java/installation](https://exercism.io/tracks/java/installation)
31+
32+
# Running the tests
33+
34+
You can run all the tests for an exercise by entering the following in your
35+
terminal:
36+
37+
```sh
38+
$ gradle test
39+
```
40+
41+
> Use `gradlew.bat` if you're on Windows
42+
43+
In the test suites all tests but the first have been skipped.
44+
45+
Once you get a test passing, you can enable the next one by removing the
46+
`@Ignore("Remove to run test")` annotation.
47+
48+
## Source
49+
50+
Wikipedia [Knapsack_problem](https://en.wikipedia.org/wiki/Knapsack_problem)
51+
52+
## Submitting Incomplete Solutions
53+
It's possible to submit an incomplete solution so you can see how others have
54+
completed the exercise.

‎exercises/knapsack/build.gradle‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
apply plugin: "java"
2+
apply plugin: "eclipse"
3+
apply plugin: "idea"
4+
5+
repositories {
6+
mavenCentral()
7+
}
8+
9+
dependencies {
10+
testCompile "junit:junit:4.12"
11+
}
12+
13+
test {
14+
testLogging {
15+
exceptionFormat = 'full'
16+
events = ["passed", "failed", "skipped"]
17+
}
18+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
/*
2+
Since this exercise has a difficulty of > 4 it doesn't come
3+
with any starter implementation.
4+
This is so that you get to practice creating classes and methods
5+
which is an important part of programming in Java.
6+
Please remove this comment when submitting your solution.
7+
*/
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
import org.junit.Ignore;
2+
import org.junit.Before;
3+
import org.junit.Test;
4+
5+
import java.util.ArrayList;
6+
7+
import static org.junit.Assert.assertEquals;
8+
9+
public class KnapsackTest {
10+
11+
private Knapsack knapsack;
12+
13+
@Before
14+
public void setup() {
15+
knapsack = new Knapsack();
16+
}
17+
18+
@Test
19+
public void testNoItems() {
20+
ArrayList<Item> items = new ArrayList<>();
21+
assertEquals(0, knapsack.maximumValue(100, items));
22+
}
23+
24+
@Ignore("Remove to run test")
25+
@Test
26+
public void testOneItemTooHeavy() {
27+
ArrayList<Item> items = new ArrayList<>();
28+
items.add(new Item(100, 1));
29+
assertEquals(0, knapsack.maximumValue(10, items));
30+
}
31+
32+
@Ignore("Remove to run test")
33+
@Test
34+
public void testFiveItemsCannotBeGreedyByWeight() {
35+
ArrayList<Item> items = new ArrayList<>();
36+
items.add(new Item(2, 5));
37+
items.add(new Item(2, 5));
38+
items.add(new Item(2, 5));
39+
items.add(new Item(2, 5));
40+
items.add(new Item(10, 21));
41+
assertEquals(21, knapsack.maximumValue(10, items));
42+
}
43+
44+
@Ignore("Remove to run test")
45+
@Test
46+
public void testFiveItemsCannotBeGreedyByValue() {
47+
ArrayList<Item> items = new ArrayList<>();
48+
items.add(new Item(2, 20));
49+
items.add(new Item(2, 20));
50+
items.add(new Item(2, 20));
51+
items.add(new Item(2, 20));
52+
items.add(new Item(10, 50));
53+
assertEquals(80, knapsack.maximumValue(10, items));
54+
}
55+
56+
@Ignore("Remove to run test")
57+
@Test
58+
public void testExampleKnapsack() {
59+
ArrayList<Item> items = new ArrayList<>();
60+
items.add(new Item(5, 10));
61+
items.add(new Item(4, 40));
62+
items.add(new Item(6, 30));
63+
items.add(new Item(4, 50));
64+
assertEquals(90, knapsack.maximumValue(10, items));
65+
}
66+
67+
@Ignore("Remove to run test")
68+
@Test
69+
public void testEightItems() {
70+
ArrayList<Item> items = new ArrayList<>();
71+
items.add(new Item(25, 350));
72+
items.add(new Item(35, 400));
73+
items.add(new Item(45, 450));
74+
items.add(new Item(5, 20));
75+
items.add(new Item(25, 70));
76+
items.add(new Item(3, 8));
77+
items.add(new Item(2, 5));
78+
items.add(new Item(2, 5));
79+
assertEquals(900, knapsack.maximumValue(104, items));
80+
}
81+
82+
@Ignore("Remove to run test")
83+
@Test
84+
public void testFifteenItems() {
85+
ArrayList<Item> items = new ArrayList<>();
86+
items.add(new Item(70, 135));
87+
items.add(new Item(73, 139));
88+
items.add(new Item(77, 149));
89+
items.add(new Item(80, 150));
90+
items.add(new Item(82, 156));
91+
items.add(new Item(87, 163));
92+
items.add(new Item(90, 173));
93+
items.add(new Item(94, 184));
94+
items.add(new Item(98, 192));
95+
items.add(new Item(106, 201));
96+
items.add(new Item(110, 210));
97+
items.add(new Item(113, 214));
98+
items.add(new Item(115, 221));
99+
items.add(new Item(118, 229));
100+
items.add(new Item(120, 240));
101+
assertEquals(1458, knapsack.maximumValue(750, items));
102+
}
103+
104+
}

‎exercises/settings.gradle‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ include 'house'
4545
include 'isbn-verifier'
4646
include 'isogram'
4747
include 'kindergarten-garden'
48+
include 'knapsack'
4849
include 'largest-series-product'
4950
include 'leap'
5051
include 'linked-list'

0 commit comments

Comments
 (0)