library(tidyverse)Day 1
Advent of Code: Worked Solutions
Setup
Import libraries:
Read text input from file into a data frame:
input <- read_table("../input/day01.txt", col_names = c("x", "y"))Part 1
Sort each list independently, then sum the distances between each pair of ordered items:
sum(abs(sort(input$x) - sort(input$y)))Part 2
For each item in list x, multiply its value by its number of occurrences in list y, then sum the total. Since an x value occurring 0 times in list y doesn’t contribute to the total, we can just filter y to the values also in x and sum the result:
sum(keep(input$y, \(y) y %in% input$x))