GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — crypto/eng.js at main · dk14/crypto Expand file tree/ Copy patheng.jsMore file actions 1619 lines (1269 loc) · 51.9 KB / Copy patheng.jsFile metadata and controls1619 lines (1269 loc) · 51.9 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 // find non-overlapping occurrences of pattern in state (left-to-right) function findNonOverlappingOccurrences(state, pattern) { const n = state.length, m = pattern.length; if (m === 0 || m > n) return []; const occ = []; for (let i = 0; i <= n - m; ) { let ok = true; for (let j = 0; j < m; j++) { if (state[i + j] !== pattern[j]) { ok = false; break; } } if (ok) { occ.push(i); i += m; } else { i += 1; } } return occ; } // getPossibleIntroSections(state, zeroToken) using non-overlapping matches function getPossibleIntroSections(state, zeroToken) { if (!Array.isArray(zeroToken) || zeroToken.length === 0) return []; const occ = findNonOverlappingOccurrences(state, zeroToken); if (occ.length < 2) return []; const sections = []; const m = zeroToken.length; for (let k = 0; k < occ.length - 1; k++) { const s = occ[k] + m; // first index after k-th match const e = occ[k + 1] - 1; // last index before (k+1)-th match if (s <= e + 1) sections.push({ start: s, end: e, slice: state.slice(s, e + 1) }); } return sections; } // helper to count occurrences of a needle (allow overlaps) const countOccurrences = (hay, needle) => { const n = hay.length, m = needle.length; if (m === 0) return 0; let c = 0; for (let i = 0; i + m <= n; i++) { let j = 0; while (j < m && hay[i + j] === needle[j]) j++; if (j === m) c++; } return c; }; // input: introSection: BigInt[], state: BigInt[] // output: Map<string, {count: number, firstStart: number}> function tokenize(introSection, state) { const nIntro = introSection.length, nState = state.length; const serialize = (arr, start, len) => { let s = ''; for (let i = 0; i < len; i++) { if (i) s += ','; s += arr[start + i].toString(); } return s; }; // 1) candidates that appear >1 times in state const inState = new Map(); // key -> stateCount (we only need >1) for (let s = 0; s < nIntro; s++) { for (let len = 1; s + len <= nIntro; len++) { const key = serialize(introSection, s, len); if (inState.has(key)) continue; let cnt = 0; for (let i = 0; i + len <= nState; i++) { let j = 0; while (j < len && state[i + j] === introSection[s + j]) j++; if (j === len) cnt++; if (cnt > 1) break; } if (cnt > 1) inState.set(key, cnt); } } if (inState.size === 0) return new Map(); // 2) collect positions inside introSection for each candidate (sorted) const positions = new Map(); // key -> [start indices] for (let s = 0; s < nIntro; s++) { for (let len = 1; s + len <= nIntro; len++) { const key = serialize(introSection, s, len); if (!inState.has(key)) continue; if (!positions.has(key)) positions.set(key, []); positions.get(key).push(s); } } for (const arr of positions.values()) arr.sort((a,b) => a-b); // 3) prepare candidates sorted by descending length (prefer longer tokens) const candidates = []; for (const [k, cState] of inState.entries()) { const len = k === '' ? 0 : k.split(',').length; candidates.push({ key: k, len, cState }); } candidates.sort((a, b) => b.len - a.len || b.cState - a.cState || (a.key < b.key ? -1 : 1)); // 4) select non-overlapping occurrences in introSection, // and record first occurrence start for each token const covered = new Array(nIntro).fill(false); const result = new Map(); // key -> { count, firstStart } for (const cand of candidates) { const starts = positions.get(cand.key) || []; let taken = 0; let firstStart = -1; for (const st of starts) { // check if this occurrence is free (no overlap with already taken occurrences) let conflict = false; for (let p = st; p < st + cand.len; p++) { if (covered[p]) { conflict = true; break; } } if (conflict) continue; // take it for (let p = st; p < st + cand.len; p++) covered[p] = true; if (firstStart === -1) firstStart = st; taken++; } if (taken > 0) result.set(cand.key, { count: countOccurrences(introSection, parseKey(cand.key)), firstStart }); } return result; } const startsWith = (seq, pat) => { if (pat.length > seq.length) return false; for (let i = 0; i < pat.length; i++) { if (seq[i] !== pat[i]) return false;} return true; }; function findUniqueSuffix(space, label, stopAt) { const candidates = []; for (let i = 0; i <= space.length - label.length; i++) { let match = true; for (let j = 0; j < label.length; j++) { if (space[i + j] !== label[j]) { match = false; break; } } if (!match) continue; const suffix = []; for (let k = i + label.length; k < space.length; k++) { let isLabel = true; for (let j = 0; j < label.length && k + j < space.length; j++) { if (space[k + j] !== label[j]) { isLabel = false; break; } } if (isLabel) break; if (stopAt.some(pat => startsWith(space.slice(k), pat))) break; suffix.push(space[k]); } if (suffix.length > 0) candidates.push(suffix); } if (candidates.length === 1) return candidates[0]; return undefined; } const space = [1n,2n,3n,4n,5n,6n]; const label = [2n,3n]; const stopAt = [[5n]]; console.log("SUFFIX:" + findUniqueSuffix(space, label, stopAt)) function tokensCoverSection(tokens, section) { const startMap = new Map(); tokens.forEach((tok, idx) => { const first = tok[0]; if (!startMap.has(first)) startMap.set(first, new Set()); startMap.get(first).add(idx); }); let i = 0; const used = new Set(); while (i < section.length) { const candidates = startMap.get(section[i]); if (!candidates) return false; let matched = false; for (const idx of candidates) { const tok = tokens[idx]; if (i + tok.length > section.length) continue; let ok = true; for (let j = 0; j < tok.length; j++) { if (section[i + j] !== tok[j]) { ok = false; break; } } if (!ok) continue; matched = true; i += tok.length; break; } if (!matched) return false; } return i === section.length; } function inferIncDec(state, zeroToken) { const sections = getPossibleIntroSections(state, zeroToken); const emptySections = sections.some(x => x.end - x.start == -1) if (sections.length === 0 || emptySections) return [[], [], 0, []] const acc = [[], [], 0, []] const incDecTokenIntro = state.slice(0, sections[0].start - zeroToken.length) for(let i = 0; i < sections.length; i++) { const sec = sections[i] const intro = sec.slice; const tokens = tokenize(intro, incDecTokenIntro.concat(intro)); // Map key -> {count, firstStart} if (tokens.size < 2) { //console.log(")))))" + parse(enrichSeqNo(incDecTokenIntro))) //console.log([...tokens.keys()].map(tk => parse(enrichSeqNo(parseKey(tk))))) return [[], [], -(i+1), []] } const entries = Array.from(tokens.entries()); const incSet = new Set(), decSet = new Set(); for (let i = 0; i < entries.length; i++) { for (let j = i + 1; j < entries.length; j++) { const [ki, vi] = entries[i]; const [kj, vj] = entries[j]; if (vi.count > 0 && vi.count === vj.count) { if (vi.firstStart <= vj.firstStart) { incSet.add(ki); decSet.add(kj); } else { incSet.add(kj); decSet.add(ki); } } } } if (incSet.size > 0 && decSet.size > 0) { for (const t of Array.from(incSet)) { if (decSet.has(t)) { incSet.delete(t); decSet.delete(t); } } const merged = [...(new Set([...incSet, ...decSet]))].map(parseKey) if (!tokensCoverSection(merged, intro)){ return acc } acc[0] = Array.from(new Set([...(new Set(acc[0])), ...incSet])) acc[1] = Array.from(new Set([...(new Set(acc[1])), ...decSet])) acc[2] = i + 1 acc[3].push(sec) //console.log("-----" + parse(enrichSeqNo(zeroToken))) //console.log("++++++" + parse(enrichSeqNo(incDecTokenIntro))) } else { return acc } } return acc; } function parseKey(key) { return key.split(',').map(s => BigInt(s)); } function countVar(state, tokenisation) { const [incs, decs] = tokenisation || [[], []]; // build list of needles (arrays) from keys const makeNeedles = (keys) => keys.map(k => ({ key: k, arr: parseKey(k), len: k === '' ? 0 : k.split(',').length })); const incNeedles = makeNeedles(incs); const decNeedles = makeNeedles(decs); let count = 0; for (const n0 of incNeedles) count += countOccurrences(state, n0.arr); for (const n0 of decNeedles) count -= countOccurrences(state, n0.arr); return count; } const eraseSeqNo = (seq) => { return seq.map(x => x[0]) } const enrichSeqNo = (seq) => { return seq.map((x, i) => [x, i]) } //todo enrich original token seqNo into turing machine const zeroBranch = (state, seq) => { for (let i = 0; i < seq.length; i++) { const candidate = eraseSeqNo(seq.slice(0, i)) const inference = inferIncDec(eraseSeqNo(state), candidate) if (inference[0].length > 0) { const [incs, decs, secCount, sections] = inference if (incs.length > 1 || decs.length > 1) { continue } return { varName: parse(enrichSeqNo(candidate)), zero: enrichSeqNo(candidate), incs: incs.map(x => enrichSeqNo(parseKey(x))), decs: decs.map(x => enrichSeqNo(parseKey(x))), incNames: incs.map(x => parse(enrichSeqNo(parseKey(x)))), decNames: decs.map(x => parse(enrichSeqNo(parseKey(x)))), secCount: secCount, sections: sections } } } return undefined } const checkIfEndsWithToken = (output, tokens) => { for (token of tokens) { const strippedToken = eraseSeqNo(token) const strippedOutput = eraseSeqNo(output.slice(-token.length)) if (bigIntArraysEqual(strippedToken, strippedOutput)) { return true } } return false } const parseIncDec = (inference) => { const [incs, decs, count] = inference const incsData = incs.map(inc => parse(enrichSeqNo(parseKey(inc)))) const decsData = decs.map(dec => parse(enrichSeqNo(parseKey(dec)))) return `incs: ${incsData}; decs: ${decsData}; sections=${count}` } console.log("HELLO") const intro = [1n,2n,3n,2n,3n]; const state2 = [1n,3n,0n,4n,1n,2n,0n, 3n,2n,1n,2n,1n,2n]; const map = tokenize(intro, state2); for (const [k,v] of map) console.log(k, '->', v); const MAX_UNICODE = 0x10FFFFn; function entityToBigInt(fragment) { const decMatch = fragment.match(/^&#(\d+);$/); if (decMatch) return BigInt(decMatch[1]); const hexMatch = fragment.match(/^&#x([0-9a-fA-F]+);$/); if (hexMatch) return BigInt('0x' + hexMatch[1]); return null; } function cpToString(cp) { if (cp <= MAX_UNICODE) { return String.fromCodePoint(Number(cp)); } return `&#${cp.toString()};`; } function tokenToBigInt(token) { const entity = entityToBigInt(token); if (entity !== null) return entity; // token is a normal character – get its code point const cp = token.codePointAt(0); return BigInt(cp); } function render(input) { const result = []; let pos = 0; let i = 0; while (i < input.length) { if (input[i] === '&') { const semi = input.indexOf(';', i + 1); if (semi !== -1) { const candidate = input.slice(i, semi + 1); const big = entityToBigInt(candidate); if (big !== null) { result.push([big, pos++]); i = semi + 1; continue; } } } const cp = input.codePointAt(i); result.push([BigInt(cp), pos++]); i += cp > 0xFFFF ? 2 : 1; } if (result.length === 1 && !result[0]) return [] return result; } function parse(state) { if (state === undefined || state.length === 0 || (state.length === 1 && !state[0])) return '' return state .map(([cp]) => cpToString(cp)) .join(''); } //turing executor and termination oracle function inferMembound(turing) { const base = turing.filter(x => x[1] !== 0n && x[1] < TURING_OFFSET).length return { currentExpansion: base, currentHyperop: 0n, hyperopBound: turing.filter(x => x[1] > TURING_OFFSET).length, baseBound: base, } } function powBigInt(base, exponent) { base = BigInt(base); exponent = BigInt(exponent); if (exponent < 0n) throw new RangeError('negative exponent not supported for BigInt'); let result = 1n; while (exponent > 0n) { if (exponent & 1n) result *= base; base *= base; exponent >>= 1n; } return result; } function checkMembound(value, membound) { let counter = 0n while (membound.currentExpansion < value && membound.currentHyperop < membound.hyperopBound) { counter++ if (counter > 30n) { console.log(membound) throw "check mem overflow" } membound.currentExpansion = powBigInt(membound.currentExpansion, membound.baseBound) membound.currentHyperop++ } return membound.currentExpansion >= value } function minBigInt(arr) { if (arr.length === 0) return undefined return arr.reduce((a, b) => (a < b ? a : b)); } function maxBigInt(arr) { if (arr.length === 0) return undefined return arr.reduce((a, b) => (a > b ? a : b)); } const getJumpDestination = jump => jump[1] - TURING_OFFSET const createJumpDestination = cur => cur + TURING_OFFSET const getLoopVar = jump => jump[0] const filterCov = (coverage, start, end) => new Set([...coverage].filter(x => x >= start && x <= end)) function checkLoopSegment(turing, coverage, jump, cursor, memory, lastLoopVarState, lastCov) { if (!lastLoopVarState || !lastCov) return true const loopStart = getJumpDestination(jump) const loopEnd = cursor if (loopStart > loopEnd) return true const loopVarIdx = getLoopVar(jump) const loopVar = memory[loopVarIdx] const segmentJumps = turing.slice(Number(loopStart), Number(loopEnd)).map(getJumpDestination).filter(x => x >= 0n) const minDest = minBigInt(segmentJumps) const maxDest = maxBigInt(segmentJumps) > loopEnd ? BigInt(turing.length-1) : loopEnd //todo improve up to any instruction that jumps above loopEnd const expandedStart = minDest === undefined ? loopStart : minBigInt([loopStart, minDest]) const expandedEnd = maxDest === undefined ? loopEnd : maxBigInt([loopStart, maxDest]) //todo check if expanded segment refers to variables in current segment //todo check if dec extruction mentioned for loopvar at all //todo exclude unreachable segments - no dec instruction for forward jmp const segmentCov = filterCov(coverage, expandedStart, expandedEnd) const segmentLastCov = filterCov(coverage, expandedStart, expandedEnd) if (BigInt(segmentCov.size) >= expandedEnd - expandedStart && loopVar >= lastLoopVarState && loopVar !== 0n) { return false } return true } function bigIntArraysEqual(a, b) { if (a.length !== b.length) return false; for (let i = 0; i < a.length; i++) { if (a[i] !== b[i]) return false; // BigInt compared with === } return true; } function checkRepeatCfg(state, cursor, history) { for (const x of history){ const [pastCursor, pastState] = x if (pastCursor === cursor && bigIntArraysEqual(pastState, state)) { return false } } return true } const TURING_INC = 2n const TURING_DEC = 1n const TURING_OUT = 0n const TURING_OFFSET = 100n const TURING_JMP = (instrPointer) => instrPointer + TURING_OFFSET //input is sequence of [mem_address, instr_address] //instr_address past offset jmpnz mem_address (instr_address - offset) //other instr_address as inc dec out function executeTuring(turing, ctx = {}) { ctx.trace = [] ctx.membound = inferMembound(turing) const membound = ctx.membound let cursor = 0n ctx.memory = [] const memory = ctx.memory const output = [] ctx.history = [] const history = ctx.history ctx.coverage = new Set() const coverage = ctx.coverage const lastCoverageForJmp = {} const lastLoopVarStateForJmp = {} let safeCounter = 0n while (cursor < turing.length) { ctx.trace.push(cursor) safeCounter++ if (safeCounter > 3000n) { console.log(ctx) console.log(printTuring(turing)) throw "overflow " + cursor } const [mem, instr] = turing[cursor] if (instr === TURING_OUT) { output.push(mem) coverage.add(cursor) cursor++ } else if (instr === TURING_INC) { if (memory[mem] === undefined) memory[mem] = 0n memory[mem]++ if(!checkMembound(memory[mem], membound)) { const loopJmp = turing.findLastIndex(x => x[1] >= TURING_OFFSET + BigInt(turing.length)) const noOuterJumps = loopJmp !== -1 && !turing.slice(loopJmp).some(x => x[1] > TURING_OFFSET && x[1] < TURING_OFFSET + BigInt(loopJmp)) if (noOuterJumps) { memory[turing[loopJmp][0]] = mem cursor = loopJmp } else { console.log("LOOP HYPER: " + cursor) ctx.loopHyper = cursor ctx.loopState = memory[mem] return output } } else { coverage.add(cursor) cursor++ } } else if (instr === TURING_DEC) { if (memory[mem] === undefined) memory[mem] = 0n memory[mem]-- if (memory[mem] < 0n) memory[mem] = 0n coverage.add(cursor) cursor++ } else { if (memory[mem] === undefined) memory[mem] = 0n if (memory[mem] === 0n) { cursor++ } else { const nextCursorShift = turing.slice(Number(cursor) + 1).findIndex(x => x[1] !== TURING_OUT) const nextCursor = nextCursorShift === -1 ? turing.length + 1 : cursor + BigInt(nextCursorShift) + 1n coverage.add(cursor) const lastCov = lastCoverageForJmp[cursor.toString] const lastLoopVarState = lastLoopVarStateForJmp[cursor.toString] const nonTerminationRecovery = turing[nextCursor] && turing[nextCursor][1] - TURING_OFFSET !== cursor && turing[nextCursor][1] > TURING_OFFSET && turing[nextCursor][0] === mem //for theorem provers if (!checkLoopSegment(turing, coverage, turing[cursor], cursor, memory, lastLoopVarState, lastCov)) { if (nonTerminationRecovery) { cursor = nextCursor } else { console.log("LOOP SEG: " + cursor) ctx.loopSegment = cursor return output } } else { cursor = instr - TURING_OFFSET if (!checkRepeatCfg(memory, cursor, history)) { if (nonTerminationRecovery) { cursor = nextCursor } else { console.log("LOOP REPEAT: " + cursor) ctx.loopRepeat = cursor return output } } lastCoverageForJmp[cursor.toString] = coverage lastLoopVarStateForJmp[cursor.toString] = memory[mem] } } } } return output } function genJump(turing, varIdx, label) { const outs = turing .map((x,i) => [x[0], x[1], BigInt(i)]) .filter(x => x[1] === 0n) .map(x => [x[0], x[2]]) //char, line_no const instrPointer = find(outs, label)[0] //take first label if (instrPointer === undefined) { return undefined } return [varIdx, instrPointer[1] + TURING_OFFSET] } function genStubJmp(turing, varIdx) { return [varIdx, BigInt(turing.length) + TURING_OFFSET + 1n] } function genInc(varIdx) { return [varIdx, TURING_INC] } function genDec(varIdx) { return [varIdx, TURING_DEC] } function genOut(next) { return [next[0], 0n] } function printTuring(turing, parseOut=true) { return turing.map((x, i) => { if (x[1] === TURING_INC) { return `${i}: inc \$${x[0]}` } else if (x[1] === TURING_DEC) { return `${i}: dec \$${x[0]}` } else if (x[1] === TURING_OUT) { return `${i}: out ${parseOut ? parse([[x[0], 0]]):x[0]}` } else { return `${i}: jmp \$${x[0]} -> ${getJumpDestination(x)}` } }).join("\n") } const ctxTuring = {} const program = [ [0n, TURING_INC], [0n, TURING_JMP(0n)], [0n, TURING_JMP(4n)], [20n, TURING_OUT], [-1n, TURING_OUT], [0n, TURING_INC], ] const program2 = [ [0n, TURING_INC], [0n, TURING_JMP(0n)], [0n, TURING_OUT], [0n, TURING_JMP(100n)], [-1n, TURING_OUT], ] console.log("\n\nTURING TEST") console.log(printTuring(program, false)) const output = executeTuring(program, ctxTuring) console.log("TURING OUT: " + output) console.log(ctxTuring) console.log("TURING END\n\n\n") //prediction const range = limit => Array.from({ length: limit + 1 }, (_, i) => i); const createMask = (length, maskCfg) => { return new Set() } const makeKey = (arr) => arr.map(x => x.toString()).join(",") const registerRule = (stateRun, patternRun, ctx, next) => { const stateRule = stateRun.map(v => v.toString()).join(','); const patternRule = patternRun.map(v => v.toString()).join(','); if (!ctx.transform.has(patternRule)) { ctx.transform.set(patternRule, {}); ctx.transformStr.set(parse(enrichSeqNo(patternRun)), {}); } if (ctx.transform.get(patternRule)[makeKey(next)] === undefined) { ctx.transform.get(patternRule)[makeKey(next)] = [] ctx.transformStr.get(parse(enrichSeqNo(patternRun)))[parse([next])] = []; } ctx.transform.get(patternRule)[makeKey(next)].push(stateRun) ctx.transformStr.get(parse(enrichSeqNo(patternRun)))[parse([next])].push(parse(stateRun)); } const emitRules = (stateArr, patternArr, next, ctx, sMask, pMask, start) => { if (sMask.size === 0 && pMask.size === 0) return let i = 0; let j = 0; const sections = (set) => { const arr = [...set].sort((a,b)=>a<b?-1:1) const breaks = allBreaks(arr) if (breaks.length === 0) { return [set] } breaks.push(arr.length - 1) const res = []; const pairs = [0, ...breaks].map((x, i) => [x, breaks[i]]) return pairs.map(range => new Set(arr.slice(range[0], range[1] + 1))) } const applyMask = (mask, arr) => { const maskArr = [...mask].sort((a,b)=>a<b?-1:1) return maskArr.map(i => arr[i]).filter(x => x !== undefined) } const sMaskSect = sections(sMask) const pMaskSect = sections(pMask) //ctx.pMaskSect = pMaskSect //ctx.sMaskSect = sMaskSect for (let i = 0; i < sMaskSect.length && i < pMaskSect.length; i++) { const stateRun = applyMask(sMaskSect[i], stateArr) const patternRun = applyMask(pMaskSect[i], patternArr) registerRule(stateRun, patternRun, ctx, next) } }; function allBreaks(arr) { const breaks = []; for (let i = 0; i < arr.length - 1; i++) { if (arr[i + 1] - arr[i] !== 1) { breaks.push(i); } } return breaks; } const find = (state, pattern, ctx = { }, fuzzy = false) => { if (!ctx.transform) ctx.transform = new Map(); if (!ctx.simillarity) ctx.simillarity = 0; if (!ctx.transformStr) ctx.transformStr = new Map(); ctx.masks = ctx.masks ?? {} const masks = ctx.masks let sMask = masks.stateMask let pMask = masks.patternMask const result = []; ctx.scores = [] for (let start = 0; start <= state.length - pattern.length; start++) { //todo infer sMask and pMask from pattern vs window simillarity let simillarity = 0 if (fuzzy) { const inferredMask = pattern.map((x, i) => x !== state[start + i][0] ? i : undefined) .filter(x => x !== undefined) pMask = sMask = new Set(inferredMask) simillarity = pattern.length - inferredMask.length if (pMask.has(0) && simillarity > 0) { inferredMask.sort((a,b) => a < b ? -1:+1) //todo apply mask and look to the next unmatched repeatedly //todo disallow section deletions/insertions (to keep masked sections aligned) let edge = allBreaks(inferredMask)[0] ?? inferredMask.length - 1 if (edge !== 0) { for (let shift = -edge; shift <= edge; shift++) { const newMask = pattern .map((x, i) => x !== (state[i <= edge ? start + i + shift : start + i] ?? [])[0] ? i : undefined) .filter(x => x !== undefined) const newSimillarity = pattern.length - newMask.length if (newSimillarity > simillarity) { simillarity = newSimillarity if (simillarity > ctx.simillarity) { ctx.edge = edge ctx.edgeStr = parse(enrichSeqNo(pattern.slice(edge + 1))) ctx.shift = shift } pMask = new Set(newMask) sMask = new Set(newMask) //continue //todo fix if (shift > 0) { sMask = new Set([...sMask] .map(i => i <= edge ? (i + shift <= edge? i + shift : undefined) : i) .filter(x => x !== undefined)) } else if (shift < 0) { sMask = new Set([...sMask] .map(i => i <= edge ? i + shift : i)) for (let i = 0; i < -shift; i++) { sMask.add(edge + i) } } } } } } } else { simillarity = pattern.every((x, i) => x === state[start + i][0]) ? pattern.length : 0 } if (simillarity > 0) { const origStateSeg = state .slice(start, start + pattern.length) const origPatternSeg = pattern.slice(); const nextIdx = start + pattern.length; const next = state[nextIdx]; if (next && simillarity > 0) { //console.log(parse(enrichSeqNo(pattern))) if (simillarity > ctx.simillarity && fuzzy) { ctx.transform = new Map(); ctx.transformStr = new Map(); } if (simillarity >= ctx.simillarity && fuzzy) { const inferredMask = [...pMask] inferredMask.sort((a,b) => a < b ? -1:+1) ctx.pattern = [...parse(enrichSeqNo(pattern))].map((x, i) => pMask.has(i) ? '*' : x).join('') ctx.match = [...parse(state.slice(start, nextIdx))].map((x, i) => sMask.has(i) ? '_' : x).join('') ctx.patSkip = pMask.has(0) ? allBreaks(inferredMask)[0] ?? inferredMask.length : 0 ctx.n = pattern.length - ctx.patSkip //console.log(ctx.pattern) //console.log(" ") masks.patternMask = pMask masks.stateMask = sMask emitRules(enrichSeqNo(origPatternSeg), eraseSeqNo(origStateSeg), next, ctx, pMask, sMask, start); } ctx.simillarity = ctx.simillarity > simillarity ? ctx.simillarity : simillarity ctx.scores.push(simillarity) result.push(next); } } } //const maxScore = Math.max(...ctx.scores) return result.filter((x, i) => ctx.scores[i] === ctx.simillarity); } function blurArray(arr, blurMask) { const out = []; let i = 0; while (i < arr.length) { if (!blurMask.has(i)) { out.push(arr[i]); i++; continue; } let sum = 0n; while (i < arr.length && blurMask.has(i)) { sum += arr[i]; i++; } out.push(sum); } return out; } const inferMaskingBound = (len) => { return 2 } const findFuzzy = (state, ctx, len, previousMany) => { const pattern = state.slice(state.length - len).map(x => x[0]) const space = state.slice(0, -len) const matches = find(space, pattern, ctx); if (!matches || matches.length === 0) { if (!ctx.fuzzyBound) { ctx.fuzzyBound = previousMany?.length ?? 0 } if (len > ctx.simillarity + ctx.fuzzyBound) { return [] } const fuzzyMatches = find(space, pattern, ctx, true); if (previousMany === undefined || fuzzyMatches === undefined) { return previousMany ?? [] } if (fuzzyMatches.length > previousMany.length) { return previousMany } return fuzzyMatches } ctx.n = len - 1 return matches } const predict = (state, ctx = {}) => { //console.log("---------") if (state.length === 0) return undefined; let previousMany = undefined; ctx.fuzzyBound = undefined ctx.simillarity = 0 for (let len = 1; len <= state.length; len++) { const matches = findFuzzy(state, ctx, len, previousMany) if (matches.length === 0) { return previousMany } else { previousMany = matches; continue; } } return undefined; } function pickRelevantTransform(next, ctx) { if (!ctx.transform) return; if (!next) return; |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |