Advent of Code 2021 - Day 1

Hi,

welcome to my solutions to the challenges of Advent of Code 2021. I present my solutions as a short post for every daily challenge. If you do not know what is going on, please go ahead and check out https://adventofcode.com/. I will not go into detail about the problem for day one, since you can simply visit https://adventofcode.com/2021/day/1.

The goal for this year is to solve every puzzle. The puzzles should get harder every day until the 24th of december. I am going to use R, with no added packages. Please the my setup below.

sessionInfo()
## R version 4.0.3 (2020-10-10)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 10 x64 (build 19043)
## 
## Matrix products: default
## 
## locale:
## [1] LC_COLLATE=German_Germany.1252  LC_CTYPE=German_Germany.1252   
## [3] LC_MONETARY=German_Germany.1252 LC_NUMERIC=C                   
## [5] LC_TIME=German_Germany.1252    
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## loaded via a namespace (and not attached):
##  [1] compiler_4.0.3    magrittr_2.0.1    bookdown_0.21     tools_4.0.3      
##  [5] htmltools_0.5.1.1 yaml_2.2.1        stringi_1.5.3     rmarkdown_2.6    
##  [9] blogdown_1.1      knitr_1.30        stringr_1.4.0     digest_0.6.27    
## [13] xfun_0.21         rlang_0.4.10      evaluate_0.14

Solution to day 1

# Data --------------------------------------------------------------------
sonar_data <- read.csv(file = "day_one_sonar",  col.names = "depth", header = FALSE)
head(sonar_data)
##   depth
## 1   184
## 2   205
## 3   211
## 4   213
## 5   227
## 6   225

Part 1:

This can be solved using diff and summing over the logical vector, where diff_depth > 0.

# Solution -----------------------------------------------------------------
diff_depth <- diff(sonar_data$depth)
sum_inc <- sum(diff_depth > 0)
sum_inc
## [1] 1195

Part 2:

I solved part two using a for loop, though there might be a simpler solution.

# Solution -----------------------------------------------------------------
shift_sum <- vector(mode = "numeric", length = nrow(sonar_data) - 2)
for(i in seq_along(shift_sum)) {
  shift_sum[i] <- sum(sonar_data[i : (i + 2), "depth"])
}

sum(diff(shift_sum) > 0)
## [1] 1235

Yes, it is that easy! See you at day 2!

Avatar
Moritz Mueller-Navarra

A Data Scientist using R

Related