Advent of Code 2023 Day 3 (Part 1)

Hello everyone.

This is a very unorthodox request on this forum as I would like to know what I am doing wrong in my approach to solving Day 3 (part1) of Advent of Code 2023. The only other question regarding Advent of Code here was posted back in 2018 (Split range of integers using integers only).

Here is my general approach:

  1. Find the position of all symbols in the input (row and column numbers)
  2. Find the position of all adjacent cells around the symbols
  3. Find the position of all numbers in the input
  4. Find the numbers whose position coincides with the positions found in (2) - the part numbers
  5. Sum up all part numbers

My code works well on the test input; however, it fails on the full input (as it always does in AoC!). Would anyone who is also doing AoC with R take a look at my code and let me know what I am doing wrong?o

Thank you very much.

# PART 1 ----

# > Input ----

test1 <- readLines(con = here::here("input/day3_test1.txt"))
input1 <- readLines(con = here::here("input/day3_input1.txt"))

# > Function ----

part1 <- function(input){
  # Find symbols positions
  symbols_df <- purrr::imap_dfr(
    .x = stringr::str_locate_all(string = input, pattern = "[^\\d\\.]"),
    .f = \(cols_matrix, row) {
      if(nrow(cols_matrix) == 0) return(tibble::tibble())
      tibble::tibble(row = row, column = cols_matrix[, "start"])
    }
  )
  
  # Find cells which are adjacent to symbols
  transformation_df <- tibble::tibble(
    row = c(rep(-1, 3), rep(0, 2), rep(1, 3)),
    col = c(-1, 0, 1, -1, 1, -1, 0, 1)
  )
  
  adjacent_df <- purrr::map2_dfr(.x = symbols_df$row, .y = symbols_df$column, .f = \(symbol_row, symbol_col) {
    purrr::map2_dfr(.x = transformation_df$row, .y = transformation_df$col, .f = \(transformation_row, transformation_col) {
      tibble::tibble(row = symbol_row + transformation_row, column = symbol_col + transformation_col)
    })
  }) |>
    dplyr::distinct(row, column) # a given cell may be adjacent to more than one symbol and will, therefore, be duplicated
  
  # Find numbers positions
  numbers_df <- purrr::imap_dfr(.x = input, .f = \(row_data, row_number) {
    purrr::map_dfr(
      .x = stringr::str_extract_all(string = row_data, pattern = "\\d+") |> unlist(),
      .f = \(number){
        ind <- stringr::str_locate(string = row_data, pattern = number) |> as.numeric()
        tibble::tibble(number = number, row = row_number, column = ind[1]:ind[2])
      }
    )
  })
  
  # Find numbers whose positions overlap with adjacent cells
  overlap_df <- dplyr::inner_join(x = numbers_df, y = adjacent_df, by = c("row", "column"))
  
  # Solution
  overlap_df$number |> as.numeric() |> unique() |> sum()
}

part1(input = test1)
part1(input = input1)

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.