Maximized Study

The problem was in last year’s Trinity programming contest problems, and I’ve been trying for a few hours to get it to work just right. I’m very close, but I know of one bug (which I’ll let you try and find).

Here’s the Java source:

import java.util.*;

public class Problem2 {
	public static void main (String args[]) throws IOException {
		Scanner scanner = new Scanner (new FileReader("problem2.txt"));
		int numberOfCases = scanner.nextInt();

		for (int i=0; i<numberOfCases; i++) {
			int bagCapacity = scanner.nextInt();
			int bagFull=0;
			int numBooks = scanner.nextInt();
			ArrayList<MyBook> books = new ArrayList<MyBook>(numBooks);
			for (int j=0; j<numBooks; j++) {
				books.add(new MyBook(, scanner.nextInt(), scanner.nextInt()));
			ListIterator<MyBook> iterator = books.listIterator();
			while (iterator.hasNext()) {
				MyBook book =;
				if (book.weight+bagFull <= bagCapacity) {
				} else {


class MyBook implements Comparable {
	String name;
	int weight;
	int gradeValue;
	double ratio;
	public MyBook (String name, int weight, int gradeValue) {		= name;
		this.weight		= weight;
		this.gradeValue	= gradeValue;
		this.ratio = (double) gradeValue/weight;
	public int compareTo (Object book) {
		return ((int)((MyBook)book).ratio-(int)this.ratio);
	public String toString () {
		return + " " + weight + " " +gradeValue;
	public static int totalGradeValue (ArrayList<MyBook> books) {
		int total = 0;
		for (int i=0; i<books.size(); i++) {
			total += (books.get(i)).gradeValue;
		return total;

And here’s the sample file loaded in (you need to save this as problem2.txt to make the above file read it).

10 3
History 7 30
Math 4 40
English 6 30
10 2
CliffNotes 5 99
OfficialText 8 1

It’ll find the most it can bring home. The first line represents the number of cases following, and the first for each case represents the number of pounds available in your backpack, and the number of books to follow. Each book has its name, weight, and point value it’s help your score.

It’ll output:


For the 70 points you can get in the first set, and the 99 (with Cliffnotes) you can potentially get in the second set.

You have to get the most possible. :slight_smile:

Try and find my bug, and see if you can solve it.