Last active
December 9, 2017 10:11
-
-
Save snarkbait/6d6c5751872b8b5df48d2d4bdd3fd3fb to your computer and use it in GitHub Desktop.
Advent of Code 2017 - Day 9
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package Advent2017; | |
import util.FileIO; | |
import util.Timer; | |
import java.util.HashMap; | |
import java.util.Map; | |
public class Day9 { | |
enum State { | |
OPEN, CLOSE, GARBAGE, IGNORE, OTHER; | |
final Map<Character, State> transitions = new HashMap<>(); | |
// Rules for Finite State Machine | |
static { | |
State.OTHER.addTransition('{', State.OPEN); | |
State.OTHER.addTransition('}', State.CLOSE); | |
State.OTHER.addTransition('<', State.GARBAGE); | |
State.OPEN.addTransition('}', State.CLOSE); | |
State.OPEN.addTransition('<', State.GARBAGE); | |
State.OPEN.addTransition(',', State.OTHER); | |
State.CLOSE.addTransition('{', State.OPEN); | |
State.CLOSE.addTransition('<', State.GARBAGE); | |
State.CLOSE.addTransition(',', State.OTHER); | |
State.GARBAGE.addTransition('!', State.IGNORE); | |
State.GARBAGE.addTransition('>', State.OTHER); | |
State.IGNORE.addTransition('!', State.GARBAGE); | |
} | |
private void addTransition(char c, State accept) { | |
transitions.put(c, accept); | |
} | |
public State getTransition(char c) { | |
return transitions.getOrDefault(c, this); | |
} | |
} | |
public static void main(String[] args) { | |
State current = State.OTHER; | |
String input = FileIO.getFileAsString("advent2017_day9.txt"); | |
int level = 0; | |
int garbageCount = 0; | |
int score = 0; | |
Timer.startTimer(); | |
for (int i = 0; i < input.length(); i++) { | |
char c = input.charAt(i); | |
if (current == State.IGNORE) c = '!'; | |
State next = current.getTransition(c); | |
switch (next) { | |
case OPEN: | |
level++; | |
break; | |
case CLOSE: | |
score += level--; | |
break; | |
case GARBAGE: | |
if (current == State.GARBAGE) garbageCount++; | |
} | |
current = next; | |
} | |
System.out.println("Part 1: " + score); | |
System.out.println("Part 2: " + garbageCount); | |
System.out.println(Timer.endTimer()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment