// merge.mjs — stitching per-copy segment automata into the whole word's ladders. // // A segment carries {n, pref:[[a,len]], suf:[[a,len]], best:[q]} for one copy of the // streamed word. Copies are contiguous in the word and the word is cyclic, so the // merge carries, per translate a, the length of the run ending at the previous // segment's last slot, and joins it to the next segment's leading run. export function mergeSegments(segs, q, cyclic) { const best = new Int32Array(q), carry = new Int32Array(q); for (let s = 0; s < segs.length; s++) { const g = segs[s]; for (let a = 0; a < q; a++) if (g.best[a] > best[a]) best[a] = g.best[a]; const prefLen = new Int32Array(q); for (const [a, len] of g.pref) prefLen[a] = len; for (const [a, len] of g.pref) { const c = carry[a]; if (c > 0) { const j = c + len; if (j > best[a]) best[a] = j; } } const sufSet = new Uint8Array(q); for (const [a, len] of g.suf) { sufSet[a] = 1; carry[a] = (prefLen[a] === g.n && prefLen[a] > 0) ? carry[a] + g.n : len; } for (let a = 0; a < q; a++) if (!sufSet[a]) carry[a] = 0; } if (cyclic && segs.length > 1) { for (const [a, len] of segs[0].pref) { const c = carry[a]; if (c > 0) { const j = c + len; if (j > best[a]) best[a] = j; } } } else if (cyclic && segs.length === 1) { const g = segs[0], sufLen = new Int32Array(q); for (const [a, len] of g.suf) sufLen[a] = len; for (const [a, len] of g.pref) { const j = len + sufLen[a]; if (j > best[a] && j <= g.n) best[a] = j; } } return best; } export function laddersOf(best) { let L_free = best[0], aStar = 0; for (let a = 1; a < best.length; a++) if (best[a] > L_free) { L_free = best[a]; aStar = a; } return { L_anch: best[0], L_free, aStar }; }