Skip to content

Instantly share code, notes, and snippets.

@marguslt
Last active December 1, 2023 08:04
Show Gist options
  • Save marguslt/d7b681eb6008b315d8ea21a6248848fa to your computer and use it in GitHub Desktop.
Save marguslt/d7b681eb6008b315d8ea21a6248848fa to your computer and use it in GitHub Desktop.
aoc2023_R
library(tidyverse)
# 1 -----------------------------------------------------------------------
# a: 142
x <- read_lines(
"1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet
")

x |>
  str_remove_all("[^\\d]") |> 
  str_split("") |> 
  map(\(l) str_c(head(l ,1), tail(l, 1))) |>
  map_int(as.numeric) |>
  sum()
#> [1] 142

# 2 -----------------------------------------------------------------------
# a: 281
x <- read_lines(
"two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen
")

num <- setNames(as.character(1:9), 
                c("one", "two", "three", "four", "five", "six", "seven", "eight", "nine")) 
x |>
  str_replace_all("(one|two|three|four|five|six|seven|eight|nine)", "\\1|") |>
  str_replace_all(num) |>
  str_remove_all("[^\\d]") |>
  str_split("") |>
  map(\(l) str_c(head(l ,1), tail(l, 1))) |>
  map_int(as.numeric) |>
  sum()
#> [1] 281

Created on 2023-12-01 with reprex v2.0.2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment