Code
# packages
library(dplyr)
# import data
<- read.delim("input.txt", blank.lines.skip = FALSE, header = FALSE)
raw
<- rename(raw, calories = V1) raw
December 1, 2022
Associate each entry with an elf. Each blank line indicates a new elf.
index elves
add the last elf
now drop empty rows
# A tibble: 1 × 2
elfID tot.cals
<dbl> <int>
1 189 68775
---
title: "2022: Day 1"
date: 2022-12-1
categories: [base R, lists]
draft: false
---
## Setup
[The original challenge](https://adventofcode.com/2022/day/1)
## My solution
```{r}
# 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.
```{r}
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
```{r}
for(e in 1:(n.elf-1)){
raw$elfID[next.elf[e]:(next.elf[e+1]-1)] <- e
}
```
add the last elf
```{r}
raw$elfID[next.elf[e+1]:NROW(raw)] <- n.elf
```
now drop empty rows
```{r}
elves <- na.omit(raw)
```
:::{.callout-warning icon=false}
### ❓ Which elf has the most calories?
:::
```{r}
elves %>% group_by(elfID) %>%
summarize(tot.cals = sum(calories)) %>%
arrange(desc(tot.cals)) %>% slice(1)
```
:::{.callout-warning icon=false}
### ❓ How many calories are carried by the top three elves?
:::
```{r}
top3 <- elves %>% group_by(elfID) %>%
summarize(tot.cals = sum(calories)) %>%
arrange(desc(tot.cals)) %>% slice(1:3)
sum(top3$tot.cals)
```