r/adventofcode • • Dec 06 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 6 Solutions -🎄-

--- Day 6: Chronal Coordinates ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 6

Transcript:

Rules for raising a programmer: never feed it after midnight, never get it wet, and never give it ___.


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked at 0:26:52!

32 Upvotes

387 comments sorted by

View all comments

1

u/chicagocode Dec 07 '18

Kotlin - [Blog/Commentary] | [GitHub Repo]

I was super busy today and didn't get to this until just now. This is one of those days where' I'm optimizing for clarity instead of speed, which is my preference especially for puzzle code.

class Day06(input: List<String>) {

    private val points: List<Point> = input.map { Point.of(it) }
    private val xRange: IntRange = (points.minBy { it.x }!!.x..points.maxBy { it.x }!!.x)
    private val yRange: IntRange = (points.minBy { it.y }!!.y..points.maxBy { it.y }!!.y)

    fun solvePart1(): Int {
        val infinite: MutableSet<Point> = mutableSetOf()
        return xRange.asSequence().flatMap { x ->
            yRange.asSequence().map { y ->
                val closest = points.map { it to it.distanceTo(x, y) }.sortedBy { it.second }.take(2)
                if (isEdge(x, y)) {
                    infinite.add(closest[0].first)
                }
                closest[0].first.takeUnless { closest[0].second == closest[1].second }
            }
        }
            .filterNot { it in infinite }
            .groupingBy { it }
            .eachCount()
            .maxBy { it.value }!!
            .value
    }

    fun solvePart2(range: Int = 10_000): Int =
        xRange.asSequence().flatMap { x ->
            yRange.asSequence().map { y ->
                points.map { it.distanceTo(x, y) }.sum()
            }
        }
            .filter { it < range }
            .count()

    private fun isEdge(x: Int, y: Int): Boolean =
        x == xRange.first || x == xRange.last || y == yRange.first || y == yRange.last

}

data class Point(val x: Int, val y: Int) {
    fun distanceTo(otherX: Int, otherY: Int): Int =
        abs(x - otherX) + abs(y - otherY)

    companion object {
        fun of(input: String): Point =
            input.split(",")
                .map { it.trim().toInt() }
                .run { Point(this[0], this[1]) }
    }
}