THINK FIRST·CODE LATER

← All labs

0/1 knapsack with the list of items

Problem

A backpack holds at most W kg. Each of n items has a weight and a value and is either taken or left (no fractions). Maximise the total value.

Write Knapsack. Input: W n, then name weight value lines. Fill the table best[i][w] = best value using the first i items with capacity w (skip vs take), then walk back through the table to list the chosen items in input order. Also compute the greedy answer "best value/weight ratio first" and say whether it is optimal.

For the input

10 4
laptop 6 30
camera 3 14
book 4 16
snack 2 9

the program prints

Best value: 46
Items: [laptop, book] (weight 10 of 10)
Greedy by ratio: 44 (not optimal)
Table cells filled: 44

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d8-4-data-1.txt

10 4
laptop 6 30
camera 3 14
book 4 16
snack 2 9
What your program must print for d8-4-data-1.txt
Best value: 46
Items: [laptop, book] (weight 10 of 10)
Greedy by ratio: 44 (not optimal)
Table cells filled: 44

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d8-4-data-1.txt

Windows PowerShell does not understand <:

Get-Content d8-4-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.