Public
Edited
Aug 25, 2023
1 fork
1 star
Insert cell
Insert cell
Insert cell
MD5Lib = require("hash-wasm@4.9.0/dist/md5.umd.min.js")
Insert cell
Insert cell
function getHash(salt, index) {
return MD5Lib.md5(salt + index);
}
Insert cell
Insert cell
async function findKeys(salt, hashFn) {
// return 22429; // Quite slow, so returning result directly. Uncomment to run
const candidates = []; // Candidate keys
const keys = []; // Valid keys
const recentHashes = Array(1000).fill(""); // Store only the most recent 1000 hashes

for (let i = 0; keys.length < 64; i++) {
const hash = await hashFn(salt, i);
recentHashes[i % 1000] = hash; // Store in recentHashes ring-buffer style

// Check if hash is a candidate
const match = hash.match(/(\w)\1\1/);
if (match) {
candidates.push({ i, hash, char: match[1] });
}

// Check if for previously valid candidate in the last 1000 hashes
const candidate = candidates.find((c) => c.i === i - 1000);
if (candidate) {
const pattern = `${candidate.char}{5}`;
if (recentHashes.some((h) => h.match(pattern))) {
keys.push({ i: candidate.i, hash });
}
}
}
return keys[63].i;
}
Insert cell
part1 = findKeys(puzzleInput, getHash)
Insert cell
Insert cell
Insert cell
Insert cell
async function getStretchedHash(salt, index) {
let hash = await MD5Lib.md5(salt + index);
for (let i = 0; i < 2016; i++) {
hash = await MD5Lib.md5(hash);
}
return hash;
}
Insert cell
part2 = 22429 // Quite slow (c.35s); uncomment to run: findKeys(puzzleInput,getStretchedHash)
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