Day 3: Gear Ratios

WebR is loading…

https://adventofcode.com/2023/day/3

Part 1

You and the Elf eventually reach a gondola lift station; he says the gondola lift will take you up to the water source, but this is as far as he can bring you. You go inside.

It doesn’t take long to find the gondolas, but there seems to be a problem: they’re not moving.

“Aaah!”

You turn around to see a slightly-greasy Elf with a wrench and a look of surprise. “Sorry, I wasn’t expecting anyone! The gondola lift isn’t working right now; it’ll still be a while before I can fix it.” You offer to help.

The engineer explains that an engine part seems to be missing from the engine, but nobody can figure out which one. If you can add up all the part numbers in the engine schematic, it should be easy to work out which part is missing.

The engine schematic (your puzzle input) consists of a visual representation of the engine. There are lots of numbers and symbols you don’t really understand, but apparently any number adjacent to a symbol, even diagonally, is a “part number” and should be included in your sum. (Periods (.) do not count as a symbol.)

Here is an example engine schematic:

467..114..
...*......
..35..633.
......#...
617*......
.....+.58.
..592.....
......755.
...$.*....
.664.598..

In this schematic, two numbers are not part numbers because they are not adjacent to a symbol: 114 (top right) and 58 (middle right). Every other number is adjacent to a symbol and so is a part number; their sum is 4361.

Of course, the actual engine schematic is much larger. What is the sum of all of the part numbers in the engine schematic?

Example Input Validation 1

sample1 = `467..114..
...*......
..35..633.
......#...
617*......
.....+.58.
..592.....
......755.
...$.*....
.664.598..`

grid = sample1.split("\n").filter((d) => d != "")
numberLocations = grid
  .map((l) => l.matchAll(/(\d+)/g))
  .map((d, i) =>
    Array.from(d).map((m) => {
      m.y = i;
      return m;
    })
  )
  .flat()
  .map((d) => ({
    value: +d[0],
    start: d.index,
    end: d[0].length + d.index - 1,
    y: d.y
  }))
symbolLocations = grid
  .map((l) => l.matchAll(/([^\d\.])/g))
  .map((d, i) =>
    Array.from(d).map((m) => {
      m.y = i;
      return m;
    })
  )
  .flat()
  .map((d) => ({
    value: d[0],
    start: d.index,
    end: d[0].length + d.index - 1,
    y: d.y
  }))
foundNumbers = [
  ...new Set(
    symbolLocations
      .map((s) => {
        return numberLocations.filter((n) => {
          return (
            s.start >= n.start - 1 &&
            s.end <= n.end + 1 &&
            s.y >= n.y - 1 &&
            s.y <= n.y + 1
          );
        });
      })
      .flat()
  )
]
jsInputValidation1 = {
  const grid = sample1.split("\n").filter((d) => d != "");
  const numberLocations = grid
    .map((l) => l.matchAll(/(\d+)/g))
    .map((d, i) =>
      Array.from(d).map((m) => {
        m.y = i;
        return m;
      })
    )
    .flat()
    .map((d) => ({
      value: +d[0],
      start: d.index,
      end: d[0].length + d.index - 1,
      y: d.y
    }));

  const symbolLocations = grid
    .map((l) => l.matchAll(/([^\d\.])/g))
    .map((d, i) =>
      Array.from(d).map((m) => {
        m.y = i;
        return m;
      })
    )
    .flat()
    .map((d) => ({
      value: d[0],
      start: d.index,
      end: d[0].length + d.index - 1,
      y: d.y
    }));

  return d3.sum(
    [
      ...new Set(
        symbolLocations
          .map((s) => {
            return numberLocations.filter((n) => {
              return (
                s.start >= n.start - 1 &&
                s.end <= n.end + 1 &&
                s.y >= n.y - 1 &&
                s.y <= n.y + 1
              );
            });
          })
          .flat()
      )
    ].map((d) => d.value)
  );
}
rInputValidation1 = await webR.evalRNumber(`
r"(${sample1})" |> 
  stri_split_lines1() -> grid

grid |> 
  imap_dfr(\\(.line, .idx) {
    as.data.frame(
      re_exec_all(.line, "([[:digit:]]+)") |> 
        pull(\`.match\`)
    ) |> 
      rename(               # makes it easier to do the comparison below
        nmatch = match,
        nstart = start,
        nend = end
      ) |> 
      mutate(
        ny = .idx
      )
  }) -> number_matches

grid |> 
  imap_dfr(\\(.line, .idx) {
    as.data.frame(
      re_exec_all(.line, "([^\\\\.[:digit:]]+)") |> # having to double escape these is a annoying
        pull(\`.match\`)
    ) |> 
      mutate(
        y = .idx
      )
  }) -> symbol_matches

symbol_matches |> 
  rowwise() |> 
  mutate(
    found_numbers = list(
      number_matches |> 
        filter(
          start >= nstart - 1 & 
            end <= nend + 1 & 
            y >= ny - 1 & 
            y <= ny + 1
        )
    )
  ) |>  
  unnest(found_numbers) |> 
  distinct(nmatch, nstart, nend, ny) |> 
  pull(nmatch) |> 
  as.integer() |> 
  sum()
`)
jsInputValidation1 == rInputValidation1

