# Libraries
library(tidyverse)
# Read input from file
<- read_table(
input "../input/day01.txt",
col_names = c("x", "y"),
show_col_types = FALSE
)
Day 1
Advent of Code: Worked Solutions
Setup
Part 1
Sort each list independently, then sum the distances between each pair of ordered items.
tibble(
x = sort(input$x),
y = sort(input$y),
dist = abs(y - x)
|>
) summarize(total = sum(dist)) |>
pull()
[1] 2285373
Part 2
For each item in list x
, multiply its value by its number of occurrences in list y
, then sum the total.
|>
input mutate(
x_match_count = map_int(x, ~ sum(.x == y)),
similarity_score = x * x_match_count
|>
) summarize(total = sum(similarity_score)) |>
pull()
[1] 21142653