Day 3-6 2019
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
package be.vandewalleh.aoc;
|
||||
|
||||
import be.vandewalleh.aoc.utils.factory.Days;
|
||||
import be.vandewalleh.aoc.utils.input.Day;
|
||||
import be.vandewalleh.aoc.utils.input.Input;
|
||||
import be.vandewalleh.aoc.utils.input.Lines;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
@Day(6)
|
||||
public class Day06 {
|
||||
|
||||
public static void main(String[] args) {
|
||||
var day = Days.createDay(Day06.class);
|
||||
System.out.println(day.part1());
|
||||
System.out.println(day.part2());
|
||||
}
|
||||
|
||||
private final List<String> input;
|
||||
|
||||
public Day06(@Lines Input<List<String>> input) {
|
||||
this.input = input.getValue();
|
||||
}
|
||||
|
||||
private final Map<String, String> reverseOrbits = new HashMap<>();
|
||||
|
||||
private int countDirectOrbits() {
|
||||
return reverseOrbits.size();
|
||||
}
|
||||
|
||||
private int countIndirectOrbits() {
|
||||
var count = 0;
|
||||
for (var key : reverseOrbits.keySet()) {
|
||||
count += countIndirectOrbits(key);
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
private int countIndirectOrbits(String key) {
|
||||
var count = 0;
|
||||
var currentKey = reverseOrbits.get(key);
|
||||
while (currentKey != null) {
|
||||
currentKey = reverseOrbits.get(currentKey);
|
||||
if (currentKey != null) count++;
|
||||
else return count;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private List<String> pathToCom(String key) {
|
||||
var path = new ArrayList<String>();
|
||||
var currentKey = reverseOrbits.get(key);
|
||||
path.add(currentKey);
|
||||
while (currentKey != null) {
|
||||
currentKey = reverseOrbits.get(currentKey);
|
||||
if (currentKey == null) return path;
|
||||
else path.add(currentKey);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
private int part1() {
|
||||
for (var line : input) {
|
||||
var split = line.split("\\)");
|
||||
reverseOrbits.put(split[1], split[0]);
|
||||
}
|
||||
return countDirectOrbits() + countIndirectOrbits();
|
||||
}
|
||||
|
||||
private int part2() {
|
||||
var sanPath = pathToCom("SAN");
|
||||
var youPath = pathToCom("YOU");
|
||||
|
||||
var common = new LinkedHashSet<>(sanPath);
|
||||
common.retainAll(youPath);
|
||||
|
||||
String closestCommon = (String) common.toArray()[0];
|
||||
return sanPath.indexOf(closestCommon) + youPath.indexOf(closestCommon);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user