-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday02.R
34 lines (29 loc) · 794 Bytes
/
day02.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
library(tidyverse)
# read the data
input <- read_lines("data/2024/day02.txt")
# part 1 solution
# helper function
is_safe <- function(vals) {
diffs <- diff(vals)
monotonic <- all(diffs > 0) || all(diffs < 0)
within_range <- all(abs(diffs) >= 1 & abs(diffs) <= 3)
monotonic && within_range
}
# how many reports are safe?
input |>
map(~ str_split(.x, "\\s+")[[1]] |> as.numeric()) |>
map_lgl(is_safe) |>
sum()
# part 2 solution
# helper function
is_safe_dampener <- function(vals) {
if (is_safe(vals)) return(TRUE)
if (length(vals) <= 2) return(FALSE)
if (any(map_lgl(seq_along(vals), ~ is_safe(vals[-.x])))) return(TRUE)
FALSE
}
# now, how many reports are safe?
input |>
map(\(x) str_split(x, "\\s+")[[1]] |> as.numeric()) |>
map_lgl(is_safe_dampener) |>
sum()