Puzzle Input Question 1

jsPuzzleInput1 = {
  const grid = puzzleInput.split("\n").filter((d) => d != "");
  const numberLocations = grid
    .map((l) => l.matchAll(/(\d+)/g))
    .map((d, i) =>
      Array.from(d).map((m) => {
        m.y = i;
        return m;
      })
    )
    .flat()
    .map((d) => ({
      value: +d[0],
      start: d.index,
      end: d[0].length + d.index - 1,
      y: d.y
    }));

  const symbolLocations = grid
    .map((l) => l.matchAll(/([^\d\.])/g))
    .map((d, i) =>
      Array.from(d).map((m) => {
        m.y = i;
        return m;
      })
    )
    .flat()
    .map((d) => ({
      value: d[0],
      start: d.index,
      end: d[0].length + d.index - 1,
      y: d.y
    }));

  return d3.sum(
    [
      ...new Set(
        symbolLocations
          .map((s) => {
            return numberLocations.filter((n) => {
              return (
                s.start >= n.start - 1 &&
                s.end <= n.end + 1 &&
                s.y >= n.y - 1 &&
                s.y <= n.y + 1
              );
            });
          })
          .flat()
      )
    ].map((d) => d.value)
  );
}
rPuzzleInput1 = await webR.evalRNumber(`
r"(${puzzleInput})" |> 
  stri_split_lines1() -> grid

grid |> 
  imap_dfr(\\(.line, .idx) {
    as.data.frame(
      re_exec_all(.line, "([[:digit:]]+)") |> 
        pull(\`.match\`)
    ) |> 
      rename(               # makes it easier to do the comparison below
        nmatch = match,
        nstart = start,
        nend = end
      ) |> 
      mutate(
        ny = .idx
      )
  }) -> number_matches

grid |> 
  imap_dfr(\\(.line, .idx) {
    as.data.frame(
      re_exec_all(.line, "([^\\\\.[:digit:]]+)") |> # having to double escape these is a annoying
        pull(\`.match\`)
    ) |> 
      mutate(
        y = .idx
      )
  }) -> symbol_matches

symbol_matches |> 
  rowwise() |> 
  mutate(
    found_numbers = list(
      number_matches |> 
        filter(
          start >= nstart - 1 & 
            end <= nend + 1 & 
            y >= ny - 1 & 
            y <= ny + 1
        )
    )
  ) |>  
  unnest(found_numbers) |> 
  distinct(nmatch, nstart, nend, ny) |> 
  pull(nmatch) |> 
  as.integer() |> 
  sum()
`)
jsPuzzleInput1 == rPuzzleInput1

Part 2

The engineer finds the missing part and installs it in the engine! As the engine springs to life, you jump in the closest gondola, finally ready to ascend to the water source.

You don’t seem to be going very fast, though. Maybe something is still wrong? Fortunately, the gondola has a phone labeled “help”, so you pick it up and the engineer answers.

Before you can explain the situation, she suggests that you look out the window. There stands the engineer, holding a phone in one hand and waving with the other. You’re going so slowly that you haven’t even left the station. You exit the gondola.

The missing part wasn’t the only issue - one of the gears in the engine is wrong. A gear is any * symbol that is adjacent to exactly two part numbers. Its gear ratio is the result of multiplying those two numbers together.

This time, you need to find the gear ratio of every gear and add them all up so that the engineer can figure out which gear needs to be replaced.

In the original schematic, there are two gears. The first is in the top left; it has part numbers 467 and 35, so its gear ratio is 16345. The second gear is in the lower right; its gear ratio is 451490. (The * adjacent to 617 is not a gear because it is only adjacent to one part number.) Adding up all of the gear ratios produces 467835.

What is the sum of all of the gear ratios in your engine schematic?

gearSymbolLocations = grid
  .map((l) => l.matchAll(/([\*])/g))
  .map((d, i) =>
    Array.from(d).map((m) => {
      m.y = i;
      return m;
    })
  )
  .flat()
  .map((d) => ({
    value: d[0],
    start: d.index,
    end: d[0].length + d.index - 1,
    y: d.y
  }))
jsInputValidation2 = d3.sum(
  symbolLocations
    .map((s) => {
      return numberLocations.filter((n) => {
        return (
          s.start >= n.start - 1 &&
          s.end <= n.end + 1 &&
          s.y >= n.y - 1 &&
          s.y <= n.y + 1
        );
      });
    })
    .filter((d) => d.length == 2)
    .map((d) => d[0].value * d[1].value)
)
rInputValidation2 = await webR.evalRNumber(`
r"(${sample1})" |> 
  stri_split_lines1() -> grid

grid |> 
  imap_dfr(\\(.line, .idx) {
    as.data.frame(
      re_exec_all(.line, "([[:digit:]]+)") |> 
        pull(\`.match\`)
    ) |> 
      rename(               # makes it easier to do the comparison below
        nmatch = match,
        nstart = start,
        nend = end
      ) |> 
      mutate(
        ny = .idx
      )
  }) -> number_matches

grid |> 
  imap_dfr(\\(.line, .idx) {
    as.data.frame(
      re_exec_all(.line, "(\\\\*)") |> 
        pull(\`.match\`)
    ) |> 
      mutate(
        y = .idx
      )
  }) -> gear_matches

gear_matches |> 
  rowwise() |> 
  mutate(
    found_numbers = list(
      number_matches |> 
        filter(
          start >= nstart - 1 & 
            end <= nend + 1 & 
            y >= ny - 1 & 
            y <= ny + 1
        )
    )
  ) |> 
  ungroup() |> 
  filter(
    map_lgl(found_numbers, \\(.x) nrow(.x) == 2)
  ) |> 
  mutate(
    ratio = map_dbl(found_numbers, \\(.x) {
      as.integer(.x$nmatch[1]) * as.integer(.x$nmatch[2])
    })
  ) |> 
  pull(ratio) |> 
  sum()
`)
jsInputValidation2 == rInputValidation2
jsPuzzleInput2 = {
  const grid = puzzleInput.split("\n").filter((d) => d != "");

  const numberLocations = grid
    .map((l) => l.matchAll(/(\d+)/g))
    .map((d, i) =>
      Array.from(d).map((m) => {
        m.y = i;
        return m;
      })
    )
    .flat()
    .map((d) => ({
      value: +d[0],
      start: d.index,
      end: d[0].length + d.index - 1,
      y: d.y
    }));

  const gearSymbolLocations = grid
    .map((l) => l.matchAll(/([\*])/g))
    .map((d, i) =>
      Array.from(d).map((m) => {
        m.y = i;
        return m;
      })
    )
    .flat()
    .map((d) => ({
      value: d[0],
      start: d.index,
      end: d[0].length + d.index - 1,
      y: d.y
    }));

  return d3.sum(
    gearSymbolLocations
      .map((s) => {
        return numberLocations.filter((n) => {
          return (
            s.start >= n.start - 1 &&
            s.end <= n.end + 1 &&
            s.y >= n.y - 1 &&
            s.y <= n.y + 1
          );
        });
      })
      .filter((d) => d.length == 2)
      .map((d) => d[0].value * d[1].value)
  );
}
rPuzzleInput2 = await webR.evalRNumber(`
r"(${puzzleInput})" |> 
  stri_split_lines1() -> grid

grid |> 
  imap_dfr(\\(.line, .idx) {
    as.data.frame(
      re_exec_all(.line, "([[:digit:]]+)") |> 
        pull(\`.match\`)
    ) |> 
      rename(               # makes it easier to do the comparison below
        nmatch = match,
        nstart = start,
        nend = end
      ) |> 
      mutate(
        ny = .idx
      )
  }) -> number_matches

grid |> 
  imap_dfr(\\(.line, .idx) {
    as.data.frame(
      re_exec_all(.line, "(\\\\*)") |> 
        pull(\`.match\`)
    ) |> 
      mutate(
        y = .idx
      )
  }) -> gear_matches

gear_matches |> 
  rowwise() |> 
  mutate(
    found_numbers = list(
      number_matches |> 
        filter(
          start >= nstart - 1 & 
            end <= nend + 1 & 
            y >= ny - 1 & 
            y <= ny + 1
        )
    )
  ) |> 
  ungroup() |> 
  filter(
    map_lgl(found_numbers, \\(.x) nrow(.x) == 2)
  ) |> 
  mutate(
    ratio = map_dbl(found_numbers, \\(.x) {
      as.integer(.x$nmatch[1]) * as.integer(.x$nmatch[2])
    })
  ) |> 
  pull(ratio) |> 
  sum()
`)
jsPuzzleInput2 == rPuzzleInput2
puzzleInput = FileAttachment("/static/data/03-01.txt").text()
webR = {
  const { WebR, ChannelType } = await import(
    "https://cdn.jsdelivr.net/npm/webr/dist/webr.mjs"
  );

  const intWebR = new WebR({
    channelType: ChannelType.PostMessage,
    interactive: false
  });

  await intWebR.init();

  await intWebR.installPackages(
    ["stringi", "dplyr", "purrr", "rematch2", "tidyr"],
    true
  );
  await intWebR.evalRVoid(`suppressPackageStartupMessages({
library(stringi)
library(dplyr)
library(purrr)
library(tidyr)
library(rematch2)
})`);

  document.querySelector("#loader").innerText = "🟢";
  document.querySelector("#msg").innerText = "WebR loaded!";

  return intWebR;
}