solve_day4_part1<-function(input){# split on : or |cards<-strsplit(input, ":|\\|")# numbers between : and |winners<-lapply(cards, \(x)x[[2]])winners<-stringi::stri_extract_all(winners, regex ="\\d+")# numbers from | to the end of the lineplaying<-lapply(cards, \(x)x[[3]])playing<-stringi::stri_extract_all(playing, regex ="\\d+")# count playing numbers in winning numberswin_count<-Map(\(w, p)sum(p%in%w),winners,playing)win_count<-as.numeric(unlist(win_count))# remove rows with no winswin_count<-win_count[win_count!=0]# start from 1 and double for each additional winsum(2^(win_count-1))}
Run
aoc_source(day =4, part =1)input=aoc_read(day =4)aoc_run(solve_day4_part1(input))
Elapsed: 0.002 seconds
Memory: 648 KB
— R Day 4 Part 2 —
solve_day4_part2<-function(input){cards<-strsplit(input, ":|\\|")# numbers between : and |winners<-lapply(cards, \(x)x[[2]])winners<-stringi::stri_extract_all(winners, regex ="\\d+")# numbers from | to the end of the lineplaying<-lapply(cards, \(x)x[[3]])playing<-stringi::stri_extract_all(playing, regex ="\\d+")# count playing numbers in winning numberswin_count<-Map(\(w, p)sum(p%in%w),winners,playing)win_count<-unlist(win_count)copies<-rep(1, length(cards))# because cards only add new copies of later cards,# we can sequence along them in orderfor(cardinseq_along(copies)){# if there are winning numbersif(win_count[card]>0){# we add wins to the number of following cardsnew_card_range<-(card+1):(card+win_count[[card]])# the number we add is the number of copies we have of the current cardcopies[new_card_range]<-copies[new_card_range]+copies[card]}}sum(copies)}
Run
aoc_source(day =4, part =2)input=aoc_read(day =4)aoc_run(solve_day4_part2(input))