Skip to content

Instantly share code, notes, and snippets.

@cranderveldt
Created December 7, 2020 02:11
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/d00185cdd3714af4ae26f7f9dcc93960 to your computer and use it in GitHub Desktop.
Save cranderveldt/d00185cdd3714af4ae26f7f9dcc93960 to your computer and use it in GitHub Desktop.
Advent of Code Day 5
const puzzleInput = ``
// Part 1
const TOTAL_ROWS = 128
const TOTAL_COLS = 8
const parseInput = (input) => {
return input.split('\n')
}
const binarySplit = (pos, high) => {
const round = high ? Math.floor : Math.ceil
const key = high ? 'min' : 'max'
pos[key] = pos.max - round((pos.max - pos.min) / 2)
}
const getSeatPosition = (directions) => {
const rowPos = {
min: 0,
max: TOTAL_ROWS - 1,
}
const colPos = {
min: 0,
max: TOTAL_COLS - 1,
}
directions.forEach(char => {
switch (char) {
case 'F': return binarySplit(rowPos, false)
case 'B': return binarySplit(rowPos, true)
case 'L': return binarySplit(colPos, false)
case 'R': return binarySplit(colPos, true)
}
})
return [rowPos.min, colPos.min]
}
const calcSeatId = (seat) => {
const [row, col] = getSeatPosition(seat.split(''))
return row * 8 + col
}
const partOne = (input) => {
const seats = parseInput(input)
const highestSeat = seats.reduce((acc, seat) => Math.max(acc, calcSeatId(seat)), 0)
console.log(highestSeat)
}
partOne(puzzleInput)
// Part 2
const codeForPosition = (row, col) => {
return `${row}:${col}`
}
const bothNeighborsFound = (lookup, row, col) => {
return lookup[codeForPosition(row, col + 1)] && lookup[codeForPosition(row, col - 1)]
}
const partTwo = (input) => {
const seatsLookup = {}
parseInput(input).forEach((seat) => {
const [row, col] = getSeatPosition(seat.split(''))
seatsLookup[codeForPosition(row, col)] = [row, col]
})
const allSeats = []
for (let i = 0; i < TOTAL_ROWS; i++) {
for (let j = 0; j < TOTAL_COLS; j++) {
allSeats.push([codeForPosition(i, j), i, j])
}
}
const missingSeats = allSeats.filter(([code]) => !seatsLookup[code])
const [myCode, myRow, myCol] = missingSeats.find(([code, row, col]) => bothNeighborsFound(seatsLookup, row, col))
console.log(myRow * 8 + myCol)
}
partTwo(puzzleInput)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment