Skip to content

Instantly share code, notes, and snippets.

@whaley
Created January 20, 2018 11:15
Show Gist options
  • Save whaley/a73c81bdd1357c59fff4ebb324967b9d to your computer and use it in GitHub Desktop.
Save whaley/a73c81bdd1357c59fff4ebb324967b9d to your computer and use it in GitHub Desktop.
fun main(args: Array<String>) {
println(createGridUntil(325489).values.max() ?: 0)
}
data class Point(val x: Int, val y: Int)
fun createGridUntil(target: Int) : Map<Point,Int>{
val initial = Point(0, 0)
val knownPointsAndScores = hashMapOf(initial to 1)
var direction = Direction.RIGHT
var currentPoint = initial
var steps = 1
var stepsRemainingBeforeTurn = steps
while ((knownPointsAndScores[currentPoint] ?: 0) < target) {
if (stepsRemainingBeforeTurn == 0 && (direction == Direction.UP || direction == Direction.DOWN)) {
direction = direction.nextDirection()
steps++
stepsRemainingBeforeTurn = steps - 1
} else if (stepsRemainingBeforeTurn == 0) {
direction = direction.nextDirection()
stepsRemainingBeforeTurn = steps - 1
} else {
stepsRemainingBeforeTurn--
}
currentPoint = direction.nextPoint(currentPoint)
val score: Int = knownPointsAndScores.keys.intersect(adjacentPoints(currentPoint)).sumBy {
knownPointsAndScores[it] ?: 0 }
knownPointsAndScores[currentPoint] = score
}
return knownPointsAndScores
}
fun adjacentPoints(point: Point): Set<Point> {
val adjacentPoints = hashSetOf<Point>()
for (x in -1..1) {
for (y in -1..1) {
adjacentPoints.add(Point(point.x + x, point.y + y))
}
}
return adjacentPoints
}
enum class Direction {
UP {
override fun nextDirection(): Direction = LEFT
override fun nextPoint(point: Point) = Point(point.x, point.y + 1)
},
DOWN {
override fun nextDirection(): Direction = RIGHT
override fun nextPoint(point: Point) = Point(point.x, point.y - 1)
},
LEFT {
override fun nextDirection(): Direction = DOWN
override fun nextPoint(point: Point) = Point(point.x - 1, point.y)
},
RIGHT {
override fun nextDirection(): Direction = UP
override fun nextPoint(point: Point) = Point(point.x + 1, point.y)
};
abstract fun nextDirection(): Direction
abstract fun nextPoint(point: Point): Point
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment