Day 1

AdventOfCode > 2022

Part 1: How many Calories are being carried by the Elf carrying the most Calories?

I manually downloaded my personal day 1 input file as a logged user, and here I get the data with blank lines as NA and “calories” as column name:

library(tidyverse)
── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
✔ ggplot2 3.4.0      ✔ purrr   0.3.5 
✔ tibble  3.1.8      ✔ dplyr   1.0.10
✔ tidyr   1.2.1      ✔ stringr 1.4.1 
✔ readr   2.1.3      ✔ forcats 0.5.2 
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
data <- 
  read_csv(
        here::here("2022/01_input"),
        col_names = c("calories"),
        show_col_types = FALSE,
        skip_empty_rows = FALSE
    )
data %>% print(n = 30)
# A tibble: 2,275 × 1
   calories
      <dbl>
 1    15931
 2     8782
 3    16940
 4    14614
 5       NA
 6     4829
 7    12415
 8    13259
 9    11441
10     8199
11       NA
12     2540
13     2500
14     6341
15     2235
16     1858
17     4157
18     5053
19     6611
20     1050
21     4401
22     6187
23     1078
24     3297
25       NA
26    25264
27    23014
28    15952
29       NA
30    10156
# … with 2,245 more rows

I identify elfs for each row, starting by 1:

data %>% 
    mutate(elf_id = 1 + cumsum(is.na(calories)))
# A tibble: 2,275 × 2
   calories elf_id
      <dbl>  <dbl>
 1    15931      1
 2     8782      1
 3    16940      1
 4    14614      1
 5       NA      2
 6     4829      2
 7    12415      2
 8    13259      2
 9    11441      2
10     8199      2
# … with 2,265 more rows

I sum the calories carried by each elf:

data %>% 
    mutate(elf_id = 1 + cumsum(is.na(calories))) %>% 
    group_by(elf_id) %>%
    summarise(calories = sum(calories, na.rm = TRUE))
# A tibble: 268 × 2
   elf_id calories
    <dbl>    <dbl>
 1      1    56267
 2      2    50143
 3      3    47308
 4      4    64230
 5      5    47238
 6      6    51084
 7      7    43075
 8      8    55682
 9      9    43784
10     10    46694
# … with 258 more rows

I sort the data to find the Elf carrying the most Calories and select it.

data %>% 
    mutate(elf_id = 1 + cumsum(is.na(calories))) %>% 
    group_by(elf_id) %>%
    summarise(calories = sum(calories, na.rm = TRUE)) %>% 
    arrange(-calories) %>%
    head(1)
# A tibble: 1 × 2
  elf_id calories
   <dbl>    <dbl>
1     22    70116

Part 2: How many calories are carried by the top three Elves carrying the most Calories?

data %>% 
    mutate(elf_id = 1 + cumsum(is.na(calories))) %>% 
    group_by(elf_id) %>%
    summarise(calories = sum(calories, na.rm = TRUE)) %>% 
    arrange(-calories) %>% 
    head(3) %>% 
    summarize(top3 = sum(calories))
# A tibble: 1 × 1
    top3
   <dbl>
1 206582