|
1 | 1 | package com.sbaars.adventofcode.year15.days;
|
2 | 2 |
|
3 | 3 | import com.sbaars.adventofcode.year15.Day2015;
|
| 4 | +import java.util.*; |
| 5 | +import java.util.stream.Collectors; |
4 | 6 |
|
5 | 7 | public class Day9 extends Day2015 {
|
| 8 | + private final Map<String, Map<String, Integer>> distances = new HashMap<>(); |
| 9 | + private final Set<String> cities = new HashSet<>(); |
| 10 | + |
6 | 11 | public Day9() {
|
7 | 12 | super(9);
|
| 13 | + parseInput(); |
8 | 14 | }
|
9 | 15 |
|
10 | 16 | public static void main(String[] args) {
|
11 |
| - new Day9().printParts(); |
| 17 | + Day9 day = new Day9(); |
| 18 | + day.printParts(); |
| 19 | + new com.sbaars.adventofcode.network.Submit().submit(day.part1(), 2015, 9, 1); |
| 20 | + new com.sbaars.adventofcode.network.Submit().submit(day.part2(), 2015, 9, 2); |
| 21 | + } |
| 22 | + |
| 23 | + private void parseInput() { |
| 24 | + day().lines().forEach(line -> { |
| 25 | + String[] parts = line.split(" = "); |
| 26 | + String[] cities = parts[0].split(" to "); |
| 27 | + int distance = Integer.parseInt(parts[1]); |
| 28 | + addDistance(cities[0], cities[1], distance); |
| 29 | + addDistance(cities[1], cities[0], distance); |
| 30 | + this.cities.add(cities[0]); |
| 31 | + this.cities.add(cities[1]); |
| 32 | + }); |
| 33 | + } |
| 34 | + |
| 35 | + private void addDistance(String from, String to, int distance) { |
| 36 | + distances.computeIfAbsent(from, k -> new HashMap<>()).put(to, distance); |
12 | 37 | }
|
13 | 38 |
|
14 | 39 | @Override
|
15 | 40 | public Object part1() {
|
16 |
| - return ""; |
| 41 | + return findPath(true); |
17 | 42 | }
|
18 | 43 |
|
19 | 44 | @Override
|
20 | 45 | public Object part2() {
|
21 |
| - return ""; |
| 46 | + return findPath(false); |
| 47 | + } |
| 48 | + |
| 49 | + private int findPath(boolean shortest) { |
| 50 | + return cities.stream() |
| 51 | + .mapToInt(start -> findPathFromCity(start, new HashSet<>(List.of(start)), shortest)) |
| 52 | + .reduce(shortest ? Integer.MAX_VALUE : Integer.MIN_VALUE, shortest ? Math::min : Math::max); |
| 53 | + } |
| 54 | + |
| 55 | + private int findPathFromCity(String current, Set<String> visited, boolean shortest) { |
| 56 | + if (visited.size() == cities.size()) { |
| 57 | + return 0; |
| 58 | + } |
| 59 | + |
| 60 | + return distances.get(current).entrySet().stream() |
| 61 | + .filter(e -> !visited.contains(e.getKey())) |
| 62 | + .mapToInt(e -> { |
| 63 | + Set<String> newVisited = new HashSet<>(visited); |
| 64 | + newVisited.add(e.getKey()); |
| 65 | + return e.getValue() + findPathFromCity(e.getKey(), newVisited, shortest); |
| 66 | + }) |
| 67 | + .reduce(shortest ? Integer.MAX_VALUE : Integer.MIN_VALUE, shortest ? Math::min : Math::max); |
22 | 68 | }
|
23 | 69 | }
|
0 commit comments