Published
Edited
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function* animate({patterns, output}) {
const search = key(patterns);
let i = 0;
for (const wiring of permute([..."abcdefg"])) {
const found =
key(initial.map((r) => r.map((i) => wiring[i])).map(sort)) === search;
if (i++ % 50 === 0 || found)
yield html`
${patterns.map((p) => display(p, wiring))}
   
${output.map((p) => display(p, wiring))}
`;
if (found) break;
}
}
Insert cell
display = (segments, wiring = [..."abcdefg"]) => svg`
<svg viewBox="-1 -1 12 22" width="20" height="40">
${[...segments].map((a) => rects[wiring.indexOf(a)]).join("")}
</svg>
`
Insert cell
rects = [
`<rect x="1" y="0" width="8" height="1" />`,
`<rect x="0" y="1" width="1" height="9" />`,
`<rect x="9" y="1" width="1" height="9" />`,
`<rect x="1" y="10" width="8" height="1" />`,
`<rect x="0" y="11" width="1" height="9" />`,
`<rect x="9" y="11" width="1" height="9" />`,
`<rect x="1" y="20" width="8" height="1" />`
]
Insert cell
part2 = d3.sum(data, decode)
Insert cell
decode = ({patterns, output}) => {
const numbers = lookup.get(key(patterns));
return +output.map((d) => numbers.indexOf(d)).join("")
}
Insert cell
Insert cell
lookup = d3.index(all(), key)
Insert cell
key = (patterns) => String(patterns.slice().sort())
Insert cell
sort = (pattern) => d3.sort(pattern).join("")
Insert cell
Insert cell
function* all() {
for (const wiring of permute([..."abcdefg"]))
yield initial.map((r) => r.map((i) => wiring[i])).map(sort);
}
Insert cell
// https://stackoverflow.com/a/37580979
function* permute(permutation) {
var length = permutation.length,
c = Array(length).fill(0),
i = 1, k, p;

yield permutation.slice();
while (i < length) {
if (c[i] < i) {
k = i % 2 && c[i];
p = permutation[i];
permutation[i] = permutation[k];
permutation[k] = p;
++c[i];
i = 1;
yield permutation.slice();
} else {
c[i] = 0;
++i;
}
}
}
Insert cell
initial = [
[0, 1, 2, 4, 5, 6],
[2, 5],
[0, 2, 3, 4, 6],
[0, 2, 3, 5, 6],
[1, 2, 3, 5],
[0, 1, 3, 5, 6],
[0, 1, 3, 4, 5, 6],
[0, 2, 5],
[0, 1, 2, 3, 4, 5, 6],
[0, 1, 2, 3, 5, 6]
]
Insert cell
part1 = data.flatMap((d) => d.output.map((p) => p.length)).filter(l => lengths.has(l)).length
Insert cell
lengths = new Set([2, 3, 4, 7])
Insert cell
data = (which === "test" ? test : input).split("\n").map((line) => {
const [patterns, output] = line
.split(" | ")
.map((half) => half.split(" ").map(sort));
return { patterns, output };
})
Insert cell
Insert cell
test0 = `acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf`
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