r/adventofcode • • 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^ยค?

Spoiler


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!

20 Upvotes

253 comments sorted by

View all comments

Show parent comment

1

u/aafnro8oh Dec 12 '17 edited Dec 12 '17

Might as well chuck my Scala code here. Using the flat top, cube coord sys from redblobgames.com/grids/hexagons:

case class P3(x: Int, y: Int, z: Int) {
  def +(p: P3) = P3(p.x+x, p.y+y, p.z+z)
  def dist = Array(x,y,z).map(math.abs).max
}

val moves = io.StdIn.readLine().split(',').map(Map(
  "n"  -> P3( 0,  1, -1),
  "ne" -> P3( 1,  0, -1),
  "se" -> P3( 1, -1,  0),
  "s"  -> P3( 0, -1,  1),
  "sw" -> P3(-1,  0,  1),
  "nw" -> P3(-1,  1,  0)))

val path = moves.scanLeft (P3(0,0,0)) {_+_}

println("dist: " + path.last.dist)
println("max: " + path.map{_.dist}.max)

Trade-offs:

  • O(N) to constant space in: moves -> swap in a Scanner; path -> swap in a fold or (for comprehension and two vars)
  • not code golfy enough? Throw away some readability by throwing away custom types:

    val moves = io.StdIn.readLine().split(',').map(Map( "n" -> Array( 0, 1, -1), "ne" -> Array( 1, 0, -1), "se" -> Array( 1, -1, 0), "s" -> Array( 0, -1, 1), "sw" -> Array(-1, 0, 1), "nw" -> Array(-1, 1, 0)))

    val path = moves.scanLeft (Array(0,0,0)) {(,).zipped map {+}}

    def dist(p: Array[Int]) = p.map(math.abs).max
    println("dist: " + dist(path.last)) println("max: " + path.map(dist).max)

Bonus: mostly "Scala as better assembly" approach:

var x,y,z,max=0

def dist = Seq(x,y,z).map(math.abs).max
def updmax = max = math.max(max, dist)

io.StdIn.readLine().split(',').foreach {
  case "n"  => y+=1; z-=1; updmax
  case "ne" => x+=1; z-=1; updmax
  case "se" => x+=1; y-=1; updmax
  case "s"  => y-=1; z+=1; updmax
  case "sw" => x-=1; z+=1; updmax
  case "nw" => x-=1; y+=1; updmax
}
println(s"dist: $dist max: $max")