From 49f5c94a750c8a11c7a19f29efa3265549df3d8f Mon Sep 17 00:00:00 2001 From: s2224834 <46319860+s2224834@users.noreply.github.com> Date: Sat, 12 Jan 2019 01:10:47 +0000 Subject: [PATCH] Bombe: further optimisation --- src/core/lib/Bombe.mjs | 63 +++++++++++++++++++++--------------------- 1 file changed, 32 insertions(+), 31 deletions(-) diff --git a/src/core/lib/Bombe.mjs b/src/core/lib/Bombe.mjs index 81581d67..1e3c5b3e 100644 --- a/src/core/lib/Bombe.mjs +++ b/src/core/lib/Bombe.mjs @@ -158,27 +158,6 @@ class SharedScrambler { } } - /** - * Get the fully cached result, if present. - * @param {number} pos - Position of the fast rotor - * @param {number} i - Letter - * @returns {number|undefined} - undefined if not cached - */ - fullTransform(pos, i) { - return this.higherCache[pos][i]; - } - - /** - * Add a value to the full result cache. - * @param {number} pos - Position of the fast rotor - * @param {number} i - Letter - * @param {number} val - Transformed letter - */ - addCache(pos, i, val) { - this.higherCache[pos][i] = val; - this.higherCache[pos][val] = i; - } - /** * Map a letter through this (partial) scrambler. * @param {number} i - The letter @@ -209,6 +188,9 @@ class Scrambler { this.changeRotor(rotor); this.end1 = end1; this.end2 = end2; + // For efficiency reasons, we pull the relevant shared cache from the baseScrambler into + // this object - this saves us a few pointer dereferences + this.cache = this.baseScrambler.higherCache[pos]; } /** @@ -233,6 +215,7 @@ class Scrambler { // simplifies caching the state of the majority of the scramblers. The results are the // same, just in a slightly different order. this.rotor.step(); + this.cache = this.baseScrambler.higherCache[this.rotor.pos]; } @@ -243,14 +226,15 @@ class Scrambler { */ transform(i) { let letter = i; - const cached = this.baseScrambler.fullTransform(this.rotor.pos, i); + const cached = this.cache[i]; if (cached !== undefined) { return cached; } letter = this.rotor.transform(letter); letter = this.baseScrambler.transform(letter); letter = this.rotor.revTransform(letter); - this.baseScrambler.addCache(this.rotor.pos, i, letter); + this.cache[i] = letter; + this.cache[letter] = i; return letter; } @@ -513,12 +497,26 @@ export class BombeMachine { // both. const idxPair = 26*j + i; this.wires[idxPair] = true; + if (i === this.testRegister || j === this.testRegister) { + this.energiseCount++; + if (this.energiseCount === 26) { + // no point continuing, bail out + return; + } + } for (let k=0; k