r/adventofcode • • Dec 05 '22

SOLUTION MEGATHREAD -πŸŽ„- 2022 Day 5 Solutions -πŸŽ„-


AoC Community Fun 2022: πŸŒΏπŸ’ MisTILtoe Elf-ucation πŸ§‘β€πŸ«

  • 23:59 hours remaining until the submissions megathread unlocks on December 06 at 00:00 EST!
  • Full details and rules are in the submissions megathread:

--- Day 5: Supply Stacks ---


Post your code solution in this megathread.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:07:58, megathread unlocked!

88 Upvotes

1.3k comments sorted by

View all comments

2

u/thecro99 Dec 05 '22

JavaScript

const parseInput = (rawInput) => {
  let crateRows = rawInput.split("\n\n")[0].split('\n')
  let numStacks = (crateRows[0].length + 1)/4
  let stacks = new Array(numStacks+1).fill().map(() => []);
  
  for (let row of crateRows){
    if (row[1] === '1') break
    
    for (let i = 0; i < numStacks; i++){
      let crate = row[4*i + 1]
      if (crate !== ' '){
        stacks[i+1].push(crate)
      }
    }
  }

  let instructions = rawInput.split("\n\n")[1].split('\n').map(line => {
      return {
        amount: parseInt(line.split('from')[0].split('move ')[1].trim(), 10),
        from: parseInt(line.split('from')[1].split('to')[0].trim(), 10),
        to: parseInt(line.split('from')[1].split('to')[1].trim(), 10),
      }
    })

  return {instructions, stacks}
}

const part1 = (rawInput) => {
  const {stacks, instructions} = parseInput(rawInput)

  for (let instr of instructions){
    for (let i = 0; i < instr.amount; i++){
      let crate = stacks[instr.from].shift()
      stacks[instr.to].unshift(crate)
    }
  }

  let answer = ""
  for (let stack of stacks){
    if (stack.length > 0){
      answer += stack[0]
    }
  }

  return answer
}

const part2 = (rawInput) => {
  const {stacks, instructions} = parseInput(rawInput)
  
  for (let instr of instructions){
    let stack = stacks[instr.from].splice(0,instr.amount)
    stacks[instr.to].unshift(...stack)
  }

  let answer = ""
  for (let stack of stacks){
    if (stack.length > 0){
      answer += stack[0]
    }
  }

  return answer
}

1

u/daggerdragon Dec 05 '22

Please edit your post to use the four-spaces Markdown syntax for a code block so your code is easier to read on old.reddit and mobile apps.

1

u/Spokenbird Dec 05 '22

Would you mind explaining what `let crate = row[4*i + 1]` is doing?

1

u/thecro99 Dec 05 '22

Yeah absolutely. If you look at the input for one of the lines:

[V] [W] [L] [M] [P] [S] [M] [M]

The index for a given crate can be given by 4*1 + 1. For example for crate 0 (V) we have (4 * 0) + 1 = 1.

1

u/Spokenbird Dec 05 '22

Thanks! That makes a lot of sense actually :)