Skip to content

Latest commit

 

History

History
120 lines (87 loc) · 9.75 KB

05.md

File metadata and controls

120 lines (87 loc) · 9.75 KB

Day 05

Part 1

Find the highest seat ID from the given boarding passes.

Let's start by determining the rows:

const input = `FBFBBFFRLR
BFFFBBFRRR
FFFBBBFRRR
BBFFBBFRLL`

input.split('\n').forEach((boardingPass) => {
  const rowInstructions = boardingPass.slice(0, 7)

  const row = [...rowInstructions].reduce(
    (acc, instruction) => {
      const half = Math.ceil((acc.max - acc.min) / 2)

      if (instruction === 'F') acc.max -= half
      else acc.min += half

      return acc
    },
    { min: 0, max: 127 }
  )
})

Then let's determine the columns. Instead of having two nearly identical reducers, let's have just one:

const reducer = (acc, instruction) => {
  const half = Math.ceil((acc.max - acc.min) / 2)

  if (instruction === 'F' || instruction === 'L') acc.max -= half
  else acc.min += half

  return acc
}

input.split('\n').forEach((boardingPass) => {
  const rowInstructions = boardingPass.slice(0, 7)
  const colInstructions = boardingPass.slice(-3)

  const row = [...rowInstructions].reduce(reducer, { min: 0, max: 127 })
  const col = [...colInstructions].reduce(reducer, { min: 0, max: 7 })
})

Nice. Then we can determine the highest seat ID by changing the forEach() to reduce(). Let's also refactor the reducer to be shorter (and possibly less readable, heh):

const reducer = ({ min, max }, instruction) => {
  const half = Math.ceil((max - min) / 2)

  return instruction === 'F' || instruction === 'L'
    ? { min, max: max - half }
    : { min: min + half, max }
}

const result = input.split('\n').reduce((highestSeatId, boardingPass) => {
  const rowInstructions = boardingPass.slice(0, 7)
  const colInstructions = boardingPass.slice(-3)

  const row = [...rowInstructions].reduce(reducer, { min: 0, max: 127 })
  const col = [...colInstructions].reduce(reducer, { min: 0, max: 7 })

  const seatId = row.min * 8 + col.min
  return Math.max(seatId, highestSeatId)
}, 0)

console.log(result)

Try it out on flems.io

Part 2

Find our seat ID, i.e. the missing ID.

Almost the same as Part 1:

const allIds = input.split('\n').reduce((ids, boardingPass) => {
  const rowInstructions = boardingPass.slice(0, 7)
  const colInstructions = boardingPass.slice(-3)

  const row = [...rowInstructions].reduce(reducer, { min: 0, max: 127 })
  const col = [...colInstructions].reduce(reducer, { min: 0, max: 7 })

  const seatId = row.min * 8 + col.min
  ids.push(seatId)
  return ids
}, [])

const previousId = allIds.sort().find((id, i) => allIds[i + 1] !== id + 1)
const myId = previousId + 1

console.log(myId)

flems

What did I learn?

Nothing, but the video The Better Boarding Method Airlines Won't Use linked on the puzzle page was interesting.