Published
Edited
Jul 23, 2018
12 stars
Insert cell
Insert cell
Insert cell
crack = {
if (!target.match(/^[a-z]+$/))
throw new Error("Target string must be just lowercase letters.");
let guessed = "";
for (let char = 0; char < target.length; char++) {
const candidates = letters.map(l => ({
char: l,
str: guessed + l,
padded: (guessed + l).padEnd(target.length, " "),
time: 0
}));
// To make this a bit more accurate, this is a triple-decker loop.
// 40000 iterations of each letter, and 2000 iterations in the letter.
// That way, V8 doesn't slowly optimize as it's comparing the 'a' string
// and then run fast optimized comparisons on the rest of the letters:
// this strategy distributes that warmup cost.
for (let i = 0; i < 40000; i++) {
for (let candidate of candidates) {
let s = performance.now();
// actually deriving a value is not necessary here, but I want to try
// and make sure that v8 doesn't simply optimize away the inner loop.
let equalities = 0;
for (let j = 0; j < 2000; j++) {
if (target == candidate.padded) equalities++;
}
candidate.time += performance.now() - s;
}
if (i % 100 == 0) {
yield html`<pre>
char=${char} i=${i}

Candidates:
${candidates
.sort((a, b) => b.time - a.time)
.map(c => `${c.str}=${c.time.toFixed(1)}`)
.join(", ")}</pre>`;
}
}
guessed += candidates.sort((a, b) => b.time - a.time)[0].char;
}
yield `DONE ${guessed}`;
}
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