base R
lists
Author

Ella Kaye

Published

December 1, 2022

Setup

The original challenge

My data

Part 1

Toggle the code
library(aochelpers)
input <- aoc_input_vector(1, 2022, "numeric")
head(input, 10)
 [1]  5686  2211  1513  7036  5196 10274  2967  2551    NA  5942

In this challenge, we’re given groups of numbers and we need to find the sum of each group. Our solution is the largest of these. The groups are separated by a blank line. When reading in the input as a numeric vector, these are coerced to NA. We can identify the new groups by the NA values, produce an index for them with cumsum(is.na(input)), which increments when a new NA is reached, then use this with split() to split the input into a list of vectors, one for each group. We need the argument na.rm = TRUE in sapply() because each vector, other than the first, starts with NA, as that’s where it was split.

Toggle the code
totals <- split(input, cumsum(is.na(input))) |> 
  sapply(sum, na.rm = TRUE) 

max(totals)
[1] 66719

Part 2

This is similar, except we want to find the sum of the sums of the top three groups.

Toggle the code
sort(totals) |> 
  tail(3) |> 
  sum()
[1] 198551

Session info

Toggle
─ Session info ───────────────────────────────────────────────────────────────
 setting  value
 version  R version 4.3.1 (2023-06-16)
 os       macOS Sonoma 14.1
 system   aarch64, darwin20
 ui       X11
 language (EN)
 collate  en_US.UTF-8
 ctype    en_US.UTF-8
 tz       Europe/London
 date     2023-11-15
 pandoc   3.1.1 @ /Applications/RStudio.app/Contents/Resources/app/quarto/bin/tools/ (via rmarkdown)
 quarto   1.4.489 @ /usr/local/bin/quarto

─ Packages ───────────────────────────────────────────────────────────────────
 package     * version    date (UTC) lib source
 aochelpers  * 0.0.0.9000 2023-11-15 [1] local
 sessioninfo * 1.2.2      2021-12-06 [1] CRAN (R 4.3.0)

 [1] /Users/ellakaye/Library/R/arm64/4.3/library
 [2] /Library/Frameworks/R.framework/Versions/4.3-arm64/Resources/library

──────────────────────────────────────────────────────────────────────────────