dt <- readLines("input.txt")
polymer <- dt[!grepl(" -> ", dt)][1]
polymer <- str_split(polymer, "", simplify = TRUE)[1,]
pairs <-
data.frame(str_split(dt[grepl(" -> ", dt)], " -> ", simplify = TRUE))
dt <-
data.frame("x" = polymer[-length(polymer)], "y" = polymer[-1]) %>%
mutate("z" = paste0(x, y, sep = "")) %>%
select("z") %>%
group_by(z) %>%
count()
counts <- unique(unlist(strsplit(pairs$X1, "")))
counts <-
rep(0, length(counts)) %>%
`names<-`(sort(unique(counts))) %>%
data.frame() %>%
rownames_to_column(var = "value") %>%
`colnames<-`(c("value", "n")) %>%
rbind(table(polymer) |> data.frame() |> `colnames<-`(c("value", "n"))) %>%
group_by(value) |>
summarise(n = sum(n)) |>
ungroup()
build_poly <- function(dt, counts, i = 1) {
if (i == 40 + 1) { return(counts) }
dt <- dt %>%
right_join(pairs, by = c("z" = "X1")) %>%
filter(!is.na(n))
counts <-
dt %>%
group_by(X2) %>%
summarise(n = sum(n)) %>%
ungroup() %>%
`colnames<-`(c("value", "n")) %>%
rbind(counts) %>%
group_by(value) %>%
summarise(n = sum(n)) %>%
ungroup() %>%
filter(!is.na(n))
dt <- dt %>%
separate("z", into = c("x", "y"), sep = 1) %>%
mutate(x = paste(x, X2, sep = ""),
y = paste(X2, y, sep = "")) %>%
select(-X2) %>%
pivot_longer(cols = c(x, y)) %>%
select(-name) %>%
group_by(value) %>%
summarise(n = sum(n)) %>%
ungroup() %>%
rename("z" = value)
build_poly(dt, counts, i + 1)
}
options(digits = 20)
tab <-
build_poly(dt, counts) |>
deframe() |>
sort()
tab[length(tab)] - tab[1]