Created
December 12, 2020 05:52
-
-
Save warriordog/45c4e1d9b388fe76b0befc589d696425 to your computer and use it in GitHub Desktop.
Solutions to Advent of Code 2020 Day 12 Part 2
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 inputSteps = parseInputFile('day12-input.txt', /^(\w)(\d+)$/gm) | |
.map(([, action, num]) => ({ | |
action, | |
amount: parseInt(num) | |
})); | |
// +east -west | |
// +north -south | |
// 0north 90east 180south 270 west | |
let shipX = 0; | |
let shipY = 0; | |
let wayX = 10; | |
let wayY = 1; | |
function rotateWaypoint(amount) { | |
while (amount > 360) { | |
amount -= 360; | |
} | |
while (amount < 0) { | |
amount += 360; | |
} | |
switch (amount) { | |
case 0: | |
case 360: | |
return; | |
case 90: { | |
const tmpY = wayY; | |
wayY = -1 * wayX; | |
wayX = tmpY; | |
break; | |
} | |
case 180: { | |
wayY = -1 * wayY; | |
wayX = -1 * wayX; | |
break; | |
} | |
case 270: { | |
const tmpY = wayY; | |
wayY = wayX; | |
wayX = -1 * tmpY; | |
break; | |
} | |
default: | |
throw new Error(`Unknown rotation: ${ amount }`); | |
} | |
} | |
for (const step of inputSteps) { | |
switch (step.action) { | |
case 'N': | |
wayY += step.amount; | |
break; | |
case 'S': | |
wayY -= step.amount; | |
break; | |
case 'E': | |
wayX += step.amount; | |
break; | |
case 'W': | |
wayX -= step.amount; | |
break; | |
case 'L': | |
rotateWaypoint(-1 * step.amount); | |
break; | |
case 'R': | |
rotateWaypoint(step.amount); | |
break; | |
case 'F': | |
shipX += (wayX * step.amount); | |
shipY += (wayY * step.amount); | |
break; | |
default: | |
throw new Error('Invalid step'); | |
} | |
} | |
const manhattanDistance = Math.abs(shipX) + Math.abs(shipY); | |
console.log(`Part 2: Manhattan distance of trip is ${ manhattanDistance }`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment