base R
lists
Published

December 1, 2022

Setup

The original challenge

My solution

Code
# packages
library(dplyr)

# import data
raw <- read.delim("input.txt", blank.lines.skip = FALSE, header = FALSE)

raw <- rename(raw, calories = V1)

Associate each entry with an elf. Each blank line indicates a new elf.

Code
next.elf <- c(1, which(is.na(raw))) # where do the next elfs start?
n.elf <- length(next.elf)           # how many new elfs?
raw$elfID <- 0                      # set index

index elves

Code
for(e in 1:(n.elf-1)){
  raw$elfID[next.elf[e]:(next.elf[e+1]-1)] <- e
}

add the last elf

Code
raw$elfID[next.elf[e+1]:NROW(raw)] <- n.elf

now drop empty rows

Code
elves <- na.omit(raw)
❓ Which elf has the most calories?
Code
elves %>% group_by(elfID) %>%
  summarize(tot.cals = sum(calories)) %>%
  arrange(desc(tot.cals)) %>% slice(1)
# A tibble: 1 × 2
  elfID tot.cals
  <dbl>    <int>
1   189    68775
❓ How many calories are carried by the top three elves?
Code
top3 <- elves %>% group_by(elfID) %>%
  summarize(tot.cals = sum(calories)) %>%
  arrange(desc(tot.cals)) %>% slice(1:3)
sum(top3$tot.cals)
[1] 202585