Skip to content

Instantly share code, notes, and snippets.

@xvrdm
Last active December 2, 2021 13:58
Show Gist options
  • Save xvrdm/6bb602e103667c89822aaadaafd587c9 to your computer and use it in GitHub Desktop.
Save xvrdm/6bb602e103667c89822aaadaafd587c9 to your computer and use it in GitHub Desktop.
Advent of Code 2021 in R - Day 1
# ------------------------------------------------------------------------------------------
# Solution with Reduce
# Challenge 1
find_increase <- function(accumulated, next_val) {
is_increase = !is.na(accumulated$previous) && accumulated$previous < next_val
list(
previous = next_val,
count = accumulated$count + ifelse(is_increase, 1, 0)
)
}
readr::read_lines("./days/d01/data.txt") %>%
as.integer() %>%
purrr::reduce(find_increase,
.init = list(previous=NA_integer_, count=0))
# Challenge 2
readr::read_lines("./days/d01/data.txt") %>%
as.integer() %>%
slider::slide(~sum(.x), .after = 2) %>%
purrr::reduce(find_increase,
.init = list(previous=NA_integer_, count=0))
# ------------------------------------------------------------------------------------------
# Solution with Partition
# Challenge 1
partition <- function(x, n) {
r <- embed(x, n)[, n:1]
split(r, row(r))
}
# Or
# partition <- \(x,n) Map(\(i) x[i:(i+n)], seq(length(x)-n))
readr::read_lines("./days/d01/data.txt") %>%
as.integer() %>%
partition(2) %>%
purrr::keep(~ .[2] > .[1]) %>%
length()
# Challenge 2
readr::read_lines("./days/d01/data.txt") %>%
as.integer() %>%
partition(3) %>%
partition(2) %>%
purrr::map_depth(2, sum) %>%
purrr::keep(~ .[[2]] > .[[1]]) %>%
length()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment