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

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more