# Libraries
library(tidyverse)
# Read input from file
<- read_lines("../input/day11.txt") |>
input trimws() |>
discard(~ .x == "")
Day 11
Advent of Code: Worked Solutions
Setup
Part 1
# Reformat input
<- str_match(input, "Starting items:(.*)")[,2] |>
items discard(is.na) |>
str_split(",") |>
map(parse_number)
<- input |>
operations keep(~ str_detect(.x, "Operation:")) |>
str_replace("Operation: new = ", "~ ") |>
str_replace_all("old", ".x") |>
map(~ rlang::as_function(as.formula(.x)))
<- parse_number(keep(input, ~ str_detect(.x, "Test:")))
div <- parse_number(keep(input, ~ str_detect(.x, "If true:")))
divt <- parse_number(keep(input, ~ str_detect(.x, "If false:")))
divf
<- pmap(
test list(div, divt, divf),
~ function(x) if_else(x %% ..1 == 0, ..2 + 1, ..3 + 1)
)
<- length(input) / 6
num_monkeys
<- function(num_rounds, worry_func) {
compute_monkey_business # Initialize
<- rep(0, num_monkeys)
activity
# Perform the tosses
for (round in 1:num_rounds) {
for (monkey in 1:num_monkeys) {
for (item in items[[monkey]]) {
<- worry_func(operations[[monkey]](item))
worry <- test[[monkey]](worry)
toss <- c(items[[toss]], worry)
items[[toss]]
}<- activity[[monkey]] + length(items[[monkey]])
activity[[monkey]] <- numeric(0)
items[[monkey]]
}
}
# Compute monkey business score
|>
activity sort() |>
tail(2) |>
reduce(`*`)
}
compute_monkey_business(num_rounds = 20, worry_func = \(x) floor(x / 3))
[1] 78678
Part 2
<- DescTools::LCM(div)
lcm compute_monkey_business(num_rounds = 10000, worry_func = \(x) x %% lcm)
[1] 15333249714