├── Algos ├── C++ │ ├── 01_Knapsack.cpp │ ├── Alphabet_triangle.cpp │ ├── Armstrong_number.cpp │ ├── Count Sort.cpp │ ├── Factorial.cpp │ ├── Fibonacci.C++ │ ├── Fibonacci.cpp │ ├── GCD.cpp │ ├── Heap-Sort.cpp │ ├── Inorder_Traversal_Iterative.cpp │ ├── Josephus_algorithm.cpp │ ├── Kadane's_Algorithm.cpp │ ├── Karatsuba_Algorithm.cpp │ ├── Kosaraju's Algo.cpp │ ├── Kruskal’s_algorithim.cpp │ ├── Longest Consecutive Subsequence.cpp │ ├── LongestCommonSubsequence.cpp │ ├── Prims.cpp │ ├── Stack_Array.cpp │ ├── StockSpan.cpp │ ├── TopologicalSort.cpp │ ├── Vector_sort.cpp │ ├── Vector_sort_HR.cpp │ ├── balance paranthesis.cpp │ ├── bellmanford.cpp │ ├── binary-search.cpp │ ├── binary_search_tree.cpp │ ├── binary_tree.cpp │ ├── binarysearch.cpp │ ├── boundary elements.cpp │ ├── bubble-sort.cpp │ ├── build a tree from inorder and postorder.cpp │ ├── cardgame.cpp │ ├── constructor overloading.cpp │ ├── cousins_in_btree.cpp │ ├── cyclic_sort.cpp │ ├── defective_chessboard_problem.cpp │ ├── dijkstra'sAlgo.cpp │ ├── exponential_search.cpp │ ├── heap_sort.cpp │ ├── insertion-sort.CPP │ ├── lowest common ancestor.cpp │ ├── merge_sort.cpp │ ├── nQueen.cpp │ ├── no._of_1_bit.cpp │ ├── palindrome.cpp │ ├── peak_index_mountain_array.cpp │ ├── pivot_index_array.cpp │ ├── pyramid.cpp │ ├── queue from 2 stacks.cpp │ ├── quick_sort.cpp │ ├── radix_sort.cpp │ ├── search_bst.cpp │ ├── selection_sort.cpp │ ├── selectionsort.cpp │ ├── shell-sort.cpp │ ├── sum-product.cpp │ ├── swap numbers.cpp │ ├── trailingZeroesInFactorial.cpp │ └── trapping rain water.cpp ├── C │ ├── 01_Knapsack.c │ ├── Donut.c │ ├── Fractional_Knapsack.c │ ├── JohnsonsAlgorithm.c │ ├── NQueen.c │ ├── Pointer.c │ ├── Topological ordering for digraph.c │ ├── Vowel_consonant.c │ ├── array_pointer.c │ ├── binarySearch.c │ ├── bubbleSort.c │ ├── call_by_reference.c │ ├── dijkstras_algorithm.c │ ├── donutt.c │ ├── double_pointer.c │ ├── fast_inverse_squareroot.c │ ├── half pyramid .c │ ├── magic number.c │ ├── palindrome.c │ ├── prims.c │ ├── return_pointer.c │ ├── right-angledtriangle-pattern.c │ ├── starpattern.c │ ├── static_type.c │ ├── structure.c │ ├── swap numbers.c │ └── uninon.c ├── Java │ ├── 234.Palindrome_Linked_List.java │ ├── Armstrong_number.java │ ├── Array.java │ ├── BFS.java │ ├── BinarySearch.java │ ├── Block_Swap_Algorithm.java │ ├── Booth's_Multiplication_Algorithm.java │ ├── BubbleSort.java │ ├── ContainsDuplicate_217.java │ ├── CountSort.java │ ├── Custom-HashMap.java │ ├── CustomSinglyLinkedList.java │ ├── Cyclic_Sort.java │ ├── Doubly_Linked_List.java │ ├── Euclidean_Algorithm.java │ ├── FirstRepeatedCharacter.java │ ├── Floyd-Warshall.java │ ├── GCD.java │ ├── GCD_LCM.java │ ├── Hamiltonian_Cycle.java │ ├── HammingDistance.java │ ├── HappyNumber.java │ ├── Heap_Sort.java │ ├── Insertion Sort.java │ ├── InsertionSort.java │ ├── JobScheduling.java │ ├── Kruskal_Minimum_Spanning_Tree.java │ ├── LRU.java │ ├── Leaders_in_array.java │ ├── ListNode.java │ ├── ManeuveringAlgorithm.java │ ├── MatrixAddition.java │ ├── MatrixChainMultiplication.java │ ├── MinimumJumps.java │ ├── MoveZeroesToLeft.java │ ├── NQueena.java │ ├── NQueens.java │ ├── NotASubsetSum.java │ ├── Order_Agnostic_Binary_Search.java │ ├── PalindromeLinkedList.java │ ├── Quick Sort.java │ ├── QuickSortAlgorithmJava.java │ ├── RobinKarp.java │ ├── RotateArray.java │ ├── RotatedSortedArray.java │ ├── SelectioSort.java │ ├── SieveOfEratosthenes.java │ ├── Singly_Linked_List.java │ ├── Spring │ │ ├── Controller │ │ │ └── UserController.java │ │ ├── Test │ │ │ └── ApplicationTests.java │ │ ├── User.java │ │ ├── application.properties │ │ ├── pom.xml │ │ └── repo │ │ │ └── UserRepository.java │ ├── Stepping_stairs.java │ ├── SubArrayWithGivenSum.java │ ├── Timsort.java │ ├── TrappedRain.java │ ├── Warnsdorff_Algorithm.java │ ├── atmcode.java │ ├── bellman_ford.java │ ├── binary_search.java │ ├── bucket_sort.java │ ├── coinchange.java │ ├── designpatterns │ │ └── singleton │ │ │ ├── EagerInitializedSingleton.java │ │ │ ├── LazyInitializedSingleton.java │ │ │ ├── StaticBlockSingleton.java │ │ │ └── ThreadSafeSingleton.java │ ├── dijkstra alogrithm.java │ ├── fibonacci series.java │ ├── find-first-and-last-position-of-element-in-sorted-array.java │ ├── half pyramid .java │ ├── josephus_algorithm.java │ ├── kadane's algo.java │ ├── kadane.java │ ├── linear search.java │ ├── matrixrowsum.java │ ├── mergesort.java │ ├── myserynumber.java │ ├── pattern.java │ ├── remove-nth-node-from-end-of-list.java │ ├── reverseofstring.java │ ├── reversestring.java │ ├── strobogrammatic_number.java │ ├── swap.java │ ├── towerOfHanoi.java │ └── trailingZeroesFromFactorial.java ├── JavaScript │ ├── Arrya_Equaliser.js │ ├── Factors.js │ ├── a_star.js │ ├── bfs.js │ ├── bubble_sort.js │ ├── bubblesort.js │ ├── dfs.js │ ├── dijstras.js │ ├── insertionsort.js │ ├── kmp.js │ ├── mergesort.js │ ├── notes.js │ ├── quicksort.js │ └── selectionsort.js ├── Powershell │ └── leapYear.ps1 ├── Python │ ├── Armstrong.py │ ├── Dollar to Indian Rupee converter.py │ ├── DutchNationalFlagProb.py │ ├── Fizz-Buzz.py │ ├── GCD.py │ ├── JosephusProblem.py │ ├── Merge mails.py │ ├── N-Queens.py │ ├── NQueens.py │ ├── Permutations calculator.py │ ├── Quick-sort.py │ ├── TestSpeed.py │ ├── applicationbilling.py │ ├── area.py │ ├── arraysum.py │ ├── binary_tree.py │ ├── binarysearch.py │ ├── breadth_first_search.py │ ├── bucket_sort.py │ ├── checkPalindrome.py │ ├── circuit_level_firewall.py │ ├── create a dictionary.py │ ├── depth_first_search.py │ ├── dijkstras_algo.py │ ├── discordbot.py │ ├── exponential_search.py │ ├── fibonacci.py │ ├── floyd_warshall.py │ ├── gcf.py │ ├── insertion_sort.py │ ├── josephus_iterative.py │ ├── largest_prime_factor.py │ ├── merge_sort.py │ ├── miles-to-kms-convertor.py │ ├── power_set.py │ ├── prime between 1 and 100.py │ ├── quick_sort.py │ ├── selection_sort.py │ ├── shell_sort.py │ ├── swap numbers.py │ └── topological_sort.py └── Ruby │ ├── Binary.rb │ ├── BubbleSort.rb │ ├── Fib.rb │ ├── Palindrome.rb │ ├── PascalTriangle.rb │ ├── Reverse.rb │ ├── Rotate.rb │ ├── add.rb │ ├── binarySearch.rb │ ├── bubbblesort.rb │ ├── global variables.rb │ ├── half pyramid .rb │ ├── leapyear.rb │ ├── mergesort.rb │ ├── primeornot.rb │ └── swap numbers using XOR.rb ├── CODE_OF_CONDUCT.md ├── LICENSE └── README.md /Algos/C++/01_Knapsack.cpp: -------------------------------------------------------------------------------- 1 | /* recursive implementation of 0-1 Knapsack problem */ 2 | #include 3 | using namespace std; 4 | 5 | int max(int a, int b) { return (a > b) ? a : b; } 6 | 7 | int knapSack(int W, int wt[], int val[], int n) 8 | { 9 | 10 | // Base Case 11 | if (n == 0 || W == 0) 12 | return 0; 13 | 14 | if (wt[n - 1] > W) 15 | return knapSack(W, wt, val, n - 1); 16 | 17 | else 18 | return max( 19 | val[n - 1] + knapSack(W - wt[n - 1],wt, val, n - 1),knapSack(W, wt, val, n - 1)); 20 | } 21 | 22 | int main() 23 | { 24 | int val[] = { 60, 100, 120 }; 25 | int wt[] = { 10, 20, 30 }; 26 | int W = 50; 27 | int n = sizeof(val) / sizeof(val[0]); 28 | cout << knapSack(W, wt, val, n); 29 | return 0; 30 | } -------------------------------------------------------------------------------- /Algos/C++/Alphabet_triangle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | char ch='A'; 6 | int i, j, k, m; 7 | for(i=1;i<=5;i++) 8 | { 9 | for(j=5;j>=i;j--) 10 | cout<<" "; 11 | for(k=1;k<=i;k++) 12 | cout< 2 | using namespace std; 3 | 4 | int main() { 5 | int num, originalNum, remainder, result = 0; 6 | cout << "Enter a three-digit integer: "; 7 | cin >> num; 8 | originalNum = num; 9 | 10 | while (originalNum != 0) { 11 | // remainder contains the last digit 12 | remainder = originalNum % 10; 13 | 14 | result += remainder * remainder * remainder; 15 | 16 | // removing last digit from the orignal number 17 | originalNum /= 10; 18 | } 19 | 20 | if (result == num) 21 | cout << num << " is an Armstrong number."; 22 | else 23 | cout << num << " is not an Armstrong number."; 24 | 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /Algos/C++/Count Sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void input_array(vector &arr) 5 | { 6 | int N; cin >> N; 7 | for(int i=0; i> inp; 9 | arr.push_back(inp); 10 | } 11 | } 12 | 13 | void count_sort(vector &arr) 14 | { 15 | int N = arr.size(); 16 | int max_ele = *max_element(arr.begin(), arr.end()); 17 | int min_ele = *min_element(arr.begin(), arr.end()); 18 | int range = max_ele - min_ele + 1; 19 | 20 | vector res(N); 21 | vector count(range); 22 | 23 | for (int i = 0; i < N; i++) 24 | count[arr[i] - min_ele]++; 25 | 26 | for (int i = 1; i < range; i++) 27 | count[i] += count[i - 1]; 28 | 29 | for (int i = N - 1; i >= 0; i--) 30 | { 31 | res[count[arr[i] - min_ele] - 1] = arr[i]; 32 | count[arr[i] - min_ele]--; 33 | } 34 | 35 | for (int i = 0; i < N; i++) 36 | arr[i] = res[i]; 37 | } 38 | 39 | void print_array(vector &arr) 40 | { 41 | for (int i = 0; i < arr.size(); i++) 42 | cout << arr[i] << " "; 43 | cout << endl; 44 | } 45 | 46 | int main() 47 | { 48 | vector arr; 49 | input_array(arr); 50 | count_sort(arr); 51 | print_array(arr); 52 | return 0; 53 | } -------------------------------------------------------------------------------- /Algos/C++/Factorial.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | 7 | { 8 | 9 | int i,fact=1,number; 10 | 11 | cout<<"Enter any Number: "; 12 | 13 | cin>>number; 14 | 15 | for(i=1;i<=number;i++){ 16 | 17 | fact=fact*i; 18 | 19 | } 20 | 21 | cout<<"Factorial of " < 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | 7 | int n, t1 = 0, t2 = 1, nextTerm = 0; 8 | 9 | cout << "Enter the number of terms: "; 10 | 11 | cin >> n; 12 | 13 | cout << "Fibonacci Series: "; 14 | 15 | for (int i = 1; i <= n; ++i) { 16 | 17 | // Prints the first two terms. 18 | 19 | if(i == 1) { 20 | 21 | cout << t1 << ", "; 22 | 23 | continue; 24 | 25 | } 26 | 27 | if(i == 2) { 28 | 29 | cout << t2 << ", "; 30 | 31 | continue; 32 | 33 | } 34 | 35 | nextTerm = t1 + t2; 36 | 37 | t1 = t2; 38 | 39 | t2 = nextTerm; 40 | 41 | 42 | 43 | cout << nextTerm << ", "; 44 | 45 | } 46 | 47 | return 0; 48 | 49 | } 50 | -------------------------------------------------------------------------------- /Algos/C++/Fibonacci.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int n, t1 = 0, t2 = 1, nextTerm = 0; 6 | 7 | cout << "Enter the number of terms: "; 8 | cin >> n; 9 | 10 | cout << "Fibonacci Series: "; 11 | 12 | for (int i = 1; i <= n; ++i) { 13 | // Prints the first two terms. 14 | if(i == 1) { 15 | cout << t1 << ", "; 16 | continue; 17 | } 18 | if(i == 2) { 19 | cout << t2 << ", "; 20 | continue; 21 | } 22 | nextTerm = t1 + t2; 23 | t1 = t2; 24 | t2 = nextTerm; 25 | 26 | cout << nextTerm << ", "; 27 | } 28 | return 0; 29 | } -------------------------------------------------------------------------------- /Algos/C++/GCD.cpp: -------------------------------------------------------------------------------- 1 | int GCD(int A, int B) { 2 | int m = min(A, B), gcd; 3 | for(int i = m; i > 0; --i) 4 | if(A % i == 0 && B % i == 0) { 5 | gcd = i; 6 | return gcd; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Algos/C++/Heap-Sort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for implementation of Heap Sort 2 | #include 3 | 4 | using namespace std; 5 | 6 | 7 | void CreateHeap(int arr[], int n, int i) 8 | { 9 | int largest = i; 10 | int l = 2*i + 1; 11 | int r = 2*i + 2; 12 | if (l < n && arr[l] > arr[largest]) 13 | largest = l; 14 | if (r < n && arr[r] > arr[largest]) 15 | largest = r; 16 | if (largest != i) 17 | { 18 | swap(arr[i], arr[largest]); 19 | CreateHeap(arr, n, largest); 20 | } 21 | } 22 | 23 | // main function to do heap sort 24 | void heapSort(int arr[], int n) 25 | { 26 | for (int i = n / 2 - 1; i >= 0; i--) 27 | CreateHeap(arr, n, i); 28 | for (int i=n-1; i>=0; i--) 29 | { 30 | swap(arr[0], arr[i]); 31 | CreateHeap(arr, i, 0); 32 | } 33 | } 34 | 35 | /* A utility function to print array of size n */ 36 | void printArray(int arr[], int n) 37 | { 38 | for (int i=0; i 2 | using namespace std; 3 | 4 | class Node 5 | { 6 | public: 7 | int data; 8 | Node *left; 9 | Node *right; 10 | Node(int data) 11 | { 12 | this->data = data; 13 | left = right = NULL; 14 | } 15 | }; 16 | 17 | void inOrder(Node *root) 18 | { 19 | stack s; 20 | Node *curr = root; 21 | 22 | while (curr != NULL || s.empty() == false) 23 | { 24 | while (curr != NULL) 25 | { 26 | s.push(curr); 27 | curr = curr->left; 28 | } 29 | 30 | curr = s.top(); 31 | s.pop(); 32 | 33 | cout << curr->data << " "; 34 | 35 | curr = curr->right; 36 | } 37 | } 38 | 39 | Node *construct_tree() 40 | { 41 | Node *root = new Node(0); 42 | root->left = new Node(1); 43 | root->right = new Node(2); 44 | root->left->left = new Node(3); 45 | root->left->right = new Node(4); 46 | root->right->left = new Node(5); 47 | root->right->right = new Node(6); 48 | return root; 49 | } 50 | 51 | int main() 52 | { 53 | Node *root = construct_tree(); 54 | inOrder(root); 55 | return 0; 56 | } -------------------------------------------------------------------------------- /Algos/C++/Josephus_algorithm.cpp: -------------------------------------------------------------------------------- 1 | // Josephus Algorithm in C++ 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | /* 7 | One liner Code for Josephus Algorith 8 | int josephus(int N, int K) { 9 | if (N == 1) 10 | return 1; 11 | else 12 | return (josephus(N - 1, K) + K - 1) % N + 1; 13 | } 14 | */ 15 | 16 | struct node{ 17 | int player_no; 18 | struct node *next; 19 | }; 20 | 21 | struct node *start , *ptr , *new_node; 22 | 23 | int main(void) 24 | { 25 | int n , k=3; 26 | cout <<"Enter number of player : "; 27 | cin >> n; 28 | start = malloc(sizeof(struct node)); 29 | start->player_no = 1; 30 | 31 | for(int i=2; i<=n; i++) 32 | { 33 | new_node = malloc(sizeof(struct node)); 34 | ptr->next =new_node; 35 | new_node->player_no=i; 36 | new_node->next = start; 37 | ptr = new_node; 38 | } 39 | 40 | for(int count=n ; count>1;count--) 41 | { 42 | for(int i=0 ; inext; 45 | cout << "Delete : " << ptr->next->player_no; 46 | ptr->next = ptr->next->next; 47 | } 48 | } 49 | cout << "surviver : "<player_no; 50 | } -------------------------------------------------------------------------------- /Algos/C++/Kadane's_Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int KadaneAlgorithm (int arr[], int size){ 6 | int sum=0; 7 | int maxsum=INT_MIN; 8 | for(int i=0;i> size; 23 | int arr[size]; 24 | cout<< "Enter the elements "; 25 | for(int i=0;i>arr[i]; 27 | } 28 | 29 | int sum = KadaneAlgorithm(arr,size); 30 | cout<<"Maximum Subarray sum is: "< 2 | using namespace std; 3 | 4 | void DFS(int node, vector adj[], vector& visited, stack& Stack){ 5 | visited[node]=true; 6 | for(auto neigh : adj[node]) 7 | if(!visited[neigh]) 8 | DFS(neigh, adj, visited, Stack); 9 | Stack.push(node); 10 | } 11 | 12 | int KosarajuAlgo(int V, vector adj[]){ 13 | int ans = 0; 14 | vector visited(V, false); 15 | stack Stack; 16 | for(int node=0; node adjTranspose[V]; 21 | for(int node=0; node visited1(V, false); 26 | stack Stack1; 27 | while(!Stack.empty()){ 28 | int node = Stack.top(); 29 | if(!visited1[node]){ 30 | DFS(node, adjTranspose, visited1, Stack1); 31 | ans++; 32 | } 33 | Stack.pop(); 34 | } 35 | return ans; 36 | } 37 | 38 | int main(){ 39 | int V, E; 40 | cin >> V >> E; 41 | vector adj[V]; 42 | for(int i=0; i> u >> v; 45 | adj[u].push_back(v); 46 | } 47 | cout << KosarajuAlgo(V, adj); 48 | return 0; 49 | } -------------------------------------------------------------------------------- /Algos/C++/Kruskal’s_algorithim.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | #include 4 | using namespace std; 5 | 6 | class DSU { 7 | int* parent; 8 | int* rank; 9 | 10 | public: 11 | DSU(int n) 12 | { 13 | parent = new int[n]; 14 | rank = new int[n]; 15 | 16 | for (int i = 0; i < n; i++) { 17 | parent[i] = -1; 18 | rank[i] = 1; 19 | } 20 | } 21 | 22 | int find(int i) 23 | { 24 | if (parent[i] == -1) 25 | return i; 26 | 27 | return parent[i] = find(parent[i]); 28 | } 29 | 30 | void unite(int x, int y) 31 | { 32 | int s1 = find(x); 33 | int s2 = find(y); 34 | 35 | if (s1 != s2) { 36 | if (rank[s1] < rank[s2]) { 37 | parent[s1] = s2; 38 | rank[s2] += rank[s1]; 39 | } 40 | else { 41 | parent[s2] = s1; 42 | rank[s1] += rank[s2]; 43 | } 44 | } 45 | } 46 | }; 47 | 48 | class Graph { 49 | vector > edgelist; 50 | int V; 51 | 52 | public: 53 | Graph(int V) { this->V = V; } 54 | 55 | void addEdge(int x, int y, int w) 56 | { 57 | edgelist.push_back({ w, x, y }); 58 | } 59 | 60 | void kruskals_mst() 61 | { 62 | sort(edgelist.begin(), edgelist.end()); 63 | 64 | 65 | DSU s(V); 66 | int ans = 0; 67 | cout << "Following are the edges in the " 68 | "constructed MST" 69 | << endl; 70 | for (auto edge : edgelist) { 71 | int w = edge[0]; 72 | int x = edge[1]; 73 | int y = edge[2]; 74 | 75 | if (s.find(x) != s.find(y)) { 76 | s.unite(x, y); 77 | ans += w; 78 | cout << x << " -- " << y << " == " << w 79 | << endl; 80 | } 81 | } 82 | 83 | cout << "Minimum Cost Spanning Tree: " << ans; 84 | } 85 | }; 86 | 87 | int main() 88 | { 89 | /* Let us create following weighted graph 90 | 10 91 | 0--------1 92 | | \ | 93 | 6| 5\ |15 94 | | \ | 95 | 2--------3 96 | 4 */ 97 | Graph g(4); 98 | g.addEdge(0, 1, 10); 99 | g.addEdge(1, 3, 15); 100 | g.addEdge(2, 3, 4); 101 | g.addEdge(2, 0, 6); 102 | g.addEdge(0, 3, 5); 103 | 104 | g.kruskals_mst(); 105 | return 0; 106 | } 107 | 108 | -------------------------------------------------------------------------------- /Algos/C++/Longest Consecutive Subsequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int find_LongestConsecutiveSubsequence(vector arr, int N) 5 | { 6 | unordered_set S; 7 | int res = 0; 8 | for (int i = 0; i < N; i++) 9 | { 10 | S.insert(arr[i]); 11 | } 12 | for (int i = 0; i < N; i++) 13 | { 14 | if (S.find(arr[i] - 1) == S.end()) 15 | { 16 | int j = arr[i]; 17 | while (S.find(j) != S.end()) 18 | j++; 19 | res = max(j - arr[i], res); 20 | } 21 | } 22 | return res; 23 | } 24 | 25 | int main() 26 | { 27 | int N; 28 | cin >> N; 29 | vector arr(N); 30 | for (int i = 0; i < N; i++) 31 | { 32 | cin >> arr[i]; 33 | } 34 | cout << find_LongestConsecutiveSubsequence(arr, N) << endl; 35 | return 0; 36 | } -------------------------------------------------------------------------------- /Algos/C++/LongestCommonSubsequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Recursive - Top Down - Memoization 5 | int lcs_recursion(string s1, string s2, int m, int n, vector< vector > &dp) { 6 | if(dp[m][n] != -1) 7 | return dp[m][n]; 8 | if(m == 0 || n == 0) 9 | return 0; 10 | if(s1[m-1] == s2[n-1]) 11 | return dp[m][n] = 1 + lcs_recursion(s1, s2, m-1, n-1, dp); 12 | else 13 | return dp[m][n] = max(lcs_recursion(s1, s2, m-1, n, dp), lcs_recursion(s1, s2, m, n-1, dp)); 14 | } 15 | 16 | // Iterative - Bottom Up - Tabulation 17 | int lcs_iterative(string s1, string s2, int m, int n) { 18 | vector< vector > dp(m+1, vector(n+1, 0)); 19 | 20 | for(int i=1; i<=m; i++) { 21 | for(int j=1; j<=n; j++) { 22 | if(s1[i-1] == s2[j-1]) 23 | dp[i][j] = 1 + dp[i-1][j-1]; 24 | else 25 | dp[i][j] = max(dp[i-1][j], dp[i][j-1]); 26 | } 27 | } 28 | 29 | return dp[m][n]; 30 | } 31 | 32 | int main() 33 | { 34 | string s1 = "AGGTAB"; 35 | string s2 = "GXTXAYB"; 36 | 37 | int m = s1.size(), n = s2.size(); 38 | 39 | vector< vector > dp(m+1, vector(n+1, -1)); 40 | 41 | cout<<"The longest common subsequence is of length (memoization): "< 3 | using namespace std; 4 | 5 | #define V 5 6 | 7 | int minKey(int key[], bool mstSet[]) 8 | { 9 | int min = INT_MAX, min_index; 10 | 11 | for (int v = 0; v < V; v++) 12 | if (mstSet[v] == false && key[v] < min) 13 | min = key[v], min_index = v; 14 | 15 | return min_index; 16 | } 17 | 18 | void printMST(int parent[], int graph[V][V]) 19 | { 20 | cout << "Edge \tWeight\n"; 21 | for (int i = 1; i < V; i++) 22 | cout << parent[i] << " - " << i << " \t" 23 | << graph[i][parent[i]] << " \n"; 24 | } 25 | 26 | void primMST(int graph[V][V]) 27 | { 28 | 29 | int parent[V]; 30 | int key[V]; 31 | bool mstSet[V]; 32 | 33 | for (int i = 0; i < V; i++) 34 | key[i] = INT_MAX, mstSet[i] = false; 35 | 36 | key[0] = 0; 37 | parent[0] = -1; // First node is always root of MST 38 | 39 | for (int count = 0; count < V - 1; count++) { 40 | int u = minKey(key, mstSet); 41 | mstSet[u] = true; 42 | for (int v = 0; v < V; v++) 43 | if (graph[u][v] && mstSet[v] == false 44 | && graph[u][v] < key[v]) 45 | parent[v] = u, key[v] = graph[u][v]; 46 | } 47 | 48 | // printing the constructed MST 49 | printMST(parent, graph); 50 | } 51 | 52 | int main() 53 | { 54 | int graph[V][V] = { { 0, 2, 0, 6, 0 }, 55 | { 2, 0, 3, 8, 5 }, 56 | { 0, 3, 0, 0, 7 }, 57 | { 6, 8, 0, 0, 9 }, 58 | { 0, 5, 7, 9, 0 } }; 59 | 60 | primMST(graph); 61 | 62 | return 0; 63 | } 64 | 65 | -------------------------------------------------------------------------------- /Algos/C++/StockSpan.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | vector v = {5, 7, 13, 7, 5, 4, 3, 5, 6, 7, 8, 9, 2, 3}; 6 | vector result(v.size(), 1); 7 | stack s; 8 | 9 | s.push(0); 10 | 11 | for(int i=1; i 2 | using namespace std; 3 | 4 | void topologicalSort(vector< vector > graph, int n) { 5 | vector indegree(n, 0); 6 | 7 | stack st; 8 | 9 | for(int i=0; i > graph(n); 37 | 38 | graph[2] = {3}; 39 | graph[3] = {1}; 40 | graph[4] = {0, 1}; 41 | graph[5] = {0, 2}; 42 | 43 | cout<<"Topological Sorted DAG: "; 44 | topologicalSort(graph, n); 45 | 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /Algos/C++/Vector_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | 9 | int main() { 10 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 11 | int n; cin >> n; 12 | vector arr; 13 | int x; 14 | for(int i=0 ; i> x; 17 | arr.push_back(x); 18 | } 19 | sort(arr.begin(),arr.end()); 20 | for(int i=0 ; i 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | 9 | int main() { 10 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 11 | int n; cin >> n; 12 | vector arr; 13 | int x; 14 | for(int i=0 ; i> x; 17 | arr.push_back(x); 18 | } 19 | sort(arr.begin(),arr.end()); 20 | for(int i=0 ; i 5 | using namespace std; 6 | 7 | void balance(string s) 8 | { 9 | stack st; 10 | int l=s.length(); 11 | int i,flag=0; 12 | for(i=0;i>exp; 57 | balance(exp); 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /Algos/C++/bellmanford.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | vector bellman_ford(int V, vector> &edges, int S) 5 | { 6 | vector dist(V, 1e8); 7 | dist[S] = 0; 8 | for (int i = 0; i < V - 1; i++) 9 | { 10 | for (auto it : edges) 11 | { 12 | int u = it[0]; 13 | int v = it[1]; 14 | int wt = it[2]; 15 | if (dist[u] != 1e8 && dist[u] + wt < dist[v]) 16 | { 17 | dist[v] = dist[u] + wt; 18 | } 19 | } 20 | } 21 | 22 | for (auto it : edges) 23 | { 24 | int u = it[0]; 25 | int v = it[1]; 26 | int wt = it[2]; 27 | if (dist[u] != 1e8 && dist[u] + wt < dist[v]) 28 | { 29 | return {-1}; 30 | } 31 | } 32 | 33 | return dist; 34 | } 35 | 36 | int main() 37 | { 38 | 39 | int V = 6; 40 | vector> edges(7, vector(3)); 41 | edges[0] = {3, 2, 6}; 42 | edges[1] = {5, 3, 1}; 43 | edges[2] = {0, 1, 5}; 44 | edges[3] = {1, 5, -3}; 45 | edges[4] = {1, 2, -2}; 46 | edges[5] = {3, 4, -2}; 47 | edges[6] = {2, 4, 3}; 48 | 49 | int S = 0; 50 | vector dist = bellman_ford(V, edges, S); 51 | for (auto d : dist) 52 | { 53 | cout << d << " "; 54 | } 55 | cout << endl; 56 | 57 | return 0; 58 | } -------------------------------------------------------------------------------- /Algos/C++/binary-search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int binarySearch(vectorarr,int key){ 5 | int start=0; 6 | int end=arr.size()-1; 7 | while(start<=end){ 8 | int mid=(start+end)/2; 9 | if(arr[mid]==key){ 10 | return mid; 11 | } 12 | else if(arr[mid]>key){ 13 | end=mid-1; 14 | } 15 | else{ 16 | start=mid+1; 17 | } 18 | } 19 | return -1; 20 | } 21 | int main(){ 22 | vectorarr={1,2,3,4,5,6,7,8,9,10}; 23 | int key; 24 | cin>>key; 25 | cout< 2 | using namespace std; 3 | 4 | struct node { 5 | int key; 6 | struct node* left, * right; 7 | }; 8 | 9 | class bst 10 | { 11 | public: 12 | 13 | struct node* newNode(int item) { 14 | node* temp = new node; 15 | temp->key = item; 16 | temp->left = temp->right = NULL; 17 | return temp; 18 | } 19 | void inorder(node* root) { 20 | if (root != NULL) { 21 | inorder(root->left); 22 | cout << root->key << " -> "; 23 | inorder(root->right); 24 | } 25 | } 26 | 27 | 28 | node* insert(node* node, int key) { 29 | if (node == NULL) 30 | return newNode(key); 31 | if (key < node->key) 32 | node->left = insert(node->left, key); 33 | else 34 | node->right = insert(node->right, key); 35 | 36 | return node; 37 | } 38 | }; 39 | 40 | int main() { 41 | bst x; 42 | node* root = NULL; 43 | root = x.insert(root, 8); 44 | root = x.insert(root, 3); 45 | root = x.insert(root, 1); 46 | root = x.insert(root, 6); 47 | root = x.insert(root, 7); 48 | root = x.insert(root, 10); 49 | root = x.insert(root, 14); 50 | root = x.insert(root, 4); 51 | root = x.insert(root, 23); 52 | 53 | cout << "Inorder traversal: "; 54 | x.inorder(root); 55 | return 0; 56 | } -------------------------------------------------------------------------------- /Algos/C++/binary_tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | struct node 5 | { 6 | int data; 7 | node* llink; 8 | node* rlink; 9 | }; 10 | class tree 11 | { 12 | public: 13 | node* insert( int info, node* root) { 14 | char direction[10]; 15 | int i; 16 | node* temp = new node; 17 | node* curr = new node; 18 | node* prev = new node; 19 | temp->data = info; 20 | temp->llink = temp->rlink = NULL; 21 | if (root==NULL) 22 | { 23 | return temp; 24 | } 25 | cout << "Give Directions" << endl; 26 | cin >> direction; 27 | prev = NULL; 28 | curr = root; 29 | for ( i = 0; i < strlen(direction)&&(curr!=NULL); i++) 30 | { 31 | prev = curr; 32 | if (direction[i]=='L') 33 | { 34 | curr = curr->llink; 35 | } 36 | else 37 | { 38 | curr = curr->rlink; 39 | } 40 | 41 | } 42 | int x = i - 1; 43 | if (direction[x] == 'L') 44 | { 45 | prev->llink = temp; 46 | } 47 | else 48 | { 49 | prev->rlink = temp; 50 | } 51 | return root; 52 | 53 | } 54 | void preorderTraversal(struct node* node) { 55 | if (node == NULL) 56 | return; 57 | 58 | cout << node->data << "->"; 59 | preorderTraversal(node->llink); 60 | preorderTraversal(node->rlink); 61 | } 62 | void inorder(node* node) { 63 | if (node==NULL) 64 | { 65 | return; 66 | } 67 | inorder(node->llink); 68 | cout << node->data << "->"; 69 | inorder(node->rlink); 70 | 71 | } 72 | void postorder(node* node) { 73 | if (node == NULL) 74 | { 75 | return; 76 | } 77 | inorder(node->llink); 78 | inorder(node->rlink); 79 | cout << node->data << "->"; 80 | 81 | } 82 | }; 83 | int main() { 84 | tree obj; 85 | node* root = NULL; 86 | root = obj.insert(1, root); 87 | root = obj.insert(2, root); 88 | root = obj.insert(3, root); 89 | root = obj.insert(4, root); 90 | root = obj.insert(5, root); 91 | obj.preorderTraversal(root); 92 | cout << endl; 93 | obj.inorder(root); 94 | cout << endl; 95 | obj.postorder(root); 96 | } 97 | //Directions to be given in capital letters and L for left and R for right 98 | //Example: LLR for left left right -------------------------------------------------------------------------------- /Algos/C++/binarysearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int binarySearch(vectorarr,int key){ 5 | int start=0; 6 | int end=arr.size()-1; 7 | while(start<=end){ 8 | int mid=(start+end)/2; 9 | if(arr[mid]==key){ 10 | return mid; 11 | } 12 | else if(arr[mid]>key){ 13 | end=mid-1; 14 | } 15 | else{ 16 | start=mid+1; 17 | } 18 | } 19 | return -1; 20 | } 21 | int main(){ 22 | vectorarr={1,2,3,4,5,6,7,8,9,10}; 23 | int key; 24 | cin>>key; 25 | cout< 2 | using namespace std; 3 | 4 | struct Node { 5 | int data; 6 | struct Node *left, *right; 7 | }; 8 | 9 | vector el; 10 | 11 | void leftBoundary(Node *root) 12 | { 13 | if(!root) 14 | return; 15 | if(find(el.begin(),el.end(),root->data)==el.end()) 16 | el.push_back(root->data); 17 | if(root->left) 18 | leftBoundary(root->left); 19 | else 20 | leftBoundary(root->right); 21 | } 22 | 23 | void leafNodes(Node *root) 24 | { 25 | if(!root) 26 | return; 27 | if(!root->left && !root->right) 28 | if(find(el.begin(),el.end(),root->data)==el.end()) 29 | el.push_back(root->data); 30 | leafNodes(root->left); 31 | leafNodes(root->right); 32 | } 33 | 34 | void rightBoundary(Node *root) 35 | { 36 | if(!root) 37 | return; 38 | if(root->right) 39 | rightBoundary(root->right); 40 | else 41 | rightBoundary(root->left); 42 | if(find(el.begin(),el.end(),root->data)==el.end()) 43 | el.push_back(root->data); 44 | } 45 | 46 | void printBoundary(Node *root) 47 | { 48 | if(!root) 49 | return; 50 | leftBoundary(root); 51 | leafNodes(root); 52 | rightBoundary(root); 53 | int i; 54 | for(i=0;idata = data; 64 | temp->left = temp->right = NULL; 65 | 66 | return temp; 67 | } 68 | 69 | int main() 70 | { 71 | // Let us construct the tree given in the above diagram 72 | struct Node* root = newNode(20); 73 | root->left = newNode(8); 74 | root->left->left = newNode(4); 75 | root->left->right = newNode(12); 76 | root->left->right->left = newNode(10); 77 | root->left->right->right = newNode(14); 78 | root->right = newNode(22); 79 | root->right->right = newNode(25); 80 | 81 | printBoundary(root); 82 | 83 | return 0; 84 | } 85 | -------------------------------------------------------------------------------- /Algos/C++/bubble-sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | void printarr(int arr[], int size){ 7 | for (int i = 0; i < size; ++i){ 8 | cout << arr[i] << " "; 9 | }// ending bracket for for loop 10 | cout << endl; 11 | }// ending bracket for printarr 12 | 13 | int main(){ 14 | int arr[] = {1,5,2,6,4,3,7,8}; 15 | int size = 8; 16 | int temp ; 17 | 18 | //print array before sorting 19 | printarr(arr, size); 20 | 21 | //sort array 22 | for ( int i = 0; i < size; ++i){ 23 | for (int j = 0; j < size-1; j++){ 24 | if (arr[j] > arr[j+1]){ //if j+1 is larger than j, swap j and j+1 25 | temp = arr[j]; 26 | arr[j] = arr[j+1]; 27 | arr[j+1] = temp; 28 | }// ending bracket for if 29 | }//ending bracket for inner for loop 30 | }//ending bracket for outter for loop 31 | 32 | //print array after sorting 33 | printarr(arr,size); 34 | 35 | return 0; 36 | } -------------------------------------------------------------------------------- /Algos/C++/build a tree from inorder and postorder.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node *left,*right; 8 | }; 9 | 10 | Node* newNode(int data) 11 | { 12 | Node* node = (Node*)malloc(sizeof(Node)); 13 | node->data = data; 14 | node->left = node->right = NULL; 15 | return (node); 16 | } 17 | void preOrder(Node* node) 18 | { 19 | if (node == NULL) 20 | return; 21 | printf("%d ", node->data); 22 | preOrder(node->left); 23 | preOrder(node->right); 24 | } 25 | int search(int arr[], int strt, int end, int value) 26 | { 27 | int i; 28 | for (i = strt; i <= end; i++) { 29 | if (arr[i] == value) 30 | break; 31 | } 32 | return i; 33 | } 34 | 35 | Node* buildTreeUtil(int in[],int post[],int is,int ie,int ps,int pe) 36 | { 37 | if(is>ie) 38 | return NULL; 39 | Node *root=newNode(post[pe]); 40 | if(is==ie) 41 | return root; 42 | int inPos=search(in,is,ie,post[pe]); 43 | root->left=buildTreeUtil(in,post,is,inPos-1,ps,ps+inPos-is-1); 44 | root->right=buildTreeUtil(in,post,inPos+1,ie,inPos,pe-1); 45 | return root; 46 | } 47 | Node* buildTree(int in[],int post[],int n) 48 | { 49 | if(n<1) 50 | return NULL; 51 | return buildTreeUtil(in,post,0,n-1,0,n-1); 52 | } 53 | 54 | int main() 55 | { 56 | int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 }; 57 | int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 }; 58 | int n = sizeof(in) / sizeof(in[0]); 59 | 60 | Node* root = buildTree(in, post, n); 61 | 62 | cout << "Preorder of the constructed tree : \n"; 63 | preOrder(root); 64 | 65 | return 0; 66 | } 67 | -------------------------------------------------------------------------------- /Algos/C++/cardgame.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | string solve(int n, vector A, vector B){ 4 | int d = 0; 5 | int e = 0; 6 | for(int i = 0; i e) 17 | return "Amal"; 18 | else 19 | return "Bimal"; 20 | } 21 | int main(){ 22 | int n = 5; 23 | vector A = {3, 2}; 24 | vector B = {5, 1, 4}; 25 | cout << solve(n, A, B) << endl; 26 | } 27 | -------------------------------------------------------------------------------- /Algos/C++/constructor overloading.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class construct // create a class construct 4 | { 5 | public: 6 | int a, b; // initialise two data members 7 | construct() // this is how default constructor is created 8 | { 9 | // We can also assign both values to zero 10 | a = 10; // intialise a with some value 11 | b = 20; // initialise b with some value 12 | } 13 | }; 14 | int main() 15 | { 16 | construct c; // creating an object of construct calls defualt constructor 17 | cout<< "a:" < 2 | #include 3 | using namespace std; 4 | //implent cyclic sort 5 | void cyclic_sort(vector &arr,int n){ 6 | int i=0; 7 | while(iarr={3,5,2,1,4}; 20 | int n=arr.size(); 21 | cyclic_sort(arr,n); 22 | for(int i=0;i<5;i++){ 23 | cout< 2 | #include 3 | using namespace std; 4 | int board[10][10],tile=1; 5 | void tileBoard(int trow,int tcol, int drow,int dcol,int size) 6 | { 7 | if(size==1) 8 | return; 9 | int tileNum=tile++; 10 | int qsize=size/2; 11 | /*First Quadrant*/ 12 | if(drow=tcol+qsize) 21 | { 22 | tileBoard(trow,tcol+qsize,drow,dcol,qsize); 23 | } 24 | else 25 | { 26 | board[trow+qsize-1][tcol+qsize]=tileNum; 27 | tileBoard(trow,tcol+qsize,trow+qsize-1,tcol+qsize,qsize); 28 | } 29 | /*Third Quadrant*/ 30 | if(drow>=trow+qsize && dcol=trow+qsize && dcol>=tcol+qsize) 41 | { 42 | tileBoard(trow+qsize,tcol+qsize,drow,dcol,qsize); 43 | } 44 | else 45 | { 46 | board[trow+qsize][tcol+qsize]=tileNum; 47 | tileBoard(trow+qsize,tcol+qsize,trow+qsize,tcol+qsize,qsize); 48 | } 49 | } 50 | void display(int n) 51 | { 52 | for(int i=0;i>n; 66 | cout<<"Enter the defective row and column:"; 67 | cin>>dr>>dc; 68 | tileBoard(0,0,dr,dc,n); 69 | display(n); 70 | 71 | } 72 | -------------------------------------------------------------------------------- /Algos/C++/dijkstra'sAlgo.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int miniDist(int distance[], bool Tset[]) // finding minimum distance 6 | { 7 | int minimum=INT_MAX,ind; 8 | 9 | for(int k=0;k<6;k++) 10 | { 11 | if(Tset[k]==false && distance[k]<=minimum) 12 | { 13 | minimum=distance[k]; 14 | ind=k; 15 | } 16 | } 17 | return ind; 18 | } 19 | 20 | void DijkstraAlgo(int graph[6][6],int src) // adjacency matrix 21 | { 22 | int distance[6]; // // array to calculate the minimum distance for each node 23 | bool Tset[6];// boolean array to mark visited and unvisited for each node 24 | 25 | 26 | for(int k = 0; k<6; k++) 27 | { 28 | distance[k] = INT_MAX; 29 | Tset[k] = false; 30 | } 31 | 32 | distance[src] = 0; // Source vertex distance is set 0 33 | 34 | for(int k = 0; k<6; k++) 35 | { 36 | int m=miniDist(distance,Tset); 37 | Tset[m]=true; 38 | for(int k = 0; k<6; k++) 39 | { 40 | // updating the distance of neighbouring vertex 41 | if(!Tset[k] && graph[m][k] && distance[m]!=INT_MAX && distance[m]+graph[m][k] 2 | #include 3 | using namespace std; 4 | int binary_search(vector &arr,int l,int r,int key){ 5 | if(l<=r){ 6 | int mid=(l+r)/2; 7 | if(arr[mid]==key){ 8 | return mid; 9 | } 10 | else if(arr[mid]>key){ 11 | return binary_search(arr,l,mid-1,key); 12 | } 13 | else{ 14 | return binary_search(arr,mid+1,r,key); 15 | } 16 | } 17 | return -1; 18 | } 19 | int exponential_search(vector &arr,int n,int key){ 20 | if(arr[0]==key){ 21 | return 0; 22 | } 23 | int i=1; 24 | while(iarr={1,2,3,4,5,6,7,8,9,10}; 32 | int n=arr.size(); 33 | int key=5; 34 | cout< 3 | 4 | using namespace std; 5 | 6 | 7 | void CreateHeap(int arr[], int n, int i) 8 | { 9 | int largest = i; 10 | int l = 2*i + 1; 11 | int r = 2*i + 2; 12 | if (l < n && arr[l] > arr[largest]) 13 | largest = l; 14 | if (r < n && arr[r] > arr[largest]) 15 | largest = r; 16 | if (largest != i) 17 | { 18 | swap(arr[i], arr[largest]); 19 | CreateHeap(arr, n, largest); 20 | } 21 | } 22 | 23 | // main function to do heap sort 24 | void heapSort(int arr[], int n) 25 | { 26 | for (int i = n / 2 - 1; i >= 0; i--) 27 | CreateHeap(arr, n, i); 28 | for (int i=n-1; i>=0; i--) 29 | { 30 | swap(arr[0], arr[i]); 31 | CreateHeap(arr, i, 0); 32 | } 33 | } 34 | 35 | /* A utility function to print array of size n */ 36 | void printArray(int arr[], int n) 37 | { 38 | for (int i=0; i 3 | using namespace std; 4 | 5 | 6 | void insertionSort(int arr[], int n) 7 | { 8 | int i, key, j; 9 | for (i = 1; i < n; i++) 10 | { 11 | key = arr[i]; 12 | j = i - 1; 13 | 14 | 15 | 16 | 17 | while (j >= 0 && arr[j] > key) 18 | { 19 | arr[j + 1] = arr[j]; 20 | j = j - 1; 21 | } 22 | arr[j + 1] = key; 23 | } 24 | } 25 | 26 | 27 | void printArray(int arr[], int n) 28 | { 29 | int i; 30 | for (i = 0; i < n; i++) 31 | cout << arr[i] << " "; 32 | cout << endl; 33 | } 34 | 35 | 36 | int main() 37 | { 38 | int arr[] = { 12, 11, 13, 5, 6 }; 39 | int n = sizeof(arr) / sizeof(arr[0]); 40 | 41 | insertionSort(arr, n); 42 | printArray(arr, n); 43 | 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /Algos/C++/lowest common ancestor.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node 5 | { 6 | int key; 7 | struct Node *left, *right; 8 | }; 9 | Node * newNode(int k) 10 | { 11 | Node *temp = new Node; 12 | temp->key = k; 13 | temp->left = temp->right = NULL; 14 | return temp; 15 | } 16 | bool path(Node *root, vector *p,int key) 17 | { 18 | if(!root) 19 | return false; 20 | (*p).push_back(root->key); 21 | if(root->key==key) 22 | return true; 23 | if(path(root->left,p,key)||path(root->right,p,key)) 24 | return true; 25 | (*p).pop_back(); 26 | return false; 27 | } 28 | int findLCA(Node *root,int n1,int n2) 29 | { 30 | vector path1,path2; 31 | int i; 32 | if((!path(root,&path1,n1))||(!path(root,&path2,n2))) 33 | return -1; 34 | for(i=0;ileft = newNode(2); 46 | root->right = newNode(3); 47 | root->left->left = newNode(4); 48 | root->left->right = newNode(5); 49 | root->right->left = newNode(6); 50 | root->right->right = newNode(7); 51 | cout << "LCA(4, 5) = " << findLCA(root, 4, 5)< 2 | using namespace std; 3 | int main(){ 4 | int num; 5 | int count=1; 6 | cout<<"enter the number"; 7 | cin>>num;//binary me 8 | while(num!=0){ 9 | if(num&1){++count;} 10 | num=num>>1; 11 | } 12 | cout<<"the number of 1 bit is"< 2 | using namespace std; 3 | int main(){int number,n; 4 | cin>>number; 5 | int arr[10]; 6 | int count=0; 7 | while(number!=0){arr[count]=number%10; 8 | number=number/10; 9 | ++count; 10 | } 11 | n=count; 12 | 13 | int c2=0; 14 | for(int i=0;i 2 | using namespace std; 3 | int peak(int arr[],int k){ 4 | int s=0; 5 | 6 | int e=k-1; 7 | int i; 8 | int m=s+((e-s)/2); 9 | while(s>k;//array size 28 | int arr[k]; 29 | for(int i=0;i>arr[i]; 31 | } 32 | cout< 2 | using namespace std; 3 | int pivot(int nums[],int k) {int sum=0; 4 | int i; 5 | for( i=0;i>k;//array size 22 | int nums[k];//array declaration 23 | for(int i=0;i>nums[i]; 25 | }//taking input 26 | cout< 2 | using namespace std: 3 | int main() 4 | { 5 | int rows; 6 | cout << "Ener number of rows:"; 7 | cin >> rows; 8 | for(int i =1; i<=rows; ++i) 9 | { 10 | for (int j=1; j<=i; ++j){ 11 | cout << "*"; 12 | } 13 | cout << "\n"; 14 | } 15 | return O; 16 | } 17 | -------------------------------------------------------------------------------- /Algos/C++/queue from 2 stacks.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | struct snode 6 | { 7 | int data; 8 | struct snode *next; 9 | }; 10 | 11 | struct Queue 12 | { 13 | struct snode *stack1; 14 | }; 15 | void push(struct snode **,int); 16 | int pop(struct snode**); 17 | void enqueue(struct Queue *q,int key) 18 | { 19 | push(&q->stack1,key); 20 | } 21 | void push(struct snode **top,int key) 22 | { 23 | struct snode *newnode=(struct snode*)malloc(sizeof(struct snode*)); 24 | if(newnode==NULL) 25 | { 26 | printf("Stack full\n"); 27 | return; 28 | } 29 | newnode->data=key; 30 | newnode->next=*top; 31 | *top=newnode; 32 | return; 33 | } 34 | int dequeue(struct Queue *q) 35 | { 36 | if(q->stack1==NULL) 37 | { 38 | printf("Empty queue\n"); 39 | return -1; 40 | } 41 | int res; 42 | if(q->stack1->next==NULL) 43 | { 44 | //q->stack1->data; 45 | res=pop(&q->stack1); 46 | return res; 47 | } 48 | //q->stack1->next; 49 | int x=pop(&q->stack1); 50 | res=dequeue(q); 51 | push(&q->stack1,x); 52 | return res; 53 | } 54 | int pop(struct snode **top) 55 | { 56 | if(*top!=NULL) 57 | { 58 | int x=(*top)->data; 59 | struct snode *newtop=(*top)->next; 60 | free(*top); 61 | *top=newtop; 62 | return x; 63 | } 64 | return -1; 65 | } 66 | 67 | int main() 68 | { 69 | struct Queue *q=(struct Queue*)malloc(sizeof(struct Queue)); 70 | q->stack1=NULL; 71 | enqueue(q,5); 72 | enqueue(q,10); 73 | enqueue(q,15); 74 | printf("%d ",dequeue(q)); 75 | printf("%d ",dequeue(q)); 76 | printf("%d ",dequeue(q)); 77 | return 0; 78 | } 79 | -------------------------------------------------------------------------------- /Algos/C++/quick_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int partition(int *a,int start,int end) 4 | { 5 | int pivot=a[end]; 6 | int partitionIndex=start; 7 | for(int i=start;i>n; 31 | int a[n]; 32 | for(int i=0;i>a[i]; 35 | } 36 | quicksort(a,0,n-1); 37 | for(int i=0;i 2 | 3 | using namespace std; 4 | 5 | // Get maximum value from array. 6 | int getMax(int arr[], int n) 7 | { 8 | int max = arr[0]; 9 | for (int i = 1; i < n; i++) 10 | if (arr[i] > max) 11 | max = arr[i]; 12 | return max; 13 | } 14 | 15 | // Count sort of arr[]. 16 | void countSort(int arr[], int n, int exp) 17 | { 18 | // Count[i] array will be counting the number of array values having that 'i' digit at their (exp)th place. 19 | int output[n], i, count[10] = {0}; 20 | 21 | // Count the number of times each digit occurred at (exp)th place in every input. 22 | for (i = 0; i < n; i++) 23 | count[(arr[i] / exp) % 10]++; 24 | 25 | // Calculating their cumulative count. 26 | for (i = 1; i < 10; i++) 27 | count[i] += count[i-1]; 28 | 29 | // Inserting values according to the digit '(arr[i] / exp) % 10' fetched into count[(arr[i] / exp) % 10]. 30 | for (i = n - 1; i >= 0; i--) 31 | { 32 | output[count[(arr[i] / exp) % 10] - 1] = arr[i]; 33 | count[(arr[i] / exp) % 10]--; 34 | } 35 | 36 | // Assigning the result to the arr pointer of main(). 37 | for (i = 0; i < n; i++) 38 | arr[i] = output[i]; 39 | } 40 | 41 | // Sort arr[] of size n using Radix Sort. 42 | void radixsort(int arr[], int n) 43 | { 44 | int exp, m; 45 | m = getMax(arr, n); 46 | 47 | // Calling countSort() for digit at (exp)th place in every input. 48 | for (exp = 1; m/exp > 0; exp *= 10) 49 | countSort(arr, n, exp); 50 | } 51 | 52 | int main() 53 | { 54 | int n, i; 55 | cout<<"\nEnter the number of data element to be sorted: "; 56 | cin>>n; 57 | 58 | int arr[n]; 59 | for(i = 0; i < n; i++) 60 | { 61 | cout<<"Enter element "<>arr[i]; 63 | } 64 | 65 | radixsort(arr, n); 66 | 67 | // Printing the sorted data. 68 | cout<<"\nSorted Data "; 69 | for (i = 0; i < n; i++) 70 | cout<<"->"< 2 | using namespace std; 3 | 4 | struct node { 5 | int key; 6 | struct node* left, * right; 7 | }; 8 | 9 | class bst 10 | { 11 | public: 12 | 13 | struct node* newNode(int item) { 14 | node* temp = new node; 15 | temp->key = item; 16 | temp->left = temp->right = NULL; 17 | return temp; 18 | } 19 | node* insert(node* node, int key) { 20 | if (node == NULL) 21 | return newNode(key); 22 | if (key < node->key) 23 | node->left = insert(node->left, key); 24 | else 25 | node->right = insert(node->right, key); 26 | 27 | return node; 28 | } 29 | bool search(node* root, int info) { 30 | if (root == NULL) 31 | return false; 32 | else if (root->key == info) 33 | return true; 34 | else if (info <= root->key) 35 | return search(root->left, info); 36 | else 37 | return search(root->right, info); 38 | } 39 | }; 40 | 41 | int main() { 42 | int y; 43 | bst x; 44 | node* root = NULL; 45 | root = x.insert(root, 8); 46 | root = x.insert(root, 3); 47 | root = x.insert(root, 1); 48 | root = x.insert(root, 6); 49 | root = x.insert(root, 7); 50 | root = x.insert(root, 10); 51 | root = x.insert(root, 14); 52 | root = x.insert(root, 4); 53 | root = x.insert(root, 23); 54 | cout << "\n"; 55 | cout << "Enter the element to be seached :"; 56 | cin >> y; 57 | if (x.search(root,y)) 58 | { 59 | cout << "Element Present"<<"\n"; 60 | } 61 | else 62 | { 63 | cout << "Element not Present" << "\n"; 64 | } 65 | 66 | } -------------------------------------------------------------------------------- /Algos/C++/selection_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | //implent selection sort 5 | void selection_sort(vector &arr,int n){ 6 | for(int i=0;iarr={6,7,2,1,4}; 19 | int n=arr.size(); 20 | selection_sort(arr,n); 21 | for(int i=0;i<5;i++){ 22 | cout< 2 | using namespace std; 3 | //Display function to print values. 4 | void display(int array[], int size) 5 | { 6 | int i; 7 | for (i = 0; i < size; i++) 8 | cout << array[i] << "\t"; 9 | 10 | cout << "\n"; 11 | } 12 | 13 | //The main function to drive other functions. 14 | int main() 15 | { 16 | int array[] = {5, 3, 1, 9, 8, 2, 4, 7}; 17 | int size = sizeof(array)/sizeof(array[0]); 18 | 19 | cout << "Before sorting: \n"; 20 | display(array, size); 21 | 22 | int i, j, min_idx,temp; 23 | 24 | //Loop to iterate elements of array. 25 | for (i = 0; i < size-1; i++) 26 | { 27 | //Here we try to find the min element in array. 28 | min_idx = i; 29 | for (j = i+1; j < size; j++){ 30 | if (array[j] < array[min_idx]) 31 | min_idx = j; 32 | } 33 | 34 | // Here we interchange the min element with first one. 35 | temp = array[min_idx]; 36 | array[min_idx] = array[i]; 37 | array[i] = temp; 38 | } 39 | 40 | cout << "After sorting: \n"; 41 | display(array, size); //Using dispaly function to print sorted array. 42 | 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /Algos/C++/shell-sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void shellSort(int arr[],int n){ 4 | for(int gap=n/2;gap>0;gap/=2){ 5 | for(int i=gap;i=gap && arr[j-gap]>temp;j-=gap){ 9 | arr[j]=arr[j-gap]; 10 | } 11 | arr[j]=temp; 12 | } 13 | } 14 | } 15 | int main(){ 16 | int arr[]={5,8,1,5,3,6,9,2,4,7}; 17 | int n=sizeof(arr)/sizeof(arr[0]); 18 | shellSort(arr,n); 19 | for(int i=0;i 2 | using namespace std; 3 | int main(){ 4 | int num; 5 | cout<<"enter the number"; 6 | cin>>num; 7 | int sum=0; 8 | int prdt=1; 9 | while(num!=0){ 10 | sum=sum+(num%10); 11 | prdt=prdt*(num%10); 12 | num=num/10; 13 | 14 | } 15 | 16 | cout<<"sum is:"< 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int a = 5, b = 10, temp; 8 | 9 | cout << "Before swapping." << endl; 10 | cout << "a = " << a << ", b = " << b << endl; 11 | 12 | temp = a; 13 | a = b; 14 | b = temp; 15 | 16 | cout << "\nAfter swapping." << endl; 17 | cout << "a = " << a << ", b = " << b << endl; 18 | 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /Algos/C++/trailingZeroesInFactorial.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int countTrailingZeros(int num) 5 | { 6 | if (num < 0) 7 | return -1; 8 | 9 | int count = 0; 10 | 11 | for (int i = 5; num / i >= 1; i *= 5) 12 | count += num / i; 13 | 14 | return count; 15 | } 16 | 17 | int main() 18 | { 19 | int num; 20 | cin>>num; 21 | cout<<"Number of trailing 0s in "<& height) { 4 | if (height.size() <= 2) return 0; 5 | int n = height.size(), maxLeft = height[0], maxRight = height[n-1]; 6 | int left = 1, right = n - 2, ans = 0; 7 | while (left <= right) { 8 | if (maxLeft < maxRight) { 9 | if (height[left] > maxLeft) 10 | maxLeft = height[left]; 11 | else 12 | ans += maxLeft - height[left]; 13 | left += 1; 14 | } else { 15 | if (height[right] > maxRight) 16 | maxRight = height[right]; 17 | else 18 | ans += maxRight - height[right]; 19 | right -= 1; 20 | } 21 | } 22 | return ans; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Algos/C/01_Knapsack.c: -------------------------------------------------------------------------------- 1 | #include 2 | int maxOf(int item1, int item2) 3 | { 4 | return (item1>item2) ? item1: item2; 5 | } 6 | int knapsack(int W, int weights[100], int profits[100],int n) 7 | { 8 | int table[n+1][W+1], i, j, temp, itemsIncluded[100]; 9 | for(i=0; i<=n; i++) 10 | { 11 | table[i][0] = 0; 12 | } 13 | for(j=0; j<=W; j++) 14 | { 15 | table[0][j] = 0; 16 | } 17 | 18 | for(j=1; j<=W; j++) 19 | { 20 | for(i=1; i<=n; i++) 21 | { 22 | if(weights[i] <= W) 23 | { 24 | if(j - weights[i] < 0) 25 | { 26 | table[i][j] = table[i-1][j]; 27 | } 28 | else 29 | { 30 | table[i][j] = maxOf(table[i-1][j], profits[i] + table[i-1][j - weights[i]]); 31 | } 32 | } 33 | else 34 | { 35 | table[i][j] = table[i-1][j]; 36 | } 37 | } 38 | } 39 | printf("The table made usng dynamic programmig is:\n"); 40 | for(i=0; i<=n; i++) 41 | { 42 | for(j=0; j<=W; j++) 43 | { 44 | printf("%d\t",table[i][j]); 45 | } 46 | printf("\n"); 47 | } 48 | 49 | i = n; 50 | j = W; 51 | temp = 1; 52 | 53 | while(i>0) 54 | { 55 | if(table[i][j]!=table[i-1][j]) 56 | { 57 | itemsIncluded[temp] = i; 58 | temp++; 59 | j = j - weights[i]; 60 | i--; 61 | } 62 | else 63 | { 64 | i--; 65 | } 66 | } 67 | 68 | printf("\nItems included are : "); 69 | for(i=temp-1; i>=1; i--) 70 | { 71 | printf("%d ",itemsIncluded[i]); 72 | } 73 | 74 | return table[n][W]; 75 | } 76 | void main() 77 | { 78 | int n, maxProfit, profits[100], weights[100], W, i; 79 | printf("Enter the number of items: "); 80 | scanf("%d", &n); 81 | for(i=1; i<=n; i++) 82 | { 83 | printf("\n\n"); 84 | printf("Enter weight of item %d: ",i); 85 | scanf("%d", &weights[i]); 86 | printf("Enter profit of item %d: ",i); 87 | scanf("%d", &profits[i]); 88 | } 89 | printf("Enter weight of knapsack: "); 90 | scanf("%d", &W); 91 | maxProfit = knapsack(W,weights,profits,n); 92 | printf("\n\nMaximum Profit is %d",maxProfit); 93 | } -------------------------------------------------------------------------------- /Algos/C/Donut.c: -------------------------------------------------------------------------------- 1 | /* 2 | 3-d Rotating Donut. 3 | */ 4 | 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | int main() { 12 | float A = 0, B = 0; 13 | float i, j; 14 | int k; 15 | float z[1760]; 16 | char b[1760]; 17 | printf(""); 18 | for (;;) { 19 | memset(b, 32, 1760); 20 | memset(z, 0, 7040); 21 | for (j = 0; j < 6.28; j += 0.07) { 22 | for (i = 0; i < 6.28; i += 0.02) { 23 | float c = sin(i); 24 | float d = cos(j); 25 | float e = sin(A); 26 | float f = sin(j); 27 | float g = cos(A); 28 | float h = d + 2; 29 | float D = 1 / (c * h * e + f * g + 5); 30 | float l = cos(i); 31 | float m = cos(B); 32 | float n = sin(B); 33 | float t = c * h * g - f * e; 34 | int x = 40 + 30 * D * (l * h * m - t * n); 35 | int y = 12 + 15 * D * (l * h * n + t * m); 36 | int o = x + 80 * y; 37 | int N = 8 * ((f * e - c * d * g) * m - c * d * e - f * g - l * d * n); 38 | if (22 > y && y > 0 && x > 0 && 80 > x && D > z[o]) { 39 | z[o] = D; 40 | b[o] = ".,-~:;=!*#$@"[N > 0 ? N : 0]; 41 | } 42 | } 43 | } 44 | printf(""); 45 | for (k = 0; k < 1761; k++) { 46 | putchar(k % 80 ? b[k] : 10); 47 | A += 0.00004; 48 | B += 0.00002; 49 | } 50 | usleep(30000); 51 | } 52 | return 0; 53 | } -------------------------------------------------------------------------------- /Algos/C/Fractional_Knapsack.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct Objects 4 | { 5 | int number; 6 | float profit; 7 | float weight; 8 | float ratio; 9 | float vector; 10 | }; 11 | 12 | void knapsack(int n, float capacity, struct Objects obj_details[100]) 13 | { 14 | int i; 15 | float weight = 0, total_profit = 0; 16 | for(i=0; i 2 | #include 3 | 4 | int min(int a, int b); 5 | int cost[10][10], a[10][10], i, j, k, c; 6 | 7 | int main(int argc, char **argv) { 8 | int n, m; 9 | printf("Enter no of vertices: \n"); 10 | scanf("%d", &n); 11 | printf("\nEnter no od edges: \n"); 12 | scanf("%d", &m); 13 | printf("\nEnter the\nEDGE Cost\n"); 14 | for (k = 1; k <= m; k++) { 15 | scanf("%d", &i); 16 | scanf("%d", &j); 17 | scanf("%d", &c); 18 | a[i][j] = cost[i][j] = c; 19 | } 20 | for (i = 1; i <= n; i++) 21 | for (j = 1; j <= n; j++) { 22 | if (a[i][j] == 0 && i != j) 23 | a[i][j] = 31999; 24 | } 25 | for (k = 1; k <= n; k++) 26 | for (i = 1; i <= n; i++) 27 | for (j = 1; j <= n; j++) 28 | a[i][j] = min(a[i][j], a[i][k] + a[k][j]); 29 | printf("Resultant adjacency matrix\n"); 30 | for (i = 1; i <= n; i++) { 31 | for (j = 1; j <= n; j++) { 32 | if (a[i][j] != 31999) 33 | printf("%d ", a[i][j]); 34 | } 35 | printf("\n"); 36 | } 37 | return 0; 38 | } 39 | int min(int a, int b) { 40 | if (a < b) 41 | return a; 42 | else 43 | return b; 44 | } -------------------------------------------------------------------------------- /Algos/C/NQueen.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | int a[30], count = 0; 5 | int place(int pos) 6 | { 7 | int i; 8 | for (i = 1; i < pos; i++) 9 | { 10 | if ((a[i] == a[pos]) || ((abs(a[i] - a[pos]) == abs(i - pos)))) 11 | return 0; 12 | } 13 | return 1; 14 | } 15 | void print_sol(int n) 16 | { 17 | int i, j; 18 | count++; 19 | printf("\n\nSolution #%d:\n", count); 20 | for (i = 1; i <= n; i++) 21 | { 22 | for (j = 1; j <= n; j++) 23 | { 24 | if (a[i] == j) 25 | printf("Q\t"); 26 | else 27 | printf("*\t"); 28 | } 29 | printf("\n"); 30 | } 31 | } 32 | void queen(int n) 33 | { 34 | int k = 1; 35 | a[k] = 0; 36 | while (k != 0) 37 | { 38 | a[k] = a[k] + 1; 39 | while ((a[k] <= n) && !place(k)) 40 | a[k]++; 41 | if (a[k] <= n) 42 | { 43 | if (k == n) 44 | print_sol(n); 45 | else 46 | { 47 | k++; 48 | a[k] = 0; 49 | } 50 | } 51 | else 52 | k--; 53 | } 54 | } 55 | void main() 56 | { 57 | int i, n; 58 | clrscr(); 59 | printf("Enter the number of Queens\n"); 60 | scanf("%d", &n); 61 | queen(n); 62 | printf("\nTotal solutions=%d", count); 63 | getch(); 64 | } -------------------------------------------------------------------------------- /Algos/C/Pointer.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main(){ 3 | int number=50; 4 | int *p; 5 | p=&number;//stores the address of number variable 6 | printf("Address of p variable is %x \n",p); // p contains the address of the number therefore printing p gives the address of number. 7 | printf("Value of p variable is %d \n",*p); // As we know that * is used to dereference a pointer therefore if we print *p, we will get the value stored at the address contained by p. 8 | return 0; 9 | } 10 | -------------------------------------------------------------------------------- /Algos/C/Topological ordering for digraph.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(){ 4 | int i, j, k, n, a[10][10], indeg[10], flag[10], count=0; 5 | 6 | printf("Enter the no of vertices:\n"); 7 | scanf("%d",&n); 8 | 9 | printf("Enter the adjacency matrix:\n"); 10 | for(i=0;i 2 | int main() 3 | { 4 | char ch; 5 | bool isVowel = false; 6 | 7 | printf("Enter an alphabet: "); 8 | scanf("%c",&ch); 9 | 10 | if(ch=='a'||ch=='A'||ch=='e'||ch=='E'||ch=='i'||ch=='I' 11 | ||ch=='o'||ch=='O'||ch=='u'||ch=='U') 12 | { 13 | isVowel = true; 14 | 15 | } 16 | if (isVowel == true) 17 | printf("%c is a Vowel", ch); 18 | else 19 | printf("%c is a Consonant", ch); 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /Algos/C/array_pointer.c: -------------------------------------------------------------------------------- 1 | //array and pointer example 2 | 3 | #include 4 | 5 | void main() 6 | { 7 | int *p, sum, i; 8 | int x[5] = {10,20,30,40,50}; 9 | i = 0; 10 | p = x; /* initializing with base address of x */ 11 | printf("\nElement\t\tValue\t\t Address\n"); 12 | while(i < 5) 13 | { 14 | printf("x[%d]\t\t%d\t\t%u\n", i, *p, p); 15 | sum = sum + *p; /* accessing array element */ 16 | i++, p++; /* incrementing pointer */ 17 | } 18 | printf("\n Sum = %d\n", sum); 19 | printf("\n base address, &x[0] = %u\n", &x[0]); 20 | printf("\n current value of p = %u\n", p); 21 | } -------------------------------------------------------------------------------- /Algos/C/binarySearch.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int search(int arr[], int key, int size) { 5 | int low = 0,high = size-1,mid; 6 | 7 | while(low <= high) { 8 | mid = (low+high)/2; 9 | 10 | if(key == arr[mid]) return mid; 11 | else if(key < arr[mid]){ 12 | high = mid-1; 13 | } 14 | else if(key > arr[mid]) { 15 | low = mid+1; 16 | } 17 | } 18 | return 0; 19 | 20 | } 21 | 22 | 23 | int main() { 24 | 25 | printf("\nBinary search : "); 26 | int arr[] = {1,2,3,4,5,6,7,8,9}; 27 | int size = sizeof(arr)/sizeof(arr[0]); 28 | 29 | //Enter the number to search in the Array using Binary Search Algorithm 30 | //(for example 4) 31 | int ret = search(arr,4,size); 32 | 33 | if(ret) printf("\nTarget found at index %d.",ret); 34 | else printf("\nTarget not found."); 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /Algos/C/bubbleSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int count, temp, i, j; 5 | printf("How many elments do you want to enter?: "); 6 | scanf("%d",&count); 7 | int number[count]; 8 | printf("Enter %d elements: \n",count); 9 | for(i=0;i=0;i--){ 13 | for(j=0;j<=i;j++){ 14 | if(number[j]>number[j+1]){ 15 | temp=number[j]; 16 | number[j]=number[j+1]; 17 | number[j+1]=temp; 18 | } 19 | } 20 | } 21 | printf("Sorted elements: "); 22 | for(i=0;i 4 | 5 | void mathoperations(int x, int y, int *s, int *d); 6 | void main() 7 | { 8 | int x=20, y=10, s, d; // x and y input arguments, s and d output arguments 9 | mathoperations(x, y, &s, &d); 10 | printf(" s=%d\n d=%d\n", s,d); 11 | } 12 | 13 | 14 | void mathoperations(int a, int b, int *sum, int *diff) // x to a, y to b, address of s to sum and address of d to diff 15 | { 16 | *sum=a+b; //sum and diff are pointer variables 17 | *diff=a-b; //*sum and *diff are pointers 18 | } -------------------------------------------------------------------------------- /Algos/C/dijkstras_algorithm.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define INFINITY 9999 4 | #define MAX 10 5 | void dijikstra(int G[MAX][MAX], int n, int startnode); 6 | void main(){ 7 | int G[MAX][MAX], i, j, n, u; 8 | clrscr(); 9 | printf("\nEnter the no. of vertices:: "); 10 | scanf("%d", &n); 11 | printf("\nEnter the adjacency matrix::\n"); 12 | for(i=0;i < n;i++) 13 | for(j=0;j < n;j++) 14 | scanf("%d", &G[i][j]); 15 | printf("\nEnter the starting node:: "); 16 | scanf("%d", &u); 17 | dijikstra(G,n,u); 18 | getch(); 19 | } 20 | void dijikstra(int G[MAX][MAX], int n, int startnode) 21 | { 22 | int cost[MAX][MAX], distance[MAX], pred[MAX]; 23 | int visited[MAX], count, mindistance, nextnode, i,j; 24 | for(i=0;i < n;i++) 25 | for(j=0;j < n;j++) 26 | if(G[i][j]==0) 27 | cost[i][j]=INFINITY; 28 | else 29 | cost[i][j]=G[i][j]; 30 | for(i=0;i< n;i++) 31 | { 32 | distance[i]=cost[startnode][i]; 33 | pred[i]=startnode; 34 | visited[i]=0; 35 | } 36 | distance[startnode]=0; 37 | visited[startnode]=1; 38 | count=1; 39 | while(count < n-1){ 40 | mindistance=INFINITY; 41 | for(i=0;i < n;i++) 42 | if(distance[i] < mindistance&&!visited[i]) 43 | { 44 | mindistance=distance[i]; 45 | nextnode=i; 46 | } 47 | visited[nextnode]=1; 48 | for(i=0;i < n;i++) 49 | if(!visited[i]) 50 | if(mindistance+cost[nextnode][i] < distance[i]) 51 | { 52 | distance[i]=mindistance+cost[nextnode][i]; 53 | pred[i]=nextnode; 54 | } 55 | count++; 56 | } 57 | for(i=0;i < n;i++) 58 | if(i!=startnode) 59 | { 60 | printf("\nDistance of %d = %d", i, distance[i]); 61 | printf("\nPath = %d", i); 62 | j=i; 63 | do 64 | { 65 | j=pred[j]; 66 | printf(" <-%d", j); 67 | } 68 | while(j!=startnode); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /Algos/C/donutt.c: -------------------------------------------------------------------------------- 1 | /* 2 | 3-d Rotating Donut. 3 | */ 4 | 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | int main() { 12 | float A = 0, B = 0; 13 | float i, j; 14 | int k; 15 | float z[1760]; 16 | char b[1760]; 17 | printf(""); 18 | for (;;) { 19 | memset(b, 32, 1760); 20 | memset(z, 0, 7040); 21 | for (j = 0; j < 6.28; j += 0.07) { 22 | for (i = 0; i < 6.28; i += 0.02) { 23 | float c = sin(i); 24 | float d = cos(j); 25 | float e = sin(A); 26 | float f = sin(j); 27 | float g = cos(A); 28 | float h = d + 2; 29 | float D = 1 / (c * h * e + f * g + 5); 30 | float l = cos(i); 31 | float m = cos(B); 32 | float n = sin(B); 33 | float t = c * h * g - f * e; 34 | int x = 40 + 30 * D * (l * h * m - t * n); 35 | int y = 12 + 15 * D * (l * h * n + t * m); 36 | int o = x + 80 * y; 37 | int N = 8 * ((f * e - c * d * g) * m - c * d * e - f * g - l * d * n); 38 | if (22 > y && y > 0 && x > 0 && 80 > x && D > z[o]) { 39 | z[o] = D; 40 | b[o] = ".,-~:;=!*#$@"[N > 0 ? N : 0]; 41 | } 42 | } 43 | } 44 | printf(""); 45 | for (k = 0; k < 1761; k++) { 46 | putchar(k % 80 ? b[k] : 10); 47 | A += 0.00004; 48 | B += 0.00002; 49 | } 50 | usleep(30000); 51 | } 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /Algos/C/double_pointer.c: -------------------------------------------------------------------------------- 1 | //double pointer example 2 | 3 | #include 4 | 5 | void main() 6 | { 7 | int x, *p1, **p2; 8 | x = 100; 9 | p1 = &x; /* address of x */ 10 | p2 = &p1; /* address of p1 */ 11 | printf("p1 contains adress of x which is : %u\n",p1); 12 | printf("Address of p1 is : %u\n",&p1); 13 | printf("p2 contains adress of p1 which is : %u\n",p2); 14 | 15 | printf("Value of x is %d",**p2); 16 | } -------------------------------------------------------------------------------- /Algos/C/fast_inverse_squareroot.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // https://en.wikipedia.org/wiki/Fast_inverse_square_root 4 | float Q_rsqrt( float number ) 5 | { 6 | int i; 7 | float x2, y; 8 | const float threehalfs = 1.5F; 9 | x2 = number * 0.5F; 10 | y = number; 11 | i = * ( int * ) &y; 12 | i = 0x5f3759df - ( i >> 1 ); 13 | y = * ( float * ) &i; 14 | y = y * ( threehalfs - ( x2 * y * y ) ); 15 | return y; 16 | } 17 | 18 | int main() 19 | { 20 | float nn; 21 | printf("Enter a number: "); 22 | scanf("%f", &nn); 23 | float n = Q_rsqrt(nn); 24 | printf("Inverse Square Root of %f = %f", nn, n); 25 | } -------------------------------------------------------------------------------- /Algos/C/half pyramid .c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() { 3 | int i, j, rows; 4 | printf("Enter the number of rows: "); 5 | scanf("%d", &rows); 6 | for (i = 1; i <= rows; ++i) { 7 | for (j = 1; j <= i; ++j) { 8 | printf("* "); 9 | } 10 | printf("\n"); 11 | } 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /Algos/C/magic number.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main () 5 | { 6 | // declare integer variables 7 | int n, temp, rev = 0, digit, sum_of_digits = 0; 8 | 9 | printf (" Enter a Number: \n"); 10 | scanf (" %d", &n); // get the number 11 | 12 | temp = n; // assign the number to temp variable 13 | 14 | // use while loop to calculate the sum of digits 15 | while ( temp > 0) 16 | { 17 | // extract digit one by one and store into the sum_of_digits 18 | sum_of_digits = sum_of_digits + temp % 10; /* use modulus symbol to get the remainder of each iteration by temp % 10 */ 19 | temp = temp / 10; 20 | } 21 | 22 | temp = sum_of_digits; // assign the sum_of_digits to temp variable 23 | printf (" \n The sum of the digits = %d", temp); 24 | 25 | // get the reverse sum of given digits 26 | while ( temp > 0) 27 | { 28 | rev = rev * 10 + temp % 10; 29 | temp = temp / 10; 30 | } 31 | 32 | printf (" \n The reverse of the digits = %d", rev); 33 | 34 | 35 | printf (" \n The product of %d * %d = %d", sum_of_digits, rev, rev * sum_of_digits); 36 | // use if else statement to check the magic number 37 | if ( rev * sum_of_digits == n) 38 | { 39 | printf (" \n %d is a Magic Number. ", n); 40 | } 41 | else 42 | { 43 | printf (" \n %d is not a Magic Number. ", n); 44 | } 45 | return 0; 46 | 47 | } 48 | -------------------------------------------------------------------------------- /Algos/C/palindrome.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int n,r,sum=0,temp; 5 | printf("enter the number="); 6 | scanf("%d",&n); 7 | temp=n; 8 | while(n>0) 9 | { 10 | r=n%10; 11 | sum=(sum*10)+r; 12 | n=n/10; 13 | } 14 | if(temp==sum) 15 | printf("palindrome number "); 16 | else 17 | printf("not palindrome"); 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /Algos/C/prims.c: -------------------------------------------------------------------------------- 1 | // A C program for Prim's Minimum 2 | #include 3 | #include 4 | #include 5 | 6 | #define V 5 7 | 8 | int minKey(int key[], bool mstSet[]) 9 | { 10 | 11 | int min = INT_MAX, min_index; 12 | 13 | for (int v = 0; v < V; v++) 14 | if (mstSet[v] == false && key[v] < min) 15 | min = key[v], min_index = v; 16 | 17 | return min_index; 18 | } 19 | 20 | int printMST(int parent[], int graph[V][V]) 21 | { 22 | printf("Edge \tWeight\n"); 23 | for (int i = 1; i < V; i++) 24 | printf("%d - %d \t%d \n", parent[i], i, 25 | graph[i][parent[i]]); 26 | } 27 | 28 | void primMST(int graph[V][V]) 29 | { 30 | int parent[V]; 31 | int key[V]; 32 | bool mstSet[V]; 33 | 34 | for (int i = 0; i < V; i++) 35 | key[i] = INT_MAX, mstSet[i] = false; 36 | 37 | key[0] = 0; 38 | parent[0] = -1; 39 | 40 | for (int count = 0; count < V - 1; count++) { 41 | int u = minKey(key, mstSet); 42 | mstSet[u] = true; 43 | for (int v = 0; v < V; v++) 44 | if (graph[u][v] && mstSet[v] == false 45 | && graph[u][v] < key[v]) 46 | parent[v] = u, key[v] = graph[u][v]; 47 | } 48 | 49 | // print the constructed MST 50 | printMST(parent, graph); 51 | } 52 | 53 | int main() 54 | { 55 | 56 | int graph[V][V] = { { 0, 2, 0, 6, 0 }, 57 | { 2, 0, 3, 8, 5 }, 58 | { 0, 3, 0, 0, 7 }, 59 | { 6, 8, 0, 0, 9 }, 60 | { 0, 5, 7, 9, 0 } }; 61 | 62 | primMST(graph); 63 | 64 | return 0; 65 | } 66 | -------------------------------------------------------------------------------- /Algos/C/return_pointer.c: -------------------------------------------------------------------------------- 1 | // functin returning pointer 2 | 3 | #include 4 | int *larger(int *, int *); /* prototype */ 5 | void main ( ) 6 | { 7 | int a = 10; 8 | int b = 20; 9 | int *p; 10 | p = larger(&a,&b); //Function call 11 | printf ("larger is %d", *p); 12 | } 13 | int *larger (int *x, int *y) 14 | { 15 | if (*x>*y) 16 | return (x); /*address of a */ 17 | else 18 | return (y); /* address of b */ 19 | } -------------------------------------------------------------------------------- /Algos/C/right-angledtriangle-pattern.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int n; 5 | scanf("%d", &n); 6 | int x = 1; 7 | for (int i = 1; i <= n; i++) { 8 | for (int j = 0; j < i; j++) { 9 | printf("%d ", x); 10 | x++; 11 | } 12 | printf("\n"); 13 | } 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /Algos/C/starpattern.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void main() 4 | { 5 | int i,j,k; 6 | for(i=1; i<=5; i++) { for(j=4; j>=i; j--) 7 | { 8 | printf(" "); 9 | } 10 | for(k=1; k<=(2*i-1); k++) 11 | { 12 | printf("*"); 13 | } 14 | printf("\n"); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Algos/C/static_type.c: -------------------------------------------------------------------------------- 1 | //static example 2 | 3 | #include 4 | 5 | void stat(void); 6 | 7 | void main ( ) 8 | { 9 | int i; 10 | for(i=1; i<=3; i++) 11 | stat( ); 12 | } 13 | void stat(void) 14 | { 15 | static int x = 0; 16 | x = x+1; 17 | printf("x = %d\n", x); 18 | } -------------------------------------------------------------------------------- /Algos/C/structure.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CodeMacrocosm/Algo-a-Thon/01246a17515402f5199be758d8329b4ba7a25726/Algos/C/structure.c -------------------------------------------------------------------------------- /Algos/C/swap numbers.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | double first, second, temp; 5 | 6 | // Prompt user for the first number 7 | printf("Enter first number: "); 8 | scanf("%lf", &first); 9 | 10 | // Prompt user for the second number 11 | printf("Enter second number: "); 12 | scanf("%lf", &second); 13 | 14 | // Swap the values 15 | temp = first; // Store the value of 'first' in 'temp' 16 | first = second; // Assign the value of 'second' to 'first' 17 | second = temp; // Assign the value of 'temp' (initial 'first') to 'second' 18 | 19 | // Display the swapped values, formatted to 2 decimal points 20 | printf("\nAfter swapping, first number = %.2lf\n", first); 21 | printf("After swapping, second number = %.2lf\n", second); 22 | 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /Algos/C/uninon.c: -------------------------------------------------------------------------------- 1 | //sizeof() an union example 2 | 3 | #include 4 | void main() 5 | { 6 | int a; 7 | float b; 8 | struct student_details 9 | { 10 | char name[20]; 11 | int regno; 12 | }student; 13 | 14 | union code 15 | { 16 | int x; 17 | char c; 18 | float y; 19 | }sample; 20 | 21 | printf("size of variable a=%d\n",sizeof(a)); 22 | printf("size of variable b=%d\n",sizeof(b)); 23 | printf("size of structure variable is %d\n",sizeof(student)); 24 | printf("size of union variable is %d\n",sizeof(sample)); 25 | printf("size of integer is %d\n",sizeof(int)); 26 | 27 | } -------------------------------------------------------------------------------- /Algos/Java/234.Palindrome_Linked_List.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given the head of a singly linked list, return true if it is a palindrome or false otherwise. 3 | 4 | Example 1: 5 | 6 | Input: head = [1,2,2,1] 7 | Output: true 8 | Example 2: 9 | 10 | Input: head = [1,2] 11 | Output: false 12 | 13 | Constraints: 14 | 15 | The number of nodes in the list is in the range [1, 105]. 16 | 0 <= Node.val <= 9 17 | */ 18 | class Solution { 19 | public boolean isPalindrome(ListNode head) { 20 | if(head==null || head.next==null)return true; 21 | ListNode mid = middle(head); 22 | ListNode rev = reverse(mid); 23 | while(rev!=null){ 24 | if(head.val!=rev.val){ 25 | return false; 26 | } 27 | head=head.next; 28 | rev=rev.next; 29 | 30 | } 31 | return true; 32 | 33 | } 34 | public static ListNode middle(ListNode head){ 35 | ListNode slow=head; 36 | ListNode fast=head; 37 | while(fast!=null && fast.next!=null){ 38 | slow=slow.next; 39 | fast=fast.next.next; 40 | } 41 | return slow; 42 | 43 | } 44 | public static ListNode reverse (ListNode head){ 45 | if(head==null)return head; 46 | ListNode prev=null; 47 | while(head!=null){ 48 | ListNode temp = head.next; 49 | head.next=prev; 50 | prev=head; 51 | head=temp; 52 | } 53 | return prev; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /Algos/Java/Armstrong_number.java: -------------------------------------------------------------------------------- 1 | public class Armstrong { 2 | 3 | public static void main(String[] args) { 4 | 5 | int number = 371, originalNumber, remainder, result = 0; 6 | 7 | originalNumber = number; 8 | 9 | while (originalNumber != 0) 10 | { 11 | remainder = originalNumber % 10; 12 | result += Math.pow(remainder, 3); 13 | originalNumber /= 10; 14 | } 15 | 16 | if(result == number) 17 | System.out.println(number + " is an Armstrong number."); 18 | else 19 | System.out.println(number + " is not an Armstrong number."); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Algos/Java/Array.java: -------------------------------------------------------------------------------- 1 | public class CopyArray { 2 | public static void main(String[] args) { 3 | //Initialize array 4 | int [] arr1 = new int [] {1, 2, 3, 4, 5}; 5 | //Create another array arr2 with size of arr1 6 | int arr2[] = new int[arr1.length]; 7 | //Copying all elements of one array into another 8 | for (int i = 0; i < arr1.length; i++) { 9 | arr2[i] = arr1[i]; 10 | } 11 | //Displaying elements of array arr1 12 | System.out.println("Elements of original array: "); 13 | for (int i = 0; i < arr1.length; i++) { 14 | System.out.print(arr1[i] + " "); 15 | } 16 | 17 | System.out.println(); 18 | 19 | //Displaying elements of array arr2 20 | System.out.println("Elements of new array: "); 21 | for (int i = 0; i < arr2.length; i++) { 22 | System.out.print(arr2[i] + " "); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Algos/Java/BFS.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class BFS { 4 | 5 | private int V; 6 | private LinkedList adj[]; 7 | private boolean visited[]; 8 | 9 | BFS(int V) { 10 | this.V = V; 11 | adj = new LinkedList[V]; 12 | visited = new boolean[V]; 13 | for (int i = 0; i < V; i++) { 14 | adj[i] = new LinkedList(); 15 | } 16 | } 17 | 18 | void addEdge(int a, int b) { 19 | adj[a].add(b); 20 | } 21 | 22 | void BFS1(int n) { 23 | LinkedList queue = new LinkedList(); 24 | visited[n] = true; 25 | queue.add(n); 26 | while (queue.size() != 0) { 27 | n = queue.poll(); 28 | System.out.print(n + " "); 29 | Iterator i = adj[n].listIterator(); 30 | while (i.hasNext()) { 31 | int s = i.next(); 32 | if (!visited[s]) { 33 | visited[s] = true; 34 | queue.add(s); 35 | } 36 | } 37 | } 38 | } 39 | 40 | public static void main(String[] args) { 41 | BFS b = new BFS(5); 42 | b.addEdge(0,1); 43 | b.addEdge(0,2); 44 | b.addEdge(0,3); 45 | b.addEdge(1,2); 46 | b.addEdge(1,4); 47 | b.addEdge(2,4); 48 | b.addEdge(2,3); 49 | b.addEdge(3,2); 50 | b.addEdge(3,4); 51 | b.BFS1(0); 52 | } 53 | } -------------------------------------------------------------------------------- /Algos/Java/BinarySearch.java: -------------------------------------------------------------------------------- 1 | public class BinarySearch { 2 | public static void main(String[] args) { 3 | //Executing binary search algorithm 4 | int[] a={1,2,3,4,6,7,8,9,10}; 5 | int key=4; 6 | System.out.println("Element found at index "+binary(a,key)); 7 | 8 | 9 | } 10 | static int binaryS(int[] arr,int key){ 11 | int start=0; 12 | int end=arr.length-1; 13 | 14 | while (start<=end){ 15 | int mid=start+(end-start)/2; 16 | if (arr[mid]==key){ 17 | return mid; 18 | } 19 | if(arr[mid]>key){ 20 | end=mid-1; 21 | } 22 | if (arr[mid] arr[j + 1]) { 14 | int temp = arr[j]; 15 | arr[j] = arr[j + 1]; 16 | arr[j + 1] = temp; 17 | } 18 | } 19 | 20 | public static void main(String args[]) { 21 | int arr[] = { 5, 4, 3, 2, 1 }; 22 | int n = arr.length; 23 | System.out.println("Before sorting: "); 24 | printarr(arr, n); 25 | bubbleSort(arr, n); 26 | System.out.println("After sorting: "); 27 | printarr(arr, n); 28 | } 29 | } -------------------------------------------------------------------------------- /Algos/Java/ContainsDuplicate_217.java: -------------------------------------------------------------------------------- 1 | package LeetcodeFirstMonth; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | public class ContainsDuplicate_217 { 7 | public static boolean containsDuplicate(int[] nums) { 8 | Set set = new HashSet(); 9 | for(int num: nums){ 10 | if(set.contains(num)){ 11 | return true; 12 | } 13 | set.add(num); 14 | } 15 | return false; 16 | } 17 | public static void main(String[] args) { 18 | int[] nums = {1,23,5,3}; 19 | System.out.println(containsDuplicate(nums)); 20 | } 21 | } -------------------------------------------------------------------------------- /Algos/Java/CountSort.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | 4 | class CountSort { 5 | public static String countSort(String arr, int n) { 6 | PriorityQueue pq = new PriorityQueue<>(); 7 | for (int i = 0; i < n; i++) { 8 | pq.add(arr.charAt(i)); 9 | } 10 | StringBuilder sb = new StringBuilder(n); 11 | while (!pq.isEmpty()) { 12 | sb.append(pq.poll()); 13 | } 14 | return sb.toString(); 15 | } 16 | 17 | public static void main(String[] args) { 18 | Scanner sc = new Scanner(System.in); 19 | int n = sc.nextInt(); 20 | String arr = ""; 21 | arr = sc.next(); 22 | System.out.println(countSort(arr, n)); 23 | } 24 | } -------------------------------------------------------------------------------- /Algos/Java/Cyclic_Sort.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Cyclic_Sort { 4 | 5 | public static void main(String[] args) 6 | { 7 | int[] arr1 = {5, 3, 4, 1, 2}; 8 | int[] arr2 = {1 ,3 ,5 ,2 ,4}; 9 | cyclicSortingAscending(arr1); 10 | cyclicSortingDecending(arr2); 11 | System.out.println("In Ascending Order: " + Arrays.toString(arr1)); 12 | System.out.println("In Descending Order: " + Arrays.toString(arr2)); 13 | } 14 | 15 | //sort an array in ascending order 16 | public static void cyclicSortingAscending(int[] arr) 17 | { 18 | int i = 0; 19 | while (i < arr.length) { 20 | int correct = arr[i] - 1; 21 | if (arr[i] != arr[correct]) { 22 | swap(arr, i , correct); 23 | } 24 | else 25 | i++; 26 | } 27 | } 28 | 29 | //sort an array in decending order 30 | public static void cyclicSortingDecending(int[] arr) 31 | { 32 | int i = 0; 33 | while (i < arr.length) { 34 | int correct = i + arr[i]; 35 | if (correct != arr.length) { 36 | swap(arr,i,correct); 37 | } 38 | else 39 | i++; 40 | } 41 | } 42 | 43 | public static void swap(int[] arr, int first, int second) 44 | { 45 | int temp = arr[first]; 46 | arr[first] = arr[second]; 47 | arr[second] = temp; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Algos/Java/Euclidean_Algorithm.java: -------------------------------------------------------------------------------- 1 | package com.company; 2 | 3 | import java.lang.*; 4 | import java.util.*; 5 | 6 | // gcd means greatest common divisor 7 | class Main { 8 | 9 | public static int gcd(int a, int b) 10 | { 11 | if (a == 0) 12 | return b; 13 | 14 | return gcd(b % a, a); 15 | } 16 | 17 | 18 | public static void main(String[] args) 19 | { 20 | int a = 8, b = 16 , g; 21 | 22 | 23 | g = gcd(a, b); 24 | System.out.println("GCD(" + a + " , " + b 25 | + ") = " + g); 26 | 27 | a = 30; 28 | b = 12; 29 | g = gcd(a, b); 30 | System.out.println("GCD(" + a + " , " + b 31 | + ") = " + g); 32 | 33 | a = 26; 34 | b = 15; 35 | g = gcd(a, b); 36 | System.out.println("GCD(" + a + " , " + b 37 | + ") = " + g); 38 | } 39 | } 40 | 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /Algos/Java/FirstRepeatedCharacter.java: -------------------------------------------------------------------------------- 1 | /*Given a String, find the first repeated character in it using Stream functions? 2 | 3 | Input : 4 | String input = "Java Articles are Awesome"; 5 | Output = a*/ 6 | 7 | 8 | 9 | import java.util.LinkedHashMap; 10 | import java.util.Map; 11 | import java.util.Optional; 12 | import java.util.function.Function; 13 | import java.util.stream.Collectors; 14 | 15 | public class FirstRepeatedCharacter { 16 | 17 | public static void main(String[] args) { 18 | // TODO Auto-generated method stub 19 | String input = "Java Articles are Awesome"; 20 | //String input = "abc"; 21 | 22 | Optional firstRepeatingChar = input.chars() // IntStream of characters 23 | .mapToObj(c -> (char) c) // Convert each int to Character 24 | .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting())) // Group by character and count occurrences, preserving order 25 | .entrySet() 26 | .stream() 27 | .filter(e -> e.getValue() > 1) // Filter out non-repeating characters 28 | .map(Map.Entry::getKey) // Get the character (key) 29 | .findFirst(); // Get the first repeating character 30 | 31 | firstRepeatingChar.ifPresentOrElse( 32 | ch -> System.out.println("First repeating character: " + ch), 33 | () -> System.out.println("No repeating characters found.") 34 | ); 35 | 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /Algos/Java/GCD.java: -------------------------------------------------------------------------------- 1 | class Main { 2 | public static void main(String[] args) { 3 | 4 | // find GCD between n1 and n2 5 | int n1 = 81, n2 = 153; 6 | 7 | // initially set to gcd 8 | int gcd = 1; 9 | 10 | for (int i = 1; i <= n1 && i <= n2; ++i) { 11 | 12 | // check if i perfectly divides both n1 and n2 13 | if (n1 % i == 0 && n2 % i == 0) 14 | gcd = i; 15 | } 16 | 17 | System.out.println("GCD of " + n1 +" and " + n2 + " is " + gcd); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Algos/Java/GCD_LCM.java: -------------------------------------------------------------------------------- 1 | package com.company; 2 | 3 | public class GCD_LCM { 4 | public static void main(String[] args) { 5 | // System.out.println(gcd(4, 9)); 6 | System.out.println(LCM(9, 18)); 7 | } 8 | static int gcd(int a, int b){ 9 | if(a == 0){ 10 | return b; 11 | } 12 | return gcd(b % a, a); 13 | } 14 | static int LCM(int a, int b){ 15 | return a * b / gcd(a, b); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Algos/Java/HammingDistance.java: -------------------------------------------------------------------------------- 1 | // Hamming distance is a metric for comparing two binary data strings 2 | class Solution { 3 | public int hammingDistance(int x, int y) { 4 | int ans = x ^ y; 5 | int SetBits = 0; 6 | while(ans > 0){ 7 | SetBits += ans & 1; 8 | ans >>= 1; 9 | } 10 | return SetBits; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Algos/Java/HappyNumber.java: -------------------------------------------------------------------------------- 1 | // a happy number is a number which eventually reaches 1 when replaced by the sum of the square of each digit 2 | class Solution { 3 | public boolean isHappy(int n) { 4 | Set seen = new HashSet<>(); 5 | // if n is not 1 or hashset does not contain n, then add n 6 | // and perform the function 7 | while(n != 1 && !seen.contains(n)){ 8 | seen.add(n); 9 | n = getNext(n); 10 | } 11 | return n == 1; 12 | } 13 | // n = 19 14 | private int getNext(int n){ 15 | int sum = 0; 16 | while(n > 0){ 17 | // 19 % 10 = 9 18 | int d = n % 10; 19 | // 19 / 10 = 1 20 | n = n / 10; 21 | sum += d * d; 22 | } 23 | return sum; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Algos/Java/Heap_Sort.java: -------------------------------------------------------------------------------- 1 | class HeapSort 2 | { 3 | /* function to heapify a subtree. Here 'i' is the 4 | index of root node in array a[], and 'n' is the size of heap. */ 5 | static void heapify(int a[], int n, int i) 6 | { 7 | int largest = i; // Initialize largest as root 8 | int left = 2 * i + 1; // left child 9 | int right = 2 * i + 2; // right child 10 | // If left child is larger than root 11 | if (left < n && a[left] > a[largest]) 12 | largest = left; 13 | // If right child is larger than root 14 | if (right < n && a[right] > a[largest]) 15 | largest = right; 16 | // If root is not largest 17 | if (largest != i) { 18 | // swap a[i] with a[largest] 19 | int temp = a[i]; 20 | a[i] = a[largest]; 21 | a[largest] = temp; 22 | 23 | heapify(a, n, largest); 24 | } 25 | } 26 | /*Function to implement the heap sort*/ 27 | static void heapSort(int a[], int n) 28 | { 29 | for (int i = n / 2 - 1; i >= 0; i--) 30 | heapify(a, n, i); 31 | 32 | // One by one extract an element from heap 33 | for (int i = n - 1; i >= 0; i--) { 34 | /* Move current root element to end*/ 35 | // swap a[0] with a[i] 36 | int temp = a[0]; 37 | a[0] = a[i]; 38 | a[i] = temp; 39 | 40 | heapify(a, i, 0); 41 | } 42 | } 43 | /* function to print the array elements */ 44 | static void printArr(int a[], int n) 45 | { 46 | for (int i = 0; i < n; ++i) 47 | System.out.print(a[i] + " "); 48 | } 49 | public static void main(String args[]) 50 | { 51 | int a[] = {45, 7, 20, 40, 25, 23, -2}; 52 | int n = a.length; 53 | System.out.print("Before sorting array elements are - \n"); 54 | printArr(a, n); 55 | heapSort(a, n); 56 | System.out.print("\nAfter sorting array elements are - \n"); 57 | printArr(a, n); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Algos/Java/Insertion Sort.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class InsertionSort { 4 | public static void insertionSort(int array[]) { 5 | int n = array.length; 6 | for (int j = 1; j < n; j++) { 7 | int key = array[j]; 8 | int i = j - 1; 9 | while ((i > -1) && (array[i] > key)) { 10 | array[i + 1] = array[i]; 11 | i--; 12 | } 13 | array[i + 1] = key; 14 | } 15 | } 16 | 17 | public static void main(String a[]) { 18 | int n; 19 | System.out.print("Enter the number of elements in an array: "); 20 | 21 | Scanner sc = new Scanner(System.in); 22 | n = sc.nextInt(); 23 | 24 | int[] arr = new int[n]; 25 | System.out.print("Enter " + n + " elements of the array: "); 26 | for (int i = 0; i < n; i++) 27 | arr[i] = sc.nextInt(); 28 | 29 | System.out.println("Before Insertion Sort"); 30 | 31 | for (int i : arr) 32 | System.out.print(i + " "); 33 | 34 | System.out.println(); 35 | 36 | insertionSort(arr); 37 | 38 | System.out.println("After Insertion Sort"); 39 | for (int i : arr) { 40 | System.out.print(i + " "); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Algos/Java/InsertionSort.java: -------------------------------------------------------------------------------- 1 | public class InsertionSort { 2 | 3 | public static void main(String[] args) { 4 | int arr[]= {5,3,2,4,1}; 5 | System.out.println("Intially array is"); 6 | for(int i = 0;i < arr.length;i++) 7 | { 8 | System.out.print(" "+arr[i]); 9 | } 10 | System.out.println(); 11 | insertion_sort(arr); 12 | System.out.println("Finally array sorted is"); 13 | for(int i = 0;i < arr.length;i++) 14 | { 15 | System.out.print(" "+arr[i]); 16 | } 17 | System.out.println(); 18 | 19 | } 20 | public static void insertion_sort(int arr[]) 21 | { 22 | for(int i = 0;i < arr.length-1;i++) 23 | { 24 | for(int j = i+1;j > 0;j--) 25 | { 26 | if(arr[j] < arr[j-1]) 27 | { 28 | int temp = arr[j]; 29 | arr[j] = arr[j-1]; 30 | arr[j-1] = temp; 31 | } 32 | } 33 | } 34 | } 35 | } 36 | 37 | -------------------------------------------------------------------------------- /Algos/Java/LRU.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedList; 2 | /** 3 | * 4 | *Given function takes cache size, pages and pages size. Function returns number of cache mises. 5 | */ 6 | public class LRUCache { 7 | 8 | static public int lruFunction(int max_cache_size,int frames[],int frame_size){ 9 | LinkedList current_cache = new LinkedList<>(); 10 | int i,temp,index,count=0; 11 | if(frame_size>0){ 12 | for(i=0;i { 9 | //the value 10 | T val; 11 | ListNode next; 12 | 13 | ListNode(T val){ 14 | this.val =val; 15 | this.next = null; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Algos/Java/ManeuveringAlgorithm.java: -------------------------------------------------------------------------------- 1 | // A Java program to count all the possible paths from top left to bottom right.... 2 | // of a mXn matrix with the constraints.... 3 | // that from each cell you can either move only to right or down. 4 | 5 | 6 | public class ManeuveringAlgorithm { 7 | 8 | static int numberOfPaths(int m, int n) 9 | { 10 | if (m == 1 || n == 1) 11 | return 1; 12 | 13 | return numberOfPaths(m - 1, n) + numberOfPaths(m, n - 1); 14 | } 15 | 16 | public static void main(String args[]) 17 | { 18 | System.out.println(numberOfPaths(3, 3)); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Algos/Java/MatrixAddition.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | 4 | class MatrixAddition { 5 | public static void main(String[] args) { 6 | Scanner sc = new Scanner(System.in); 7 | System.out.print("Matrix1\nEnter the number of rows: "); 8 | int m = sc.nextInt(); 9 | System.out.print("Enter the number of collumn: "); 10 | int n = sc.nextInt(); 11 | 12 | System.out.print("Matrix2\nEnter the number of rows: "); 13 | int x = sc.nextInt(); 14 | System.out.print("Enter the number of rows: "); 15 | int y = sc.nextInt(); 16 | 17 | if (m != x || n != y) { 18 | System.out.println("Addition not possible"); 19 | return; 20 | } 21 | 22 | int[][] a = new int[m][n]; 23 | int[][] b = new int[x][y]; 24 | 25 | System.out.println("Enter the matrix-1"); 26 | for (int i = 0; i < m; i++) 27 | for (int j = 0; j < n; j++) { 28 | a[i][j] = sc.nextInt(); 29 | } 30 | 31 | System.out.println("Enter the matrix-2"); 32 | for (int i = 0; i < x; i++) 33 | for (int j = 0; j < y; j++) { 34 | b[i][j] = sc.nextInt(); 35 | } 36 | for (int i = 0; i < m; i++) { 37 | for (int j = 0; j < n; j++) { 38 | System.out.print(a[i][j] + b[i][j] + " "); 39 | } 40 | System.out.println(" "); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Algos/Java/MinimumJumps.java: -------------------------------------------------------------------------------- 1 | /* Given an array arr[] of non-negative integers. Each array element represents the maximum length of the jumps that can be made forward from that element. This means if arr[i] = x, then we can jump any distance y such that y ≤ x. 2 | Find the minimum number of jumps to reach the end of the array starting from the first element. If an element is 0, then you cannot move through that element. 3 | Note: Return -1 if you can't reach the end of the array. 4 | Example : 5 | Input: arr[] = {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9} 6 | Output: 3 7 | Explanation:First jump from 1st element to 2nd element with value 3. From here we jump to 5th element with value 9, and from here we will jump to the last. */ 8 | 9 | 10 | 11 | 12 | public class MinimumJumps { 13 | 14 | public static void main(String[] args) { 15 | // TODO Auto-generated method stub 16 | //int arr[] = {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9}; 17 | //int arr[] = {1, 4, 3, 2, 6, 7}; 18 | int arr[] = {0, 10, 20}; 19 | System.out.println(minJumps(arr)); 20 | 21 | } 22 | public static int minJumps(int arr[]) { 23 | int n = arr.length; 24 | int maxReach = arr[0]; 25 | int step = arr[0]; 26 | int jump = 1; 27 | if(n == 1) return 0; 28 | else if(arr[0] == 0) return -1; 29 | else{ 30 | for(int i = 1; i= maxReach) return -1; 39 | step = maxReach - i; 40 | } 41 | } 42 | } 43 | return jump; 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /Algos/Java/MoveZeroesToLeft.java: -------------------------------------------------------------------------------- 1 | public class MoveZeroesToLeft { 2 | public static void moveToLeft(int arr[], int n) { 3 | int i = n - 1; 4 | for (int j = n - 1; j >= 0; j--) { 5 | if (arr[j] != 0) { 6 | int temp = arr[j]; 7 | arr[j] = arr[i]; 8 | arr[i] = temp; 9 | i--; 10 | } 11 | } 12 | } 13 | 14 | public static void printArray(int arr[], int n) { 15 | for (int i = 0; i < n; i++) { 16 | System.out.print(arr[i] + " "); 17 | } 18 | System.out.println(); 19 | } 20 | 21 | public static void main(String[] args) { 22 | int num[] = { 1, 0, 2, 3, 0, 0, 0, 4, 5, 6, 0 }; 23 | printArray(num, num.length); 24 | moveToLeft(num, num.length); 25 | printArray(num, num.length); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Algos/Java/NQueens.java: -------------------------------------------------------------------------------- 1 | package com.company.backtracking; 2 | 3 | public class NQueens { 4 | public static void main(String[] args) { 5 | int n = 4; 6 | boolean[][] board = new boolean[n][n]; 7 | System.out.println(queens(board, 0)); 8 | 9 | } 10 | 11 | // since it is always starting row: 0, so it does not make sense to use column here 12 | static int queens(boolean[][] board, int row) { 13 | if (row == board.length) { 14 | display(board); 15 | System.out.println(); 16 | return 1; 17 | } 18 | 19 | int count = 0; 20 | 21 | // placing the queen and checking for every row and col 22 | for (int col = 0; col < board.length; col++) { 23 | // place the queen if it is safe 24 | if(isSafe(board, row, col)) { 25 | board[row][col] = true; 26 | count += queens(board, row + 1); 27 | board[row][col] = false; 28 | } 29 | } 30 | return count; 31 | } 32 | 33 | private static boolean isSafe(boolean[][] board, int row, int col) { 34 | // check the vertical row 35 | for (int i = 0; i < row; i++) { 36 | if(board[i][col]) { 37 | return false; 38 | } 39 | } 40 | 41 | // diagonal left 42 | int maxLeft = Math.min(row, col); 43 | for (int i = 1; i <= maxLeft ; i++) { 44 | if(board[row-i][col-i]) { 45 | return false; 46 | } 47 | } 48 | 49 | // diagonal right 50 | int maxRight = Math.min(row, board.length - col - 1); 51 | for (int i = 1; i <= maxRight ; i++) { 52 | if(board[row-i][col+i]) { 53 | return false; 54 | } 55 | } 56 | return true; 57 | } 58 | 59 | private static void display(boolean[][] board) { 60 | for (boolean[] row : board) { 61 | for (boolean element : row) { 62 | if (element) { 63 | System.out.print("Q "); 64 | } else { 65 | System.out.print("X "); 66 | } 67 | } 68 | System.out.println(); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /Algos/Java/NotASubsetSum.java: -------------------------------------------------------------------------------- 1 | /*Given a sorted array arr[] of positive integers, find the smallest positive integer such that it cannot be represented as the sum of elements of any subset of the given array set. 2 | 3 | Input: arr[] = [1, 2, 3] 4 | Output: 7 5 | 6 | Input: arr[] = [3, 6, 9, 10, 20, 28] 7 | Output: 1 */ 8 | 9 | 10 | public class NotASubsetSum { 11 | 12 | public static void main(String[] args) { 13 | // TODO Auto-generated method stub 14 | //int arr[] = {1, 2, 3}; 15 | int arr[] = {3, 6, 9, 10, 20, 28}; 16 | int ans = findSmallest(arr); 17 | System.out.println(ans); 18 | } 19 | public static int findSmallest(int[] arr) { 20 | int ans = 1; 21 | int n = arr.length; 22 | for(int i = 0; i ans) return ans; 24 | else ans+=arr[i]; 25 | } 26 | return ans; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /Algos/Java/Order_Agnostic_Binary_Search.java: -------------------------------------------------------------------------------- 1 | public class OrderAgnosticBS { 2 | public static void main(String[] args) { 3 | int[] arr = {89, 45, 22, 18, 16, 15, 4, 3, 2, 0, -4, -12, -18}; 4 | int target = 22; 5 | int ans = OrderAgnosticBinarySearch(arr, target); 6 | System.out.println(ans); 7 | } 8 | 9 | static int OrderAgnosticBinarySearch(int[] arr, int target){ 10 | int start = 0; 11 | int end = arr.length - 1; 12 | 13 | // find array is sorted in ascending or descending 14 | boolean isAsc = arr[start] < arr[end]; 15 | 16 | while (start < end){ 17 | // find the middle element 18 | // int mid = (start + end)/2; might be the case that it may exceed the range of integer 19 | int mid = start + (end - start)/2; 20 | 21 | if (target == arr[mid]){ 22 | return mid; 23 | } 24 | if (isAsc){ 25 | if (target < arr[mid]){ 26 | end = mid - 1; 27 | }else { 28 | start = mid + 1; 29 | } 30 | }else { 31 | if (target > arr[mid]){ 32 | end = mid - 1; 33 | }else { 34 | start = mid + 1; 35 | } 36 | } 37 | } 38 | return -1; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Algos/Java/PalindromeLinkedList.java: -------------------------------------------------------------------------------- 1 | 2 | /*Given a singly linked list of integers. The task is to check if the given linked list is palindrome or not. 3 | 4 | Input: LinkedList: 1->2->1->1->2->1 5 | Output: true 6 | 7 | Input: LinkedList: 1->2->3->4 8 | Output: false */ 9 | 10 | import java.io.BufferedReader; 11 | import java.io.IOException; 12 | import java.io.InputStreamReader; 13 | //structure of the node 14 | class Node{ 15 | int data; 16 | Node next; 17 | Node(int data){ 18 | this.data = data; 19 | this.next = null; 20 | } 21 | } 22 | //creating the linked list 23 | public class PalindromeLinkedList { 24 | static Node insert(Node head, int data) { 25 | Node temp = new Node(data); 26 | if(head == null) { 27 | head = temp; 28 | return head; 29 | } 30 | else { 31 | Node t = head; 32 | while(t.next != null) { 33 | t = t.next; 34 | } 35 | t.next = temp; 36 | } 37 | return head; 38 | } 39 | //main function 40 | public static void main(String[] args) throws NumberFormatException, IOException { 41 | // TODO Auto-generated method stub 42 | BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); 43 | int t = Integer.parseInt(read.readLine()); // t -> number of test cases 44 | while(t-- > 0) { 45 | Node head = null; 46 | String str[] = read.readLine().trim().split(" "); 47 | int listSize = str.length; 48 | for(int i = 0; i< listSize; i++) { 49 | head = insert(head, Integer.parseInt(str[i])); 50 | } 51 | boolean f = isPalindrome(head); 52 | System.out.println(f ? "true" : "false"); 53 | } 54 | } 55 | //function to check the linked list is palindrome or not 56 | public static boolean isPalindrome(Node head) { 57 | Node slow = head, fast = head; 58 | while(fast != null && fast.next != null) { 59 | slow = slow.next; 60 | fast = fast.next.next; 61 | } 62 | Node prev = null, curr = slow; 63 | while(curr != null) { 64 | Node nextNode = curr.next; 65 | curr.next = prev; 66 | prev = curr; 67 | curr = nextNode; 68 | } 69 | Node first = head, second = prev; 70 | while(second != null) { 71 | if(first.data != second.data) return false; 72 | first = first.next; 73 | second = second.next; 74 | } 75 | return true; 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /Algos/Java/Quick Sort.java: -------------------------------------------------------------------------------- 1 | public class Quick 2 | { 3 | /* function that consider last element as pivot, 4 | place the pivot at its exact position, and place 5 | smaller elements to left of pivot and greater 6 | elements to right of pivot. */ 7 | int partition (int a[], int start, int end) 8 | { 9 | int pivot = a[end]; // pivot element 10 | int i = (start - 1); 11 | 12 | for (int j = start; j <= end - 1; j++) 13 | { 14 | // If current element is smaller than the pivot 15 | if (a[j] < pivot) 16 | { 17 | i++; // increment index of smaller element 18 | int t = a[i]; 19 | a[i] = a[j]; 20 | a[j] = t; 21 | } 22 | } 23 | int t = a[i+1]; 24 | a[i+1] = a[end]; 25 | a[end] = t; 26 | return (i + 1); 27 | } 28 | 29 | /* function to implement quick sort */ 30 | void quick(int a[], int start, int end) /* a[] = array to be sorted, start = Starting index, end = Ending index */ 31 | { 32 | if (start < end) 33 | { 34 | int p = partition(a, start, end); //p is partitioning index 35 | quick(a, start, p - 1); 36 | quick(a, p + 1, end); 37 | } 38 | } 39 | 40 | /* function to print an array */ 41 | void printArr(int a[], int n) 42 | { 43 | int i; 44 | for (i = 0; i < n; i++) 45 | System.out.print(a[i] + " "); 46 | } 47 | public static void main(String[] args) { 48 | int a[] = { 13, 18, 27, 2, 19, 25 }; 49 | int n = a.length; 50 | System.out.println("\nBefore sorting array elements are - "); 51 | Quick q1 = new Quick(); 52 | q1.printArr(a, n); 53 | q1.quick(a, 0, n - 1); 54 | System.out.println("\nAfter sorting array elements are - "); 55 | q1.printArr(a, n); 56 | System.out.println(); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Algos/Java/QuickSortAlgorithmJava.java: -------------------------------------------------------------------------------- 1 | public class QuickSortAlgorithmJava 2 | { 3 | int partition (int a[], int start, int end) 4 | { 5 | int pivot = a[end]; // pivot element 6 | int i = (start - 1); 7 | 8 | for (int j = start; j <= end - 1; j++) 9 | { 10 | // If current element is smaller than the pivot 11 | if (a[j] < pivot) 12 | { 13 | i++; // increment index of smaller element 14 | int t = a[i]; 15 | a[i] = a[j]; 16 | a[j] = t; 17 | } 18 | } 19 | int t = a[i+1]; 20 | a[i+1] = a[end]; 21 | a[end] = t; 22 | return (i + 1); 23 | } 24 | 25 | /* function to implement quick sort */ 26 | void quick(int a[], int start, int end) /* a[] = array to be sorted, start = Starting index, end = Ending index */ 27 | { 28 | if (start < end) 29 | { 30 | int p = partition(a, start, end); //p is partitioning index 31 | quick(a, start, p - 1); 32 | quick(a, p + 1, end); 33 | } 34 | } 35 | 36 | /* function to print an array */ 37 | void printArr(int a[], int n) 38 | { 39 | int i; 40 | for (i = 0; i < n; i++) 41 | System.out.print(a[i] + " "); 42 | } 43 | public static void main(String[] args) { 44 | int a[] = { 13, 18, 27, 2, 19, 25 }; 45 | int n = a.length; 46 | System.out.println("\nBefore sorting array elements are - "); 47 | QuickSortAlgorithmJava q1 = new QuickSortAlgorithmJava(); 48 | q1.printArr(a, n); 49 | q1.quick(a, 0, n - 1); 50 | System.out.println("\nAfter sorting array elements are - "); 51 | q1.printArr(a, n); 52 | System.out.println(); 53 | } 54 | } -------------------------------------------------------------------------------- /Algos/Java/RobinKarp.java: -------------------------------------------------------------------------------- 1 | /** 2 | Given a text txt[0. . .n-1] and a pattern pat[0. . .m-1], 3 | write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. 4 | You may assume that n > m. 5 | 6 | Input: txt[] = “THIS IS A TEST TEXT”, pat[] = “TEST” 7 | Output: Pattern found at index 10 8 | 9 | Input: txt[] = “AABAACAADAABAABA”, pat[] = “AABA” 10 | Output: Pattern found at index 0 11 | Pattern found at index 9 12 | Pattern found at index 12 13 | */ 14 | 15 | public class RabinKarp { 16 | 17 | public static final int d = 10; 18 | 19 | static void search(String pattern, String str, int q) { 20 | int m = pattern.length(); 21 | int n = str.length(); 22 | int i, j; 23 | int p = 0; 24 | int t = 0; 25 | int h = 1; 26 | 27 | for (i = 0; i < m - 1; i++) h = (h * d) % q; 28 | // Calculate hash value for pattern and text 29 | for (i = 0; i < m; i++) { 30 | p = (d * p + pattern.charAt(i)) % q; 31 | t = (d * t + str.charAt(i)) % q; 32 | } 33 | 34 | // Find the match 35 | for (i = 0; i <= n - m; i++) { 36 | if (p == t) { 37 | for (j = 0; j < m; j++) { 38 | if (str.charAt(i + j) != pattern.charAt(j)) break; 39 | } 40 | if (j == m) System.out.println( 41 | "Pattern is found at position: " + (i + 1) 42 | ); 43 | } 44 | 45 | if (i < n - m) { 46 | t = (d * (t - str.charAt(i) * h) + str.charAt(i + m)) % q; 47 | if (t < 0) t = (t + q); 48 | } 49 | } 50 | } 51 | 52 | public static void main(String[] args) { 53 | String str = "ABCCDDAEFG"; 54 | String pattern = "CDD"; 55 | int q = 13; 56 | search(pattern, str, q); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Algos/Java/RotateArray.java: -------------------------------------------------------------------------------- 1 | public class RotateArray { 2 | public static void rotateArray(int nums[], int k) { 3 | int temp[] = new int[nums.length]; 4 | for (int i = 0; i < nums.length; i++) { 5 | temp[(i + k) % nums.length] = nums[i]; 6 | // temp[i] = nums[i]; 7 | } 8 | for (int i = 0; i < nums.length; i++) { 9 | nums[i] = temp[i]; 10 | } 11 | } 12 | 13 | public static void printArray(int arr[], int n) { 14 | for (int i = 0; i < n; i++) { 15 | System.out.print(arr[i] + " "); 16 | } 17 | System.out.println(); 18 | } 19 | 20 | public static void main(String[] args) { 21 | int arr[] = { 1, 2, 3, 4, 5 }; 22 | int k = 2; 23 | rotateArray(arr, k); 24 | printArray(arr, arr.length); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Algos/Java/RotatedSortedArray.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class JavaQuizes { 3 | public static void main(String[] args) { 4 | int[] arr={3,1,2,3,3,3,3}; 5 | int l=0; 6 | int h=arr.length-1; 7 | int t=10; 8 | int flag=0; 9 | while(l<=h){ 10 | int m=(l+h)/2; 11 | if(arr[m]==t){ 12 | System.out.println("TRUE"); 13 | flag=1; 14 | break; 15 | } 16 | if(arr[l]==arr[m] && arr[m]==arr[h]){ 17 | l=l+1; 18 | h=h-1; 19 | continue; 20 | } 21 | if(arr[m]>=arr[l]){ 22 | if(arr[l]<=t && t<=arr[m]){ 23 | h=m-1; 24 | }else{ 25 | l=m+1; 26 | } 27 | } 28 | else{ 29 | if(arr[m]<=t && t<=arr[h]){ 30 | l=m+1; 31 | }else{ 32 | h=m-1; 33 | } 34 | } 35 | } 36 | if(flag==0){ 37 | System.out.println("FALSE"); 38 | } 39 | } 40 | } 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Algos/Java/SelectioSort.java: -------------------------------------------------------------------------------- 1 | // SELECTION SORT -: 2 | 3 | /* Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-based 4 | algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted 5 | part at the right end*/ 6 | 7 | import java.util.Arrays; 8 | 9 | public class SelectionSort { 10 | public static void main(String[] args) { 11 | int[] arr = {5, 3, 4, 1, 2}; 12 | selection(arr); 13 | System.out.println(Arrays.toString(arr)); 14 | } 15 | 16 | static void selection(int[] arr) { 17 | for (int i = 0; i < arr.length; i++) { 18 | // find the max item in the remaining array and swap with correct index 19 | int last = arr.length - i - 1; 20 | int maxIndex = getMaxIndex(arr, 0, last); 21 | swap(arr, maxIndex, last); 22 | } 23 | } 24 | 25 | static void swap(int[] arr, int first, int second) { 26 | int temp = arr[first]; 27 | arr[first] = arr[second]; 28 | arr[second] = temp; 29 | } 30 | 31 | static int getMaxIndex(int[] arr, int start, int end) { 32 | int max = start; 33 | for (int i = start; i <= end; i++) { 34 | if (arr[max] < arr[i]) { 35 | max = i; 36 | } 37 | } 38 | return max; 39 | } 40 | 41 | } 42 | 43 | // Output - [1, 2, 3, 4, 5] -------------------------------------------------------------------------------- /Algos/Java/SieveOfEratosthenes.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Scanner; 3 | 4 | public class SieveOfEratosthenes { 5 | public static void main(String[] args) { 6 | Scanner sc=new Scanner(System.in); 7 | int n; // It is the limit 8 | System.out.println("Enter the number upto which the number of prime numbers must be printed here"); 9 | n=sc.nextInt(); 10 | sc.close(); 11 | boolean[] primes = sieveOfEratosthenes(n); 12 | 13 | // It prints all prime numbers up to n 14 | System.out.println("Prime numbers up to " + n + ":"); 15 | for (int i = 2; i <= n; i++) { 16 | if (primes[i]) { 17 | System.out.print(i + " "); 18 | } 19 | } 20 | } 21 | 22 | public static boolean[] sieveOfEratosthenes(int n) { 23 | /* 24 | Creating a boolean array "isPrime[]" and initializing all entries it as true. A value in isPrime[i] will finally be false if i is not a prime number, else true. 25 | */ 26 | boolean[] isPrime = new boolean[n + 1]; 27 | Arrays.fill(isPrime, true); // Here we assume all numbers are prime initially 28 | isPrime[0] = false; // 0 is not a prime number 29 | isPrime[1] = false; // 1 is not a prime number 30 | 31 | // We will start marking multiples of each number 32 | for (int i = 2; i * i <= n; i++) { 33 | // If isPrime[i] is not changed, then it is a prime number 34 | if (isPrime[i]) { 35 | // We are updating all multiples of i as non-prime numbers 36 | for (int j = i * i; j <= n; j += i) { 37 | isPrime[j] = false; 38 | } 39 | } 40 | } 41 | 42 | return isPrime; 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /Algos/Java/Spring/application.properties: -------------------------------------------------------------------------------- 1 | ## Database Properties 2 | spring.datasource.url = jdbc:mysql://localhost:3306/users_database?useSSL=false 3 | spring.datasource.username = root 4 | spring.datasource.password = root 5 | 6 | 7 | ## Hibernate Properties 8 | # The SQL dialect makes Hibernate generate better SQL for the chosen database 9 | spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect 10 | 11 | # Hibernate ddl auto (create, create-drop, validate, update) 12 | spring.jpa.hibernate.ddl-auto = update -------------------------------------------------------------------------------- /Algos/Java/Spring/repo/UserRepository.java: -------------------------------------------------------------------------------- 1 | @Repository 2 | public interface UserRepository extends JpaRepository {} -------------------------------------------------------------------------------- /Algos/Java/Stepping_stairs.java: -------------------------------------------------------------------------------- 1 | class Stepping_stairs { 2 | 3 | static int fib(int n) 4 | { 5 | if (n <= 1) 6 | return n; 7 | return fib(n - 1) + fib(n - 2); 8 | } 9 | 10 | 11 | static int countWays(int s) 12 | { 13 | return fib(s + 1); 14 | } 15 | 16 | public static void main(String args[]) 17 | { 18 | int s = 4; 19 | System.out.println("Number of ways = " + countWays(s)); 20 | } 21 | } -------------------------------------------------------------------------------- /Algos/Java/SubArrayWithGivenSum.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class SubArrayWithGivenSum { 4 | static ArrayList subarraySum(int[] arr, int n, int s) { 5 | // Your code here 6 | ArrayList a = new ArrayList<>(); 7 | int sum = 0; 8 | int j = 0, k = 0; 9 | 10 | while (j < n && k < n) { 11 | sum += arr[j]; 12 | if (sum == s) { 13 | a.add(k + 1); 14 | a.add(j + 1); 15 | return a; 16 | } else if (sum < s) { 17 | j++; 18 | } else if (sum > s) { 19 | k++; 20 | j = k; 21 | sum = 0; 22 | } 23 | 24 | } 25 | a.add(-1); 26 | return a; 27 | } 28 | 29 | public static void main(String[] args) { 30 | int arr[] = { 1, 2, 3, 7, 5 }; 31 | int n = arr.length; 32 | int sum = 12; 33 | ArrayList res = new ArrayList<>(); 34 | res = subarraySum(arr, n, sum); 35 | System.out.println(res); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Algos/Java/TrappedRain.java: -------------------------------------------------------------------------------- 1 | package Practice.DSA; 2 | 3 | public class TrappedRain { 4 | public static int tappedrain(int height[]) { 5 | int n = height.length; 6 | 7 | //calculate leftMax boundary -array 8 | int leftmax[] = new int[n]; 9 | leftmax[0] = height[0]; 10 | for(int i=1; i=0 ;i--) { 18 | rightmax[i] = Math.max(height[i], rightmax[i+1]); 19 | } 20 | int trappedwater = 0; 21 | for(int i=0; ikey){ 20 | end=mid-1; 21 | } 22 | if (arr[mid][] bucket = new ArrayList[n]; 11 | 12 | // Create empty buckets 13 | for (int i = 0; i < n; i++) 14 | bucket[i] = new ArrayList(); 15 | 16 | // Add elements into the buckets 17 | for (int i = 0; i < n; i++) { 18 | int bucketIndex = (int) arr[i] * n; 19 | bucket[bucketIndex].add(arr[i]); 20 | } 21 | 22 | // Sort the elements of each bucket 23 | for (int i = 0; i < n; i++) { 24 | Collections.sort((bucket[i])); 25 | } 26 | 27 | // Get the sorted array 28 | int index = 0; 29 | for (int i = 0; i < n; i++) { 30 | for (int j = 0, size = bucket[i].size(); j < size; j++) { 31 | arr[index++] = bucket[i].get(j); 32 | } 33 | } 34 | } 35 | 36 | public static void main(String[] args) { 37 | BucketSort b = new BucketSort(); 38 | float[] arr = { (float) 0.42, (float) 0.32, (float) 0.33, (float) 0.52, (float) 0.37, (float) 0.47, 39 | (float) 0.51 }; 40 | b.bucketSort(arr, 7); 41 | 42 | for (float i : arr) 43 | System.out.print(i + " "); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Algos/Java/coinchange.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | class coinchange { 4 | 5 | 6 | static int count(int coins[], int n, int sum) 7 | { 8 | 9 | 10 | if (sum == 0) 11 | return 1; 12 | 13 | 14 | if (sum < 0) 15 | return 0; 16 | 17 | 18 | if (n <= 0) 19 | return 0; 20 | 21 | return count(coins, n - 1, sum) 22 | + count(coins, n, sum - coins[n - 1]); 23 | } 24 | 25 | public static void main(String args[]) 26 | { 27 | int coins[] = { 1, 2, 3 }; 28 | int n = coins.length; 29 | 30 | System.out.println(count(coins, n, 4)); 31 | } 32 | } 33 | 34 | 35 | -------------------------------------------------------------------------------- /Algos/Java/designpatterns/singleton/EagerInitializedSingleton.java: -------------------------------------------------------------------------------- 1 | public class EagerInitializedSingleton { 2 | 3 | private static final EagerInitializedSingleton instance = new EagerInitializedSingleton(); 4 | 5 | //private constructor to avoid client applications to use constructor 6 | private EagerInitializedSingleton(){} 7 | 8 | public static EagerInitializedSingleton getInstance(){ 9 | return instance; 10 | } 11 | 12 | public void test() { 13 | System.out.println("This is Singleton instance"); 14 | } 15 | 16 | public static void main(String[] args) { 17 | EagerInitializedSingleton.getInstance().test(); 18 | } 19 | } -------------------------------------------------------------------------------- /Algos/Java/designpatterns/singleton/LazyInitializedSingleton.java: -------------------------------------------------------------------------------- 1 | public class LazyInitializedSingleton { 2 | 3 | private static LazyInitializedSingleton instance; 4 | 5 | private LazyInitializedSingleton(){} 6 | 7 | public static LazyInitializedSingleton getInstance(){ 8 | if(instance == null){ 9 | instance = new LazyInitializedSingleton(); 10 | } 11 | return instance; 12 | } 13 | 14 | public void test() { 15 | System.out.println("This is LazyInitializedSingleton instance"); 16 | } 17 | 18 | public static void main(String[] args) { 19 | LazyInitializedSingleton.getInstance().test(); 20 | } 21 | } -------------------------------------------------------------------------------- /Algos/Java/designpatterns/singleton/StaticBlockSingleton.java: -------------------------------------------------------------------------------- 1 | public class StaticBlockSingleton { 2 | 3 | private static StaticBlockSingleton instance; 4 | 5 | private StaticBlockSingleton(){} 6 | 7 | //static block initialization for exception handling 8 | static{ 9 | try{ 10 | instance = new StaticBlockSingleton(); 11 | }catch(Exception e){ 12 | throw new RuntimeException("Exception occured in creating singleton instance"); 13 | } 14 | } 15 | 16 | public static StaticBlockSingleton getInstance(){ 17 | return instance; 18 | } 19 | 20 | public void test() { 21 | System.out.println("This is StaticBlockSingleton instance"); 22 | } 23 | 24 | public static void main(String[] args) { 25 | StaticBlockSingleton.getInstance().test(); 26 | } 27 | } -------------------------------------------------------------------------------- /Algos/Java/designpatterns/singleton/ThreadSafeSingleton.java: -------------------------------------------------------------------------------- 1 | public class ThreadSafeSingleton { 2 | 3 | private static ThreadSafeSingleton instance; 4 | 5 | private ThreadSafeSingleton(){} 6 | 7 | public static synchronized ThreadSafeSingleton getInstance(){ 8 | if(instance == null){ 9 | instance = new ThreadSafeSingleton(); 10 | } 11 | return instance; 12 | } 13 | 14 | public void test() { 15 | System.out.println("This is ThreadSafeSingleton instance"); 16 | } 17 | 18 | public static void main(String[] args) { 19 | ThreadSafeSingleton.getInstance().test(); 20 | } 21 | 22 | } -------------------------------------------------------------------------------- /Algos/Java/fibonacci series.java: -------------------------------------------------------------------------------- 1 | //Fibonacci Series using Optimized Method 2 | public class fibonacci 3 | { 4 | /* function that returns nth Fibonacci number */ 5 | static int fib(int n) 6 | { 7 | int F[][] = new int[][]{{1,1},{1,0}}; 8 | if (n == 0) 9 | return 0; 10 | power(F, n-1); 11 | 12 | return F[0][0]; 13 | } 14 | 15 | static void multiply(int F[][], int M[][]) 16 | { 17 | int x = F[0][0]*M[0][0] + F[0][1]*M[1][0]; 18 | int y = F[0][0]*M[0][1] + F[0][1]*M[1][1]; 19 | int z = F[1][0]*M[0][0] + F[1][1]*M[1][0]; 20 | int w = F[1][0]*M[0][1] + F[1][1]*M[1][1]; 21 | 22 | F[0][0] = x; 23 | F[0][1] = y; 24 | F[1][0] = z; 25 | F[1][1] = w; 26 | } 27 | 28 | /* Optimized version of power() in method 4 */ 29 | static void power(int F[][], int n) 30 | { 31 | if( n == 0 || n == 1) 32 | return; 33 | int M[][] = new int[][]{{1,1},{1,0}}; 34 | 35 | power(F, n/2); 36 | multiply(F, F); 37 | 38 | if (n%2 != 0) 39 | multiply(F, M); 40 | } 41 | 42 | /* Driver program to test above function */ 43 | public static void main (String args[]) 44 | { 45 | int n = 9; 46 | System.out.println(fib(n)); 47 | } 48 | }; 49 | /* This code is contributed by halmoside */ 50 | -------------------------------------------------------------------------------- /Algos/Java/find-first-and-last-position-of-element-in-sorted-array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] searchRange(int[] nums, int target) { 3 | int[] ans=new int[2]; 4 | ans[0]=search(nums,target,true); 5 | ans[1]=search(nums,target,false); 6 | return ans; 7 | } 8 | int search(int[] nums,int target,boolean findStartIndex) 9 | { 10 | int ans=-1; 11 | int start=0,end=nums.length-1; 12 | while(start<=end) 13 | { 14 | int mid=start+(end-start)/2; 15 | if(targetnums[mid]) 18 | start=mid+1; 19 | else{ 20 | ans=mid; 21 | if(findStartIndex) 22 | end=mid-1; 23 | else 24 | start=mid+1; 25 | } 26 | } 27 | return ans; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Algos/Java/half pyramid .java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | // Java code to demonstrate star patterns 4 | 5 | public class GeeksForGeeks 6 | { 7 | 8 | // Function to demonstrate printing pattern 9 | 10 | public static void printStars(int n) 11 | 12 | { 13 | 14 | int i, j; 15 | 16 | 17 | // outer loop to handle number of rows 18 | 19 | // n in this case 20 | 21 | for(i=0; i ll = new LinkedList<>(); 11 | for (int i=0; i=ei) 5 | return; 6 | int mid=(si+ei)/2; 7 | divide(arr,si,mid); 8 | divide(arr,mid+1,ei); 9 | conquer(arr,si,mid,ei); 10 | } 11 | public static void conquer(int arr[],int si,int mid,int ei) 12 | { 13 | int merged[] = new int[ei-si+1]; 14 | int idx1=si; 15 | int idx2=mid+1; 16 | int x=0; 17 | while(idx1<=mid && idx2<=ei) 18 | { 19 | if(arr[idx1]<=arr[idx2]) 20 | { 21 | merged[x++]=arr[idx1++]; 22 | } 23 | else 24 | { 25 | merged[x++]=arr[idx2++]; 26 | } 27 | } 28 | while(idx1<=mid) 29 | { 30 | merged[x++]=arr[idx1++]; 31 | } 32 | while(idx2<=ei) 33 | { 34 | merged[x++]=arr[idx2++]; 35 | } 36 | for(int i=0, j=si;i< merged.length;i++,j++) 37 | { 38 | arr[j]=merged[i]; 39 | } 40 | 41 | } 42 | 43 | public static void main(String[] args) { 44 | Scanner sc = new Scanner(System.in); 45 | int arr[] = {6,3,9,5,2,8}; 46 | int n=arr.length -1; 47 | 48 | divide(arr,0,n); 49 | 50 | for(int i=0;i=0;i--) 9 | { 10 | string=string+str.charAt(i); 11 | } 12 | int rev=Integer.parseInt(str); 13 | //returns the reverse number 14 | return rev; 15 | } 16 | static boolean isMysteryNo(int num) 17 | { 18 | for (int i=1; i <= num/2; i++) 19 | { 20 | int j = reverse(i); 21 | if (i + j == num) 22 | { 23 | System.out.println( i + " " + j); 24 | System.out.println(num+ " is a mystery number."); 25 | //returns a boolean value if pair is found 26 | return true; 27 | } 28 | } 29 | System.out.println("The given number is not a mystery number."); 30 | return false; 31 | } 32 | public static void main(String args[]) 33 | { 34 | Scanner sc=new Scanner(System.in); 35 | System.out.print("Enter a number: "); 36 | int num = sc.nextInt(); 37 | isMysteryNo(num); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Algos/Java/pattern.java: -------------------------------------------------------------------------------- 1 | public class Main{ 2 | public static void main(String []args){ 3 | int i,j,lines=5; 4 | for(i=1;i<=lines;i++){// this loop is used to print the lines 5 | for(j=lines;j>=1;j--){// this loop is used to print numbers in a line 6 | if(j!=i) 7 | System.out.print(j); 8 | else 9 | System.out.print("*"); 10 | } 11 | System.out.println(""); 12 | } 13 | }} 14 | -------------------------------------------------------------------------------- /Algos/Java/remove-nth-node-from-end-of-list.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 removeNthFromEnd(ListNode head, int n) { 13 | if(head.next==null) 14 | return null; 15 | ListNode p=head,q=head; 16 | int len=0; 17 | while(p!=null) 18 | { 19 | len=len+1; 20 | p=p.next; 21 | } 22 | int pos=len-n+1,i=1; 23 | if(pos==1) 24 | head=head.next; 25 | else{ 26 | while(i= 0; i--){ 10 | reversedStr = reversedStr + string.charAt(i); 11 | } 12 | 13 | System.out.println("Original string: " + string); 14 | //Displays the reverse of given string 15 | System.out.println("Reverse of given string: " + reversedStr); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Algos/Java/reversestring.java: -------------------------------------------------------------------------------- 1 | // java program to reverse a word 2 | 3 | import java.io.*; 4 | import java.util.Scanner; 5 | 6 | class GFG { 7 | public static void main (String[] args) { 8 | 9 | String str= "Geeks", nstr=""; 10 | char ch; 11 | 12 | System.out.print("Original word: "); 13 | System.out.println("Geeks"); 14 | 15 | for (int i=0; i= 0; i--) { 8 | if (s.charAt(i) == '6') { 9 | ns.append("9"); 10 | } else if (s.charAt(i) == '9') { 11 | ns.append("6"); 12 | } else { 13 | ns.append(s.charAt(i)); 14 | } 15 | } 16 | if (ns.toString().equals(s)) { 17 | System.out.println("It is a Strobogramattic Number"); 18 | } else { 19 | System.out.println("It is not a Strobogramattic Number"); 20 | } 21 | } 22 | 23 | public static void main(String[] args) { 24 | Scanner sc = new Scanner(System.in); 25 | long n = sc.nextLong(); 26 | SN(n); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Algos/Java/swap.java: -------------------------------------------------------------------------------- 1 | public class SwapNumbers { 2 | 3 | public static void main(String[] args) { 4 | 5 | float first = 1.20f, second = 2.45f; 6 | 7 | System.out.println("--Before swap--"); 8 | System.out.println("First number = " + first); 9 | System.out.println("Second number = " + second); 10 | 11 | // Value of first is assigned to temporary 12 | float temporary = first; 13 | 14 | // Value of second is assigned to first 15 | first = second; 16 | 17 | // Value of temporary (which contains the initial value of first) is assigned to second 18 | second = temporary; 19 | 20 | System.out.println("--After swap--"); 21 | System.out.println("First number = " + first); 22 | System.out.println("Second number = " + second); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Algos/Java/towerOfHanoi.java: -------------------------------------------------------------------------------- 1 | package com.kraken; 2 | import java.util.*; 3 | public class towerOfHanoi { 4 | public static void Hanoi(int n, String src, String help, String dest) 5 | { 6 | if(n==1) 7 | { 8 | System.out.println("Transfer disk from "+src+" to "+dest); 9 | return; 10 | } 11 | Hanoi(n-1,src,dest,help); 12 | System.out.println("Transfer disk from "+src+" to "+dest); 13 | Hanoi(n-1,help,src,dest); 14 | } 15 | 16 | public static void main(String [] args) 17 | { 18 | Scanner sc = new Scanner(System.in); 19 | int n = sc.nextInt(); 20 | Hanoi(n,"A","B","C"); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Algos/Java/trailingZeroesFromFactorial.java: -------------------------------------------------------------------------------- 1 | public class trailingZeroesFromFactorial { 2 | 3 | 4 | static int CountZero(int x){ 5 | int res=0; 6 | int i=5; 7 | while(i<=x){ 8 | res=res+(x/i); 9 | i=i*i; 10 | } 11 | 12 | return res; 13 | } 14 | 15 | public static void main(String[] args) { 16 | System.out.println(CountZero(251)); 17 | } 18 | 19 | 20 | 21 | 22 | 23 | } 24 | -------------------------------------------------------------------------------- /Algos/JavaScript/Arrya_Equaliser.js: -------------------------------------------------------------------------------- 1 | //https://www.hackerrank.com/challenges/equality-in-a-array/problem 2 | 'use strict'; 3 | 4 | const fs = require('fs'); 5 | 6 | process.stdin.resume(); 7 | process.stdin.setEncoding('utf-8'); 8 | 9 | let inputString = ''; 10 | let currentLine = 0; 11 | 12 | const readLine = () =>inputString[currentLine++]; 13 | 14 | process.stdin.on('data', inputStdin => { 15 | inputString += inputStdin; 16 | }); 17 | 18 | process.stdin.on('end', () => { 19 | inputString = inputString.replace(/\s*$/, '') 20 | .split('\n') 21 | .map(str => str.replace(/\s*$/, '')); 22 | 23 | main(); 24 | }); 25 | 26 | const equalizeArray = (arr) => { 27 | const occurences = {}; 28 | let max = 1; 29 | 30 | arr.forEach(value => { 31 | if (!occurences[value]) { 32 | occurences[value] = 1; 33 | } else { 34 | occurences[value]++; 35 | if (occurences[value] > max) { 36 | max = occurences[value]; 37 | } 38 | } 39 | }) 40 | 41 | return arr.length - max; 42 | } 43 | 44 | const main = () => { 45 | const ws = fs.createWriteStream(process.env.OUTPUT_PATH); 46 | 47 | const n = parseInt(readLine(), 10); 48 | const arr = readLine().split(' ').map(arrTemp => parseInt(arrTemp, 10)); 49 | 50 | ws.write(equalizeArray(arr) + "\n"); 51 | ws.end(); 52 | } 53 | -------------------------------------------------------------------------------- /Algos/JavaScript/Factors.js: -------------------------------------------------------------------------------- 1 | // program to find the factors of an integer 2 | 3 | // take input 4 | const num = prompt('Enter a positive number: '); 5 | 6 | console.log(`The factors of ${num} is:`); 7 | 8 | // looping through 1 to num 9 | for(let i = 1; i <= num; i++) { 10 | 11 | // check if number is a factor 12 | if(num % i == 0) { 13 | console.log(i); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Algos/JavaScript/bfs.js: -------------------------------------------------------------------------------- 1 | class Graph { 2 | constructor() { 3 | this.vertices = []; 4 | this.adjacent = {}; 5 | this.edges = 0; 6 | } 7 | 8 | addVertex(v) { 9 | this.vertices.push(v); 10 | this.adjacent[v] = []; 11 | } 12 | 13 | addEdge(v, w) { 14 | this.adjacent[v].push(w); 15 | this.adjacent[w].push(v); 16 | this.edges++; 17 | } 18 | bfs(goal, root = this.vertices[0]) { 19 | let adj = this.adjacent; 20 | 21 | const queue = []; 22 | queue.push(root); 23 | 24 | while (queue.length) { 25 | let v = queue.shift(); 26 | console.log(v); 27 | 28 | if (v === goal) { 29 | return true; 30 | } 31 | 32 | for (let i = 0; i < adj[v].length; i++) { 33 | queue.push(adj[v][i]); 34 | } 35 | } 36 | 37 | return false; 38 | } 39 | } 40 | 41 | const g = new Graph(); 42 | 43 | g.addVertex("A"); 44 | g.addVertex("B"); 45 | g.addVertex("C"); 46 | g.addVertex("D"); 47 | 48 | g.addEdge("A", "B"); 49 | g.addEdge("A", "C"); 50 | g.addEdge("A", "D"); 51 | g.addEdge("B", "C"); 52 | g.addEdge("B", "D"); 53 | g.addEdge("C", "D"); 54 | 55 | console.log(g.bfs("D")); 56 | -------------------------------------------------------------------------------- /Algos/JavaScript/bubble_sort.js: -------------------------------------------------------------------------------- 1 | // Bubble sort Implementation using Javascript 2 | 3 | //array to be sorted 4 | var arr = [25, 13, 55, 63, 2, 61, 35, 47]; 5 | 6 | function bubbleSort(arr) { 7 | for (var i = 0; i < arr.length; i++) { 8 | for (var j = 0; j < arr.length - i - 1; j++) { 9 | if (arr[j] > arr[j + 1]) { 10 | var temp = arr[j]; 11 | arr[j] = arr[j + 1]; 12 | arr[j + 1] = temp; 13 | } 14 | } 15 | } 16 | console.log(arr); 17 | } 18 | 19 | //One of the simple easy algorithm to implement 20 | //Bubble sort algorithm sorts the array 21 | //by comparing two adjacent elements and swaps them if they are not in the intended order 22 | bubbleSort(arr); 23 | -------------------------------------------------------------------------------- /Algos/JavaScript/bubblesort.js: -------------------------------------------------------------------------------- 1 | // Bubble sort Implementation using Javascript 2 | 3 | //array to be sorted 4 | var arr = [25, 13, 55, 63, 2, 61, 35, 47]; 5 | 6 | function bubbleSort(arr) { 7 | for (var i = 0; i < arr.length; i++) { 8 | for (var j = 0; j < arr.length - i - 1; j++) { 9 | if (arr[j] > arr[j + 1]) { 10 | var temp = arr[j]; 11 | arr[j] = arr[j + 1]; 12 | arr[j + 1] = temp; 13 | } 14 | } 15 | } 16 | console.log(arr); 17 | } 18 | 19 | //One of the simple easy algorithm to implement 20 | //Bubble sort algorithm sorts the array 21 | //by comparing two adjacent elements and swaps them if they are not in the intended order 22 | bubbleSort(arr); 23 | -------------------------------------------------------------------------------- /Algos/JavaScript/dfs.js: -------------------------------------------------------------------------------- 1 | class Graph { 2 | constructor() { 3 | this.vertices = []; 4 | this.adjacent = {}; 5 | this.edges = 0; 6 | } 7 | 8 | addVertex(v) { 9 | this.vertices.push(v); 10 | this.adjacent[v] = []; 11 | } 12 | 13 | addEdge(v, w) { 14 | this.adjacent[v].push(w); 15 | this.adjacent[w].push(v); 16 | this.edges++; 17 | } 18 | dfs(goal, v = this.vertices[0], discovered = []) { 19 | let adj = this.adjacent; 20 | 21 | discovered[v] = true; 22 | 23 | for (let i = 0; i < adj[v].length; i++) { 24 | let w = adj[v][i]; 25 | 26 | if (!discovered[w]) { 27 | this.dfs(goal, w, discovered); 28 | } 29 | } 30 | 31 | return discovered[goal] || false; 32 | } 33 | } 34 | 35 | const g = new Graph(); 36 | 37 | g.addVertex("A"); 38 | g.addVertex("B"); 39 | g.addVertex("C"); 40 | g.addVertex("D"); 41 | 42 | g.addEdge("A", "B"); 43 | g.addEdge("A", "C"); 44 | g.addEdge("A", "D"); 45 | g.addEdge("B", "C"); 46 | g.addEdge("B", "D"); 47 | g.addEdge("C", "D"); 48 | 49 | console.log(g.dfs("D")); 50 | -------------------------------------------------------------------------------- /Algos/JavaScript/dijstras.js: -------------------------------------------------------------------------------- 1 | class Graph { 2 | constructor() { 3 | this.vertices = []; 4 | this.adjacencyList = {}; 5 | } 6 | addVertex(vertex) { 7 | this.vertices.push(vertex); 8 | this.adjacencyList[vertex] = {}; 9 | } 10 | 11 | addEdge(vertex1, vertex2, weight) { 12 | this.adjacencyList[vertex1][vertex2] = weight; 13 | } 14 | 15 | changeWeight(vertex1, vertex2, weight) { 16 | this.adjacencyList[vertex1][vertex2] = weight; 17 | } 18 | dijkstra(source) { 19 | let distances = {}, 20 | parents = {}, 21 | visited = new Set(); 22 | for (let i = 0; i < this.vertices.length; i++) { 23 | if (this.vertices[i] === source) { 24 | distances[source] = 0; 25 | } else { 26 | distances[this.vertices[i]] = Infinity; 27 | } 28 | parents[this.vertices[i]] = null; 29 | } 30 | 31 | let currVertex = this.vertexWithMinDistance(distances, visited); 32 | 33 | while (currVertex !== null) { 34 | let distance = distances[currVertex], 35 | neighbors = this.adjacencyList[currVertex]; 36 | for (let neighbor in neighbors) { 37 | let newDistance = distance + neighbors[neighbor]; 38 | if (distances[neighbor] > newDistance) { 39 | distances[neighbor] = newDistance; 40 | parents[neighbor] = currVertex; 41 | } 42 | } 43 | visited.add(currVertex); 44 | currVertex = this.vertexWithMinDistance(distances, visited); 45 | } 46 | 47 | console.log(parents); 48 | console.log(distances); 49 | } 50 | vertexWithMinDistance(distances, visited) { 51 | let minDistance = Infinity, 52 | minVertex = null; 53 | for (let vertex in distances) { 54 | let distance = distances[vertex]; 55 | if (distance < minDistance && !visited.has(vertex)) { 56 | minDistance = distance; 57 | minVertex = vertex; 58 | } 59 | } 60 | return minVertex; 61 | } 62 | } 63 | 64 | let g = new Graph(); 65 | 66 | // add the vertices 67 | g.addVertex("A"); 68 | g.addVertex("B"); 69 | g.addVertex("C"); 70 | g.addVertex("D"); 71 | 72 | // create the edges 73 | g.addEdge("A", "B", 3); 74 | g.addEdge("A", "C", 2); 75 | g.addEdge("B", "D", 2); 76 | g.addEdge("C", "D", 6); 77 | 78 | // run dijkstra's algorithm, with A as the source vertex. 79 | g.dijkstra("A"); 80 | 81 | // should log 82 | // { A: null, B: 'A', C: 'A', D: 'B' } 83 | // { A: 0, B: 3, C: 2, D: 5 } 84 | -------------------------------------------------------------------------------- /Algos/JavaScript/insertionsort.js: -------------------------------------------------------------------------------- 1 | // Insertion sort Implementation using Javascript 2 | 3 | //array to be sorted 4 | var arr = [25, 13, 55, 63, 2, 61, 35, 47]; 5 | 6 | function insertionSort(arr) { 7 | let i, key, j; 8 | for (i = 1; i < arr.length; i++) { 9 | key = arr[i]; 10 | j = i - 1; 11 | 12 | while (j >= 0 && arr[j] > key) { 13 | arr[j + 1] = arr[j]; 14 | j = j - 1; 15 | } 16 | arr[j + 1] = key; 17 | } 18 | 19 | console.log(arr); 20 | } 21 | 22 | // array is split into a sorted and an unsorted part and then arranged accordingly 23 | // it is appropriate for data sets which are already partially sorted. 24 | insertionSort(arr); 25 | -------------------------------------------------------------------------------- /Algos/JavaScript/kmp.js: -------------------------------------------------------------------------------- 1 | let btn = document.getElementById('btn') 2 | let output = document.getElementById('output') 3 | 4 | btn.addEventListener("click",()=>{ 5 | text = document.getElementById("text").value 6 | pattern = document.getElementById("pattern").value 7 | let res = kmpMatching(text, pattern) 8 | output.innerHTML = `Pattern found at index ${res}` 9 | 10 | }) 11 | 12 | function longestPrefix(str) { 13 | var table = new Array(str.length); 14 | var maxPrefix = 0; 15 | 16 | table[0] = 0; 17 | for (var i = 1; i < str.length; i++) { 18 | while (maxPrefix > 0 && str.charAt(i) !== str.charAt(maxPrefix)) { 19 | maxPrefix = table[maxPrefix - 1]; 20 | } 21 | if (str.charAt(maxPrefix) === str.charAt(i)) { 22 | maxPrefix++; 23 | } 24 | table[i] = maxPrefix; 25 | } 26 | return table; 27 | } 28 | 29 | function kmpMatching(str, pattern) { 30 | var prefixes = longestPrefix(pattern); 31 | var matches = []; 32 | var j = 0; 33 | var i = 0; 34 | while (i < str.length) { 35 | if (str.charAt(i) === pattern.charAt(j)) { 36 | i++; 37 | j++; 38 | } 39 | if (j === pattern.length) { 40 | matches.push(i - j); 41 | j = prefixes[j - 1]; 42 | } 43 | else if (str.charAt(i) !== pattern.charAt(j)) { 44 | if (j !== 0) { 45 | j = prefixes[j - 1]; 46 | } else { 47 | i++; 48 | } 49 | } 50 | } 51 | return matches; 52 | } 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /Algos/JavaScript/mergesort.js: -------------------------------------------------------------------------------- 1 | // Merge sort Implementation using Javascript 2 | 3 | //array to be sorted 4 | var arr = [25, 13, 55, 63, 2, 61, 35, 47]; 5 | 6 | function merge(arr, l, m, r) { 7 | var n1 = m - l + 1; 8 | var n2 = r - m; 9 | 10 | var L = new Array(n1); 11 | var R = new Array(n2); 12 | 13 | for (var i = 0; i < n1; i++) L[i] = arr[l + i]; 14 | for (var j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; 15 | 16 | var i = 0; 17 | var j = 0; 18 | var k = l; 19 | 20 | while (i < n1 && j < n2) { 21 | if (L[i] <= R[j]) { 22 | arr[k] = L[i]; 23 | i++; 24 | } else { 25 | arr[k] = R[j]; 26 | j++; 27 | } 28 | k++; 29 | } 30 | 31 | while (i < n1) { 32 | arr[k] = L[i]; 33 | i++; 34 | k++; 35 | } 36 | 37 | while (j < n2) { 38 | arr[k] = R[j]; 39 | j++; 40 | k++; 41 | } 42 | } 43 | 44 | // l is for left index and r is 45 | function mergeSort(arr, l, r) { 46 | if (l >= r) { 47 | return; 48 | } 49 | var m = l + parseInt((r - l) / 2); 50 | mergeSort(arr, l, m); 51 | mergeSort(arr, m + 1, r); 52 | merge(arr, l, m, r); 53 | console.log(arr); 54 | } 55 | 56 | //this is a recursive algorithm 57 | //splits the array recursively until the last element and merge them back in sorted manner 58 | mergeSort(arr, 0, arr.length - 1); 59 | -------------------------------------------------------------------------------- /Algos/JavaScript/quicksort.js: -------------------------------------------------------------------------------- 1 | // Quick sort Implementation using Javascript 2 | 3 | //array to be sorted 4 | var arr = [25, 13, 55, 63, 2, 61, 35, 47]; 5 | 6 | /* Utility Functions */ 7 | 8 | //swapping function 9 | function swap(arr, i, j) { 10 | let temp = arr[i]; 11 | arr[i] = arr[j]; 12 | arr[j] = temp; 13 | } 14 | 15 | //piovting function 16 | function partition(arr, low, high) { 17 | let pivot = arr[high]; 18 | let i = low - 1; 19 | 20 | for (let j = low; j <= high - 1; j++) { 21 | if (arr[j] < pivot) { 22 | i++; 23 | swap(arr, i, j); 24 | } 25 | } 26 | swap(arr, i + 1, high); 27 | return i + 1; 28 | } 29 | 30 | //main function 31 | function quickSort(arr, low, high) { 32 | if (low < high) { 33 | let pi = partition(arr, low, high); 34 | quickSort(arr, low, pi - 1); 35 | quickSort(arr, pi + 1, high); 36 | } 37 | console.log(arr); 38 | } 39 | 40 | //just like merge sort, this is also a recursive algorithm 41 | quickSort(arr, 0, arr.length - 1); 42 | -------------------------------------------------------------------------------- /Algos/JavaScript/selectionsort.js: -------------------------------------------------------------------------------- 1 | function selectionSort(inputArr) { 2 | let n = inputArr.length; 3 | 4 | for(let i = 0; i < n; i++) { 5 | // Finding the smallest number in the subarray 6 | let min = i; 7 | for(let j = i+1; j < n; j++){ 8 | if(inputArr[j] < inputArr[min]) { 9 | min=j; 10 | } 11 | } 12 | if (min != i) { 13 | // Swapping the elements 14 | let tmp = inputArr[i]; 15 | inputArr[i] = inputArr[min]; 16 | inputArr[min] = tmp; 17 | } 18 | } 19 | return inputArr; 20 | } 21 | -------------------------------------------------------------------------------- /Algos/Python/Armstrong.py: -------------------------------------------------------------------------------- 1 | num = int(input("Enter a number: ")) 2 | 3 | 4 | sum = 0 5 | 6 | 7 | temp = num 8 | while temp > 0: 9 | digit = temp % 10 10 | sum += digit ** 3 11 | temp //= 10 12 | 13 | 14 | if num == sum: 15 | print(num, "is an Armstrong number") 16 | else: 17 | print(num, "is not an Armstrong number") 18 | -------------------------------------------------------------------------------- /Algos/Python/Dollar to Indian Rupee converter.py: -------------------------------------------------------------------------------- 1 | #Dollar to Indian Rupee Converter 2 | 3 | print('Dollar to Indian Rupee Converter') 4 | 5 | dollar=int(input('Enter amount in Dollar:')) 6 | rupee=dollar*82 7 | print("Amount in Indian Rupee:", rupee) 8 | -------------------------------------------------------------------------------- /Algos/Python/DutchNationalFlagProb.py: -------------------------------------------------------------------------------- 1 | def dutch_sort(a, arr_size): 2 | low = 0 3 | high = arr_size - 1 4 | mid = 0 5 | # Iterate till all the elements are sorted 6 | while mid <= high: 7 | # If the element is 0 8 | if a[mid] == 0: 9 | a[low], a[mid] = a[mid], a[low] 10 | low = low + 1 11 | mid = mid + 1 12 | # If the element is 1 13 | elif a[mid] == 1: 14 | mid = mid + 1 15 | # If the element is 2 16 | else: 17 | a[mid], a[high] = a[high], a[mid] 18 | high = high - 1 19 | return a 20 | 21 | # Function to print array 22 | 23 | 24 | def printArray(a): 25 | for k in a: 26 | print(k, end=' ') 27 | 28 | 29 | arr = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 1] 30 | arr_size = len(arr) 31 | arr = dutch_sort(arr, arr_size) 32 | printArray(arr) 33 | -------------------------------------------------------------------------------- /Algos/Python/Fizz-Buzz.py: -------------------------------------------------------------------------------- 1 | choice = int(input("Enter maximum range: ")) 2 | choice = choice + 1 3 | 4 | def FizzBuzz(choice): 5 | for num in range(1,choice): 6 | if num % 3 == 0 and num % 5 == 0: 7 | print("fizzbuzz") 8 | elif num % 5 == 0: 9 | print("buzz") 10 | elif num % 3 == 0: 11 | print("fizz") 12 | else: 13 | print(num) 14 | 15 | FizzBuzz(choice) -------------------------------------------------------------------------------- /Algos/Python/GCD.py: -------------------------------------------------------------------------------- 1 | def GCD_Loop( a, b): 2 | if a > b: # define the if condition 3 | temp = b 4 | else: 5 | temp = a 6 | for i in range(1, temp + 1): 7 | if (( a % i == 0) and (b % i == 0 )): 8 | gcd = i 9 | return gcd 10 | -------------------------------------------------------------------------------- /Algos/Python/JosephusProblem.py: -------------------------------------------------------------------------------- 1 | def JosephusProblem(n , k): 2 | if n==1: 3 | return 1 4 | else: 5 | return (JosephusProblem(n-1 , k) + k-1) % n +1 6 | 7 | print("JosephusProblem(8,2) = " , end=' ') 8 | print(JosephusProblem(8,2)) 9 | print("JosephusProblem(7,3) = " , end=' ') 10 | print(JosephusProblem(7,3)) -------------------------------------------------------------------------------- /Algos/Python/Merge mails.py: -------------------------------------------------------------------------------- 1 | # Python program to mail merger 2 | # Names are in the file names.txt 3 | # Body of the mail is in body.txt 4 | 5 | # open names.txt for reading 6 | with open("names.txt", 'r', encoding='utf-8') as names_file: 7 | 8 | # open body.txt for reading 9 | with open("body.txt", 'r', encoding='utf-8') as body_file: 10 | 11 | # read entire content of the body 12 | body = body_file.read() 13 | 14 | # iterate over names 15 | for name in names_file: 16 | mail = "Hello " + name.strip() + "\n" + body 17 | 18 | # write the mails to individual files 19 | with open(name.strip()+".txt", 'w', encoding='utf-8') as mail_file: 20 | mail_file.write(mail) 21 | -------------------------------------------------------------------------------- /Algos/Python/N-Queens.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def solveNQueens(self, N: int) -> list[list[str]]: 3 | board = [list("." * N) for _ in range(N)] 4 | listOfSolutions = [] 5 | columnUnsafe = set() 6 | positiveDiagonalUnsafe = set() 7 | negativeDiagonalUnsafe = set() 8 | 9 | def backtrackingNQueensSolution(row: int): 10 | if (row == N): 11 | listOfSolutions.append(list(map(lambda x: "".join(x), board))) 12 | else: 13 | for column in range(len(board)): 14 | if (column in columnUnsafe or (column + row) in positiveDiagonalUnsafe or (column - row) in negativeDiagonalUnsafe): 15 | continue 16 | 17 | columnUnsafe.add(column) 18 | positiveDiagonalUnsafe.add(column + row) 19 | negativeDiagonalUnsafe.add(column - row) 20 | board[row][column] = "Q" 21 | 22 | backtrackingNQueensSolution(row+1) 23 | 24 | columnUnsafe.remove(column) 25 | positiveDiagonalUnsafe.remove(column + row) 26 | negativeDiagonalUnsafe.remove(column - row) 27 | board[row][column] = "." 28 | 29 | backtrackingNQueensSolution(0) 30 | return listOfSolutions -------------------------------------------------------------------------------- /Algos/Python/Permutations calculator.py: -------------------------------------------------------------------------------- 1 | #To calculate factorial 2 | 3 | def factorial(x): 4 | if x == 1: 5 | return 1 6 | else: 7 | return (x * factorial(x-1)) 8 | 9 | 10 | print("Calculate the number of permutations possible (nPr)") 11 | 12 | #to get the input 13 | 14 | n=int(input("Total number of objects (n): ")) 15 | r=int(input("Number of objects selected (r): ")) 16 | 17 | #to check calculation possible 18 | 19 | if n>=r: 20 | #calculations of permutation 21 | n_min_r=n-r 22 | n_fac = factorial(n) 23 | n_min_r_fac = factorial(n_min_r) 24 | nPr=int(n_fac/n_min_r_fac) 25 | print("Number of permutations possible (nPr) is",nPr) 26 | else: 27 | print("Number of objects selected cannot be more than Total objects") 28 | -------------------------------------------------------------------------------- /Algos/Python/Quick-sort.py: -------------------------------------------------------------------------------- 1 | quickSort(arr[], low, high) 2 | { 3 | if (low < high) 4 | { 5 | /* pi is partitioning index, arr[p] is now 6 | at right place */ 7 | pi = partition(arr, low, high); 8 | 9 | quickSort(arr, low, pi - 1); // Before pi 10 | quickSort(arr, pi + 1, high); // After pi 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Algos/Python/TestSpeed.py: -------------------------------------------------------------------------------- 1 | from speedtest import Speedtest 2 | from tkinter import * 3 | 4 | def update_text(): 5 | st = Speedtest() 6 | download = st.download() 7 | upload = st.upload() 8 | download_speed = round(download / (10**6), 2) 9 | upload_speed = round(upload / (10**6), 2) 10 | down_label.config(text = "Download Speed: " + str(download_speed) + "MBps") 11 | up_label.config(text = "Upload Speed: " + str(upload_speed) + "MBps") 12 | #print("Download speed: ", st.download(), "bytes/s") 13 | #print("Upload speed: ", st.upload(), "bytes/s") 14 | root = Tk() 15 | root.title("Internet Speed Tester") 16 | root.geometry("400x200") 17 | Label(root, text="Internet Speed Tester", font=("Arial 22 italic")).pack(pady=10) 18 | 19 | 20 | button = Button(root, text="Check speed", font=("Helvetica 18") ,command=update_text) 21 | button.pack() 22 | down_label = Label(root, text="", font=("Arial 15")) 23 | down_label.pack() 24 | up_label = Label(root, text="", font=("Arial 15")) 25 | up_label.pack() 26 | root.mainloop() 27 | 28 | -------------------------------------------------------------------------------- /Algos/Python/applicationbilling.py: -------------------------------------------------------------------------------- 1 | //write a python program to create a application to read no of pizza, no of burger, no of cooldrinks and print the final billing 2 | pizza=int(input("enter the no of pizza")) 3 | burger=int(input("enter the no of burger")) 4 | cd=int(input("enter the no of cd")) 5 | total=pizza*100+burger*60+cd*20 6 | print("total=",total) 7 | -------------------------------------------------------------------------------- /Algos/Python/area.py: -------------------------------------------------------------------------------- 1 | # Three sides of the triangle is a, b and c: 2 | a = float(input('Enter first side: ')) 3 | b = float(input('Enter second side: ')) 4 | c = float(input('Enter third side: ')) 5 | 6 | # calculate the semi-perimeter 7 | s = (a + b + c) / 2 8 | 9 | # calculate the area 10 | area = (s*(s-a)(s-b)(s-c)) ** 0.5 11 | print('The area of the triangle is %0.2f' %area) 12 | -------------------------------------------------------------------------------- /Algos/Python/arraysum.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | ar = list(map(int,input().split())) 3 | ans = 0 4 | for i in range(n): 5 | ans = ans + ar[i] 6 | print(ans) 7 | -------------------------------------------------------------------------------- /Algos/Python/binary_tree.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, data): 3 | self.left = None 4 | self.right = None 5 | self.data = data 6 | # Insert Node 7 | def insert(self, data): 8 | if self.data: 9 | if data < self.data: 10 | if self.left is None: 11 | self.left = Node(data) 12 | else: 13 | self.left.insert(data) 14 | else data > self.data: 15 | if self.right is None: 16 | self.right = Node(data) 17 | else: 18 | self.right.insert(data) 19 | else: 20 | self.data = data 21 | # Print the Tree 22 | def PrintTree(self): 23 | if self.left: 24 | self.left.PrintTree() 25 | print( self.data), 26 | if self.right: 27 | self.right.PrintTree() 28 | # Inorder traversal 29 | # Left -> Root -> Right 30 | def inorderTraversal(self, root): 31 | res = [] 32 | if root: 33 | res = self.inorderTraversal(root.left) 34 | res.append(root.data) 35 | res = res + self.inorderTraversal(root.right) 36 | return res 37 | 38 | print(root.inorderTraversal(root)) -------------------------------------------------------------------------------- /Algos/Python/binarysearch.py: -------------------------------------------------------------------------------- 1 | def binary_search(arr, low, high, x): 2 | 3 | # Check base case 4 | if high >= low: 5 | 6 | mid = (high + low) // 2 7 | 8 | # If element is present at the middle itself 9 | if arr[mid] == x: 10 | return mid 11 | 12 | # If element is smaller than mid, then it can only 13 | # be present in left subarray 14 | elif arr[mid] > x: 15 | return binary_search(arr, low, mid - 1, x) 16 | 17 | # Else the element can only be present in right subarray 18 | else: 19 | return binary_search(arr, mid + 1, high, x) 20 | 21 | else: 22 | # Element is not present in the array 23 | return -1 24 | 25 | 26 | # Test array 27 | arr = input('Enter the elements ').split(',') 28 | arr = [int(i) for i in arr] 29 | 30 | x = int(input('Enter the element to be searched ')) 31 | 32 | # Function call 33 | result = binary_search(arr, 0, len(arr)-1, x) 34 | 35 | if result != -1: 36 | print("Element is present at index", str(result)) 37 | else: 38 | print("Element is not present in array") 39 | -------------------------------------------------------------------------------- /Algos/Python/breadth_first_search.py: -------------------------------------------------------------------------------- 1 | # Python3 Program to print BFS traversal 2 | # from a given source vertex. BFS(int s) 3 | # traverses vertices reachable from s. 4 | from collections import defaultdict 5 | 6 | # This class represents a directed graph 7 | # using adjacency list representation 8 | class Graph: 9 | 10 | # Constructor 11 | def __init__(self): 12 | 13 | # default dictionary to store graph 14 | self.graph = defaultdict(list) 15 | 16 | # function to add an edge to graph 17 | def addEdge(self,u,v): 18 | self.graph[u].append(v) 19 | 20 | # Function to print a BFS of graph 21 | def BFS(self, s): 22 | 23 | # Mark all the vertices as not visited 24 | visited = [False] * (len(self.graph)) 25 | 26 | # Create a queue for BFS 27 | queue = [] 28 | 29 | # Mark the source node as 30 | # visited and enqueue it 31 | queue.append(s) 32 | visited[s] = True 33 | 34 | while queue: 35 | 36 | # Dequeue a vertex from 37 | # queue and print it 38 | s = queue.pop(0) 39 | print (s, end = " ") 40 | 41 | # Get all adjacent vertices of the 42 | # dequeued vertex s. If a adjacent 43 | # has not been visited, then mark it 44 | # visited and enqueue it 45 | for i in self.graph[s]: 46 | if visited[i] == False: 47 | queue.append(i) 48 | visited[i] = True 49 | 50 | # Driver code 51 | 52 | # Create a graph given in 53 | # the above diagram 54 | g = Graph() 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 | g.addEdge(3, 3) 61 | 62 | print ("Following is Breadth First Traversal" 63 | " (starting from vertex 2)") 64 | g.BFS(2) 65 | 66 | -------------------------------------------------------------------------------- /Algos/Python/bucket_sort.py: -------------------------------------------------------------------------------- 1 | def bucketSort(array): 2 | bucket = [] 3 | for i in range(len(array)): 4 | bucket.append([]) 5 | for j in array: 6 | index_b = int(10 * j) 7 | bucket[index_b].append(j) 8 | for i in range(len(array)): 9 | bucket[i] = sorted(bucket[i]) 10 | k = 0 11 | for i in range(len(array)): 12 | for j in range(len(bucket[i])): 13 | array[k] = bucket[i][j] 14 | k += 1 15 | return array 16 | #driver code 17 | array = [.42, .32, .33, .52, .37, .47, .51] 18 | print("Sorted Array in descending order is") 19 | print(bucketSort(array)) 20 | 21 | -------------------------------------------------------------------------------- /Algos/Python/checkPalindrome.py: -------------------------------------------------------------------------------- 1 | def isPalindrome(str,rev_str): 2 | x = str == rev_str 3 | return x 4 | 5 | while True: 6 | print("\n####################\tPalindrome Checker by Cyber-Mukherjee\t####################\n") 7 | try: 8 | choice = int(input("Press the number corresponding to the option to select it\n0.\tExit\n1.\tCheck for Palindrome\n")) 9 | 10 | if choice == 1: 11 | string = input("Enter the string you want to check: ") 12 | low_str = string.lower() 13 | rev_str = low_str[-1::-1] 14 | 15 | result = isPalindrome(low_str,rev_str) 16 | if result == True: 17 | print(f"\n{string} is a palindrome!") 18 | elif result == False: 19 | print(f"\n{string} is not a palindrome as it spells {rev_str} when reversed.") 20 | else: 21 | print("invalid input") 22 | 23 | elif choice == 0: 24 | print("\n####################\tThank you for using my program\t####################") 25 | break 26 | else: 27 | print("\nInvalid input") 28 | 29 | except: 30 | print("\nEnter an integer value corresponding to your choice!") 31 | -------------------------------------------------------------------------------- /Algos/Python/create a dictionary.py: -------------------------------------------------------------------------------- 1 | # Initializing a dictionary with some elements 2 | Dictionary = {1: 'Javatpoint', 2: 'Python', 3: 'Dictionary'} 3 | print("\nDictionary created using curly braces: ") 4 | print(Dictionary) 5 | # Creating a Dictionary with keys of different data types 6 | Dictionary = {'Website': 'Javatpoint', 3: [2, 3, 5, 'Dictionary']} 7 | print("\nDictionary with keys of multiple data type: ") 8 | print(Dictionary) 9 | -------------------------------------------------------------------------------- /Algos/Python/depth_first_search.py: -------------------------------------------------------------------------------- 1 | # Python program to print DFS traversal for complete graph 2 | from collections import defaultdict 3 | 4 | # This class represents a directed graph using adjacency 5 | # list representation 6 | class Graph: 7 | 8 | # Constructor 9 | def __init__(self): 10 | 11 | # default dictionary to store graph 12 | self.graph = defaultdict(list) 13 | 14 | # function to add an edge to graph 15 | def addEdge(self,u,v): 16 | self.graph[u].append(v) 17 | 18 | # A function used by DFS 19 | def DFSUtil(self, v, visited): 20 | 21 | # Mark the current node as visited and print it 22 | visited[v]= True 23 | print v, 24 | 25 | # Recur for all the vertices adjacent to 26 | # this vertex 27 | for i in self.graph[v]: 28 | if visited[i] == False: 29 | self.DFSUtil(i, visited) 30 | 31 | 32 | # The function to do DFS traversal. It uses 33 | # recursive DFSUtil() 34 | def DFS(self): 35 | V = len(self.graph) #total vertices 36 | 37 | # Mark all the vertices as not visited 38 | visited =[False]*(V) 39 | 40 | # Call the recursive helper function to print 41 | # DFS traversal starting from all vertices one 42 | # by one 43 | for i in range(V): 44 | if visited[i] == False: 45 | self.DFSUtil(i, visited) 46 | 47 | 48 | # Driver code 49 | # Create a graph given in the above diagram 50 | g = Graph() 51 | g.addEdge(0, 1) 52 | g.addEdge(0, 2) 53 | g.addEdge(1, 2) 54 | g.addEdge(2, 0) 55 | g.addEdge(2, 3) 56 | g.addEdge(3, 3) 57 | 58 | print "Following is Depth First Traversal" 59 | g.DFS() 60 | 61 | -------------------------------------------------------------------------------- /Algos/Python/dijkstras_algo.py: -------------------------------------------------------------------------------- 1 | 2 | class Graph(): 3 | 4 | def __init__(self, vertices): 5 | self.V = vertices 6 | self.graph = [[0 for column in range(vertices)] 7 | for row in range(vertices)] 8 | 9 | def printSolution(self, dist): 10 | print("Vertex \t Distance from Source") 11 | for node in range(self.V): 12 | print(node, "\t\t", dist[node]) 13 | 14 | def minDistance(self, dist, sptSet): 15 | 16 | min = 1e7 17 | 18 | for v in range(self.V): 19 | if dist[v] < min and sptSet[v] == False: 20 | min = dist[v] 21 | min_index = v 22 | 23 | return min_index 24 | 25 | def dijkstra(self, src): 26 | 27 | dist = [1e7] * self.V 28 | dist[src] = 0 29 | sptSet = [False] * self.V 30 | 31 | for cout in range(self.V): 32 | 33 | u = self.minDistance(dist, sptSet) 34 | 35 | sptSet[u] = True 36 | for v in range(self.V): 37 | if (self.graph[u][v] > 0 and 38 | sptSet[v] == False and 39 | dist[v] > dist[u] + self.graph[u][v]): 40 | dist[v] = dist[u] + self.graph[u][v] 41 | 42 | self.printSolution(dist) 43 | 44 | # Driver program 45 | g = Graph(9) 46 | g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0], 47 | [4, 0, 8, 0, 0, 0, 0, 11, 0], 48 | [0, 8, 0, 7, 0, 4, 0, 0, 2], 49 | [0, 0, 7, 0, 9, 14, 0, 0, 0], 50 | [0, 0, 0, 9, 0, 10, 0, 0, 0], 51 | [0, 0, 4, 14, 10, 0, 2, 0, 0], 52 | [0, 0, 0, 0, 0, 2, 0, 1, 6], 53 | [8, 11, 0, 0, 0, 0, 1, 0, 7], 54 | [0, 0, 2, 0, 0, 0, 6, 7, 0] 55 | ] 56 | 57 | g.dijkstra(0) 58 | 59 | -------------------------------------------------------------------------------- /Algos/Python/discordbot.py: -------------------------------------------------------------------------------- 1 | import discord 2 | import random 3 | from discord.ext import commands 4 | 5 | bot = commands.Bot(command_prefix=".") 6 | 7 | 8 | @bot.event 9 | async def on_ready(): 10 | print("Let's get started!") 11 | 12 | 13 | @bot.command() 14 | async def hello(ctx): 15 | await ctx.reply('Hello!') 16 | 17 | 18 | @bot.command() 19 | async def rps(ctx, message): 20 | answer = message.lower() 21 | choice = ["rock", "paper", "scissors"] 22 | computers_answer = random.choice(choice) 23 | if answer not in choice: 24 | await ctx.reply("This is not a valid choice. Choose one of these: rock, paper, scissors.") 25 | else: 26 | if computers_answer == answer: 27 | await ctx.reply("It's a tie :/.") 28 | if computers_answer == "rock": 29 | if answer == "paper": 30 | await ctx.reply(f"You win! I chose {computers_answer} and you chose {answer}!") 31 | if computers_answer == "rock": 32 | if answer == "scissors": 33 | await ctx.reply(f"You loose! I chose {computers_answer} and you chose {answer}!") 34 | if computers_answer == "paper": 35 | if answer == "rock": 36 | await ctx.reply(f"You loose! I chose {computers_answer} and you chose {answer}!") 37 | if computers_answer == "paper": 38 | if answer == "scissors": 39 | await ctx.reply(f"You win! I chose {computers_answer} and you chose {answer}!") 40 | if computers_answer == "scissors": 41 | if answer == "rock": 42 | await ctx.reply(f"You win! I chose {computers_answer} and you chose {answer}!") 43 | if computers_answer == "scissors": 44 | if answer == "paper": 45 | await ctx.reply(f"You loose! I chose {computers_answer} and you chose {answer}!") 46 | 47 | bot.run('OTMwMzU2NDk4NjAzODQ3NzMw.Yd0sAg.hD8J5UTjQ58XoPB36YW83Z-LnV8') 48 | -------------------------------------------------------------------------------- /Algos/Python/exponential_search.py: -------------------------------------------------------------------------------- 1 | def binary_search(arr, e, s, key): 2 | if s >= e: 3 | mid = e + (s - e) // 2 4 | if arr[mid] == key: 5 | return mid 6 | elif arr[mid] > key: 7 | return binary_search(arr, e, mid - 1, key) 8 | else: 9 | return binary_search(arr, mid + 1, s, key) 10 | else: 11 | return -1 12 | def exponential_search(arr, n, key): 13 | if arr[0] == key: 14 | return 0 15 | i = 1 16 | while i < n and arr[i] <= key: 17 | i = i * 2 18 | return binary_search(arr, i // 2, min(i, n), key) 19 | 20 | #driver code 21 | arr = [2, 3, 4, 10, 40] 22 | n = len(arr) 23 | key = 10 24 | result = exponential_search(arr, n, key) 25 | print(result) 26 | -------------------------------------------------------------------------------- /Algos/Python/fibonacci.py: -------------------------------------------------------------------------------- 1 | def Fibonacci(n): 2 | 3 | # Check if input is 0 then it will 4 | if n < 0: 5 | print("Incorrect input") 6 | elif n == 0: 7 | return 0 8 | 9 | # Check if n is 1,2 10 | elif n == 1 or n == 2: 11 | return 1 12 | 13 | else: 14 | return Fibonacci(n-1) + Fibonacci(n-2) 15 | print(Fibonacci(9)) 16 | -------------------------------------------------------------------------------- /Algos/Python/floyd_warshall.py: -------------------------------------------------------------------------------- 1 | 2 | V = 3 3 | 4 | 5 | INF = 86757 6 | 7 | 8 | 9 | def floydWarshall(graph): 10 | 11 | dist = list(map(lambda i: list(map(lambda j: j, i)), graph)) 12 | 13 | for k in range(V): 14 | 15 | for i in range(V): 16 | 17 | 18 | for j in range(V): 19 | 20 | dist[i][j] = min(dist[i][j], 21 | dist[i][k] + dist[k][j] 22 | ) 23 | printSolution(dist) 24 | 25 | 26 | def printSolution(dist): 27 | print("Following matrix shows the shortest distances between every pair of vertices") 28 | for i in range(V): 29 | for j in range(V): 30 | if(dist[i][j] == INF): 31 | print("%7s" % ("INF"), end=" ") 32 | else: 33 | print("%7d\t" % (dist[i][j]), end=' ') 34 | if j == V-1: 35 | print() 36 | if __name__ == "__main__": 37 | 38 | graph = [[0, 5, INF, 10], 39 | [INF, 0, 3, INF], 40 | [INF, INF, 0, 1], 41 | ] 42 | floydWarshall(graph) 43 | -------------------------------------------------------------------------------- /Algos/Python/gcf.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from matplotlib.backends.backend_agg import FigureCanvasAgg 3 | import matplotlib.pyplot as plot 4 | 5 | plot.plot([2, 3, 4]) 6 | 7 | # implementation of the 8 | # matplotlib.pyplot.gcf() 9 | # function 10 | figure = plot.gcf().canvas 11 | 12 | ag = figure.switch_backends(FigureCanvasAgg) 13 | ag.draw() 14 | A = np.asarray(ag.buffer_rgba()) 15 | 16 | # Pass off to PIL. 17 | from PIL import Image 18 | img = Image.fromarray(A) 19 | 20 | # show image 21 | img.show() 22 | -------------------------------------------------------------------------------- /Algos/Python/insertion_sort.py: -------------------------------------------------------------------------------- 1 | def insertionSort(arr): 2 | for i in range(1, len(arr)): 3 | key = arr[i] 4 | j = i-1 5 | while j >= 0 and key < arr[j] : 6 | arr[j + 1] = arr[j] 7 | j -= 1 8 | arr[j + 1] = key 9 | #driver code 10 | arr = [12, 11, 13, 5, 6] 11 | insertionSort(arr) 12 | print ("Sorted array is:") 13 | for i in range(len(arr)): 14 | print ("%d" %arr[i]) 15 | -------------------------------------------------------------------------------- /Algos/Python/josephus_iterative.py: -------------------------------------------------------------------------------- 1 | def Josephus_iterative(n, k): 2 | 3 | k -= 1 4 | arr = [0]*n 5 | for i in range(n): 6 | arr[i] = 1 7 | cnt = 0 8 | cut = 0 9 | num = 1 10 | while (cnt < (n - 1)): 11 | 12 | 13 | while (num <= k): 14 | 15 | 16 | cut += 1 17 | cut = cut % n 18 | if (arr[cut] == 1): 19 | num+=1 20 | num = 1 21 | arr[cut] = 0 # 22 | cnt += 1 # 23 | cut += 1 24 | cut = cut % n # Ch 25 | while (arr[cut] == 0): 26 | 27 | cut += 1 28 | cut = cut % n 29 | # of Index. 30 | 31 | return cut + 1 32 | 33 | # Driver Code 34 | n, k = 14, 2 35 | print(Josephus_iterative(n, k)) 36 | -------------------------------------------------------------------------------- /Algos/Python/largest_prime_factor.py: -------------------------------------------------------------------------------- 1 | def largest_prime_factor(n): 2 | while n: 3 | i = 2 4 | while n > 1: 5 | if n % i == 0: 6 | n /= i 7 | else: 8 | i += 1 9 | return i 10 | 11 | 12 | print(largest_prime_factor(600851475143)) 13 | -------------------------------------------------------------------------------- /Algos/Python/merge_sort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of MergeSort 2 | 3 | # Merges two subarrays of arr[]. 4 | # First subarray is arr[l..m] 5 | # Second subarray is arr[m+1..r] 6 | 7 | 8 | def merge(arr, l, m, r): 9 | n1 = m - l + 1 10 | n2 = r - m 11 | 12 | # create temp arrays 13 | L = [0] * (n1) 14 | R = [0] * (n2) 15 | 16 | # Copy data to temp arrays L[] and R[] 17 | for i in range(0, n1): 18 | L[i] = arr[l + i] 19 | 20 | for j in range(0, n2): 21 | R[j] = arr[m + 1 + j] 22 | 23 | # Merge the temp arrays back into arr[l..r] 24 | i = 0 # Initial index of first subarray 25 | j = 0 # Initial index of second subarray 26 | k = l # Initial index of merged subarray 27 | 28 | while i < n1 and j < n2: 29 | if L[i] <= R[j]: 30 | arr[k] = L[i] 31 | i += 1 32 | else: 33 | arr[k] = R[j] 34 | j += 1 35 | k += 1 36 | 37 | # Copy the remaining elements of L[], if there 38 | # are any 39 | while i < n1: 40 | arr[k] = L[i] 41 | i += 1 42 | k += 1 43 | 44 | # Copy the remaining elements of R[], if there 45 | # are any 46 | while j < n2: 47 | arr[k] = R[j] 48 | j += 1 49 | k += 1 50 | 51 | # l is for left index and r is right index of the 52 | # sub-array of arr to be sorted 53 | 54 | 55 | def mergeSort(arr, l, r): 56 | if l < r: 57 | 58 | # Same as (l+r)//2, but avoids overflow for 59 | # large l and h 60 | m = l+(r-l)//2 61 | 62 | # Sort first and second halves 63 | mergeSort(arr, l, m) 64 | mergeSort(arr, m+1, r) 65 | merge(arr, l, m, r) 66 | 67 | 68 | # Driver code to test above 69 | arr = [12, 11, 13, 5, 6, 7] 70 | n = len(arr) 71 | print("Given array is") 72 | for i in range(n): 73 | print("%d" % arr[i],end=" ") 74 | 75 | mergeSort(arr, 0, n-1) 76 | print("\n\nSorted array is") 77 | for i in range(n): 78 | print("%d" % arr[i],end=" ") 79 | 80 | # This code is contributed by Mohit Kumra 81 | -------------------------------------------------------------------------------- /Algos/Python/miles-to-kms-convertor.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | import ttkbootstrap as ttk 3 | 4 | def convert(): 5 | mile_input = entry_int.get() 6 | km_output = mile_input * 1.61 7 | output_string.set(km_output) 8 | # window 9 | window = ttk.Window(themename = "cyborg") 10 | window.title("Demo") 11 | window.geometry("400x250") 12 | 13 | # title 14 | title_label = tk.Label( 15 | master = window, 16 | text = "Miles to Kilometers", 17 | font = "Calibri 20 bold" 18 | ) 19 | title_label.pack() 20 | 21 | # input 22 | 23 | 24 | input_frame = ttk.Frame( 25 | master = window 26 | ) 27 | 28 | input_label = tk.Label( 29 | master = input_frame, 30 | text = "Enter a value:" 31 | ) 32 | 33 | input_label.pack() 34 | 35 | entry_int = tk.IntVar() 36 | entry = ttk.Entry( 37 | master = input_frame, 38 | textvariable = entry_int 39 | ) 40 | 41 | button = ttk.Button( 42 | master = input_frame, 43 | text = "Convert", 44 | command = convert 45 | ) 46 | 47 | entry.pack(side = "left", padx = 0.5) 48 | button.pack(side = "right", padx = 0.5) 49 | input_frame.pack(pady = 10) 50 | 51 | # output 52 | output_string = tk.StringVar() 53 | output_label = ttk.Label( 54 | master = window, 55 | text = "Output", 56 | font = "Calibri 20", 57 | textvariable = output_string 58 | ) 59 | 60 | output_label.pack(pady = 10) 61 | 62 | # run 63 | window.mainloop() -------------------------------------------------------------------------------- /Algos/Python/power_set.py: -------------------------------------------------------------------------------- 1 | # A py program to find the power set 2 | 3 | from typing import List 4 | 5 | 6 | def powSet( li:List ) : 7 | result = [] 8 | for i in range( 0 , 2**len(li) ): 9 | temp = [] 10 | for j in range( 0 , len(li) ): 11 | if (i & ( 1< 0 : 12 | temp.append( li[j] ) 13 | result.append(temp) 14 | return result 15 | 16 | if __name__ == '__main__': 17 | li=list(input("Enter the elements of the list : \n").split()) 18 | print(powSet(li)) -------------------------------------------------------------------------------- /Algos/Python/prime between 1 and 100.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This is a program to print prime numbers between 1 to 100 3 | 4 | ''' 5 | 6 | def IsPrime(n : int): 7 | for i in range(2,int(n/2)): 8 | if n%i ==0 : 9 | return False 10 | else: 11 | return True 12 | 13 | 14 | for i in range(2,101): 15 | if IsPrime(i) : 16 | print(i, end = ", ") 17 | -------------------------------------------------------------------------------- /Algos/Python/quick_sort.py: -------------------------------------------------------------------------------- 1 | quickSort(arr[], low, high) 2 | { 3 | if (low < high) 4 | { 5 | /* pi is partitioning index, arr[p] is now 6 | at right place */ 7 | pi = partition(arr, low, high); 8 | 9 | quickSort(arr, low, pi - 1); // Before pi 10 | quickSort(arr, pi + 1, high); // After pi 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Algos/Python/selection_sort.py: -------------------------------------------------------------------------------- 1 | def selection_sort(arr): 2 | for i in range(len(arr)): 3 | min_index = i 4 | for j in range(i+1, len(arr)): 5 | if arr[min_index] > arr[j]: 6 | min_index = j 7 | arr[i], arr[min_index] = arr[min_index], arr[i] 8 | #driver code 9 | arr = [64, 25, 12, 22, 11] 10 | selection_sort(arr) 11 | print ("Sorted array") 12 | for i in range(len(arr)): 13 | print("%d" %arr[i]) 14 | -------------------------------------------------------------------------------- /Algos/Python/shell_sort.py: -------------------------------------------------------------------------------- 1 | def shell_sort(arr): 2 | n = len(arr) 3 | gap = n//2 4 | while gap > 0: 5 | for i in range(gap, n): 6 | temp = arr[i] 7 | j = i 8 | while j >= gap and arr[j-gap] > temp: 9 | arr[j] = arr[j-gap] 10 | j -= gap 11 | arr[j] = temp 12 | gap //= 2 13 | #driver code 14 | arr = [12, 34, 54, 2, 3] 15 | shell_sort(arr) 16 | print ("Sorted array is:") 17 | for i in range(len(arr)): 18 | print ("%d" %arr[i]) 19 | -------------------------------------------------------------------------------- /Algos/Python/swap numbers.py: -------------------------------------------------------------------------------- 1 | # Python program to swap two variables 2 | 3 | x = 5 4 | y = 10 5 | 6 | # To take inputs from the user 7 | #x = input('Enter value of x: ') 8 | #y = input('Enter value of y: ') 9 | 10 | # create a temporary variable and swap the values 11 | temp = x 12 | x = y 13 | y = temp 14 | 15 | print('The value of x after swapping: {}'.format(x)) 16 | print('The value of y after swapping: {}'.format(y)) 17 | -------------------------------------------------------------------------------- /Algos/Python/topological_sort.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | #Python program to print topological sorting of a DAG 4 | from collections import defaultdict 5 | 6 | #Class to represent a graph 7 | class Graph: 8 | def __init__(self,vertices): 9 | self.graph = defaultdict(list) #dictionary containing adjacency List 10 | self.V = vertices #No. of vertices 11 | 12 | # function to add an edge to graph 13 | def addEdge(self,u,v): 14 | self.graph[u].append(v) 15 | 16 | # A recursive function used by topologicalSort 17 | def topologicalSortUtil(self,v,visited,stack): 18 | 19 | # Mark the current node as visited. 20 | visited[v] = True 21 | 22 | # Recur for all the vertices adjacent to this vertex 23 | for i in self.graph[v]: 24 | if visited[i] == False: 25 | self.topologicalSortUtil(i,visited,stack) 26 | 27 | # Push current vertex to stack which stores result 28 | stack.insert(0,v) 29 | 30 | # The function to do Topological Sort. It uses recursive 31 | # topologicalSortUtil() 32 | def topologicalSort(self): 33 | # Mark all the vertices as not visited 34 | visited = [False]*self.V 35 | stack =[] 36 | 37 | # Call the recursive helper function to store Topological 38 | # Sort starting from all vertices one by one 39 | for i in range(self.V): 40 | if visited[i] == False: 41 | self.topologicalSortUtil(i,visited,stack) 42 | 43 | # Print contents of stack 44 | print (stack) 45 | 46 | g= Graph(6) 47 | g.addEdge(5, 2); 48 | g.addEdge(5, 0); 49 | g.addEdge(4, 0); 50 | g.addEdge(4, 1); 51 | g.addEdge(2, 3); 52 | g.addEdge(3, 1); 53 | 54 | print ("Following is a Topological Sort of the given graph") 55 | g.topologicalSort() 56 | -------------------------------------------------------------------------------- /Algos/Ruby/Binary.rb: -------------------------------------------------------------------------------- 1 | def add(new_value) 2 | 3 | if @root == nil 4 | @root = Node.new(new_value) 5 | @total_nodes = 1 6 | return 7 | end 8 | 9 | current = @root 10 | while(true) 11 | if new_value <= current.value 12 | if current.right == nil 13 | current.right = Node.new(new_value) 14 | break 15 | else 16 | current = current.right 17 | end 18 | else 19 | if current.left == nil 20 | current.left = Node.new(new_value) 21 | break 22 | else 23 | current = current.left 24 | end 25 | end 26 | end 27 | 28 | @total_nodes += 1 29 | end 30 | -------------------------------------------------------------------------------- /Algos/Ruby/BubbleSort.rb: -------------------------------------------------------------------------------- 1 | def bubbleSort(arr) 2 | n=arr.length 3 | for i in 0...n-1 4 | for j in 0...n-i-1 5 | if arr[j]>arr[j+1] 6 | temp=arr[j] 7 | arr[j]=arr[j+1] 8 | arr[j+1]=temp 9 | end 10 | end 11 | end 12 | return arr 13 | end 14 | 15 | array = [1,4, 6, 11, 6, 2, 78, 32, 88, 21] 16 | sorted = bubbleSort(array) 17 | print(sorted) -------------------------------------------------------------------------------- /Algos/Ruby/Fib.rb: -------------------------------------------------------------------------------- 1 | =begin 2 | Ruby program to print Fibonacci series 3 | without recursion 4 | =end 5 | 6 | first=0 7 | second=1 8 | nextterm=0 9 | 10 | puts "Enter the number of terms:-" 11 | n=gets.chomp.to_i 12 | 13 | puts "The first #{n} terms of Fibonacci series are:-" 14 | c=1 15 | while(c<=n+1) 16 | if(c<=1) 17 | nextterm=c 18 | else 19 | puts nextterm 20 | nextterm=first+second 21 | first=second 22 | second=nextterm 23 | end 24 | c+=1 25 | end 26 | -------------------------------------------------------------------------------- /Algos/Ruby/Palindrome.rb: -------------------------------------------------------------------------------- 1 | def Palindrome(str) 2 | str = str.downcase 3 | i = 0 4 | j = str.size-1 5 | while i < j do 6 | while (i= '0' && str[i] <= '9') || (str[i].ord >= 97 && str[i].ord <= 122))) do 7 | i = i+1 8 | end 9 | while (i= '0' && str[j] <= '9') || (str[j].ord >= 97 && str[j].ord <= 122))) do 10 | j = j-1 11 | end 12 | if str[i] != str[j] 13 | return false 14 | end 15 | i = i+1 16 | j = j-1 17 | end 18 | true 19 | end 20 | 21 | string = 'MADAM' 22 | 23 | check = Palindrome(string) 24 | if check == true 25 | print("Palindrome") 26 | else 27 | print("Not Palindrome") 28 | end -------------------------------------------------------------------------------- /Algos/Ruby/PascalTriangle.rb: -------------------------------------------------------------------------------- 1 | def PascalTriangle(rows) 2 | res = [] 3 | for i in 1..rows do 4 | arr = [] 5 | arr[0] = 1 6 | arr[i-1] = 1 7 | 8 | if i == 1 || i == 2 9 | res << arr 10 | next 11 | end 12 | 13 | for j in 1..i-2 do 14 | arr[j] = res[i-2][j-1] + res[i-2][j] 15 | end 16 | res << arr 17 | end 18 | return res 19 | end 20 | 21 | print PascalTriangle(8) -------------------------------------------------------------------------------- /Algos/Ruby/Reverse.rb: -------------------------------------------------------------------------------- 1 | def Reverse(arr) 2 | b = arr.length-1 3 | start=0 4 | while(startarr[j+1] 6 | temp=arr[j] 7 | arr[j]=arr[j+1] 8 | arr[j+1]=temp 9 | end 10 | end 11 | end 12 | return arr 13 | end 14 | 15 | array = [1,4, 6, 11, 6, 2, 78, 32, 88, 21] 16 | sorted = bubbleSort(array) 17 | print(sorted) 18 | -------------------------------------------------------------------------------- /Algos/Ruby/global variables.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/ruby 2 | 3 | $global_var = "GLOBAL" 4 | class One 5 | def display 6 | puts "Global variable in One is #$global_var" 7 | end 8 | end 9 | class Two 10 | def display 11 | puts "Global variable in Two is #$global_var" 12 | end 13 | end 14 | 15 | oneobj = One.new 16 | oneobj.display 17 | twoobj = Two.new 18 | twoobj.display 19 | -------------------------------------------------------------------------------- /Algos/Ruby/half pyramid .rb: -------------------------------------------------------------------------------- 1 | #include 2 | void main(){ 3 | int n=6,i,j; 4 | for(i=1;i<=n;i++){ 5 | for(j=1;j<=i;j++){ 6 | printf("%d ",i); 7 | } 8 | printf("\n"); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Algos/Ruby/leapyear.rb: -------------------------------------------------------------------------------- 1 | =begin 2 | Ruby program to check whether 3 | the year is leap year or not. 4 | =end 5 | 6 | puts "Enter the year you want to check" 7 | yr = gets.chomp.to_i 8 | 9 | if yr % 400 == 0 10 | puts "#{yr} is a leap year" 11 | elsif yr % 4 == 0 && yr % 100 !=0 12 | puts "#{yr} is a leap year" 13 | else 14 | puts "#{yr} is not a leap year" 15 | end 16 | -------------------------------------------------------------------------------- /Algos/Ruby/mergesort.rb: -------------------------------------------------------------------------------- 1 | class MergeSort 2 | def sort(numbers) 3 | 4 | num_elements = numbers.length 5 | if num_elements <= 1 6 | return numbers 7 | end 8 | 9 | half_of_elements = (num_elements / 2).round 10 | 11 | left = numbers.take(half_of_elements) 12 | right = numbers.drop(half_of_elements) 13 | 14 | sorted_left = sort(left) 15 | sorted_right = sort(right) 16 | 17 | merge(sorted_left, sorted_right) 18 | end 19 | 20 | def merge(left_array, right_array) 21 | if right_array.empty? 22 | return left_array 23 | end 24 | 25 | if left_array.empty? 26 | return right_array 27 | end 28 | 29 | smallest_number = if left_array.first <= right_array.first 30 | left_array.shift 31 | else 32 | right_array.shift 33 | end 34 | 35 | recursive = merge(left_array, right_array) 36 | 37 | [smallest_number].concat(recursive) 38 | end 39 | end 40 | -------------------------------------------------------------------------------- /Algos/Ruby/primeornot.rb: -------------------------------------------------------------------------------- 1 | puts "Enter the number:" 2 | num=gets.chomp.to_i 3 | count=0 4 | if (num==0) 5 | puts "0 is not prime" 6 | else 7 | 8 | i=2 9 | while(i1 18 | puts "#{num} is not a prime number" 19 | else 20 | puts "#{num} is a prime number" 21 | end 22 | -------------------------------------------------------------------------------- /Algos/Ruby/swap numbers using XOR.rb: -------------------------------------------------------------------------------- 1 | # Ruby program to swap two numbers 2 | # using the Bitwise XOR (^) operator 3 | 4 | num1=5 5 | num2=3 6 | 7 | print "Number before swapping:\n" 8 | print "num1: ",num1,"\n" 9 | print "num2: ",num2,"\n" 10 | 11 | num1 = num1 ^ num2 12 | num2 = num1 ^ num2 13 | num1 = num1 ^ num2 14 | 15 | print "\nNumber after swapping:\n" 16 | print "num1: ",num1,"\n" 17 | print "num2: ",num2,"\n" 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 CodeMacrocosm 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | --------------------------------------------------------------------------------