2022 - day 01

Author

Hendrik Wagenseil

Data

Load and preview the data set.

y = "2022"
d = "01"

ifl = file.path(
  here::here()
  , y
  , "data"
  , paste0(y, "-day", d, "input")
)

txt = readLines(ifl)
head(txt, n = 30L)
 [1] "4456"  "15332" "15148" "8795"  "11382" ""      "9808"  "8430"  "8486" 
[10] "18918" ""      "57935" ""      "1604"  "3015"  "4529"  "4862"  "1822" 
[19] "4297"  "2568"  "3263"  "3011"  "2127"  "5186"  "1947"  "5816"  "4255" 
[28] "4041"  ""      "35216"

Part I

Aggregate the calories per elf and get the maximum number of calories per elf.

Approach:

  • create a vector of indices for the empty string
  • create vector of start and end indices of each elf
  • create list cal with subsets per elf
  • convert all strings per element of cal to integer and sum up
  • get the maximum
empty = which(txt == "")
from = c(1L, empty + 1L)
to = c(empty - 1L, length(txt))

cal = mapply(
  \(f, t) txt[f:t]
  , f = from
  , t = to
) |> 
  lapply(as.integer) |> 
  lapply(sum) |> 
  unlist() 

max(cal)
[1] 72478

Approach:

  • create an empty list elf
  • create an integer cal which defaults to 0
  • loop over the string list
    • if \(i\)th element is not an empty string, add the value to cal
    • if \(i\)th element is an empty string, append cal to elf and reset cal
  • get the maximum of the result
txt = r.txt

elf = []
cal = 0

for i in range(len(txt)):
  if txt[i] != '':
    cal = cal + int(txt[i])
  else:
    elf.append(cal)
    cal = 0

max(elf)
72478

Part II

Approach:

  • sort vector cal in decreasing order
  • select first three elements and sum up
cal = cal[order(cal, decreasing = TRUE)]
sum(cal[1:3])
[1] 210367
elf.sort(reverse = True)
sum(elf[0:3])
210367