Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package adventofcode;
- import adventofcode.utils.Utils;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- public class Day6 {
- public static void solve() {
- List<String> input = Utils.getInput(6);
- Map<String, String> orbits = new HashMap<>();
- input.forEach(e -> {
- String[] objects = e.split("\\)");
- orbits.put(objects[1], objects[0]);
- });
- int totalOrbits = part1(orbits);
- int orbitalTransfers = part2(orbits);
- System.out.println(totalOrbits);
- System.out.println(orbitalTransfers);
- }
- private static int part1(Map<String, String> orbits) {
- return orbits.entrySet().stream()
- .mapToInt(orbit -> countOrbits(orbits, orbit.getKey()))
- .sum();
- }
- private static int part2(Map<String, String> orbits) {
- // find the first common point and calculate distance to it from YOU and SAN
- List<String> santa = new ArrayList<>();
- String key = "SAN";
- do {
- String value = orbits.get(key);
- santa.add(value);
- key = value;
- } while(!key.equals("COM"));
- key = "YOU";
- int transfers = 0;
- do {
- transfers++;
- key = orbits.get(key);
- } while(!santa.contains(key));
- String key2 = "SAN";
- do {
- transfers++;
- key2 = orbits.get(key2);
- } while(!key2.equals(key));
- return transfers - 2; // because you don't need a transfer from YOU/SAN to the starting object
- }
- private static int countOrbits(Map<String, String> orbits, String key) {
- if(key.equals(("COM"))) {
- return 0;
- }
- return 1 + countOrbits(orbits, orbits.get(key));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement