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