Advertisement
Guest User

Untitled

a guest
Dec 6th, 2019
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.85 KB | None | 0 0
  1. package adventofcode;
  2.  
  3. import adventofcode.utils.Utils;
  4. import java.util.ArrayList;
  5. import java.util.HashMap;
  6. import java.util.List;
  7. import java.util.Map;
  8.  
  9. public class Day6 {
  10.     public static void solve() {
  11.         List<String> input = Utils.getInput(6);
  12.  
  13.         Map<String, String> orbits = new HashMap<>();
  14.         input.forEach(e -> {
  15.             String[] objects = e.split("\\)");
  16.             orbits.put(objects[1], objects[0]);
  17.         });
  18.  
  19.         int totalOrbits = part1(orbits);
  20.         int orbitalTransfers = part2(orbits);
  21.  
  22.         System.out.println(totalOrbits);
  23.         System.out.println(orbitalTransfers);
  24.     }
  25.  
  26.     private static int part1(Map<String, String> orbits) {
  27.         return orbits.entrySet().stream()
  28.                 .mapToInt(orbit -> countOrbits(orbits, orbit.getKey()))
  29.                 .sum();
  30.     }
  31.  
  32.     private static int part2(Map<String, String> orbits) {
  33.         // find the first common point and calculate distance to it from YOU and SAN
  34.  
  35.         List<String> santa = new ArrayList<>();
  36.         String key = "SAN";
  37.         do {
  38.             String value = orbits.get(key);
  39.             santa.add(value);
  40.             key = value;
  41.         } while(!key.equals("COM"));
  42.  
  43.         key = "YOU";
  44.         int transfers = 0;
  45.         do {
  46.             transfers++;
  47.             key = orbits.get(key);
  48.         } while(!santa.contains(key));
  49.  
  50.         String key2 = "SAN";
  51.         do {
  52.             transfers++;
  53.             key2 = orbits.get(key2);
  54.         } while(!key2.equals(key));
  55.  
  56.         return transfers - 2; // because you don't need a transfer from YOU/SAN to the starting object
  57.     }
  58.  
  59.     private static int countOrbits(Map<String, String> orbits, String key) {
  60.         if(key.equals(("COM"))) {
  61.             return 0;
  62.         }
  63.  
  64.         return 1 + countOrbits(orbits, orbits.get(key));
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement