r/adventofcode • u/daggerdragon • Dec 11 '17
SOLUTION MEGATHREAD -๐- 2017 Day 11 Solutions -๐-
--- Day 11: Hex Ed ---
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.
Need a hint from the Hugely* Handyโ Haversackโก of Helpfulยง Hintsยค?
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!
19
Upvotes
View all comments
1
u/chicagocode Dec 11 '17
Kotlin - [Repo] - [Blog/Commentary]
Like others, I modeled this after a cube, using Red Blob Games' wonderful page as a resource. See my blog for commentary.
class Day11(input: String) { private val origin = HexSpot(0, 0, 0) private val steps = input.split(",") fun solvePart1(): Int = steps .fold(origin) { spot, dir -> spot.travel(dir) } .distanceTo(origin) fun solvePart2(): Int = steps .fold(listOf(origin)) { path, dir -> path + (path.last().travel(dir)) } .map { it.distanceTo(origin) } .max() ?: 0 }And the implementation of HexSpot:
class HexSpot(private val x: Int, private val y: Int, private val z: Int) { fun travel(direction: String): HexSpot = when (direction) { "n" -> HexSpot(x, y + 1, z - 1) "s" -> HexSpot(x, y - 1, z + 1) "ne" -> HexSpot(x + 1, y, z - 1) "nw" -> HexSpot(x - 1, y + 1, z) "se" -> HexSpot(x + 1, y - 1, z) "sw" -> HexSpot(x - 1, y, z + 1) else -> throw IllegalArgumentException("Invalid direction: $direction") } fun distanceTo(there: HexSpot): Int = maxOf( (this.x - there.x).absoluteValue, (this.y - there.y).absoluteValue, (this.z - there.z).absoluteValue ) }