Created
December 13, 2017 23:58
-
-
Save DeltaGeek/e85b88c1d2244d97788944ea67a5ec99 to your computer and use it in GitHub Desktop.
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
public class Day13 { | |
public static void main(String[] args) throws Exception { | |
// Iterable<String> input = Files.readAllLines(Paths.get("H:/Data/day13-test.txt")); | |
Iterable<String> input = Files.readAllLines(Paths.get("H:/Data/day13.txt")); | |
int max = 0; | |
Map<Integer, Integer> scanners = new HashMap<>(); | |
for(String line : input){ | |
String[] tokens = line.split(": "); | |
int layer = Integer.parseInt(tokens[0]); | |
int depth = Integer.parseInt(tokens[1]); | |
scanners.put(layer, depth); | |
if(layer > max) | |
max = layer; | |
} | |
System.out.println(computeSeverity(scanners, max)); | |
System.out.println(findDelay(scanners)); | |
} | |
private static int findDelay(Map<Integer, Integer> scanners) { | |
int delay = 0; | |
boolean done = false; | |
while(!done){ | |
delay++; | |
skip: while(!done){ | |
for(Map.Entry<Integer, Integer> entry : scanners.entrySet()){ | |
if((delay + entry.getKey()) % ((entry.getValue() - 1)*2) == 0) | |
break skip; | |
} | |
done = true; | |
} | |
} | |
return delay; | |
} | |
private static int computeSeverity(Map<Integer, Integer> scanners, int max) { | |
List<Layer> layers = new ArrayList<>(); | |
for(int i=0; i<= max; i++){ | |
if(scanners.containsKey(i)){ | |
int depth = scanners.get(i); | |
layers.add(new Layer(depth)); | |
} | |
else | |
layers.add(new Layer(0)); | |
} | |
int severity = 0; | |
for(int location = 0; location < layers.size(); location++){ | |
Layer layer = layers.get(location); | |
if(layer.location == 0) | |
severity += location * layer.depth; | |
layers.forEach(Layer::move); | |
} | |
return severity; | |
} | |
static class Layer{ | |
public int location = 0; | |
int depth; | |
boolean movingForward = true; | |
public Layer(int depth){ | |
this.depth = depth; | |
} | |
public void move(){ | |
if(depth == 0) | |
return; | |
if(movingForward) | |
location++; | |
else | |
location--; | |
if(location == 0) | |
movingForward = true; | |
if(location == depth-1) | |
movingForward = false; | |
} | |
@Override | |
public String toString(){ | |
return String.format("%d (%d)", location, depth); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment