Skip to content

Instantly share code, notes, and snippets.

Created November 29, 2017 08:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/5d12af91be2196fba4e43bfe91191427 to your computer and use it in GitHub Desktop.
Save anonymous/5d12af91be2196fba4e43bfe91191427 to your computer and use it in GitHub Desktop.
Direction enum example - Advent of Code 2016 Day 1
package Advent2016;
import util.Direction;
import util.FileIO;
import util.Timer;
import java.awt.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* @author /u/Philboyd_Studge on 12/26/2016.
*/
public class Day1 {
private int x; // current 'x' location
private int y; // current 'y' location
private Set<Point> visited = new HashSet<>(); // set of visited points for part 2
private Direction current = Direction.NORTH; // current direction 'facing'
private boolean first; // boolean for part 2, set true once point is visited twice
public Day1() {
visited.add(new Point(x, y));
}
// simplified manhattan or 'taxicab' distance formula
// only need one set of point as it is always distance to 0,0
public int manhattanDistance() {
return Math.abs(x + y);
}
/**
* Parse right/left instruction from string
* @param s Instruction string
* @return string stripped of letter
*/
private String setDir(String s) {
if (s.startsWith("R")) {
current = current.getRight();
}
else {
current = current.getLeft();
}
return s.substring(1);
}
/**
* move by distance in current direction, saving each point as visited
* if point has been visited before, the first time this happens will
* be printed to the console as a solution for part 2
* @param distance number of points to move
*/
private void move(int distance) {
for (int i = 0; i < distance; i++) {
x += current.getDx();
y += current.getDy();
Point p = new Point(x, y);
if (visited.contains(p)) {
if (!first) {
System.out.println("Part 2: " + manhattanDistance());
first = true;
}
} else {
visited.add(p);
}
}
}
/**
* split input string by ',', get R/L direction, and get distance
* and then do the simulated move
* @param input String from input file
*/
public void processInput(String input) {
Arrays.asList(input.split(",")).stream()
.map(String::trim)
.map(this::setDir)
.mapToInt(Integer::parseInt)
.forEach(this::move);
}
public static void main(String[] args) {
String input = FileIO.getFileAsString("advent1.txt"); // input is one long string
Day1 day1 = new Day1();
Timer.startTimer();
day1.processInput(input);
System.out.println("Part 1: " + day1.manhattanDistance());
System.out.println(Timer.endTimer());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment