Public
Edited
Dec 22
Paused
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function process(n) {
n ^= (n << 6) & 0xffffff; // Multiply by 64
n ^= (n >>> 5) & 0xffffff; // Divide by 32
n ^= (n << 11) & 0xffffff; // Multiply by 2048
return n;
}
Insert cell
Insert cell
function iterate(secret, n) {
return Array.from({ length: n }).reduce((s) => process(s), secret);
}
Insert cell
function part1(input) {
return d3.sum(input.split("\n").map((n) => iterate(Number(n), 2000)));
}
Insert cell
Insert cell
Insert cell
Insert cell
function changeSequence(secret, n) {
const result = [];
let s = secret;
let prev = secret % 10;

for (let i = 0; i < n; i++) {
s = process(s);
result.push([s % 10, (s % 10) - prev]);
prev = s % 10;
}

return result;
}
Insert cell
Insert cell
Insert cell
function encodeSeq(seq) {
return (
(seq[0] + 9) * 6859 + (seq[1] + 9) * 361 + (seq[2] + 9) * 19 + (seq[3] + 9)
);
}
Insert cell
function part2(input) {
let seqPrices = new Map(); // Global map for all buyers

input.split("\n").forEach((secret) => {
const changes = changeSequence(Number(secret), 2000);
const monkeySeq = new Map(); // Map for each monkey

let seq4 = changes.slice(0, 4).map((d) => d[1]);
monkeySeq.set(encodeSeq(seq4), changes[3][0]);

for (let i = 4; i < changes.length; i++) {
seq4.push(changes[i][1]);
seq4.shift();

// If the sequence has already been matched for this monkey, skip it
const seqKey = encodeSeq(seq4);
if (!monkeySeq.has(seqKey)) {
monkeySeq.set(seqKey, changes[i][0]);
}
}

// Merge the current monkey's prices into the global prices
seqPrices = AOC.mergeMaps(seqPrices, monkeySeq);
});

return d3.max([...seqPrices.values()]);
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
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