Published
Edited
Dec 10, 2020
1 fork
1 star
Insert cell
Insert cell
Insert cell
answer1 = {
let jolt1 = 1,
jolt3 = 1;
for (let i = 0; i < input.length - 1; i++) {
const dj = input[i + 1] - input[i];
if (dj === 1) jolt1++;
else if (dj === 3) jolt3++;
}
return { jolt1, jolt3, prod: jolt1 * jolt3 };
}
Insert cell
Insert cell
answer2 = {
// make a directed acyclic graph out of all possible connections
// {v: value, c: children, a: arrangements}
const root = { v: 0, c: [], a: 0 };
const nodeMap = new Map();
for (const v of input) {
nodeMap.set(v, { v, c: [], a: 0 });
}
for (let i = 1; i <= 3; i++) {
const child = nodeMap.get(i);
if (child) root.c.push(child);
}
for (const [v, node] of nodeMap) {
for (let i = v + 1; i <= v + 3; i++) {
const child = nodeMap.get(i);
if (child) node.c.push(child);
}
}
// now use recursion + memoization to compute all arrangements
const maxJolt = input[input.length - 1];
const arrangements = node => {
if (node.a !== 0) return node.a;
if (node.v === maxJolt) {
node.a = 1;
return 1;
}
for (const child of node.c) {
node.a += arrangements(child);
}
return node.a;
};

arrangements(root);
return { arrangements: root.a, root, nodeMap };
}
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