Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 | 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1274182x 1274182x 1274182x 1274182x 2x 2x 380185x 380185x 380185x 380185x 175520x 380185x 42252x 380185x 162413x 380185x 380185x 380185x 380185x 2x 2x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 2x 162413x 162413x 162413x 162413x 162413x 162413x 162413x 162413x 162413x 162413x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 2x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 175520x 175520x 415647x 415647x 415647x 415647x 2x 2x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 210982x 210982x 104315x 106667x 34711x 71956x 71956x 2275x 69681x 591167x 380185x 380185x 175520x 204665x 42252x 162413x 162413x 6924x 155489x 380185x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 234369x 71956x 71956x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2280x 2280x 2280x 2275x 2275x 2275x 71956x 69681x 69681x 234369x 162413x 162413x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6940x 6940x 6940x 6924x 6924x 6924x 6924x 162413x 155489x 155489x 162413x 234369x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 210982x 210982x 104315x 63612x 104315x 15077x 37699x 25626x 25626x 25626x 210982x 34711x 106667x 71956x 2275x 71950x 69681x 69681x 71956x 591167x 380185x 380185x 175520x 95331x 175520x 80189x 80189x 80189x 380185x 42252x 204652x 162413x 6924x 162408x 155489x 155489x 162413x 380185x 591167x 591167x 591167x 591167x 210982x 210982x 104315x 63612x 40703x 106667x 34711x 71956x 71956x 591167x 380185x 380185x 175520x 95331x 80189x 204665x 42252x 162413x 162413x 380185x 591167x 591167x 591167x 591167x 591167x 210982x 210982x 210982x 210982x 591167x 380185x 380185x 380185x 380185x 380185x 591167x 591167x 591167x 591167x 591167x 210982x 34711x 210982x 71956x 71956x 591167x 380185x 42252x 380185x 162413x 162413x 380185x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 2x 390965x 390965x 390965x 390965x 390965x 390965x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 204665x 204665x 204665x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 591167x 390965x 390965x 2x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 119819x 119819x 119819x 119819x 119819x 119819x 119819x 119819x 260366x 260366x 260366x 260366x 260366x 260366x 260366x 260366x 260366x 380185x 55701x 55701x 55701x 55701x 55701x 55701x 55701x 55701x 204665x 204665x 204665x 204665x 204665x 204665x 379881x 162413x 162413x 162413x 162413x 162413x 42252x 42252x 42252x 42252x 2x 2x 2x 2x 2x 2x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 86302x 65334x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 993047x 390965x 390965x 390965x 390965x 591167x 993047x 591167x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 132111x 132111x 258848x 258848x 258848x 258848x 258848x 258848x 258848x 258848x 258848x 258848x 258848x 360648x 393663x 393663x 393663x 393663x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 393663x 393663x 393663x 393663x 393663x 393663x 393663x 393663x 393663x 393663x 393663x 393663x 393663x 393663x 393663x 393663x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 393663x 393663x 393663x 393663x 393663x 2x 2x 2x 2x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 380185x 217772x 217772x 380127x 162413x 162413x 162413x 380185x 2x 2x 2x 2x 217772x 217772x 217772x 217772x 217772x 217772x 217772x 217772x 217772x 217772x 217772x 217772x 217772x 217772x 137583x 137583x 95331x 95331x 95331x 95331x 95331x 95331x 95331x 95331x 95331x 95331x 95331x 95331x 95331x 95331x 95331x 95331x 137583x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 42252x 217772x 80189x 80189x 80189x 80189x 80189x 80189x 80189x 80189x 80189x 80189x 80189x 80189x 80189x 80189x 80189x 80189x 80189x 80189x 80189x 55701x 55701x 55701x 55701x 55701x 55701x 55701x 55701x 55701x 55701x 55701x 55701x 80189x 80189x 80189x 80189x 80189x 80189x 217772x 217772x 217772x 217772x 217772x 217772x 217772x 2x 2x 2x 2x 162413x 162413x 162413x 162413x 162413x 162413x 162413x 162413x 162413x 162413x 162413x 162413x 162413x 162413x 162413x 162413x 162413x 162413x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 162408x 155489x 155489x 155489x 155489x 155489x 155489x 155489x 155489x 155489x 155489x 155489x 155489x 155489x 155489x 155489x 155489x 155489x 155489x 155489x 155489x 155489x 155489x 155489x 155489x 155489x 155489x 155489x 155489x 155489x 155489x 162413x 162413x 162413x 162413x 162413x 162413x 162413x 162413x 162413x 162413x 2x 2x 2x 2x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6940x 6940x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6940x 6940x 6940x 6940x 6940x 6940x 6940x 6940x 6940x 6940x 6940x 6940x 6940x 6940x 6940x 6940x 6940x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 6924x 2x 2x 2x 2x 2x 2x 2x 2x 2x 132111x 132111x 132111x 132111x 132111x 132111x 132111x 132111x 132111x 132111x 132111x 132111x 132111x 132111x 132111x 132111x 132111x 132111x 132111x 132111x 132111x 132111x 220180x 220180x 220180x 220180x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 220180x 220180x 220180x 220180x 220180x 220180x 220180x 220180x 220180x 220180x 220180x 220180x 220180x 220180x 220180x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 220180x 220180x 220180x 220180x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 139026x 139026x 210982x 71956x 71956x 71956x 210982x 2x 2x 2x 2x 2x 2x 2x 2x 2x 139026x 139026x 139026x 139026x 139026x 139026x 139026x 139026x 139026x 139026x 139026x 139026x 139026x 139026x 98323x 63612x 63612x 63612x 63612x 63612x 63612x 63612x 63612x 63612x 63612x 63612x 63612x 63612x 63612x 98323x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 139026x 15077x 15077x 15077x 15077x 15077x 15077x 15077x 15077x 15077x 15077x 15077x 15077x 15077x 15077x 37699x 25626x 25626x 25626x 25626x 25626x 25626x 25626x 25626x 25626x 25626x 25626x 25626x 25626x 25626x 25626x 25626x 25626x 25626x 25626x 25626x 25626x 25626x 25626x 25626x 25626x 25626x 25626x 25626x 25626x 25626x 25626x 25626x 25626x 25626x 139026x 139026x 139026x 139026x 139026x 139026x 2x 2x 2x 2x 2x 2x 71956x 71956x 71956x 71956x 71956x 71956x 71956x 71956x 71956x 71956x 71956x 71956x 71956x 71956x 71956x 71956x 71956x 71956x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 71950x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 71956x 71956x 71956x 71956x 71956x 71956x 71956x 71956x 71956x 71956x 2x 2x 2x 2x 2x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2281x 2281x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2281x 2281x 2281x 2281x 2281x 2281x 2281x 2281x 2281x 2281x 2281x 2281x 2281x 2281x 2281x 2281x 2281x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2x 2x 2x 2x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 210982x 106667x 210982x 210982x 210982x 285219x 285219x 210982x 210982x 345556x 345556x 210982x 210982x 210982x 139026x 139026x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 34711x 104315x 104315x 104315x 104315x 104315x 104315x 104315x 104315x 71956x 71956x 180942x 210982x 210982x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 2275x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 69681x 2x 2x 2x 2x 210982x 210982x 210982x 210982x 104315x 210982x 34711x 210982x 71956x 210982x 210982x 210982x 210982x 2x 2x 2x 2x 2x 2x 2x 2x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 448213x 448213x 147788x 448213x 54439x 300406x 18684x 18684x 245986x 107730x 107730x 227302x 119572x 119572x 119572x 80851x 119572x 60970x 60970x 60970x 448213x 544834x 544834x 544834x 993047x 544834x 86302x 544834x 151955x 458532x 9260x 9260x 306577x 192045x 192045x 297303x 105272x 105272x 105272x 61080x 105272x 51239x 51239x 544834x 2x 4415641x 4415641x 4415641x 4415641x 4415641x 4415641x 4415641x 4415641x 4415641x 4415641x 4415641x 4415641x 2x 2x 2x 2x 853177x 853177x 853177x 2x 1869056x 1869056x 1869056x 6096045x 6096045x 6096045x 1869056x 1869056x 1869056x 2x 2x 2x 2x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 448213x 448213x 448213x 448213x 448213x 448213x 448213x 992966x 544834x 544834x 544834x 544834x 544834x 544834x 544834x 544834x 2x 2x 2x 2x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 910222x 910222x 910222x 910222x 910222x 910222x 993047x 993047x 993047x 993047x 777097x 777097x 777097x 777097x 777097x 777097x 993047x 993047x 993047x 993047x 993047x 759474x 759474x 759474x 570532x 993047x 993047x 993047x 993047x 1687319x 993047x 993047x 993047x 993047x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 993047x 1687319x 1687319x 1687319x 910222x 171894x 910222x 738328x 738328x 1687319x 777097x 175502x 777097x 601595x 601595x 777097x 993047x 993047x 993047x 993047x 3333296x 3333296x 3333296x 3333296x 3x 3x 3333296x 3333296x 3333296x 993047x 993047x 993047x 3333296x 3333296x 3333296x 3333296x 3333296x 3333296x 3333296x 3333296x 3333296x 3333296x 993047x 993047x 993047x 3333296x 3333296x 993047x 993047x 993047x 993047x 4x 4x 993047x 993047x 993047x 993047x 993047x 993047x 2x 2x 2x 2x 2x 390973x 390973x 390973x 390973x 390973x 390973x 390973x 390973x 390973x 390973x 390973x 390973x 7x 7x 7x 7x 7x 390966x 390966x 390966x 390966x 390966x 390966x 390966x 390966x 390966x 390966x 390971x 672504x 672504x 672504x 236609x 236609x 236609x 106667x 106667x 106667x 108948x 108948x 108948x 106667x 106667x 106667x 106667x 106667x 106667x 236609x 129942x 129942x 129942x 129942x 129942x 129942x 672504x 435895x 435895x 204671x 204671x 204671x 211615x 211615x 211615x 204671x 204671x 204671x 204671x 204671x 204671x 435895x 231224x 231224x 231224x 231224x 231224x 231224x 435895x 672504x 390966x 390966x 390966x 390966x 390966x 390966x 672504x 311338x 106667x 106667x 106667x 106667x 106667x 106667x 106667x 60913x 106667x 45754x 45754x 311338x 204671x 204671x 204671x 204671x 204671x 204671x 204671x 130025x 204668x 74646x 74646x 204671x 672504x 361166x 361166x 361166x 200028x 71199x 71199x 200028x 128829x 128829x 361166x 58743x 161127x 102395x 102395x 361166x 390966x 390966x 390966x 390966x 390973x 132112x 132112x 390973x 258854x 258854x 390966x 390966x 390966x 390966x 390966x 390966x 390966x 390966x 672504x 311338x 311338x 120400x 120400x 311338x 311338x 311338x 311338x 311338x 106667x 106667x 215615x 106667x 106667x 106667x 106667x 106667x 106667x 106667x 106667x 206553x 108948x 108948x 108948x 108948x 108948x 108948x 108948x 108948x 215615x 106667x 311338x 204671x 204671x 416286x 416286x 416286x 204671x 204671x 204671x 204671x 204671x 204671x 373575x 211615x 211615x 211615x 211615x 211615x 211615x 211615x 211615x 211615x 416286x 204671x 204671x 311338x 311338x 672504x 361166x 361166x 361166x 361166x 161138x 161138x 361166x 361166x 129942x 129942x 129942x 129942x 129942x 129942x 129942x 129942x 129942x 129942x 361166x 231224x 231224x 231224x 231224x 231224x 231224x 231224x 231224x 361166x 361166x 390966x 390966x 390966x 390966x 2x 390965x 390965x 390965x 390965x 993047x 993047x 993047x 993047x 390965x 390965x 390965x 390965x 591167x 591167x 390965x 390965x 2x 2x 2x 2x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 132111x 132111x 132111x 132111x 390965x 390965x 390965x 390965x 390965x 745960x 745960x 745960x 390965x 390965x 390965x 2x 2x 2x 2x 2x 2x 2x 2x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 390965x 6x 6x 390959x 390959x 390959x 390959x 390959x 390965x 293552x 293552x 97407x 97407x 97407x 390965x 46772x 46772x 37245x 37245x 25737x 25737x 37245x 21035x 21035x 50635x 50635x 50635x 50635x 50635x 50635x 50635x 50635x 390965x 390965x | // Unified step generator that computes all tutorial step information simultaneously
// to guarantee consistency between pedagogical decomposition, English instructions,
// expected states, and bead mappings.
import {
type AbacusState,
calculateBeadChanges,
numberToAbacusState,
type StepBeadHighlight,
} from './abacusInstructionGenerator'
export type PedagogicalRule = 'Direct' | 'FiveComplement' | 'TenComplement' | 'Cascade'
export interface SegmentReadable {
title: string // "Make 10 — ones" or "Make 10 (carry) — ones"
subtitle?: string // "Using pairs that make 10"
chips: Array<{ label: string; value: string }>
why: string[] // short, plain bullets
carryPath?: string // "Tens is 9 → hundreds +1; tens → 0"
stepsFriendly: string[] // bead verbs for each subterm
showMath?: { lines: string[] } // ["We take away 5 here (that's 10 minus 5)."]
/** NEW: one or two sentences that explain the move in plain language */
summary: string
/** NEW: dev-only self-check of the summary against the segment's guards */
validation?: { ok: boolean; issues: string[] }
}
export interface SegmentDecision {
/** Short, machine-readable rule fired at this segment */
rule: PedagogicalRule
/** Guard conditions that selected this rule */
conditions: string[] // e.g., ["a+d=6 ≤ 9", "L+d=5 > 4"]
/** Friendly bullets explaining the why */
explanation: string[] // e.g., ["No room for 3 lowers → use +5 − (5−3)"]
}
export interface PedagogicalSegment {
id: string // e.g., "P1-d4-#2"
place: number // P
digit: number // d
a: number // digit currently showing at P before the segment
L: number // lowers down at P
U: 0 | 1 // upper down?
goal: string // "Increase tens by 4 without carry"
plan: SegmentDecision[] // one or more rules (Cascade includes TenComplement+Cascade)
/** Expression for the whole segment, e.g., "40" or "(100 - 90 - 6)" */
expression: string
/** Indices into the flat `steps` array that belong to this segment */
stepIndices: number[]
/** Indices into the decompositionTerms list that belong to this segment */
termIndices: number[]
/** character range inside `fullDecomposition` spanning the expression */
termRange: { startIndex: number; endIndex: number }
/** Segment start→end snapshot (optional but useful for UI tooltips) */
startValue: number
endValue: number
startState: AbacusState
endState: AbacusState
/** Learner-friendly descriptions without technical variables */
readable: SegmentReadable
}
export interface TermProvenance {
rhs: number // the addend (difference), e.g., 25
rhsDigit: number // e.g., 2 (for tens), 5 (for ones)
rhsPlace: number // 1=tens, 0=ones, etc.
rhsPlaceName: string // "tens"
rhsDigitIndex: number // index of the digit in the addend string (for highlighting)
rhsValue: number // digit * 10^place (e.g., 20)
groupId?: string // same id for a complement group (e.g., +100 -90 -5)
// NEW: For terms that affect multiple columns (like complement operations)
termPlace?: number // the actual place this specific term affects (overrides rhsPlace for column mapping)
termPlaceName?: string // the name of the place this term affects
termValue?: number // the actual value of this term (e.g., 100, -90, -5)
}
export interface UnifiedStepData {
stepIndex: number
// Pedagogical decomposition - the math term for this step
mathematicalTerm: string // e.g., "10", "(5 - 1)", "-6"
termPosition: { startIndex: number; endIndex: number } // Position in full decomposition
// English instruction - what the user should do
englishInstruction: string // e.g., "Click earth bead 1 in tens column"
// Expected ending state/value after this step
expectedValue: number // e.g., 13, 17, 11
expectedState: AbacusState
// Bead movements for this step (for arrows/highlights)
beadMovements: StepBeadHighlight[]
// Validation
isValid: boolean
validationIssues?: string[]
/** Link to pedagogy segment this step belongs to */
segmentId?: string
/** NEW: Provenance linking this term to its source digit in the addend */
provenance?: TermProvenance
}
export interface EquationAnchors {
differenceText: string // "25"
rhsDigitPositions: Array<{
digitIndex: number
startIndex: number
endIndex: number
}>
}
export interface UnifiedInstructionSequence {
// Overall pedagogical decomposition
fullDecomposition: string // e.g., "3 + 14 = 3 + 10 + (5 - 1) = 17"
// Whether the decomposition is meaningful (not redundant)
isMeaningfulDecomposition: boolean
// Step-by-step breakdown
steps: UnifiedStepData[]
// Summary
startValue: number
targetValue: number
totalSteps: number
/** NEW: Schema version for compatibility */
schemaVersion?: '1' | '2'
/** NEW: High-level "chapters" that explain the why */
segments: PedagogicalSegment[]
/** NEW: Character positions for highlighting addend digits */
equationAnchors?: EquationAnchors
}
// Internal draft interface for building segments
interface SegmentDraft {
id: string
place: number
digit: number
a: number
L: number
U: 0 | 1
plan: SegmentDecision[]
goal: string
/** contiguous indices into steps[] / terms[] for this segment */
stepIndices: number[]
termIndices: number[]
// Value/state snapshots
startValue: number
startState: AbacusState
endValue: number
endState: AbacusState
}
/**
* Helper functions for building segment decisions and explanations
*/
function isPowerOfTen(n: number): boolean {
if (n < 1) return false
return /^10*$/.test(n.toString())
}
const isPowerOfTenGE10 = (n: number) => n >= 10 && isPowerOfTen(n)
function inferGoal(seg: SegmentDraft): string {
const placeName = getPlaceName(seg.place)
switch (seg.plan[0]?.rule) {
case 'Direct':
return `Increase ${placeName} by ${seg.digit} without carry`
case 'FiveComplement':
return `Add ${seg.digit} to ${placeName} using 5's complement`
case 'TenComplement':
return `Add ${seg.digit} to ${placeName} with a carry`
case 'Cascade':
return `Carry through ${placeName}+ to nearest non‑9 place`
default:
return `Apply operation at ${placeName}`
}
}
function _decisionForDirect(a: number, d: number, L: number): SegmentDecision[] {
if (L + d <= 4) {
return [
{
rule: 'Direct',
conditions: [`a+d=${a}+${d}=${a + d} ≤ 9`],
explanation: ['Fits inside this place; add earth beads directly.'],
},
]
} else {
const s = 5 - d
return [
{
rule: 'FiveComplement',
conditions: [`a+d=${a}+${d}=${a + d} ≤ 9`, `L+d=${L}+${d}=${L + d} > 4`],
explanation: [
'No room for that many earth beads.',
`Use +5 − (5−${d}) = +5 − ${s}; subtraction is possible because lowers ≥ ${s}.`,
],
},
]
}
}
function decisionForFiveComplement(a: number, d: number): SegmentDecision[] {
const s = 5 - d
return [
{
rule: 'FiveComplement',
conditions: [`a+d=${a}+${d}=${a + d} ≤ 9`, `L+d > 4`],
explanation: [
'No room for that many earth beads.',
`Use +5 − (5−${d}) = +5 − ${s}; subtraction is possible because lowers ≥ ${s}.`,
],
},
]
}
function decisionForTenComplement(a: number, d: number, nextIs9: boolean): SegmentDecision[] {
const base: SegmentDecision = {
rule: 'TenComplement',
conditions: [`a+d=${a}+${d}=${a + d} ≥ 10`, `a ≥ 10−d = ${10 - d}`],
explanation: [
'Need a carry to the next higher place.',
`No borrow at this place because a ≥ ${10 - d}.`,
],
}
if (!nextIs9) return [base]
return [
base,
{
rule: 'Cascade',
conditions: ['next place is 9 ⇒ ripple carry'],
explanation: ['Increment nearest non‑9 place; clear intervening 9s.'],
},
]
}
function formatSegmentExpression(terms: string[]): string {
if (terms.length === 0) return ''
const positives = terms.filter((t) => !t.startsWith('-'))
const negatives = terms.filter((t) => t.startsWith('-')).map((t) => t.slice(1))
// All positive → join with pluses (no parentheses)
if (negatives.length === 0) {
return positives.join(' + ')
}
// Complement group → (pos - n1 - n2 - …)
return `(${positives[0]} - ${negatives.join(' - ')})`
}
function _formatSegmentGoal(digit: number, placeValue: number): string {
const placeName = getPlaceName(placeValue)
return `Add ${digit} to ${placeName}`
}
function generateSegmentReadable(
rule: PedagogicalRule,
place: number,
digit: number,
currentDigit: number,
plan: SegmentDecision[],
steps: UnifiedStepData[],
stepIndices: number[],
startState: AbacusState,
_targetState: AbacusState
): SegmentReadable {
const placeName = getPlaceName(place)
const hasCascade = plan.some((p) => p.rule === 'Cascade')
// Pull first available provenance from this segment's steps
const provenance = stepIndices.map((i) => steps[i]?.provenance).find(Boolean)
// Detect if this is a subtraction segment (negative rhs in provenance)
const isSubtraction = provenance?.rhs !== undefined && provenance.rhs < 0
// Helper numbers
const s5 = 5 - digit
const s10 = 10 - digit
const nextPlaceName = getPlaceName(place + 1)
// Title is short + kid-friendly
let title: string
if (isSubtraction) {
title =
rule === 'Direct'
? `Subtract ${digit} — ${placeName}`
: rule === 'FiveComplement'
? `Break 5 — ${placeName}`
: rule === 'TenComplement'
? hasCascade
? `Borrow (cascade) — ${placeName}`
: `Borrow 10 — ${placeName}`
: rule === 'Cascade'
? `Borrow ripple — ${placeName}`
: `Strategy — ${placeName}`
} else {
title =
rule === 'Direct'
? `Add ${digit} — ${placeName}`
: rule === 'FiveComplement'
? `Make 5 — ${placeName}`
: rule === 'TenComplement'
? hasCascade
? `Make 10 (carry) — ${placeName}`
: `Make 10 — ${placeName}`
: rule === 'Cascade'
? `Carry ripple — ${placeName}`
: `Strategy — ${placeName}`
}
// Minimal chips (0–2), provenance first if present
const chips: Array<{ label: string; value: string }> = []
if (provenance) {
chips.push({
label: isSubtraction ? 'From subtrahend' : 'From addend',
value: `${provenance.rhsDigit} ${provenance.rhsPlaceName}`,
})
}
chips.push({ label: 'Rod shows', value: `${currentDigit}` })
// Carry/borrow path (kept terse)
let carryPath: string | undefined
if (rule === 'TenComplement') {
if (isSubtraction) {
// Borrow path for subtraction
if (hasCascade) {
const nextPlace = place + 1
const nextVal =
(startState[nextPlace]?.heavenActive ? 5 : 0) + (startState[nextPlace]?.earthActive || 0)
if (nextVal === 0) {
// Find highest non-0 to name the borrowing source
const maxPlace = Math.max(0, ...Object.keys(startState).map(Number)) + 2
let k = nextPlace + 1
for (; k <= maxPlace; k++) {
const v = (startState[k]?.heavenActive ? 5 : 0) + (startState[k]?.earthActive || 0)
if (v !== 0) break
}
const toName = getPlaceName(k)
carryPath = `${getPlaceName(nextPlace)} is 0 ⇒ borrow from ${toName}; fill 9s`
} else {
carryPath = `Borrow from ${nextPlaceName}`
}
} else {
carryPath = `Borrow from ${nextPlaceName}`
}
} else {
// Carry path for addition
if (hasCascade) {
const nextPlace = place + 1
const nextVal =
(startState[nextPlace]?.heavenActive ? 5 : 0) + (startState[nextPlace]?.earthActive || 0)
if (nextVal === 9) {
const maxPlace = Math.max(0, ...Object.keys(startState).map(Number)) + 2
let k = nextPlace + 1
for (; k <= maxPlace; k++) {
const v = (startState[k]?.heavenActive ? 5 : 0) + (startState[k]?.earthActive || 0)
if (v !== 9) break
}
const landingIsNewHighest = k > maxPlace
const toName = landingIsNewHighest ? 'next higher place' : getPlaceName(k)
carryPath = `${getPlaceName(nextPlace)} is 9 ⇒ ${toName} +1; clear 9s`
} else {
carryPath = `${nextPlaceName} +1`
}
} else {
carryPath = `${nextPlaceName} +1`
}
}
}
// Steps (kept for the expandable "details" UI)
const stepsFriendly = stepIndices
.map((i) => steps[i]?.englishInstruction)
.filter(Boolean) as string[]
// Semantic, 1–2 sentence summary
let summary = ''
if (isSubtraction) {
// Subtraction summaries
if (rule === 'Direct') {
if (digit <= 4) {
summary = `Subtract ${digit} from the ${placeName}. You have enough beads, so just remove ${digit} lower bead${digit > 1 ? 's' : ''}.`
} else if (digit === 5) {
summary = `Subtract ${digit} from the ${placeName}. Just lower the heaven bead.`
} else {
const rest = digit - 5
summary = `Subtract ${digit} from the ${placeName}: lower the heaven bead (−5) and remove ${rest} earth bead${rest > 1 ? 's' : ''}.`
}
} else if (rule === 'FiveComplement') {
summary = `Subtract ${digit} from the ${placeName}, but there aren't enough lower beads. Use 5's friend: lower the heaven bead (−5) and add ${s5} — that's −5 + ${s5}.`
} else if (rule === 'TenComplement') {
if (hasCascade) {
summary = `Subtract ${digit} from the ${placeName}, but you only have ${currentDigit}. Borrow from a higher place; because the next rod is 0, the borrow cascades, then add ${s10} here (that's −10 + ${s10}).`
} else {
summary = `Subtract ${digit} from the ${placeName}, but you only have ${currentDigit}. Borrow 10 from ${nextPlaceName} and add ${s10} here (that's −10 + ${s10}).`
}
} else {
summary = `Apply the strategy on the ${placeName}.`
}
} else {
// Addition summaries (existing)
if (rule === 'Direct') {
if (digit <= 4) {
summary = `Add ${digit} to the ${placeName}. It fits here, so just move ${digit} lower bead${digit > 1 ? 's' : ''}.`
} else {
const rest = digit - 5
summary = `Add ${digit} to the ${placeName} using the heaven bead: +5${rest ? ` + ${rest}` : ''}. No carry needed.`
}
} else if (rule === 'FiveComplement') {
summary = `Add ${digit} to the ${placeName}, but there isn't room for that many lower beads. Use 5's friend: press the heaven bead (5) and lift ${s5} — that's +5 − ${s5}.`
} else if (rule === 'TenComplement') {
if (hasCascade) {
summary = `Add ${digit} to the ${placeName} to make 10. Carry to ${nextPlaceName}; because the next rod is 9, the carry ripples up, then take ${s10} here (that's +10 − ${s10}).`
} else {
summary = `Add ${digit} to the ${placeName} to make 10: carry 1 to ${nextPlaceName} and take ${s10} here (that's +10 − ${s10}).`
}
} else {
summary = `Apply the strategy on the ${placeName}.`
}
}
// Short subtitle (optional, reused from your rule badges)
let subtitle: string | undefined
if (isSubtraction) {
subtitle =
rule === 'Direct'
? digit <= 4
? 'Simple removal'
: 'Heaven bead helps'
: rule === 'FiveComplement'
? "Using 5's friend"
: rule === 'TenComplement'
? 'Borrowing'
: undefined
} else {
subtitle =
rule === 'Direct'
? digit <= 4
? 'Simple move'
: 'Heaven bead helps'
: rule === 'FiveComplement'
? "Using 5's friend"
: rule === 'TenComplement'
? "Using 10's friend"
: undefined
}
// Tiny, dev-only validation of the summary against the selected rule
const issues: string[] = []
const guards = plan.flatMap((p) => p.conditions)
if (isSubtraction) {
// Subtraction validation
if (rule === 'FiveComplement' && !guards.some((g) => /L\s*<\s*d/.test(g))) {
issues.push('FiveComplement (sub) summary emitted but guard L < d not present')
}
if (rule === 'TenComplement' && !guards.some((g) => /a.*<.*d/.test(g))) {
issues.push('TenComplement (sub) summary emitted but guard a < d not present')
}
if (rule === 'Direct' && !guards.some((g) => /a.*>=.*d/.test(g))) {
issues.push('Direct (sub) summary emitted but guard a >= d not present')
}
} else {
// Addition validation
if (rule === 'FiveComplement' && !guards.some((g) => /L\s*\+\s*d.*>\s*4/.test(g))) {
issues.push('FiveComplement summary emitted but guard L+d>4 not present')
}
if (rule === 'TenComplement' && !guards.some((g) => /a\s*\+\s*d.*(≥|>=)\s*10/.test(g))) {
issues.push('TenComplement summary emitted but guard a+d≥10 not present')
}
if (rule === 'Direct' && !guards.some((g) => /a\s*\+\s*d.*(≤|<=)\s*9/.test(g))) {
issues.push('Direct summary emitted but guard a+d≤9 not present')
}
}
const validation = { ok: issues.length === 0, issues }
// Minimal "show the math" for students who want it
const showMathLines: string[] = []
if (isSubtraction) {
if (rule === 'FiveComplement') {
showMathLines.push(`−5 + ${s5} = −${digit} (at this rod)`)
} else if (rule === 'TenComplement') {
showMathLines.push(`−10 + ${s10} = −${digit} (with a borrow)`)
}
} else {
if (rule === 'FiveComplement') {
showMathLines.push(`+5 − ${s5} = +${digit} (at this rod)`)
} else if (rule === 'TenComplement') {
showMathLines.push(`+10 − ${s10} = +${digit} (with a carry)`)
}
}
return {
title,
subtitle,
chips,
why: [], // replaced by summary
carryPath,
stepsFriendly,
showMath: showMathLines.length ? { lines: showMathLines } : undefined,
summary,
validation,
}
}
function buildSegmentsWithPositions(
segmentsPlan: SegmentDraft[],
fullDecomposition: string,
steps: UnifiedStepData[]
): PedagogicalSegment[] {
return segmentsPlan.map((draft) => {
const segmentTerms = draft.stepIndices
.map((i) => steps[i]?.mathematicalTerm)
.filter((t): t is string => !!t)
// Range from steps -> exact, no string search
const ranges = draft.stepIndices
.map((i) => steps[i]?.termPosition)
.filter((r): r is { startIndex: number; endIndex: number } => !!r)
let start = Math.min(...ranges.map((r) => r.startIndex))
let end = Math.max(...ranges.map((r) => r.endIndex))
// Safely include surrounding parentheses for complement groups
const before = start > 0 ? fullDecomposition[start - 1] : ''
const after = end < fullDecomposition.length ? fullDecomposition[end] : ''
if (before === '(' && after === ')') {
start -= 1
end += 1
}
const primaryRule = draft.plan[0]?.rule || 'Direct'
return {
id: draft.id,
place: draft.place,
digit: draft.digit,
a: draft.a,
L: draft.L,
U: draft.U,
goal: draft.goal,
plan: draft.plan,
expression: formatSegmentExpression(segmentTerms),
stepIndices: draft.stepIndices,
termIndices: draft.termIndices,
termRange: { startIndex: start, endIndex: end },
startValue: draft.startValue,
endValue: draft.endValue,
startState: draft.startState,
endState: draft.endState,
readable: generateSegmentReadable(
primaryRule,
draft.place,
draft.digit,
draft.a,
draft.plan,
steps,
draft.stepIndices,
draft.startState,
draft.endState
),
}
})
}
function determineSegmentDecisions(
digit: number,
place: number,
currentDigit: number,
steps: DecompositionStep[]
): SegmentDecision[] {
const sum = currentDigit + digit
// If there is exactly one step and it's positive, it's direct.
if (steps.length === 1 && !steps[0].operation.startsWith('-')) {
return [
{
rule: 'Direct',
conditions: [`a+d=${currentDigit}+${digit}=${sum} ≤ 9`],
explanation: ['Fits in this place; add beads directly.'],
},
]
}
const positives = steps
.filter((s) => !s.operation.startsWith('-'))
.map((s) => parseInt(s.operation, 10))
const negatives = steps
.filter((s) => s.operation.startsWith('-'))
.map((s) => Math.abs(parseInt(s.operation, 10)))
// No negatives → it's a direct (possibly 5+earth remainder) entry, not complement
if (negatives.length === 0) {
return [
{
rule: 'Direct',
conditions: [`a+d=${currentDigit}+${digit}=${sum} ≤ 9`],
explanation: ['Heaven bead (5) plus lower beads: still direct addition.'],
},
]
}
// There are negatives → complement family
const hasFiveAdd = positives.some((v) => Number.isInteger(v / 5) && isPowerOfTen(v / 5))
const tenAdd = positives.find((v) => isPowerOfTenGE10(v))
const hasTenAdd = tenAdd !== undefined
if (hasTenAdd) {
const tenAddPlace = Math.round(Math.log10(tenAdd!))
const negPlaces = new Set(negatives.map((v) => Math.floor(Math.log10(v))))
const cascades = tenAddPlace > place + 1 || negPlaces.size >= 2
return decisionForTenComplement(currentDigit, digit, cascades)
}
if (hasFiveAdd) {
return decisionForFiveComplement(currentDigit, digit)
}
// Fallback (unlikely with current generators)
return [
{
rule: 'Direct',
conditions: [`processing digit ${digit} at ${getPlaceName(place)}`],
explanation: ['Standard operation.'],
},
]
}
/**
* THE UNIFIED FUNCTION: Generates all tutorial step information simultaneously
* to ensure perfect consistency between math, instructions, states, and bead mappings.
*/
export function generateUnifiedInstructionSequence(
startValue: number,
targetValue: number
): UnifiedInstructionSequence {
const _difference = targetValue - startValue
// Ensure consistent width across all state conversions to prevent place misalignment
const digits = (n: number) => Math.max(1, Math.floor(Math.log10(Math.abs(n))) + 1)
const width =
Math.max(digits(startValue), digits(targetValue), digits(Math.abs(targetValue - startValue))) +
1 // +1 to absorb carries
const toState = (n: number) => numberToAbacusState(n, width)
// Step 1: Generate pedagogical decomposition terms and segment plan
const startState = toState(startValue)
const {
terms: decompositionTerms,
segmentsPlan,
decompositionSteps,
} = generateDecompositionTerms(startValue, targetValue, toState)
// Step 3: Generate unified steps - each step computes ALL aspects simultaneously
const steps: UnifiedStepData[] = []
let currentValue = startValue
let currentState = { ...startState }
for (let stepIndex = 0; stepIndex < decompositionTerms.length; stepIndex++) {
const term = decompositionTerms[stepIndex]
// Calculate what this step should accomplish
const stepResult = calculateStepResult(currentValue, term)
const newValue = stepResult.newValue
const newState = toState(newValue)
// Find the bead movements for this specific step
const stepBeadMovements = calculateStepBeadMovements(currentState, newState, stepIndex)
// Generate English instruction with hybrid approach
// Use term-based for consistency with tests, bead-movements as validation
const isComplementContext =
term === '5' &&
stepIndex + 1 < decompositionTerms.length &&
decompositionTerms[stepIndex + 1].startsWith('-')
const englishInstruction =
generateInstructionFromTerm(term, stepIndex, isComplementContext) ||
(stepBeadMovements.length > 0
? generateStepInstruction(stepBeadMovements, term, stepResult)
: `perform operation: ${term}`)
// Validate that everything is consistent
const validation = validateStepConsistency(
term,
englishInstruction,
currentValue,
newValue,
stepBeadMovements,
toState
)
// Create the unified step data
const stepData: UnifiedStepData = {
stepIndex,
mathematicalTerm: term,
termPosition: { startIndex: 0, endIndex: 0 }, // Will be set later
englishInstruction,
expectedValue: newValue,
expectedState: newState,
beadMovements: stepBeadMovements,
isValid: validation.isValid,
validationIssues: validation.issues,
provenance: decompositionSteps[stepIndex]?.provenance,
}
steps.push(stepData)
// Move to next step
currentValue = newValue
currentState = { ...newState }
}
// Step 4: Build full decomposition string and calculate term positions
const { fullDecomposition, termPositions } = buildFullDecompositionWithPositions(
startValue,
targetValue,
decompositionTerms
)
// Defensive check: ensure position count matches term count
if (termPositions.length !== decompositionTerms.length) {
throw new Error(
`Position count mismatch: ${termPositions.length} positions for ${decompositionTerms.length} terms`
)
}
// Step 5: Determine if this decomposition is meaningful
const isMeaningfulDecomposition = isDecompositionMeaningful(
startValue,
targetValue,
decompositionTerms,
fullDecomposition
)
// Step 6: Attach term positions and segment ids to steps
steps.forEach((step, idx) => {
if (termPositions[idx]) step.termPosition = termPositions[idx]
})
// (optional) annotate steps with the segment they belong to
segmentsPlan.forEach((seg) =>
seg.stepIndices.forEach((i) => {
if (steps[i]) steps[i].segmentId = seg.id
})
)
// Step 7: Build segments using step positions (exact indices, robust)
const segments = buildSegmentsWithPositions(segmentsPlan, fullDecomposition, steps)
// Step 8: Build equation anchors for addend digit highlighting
const equationAnchors = buildEquationAnchors(startValue, targetValue, fullDecomposition)
const result = {
schemaVersion: '2' as const,
fullDecomposition,
isMeaningfulDecomposition,
steps,
segments,
startValue,
targetValue,
totalSteps: steps.length,
equationAnchors,
}
// Development-time invariant checks
if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {
assertSegments(result)
}
return result
}
/**
* Generate decomposition terms based on actual bead movements
*/
interface AbacusPlaceState {
heavenActive: boolean
earthActive: number // 0-4
}
interface DecompositionStep {
operation: string // The mathematical term like "7", "(10 - 3)", etc.
description: string // What this step does pedagogically
targetValue: number // Expected value after this step
provenance?: TermProvenance // NEW: Link to source digit
}
/**
* NEW ALGORITHM: Generate pedagogical decomposition using proper soroban logic
* Process addend left-to-right, checking abacus state constraints at each place
*/
function generateDecompositionTerms(
startValue: number,
targetValue: number,
toState: (n: number) => AbacusState
): {
terms: string[]
segmentsPlan: SegmentDraft[]
decompositionSteps: DecompositionStep[]
} {
const addend = targetValue - startValue
if (addend === 0) return { terms: [], segmentsPlan: [], decompositionSteps: [] }
if (addend < 0) {
return generateSubtractionDecompositionTerms(startValue, targetValue, toState)
}
// Convert to abacus state representation with correct dimensions
let currentState = toState(startValue)
let currentValue = startValue
const steps: DecompositionStep[] = []
const segmentsPlan: SegmentDraft[] = []
// Process addend digit by digit from left to right (highest to lowest place)
const addendStr = addend.toString()
const addendLength = addendStr.length
for (let digitIndex = 0; digitIndex < addendLength; digitIndex++) {
const digit = parseInt(addendStr[digitIndex], 10)
const placeValue = addendLength - 1 - digitIndex
if (digit === 0) continue // Skip zeros
// Get current digit at this place value
const currentDigitAtPlace = getDigitAtPlace(currentValue, placeValue)
const startStepCount = steps.length
// DEBUG: Log the processing for troubleshooting
// console.log(`Processing place ${placeValue}: digit=${digit}, current=${currentDigitAtPlace}, sum=${currentDigitAtPlace + digit}`)
// Create base provenance for this digit
const baseProvenance: TermProvenance = {
rhs: addend,
rhsDigit: digit,
rhsPlace: placeValue,
rhsPlaceName: getPlaceName(placeValue),
rhsDigitIndex: digitIndex,
rhsValue: digit * 10 ** placeValue,
}
// Apply the pedagogical algorithm decision tree
const stepResult = processDigitAtPlace(
digit,
placeValue,
currentDigitAtPlace,
currentState,
addend, // Pass the full addend to determine if it's multi-place
toState, // Pass consistent state converter
baseProvenance // NEW: Pass provenance info
)
const segmentId = `place-${placeValue}-digit-${digit}`
const segmentStartValue = currentValue
const segmentStartState = { ...currentState }
const placeStart = segmentStartState[placeValue] ?? {
heavenActive: false,
earthActive: 0,
}
const L = placeStart.earthActive
const U: 0 | 1 = placeStart.heavenActive ? 1 : 0
// Apply the step result
steps.push(...stepResult.steps)
currentValue = stepResult.newValue
currentState = stepResult.newState
const endStepCount = steps.length
const stepIndices = Array.from(
{ length: endStepCount - startStepCount },
(_, i) => startStepCount + i
)
if (stepIndices.length === 0) {
// skip building a segment with no terms/steps
continue
}
// Decide pedagogy
const plan = determineSegmentDecisions(digit, placeValue, currentDigitAtPlace, stepResult.steps)
const goal = inferGoal({
id: segmentId,
place: placeValue,
digit,
a: currentDigitAtPlace,
L,
U,
plan,
goal: '',
stepIndices,
termIndices: stepIndices,
startValue: segmentStartValue,
startState: segmentStartState,
endValue: currentValue,
endState: { ...currentState },
})
const segment: SegmentDraft = {
id: segmentId,
place: placeValue,
digit,
a: currentDigitAtPlace,
L,
U,
plan,
goal,
stepIndices,
termIndices: stepIndices,
startValue: segmentStartValue,
startState: segmentStartState,
endValue: currentValue,
endState: { ...currentState },
}
segmentsPlan.push(segment)
}
// Convert steps to string terms for compatibility
const terms = steps.map((step) => step.operation)
return { terms, segmentsPlan, decompositionSteps: steps }
}
/**
* Process a single digit at a specific place value using soroban algorithm
*/
function processDigitAtPlace(
digit: number,
placeValue: number,
currentDigitAtPlace: number,
currentState: AbacusState,
addend: number,
toState: (n: number) => AbacusState,
baseProvenance: TermProvenance
): { steps: DecompositionStep[]; newValue: number; newState: AbacusState } {
const a = currentDigitAtPlace
const d = digit
// Decision: Direct addition vs 10's complement
if (a + d <= 9) {
// Case A: Direct addition at this place
return processDirectAddition(d, placeValue, currentState, addend, toState, baseProvenance)
} else {
// Case B: 10's complement required
return processTensComplement(d, placeValue, currentState, toState, baseProvenance)
}
}
/**
* Handle direct addition at a place value (a + d ≤ 9)
*/
function processDirectAddition(
digit: number,
placeValue: number,
currentState: AbacusState,
_addend: number,
_toState: (n: number) => AbacusState,
baseProvenance: TermProvenance
): { steps: DecompositionStep[]; newValue: number; newState: AbacusState } {
const placeState = currentState[placeValue] || {
heavenActive: false,
earthActive: 0,
}
const L = placeState.earthActive // Current earth beads (matches algorithm spec)
const steps: DecompositionStep[] = []
const newState = { ...currentState }
if (digit <= 4) {
// For digits 1-4: try to add earth beads directly
if (L + digit <= 4) {
// Direct earth bead addition
steps.push({
operation: (digit * 10 ** placeValue).toString(),
description: `Add ${digit} earth bead${digit > 1 ? 's' : ''} at place ${placeValue}`,
targetValue: 0, // Will be calculated later
provenance: {
...baseProvenance,
termPlace: placeValue,
termPlaceName: getPlaceName(placeValue),
termValue: digit * 10 ** placeValue,
},
})
newState[placeValue] = {
...placeState,
earthActive: L + digit,
}
} else if (!placeState.heavenActive) {
// Use 5's complement: digit = (5 - (5 - digit)) when pedagogically valuable
const complement = 5 - digit
const groupId = `5comp-${baseProvenance.rhsPlace}-${baseProvenance.rhsDigit}`
// Always show five-complement pedagogy as separate steps
const fiveValue = 5 * 10 ** placeValue
const subtractValue = complement * 10 ** placeValue
steps.push({
operation: fiveValue.toString(),
description: `Add heaven bead at place ${placeValue}`,
targetValue: 0,
provenance: {
...baseProvenance,
groupId,
termPlace: placeValue,
termPlaceName: getPlaceName(placeValue),
termValue: fiveValue,
},
})
steps.push({
operation: `-${subtractValue}`,
description: `Remove ${complement} earth beads at place ${placeValue}`,
targetValue: 0,
provenance: {
...baseProvenance,
groupId,
termPlace: placeValue,
termPlaceName: getPlaceName(placeValue),
termValue: -subtractValue,
},
})
newState[placeValue] = {
heavenActive: true,
earthActive: placeState.earthActive - complement,
}
}
} else {
// For digits 5-9: always fits under Case A assumption (a + d ≤ 9)
// Activate heaven bead and add remainder earth beads
const earthBeadsNeeded = digit - 5
const fiveValue = 5 * 10 ** placeValue
const remainderValue = earthBeadsNeeded * 10 ** placeValue
steps.push({
operation: fiveValue.toString(),
description: `Add heaven bead at place ${placeValue}`,
targetValue: 0,
provenance: {
...baseProvenance,
termPlace: placeValue,
termPlaceName: getPlaceName(placeValue),
termValue: fiveValue,
},
})
if (earthBeadsNeeded > 0) {
steps.push({
operation: remainderValue.toString(),
description: `Add ${earthBeadsNeeded} earth beads at place ${placeValue}`,
targetValue: 0,
provenance: {
...baseProvenance,
termPlace: placeValue,
termPlaceName: getPlaceName(placeValue),
termValue: remainderValue,
},
})
}
newState[placeValue] = {
heavenActive: true,
earthActive: placeState.earthActive + earthBeadsNeeded,
}
}
// Calculate new total value
const _currentValue = abacusStateToNumber(currentState)
const newValue = abacusStateToNumber(newState)
return { steps, newValue, newState }
}
/**
* Handle 10's complement when a + d ≥ 10
*/
function processTensComplement(
digit: number,
placeValue: number,
currentState: AbacusState,
toState: (n: number) => AbacusState,
baseProvenance: TermProvenance
): { steps: DecompositionStep[]; newValue: number; newState: AbacusState } {
const steps: DecompositionStep[] = []
const complementToSubtract = 10 - digit
const currentValue = abacusStateToNumber(currentState)
// Check if this requires cascading (next place is 9)
const nextPlaceDigit = getDigitAtPlace(currentValue, placeValue + 1)
const requiresCascading = nextPlaceDigit === 9
const groupId = `10comp-${baseProvenance.rhsPlace}-${baseProvenance.rhsDigit}`
if (requiresCascading) {
// Generate cascading complement terms in parenthesized format
const cascadeSteps = generateCascadeComplementSteps(
currentValue,
placeValue,
complementToSubtract,
baseProvenance,
groupId
)
steps.push(...cascadeSteps)
} else {
// Simple ten-complement: generate separate add/subtract steps
const higherPlaceValue = 10 ** (placeValue + 1)
const subtractValue = complementToSubtract * 10 ** placeValue
steps.push({
operation: higherPlaceValue.toString(),
description: `Add 1 to ${getPlaceName(placeValue + 1)} (carry)`,
targetValue: 0,
provenance: {
...baseProvenance,
groupId,
termPlace: placeValue + 1,
termPlaceName: getPlaceName(placeValue + 1),
termValue: higherPlaceValue,
},
})
steps.push({
operation: `-${subtractValue}`,
description: `Remove ${complementToSubtract} earth beads (no borrow needed)`,
targetValue: 0,
provenance: {
...baseProvenance,
groupId,
termPlace: placeValue,
termPlaceName: getPlaceName(placeValue),
termValue: -subtractValue,
},
})
}
// Calculate new value mathematically
const newValue = currentValue + digit * 10 ** placeValue
return {
steps,
newValue,
newState: toState(newValue),
}
}
/**
* Generate cascade complement steps as individual terms for UI tracking
*/
function generateCascadeComplementSteps(
currentValue: number,
startPlace: number,
onesComplement: number,
baseProvenance: TermProvenance,
groupId: string
): DecompositionStep[] {
const steps: DecompositionStep[] = []
// First, add to the highest non-9 place
let checkPlace = startPlace + 1
const maxCheck = Math.max(1, Math.floor(Math.log10(Math.max(1, currentValue))) + 1) + 2
while (getDigitAtPlace(currentValue, checkPlace) === 9 && checkPlace <= maxCheck) {
checkPlace += 1
}
// Add 1 to the highest place (this creates the cascade)
const higherPlaceValue = 10 ** checkPlace
steps.push({
operation: higherPlaceValue.toString(),
description: `Add 1 to ${getPlaceName(checkPlace)} (cascade trigger)`,
targetValue: 0,
provenance: {
...baseProvenance,
groupId,
termPlace: checkPlace,
termPlaceName: getPlaceName(checkPlace),
termValue: higherPlaceValue,
},
})
// Clear all the 9s in between (working downward)
for (let clearPlace = checkPlace - 1; clearPlace > startPlace; clearPlace--) {
const digitAtClearPlace = getDigitAtPlace(currentValue, clearPlace)
if (digitAtClearPlace === 9) {
const clearValue = 9 * 10 ** clearPlace
steps.push({
operation: `-${clearValue}`,
description: `Remove 9 from ${getPlaceName(clearPlace)} (cascade)`,
targetValue: 0,
provenance: {
...baseProvenance,
groupId,
termPlace: clearPlace,
termPlaceName: getPlaceName(clearPlace),
termValue: -clearValue,
},
})
}
}
// Finally, subtract at the original place
const onesSubtractValue = onesComplement * 10 ** startPlace
steps.push({
operation: `-${onesSubtractValue}`,
description: `Remove ${onesComplement} earth beads (ten's complement)`,
targetValue: 0,
provenance: {
...baseProvenance,
groupId,
termPlace: startPlace,
termPlaceName: getPlaceName(startPlace),
termValue: -onesSubtractValue,
},
})
return steps
}
// =============================================================================
// SUBTRACTION IMPLEMENTATION
// =============================================================================
/**
* Generate decomposition terms for subtraction operations.
* Process subtrahend left-to-right (highest to lowest place), same as addition.
*/
function generateSubtractionDecompositionTerms(
startValue: number,
targetValue: number,
toState: (n: number) => AbacusState
): {
terms: string[]
segmentsPlan: SegmentDraft[]
decompositionSteps: DecompositionStep[]
} {
const subtrahend = startValue - targetValue // positive number to subtract
if (subtrahend <= 0) return { terms: [], segmentsPlan: [], decompositionSteps: [] }
let currentState = toState(startValue)
let currentValue = startValue
const steps: DecompositionStep[] = []
const segmentsPlan: SegmentDraft[] = []
// Process subtrahend digit by digit from left to right (highest to lowest place)
const subtrahendStr = subtrahend.toString()
const subtrahendLength = subtrahendStr.length
for (let digitIndex = 0; digitIndex < subtrahendLength; digitIndex++) {
const digit = parseInt(subtrahendStr[digitIndex], 10)
const placeValue = subtrahendLength - 1 - digitIndex
if (digit === 0) continue // Skip zeros
const currentDigitAtPlace = getDigitAtPlace(currentValue, placeValue)
const startStepCount = steps.length
// Create base provenance for this digit (negative RHS value for subtraction)
const baseProvenance: TermProvenance = {
rhs: -subtrahend, // Negative to indicate subtraction
rhsDigit: digit,
rhsPlace: placeValue,
rhsPlaceName: getPlaceName(placeValue),
rhsDigitIndex: digitIndex,
rhsValue: -(digit * 10 ** placeValue), // Negative value
}
// Apply the subtraction algorithm decision tree
const stepResult = processSubtractionDigitAtPlace(
digit,
placeValue,
currentDigitAtPlace,
currentState,
currentValue,
toState,
baseProvenance
)
const segmentId = `place-${placeValue}-digit-${digit}-sub`
const segmentStartValue = currentValue
const segmentStartState = { ...currentState }
const placeStart = segmentStartState[placeValue] ?? {
heavenActive: false,
earthActive: 0,
}
const L = placeStart.earthActive
const U: 0 | 1 = placeStart.heavenActive ? 1 : 0
steps.push(...stepResult.steps)
currentValue = stepResult.newValue
currentState = stepResult.newState
const endStepCount = steps.length
const stepIndices = Array.from(
{ length: endStepCount - startStepCount },
(_, i) => startStepCount + i
)
if (stepIndices.length === 0) continue
// Determine pedagogy for subtraction
const plan = determineSubtractionSegmentDecisions(
digit,
placeValue,
currentDigitAtPlace,
stepResult.steps
)
const goal = inferSubtractionGoal({
id: segmentId,
place: placeValue,
digit,
a: currentDigitAtPlace,
L,
U,
plan,
goal: '',
stepIndices,
termIndices: stepIndices,
startValue: segmentStartValue,
startState: segmentStartState,
endValue: currentValue,
endState: { ...currentState },
})
const segment: SegmentDraft = {
id: segmentId,
place: placeValue,
digit,
a: currentDigitAtPlace,
L,
U,
plan,
goal,
stepIndices,
termIndices: stepIndices,
startValue: segmentStartValue,
startState: segmentStartState,
endValue: currentValue,
endState: { ...currentState },
}
segmentsPlan.push(segment)
}
const terms = steps.map((step) => step.operation)
return { terms, segmentsPlan, decompositionSteps: steps }
}
/**
* Process a single digit subtraction at a specific place value.
* Decision tree:
* a >= d: Can subtract without borrowing
* - Direct if enough beads available
* - Five's complement if heaven bead is active but not enough earth beads
* a < d: Need to borrow from higher place
* - Simple borrow if next place > 0
* - Cascade borrow if next place = 0
*/
function processSubtractionDigitAtPlace(
digit: number,
placeValue: number,
currentDigitAtPlace: number,
currentState: AbacusState,
currentValue: number,
toState: (n: number) => AbacusState,
baseProvenance: TermProvenance
): { steps: DecompositionStep[]; newValue: number; newState: AbacusState } {
const a = currentDigitAtPlace
const d = digit
if (a >= d) {
// Can subtract without borrowing
return processDirectSubtraction(d, placeValue, currentState, toState, baseProvenance)
} else {
// Need to borrow from higher place
return processTensBorrow(d, placeValue, currentState, currentValue, toState, baseProvenance)
}
}
/**
* Handle direct subtraction at a place value (a >= d, no borrow needed).
* Cases:
* - d <= 4 and L >= d: Remove earth beads directly
* - d <= 4 and L < d but U = 1: Five's complement (-5 + (5-d))
* - d = 5 and U = 1: Deactivate heaven bead
* - d >= 6 and U = 1: Deactivate heaven + remove (d-5) earth beads
*/
function processDirectSubtraction(
digit: number,
placeValue: number,
currentState: AbacusState,
toState: (n: number) => AbacusState,
baseProvenance: TermProvenance
): { steps: DecompositionStep[]; newValue: number; newState: AbacusState } {
const placeState = currentState[placeValue] || {
heavenActive: false,
earthActive: 0,
}
const L = placeState.earthActive
const U = placeState.heavenActive
const steps: DecompositionStep[] = []
const newState = { ...currentState }
if (digit <= 4) {
if (L >= digit) {
// Direct: Remove earth beads
const subtractValue = digit * 10 ** placeValue
steps.push({
operation: `-${subtractValue}`,
description: `Remove ${digit} earth bead${digit > 1 ? 's' : ''} at ${getPlaceName(placeValue)}`,
targetValue: 0,
provenance: {
...baseProvenance,
termPlace: placeValue,
termPlaceName: getPlaceName(placeValue),
termValue: -subtractValue,
},
})
newState[placeValue] = { ...placeState, earthActive: L - digit }
} else if (U) {
// Five's complement: -d = -5 + (5-d)
const complement = 5 - digit
const groupId = `5comp-sub-${baseProvenance.rhsPlace}-${baseProvenance.rhsDigit}`
const fiveValue = 5 * 10 ** placeValue
const addValue = complement * 10 ** placeValue
steps.push({
operation: `-${fiveValue}`,
description: `Deactivate heaven bead at ${getPlaceName(placeValue)}`,
targetValue: 0,
provenance: {
...baseProvenance,
groupId,
termPlace: placeValue,
termPlaceName: getPlaceName(placeValue),
termValue: -fiveValue,
},
})
steps.push({
operation: `${addValue}`,
description: `Add ${complement} earth bead${complement > 1 ? 's' : ''} at ${getPlaceName(placeValue)}`,
targetValue: 0,
provenance: {
...baseProvenance,
groupId,
termPlace: placeValue,
termPlaceName: getPlaceName(placeValue),
termValue: addValue,
},
})
newState[placeValue] = {
heavenActive: false,
earthActive: L + complement,
}
}
} else if (digit === 5) {
// Deactivate heaven bead
const subtractValue = 5 * 10 ** placeValue
steps.push({
operation: `-${subtractValue}`,
description: `Deactivate heaven bead at ${getPlaceName(placeValue)}`,
targetValue: 0,
provenance: {
...baseProvenance,
termPlace: placeValue,
termPlaceName: getPlaceName(placeValue),
termValue: -subtractValue,
},
})
newState[placeValue] = { ...placeState, heavenActive: false }
} else {
// d >= 6: Deactivate heaven + remove (d-5) earth beads
const earthToRemove = digit - 5
const fiveValue = 5 * 10 ** placeValue
const earthValue = earthToRemove * 10 ** placeValue
steps.push({
operation: `-${fiveValue}`,
description: `Deactivate heaven bead at ${getPlaceName(placeValue)}`,
targetValue: 0,
provenance: {
...baseProvenance,
termPlace: placeValue,
termPlaceName: getPlaceName(placeValue),
termValue: -fiveValue,
},
})
steps.push({
operation: `-${earthValue}`,
description: `Remove ${earthToRemove} earth bead${earthToRemove > 1 ? 's' : ''} at ${getPlaceName(placeValue)}`,
targetValue: 0,
provenance: {
...baseProvenance,
termPlace: placeValue,
termPlaceName: getPlaceName(placeValue),
termValue: -earthValue,
},
})
newState[placeValue] = {
heavenActive: false,
earthActive: L - earthToRemove,
}
}
const currentValue = abacusStateToNumber(currentState)
const newValue = abacusStateToNumber(newState)
return { steps, newValue, newState: toState(newValue) }
}
/**
* Handle ten's borrow when a < d.
* Borrow 10 from next higher place, then subtract.
* If next place is 0, cascade the borrow.
*/
function processTensBorrow(
digit: number,
placeValue: number,
currentState: AbacusState,
currentValue: number,
toState: (n: number) => AbacusState,
baseProvenance: TermProvenance
): { steps: DecompositionStep[]; newValue: number; newState: AbacusState } {
const steps: DecompositionStep[] = []
const complementToAdd = 10 - digit // What we add after borrowing 10
// Check if this requires cascading (next place is 0)
const nextPlaceDigit = getDigitAtPlace(currentValue, placeValue + 1)
const requiresCascading = nextPlaceDigit === 0
const groupId = `10borrow-${baseProvenance.rhsPlace}-${baseProvenance.rhsDigit}`
if (requiresCascading) {
// Generate cascading borrow steps
const cascadeSteps = generateCascadeBorrowSteps(
currentValue,
placeValue,
complementToAdd,
baseProvenance,
groupId
)
steps.push(...cascadeSteps)
} else {
// Simple borrow: -10 from next place, + complement at current place
const borrowValue = 10 ** (placeValue + 1)
const addValue = complementToAdd * 10 ** placeValue
steps.push({
operation: `-${borrowValue}`,
description: `Borrow from ${getPlaceName(placeValue + 1)}`,
targetValue: 0,
provenance: {
...baseProvenance,
groupId,
termPlace: placeValue + 1,
termPlaceName: getPlaceName(placeValue + 1),
termValue: -borrowValue,
},
})
steps.push({
operation: `${addValue}`,
description: `Add ${complementToAdd} to ${getPlaceName(placeValue)} (ten's complement)`,
targetValue: 0,
provenance: {
...baseProvenance,
groupId,
termPlace: placeValue,
termPlaceName: getPlaceName(placeValue),
termValue: addValue,
},
})
}
// Calculate new value: subtract digit at this place
const newValue = currentValue - digit * 10 ** placeValue
return {
steps,
newValue,
newState: toState(newValue),
}
}
/**
* Generate cascade borrow steps when borrowing through zeros.
* Find first non-zero higher place, subtract there, fill 9s in between.
*/
function generateCascadeBorrowSteps(
currentValue: number,
startPlace: number,
complementToAdd: number,
baseProvenance: TermProvenance,
groupId: string
): DecompositionStep[] {
const steps: DecompositionStep[] = []
// Find first non-zero place to borrow from
let borrowPlace = startPlace + 1
const maxCheck = Math.max(1, Math.floor(Math.log10(Math.max(1, currentValue))) + 1) + 2
while (getDigitAtPlace(currentValue, borrowPlace) === 0 && borrowPlace <= maxCheck) {
borrowPlace += 1
}
// Subtract from the highest non-zero place
const borrowValue = 10 ** borrowPlace
steps.push({
operation: `-${borrowValue}`,
description: `Borrow from ${getPlaceName(borrowPlace)} (cascade)`,
targetValue: 0,
provenance: {
...baseProvenance,
groupId,
termPlace: borrowPlace,
termPlaceName: getPlaceName(borrowPlace),
termValue: -borrowValue,
},
})
// Fill all zeros between borrowPlace and startPlace+1 with 9s
for (let fillPlace = borrowPlace - 1; fillPlace > startPlace; fillPlace--) {
const digitAtFillPlace = getDigitAtPlace(currentValue, fillPlace)
if (digitAtFillPlace === 0) {
const fillValue = 9 * 10 ** fillPlace
steps.push({
operation: `${fillValue}`,
description: `Fill ${getPlaceName(fillPlace)} with 9 (cascade)`,
targetValue: 0,
provenance: {
...baseProvenance,
groupId,
termPlace: fillPlace,
termPlaceName: getPlaceName(fillPlace),
termValue: fillValue,
},
})
}
}
// Add complement at the original place
const addValue = complementToAdd * 10 ** startPlace
steps.push({
operation: `${addValue}`,
description: `Add ${complementToAdd} to ${getPlaceName(startPlace)} (ten's complement)`,
targetValue: 0,
provenance: {
...baseProvenance,
groupId,
termPlace: startPlace,
termPlaceName: getPlaceName(startPlace),
termValue: addValue,
},
})
return steps
}
/**
* Determine segment decisions for subtraction operations.
*/
function determineSubtractionSegmentDecisions(
digit: number,
place: number,
currentDigit: number,
steps: DecompositionStep[]
): SegmentDecision[] {
// Check if this is a borrow operation (has positive terms after negative)
const hasNegativeTen = steps.some(
(s) => s.operation.startsWith('-') && isPowerOfTenGE10(Math.abs(parseInt(s.operation, 10)))
)
const hasPositiveAfterNegative =
steps.some((s) => !s.operation.startsWith('-')) &&
steps.some((s) => s.operation.startsWith('-'))
// Check for five's complement pattern: -5 followed by positive
const hasFiveSub = steps.some((s) => {
const val = parseInt(s.operation, 10)
return val < 0 && Math.abs(val) === 5 * 10 ** place
})
const hasPositiveAtPlace = steps.some((s) => {
const val = parseInt(s.operation, 10)
return val > 0 && val < 10 ** (place + 1) && val >= 10 ** place
})
if (currentDigit >= digit) {
// No borrow needed
if (hasFiveSub && hasPositiveAtPlace) {
// Five's complement subtraction: -5 + n
return [
{
rule: 'FiveComplement',
conditions: [`a=${currentDigit} >= d=${digit}`, `L < d, U=1`],
explanation: [
'Not enough earth beads to remove directly.',
`Use -5 + ${5 - digit}; the heaven bead provides the 5.`,
],
},
]
}
return [
{
rule: 'Direct',
conditions: [`a=${currentDigit} >= d=${digit}`],
explanation: ['Can subtract directly without borrowing.'],
},
]
}
// Need to borrow
const hasCascade = steps.length > 2 && steps.some((s) => s.description?.includes('cascade'))
if (hasCascade) {
return [
{
rule: 'TenComplement',
conditions: [`a=${currentDigit} < d=${digit}`, `next place = 0`],
explanation: ['Need to borrow, but next place is 0.', 'Cascade borrow through zeros.'],
},
{
rule: 'Cascade',
conditions: ['zeros in borrowing path'],
explanation: ['Fill intermediate zeros with 9s.'],
},
]
}
return [
{
rule: 'TenComplement',
conditions: [`a=${currentDigit} < d=${digit}`],
explanation: [
'Need to borrow from next higher place.',
`Use -10 + ${10 - digit} to subtract ${digit}.`,
],
},
]
}
/**
* Infer a human-readable goal for subtraction segments.
*/
function inferSubtractionGoal(seg: SegmentDraft): string {
const placeName = getPlaceName(seg.place)
switch (seg.plan[0]?.rule) {
case 'Direct':
return `Subtract ${seg.digit} from ${placeName} directly`
case 'FiveComplement':
return `Subtract ${seg.digit} from ${placeName} using 5's complement`
case 'TenComplement':
return `Subtract ${seg.digit} from ${placeName} with a borrow`
case 'Cascade':
return `Borrow through ${placeName}+ from nearest non-zero place`
default:
return `Subtract at ${placeName}`
}
}
// =============================================================================
// END SUBTRACTION IMPLEMENTATION
// =============================================================================
/**
* Generate English instruction from mathematical term
*/
function generateInstructionFromTerm(
term: string,
_stepIndex: number,
isComplementContext: boolean = false
): string {
// Parse the term to determine what instruction to give
// Handle negative numbers FIRST
if (term.startsWith('-')) {
const value = parseInt(term.substring(1), 10)
if (value <= 4) {
return `remove ${value} earth bead${value > 1 ? 's' : ''} in ones column`
} else if (value === 5) {
return 'deactivate heaven bead'
} else if (value >= 6 && value <= 9) {
const e = value - 5
return `deactivate heaven bead and remove ${e} earth bead${e > 1 ? 's' : ''} in ones column`
} else if (isPowerOfTenGE10(value)) {
const place = Math.round(Math.log10(value))
return `remove 1 from ${getPlaceName(place)}`
} else if (value >= 10 && !isPowerOfTenGE10(value)) {
const place = Math.floor(Math.log10(value))
const digit = Math.floor(value / 10 ** place)
if (digit === 5) return `deactivate heaven bead in ${getPlaceName(place)} column`
if (digit > 5)
return `deactivate heaven bead and remove ${digit - 5} earth beads in ${getPlaceName(place)} column`
// (digit 6..9 handled above; digit 1..4 would be rare here)
return `remove ${digit} from ${getPlaceName(place)}`
}
}
// Handle simple positive numbers
const value = parseInt(term, 10)
if (!Number.isNaN(value) && value > 0) {
if (value === 5) {
return isComplementContext ? 'add 5' : 'activate heaven bead'
} else if (value <= 4) {
return `add ${value} earth bead${value > 1 ? 's' : ''} in ones column`
} else if (value >= 6 && value <= 9) {
const earthBeads = value - 5
return `activate heaven bead and add ${earthBeads} earth beads in ones column`
} else if (isPowerOfTenGE10(value)) {
const place = Math.round(Math.log10(value))
return `add 1 to ${getPlaceName(place)}`
} else if (value >= 10 && !isPowerOfTenGE10(value)) {
const place = Math.floor(Math.log10(value))
const digit = Math.floor(value / 10 ** place)
if (digit === 5) return `activate heaven bead in ${getPlaceName(place)} column`
if (digit > 5)
return `activate heaven bead and add ${digit - 5} earth beads in ${getPlaceName(place)} column`
return `add ${digit} to ${getPlaceName(place)}`
}
}
return `perform operation: ${term}`
}
function getPlaceName(place: number): string {
const names = [
'ones',
'tens',
'hundreds',
'thousands',
'ten-thousands',
'hundred-thousands',
'millions',
]
return names[place] ?? `${place} place`
}
/**
* Helper functions
*/
function getDigitAtPlace(value: number, placeValue: number): number {
return Math.floor(value / 10 ** placeValue) % 10
}
function abacusStateToNumber(state: AbacusState): number {
let total = 0
Object.entries(state).forEach(([place, beadState]) => {
const placeNum = parseInt(place, 10)
const placeValue = (beadState.heavenActive ? 5 : 0) + beadState.earthActive
total += placeValue * 10 ** placeNum
})
return total
}
/**
* Calculate what a mathematical term should accomplish
*/
function calculateStepResult(
currentValue: number,
term: string
): {
newValue: number
operation: 'add' | 'subtract'
addAmount?: number
subtractAmount?: number
} {
// Parse the term to understand the operation
if (term.startsWith('-')) {
// Pure subtraction like "-6"
const amount = parseInt(term.substring(1), 10)
return {
newValue: currentValue - amount,
operation: 'subtract',
subtractAmount: amount,
}
} else {
// Pure addition like "10"
const amount = parseInt(term, 10)
return {
newValue: currentValue + amount,
operation: 'add',
addAmount: amount,
}
}
// Fallback
return {
newValue: currentValue,
operation: 'add',
}
}
/**
* Calculate bead movements for a specific step
*/
function calculateStepBeadMovements(
fromState: AbacusState,
toState: AbacusState,
stepIndex: number
): StepBeadHighlight[] {
const { additions, removals } = calculateBeadChanges(fromState, toState)
const movements: StepBeadHighlight[] = []
// Convert additions to step bead movements
additions.forEach((bead, index) => {
movements.push({
...bead,
stepIndex,
direction: 'activate',
order: index,
})
})
// Convert removals to step bead movements
removals.forEach((bead, index) => {
movements.push({
...bead,
stepIndex,
direction: 'deactivate',
order: additions.length + index,
})
})
// Stabilize movement ordering for consistent UI animations
// Priority: higher place → heaven beads → activations first
movements.sort((a, b) => {
if (a.placeValue !== b.placeValue) return b.placeValue - a.placeValue
if (a.beadType !== b.beadType) return a.beadType === 'heaven' ? -1 : 1
if (a.direction !== b.direction) return a.direction === 'activate' ? -1 : 1
return 0
})
// Reassign order indices after sorting
movements.forEach((movement, index) => {
movement.order = index
})
return movements
}
/**
* Generate English instruction based on actual bead movements
*/
function generateStepInstruction(
beadMovements: StepBeadHighlight[],
_mathematicalTerm: string,
_stepResult: any
): string {
if (beadMovements.length === 0) {
return 'No bead movements required'
}
// Group by place and direction
const byPlace: {
[place: number]: {
adds: StepBeadHighlight[]
removes: StepBeadHighlight[]
}
} = {}
beadMovements.forEach((bead) => {
if (!byPlace[bead.placeValue]) {
byPlace[bead.placeValue] = { adds: [], removes: [] }
}
if (bead.direction === 'activate') {
byPlace[bead.placeValue].adds.push(bead)
} else {
byPlace[bead.placeValue].removes.push(bead)
}
})
// Generate instruction for each place
const instructions: string[] = []
Object.keys(byPlace)
.map((p) => parseInt(p, 10))
.sort((a, b) => b - a) // Pedagogical order: highest place first
.forEach((place) => {
const placeName = getPlaceName(place)
const placeData = byPlace[place]
// Handle additions
if (placeData.adds.length > 0) {
const instruction = generatePlaceInstruction(placeData.adds, 'add', placeName)
instructions.push(instruction)
}
// Handle removals
if (placeData.removes.length > 0) {
const instruction = generatePlaceInstruction(placeData.removes, 'remove', placeName)
instructions.push(instruction)
}
})
return instructions.join(', then ')
}
/**
* Generate instruction for a specific place
*/
function generatePlaceInstruction(
beads: StepBeadHighlight[],
action: 'add' | 'remove',
placeName: string
): string {
const heavenBeads = beads.filter((b) => b.beadType === 'heaven')
const earthBeads = beads.filter((b) => b.beadType === 'earth')
const parts: string[] = []
if (heavenBeads.length > 0) {
parts.push(
action === 'add'
? `activate heaven bead in ${placeName} column`
: `deactivate heaven bead in ${placeName} column`
)
}
if (earthBeads.length > 0) {
const verb = action === 'add' ? 'add' : 'remove'
const count = earthBeads.length
const beadText = count === 1 ? 'earth bead' : `${count} earth beads`
parts.push(`${verb} ${beadText} in ${placeName} column`)
}
return parts.join(' and ')
}
/**
* Validate that all aspects of a step are consistent
*/
function validateStepConsistency(
_mathematicalTerm: string,
_englishInstruction: string,
startValue: number,
expectedValue: number,
beadMovements: StepBeadHighlight[],
toState: (n: number) => AbacusState
): { isValid: boolean; issues: string[] } {
const issues: string[] = []
// Validate that bead movements produce the expected value
const startState = toState(startValue)
const expectedState = toState(expectedValue)
// Apply bead movements to start state
const simulatedState = { ...startState }
beadMovements.forEach((movement) => {
// Ensure place exists before mutating
if (!simulatedState[movement.placeValue]) {
simulatedState[movement.placeValue] = {
heavenActive: false,
earthActive: 0,
}
}
if (movement.direction === 'activate') {
if (movement.beadType === 'heaven') {
simulatedState[movement.placeValue].heavenActive = true
} else {
simulatedState[movement.placeValue].earthActive++
}
} else {
if (movement.beadType === 'heaven') {
simulatedState[movement.placeValue].heavenActive = false
} else {
simulatedState[movement.placeValue].earthActive--
}
}
})
// Validate bead ranges after applying movements
for (const place in simulatedState) {
const placeNum = parseInt(place, 10)
const state = simulatedState[placeNum]
if (state.earthActive < 0 || state.earthActive > 4) {
issues.push(`Place ${place}: earth beads out of range (${state.earthActive})`)
}
if (typeof state.heavenActive !== 'boolean') {
issues.push(`Place ${place}: heaven bead state invalid (${state.heavenActive})`)
}
}
// Check if simulated state matches expected state
for (const place in expectedState) {
const placeNum = parseInt(place, 10)
const expected = expectedState[placeNum]
const simulated = simulatedState[placeNum]
if (!simulated) {
issues.push(`Place ${place}: missing in simulated state`)
continue
}
if (expected.heavenActive !== simulated.heavenActive) {
issues.push(`Place ${place}: heaven bead mismatch`)
}
if (expected.earthActive !== simulated.earthActive) {
issues.push(`Place ${place}: earth bead count mismatch`)
}
}
// Check for extra places in simulated state that shouldn't exist
for (const place in simulatedState) {
if (!(place in expectedState)) {
const placeNum = parseInt(place, 10)
const s = simulatedState[placeNum]
if (s.heavenActive || s.earthActive > 0) {
issues.push(`Place ${place}: unexpected nonzero state in simulation`)
}
}
}
// Final numeric equivalence check
const simulatedValue = abacusStateToNumber(simulatedState)
if (simulatedValue !== expectedValue) {
issues.push(`Numeric mismatch: simulated=${simulatedValue}, expected=${expectedValue}`)
}
return {
isValid: issues.length === 0,
issues,
}
}
/**
* Build the full pedagogical decomposition string with term positions
*/
export function buildFullDecompositionWithPositions(
startValue: number,
targetValue: number,
terms: string[]
): {
fullDecomposition: string
termPositions: Array<{ startIndex: number; endIndex: number }>
} {
const difference = targetValue - startValue
const isSubtraction = difference < 0
// Handle zero difference special case
if (difference === 0) {
return {
fullDecomposition: `${startValue} + 0 = ${targetValue}`,
termPositions: [],
}
}
// Group consecutive complement terms into segments
// For subtraction: group negative term followed by positive(s) as complement
// For addition: group positive term followed by negative(s) as complement
const segments: Array<{
terms: string[]
isComplement: boolean
}> = []
let i = 0
while (i < terms.length) {
const currentTerm = terms[i]
if (isSubtraction) {
// Subtraction: complement is negative followed by positive(s)
// e.g., "-5" followed by "1" for five's complement subtraction
if (i + 1 < terms.length && currentTerm.startsWith('-') && !terms[i + 1].startsWith('-')) {
const complementTerms = [currentTerm]
let j = i + 1
while (j < terms.length && !terms[j].startsWith('-')) {
complementTerms.push(terms[j])
j++
}
segments.push({
terms: complementTerms,
isComplement: true,
})
i = j
} else {
segments.push({
terms: [currentTerm],
isComplement: false,
})
i++
}
} else {
// Addition: complement is positive followed by negative(s)
if (i + 1 < terms.length && !currentTerm.startsWith('-') && terms[i + 1].startsWith('-')) {
const complementTerms = [currentTerm]
let j = i + 1
while (j < terms.length && terms[j].startsWith('-')) {
complementTerms.push(terms[j])
j++
}
segments.push({
terms: complementTerms,
isComplement: true,
})
i = j
} else {
segments.push({
terms: [currentTerm],
isComplement: false,
})
i++
}
}
}
// Build decomposition string with proper segment formatting
let termString = ''
const termPositions: Array<{ startIndex: number; endIndex: number }> = []
segments.forEach((segment, segmentIndex) => {
if (segment.isComplement) {
if (isSubtraction) {
// Subtraction complement: (-5 + 1) format
const negativeStr = segment.terms[0].substring(1) // Remove '-' sign
const positiveStrs = segment.terms.slice(1)
const segmentStr = `(-${negativeStr} + ${positiveStrs.join(' + ')})`
if (segmentIndex === 0) {
termString = segmentStr
} else {
termString += ` + ${segmentStr}`
}
} else {
// Addition complement: (10 - 3) format
const positiveStr = segment.terms[0]
const negativeStrs = segment.terms.slice(1).map((t) => t.substring(1))
const segmentStr = `(${positiveStr} - ${negativeStrs.join(' - ')})`
if (segmentIndex === 0) {
termString = segmentStr
} else {
termString += ` + ${segmentStr}`
}
}
} else {
// Single term
const term = segment.terms[0]
if (segmentIndex === 0) {
if (isSubtraction && term.startsWith('-')) {
// First term in subtraction is negative, wrap in parens
termString = `(${term})`
} else {
termString = term
}
} else if (term.startsWith('-')) {
termString += ` + (${term})` // Wrap negative terms for subtraction
} else {
termString += ` + ${term}`
}
}
})
// Build full decomposition
let leftSide: string
if (isSubtraction) {
// Format: "startValue - |difference| = startValue + "
leftSide = `${startValue} - ${Math.abs(difference)} = ${startValue} + `
} else {
leftSide = `${startValue} + ${difference} = ${startValue} + `
}
const rightSide = ` = ${targetValue}`
const fullDecomposition = leftSide + termString + rightSide
// Calculate precise positions for each original term
let currentPos = leftSide.length
let segmentTermIndex = 0
segments.forEach((segment, segmentIndex) => {
if (segment.isComplement) {
// Account for " + " delimiter before complement segments (except first)
if (segmentIndex > 0) {
currentPos += 3 // Skip " + "
}
// Position within parenthesized complement
currentPos += 1 // Skip opening '('
if (isSubtraction) {
// Subtraction complement: (-5 + 1)
segment.terms.forEach((term, termInSegmentIndex) => {
if (termInSegmentIndex === 0) {
// Negative term - position on number part (skip -)
currentPos += 1 // Skip '-'
const numberStr = term.substring(1)
termPositions[segmentTermIndex] = {
startIndex: currentPos,
endIndex: currentPos + numberStr.length,
}
currentPos += numberStr.length
} else {
// Positive term
currentPos += 3 // Skip ' + '
termPositions[segmentTermIndex] = {
startIndex: currentPos,
endIndex: currentPos + term.length,
}
currentPos += term.length
}
segmentTermIndex++
})
} else {
// Addition complement: (10 - 3)
segment.terms.forEach((term, termInSegmentIndex) => {
const startIndex = currentPos
if (termInSegmentIndex === 0) {
// Positive term
termPositions[segmentTermIndex] = {
startIndex,
endIndex: startIndex + term.length,
}
currentPos += term.length
} else {
// Negative term (but we position on just the number part)
currentPos += 3 // Skip ' - '
const numberStr = term.substring(1) // Remove '-'
termPositions[segmentTermIndex] = {
startIndex: currentPos,
endIndex: currentPos + numberStr.length,
}
currentPos += numberStr.length
}
segmentTermIndex++
})
}
currentPos += 1 // Skip closing ')'
} else {
// Single term segment
const term = segment.terms[0]
if (segmentIndex > 0) {
currentPos += 3 // Skip ' + '
}
if (isSubtraction && term.startsWith('-')) {
// Wrapped negative: (−5)
currentPos += 1 // Skip '('
currentPos += 1 // Skip '−'
const numberStr = term.substring(1)
termPositions[segmentTermIndex] = {
startIndex: currentPos,
endIndex: currentPos + numberStr.length,
}
currentPos += numberStr.length
currentPos += 1 // Skip ')'
} else if (term.startsWith('-')) {
// Unwrapped negative (shouldn't happen often)
currentPos += 1 // Skip '−'
const numberStr = term.substring(1)
termPositions[segmentTermIndex] = {
startIndex: currentPos,
endIndex: currentPos + numberStr.length,
}
currentPos += numberStr.length
} else {
// Positive term
termPositions[segmentTermIndex] = {
startIndex: currentPos,
endIndex: currentPos + term.length,
}
currentPos += term.length
}
segmentTermIndex++
}
})
return { fullDecomposition, termPositions }
}
function assertSegments(seq: UnifiedInstructionSequence) {
// 1) Every step that has a segmentId belongs to a segment that includes it
const byId = new Map(seq.segments.map((s) => [s.id, s]))
seq.steps.forEach((st, i) => {
if (!st.segmentId) return
const seg = byId.get(st.segmentId)
if (!seg) throw new Error(`step[${i}] has unknown segmentId ${st.segmentId}`)
if (!seg.stepIndices.includes(i)) {
throw new Error(`step[${i}] not contained in its segment ${st.segmentId}`)
}
})
// 2) Segment ranges are contiguous and non-empty
seq.segments.forEach((seg) => {
if (seg.stepIndices.length === 0) {
throw new Error(`segment ${seg.id} has no steps`)
}
if (seg.termRange.endIndex <= seg.termRange.startIndex) {
throw new Error(`segment ${seg.id} has empty term range`)
}
})
}
/**
* Build equation anchors for addend digit highlighting
*/
function buildEquationAnchors(
startValue: number,
targetValue: number,
fullDecomposition: string
): EquationAnchors {
const addend = targetValue - startValue
const addendText = addend.toString()
const expectedPrefix = `${startValue} + `
// Addend starts immediately after "startValue + "
const startIndex = expectedPrefix.length
// Optional sanity check (no throw in prod)
if (process.env.NODE_ENV !== 'production') {
const head = fullDecomposition.slice(0, startIndex + addendText.length)
if (head !== `${expectedPrefix}${addendText}`) {
// fall back to a search if format changes
const idx = fullDecomposition.indexOf(`${expectedPrefix}${addendText}`)
if (idx !== -1) {
const start = idx + expectedPrefix.length
return {
differenceText: Math.abs(addend).toString(),
rhsDigitPositions: Array.from(addendText).map((_, i) => ({
digitIndex: i,
startIndex: start + i,
endIndex: start + i + 1,
})),
}
}
}
}
return {
differenceText: Math.abs(addend).toString(),
rhsDigitPositions: Array.from(addendText).map((_, i) => ({
digitIndex: i,
startIndex: startIndex + i,
endIndex: startIndex + i + 1,
})),
}
}
/**
* Check if a number is a power of 10
*/
/**
* Determine if a pedagogical decomposition is meaningful (not redundant)
*/
function isDecompositionMeaningful(
startValue: number,
targetValue: number,
decompositionTerms: string[],
fullDecomposition: string
): boolean {
const difference = targetValue - startValue
// No change = not meaningful
if (difference === 0) {
return false
}
// Check if we have complement expressions (parentheses)
const hasComplementOperations = fullDecomposition.includes('(')
// Complement operations are always meaningful (they show soroban technique)
if (hasComplementOperations) {
return true
}
// Multiple terms without complements can be meaningful for multi-place operations
// but not for simple natural breakdowns like 6 = 5 + 1
if (decompositionTerms.length > 1) {
// Check if it's a simple natural breakdown (like 5 + 1, 5 + 2, 5 + 3, 5 + 4)
if (decompositionTerms.length === 2) {
const [first, second] = decompositionTerms
if (first === '5' && parseInt(second, 10) >= 1 && parseInt(second, 10) <= 4) {
return false // Natural soroban representation, not pedagogically meaningful
}
}
return true
}
// Single term that equals the difference = not meaningful (redundant)
if (decompositionTerms.length === 1) {
const term = decompositionTerms[0]
if (term === Math.abs(difference).toString()) {
return false
}
}
// For complex cases with multiple breakdowns, check if it's just restating
const decompositionPart = fullDecomposition.split(' = ')[1]?.split(' = ')[0]
if (decompositionPart) {
// If the middle part is just the same as "start + difference", it's redundant
const simplePattern = `${startValue} + ${Math.abs(difference)}`
if (decompositionPart.replace(/\s/g, '') === simplePattern.replace(/\s/g, '')) {
return false
}
}
// Default to meaningful
return true
}
|