From 6691d26768f22ab1751b8a9e733e0c3920a5b74b Mon Sep 17 00:00:00 2001 From: Sohan Rout Date: Sun, 2 Aug 2026 18:12:15 +0530 Subject: [PATCH 1/2] Fix : refactored code block to a scalable architecture --- app/components/modules/CodeBlock.jsx | 155 +++++++ .../operations/comparison/animation.jsx | 5 +- .../{data/codeExamples.json => code.js} | 6 +- .../operations/comparison/codeBlock.jsx | 159 ------- .../operations/deletion/animation.jsx | 5 +- .../{data/codeExamples.json => code.js} | 6 +- .../operations/deletion/codeBlock.jsx | 159 ------- .../operations/insertion/animation.jsx | 5 +- .../{data/codeExamples.json => code.js} | 6 +- .../operations/insertion/codeBlock.jsx | 159 ------- .../operations/merge/._codeBlock.jsx | Bin 4096 -> 0 bytes .../linkedList/operations/merge/animation.jsx | 5 +- .../merge/{data/codeExamples.json => code.js} | 6 +- .../linkedList/operations/merge/codeBlock.jsx | 159 ------- .../operations/reverse/animation.jsx | 5 +- .../linkedList/operations/reverse/code.js | 9 + .../operations/reverse/codeBlock.jsx | 159 ------- .../operations/reverse/data/codeExamples.json | 7 - .../operations/traversal/animation.jsx | 5 +- .../{data/codeExamples.json => code.js} | 6 +- .../operations/traversal/codeBlock.jsx | 159 ------- .../types/circular/{codeBlock.jsx => code.js} | 157 +------ .../linkedList/types/circular/page.jsx | 5 +- .../linkedList/types/doubly/animation.jsx | 5 +- .../types/doubly/{codeBlock.jsx => code.js} | 157 +------ .../types/singly/{codeBlock.jsx => code.js} | 157 +------ .../linkedList/types/singly/page.jsx | 5 +- .../linkedList/{codeBlock.jsx => code.js} | 157 +------ .../queue/implementation/linkedList/page.jsx | 5 +- .../queue/operations/enqueue-dequeue/code.js | 278 +++++++++++ .../operations/enqueue-dequeue/codeBlock.jsx | 433 ------------------ .../queue/operations/enqueue-dequeue/page.jsx | 5 +- .../queue/operations/isempty/code.js | 89 ++++ .../queue/operations/isempty/codeBlock.jsx | 244 ---------- .../queue/operations/isempty/page.jsx | 5 +- .../queue/operations/isfull/code.js | 81 ++++ .../queue/operations/isfull/codeBlock.jsx | 236 ---------- .../queue/operations/isfull/page.jsx | 5 +- .../queue/operations/peek-front/code.js | 124 +++++ .../queue/operations/peek-front/codeBlock.jsx | 279 ----------- .../queue/operations/peek-front/page.jsx | 5 +- .../types/circular/{codeBlock.jsx => code.js} | 159 +------ app/visualizer/queue/types/circular/page.jsx | 5 +- .../types/deque/{codeBlock.jsx => code.js} | 159 +------ app/visualizer/queue/types/deque/page.jsx | 5 +- .../types/priority/{codeBlock.jsx => code.js} | 159 +------ app/visualizer/queue/types/priority/page.jsx | 5 +- .../singleEnded/{codeBlock.jsx => code.js} | 159 +------ .../queue/types/singleEnded/page.jsx | 5 +- app/visualizer/searching/binarysearch/code.js | 171 +++++++ .../searching/binarysearch/codeBlock.jsx | 323 ------------- .../searching/binarysearch/page.jsx | 5 +- app/visualizer/searching/linearsearch/code.js | 122 +++++ .../searching/linearsearch/codeBlock.jsx | 274 ----------- .../searching/linearsearch/page.jsx | 5 +- app/visualizer/sorting/bubblesort/code.js | 172 +++++++ .../sorting/bubblesort/codeBlock.jsx | 324 ------------- app/visualizer/sorting/bubblesort/page.jsx | 5 +- app/visualizer/sorting/insertionsort/code.js | 181 ++++++++ .../sorting/insertionsort/codeBlock.jsx | 333 -------------- app/visualizer/sorting/insertionsort/page.jsx | 5 +- app/visualizer/sorting/mergesort/code.js | 267 +++++++++++ .../sorting/mergesort/codeBlock.jsx | 422 ----------------- app/visualizer/sorting/mergesort/page.jsx | 5 +- app/visualizer/sorting/quicksort/code.js | 214 +++++++++ .../sorting/quicksort/codeBlock.jsx | 369 --------------- app/visualizer/sorting/quicksort/page.jsx | 5 +- app/visualizer/sorting/selectionsort/code.js | 172 +++++++ .../sorting/selectionsort/codeBlock.jsx | 327 ------------- app/visualizer/sorting/selectionsort/page.jsx | 5 +- .../usingArray/{codeBlock.jsx => code.js} | 159 +------ .../stack/implementation/usingArray/page.jsx | 5 +- .../{codeBlock.jsx => code.js} | 159 +------ .../implementation/usingLinkedList/page.jsx | 5 +- .../stack/isempty/{codeBlock.jsx => code.js} | 159 +------ app/visualizer/stack/isempty/page.jsx | 5 +- .../stack/isfull/{codeBlock.jsx => code.js} | 159 +------ app/visualizer/stack/isfull/page.jsx | 5 +- .../stack/peek/{codeBlock.jsx => code.js} | 159 +------ app/visualizer/stack/peek/page.jsx | 5 +- app/visualizer/stack/polish/postfix/code.js | 161 +++++++ .../stack/polish/postfix/codeBlock.jsx | 316 ------------- app/visualizer/stack/polish/postfix/page.jsx | 5 +- app/visualizer/stack/polish/prefix/code.js | 168 +++++++ .../stack/polish/prefix/codeBlock.jsx | 323 ------------- app/visualizer/stack/polish/prefix/page.jsx | 5 +- app/visualizer/stack/push-pop/code.js | 260 +++++++++++ app/visualizer/stack/push-pop/codeBlock.jsx | 415 ----------------- app/visualizer/stack/push-pop/page.jsx | 5 +- .../trees/binaryTree/types/animation.jsx | 5 +- app/visualizer/trees/binaryTree/types/code.js | 165 +++++++ .../trees/binaryTree/types/codeBlock.jsx | 320 ------------- 92 files changed, 2933 insertions(+), 8014 deletions(-) create mode 100755 app/components/modules/CodeBlock.jsx rename app/visualizer/linkedList/operations/comparison/{data/codeExamples.json => code.js} (96%) delete mode 100755 app/visualizer/linkedList/operations/comparison/codeBlock.jsx rename app/visualizer/linkedList/operations/deletion/{data/codeExamples.json => code.js} (99%) delete mode 100755 app/visualizer/linkedList/operations/deletion/codeBlock.jsx rename app/visualizer/linkedList/operations/insertion/{data/codeExamples.json => code.js} (99%) delete mode 100755 app/visualizer/linkedList/operations/insertion/codeBlock.jsx delete mode 100755 app/visualizer/linkedList/operations/merge/._codeBlock.jsx rename app/visualizer/linkedList/operations/merge/{data/codeExamples.json => code.js} (97%) delete mode 100755 app/visualizer/linkedList/operations/merge/codeBlock.jsx create mode 100755 app/visualizer/linkedList/operations/reverse/code.js delete mode 100755 app/visualizer/linkedList/operations/reverse/codeBlock.jsx delete mode 100755 app/visualizer/linkedList/operations/reverse/data/codeExamples.json rename app/visualizer/linkedList/operations/traversal/{data/codeExamples.json => code.js} (97%) delete mode 100755 app/visualizer/linkedList/operations/traversal/codeBlock.jsx rename app/visualizer/linkedList/types/circular/{codeBlock.jsx => code.js} (79%) rename app/visualizer/linkedList/types/doubly/{codeBlock.jsx => code.js} (79%) rename app/visualizer/linkedList/types/singly/{codeBlock.jsx => code.js} (70%) rename app/visualizer/queue/implementation/linkedList/{codeBlock.jsx => code.js} (52%) create mode 100755 app/visualizer/queue/operations/enqueue-dequeue/code.js delete mode 100755 app/visualizer/queue/operations/enqueue-dequeue/codeBlock.jsx create mode 100755 app/visualizer/queue/operations/isempty/code.js delete mode 100755 app/visualizer/queue/operations/isempty/codeBlock.jsx create mode 100755 app/visualizer/queue/operations/isfull/code.js delete mode 100755 app/visualizer/queue/operations/isfull/codeBlock.jsx create mode 100755 app/visualizer/queue/operations/peek-front/code.js delete mode 100755 app/visualizer/queue/operations/peek-front/codeBlock.jsx rename app/visualizer/queue/types/circular/{codeBlock.jsx => code.js} (64%) rename app/visualizer/queue/types/deque/{codeBlock.jsx => code.js} (72%) rename app/visualizer/queue/types/priority/{codeBlock.jsx => code.js} (62%) rename app/visualizer/queue/types/singleEnded/{codeBlock.jsx => code.js} (60%) create mode 100755 app/visualizer/searching/binarysearch/code.js delete mode 100755 app/visualizer/searching/binarysearch/codeBlock.jsx create mode 100755 app/visualizer/searching/linearsearch/code.js delete mode 100755 app/visualizer/searching/linearsearch/codeBlock.jsx create mode 100755 app/visualizer/sorting/bubblesort/code.js delete mode 100755 app/visualizer/sorting/bubblesort/codeBlock.jsx create mode 100755 app/visualizer/sorting/insertionsort/code.js delete mode 100755 app/visualizer/sorting/insertionsort/codeBlock.jsx create mode 100755 app/visualizer/sorting/mergesort/code.js delete mode 100755 app/visualizer/sorting/mergesort/codeBlock.jsx create mode 100755 app/visualizer/sorting/quicksort/code.js delete mode 100755 app/visualizer/sorting/quicksort/codeBlock.jsx create mode 100755 app/visualizer/sorting/selectionsort/code.js delete mode 100755 app/visualizer/sorting/selectionsort/codeBlock.jsx rename app/visualizer/stack/implementation/usingArray/{codeBlock.jsx => code.js} (57%) rename app/visualizer/stack/implementation/usingLinkedList/{codeBlock.jsx => code.js} (58%) rename app/visualizer/stack/isempty/{codeBlock.jsx => code.js} (51%) rename app/visualizer/stack/isfull/{codeBlock.jsx => code.js} (55%) rename app/visualizer/stack/peek/{codeBlock.jsx => code.js} (50%) create mode 100755 app/visualizer/stack/polish/postfix/code.js delete mode 100755 app/visualizer/stack/polish/postfix/codeBlock.jsx create mode 100755 app/visualizer/stack/polish/prefix/code.js delete mode 100755 app/visualizer/stack/polish/prefix/codeBlock.jsx create mode 100755 app/visualizer/stack/push-pop/code.js delete mode 100755 app/visualizer/stack/push-pop/codeBlock.jsx create mode 100755 app/visualizer/trees/binaryTree/types/code.js delete mode 100755 app/visualizer/trees/binaryTree/types/codeBlock.jsx diff --git a/app/components/modules/CodeBlock.jsx b/app/components/modules/CodeBlock.jsx new file mode 100755 index 0000000..e7a31fa --- /dev/null +++ b/app/components/modules/CodeBlock.jsx @@ -0,0 +1,155 @@ +"use client"; +import { useState } from "react"; +import { FaCopy, FaCheck, FaCode } from "react-icons/fa"; +import { motion, AnimatePresence } from "framer-motion"; +import hljs from "highlight.js"; +import "highlight.js/styles/github.css"; +import "highlight.js/styles/github-dark.css"; + +const LANGUAGE_NAMES = { + javascript: "JavaScript", + python: "Python", + java: "Java", + c: "C", + cpp: "C++", +}; + +export const highlightCode = (code, language) => { + const validLanguage = hljs.getLanguage(language) ? language : "plaintext"; + return hljs.highlight(code, { language: validLanguage }).value; +}; + +const CodeBlock = ({ title, codeExamples }) => { + const languageIds = Object.keys(codeExamples); + const [selectedLanguage, setSelectedLanguage] = useState(languageIds[0]); + const [copied, setCopied] = useState(false); + const [isHovered, setIsHovered] = useState(false); + + const copyToClipboard = async (text) => { + try { + await navigator.clipboard.writeText(text); + setCopied(true); + setTimeout(() => setCopied(false), 2000); + } catch (err) { + console.error("Failed to copy text: ", err); + } + }; + + return ( +
setIsHovered(true)} + onMouseLeave={() => setIsHovered(false)} + > + + {/* Header */} +
+
+ +

+ {title} +

+
+ + copyToClipboard(codeExamples[selectedLanguage])} + className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" + aria-label="Copy code" + > + + {copied ? ( + + Copied + + ) : ( + + Copy Code + + )} + + +
+ + {/* Language Selector */} +
+ {languageIds.map((id) => ( + setSelectedLanguage(id)} + className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ + selectedLanguage === id + ? "bg-blue-500 text-white shadow-md" + : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" + }`} + > + {LANGUAGE_NAMES[id] || id} + + ))} +
+ + {/* Code Block */} +
+ + +
+                
+              
+
+
+ + {/* Language indicator (shown on hover) */} + + {isHovered && ( + + {selectedLanguage.toUpperCase()} + + )} + +
+
+
+ ); +}; + +export default CodeBlock; diff --git a/app/visualizer/linkedList/operations/comparison/animation.jsx b/app/visualizer/linkedList/operations/comparison/animation.jsx index c6e9bc3..ead9709 100755 --- a/app/visualizer/linkedList/operations/comparison/animation.jsx +++ b/app/visualizer/linkedList/operations/comparison/animation.jsx @@ -5,7 +5,8 @@ import Footer from '@/app/components/footer'; import ExploreOther from '@/app/components/ui/exploreOther'; import Content from "@/app/visualizer/linkedList/operations/comparison/content"; import Quiz from '@/app/visualizer/linkedList/operations/comparison/quiz'; -import CodeBlock from "@/app/visualizer/linkedList/operations/comparison/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import BackToTop from '@/app/components/ui/backtotop'; import GoBackButton from "@/app/components/ui/goback"; @@ -279,7 +280,7 @@ const LinkedListComparison = () => {

- + \n#include \n#include \n\ntypedef struct Node {\n int data;\n struct Node* next;\n} Node;\n\nbool compareLists(Node* l1, Node* l2) {\n while (l1 && l2) {\n if (l1->data != l2->data) return false;\n l1 = l1->next;\n l2 = l2->next;\n }\n return l1 == NULL && l2 == NULL;\n}", "cpp": "#include \nusing namespace std;\n\nclass Node {\npublic:\n int data;\n Node* next;\n Node(int d) : data(d), next(nullptr) {}\n};\n\nbool compareLists(Node* l1, Node* l2) {\n while (l1 && l2) {\n if (l1->data != l2->data) return false;\n l1 = l1->next;\n l2 = l2->next;\n }\n return l1 == nullptr && l2 == nullptr;\n}" -} \ No newline at end of file +}; + +export default codeExamples; diff --git a/app/visualizer/linkedList/operations/comparison/codeBlock.jsx b/app/visualizer/linkedList/operations/comparison/codeBlock.jsx deleted file mode 100755 index fbd10bb..0000000 --- a/app/visualizer/linkedList/operations/comparison/codeBlock.jsx +++ /dev/null @@ -1,159 +0,0 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; -import CodeExamples from "@/app/visualizer/linkedList/operations/comparison/data/codeExamples.json"; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - -const codeExamples = CodeExamples; - - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Linked List Comparison Implementation -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                   
-                 
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); - }; - - export default CodeBlock; \ No newline at end of file diff --git a/app/visualizer/linkedList/operations/deletion/animation.jsx b/app/visualizer/linkedList/operations/deletion/animation.jsx index 8bf47ab..3a47961 100755 --- a/app/visualizer/linkedList/operations/deletion/animation.jsx +++ b/app/visualizer/linkedList/operations/deletion/animation.jsx @@ -5,7 +5,8 @@ import Footer from '@/app/components/footer'; import ExploreOther from '@/app/components/ui/exploreOther'; import Content from "@/app/visualizer/linkedList/operations/deletion/content"; import Quiz from '@/app/visualizer/linkedList/operations/deletion/quiz'; -import CodeBlock from "@/app/visualizer/linkedList/operations/deletion/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import BackToTop from '@/app/components/ui/backtotop'; import GoBackButton from "@/app/components/ui/goback"; @@ -236,7 +237,7 @@ const LinkedListVisualizer = () => {

- + = this.size) return null;\n if (index === 0) return this.deleteFirst();\n \n let current = this.head;\n for (let i = 0; i < index - 1; i++) {\n current = current.next;\n }\n \n const deletedNode = current.next;\n current.next = deletedNode.next;\n this.size--;\n return deletedNode.data;\n }\n\n // 4. Delete by value (first occurrence)\n deleteValue(value) {\n if (!this.head) return null;\n \n if (this.head.data === value) {\n return this.deleteFirst();\n }\n \n let current = this.head;\n while (current.next && current.next.data !== value) {\n current = current.next;\n }\n \n if (!current.next) return null;\n \n const deletedNode = current.next;\n current.next = deletedNode.next;\n this.size--;\n return deletedNode.data;\n }\n}", "python": "class SinglyLinkedList:\n # 1. Delete first node\n def delete_first(self):\n if not self.head:\n return None\n \n deleted_node = self.head\n self.head = self.head.next\n self.size -= 1\n return deleted_node.data\n \n # 2. Delete last node\n def delete_last(self):\n if not self.head:\n return None\n \n if not self.head.next:\n data = self.head.data\n self.head = None\n self.size -= 1\n return data\n \n current = self.head\n while current.next.next:\n current = current.next\n \n data = current.next.data\n current.next = None\n self.size -= 1\n return data\n \n # 3. Delete at specific index\n def delete_at(self, index):\n if index < 0 or index >= self.size:\n return None\n if index == 0:\n return self.delete_first()\n \n current = self.head\n for _ in range(index - 1):\n current = current.next\n \n deleted_node = current.next\n current.next = deleted_node.next\n self.size -= 1\n return deleted_node.data\n \n # 4. Delete by value (first occurrence)\n def delete_value(self, value):\n if not self.head:\n return None\n \n if self.head.data == value:\n return self.delete_first()\n \n current = self.head\n while current.next and current.next.data != value:\n current = current.next\n \n if not current.next:\n return None\n \n deleted_node = current.next\n current.next = deleted_node.next\n self.size -= 1\n return deleted_node.data", "java": "public class SinglyLinkedList {\n // 1. Delete first node\n public Integer deleteFirst() {\n if (head == null) return null;\n \n int data = head.data;\n head = head.next;\n size--;\n return data;\n }\n \n // 2. Delete last node\n public Integer deleteLast() {\n if (head == null) return null;\n \n if (head.next == null) {\n int data = head.data;\n head = null;\n size--;\n return data;\n }\n \n Node current = head;\n while (current.next.next != null) {\n current = current.next;\n }\n \n int data = current.next.data;\n current.next = null;\n size--;\n return data;\n }\n \n // 3. Delete at specific index\n public Integer deleteAt(int index) {\n if (index < 0 || index >= size) return null;\n if (index == 0) return deleteFirst();\n \n Node current = head;\n for (int i = 0; i < index - 1; i++) {\n current = current.next;\n }\n \n int data = current.next.data;\n current.next = current.next.next;\n size--;\n return data;\n }\n \n // 4. Delete by value (first occurrence)\n public Integer deleteValue(int value) {\n if (head == null) return null;\n \n if (head.data == value) {\n return deleteFirst();\n }\n \n Node current = head;\n while (current.next != null && current.next.data != value) {\n current = current.next;\n }\n \n if (current.next == null) return null;\n \n int data = current.next.data;\n current.next = current.next.next;\n size--;\n return data;\n }\n \n // Usage Example\n public static void main(String[] args) {\n SinglyLinkedList sll = new SinglyLinkedList();\n // Example of the insertion for insertion refer insertion article\n sll.insertLast(100);\n sll.insertLast(200);\n sll.insertLast(300);\n sll.insertLast(400);\n \n System.out.println(sll.deleteFirst()); // 100\n System.out.println(sll.deleteLast()); // 400\n System.out.println(sll.deleteAt(1)); // 300\n System.out.println(sll.deleteValue(200)); // 200\n }\n}", "c": "int deleteFirst(SinglyLinkedList* list) {\n if (list->head == NULL) return -1;\n \n Node* temp = list->head;\n int data = temp->data;\n list->head = list->head->next;\n free(temp);\n list->size--;\n return data;\n}\n\n// 2. Delete last node\nint deleteLast(SinglyLinkedList* list) {\n if (list->head == NULL) return -1;\n \n if (list->head->next == NULL) {\n int data = list->head->data;\n free(list->head);\n list->head = NULL;\n list->size--;\n return data;\n }\n \n Node* current = list->head;\n while (current->next->next != NULL) {\n current = current->next;\n }\n \n int data = current->next->data;\n free(current->next);\n current->next = NULL;\n list->size--;\n return data;\n}\n\n// 3. Delete at specific index\nint deleteAt(SinglyLinkedList* list, int index) {\n if (index < 0 || index >= list->size) return -1;\n if (index == 0) return deleteFirst(list);\n \n Node* current = list->head;\n for (int i = 0; i < index - 1; i++) {\n current = current->next;\n }\n \n Node* temp = current->next;\n int data = temp->data;\n current->next = temp->next;\n free(temp);\n list->size--;\n return data;\n}\n\n// 4. Delete by value (first occurrence)\nint deleteValue(SinglyLinkedList* list, int value) {\n if (list->head == NULL) return -1;\n \n if (list->head->data == value) {\n return deleteFirst(list);\n }\n \n Node* current = list->head;\n while (current->next != NULL && current->next->data != value) {\n current = current->next;\n }\n \n if (current->next == NULL) return -1;\n \n Node* temp = current->next;\n int data = temp->data;\n current->next = temp->next;\n free(temp);\n list->size--;\n return data;\n}", "cpp": "public:\n // 1. Delete first node\n int deleteFirst() {\n if (!head) throw std::out_of_range(\"List is empty\");\n \n Node* temp = head;\n int data = temp->data;\n head = head->next;\n delete temp;\n size--;\n return data;\n }\n \n // 2. Delete last node\n int deleteLast() {\n if (!head) throw std::out_of_range(\"List is empty\");\n \n if (!head->next) {\n int data = head->data;\n delete head;\n head = nullptr;\n size--;\n return data;\n }\n \n Node* current = head;\n while (current->next->next) {\n current = current->next;\n }\n \n int data = current->next->data;\n delete current->next;\n current->next = nullptr;\n size--;\n return data;\n }\n \n // 3. Delete at specific index\n int deleteAt(int index) {\n if (index < 0 || index >= size) throw std::out_of_range(\"Index out of range\");\n if (index == 0) return deleteFirst();\n \n Node* current = head;\n for (int i = 0; i < index - 1; i++) {\n current = current->next;\n }\n \n Node* temp = current->next;\n int data = temp->data;\n current->next = temp->next;\n delete temp;\n size--;\n return data;\n }\n \n // 4. Delete by value (first occurrence)\n int deleteValue(int value) {\n if (!head) throw std::out_of_range(\"List is empty\");\n \n if (head->data == value) {\n return deleteFirst();\n }\n \n Node* current = head;\n while (current->next && current->next->data != value) {\n current = current->next;\n }\n \n if (!current->next) throw std::out_of_range(\"Value not found\");\n \n Node* temp = current->next;\n int data = temp->data;\n current->next = temp->next;\n delete temp;\n size--;\n return data;\n }\n};" -} \ No newline at end of file +}; + +export default codeExamples; diff --git a/app/visualizer/linkedList/operations/deletion/codeBlock.jsx b/app/visualizer/linkedList/operations/deletion/codeBlock.jsx deleted file mode 100755 index 9b0b88b..0000000 --- a/app/visualizer/linkedList/operations/deletion/codeBlock.jsx +++ /dev/null @@ -1,159 +0,0 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; -import CodeExamples from "@/app/visualizer/linkedList/operations/deletion/data/codeExamples.json"; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - -const codeExamples = CodeExamples; - - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Linked List Deletion Implementation -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                   
-                 
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); - }; - - export default CodeBlock; \ No newline at end of file diff --git a/app/visualizer/linkedList/operations/insertion/animation.jsx b/app/visualizer/linkedList/operations/insertion/animation.jsx index d30d2b0..01d84ea 100755 --- a/app/visualizer/linkedList/operations/insertion/animation.jsx +++ b/app/visualizer/linkedList/operations/insertion/animation.jsx @@ -5,7 +5,8 @@ import Footer from '@/app/components/footer'; import ExploreOther from '@/app/components/ui/exploreOther'; import Content from "@/app/visualizer/linkedList/operations/insertion/content"; import Quiz from '@/app/visualizer/linkedList/operations/insertion/quiz'; -import CodeBlock from "@/app/visualizer/linkedList/operations/insertion/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import BackToTop from '@/app/components/ui/backtotop'; import GoBackButton from "@/app/components/ui/goback"; @@ -228,7 +229,7 @@ const LinkedListVisualizer = () => {

