Skip to content

Instantly share code, notes, and snippets.

@sclark39
Last active December 7, 2017 09:57
Show Gist options
  • Save sclark39/b7441ddac94b4cbd8fc4e644c021feaf to your computer and use it in GitHub Desktop.
Save sclark39/b7441ddac94b4cbd8fc4e644c021feaf to your computer and use it in GitHub Desktop.
Advent of code 2017 Day 3 part 2
// Advent of Code 2017 - Day 3 Part 2
// by @sclark39
var add = ( a, b ) => ([ a[0] + b[0], a[1] + b[1] ])
var turn = (a) => ( a[0] == 0 ? [ -a[1], 0 ] : [ 0, a[0] ] )
function buildSpiral(input)
{
var spiral = [ [1] ]
spiral.get = ( c ) => ( spiral[c[0]] && spiral[c[0]][c[1]] )
spiral.set = ( c, v ) => {
spiral[c[0]] = spiral[c[0]] || []
spiral[c[0]][c[1]] = v
}
var d = [1,0], c = [0,0]
while ( true )
{
// Move cursor
c = add( c, d )
// Find sum of adjacent
var sum = 0
for ( var i = -1; i <= 1; i++ )
for ( var j = -1; j <= 1; j++ )
sum += spiral.get( add( c, [i,j] ) ) || 0
// Add to spiral
spiral.set( c, sum )
// Time to return?
if ( sum > input )
return sum
// Should we change direction?
var l = add( c, turn(d) )
if ( ! spiral.get( l ) )
d = turn(d)
}
}
console.log( buildSpiral(289326) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment