Skip to content

Instantly share code, notes, and snippets.

@danellis
Created December 3, 2017 09:43
Show Gist options
  • Save danellis/78b3313b4b1066e966e4fb56cea7cb80 to your computer and use it in GitHub Desktop.
Save danellis/78b3313b4b1066e966e4fb56cea7cb80 to your computer and use it in GitHub Desktop.
AoC 2017 | day 3 | part 2
import scala.annotation.tailrec
val input = 347991
type Grid = Map[(Int, Int), Int]
val grid: Grid = Map(
(0, 0) -> 1,
(1, 0) -> 1
).withDefaultValue(0)
sealed trait Direction
object Upwards extends Direction
object Downwards extends Direction
object Leftwards extends Direction
object Rightwards extends Direction
def neighborSum(grid: Grid, x: Int, y: Int): Int = {
List(
(x - 1, y + 1), (x, y + 1), (x + 1, y + 1),
(x - 1, y), (x + 1, y),
(x - 1, y - 1), (x, y - 1), (x + 1, y - 1)
).map(grid).sum
}
@tailrec
def traverseGrid(grid: Grid, x: Int, y: Int, dir: Direction, level: Int, count: Int, limit: Int): Int = {
val value = neighborSum(grid, x, y)
if (value > limit)
value
else {
val updatedGrid = grid + ((x, y) -> value)
dir match {
case Upwards =>
if (count < level * 2 - 2)
traverseGrid(updatedGrid, x, y + 1, Upwards, level, count + 1, limit)
else
traverseGrid(updatedGrid, x - 1, y, Leftwards, level, 0, limit)
case Leftwards =>
if (count < level * 2 - 1)
traverseGrid(updatedGrid, x - 1, y, Leftwards, level, count + 1, limit)
else
traverseGrid(updatedGrid, x, y - 1, Downwards, level, 0, limit)
case Downwards =>
if (count < level * 2 - 1)
traverseGrid(updatedGrid, x, y - 1, Downwards, level, count + 1, limit)
else
traverseGrid(updatedGrid, x + 1, y, Rightwards, level, 0, limit)
case Rightwards =>
if (count < level * 2)
traverseGrid(updatedGrid, x + 1, y, Rightwards, level, count + 1, limit)
else
traverseGrid(updatedGrid, x, y + 1, Upwards, level + 1, 0, limit)
}
}
}
traverseGrid(grid, 1, 1, Upwards, 1, 0, input)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment