Day 7: The Treachery of Whales

Click for Problem Statement

Back to 2021


library(tidyverse)
library(here)
path_data <- here("2021/inputs/07-input.txt")
input <- tibble(x = read_lines(path_data))

In this one we must help the crabs save us from a giant whale. Let’s go…

Setup

# raw data
input <- read_lines(path_data)

# make into a vector
data <- input %>% 
  str_split(pattern = ",")
data <- as.numeric(data[[1]])

# test input
testing <- c(16,1,2,0,4,2,7,1,2,14)

# dfs
test <- tibble(raw = testing)
df <- tibble(raw = data)

Part 1

The crabs need a position that minimizes the distance they collectively have to travel. So the median of the distribution.

# every step is equal, so choose the median
part_1 <- df %>% 
  mutate(fuel_spent = abs(raw - median(raw)))

# result
part_1 %>% 
  summarise(total_fuel = sum(fuel_spent))
## # A tibble: 1 × 1
##   total_fuel
##        <dbl>
## 1     342641

Part 2

I would actually want a good explainer on why flooring is necessary rather than rounding. Never adds extra steps? Anywho, we can be fancy about finding the fuel spent thanks to Gauss and his wiliness in school.

# find the steps from the floored mean
# then find spent fuel (thanks Gauss)
part_2 <- df %>% 
  mutate(steps = abs(raw - floor(mean(raw)))) %>% 
  mutate(fuel_spent = (steps * (steps + 1) / 2))
  
# result
part_2 %>% 
  summarise(total_fuel = sum(fuel_spent))
## # A tibble: 1 × 1
##   total_fuel
##        <dbl>
## 1   93006301

All Done!

And the crabs have saved the day! Hope you learned something!

How would you do it? What’s your shortcut? Please share!

Till next time!