await note(
`Thanks to WebR we can solve this year's Advent of Code puzzles in both R and JavaScript in the same Observable Notebook!`
)
Day 1: Trebuchet?!
⏳ WebR is loading…
https://adventofcode.com/2023/day/1
Part 1
The newly-improved calibration document consists of lines of text; each line originally contained a specific calibration value that the Elves now need to recover. On each line, the calibration value can be found by combining the first digit and the last digit (in that order) to form a single two-digit number.
For example:
1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet
In this example, the calibration values of these four lines are 12, 38, 15, and 77. Adding these together produces 142.
Consider your entire calibration document. What is the sum of all of the calibration values?`
Example Input Validation 1
= `1abc2
sample1 pqr3stu8vwx
a1b2c3d4e5f
treb7uchet`;
= d3.sum(
jsInputValidation1
sample1.split("\n")
.filter((d) => d != "")
.map((d) => {
const digits = d.split("").filter((d) => d.match(/\d/));
return +`${digits[0]}${digits.at(-1)}`;
}) )
= await webR.evalRNumber(`
rInputValidation1 r"(${sample1})" |>
stri_split_lines1() |>
sapply(\\(.s) {
chars <- strsplit(.s, '')[[1]]
chars <- chars[grepl(r"(\\d)", chars)]
as.integer(sprintf("%s%s", chars[1], chars[length(chars)]))
}) |>
sum()
`)
== jsInputValidation1 rInputValidation1
Puzzle Input Question 1
= d3.sum(
jsPuzzleInput1
puzzleInput.split("\n")
.filter((d) => d != "")
.map((d) => {
const digits = d.split("").filter((d) => d.match(/\d/));
return +`${digits[0]}${digits.at(-1)}`;
}) )
= await webR.evalRNumber(`
rPuzzleInput1 r"(${puzzleInput})" |>
stri_split_lines1() |>
sapply(\\(.s) {
chars <- strsplit(.s, '')[[1]]
chars <- chars[grepl(r"(\\d)", chars)]
as.integer(sprintf("%s%s", chars[1], chars[length(chars)]))
}) |>
sum()
`)
== rPuzzleInput1 jsPuzzleInput1
Part 2
Your calculation isn’t quite right. It looks like some of the digits are actually spelled out with letters: one, two, three, four, five, six, seven, eight, and nine also count as valid “digits”.
Equipped with this new information, you now need to find the real first and last digit on each line. For example:
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen
In this example, the calibration values are 29, 83, 13, 24, 42, 14, and 76. Adding these together produces 281.
What is the sum of all of the calibration values?
JS Helpers
= ({
numberMap one: "1",
two: "2",
three: "3",
four: "4",
five: "5",
six: "6",
seven: "7",
eight: "8",
nine: "9"
})
function parseDigits(str) {
let d = [];
while (str.length > 0) {
.push(str.match(/^(\d|one|two|three|four|five|six|seven|eight|nine)/));
d= str.slice(1);
str
}return d.filter((d) => d).map((d) => numberMap[d[0]] || d[0]);
}
WebR Helpers
Example Input Validation 2
= `two1nine
sample2 eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen`
= d3.sum(
jsInputValidation2
sample2.split("\n")
.filter((d) => d != "")
.map((d) => {
const digits = parseDigits(d);
return +`${digits[0][0]}${digits.at(-1)[0]}`;
}) )
= await webR.evalRNumber(`
rInputValidation2 r"(${sample2})" |>
stri_split_lines1() |>
sapply(\\(.s) {
digits <- parse_digits(.s)
as.integer(sprintf("%s%s", digits[1], digits[length(digits)]))
}) |>
sum()
`)
== jsInputValidation2 rInputValidation2
Puzzle Input Question 2`
= d3.sum(
jsPuzzleInput2
puzzleInput.split("\n")
.filter((d) => d != "")
.map((d) => {
const digits = parseDigits(d);
return +`${digits[0][0]}${digits.at(-1)[0]}`;
}) )
= await webR.evalRNumber(`
rPuzzleInput2 r"(${puzzleInput})" |>
stri_split_lines1() |>
sapply(\\(.s) {
digits <- parse_digits(.s)
as.integer(sprintf("%s%s", digits[1], digits[length(digits)]))
}) |>
sum()
`)
== rPuzzleInput2 jsPuzzleInput2
Puzzle Input
= FileAttachment("/static/data/01-01.txt").text() puzzleInput
= {
webR const { WebR, ChannelType } = await import(
"https://cdn.jsdelivr.net/npm/webr/dist/webr.mjs"
;
)
const intWebR = new WebR({
channelType: ChannelType.PostMessage,
interactive: false
;
})
await intWebR.init();
await intWebR.installPackages(["stringi"], true);
await intWebR.evalRVoid(`library(stringi)`);
await intWebR.evalRVoid(`
setNames(
c(1:9, 1:9),
c(
"one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", 1:9)
) -> number_map
number_regex <- sprintf("^(%s)", paste0(names(number_map), collapse="|"))
parse_digits <- function (str) {
out <- c()
while (nchar(str) > 0) {
match <- stri_match_first_regex(str, number_regex)[1]
out <- c(out, match)
str <- substring(str, 2);
}
unname(number_map[as.character(na.omit(out))])
}`);
document.querySelector("#loader").innerText = "🟢";
document.querySelector("#msg").innerText = "WebR loaded!";
return intWebR;
}
Christmas ball/ornament icon from:
https://icon-sets.iconify.design/mingcute/christmas-ball-fill/`