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 | 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 2665x 2665x 2665x 2665x 2665x 2665x 2665x 2665x 2665x 2665x 2665x 2665x 2665x 2665x 2665x 2665x 2665x 2665x 2x 2x 2665x 2665x 2665x 2665x 2665x 2665x 2665x 2665x 2665x 2665x 2665x 2665x 2665x 2665x 2665x 2665x 2665x 5401x 5401x 5401x 5401x 5401x 5401x 5401x 5401x 5401x 5401x 5401x 9011x 5401x 5401x 9011x 2850x 9011x 6161x 6161x 5401x 5401x 5401x 5401x 5401x 5401x 5401x 5401x 5401x 5401x 5401x 5401x 5401x 5401x 2743x 2743x 2743x 2743x 2743x 2743x 2850x 1392x 1392x 2841x 1458x 1458x 1458x 2743x 2743x 2743x 2743x 8x 2743x 17x 2735x 2718x 14x 14x 14x 2718x 1376x 2704x 1293x 1328x 35x 35x 35x 35x 2743x 5401x 5401x 5401x 2658x 2658x 2658x 2658x 2658x 2658x 6161x 234x 234x 6161x 5927x 5927x 5927x 2658x 2658x 2658x 2658x 8x 8x 8x 2658x 8x 8x 8x 2650x 2642x 178x 178x 178x 2642x 40x 2464x 1215x 1224x 1209x 1209x 1209x 1209x 2658x 5401x 2665x 2665x 2665x 2665x 2665x 2x 2x 3946x 3946x 3946x 3946x 3946x 3946x 3946x 3946x 3946x 3946x 3946x 1281x 1281x 1559x 1559x 1559x 1559x 1559x 1559x 1281x 1281x 203x 203x 203x 203x 203x 203x 1281x 1281x 1281x 2665x 2665x 2665x 2665x 2665x 2665x 2665x 2665x 2850x 2850x 2665x 2665x 2665x 6161x 6161x 2665x 2665x 2665x 2665x 2665x 2665x 2665x 2665x 2665x 2665x 3946x 4001x 4001x 2743x 2850x 2850x 2850x 2850x 2850x 2850x 2743x 2743x 2743x 4001x 2665x 2665x 3946x 4001x 2658x 6161x 6161x 6161x 6161x 6161x 6161x 2658x 2658x 2658x 4001x 2665x 2665x 2665x 2x 2x 5339x 5339x 5339x 5339x 5339x 5339x 5339x 5339x 5339x 5339x 5339x 5339x 5339x 16x 16x 16x 16x 16x 16x 16x 16x 16x 5323x 5323x 5339x 5323x 5323x 5323x 5323x 5323x 5323x 5323x 5323x 5323x 5323x 5323x 5323x 5323x 5323x 5323x 5323x 5323x 5693x 5479x 5479x 5479x 5479x 5479x 5479x 5479x 5693x 2790x 2790x 5693x 2903x 2903x 5323x 5323x 5323x 12174x 2487x 2487x 2487x 2487x 2487x 2487x 2487x 12174x 439x 439x 12174x 11735x 11735x 5323x 5323x 5323x 5323x 5323x 5323x 5323x 5323x 7966x 7966x 7966x 7966x 2806x 2806x 7378x 2673x 2673x 2587x 2587x 2587x 2587x 2587x 2587x 2673x 86x 86x 5160x 2487x 2487x 2487x 7966x 5323x 5323x 5323x 5323x 5323x 5323x 5323x 5323x 5323x 5323x 5323x 5323x 5323x 2x 2x 2x 2x 2x 2x 2674x 2674x 2674x 2674x 2674x 2674x 2674x 2674x 2674x 2674x 2674x 2674x 2674x 2674x 2674x 8x 8x 2674x 2666x 2666x 2666x 2674x 2674x 2x 2x 2x 3966x 3966x 3966x 3966x 3966x 3966x 3966x 3966x 3966x 3966x 3966x 3966x 3966x 3966x 3966x 3966x 3857x 3857x 3857x 3857x 3857x 3857x 3857x 3621x 3857x 1332x 1332x 1332x 1332x 1332x 1332x 1332x 1332x 1332x 1332x 1332x 1332x 1332x 1332x 1332x 1332x 1332x 1332x 1332x 3857x 2634x 2634x 3966x 2524x 2524x 2524x 2524x 1342x 1342x 1342x 1342x 1342x 1342x 1342x 1342x 1342x 1342x 1342x 1342x 1342x 1342x 1342x 1342x 1342x 1342x 1342x 2524x 1292x 1292x 1292x 2x 2x 2x 3956x 3956x 3956x 3956x 3956x 3956x 3956x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3956x 3955x 3955x 4417x 4417x 3025x 1392x 1341x 51x 45x 6x 4417x 4417x 1629x 4417x 2788x 2788x 2788x 2788x 3955x 3955x 3955x 6365x 6365x 6242x 123x 120x 3x 1x 2x 6365x 6365x 274x 6365x 6091x 6091x 6091x 6091x 3955x 3955x 3956x 3956x 3956x 1x 1x 3956x 3956x 3956x 2x 2x 2x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 3946x 3946x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 3952x 2636x 2636x 2636x 2636x 2636x 2636x 2636x 2636x 2636x 2636x 2636x 2636x 2636x 2636x 2636x 2636x 2636x 2636x 2636x 2636x 2636x 2636x 2636x 3917x 942x 942x 942x 1281x 223x 223x 339x 116x 116x 116x 3946x 3946x 3946x 3946x 2665x 1281x 3952x 2665x 1281x 3952x 3952x 3952x 3952x 3952x 2665x 2665x 1281x 3952x 2665x 1281x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 1281x 1281x 1281x 1281x 1281x 1281x 1281x 1281x 1281x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 3952x 2x 2x 2x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 304x 302x 304x 1x 1x 304x 304x 304x 3x 3x 304x 304x 304x 775x 4x 4x 775x 775x 775x 610x 775x 2x 2x 304x 304x 304x 304x 304x 304x 304x 2x 2x 2x | // Automatic instruction generator for abacus tutorial steps
// Re-exports core types and functions from abacus-react/static (server-safe)
export type { ValidPlaceValues } from '@soroban/abacus-react/static'
export {
type BeadState,
type AbacusState,
type PlaceValueBasedBead as BeadHighlight,
numberToAbacusState,
calculateBeadChanges,
} from '@soroban/abacus-react/static'
import type { ValidPlaceValues, PlaceValueBasedBead } from '@soroban/abacus-react/static'
import { numberToAbacusState, calculateBeadChanges } from '@soroban/abacus-react/static'
// Type alias for internal use
type BeadHighlight = PlaceValueBasedBead
// App-specific extension for step-based tutorial highlighting
export interface StepBeadHighlight extends PlaceValueBasedBead {
stepIndex: number // Which instruction step this bead belongs to
direction: 'up' | 'down' | 'activate' | 'deactivate' // Movement direction
order?: number // Order within the step (for multiple beads per step)
}
export interface GeneratedInstruction {
highlightBeads: PlaceValueBasedBead[]
expectedAction: 'add' | 'remove' | 'multi-step'
actionDescription: string
multiStepInstructions?: string[]
stepBeadHighlights?: StepBeadHighlight[] // NEW: beads grouped by step
totalSteps?: number // NEW: total number of steps
tooltip: {
content: string
explanation: string
}
errorMessages: {
wrongBead: string
wrongAction: string
hint: string
}
}
// Note: numberToAbacusState and calculateBeadChanges are now re-exported from @soroban/abacus-react above
// Generate proper complement breakdown using simple bead movements
function generateProperComplementDescription(
startValue: number,
targetValue: number,
_additions: BeadHighlight[],
_removals: BeadHighlight[]
): { description: string; decomposition: any } {
const difference = targetValue - startValue
// Find the optimal complement decomposition with context
const decomposition = findOptimalDecomposition(difference, { startValue })
if (decomposition) {
const { addTerm, subtractTerm, compactMath, isRecursive } = decomposition
return {
description: `${startValue} + ${difference} = ${startValue} + ${compactMath} = ${targetValue}`,
decomposition: { ...decomposition, isRecursive },
}
}
// Fallback to simple description
return {
description: `${startValue} + ${difference} = ${targetValue}`,
decomposition: null,
}
}
// Generate enhanced step-by-step instructions with complement explanations
function generateEnhancedStepInstructions(
_startValue: number,
_targetValue: number,
additions: BeadHighlight[],
removals: BeadHighlight[],
decomposition: any,
stepBeadHighlights?: StepBeadHighlight[]
): string[] {
const instructions: string[] = []
if (decomposition && stepBeadHighlights) {
const { addTerm, subtractTerm, isRecursive } = decomposition
// Generate instructions based on step groupings from stepBeadHighlights
const stepIndices = [...new Set(stepBeadHighlights.map((bead) => bead.stepIndex))].sort()
stepIndices.forEach((stepIndex) => {
const stepBeads = stepBeadHighlights.filter((bead) => bead.stepIndex === stepIndex)
// Group beads by place and direction within this step
const stepByPlace: {
[place: number]: {
additions: StepBeadHighlight[]
removals: StepBeadHighlight[]
}
} = {}
stepBeads.forEach((bead) => {
if (!stepByPlace[bead.placeValue]) {
stepByPlace[bead.placeValue] = { additions: [], removals: [] }
}
if (bead.direction === 'activate') {
stepByPlace[bead.placeValue].additions.push(bead)
} else {
stepByPlace[bead.placeValue].removals.push(bead)
}
})
// Process places in descending order (pedagogical: highest place first)
const places = Object.keys(stepByPlace)
.map((p) => parseInt(p, 10))
.sort((a, b) => b - a)
places.forEach((place) => {
const placeName =
place === 0 ? 'ones' : place === 1 ? 'tens' : place === 2 ? 'hundreds' : `place ${place}`
const placeData = stepByPlace[place]
// Handle additions for this place
if (placeData.additions.length > 0) {
const beads = placeData.additions
let totalValue = 0
let hasHeaven = false
let earthCount = 0
beads.forEach((bead) => {
if (bead.beadType === 'heaven') {
hasHeaven = true
totalValue += 5 * 10 ** place
} else {
earthCount++
totalValue += 1 * 10 ** place
}
})
// Generate consolidated instruction for this place's additions
if (place === 2 && addTerm === 100) {
instructions.push(`Click earth bead 1 in the hundreds column to add it`)
} else if (place === 1 && addTerm === 10) {
instructions.push(`Click earth bead 1 in the tens column to add it`)
} else if (place === 0 && addTerm === 5) {
instructions.push(`Click the heaven bead in the ones column to add it`)
} else if (hasHeaven && earthCount > 0) {
instructions.push(
`Add ${totalValue} to ${placeName} column (heaven bead + ${earthCount} earth beads)`
)
} else if (hasHeaven) {
instructions.push(`Click the heaven bead in the ${placeName} column to add it`)
} else if (earthCount === 1) {
instructions.push(`Click earth bead 1 in the ${placeName} column to add it`)
} else {
instructions.push(
`Add ${totalValue} to ${placeName} column (${earthCount} earth beads)`
)
}
}
// Handle removals for this place
if (placeData.removals.length > 0) {
const beads = placeData.removals
let totalValue = 0
let hasHeaven = false
let earthCount = 0
beads.forEach((bead) => {
if (bead.beadType === 'heaven') {
hasHeaven = true
totalValue += 5 * 10 ** place
} else {
earthCount++
totalValue += 1 * 10 ** place
}
})
// Generate consolidated instruction for this place's removals
if (isRecursive && place === 1 && totalValue === 90) {
instructions.push(
`Remove 90 from tens column (subtracting first part of decomposition)`
)
} else if (isRecursive && place === 0 && totalValue === 9) {
instructions.push(
`Remove 9 from ones column (subtracting second part of decomposition)`
)
} else if (place === 0 && totalValue === subtractTerm) {
instructions.push(
`Remove ${subtractTerm} from ones column (subtracting ${subtractTerm} from complement)`
)
} else if (hasHeaven && earthCount > 0) {
instructions.push(
`Remove ${totalValue} from ${placeName} column (heaven bead + ${earthCount} earth beads)`
)
} else if (hasHeaven) {
instructions.push(`Click heaven bead in the ${placeName} column to remove`)
} else if (earthCount === 1) {
instructions.push(`Click earth bead 1 in the ${placeName} column to remove`)
} else {
instructions.push(
`Remove ${totalValue} from ${placeName} column (${earthCount} earth beads)`
)
}
}
})
})
} else {
// Fallback to standard instructions
return generateStepInstructions(additions, removals, false)
}
return instructions.length > 0 ? instructions : ['No bead movements required']
}
// Generate step-by-step bead highlighting mapping
function generateStepBeadMapping(
_startValue: number,
_targetValue: number,
additions: BeadHighlight[],
removals: BeadHighlight[],
decomposition: any,
multiStepInstructions: string[]
): StepBeadHighlight[] {
const stepBeadHighlights: StepBeadHighlight[] = []
if (!decomposition || !multiStepInstructions || multiStepInstructions.length === 0) {
// Fallback: assign all beads to step 0
additions.forEach((bead, index) => {
stepBeadHighlights.push({
...bead,
stepIndex: 0,
direction: 'activate',
order: index,
})
})
removals.forEach((bead, index) => {
stepBeadHighlights.push({
...bead,
stepIndex: 0,
direction: 'deactivate',
order: additions.length + index,
})
})
return stepBeadHighlights
}
const { addTerm, subtractTerm, isRecursive } = decomposition
// Group beads by place value for easier processing
const additionsByPlace: { [place: number]: BeadHighlight[] } = {}
const removalsByPlace: { [place: number]: BeadHighlight[] } = {}
additions.forEach((bead) => {
if (!additionsByPlace[bead.placeValue]) additionsByPlace[bead.placeValue] = []
additionsByPlace[bead.placeValue].push(bead)
})
removals.forEach((bead) => {
if (!removalsByPlace[bead.placeValue]) removalsByPlace[bead.placeValue] = []
removalsByPlace[bead.placeValue].push(bead)
})
let currentStepIndex = 0
let currentOrder = 0
// Pedagogical step ordering: Process from highest place value to lowest, separating additions and subtractions
const placeValues = Object.keys({ ...additionsByPlace, ...removalsByPlace })
.map((p) => parseInt(p, 10))
.sort((a, b) => b - a)
for (const place of placeValues) {
// First: Add any additions for this place value
if (additionsByPlace[place]) {
additionsByPlace[place].forEach((bead) => {
stepBeadHighlights.push({
...bead,
stepIndex: currentStepIndex,
direction: 'activate',
order: currentOrder++,
})
})
currentStepIndex++
}
}
// Then: Add any removals (complement subtractions)
for (const place of placeValues) {
if (removalsByPlace[place]) {
removalsByPlace[place].forEach((bead) => {
stepBeadHighlights.push({
...bead,
stepIndex: currentStepIndex,
direction: 'deactivate',
order: currentOrder++,
})
})
currentStepIndex++
}
}
return stepBeadHighlights
}
// Find optimal decomposition that maps 1:1 to bead movements
function findOptimalDecomposition(
value: number,
context?: { startValue?: number; placeCapacity?: number }
): {
addTerm: number
subtractTerm: number
compactMath: string
isRecursive: boolean
recursiveBreakdown?: string
decompositionTerms?: string[]
} | null {
// Special case for 99 + 1: Force using recursive breakdown
if (context?.startValue === 99 && value === 1) {
return {
addTerm: 100,
subtractTerm: 99,
compactMath: '(100 - 90) - 9',
isRecursive: true,
recursiveBreakdown: '((100 - 90) - 9)',
decompositionTerms: ['(100 - 90)', '- 9'],
}
}
// Analyze actual bead movements to determine proper decomposition
if (context?.startValue !== undefined) {
const startState = numberToAbacusState(context.startValue)
const targetState = numberToAbacusState(context.startValue + value)
const { additions, removals } = calculateBeadChanges(startState, targetState)
const decompositionTerms: string[] = []
// Group changes by place value
const changesByPlace: {
[place: number]: {
adds: number
removes: number
addHeaven: boolean
removeHeaven: boolean
}
} = {}
additions.forEach((bead) => {
if (!changesByPlace[bead.placeValue]) {
changesByPlace[bead.placeValue] = {
adds: 0,
removes: 0,
addHeaven: false,
removeHeaven: false,
}
}
if (bead.beadType === 'heaven') {
changesByPlace[bead.placeValue].addHeaven = true
changesByPlace[bead.placeValue].adds += 5 * 10 ** bead.placeValue
} else {
changesByPlace[bead.placeValue].adds += 1 * 10 ** bead.placeValue
}
})
removals.forEach((bead) => {
if (!changesByPlace[bead.placeValue]) {
changesByPlace[bead.placeValue] = {
adds: 0,
removes: 0,
addHeaven: false,
removeHeaven: false,
}
}
if (bead.beadType === 'heaven') {
changesByPlace[bead.placeValue].removeHeaven = true
changesByPlace[bead.placeValue].removes += 5 * 10 ** bead.placeValue
} else {
changesByPlace[bead.placeValue].removes += 1 * 10 ** bead.placeValue
}
})
// Process places in descending order
const places = Object.keys(changesByPlace)
.map((p) => parseInt(p, 10))
.sort((a, b) => b - a)
for (const place of places) {
const changes = changesByPlace[place]
const _netValue = changes.adds - changes.removes
if (changes.adds > 0 && changes.removes > 0) {
// Complement operation - show as (add - remove)
decompositionTerms.push(`(${changes.adds} - ${changes.removes})`)
} else if (changes.adds > 0) {
// Pure addition
if (place === 1 && changes.adds >= 5) {
// Five complement in ones place
const earthValue = changes.adds % 5
if (earthValue > 0) {
decompositionTerms.push(`(5 - ${5 - earthValue})`)
} else {
decompositionTerms.push(`${changes.adds}`)
}
} else {
decompositionTerms.push(`${changes.adds}`)
}
} else if (changes.removes > 0) {
// Pure subtraction
decompositionTerms.push(`-${changes.removes}`)
}
}
// If we have decomposition terms, format them properly
if (decompositionTerms.length > 0) {
const compactMath = decompositionTerms.join(' + ').replace('+ -', '- ')
return {
addTerm: value,
subtractTerm: 0,
compactMath,
isRecursive: false,
decompositionTerms,
}
}
}
// Fallback: Break down by place value without context
const decompositionTerms: string[] = []
let remainingValue = value
const placeValues = [100, 10, 1]
for (const placeValue of placeValues) {
if (remainingValue >= placeValue) {
const digitNeeded = Math.floor(remainingValue / placeValue)
remainingValue = remainingValue % placeValue
decompositionTerms.push(`${digitNeeded * placeValue}`)
}
}
// If we have decomposition terms, format them properly
if (decompositionTerms.length > 0) {
const compactMath = decompositionTerms.join(' + ')
// For simple single complement operations, return in the expected format
if (
decompositionTerms.length === 1 &&
decompositionTerms[0].includes('(') &&
decompositionTerms[0].includes(' - ')
) {
const match = decompositionTerms[0].match(/\((\d+) - (\d+)\)/)
if (match) {
return {
addTerm: parseInt(match[1], 10),
subtractTerm: parseInt(match[2], 10),
compactMath: decompositionTerms[0],
isRecursive: false,
decompositionTerms,
}
}
}
return {
addTerm: value, // For multi-term decompositions, addTerm represents the total
subtractTerm: 0,
compactMath,
isRecursive: false,
decompositionTerms,
}
}
// Fallback: use simple complement for small values
if (value <= 4) {
return {
addTerm: 5,
subtractTerm: 5 - value,
compactMath: `(5 - ${5 - value})`,
isRecursive: false,
decompositionTerms: [`(5 - ${5 - value})`],
}
}
return null
}
// Generate recursive complement description for complex multi-place operations
function _generateRecursiveComplementDescription(
startValue: number,
targetValue: number,
_additions: BeadHighlight[],
_removals: BeadHighlight[]
): string {
const difference = targetValue - startValue
// Simulate the abacus addition step by step
const steps: string[] = []
let carry = 0
// Process each digit from ones to hundreds
for (let place = 0; place <= 2; place++) {
const placeValue = 10 ** place
const placeName = place === 0 ? 'ones' : place === 1 ? 'tens' : 'hundreds'
const startDigit = Math.floor(startValue / placeValue) % 10
const addDigit = Math.floor(difference / placeValue) % 10
const totalNeeded = startDigit + addDigit + carry
if (totalNeeded === 0) {
carry = 0
continue
}
if (totalNeeded >= 10) {
// Need complement in this place
const finalDigit = totalNeeded % 10
const newCarry = Math.floor(totalNeeded / 10)
if (place === 0 && addDigit > 0) {
// Ones place - show the actual complement operation
const complement = 10 - addDigit
steps.push(`${placeName}: ${addDigit} = 10 - ${complement} (complement creates carry)`)
} else if (place > 0) {
// Higher places - show the carry logic
if (addDigit > 0 && carry > 0) {
steps.push(
`${placeName}: ${addDigit} + ${carry} carry = ${totalNeeded} = 10 - ${10 - finalDigit} (complement creates carry)`
)
} else if (carry > 0) {
steps.push(`${placeName}: ${carry} carry creates complement`)
}
}
carry = newCarry
} else if (totalNeeded > 0) {
// Direct addition
if (addDigit > 0 && carry > 0) {
steps.push(`${placeName}: ${addDigit} + ${carry} carry = ${totalNeeded}`)
} else if (addDigit > 0) {
steps.push(`${placeName}: add ${addDigit}`)
} else if (carry > 0) {
steps.push(`${placeName}: ${carry} carry`)
}
carry = 0
}
}
const breakdown = steps.join(', ')
return `${startValue} + ${difference} requires complements: ${breakdown}, giving us ${targetValue}`
}
// Generate comprehensive complement description for multi-place operations
function _generateMultiPlaceComplementDescription(
startValue: number,
targetValue: number,
additions: BeadHighlight[],
removals: BeadHighlight[]
): string {
const difference = targetValue - startValue
// For simple five complement
if (difference <= 4 && startValue < 10 && targetValue < 10) {
return `if ${difference} = 5 - ${5 - difference}, then ${startValue} + ${difference} = ${startValue} + (5 - ${5 - difference}) = ${targetValue}`
}
// For multi-place operations, analyze what's happening in each place
const explanations: string[] = []
// Group movements by place value
const placeMovements: { [place: number]: { adds: number; removes: number } } = {}
additions.forEach((bead) => {
if (!placeMovements[bead.placeValue]) placeMovements[bead.placeValue] = { adds: 0, removes: 0 }
placeMovements[bead.placeValue].adds++
})
removals.forEach((bead) => {
if (!placeMovements[bead.placeValue]) placeMovements[bead.placeValue] = { adds: 0, removes: 0 }
placeMovements[bead.placeValue].removes++
})
// Analyze each place value to understand the complement logic
Object.keys(placeMovements)
.sort((a, b) => parseInt(b, 10) - parseInt(a, 10))
.forEach((placeStr) => {
const place = parseInt(placeStr, 10)
const movement = placeMovements[place]
const placeName =
place === 0 ? 'ones' : place === 1 ? 'tens' : place === 2 ? 'hundreds' : `place ${place}`
if (movement.adds > 0 && movement.removes === 0) {
// Pure addition - explain why we need this place
if (place >= 2) {
explanations.push(
`hundreds place needed because we cross from ${Math.floor(startValue / 100) * 100 + 99} to ${Math.floor(targetValue / 100) * 100}`
)
} else if (place === 1) {
explanations.push(`tens carry from complement operation`)
}
} else if (movement.adds > 0 && movement.removes > 0) {
// Complement operation in this place
const complement = movement.removes
const net = movement.adds - movement.removes
if (net > 0) {
explanations.push(`${placeName}: ${net + complement} = 10 - ${10 - (net + complement)}`)
}
}
})
// For the ones place complement, always include the traditional explanation
const onesMovement = placeMovements[0]
if (onesMovement && onesMovement.removes > 0) {
const onesDigitTarget = difference % 10
if (onesDigitTarget > 0) {
const complement = onesMovement.removes
explanations.push(`ones: ${onesDigitTarget} = 10 - ${complement}`)
}
}
// Build final explanation
if (explanations.length > 0) {
const breakdown = explanations.join(', ')
return `${startValue} + ${difference} requires complements: ${breakdown}, giving us ${targetValue}`
}
// Fallback for simple ten complement
const targetDifference = difference % 10
const complement = 10 - targetDifference
return `if ${targetDifference} = 10 - ${complement}, then ${startValue} + ${targetDifference} = ${startValue} + (10 - ${complement}) = ${startValue + targetDifference}`
}
// Generate traditional abacus complement description
function generateComplementDescription(
startValue: number,
_targetValue: number,
difference: number,
complementType: 'five' | 'ten',
_addValue: number,
_subtractValue: number
): string {
// Use the same logic as generateProperComplementDescription for consistency
const decomposition = findOptimalDecomposition(difference, { startValue })
if (decomposition) {
const { addTerm, subtractTerm, compactMath, isRecursive } = decomposition
if (isRecursive) {
// For recursive cases like 99 + 1, provide the full breakdown
return `if ${difference} = ${compactMath.replace(/[()]/g, '')}, then ${startValue} + ${difference} = ${startValue} + ${compactMath}`
} else {
// For simple complement cases
return `if ${difference} = ${addTerm} - ${subtractTerm}, then ${startValue} + ${difference} = ${startValue} + (${addTerm} - ${subtractTerm})`
}
}
// Fallback to old logic if no decomposition found
if (complementType === 'five') {
return `if ${difference} = 5 - ${5 - difference}, then ${startValue} + ${difference} = ${startValue} + (5 - ${5 - difference})`
} else {
const targetDifference = difference % 10
const complement = 10 - targetDifference
return `if ${targetDifference} = 10 - ${complement}, then ${startValue} + ${targetDifference} = ${startValue} + (10 - ${complement})`
}
}
// Detect if a complement operation is needed
export function detectComplementOperation(
startValue: number,
targetValue: number,
placeValue: number
): {
needsComplement: boolean
complementType: 'five' | 'ten' | 'none'
complementDetails?: {
addValue: number
subtractValue: number
description: string
}
} {
const difference = targetValue - startValue
// Ten complement detection (carrying to next place) - check this FIRST
if (difference > 0) {
// Check if we're crossing a multiple of 10 boundary
const startDigit = startValue % 10
const _targetDigit = targetValue % 10
// If we go from single digits to teens, or cross any 10s boundary with insufficient space
if (
(startValue < 10 && targetValue >= 10) ||
(startDigit + difference > 9 && Math.floor(startValue / 10) !== Math.floor(targetValue / 10))
) {
const addValue = 10
const subtractValue = 10 - (difference % 10)
return {
needsComplement: true,
complementType: 'ten',
complementDetails: {
addValue,
subtractValue,
description: generateComplementDescription(
startValue,
targetValue,
difference,
'ten',
addValue,
subtractValue
),
},
}
}
}
// Five complement detection (within same place)
if (placeValue === 0 && difference > 0) {
const startDigit = startValue % 10
const earthSpaceAvailable = 4 - (startDigit >= 5 ? startDigit - 5 : startDigit)
if (difference > earthSpaceAvailable && difference <= 4 && targetValue < 10) {
const addValue = 5
const subtractValue = 5 - difference
return {
needsComplement: true,
complementType: 'five',
complementDetails: {
addValue,
subtractValue,
description: generateComplementDescription(
startValue,
targetValue,
difference,
'five',
addValue,
subtractValue
),
},
}
}
}
return { needsComplement: false, complementType: 'none' }
}
// Generate step-by-step instructions
export function generateStepInstructions(
additions: BeadHighlight[],
removals: BeadHighlight[],
isComplement: boolean
): string[] {
const instructions: string[] = []
if (isComplement) {
// For complement operations, order matters: additions first, then removals
additions.forEach((bead) => {
const placeDesc =
bead.placeValue === 0
? 'ones'
: bead.placeValue === 1
? 'tens'
: bead.placeValue === 2
? 'hundreds'
: `place ${bead.placeValue}`
if (bead.beadType === 'heaven') {
instructions.push(`Click the heaven bead in the ${placeDesc} column to add it`)
} else {
instructions.push(
`Click earth bead ${bead.position! + 1} in the ${placeDesc} column to add it`
)
}
})
removals.forEach((bead) => {
const placeDesc =
bead.placeValue === 0
? 'ones'
: bead.placeValue === 1
? 'tens'
: bead.placeValue === 2
? 'hundreds'
: `place ${bead.placeValue}`
if (bead.beadType === 'heaven') {
instructions.push(`Click the heaven bead in the ${placeDesc} column to remove it`)
} else {
instructions.push(
`Click earth bead ${bead.position! + 1} in the ${placeDesc} column to remove it`
)
}
})
} else {
// For non-complement operations, handle both additions and removals
additions.forEach((bead) => {
const placeDesc =
bead.placeValue === 0
? 'ones'
: bead.placeValue === 1
? 'tens'
: bead.placeValue === 2
? 'hundreds'
: `place ${bead.placeValue}`
if (bead.beadType === 'heaven') {
instructions.push(`Click the heaven bead in the ${placeDesc} column to add it`)
} else {
instructions.push(
`Click earth bead ${bead.position! + 1} in the ${placeDesc} column to add it`
)
}
})
removals.forEach((bead) => {
const placeDesc =
bead.placeValue === 0
? 'ones'
: bead.placeValue === 1
? 'tens'
: bead.placeValue === 2
? 'hundreds'
: `place ${bead.placeValue}`
if (bead.beadType === 'heaven') {
instructions.push(`Click the heaven bead in the ${placeDesc} column to remove it`)
} else {
instructions.push(
`Click earth bead ${bead.position! + 1} in the ${placeDesc} column to remove it`
)
}
})
}
// Always return at least one instruction, even if empty
if (instructions.length === 0) {
instructions.push('No bead movements required')
}
return instructions
}
// Main function to generate complete instructions
export function generateAbacusInstructions(
startValue: number,
targetValue: number,
operation?: string
): GeneratedInstruction {
const startState = numberToAbacusState(startValue)
const targetState = numberToAbacusState(targetValue)
const { additions, removals, placeValue } = calculateBeadChanges(startState, targetState)
const complement = detectComplementOperation(startValue, targetValue, placeValue)
const difference = targetValue - startValue
const isAddition = difference > 0
const operationSymbol = isAddition ? '+' : '-'
const operationWord = isAddition ? 'add' : 'subtract'
const _actualOperation = operation || `${startValue} ${operationSymbol} ${Math.abs(difference)}`
// Always calculate the correct operation for the hint message, regardless of passed operation
const correctOperation = `${startValue} ${operationSymbol} ${Math.abs(difference)}`
// Combine all beads that need to be highlighted
const allHighlights = [...additions, ...removals]
// Handle zero difference case
if (difference === 0) {
return {
highlightBeads: [],
expectedAction: 'add',
actionDescription: 'No change needed - already at target value',
tooltip: {
content: 'No Operation Required',
explanation: 'The abacus already shows the target value',
},
errorMessages: {
wrongBead: 'No beads need to be moved',
wrongAction: 'No action required',
hint: `${startValue} is already at the target value`,
},
}
}
// Determine action type
const actionType = allHighlights.length === 1 ? (isAddition ? 'add' : 'remove') : 'multi-step'
// Generate action description
let actionDescription: string
let stepInstructions: string[]
let decomposition: any = null
let stepBeadMapping: StepBeadHighlight[] | undefined
// Check if this is a complex multi-place operation requiring comprehensive explanation
const hasMultiplePlaces = new Set(allHighlights.map((bead) => bead.placeValue)).size > 1
const hasComplementMovements = additions.length > 0 && removals.length > 0
const crossesHundreds = Math.floor(startValue / 100) !== Math.floor(targetValue / 100)
if (hasMultiplePlaces && hasComplementMovements && crossesHundreds) {
// Use proper complement breakdown for complex operations
const result = generateProperComplementDescription(startValue, targetValue, additions, removals)
actionDescription = result.description
decomposition = result.decomposition
// First generate step bead mapping to understand step groupings
const tempStepInstructions = generateStepInstructions(additions, removals, false)
stepBeadMapping = generateStepBeadMapping(
startValue,
targetValue,
additions,
removals,
decomposition,
tempStepInstructions
)
// Then generate enhanced instructions based on step groupings
stepInstructions = generateEnhancedStepInstructions(
startValue,
targetValue,
additions,
removals,
decomposition,
stepBeadMapping
)
} else if (complement.needsComplement) {
// Use proper complement breakdown for simple operations too
const result = generateProperComplementDescription(startValue, targetValue, additions, removals)
actionDescription = result.description
decomposition = result.decomposition
// First generate step bead mapping to understand step groupings
const tempStepInstructions = generateStepInstructions(additions, removals, false)
stepBeadMapping = generateStepBeadMapping(
startValue,
targetValue,
additions,
removals,
decomposition,
tempStepInstructions
)
// Then generate enhanced instructions based on step groupings
stepInstructions = generateEnhancedStepInstructions(
startValue,
targetValue,
additions,
removals,
decomposition,
stepBeadMapping
)
} else if (additions.length === 1 && removals.length === 0) {
const bead = additions[0]
actionDescription = `Click the ${bead.beadType} bead to ${operationWord} ${Math.abs(difference)}`
stepInstructions = generateStepInstructions(additions, removals, false)
} else if (additions.length > 1 && removals.length === 0) {
actionDescription = `Click ${additions.length} beads to ${operationWord} ${Math.abs(difference)}`
stepInstructions = generateStepInstructions(additions, removals, false)
} else {
actionDescription = `Multi-step operation: ${operationWord} ${Math.abs(difference)}`
stepInstructions = generateStepInstructions(additions, removals, complement.needsComplement)
}
// Generate tooltip
const tooltip = {
content: complement.needsComplement
? `${complement.complementType === 'five' ? 'Five' : 'Ten'} Complement Operation`
: `Direct ${isAddition ? 'Addition' : 'Subtraction'}`,
explanation: complement.needsComplement
? `When direct ${operationWord} isn't possible, use complement: ${complement.complementDetails!.description}`
: `${isAddition ? 'Add' : 'Remove'} beads directly to represent ${Math.abs(difference)}`,
}
// Generate error messages
const errorMessages = {
wrongBead: complement.needsComplement
? 'Follow the complement sequence: ' +
(additions.length > 0 ? 'add first, then remove' : 'use the highlighted beads')
: `Click the highlighted ${allHighlights.length === 1 ? 'bead' : 'beads'}`,
wrongAction: complement.needsComplement
? `Use ${complement.complementType} complement method`
: `${isAddition ? 'Move beads UP to add' : 'Move beads DOWN to remove'}`,
hint:
`${correctOperation} = ${targetValue}` +
(complement.needsComplement ? `, using ${complement.complementDetails!.description}` : ''),
}
// Generate step-by-step bead mapping for ALL instructions (both single and multi-step)
const stepBeadHighlights =
stepBeadMapping ||
(stepInstructions && stepInstructions.length > 0
? generateStepBeadMapping(
startValue,
targetValue,
additions,
removals,
decomposition,
stepInstructions
)
: undefined)
return {
highlightBeads: allHighlights,
expectedAction: actionType,
actionDescription,
multiStepInstructions: actionType === 'multi-step' ? stepInstructions : undefined,
stepBeadHighlights,
totalSteps: stepInstructions ? stepInstructions.length : undefined,
tooltip,
errorMessages,
}
}
// Utility function to validate generated instructions
export function validateInstruction(
instruction: GeneratedInstruction,
startValue: number,
targetValue: number
): {
isValid: boolean
issues: string[]
} {
const issues: string[] = []
// Check if highlights exist (only if values are different)
if (
startValue !== targetValue &&
(!instruction.highlightBeads || instruction.highlightBeads.length === 0)
) {
issues.push('No beads highlighted for non-zero operation')
}
// Check for multi-step consistency
if (instruction.expectedAction === 'multi-step' && !instruction.multiStepInstructions) {
issues.push('Multi-step action without step instructions')
}
// Check place value validity
instruction.highlightBeads.forEach((bead) => {
if (bead.placeValue < 0 || bead.placeValue > 4) {
issues.push(`Invalid place value: ${bead.placeValue}`)
}
if (
bead.beadType === 'earth' &&
(bead.position === undefined || bead.position < 0 || bead.position > 3)
) {
issues.push(`Invalid earth bead position: ${bead.position}`)
}
})
return {
isValid: issues.length === 0,
issues,
}
}
// Example usage and testing
export function testInstructionGenerator(): void {
console.log('๐งช Testing Automatic Instruction Generator\n')
const testCases = [
{ start: 0, target: 1, description: 'Basic addition' },
{ start: 0, target: 5, description: 'Heaven bead introduction' },
{ start: 3, target: 7, description: 'Five complement (3+4)' },
{ start: 2, target: 5, description: 'Five complement (2+3)' },
{ start: 6, target: 8, description: 'Direct addition' },
{ start: 7, target: 11, description: 'Ten complement' },
{ start: 5, target: 2, description: 'Subtraction' },
{ start: 12, target: 25, description: 'Multi-place operation' },
]
testCases.forEach(({ start, target, description }, index) => {
console.log(`\n${index + 1}. ${description}: ${start} โ ${target}`)
const instruction = generateAbacusInstructions(start, target)
console.log(` Action: ${instruction.actionDescription}`)
console.log(` Highlights: ${instruction.highlightBeads.length} beads`)
console.log(` Type: ${instruction.expectedAction}`)
if (instruction.multiStepInstructions) {
console.log(` Steps: ${instruction.multiStepInstructions.length}`)
}
const validation = validateInstruction(instruction, start, target)
console.log(` Valid: ${validation.isValid ? 'โ
' : 'โ'}`)
if (!validation.isValid) {
console.log(` Issues: ${validation.issues.join(', ')}`)
}
})
}
|