├── .DS_Store ├── .github └── workflows │ └── follow_and_star_check.yml ├── .vscode ├── c_cpp_properties.json ├── launch.json └── settings.json ├── 3Sum Closest ├── BsearchForinfiniteArraysize.java ├── C++ ├── Best Time to Buy and Sell Stock with Transaction Fee.cpp ├── Book Allocation Problem.cpp ├── Equilateral_Algorithm.cpp ├── GCD.cpp ├── GCD_or_HCF.cpp ├── HCF.cpp ├── Knapsack.cpp ├── Kruskals_Algorithm.cpp ├── Linked List │ ├── Circular LinkedList.cpp │ ├── Doubly LinkedList.cpp │ ├── MergeTwoSortedLists.cpp │ └── singly LinkedList.cpp ├── Longest_Common_Subsequence.cpp ├── Matrix multiplication.cpp ├── N _times_names.cpp ├── Prims-algo ├── Prims_Algorithm.cpp ├── Prims_Kruskal.cpp ├── SelectionSort.cpp ├── Stack.cpp │ ├── Area of largest rectangle in Histogram.cpp │ ├── AsteroidCollision.cpp │ ├── CelebrityProblem.cpp │ ├── Nearest_Left_Right.cpp │ └── NextGreaterElement.cpp ├── StringInterviewQuetions │ ├── Strings.md │ ├── quetion1.cpp │ ├── quetion10.cpp │ ├── quetion10.exe │ ├── quetion2.cpp │ ├── quetion2.exe │ ├── quetion3.cpp │ ├── quetion3.exe │ ├── quetion4.cpp │ ├── quetion4.exe │ ├── quetion5.cpp │ ├── quetion5.exe │ ├── quetion6.cpp │ ├── quetion6.exe │ ├── quetion7.cpp │ ├── quetion7.exe │ ├── quetion8.cpp │ ├── quetion8.exe │ ├── quetion9.cpp │ └── quetion9.exe ├── Sudoku_Solver.cpp ├── Treap.cpp ├── Update BinarySearch.md ├── binary_search.cpp ├── binary_search.exe ├── linear-search.cpp ├── mostOptimalBFS.cpp ├── multipleconstructor.cpp ├── paintersPartition.cpp ├── print_name_n_times.cpp ├── printnameNtimes.cpp ├── segment.cpp └── symmetric_Tree.cpp ├── C ├── Binarysearch.c ├── Pattern 1.c ├── Pattern 10.c ├── Pattern 2.c ├── Pattern 3.c ├── Pattern 4.c ├── Pattern 5.c ├── Pattern 6.c ├── Pattern 7.c ├── Pattern 8.c ├── Pattern 9.c ├── Pattern1.c ├── Pattern2.c ├── Pattern3.c ├── Pattern5.c ├── Right-Triangle-Pattern.c └── output │ └── Pattern 1.exe ├── CONTRIBUTING.md ├── JAVA ├── A.java ├── BinarySearch.java ├── BucketSort.java ├── DYNAMIC_PROGRAMMING │ ├── UniquePaths.java │ ├── House-robber.java │ ├── IntegerBreak.java │ ├── JumpGame.java │ ├── MaximumProductSubarray.java │ └── MaximumSubarray.java ├── DoublyLinkedList.java ├── LINKEDLIST │ ├── DeleteNode.java │ └── LinkedList.java ├── LinkedList.java ├── LinkedList │ ├── LinkedListPailendrom.java │ └── LinkedListSize.java ├── SEARCHING_ALGORITHM │ ├── BinarySearch.java │ └── linear-search.java └── Treap_in_Java.java ├── JavaScript ├── TelephoneNumberValidator ├── bookmark_manager │ ├── index.html │ └── script.js ├── clock.js └── gradient-generator │ ├── README.md │ ├── css │ └── style.css │ ├── img │ ├── Untitled design (3).png │ └── logo.png │ └── index.html ├── Median of Two Sorted Arrays ├── PYTHON ├── A.py ├── Kruskals.py ├── Prims.py ├── RAG_boilerplate.py ├── Treap_in_Python.py ├── WikiLLM.py ├── Wikipedia_bot.py ├── anti-malware.py ├── calculator.py ├── database3.csv ├── editor.ui ├── even.txt ├── file.py ├── file2.py ├── file3.py ├── firstfile.txt ├── hello.txt ├── image_detection.py ├── k_means_clustering.py ├── linear-search.py ├── merge_sort.py ├── numbers.txt ├── odd.txt ├── password_protected_pdf.py ├── pdf_merger.py ├── product.txt └── text_editor.py ├── README.md ├── Rhombus_patten.c ├── Spiral Matrix └── portfolio.html /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panditakshay402/Hacktoberfest/d3cd7b4552bd0543c1b182545aecc66a1ebca038/.DS_Store -------------------------------------------------------------------------------- /.github/workflows/follow_and_star_check.yml: -------------------------------------------------------------------------------- 1 | name: PR Follow and Star Check 2 | 3 | on: 4 | pull_request: 5 | types: [opened, reopened] 6 | 7 | jobs: 8 | check-follow-and-star: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - name: Checkout repository 12 | uses: actions/checkout@v3 13 | 14 | - name: Check if user is following 15 | id: check-follow 16 | uses: actions/github-script@v6 17 | with: 18 | script: | 19 | const { github, context } = require('@actions/github'); 20 | 21 | const owner = context.repo.owner; 22 | const prAuthor = context.payload.pull_request.user.login; 23 | 24 | const result = await github.rest.users.checkFollowing({ 25 | username: prAuthor, 26 | target_user: owner 27 | }); 28 | return result.data; 29 | 30 | - name: Check if user has starred the repository 31 | id: check-star 32 | uses: actions/github-script@v6 33 | with: 34 | script: | 35 | const { github, context } = require('@actions/github'); 36 | 37 | const owner = context.repo.owner; 38 | const repo = context.repo.repo; 39 | const prAuthor = context.payload.pull_request.user.login; 40 | 41 | try { 42 | const result = await github.rest.activity.getRepoSubscription({ 43 | owner: owner, 44 | repo: repo, 45 | username: prAuthor 46 | }); 47 | return result.data.subscribed; 48 | } catch (error) { 49 | return false; // User hasn't starred the repo 50 | } 51 | 52 | - name: Set check status and leave comment 53 | uses: actions/github-script@v6 54 | with: 55 | script: | 56 | const { github, context } = require('@actions/github'); 57 | 58 | const isFollowing = steps['check-follow'].outputs.result; 59 | const hasStarred = steps['check-star'].outputs.result; 60 | 61 | if (isFollowing && hasStarred) { 62 | await github.rest.checks.create({ 63 | owner: context.repo.owner, 64 | repo: context.repo.repo, 65 | name: 'Follow and Star Check', 66 | head_sha: context.payload.pull_request.head.sha, 67 | status: 'completed', 68 | conclusion: 'success', 69 | output: { 70 | title: 'Success', 71 | summary: 'User is following and has starred the repository.' 72 | } 73 | }); 74 | } else { 75 | await github.rest.checks.create({ 76 | owner: context.repo.owner, 77 | repo: context.repo.repo, 78 | name: 'Follow and Star Check', 79 | head_sha: context.payload.pull_request.head.sha, 80 | status: 'completed', 81 | conclusion: 'failure', 82 | output: { 83 | title: 'Failure', 84 | summary: 'User must follow and star the repository to proceed.' 85 | } 86 | }); 87 | 88 | await github.rest.issues.createComment({ 89 | owner: context.repo.owner, 90 | repo: context.repo.repo, 91 | issue_number: context.payload.pull_request.number, 92 | body: 'Please follow and star the repository to proceed with your pull request.' 93 | }); 94 | } 95 | -------------------------------------------------------------------------------- /.vscode/c_cpp_properties.json: -------------------------------------------------------------------------------- 1 | { 2 | "configurations": [ 3 | { 4 | "name": "windows-gcc-x86", 5 | "includePath": [ 6 | "${workspaceFolder}/**" 7 | ], 8 | "compilerPath": "C:/MinGW/bin/gcc.exe", 9 | "cStandard": "${default}", 10 | "cppStandard": "${default}", 11 | "intelliSenseMode": "windows-gcc-x86", 12 | "compilerArgs": [ 13 | "" 14 | ] 15 | } 16 | ], 17 | "version": 4 18 | } -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "type": "java", 6 | "name": "LinkedList", 7 | "request": "launch", 8 | "mainClass": "LinkedList.LinkedList", 9 | "projectName": "Hacktoberfest2023_a7cb01fd" 10 | }, 11 | { 12 | "type": "java", 13 | "name": "LinkedList", 14 | "request": "launch", 15 | "mainClass": "LinkedList", 16 | "projectName": "Hacktoberfest2023_a7cb01fd" 17 | }, 18 | { 19 | "name": "C/C++ Runner: Debug Session", 20 | "type": "cppdbg", 21 | "request": "launch", 22 | "args": [], 23 | "stopAtEntry": false, 24 | "externalConsole": true, 25 | "cwd": ".", 26 | "program": "build/Debug/outDebug", 27 | "MIMode": "gdb", 28 | "miDebuggerPath": "gdb", 29 | "setupCommands": [ 30 | { 31 | "description": "Enable pretty-printing for gdb", 32 | "text": "-enable-pretty-printing", 33 | "ignoreFailures": true 34 | } 35 | ] 36 | } 37 | ] 38 | } 39 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "C_Cpp_Runner.cCompilerPath": "gcc", 3 | "C_Cpp_Runner.cppCompilerPath": "g++", 4 | "C_Cpp_Runner.debuggerPath": "gdb", 5 | "C_Cpp_Runner.cStandard": "", 6 | "C_Cpp_Runner.cppStandard": "", 7 | "C_Cpp_Runner.msvcBatchPath": "", 8 | "C_Cpp_Runner.useMsvc": false, 9 | "C_Cpp_Runner.warnings": [ 10 | "-Wall", 11 | "-Wextra", 12 | "-Wpedantic", 13 | "-Wshadow", 14 | "-Wformat=2", 15 | "-Wcast-align", 16 | "-Wconversion", 17 | "-Wsign-conversion", 18 | "-Wnull-dereference" 19 | ], 20 | "C_Cpp_Runner.msvcWarnings": [ 21 | "/W4", 22 | "/permissive-", 23 | "/w14242", 24 | "/w14287", 25 | "/w14296", 26 | "/w14311", 27 | "/w14826", 28 | "/w44062", 29 | "/w44242", 30 | "/w14905", 31 | "/w14906", 32 | "/w14263", 33 | "/w44265", 34 | "/w14928" 35 | ], 36 | "C_Cpp_Runner.enableWarnings": true, 37 | "C_Cpp_Runner.warningsAsError": false, 38 | "C_Cpp_Runner.compilerArgs": [], 39 | "C_Cpp_Runner.linkerArgs": [], 40 | "C_Cpp_Runner.includePaths": [], 41 | "C_Cpp_Runner.includeSearch": [ 42 | "*", 43 | "**/*" 44 | ], 45 | "C_Cpp_Runner.excludeSearch": [ 46 | "**/build", 47 | "**/build/**", 48 | "**/.*", 49 | "**/.*/**", 50 | "**/.vscode", 51 | "**/.vscode/**" 52 | ], 53 | "C_Cpp_Runner.useAddressSanitizer": false, 54 | "C_Cpp_Runner.useUndefinedSanitizer": false, 55 | "C_Cpp_Runner.useLeakSanitizer": false, 56 | "C_Cpp_Runner.showCompilationTime": false, 57 | "C_Cpp_Runner.useLinkTimeOptimization": false, 58 | "C_Cpp_Runner.msvcSecureNoWarnings": false 59 | } -------------------------------------------------------------------------------- /3Sum Closest: -------------------------------------------------------------------------------- 1 | int comparator(const void *p1, const void *p2){ 2 | return (*(int*)p1 - *(int*)p2); 3 | } 4 | 5 | int threeSumClosest(int* nums, int numsSize, int target) { 6 | qsort(nums,numsSize,sizeof(int),comparator); 7 | int ans = 0; 8 | int new_diff = INT_MAX; 9 | for(int i=0; iarr[end]){ 23 | int newstart=end+1; 24 | end=end+(end-start+1)*2; 25 | start=newstart; 26 | } 27 | if(end>=arr.length)end=arr.length-1; 28 | int position=binsearch(arr, start, end, target); 29 | if(position<0)System.out.println("Element not Found"); 30 | else System.out.println("Element found at = "+position); 31 | 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /C++/Best Time to Buy and Sell Stock with Transaction Fee.cpp: -------------------------------------------------------------------------------- 1 | //Link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/description/ 2 | 3 | class Solution { 4 | public: 5 | 6 | int solve(int index, int buy, vector&prices, int fee, vector>& dp) { 7 | if(index>=prices.size()) return 0; 8 | int profit = 0; 9 | 10 | 11 | if(dp[index][buy]!=-1) return dp[index][buy]; 12 | if(buy) { 13 | int buy = -prices[index] + solve(index+1, 0, prices, fee, dp); 14 | int skip = 0 + solve(index+1, 1, prices, fee, dp); 15 | profit = max(buy, skip); 16 | } 17 | else { 18 | int sell = (prices[index] + solve(index+1, 1, prices, fee, dp)) - fee; 19 | int skip = 0 + solve(index+1, 0, prices, fee, dp); 20 | profit = max(sell, skip); 21 | } 22 | 23 | dp[index][buy] = profit; 24 | return dp[index][buy]; 25 | } 26 | 27 | int maxProfit(vector& prices, int fee) { 28 | vector>dp(prices.size(), vector(2, -1)); 29 | return solve(0, 1, prices, fee, dp); 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /C++/Book Allocation Problem.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool isPossible(vector arr, int n, int m, int mid) { 5 | int studentCount = 1; 6 | int pageSum = 0; 7 | //cout << "checking for mid "<< mid < m || arr[i] > mid ) { 17 | return false; 18 | } 19 | pageSum = arr[i]; 20 | } 21 | if(studentCount > m) { 22 | return false; 23 | } 24 | //cout << " for i " << i << " Student "<< studentCount << " pageSum " << pageSum << endl; 25 | } 26 | return true; 27 | } 28 | 29 | int allocateBooks(vector arr, int n, int m) { 30 | int s = 0; 31 | int sum = 0; 32 | 33 | for(int i = 0; i to enable input and output operations. 4 | 5 | // Create the main function, the entry point of the program. 6 | 7 | // Declare three variables (side1, side2, and side3) to store the lengths of the three sides of the triangle. 8 | 9 | // Prompt the user to input the lengths of the three sides using cout and cin for each side. 10 | 11 | // Check if all three sides are equal. If they are, it's an equilateral triangle because all sides of an equilateral triangle have the same length. We use an if statement to perform this check. 12 | 13 | // If all three sides are equal, display "It's an equilateral triangle" using cout. Otherwise, display "It's not an equilateral triangle." 14 | 15 | // Also calculating the area of the equilatereal triangle using area function 16 | 17 | // Finally, return 0 to indicate successful execution of the program. 18 | 19 | // This program calculates whether a triangle is equilateral based on user-provided side lengths. If all three sides are equal, it's an equilateral triangle; otherwise, it's not. 20 | 21 | #include 22 | using namespace std; 23 | 24 | void area(double side1){ 25 | cout<<"Area of Equilateral triangle is "<< sqrt(3)/4*side1*side1; 26 | } 27 | 28 | int main() { 29 | // Initialize variables to store the lengths of the three sides of the triangle 30 | double side1, side2, side3; 31 | // Prompt the user to input the lengths of the three sides 32 | cout << "Enter the length of side 1: "; 33 | cin >> side1; 34 | cout << "Enter the length of side 2: "; 35 | cin >> side2; 36 | cout << "Enter the length of side 3: "; 37 | cin >> side3; 38 | 39 | // Check if all three sides are equal (equilateral) 40 | if (side1 == side2 && side2 == side3) { 41 | cout << "It's an equilateral triangle." << endl; 42 | cout<<"Do you also want to know the area of the equilateral triangle:(Y/N)?"; 43 | char d; 44 | cin>>d; 45 | if(d=='Y'){ 46 | area(side1); 47 | } 48 | 49 | } else { 50 | cout << "It's not an equilateral triangle." << endl; 51 | } 52 | 53 | return 0; 54 | } 55 | 56 | -------------------------------------------------------------------------------- /C++/GCD.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // The gcd function is a recursive function uses Euclid's algorithm to calculate the GCD of two integers a and b. 5 | // The algorithm states that the GCD of two numbers is the same as the GCD of the smaller number and the remainder of the larger number divided by the smaller number. 6 | // This process is repeated until the remainder is 0, at which point the GCD is found. 7 | int gcd(int a, int b) 8 | { 9 | if (b == 0) 10 | { 11 | return a; 12 | } 13 | return gcd(b, a % b); 14 | } 15 | 16 | int main() 17 | { 18 | int num1, num2; 19 | cout << "Enter two numbers: \n"; 20 | cin >> num1 >> num2; 21 | 22 | int result = gcd(num1, num2); 23 | cout << "GCD/HCF of " << num1 << " and " << num2 << " is: " << result << endl; 24 | 25 | return 0; 26 | } 27 | 28 | // What is GCD/HCF? 29 | // GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest number that divides both of them. 30 | // For example GCD of 20 and 28 is 4 and GCD of 98 and 56 is 14. 31 | 32 | // What is Euclid's Algorithm? 33 | // Euclid's algorithm is an efficient method for computing the greatest common divisor (GCD) of two numbers, 34 | // the largest number that divides both of them without leaving a remainder. 35 | -------------------------------------------------------------------------------- /C++/GCD_or_HCF.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | // Function to calculate the GCD of two numbers using the Euclidean algorithm 6 | int findGCD(int a, int b) { 7 | // Keep looping until b becomes 0 8 | while (b != 0) { 9 | // Store the current value of b 10 | int temp = b; 11 | // Update b to be the remainder when a is divided by b 12 | b = a % b; 13 | // Assign the previous value of b to a 14 | a = temp; 15 | } 16 | // When b becomes 0, a contains the GCD 17 | return a; 18 | } 19 | 20 | int main() { 21 | int num1, num2; 22 | 23 | cout << "Enter two numbers: "; 24 | cin >> num1 >> num2; 25 | 26 | // Find and display the GCD 27 | int gcd = findGCD(num1, num2); 28 | cout << "GCD of " << num1 << " and " << num2 << " is: " << gcd << endl; 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /C++/HCF.cpp: -------------------------------------------------------------------------------- 1 | //We start by including the necessary header files, which in this case is for input and output. 2 | #include 3 | using namespace std; 4 | 5 | //We create a function named findHCF that takes two integers as input parameters, num1 and num2. This function will calculate the HCF of these two numbers. 6 | int findHCF(int num1, int num2) { 7 | // Inside 'findHCF' function we initialize a variable to store the HCF 8 | int hcf; 9 | 10 | //We use a for loop to iterate from 1 to the minimum of num1 and num2. 11 | //Inside the loop, we check if both num1 and num2 are divisible by the current value of i using the modulus operator (%). 12 | //If both numbers are divisible by i, we update the hcf variable with the current value of i. This is because, at this point, i is a common factor of both num1 and num2. 13 | for (int i = 1; i <= min(num1, num2); ++i) { 14 | // Check if both num1 and num2 are divisible by i 15 | if (num1 % i == 0 && num2 % i == 0) { 16 | // If yes, update the HCF to the current value of i 17 | hcf = i; 18 | } 19 | } 20 | 21 | // Return the HCF 22 | return hcf; 23 | } 24 | //In the main function, we input two numbers from the user using cin. 25 | //We then call the findHCF function with the input numbers and store the result in the hcf variable. 26 | //Finally, we output the HCF to the user. 27 | int main() { 28 | int num1, num2; 29 | 30 | // Input two numbers from the user 31 | cout << "Enter the first number: "; 32 | cin >> num1; 33 | cout << "Enter the second number: "; 34 | cin >> num2; 35 | 36 | // Call the findHCF function to calculate the HCF 37 | int hcf = findHCF(num1, num2); 38 | 39 | // Output the result 40 | cout << "The Highest Common Factor (HCF) of " << num1 << " and " << num2 << " is " << hcf << endl; 41 | 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /C++/Knapsack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int knapsack(int W, const vector& weights, const vector& values) { 7 | int n = weights.size(); 8 | vector> dp(n + 1, vector(W + 1, 0)); 9 | 10 | for (int i = 1; i <= n; ++i) { 11 | for (int w = 0; w <= W; ++w) { 12 | if (weights[i - 1] <= w) { 13 | dp[i][w] = max(dp[i - 1][w], dp[i - 1][w - weights[i - 1]] + values[i - 1]); 14 | } else { 15 | dp[i][w] = dp[i - 1][w]; 16 | } 17 | } 18 | } 19 | 20 | return dp[n][W]; 21 | } 22 | 23 | int main() { 24 | int W, n; 25 | cin >> W >> n; 26 | vector weights(n); 27 | vector values(n); 28 | 29 | for (int i = 0; i < n; ++i) { 30 | cin >> weights[i] >> values[i]; 31 | } 32 | 33 | int result = knapsack(W, weights, values); 34 | cout << result << endl; 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /C++/Kruskals_Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | // Define a structure to represent edges in the graph 8 | struct Edge { 9 | int from; 10 | int to; 11 | int weight; 12 | Edge(int u, int v, int w) : from(u), to(v), weight(w) {} 13 | }; 14 | 15 | // Define a custom comparison function to sort edges by weight 16 | bool compareEdges(const Edge& a, const Edge& b) { 17 | return a.weight < b.weight; 18 | } 19 | 20 | // Function to find the minimum spanning tree using Kruskal's algorithm 21 | void kruskal(vector& edges, int numVertices) { 22 | vector minimumSpanningTree; // Stores the edges of the minimum spanning tree 23 | vector parent(numVertices); // Parent array for disjoint-set data structure 24 | 25 | // Initialize each vertex as its own parent (initially disjoint sets) 26 | for (int i = 0; i < numVertices; ++i) { 27 | parent[i] = i; 28 | } 29 | 30 | // Sort edges in ascending order of weight 31 | sort(edges.begin(), edges.end(), compareEdges); 32 | 33 | for (const Edge& edge : edges) { 34 | int rootA = find(parent, edge.from); 35 | int rootB = find(parent, edge.to); 36 | 37 | // Check if adding this edge forms a cycle 38 | if (rootA != rootB) { 39 | minimumSpanningTree.push_back(edge); 40 | unionSets(parent, rootA, rootB); 41 | } 42 | } 43 | 44 | // Output the edges in the minimum spanning tree 45 | for (const Edge& edge : minimumSpanningTree) { 46 | cout << "Edge: " << edge.from << " - " << edge.to << " | Weight: " << edge.weight << endl; 47 | } 48 | } 49 | 50 | // Function to find the root of a set (used in the disjoint-set data structure) 51 | int find(vector& parent, int vertex) { 52 | if (parent[vertex] != vertex) { 53 | // Recursively find the root 54 | parent[vertex] = find(parent, parent[vertex]); 55 | } 56 | return parent[vertex]; 57 | } 58 | 59 | // Function to union two sets (used in the disjoint-set data structure) 60 | void unionSets(vector& parent, int rootA, int rootB) { 61 | parent[rootA] = rootB; 62 | } 63 | 64 | int main() { 65 | int numVertices, numEdges; // Number of vertices and edges 66 | cin >> numVertices >> numEdges; 67 | 68 | vector edges; 69 | 70 | // Read the edges and their weights 71 | for (int i = 0; i < numEdges; ++i) { 72 | int from, to, weight; // Edge from 'from' to 'to' with weight 'weight' 73 | cin >> from >> to >> weight; 74 | edges.push_back(Edge(from, to, weight)); 75 | } 76 | 77 | kruskal(edges, numVertices); 78 | 79 | return 0; 80 | } 81 | -------------------------------------------------------------------------------- /C++/Linked List/Circular LinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Node { 6 | public: 7 | int data; 8 | Node* next; 9 | 10 | //constrcutor 11 | Node(int d) { 12 | this->data = d; 13 | this->next = NULL; 14 | } 15 | 16 | ~Node() { 17 | int value = this->data; 18 | if(this->next != NULL) { 19 | delete next; 20 | next = NULL; 21 | } 22 | cout << " memory is free for node with data " << value << endl; 23 | } 24 | 25 | }; 26 | 27 | void insertNode(Node* &tail, int element, int d) { 28 | 29 | 30 | //empty list 31 | if(tail == NULL) { 32 | Node* newNode = new Node(d); 33 | tail = newNode; 34 | newNode -> next = newNode; 35 | } 36 | else{ 37 | //non-empty list 38 | //assuming that the element is present in the list 39 | 40 | Node* curr = tail; 41 | 42 | while(curr->data != element) { 43 | curr = curr -> next; 44 | } 45 | 46 | //element found -> curr is representing element wala node 47 | Node* temp = new Node(d); 48 | temp -> next = curr -> next; 49 | curr -> next = temp; 50 | 51 | } 52 | 53 | } 54 | 55 | void print(Node* tail) { 56 | 57 | Node* temp = tail; 58 | 59 | //empty list 60 | if(tail == NULL) { 61 | cout << "List is Empty "<< endl; 62 | return ; 63 | } 64 | 65 | do { 66 | cout << tail -> data << " "; 67 | tail = tail -> next; 68 | } while(tail != temp); 69 | 70 | cout << endl; 71 | } 72 | 73 | void deleteNode(Node* &tail, int value) { 74 | 75 | //empty list 76 | if(tail == NULL) { 77 | cout << " List is empty, please check again" << endl; 78 | return; 79 | } 80 | else{ 81 | //non-empty 82 | 83 | //assuming that "value" is present in the Linked List 84 | Node* prev = tail; 85 | Node* curr = prev -> next; 86 | 87 | while(curr -> data != value) { 88 | prev = curr; 89 | curr = curr -> next; 90 | } 91 | 92 | prev -> next = curr -> next; 93 | 94 | //1 Node Linked List 95 | if(curr == prev) { 96 | tail = NULL; 97 | } 98 | 99 | //>=2 Node linked list 100 | else if(tail == curr ) { 101 | tail = prev; 102 | } 103 | 104 | curr -> next = NULL; 105 | delete curr; 106 | 107 | } 108 | 109 | } 110 | 111 | bool isCircularList(Node* head) { 112 | //empty list 113 | if(head == NULL) { 114 | return true; 115 | } 116 | 117 | Node* temp = head -> next; 118 | while(temp != NULL && temp != head ) { 119 | temp = temp -> next; 120 | } 121 | 122 | if(temp == head ) { 123 | return true; 124 | } 125 | 126 | return false; 127 | 128 | } 129 | 130 | bool detectLoop(Node* head) { 131 | 132 | if(head == NULL) 133 | return false; 134 | 135 | map visited; 136 | 137 | Node* temp = head; 138 | 139 | while(temp !=NULL) { 140 | 141 | //cycle is present 142 | if(visited[temp] == true) { 143 | return true; 144 | } 145 | 146 | visited[temp] = true; 147 | temp = temp -> next; 148 | 149 | } 150 | return false; 151 | 152 | } 153 | 154 | 155 | int main() { 156 | 157 | Node* tail = NULL; 158 | 159 | // insertNode(tail, 5, 3); 160 | //print(tail); 161 | 162 | // insertNode(tail, 3, 5); 163 | // print(tail); 164 | 165 | /* 166 | insertNode(tail, 5, 7); 167 | print(tail); 168 | 169 | insertNode(tail, 7, 9); 170 | print(tail); 171 | 172 | insertNode(tail, 5, 6); 173 | print(tail); 174 | 175 | insertNode(tail, 9, 10); 176 | print(tail); 177 | 178 | insertNode(tail, 3, 4); 179 | print(tail); 180 | 181 | 182 | deleteNode(tail, 5); 183 | print(tail); 184 | */ 185 | 186 | if(isCircularList(tail)) { 187 | cout << " Linked List is Circular in nature" << endl; 188 | } 189 | else{ 190 | cout << "Linked List is not Circular " << endl; 191 | } 192 | 193 | return 0; 194 | } -------------------------------------------------------------------------------- /C++/Linked List/Doubly LinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node { 5 | public: 6 | int data; 7 | Node* prev; 8 | Node* next; 9 | 10 | //constructor 11 | Node(int d ) { 12 | this-> data = d; 13 | this->prev = NULL; 14 | this->next = NULL; 15 | } 16 | 17 | ~Node() { 18 | int val = this -> data; 19 | if(next != NULL) { 20 | delete next; 21 | next = NULL; 22 | } 23 | cout << "memory free for node with data "<< val << endl; 24 | } 25 | }; 26 | 27 | //traversing a linked list 28 | void print(Node* head) { 29 | Node* temp = head ; 30 | 31 | while(temp != NULL) { 32 | cout << temp -> data << " "; 33 | temp = temp -> next; 34 | } 35 | cout << endl; 36 | } 37 | 38 | //gives length of Linked List 39 | int getLength(Node* head) { 40 | int len = 0; 41 | Node* temp = head ; 42 | 43 | while(temp != NULL) { 44 | len++; 45 | temp = temp -> next; 46 | } 47 | 48 | return len; 49 | } 50 | void insertAtHead(Node* &tail, Node* &head, int d) { 51 | 52 | //empty list 53 | if(head == NULL) { 54 | Node* temp = new Node(d); 55 | head = temp; 56 | tail = temp; 57 | } 58 | else{ 59 | Node* temp = new Node(d); 60 | temp -> next = head; 61 | head -> prev = temp; 62 | head = temp; 63 | } 64 | 65 | } 66 | 67 | 68 | void insertAtTail(Node* &tail,Node* &head, int d) { 69 | if(tail == NULL) { 70 | Node* temp = new Node(d); 71 | tail = temp; 72 | head = temp; 73 | } 74 | else{ 75 | Node* temp = new Node(d); 76 | tail -> next = temp; 77 | temp -> prev = tail; 78 | tail = temp; 79 | } 80 | 81 | } 82 | 83 | void insertAtPosition(Node* & tail, Node* &head, int position, int d) { 84 | 85 | //insert at Start 86 | if(position == 1) { 87 | insertAtHead(tail,head, d); 88 | return; 89 | } 90 | 91 | Node* temp = head; 92 | int cnt = 1; 93 | 94 | while(cnt < position-1) { 95 | temp = temp->next; 96 | cnt++; 97 | } 98 | 99 | //inserting at Last Position 100 | if(temp -> next == NULL) { 101 | insertAtTail(tail,head,d); 102 | return ; 103 | } 104 | 105 | //creating a node for d 106 | Node* nodeToInsert = new Node(d); 107 | 108 | nodeToInsert ->next = temp -> next; 109 | temp -> next -> prev = nodeToInsert; 110 | temp -> next = nodeToInsert; 111 | nodeToInsert -> prev = temp; 112 | } 113 | 114 | void deleteNode(int position, Node* & head) { 115 | 116 | //deleting first or start node 117 | if(position == 1) { 118 | Node* temp = head; 119 | temp -> next -> prev = NULL; 120 | head = temp ->next; 121 | temp -> next = NULL; 122 | delete temp; 123 | } 124 | else 125 | { 126 | //deleting any middle node or last node 127 | Node* curr = head; 128 | Node* prev = NULL; 129 | 130 | int cnt = 1; 131 | while(cnt < position) { 132 | prev = curr; 133 | curr = curr -> next; 134 | cnt++; 135 | } 136 | 137 | curr -> prev = NULL; 138 | prev -> next = curr -> next; 139 | curr -> next = NULL; 140 | 141 | delete curr; 142 | 143 | } 144 | } 145 | 146 | 147 | 148 | int main() { 149 | 150 | 151 | Node* head = NULL; 152 | Node* tail = NULL; 153 | 154 | print(head); 155 | //cout << getLength(head) << endl; 156 | 157 | insertAtHead(tail,head, 11); 158 | print(head); 159 | cout << "head " << head -> data << endl; 160 | cout << "tail " << tail -> data << endl; 161 | 162 | insertAtHead(tail,head, 13); 163 | print(head); 164 | cout << "head " << head -> data << endl; 165 | cout << "tail " << tail -> data << endl; 166 | 167 | insertAtHead(tail,head, 8); 168 | print(head); 169 | cout << "head " << head -> data << endl; 170 | cout << "tail " << tail -> data << endl; 171 | 172 | insertAtTail(tail,head, 25); 173 | print(head); 174 | cout << "head " << head -> data << endl; 175 | cout << "tail " << tail -> data << endl; 176 | 177 | insertAtPosition(tail, head, 2, 100); 178 | print(head); 179 | cout << "head " << head -> data << endl; 180 | cout << "tail " << tail -> data << endl; 181 | 182 | insertAtPosition(tail, head, 1, 101); 183 | print(head); 184 | 185 | cout << "head " << head -> data << endl; 186 | cout << "tail " << tail -> data << endl; 187 | 188 | insertAtPosition(tail, head, 7, 102); 189 | print(head); 190 | cout << "head " << head -> data << endl; 191 | cout << "tail " << tail -> data << endl; 192 | 193 | deleteNode(7, head); 194 | print(head); 195 | cout << "head " << head -> data << endl; 196 | cout << "tail " << tail -> data << endl; 197 | 198 | 199 | 200 | 201 | 202 | return 0; 203 | } -------------------------------------------------------------------------------- /C++/Linked List/MergeTwoSortedLists.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Node structure 5 | struct Node { 6 | int data; 7 | Node* next; 8 | Node(int val) : data(val), next(nullptr) {} 9 | }; 10 | 11 | // Function to insert a new node at the end of the linked list 12 | void insertAtEnd(Node*& head, int data) { 13 | Node* newNode = new Node(data); 14 | if (!head) { 15 | head = newNode; 16 | } else { 17 | Node* temp = head; 18 | while (temp->next) { 19 | temp = temp->next; 20 | } 21 | temp->next = newNode; 22 | } 23 | } 24 | 25 | // Function to merge two sorted linked lists 26 | Node* mergeSortedLists(Node* list1, Node* list2) { 27 | if (!list1) return list2; 28 | if (!list2) return list1; 29 | 30 | Node* mergedHead = nullptr; 31 | if (list1->data <= list2->data) { 32 | mergedHead = list1; 33 | list1 = list1->next; 34 | } else { 35 | mergedHead = list2; 36 | list2 = list2->next; 37 | } 38 | 39 | Node* mergedTail = mergedHead; 40 | while (list1 && list2) { 41 | if (list1->data <= list2->data) { 42 | mergedTail->next = list1; 43 | list1 = list1->next; 44 | } else { 45 | mergedTail->next = list2; 46 | list2 = list2->next; 47 | } 48 | mergedTail = mergedTail->next; 49 | } 50 | 51 | // Attach remaining nodes 52 | mergedTail->next = (list1) ? list1 : list2; 53 | 54 | return mergedHead; 55 | } 56 | 57 | // Function to print the linked list 58 | void printList(Node* head) { 59 | while (head) { 60 | cout << head->data << " "; 61 | head = head->next; 62 | } 63 | cout << endl; 64 | } 65 | 66 | int main() { 67 | Node* list1 = nullptr; 68 | Node* list2 = nullptr; 69 | 70 | // Insert elements into list1 71 | insertAtEnd(list1, 1); 72 | insertAtEnd(list1, 3); 73 | insertAtEnd(list1, 5); 74 | 75 | // Insert elements into list2 76 | insertAtEnd(list2, 2); 77 | insertAtEnd(list2, 4); 78 | insertAtEnd(list2, 6); 79 | 80 | cout << "List 1: "; 81 | printList(list1); 82 | cout << "List 2: "; 83 | printList(list2); 84 | 85 | // Merge the lists 86 | Node* mergedList = mergeSortedLists(list1, list2); 87 | cout << "Merged List: "; 88 | printList(mergedList); 89 | 90 | return 0; 91 | } 92 | -------------------------------------------------------------------------------- /C++/Linked List/singly LinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Node { 6 | 7 | public: 8 | int data; 9 | Node* next; 10 | 11 | //constructor 12 | Node(int data) { 13 | this -> data = data; 14 | this -> next = NULL; 15 | } 16 | 17 | //destructor 18 | ~Node() { 19 | int value = this -> data; 20 | //memory free 21 | if(this->next != NULL) { 22 | delete next; 23 | this->next = NULL; 24 | } 25 | cout << " memory is free for node with data " << value << endl; 26 | } 27 | 28 | }; 29 | 30 | void insertAtHead(Node* &head, int d) { 31 | 32 | // new node create 33 | Node* temp = new Node(d); 34 | temp -> next = head; 35 | head = temp; 36 | } 37 | 38 | void insertAtTail(Node* &tail, int d) { 39 | // new node create 40 | Node* temp = new Node(d); 41 | tail -> next = temp; 42 | tail = temp; 43 | } 44 | 45 | void print(Node* &head) { 46 | 47 | if(head == NULL) { 48 | cout << "List is empty "<< endl; 49 | return ; 50 | } 51 | Node* temp = head; 52 | 53 | while(temp != NULL ) { 54 | cout << temp -> data << " "; 55 | temp = temp -> next; 56 | } 57 | cout << endl; 58 | } 59 | 60 | void insertAtPosition(Node* &tail, Node* & head, int position, int d) { 61 | 62 | 63 | //insert at Start 64 | if(position == 1) { 65 | insertAtHead(head, d); 66 | return; 67 | } 68 | 69 | Node* temp = head; 70 | int cnt = 1; 71 | 72 | while(cnt < position-1) { 73 | temp = temp->next; 74 | cnt++; 75 | } 76 | 77 | //inserting at Last Position 78 | if(temp -> next == NULL) { 79 | insertAtTail(tail,d); 80 | return ; 81 | } 82 | 83 | //creating a node for d 84 | Node* nodeToInsert = new Node(d); 85 | 86 | nodeToInsert -> next = temp -> next; 87 | 88 | temp -> next = nodeToInsert; 89 | } 90 | 91 | void deleteNode(int position, Node* & head) { 92 | 93 | //deleting first or start node 94 | if(position == 1) { 95 | Node* temp = head; 96 | head = head -> next; 97 | //memory free start ndoe 98 | temp -> next = NULL; 99 | delete temp; 100 | } 101 | else 102 | { 103 | //deleting any middle node or last node 104 | Node* curr = head; 105 | Node* prev = NULL; 106 | 107 | int cnt = 1; 108 | while(cnt < position) { 109 | prev = curr; 110 | curr = curr -> next; 111 | cnt++; 112 | } 113 | 114 | prev -> next = curr -> next; 115 | curr -> next = NULL; 116 | delete curr; 117 | 118 | } 119 | } 120 | 121 | bool isCircularList(Node* head) { 122 | //empty list 123 | if(head == NULL) { 124 | return true; 125 | } 126 | 127 | Node* temp = head -> next; 128 | while(temp != NULL && temp != head ) { 129 | temp = temp -> next; 130 | } 131 | 132 | if(temp == head ) { 133 | return true; 134 | } 135 | 136 | return false; 137 | } 138 | 139 | 140 | bool detectLoop(Node* head) { 141 | 142 | if(head == NULL) 143 | return false; 144 | 145 | map visited; 146 | 147 | Node* temp = head; 148 | 149 | while(temp !=NULL) { 150 | 151 | //cycle is present 152 | if(visited[temp] == true) { 153 | cout << "Present on element " << temp->data << endl; 154 | return true; 155 | } 156 | 157 | visited[temp] = true; 158 | temp = temp -> next; 159 | 160 | } 161 | return false; 162 | 163 | } 164 | 165 | Node* floydDetectLoop(Node* head) { 166 | 167 | if(head == NULL) 168 | return NULL; 169 | 170 | Node* slow = head; 171 | Node* fast = head; 172 | 173 | while(slow != NULL && fast !=NULL) { 174 | 175 | fast = fast -> next; 176 | if(fast != NULL) { 177 | fast = fast -> next; 178 | } 179 | 180 | slow = slow -> next; 181 | 182 | if(slow == fast) { 183 | cout << "present at " << slow -> data << endl; 184 | return slow; 185 | } 186 | } 187 | 188 | return NULL; 189 | 190 | } 191 | 192 | Node* getStartingNode(Node* head) { 193 | 194 | if(head == NULL) 195 | return NULL; 196 | 197 | Node* intersection = floydDetectLoop(head); 198 | Node* slow = head; 199 | 200 | while(slow != intersection) { 201 | slow = slow -> next; 202 | intersection = intersection -> next; 203 | } 204 | 205 | return slow; 206 | 207 | } 208 | 209 | void removeLoop(Node* head) { 210 | 211 | if( head == NULL) 212 | return; 213 | 214 | Node* startOfLoop = getStartingNode(head); 215 | Node* temp = startOfLoop; 216 | 217 | while(temp -> next != startOfLoop) { 218 | temp = temp -> next; 219 | } 220 | 221 | temp -> next = NULL; 222 | 223 | } 224 | 225 | 226 | int main() { 227 | 228 | //created a new node 229 | Node* node1 = new Node(10); 230 | //cout << node1 -> data << endl; 231 | // cout << node1 -> next << endl; 232 | 233 | //head pointed to node1 234 | Node* head = node1; 235 | Node* tail = node1; 236 | //print(head); 237 | 238 | insertAtTail(tail, 12); 239 | 240 | //print(head); 241 | 242 | insertAtTail(tail, 15); 243 | //print(head); 244 | 245 | insertAtPosition(tail,head, 4, 22); 246 | //print(head); 247 | 248 | //cout << "head " << head -> data << endl; 249 | //cout << "tail " << tail -> data << endl; 250 | 251 | //deleteNode(4, head); 252 | 253 | 254 | tail -> next = head ->next; 255 | 256 | cout << "head " << head -> data << endl; 257 | cout << "tail " << tail -> data << endl; 258 | //print(head); 259 | 260 | if(floydDetectLoop(head) != NULL) { 261 | cout << "Cycle is present " << endl; 262 | } 263 | else 264 | { 265 | cout << "no cycle" << endl; 266 | } 267 | 268 | Node* loop = getStartingNode(head); 269 | 270 | cout << "loop starts at " << loop -> data << endl; 271 | 272 | removeLoop(head); 273 | print(head); 274 | 275 | /* 276 | print(head); 277 | 278 | if(isCircularList(head)) { 279 | cout << " Linked List is Circular in nature" << endl; 280 | } 281 | else{ 282 | cout << "Linked List is not Circular " << endl; 283 | } 284 | */ 285 | 286 | 287 | return 0; 288 | } -------------------------------------------------------------------------------- /C++/Longest_Common_Subsequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int lcs(string text1, string text2) { 7 | int m = text1.length(); 8 | int n = text2.length(); 9 | 10 | vector> dp(m + 1, vector(n + 1, 0)); 11 | 12 | for (int i = 1; i <= m; i++) { 13 | for (int j = 1; j <= n; j++) { 14 | if (text1[i - 1] == text2[j - 1]) { 15 | dp[i][j] = dp[i - 1][j - 1] + 1; 16 | } else { 17 | dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); 18 | } 19 | } 20 | } 21 | 22 | return dp[m][n]; 23 | } 24 | 25 | int main() { 26 | string text1 = "abcde"; 27 | string text2 = "ace"; 28 | 29 | int result = lcs(text1, text2); 30 | cout << "Length of Longest Common Subsequence: " << result << endl; 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /C++/Matrix multiplication.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // mat1[R1][C1] and mat2[R2][C2] 5 | #define R1 2 // number of rows in Matrix-1 6 | #define C1 2 // number of columns in Matrix-1 7 | #define R2 2 // number of rows in Matrix-2 8 | #define C2 2 // number of columns in Matrix-2 9 | 10 | void mulMat(int mat1[][C1], int mat2[][C2]) 11 | { 12 | int rslt[R1][C2]; 13 | 14 | cout << "Multiplication of given two matrices is:\n"; 15 | 16 | for (int i = 0; i < R1; i++) { 17 | for (int j = 0; j < C2; j++) { 18 | rslt[i][j] = 0; 19 | 20 | for (int k = 0; k < R2; k++) { 21 | rslt[i][j] += mat1[i][k] * mat2[k][j]; 22 | } 23 | cout << rslt[i][j] << "\t"; 24 | } 25 | cout << endl; 26 | } 27 | } 28 | 29 | // Driver code 30 | int main() 31 | { 32 | int mat1[R1][C1] = { { 1, 3 }, 33 | { 2, 4 } }; 34 | 35 | int mat2[R2][C2] = { { 1, 2 }, 36 | { 3, 4 } }; 37 | 38 | if (C1 != R2) { 39 | cout << "The number of columns in Matrix-1 must " 40 | "be equal to the number of rows in " 41 | "Matrix-2" 42 | << endl; 43 | cout << "Please update MACROs according to your " 44 | "array dimension in #define section" 45 | << endl; 46 | 47 | exit(EXIT_FAILURE); 48 | } 49 | // Function call 50 | mulMat(mat1, mat2); 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /C++/N _times_names.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | void func(int i, int n){ 6 | 7 | // Base Condition. 8 | if(i>n) return; 9 | cout<<"Raj"< 2 | using namespace std; 3 | 4 | class Solution 5 | { 6 | public: 7 | //Function to find sum of weights of edges of the Minimum Spanning Tree. 8 | int spanningTree(int V, vector> adj[]) 9 | { 10 | priority_queue, 11 | vector >, greater>> pq; 12 | 13 | vector vis(V, 0); 14 | // {wt, node} 15 | pq.push({0, 0}); 16 | int sum = 0; 17 | while (!pq.empty()) { 18 | auto it = pq.top(); 19 | pq.pop(); 20 | int node = it.second; 21 | int wt = it.first; 22 | 23 | if (vis[node] == 1) continue; 24 | // add it to the mst 25 | vis[node] = 1; 26 | sum += wt; 27 | for (auto it : adj[node]) { 28 | int adjNode = it[0]; 29 | int edW = it[1]; 30 | if (!vis[adjNode]) { 31 | pq.push({edW, adjNode}); 32 | } 33 | } 34 | } 35 | return sum; 36 | } 37 | }; 38 | 39 | 40 | int main() { 41 | 42 | int V = 5; 43 | vector> edges = {{0, 1, 2}, {0, 2, 1}, {1, 2, 1}, {2, 3, 2}, {3, 4, 1}, {4, 2, 2}}; 44 | vector> adj[V]; 45 | for (auto it : edges) { 46 | vector tmp(2); 47 | tmp[0] = it[1]; 48 | tmp[1] = it[2]; 49 | adj[it[0]].push_back(tmp); 50 | 51 | tmp[0] = it[0]; 52 | tmp[1] = it[2]; 53 | adj[it[1]].push_back(tmp); 54 | } 55 | 56 | Solution obj; 57 | int sum = obj.spanningTree(V, adj); 58 | cout << "The sum of all the edge weights: " << sum << endl; 59 | 60 | return 0; 61 | } 62 | -------------------------------------------------------------------------------- /C++/Prims_Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | // Define a structure to represent edges in the graph 9 | struct Edge { 10 | int to; 11 | int weight; 12 | Edge(int t, int w) : to(t), weight(w) {} 13 | }; 14 | 15 | // Define a custom comparison function for the priority queue 16 | // to select the edge with the minimum weight 17 | struct CompareEdges { 18 | bool operator()(const Edge& a, const Edge& b) { 19 | return a.weight > b.weight; 20 | } 21 | }; 22 | 23 | // Function to find the minimum spanning tree using Prim's algorithm 24 | void prim(vector>& graph) { 25 | int n = graph.size(); // Number of vertices 26 | vector visited(n, false); // Track visited vertices 27 | priority_queue, CompareEdges> pq; // Priority queue for edges 28 | int totalWeight = 0; // Total weight of the minimum spanning tree 29 | 30 | // Start from the first vertex (you can choose any starting vertex) 31 | pq.push(Edge(0, 0)); 32 | 33 | while (!pq.empty()) { 34 | // Get the edge with the minimum weight 35 | Edge current = pq.top(); 36 | pq.pop(); 37 | 38 | int vertex = current.to; 39 | int weight = current.weight; 40 | 41 | // If the vertex has already been visited, skip it 42 | if (visited[vertex]) { 43 | continue; 44 | } 45 | 46 | // Mark the vertex as visited 47 | visited[vertex] = true; 48 | totalWeight += weight; 49 | 50 | // Output the edge in the minimum spanning tree 51 | cout << "Add edge: " << vertex << " to " << current.weight << endl; 52 | 53 | // Explore adjacent vertices and add their edges to the priority queue 54 | for (const Edge& neighbor : graph[vertex]) { 55 | if (!visited[neighbor.to]) { 56 | pq.push(neighbor); 57 | } 58 | } 59 | } 60 | 61 | cout << "Total weight of minimum spanning tree: " << totalWeight << endl; 62 | } 63 | 64 | int main() { 65 | int n, m; // Number of vertices and edges 66 | cin >> n >> m; 67 | 68 | vector> graph(n); 69 | 70 | // Read the edges and their weights 71 | for (int i = 0; i < m; ++i) { 72 | int u, v, w; // Edge from u to v with weight w 73 | cin >> u >> v >> w; 74 | graph[u].emplace_back(v, w); 75 | graph[v].emplace_back(u, w); // For undirected graph 76 | } 77 | 78 | prim(graph); 79 | 80 | return 0; 81 | } 82 | -------------------------------------------------------------------------------- /C++/Prims_Kruskal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | // Structure to represent an edge in the graph 9 | struct Edge { 10 | int u, v, weight; 11 | Edge(int _u, int _v, int _weight) : u(_u), v(_v), weight(_weight) {} 12 | }; 13 | 14 | // Graph class using adjacency list representation 15 | class Graph { 16 | public: 17 | int V; // Number of vertices 18 | vector>> adj; // Adjacency list (vertex, weight) 19 | 20 | Graph(int vertices) : V(vertices) { 21 | adj.resize(V); 22 | } 23 | 24 | // Add an edge to the graph 25 | void addEdge(int u, int v, int weight) { 26 | adj[u].emplace_back(v, weight); 27 | adj[v].emplace_back(u, weight); // For undirected graph 28 | } 29 | }; 30 | 31 | // Function to implement Prim's algorithm for finding MST 32 | void primMST(Graph& graph) { 33 | vector inMST(graph.V, false); 34 | vector key(graph.V, INT_MAX); 35 | vector parent(graph.V, -1); 36 | 37 | priority_queue, vector>, greater>> pq; 38 | 39 | int src = 0; // Start from the first vertex 40 | pq.push({0, src}); 41 | key[src] = 0; 42 | 43 | while (!pq.empty()) { 44 | int u = pq.top().second; 45 | pq.pop(); 46 | inMST[u] = true; 47 | 48 | for (auto& neighbor : graph.adj[u]) { 49 | int v = neighbor.first; 50 | int weight = neighbor.second; 51 | if (!inMST[v] && weight < key[v]) { 52 | key[v] = weight; 53 | parent[v] = u; 54 | pq.push({key[v], v}); 55 | } 56 | } 57 | } 58 | 59 | // Print the MST 60 | cout << "Edges in MST (Prim's Algorithm):\n"; 61 | for (int i = 1; i < graph.V; ++i) { 62 | cout << "Edge: " << parent[i] << " - " << i << " Weight: " << key[i] << "\n"; 63 | } 64 | } 65 | 66 | // Function to implement Kruskal's algorithm for finding MST 67 | void kruskalMST(Graph& graph) { 68 | int V = graph.V; 69 | vector edges; 70 | 71 | // Create a list of edges 72 | for (int u = 0; u < V; ++u) { 73 | for (auto& neighbor : graph.adj[u]) { 74 | int v = neighbor.first; 75 | int weight = neighbor.second; 76 | edges.emplace_back(u, v, weight); 77 | } 78 | } 79 | 80 | // Sort edges in ascending order by weight 81 | sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b) { 82 | return a.weight < b.weight; 83 | }); 84 | 85 | vector parent(V, -1); 86 | vector MST; 87 | 88 | for (const Edge& edge : edges) { 89 | int u = edge.u; 90 | int v = edge.v; 91 | int weight = edge.weight; 92 | 93 | int parent_u = u; 94 | int parent_v = v; 95 | 96 | while (parent[parent_u] != -1) { 97 | parent_u = parent[parent_u]; 98 | } 99 | 100 | while (parent[parent_v] != -1) { 101 | parent_v = parent[parent_v]; 102 | } 103 | 104 | if (parent_u != parent_v) { 105 | MST.push_back(edge); 106 | parent[parent_u] = parent_v; 107 | } 108 | } 109 | 110 | // Print the MST 111 | cout << "Edges in MST (Kruskal's Algorithm):\n"; 112 | for (const Edge& edge : MST) { 113 | cout << "Edge: " << edge.u << " - " << edge.v << " Weight: " << edge.weight << "\n"; 114 | } 115 | } 116 | 117 | int main() { 118 | int V, E; // Number of vertices and edges 119 | cout << "Enter the number of vertices and edges: "; 120 | cin >> V >> E; 121 | 122 | Graph graph(V); 123 | 124 | cout << "Enter the edges (u, v, weight):\n"; 125 | for (int i = 0; i < E; ++i) { 126 | int u, v, weight; 127 | cin >> u >> v >> weight; 128 | graph.addEdge(u, v, weight); 129 | } 130 | 131 | primMST(graph); 132 | kruskalMST(graph); 133 | 134 | return 0; 135 | } 136 | -------------------------------------------------------------------------------- /C++/SelectionSort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for implementation of 2 | // selection sort 3 | #include 4 | using namespace std; 5 | 6 | // Function for Selection sort 7 | void selectionSort(int arr[], int n) 8 | { 9 | int i, j, min_idx; 10 | 11 | // One by one move boundary of 12 | // unsorted subarray 13 | for (i = 0; i < n - 1; i++) 14 | { 15 | 16 | // Find the minimum element in 17 | // unsorted array 18 | min_idx = i; 19 | for (j = i + 1; j < n; j++) 20 | { 21 | if (arr[j] < arr[min_idx]) 22 | min_idx = j; 23 | } 24 | 25 | // Swap the found minimum element 26 | // with the first element 27 | if (min_idx != i) 28 | swap(arr[min_idx], arr[i]); 29 | } 30 | } 31 | 32 | // Function to print an array 33 | void printArray(int arr[], int size) 34 | { 35 | int i; 36 | for (i = 0; i < size; i++) 37 | { 38 | cout << arr[i] << " "; 39 | cout << endl; 40 | } 41 | } 42 | 43 | // Driver program 44 | int main() 45 | { 46 | int arr[] = {64, 25, 12, 22, 11}; 47 | int n = sizeof(arr) / sizeof(arr[0]); 48 | 49 | // Function Call 50 | selectionSort(arr, n); 51 | cout << "Sorted array: \n"; 52 | printArray(arr, n); 53 | return 0; 54 | } 55 | 56 | // This is code is contributed by Rohit. 57 | -------------------------------------------------------------------------------- /C++/Stack.cpp/Area of largest rectangle in Histogram.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | class Solution { 5 | public: 6 | vector < int > nextGreaterElements(vector < int > & nums) { 7 | int n = nums.size(); 8 | vector < int > nge(n, -1); 9 | stack < int > st; 10 | for (int i = 2 * n - 1; i >= 0; i--) { 11 | while (!st.empty() && st.top() <= nums[i % n]) { 12 | st.pop(); 13 | } 14 | 15 | if (i < n) { 16 | if (!st.empty()) nge[i] = st.top(); 17 | } 18 | st.push(nums[i % n]); 19 | } 20 | return nge; 21 | } 22 | }; 23 | int main() { 24 | Solution obj; 25 | vector < int > v {5,7,1,2,6,0}; 26 | vector < int > res = obj.nextGreaterElements(v); 27 | cout << "The next greater elements are" << endl; 28 | for (int i = 0; i < res.size(); i++) { 29 | cout << res[i] << " "; 30 | } 31 | } -------------------------------------------------------------------------------- /C++/Stack.cpp/AsteroidCollision.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector asteroidCollision(vector& asteroids) { 4 | stack st; 5 | 6 | for (int asteroid : asteroids) { 7 | int flag = 1; 8 | while (!st.empty() && (st.top() > 0 && asteroid < 0)) { 9 | // If the top asteroid in the stack is smaller, then it will explode. 10 | // Hence pop it from the stack, also continue with the next asteroid in the stack. 11 | if (abs(st.top()) < abs(asteroid)) { 12 | st.pop(); 13 | continue; 14 | } 15 | // If both asteroids are the same size, then both asteroids will explode. 16 | // Pop the asteroid from the stack; also, we won't push the current asteroid to the stack. 17 | else if (abs(st.top()) == abs(asteroid)) { 18 | st.pop(); 19 | } 20 | 21 | // If we reach here, the current asteroid will be destroyed 22 | // Hence, we should not add it to the stack 23 | flag = 0; 24 | break; 25 | } 26 | 27 | if (flag) { 28 | st.push(asteroid); 29 | } 30 | } 31 | 32 | // Add the asteroids from the stack to the vector in the reverse order. 33 | vector remainingAsteroids (st.size()); 34 | for (int i = remainingAsteroids.size() - 1; i >= 0; i--){ 35 | remainingAsteroids[i] = st.top(); 36 | st.pop(); 37 | } 38 | 39 | return remainingAsteroids; 40 | } 41 | }; -------------------------------------------------------------------------------- /C++/Stack.cpp/CelebrityProblem.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find celebrity 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | // Max # of persons in the party 7 | #define N 8 8 | 9 | // Person with 2 is celebrity 10 | bool MATRIX[N][N] = { { 0, 0, 1, 0 }, 11 | { 0, 0, 1, 0 }, 12 | { 0, 0, 0, 0 }, 13 | { 0, 0, 1, 0 } }; 14 | 15 | bool knows(int a, int b) { return MATRIX[a][b]; } 16 | 17 | // Returns -1 if celebrity 18 | // is not present. If present, 19 | // returns id (value from 0 to n-1). 20 | int findCelebrity(int n) 21 | { 22 | 23 | stack s;- 24 | 25 | // Celebrity 26 | int C; 27 | 28 | // Push everybody to stack 29 | for (int i = 0; i < n; i++) 30 | s.push(i); 31 | 32 | // Extract top 2 33 | 34 | // Find a potential celebrity 35 | while (s.size() > 1) { 36 | int A = s.top(); 37 | s.pop(); 38 | int B = s.top(); 39 | s.pop(); 40 | if (knows(A, B)) { 41 | s.push(B); 42 | } 43 | else { 44 | s.push(A); 45 | } 46 | } 47 | 48 | // Potential candidate? 49 | C = s.top(); 50 | s.pop(); 51 | 52 | // Check if C is actually 53 | // a celebrity or not 54 | for (int i = 0; i < n; i++) { 55 | // If any person doesn't 56 | // know 'C' or 'C' doesn't 57 | // know any person, return -1 58 | if ((i != C) && (knows(C, i) || !knows(i, C))) 59 | return -1; 60 | } 61 | 62 | return C; 63 | } 64 | 65 | // Driver code 66 | int main() 67 | { 68 | int n = 4; 69 | int id = findCelebrity(n); 70 | id == -1 ? cout << "No celebrity" 71 | : cout << "Celebrity ID " << id; 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /C++/Stack.cpp/Nearest_Left_Right.cpp: -------------------------------------------------------------------------------- 1 | // program to find the difference between left and right smaller element of every element in array 2 | #include 3 | using namespace std; 4 | 5 | // Function to fill left smaller element for every element of arr[0..n-1]. These values are filled in SE[0..n-1] 6 | void leftSmaller(int arr[], int n, int SE[]) 7 | { 8 | // Create an empty stack 9 | stackS; 10 | 11 | // Traverse all array elements compute nearest smaller elements of every element 12 | for (int i=0; i= arr[i]) 16 | S.pop(); 17 | 18 | // Store the smaller element of current element 19 | if (!S.empty()) 20 | SE[i] = S.top(); 21 | 22 | // If all elements in S were greater than arr[i] 23 | else 24 | SE[i] = 0; 25 | 26 | // Push this element 27 | S.push(arr[i]); 28 | } 29 | } 30 | 31 | // Function returns maximum difference b/w Left & right smaller element 32 | int findMaxDiff(int arr[], int n) 33 | { 34 | int LS[n]; // To store left smaller elements 35 | 36 | // find left smaller element of every element 37 | leftSmaller(arr, n, LS); 38 | 39 | // find right smaller element of every element first reverse the array and do the same process 40 | int RRS[n]; // To store right smaller elements in 41 | // reverse array 42 | reverse(arr, arr + n); 43 | leftSmaller(arr, n, RRS); 44 | 45 | // find maximum absolute difference b/w LS & RRS In the reversed array right smaller for arr[i] is stored at RRS[n-i-1] 46 | int result = -1; 47 | for (int i=0 ; i< n ; i++) 48 | result = max(result, abs(LS[i] - RRS[n-1-i])); 49 | 50 | // return maximum difference b/w LS & RRS 51 | return result; 52 | } 53 | 54 | // Driver program 55 | int main() 56 | { 57 | int arr[] = {2, 4, 8, 7, 7, 9, 3}; 58 | int n = sizeof(arr)/sizeof(arr[0]); 59 | cout << "Maximum diff : " 60 | << findMaxDiff(arr, n) << endl; 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /C++/Stack.cpp/NextGreaterElement.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | vector < int > nextGreaterElements(vector < int > & nums) { 8 | int n = nums.size(); 9 | vector < int > nge(n, -1); // Initialize a vector to store the next greater elements, initially set to -1 10 | stack < int > st; // Initialize a stack to store indices of elements in 'nums' 11 | 12 | // Traverse the 'nums' array in reverse order (circularly) 13 | for (int i = 2 * n - 1; i >= 0; i--) { 14 | while (!st.empty() && st.top() <= nums[i % n]) { 15 | st.pop(); // Pop elements from the stack if they are smaller than or equal to the current element 16 | } 17 | 18 | if (i < n) { 19 | if (!st.empty()) { 20 | nge[i] = st.top(); // If there is a greater element in the stack, update nge[i] with its value 21 | } 22 | } 23 | st.push(nums[i % n]); // Push the current element's value into the stack 24 | } 25 | return nge; // Return the vector containing the next greater elements 26 | } 27 | }; 28 | 29 | int main() { 30 | Solution obj; 31 | vector < int > v {5,7,1,2,6,0}; 32 | vector < int > res = obj.nextGreaterElements(v); 33 | cout << "The next greater elements are" << endl; 34 | for (int i = 0; i < res.size(); i++) { 35 | cout << res[i] << " "; // Print the next greater elements 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /C++/StringInterviewQuetions/Strings.md: -------------------------------------------------------------------------------- 1 | # STL and Strings in C++ 2 | 3 | ## Introduction 4 | The Standard Template Library (STL) in C++ provides various useful algorithms and containers to manage data. When working with strings, STL offers a powerful set of functions, containers, and algorithms that allow for efficient manipulation of text. 5 | 6 | In this guide, we will discuss how to use STL features to work with `std::string` in C++, focusing on common operations such as iteration, search, modification, and transformation. 7 | 8 | --- 9 | 10 | ## Table of Contents 11 | 1. [What is `std::string`?](#what-is-stdstring) 12 | 2. [Basic Operations on Strings](#basic-operations-on-strings) 13 | 3. [Iterating Over Strings](#iterating-over-strings) 14 | 4. [String Modifications](#string-modifications) 15 | 5. [Search Operations](#search-operations) 16 | 6. [Common STL Algorithms with Strings](#common-stl-algorithms-with-strings) 17 | 7. [Conclusion](#conclusion) 18 | 19 | --- 20 | 21 | ## What is `std::string`? 22 | 23 | `std::string` is part of the STL, which provides a flexible and powerful way to work with character sequences. Unlike traditional C-style strings (`char` arrays), `std::string` is a class that provides dynamic memory management, making it easier to work with strings of varying lengths. 24 | 25 | ### Example: 26 | ```cpp 27 | #include 28 | #include 29 | 30 | int main() { 31 | std::string str = "Hello, STL!"; 32 | std::cout << str << std::endl; // Output: Hello, STL! 33 | return 0; 34 | } 35 | ``` 36 | ### Basic Operations on Strings 37 | ## String Length 38 | The size() or length() function returns the number of characters in a string. 39 | ```cpp 40 | std::string str = "C++ STL"; 41 | std::cout << "Length: " << str.length() << std::endl; // Output: 7 42 | ``` 43 | ## Concatenation 44 | You can concatenate two strings using the + operator. 45 | ```cpp 46 | std::string str1 = "Hello, "; 47 | std::string str2 = "World!"; 48 | std::string result = str1 + str2; 49 | std::cout << result << std::endl; // Output: Hello, World! 50 | ``` 51 | ## SubStrings 52 | The substr() function extracts a substring from a given string. 53 | ```cpp 54 | std::string str = "C++ Programming"; 55 | std::string sub = str.substr(4, 11); // Extracts "Programming" 56 | std::cout << sub << std::endl; 57 | ``` 58 |
59 | 60 | ### Iterating Over Strings 61 | You can use different iteration techniques to loop through the characters of a string. 62 | ## 1. Using for Loop 63 | ```cpp 64 | std::string str = "STL Example"; 65 | for (int i = 0; i < str.size(); ++i) { 66 | std::cout << str[i] << " "; 67 | } 68 | ``` 69 | ## 2. Using Range-based for Loop 70 | ```cpp 71 | for (char c : str) { 72 | std::cout << c << " "; 73 | } 74 | ``` 75 | ## 3. Using Iterators 76 | ```cpp 77 | for (auto it = str.begin(); it != str.end(); ++it) { 78 | std::cout << *it << " "; 79 | } 80 | ``` 81 |
82 | 83 | ### String Modifications 84 | ## 1. Inserting Characters or Strings 85 | The insert() function can add characters or strings at a specified position. 86 | ```cpp 87 | std::string str = "Hello!"; 88 | str.insert(5, ", World"); // Inserts ", World" at position 5 89 | std::cout << str << std::endl; // Output: Hello, World! 90 | ``` 91 | ## 2. Removing Characters or Substrings 92 | The erase() function removes characters or substrings from the string. 93 | ```cpp 94 | std::string str = "abcdef"; 95 | str.erase(2, 3); // Removes 3 characters starting from position 2 96 | std::cout << str << std::endl; // Output: abf 97 | ``` 98 | ## 3. Replacing Part of a String 99 | The replace() function allows replacing parts of the string. 100 | ```cpp 101 | std::string str = "Good Morning!"; 102 | str.replace(5, 7, "Evening"); // Replaces "Morning" with "Evening" 103 | std::cout << str << std::endl; // Output: Good Evening! 104 | ``` 105 | 106 | ### Search Operations 107 | ## 1. Finding Substrings 108 | The find() function locates a substring within the string. 109 | ```cpp 110 | std::string str = "C++ is fun"; 111 | size_t pos = str.find("fun"); 112 | if (pos != std::string::npos) { 113 | std::cout << "'fun' found at position " << pos << std::endl; 114 | } 115 | ``` 116 | ## 2. Reverse Find 117 | The rfind() function searches for the last occurrence of a substring. 118 | ```cpp 119 | std::string str = "one two one three"; 120 | size_t pos = str.rfind("one"); 121 | std::cout << "Last occurrence of 'one' is at: " << pos << std::endl; // Output: 8 122 | ``` 123 |
124 | 125 | ### Common STL Algorithms with Strings 126 | ## 1. Sorting Characters 127 | Using std::sort() to sort the characters of a string. 128 | ```cpp 129 | std::string str = "dbca"; 130 | std::sort(str.begin(), str.end()); 131 | std::cout << str << std::endl; // Output: abcd 132 | ``` 133 | ## 2. Counting Occurrences 134 | You can use std::count() to count the occurrences of a character in a string. 135 | ```cpp 136 | int count = std::count(str.begin(), str.end(), 'a'); 137 | std::cout << "'a' appears " << count << " times" << std::endl; 138 | ``` 139 | ## 3. Transforming Case 140 | Using std::transform() to convert all characters to uppercase or lowercase. 141 | ```cpp 142 | std::transform(str.begin(), str.end(), str.begin(), ::toupper); 143 | std::cout << str << std::endl; // Output: ABCD 144 | ``` 145 |
146 | 147 | ### Conclusion 148 | The std::string class in STL offers a wide range of functionality for efficient string manipulation. Combining std::string with STL algorithms and iterators makes it a powerful tool for handling text in C++. With the examples and functions discussed in this guide, you should be able to perform most common string operations in your C++ projects. 149 | 150 | ### References 151 | https://www.geeksforgeeks.org/strings-in-cpp/ 152 | -------------------------------------------------------------------------------- /C++/StringInterviewQuetions/quetion1.cpp: -------------------------------------------------------------------------------- 1 | // to check whether a string is a palindrome 2 | // a palindrome can be considered as a string readed backwards and forwards same. 3 | #include 4 | using namespace std; 5 | 6 | int main(){ 7 | //declaration of a string 8 | string result = "hi"; 9 | //creating a copy by storing the string in another string. 10 | string check = result; 11 | //reversing the string 12 | int start = 0; 13 | int end = result.size() - 1; 14 | while(start<=end){ 15 | swap(result[start], result[end]); 16 | start++; 17 | end--; 18 | } 19 | if(result==check){ 20 | cout<<"String is a Palindrome"< 3 | using namespace std; 4 | 5 | int main(){ 6 | string result = "Aaaabhirajjjjj"; 7 | unordered_map freq; 8 | 9 | // Convert all characters to lowercase and count frequency 10 | for(int i = 0; i < result.size(); i++){ 11 | char lowerChar = tolower(result[i]); 12 | freq[lowerChar]++; 13 | } 14 | 15 | // Find the maximum occurring character 16 | char maxChar = result[0]; 17 | int maxCount = 0; 18 | for(auto& pair : freq){ 19 | if(pair.second > maxCount){ 20 | maxCount = pair.second; 21 | maxChar = pair.first; 22 | } 23 | } 24 | 25 | cout << "The maximum occurring character is: " << maxChar << " with " << maxCount << " occurrences." << endl; 26 | return 0; 27 | } -------------------------------------------------------------------------------- /C++/StringInterviewQuetions/quetion10.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panditakshay402/Hacktoberfest/d3cd7b4552bd0543c1b182545aecc66a1ebca038/C++/StringInterviewQuetions/quetion10.exe -------------------------------------------------------------------------------- /C++/StringInterviewQuetions/quetion2.cpp: -------------------------------------------------------------------------------- 1 | //count number of vowels,consonants and spaces in a string 2 | #include 3 | using namespace std; 4 | 5 | int main(){ 6 | string testCase = "Abhiraj Tiwari"; 7 | int vowels = 0, consonants = 0, spaces = 0; 8 | unordered_map alphabets = {{'a', true}, {'e', true}, {'i', true}, {'o', true}, {'u', true}, {'A', true}, {'E', true}, {'I', true}, {'O', true}, {'U', true}}; 9 | for(int i=0;i 3 | using namespace std; 4 | 5 | int main(){ 6 | string result = "This is a sample string with vowels."; 7 | unordered_map alphabets = {{'a', true}, {'e', true}, {'i', true}, {'o', true}, {'u', true}, {'A', true}, {'E', true}, {'I', true}, {'O', true}, {'U', true}}; 8 | for(int i=0; i 3 | using namespace std; 4 | 5 | int main(){ 6 | string result = "(Abhiraj)"; 7 | for(int i=0;i 2 | using namespace std; 3 | 4 | int main(){ 5 | string numbers = "12345"; 6 | int sum = 0; 7 | for(int i=0;i 3 | using namespace std; 4 | 5 | int main(){ 6 | string result = "abhiraj"; 7 | for(int i=0;i 4 | using namespace std; 5 | 6 | int main(){ 7 | string result = "Abhiraj"; 8 | sort(result.begin(),result.end()); 9 | 10 | for(int i=0;i 4 | using namespace std; 5 | 6 | int main(){ 7 | string result1 = "mug"; 8 | string result2 = "gum"; 9 | sort(result1.begin(), result1.end()); 10 | sort(result2.begin(), result2.end()); 11 | if(result1 == result2){ 12 | cout<<"Both strings are Anagrams"< 3 | using namespace std; 4 | 5 | int main(){ 6 | unordered_map alphabets = {{'*', true}, {'@', true}, {'#', true}, {'$', true}}; 7 | string result1 = "Abhiraj"; 8 | string result2 = "@Abhiraj"; 9 | for(int i=0;i 2 | #include 3 | 4 | using namespace std; 5 | 6 | bool isSafe(vector>& board, int row, int col, int num) { 7 | for (int i = 0; i < 9; ++i) { 8 | if (board[row][i] == num || board[i][col] == num) { 9 | return false; 10 | } 11 | } 12 | 13 | int startRow = row - row % 3; 14 | int startCol = col - col % 3; 15 | 16 | for (int i = 0; i < 3; ++i) { 17 | for (int j = 0; j < 3; ++j) { 18 | if (board[startRow + i][startCol + j] == num) { 19 | return false; 20 | } 21 | } 22 | } 23 | 24 | return true; 25 | } 26 | 27 | bool solveSudoku(vector>& board) { 28 | for (int row = 0; row < 9; ++row) { 29 | for (int col = 0; col < 9; ++col) { 30 | if (board[row][col] == 0) { 31 | for (int num = 1; num <= 9; ++num) { 32 | if (isSafe(board, row, col, num)) { 33 | board[row][col] = num; 34 | if (solveSudoku(board)) { 35 | return true; 36 | } 37 | board[row][col] = 0; 38 | } 39 | } 40 | return false; 41 | } 42 | } 43 | } 44 | return true; 45 | } 46 | 47 | int main() { 48 | vector> board = { 49 | {5, 3, 0, 0, 7, 0, 0, 0, 0}, 50 | {6, 0, 0, 1, 9, 5, 0, 0, 0}, 51 | {0, 9, 8, 0, 0, 0, 0, 6, 0}, 52 | {8, 0, 0, 0, 6, 0, 0, 0, 3}, 53 | {4, 0, 0, 8, 0, 3, 0, 0, 1}, 54 | {7, 0, 0, 0, 2, 0, 0, 0, 6}, 55 | {0, 6, 0, 0, 0, 0, 2, 8, 0}, 56 | {0, 0, 0, 4, 1, 9, 0, 0, 5}, 57 | {0, 0, 0, 0, 8, 0, 0, 7, 9} 58 | }; 59 | 60 | if (solveSudoku(board)) { 61 | for (int i = 0; i < 9; ++i) { 62 | for (int j = 0; j < 9; ++j) { 63 | cout << board[i][j] << " "; 64 | } 65 | cout << endl; 66 | } 67 | } else { 68 | cout << "No solution exists." << endl; 69 | } 70 | 71 | return 0; 72 | } 73 | -------------------------------------------------------------------------------- /C++/Treap.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | struct Node { 7 | int key; 8 | int priority; 9 | Node* left; 10 | Node* right; 11 | 12 | Node(int k, int p) : key(k), priority(p), left(NULL), right(NULL) {} 13 | }; 14 | 15 | Node* rotateRight(Node* y) { 16 | Node* x = y->left; 17 | Node* T2 = x->right; 18 | 19 | x->right = y; 20 | y->left = T2; 21 | 22 | return x; 23 | } 24 | 25 | Node* rotateLeft(Node* x) { 26 | Node* y = x->right; 27 | Node* T2 = y->left; 28 | 29 | y->left = x; 30 | x->right = T2; 31 | 32 | return y; 33 | } 34 | 35 | Node* insert(Node* root, int key, int priority) { 36 | if (root == NULL) return new Node(key, priority); 37 | 38 | if (key <= root->key) { 39 | root->left = insert(root->left, key, priority); 40 | 41 | if (root->left->priority > root->priority) 42 | root = rotateRight(root); 43 | } else { 44 | root->right = insert(root->right, key, priority); 45 | 46 | if (root->right->priority > root->priority) 47 | root = rotateLeft(root); 48 | } 49 | 50 | return root; 51 | } 52 | 53 | void inorder(Node* root) { 54 | if (root) { 55 | inorder(root->left); 56 | cout << "Key: " << root->key << ", Priority: " << root->priority << endl; 57 | inorder(root->right); 58 | } 59 | } 60 | 61 | int main() { 62 | Node* root = NULL; 63 | 64 | // Insert keys with random priorities 65 | root = insert(root, 10, 5); 66 | root = insert(root, 20, 10); 67 | root = insert(root, 5, 15); 68 | 69 | // Print inorder traversal 70 | inorder(root); 71 | 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /C++/Update BinarySearch.md: -------------------------------------------------------------------------------- 1 | # Binary Search Implementation 2 | 3 | ## Overview 4 | Binary Search is an efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing the portion of the list that could contain the item in half until you've narrowed down the possible locations to just one. 5 | 6 | ## Iterative Binary Search Implementation 7 | 8 | ### C++ Code 9 | ```cpp 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | // Function to perform binary search iteratively 15 | // Time Complexity: O(log n), Space Complexity: O(1) 16 | int binarySearch(vector &arr, int target) 17 | { 18 | int n = arr.size(); 19 | int start = 0; 20 | int end = n - 1; 21 | 22 | // Loop until the start index exceeds the end index 23 | while (start <= end) 24 | { 25 | // Calculate mid index to avoid overflow 26 | int mid = start + (end - start) / 2; 27 | 28 | // Check if the target is found at mid index 29 | if (target == arr[mid]) 30 | return mid; // Return the mid index if found 31 | else if (target > arr[mid]) 32 | start = mid + 1; // Search in right half 33 | else 34 | end = mid - 1; // Search in left half 35 | } 36 | return -1; // Return -1 if the target is not found 37 | } 38 | 39 | int main() 40 | { 41 | vector arr = {-1, 0, 3, 4, 5, 9, 12}; // Example sorted array 42 | cout << binarySearch(arr, 3) << endl; 43 | return 0; 44 | } 45 | ``` 46 | ### Recursion Binary Serach Implemenation 47 | 48 | ### C++ Code 49 | ```cpp 50 | #include 51 | #include 52 | using namespace std; 53 | 54 | // Function to perform binary search recusrively 55 | // Time Complexity: O(log n), Space Complexity: O(log n) 56 | int recursiveBinarySearch(vector &arr, int target, int start, int end) 57 | { 58 | // Base condition: if search range is valid 59 | if (start <= end) 60 | { 61 | // Calculate the middle index (avoids overflow) 62 | int mid = start + (end - start) / 2; 63 | 64 | // If target is less than mid element, search left half 65 | if (target < arr[mid]) 66 | { 67 | return recursiveBinarySearch(arr, target, start, mid - 1); 68 | } 69 | // If target is greater than mid element, search right half 70 | else if (target > arr[mid]) 71 | { 72 | return recursiveBinarySearch(arr, target, mid + 1, end); 73 | } 74 | // Target found at mid index 75 | else 76 | { 77 | return mid; 78 | } 79 | } 80 | 81 | // Target not found in array 82 | return -1; 83 | } 84 | int main() 85 | { 86 | vector arr = {-1, 0, 3, 4, 5, 9, 12}; // Example sorted array 87 | int n = arr.size(); 88 | cout << recursiveBinarySearch(arr, 9, 0, n - 1) << endl; 89 | return 0; 90 | } 91 | 92 | ``` 93 | ## Complexity Analysis 94 | 95 | ### Iterative Binary Search 96 | - **Time Complexity**: O(log n) 97 | - The algorithm halves the search space with each comparison, making it efficient for large datasets. 98 | 99 | - **Space Complexity**: O(1) 100 | - The iterative approach uses a constant amount of space, as it does not require additional space for function call stacks. 101 | 102 | ### Recursive Binary Search 103 | - **Time Complexity**: O(log n) 104 | - Similar to the iterative version, it also reduces the search space by half with each recursive call. 105 | 106 | - **Space Complexity**: O(log n) 107 | - The recursive approach utilizes the call stack, which can lead to increased memory usage for deep recursion. 108 | 109 | ### Why Iterative is Preferred 110 | - **Memory Efficiency**: The iterative approach uses O(1) space, making it more memory-efficient than the recursive version, which requires O(log n) space due to the call stack. 111 | 112 | - **Performance**: Iterative solutions generally have lower overhead than recursive solutions. Each recursive call involves function call overhead, which can slow down execution. 113 | 114 | - **Avoiding Stack Overflow**: The iterative approach can handle larger datasets without the risk of stack overflow errors that can occur with deep recursion in the recursive version. 115 | 116 | In summary, the iterative binary search is often favored in practice due to its efficiency in both time and space, making it a more robust solution for larger datasets. 117 | -------------------------------------------------------------------------------- /C++/binary_search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int binarySearchRecursive(const std::vector& arr, int target, int left, int right) { 5 | if (left > right) { 6 | return -1; // Target not found 7 | } 8 | 9 | int mid = left + (right - left) / 2; 10 | 11 | if (arr[mid] == target) { 12 | return mid; // Target found at index 'mid' 13 | } else if (arr[mid] < target) { 14 | return binarySearchRecursive(arr, target, mid + 1, right); 15 | } else { 16 | return binarySearchRecursive(arr, target, left, mid - 1); 17 | } 18 | } 19 | 20 | int main() { 21 | std::vector arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 22 | int target = 7; 23 | int result = binarySearchRecursive(arr, target, 0, arr.size() - 1); 24 | 25 | if (result != -1) { 26 | std::cout << "Target " << target << " found at index " << result << std::endl; 27 | } else { 28 | std::cout << "Target " << target << " not found in the array." << std::endl; 29 | } 30 | 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /C++/binary_search.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panditakshay402/Hacktoberfest/d3cd7b4552bd0543c1b182545aecc66a1ebca038/C++/binary_search.exe -------------------------------------------------------------------------------- /C++/linear-search.cpp: -------------------------------------------------------------------------------- 1 | // Linear Search in C++ 2 | 3 | #include 4 | using namespace std; 5 | 6 | int search(int array[], int n, int x) { 7 | 8 | // Going through array sequencially 9 | for (int i = 0; i < n; i++) 10 | if (array[i] == x) 11 | return i; 12 | return -1; 13 | } 14 | 15 | int main() { 16 | int array[] = {2, 4, 0, 1, 9}; 17 | int x = 1; 18 | int n = sizeof(array) / sizeof(array[0]); 19 | 20 | int result = search(array, n, x); 21 | 22 | (result == -1) ? cout << "Element not found" : cout << "Element found at index: " << result; 23 | } 24 | -------------------------------------------------------------------------------- /C++/mostOptimalBFS.cpp: -------------------------------------------------------------------------------- 1 | //BFS stands for Breadth First Search. It is a graph traversal algorithm that visits all the vertices of a graph in breadth-first order, i.e., it visits all the vertices at the same level before moving on to the next level. BFS is implemented using a queue data structure. 2 | 3 | //The algorithm starts at a given vertex (usually the root) and explores all the vertices at the current level before moving on to the next level. It maintains a queue of vertices that are yet to be explored. The algorithm dequeues a vertex from the queue, explores all its neighbors, and enqueues any unexplored neighbors. This process continues until all the vertices have been explored. 4 | 5 | //BFS is useful for finding the shortest path between two vertices in an unweighted graph. It can also be used to detect cycles in a graph and to check if a graph is bipartite. 6 | 7 | //In the code provided, the BFS algorithm is implemented using an adjacency list to represent the graph and a boolean array to keep track of visited nodes. The algorithm starts at node 0 and explores all the nodes reachable from it using the BFS traversal. The output of the algorithm is the order in which the nodes are visited. 8 | 9 | #include 10 | #include 11 | #include 12 | 13 | using namespace std; 14 | 15 | // Function to perform Breadth First Search (BFS) traversal on a graph 16 | void bfs(vector adj[], int start, bool visited[]) { 17 | queue q; 18 | visited[start] = true; 19 | q.push(start); 20 | 21 | // Loop until all nodes in the graph have been visited 22 | while (!q.empty()) { 23 | int curr = q.front(); 24 | q.pop(); 25 | cout << curr << " "; // Print the current node 26 | 27 | // Visit all neighbors of the current node 28 | for (int i = 0; i < adj[curr].size(); i++) { 29 | int neighbor = adj[curr][i]; 30 | if (!visited[neighbor]) { 31 | visited[neighbor] = true; 32 | q.push(neighbor); 33 | } 34 | } 35 | } 36 | } 37 | 38 | int main() { 39 | int n, m; 40 | cin >> n >> m; 41 | 42 | vector adj[n]; // Create an adjacency list to represent the graph 43 | bool visited[n] = {false}; // Create an array to keep track of visited nodes 44 | 45 | // Read in the edges of the graph 46 | for (int i = 0; i < m; i++) { 47 | int u, v; 48 | cin >> u >> v; 49 | adj[u].push_back(v); // Add edge from u to v 50 | adj[v].push_back(u); // Add edge from v to u 51 | } 52 | 53 | bfs(adj, 0, visited); // Perform BFS traversal starting from node 0 54 | 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /C++/multipleconstructor.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | class box 4 | { 5 | double height, width, depth; 6 | 7 | public: 8 | box() 9 | { 10 | height = width = depth = 0; 11 | } 12 | box(double length) 13 | { 14 | height = width = depth = length; 15 | } 16 | box(double h,double w,double d) 17 | { 18 | height = h; 19 | width = w; 20 | depth = d; 21 | } 22 | void show() 23 | { 24 | std::cout << "Height = " << height; 25 | std::cout << "\n"; 26 | std::cout << "Width = " << width; 27 | std::cout << "\n"; 28 | std::cout << "Depth = " << depth; 29 | std::cout << "\n"; 30 | } 31 | }; 32 | 33 | int main() 34 | { 35 | box b1(10,20,10); 36 | box b2(25); 37 | box b3; 38 | b1.show(); 39 | std::cout << "\n------------------\n"; 40 | b2.show(); 41 | std::cout << "\n------------------\n"; 42 | b3.show(); 43 | } -------------------------------------------------------------------------------- /C++/paintersPartition.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given n boards of different lengths represented by an array arr of size n, and m painters, 3 | you need to determine the minimum amount of time required to paint all the boards. Each painter paints a contiguous segment of boards. 4 | Constraints: 5 | 6 | A painter can only paint continuous segments of boards. 7 | Each painter takes the same amount of time to paint a unit length of the board. 8 | You have to minimize the maximum time taken by a painter to paint their assigned boards. 9 | Input: 10 | An integer n representing the number of boards. 11 | An integer m representing the number of painters. 12 | An array arr[] of size n, where each element arr[i] represents the length of the i-th board. 13 | Output: 14 | Return the minimum time required to paint all the boards such that no painter is overloaded with work. 15 | */ 16 | 17 | #include 18 | #include 19 | #include 20 | using namespace std; 21 | 22 | bool isPossible(vector&arr, int n, int m, int maxAllowedTime){ 23 | int painter = 1, time = 0; 24 | for(int i=0; i &arr, int n, int m){ 36 | int sum =0, maxVal = INT_MIN; 37 | for(int i=0; iarr = {40,30,10,20}; 59 | int n = 4, m =2; 60 | cout< 2 | using namespace std; 3 | // #define int long long 4 | // #define endl "\n" 5 | 6 | void prrt(int n,string s){ 7 | if(n==0){ 8 | return; 9 | } 10 | cout<>n;//enter the number of times you want to print your string 18 | string s; 19 | cin>>s;// enter the string you want to plrint 20 | prrt(n,s);//function to recursively print the string 21 | return 0; 22 | } -------------------------------------------------------------------------------- /C++/printnameNtimes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void printName(int N, const std::string& name) { 5 | if (N > 0) { 6 | std::cout << name << std::endl; 7 | printName(N - 1, name); 8 | } 9 | } 10 | 11 | int main() { 12 | int N; 13 | std::string name; 14 | 15 | std::cout << "Enter your name: "; 16 | std::cin >> name; 17 | 18 | std::cout << "Enter the number of times to print your name: "; 19 | std::cin >> N; 20 | 21 | printName(N, name); 22 | 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /C++/segment.cpp: -------------------------------------------------------------------------------- 1 | // C++ code for segment tree with sum 2 | // range and update query 3 | 4 | #include 5 | using namespace std; 6 | vector A, ST; 7 | 8 | void build(int node, int L, int R) 9 | { 10 | 11 | // Leaf node where L == R 12 | if (L == R) { 13 | ST[node] = A[L]; 14 | } 15 | else { 16 | 17 | // Find the middle element to 18 | // split the array into two halves 19 | int mid = (L + R) / 2; 20 | 21 | // Recursively travel the 22 | // left half 23 | build(2 * node, L, mid); 24 | 25 | // Recursively travel the 26 | // right half 27 | build(2 * node + 1, mid + 1, R); 28 | 29 | // Storing the sum of both the 30 | // children into the parent 31 | ST[node] = ST[2 * node] + ST[2 * node + 1]; 32 | } 33 | } 34 | 35 | void update(int node, int L, int R, int idx, int val) 36 | { 37 | 38 | // Find the lead node and 39 | // update its value 40 | if (L == R) { 41 | A[idx] += val; 42 | ST[node] += val; 43 | } 44 | else { 45 | 46 | // Find the mid 47 | int mid = (L + R) / 2; 48 | 49 | // If node value idx is at the 50 | // left part then update 51 | // the left part 52 | if (L <= idx and idx <= mid) 53 | update(2 * node, L, mid, idx, val); 54 | else 55 | update(2 * node + 1, mid + 1, R, idx, val); 56 | 57 | // Store the information in parents 58 | ST[node] = ST[2 * node] + ST[2 * node + 1]; 59 | } 60 | } 61 | 62 | int query(int node, int tl, int tr, int l, int r) 63 | { 64 | 65 | // If it lies out of range then 66 | // return 0 67 | if (r < tl or tr < l) 68 | return 0; 69 | 70 | // If the node contains the range then 71 | // return the node value 72 | if (l <= tl and tr <= r) 73 | return ST[node]; 74 | int tm = (tl + tr) / 2; 75 | 76 | // Recursively traverse left and right 77 | // and find the node 78 | return query(2 * node, tl, tm, l, r) 79 | + query(2 * node + 1, tm + 1, tr, l, r); 80 | } 81 | 82 | // Driver code 83 | int main() 84 | { 85 | int n = 6; 86 | A = { 0, 1, 3, 5, -2, 3 }; 87 | 88 | // Create a segment tree of size 4*n 89 | ST.resize(4 * n); 90 | 91 | // Build a segment tree 92 | build(1, 0, n - 1); 93 | cout << "Sum of values in range 0-4 are: " 94 | << query(1, 0, n - 1, 0, 4) << "\n"; 95 | 96 | // Update the value at idx = 1 by 97 | // 100 thus becoming 101 98 | update(1, 0, n - 1, 1, 100); 99 | cout << "Value at index 1 increased by 100\n"; 100 | cout << "sum of value in range 1-3 are: " 101 | << query(1, 0, n - 1, 1, 3) << "\n"; 102 | 103 | return 0; 104 | } 105 | -------------------------------------------------------------------------------- /C++/symmetric_Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | bool solve(TreeNode* left, TreeNode* right){ 15 | if(!left && !right) return true; 16 | if(!left || !right) return false; 17 | return (left->val == right->val && solve(left->left, right->right) && solve(left->right, right->left)); 18 | } 19 | bool isSymmetric(TreeNode* root) { 20 | return solve(root->left, root->right); 21 | } 22 | }; -------------------------------------------------------------------------------- /C/Binarysearch.c: -------------------------------------------------------------------------------- 1 | // Binary Search in C 2 | 3 | #include 4 | 5 | int binarySearch(int array[], int x, int low, int high) { 6 | // Repeat until the pointers low and high meet each other 7 | while (low <= high) { 8 | int mid = low + (high - low) / 2; 9 | 10 | if (array[mid] == x) 11 | return mid; 12 | 13 | if (array[mid] < x) 14 | low = mid + 1; 15 | 16 | else 17 | high = mid - 1; 18 | } 19 | 20 | return -1; 21 | } 22 | 23 | int main(void) { 24 | int array[] = {3, 4, 5, 6, 7, 8, 9}; 25 | int n = sizeof(array) / sizeof(array[0]); 26 | int x = 4; 27 | int result = binarySearch(array, x, 0, n - 1); 28 | if (result == -1) 29 | printf("Not found"); 30 | else 31 | printf("Element is found at index %d", result); 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /C/Pattern 1.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() { 3 | int i, j, n; 4 | printf("Enter no. of rows: "); 5 | scanf("%d", &n); 6 | 7 | // Iterate over the rows 8 | for (i = 0; i < n; i++) { 9 | // Iterate over the columns 10 | for (j = 0; j < n; j++) { 11 | // Print an asterisk 12 | printf("*"); 13 | } 14 | 15 | // Print a newline character to start a new row 16 | printf("\n"); 17 | } 18 | return 0; 19 | } 20 | 21 | 22 | /* 23 | OUTPUT 24 | 25 | Enter no. of rows: 5 26 | 27 | ***** 28 | ***** 29 | ***** 30 | ***** 31 | ***** 32 | 33 | */ -------------------------------------------------------------------------------- /C/Pattern 10.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int i,j,n; 6 | printf("Enter no. of rows: "); 7 | scanf("%d",&n); 8 | for(i=5;i>=1;i--){ 9 | for(j=1;j<=i;j++){ 10 | printf("%d",j); 11 | } 12 | printf("\n"); 13 | } 14 | return 0; 15 | } -------------------------------------------------------------------------------- /C/Pattern 2.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int i,j,n; 6 | printf("Enter no. of rows: "); 7 | scanf("%d",&n); 8 | for(i=0;i 2 | 3 | int main() 4 | { 5 | int i,j,n; 6 | printf("Enter no. of rows: "); 7 | scanf("%d",&n); 8 | for(i=1;i<=n;i++){ 9 | for(j=1;j<=i;j++){ 10 | printf("%d",j); 11 | } 12 | printf("\n"); 13 | } 14 | return 0; 15 | } -------------------------------------------------------------------------------- /C/Pattern 4.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int i,j,n; 6 | printf("Enter no. of rows: "); 7 | scanf("%d",&n); 8 | for(i=1;i<=n;i++){ 9 | for(j=1;j<=i;j++){ 10 | printf("%d",i); 11 | } 12 | printf("\n"); 13 | } 14 | return 0; 15 | } -------------------------------------------------------------------------------- /C/Pattern 5.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int i,j,n; 6 | printf("Enter no. of rows: "); 7 | scanf("%d",&n); 8 | for(i=1;i<=n;i++){ 9 | for(j=n;j>=i;j--){ 10 | printf("*"); 11 | } 12 | printf("\n"); 13 | } 14 | return 0; 15 | } -------------------------------------------------------------------------------- /C/Pattern 6.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int i,j,n; 6 | printf("Enter no. of rows: "); 7 | scanf("%d",&n); 8 | for(i=1;i<=n;i++){ 9 | for(j=n;j>i;j--){ 10 | printf(" "); 11 | } 12 | for(j=1;j<=i;j++){ 13 | printf("*"); 14 | } 15 | for(j=1;j 2 | 3 | int main() 4 | { 5 | int i,j,n; 6 | printf("Enter no. of rows: "); 7 | scanf("%d",&n); 8 | for(i=1;i<=n;i++){ 9 | for(j=n;j>=i;j--){ 10 | printf(" "); 11 | } 12 | for(j=1;j<=i;j++){ 13 | printf("*"); 14 | } 15 | for(j=1;j=i;j--){ 25 | printf("*"); 26 | } 27 | for(j=n;j>i;j--){ 28 | printf("*"); 29 | } 30 | printf("\n"); 31 | } 32 | return 0; 33 | } -------------------------------------------------------------------------------- /C/Pattern 8.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int i,j,n; 6 | printf("Enter no. of rows: "); 7 | scanf("%d",&n); 8 | for(i=1;i<=n;i++){ 9 | for(j=1;j<=i;j++){ 10 | printf("%d",j); 11 | } 12 | for(j=n;j>i;j--){ 13 | printf(" "); 14 | } 15 | for(j=n;j>i;j--){ 16 | printf(" "); 17 | } 18 | for(j=i;j>=1;j--){ 19 | printf("%d",j); 20 | } 21 | printf("\n"); 22 | } 23 | return 0; 24 | } -------------------------------------------------------------------------------- /C/Pattern 9.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int i,j,n; 6 | printf("Enter no. of rows: "); 7 | scanf("%d",&n); 8 | for(i=1;i<=n;i++){ 9 | for(j=n;j>=i;j--){ 10 | printf("*"); 11 | } 12 | for(j=i;j>1;j--){ 13 | printf(" "); 14 | } 15 | for(j=i;j>1;j--){ 16 | printf(" "); 17 | } 18 | for(j=n;j>=i;j--){ 19 | printf("*"); 20 | } 21 | printf("\n"); 22 | } 23 | for(i=1;i<=n;i++){ 24 | for(j=1;j<=i;j++){ 25 | printf("*"); 26 | } 27 | for(j=n;j>i;j--){ 28 | printf(" "); 29 | } 30 | for(j=n;j>i;j--){ 31 | printf(" "); 32 | } 33 | for(j=1;j<=i;j++){ 34 | printf("*"); 35 | } 36 | printf("\n"); 37 | } 38 | return 0; 39 | } -------------------------------------------------------------------------------- /C/Pattern1.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int i, j, rows; 5 | 6 | // Prompt the user to enter the number of rows 7 | printf("Enter the number of rows: "); 8 | scanf("%d", &rows); 9 | 10 | // Outer loop to iterate through rows 11 | for (i = 1; i <= rows; i++) { 12 | // Inner loop to print spaces before numbers 13 | for (j = 1; j <= rows - i; j++) { 14 | printf(" "); // Two spaces for alignment 15 | } 16 | 17 | // Inner loop to print numbers 18 | for (j = 1; j <= i; j++) { 19 | printf("%2d ", j); // %2d ensures a minimum width of 2 characters for alignment 20 | } 21 | 22 | // Move to the next line after each row 23 | printf("\n"); 24 | } 25 | 26 | return 0; 27 | } 28 | 29 | // Explanation: 30 | 31 | // We start by including the necessary header file, , which is required for input and output functions. 32 | 33 | // We declare integer variables i, j, and rows. i is used to iterate through rows, j is used for column printing, and rows stores the user input for the number of rows. 34 | 35 | // We prompt the user to enter the number of rows using printf and then read the input using scanf. 36 | 37 | // We use an outer loop (for loop) to iterate through the rows. The loop runs from 1 to rows. 38 | 39 | // Inside the outer loop, we use two inner loops: 40 | 41 | // The first inner loop (for j) is used to print spaces before the numbers. The number of spaces is determined by rows - i to create a right-angled triangle effect. 42 | 43 | // The second inner loop (for j) is used to print the numbers. We use %2d in printf to ensure that each number occupies at least two characters for better alignment. 44 | 45 | // After printing each row of numbers, we move to the next line using printf("\n") to start a new row. 46 | 47 | // This program will print a right-angled triangle pattern of numbers with proper alignment and comments for clarity. You can change the number of rows by entering a different value when prompted. -------------------------------------------------------------------------------- /C/Pattern2.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int i, j, space, rows; 5 | 6 | // Prompt the user to enter the number of rows 7 | printf("Enter the number of rows: "); 8 | scanf("%d", &rows); 9 | 10 | // Loop to print the rows 11 | for (i = 1; i <= rows; i++) { 12 | // Loop to print leading spaces 13 | for (space = 1; space <= rows - i; space++) { 14 | printf(" "); 15 | } 16 | 17 | // Loop to print asterisks 18 | for (j = 1; j <= 2 * i - 1; j++) { 19 | printf("*"); 20 | } 21 | 22 | // Move to the next line after each row 23 | printf("\n"); 24 | } 25 | 26 | return 0; 27 | } 28 | 29 | // Explanation: 30 | 31 | // This program, like the previous one, includes the necessary header file for input and output functions. 32 | 33 | // We declare integer variables i, j, space, and rows. i is used to iterate through rows, j is used for printing asterisks, space is used for printing leading spaces, and rows stores the user input for the number of rows. 34 | 35 | // The program prompts the user to enter the number of rows and reads the input using scanf. 36 | 37 | // We use an outer loop (for i) to iterate through the rows, starting from 1 and going up to rows. 38 | 39 | // Inside the outer loop, we have two inner loops: 40 | 41 | // The first inner loop (for space) is used to print leading spaces before the asterisks. The number of spaces is determined by rows - i. 42 | 43 | // The second inner loop (for j) is used to print the asterisks. The number of asterisks in each row is 2 * i - 1, which creates a pyramid shape. 44 | 45 | // After printing each row, we move to the next line using printf("\n") to start a new row. 46 | 47 | // This program will print a pyramid pattern made of asterisks with the specified number of rows. You can change the number of rows by entering a different value when prompted. -------------------------------------------------------------------------------- /C/Pattern3.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int i, j, space, rows; 5 | 6 | // Prompt the user to enter the number of rows (must be an odd number for a symmetric diamond) 7 | printf("Enter the number of rows (odd number): "); 8 | scanf("%d", &rows); 9 | 10 | if (rows % 2 == 0) { 11 | printf("Please enter an odd number for a symmetric diamond.\n"); 12 | return 1; // Exit the program with an error code 13 | } 14 | 15 | int midpoint = (rows + 1) / 2; // Calculate the midpoint of the diamond 16 | 17 | // Loop to print the upper half of the diamond 18 | for (i = 1; i <= midpoint; i++) { 19 | // Loop to print leading spaces 20 | for (space = 1; space <= midpoint - i; space++) { 21 | printf(" "); 22 | } 23 | 24 | // Loop to print asterisks 25 | for (j = 1; j <= 2 * i - 1; j++) { 26 | printf("*"); 27 | } 28 | 29 | // Move to the next line after each row 30 | printf("\n"); 31 | } 32 | 33 | // Loop to print the lower half of the diamond 34 | for (i = midpoint - 1; i >= 1; i--) { 35 | // Loop to print leading spaces 36 | for (space = 1; space <= midpoint - i; space++) { 37 | printf(" "); 38 | } 39 | 40 | // Loop to print asterisks 41 | for (j = 1; j <= 2 * i - 1; j++) { 42 | printf("*"); 43 | } 44 | 45 | // Move to the next line after each row 46 | printf("\n"); 47 | } 48 | 49 | return 0; 50 | } 51 | 52 | // Explanation: 53 | 54 | // This program prints a diamond pattern of asterisks with the specified number of rows. It includes a check to ensure that the number of rows entered by the user is odd because a symmetric diamond pattern requires an odd number of rows. 55 | 56 | // It declares integer variables i, j, space, rows, and midpoint. i is used to iterate through rows, j is used for printing asterisks, space is used for printing leading spaces, rows stores the user input for the number of rows, and midpoint calculates the midpoint of the diamond. 57 | 58 | // The program prompts the user to enter the number of rows and reads the input using scanf. 59 | 60 | // It checks if the entered number of rows is even. If it is, it prints an error message and exits the program with an error code. 61 | 62 | // The program calculates the midpoint of the diamond pattern. 63 | 64 | // It uses an outer loop (for i) to print the upper half of the diamond pattern and another outer loop to print the lower half of the diamond pattern. Both loops use similar logic for printing leading spaces and asterisks. 65 | 66 | // After printing each row, the program moves to the next line using printf("\n"). 67 | 68 | // This program will print a diamond pattern made of asterisks with the specified number of rows, ensuring it is symmetric for odd row counts. You can change the number of rows by entering a different odd value when prompted. -------------------------------------------------------------------------------- /C/Pattern5.c: -------------------------------------------------------------------------------- 1 | /*Sample OUTPUT 2 | 1 3 | 21 4 | 321 5 | 4321 6 | 54321*/ 7 | #include 8 | int main() 9 | { 10 | int n, i, j; 11 | // Prompt the user to enter the number of rows 12 | printf("Enter the number of rows: "); 13 | scanf("%d", &n); 14 | // Outer loop to iterate through rows 15 | for (i = 1; i <= n; i++) 16 | { 17 | // Inner loop to print spaces before numbers 18 | for (j = n; j >= 1; j--) 19 | { 20 | if (j <= i) 21 | { 22 | //To print the number 23 | printf("%d", j); 24 | } 25 | else 26 | { 27 | //Space for alignment 28 | printf(" "); 29 | } 30 | } 31 | // Move to the next line after each row 32 | printf("\n"); 33 | } 34 | } 35 | /*This C code generates a right-angled triangle pattern with descending numbers and spaces. It first prompts the user for the number of rows, which determines the pattern's size. It uses nested loops: the outer one controls rows, and the inner one handles numbers and spaces. The inner loop prints numbers in descending order from the current row number and spaces for alignment. A newline character separates each row. This process repeats until the specified number of rows is reached, resulting in a visually appealing pattern similar to the provided sample output.*/ -------------------------------------------------------------------------------- /C/Right-Triangle-Pattern.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int rows; 5 | 6 | // Ask the user to enter the number of rows in the pattern 7 | printf("Enter the number of rows: "); 8 | scanf("%d", &rows); 9 | 10 | // Outer loop will iterate through each row of the pattern 11 | for(int i = 1; i <= rows; i++) { 12 | // Inner loop will print stars in each row 13 | for(int j = 1; j <= i; j++) { 14 | // Print a star and a space 15 | printf("* "); 16 | } 17 | // Move to the next line after printing stars in one row 18 | printf("\n"); 19 | } 20 | 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /C/output/Pattern 1.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panditakshay402/Hacktoberfest/d3cd7b4552bd0543c1b182545aecc66a1ebca038/C/output/Pattern 1.exe -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | 2 | # Contributing to Hacktoberfest2025 3 | 4 | Thank you for considering contributing to Hacktoberfest2025! We welcome your contributions and appreciate your interest in making this project better. 5 | 6 | --- 7 | 8 | ## Getting Started 9 | 10 | Before you start contributing, please take a moment to: 11 | 12 | 1. **Read our [README](https://github.com/panditakshay402/Hacktoberfest/blob/main/README.md):** Understand the project's goals, scope, and structure. 13 | 2. **Review the Issues:** Check the [Issues](https://github.com/panditakshay402/Hacktoberfest/issues) section to see if your contribution idea or bug has already been discussed. 14 | 15 | --- 16 | 17 | ## Ways to Contribute 18 | 19 | We welcome various types of contributions, including but not limited to: 20 | 21 | - Reporting bugs. 22 | - Proposing and implementing new features. 23 | - Writing or improving documentation. 24 | - Enhancing code quality or performance. 25 | - Reviewing pull requests. 26 | - Participating in discussions. 27 | 28 | --- 29 | 30 | ## How to Contribute 31 | 32 | ### 1. **Fork the Repository** 33 | 34 | Click the "Fork" button on the top right corner of this repository's page, and clone your forked repository to your local machine: 35 | 36 | ```bash 37 | git clone https://github.com/your-username/hacktoberfest.git 38 | cd hacktoberfest2025 39 | ``` 40 | 41 | ### 2. **Create a New Branch** 42 | 43 | Create a new branch for your contribution. Use a descriptive branch name that reflects the purpose of your changes: 44 | 45 | ```bash 46 | git checkout -b feature/your-feature-name 47 | ``` 48 | 49 | ### 3. **Make Your Changes** 50 | 51 | Implement your changes in your local branch. Ensure your code adheres to our coding standards and includes comments where necessary. For documentation changes, follow the existing format. 52 | 53 | ### 4. **Test Your Changes** 54 | 55 | If applicable, run the project's tests to ensure your changes do not introduce any regressions. Add new tests if you are adding new functionality. 56 | 57 | ```bash 58 | # Example (adjust to your project's test framework): 59 | npm test 60 | ``` 61 | 62 | ### 5. **Commit Your Changes** 63 | 64 | Write clear and concise commit messages that explain the purpose of your changes. Follow this format: 65 | 66 | ``` 67 | [type] Brief description of changes 68 | 69 | - Detailed description of the changes. 70 | - Mention any related issues (e.g., closes #123). 71 | ``` 72 | 73 | Example: 74 | 75 | ```bash 76 | git add . 77 | git commit -m "[fix] Resolve issue with API response timeout" 78 | ``` 79 | 80 | ### 6. **Push Your Changes** 81 | 82 | Push your branch to your forked repository: 83 | 84 | ```bash 85 | git push origin feature/your-feature-name 86 | ``` 87 | 88 | ### 7. **Open a Pull Request** 89 | 90 | Go to the original repository and click the "New Pull Request" button. Fill out the pull request template with the following details: 91 | 92 | - **Description:** Clearly describe the changes you made and why they are necessary. 93 | - **Issue Reference:** Link any related issues. 94 | - **Testing:** Explain how your changes were tested. 95 | - **Checklist:** Confirm that your work meets the project’s contribution requirements. 96 | 97 | --- 98 | 99 | ## Guidelines 100 | 101 | ### Coding Standards 102 | 103 | - Ensure your code is clean, modular, and well-documented. 104 | - Use meaningful variable and function names. 105 | 106 | ### Documentation Standards 107 | 108 | - Use Markdown for documentation files. 109 | - Follow the structure and tone of existing documentation. 110 | - Ensure clarity and conciseness. 111 | 112 | ### Issue Reporting 113 | 114 | - Search the existing issues before opening a new one to avoid duplicates. 115 | - Use a clear and descriptive title. 116 | - Include steps to reproduce the issue, if applicable. 117 | - Attach relevant screenshots or logs, if helpful. 118 | 119 | --- 120 | 121 | ## Additional Resources 122 | 123 | - **Hacktoberfest:** [https://hacktoberfest.com](https://hacktoberfest.com) 124 | - **GitHub Documentation:** [https://docs.github.com](https://docs.github.com) 125 | - **Markdown Guide:** [https://www.markdownguide.org](https://www.markdownguide.org) 126 | 127 | --- 128 | 129 | **Thank you for your contributions to Hacktoberfest!** 130 | 131 | -------------------------------------------------------------------------------- /JAVA/A.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panditakshay402/Hacktoberfest/d3cd7b4552bd0543c1b182545aecc66a1ebca038/JAVA/A.java -------------------------------------------------------------------------------- /JAVA/BinarySearch.java: -------------------------------------------------------------------------------- 1 | class BinarySearch { 2 | private static int binarySearch(int numArray[], int number_to_search_for) { 3 | int low = 0; 4 | int high = numArray.length - 1; 5 | 6 | while (low <= high){ 7 | int middleIndex = (low + high) / 2; 8 | int middleIndexNumber = numArray[middleIndex]; 9 | 10 | if (number_to_search_for == middleIndexNumber){ 11 | return middleIndex; 12 | } 13 | if (number_to_search_for < middleIndexNumber){ 14 | high = middleIndex - 1; 15 | } 16 | if (number_to_search_for > middleIndexNumber){ 17 | low = middleIndex + 1; 18 | } 19 | } 20 | 21 | return -1; 22 | } 23 | public static void main(String args[]) { 24 | 25 | int[] arrayofnums = {2,3,6,8,9,13,20}; 26 | 27 | System.out.println(binarySearch(arrayofnums, 13)); 28 | // 5 29 | 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /JAVA/BucketSort.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class BucketSort 3 | { 4 | //user-defined method to sort array 5 | private static void binSort(int[] array, int bucketSize) 6 | { 7 | //creating a list of buckets for storing lists 8 | List[] buckets = new List[bktSize]; 9 | // Linked list with each bucket array index 10 | // as there may be hash collision 11 | for(int i = 0; i < bktSize; i++) 12 | { 13 | buckets[i] = new LinkedList<>(); 14 | } 15 | //calculate the hash and assigns elements to the proper bucket 16 | for(int num : array) 17 | { 18 | buckets[hash(num, bktSize)].add(num); 19 | } 20 | //iterate over the buckets and sorts the elements 21 | for(List bucket : buckets) 22 | { 23 | //sorts the bucket 24 | Collections.sort(bucket); 25 | } 26 | int index = 0; 27 | //gethered the buckets after sorting 28 | for(List bucket : buckets) 29 | { 30 | for(int num : bucket) 31 | { 32 | array[index++] = num; 33 | } 34 | } 35 | } 36 | //distributing elements 37 | private static int hash(int num, int bucketSize) 38 | { 39 | return num/bucketSize; 40 | } 41 | public static void main(String args[]) 42 | { 43 | //array to be sort 44 | int[] array = {22, 45, 12, 8, 10, 6, 72, 81, 33, 18, 50, 14, 55, 0, 12, 55}; 45 | System.out.println("Unsorted Array: " + Arrays.toString(array)); 46 | //calling the user-defined method to sort the array 47 | binSort(array, 10); 48 | System.out.println("Sorted Array: " + Arrays.toString(array)); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /JAVA/DYNAMIC_PROGRAMMING/ UniquePaths.java: -------------------------------------------------------------------------------- 1 | 2 | There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. 3 | 4 | Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner. 5 | 6 | The test cases are generated so that the answer will be less than or equal to 2 * 109. 7 | 8 | 9 | ## Solution 10 | 11 | 12 | class Solution { 13 | public int uniquePaths(int m, int n) { 14 | int[][] paths = new int[m][n]; 15 | for (int i = 0; i < m; i ++){ 16 | paths[i][0] = 1; 17 | } 18 | for (int j = 0; j < n; j ++){ 19 | paths[0][j] = 1; 20 | } 21 | for (int i = 1; i < m ; i ++){ 22 | for (int j = 1; j < n; j ++){ 23 | paths[i][j] = paths[i-1][j] + paths[i][j-1]; 24 | } 25 | } 26 | return paths[m-1][n-1]; 27 | } 28 | } -------------------------------------------------------------------------------- /JAVA/DYNAMIC_PROGRAMMING/House-robber.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class TUF{ 3 | static long solve(ArrayList arr){ 4 | int n = arr.size(); 5 | long prev = arr.get(0); 6 | long prev2 =0; 7 | 8 | for(int i=1; i1) 11 | pick += prev2; 12 | long nonPick = 0 + prev; 13 | 14 | long cur_i = Math.max(pick, nonPick); 15 | prev2 = prev; 16 | prev= cur_i; 17 | 18 | } 19 | return prev; 20 | } 21 | 22 | static long robStreet(int n, ArrayList arr){ 23 | ArrayList arr1=new ArrayList<>(); 24 | ArrayList arr2=new ArrayList<>(); 25 | 26 | if(n==1) 27 | return arr.get(0); 28 | 29 | for(int i=0; i arr=new ArrayList<>(); 45 | arr.add(1); 46 | arr.add(5); 47 | arr.add(1); 48 | arr.add(2); 49 | arr.add(6); 50 | int n=arr.size(); 51 | System.out.println(robStreet(n,arr)); 52 | 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /JAVA/DYNAMIC_PROGRAMMING/IntegerBreak.java: -------------------------------------------------------------------------------- 1 | Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers. 2 | 3 | Return the maximum product you can get. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: n = 2 10 | Output: 1 11 | Explanation: 2 = 1 + 1, 1 × 1 = 1. 12 | Example 2: 13 | 14 | Input: n = 10 15 | Output: 36 16 | Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36. 17 | 18 | ## Solution 19 | 20 | public class Solution { 21 | public int integerBreak(int n) { 22 | if (n == 2) return 1; 23 | if (n == 3) return 2; 24 | 25 | int[] dp = new int[n + 1]; 26 | dp[2] = 2; 27 | dp[3] = 3; 28 | 29 | for (int i = 4; i <= n; i++) { 30 | for (int j = 1; j <= i / 2; j++) { 31 | dp[i] = Math.max(dp[i], dp[j] * dp[i - j]); 32 | } 33 | } 34 | 35 | return dp[n]; 36 | } 37 | } -------------------------------------------------------------------------------- /JAVA/DYNAMIC_PROGRAMMING/JumpGame.java: -------------------------------------------------------------------------------- 1 | 2 | You are given an integer array nums. You are initially positioned at the arrays first index, and each 3 | element in the array represents your maximum jump length at that position. 4 | Return true if you can reach the last index, or false otherwise. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: nums = [2,3,1,1,4] 11 | Output: true 12 | Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. 13 | Example 2: 14 | 15 | Input: nums = [3,2,1,0,4] 16 | Output: false 17 | Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. 18 | 19 | ## Solution 20 | 21 | 22 | public class Solution { 23 | public boolean canJump(int[] nums) { 24 | int maxReach = 0; 25 | 26 | for (int i = 0; i < nums.length; i++) { 27 | if (i > maxReach) { 28 | return false; 29 | } 30 | 31 | maxReach = Math.max(maxReach, i + nums[i]); 32 | 33 | if (maxReach >= nums.length - 1) { 34 | return true; 35 | } 36 | } 37 | 38 | return true; 39 | } 40 | } -------------------------------------------------------------------------------- /JAVA/DYNAMIC_PROGRAMMING/MaximumProductSubarray.java: -------------------------------------------------------------------------------- 1 | Given an integer array nums, find a subarray that has the largest product, and return the product. 2 | 3 | The test cases are generated so that the answer will fit in a 32-bit integer. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: nums = [2,3,-2,4] 10 | Output: 6 11 | Explanation: [2,3] has the largest product 6. 12 | Example 2: 13 | 14 | Input: nums = [-2,0,-1] 15 | Output: 0 16 | Explanation: The result cannot be 2, because [-2,-1] is not a subarray. 17 | 18 | 19 | ## Solution 20 | 21 | 22 | class Solution { 23 | public int maxProduct(int[] A) { 24 | int n = A.length; 25 | int r = A[0]; 26 | 27 | int imax = r, imin = r; 28 | for (int i = 1; i < n; i++) { 29 | 30 | if (A[i] < 0) { 31 | int temp = imax; 32 | imax = imin; 33 | imin = temp; 34 | } 35 | 36 | imax = Math.max(A[i], imax * A[i]); 37 | imin = Math.min(A[i], imin * A[i]); 38 | 39 | r = Math.max(r, imax); 40 | } 41 | return r; 42 | } 43 | } -------------------------------------------------------------------------------- /JAVA/DYNAMIC_PROGRAMMING/MaximumSubarray.java: -------------------------------------------------------------------------------- 1 | Given an integer array nums, find the subarray with the largest sum, and return its sum. 2 | 3 | Example 1: 4 | 5 | Input: nums = [-2,1,-3,4,-1,2,1,-5,4] 6 | Output: 6 7 | Explanation: The subarray [4,-1,2,1] has the largest sum 6. 8 | Example 2: 9 | 10 | Input: nums = [1] 11 | Output: 1 12 | Explanation: The subarray [1] has the largest sum 1. 13 | 14 | ## Solution 15 | 16 | class Solution { 17 | public int maxSubArray(int[] nums) { 18 | int sum = 0; 19 | int ans = Integer.MIN_VALUE; 20 | for(final int val :nums){ 21 | sum = Math.max(val, val+sum); 22 | ans = Math.max(ans , sum); 23 | } 24 | return ans; 25 | 26 | } 27 | } -------------------------------------------------------------------------------- /JAVA/DoublyLinkedList.java: -------------------------------------------------------------------------------- 1 | public class DoublyLinkedList { 2 | 3 | //Represent a node of the doubly linked list 4 | 5 | class Node{ 6 | int data; 7 | Node previous; 8 | Node next; 9 | 10 | public Node(int data) { 11 | this.data = data; 12 | } 13 | } 14 | 15 | //Represent the head and tail of the doubly linked list 16 | Node head, tail = null; 17 | 18 | //addNode() will add a node to the list 19 | public void addNode(int data) { 20 | //Create a new node 21 | Node newNode = new Node(data); 22 | 23 | //If list is empty 24 | if(head == null) { 25 | //Both head and tail will point to newNode 26 | head = tail = newNode; 27 | //head's previous will point to null 28 | head.previous = null; 29 | //tail's next will point to null, as it is the last node of the list 30 | tail.next = null; 31 | } 32 | else { 33 | //newNode will be added after tail such that tail's next will point to newNode 34 | tail.next = newNode; 35 | //newNode's previous will point to tail 36 | newNode.previous = tail; 37 | //newNode will become new tail 38 | tail = newNode; 39 | //As it is last node, tail's next will point to null 40 | tail.next = null; 41 | } 42 | } 43 | 44 | //display() will print out the nodes of the list 45 | public void display() { 46 | //Node current will point to head 47 | Node current = head; 48 | if(head == null) { 49 | System.out.println("List is empty"); 50 | return; 51 | } 52 | System.out.println("Nodes of doubly linked list: "); 53 | while(current != null) { 54 | //Prints each node by incrementing the pointer. 55 | 56 | System.out.print(current.data + " "); 57 | current = current.next; 58 | } 59 | } 60 | 61 | public static void main(String[] args) { 62 | 63 | DoublyLinkedList dList = new DoublyLinkedList(); 64 | //Add nodes to the list 65 | dList.addNode(1); 66 | dList.addNode(2); 67 | dList.addNode(3); 68 | dList.addNode(4); 69 | dList.addNode(5); 70 | 71 | //Displays the nodes present in the list 72 | dList.display(); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /JAVA/LINKEDLIST/DeleteNode.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class Node { 3 | int num; 4 | Node next; 5 | Node(int a) { 6 | num = a; 7 | next = null; 8 | } 9 | } 10 | class DeleteNode{ 11 | //function to insert node at the end of the list 12 | static Node insertNode(Node head,int val) { 13 | Node newNode = new Node(val); 14 | if(head == null) { 15 | head = newNode; 16 | return head; 17 | } 18 | Node temp = head; 19 | while(temp.next != null) temp = temp.next; 20 | temp.next = newNode; 21 | return head; 22 | } 23 | //function to get reference of the node to delete 24 | static Node getNode(Node head,int val) { 25 | if(head==null) 26 | return null; 27 | while(head.num != val) head = head.next; 28 | 29 | return head; 30 | } 31 | //delete function as per the question 32 | static void deleteNode(Node t) { 33 | if(t==null) 34 | return; 35 | t.num = t.next.num; 36 | t.next = t.next.next; 37 | return; 38 | } 39 | //printing the list function 40 | static void printList(Node head) { 41 | if(head==null) 42 | return; 43 | while(head.next!=null ) { 44 | System.out.print(head.num+"->"); 45 | head = head.next; 46 | } 47 | System.out.println(head.num); 48 | } 49 | 50 | public static void main(String args[]) { 51 | Node head = null; 52 | //inserting node 53 | head=insertNode(head,1); 54 | head=insertNode(head,4); 55 | head=insertNode(head,2); 56 | head=insertNode(head,3); 57 | //printing given list 58 | System.out.println("Given Linked List: "); 59 | printList(head); 60 | Node t = getNode(head,2); 61 | //delete node 62 | deleteNode(t); 63 | //list after deletion operation 64 | System.out.println("Linked List after deletion: "); 65 | printList(head); 66 | } 67 | } -------------------------------------------------------------------------------- /JAVA/LINKEDLIST/LinkedList.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | class LinkedList { 4 | 5 | 6 | Node head; 7 | 8 | 9 | class Node { 10 | int data; 11 | Node next; 12 | 13 | Node(int d) 14 | { 15 | data = d; 16 | next = null; 17 | } 18 | } 19 | 20 | // Inserting node at the front 21 | public void insertfront(int data) 22 | { 23 | // Allocating and inserting the data in that node 24 | Node new_node = new Node(data); 25 | 26 | // Make the next of the newly allocated node to be 27 | // the head 28 | new_node.next = head; 29 | 30 | // Now make the head to be the newly allocated node 31 | head = new_node; 32 | } 33 | 34 | // Printing the List 35 | public void print() 36 | { 37 | Node temp = head; 38 | while (temp != null) { 39 | System.out.print(temp.data + " "); 40 | temp = temp.next; 41 | } 42 | } 43 | 44 | public static void main(String args[]) 45 | { 46 | // create a linkedlist 47 | LinkedList l = new LinkedList(); 48 | 49 | // insert elements at the front 50 | l.insertfront(6); 51 | l.insertfront(5); 52 | l.insertfront(8); 53 | l.insertfront(9); 54 | 55 | // print the linkedlist 56 | l.print(); 57 | } 58 | } 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /JAVA/LinkedList.java: -------------------------------------------------------------------------------- 1 | // Linked list implementation in Java 2 | 3 | class LinkedList { 4 | // Creating a node 5 | Node head; 6 | 7 | static class Node { 8 | int value; 9 | Node next; 10 | 11 | Node(int d) { 12 | value = d; 13 | next = null; 14 | } 15 | } 16 | 17 | public static void main(String[] args) { 18 | LinkedList linkedList = new LinkedList(); 19 | 20 | // Assign value values 21 | linkedList.head = new Node(1); 22 | Node second = new Node(2); 23 | Node third = new Node(3); 24 | 25 | // Connect nodess 26 | linkedList.head.next = second; 27 | second.next = third; 28 | 29 | // printing node-value 30 | while (linkedList.head != null) { 31 | System.out.print(linkedList.head.value + " "); 32 | linkedList.head = linkedList.head.next; 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /JAVA/LinkedList/LinkedListPailendrom.java: -------------------------------------------------------------------------------- 1 | class LinkedList { 2 | public class Node{ 3 | int data; 4 | Node next; 5 | Node(int data) 6 | { 7 | this.data=data; 8 | this.next=null; 9 | } 10 | } 11 | public static Node head; 12 | public static Node tail; 13 | public static int size; 14 | public void print() 15 | { 16 | if(head==null) 17 | { 18 | System.out.println("List is Empty"); 19 | return; 20 | } 21 | 22 | Node temp=head; 23 | while(temp!=null) 24 | { 25 | System.out.print(temp.data+"->"); 26 | temp=temp.next; 27 | } 28 | System.out.println("null"); 29 | } 30 | public void addFirst(int data) 31 | { 32 | Node newNode=new Node(data); 33 | if(head==null) 34 | { 35 | head=tail=newNode; 36 | size++; 37 | return; 38 | } 39 | newNode.next=head; 40 | head=newNode; 41 | size++; 42 | } 43 | public void addLast(int data) 44 | { 45 | Node newNode=new Node(data); 46 | if(head==null) 47 | { 48 | head=tail=newNode; 49 | size++; 50 | return; 51 | } 52 | tail.next=newNode; 53 | tail=newNode; 54 | size++; 55 | } 56 | public void addmid(int idx,int data) 57 | { 58 | if(idx==0) 59 | { 60 | addFirst(data); 61 | return; 62 | } 63 | 64 | Node newNode=new Node(data); 65 | Node temp=head; 66 | int i=0; 67 | while(i mid){ 19 | low = midIndex + 1; 20 | } 21 | } 22 | 23 | return -1; 24 | } 25 | 26 | public static void main(String args[]) 27 | { 28 | int[] array = {2,4,5,6,8,11,14}; 29 | 30 | System.out.println("The location of number in Array:"+binarySearch(array, 11)); 31 | // 5 32 | System.out.println("The location of number in Array:"+binarySearch(array, 3)); 33 | //-1 i.e the array doesnt contain that number. 34 | 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /JAVA/SEARCHING_ALGORITHM/linear-search.java: -------------------------------------------------------------------------------- 1 | // Linear Search in Java 2 | 3 | class LinearSearch { 4 | public static int linearSearch(int array[], int x) { 5 | int n = array.length; 6 | 7 | // Going through array sequencially 8 | for (int i = 0; i < n; i++) { 9 | if (array[i] == x) 10 | return i; 11 | } 12 | return -1; 13 | } 14 | 15 | public static void main(String args[]) { 16 | int array[] = { 2, 4, 0, 1, 9 }; 17 | int x = 1; 18 | 19 | int result = linearSearch(array, x); 20 | 21 | if (result == -1) 22 | System.out.print("Element not found"); 23 | else 24 | System.out.print("Element found at index: " + result); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /JAVA/Treap_in_Java.java: -------------------------------------------------------------------------------- 1 | import java.util.Random; 2 | 3 | class Node { 4 | int key; 5 | int priority; 6 | Node left, right; 7 | 8 | Node(int key) { 9 | this.key = key; 10 | this.priority = new Random().nextInt(100); // Assign a random priority 11 | this.left = this.right = null; 12 | } 13 | } 14 | 15 | public class Treap { 16 | Node root; 17 | 18 | Node rotateRight(Node y) { 19 | Node x = y.left; 20 | Node T2 = x.right; 21 | 22 | x.right = y; 23 | y.left = T2; 24 | 25 | return x; 26 | } 27 | 28 | Node rotateLeft(Node x) { 29 | Node y = x.right; 30 | Node T2 = y.left; 31 | 32 | y.left = x; 33 | x.right = T2; 34 | 35 | return y; 36 | } 37 | 38 | Node insert(Node root, int key) { 39 | if (root == null) 40 | return new Node(key); 41 | 42 | if (key <= root.key) { 43 | root.left = insert(root.left, key); 44 | 45 | if (root.left.priority > root.priority) 46 | root = rotateRight(root); 47 | } else { 48 | root.right = insert(root.right, key); 49 | 50 | if (root.right.priority > root.priority) 51 | root = rotateLeft(root); 52 | } 53 | 54 | return root; 55 | } 56 | 57 | void inorder(Node root) { 58 | if (root != null) { 59 | inorder(root.left); 60 | System.out.println("Key: " + root.key + ", Priority: " + root.priority); 61 | inorder(root.right); 62 | } 63 | } 64 | 65 | public static void main(String[] args) { 66 | Treap treap = new Treap(); 67 | 68 | // Insert keys with random priorities 69 | treap.root = treap.insert(treap.root, 10); 70 | treap.root = treap.insert(treap.root, 20); 71 | treap.root = treap.insert(treap.root, 5); 72 | 73 | // Print inorder traversal 74 | treap.inorder(treap.root); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /JavaScript/TelephoneNumberValidator: -------------------------------------------------------------------------------- 1 | function telephoneCheck(str) { 2 | let phoneFilter = /^(1 )?[\S ]?(\d{3}|\(\d{3}\))[\- ]?\d{3}[\- ]?\d{4}$/ 3 | 4 | let regex = /^([1]\s?)?(\([0-9]{3}\)|[0-9]{3})(\s|-)?[0-9]{3}(\s|-)?[0-9]{4}$/g 5 | 6 | 7 | 8 | let strFilter = str.replace(/[^0-9]/g, '') 9 | console.log(strFilter) 10 | 11 | if(strFilter.length === 10 && 12 | str.match(regex)) { 13 | console.log('true') 14 | return true 15 | } else if(strFilter.length === 11 && 16 | strFilter.slice(0,1) === '1' && 17 | str.match(regex)) { 18 | console.log('true') 19 | 20 | return true 21 | } else { 22 | console.log('false') 23 | return false 24 | } 25 | 26 | } 27 | 28 | //should be true 29 | telephoneCheck("1(555)555-5555") //true 30 | telephoneCheck("(555-555-5555") //false -------------------------------------------------------------------------------- /JavaScript/bookmark_manager/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Bookmark Manager 7 | 8 | 9 | 10 | 11 |
12 |

Bookmark Manager

13 | 14 |
15 | 21 | 26 |
27 | 28 |
29 | 30 |
31 |
32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /JavaScript/bookmark_manager/script.js: -------------------------------------------------------------------------------- 1 | // Select elements 2 | const bookmarkForm = document.getElementById('bookmarkForm'); 3 | const bookmarkUrl = document.getElementById('bookmarkUrl'); 4 | const bookmarkList = document.getElementById('bookmarkList'); 5 | 6 | // Retrieve bookmarks from localStorage 7 | let bookmarks = JSON.parse(localStorage.getItem('bookmarks')) || []; 8 | 9 | // Function to display bookmarks 10 | function displayBookmarks() { 11 | bookmarkList.innerHTML = ''; 12 | bookmarks.forEach((bookmark, index) => { 13 | bookmarkList.innerHTML += ` 14 |
15 | ${bookmark} 16 | 17 |
18 | `; 19 | }); 20 | } 21 | 22 | // Function to add a new bookmark 23 | bookmarkForm.addEventListener('submit', (e) => { 24 | e.preventDefault(); 25 | const url = bookmarkUrl.value; 26 | 27 | // Add bookmark and save to localStorage 28 | bookmarks.push(url); 29 | localStorage.setItem('bookmarks', JSON.stringify(bookmarks)); 30 | 31 | // Clear input and update the list 32 | bookmarkUrl.value = ''; 33 | displayBookmarks(); 34 | }); 35 | 36 | // Function to delete a bookmark 37 | function deleteBookmark(index) { 38 | bookmarks.splice(index, 1); 39 | localStorage.setItem('bookmarks', JSON.stringify(bookmarks)); 40 | displayBookmarks(); 41 | } 42 | 43 | // Display bookmarks on page load 44 | displayBookmarks(); 45 | -------------------------------------------------------------------------------- /JavaScript/clock.js: -------------------------------------------------------------------------------- 1 | // Get the clock element 2 | var clockElement = document.getElementById("clock"); 3 | 4 | // Set the clock 5 | function setClock() { 6 | // Get the current time 7 | var now = new Date(); 8 | 9 | // Get the hours, minutes, and seconds 10 | var hours = now.getHours(); 11 | var minutes = now.getMinutes(); 12 | var seconds = now.getSeconds(); 13 | 14 | // Format the time 15 | var time = `${hours}:${minutes}:${seconds}`; 16 | 17 | // Update the clock element 18 | clockElement.innerHTML = time; 19 | } 20 | 21 | // Set the clock every second 22 | setInterval(setClock, 1000); 23 | -------------------------------------------------------------------------------- /JavaScript/gradient-generator/README.md: -------------------------------------------------------------------------------- 1 | # Gradient Generator 2 | 3 | This is a web app that helps you generate random gradients that you can use in your CSS projects. 4 | 5 | 6 | 7 | ![Screenshoots](https://raw.githubusercontent.com/yasir2002/gradient-generator/main/img/Untitled%20design%20(3).png) 8 | 9 | ## Technologies Used 10 | ![HTML5](https://img.shields.io/badge/html5-%23E34F26.svg?style=for-the-badge&logo=html5&logoColor=white) 11 | ![CSS3](https://img.shields.io/badge/css3-%231572B6.svg?style=for-the-badge&logo=css3&logoColor=white) 12 | ![JavaScript](https://img.shields.io/badge/javascript-%23323330.svg?style=for-the-badge&logo=javascript&logoColor=%23F7DF1E) 13 | ![Bootstrap](https://img.shields.io/badge/bootstrap-%23563D7C.svg?style=for-the-badge&logo=bootstrap&logoColor=white) 14 | 15 | 16 | ## How to Use 17 | 1. Visit the Gradient Generator website. 18 | 2. Click on the "Generate" button to generate a new gradient. 19 | 3. Use the "Copy" button to copy the CSS code for the generated gradient. 20 | 4. Paste the CSS code into your own project to use the gradient. 21 | 22 | ## Features 23 | * Generate a random gradient with the click of a button. 24 | * Copy the CSS code for the generated gradient with one click. 25 | * Customizable gradient styles, including the direction and color stops. 26 | * Mobile responsive design for use on all devices. 27 | 28 | ## Credits 29 | This web app was created by [Yasir Nawaz](https://yasir2002.github.io/portfolio/) 30 | -------------------------------------------------------------------------------- /JavaScript/gradient-generator/css/style.css: -------------------------------------------------------------------------------- 1 | @import url('https://fonts.googleapis.com/css2?family=Righteous&display=swap'); 2 | @import url('https://fonts.googleapis.com/css2?family=Bad+Script&display=swap'); 3 | 4 | body { 5 | transition: background 1s ease-in-out; 6 | margin: 1px !important; 7 | background-color: #333333 !important; 8 | } 9 | .centerContent { 10 | position: absolute; 11 | top: 50%; 12 | left: 50%; 13 | transform: translate(-50%, -50%); 14 | text-align: center; 15 | background-color: #00000081; 16 | padding: 30px; 17 | border-radius: 20px; 18 | color: white; 19 | width: 60%; 20 | transition: .8s all; 21 | cursor: pointer; 22 | } 23 | .centerContent:hover{ 24 | box-shadow: 0px 0px 20px 0px #333333; 25 | 26 | } 27 | .colorPicker{ 28 | width: 50px !important; 29 | height: 50px; 30 | margin: 10px 10px; 31 | } 32 | 33 | 34 | .centerContent h1{ 35 | font-size: 50px; 36 | font-family: 'Righteous', cursive; 37 | } 38 | .btn:active, 39 | .btn:focus { 40 | box-shadow: none; 41 | outline: none; 42 | } 43 | .copy-link { 44 | --height: 36px; 45 | 46 | display: flex; 47 | margin-top: 20px; 48 | 49 | } 50 | 51 | .copy-link-input { 52 | flex-grow: 1; 53 | padding: 0 18px; 54 | font-size: 14px; 55 | border: 1px solid #cccccc; 56 | border-right: none; 57 | outline: none; 58 | border-top-left-radius: 50rem ; 59 | border-bottom-left-radius: 50rem ; 60 | background-color: rgba(255, 255, 255, 0); 61 | color: white; 62 | transition: .5s all; 63 | } 64 | 65 | .copy-link-input:hover { 66 | background: #eeeeee; 67 | color: #333333; 68 | } 69 | 70 | .copy-link-button { 71 | flex-shrink: 0; 72 | width: var(--height); 73 | height: var(--height); 74 | display: flex; 75 | align-items: center; 76 | justify-content: center; 77 | background: #dddddd; 78 | color: #333333; 79 | outline: none; 80 | border: 1px solid #cccccc; 81 | cursor: pointer; 82 | border-top-right-radius: 50rem ; 83 | border-bottom-right-radius: 50rem ; 84 | } 85 | 86 | .copy-link-button:hover { 87 | background: #cccccc; 88 | } 89 | .credits{ 90 | position: absolute; 91 | bottom: 0; 92 | right: 45%; 93 | font-family: 'Bad Script', cursive; 94 | } 95 | .credits { 96 | animation: move 10s linear infinite; 97 | 98 | } 99 | 100 | 101 | @keyframes move { 102 | 0% { transform: translateX(0); } 103 | 50% { transform: translateX(50%); } 104 | 100% { transform: translateX(0); } 105 | } 106 | .heartEmoji{ 107 | color: red; 108 | font-size: 20px; 109 | } 110 | .manuallGen{ 111 | margin-top: 20px; 112 | } 113 | 114 | 115 | @media screen and (max-width:768px) { 116 | .centerContent h1{ 117 | font-size: 30px; 118 | } 119 | .centerContent{ 120 | padding: 30px 10px; 121 | } 122 | .copy-link{ 123 | --height: 30px !important; 124 | } 125 | .copy-link-input{ 126 | font-size: 11px !important; 127 | } 128 | .credits{ 129 | right: 37% !important; 130 | } 131 | .btn{ 132 | font-size: 10px !important; 133 | padding: 5px 10px !important; 134 | } 135 | .centerContent p{ 136 | display: none; 137 | } 138 | .colorPicker{ 139 | height: 30px; 140 | width: 20px; 141 | } 142 | 143 | 144 | } -------------------------------------------------------------------------------- /JavaScript/gradient-generator/img/Untitled design (3).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panditakshay402/Hacktoberfest/d3cd7b4552bd0543c1b182545aecc66a1ebca038/JavaScript/gradient-generator/img/Untitled design (3).png -------------------------------------------------------------------------------- /JavaScript/gradient-generator/img/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panditakshay402/Hacktoberfest/d3cd7b4552bd0543c1b182545aecc66a1ebca038/JavaScript/gradient-generator/img/logo.png -------------------------------------------------------------------------------- /JavaScript/gradient-generator/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | Gradient Generator 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 |

Random Gradient Generator

20 |

By clicking above button a random gradient will be generated for you

21 | 22 | 23 | 29 | 30 |
31 |

Generate gradient by giving two color values

32 | 33 |
34 | 35 |
36 | 37 | 38 |
39 |

Made By Yasir Nawaz with

40 | 41 | 110 | 111 | 112 | -------------------------------------------------------------------------------- /Median of Two Sorted Arrays: -------------------------------------------------------------------------------- 1 | double findMedianSortedArrays(vector& nums1, vector& nums2) { 2 | vectorv; 3 | double ans=0; 4 | for(int i=0;i 30 | {context} 31 | 32 | 33 | Question: {input} 34 | """ 35 | ) 36 | # Linking the LLM, vector DB and the prompt 37 | docs_chain = create_stuff_documents_chain(llm, prompt) 38 | retriever = vector_store.as_retriever() 39 | retrieval_chain = create_retrieval_chain(retriever, docs_chain) 40 | return retrieval_chain 41 | 42 | # Using the retrieval chain 43 | # Example: 44 | 45 | ''' 46 | chain = create_RAG_model("your_file_here.pdf", "mistral") 47 | output = chain.invoke({"input":"What is the purpose of RAG?"}) 48 | print(output["answer"]) 49 | ''' 50 | 51 | -------------------------------------------------------------------------------- /PYTHON/Treap_in_Python.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | class Node: 4 | def __init__(self, key): 5 | self.key = key 6 | self.priority = random.randint(0, 100) # Assign a random priority 7 | self.left = None 8 | self.right = None 9 | 10 | class Treap: 11 | def __init__(self): 12 | self.root = None 13 | 14 | def rotate_right(self, y): 15 | x = y.left 16 | T2 = x.right 17 | 18 | x.right = y 19 | y.left = T2 20 | 21 | return x 22 | 23 | def rotate_left(self, x): 24 | y = x.right 25 | T2 = y.left 26 | 27 | y.left = x 28 | x.right = T2 29 | 30 | return y 31 | 32 | def insert(self, root, key): 33 | if not root: 34 | return Node(key) 35 | 36 | if key <= root.key: 37 | root.left = self.insert(root.left, key) 38 | 39 | if root.left.priority > root.priority: 40 | root = self.rotate_right(root) 41 | else: 42 | root.right = self.insert(root.right, key) 43 | 44 | if root.right.priority > root.priority: 45 | root = self.rotate_left(root) 46 | 47 | return root 48 | 49 | def inorder(self, root): 50 | if root: 51 | self.inorder(root.left) 52 | print("Key: " + str(root.key) + ", Priority: " + str(root.priority)) 53 | self.inorder(root.right) 54 | 55 | if __name__ == "__main__": 56 | treap = Treap() 57 | 58 | # Insert keys with random priorities 59 | treap.root = treap.insert(treap.root, 10) 60 | treap.root = treap.insert(treap.root, 20) 61 | treap.root = treap.insert(treap.root, 5) 62 | 63 | # Print inorder traversal 64 | treap.inorder(treap.root) 65 | -------------------------------------------------------------------------------- /PYTHON/WikiLLM.py: -------------------------------------------------------------------------------- 1 | from langchain_community.llms import Ollama 2 | from langchain_community.document_loaders import WebBaseLoader 3 | from langchain_community.embeddings import OllamaEmbeddings 4 | from langchain_community.vectorstores import FAISS 5 | from langchain_core.prompts import ChatPromptTemplate 6 | from langchain_text_splitters import RecursiveCharacterTextSplitter 7 | from langchain.chains.combine_documents import create_stuff_documents_chain 8 | from langchain.chains import create_retrieval_chain 9 | import wikipedia as wiki 10 | import os 11 | 12 | # NOTE: The following function is a RAG template written by me and wasn't copied from anywhere 13 | def create_RAG_model(url, llm): 14 | # Create the LLM (Large Language Model) 15 | llm = Ollama(model=str(llm)) 16 | # Define model used to embed the info 17 | embeddings = OllamaEmbeddings(model="nomic-embed-text") 18 | # Load the webpage 19 | loader = WebBaseLoader(str(url)) 20 | webpage = loader.load() 21 | # Split the text and embed it into the vector DB 22 | text_splitter = RecursiveCharacterTextSplitter() 23 | split = text_splitter.split_documents(webpage) 24 | if (os.path.exists("wiki_index")): 25 | vector_store = FAISS.load_local("wiki_index", allow_dangerous_deserialization=True, embeddings=embeddings) 26 | vector_store = vector_store.from_documents(split, embeddings) 27 | else: 28 | vector_store = FAISS.from_documents(split, embeddings) 29 | print("[+] Finished embedding!") 30 | vector_store.save_local("wiki_index") 31 | 32 | # Prompt generation: Giving the LLM character and purpose 33 | prompt = ChatPromptTemplate.from_template( 34 | """ 35 | Answer the following questions only based on the given context 36 | 37 | 38 | {context} 39 | 40 | 41 | Question: {input} 42 | """ 43 | ) 44 | # Linking the LLM, vector DB and the prompt 45 | docs_chain = create_stuff_documents_chain(llm, prompt) 46 | retriever = vector_store.as_retriever() 47 | retrieval_chain = create_retrieval_chain(retriever, docs_chain) 48 | return retrieval_chain 49 | 50 | number = int(input("Do you want me to:\n 1) Learn from a single article \n 2) Learn from articles of a given topic\n :")) 51 | if (number == 2): 52 | topic = input("What topic to do you want me to learn?: ") 53 | results = wiki.search(topic) 54 | for result in results: 55 | wiki_url = str("https://en.wikipedia.org/wiki/"+str(result)).replace(' ','_') 56 | chain = create_RAG_model(wiki_url, "dolphin-phi") 57 | elif (number == 1): 58 | wiki_url = input("Give me the URL of the article: ") 59 | chain = create_RAG_model(wiki_url, "dolphin-phi") 60 | 61 | print("Type 'exit' to exit") 62 | 63 | while True: 64 | query = input("Ask me a question: ") 65 | if (query == "exit"): 66 | break 67 | else: 68 | output = chain.invoke({"input":query}) 69 | print(output["answer"]) 70 | -------------------------------------------------------------------------------- /PYTHON/Wikipedia_bot.py: -------------------------------------------------------------------------------- 1 | import wikipedia as wiki # Import the library 2 | 3 | topic = input("Please enter the topic: ") 4 | results = wiki.search(topic) # Search for related articles 5 | print("[+] Found", len(results), "entries!") 6 | print("Select the article: ") 7 | for index, value in enumerate(results): # Give the user an opportunity to choose between the articles 8 | print(str(index)+ ")"+" "+str(value)) 9 | 10 | print("\n") 11 | article = int(input()) 12 | try: # Try retrieving info from the Wiki page 13 | page = wiki.page(results[article]) 14 | print(str(page.title).center(1000)) 15 | print(page.url) 16 | print(wiki.summary(results[article], sentences=1)) 17 | except DisambiguationError as e: # Workaround for the disambiguation error 18 | print("[-] An error occured!") 19 | print("URL: "+"https://en.wikipedia.org/wiki/"+str(results[article]).replace(' ', '_')) -------------------------------------------------------------------------------- /PYTHON/anti-malware.py: -------------------------------------------------------------------------------- 1 | ################################################################################# 2 | ### Author: Pyerie # 3 | ### Application: A not-so-accurate ML based anti-malware solution # 4 | ################################################################################# 5 | 6 | print("[+] Loading.... ") 7 | import customtkinter 8 | from tkinter.filedialog import * 9 | from tkinter import * 10 | import pefile 11 | import numpy as np 12 | import pandas as pd 13 | from sklearn.tree import DecisionTreeClassifier 14 | from sklearn.model_selection import train_test_split 15 | from sklearn import metrics 16 | import os 17 | 18 | 19 | 20 | dataset = pd.read_csv('database3.csv') 21 | X = dataset.drop(['legitimate'],axis=1).values 22 | 23 | y = dataset['legitimate'].values 24 | 25 | 26 | 27 | X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1) 28 | clf = DecisionTreeClassifier() 29 | 30 | 31 | y_test = y_test.reshape(-1,1) 32 | for i in range(0, 10): 33 | clf = clf.fit(X_train,y_train) 34 | res1 = clf.predict(X_test) 35 | accuracy = metrics.accuracy_score(y_test, res1) 36 | accuracy = str(accuracy)[2:4] + "%" 37 | print("Accuracy: "+accuracy) 38 | 39 | 40 | customtkinter.set_appearance_mode("dark") 41 | customtkinter.set_default_color_theme("dark-blue") 42 | 43 | 44 | window = Tk() 45 | screen_width = window.winfo_screenwidth() 46 | screen_height = window.winfo_screenheight() 47 | window.geometry(str(screen_width)+"x"+str(screen_height)) 48 | window.title("eSuraksha") 49 | window['bg'] = "#121212" 50 | def extract_features(file): 51 | features = [] 52 | 53 | 54 | 55 | try: 56 | 57 | pe_obj = pefile.PE(file, fast_load=True) 58 | except pefile.PEFormatError as error: 59 | print("Not PE file!") 60 | 61 | features.append(pe_obj.OPTIONAL_HEADER.DATA_DIRECTORY[6].Size) 62 | features.append(pe_obj.OPTIONAL_HEADER.DATA_DIRECTORY[6].VirtualAddress) 63 | features.append(pe_obj.OPTIONAL_HEADER.MajorImageVersion) 64 | features.append(pe_obj.OPTIONAL_HEADER.MajorOperatingSystemVersion) 65 | features.append(pe_obj.OPTIONAL_HEADER.DATA_DIRECTORY[0].VirtualAddress) 66 | features.append(pe_obj.OPTIONAL_HEADER.DATA_DIRECTORY[0].Size) 67 | try: 68 | features.append(pe_obj.OPTIONAL_HEADER.DATA_DIRECTORY[12].VirtualAddress) 69 | except: 70 | features.append(0) 71 | features.append(pe_obj.OPTIONAL_HEADER.DATA_DIRECTORY[2].Size) 72 | features.append(pe_obj.OPTIONAL_HEADER.MajorLinkerVersion) 73 | features.append(pe_obj.FILE_HEADER.NumberOfSections) 74 | features.append(pe_obj.OPTIONAL_HEADER.SizeOfStackReserve) 75 | features.append(pe_obj.OPTIONAL_HEADER.DllCharacteristics) 76 | features.append(pe_obj.OPTIONAL_HEADER.AddressOfEntryPoint) 77 | features.append(pe_obj.OPTIONAL_HEADER.ImageBase) 78 | 79 | 80 | 81 | 82 | 83 | 84 | return features 85 | 86 | toplevel_created = False 87 | 88 | toplevel2_created = False 89 | 90 | def single_file(): 91 | 92 | global toplevel_created 93 | global toplevel2_created 94 | global single_file_top 95 | if toplevel_created == "True": 96 | single_file_top.destroy() 97 | toplevel_created = "False" 98 | elif toplevel_created == "False": 99 | pass 100 | 101 | if toplevel2_created == "True": 102 | many_files.destroy() 103 | toplevel2_created = "False" 104 | elif toplevel2_created == "False": 105 | pass 106 | 107 | single_file_top = Toplevel(window) 108 | single_file_top.geometry("350x200") 109 | customtkinter.set_appearance_mode("dark") 110 | customtkinter.set_default_color_theme("dark-blue") 111 | single_file_top['bg'] = "#121212" 112 | single_file_top.title("Scan a single file") 113 | toplevel_created = "True" 114 | result = customtkinter.CTkLabel(single_file_top, text="Loading...") 115 | result.pack() 116 | 117 | file_path = askopenfilename() 118 | try: 119 | features_extracted = extract_features(str(file_path)) 120 | not_pe = False 121 | except UnboundLocalError as e: 122 | not_pe = True 123 | result.after(0, result.destroy) 124 | benign_l = customtkinter.CTkLabel(single_file_top, text="Not PE file!") 125 | benign_l.pack() 126 | toplevel2_created = False 127 | 128 | if not_pe != True: 129 | data_of_sample = np.array(features_extracted) 130 | data_of_sample = data_of_sample.reshape(1,-1) 131 | 132 | 133 | prediction = clf.predict(data_of_sample) 134 | 135 | 136 | if prediction == 1: 137 | result.after(0, result.destroy) 138 | 139 | malware_l = customtkinter.CTkLabel(single_file_top, fg_color="red", text="ML model detected malware!") 140 | malware_l.pack() 141 | 142 | 143 | elif prediction == 0: 144 | result.after(0, result.destroy) 145 | benign_l = customtkinter.CTkLabel(single_file_top, fg_color="green", text="No malware detected!") 146 | benign_l.pack() 147 | 148 | 149 | def scan_many(): 150 | 151 | 152 | global toplevel2_created 153 | global toplevel_created 154 | global many_files 155 | 156 | if toplevel2_created == "True": 157 | many_files.destroy() 158 | toplevel2_created = "False" 159 | elif toplevel2_created == "False": 160 | pass 161 | 162 | if toplevel_created == "True": 163 | single_file_top.destroy() 164 | toplevel_created = "False" 165 | elif toplevel_created == "False": 166 | pass 167 | 168 | many_files = Toplevel(window) 169 | many_files.geometry("350x200") 170 | customtkinter.set_appearance_mode("dark") 171 | customtkinter.set_default_color_theme("dark-blue") 172 | many_files['bg'] = "#121212" 173 | many_files.title("Scan a directory") 174 | toplevel2_created = "True" 175 | result2 = customtkinter.CTkLabel(many_files, text="Loading...") 176 | result2.pack() 177 | malware_many = [] 178 | directory = askdirectory() 179 | global extracted 180 | for root, directory, files in os.walk(str(directory)): 181 | for name_of_file in files: 182 | path = os.path.join(str(root),str(name_of_file)) 183 | 184 | formats_of_pe = [".acm" , ".ax" , ".cpl" , ".dll" , ".drv" , ".efi" , ".exe" , ".mui" , ".ocx" , ".scr" , ".sys" , ".tsp", ".bin"] 185 | for format_i in formats_of_pe: 186 | if name_of_file.endswith(format_i) == True: 187 | 188 | extracted = 1 189 | try: 190 | 191 | features_of_many = extract_features(str(path)) 192 | except UnboundLocalError as e: 193 | pass 194 | break 195 | 196 | else: 197 | extracted = 0 198 | 199 | 200 | 201 | if extracted == 1: 202 | data_for_many = np.array(features_of_many) 203 | data_for_many = data_for_many.reshape(1,-1) 204 | 205 | prediction_for_many = clf.predict(data_for_many) 206 | 207 | 208 | if prediction_for_many == 1: 209 | malware_many.append(str(path)) 210 | 211 | 212 | if len(malware_many) != 0: 213 | result2.after(0, result2.destroy) 214 | malware_label2 = customtkinter.CTkLabel(many_files,text="Malware found: ") 215 | malware_label2.pack() 216 | malware_text_box = customtkinter.CTkTextbox(many_files) 217 | for_text_box = '' 218 | 219 | for name_of_malware in malware_many: 220 | for_text_box += "".join([name_of_malware, '\n------------------------------------------']) 221 | 222 | 223 | 224 | malware_text_box.insert('0.0',for_text_box) 225 | malware_text_box.configure(state="disabled") 226 | malware_text_box.pack() 227 | 228 | 229 | 230 | 231 | elif len(malware_many) == 0: 232 | result2.after(0, result2.destroy) 233 | benign_label = customtkinter.CTkLabel(many_files,text="No malware found!") 234 | benign_label.pack() 235 | 236 | button1 = customtkinter.CTkButton(master=window, command=single_file,text="Scan a single file") 237 | button1.pack() 238 | button2 = customtkinter.CTkButton(master=window, command=scan_many, text="Scan a folder") 239 | button2.pack() 240 | 241 | window.mainloop() -------------------------------------------------------------------------------- /PYTHON/calculator.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | 3 | def button_click(number): 4 | current = entry.get() 5 | entry.delete(0, tk.END) 6 | entry.insert(tk.END, current + str(number)) 7 | 8 | def button_clear(): 9 | entry.delete(0, tk.END) 10 | 11 | 12 | def button_equal(): 13 | try: 14 | result = eval(entry.get()) 15 | entry.delete(0, tk.END) 16 | entry.insert(tk.END, result) 17 | except Exception: 18 | entry.delete(0, tk.END) 19 | entry.insert(tk.END, "Error") 20 | 21 | # Create the main window 22 | window = tk.Tk() 23 | window.title("Calculator") 24 | 25 | # Create entry widget to display the numbers and results 26 | entry = tk.Entry(window, width=30, borderwidth=5) 27 | entry.grid(row=0, column=0, columnspan=4, padx=10, pady=10) 28 | 29 | # Define the buttons 30 | buttons = [ 31 | ("7", 1, 0), 32 | ("8", 1, 1), 33 | ("9", 1, 2), 34 | ("/", 1, 3), 35 | ("4", 2, 0), 36 | ("5", 2, 1), 37 | ("6", 2, 2), 38 | ("*", 2, 3), 39 | ("1", 3, 0), 40 | ("2", 3, 1), 41 | ("3", 3, 2), 42 | ("-", 3, 3), 43 | ("0", 4, 0), 44 | (".", 4, 1), 45 | ("=", 4, 2), 46 | ("+", 4, 3), 47 | ] 48 | 49 | # Create the buttons and assign their respective functions 50 | for button_text, row, col in buttons: 51 | button = tk.Button(window, text=button_text, padx=20, pady=10, command=lambda text=button_text: button_click(text)) 52 | button.grid(row=row, column=col) 53 | 54 | # Create the clear button 55 | clear_button = tk.Button(window, text="Clear", padx=20, pady=10, command=button_clear) 56 | clear_button.grid(row=5, column=0, columnspan=2) 57 | 58 | 59 | # Create the equal button 60 | equal_button = tk.Button(window, text="=", padx=20, pady=10, command=button_equal) 61 | equal_button.grid(row=5, column=2, columnspan=2) 62 | 63 | # Start the main loop 64 | window.mainloop() 65 | -------------------------------------------------------------------------------- /PYTHON/editor.ui: -------------------------------------------------------------------------------- 1 | 2 | 3 | MainWindow 4 | 5 | 6 | 7 | 0 8 | 0 9 | 896 10 | 618 11 | 12 | 13 | 14 | MainWindow 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | Tahoma 23 | 24 | 25 | 26 | QPlainTextEdit::NoWrap 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 0 36 | 0 37 | 896 38 | 21 39 | 40 | 41 | 42 | 43 | Menu 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | View 52 | 53 | 54 | 55 | Text Size 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | Open 74 | 75 | 76 | 77 | 78 | Save 79 | 80 | 81 | 82 | 83 | Save as 84 | 85 | 86 | 87 | 88 | Exit 89 | 90 | 91 | 92 | 93 | 10pt 94 | 95 | 96 | 97 | 98 | 12pt 99 | 100 | 101 | 102 | 103 | 14pt 104 | 105 | 106 | 107 | 108 | 16pt 109 | 110 | 111 | 112 | 113 | 18pt 114 | 115 | 116 | 117 | 118 | 24pt 119 | 120 | 121 | 122 | 123 | 30pt 124 | 125 | 126 | 127 | 128 | 129 | 130 | -------------------------------------------------------------------------------- /PYTHON/even.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panditakshay402/Hacktoberfest/d3cd7b4552bd0543c1b182545aecc66a1ebca038/PYTHON/even.txt -------------------------------------------------------------------------------- /PYTHON/file.py: -------------------------------------------------------------------------------- 1 | '''WAP to to store the inputs from users. You will store (Product name, brand, price, quantity, Total) ''' 2 | basepath="product.txt" 3 | mode="w" 4 | myfile=open(basepath,mode) 5 | product_name=input("Enter the product name : ") 6 | brand=input("Enter the brand : ") 7 | price=int(input("Enter the price : ")) 8 | quantity=int(input("Enter the quantity : ")) 9 | total=price*quantity 10 | myfile.write(f'Product name = {product_name}\n') 11 | myfile.write(f'Brand name = {brand}\n') 12 | myfile.write(f'Price = {price}\n') 13 | myfile.write(f'Quantity = {quantity}\n') 14 | myfile.write(f'Total = {total}\n\n') 15 | myfile.close() -------------------------------------------------------------------------------- /PYTHON/file2.py: -------------------------------------------------------------------------------- 1 | ''''WAP to create the file to store even numbers from user''' 2 | myfile=open(r'numbers.txt','w') 3 | jk=int(input("Enter the limit of numbers : ")) 4 | for i in range(jk): 5 | val=int(input("Enter the no = ")) 6 | myfile.write(str(val)) 7 | myfile.write(" ") 8 | 9 | myfile.close() 10 | myfile=open(r'numbers.txt','r') 11 | print(myfile.read()) 12 | 13 | file1=open(r'even.txt','w') 14 | file2=open(r'odd.txt','w') 15 | data=myfile.read() 16 | List=data.split(' ') 17 | print(List) 18 | for line in List: 19 | # if(int(line)%2==0): 20 | # file1.write(f'{line}\n') 21 | # else: 22 | # file2.write(f'{line}\n') 23 | print(line , end=' ') 24 | 25 | myfile.close() 26 | 27 | 28 | -------------------------------------------------------------------------------- /PYTHON/file3.py: -------------------------------------------------------------------------------- 1 | n=5 2 | for i in range(n,0,-1): 3 | for j in range(i): 4 | print('*',end='') 5 | print() -------------------------------------------------------------------------------- /PYTHON/firstfile.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panditakshay402/Hacktoberfest/d3cd7b4552bd0543c1b182545aecc66a1ebca038/PYTHON/firstfile.txt -------------------------------------------------------------------------------- /PYTHON/hello.txt: -------------------------------------------------------------------------------- 1 | paragraph -------------------------------------------------------------------------------- /PYTHON/image_detection.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | from ultralytics import YOLO 3 | import os 4 | # Load a pretrained YOLOv8n model 5 | model = YOLO('yolov8n.pt') 6 | #THIS IS FOR IMAAAAAAGEEEEEEEEEE DETECTION !! 7 | img_count = 0 8 | image_paths = [] 9 | image_directory = "F:\\GFG\\Images\\" #enter the path for image folder here ! 10 | for filename in os.listdir(image_directory): 11 | if filename.endswith(".jpg") or filename.endswith(".JPG") or filename.endswith(".jpeg") or filename.endswith(".png"): 12 | image_paths.append(os.path.join(image_directory, filename)) 13 | img_count += 1 14 | # Now, image_paths contains the paths of the images 15 | print(f'Total number of images in the folder {image_directory} : ',img_count) 16 | # # For example, if you have a directory with multiple image files: 17 | # image path example : 'F:\\GFG\\Images\\img3.jpg' 18 | count = 0 19 | for i in image_paths: 20 | results = model(i) # results list 21 | count += 1 22 | # Show the results 23 | for r in results: 24 | im_array = r.plot() # plot a BGR numpy array of predictions 25 | im = Image.fromarray(im_array[..., ::-1]) # RGB PIL image 26 | im.show() # show image 27 | im.save(f'F:\\GFG\\static\\detection_result\\{count}.jpg') # save image -------------------------------------------------------------------------------- /PYTHON/k_means_clustering.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | from sklearn.datasets import make_blobs 4 | 5 | X,y = make_blobs(n_samples = 500,n_features = 2,centers = 3,random_state = 23) 6 | 7 | fig = plt.figure(0) 8 | plt.grid(True) 9 | plt.scatter(X[:,0],X[:,1]) 10 | plt.show() 11 | 12 | k = 3 13 | 14 | clusters = {} 15 | np.random.seed(23) 16 | 17 | for idx in range(k): 18 | center = 2*(2*np.random.random((X.shape[1],))-1) 19 | points = [] 20 | cluster = { 21 | 'center' : center, 22 | 'points' : [] 23 | } 24 | 25 | clusters[idx] = cluster 26 | 27 | clusters 28 | 29 | plt.scatter(X[:,0],X[:,1]) 30 | plt.grid(True) 31 | for i in clusters: 32 | center = clusters[i]['center'] 33 | plt.scatter(center[0],center[1],marker = '*',c = 'red') 34 | plt.show() 35 | 36 | 37 | def distance(p1,p2): 38 | return np.sqrt(np.sum((p1-p2)**2)) 39 | 40 | def assign_clusters(X, clusters): 41 | for idx in range(X.shape[0]): 42 | dist = [] 43 | 44 | curr_x = X[idx] 45 | 46 | for i in range(k): 47 | dis = distance(curr_x,clusters[i]['center']) 48 | dist.append(dis) 49 | curr_cluster = np.argmin(dist) 50 | clusters[curr_cluster]['points'].append(curr_x) 51 | return clusters 52 | 53 | #Implementing the M-Step 54 | def update_clusters(X, clusters): 55 | for i in range(k): 56 | points = np.array(clusters[i]['points']) 57 | if points.shape[0] > 0: 58 | new_center = points.mean(axis =0) 59 | clusters[i]['center'] = new_center 60 | 61 | clusters[i]['points'] = [] 62 | return clusters 63 | 64 | def pred_cluster(X, clusters): 65 | pred = [] 66 | for i in range(X.shape[0]): 67 | dist = [] 68 | for j in range(k): 69 | dist.append(distance(X[i],clusters[j]['center'])) 70 | pred.append(np.argmin(dist)) 71 | return pred 72 | 73 | clusters = assign_clusters(X,clusters) 74 | clusters = update_clusters(X,clusters) 75 | pred = pred_cluster(X,clusters) 76 | 77 | plt.scatter(X[:,0],X[:,1],c = pred) 78 | for i in clusters: 79 | center = clusters[i]['center'] 80 | plt.scatter(center[0],center[1],marker = '^',c = 'red') 81 | plt.show() 82 | -------------------------------------------------------------------------------- /PYTHON/linear-search.py: -------------------------------------------------------------------------------- 1 | # Linear Search in Python 2 | 3 | 4 | def linearSearch(array, n, x): 5 | 6 | # Going through array sequencially 7 | for i in range(0, n): 8 | if (array[i] == x): 9 | return i 10 | return -1 11 | 12 | 13 | array = [2, 4, 0, 1, 9] 14 | x = 1 15 | n = len(array) 16 | result = linearSearch(array, n, x) 17 | if(result == -1): 18 | print("Element not found") 19 | else: 20 | print("Element found at index: ", result) 21 | -------------------------------------------------------------------------------- /PYTHON/merge_sort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of MergeSort 2 | def mergeSort(arr): 3 | if len(arr) > 1: 4 | 5 | # Finding the mid of the array 6 | mid = len(arr)//2 7 | 8 | # Dividing the array elements 9 | L = arr[:mid] 10 | 11 | # Into 2 halves 12 | R = arr[mid:] 13 | 14 | # Sorting the first half 15 | mergeSort(L) 16 | 17 | # Sorting the second half 18 | mergeSort(R) 19 | 20 | i = j = k = 0 21 | 22 | # Copy data to temp arrays L[] and R[] 23 | while i < len(L) and j < len(R): 24 | if L[i] <= R[j]: 25 | arr[k] = L[i] 26 | i += 1 27 | else: 28 | arr[k] = R[j] 29 | j += 1 30 | k += 1 31 | 32 | # Checking if any element was left 33 | while i < len(L): 34 | arr[k] = L[i] 35 | i += 1 36 | k += 1 37 | 38 | while j < len(R): 39 | arr[k] = R[j] 40 | j += 1 41 | k += 1 42 | 43 | 44 | # Code to print the list 45 | def printList(arr): 46 | for i in range(len(arr)): 47 | print(arr[i], end=" ") 48 | print() 49 | 50 | 51 | # Driver Code 52 | if __name__ == '__main__': 53 | arr = [12, 11, 13, 5, 6, 7] 54 | print("Given array is") 55 | printList(arr) 56 | mergeSort(arr) 57 | print("\nSorted array is ") 58 | printList(arr) 59 | -------------------------------------------------------------------------------- /PYTHON/numbers.txt: -------------------------------------------------------------------------------- 1 | 2 -------------------------------------------------------------------------------- /PYTHON/odd.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/panditakshay402/Hacktoberfest/d3cd7b4552bd0543c1b182545aecc66a1ebca038/PYTHON/odd.txt -------------------------------------------------------------------------------- /PYTHON/password_protected_pdf.py: -------------------------------------------------------------------------------- 1 | from PyPDF2 import PdfFileWriter, PdfFileReader 2 | import getpass 3 | 4 | pdfwriter = PdfFileWriter() 5 | pdf = PdfFileReader("GRE-Syllabus.pdf") 6 | 7 | for page_num in range(pdf.numPages): 8 | pdfwriter.addPage(pdf.getPage(page_num)) 9 | passw = getpass.getpass(prompt='Enter Password: ') 10 | pdfwriter.encrypt(passw) 11 | with open('GRE-Syllabus.pdf','wb') as f: 12 | pdfwriter.write(f) -------------------------------------------------------------------------------- /PYTHON/pdf_merger.py: -------------------------------------------------------------------------------- 1 | from PyPDF2 import PdfFileMerger 2 | import os 3 | 4 | merger = PdfFileMerger() 5 | for items in os.listdir(): 6 | if items.endswith('.pdf'): 7 | merger.append(items) 8 | merger.write("Final_pdf.pdf") 9 | merger = PdfFileMerger() 10 | with open(originalFile, 'rb') as fin: 11 | merger.append(PdfFileReader(fin)) 12 | 13 | os.remove(originalFile) 14 | 15 | merger.close() 16 | -------------------------------------------------------------------------------- /PYTHON/product.txt: -------------------------------------------------------------------------------- 1 | Product name = Headphones 2 | Brand name = BOAT 3 | Price = 1280 4 | Quantity = 2 5 | Total = 2560 6 | 7 | -------------------------------------------------------------------------------- /PYTHON/text_editor.py: -------------------------------------------------------------------------------- 1 | #Author: Sumon Chatterjee 2 | from PyQt5.QtWidgets import * 3 | from PyQt5 import uic 4 | from PyQt5.QtGui import QFont 5 | 6 | class MyUI(QMainWindow): 7 | def __init__(self): 8 | super(MyUI, self).__init__() 9 | uic.loadUi('editor.ui',self) 10 | self.show() 11 | self.setWindowTitle("Text Editor") 12 | 13 | self.action10pt.triggered.connect(lambda: self.size(10)) 14 | self.action12pt.triggered.connect(lambda: self.size(12)) 15 | self.action14pt.triggered.connect(lambda: self.size(14)) 16 | self.action16pt.triggered.connect(lambda: self.size(16)) 17 | self.action18pt.triggered.connect(lambda: self.size(18)) 18 | self.action24pt.triggered.connect(lambda: self.size(24)) 19 | self.action30pt.triggered.connect(lambda: self.size(30)) 20 | 21 | self.actionOpen.triggered.connect(self.open_file) 22 | 23 | self.actionSave.triggered.connect(self.save_file) 24 | self.actionClose.triggered.connect(exit) 25 | 26 | def size(self,s): 27 | self.plainTextEdit.setFont(QFont("Tahoma",s)) 28 | 29 | def open_file (self): 30 | options = QFileDialog.Options() 31 | file_name, _ = QFileDialog.getOpenFileName(self,"Open File", "", "Text Files (*.txt);;Python File (*.py)",options=options) 32 | if file_name != "": 33 | with open(file_name,"r") as f: 34 | self.plainTextEdit.setPlainText(f.read()) 35 | 36 | def save_file (self): 37 | options = QFileDialog.Options() 38 | file_name, _ = QFileDialog.getSaveFileName(self,"Save File", "", "Text Files (*.txt);;All File (*)",options=options) 39 | if file_name != "": 40 | with open (file_name, "w") as f: 41 | f.write(self.plainTextEdit.toPlainText()) 42 | 43 | def closeEvent (self,e): 44 | s = QMessageBox() 45 | s.setText("Do you want to save changes to this file?") 46 | s.addButton(QPushButton("Save"), QMessageBox.YesRole) 47 | s.addButton(QPushButton("Don't Save"), QMessageBox.NoRole) 48 | s.addButton(QPushButton("Cancel"), QMessageBox.RejectRole) 49 | ans = s.exec_() 50 | if ans == 0: 51 | self.save_file() 52 | e.accept() 53 | elif ans == 2: 54 | e.ignore() 55 | 56 | def main(): 57 | app = QApplication([]) 58 | window = MyUI() 59 | app.exec_() 60 | if __name__ == "__main__": 61 | main() 62 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Hacktoberfest 2 | Join the Hacktoberfest fun! Contribute to this repo and earn cool swag while improving open-source projects. 3 | 4 | 5 | ## About Hacktoberfest 6 | Hacktoberfest is a month-long celebration of open source software in October. It's a great opportunity for developers of all skill levels to contribute to open source projects and earn cool swag! 7 | 8 | ## Rules 9 | 10 | 1. Follow User and star⭐ this repository. 11 | 2. Clone the forked repository to your local machine. 12 | 3. Create a new branch for your contributions. 13 | 4. Make your contributions (e.g., bug fixes, new features, documentation improvements, etc.). 14 | 5. Commit your changes with meaningful messages. 15 | 6. Push your changes to your forked repository. 16 | 7. Create a Pull Request (PR) to this repository. 17 | 8. Wait for your PR to be reviewed and merged! 18 | 19 | ## Contribution Guidelines 20 | - Make sure your code follows best practices and coding standards. 21 | - Include clear and concise commit messages. 22 | - Be respectful and considerate in all interactions. 23 | 24 | ## Get Started 25 | Ready to contribute? Start by forking and cloning this repository! 26 | 27 | 28 | ## Resources 29 | - [Hacktoberfest Official Website](https://hacktoberfest.digitalocean.com/) 30 | - [Hacktoberfest on GitHub](https://github.com/topics/hacktoberfest) 31 | -------------------------------------------------------------------------------- /Rhombus_patten.c: -------------------------------------------------------------------------------- 1 | // C Program to print the rhombus pattern using * star 2 | #include 3 | int main() 4 | { 5 | int rows = 5; 6 | // first outer loop to iterate through each row 7 | 8 | for (int i = 0; i < rows; i++) { 9 | // first inner loop to print white spaces 10 | 11 | for (int j = 0; j < rows - i - 1; j++) { 12 | printf(" "); 13 | } 14 | // second inner loop to print * star in each row 15 | 16 | for (int k = 0; k < rows; k++) { 17 | printf("* "); 18 | } 19 | printf("\n"); 20 | } 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /Spiral Matrix: -------------------------------------------------------------------------------- 1 | vector spiralOrder(vector>& matrix) { 2 | vectorv; 3 | int row=matrix.size(); 4 | int col=matrix[0].size(); 5 | int c=0,total=row*col; 6 | int sr=0,er=row-1,sc=0,ec=col-1; 7 | while(c=sc && c=sr && c 2 | 3 | 4 | 5 | 6 | 7 | My Portfolio 8 | 112 | 113 | 114 |
115 |

My Portfolio

116 | 123 |
124 | 125 |
126 |

Welcome to My World!

127 |

I am a passionate developer, problem solver, and tech enthusiast. Here you can explore my journey, work, and interests.

128 |
129 | 130 |
131 |

My Projects

132 |
133 |
134 |

Project One

135 |

Responsive web design with advanced CSS techniques and animations.

136 |
137 |
138 |

Project Two

139 |

Full-stack web application with Node.js, MongoDB, and RESTful API integration.

140 |
141 |
142 |

Project Three

143 |

Automation scripts using Python, improving efficiency and reducing manual work.

144 |
145 |
146 |
147 | 148 | 149 | 150 | 151 | --------------------------------------------------------------------------------