|
| 1 | +package de.ronny_h.aoc.year2017.day24 |
| 2 | + |
| 3 | +import de.ronny_h.aoc.AdventOfCode |
| 4 | +import de.ronny_h.aoc.extensions.collections.filterMaxBy |
| 5 | + |
| 6 | +fun main() = ElectromagneticMoat().run(1906, 1824) |
| 7 | + |
| 8 | +class ElectromagneticMoat : AdventOfCode<Int>(2017, 24) { |
| 9 | + override fun part1(input: List<String>): Int { |
| 10 | + return buildStrongestBridge(0, 0, input.parseComponents()) |
| 11 | + } |
| 12 | + |
| 13 | + override fun part2(input: List<String>): Int { |
| 14 | + return buildLongestBridge(0, emptyList(), input.parseComponents()).strength() |
| 15 | + } |
| 16 | +} |
| 17 | + |
| 18 | +fun List<String>.parseComponents() = map { |
| 19 | + val (port1, port2) = it.split("/") |
| 20 | + Component(port1.toInt(), port2.toInt()) |
| 21 | +} |
| 22 | + |
| 23 | +data class Component(private val port1: Int, private val port2: Int) { |
| 24 | + fun hasPort(port: Int): Boolean = port1 == port || port2 == port |
| 25 | + fun other(port: Int) = if (port1 != port) port1 else port2 |
| 26 | + fun strength() = port1 + port2 |
| 27 | +} |
| 28 | + |
| 29 | +private fun List<Component>.strength() = sumOf(Component::strength) |
| 30 | + |
| 31 | +fun buildStrongestBridge(lastPort: Int, strength: Int, remaining: List<Component>): Int { |
| 32 | + if (remaining.isEmpty()) { |
| 33 | + return strength |
| 34 | + } |
| 35 | + |
| 36 | + val matching = remaining.filter { it.hasPort(lastPort) } |
| 37 | + if (matching.isEmpty()) { |
| 38 | + return strength |
| 39 | + } |
| 40 | + |
| 41 | + return matching.maxOf { buildStrongestBridge(it.other(lastPort), strength + it.strength(), remaining - it) } |
| 42 | +} |
| 43 | + |
| 44 | +fun buildLongestBridge(lastPort: Int, bridge: List<Component>, remaining: List<Component>): List<Component> { |
| 45 | + if (remaining.isEmpty()) { |
| 46 | + return bridge |
| 47 | + } |
| 48 | + |
| 49 | + val matching = remaining.filter { it.hasPort(lastPort) } |
| 50 | + if (matching.isEmpty()) { |
| 51 | + return bridge |
| 52 | + } |
| 53 | + |
| 54 | + return matching |
| 55 | + .map { buildLongestBridge(it.other(lastPort), bridge + it, remaining - it) } |
| 56 | + .filterMaxBy(List<Component>::size) |
| 57 | + .maxBy(List<Component>::strength) |
| 58 | +} |
0 commit comments