Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package advent
- import java.awt.Point
- import kotlin.math.abs
- import kotlin.math.max
- import kotlin.math.min
- class Day3 {
- private class Line(
- val x1 : Int,
- val y1 : Int,
- val x2 : Int,
- val y2 : Int
- ) {
- fun isHorizontal() = y1 == y2
- override fun toString() = "[$x1, $y1] -> [$x2, $y2]"
- }
- private class Step(
- val direction : String,
- val steps : Int
- ) {
- override fun toString() = "$direction$steps"
- }
- companion object {
- private fun getInput() : Pair<List<Step>, List<Step>> {
- val lines = javaClass
- .getResource("/Day3Input")
- .readText()
- .lines()
- .map { line ->
- line.split(',').map { Step(it.substring(0, 1), it.substring(1).toInt()) }
- }
- return Pair(lines[0], lines[1])
- }
- private fun getWire(steps : List<Step>) : MutableList<Line> {
- var (x, y) = Pair(0, 0)
- val lines = mutableListOf<Line>()
- for (step in steps) {
- val (x0, y0) = Pair(x, y)
- when (step.direction) {
- "U" -> y -= step.steps
- "D" -> y += step.steps
- "L" -> x -= step.steps
- "R" -> x += step.steps
- }
- lines.add(Line(min(x0, x), min(y0, y), max(x0, x), max(y0, y)))
- }
- return lines
- }
- private fun areLinesIntersecting(line1 : Line, line2 : Line) : Point? {
- val hLine : Line
- val vLine : Line
- if (line1.isHorizontal() && !line2.isHorizontal()) {
- hLine = line1
- vLine = line2
- } else if (!line1.isHorizontal() && line2.isHorizontal()) {
- hLine = line2
- vLine = line1
- } else {
- return null
- }
- if (hLine.y1 >= vLine.y1 && hLine.y1 <= vLine.y2 && vLine.x1 >= hLine.x1 && vLine.x1 <= hLine.x2) {
- return Point(vLine.x1, hLine.y1)
- }
- return null
- }
- private fun getIntersections(wire1 : List<Line>, wire2 : List<Line>) : MutableList<Point> {
- val intersections = mutableListOf<Point>()
- for (line1 in wire1) {
- for (line2 in wire2) {
- areLinesIntersecting(line1, line2)?.let { intersections.add(it) }
- }
- }
- return intersections
- }
- @JvmStatic
- fun main(args : Array<String>) {
- val input = getInput()
- val wire1 = getWire(input.first)
- val wire2 = getWire(input.second)
- val intersections = getIntersections(wire1, wire2)
- var closestDistance= Int.MAX_VALUE
- intersections.forEach {
- val distance = abs(it.x) + abs(it.y)
- if (distance in 1 until closestDistance) {
- closestDistance = distance
- }
- }
- println(closestDistance)
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement