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:
- Find the position of all symbols in the input (row and column numbers)
- Find the position of all adjacent cells around the symbols
- Find the position of all numbers in the input
- Find the numbers whose position coincides with the positions found in (2) - the part numbers
- 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)