├── .vscode ├── c_cpp_properties.json ├── launch.json └── settings.json ├── C++ ├── 2D-word-search.cpp ├── 4-Sum_Problem.cpp ├── BFS.cpp ├── CircularLinkedList.cpp ├── Comparisson_of_Array.cpp ├── DFS.cpp ├── Dijkstra's_Algorithm.cpp ├── Distinct_Subsequences.cpp ├── Fibonacci_Series.cpp ├── Graph │ ├── Adjacency_Matrix.cpp │ └── Graph_AdjacencyList.cpp ├── Heap sort.cpp ├── ISPRIME.cpp ├── Mergesort.cpp ├── MillerRabin.cpp ├── Minimum number of subsets with distinct elements ├── MinimumRecolorstogetKconsecutivethings.cpp ├── Palindrome_Number_Check.cpp ├── Queue.cpp ├── SetOperations.cpp ├── WavePrintMatrix.cpp ├── balanced_paranthesis.cpp ├── bankprogram.cpp ├── binarysearch.cpp ├── convert_number_to_hexadecimal.cpp ├── linearsearch.cpp ├── linkedlist.cpp ├── quick_sort.cpp ├── radix_sort.cpp ├── stock_max_profit.cpp ├── towerofhanoi.cpp ├── towerofhanoi.exe └── trees.cpp ├── C ├── 3_sum.c ├── BinarySearch.c ├── Binary_Search_Tree_Traversal.c ├── Compute.C ├── To_find_keywords.c ├── To_find_keywords.txt ├── Two_Sum.c ├── binary_search.c ├── bubble_sort.c ├── calculator.c ├── createpattern ├── first.c ├── infix_to_postfix.c ├── linear_search.c ├── passwordgenerator.c ├── quick_sort.c ├── rps.c ├── rps.exe ├── self_printing_code.c ├── sieveOfEratosthenes.c └── sort.c ├── CONTRIBUTING.md ├── Java ├── 123Pattern.java ├── 3Sum.java ├── Abstraction.java ├── AddTwoNumbers.java ├── AllArray.java ├── BubbleSort.java ├── DoubleEndedQueue.java ├── GCD.java ├── Leaders.java ├── Linkedlist_Codestudio │ ├── Addone.java │ ├── DeleteLastNode.java │ ├── DeleteNodeUsingOnePointer.java │ ├── DoubleLL.java │ ├── FindMiddle.java │ ├── Linkedlistremovenodefromlast.java │ ├── MaxSubarrSum.java │ ├── Sort012.java │ └── SortLL.java ├── MaxSubArray.java ├── MergeSortedLists.java ├── ParindromicNumPattern.java ├── RadixSortingAlgo.java ├── ReverseWordsInString-III.java ├── ShellSortingAlgo.java ├── SieveOfEratosthenes.java ├── Stack.java ├── StackTest.java ├── StackTest.txt ├── TwoSum.java ├── binarysearchalgo.java ├── medianTwoSortedArrays.java ├── mergeTwoSortedLists.java └── neonnumber.java ├── Javascript ├── marksheet.js └── randomPass.js ├── Linear.java ├── PHP └── Web-Scrapper │ ├── Php and Database Connection.php │ ├── README.md │ ├── crawl.php │ └── crawler.sql ├── Pattern_Printing.py ├── Python ├── Automate Whatsapp Messeges ├── Brest Cancer Classification Using Python ├── Bubble_Sort ├── Cartoonify using Python ├── Hand Gesture Recognation Using Python ├── Hollow Butterfly Pattern ├── Hourglass ├── Hourglass.py ├── Insertion Sort using Python ├── Password_Generator.py ├── Selection Sort using Python ├── atm.py ├── binarysearchalgo.py ├── certificate_generator.py ├── crud.py ├── guess_the_number.py ├── heapsort.py ├── kadanes_algorithm.py ├── kth largest element ├── linear-regression.py ├── nim.py ├── sieveOfEratosthenes.py ├── telephone_directory.py └── tic_tac_toe.py ├── README.md ├── SelectionSortAlgo.cpp ├── binary.py ├── bubblesort.cpp ├── c code └── longestPalindrome.cpp /.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 | "name": "C/C++ Runner: Debug Session", 6 | "type": "cppdbg", 7 | "request": "launch", 8 | "args": [], 9 | "stopAtEntry": false, 10 | "externalConsole": true, 11 | "cwd": "c:/Users/vlpvg/hactoberfest-2k23/CodingPractice-Hacktoberfest23", 12 | "program": "c:/Users/vlpvg/hactoberfest-2k23/CodingPractice-Hacktoberfest23/build/Debug/outDebug", 13 | "MIMode": "gdb", 14 | "miDebuggerPath": "gdb", 15 | "setupCommands": [ 16 | { 17 | "description": "Enable pretty-printing for gdb", 18 | "text": "-enable-pretty-printing", 19 | "ignoreFailures": true 20 | } 21 | ] 22 | } 23 | ] 24 | } -------------------------------------------------------------------------------- /.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 | } -------------------------------------------------------------------------------- /C++/2D-word-search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int x[] = {-1, -1, -1, 0, 0, 1, 1, 1}; 5 | int y[] = {-1, 0, 1, -1, 1, -1, 0, 1}; 6 | 7 | bool search2D(char *grid, int row, int col, 8 | string word, int R, int C) 9 | { 10 | if (*(grid + row * C + col) != word[0]) 11 | return false; 12 | 13 | int len = word.length(); 14 | 15 | for (int dir = 0; dir < 8; dir++) 16 | { 17 | 18 | int k, rd = row + x[dir], cd = col + y[dir]; 19 | 20 | for (k = 1; k < len; k++) 21 | { 22 | 23 | if (rd >= R || rd < 0 || cd >= C || cd < 0) 24 | break; 25 | 26 | if (*(grid + rd * C + cd) != word[k]) 27 | break; 28 | 29 | rd += x[dir], cd += y[dir]; 30 | } 31 | 32 | if (k == len) 33 | return true; 34 | } 35 | return false; 36 | } 37 | 38 | void patternSearch(char *grid, string word, 39 | int R, int C) 40 | { 41 | for (int row = 0; row < R; row++) 42 | for (int col = 0; col < C; col++) 43 | if (search2D(grid, row, col, word, R, C)) 44 | cout << "pattern found at " 45 | << row << ", " 46 | << col << endl; 47 | } 48 | 49 | int main() 50 | { 51 | int R = 3, C = 13; 52 | char grid[R][C] = {"THISISAFUNPROGRAM", 53 | "WELEARNTHROGHCODE", 54 | "CODINGISVERYFUNEE"}; 55 | 56 | patternSearch((char *)grid, "FUN", R, C); 57 | cout << endl; 58 | patternSearch((char *)grid, "CODING", R, C); 59 | 60 | return 0; 61 | } 62 | -------------------------------------------------------------------------------- /C++/4-Sum_Problem.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | class Solution { 6 | public: 7 | std::vector> fourSum(std::vector& nums, int target) { 8 | std::vector> result; 9 | 10 | if (nums.empty()) { 11 | return result; 12 | } 13 | 14 | int n = nums.size(); 15 | std::sort(nums.begin(), nums.end()); 16 | 17 | for (int i = 0; i < n; i++) { 18 | int target_3 = target - nums[i]; 19 | 20 | for (int j = i + 1; j < n; j++) { 21 | int target_2 = target_3 - nums[j]; 22 | int front = j + 1; 23 | int back = n - 1; 24 | 25 | while (front < back) { 26 | int two_sum = nums[front] + nums[back]; 27 | 28 | if (two_sum < target_2) { 29 | front++; 30 | } else if (two_sum > target_2) { 31 | back--; 32 | } else { 33 | std::vector quadruplet(4, 0); 34 | quadruplet[0] = nums[i]; 35 | quadruplet[1] = nums[j]; 36 | quadruplet[2] = nums[front]; 37 | quadruplet[3] = nums[back]; 38 | result.push_back(quadruplet); 39 | 40 | while (front < back && nums[front] == quadruplet[2]) { 41 | front++; 42 | } 43 | 44 | while (front < back && nums[back] == quadruplet[3]) { 45 | back--; 46 | } 47 | } 48 | } 49 | 50 | while (j + 1 < n && nums[j + 1] == nums[j]) { 51 | j++; 52 | } 53 | } 54 | 55 | while (i + 1 < n && nums[i + 1] == nums[i]) { 56 | i++; 57 | } 58 | } 59 | 60 | return result; 61 | } 62 | }; 63 | 64 | int main() { 65 | Solution obj; 66 | std::vector v{1, 0, -1, 0, -2, 2}; 67 | 68 | std::vector> sum = obj.fourSum(v, 0); 69 | std::cout << "The unique quadruplets are" << std::endl; 70 | 71 | for (int i = 0; i < sum.size(); i++) { 72 | for (int j = 0; j < sum[i].size(); j++) { 73 | std::cout << sum[i][j] << " "; 74 | } 75 | std::cout << std::endl; 76 | } 77 | 78 | return 0; 79 | } 80 | -------------------------------------------------------------------------------- /C++/BFS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | // Function to return Breadth First Traversal of given graph. 7 | vector bfsOfGraph(int V, vector adj[]) { 8 | int vis[V] = {0}; 9 | vis[0] = 1; 10 | queue q; 11 | // push the initial starting node 12 | q.push(0); 13 | vector bfs; 14 | // iterate till the queue is empty 15 | while(!q.empty()) { 16 | // get the topmost element in the queue 17 | int node = q.front(); 18 | q.pop(); 19 | bfs.push_back(node); 20 | // traverse for all its neighbours 21 | for(auto it : adj[node]) { 22 | // if the neighbour has previously not been visited, 23 | // store in Q and mark as visited 24 | if(!vis[it]) { 25 | vis[it] = 1; 26 | q.push(it); 27 | } 28 | } 29 | } 30 | return bfs; 31 | } 32 | }; 33 | 34 | void addEdge(vector adj[], int u, int v) { 35 | adj[u].push_back(v); 36 | adj[v].push_back(u); 37 | } 38 | 39 | void printAns(vector &ans) { 40 | for (int i = 0; i < ans.size(); i++) { 41 | cout << ans[i] << " "; 42 | } 43 | } 44 | 45 | int main() 46 | { 47 | vector adj[6]; 48 | 49 | addEdge(adj, 0, 1); 50 | addEdge(adj, 1, 2); 51 | addEdge(adj, 1, 3); 52 | addEdge(adj, 0, 4); 53 | 54 | Solution obj; 55 | vector ans = obj.bfsOfGraph(5, adj); 56 | printAns(ans); 57 | 58 | return 0; 59 | } 60 | 61 | // Output: 0 1 4 2 3 62 | 63 | // Time Complexity: O(N) + O(2E), Where N = Nodes, 2E is for total degrees as we traverse all adjacent nodes. 64 | 65 | // Space Complexity: O(3N) ~ O(N), Space for queue data structure visited array and an adjacency list 66 | 67 | -------------------------------------------------------------------------------- /C++/CircularLinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | class Node 4 | { 5 | public: 6 | int data; 7 | Node *next; 8 | 9 | Node(int value) 10 | { 11 | data = value; 12 | next = nullptr; 13 | } 14 | }; 15 | 16 | class CircularLinkedList 17 | { 18 | private: 19 | Node *head; 20 | 21 | public: 22 | CircularLinkedList() 23 | { 24 | head = nullptr; 25 | } 26 | 27 | ~CircularLinkedList() 28 | { 29 | if (head != nullptr) 30 | { 31 | Node *temp = head->next; 32 | while (temp != head) 33 | { 34 | Node *prev = temp; 35 | temp = temp->next; 36 | delete prev; 37 | } 38 | delete head; 39 | } 40 | } 41 | 42 | void append(int data) 43 | { 44 | Node *new_node = new Node(data); 45 | if (head == nullptr) 46 | { 47 | head = new_node; 48 | head->next = head; 49 | } 50 | else 51 | { 52 | Node *temp = head; 53 | while (temp->next != head) 54 | { 55 | temp = temp->next; 56 | } 57 | temp->next = new_node; 58 | new_node->next = head; 59 | } 60 | } 61 | 62 | void display() 63 | { 64 | if (head == nullptr) 65 | { 66 | std::cout << "Circular Linked List is empty." << std::endl; 67 | return; 68 | } 69 | 70 | Node *temp = head; 71 | do 72 | { 73 | std::cout << temp->data << " -> "; 74 | temp = temp->next; 75 | } while (temp != head); 76 | std::cout << head->data << std::endl; 77 | } 78 | }; 79 | 80 | int main() 81 | { 82 | CircularLinkedList cll; 83 | cll.append(1); 84 | cll.append(2); 85 | cll.append(3); 86 | cll.append(4); 87 | 88 | std::cout << "Circular Linked List:" << std::endl; 89 | cll.display(); 90 | 91 | return 0; 92 | } 93 | -------------------------------------------------------------------------------- /C++/Comparisson_of_Array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main(){ 4 | int arr[5],temp,temp2,arr2[5]; 5 | for(int i=0; i<5; i++){ 6 | cout<<"Enter 1st"<>arr[i]; 8 | cout<<"Enter 2nd array of"<>arr2[i]; 10 | } 11 | 12 | for(int i=0; i<5; i++){ 13 | for(int j=i+1; j<5; j++ ){ 14 | if(arr[j] 2 | using namespace std; 3 | 4 | class Solution { 5 | private: 6 | void dfs(int node, vector adj[], int vis[], vector &ls) { 7 | vis[node] = 1; 8 | ls.push_back(node); 9 | // traverse all its neighbours 10 | for(auto it : adj[node]) { 11 | // if the neighbour is not visited 12 | if(!vis[it]) { 13 | dfs(it, adj, vis, ls); 14 | } 15 | } 16 | } 17 | public: 18 | // Function to return a list containing the DFS traversal of the graph. 19 | vector dfsOfGraph(int V, vector adj[]) { 20 | int vis[V] = {0}; 21 | int start = 0; 22 | // create a list to store dfs 23 | vector ls; 24 | // call dfs for starting node 25 | dfs(start, adj, vis, ls); 26 | return ls; 27 | } 28 | }; 29 | 30 | void addEdge(vector adj[], int u, int v) { 31 | adj[u].push_back(v); 32 | adj[v].push_back(u); 33 | } 34 | 35 | void printAns(vector &ans) { 36 | for (int i = 0; i < ans.size(); i++) { 37 | cout << ans[i] << " "; 38 | } 39 | } 40 | 41 | int main() 42 | { 43 | vector adj[5]; 44 | 45 | addEdge(adj, 0, 2); 46 | addEdge(adj, 2, 4); 47 | addEdge(adj, 0, 1); 48 | addEdge(adj, 0, 3); 49 | 50 | Solution obj; 51 | vector ans = obj.dfsOfGraph(5, adj); 52 | printAns(ans); 53 | 54 | return 0; 55 | } 56 | 57 | // Output: 0 2 4 1 3 58 | 59 | // Time Complexity: For an undirected graph, O(N) + O(2E), For a directed graph, O(N) + O(E), Because for every node we are calling the recursive function once, the time taken is O(N) and 2E is for total degrees as we traverse for all adjacent nodes. 60 | 61 | // Space Complexity: O(3N) ~ O(N), Space for dfs stack space, visited array and an adjacency list. 62 | -------------------------------------------------------------------------------- /C++/Dijkstra's_Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution 5 | { 6 | public: 7 | //Function to find the shortest distance of all the vertices 8 | //from the source vertex S. 9 | vector dijkstra(int V, vector> adj[], int S) 10 | { 11 | // Create a set ds for storing the nodes as a pair {dist,node} 12 | // where dist is the distance from source to the node. 13 | // set stores the nodes in ascending order of the distances 14 | set> st; 15 | 16 | // Initialising dist list with a large number to 17 | // indicate the nodes are unvisited initially. 18 | // This list contains distance from source to the nodes. 19 | vector dist(V, 1e9); 20 | 21 | st.insert({0, S}); 22 | 23 | // Source initialised with dist=0 24 | dist[S] = 0; 25 | 26 | // Now, erase the minimum distance node first from the set 27 | // and traverse for all its adjacent nodes. 28 | while(!st.empty()) { 29 | auto it = *(st.begin()); 30 | int node = it.second; 31 | int dis = it.first; 32 | st.erase(it); 33 | 34 | // Check for all adjacent nodes of the erased 35 | // element whether the prev dist is larger than current or not. 36 | for(auto it : adj[node]) { 37 | int adjNode = it[0]; 38 | int edgW = it[1]; 39 | 40 | if(dis + edgW < dist[adjNode]) { 41 | // erase if it was visited previously at 42 | // a greater cost. 43 | if(dist[adjNode] != 1e9) 44 | st.erase({dist[adjNode], adjNode}); 45 | 46 | // If current distance is smaller, 47 | // push it into the queue 48 | dist[adjNode] = dis + edgW; 49 | st.insert({dist[adjNode], adjNode}); 50 | } 51 | } 52 | } 53 | // Return the list containing shortest distances 54 | // from source to all the nodes. 55 | return dist; 56 | } 57 | }; 58 | 59 | int main() 60 | { 61 | // Driver code. 62 | int V = 3, E = 3, S = 2; 63 | vector> adj[V]; 64 | vector> edges; 65 | vector v1{1, 1}, v2{2, 6}, v3{2, 3}, v4{0, 1}, v5{1, 3}, v6{0, 6}; 66 | int i = 0; 67 | adj[0].push_back(v1); 68 | adj[0].push_back(v2); 69 | adj[1].push_back(v3); 70 | adj[1].push_back(v4); 71 | adj[2].push_back(v5); 72 | adj[2].push_back(v6); 73 | 74 | Solution obj; 75 | vector res = obj.dijkstra(V, adj, S); 76 | 77 | for (int i = 0; i < V; i++) 78 | { 79 | cout << res[i] << " "; 80 | } 81 | cout << endl; 82 | return 0; 83 | } 84 | 85 | // Output: 4 3 0 86 | 87 | // Time Complexity : O( E log(V) ) 88 | // Where E = Number of edges and V = Number of Nodes. 89 | 90 | // Space Complexity : O( |E| + |V| ) 91 | // Where E = Number of edges and V = Number of Nodes. 92 | -------------------------------------------------------------------------------- /C++/Distinct_Subsequences.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // To count distinct subsequences of string 't' in string 's' 5 | long long distinct_subsequence(int x, int y, string &s, string &t, vector>& dp) 6 | { 7 | // If we have matched all characters in 't', return 1 as we have found a distinct subsequence. 8 | if(y == t.size()) 9 | { 10 | return 1; 11 | } 12 | // If we have reached the end of string 's' but not yet matched all characters in 't', return 0. 13 | if(x == s.size()) 14 | { 15 | return 0; 16 | } 17 | // returning the memoized value if already calculated 18 | if(dp[x][y] != -1) 19 | { 20 | return dp[x][y]; 21 | } 22 | // If character matches then either continue or look for another occurrence of it in 's' 23 | if(s[x] == t[y]) 24 | { 25 | long long a = distinct_subsequence(x + 1, y + 1, s, t, dp); 26 | long long b = distinct_subsequence(x + 1, y, s, t, dp); 27 | return dp[x][y] = a + b; 28 | } 29 | return dp[x][y] = distinct_subsequence(x + 1, y, s, t, dp) + 0; 30 | } 31 | 32 | int main() { 33 | string s = "baggbag"; 34 | string t = "bag"; 35 | long long x = s.size(); 36 | long long y = t.size(); 37 | // Initializing a memoization table 38 | vector> dp(x, vector(y, -1)); 39 | cout << distinct_subsequence(0, 0, s, t, dp) << endl; 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /C++/Fibonacci_Series.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int n1=0,n2=1,n3,i,number; 6 | cout<<"Enter the number of elements: "; 7 | cin>>number; 8 | cout< 4 | using namespace std; 5 | 6 | class Graph { 7 | private: 8 | bool** adjMatrix; 9 | int numVertices; 10 | 11 | public: 12 | // Initialize the matrix to zero 13 | Graph(int numVertices) { 14 | this->numVertices = numVertices; 15 | adjMatrix = new bool*[numVertices]; 16 | for (int i = 0; i < numVertices; i++) { 17 | adjMatrix[i] = new bool[numVertices]; 18 | for (int j = 0; j < numVertices; j++) 19 | adjMatrix[i][j] = false; 20 | } 21 | } 22 | 23 | // Add edges 24 | void addEdge(int i, int j) { 25 | adjMatrix[i][j] = true; 26 | adjMatrix[j][i] = true; 27 | } 28 | 29 | // Remove edges 30 | void removeEdge(int i, int j) { 31 | adjMatrix[i][j] = false; 32 | adjMatrix[j][i] = false; 33 | } 34 | 35 | // Print the martix 36 | void toString() { 37 | for (int i = 0; i < numVertices; i++) { 38 | cout << i << " : "; 39 | for (int j = 0; j < numVertices; j++) 40 | cout << adjMatrix[i][j] << " "; 41 | cout << "\n"; 42 | } 43 | } 44 | 45 | ~Graph() { 46 | for (int i = 0; i < numVertices; i++) 47 | delete[] adjMatrix[i]; 48 | delete[] adjMatrix; 49 | } 50 | }; 51 | 52 | int main() { 53 | Graph g(4); 54 | 55 | g.addEdge(0, 1); 56 | g.addEdge(0, 2); 57 | g.addEdge(1, 2); 58 | g.addEdge(2, 0); 59 | g.addEdge(2, 3); 60 | 61 | g.toString(); 62 | } -------------------------------------------------------------------------------- /C++/Graph/Graph_AdjacencyList.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | template 8 | class graph{ 9 | public: 10 | unordered_map> adj; 11 | void addEdge(T u,T v,bool direction){ 12 | //direction = 0 ->undirected 13 | //direction = 1 ->directed graph 14 | 15 | //create an edge from u to v 16 | adj[u].push_back(v); 17 | if(direction == 0){ 18 | adj[v].push_back(u); 19 | } 20 | } 21 | 22 | void printAdjList(){ 23 | for(auto i:adj){ 24 | cout<"; 25 | for(auto j:i.second){ 26 | cout<>n; 37 | 38 | int m; 39 | cout<<"Enter the number of edges"<>m; 41 | 42 | graph g; 43 | 44 | for(int i=0;i>u>>v; 47 | //creating undirected graph 48 | g.addEdge(u,v,0); 49 | 50 | } 51 | g.printAdjList(); 52 | 53 | } -------------------------------------------------------------------------------- /C++/Heap sort.cpp: -------------------------------------------------------------------------------- 1 | 2 | // C++ program for implementation of Heap Sort 3 | 4 | #include 5 | using namespace std; 6 | 7 | // To heapify a subtree rooted with node i 8 | // which is an index in arr[]. 9 | // n is size of heap 10 | void heapify(int arr[], int N, int i) 11 | { 12 | 13 | // Initialize largest as root 14 | int largest = i; 15 | 16 | // left = 2*i + 1 17 | int l = 2 * i + 1; 18 | 19 | // right = 2*i + 2 20 | int r = 2 * i + 2; 21 | 22 | // If left child is larger than root 23 | if (l < N && arr[l] > arr[largest]) 24 | largest = l; 25 | 26 | // If right child is larger than largest 27 | // so far 28 | if (r < N && arr[r] > arr[largest]) 29 | largest = r; 30 | 31 | // If largest is not root 32 | if (largest != i) { 33 | swap(arr[i], arr[largest]); 34 | 35 | // Recursively heapify the affected 36 | // sub-tree 37 | heapify(arr, N, largest); 38 | } 39 | } 40 | 41 | // Main function to do heap sort 42 | void heapSort(int arr[], int N) 43 | { 44 | 45 | // Build heap (rearrange array) 46 | for (int i = N / 2 - 1; i >= 0; i--) 47 | heapify(arr, N, i); 48 | 49 | // One by one extract an element 50 | // from heap 51 | for (int i = N - 1; i > 0; i--) { 52 | 53 | // Move current root to end 54 | swap(arr[0], arr[i]); 55 | 56 | // call max heapify on the reduced heap 57 | heapify(arr, i, 0); 58 | } 59 | } 60 | 61 | // A utility function to print array of size n 62 | void printArray(int arr[], int N) 63 | { 64 | for (int i = 0; i < N; ++i) 65 | cout << arr[i] << " "; 66 | cout << "\n"; 67 | } 68 | 69 | // Driver's code 70 | int main() 71 | { 72 | int arr[] = { 12, 11, 13, 5, 6, 7 }; 73 | int N = sizeof(arr) / sizeof(arr[0]); 74 | 75 | // Function call 76 | heapSort(arr, N); 77 | 78 | cout << "Sorted array is \n"; 79 | printArray(arr, N); 80 | } 81 | -------------------------------------------------------------------------------- /C++/ISPRIME.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Simple algorthiam to check Primality of a 32 bit int 4 | Time complaxity : O(sqrt(n/3)) 5 | */ 6 | 7 | #include 8 | #include 9 | 10 | using namespace std; 11 | bool isPrime(int num) 12 | { 13 | if(num < 4) return n>1; 14 | 15 | if(!(num&1) or num%3==0 ) return false; 16 | 17 | for(int i=5;i*i<=num;i+=6) 18 | if(num%i==0 or num%(i+2)==0) 19 | return false; 20 | 21 | return true; 22 | } 23 | 24 | int main() 25 | { 26 | int num; 27 | cout<<"Enter number to check:"; 28 | cin>>num; 29 | assert(num>0); 30 | if(isPrime(num)) 31 | cout<< num <<" is Prime Number\n"; 32 | else 33 | cout<< num <<" is not a Prime Number\n"; 34 | 35 | 36 | } -------------------------------------------------------------------------------- /C++/Mergesort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for Merge Sort 2 | #include 3 | using namespace std; 4 | 5 | // Merges two subarrays of array[]. 6 | // First subarray is arr[begin..mid] 7 | // Second subarray is arr[mid+1..end] 8 | void merge(int array[], int const left, int const mid, 9 | int const right) 10 | { 11 | int const subArrayOne = mid - left + 1; 12 | int const subArrayTwo = right - mid; 13 | 14 | // Create temp arrays 15 | auto *leftArray = new int[subArrayOne], 16 | *rightArray = new int[subArrayTwo]; 17 | 18 | // Copy data to temp arrays leftArray[] and rightArray[] 19 | for (auto i = 0; i < subArrayOne; i++) 20 | leftArray[i] = array[left + i]; 21 | for (auto j = 0; j < subArrayTwo; j++) 22 | rightArray[j] = array[mid + 1 + j]; 23 | 24 | auto indexOfSubArrayOne = 0, indexOfSubArrayTwo = 0; 25 | int indexOfMergedArray = left; 26 | 27 | // Merge the temp arrays back into array[left..right] 28 | while (indexOfSubArrayOne < subArrayOne 29 | && indexOfSubArrayTwo < subArrayTwo) { 30 | if (leftArray[indexOfSubArrayOne] 31 | <= rightArray[indexOfSubArrayTwo]) { 32 | array[indexOfMergedArray] 33 | = leftArray[indexOfSubArrayOne]; 34 | indexOfSubArrayOne++; 35 | } 36 | else { 37 | array[indexOfMergedArray] 38 | = rightArray[indexOfSubArrayTwo]; 39 | indexOfSubArrayTwo++; 40 | } 41 | indexOfMergedArray++; 42 | } 43 | 44 | // Copy the remaining elements of 45 | // left[], if there are any 46 | while (indexOfSubArrayOne < subArrayOne) { 47 | array[indexOfMergedArray] 48 | = leftArray[indexOfSubArrayOne]; 49 | indexOfSubArrayOne++; 50 | indexOfMergedArray++; 51 | } 52 | 53 | // Copy the remaining elements of 54 | // right[], if there are any 55 | while (indexOfSubArrayTwo < subArrayTwo) { 56 | array[indexOfMergedArray] 57 | = rightArray[indexOfSubArrayTwo]; 58 | indexOfSubArrayTwo++; 59 | indexOfMergedArray++; 60 | } 61 | delete[] leftArray; 62 | delete[] rightArray; 63 | } 64 | 65 | // begin is for left index and end is right index 66 | // of the sub-array of arr to be sorted 67 | void mergeSort(int array[], int const begin, int const end) 68 | { 69 | if (begin >= end) 70 | return; 71 | 72 | int mid = begin + (end - begin) / 2; 73 | mergeSort(array, begin, mid); 74 | mergeSort(array, mid + 1, end); 75 | merge(array, begin, mid, end); 76 | } 77 | 78 | // UTILITY FUNCTIONS 79 | // Function to print an array 80 | void printArray(int A[], int size) 81 | { 82 | for (int i = 0; i < size; i++) 83 | cout << A[i] << " "; 84 | cout << endl; 85 | } 86 | 87 | // Driver code 88 | int main() 89 | { 90 | int arr[] = { 12, 11, 13, 5, 6, 7 }; 91 | int arr_size = sizeof(arr) / sizeof(arr[0]); 92 | 93 | cout << "Given array is \n"; 94 | printArray(arr, arr_size); 95 | 96 | mergeSort(arr, 0, arr_size - 1); 97 | 98 | cout << "\nSorted array is \n"; 99 | printArray(arr, arr_size); 100 | return 0; 101 | } 102 | 103 | // This code is contributed by Mayank Tyagi 104 | // This code was revised by Joshua Estes 105 | -------------------------------------------------------------------------------- /C++/MillerRabin.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Miller Ranbin test Deterministic method for checking a prime number; 4 | Time Complexity : O(12*log(n)); 5 | Its Implementation 6 | 7 | */ 8 | 9 | #include 10 | using namespace std; 11 | using u64 = uint64_t; 12 | using u128 = __uint128_t; 13 | 14 | u64 bin_exp(u64 base, u64 e, u64 mod) { 15 | u64 result = 1; 16 | base %= mod; 17 | while (e) { 18 | if (e & 1) 19 | result = (u128)result * base % mod; 20 | base = (u128)base * base % mod; 21 | e >>= 1; 22 | } 23 | return result; 24 | } 25 | 26 | bool check_composite(u64 n, u64 a, u64 d, int s) { 27 | u64 x = bin_exp(a, d, n); 28 | if (x == 1 || x == n - 1) 29 | return false; 30 | for (int r = 1; r < s; r++) { 31 | x = (u128)x * x % n; 32 | if (x == n - 1) 33 | return false; 34 | } 35 | return true; 36 | }; 37 | 38 | bool MillerRabin(u64 n) { 39 | if (n < 4) 40 | return n > 1; 41 | 42 | int r = 0; u64 d = n - 1; 43 | while ((d & 1) == 0) { 44 | d >>= 1,r++; 45 | } 46 | 47 | for (int a : {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37}) { 48 | if (n == a) 49 | return true; 50 | if (check_composite(n, a, d, r)) 51 | return false; 52 | } 53 | return true; 54 | } 55 | int main() 56 | { 57 | u64 num; 58 | cout<<"Enter number to check:"; 59 | cin>>num; 60 | assert(num>0); 61 | if(MillerRabin(num)) 62 | cout<< num <<" is Prime Number\n"; 63 | else 64 | cout<< num <<" is not a Prime Number\n"; 65 | } -------------------------------------------------------------------------------- /C++/Minimum number of subsets with distinct elements: -------------------------------------------------------------------------------- 1 | / A sorting based solution to find the 2 | // minimum number of subsets of a set 3 | // such that every subset contains distinct 4 | // elements. 5 | #include 6 | using namespace std; 7 | 8 | // Function to count subsets such that all 9 | // subsets have distinct elements. 10 | int subset(int ar[], int n) 11 | { 12 | // Take input and initialize res = 0 13 | int res = 0; 14 | 15 | // Sort the array 16 | sort(ar, ar + n); 17 | 18 | // Traverse the input array and 19 | // find maximum frequency 20 | for (int i = 0; i < n; i++) { 21 | int count = 1; 22 | 23 | // For each number find its repetition / frequency 24 | for (; i < n - 1; i++) { 25 | if (ar[i] == ar[i + 1]) 26 | count++; 27 | else 28 | break; 29 | } 30 | 31 | // Update res 32 | res = max(res, count); 33 | } 34 | 35 | return res; 36 | } 37 | 38 | // Driver code 39 | int main() 40 | { 41 | int arr[] = { 5, 6, 9, 3, 4, 3, 4 }; 42 | int n = sizeof(arr) / sizeof(arr[0]); 43 | cout << subset(arr, n); 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /C++/MinimumRecolorstogetKconsecutivethings.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | 6 | class Solution { 7 | public: 8 | int minimumRecolors(string s, int k) { 9 | int i = 0 , j = 0 , n = s.length(), curr = 0 , ans = INT_MAX; 10 | 11 | while(j 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n, num, digit, rev = 0; 7 | 8 | cout << "Enter a positive number: "; 9 | cin >> num; 10 | 11 | n = num; 12 | 13 | do 14 | { 15 | digit = num % 10; 16 | rev = (rev * 10) + digit; 17 | num = num / 10; 18 | } while (num != 0); 19 | 20 | cout << " The reverse of the number is: " << rev << endl; 21 | 22 | if (n == rev) 23 | cout << " The number is a palindrome."; 24 | else 25 | cout << " The number is not a palindrome."; 26 | 27 | return 0; 28 | } -------------------------------------------------------------------------------- /C++/Queue.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | queueq; //object creation 9 | int item; 10 | char ans; 11 | int choice; 12 | do 13 | { 14 | cout << "\n Main Menu"; 15 | cout <<"\n1. Insert element "; 16 | cout<<"\n2. Delete Element "; 17 | cout<<"\n3. Display Rear Element "; 18 | cout <<"\n4.Display Front Element "; 19 | cout <<"\n5. Size of queue "; 20 | cout <<"\n Enter your choice: "; 21 | cin >> choice; 22 | switch(choice) 23 | { 24 | case 1 :cout << "Enter the value to be inserted in Queue:"; 25 | cin>>item ; 26 | q.push(item); 27 | cout<< "\n Item is Inserted!"; 28 | break; 29 | case 2: item = q.front(); 30 | q.pop(); 31 | cout << "\n Deleted item is " << item; 32 | break; 33 | case 3: 34 | cout << "The element at the rear end is: " << q.back(); 35 | break; 36 | case 4: 37 | cout << "The element at the front end is: " << q.front(); 38 | break; 39 | case 5: 40 | cout << "\n Size of queue = " << q.size(); 41 | break; 42 | 43 | } 44 | cout << "\n Do you want to continue?"; 45 | cin >>ans; 46 | 47 | 48 | 49 | } while (ans == 'y'); 50 | return 0; 51 | } -------------------------------------------------------------------------------- /C++/SetOperations.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | int item, count; 8 | char ans = 'y'; 9 | int choice; 10 | set s; 11 | set::iterator i; 12 | 13 | do { 14 | cout << "\nMain Menu"; 15 | cout << "\n1. Insert an element"; 16 | cout << "\n2. Delete an Element"; 17 | cout << "\n3. Get the size of set"; 18 | cout << "\n4. Search an element"; 19 | cout << "\n5. Display"; 20 | cout << "\nEnter your choice: "; 21 | cin >> choice; 22 | 23 | switch (choice) { 24 | case 1: 25 | cout << "\nEnter the element to be inserted: "; 26 | cin >> item; 27 | s.insert(item); 28 | break; 29 | case 2: 30 | cout << "\nEnter the element to be deleted: "; 31 | cin >> item; 32 | s.erase(item); 33 | break; 34 | case 3: 35 | count = s.size(); 36 | cout << "\nThe size of set is: " << count; 37 | break; 38 | case 4: 39 | cout << "\nEnter the element to be searched: "; 40 | cin >> item; 41 | i = s.find(item); 42 | if (i != s.end()) { 43 | cout << "Element " << *i << " is present in the set" << endl; 44 | } else { 45 | cout << "Element is not present in the set." << endl; 46 | } 47 | break; 48 | case 5: 49 | cout << "Elements of set are: "; 50 | for (i = s.begin(); i != s.end(); i++) { 51 | cout << *i << " "; 52 | } 53 | break; 54 | default: 55 | cout << "\nInvalid choice. Please enter a valid choice." << endl; 56 | break; 57 | } 58 | cout << "\nDo you want to continue? (y/n): "; 59 | cin >> ans; 60 | } while ((ans == 'Y') || (ans == 'y')); 61 | 62 | return 0; 63 | } 64 | 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /C++/WavePrintMatrix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | void wavePrint(const vector>& matrix) { 7 | int rows = matrix.size(); 8 | int cols = matrix[0].size(); 9 | 10 | for (int j = 0; j < cols; ++j) { 11 | 12 | if (j % 2 == 0) { 13 | for (int i = 0; i < rows; ++i) { 14 | cout << matrix[i][j] << " "; 15 | } 16 | } else { 17 | 18 | for (int i = rows - 1; i >= 0; --i) { 19 | cout << matrix[i][j] << " "; 20 | } 21 | } 22 | } 23 | } 24 | 25 | int main() { 26 | int rows, cols; 27 | 28 | cout << "Enter the number of rows: "; 29 | cin >> rows; 30 | cout << "Enter the number of columns: "; 31 | cin >> cols; 32 | 33 | vector> matrix(rows, vector(cols)); 34 | cout << "Enter the matrix elements:\n"; 35 | for (int i = 0; i < rows; ++i) { 36 | for (int j = 0; j < cols; ++j) { 37 | cin >> matrix[i][j]; 38 | } 39 | } 40 | 41 | cout << "Wave print of the matrix:\n"; 42 | wavePrint(matrix); 43 | 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /C++/balanced_paranthesis.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | unordered_map symbol {{'{',1},{'(',2},{'[',3},{'}',-1},{')',-2},{']',-3}}; 7 | string check_balanced_paranthesis(string test){ 8 | stack st; 9 | for(char bracket:test){ 10 | if(symbol[bracket] > 0){ 11 | st.push(bracket); 12 | } 13 | else{ 14 | if(st.empty()) return "NO"; 15 | char c = st.top(); 16 | st.pop(); 17 | if(symbol[bracket] + symbol[c] != 0){ 18 | return "NO"; 19 | } 20 | } 21 | } 22 | if(st.empty()) return "YES"; 23 | return "NO"; 24 | } 25 | int main(){ 26 | string test_string,result; 27 | cout << "Enter the paranthesis string: "; 28 | cin >> test_string; 29 | result = check_balanced_paranthesis(test_string); 30 | cout << "The result is: " << result << endl; 31 | return 0; 32 | } -------------------------------------------------------------------------------- /C++/bankprogram.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define max 10 4 | using namespace std; 5 | 6 | struct antri 7 | { 8 | int data; 9 | }; 10 | 11 | struct identitas 12 | { 13 | char nama[20]; 14 | char transaksi[15]; 15 | int nominal; 16 | }; 17 | 18 | int main() 19 | { 20 | 21 | identitas id[15]; 22 | antri ant[15]; 23 | int cek=0, y=0, hapus; 24 | char pil; 25 | do { 26 | cout<<"\n========================"; 27 | cout<<"\nMENU ANTRIAN BANK COTAN "; 28 | cout<<"\n========================"<>id[cek].nama; 52 | cout<<"Jumlah transaksi: "; 53 | cin>>id[cek].transaksi; 54 | cout< 3 | using namespace std; 4 | 5 | int binarySearch(int arr[], int l, int r, int x) 6 | { 7 | while (l <= r) { 8 | int m = l + (r - l) / 2; 9 | 10 | if (arr[m] == x) 11 | return m; 12 | 13 | if (arr[m] < x) 14 | l = m + 1; 15 | 16 | else 17 | r = m - 1; 18 | } 19 | 20 | 21 | return -1; 22 | } 23 | 24 | 25 | int main() 26 | { 27 | int x; 28 | cout<<"Enter size of array "; 29 | cin>>x; 30 | int arr[x]; 31 | 32 | for (int i = 0; i < x; i++) 33 | { 34 | cin >> arr[i]; 35 | } 36 | 37 | int key; 38 | cout<<"enter key "; 39 | cin>>key; 40 | int n = sizeof(arr) / sizeof(arr[0]); 41 | int result = binarySearch(arr, 0, n - 1, key); 42 | (result == -1) 43 | ? cout << "Element is not present in array" 44 | : cout << "Element is present at index " << result; 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /C++/convert_number_to_hexadecimal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | string toHex(int num) { 7 | string hex = "0123456789abcdef"; 8 | string ans; 9 | if(num==0) return "0"; 10 | while (num>0) { 11 | ans = hex[num & 15] + ans; 12 | num >>= 4; 13 | } 14 | if(num<0){ 15 | ans = "00000000"; 16 | num++; 17 | num*=-1; 18 | int i=7; 19 | while(i>=0){ 20 | ans[i] = hex[15 -(num & 15)]; 21 | num >>= 4; 22 | i--; 23 | } 24 | } 25 | return ans; 26 | } 27 | }; 28 | 29 | -------------------------------------------------------------------------------- /C++/linearsearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n; 7 | cin >> n; 8 | int arr[n]; 9 | for (int i = 0; i < n; i++) 10 | cin >> arr[i]; 11 | 12 | int key; 13 | cin >> key; 14 | 15 | int i; 16 | for (i = 0; i < n; i++) 17 | { 18 | if (arr[i] == key) 19 | { 20 | cout << "Found at index " << i << endl; 21 | break; 22 | } 23 | } 24 | if (i == n) 25 | cout << "Not found" << endl; 26 | return 0; 27 | } -------------------------------------------------------------------------------- /C++/linkedlist.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node 5 | { 6 | public: 7 | int data; 8 | Node *next; 9 | }; 10 | 11 | class NodeList 12 | { 13 | public: 14 | Node *head; 15 | int size; 16 | 17 | NodeList() 18 | { 19 | head = nullptr; 20 | size = 0; 21 | } 22 | 23 | ~NodeList() 24 | { 25 | Node *temp = head; 26 | while (temp != nullptr) 27 | { 28 | Node *temp1 = temp->next; 29 | delete temp; 30 | temp = temp1; 31 | } 32 | } 33 | 34 | void insertatstart(int data) 35 | { 36 | Node *temp = new Node; 37 | temp->data = data; 38 | temp->next = head; 39 | head = temp; 40 | size++; 41 | } 42 | 43 | void insertatend(int data) 44 | { 45 | Node *temp = new Node; 46 | temp->data = data; 47 | temp->next = nullptr; 48 | Node *temp1 = head; 49 | while (temp1->next != nullptr) 50 | { 51 | temp1 = temp1->next; 52 | } 53 | temp1->next = temp; 54 | size++; 55 | } 56 | 57 | int length() 58 | { 59 | return size; 60 | } 61 | 62 | void print() 63 | { 64 | Node *temp = head; 65 | while (temp != nullptr) 66 | { 67 | cout << temp->data << " "; 68 | temp = temp->next; 69 | } 70 | cout << endl; 71 | } 72 | 73 | void printMiddle() 74 | { 75 | if (head == nullptr) 76 | { 77 | cout << "List is empty." << endl; 78 | return; 79 | } 80 | 81 | Node *slow = head; 82 | Node *fast = head; 83 | 84 | while (fast != nullptr && fast->next != nullptr) 85 | { 86 | slow = slow->next; 87 | fast = fast->next->next; 88 | } 89 | 90 | cout << "Middle element: " << slow->data << endl; 91 | } 92 | 93 | void CheckCircularList() 94 | { 95 | if (head == nullptr) 96 | { 97 | cout << "List is empty." << endl; 98 | return; 99 | } 100 | 101 | Node *slow = head; 102 | Node *fast = head; 103 | 104 | while (fast != nullptr && fast->next != nullptr) 105 | { 106 | slow = slow->next; 107 | fast = fast->next->next; 108 | 109 | if (slow == fast) 110 | { 111 | cout << "List is circular." << endl; 112 | return; 113 | } 114 | } 115 | cout << "List is not circular." << endl; 116 | } 117 | }; 118 | 119 | void RemoveCircularList(Node *head) 120 | { 121 | if (head == nullptr) 122 | { 123 | cout << "List is empty." << endl; 124 | return; 125 | } 126 | Node *slow = head; 127 | Node *fast = head; 128 | Node *temp; 129 | while (fast != nullptr && fast->next != nullptr) 130 | { 131 | temp = slow; 132 | slow = slow->next; 133 | fast = fast->next->next; 134 | if (slow == fast) 135 | { 136 | temp->next = nullptr; 137 | } 138 | } 139 | } 140 | Node *ReverseLList(Node *head) 141 | { 142 | if (head == nullptr) 143 | { 144 | cout << "List is empty." << endl; 145 | return nullptr; 146 | } 147 | 148 | Node *prev = nullptr; 149 | Node *curr = head; 150 | 151 | while (curr != nullptr) 152 | { 153 | Node *temp = curr->next; 154 | curr->next = prev; 155 | prev = curr; 156 | curr = temp; 157 | } 158 | 159 | return prev; 160 | } 161 | 162 | int main() 163 | { 164 | NodeList l1; 165 | l1.insertatstart(1); 166 | l1.insertatstart(2); 167 | l1.insertatstart(3); 168 | l1.insertatstart(4); 169 | l1.insertatstart(6); 170 | l1.insertatstart(5); 171 | l1.insertatend(99); 172 | 173 | // res = l1.search_val(4); 174 | // l1.print(); 175 | // printMiddle(l1.head); 176 | // CheckCircularlists(l1.head); 177 | 178 | 179 | l1.CheckCircularList(); 180 | l1.insertatstart(12); 181 | 182 | l1.print(); 183 | l1.head = ReverseLList(l1.head); 184 | l1.print(); 185 | cout << "Length: " << l1.length() << endl; 186 | 187 | return 0; 188 | } 189 | -------------------------------------------------------------------------------- /C++/quick_sort.cpp: -------------------------------------------------------------------------------- 1 | // C++ Implementation of the Quick Sort Algorithm. 2 | #include 3 | using namespace std; 4 | 5 | int partition(int arr[], int start, int end) 6 | { 7 | 8 | int pivot = arr[start]; 9 | 10 | int count = 0; 11 | for (int i = start + 1; i <= end; i++) { 12 | if (arr[i] <= pivot) 13 | count++; 14 | } 15 | 16 | // Giving pivot element its correct position 17 | int pivotIndex = start + count; 18 | swap(arr[pivotIndex], arr[start]); 19 | 20 | // Sorting left and right parts of the pivot element 21 | int i = start, j = end; 22 | 23 | while (i < pivotIndex && j > pivotIndex) { 24 | 25 | while (arr[i] <= pivot) { 26 | i++; 27 | } 28 | 29 | while (arr[j] > pivot) { 30 | j--; 31 | } 32 | 33 | if (i < pivotIndex && j > pivotIndex) { 34 | swap(arr[i++], arr[j--]); 35 | } 36 | } 37 | 38 | return pivotIndex; 39 | } 40 | 41 | void quickSort(int arr[], int start, int end) 42 | { 43 | 44 | // base case 45 | if (start >= end) 46 | return; 47 | 48 | // partitioning the array 49 | int p = partition(arr, start, end); 50 | 51 | // Sorting the left part 52 | quickSort(arr, start, p - 1); 53 | 54 | // Sorting the right part 55 | quickSort(arr, p + 1, end); 56 | } 57 | 58 | int main() 59 | { 60 | 61 | int arr[] = { 9, 3, 4, 2, 1, 8 }; 62 | int n = 6; 63 | 64 | quickSort(arr, 0, n - 1); 65 | 66 | for (int i = 0; i < n; i++) { 67 | cout << arr[i] << " "; 68 | } 69 | 70 | return 0; 71 | } 72 | -------------------------------------------------------------------------------- /C++/radix_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // A utility function to get the maximum element from an array 5 | int getMax(std::vector& arr) { 6 | int max = arr[0]; 7 | for (int i = 1; i < arr.size(); i++) { 8 | if (arr[i] > max) { 9 | max = arr[i]; 10 | } 11 | } 12 | return max; 13 | } 14 | 15 | // A function to do counting sort based on a specific digit 16 | void countSort(std::vector& arr, int exp) { 17 | int n = arr.size(); 18 | std::vector output(n); 19 | std::vector count(10, 0); 20 | 21 | // Count occurrences of digits at the specified position 22 | for (int i = 0; i < n; i++) { 23 | count[(arr[i] / exp) % 10]++; 24 | } 25 | 26 | // Convert count to cumulative count 27 | for (int i = 1; i < 10; i++) { 28 | count[i] += count[i - 1]; 29 | } 30 | 31 | // Build the output array 32 | for (int i = n - 1; i >= 0; i--) { 33 | output[count[(arr[i] / exp) % 10] - 1] = arr[i]; 34 | count[(arr[i] / exp) % 10]--; 35 | } 36 | 37 | // Copy the output array to the original array 38 | for (int i = 0; i < n; i++) { 39 | arr[i] = output[i]; 40 | } 41 | } 42 | 43 | // Radix Sort 44 | void radixSort(std::vector& arr) { 45 | int max = getMax(arr); 46 | 47 | // Perform counting sort for every digit place 48 | for (int exp = 1; max / exp > 0; exp *= 10) { 49 | countSort(arr, exp); 50 | } 51 | } 52 | 53 | int main() { 54 | std::vector arr = {170, 45, 75, 90, 802, 24, 2, 66}; 55 | 56 | std::cout << "Original Array: "; 57 | for (int num : arr) { 58 | std::cout << num << " "; 59 | } 60 | 61 | radixSort(arr); 62 | 63 | std::cout << "\nSorted Array: "; 64 | for (int num : arr) { 65 | std::cout << num << " "; 66 | } 67 | 68 | return 0; 69 | } 70 | -------------------------------------------------------------------------------- /C++/stock_max_profit.cpp: -------------------------------------------------------------------------------- 1 | //determine the maximum profit that can be made in a range of stock prices. 2 | // have the function StockPicker(arr) take the array of numbers stored in arr which will contain integers that represent the amount in dollars that a single stock is worth, 3 | //and return the maximum profit that could have been made by buying stock on day x and selling stock on day y where y > x. 4 | //For example: if arr is [44, 30, 24, 32, 35, 30, 40, 38, 15] then your program should return 16 because at index 2 the stock was worth $24 and at index 6 the stock was then worth $40, 5 | //so if you bought the stock at 24 and sold it at 40, you would have made a profit of $16, which is the maximum profit that could have been made with this list of stock prices. 6 | // If there is not profit that could have been made with the stock prices, then your program should return -1. For example : arr is[10, 9, 8, 2] then your program should return -1 7 | 8 | #include 9 | #include 10 | using namespace std; 11 | 12 | int StockPicker(int arr[], int size) { 13 | 14 | int value; 15 | int high = -1; 16 | 17 | // Loop to analyze each stock 18 | for (int x = 0; x < size-1; x++) 19 | { 20 | // Loop to compare which is the maximum profit 21 | // This takes the stock on day x and day y, to find difference 22 | for (int y = x+1; y < size; y++) 23 | { 24 | if (arr[x] < arr[y]) 25 | { 26 | value = arr[y] - arr[x]; 27 | 28 | if (value > high) 29 | { 30 | high = value; 31 | } 32 | } 33 | } 34 | } 35 | 36 | return high; 37 | } 38 | 39 | int main() { 40 | 41 | // keep this function call here 42 | /* Note: In C++ you first have to initialize an array and set 43 | it equal to the stdin to test your code with arrays. */ 44 | 45 | int A[] = { 10, 12, 4, 5, 9 }; 46 | int B[] = { 14, 20, 4, 12, 5, 11 }; 47 | int C[] = { 44, 30, 24, 32, 35, 30, 40, 38, 15 }; 48 | int D[] = { 10, 9, 8, 2 }; 49 | cout << StockPicker(A, sizeof(A) / sizeof(A[0])) << endl; // 5 50 | cout << StockPicker(B, sizeof(B) / sizeof(B[0])) << endl; // 8 51 | cout << StockPicker(C, sizeof(C) / sizeof(C[0])) << endl; // 16 52 | cout << StockPicker(D, sizeof(D) / sizeof(D[0])) << endl; // -1 53 | return 0; 54 | } -------------------------------------------------------------------------------- /C++/towerofhanoi.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) { 6 | if (n == 1) { 7 | cout << "Move disk 1 from rod " << from_rod << " to rod " << to_rod << endl; 8 | return; 9 | } 10 | 11 | 12 | towerOfHanoi(n - 1, from_rod, aux_rod, to_rod); 13 | 14 | 15 | cout << "Move disk " << n << " from rod " << from_rod << " to rod " << to_rod << endl; 16 | 17 | 18 | towerOfHanoi(n - 1, aux_rod, to_rod, from_rod); 19 | } 20 | 21 | int main() { 22 | int n; 23 | cout << "Enter the number of disks: "; 24 | cin >> n; 25 | 26 | towerOfHanoi(n, 'A', 'C', 'B'); 27 | 28 | return 0; 29 | } -------------------------------------------------------------------------------- /C++/towerofhanoi.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/csubhasundar/CodingPractice-Hacktoberfest23/65df5909deaafbd8102ac710fa34f31ffb2e4b29/C++/towerofhanoi.exe -------------------------------------------------------------------------------- /C++/trees.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | //---------------------------------------------------------------- 8 | class Node 9 | { 10 | public: 11 | int data; 12 | int hd; // to calculate the horizontal distance for Top View 13 | Node *left; 14 | Node *right; 15 | Node(int data) 16 | { 17 | this->data = data; 18 | left = NULL; 19 | right = NULL; 20 | hd = -1; 21 | } 22 | }; 23 | 24 | // ---------------------------------------------------------------- 25 | // to calculate the diameter of tree in O(n) time complexity 26 | // ---------------------------------------------------------------- 27 | class info 28 | { 29 | public: 30 | int diameter; 31 | int height; 32 | info(int d, int h) 33 | { 34 | diameter = d; 35 | height = h; 36 | } 37 | }; 38 | 39 | // ---------------------------------------------------------------- 40 | class Tree 41 | { 42 | 43 | public: 44 | int idx = -1; 45 | Node *buildTree(int nodes[]) 46 | { 47 | idx++; 48 | if (nodes[idx] == -1) 49 | { 50 | return NULL; 51 | } 52 | Node *root = new Node(nodes[idx]); 53 | root->left = buildTree(nodes); 54 | root->right = buildTree(nodes); 55 | return root; 56 | } 57 | void PrintPreOrder(Node *root) 58 | { 59 | if (root == NULL) 60 | { 61 | return; 62 | } 63 | cout << root->data << " "; 64 | PrintPreOrder(root->left); 65 | PrintPreOrder(root->right); 66 | } 67 | void printInOrder(Node *root) 68 | { 69 | if (root == NULL) 70 | { 71 | return; 72 | } 73 | printInOrder(root->left); 74 | cout << root->data << " "; 75 | printInOrder(root->right); 76 | } 77 | void PrintPostOrder(Node *root) 78 | { 79 | if (root == NULL) 80 | { 81 | return; 82 | } 83 | PrintPostOrder(root->left); 84 | PrintPostOrder(root->right); 85 | cout << root->data << " "; 86 | } 87 | void PrintLevelOrder(Node *root) 88 | { 89 | if (root == NULL) 90 | { 91 | return; 92 | } 93 | queue q; 94 | q.push(root); 95 | while (!q.empty()) 96 | { 97 | Node *curr = q.front(); 98 | q.pop(); 99 | cout << curr->data << " "; 100 | if (curr->left != NULL) 101 | { 102 | q.push(curr->left); 103 | } 104 | if (curr->right != NULL) 105 | { 106 | q.push(curr->right); 107 | } 108 | } 109 | } 110 | 111 | int Height(Node *root) 112 | { 113 | if (root == NULL) 114 | return 0; 115 | 116 | int leftHeight = Height(root->left); 117 | int rightHeight = Height(root->right); 118 | return max(leftHeight, rightHeight) + 1; 119 | } 120 | int NoOfNodes(Node *root) 121 | { 122 | if (root == NULL) 123 | return 0; 124 | int leftCount = NoOfNodes(root->left); 125 | int rightCount = NoOfNodes(root->right); 126 | return leftCount + rightCount + 1; 127 | } 128 | 129 | info diameter(Node *root) 130 | { 131 | if (root == NULL) 132 | { 133 | info base(0, 0); 134 | return base; 135 | } 136 | info left = diameter(root->left); 137 | info right = diameter(root->right); 138 | int height = max(left.height, right.height) + 1; 139 | int op1 = left.height + right.height + 1; 140 | int op2 = left.diameter; 141 | int op3 = right.diameter; 142 | int diameter = max(op1, max(op2, op3)); 143 | info ans(diameter, height); 144 | return ans; 145 | } 146 | 147 | void PrintTopViewofTree(Node *root) 148 | { 149 | if (root == NULL) 150 | { 151 | return; 152 | } 153 | map m; 154 | queue q; 155 | root->hd = 0; 156 | q.push(root); 157 | while (!q.empty()) 158 | { 159 | Node *curr = q.front(); 160 | q.pop(); 161 | int hd = curr->hd; 162 | if (m.count(hd) == 0) 163 | { 164 | m[hd] = curr->data; 165 | } 166 | if (curr->left != NULL) 167 | { 168 | curr->left->hd = hd - 1; 169 | q.push(curr->left); 170 | } 171 | if (curr->right != NULL) 172 | { 173 | curr->right->hd = hd + 1; 174 | q.push(curr->right); 175 | } 176 | } 177 | for (auto it : m) 178 | { 179 | cout << it.second << " "; 180 | } 181 | cout << endl; 182 | } 183 | 184 | void PrintBottomViewOfTree(Node *root) 185 | { 186 | if (root == NULL) 187 | { 188 | return; 189 | } 190 | map m; 191 | queue q; 192 | root->hd = 0; 193 | q.push(root); 194 | while (!q.empty()) 195 | { 196 | Node *curr = q.front(); 197 | q.pop(); 198 | int hd = curr->hd; 199 | m[hd] = curr->data; 200 | if (curr->left != NULL) 201 | { 202 | curr->left->hd = hd - 1; 203 | q.push(curr->left); 204 | } 205 | if (curr->right != NULL) 206 | { 207 | curr->right->hd = hd + 1; 208 | q.push(curr->right); 209 | } 210 | } 211 | for (auto it : m) 212 | { 213 | cout << it.second << " "; 214 | } 215 | cout << endl; 216 | } 217 | void KlevelOfTree(Node *root, int K) 218 | { 219 | if (root == NULL) 220 | { 221 | return; 222 | } 223 | if (K == 0) 224 | { 225 | cout << root->data << " "; 226 | return; 227 | } 228 | else 229 | { 230 | KlevelOfTree(root->left, K - 1); 231 | KlevelOfTree(root->right, K - 1); 232 | } 233 | } 234 | }; 235 | bool findPath(Node *root, std::vector &v, int dat) 236 | { 237 | if (root == NULL) 238 | { 239 | return false; 240 | } 241 | if (root->data == dat) 242 | { 243 | v.push_back(root->data); 244 | return true; 245 | } 246 | v.push_back(root->data); 247 | if (findPath(root->left, v, dat) || findPath(root->right, v, dat)) 248 | { 249 | return true; 250 | } 251 | v.pop_back(); 252 | return false; 253 | } 254 | 255 | int lowestCommonAncestor(Node *root1, int from, int to) 256 | { 257 | if (root1 == NULL) 258 | { 259 | return -1; 260 | } 261 | std::vector v1; 262 | std::vector v2; 263 | bool ans1 = findPath(root1, v1, from); 264 | bool ans2 = findPath(root1, v2, to); 265 | if (!ans1 || !ans2) 266 | { 267 | return -1; 268 | } 269 | size_t i = 0; 270 | while (i < v1.size() && i < v2.size()) 271 | { 272 | if (v1[i] != v2[i]) 273 | { 274 | break; 275 | } 276 | i++; 277 | } 278 | return v1[i - 1]; 279 | } 280 | int transformSumTree(Node *root) 281 | { 282 | if (root == nullptr) 283 | { 284 | return 0; 285 | } 286 | 287 | int originalValue = root->data; 288 | 289 | int leftSum = transformSumTree(root->left); 290 | int rightSum = transformSumTree(root->right); 291 | 292 | root->data = leftSum + rightSum; 293 | 294 | return originalValue + leftSum + rightSum; 295 | } 296 | 297 | //============================================================================ 298 | 299 | /* 300 | tree format 301 | tree 2 302 | / 303 | 1 304 | / \ 305 | 2 3 306 | / \ / \ 307 | 4 5 6 7 308 | \ 309 | 9 310 | */ 311 | int main() 312 | { 313 | int nodes[] = {2, 1, 2, 4, -1, -1, 5, -1, -1, 3, 6, -1, -1, 7, -1, 9, -1, -1, -1}; 314 | Tree t; 315 | Node *root = t.buildTree(nodes); 316 | 317 | t.PrintPreOrder(root); 318 | cout << endl; 319 | t.printInOrder(root); 320 | cout << endl; 321 | 322 | t.PrintPostOrder(root); 323 | cout << endl; 324 | 325 | t.PrintLevelOrder(root); 326 | cout << endl; 327 | 328 | cout << t.Height(root) << endl; 329 | 330 | cout << t.NoOfNodes(root) << endl; 331 | 332 | info ans = t.diameter(root); 333 | cout << ans.diameter << endl; 334 | cout << ans.height << endl; 335 | 336 | t.PrintTopViewofTree(root); 337 | 338 | t.PrintBottomViewOfTree(root); 339 | 340 | t.KlevelOfTree(root, 3); 341 | cout << endl; 342 | // int nodes2[] = {1, 2, 4, -1, -1, 5, -1, -1, 3, 6, -1, -1, 7, -1, 9, -1, -1,}; 343 | // Tree t2; 344 | // Node *root2 = t2.buildTree(nodes2); 345 | // cout << lowestCommonAncestor(root, 6, 9) << endl; 346 | 347 | transformSumTree(root); 348 | // t.PrintPreOrder(root); 349 | t.PrintLevelOrder(root); 350 | cout << endl; 351 | return 0; 352 | } -------------------------------------------------------------------------------- /C/3_sum.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | // Prints all triplets in arr[] with 0 sum 6 | void findTriplets(int arr[], int n) 7 | { 8 | bool found = false; 9 | for (int i = 0; i < n - 2; i++) { 10 | for (int j = i + 1; j < n - 1; j++) { 11 | for (int k = j + 1; k < n; k++) { 12 | if (arr[i] + arr[j] + arr[k] == 0) { 13 | printf("%d %d %d\n", arr[i], arr[j], 14 | arr[k]); 15 | found = true; 16 | } 17 | } 18 | } 19 | } 20 | 21 | // If no triplet with 0 sum found in array 22 | if (found == false) 23 | printf(" not exist \n"); 24 | } 25 | 26 | // Driver code 27 | int main() 28 | { 29 | int arr[] = { 0, -1, 2, -3, 1 }; 30 | int n = sizeof(arr) / sizeof(arr[0]); 31 | findTriplets(arr, n); 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /C/BinarySearch.c: -------------------------------------------------------------------------------- 1 | #include 2 | //Binary Search Algorithm 3 | 4 | int binarySearch(int arr[], int size, int target) { 5 | int left = 0; 6 | int right = size - 1; 7 | 8 | while (left <= right) { 9 | int mid = left + (right - left) / 2; 10 | 11 | // If the target is found at the middle, return its index 12 | if (arr[mid] == target) { 13 | return mid; 14 | } 15 | 16 | // If the target is greater, ignore the left half 17 | if (arr[mid] < target) { 18 | left = mid + 1; 19 | } 20 | 21 | // If the target is smaller, ignore the right half 22 | else { 23 | right = mid - 1; 24 | } 25 | } 26 | 27 | // Target not found in the array 28 | return -1; 29 | } 30 | 31 | int main() { 32 | int arr[] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}; 33 | int size = sizeof(arr) / sizeof(arr[0]); 34 | int target = 12; 35 | 36 | int result = binarySearch(arr, size, target); 37 | 38 | if (result != -1) { 39 | printf("Element %d found at index %d\n", target, result); 40 | } else { 41 | printf("Element %d not found in the array\n", target); 42 | } 43 | 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /C/Binary_Search_Tree_Traversal.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | 5 | // Defining the structure of the Binary Search Tree Nodes: 6 | struct node 7 | { 8 | struct node *left_child; 9 | int data; 10 | struct node *right_child; 11 | }; 12 | 13 | 14 | // All the neccessary function declaration: 15 | struct node *create_node(int); 16 | void insert_BST(struct node **root, int item); 17 | 18 | 19 | // Traversing Function Declaration: 20 | void preorder_display(struct node *); 21 | void inorder_display(struct node *); 22 | void postorder_display(struct node *); 23 | 24 | 25 | 26 | int main() 27 | { 28 | // Initializing the root node as NULL initially. 29 | struct node *root = NULL; 30 | 31 | // Inserting the nodes to the BST: 32 | insert_BST(&root, 45); 33 | insert_BST(&root, 36); 34 | insert_BST(&root, 76); 35 | insert_BST(&root, 23); 36 | insert_BST(&root, 89); 37 | insert_BST(&root, 115); 38 | insert_BST(&root, 98); 39 | insert_BST(&root, 39); 40 | insert_BST(&root, 41); 41 | insert_BST(&root, 56); 42 | insert_BST(&root, 69); 43 | insert_BST(&root, 48); 44 | 45 | printf("PRE-OREDR TRAVERSAL: "); 46 | preorder_display(root); 47 | printf("\n"); 48 | 49 | printf("IN-OREDR TRAVERSAL: "); 50 | inorder_display(root); 51 | printf("\n"); 52 | 53 | printf("POST-OREDR TRAVERSAL: "); 54 | postorder_display(root); 55 | return 0; 56 | } 57 | 58 | 59 | 60 | 61 | // Function for creating the nodes of BST: 62 | struct node *create_node(int item) 63 | { 64 | // Dynamic declaration of newnode: 65 | struct node *newnode = (struct node *)malloc(sizeof(struct node)); 66 | 67 | // Assigning the node value to newnode: 68 | newnode->data = item; 69 | 70 | // Initializing the left and right child as NULL 71 | newnode->left_child = NULL; 72 | newnode->right_child = NULL; 73 | return newnode; 74 | } 75 | 76 | 77 | 78 | 79 | // Function for inserting the node in the BST at its correct position: 80 | void insert_BST(struct node **root, int item) 81 | { 82 | struct node *current; // Current node being examined 83 | struct node *parent; // Parent of the current node 84 | 85 | // If the root node is NULL, then creating the root node: 86 | if (*root == NULL) 87 | { 88 | // Create a new node and set it as the root 89 | *root = create_node(item); 90 | } 91 | 92 | // else node is already present in the BST: 93 | else 94 | { 95 | current = *root; // Start with the root node 96 | parent = NULL; 97 | 98 | // Continue until a proper position for the new node is found 99 | while (1) 100 | { 101 | parent = current; // Update the parent as the current node 102 | 103 | // Check whether the new item should be placed in the left or right subtree 104 | if (item < current->data) 105 | { 106 | // Move to the left child 107 | current = current->left_child; 108 | 109 | // If the left child is NULL, insert the new node here and return 110 | if (current == NULL) 111 | { 112 | // Create a new node and set it as the left child 113 | parent->left_child = create_node(item); 114 | return; 115 | } 116 | } 117 | else 118 | { 119 | // Move to the right child 120 | current = current->right_child; 121 | 122 | // If the right child is NULL, insert the new node here and return 123 | if (current == NULL) 124 | { 125 | // Create a new node and set it as the right child 126 | parent->right_child = create_node(item); 127 | return; 128 | } 129 | } 130 | } 131 | } 132 | } 133 | 134 | 135 | 136 | 137 | // Pre-order Traversal: Root -> Left -> Right 138 | void preorder_display(struct node *root) 139 | { 140 | if (root != NULL) 141 | { 142 | printf("%d ", root->data); 143 | preorder_display(root->left_child); 144 | preorder_display(root->right_child); 145 | } 146 | } 147 | 148 | 149 | 150 | 151 | // In-order Traversal: Left -> Root -> Right 152 | void inorder_display(struct node *root) 153 | { 154 | if (root != NULL) 155 | { 156 | inorder_display(root->left_child); 157 | printf("%d ", root->data); 158 | inorder_display(root->right_child); 159 | } 160 | } 161 | 162 | 163 | 164 | 165 | // Post-order Traversal: Left -> Right-> Root 166 | void postorder_display(struct node *root) 167 | { 168 | 169 | if (root != NULL) 170 | { 171 | postorder_display(root->left_child); 172 | postorder_display(root->right_child); 173 | printf("%d ", root->data); 174 | } 175 | } 176 | -------------------------------------------------------------------------------- /C/Compute.C: -------------------------------------------------------------------------------- 1 | #include 2 | int main() { 3 | int dividend, divisor, quotient, remainder; 4 | printf("Enter dividend: "); 5 | scanf("%d", ÷nd); 6 | printf("Enter divisor: "); 7 | scanf("%d", &divisor); 8 | 9 | // Computes quotient 10 | quotient = dividend / divisor; 11 | 12 | // Computes remainder 13 | remainder = dividend % divisor; 14 | 15 | printf("Quotient = %d\n", quotient); 16 | printf("Remainder = %d", remainder); 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /C/To_find_keywords.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | void main() 6 | { 7 | int i,j,count=0; 8 | char c='\n'; 9 | char ch; 10 | FILE *fp; 11 | char Keyword[32][15]={ 12 | "extern","return","union","const","float","short", 13 | "auto","double","int","struct","break","else","long", 14 | "goto","sizeof","voltile","do","if","static","while", 15 | "unsigned","continue","for","signed","void","default", 16 | "switch","case","enum","register","typedef","char" 17 | }; 18 | fp=fopen("file.txt","w"); 19 | if(fp==NULL) 20 | { 21 | printf("File not exist"); 22 | exit(1); 23 | } 24 | for(i=0;i<32;i++) 25 | { 26 | for(j=0;j 2 | 3 | // Function to find and print pair 4 | int chkPair(int A[], int size, int x) 5 | { 6 | for (int i = 0; i < (size - 1); i++) { 7 | for (int j = (i + 1); j < size; j++) { 8 | if (A[i] + A[j] == x) { 9 | return 1; 10 | } 11 | } 12 | } 13 | 14 | return 0; 15 | } 16 | 17 | int main(void) 18 | { 19 | int A[] = { 0, -1, 2, -3, 1 }; 20 | int x = -2; 21 | int size = sizeof(A) / sizeof(A[0]); 22 | 23 | if (chkPair(A, size, x)) { 24 | printf("Yes\n"); 25 | } 26 | else { 27 | printf("No\n"); 28 | } 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /C/binary_search.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int binarySearch(int arr[], int l, int r, int x) 4 | { 5 | while (l <= r) { 6 | int m = l + (r - l) / 2; 7 | 8 | // Check if x is present at mid 9 | if (arr[m] == x) 10 | return m; 11 | 12 | // If x greater, ignore left half 13 | if (arr[m] < x) 14 | l = m + 1; 15 | 16 | // If x is smaller, ignore right half 17 | else 18 | r = m - 1; 19 | } 20 | 21 | // If we reach here, then element was not present 22 | return -1; 23 | } 24 | 25 | int binarySearchRecursive(int arr[], int l, int r,int x){ 26 | if(l>r) return 0; 27 | int mid=l+(r-l)/2; 28 | if(arr[mid]==x){ 29 | return mid; 30 | } 31 | if(arr[mid]>x){ 32 | return binarySearchRecursive(arr,l,mid,x); 33 | }else{ 34 | return binarySearchRecursive(arr,mid,r,x); 35 | } 36 | } 37 | // Driver code 38 | int main(void) 39 | { 40 | int arr[] = {1, 2, 3, 4, 10, 40,87,25 }; 41 | int n = sizeof(arr) / sizeof(arr[0]); 42 | int x = 10; 43 | // int result = binarySearch(arr, 0, n - 1, x); 44 | int result = binarySearchRecursive(arr, 0, n - 1, x); 45 | (result == -1) ? printf("Element is not present" 46 | " in array") 47 | : printf("Element is present at " 48 | "index %d", 49 | result); 50 | return 0; 51 | } -------------------------------------------------------------------------------- /C/bubble_sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | void main() 3 | { 4 | int a[5],n,i,j,temp; 5 | printf("Enter size of array : "); 6 | scanf("%d",&n); 7 | printf("Enter %d elements ",n); 8 | for(i=0;i1;i--) 12 | { 13 | for(j=0;ja[j+1]) 16 | { 17 | temp = a[j+1]; 18 | a[j+1] = a[j]; 19 | a[j] = temp; 20 | } 21 | } 22 | } 23 | 24 | printf("Array after sorting\n"); 25 | for(i=0;i 2 | 3 | int main() { 4 | char operator; 5 | float num1, num2, result; 6 | 7 | printf("Enter an operator (+, -, *, /): "); 8 | scanf("%c", &operator); 9 | printf("Enter two numbers: "); 10 | scanf("%f %f", &num1, &num2); 11 | 12 | switch (operator) { 13 | case '+': 14 | result = num1 + num2; 15 | break; 16 | case '-': 17 | result = num1 - num2; 18 | break; 19 | case '*': 20 | result = num1 * num2; 21 | break; 22 | case '/': 23 | result = num1 / num2; 24 | break; 25 | default: 26 | printf("Invalid operator!\n"); 27 | return 1; 28 | } 29 | 30 | printf("The result is: %.2f\n", result); 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /C/createpattern: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | printf("Pattern of stars:\n"); 5 | for (int i = 0; i < 5; i++) { 6 | for (int j = 0; j <= i; j++) { 7 | printf("*"); 8 | } 9 | printf("\n"); 10 | } 11 | 12 | printf("\nPattern of numbers:\n"); 13 | for (int i = 0; i < 5; i++) { 14 | for (int j = 0; j <= i; j++) { 15 | printf("%d", j); 16 | } 17 | printf("\n"); 18 | } 19 | 20 | printf("\nPattern of characters:\n"); 21 | for (int i = 0; i < 5; i++) { 22 | for (int j = 0; j <= i; j++) { 23 | printf("%c", 'a' + j); 24 | } 25 | printf("\n"); 26 | } 27 | 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /C/first.c: -------------------------------------------------------------------------------- 1 | bnvhggjtgiluy 2 | -------------------------------------------------------------------------------- /C/infix_to_postfix.c: -------------------------------------------------------------------------------- 1 | //limitation= no parenthesis 2 | #include 3 | #include 4 | #include 5 | #define MAX 50 6 | 7 | typedef struct { 8 | int top; 9 | int items[MAX]; 10 | }stack; 11 | 12 | void push(stack* s,int value){ 13 | if(s->top==MAX-1){ 14 | printf("stack overflow can't push"); 15 | exit(1); 16 | } 17 | s->items[++s->top]=value; 18 | } 19 | 20 | int pop(stack* s){ 21 | if(s->top==-1){ 22 | printf("stack underflow can't pop"); 23 | // return 1; 24 | exit(1); 25 | } 26 | return s->items[s->top--]; 27 | } 28 | int isEmpty(stack* s){ 29 | if(s->top==-1){ 30 | return 1; 31 | } 32 | return 0; 33 | } 34 | int stackTop(stack*s){ 35 | return s->items[s->top]; 36 | } 37 | int pOrder(char a){ 38 | switch(a){ 39 | 40 | case '^': 41 | return 0; 42 | case '*': 43 | return 1; 44 | case '/': 45 | return 1; 46 | case '+': 47 | return 2; 48 | case '-': 49 | return 2; 50 | } 51 | } 52 | 53 | int preced(char a,char b){ 54 | // return true if a>b in precedence 55 | if(pOrder(a)>pOrder(b)) return 0; 56 | return 1; 57 | 58 | } 59 | void infix_to_postfix(char* infix,char* postfix){ 60 | int n=strlen(infix); 61 | stack stk; 62 | stk.top=-1; 63 | int k=0; //k=index of postfix 64 | for(int i=0;i='0'){ 66 | postfix[k++]=infix[i]; 67 | 68 | } 69 | else{ 70 | while(!isEmpty(&stk) && preced(stackTop(&stk),infix[i])){ 71 | //if stackTop is greater in precedence then current element the start popping 72 | char opr=pop(&stk); 73 | postfix[k++]=opr; 74 | } 75 | 76 | push(&stk,infix[i]); 77 | } 78 | } 79 | while(!isEmpty(&stk)){ 80 | postfix[k++]=pop(&stk); 81 | 82 | } 83 | 84 | } 85 | 86 | int main() 87 | { 88 | stack stk; 89 | stk.top=-1; 90 | char infix[MAX]; 91 | printf("enter a valid infix expression:"); 92 | scanf("%s",infix); 93 | char postfix[MAX]; 94 | infix_to_postfix(infix,postfix); 95 | printf("postfix=%s \n",postfix); 96 | 97 | return 0; 98 | } 99 | 100 | 101 | -------------------------------------------------------------------------------- /C/linear_search.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int a[10],n,i,ele; 5 | printf("Enter size of array : "); 6 | scanf("%d",&n); 7 | printf("Enter %d elements ",n); 8 | for(i=0;i 2 | #include 3 | #include 4 | 5 | #define PASSWORD_LENGTH 12 6 | 7 | char password[PASSWORD_LENGTH + 1]; 8 | 9 | int main() { 10 | srand((unsigned int)(time(NULL))); 11 | 12 | char characters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+=-"; 13 | 14 | for (int i = 0; i < PASSWORD_LENGTH; i++) { 15 | int random_index = rand() % (sizeof(characters) / sizeof(characters[0])); 16 | password[i] = characters[random_index]; 17 | } 18 | 19 | password[PASSWORD_LENGTH] = '\0'; 20 | 21 | printf("Your random password is: %s\n", password); 22 | 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /C/quick_sort.c: -------------------------------------------------------------------------------- 1 | // C code to implement quicksort 2 | 3 | #include 4 | 5 | // Function to swap two elements 6 | void swap(int* a, int* b) 7 | { 8 | int t = *a; 9 | *a = *b; 10 | *b = t; 11 | } 12 | 13 | // Partition the array using the last element as the pivot 14 | int partition(int arr[], int low, int high) 15 | { 16 | // Choosing the pivot 17 | int pivot = arr[high]; 18 | 19 | // Index of smaller element and indicates 20 | // the right position of pivot found so far 21 | int i = (low - 1); 22 | 23 | for (int j = low; j <= high - 1; j++) { 24 | 25 | // If current element is smaller than the pivot 26 | if (arr[j] < pivot) { 27 | 28 | // Increment index of smaller element 29 | i++; 30 | swap(&arr[i], &arr[j]); 31 | } 32 | } 33 | swap(&arr[i + 1], &arr[high]); 34 | return (i + 1); 35 | } 36 | 37 | // The main function that implements QuickSort 38 | // arr[] --> Array to be sorted, 39 | // low --> Starting index, 40 | // high --> Ending index 41 | void quickSort(int arr[], int low, int high) 42 | { 43 | if (low < high) { 44 | 45 | // pi is partitioning index, arr[p] 46 | // is now at right place 47 | int pi = partition(arr, low, high); 48 | 49 | // Separately sort elements before 50 | // partition and after partition 51 | quickSort(arr, low, pi - 1); 52 | quickSort(arr, pi + 1, high); 53 | } 54 | } 55 | 56 | // Driver code 57 | int main() 58 | { 59 | int arr[] = { 10, 7, 8, 9, 1, 5 }; 60 | int N = sizeof(arr) / sizeof(arr[0]); 61 | 62 | // Function call 63 | quickSort(arr, 0, N - 1); 64 | printf("Sorted array: \n"); 65 | for (int i = 0; i < N; i++) 66 | printf("%d ", arr[i]); 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /C/rps.c: -------------------------------------------------------------------------------- 1 | //simple rock paper scissor game in c 2 | 3 | #include 4 | #include 5 | #include 6 | int generateRandomNumber(int n) 7 | { 8 | srand(time(NULL)); 9 | return rand() % n; 10 | } 11 | 12 | int greater(char c1, char c2) 13 | { 14 | if (c1 == c2) 15 | { 16 | return -1; 17 | } 18 | else if (c1 == 'r' && c2 == 's') 19 | { 20 | return 1; 21 | } 22 | else if (c2 == 'r' && c1 == 's') 23 | { 24 | return 0; 25 | } 26 | else if (c1 == 'p' && c2 == 'r') 27 | { 28 | return 1; 29 | } 30 | else if (c2 == 'p' && c1 == 'r') 31 | { 32 | return 0; 33 | } 34 | 35 | else if (c1 == 's' && c2 == 'p') 36 | { 37 | return 1; 38 | } 39 | else if (c2 == 's' && c1 == 'p') 40 | { 41 | return 0; 42 | } 43 | } 44 | int main() 45 | { 46 | int playerScore = 0, compScore = 0, temp; 47 | char playerChar, compChar; 48 | char dict[] = {'r', 'p', 's'}; 49 | printf("\tWelcome to the Rock Paper Scissors\n"); 50 | printf("\t----------------------------------\n\n"); 51 | 52 | for (int i = 0; i < 3; i++) 53 | { 54 | // Take player input 55 | printf("Press 1 for Rock, Press 2 for Paper, Press 3 for Scissors\n\n"); 56 | printf("\tPlayer's turn: "); 57 | scanf("%d", &temp); 58 | getchar(); 59 | playerChar = dict[temp - 1]; 60 | printf(" -----------------\n"); 61 | printf("| You choose: %c |\n", playerChar); 62 | printf(" -----------------\n\n"); 63 | 64 | //computer 65 | printf("Press 1 for Rock, Press 2 for Paper, Press 3 for Scissors\n\n"); 66 | printf("\tComputer's turn\n"); 67 | temp = generateRandomNumber(3) + 1; 68 | compChar = dict[temp - 1]; 69 | printf(" --------------------\n"); 70 | printf("| Computer choose: %c |\n", compChar); 71 | printf(" --------------------\n\n"); 72 | 73 | // compater character and increment the score 74 | if (greater(compChar, playerChar) == 1) 75 | { 76 | compScore++; 77 | printf("\t\tComputer Got It!\n\n"); 78 | } 79 | else if (greater(compChar, playerChar) == -1) 80 | { 81 | compScore++; 82 | playerScore++; 83 | printf("\t\tIt's a draw. Both got 1 point!\n\n"); 84 | } 85 | else 86 | { 87 | playerScore++; 88 | printf("\t\tYou Got It!\n\n"); 89 | } 90 | 91 | printf(" -------------\n"); 92 | printf("| You: %d |\n", playerScore); 93 | printf("| Computer: %d |\n", compScore); 94 | printf(" -------------\n\n"); 95 | 96 | printf("===========================================================\n\n"); 97 | } 98 | 99 | printf(" -----------------\n"); 100 | printf("| Final Score |\n"); 101 | printf(" -----------------\n"); 102 | printf("| You | Computer |\n"); 103 | printf("|------|----------|\n"); 104 | printf("| %d | %d |\n", playerScore, compScore); 105 | printf(" -----------------\n\n"); 106 | 107 | // compare score 108 | if (playerScore > compScore) 109 | { 110 | printf("\n\t -------------------\n"); 111 | printf("\t| You Win the match |\n"); 112 | printf("\t -------------------\n"); 113 | } 114 | else if (playerScore < compScore) 115 | { 116 | printf("\n\t ------------------------\n"); 117 | printf("\t| Computer Win the match |\n"); 118 | printf("\t ------------------------\n"); 119 | } 120 | else 121 | { 122 | printf("\n\t -------------\n"); 123 | printf("\t| It's a draw |\n"); 124 | printf("\t -------------\n"); 125 | } 126 | 127 | return 0; 128 | } -------------------------------------------------------------------------------- /C/rps.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/csubhasundar/CodingPractice-Hacktoberfest23/65df5909deaafbd8102ac710fa34f31ffb2e4b29/C/rps.exe -------------------------------------------------------------------------------- /C/self_printing_code.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void self_print(); 4 | void main(){self_print();} 5 | 6 | void self_print() 7 | { 8 | char c; // to print the source code 9 | FILE *file = fopen(__FILE__, "r"); // __FILE__ gets the location of the current C program file 10 | do { 11 | c = fgetc(file); //printing the contents of the file 12 | putchar(c); 13 | } 14 | while (c != EOF); 15 | fclose(file); 16 | } 17 | 18 | -------------------------------------------------------------------------------- /C/sieveOfEratosthenes.c: -------------------------------------------------------------------------------- 1 | // C program to print all primes smaller than or equal to 2 | // The sieve of Eratosthenes is one of the most efficient ways to find 3 | // all primes smaller than n when n is smaller than 10 million or so. 4 | 5 | // C program to print all primes smaller than or equal to 6 | // n using Sieve of Eratosthenes 7 | #include 8 | #include 9 | #include 10 | 11 | void SieveOfEratosthenes(int n) 12 | { 13 | bool prime[n + 1]; 14 | memset(prime, true, sizeof(prime)); 15 | 16 | for (int p = 2; p * p <= n; p++) { 17 | if (prime[p] == true) { 18 | for (int i = p * p; i <= n; i += p) 19 | prime[i] = false; 20 | } 21 | } 22 | 23 | for (int p = 2; p <= n; p++) 24 | if (prime[p]) 25 | printf("%d ",p); 26 | } 27 | 28 | // Driver Code 29 | int main() 30 | { 31 | int n = 30; 32 | printf("Following are the prime numbers smaller than or equal to %d \n", n); 33 | SieveOfEratosthenes(n); 34 | return 0; 35 | } 36 | 37 | -------------------------------------------------------------------------------- /C/sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | //Initialize array 6 | int arr[] = {5, 2, 8, 7, 1}; 7 | int temp = 0; 8 | 9 | //Calculate length of array arr 10 | int length = sizeof(arr)/sizeof(arr[0]); 11 | 12 | //Displaying elements of original array 13 | printf("Elements of original array: \n"); 14 | for (int i = 0; i < length; i++) { 15 | printf("%d ", arr[i]); 16 | } 17 | 18 | //Sort the array in ascending order 19 | for (int i = 0; i < length; i++) { 20 | for (int j = i+1; j < length; j++) { 21 | if(arr[i] > arr[j]) { 22 | temp = arr[i]; 23 | arr[i] = arr[j]; 24 | arr[j] = temp; 25 | } 26 | } 27 | } 28 | 29 | printf("\n"); 30 | 31 | //Displaying elements of array after sorting 32 | printf("Elements of array sorted in ascending order: \n"); 33 | for (int i = 0; i < length; i++) { 34 | printf("%d ", arr[i]); 35 | } 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Follow the below format to add your name: 2 | 3 | 4 | 5 | ```markdown 6 | #### Name: 7 | 8 | - GitHub: https://github.com// 9 | ``` 10 | 11 | ```markdown 12 | #### Name: Subha Sundar Chakraborty 13 | 14 | - GitHub: https://github.com/csubhasundar 15 | ``` 16 | 17 | ```markdown 18 | #### Name: Anuj Dhar 19 | 20 | - GitHub: https://github.com/AnujDhar27 21 | ``` 22 | -------------------------------------------------------------------------------- /Java/123Pattern.java: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/132-pattern/description/ 2 | 3 | class Solution { 4 | public boolean find132pattern(int[] nums) { 5 | if(nums.length<3) return false; 6 | 7 | int[] minI = new int[nums.length]; 8 | minI[0] = nums[0]; 9 | 10 | for(int i=1;i stack = new Stack<>(); 15 | 16 | for(int j=nums.length-1;j>=0;j--){ 17 | if(nums[j] > minI[j]){ 18 | while(!stack.isEmpty() && stack.peek() <= minI[j]){ 19 | stack.pop(); 20 | } 21 | 22 | if(!stack.isEmpty() && stack.peek() < nums[j]){ 23 | return true; 24 | } 25 | 26 | stack.push(nums[j]); 27 | } 28 | } 29 | return false; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Java/3Sum.java: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/3sum/ 2 | 3 | class Solution { 4 | public List> threeSum(int[] nums) { 5 | int target = 0; 6 | Arrays.sort(nums); 7 | Set> set = new HashSet<>(); 8 | List> ans = new ArrayList<>(); 9 | 10 | for(int i=0; i Object of abstract class can not be implemented 48 | child c = new child(); 49 | c.family(); 50 | c.name(); 51 | c.title("name"); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Java/AddTwoNumbers.java: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/add-two-numbers/ 2 | 3 | class Solution { 4 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 5 | 6 | ListNode dummy = new ListNode(0); 7 | ListNode temp = dummy; 8 | 9 | int carry = 0; 10 | while(l1 != null || l2 != null || carry == 1) 11 | { 12 | int sum = 0; 13 | if(l1 != null){ 14 | sum += l1.val; 15 | l1 = l1.next; 16 | } 17 | if(l2 != null){ 18 | sum += l2.val; 19 | l2 = l2.next; 20 | } 21 | 22 | sum += carry; 23 | carry = sum/ 10; 24 | ListNode node = new ListNode(sum % 10); 25 | temp.next = node; 26 | temp = temp.next; 27 | } 28 | return dummy.next; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Java/AllArray.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Scanner; 3 | // array 4 | public class AllArray{ 5 | // function for taking input of elements of an array 6 | public static void input(int marks[]){ 7 | Scanner sc = new Scanner(System.in); 8 | for(int i =0;imax){ 36 | max=arr[i]; 37 | 38 | } 39 | 40 | } 41 | System.out.println(("maximu number in the given arr is "+ max )); 42 | } 43 | 44 | // code for binary seacrh 45 | public static void binarysearch (int nums[],int key){ 46 | int start = 0,end=nums.length-1; 47 | int middle = (start+end)/2; 48 | 49 | while(middle!=start||middle!=end){ 50 | if(nums[middle]==key){ 51 | System.out.println("Key Find Succ at:- " + middle); 52 | break; 53 | } 54 | else if(nums[middle]max){ 122 | max=sum; 123 | } 124 | j++; 125 | } 126 | i++; 127 | } 128 | System.out.println("the maximum sum of subarray is : "+ max); 129 | } 130 | // kadans algorith 131 | public static void kadans(int nums[]){ 132 | int count_sum=0,max_sum=Integer.MIN_VALUE,j=0; 133 | while(jmax_sum){ 139 | max_sum=count_sum; 140 | } 141 | j++; 142 | } 143 | System.out.println("Maximus Sum Of The Given SubArray Is :" + max_sum); 144 | } 145 | 146 | // Bubble Sorting 147 | public static void bubblesort(int [] arr){ 148 | int i=0; 149 | while(iarr[i]){ 170 | 171 | } 172 | } 173 | } 174 | // merge sorted array 175 | public static void merge(int[] nums1, int m, int[] nums2, int n) { 176 | int a1=0,a2=0; 177 | int arr[]= new int[n+m]; 178 | for(int i=0;inums2[a2]){ 181 | arr[i]=nums2[a2]; 182 | a2++; 183 | continue; 184 | } 185 | else if(nums1[a1] arr[j + 1]) { 7 | int temp = arr[j]; 8 | arr[j] = arr[j + 1]; 9 | arr[j + 1] = temp; 10 | } 11 | } 12 | } 13 | } 14 | 15 | public static void main(String[] args) { 16 | int[] arr = {64, 34, 25, 12, 22, 11, 90}; 17 | bubbleSort(arr); 18 | System.out.println("Sorted array:"); 19 | for (int i = 0; i < arr.length; i++) { 20 | System.out.print(arr[i] + " "); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Java/DoubleEndedQueue.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayDeque; 2 | import java.util.Deque; 3 | import java.util.Scanner; 4 | 5 | public class DoubleEndedQueue { 6 | public static void main(String[] args) { 7 | // Create a deque 8 | Deque deque = new ArrayDeque<>(); 9 | 10 | Scanner scanner = new Scanner(System.in); 11 | 12 | while (true) { 13 | System.out.println("Choose an operation:"); 14 | System.out.println("1. Add element at the front"); 15 | System.out.println("2. Add element at the back"); 16 | System.out.println("3. Remove element from the front"); 17 | System.out.println("4. Remove element from the back"); 18 | System.out.println("5. Exit"); 19 | 20 | int choice = scanner.nextInt(); 21 | scanner.nextLine(); // Consume the newline character 22 | 23 | switch (choice) { 24 | case 1: 25 | System.out.print("Enter the element to add at the front: "); 26 | String frontElement = scanner.nextLine(); 27 | deque.addFirst(frontElement); 28 | break; 29 | case 2: 30 | System.out.print("Enter the element to add at the back: "); 31 | String backElement = scanner.nextLine(); 32 | deque.addLast(backElement); 33 | break; 34 | case 3: 35 | if (!deque.isEmpty()) { 36 | String removedFront = deque.removeFirst(); 37 | System.out.println("Removed from the front: " + removedFront); 38 | } else { 39 | System.out.println("Deque is empty."); 40 | } 41 | break; 42 | case 4: 43 | if (!deque.isEmpty()) { 44 | String removedBack = deque.removeLast(); 45 | System.out.println("Removed from the back: " + removedBack); 46 | } else { 47 | System.out.println("Deque is empty."); 48 | } 49 | break; 50 | case 5: 51 | scanner.close(); 52 | System.exit(0); 53 | default: 54 | System.out.println("Invalid choice. Please select a valid operation."); 55 | break; 56 | } 57 | 58 | System.out.println("Current Deque: " + deque); 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /Java/GCD.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class GCD { 4 | public static void main(String[] args) { 5 | Scanner scanner = new Scanner(System.in); 6 | System.out.print("Enter the first number: "); 7 | int num1 = scanner.nextInt(); 8 | System.out.print("Enter the second number: "); 9 | int num2 = scanner.nextInt(); 10 | scanner.close(); 11 | 12 | int gcd = calculateGCD(num1, num2); 13 | System.out.println("GCD of " + num1 + " and " + num2 + " is " + gcd); 14 | } 15 | 16 | // Function to calculate the GCD using the Euclidean algorithm 17 | public static int calculateGCD(int a, int b) { 18 | if (b == 0) { 19 | return a; 20 | } 21 | return calculateGCD(b, a % b); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Java/Leaders.java: -------------------------------------------------------------------------------- 1 | //Leader in an Array: 2 | //If a member in the array is larger than every member on 3 | //its right side, it is considered an Leader Element of the 4 | //array. 5 | //An array's rightmost element is always the Leader. 6 | 7 | import java.util.*; 8 | class Leaders{ 9 | public static ArrayList 10 | printLeadersBruteForce(int[] arr, int n){ 11 | ArrayList ans= new ArrayList<>(); 12 | int max = arr[n - 1]; 13 | ans.add(arr[n-1]); 14 | for (int i = n - 2; i >= 0; i--) 15 | if (arr[i] > max) { 16 | ans.add(arr[i]); 17 | max = arr[i]; 18 | } 19 | return ans; 20 | } 21 | public static void main(String args[]) 22 | { 23 | int n = 6; 24 | int arr[]= {1, 2, 12, 13, 0, 6}; 25 | ArrayList ans= 26 | printLeadersBruteForce(arr,n); 27 | Collections.sort(ans,Collections.reverseOrder()); 28 | for (int i = 0; i < ans.size(); i++) 29 | { 30 | System.out.print(ans.get(i)+" "); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /Java/Linkedlist_Codestudio/Addone.java: -------------------------------------------------------------------------------- 1 | package Linkedlist_Codestudio; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class Addone { 6 | static class Node{ 7 | int data; 8 | Node next; 9 | Node(int data){ 10 | this.data=data; 11 | this.next=null; 12 | } 13 | } 14 | 15 | public static void main(String[] args) { 16 | 17 | int[] arr1={5,6,3}; 18 | int[] arr2={8,4,2}; 19 | Node head1=createll(arr1); 20 | Node head2=createll(arr2); 21 | Node temp1=head1; 22 | Node temp2=head2; 23 | int sum1=0,sum2=0,sum=0; 24 | ArrayList ans=new ArrayList<>(); 25 | while (temp1!=null && temp2!=null){ 26 | sum+= temp1.data+temp2.data; 27 | ans.add(sum); 28 | temp1=temp1.next; 29 | temp2=temp2.next; 30 | sum=0; 31 | } 32 | 33 | Node h=createLL(ans); 34 | printLL(h); 35 | 36 | 37 | 38 | 39 | } 40 | 41 | public static Node createLL(ArrayList data){ 42 | if(data==null || data.size()==0){ 43 | return null; 44 | } 45 | 46 | Node head=new Node(data.get(0)); 47 | Node temp=head; 48 | 49 | for (int i = 1; i < data.size(); i++) { 50 | temp.next=new Node(data.get(i)); 51 | temp=temp.next; 52 | } 53 | return head; 54 | 55 | } 56 | 57 | private static Node createll(int[] data) { 58 | 59 | if(data==null || data.length==0){ 60 | return null; 61 | } 62 | Node head=new Node(data[0]); 63 | Node temp=head; 64 | for (int i = 1; i < data.length; i++) { 65 | temp.next=new Node(data[i]); 66 | temp=temp.next; 67 | } 68 | return head; 69 | 70 | } 71 | public static void printLL(Node head){ 72 | 73 | Node temp=head; 74 | while (temp!=null){ 75 | System.out.print(temp.data+" => "); 76 | temp=temp.next; 77 | } 78 | System.out.print("null"); 79 | System.out.println(); 80 | } 81 | 82 | } 83 | -------------------------------------------------------------------------------- /Java/Linkedlist_Codestudio/DeleteLastNode.java: -------------------------------------------------------------------------------- 1 | package Linkedlist_Codestudio; 2 | 3 | import com.sun.source.doctree.StartElementTree; 4 | 5 | public class DeleteLastNode { 6 | 7 | static class Node{ 8 | int data; 9 | Node next; 10 | 11 | 12 | Node(int data){ 13 | 14 | this.data=data; 15 | this.next=null; 16 | 17 | } 18 | } 19 | public static void printll(Node head){ 20 | Node temp=head; 21 | while (temp!=null){ 22 | System.out.print(temp.data+" -> "); 23 | temp=temp.next; 24 | } 25 | System.out.print("NULL"); 26 | } 27 | public static void main(String[] args) { 28 | 29 | Node head=new Node(1); 30 | head.next=new Node(2); 31 | head.next.next=new Node(3); 32 | head.next.next.next=new Node(4); 33 | head.next.next.next.next=new Node(5); 34 | 35 | 36 | 37 | Node temp=head; 38 | 39 | while (temp.next.next!=null){ 40 | System.out.print(temp.data+ "-> "); 41 | temp=temp.next; 42 | } 43 | // System.out.println(temp.data); 44 | temp.next=null; 45 | printll(head); 46 | 47 | 48 | 49 | 50 | 51 | 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Java/Linkedlist_Codestudio/DeleteNodeUsingOnePointer.java: -------------------------------------------------------------------------------- 1 | package Linkedlist_Codestudio; 2 | 3 | import java.util.concurrent.TimeoutException; 4 | 5 | public class DeleteNodeUsingOnePointer { 6 | static class Node{ 7 | 8 | int data; 9 | Node next; 10 | Node(int data){ 11 | 12 | this.data=data; 13 | this.next=null; 14 | 15 | } 16 | } 17 | public static void main(String[] args) { 18 | 19 | Node head=new Node(1); 20 | head.next=new Node(2); 21 | head.next.next=new Node(3); 22 | head.next.next.next=new Node(4); 23 | head.next.next.next.next=new Node(5); 24 | 25 | printNodes(head); 26 | 27 | // int counter=1; 28 | // Node curr=head; 29 | // while (counter < 3) { 30 | // if (curr == null || curr.next == null) { 31 | // // Handle the case where there are not enough nodes to delete the 3rd node 32 | // return; 33 | // } 34 | // curr = curr.next; 35 | // counter++; 36 | // } 37 | // 38 | // delete3rd(curr); 39 | // printNodes(head); 40 | 41 | } 42 | 43 | private static void delete3rd(Node curr) { 44 | 45 | // 46 | // if(curr.next==null || curr.next==null){ 47 | // return; 48 | // } 49 | curr.data=curr.next.data; 50 | curr.next=curr.next.next; 51 | 52 | 53 | 54 | } 55 | 56 | 57 | private static void printNodes(Node head) { 58 | Node temp=head; 59 | while (temp!=null){ 60 | 61 | System.out.print(temp.data+" -> "); 62 | temp=temp.next; 63 | // if(temp.next==null){ 64 | // System.out.print("NULL"); 65 | // break; 66 | // 67 | // } 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /Java/Linkedlist_Codestudio/DoubleLL.java: -------------------------------------------------------------------------------- 1 | package Linkedlist_Codestudio; 2 | 3 | public class DoubleLL { 4 | 5 | static class Node{ 6 | int data; 7 | Node prev; 8 | Node next; 9 | 10 | Node(int data){ 11 | this.data=data; 12 | this.prev=null; 13 | this.next=null; 14 | } 15 | } 16 | public static Node head; 17 | public static Node tail; 18 | public static int size; 19 | 20 | public void addFirst(int data){ 21 | Node newnode=new Node(data); 22 | if(head==null){ 23 | head=tail=newnode; 24 | return; 25 | } 26 | newnode.next=head; 27 | head.prev=newnode; 28 | head=newnode; 29 | } 30 | public static void main(String[] args) { 31 | 32 | 33 | DoubleLL dl=new DoubleLL(); 34 | dl.addFirst(5); 35 | dl.addFirst(4); 36 | dl.addFirst(3); 37 | dl.addFirst(2); 38 | dl.addFirst(1); 39 | 40 | Node temp=head; 41 | while (temp!=null){ 42 | System.out.print(temp.data+" -> "); 43 | temp=temp.next; 44 | } 45 | 46 | 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Java/Linkedlist_Codestudio/FindMiddle.java: -------------------------------------------------------------------------------- 1 | package Linkedlist_Codestudio; 2 | 3 | public class FindMiddle { 4 | static class Node{ 5 | int data; 6 | Node next; 7 | Node(int data){ 8 | this.data=data; 9 | this.next=null; 10 | } 11 | } 12 | public static Node head; 13 | public static Node tail; 14 | 15 | public static void main(String[] args) { 16 | 17 | 18 | head=new Node(1); 19 | Node newnode=new Node(2); 20 | head.next=newnode; 21 | head.next.next=new Node(3); 22 | head.next.next.next=new Node(4); 23 | head.next.next.next.next=new Node(5); 24 | head.next.next.next.next.next=new Node(6); 25 | 26 | // Node rev=reverseLL(head); 27 | // printLL(rev); 28 | 29 | findmidofLL(head); 30 | 31 | 32 | 33 | 34 | } 35 | 36 | private static Node findmidofLL(Node head) { 37 | 38 | Node temp=head; 39 | int n=0; 40 | while (temp!=null){ 41 | temp=temp.next; 42 | n++; 43 | } 44 | temp=head; 45 | System.out.println(n); 46 | for(int i = 0; i < n / 2; i++) { 47 | System.out.print(temp.data+"->"); 48 | temp = temp.next; 49 | } 50 | return temp; 51 | } 52 | 53 | private static Node reverseLL(Node head) { 54 | Node prev = null; 55 | Node curr = head; 56 | Node next; 57 | while (curr != null) { 58 | next = curr.next; 59 | curr.next = prev; 60 | prev = curr; 61 | curr = next; 62 | } 63 | return prev; // Return the new head of the reversed list 64 | } 65 | private static void printLL(Node head) { 66 | Node temp=head; 67 | 68 | while (temp!=null){ 69 | System.out.print(temp.data+" -> "); 70 | temp=temp.next; 71 | 72 | } 73 | System.out.print("null"); 74 | } 75 | } 76 | 77 | -------------------------------------------------------------------------------- /Java/Linkedlist_Codestudio/Linkedlistremovenodefromlast.java: -------------------------------------------------------------------------------- 1 | package Linkedlist_Codestudio; 2 | 3 | public class Linkedlistremovenodefromlast { 4 | 5 | static class Node 6 | { 7 | int data; 8 | Node next; 9 | Node(int data) 10 | { 11 | this.data=data; 12 | this.next=null; 13 | } 14 | } 15 | 16 | public static void main(String[] args) { 17 | 18 | Node head=new Node(1); 19 | head.next=new Node(2); 20 | head.next.next=new Node(3); 21 | head.next.next.next=new Node(4); 22 | head.next.next.next.next=new Node(5); 23 | 24 | deletemiddlenode(head); 25 | 26 | Node temp=head; 27 | while (temp!=null){ 28 | System.out.print(temp.data+" -> "); 29 | temp=temp.next; 30 | } 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | } 42 | 43 | private static void deletemiddlenode(Node head) { 44 | 45 | if(head==null || head.next==null){ 46 | return; 47 | } 48 | Node slow=head; 49 | Node fast=head; 50 | Node prev=null; 51 | 52 | while (fast!=null && fast.next!=null){ 53 | 54 | fast=fast.next.next; 55 | prev=slow; 56 | slow=slow.next; 57 | 58 | } 59 | 60 | prev.next=slow.next; 61 | } 62 | 63 | private static Node reverse(Node head) { 64 | 65 | Node prev=null; 66 | Node curr=head; 67 | Node next; 68 | 69 | while (curr!=null){ 70 | next=curr.next; 71 | curr.next=prev; 72 | prev=curr; 73 | curr=next; 74 | } 75 | return prev; 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /Java/Linkedlist_Codestudio/MaxSubarrSum.java: -------------------------------------------------------------------------------- 1 | package Linkedlist_Codestudio; 2 | 3 | public class MaxSubarrSum { 4 | public static void main(String[] args) { 5 | int[] arr={1,2,3,4}; 6 | int n=arr.length; 7 | 8 | int maxsum=arr[0]; 9 | int currsum=arr[0]; 10 | 11 | for (int i = 1; i < n; i++) { 12 | 13 | currsum=Math.max(arr[i],currsum+arr[i]); 14 | maxsum=Math.max(maxsum,currsum); 15 | 16 | 17 | 18 | } 19 | 20 | return amz 21 | 22 | 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Java/Linkedlist_Codestudio/Sort012.java: -------------------------------------------------------------------------------- 1 | //package Linkedlist_Codestudio; 2 | // 3 | //import java.util.Arrays; 4 | // 5 | //public class Sort012 { 6 | // 7 | // static class Node{ 8 | // int data; 9 | // Node next; 10 | // 11 | // Node(int data){ 12 | // this.data=data; 13 | // this.next=null; 14 | // } 15 | // } 16 | // 17 | // 18 | // 19 | // public static void main(String[] args) { 20 | // 21 | // 22 | // 23 | // 24 | // 25 | // } 26 | //} 27 | -------------------------------------------------------------------------------- /Java/Linkedlist_Codestudio/SortLL.java: -------------------------------------------------------------------------------- 1 | package Linkedlist_Codestudio; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | 6 | public class SortLL { 7 | static class Node{ 8 | int data; 9 | Node next; 10 | 11 | Node(int data){ 12 | this.data=data; 13 | this.next=null; 14 | } 15 | } 16 | public static Node createLL(ArrayList data){ 17 | if(data==null || data.size()==0){ 18 | return null; 19 | } 20 | 21 | Node head=new Node(data.get(0)); 22 | Node temp=head; 23 | 24 | for (int i = 1; i < data.size(); i++) { 25 | temp.next=new Node(data.get(i)); 26 | temp=temp.next; 27 | } 28 | return head; 29 | 30 | } 31 | public static Node createLL(int[] data){ 32 | if(data==null || data.length==0){ 33 | return null; 34 | } 35 | 36 | Node head=new Node(data[0]); 37 | Node temp=head; 38 | 39 | for (int i = 1; i < data.length; i++) { 40 | temp.next=new Node(data[i]); 41 | temp=temp.next; 42 | } 43 | return head; 44 | 45 | } 46 | 47 | public static void printLL(Node head){ 48 | 49 | Node temp=head; 50 | while (temp!=null){ 51 | System.out.print(temp.data+" => "); 52 | temp=temp.next; 53 | } 54 | System.out.print("null"); 55 | 56 | } 57 | public static void main(String[] args) { 58 | int[] data = {1, 9, 2, 8, 3, 7, 4}; 59 | int n=data.length; 60 | 61 | 62 | Node head=createLL(data); 63 | sortLL(head); 64 | 65 | } 66 | 67 | private static void sortLL(Node head) { 68 | 69 | Node temp=head; 70 | ArrayList arr=new ArrayList<>(); 71 | while (temp!=null){ 72 | arr.add(temp.data); 73 | temp=temp.next; 74 | } 75 | Collections.sort(arr); 76 | Node head2=createLL(arr); 77 | printLL(head2); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /Java/MaxSubArray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxSubArray(int[] nums) { 3 | int max = nums[0]; 4 | int currentSum=0; 5 | 6 | for (int i : nums) { 7 | if(currentSum<0){ 8 | currentSum=0; 9 | } 10 | currentSum+=i; 11 | max = Math.max(max,currentSum); 12 | } 13 | return max; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Java/MergeSortedLists.java: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/merge-two-sorted-lists/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * public class ListNode { 6 | * int val; 7 | * ListNode next; 8 | * ListNode() {} 9 | * ListNode(int val) { this.val = val; } 10 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 11 | * } 12 | */ 13 | class Solution { 14 | public ListNode mergeTwoLists(ListNode list1, ListNode list2) { 15 | if(list1==null)return list2; 16 | if(list2==null)return list1; 17 | 18 | if(list1.val=1; j--){ 17 | System.out.print(j); 18 | } 19 | //2nd half print 2 to i 20 | for(int j=2; j<=i; j++){ 21 | System.out.print(j); 22 | } 23 | System.out.println(); 24 | } 25 | } 26 | } 27 | } 28 | 29 | /* 30 | 31 | OUTPUT: 32 | 33 | Enter the number of row:5 34 | 1 35 | 212 36 | 32123 37 | 4321234 38 | 543212345 39 | 40 | */ -------------------------------------------------------------------------------- /Java/RadixSortingAlgo.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class RadixSort { 4 | 5 | // Using counting sort to sort the elements in the basis of significant places 6 | void countingSort(int array[], int size, int place) { 7 | int[] output = new int[size + 1]; 8 | int max = array[0]; 9 | for (int i = 1; i < size; i++) { 10 | if (array[i] > max) 11 | max = array[i]; 12 | } 13 | int[] count = new int[max + 1]; 14 | 15 | for (int i = 0; i < max; ++i) 16 | count[i] = 0; 17 | 18 | // Calculate count of elements 19 | for (int i = 0; i < size; i++) 20 | count[(array[i] / place) % 10]++; 21 | 22 | // Calculate cumulative count 23 | for (int i = 1; i < 10; i++) 24 | count[i] += count[i - 1]; 25 | 26 | // Place the elements in sorted order 27 | for (int i = size - 1; i >= 0; i--) { 28 | output[count[(array[i] / place) % 10] - 1] = array[i]; 29 | count[(array[i] / place) % 10]--; 30 | } 31 | 32 | for (int i = 0; i < size; i++) 33 | array[i] = output[i]; 34 | } 35 | 36 | // Function to get the largest element from an array 37 | int getMax(int array[], int n) { 38 | int max = array[0]; 39 | for (int i = 1; i < n; i++) 40 | if (array[i] > max) 41 | max = array[i]; 42 | return max; 43 | } 44 | 45 | // Main function to implement radix sort 46 | void radixSort(int array[], int size) { 47 | // Get maximum element 48 | int max = getMax(array, size); 49 | 50 | // Apply counting sort to sort elements based on place value. 51 | for (int place = 1; max / place > 0; place *= 10) 52 | countingSort(array, size, place); 53 | } 54 | 55 | // Driver code 56 | public static void main(String args[]) { 57 | int[] data = { 121, 432, 564, 23, 1, 45, 788 }; 58 | int size = data.length; 59 | RadixSort rs = new RadixSort(); 60 | rs.radixSort(data, size); 61 | System.out.println("Sorted Array in Ascending Order: "); 62 | System.out.println(Arrays.toString(data)); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /Java/ReverseWordsInString-III.java: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/reverse-words-in-a-string-iii/description/ 2 | 3 | class Solution { 4 | public String reverseWords(String s) { 5 | String[] words = s.split(" "); 6 | StringBuilder result = new StringBuilder(); 7 | 8 | for (String word : words) { 9 | StringBuilder reversedWord = new StringBuilder(); 10 | for (int i = word.length() - 1; i >= 0; i--) { 11 | reversedWord.append(word.charAt(i)); 12 | } 13 | result.append(reversedWord).append(" "); 14 | } 15 | 16 | result.deleteCharAt(result.length() - 1); 17 | 18 | return result.toString(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Java/ShellSortingAlgo.java: -------------------------------------------------------------------------------- 1 | 2 | class ShellSort { 3 | /* An utility function to print array of size n*/ 4 | static void printArray(int arr[]) 5 | { 6 | int n = arr.length; 7 | for (int i = 0; i < n; ++i) 8 | System.out.print(arr[i] + " "); 9 | System.out.println(); 10 | } 11 | 12 | /* function to sort arr using shellSort */ 13 | int sort(int arr[]) 14 | { 15 | int n = arr.length; 16 | 17 | // Start with a big gap, then reduce the gap 18 | for (int gap = n / 2; gap > 0; gap /= 2) { 19 | // Do a gapped insertion sort for this gap size. 20 | // The first gap elements a[0..gap-1] are already 21 | // in gapped order keep adding one more element 22 | // until the entire array is gap sorted 23 | for (int i = gap; i < n; i += 1) { 24 | // add a[i] to the elements that have been gap 25 | // sorted save a[i] in temp and make a hole at 26 | // position i 27 | int temp = arr[i]; 28 | 29 | // shift earlier gap-sorted elements up until 30 | // the correct location for a[i] is found 31 | int j; 32 | for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) 33 | arr[j] = arr[j - gap]; 34 | 35 | // put temp (the original a[i]) in its correct 36 | // location 37 | arr[j] = temp; 38 | } 39 | } 40 | return 0; 41 | } 42 | 43 | // Driver method 44 | public static void main(String args[]) 45 | { 46 | int arr[] = { 12, 34, 54, 2, 3 }; 47 | System.out.println("Array before sorting"); 48 | printArray(arr); 49 | 50 | ShellSort ob = new ShellSort(); 51 | ob.sort(arr); 52 | 53 | System.out.println("Array after sorting"); 54 | printArray(arr); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Java/SieveOfEratosthenes.java: -------------------------------------------------------------------------------- 1 | // Java program to print all primes smaller than or equal to 2 | // n using Sieve of Eratosthenes 3 | 4 | class SieveOfEratosthenes { 5 | void sieveOfEratosthenes(int n) 6 | { 7 | boolean prime[] = new boolean[n + 1]; 8 | for (int i = 0; i <= n; i++) 9 | prime[i] = true; 10 | 11 | for (int p = 2; p * p <= n; p++) { 12 | if (prime[p] == true) { 13 | for (int i = p * p; i <= n; i += p) 14 | prime[i] = false; 15 | } 16 | } 17 | 18 | for (int i = 2; i <= n; i++) { 19 | if (prime[i] == true) 20 | System.out.print(i + " "); 21 | } 22 | } 23 | 24 | public static void main(String args[]) 25 | { 26 | int n = 30; 27 | System.out.print("Following are the prime numbers "); 28 | System.out.println("smaller than or equal to " + n); 29 | SieveOfEratosthenes g = new SieveOfEratosthenes(); 30 | g.sieveOfEratosthenes(n); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Java/Stack.java: -------------------------------------------------------------------------------- 1 | 2 | //Importing Scanner class for input 3 | import java.util.Scanner; 4 | import java.util.InputMismatchException; 5 | 6 | // Stack class 7 | class Stack { 8 | private int top; 9 | private int maxSize; 10 | private int stack[]; 11 | 12 | // Constructor for Stack class intialize stack with given maximum size 13 | public Stack(int maxSize) { 14 | this.maxSize = maxSize; 15 | this.stack = new int[maxSize]; 16 | this.top = -1; // stack is empty 17 | } 18 | 19 | // adding element to stack 20 | public void push(int element) { 21 | if (top == maxSize - 1) { // to check stack is full 22 | System.out.println("-1"); 23 | return; 24 | } 25 | stack[++top] = element; // increasing the top and adding element 26 | } 27 | 28 | // removing element from stack 29 | public void pop() { 30 | if (top == -1) { // to check stack is empty 31 | System.out.println("-1"); 32 | return; 33 | } 34 | top--; // decrement top and get element at top of stack 35 | } 36 | 37 | // to get top of stack 38 | public int peek() { 39 | if (top == -1) { // to check stack is empty 40 | return -1; 41 | } 42 | return stack[top]; // get top element of stack 43 | } 44 | 45 | // method to check empty stack 46 | public boolean isEmpty() { 47 | return top == -1; 48 | } 49 | 50 | // method to check stack is Full 51 | public boolean isFull() { 52 | return top == maxSize - 1; 53 | } 54 | 55 | // to display the stack 56 | public void display() { 57 | if (top == -1) { // to check stack is empty 58 | return; 59 | } 60 | for (int index = top; index >= 0; index--) { 61 | System.out.print(stack[index] + " "); 62 | } 63 | } 64 | 65 | public static void main(String[] args) { 66 | try (Scanner input = new Scanner(System.in)) { 67 | System.out.println("Enter size of stack you want: "); 68 | int maxSize = input.nextInt(); // user input for max size 69 | Stack stack = new Stack(maxSize); 70 | int choice; 71 | do { 72 | System.out.println("1. Push"); 73 | System.out.println("2. Pop"); 74 | System.out.println("3. Peek"); 75 | System.out.println("4. Is empty"); 76 | System.out.println("5. Display"); 77 | System.out.println("6. Exit"); 78 | System.out.println("Enter your choice: "); 79 | choice = input.nextInt(); // getting user's choice 80 | switch (choice) { 81 | case 1: 82 | System.out.println("Enter element to push: "); 83 | int element = input.nextInt(); 84 | if (stack.isFull()) { 85 | System.out.println("stack is full"); 86 | break; 87 | } 88 | stack.push(element); 89 | break; 90 | case 2: 91 | if (stack.isEmpty()) { 92 | System.out.println("Stack is empty"); 93 | break; 94 | } 95 | int top = stack.peek(); 96 | stack.pop(); 97 | System.out.println("Deleted element is " + top); 98 | break; 99 | case 3: 100 | if (stack.isEmpty()) { 101 | System.out.println("Stack is empty"); 102 | break; 103 | } 104 | System.out.println("Top element is " + stack.peek()); 105 | break; 106 | case 4: 107 | if (stack.isEmpty()) { 108 | System.out.println("Stack is empty"); 109 | } else { 110 | System.out.println("Stack is not empty"); 111 | } 112 | break; 113 | case 5: 114 | if (stack.isEmpty()) { 115 | System.out.println("stack is empty"); 116 | break; 117 | } 118 | stack.display(); 119 | System.out.println(); 120 | break; 121 | case 6: 122 | System.out.println("Exit done"); 123 | break; 124 | default: 125 | System.out.println("Invalid choice"); 126 | } 127 | } while (choice != 6); 128 | } catch (InputMismatchException exception) { 129 | System.out.println(exception); 130 | } catch (Exception exception) { 131 | System.out.println(exception); 132 | } 133 | } 134 | } -------------------------------------------------------------------------------- /Java/StackTest.java: -------------------------------------------------------------------------------- 1 | import java.io.ByteArrayOutputStream; 2 | import java.io.PrintStream; 3 | import org.junit.Test; 4 | import org.junit.jupiter.api.Assertions; 5 | 6 | public class StackTest{ 7 | Stack stackTest =new Stack(10); 8 | 9 | @Test 10 | public void testIsEmpty(){ 11 | Assertions.assertTrue(stackTest.isEmpty()); 12 | } 13 | 14 | @Test 15 | public void testIsEmptyFalse(){ 16 | stackTest.push(10); 17 | Assertions.assertFalse(stackTest.isEmpty()); 18 | } 19 | 20 | @Test 21 | public void testPush() 22 | { 23 | ByteArrayOutputStream out= new ByteArrayOutputStream(); 24 | System.setOut(new PrintStream(out)); 25 | stackTest.push(5); 26 | stackTest.peek(); 27 | Assertions.assertEquals(5,stackTest.peek()); 28 | stackTest.push(4); 29 | Assertions.assertEquals(4,stackTest.peek()); 30 | stackTest.push(3); 31 | Assertions.assertEquals(3,stackTest.peek()); 32 | stackTest.push(2); 33 | Assertions.assertEquals(2,stackTest.peek()); 34 | stackTest.push(1); 35 | Assertions.assertEquals(1,stackTest.peek()); 36 | } 37 | 38 | @Test 39 | public void testPeek() 40 | { 41 | ByteArrayOutputStream out= new ByteArrayOutputStream(); 42 | System.setOut(new PrintStream(out)); 43 | stackTest.push(5); 44 | stackTest.push(4); 45 | stackTest.push(3); 46 | stackTest.push(2); 47 | stackTest.push(1); 48 | Assertions.assertEquals(1,stackTest.peek()); 49 | stackTest.pop(); 50 | Assertions.assertEquals(2,stackTest.peek()); 51 | stackTest.pop(); 52 | Assertions.assertEquals(3,stackTest.peek()); 53 | stackTest.pop(); 54 | Assertions.assertEquals(4,stackTest.peek()); 55 | } 56 | 57 | @Test 58 | public void testPop() 59 | { 60 | stackTest.push(5); 61 | stackTest.push(4); 62 | stackTest.push(3); 63 | stackTest.push(2); 64 | stackTest.push(1); 65 | Assertions.assertEquals(1,stackTest.peek()); 66 | stackTest.pop(); 67 | Assertions.assertEquals(2,stackTest.peek()); 68 | stackTest.pop(); 69 | Assertions.assertEquals(3,stackTest.peek()); 70 | stackTest.pop(); 71 | Assertions.assertEquals(4,stackTest.peek()); 72 | 73 | } 74 | 75 | @Test 76 | public void testDisplay() 77 | { 78 | ByteArrayOutputStream out= new ByteArrayOutputStream(); 79 | System.setOut(new PrintStream(out)); 80 | 81 | stackTest.push(5); 82 | stackTest.push(4); 83 | stackTest.push(3); 84 | stackTest.push(2); 85 | stackTest.push(1); 86 | stackTest.display(); 87 | Assertions.assertEquals("1 2 3 4 5".replaceAll(" ",""),out.toString().replaceAll(" ","")); 88 | } 89 | } -------------------------------------------------------------------------------- /Java/StackTest.txt: -------------------------------------------------------------------------------- 1 | Operations: 2 | 3 | 1. Push 4 | 2. Pop 5 | 3. Peek 6 | 4. Is empty 7 | 5. Display 8 | 6. Exit 9 | 10 | 11 | Test case-1 (Test case for push) 12 | 13 | size of stack - 4 14 | 15 | choice- 1 16 | input- 10 17 | choice- 1 18 | input- 20 19 | choice- 1 20 | input- 30 21 | choice- 5 22 | 23 | Output:- 30 20 10 24 | 25 | ------------------------------------------------------------------------------------------------ 26 | 27 | Test case-2 (Test case for pop) 28 | 29 | choice- 1 30 | input- 10 31 | choice- 1 32 | input- 20 33 | choice- 1 34 | input- 30 35 | choice- 2 36 | choice- 2 37 | choice- 5 38 | 39 | Output:- 10 40 | 41 | ------------------------------------------------------------------------------------------------ 42 | 43 | Test case-3 (Test case for Top elements) 44 | 45 | choice- 1 46 | input- 10 47 | choice- 1 48 | input- 20 49 | choice- 1 50 | input- 30 51 | choice- 3 52 | 53 | Output:- Top element is 30 54 | 55 | ------------------------------------------------------------------------------------------------ 56 | 57 | Test case-4 (Test case to check Empty Stack) 58 | 59 | choice- 4 60 | 61 | Output:- Stack is Empty 62 | 63 | choice- 1 64 | input- 10 65 | choice- 4 66 | 67 | Output:- Stack is not Empty 68 | 69 | ------------------------------------------------------------------------------------------------ 70 | 71 | Test case-5 (Test case for Display Stack) 72 | 73 | choice- 1 74 | input- 10 75 | choice- 1 76 | input- 20 77 | choice- 1 78 | input- 30 79 | choice- 5 80 | Output:- 30 20 10 81 | 82 | ------------------------------------------------------------------------------------------------ 83 | 84 | Test case-6 (Test case for Invalid user choice from Menu) 85 | 86 | choice- 7 87 | Output:- Invalid choice 88 | 89 | ------------------------------------------------------------------------------------------------ 90 | 91 | Test case-7 (Test case for invalid input type) 92 | 93 | input - hi 94 | Output:- 95 | java.util.InputMismatchException -------------------------------------------------------------------------------- /Java/TwoSum.java: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/two-sum/description/ 2 | 3 | class Solution { 4 | public int[] twoSum(int[] nums, int target) { 5 | for (int i = 0; i < nums.length; i++) { 6 | for (int j = i + 1; j < nums.length; j++) { 7 | if (nums[i] + nums[j] == target) { 8 | return new int[] {i, j}; 9 | } 10 | } 11 | } 12 | return new int[] {}; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Java/binarysearchalgo.java: -------------------------------------------------------------------------------- 1 | public class BinarySearch { 2 | // Returns the index of x if it is present in arr[], else return -1 3 | int binarySearch(int arr[], int x) { 4 | int left = 0, right = arr.length - 1; 5 | 6 | while (left <= right) { 7 | int mid = left + (right - left) / 2; 8 | 9 | // Check if x is present at mid 10 | if (arr[mid] == x) 11 | return mid; 12 | 13 | // If x greater, ignore the left half 14 | if (arr[mid] < x) 15 | left = mid + 1; 16 | 17 | // If x is smaller, ignore the right half 18 | else 19 | right = mid - 1; 20 | } 21 | 22 | // if we reach here, then the element was not present 23 | return -1; 24 | } 25 | 26 | // Driver method 27 | public static void main(String args[]) { 28 | BinarySearch ob = new BinarySearch(); 29 | int arr[] = { 2, 3, 4, 10, 40 }; 30 | int n = arr.length; 31 | int x = 10; 32 | int result = ob.binarySearch(arr, x); 33 | if (result == -1) 34 | System.out.println("Element not present in array"); 35 | else 36 | System.out.println("Element found at index " + result); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Java/medianTwoSortedArrays.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public double findMedianSortedArrays(int[] nums1, int[] nums2) { 3 | int[] arr = new int[nums1.length + nums2.length]; 4 | 5 | System.arraycopy(nums1, 0, arr, 0, nums1.length); 6 | System.arraycopy(nums2, 0, arr, nums1.length, nums2.length); 7 | 8 | Arrays.sort(arr); 9 | double median; 10 | 11 | if(arr.length%2!=0){ 12 | median = arr[arr.length/2]; 13 | } 14 | 15 | else { 16 | int middle1 = arr[arr.length / 2 - 1]; 17 | int middle2 = arr[arr.length / 2]; 18 | median = (double) (middle1 + middle2) / 2; 19 | } 20 | 21 | return median; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Java/mergeTwoSortedLists.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode mergeTwoLists(ListNode list1, ListNode list2) { 13 | ListNode dummy=new ListNode(); 14 | ListNode tail=dummy; 15 | while(list1!=null && list2!=null){ 16 | if(list1.val= 0 && subject.marks <= 100) { 10 | totalMarks += subject.marks; 11 | } else { 12 | return "Invalid marks. Marks should be between 0 and 100."; 13 | } 14 | } 15 | 16 | const percentage = (totalMarks / (totalSubjects * 100)) * 100; 17 | 18 | let grade; 19 | if (percentage >= 90) { 20 | grade = "A+"; 21 | } else if (percentage >= 80) { 22 | grade = "A"; 23 | } else if (percentage >= 70) { 24 | grade = "B"; 25 | } else if (percentage >= 60) { 26 | grade = "C"; 27 | } else if (percentage >= 50) { 28 | grade = "D"; 29 | } else { 30 | grade = "F"; 31 | } 32 | 33 | return { 34 | totalMarks, 35 | percentage: percentage.toFixed(2), 36 | grade, 37 | }; 38 | } 39 | 40 | // Example usage: 41 | const subjects = [ 42 | { name: "Math", marks: 85 }, 43 | { name: "Science", marks: 78 }, 44 | { name: "English", marks: 92 }, 45 | ]; 46 | 47 | const marksSheet = calculateMarksSheet(subjects); 48 | console.log("Marks Sheet:", marksSheet); 49 | -------------------------------------------------------------------------------- /Javascript/randomPass.js: -------------------------------------------------------------------------------- 1 | /** @format */ 2 | 3 | const characters = [ 4 | "A", 5 | "B", 6 | "C", 7 | "D", 8 | "E", 9 | "F", 10 | "G", 11 | "H", 12 | "I", 13 | "J", 14 | "K", 15 | "L", 16 | "M", 17 | "N", 18 | "O", 19 | "P", 20 | "Q", 21 | "R", 22 | "S", 23 | "T", 24 | "U", 25 | "V", 26 | "W", 27 | "X", 28 | "Y", 29 | "Z", 30 | "a", 31 | "b", 32 | "c", 33 | "d", 34 | "e", 35 | "f", 36 | "g", 37 | "h", 38 | "i", 39 | "j", 40 | "k", 41 | "l", 42 | "m", 43 | "n", 44 | "o", 45 | "p", 46 | "q", 47 | "r", 48 | "s", 49 | "t", 50 | "u", 51 | "v", 52 | "w", 53 | "x", 54 | "y", 55 | "z", 56 | "0", 57 | "1", 58 | "2", 59 | "3", 60 | "4", 61 | "5", 62 | "6", 63 | "7", 64 | "8", 65 | "9", 66 | "~", 67 | "`", 68 | "!", 69 | "@", 70 | "#", 71 | "$", 72 | "%", 73 | "^", 74 | "&", 75 | "*", 76 | "(", 77 | ")", 78 | "_", 79 | "-", 80 | "+", 81 | "=", 82 | "{", 83 | "[", 84 | "}", 85 | "]", 86 | ",", 87 | "|", 88 | ":", 89 | ";", 90 | "<", 91 | ">", 92 | ".", 93 | "?", 94 | "/", 95 | ]; 96 | 97 | let password1El = document.querySelector("#password1"); 98 | let password2El = document.querySelector("#password2"); 99 | let passlengthEl = document.querySelector("#pass-length"); 100 | let length = 8; 101 | 102 | passlengthEl.textContent = "Length = " + length; 103 | 104 | function addPassLength() { 105 | length += 1; 106 | passlengthEl.textContent = "Length = " + length; 107 | } 108 | 109 | function subtractPassLength() { 110 | if (length > 1) { 111 | length -= 1; 112 | } 113 | passlengthEl.textContent = "Length = " + length; 114 | } 115 | 116 | function generatePass() { 117 | password1El.textContent = ""; 118 | password2El.textContent = ""; 119 | 120 | for (let i = 1; i <= length; i++) { 121 | let pass = Math.floor(Math.random() * characters.length); 122 | password1El.textContent += characters[pass]; 123 | } 124 | 125 | for (let i = 1; i <= length; i++) { 126 | let pass = Math.floor(Math.random() * characters.length); 127 | password2El.textContent += characters[pass]; 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /Linear.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | class LinearSearchExample 3 | { 4 | public static void main(String args[]) 5 | { 6 | int counter, num, item, array[]; 7 | Scanner input = new Scanner(System.in); 8 | System.out.println("Enter number of elements:"); 9 | num = input.nextInt(); 10 | array = new int[num]; 11 | System.out.println("Enter " + num + " integers"); 12 | for (counter = 0; counter < num; counter++) 13 | array[counter] = input.nextInt(); 14 | 15 | System.out.println("Enter the search value:"); 16 | item = input.nextInt(); 17 | 18 | for (counter = 0; counter < num; counter++) 19 | { 20 | if (array[counter] == item) 21 | { 22 | System.out.println(item+" is present at location "+(counter+1)); 23 | break; 24 | } 25 | } 26 | if (counter == num) 27 | System.out.println(item + " doesn't exist in array."); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /PHP/Web-Scrapper/Php and Database Connection.php: -------------------------------------------------------------------------------- 1 | connect_error) 9 | { 10 | die("connection failed:".$conn->connect_error); 11 | } 12 | 13 | else 14 | { 15 | 16 | } 17 | 18 | 19 | ?> -------------------------------------------------------------------------------- /PHP/Web-Scrapper/README.md: -------------------------------------------------------------------------------- 1 | # Website-Scrapper 2 | This web scrapper is developed in core php with a user friendly GUI. 3 | 4 | ## Scraps 5 | - Website 6 | - Title 7 | - Desciption 8 | - Internal Links 9 | 10 | ## Requirments 11 | In Order for this scrapper to work you must have 12 | 13 | 1) Xaamp installed in your computer with a database. 14 | 2) Change the database connectivity settings in the Php and Database Connection file according to your needs. 15 | 3) Import crawler.sql into your database. 16 | -------------------------------------------------------------------------------- /PHP/Web-Scrapper/crawl.php: -------------------------------------------------------------------------------- 1 | // DB Connection 2 | 5 | 6 |
7 | 8 | 9 | 10 | 16 | 17 | 0) 29 | { 30 | $str = trim(preg_replace('/\s+/', ' ', $str)); // supports line breaks inside 31 | preg_match("/\<title\>(.*)\<\/title\>/i",$str,$title); // ignore case 32 | $title=$title[1]; 33 | } 34 | 35 | // Gets Webpage Description 36 | $b =$main_url; 37 | @$url = parse_url( $b ); 38 | @$tags = get_meta_tags($url['scheme'].'://'.$url['host'] ); 39 | $description=$tags['description']; 40 | 41 | // Gets Webpage Internal Links 42 | $doc = new DOMDocument; 43 | @$doc->loadHTML($str); 44 | 45 | // Gets all internal links 46 | $items = $doc->getElementsByTagName('a'); 47 | foreach($items as $value) 48 | { 49 | $attrs = $value->attributes; 50 | $sec_url[]=$attrs->getNamedItem('href')->nodeValue; 51 | } 52 | $all_links=implode(",",$sec_url); 53 | 54 | // Store Data In Database 55 | 56 | $sql2="INSERT INTO webpage_details(link,title,description,internal_link) VALUES('$main_url','$title','$description','$all_links')"; 57 | if($conn->query($sql2)===TRUE) 58 | { 59 | 60 | echo "<table style='border:1px solid black;'> 61 | <thead> 62 | <tr> 63 | <th style='border:1px solid black;'> Link </th> 64 | <th style='border:1px solid black;'> Title </th> 65 | <th style='border:1px solid black;'> Description </th> 66 | <th style='border:1px solid black;'> Internal Links </th> 67 | </tr> 68 | </thead> 69 | <tbody>"; 70 | 71 | // Shows scrapped data on web view 72 | 73 | $sql="SELECT link,title,description,internal_link FROM webpage_details"; 74 | $result=$conn->query($sql); 75 | if($result->num_rows>0) 76 | { 77 | while($row=$result->fetch_assoc()) 78 | { 79 | $A=$row['link']; 80 | $B=$row['title']; 81 | $C=$row['description']; 82 | $D=$row['internal_link']; 83 | 84 | 85 | echo " 86 | <tr> 87 | <td style='border:1px solid black;'>$A</td> 88 | <td style='border:1px solid black;'>$B</td> 89 | <td style='border:1px solid black;'>$C</td> 90 | <td style='border:1px solid black;'>$D</td> 91 | </tr>"; 92 | } 93 | 94 | } 95 | 96 | else 97 | { 98 | echo "ERROR"; 99 | } 100 | 101 | echo "</tbody> 102 | </table>"; 103 | 104 | } 105 | else 106 | { 107 | echo "Error"; 108 | } 109 | 110 | } 111 | ?> 112 | -------------------------------------------------------------------------------- /PHP/Web-Scrapper/crawler.sql: -------------------------------------------------------------------------------- 1 | -- phpMyAdmin SQL Dump 2 | -- version 5.0.4 3 | -- https://www.phpmyadmin.net/ 4 | -- 5 | -- Host: 127.0.0.1 6 | -- Generation Time: Mar 24, 2021 at 10:13 PM 7 | -- Server version: 10.4.16-MariaDB 8 | -- PHP Version: 7.4.12 9 | 10 | SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; 11 | START TRANSACTION; 12 | SET time_zone = "+00:00"; 13 | 14 | 15 | /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; 16 | /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; 17 | /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; 18 | /*!40101 SET NAMES utf8mb4 */; 19 | 20 | -- 21 | -- Database: `crawler` 22 | -- 23 | 24 | -- -------------------------------------------------------- 25 | 26 | -- 27 | -- Table structure for table `webpage_details` 28 | -- 29 | 30 | CREATE TABLE `webpage_details` ( 31 | `id` int(11) NOT NULL, 32 | `link` varchar(1024) NOT NULL, 33 | `title` varchar(1024) NOT NULL, 34 | `description` varchar(1024) NOT NULL, 35 | `internal_link` varchar(1024) NOT NULL 36 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; 37 | 38 | -- 39 | -- Dumping data for table `webpage_details` 40 | -- 41 | 42 | INSERT INTO `webpage_details` (`id`, `link`, `title`, `description`, `internal_link`) VALUES 43 | (2, 'https://github.com/', 'GitHub: Where the world builds software · GitHub', 'GitHub is where over 56 million developers shape the future of software, together. Contribute to the open source community, manage your Git repositories, review code like a pro, track bugs and features, power your CI/CD and DevOps workflows, and secure code before you commit it.', '#start-of-content,https://docs.github.com/articles/supported-browsers,https://github.com/,/join?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F&source=header-home,/join_next?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F&source=header-home,/features,/mobile,/features/actions,/features/codespaces,/features/packages,/features/security,/features/code-review/,/features/project-management/,/features/integrations,/sponsors,/customer-stories,/team,/enterprise,/explore,/topics,/collections,/trending,https://lab.github.com/,https://opensource.guide,https://github.com/readme,https://github.com/events,https://github.community,https://education.github.com,https://stars.github.com,/marketplace,/pricing,/pricing#feature-comparison,https://enterprise.github.com/contact,https://education.github.com,,,,,/login,/join?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F&source=header-home,/join_next?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F&source=header-home,https://enterprise.github.com/contact?r'); 44 | 45 | -- 46 | -- Indexes for dumped tables 47 | -- 48 | 49 | -- 50 | -- Indexes for table `webpage_details` 51 | -- 52 | ALTER TABLE `webpage_details` 53 | ADD PRIMARY KEY (`id`); 54 | 55 | -- 56 | -- AUTO_INCREMENT for dumped tables 57 | -- 58 | 59 | -- 60 | -- AUTO_INCREMENT for table `webpage_details` 61 | -- 62 | ALTER TABLE `webpage_details` 63 | MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12; 64 | COMMIT; 65 | 66 | /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; 67 | /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; 68 | /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; 69 | -------------------------------------------------------------------------------- /Pattern_Printing.py: -------------------------------------------------------------------------------- 1 | # python 3 code to print inverted star 2 | # pattern 3 | 4 | # n is the number of rows in which 5 | # star is going to be printed. 6 | n=11 7 | 8 | # i is going to be enabled to 9 | # range between n-i t 0 with a 10 | # decrement of 1 with each iteration. 11 | # and in print function, for each iteration, 12 | # ” ” is multiplied with n-i and ‘*’ is 13 | # multiplied with i to create correct 14 | # space before of the stars. 15 | for i in range (n, 0, -1): 16 | print((n-i) * ' ' + i * '*') 17 | -------------------------------------------------------------------------------- /Python/Automate Whatsapp Messeges: -------------------------------------------------------------------------------- 1 | import pywhatkit as pw 2 | import pyautogui 3 | import time 4 | time.sleep(3) 5 | count = 0 6 | while count<=100: 7 | pyautogui.typewrite("This is Rubbish, Nothing but a Rubbish") 8 | pyautogui.press("enter") 9 | count+=1 10 | -------------------------------------------------------------------------------- /Python/Brest Cancer Classification Using Python: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | import sklearn.datasets 4 | from sklearn.model_selection import train_test_split 5 | from sklearn.linear_model import LogisticRegression 6 | from sklearn.metrics import accuracy_score 7 | 8 | # loading the data from sklearn 9 | breast_cancer_dataset = sklearn.datasets.load_breast_cancer() 10 | 11 | print(breast_cancer_dataset) 12 | 13 | # loading the data to a data frame 14 | data_frame = pd.DataFrame(breast_cancer_dataset.data, columns = breast_cancer_dataset.feature_names) 15 | 16 | # print the first 5 rows of the dataframe 17 | data_frame.head() 18 | 19 | # adding the 'target' column to the data frame 20 | data_frame['label'] = breast_cancer_dataset.target 21 | 22 | # print last 5 rows of the dataframe 23 | data_frame.tail() 24 | 25 | # number of rows and columns in the dataset 26 | data_frame.shape 27 | 28 | # getting some information about the data 29 | data_frame.info() 30 | 31 | # checking for missing values 32 | data_frame.isnull().sum() 33 | 34 | # statistical measures about the data 35 | data_frame.describe() 36 | 37 | # checking the distribution of Target Varibale 38 | data_frame['label'].value_counts() 39 | 40 | data_frame.groupby('label').mean() 41 | 42 | X = data_frame.drop(columns='label', axis=1) 43 | Y = data_frame['label'] 44 | 45 | print(X) 46 | 47 | print(Y) 48 | 49 | X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=2) 50 | 51 | print(X.shape, X_train.shape, X_test.shape) 52 | 53 | model = LogisticRegression() 54 | 55 | # training the Logistic Regression model using Training data 56 | 57 | model.fit(X_train, Y_train) 58 | 59 | # accuracy on training data 60 | X_train_prediction = model.predict(X_train) 61 | training_data_accuracy = accuracy_score(Y_train, X_train_prediction) 62 | 63 | print('Accuracy on training data = ', training_data_accuracy) 64 | 65 | # accuracy on test data 66 | X_test_prediction = model.predict(X_test) 67 | test_data_accuracy = accuracy_score(Y_test, X_test_prediction) 68 | 69 | print('Accuracy on test data = ', test_data_accuracy) 70 | 71 | input_data = (13.54,14.36,87.46,566.3,0.09779,0.08129,0.06664,0.04781,0.1885,0.05766,0.2699,0.7886,2.058,23.56,0.008462,0.0146,0.02387,0.01315,0.0198,0.0023,15.11,19.26,99.7,711.2,0.144,0.1773,0.239,0.1288,0.2977,0.07259) 72 | 73 | # change the input data to a numpy array 74 | input_data_as_numpy_array = np.asarray(input_data) 75 | 76 | # reshape the numpy array as we are predicting for one datapoint 77 | input_data_reshaped = input_data_as_numpy_array.reshape(1,-1) 78 | 79 | prediction = model.predict(input_data_reshaped) 80 | print(prediction) 81 | 82 | if (prediction[0] == 0): 83 | print('The Breast cancer is Malignant') 84 | 85 | else: 86 | print('The Breast Cancer is Benign') 87 | 88 | -------------------------------------------------------------------------------- /Python/Bubble_Sort: -------------------------------------------------------------------------------- 1 | def BubbleSort(arr): 2 | for i in range(len(arr)): 3 | for j in range(len(arr)-i-1): 4 | if arr[j] > arr[j+1]: 5 | arr[j], arr[j+1] = arr[j+1], arr[j] 6 | return arr 7 | 8 | arr = [2,5,3,6,3,8,2,6,8] 9 | 10 | BubbleSort(arr) 11 | -------------------------------------------------------------------------------- /Python/Cartoonify using Python: -------------------------------------------------------------------------------- 1 | import cv2 #for image processing 2 | import easygui #to open the filebox 3 | import imageio #to read image stored at particular path 4 | 5 | import sys #to exit from the function, if null file chosen 6 | import matplotlib.pyplot as plt #to plot all images 7 | import os #to save image file 8 | import tkinter as tk #to creat dialouge box and messege box 9 | from tkinter import filedialog 10 | from tkinter import * 11 | # from PIL import ImageTk, Image 12 | 13 | top=tk.Tk() 14 | top.geometry('400x400') 15 | top.title('Cartoonify Your Image !') 16 | top.configure(background='white') 17 | label=Label(top,background='#CDCDCD', font=('calibri',20,'bold')) 18 | 19 | def upload(): 20 | ImagePath=easygui.fileopenbox() 21 | cartoonify(ImagePath) 22 | 23 | def cartoonify(ImagePath): 24 | # read the image 25 | originalmage = cv2.imread(ImagePath) 26 | originalmage = cv2.cvtColor(originalmage, cv2.COLOR_BGR2RGB) 27 | #print(image) # image is stored in form of numbers 28 | 29 | # confirm that image is chosen 30 | if originalmage is None: 31 | print("Can not find any image. Choose appropriate file") 32 | sys.exit() 33 | 34 | ReSized1 = cv2.resize(originalmage, (960, 540)) 35 | #plt.imshow(ReSized1, cmap='grey') 36 | 37 | 38 | #converting an image to grayscale 39 | grayScaleImage= cv2.cvtColor(originalmage, cv2.COLOR_BGR2GRAY) 40 | ReSized2 = cv2.resize(grayScaleImage, (960, 540)) 41 | #plt.imshow(ReSized2, cmap='gray') 42 | 43 | 44 | #applying median blur to smoothen an image 45 | smoothGrayScale = cv2.medianBlur(grayScaleImage, 5) 46 | ReSized3 = cv2.resize(smoothGrayScale, (960, 540)) 47 | #plt.imshow(ReSized3, cmap='gray') 48 | 49 | #retrieving the edges for cartoon effect 50 | #by using thresholding technique 51 | getEdge = cv2.adaptiveThreshold(smoothGrayScale, 255, 52 | cv2.ADAPTIVE_THRESH_MEAN_C, 53 | cv2.THRESH_BINARY, 9, 9) 54 | 55 | ReSized4 = cv2.resize(getEdge, (960, 540)) 56 | #plt.imshow(ReSized4, cmap='gray') 57 | 58 | #applying bilateral filter to remove noise 59 | #and keep edge sharp as required 60 | colorImage = cv2.bilateralFilter(originalmage, 9, 300, 300) 61 | ReSized5 = cv2.resize(colorImage, (960, 540)) 62 | #plt.imshow(ReSized5, cmap='gray') 63 | 64 | 65 | #masking edged image with our "BEAUTIFY" image 66 | cartoonImage = cv2.bitwise_and(colorImage, colorImage, mask=getEdge) 67 | 68 | ReSized6 = cv2.resize(cartoonImage, (960, 540)) 69 | #plt.imshow(ReSized6, cmap='gray') 70 | 71 | # Plotting the whole transition 72 | images=[ReSized1, ReSized2, ReSized3, ReSized4, ReSized5, ReSized6] 73 | 74 | fig, axes = plt.subplots(3,2, figsize=(8,8), subplot_kw={'xticks':[], 'yticks':[]}, gridspec_kw=dict(hspace=0.1, wspace=0.1)) 75 | for i, ax in enumerate(axes.flat): 76 | ax.imshow(images[i], cmap='gray') 77 | 78 | save1=Button(top,text="Save cartoon image",command=lambda: save(ReSized6, ImagePath),padx=30,pady=5) 79 | save1.configure(background='#364156', foreground='white',font=('calibri',10,'bold')) 80 | save1.pack(side=TOP,pady=50) 81 | 82 | plt.show() 83 | 84 | def save(ReSized6, ImagePath): 85 | #saving an image using imwrite() 86 | newName="cartoonified_Image" 87 | path1 = os.path.dirname(ImagePath) 88 | extension = os.path.splitext(ImagePath)[1] 89 | path = os.path.join(path1, newName+extension) 90 | cv2.imwrite(path, cv2.cvtColor(ReSized6, cv2.COLOR_RGB2BGR)) 91 | I= "Image saved by name " + newName +" at "+ path 92 | tk.messagebox.showinfo(title=None, message=I) 93 | 94 | upload=Button(top,text="Cartoonify an Image",command=upload,padx=10,pady=5) 95 | upload.configure(background='#364156', foreground='white',font=('calibri',10,'bold')) 96 | upload.pack(side=TOP,pady=50) 97 | 98 | top.mainloop() 99 | -------------------------------------------------------------------------------- /Python/Hand Gesture Recognation Using Python: -------------------------------------------------------------------------------- 1 | import mediapipe as mp #to detect hand and draw the landmarks accordingly 2 | import cv2 #to continueously capture input images 3 | import uuid #to rename each image uniquely while saving 4 | import os #to creat and modify folder in storage 5 | 6 | mp_drawing = mp.solutions.drawing_utils #to draw patterns 7 | mp_hands = mp.solutions.hands #to recognise hands in input image 8 | 9 | cap = cv2.VideoCapture(0) 10 | 11 | with mp_hands.Hands(min_detection_confidence=0.8, min_tracking_confidence=0.5, max_num_hands = 2) as hands: 12 | while cap.isOpened(): 13 | ret, frame = cap.read() 14 | 15 | # BGR_Image to RGB_Image 16 | hand_image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) 17 | 18 | # Flip Image horizontal 19 | hand_image = cv2.flip(hand_image, 1) 20 | 21 | hand_image.flags.writeable = False 22 | 23 | # Results 24 | results = hands.process(hand_image) 25 | 26 | hand_image.flags.writeable = True 27 | 28 | # RGB_Image to BGR_Image 29 | hand_image = cv2.cvtColor(hand_image, cv2.COLOR_RGB2BGR) 30 | 31 | #print(results) 32 | 33 | # Rendering Results 34 | if results.multi_hand_landmarks: 35 | for num, hand in enumerate(results.multi_hand_landmarks): 36 | mp_drawing.draw_landmarks(hand_image, hand, mp_hands.HAND_CONNECTIONS, 37 | mp_drawing.DrawingSpec(color=(121, 22, 76), thickness=2, circle_radius=2), 38 | mp_drawing.DrawingSpec(color=(50, 184, 150), thickness=2, circle_radius=2), 39 | ) 40 | 41 | 42 | cv2.imshow('Continueous Image with Hand Tracking', hand_image) 43 | 44 | if cv2.waitKey(10) & 0xFF == ord('q'): 45 | break 46 | 47 | cap.release() 48 | cv2.destroyAllWindows() 49 | -------------------------------------------------------------------------------- /Python/Hollow Butterfly Pattern: -------------------------------------------------------------------------------- 1 | n=int(input("Enter number of rows: ")) 2 | for i in range(1,n): 3 | for j in range(i+1): 4 | if j == i or j == 1: 5 | print("*",end="") 6 | else: 7 | print(" ",end="") 8 | for k in range(n-i): 9 | print(" "*2,end="") 10 | for l in range(i+1): 11 | if l == i or l == 1: 12 | print("*",end="") 13 | else: 14 | print(" ",end="") 15 | print("") 16 | for i in range(n,0,-1): 17 | for j in range(i+1): 18 | if j == i or j == 1: 19 | print("*",end="") 20 | else: 21 | print(" ",end="") 22 | for k in range(n-i): 23 | print(" "*2,end="") 24 | for l in range(i+1): 25 | if l == i or l == 1: 26 | print("*",end="") 27 | else: 28 | print(" ",end="") 29 | print("") 30 | -------------------------------------------------------------------------------- /Python/Hourglass: -------------------------------------------------------------------------------- 1 | #hourglass patern 2 | n = int(input("Enter height of pyramid: ")) 3 | # downward pyramid 4 | for i in range(n-1): 5 | for j in range(i): 6 | print(' ', end='') 7 | for k in range(2*(n-i)-1): 8 | print('*', end='') 9 | print() 10 | 11 | 12 | # upward pyramid 13 | for i in range(n): 14 | for j in range(n-i-1): 15 | print(' ', end='') 16 | for k in range(2*i+1): 17 | print('*', end='') 18 | print() 19 | -------------------------------------------------------------------------------- /Python/Hourglass.py: -------------------------------------------------------------------------------- 1 | 2 | n = int(input("Enter height of pyramid: ")) 3 | # downward pyramid 4 | for i in range(n-1): 5 | for j in range(i): 6 | print(' ', end='') 7 | for k in range(2*(n-i)-1): 8 | print('*', end='') 9 | print() 10 | 11 | 12 | # upward pyramid 13 | for i in range(n): 14 | for j in range(n-i-1): 15 | print(' ', end='') 16 | for k in range(2*i+1): 17 | print('*', end='') 18 | print() 19 | -------------------------------------------------------------------------------- /Python/Insertion Sort using Python: -------------------------------------------------------------------------------- 1 | def InsertionSort(arr): 2 | for i in range(len(arr)): 3 | current = arr[i] 4 | j = i - 1 5 | while(j >= 0 and current < arr[j]): 6 | arr[j+1] = arr[j] 7 | j -= 1 8 | arr[j + 1] = current 9 | return arr 10 | 11 | def main(): 12 | # Ask the user for the number of elements 13 | n = int(input("Enter the number of elements: ")) 14 | 15 | arr = [] # Empty list to store the elements 16 | 17 | # Loop through n times to get the elements from the user 18 | for i in range(n): 19 | element = int(input(f"Enter element {i+1}: ")) 20 | arr.append(element) 21 | 22 | # Call the InsertionSort function and print the sorted list 23 | sorted_arr = InsertionSort(arr) 24 | print("Sorted array:", sorted_arr) 25 | 26 | if __name__ == "__main__": 27 | main() 28 | 29 | -------------------------------------------------------------------------------- /Python/Password_Generator.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | letters = ["a","b","c","d","e","f","g","h","i","j","k" 4 | ,"l","m","n","o","p","q","r","s","t","u","v","w","x","y", 5 | "z",'A','B','C','D','E','F','G','H','I','J','K','L','M', 6 | 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] 7 | numbers = ["0",'1','2','3','4','5','6','7','8','9'] 8 | symbols = ['!','@','#',"$","%","^","&",'*',"(",")","+","_","-"] 9 | 10 | print("Welcome to the PyPassword Generator!") 11 | nr_letters= int(input("How many letters would you like in your password? \n")) 12 | nr_numbers= int(input("How many numbers would you like in your password? \n")) 13 | nr_symbols= int(input("How many symbols would you like in your password? \n")) 14 | 15 | string = num = symbl ="" 16 | for i in range (0, nr_letters): 17 | string += letters[random.randint(0, len(letters)-1)] 18 | 19 | for j in range (0, nr_numbers): 20 | num += numbers[random.randint(0, len(numbers)-1)] 21 | 22 | for k in range (0, nr_symbols): 23 | symbl += symbols[random.randint(0, len(symbols)-1)] 24 | 25 | easy = string + num + symbl 26 | print(f"The easy password is {easy}") 27 | 28 | password = [] 29 | for l in range (0, nr_letters): 30 | password.append(random.choice(letters)) 31 | 32 | for m in range (0, nr_numbers): 33 | password += random.choice(numbers) 34 | 35 | for n in range (0, nr_symbols): 36 | password += random.choice(symbols) 37 | 38 | random.shuffle(password) 39 | 40 | hard ="" 41 | for p in password: 42 | hard += p 43 | print(f"The hard password is {hard}") 44 | -------------------------------------------------------------------------------- /Python/Selection Sort using Python: -------------------------------------------------------------------------------- 1 | def SelectionSort(arr): 2 | for i in range(len(arr)): 3 | smallest = i 4 | for j in range(i, len(arr)): 5 | if arr[j] < arr[smallest]: 6 | smallest = j 7 | arr[i], arr[smallest] = arr[smallest], arr[i] 8 | return arr 9 | 10 | arr = [6,8,3,9,68,37,27] 11 | 12 | SelectionSort(arr) 13 | -------------------------------------------------------------------------------- /Python/atm.py: -------------------------------------------------------------------------------- 1 | class Atm: 2 | 3 | counter=0 4 | def __init__(self): 5 | self.__pin = "" 6 | self.__balance = 0 7 | self.sno = Atm.counter 8 | Atm.counter+=1 9 | 10 | self.menu() 11 | 12 | def get_pin(self): 13 | return self.__pin 14 | 15 | def set_pin(self,new_pin): 16 | if type(new_pin) == str: 17 | self.__pin = new_pin 18 | print("Pin changed") 19 | else: 20 | print("Not allowed") 21 | 22 | def menu(self): 23 | user_input = input("""HEllo how would like to proceed ?\n1. Enter 1 to create pin\n2. Enter 2 to deposit\n3. Enter 3 to withdraw\n4. Enter 4 to check balance\n5. Enter 5 to exit\n""") 24 | if user_input == '1': 25 | self.create_pin() 26 | elif user_input == '2': 27 | self.deposit() 28 | elif user_input == '3': 29 | self.withdraw() 30 | elif user_input == '1': 31 | self.check_balance() 32 | else: 33 | print("Bye") 34 | 35 | def create_pin(self): 36 | self.__pin = input("Enter your pin : ") 37 | print("Pin set successfully") 38 | def deposit(self): 39 | temp = input("Enter your pin : ") 40 | if temp==self.__pin: 41 | amount = int(input("Enter your amount")) 42 | self.__balance += amount 43 | print("Deposit succesfull") 44 | else: 45 | print("Invalid pin") 46 | 47 | def withdraw(self): 48 | temp = input("Enter your pin : ") 49 | if temp==self.__pin: 50 | amount = int(input("Enter your amount")) 51 | if amount<=self.__balance: 52 | self.__balance -= amount 53 | print("Operation succesfull") 54 | else: 55 | print("Insufficent funds") 56 | else: 57 | print("Invalid pin") 58 | 59 | def check_balance(self): 60 | temp = input("En 61 | ter your pin : ") 62 | if temp==self.__pin: 63 | print("Balance :",self.__balance) 64 | else: 65 | print("Invalid pin") 66 | 67 | sbi = Atm() 68 | sbi.deposit() 69 | sbi.check_balance() 70 | sbi.withdraw() -------------------------------------------------------------------------------- /Python/binarysearchalgo.py: -------------------------------------------------------------------------------- 1 | def binary_search(arr, x): 2 | left, right = 0, len(arr) - 1 3 | 4 | while left <= right: 5 | mid = left + (right - left) // 2 6 | 7 | # Check if x is present at mid 8 | if arr[mid] == x: 9 | return mid 10 | 11 | # If x greater, ignore the left half 12 | elif arr[mid] < x: 13 | left = mid + 1 14 | 15 | # If x is smaller, ignore the right half 16 | else: 17 | right = mid - 1 18 | 19 | # If we reach here, then the element was not present 20 | return -1 21 | 22 | # Example: 23 | arr = [2, 3, 4, 10, 40] 24 | x = 10 25 | 26 | result = binary_search(arr, x) 27 | 28 | if result != -1: 29 | print(f"Element found at index {result}") 30 | else: 31 | print("Element not present in array") 32 | -------------------------------------------------------------------------------- /Python/certificate_generator.py: -------------------------------------------------------------------------------- 1 | import os 2 | from PIL import Image, ImageDraw 3 | import xlrd 4 | 5 | def generate_certificate(name, template_path): 6 | """Generates a certificate for the given name using the given template.""" 7 | 8 | template = Image.open(template_path) 9 | draw = ImageDraw.Draw(template) 10 | 11 | # Write the name of the certificate recipient on the certificate. 12 | draw.text((100, 100), name, fill=(0, 0, 0), font_size=24) 13 | 14 | # Save the certificate. 15 | output_path = os.path.join("certificates", name + ".pdf") 16 | template.save(output_path, format="PDF") 17 | 18 | def main(): 19 | """Main function.""" 20 | 21 | # Read the Excel data containing the names of the certificate recipients. 22 | excel_file = xlrd.open_workbook("recipients.xlsx") 23 | sheet = excel_file.sheet_by_index(0) 24 | 25 | # Get the template path. 26 | template_path = "certificate_template.pdf" 27 | 28 | # Generate a certificate for each recipient. 29 | for row in range(1, sheet.nrows): 30 | name = sheet.cell(row, 0).value 31 | generate_certificate(name, template_path) 32 | 33 | if __name__ == "__main__": 34 | main() 35 | -------------------------------------------------------------------------------- /Python/crud.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | # Create a SQLite database or connect to an existing one 4 | conn = sqlite3.connect('crud_example.db') 5 | cursor = conn.cursor() 6 | 7 | # Create a table to store data 8 | cursor.execute(''' 9 | CREATE TABLE IF NOT EXISTS students ( 10 | id INTEGER PRIMARY KEY, 11 | name TEXT NOT NULL, 12 | age INTEGER 13 | ) 14 | ''') 15 | 16 | # Function to create a new student record 17 | def create_student(name, age): 18 | cursor.execute('INSERT INTO students (name, age) VALUES (?, ?)', (name, age)) 19 | conn.commit() 20 | print(f"Student {name} added successfully.") 21 | 22 | # Function to read all student records 23 | def read_students(): 24 | cursor.execute('SELECT * FROM students') 25 | students = cursor.fetchall() 26 | for student in students: 27 | print(f"ID: {student[0]}, Name: {student[1]}, Age: {student[2]}") 28 | 29 | # Function to update a student record by ID 30 | def update_student(id, name, age): 31 | cursor.execute('UPDATE students SET name=?, age=? WHERE id=?', (name, age, id)) 32 | conn.commit() 33 | print(f"Student with ID {id} updated successfully.") 34 | 35 | # Function to delete a student record by ID 36 | def delete_student(id): 37 | cursor.execute('DELETE FROM students WHERE id=?', (id,)) 38 | conn.commit() 39 | print(f"Student with ID {id} deleted successfully.") 40 | 41 | # Example usage 42 | create_student('Alice', 25) 43 | create_student('Bob', 22) 44 | read_students() 45 | update_student(1, 'Alice Johnson', 26) 46 | delete_student(2) 47 | read_students() 48 | 49 | # Close the database connection 50 | conn.close() 51 | -------------------------------------------------------------------------------- /Python/guess_the_number.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def number_guessing_game(): 4 | # Generate a random number between 1 and 100 5 | secret_number = random.randint(1, 100) 6 | 7 | attempts = 0 8 | max_attempts = 10 9 | 10 | print("Welcome to the Number Guessing Game!") 11 | print(f"Try to guess the secret number between 1 and 100. You have {max_attempts} attempts.") 12 | 13 | while attempts < max_attempts: 14 | try: 15 | guess = int(input("Enter your guess: ")) 16 | except ValueError: 17 | print("Invalid input. Please enter a valid number.") 18 | continue 19 | 20 | attempts += 1 21 | 22 | if guess < secret_number: 23 | print("Too low! Try again.") 24 | elif guess > secret_number: 25 | print("Too high! Try again.") 26 | else: 27 | print(f"Congratulations! You guessed the secret number {secret_number} in {attempts} attempts.") 28 | break 29 | else: 30 | print(f"Sorry, you've run out of attempts. The secret number was {secret_number}.") 31 | 32 | if __name__ == "__main__": 33 | number_guessing_game() 34 | -------------------------------------------------------------------------------- /Python/heapsort.py: -------------------------------------------------------------------------------- 1 | from heapq import heappop, heappush 2 | 3 | def heapsort(list1): 4 | heap = [] 5 | for ele in list1: 6 | heappush(heap, ele) 7 | 8 | sort = [] 9 | while heap: 10 | sort.append(heappop(heap)) 11 | 12 | return sort 13 | 14 | list1 = [27, 21, 55, 15, 60, 4, 11, 17, 2, 87] 15 | print(heapsort(list1)) 16 | -------------------------------------------------------------------------------- /Python/kadanes_algorithm.py: -------------------------------------------------------------------------------- 1 | def kadanes_algorithm(nums: list[int]) -> int: 2 | """ 3 | Find the maximum subarray sum using Kadane's Algorithm. 4 | Args: 5 | nums (List[int]): List of integers. 6 | Returns: 7 | int: Maximum subarray sum. 8 | Examples: 9 | >>> kadanes_algorithm([5, 4, -1, 2, 6, -9]) 10 | 16 11 | """ 12 | max_sum = float("-inf") # Negative infinity initialized to max_sum 13 | current_sum = 0 14 | 15 | for num in nums: 16 | current_sum = max(num, current_sum + num) 17 | # Update the max sum with the greater of the current max sum and current sum 18 | max_sum = max(max_sum, current_sum) 19 | 20 | return max_sum 21 | 22 | 23 | if __name__ == "__main__": 24 | import doctest 25 | 26 | doctest.testmod() 27 | 28 | try: 29 | input_str = input("Enter a list of integers separated by spaces: ") 30 | nums = list(map(int, input_str.split())) 31 | max_subarray_sum = kadanes_algorithm(nums) 32 | print("Maximum subarray sum:", max_subarray_sum) 33 | except ValueError: 34 | print("Invalid input. Please enter a list of integers separated by spaces.") -------------------------------------------------------------------------------- /Python/kth largest element: -------------------------------------------------------------------------------- 1 | def kthSmallest(arr, N, K): 2 | 3 | # Sort the given array 4 | arr.sort() 5 | 6 | # Return k'th element in the 7 | # sorted array 8 | return arr[K-1] 9 | 10 | 11 | # Driver code 12 | if __name__ == '__main__': 13 | arr = [12, 3, 5, 7, 19] 14 | N = len(arr) 15 | K = 2 16 | 17 | # Function call 18 | print("K'th smallest element is", 19 | kthSmallest(arr, N, K)) 20 | -------------------------------------------------------------------------------- /Python/linear-regression.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | 4 | class MeraLR: 5 | 6 | def __init__(self): 7 | self.m = None 8 | self.b = None 9 | 10 | def fit(self,X_train,y_train): 11 | 12 | num = 0 13 | den = 0 14 | 15 | for i in range(X_train.shape[0]): 16 | 17 | num = num + ((X_train[i] - X_train.mean())*(y_train[i] - y_train.mean())) 18 | den = den + ((X_train[i] - X_train.mean())*(X_train[i] - X_train.mean())) 19 | 20 | self.m = num/den 21 | self.b = y_train.mean() - (self.m * X_train.mean()) 22 | print(self.m) 23 | print(self.b) 24 | 25 | def predict(self,X_test): 26 | 27 | print(X_test) 28 | 29 | return self.m * X_test + self.b 30 | -------------------------------------------------------------------------------- /Python/nim.py: -------------------------------------------------------------------------------- 1 | 2 | import turtle 3 | import random 4 | import time 5 | 6 | SCREENWIDTH = 640 7 | SCREENHEIGHT = 480 8 | 9 | MINSTICKS = 7 10 | MAXSTICKS = 31 11 | 12 | HUNIT = SCREENHEIGHT // 12 13 | WUNIT = SCREENWIDTH // ((MAXSTICKS // 5) * 11 + (MAXSTICKS % 5) * 2) 14 | 15 | SCOLOR = (63, 63, 31) 16 | HCOLOR = (255, 204, 204) 17 | COLOR = (204, 204, 255) 18 | 19 | def randomrow(): 20 | return random.randint(MINSTICKS, MAXSTICKS) 21 | 22 | def computerzug(state): 23 | xored = state[0] ^ state[1] ^ state[2] 24 | if xored == 0: 25 | return randommove(state) 26 | for z in range(3): 27 | s = state[z] ^ xored 28 | if s <= state[z]: 29 | move = (z, s) 30 | return move 31 | 32 | def randommove(state): 33 | m = max(state) 34 | while True: 35 | z = random.randint(0,2) 36 | if state[z] > (m > 1): 37 | break 38 | rand = random.randint(m > 1, state[z]-1) 39 | return z, rand 40 | 41 | 42 | class NimModel(object): 43 | def __init__(self, game): 44 | self.game = game 45 | 46 | def setup(self): 47 | if self.game.state not in [Nim.CREATED, Nim.OVER]: 48 | return 49 | self.sticks = [randomrow(), randomrow(), randomrow()] 50 | self.player = 0 51 | self.winner = None 52 | self.game.view.setup() 53 | self.game.state = Nim.RUNNING 54 | 55 | def move(self, row, col): 56 | maxspalte = self.sticks[row] 57 | self.sticks[row] = col 58 | self.game.view.notify_move(row, col, maxspalte, self.player) 59 | if self.game_over(): 60 | self.game.state = Nim.OVER 61 | self.winner = self.player 62 | self.game.view.notify_over() 63 | elif self.player == 0: 64 | self.player = 1 65 | row, col = computerzug(self.sticks) 66 | self.move(row, col) 67 | self.player = 0 68 | 69 | def game_over(self): 70 | return self.sticks == [0, 0, 0] 71 | 72 | def notify_move(self, row, col): 73 | if self.sticks[row] <= col: 74 | return 75 | self.move(row, col) 76 | 77 | 78 | class Stick(turtle.Turtle): 79 | def __init__(self, row, col, game): 80 | turtle.Turtle.__init__(self, visible=False) 81 | self.row = row 82 | self.col = col 83 | self.game = game 84 | x, y = self.coords(row, col) 85 | self.shape("square") 86 | self.shapesize(HUNIT/10.0, WUNIT/20.0) 87 | self.speed(0) 88 | self.pu() 89 | self.goto(x,y) 90 | self.color("white") 91 | self.showturtle() 92 | 93 | def coords(self, row, col): 94 | packet, remainder = divmod(col, 5) 95 | x = (3 + 11 * packet + 2 * remainder) * WUNIT 96 | y = (2 + 3 * row) * HUNIT 97 | return x - SCREENWIDTH // 2 + WUNIT // 2, SCREENHEIGHT // 2 - y - HUNIT // 2 98 | 99 | def makemove(self, x, y): 100 | if self.game.state != Nim.RUNNING: 101 | return 102 | self.game.controller.notify_move(self.row, self.col) 103 | 104 | 105 | class NimView(object): 106 | def __init__(self, game): 107 | self.game = game 108 | self.screen = game.screen 109 | self.model = game.model 110 | self.screen.colormode(255) 111 | self.screen.tracer(False) 112 | self.screen.bgcolor((240, 240, 255)) 113 | self.writer = turtle.Turtle(visible=False) 114 | self.writer.pu() 115 | self.writer.speed(0) 116 | self.sticks = {} 117 | for row in range(3): 118 | for col in range(MAXSTICKS): 119 | self.sticks[(row, col)] = Stick(row, col, game) 120 | self.display("... a moment please ...") 121 | self.screen.tracer(True) 122 | 123 | def display(self, msg1, msg2=None): 124 | self.screen.tracer(False) 125 | self.writer.clear() 126 | if msg2 is not None: 127 | self.writer.goto(0, - SCREENHEIGHT // 2 + 48) 128 | self.writer.pencolor("red") 129 | self.writer.write(msg2, align="center", font=("Courier",18,"bold")) 130 | self.writer.goto(0, - SCREENHEIGHT // 2 + 20) 131 | self.writer.pencolor("black") 132 | self.writer.write(msg1, align="center", font=("Courier",14,"bold")) 133 | self.screen.tracer(True) 134 | 135 | def setup(self): 136 | self.screen.tracer(False) 137 | for row in range(3): 138 | for col in range(self.model.sticks[row]): 139 | self.sticks[(row, col)].color(SCOLOR) 140 | for row in range(3): 141 | for col in range(self.model.sticks[row], MAXSTICKS): 142 | self.sticks[(row, col)].color("white") 143 | self.display("Your turn! Click leftmost stick to remove.") 144 | self.screen.tracer(True) 145 | 146 | def notify_move(self, row, col, maxspalte, player): 147 | if player == 0: 148 | farbe = HCOLOR 149 | for s in range(col, maxspalte): 150 | self.sticks[(row, s)].color(farbe) 151 | else: 152 | self.display(" ... thinking ... ") 153 | time.sleep(0.5) 154 | self.display(" ... thinking ... aaah ...") 155 | farbe = COLOR 156 | for s in range(maxspalte-1, col-1, -1): 157 | time.sleep(0.2) 158 | self.sticks[(row, s)].color(farbe) 159 | self.display("Your turn! Click leftmost stick to remove.") 160 | 161 | def notify_over(self): 162 | if self.game.model.winner == 0: 163 | msg2 = "Congrats. You're the winner!!!" 164 | else: 165 | msg2 = "Sorry, the computer is the winner." 166 | self.display("To play again press space bar. To leave press ESC.", msg2) 167 | 168 | def clear(self): 169 | if self.game.state == Nim.OVER: 170 | self.screen.clear() 171 | 172 | 173 | class NimController(object): 174 | 175 | def __init__(self, game): 176 | self.game = game 177 | self.sticks = game.view.sticks 178 | self.BUSY = False 179 | for stick in self.sticks.values(): 180 | stick.onclick(stick.makemove) 181 | self.game.screen.onkey(self.game.model.setup, "space") 182 | self.game.screen.onkey(self.game.view.clear, "Escape") 183 | self.game.view.display("Press space bar to start game") 184 | self.game.screen.listen() 185 | 186 | def notify_move(self, row, col): 187 | if self.BUSY: 188 | return 189 | self.BUSY = True 190 | self.game.model.notify_move(row, col) 191 | self.BUSY = False 192 | 193 | 194 | class Nim(object): 195 | CREATED = 0 196 | RUNNING = 1 197 | OVER = 2 198 | def __init__(self, screen): 199 | self.state = Nim.CREATED 200 | self.screen = screen 201 | self.model = NimModel(self) 202 | self.view = NimView(self) 203 | self.controller = NimController(self) 204 | 205 | 206 | def main(): 207 | mainscreen = turtle.Screen() 208 | mainscreen.mode("standard") 209 | mainscreen.setup(SCREENWIDTH, SCREENHEIGHT) 210 | nim = Nim(mainscreen) 211 | return "EVENTLOOP" 212 | 213 | if __name__ == "__main__": 214 | main() 215 | turtle.mainloop() 216 | 217 | -------------------------------------------------------------------------------- /Python/sieveOfEratosthenes.py: -------------------------------------------------------------------------------- 1 | # Python program to print all primes smaller than or equal to n 2 | # using Sieve of Eratosthenes 3 | 4 | def SieveOfEratosthenes(n): 5 | prime = [True for i in range(n+1)] 6 | p = 2 7 | while (p * p <= n): 8 | if (prime[p] == True): 9 | for i in range(p * p, n+1, p): 10 | prime[i] = False 11 | p += 1 12 | 13 | for p in range(2, n+1): 14 | if prime[p]: 15 | print(p) 16 | 17 | if __name__ == '__main__': 18 | n = 20 19 | print("Following are the prime numbers smaller"), 20 | print("than or equal to", n) 21 | SieveOfEratosthenes(n) 22 | -------------------------------------------------------------------------------- /Python/telephone_directory.py: -------------------------------------------------------------------------------- 1 | import pickle 2 | try: 3 | contact=pickle.load(open("save.p", "rb+")) 4 | except IOError: 5 | contact={} 6 | pass 7 | def pick(): 8 | pickle.dump(contact, open("save.p", "wb")) 9 | def store(): 10 | global contact 11 | name=input("Enter name:") 12 | phone=input("Enter Phone:") 13 | if name in contact: 14 | print("Contact Already exists !\n") 15 | else: 16 | contact[name] =phone 17 | print("Contact Stored !") 18 | print(contact) 19 | print("Do you want to perform more operations? (y / n)") 20 | choice = input().strip() 21 | if choice == "y": 22 | main() 23 | pick() 24 | def search(): 25 | global contact 26 | print("Enter the name to be searched") 27 | iname = input().strip() 28 | if iname in contact: 29 | print (contact[iname]) 30 | else: 31 | print("Contact not found !\n") 32 | print("Do you want to perform more operations? (y / n)") 33 | choice = input().strip() 34 | if choice == "y": 35 | main() 36 | def update(): 37 | global contact 38 | print("Enter the contact name to be updated -") 39 | name = input().strip() 40 | if name in contact: 41 | print("Enter the phone number-") 42 | phone = input() 43 | contact[name]=phone 44 | print("Contact updated\n") 45 | print(contact) 46 | 47 | else: 48 | print("Contact not found !\n") 49 | print("Do you want to perform more operations? (y / n)") 50 | choice = input().strip() 51 | if choice == "y": 52 | main() 53 | pick() 54 | def delete(): 55 | global contact 56 | print("Enter the contact name to be deleted") 57 | name = input().strip() 58 | if name in contact: 59 | del(contact[name]) 60 | print("Contact Deleted !\n") 61 | else: 62 | print("Contact not found !\n") 63 | print("Do you want to perform more operations? (y / n)") 64 | choice = input().strip() 65 | if choice == "y": 66 | main() 67 | pick() 68 | def main(): 69 | print("lookup (1)") 70 | print("add (2)") 71 | print("change (3)") 72 | print("Delete (4)") 73 | 74 | choice = int(input()) 75 | if choice==1: 76 | search() 77 | elif choice==2: 78 | store() 79 | elif choice==3: 80 | update() 81 | elif choice==4: 82 | delete() 83 | 84 | main() -------------------------------------------------------------------------------- /Python/tic_tac_toe.py: -------------------------------------------------------------------------------- 1 | def print_board(board): 2 | for row in board: 3 | print(" | ".join(row)) 4 | print("-" * 5) 5 | 6 | def check_winner(board): 7 | # Check rows 8 | for row in board: 9 | if row.count(row[0]) == len(row) and row[0] != ' ': 10 | return True 11 | 12 | # Check columns 13 | for col in range(len(board[0])): 14 | if all(board[row][col] == board[0][col] and board[row][col] != ' ' for row in range(len(board))): 15 | return True 16 | 17 | # Check diagonals 18 | if board[0][0] == board[1][1] == board[2][2] != ' ': 19 | return True 20 | if board[0][2] == board[1][1] == board[2][0] != ' ': 21 | return True 22 | 23 | return False 24 | 25 | def is_board_full(board): 26 | return all(all(cell != ' ' for cell in row) for row in board) 27 | 28 | def is_valid_move(board, row, col): 29 | return 0 <= row < 3 and 0 <= col < 3 and board[row][col] == ' ' 30 | 31 | def tic_tac_toe(): 32 | board = [[' ' for _ in range(3)] for _ in range(3)] 33 | current_player = 'X' 34 | 35 | while True: 36 | print_board(board) 37 | 38 | row = int(input(f"Player {current_player}, enter row (0, 1, or 2): ")) 39 | col = int(input(f"Player {current_player}, enter column (0, 1, or 2): ")) 40 | 41 | if not is_valid_move(board, row, col): 42 | print("Invalid move. Try again.") 43 | continue 44 | 45 | board[row][col] = current_player 46 | 47 | if check_winner(board): 48 | print_board(board) 49 | print(f"Player {current_player} wins!") 50 | break 51 | 52 | if is_board_full(board): 53 | print_board(board) 54 | print("It's a tie!") 55 | break 56 | 57 | current_player = 'O' if current_player == 'X' else 'X' 58 | 59 | if __name__ == "__main__": 60 | tic_tac_toe() 61 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CodingPractice-Hacktoberfest23 2 | Repository totally dedicated to Hacktober Fest 2023, feel free to use it. Topics hacktoberfest hacktoberfest-accepted hacktoberfest2023 3 | 4 | <p align="center"> 5 | <a href="https://hacktoberfest.com/" target="_blank"> 6 | <img src="https://miro.medium.com/v2/resize:fit:1400/0*McOGR_vW3LivYNor.png" width="800px" height="400px"> 7 | </a> 8 | </p> 9 | 10 | # HacktoberFest23 11 | 12 | Hello Hackers! HacktoberFest has begun again for year 2023, and everyone's excited to get started! 13 | Contribute between: <h4>1 OCTOBER - 31 OCTOBER</h4> 14 | 15 | Create a Pull request and add any feature update to the repository. 16 | 17 | * [Click here to register for hacktoberfest2023.](https://hacktoberfest.com/) 18 | 19 | ## How to contribute to this project? 20 | 21 | Choose both, make a pull request for your work and wait for it to be merged!! 22 | 23 | ## Getting started 24 | * Fork this repository (Click the Fork button in the top right of this page, click your Profile Image) 25 | * Clone your fork down to your local machine. 26 | 27 | ```markdown 28 | [git clone https:[//github.com/csubhasundar/CodingPractice-Hacktoberfest23](https://github.com/csubhasundar/CodingPractice-Hacktoberfest23/tree/main)](https://github.com/csubhasundar/CodingPractice-Hacktoberfest23) 29 | ``` 30 | 31 | * Create a branch 32 | 33 | ```markdown 34 | git checkout -b your-branch-name 35 | ``` 36 | 37 | * Make your changes in "Python/C/C++/Java" folder. 38 | * Commit and push your code. 39 | 40 | 41 | * Create a new pull request from your forked repository (Click the `New Pull Request` button located at the top of your repo) 42 | * Wait for your PR review and merge approval... 43 | * __Star this repository__ if you had fun contributing! 44 | 45 | 46 | ## A BIG Thanks To Our Contributors :handshake: :handshake: 47 | <a href="https://github.com/csubhasundar/CodingPractice-Hacktoberfest23/graphs/contributors"> 48 | <img src="https://contrib.rocks/image?repo=csubhasundar/CodingPractice-Hacktoberfest23" /> 49 | </a> 50 | -------------------------------------------------------------------------------- /SelectionSortAlgo.cpp: -------------------------------------------------------------------------------- 1 | 2 | // C++ program for implementation of 3 | // selection sort 4 | #include <bits/stdc++.h> 5 | using namespace std; 6 | 7 | //Swap function 8 | void swap(int *xp, int *yp) 9 | { 10 | int temp = *xp; 11 | *xp = *yp; 12 | *yp = temp; 13 | } 14 | 15 | void selectionSort(int arr[], int n) 16 | { 17 | int i, j, min_idx; 18 | 19 | // One by one move boundary of 20 | // unsorted subarray 21 | for (i = 0; i < n-1; i++) 22 | { 23 | 24 | 25 | // unsorted array 26 | min_idx = i; 27 | for (j = i+1; j < n; j++) 28 | if (arr[j] < arr[min_idx]) 29 | min_idx = j; 30 | 31 | // Swap the found minimum element 32 | // with the first element 33 | if(min_idx!=i) 34 | swap(&arr[min_idx], &arr[i]); 35 | } 36 | } 37 | 38 | //Function to print an array 39 | void printArray(int arr[], int size) 40 | { 41 | int i; 42 | for (i=0; i < size; i++) 43 | cout << arr[i] << " "; 44 | cout << endl; 45 | } 46 | 47 | int main() 48 | { 49 | int arr[] = {64, 25, 12, 22, 11}; 50 | int n = sizeof(arr)/sizeof(arr[0]); 51 | selectionSort(arr, n); 52 | cout << "Sorted array: \n"; 53 | printArray(arr, n); 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /binary.py: -------------------------------------------------------------------------------- 1 | def binarySearch(arr, l, r, x): 2 | 3 | while l <= r: 4 | 5 | mid = l + (r - l) // 2 6 | 7 | # Check if x is present at mid 8 | if arr[mid] == x: 9 | return mid 10 | 11 | # If x is greater, ignore left half 12 | elif arr[mid] < x: 13 | l = mid + 1 14 | 15 | # If x is smaller, ignore right half 16 | else: 17 | r = mid - 1 18 | 19 | # If we reach here, then the element 20 | # was not present 21 | return -1 22 | 23 | 24 | # Driver Code 25 | if __name__ == '__main__': 26 | arr = [2, 3, 4, 10, 40] 27 | x = 10 28 | 29 | # Function call 30 | result = binarySearch(arr, 0, len(arr)-1, x) 31 | if result != -1: 32 | print("Element is present at index", result) 33 | else: 34 | print("Element is not present in array") 35 | -------------------------------------------------------------------------------- /bubblesort.cpp: -------------------------------------------------------------------------------- 1 | // // Bubble Sort Algorithm is the simplest sorting algorithm that works by repeatedly swapping 2 | // // the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data 3 | // // sets as its average and worst-case time complexity is quite high. 4 | 5 | // Bubble Sort Example 6 | // Consider an array to be mentioned below: 7 | 8 | // arr[] = {5, 1, 4, 2, 8} 9 | // First Traversing 10 | // Bubble sort starts with very first two elements, comparing them to check which one is greater. 11 | 12 | // ( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1. 13 | // ( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4 14 | // ( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2 15 | // ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them. 16 | // Second Traversing 17 | // Now, during second iteration it should look like this: 18 | 19 | // ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ) 20 | // ( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2 21 | // ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) 22 | // ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) 23 | 24 | // Third Traversing 25 | // Now, the array is already sorted, but our algorithm does not know if it is completed. 26 | 27 | // The algorithm needs one whole pass without any swap to know it is sorted. 28 | 29 | // ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) 30 | // ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) 31 | // ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) 32 | // ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) 33 | // Output: 34 | // // Sorted 35 | // arr=[1,2,4,5,8] 36 | 37 | #include <bits/stdc++.h> 38 | using namespace std; 39 | 40 | // A function to implement bubble sort 41 | void bubbleSort(int arr[], int n) 42 | { 43 | int i, j; 44 | for (i = 0; i < n - 1; i++) 45 | 46 | // Last i elements are already 47 | // in place 48 | for (j = 0; j < n - i - 1; j++) 49 | if (arr[j] > arr[j + 1]) 50 | swap(arr[j], arr[j + 1]); 51 | } 52 | 53 | // Function to print an array 54 | void printArray(int arr[], int size) 55 | { 56 | int i; 57 | for (i = 0; i < size; i++) 58 | cout << arr[i] << " "; 59 | cout << endl; 60 | } 61 | 62 | // Driver code 63 | int main() 64 | { 65 | int arr[] = { 5, 1, 4, 2, 8}; 66 | int N = sizeof(arr) / sizeof(arr[0]); 67 | bubbleSort(arr, N); 68 | cout << "Sorted array: \n"; 69 | printArray(arr, N); 70 | return 0; 71 | } -------------------------------------------------------------------------------- /c code: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /longestPalindrome.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include <bits/stdc++.h> 3 | 4 | using namespace std; 5 | 6 | 7 | string longestPalindrome(string s) { 8 | int n=s.length(); 9 | vector<vector<bool>>dp(n, vector<bool>(n)); 10 | 11 | for(int i=n-1;i>=0;i--) 12 | { 13 | for(int j=i;j<n;j++) 14 | { 15 | if(i==j) 16 | { 17 | dp[i][j] = true; 18 | } 19 | else if(s[i]==s[j]) 20 | { 21 | dp[i][j] = (i+1<j-1)?dp[i+1][j-1]:true; 22 | } 23 | else 24 | dp[i][j] =0; 25 | } 26 | } 27 | int maxx = 0; 28 | int ind = -1; 29 | int jnd = -1; 30 | 31 | for(int i=0;i<n;i++) 32 | { 33 | for(int j=i;j<n;j++) 34 | { 35 | if(dp[i][j] && (j-i+1)>maxx) 36 | { 37 | maxx = j-i+1; 38 | ind = i; 39 | jnd = j; 40 | } 41 | } 42 | } 43 | 44 | //cout<<ind<<" "<<jnd<<endl; 45 | //return ""; 46 | return string(s.begin()+ind, s.begin()+jnd+1); 47 | 48 | 49 | } 50 | int main() 51 | { 52 | int t; 53 | cin>>t; 54 | while(t--) 55 | { 56 | string s; 57 | cin>>s; 58 | string ans = longestPalindrome(s); 59 | cout<<ans<<endl; 60 | } 61 | return 0; 62 | } 63 | --------------------------------------------------------------------------------