-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgo-script.js
More file actions
1529 lines (1232 loc) · 49 KB
/
Copy pathalgo-script.js
File metadata and controls
1529 lines (1232 loc) · 49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const CANVAS_WIDTH = 900;
const CANVAS_HEIGHT = 440;
const COLORS = {
background: "#0a0a18",
defaultBar: "#00f5ff",
comparing: "#f5a623",
swapping: "#ff3860",
sorted: "#00ff88",
current: "#00f5ff",
minimum: "#bf5fff",
shifting: "#f5a623",
queueBox: "#111120",
queueActive: "#00ff88",
queueRemove: "#ff3860",
queueWrap: "#bf5fff",
stackBox: "#111120",
stackPush: "#00ff88",
stackPop: "#ff3860",
stackTop: "#00f5ff",
nodeBox: "#111120",
nodeVisit: "#00f5ff",
nodeNew: "#00ff88",
nodeDelete: "#ff3860",
arrow: "#8c90aa",
treeNode: "#111120",
treeVisit: "#f5a623",
treeFound: "#00ff88",
treeNew: "#00ff88",
treeEdge: "#8c90aa",
gridEmpty: "#111120",
gridWall: "#05050c",
gridStart: "#00ff88",
gridEnd: "#ff3860",
gridExplore: "#00f5ff",
gridPath: "#f5ff00",
text: "#f4f7fb",
muted: "#8c90aa",
grid: "#1e1e35"
};
const SPEEDS = {
slow: 1000,
medium: 200,
fast: 50
};
const CATEGORY_ALGORITHMS = {
SORTING: [
{ label: "Bubble Sort", value: "bubbleSort" },
{ label: "Selection Sort", value: "selectionSort" },
{ label: "Insertion Sort", value: "insertionSort" }
],
QUEUE: [
{ label: "Circular Queue", value: "circularQueue" }
],
STACK: [
{ label: "Stack Push / Pop", value: "stackPushPop" }
],
LINKED_LIST: [
{ label: "Linked List Demo", value: "linkedListDemo" }
],
BINARY_TREE: [
{ label: "BST Insert", value: "bstInsert" },
{ label: "BST Search", value: "bstSearch" },
{ label: "In-order", value: "inOrderTraversal" },
{ label: "Pre-order", value: "preOrderTraversal" },
{ label: "Post-order", value: "postOrderTraversal" }
],
PATHFINDING: [
{ label: "BFS Grid", value: "bfsGrid" }
]
};
const ALGORITHM_INFO = {
bubbleSort: {
name: "Bubble Sort",
title: "Bubble Sort Recorder",
subtitle: "Compare nearby values, swap when needed, and watch the largest values move right.",
time: "Time: O(n^2)",
space: "Space: O(1)",
description: "Bubble Sort compares nearby values. Bigger values slowly move right, like bubbles rising to the top."
},
selectionSort: {
name: "Selection Sort",
title: "Selection Sort Scanner",
subtitle: "Scan the unsorted area, find the smallest value, then place it in the correct position.",
time: "Time: O(n^2)",
space: "Space: O(1)",
description: "Selection Sort repeatedly searches for the smallest value. It then swaps that value into the next sorted position."
},
insertionSort: {
name: "Insertion Sort",
title: "Insertion Sort Builder",
subtitle: "Take one value at a time and insert it into the already sorted left side.",
time: "Time: O(n^2)",
space: "Space: O(1)",
description: "Insertion Sort builds a sorted section from left to right. Each new value shifts bigger values until it fits."
},
circularQueue: {
name: "Circular Queue",
title: "Circular Queue Simulator",
subtitle: "Watch front and rear pointers move through a fixed-size queue and wrap around.",
time: "Time: O(1)",
space: "Space: O(n)",
description: "A circular queue uses a fixed-size array. Rear wraps back to the start when it reaches the end, so empty spaces can be reused."
},
stackPushPop: {
name: "Stack Push / Pop",
title: "Stack Push / Pop Simulator",
subtitle: "Watch values enter and leave from the top of a vertical stack.",
time: "Time: O(1)",
space: "Space: O(n)",
description: "A stack follows Last In, First Out. The newest value added to the top is always the first value removed."
},
linkedListDemo: {
name: "Linked List Demo",
title: "Linked List Pointer Visualizer",
subtitle: "Watch nodes connect through arrows while insert, search, and delete operations run.",
time: "Time: O(n)",
space: "Space: O(n)",
description: "A linked list stores values in separate nodes. Each node points to the next node instead of sitting beside it in an array."
},
bstInsert: {
name: "BST Insert",
title: "Binary Search Tree Insert",
subtitle: "Watch values move left or right until they find the correct empty position.",
time: "Time: O(log n) avg",
space: "Space: O(n)",
description: "A Binary Search Tree places smaller values on the left and larger values on the right. Insert follows comparisons until it finds an empty spot."
},
bstSearch: {
name: "BST Search",
title: "Binary Search Tree Search",
subtitle: "Search moves left or right based on comparison with the current node.",
time: "Time: O(log n) avg",
space: "Space: O(1)",
description: "BST search skips large parts of the tree by comparing values. If the target is smaller, go left; if larger, go right."
},
inOrderTraversal: {
name: "In-order Traversal",
title: "In-order Tree Traversal",
subtitle: "Visit left subtree, then root, then right subtree.",
time: "Time: O(n)",
space: "Space: O(h)",
description: "In-order traversal visits BST values in sorted order. It uses recursion to fully visit the left side before the current node."
},
preOrderTraversal: {
name: "Pre-order Traversal",
title: "Pre-order Tree Traversal",
subtitle: "Visit root first, then left subtree, then right subtree.",
time: "Time: O(n)",
space: "Space: O(h)",
description: "Pre-order traversal is useful when you want to process the current node before its children. It visits root, left, then right."
},
postOrderTraversal: {
name: "Post-order Traversal",
title: "Post-order Tree Traversal",
subtitle: "Visit left subtree, then right subtree, then root.",
time: "Time: O(n)",
space: "Space: O(h)",
description: "Post-order traversal processes children before the parent. It is commonly used when deleting or evaluating trees."
},
bfsGrid: {
name: "BFS Grid Pathfinding",
title: "Breadth-First Search Grid",
subtitle: "Explore cells level by level until the shortest path is found.",
time: "Time: O(V + E)",
space: "Space: O(V)",
description: "BFS uses a queue to explore nearby cells first. On an unweighted grid, it finds the shortest path from start to end."
}
};
const appState = {
activeCategory: "SORTING",
activeAlgorithm: "bubbleSort",
inputData: [34, 12, 45, 8, 67, 23],
steps: [],
currentStep: 0,
isPlaying: false,
speed: "medium",
playInterval: null
};
const gridState = {
rows: 10,
cols: 16,
startIndex: 17,
endIndex: 142,
walls: [35, 36, 37, 53, 69, 85, 101, 102, 103, 104],
editMode: "start"
};
const canvas = document.getElementById("algorithmCanvas");
const ctx = canvas.getContext("2d");
const playBtn = document.getElementById("playBtn");
const pauseBtn = document.getElementById("pauseBtn");
const stepBackBtn = document.getElementById("stepBackBtn");
const stepForwardBtn = document.getElementById("stepForwardBtn");
const resetBtn = document.getElementById("resetBtn");
const randomBtn = document.getElementById("randomBtn");
const applyDataBtn = document.getElementById("applyDataBtn");
const speedSelect = document.getElementById("speedSelect");
const dataInput = document.getElementById("dataInput");
const explanationText = document.getElementById("explanationText");
const stepCounter = document.getElementById("stepCounter");
const dataPills = document.getElementById("dataPills");
const inputError = document.getElementById("inputError");
const algorithmPills = document.getElementById("algorithmPills");
const algorithmTitle = document.getElementById("algorithmTitle");
const algorithmSubtitle = document.getElementById("algorithmSubtitle");
const infoName = document.getElementById("infoName");
const timeComplexity = document.getElementById("timeComplexity");
const spaceComplexity = document.getElementById("spaceComplexity");
const infoDescription = document.getElementById("infoDescription");
/* Sends the selected algorithm to its own step recorder. */
function generateSteps(algorithm, data) {
if (algorithm === "bubbleSort") return generateBubbleSortSteps(data);
if (algorithm === "selectionSort") return generateSelectionSortSteps(data);
if (algorithm === "insertionSort") return generateInsertionSortSteps(data);
if (algorithm === "circularQueue") return generateCircularQueueSteps(data);
if (algorithm === "stackPushPop") return generateStackSteps(data);
if (algorithm === "linkedListDemo") return generateLinkedListSteps(data);
if (algorithm === "bstInsert") return generateBstInsertSteps(data);
if (algorithm === "bstSearch") return generateBstSearchSteps(data);
if (algorithm === "inOrderTraversal") return generateTreeTraversalSteps(data, "inOrder");
if (algorithm === "preOrderTraversal") return generateTreeTraversalSteps(data, "preOrder");
if (algorithm === "postOrderTraversal") return generateTreeTraversalSteps(data, "postOrder");
if (algorithm === "bfsGrid") return generateBfsSteps();
return [];
}
/* Records Bubble Sort comparison and swap steps. */
function generateBubbleSortSteps(data) {
const recordedSteps = [];
const workingData = [...data];
const sortedIndexes = [];
recordedSteps.push(createBarStep(workingData, [], [], [], null, null, [], "Starting Bubble Sort."));
for (let passIndex = 0; passIndex < workingData.length - 1; passIndex++) {
for (let compareIndex = 0; compareIndex < workingData.length - passIndex - 1; compareIndex++) {
const leftValue = workingData[compareIndex];
const rightValue = workingData[compareIndex + 1];
recordedSteps.push(createBarStep(workingData, [compareIndex, compareIndex + 1], [], sortedIndexes, null, null, [], `Comparing ${leftValue} and ${rightValue}.`));
if (leftValue > rightValue) {
workingData[compareIndex] = rightValue;
workingData[compareIndex + 1] = leftValue;
recordedSteps.push(createBarStep(workingData, [], [compareIndex, compareIndex + 1], sortedIndexes, null, null, [], `${leftValue} is greater than ${rightValue}, so we swap them.`));
}
}
const sortedIndex = workingData.length - 1 - passIndex;
sortedIndexes.push(sortedIndex);
recordedSteps.push(createBarStep(workingData, [], [], sortedIndexes, null, null, [], `${workingData[sortedIndex]} is locked into position.`));
}
sortedIndexes.push(0);
recordedSteps.push(createBarStep(workingData, [], [], sortedIndexes, null, null, [], "Bubble Sort is complete."));
return recordedSteps;
}
/* Records Selection Sort scan and swap steps. */
function generateSelectionSortSteps(data) {
const recordedSteps = [];
const workingData = [...data];
const sortedIndexes = [];
recordedSteps.push(createBarStep(workingData, [], [], [], null, null, [], "Starting Selection Sort."));
for (let startIndex = 0; startIndex < workingData.length - 1; startIndex++) {
let minimumIndex = startIndex;
recordedSteps.push(createBarStep(workingData, [], [], sortedIndexes, minimumIndex, startIndex, [], `Assume ${workingData[minimumIndex]} is the smallest value.`));
for (let scanIndex = startIndex + 1; scanIndex < workingData.length; scanIndex++) {
recordedSteps.push(createBarStep(workingData, [minimumIndex, scanIndex], [], sortedIndexes, minimumIndex, scanIndex, [], `Comparing ${workingData[minimumIndex]} with ${workingData[scanIndex]}.`));
if (workingData[scanIndex] < workingData[minimumIndex]) {
minimumIndex = scanIndex;
recordedSteps.push(createBarStep(workingData, [], [], sortedIndexes, minimumIndex, scanIndex, [], `${workingData[minimumIndex]} is the new smallest value.`));
}
}
const temp = workingData[startIndex];
workingData[startIndex] = workingData[minimumIndex];
workingData[minimumIndex] = temp;
recordedSteps.push(createBarStep(workingData, [], [startIndex, minimumIndex], sortedIndexes, null, null, [], "Swap the smallest value into the sorted position."));
sortedIndexes.push(startIndex);
recordedSteps.push(createBarStep(workingData, [], [], sortedIndexes, null, null, [], `${workingData[startIndex]} is now sorted.`));
}
sortedIndexes.push(workingData.length - 1);
recordedSteps.push(createBarStep(workingData, [], [], sortedIndexes, null, null, [], "Selection Sort is complete."));
return recordedSteps;
}
/* Records Insertion Sort shift and insert steps. */
function generateInsertionSortSteps(data) {
const recordedSteps = [];
const workingData = [...data];
recordedSteps.push(createBarStep(workingData, [], [], [0], null, 0, [], "Starting Insertion Sort."));
for (let currentIndex = 1; currentIndex < workingData.length; currentIndex++) {
const currentValue = workingData[currentIndex];
let compareIndex = currentIndex - 1;
recordedSteps.push(createBarStep(workingData, [], [], getRangeIndexes(0, currentIndex - 1), null, currentIndex, [], `Pick up ${currentValue}.`));
while (compareIndex >= 0 && workingData[compareIndex] > currentValue) {
recordedSteps.push(createBarStep(workingData, [compareIndex, compareIndex + 1], [], getRangeIndexes(0, currentIndex - 1), null, compareIndex + 1, [compareIndex], `${workingData[compareIndex]} shifts right.`));
workingData[compareIndex + 1] = workingData[compareIndex];
compareIndex--;
}
workingData[compareIndex + 1] = currentValue;
recordedSteps.push(createBarStep(workingData, [], [compareIndex + 1], getRangeIndexes(0, currentIndex), null, compareIndex + 1, [], `${currentValue} is inserted into place.`));
}
recordedSteps.push(createBarStep(workingData, [], [], getRangeIndexes(0, workingData.length - 1), null, null, [], "Insertion Sort is complete."));
return recordedSteps;
}
/* Creates one reusable sorting snapshot object. */
function createBarStep(array, comparing, swapping, sortedIndexes, minimumIndex, currentIndex, shifting, explanation) {
return {
type: "bars",
array: [...array],
comparing: [...comparing],
swapping: [...swapping],
sortedIndexes: [...sortedIndexes],
minimumIndex,
currentIndex,
shifting: [...shifting],
explanation
};
}
/* Records Circular Queue steps. */
function generateCircularQueueSteps(data) {
const capacity = 6;
const queue = new Array(capacity).fill(null);
const recordedSteps = [];
let front = -1;
let rear = -1;
let size = 0;
recordedSteps.push(createQueueStep(queue, front, rear, null, null, null, "Starting Circular Queue."));
for (let index = 0; index < Math.min(data.length, capacity); index++) {
if (size === 0) {
front = 0;
rear = 0;
} else {
rear = (rear + 1) % capacity;
}
queue[rear] = data[index];
size++;
recordedSteps.push(createQueueStep(queue, front, rear, rear, null, rear === 0 && size > 1 ? rear : null, `Enqueue ${data[index]} at the rear.`));
}
for (let count = 0; count < 2; count++) {
const removedValue = queue[front];
recordedSteps.push(createQueueStep(queue, front, rear, null, front, null, `Dequeue ${removedValue} from the front.`));
queue[front] = null;
size--;
front = size === 0 ? -1 : (front + 1) % capacity;
recordedSteps.push(createQueueStep(queue, front, rear, front, null, null, "Front moves to the next item."));
}
const extraValues = [77, 88];
for (let index = 0; index < extraValues.length; index++) {
rear = (rear + 1) % capacity;
queue[rear] = extraValues[index];
recordedSteps.push(createQueueStep(queue, front, rear, rear, null, rear === 0 ? rear : null, `Enqueue ${extraValues[index]}. Rear may wrap around.`));
}
recordedSteps.push(createQueueStep(queue, front, rear, null, null, null, "Circular Queue demo complete."));
return recordedSteps;
}
/* Creates one reusable queue snapshot object. */
function createQueueStep(queue, front, rear, activeIndex, removeIndex, wrapIndex, explanation) {
return {
type: "queue",
queue: [...queue],
front,
rear,
activeIndex,
removeIndex,
wrapIndex,
explanation
};
}
/* Records Stack push and pop steps. */
function generateStackSteps(data) {
const capacity = 6;
const stack = [];
const recordedSteps = [];
recordedSteps.push(createStackStep(stack, capacity, null, null, "", "Starting Stack."));
for (let index = 0; index < Math.min(data.length, capacity); index++) {
stack.push(data[index]);
recordedSteps.push(createStackStep(stack, capacity, stack.length - 1, null, "", `Push ${data[index]} on top.`));
}
recordedSteps.push(createStackStep(stack, capacity, null, null, "Stack overflow warning: capacity is full.", "The stack is full."));
for (let count = 0; count < 2; count++) {
const topIndex = stack.length - 1;
const removedValue = stack[topIndex];
recordedSteps.push(createStackStep(stack, capacity, null, topIndex, "", `Pop ${removedValue} from the top.`));
stack.pop();
recordedSteps.push(createStackStep(stack, capacity, stack.length - 1, null, "", "The top pointer moves down."));
}
recordedSteps.push(createStackStep(stack, capacity, null, null, "", "Stack demo complete."));
return recordedSteps;
}
/* Creates one reusable stack snapshot object. */
function createStackStep(stack, capacity, activeIndex, removeIndex, warning, explanation) {
return {
type: "stack",
stack: [...stack],
capacity,
activeIndex,
removeIndex,
warning,
explanation
};
}
/* Records linked list insert, search, and delete steps. */
function generateLinkedListSteps(data) {
const recordedSteps = [];
let nodes = [];
recordedSteps.push(createLinkedListStep(nodes, null, null, null, "Starting Linked List. Head is null because the list is empty."));
const headValue = data[0] ?? 34;
nodes.unshift({ id: createNodeId(), value: headValue });
recordedSteps.push(createLinkedListStep(nodes, 0, 0, null, `Insert ${headValue} at head. The new node becomes the first node.`));
const tailValues = data.slice(1, 5);
for (let index = 0; index < tailValues.length; index++) {
const newValue = tailValues[index];
recordedSteps.push(createLinkedListStep(nodes, nodes.length - 1, null, null, `Move to the current tail node ${nodes[nodes.length - 1].value}.`));
nodes.push({ id: createNodeId(), value: newValue });
recordedSteps.push(createLinkedListStep(nodes, nodes.length - 1, nodes.length - 1, null, `Insert ${newValue} at tail. The previous tail now points to this new node.`));
}
const searchValue = nodes[Math.min(2, nodes.length - 1)].value;
for (let index = 0; index < nodes.length; index++) {
recordedSteps.push(createLinkedListStep(nodes, index, null, null, `Searching for ${searchValue}. Visiting node with value ${nodes[index].value}.`));
if (nodes[index].value === searchValue) {
recordedSteps.push(createLinkedListStep(nodes, index, null, null, `Found ${searchValue}. Search stops here.`));
break;
}
}
const deleteIndex = Math.min(2, nodes.length - 1);
const deletedValue = nodes[deleteIndex].value;
recordedSteps.push(createLinkedListStep(nodes, deleteIndex, null, deleteIndex, `Delete node ${deletedValue}. First we highlight the node that will be removed.`));
nodes.splice(deleteIndex, 1);
recordedSteps.push(createLinkedListStep(nodes, deleteIndex < nodes.length ? deleteIndex : nodes.length - 1, null, null, `${deletedValue} is removed. The previous node now points to the next node.`));
recordedSteps.push(createLinkedListStep(nodes, null, null, null, "Linked List demo complete."));
return recordedSteps;
}
/* Creates one linked list snapshot object. */
function createLinkedListStep(nodes, visitIndex, newIndex, deleteIndex, explanation) {
return {
type: "linkedList",
nodes: nodes.map(node => ({ ...node })),
visitIndex,
newIndex,
deleteIndex,
explanation
};
}
/* Creates a simple unique id for linked list nodes. */
function createNodeId() {
return `node-${Date.now()}-${Math.random()}`;
}
/* Records BST insert comparisons and new node placement. */
function generateBstInsertSteps(data) {
const values = data.slice(0, 7);
const treeData = { root: null };
const recordedSteps = [];
recordedSteps.push(createTreeStep(null, [], null, null, "Starting BST insert. The tree is empty."));
for (let index = 0; index < values.length; index++) {
insertTreeValue(treeData, values[index], recordedSteps);
}
recordedSteps.push(createTreeStep(treeData.root, [], null, null, "BST insert demo complete. Smaller values went left, larger values went right."));
return recordedSteps;
}
/* Inserts one value into the BST while recording the path. */
function insertTreeValue(treeData, value, recordedSteps) {
if (!treeData.root) {
treeData.root = createTreeNode(value);
recordedSteps.push(createTreeStep(treeData.root, [], treeData.root.id, null, `${value} becomes the root node.`));
return;
}
let currentNode = treeData.root;
const pathIds = [];
while (currentNode) {
pathIds.push(currentNode.id);
recordedSteps.push(createTreeStep(treeData.root, [...pathIds], null, null, `Compare ${value} with ${currentNode.value}.`));
if (value < currentNode.value) {
if (!currentNode.left) {
currentNode.left = createTreeNode(value);
recordedSteps.push(createTreeStep(treeData.root, [...pathIds], currentNode.left.id, null, `${value} is smaller, so it is inserted on the left.`));
return;
}
currentNode = currentNode.left;
} else {
if (!currentNode.right) {
currentNode.right = createTreeNode(value);
recordedSteps.push(createTreeStep(treeData.root, [...pathIds], currentNode.right.id, null, `${value} is larger or equal, so it is inserted on the right.`));
return;
}
currentNode = currentNode.right;
}
}
}
/* Records BST search path for a target value. */
function generateBstSearchSteps(data) {
const values = data.slice(0, 7);
const treeData = { root: null };
const recordedSteps = [];
for (let index = 0; index < values.length; index++) {
insertTreeValueWithoutSteps(treeData, values[index]);
}
const targetValue = values[Math.min(3, values.length - 1)];
let currentNode = treeData.root;
const pathIds = [];
recordedSteps.push(createTreeStep(treeData.root, [], null, null, `Starting BST search for ${targetValue}.`));
while (currentNode) {
pathIds.push(currentNode.id);
recordedSteps.push(createTreeStep(treeData.root, [...pathIds], null, null, `Visiting ${currentNode.value}. Compare it with ${targetValue}.`));
if (currentNode.value === targetValue) {
recordedSteps.push(createTreeStep(treeData.root, [...pathIds], null, currentNode.id, `Found ${targetValue}. Search complete.`));
return recordedSteps;
}
if (targetValue < currentNode.value) {
currentNode = currentNode.left;
} else {
currentNode = currentNode.right;
}
}
recordedSteps.push(createTreeStep(treeData.root, pathIds, null, null, `${targetValue} was not found.`));
return recordedSteps;
}
/* Records in-order, pre-order, or post-order traversal steps. */
function generateTreeTraversalSteps(data, traversalType) {
const values = data.slice(0, 7);
const treeData = { root: null };
const recordedSteps = [];
const visitedIds = [];
for (let index = 0; index < values.length; index++) {
insertTreeValueWithoutSteps(treeData, values[index]);
}
recordedSteps.push(createTreeStep(treeData.root, [], null, null, `Starting ${traversalType} traversal.`));
traverseTree(treeData.root, traversalType, visitedIds, recordedSteps, treeData.root);
recordedSteps.push(createTreeStep(treeData.root, visitedIds, null, null, `${traversalType} traversal complete.`));
return recordedSteps;
}
/* Recursively visits tree nodes in the selected traversal order. */
function traverseTree(node, traversalType, visitedIds, recordedSteps, root) {
if (!node) return;
if (traversalType === "preOrder") {
visitedIds.push(node.id);
recordedSteps.push(createTreeStep(root, [...visitedIds], null, node.id, `Visit ${node.value} first, then move to its children.`));
}
traverseTree(node.left, traversalType, visitedIds, recordedSteps, root);
if (traversalType === "inOrder") {
visitedIds.push(node.id);
recordedSteps.push(createTreeStep(root, [...visitedIds], null, node.id, `Visit ${node.value} after its left subtree.`));
}
traverseTree(node.right, traversalType, visitedIds, recordedSteps, root);
if (traversalType === "postOrder") {
visitedIds.push(node.id);
recordedSteps.push(createTreeStep(root, [...visitedIds], null, node.id, `Visit ${node.value} after both children.`));
}
}
/* Inserts a value into the tree without recording steps. */
function insertTreeValueWithoutSteps(treeData, value) {
if (!treeData.root) {
treeData.root = createTreeNode(value);
return;
}
let currentNode = treeData.root;
while (currentNode) {
if (value < currentNode.value) {
if (!currentNode.left) {
currentNode.left = createTreeNode(value);
return;
}
currentNode = currentNode.left;
} else {
if (!currentNode.right) {
currentNode.right = createTreeNode(value);
return;
}
currentNode = currentNode.right;
}
}
}
/* Creates one tree node object. */
function createTreeNode(value) {
return {
id: `tree-${Date.now()}-${Math.random()}`,
value,
left: null,
right: null
};
}
/* Creates one reusable tree snapshot object. */
function createTreeStep(root, visitedIds, newNodeId, foundNodeId, explanation) {
return {
type: "tree",
root: cloneTree(root),
visitedIds: [...visitedIds],
newNodeId,
foundNodeId,
explanation
};
}
/* Copies the tree so old steps do not change later. */
function cloneTree(node) {
if (!node) return null;
return {
id: node.id,
value: node.value,
left: cloneTree(node.left),
right: cloneTree(node.right)
};
}
/* Records BFS exploration and final shortest path steps. */
function generateBfsSteps() {
const totalCells = gridState.rows * gridState.cols;
const visited = new Array(totalCells).fill(false);
const parent = new Array(totalCells).fill(null);
const queue = [gridState.startIndex];
const explored = [];
const recordedSteps = [];
visited[gridState.startIndex] = true;
recordedSteps.push(createGridStep([], [], gridState.startIndex, "Starting BFS. The start cell enters the queue first."));
while (queue.length > 0) {
const currentIndex = queue.shift();
explored.push(currentIndex);
recordedSteps.push(createGridStep([...explored], [], currentIndex, `Exploring cell ${currentIndex}. BFS checks its neighbours.`));
if (currentIndex === gridState.endIndex) {
const path = reconstructPath(parent, gridState.endIndex);
recordedSteps.push(createGridStep([...explored], path, currentIndex, "End found. Now we reconstruct the shortest path using parent links."));
return recordedSteps;
}
const neighbours = getGridNeighbours(currentIndex);
for (let index = 0; index < neighbours.length; index++) {
const neighbourIndex = neighbours[index];
if (!visited[neighbourIndex] && !gridState.walls.includes(neighbourIndex)) {
visited[neighbourIndex] = true;
parent[neighbourIndex] = currentIndex;
queue.push(neighbourIndex);
recordedSteps.push(createGridStep([...explored, neighbourIndex], [], neighbourIndex, `Cell ${neighbourIndex} is added to the queue. Its parent is cell ${currentIndex}.`));
}
}
}
recordedSteps.push(createGridStep([...explored], [], null, "No path found. The queue became empty before reaching the end."));
return recordedSteps;
}
/* Creates one reusable grid snapshot object. */
function createGridStep(explored, path, currentIndex, explanation) {
return {
type: "grid",
rows: gridState.rows,
cols: gridState.cols,
startIndex: gridState.startIndex,
endIndex: gridState.endIndex,
walls: [...gridState.walls],
explored: [...explored],
path: [...path],
currentIndex,
explanation
};
}
/* Gets valid up, down, left, and right neighbours for one cell. */
function getGridNeighbours(index) {
const neighbours = [];
const row = Math.floor(index / gridState.cols);
const col = index % gridState.cols;
const directions = [
{ row: -1, col: 0 },
{ row: 1, col: 0 },
{ row: 0, col: -1 },
{ row: 0, col: 1 }
];
for (let i = 0; i < directions.length; i++) {
const nextRow = row + directions[i].row;
const nextCol = col + directions[i].col;
if (nextRow >= 0 && nextRow < gridState.rows && nextCol >= 0 && nextCol < gridState.cols) {
neighbours.push(nextRow * gridState.cols + nextCol);
}
}
return neighbours;
}
/* Rebuilds the shortest path by walking parent links backward. */
function reconstructPath(parent, endIndex) {
const path = [];
let currentIndex = endIndex;
while (currentIndex !== null) {
path.unshift(currentIndex);
currentIndex = parent[currentIndex];
}
return path;
}
/* Creates a list of indexes from start to end. */
function getRangeIndexes(start, end) {
const indexes = [];
for (let index = start; index <= end; index++) {
indexes.push(index);
}
return indexes;
}
/* Renders the current recorded step and updates the UI text. */
function renderStep(step) {
if (!step) return;
if (step.type === "queue") {
drawQueue(step);
renderDataPills(step.queue);
} else if (step.type === "stack") {
drawStack(step);
renderDataPills(step.stack);
} else if (step.type === "linkedList") {
drawLinkedList(step);
renderDataPills(step.nodes.map(node => node.value));
} else if (step.type === "tree") {
drawTree(step);
renderDataPills(flattenTreeValues(step.root));
} else if (step.type === "grid") {
drawGrid(step);
renderDataPills(["START", "END", "WALLS", step.walls.length]);
} else {
drawBars(step);
renderDataPills(step.array);
}
explanationText.textContent = step.explanation;
const currentNumber = String(appState.currentStep).padStart(2, "0");
const totalNumber = String(appState.steps.length - 1).padStart(2, "0");
stepCounter.textContent = `Step ${currentNumber} / ${totalNumber}`;
}
/* Starts automatic playback using the selected speed. */
function play() {
pause();
appState.isPlaying = true;
appState.playInterval = setInterval(() => {
if (appState.currentStep >= appState.steps.length - 1) {
pause();
return;
}
stepForward();
}, SPEEDS[appState.speed]);
}
/* Stops automatic playback. */
function pause() {
appState.isPlaying = false;
if (appState.playInterval) {
clearInterval(appState.playInterval);
appState.playInterval = null;
}
}
/* Moves one recorded step forward. */
function stepForward() {
appState.currentStep = Math.min(appState.currentStep + 1, appState.steps.length - 1);
renderStep(appState.steps[appState.currentStep]);
}
/* Moves one recorded step backward. */
function stepBack() {
appState.currentStep = Math.max(appState.currentStep - 1, 0);
renderStep(appState.steps[appState.currentStep]);
}
/* Resets the visualizer back to the first recorded step. */
function reset() {
pause();
appState.currentStep = 0;
renderStep(appState.steps[appState.currentStep]);
}
/* Loads an algorithm and renders its first step. */
function loadAlgorithm(category, algorithm) {
pause();
appState.activeCategory = category;
appState.activeAlgorithm = algorithm;
appState.steps = generateSteps(algorithm, appState.inputData);
appState.currentStep = 0;
updateAlgorithmInfo();
updateActiveCategoryButton();
renderAlgorithmPills();
renderStep(appState.steps[appState.currentStep]);
}
/* Creates random numbers for the visualizer. */
function generateRandomData(size) {
const randomValues = [];
for (let index = 0; index < size; index++) {
randomValues.push(Math.floor(Math.random() * 95) + 5);
}
return randomValues;
}
/* Converts comma-separated text into numbers. */
function parseInputData(inputText) {
const textParts = inputText.split(",");
const parsedNumbers = [];
for (let index = 0; index < textParts.length; index++) {
const trimmedValue = textParts[index].trim();
const numberValue = Number(trimmedValue);
if (trimmedValue !== "" && !Number.isNaN(numberValue)) {
parsedNumbers.push(numberValue);
}
}
return parsedNumbers;
}
/* Validates custom data before rebuilding the visualizer. */
function applyCustomData() {
const parsedNumbers = parseInputData(dataInput.value);
if (parsedNumbers.length < 2) {
inputError.textContent = "Please enter at least 2 valid numbers.";
return;
}
if (parsedNumbers.length > 12) {
inputError.textContent = "Use 12 numbers or fewer so the Canvas stays readable.";
return;
}
inputError.textContent = "";
appState.inputData = parsedNumbers;
loadAlgorithm(appState.activeCategory, appState.activeAlgorithm);
}
/* Updates title, complexity, description, and grid tool visibility. */
function updateAlgorithmInfo() {
const selectedInfo = ALGORITHM_INFO[appState.activeAlgorithm];
algorithmTitle.textContent = selectedInfo.title;
algorithmSubtitle.textContent = selectedInfo.subtitle;
infoName.textContent = selectedInfo.name;
timeComplexity.textContent = selectedInfo.time;
spaceComplexity.textContent = selectedInfo.space;
infoDescription.textContent = selectedInfo.description;
const gridTools = document.getElementById("gridTools");
if (gridTools) {
gridTools.classList.toggle("show", appState.activeAlgorithm === "bfsGrid");
}
}
/* Updates the active category button. */
function updateActiveCategoryButton() {
const categoryButtons = document.querySelectorAll(".category-btn");
for (let index = 0; index < categoryButtons.length; index++) {