Created
December 12, 2020 05:51
-
-
Save warriordog/81f8bd3f8b5b959bf14aeb488e3088f4 to your computer and use it in GitHub Desktop.
Solution to Advent of Code 2020 Day 12 Part 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { parseInputFile } = require('../utils/parser'); | |
const Dir = { | |
NORTH: 0, | |
EAST: 90, | |
SOUTH: 180, | |
WEST: 270 | |
}; | |
const inputSteps = parseInputFile('day12-input.txt', /^(\w)(\d+)$/gm) | |
.map(([, action, num]) => ({ | |
action, | |
amount: parseInt(num) | |
})); | |
// +east -west | |
let x = 0; | |
// +north -south | |
let y = 0; | |
// 0north 90east 180south 270 west | |
let dir = Dir.EAST; | |
function adjustDir(amount) { | |
dir += amount; | |
while (dir > 360) { | |
dir -= 360; | |
} | |
while (dir < 0) { | |
dir += 360; | |
} | |
if (dir === 360) { | |
dir = 0; | |
} | |
} | |
for (const step of inputSteps) { | |
switch (step.action) { | |
case 'N': | |
y += step.amount; | |
break; | |
case 'S': | |
y -= step.amount; | |
break; | |
case 'E': | |
x += step.amount; | |
break; | |
case 'W': | |
x -= step.amount; | |
break; | |
case 'L': | |
adjustDir(-1 * step.amount); | |
break; | |
case 'R': | |
adjustDir(step.amount); | |
break; | |
case 'F': | |
switch (dir) { | |
case Dir.NORTH: | |
y += step.amount; | |
break; | |
case Dir.SOUTH: | |
y -= step.amount; | |
break; | |
case Dir.EAST: | |
x += step.amount; | |
break; | |
case Dir.WEST: | |
x -= step.amount; | |
break; | |
default: | |
throw new Error(`Unknown direction: ${ dir }`); | |
} | |
break; | |
default: | |
throw new Error('Invalid step'); | |
} | |
} | |
const manhattanDistance = Math.abs(x) + Math.abs(y); | |
console.log(`Part 1: Manhattan distance of trip is ${ manhattanDistance }`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment