library(data.table)
Happy December, R friends!
One of my favorite traditions in the R community is the Advent of Code, a series of puzzles released at midnight EST from December 1st through 25th, to be solved through programming in the language of your choosing. I usually do a few of them each year, and once tried to do every single one at the moment it released!
This year, I know I won’t be able to do it daily, but I’m going to do as many as I can using just data.table
solutions.
I’ll allow myself to use other packages when there isn’t any data.table
equivalent, but my solutions must be as data.table
-y as possible.
I’m going to abuse the blog post structure and update this file throughout the week.
December 1st
Part One
<- fread("day1_dat1.txt") d1
:= sort(V1)]
d1[, V1 := sort(V2)]
d1[, V2 := abs(V1-V2)]
d1[, diff
sum(d1$diff)
[1] 2815556
Part Two
:= sum(V1 == d1$V2)*V1, by = V1]
d1[, similarity
sum(d1$similarity)
[1] 23927637
December 2nd
Part One
<- fread("day2_dat1.txt", fill = TRUE) d1
<- function(vec) {
check_report
<- na.omit(vec)
vec
<- vec < 0
has_neg <- vec > 0
has_pos
<- sum(has_neg) == length(vec) | sum(has_pos) == length(vec)
inc_dec
<- max(abs(vec)) > 3
too_big
return(inc_dec & !too_big)
}
<- transpose(d1)
d1t <- d1t[-nrow(d1t)] - d1t[2:nrow(d1t)]
deltas
<- apply(deltas, 2, "check_report")
res
sum(res)
[1] 479
Part Two
<- function(dat) {
test_reports
<- dat[-nrow(dat)] - dat[2:nrow(dat)]
deltas
<- apply(deltas, 2, "check_report")
res
res }
<- test_reports(d1t)
res
for (i in 1:nrow(d1t)) {
<- res | test_reports(d1t[-i,])
res
}
sum(res)
[1] 531
Just for fun
I found the use of apply
deeply unsatisfying, even though it was fast, so just for fun:
<- transpose(d1)
d1t <- d1t[-nrow(d1t)] - d1t[2:nrow(d1t)]
deltas
<- deltas <= 0
is_not_pos <- deltas >= 0
is_not_neg <- abs(deltas) > 3
is_big
<- colSums(is_not_neg | is_big, na.rm = TRUE)
res_inc
<- colSums(is_not_pos | is_big, na.rm = TRUE)
res_dec
sum(res_inc == 0) + sum(res_dec == 0)
[1] 479
Yay. :)
December 3rd-7th
Nothing data.table
-y in this one; you can see my solution here if you want.