forked from Eshajha19/Algo-Infinity-Verse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js.backup
More file actions
1167 lines (1005 loc) · 45 KB
/
Copy pathscript.js.backup
File metadata and controls
1167 lines (1005 loc) · 45 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
// ===== DATA OBJECTS =====
const dsaTopics = [
{
id: 1,
name: "Arrays",
icon: "📊",
description: "Learn array operations, manipulations, and common interview problems",
difficulty: "Easy-Medium",
theory: "Arrays are contiguous memory locations that store elements of the same type. They provide O(1) access time but fixed size.",
problems: ["Two Sum", "Maximum Subarray", "Merge Intervals", "Product Except Self", "Spiral Matrix"]
},
{
id: 2,
name: "Strings",
icon: "🔤",
description: "Master string algorithms, pattern matching, and string manipulation",
difficulty: "Easy-Medium",
theory: "Strings are arrays of characters. Key operations include concatenation, substring search, and pattern matching using algorithms like KMP.",
problems: ["Longest Substring Without Repeating", "Valid Parentheses", "Palindrome Partitioning", "String to Integer", "Group Anagrams"]
},
{
id: 3,
name: "Linked List",
icon: "🔗",
description: "Singly, doubly, and circular linked lists with traversal techniques",
difficulty: "Medium",
theory: "Linked lists are linear data structures where elements are linked using pointers. Allows dynamic size and efficient insertions/deletions.",
problems: ["Reverse Linked List", "Detect Cycle", "Merge Two Sorted Lists", "Remove Nth From End", "Intersection of Two Lists"]
},
{
id: 4,
name: "Trees",
icon: "🌳",
description: "Binary trees, BST, traversal algorithms, and tree-based problems",
difficulty: "Medium-Hard",
theory: "Trees are hierarchical structures. Binary trees have at most two children per node. BST maintains sorted order: left < root < right.",
problems: ["Maximum Depth", "Validate BST", "Lowest Common Ancestor", "Serialize/Deserialize", "Path Sum"]
},
{
id: 5,
name: "Graphs",
icon: "🕸️",
description: "Graph representations, traversal (BFS/DFS), shortest paths, and networks",
difficulty: "Hard",
theory: "Graphs consist of vertices connected by edges. Representations: adjacency list/matrix. Traversals: BFS (level-order) and DFS (depth-first).",
problems: ["Clone Graph", "Number of Islands", "Course Schedule", "Word Ladder", "Network Delay Time"]
},
{
id: 6,
name: "Dynamic Programming",
icon: "🎯",
description: "Recursion, memoization, tabulation, and optimization problems",
difficulty: "Hard",
theory: "DP breaks problems into overlapping subproblems. Stores solutions to avoid recomputation. Approaches: top-down (memoization) and bottom-up (tabulation).",
problems: ["Climbing Stairs", "Coin Change", "Longest Increasing Subsequence", "Edit Distance", "House Robber"]
}
];
const practiceProblems = [
{ id: 1, title: "Two Sum", difficulty: "easy", tags: ["Arrays", "Hash Table"], acceptance: "48.2%", category: "arrays" },
{ id: 2, title: "Valid Parentheses", difficulty: "easy", tags: ["Strings", "Stack"], acceptance: "40.2%", category: "strings" },
{ id: 3, title: "Merge Two Sorted Lists", difficulty: "easy", tags: ["Linked List", "Recursion"], acceptance: "58.5%", category: "linkedlist" },
{ id: 4, title: "Maximum Subarray", difficulty: "medium", tags: ["Arrays", "Divide & Conquer"], acceptance: "46.2%", category: "arrays" },
{ id: 5, title: "LRU Cache", difficulty: "medium", tags: ["Design", "Hash Table"], acceptance: "37.5%", category: "arrays" },
{ id: 6, title: "Clone Graph", difficulty: "medium", tags: ["Graphs", "DFS", "BFS"], acceptance: "43.2%", category: "graphs" },
{ id: 7, title: "Longest Increasing Subsequence", difficulty: "hard", tags: ["DP", "Binary Search"], acceptance: "42.1%", category: "dp" },
{ id: 8, title: "Word Ladder", difficulty: "hard", tags: ["Graphs", "BFS"], acceptance: "31.4%", category: "graphs" },
{ id: 9, title: "Trapping Rain Water", difficulty: "hard", tags: ["Arrays", "Two Pointers"], acceptance: "48.7%", category: "arrays" },
{ id: 10, title: "Reverse Linked List", difficulty: "easy", tags: ["Linked List"], acceptance: "72.1%", category: "linkedlist" },
{ id: 11, title: "Invert Binary Tree", difficulty: "easy", tags: ["Trees", "DFS"], acceptance: "68.5%", category: "trees" },
{ id: 12, title: "Validate BST", difficulty: "medium", tags: ["Trees", "Recursion"], acceptance: "28.4%", category: "trees" },
{ id: 13, title: "Number of Islands", difficulty: "medium", tags: ["Graphs", "DFS"], acceptance: "54.8%", category: "graphs" },
{ id: 14, title: "House Robber", difficulty: "medium", tags: ["DP", "Arrays"], acceptance: "42.3%", category: "dp" },
{ id: 15, title: "Course Schedule", difficulty: "medium", tags: ["Graphs", "Topological Sort"], acceptance: "44.7%", category: "graphs" }
];
const chatbotResponses = {
"time complexity": "Time complexity measures how an algorithm's runtime grows with input size. Common complexities: O(1) constant, O(log n) logarithmic, O(n) linear, O(n log n) linearithmic, O(n²) quadratic, O(2^n) exponential.",
"space complexity": "Space complexity measures memory usage relative to input size. Aim for O(1) or O(n) space. In-place algorithms modify input directly.",
"arrays": "Arrays provide O(1) random access but fixed size. Use when you need fast lookups and index-based access. Key operations: insert O(n), delete O(n), search O(n) unsorted / O(log n) binary search on sorted arrays.",
"linked list": "Linked lists offer O(1) insertion/deletion at any position but O(n) access time. Use when frequent insertions/deletions needed. Types: singly (one pointer), doubly (two pointers), circular (last points to first).",
"tree": "Trees are hierarchical. Binary trees: each node has ≤2 children. BST: left < root < right. Balanced (AVL, Red-Black) ensure O(log n) operations. Traversals: inorder (left-root-right), preorder (root-left-right), postorder (left-right-root).",
"graph": "Graphs represent networks. Directed vs undirected, weighted vs unweighted, cyclic vs acyclic. Representations: adjacency list (space-efficient) vs adjacency matrix (O(1) edge lookup). Traversals: BFS (shortest path on unweighted graphs), DFS (cycle detection, topological sort).",
"dynamic programming": "DP solves problems with optimal substructure & overlapping subproblems. Memoization (top-down) caches recursive calls. Tabulation (bottom-up) fills DP table iteratively. Steps: identify state, recurrence, base cases. Classic problems: Fibonacci, Knapsack, LCS, LIS, Coin Change.",
"greedy": "Greedy algorithms make locally optimal choices hoping for global optimum. Works when greedy choice property holds. Examples: Dijkstra's shortest path, Huffman coding, activity selection.",
"sorting": "Common sorting algorithms: Bubble O(n²), Selection O(n²), Insertion O(n²) (good for small/nearly sorted), Merge O(n log n) stable, Quick O(n log n) average, Heap O(n log n) in-place, Counting O(n+k) for bounded range, Radix O(d(n+b)).",
"binary search": "Binary search on sorted arrays: repeatedly divide search interval in half. Time O(log n). Template: low=0, high=n-1; while low≤high: mid=(low+high)/2; if target=arr[mid] return; else adjust bounds.",
"recursion": "Recursion solves problems by breaking into smaller subproblems. Base case stops recursion. Recursive case calls function with smaller input. Use for tree traversals, backtracking, divide & conquer. Watch stack overflow for deep recursion.",
"big o": "Big O describes upper bound of growth rate. Best, average, worst cases differ. Common: O(1) < O(log n) < O(n) < O(n log n) < O(n²) < O(2^n) < O(n!). Space complexity also matters.",
"bfs": "Breadth-First Search explores all neighbors before moving deeper. Use queue. Applications: shortest path (unweighted), level-order traversal, web crawling, social networks (degrees of separation).",
"dfs": "Depth-First Search goes deep before backtracking. Use stack (explicit or recursion). Applications: cycle detection, topological sort, connected components, maze solving. Three tree traversals: inorder, preorder, postorder.",
"system design": "System design involves scaling systems. Key concepts: load balancers, caching (Redis), databases (SQL vs NoSQL), CDNs, message queues, microservices, replication, sharding, CAP theorem, consistency models. Start with requirements, then high-level design, deep dive on components.",
"object oriented design": "OOD principles: encapsulation (data hiding), inheritance (code reuse), polymorphism (same interface, different implementations), abstraction (simplify complexity). Design patterns: Singleton, Factory, Observer, Strategy, Decorator, Adapter.",
"api": "API (Application Programming Interface) defines how software components interact. RESTful APIs use HTTP verbs (GET, POST, PUT, DELETE), stateless, resource-based. GraphQL allows flexible queries. Design for scalability, versioning, authentication, rate limiting.",
"sql": "SQL (Structured Query Language) manages relational databases. Key commands: SELECT (retrieve), INSERT (add), UPDATE (modify), DELETE (remove), JOIN (combine tables), GROUP BY (aggregate), WHERE (filter), ORDER BY (sort). Indexes speed up reads.",
"cache": "Cache stores frequently accessed data in faster storage (memory). Strategies: LRU (least recently used), LFU (least frequently used). Cache aside, write-through, write-back patterns. Cache invalidation is critical. Redis, Memcached implementations.",
"default": "I can help with DSA topics, coding problems, system design, interview tips, and career advice. Try asking about specific algorithms, data structures, time complexity, or problem-solving strategies!"
};
// ===== STATE MANAGEMENT =====
let userProgress = {
completedProblems: [],
xp: 0,
level: 1,
streak: 0,
badges: [],
lastActive: null
};
// ===== INITIALIZATION =====
document.addEventListener('DOMContentLoaded', () => {
loadUserData();
initLoadingScreen();
initNavbar();
initHeroSection();
initTopicsSection();
initPracticeSection();
initRoadmap();
initDashboard();
initGamification();
initChatbot();
initScrollEffects();
initDarkMode();
});
// ===== LOADING SCREEN =====
function initLoadingScreen() {
setTimeout(() => {
document.getElementById('loading-screen').classList.add('hidden');
initializeAnimations();
}, 2000);
}
// ===== NAVBAR =====
function initNavbar() {
const menuToggle = document.getElementById('menuToggle');
const navLinks = document.getElementById('navLinks');
menuToggle.addEventListener('click', () => {
navLinks.classList.toggle('active');
const icon = menuToggle.querySelector('i');
icon.classList.toggle('fa-bars');
icon.classList.toggle('fa-times');
});
// Close menu on link click
navLinks.querySelectorAll('a').forEach(link => {
link.addEventListener('click', () => {
navLinks.classList.remove('active');
const icon = menuToggle.querySelector('i');
icon.classList.add('fa-bars');
icon.classList.remove('fa-times');
});
});
// Scroll effect
window.addEventListener('scroll', () => {
const navbar = document.querySelector('.navbar');
if (window.scrollY > 100) {
navbar.style.background = 'rgba(10, 10, 26, 0.95)';
} else {
navbar.style.background = 'rgba(10, 10, 26, 0.8)';
}
});
}
// ===== HERO SECTION =====
function initHeroSection() {
// Typing animation
const typingElement = document.getElementById('typingText');
const texts = ["Arrays", "Linked Lists", "Trees", "Graphs", "Dynamic Programming", "System Design"];
let textIndex = 0;
let charIndex = 0;
let isDeleting = false;
function typeEffect() {
const currentText = texts[textIndex];
if (isDeleting) {
typingElement.textContent = currentText.substring(0, charIndex - 1);
charIndex--;
} else {
typingElement.textContent = currentText.substring(0, charIndex + 1);
charIndex++;
}
let typeSpeed = isDeleting ? 50 : 100;
if (!isDeleting && charIndex === currentText.length) {
typeSpeed = 2000;
isDeleting = true;
} else if (isDeleting && charIndex === 0) {
isDeleting = false;
textIndex = (textIndex + 1) % texts.length;
typeSpeed = 500;
}
setTimeout(typeEffect, typeSpeed);
}
typeEffect();
// Animate stats
const statNumbers = document.querySelectorAll('.stat-number');
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
animateValue(entry.target);
observer.unobserve(entry.target);
}
});
}, { threshold: 0.5 });
statNumbers.forEach(stat => observer.observe(stat));
}
function animateValue(element) {
const target = parseInt(element.getAttribute('data-target'));
const duration = 2000;
const increment = target / (duration / 16);
let current = 0;
const timer = setInterval(() => {
current += increment;
if (current >= target) {
current = target;
clearInterval(timer);
}
element.textContent = Math.ceil(current).toLocaleString();
}, 16);
}
// ===== TOPICS SECTION =====
function initTopicsSection() {
const topicsGrid = document.querySelector('.topics-grid');
dsaTopics.forEach((topic, index) => {
const card = document.createElement('div');
card.className = 'topic-card animate-in';
card.style.animationDelay = `${index * 0.1}s`;
card.innerHTML = `
<div class="topic-icon">${topic.icon}</div>
<h3 class="topic-name">${topic.name}</h3>
<p class="topic-desc">${topic.description}</p>
<div class="topic-meta">
<span class="difficulty-badge ${getDifficultyClass(topic.difficulty)}">${topic.difficulty}</span>
<span class="topic-count">${topic.problems.length} problems</span>
</div>
`;
topicsGrid.appendChild(card);
card.addEventListener('click', () => {
openTopicModal(topic);
});
});
}
function getDifficultyClass(difficulty) {
switch(difficulty.toLowerCase()) {
case 'easy': return 'easy';
case 'medium': return 'medium';
case 'hard': return 'hard';
default: return 'medium';
}
}
// ===== PRACTICE SECTION =====
function initPracticeSection() {
const problemsGrid = document.querySelector('.problems-grid');
if (!problemsGrid) return;
// Filter buttons
const filterButtons = document.querySelectorAll('.filter-btn');
let currentFilter = 'all';
filterButtons.forEach(btn => {
btn.addEventListener('click', () => {
filterButtons.forEach(b => b.classList.remove('active'));
btn.classList.add('active');
currentFilter = btn.dataset.filter;
renderProblems(currentFilter);
});
});
// Search bar
const searchInput = document.getElementById('searchInput');
if (searchInput) {
searchInput.addEventListener('input', (e) => {
renderProblems(currentFilter, e.target.value.toLowerCase());
});
}
// Initial render
renderProblems('all');
}
function renderProblems(filter = 'all', searchQuery = '') {
const problemsGrid = document.querySelector('.problems-grid');
if (!problemsGrid) return;
let filteredProblems = practiceProblems.filter(problem => {
const matchesFilter = filter === 'all' || problem.difficulty === filter;
const matchesSearch = !searchQuery ||
problem.title.toLowerCase().includes(searchQuery) ||
problem.tags.some(tag => tag.toLowerCase().includes(searchQuery));
return matchesFilter && matchesSearch;
});
problemsGrid.innerHTML = filteredProblems.map(problem => `
<div class="problem-card animate-in" data-id="${problem.id}">
<div class="problem-header">
<h3 class="problem-title">${problem.title}</h3>
<span class="difficulty-badge ${getDifficultyClass(problem.difficulty)}">${problem.difficulty}</span>
</div>
<div class="problem-tags">
${problem.tags.map(tag => `<span class="tag">${tag}</span>`).join('')}
</div>
<div class="problem-meta">
<span class="acceptance-rate">
<i class="fas fa-users"></i> ${problem.acceptance} acceptance
</span>
${userProgress.completedProblems.includes(problem.id)
? '<span class="completed-badge"><i class="fas fa-check"></i> Completed</span>'
: ''
}
</div>
</div>
`).join('');
// Add click handlers
problemsGrid.querySelectorAll('.problem-card').forEach(card => {
card.addEventListener('click', () => {
const problemId = parseInt(card.dataset.id);
handleProblemClick(problemId);
});
});
}
// ===== ROADMAP =====
function initRoadmap() {
const progressBar = document.getElementById('roadmapProgress');
const stages = document.querySelectorAll('.stage');
// Calculate progress based on completed problems
const totalProblems = practiceProblems.length;
const completed = userProgress.completedProblems.length;
const progress = Math.min((completed / totalProblems) * 100, 100);
setTimeout(() => {
progressBar.style.width = `${progress}%`;
// Activate stages based on progress
if (progress >= 25) stages[0].classList.add('active');
if (progress >= 70) stages[1].classList.add('active');
if (progress === 100) stages[2].classList.add('active');
}, 500);
}
// ===== DASHBOARD =====
function initDashboard() {
updateDashboard();
}
function updateDashboard() {
document.getElementById('completedProblems').textContent = userProgress.completedProblems.length;
document.getElementById('currentStreak').textContent = userProgress.streak;
document.getElementById('totalXP').textContent = userProgress.xp;
updateActivityList();
updateBadges();
updateLeaderboard();
}
function updateActivityList() {
const activityList = document.getElementById('activityList');
if (userProgress.completedProblems.length === 0) {
activityList.innerHTML = '<p class="empty-state">No recent activity. Start solving problems!</p>';
return;
}
const activities = userProgress.completedProblems.slice(-5).map(pid => {
const problem = practiceProblems.find(p => p.id === pid);
return {
problem: problem ? problem.title : 'Unknown',
time: 'Today'
};
});
activityList.innerHTML = activities.map(activity => `
<div class="activity-item">
<div class="activity-type">
<span class="activity-icon"><i class="fas fa-code"></i></span>
<span>Solved: ${activity.problem}</span>
</div>
<span class="activity-time">${activity.time}</span>
</div>
`).join('');
}
function updateBadges() {
const container = document.getElementById('badgesContainer');
const grid = document.getElementById('badgesGrid');
const badges = [
{ id: 1, icon: '🌟', name: 'First Steps', earned: userProgress.completedProblems.length >= 1 },
{ id: 2, icon: '🔥', name: 'On Fire', earned: userProgress.streak >= 7 },
{ id: 3, icon: '💎', name: 'Diamond', earned: userProgress.xp >= 5000 },
{ id: 4, icon: '🚀', name: 'Rocket', earned: userProgress.completedProblems.length >= 50 },
{ id: 5, icon: '👑', name: 'Master', earned: userProgress.completedProblems.length >= 100 },
{ id: 6, icon: '🎯', name: 'Sharpshooter', earned: userProgress.completedProblems.length >= 25 && userProgress.xp >= 2500 }
];
// Dashboard badges
container.innerHTML = badges.map(badge =>
`<div class="badge ${badge.earned ? '' : 'locked'}">
${badge.icon}
<span class="badge-tooltip">${badge.name}</span>
</div>`
).join('');
// Gamification section badges
grid.innerHTML = badges.map(badge =>
`<div class="badge-lg ${badge.earned ? '' : 'locked'}">
${badge.icon}
<span class="badge-tooltip">${badge.name}</span>
</div>`
).join('');
}
function updateLeaderboard() {
const leaderboardList = document.getElementById('leaderboardList');
// Mock leaderboard data
const leaders = [
{ name: "CodeMaster", xp: 15420, rank: 1 },
{ name: "AlgoNinja", xp: 14890, rank: 2 },
{ name: "DevGuru", xp: 13200, rank: 3 },
{ name: "You", xp: userProgress.xp, rank: 4 },
{ name: "BinaryBeast", xp: 11500, rank: 5 }
];
leaderboardList.innerHTML = leaders.map(user => `
<div class="leaderboard-item ${user.name === 'You' ? 'current-user' : ''}" style="${user.name === 'You' ? 'border: 2px solid var(--primary);' : ''}">
<span class="leader-rank">#${user.rank}</span>
<span class="leader-name">${user.name}</span>
<span class="leader-xp">${user.xp.toLocaleString()} XP</span>
</div>
`).join('');
}
// ===== GAMIFICATION =====
function initGamification() {
updateXPBar();
}
function addXP(amount) {
userProgress.xp += amount;
checkLevelUp();
saveUserData();
}
function checkLevelUp() {
const levels = [0, 1000, 2500, 5000, 10000, 20000, 50000, 100000];
const levelNames = ['Beginner', 'Novice', 'Intermediate', 'Advanced', 'Expert', 'Master', 'Grandmaster', 'Legend'];
let newLevel = 1;
for (let i = levels.length - 1; i >= 0; i--) {
if (userProgress.xp >= levels[i]) {
newLevel = i + 1;
break;
}
}
if (newLevel > userProgress.level) {
// Level up notification
showNotification(`🎉 Level Up! You're now Level ${newLevel} - ${levelNames[newLevel-1]}`, 'success');
}
userProgress.level = newLevel;
document.getElementById('levelBadge').textContent = `Level ${newLevel} - ${levelNames[newLevel-1]}`;
}
function updateGamification() {
updateXPBar();
updateBadges();
}
function showNotification(message, type = 'info') {
const notification = document.createElement('div');
notification.style.cssText = `
position: fixed;
top: 100px;
right: 20px;
padding: 1rem 1.5rem;
background: ${type === 'success' ? 'var(--gradient-4)' : type === 'error' ? '#ef4444' : 'var(--primary)'};
color: ${type === 'success' ? 'var(--dark-bg)' : 'white'};
border-radius: 10px;
box-shadow: var(--glass-shadow);
z-index: 10000;
animation: slideIn 0.3s ease;
font-weight: 600;
max-width: 350px;
`;
notification.textContent = message;
document.body.appendChild(notification);
setTimeout(() => {
notification.style.opacity = '0';
notification.style.transform = 'translateX(100%)';
notification.style.transition = 'all 0.3s ease';
setTimeout(() => notification.remove(), 300);
}, 3000);
}
function updateXPBar() {
const levels = [0, 1000, 2500, 5000, 10000, 20000, 50000, 100000];
const currentLevel = userProgress.level;
const currentLevelXP = levels[currentLevel - 1] || 0;
const nextLevelXP = levels[currentLevel] || 100000;
const xpProgress = ((userProgress.xp - currentLevelXP) / (nextLevelXP - currentLevelXP)) * 100;
setTimeout(() => {
document.getElementById('xpBar').style.width = `${Math.min(xpProgress, 100)}%`;
document.getElementById('xpText').textContent = `${userProgress.xp} / ${nextLevelXP} XP`;
}, 300);
}
// ===== CHATBOT =====
function initChatbot() {
const toggle = document.getElementById('chatbotToggle');
const windowEl = document.getElementById('chatbotWindow');
const close = document.getElementById('chatbotClose');
const input = document.getElementById('chatbotInput');
const send = document.getElementById('chatbotSend');
const quickQs = document.querySelectorAll('.quick-q');
toggle.addEventListener('click', () => {
windowEl.classList.toggle('hidden');
toggle.querySelector('.chatbot-badge').style.display = 'none';
});
close.addEventListener('click', () => {
windowEl.classList.add('hidden');
});
function sendMessage() {
const message = input.value.trim();
if (!message) return;
addChatMessage(message, 'user');
input.value = '';
// Simulate bot response
setTimeout(() => {
const response = getBotResponse(message);
addChatMessage(response, 'bot');
}, 800);
}
send.addEventListener('click', sendMessage);
input.addEventListener('keypress', (e) => {
if (e.key === 'Enter') sendMessage();
});
quickQs.forEach(btn => {
btn.addEventListener('click', () => {
const question = btn.getAttribute('data-question');
input.value = question;
sendMessage();
});
});
}
function addChatMessage(message, sender) {
const messagesContainer = document.getElementById('chatbotMessages');
const messageEl = document.createElement('div');
messageEl.className = `message ${sender}`;
messageEl.innerHTML = `<p>${message}</p>`;
messagesContainer.appendChild(messageEl);
messagesContainer.scrollTop = messagesContainer.scrollHeight;
}
function getBotResponse(question) {
const q = question.toLowerCase();
for (const key in chatbotResponses) {
if (q.includes(key)) {
return chatbotResponses[key];
}
}
return chatbotResponses['default'];
}
// ===== SCROLL EFFECTS =====
function initScrollEffects() {
const scrollTopBtn = document.getElementById('scrollTopBtn');
window.addEventListener('scroll', () => {
if (window.scrollY > 500) {
scrollTopBtn.classList.add('visible');
} else {
scrollTopBtn.classList.remove('visible');
}
});
scrollTopBtn.addEventListener('click', () => {
window.scrollTo({ top: 0, behavior: 'smooth' });
});
// Intersection Observer for animations
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('animate-in');
}
});
}, { threshold: 0.1 });
document.querySelectorAll('.topic-card, .problem-card, .interview-card, .dashboard-card').forEach(el => {
observer.observe(el);
});
}
// ===== DARK MODE =====
function initDarkMode() {
const toggle = document.getElementById('darkModeToggle');
const icon = toggle.querySelector('i');
// Check saved preference
const savedMode = localStorage.getItem('darkMode');
if (savedMode === 'light') {
document.body.classList.add('light-mode');
icon.classList.remove('fa-moon');
icon.classList.add('fa-sun');
}
toggle.addEventListener('click', () => {
document.body.classList.toggle('light-mode');
const isLight = document.body.classList.contains('light-mode');
icon.classList.toggle('fa-moon');
icon.classList.toggle('fa-sun');
localStorage.setItem('darkMode', isLight ? 'light' : 'dark');
});
}
// ===== UTILITIES =====
function initializeAnimations() {
// Animate elements on scroll using Intersection Observer
const animatedElements = document.querySelectorAll('.animate-in');
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.style.opacity = '1';
entry.target.style.transform = 'translateY(0)';
}
});
}, { threshold: 0.1 });
animatedElements.forEach(el => {
el.style.opacity = '0';
el.style.transform = 'translateY(30px)';
el.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
observer.observe(el);
});
}
// ===== LOCAL STORAGE =====
function saveUserData() {
userProgress.lastActive = new Date().toISOString();
localStorage.setItem('algoInfinityVerse', JSON.stringify(userProgress));
}
function loadUserData() {
const saved = localStorage.getItem('algoInfinityVerse');
if (saved) {
const data = JSON.parse(saved);
userProgress = { ...userProgress, ...data };
// Update streak if user was active yesterday
if (userProgress.lastActive) {
const lastActive = new Date(userProgress.lastActive);
const today = new Date();
const diffDays = Math.floor((today - lastActive) / (1000 * 60 * 60 * 24));
if (diffDays === 0) {
// Already active today
} else if (diffDays === 1) {
userProgress.streak += 1;
} else {
userProgress.streak = 0;
}
saveUserData();
}
} else {
// Initialize with some demo data
userProgress.completedProblems = [1, 2, 10];
userProgress.xp = 350;
userProgress.level = 2;
userProgress.streak = 3;
userProgress.badges = [1];
saveUserData();
}
}
// ===== QUIZ EDITOR =====
let currentProblem = null;
function openTopicModal(topic) {
const modal = document.getElementById('topicModal');
document.getElementById('modalTitle').textContent = topic.name;
document.getElementById('modalTheory').textContent = topic.theory;
document.getElementById('modalDifficulty').innerHTML =
`<span class="difficulty-badge ${getDifficultyClass(topic.difficulty)}">${topic.difficulty}</span>`;
const problemsList = document.getElementById('modalProblems');
problemsList.innerHTML = topic.problems.map(p => `<li>${p}</li>`).join('');
document.getElementById('startPracticeBtn').onclick = () => {
modal.classList.remove('active');
document.getElementById('practice').scrollIntoView({ behavior: 'smooth' });
};
modal.classList.add('active');
}
function closeTopicModal() {
document.getElementById('topicModal').classList.remove('active');
}
function openQuizEditor(problem) {
currentProblem = problem;
const modal = document.getElementById('quizEditorModal');
document.getElementById('quizTitle').textContent = problem.title;
document.getElementById('quizTopicBadge').textContent = problem.tags.join(', ');
document.getElementById('quizDifficulty').textContent = problem.difficulty;
document.getElementById('quizDifficulty').className = 'quiz-difficulty ' +
(problem.difficulty === 'easy' ? 'difficulty-easy' :
problem.difficulty === 'medium' ? 'difficulty-medium' : 'difficulty-hard');
// Set problem description
document.getElementById('quizDescription').textContent =
`Solve the "${problem.title}" problem. ${problem.tags.map(t => `[${t}]`).join(' ')}`;
// Set examples
const examples = generateExamples(problem);
document.getElementById('quizExamples').innerHTML = examples;
// Set test cases
const testCases = generateTestCases(problem);
renderTestCases(testCases);
// Reset editor
const editor = document.getElementById('codeEditor');
const lang = document.getElementById('languageSelect').value;
editor.value = getDefaultCode(lang, problem);
// Clear output
clearQuizOutput();
// Show modal
modal.classList.add('active');
// Setup line numbers
updateLineNumbers();
}
function closeQuizEditor() {
document.getElementById('quizEditorModal').classList.remove('active');
currentProblem = null;
}
function clearQuizOutput() {
const output = document.getElementById('quizOutputContent');
output.innerHTML = '<p class="output-placeholder">Run your code to see output...</p>';
}
function runQuizCode() {
const editor = document.getElementById('codeEditor');
const code = editor.value;
const lang = document.getElementById('languageSelect').value;
const output = document.getElementById('quizOutputContent');
if (!code.trim()) {
output.innerHTML = '<p class="output-error">❌ Error: Please write some code first.</p>';
return;
}
output.innerHTML = '<p class="output-running">⏳ Running code...</p>';
// Simulate code execution
setTimeout(() => {
try {
const result = executeCode(code, lang);
output.innerHTML = `<pre class="output-success">✅ Output:\n${result}</pre>`;
} catch (e) {
output.innerHTML = `<pre class="output-error">❌ Error:\n${e.message}</pre>`;
}
}, 500);
}
function submitQuizCode() {
const editor = document.getElementById('codeEditor');
const code = editor.value;
if (!code.trim()) {
showNotification('Please write some code before submitting!', 'error');
return;
}
if (!currentProblem) {
showNotification('No problem selected!', 'error');
return;
}
// Check if already completed
if (userProgress.completedProblems.includes(currentProblem.id)) {
showNotification('You have already completed this problem!', 'info');
return;
}
// Mark as completed
userProgress.completedProblems.push(currentProblem.id);
addXP(getXPForDifficulty(currentProblem.difficulty));
updateStreak();
saveUserData();
// Update UI
updateDashboard();
updateGamification();
initRoadmap();
closeQuizEditor();
showNotification(`🎉 Problem solved! +${getXPForDifficulty(currentProblem.difficulty)} XP`, 'success');
}
function generateExamples(problem) {
const examples = {
1: '<strong>Example 1:</strong><br>Input: nums = [2,7,11,15], target = 9<br>Output: [0,1]<br>Explanation: nums[0] + nums[1] = 2 + 7 = 9',
2: '<strong>Example 1:</strong><br>Input: s = "()"<br>Output: true',
3: '<strong>Example 1:</strong><br>Input: l1 = [1,2,4], l2 = [1,3,4]<br>Output: [1,1,2,3,4,4]',
4: '<strong>Example 1:</strong><br>Input: nums = [-2,1,-3,4,-1,2,1,-5,4]<br>Output: 6<br>Explanation: [4,-1,2,1] has the largest sum = 6',
5: '<strong>Example:</strong><br>Design and implement LRU Cache',
6: '<strong>Example 1:</strong><br>Input: adjList = [[2,4],[1,3],[2,4],[1,3]]<br>Output: [[2,4],[1,3],[2,4],[1,3]]',
7: '<strong>Example 1:</strong><br>Input: nums = [10,9,2,5,3,7,101,18]<br>Output: 4',
8: '<strong>Example 1:</strong><br>Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]<br>Output: 5',
9: '<strong>Example 1:</strong><br>Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]<br>Output: 6',
10: '<strong>Example 1:</strong><br>Input: head = [1,2,3,4,5]<br>Output: [5,4,3,2,1]',
11: '<strong>Example 1:</strong><br>Input: root = [4,2,7,1,3,6,9]<br>Output: [4,7,2,9,6,3,1]',
12: '<strong>Example 1:</strong><br>Input: root = [2,1,3]<br>Output: true',
13: '<strong>Example 1:</strong><br>Input: grid = [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]<br>Output: 3',
14: '<strong>Example 1:</strong><br>Input: nums = [1,2,3,1]<br>Output: 4',
15: '<strong>Example 1:</strong><br>Input: numCourses = 2, prerequisites = [[1,0]]<br>Output: [0,1]'
};
return examples[problem.id] || '<strong>Example:</strong><br>Solve this problem';
}
function generateTestCases(problem) {
return [
{ input: 'Test input 1', expected: 'Expected output', passed: true },
{ input: 'Test input 2', expected: 'Expected output', passed: true },
{ input: 'Test input 3', expected: 'Expected output', passed: false }
];
}
function renderTestCases(testCases) {
const container = document.getElementById('quizTestCasesContainer');
container.innerHTML = testCases.map(tc => `
<div class="test-case">
<span class="test-case-input">${tc.input}</span>
<span class="test-case-result ${tc.passed ? 'passed' : 'failed'}">
${tc.passed ? '✓ PASS' : '✗ FAIL'}
</span>
</div>
`).join('');
}
function getDefaultCode(lang, problem) {
const templates = {
javascript: `/**
* @param {*} params - Problem parameters
* @return {*} - Solution result
*/
function solution(params) {
}
// Test your solution
// console.log(solution());`,
python: `def solution(params):
"""
:type params:
:rtype:
"""
# Test your solution
# print(solution())`,
java: `class Solution {
public ReturnType solution(ParamsType params) {
}
}`,
cpp: `class Solution {
public:
ReturnType solution(ParamsType params) {
}
};`
};
return templates[lang] || templates.javascript;
}
function executeCode(code, lang) {
// Simulate code execution based on language
if (lang === 'javascript') {
// Try to find and execute a function
const fnMatch = code.match(/function\s+(\w+)/);
if (fnMatch) {
return `Executed successfully. Function "${fnMatch[1]}" found.`;
}
return 'Code executed (simulation).';
}
return `Code executed in ${lang.toUpperCase()} (simulation).`;
}
function getXPForDifficulty(difficulty) {
const xpMap = { easy: 100, medium: 250, hard: 500 };
return xpMap[difficulty.toLowerCase()] || 100;
}
function updateStreak() {
const today = new Date();
const lastActive = userProgress.lastActive ? new Date(userProgress.lastActive) : null;
if (lastActive) {
const diffDays = Math.floor((today - lastActive) / (1000 * 60 * 60 * 24));
if (diffDays > 1) {
userProgress.streak = 1;
} else if (diffDays === 0) {
// Already active today, don't increment streak
} else {
userProgress.streak += 1;
}
} else {
userProgress.streak = 1;
}
userProgress.lastActive = today.toISOString();
}
// ===== PROBLEM LIST CLICK HANDLERS =====
function handleProblemClick(problemId) {
const problem = practiceProblems.find(p => p.id === problemId);
if (problem) {
openQuizEditor(problem);
}
}
// ===== CODE EDITOR UTILITIES =====
function updateLineNumbers() {
const editor = document.getElementById('codeEditor');
const lineNumbers = document.getElementById('lineNumbers');
const lines = editor.value.split('\n').length;
lineNumbers.innerHTML = Array.from({ length: Math.max(lines, 1) }, (_, i) => i + 1).join('\n');
}
function syncScroll() {
const editor = document.getElementById('codeEditor');
const lineNumbers = document.getElementById('lineNumbers');
lineNumbers.scrollTop = editor.scrollTop;
}
// Insert code snippet
function insertSnippet(type) {
const editor = document.getElementById('codeEditor');
const snippets = {
'for': 'for (let i = 0; i < array.length; i++) {\n \n}',
'if': 'if (condition) {\n \n} else {\n \n}',
'function': 'function functionName(params) {\n \n return;\n}',
'while': 'while (condition) {\n \n}',
'switch': 'switch (expression) {\n case value:\n break;\n default:\n break;\n}'
};
const snippet = snippets[type] || '';
const start = editor.selectionStart;
const end = editor.selectionEnd;
const before = editor.value.substring(0, start);
const after = editor.value.substring(end);
editor.value = before + snippet + after;
editor.selectionStart = start;
editor.selectionEnd = start + snippet.length;