<- function (vec, strs_to_drop) {
helper1_day4 %>%
vec ::str_split(" ") %>%
stringrmap(~.x %>%
setdiff(strs_to_drop) %>%
as.numeric() %>%
!is.na(.)]
.[
)
}= readr::read_delim(
input_df "input.txt",
delim = "|",
col_names = FALSE
)<- input_df %>%
my_counts transmute(
card = 1:n(),
winning_numbers = helper1_day4(X1, strs_to_drop = c("Card", "")),
my_numbers = helper1_day4(X2, strs_to_drop = "")
%>%
) rowwise() %>%
mutate(count = sum(my_numbers %in% winning_numbers)) %>%
ungroup()
Day 4 ⋆⋆
Puzzle
Solution
Preprocessing
Part One
<- sum(ifelse(my_counts$count > 0, 2^(my_counts$count - 1), 0))
answer1 answer1
[1] 21821
Part Two
I find tasks like this – “bespoke” rowwise data frame manipulation – to be easier with for loops. Not pretty, but it gets the job done:
<- my_counts %>%
tmp1_pt2 mutate(copies = 1)
for (card in 1:nrow(tmp1_pt2)) {
<- pull(tmp1_pt2[card,], count)
this_count if (this_count > 0) {
$copies[(card + 1):(card + this_count)] %<>%
tmp1_pt2`+`(tmp1_pt2$copies[card]) ## Syntactic sugar to avoid repeating a long object name
}
}<- sum(tmp1_pt2$copies)
answer2 answer2
[1] 5539496