TechWorkRamblings

by Mike Kalvas

202412050000 Advent of Code 2024 Day 05

Print Queue

Today we found the printer from 2017 day 1 and need to help sort it out.

#blog #project

The Puzzle

Today we found the printer from 2017 day 1 and need to help sort it out.

We're given a list of rules and a list of pages that need to be printed in an order determined by the rules. For example,

47|53

75,47,61,53,29
53,47,29

The 47|53 portion of the input is the rule, meaning 47 has to appear before 53 in the pages. The first set of pages passes this rule validation and the second fails. There are some other nuances in how to apply these rules that I won't go into, but you might see in the solution code below.

For the first part of the puzzle, we're asked to find the sets of pages that are valid already. For the second, we're asked to correct the sets that were invalid. In both cases we get our arbitrary puzzle answer by finding the middle number and summing them.

Solution

I went down a long rabbit hole today manually doing things with if statements and jumping around. It was very bad, kind of slow, and a mess to debug, but it eventually got the answer.

Unfortunately, I thought of using a comparator with the built in JS sort method right at the beginning, but didn't pursue that solution because I didn't think it would work. I was worried that there would be cyclical rules and that the sorts would not be deterministic. Thinking about it later, I realized that it would be pretty wild for this puzzle to not adhere to these properties. The solutions would have been more complicated that an AoC day 5 typically is. I should have just plowed through with the sort in the first place. This is what I ended up with after the day was over and I refactored the code.

const middle = (ns) => ns[Math.floor(ns.length / 2)];
const cmp = (rules) => (a, b) => {
  if (rules.includes(`${a}|${b}`)) return -1;
  if (rules.includes(`${b}|${a}`)) return 1;
  return 0;
};

export const solve = (input, fix = false) => {
  let valid = [];
  const [constraints, updates] = groupLines(input);
  for (const u of updates.map((u) => u.split(',').nums())) {
    const sorted = u.clone().sort(cmp(constraints));
    const alreadySorted = u.eq(sorted);
    if (!fix && alreadySorted) valid.push(u);
    else if (fix && !alreadySorted) valid.push(sorted);
  }
  return valid.map(middle).sum();
};

export const solutionOne = (input) => solve(input, false);
export const solutionTwo = (input) => solve(input, true);

Really slow solve today getting caught up in overthinking the solution. That's two of the easier days in a row that I felt like I could have done better. Hopefully I don't miss too many other chances to go quick while they aren't too complicated. I did learn some interesting math bits today though. So overall a win.

You can find the full solutions to today's AoC puzzles in my AoC GitHub repo.