|
| 1 | +import de.ronny_h.extensions.Coordinates |
| 2 | +import de.ronny_h.extensions.Direction |
| 3 | +import de.ronny_h.extensions.Direction.EAST |
| 4 | +import de.ronny_h.extensions.Direction.NORTH |
| 5 | +import de.ronny_h.extensions.Direction.SOUTH |
| 6 | +import de.ronny_h.extensions.Direction.WEST |
| 7 | +import de.ronny_h.extensions.Grid |
| 8 | +import de.ronny_h.extensions.ShortestPath |
| 9 | +import de.ronny_h.extensions.aStar |
| 10 | + |
| 11 | +fun main() { |
| 12 | + val day = "Day18" |
| 13 | + |
| 14 | + fun part1(input: List<String>, width: Int): Int { |
| 15 | + val memorySpace = MemorySpace(width, input.map { |
| 16 | + val (x, y) = it.split(',') |
| 17 | + Coordinates(x.toInt(), y.toInt()) |
| 18 | + }) |
| 19 | + memorySpace.printGrid() |
| 20 | + println("-----------------") |
| 21 | + val shortestPaths = memorySpace.shortestPath(Coordinates(0,0), Coordinates(width-1, width-1)) |
| 22 | + memorySpace.printGrid(path = shortestPaths.first().path.associateWith { 'O' }) |
| 23 | + return shortestPaths.first().distance |
| 24 | + } |
| 25 | + |
| 26 | + fun part1Small(input: List<String>) = part1(input, 7) // 0..6 |
| 27 | + fun part1Big(input: List<String>) = part1(input, 71) // 0..70 |
| 28 | + |
| 29 | + fun part2(input: List<String>): Int { |
| 30 | + return input.size |
| 31 | + } |
| 32 | + |
| 33 | + println("$day part 1") |
| 34 | + |
| 35 | + val testInput = readInput("${day}_test") |
| 36 | + printAndCheck(testInput.subList(0, 12), ::part1Small, 22) |
| 37 | + |
| 38 | + val input = readInput(day) |
| 39 | + printAndCheck(input.subList(0, 1024), ::part1Big, 3714264) |
| 40 | + |
| 41 | + |
| 42 | + println("$day part 2") |
| 43 | + |
| 44 | + printAndCheck( |
| 45 | + listOf( |
| 46 | + "1 6" |
| 47 | + ), ::part2, 1 |
| 48 | + ) |
| 49 | + printAndCheck(testInput, ::part2, 31) |
| 50 | + printAndCheck(input, ::part2, 18805872) |
| 51 | +} |
| 52 | + |
| 53 | +private class MemorySpace(width: Int, corrupted: List<Coordinates>) : Grid<Char>(width, width, '.', '#', corrupted) { |
| 54 | + private val corrupted = '#' |
| 55 | + override fun Char.toElementType() = this |
| 56 | + |
| 57 | + fun shortestPath(start: Coordinates, goal: Coordinates): List<ShortestPath<Coordinates>> { |
| 58 | + val neighbours: (Coordinates) -> List<Coordinates> = { node -> |
| 59 | + Direction |
| 60 | + .entries |
| 61 | + .map { node + it } |
| 62 | + .filter { getAt(node) != corrupted } |
| 63 | + } |
| 64 | + |
| 65 | + val d: (Coordinates, Coordinates) -> Int = { a, b -> |
| 66 | + // pre-condition: a and b are neighbours |
| 67 | + 1 |
| 68 | + } |
| 69 | + |
| 70 | + val h: (Coordinates) -> Int = { it taxiDistanceTo goal} |
| 71 | + |
| 72 | + return aStar(start, goal::equals, neighbours, d, h) |
| 73 | + } |
| 74 | +} |
0 commit comments