Skip to content

Instantly share code, notes, and snippets.

@cranderveldt
Created December 14, 2020 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cranderveldt/3eacffcf1be94cc20856837443dcc8bb to your computer and use it in GitHub Desktop.
Save cranderveldt/3eacffcf1be94cc20856837443dcc8bb to your computer and use it in GitHub Desktop.
Advent of Code 2020 Day 12
const puzzleInput = ``
const parseInput = (input) => {
return input.split(/\n/)
}
// Part 1
const nextDir = (facing, going, amount) => {
const clockwise = 'NESW'
const facingIndex = clockwise.indexOf(facing)
if (going === 'L') {
amount = 360 - amount
}
const goingIndex = (facingIndex + (amount / 90)) % clockwise.length
return clockwise[goingIndex]
}
const moveByDirection = (acc, dir, amount) => {
switch (dir) {
case 'N': return acc.y -= amount
case 'S': return acc.y += amount
case 'E': return acc.x += amount
case 'W': return acc.x -= amount
case 'F': return moveByDirection(acc, acc.facing, amount)
default: return acc.facing = nextDir(acc.facing, dir, amount)
}
}
const parseInstruction = (acc, instruction) => {
const dir = instruction[0]
const amount = parseInt(instruction.substr(1))
moveByDirection(acc, dir, amount)
return acc
}
const partOne = (input) => {
const instructions = parseInput(input)
const distance = instructions.reduce(parseInstruction, { x: 0, y: 0, facing: 'E' })
console.log(Math.abs(distance.x) + Math.abs(distance.y))
}
partOne(puzzleInput)
// Part 2
const moveFerry = (acc, amount) => {
acc.ferry.x += (acc.waypoint.x * amount)
acc.ferry.y += (acc.waypoint.y * amount)
}
const rotateWaypoint = (acc, dir, amount) => {
let { x, y } = acc.waypoint
const steps = Math.floor((dir === 'R' ? amount : (360 - amount)) / 90)
for (let i = 0; i < steps; i++) {
acc.waypoint.x = y * -1
acc.waypoint.y = x
x = acc.waypoint.x
y = acc.waypoint.y
}
}
const moveCorrectly = (acc, dir, amount) => {
switch (dir) {
case 'N': return acc.waypoint.y -= amount
case 'S': return acc.waypoint.y += amount
case 'E': return acc.waypoint.x += amount
case 'W': return acc.waypoint.x -= amount
case 'F': return moveFerry(acc, amount)
default: return rotateWaypoint(acc, dir, amount)
}
}
const navigate = (acc, instruction) => {
const dir = instruction[0]
const amount = parseInt(instruction.substr(1))
moveCorrectly(acc, dir, amount)
return acc
}
const partTwo = (input) => {
const instructions = parseInput(input)
const result = instructions.reduce(navigate, {
waypoint: { x: 10, y: -1 },
ferry: { x: 0, y: 0 },
})
const distance = Math.abs(result.ferry.x) + Math.abs(result.ferry.y)
console.log(distance)
}
partTwo(puzzleInput)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment