Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
1315 lines (1152 loc) · 53.6 KB
/
Copy pathscript.js
File metadata and controls
1315 lines (1152 loc) · 53.6 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
/**
* ============================================================================
* Algorithm Library - Main Orchestrator & Controller (script.js)
* ============================================================================
* Coordinates the entire SPA:
* - Tab & Hash routing (Home, Sorting, Searching, Pathfinding, Compare, Quiz)
* - Dark/Light Zen Theme & Books-as-Bars style switching
* - Audio synthesizer control & Mute toggle
* - Home hero live mini-animation
* - Sorting Visualizer (Single Mode & Race Mode)
* - Searching Visualizer (Linear & Binary search with pointers)
* - Pathfinding Visualizer (Grid interaction & maze generator)
* - Interactive Algorithm Comparison Matrix
* - Interactive DSA Quiz with immediate viva feedback
* - Universal keyboard shortcuts (Space, Arrows, R, M)
*/
function safeGet(key, defVal) {
try {
const val = localStorage.getItem(key);
return val !== null ? val : defVal;
} catch (e) {
return defVal;
}
}
function safeSet(key, val) {
try {
localStorage.setItem(key, val);
} catch (e) {}
}
document.addEventListener('DOMContentLoaded', () => {
// ========================================================================
// 1. STATE & GLOBAL INSTANCES
// ========================================================================
const AppState = {
currentSection: 'home',
theme: safeGet('algolib_theme', 'dark'),
barStyle: safeGet('algolib_bar_style', 'minimal'), // 'minimal' or 'books'
// Sorting State
sorting: {
algo: 'bubble',
array: [],
size: 25,
speedMs: 50,
player: null,
renderer: null,
// Race mode support
isRaceMode: false,
raceAlgo2: 'quick',
player2: null,
renderer2: null
},
// Searching State
searching: {
algo: 'binary',
array: [],
target: 42,
size: 20,
speedMs: 250,
player: null,
renderer: null
},
// Pathfinding State
pathfinding: {
algo: 'bfs',
grid: null,
speedMs: 20
},
// Quiz State
quiz: {
currentIndex: 0,
score: 0,
answered: false,
selectedOption: null
},
// Hero Mini Animation State
hero: {
player: null,
renderer: null
}
};
// ========================================================================
// 2. THEME & DISPLAY INITIALIZATION
// ========================================================================
function applyTheme(theme) {
AppState.theme = theme;
document.documentElement.setAttribute('data-theme', theme);
document.documentElement.setAttribute('data-bs-theme', theme);
safeSet('algolib_theme', theme);
const themeBtn = document.getElementById('theme-toggle-btn');
if (themeBtn) {
themeBtn.innerHTML = theme === 'dark'
? '<i class="bi bi-sun-fill me-1"></i> <span class="d-none d-sm-inline">Light</span>'
: '<i class="bi bi-moon-stars-fill me-1"></i> <span class="d-none d-sm-inline">Dark</span>';
themeBtn.setAttribute('aria-label', `Switch to ${theme === 'dark' ? 'Light' : 'Dark'} mode`);
}
}
function toggleTheme() {
const next = AppState.theme === 'dark' ? 'light' : 'dark';
applyTheme(next);
}
function applyBarStyle(style) {
AppState.barStyle = style;
safeSet('algolib_bar_style', style);
if (AppState.sorting.renderer) AppState.sorting.renderer.setTheme(style);
if (AppState.sorting.renderer2) AppState.sorting.renderer2.setTheme(style);
if (AppState.searching.renderer) AppState.searching.renderer.setTheme(style);
if (AppState.hero.renderer) AppState.hero.renderer.setTheme(style);
// Re-render current steps
if (AppState.sorting.player) {
const step = AppState.sorting.player.getCurrentStep();
if (step && AppState.sorting.renderer) AppState.sorting.renderer.render(step);
}
if (AppState.sorting.player2 && AppState.sorting.renderer2) {
const step2 = AppState.sorting.player2.getCurrentStep();
if (step2) AppState.sorting.renderer2.render(step2);
}
if (AppState.searching.player && AppState.searching.renderer) {
const sStep = AppState.searching.player.getCurrentStep();
if (sStep) AppState.searching.renderer.render(sStep);
}
const barStyleBtn = document.getElementById('bar-style-toggle-btn');
if (barStyleBtn) {
barStyleBtn.innerHTML = style === 'books'
? '<i class="bi bi-bar-chart-fill me-1"></i> Minimal'
: '<i class="bi bi-book-half me-1"></i> Library Books';
}
}
function toggleBarStyle() {
const next = AppState.barStyle === 'books' ? 'minimal' : 'books';
applyBarStyle(next);
}
// Sound toggle
function updateAudioIcon() {
const muteBtn = document.getElementById('mute-toggle-btn');
if (muteBtn && window.soundSynth) {
muteBtn.innerHTML = window.soundSynth.isMuted
? '<i class="bi bi-volume-mute-fill"></i>'
: '<i class="bi bi-volume-up-fill"></i>';
muteBtn.title = window.soundSynth.isMuted ? 'Unmute Audio (M)' : 'Mute Audio (M)';
muteBtn.setAttribute('aria-label', muteBtn.title);
}
}
// ========================================================================
// 3. SPA ROUTING & SECTION SWITCHING
// ========================================================================
function navigateTo(sectionId, optionalParam = null) {
AppState.currentSection = sectionId;
// Pause any active players
if (AppState.sorting.player) AppState.sorting.player.pause();
if (AppState.sorting.player2) AppState.sorting.player2.pause();
if (AppState.searching.player) AppState.searching.player.pause();
// Update active nav links
document.querySelectorAll('.nav-link').forEach(link => {
const target = link.getAttribute('data-target');
if (target === sectionId) {
link.classList.add('active');
link.setAttribute('aria-current', 'page');
} else {
link.classList.remove('active');
link.removeAttribute('aria-current');
}
});
// Hide all views, display requested view
document.querySelectorAll('.spa-view').forEach(view => {
view.classList.remove('active');
});
const activeView = document.getElementById(`view-${sectionId}`);
if (activeView) {
activeView.classList.add('active');
window.scrollTo({ top: 0, behavior: 'smooth' });
}
// URL hash sync
if (window.location.hash !== `#${sectionId}`) {
window.location.hash = sectionId;
}
// Section-specific setup
if (sectionId === 'sorting') {
if (optionalParam) {
const select = document.getElementById('sorting-algo-select');
if (select) {
select.value = optionalParam;
AppState.sorting.algo = optionalParam;
}
}
initSortingVisualizer();
} else if (sectionId === 'searching') {
if (optionalParam) {
const select = document.getElementById('searching-algo-select');
if (select) {
select.value = optionalParam;
AppState.searching.algo = optionalParam;
}
}
initSearchingVisualizer();
} else if (sectionId === 'pathfinding') {
if (optionalParam) {
const select = document.getElementById('pathfinding-algo-select');
if (select) {
select.value = optionalParam;
AppState.pathfinding.algo = optionalParam;
}
}
initPathfindingVisualizer();
} else if (sectionId === 'compare') {
renderCompareTable();
} else if (sectionId === 'quiz') {
initQuiz();
} else if (sectionId === 'home') {
initHeroMiniVisualizer();
}
}
window.navigateTo = navigateTo;
// ========================================================================
// 4. RANDOM ARRAY GENERATORS
// ========================================================================
function generateArray(type = 'random', size = 25, minVal = 10, maxVal = 95) {
let arr = [];
if (type === 'random') {
for (let i = 0; i < size; i++) {
arr.push(Math.floor(Math.random() * (maxVal - minVal + 1)) + minVal);
}
} else if (type === 'reversed') {
const step = (maxVal - minVal) / (size - 1 || 1);
for (let i = 0; i < size; i++) {
arr.push(Math.round(maxVal - i * step));
}
} else if (type === 'nearly_sorted') {
const step = (maxVal - minVal) / (size - 1 || 1);
for (let i = 0; i < size; i++) {
arr.push(Math.round(minVal + i * step));
}
// Swap a few random pairs
const swaps = Math.max(1, Math.floor(size * 0.1));
for (let k = 0; k < swaps; k++) {
const i = Math.floor(Math.random() * size);
const j = Math.floor(Math.random() * size);
const temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;
}
} else if (type === 'few_unique') {
const pool = [15, 35, 55, 75, 95];
for (let i = 0; i < size; i++) {
arr.push(pool[Math.floor(Math.random() * pool.length)]);
}
}
return arr;
}
// ========================================================================
// 5. SORTING VISUALIZER LOGIC (SINGLE & RACE MODE)
// ========================================================================
function initSortingVisualizer() {
const container = document.getElementById('sorting-canvas');
if (!container) return;
if (!AppState.sorting.renderer) {
AppState.sorting.renderer = new ArrayRenderer(container, {
theme: AppState.barStyle,
showValues: true
});
}
// Initialize Race Mode Secondary Renderer
const container2 = document.getElementById('sorting-canvas-race');
if (container2 && !AppState.sorting.renderer2) {
AppState.sorting.renderer2 = new ArrayRenderer(container2, {
theme: AppState.barStyle,
showValues: true
});
}
if (AppState.sorting.array.length === 0) {
resetSortingArray('random');
} else {
loadSortingSteps();
}
updateSortingInfoPanel();
}
function resetSortingArray(type = 'random') {
const sizeInput = document.getElementById('sorting-size-slider');
const size = sizeInput ? parseInt(sizeInput.value, 10) : AppState.sorting.size;
AppState.sorting.size = size;
AppState.sorting.array = generateArray(type, size);
loadSortingSteps();
}
function loadSortingSteps() {
const algoKey = AppState.sorting.algo;
const steps = window.AlgoLib.Sorting.getSteps(algoKey, AppState.sorting.array);
// Player 1 Setup
if (!AppState.sorting.player) {
AppState.sorting.player = new AlgorithmPlayer({
speed: AppState.sorting.speedMs,
onStep: (step, index, total) => {
if (AppState.sorting.renderer) AppState.sorting.renderer.render(step);
updateSortingStats(step, index, total);
highlightPseudocode('sorting-code-list', step.codeLine);
updateNarrative('sorting-narrative', step.description);
},
onStateChange: (isPlaying) => {
updatePlayButton('sorting-play-btn', isPlaying);
if (AppState.sorting.isRaceMode && AppState.sorting.player2) {
if (isPlaying && !AppState.sorting.player2.isPlaying) AppState.sorting.player2.play();
else if (!isPlaying && AppState.sorting.player2.isPlaying) AppState.sorting.player2.pause();
}
},
onComplete: () => {
checkRaceFinish();
}
});
}
AppState.sorting.player.loadSteps(steps, false);
// If in Race Mode, setup Player 2 with same array
if (AppState.sorting.isRaceMode) {
const algo2Key = AppState.sorting.raceAlgo2;
const steps2 = window.AlgoLib.Sorting.getSteps(algo2Key, AppState.sorting.array);
if (!AppState.sorting.player2) {
AppState.sorting.player2 = new AlgorithmPlayer({
speed: AppState.sorting.speedMs,
onStep: (step, index, total) => {
if (AppState.sorting.renderer2) AppState.sorting.renderer2.render(step);
updateRace2Stats(step, index, total);
},
onStateChange: (isPlaying) => {
// Synced with master button
},
onComplete: () => {
checkRaceFinish();
}
});
}
AppState.sorting.player2.loadSteps(steps2, false);
const raceBanner = document.getElementById('race-status-banner');
if (raceBanner) raceBanner.classList.add('d-none');
}
// Update timeline scrub max
const scrubber = document.getElementById('sorting-scrubber');
if (scrubber) {
scrubber.max = steps.length - 1;
scrubber.value = 0;
}
}
function updateSortingStats(step, index, total) {
const compEl = document.getElementById('sorting-counter-comps');
const swapEl = document.getElementById('sorting-counter-swaps');
const stepEl = document.getElementById('sorting-counter-steps');
const scrubber = document.getElementById('sorting-scrubber');
if (compEl && step.counters) compEl.textContent = step.counters.comparisons;
if (swapEl && step.counters) swapEl.textContent = step.counters.swaps;
if (stepEl) stepEl.textContent = `${index + 1} / ${total}`;
if (scrubber && !scrubber.matches(':active')) scrubber.value = index;
}
function updateRace2Stats(step, index, total) {
const compEl = document.getElementById('race2-counter-comps');
const swapEl = document.getElementById('race2-counter-swaps');
const stepEl = document.getElementById('race2-counter-steps');
if (compEl && step.counters) compEl.textContent = step.counters.comparisons;
if (swapEl && step.counters) swapEl.textContent = step.counters.swaps;
if (stepEl) stepEl.textContent = `${index + 1} / ${total}`;
}
function checkRaceFinish() {
if (!AppState.sorting.isRaceMode) return;
const p1 = AppState.sorting.player;
const p2 = AppState.sorting.player2;
if (!p1 || !p2) return;
const p1Done = p1.currentStepIndex >= p1.steps.length - 1;
const p2Done = p2.currentStepIndex >= p2.steps.length - 1;
if (p1Done || p2Done) {
const banner = document.getElementById('race-status-banner');
if (banner) {
banner.classList.remove('d-none');
const info1 = window.AlgoLib.Sorting.registry[AppState.sorting.algo];
const info2 = window.AlgoLib.Sorting.registry[AppState.sorting.raceAlgo2];
if (p1Done && !p2Done) {
banner.innerHTML = `<i class="bi bi-trophy-fill text-gold me-2"></i> <strong>${info1.name}</strong> finished first in ${p1.steps.length} steps! (${info2.name} still working: ${p2.currentStepIndex + 1}/${p2.steps.length})`;
} else if (p2Done && !p1Done) {
banner.innerHTML = `<i class="bi bi-trophy-fill text-gold me-2"></i> <strong>${info2.name}</strong> finished first in ${p2.steps.length} steps! (${info1.name} still working: ${p1.currentStepIndex + 1}/${p1.steps.length})`;
} else {
banner.innerHTML = `<i class="bi bi-flag-fill text-gold me-2"></i> Both algorithms completed! <strong>${info1.name}</strong>: ${p1.steps.length} steps vs <strong>${info2.name}</strong>: ${p2.steps.length} steps.`;
}
}
}
}
function updateSortingInfoPanel() {
const info = window.AlgoLib.Sorting.registry[AppState.sorting.algo];
if (!info) return;
const nameEl = document.getElementById('sorting-title');
const descEl = document.getElementById('sorting-desc');
const bestEl = document.getElementById('complexity-best');
const avgEl = document.getElementById('complexity-avg');
const worstEl = document.getElementById('complexity-worst');
const spaceEl = document.getElementById('complexity-space');
const stableEl = document.getElementById('complexity-stable');
const vivaEl = document.getElementById('sorting-viva-tip');
if (nameEl) nameEl.textContent = info.name;
if (descEl) descEl.textContent = info.description;
if (bestEl) bestEl.textContent = info.bestTime;
if (avgEl) avgEl.textContent = info.avgTime;
if (worstEl) worstEl.textContent = info.worstTime;
if (spaceEl) spaceEl.textContent = info.space;
if (stableEl) stableEl.textContent = info.stable;
if (vivaEl) vivaEl.textContent = info.vivaTip;
renderPseudocode('sorting-code-list', info.pseudocode);
}
// ========================================================================
// 6. SEARCHING VISUALIZER LOGIC
// ========================================================================
function initSearchingVisualizer() {
const container = document.getElementById('searching-canvas');
if (!container) return;
if (!AppState.searching.renderer) {
AppState.searching.renderer = new ArrayRenderer(container, {
theme: AppState.barStyle,
showValues: true
});
}
if (AppState.searching.array.length === 0) {
resetSearchingArray();
} else {
loadSearchingSteps();
}
updateSearchingInfoPanel();
}
function resetSearchingArray() {
const sizeInput = document.getElementById('searching-size-slider');
const size = sizeInput ? parseInt(sizeInput.value, 10) : AppState.searching.size;
AppState.searching.size = size;
let arr = generateArray('random', size, 10, 95);
if (AppState.searching.algo === 'binary') {
arr.sort((a, b) => a - b);
}
AppState.searching.array = arr;
// Choose random target from array or nearby
if (Math.random() < 0.8) {
AppState.searching.target = arr[Math.floor(Math.random() * arr.length)];
} else {
AppState.searching.target = Math.floor(Math.random() * 90) + 10;
}
const targetInput = document.getElementById('searching-target-input');
if (targetInput) targetInput.value = AppState.searching.target;
loadSearchingSteps();
}
function loadSearchingSteps() {
const targetInput = document.getElementById('searching-target-input');
if (targetInput && targetInput.value !== '') {
AppState.searching.target = parseInt(targetInput.value, 10) || AppState.searching.target;
}
const algoKey = AppState.searching.algo;
const steps = window.AlgoLib.Searching.getSteps(
algoKey,
AppState.searching.array,
AppState.searching.target
);
if (!AppState.searching.player) {
AppState.searching.player = new AlgorithmPlayer({
speed: AppState.searching.speedMs,
onStep: (step, index, total) => {
if (AppState.searching.renderer) AppState.searching.renderer.render(step);
updateSearchingStats(step, index, total);
highlightPseudocode('searching-code-list', step.codeLine);
updateNarrative('searching-narrative', step.description);
},
onStateChange: (isPlaying) => {
updatePlayButton('searching-play-btn', isPlaying);
}
});
}
AppState.searching.player.loadSteps(steps, false);
const scrubber = document.getElementById('searching-scrubber');
if (scrubber) {
scrubber.max = steps.length - 1;
scrubber.value = 0;
}
}
function updateSearchingStats(step, index, total) {
const compEl = document.getElementById('searching-counter-comps');
const statusEl = document.getElementById('searching-counter-status');
const stepEl = document.getElementById('searching-counter-steps');
const scrubber = document.getElementById('searching-scrubber');
if (compEl && step.counters) compEl.textContent = step.counters.comparisons;
if (statusEl) {
if (step.type === 'found') {
statusEl.innerHTML = '<span class="text-success"><i class="bi bi-check-circle-fill"></i> Found!</span>';
} else if (step.type === 'not_found') {
statusEl.innerHTML = '<span class="text-danger"><i class="bi bi-x-circle-fill"></i> Not Found</span>';
} else {
statusEl.innerHTML = '<span class="text-primary"><i class="bi bi-search"></i> Searching...</span>';
}
}
if (stepEl) stepEl.textContent = `${index + 1} / ${total}`;
if (scrubber && !scrubber.matches(':active')) scrubber.value = index;
}
function updateSearchingInfoPanel() {
const info = window.AlgoLib.Searching.registry[AppState.searching.algo];
if (!info) return;
const nameEl = document.getElementById('searching-title');
const descEl = document.getElementById('searching-desc');
const bestEl = document.getElementById('searching-complexity-best');
const avgEl = document.getElementById('searching-complexity-avg');
const worstEl = document.getElementById('searching-complexity-worst');
const spaceEl = document.getElementById('searching-complexity-space');
const vivaEl = document.getElementById('searching-viva-tip');
if (nameEl) nameEl.textContent = info.name;
if (descEl) descEl.textContent = info.description;
if (bestEl) bestEl.textContent = info.bestTime;
if (avgEl) avgEl.textContent = info.avgTime;
if (worstEl) worstEl.textContent = info.worstTime;
if (spaceEl) spaceEl.textContent = info.space;
if (vivaEl) vivaEl.textContent = info.vivaTip;
renderPseudocode('searching-code-list', info.pseudocode);
}
// ========================================================================
// 7. PATHFINDING VISUALIZER LOGIC
// ========================================================================
function initPathfindingVisualizer() {
const container = document.getElementById('grid-canvas');
if (!container) return;
if (!AppState.pathfinding.grid) {
AppState.pathfinding.grid = new PathfindingGrid(container, {
rows: 18,
cols: 35,
onMetricsUpdate: (metrics) => {
const visitedEl = document.getElementById('path-counter-visited');
const lengthEl = document.getElementById('path-counter-length');
const timeEl = document.getElementById('path-counter-time');
if (visitedEl) visitedEl.textContent = metrics.visited;
if (lengthEl) lengthEl.textContent = metrics.length;
if (timeEl) timeEl.textContent = `${metrics.time} ms`;
}
});
}
updatePathfindingInfoPanel();
}
function updatePathfindingInfoPanel() {
const info = window.AlgoLib.Pathfinding.registry[AppState.pathfinding.algo];
if (!info) return;
const nameEl = document.getElementById('pathfinding-title');
const descEl = document.getElementById('pathfinding-desc');
const timeEl = document.getElementById('path-complexity-time');
const spaceEl = document.getElementById('path-complexity-space');
const shortestEl = document.getElementById('path-complexity-shortest');
const vivaEl = document.getElementById('pathfinding-viva-tip');
if (nameEl) nameEl.textContent = info.name;
if (descEl) descEl.textContent = info.description;
if (timeEl) timeEl.textContent = info.worstTime;
if (spaceEl) spaceEl.textContent = info.space;
if (shortestEl) shortestEl.textContent = info.guaranteesShortest;
if (vivaEl) vivaEl.textContent = info.vivaTip;
renderPseudocode('pathfinding-code-list', info.pseudocode);
}
// ========================================================================
// 8. COMPARE MATRIX TABLE
// ========================================================================
function renderCompareTable(categoryFilter = 'all', searchQuery = '') {
const tbody = document.getElementById('compare-table-body');
if (!tbody) return;
const allAlgos = [
// Sorting
...Object.entries(window.AlgoLib.Sorting.registry).map(([key, item]) => ({ ...item, key, type: 'sorting' })),
// Searching
...Object.entries(window.AlgoLib.Searching.registry).map(([key, item]) => ({ ...item, key, type: 'searching' })),
// Pathfinding
...Object.entries(window.AlgoLib.Pathfinding.registry).map(([key, item]) => ({ ...item, key, type: 'pathfinding' }))
];
const query = searchQuery.trim().toLowerCase();
const filtered = allAlgos.filter(algo => {
const matchesCat = categoryFilter === 'all' || algo.type === categoryFilter;
const matchesSearch = query === '' ||
algo.name.toLowerCase().includes(query) ||
algo.description.toLowerCase().includes(query) ||
algo.paradigm.toLowerCase().includes(query);
return matchesCat && matchesSearch;
});
tbody.innerHTML = '';
if (filtered.length === 0) {
tbody.innerHTML = `<tr><td colspan="9" class="text-center py-4 text-muted">No algorithms match your search criteria.</td></tr>`;
return;
}
filtered.forEach(algo => {
const tr = document.createElement('tr');
tr.innerHTML = `
<td>
<div class="fw-bold">${algo.name}</div>
<small class="text-muted">${algo.paradigm}</small>
</td>
<td><span class="badge badge-cat-${algo.type}">${algo.category}</span></td>
<td><code class="text-gold">${algo.bestTime || 'N/A'}</code></td>
<td><code>${algo.avgTime || 'N/A'}</code></td>
<td><code>${algo.worstTime || 'N/A'}</code></td>
<td><code>${algo.space || 'O(1)'}</code></td>
<td>${algo.stable ? (algo.stable === 'Yes' ? '<span class="badge bg-success-subtle text-success">Yes</span>' : '<span class="badge bg-secondary-subtle text-secondary">No</span>') : (algo.guaranteesShortest ? '<span class="badge bg-info-subtle text-info">Optimal</span>' : 'N/A')}</td>
<td><small class="text-muted d-block" style="max-width: 260px;">${algo.vivaTip}</small></td>
<td>
<button class="btn btn-sm btn-outline-gold action-viz-btn" data-type="${algo.type}" data-key="${algo.key}">
<i class="bi bi-play-circle me-1"></i> Visualize
</button>
</td>
`;
tr.querySelector('.action-viz-btn').addEventListener('click', () => {
navigateTo(algo.type, algo.key);
});
tbody.appendChild(tr);
});
}
// ========================================================================
// 9. INTERACTIVE DSA QUIZ
// ========================================================================
function initQuiz() {
AppState.quiz.currentIndex = 0;
AppState.quiz.score = 0;
AppState.quiz.answered = false;
AppState.quiz.selectedOption = null;
const resultsCard = document.getElementById('quiz-results-card');
const questionCard = document.getElementById('quiz-question-card');
if (resultsCard) resultsCard.classList.add('d-none');
if (questionCard) questionCard.classList.remove('d-none');
renderCurrentQuestion();
}
function renderCurrentQuestion() {
const questions = window.AlgoLib.QuizData;
const qIndex = AppState.quiz.currentIndex;
if (qIndex >= questions.length) {
showQuizResults();
return;
}
const q = questions[qIndex];
AppState.quiz.answered = false;
AppState.quiz.selectedOption = null;
// Progress bar
const progressEl = document.getElementById('quiz-progress-bar');
const trackerEl = document.getElementById('quiz-question-tracker');
const scoreTracker = document.getElementById('quiz-score-tracker');
const pct = Math.round((qIndex / questions.length) * 100);
if (progressEl) progressEl.style.width = `${pct}%`;
if (trackerEl) trackerEl.textContent = `Question ${qIndex + 1} of ${questions.length}`;
if (scoreTracker) scoreTracker.textContent = `Score: ${AppState.quiz.score}`;
// Question Details
const catBadge = document.getElementById('quiz-category-badge');
const questionText = document.getElementById('quiz-question-text');
const optionsContainer = document.getElementById('quiz-options-container');
const explanationBox = document.getElementById('quiz-explanation-box');
const nextBtn = document.getElementById('quiz-next-btn');
if (catBadge) catBadge.textContent = q.category;
if (questionText) questionText.textContent = q.question;
if (explanationBox) explanationBox.classList.add('d-none');
if (nextBtn) nextBtn.classList.add('d-none');
if (optionsContainer) {
optionsContainer.innerHTML = '';
q.options.forEach((optText, idx) => {
const optBtn = document.createElement('button');
optBtn.className = 'quiz-option-btn list-group-item list-group-item-action';
optBtn.setAttribute('data-idx', idx);
optBtn.innerHTML = `
<span class="quiz-option-letter me-3">${String.fromCharCode(65 + idx)}</span>
<span class="quiz-option-text">${optText}</span>
`;
optBtn.addEventListener('click', () => handleOptionSelect(idx));
optionsContainer.appendChild(optBtn);
});
}
}
function handleOptionSelect(selectedIdx) {
if (AppState.quiz.answered) return;
AppState.quiz.answered = true;
AppState.quiz.selectedOption = selectedIdx;
const q = window.AlgoLib.QuizData[AppState.quiz.currentIndex];
const isCorrect = selectedIdx === q.correctIndex;
if (isCorrect) AppState.quiz.score++;
// Update option button styles
const optionBtns = document.querySelectorAll('.quiz-option-btn');
optionBtns.forEach((btn, idx) => {
btn.disabled = true;
if (idx === q.correctIndex) {
btn.classList.add('option-correct');
} else if (idx === selectedIdx) {
btn.classList.add('option-incorrect');
}
});
// Show Explanation
const explanationBox = document.getElementById('quiz-explanation-box');
const explanationText = document.getElementById('quiz-explanation-text');
const explanationVerdict = document.getElementById('quiz-verdict-tag');
if (explanationBox && explanationText && explanationVerdict) {
explanationBox.classList.remove('d-none');
if (isCorrect) {
explanationVerdict.className = 'badge bg-success me-2';
explanationVerdict.innerHTML = '<i class="bi bi-check-circle-fill"></i> Correct!';
if (window.soundSynth) window.soundSynth.playTone(80, 0, 100, 'sorted');
} else {
explanationVerdict.className = 'badge bg-danger me-2';
explanationVerdict.innerHTML = '<i class="bi bi-x-circle-fill"></i> Incorrect';
if (window.soundSynth) window.soundSynth.playTone(20, 0, 100, 'swap');
}
explanationText.textContent = q.explanation;
}
const nextBtn = document.getElementById('quiz-next-btn');
if (nextBtn) nextBtn.classList.remove('d-none');
const scoreTracker = document.getElementById('quiz-score-tracker');
if (scoreTracker) scoreTracker.textContent = `Score: ${AppState.quiz.score}`;
}
function showQuizResults() {
const questions = window.AlgoLib.QuizData;
const total = questions.length;
const score = AppState.quiz.score;
const pct = Math.round((score / total) * 100);
const questionCard = document.getElementById('quiz-question-card');
const resultsCard = document.getElementById('quiz-results-card');
if (questionCard) questionCard.classList.add('d-none');
if (resultsCard) resultsCard.classList.remove('d-none');
const finalScoreEl = document.getElementById('quiz-final-score');
const titleEl = document.getElementById('quiz-rank-title');
const descEl = document.getElementById('quiz-rank-desc');
if (finalScoreEl) finalScoreEl.textContent = `${score} / ${total} (${pct}%)`;
let rankTitle = "Apprentice Scholar";
let rankDesc = "Solid foundation! Review the complexity tables and step-by-step traces to master subtle edge cases.";
if (pct >= 90) {
rankTitle = "Grand Archivist of Algorithms 🏆";
rankDesc = "Exceptional mastery! You understand algorithmic invariants, worst-case degradations, and graph optimalities thoroughly.";
} else if (pct >= 70) {
rankTitle = "Senior Algorithm Fellow";
rankDesc = "Great performance! You possess a clear understanding of core DSA paradigms and search behaviors.";
}
if (titleEl) titleEl.textContent = rankTitle;
if (descEl) descEl.textContent = rankDesc;
}
// ========================================================================
// 10. HOME HERO LIVE MINI-VISUALIZER
// ========================================================================
function initHeroMiniVisualizer() {
const heroContainer = document.getElementById('hero-mini-canvas');
if (!heroContainer) return;
if (!AppState.hero.renderer) {
AppState.hero.renderer = new ArrayRenderer(heroContainer, {
theme: AppState.barStyle,
showValues: true
});
}
const miniArray = [68, 24, 85, 42, 16, 95, 33, 72, 12, 53, 90, 38];
const steps = window.AlgoLib.Sorting.recordBubbleSort(miniArray);
if (!AppState.hero.player) {
AppState.hero.player = new AlgorithmPlayer({
speed: 120,
enableSound: false, // Hero animation is purely visual / silent
onStep: (step) => {
if (AppState.hero.renderer) AppState.hero.renderer.render(step);
},
onComplete: () => {
// Loop hero animation calmly after a pause
setTimeout(() => {
if (AppState.currentSection === 'home' && AppState.hero.player) {
AppState.hero.player.reset();
AppState.hero.player.play();
}
}, 2400);
}
});
}
AppState.hero.player.loadSteps(steps, true);
}
// ========================================================================
// 11. UI HELPER UTILITIES
// ========================================================================
function renderPseudocode(containerId, lines) {
const list = document.getElementById(containerId);
if (!list || !lines) return;
list.innerHTML = '';
lines.forEach((lineText, idx) => {
const li = document.createElement('li');
li.id = `${containerId}-line-${idx + 1}`;
li.textContent = lineText;
list.appendChild(li);
});
}
function highlightPseudocode(containerId, activeLine) {
const list = document.getElementById(containerId);
if (!list) return;
list.querySelectorAll('li').forEach(li => li.classList.remove('active-code-line'));
if (activeLine) {
const targetLi = document.getElementById(`${containerId}-line-${activeLine}`);
if (targetLi) {
targetLi.classList.add('active-code-line');
}
}
}
function updateNarrative(containerId, text) {
const el = document.getElementById(containerId);
if (el && text) {
el.textContent = text;
}
}
function updatePlayButton(btnId, isPlaying) {
const btn = document.getElementById(btnId);
if (btn) {
btn.innerHTML = isPlaying
? '<i class="bi bi-pause-fill"></i> Pause'
: '<i class="bi bi-play-fill"></i> Play';
btn.setAttribute('aria-label', isPlaying ? 'Pause visualization' : 'Play visualization');
}
}
// ========================================================================
// 12. EVENT LISTENERS & DOM HOOKS
// ========================================================================
// Navigation Links
document.querySelectorAll('.spa-nav-link').forEach(link => {
link.addEventListener('click', (e) => {
e.preventDefault();
const target = link.getAttribute('data-target');
if (target) navigateTo(target);
});
});
// Theme & Audio Toggles
const themeBtn = document.getElementById('theme-toggle-btn');
if (themeBtn) themeBtn.addEventListener('click', toggleTheme);
const barStyleBtn = document.getElementById('bar-style-toggle-btn');
if (barStyleBtn) barStyleBtn.addEventListener('click', toggleBarStyle);
const muteBtn = document.getElementById('mute-toggle-btn');
if (muteBtn) {
muteBtn.addEventListener('click', () => {
if (window.soundSynth) {
window.soundSynth.toggleMute();
updateAudioIcon();
}
});
}
// ------------------------------------------------------------------------
// Sorting Visualizer Controls
// ------------------------------------------------------------------------
const sortAlgoSelect = document.getElementById('sorting-algo-select');
if (sortAlgoSelect) {
sortAlgoSelect.addEventListener('change', (e) => {
AppState.sorting.algo = e.target.value;
loadSortingSteps();
updateSortingInfoPanel();
});
}
const sortPlayBtn = document.getElementById('sorting-play-btn');
if (sortPlayBtn) {
sortPlayBtn.addEventListener('click', () => {
if (AppState.sorting.player) AppState.sorting.player.togglePlayPause();
});
}
const sortNextBtn = document.getElementById('sorting-next-btn');
if (sortNextBtn) {
sortNextBtn.addEventListener('click', () => {
if (AppState.sorting.player) AppState.sorting.player.nextStep(true);
if (AppState.sorting.isRaceMode && AppState.sorting.player2) {
AppState.sorting.player2.nextStep(true);
}
});
}
const sortPrevBtn = document.getElementById('sorting-prev-btn');
if (sortPrevBtn) {
sortPrevBtn.addEventListener('click', () => {
if (AppState.sorting.player) AppState.sorting.player.prevStep();
if (AppState.sorting.isRaceMode && AppState.sorting.player2) {
AppState.sorting.player2.prevStep();
}
});
}
const sortResetBtn = document.getElementById('sorting-reset-btn');
if (sortResetBtn) {
sortResetBtn.addEventListener('click', () => {
if (AppState.sorting.player) AppState.sorting.player.reset();
if (AppState.sorting.isRaceMode && AppState.sorting.player2) {
AppState.sorting.player2.reset();
}
});
}
const sortScrubber = document.getElementById('sorting-scrubber');
if (sortScrubber) {
sortScrubber.addEventListener('input', (e) => {
const val = parseInt(e.target.value, 10);
if (AppState.sorting.player) AppState.sorting.player.seek(val);
});
}
const sortSpeedSlider = document.getElementById('sorting-speed-slider');
if (sortSpeedSlider) {
sortSpeedSlider.addEventListener('input', (e) => {