- + this.size) {\n console.log(\"Invalid index\");\n return;\n }\n \n if (index === 0) {\n this.insertFirst(data);\n return;\n }\n \n const newNode = new Node(data);\n let current = this.head;\n let count = 0;\n \n while (count < index - 1) {\n current = current.next;\n count++;\n }\n \n newNode.next = current.next;\n current.next = newNode;\n this.size++;\n }\n\n printList() {\n let current = this.head;\n let result = \"\";\n while (current) {\n result += current.data + \" -> \";\n current = current.next;\n }\n result += \"null\";\n console.log(result);\n }\n}\n\nconst sll = new SinglyLinkedList();\nsll.insertFirst(100);\nsll.insertFirst(200);\nsll.insertLast(300);\nsll.insertAt(500, 1);\nsll.printList();", "python": "class Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n\nclass SinglyLinkedList:\n def __init__(self):\n self.head = None\n self.size = 0\n \n # 1. Insert at beginning\n def insert_first(self, data):\n new_node = Node(data)\n new_node.next = self.head\n self.head = new_node\n self.size += 1\n \n # 2. Insert at end\n def insert_last(self, data):\n new_node = Node(data)\n \n if not self.head:\n self.head = new_node\n else:\n current = self.head\n while current.next:\n current = current.next\n current.next = new_node\n self.size += 1\n \n # 3. Insert at specific index\n def insert_at(self, data, index):\n if index < 0 or index > self.size:\n print(\"Invalid index\")\n return\n \n if index == 0:\n self.insert_first(data)\n return\n \n new_node = Node(data)\n current = self.head\n count = 0\n \n # Traverse to the node before the insertion point\n while count < index - 1:\n current = current.next\n count += 1\n \n new_node.next = current.next\n current.next = new_node\n self.size += 1\n \n # Print the list\n def print_list(self):\n current = self.head\n result = []\n while current:\n result.append(str(current.data))\n current = current.next\n print(\" -> \".join(result) + \" -> None\")\n\n# Usage Example\nsll = SinglyLinkedList()\nsll.insert_first(100) # List: 100 -> None\nsll.insert_first(200) # List: 200 -> 100 -> None\nsll.insert_last(300) # List: 200 -> 100 -> 300 -> None\nsll.insert_at(500, 1) # List: 200 -> 500 -> 100 -> 300 -> None\nsll.print_list()", "java": "public class SinglyLinkedList {\n private class Node {\n int data;\n Node next;\n \n Node(int data) {\n this.data = data;\n this.next = null;\n }\n }\n \n private Node head;\n private int size;\n \n public SinglyLinkedList() {\n head = null;\n size = 0;\n }\n \n // 1. Insert at beginning\n public void insertFirst(int data) {\n Node newNode = new Node(data);\n newNode.next = head;\n head = newNode;\n size++;\n }\n \n // 2. Insert at end\n public void insertLast(int data) {\n Node newNode = new Node(data);\n \n if (head == null) {\n head = newNode;\n } else {\n Node current = head;\n while (current.next != null) {\n current = current.next;\n }\n current.next = newNode;\n }\n size++;\n }\n \n // 3. Insert at specific index\n public void insertAt(int data, int index) {\n if (index < 0 || index > size) {\n System.out.println(\"Invalid index\");\n return;\n }\n \n if (index == 0) {\n insertFirst(data);\n return;\n }\n \n Node newNode = new Node(data);\n Node current = head;\n int count = 0;\n \n // Traverse to the node before the insertion point\n while (count < index - 1) {\n current = current.next;\n count++;\n }\n \n newNode.next = current.next;\n current.next = newNode;\n size++;\n }\n \n // Print the list\n public void printList() {\n Node current = head;\n while (current != null) {\n System.out.print(current.data + \" -> \");\n current = current.next;\n }\n System.out.println(\"null\");\n }\n \n // Usage Example\n public static void main(String[] args) {\n SinglyLinkedList sll = new SinglyLinkedList();\n sll.insertFirst(100); // List: 100 -> null\n sll.insertFirst(200); // List: 200 -> 100 -> null\n sll.insertLast(300); // List: 200 -> 100 -> 300 -> null\n sll.insertAt(500, 1); // List: 200 -> 500 -> 100 -> 300 -> null\n sll.printList();\n }\n}", "c": "#include \n#include \n\ntypedef struct Node {\n int data;\n struct Node* next;\n} Node;\n\ntypedef struct {\n Node* head;\n int size;\n} SinglyLinkedList;\n\nvoid initList(SinglyLinkedList* list) {\n list->head = NULL;\n list->size = 0;\n}\n\n// 1. Insert at beginning\nvoid insertFirst(SinglyLinkedList* list, int data) {\n Node* newNode = (Node*)malloc(sizeof(Node));\n newNode->data = data;\n newNode->next = list->head;\n list->head = newNode;\n list->size++;\n}\n\n// 2. Insert at end\nvoid insertLast(SinglyLinkedList* list, int data) {\n Node* newNode = (Node*)malloc(sizeof(Node));\n newNode->data = data;\n newNode->next = NULL;\n \n if (list->head == NULL) {\n list->head = newNode;\n } else {\n Node* current = list->head;\n while (current->next != NULL) {\n current = current->next;\n }\n current->next = newNode;\n }\n list->size++;\n}\n\n// 3. Insert at specific index\nvoid insertAt(SinglyLinkedList* list, int data, int index) {\n if (index < 0 || index > list->size) {\n printf(\"Invalid index\\n\");\n return;\n }\n \n if (index == 0) {\n insertFirst(list, data);\n return;\n }\n \n Node* newNode = (Node*)malloc(sizeof(Node));\n newNode->data = data;\n \n Node* current = list->head;\n int count = 0;\n \n // Traverse to the node before the insertion point\n while (count < index - 1) {\n current = current->next;\n count++;\n }\n \n newNode->next = current->next;\n current->next = newNode;\n list->size++;\n}\n\n// Print the list\nvoid printList(SinglyLinkedList* list) {\n Node* current = list->head;\n while (current != NULL) {\n printf(\"%d -> \", current->data);\n current = current->next;\n }\n printf(\"NULL\\n\");\n}\n\n// Usage Example\nint main() {\n SinglyLinkedList list;\n initList(&list);\n \n insertFirst(&list, 100); // List: 100 -> NULL\n insertFirst(&list, 200); // List: 200 -> 100 -> NULL\n insertLast(&list, 300); // List: 200 -> 100 -> 300 -> NULL\n insertAt(&list, 500, 1); // List: 200 -> 500 -> 100 -> 300 -> NULL\n printList(&list);\n \n return 0;\n}", "cpp": "#include \nusing namespace std;\n\nclass Node {\npublic:\n int data;\n Node* next;\n \n Node(int data) : data(data), next(nullptr) {}\n};\n\nclass SinglyLinkedList {\nprivate:\n Node* head;\n int size;\n \npublic:\n SinglyLinkedList() : head(nullptr), size(0) {}\n \n // 1. Insert at beginning\n void insertFirst(int data) {\n Node* newNode = new Node(data);\n newNode->next = head;\n head = newNode;\n size++;\n }\n \n // 2. Insert at end\n void insertLast(int data) {\n Node* newNode = new Node(data);\n \n if (head == nullptr) {\n head = newNode;\n } else {\n Node* current = head;\n while (current->next != nullptr) {\n current = current->next;\n }\n current->next = newNode;\n }\n size++;\n }\n \n // 3. Insert at specific index\n void insertAt(int data, int index) {\n if (index < 0 || index > size) {\n cout << \"Invalid index\" << endl;\n return;\n }\n \n if (index == 0) {\n insertFirst(data);\n return;\n }\n \n Node* newNode = new Node(data);\n Node* current = head;\n int count = 0;\n \n // Traverse to the node before the insertion point\n while (count < index - 1) {\n current = current->next;\n count++;\n }\n \n newNode->next = current->next;\n current->next = newNode;\n size++;\n }\n \n // Print the list\n void printList() {\n Node* current = head;\n while (current != nullptr) {\n cout << current->data << \" -> \";\n current = current->next;\n }\n cout << \"NULL\" << endl;\n }\n};\n\n// Usage Example\nint main() {\n SinglyLinkedList sll;\n sll.insertFirst(100); // List: 100 -> NULL\n sll.insertFirst(200); // List: 200 -> 100 -> NULL\n sll.insertLast(300); // List: 200 -> 100 -> 300 -> NULL\n sll.insertAt(500, 1); // List: 200 -> 500 -> 100 -> 300 -> NULL\n sll.printList();\n \n return 0;\n}" -} \ No newline at end of file +}; + +export default codeExamples; diff --git a/app/visualizer/linkedList/operations/insertion/codeBlock.jsx b/app/visualizer/linkedList/operations/insertion/codeBlock.jsx deleted file mode 100755 index 6773c57..0000000 --- a/app/visualizer/linkedList/operations/insertion/codeBlock.jsx +++ /dev/null @@ -1,159 +0,0 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; -import CodeExamples from "@/app/visualizer/linkedList/operations/insertion/data/codeExamples.json"; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - -const codeExamples = CodeExamples; - - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Linked List Insertion Implementation -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                   
-                 
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); - }; - - export default CodeBlock; \ No newline at end of file diff --git a/app/visualizer/linkedList/operations/merge/._codeBlock.jsx b/app/visualizer/linkedList/operations/merge/._codeBlock.jsx deleted file mode 100755 index c6b0cdc6b1d21af2047ffc9a63bd55f6427a9d8f..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4096 zcmZQz6=P>$Vqox1Ojhs@R)|o50+1L3ClDJkFz{^v(m+1nBL)UWIUt(=a103vf+zv$ zVAuo1QfOL0rh~-!85qQq^K22q5Xf};Gg z)V##Jzk~CclYeQobBSUjb3ll~r2CvUdS3lcqc?!`yN{)uWXb6mkz-S1JhQMeD zjE2By2#kinXb6mkz-S1JtPo%XdKZMjKrSRBvsj@hwK%`DC^=OjEx#yRAv3QeHLoNy mKQA#Sr&1v&HLXM;DJL;68`u|y>Kf7%s{i3$kztVg{~rLSw>GZ; diff --git a/app/visualizer/linkedList/operations/merge/animation.jsx b/app/visualizer/linkedList/operations/merge/animation.jsx index 24fda79..ac52d12 100755 --- a/app/visualizer/linkedList/operations/merge/animation.jsx +++ b/app/visualizer/linkedList/operations/merge/animation.jsx @@ -5,7 +5,8 @@ import Footer from '@/app/components/footer'; import ExploreOther from '@/app/components/ui/exploreOther'; import Content from "@/app/visualizer/linkedList/operations/merge/content"; import Quiz from '@/app/visualizer/linkedList/operations/merge/quiz'; -import CodeBlock from "@/app/visualizer/linkedList/operations/merge/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import BackToTop from '@/app/components/ui/backtotop'; import GoBackButton from "@/app/components/ui/goback"; @@ -392,7 +393,7 @@ const LinkedListMerge = () => {

- + \n#include \n\ntypedef struct Node {\n int data;\n struct Node* next;\n} Node;\n\nNode* mergeLists(Node* l1, Node* l2) {\n Node dummy;\n Node* current = &dummy;\n dummy.next = NULL;\n\n while (l1 && l2) {\n if (l1->data < l2->data) {\n current->next = l1;\n l1 = l1->next;\n } else {\n current->next = l2;\n l2 = l2->next;\n }\n current = current->next;\n }\n\n current->next = l1 ? l1 : l2;\n return dummy.next;\n}", "cpp": "#include \nusing namespace std;\n\nclass Node {\npublic:\n int data;\n Node* next;\n Node(int d) : data(d), next(nullptr) {}\n};\n\nNode* mergeLists(Node* l1, Node* l2) {\n Node dummy(0);\n Node* current = &dummy;\n\n while (l1 && l2) {\n if (l1->data < l2->data) {\n current->next = l1;\n l1 = l1->next;\n } else {\n current->next = l2;\n l2 = l2->next;\n }\n current = current->next;\n }\n\n current->next = l1 ? l1 : l2;\n return dummy.next;\n}" -} \ No newline at end of file +}; + +export default codeExamples; diff --git a/app/visualizer/linkedList/operations/merge/codeBlock.jsx b/app/visualizer/linkedList/operations/merge/codeBlock.jsx deleted file mode 100755 index bd6a315..0000000 --- a/app/visualizer/linkedList/operations/merge/codeBlock.jsx +++ /dev/null @@ -1,159 +0,0 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; -import CodeExamples from "@/app/visualizer/linkedList/operations/merge/data/codeExamples.json"; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - -const codeExamples = CodeExamples; - - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Linked List Merging Implementation -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                   
-                 
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); - }; - - export default CodeBlock; \ No newline at end of file diff --git a/app/visualizer/linkedList/operations/reverse/animation.jsx b/app/visualizer/linkedList/operations/reverse/animation.jsx index d690ca5..dcd16db 100755 --- a/app/visualizer/linkedList/operations/reverse/animation.jsx +++ b/app/visualizer/linkedList/operations/reverse/animation.jsx @@ -7,7 +7,8 @@ import BackToTop from '@/app/components/ui/backtotop'; import GoBackButton from "@/app/components/ui/goback"; import Content from "@/app/visualizer/linkedList/operations/reverse/content"; import Quiz from "@/app/visualizer/linkedList/operations/reverse/quiz"; -import CodeBlock from "@/app/visualizer/linkedList/operations/reverse/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; const LinkedListReverse = () => { const [list, setList] = useState([]); @@ -357,7 +358,7 @@ const LinkedListReverse = () => { Test Your Knowledge Before Moving Forward!

- + \n#include \n\ntypedef struct Node {\n int data;\n struct Node* next;\n} Node;\n\nNode* reverseList(Node* head) {\n Node* prev = NULL;\n Node* current = head;\n\n while (current) {\n Node* next = current->next;\n current->next = prev;\n prev = current;\n current = next;\n }\n\n return prev;\n}", + "cpp": "#include \nusing namespace std;\n\nclass Node {\npublic:\n int data;\n Node* next;\n Node(int d) : data(d), next(nullptr) {}\n};\n\nNode* reverseList(Node* head) {\n Node* prev = nullptr;\n Node* current = head;\n\n while (current) {\n Node* next = current->next;\n current->next = prev;\n prev = current;\n current = next;\n }\n\n return prev;\n}" +}; + +export default codeExamples; diff --git a/app/visualizer/linkedList/operations/reverse/codeBlock.jsx b/app/visualizer/linkedList/operations/reverse/codeBlock.jsx deleted file mode 100755 index 3e60a92..0000000 --- a/app/visualizer/linkedList/operations/reverse/codeBlock.jsx +++ /dev/null @@ -1,159 +0,0 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; -import CodeExamples from "@/app/visualizer/linkedList/operations/reverse/data/codeExamples.json"; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const codeExamples = CodeExamples - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Linked List Reversal Implementation -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                   
-                 
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); - }; - - export default CodeBlock; \ No newline at end of file diff --git a/app/visualizer/linkedList/operations/reverse/data/codeExamples.json b/app/visualizer/linkedList/operations/reverse/data/codeExamples.json deleted file mode 100755 index a3180d1..0000000 --- a/app/visualizer/linkedList/operations/reverse/data/codeExamples.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "javascript": "class Node {\n constructor(data) {\n this.data = data;\n this.next = null;\n }\n}\n\nfunction reverseList(head) {\n let prev = null;\n let current = head;\n\n while (current) {\n let next = current.next;\n current.next = prev;\n prev = current;\n current = next;\n }\n\n return prev;\n}", - "python": "class Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n\ndef reverse_list(head):\n prev = None\n current = head\n\n while current:\n next_node = current.next\n current.next = prev\n prev = current\n current = next_node\n\n return prev", - "java": "class Node {\n int data;\n Node next;\n Node(int data) {\n this.data = data;\n this.next = null;\n }\n}\n\npublic class ReverseList {\n public static Node reverse(Node head) {\n Node prev = null;\n Node current = head;\n\n while (current != null) {\n Node next = current.next;\n current.next = prev;\n prev = current;\n current = next;\n }\n\n return prev;\n }\n}", - "c": "#include \n#include \n\ntypedef struct Node {\n int data;\n struct Node* next;\n} Node;\n\nNode* reverseList(Node* head) {\n Node* prev = NULL;\n Node* current = head;\n\n while (current) {\n Node* next = current->next;\n current->next = prev;\n prev = current;\n current = next;\n }\n\n return prev;\n}", - "cpp": "#include \nusing namespace std;\n\nclass Node {\npublic:\n int data;\n Node* next;\n Node(int d) : data(d), next(nullptr) {}\n};\n\nNode* reverseList(Node* head) {\n Node* prev = nullptr;\n Node* current = head;\n\n while (current) {\n Node* next = current->next;\n current->next = prev;\n prev = current;\n current = next;\n }\n\n return prev;\n}" -} \ No newline at end of file diff --git a/app/visualizer/linkedList/operations/traversal/animation.jsx b/app/visualizer/linkedList/operations/traversal/animation.jsx index b45cf7a..a838119 100755 --- a/app/visualizer/linkedList/operations/traversal/animation.jsx +++ b/app/visualizer/linkedList/operations/traversal/animation.jsx @@ -5,7 +5,8 @@ import Footer from '@/app/components/footer'; import ExploreOther from '@/app/components/ui/exploreOther'; import Content from "@/app/visualizer/linkedList/operations/traversal/content"; import Quiz from '@/app/visualizer/linkedList/operations/traversal/quiz'; -import CodeBlock from "@/app/visualizer/linkedList/operations/traversal/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import BackToTop from '@/app/components/ui/backtotop'; import GoBackButton from "@/app/components/ui/goback"; @@ -283,7 +284,7 @@ const LinkedListTraversal = () => {

- + \n#include \n\nstruct Node {\n int data;\n struct Node* next;\n};\n\nvoid traverse(struct Node* head) {\n struct Node* current = head;\n while (current != NULL) {\n printf(\"%d\\n\", current->data);\n current = current->next;\n }\n}\n\nint main() {\n struct node * head = (struct node *)malloc(sizeof(struct node));\n struct node * second = (struct node *)malloc(sizeof(struct node));\n struct node * third = (struct node *)malloc(sizeof(struct node));\n\n head->data = 1;\n head->next = second;\n second->data = 2;\n second->next = third;\n third->data = 3;\n third->next = NULL;\n\n traverse(head);\n\n return 0;\n}", "cpp": "#include \nusing namespace std;\n\nclass Node {\npublic:\n int data;\n Node* next;\n Node(int data) : data(data), next(nullptr) {}\n};\n\nvoid traverse(Node* head) {\n Node* current = head;\n while (current != nullptr) {\n cout << current->data << endl;\n current = current->next;\n }\n}\n\nint main() {\n Node* head = new Node(1);\n head->next = new Node(2);\n head->next->next = new Node(3);\n traverse(head);\n\n // Free memory\n Node* temp;\n while (head != nullptr) {\n temp = head;\n head = head->next;\n delete temp;\n }\n\n return 0;\n}" -} \ No newline at end of file +}; + +export default codeExamples; diff --git a/app/visualizer/linkedList/operations/traversal/codeBlock.jsx b/app/visualizer/linkedList/operations/traversal/codeBlock.jsx deleted file mode 100755 index 2c401ea..0000000 --- a/app/visualizer/linkedList/operations/traversal/codeBlock.jsx +++ /dev/null @@ -1,159 +0,0 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; -import CodeExamples from "@/app/visualizer/linkedList/operations/traversal/data/codeExamples.json" - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - -const codeExamples = CodeExamples; - - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Linked List Insertion Implementation -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                   
-                 
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); - }; - - export default CodeBlock; \ No newline at end of file diff --git a/app/visualizer/linkedList/types/circular/codeBlock.jsx b/app/visualizer/linkedList/types/circular/code.js similarity index 79% rename from app/visualizer/linkedList/types/circular/codeBlock.jsx rename to app/visualizer/linkedList/types/circular/code.js index 5ebcab2..1bef04d 100755 --- a/app/visualizer/linkedList/types/circular/codeBlock.jsx +++ b/app/visualizer/linkedList/types/circular/code.js @@ -1,40 +1,3 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - const codeExamples = { javascript: `// Circular Linked List Implementation in JavaScript class Node { @@ -1031,122 +994,4 @@ int main() { }` }; - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Circular Linked List Implementation -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                   
-                 
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); - }; - - export default CodeBlock; \ No newline at end of file +export default codeExamples; diff --git a/app/visualizer/linkedList/types/circular/page.jsx b/app/visualizer/linkedList/types/circular/page.jsx index 166c7ff..91553db 100755 --- a/app/visualizer/linkedList/types/circular/page.jsx +++ b/app/visualizer/linkedList/types/circular/page.jsx @@ -5,7 +5,8 @@ import Footer from "@/app/components/footer"; import BackToTopButton from "@/app/components/ui/backtotop"; import Content from "./content"; import Quiz from "./quiz"; -import Code from "./codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import ModuleCard from "@/app/components/ui/ModuleCard"; import { MODULE_MAPS } from "@/lib/modulesMap"; import ExploreOther from "@/app/components/ui/exploreOther"; @@ -86,7 +87,7 @@ export default function Page() {
- +
diff --git a/app/visualizer/linkedList/types/doubly/animation.jsx b/app/visualizer/linkedList/types/doubly/animation.jsx index b36c79b..b95d559 100755 --- a/app/visualizer/linkedList/types/doubly/animation.jsx +++ b/app/visualizer/linkedList/types/doubly/animation.jsx @@ -5,7 +5,8 @@ import ResetButton from '@/app/components/ui/resetButton'; import ExploreOther from '@/app/components/ui/exploreOther'; import Content from "@/app/visualizer/linkedList/types/doubly/content"; import Quiz from '@/app/visualizer/linkedList/types/doubly/quiz'; -import CodeBlock from "@/app/visualizer/linkedList/types/doubly/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import BackToTop from '@/app/components/ui/backtotop'; import GoBackButton from "@/app/components/ui/goback"; @@ -211,7 +212,7 @@ const DoublyLinkedListVisualizer = () => {

- + { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - const codeExamples = { javascript: `// Doubly Linked List Implementation in JavaScript class Node { @@ -1038,122 +1001,4 @@ int main() { }` }; - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Doubly Linked List Implementation -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                   
-                 
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); - }; - - export default CodeBlock; \ No newline at end of file +export default codeExamples; diff --git a/app/visualizer/linkedList/types/singly/codeBlock.jsx b/app/visualizer/linkedList/types/singly/code.js similarity index 70% rename from app/visualizer/linkedList/types/singly/codeBlock.jsx rename to app/visualizer/linkedList/types/singly/code.js index c6213f8..ae4bdf1 100755 --- a/app/visualizer/linkedList/types/singly/codeBlock.jsx +++ b/app/visualizer/linkedList/types/singly/code.js @@ -1,40 +1,3 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - const codeExamples = { javascript: `// Singly Linked List Implementation in JavaScript class Node { @@ -682,122 +645,4 @@ int main() { }` }; - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Singly Linked List Implementation -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                   
-                 
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); - }; - - export default CodeBlock; \ No newline at end of file +export default codeExamples; diff --git a/app/visualizer/linkedList/types/singly/page.jsx b/app/visualizer/linkedList/types/singly/page.jsx index 994358e..ae4baca 100755 --- a/app/visualizer/linkedList/types/singly/page.jsx +++ b/app/visualizer/linkedList/types/singly/page.jsx @@ -3,7 +3,8 @@ import Navbar from "@/app/components/navbarinner"; import ModuleHeader from "@/app/components/modules/Header"; import Content from "@/app/visualizer/linkedList/types/singly/content"; import Quiz from "@/app/visualizer/linkedList/types/singly/quiz"; -import Code from "@/app/visualizer/linkedList/types/singly/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import ModuleCard from "@/app/components/ui/ModuleCard"; import { MODULE_MAPS } from "@/lib/modulesMap"; import ExploreOther from '@/app/components/ui/exploreOther'; @@ -75,7 +76,7 @@ export default function Page() {
- +
diff --git a/app/visualizer/queue/implementation/linkedList/codeBlock.jsx b/app/visualizer/queue/implementation/linkedList/code.js similarity index 52% rename from app/visualizer/queue/implementation/linkedList/codeBlock.jsx rename to app/visualizer/queue/implementation/linkedList/code.js index 3d0a1b3..e71b90e 100755 --- a/app/visualizer/queue/implementation/linkedList/codeBlock.jsx +++ b/app/visualizer/queue/implementation/linkedList/code.js @@ -1,40 +1,3 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - const codeExamples = { javascript: `// Queue Implementation in JavaScript (Linked List) class Node { @@ -339,122 +302,4 @@ int main() { }` }; - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Implementation Enqueue & Dequeue -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                
-              
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); -}; - -export default CodeBlock; \ No newline at end of file +export default codeExamples; diff --git a/app/visualizer/queue/implementation/linkedList/page.jsx b/app/visualizer/queue/implementation/linkedList/page.jsx index 6adfb73..aab5285 100755 --- a/app/visualizer/queue/implementation/linkedList/page.jsx +++ b/app/visualizer/queue/implementation/linkedList/page.jsx @@ -1,7 +1,8 @@ import Navbar from "@/app/components/navbarinner"; import ModuleHeader from "@/app/components/modules/Header"; import Content from "@/app/visualizer/queue/implementation/linkedList/content"; -import Code from "@/app/visualizer/queue/implementation/linkedList/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import ModuleCard from "@/app/components/ui/ModuleCard"; import { MODULE_MAPS } from "@/lib/modulesMap"; import ExploreOther from "@/app/components/ui/exploreOther"; @@ -62,7 +63,7 @@ export default function Page() {
- +
diff --git a/app/visualizer/queue/operations/enqueue-dequeue/code.js b/app/visualizer/queue/operations/enqueue-dequeue/code.js new file mode 100755 index 0000000..807e905 --- /dev/null +++ b/app/visualizer/queue/operations/enqueue-dequeue/code.js @@ -0,0 +1,278 @@ +const codeExamples = { + javascript: `// Queue Implementation in JavaScript (Linked List) +class Node { + constructor(data) { + this.data = data; + this.next = null; + } +} + +class Queue { + constructor() { + this.front = null; + this.rear = null; + } + + // Add element to the rear (enqueue) + enqueue(item) { + const newNode = new Node(item); + if (this.rear === null) { + this.front = this.rear = newNode; + } else { + this.rear.next = newNode; + this.rear = newNode; + } + } + + // Remove element from front (dequeue) + dequeue() { + if (this.front === null) { + return "Queue Underflow"; + } + const temp = this.front; + this.front = temp.next; + + if (this.front === null) { + this.rear = null; + } + return temp.data; + } +} + +// Usage Example +const queue = new Queue(); +queue.enqueue(10); +queue.enqueue(20); +queue.enqueue(30); +console.log(queue.dequeue()); // 10 +console.log(queue.dequeue()); // 20`, + + python: `# Queue Implementation in Python (Linked List) +class Node: + def __init__(self, data): + self.data = data + self.next = None + +class Queue: + def __init__(self): + self.front = None + self.rear = None + + # Add element to the rear (enqueue) + def enqueue(self, item): + new_node = Node(item) + if self.rear is None: + self.front = self.rear = new_node + else: + self.rear.next = new_node + self.rear = new_node + + # Remove element from front (dequeue) + def dequeue(self): + if self.front is None: + return "Queue Underflow" + temp = self.front + self.front = temp.next + + if self.front is None: + self.rear = None + return temp.data + +# Usage Example +q = Queue() +q.enqueue(10) +q.enqueue(20) +q.enqueue(30) +print(q.dequeue()) # 10 +print(q.dequeue()) # 20`, + + java: `// Queue Implementation in Java (Array) +public class ArrayQueue { + private int[] arr; + private int front, rear, capacity; + + public ArrayQueue(int size) { + capacity = size; + arr = new int[capacity]; + front = rear = -1; + } + + // Add element to the rear (enqueue) + public void enqueue(int item) { + if ((rear + 1) % capacity == front) { + System.out.println("Queue Overflow"); + return; + } + if (front == -1) { + front = rear = 0; + } else { + rear = (rear + 1) % capacity; + } + arr[rear] = item; + } + + // Remove element from front (dequeue) + public int dequeue() { + if (front == -1) { + System.out.println("Queue Underflow"); + return -1; + } + int item = arr[front]; + if (front == rear) { + front = rear = -1; + } else { + front = (front + 1) % capacity; + } + return item; + } + + public static void main(String[] args) { + ArrayQueue queue = new ArrayQueue(5); + queue.enqueue(10); + queue.enqueue(20); + queue.enqueue(30); + System.out.println(queue.dequeue()); // 10 + System.out.println(queue.dequeue()); // 20 + } +}`, + + c: `// Queue Implementation in C (Array) +#include +#include + +#define MAX_SIZE 100 + +typedef struct { + int arr[MAX_SIZE]; + int front, rear; +} Queue; + +void initialize(Queue *q) { + q->front = q->rear = -1; +} + +bool isEmpty(Queue *q) { + return q->front == -1; +} + +bool isFull(Queue *q) { + return (q->rear + 1) % MAX_SIZE == q->front; +} + +// Add element to the rear (enqueue) +void enqueue(Queue *q, int item) { + if (isFull(q)) { + printf("Queue Overflow\\n"); + return; + } + if (isEmpty(q)) { + q->front = q->rear = 0; + } else { + q->rear = (q->rear + 1) % MAX_SIZE; + } + q->arr[q->rear] = item; +} + +// Remove element from front (dequeue) +int dequeue(Queue *q) { + if (isEmpty(q)) { + printf("Queue Underflow\\n"); + return -1; + } + int item = q->arr[q->front]; + if (q->front == q->rear) { + q->front = q->rear = -1; + } else { + q->front = (q->front + 1) % MAX_SIZE; + } + return item; +} + +int main() { + Queue q; + initialize(&q); + + enqueue(&q, 10); + enqueue(&q, 20); + enqueue(&q, 30); + + printf("%d\\n", dequeue(&q)); // 10 + printf("%d\\n", dequeue(&q)); // 20 + + return 0; +}`, + + cpp: `// Queue Implementation in C++ (Linked List) +#include +using namespace std; + +class Node { +public: + int data; + Node* next; + + Node(int val) : data(val), next(nullptr) {} +}; + +class Queue { +private: + Node* front; + Node* rear; + +public: + Queue() : front(nullptr), rear(nullptr) {} + + ~Queue() { + while (!isEmpty()) { + dequeue(); + } + } + + // Add element to the rear (enqueue) + void enqueue(int item) { + Node* newNode = new Node(item); + if (rear == nullptr) { + front = rear = newNode; + } else { + rear->next = newNode; + rear = newNode; + } + } + + // Remove element from front (dequeue) + int dequeue() { + if (front == nullptr) { + cout << "Queue Underflow" << endl; + return -1; + } + Node* temp = front; + int item = temp->data; + front = front->next; + + if (front == nullptr) { + rear = nullptr; + } + + delete temp; + return item; + } + + bool isEmpty() const { + return front == nullptr; + } +}; + +int main() { + Queue q; + q.enqueue(10); + q.enqueue(20); + q.enqueue(30); + + cout << q.dequeue() << endl; // 10 + cout << q.dequeue() << endl; // 20 + + return 0; +}`, + }; + +export default codeExamples; diff --git a/app/visualizer/queue/operations/enqueue-dequeue/codeBlock.jsx b/app/visualizer/queue/operations/enqueue-dequeue/codeBlock.jsx deleted file mode 100755 index 261ddf2..0000000 --- a/app/visualizer/queue/operations/enqueue-dequeue/codeBlock.jsx +++ /dev/null @@ -1,433 +0,0 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - - const codeExamples = { - javascript: `// Queue Implementation in JavaScript (Linked List) -class Node { - constructor(data) { - this.data = data; - this.next = null; - } -} - -class Queue { - constructor() { - this.front = null; - this.rear = null; - } - - // Add element to the rear (enqueue) - enqueue(item) { - const newNode = new Node(item); - if (this.rear === null) { - this.front = this.rear = newNode; - } else { - this.rear.next = newNode; - this.rear = newNode; - } - } - - // Remove element from front (dequeue) - dequeue() { - if (this.front === null) { - return "Queue Underflow"; - } - const temp = this.front; - this.front = temp.next; - - if (this.front === null) { - this.rear = null; - } - return temp.data; - } -} - -// Usage Example -const queue = new Queue(); -queue.enqueue(10); -queue.enqueue(20); -queue.enqueue(30); -console.log(queue.dequeue()); // 10 -console.log(queue.dequeue()); // 20`, - - python: `# Queue Implementation in Python (Linked List) -class Node: - def __init__(self, data): - self.data = data - self.next = None - -class Queue: - def __init__(self): - self.front = None - self.rear = None - - # Add element to the rear (enqueue) - def enqueue(self, item): - new_node = Node(item) - if self.rear is None: - self.front = self.rear = new_node - else: - self.rear.next = new_node - self.rear = new_node - - # Remove element from front (dequeue) - def dequeue(self): - if self.front is None: - return "Queue Underflow" - temp = self.front - self.front = temp.next - - if self.front is None: - self.rear = None - return temp.data - -# Usage Example -q = Queue() -q.enqueue(10) -q.enqueue(20) -q.enqueue(30) -print(q.dequeue()) # 10 -print(q.dequeue()) # 20`, - - java: `// Queue Implementation in Java (Array) -public class ArrayQueue { - private int[] arr; - private int front, rear, capacity; - - public ArrayQueue(int size) { - capacity = size; - arr = new int[capacity]; - front = rear = -1; - } - - // Add element to the rear (enqueue) - public void enqueue(int item) { - if ((rear + 1) % capacity == front) { - System.out.println("Queue Overflow"); - return; - } - if (front == -1) { - front = rear = 0; - } else { - rear = (rear + 1) % capacity; - } - arr[rear] = item; - } - - // Remove element from front (dequeue) - public int dequeue() { - if (front == -1) { - System.out.println("Queue Underflow"); - return -1; - } - int item = arr[front]; - if (front == rear) { - front = rear = -1; - } else { - front = (front + 1) % capacity; - } - return item; - } - - public static void main(String[] args) { - ArrayQueue queue = new ArrayQueue(5); - queue.enqueue(10); - queue.enqueue(20); - queue.enqueue(30); - System.out.println(queue.dequeue()); // 10 - System.out.println(queue.dequeue()); // 20 - } -}`, - - c: `// Queue Implementation in C (Array) -#include -#include - -#define MAX_SIZE 100 - -typedef struct { - int arr[MAX_SIZE]; - int front, rear; -} Queue; - -void initialize(Queue *q) { - q->front = q->rear = -1; -} - -bool isEmpty(Queue *q) { - return q->front == -1; -} - -bool isFull(Queue *q) { - return (q->rear + 1) % MAX_SIZE == q->front; -} - -// Add element to the rear (enqueue) -void enqueue(Queue *q, int item) { - if (isFull(q)) { - printf("Queue Overflow\\n"); - return; - } - if (isEmpty(q)) { - q->front = q->rear = 0; - } else { - q->rear = (q->rear + 1) % MAX_SIZE; - } - q->arr[q->rear] = item; -} - -// Remove element from front (dequeue) -int dequeue(Queue *q) { - if (isEmpty(q)) { - printf("Queue Underflow\\n"); - return -1; - } - int item = q->arr[q->front]; - if (q->front == q->rear) { - q->front = q->rear = -1; - } else { - q->front = (q->front + 1) % MAX_SIZE; - } - return item; -} - -int main() { - Queue q; - initialize(&q); - - enqueue(&q, 10); - enqueue(&q, 20); - enqueue(&q, 30); - - printf("%d\\n", dequeue(&q)); // 10 - printf("%d\\n", dequeue(&q)); // 20 - - return 0; -}`, - - cpp: `// Queue Implementation in C++ (Linked List) -#include -using namespace std; - -class Node { -public: - int data; - Node* next; - - Node(int val) : data(val), next(nullptr) {} -}; - -class Queue { -private: - Node* front; - Node* rear; - -public: - Queue() : front(nullptr), rear(nullptr) {} - - ~Queue() { - while (!isEmpty()) { - dequeue(); - } - } - - // Add element to the rear (enqueue) - void enqueue(int item) { - Node* newNode = new Node(item); - if (rear == nullptr) { - front = rear = newNode; - } else { - rear->next = newNode; - rear = newNode; - } - } - - // Remove element from front (dequeue) - int dequeue() { - if (front == nullptr) { - cout << "Queue Underflow" << endl; - return -1; - } - Node* temp = front; - int item = temp->data; - front = front->next; - - if (front == nullptr) { - rear = nullptr; - } - - delete temp; - return item; - } - - bool isEmpty() const { - return front == nullptr; - } -}; - -int main() { - Queue q; - q.enqueue(10); - q.enqueue(20); - q.enqueue(30); - - cout << q.dequeue() << endl; // 10 - cout << q.dequeue() << endl; // 20 - - return 0; -}`, - }; - - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Queue (Enqueue & Dequeue) -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                
-              
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); -}; - -export default CodeBlock; \ No newline at end of file diff --git a/app/visualizer/queue/operations/enqueue-dequeue/page.jsx b/app/visualizer/queue/operations/enqueue-dequeue/page.jsx index 138ea46..c77b235 100755 --- a/app/visualizer/queue/operations/enqueue-dequeue/page.jsx +++ b/app/visualizer/queue/operations/enqueue-dequeue/page.jsx @@ -3,7 +3,8 @@ import Navbar from "@/app/components/navbarinner"; import ModuleHeader from "@/app/components/modules/Header"; import Content from "@/app/visualizer/queue/operations/enqueue-dequeue/content"; import Quiz from "@/app/visualizer/queue/operations/enqueue-dequeue/quiz"; -import Code from "@/app/visualizer/queue/operations/enqueue-dequeue/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import ModuleCard from "@/app/components/ui/ModuleCard"; import { MODULE_MAPS } from "@/lib/modulesMap"; import ExploreOther from "@/app/components/ui/exploreOther"; @@ -74,7 +75,7 @@ export default function Page() {
- +
diff --git a/app/visualizer/queue/operations/isempty/code.js b/app/visualizer/queue/operations/isempty/code.js new file mode 100755 index 0000000..bcd0668 --- /dev/null +++ b/app/visualizer/queue/operations/isempty/code.js @@ -0,0 +1,89 @@ +const codeExamples = { + javascript: `// Queue Implementation in JavaScript (Linked List) +class Queue { + constructor() { + this.front = null; + this.rear = null; + } + + // Check if queue is empty + isEmpty() { + return this.front === null; + } +}`, + + python: `# Queue Implementation in Python (Linked List) +class Queue: + def __init__(self): + self.front = None + self.rear = None + + # Check if queue is empty + def is_empty(self): + return self.front is None`, + + java: `// Queue Implementation in Java (Array) +public class ArrayQueue { + private int front, rear; + private int[] arr; + + public ArrayQueue(int size) { + arr = new int[size]; + front = rear = -1; + } + + // Check if queue is empty + public boolean isEmpty() { + return front == -1; + } +}`, + + c: `// Queue Implementation in C (Array) +#include +#define MAX_SIZE 100 + +typedef struct { + int arr[MAX_SIZE]; + int front, rear; +} Queue; + +// Check if queue is empty +bool isEmpty(Queue *q) { + return q->front == -1; +}`, + + cpp: `// Queue Implementation in C++ (Linked List) +#include + +class Node { +public: + int data; + Node* next; + + Node(int val) : data(val), next(nullptr) {} +}; + +class Queue { +private: + Node* front; + Node* rear; + +public: + Queue() : front(nullptr), rear(nullptr) {} + + ~Queue() { + while (front != nullptr) { + Node* temp = front; + front = front->next; + delete temp; + } + } + + // Check if queue is empty + bool isEmpty() const { + return front == nullptr; + } +};` + }; + +export default codeExamples; diff --git a/app/visualizer/queue/operations/isempty/codeBlock.jsx b/app/visualizer/queue/operations/isempty/codeBlock.jsx deleted file mode 100755 index c839aee..0000000 --- a/app/visualizer/queue/operations/isempty/codeBlock.jsx +++ /dev/null @@ -1,244 +0,0 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - - const codeExamples = { - javascript: `// Queue Implementation in JavaScript (Linked List) -class Queue { - constructor() { - this.front = null; - this.rear = null; - } - - // Check if queue is empty - isEmpty() { - return this.front === null; - } -}`, - - python: `# Queue Implementation in Python (Linked List) -class Queue: - def __init__(self): - self.front = None - self.rear = None - - # Check if queue is empty - def is_empty(self): - return self.front is None`, - - java: `// Queue Implementation in Java (Array) -public class ArrayQueue { - private int front, rear; - private int[] arr; - - public ArrayQueue(int size) { - arr = new int[size]; - front = rear = -1; - } - - // Check if queue is empty - public boolean isEmpty() { - return front == -1; - } -}`, - - c: `// Queue Implementation in C (Array) -#include -#define MAX_SIZE 100 - -typedef struct { - int arr[MAX_SIZE]; - int front, rear; -} Queue; - -// Check if queue is empty -bool isEmpty(Queue *q) { - return q->front == -1; -}`, - - cpp: `// Queue Implementation in C++ (Linked List) -#include - -class Node { -public: - int data; - Node* next; - - Node(int val) : data(val), next(nullptr) {} -}; - -class Queue { -private: - Node* front; - Node* rear; - -public: - Queue() : front(nullptr), rear(nullptr) {} - - ~Queue() { - while (front != nullptr) { - Node* temp = front; - front = front->next; - delete temp; - } - } - - // Check if queue is empty - bool isEmpty() const { - return front == nullptr; - } -};` - }; - - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Queue Implementation (IsEmpty) -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                    
-                  
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); - }; - - export default CodeBlock; \ No newline at end of file diff --git a/app/visualizer/queue/operations/isempty/page.jsx b/app/visualizer/queue/operations/isempty/page.jsx index 66f0b54..0023311 100755 --- a/app/visualizer/queue/operations/isempty/page.jsx +++ b/app/visualizer/queue/operations/isempty/page.jsx @@ -3,7 +3,8 @@ import Navbar from "@/app/components/navbarinner"; import ModuleHeader from "@/app/components/modules/Header"; import Content from "@/app/visualizer/queue/operations/isempty/content"; import Quiz from "@/app/visualizer/queue/operations/isempty/quiz"; -import Code from "@/app/visualizer/queue/operations/isempty/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import ModuleCard from "@/app/components/ui/ModuleCard"; import { MODULE_MAPS } from "@/lib/modulesMap"; import ExploreOther from '@/app/components/ui/exploreOther'; @@ -71,7 +72,7 @@ export default function Page() {
- +
diff --git a/app/visualizer/queue/operations/isfull/code.js b/app/visualizer/queue/operations/isfull/code.js new file mode 100755 index 0000000..0886823 --- /dev/null +++ b/app/visualizer/queue/operations/isfull/code.js @@ -0,0 +1,81 @@ +const codeExamples = { + javascript: `// Array Queue isFull in JavaScript +class ArrayQueue { + constructor(capacity) { + this.arr = new Array(capacity); + this.front = -1; + this.rear = -1; + this.capacity = capacity; + } + + isFull() { + return (this.rear + 1) % this.capacity === this.front; + } +}`, + + python: `# Array Queue isFull in Python +class ArrayQueue: + def __init__(self, capacity): + self.arr = [None] * capacity + self.front = -1 + self.rear = -1 + self.capacity = capacity + + def is_full(self): + return (self.rear + 1) % self.capacity == self.front`, + + java: `// Array Queue isFull in Java +public class ArrayQueue { + private int[] arr; + private int front, rear, capacity; + + public ArrayQueue(int size) { + capacity = size; + arr = new int[capacity]; + front = rear = -1; + } + + public boolean isFull() { + return (rear + 1) % capacity == front; + } +}`, + + c: `// Array Queue isFull in C +#include +#define MAX_SIZE 100 + +typedef struct { + int arr[MAX_SIZE]; + int front, rear; +} Queue; + +bool isFull(Queue *q) { + return (q->rear + 1) % MAX_SIZE == q->front; +}`, + + cpp: `// Array Queue isFull in C++ +#include + +class ArrayQueue { +private: + int* arr; + int front; + int rear; + int capacity; + +public: + ArrayQueue(int size) : front(-1), rear(-1), capacity(size) { + arr = new int[capacity]; + } + + ~ArrayQueue() { + delete[] arr; + } + + bool isFull() const { + return (rear + 1) % capacity == front; + } +};` + }; + +export default codeExamples; diff --git a/app/visualizer/queue/operations/isfull/codeBlock.jsx b/app/visualizer/queue/operations/isfull/codeBlock.jsx deleted file mode 100755 index e11b578..0000000 --- a/app/visualizer/queue/operations/isfull/codeBlock.jsx +++ /dev/null @@ -1,236 +0,0 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - - const codeExamples = { - javascript: `// Array Queue isFull in JavaScript -class ArrayQueue { - constructor(capacity) { - this.arr = new Array(capacity); - this.front = -1; - this.rear = -1; - this.capacity = capacity; - } - - isFull() { - return (this.rear + 1) % this.capacity === this.front; - } -}`, - - python: `# Array Queue isFull in Python -class ArrayQueue: - def __init__(self, capacity): - self.arr = [None] * capacity - self.front = -1 - self.rear = -1 - self.capacity = capacity - - def is_full(self): - return (self.rear + 1) % self.capacity == self.front`, - - java: `// Array Queue isFull in Java -public class ArrayQueue { - private int[] arr; - private int front, rear, capacity; - - public ArrayQueue(int size) { - capacity = size; - arr = new int[capacity]; - front = rear = -1; - } - - public boolean isFull() { - return (rear + 1) % capacity == front; - } -}`, - - c: `// Array Queue isFull in C -#include -#define MAX_SIZE 100 - -typedef struct { - int arr[MAX_SIZE]; - int front, rear; -} Queue; - -bool isFull(Queue *q) { - return (q->rear + 1) % MAX_SIZE == q->front; -}`, - - cpp: `// Array Queue isFull in C++ -#include - -class ArrayQueue { -private: - int* arr; - int front; - int rear; - int capacity; - -public: - ArrayQueue(int size) : front(-1), rear(-1), capacity(size) { - arr = new int[capacity]; - } - - ~ArrayQueue() { - delete[] arr; - } - - bool isFull() const { - return (rear + 1) % capacity == front; - } -};` - }; - - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Queue IsFull Operation -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                   
-                 
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); - }; - - export default CodeBlock; \ No newline at end of file diff --git a/app/visualizer/queue/operations/isfull/page.jsx b/app/visualizer/queue/operations/isfull/page.jsx index 0b018d5..b8e14bd 100755 --- a/app/visualizer/queue/operations/isfull/page.jsx +++ b/app/visualizer/queue/operations/isfull/page.jsx @@ -3,7 +3,8 @@ import Navbar from "@/app/components/navbarinner"; import ModuleHeader from "@/app/components/modules/Header"; import Content from "@/app/visualizer/queue/operations/isfull/content"; import Quiz from '@/app/visualizer/queue/operations/isfull/quiz'; -import Code from "@/app/visualizer/queue/operations/isfull/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import ModuleCard from "@/app/components/ui/ModuleCard"; import { MODULE_MAPS } from "@/lib/modulesMap"; import ExploreOther from '@/app/components/ui/exploreOther'; @@ -71,7 +72,7 @@ export default function page() {
- +
diff --git a/app/visualizer/queue/operations/peek-front/code.js b/app/visualizer/queue/operations/peek-front/code.js new file mode 100755 index 0000000..f26a6c1 --- /dev/null +++ b/app/visualizer/queue/operations/peek-front/code.js @@ -0,0 +1,124 @@ +const codeExamples = { + javascript: `// Queue peek (front) in JavaScript +class Queue { + constructor() { + this.items = []; + } + + // Get front element without removing + peek() { + if (this.isEmpty()) { + return "Queue is empty"; + } + return this.items[0]; + } + + // Helper method + isEmpty() { + return this.items.length === 0; + } +}`, + + python: `# Queue peek (front) in Python +class Queue: + def __init__(self): + self.items = [] + + # Get front element without removing + def peek(self): + if self.is_empty(): + return "Queue is empty" + return self.items[0] + + # Helper method + def is_empty(self): + return len(self.items) == 0`, + + java: `// Queue peek (front) in Java +import java.util.LinkedList; +import java.util.Queue; + +public class Main { + public static void main(String[] args) { + Queue queue = new LinkedList<>(); + + // Peek at front element + Integer front = queue.peek(); + System.out.println("Front element: " + front); + } +}`, + + c: `// Queue peek (front) in C +#include +#define MAX_SIZE 100 + +typedef struct { + int items[MAX_SIZE]; + int front, rear; +} Queue; + +int peek(Queue *q) { + if (q->front == -1) { + printf("Queue is empty\n"); + return -1; + } + return q->items[q->front]; +}`, + + cpp: `// Queue peek (front) in C++ +#include +#include + +int main() { + std::queue q; + + // Using STL queue's front() method + if (!q.empty()) { + std::cout << "Front element: " << q.front() << std::endl; + } else { + std::cout << "Queue is empty" << std::endl; + } + + // Custom queue implementation + class CustomQueue { + private: + struct Node { + int data; + Node* next; + Node(int val) : data(val), next(nullptr) {} + }; + Node* front; + Node* rear; + + public: + CustomQueue() : front(nullptr), rear(nullptr) {} + + ~CustomQueue() { + while (front != nullptr) { + Node* temp = front; + front = front->next; + delete temp; + } + } + + int peek() const { + if (front == nullptr) { + std::cout << "Queue is empty" << std::endl; + return -1; + } + return front->data; + } + + bool isEmpty() const { + return front == nullptr; + } + }; + + CustomQueue customQ; + std::cout << "Custom queue front: " << customQ.peek() << std::endl; + + return 0; +}` + }; + +export default codeExamples; diff --git a/app/visualizer/queue/operations/peek-front/codeBlock.jsx b/app/visualizer/queue/operations/peek-front/codeBlock.jsx deleted file mode 100755 index 882d98d..0000000 --- a/app/visualizer/queue/operations/peek-front/codeBlock.jsx +++ /dev/null @@ -1,279 +0,0 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - - const codeExamples = { - javascript: `// Queue peek (front) in JavaScript -class Queue { - constructor() { - this.items = []; - } - - // Get front element without removing - peek() { - if (this.isEmpty()) { - return "Queue is empty"; - } - return this.items[0]; - } - - // Helper method - isEmpty() { - return this.items.length === 0; - } -}`, - - python: `# Queue peek (front) in Python -class Queue: - def __init__(self): - self.items = [] - - # Get front element without removing - def peek(self): - if self.is_empty(): - return "Queue is empty" - return self.items[0] - - # Helper method - def is_empty(self): - return len(self.items) == 0`, - - java: `// Queue peek (front) in Java -import java.util.LinkedList; -import java.util.Queue; - -public class Main { - public static void main(String[] args) { - Queue queue = new LinkedList<>(); - - // Peek at front element - Integer front = queue.peek(); - System.out.println("Front element: " + front); - } -}`, - - c: `// Queue peek (front) in C -#include -#define MAX_SIZE 100 - -typedef struct { - int items[MAX_SIZE]; - int front, rear; -} Queue; - -int peek(Queue *q) { - if (q->front == -1) { - printf("Queue is empty\n"); - return -1; - } - return q->items[q->front]; -}`, - - cpp: `// Queue peek (front) in C++ -#include -#include - -int main() { - std::queue q; - - // Using STL queue's front() method - if (!q.empty()) { - std::cout << "Front element: " << q.front() << std::endl; - } else { - std::cout << "Queue is empty" << std::endl; - } - - // Custom queue implementation - class CustomQueue { - private: - struct Node { - int data; - Node* next; - Node(int val) : data(val), next(nullptr) {} - }; - Node* front; - Node* rear; - - public: - CustomQueue() : front(nullptr), rear(nullptr) {} - - ~CustomQueue() { - while (front != nullptr) { - Node* temp = front; - front = front->next; - delete temp; - } - } - - int peek() const { - if (front == nullptr) { - std::cout << "Queue is empty" << std::endl; - return -1; - } - return front->data; - } - - bool isEmpty() const { - return front == nullptr; - } - }; - - CustomQueue customQ; - std::cout << "Custom queue front: " << customQ.peek() << std::endl; - - return 0; -}` - }; - - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Queue Peek Front -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                 
-               
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); - }; - - export default CodeBlock; \ No newline at end of file diff --git a/app/visualizer/queue/operations/peek-front/page.jsx b/app/visualizer/queue/operations/peek-front/page.jsx index 6417065..ca95270 100755 --- a/app/visualizer/queue/operations/peek-front/page.jsx +++ b/app/visualizer/queue/operations/peek-front/page.jsx @@ -3,7 +3,8 @@ import Navbar from "@/app/components/navbarinner"; import ModuleHeader from "@/app/components/modules/Header"; import Content from "@/app/visualizer/queue/operations/peek-front/content"; import Quiz from "@/app/visualizer/queue/operations/peek-front/quiz"; -import Code from "@/app/visualizer/queue/operations/peek-front/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import ModuleCard from "@/app/components/ui/ModuleCard"; import { MODULE_MAPS } from "@/lib/modulesMap"; import ExploreOther from '@/app/components/ui/exploreOther'; @@ -73,7 +74,7 @@ export default function Page() {
- +
diff --git a/app/visualizer/queue/types/circular/codeBlock.jsx b/app/visualizer/queue/types/circular/code.js similarity index 64% rename from app/visualizer/queue/types/circular/codeBlock.jsx rename to app/visualizer/queue/types/circular/code.js index cc8da12..7e7612a 100755 --- a/app/visualizer/queue/types/circular/codeBlock.jsx +++ b/app/visualizer/queue/types/circular/code.js @@ -1,41 +1,4 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - - const codeExamples = { +const codeExamples = { javascript: `// Circular Queue Implementation (JavaScript) class CircularQueue { constructor(capacity) { @@ -543,122 +506,4 @@ int main() { }` }; - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Double Ended Queue Implementation -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                   
-                 
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); - }; - - export default CodeBlock; \ No newline at end of file +export default codeExamples; diff --git a/app/visualizer/queue/types/circular/page.jsx b/app/visualizer/queue/types/circular/page.jsx index 0b78e8e..001bb9b 100755 --- a/app/visualizer/queue/types/circular/page.jsx +++ b/app/visualizer/queue/types/circular/page.jsx @@ -3,7 +3,8 @@ import Navbar from "@/app/components/navbarinner"; import ModuleHeader from "@/app/components/modules/Header"; import Content from "@/app/visualizer/queue/types/circular/content"; import Quiz from "@/app/visualizer/queue/types/circular/quiz"; -import Code from "@/app/visualizer/queue/types/circular/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import ModuleCard from "@/app/components/ui/ModuleCard"; import { MODULE_MAPS } from "@/lib/modulesMap"; import ExploreOther from "@/app/components/ui/exploreOther"; @@ -71,7 +72,7 @@ export default function Page() {
- +
diff --git a/app/visualizer/queue/types/deque/codeBlock.jsx b/app/visualizer/queue/types/deque/code.js similarity index 72% rename from app/visualizer/queue/types/deque/codeBlock.jsx rename to app/visualizer/queue/types/deque/code.js index 2820970..2862fb5 100755 --- a/app/visualizer/queue/types/deque/codeBlock.jsx +++ b/app/visualizer/queue/types/deque/code.js @@ -1,41 +1,4 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - - const codeExamples = { +const codeExamples = { javascript: `// Double-Ended Queue Implementation (JavaScript) class Deque { constructor(size = 10) { @@ -748,122 +711,4 @@ int main() { }` }; - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Double Ended Queue Implementation -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                 
-               
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); - }; - - export default CodeBlock; \ No newline at end of file +export default codeExamples; diff --git a/app/visualizer/queue/types/deque/page.jsx b/app/visualizer/queue/types/deque/page.jsx index 309639a..7f1c726 100755 --- a/app/visualizer/queue/types/deque/page.jsx +++ b/app/visualizer/queue/types/deque/page.jsx @@ -3,7 +3,8 @@ import Navbar from "@/app/components/navbarinner"; import ModuleHeader from "@/app/components/modules/Header"; import Content from "@/app/visualizer/queue/types/deque/content"; import Quiz from "@/app/visualizer/queue/types/deque/quiz"; -import Code from "@/app/visualizer/queue/types/deque/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import ModuleCard from "@/app/components/ui/ModuleCard"; import { MODULE_MAPS } from "@/lib/modulesMap"; import ExploreOther from '@/app/components/ui/exploreOther'; @@ -71,7 +72,7 @@ export default function Page() {
- +
diff --git a/app/visualizer/queue/types/priority/codeBlock.jsx b/app/visualizer/queue/types/priority/code.js similarity index 62% rename from app/visualizer/queue/types/priority/codeBlock.jsx rename to app/visualizer/queue/types/priority/code.js index be83f38..dc1a629 100755 --- a/app/visualizer/queue/types/priority/codeBlock.jsx +++ b/app/visualizer/queue/types/priority/code.js @@ -1,41 +1,4 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - - const codeExamples = { +const codeExamples = { javascript: `// Priority Queue Implementation in JavaScript (Min-Heap) class PriorityQueue { constructor(comparator = (a, b) => a.priority - b.priority) { @@ -402,122 +365,4 @@ int main() { }` }; - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Double Ended Queue Implementation -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                 
-               
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); - }; - - export default CodeBlock; \ No newline at end of file +export default codeExamples; diff --git a/app/visualizer/queue/types/priority/page.jsx b/app/visualizer/queue/types/priority/page.jsx index 8332b79..733e8ea 100755 --- a/app/visualizer/queue/types/priority/page.jsx +++ b/app/visualizer/queue/types/priority/page.jsx @@ -3,7 +3,8 @@ import Navbar from "@/app/components/navbarinner"; import ModuleHeader from "@/app/components/modules/Header"; import Content from "@/app/visualizer/queue/types/priority/content"; import Quiz from "@/app/visualizer/queue/types/priority/quiz"; -import Code from "@/app/visualizer/queue/types/priority/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import ModuleCard from "@/app/components/ui/ModuleCard"; import { MODULE_MAPS } from "@/lib/modulesMap"; import ExploreOther from "@/app/components/ui/exploreOther"; @@ -75,7 +76,7 @@ export default function Page() {
- +
diff --git a/app/visualizer/queue/types/singleEnded/codeBlock.jsx b/app/visualizer/queue/types/singleEnded/code.js similarity index 60% rename from app/visualizer/queue/types/singleEnded/codeBlock.jsx rename to app/visualizer/queue/types/singleEnded/code.js index cfce87f..31a75ba 100755 --- a/app/visualizer/queue/types/singleEnded/codeBlock.jsx +++ b/app/visualizer/queue/types/singleEnded/code.js @@ -1,41 +1,4 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - - const codeExamples = { +const codeExamples = { javascript: `// Queue Implementation (JavaScript) class Queue { constructor(size = 10) { @@ -450,122 +413,4 @@ int main() { }` }; - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Single Ended Queue Implementation -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                 
-               
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); - }; - - export default CodeBlock; \ No newline at end of file +export default codeExamples; diff --git a/app/visualizer/queue/types/singleEnded/page.jsx b/app/visualizer/queue/types/singleEnded/page.jsx index 506c68c..57ea6af 100755 --- a/app/visualizer/queue/types/singleEnded/page.jsx +++ b/app/visualizer/queue/types/singleEnded/page.jsx @@ -3,7 +3,8 @@ import Navbar from "@/app/components/navbarinner"; import ModuleHeader from "@/app/components/modules/Header"; import Content from "@/app/visualizer/queue/types/singleEnded/content"; import Quiz from "@/app/visualizer/queue/types/singleEnded/quiz"; -import Code from "@/app/visualizer/queue/types/singleEnded/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import ModuleCard from "@/app/components/ui/ModuleCard"; import { MODULE_MAPS } from "@/lib/modulesMap"; import ExploreOther from '@/app/components/ui/exploreOther'; @@ -70,7 +71,7 @@ export default function Page() {
- +
diff --git a/app/visualizer/searching/binarysearch/code.js b/app/visualizer/searching/binarysearch/code.js new file mode 100755 index 0000000..7e7d338 --- /dev/null +++ b/app/visualizer/searching/binarysearch/code.js @@ -0,0 +1,171 @@ +const codeExamples = { + javascript: `// Binary Search in JavaScript (Iterative) +function binarySearch(arr, target) { + let left = 0; + let right = arr.length - 1; + + while (left <= right) { + const mid = Math.floor((left + right) / 2); + + if (arr[mid] === target) { + return mid; // Target found + } else if (arr[mid] < target) { + left = mid + 1; // Search right half + } else { + right = mid - 1; // Search left half + } + } + + return -1; // Target not found +} + +// Usage example +const sortedNumbers = [10, 20, 30, 40, 50, 60, 70]; +const target = 40; +const result = binarySearch(sortedNumbers, target); + +if (result !== -1) { + console.log(\`Element found at index: \${result}\`); +} else { + console.log("Element not found"); +}`, + + python: `# Binary Search in Python (Iterative) +def binary_search(arr, target): + left, right = 0, len(arr) - 1 + + while left <= right: + mid = (left + right) // 2 + + if arr[mid] == target: + return mid # Target found + elif arr[mid] < target: + left = mid + 1 # Search right half + else: + right = mid - 1 # Search left half + + return -1 # Target not found + +# Usage example +sorted_numbers = [10, 20, 30, 40, 50, 60, 70] +target = 40 +result = binary_search(sorted_numbers, target) + +if result != -1: + print(f"Element found at index: {result}") +else: + print("Element not found")`, + + java: `// Binary Search in Java (Iterative) +public class BinarySearch { + public static int binarySearch(int[] arr, int target) { + int left = 0; + int right = arr.length - 1; + + while (left <= right) { + int mid = left + (right - left) / 2; + + if (arr[mid] == target) { + return mid; // Target found + } else if (arr[mid] < target) { + left = mid + 1; // Search right half + } else { + right = mid - 1; // Search left half + } + } + + return -1; // Target not found + } + + public static void main(String[] args) { + int[] sortedNumbers = {10, 20, 30, 40, 50, 60, 70}; + int target = 40; + int result = binarySearch(sortedNumbers, target); + + if (result != -1) { + System.out.println("Element found at index: " + result); + } else { + System.out.println("Element not found"); + } + } +}`, + + c: `// Binary Search in C (Iterative) +#include + +int binarySearch(int arr[], int size, int target) { + int left = 0; + int right = size - 1; + + while (left <= right) { + int mid = left + (right - left) / 2; + + if (arr[mid] == target) { + return mid; // Target found + } else if (arr[mid] < target) { + left = mid + 1; // Search right half + } else { + right = mid - 1; // Search left half + } + } + + return -1; // Target not found +} + +int main() { + int sortedNumbers[] = {10, 20, 30, 40, 50, 60, 70}; + int size = sizeof(sortedNumbers) / sizeof(sortedNumbers[0]); + int target = 40; + + int result = binarySearch(sortedNumbers, size, target); + + if (result != -1) { + printf("Element found at index: %d\\n", result); + } else { + printf("Element not found\\n"); + } + + return 0; +}`, + + cpp: `// Binary Search in C++ (Iterative) +#include +#include +using namespace std; + +int binarySearch(const vector& arr, int target) { + int left = 0; + int right = arr.size() - 1; + + while (left <= right) { + int mid = left + (right - left) / 2; + + if (arr[mid] == target) { + return mid; // Target found + } else if (arr[mid] < target) { + left = mid + 1; // Search right half + } else { + right = mid - 1; // Search left half + } + } + + return -1; // Target not found +} + +int main() { + vector sortedNumbers = {10, 20, 30, 40, 50, 60, 70}; + int target = 40; + + int result = binarySearch(sortedNumbers, target); + + if (result != -1) { + cout << "Element found at index: " << result << endl; + } else { + cout << "Element not found" << endl; + } + + return 0; +}` + }; + +export default codeExamples; diff --git a/app/visualizer/searching/binarysearch/codeBlock.jsx b/app/visualizer/searching/binarysearch/codeBlock.jsx deleted file mode 100755 index e19c199..0000000 --- a/app/visualizer/searching/binarysearch/codeBlock.jsx +++ /dev/null @@ -1,323 +0,0 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState('javascript'); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: 'javascript', name: 'JavaScript' }, - { id: 'python', name: 'Python' }, - { id: 'java', name: 'Java' }, - { id: 'c', name: 'C' }, - { id: 'cpp', name: 'C++' } - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error('Failed to copy text: ', err); - } - }; - - const codeExamples = { - javascript: `// Binary Search in JavaScript (Iterative) -function binarySearch(arr, target) { - let left = 0; - let right = arr.length - 1; - - while (left <= right) { - const mid = Math.floor((left + right) / 2); - - if (arr[mid] === target) { - return mid; // Target found - } else if (arr[mid] < target) { - left = mid + 1; // Search right half - } else { - right = mid - 1; // Search left half - } - } - - return -1; // Target not found -} - -// Usage example -const sortedNumbers = [10, 20, 30, 40, 50, 60, 70]; -const target = 40; -const result = binarySearch(sortedNumbers, target); - -if (result !== -1) { - console.log(\`Element found at index: \${result}\`); -} else { - console.log("Element not found"); -}`, - - python: `# Binary Search in Python (Iterative) -def binary_search(arr, target): - left, right = 0, len(arr) - 1 - - while left <= right: - mid = (left + right) // 2 - - if arr[mid] == target: - return mid # Target found - elif arr[mid] < target: - left = mid + 1 # Search right half - else: - right = mid - 1 # Search left half - - return -1 # Target not found - -# Usage example -sorted_numbers = [10, 20, 30, 40, 50, 60, 70] -target = 40 -result = binary_search(sorted_numbers, target) - -if result != -1: - print(f"Element found at index: {result}") -else: - print("Element not found")`, - - java: `// Binary Search in Java (Iterative) -public class BinarySearch { - public static int binarySearch(int[] arr, int target) { - int left = 0; - int right = arr.length - 1; - - while (left <= right) { - int mid = left + (right - left) / 2; - - if (arr[mid] == target) { - return mid; // Target found - } else if (arr[mid] < target) { - left = mid + 1; // Search right half - } else { - right = mid - 1; // Search left half - } - } - - return -1; // Target not found - } - - public static void main(String[] args) { - int[] sortedNumbers = {10, 20, 30, 40, 50, 60, 70}; - int target = 40; - int result = binarySearch(sortedNumbers, target); - - if (result != -1) { - System.out.println("Element found at index: " + result); - } else { - System.out.println("Element not found"); - } - } -}`, - - c: `// Binary Search in C (Iterative) -#include - -int binarySearch(int arr[], int size, int target) { - int left = 0; - int right = size - 1; - - while (left <= right) { - int mid = left + (right - left) / 2; - - if (arr[mid] == target) { - return mid; // Target found - } else if (arr[mid] < target) { - left = mid + 1; // Search right half - } else { - right = mid - 1; // Search left half - } - } - - return -1; // Target not found -} - -int main() { - int sortedNumbers[] = {10, 20, 30, 40, 50, 60, 70}; - int size = sizeof(sortedNumbers) / sizeof(sortedNumbers[0]); - int target = 40; - - int result = binarySearch(sortedNumbers, size, target); - - if (result != -1) { - printf("Element found at index: %d\\n", result); - } else { - printf("Element not found\\n"); - } - - return 0; -}`, - - cpp: `// Binary Search in C++ (Iterative) -#include -#include -using namespace std; - -int binarySearch(const vector& arr, int target) { - int left = 0; - int right = arr.size() - 1; - - while (left <= right) { - int mid = left + (right - left) / 2; - - if (arr[mid] == target) { - return mid; // Target found - } else if (arr[mid] < target) { - left = mid + 1; // Search right half - } else { - right = mid - 1; // Search left half - } - } - - return -1; // Target not found -} - -int main() { - vector sortedNumbers = {10, 20, 30, 40, 50, 60, 70}; - int target = 40; - - int result = binarySearch(sortedNumbers, target); - - if (result != -1) { - cout << "Element found at index: " << result << endl; - } else { - cout << "Element not found" << endl; - } - - return 0; -}` - }; - - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Binary Search Implementation -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? 'bg-blue-500 text-white shadow-md' - : 'bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600' - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                
-              
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); -}; - -export default CodeBlock; \ No newline at end of file diff --git a/app/visualizer/searching/binarysearch/page.jsx b/app/visualizer/searching/binarysearch/page.jsx index 485ccfd..4d9bbfd 100755 --- a/app/visualizer/searching/binarysearch/page.jsx +++ b/app/visualizer/searching/binarysearch/page.jsx @@ -4,7 +4,8 @@ import ModuleHeader from "@/app/components/modules/Header"; import Footer from "@/app/components/footer"; import BackToTop from "@/app/components/ui/backtotop"; import ExploreOther from "@/app/components/ui/exploreOther"; -import Code from "@/app/visualizer/searching/binarysearch/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import Quiz from "@/app/visualizer/searching/binarysearch/quiz"; import Content from '@/app/visualizer/searching/binarysearch/content'; import ModuleCard from "@/app/components/ui/ModuleCard"; @@ -83,7 +84,7 @@ export default function Page() {
- +
diff --git a/app/visualizer/searching/linearsearch/code.js b/app/visualizer/searching/linearsearch/code.js new file mode 100755 index 0000000..6d1865c --- /dev/null +++ b/app/visualizer/searching/linearsearch/code.js @@ -0,0 +1,122 @@ +const codeExamples = { + javascript: `// Linear Search in JavaScript +function linearSearch(arr, target) { + for (let i = 0; i < arr.length; i++) { + if (arr[i] === target) { + return i; // Return index if found + } + } + return -1; // Return -1 if not found +} + +// Usage example +const numbers = [10, 20, 30, 40, 50]; +const target = 30; +const result = linearSearch(numbers, target); + +if (result !== -1) { + console.log(\`Element found at index: \${result}\`); +} else { + console.log("Element not found"); +}`, + + python: `# Linear Search in Python +def linear_search(arr, target): + for i in range(len(arr)): + if arr[i] == target: + return i # Return index if found + return -1 # Return -1 if not found + +# Usage example +numbers = [10, 20, 30, 40, 50] +target = 30 +result = linear_search(numbers, target) + +if result != -1: + print(f"Element found at index: {result}") +else: + print("Element not found")`, + + java: `// Linear Search in Java +public class LinearSearch { + public static int linearSearch(int[] arr, int target) { + for (int i = 0; i < arr.length; i++) { + if (arr[i] == target) { + return i; // Return index if found + } + } + return -1; // Return -1 if not found + } + + public static void main(String[] args) { + int[] numbers = {10, 20, 30, 40, 50}; + int target = 30; + int result = linearSearch(numbers, target); + + if (result != -1) { + System.out.println("Element found at index: " + result); + } else { + System.out.println("Element not found"); + } + } +}`, + + c: `// Linear Search in C +#include + +int linearSearch(int arr[], int size, int target) { + for (int i = 0; i < size; i++) { + if (arr[i] == target) { + return i; // Return index if found + } + } + return -1; // Return -1 if not found +} + +int main() { + int numbers[] = {10, 20, 30, 40, 50}; + int size = sizeof(numbers) / sizeof(numbers[0]); + int target = 30; + + int result = linearSearch(numbers, size, target); + + if (result != -1) { + printf("Element found at index: %d\\n", result); + } else { + printf("Element not found\\n"); + } + + return 0; +}`, + + cpp: `// Linear Search in C++ +#include +#include +using namespace std; + +int linearSearch(const vector& arr, int target) { + for (int i = 0; i < arr.size(); i++) { + if (arr[i] == target) { + return i; // Return index if found + } + } + return -1; // Return -1 if not found +} + +int main() { + vector numbers = {10, 20, 30, 40, 50}; + int target = 30; + + int result = linearSearch(numbers, target); + + if (result != -1) { + cout << "Element found at index: " << result << endl; + } else { + cout << "Element not found" << endl; + } + + return 0; +}` + }; + +export default codeExamples; diff --git a/app/visualizer/searching/linearsearch/codeBlock.jsx b/app/visualizer/searching/linearsearch/codeBlock.jsx deleted file mode 100755 index 380a676..0000000 --- a/app/visualizer/searching/linearsearch/codeBlock.jsx +++ /dev/null @@ -1,274 +0,0 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState('javascript'); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: 'javascript', name: 'JavaScript' }, - { id: 'python', name: 'Python' }, - { id: 'java', name: 'Java' }, - { id: 'c', name: 'C' }, - { id: 'cpp', name: 'C++' } - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error('Failed to copy text: ', err); - } - }; - - const codeExamples = { - javascript: `// Linear Search in JavaScript -function linearSearch(arr, target) { - for (let i = 0; i < arr.length; i++) { - if (arr[i] === target) { - return i; // Return index if found - } - } - return -1; // Return -1 if not found -} - -// Usage example -const numbers = [10, 20, 30, 40, 50]; -const target = 30; -const result = linearSearch(numbers, target); - -if (result !== -1) { - console.log(\`Element found at index: \${result}\`); -} else { - console.log("Element not found"); -}`, - - python: `# Linear Search in Python -def linear_search(arr, target): - for i in range(len(arr)): - if arr[i] == target: - return i # Return index if found - return -1 # Return -1 if not found - -# Usage example -numbers = [10, 20, 30, 40, 50] -target = 30 -result = linear_search(numbers, target) - -if result != -1: - print(f"Element found at index: {result}") -else: - print("Element not found")`, - - java: `// Linear Search in Java -public class LinearSearch { - public static int linearSearch(int[] arr, int target) { - for (int i = 0; i < arr.length; i++) { - if (arr[i] == target) { - return i; // Return index if found - } - } - return -1; // Return -1 if not found - } - - public static void main(String[] args) { - int[] numbers = {10, 20, 30, 40, 50}; - int target = 30; - int result = linearSearch(numbers, target); - - if (result != -1) { - System.out.println("Element found at index: " + result); - } else { - System.out.println("Element not found"); - } - } -}`, - - c: `// Linear Search in C -#include - -int linearSearch(int arr[], int size, int target) { - for (int i = 0; i < size; i++) { - if (arr[i] == target) { - return i; // Return index if found - } - } - return -1; // Return -1 if not found -} - -int main() { - int numbers[] = {10, 20, 30, 40, 50}; - int size = sizeof(numbers) / sizeof(numbers[0]); - int target = 30; - - int result = linearSearch(numbers, size, target); - - if (result != -1) { - printf("Element found at index: %d\\n", result); - } else { - printf("Element not found\\n"); - } - - return 0; -}`, - - cpp: `// Linear Search in C++ -#include -#include -using namespace std; - -int linearSearch(const vector& arr, int target) { - for (int i = 0; i < arr.size(); i++) { - if (arr[i] == target) { - return i; // Return index if found - } - } - return -1; // Return -1 if not found -} - -int main() { - vector numbers = {10, 20, 30, 40, 50}; - int target = 30; - - int result = linearSearch(numbers, target); - - if (result != -1) { - cout << "Element found at index: " << result << endl; - } else { - cout << "Element not found" << endl; - } - - return 0; -}` - }; - - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Linear Search Implementation -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? 'bg-blue-500 text-white shadow-md' - : 'bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600' - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                
-              
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); -}; - -export default CodeBlock; \ No newline at end of file diff --git a/app/visualizer/searching/linearsearch/page.jsx b/app/visualizer/searching/linearsearch/page.jsx index 7550214..3deb5b8 100755 --- a/app/visualizer/searching/linearsearch/page.jsx +++ b/app/visualizer/searching/linearsearch/page.jsx @@ -4,7 +4,8 @@ import ModuleHeader from "@/app/components/modules/Header"; import BackToTopButton from "@/app/components/ui/backtotop"; import Footer from "@/app/components/footer"; import ExploreOther from "@/app/components/ui/exploreOther"; -import Code from "@/app/visualizer/searching/linearsearch/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import Quiz from "@/app/visualizer/searching/linearsearch/quiz"; import Content from "@/app/visualizer/searching/linearsearch/content"; import ModuleCard from "@/app/components/ui/ModuleCard"; @@ -82,7 +83,7 @@ export default function Page() {
- +
diff --git a/app/visualizer/sorting/bubblesort/code.js b/app/visualizer/sorting/bubblesort/code.js new file mode 100755 index 0000000..b38c95d --- /dev/null +++ b/app/visualizer/sorting/bubblesort/code.js @@ -0,0 +1,172 @@ +const codeExamples = { + javascript: `// Bubble Sort in JavaScript +function bubbleSort(arr) { + let n = arr.length; + + // Outer loop for passes + for (let i = 0; i < n - 1; i++) { + // Inner loop for comparisons + for (let j = 0; j < n - i - 1; j++) { + // Swap if current element is greater than next + if (arr[j] > arr[j + 1]) { + // ES6 destructuring assignment for swap + [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]; + } + } + } + return arr; +} + +// Usage example +const unsortedArray = [64, 34, 25, 12, 22, 11, 90]; +console.log("Unsorted array:", unsortedArray); +const sortedArray = bubbleSort(unsortedArray); +console.log("Sorted array:", sortedArray);`, + + python: `# Bubble Sort in Python +def bubble_sort(arr): + n = len(arr) + + # Outer loop for passes + for i in range(n - 1): + # Inner loop for comparisons + for j in range(n - i - 1): + # Swap if current element is greater than next + if arr[j] > arr[j + 1]: + # Python tuple unpacking for swap + arr[j], arr[j + 1] = arr[j + 1], arr[j] + return arr + +# Usage example +unsorted_array = [64, 34, 25, 12, 22, 11, 90] +print("Unsorted array:", unsorted_array) +sorted_array = bubble_sort(unsorted_array) +print("Sorted array:", sorted_array)`, + + java: `// Bubble Sort in Java +public class BubbleSort { + public static void bubbleSort(int[] arr) { + int n = arr.length; + + // Outer loop for passes + for (int i = 0; i < n - 1; i++) { + // Inner loop for comparisons + for (int j = 0; j < n - i - 1; j++) { + // Swap if current element is greater than next + if (arr[j] > arr[j + 1]) { + // Traditional swap using temp variable + int temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + } + } + } + } + + public static void main(String[] args) { + int[] unsortedArray = {64, 34, 25, 12, 22, 11, 90}; + System.out.print("Unsorted array: "); + printArray(unsortedArray); + + bubbleSort(unsortedArray); + + System.out.print("Sorted array: "); + printArray(unsortedArray); + } + + // Helper method to print array + private static void printArray(int[] arr) { + for (int num : arr) { + System.out.print(num + " "); + } + System.out.println(); + } +}`, + + c: `// Bubble Sort in C +#include + +void bubbleSort(int arr[], int n) { + // Outer loop for passes + for (int i = 0; i < n - 1; i++) { + // Inner loop for comparisons + for (int j = 0; j < n - i - 1; j++) { + // Swap if current element is greater than next + if (arr[j] > arr[j + 1]) { + // Traditional swap using temp variable + int temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + } + } + } +} + +// Function to print an array +void printArray(int arr[], int size) { + for (int i = 0; i < size; i++) { + printf("%d ", arr[i]); + } + printf("\\n"); +} + +int main() { + int unsortedArray[] = {64, 34, 25, 12, 22, 11, 90}; + int n = sizeof(unsortedArray) / sizeof(unsortedArray[0]); + + printf("Unsorted array: "); + printArray(unsortedArray, n); + + bubbleSort(unsortedArray, n); + + printf("Sorted array: "); + printArray(unsortedArray, n); + + return 0; +}`, + + cpp: `// Bubble Sort in C++ +#include +#include +using namespace std; + +void bubbleSort(vector& arr) { + int n = arr.size(); + + // Outer loop for passes + for (int i = 0; i < n - 1; i++) { + // Inner loop for comparisons + for (int j = 0; j < n - i - 1; j++) { + // Swap if current element is greater than next + if (arr[j] > arr[j + 1]) { + // Using std::swap for cleaner code + swap(arr[j], arr[j + 1]); + } + } + } +} + +// Function to print an array +void printArray(const vector& arr) { + for (int num : arr) { + cout << num << " "; + } + cout << endl; +} + +int main() { + vector unsortedArray = {64, 34, 25, 12, 22, 11, 90}; + + cout << "Unsorted array: "; + printArray(unsortedArray); + + bubbleSort(unsortedArray); + + cout << "Sorted array: "; + printArray(unsortedArray); + + return 0; +}` + }; + +export default codeExamples; diff --git a/app/visualizer/sorting/bubblesort/codeBlock.jsx b/app/visualizer/sorting/bubblesort/codeBlock.jsx deleted file mode 100755 index 7a65e0e..0000000 --- a/app/visualizer/sorting/bubblesort/codeBlock.jsx +++ /dev/null @@ -1,324 +0,0 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState('javascript'); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: 'javascript', name: 'JavaScript' }, - { id: 'python', name: 'Python' }, - { id: 'java', name: 'Java' }, - { id: 'c', name: 'C' }, - { id: 'cpp', name: 'C++' } - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error('Failed to copy text: ', err); - } - }; - - const codeExamples = { - javascript: `// Bubble Sort in JavaScript -function bubbleSort(arr) { - let n = arr.length; - - // Outer loop for passes - for (let i = 0; i < n - 1; i++) { - // Inner loop for comparisons - for (let j = 0; j < n - i - 1; j++) { - // Swap if current element is greater than next - if (arr[j] > arr[j + 1]) { - // ES6 destructuring assignment for swap - [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]; - } - } - } - return arr; -} - -// Usage example -const unsortedArray = [64, 34, 25, 12, 22, 11, 90]; -console.log("Unsorted array:", unsortedArray); -const sortedArray = bubbleSort(unsortedArray); -console.log("Sorted array:", sortedArray);`, - - python: `# Bubble Sort in Python -def bubble_sort(arr): - n = len(arr) - - # Outer loop for passes - for i in range(n - 1): - # Inner loop for comparisons - for j in range(n - i - 1): - # Swap if current element is greater than next - if arr[j] > arr[j + 1]: - # Python tuple unpacking for swap - arr[j], arr[j + 1] = arr[j + 1], arr[j] - return arr - -# Usage example -unsorted_array = [64, 34, 25, 12, 22, 11, 90] -print("Unsorted array:", unsorted_array) -sorted_array = bubble_sort(unsorted_array) -print("Sorted array:", sorted_array)`, - - java: `// Bubble Sort in Java -public class BubbleSort { - public static void bubbleSort(int[] arr) { - int n = arr.length; - - // Outer loop for passes - for (int i = 0; i < n - 1; i++) { - // Inner loop for comparisons - for (int j = 0; j < n - i - 1; j++) { - // Swap if current element is greater than next - if (arr[j] > arr[j + 1]) { - // Traditional swap using temp variable - int temp = arr[j]; - arr[j] = arr[j + 1]; - arr[j + 1] = temp; - } - } - } - } - - public static void main(String[] args) { - int[] unsortedArray = {64, 34, 25, 12, 22, 11, 90}; - System.out.print("Unsorted array: "); - printArray(unsortedArray); - - bubbleSort(unsortedArray); - - System.out.print("Sorted array: "); - printArray(unsortedArray); - } - - // Helper method to print array - private static void printArray(int[] arr) { - for (int num : arr) { - System.out.print(num + " "); - } - System.out.println(); - } -}`, - - c: `// Bubble Sort in C -#include - -void bubbleSort(int arr[], int n) { - // Outer loop for passes - for (int i = 0; i < n - 1; i++) { - // Inner loop for comparisons - for (int j = 0; j < n - i - 1; j++) { - // Swap if current element is greater than next - if (arr[j] > arr[j + 1]) { - // Traditional swap using temp variable - int temp = arr[j]; - arr[j] = arr[j + 1]; - arr[j + 1] = temp; - } - } - } -} - -// Function to print an array -void printArray(int arr[], int size) { - for (int i = 0; i < size; i++) { - printf("%d ", arr[i]); - } - printf("\\n"); -} - -int main() { - int unsortedArray[] = {64, 34, 25, 12, 22, 11, 90}; - int n = sizeof(unsortedArray) / sizeof(unsortedArray[0]); - - printf("Unsorted array: "); - printArray(unsortedArray, n); - - bubbleSort(unsortedArray, n); - - printf("Sorted array: "); - printArray(unsortedArray, n); - - return 0; -}`, - - cpp: `// Bubble Sort in C++ -#include -#include -using namespace std; - -void bubbleSort(vector& arr) { - int n = arr.size(); - - // Outer loop for passes - for (int i = 0; i < n - 1; i++) { - // Inner loop for comparisons - for (int j = 0; j < n - i - 1; j++) { - // Swap if current element is greater than next - if (arr[j] > arr[j + 1]) { - // Using std::swap for cleaner code - swap(arr[j], arr[j + 1]); - } - } - } -} - -// Function to print an array -void printArray(const vector& arr) { - for (int num : arr) { - cout << num << " "; - } - cout << endl; -} - -int main() { - vector unsortedArray = {64, 34, 25, 12, 22, 11, 90}; - - cout << "Unsorted array: "; - printArray(unsortedArray); - - bubbleSort(unsortedArray); - - cout << "Sorted array: "; - printArray(unsortedArray); - - return 0; -}` - }; - - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Bubble Sort Implementation -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? 'bg-blue-500 text-white shadow-md' - : 'bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600' - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                    
-                  
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); -}; - -export default CodeBlock; \ No newline at end of file diff --git a/app/visualizer/sorting/bubblesort/page.jsx b/app/visualizer/sorting/bubblesort/page.jsx index 8e55a7d..e3ce024 100755 --- a/app/visualizer/sorting/bubblesort/page.jsx +++ b/app/visualizer/sorting/bubblesort/page.jsx @@ -5,7 +5,8 @@ import Footer from "@/app/components/footer"; import ModuleHeader from "@/app/components/modules/Header"; import Content from "@/app/visualizer/sorting/bubblesort/content"; import Quiz from "@/app/visualizer/sorting/bubblesort/quiz"; -import Code from "@/app/visualizer/sorting/bubblesort/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import ExploreOther from "@/app/components/ui/exploreOther"; import ModuleCard from "@/app/components/ui/ModuleCard"; import { MODULE_MAPS } from "@/lib/modulesMap"; @@ -78,7 +79,7 @@ export default function Page() {
- +
diff --git a/app/visualizer/sorting/insertionsort/code.js b/app/visualizer/sorting/insertionsort/code.js new file mode 100755 index 0000000..edfb33d --- /dev/null +++ b/app/visualizer/sorting/insertionsort/code.js @@ -0,0 +1,181 @@ +const codeExamples = { + javascript: `// Insertion Sort in JavaScript +function insertionSort(arr) { + // Start from the second element (index 1) + for (let i = 1; i < arr.length; i++) { + // Current element to be inserted + let current = arr[i]; + // Compare with the sorted portion + let j = i - 1; + + // Shift elements greater than current to the right + while (j >= 0 && arr[j] > current) { + arr[j + 1] = arr[j]; + j--; + } + // Insert the current element in correct position + arr[j + 1] = current; + } + return arr; +} + +// Usage example +const unsortedArray = [12, 11, 13, 5, 6]; +console.log("Unsorted array:", unsortedArray); +const sortedArray = insertionSort(unsortedArray); +console.log("Sorted array:", sortedArray);`, + + python: `# Insertion Sort in Python +def insertion_sort(arr): + # Start from the second element (index 1) + for i in range(1, len(arr)): + # Current element to be inserted + current = arr[i] + # Compare with the sorted portion + j = i - 1 + + # Shift elements greater than current to the right + while j >= 0 and arr[j] > current: + arr[j + 1] = arr[j] + j -= 1 + # Insert the current element in correct position + arr[j + 1] = current + return arr + +# Usage example +unsorted_array = [12, 11, 13, 5, 6] +print("Unsorted array:", unsorted_array) +sorted_array = insertion_sort(unsorted_array) +print("Sorted array:", sorted_array)`, + + java: `// Insertion Sort in Java +public class InsertionSort { + public static void insertionSort(int[] arr) { + // Start from the second element (index 1) + for (int i = 1; i < arr.length; i++) { + // Current element to be inserted + int current = arr[i]; + // Compare with the sorted portion + int j = i - 1; + + // Shift elements greater than current to the right + while (j >= 0 && arr[j] > current) { + arr[j + 1] = arr[j]; + j--; + } + // Insert the current element in correct position + arr[j + 1] = current; + } + } + + public static void main(String[] args) { + int[] unsortedArray = {12, 11, 13, 5, 6}; + System.out.print("Unsorted array: "); + printArray(unsortedArray); + + insertionSort(unsortedArray); + + System.out.print("Sorted array: "); + printArray(unsortedArray); + } + + // Helper method to print array + private static void printArray(int[] arr) { + for (int num : arr) { + System.out.print(num + " "); + } + System.out.println(); + } +}`, + + c: `// Insertion Sort in C +#include + +void insertionSort(int arr[], int n) { + // Start from the second element (index 1) + for (int i = 1; i < n; i++) { + // Current element to be inserted + int current = arr[i]; + // Compare with the sorted portion + int j = i - 1; + + // Shift elements greater than current to the right + while (j >= 0 && arr[j] > current) { + arr[j + 1] = arr[j]; + j--; + } + // Insert the current element in correct position + arr[j + 1] = current; + } +} + +// Function to print an array +void printArray(int arr[], int size) { + for (int i = 0; i < size; i++) { + printf("%d ", arr[i]); + } + printf("\\n"); +} + +int main() { + int unsortedArray[] = {12, 11, 13, 5, 6}; + int n = sizeof(unsortedArray) / sizeof(unsortedArray[0]); + + printf("Unsorted array: "); + printArray(unsortedArray, n); + + insertionSort(unsortedArray, n); + + printf("Sorted array: "); + printArray(unsortedArray, n); + + return 0; +}`, + + cpp: `// Insertion Sort in C++ +#include +#include +using namespace std; + +void insertionSort(vector& arr) { + // Start from the second element (index 1) + for (int i = 1; i < arr.size(); i++) { + // Current element to be inserted + int current = arr[i]; + // Compare with the sorted portion + int j = i - 1; + + // Shift elements greater than current to the right + while (j >= 0 && arr[j] > current) { + arr[j + 1] = arr[j]; + j--; + } + // Insert the current element in correct position + arr[j + 1] = current; + } +} + +// Function to print an array +void printArray(const vector& arr) { + for (int num : arr) { + cout << num << " "; + } + cout << endl; +} + +int main() { + vector unsortedArray = {12, 11, 13, 5, 6}; + + cout << "Unsorted array: "; + printArray(unsortedArray); + + insertionSort(unsortedArray); + + cout << "Sorted array: "; + printArray(unsortedArray); + + return 0; +}` + }; + +export default codeExamples; diff --git a/app/visualizer/sorting/insertionsort/codeBlock.jsx b/app/visualizer/sorting/insertionsort/codeBlock.jsx deleted file mode 100755 index 22eeda9..0000000 --- a/app/visualizer/sorting/insertionsort/codeBlock.jsx +++ /dev/null @@ -1,333 +0,0 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState('javascript'); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: 'javascript', name: 'JavaScript' }, - { id: 'python', name: 'Python' }, - { id: 'java', name: 'Java' }, - { id: 'c', name: 'C' }, - { id: 'cpp', name: 'C++' } - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error('Failed to copy text: ', err); - } - }; - - const codeExamples = { - javascript: `// Insertion Sort in JavaScript -function insertionSort(arr) { - // Start from the second element (index 1) - for (let i = 1; i < arr.length; i++) { - // Current element to be inserted - let current = arr[i]; - // Compare with the sorted portion - let j = i - 1; - - // Shift elements greater than current to the right - while (j >= 0 && arr[j] > current) { - arr[j + 1] = arr[j]; - j--; - } - // Insert the current element in correct position - arr[j + 1] = current; - } - return arr; -} - -// Usage example -const unsortedArray = [12, 11, 13, 5, 6]; -console.log("Unsorted array:", unsortedArray); -const sortedArray = insertionSort(unsortedArray); -console.log("Sorted array:", sortedArray);`, - - python: `# Insertion Sort in Python -def insertion_sort(arr): - # Start from the second element (index 1) - for i in range(1, len(arr)): - # Current element to be inserted - current = arr[i] - # Compare with the sorted portion - j = i - 1 - - # Shift elements greater than current to the right - while j >= 0 and arr[j] > current: - arr[j + 1] = arr[j] - j -= 1 - # Insert the current element in correct position - arr[j + 1] = current - return arr - -# Usage example -unsorted_array = [12, 11, 13, 5, 6] -print("Unsorted array:", unsorted_array) -sorted_array = insertion_sort(unsorted_array) -print("Sorted array:", sorted_array)`, - - java: `// Insertion Sort in Java -public class InsertionSort { - public static void insertionSort(int[] arr) { - // Start from the second element (index 1) - for (int i = 1; i < arr.length; i++) { - // Current element to be inserted - int current = arr[i]; - // Compare with the sorted portion - int j = i - 1; - - // Shift elements greater than current to the right - while (j >= 0 && arr[j] > current) { - arr[j + 1] = arr[j]; - j--; - } - // Insert the current element in correct position - arr[j + 1] = current; - } - } - - public static void main(String[] args) { - int[] unsortedArray = {12, 11, 13, 5, 6}; - System.out.print("Unsorted array: "); - printArray(unsortedArray); - - insertionSort(unsortedArray); - - System.out.print("Sorted array: "); - printArray(unsortedArray); - } - - // Helper method to print array - private static void printArray(int[] arr) { - for (int num : arr) { - System.out.print(num + " "); - } - System.out.println(); - } -}`, - - c: `// Insertion Sort in C -#include - -void insertionSort(int arr[], int n) { - // Start from the second element (index 1) - for (int i = 1; i < n; i++) { - // Current element to be inserted - int current = arr[i]; - // Compare with the sorted portion - int j = i - 1; - - // Shift elements greater than current to the right - while (j >= 0 && arr[j] > current) { - arr[j + 1] = arr[j]; - j--; - } - // Insert the current element in correct position - arr[j + 1] = current; - } -} - -// Function to print an array -void printArray(int arr[], int size) { - for (int i = 0; i < size; i++) { - printf("%d ", arr[i]); - } - printf("\\n"); -} - -int main() { - int unsortedArray[] = {12, 11, 13, 5, 6}; - int n = sizeof(unsortedArray) / sizeof(unsortedArray[0]); - - printf("Unsorted array: "); - printArray(unsortedArray, n); - - insertionSort(unsortedArray, n); - - printf("Sorted array: "); - printArray(unsortedArray, n); - - return 0; -}`, - - cpp: `// Insertion Sort in C++ -#include -#include -using namespace std; - -void insertionSort(vector& arr) { - // Start from the second element (index 1) - for (int i = 1; i < arr.size(); i++) { - // Current element to be inserted - int current = arr[i]; - // Compare with the sorted portion - int j = i - 1; - - // Shift elements greater than current to the right - while (j >= 0 && arr[j] > current) { - arr[j + 1] = arr[j]; - j--; - } - // Insert the current element in correct position - arr[j + 1] = current; - } -} - -// Function to print an array -void printArray(const vector& arr) { - for (int num : arr) { - cout << num << " "; - } - cout << endl; -} - -int main() { - vector unsortedArray = {12, 11, 13, 5, 6}; - - cout << "Unsorted array: "; - printArray(unsortedArray); - - insertionSort(unsortedArray); - - cout << "Sorted array: "; - printArray(unsortedArray); - - return 0; -}` - }; - - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Insertion Sort Implementation -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? 'bg-blue-500 text-white shadow-md' - : 'bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600' - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                    
-                  
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); -}; - -export default CodeBlock; \ No newline at end of file diff --git a/app/visualizer/sorting/insertionsort/page.jsx b/app/visualizer/sorting/insertionsort/page.jsx index b19c0b9..dbee89c 100755 --- a/app/visualizer/sorting/insertionsort/page.jsx +++ b/app/visualizer/sorting/insertionsort/page.jsx @@ -3,7 +3,8 @@ import Navbar from "@/app/components/navbarinner"; import ModuleHeader from "@/app/components/modules/Header"; import Content from "@/app/visualizer/sorting/insertionsort/content"; import Quiz from "@/app/visualizer/sorting/insertionsort/quiz"; -import Code from "@/app/visualizer/sorting/insertionsort/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import ExploreOther from "@/app/components/ui/exploreOther"; import BackToTopButton from "@/app/components/ui/backtotop"; import Footer from "@/app/components/footer"; @@ -78,7 +79,7 @@ export default function Page() {
- +
diff --git a/app/visualizer/sorting/mergesort/code.js b/app/visualizer/sorting/mergesort/code.js new file mode 100755 index 0000000..1f3e756 --- /dev/null +++ b/app/visualizer/sorting/mergesort/code.js @@ -0,0 +1,267 @@ +const codeExamples = { + javascript: `// Merge Sort in JavaScript +function mergeSort(arr) { + if (arr.length <= 1) return arr; + + const mid = Math.floor(arr.length / 2); + const left = mergeSort(arr.slice(0, mid)); + const right = mergeSort(arr.slice(mid)); + + return merge(left, right); +} + +function merge(left, right) { + let result = []; + let leftIndex = 0; + let rightIndex = 0; + + while (leftIndex < left.length && rightIndex < right.length) { + if (left[leftIndex] < right[rightIndex]) { + result.push(left[leftIndex++]); + } else { + result.push(right[rightIndex++]); + } + } + + return result.concat(left.slice(leftIndex)).concat(right.slice(rightIndex)); +} + +// Usage +const arr = [38, 27, 43, 3, 9, 82, 10]; +console.log("Original:", arr); +console.log("Sorted:", mergeSort(arr));`, + + python: `# Merge Sort in Python +def merge_sort(arr): + if len(arr) <= 1: + return arr + + mid = len(arr) // 2 + left = merge_sort(arr[:mid]) + right = merge_sort(arr[mid:]) + + return merge(left, right) + +def merge(left, right): + result = [] + left_idx, right_idx = 0, 0 + + while left_idx < len(left) and right_idx < len(right): + if left[left_idx] < right[right_idx]: + result.append(left[left_idx]) + left_idx += 1 + else: + result.append(right[right_idx]) + right_idx += 1 + + result.extend(left[left_idx:]) + result.extend(right[right_idx:]) + return result + +# Usage +arr = [38, 27, 43, 3, 9, 82, 10] +print("Original:", arr) +print("Sorted:", merge_sort(arr))`, + + java: `// Merge Sort in Java +public class MergeSort { + public static void mergeSort(int[] arr) { + if (arr.length <= 1) return; + + int mid = arr.length / 2; + int[] left = new int[mid]; + int[] right = new int[arr.length - mid]; + + System.arraycopy(arr, 0, left, 0, mid); + System.arraycopy(arr, mid, right, 0, arr.length - mid); + + mergeSort(left); + mergeSort(right); + merge(arr, left, right); + } + + private static void merge(int[] arr, int[] left, int[] right) { + int i = 0, j = 0, k = 0; + + while (i < left.length && j < right.length) { + if (left[i] < right[j]) { + arr[k++] = left[i++]; + } else { + arr[k++] = right[j++]; + } + } + + while (i < left.length) { + arr[k++] = left[i++]; + } + + while (j < right.length) { + arr[k++] = right[j++]; + } + } + + public static void main(String[] args) { + int[] arr = {38, 27, 43, 3, 9, 82, 10}; + System.out.print("Original: "); + printArray(arr); + + mergeSort(arr); + + System.out.print("Sorted: "); + printArray(arr); + } + + private static void printArray(int[] arr) { + for (int num : arr) { + System.out.print(num + " "); + } + System.out.println(); + } +}`, + + c: `// Merge Sort in C +#include +#include + +void merge(int arr[], int l, int m, int r) { + int i, j, k; + int n1 = m - l + 1; + int n2 = r - m; + + int L[n1], R[n2]; + + for (i = 0; i < n1; i++) + L[i] = arr[l + i]; + for (j = 0; j < n2; j++) + R[j] = arr[m + 1 + j]; + + i = 0; j = 0; k = l; + + while (i < n1 && j < n2) { + if (L[i] <= R[j]) { + arr[k] = L[i]; + i++; + } else { + arr[k] = R[j]; + j++; + } + k++; + } + + while (i < n1) { + arr[k] = L[i]; + i++; + k++; + } + + while (j < n2) { + arr[k] = R[j]; + j++; + k++; + } +} + +void mergeSort(int arr[], int l, int r) { + if (l < r) { + int m = l + (r - l) / 2; + mergeSort(arr, l, m); + mergeSort(arr, m + 1, r); + merge(arr, l, m, r); + } +} + +void printArray(int arr[], int size) { + for (int i = 0; i < size; i++) + printf("%d ", arr[i]); + printf("\\n"); +} + +int main() { + int arr[] = {38, 27, 43, 3, 9, 82, 10}; + int size = sizeof(arr) / sizeof(arr[0]); + + printf("Original: "); + printArray(arr, size); + + mergeSort(arr, 0, size - 1); + + printf("Sorted: "); + printArray(arr, size); + + return 0; +}`, + + cpp: `// Merge Sort in C++ +#include +#include +using namespace std; + +void merge(vector& arr, int l, int m, int r) { + int n1 = m - l + 1; + int n2 = r - m; + + vector L(n1), R(n2); + + for (int i = 0; i < n1; i++) + L[i] = arr[l + i]; + for (int j = 0; j < n2; j++) + R[j] = arr[m + 1 + j]; + + int i = 0, j = 0, k = l; + + while (i < n1 && j < n2) { + if (L[i] <= R[j]) { + arr[k] = L[i]; + i++; + } else { + arr[k] = R[j]; + j++; + } + k++; + } + + while (i < n1) { + arr[k] = L[i]; + i++; + k++; + } + + while (j < n2) { + arr[k] = R[j]; + j++; + k++; + } +} + +void mergeSort(vector& arr, int l, int r) { + if (l < r) { + int m = l + (r - l) / 2; + mergeSort(arr, l, m); + mergeSort(arr, m + 1, r); + merge(arr, l, m, r); + } +} + +void printArray(const vector& arr) { + for (int num : arr) { + cout << num << " "; + } + cout << endl; +} + +int main() { + vector arr = {38, 27, 43, 3, 9, 82, 10}; + + cout << "Original: "; + printArray(arr); + + mergeSort(arr, 0, arr.size() - 1); + + cout << "Sorted: "; + printArray(arr); + + return 0; +}` + }; + +export default codeExamples; diff --git a/app/visualizer/sorting/mergesort/codeBlock.jsx b/app/visualizer/sorting/mergesort/codeBlock.jsx deleted file mode 100755 index e6b6b34..0000000 --- a/app/visualizer/sorting/mergesort/codeBlock.jsx +++ /dev/null @@ -1,422 +0,0 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState('javascript'); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: 'javascript', name: 'JavaScript' }, - { id: 'python', name: 'Python' }, - { id: 'java', name: 'Java' }, - { id: 'c', name: 'C' }, - { id: 'cpp', name: 'C++' } - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error('Failed to copy text: ', err); - } - }; - - const codeExamples = { - javascript: `// Merge Sort in JavaScript -function mergeSort(arr) { - if (arr.length <= 1) return arr; - - const mid = Math.floor(arr.length / 2); - const left = mergeSort(arr.slice(0, mid)); - const right = mergeSort(arr.slice(mid)); - - return merge(left, right); -} - -function merge(left, right) { - let result = []; - let leftIndex = 0; - let rightIndex = 0; - - while (leftIndex < left.length && rightIndex < right.length) { - if (left[leftIndex] < right[rightIndex]) { - result.push(left[leftIndex++]); - } else { - result.push(right[rightIndex++]); - } - } - - return result.concat(left.slice(leftIndex)).concat(right.slice(rightIndex)); -} - -// Usage -const arr = [38, 27, 43, 3, 9, 82, 10]; -console.log("Original:", arr); -console.log("Sorted:", mergeSort(arr));`, - - python: `# Merge Sort in Python -def merge_sort(arr): - if len(arr) <= 1: - return arr - - mid = len(arr) // 2 - left = merge_sort(arr[:mid]) - right = merge_sort(arr[mid:]) - - return merge(left, right) - -def merge(left, right): - result = [] - left_idx, right_idx = 0, 0 - - while left_idx < len(left) and right_idx < len(right): - if left[left_idx] < right[right_idx]: - result.append(left[left_idx]) - left_idx += 1 - else: - result.append(right[right_idx]) - right_idx += 1 - - result.extend(left[left_idx:]) - result.extend(right[right_idx:]) - return result - -# Usage -arr = [38, 27, 43, 3, 9, 82, 10] -print("Original:", arr) -print("Sorted:", merge_sort(arr))`, - - java: `// Merge Sort in Java -public class MergeSort { - public static void mergeSort(int[] arr) { - if (arr.length <= 1) return; - - int mid = arr.length / 2; - int[] left = new int[mid]; - int[] right = new int[arr.length - mid]; - - System.arraycopy(arr, 0, left, 0, mid); - System.arraycopy(arr, mid, right, 0, arr.length - mid); - - mergeSort(left); - mergeSort(right); - merge(arr, left, right); - } - - private static void merge(int[] arr, int[] left, int[] right) { - int i = 0, j = 0, k = 0; - - while (i < left.length && j < right.length) { - if (left[i] < right[j]) { - arr[k++] = left[i++]; - } else { - arr[k++] = right[j++]; - } - } - - while (i < left.length) { - arr[k++] = left[i++]; - } - - while (j < right.length) { - arr[k++] = right[j++]; - } - } - - public static void main(String[] args) { - int[] arr = {38, 27, 43, 3, 9, 82, 10}; - System.out.print("Original: "); - printArray(arr); - - mergeSort(arr); - - System.out.print("Sorted: "); - printArray(arr); - } - - private static void printArray(int[] arr) { - for (int num : arr) { - System.out.print(num + " "); - } - System.out.println(); - } -}`, - - c: `// Merge Sort in C -#include -#include - -void merge(int arr[], int l, int m, int r) { - int i, j, k; - int n1 = m - l + 1; - int n2 = r - m; - - int L[n1], R[n2]; - - for (i = 0; i < n1; i++) - L[i] = arr[l + i]; - for (j = 0; j < n2; j++) - R[j] = arr[m + 1 + j]; - - i = 0; j = 0; k = l; - - while (i < n1 && j < n2) { - if (L[i] <= R[j]) { - arr[k] = L[i]; - i++; - } else { - arr[k] = R[j]; - j++; - } - k++; - } - - while (i < n1) { - arr[k] = L[i]; - i++; - k++; - } - - while (j < n2) { - arr[k] = R[j]; - j++; - k++; - } -} - -void mergeSort(int arr[], int l, int r) { - if (l < r) { - int m = l + (r - l) / 2; - mergeSort(arr, l, m); - mergeSort(arr, m + 1, r); - merge(arr, l, m, r); - } -} - -void printArray(int arr[], int size) { - for (int i = 0; i < size; i++) - printf("%d ", arr[i]); - printf("\\n"); -} - -int main() { - int arr[] = {38, 27, 43, 3, 9, 82, 10}; - int size = sizeof(arr) / sizeof(arr[0]); - - printf("Original: "); - printArray(arr, size); - - mergeSort(arr, 0, size - 1); - - printf("Sorted: "); - printArray(arr, size); - - return 0; -}`, - - cpp: `// Merge Sort in C++ -#include -#include -using namespace std; - -void merge(vector& arr, int l, int m, int r) { - int n1 = m - l + 1; - int n2 = r - m; - - vector L(n1), R(n2); - - for (int i = 0; i < n1; i++) - L[i] = arr[l + i]; - for (int j = 0; j < n2; j++) - R[j] = arr[m + 1 + j]; - - int i = 0, j = 0, k = l; - - while (i < n1 && j < n2) { - if (L[i] <= R[j]) { - arr[k] = L[i]; - i++; - } else { - arr[k] = R[j]; - j++; - } - k++; - } - - while (i < n1) { - arr[k] = L[i]; - i++; - k++; - } - - while (j < n2) { - arr[k] = R[j]; - j++; - k++; - } -} - -void mergeSort(vector& arr, int l, int r) { - if (l < r) { - int m = l + (r - l) / 2; - mergeSort(arr, l, m); - mergeSort(arr, m + 1, r); - merge(arr, l, m, r); - } -} - -void printArray(const vector& arr) { - for (int num : arr) { - cout << num << " "; - } - cout << endl; -} - -int main() { - vector arr = {38, 27, 43, 3, 9, 82, 10}; - - cout << "Original: "; - printArray(arr); - - mergeSort(arr, 0, arr.size() - 1); - - cout << "Sorted: "; - printArray(arr); - - return 0; -}` - }; - - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Merge Sort Implementation -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                
-              
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); -}; - -export default CodeBlock; \ No newline at end of file diff --git a/app/visualizer/sorting/mergesort/page.jsx b/app/visualizer/sorting/mergesort/page.jsx index 7fd1871..fc8a869 100755 --- a/app/visualizer/sorting/mergesort/page.jsx +++ b/app/visualizer/sorting/mergesort/page.jsx @@ -3,7 +3,8 @@ import Navbar from "@/app/components/navbarinner"; import ModuleHeader from "@/app/components/modules/Header"; import Content from "@/app/visualizer/sorting/mergesort/content"; import Quiz from "@/app/visualizer/sorting/mergesort/quiz"; -import Code from "@/app/visualizer/sorting/mergesort/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import ExploreOther from "@/app/components/ui/exploreOther"; import BackToTopButton from "@/app/components/ui/backtotop"; import Footer from "@/app/components/footer"; @@ -76,7 +77,7 @@ export default function Page() {
- +
diff --git a/app/visualizer/sorting/quicksort/code.js b/app/visualizer/sorting/quicksort/code.js new file mode 100755 index 0000000..6f1bfef --- /dev/null +++ b/app/visualizer/sorting/quicksort/code.js @@ -0,0 +1,214 @@ +const codeExamples = { + javascript: `// Quick Sort in JavaScript +function quickSort(arr, left = 0, right = arr.length - 1) { + if (left < right) { + const pivotIndex = partition(arr, left, right); + quickSort(arr, left, pivotIndex - 1); + quickSort(arr, pivotIndex + 1, right); + } + return arr; +} + +function partition(arr, left, right) { + const pivot = arr[right]; + let i = left; + + for (let j = left; j < right; j++) { + if (arr[j] < pivot) { + [arr[i], arr[j]] = [arr[j], arr[i]]; + i++; + } + } + + [arr[i], arr[right]] = [arr[right], arr[i]]; + return i; +} + +// Usage +const arr = [10, 7, 8, 9, 1, 5]; +console.log("Original:", arr); +console.log("Sorted:", quickSort([...arr]));`, + + python: `# Quick Sort in Python +def quick_sort(arr, low=0, high=None): + if high is None: + high = len(arr) - 1 + + if low < high: + pivot_index = partition(arr, low, high) + quick_sort(arr, low, pivot_index - 1) + quick_sort(arr, pivot_index + 1, high) + return arr + +def partition(arr, low, high): + pivot = arr[high] + i = low + + for j in range(low, high): + if arr[j] < pivot: + arr[i], arr[j] = arr[j], arr[i] + i += 1 + + arr[i], arr[high] = arr[high], arr[i] + return i + +# Usage +arr = [10, 7, 8, 9, 1, 5] +print("Original:", arr) +print("Sorted:", quick_sort(arr.copy()))`, + + java: `// Quick Sort in Java +public class QuickSort { + public static void quickSort(int[] arr, int low, int high) { + if (low < high) { + int pivotIndex = partition(arr, low, high); + quickSort(arr, low, pivotIndex - 1); + quickSort(arr, pivotIndex + 1, high); + } + } + + private static int partition(int[] arr, int low, int high) { + int pivot = arr[high]; + int i = low; + + for (int j = low; j < high; j++) { + if (arr[j] < pivot) { + swap(arr, i, j); + i++; + } + } + + swap(arr, i, high); + return i; + } + + private static void swap(int[] arr, int i, int j) { + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + + public static void main(String[] args) { + int[] arr = {10, 7, 8, 9, 1, 5}; + System.out.print("Original: "); + printArray(arr); + + quickSort(arr, 0, arr.length - 1); + + System.out.print("Sorted: "); + printArray(arr); + } + + private static void printArray(int[] arr) { + for (int num : arr) { + System.out.print(num + " "); + } + System.out.println(); + } +}`, + + c: `// Quick Sort in C +#include + +void swap(int* a, int* b) { + int temp = *a; + *a = *b; + *b = temp; +} + +int partition(int arr[], int low, int high) { + int pivot = arr[high]; + int i = low; + + for (int j = low; j < high; j++) { + if (arr[j] < pivot) { + swap(&arr[i], &arr[j]); + i++; + } + } + + swap(&arr[i], &arr[high]); + return i; +} + +void quickSort(int arr[], int low, int high) { + if (low < high) { + int pivotIndex = partition(arr, low, high); + quickSort(arr, low, pivotIndex - 1); + quickSort(arr, pivotIndex + 1, high); + } +} + +void printArray(int arr[], int size) { + for (int i = 0; i < size; i++) { + printf("%d ", arr[i]); + } + printf("\\n"); +} + +int main() { + int arr[] = {10, 7, 8, 9, 1, 5}; + int size = sizeof(arr) / sizeof(arr[0]); + + printf("Original: "); + printArray(arr, size); + + quickSort(arr, 0, size - 1); + + printf("Sorted: "); + printArray(arr, size); + + return 0; +}`, + + cpp: `// Quick Sort in C++ +#include +#include +using namespace std; + +int partition(vector& arr, int low, int high) { + int pivot = arr[high]; + int i = low; + + for (int j = low; j < high; j++) { + if (arr[j] < pivot) { + swap(arr[i], arr[j]); + i++; + } + } + + swap(arr[i], arr[high]); + return i; +} + +void quickSort(vector& arr, int low, int high) { + if (low < high) { + int pivotIndex = partition(arr, low, high); + quickSort(arr, low, pivotIndex - 1); + quickSort(arr, pivotIndex + 1, high); + } +} + +void printArray(const vector& arr) { + for (int num : arr) { + cout << num << " "; + } + cout << endl; +} + +int main() { + vector arr = {10, 7, 8, 9, 1, 5}; + + cout << "Original: "; + printArray(arr); + + quickSort(arr, 0, arr.size() - 1); + + cout << "Sorted: "; + printArray(arr); + + return 0; +}`, + }; + +export default codeExamples; diff --git a/app/visualizer/sorting/quicksort/codeBlock.jsx b/app/visualizer/sorting/quicksort/codeBlock.jsx deleted file mode 100755 index 69c87d0..0000000 --- a/app/visualizer/sorting/quicksort/codeBlock.jsx +++ /dev/null @@ -1,369 +0,0 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - - const codeExamples = { - javascript: `// Quick Sort in JavaScript -function quickSort(arr, left = 0, right = arr.length - 1) { - if (left < right) { - const pivotIndex = partition(arr, left, right); - quickSort(arr, left, pivotIndex - 1); - quickSort(arr, pivotIndex + 1, right); - } - return arr; -} - -function partition(arr, left, right) { - const pivot = arr[right]; - let i = left; - - for (let j = left; j < right; j++) { - if (arr[j] < pivot) { - [arr[i], arr[j]] = [arr[j], arr[i]]; - i++; - } - } - - [arr[i], arr[right]] = [arr[right], arr[i]]; - return i; -} - -// Usage -const arr = [10, 7, 8, 9, 1, 5]; -console.log("Original:", arr); -console.log("Sorted:", quickSort([...arr]));`, - - python: `# Quick Sort in Python -def quick_sort(arr, low=0, high=None): - if high is None: - high = len(arr) - 1 - - if low < high: - pivot_index = partition(arr, low, high) - quick_sort(arr, low, pivot_index - 1) - quick_sort(arr, pivot_index + 1, high) - return arr - -def partition(arr, low, high): - pivot = arr[high] - i = low - - for j in range(low, high): - if arr[j] < pivot: - arr[i], arr[j] = arr[j], arr[i] - i += 1 - - arr[i], arr[high] = arr[high], arr[i] - return i - -# Usage -arr = [10, 7, 8, 9, 1, 5] -print("Original:", arr) -print("Sorted:", quick_sort(arr.copy()))`, - - java: `// Quick Sort in Java -public class QuickSort { - public static void quickSort(int[] arr, int low, int high) { - if (low < high) { - int pivotIndex = partition(arr, low, high); - quickSort(arr, low, pivotIndex - 1); - quickSort(arr, pivotIndex + 1, high); - } - } - - private static int partition(int[] arr, int low, int high) { - int pivot = arr[high]; - int i = low; - - for (int j = low; j < high; j++) { - if (arr[j] < pivot) { - swap(arr, i, j); - i++; - } - } - - swap(arr, i, high); - return i; - } - - private static void swap(int[] arr, int i, int j) { - int temp = arr[i]; - arr[i] = arr[j]; - arr[j] = temp; - } - - public static void main(String[] args) { - int[] arr = {10, 7, 8, 9, 1, 5}; - System.out.print("Original: "); - printArray(arr); - - quickSort(arr, 0, arr.length - 1); - - System.out.print("Sorted: "); - printArray(arr); - } - - private static void printArray(int[] arr) { - for (int num : arr) { - System.out.print(num + " "); - } - System.out.println(); - } -}`, - - c: `// Quick Sort in C -#include - -void swap(int* a, int* b) { - int temp = *a; - *a = *b; - *b = temp; -} - -int partition(int arr[], int low, int high) { - int pivot = arr[high]; - int i = low; - - for (int j = low; j < high; j++) { - if (arr[j] < pivot) { - swap(&arr[i], &arr[j]); - i++; - } - } - - swap(&arr[i], &arr[high]); - return i; -} - -void quickSort(int arr[], int low, int high) { - if (low < high) { - int pivotIndex = partition(arr, low, high); - quickSort(arr, low, pivotIndex - 1); - quickSort(arr, pivotIndex + 1, high); - } -} - -void printArray(int arr[], int size) { - for (int i = 0; i < size; i++) { - printf("%d ", arr[i]); - } - printf("\\n"); -} - -int main() { - int arr[] = {10, 7, 8, 9, 1, 5}; - int size = sizeof(arr) / sizeof(arr[0]); - - printf("Original: "); - printArray(arr, size); - - quickSort(arr, 0, size - 1); - - printf("Sorted: "); - printArray(arr, size); - - return 0; -}`, - - cpp: `// Quick Sort in C++ -#include -#include -using namespace std; - -int partition(vector& arr, int low, int high) { - int pivot = arr[high]; - int i = low; - - for (int j = low; j < high; j++) { - if (arr[j] < pivot) { - swap(arr[i], arr[j]); - i++; - } - } - - swap(arr[i], arr[high]); - return i; -} - -void quickSort(vector& arr, int low, int high) { - if (low < high) { - int pivotIndex = partition(arr, low, high); - quickSort(arr, low, pivotIndex - 1); - quickSort(arr, pivotIndex + 1, high); - } -} - -void printArray(const vector& arr) { - for (int num : arr) { - cout << num << " "; - } - cout << endl; -} - -int main() { - vector arr = {10, 7, 8, 9, 1, 5}; - - cout << "Original: "; - printArray(arr); - - quickSort(arr, 0, arr.size() - 1); - - cout << "Sorted: "; - printArray(arr); - - return 0; -}`, - }; - - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Quick Sort Implementation -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                
-              
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); -}; - -export default CodeBlock; \ No newline at end of file diff --git a/app/visualizer/sorting/quicksort/page.jsx b/app/visualizer/sorting/quicksort/page.jsx index fa75cf6..c18e5e7 100755 --- a/app/visualizer/sorting/quicksort/page.jsx +++ b/app/visualizer/sorting/quicksort/page.jsx @@ -3,7 +3,8 @@ import Navbar from "@/app/components/navbarinner"; import ModuleHeader from "@/app/components/modules/Header"; import Content from "@/app/visualizer/sorting/quicksort/content"; import Quiz from "@/app/visualizer/sorting/quicksort/quiz"; -import Code from "@/app/visualizer/sorting/quicksort/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import ExploreOther from "@/app/components/ui/exploreOther"; import BackToTopButton from "@/app/components/ui/backtotop"; import Footer from "@/app/components/footer"; @@ -77,7 +78,7 @@ export default function Page() {
- +
diff --git a/app/visualizer/sorting/selectionsort/code.js b/app/visualizer/sorting/selectionsort/code.js new file mode 100755 index 0000000..8fc2f71 --- /dev/null +++ b/app/visualizer/sorting/selectionsort/code.js @@ -0,0 +1,172 @@ +const codeExamples = { + javascript: `// Selection Sort in JavaScript +function selectionSort(arr) { + const n = arr.length; + + for (let i = 0; i < n - 1; i++) { + // Find the minimum element in unsorted array + let minIdx = i; + for (let j = i + 1; j < n; j++) { + if (arr[j] < arr[minIdx]) { + minIdx = j; + } + } + + // Swap the found minimum with the first element + [arr[i], arr[minIdx]] = [arr[minIdx], arr[i]]; + } + return arr; +} + +// Usage +const arr = [64, 25, 12, 22, 11]; +console.log("Original:", arr); +console.log("Sorted:", selectionSort([...arr]));`, + + python: `# Selection Sort in Python +def selection_sort(arr): + n = len(arr) + + for i in range(n - 1): + # Find the minimum element in unsorted array + min_idx = i + for j in range(i + 1, n): + if arr[j] < arr[min_idx]: + min_idx = j + + # Swap the found minimum with the first element + arr[i], arr[min_idx] = arr[min_idx], arr[i] + return arr + +# Usage +arr = [64, 25, 12, 22, 11] +print("Original:", arr) +print("Sorted:", selection_sort(arr.copy()))`, + + java: `// Selection Sort in Java +public class SelectionSort { + public static void selectionSort(int[] arr) { + int n = arr.length; + + for (int i = 0; i < n - 1; i++) { + // Find the minimum element in unsorted array + int minIdx = i; + for (int j = i + 1; j < n; j++) { + if (arr[j] < arr[minIdx]) { + minIdx = j; + } + } + + // Swap the found minimum with the first element + int temp = arr[minIdx]; + arr[minIdx] = arr[i]; + arr[i] = temp; + } + } + + public static void main(String[] args) { + int[] arr = {64, 25, 12, 22, 11}; + System.out.print("Original: "); + printArray(arr); + + selectionSort(arr); + + System.out.print("Sorted: "); + printArray(arr); + } + + private static void printArray(int[] arr) { + for (int num : arr) { + System.out.print(num + " "); + } + System.out.println(); + } +}`, + + c: `// Selection Sort in C +#include + +void selectionSort(int arr[], int n) { + for (int i = 0; i < n - 1; i++) { + // Find the minimum element in unsorted array + int minIdx = i; + for (int j = i + 1; j < n; j++) { + if (arr[j] < arr[minIdx]) { + minIdx = j; + } + } + + // Swap the found minimum with the first element + int temp = arr[minIdx]; + arr[minIdx] = arr[i]; + arr[i] = temp; + } +} + +void printArray(int arr[], int size) { + for (int i = 0; i < size; i++) { + printf("%d ", arr[i]); + } + printf("\\n"); +} + +int main() { + int arr[] = {64, 25, 12, 22, 11}; + int n = sizeof(arr) / sizeof(arr[0]); + + printf("Original: "); + printArray(arr, n); + + selectionSort(arr, n); + + printf("Sorted: "); + printArray(arr, n); + + return 0; +}`, + + cpp: `// Selection Sort in C++ +#include +#include +using namespace std; + +void selectionSort(vector& arr) { + int n = arr.size(); + + for (int i = 0; i < n - 1; i++) { + // Find the minimum element in unsorted array + int minIdx = i; + for (int j = i + 1; j < n; j++) { + if (arr[j] < arr[minIdx]) { + minIdx = j; + } + } + + // Swap the found minimum with the first element + swap(arr[i], arr[minIdx]); + } +} + +void printArray(const vector& arr) { + for (int num : arr) { + cout << num << " "; + } + cout << endl; +} + +int main() { + vector arr = {64, 25, 12, 22, 11}; + + cout << "Original: "; + printArray(arr); + + selectionSort(arr); + + cout << "Sorted: "; + printArray(arr); + + return 0; +}` + }; + +export default codeExamples; diff --git a/app/visualizer/sorting/selectionsort/codeBlock.jsx b/app/visualizer/sorting/selectionsort/codeBlock.jsx deleted file mode 100755 index f39d088..0000000 --- a/app/visualizer/sorting/selectionsort/codeBlock.jsx +++ /dev/null @@ -1,327 +0,0 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - - const codeExamples = { - javascript: `// Selection Sort in JavaScript -function selectionSort(arr) { - const n = arr.length; - - for (let i = 0; i < n - 1; i++) { - // Find the minimum element in unsorted array - let minIdx = i; - for (let j = i + 1; j < n; j++) { - if (arr[j] < arr[minIdx]) { - minIdx = j; - } - } - - // Swap the found minimum with the first element - [arr[i], arr[minIdx]] = [arr[minIdx], arr[i]]; - } - return arr; -} - -// Usage -const arr = [64, 25, 12, 22, 11]; -console.log("Original:", arr); -console.log("Sorted:", selectionSort([...arr]));`, - - python: `# Selection Sort in Python -def selection_sort(arr): - n = len(arr) - - for i in range(n - 1): - # Find the minimum element in unsorted array - min_idx = i - for j in range(i + 1, n): - if arr[j] < arr[min_idx]: - min_idx = j - - # Swap the found minimum with the first element - arr[i], arr[min_idx] = arr[min_idx], arr[i] - return arr - -# Usage -arr = [64, 25, 12, 22, 11] -print("Original:", arr) -print("Sorted:", selection_sort(arr.copy()))`, - - java: `// Selection Sort in Java -public class SelectionSort { - public static void selectionSort(int[] arr) { - int n = arr.length; - - for (int i = 0; i < n - 1; i++) { - // Find the minimum element in unsorted array - int minIdx = i; - for (int j = i + 1; j < n; j++) { - if (arr[j] < arr[minIdx]) { - minIdx = j; - } - } - - // Swap the found minimum with the first element - int temp = arr[minIdx]; - arr[minIdx] = arr[i]; - arr[i] = temp; - } - } - - public static void main(String[] args) { - int[] arr = {64, 25, 12, 22, 11}; - System.out.print("Original: "); - printArray(arr); - - selectionSort(arr); - - System.out.print("Sorted: "); - printArray(arr); - } - - private static void printArray(int[] arr) { - for (int num : arr) { - System.out.print(num + " "); - } - System.out.println(); - } -}`, - - c: `// Selection Sort in C -#include - -void selectionSort(int arr[], int n) { - for (int i = 0; i < n - 1; i++) { - // Find the minimum element in unsorted array - int minIdx = i; - for (int j = i + 1; j < n; j++) { - if (arr[j] < arr[minIdx]) { - minIdx = j; - } - } - - // Swap the found minimum with the first element - int temp = arr[minIdx]; - arr[minIdx] = arr[i]; - arr[i] = temp; - } -} - -void printArray(int arr[], int size) { - for (int i = 0; i < size; i++) { - printf("%d ", arr[i]); - } - printf("\\n"); -} - -int main() { - int arr[] = {64, 25, 12, 22, 11}; - int n = sizeof(arr) / sizeof(arr[0]); - - printf("Original: "); - printArray(arr, n); - - selectionSort(arr, n); - - printf("Sorted: "); - printArray(arr, n); - - return 0; -}`, - - cpp: `// Selection Sort in C++ -#include -#include -using namespace std; - -void selectionSort(vector& arr) { - int n = arr.size(); - - for (int i = 0; i < n - 1; i++) { - // Find the minimum element in unsorted array - int minIdx = i; - for (int j = i + 1; j < n; j++) { - if (arr[j] < arr[minIdx]) { - minIdx = j; - } - } - - // Swap the found minimum with the first element - swap(arr[i], arr[minIdx]); - } -} - -void printArray(const vector& arr) { - for (int num : arr) { - cout << num << " "; - } - cout << endl; -} - -int main() { - vector arr = {64, 25, 12, 22, 11}; - - cout << "Original: "; - printArray(arr); - - selectionSort(arr); - - cout << "Sorted: "; - printArray(arr); - - return 0; -}` - }; - - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Selection Sort Implementation -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                  
-                
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); - }; - - export default CodeBlock; \ No newline at end of file diff --git a/app/visualizer/sorting/selectionsort/page.jsx b/app/visualizer/sorting/selectionsort/page.jsx index cd6a310..0414375 100755 --- a/app/visualizer/sorting/selectionsort/page.jsx +++ b/app/visualizer/sorting/selectionsort/page.jsx @@ -5,7 +5,8 @@ import BackToTopButton from "@/app/components/ui/backtotop"; import Footer from "@/app/components/footer"; import Content from '@/app/visualizer/sorting/selectionsort/content'; import ExploreOther from "@/app/components/ui/exploreOther"; -import Code from "@/app/visualizer/sorting/selectionsort/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import Quiz from "@/app/visualizer/sorting/selectionsort/quiz"; import ModuleCard from "@/app/components/ui/ModuleCard"; import { MODULE_MAPS } from "@/lib/modulesMap"; @@ -74,7 +75,7 @@ export default function Page() {
- +
diff --git a/app/visualizer/stack/implementation/usingArray/codeBlock.jsx b/app/visualizer/stack/implementation/usingArray/code.js similarity index 57% rename from app/visualizer/stack/implementation/usingArray/codeBlock.jsx rename to app/visualizer/stack/implementation/usingArray/code.js index 27f1e5d..bc2acce 100755 --- a/app/visualizer/stack/implementation/usingArray/codeBlock.jsx +++ b/app/visualizer/stack/implementation/usingArray/code.js @@ -1,41 +1,4 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - - const codeExamples = { +const codeExamples = { javascript: `// Stack Implementation using Array (JavaScript) class Stack { constructor(size = 10) { @@ -409,122 +372,4 @@ int main() { }`, }; - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Stack Implementation using Array -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                
-              
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); -}; - -export default CodeBlock; \ No newline at end of file +export default codeExamples; diff --git a/app/visualizer/stack/implementation/usingArray/page.jsx b/app/visualizer/stack/implementation/usingArray/page.jsx index f73d349..6211778 100755 --- a/app/visualizer/stack/implementation/usingArray/page.jsx +++ b/app/visualizer/stack/implementation/usingArray/page.jsx @@ -1,7 +1,8 @@ import Navbar from "@/app/components/navbarinner"; import ModuleHeader from "@/app/components/modules/Header"; import Content from "@/app/visualizer/stack/implementation/usingArray/content"; -import Code from "@/app/visualizer/stack/implementation/usingArray/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import ModuleCard from "@/app/components/ui/ModuleCard"; import { MODULE_MAPS } from "@/lib/modulesMap"; import Footer from "@/app/components/footer"; @@ -60,7 +61,7 @@ export default function Page() {
- +
diff --git a/app/visualizer/stack/implementation/usingLinkedList/codeBlock.jsx b/app/visualizer/stack/implementation/usingLinkedList/code.js similarity index 58% rename from app/visualizer/stack/implementation/usingLinkedList/codeBlock.jsx rename to app/visualizer/stack/implementation/usingLinkedList/code.js index 2f095c2..5124c7e 100755 --- a/app/visualizer/stack/implementation/usingLinkedList/codeBlock.jsx +++ b/app/visualizer/stack/implementation/usingLinkedList/code.js @@ -1,41 +1,4 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - - const codeExamples = { +const codeExamples = { javascript: `// Stack Implementation using Linked List (JavaScript) class Node { constructor(value) { @@ -441,122 +404,4 @@ int main() { }` }; - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Stack Implementation using Linked-List -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                  
-                
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); - }; - - export default CodeBlock; \ No newline at end of file +export default codeExamples; diff --git a/app/visualizer/stack/implementation/usingLinkedList/page.jsx b/app/visualizer/stack/implementation/usingLinkedList/page.jsx index 3bc4ac8..f2d635f 100755 --- a/app/visualizer/stack/implementation/usingLinkedList/page.jsx +++ b/app/visualizer/stack/implementation/usingLinkedList/page.jsx @@ -1,7 +1,8 @@ import Navbar from "@/app/components/navbarinner"; import ModuleHeader from "@/app/components/modules/Header"; import Content from "@/app/visualizer/stack/implementation/usingLinkedList/content"; -import Code from "@/app/visualizer/stack/implementation/usingLinkedList/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import ModuleCard from "@/app/components/ui/ModuleCard"; import { MODULE_MAPS } from "@/lib/modulesMap"; import Footer from "@/app/components/footer"; @@ -60,7 +61,7 @@ export default function Page() {
- +
diff --git a/app/visualizer/stack/isempty/codeBlock.jsx b/app/visualizer/stack/isempty/code.js similarity index 51% rename from app/visualizer/stack/isempty/codeBlock.jsx rename to app/visualizer/stack/isempty/code.js index 3d0df8f..ad12fb4 100755 --- a/app/visualizer/stack/isempty/codeBlock.jsx +++ b/app/visualizer/stack/isempty/code.js @@ -1,41 +1,4 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - - const codeExamples = { +const codeExamples = { javascript: `// Stack Implementation with isEmpty Operation in JavaScript class Stack { constructor() { @@ -330,122 +293,4 @@ int main() { }`, }; - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Stack Push & Pop Implementation -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                
-              
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); -}; - -export default CodeBlock; \ No newline at end of file +export default codeExamples; diff --git a/app/visualizer/stack/isempty/page.jsx b/app/visualizer/stack/isempty/page.jsx index 24165eb..570280b 100755 --- a/app/visualizer/stack/isempty/page.jsx +++ b/app/visualizer/stack/isempty/page.jsx @@ -3,7 +3,8 @@ import Navbar from "@/app/components/navbarinner"; import ModuleHeader from "@/app/components/modules/Header"; import Content from "@/app/visualizer/stack/isempty/content"; import Quiz from "@/app/visualizer/stack/isempty/quiz"; -import Code from "@/app/visualizer/stack/isempty/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import ModuleCard from "@/app/components/ui/ModuleCard"; import { MODULE_MAPS } from "@/lib/modulesMap"; import ExploreOther from "@/app/components/ui/exploreOther"; @@ -72,7 +73,7 @@ export default function Page() {
- +
diff --git a/app/visualizer/stack/isfull/codeBlock.jsx b/app/visualizer/stack/isfull/code.js similarity index 55% rename from app/visualizer/stack/isfull/codeBlock.jsx rename to app/visualizer/stack/isfull/code.js index 72c4dc5..05d3dff 100755 --- a/app/visualizer/stack/isfull/codeBlock.jsx +++ b/app/visualizer/stack/isfull/code.js @@ -1,41 +1,4 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - - const codeExamples = { +const codeExamples = { javascript: `// Stack Implementation with isFull Operation in JavaScript class Stack { constructor(maxSize = 5) { @@ -379,122 +342,4 @@ int main() { }` }; - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Stack Push & Pop Implementation -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                    
-                  
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); - }; - - export default CodeBlock; \ No newline at end of file +export default codeExamples; diff --git a/app/visualizer/stack/isfull/page.jsx b/app/visualizer/stack/isfull/page.jsx index 19b9af1..246ae15 100755 --- a/app/visualizer/stack/isfull/page.jsx +++ b/app/visualizer/stack/isfull/page.jsx @@ -3,7 +3,8 @@ import Navbar from "@/app/components/navbarinner"; import ModuleHeader from "@/app/components/modules/Header"; import Content from "@/app/visualizer/stack/isfull/content"; import Quiz from "@/app/visualizer/stack/isfull/quiz"; -import Code from "@/app/visualizer/stack/isfull/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import ModuleCard from "@/app/components/ui/ModuleCard"; import { MODULE_MAPS } from "@/lib/modulesMap"; import ExploreOther from '@/app/components/ui/exploreOther'; @@ -72,7 +73,7 @@ export default function Page() {
- +
diff --git a/app/visualizer/stack/peek/codeBlock.jsx b/app/visualizer/stack/peek/code.js similarity index 50% rename from app/visualizer/stack/peek/codeBlock.jsx rename to app/visualizer/stack/peek/code.js index 34b9b13..d26c1f1 100755 --- a/app/visualizer/stack/peek/codeBlock.jsx +++ b/app/visualizer/stack/peek/code.js @@ -1,41 +1,4 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - - const codeExamples = { +const codeExamples = { javascript: `// Stack Implementation with Peek Operation in JavaScript class Stack { constructor() { @@ -347,122 +310,4 @@ int main() { }` }; - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Stack Push & Pop Implementation -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                  
-                
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); - }; - - export default CodeBlock; \ No newline at end of file +export default codeExamples; diff --git a/app/visualizer/stack/peek/page.jsx b/app/visualizer/stack/peek/page.jsx index 7a285c7..2755a99 100755 --- a/app/visualizer/stack/peek/page.jsx +++ b/app/visualizer/stack/peek/page.jsx @@ -3,7 +3,8 @@ import Navbar from "@/app/components/navbarinner"; import ModuleHeader from "@/app/components/modules/Header"; import Content from "@/app/visualizer/stack/peek/content"; import Quiz from "@/app/visualizer/stack/peek/quiz"; -import Code from "@/app/visualizer/stack/peek/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import ModuleCard from "@/app/components/ui/ModuleCard"; import { MODULE_MAPS } from "@/lib/modulesMap"; import ExploreOther from '@/app/components/ui/exploreOther'; @@ -73,7 +74,7 @@ export default function Page() {
- +
diff --git a/app/visualizer/stack/polish/postfix/code.js b/app/visualizer/stack/polish/postfix/code.js new file mode 100755 index 0000000..19f5aa9 --- /dev/null +++ b/app/visualizer/stack/polish/postfix/code.js @@ -0,0 +1,161 @@ +const codeExamples = { + javascript: `// Postfix Evaluation using Stack (JavaScript) +function evaluatePostfix(expression) { + let stack = []; + + for (let char of expression) { + if (!isNaN(char)) { + stack.push(parseInt(char)); + } else { + const b = stack.pop(); + const a = stack.pop(); + + switch(char) { + case '+': stack.push(a + b); break; + case '-': stack.push(a - b); break; + case '*': stack.push(a * b); break; + case '/': stack.push(Math.floor(a / b)); break; + } + } + } + return stack.pop(); +} + +// Example: "23*5+" becomes (2*3)+5 = 11 +console.log(evaluatePostfix("23*5+")); // Output: 11`, + + python: `# Postfix Evaluation using Stack (Python) +def evaluate_postfix(expression): + stack = [] + + for char in expression: + if char.isdigit(): + stack.append(int(char)) + else: + b = stack.pop() + a = stack.pop() + + if char == '+': stack.append(a + b) + elif char == '-': stack.append(a - b) + elif char == '*': stack.append(a * b) + elif char == '/': stack.append(a // b) + + return stack.pop() + +# Example: "23*5+" becomes (2*3)+5 = 11 +print(evaluate_postfix("23*5+")) # Output: 11`, + + java: `// Postfix Evaluation using Stack (Java) +import java.util.Stack; + +public class PostfixEvaluator { + public static int evaluatePostfix(String expression) { + Stack stack = new Stack<>(); + + for (char c : expression.toCharArray()) { + if (Character.isDigit(c)) { + stack.push(c - '0'); + } else { + int b = stack.pop(); + int a = stack.pop(); + + switch (c) { + case '+': stack.push(a + b); break; + case '-': stack.push(a - b); break; + case '*': stack.push(a * b); break; + case '/': stack.push(a / b); break; + } + } + } + return stack.pop(); + } + + public static void main(String[] args) { + // Example: "23*5+" becomes (2*3)+5 = 11 + System.out.println(evaluatePostfix("23*5+")); // Output: 11 + } +}`, + + c: `// Postfix Evaluation using Stack (C) +#include +#include +#include + +#define MAX_SIZE 100 + +typedef struct { + int data[MAX_SIZE]; + int top; +} Stack; + +void push(Stack *s, int val) { + s->data[++s->top] = val; +} + +int pop(Stack *s) { + return s->data[s->top--]; +} + +int evaluatePostfix(char* expression) { + Stack s = { .top = -1 }; + + for (int i = 0; expression[i]; i++) { + if (isdigit(expression[i])) { + push(&s, expression[i] - '0'); + } else { + int b = pop(&s); + int a = pop(&s); + + switch (expression[i]) { + case '+': push(&s, a + b); break; + case '-': push(&s, a - b); break; + case '*': push(&s, a * b); break; + case '/': push(&s, a / b); break; + } + } + } + return pop(&s); +} + +int main() { + // Example: "23*5+" becomes (2*3)+5 = 11 + printf("%d\\n", evaluatePostfix("23*5+")); // Output: 11 + return 0; +}`, + + cpp: `// Postfix Evaluation using Stack (C++) +#include +#include +#include +#include +using namespace std; + +int evaluatePostfix(const string& expression) { + stack st; + + for (char c : expression) { + if (isdigit(c)) { + st.push(c - '0'); + } else { + int b = st.top(); st.pop(); + int a = st.top(); st.pop(); + + switch (c) { + case '+': st.push(a + b); break; + case '-': st.push(a - b); break; + case '*': st.push(a * b); break; + case '/': st.push(a / b); break; + } + } + } + return st.top(); +} + +int main() { + // Example: "23*5+" becomes (2*3)+5 = 11 + cout << evaluatePostfix("23*5+") << endl; // Output: 11 + return 0; +}` + }; + +export default codeExamples; diff --git a/app/visualizer/stack/polish/postfix/codeBlock.jsx b/app/visualizer/stack/polish/postfix/codeBlock.jsx deleted file mode 100755 index b366978..0000000 --- a/app/visualizer/stack/polish/postfix/codeBlock.jsx +++ /dev/null @@ -1,316 +0,0 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - - const codeExamples = { - javascript: `// Postfix Evaluation using Stack (JavaScript) -function evaluatePostfix(expression) { - let stack = []; - - for (let char of expression) { - if (!isNaN(char)) { - stack.push(parseInt(char)); - } else { - const b = stack.pop(); - const a = stack.pop(); - - switch(char) { - case '+': stack.push(a + b); break; - case '-': stack.push(a - b); break; - case '*': stack.push(a * b); break; - case '/': stack.push(Math.floor(a / b)); break; - } - } - } - return stack.pop(); -} - -// Example: "23*5+" becomes (2*3)+5 = 11 -console.log(evaluatePostfix("23*5+")); // Output: 11`, - - python: `# Postfix Evaluation using Stack (Python) -def evaluate_postfix(expression): - stack = [] - - for char in expression: - if char.isdigit(): - stack.append(int(char)) - else: - b = stack.pop() - a = stack.pop() - - if char == '+': stack.append(a + b) - elif char == '-': stack.append(a - b) - elif char == '*': stack.append(a * b) - elif char == '/': stack.append(a // b) - - return stack.pop() - -# Example: "23*5+" becomes (2*3)+5 = 11 -print(evaluate_postfix("23*5+")) # Output: 11`, - - java: `// Postfix Evaluation using Stack (Java) -import java.util.Stack; - -public class PostfixEvaluator { - public static int evaluatePostfix(String expression) { - Stack stack = new Stack<>(); - - for (char c : expression.toCharArray()) { - if (Character.isDigit(c)) { - stack.push(c - '0'); - } else { - int b = stack.pop(); - int a = stack.pop(); - - switch (c) { - case '+': stack.push(a + b); break; - case '-': stack.push(a - b); break; - case '*': stack.push(a * b); break; - case '/': stack.push(a / b); break; - } - } - } - return stack.pop(); - } - - public static void main(String[] args) { - // Example: "23*5+" becomes (2*3)+5 = 11 - System.out.println(evaluatePostfix("23*5+")); // Output: 11 - } -}`, - - c: `// Postfix Evaluation using Stack (C) -#include -#include -#include - -#define MAX_SIZE 100 - -typedef struct { - int data[MAX_SIZE]; - int top; -} Stack; - -void push(Stack *s, int val) { - s->data[++s->top] = val; -} - -int pop(Stack *s) { - return s->data[s->top--]; -} - -int evaluatePostfix(char* expression) { - Stack s = { .top = -1 }; - - for (int i = 0; expression[i]; i++) { - if (isdigit(expression[i])) { - push(&s, expression[i] - '0'); - } else { - int b = pop(&s); - int a = pop(&s); - - switch (expression[i]) { - case '+': push(&s, a + b); break; - case '-': push(&s, a - b); break; - case '*': push(&s, a * b); break; - case '/': push(&s, a / b); break; - } - } - } - return pop(&s); -} - -int main() { - // Example: "23*5+" becomes (2*3)+5 = 11 - printf("%d\\n", evaluatePostfix("23*5+")); // Output: 11 - return 0; -}`, - - cpp: `// Postfix Evaluation using Stack (C++) -#include -#include -#include -#include -using namespace std; - -int evaluatePostfix(const string& expression) { - stack st; - - for (char c : expression) { - if (isdigit(c)) { - st.push(c - '0'); - } else { - int b = st.top(); st.pop(); - int a = st.top(); st.pop(); - - switch (c) { - case '+': st.push(a + b); break; - case '-': st.push(a - b); break; - case '*': st.push(a * b); break; - case '/': st.push(a / b); break; - } - } - } - return st.top(); -} - -int main() { - // Example: "23*5+" becomes (2*3)+5 = 11 - cout << evaluatePostfix("23*5+") << endl; // Output: 11 - return 0; -}` - }; - - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- PostFix implementation using Stack -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                    
-                  
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); - }; - - export default CodeBlock; \ No newline at end of file diff --git a/app/visualizer/stack/polish/postfix/page.jsx b/app/visualizer/stack/polish/postfix/page.jsx index 26e7f09..7b48910 100755 --- a/app/visualizer/stack/polish/postfix/page.jsx +++ b/app/visualizer/stack/polish/postfix/page.jsx @@ -3,7 +3,8 @@ import Navbar from "@/app/components/navbarinner"; import ModuleHeader from "@/app/components/modules/Header"; import Content from "@/app/visualizer/stack/polish/postfix/content"; import Quiz from "@/app/visualizer/stack/polish/postfix/quiz"; -import Code from "@/app/visualizer/stack/polish/postfix/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import ModuleCard from "@/app/components/ui/ModuleCard"; import { MODULE_MAPS } from "@/lib/modulesMap"; import Footer from "@/app/components/footer"; @@ -73,7 +74,7 @@ export default function Page() {
- +
diff --git a/app/visualizer/stack/polish/prefix/code.js b/app/visualizer/stack/polish/prefix/code.js new file mode 100755 index 0000000..af7fcc2 --- /dev/null +++ b/app/visualizer/stack/polish/prefix/code.js @@ -0,0 +1,168 @@ +const codeExamples = { + javascript: `// Prefix Evaluation using Stack (JavaScript) +function evaluatePrefix(expression) { + let stack = []; + // Process expression in reverse order + for (let i = expression.length - 1; i >= 0; i--) { + const char = expression[i]; + if (!isNaN(char)) { + stack.push(parseInt(char)); + } else { + const a = stack.pop(); + const b = stack.pop(); + + switch(char) { + case '+': stack.push(a + b); break; + case '-': stack.push(a - b); break; + case '*': stack.push(a * b); break; + case '/': stack.push(Math.floor(a / b)); break; + } + } + } + return stack.pop(); +} + +// Example: "+*235" becomes (2*3)+5 = 11 +console.log(evaluatePrefix("+*235")); // Output: 11`, + + python: `# Prefix Evaluation using Stack (Python) +def evaluate_prefix(expression): + stack = [] + # Process expression in reverse order + for char in reversed(expression): + if char.isdigit(): + stack.append(int(char)) + else: + a = stack.pop() + b = stack.pop() + + if char == '+': stack.append(a + b) + elif char == '-': stack.append(a - b) + elif char == '*': stack.append(a * b) + elif char == '/': stack.append(a // b) + + return stack.pop() + +# Example: "+*235" becomes (2*3)+5 = 11 +print(evaluate_prefix("+*235")) # Output: 11`, + + java: `// Prefix Evaluation using Stack (Java) +import java.util.Stack; + +public class PrefixEvaluator { + public static int evaluatePrefix(String expression) { + Stack stack = new Stack<>(); + // Process expression in reverse order + for (int i = expression.length() - 1; i >= 0; i--) { + char c = expression.charAt(i); + if (Character.isDigit(c)) { + stack.push(c - '0'); + } else { + int a = stack.pop(); + int b = stack.pop(); + + switch (c) { + case '+': stack.push(a + b); break; + case '-': stack.push(a - b); break; + case '*': stack.push(a * b); break; + case '/': stack.push(a / b); break; + } + } + } + return stack.pop(); + } + + public static void main(String[] args) { + // Example: "+*235" becomes (2*3)+5 = 11 + System.out.println(evaluatePrefix("+*235")); // Output: 11 + } +}`, + + c: `// Prefix Evaluation using Stack (C) +#include +#include +#include +#include + +#define MAX_SIZE 100 + +typedef struct { + int data[MAX_SIZE]; + int top; +} Stack; + +void push(Stack *s, int val) { + s->data[++s->top] = val; +} + +int pop(Stack *s) { + return s->data[s->top--]; +} + +int evaluatePrefix(char* expression) { + Stack s = { .top = -1 }; + int length = strlen(expression); + + // Process expression in reverse order + for (int i = length - 1; i >= 0; i--) { + if (isdigit(expression[i])) { + push(&s, expression[i] - '0'); + } else { + int a = pop(&s); + int b = pop(&s); + + switch (expression[i]) { + case '+': push(&s, a + b); break; + case '-': push(&s, a - b); break; + case '*': push(&s, a * b); break; + case '/': push(&s, a / b); break; + } + } + } + return pop(&s); +} + +int main() { + // Example: "+*235" becomes (2*3)+5 = 11 + printf("%d\n", evaluatePrefix("+*235")); // Output: 11 + return 0; +}`, + + cpp: `// Prefix Evaluation using Stack (C++) +#include +#include +#include +#include +using namespace std; + +int evaluatePrefix(const string& expression) { + stack st; + + // Process expression in reverse order + for (auto it = expression.rbegin(); it != expression.rend(); ++it) { + char c = *it; + if (isdigit(c)) { + st.push(c - '0'); + } else { + int a = st.top(); st.pop(); + int b = st.top(); st.pop(); + + switch (c) { + case '+': st.push(a + b); break; + case '-': st.push(a - b); break; + case '*': st.push(a * b); break; + case '/': st.push(a / b); break; + } + } + } + return st.top(); +} + +int main() { + // Example: "+*235" becomes (2*3)+5 = 11 + cout << evaluatePrefix("+*235") << endl; // Output: 11 + return 0; +}`, + }; + +export default codeExamples; diff --git a/app/visualizer/stack/polish/prefix/codeBlock.jsx b/app/visualizer/stack/polish/prefix/codeBlock.jsx deleted file mode 100755 index 0c03e46..0000000 --- a/app/visualizer/stack/polish/prefix/codeBlock.jsx +++ /dev/null @@ -1,323 +0,0 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - - const codeExamples = { - javascript: `// Prefix Evaluation using Stack (JavaScript) -function evaluatePrefix(expression) { - let stack = []; - // Process expression in reverse order - for (let i = expression.length - 1; i >= 0; i--) { - const char = expression[i]; - if (!isNaN(char)) { - stack.push(parseInt(char)); - } else { - const a = stack.pop(); - const b = stack.pop(); - - switch(char) { - case '+': stack.push(a + b); break; - case '-': stack.push(a - b); break; - case '*': stack.push(a * b); break; - case '/': stack.push(Math.floor(a / b)); break; - } - } - } - return stack.pop(); -} - -// Example: "+*235" becomes (2*3)+5 = 11 -console.log(evaluatePrefix("+*235")); // Output: 11`, - - python: `# Prefix Evaluation using Stack (Python) -def evaluate_prefix(expression): - stack = [] - # Process expression in reverse order - for char in reversed(expression): - if char.isdigit(): - stack.append(int(char)) - else: - a = stack.pop() - b = stack.pop() - - if char == '+': stack.append(a + b) - elif char == '-': stack.append(a - b) - elif char == '*': stack.append(a * b) - elif char == '/': stack.append(a // b) - - return stack.pop() - -# Example: "+*235" becomes (2*3)+5 = 11 -print(evaluate_prefix("+*235")) # Output: 11`, - - java: `// Prefix Evaluation using Stack (Java) -import java.util.Stack; - -public class PrefixEvaluator { - public static int evaluatePrefix(String expression) { - Stack stack = new Stack<>(); - // Process expression in reverse order - for (int i = expression.length() - 1; i >= 0; i--) { - char c = expression.charAt(i); - if (Character.isDigit(c)) { - stack.push(c - '0'); - } else { - int a = stack.pop(); - int b = stack.pop(); - - switch (c) { - case '+': stack.push(a + b); break; - case '-': stack.push(a - b); break; - case '*': stack.push(a * b); break; - case '/': stack.push(a / b); break; - } - } - } - return stack.pop(); - } - - public static void main(String[] args) { - // Example: "+*235" becomes (2*3)+5 = 11 - System.out.println(evaluatePrefix("+*235")); // Output: 11 - } -}`, - - c: `// Prefix Evaluation using Stack (C) -#include -#include -#include -#include - -#define MAX_SIZE 100 - -typedef struct { - int data[MAX_SIZE]; - int top; -} Stack; - -void push(Stack *s, int val) { - s->data[++s->top] = val; -} - -int pop(Stack *s) { - return s->data[s->top--]; -} - -int evaluatePrefix(char* expression) { - Stack s = { .top = -1 }; - int length = strlen(expression); - - // Process expression in reverse order - for (int i = length - 1; i >= 0; i--) { - if (isdigit(expression[i])) { - push(&s, expression[i] - '0'); - } else { - int a = pop(&s); - int b = pop(&s); - - switch (expression[i]) { - case '+': push(&s, a + b); break; - case '-': push(&s, a - b); break; - case '*': push(&s, a * b); break; - case '/': push(&s, a / b); break; - } - } - } - return pop(&s); -} - -int main() { - // Example: "+*235" becomes (2*3)+5 = 11 - printf("%d\n", evaluatePrefix("+*235")); // Output: 11 - return 0; -}`, - - cpp: `// Prefix Evaluation using Stack (C++) -#include -#include -#include -#include -using namespace std; - -int evaluatePrefix(const string& expression) { - stack st; - - // Process expression in reverse order - for (auto it = expression.rbegin(); it != expression.rend(); ++it) { - char c = *it; - if (isdigit(c)) { - st.push(c - '0'); - } else { - int a = st.top(); st.pop(); - int b = st.top(); st.pop(); - - switch (c) { - case '+': st.push(a + b); break; - case '-': st.push(a - b); break; - case '*': st.push(a * b); break; - case '/': st.push(a / b); break; - } - } - } - return st.top(); -} - -int main() { - // Example: "+*235" becomes (2*3)+5 = 11 - cout << evaluatePrefix("+*235") << endl; // Output: 11 - return 0; -}`, - }; - - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- PreFix implementation using Stack -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                
-              
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); -}; - -export default CodeBlock; \ No newline at end of file diff --git a/app/visualizer/stack/polish/prefix/page.jsx b/app/visualizer/stack/polish/prefix/page.jsx index 11f9548..3049c9e 100755 --- a/app/visualizer/stack/polish/prefix/page.jsx +++ b/app/visualizer/stack/polish/prefix/page.jsx @@ -3,7 +3,8 @@ import Navbar from "@/app/components/navbarinner"; import ModuleHeader from "@/app/components/modules/Header"; import Content from "@/app/visualizer/stack/polish/prefix/content"; import Quiz from "@/app/visualizer/stack/polish/postfix/quiz"; -import Code from "@/app/visualizer/stack/polish/prefix/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import ModuleCard from "@/app/components/ui/ModuleCard"; import { MODULE_MAPS } from "@/lib/modulesMap"; import Footer from "@/app/components/footer"; @@ -73,7 +74,7 @@ export default function Page() {
- +
diff --git a/app/visualizer/stack/push-pop/code.js b/app/visualizer/stack/push-pop/code.js new file mode 100755 index 0000000..3b15d0c --- /dev/null +++ b/app/visualizer/stack/push-pop/code.js @@ -0,0 +1,260 @@ +const codeExamples = { + javascript: `// Stack Implementation with Push/Pop in JavaScript +class Stack { + constructor() { + this.items = []; + this.top = -1; + this.MAX_SIZE = 10; + } + + // Push operation + push(element) { + if (this.top >= this.MAX_SIZE - 1) { + console.log("Stack Overflow"); + return; + } + this.items[++this.top] = element; + console.log(\`Pushed: \${element}\`); + } + + // Pop operation + pop() { + if (this.top < 0) { + console.log("Stack Underflow"); + return -1; + } + const element = this.items[this.top--]; + console.log(\`Popped: \${element}\`); + return element; + } + + // Display stack + display() { + console.log("Current Stack:", this.items.slice(0, this.top + 1)); + } +} + +// Usage +const stack = new Stack(); +stack.push(10); +stack.push(20); +stack.push(30); +stack.display(); +stack.pop(); +stack.display();`, + + python: `# Stack Implementation with Push/Pop in Python +class Stack: + def __init__(self): + self.items = [] + self.top = -1 + self.MAX_SIZE = 10 + + # Push operation + def push(self, element): + if self.top >= self.MAX_SIZE - 1: + print("Stack Overflow") + return + self.top += 1 + self.items.append(element) + print(f"Pushed: {element}") + + # Pop operation + def pop(self): + if self.top < 0: + print("Stack Underflow") + return -1 + element = self.items.pop() + self.top -= 1 + print(f"Popped: {element}") + return element + + # Display stack + def display(self): + print("Current Stack:", self.items) + +# Usage +stack = Stack() +stack.push(10) +stack.push(20) +stack.push(30) +stack.display() +stack.pop() +stack.display()`, + + java: `// Stack Implementation with Push/Pop in Java +import java.util.ArrayList; + +class Stack { + private ArrayList items; + private int top; + private final int MAX_SIZE = 10; + + public Stack() { + items = new ArrayList<>(); + top = -1; + } + + // Push operation + public void push(int element) { + if (top >= MAX_SIZE - 1) { + System.out.println("Stack Overflow"); + return; + } + items.add(++top, element); + System.out.println("Pushed: " + element); + } + + // Pop operation + public int pop() { + if (top < 0) { + System.out.println("Stack Underflow"); + return -1; + } + int element = items.remove(top--); + System.out.println("Popped: " + element); + return element; + } + + // Display stack + public void display() { + System.out.print("Current Stack: "); + for (int i = 0; i <= top; i++) { + System.out.print(items.get(i) + " "); + } + System.out.println(); + } +} + +public class Main { + public static void main(String[] args) { + Stack stack = new Stack(); + stack.push(10); + stack.push(20); + stack.push(30); + stack.display(); + stack.pop(); + stack.display(); + } +}`, + + c: `// Stack Implementation with Push/Pop in C +#include +#include +#define MAX_SIZE 10 + +typedef struct { + int items[MAX_SIZE]; + int top; +} Stack; + +void initialize(Stack *s) { + s->top = -1; +} + +// Push operation +void push(Stack *s, int element) { + if (s->top >= MAX_SIZE - 1) { + printf("Stack Overflow\\n"); + return; + } + s->items[++s->top] = element; + printf("Pushed: %d\\n", element); +} + +// Pop operation +int pop(Stack *s) { + if (s->top < 0) { + printf("Stack Underflow\\n"); + return -1; + } + int element = s->items[s->top--]; + printf("Popped: %d\\n", element); + return element; +} + +// Display stack +void display(Stack *s) { + printf("Current Stack: "); + for (int i = 0; i <= s->top; i++) { + printf("%d ", s->items[i]); + } + printf("\\n"); +} + +int main() { + Stack stack; + initialize(&stack); + + push(&stack, 10); + push(&stack, 20); + push(&stack, 30); + display(&stack); + pop(&stack); + display(&stack); + + return 0; +}`, + + cpp: `// Stack Implementation with Push/Pop in C++ +#include +#include +using namespace std; + +class Stack { +private: + vector items; + int top; + const int MAX_SIZE = 10; + +public: + Stack() : top(-1) {} + + // Push operation + void push(int element) { + if (top >= MAX_SIZE - 1) { + cout << "Stack Overflow" << endl; + return; + } + items.push_back(element); + top++; + cout << "Pushed: " << element << endl; + } + + // Pop operation + int pop() { + if (top < 0) { + cout << "Stack Underflow" << endl; + return -1; + } + int element = items.back(); + items.pop_back(); + top--; + cout << "Popped: " << element << endl; + return element; + } + + // Display stack + void display() { + cout << "Current Stack: "; + for (int i = 0; i <= top; i++) { + cout << items[i] << " "; + } + cout << endl; + } +}; + +int main() { + Stack stack; + stack.push(10); + stack.push(20); + stack.push(30); + stack.display(); + stack.pop(); + stack.display(); + + return 0; +}`, + }; + +export default codeExamples; diff --git a/app/visualizer/stack/push-pop/codeBlock.jsx b/app/visualizer/stack/push-pop/codeBlock.jsx deleted file mode 100755 index 135138a..0000000 --- a/app/visualizer/stack/push-pop/codeBlock.jsx +++ /dev/null @@ -1,415 +0,0 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - - const codeExamples = { - javascript: `// Stack Implementation with Push/Pop in JavaScript -class Stack { - constructor() { - this.items = []; - this.top = -1; - this.MAX_SIZE = 10; - } - - // Push operation - push(element) { - if (this.top >= this.MAX_SIZE - 1) { - console.log("Stack Overflow"); - return; - } - this.items[++this.top] = element; - console.log(\`Pushed: \${element}\`); - } - - // Pop operation - pop() { - if (this.top < 0) { - console.log("Stack Underflow"); - return -1; - } - const element = this.items[this.top--]; - console.log(\`Popped: \${element}\`); - return element; - } - - // Display stack - display() { - console.log("Current Stack:", this.items.slice(0, this.top + 1)); - } -} - -// Usage -const stack = new Stack(); -stack.push(10); -stack.push(20); -stack.push(30); -stack.display(); -stack.pop(); -stack.display();`, - - python: `# Stack Implementation with Push/Pop in Python -class Stack: - def __init__(self): - self.items = [] - self.top = -1 - self.MAX_SIZE = 10 - - # Push operation - def push(self, element): - if self.top >= self.MAX_SIZE - 1: - print("Stack Overflow") - return - self.top += 1 - self.items.append(element) - print(f"Pushed: {element}") - - # Pop operation - def pop(self): - if self.top < 0: - print("Stack Underflow") - return -1 - element = self.items.pop() - self.top -= 1 - print(f"Popped: {element}") - return element - - # Display stack - def display(self): - print("Current Stack:", self.items) - -# Usage -stack = Stack() -stack.push(10) -stack.push(20) -stack.push(30) -stack.display() -stack.pop() -stack.display()`, - - java: `// Stack Implementation with Push/Pop in Java -import java.util.ArrayList; - -class Stack { - private ArrayList items; - private int top; - private final int MAX_SIZE = 10; - - public Stack() { - items = new ArrayList<>(); - top = -1; - } - - // Push operation - public void push(int element) { - if (top >= MAX_SIZE - 1) { - System.out.println("Stack Overflow"); - return; - } - items.add(++top, element); - System.out.println("Pushed: " + element); - } - - // Pop operation - public int pop() { - if (top < 0) { - System.out.println("Stack Underflow"); - return -1; - } - int element = items.remove(top--); - System.out.println("Popped: " + element); - return element; - } - - // Display stack - public void display() { - System.out.print("Current Stack: "); - for (int i = 0; i <= top; i++) { - System.out.print(items.get(i) + " "); - } - System.out.println(); - } -} - -public class Main { - public static void main(String[] args) { - Stack stack = new Stack(); - stack.push(10); - stack.push(20); - stack.push(30); - stack.display(); - stack.pop(); - stack.display(); - } -}`, - - c: `// Stack Implementation with Push/Pop in C -#include -#include -#define MAX_SIZE 10 - -typedef struct { - int items[MAX_SIZE]; - int top; -} Stack; - -void initialize(Stack *s) { - s->top = -1; -} - -// Push operation -void push(Stack *s, int element) { - if (s->top >= MAX_SIZE - 1) { - printf("Stack Overflow\\n"); - return; - } - s->items[++s->top] = element; - printf("Pushed: %d\\n", element); -} - -// Pop operation -int pop(Stack *s) { - if (s->top < 0) { - printf("Stack Underflow\\n"); - return -1; - } - int element = s->items[s->top--]; - printf("Popped: %d\\n", element); - return element; -} - -// Display stack -void display(Stack *s) { - printf("Current Stack: "); - for (int i = 0; i <= s->top; i++) { - printf("%d ", s->items[i]); - } - printf("\\n"); -} - -int main() { - Stack stack; - initialize(&stack); - - push(&stack, 10); - push(&stack, 20); - push(&stack, 30); - display(&stack); - pop(&stack); - display(&stack); - - return 0; -}`, - - cpp: `// Stack Implementation with Push/Pop in C++ -#include -#include -using namespace std; - -class Stack { -private: - vector items; - int top; - const int MAX_SIZE = 10; - -public: - Stack() : top(-1) {} - - // Push operation - void push(int element) { - if (top >= MAX_SIZE - 1) { - cout << "Stack Overflow" << endl; - return; - } - items.push_back(element); - top++; - cout << "Pushed: " << element << endl; - } - - // Pop operation - int pop() { - if (top < 0) { - cout << "Stack Underflow" << endl; - return -1; - } - int element = items.back(); - items.pop_back(); - top--; - cout << "Popped: " << element << endl; - return element; - } - - // Display stack - void display() { - cout << "Current Stack: "; - for (int i = 0; i <= top; i++) { - cout << items[i] << " "; - } - cout << endl; - } -}; - -int main() { - Stack stack; - stack.push(10); - stack.push(20); - stack.push(30); - stack.display(); - stack.pop(); - stack.display(); - - return 0; -}`, - }; - - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Stack Push & Pop Implementation -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                
-              
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); -}; - -export default CodeBlock; \ No newline at end of file diff --git a/app/visualizer/stack/push-pop/page.jsx b/app/visualizer/stack/push-pop/page.jsx index c4737a9..8e0ad4b 100755 --- a/app/visualizer/stack/push-pop/page.jsx +++ b/app/visualizer/stack/push-pop/page.jsx @@ -3,7 +3,8 @@ import Navbar from "@/app/components/navbarinner"; import ModuleHeader from "@/app/components/modules/Header"; import Content from "@/app/visualizer/stack/push-pop/content"; import Quiz from "@/app/visualizer/stack/push-pop/quiz"; -import Code from "@/app/visualizer/stack/push-pop/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import ExploreOther from "@/app/components/ui/exploreOther"; import ModuleCard from "@/app/components/ui/ModuleCard"; import { MODULE_MAPS } from "@/lib/modulesMap"; @@ -77,7 +78,7 @@ export default function Page() {
- +
diff --git a/app/visualizer/trees/binaryTree/types/animation.jsx b/app/visualizer/trees/binaryTree/types/animation.jsx index 8b1d272..d6c04a7 100755 --- a/app/visualizer/trees/binaryTree/types/animation.jsx +++ b/app/visualizer/trees/binaryTree/types/animation.jsx @@ -2,7 +2,8 @@ import Footer from "@/app/components/footer"; import ExploreOther from "@/app/components/ui/exploreOther"; import Content from "@/app/visualizer/trees/binaryTree/types/content"; -import CodeBlock from "@/app/visualizer/trees/binaryTree/types/codeBlock"; +import CodeBlock from "@/app/components/modules/CodeBlock"; +import codeExamples from "./code"; import GoBackButton from "@/app/components/ui/goback"; import BackToTop from "@/app/components/ui/backtotop"; @@ -23,7 +24,7 @@ const InfixToPostfixVisualizer = () => {

- + i + 1); + console.log("Full Binary Tree (level):", tree.join(" ")); + } + + static Degenerate(count = 4) { + const tree = Array.from({ length: count }, (_, i) => i + 1); + console.log("Degenerate/Skewed (in-order):", tree.join(" -> ")); + } + + static Complete(count = 10) { + const tree = Array.from({ length: count }, (_, i) => i + 1); + console.log("Complete Binary Tree (level):", tree.join(" ")); + } +} + +TreeTypes.Full(7); +TreeTypes.Degenerate(4); +TreeTypes.Complete(10);`, + + python: `class TreeTypes: + @staticmethod + def Full(capacity=7): + tree = [i + 1 for i in range(capacity)] + print("Full Binary Tree (level):", *tree) + + @staticmethod + def Degenerate(count=4): + tree = [i + 1 for i in range(count)] + print("Degenerate/Skewed (in-order):", " -> ".join(map(str, tree))) + + @staticmethod + def Complete(count=10): + tree = [i + 1 for i in range(count)] + print("Complete Binary Tree (level):", *tree) + + +if __name__ == "__main__": + TreeTypes.Full(7) + TreeTypes.Degenerate(4) + TreeTypes.Complete(10)`, + + java: `public class TreeTypes { + + public static void Full(int capacity) { + int[] tree = new int[capacity]; + for (int i = 0; i < capacity; i++) tree[i] = i + 1; + System.out.print("Full Binary Tree (level):"); + for (int v : tree) System.out.print(" " + v); + System.out.println(); + } + + public static void Degenerate(int count) { + int[] tree = new int[count]; + for (int i = 0; i < count; i++) tree[i] = i + 1; + System.out.print("Degenerate/Skewed (in-order):"); + for (int i = 0; i < count; i++) { + System.out.print(i == 0 ? " " : " -> "); + System.out.print(tree[i]); + } + System.out.println(); + } + + public static void Complete(int count) { + int[] tree = new int[count]; + for (int i = 0; i < count; i++) tree[i] = i + 1; + System.out.print("Complete Binary Tree (level):"); + for (int v : tree) System.out.print(" " + v); + System.out.println(); + } + + public static void main(String[] args) { + Full(7); + Degenerate(4); + Complete(10); + } +}`, + + c: `#include +#include + +typedef struct { + int *tree; + int size; +} TreeArray; + +void Full(int capacity) { + TreeArray t = { malloc(capacity * sizeof(int)), capacity }; + for (int i = 0; i < capacity; i++) t.tree[i] = i + 1; + printf("Full Binary Tree (level):"); + for (int i = 0; i < capacity; i++) printf(" %d", t.tree[i]); + printf("\n"); + free(t.tree); +} + +void Degenerate(int count) { + TreeArray t = { malloc(count * sizeof(int)), count }; + for (int i = 0; i < count; i++) t.tree[i] = i + 1; + printf("Degenerate/Skewed (in-order):"); + for (int i = 0; i < count; i++) { + printf(i ? " -> %d" : " %d", t.tree[i]); + } + printf("\n"); + free(t.tree); +} + +void Complete(int count) { + TreeArray t = { malloc(count * sizeof(int)), count }; + for (int i = 0; i < count; i++) t.tree[i] = i + 1; + printf("Complete Binary Tree (level):"); + for (int i = 0; i < count; i++) printf(" %d", t.tree[i]); + printf("\n"); + free(t.tree); +} + +int main() { + Full(7); + Degenerate(4); + Complete(10); + return 0; +}`, + + cpp: `#include +#include + +class TreeTypes { +public: + static void Full(int capacity = 7) { + std::vector tree(capacity); + for (int i = 0; i < capacity; ++i) tree[i] = i + 1; + std::cout << "Full Binary Tree (level):"; + for (int v : tree) std::cout << ' ' << v; + std::cout << '\n'; + } + + static void Degenerate(int count = 4) { + std::vector tree(count); + for (int i = 0; i < count; ++i) tree[i] = i + 1; + std::cout << "Degenerate/Skewed (in-order):"; + for (int i = 0; i < count; ++i) { + std::cout << (i ? " -> " : " ") << tree[i]; + } + std::cout << '\n'; + } + + static void Complete(int count = 10) { + std::vector tree(count); + for (int i = 0; i < count; ++i) tree[i] = i + 1; + std::cout << "Complete Binary Tree (level):"; + for (int v : tree) std::cout << ' ' << v; + std::cout << '\n'; + } +}; + +int main() { + TreeTypes::Full(7); + TreeTypes::Degenerate(4); + TreeTypes::Complete(10); + return 0; +}`, + }; + +export default codeExamples; diff --git a/app/visualizer/trees/binaryTree/types/codeBlock.jsx b/app/visualizer/trees/binaryTree/types/codeBlock.jsx deleted file mode 100755 index 10f90ae..0000000 --- a/app/visualizer/trees/binaryTree/types/codeBlock.jsx +++ /dev/null @@ -1,320 +0,0 @@ -'use client'; -import { useState, useRef } from 'react'; -import { FaCopy, FaCheck, FaCode } from 'react-icons/fa'; -import { motion, AnimatePresence } from 'framer-motion'; -import hljs from 'highlight.js'; -import 'highlight.js/styles/github.css'; -import 'highlight.js/styles/github-dark.css'; - -export const highlightCode = (code, language) => { - const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'; - return hljs.highlight(code, { language: validLanguage }).value; -}; - -const CodeBlock = () => { - const [selectedLanguage, setSelectedLanguage] = useState("javascript"); - const [copied, setCopied] = useState(false); - const [isHovered, setIsHovered] = useState(false); - const topRef = useRef(null); - - const languages = [ - { id: "javascript", name: "JavaScript" }, - { id: "python", name: "Python" }, - { id: "java", name: "Java" }, - { id: "c", name: "C" }, - { id: "cpp", name: "C++" }, - ]; - - const copyToClipboard = async (text) => { - try { - await navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (err) { - console.error("Failed to copy text: ", err); - } - }; - - const codeExamples = { - javascript: `class TreeTypes { - static Full(capacity = 7) { - const tree = Array.from({ length: capacity }, (_, i) => i + 1); - console.log("Full Binary Tree (level):", tree.join(" ")); - } - - static Degenerate(count = 4) { - const tree = Array.from({ length: count }, (_, i) => i + 1); - console.log("Degenerate/Skewed (in-order):", tree.join(" -> ")); - } - - static Complete(count = 10) { - const tree = Array.from({ length: count }, (_, i) => i + 1); - console.log("Complete Binary Tree (level):", tree.join(" ")); - } -} - -TreeTypes.Full(7); -TreeTypes.Degenerate(4); -TreeTypes.Complete(10);`, - - python: `class TreeTypes: - @staticmethod - def Full(capacity=7): - tree = [i + 1 for i in range(capacity)] - print("Full Binary Tree (level):", *tree) - - @staticmethod - def Degenerate(count=4): - tree = [i + 1 for i in range(count)] - print("Degenerate/Skewed (in-order):", " -> ".join(map(str, tree))) - - @staticmethod - def Complete(count=10): - tree = [i + 1 for i in range(count)] - print("Complete Binary Tree (level):", *tree) - - -if __name__ == "__main__": - TreeTypes.Full(7) - TreeTypes.Degenerate(4) - TreeTypes.Complete(10)`, - - java: `public class TreeTypes { - - public static void Full(int capacity) { - int[] tree = new int[capacity]; - for (int i = 0; i < capacity; i++) tree[i] = i + 1; - System.out.print("Full Binary Tree (level):"); - for (int v : tree) System.out.print(" " + v); - System.out.println(); - } - - public static void Degenerate(int count) { - int[] tree = new int[count]; - for (int i = 0; i < count; i++) tree[i] = i + 1; - System.out.print("Degenerate/Skewed (in-order):"); - for (int i = 0; i < count; i++) { - System.out.print(i == 0 ? " " : " -> "); - System.out.print(tree[i]); - } - System.out.println(); - } - - public static void Complete(int count) { - int[] tree = new int[count]; - for (int i = 0; i < count; i++) tree[i] = i + 1; - System.out.print("Complete Binary Tree (level):"); - for (int v : tree) System.out.print(" " + v); - System.out.println(); - } - - public static void main(String[] args) { - Full(7); - Degenerate(4); - Complete(10); - } -}`, - - c: `#include -#include - -typedef struct { - int *tree; - int size; -} TreeArray; - -void Full(int capacity) { - TreeArray t = { malloc(capacity * sizeof(int)), capacity }; - for (int i = 0; i < capacity; i++) t.tree[i] = i + 1; - printf("Full Binary Tree (level):"); - for (int i = 0; i < capacity; i++) printf(" %d", t.tree[i]); - printf("\n"); - free(t.tree); -} - -void Degenerate(int count) { - TreeArray t = { malloc(count * sizeof(int)), count }; - for (int i = 0; i < count; i++) t.tree[i] = i + 1; - printf("Degenerate/Skewed (in-order):"); - for (int i = 0; i < count; i++) { - printf(i ? " -> %d" : " %d", t.tree[i]); - } - printf("\n"); - free(t.tree); -} - -void Complete(int count) { - TreeArray t = { malloc(count * sizeof(int)), count }; - for (int i = 0; i < count; i++) t.tree[i] = i + 1; - printf("Complete Binary Tree (level):"); - for (int i = 0; i < count; i++) printf(" %d", t.tree[i]); - printf("\n"); - free(t.tree); -} - -int main() { - Full(7); - Degenerate(4); - Complete(10); - return 0; -}`, - - cpp: `#include -#include - -class TreeTypes { -public: - static void Full(int capacity = 7) { - std::vector tree(capacity); - for (int i = 0; i < capacity; ++i) tree[i] = i + 1; - std::cout << "Full Binary Tree (level):"; - for (int v : tree) std::cout << ' ' << v; - std::cout << '\n'; - } - - static void Degenerate(int count = 4) { - std::vector tree(count); - for (int i = 0; i < count; ++i) tree[i] = i + 1; - std::cout << "Degenerate/Skewed (in-order):"; - for (int i = 0; i < count; ++i) { - std::cout << (i ? " -> " : " ") << tree[i]; - } - std::cout << '\n'; - } - - static void Complete(int count = 10) { - std::vector tree(count); - for (int i = 0; i < count; ++i) tree[i] = i + 1; - std::cout << "Complete Binary Tree (level):"; - for (int v : tree) std::cout << ' ' << v; - std::cout << '\n'; - } -}; - -int main() { - TreeTypes::Full(7); - TreeTypes::Degenerate(4); - TreeTypes::Complete(10); - return 0; -}`, - }; - - return ( -
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} - > - - {/* Header */} -
-
- -

