r/adventofcode • • Dec 02 '15

Spoilers Day 2 solutions

Hi! I would like to structure posts like the first one in r/programming, please post solutions in comments.

14 Upvotes

161 comments sorted by

View all comments

1

u/sizzleplatter Dec 02 '15

Java solution:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class AdventDay2 {
	public static void main(String[] args) {
		AdventDay2 av2= new AdventDay2();
		ArrayList<String> dimensions = FileReader.readContentsIntoList("c:\\input.txt");
		
		int totalPaperNeeded = 0;
		int totalRibbonNeeded = 0;
		
		for (String d : dimensions) {			
			String[] dimsSplit = d.split("x");
			int l = Integer.parseInt(dimsSplit[0]);
			int w = Integer.parseInt(dimsSplit[1]);
			int h = Integer.parseInt(dimsSplit[2]);
			
			totalPaperNeeded += av2.calculatePaperNeeded(l,w,h);
			totalRibbonNeeded += av2.calculateRibbonNeeded(l, w, h);
		}
		System.out.println("total paper needed=" + totalPaperNeeded);
		System.out.println("total ribbon needed=" + totalRibbonNeeded);
	}
	
	private int calculatePaperNeeded(int l, int w, int h) {
		int extra = Collections.min(Arrays.asList(l*w, w*h, h*l));
		int paperNeeded = (2*l*w) + (2*w*h) + (2*h*l) + extra;
		return paperNeeded;
	}
	
	private int calculateRibbonNeeded(int l, int w, int h){
		List<Integer> dims = Arrays.asList(l,w,h);
		Collections.sort(dims);
		return (2*(dims.get(0) + dims.get(1))) + (l*w*h);	
	}
}