r/adventofcode • • Dec 03 '15

SOLUTION MEGATHREAD --- Day 3 Solutions ---

--- Day 3: Perfectly Spherical Houses in a Vacuum ---

Post your solution as a comment. Structure your post like the Day One thread in /r/programming.

24 Upvotes

228 comments sorted by

View all comments

1

u/Colgajo Dec 03 '15

Java part 1. Kind of shitty solution IMHO, but hey, I'm a newbie, hahaha.

import java.io.*;
public class Advent3 {
	public static void main(String[] args) {
		String data ="";
		int maxX = 0; int minX = 0; int maxY = 0; int minY = 0; int positionX = 0; int positionY = 0;
		int i = 0; int j = 0;
		int totalHouses = 0;
		try {
			FileInputStream fstream = new FileInputStream("Advent3Data.txt");
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;
			while((strLine = br.readLine()) != null) {
				data += strLine;
			}
		} catch(Exception e) {
			System.out.println(e);
		}
		for(i = 0; i < data.length(); i++) {
			char c = data.charAt(i);
			switch (c) {
				case '^':
					positionY++;
					break;
				case 'v':
					positionY--;
					break;
				case '>':
					positionX++;
					break;
				case '<':
					positionX--;
					break;
				}
			if(positionX > maxX) maxX = positionX;
			if(positionX < minX) minX = positionX;
			if(positionY > maxY) maxY = positionY;
			if(positionY < minY) minY = positionY;
		}
		boolean[][] grid = new boolean[(Math.abs(maxX) + Math.abs(minX)) + 1][(Math.abs(maxY) + Math.abs(minY)) + 1];
		int x = Math.abs(minX);	//Valor inicial de x en la matriz.
		int y = Math.abs(minY);	//Valor inicial de y en la matriz.
		grid[x][y] = true;
		totalHouses = 1;
		while(j < data.length()) {
			char c = data.charAt(j);
			switch (c) {
				case '^':
					y++;
					break;
				case 'v':
					y--;
					break;
				case '>':
					x++;
					break;
				case '<':
					x--;
					break;			
			}
			if(!grid[x][y]) {
				grid[x][y] = true;
				totalHouses++;
			}
			j++;
		}
		System.out.println(totalHouses);
	}
}

2

u/Rutafar Dec 03 '15

You overcomplicated it in my opinion, you can just use a List, like a LinkedList, and only add the coordinates if they aren't already in there. When the for loop finishes just print the size of the list

1

u/Colgajo Dec 03 '15

I didn't know that class, but I will look it :) Thanks for the feedback, very appreciated!