Skip to content

Instantly share code, notes, and snippets.

@jnolis
Created December 7, 2021 05:53
Show Gist options
  • Save jnolis/50df59133123017277fc3ca6f1d85f57 to your computer and use it in GitHub Desktop.
Save jnolis/50df59133123017277fc3ca6f1d85f57 to your computer and use it in GitHub Desktop.
Advent of Code 2021 Day 7
library(tidyverse)
data <-
read_lines("07/input.txt") %>%
str_split(",") %>%
.[[1]] %>%
as.integer()
# part 1
# the optimal location to meet is exactly the median (think L1 space if you're mathy)
location <- median(data)
fuel <- sum(abs(data-location))
# part 2
# the optimal location allowing for non-integer spaces is exactly the mean, but since we have to
# round it to an integer you can try the floor and ceiling of that location
location <- mean(data)
fuel_func <- function(x,y) if(x==y) 0 else sum(1:(abs(x-y)))
location_floor <- sum(map_dbl(data,~fuel_func(.x,floor(location))))
location_ceiling <- sum(map_dbl(data,~fuel_func(.x,ceiling(location))))
min(location_floor, location_ceiling)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment