Advertisement
Guest User

Untitled

a guest
Dec 5th, 2021
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.94 KB | None | 0 0
  1. import java.io.File
  2.  
  3. fun main(args: Array<String>) {
  4.     println("2021 Advent of Code day 5")
  5.  
  6.     // Setup - Read the vent lines.
  7.     val LINES_REGEX = """(\d+),(\d+) -> (\d+),(\d+)""".toRegex()
  8.     val ventLines = ArrayList<Pair<Point, Point>>()
  9.     File("day5input").forEachLine {
  10.         val parse = LINES_REGEX.matchEntire(it)
  11.         val p1 = Point(parse?.groups?.get(1)?.value?.toInt()!!, parse?.groups?.get(2)?.value?.toInt()!!)
  12.         val p2 = Point(parse?.groups?.get(3)?.value?.toInt()!!, parse?.groups?.get(4)?.value?.toInt()!!)
  13.         ventLines.add(Pair(p1, p2))
  14.     }
  15.  
  16.     // Create the vent map.
  17.     val vents = VentMap()
  18.  
  19.     // Part 1 - plot the terrain map with just horizontal and vertical lines.
  20.     val straightLines = ventLines.filter { (it.first.x == it.second.x) or (it.first.y == it.second.y) }
  21.     straightLines.forEach { vents.plotLine(it) }
  22.     println("The horizontal and vertical lines overlap at ${vents.overlapCount} points")
  23.  
  24.     // Part 2 - plot the rest of the lines.
  25.     val remainingLines = ventLines.filterNot {(it.first.x == it.second.x) or (it.first.y == it.second.y) }
  26.     remainingLines.forEach { vents.plotLine(it) }
  27.     println("After plotting the remaining lines, they overlap at ${vents.overlapCount} points")
  28. }
  29.  
  30. data class Point(val x:Int, val y:Int)
  31.  
  32. class VentMap() {
  33.     val vents = HashMap<Point, Int>()
  34.     val overlapCount get() = vents.count { it.value > 1 }
  35.  
  36.     fun plotLine(line: Pair<Point, Point>) {
  37.         val dx = if (line.first.x < line.second.x) 1 else if (line.first.x > line.second.x) -1 else 0
  38.         val dy = if (line.first.y < line.second.y) 1 else if (line.first.y > line.second.y) -1 else 0
  39.         var plotPoint = line.first
  40.         while (plotPoint != line.second) {
  41.             vents[plotPoint] = (vents[plotPoint] ?: 0) + 1
  42.             plotPoint = Point(plotPoint.x + dx, plotPoint.y + dy)
  43.         }
  44.         vents[plotPoint] = (vents[plotPoint] ?: 0) + 1
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement