-
Notifications
You must be signed in to change notification settings - Fork 1
/
day07.Rmd
75 lines (74 loc) · 1.51 KB
/
day07.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
---
title: "--- Day 7: Handy Haversacks ---"
author: Fleur Kelpin
date: Dec 7, 2020
output: github_document
---
```{r message=FALSE, warning=FALSE}
library(tidyverse)
input <- readr::read_lines("day07.txt") %>%
as_tibble()
input
```
# Part 1
How many bag colors can eventually contain at least one shiny gold bag?
```{r}
who_contains <- function(type) {
input %>%
extract(value,
paste0("(.+) bags contain .*", type, " bags?"),
into = c("container")
) %>%
drop_na() %>%
{
.$container
}
}
who_contains("shiny gold")
```
```{r}
all_contains <- function(containers, checked) {
new_containers <- containers %>%
map(who_contains) %>%
unlist() %>%
unique() %>%
setdiff(checked)
num_found <- length(new_containers)
if (num_found == 0) {
return(0)
}
length(new_containers) + all_contains(
new_containers,
unique(c(
checked,
containers,
new_containers
))
)
}
all_contains("shiny gold", c())
```
# Part 2
How many individual bags are required inside your single shiny gold bag?
```{r}
contents <- function(type) {
inside <- input %>%
extract(value, paste0(type, " bags contain (.*)"), into = "line") %>%
separate_rows(line, sep = ",") %>%
extract(line,
"(\\d+) (.*) bags?",
convert = TRUE, into = c("num", "type")
) %>%
drop_na()
if (nrow(inside) == 0) {
return(0)
}
inside %>%
rowwise() %>%
mutate(total = num + num * contents(type)) %>%
{
sum(.$total)
}
}
contents("shiny gold")
```