- Binary tree types -

-
- - copyToClipboard(codeExamples[selectedLanguage])} - className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-600 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-500 transition-colors text-gray-800 dark:text-gray-100 text-sm font-medium" - aria-label="Copy code" - > - - {copied ? ( - - Copied - - ) : ( - - Copy Code - - )} - - -
- - {/* Language Selector */} -
- {languages.map((lang) => ( - setSelectedLanguage(lang.id)} - className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${ - selectedLanguage === lang.id - ? "bg-blue-500 text-white shadow-md" - : "bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600" - }`} - > - {lang.name} - - ))} -
- - {/* Code Block */} -
- - -
-                
-              
-
-
- - {/* Language indicator (shown on hover) */} - - {isHovered && ( - - {selectedLanguage.toUpperCase()} - - )} - -
-
-
- ); -}; - -export default CodeBlock; \ No newline at end of file From 4860dd5ec4330a2dbafb4ab038b652ba2e992991 Mon Sep 17 00:00:00 2001 From: Sohan Rout Date: Sun, 2 Aug 2026 19:25:38 +0530 Subject: [PATCH 2/2] Feat : made the modules more interactive --- .../operations/comparison/animation.jsx | 42 +---- .../linkedList/operations/comparison/page.jsx | 42 +++++ .../linkedList/operations/comparison/quiz.jsx | 1 + .../operations/deletion/animation.jsx | 40 +---- .../linkedList/operations/deletion/page.jsx | 40 +++++ .../linkedList/operations/deletion/quiz.jsx | 1 + .../operations/insertion/animation.jsx | 42 +---- .../linkedList/operations/insertion/page.jsx | 42 +++++ .../linkedList/operations/insertion/quiz.jsx | 1 + .../linkedList/operations/merge/animation.jsx | 42 +---- .../linkedList/operations/merge/page.jsx | 42 +++++ .../linkedList/operations/merge/quiz.jsx | 1 + .../operations/reverse/animation.jsx | 42 +---- .../linkedList/operations/reverse/page.jsx | 42 +++++ .../linkedList/operations/reverse/quiz.jsx | 1 + .../operations/traversal/animation.jsx | 42 +---- .../linkedList/operations/traversal/page.jsx | 42 +++++ .../linkedList/operations/traversal/quiz.jsx | 1 + .../linkedList/types/doubly/animation.jsx | 44 +----- .../linkedList/types/doubly/page.jsx | 38 +++++ .../linkedList/types/doubly/quiz.jsx | 1 + .../searching/binarysearch/content.jsx | 148 +++++++++++++++++- .../searching/linearsearch/content.jsx | 134 +++++++++++++++- app/visualizer/sorting/bubblesort/content.jsx | 148 +++++++++++++++++- lib/modulesMap.js | 7 + public/sitemap-0.xml | 91 +++++------ 26 files changed, 774 insertions(+), 343 deletions(-) diff --git a/app/visualizer/linkedList/operations/comparison/animation.jsx b/app/visualizer/linkedList/operations/comparison/animation.jsx index ead9709..be41ef1 100755 --- a/app/visualizer/linkedList/operations/comparison/animation.jsx +++ b/app/visualizer/linkedList/operations/comparison/animation.jsx @@ -1,14 +1,6 @@ "use client"; import React, { useState, useRef, useEffect } from 'react'; import { gsap } from 'gsap'; -import Footer from '@/app/components/footer'; -import ExploreOther from '@/app/components/ui/exploreOther'; -import Content from "@/app/visualizer/linkedList/operations/comparison/content"; -import Quiz from '@/app/visualizer/linkedList/operations/comparison/quiz'; -import CodeBlock from "@/app/components/modules/CodeBlock"; -import codeExamples from "./code"; -import BackToTop from '@/app/components/ui/backtotop'; -import GoBackButton from "@/app/components/ui/goback"; const LinkedListComparison = () => { const [list1, setList1] = useState([]); @@ -112,17 +104,7 @@ const LinkedListComparison = () => { }, [list1, list2]); return ( -
-
-
- -
- -

- Linked List Comparison -

-
- +

Visualize comparison of two linked lists node by node

@@ -274,28 +256,6 @@ const LinkedListComparison = () => {
- -

- Test Your Knowledge Before Moving Forward! -

- - - - - - - -