Public
Edited
Dec 4, 2023
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
grid = sample1.innerText.split("\n").filter((d) => d != "")
Insert cell
Insert cell
numberLocations = grid
.map((l) => l.matchAll(/(\d+)/g))
.map((d, i) =>
Array.from(d).map((m) => {
m.y = i;
return m;
})
)
.flat()
.map((d) => ({
value: +d[0],
start: d.index,
end: d[0].length + d.index - 1,
y: d.y
}))
Insert cell
Insert cell
symbolLocations = grid
.map((l) => l.matchAll(/([^\d\.])/g))
.map((d, i) =>
Array.from(d).map((m) => {
m.y = i;
return m;
})
)
.flat()
.map((d) => ({
value: d[0],
start: d.index,
end: d[0].length + d.index - 1,
y: d.y
}))
Insert cell
Insert cell
foundNumbers = [
...new Set(
symbolLocations
.map((s) => {
return numberLocations.filter((n) => {
return (
s.start >= n.start - 1 &&
s.end <= n.end + 1 &&
s.y >= n.y - 1 &&
s.y <= n.y + 1
);
});
})
.flat()
)
]
Insert cell
Insert cell
Insert cell
rInputValidation1 = await webR.evalRNumber(`
r"(${sample1.innerText})" |>
stri_split_lines1() -> grid

grid |>
imap_dfr(\\(.line, .idx) {
as.data.frame(
re_exec_all(.line, "([[:digit:]]+)") |>
pull(\`.match\`)
) |>
rename( # makes it easier to do the comparison below
nmatch = match,
nstart = start,
nend = end
) |>
mutate(
ny = .idx
)
}) -> number_matches

grid |>
imap_dfr(\\(.line, .idx) {
as.data.frame(
re_exec_all(.line, "([^\\\\.[:digit:]]+)") |> # having to double escape these is a annoying
pull(\`.match\`)
) |>
mutate(
y = .idx
)
}) -> symbol_matches

symbol_matches |>
rowwise() |>
mutate(
found_numbers = list(
number_matches |>
filter(
start >= nstart - 1 &
end <= nend + 1 &
y >= ny - 1 &
y <= ny + 1
)
)
) |>
unnest(found_numbers) |>
distinct(nmatch, nstart, nend, ny) |>
pull(nmatch) |>
as.integer() |>
sum()
`)
Insert cell
jsInputValidation1 == rInputValidation1
Insert cell
Insert cell
Insert cell
Insert cell
jsPuzzleInput1 == rPuzzleInput1
Insert cell
Insert cell
Insert cell
Insert cell
gearSymbolLocations = grid
.map((l) => l.matchAll(/([\*])/g))
.map((d, i) =>
Array.from(d).map((m) => {
m.y = i;
return m;
})
)
.flat()
.map((d) => ({
value: d[0],
start: d.index,
end: d[0].length + d.index - 1,
y: d.y
}))
Insert cell
jsInputValidation2 = d3.sum(
symbolLocations
.map((s) => {
return numberLocations.filter((n) => {
return (
s.start >= n.start - 1 &&
s.end <= n.end + 1 &&
s.y >= n.y - 1 &&
s.y <= n.y + 1
);
});
})
.filter((d) => d.length == 2)
.map((d) => d[0].value * d[1].value)
)
Insert cell
Insert cell
jsInputValidation2 == rInputValidation2
Insert cell
Insert cell
Insert cell
jsPuzzleInput2 == rPuzzleInput2
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more