From 1f5533c77fef2706361ec29b1c2bd07c64561322 Mon Sep 17 00:00:00 2001 From: DDullahan Date: Wed, 29 Aug 2018 22:48:13 +0800 Subject: [PATCH 001/277] Added FenwickTree For Range Query --- Range queries/FenwickTree.cpp | 56 +++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Range queries/FenwickTree.cpp diff --git a/Range queries/FenwickTree.cpp b/Range queries/FenwickTree.cpp new file mode 100644 index 000000000..a4d1a02de --- /dev/null +++ b/Range queries/FenwickTree.cpp @@ -0,0 +1,56 @@ +#include +using namespace std; + +/** + * ` lowbit(x) ` aims to find the last 1 in binary of a positive number + * twos complement works good on this + * also using ` x - (x & (x - 1)) ` + */ +#define lowbit(x) (x & (-x) ) + +const int maxn = 1e5 + 7; +int tree[maxn] = {0}, + range; // segement of [1...range], notice it must be less than `maxn` + +void update(int x, int c) { + while(x <= range) { + tree[x] += c; + x += lowbit(x); + } +} +int query(int x) { + int ans = 0; + while(x) { + ans += tree[x]; + x -= lowbit(x); + } + return ans; +} +int query_segement(int l, int r) { + return query(r) - query(l - 1); +} + +int main() { + cin >> range; + for(int i = 1; i <= range; i++) { + int num; + cin >> num; + update(i, num); + } + int q; + cin >> q; + while(q--) { + int op; + cin >> op; + if(op == 0) { + int l, r; + cin >> l >> r; + cout << query_segement(l, r) << endl; + } else { + int x, c; + cin >> x >> c; + update(x, c); + } + } + return 0; +} From c7b69429c1218d9844b4bc9d46c0b83cd666c564 Mon Sep 17 00:00:00 2001 From: Nikhil Arora Date: Tue, 2 Oct 2018 01:05:40 +0530 Subject: [PATCH 002/277] added knight tour to backtracking and longest common string to dynamic --- Backtracking/knight-tour.cpp | 59 +++++++++++++++++ Dynamic Programming/longest_common_string.cpp | 65 +++++++++++++++++++ 2 files changed, 124 insertions(+) create mode 100644 Backtracking/knight-tour.cpp create mode 100644 Dynamic Programming/longest_common_string.cpp diff --git a/Backtracking/knight-tour.cpp b/Backtracking/knight-tour.cpp new file mode 100644 index 000000000..978a2d34b --- /dev/null +++ b/Backtracking/knight-tour.cpp @@ -0,0 +1,59 @@ +#include +# define n 8 +using namespace std; +bool issafe(int x,int y,int sol[n][n]) +{ + return (x=0 && y=0 && sol[x][y]==-1); + +} +bool solve(int x,int y, int mov, int sol[n][n], int xmov[n], int ymov[n]) +{ + int k,xnext,ynext; + + if(mov == n*n) + return true; + + for(k=0;k<8;k++) + { + xnext=x+xmov[k]; + ynext=y+ymov[k]; + + if(issafe(xnext,ynext,sol)) + { + sol[xnext][ynext]=mov; + + if(solve(xnext,ynext,mov+1,sol,xmov,ymov)==true) + return true; + else + sol[xnext][ynext]=-1; + } + } + return false; +} +int main() +{ + //initialize(); + + int sol[n][n]; + int i,j; + for(i=0;i +using namespace std; + +int max(int a,int b) +{ + return (a > b) ? a : b; +} + +int main() +{ + char str1[]="DEFBCD"; + char str2[]="ABDEFJ"; + int i,j,k; + int n=strlen(str1)+1; + int m=strlen(str2)+1; + //cout<ma) + { + ma=a[i][j]; + indi=i; + indj=j; + } + } + } + + cout< Date: Tue, 2 Oct 2018 12:00:43 +0530 Subject: [PATCH 003/277] median search=> --- Search/interpolition.cpp | 251 +++++++++++++++++++++++++++++++++++++++ Search/median_search.cpp | 72 +++++++++++ 2 files changed, 323 insertions(+) create mode 100644 Search/interpolition.cpp create mode 100644 Search/median_search.cpp diff --git a/Search/interpolition.cpp b/Search/interpolition.cpp new file mode 100644 index 000000000..de0cc8faa --- /dev/null +++ b/Search/interpolition.cpp @@ -0,0 +1,251 @@ +#include +#include +#include +#include +using namespace std; +class interpolition +{ + public: + int i,j=0,j1=0,j2=0,j3=0; + vectora; + vectora1; + vectora2; + vectora3; + void input(int n) + { + a[j]=n;j++; + } + void input(double n) + { + a1.push_back(n); + } + void input(char n) + { + a2.push_back(n); + } + void input(string n) + { + a3.push_back(n); + } + void sorting() + { + if(a.size()!=0) + {sort(a.begin(),a.end()); + } + if(a1.size()!=0) + {sort(a1.begin(),a1.end()); + } + if(a2.size()!=0) + {sort(a2.begin(),a2.end()); + } + if(a3.size()!=0) + {sort(a3.begin(),a3.end()); + } + } + int binary(int x) + { + int s=0,l=a.size(),c=0,mid; + do + { + c=0; + mid=(l-s/(a[l]-a[s]))*(x-a[s]); + if(a[mid]==x) + { + return mid; + } + if(a[mid]>x) + { + l=mid-1; + } + if(a[mid]x) + { + l=mid-1; + } + if(a1[mid]x) + { + l=mid-1; + } + if(a2[mid] st1) + { + hi=pos-1; + } + else + { + low=pos+1; + } + } + return -1; + } +}; +int main() +{ + interpolition b; + int ch; + cout<<"what is the datatype of input:-\n1. int\n2. double\n3. char\n4. string"<>ch; + switch(ch) + { + case 1: + { + int n,m; + do + { + cout<<"enter the value to be inserted in array:-"; + cin>>n; + b.input(n); + cout<<"do you want to add more elements? 1. yes 2. no\n"; + cin>>m; + }while(m!=0); + b.sorting(); + int x; + cout<<"enter the value to be searched in array:-"; + cin>>x; + int k=b.binary(x); + if(k==-1) + { + cout<>n; + b.input(n); + cout<<"do you want to add more elements? 1. yes 2. no\n"; + cin>>m; + }while(m!=0); + b.sorting(); + double x; + cout<<"enter the value to be searched in array:-"; + cin>>x; + int k=b.binary(x); + if(k==-1) + { + cout<>n; + b.input(n); + cout<<"do you want to add more elements? 1. yes 2. no\n"; + cin>>m; + }while(m!=0); + b.sorting(); + char x; + cout<<"enter the value to be searched in array:-"; + cin>>x; + int k=b.binary(x); + if(k==-1) + { + cout<>n; + b.input(n); + cout<<"do you want to add more elements? 1. yes 2. no\n"; + cin>>m; + }while(m!=0); + b.sorting(); + string x; + cout<<"enter the value to be searched in array:-"; + cin>>x; + int k=b.binary(x); + if(k==-1) + { + cout< +#include +#include +#include +#include +#include +#include +using namespace std; +vectorv; +vectors1; +vectors2; +vectors3; +template +void comp(X x) +{ + if(s1.size()>=x && s1.size()+s2.size()x) + { + sort(s1.begin(),s1.end()); + cout<x) + { + sort(s3.begin(),s3.end()); + cout<>x; + comp(x-1); + return 0; +} From df74e656a2b5cc327f6423d4c1518a30ea15e2ab Mon Sep 17 00:00:00 2001 From: Piyush Date: Tue, 2 Oct 2018 23:16:58 +0530 Subject: [PATCH 004/277] add: sort technique using vectors --- imp_fun.cpp | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 imp_fun.cpp diff --git a/imp_fun.cpp b/imp_fun.cpp new file mode 100644 index 000000000..e0a70eeda --- /dev/null +++ b/imp_fun.cpp @@ -0,0 +1,45 @@ +// A C++ program to demonstrate working of sort(), +// reverse() +#include +#include +#include +#include //For accumulate operation +using namespace std; + +int main() +{ + // Initializing vector with array values + int arr[] = {10, 20, 5, 23 ,42 , 15}; + int n = sizeof(arr)/sizeof(arr[0]); + vector vect(arr, arr+n); + + cout << "Vector is: "; + for (int i=0; i Date: Mon, 15 Oct 2018 23:04:45 +0530 Subject: [PATCH 005/277] Program for Huffman Coding in C++ --- Greedy Algorithms/huffman.cpp | 108 ++++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 Greedy Algorithms/huffman.cpp diff --git a/Greedy Algorithms/huffman.cpp b/Greedy Algorithms/huffman.cpp new file mode 100644 index 000000000..be3ed4880 --- /dev/null +++ b/Greedy Algorithms/huffman.cpp @@ -0,0 +1,108 @@ +// C++ program for Huffman Coding +#include +using namespace std; + +// A Huffman tree node +struct MinHeapNode { + + // One of the input characters + char data; + + // Frequency of the character + unsigned freq; + + // Left and right child + MinHeapNode *left, *right; + + MinHeapNode(char data, unsigned freq) + + { + + left = right = NULL; + this->data = data; + this->freq = freq; + } +}; + +// For comparison of +// two heap nodes (needed in min heap) +struct compare { + + bool operator()(MinHeapNode* l, MinHeapNode* r) + + { + return (l->freq > r->freq); + } +}; + +// Prints huffman codes from +// the root of Huffman Tree. +void printCodes(struct MinHeapNode* root, string str) +{ + + if (!root) + return; + + if (root->data != '$') + cout << root->data << ": " << str << "\n"; + + printCodes(root->left, str + "0"); + printCodes(root->right, str + "1"); +} + +// The main function that builds a Huffman Tree and +// print codes by traversing the built Huffman Tree +void HuffmanCodes(char data[], int freq[], int size) +{ + struct MinHeapNode *left, *right, *top; + + // Create a min heap & inserts all characters of data[] + priority_queue, compare> minHeap; + + for (int i = 0; i < size; ++i) + minHeap.push(new MinHeapNode(data[i], freq[i])); + + // Iterate while size of heap doesn't become 1 + while (minHeap.size() != 1) { + + // Extract the two minimum + // freq items from min heap + left = minHeap.top(); + minHeap.pop(); + + right = minHeap.top(); + minHeap.pop(); + + // Create a new internal node with + // frequency equal to the sum of the + // two nodes frequencies. Make the + // two extracted node as left and right children + // of this new node. Add this node + // to the min heap '$' is a special value + // for internal nodes, not used + top = new MinHeapNode('$', left->freq + right->freq); + + top->left = left; + top->right = right; + + minHeap.push(top); + } + + // Print Huffman codes using + // the Huffman tree built above + printCodes(minHeap.top(), ""); +} + +// Driver program to test above functions +int main() +{ + + char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; + int freq[] = { 5, 9, 12, 13, 16, 45 }; + + int size = sizeof(arr) / sizeof(arr[0]); + + HuffmanCodes(arr, freq, size); + + return 0; +} From 12a886fae7d8966df7fdeab952a2f2ee02de8cc1 Mon Sep 17 00:00:00 2001 From: "mahbubur.rahman" Date: Fri, 19 Jul 2019 17:52:48 +0900 Subject: [PATCH 006/277] Added knuth pratt morris algorithm for sfinding string match. - Calculate whether the given pattern exist in the given text. - Return true if it finds a match. - Otherwise return false. --- String/knuth_morris_pratt.cpp | 64 +++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 String/knuth_morris_pratt.cpp diff --git a/String/knuth_morris_pratt.cpp b/String/knuth_morris_pratt.cpp new file mode 100644 index 000000000..f6f1169d3 --- /dev/null +++ b/String/knuth_morris_pratt.cpp @@ -0,0 +1,64 @@ +/* + The Knuth-Morris-Pratt Algorithm for finding a pattern within a piece of text + with complexity O(n + m) + 1) Preprocess pattern to identify any suffixes that are identical to prefixes + This tells us where to continue from if we get a mismatch between a character in our pattern + and the text. + 2) Step through the text one character at a time and compare it to a character in the pattern + updating our location within the pattern if necessary +*/ + +#include +#include +#include +using namespace std; +vector getFailureArray(string pattern){ + int pattern_length=pattern.size(); + vectorfailure(pattern_length+1); + failure[0]=-1; + int j=-1; + for(int i=0; ifailure=getFailureArray(pattern); + int k=0; + for(int j=0; j Date: Tue, 30 Jul 2019 22:40:44 +0530 Subject: [PATCH 007/277] added Dynamic Programming Problems --- Dynamic Programming/Coin-Change.cpp | 51 +++++++++++++++ .../Matrix-Chain-Multiplication.cpp | 62 +++++++++++++++++++ 2 files changed, 113 insertions(+) create mode 100644 Dynamic Programming/Coin-Change.cpp create mode 100644 Dynamic Programming/Matrix-Chain-Multiplication.cpp diff --git a/Dynamic Programming/Coin-Change.cpp b/Dynamic Programming/Coin-Change.cpp new file mode 100644 index 000000000..9b8feda3c --- /dev/null +++ b/Dynamic Programming/Coin-Change.cpp @@ -0,0 +1,51 @@ +#include +#include +using namespace std; + +// Function to find the Minimum number of coins required to get Sum S +int findMinCoins(int arr[], int n, int N) +{ + // dp[i] = no of coins required to get a total of i + int dp[N + 1]; + + // 0 coins are needed for 0 sum + + dp[0] = 0; + + + for (int i = 1; i <= N; i++) + { + // initialize minimum number of coins needed to infinity + dp[i] = INT_MAX; + int res = INT_MAX; + + // do for each coin + for (int c = 0; c < n; c++) + { + if (i - arr[c] >= 0) // check if coins doesn't become negative by including it + res = dp[i - arr[c]]; + + // if total can be reached by including current coin c, + // update minimum number of coins needed dp[i] + if (res != INT_MAX) + dp[i] = min(dp[i], res + 1); + } + } + + // The Minimum No of Coins Required for N = dp[N] + return dp[N]; +} + +int main() +{ + // No of Coins We Have + int arr[] = { 1, 2, 3, 4 }; + int n = sizeof(arr) / sizeof(arr[0]); + + // Total Change Required + int N = 15; + + cout << "Minimum Number of Coins Required "<< findMinCoins(arr, n, N) << "\n"; + + return 0; +} \ No newline at end of file diff --git a/Dynamic Programming/Matrix-Chain-Multiplication.cpp b/Dynamic Programming/Matrix-Chain-Multiplication.cpp new file mode 100644 index 000000000..e1e3f12e0 --- /dev/null +++ b/Dynamic Programming/Matrix-Chain-Multiplication.cpp @@ -0,0 +1,62 @@ +#include +#include +using namespace std; + +#define MAX 10 + +// dp table to store the solution for already computed sub problems +int dp[MAX][MAX]; + +// Function to find the most efficient way to multiply the given sequence of matrices +int MatrixChainMultiplication(int dim[], int i, int j) +{ + // base case: one matrix + if (j <= i + 1) + return 0; + + // stores minimum number of scalar multiplications (i.e., cost) + // needed to compute the matrix M[i+1]...M[j] = M[i..j] + int min = INT_MAX; + + // if dp[i][j] is not calculated (calculate it!!) + + if (dp[i][j] == 0) + { + // take the minimum over each possible position at which the + // sequence of matrices can be split + + for (int k = i + 1; k <= j - 1; k++) + { + // recur for M[i+1]..M[k] to get a i x k matrix + int cost = MatrixChainMultiplication(dim, i, k); + + // recur for M[k+1]..M[j] to get a k x j matrix + cost += MatrixChainMultiplication(dim, k, j); + + // cost to multiply two (i x k) and (k x j) matrix + cost += dim[i] * dim[k] * dim[j]; + + if (cost < min) + min = cost; // store the minimum cost + } + dp[i][j] = min; + } + + // return min cost to multiply M[j+1]..M[j] + return dp[i][j]; +} + +// main function +int main() +{ + // Matrix i has Dimensions dim[i-1] & dim[i] for i=1..n + // input is 10 x 30 matrix, 30 x 5 matrix, 5 x 60 matrix + int dim[] = { 10, 30, 5, 60 }; + int n = sizeof(dim) / sizeof(dim[0]); + + // Function Calling: MatrixChainMultiplications(dimensions_array, starting, ending); + + cout << "Minimum cost is " << MatrixChainMultiplication(dim, 0, n - 1) << "\n"; + + return 0; +} \ No newline at end of file From 5db2683566f0385c7e579e0e1f1579b8e1aa7965 Mon Sep 17 00:00:00 2001 From: Khavin Shankar Date: Wed, 7 Aug 2019 07:04:58 +0530 Subject: [PATCH 008/277] Update Linked List.cpp --- Data Structure/Linked List.cpp | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/Data Structure/Linked List.cpp b/Data Structure/Linked List.cpp index 5abebd584..b0da4a3b6 100644 --- a/Data Structure/Linked List.cpp +++ b/Data Structure/Linked List.cpp @@ -92,6 +92,20 @@ void show() } +void reverse(){ + node* first = start; + node* second = first->next; + while(second != NULL){ + node* tem = second->next; + second->next = first; + first = second; + second = tem; + } + + start->next = NULL; + start = first; +} + int main() { int choice, x; @@ -101,9 +115,10 @@ int main() cout<<"\n2. Delete"; cout<<"\n3. Search"; cout<<"\n4. Print"; + cout<<"\n5. Reverse"; cout<<"\n0. Exit"; cout<<"\n\nEnter you choice : "; - cin>>choice; + cin>>choice; switch (choice) { case 1 : cout<<"\nEnter the element to be inserted : "; @@ -115,8 +130,11 @@ int main() case 3 : cout<<"\nEnter the element to be searched : "; cin>>x; search(x); break; - case 4 : show(); - cout<<"\n"; break; + case 4 : show(); + cout<<"\n"; break; + case 5 : cout<<"The reversed list: \n"; + reverse(); show(); + cout<<"\n"; break; } } while(choice!=0); From 3631f6570e9e81e4736d39ab3b97ee50d95bb901 Mon Sep 17 00:00:00 2001 From: Omkar Kolate <53403067+omkarkolate@users.noreply.github.com> Date: Thu, 15 Aug 2019 16:10:59 +0530 Subject: [PATCH 009/277] Update in Deque() fuction Because of earlier logic not going to deque the last element of the queue because at the last front == rear as per your logic which directly results in "Underflow". --- Data Structure/Queue Using Linked List.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Data Structure/Queue Using Linked List.cpp b/Data Structure/Queue Using Linked List.cpp index acf32ebd5..763534f83 100644 --- a/Data Structure/Queue Using Linked List.cpp +++ b/Data Structure/Queue Using Linked List.cpp @@ -35,7 +35,7 @@ void Enque(int x) void Deque() { - if (rear==front) + if (rear == NULL && front == NULL) { cout<<"\nUnderflow"; } @@ -45,6 +45,8 @@ void Deque() cout<<"\n"<val<<" deleted"; front=front->next; delete t; + if(front == NULL) + rear = NULL; } } From abc0d365dea654aecc5fbddd5d2b1833ab989722 Mon Sep 17 00:00:00 2001 From: Yang Libin Date: Wed, 21 Aug 2019 09:17:20 +0800 Subject: [PATCH 010/277] Update Queue Using Linked List.cpp --- Data Structure/Queue Using Linked List.cpp | 129 ++++++++++----------- 1 file changed, 63 insertions(+), 66 deletions(-) diff --git a/Data Structure/Queue Using Linked List.cpp b/Data Structure/Queue Using Linked List.cpp index 763534f83..39d7a9ae3 100644 --- a/Data Structure/Queue Using Linked List.cpp +++ b/Data Structure/Queue Using Linked List.cpp @@ -1,92 +1,89 @@ -#include +#include using namespace std; struct node { - int val; - node *next; + int val; + node *next; }; - node *front, *rear; - void Enque(int x) { - if (rear==NULL) - { - node *n= new node; - n->val=x; - n->next=NULL; - rear=n; - front=n; - } + if (rear == NULL) + { + node *n = new node; + n->val = x; + n->next = NULL; + rear = n; + front = n; + } - else - { + else + { - node *n = new node; - n->val=x; - n->next=NULL; - rear->next=n; - rear=n; - } + node *n = new node; + n->val = x; + n->next = NULL; + rear->next = n; + rear = n; + } } void Deque() { - if (rear == NULL && front == NULL) - { - cout<<"\nUnderflow"; - } - else - { - node *t = front; - cout<<"\n"<val<<" deleted"; - front=front->next; - delete t; - if(front == NULL) - rear = NULL; - } + if (rear == NULL && front == NULL) + { + cout << "\nUnderflow"; + } + else + { + node *t = front; + cout << "\n" + << t->val << " deleted"; + front = front->next; + delete t; + if (front == NULL) + rear = NULL; + } } void show() { - node *t=front; - while(t!=NULL) - { - cout<val<<"\t"; - t=t->next; - } + node *t = front; + while (t != NULL) + { + cout << t->val << "\t"; + t = t->next; + } } int main() { - int ch, x; - do - { - cout<<"\n1. Enque"; - cout<<"\n2. Deque"; - cout<<"\n3. Print"; - cout<<"\nEnter Your Choice : "; - cin>>ch; - if (ch==1) - { - cout<<"\nInsert : "; - cin>>x; - Enque(x); - } - else if (ch==2) - { - Deque(); - } - else if (ch==3) - { - show(); - } - } - while(ch!=0); + int ch, x; + do + { + cout << "\n1. Enque"; + cout << "\n2. Deque"; + cout << "\n3. Print"; + cout << "\nEnter Your Choice : "; + cin >> ch; + if (ch == 1) + { + cout << "\nInsert : "; + cin >> x; + Enque(x); + } + else if (ch == 2) + { + Deque(); + } + else if (ch == 3) + { + show(); + } + } while (ch != 0); - return 0; + return 0; } - From 69ddc9fc527c9e955356235276e027ff9c55f514 Mon Sep 17 00:00:00 2001 From: yanglbme Date: Wed, 21 Aug 2019 10:10:08 +0800 Subject: [PATCH 011/277] style: format code --- Backtracking/Graph Coloring.cpp | 46 +-- Backtracking/N Queens.cpp | 55 ++- Backtracking/Rat_maze.cpp | 49 ++- Backtracking/sudoku_solve.cpp | 111 +++--- .../Bisection_method.CPP | 46 +-- .../Gaussian_elimination.cpp | 56 ++-- .../Newton_Raphson.CPP | 46 +-- .../Secant_method.CPP | 48 +-- .../false-position.CPP | 46 +-- .../successive_approximation.CPP | 36 +- Data Structure/AVLtree.cpp | 113 ++++--- Data Structure/Binary Search Tree.cpp | 192 +++++------ Data Structure/Binaryheap.cpp | 317 +++++++++--------- Data Structure/Doubly Linked List.cpp | 129 +++---- Data Structure/Linked List.cpp | 162 +++++---- Data Structure/List Array.cpp | 157 ++++----- Data Structure/MorrisInorder.cpp | 66 ++-- Data Structure/Queue Using Array.cpp | 55 ++- Data Structure/Stack Using Array.cpp | 59 ++-- Data Structure/Stack Using Linked List.cpp | 50 ++- Data Structure/Tree.cpp | 139 ++++---- Data Structure/TrieTree.cpp | 18 +- .../circular_Queue_using_Linked_List.cpp | 56 ++-- .../linkedList_implentation_usingArray.cpp | 127 ++++--- Dynamic Programming/0-1 Knapsack.cpp | 41 +-- Dynamic Programming/Armstrong Number.cpp | 26 +- Dynamic Programming/Bellman-Ford.cpp | 114 ++++--- Dynamic Programming/Catalan-Numbers.cpp | 38 +-- Dynamic Programming/Coin-Change.cpp | 13 +- Dynamic Programming/Cut Rod.cpp | 21 +- Dynamic Programming/Edit Distance.cpp | 73 ++-- Dynamic Programming/Egg-Dropping-Puzzle.cpp | 33 +- Dynamic Programming/Fibonacci_Bottom_Up.cpp | 21 +- Dynamic Programming/Fibonacci_Top_Down.cpp | 18 +- Dynamic Programming/Floyd-Warshall.cpp | 132 ++++---- .../Longest Common Subsequence.cpp | 57 ++-- .../Longest Increasing Subsequence.cpp | 17 +- .../Matrix-Chain-Multiplication.cpp | 6 +- Graph/BFS.cpp | 67 ++-- Graph/DFS.cpp | 30 +- Graph/DFS_with_stack.cc | 44 +-- Graph/Dijkstra.cpp | 54 +-- Graph/Kruskal.cpp | 115 +++++-- Graph/Topological-Sort.cpp | 35 +- Greedy Algorithms/Dijkstra.cpp | 65 ++-- Greedy Algorithms/Knapsack.cpp | 101 +++--- .../Kruskals Minimum Spanning Tree.cpp | 19 +- .../Prims Minimum Spanning Tree.cpp | 39 +-- Hashing/Chaining.cpp | 171 +++++----- Math/Power_For_Huge_Num/Power_Huge.cpp | 21 +- .../primefactorization.cpp | 35 +- Math/sieve_of_Eratosthenes.cpp | 30 +- .../Array Left Rotation.cpp | 50 +-- .../Array Right Rotation.cpp | 56 ++-- .../Circular Linked List.cpp | 109 +++--- .../Circular Queue Using Array.cpp | 57 ++-- .../Intersection_of_2_arrays.cpp | 31 +- .../Reverse a Linked List using Recusion.cpp | 48 ++- .../Union_of_2_arrays.cpp | 47 +-- .../selectionSortLinkedList.cpp | 97 +++--- Others/Buzz_number.cpp | 14 +- Others/Decimal To Binary.cpp | 13 +- Others/Decimal To Hexadecimal .cpp | 22 +- Others/Decimal to Roman Numeral.cpp | 101 ++++-- Others/GCD_of_n_numbers.cpp | 18 +- Others/Happy_number.cpp | 25 +- Others/Palindromeofnumber.cpp | 8 +- Others/Paranthesis Matching.cpp | 81 +++-- Others/Primality Test.cpp | 59 ++-- Others/Sparse matrix.cpp | 26 +- Others/Strassen Matrix Multiplication.cpp | 54 ++- Others/String Fibonacci.cpp | 4 +- Others/Tower of Hanoi.cpp | 61 ++-- Others/fibonacci.cpp | 29 +- Others/sieve_of_Eratosthenes.cpp | 20 +- Others/smallest-circle.cpp | 42 +-- Others/spiral_print.cpp | 66 ++-- Range queries/MO.cpp | 70 ++-- Range queries/segTree.cpp | 105 +++--- Search/Binary Search.cpp | 38 ++- Search/Linear Search.cpp | 29 +- Search/searching.cpp | 31 +- Search/ternary_search.cpp | 110 +++--- Sorting/BitonicSort.cpp | 118 +++---- Sorting/Bubble Sort.cpp | 39 +-- Sorting/CocktailSelectionSort.cpp | 139 ++++---- Sorting/CountingSortString.cpp | 69 ++-- Sorting/Counting_Sort.cpp | 65 ++-- Sorting/Insertion Sort.cpp | 45 ++- Sorting/Merge Sort.cpp | 52 ++- Sorting/NumericStringSort.cpp | 78 +++-- Sorting/OddEven Sort.cpp | 19 +- Sorting/Quick Sort.cpp | 54 ++- Sorting/Radix Sort.cpp | 50 +-- Sorting/Selection Sort.cpp | 36 +- Sorting/Shell Sort.cpp | 30 +- Sorting/Slow Sort.cpp | 60 ++-- Sorting/bucketSort.cpp | 58 ++-- Sorting/combsort.cpp | 30 +- sleep sort.c | 41 --- ternary_search.cpp | 19 -- 101 files changed, 3154 insertions(+), 2984 deletions(-) delete mode 100644 sleep sort.c delete mode 100644 ternary_search.cpp diff --git a/Backtracking/Graph Coloring.cpp b/Backtracking/Graph Coloring.cpp index fdf50b288..cadc6d5ec 100644 --- a/Backtracking/Graph Coloring.cpp +++ b/Backtracking/Graph Coloring.cpp @@ -1,48 +1,47 @@ -#include - +#include + // Number of vertices in the graph #define V 4 - + void printSolution(int color[]); - + /* A utility function to check if the current color assignment is safe for vertex v */ -bool isSafe (int v, bool graph[V][V], int color[], int c) +bool isSafe(int v, bool graph[V][V], int color[], int c) { for (int i = 0; i < V; i++) if (graph[v][i] && c == color[i]) return false; return true; } - + /* A recursive utility function to solve m coloring problem */ void graphColoring(bool graph[V][V], int m, int color[], int v) { /* base case: If all vertices are assigned a color then return true */ - if (v == V){ - printSolution(color); + if (v == V) + { + printSolution(color); return; } - + /* Consider this vertex v and try different colors */ for (int c = 1; c <= m; c++) { /* Check if assignment of color c to v is fine*/ if (isSafe(v, graph, color, c)) { - color[v] = c; - - /* recur to assign colors to rest of the vertices */ - graphColoring (graph, m, color, v+1); - - + color[v] = c; + + /* recur to assign colors to rest of the vertices */ + graphColoring(graph, m, color, v + 1); + /* If assigning color c doesn't lead to a solution then remove it */ - color[v] = 0; + color[v] = 0; } } - } /* A utility function to print solution */ @@ -50,10 +49,10 @@ void printSolution(int color[]) { printf(" Following are the assigned colors \n"); for (int i = 0; i < V; i++) - printf(" %d ", color[i]); + printf(" %d ", color[i]); printf("\n"); } - + // driver program to test above function int main() { @@ -64,18 +63,19 @@ int main() | / | (0)---(1) */ - bool graph[V][V] = {{0, 1, 1, 1}, + bool graph[V][V] = { + {0, 1, 1, 1}, {1, 0, 1, 0}, {1, 1, 0, 1}, {1, 0, 1, 0}, }; int m = 3; // Number of colors - int color[V]; + int color[V]; - for (int i = 0; i < V; i++) + for (int i = 0; i < V; i++) color[i] = 0; - + graphColoring(graph, m, color, 0); return 0; } diff --git a/Backtracking/N Queens.cpp b/Backtracking/N Queens.cpp index f070c5803..472aaa2fe 100644 --- a/Backtracking/N Queens.cpp +++ b/Backtracking/N Queens.cpp @@ -1,82 +1,77 @@ -#include +#include #define N 4 using namespace std; void printSolution(int board[N][N]) { - cout<<"\n"; + cout << "\n"; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) - cout<<""<=0 && j>=0; i--, j--) + for (i = row, j = col; i >= 0 && j >= 0; i--, j--) if (board[i][j]) return false; - + /* Check lower diagonal on left side */ - for (i=row, j=col; j>=0 && i= 0 && i < N; i++, j--) if (board[i][j]) return false; - + return true; } - void solveNQ(int board[N][N], int col) { - - if (col >= N){ + + if (col >= N) + { printSolution(board); return; } - + /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { /* Check if queen can be placed on board[i][col] */ - if ( isSafe(board, i, col) ) + if (isSafe(board, i, col)) { /* Place this queen in board[i][col] */ -// cout<<"\n"< +#include using namespace std; ///N=9; -int n=9; +int n = 9; - -bool isPossible(int mat[][9],int i,int j,int no){ +bool isPossible(int mat[][9], int i, int j, int no) +{ ///Row or col nahin hona chahiye - for(int x=0;x -#include -#include +#include +#include +#include float eq(float i) { - return (pow(i,3)-(4*i)-9); // original equation + return (pow(i, 3) - (4 * i) - 9); // original equation } void main() { - float a,b,x,z; + float a, b, x, z; clrscr(); - for(int i=0;i<100;i++) + for (int i = 0; i < 100; i++) { - z=eq(i); - if(z>=0) + z = eq(i); + if (z >= 0) { - b=i; - a=--i; + b = i; + a = --i; goto START; } } - START: +START: - cout<<"\nFirst initial: "< 0 && z<0.0009) // stoping criteria + if (z > 0 && z < 0.0009) // stoping criteria { goto END; } } - END: - cout<<"\n\nRoot: "< +#include using namespace std; int main() { - int mat_size,i,j,step; + int mat_size, i, j, step; - cout<<"Matrix size: "; - cin>>mat_size; + cout << "Matrix size: "; + cin >> mat_size; - double mat[mat_size+1][mat_size+1], x[mat_size][mat_size+1]; + double mat[mat_size + 1][mat_size + 1], x[mat_size][mat_size + 1]; - cout<>mat[i][j]; //Enter (mat_size*mat_size) value of the matrix. + cin >> mat[i][j]; //Enter (mat_size*mat_size) value of the matrix. } } - for(step=0;step=0;i--) + cout << endl + << "Value of the Gaussian Elimination method: " << endl; + for (i = mat_size - 1; i >= 0; i--) { double sum = 0; - for(j=mat_size-1;j>i;j--) + for (j = mat_size - 1; j > i; j--) { x[i][j] = x[j][j] * x[i][j]; sum = x[i][j] + sum; } - if(x[i][i]==0) + if (x[i][i] == 0) x[i][i] = 0; else - x[i][i] = (x[i][mat_size] - sum)/(x[i][i]); + x[i][i] = (x[i][mat_size] - sum) / (x[i][i]); - cout<<"x"< 0 && m<0.009) // stoping criteria + if (m > 0 && m < 0.009) // stoping criteria { goto END; } } - END: - cout<<"\n\nRoot: "< -#include -#include +#include +#include +#include float eq(float i) { - return (pow(i,3)-(4*i)-9); // original equation + return (pow(i, 3) - (4 * i) - 9); // original equation } void main() { - float a,b,z,c,m,n; + float a, b, z, c, m, n; clrscr(); - for(int i=0;i<100;i++) + for (int i = 0; i < 100; i++) { - z=eq(i); - if(z>=0) + z = eq(i); + if (z >= 0) { - b=i; - a=--i; + b = i; + a = --i; goto START; } } - START: +START: - cout<<"\nFirst initial: "< 0 && z<0.09) // stoping criteria + z = eq(c); + if (z > 0 && z < 0.09) // stoping criteria { goto END; } } - END: - cout<<"\n\nRoot: "< -#include -#include +#include +#include +#include float eq(float i) { - return (pow(i,3)-(4*i)-9); // origial equation + return (pow(i, 3) - (4 * i) - 9); // origial equation } void main() { - float a,b,z,c,m,n; + float a, b, z, c, m, n; clrscr(); - for(int i=0;i<100;i++) + for (int i = 0; i < 100; i++) { - z=eq(i); - if(z>=0) + z = eq(i); + if (z >= 0) { - b=i; - a=--i; + b = i; + a = --i; goto START; } } - START: +START: - cout<<"\nFirst initial: "< 0 && z<0.09) // stoping criteria + z = eq(c); + if (z > 0 && z < 0.09) // stoping criteria { goto END; } } - END: - cout<<"\n\nRoot: "< -#include -#include +#include +#include +#include float eq(float y) { - return((3*y)-(cos(y))-2); + return ((3 * y) - (cos(y)) - 2); } float eqd(float y) { - return((0.5)*((cos(y))+2)); + return ((0.5) * ((cos(y)) + 2)); } void main() { - float y,x1,x2,x3,sum,s,a,f1,f2,gd; - int i,n; + float y, x1, x2, x3, sum, s, a, f1, f2, gd; + int i, n; clrscr(); - for(i=0;i<10;i++) + for (i = 0; i < 10; i++) { - sum=eq(y); - cout<<"value of equation at "<"; - cin>>x1; - cout<<"enter the no iteration to perform->\n"; - cin>>n; + cout << "enter the x1->"; + cin >> x1; + cout << "enter the no iteration to perform->\n"; + cin >> n; - for(i=0;i<=n;i++) + for (i = 0; i <= n; i++) { - x2=eqd(x1); - cout<<"\nenter the x2->"<" << x2; + x1 = x2; } getch(); } \ No newline at end of file diff --git a/Data Structure/AVLtree.cpp b/Data Structure/AVLtree.cpp index a3cd52919..db6b9e0d4 100644 --- a/Data Structure/AVLtree.cpp +++ b/Data Structure/AVLtree.cpp @@ -3,20 +3,23 @@ using namespace std; -typedef struct node { +typedef struct node +{ int data; int height; - struct node* left; - struct node* right; -}node; + struct node *left; + struct node *right; +} node; -int max(int a, int b) { +int max(int a, int b) +{ return a > b ? a : b; } // Returns a new Node -node* createNode(int data) { +node *createNode(int data) +{ node *nn = new node(); nn->data = data; nn->height = 0; @@ -27,21 +30,24 @@ node* createNode(int data) { // Returns height of tree -int height(node *root) { - if(root==NULL) +int height(node *root) +{ + if (root == NULL) return 0; return 1 + max(height(root->left), height(root->right)); } // Returns difference between height of left and right subtree -int getBalance(node *root) { +int getBalance(node *root) +{ return height(root->left) - height(root->right); } // Returns Node after Right Rotation -node* rightRotate(node *root) { +node *rightRotate(node *root) +{ node *t = root->left; node *u = t->right; t->right = root; @@ -51,7 +57,8 @@ node* rightRotate(node *root) { // Returns Node after Left Rotation -node* leftRotate(node *root) { +node *leftRotate(node *root) +{ node *t = root->right; node *u = t->left; t->left = root; @@ -61,57 +68,65 @@ node* leftRotate(node *root) { // Returns node with minimum value in the tree -node* minValue(node* root) { - if(root->left==NULL) +node *minValue(node *root) +{ + if (root->left == NULL) return root; return minValue(root->left); } // Balanced Insertion -node* insert(node* root, int item) { +node *insert(node *root, int item) +{ node *nn = createNode(item); - if(root == NULL) + if (root == NULL) return nn; - if(itemdata) + if (item < root->data) root->left = insert(root->left, item); else root->right = insert(root->right, item); int b = getBalance(root); - if(b>1) { - if(getBalance(root->left)<0) - root->left = leftRotate(root->left); // Left-Right Case - return rightRotate(root); // Left-Left Case + if (b > 1) + { + if (getBalance(root->left) < 0) + root->left = leftRotate(root->left); // Left-Right Case + return rightRotate(root); // Left-Left Case } - else if(b<-1) { - if(getBalance(root->right)>0) - root->right = rightRotate(root->right); // Right-Left Case - return leftRotate(root); // Right-Right Case + else if (b < -1) + { + if (getBalance(root->right) > 0) + root->right = rightRotate(root->right); // Right-Left Case + return leftRotate(root); // Right-Right Case } return root; } // Balanced Deletion -node* deleteNode(node *root, int key) { - if(root == NULL) +node *deleteNode(node *root, int key) +{ + if (root == NULL) return root; - if(key < root->data) + if (key < root->data) root->left = deleteNode(root->left, key); - else if(key > root->data) + else if (key > root->data) root->right = deleteNode(root->right, key); - else { + else + { // Node to be deleted is leaf node or have only one Child - if(!root->right) { - node* temp = root->left; - delete(root); + if (!root->right) + { + node *temp = root->left; + delete (root); root = NULL; return temp; } - else if(!root->left) { - node* temp = root->right; - delete(root); + else if (!root->left) + { + node *temp = root->right; + delete (root); root = NULL; return temp; } @@ -124,36 +139,38 @@ node* deleteNode(node *root, int key) { return root; } - // LevelOrder (Breadth First Search) -void levelOrder(node* root) { - queue q; +void levelOrder(node *root) +{ + queue q; q.push(root); - while(!q.empty()) { + while (!q.empty()) + { root = q.front(); - cout<data<<" "; + cout << root->data << " "; q.pop(); - if(root->left) + if (root->left) q.push(root->left); - if(root->right) + if (root->right) q.push(root->right); } } -int main() { +int main() +{ // Testing AVL Tree node *root = NULL; int i; - for(i = 1 ; i <= 7 ; i++) + for (i = 1; i <= 7; i++) root = insert(root, i); - cout<<"LevelOrder: "; + cout << "LevelOrder: "; levelOrder(root); root = deleteNode(root, 1); // Deleting key with value 1 - cout<<"\nLevelOrder: "; + cout << "\nLevelOrder: "; levelOrder(root); - root = deleteNode(root, 4); // Deletin key with value 4 - cout<<"\nLevelOrder: "; + root = deleteNode(root, 4); // Deletin key with value 4 + cout << "\nLevelOrder: "; levelOrder(root); return 0; } diff --git a/Data Structure/Binary Search Tree.cpp b/Data Structure/Binary Search Tree.cpp index 5b83263bc..32a65517c 100644 --- a/Data Structure/Binary Search Tree.cpp +++ b/Data Structure/Binary Search Tree.cpp @@ -1,7 +1,6 @@ -#include +#include using namespace std; - struct node { int val; @@ -18,30 +17,27 @@ struct queue queue q; - void enqueue(node *n) { - q.t[q.rear++]=n; + q.t[q.rear++] = n; } -node * dequeue() +node *dequeue() { return (q.t[q.front++]); } - - void Insert(node *n, int x) { - if (xval) + if (x < n->val) { - if (n->left==NULL) + if (n->left == NULL) { - node *temp=new node; - temp->val=x; - temp->left=NULL; - temp->right=NULL; - n->left=temp; + node *temp = new node; + temp->val = x; + temp->left = NULL; + temp->right = NULL; + n->left = temp; } else { @@ -50,13 +46,13 @@ void Insert(node *n, int x) } else { - if (n->right==NULL) + if (n->right == NULL) { - node *temp=new node; - temp->val=x; - temp->left=NULL; - temp->right=NULL; - n->left=temp; + node *temp = new node; + temp->val = x; + temp->left = NULL; + temp->right = NULL; + n->left = temp; } else { @@ -65,63 +61,60 @@ void Insert(node *n, int x) } } - - - int findMaxInLeftST(node *n) { - while(n->right!=NULL) + while (n->right != NULL) { - n=n->right; + n = n->right; } return n->val; } void Remove(node *p, node *n, int x) { - if (n->val==x) + if (n->val == x) { - if (n->right==NULL && n->left==NULL) + if (n->right == NULL && n->left == NULL) { - if (xval) + if (x < p->val) { - p->right=NULL; + p->right = NULL; } else { - p->left=NULL; - } - } - else if (n->right==NULL) - { - if (xval) - { - p->right=n->left; - } - else - { - p->left=n->left; + p->left = NULL; } } - else if (n->left==NULL) + else if (n->right == NULL) { - if (xval) + if (x < p->val) { - p->right=n->right; + p->right = n->left; } else { - p->left=n->right; + p->left = n->left; + } + } + else if (n->left == NULL) + { + if (x < p->val) + { + p->right = n->right; + } + else + { + p->left = n->right; } } else { - int y=findMaxInLeftST(n->left); - n->val=y; + int y = findMaxInLeftST(n->left); + n->val = y; Remove(n, n->right, y); } } - else if (xval) + else if (x < n->val) { Remove(n, n->left, x); } @@ -131,14 +124,11 @@ void Remove(node *p, node *n, int x) } } - - - void BFT(node *n) { - if(n!=NULL) + if (n != NULL) { - cout<val<<" "; + cout << n->val << " "; enqueue(n->left); enqueue(n->right); BFT(dequeue()); @@ -147,9 +137,9 @@ void BFT(node *n) void Pre(node *n) { - if (n!=NULL) + if (n != NULL) { - cout<val<<" "; + cout << n->val << " "; Pre(n->left); Pre(n->right); } @@ -157,76 +147,72 @@ void Pre(node *n) void In(node *n) { - if (n!=NULL) + if (n != NULL) { In(n->left); - cout<val<<" "; + cout << n->val << " "; In(n->right); } } - void Post(node *n) { - if (n!=NULL) + if (n != NULL) { Post(n->left); Post(n->right); - cout<val<<" "; + cout << n->val << " "; } } - - int main() { - q.front=0; - q.rear=0; + q.front = 0; + q.rear = 0; int value; int ch; - node *root=new node; - cout<<"\nEnter the value of root node :"; - cin>>value; - root->val=value; - root->left=NULL; - root->right=NULL; + node *root = new node; + cout << "\nEnter the value of root node :"; + cin >> value; + root->val = value; + root->left = NULL; + root->right = NULL; do { - cout<<"\n1. Insert"; - cout<<"\n2. Delete"; - cout<<"\n3. Breadth First"; - cout<<"\n4. Preorder Depth First"; - cout<<"\n5. Inorder Depth First"; - cout<<"\n6. Postorder Depth First"; + cout << "\n1. Insert"; + cout << "\n2. Delete"; + cout << "\n3. Breadth First"; + cout << "\n4. Preorder Depth First"; + cout << "\n5. Inorder Depth First"; + cout << "\n6. Postorder Depth First"; - cout<<"\nEnter Your Choice : "; - cin>>ch; + cout << "\nEnter Your Choice : "; + cin >> ch; int x; - switch(ch) + switch (ch) { - case 1: - cout<<"\nEnter the value to be Inserted : "; - cin>>x; - Insert(root, x); - break; - case 2: - cout<<"\nEnter the value to be Deleted : "; - cin>>x; - Remove(root, root, x); - break; - case 3: - BFT(root); - break; - case 4: - Pre(root); - break; - case 5: - In(root); - break; - case 6: - Post(root); - break; + case 1: + cout << "\nEnter the value to be Inserted : "; + cin >> x; + Insert(root, x); + break; + case 2: + cout << "\nEnter the value to be Deleted : "; + cin >> x; + Remove(root, root, x); + break; + case 3: + BFT(root); + break; + case 4: + Pre(root); + break; + case 5: + In(root); + break; + case 6: + Post(root); + break; } - } - while(ch!=0); + } while (ch != 0); } diff --git a/Data Structure/Binaryheap.cpp b/Data Structure/Binaryheap.cpp index 92bcb275a..31129a823 100644 --- a/Data Structure/Binaryheap.cpp +++ b/Data Structure/Binaryheap.cpp @@ -1,159 +1,158 @@ -// A C++ program to demonstrate common Binary Heap Operations -#include -#include -using namespace std; - -// Prototype of a utility function to swap two integers -void swap(int *x, int *y); - -// A class for Min Heap -class MinHeap -{ - int *harr; // pointer to array of elements in heap - int capacity; // maximum possible size of min heap - int heap_size; // Current number of elements in min heap -public: - // Constructor - MinHeap(int capacity); - - // to heapify a subtree with the root at given index - void MinHeapify(int ); - - int parent(int i) { return (i-1)/2; } - - // to get index of left child of node at index i - int left(int i) { return (2*i + 1); } - - // to get index of right child of node at index i - int right(int i) { return (2*i + 2); } - - // to extract the root which is the minimum element - int extractMin(); - - // Decreases key value of key at index i to new_val - void decreaseKey(int i, int new_val); - - // Returns the minimum key (key at root) from min heap - int getMin() { return harr[0]; } - - // Deletes a key stored at index i - void deleteKey(int i); - - // Inserts a new key 'k' - void insertKey(int k); -}; - -// Constructor: Builds a heap from a given array a[] of given size -MinHeap::MinHeap(int cap) -{ - heap_size = 0; - capacity = cap; - harr = new int[cap]; -} - -// Inserts a new key 'k' -void MinHeap::insertKey(int k) -{ - if (heap_size == capacity) - { - cout << "\nOverflow: Could not insertKey\n"; - return; - } - - // First insert the new key at the end - heap_size++; - int i = heap_size - 1; - harr[i] = k; - - // Fix the min heap property if it is violated - while (i != 0 && harr[parent(i)] > harr[i]) - { - swap(&harr[i], &harr[parent(i)]); - i = parent(i); - } -} - -// Decreases value of key at index 'i' to new_val. It is assumed that -// new_val is smaller than harr[i]. -void MinHeap::decreaseKey(int i, int new_val) -{ - harr[i] = new_val; - while (i != 0 && harr[parent(i)] > harr[i]) - { - swap(&harr[i], &harr[parent(i)]); - i = parent(i); - } -} - -// Method to remove minimum element (or root) from min heap -int MinHeap::extractMin() -{ - if (heap_size <= 0) - return INT_MAX; - if (heap_size == 1) - { - heap_size--; - return harr[0]; - } - - // Store the minimum value, and remove it from heap - int root = harr[0]; - harr[0] = harr[heap_size-1]; - heap_size--; - MinHeapify(0); - - return root; -} - - -// This function deletes key at index i. It first reduced value to minus -// infinite, then calls extractMin() -void MinHeap::deleteKey(int i) -{ - decreaseKey(i, INT_MIN); - extractMin(); -} - -// A recursive method to heapify a subtree with the root at given index -// This method assumes that the subtrees are already heapified -void MinHeap::MinHeapify(int i) -{ - int l = left(i); - int r = right(i); - int smallest = i; - if (l < heap_size && harr[l] < harr[i]) - smallest = l; - if (r < heap_size && harr[r] < harr[smallest]) - smallest = r; - if (smallest != i) - { - swap(&harr[i], &harr[smallest]); - MinHeapify(smallest); - } -} - -// A utility function to swap two elements -void swap(int *x, int *y) -{ - int temp = *x; - *x = *y; - *y = temp; -} - -// Driver program to test above functions -int main() -{ - MinHeap h(11); - h.insertKey(3); - h.insertKey(2); - h.deleteKey(1); - h.insertKey(15); - h.insertKey(5); - h.insertKey(4); - h.insertKey(45); - cout << h.extractMin() << " "; - cout << h.getMin() << " "; - h.decreaseKey(2, 1); - cout << h.getMin(); - return 0; -} +// A C++ program to demonstrate common Binary Heap Operations +#include +#include +using namespace std; + +// Prototype of a utility function to swap two integers +void swap(int *x, int *y); + +// A class for Min Heap +class MinHeap +{ + int *harr; // pointer to array of elements in heap + int capacity; // maximum possible size of min heap + int heap_size; // Current number of elements in min heap +public: + // Constructor + MinHeap(int capacity); + + // to heapify a subtree with the root at given index + void MinHeapify(int); + + int parent(int i) { return (i - 1) / 2; } + + // to get index of left child of node at index i + int left(int i) { return (2 * i + 1); } + + // to get index of right child of node at index i + int right(int i) { return (2 * i + 2); } + + // to extract the root which is the minimum element + int extractMin(); + + // Decreases key value of key at index i to new_val + void decreaseKey(int i, int new_val); + + // Returns the minimum key (key at root) from min heap + int getMin() { return harr[0]; } + + // Deletes a key stored at index i + void deleteKey(int i); + + // Inserts a new key 'k' + void insertKey(int k); +}; + +// Constructor: Builds a heap from a given array a[] of given size +MinHeap::MinHeap(int cap) +{ + heap_size = 0; + capacity = cap; + harr = new int[cap]; +} + +// Inserts a new key 'k' +void MinHeap::insertKey(int k) +{ + if (heap_size == capacity) + { + cout << "\nOverflow: Could not insertKey\n"; + return; + } + + // First insert the new key at the end + heap_size++; + int i = heap_size - 1; + harr[i] = k; + + // Fix the min heap property if it is violated + while (i != 0 && harr[parent(i)] > harr[i]) + { + swap(&harr[i], &harr[parent(i)]); + i = parent(i); + } +} + +// Decreases value of key at index 'i' to new_val. It is assumed that +// new_val is smaller than harr[i]. +void MinHeap::decreaseKey(int i, int new_val) +{ + harr[i] = new_val; + while (i != 0 && harr[parent(i)] > harr[i]) + { + swap(&harr[i], &harr[parent(i)]); + i = parent(i); + } +} + +// Method to remove minimum element (or root) from min heap +int MinHeap::extractMin() +{ + if (heap_size <= 0) + return INT_MAX; + if (heap_size == 1) + { + heap_size--; + return harr[0]; + } + + // Store the minimum value, and remove it from heap + int root = harr[0]; + harr[0] = harr[heap_size - 1]; + heap_size--; + MinHeapify(0); + + return root; +} + +// This function deletes key at index i. It first reduced value to minus +// infinite, then calls extractMin() +void MinHeap::deleteKey(int i) +{ + decreaseKey(i, INT_MIN); + extractMin(); +} + +// A recursive method to heapify a subtree with the root at given index +// This method assumes that the subtrees are already heapified +void MinHeap::MinHeapify(int i) +{ + int l = left(i); + int r = right(i); + int smallest = i; + if (l < heap_size && harr[l] < harr[i]) + smallest = l; + if (r < heap_size && harr[r] < harr[smallest]) + smallest = r; + if (smallest != i) + { + swap(&harr[i], &harr[smallest]); + MinHeapify(smallest); + } +} + +// A utility function to swap two elements +void swap(int *x, int *y) +{ + int temp = *x; + *x = *y; + *y = temp; +} + +// Driver program to test above functions +int main() +{ + MinHeap h(11); + h.insertKey(3); + h.insertKey(2); + h.deleteKey(1); + h.insertKey(15); + h.insertKey(5); + h.insertKey(4); + h.insertKey(45); + cout << h.extractMin() << " "; + cout << h.getMin() << " "; + h.decreaseKey(2, 1); + cout << h.getMin(); + return 0; +} diff --git a/Data Structure/Doubly Linked List.cpp b/Data Structure/Doubly Linked List.cpp index db550d422..84a239d3f 100644 --- a/Data Structure/Doubly Linked List.cpp +++ b/Data Structure/Doubly Linked List.cpp @@ -1,4 +1,4 @@ -#include +#include using namespace std; struct node @@ -12,83 +12,82 @@ node *start; void insert(int x) { - node *t=start; - if (start!=NULL) + node *t = start; + if (start != NULL) { - while(t->next!=NULL) + while (t->next != NULL) { - t=t->next; + t = t->next; } - node *n= new node; - t->next=n; - n->prev=t; - n->val=x; - n->next=NULL; + node *n = new node; + t->next = n; + n->prev = t; + n->val = x; + n->next = NULL; } else { - node *n= new node; - n->val=x; - n->prev=NULL; - n->next=NULL; - start=n; + node *n = new node; + n->val = x; + n->prev = NULL; + n->next = NULL; + start = n; } } void remove(int x) { - node *t=start; - while(t->val!=x) + node *t = start; + while (t->val != x) { - t=t->next; + t = t->next; } - t->prev->next=t->next; - t->next->prev=t->prev; + t->prev->next = t->next; + t->next->prev = t->prev; delete t; } void search(int x) { - node *t= start; - int found =0; - while(t!=NULL) + node *t = start; + int found = 0; + while (t != NULL) { - if(t->val==x) + if (t->val == x) { - cout<<"\nFound"; - found=1; + cout << "\nFound"; + found = 1; break; } - t=t->next; + t = t->next; } - if(found==0) + if (found == 0) { - cout<<"\nNot Found"; + cout << "\nNot Found"; } } void show() { - node *t=start; - while(t!=NULL) + node *t = start; + while (t != NULL) { - cout<val<<"\t"; - t=t->next; + cout << t->val << "\t"; + t = t->next; } - } void reverseShow() { - node *t=start; - while(t->next!=NULL) + node *t = start; + while (t->next != NULL) { - t=t->next; + t = t->next; } - while(t!=NULL) + while (t != NULL) { - cout<val<<"\t"; - t=t->prev; + cout << t->val << "\t"; + t = t->prev; } } @@ -97,29 +96,39 @@ int main() int choice, x; do { - cout<<"\n1. Insert"; - cout<<"\n2. Delete"; - cout<<"\n3. Search"; - cout<<"\n4. Forward print"; - cout<<"\n5. Reverse print"; - cout<<"\n\nEnter you choice : "; - cin>>choice; + cout << "\n1. Insert"; + cout << "\n2. Delete"; + cout << "\n3. Search"; + cout << "\n4. Forward print"; + cout << "\n5. Reverse print"; + cout << "\n\nEnter you choice : "; + cin >> choice; switch (choice) { - case 1 : cout<<"\nEnter the element to be inserted : "; - cin>>x;; - insert(x); break; - case 2 : cout<<"\nEnter the element to be removed : "; - cin>>x; - remove(x); break; - case 3 : cout<<"\nEnter the element to be searched : "; - cin>>x; - search(x); break; - case 4 : show(); break; - case 5 : reverseShow(); break; + case 1: + cout << "\nEnter the element to be inserted : "; + cin >> x; + ; + insert(x); + break; + case 2: + cout << "\nEnter the element to be removed : "; + cin >> x; + remove(x); + break; + case 3: + cout << "\nEnter the element to be searched : "; + cin >> x; + search(x); + break; + case 4: + show(); + break; + case 5: + reverseShow(); + break; } - } - while(choice!=0); + } while (choice != 0); return 0; } diff --git a/Data Structure/Linked List.cpp b/Data Structure/Linked List.cpp index b0da4a3b6..a9b839114 100644 --- a/Data Structure/Linked List.cpp +++ b/Data Structure/Linked List.cpp @@ -1,4 +1,4 @@ -#include +#include using namespace std; struct node @@ -11,50 +11,56 @@ node *start; void insert(int x) { - node *t=start; - if (start!=NULL) + node *t = start; + if (start != NULL) { - while(t->next!=NULL) + while (t->next != NULL) { - t=t->next; + t = t->next; } - node *n= new node; - t->next=n; - n->val=x; - n->next=NULL; + node *n = new node; + t->next = n; + n->val = x; + n->next = NULL; } else { - node *n= new node; - n->val=x; - n->next=NULL; - start=n; + node *n = new node; + n->val = x; + n->next = NULL; + start = n; } } -void remove(int x){ +void remove(int x) +{ - if( start == NULL ){ - cout<<"\nLinked List is empty\n"; - return ; + if (start == NULL) + { + cout << "\nLinked List is empty\n"; + return; } - else if( start->val == x ){ + else if (start->val == x) + { node *temp = start; start = start->next; delete temp; - return ; + return; } node *temp = start, *parent = start; - while( temp != NULL && temp->val != x ){ + while (temp != NULL && temp->val != x) + { parent = temp; temp = temp->next; } - if( temp == NULL ){ - cout <next = temp->next; @@ -63,47 +69,48 @@ void remove(int x){ void search(int x) { - node *t= start; - int found =0; - while(t!=NULL) + node *t = start; + int found = 0; + while (t != NULL) { - if(t->val==x) + if (t->val == x) { - cout<<"\nFound"; - found=1; + cout << "\nFound"; + found = 1; break; } - t=t->next; + t = t->next; } - if(found==0) + if (found == 0) { - cout<<"\nNot Found"; + cout << "\nNot Found"; } } void show() { - node *t=start; - while(t!=NULL) + node *t = start; + while (t != NULL) { - cout<val<<"\t"; - t=t->next; + cout << t->val << "\t"; + t = t->next; } - } -void reverse(){ - node* first = start; - node* second = first->next; - while(second != NULL){ - node* tem = second->next; - second->next = first; - first = second; - second = tem; - } +void reverse() +{ + node *first = start; + node *second = first->next; + while (second != NULL) + { + node *tem = second->next; + second->next = first; + first = second; + second = tem; + } - start->next = NULL; - start = first; + start->next = NULL; + start = first; } int main() @@ -111,33 +118,44 @@ int main() int choice, x; do { - cout<<"\n1. Insert"; - cout<<"\n2. Delete"; - cout<<"\n3. Search"; - cout<<"\n4. Print"; - cout<<"\n5. Reverse"; - cout<<"\n0. Exit"; - cout<<"\n\nEnter you choice : "; - cin>>choice; + cout << "\n1. Insert"; + cout << "\n2. Delete"; + cout << "\n3. Search"; + cout << "\n4. Print"; + cout << "\n5. Reverse"; + cout << "\n0. Exit"; + cout << "\n\nEnter you choice : "; + cin >> choice; switch (choice) { - case 1 : cout<<"\nEnter the element to be inserted : "; - cin>>x;; - insert(x); break; - case 2 : cout<<"\nEnter the element to be removed : "; - cin>>x; - remove(x); break; - case 3 : cout<<"\nEnter the element to be searched : "; - cin>>x; - search(x); break; - case 4 : show(); - cout<<"\n"; break; - case 5 : cout<<"The reversed list: \n"; - reverse(); show(); - cout<<"\n"; break; + case 1: + cout << "\nEnter the element to be inserted : "; + cin >> x; + ; + insert(x); + break; + case 2: + cout << "\nEnter the element to be removed : "; + cin >> x; + remove(x); + break; + case 3: + cout << "\nEnter the element to be searched : "; + cin >> x; + search(x); + break; + case 4: + show(); + cout << "\n"; + break; + case 5: + cout << "The reversed list: \n"; + reverse(); + show(); + cout << "\n"; + break; } - } - while(choice!=0); + } while (choice != 0); return 0; } diff --git a/Data Structure/List Array.cpp b/Data Structure/List Array.cpp index 21f5c6ae5..de984876b 100644 --- a/Data Structure/List Array.cpp +++ b/Data Structure/List Array.cpp @@ -1,32 +1,32 @@ -#include +#include using namespace std; struct list { int data[50]; - int top=0; - bool isSorted=false; - + int top = 0; + bool isSorted = false; + int BinarySearch(int *array, int first, int last, int x) { - if(lastarray[mid]) - return (BinarySearch(array, mid+1, last, x)); + else if (x < array[mid]) + return (BinarySearch(array, first, mid - 1, x)); + else if (x > array[mid]) + return (BinarySearch(array, mid + 1, last, x)); } int LinarSearch(int *array, int x) { for (int i = 0; i < top; i++) { - if (array[i]==x) + if (array[i] == x) { return i; } @@ -37,102 +37,101 @@ struct list int Search(int x) { - int pos=-1; + int pos = -1; if (isSorted) { - pos=BinarySearch(data, 0, top-1, x); + pos = BinarySearch(data, 0, top - 1, x); } else { - pos=LinarSearch(data, x); + pos = LinarSearch(data, x); } - if (pos!=-1) + if (pos != -1) { - cout<<"\nElement found at position : "< pos; i--) { - data[i]=data[i-1]; + data[i] = data[i - 1]; } top++; - data[pos]=x; + data[pos] = x; } } void Remove(int x) { - int pos=Search(x); - cout<<"\n"<>choice; + { + cout << "\n1.Insert"; + cout << "\n2.Delete"; + cout << "\n3.Search"; + cout << "\n4.Sort"; + cout << "\n5.Print"; + cout << "\n\nEnter Your Choice : "; + cin >> choice; switch (choice) { - case 1: cout<<"\nEnter the element to be inserted : "; - cin>>x; - L.insert(x); - break; - case 2: cout<<"\nEnter the element to be removed : "; - cin>>x; - L.Remove(x); - break; - case 3: cout<<"\nEnter the element to be searched : "; - cin>>x; - L.Search(x); - break; - case 4: L.Sort(); - break; - case 5: L.Show(); - break; + case 1: + cout << "\nEnter the element to be inserted : "; + cin >> x; + L.insert(x); + break; + case 2: + cout << "\nEnter the element to be removed : "; + cin >> x; + L.Remove(x); + break; + case 3: + cout << "\nEnter the element to be searched : "; + cin >> x; + L.Search(x); + break; + case 4: + L.Sort(); + break; + case 5: + L.Show(); + break; } - } - while(choice!=0); + } while (choice != 0); return 0; } diff --git a/Data Structure/MorrisInorder.cpp b/Data Structure/MorrisInorder.cpp index 5ea630fac..d3a2e9fd7 100644 --- a/Data Structure/MorrisInorder.cpp +++ b/Data Structure/MorrisInorder.cpp @@ -7,73 +7,86 @@ using namespace std; -struct Btree { +struct Btree +{ int data; - struct Btree* left; //Pointer to left subtree - struct Btree* right; //Pointer to right subtree + struct Btree *left; //Pointer to left subtree + struct Btree *right; //Pointer to right subtree }; -void insert(Btree **root, int d) { - Btree *nn = new Btree(); //Creating new node +void insert(Btree **root, int d) +{ + Btree *nn = new Btree(); //Creating new node nn->data = d; nn->left = NULL; nn->right = NULL; - if(*root == NULL) { + if (*root == NULL) + { *root = nn; return; } - else { - queue q; + else + { + queue q; // Adding root node to queue q.push(*root); - while(!q.empty()) { + while (!q.empty()) + { Btree *node = q.front(); // Removing parent node from queue q.pop(); - if(node->left) + if (node->left) // Adding left child of removed node to queue q.push(node->left); - else { + else + { // Adding new node if no left child is present node->left = nn; return; } - if(node->right) + if (node->right) // Adding right child of removed node to queue q.push(node->right); - else { + else + { // Adding new node if no right child is present node->right = nn; return; - } + } } } } -void morrisInorder(Btree *root) { +void morrisInorder(Btree *root) +{ Btree *curr = root; Btree *temp; - while(curr) { - if(curr->left==NULL) { - cout<data<<" "; + while (curr) + { + if (curr->left == NULL) + { + cout << curr->data << " "; // If left of current node is NULL then curr is shifted to right curr = curr->right; } - else { + else + { // Left of current node is stored in temp temp = curr->left; // Moving to extreme right of temp - while(temp->right&&temp->right!=curr) + while (temp->right && temp->right != curr) temp = temp->right; // If extreme right is null it is made to point to currrent node (will be used for backtracking) - if(temp->right == NULL) { + if (temp->right == NULL) + { temp->right = curr; // current node is made to point its left subtree curr = curr->left; } // If extreme right already points to currrent node it it set to null - else if(temp->right == curr) { - cout<data<<" "; + else if (temp->right == curr) + { + cout << curr->data << " "; temp->right = NULL; // current node is made to point its right subtree curr = curr->right; @@ -82,13 +95,14 @@ void morrisInorder(Btree *root) { } } -int main() { +int main() +{ // Testing morrisInorder funtion Btree *root = NULL; int i; - for(i = 1 ; i <= 7 ; i++) + for (i = 1; i <= 7; i++) insert(&root, i); - cout<<"Morris Inorder: "; + cout << "Morris Inorder: "; morrisInorder(root); return 0; } diff --git a/Data Structure/Queue Using Array.cpp b/Data Structure/Queue Using Array.cpp index 7b5816f84..3b79d06fc 100644 --- a/Data Structure/Queue Using Array.cpp +++ b/Data Structure/Queue Using Array.cpp @@ -1,48 +1,47 @@ -#include +#include using namespace std; int queue[10]; -int front=0; -int rear=0; +int front = 0; +int rear = 0; void Enque(int x) { - if(rear==10) + if (rear == 10) { - cout<<"\nOverflow"; + cout << "\nOverflow"; } else { - queue[rear++]=x; + queue[rear++] = x; } } void Deque() { - if (front==rear) + if (front == rear) { - cout<<"\nUnderflow"; + cout << "\nUnderflow"; } - + else { - cout<<"\n"<>ch; - if (ch==1) + cout << "\n1. Enque"; + cout << "\n2. Deque"; + cout << "\n3. Print"; + cout << "\nEnter Your Choice : "; + cin >> ch; + if (ch == 1) { - cout<<"\nInsert : "; - cin>>x; + cout << "\nInsert : "; + cin >> x; Enque(x); } - else if (ch==2) + else if (ch == 2) { Deque(); } - else if (ch==3) + else if (ch == 3) { show(); } - } - while(ch!=0); + } while (ch != 0); return 0; } - diff --git a/Data Structure/Stack Using Array.cpp b/Data Structure/Stack Using Array.cpp index c5ad146cb..af1d57c46 100644 --- a/Data Structure/Stack Using Array.cpp +++ b/Data Structure/Stack Using Array.cpp @@ -1,30 +1,31 @@ -#include +#include using namespace std; int *stack; -int top=0, size; +int top = 0, size; void push(int x) { - if(top==size) + if (top == size) { - cout<<"\nOverflow"; + cout << "\nOverflow"; } else { - stack[top++]=x; + stack[top++] = x; } } void pop() { - if (top==0) + if (top == 0) { - cout<<"\nUnderflow"; + cout << "\nUnderflow"; } else { - cout<<"\n"<>size; + cout << "\nEnter Size of stack : "; + cin >> size; stack = new int[size]; int ch, x; do { - cout<<"\n1. Push"; - cout<<"\n2. Pop"; - cout<<"\n3. Print"; - cout<<"\n4. Print topmost element:"; - cout<<"\nEnter Your Choice : "; - cin>>ch; - if (ch==1) + cout << "\n1. Push"; + cout << "\n2. Pop"; + cout << "\n3. Print"; + cout << "\n4. Print topmost element:"; + cout << "\nEnter Your Choice : "; + cin >> ch; + if (ch == 1) { - cout<<"\nInsert : "; - cin>>x; + cout << "\nInsert : "; + cin >> x; push(x); } - else if (ch==2) + else if (ch == 2) { pop(); } - else if (ch==3) + else if (ch == 3) { show(); } - else if(ch==4) - { - topmost(); - } - } - while(ch!=0); + else if (ch == 4) + { + topmost(); + } + } while (ch != 0); return 0; } - diff --git a/Data Structure/Stack Using Linked List.cpp b/Data Structure/Stack Using Linked List.cpp index 753fda8ed..6925cf10c 100644 --- a/Data Structure/Stack Using Linked List.cpp +++ b/Data Structure/Stack Using Linked List.cpp @@ -1,4 +1,4 @@ -#include +#include using namespace std; struct node @@ -7,39 +7,39 @@ struct node node *next; }; - node *top; void push(int x) { node *n = new node; - n->val=x; - n->next=top; - top=n; + n->val = x; + n->next = top; + top = n; } void pop() { - if (top==NULL) + if (top == NULL) { - cout<<"\nUnderflow"; + cout << "\nUnderflow"; } else { node *t = top; - cout<<"\n"<val<<" deleted"; - top=top->next; + cout << "\n" + << t->val << " deleted"; + top = top->next; delete t; } } void show() { - node *t=top; - while(t!=NULL) + node *t = top; + while (t != NULL) { - cout<val<<"\n"; - t=t->next; + cout << t->val << "\n"; + t = t->next; } } @@ -48,28 +48,26 @@ int main() int ch, x; do { - cout<<"\n1. Push"; - cout<<"\n2. Pop"; - cout<<"\n3. Print"; - cout<<"\nEnter Your Choice : "; - cin>>ch; - if (ch==1) + cout << "\n1. Push"; + cout << "\n2. Pop"; + cout << "\n3. Print"; + cout << "\nEnter Your Choice : "; + cin >> ch; + if (ch == 1) { - cout<<"\nInsert : "; - cin>>x; + cout << "\nInsert : "; + cin >> x; push(x); } - else if (ch==2) + else if (ch == 2) { pop(); } - else if (ch==3) + else if (ch == 3) { show(); } - } - while(ch!=0); + } while (ch != 0); return 0; } - diff --git a/Data Structure/Tree.cpp b/Data Structure/Tree.cpp index 963779abe..9be60c309 100644 --- a/Data Structure/Tree.cpp +++ b/Data Structure/Tree.cpp @@ -1,7 +1,6 @@ -#include +#include using namespace std; - struct node { int val; @@ -18,55 +17,51 @@ struct queue queue q; - void enqueue(node *n) { - q.t[q.rear++]=n; + q.t[q.rear++] = n; } -node * dequeue() +node *dequeue() { return (q.t[q.front++]); } - - void CreateTree(node *curr, node *n, int x, char pos) { - if(n!=NULL) + if (n != NULL) { char ch; - cout<<"\nLeft or Right of "<val<<" : "; - cin>>ch; - if(ch=='l') + cout << "\nLeft or Right of " << n->val << " : "; + cin >> ch; + if (ch == 'l') CreateTree(n, n->left, x, ch); - else if(ch=='r') + else if (ch == 'r') CreateTree(n, n->right, x, ch); } else { - node *t=new node; - t->val=x; - t->left=NULL; - t->right=NULL; - if (pos=='l') + node *t = new node; + t->val = x; + t->left = NULL; + t->right = NULL; + if (pos == 'l') { - curr->left=t; + curr->left = t; } - else if(pos=='r') + else if (pos == 'r') { - curr->right=t; + curr->right = t; } } } - void BFT(node *n) { - if(n!=NULL) + if (n != NULL) { - cout<val<<" "; + cout << n->val << " "; enqueue(n->left); enqueue(n->right); BFT(dequeue()); @@ -75,9 +70,9 @@ void BFT(node *n) void Pre(node *n) { - if (n!=NULL) + if (n != NULL) { - cout<val<<" "; + cout << n->val << " "; Pre(n->left); Pre(n->right); } @@ -85,76 +80,72 @@ void Pre(node *n) void In(node *n) { - if (n!=NULL) + if (n != NULL) { In(n->left); - cout<val<<" "; + cout << n->val << " "; In(n->right); } } - void Post(node *n) { - if (n!=NULL) + if (n != NULL) { Post(n->left); Post(n->right); - cout<val<<" "; + cout << n->val << " "; } } - - int main() { - q.front=0; - q.rear=0; + q.front = 0; + q.rear = 0; int value; int ch; - node *root=new node; - cout<<"\nEnter the value of root node :"; - cin>>value; - root->val=value; - root->left=NULL; - root->right=NULL; + node *root = new node; + cout << "\nEnter the value of root node :"; + cin >> value; + root->val = value; + root->left = NULL; + root->right = NULL; do { - cout<<"\n1. Insert : "; - cout<<"\n2. Breadth First"; - cout<<"\n3. Preorder Depth First"; - cout<<"\n4. Inorder Depth First"; - cout<<"\n5. Postorder Depth First"; + cout << "\n1. Insert : "; + cout << "\n2. Breadth First"; + cout << "\n3. Preorder Depth First"; + cout << "\n4. Inorder Depth First"; + cout << "\n5. Postorder Depth First"; - cout<<"\nEnter Your Choice : "; - cin>>ch; - switch(ch) + cout << "\nEnter Your Choice : "; + cin >> ch; + switch (ch) { - case 1: - int x; - char pos; - cout<<"\nEnter the value to be Inserted : "; - cin>>x; - cout<<"\nLeft or Right of Root : "; - cin>>pos; - if(pos=='l') - CreateTree(root, root->left, x, pos); - else if(pos=='r') - CreateTree(root, root->right, x, pos); - break; - case 2: - BFT(root); - break; - case 3: - Pre(root); - break; - case 4: - In(root); - break; - case 5: - Post(root); - break; + case 1: + int x; + char pos; + cout << "\nEnter the value to be Inserted : "; + cin >> x; + cout << "\nLeft or Right of Root : "; + cin >> pos; + if (pos == 'l') + CreateTree(root, root->left, x, pos); + else if (pos == 'r') + CreateTree(root, root->right, x, pos); + break; + case 2: + BFT(root); + break; + case 3: + Pre(root); + break; + case 4: + In(root); + break; + case 5: + Post(root); + break; } - } - while(ch!=0); + } while (ch != 0); } diff --git a/Data Structure/TrieTree.cpp b/Data Structure/TrieTree.cpp index 866087d87..2368a76aa 100644 --- a/Data Structure/TrieTree.cpp +++ b/Data Structure/TrieTree.cpp @@ -1,6 +1,6 @@ -#include -#include -#include +#include +#include +#include using namespace std; // structure definition typedef struct trie @@ -8,7 +8,7 @@ typedef struct trie struct trie *arr[26]; bool isEndofWord; } trie; -// create a new node for trie +// create a new node for trie trie *createNode() { trie *nn = new trie(); @@ -18,8 +18,8 @@ trie *createNode() return nn; } -// insert string into the trie -void insert(trie *root, char* str) +// insert string into the trie +void insert(trie *root, char *str) { for (int i = 0; i < strlen(str); i++) { @@ -38,7 +38,7 @@ void insert(trie *root, char* str) } // search a string exists inside the trie -bool search(trie *root, char* str, int index) +bool search(trie *root, char *str, int index) { if (index == strlen(str)) { @@ -54,7 +54,7 @@ bool search(trie *root, char* str, int index) /* removes the string if it is not a prefix of any other string, if it is then just sets the endofword to false, else removes the given string*/ -bool deleteString (trie *root, char* str, int index) +bool deleteString(trie *root, char *str, int index) { if (index == strlen(str)) { @@ -68,7 +68,7 @@ bool deleteString (trie *root, char* str, int index) int j = str[index] - 'a'; if (!root->arr[j]) return false; - bool var = deleteString (root, str, index + 1); + bool var = deleteString(root, str, index + 1); if (var) { root->arr[j] = NULL; diff --git a/Data Structure/circular_Queue_using_Linked_List.cpp b/Data Structure/circular_Queue_using_Linked_List.cpp index bf700ae8b..4b1ec476c 100644 --- a/Data Structure/circular_Queue_using_Linked_List.cpp +++ b/Data Structure/circular_Queue_using_Linked_List.cpp @@ -1,36 +1,44 @@ -#include +#include using namespace std; -struct node{ +struct node +{ int data; struct node *next; }; -class Queue{ +class Queue +{ node *front; node *rear; + public: - Queue(){ + Queue() + { front = NULL; rear = NULL; } - void createNode(int val){ + void createNode(int val) + { node *ptr; node *nn; nn = new node; ptr = front; nn->data = val; nn->next = NULL; - front=nn; - rear=nn; + front = nn; + rear = nn; } - void enqueue(int val){ - if(front==NULL || rear==NULL){ + void enqueue(int val) + { + if (front == NULL || rear == NULL) + { createNode(val); } - else{ + else + { node *ptr; node *nn; - ptr=front; + ptr = front; nn = new node; nn->data = val; rear->next = nn; @@ -38,24 +46,28 @@ public: rear = nn; } } - void dequeue(){ + void dequeue() + { node *n; n = front; front = front->next; - delete(n); + delete (n); } - void traverse(){ + void traverse() + { node *ptr; - ptr=front; - do{ - cout<data<<" "; - ptr=ptr->next; - }while(ptr!=rear->next); - cout<data; - cout<data << " "; + ptr = ptr->next; + } while (ptr != rear->next); + cout << front->data; + cout << endl; } }; -int main(void){ +int main(void) +{ Queue q; q.enqueue(10); q.enqueue(20); diff --git a/Data Structure/linkedList_implentation_usingArray.cpp b/Data Structure/linkedList_implentation_usingArray.cpp index ca08653de..6f8205f27 100644 --- a/Data Structure/linkedList_implentation_usingArray.cpp +++ b/Data Structure/linkedList_implentation_usingArray.cpp @@ -3,107 +3,104 @@ 2. Limited size. (in the following case it is 100 nodes at max). But we can reuse the nodes that are to be deleted by again linking it bacj to the list. */ -#include +#include using namespace std; -struct Node{ +struct Node +{ int data; int next; }; -Node AvailArray[100]; //array that will act as nodes of a linked list. -int head=-1; -int avail=0; +Node AvailArray[100]; //array that will act as nodes of a linked list. +int head = -1; +int avail = 0; void initialise_list() { - for(int i=0;i<=98;i++) + for (int i = 0; i <= 98; i++) { - AvailArray[i].next=i+1; + AvailArray[i].next = i + 1; } - AvailArray[99].next=-1; //indicating the end of the linked list. - + AvailArray[99].next = -1; //indicating the end of the linked list. } -int getnode() //This will return the index of the first free node present in the avail list +int getnode() //This will return the index of the first free node present in the avail list { - int NodeIndexToBeReturned=avail; - avail=AvailArray[avail].next; + int NodeIndexToBeReturned = avail; + avail = AvailArray[avail].next; return NodeIndexToBeReturned; } -void freeNode(int nodeToBeDeleted) //This function when called will delete the node with the index presented as an argument, and will put back that node into the array. +void freeNode(int nodeToBeDeleted) //This function when called will delete the node with the index presented as an argument, and will put back that node into the array. { - AvailArray[nodeToBeDeleted].next=avail; - avail=nodeToBeDeleted; + AvailArray[nodeToBeDeleted].next = avail; + avail = nodeToBeDeleted; } -void insertAtTheBeginning(int data) //The function will insert the given data into the front of the linked list. +void insertAtTheBeginning(int data) //The function will insert the given data into the front of the linked list. { - int newNode=getnode(); - AvailArray[newNode].data=data; - AvailArray[newNode].next=head; - head=newNode; - + int newNode = getnode(); + AvailArray[newNode].data = data; + AvailArray[newNode].next = head; + head = newNode; } void insertAtTheEnd(int data) { - int newNode=getnode(); - int temp=head; - while(AvailArray[temp].next!=-1) + int newNode = getnode(); + int temp = head; + while (AvailArray[temp].next != -1) { - temp=AvailArray[temp].next; - + temp = AvailArray[temp].next; } //temp is now pointing to the end node. - AvailArray[newNode].data=data; - AvailArray[newNode].next=-1; - AvailArray[temp].next=newNode; + AvailArray[newNode].data = data; + AvailArray[newNode].next = -1; + AvailArray[temp].next = newNode; } - void display() { - int temp=head; - while(temp!=-1) + int temp = head; + while (temp != -1) { - cout<"; - temp=AvailArray[temp].next; + cout << AvailArray[temp].data << "->"; + temp = AvailArray[temp].next; } - cout<<"-1"<>z; - switch(z) + cout << "1. Insert At The Beginning" << endl; + cout << "2. Insert At The End" << endl; + cout << "3. Display" << endl; + cout << "4.Exit" << endl; + cout << "Enter Your choice" << endl; + cin >> z; + switch (z) { - case 1: - cout<<"Enter the number you want to enter"<>x; - insertAtTheBeginning(x); - break; - case 2: - cout<<"Enter the number you want to enter"<>y; - insertAtTheEnd(y); - break; - case 3: - cout<<"The linked list contains the following element in order"<> x; + insertAtTheBeginning(x); + break; + case 2: + cout << "Enter the number you want to enter" << endl; + cin >> y; + insertAtTheEnd(y); + break; + case 3: + cout << "The linked list contains the following element in order" << endl; + display(); + break; + case 4: + exit(0); + default: + cout << "The entered choice is not correct" << endl; } } } diff --git a/Dynamic Programming/0-1 Knapsack.cpp b/Dynamic Programming/0-1 Knapsack.cpp index 4bed36fb2..9348372b2 100644 --- a/Dynamic Programming/0-1 Knapsack.cpp +++ b/Dynamic Programming/0-1 Knapsack.cpp @@ -1,6 +1,6 @@ //0-1 Knapsack problem - Dynamic programming //#include -#include +#include using namespace std; //void Print(int res[20][20], int i, int j, int capacity) @@ -15,7 +15,7 @@ using namespace std; // { // cout<res[i][j-1]) @@ -28,43 +28,44 @@ using namespace std; // } //} -int Knapsack(int capacity,int n,int weight[],int value[]){ +int Knapsack(int capacity, int n, int weight[], int value[]) +{ int res[20][20]; - for (int i = 0; i < n+1; ++i) + for (int i = 0; i < n + 1; ++i) { - for (int j = 0; j < capacity+1; ++j) + for (int j = 0; j < capacity + 1; ++j) { - if(i==0||j==0) + if (i == 0 || j == 0) res[i][j] = 0; - else if(weight[i-1]<=j) - res[i][j] = max(value[i-1]+res[i-1][j-weight[i-1]], res[i-1][j]); + else if (weight[i - 1] <= j) + res[i][j] = max(value[i - 1] + res[i - 1][j - weight[i - 1]], res[i - 1][j]); else - res[i][j] = res[i-1][j]; + res[i][j] = res[i - 1][j]; } } -// Print(res, n, capacity, capacity); -// cout<<"\n"; + // Print(res, n, capacity, capacity); + // cout<<"\n"; return res[n][capacity]; } int main() { int n; - cout<<"Enter number of items: "; - cin>>n; + cout << "Enter number of items: "; + cin >> n; int weight[n], value[n]; - cout<<"Enter weights: "; + cout << "Enter weights: "; for (int i = 0; i < n; ++i) { - cin>>weight[i]; + cin >> weight[i]; } - cout<<"Enter values: "; + cout << "Enter values: "; for (int i = 0; i < n; ++i) { - cin>>value[i]; + cin >> value[i]; } int capacity; - cout<<"Enter capacity: "; - cin>>capacity; - cout<> capacity; + cout << Knapsack(capacity, n, weight, value); return 0; } diff --git a/Dynamic Programming/Armstrong Number.cpp b/Dynamic Programming/Armstrong Number.cpp index 18d625e1e..098c8c628 100644 --- a/Dynamic Programming/Armstrong Number.cpp +++ b/Dynamic Programming/Armstrong Number.cpp @@ -1,20 +1,20 @@ //program to check whether a number is an armstrong number or not -#include -#include +#include +#include int main() { - int n,k,d,s=0; - cout<<"Enter a number:"; - cin>>n; - k=n; - while(k!=0) + int n, k, d, s = 0; + cout << "Enter a number:"; + cin >> n; + k = n; + while (k != 0) { - d=k%10; - s+=(int)pow(d,3); - k/=10; + d = k % 10; + s += (int)pow(d, 3); + k /= 10; } - if(s==n) - cout< -#include +#include +#include using namespace std; //Wrapper class for storing an edge -class Edge{ - public: int src,dst,weight; +class Edge +{ +public: + int src, dst, weight; }; //Wrapper class for storing a graph -class Graph{ - public: - int vertexNum,edgeNum; - Edge* edges; +class Graph +{ +public: + int vertexNum, edgeNum; + Edge *edges; //Constructs a graph with V vertices and E edges - Graph(int V,int E){ + Graph(int V, int E) + { this->vertexNum = V; this->edgeNum = E; - this->edges =(Edge*) malloc(E * sizeof(Edge)); + this->edges = (Edge *)malloc(E * sizeof(Edge)); } - //Adds the given edge to the graph - void addEdge(int src, int dst, int weight){ + //Adds the given edge to the graph + void addEdge(int src, int dst, int weight) + { static int edgeInd = 0; - if(edgeInd < this->edgeNum){ + if (edgeInd < this->edgeNum) + { Edge newEdge; newEdge.src = src; newEdge.dst = dst; newEdge.weight = weight; this->edges[edgeInd++] = newEdge; } - } - }; //Utility function to print distances -void print(int dist[], int V){ - cout<<"\nVertex Distance"<>V; - cout<<"Enter number of edges: "; - cin>>E; - Graph G(V,E); - for(int i=0; i>src; - cout<<"Enter destination: "; - cin>>dst; - cout<<"Enter weight: "; - cin>>weight; +int main() +{ + int V, E, gsrc; + int src, dst, weight; + cout << "Enter number of vertices: "; + cin >> V; + cout << "Enter number of edges: "; + cin >> E; + Graph G(V, E); + for (int i = 0; i < E; i++) + { + cout << "\nEdge " << i + 1 << "\nEnter source: "; + cin >> src; + cout << "Enter destination: "; + cin >> dst; + cout << "Enter weight: "; + cin >> weight; G.addEdge(src, dst, weight); } - cout<<"\nEnter source: "; - cin>>gsrc; - BellmanFord(G,gsrc); + cout << "\nEnter source: "; + cin >> gsrc; + BellmanFord(G, gsrc); return 0; } diff --git a/Dynamic Programming/Catalan-Numbers.cpp b/Dynamic Programming/Catalan-Numbers.cpp index a086ae6c1..4d73cd51a 100644 --- a/Dynamic Programming/Catalan-Numbers.cpp +++ b/Dynamic Programming/Catalan-Numbers.cpp @@ -13,7 +13,7 @@ int *cat; // global array to hold catalan numbers unsigned long int catalan_dp(int n) { - /** Using the tabulation technique in dynamic programming, + /** Using the tabulation technique in dynamic programming, this function computes the first `n+1` Catalan numbers Parameter @@ -26,39 +26,39 @@ unsigned long int catalan_dp(int n) */ // By definition, the first two Catalan numbers are 1 - cat[0] = cat[1] = 1; + cat[0] = cat[1] = 1; // Compute the remaining numbers from index 2 to index n, using tabulation - for (int i = 2; i <= n; i++) - { - cat[i] = 0; - for (int j = 0; j < i; j++) - cat[i] += cat[j] * cat[i-j-1]; // applying the definition here - } + for (int i = 2; i <= n; i++) + { + cat[i] = 0; + for (int j = 0; j < i; j++) + cat[i] += cat[j] * cat[i - j - 1]; // applying the definition here + } // Return the result - return cat[n]; + return cat[n]; } int main(int argc, char *argv[]) { - int n; - cout << "Enter n: "; - cin >> n; + int n; + cout << "Enter n: "; + cin >> n; - cat = new int[n+1]; + cat = new int[n + 1]; - cout << "Catalan numbers from 0 to " << n << " are:\n"; - for (int i = 0; i <= n; i++) + cout << "Catalan numbers from 0 to " << n << " are:\n"; + for (int i = 0; i <= n; i++) { - cout << "catalan (" << i << ") = " << catalan_dp(i) << endl; - // NOTE: Since `cat` is a global array, calling `catalan_dp` + cout << "catalan (" << i << ") = " << catalan_dp(i) << endl; + // NOTE: Since `cat` is a global array, calling `catalan_dp` // repeatedly will not recompute the the values already computed - // as in case of pre-computed values, the array will simply return them, + // as in case of pre-computed values, the array will simply return them, // instead of recomputing them. } - return 0; + return 0; } /** Sample Test Case: diff --git a/Dynamic Programming/Coin-Change.cpp b/Dynamic Programming/Coin-Change.cpp index 9b8feda3c..c8acad48e 100644 --- a/Dynamic Programming/Coin-Change.cpp +++ b/Dynamic Programming/Coin-Change.cpp @@ -1,5 +1,5 @@ #include -#include +#include using namespace std; // Function to find the Minimum number of coins required to get Sum S @@ -7,11 +7,10 @@ int findMinCoins(int arr[], int n, int N) { // dp[i] = no of coins required to get a total of i int dp[N + 1]; - - // 0 coins are needed for 0 sum - - dp[0] = 0; + // 0 coins are needed for 0 sum + + dp[0] = 0; for (int i = 1; i <= N; i++) { @@ -39,13 +38,13 @@ int findMinCoins(int arr[], int n, int N) int main() { // No of Coins We Have - int arr[] = { 1, 2, 3, 4 }; + int arr[] = {1, 2, 3, 4}; int n = sizeof(arr) / sizeof(arr[0]); // Total Change Required int N = 15; - cout << "Minimum Number of Coins Required "<< findMinCoins(arr, n, N) << "\n"; + cout << "Minimum Number of Coins Required " << findMinCoins(arr, n, N) << "\n"; return 0; } \ No newline at end of file diff --git a/Dynamic Programming/Cut Rod.cpp b/Dynamic Programming/Cut Rod.cpp index 90e12a532..826332a23 100644 --- a/Dynamic Programming/Cut Rod.cpp +++ b/Dynamic Programming/Cut Rod.cpp @@ -5,25 +5,24 @@ the pieces.*/ #include using namespace std; -int cutrod(int p[],int n) +int cutrod(int p[], int n) { - int r[n+1]; - r[0]=0; - for(int j=0;j using namespace std; -int min(int x, int y, int z){ - return min(min(x,y), z); +int min(int x, int y, int z) +{ + return min(min(x, y), z); } /* A Naive recursive C++ program to find @@ -24,62 +25,68 @@ int min(int x, int y, int z){ * str1 to str2. * O(3^m) */ -int editDist(string str1, string str2, int m, int n) { - if(m == 0) return n; - if(n == 0) return m; - - //If last characters are same then continue - //for the rest of them. - if(str1[m-1] == str2[n-1]) - return editDist(str1, str2, m-1, n-1); +int editDist(string str1, string str2, int m, int n) +{ + if (m == 0) + return n; + if (n == 0) + return m; - //If last not same, then 3 possibilities - //a.Insert b.Remove c. Replace - //Get min of three and continue for rest. - return 1 + min ( editDist(str1, str2, m, n-1), - editDist(str1, str2, m-1, n), - editDist(str1, str2, m-1, n-1) - ); + //If last characters are same then continue + //for the rest of them. + if (str1[m - 1] == str2[n - 1]) + return editDist(str1, str2, m - 1, n - 1); + + //If last not same, then 3 possibilities + //a.Insert b.Remove c. Replace + //Get min of three and continue for rest. + return 1 + min(editDist(str1, str2, m, n - 1), + editDist(str1, str2, m - 1, n), + editDist(str1, str2, m - 1, n - 1)); } /* A DP based program * O(m x n) */ -int editDistDP(string str1, string str2, int m, int n) { +int editDistDP(string str1, string str2, int m, int n) +{ //Create Table for SubProblems - int dp[m+1][n+1]; + int dp[m + 1][n + 1]; //Fill d[][] in bottom up manner - for(int i=0; i<=m; i++) { - for(int j=0; j<=n; j++) { + for (int i = 0; i <= m; i++) + { + for (int j = 0; j <= n; j++) + { //If str1 empty. Then add all of str2 - if(i==0) + if (i == 0) dp[i][j] = j; - //If str2 empty. Then add all of str1 - else if(j==0) + //If str2 empty. Then add all of str1 + else if (j == 0) dp[i][j] = i; - //If character same. Recur for remaining - else if(str1[i-1] == str2[j-1]) - dp[i][j] = dp[i-1][j-1]; + //If character same. Recur for remaining + else if (str1[i - 1] == str2[j - 1]) + dp[i][j] = dp[i - 1][j - 1]; else - dp[i][j] = 1 + min(dp[i][j-1],//Insert - dp[i-1][j],//Remove - dp[i-1][j-1]//Replace - ); + dp[i][j] = 1 + min(dp[i][j - 1], //Insert + dp[i - 1][j], //Remove + dp[i - 1][j - 1] //Replace + ); } } return dp[m][n]; } -int main() { +int main() +{ string str1 = "sunday"; string str2 = "saturday"; - + cout << editDist(str1, str2, str1.length(), str2.length()) << endl; cout << editDistDP(str1, str2, str1.length(), str2.length()) << endl; diff --git a/Dynamic Programming/Egg-Dropping-Puzzle.cpp b/Dynamic Programming/Egg-Dropping-Puzzle.cpp index 5b277be26..a441f29cb 100644 --- a/Dynamic Programming/Egg-Dropping-Puzzle.cpp +++ b/Dynamic Programming/Egg-Dropping-Puzzle.cpp @@ -6,40 +6,47 @@ #include using namespace std; -int eggDrop(int n, int k) { - int eggFloor[n+1][k+1]; +int eggDrop(int n, int k) +{ + int eggFloor[n + 1][k + 1]; int result; - for(int i=1; i<=n; i++) { + for (int i = 1; i <= n; i++) + { eggFloor[i][1] = 1; //n eggs..1 Floor eggFloor[i][0] = 0; //n eggs..0 Floor } - + // Only one egg available - for(int j=1; j<=k ; j++) { + for (int j = 1; j <= k; j++) + { eggFloor[1][j] = j; } - for(int i=2; i<=n; i++) { - for(int j=2; j<=k; j++) { + for (int i = 2; i <= n; i++) + { + for (int j = 2; j <= k; j++) + { eggFloor[i][j] = INT_MAX; - for(int x=1; x<=j; x++) { + for (int x = 1; x <= j; x++) + { // 1+max(eggBreak[one less egg, lower floors], // eggDoesntBreak[same # of eggs, upper floors]); - result = 1 + max(eggFloor[i-1][x-1], eggFloor[i][j-x]); - if(result < eggFloor[i][j]) + result = 1 + max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]); + if (result < eggFloor[i][j]) eggFloor[i][j] = result; } } } - + return eggFloor[n][k]; } -int main() { +int main() +{ int n, k; cout << "Enter number of eggs and floors: "; - cin>>n>>k; + cin >> n >> k; cout << "Minimum number of trials in worst case: " << eggDrop(n, k) << endl; return 0; } diff --git a/Dynamic Programming/Fibonacci_Bottom_Up.cpp b/Dynamic Programming/Fibonacci_Bottom_Up.cpp index cbd0912e8..929547d7d 100644 --- a/Dynamic Programming/Fibonacci_Bottom_Up.cpp +++ b/Dynamic Programming/Fibonacci_Bottom_Up.cpp @@ -1,19 +1,22 @@ #include using namespace std; -int fib(int n){ - int res[n+1]; - res[0] = 0; res[1] = 1; - for(int i=2;i<=n;i++){ - res[i] = res[i-1] + res[i-2]; +int fib(int n) +{ + int res[n + 1]; + res[0] = 0; + res[1] = 1; + for (int i = 2; i <= n; i++) + { + res[i] = res[i - 1] + res[i - 2]; } return res[n]; } int main(int argc, char const *argv[]) { int n; - cout<<"Enter n: "; - cin>>n; - cout<<"Fibonacci number is "; - cout<> n; + cout << "Fibonacci number is "; + cout << fib(n) << endl; return 0; } \ No newline at end of file diff --git a/Dynamic Programming/Fibonacci_Top_Down.cpp b/Dynamic Programming/Fibonacci_Top_Down.cpp index 657881892..449aefbdc 100644 --- a/Dynamic Programming/Fibonacci_Top_Down.cpp +++ b/Dynamic Programming/Fibonacci_Top_Down.cpp @@ -1,24 +1,26 @@ #include using namespace std; int arr[1000000]; -int fib(int n){ - if(arr[n]==-1){ - if(n<=1) +int fib(int n) +{ + if (arr[n] == -1) + { + if (n <= 1) arr[n] = n; else - arr[n] = fib(n-1) + fib(n-2); + arr[n] = fib(n - 1) + fib(n - 2); } return arr[n]; } int main(int argc, char const *argv[]) { int n; - cout<<"Enter n: "; - cin>>n; - for (int i = 0; i < n+1; ++i) + cout << "Enter n: "; + cin >> n; + for (int i = 0; i < n + 1; ++i) { arr[i] = -1; } - cout<<"Fibonacci number is "< -#include -#include +#include +#include +#include using namespace std; //Wrapper class for storing a graph -class Graph{ - public: +class Graph +{ +public: int vertexNum; - int** edges; + int **edges; //Constructs a graph with V vertices and E edges - Graph(int V){ + Graph(int V) + { this->vertexNum = V; - this->edges =(int**) malloc(V * sizeof(int*)); - for(int i=0; iedges[i] = (int*) malloc(V * sizeof(int)); - for(int j=0; jedges = (int **)malloc(V * sizeof(int *)); + for (int i = 0; i < V; i++) + { + this->edges[i] = (int *)malloc(V * sizeof(int)); + for (int j = 0; j < V; j++) this->edges[i][j] = INT_MAX; this->edges[i][i] = 0; - } + } } - //Adds the given edge to the graph - void addEdge(int src, int dst, int weight){ + //Adds the given edge to the graph + void addEdge(int src, int dst, int weight) + { this->edges[src][dst] = weight; } - - }; - //Utility function to print distances -void print(int dist[], int V){ - cout<<"\nThe Distance matrix for Floyd - Warshall"<>V; - cout<<"Enter number of edges: "; - cin>>E; +int main() +{ + int V, E; + int src, dst, weight; + cout << "Enter number of vertices: "; + cin >> V; + cout << "Enter number of edges: "; + cin >> E; Graph G(V); - for(int i=0; i>src; - cout<<"Enter destination: "; - cin>>dst; - cout<<"Enter weight: "; - cin>>weight; + for (int i = 0; i < E; i++) + { + cout << "\nEdge " << i + 1 << "\nEnter source: "; + cin >> src; + cout << "Enter destination: "; + cin >> dst; + cout << "Enter weight: "; + cin >> weight; G.addEdge(src, dst, weight); } FloydWarshall(G); diff --git a/Dynamic Programming/Longest Common Subsequence.cpp b/Dynamic Programming/Longest Common Subsequence.cpp index aba1eeb54..af50720b4 100644 --- a/Dynamic Programming/Longest Common Subsequence.cpp +++ b/Dynamic Programming/Longest Common Subsequence.cpp @@ -4,69 +4,67 @@ using namespace std; void Print(int trace[20][20], int m, int n, string a) { - if (m==0 || n==0) + if (m == 0 || n == 0) { return; } - if (trace[m][n]==1) + if (trace[m][n] == 1) { - Print(trace, m-1, n-1, a); - cout<res[i][j-1]) + if (res[i - 1][j] > res[i][j - 1]) { - res[i][j]=res[i-1][j]; - trace[i][j]=2; // 2 means trace the matrix in upwards direction. + res[i][j] = res[i - 1][j]; + trace[i][j] = 2; // 2 means trace the matrix in upwards direction. } else { - res[i][j]=res[i][j-1]; - trace[i][j]=3; // means trace the matrix in left direction. + res[i][j] = res[i][j - 1]; + trace[i][j] = 3; // means trace the matrix in left direction. } } } @@ -75,13 +73,10 @@ int lcs(string a, string b) return res[m][n]; } - - - int main() { - string a,b; - cin>>a>>b; - cout<> a >> b; + cout << lcs(a, b); return 0; } diff --git a/Dynamic Programming/Longest Increasing Subsequence.cpp b/Dynamic Programming/Longest Increasing Subsequence.cpp index e2d6111c8..49c54a941 100644 --- a/Dynamic Programming/Longest Increasing Subsequence.cpp +++ b/Dynamic Programming/Longest Increasing Subsequence.cpp @@ -1,7 +1,8 @@ //Program to calculate length of longest increasing subsequence in an array #include using namespace std; -int LIS(int a[],int n){ +int LIS(int a[], int n) +{ int lis[n]; for (int i = 0; i < n; ++i) { @@ -11,28 +12,28 @@ int LIS(int a[],int n){ { for (int j = 0; j < i; ++j) { - if(a[i]>a[j] && lis[i] a[j] && lis[i] < lis[j] + 1) lis[i] = lis[j] + 1; } } int res = 0; for (int i = 0; i < n; ++i) { - res = max(res,lis[i]); + res = max(res, lis[i]); } return res; } int main(int argc, char const *argv[]) { int n; - cout<<"Enter size of array: "; - cin>>n; + cout << "Enter size of array: "; + cin >> n; int a[n]; - cout<<"Enter array elements: "; + cout << "Enter array elements: "; for (int i = 0; i < n; ++i) { - cin>>a[i]; + cin >> a[i]; } - cout< +#include using namespace std; -class graph{ +class graph +{ int v; list *adj; - public: + +public: graph(int v); - void addedge(int src,int dest); + void addedge(int src, int dest); void printgraph(); void bfs(int s); }; -graph::graph(int v){ +graph::graph(int v) +{ this->v = v; this->adj = new list[v]; } -void graph::addedge(int src,int dest){ - src--;dest--; +void graph::addedge(int src, int dest) +{ + src--; + dest--; adj[src].push_back(dest); //adj[dest].push_back(src); } -void graph::printgraph(){ - for(int i=0;iv;i++){ - cout<<"Adjacency list of vertex "<v; i++) + { + cout << "Adjacency list of vertex " << i + 1 << " is \n"; list::iterator it; - for(it=adj[i].begin();it!=adj[i].end();++it){ - cout<<*it+1<<" "; + for (it = adj[i].begin(); it != adj[i].end(); ++it) + { + cout << *it + 1 << " "; } - cout<v+1]; - memset(visited,false,sizeof(bool)*(this->v+1)); - visited[s]=true; +void graph::bfs(int s) +{ + bool *visited = new bool[this->v + 1]; + memset(visited, false, sizeof(bool) * (this->v + 1)); + visited[s] = true; list q; q.push_back(s); list::iterator it; - while(!q.empty()){ + while (!q.empty()) + { int u = q.front(); - cout< using namespace std; int v = 4; -void DFSUtil_(int graph[4][4],bool visited[],int s){ +void DFSUtil_(int graph[4][4], bool visited[], int s) +{ visited[s] = true; - cout< #include - #define WHITE 0 #define GREY 1 #define BLACK 2 @@ -12,23 +11,27 @@ using namespace std; int checked[999] = {WHITE}; -void dfs(const list lista[], int start) { +void dfs(const list lista[], int start) +{ stack stack; int checked[999] = {WHITE}; - + stack.push(start); - + checked[start] = GREY; - while(!stack.empty()) { + while (!stack.empty()) + { int act = stack.top(); stack.pop(); - if(checked[act] == GREY) { + if (checked[act] == GREY) + { cout << act << ' '; - for(auto it = lista[act].begin(); it != lista[act].end(); ++it) { + for (auto it = lista[act].begin(); it != lista[act].end(); ++it) + { stack.push(*it); - if(checked[*it] != BLACK) + if (checked[*it] != BLACK) checked[*it] = GREY; } checked[act] = BLACK; //nodo controllato @@ -36,18 +39,19 @@ void dfs(const list lista[], int start) { } } -int main() { - int u, w; - int n; - cin >> n; - list lista[INF]; - for(int i = 0; i < n; ++i) { - cin >> u >> w; - lista[u].push_back(w); - } +int main() +{ + int u, w; + int n; + cin >> n; + list lista[INF]; + for (int i = 0; i < n; ++i) + { + cin >> u >> w; + lista[u].push_back(w); + } - dfs(lista, 0); - + dfs(lista, 0); - return 0; + return 0; } diff --git a/Graph/Dijkstra.cpp b/Graph/Dijkstra.cpp index c395cd527..b3ee44c41 100644 --- a/Graph/Dijkstra.cpp +++ b/Graph/Dijkstra.cpp @@ -4,46 +4,52 @@ #include using namespace std; #define INF 10000010 -vector < pair > graph[5*100001]; -int dis[5*100001]; -int dij(vector > * v,int s,int * dis) { - priority_queue < pair , vector < pair >,greater < pair > > pq; +vector> graph[5 * 100001]; +int dis[5 * 100001]; +int dij(vector> *v, int s, int *dis) +{ + priority_queue, vector>, greater>> pq; // source distance to zero. - pq.push(make_pair(0,s)); + pq.push(make_pair(0, s)); dis[s] = 0; int u; - while(!pq.empty()) { + while (!pq.empty()) + { u = (pq.top()).second; pq.pop(); - for( vector > :: iterator it = v[u].begin(); it != v[u].end();it++) { - if(dis[u] + it->first < dis[it->second]) { + for (vector>::iterator it = v[u].begin(); it != v[u].end(); it++) + { + if (dis[u] + it->first < dis[it->second]) + { dis[it->second] = dis[u] + it->first; - pq.push(make_pair(dis[it->second],it->second)); + pq.push(make_pair(dis[it->second], it->second)); } } } } -int main() { - int m,n,l,x,y,s; +int main() +{ + int m, n, l, x, y, s; // n--> number of nodes , m --> number of edges - cin>>n>>m; - for(int i = 0;i < m;i++) { + cin >> n >> m; + for (int i = 0; i < m; i++) + { // input edges. - scanf("%d%d%d",&x,&y,&l); - graph[x].push_back(make_pair(l,y)); - graph[y].push_back(make_pair(l,x)); // comment this line for directed graph + scanf("%d%d%d", &x, &y, &l); + graph[x].push_back(make_pair(l, y)); + graph[y].push_back(make_pair(l, x)); // comment this line for directed graph } // start node. - scanf("%d",&s); + scanf("%d", &s); // intialise all distances to infinity. - for(int i = 1;i <= n;i++) + for (int i = 1; i <= n; i++) dis[i] = INF; - dij(graph,s,dis); - - for(int i = 1;i <= n;i++) - if(dis[i] == INF) - cout<<"-1 "; + dij(graph, s, dis); + + for (int i = 1; i <= n; i++) + if (dis[i] == INF) + cout << "-1 "; else - cout< //using namespace boost::multiprecision; -const int mx = 1e6+5; +const int mx = 1e6 + 5; const long int inf = 2e9; typedef long long ll; -#define rep(i,n) for(i=0;i -#define vpii vector< pii > +#define rep(i, n) for (i = 0; i < n; i++) +#define repp(i, a, b) for (i = a; i <= b; i++) +#define pii pair +#define vpii vector #define vi vector -#define vll vector -#define r(x) scanf("%d",&x) -#define rs(s) scanf("%s",s) +#define vll vector +#define r(x) scanf("%d", &x) +#define rs(s) scanf("%s", s) #define gc getchar_unlocked #define pc putchar_unlocked #define mp make_pair -#define pb push_back +#define pb push_back #define lb lower_bound #define ub upper_bound #define endl "\n" -#define fast ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); +#define fast \ + ios_base::sync_with_stdio(false); \ + cin.tie(NULL); \ + cout.tie(NULL); using namespace std; void in(int &x) { - register int c = gc(); x = 0; int neg = 0; - for(;((c<48 || c>57) && c != '-');c = gc());if(c=='-') {neg=1;c=gc();} for(;c>47 && c<58;c = gc()) {x = (x<<1) + (x<<3) + c - 48;} - if(neg) x=-x; + register int c = gc(); + x = 0; + int neg = 0; + for (; ((c < 48 || c > 57) && c != '-'); c = gc()) + ; + if (c == '-') + { + neg = 1; + c = gc(); + } + for (; c > 47 && c < 58; c = gc()) + { + x = (x << 1) + (x << 3) + c - 48; + } + if (neg) + x = -x; } -void out (int n) { int N = n, rev, count = 0;rev = N; if (N == 0) { pc('0'); return ;} while ((rev % 10) == 0) { count++; rev /= 10;} rev = 0;while (N != 0) { rev = (rev<<3) + (rev<<1) + N % 10; N /= 10;}while (rev != 0) { pc(rev % 10 + '0'); rev /= 10;} -while (count--) pc('0'); +void out(int n) +{ + int N = n, rev, count = 0; + rev = N; + if (N == 0) + { + pc('0'); + return; + } + while ((rev % 10) == 0) + { + count++; + rev /= 10; + } + rev = 0; + while (N != 0) + { + rev = (rev << 3) + (rev << 1) + N % 10; + N /= 10; + } + while (rev != 0) + { + pc(rev % 10 + '0'); + rev /= 10; + } + while (count--) + pc('0'); } -ll parent[mx],arr[mx],node,edge; -vector>>v; +ll parent[mx], arr[mx], node, edge; +vector>> v; void initial() { int i; - rep(i,node+edge) + rep(i, node + edge) parent[i] = i; } int root(int i) { - while(parent[i] != i) + while (parent[i] != i) { parent[i] = parent[parent[i]]; i = parent[i]; } return i; } -void join(int x,int y) +void join(int x, int y) { - int root_x = root(x); //Disjoint set union by rank + int root_x = root(x); //Disjoint set union by rank int root_y = root(y); parent[root_x] = root_y; } ll kruskal() { - ll mincost=0,i,x,y; - rep(i,edge) + ll mincost = 0, i, x, y; + rep(i, edge) { x = v[i].second.first; y = v[i].second.second; - if(root(x) != root(y)) + if (root(x) != root(y)) { mincost += v[i].first; - join(x,y); + join(x, y); } } return mincost; } -int main(){ +int main() +{ fast; - while(1) + while (1) { - int i,j,from,to,cost,totalcost=0; - cin>>node>>edge; //Enter the nodes and edges - if(node==0 && edge==0) break; //Enter 0 0 to break out - initial(); //Initialise the parent array - rep(i,edge) + int i, j, from, to, cost, totalcost = 0; + cin >> node >> edge; //Enter the nodes and edges + if (node == 0 && edge == 0) + break; //Enter 0 0 to break out + initial(); //Initialise the parent array + rep(i, edge) { - cin>>from>>to>>cost; - v.pb(mp(cost,mp(from,to))); + cin >> from >> to >> cost; + v.pb(mp(cost, mp(from, to))); totalcost += cost; } - sort(v.begin(),v.end()); + sort(v.begin(), v.end()); // rep(i,v.size()) // cout< #include #include - using namespace std; +using namespace std; -int n , m; // For number of Vertices (V) and number of edges (E) -vector< vector > G; +int n, m; // For number of Vertices (V) and number of edges (E) +vector> G; vector visited; vector ans; -void dfs(int v) { +void dfs(int v) +{ visited[v] = true; - for (int u : G[v]) { + for (int u : G[v]) + { if (!visited[u]) dfs(u); } ans.push_back(v); } - -void topological_sort() { + +void topological_sort() +{ visited.assign(n, false); ans.clear(); - for (int i = 0; i < n; ++i) { + for (int i = 0; i < n; ++i) + { if (!visited[i]) dfs(i); } reverse(ans.begin(), ans.end()); } -int main(){ +int main() +{ cout << "Enter the number of vertices and the number of directed edges\n"; cin >> n >> m; - int x , y; - G.resize(n , vector()); - for(int i = 0 ; i < n ; ++i) { + int x, y; + G.resize(n, vector()); + for (int i = 0; i < n; ++i) + { cin >> x >> y; - x-- , y--; // to convert 1-indexed to 0-indexed + x--, y--; // to convert 1-indexed to 0-indexed G[x].push_back(y); } topological_sort(); cout << "Topological Order : \n"; - for(int v : ans) { + for (int v : ans) + { cout << v + 1 << ' '; // converting zero based indexing back to one based. } cout << '\n'; diff --git a/Greedy Algorithms/Dijkstra.cpp b/Greedy Algorithms/Dijkstra.cpp index 05191a279..0c7fffc8c 100644 --- a/Greedy Algorithms/Dijkstra.cpp +++ b/Greedy Algorithms/Dijkstra.cpp @@ -15,7 +15,7 @@ public: { // initializes the array edges. - this->edges = new int*[V]; + this->edges = new int *[V]; for (int i = 0; i < V; i++) { edges[i] = new int[V]; @@ -31,7 +31,6 @@ public: } this->vertexNum = V; - } //Adds the given edge to the graph @@ -39,36 +38,33 @@ public: { this->edges[src][dst] = weight; } - - }; //Utility function to find minimum distance vertex in mdist int minDistance(int mdist[], bool vset[], int V) { int minVal = INT_MAX, minInd = 0; - for(int i=0; i>V; - cout<<"Enter number of edges: "; - cin>>E; + int V, E, gsrc; + int src, dst, weight; + cout << "Enter number of vertices: "; + cin >> V; + cout << "Enter number of edges: "; + cin >> E; Graph G(V); - for(int i=0; i>src; - cout<<"Enter destination: "; - cin>>dst; - cout<<"Enter weight: "; - cin>>weight; + cout << "\nEdge " << i + 1 << "\nEnter source: "; + cin >> src; + cout << "Enter destination: "; + cin >> dst; + cout << "Enter weight: "; + cin >> weight; // makes sure source and destionation are in the proper bounds. if (src >= 0 && src < V && dst >= 0 && dst < V) @@ -144,9 +137,9 @@ int main() continue; } } - cout<<"\nEnter source:"; - cin>>gsrc; - Dijkstra(G,gsrc); + cout << "\nEnter source:"; + cin >> gsrc; + Dijkstra(G, gsrc); return 0; } diff --git a/Greedy Algorithms/Knapsack.cpp b/Greedy Algorithms/Knapsack.cpp index 41ce4cc9b..2135bd1eb 100644 --- a/Greedy Algorithms/Knapsack.cpp +++ b/Greedy Algorithms/Knapsack.cpp @@ -1,4 +1,4 @@ -#include +#include using namespace std; struct Item @@ -7,91 +7,86 @@ struct Item int profit; }; - float profitPerUnit(Item x) { - return (float)x.profit/(float)x.weight; + return (float)x.profit / (float)x.weight; } -int partition (Item arr[], int low, int high) +int partition(Item arr[], int low, int high) { - Item pivot = arr[high]; // pivot - int i = (low - 1); // Index of smaller element - - for (int j = low; j >capacity; - cout<<"\n Enter the number of Items : "; + cin >> capacity; + cout << "\n Enter the number of Items : "; int n; - cin>>n; + cin >> n; Item itemArray[n]; for (int i = 0; i < n; i++) { - cout<<"\nEnter the weight and profit of item "<>itemArray[i].weight; - cin>>itemArray[i].profit; + cout << "\nEnter the weight and profit of item " << i + 1 << " : "; + cin >> itemArray[i].weight; + cin >> itemArray[i].profit; } - quickSort(itemArray, 0, n-1); + quickSort(itemArray, 0, n - 1); // show(itemArray, n); - float maxProfit=0; - int i=n; - while(capacity>0 && --i>=0) + float maxProfit = 0; + int i = n; + while (capacity > 0 && --i >= 0) { - if(capacity>=itemArray[i].weight) + if (capacity >= itemArray[i].weight) { - maxProfit+=itemArray[i].profit; - capacity-=itemArray[i].weight; - cout<<"\n\t"< -#include +#include +#include using namespace std; -struct Node { +struct Node +{ int data; struct Node *next; -} *head[100],*curr; +} * head[100], *curr; -void init() { - for(int i=0;i<100;i++) - head[i]=NULL; +void init() +{ + for (int i = 0; i < 100; i++) + head[i] = NULL; } -void add(int x,int h) { +void add(int x, int h) +{ struct Node *temp = new Node; temp->data = x; temp->next = NULL; - if(!head[h]) { + if (!head[h]) + { head[h] = temp; curr = head[h]; } - else { - curr=head[h]; - while(curr->next) + else + { + curr = head[h]; + while (curr->next) curr = curr->next; curr->next = temp; } } -void display(int mod) { +void display(int mod) +{ struct Node *temp; int i; - for(i=0;inext; + while (temp->next) + { + cout << temp->data << " "; + temp = temp->next; } - cout<data; - cout<data; + cout << endl; } } } -int hash(int x,int mod) { - return x%mod; +int hash(int x, int mod) +{ + return x % mod; } -void find(int x,int h) { - struct Node *temp =head[h]; - if(!head[h]) { - cout<<"Element not found"; +void find(int x, int h) +{ + struct Node *temp = head[h]; + if (!head[h]) + { + cout << "Element not found"; return; } - while(temp->data !=x && temp->next) - temp=temp->next; - if(temp->next) - cout<<"Element found"; - else{ - if(temp->data == x) - cout<<"Element found"; + while (temp->data != x && temp->next) + temp = temp->next; + if (temp->next) + cout << "Element found"; + else + { + if (temp->data == x) + cout << "Element found"; else - cout<< "Element not found"; + cout << "Element not found"; } -} +} -int main(void) { +int main(void) +{ init(); - int c,x,mod,h; - cout<<"Enter the size of Hash Table. = "; - cin>>mod; + int c, x, mod, h; + cout << "Enter the size of Hash Table. = "; + cin >> mod; bool loop = true; - while(loop) { - cout<>c; - switch(c) { - case 1: - cout<<"Enter element to add = "; - cin>>x; - h = hash(x,mod); - h = fabs(h); - add(x,h); - break; - case 2: - cout<<"Enter element to search = "; - cin>>x; - h = hash(x,mod); - find(x,h); - break; - case 3: - cout<<"Enter element to generate hash = "; - cin>>x; - cout<<"Hash of "<> c; + switch (c) + { + case 1: + cout << "Enter element to add = "; + cin >> x; + h = hash(x, mod); + h = fabs(h); + add(x, h); + break; + case 2: + cout << "Enter element to search = "; + cin >> x; + h = hash(x, mod); + find(x, h); + break; + case 3: + cout << "Enter element to generate hash = "; + cin >> x; + cout << "Hash of " << x << " is = " << hash(x, mod); + break; + case 4: + display(mod); + break; + default: + loop = false; + break; } - cout< prime_numbers; -vector > factors; +vector> factors; // Calculating prime number upto a given range void SieveOfEratosthenes(int N) @@ -14,21 +14,20 @@ void SieveOfEratosthenes(int N) // initializes the array isprime memset(isprime, true, sizeof isprime); - for(int i=2; i<=N ; i++) + for (int i = 2; i <= N; i++) { - if(isprime[i]) + if (isprime[i]) { - for(int j=2*i; j<=N; j+=i) - isprime[j]=false; + for (int j = 2 * i; j <= N; j += i) + isprime[j] = false; } } - for(int i=2; i<=N; i++) + for (int i = 2; i <= N; i++) { - if(isprime[i]) + if (isprime[i]) prime_numbers.push_back(i); } - } // Prime factorization of a number @@ -37,9 +36,9 @@ void prime_factorization(int num) int number = num; - for(int i=0; prime_numbers[i]<=num; i++) + for (int i = 0; prime_numbers[i] <= num; i++) { - int count=0; + int count = 0; // termination condition if (number == 1) @@ -47,17 +46,15 @@ void prime_factorization(int num) break; } - while(number%prime_numbers[i] == 0) + while (number % prime_numbers[i] == 0) { count++; - number = number/prime_numbers[i]; + number = number / prime_numbers[i]; } - if(count) - factors.push_back(make_pair(prime_numbers[i],count)); + if (count) + factors.push_back(make_pair(prime_numbers[i], count)); } - - } /* @@ -68,16 +65,16 @@ int main() int num; cout << "\t\tComputes the prime factorization\n\n"; cout << "Type in a number: "; - cin>>num; + cin >> num; SieveOfEratosthenes(num); prime_factorization(num); // Prime factors with their powers in the given number in new line - for(auto it: factors) + for (auto it : factors) { - cout< +#include using namespace std; -int main(){ - int n,k; - cout<<"Enter size of array=\t"; - cin>>n; - cout<<"Enter Number of indeces u want to rotate the array to left=\t"; - cin>>k; +int main() +{ + int n, k; + cout << "Enter size of array=\t"; + cin >> n; + cout << "Enter Number of indeces u want to rotate the array to left=\t"; + cin >> k; int a[n]; - cout<<"Enter elements of array=\t"; - for(int i=0;i>a[i]; + cout << "Enter elements of array=\t"; + for (int i = 0; i < n; i++) + { + cin >> a[i]; } - int temp=0; - for(int i=0;i using namespace std; -int main(){ - int n,k; - cout<<"Enter size of array=\t"; - cin>>n; - cout<<"Enter Number of indices u want to rotate the array to right=\t"; -cin>>k; -int a[n]; -cout<<"Enter elements of array=\t"; - for(int i=0;i>a[i]; - int temp=0; - for(int i=0;i=0;j--){ - if(j==0){ - a[j]=temp; +int main() +{ + int n, k; + cout << "Enter size of array=\t"; + cin >> n; + cout << "Enter Number of indices u want to rotate the array to right=\t"; + cin >> k; + int a[n]; + cout << "Enter elements of array=\t"; + for (int i = 0; i < n; i++) + cin >> a[i]; + int temp = 0; + for (int i = 0; i < k; i++) + { + temp = a[n - 1]; + for (int j = n - 1; j >= 0; j--) + { + if (j == 0) + { + a[j] = temp; } - else{ - a[j]=a[j-1];} - - } - + else + { + a[j] = a[j - 1]; + } + } + } + cout << "Your rotated array is=\t"; + for (int i = 0; i < n; i++) + { + cout << a[i] << " "; } - cout<<"Your rotated array is=\t"; - for(int i=0;i +#include using namespace std; struct node @@ -11,71 +11,69 @@ node *start; void insert(int x) { - node *t=start; - - if (start!=NULL) + node *t = start; + + if (start != NULL) { - while(t->next!=start) + while (t->next != start) { - t=t->next; + t = t->next; } - node *n= new node; - t->next=n; - n->val=x; - n->next=start; + node *n = new node; + t->next = n; + n->val = x; + n->next = start; } else { - node *n= new node; - n->val=x; - start=n; - n->next=start; + node *n = new node; + n->val = x; + start = n; + n->next = start; } } void remove(int x) { - node *t=start; + node *t = start; node *p; - while(t->val!=x) + while (t->val != x) { - p=t; - t=t->next; + p = t; + t = t->next; } - p->next=t->next; + p->next = t->next; delete t; } void search(int x) { - node *t= start; - int found =0; - while(t->next!=start) + node *t = start; + int found = 0; + while (t->next != start) { - if(t->val==x) + if (t->val == x) { - cout<<"\nFound"; - found=1; + cout << "\nFound"; + found = 1; break; } - t=t->next; + t = t->next; } - if(found==0) + if (found == 0) { - cout<<"\nNot Found"; + cout << "\nNot Found"; } } void show() { - node *t=start; + node *t = start; do { - cout<val<<"\t"; - t=t->next; - } - while(t!=start); - + cout << t->val << "\t"; + t = t->next; + } while (t != start); } int main() @@ -83,27 +81,34 @@ int main() int choice, x; do { - cout<<"\n1. Insert"; - cout<<"\n2. Delete"; - cout<<"\n3. Search"; - cout<<"\n4. Print"; - cout<<"\n\nEnter you choice : "; - cin>>choice; + cout << "\n1. Insert"; + cout << "\n2. Delete"; + cout << "\n3. Search"; + cout << "\n4. Print"; + cout << "\n\nEnter you choice : "; + cin >> choice; switch (choice) { - case 1 : cout<<"\nEnter the element to be inserted : "; - cin>>x; - insert(x); break; - case 2 : cout<<"\nEnter the element to be removed : "; - cin>>x; - remove(x); break; - case 3 : cout<<"\nEnter the element to be searched : "; - cin>>x; - search(x); break; - case 4 : show(); break; + case 1: + cout << "\nEnter the element to be inserted : "; + cin >> x; + insert(x); + break; + case 2: + cout << "\nEnter the element to be removed : "; + cin >> x; + remove(x); + break; + case 3: + cout << "\nEnter the element to be searched : "; + cin >> x; + search(x); + break; + case 4: + show(); + break; } - } - while(choice!=0); + } while (choice != 0); return 0; } diff --git a/Operations on Datastructures/Circular Queue Using Array.cpp b/Operations on Datastructures/Circular Queue Using Array.cpp index d91f31af3..36d7e22c3 100644 --- a/Operations on Datastructures/Circular Queue Using Array.cpp +++ b/Operations on Datastructures/Circular Queue Using Array.cpp @@ -1,47 +1,46 @@ -#include +#include using namespace std; int queue[10]; -int front=0; -int rear=0; -int count=0; +int front = 0; +int rear = 0; +int count = 0; void Enque(int x) { - if(count==10) + if (count == 10) { - cout<<"\nOverflow"; + cout << "\nOverflow"; } else { - queue[rear]=x; - rear=(rear+1)%10; + queue[rear] = x; + rear = (rear + 1) % 10; count++; } } void Deque() { - if (front==rear) + if (front == rear) { - cout<<"\nUnderflow"; + cout << "\nUnderflow"; } - + else { - cout<<"\n"<>ch; - if (ch==1) + cout << "\n1. Enque"; + cout << "\n2. Deque"; + cout << "\n3. Print"; + cout << "\nEnter Your Choice : "; + cin >> ch; + if (ch == 1) { - cout<<"\nInsert : "; - cin>>x; + cout << "\nInsert : "; + cin >> x; Enque(x); } - else if (ch==2) + else if (ch == 2) { Deque(); } - else if (ch==3) + else if (ch == 3) { show(); } - } - while(ch!=0); + } while (ch != 0); return 0; } - diff --git a/Operations on Datastructures/Intersection_of_2_arrays.cpp b/Operations on Datastructures/Intersection_of_2_arrays.cpp index e2c064e1b..05652811f 100644 --- a/Operations on Datastructures/Intersection_of_2_arrays.cpp +++ b/Operations on Datastructures/Intersection_of_2_arrays.cpp @@ -1,28 +1,29 @@ #include int main() { - int i,j,m,n; - cout <<"Enter size of array 1:"; + int i, j, m, n; + cout << "Enter size of array 1:"; cin >> m; - cout <<"Enter size of array 2:"; + cout << "Enter size of array 2:"; cin >> n; int a[m]; int b[n]; - cout <<"Enter elements of array 1:"; - for(i=0;i> a[i]; - for(i=0;i> b[i]; - i=0;j=0; - while((i> a[i]; + for (i = 0; i < n; i++) + cin >> b[i]; + i = 0; + j = 0; + while ((i < m) && (j < n)) { - if(a[i]b[j]) - j++; + if (a[i] < b[j]) + i++; + else if (a[i] > b[j]) + j++; else { - cout << a[i++]<<" "; + cout << a[i++] << " "; j++; } } diff --git a/Operations on Datastructures/Reverse a Linked List using Recusion.cpp b/Operations on Datastructures/Reverse a Linked List using Recusion.cpp index daefa18e8..0908080cc 100644 --- a/Operations on Datastructures/Reverse a Linked List using Recusion.cpp +++ b/Operations on Datastructures/Reverse a Linked List using Recusion.cpp @@ -1,4 +1,4 @@ -#include +#include using namespace std; struct node @@ -11,24 +11,24 @@ node *start; void insert(int x) { - node *t=start; - if (start!=NULL) + node *t = start; + if (start != NULL) { - while(t->next!=NULL) + while (t->next != NULL) { - t=t->next; + t = t->next; } - node *n= new node; - t->next=n; - n->val=x; - n->next=NULL; + node *n = new node; + t->next = n; + n->val = x; + n->next = NULL; } else { - node *n= new node; - n->val=x; - n->next=NULL; - start=n; + node *n = new node; + n->val = x; + n->next = NULL; + start = n; } } @@ -36,30 +36,27 @@ void reverse(node *p, node *q) { if (q->next == NULL) { - q->next=p; - p->next=NULL; - start=q; + q->next = p; + p->next = NULL; + start = q; return; } else { reverse(q, q->next); - q->next=p; - p->next=NULL; + q->next = p; + p->next = NULL; } - } - void show() { - node *t=start; - while(t!=NULL) + node *t = start; + while (t != NULL) { - cout<val<<"\t"; - t=t->next; + cout << t->val << "\t"; + t = t->next; } - } int main() @@ -75,6 +72,5 @@ int main() show(); - return 0; } diff --git a/Operations on Datastructures/Union_of_2_arrays.cpp b/Operations on Datastructures/Union_of_2_arrays.cpp index 4046e1ae8..aaaeb8378 100644 --- a/Operations on Datastructures/Union_of_2_arrays.cpp +++ b/Operations on Datastructures/Union_of_2_arrays.cpp @@ -1,33 +1,34 @@ #include int main() { - int m,n,i=0,j=0; - cout << "Enter size of both arrays:"; - cin >> m >> n; - int a[m]; - int b[n]; - cout << "Enter elements of array 1:"; - for(i=0;i>a[i]; - cout << "Enter elements of array 2:"; - for(i=0;i> m >> n; + int a[m]; + int b[n]; + cout << "Enter elements of array 1:"; + for (i = 0; i < m; i++) + cin >> a[i]; + cout << "Enter elements of array 2:"; + for (i = 0; i < n; i++) cin >> b[i]; - i=0;j=0; - while((ib[j]) - cout << b[j++] <<" "; + i = 0; + j = 0; + while ((i < m) && (j < n)) + { + if (a[i] < b[j]) + cout << a[i++] << " "; + else if (a[i] > b[j]) + cout << b[j++] << " "; else { cout << a[i++]; j++; } - } - while(i using namespace std; - //node defined class node { public: int data; - node* link; + node *link; node(int d) { data = d; link = NULL; } - }; //printing the linked list -void print(node* head) +void print(node *head) { - node* current = head; + node *current = head; while (current != NULL) { cout << current->data << " "; - current = current-> link; + current = current->link; } cout << endl; } //creating the linked list with 'n' nodes -node* createlist(int n) +node *createlist(int n) { - node* head = NULL; - node* t = NULL; + node *head = NULL; + node *t = NULL; for (int i = 0; i < n; i++) { - node* temp = NULL; + node *temp = NULL; int num; cin >> num; temp = new node(num); @@ -45,58 +43,58 @@ node* createlist(int n) t = temp; continue; } - if (t->link == NULL) t->link = temp; + if (t->link == NULL) + t->link = temp; t = temp; } return head; } - //performing selection sort on the linked list in an iterative manner -void my_selection_sort_linked_list(node* &head) +void my_selection_sort_linked_list(node *&head) { - node* min = head; //throughout the algorithm 'min' is used to denote the node with min value out of all the nodes left for scanning - //while scanning if we find a node 'X' with value lesser than min, - //then we update the pointers in such a way that 'X' becomes the predecessor of 'min' - node* current = min->link; // 'current' refers to the current node we are scanning - node* previous = min; //'previous' refers to the node that is previous to the current node - node* temp = NULL; // 'temp' in this algo is used to point to the last node of the sorted part of the linked list. - //eg. If at any time instance the state of the linked list is suppose 1->2->5->3->8->NULL - //then, we see that "1->2" is the sorted part of the LL, and therefore temp will be pointing to the last node of the sorted part,i.e,'2' - //We keep on arranging the Linked list in such a way that after each iteration the node with 'min' value is placed at its correct position. - //Eg. Let suppose initially we have 5->4->1->3->2->NULL - //After 1st iteration : 1->4->5->3->2->NULL and so on - - while (min->link != NULL) //so that all the nodes are scanned or until there exists a node - { - //pick the first node from the unsorted part and assume that it is the minimum and then start scanning from the next node + node *min = head; //throughout the algorithm 'min' is used to denote the node with min value out of all the nodes left for scanning + //while scanning if we find a node 'X' with value lesser than min, + //then we update the pointers in such a way that 'X' becomes the predecessor of 'min' + node *current = min->link; // 'current' refers to the current node we are scanning + node *previous = min; //'previous' refers to the node that is previous to the current node + node *temp = NULL; // 'temp' in this algo is used to point to the last node of the sorted part of the linked list. + //eg. If at any time instance the state of the linked list is suppose 1->2->5->3->8->NULL + //then, we see that "1->2" is the sorted part of the LL, and therefore temp will be pointing to the last node of the sorted part,i.e,'2' + //We keep on arranging the Linked list in such a way that after each iteration the node with 'min' value is placed at its correct position. + //Eg. Let suppose initially we have 5->4->1->3->2->NULL + //After 1st iteration : 1->4->5->3->2->NULL and so on - while (current != NULL) //suppose you choose the min node to be X, then scan starts from the (X+1)th node until its NULL. current = (X+1)th node and min = X + while (min->link != NULL) //so that all the nodes are scanned or until there exists a node + { + //pick the first node from the unsorted part and assume that it is the minimum and then start scanning from the next node + + while (current != NULL) //suppose you choose the min node to be X, then scan starts from the (X+1)th node until its NULL. current = (X+1)th node and min = X { - if (current->data < min->data) //if the current node is smaller than the presumed node 'min' + if (current->data < min->data) //if the current node is smaller than the presumed node 'min' { - if (temp == NULL) //temp stays null for the first iteration, therefore it symbolizes that we are scanning for the first time + if (temp == NULL) //temp stays null for the first iteration, therefore it symbolizes that we are scanning for the first time { - if (previous == min) //if the 'previous' is pointing to the 'min' node + if (previous == min) //if the 'previous' is pointing to the 'min' node { - //Update the pointers - head = current; //update the head pointer with the current node + //Update the pointers + head = current; //update the head pointer with the current node min->link = current->link; current->link = previous; min = current; current = previous->link; } - else //if the 'previous' is not pointing to the 'min' node + else //if the 'previous' is not pointing to the 'min' node { - //Update the pointers - head = current; //update the head pointer with the current node + //Update the pointers + head = current; //update the head pointer with the current node previous->link = current->link; current->link = min; min = current; current = previous->link; } } - else //if 'temp' is not NULL, i.e., its not the 1st iteration + else //if 'temp' is not NULL, i.e., its not the 1st iteration { temp->link = current; previous->link = current->link; @@ -105,15 +103,15 @@ void my_selection_sort_linked_list(node* &head) current = previous->link; } } - else //if the current node is greater than min, just move the previous and the current pointer a step further + else //if the current node is greater than min, just move the previous and the current pointer a step further { previous = previous->link; current = current->link; } } - //update the pointers. Set 'temp' to the last node in the sorted part. Make 'min' move a step further so that 'min' points to the 1st node of the unsorted part - //start the iteration again + //update the pointers. Set 'temp' to the last node in the sorted part. Make 'min' move a step further so that 'min' points to the 1st node of the unsorted part + //start the iteration again temp = min; min = min->link; previous = min; @@ -133,7 +131,6 @@ void my_selection_sort_linked_list(node* &head) // original list is : -1 -2 -3 // sorted list is : -3 -2 -1 - // enter the no. of nodes : 8 // 8 7 6 5 4 3 2 1 // original list is : 8 7 6 5 4 3 2 1 @@ -144,19 +141,19 @@ void my_selection_sort_linked_list(node* &head) // original list is : 5 3 4 1 -2 -4 // sorted list is : -4 -2 1 3 4 5 - int main() { - node* head = NULL; + node *head = NULL; int n; - cout << "enter the no. of nodes : "; //taking input from user about the number of nodes in linked list + cout << "enter the no. of nodes : "; //taking input from user about the number of nodes in linked list cin >> n; - if (n == 0) return 0; - head = createlist(n); //creating the list + if (n == 0) + return 0; + head = createlist(n); //creating the list cout << "original list is : "; - print(head); //printing the original linked list - my_selection_sort_linked_list(head); //applying selection sort + print(head); //printing the original linked list + my_selection_sort_linked_list(head); //applying selection sort cout << "sorted list is : "; - print(head); //printing the sorted linked list + print(head); //printing the sorted linked list return 0; } \ No newline at end of file diff --git a/Others/Buzz_number.cpp b/Others/Buzz_number.cpp index 3d39c50f6..f31038aad 100644 --- a/Others/Buzz_number.cpp +++ b/Others/Buzz_number.cpp @@ -3,15 +3,15 @@ using namespace std; int main() { - int n,t; + int n, t; cin >> t; - while(t--) + while (t--) { - cin >> n; - if((n%7==0)||(n%10==7)) - cout << n << " is a buzz number" << endl; - else - cout << n << " is not a buzz number" << endl; + cin >> n; + if ((n % 7 == 0) || (n % 10 == 7)) + cout << n << " is a buzz number" << endl; + else + cout << n << " is not a buzz number" << endl; } return 0; } diff --git a/Others/Decimal To Binary.cpp b/Others/Decimal To Binary.cpp index b8eaba1f1..4e2119ebc 100644 --- a/Others/Decimal To Binary.cpp +++ b/Others/Decimal To Binary.cpp @@ -1,4 +1,4 @@ -// This function convert decimal to binary number +// This function convert decimal to binary number // #include using namespace std; @@ -10,13 +10,14 @@ int main() cin >> number; int remainder, binary = 0, var = 1; - do { - remainder = number % 2; - number = number / 2; - binary = binary + (remainder*var); + do + { + remainder = number % 2; + number = number / 2; + binary = binary + (remainder * var); var = var * 10; - } while (number>0); + } while (number > 0); cout << "the binary is :"; cout << binary; cout << endl; diff --git a/Others/Decimal To Hexadecimal .cpp b/Others/Decimal To Hexadecimal .cpp index 39333ca00..705f21ba4 100644 --- a/Others/Decimal To Hexadecimal .cpp +++ b/Others/Decimal To Hexadecimal .cpp @@ -2,25 +2,27 @@ using namespace std; -int main(void){ +int main(void) +{ int valueToConvert = 0; //Holds user input - int hexArray[8]; //Contains hex values backwards - int i = 0; //counter + int hexArray[8]; //Contains hex values backwards + int i = 0; //counter char HexValues[] = "0123456789ABCDEF"; cout << "Enter a Decimal Value" << endl; //Displays request to stdout - cin >> valueToConvert; //Stores value into valueToConvert via user input + cin >> valueToConvert; //Stores value into valueToConvert via user input - while (valueToConvert > 15){ //Dec to Hex Algorithm - hexArray[i++] = valueToConvert % 16; //Gets remainder + while (valueToConvert > 15) + { //Dec to Hex Algorithm + hexArray[i++] = valueToConvert % 16; //Gets remainder valueToConvert /= 16; } - hexArray[i] = valueToConvert; //Gets last value - + hexArray[i] = valueToConvert; //Gets last value + cout << "Hex Value: "; while (i >= 0) - cout<> n; -cout << n << " in Upper Roman Numerals is " << toupperRoman(n) << "\n"; -cout << n << " in Lower Roman Numerals is " << tolowerRoman(n) << "\n"; -return 0; + int n; + cout << "\t\tRoman numbers converter\n\n"; + cout << "Type in decimal number between 0 up to 4000 (exclusive): "; + cin >> n; + cout << n << " in Upper Roman Numerals is " << toupperRoman(n) << "\n"; + cout << n << " in Lower Roman Numerals is " << tolowerRoman(n) << "\n"; + return 0; } diff --git a/Others/GCD_of_n_numbers.cpp b/Others/GCD_of_n_numbers.cpp index 3e9e9ce17..8158052f8 100644 --- a/Others/GCD_of_n_numbers.cpp +++ b/Others/GCD_of_n_numbers.cpp @@ -3,21 +3,21 @@ using namepsace std; int main() { - cout <<"Enter value of n:"<> n; int a[n]; - int i,j,gcd; + int i, j, gcd; cout << "Enter the n numbers:" << endl; - for(i=0;i> a[i]; - j=1; //to access all elements of the array starting from 1 - gcd=a[0]; - while(j> n; - s=0;k=n; - while(k>9) + s = 0; + k = n; + while (k > 9) { - while(k!=0) + while (k != 0) { - d=k%10; - s+=d; - k/=10; + d = k % 10; + s += d; + k /= 10; } - k=s; - s=0; + k = s; + s = 0; } - if(k==1) - cout << n << " is a happy number" << endl; + if (k == 1) + cout << n << " is a happy number" << endl; else - cout << n << " is not a happy number" << endl; + cout << n << " is not a happy number" << endl; return 0; } diff --git a/Others/Palindromeofnumber.cpp b/Others/Palindromeofnumber.cpp index 8bfdfb073..647803997 100644 --- a/Others/Palindromeofnumber.cpp +++ b/Others/Palindromeofnumber.cpp @@ -12,12 +12,12 @@ int main() string s1 = to_string(num); string s2 = s1; - reverse(s1.begin(),s1.end()); + reverse(s1.begin(), s1.end()); - if(s1 == s2) - cout<<"true"; + if (s1 == s2) + cout << "true"; else - cout<<"false"; + cout << "false"; return 0; } diff --git a/Others/Paranthesis Matching.cpp b/Others/Paranthesis Matching.cpp index 25ee7287b..d2bb4d39c 100644 --- a/Others/Paranthesis Matching.cpp +++ b/Others/Paranthesis Matching.cpp @@ -1,5 +1,5 @@ -#include -#include +#include +#include using namespace std; @@ -10,55 +10,66 @@ using namespace std; char stack[MAX]; int top = -1; -void push(char ch){ - stack[ ++top ] = ch; +void push(char ch) +{ + stack[++top] = ch; } -char pop(){ - return stack[ top-- ]; +char pop() +{ + return stack[top--]; } // -------------- end stack ----------- -char opening(char ch){ - switch(ch){ - case '}': - return '{'; - case ']': - return '['; - case ')': - return '('; - case '>': - return '<'; +char opening(char ch) +{ + switch (ch) + { + case '}': + return '{'; + case ']': + return '['; + case ')': + return '('; + case '>': + return '<'; } } -int main(){ +int main() +{ string exp; int valid = 1, i = 0; - cout<<"Enter The Expression : "; + cout << "Enter The Expression : "; cin >> exp; - - while (valid == 1 && i < exp.length()){ - if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[' || exp[i] == '<'){ - push(exp[i]); - } - else if (top >= 0 && stack[top] == opening(exp[i])){ - pop(); - } - else{ - valid = 0; - } - i++; + + while (valid == 1 && i < exp.length()) + { + if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[' || exp[i] == '<') + { + push(exp[i]); + } + else if (top >= 0 && stack[top] == opening(exp[i])) + { + pop(); + } + else + { + valid = 0; + } + i++; } - // makes sure the stack is empty after processsing (above) - if (valid == 1 && top == -1){ - cout<<"\nCorrect Expression"; + // makes sure the stack is empty after processsing (above) + if (valid == 1 && top == -1) + { + cout << "\nCorrect Expression"; } - else{ - cout<<"\nWrong Expression"; + else + { + cout << "\nWrong Expression"; } return 0; diff --git a/Others/Primality Test.cpp b/Others/Primality Test.cpp index 0b4bb67de..ce8fc1706 100644 --- a/Others/Primality Test.cpp +++ b/Others/Primality Test.cpp @@ -1,33 +1,32 @@ #include using namespace std; - - - //A simple and efficient implementation of a function to test if a number is prime, based on the fact that - //Every Prime number, except 2 and 3 are of the form 6*k+1 or 6*k-1 for integer values of k. - - bool IsPrime( int number ) - { - if ( ( (!(number & 1)) && number != 2 ) || (number < 2) || (number % 3 == 0 && number != 3) ) - return false; - for( int k = 1; 36*k*k-12*k < number;++k) - { - if ( (number % (6*k+1) == 0) || (number % (6*k-1) == 0) ) - return false; - } - return true; - } - - int main() - { - //Main Function - cout <<"Enter the value of n to check if Prime\n"; - int n; - cin >> n; - if(IsPrime(n)) - cout << n << " is Prime" <> n; + if (IsPrime(n)) + cout << n << " is Prime" << endl; + else + cout << n << " is not Prime" << endl; + + return 0; +} diff --git a/Others/Sparse matrix.cpp b/Others/Sparse matrix.cpp index 40073c345..1861163f1 100644 --- a/Others/Sparse matrix.cpp +++ b/Others/Sparse matrix.cpp @@ -5,8 +5,8 @@ using namespace std; int main() { - int m,n; - int counterZeros=0; + int m, n; + int counterZeros = 0; cout << "Enter dimensions of matrix (seperated with space): "; cin >> m >> n; int a[m][n]; @@ -14,28 +14,28 @@ int main() cout << "\n"; // reads the matrix from stdin - for(int i=0;i> a[i][j]; + cout << "element? "; + cin >> a[i][j]; } } // counts the zero's - for(int i=0;i((m*n)/2)) //Checking for sparse matrix - cout << "Sparse matrix"; + if (counterZeros > ((m * n) / 2)) //Checking for sparse matrix + cout << "Sparse matrix"; else - cout << "Not a sparse matrix"; + cout << "Not a sparse matrix"; } diff --git a/Others/Strassen Matrix Multiplication.cpp b/Others/Strassen Matrix Multiplication.cpp index 1cb398a62..85b627763 100644 --- a/Others/Strassen Matrix Multiplication.cpp +++ b/Others/Strassen Matrix Multiplication.cpp @@ -3,55 +3,51 @@ using namespace std; Multiply(int A[][], int B[][], int n) { - if (n==2) + if (n == 2) { - int p1= (a[0][0] + a[1][1])*(b[0][0]+b[1][1]); - int p2= (a[1][0]+a[1][1])*b[0][0]; - int p3= a[0][0]*(b[0][1]-b[1][1]); - int p4= a[1][1]*(b[1][0]-b[0][0]); - int p5= (a[0][0]+a[0][1])*b[1][1]; - int p6= (a[1][0]-a[0][0])*(b[0][0]+b[0][1]); - int p7= (a[0][1]-a[1][1])*(b[1][0]+b[1][1]); + int p1 = (a[0][0] + a[1][1]) * (b[0][0] + b[1][1]); + int p2 = (a[1][0] + a[1][1]) * b[0][0]; + int p3 = a[0][0] * (b[0][1] - b[1][1]); + int p4 = a[1][1] * (b[1][0] - b[0][0]); + int p5 = (a[0][0] + a[0][1]) * b[1][1]; + int p6 = (a[1][0] - a[0][0]) * (b[0][0] + b[0][1]); + int p7 = (a[0][1] - a[1][1]) * (b[1][0] + b[1][1]); + int c[n][n]; + c[0][0] = p1 + p4 - p5 + p7; + c[0][1] = p3 + p5; + c[1][0] = p2 + p4; + c[1][1] = p1 - p2 + p3 + p6; - int c[n][n]; - c[0][0]=p1+p4-p5+p7; - c[0][1]=p3+p5; - c[1][0]=p2+p4; - c[1][1]=p1-p2+p3+p6; - - return c[][]; + return c[][]; } else { - } - } int main() { - int p,q,r,s; - cout<<"Enter the dimensions of Matrices"; - cin>>n; - int A[n][n],; - int B[n][n],; - cout<<"Enter the elements of Matrix A"; + int p, q, r, s; + cout << "Enter the dimensions of Matrices"; + cin >> n; + int A[n][n], ; + int B[n][n], ; + cout << "Enter the elements of Matrix A"; for (int i = 0; i < n; i++) { - for (int j = 0; j >A[i][j]; + cin >> A[i][j]; } } - - cout<<"Enter the elements of Matrix B"; + cout << "Enter the elements of Matrix B"; for (int i = 0; i < n; i++) { - for (int j = 0; j >B[i][j]; + cin >> B[i][j]; } } diff --git a/Others/String Fibonacci.cpp b/Others/String Fibonacci.cpp index 8027b9668..e5475eec9 100644 --- a/Others/String Fibonacci.cpp +++ b/Others/String Fibonacci.cpp @@ -2,7 +2,6 @@ //The method used is manual addition with carry and placing it in a string which is called string addition //This makes it have no bounds or limits - #include #include @@ -69,10 +68,9 @@ void fib_Accurate(long long n) fibMinus2 = fibMinus1; fibMinus1 = tmp; } - cout << fibMinus2; + cout << fibMinus2; } - int main() { int n; diff --git a/Others/Tower of Hanoi.cpp b/Others/Tower of Hanoi.cpp index f9b363784..5783d6a98 100644 --- a/Others/Tower of Hanoi.cpp +++ b/Others/Tower of Hanoi.cpp @@ -1,88 +1,73 @@ -#include +#include using namespace std; struct tower { int values[10]; int top; -}F, U, T; - - +} F, U, T; void show() { - cout<<"\n\n\tF : "; - for(int i=0; i> no; - - for (int i = no; i >0; i--) + + for (int i = no; i > 0; i--) { - F.values[F.top++]=i; + F.values[F.top++] = i; }; - - - - show(); TH(no, F, U, T); - - - - return 0; } diff --git a/Others/fibonacci.cpp b/Others/fibonacci.cpp index 82b1fd322..87ccda6d3 100644 --- a/Others/fibonacci.cpp +++ b/Others/fibonacci.cpp @@ -6,14 +6,12 @@ //It is a property of fibonacci similar to matrix exponentiation. #include -#include +#include using namespace std; const long long MAX = 93; - long long f[MAX] = {0}; - long long fib(long long n) { @@ -22,26 +20,23 @@ long long fib(long long n) return 0; if (n == 1 || n == 2) return (f[n] = 1); - if (f[n]) return f[n]; - - long long k = (n%2!=0)? (n+1)/2 : n/2; - - f[n] = (n%2!=0)? (fib(k)*fib(k) + fib(k-1)*fib(k-1)) - : (2*fib(k-1) + fib(k))*fib(k); + + long long k = (n % 2 != 0) ? (n + 1) / 2 : n / 2; + + f[n] = (n % 2 != 0) ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) + : (2 * fib(k - 1) + fib(k)) * fib(k); return f[n]; } - int main() { - //Main Function - for(long long i=1;i<93;i++) - { - cout << i << " th fibonacci number is " << fib(i) << "\n"; - } - return 0; + //Main Function + for (long long i = 1; i < 93; i++) + { + cout << i << " th fibonacci number is " << fib(i) << "\n"; + } + return 0; } - diff --git a/Others/sieve_of_Eratosthenes.cpp b/Others/sieve_of_Eratosthenes.cpp index e20aec6ae..e87ad4983 100644 --- a/Others/sieve_of_Eratosthenes.cpp +++ b/Others/sieve_of_Eratosthenes.cpp @@ -13,7 +13,6 @@ using namespace std; int primes[MAX]; - /* * This is the function that finds the primes and eliminates * the multiples. @@ -22,12 +21,13 @@ void sieve(int N) { primes[0] = 1; primes[1] = 1; - for(int i=2;i<=N;i++) - { - if(primes[i] == 1) continue; - for(int j=i+i;j<=N;j+=i) - primes[j] = 1; - } + for (int i = 2; i <= N; i++) + { + if (primes[i] == 1) + continue; + for (int j = i + i; j <= N; j += i) + primes[j] = 1; + } } /* @@ -35,8 +35,8 @@ void sieve(int N) */ void print(int N) { - for(int i=0;i<=N;i++) - if(primes[i] == 0) + for (int i = 0; i <= N; i++) + if (primes[i] == 0) cout << i << ' '; cout << '\n'; } @@ -47,7 +47,7 @@ void print(int N) */ void init() { - for(int i=0;i &P, Point Center, double R) @@ -44,12 +45,12 @@ double circle(vector P) Point C; Point minC; for (size_t i = 0; i < P.size() - 2; i++) - for (size_t j = i+1; j < P.size(); j++) - for (size_t k = j+1; k < P.size(); k++) + for (size_t j = i + 1; j < P.size(); j++) + for (size_t k = j + 1; k < P.size(); k++) { - C.x = -0.5 * ((P[i].y*(P[j].x*P[j].x + P[j].y*P[j].y - P[k].x*P[k].x - P[k].y*P[k].y) + P[j].y*(P[k].x*P[k].x + P[k].y*P[k].y - P[i].x*P[i].x - P[i].y*P[i].y) + P[k].y*(P[i].x*P[i].x + P[i].y*P[i].y - P[j].x*P[j].x - P[j].y*P[j].y)) / (P[i].x*(P[j].y - P[k].y) + P[j].x*(P[k].y - P[i].y) + P[k].x*(P[i].y - P[j].y) )); - C.y = 0.5 * ((P[i].x*(P[j].x*P[j].x + P[j].y*P[j].y - P[k].x*P[k].x - P[k].y*P[k].y) + P[j].x*(P[k].x*P[k].x + P[k].y*P[k].y - P[i].x*P[i].x - P[i].y*P[i].y) + P[k].x*(P[i].x*P[i].x + P[i].y*P[i].y - P[j].x*P[j].x - P[j].y*P[j].y)) / (P[i].x*(P[j].y - P[k].y) + P[j].x*(P[k].y - P[i].y) + P[k].x*(P[i].y - P[j].y) )); - R = (LenghtLine(P[i], P[j]) * LenghtLine(P[j], P[k]) * LenghtLine(P[k], P[i])) / (4 * TriangleArea(P[i], P[j], P[k])); + C.x = -0.5 * ((P[i].y * (P[j].x * P[j].x + P[j].y * P[j].y - P[k].x * P[k].x - P[k].y * P[k].y) + P[j].y * (P[k].x * P[k].x + P[k].y * P[k].y - P[i].x * P[i].x - P[i].y * P[i].y) + P[k].y * (P[i].x * P[i].x + P[i].y * P[i].y - P[j].x * P[j].x - P[j].y * P[j].y)) / (P[i].x * (P[j].y - P[k].y) + P[j].x * (P[k].y - P[i].y) + P[k].x * (P[i].y - P[j].y))); + C.y = 0.5 * ((P[i].x * (P[j].x * P[j].x + P[j].y * P[j].y - P[k].x * P[k].x - P[k].y * P[k].y) + P[j].x * (P[k].x * P[k].x + P[k].y * P[k].y - P[i].x * P[i].x - P[i].y * P[i].y) + P[k].x * (P[i].x * P[i].x + P[i].y * P[i].y - P[j].x * P[j].x - P[j].y * P[j].y)) / (P[i].x * (P[j].y - P[k].y) + P[j].x * (P[k].y - P[i].y) + P[k].x * (P[i].y - P[j].y))); + R = (LenghtLine(P[i], P[j]) * LenghtLine(P[j], P[k]) * LenghtLine(P[k], P[i])) / (4 * TriangleArea(P[i], P[j], P[k])); if (!PointInCircle(P, C, R)) { continue; @@ -59,7 +60,6 @@ double circle(vector P) minR = R; minC = C; } - } for (size_t i = 0; i < P.size() - 1; i++) for (size_t j = i + 1; j < P.size(); j++) @@ -84,30 +84,30 @@ double circle(vector P) void test() { vector Pv(5); - Pv.push_back(Point(0,0)); - Pv.push_back(Point(1,3)); - Pv.push_back(Point(4,1)); - Pv.push_back(Point(5,4)); - Pv.push_back(Point(3,-2)); + Pv.push_back(Point(0, 0)); + Pv.push_back(Point(1, 3)); + Pv.push_back(Point(4, 1)); + Pv.push_back(Point(5, 4)); + Pv.push_back(Point(3, -2)); cout << circle(Pv) << endl; } void test2() { vector Pv(4); - Pv.push_back(Point(0,0)); - Pv.push_back(Point(0,2)); - Pv.push_back(Point(2,2)); - Pv.push_back(Point(2,0)); + Pv.push_back(Point(0, 0)); + Pv.push_back(Point(0, 2)); + Pv.push_back(Point(2, 2)); + Pv.push_back(Point(2, 0)); cout << circle(Pv) << endl; } void test3() { vector Pv(3); - Pv.push_back(Point(0.5,1)); - Pv.push_back(Point(3.5,3)); - Pv.push_back(Point(2.5,0)); + Pv.push_back(Point(0.5, 1)); + Pv.push_back(Point(3.5, 3)); + Pv.push_back(Point(2.5, 0)); cout << circle(Pv) << endl; } int main() diff --git a/Others/spiral_print.cpp b/Others/spiral_print.cpp index 03ea074e9..1a843c8cd 100644 --- a/Others/spiral_print.cpp +++ b/Others/spiral_print.cpp @@ -1,54 +1,65 @@ -#include +#include using namespace std; -void genArray(int a[][10],int r,int c){ +void genArray(int a[][10], int r, int c) +{ - int value=1; - for(int i=0;i=startCol;i--,cnt++){ - cout<= startCol; i--, cnt++) + { + cout << a[endRow][i] << " "; } endRow--; ///Print the start Col - if(cnt==r*c){ + if (cnt == r * c) + { break; } - for(int i=endRow;i>=startRow;i--,cnt++){ - cout<= startRow; i--, cnt++) + { + cout << a[i][startCol] << " "; } startCol++; } @@ -58,11 +69,10 @@ int main() { int a[10][10]; - int r,c; - cin>>r>>c; - genArray(a,r,c); - spiralPrint(a,r,c); + int r, c; + cin >> r >> c; + genArray(a, r, c); + spiralPrint(a, r, c); - -return 0; + return 0; } diff --git a/Range queries/MO.cpp b/Range queries/MO.cpp index 2a2cbfffd..44a0883e3 100644 --- a/Range queries/MO.cpp +++ b/Range queries/MO.cpp @@ -1,75 +1,77 @@ #include "bits/stdc++.h" using namespace std; -const int N = 1e6+5; -int a[N],bucket[N],cnt[N]; +const int N = 1e6 + 5; +int a[N], bucket[N], cnt[N]; int bucket_size; -struct query{ - int l,r,i; -}q[N]; -int ans=0; +struct query +{ + int l, r, i; +} q[N]; +int ans = 0; void add(int index) { cnt[a[index]]++; - if(cnt[a[index]] == 1) + if (cnt[a[index]] == 1) ans++; } void remove(int index) { cnt[a[index]]--; - if(cnt[a[index]] == 0) + if (cnt[a[index]] == 0) ans--; } - bool mycmp(query x, query y) { - if(x.l/bucket_size != y.l/bucket_size) - return x.l/bucket_size < y.l/bucket_size; - return x.rL) + while (left > L) { - add(left-1); + add(left - 1); left--; } - while(right<=R) + while (right <= R) { add(right); right++; } - while(right>R+1) + while (right > R + 1) { - remove(right-1); + remove(right - 1); right--; } - bucket[q[i].i] = ans; + bucket[q[i].i] = ans; } - for(i=0;i high) + if (low > high) return 0; - if(qlow>high || qhigh high || qhigh < low) return 0; - if(lazy[pos] != 0) + if (lazy[pos] != 0) { - segtree[pos] += lazy[pos]*(high-low+1); - if(low != high) + segtree[pos] += lazy[pos] * (high - low + 1); + if (low != high) { - lazy[2*pos+1] += lazy[pos]; - lazy[2*pos+2] += lazy[pos]; + lazy[2 * pos + 1] += lazy[pos]; + lazy[2 * pos + 2] += lazy[pos]; } lazy[pos] = 0; } - if(qlow<=low && qhigh>=high) + if (qlow <= low && qhigh >= high) return segtree[pos]; - ll mid = (low+high)/2; - return query(segtree,lazy,qlow,qhigh,low,mid,2*pos+1) + query(segtree,lazy,qlow,qhigh,mid+1,high,2*pos+2); + ll mid = (low + high) / 2; + return query(segtree, lazy, qlow, qhigh, low, mid, 2 * pos + 1) + query(segtree, lazy, qlow, qhigh, mid + 1, high, 2 * pos + 2); } -void update(ll segtree[],ll lazy[],ll start,ll end,ll delta,ll low,ll high,ll pos) +void update(ll segtree[], ll lazy[], ll start, ll end, ll delta, ll low, ll high, ll pos) { - if(low>high) + if (low > high) return; - if(lazy[pos] != 0) + if (lazy[pos] != 0) { - segtree[pos] += lazy[pos]*(high-low+1); - if(low!=high) + segtree[pos] += lazy[pos] * (high - low + 1); + if (low != high) { - lazy[2*pos+1] += lazy[pos]; - lazy[2*pos+2] += lazy[pos]; + lazy[2 * pos + 1] += lazy[pos]; + lazy[2 * pos + 2] += lazy[pos]; } lazy[pos] = 0; } - if(start > high || end < low) + if (start > high || end < low) return; - if(start <= low && end >= high) + if (start <= low && end >= high) { - segtree[pos] += delta*(high-low+1); - if(low != high) + segtree[pos] += delta * (high - low + 1); + if (low != high) { - lazy[2*pos+1] += delta; - lazy[2*pos+2] += delta; + lazy[2 * pos + 1] += delta; + lazy[2 * pos + 2] += delta; } return; } - ll mid = (low+high)/2; - update(segtree,lazy,start,end,delta,low,mid,2*pos+1); - update(segtree,lazy,start,end,delta,mid+1,high,2*pos+2); - segtree[pos] = segtree[2*pos+1] + segtree[2*pos+2]; + ll mid = (low + high) / 2; + update(segtree, lazy, start, end, delta, low, mid, 2 * pos + 1); + update(segtree, lazy, start, end, delta, mid + 1, high, 2 * pos + 2); + segtree[pos] = segtree[2 * pos + 1] + segtree[2 * pos + 2]; } -int main() { - ll n,c; - scanf("%lld %lld",&n,&c); - ll arr[n]={0},p,q,v,choice; - ll segtree[MAX],lazy[MAX]={0}; - ConsTree(arr,segtree,0,n-1,0); - while(c--) +int main() +{ + ll n, c; + scanf("%lld %lld", &n, &c); + ll arr[n] = {0}, p, q, v, choice; + ll segtree[MAX], lazy[MAX] = {0}; + ConsTree(arr, segtree, 0, n - 1, 0); + while (c--) + { + scanf("%lld", &choice); + if (choice == 0) { - scanf("%lld",&choice); - if(choice == 0) - { - scanf("%lld %lld %lld",&p,&q,&v); - update(segtree,lazy,p-1,q-1,v,0,n-1,0); - } - else - { - scanf("%lld %lld",&p,&q); - printf("%lld\n",query(segtree,lazy,p-1,q-1,0,n-1,0)); - } + scanf("%lld %lld %lld", &p, &q, &v); + update(segtree, lazy, p - 1, q - 1, v, 0, n - 1, 0); } + else + { + scanf("%lld %lld", &p, &q); + printf("%lld\n", query(segtree, lazy, p - 1, q - 1, 0, n - 1, 0)); + } + } return 0; } diff --git a/Search/Binary Search.cpp b/Search/Binary Search.cpp index cb67e3a07..2e90855e8 100644 --- a/Search/Binary Search.cpp +++ b/Search/Binary Search.cpp @@ -1,34 +1,36 @@ #include using namespace std; -int binary_search(int a[],int l,int r,int key){ - while(l<=r){ - int m = l+(r-l)/2; - if(key==a[m]) +int binary_search(int a[], int l, int r, int key) +{ + while (l <= r) + { + int m = l + (r - l) / 2; + if (key == a[m]) return m; - else if(key>n; - cout<<"Enter array elements: "; + int n, key; + cout << "Enter size of array: "; + cin >> n; + cout << "Enter array elements: "; int a[n]; for (int i = 0; i < n; ++i) { - cin>>a[i]; + cin >> a[i]; } - cout<<"Enter search key: "; - cin>>key; - int res = binary_search(a,0,n-1,key); - if(res != -1) - cout<> key; + int res = binary_search(a, 0, n - 1, key); + if (res != -1) + cout << key << " found at index " << res << endl; else - cout< +#include using namespace std; int LinearSearch(int *array, int size, int key) { for (int i = 0; i < size; ++i) { - if (array[i]==key) + if (array[i] == key) { return i; } @@ -14,35 +14,34 @@ int LinearSearch(int *array, int size, int key) return -1; } - int main() { int size; - cout<<"\nEnter the size of the Array : "; + cout << "\nEnter the size of the Array : "; cin >> size; - + int array[size]; int key; //Input array - cout<<"\nEnter the Array of " << size << " numbers : "; + cout << "\nEnter the Array of " << size << " numbers : "; for (int i = 0; i < size; i++) { - cin>>array[i]; + cin >> array[i]; } - - cout<<"\nEnter the number to be searched : "; - cin>>key; - int index=LinearSearch(array, size, key); - if (index!=-1) + cout << "\nEnter the number to be searched : "; + cin >> key; + + int index = LinearSearch(array, size, key); + if (index != -1) { - cout<<"\nNumber found at index : "< A[twoThird]) left = twoThird+1; - else if(target < A[oneThird]) right = oneThird-1; - - else left = oneThird+1, right = twoThird-1; - } - else return -1; + if (right - left < absolutePrecision) + { + for (int i = left; i <= right; i++) + if (A[i] == target) + return i; + + return -1; + } + + int oneThird = (left + right) / 3 + 1; + int twoThird = (left + right) * 2 / 3 + 1; + + if (A[oneThird] == target) + return oneThird; + else if (A[twoThird] == target) + return twoThird; + + else if (target > A[twoThird]) + left = twoThird + 1; + else if (target < A[oneThird]) + right = oneThird - 1; + + else + left = oneThird + 1, right = twoThird - 1; } + else + return -1; + } } /* * This is the recursive method of the ternary search which returns the index of the element. */ -int rec_ternary_search(int left, int right, int A[],int target) +int rec_ternary_search(int left, int right, int A[], int target) { - if(left A[twoThird]) return rec_ternary_search(twoThird+1, right, A, target); - - return rec_ternary_search(oneThird+1, twoThird-1, A, target); + return -1; } - else return -1; + + int oneThird = (left + right) / 3 + 1; + int twoThird = (left + right) * 2 / 3 + 1; + + if (A[oneThird] == target) + return oneThird; + if (A[twoThird] == target) + return twoThird; + + if (target < A[oneThird]) + return rec_ternary_search(left, oneThird - 1, A, target); + if (target > A[twoThird]) + return rec_ternary_search(twoThird + 1, right, A, target); + + return rec_ternary_search(oneThird + 1, twoThird - 1, A, target); + } + else + return -1; } /* * ternary_search is a template function * You could either use it_ternary_search or rec_ternary_search according to preference. */ -void ternary_search(int N,int A[],int target) +void ternary_search(int N, int A[], int target) { - cout << it_ternary_search(0,N-1,A,target) << '\t'; - cout << rec_ternary_search(0,N-1,A,target) << '\t'; + cout << it_ternary_search(0, N - 1, A, target) << '\t'; + cout << rec_ternary_search(0, N - 1, A, target) << '\t'; cout << '\n'; } int main() { get_input(); - ternary_search(N,A,_target); + ternary_search(N, A, _target); return 0; } diff --git a/Sorting/BitonicSort.cpp b/Sorting/BitonicSort.cpp index e03e4fc14..6ad2489d2 100644 --- a/Sorting/BitonicSort.cpp +++ b/Sorting/BitonicSort.cpp @@ -2,75 +2,75 @@ /* C++ Program for Bitonic Sort. Note that this program works only when size of input is a power of 2. */ - -#include -#include -using namespace std; - + +#include +#include +using namespace std; + /*The parameter dir indicates the sorting direction, ASCENDING or DESCENDING; if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are interchanged.*/ -void compAndSwap(int a[], int i, int j, int dir) -{ - if (dir==(a[i]>a[j])) - swap(a[i],a[j]); -} - +void compAndSwap(int a[], int i, int j, int dir) +{ + if (dir == (a[i] > a[j])) + swap(a[i], a[j]); +} + /*It recursively sorts a bitonic sequence in ascending order, if dir = 1, and in descending order otherwise (means dir=0). The sequence to be sorted starts at index position low, the parameter cnt is the number of elements to be sorted.*/ -void bitonicMerge(int a[], int low, int cnt, int dir) -{ - if (cnt>1) - { - int k = cnt/2; - for (int i=low; i 1) + { + int k = cnt / 2; + for (int i = low; i < low + k; i++) + compAndSwap(a, i, i + k, dir); + bitonicMerge(a, low, k, dir); + bitonicMerge(a, low + k, k, dir); + } +} + /* This function first produces a bitonic sequence by recursively sorting its two halves in opposite sorting orders, and then calls bitonicMerge to make them in the same order */ -void bitonicSort(int a[],int low, int cnt, int dir) -{ - if (cnt>1) - { - int k = cnt/2; - - // sort in ascending order since dir here is 1 - bitonicSort(a, low, k, 1); - - // sort in descending order since dir here is 0 - bitonicSort(a, low+k, k, 0); - - // Will merge wole sequence in ascending order - // since dir=1. - bitonicMerge(a,low, cnt, dir); - } -} - +void bitonicSort(int a[], int low, int cnt, int dir) +{ + if (cnt > 1) + { + int k = cnt / 2; + + // sort in ascending order since dir here is 1 + bitonicSort(a, low, k, 1); + + // sort in descending order since dir here is 0 + bitonicSort(a, low + k, k, 0); + + // Will merge wole sequence in ascending order + // since dir=1. + bitonicMerge(a, low, cnt, dir); + } +} + /* Caller of bitonicSort for sorting the entire array of length N in ASCENDING order */ -void sort(int a[], int N, int up) -{ - bitonicSort(a,0, N, up); -} - -// Driver code -int main() -{ - int a[]= {3, 7, 4, 8, 6, 2, 1, 5}; - int N = sizeof(a)/sizeof(a[0]); - - int up = 1; // means sort in ascending order - sort(a, N, up); - - printf("Sorted array: \n"); - for (int i=0; i -#include +#include +#include using namespace std; int main() { int n; - short swap_check=0; - cout << "Enter the amount of numbers to sort: "; + short swap_check = 0; + cout << "Enter the amount of numbers to sort: "; cin >> n; vector numbers; cout << "Enter " << n << " numbers: "; int num; - //Input - for(int i=0; i> num; numbers.push_back(num); } //Bubble Sorting - for(int i=0; inumbers[j+1]) + if (numbers[j] > numbers[j + 1]) { - swap_check=1; - swap(numbers[j], numbers[j+1]); + swap_check = 1; + swap(numbers[j], numbers[j + 1]); } } - if(swap_check == 0) - { + if (swap_check == 0) + { break; } } //Output - cout<<"\nSorted Array : "; - for(int i=0; i +#include using namespace std; //Iterative Version -void CocktailSelectionSort(vector &vec,int low,int high) +void CocktailSelectionSort(vector &vec, int low, int high) { - while(low<=high) + while (low <= high) { - int minimum=vec[low]; - int minimumindex=low; - int maximum=vec[high]; - int maximumindex=high; + int minimum = vec[low]; + int minimumindex = low; + int maximum = vec[high]; + int maximumindex = high; - for(int i=low;i<=high;i++) - { - if(vec[i]>=maximum) + for (int i = low; i <= high; i++) { - maximum=vec[i]; - maximumindex=i; + if (vec[i] >= maximum) + { + maximum = vec[i]; + maximumindex = i; + } + if (vec[i] <= minimum) + { + minimum = vec[i]; + minimumindex = i; + } } - if(vec[i]<=minimum) + if (low != maximumindex || high != minimumindex) { - minimum=vec[i]; - minimumindex=i; + swap(vec[low], vec[minimumindex]); + swap(vec[high], vec[maximumindex]); + } + else + { + swap(vec[low], vec[high]); } - } - if(low!=maximumindex||high!=minimumindex) - { - swap(vec[low],vec[minimumindex]); - swap(vec[high],vec[maximumindex]); - } - else - { - swap(vec[low],vec[high]); - } - - low++; - high--; -} - -} + low++; + high--; + } +} //Recursive Version -void CocktailSelectionSort(vector &vec,int low,int high) +void CocktailSelectionSort(vector &vec, int low, int high) { - - if(low>=high) - return; - - int minimum=vec[low]; - int minimumindex=low; - int maximum=vec[high]; - int maximumindex=high; - for(int i=low;i<=high;i++) + if (low >= high) + return; + + int minimum = vec[low]; + int minimumindex = low; + int maximum = vec[high]; + int maximumindex = high; + + for (int i = low; i <= high; i++) { - if(vec[i]>=maximum) + if (vec[i] >= maximum) { - maximum=vec[i]; - maximumindex=i; + maximum = vec[i]; + maximumindex = i; } - if(vec[i]<=minimum) + if (vec[i] <= minimum) { - minimum=vec[i]; - minimumindex=i; + minimum = vec[i]; + minimumindex = i; } } - if(low!=maximumindex||high!=minimumindex) + if (low != maximumindex || high != minimumindex) { - swap(vec[low],vec[minimumindex]); - swap(vec[high],vec[maximumindex]); + swap(vec[low], vec[minimumindex]); + swap(vec[high], vec[maximumindex]); } else { - swap(vec[low],vec[high]); + swap(vec[low], vec[high]); } - - CocktailSelectionSort(vec,low+1,high-1); - + CocktailSelectionSort(vec, low + 1, high - 1); } - //main function, select any one of iterative or recursive version int main() { - int n; - cout << "Enter number of elements\n"; - cin >> n; - std::vector v(n); - cout << "Enter all the elements\n"; - for (int i = 0; i < n; ++i) - { - cin >> v[i]; - } + int n; + cout << "Enter number of elements\n"; + cin >> n; + std::vector v(n); + cout << "Enter all the elements\n"; + for (int i = 0; i < n; ++i) + { + cin >> v[i]; + } - CocktailSelectionSort(v,0,n-1); - cout << "Sorted elements are\n"; - for (int i = 0; i < n; ++i) - { - cout << v[i] << " "; - } + CocktailSelectionSort(v, 0, n - 1); + cout << "Sorted elements are\n"; + for (int i = 0; i < n; ++i) + { + cout << v[i] << " "; + } - return 0; } diff --git a/Sorting/CountingSortString.cpp b/Sorting/CountingSortString.cpp index 2dbf499e7..6179e5d11 100644 --- a/Sorting/CountingSortString.cpp +++ b/Sorting/CountingSortString.cpp @@ -1,44 +1,41 @@ -// C++ Program for counting sort +// C++ Program for counting sort #include - + using namespace std; -void countSort(string arr) -{ +void countSort(string arr) +{ string output; - - int count[256], i; - for(int i=0;i<256;i++) - count[i]=0; - - - for(i = 0; arr[i]; ++i) - ++count[arr[i]]; - - for (i = 1; i <= 256; ++i) - count[i] += count[i-1]; - - for (i = 0; arr[i]; ++i) - { - output[count[arr[i]]-1] = arr[i]; - --count[arr[i]]; - } + int count[256], i; + for (int i = 0; i < 256; i++) + count[i] = 0; - for (i = 0; arr[i]; ++i) - arr[i] = output[i]; - - cout<<"Sorted character array is "<>arr; - - countSort(arr); - - return 0; -} + cin >> arr; + + countSort(arr); + + return 0; +} diff --git a/Sorting/Counting_Sort.cpp b/Sorting/Counting_Sort.cpp index bea604a98..bda37bbd8 100644 --- a/Sorting/Counting_Sort.cpp +++ b/Sorting/Counting_Sort.cpp @@ -1,55 +1,66 @@ -#include +#include using namespace std; -int Max(int Arr[], int N){ +int Max(int Arr[], int N) +{ int max = Arr[0]; - for(int i=1; i max) + for (int i = 1; i < N; i++) + if (Arr[i] > max) max = Arr[i]; return max; } -int Min(int Arr[], int N){ +int Min(int Arr[], int N) +{ int min = Arr[0]; - for(int i=1; i=0; i--){ - Sorted_Arr[Count[Arr[i]-min]-1] = Arr[i]; - Count[Arr[i]-min]--; + + int *Count = new int[max - min + 1]; + + for (int i = 0; i < N; i++) + Count[Arr[i] - min]++; + + for (int i = 1; i < (max - min + 1); i++) + Count[i] += Count[i - 1]; + + for (int i = N - 1; i >= 0; i--) + { + Sorted_Arr[Count[Arr[i] - min] - 1] = Arr[i]; + Count[Arr[i] - min]--; } - + return Sorted_Arr; } -int main(){ +int main() +{ int Arr[] = {47, 65, 20, 66, 25, 53, 64, 69, 72, 22, 74, 25, 53, 15, 42, 36, 4, 69, 86, 19}, N = 20; int *Sorted_Arr; - - cout<<"\n\tOrignal Array = ";Print(Arr, N); + + cout << "\n\tOrignal Array = "; + Print(Arr, N); Sorted_Arr = Counting_Sort(Arr, N); - cout<<"\n\t Sorted Array = ";Print(Sorted_Arr, N); - cout<>n; + cout << "\nEnter the length of your array : "; + cin >> n; int Array[n]; - cout<<"\nEnter any "<>Array[i]; + cin >> Array[i]; } - + //Sorting - for(int i=1; i=0 && temp= 0 && temp < Array[j]) { - Array[j+1]=Array[j]; + Array[j + 1] = Array[j]; j--; } - Array[j+1]=temp; + Array[j + 1] = temp; } - - //Output - cout<<"\nSorted Array : "; - for(int i=0; i +#include using namespace std; void merge(int arr[], int l, int m, int r) { int i, j, k; int n1 = m - l + 1; - int n2 = r - m; - + int n2 = r - m; + int L[n1], R[n2]; - - + for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) - R[j] = arr[m + 1+ j]; - + R[j] = arr[m + 1 + j]; + i = 0; j = 0; k = l; @@ -32,14 +31,13 @@ void merge(int arr[], int l, int m, int r) } k++; } - + while (i < n1) { arr[k] = L[i]; i++; k++; } - while (j < n2) { @@ -48,52 +46,48 @@ void merge(int arr[], int l, int m, int r) k++; } } - void mergeSort(int arr[], int l, int r) { if (l < r) { - - int m = l+(r-l)/2; - - + + int m = l + (r - l) / 2; + mergeSort(arr, l, m); - mergeSort(arr, m+1, r); - + mergeSort(arr, m + 1, r); + merge(arr, l, m, r); } } - void show(int A[], int size) { int i; - for (i=0; i < size; i++) - cout<>size; + cin >> size; int arr[size]; - - cout<<"\nEnter the unsorted elements : "; + + cout << "\nEnter the unsorted elements : "; for (int i = 0; i < size; ++i) { - cout<<"\n"; - cin>>arr[i]; + cout << "\n"; + cin >> arr[i]; } mergeSort(arr, 0, size); - - cout<<"Sorted array\n"; + + cout << "Sorted array\n"; show(arr, size); return 0; } diff --git a/Sorting/NumericStringSort.cpp b/Sorting/NumericStringSort.cpp index 726377ebe..02f6964ba 100644 --- a/Sorting/NumericStringSort.cpp +++ b/Sorting/NumericStringSort.cpp @@ -7,58 +7,56 @@ //This Programme uses a comparator to sort the array in Numerical order instead of Alphanumeric order - -#include -#include -#include +#include +#include +#include using namespace std; -bool NumericSort(string a,string b) +bool NumericSort(string a, string b) { - while(a[0]=='0') + while (a[0] == '0') { a.erase(a.begin()); } - while(b[0]=='0') + while (b[0] == '0') { b.erase(b.begin()); - } - int n=a.length(); - int m=b.length(); - if(n==m) - return a> n; + int n; + cout << "Enter number of elements to be sorted Numerically\n"; + cin >> n; -vector v(n); -cout << "Enter the string of Numbers\n"; -for(int i=0;i> v[i]; -} - -sort(v.begin(),v.end()); -cout << "Elements sorted normally \n"; -for(int i=0;i v(n); + cout << "Enter the string of Numbers\n"; + for (int i = 0; i < n; i++) + { + cin >> v[i]; + } + + sort(v.begin(), v.end()); + cout << "Elements sorted normally \n"; + for (int i = 0; i < n; i++) + { + cout << v[i] << " "; + } + cout << "\n"; + + sort(v.begin(), v.end(), NumericSort); + cout << "Elements sorted Numerically \n"; + for (int i = 0; i < n; i++) + { + cout << v[i] << " "; + } + + return 0; } diff --git a/Sorting/OddEven Sort.cpp b/Sorting/OddEven Sort.cpp index 6319cca91..62842c174 100644 --- a/Sorting/OddEven Sort.cpp +++ b/Sorting/OddEven Sort.cpp @@ -7,23 +7,23 @@ using namespace std; void oddEven(vector &arr, int size) { bool sorted = false; - while( ! sorted ) + while (!sorted) { sorted = true; - for(int i = 1; i < size-1; i += 2)//Odd + for (int i = 1; i < size - 1; i += 2) //Odd { - if(arr[i] > arr[i+1]) + if (arr[i] > arr[i + 1]) { - swap(arr[i], arr[i+1]); + swap(arr[i], arr[i + 1]); sorted = false; } } - for(int i = 0; i < size-1; i += 2)//Even + for (int i = 0; i < size - 1; i += 2) //Even { - if(arr[i] > arr[i+1]) + if (arr[i] > arr[i + 1]) { - swap(arr[i], arr[i+1]); + swap(arr[i], arr[i + 1]); sorted = false; } } @@ -37,7 +37,6 @@ void show(vector A, int size) cout << A[i] << "\n"; } - int main() { int size, temp; @@ -46,7 +45,7 @@ int main() vector arr; - cout<<"\nEnter the unsorted elements : \n"; + cout << "\nEnter the unsorted elements : \n"; for (int i = 0; i < size; ++i) { @@ -56,7 +55,7 @@ int main() oddEven(arr, size); - cout<<"Sorted array\n"; + cout << "Sorted array\n"; show(arr, size); return 0; } diff --git a/Sorting/Quick Sort.cpp b/Sorting/Quick Sort.cpp index b2bb21a77..0b807898f 100644 --- a/Sorting/Quick Sort.cpp +++ b/Sorting/Quick Sort.cpp @@ -1,69 +1,67 @@ /* C implementation QuickSort */ -#include +#include using namespace std; - -int partition (int arr[], int low, int high) + +int partition(int arr[], int low, int high) { - int pivot = arr[high]; // pivot - int i = (low - 1); // Index of smaller element - - for (int j = low; j >size; + cin >> size; int arr[size]; - - cout<<"\nEnter the unsorted elements : "; + + cout << "\nEnter the unsorted elements : "; for (int i = 0; i < size; ++i) { - cout<<"\n"; - cin>>arr[i]; + cout << "\n"; + cin >> arr[i]; } quickSort(arr, 0, size); - cout<<"Sorted array\n"; + cout << "Sorted array\n"; show(arr, size); return 0; } diff --git a/Sorting/Radix Sort.cpp b/Sorting/Radix Sort.cpp index eb3f12a57..09c91bb22 100644 --- a/Sorting/Radix Sort.cpp +++ b/Sorting/Radix Sort.cpp @@ -3,58 +3,66 @@ #include #include using namespace std; -void radixsort(int a[],int n){ +void radixsort(int a[], int n) +{ int count[10]; int output[n]; - memset(output,0,sizeof(output)); - memset(count,0,sizeof(count)); + memset(output, 0, sizeof(output)); + memset(count, 0, sizeof(count)); int max = 0; for (int i = 0; i < n; ++i) { - if (a[i]>max) + if (a[i] > max) { max = a[i]; } } int maxdigits = 0; - while(max){ + while (max) + { maxdigits++; - max/=10; + max /= 10; } - for(int j=0;j +#include using namespace std; int main() { int Array[6]; - cout<<"\nEnter any 6 Numbers for Unsorted Array : "; - + cout << "\nEnter any 6 Numbers for Unsorted Array : "; + //Input - for(int i=0; i<6; i++) + for (int i = 0; i < 6; i++) { - cin>>Array[i]; + cin >> Array[i]; } - + //Selection Sorting - for(int i=0; i<6; i++) + for (int i = 0; i < 6; i++) { - int min=i; - for(int j=i+1; j<6; j++) + int min = i; + for (int j = i + 1; j < 6; j++) { - if(Array[j] +#include using namespace std; int main() { - int size=10; + int size = 10; int array[size]; // Input - cout<<"\nHow many numbers do want to enter in unsorted array : "; - cin>>size; - cout<<"\nEnter the numbers for unsorted array : "; + cout << "\nHow many numbers do want to enter in unsorted array : "; + cin >> size; + cout << "\nEnter the numbers for unsorted array : "; for (int i = 0; i < size; i++) { - cin>>array[i]; + cin >> array[i]; } // Sorting - for (int i = size/2; i>0 ; i=i/2) + for (int i = size / 2; i > 0; i = i / 2) { - for (int j = i; j =0; k=k-i) + for (int k = j - i; k >= 0; k = k - i) { - if (array[k] +#include using namespace std; void SlowSort(int a[], int i, int j) { - if(i>=j) + if (i >= j) return; - int m=i+(j-i)/2; //midpoint, implemented this way to avoid overflow + int m = i + (j - i) / 2; //midpoint, implemented this way to avoid overflow int temp; SlowSort(a, i, m); SlowSort(a, m + 1, j); - if(a[j]>size; + cin >> size; - int arr[size]; - - cout<<"\nEnter the unsorted elements : "; + int arr[size]; - for (int i = 0; i < size; ++i) - { - cout<<"\n"; - cin>>arr[i]; - } + cout << "\nEnter the unsorted elements : "; - SlowSort(arr, 0, size); - - cout<<"Sorted array\n"; - - for (int i = 0; i < size; ++i) - { - cout << arr[i] << " "; - } - return 0; + for (int i = 0; i < size; ++i) + { + cout << "\n"; + cin >> arr[i]; + } + + SlowSort(arr, 0, size); + + cout << "Sorted array\n"; + + for (int i = 0; i < size; ++i) + { + cout << arr[i] << " "; + } + return 0; } diff --git a/Sorting/bucketSort.cpp b/Sorting/bucketSort.cpp index 278da92bd..0ffbf8e4c 100644 --- a/Sorting/bucketSort.cpp +++ b/Sorting/bucketSort.cpp @@ -3,40 +3,40 @@ #include #include using namespace std; - + // Function to sort arr[] of size n using bucket sort void bucketSort(float arr[], int n) { - // 1) Create n empty buckets - vector b[n]; - - // 2) Put array elements in different buckets - for (int i=0; i b[n]; + + // 2) Put array elements in different buckets + for (int i = 0; i < n; i++) + { + int bi = n * arr[i]; // Index in bucket + b[bi].push_back(arr[i]); + } + + // 3) Sort individual buckets + for (int i = 0; i < n; i++) + sort(b[i].begin(), b[i].end()); + + // 4) Concatenate all buckets into arr[] + int index = 0; + for (int i = 0; i < n; i++) + for (int j = 0; j < b[i].size(); j++) + arr[index++] = b[i][j]; } - + /* Driver program to test above funtion */ int main() { - float arr[] = {0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434}; - int n = sizeof(arr)/sizeof(arr[0]); - bucketSort(arr, n); - - cout << "Sorted array is \n"; - for (int i=0; i a[i + gap]) { + for (int i = l; i <= r - gap; ++i) + { + if (a[i] > a[i + gap]) + { swap(a[i], a[i + gap]); swapped = true; } @@ -40,12 +45,15 @@ void CombSort(int a[], int l, int r) { } } -int main() { +int main() +{ cin >> n; - for(int i = 1; i <= n; ++i) cin >> a[i]; + for (int i = 1; i <= n; ++i) + cin >> a[i]; CombSort(a, 1, n); - for(int i = 1; i <= n; ++i) cout << a[i] << ' '; + for (int i = 1; i <= n; ++i) + cout << a[i] << ' '; return 0; } diff --git a/sleep sort.c b/sleep sort.c deleted file mode 100644 index e0217ca25..000000000 --- a/sleep sort.c +++ /dev/null @@ -1,41 +0,0 @@ -#include -#include -#include - -void routine(void *a) -{ - int n = *(int *) a; // typecasting from void to int - - // Sleeping time is proportional to the number - // More precisely this thread sleep for 'n' milliseconds - Sleep(n); - - // After the sleep, print the number - printf("%d ", n); - -void sleepSort(int arr[], int n) -{ - // An array of threads, one for each of the elements - // in the input array - HANDLE threads[n]; - - // Create the threads for each of the input array elements - for (int i = 0; i < n; i++) - threads[i] = (HANDLE)_beginthread(&routine, 0, &arr[i]); - - // Process these threads - WaitForMultipleObjects(n, threads, TRUE, INFINITE); - return; -} - -// Driver program to test above functions -int main() -{ - // Doesn't work for negative numbers - int arr[] = {34, 23, 122, 9}; - int n = sizeof(arr) / sizeof(arr[0]); - - sleepSort (arr, n); - - return(0); -} \ No newline at end of file diff --git a/ternary_search.cpp b/ternary_search.cpp deleted file mode 100644 index 0a2ffbd2a..000000000 --- a/ternary_search.cpp +++ /dev/null @@ -1,19 +0,0 @@ -int three_part_binary_search(int a[], int x, int low, int high){ - if (low < high){ - int m1 = (low + high) / 3 + 1; - int m2 = 2 * (low + high) / 3 + 1; - - if (x == a[m1]) - return m1; - else if (x == a[m2]) - return m2; - else if (x < a[m1]) - return three_part_binary_search(a, x, low, m1 - 1); - else if (xa[m2]) - return three_part_binary_search(a, x, m2 + 1, high); - } - else - return -1; -} \ No newline at end of file From c09256f42dfa9009f6ba9c06c68a05f4dee23d80 Mon Sep 17 00:00:00 2001 From: jordan-matthews-98 <45404939+jordan-matthews-98@users.noreply.github.com> Date: Tue, 27 Aug 2019 10:14:38 -0500 Subject: [PATCH 012/277] fixed BFT, removed unneeded code --- Data Structure/Tree.cpp | 46 ++++++++++++++--------------------------- 1 file changed, 16 insertions(+), 30 deletions(-) diff --git a/Data Structure/Tree.cpp b/Data Structure/Tree.cpp index 963779abe..9058eece4 100644 --- a/Data Structure/Tree.cpp +++ b/Data Structure/Tree.cpp @@ -1,4 +1,5 @@ #include +#include using namespace std; @@ -9,27 +10,6 @@ struct node node *right; }; -struct queue -{ - node *t[100]; - int front; - int rear; -}; - -queue q; - - -void enqueue(node *n) -{ - q.t[q.rear++]=n; -} - -node * dequeue() -{ - return (q.t[q.front++]); -} - - void CreateTree(node *curr, node *n, int x, char pos) { @@ -64,13 +44,21 @@ void CreateTree(node *curr, node *n, int x, char pos) void BFT(node *n) { - if(n!=NULL) - { - cout<val<<" "; - enqueue(n->left); - enqueue(n->right); - BFT(dequeue()); - } + list queue; + + queue.push_back(n); + + while(!queue.empty()) + { + n = queue.front(); + cout << n->val << " "; + queue.pop_front(); + + if(n->left != NULL) + queue.push_back(n->left); + if(n->right != NULL) + queue.push_back(n->right); + } } void Pre(node *n) @@ -108,8 +96,6 @@ void Post(node *n) int main() { - q.front=0; - q.rear=0; int value; int ch; node *root=new node; From ded49a00164459dca8c3885da82c4a08131a5532 Mon Sep 17 00:00:00 2001 From: Shoaib Rayeen Date: Thu, 29 Aug 2019 13:19:45 +0530 Subject: [PATCH 013/277] Space Optimization for the code - Constant Space --- Dynamic Programming/Fibonacci_Bottom_Up.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Dynamic Programming/Fibonacci_Bottom_Up.cpp b/Dynamic Programming/Fibonacci_Bottom_Up.cpp index 929547d7d..a72a6c895 100644 --- a/Dynamic Programming/Fibonacci_Bottom_Up.cpp +++ b/Dynamic Programming/Fibonacci_Bottom_Up.cpp @@ -2,14 +2,16 @@ using namespace std; int fib(int n) { - int res[n + 1]; + int res[3]; res[0] = 0; res[1] = 1; for (int i = 2; i <= n; i++) { - res[i] = res[i - 1] + res[i - 2]; + res[2] = res[1] + res[0]; + res[0] = res[1]; + res[1] = res[2]; } - return res[n]; + return res[1]; } int main(int argc, char const *argv[]) { @@ -19,4 +21,4 @@ int main(int argc, char const *argv[]) cout << "Fibonacci number is "; cout << fib(n) << endl; return 0; -} \ No newline at end of file +} From c05fe4316821e49cc32a51e92db8b60df77cb01c Mon Sep 17 00:00:00 2001 From: PRITI1999 <35490584+PRITI1999@users.noreply.github.com> Date: Tue, 17 Sep 2019 21:49:29 +0530 Subject: [PATCH 014/277] Update Bubble Sort.cpp Removed unnecessary usage of break and restored the single entry and single exit mechanism --- Sorting/Bubble Sort.cpp | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/Sorting/Bubble Sort.cpp b/Sorting/Bubble Sort.cpp index be58be2c9..af4cdbfa9 100644 --- a/Sorting/Bubble Sort.cpp +++ b/Sorting/Bubble Sort.cpp @@ -7,7 +7,7 @@ using namespace std; int main() { int n; - short swap_check = 0; + short swap_check = 1; cout << "Enter the amount of numbers to sort: "; cin >> n; vector numbers; @@ -22,7 +22,7 @@ int main() } //Bubble Sorting - for (int i = 0; i < n; i++) + for (int i = 0; (i < n) && (swap_check == 1); i++) { swap_check = 0; for (int j = 0; j < n - 1 - i; j++) @@ -33,10 +33,6 @@ int main() swap(numbers[j], numbers[j + 1]); } } - if (swap_check == 0) - { - break; - } } //Output From de2111439195f5aec77de38bf2b603a92ac2c83d Mon Sep 17 00:00:00 2001 From: walter-ind <52423075+walter-ind@users.noreply.github.com> Date: Wed, 2 Oct 2019 13:22:43 +0530 Subject: [PATCH 015/277] Add files via upload --- Search/Interpolation Search.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Search/Interpolation Search.cpp diff --git a/Search/Interpolation Search.cpp b/Search/Interpolation Search.cpp new file mode 100644 index 000000000..7a9d67a67 --- /dev/null +++ b/Search/Interpolation Search.cpp @@ -0,0 +1,30 @@ +#include +int InterpolationSearch(int A[], int n, int x){ + int low =0; + int high =n-1; + while (low<=high){ + int mid = low + (((high-1)*(x-A[low]))/(A[high]-A[low])); + if(x==A[mid]) + return mid; // Found x, return (exit) + else if (x Date: Wed, 2 Oct 2019 17:03:24 +0800 Subject: [PATCH 016/277] Update Interpolation Search.cpp --- Search/Interpolation Search.cpp | 49 +++++++++++++++++---------------- 1 file changed, 25 insertions(+), 24 deletions(-) diff --git a/Search/Interpolation Search.cpp b/Search/Interpolation Search.cpp index 7a9d67a67..f52ce4f4f 100644 --- a/Search/Interpolation Search.cpp +++ b/Search/Interpolation Search.cpp @@ -1,30 +1,31 @@ -#include -int InterpolationSearch(int A[], int n, int x){ - int low =0; - int high =n-1; - while (low<=high){ - int mid = low + (((high-1)*(x-A[low]))/(A[high]-A[low])); - if(x==A[mid]) - return mid; // Found x, return (exit) - else if (x +int InterpolationSearch(int A[], int n, int x) +{ + int low = 0; + int high = n - 1; + while (low <= high) + { + int mid = low + (((high - 1) * (x - A[low])) / (A[high] - A[low])); + if (x == A[mid]) + return mid; // Found x, return (exit) + else if (x < A[mid]) + high = mid - 1; // X lies before mid + else + low = mid + 1; // x lies after mid + } + return -1; } -int main(){ - int A[] = {2,4,5,7,13,14,15,23}; - int x=17; - int index = InterpolationSearch(A, 8, x); // passed array A inside the InterpolationSearch function - if(index!= -1) - std::cout << "Number "< Date: Fri, 4 Oct 2019 18:43:42 +0530 Subject: [PATCH 017/277] Added LIS O(nlogn) --- ...Longest Increasing Subsequence (nlogn).cpp | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Dynamic Programming/Longest Increasing Subsequence (nlogn).cpp diff --git a/Dynamic Programming/Longest Increasing Subsequence (nlogn).cpp b/Dynamic Programming/Longest Increasing Subsequence (nlogn).cpp new file mode 100644 index 000000000..eaf28ff8c --- /dev/null +++ b/Dynamic Programming/Longest Increasing Subsequence (nlogn).cpp @@ -0,0 +1,39 @@ +//Program to calculate length of longest increasing subsequence in an array +// in O(n log n) +// tested on : https://cses.fi/problemset/task/1145/ + +#include +using namespace std; +int LIS(int arr[], int n) +{ + set active; // The current built LIS. + active.insert(arr[0]); + // Loop through every element. + for(int i=1; i arr[i] ){ + // else we remove the bigger element and add a smaller element (which is arr[i]) and continue; + active.erase(get); + active.insert(arr[i]); + } + } + } + return active.size(); // size of the LIS. +} +int main(int argc, char const *argv[]) +{ + int n; + cout << "Enter size of array: "; + cin >> n; + int a[n]; + cout << "Enter array elements: "; + for (int i = 0; i < n; ++i) + { + cin >> a[i]; + } + cout << LIS(a, n) << endl; + return 0; +} From 4961000113393a4bca1294212d31887c2c7862b5 Mon Sep 17 00:00:00 2001 From: rohan Date: Fri, 4 Oct 2019 18:55:54 +0530 Subject: [PATCH 018/277] Added BIT --- Range queries/bit.cpp | 66 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Range queries/bit.cpp diff --git a/Range queries/bit.cpp b/Range queries/bit.cpp new file mode 100644 index 000000000..1a1d60e36 --- /dev/null +++ b/Range queries/bit.cpp @@ -0,0 +1,66 @@ +// Binary Indexed Tree. +#include +using namespace std; + +class Bit{ + int n; + vector bit; + inline int offset(int x){ return (x & (-x)); } + + public: + + Bit(vector& arr){ + n = arr.size(); + bit.assign(n+1,0); + for(int i=0; i 0 ){ + res += bit[id]; + id -= offset(id); + } + return res; + } + + int sum_range(int l, int r){ + return sum(r) - sum(l-1); + } +}; + + + +int main(){ + + int n = 5; + vector arr = {1,2,3,4,5}; + Bit x(arr); + + assert(x.sum_range(0,0) == 1); + assert(x.sum_range(0,1) == 3); + assert(x.sum_range(0,2) == 6); + x.update(0,6); + assert(x.sum_range(0,0) == 6); + assert(x.sum_range(0,1) == 8); + assert(x.sum_range(0,2) == 11); + + +} From c45683bb8cb4d4df1d4ddcd19c487cd63c1a6411 Mon Sep 17 00:00:00 2001 From: rohan Date: Fri, 4 Oct 2019 19:05:23 +0530 Subject: [PATCH 019/277] Added LCA binary Lifting O(nlogn) --- Graph/lca.cpp | 90 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 Graph/lca.cpp diff --git a/Graph/lca.cpp b/Graph/lca.cpp new file mode 100644 index 000000000..b0ff12750 --- /dev/null +++ b/Graph/lca.cpp @@ -0,0 +1,90 @@ +#include +using namespace std; +// Find the lowest common ancestor using binary lifting in O(nlogn) +// Zero based indexing +// Resource : https://cp-algorithms.com/graph/lca_binary_lifting.html +const int N = 1005; +const int LG = log2(N)+1; +struct lca{ + int n; + vector adj[N]; // Graph + int up[LG][N]; // build this table + int level[N]; // get the levels of all of them + + lca(int n_) : n(n_){ + memset(up,-1,sizeof(up)); + memset(level,0,sizeof(level)); + for(int i=0; i>a>>b; a--; b--; + adj[a].push_back(b); + adj[b].push_back(a); + } + level[0] = 0; + dfs(0,-1); + build(); + } + void verify(){ + for(int i=0; i level[u] ){ swap(u,v); } + // u is at the bottom. + int dist = level[u] - level[v]; + // Go up this much distance + for(int i=LG-1; i>=0; --i){ + if( dist & ( 1 << i) ){ + u = up[i][u]; + } + } + if( u == v ){ return u; } + assert(level[u] == level[v]); + for(int i=LG-1; i>=0; --i){ + if( up[i][u] != up[i][v] ){ + u = up[i][u]; + v = up[i][v]; + } + } + assert(up[0][u] == up[0][v]); + return up[0][u]; + } +}; + +int main(){ + int n; // number of nodes in the tree. + lca l(n); // will take the input in the format given + // n-1 edges of the form + // a b + // Use verify function to see. +} From ddef541cfdbd29c78c875b307991e60cabb84334 Mon Sep 17 00:00:00 2001 From: Shivam Mishra <41479737+codder-shivam@users.noreply.github.com> Date: Tue, 8 Oct 2019 14:25:10 +0530 Subject: [PATCH 020/277] Update Linked List.cpp --- Data Structure/Linked List.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/Data Structure/Linked List.cpp b/Data Structure/Linked List.cpp index a9b839114..cf976e3a5 100644 --- a/Data Structure/Linked List.cpp +++ b/Data Structure/Linked List.cpp @@ -131,7 +131,6 @@ int main() case 1: cout << "\nEnter the element to be inserted : "; cin >> x; - ; insert(x); break; case 2: From eb6db42fac506c1a7597e5256c43301ebb55a8ab Mon Sep 17 00:00:00 2001 From: John Law Date: Tue, 8 Oct 2019 23:58:49 +0800 Subject: [PATCH 021/277] Update Longest Increasing Subsequence (nlogn).cpp --- ...Longest Increasing Subsequence (nlogn).cpp | 65 ++++++++++--------- 1 file changed, 36 insertions(+), 29 deletions(-) diff --git a/Dynamic Programming/Longest Increasing Subsequence (nlogn).cpp b/Dynamic Programming/Longest Increasing Subsequence (nlogn).cpp index eaf28ff8c..56dcca969 100644 --- a/Dynamic Programming/Longest Increasing Subsequence (nlogn).cpp +++ b/Dynamic Programming/Longest Increasing Subsequence (nlogn).cpp @@ -3,37 +3,44 @@ // tested on : https://cses.fi/problemset/task/1145/ #include + using namespace std; int LIS(int arr[], int n) { - set active; // The current built LIS. - active.insert(arr[0]); - // Loop through every element. - for(int i=1; i arr[i] ){ - // else we remove the bigger element and add a smaller element (which is arr[i]) and continue; - active.erase(get); - active.insert(arr[i]); - } - } - } - return active.size(); // size of the LIS. -} -int main(int argc, char const *argv[]) -{ - int n; - cout << "Enter size of array: "; - cin >> n; - int a[n]; - cout << "Enter array elements: "; - for (int i = 0; i < n; ++i) + set < int > active; // The current built LIS. + active.insert(arr[0]); + // Loop through every element. + for (int i = 1; i < n; ++i) + { + auto get = active.lower_bound(arr[i]); + if (get == active.end()) { - cin >> a[i]; - } - cout << LIS(a, n) << endl; - return 0; + active.insert(arr[i]); + } // current element is the greatest so LIS increases by 1. + else + { + int val = * get; // we find the position where arr[i] will be in the LIS. If it is in the LIS already we do nothing + if (val > arr[i]) + { + // else we remove the bigger element and add a smaller element (which is arr[i]) and continue; + active.erase(get); + active.insert(arr[i]); + } + } + } + return active.size(); // size of the LIS. +} +int main(int argc, char const * argv[]) +{ + int n; + cout << "Enter size of array: "; + cin >> n; + int a[n]; + cout << "Enter array elements: "; + for (int i = 0; i < n; ++i) + { + cin >> a[i]; + } + cout << LIS(a, n) << endl; + return 0; } From 1b3521d86115bd64fd411311c695dea13ae5c75a Mon Sep 17 00:00:00 2001 From: John Law Date: Wed, 9 Oct 2019 00:00:02 +0800 Subject: [PATCH 022/277] Update lca.cpp --- Graph/lca.cpp | 186 +++++++++++++++++++++++++++++--------------------- 1 file changed, 108 insertions(+), 78 deletions(-) diff --git a/Graph/lca.cpp b/Graph/lca.cpp index b0ff12750..70a9e3e42 100644 --- a/Graph/lca.cpp +++ b/Graph/lca.cpp @@ -1,90 +1,120 @@ #include + using namespace std; // Find the lowest common ancestor using binary lifting in O(nlogn) // Zero based indexing // Resource : https://cp-algorithms.com/graph/lca_binary_lifting.html const int N = 1005; -const int LG = log2(N)+1; -struct lca{ - int n; - vector adj[N]; // Graph - int up[LG][N]; // build this table - int level[N]; // get the levels of all of them +const int LG = log2(N) + 1; +struct lca +{ + int n; + vector < int > adj[N]; // Graph + int up[LG][N]; // build this table + int level[N]; // get the levels of all of them - lca(int n_) : n(n_){ - memset(up,-1,sizeof(up)); - memset(level,0,sizeof(level)); - for(int i=0; i>a>>b; a--; b--; - adj[a].push_back(b); - adj[b].push_back(a); - } - level[0] = 0; - dfs(0,-1); - build(); - } - void verify(){ - for(int i=0; i> a >> b; + a--; + b--; + adj[a].push_back(b); + adj[b].push_back(a); + } + level[0] = 0; + dfs(0, -1); + build(); + } + void verify() + { + for (int i = 0; i < n; ++i) + { + cout << i << " : level: " << level[i] << endl; + } + cout << endl; + for (int i = 0; i < LG; ++i) + { + cout << "Power:" << i << ": "; + for (int j = 0; j < n; ++j) + { + cout << up[i][j] << " "; + } + cout << endl; + } + } - void build(){ - for(int i=1; i level[u] ){ swap(u,v); } - // u is at the bottom. - int dist = level[u] - level[v]; - // Go up this much distance - for(int i=LG-1; i>=0; --i){ - if( dist & ( 1 << i) ){ - u = up[i][u]; - } - } - if( u == v ){ return u; } - assert(level[u] == level[v]); - for(int i=LG-1; i>=0; --i){ - if( up[i][u] != up[i][v] ){ - u = up[i][u]; - v = up[i][v]; - } - } - assert(up[0][u] == up[0][v]); - return up[0][u]; - } + void dfs(int node, int par) + { + up[0][node] = par; + for (auto i: adj[node]) + { + if (i != par) + { + level[i] = level[node] + 1; + dfs(i, node); + } + } + } + int query(int u, int v) + { + u--; + v--; + if (level[v] > level[u]) + { + swap(u, v); + } + // u is at the bottom. + int dist = level[u] - level[v]; + // Go up this much distance + for (int i = LG - 1; i >= 0; --i) + { + if (dist & (1 << i)) + { + u = up[i][u]; + } + } + if (u == v) + { + return u; + } + assert(level[u] == level[v]); + for (int i = LG - 1; i >= 0; --i) + { + if (up[i][u] != up[i][v]) + { + u = up[i][u]; + v = up[i][v]; + } + } + assert(up[0][u] == up[0][v]); + return up[0][u]; + } }; -int main(){ - int n; // number of nodes in the tree. - lca l(n); // will take the input in the format given - // n-1 edges of the form - // a b - // Use verify function to see. +int main() +{ + int n; // number of nodes in the tree. + lca l(n); // will take the input in the format given + // n-1 edges of the form + // a b + // Use verify function to see. } From 883d9dc3a42b565580f130e2f4ff427f9fe64be5 Mon Sep 17 00:00:00 2001 From: John Law Date: Wed, 9 Oct 2019 00:01:36 +0800 Subject: [PATCH 023/277] Update bit.cpp --- Range queries/bit.cpp | 118 +++++++++++++++++++++++------------------- 1 file changed, 64 insertions(+), 54 deletions(-) diff --git a/Range queries/bit.cpp b/Range queries/bit.cpp index 1a1d60e36..0a2ba9720 100644 --- a/Range queries/bit.cpp +++ b/Range queries/bit.cpp @@ -1,66 +1,76 @@ // Binary Indexed Tree. #include + using namespace std; -class Bit{ - int n; - vector bit; - inline int offset(int x){ return (x & (-x)); } - - public: - - Bit(vector& arr){ - n = arr.size(); - bit.assign(n+1,0); - for(int i=0; i bit; + inline int offset(int x) + { + return (x & (-x)); } - } - int sum(int id){ - // Get prefix sum upto id. - id++; - int res = 0; - while( id > 0 ){ - res += bit[id]; - id -= offset(id); + public: + + Bit(vector < int > & arr) + { + n = arr.size(); + bit.assign(n + 1, 0); + for (int i = 0; i < n; ++i) + { + update(i, arr[i]); + } + } + Bit(int x) + { + n = x; + bit.assign(n + 1, 0); } - return res; - } - int sum_range(int l, int r){ - return sum(r) - sum(l-1); - } + void update(int id, int val) + { + // Add val at id + id++; + while (id <= n) + { + bit[id] += val; + id += offset(id); + } + } + + int sum(int id) + { + // Get prefix sum upto id. + id++; + int res = 0; + while (id > 0) + { + res += bit[id]; + id -= offset(id); + } + return res; + } + + int sum_range(int l, int r) + { + return sum(r) - sum(l - 1); + } }; +int main() +{ + int n = 5; + vector arr = { 1, 2, 3, 4, 5 }; + Bit x(arr); - -int main(){ - - int n = 5; - vector arr = {1,2,3,4,5}; - Bit x(arr); - - assert(x.sum_range(0,0) == 1); - assert(x.sum_range(0,1) == 3); - assert(x.sum_range(0,2) == 6); - x.update(0,6); - assert(x.sum_range(0,0) == 6); - assert(x.sum_range(0,1) == 8); - assert(x.sum_range(0,2) == 11); - - + assert(x.sum_range(0, 0) == 1); + assert(x.sum_range(0, 1) == 3); + assert(x.sum_range(0, 2) == 6); + x.update(0, 6); + assert(x.sum_range(0, 0) == 6); + assert(x.sum_range(0, 1) == 8); + assert(x.sum_range(0, 2) == 11); + return 0; } From dba806ca60b06611a164283c9bc44c3f3a1f4a22 Mon Sep 17 00:00:00 2001 From: John Law Date: Wed, 9 Oct 2019 00:02:29 +0800 Subject: [PATCH 024/277] Update bit.cpp --- Range queries/bit.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Range queries/bit.cpp b/Range queries/bit.cpp index 0a2ba9720..449177a77 100644 --- a/Range queries/bit.cpp +++ b/Range queries/bit.cpp @@ -6,7 +6,7 @@ using namespace std; class Bit { int n; - vector < int > bit; + vector bit; inline int offset(int x) { return (x & (-x)); @@ -14,7 +14,7 @@ class Bit public: - Bit(vector < int > & arr) + Bit(vector& arr) { n = arr.size(); bit.assign(n + 1, 0); @@ -62,7 +62,7 @@ class Bit int main() { int n = 5; - vector arr = { 1, 2, 3, 4, 5 }; + vector arr = { 1, 2, 3, 4, 5 }; Bit x(arr); assert(x.sum_range(0, 0) == 1); From ae701243c2fa6c94fdeecc6535407c90e15b05de Mon Sep 17 00:00:00 2001 From: John Law Date: Wed, 9 Oct 2019 00:02:49 +0800 Subject: [PATCH 025/277] Update lca.cpp --- Graph/lca.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Graph/lca.cpp b/Graph/lca.cpp index 70a9e3e42..a69a1a5b3 100644 --- a/Graph/lca.cpp +++ b/Graph/lca.cpp @@ -9,7 +9,7 @@ const int LG = log2(N) + 1; struct lca { int n; - vector < int > adj[N]; // Graph + vector adj[N]; // Graph int up[LG][N]; // build this table int level[N]; // get the levels of all of them From f4e1f7f58a2f0ff66462ebc8a16d2a0b32dbc7b3 Mon Sep 17 00:00:00 2001 From: aniakubik Date: Fri, 25 Oct 2019 17:42:51 +0200 Subject: [PATCH 026/277] extended eucildean algorithm --- Math/extendedEuclidian.cpp | 51 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Math/extendedEuclidian.cpp diff --git a/Math/extendedEuclidian.cpp b/Math/extendedEuclidian.cpp new file mode 100644 index 000000000..ad9846a87 --- /dev/null +++ b/Math/extendedEuclidian.cpp @@ -0,0 +1,51 @@ +#include +#include + +using namespace std; + +/* + for numbers a, b returns x, y such as x * a + y * b = gcd(a,b) +*/ + +pair extendedEuclidian(int a, int b) { + int a_old = a, b_old = b; + if(a < b) swap(a,b); + + int x = 0, y = 1, old_x = 1, old_y = 0; + + int quotient, residue; + while (b) { + quotient = a / b; + residue = a % b; + + a = b; + b = residue; + + int temp; + + temp = x; + x = old_x - quotient * x; + old_x = temp; + + + temp = y; + y = old_y - quotient * y; + old_y = temp; + } + + if(b_old > a_old) swap(old_x, old_y); + + return make_pair(old_x, old_y); + +} + +int main() { + + int a, b; + cin >> a >> b; + pair result = extendedEuclidian(a, b); + + cout<< result.first << " " << result.second; + + +} \ No newline at end of file From 566a509c341d83a856d2e70ee089ae562ebbae58 Mon Sep 17 00:00:00 2001 From: walter-ind <52423075+walter-ind@users.noreply.github.com> Date: Sat, 26 Oct 2019 14:36:03 +0530 Subject: [PATCH 027/277] Create LICENSE --- LICENSE | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000..38c6144c1 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 TheAlgorithms + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. From b0c0e8fccee0ace738905d9cd281aff3b29955b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luis=20Fuentes=20Gonz=C3=A1lez?= <47273700+Luisfueg@users.noreply.github.com> Date: Sun, 27 Oct 2019 00:45:55 +0200 Subject: [PATCH 028/277] Upadate Tree.cpp It " : " is unnecessary. (I think) --- Data Structure/Tree.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Data Structure/Tree.cpp b/Data Structure/Tree.cpp index ca6197c5c..9ccc7069b 100644 --- a/Data Structure/Tree.cpp +++ b/Data Structure/Tree.cpp @@ -99,7 +99,7 @@ int main() root->right = NULL; do { - cout << "\n1. Insert : "; + cout << "\n1. Insert"; cout << "\n2. Breadth First"; cout << "\n3. Preorder Depth First"; cout << "\n4. Inorder Depth First"; From 56cfe3f041a3dc65ccbe18ef0783ad73b19a207c Mon Sep 17 00:00:00 2001 From: aniakubik Date: Tue, 29 Oct 2019 22:26:55 +0100 Subject: [PATCH 029/277] added euler totient function --- Math/eulerTotient.cpp | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Math/eulerTotient.cpp diff --git a/Math/eulerTotient.cpp b/Math/eulerTotient.cpp new file mode 100644 index 000000000..c71219641 --- /dev/null +++ b/Math/eulerTotient.cpp @@ -0,0 +1,37 @@ +#include +#include +using namespace std; + +/* +this function calculate euler totien function +*/ + +long long eulerTotient(long long n){ + + if(n == 1) return 1; + long long result = 1LL; + long long temp = n; + for(int i = 2; i <= floor(sqrt(n)) + 10; i++) { + if( temp % i == 0) { + int j = 0; + while(temp % i == 0){ + j ++; + temp /= i; + } + result = result * pow(i,j-1) * (i-1); + } + } + + if(temp == n){ + return n-1; + } + + return result; +} + +int main(){ + long long n; + cin >> n; + cout << eulerTotient(n); + +} \ No newline at end of file From 43cb4ad4eb009ac5ac0624f35fe5a0b76bdf9d43 Mon Sep 17 00:00:00 2001 From: Riot Date: Tue, 5 Nov 2019 01:22:27 +0100 Subject: [PATCH 030/277] playfair --- Others/PlayfairCipher.cpp | 83 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 Others/PlayfairCipher.cpp diff --git a/Others/PlayfairCipher.cpp b/Others/PlayfairCipher.cpp new file mode 100644 index 000000000..fdb327cfc --- /dev/null +++ b/Others/PlayfairCipher.cpp @@ -0,0 +1,83 @@ +#include +#include +#include +#define ENGLISH_ABC "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + +using namespace std; + +inline pair getCoordinate(char*code_table,const char character) { + for (uint8_t x(0); x < 5;x++) { + for (uint8_t y(0); y < 5;y++) { + if (*(code_table + (x * 5) + y) == character) + return make_pair(x, y); + } + } +} +string playfair(string str, string keyword) { + + char code_table[5][5]; + int32_t keyword_index(-1); + + string::iterator str_iter = str.begin(), keywor_iter = keyword.begin(); + + while (str_iter != str.end() || keywor_iter != keyword.end()) + { + if (str_iter != str.end()) { + if ((*str_iter = toupper(*str_iter)) >= 'A' && *str_iter <= 'Z') + str_iter++; + else str.erase(str_iter); + } + if (keywor_iter != keyword.end()) { + if ((*keywor_iter = toupper(*keywor_iter)) >= 'A' && *keywor_iter <= 'Z') + keywor_iter++; + else keyword.erase(keywor_iter); + } + } + if (str.length() == 0)return str; + + keyword.append(ENGLISH_ABC); + for (uint8_t x(0); x < 5;x++) { + for (uint8_t y(0); y < 5;y++) { + while (true) + { + if (keyword.find_first_of(keyword.at(++keyword_index)) == keyword_index){ + code_table[x][y] = keyword.at(keyword_index); + break; + } + } + } + } + + for (string::iterator iter = str.begin() + 1; iter != str.end(); iter+= iter == str.end() - 1 ? 1 : 2) { + if (*(iter - 1) == *iter) + str.insert(iter, 'x'); + } + if (str.length() % 2 != 0) str.append("x"); + + for (string::iterator iter = str.begin(); iter != str.end(); iter += 2) { + pair, pair> character_pair_coordinate; + character_pair_coordinate.first = getCoordinate(&code_table[0][0], *iter); + character_pair_coordinate.second = getCoordinate(&code_table[0][0], *(iter + 1)); + if (character_pair_coordinate.first.first == character_pair_coordinate.second.first) // x1 == x2 + { + *iter = (code_table[character_pair_coordinate.first.first][(character_pair_coordinate.first.second + 1) % 5]); + *(iter + 1) = (code_table[character_pair_coordinate.second.first][(character_pair_coordinate.second.second + 1) % 5]); + } + else if (character_pair_coordinate.first.second == character_pair_coordinate.second.second) //y1 == y2 + { + *iter = (code_table[(character_pair_coordinate.first.first + 1) % 5][character_pair_coordinate.first.second]); + *(iter + 1) = (code_table[(character_pair_coordinate.second.first + 1) % 5][character_pair_coordinate.second.second]); + } + else + { + *iter = (code_table[character_pair_coordinate.first.first ][character_pair_coordinate.second.second]); + *(iter + 1) = (code_table[character_pair_coordinate.second.first][character_pair_coordinate.first.second]); + } + } + + return str; +} +int main(){ + playfair("Welcome from Hungary!","playfair"); //return the encrypted text + return 0; +} From 0cf239a812cd8c1bad79070d98c0e0c69f2b7d42 Mon Sep 17 00:00:00 2001 From: Pooja Gupta Date: Tue, 5 Nov 2019 21:28:23 +0530 Subject: [PATCH 031/277] Created PigeonHole sorting algorithm --- .../PigeonHole sorting algorithm.cpp | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Data Structure/PigeonHole sorting algorithm.cpp diff --git a/Data Structure/PigeonHole sorting algorithm.cpp b/Data Structure/PigeonHole sorting algorithm.cpp new file mode 100644 index 000000000..174f405b9 --- /dev/null +++ b/Data Structure/PigeonHole sorting algorithm.cpp @@ -0,0 +1,45 @@ +#include +using namespace std; +/* Sorts the array using pigeonhole algorithm */ +void pigeonholeSort(int arr[], int n) +{ + // Find minimum and maximum values in arr[] + int min = arr[0], max = arr[0]; + for (int i = 1; i < n; i++) + { + if (arr[i] < min) + min = arr[i]; + if (arr[i] > max) + max = arr[i]; + } + int range = max - min + 1; // Find range + // Create an array of vectors. Size of array + // range. Each vector represents a hole that + // is going to contain matching elements. + vector holes[range]; + // Traverse through input array and put every + // element in its respective hole + for (int i = 0; i < n; i++) + holes[arr[i]-min].push_back(arr[i]); + // Traverse through all holes one by one. For + // every hole, take its elements and put in + // array. + int index = 0; // index in sorted array + for (int i = 0; i < range; i++) + { + vector::iterator it; + for (it = holes[i].begin(); it != holes[i].end(); ++it) + arr[index++] = *it; + } +} + +int main() +{ + int arr[] = {9,2,3,8,1,6,9}; + int n = sizeof(arr)/sizeof(arr[0]); + pigeonholeSort(arr, n); + printf("Sorted order is : "); + for (int i = 0; i < n; i++) + printf("%d ", arr[i]); + return 0; +} From 77376626132f74e57759f16ff555c2d41d5d33dd Mon Sep 17 00:00:00 2001 From: Ashwek Swamy <39827514+ashwek@users.noreply.github.com> Date: Thu, 7 Nov 2019 00:19:34 +0530 Subject: [PATCH 032/277] Rename imp_fun.cpp to Others/vector_important_functions.cpp --- imp_fun.cpp => Others/vector_important_functions.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename imp_fun.cpp => Others/vector_important_functions.cpp (100%) diff --git a/imp_fun.cpp b/Others/vector_important_functions.cpp similarity index 100% rename from imp_fun.cpp rename to Others/vector_important_functions.cpp From 913c0acf2f6f5fdf119046b4be37f58325dbadaf Mon Sep 17 00:00:00 2001 From: Jeong Tae Yong Date: Fri, 8 Nov 2019 18:44:27 +0900 Subject: [PATCH 033/277] Create BeadSort.cpp --- Sorting/BeadSort.cpp | 63 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Sorting/BeadSort.cpp diff --git a/Sorting/BeadSort.cpp b/Sorting/BeadSort.cpp new file mode 100644 index 000000000..c8e27b250 --- /dev/null +++ b/Sorting/BeadSort.cpp @@ -0,0 +1,63 @@ +// C++ program to implement gravity/bead sort +#include +#include +using namespace std; + +#define BEAD(i, j) beads[i * max + j] + +// function to perform the above algorithm +void beadSort(int *a, int len) +{ + // Find the maximum element + int max = a[0]; + for (int i = 1; i < len; i++) + if (a[i] > max) + max = a[i]; + + // allocating memory + unsigned char beads[max*len]; + memset(beads, 0, sizeof(beads)); + + // mark the beads + for (int i = 0; i < len; i++) + for (int j = 0; j < a[i]; j++) + BEAD(i, j) = 1; + + for (int j = 0; j < max; j++) + { + // count how many beads are on each post + int sum = 0; + for (int i=0; i < len; i++) + { + sum += BEAD(i, j); + BEAD(i, j) = 0; + } + + // Move beads down + for (int i = len - sum; i < len; i++) + BEAD(i, j) = 1; + } + + // Put sorted values in array using beads + for (int i = 0; i < len; i++) + { + int j; + for (j = 0; j < max && BEAD(i, j); j++); + + a[i] = j; + } +} + +// driver function to test the algorithm +int main() +{ + int a[] = {5, 3, 1, 7, 4, 1, 1, 20}; + int len = sizeof(a)/sizeof(a[0]); + + beadSort(a, len); + + for (int i = 0; i < len; i++) + printf("%d ", a[i]); + + return 0; +} From 85c3d5aaad5e5f691b28b3a663501a9199ee7217 Mon Sep 17 00:00:00 2001 From: Ashwek Swamy <39827514+ashwek@users.noreply.github.com> Date: Sun, 10 Nov 2019 19:02:54 +0530 Subject: [PATCH 034/277] change header files --- Greedy Algorithms/huffman.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Greedy Algorithms/huffman.cpp b/Greedy Algorithms/huffman.cpp index be3ed4880..253d8d0b5 100644 --- a/Greedy Algorithms/huffman.cpp +++ b/Greedy Algorithms/huffman.cpp @@ -1,5 +1,6 @@ // C++ program for Huffman Coding -#include +#include +#include using namespace std; // A Huffman tree node From 3cd8214e29f8193735a4099272cb4e5d86915e56 Mon Sep 17 00:00:00 2001 From: "MEDICACORP\\bmistry" Date: Mon, 11 Nov 2019 10:28:59 -0500 Subject: [PATCH 035/277] Add template for bug and feature as issue --- .github/ISSUE_TEMPLATE/bug_report.md | 33 +++++++++++++++++++++++ .github/ISSUE_TEMPLATE/feature_request.md | 20 ++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/ISSUE_TEMPLATE/feature_request.md diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 000000000..6506be174 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,33 @@ +--- +name: Bug report +about: Create a report to help us improve. Report bugs found while using the project +title: "[BUG]" +labels: bug +assignees: '' + +--- + + + +## Description + + +## Expected Behavior + + +## Actual Behavior + + +## Possible Fix + + +## Steps to Reproduce + + +1. +2. +3. +4. + +## Context + diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 000000000..2d1696261 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest features, propose improvements, discuss new ideas. +title: "[FEATURE]" +labels: enhancement +assignees: '' + +--- + + + +## Detailed Description + + +## Context + + + +## Possible Implementation + From cb4722e052ff10c217200433bb7f819b48aec49f Mon Sep 17 00:00:00 2001 From: joker123 <56662119+leechiyun@users.noreply.github.com> Date: Tue, 12 Nov 2019 22:39:16 +0900 Subject: [PATCH 036/277] Add files via upload add Pascal's Triangle Algorithm --- Others/Pascal_Triangle.cpp | 52 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Others/Pascal_Triangle.cpp diff --git a/Others/Pascal_Triangle.cpp b/Others/Pascal_Triangle.cpp new file mode 100644 index 000000000..5c3b727c6 --- /dev/null +++ b/Others/Pascal_Triangle.cpp @@ -0,0 +1,52 @@ +#include + +using namespace std; + +int main() +{ + int n = 0; + + cout << "Set Pascal's Triangle Height" << endl; + cin >> n; + + //memory allocation (Assign two-dimensional array to store Pascal triangle) + int **arr = new int*[n]; + for (int i = 0; i < n; ++i) + { + arr[i] = new int[2 * n - 1]; + memset(arr[i], 0, sizeof(int)*(2 * n - 1)); + } + + for (int i = 0; i < n; ++i) + { + for (int j = n-i-1; j < n+i; ++j) + { + if (j == n - i - 1 || j == n + i - 1) + arr[i][j] = 1; //The edge of the Pascal triangle goes in 1 + else + arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j + 1]; + } + } + + //pint Pascal's Triangle + for (int i = 0; i < n; ++i) + { + for (int j = 0; j < n + i; ++j) + { + if (arr[i][j] == 0) + cout << " "; + else + cout << arr[i][j]; + } + cout << endl; + } + + //deallocation + for (int i = 0; i < n; ++i) + { + delete[] arr[i]; + } + delete [] arr; + + return 0; +} \ No newline at end of file From c24422fd35d84a3bb2c40ec7b68f43c714b50123 Mon Sep 17 00:00:00 2001 From: bhaumikmistry Date: Wed, 13 Nov 2019 12:23:29 -0500 Subject: [PATCH 037/277] docs changes to readme files, reformat --- README.md | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 81367fcb4..5418b6316 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,13 @@ -# C++ +# The Algorithms - C++ +[![contributions welcome](https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square)](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTION.md)  +![GitHub repo size](https://img.shields.io/github/repo-size/TheAlgorithms/C-Plus-Plus?color=red&style=flat-square) +![GitHub closed pull requests](https://img.shields.io/github/issues-pr-closed/TheAlgorithms/C-Plus-Plus?color=green&style=flat-square) -This repository contains some useful algorithms and data structures. +### All algorithms implemented in C++ (for education) +The implementations are for learning purpose. They may be less efficient than the implementation in the standard library. -### Contribute +### Contribute Guidelines +Read our [Contribution Guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/README.md) before you contribute How you can contribute? See this small guide. -* Use the directory structure of the repository. -* Please describe your pull requests. -* Don't use **bits/stdc++.h** because this is quite Linux specific and slows down the compiler process. -* Put comments in your code. -* Avoid **struct**. Instead use the **class** keyword. -* Add some test cases in the main-function. -* Can suggest any change in present algorithms(if needed). \ No newline at end of file From 08ed2e21aa0a3f0629f16b3cf8dd4e96ea165d07 Mon Sep 17 00:00:00 2001 From: bhaumikmistry Date: Wed, 13 Nov 2019 12:23:59 -0500 Subject: [PATCH 038/277] feat add contribution file with much more details --- CONTRIBUTION.md | 65 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 CONTRIBUTION.md diff --git a/CONTRIBUTION.md b/CONTRIBUTION.md new file mode 100644 index 000000000..58d2bc828 --- /dev/null +++ b/CONTRIBUTION.md @@ -0,0 +1,65 @@ +# CONTRIBUTION GUIDELINES + +## Before contributing +Welcome to [TheAlgorithms/c-plus-plus](https://github.com/TheAlgorithms/C-Plus-Plus)! Before sending your pull requests, make sure that you **read the whole guidelines**. If you have any doubt on the contribution guide, please feel free to state it clearly in [an issues](https://github.com/TheAlgorithms/C-Plus-Plus/issues/new/choose). + +## Contributing +--- +### Contributor +We are very happy that you consider implementing algorithms and data structure for others! This repository is referenced and used by learners from all over the globe. Being one of our contributors, you agree and confirm that: + +- You did your work. + - No plagiarism allowed. Any plagiarized work will not be merged. +- Your work will be distributed under [MIT License](License) Once your pull request is merged. +- You submitted work fulfils or mostly fulfils our styles and standards. + +**New implementation** New implementation are welcome! +**Improving comments** and **Adding test cases** are also highly welcome. + +### Making Changes + +#### Code +- Use the directory structure of the repository. +- File extension for code should be *.h *.cpp. +- Don't use **bits/stdc++.h** because this is quite Linux specific and slows down the compiler process. +- Avoid using **struct**. Instead use the **class** keyword. +- You can suggest any change in present algorithms(if needed). +- Strictly use snake_case (underscore_separated) in your file names, later to be used by a script. +- If you have modified/added code work, make sure the code compiles before submitting. +- **Be consistent in use of there guidelines when submitting** + +#### Commit Guidelines +- It is recommended to keep your changes grouped logically within individual commits. Contributors and Reviews find it easier to review changes that are silt across multiple commits. +``` +git add file_xyz.cpp +git commit -m "your message" +``` +Examples of commit messages with semantic prefixes: +``` +fix: xyz algorithm bug +feat: add xyx algorithm, class xyz +test: add test for xyz algorithm +docs: add comments and explanation to xyz algorithm +``` +Common prefixes: +- fix: A bug fix +- feat: A new feature +- docs: Documentation changes +- test: Adding missing tests or correcting existing tests + +#### Documentation +- Make sure you put comments in your code. +- Please avoid creating a new directories if at all possible. Try to fit your work into existing directory structure. If you want to create one, please check if the same category has been recently suggested or created by another pull request. +- If you have modified/added documentation work, ensure your language is concise and contains no grammar errors. +- Do not update the README.md along with other changes, first create an issue and link that issue with the pull request to suggest specific changes to README.md + +#### test +- Make sure you add test cases and examples in the main-function. +- If you find any algorithm or document without tests please feel free to create issue of suggest changes. + +### Pull Requests +- Checkout our [pull request template](https://github.com/TheAlgorithms/C-Plus-Plus/.github/pull_request_template.md) + +- Most importantly, + - Happy coding! + From b66f9a569c3468a31944a8afb451c2a38b5a369d Mon Sep 17 00:00:00 2001 From: bhaumikmistry Date: Wed, 13 Nov 2019 12:24:32 -0500 Subject: [PATCH 039/277] feat add pull request template for future contribution guide --- .github/pull_request_template.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 .github/pull_request_template.md diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 000000000..038ba8842 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,20 @@ +#### Description of Change + + +#### Checklist + + +- [ ] Added description of change +- [ ] Added tests and example, test passes +- [ ] Relevant documentation/comments is changed or added +- [ ] PR title follows semantic [commit guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTION.md#Commit-Guidelines) +- [ ] Search previous suggestions before making a new one, as yours may be a duplicate. +- [ ] Sort by alphabetical order +- [ ] I acknowledge that all my contributions will be made under the project's license. + +Notes: \ No newline at end of file From a968f90ea7b85abb7d86473d1b261e3661cfe66e Mon Sep 17 00:00:00 2001 From: bhaumikmistry Date: Wed, 13 Nov 2019 12:34:12 -0500 Subject: [PATCH 040/277] fix add fixes to latest contribution.md file --- CONTRIBUTION.md | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/CONTRIBUTION.md b/CONTRIBUTION.md index 58d2bc828..1f68f9cd5 100644 --- a/CONTRIBUTION.md +++ b/CONTRIBUTION.md @@ -4,7 +4,6 @@ Welcome to [TheAlgorithms/c-plus-plus](https://github.com/TheAlgorithms/C-Plus-Plus)! Before sending your pull requests, make sure that you **read the whole guidelines**. If you have any doubt on the contribution guide, please feel free to state it clearly in [an issues](https://github.com/TheAlgorithms/C-Plus-Plus/issues/new/choose). ## Contributing ---- ### Contributor We are very happy that you consider implementing algorithms and data structure for others! This repository is referenced and used by learners from all over the globe. Being one of our contributors, you agree and confirm that: @@ -29,7 +28,7 @@ We are very happy that you consider implementing algorithms and data structure f - **Be consistent in use of there guidelines when submitting** #### Commit Guidelines -- It is recommended to keep your changes grouped logically within individual commits. Contributors and Reviews find it easier to review changes that are silt across multiple commits. +- It is recommended to keep your changes grouped logically within individual commits. Contributors find it easier to review changes that are silt across multiple commits. ``` git add file_xyz.cpp git commit -m "your message" @@ -53,13 +52,12 @@ Common prefixes: - If you have modified/added documentation work, ensure your language is concise and contains no grammar errors. - Do not update the README.md along with other changes, first create an issue and link that issue with the pull request to suggest specific changes to README.md -#### test +#### Test - Make sure you add test cases and examples in the main-function. - If you find any algorithm or document without tests please feel free to create issue of suggest changes. ### Pull Requests -- Checkout our [pull request template](https://github.com/TheAlgorithms/C-Plus-Plus/.github/pull_request_template.md) +- Checkout our [pull request template](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/.github/pull_request_template.md) - Most importantly, - - Happy coding! - + - Happy coding! \ No newline at end of file From b0a97adb4a3224baceae3946d7952024f53912d9 Mon Sep 17 00:00:00 2001 From: Yang Libin Date: Thu, 14 Nov 2019 19:23:55 +0800 Subject: [PATCH 041/277] docs: update README.md --- README.md | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/README.md b/README.md index 5418b6316..9ca63afac 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,4 @@ The implementations are for learning purpose. They may be less efficient than the implementation in the standard library. ### Contribute Guidelines -Read our [Contribution Guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/README.md) before you contribute - -How you can contribute? See this small guide. - +Read our [Contribution Guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/README.md) before you contribute. From 00fbc7a6905d20ec805987abe38b9e56a1619ece Mon Sep 17 00:00:00 2001 From: Yoonseo Kim <45335586+SophieYoonseo@users.noreply.github.com> Date: Fri, 15 Nov 2019 14:44:55 +0900 Subject: [PATCH 042/277] I modified a link The 'contribution guidelines' link is incorrectly linked, so I fixed it with the correct link. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9ca63afac..a3077cdc5 100644 --- a/README.md +++ b/README.md @@ -7,4 +7,4 @@ The implementations are for learning purpose. They may be less efficient than the implementation in the standard library. ### Contribute Guidelines -Read our [Contribution Guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/README.md) before you contribute. +Read our [Contribution Guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTION.md) before you contribute. From cf36eab3fd3330be3d12c6f82eb81fa4919d2100 Mon Sep 17 00:00:00 2001 From: nikhil kala Date: Fri, 15 Nov 2019 15:18:25 +0530 Subject: [PATCH 043/277] Revert "Created PigeonHole sorting algorithm" --- .../PigeonHole sorting algorithm.cpp | 45 ------------------- 1 file changed, 45 deletions(-) delete mode 100644 Data Structure/PigeonHole sorting algorithm.cpp diff --git a/Data Structure/PigeonHole sorting algorithm.cpp b/Data Structure/PigeonHole sorting algorithm.cpp deleted file mode 100644 index 174f405b9..000000000 --- a/Data Structure/PigeonHole sorting algorithm.cpp +++ /dev/null @@ -1,45 +0,0 @@ -#include -using namespace std; -/* Sorts the array using pigeonhole algorithm */ -void pigeonholeSort(int arr[], int n) -{ - // Find minimum and maximum values in arr[] - int min = arr[0], max = arr[0]; - for (int i = 1; i < n; i++) - { - if (arr[i] < min) - min = arr[i]; - if (arr[i] > max) - max = arr[i]; - } - int range = max - min + 1; // Find range - // Create an array of vectors. Size of array - // range. Each vector represents a hole that - // is going to contain matching elements. - vector holes[range]; - // Traverse through input array and put every - // element in its respective hole - for (int i = 0; i < n; i++) - holes[arr[i]-min].push_back(arr[i]); - // Traverse through all holes one by one. For - // every hole, take its elements and put in - // array. - int index = 0; // index in sorted array - for (int i = 0; i < range; i++) - { - vector::iterator it; - for (it = holes[i].begin(); it != holes[i].end(); ++it) - arr[index++] = *it; - } -} - -int main() -{ - int arr[] = {9,2,3,8,1,6,9}; - int n = sizeof(arr)/sizeof(arr[0]); - pigeonholeSort(arr, n); - printf("Sorted order is : "); - for (int i = 0; i < n; i++) - printf("%d ", arr[i]); - return 0; -} From d36e3f49ba6e37e4f262389fd260ae61d4f22665 Mon Sep 17 00:00:00 2001 From: Riot Date: Fri, 15 Nov 2019 20:27:37 +0100 Subject: [PATCH 044/277] matrix rotation --- .../matrix_layer_rotation.cpp | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Operations on Datastructures/matrix_layer_rotation.cpp diff --git a/Operations on Datastructures/matrix_layer_rotation.cpp b/Operations on Datastructures/matrix_layer_rotation.cpp new file mode 100644 index 000000000..1056b2523 --- /dev/null +++ b/Operations on Datastructures/matrix_layer_rotation.cpp @@ -0,0 +1,52 @@ +#include +#include +using namespace std; +template inline void do_rotate(Type* rotated_matrix, const pair& position, const unsigned &row, const unsigned &columm, const uint8_t inside_row, const uint8_t inside_columm, const uint8_t rotation_position, const Type* const element) { + int*rotated_matrix_walker = (rotated_matrix + position.first * columm + (position.second)); + int offset = 1, element_index = -1; + while (true) + { + if (++element_index == rotation_position) { + *rotated_matrix_walker = *element; + return; + } + rotated_matrix_walker += offset; + if (rotated_matrix + ((position.first * columm) + position.second + inside_columm - 1) == rotated_matrix_walker) offset = columm; + else if (rotated_matrix + ((position.first * columm) + position.second + ((inside_row - 1) * columm) + inside_columm - 1) == rotated_matrix_walker) offset = -1; + else if (rotated_matrix + ((position.first * columm) + position.second + ((inside_row - 1) * columm)) == rotated_matrix_walker) offset = -1 * columm; + } +} +template Type* matrix_rotation(Type * const matrix, const unsigned row, const unsigned column, const unsigned rotation) { + pair position = make_pair(0, 0); + Type *rotated_matrix = new Type[row * column]; + int offset = 1; + int *matrix_walker = matrix; + uint8_t inside_row = row, inside_column = column; + int32_t array_lenght(0), element_index(0); + while (inside_row > 0 && inside_column > 0) + { + array_lenght = (2 * inside_column + ((inside_row - 2) * 2)); + do + { + do_rotate(rotated_matrix, position, row, column, inside_row, inside_column, (rotation + element_index) % array_lenght, matrix_walker); + matrix_walker += offset; + element_index++; + if (matrix + ((position.first * column) + position.second + inside_column - 1) == matrix_walker) offset = column; + else if (matrix + ((position.first * column) + position.second + ((inside_row - 1) * column) + inside_column - 1) == matrix_walker) offset = -1; + else if (matrix + ((position.first * column) + position.second + ((inside_row - 1) * column)) == matrix_walker) offset = -1 * column; + } while ((matrix + (position.first * column + position.second)) != matrix_walker); + position.first++; + position.second++; + inside_row -= 2; + inside_column -= 2; + offset = 1; + matrix_walker = matrix + (position.first * column) + (position.second); + } + return rotated_matrix; +} +int main() +{ + int *matrix = new int[16]{7,20,31,90,9,10,40,8,50,2,70,10,10,20,25,49}; + int*rotated_matrix = matrix_rotation(matrix,4,4,1); + return 0; +} From 2cbd85914d2304f18e8c291cc0e8f788a6a2a6c7 Mon Sep 17 00:00:00 2001 From: joker123 <56662119+leechiyun@users.noreply.github.com> Date: Sun, 17 Nov 2019 15:00:37 +0900 Subject: [PATCH 045/277] Update and rename Pascal_Triangle.cpp to pascal_triangle.cpp change file name and put code inside a function --- ...ascal_Triangle.cpp => pascal_triangle.cpp} | 65 +++++++++++-------- 1 file changed, 38 insertions(+), 27 deletions(-) rename Others/{Pascal_Triangle.cpp => pascal_triangle.cpp} (71%) diff --git a/Others/Pascal_Triangle.cpp b/Others/pascal_triangle.cpp similarity index 71% rename from Others/Pascal_Triangle.cpp rename to Others/pascal_triangle.cpp index 5c3b727c6..b6f762d97 100644 --- a/Others/Pascal_Triangle.cpp +++ b/Others/pascal_triangle.cpp @@ -2,32 +2,8 @@ using namespace std; -int main() +void show_pascal(int **arr, int n) { - int n = 0; - - cout << "Set Pascal's Triangle Height" << endl; - cin >> n; - - //memory allocation (Assign two-dimensional array to store Pascal triangle) - int **arr = new int*[n]; - for (int i = 0; i < n; ++i) - { - arr[i] = new int[2 * n - 1]; - memset(arr[i], 0, sizeof(int)*(2 * n - 1)); - } - - for (int i = 0; i < n; ++i) - { - for (int j = n-i-1; j < n+i; ++j) - { - if (j == n - i - 1 || j == n + i - 1) - arr[i][j] = 1; //The edge of the Pascal triangle goes in 1 - else - arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j + 1]; - } - } - //pint Pascal's Triangle for (int i = 0; i < n; ++i) { @@ -40,13 +16,48 @@ int main() } cout << endl; } +} + +int **pascal_triangle(int **arr, int n) +{ + for (int i = 0; i < n; ++i) + { + for (int j = n - i - 1; j < n + i; ++j) + { + if (j == n - i - 1 || j == n + i - 1) + arr[i][j] = 1; //The edge of the Pascal triangle goes in 1 + else + arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j + 1]; + } + } + + return arr; +} + +int main() +{ + int n = 0; + + cout << "Set Pascal's Triangle Height" << endl; + cin >> n; + //memory allocation (Assign two-dimensional array to store Pascal triangle) + int **arr = new int*[n]; + for (int i = 0; i < n; ++i) + { + arr[i] = new int[2 * n - 1]; + memset(arr[i], 0, sizeof(int)*(2 * n - 1)); + } + + pascal_triangle(arr, n); + show_pascal(arr, n); + //deallocation for (int i = 0; i < n; ++i) { delete[] arr[i]; } - delete [] arr; + delete[] arr; return 0; -} \ No newline at end of file +} From 5da2760d3fba77d88a98c0ad3e61bb13ad639777 Mon Sep 17 00:00:00 2001 From: Anirban Chetia Date: Mon, 18 Nov 2019 20:16:58 +0530 Subject: [PATCH 046/277] Kosaraju Algorithm for SCCs. --- Graph/Kosaraju.cpp | 103 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 Graph/Kosaraju.cpp diff --git a/Graph/Kosaraju.cpp b/Graph/Kosaraju.cpp new file mode 100644 index 000000000..a9131faa8 --- /dev/null +++ b/Graph/Kosaraju.cpp @@ -0,0 +1,103 @@ +/* Implementation of Kosaraju's Algorithm to find out the strongly connected components (SCCs) in a graph. + Author:Anirban166 +*/ + +#include +#include + +using namespace std; + +void print(vector a[],int V) +{ + for(int i=0;i"; + for(int j=0;j &st,bool vis[],vector adj[]) +{ + vis[v]=true; + for(auto i=adj[v].begin();i!=adj[v].end();i++) + { + if(vis[*i]==false) + calculate_time(*i,st,vis,adj); + } + st.push(v); +} +void dfs(int v,bool vis[],vector grev[]) +{ + vis[v]=true; + // cout< adj[]) +{ + // print(adj,V); + bool vis[V]={}; + stack st; + for(int v=0;v>ch; - switch(ch) - { - case 1: - { - int n,m; - do - { - cout<<"enter the value to be inserted in array:-"; - cin>>n; - b.input(n); - cout<<"do you want to add more elements? 1. yes 2. no\n"; - cin>>m; - }while(m!=0); - b.sorting(); - int x; - cout<<"enter the value to be searched in array:-"; - cin>>x; - int k=b.binary(x); - if(k==-1) - { - cout<>n; - b.input(n); - cout<<"do you want to add more elements? 1. yes 2. no\n"; - cin>>m; - }while(m!=0); - b.sorting(); - double x; - cout<<"enter the value to be searched in array:-"; - cin>>x; - int k=b.binary(x); - if(k==-1) - { - cout<>n; - b.input(n); - cout<<"do you want to add more elements? 1. yes 2. no\n"; - cin>>m; - }while(m!=0); - b.sorting(); - char x; - cout<<"enter the value to be searched in array:-"; - cin>>x; - int k=b.binary(x); - if(k==-1) - { - cout<>n; - b.input(n); - cout<<"do you want to add more elements? 1. yes 2. no\n"; - cin>>m; - }while(m!=0); - b.sorting(); - string x; - cout<<"enter the value to be searched in array:-"; - cin>>x; - int k=b.binary(x); - if(k==-1) - { - cout< Date: Fri, 22 Nov 2019 22:44:43 +0530 Subject: [PATCH 049/277] Add detailed function definitions (comments) Updated with proper function definitions Information about method included @param parameter : what it is/explanation included @return return type included --- Graph/Kosaraju.cpp | 39 +++++++++++++++++++++++++++++---------- 1 file changed, 29 insertions(+), 10 deletions(-) diff --git a/Graph/Kosaraju.cpp b/Graph/Kosaraju.cpp index ca747bdbc..2e66f131f 100644 --- a/Graph/Kosaraju.cpp +++ b/Graph/Kosaraju.cpp @@ -7,14 +7,12 @@ using namespace std; -/*Common terms/anotations used as parameters in functions below: - V: number of vertices, - adj[]: array of vectors to represent graph, - vis[]: array to keep track of visited nodes, (boolean type) - grev[]: graph with reverse edges. -*/ - -//iterative function/method to print graph: +/** +* Iterative function/method to print graph: +* @param a[] : array of vectors (2D) +* @param V : vertices +* @return void +**/ void print(vector a[],int V) { for(int i=0;i a[],int V) } } -//recursive function/method to push vertices into stack passed as parameter: (referenced) +/** +* //Recursive function/method to push vertices into stack passed as parameter: +* @param v : vertices +* @param &st : stack passed by reference +* @param vis[] : array to keep track of visited nodes (boolean type) +* @param adj[] : array of vectors to represent graph +* @return void +**/ void push_vertex(int v,stack &st,bool vis[],vector adj[]) { vis[v]=true; @@ -40,7 +45,14 @@ void push_vertex(int v,stack &st,bool vis[],vector adj[]) st.push(v); } -//recursive function/method to implement depth first traversal(dfs): + +/** +* //Recursive function/method to implement depth first traversal(dfs): +* @param v : vertices +* @param vis[] : array to keep track of visited nodes (boolean type) +* @param grev[] : graph with reversed edges +* @return void +**/ void dfs(int v,bool vis[],vector grev[]) { vis[v]=true; @@ -53,6 +65,13 @@ void dfs(int v,bool vis[],vector grev[]) } //function/method to implement Kosaraju's Algorithm: +/** +* Info about the method +* @param V : vertices in graph +* @param adj[] : array of vectors that represent a graph (adjacency list/array) +* @return int ( 0, 1, 2..and so on, only unsigned values as either there can be no SCCs i.e. none(0) or there will be x no. of SCCs (x>0)) + i.e. it returns the count of (number of) strongly connected components (SCCs) in the graph. (variable 'count_scc' within function) +**/ int kosaraju(int V, vector adj[]) { bool vis[V]={}; From ce655b716bbd311ed9d2c5b30f39af3523763979 Mon Sep 17 00:00:00 2001 From: Bhaumik Mistry Date: Fri, 22 Nov 2019 17:09:52 -0500 Subject: [PATCH 050/277] Rename Kosaraju.cpp to kosaraju.cpp Change file name. --- Graph/{Kosaraju.cpp => kosaraju.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Graph/{Kosaraju.cpp => kosaraju.cpp} (100%) diff --git a/Graph/Kosaraju.cpp b/Graph/kosaraju.cpp similarity index 100% rename from Graph/Kosaraju.cpp rename to Graph/kosaraju.cpp From f8e1cb388c8ab0cb31eb6dc545f73654faae1471 Mon Sep 17 00:00:00 2001 From: bhaumikmistry Date: Mon, 25 Nov 2019 10:49:48 -0500 Subject: [PATCH 051/277] feat/ add new file name guidelines --- .github/pull_request_template.md | 3 ++- CONTRIBUTION.md | 10 ++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 038ba8842..efaaf3765 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -10,7 +10,8 @@ Contributors guide: https://github.com/TheAlgorithms/C-Plus-Plus/CONTRIBUTION.md - [ ] Added description of change -- [ ] Added tests and example, test passes +- [ ] Added file name matches [File name guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTION.md#New-File-Name-guidelines) +- [ ] Added tests and example, test must pass - [ ] Relevant documentation/comments is changed or added - [ ] PR title follows semantic [commit guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTION.md#Commit-Guidelines) - [ ] Search previous suggestions before making a new one, as yours may be a duplicate. diff --git a/CONTRIBUTION.md b/CONTRIBUTION.md index 1f68f9cd5..df2a6b915 100644 --- a/CONTRIBUTION.md +++ b/CONTRIBUTION.md @@ -27,6 +27,16 @@ We are very happy that you consider implementing algorithms and data structure f - If you have modified/added code work, make sure the code compiles before submitting. - **Be consistent in use of there guidelines when submitting** +#### New File Name guidelines +- Use lowercase words with ``"_"`` as separator +- For instance +``` +MyNewCppClass.cpp is incorrect +my_new_cpp_class.cpp is correct format +``` +- It will be used to dynamically create a directory of files and implementation. +- File name validation will run on docker to ensure the validity. + #### Commit Guidelines - It is recommended to keep your changes grouped logically within individual commits. Contributors find it easier to review changes that are silt across multiple commits. ``` From 8abb4aa1f917d56427babf45c3e2a5ab1a0a89b6 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Tue, 26 Nov 2019 18:59:21 +0100 Subject: [PATCH 052/277] GitHub Action to run cpplint on all pull requests --- .github/workflows/ccpp.yml | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 .github/workflows/ccpp.yml diff --git a/.github/workflows/ccpp.yml b/.github/workflows/ccpp.yml new file mode 100644 index 000000000..c71d39918 --- /dev/null +++ b/.github/workflows/ccpp.yml @@ -0,0 +1,10 @@ +name: cpplint +on: [push, pull_request] +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + - uses: actions/setup-python@v1 + - run: pip install cpplint + - run: cpplint --recursive . From d9241950166254139b2a4c647b78b1858ae94bec Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 27 Nov 2019 00:15:06 +0100 Subject: [PATCH 053/277] cpplint --counting=detailed --recursive . --- .github/workflows/ccpp.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ccpp.yml b/.github/workflows/ccpp.yml index c71d39918..b7c0baa9a 100644 --- a/.github/workflows/ccpp.yml +++ b/.github/workflows/ccpp.yml @@ -7,4 +7,4 @@ jobs: - uses: actions/checkout@v1 - uses: actions/setup-python@v1 - run: pip install cpplint - - run: cpplint --recursive . + - run: cpplint --counting=detailed --recursive . From 88c7121c84ad9ef59fc8f81a8cfaed049f3c4cd0 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 27 Nov 2019 00:29:00 +0100 Subject: [PATCH 054/277] --filter --- .github/workflows/ccpp.yml | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ccpp.yml b/.github/workflows/ccpp.yml index b7c0baa9a..f6a71b6d3 100644 --- a/.github/workflows/ccpp.yml +++ b/.github/workflows/ccpp.yml @@ -7,4 +7,11 @@ jobs: - uses: actions/checkout@v1 - uses: actions/setup-python@v1 - run: pip install cpplint - - run: cpplint --counting=detailed --recursive . + - run: | + cpplint --filter=-build/include_order,-build/namespaces,-legal/copyright,\ + -readability/casting,-readability/todo,-runtime/arrays,-runtime/explicit,\ + -runtime/int,-runtime/references,-runtime/threadsafe_fn,-whitespace --recursive . +# whitespace/blank_line,-whitespace/braces,-whitespace/comma,-whitespace/comments +# whitespace/empty_loop_body,-whitespace/end_of_line,-whitespace/ending_newline +# whitespace/forcolon,-whitespace/indent,-whitespace/line_length,-whitespace/newline +# whitespace/operators,-whitespace/parens,-whitespace/semicolon,-whitespace/tab --recursive . From 4f65b23c36af444a1d9d39a71e6cceaec6f6c5c5 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 27 Nov 2019 00:34:26 +0100 Subject: [PATCH 055/277] No backslash --- .github/workflows/ccpp.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ccpp.yml b/.github/workflows/ccpp.yml index f6a71b6d3..2c0556259 100644 --- a/.github/workflows/ccpp.yml +++ b/.github/workflows/ccpp.yml @@ -8,8 +8,8 @@ jobs: - uses: actions/setup-python@v1 - run: pip install cpplint - run: | - cpplint --filter=-build/include_order,-build/namespaces,-legal/copyright,\ - -readability/casting,-readability/todo,-runtime/arrays,-runtime/explicit,\ + cpplint --filter=-build/include_order,-build/namespaces,-legal/copyright, + -readability/casting,-readability/todo,-runtime/arrays,-runtime/explicit, -runtime/int,-runtime/references,-runtime/threadsafe_fn,-whitespace --recursive . # whitespace/blank_line,-whitespace/braces,-whitespace/comma,-whitespace/comments # whitespace/empty_loop_body,-whitespace/end_of_line,-whitespace/ending_newline From 60cd628762e1fddb9bb4d855ce98f0917bcec0de Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 27 Nov 2019 00:38:20 +0100 Subject: [PATCH 056/277] cpplint --filter=-build,-legal,-readability,-runtime,-whitespace --recursive . --- .github/workflows/ccpp.yml | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/.github/workflows/ccpp.yml b/.github/workflows/ccpp.yml index 2c0556259..03c76db29 100644 --- a/.github/workflows/ccpp.yml +++ b/.github/workflows/ccpp.yml @@ -7,11 +7,5 @@ jobs: - uses: actions/checkout@v1 - uses: actions/setup-python@v1 - run: pip install cpplint - - run: | - cpplint --filter=-build/include_order,-build/namespaces,-legal/copyright, - -readability/casting,-readability/todo,-runtime/arrays,-runtime/explicit, - -runtime/int,-runtime/references,-runtime/threadsafe_fn,-whitespace --recursive . -# whitespace/blank_line,-whitespace/braces,-whitespace/comma,-whitespace/comments -# whitespace/empty_loop_body,-whitespace/end_of_line,-whitespace/ending_newline -# whitespace/forcolon,-whitespace/indent,-whitespace/line_length,-whitespace/newline -# whitespace/operators,-whitespace/parens,-whitespace/semicolon,-whitespace/tab --recursive . + - run: cpplint --filter= + - run: cpplint --filter=-build,-legal,-readability,-runtime,-whitespace --recursive . From 639e46f023b41b2efaa92c5efc540fe03515dd19 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 27 Nov 2019 00:50:33 +0100 Subject: [PATCH 057/277] Add TODO --- .github/workflows/ccpp.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ccpp.yml b/.github/workflows/ccpp.yml index 03c76db29..744fd7c48 100644 --- a/.github/workflows/ccpp.yml +++ b/.github/workflows/ccpp.yml @@ -7,5 +7,6 @@ jobs: - uses: actions/checkout@v1 - uses: actions/setup-python@v1 - run: pip install cpplint - - run: cpplint --filter= + # - run: cpplint --filter= # print out all cpplint rules + # TODO: Remove each filter one at a time and fix those failures - run: cpplint --filter=-build,-legal,-readability,-runtime,-whitespace --recursive . From 1568b2bc1b5eab8cc95cbeff2ecc7982c423a516 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 27 Nov 2019 14:17:48 +0100 Subject: [PATCH 058/277] Create validate_new_filenames.yml Just like #640 but: 1. Does a git diff and only checks newly added .cpp files 2. Embeds the Python code directly in the .yml file --- .github/workflows/validate_new_filenames.yml | 37 ++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 .github/workflows/validate_new_filenames.yml diff --git a/.github/workflows/validate_new_filenames.yml b/.github/workflows/validate_new_filenames.yml new file mode 100644 index 000000000..2da1638e1 --- /dev/null +++ b/.github/workflows/validate_new_filenames.yml @@ -0,0 +1,37 @@ +name: validate_new_filenames +on: [push, pull_request] +jobs: + validate_new_filenames: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + - run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY + - run: git diff origin/master --name-only > git_diff.txt + - name: Validate new filenames + shell: python + run: | + import os + import sys + print(sys.version_info) # legacy Python :-( + with open("git_diff.txt") as in_file: + cpp_files = sorted(line.strip() for line in in_file + if line.strip().lower().endswith(".cpp")) + + upper_files = [file for file in cpp_files if file != file.lower()] + if upper_files: + print("{} files contain uppercase characters:".format(len(upper_files))) + print("\n".join(upper_files) + "\n") + + space_files = [file for file in cpp_files if " " in file or "-" in file] + if space_files: + print("{} files contain space or dash characters:".format(len(space_files))) + print("\n".join(space_files) + "\n") + + nodir_files = [file for file in cpp_files if os.sep not in file] + if nodir_files: + print("{} files are not in a directory:".format(len(nodir_files))) + print("\n".join(nodir_files) + "\n") + + bad_files = len(upper_files + space_files + nodir_files) + if bad_files: + sys.exit(bad_files) From 56aeed2d18b4951e6010891bee98d73f8c7ad154 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 27 Nov 2019 14:36:03 +0100 Subject: [PATCH 059/277] Update and rename ccpp.yml to cpplint.yml --- .github/workflows/{ccpp.yml => cpplint.yml} | 1 + 1 file changed, 1 insertion(+) rename .github/workflows/{ccpp.yml => cpplint.yml} (85%) diff --git a/.github/workflows/ccpp.yml b/.github/workflows/cpplint.yml similarity index 85% rename from .github/workflows/ccpp.yml rename to .github/workflows/cpplint.yml index 744fd7c48..a6999e1f2 100644 --- a/.github/workflows/ccpp.yml +++ b/.github/workflows/cpplint.yml @@ -8,5 +8,6 @@ jobs: - uses: actions/setup-python@v1 - run: pip install cpplint # - run: cpplint --filter= # print out all cpplint rules + - run: cpplint --recursive . || true # all issues to be fixed # TODO: Remove each filter one at a time and fix those failures - run: cpplint --filter=-build,-legal,-readability,-runtime,-whitespace --recursive . From 2d150ee37e0e82795cd9f925dc35a32d3c8bb3b5 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 27 Nov 2019 14:46:36 +0100 Subject: [PATCH 060/277] Allow directories to have spaces and uppercase --- .github/workflows/validate_new_filenames.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/validate_new_filenames.yml b/.github/workflows/validate_new_filenames.yml index 2da1638e1..f201829da 100644 --- a/.github/workflows/validate_new_filenames.yml +++ b/.github/workflows/validate_new_filenames.yml @@ -17,12 +17,12 @@ jobs: cpp_files = sorted(line.strip() for line in in_file if line.strip().lower().endswith(".cpp")) - upper_files = [file for file in cpp_files if file != file.lower()] + upper_files = [file for file in cpp_files if os.path.basename(file) != os.path.basename(file).lower()] if upper_files: print("{} files contain uppercase characters:".format(len(upper_files))) print("\n".join(upper_files) + "\n") - space_files = [file for file in cpp_files if " " in file or "-" in file] + space_files = [file for file in cpp_files if " " in os.path.basename(file) or "-" in file] if space_files: print("{} files contain space or dash characters:".format(len(space_files))) print("\n".join(space_files) + "\n") From 44f05754bf4e34ef406e0691c566cc2afac9e6ab Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 27 Nov 2019 14:48:57 +0100 Subject: [PATCH 061/277] Rename Graph Coloring.cpp to graph_coloring.cpp --- Backtracking/{Graph Coloring.cpp => graph_coloring.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Backtracking/{Graph Coloring.cpp => graph_coloring.cpp} (100%) diff --git a/Backtracking/Graph Coloring.cpp b/Backtracking/graph_coloring.cpp similarity index 100% rename from Backtracking/Graph Coloring.cpp rename to Backtracking/graph_coloring.cpp From a630058d494aea780319ef651b2040a0af4d15a3 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 27 Nov 2019 14:49:47 +0100 Subject: [PATCH 062/277] Rename N Queens.cpp to n_queens.cpp --- Backtracking/{N Queens.cpp => n_queens.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Backtracking/{N Queens.cpp => n_queens.cpp} (100%) diff --git a/Backtracking/N Queens.cpp b/Backtracking/n_queens.cpp similarity index 100% rename from Backtracking/N Queens.cpp rename to Backtracking/n_queens.cpp From cb064e5ce12c22356fd71c0841f9a98abc55a74d Mon Sep 17 00:00:00 2001 From: Bhaumik Mistry Date: Wed, 27 Nov 2019 10:07:55 -0500 Subject: [PATCH 063/277] Update and rename knight-tour.cpp to knight_tour.cpp Add information about the file for brief intro --- Backtracking/{knight-tour.cpp => knight_tour.cpp} | 9 +++++++++ 1 file changed, 9 insertions(+) rename Backtracking/{knight-tour.cpp => knight_tour.cpp} (78%) diff --git a/Backtracking/knight-tour.cpp b/Backtracking/knight_tour.cpp similarity index 78% rename from Backtracking/knight-tour.cpp rename to Backtracking/knight_tour.cpp index 978a2d34b..f1bc9f72f 100644 --- a/Backtracking/knight-tour.cpp +++ b/Backtracking/knight_tour.cpp @@ -1,5 +1,14 @@ #include # define n 8 + +/** +A knight's tour is a sequence of moves of a knight on a chessboard +such that the knight visits every square only once. If the knight +ends on a square that is one knight's move from the beginning +square (so that it could tour the board again immediately, following +the same path), the tour is closed; otherwise, it is open. +**/ + using namespace std; bool issafe(int x,int y,int sol[n][n]) { From 488cfb7b816b2e7ecefe3e4abb24277dacfba9ca Mon Sep 17 00:00:00 2001 From: Bhaumik Mistry Date: Wed, 27 Nov 2019 10:24:21 -0500 Subject: [PATCH 064/277] Rename Rat_maze.cpp to rat_maze.cpp --- Backtracking/{Rat_maze.cpp => rat_maze.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Backtracking/{Rat_maze.cpp => rat_maze.cpp} (100%) diff --git a/Backtracking/Rat_maze.cpp b/Backtracking/rat_maze.cpp similarity index 100% rename from Backtracking/Rat_maze.cpp rename to Backtracking/rat_maze.cpp From 7a8b5c93462ccb809d89219fff5cd9b089b6ac8f Mon Sep 17 00:00:00 2001 From: bhaumikmistry Date: Wed, 27 Nov 2019 10:26:36 -0500 Subject: [PATCH 065/277] add new guidelines --- CONTRIBUTION.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTION.md b/CONTRIBUTION.md index df2a6b915..902ceea6e 100644 --- a/CONTRIBUTION.md +++ b/CONTRIBUTION.md @@ -31,14 +31,14 @@ We are very happy that you consider implementing algorithms and data structure f - Use lowercase words with ``"_"`` as separator - For instance ``` -MyNewCppClass.cpp is incorrect +MyNewCppClass.CPP is incorrect my_new_cpp_class.cpp is correct format ``` - It will be used to dynamically create a directory of files and implementation. - File name validation will run on docker to ensure the validity. #### Commit Guidelines -- It is recommended to keep your changes grouped logically within individual commits. Contributors find it easier to review changes that are silt across multiple commits. +- It is recommended to keep your changes grouped logically within individual commits. Contributors find it easier to review changes that are split across multiple commits. ``` git add file_xyz.cpp git commit -m "your message" From 194b039001fd3941bc020d15fda1c026add5476c Mon Sep 17 00:00:00 2001 From: bhaumikmistry Date: Wed, 27 Nov 2019 10:43:53 -0500 Subject: [PATCH 066/277] add directory guidelines --- CONTRIBUTION.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CONTRIBUTION.md b/CONTRIBUTION.md index 902ceea6e..a9cb80f49 100644 --- a/CONTRIBUTION.md +++ b/CONTRIBUTION.md @@ -37,6 +37,16 @@ my_new_cpp_class.cpp is correct format - It will be used to dynamically create a directory of files and implementation. - File name validation will run on docker to ensure the validity. +#### New Directory guidelines +- Use lowercase words with ``"_"`` as separator ( no spaces or '-' allowed ) +- For instance +``` +SomeNew Fancy-Category is incorrect +some_new_fancy_category is correct + +- It will be used to dynamically create a directory of files and implementation. +- File name validation will run on docker to ensure the validity. + #### Commit Guidelines - It is recommended to keep your changes grouped logically within individual commits. Contributors find it easier to review changes that are split across multiple commits. ``` From 886960a3c243e6bd39a2b1874c95a050ff162556 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 28 Nov 2019 10:27:27 +0100 Subject: [PATCH 067/277] Add cpplint to validate_filenames (#643) * Add cpplint to validate_filenames * Update and rename Happy_number.cpp to happy_number.cpp * Update validate_new_filenames.yml * pip install cpplint * python3 -m pip install cpplint * python3 -m pip install --useer cpplint * python3 -m pip install --user cpplint * Update validate_new_filenames.yml * sudo python3 -m pip install cpplint * sudo python3 -m pip install cpplint * uses: actions/setup-python@v1 * Run cpplint first * cpp_exts * tuple * cpplint_modified_files --- ...lenames.yml => cpplint_modified_files.yml} | 25 ++++++++++++++----- Others/{Happy_number.cpp => happy_number.cpp} | 23 ++++++++--------- 2 files changed, 30 insertions(+), 18 deletions(-) rename .github/workflows/{validate_new_filenames.yml => cpplint_modified_files.yml} (60%) rename Others/{Happy_number.cpp => happy_number.cpp} (53%) diff --git a/.github/workflows/validate_new_filenames.yml b/.github/workflows/cpplint_modified_files.yml similarity index 60% rename from .github/workflows/validate_new_filenames.yml rename to .github/workflows/cpplint_modified_files.yml index f201829da..d1d850c1d 100644 --- a/.github/workflows/validate_new_filenames.yml +++ b/.github/workflows/cpplint_modified_files.yml @@ -1,21 +1,34 @@ -name: validate_new_filenames +name: cpplint_modified_files on: [push, pull_request] jobs: - validate_new_filenames: + cpplint_modified_files: runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 + - uses: actions/setup-python@v1 + - run: python -m pip install cpplint - run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - run: git diff origin/master --name-only > git_diff.txt - - name: Validate new filenames + - name: cpplint_modified_files shell: python run: | import os + import subprocess import sys - print(sys.version_info) # legacy Python :-( + + print("Python {}.{}.{}".format(*sys.version_info)) # legacy Python :-( with open("git_diff.txt") as in_file: - cpp_files = sorted(line.strip() for line in in_file - if line.strip().lower().endswith(".cpp")) + modified_files = sorted(in_file.read().splitlines()) + print("{} files were modified.".format(len(modified_files))) + + cpp_exts = tuple(".c .c++ .cc .cpp .cu .cuh .cxx .h .h++ .hh .hpp .hxx".split()) + cpp_files = [file for file in modified_files if file.lower().endswith(cpp_exts)] + print("{} C++ files were modified.".format(len(cpp_files))) + if not cpp_files: + sys.exit(0) + + print("cpplint:") + print(subprocess.check_output(["cpplint"] + cpp_files).decode("utf-8")) upper_files = [file for file in cpp_files if os.path.basename(file) != os.path.basename(file).lower()] if upper_files: diff --git a/Others/Happy_number.cpp b/Others/happy_number.cpp similarity index 53% rename from Others/Happy_number.cpp rename to Others/happy_number.cpp index f1b100810..7d25a1bbd 100644 --- a/Others/Happy_number.cpp +++ b/Others/happy_number.cpp @@ -1,19 +1,18 @@ /* A happy number is a number whose sum of digits is calculated until the sum is a single digit, and this sum turns out to be 1 */ -#include -using namespace std; -int main() -{ +// Copyright 2019 TheAlgorithms contributors + +#include + +int main() { int n, k, s = 0, d; - cout << "Enter a number:"; - cin >> n; + std::cout << "Enter a number:"; + std::cin >> n; s = 0; k = n; - while (k > 9) - { - while (k != 0) - { + while (k > 9) { + while (k != 0) { d = k % 10; s += d; k /= 10; @@ -22,8 +21,8 @@ int main() s = 0; } if (k == 1) - cout << n << " is a happy number" << endl; + std::cout << n << " is a happy number" << std::endl; else - cout << n << " is not a happy number" << endl; + std::cout << n << " is not a happy number" << std::endl; return 0; } From fb2bef8cd0d350307ce72bd7f5b3dc6d115e49e5 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 28 Nov 2019 13:28:16 +0100 Subject: [PATCH 068/277] rename Range queries -> range_queries (#646) --- {Range queries => range_queries}/FenwickTree.cpp | 0 {Range queries => range_queries}/MO.cpp | 0 {Range queries => range_queries}/bit.cpp | 0 {Range queries => range_queries}/segTree.cpp | 0 4 files changed, 0 insertions(+), 0 deletions(-) rename {Range queries => range_queries}/FenwickTree.cpp (100%) rename {Range queries => range_queries}/MO.cpp (100%) rename {Range queries => range_queries}/bit.cpp (100%) rename {Range queries => range_queries}/segTree.cpp (100%) diff --git a/Range queries/FenwickTree.cpp b/range_queries/FenwickTree.cpp similarity index 100% rename from Range queries/FenwickTree.cpp rename to range_queries/FenwickTree.cpp diff --git a/Range queries/MO.cpp b/range_queries/MO.cpp similarity index 100% rename from Range queries/MO.cpp rename to range_queries/MO.cpp diff --git a/Range queries/bit.cpp b/range_queries/bit.cpp similarity index 100% rename from Range queries/bit.cpp rename to range_queries/bit.cpp diff --git a/Range queries/segTree.cpp b/range_queries/segTree.cpp similarity index 100% rename from Range queries/segTree.cpp rename to range_queries/segTree.cpp From fc7e4160308dbdee72eaf817be2973cf1310ee3c Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 28 Nov 2019 13:28:41 +0100 Subject: [PATCH 069/277] rename Data Structure -> data_structure (#644) --- {Data Structure => data_structure}/AVLtree.cpp | 0 {Data Structure => data_structure}/Binary Search Tree.cpp | 0 {Data Structure => data_structure}/Binaryheap.cpp | 0 {Data Structure => data_structure}/Doubly Linked List.cpp | 0 {Data Structure => data_structure}/Linked List.cpp | 0 {Data Structure => data_structure}/List Array.cpp | 0 {Data Structure => data_structure}/MorrisInorder.cpp | 0 {Data Structure => data_structure}/Queue Using Array.cpp | 0 {Data Structure => data_structure}/Queue Using Linked List.cpp | 0 {Data Structure => data_structure}/Stack Using Array.cpp | 0 {Data Structure => data_structure}/Stack Using Linked List.cpp | 0 {Data Structure => data_structure}/Tree.cpp | 0 {Data Structure => data_structure}/TrieTree.cpp | 0 .../circular_Queue_using_Linked_List.cpp | 0 .../linkedList_implentation_usingArray.cpp | 0 15 files changed, 0 insertions(+), 0 deletions(-) rename {Data Structure => data_structure}/AVLtree.cpp (100%) rename {Data Structure => data_structure}/Binary Search Tree.cpp (100%) rename {Data Structure => data_structure}/Binaryheap.cpp (100%) rename {Data Structure => data_structure}/Doubly Linked List.cpp (100%) rename {Data Structure => data_structure}/Linked List.cpp (100%) rename {Data Structure => data_structure}/List Array.cpp (100%) rename {Data Structure => data_structure}/MorrisInorder.cpp (100%) rename {Data Structure => data_structure}/Queue Using Array.cpp (100%) rename {Data Structure => data_structure}/Queue Using Linked List.cpp (100%) rename {Data Structure => data_structure}/Stack Using Array.cpp (100%) rename {Data Structure => data_structure}/Stack Using Linked List.cpp (100%) rename {Data Structure => data_structure}/Tree.cpp (100%) rename {Data Structure => data_structure}/TrieTree.cpp (100%) rename {Data Structure => data_structure}/circular_Queue_using_Linked_List.cpp (100%) rename {Data Structure => data_structure}/linkedList_implentation_usingArray.cpp (100%) diff --git a/Data Structure/AVLtree.cpp b/data_structure/AVLtree.cpp similarity index 100% rename from Data Structure/AVLtree.cpp rename to data_structure/AVLtree.cpp diff --git a/Data Structure/Binary Search Tree.cpp b/data_structure/Binary Search Tree.cpp similarity index 100% rename from Data Structure/Binary Search Tree.cpp rename to data_structure/Binary Search Tree.cpp diff --git a/Data Structure/Binaryheap.cpp b/data_structure/Binaryheap.cpp similarity index 100% rename from Data Structure/Binaryheap.cpp rename to data_structure/Binaryheap.cpp diff --git a/Data Structure/Doubly Linked List.cpp b/data_structure/Doubly Linked List.cpp similarity index 100% rename from Data Structure/Doubly Linked List.cpp rename to data_structure/Doubly Linked List.cpp diff --git a/Data Structure/Linked List.cpp b/data_structure/Linked List.cpp similarity index 100% rename from Data Structure/Linked List.cpp rename to data_structure/Linked List.cpp diff --git a/Data Structure/List Array.cpp b/data_structure/List Array.cpp similarity index 100% rename from Data Structure/List Array.cpp rename to data_structure/List Array.cpp diff --git a/Data Structure/MorrisInorder.cpp b/data_structure/MorrisInorder.cpp similarity index 100% rename from Data Structure/MorrisInorder.cpp rename to data_structure/MorrisInorder.cpp diff --git a/Data Structure/Queue Using Array.cpp b/data_structure/Queue Using Array.cpp similarity index 100% rename from Data Structure/Queue Using Array.cpp rename to data_structure/Queue Using Array.cpp diff --git a/Data Structure/Queue Using Linked List.cpp b/data_structure/Queue Using Linked List.cpp similarity index 100% rename from Data Structure/Queue Using Linked List.cpp rename to data_structure/Queue Using Linked List.cpp diff --git a/Data Structure/Stack Using Array.cpp b/data_structure/Stack Using Array.cpp similarity index 100% rename from Data Structure/Stack Using Array.cpp rename to data_structure/Stack Using Array.cpp diff --git a/Data Structure/Stack Using Linked List.cpp b/data_structure/Stack Using Linked List.cpp similarity index 100% rename from Data Structure/Stack Using Linked List.cpp rename to data_structure/Stack Using Linked List.cpp diff --git a/Data Structure/Tree.cpp b/data_structure/Tree.cpp similarity index 100% rename from Data Structure/Tree.cpp rename to data_structure/Tree.cpp diff --git a/Data Structure/TrieTree.cpp b/data_structure/TrieTree.cpp similarity index 100% rename from Data Structure/TrieTree.cpp rename to data_structure/TrieTree.cpp diff --git a/Data Structure/circular_Queue_using_Linked_List.cpp b/data_structure/circular_Queue_using_Linked_List.cpp similarity index 100% rename from Data Structure/circular_Queue_using_Linked_List.cpp rename to data_structure/circular_Queue_using_Linked_List.cpp diff --git a/Data Structure/linkedList_implentation_usingArray.cpp b/data_structure/linkedList_implentation_usingArray.cpp similarity index 100% rename from Data Structure/linkedList_implentation_usingArray.cpp rename to data_structure/linkedList_implentation_usingArray.cpp From 5c241487aa2cd9b44afe4998a2ee168c8a80cc6d Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 28 Nov 2019 13:29:01 +0100 Subject: [PATCH 070/277] rename Dynamic Programming -> dynamic_programming (#645) * rename Dynamic Programming -> dynamic_programming * rename dynamic-programming -> dynamic_programming --- {Dynamic Programming => dynamic_programming}/0-1 Knapsack.cpp | 0 {Dynamic Programming => dynamic_programming}/Armstrong Number.cpp | 0 {Dynamic Programming => dynamic_programming}/Bellman-Ford.cpp | 0 {Dynamic Programming => dynamic_programming}/Catalan-Numbers.cpp | 0 {Dynamic Programming => dynamic_programming}/Coin-Change.cpp | 0 {Dynamic Programming => dynamic_programming}/Cut Rod.cpp | 0 {Dynamic Programming => dynamic_programming}/Edit Distance.cpp | 0 .../Egg-Dropping-Puzzle.cpp | 0 .../Fibonacci_Bottom_Up.cpp | 0 .../Fibonacci_Top_Down.cpp | 0 {Dynamic Programming => dynamic_programming}/Floyd-Warshall.cpp | 0 .../Longest Common Subsequence.cpp | 0 .../Longest Increasing Subsequence (nlogn).cpp | 0 .../Longest Increasing Subsequence.cpp | 0 .../Matrix-Chain-Multiplication.cpp | 0 .../longest_common_string.cpp | 0 16 files changed, 0 insertions(+), 0 deletions(-) rename {Dynamic Programming => dynamic_programming}/0-1 Knapsack.cpp (100%) rename {Dynamic Programming => dynamic_programming}/Armstrong Number.cpp (100%) rename {Dynamic Programming => dynamic_programming}/Bellman-Ford.cpp (100%) rename {Dynamic Programming => dynamic_programming}/Catalan-Numbers.cpp (100%) rename {Dynamic Programming => dynamic_programming}/Coin-Change.cpp (100%) rename {Dynamic Programming => dynamic_programming}/Cut Rod.cpp (100%) rename {Dynamic Programming => dynamic_programming}/Edit Distance.cpp (100%) rename {Dynamic Programming => dynamic_programming}/Egg-Dropping-Puzzle.cpp (100%) rename {Dynamic Programming => dynamic_programming}/Fibonacci_Bottom_Up.cpp (100%) rename {Dynamic Programming => dynamic_programming}/Fibonacci_Top_Down.cpp (100%) rename {Dynamic Programming => dynamic_programming}/Floyd-Warshall.cpp (100%) rename {Dynamic Programming => dynamic_programming}/Longest Common Subsequence.cpp (100%) rename {Dynamic Programming => dynamic_programming}/Longest Increasing Subsequence (nlogn).cpp (100%) rename {Dynamic Programming => dynamic_programming}/Longest Increasing Subsequence.cpp (100%) rename {Dynamic Programming => dynamic_programming}/Matrix-Chain-Multiplication.cpp (100%) rename {Dynamic Programming => dynamic_programming}/longest_common_string.cpp (100%) diff --git a/Dynamic Programming/0-1 Knapsack.cpp b/dynamic_programming/0-1 Knapsack.cpp similarity index 100% rename from Dynamic Programming/0-1 Knapsack.cpp rename to dynamic_programming/0-1 Knapsack.cpp diff --git a/Dynamic Programming/Armstrong Number.cpp b/dynamic_programming/Armstrong Number.cpp similarity index 100% rename from Dynamic Programming/Armstrong Number.cpp rename to dynamic_programming/Armstrong Number.cpp diff --git a/Dynamic Programming/Bellman-Ford.cpp b/dynamic_programming/Bellman-Ford.cpp similarity index 100% rename from Dynamic Programming/Bellman-Ford.cpp rename to dynamic_programming/Bellman-Ford.cpp diff --git a/Dynamic Programming/Catalan-Numbers.cpp b/dynamic_programming/Catalan-Numbers.cpp similarity index 100% rename from Dynamic Programming/Catalan-Numbers.cpp rename to dynamic_programming/Catalan-Numbers.cpp diff --git a/Dynamic Programming/Coin-Change.cpp b/dynamic_programming/Coin-Change.cpp similarity index 100% rename from Dynamic Programming/Coin-Change.cpp rename to dynamic_programming/Coin-Change.cpp diff --git a/Dynamic Programming/Cut Rod.cpp b/dynamic_programming/Cut Rod.cpp similarity index 100% rename from Dynamic Programming/Cut Rod.cpp rename to dynamic_programming/Cut Rod.cpp diff --git a/Dynamic Programming/Edit Distance.cpp b/dynamic_programming/Edit Distance.cpp similarity index 100% rename from Dynamic Programming/Edit Distance.cpp rename to dynamic_programming/Edit Distance.cpp diff --git a/Dynamic Programming/Egg-Dropping-Puzzle.cpp b/dynamic_programming/Egg-Dropping-Puzzle.cpp similarity index 100% rename from Dynamic Programming/Egg-Dropping-Puzzle.cpp rename to dynamic_programming/Egg-Dropping-Puzzle.cpp diff --git a/Dynamic Programming/Fibonacci_Bottom_Up.cpp b/dynamic_programming/Fibonacci_Bottom_Up.cpp similarity index 100% rename from Dynamic Programming/Fibonacci_Bottom_Up.cpp rename to dynamic_programming/Fibonacci_Bottom_Up.cpp diff --git a/Dynamic Programming/Fibonacci_Top_Down.cpp b/dynamic_programming/Fibonacci_Top_Down.cpp similarity index 100% rename from Dynamic Programming/Fibonacci_Top_Down.cpp rename to dynamic_programming/Fibonacci_Top_Down.cpp diff --git a/Dynamic Programming/Floyd-Warshall.cpp b/dynamic_programming/Floyd-Warshall.cpp similarity index 100% rename from Dynamic Programming/Floyd-Warshall.cpp rename to dynamic_programming/Floyd-Warshall.cpp diff --git a/Dynamic Programming/Longest Common Subsequence.cpp b/dynamic_programming/Longest Common Subsequence.cpp similarity index 100% rename from Dynamic Programming/Longest Common Subsequence.cpp rename to dynamic_programming/Longest Common Subsequence.cpp diff --git a/Dynamic Programming/Longest Increasing Subsequence (nlogn).cpp b/dynamic_programming/Longest Increasing Subsequence (nlogn).cpp similarity index 100% rename from Dynamic Programming/Longest Increasing Subsequence (nlogn).cpp rename to dynamic_programming/Longest Increasing Subsequence (nlogn).cpp diff --git a/Dynamic Programming/Longest Increasing Subsequence.cpp b/dynamic_programming/Longest Increasing Subsequence.cpp similarity index 100% rename from Dynamic Programming/Longest Increasing Subsequence.cpp rename to dynamic_programming/Longest Increasing Subsequence.cpp diff --git a/Dynamic Programming/Matrix-Chain-Multiplication.cpp b/dynamic_programming/Matrix-Chain-Multiplication.cpp similarity index 100% rename from Dynamic Programming/Matrix-Chain-Multiplication.cpp rename to dynamic_programming/Matrix-Chain-Multiplication.cpp diff --git a/Dynamic Programming/longest_common_string.cpp b/dynamic_programming/longest_common_string.cpp similarity index 100% rename from Dynamic Programming/longest_common_string.cpp rename to dynamic_programming/longest_common_string.cpp From 6fe40bd0a24534832d7755bdd1d8bc2daee75383 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 28 Nov 2019 13:29:38 +0100 Subject: [PATCH 071/277] Greedy Algorithms -> greedy_algorithms (#647) --- Greedy Algorithms/.DS_Store | Bin 6148 -> 0 bytes .../Dijkstra.cpp | 0 .../Knapsack.cpp | 0 .../Kruskals Minimum Spanning Tree.cpp | 0 .../Prims Minimum Spanning Tree.cpp | 0 .../huffman.cpp | 0 6 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 Greedy Algorithms/.DS_Store rename {Greedy Algorithms => greedy_algorithms}/Dijkstra.cpp (100%) rename {Greedy Algorithms => greedy_algorithms}/Knapsack.cpp (100%) rename {Greedy Algorithms => greedy_algorithms}/Kruskals Minimum Spanning Tree.cpp (100%) rename {Greedy Algorithms => greedy_algorithms}/Prims Minimum Spanning Tree.cpp (100%) rename {Greedy Algorithms => greedy_algorithms}/huffman.cpp (100%) diff --git a/Greedy Algorithms/.DS_Store b/Greedy Algorithms/.DS_Store deleted file mode 100644 index 20f69ade7c956465da7c8adce9a4978bbf05b239..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHK!Ab)`41K9RRP@lJHwRCi1pi1~v@n z`yo*kvtwgeUL7=L1R!?lF2c2bDr!!0%#MvAuTaENiIyrpVu+>FpFA!*HiniC@!>;! zXYmO|%I>V6N;o7Nh7AUSfsYL6>__Qq|3CYB{x3mcf`MS*Z!#d=;b=JEy?JkK-KF;0 rM7^V`Xk25sN#UZjV#aDKKA;w%Kk0&)9UDV>DDfdsXb2Mw{3ru&?LkL0 diff --git a/Greedy Algorithms/Dijkstra.cpp b/greedy_algorithms/Dijkstra.cpp similarity index 100% rename from Greedy Algorithms/Dijkstra.cpp rename to greedy_algorithms/Dijkstra.cpp diff --git a/Greedy Algorithms/Knapsack.cpp b/greedy_algorithms/Knapsack.cpp similarity index 100% rename from Greedy Algorithms/Knapsack.cpp rename to greedy_algorithms/Knapsack.cpp diff --git a/Greedy Algorithms/Kruskals Minimum Spanning Tree.cpp b/greedy_algorithms/Kruskals Minimum Spanning Tree.cpp similarity index 100% rename from Greedy Algorithms/Kruskals Minimum Spanning Tree.cpp rename to greedy_algorithms/Kruskals Minimum Spanning Tree.cpp diff --git a/Greedy Algorithms/Prims Minimum Spanning Tree.cpp b/greedy_algorithms/Prims Minimum Spanning Tree.cpp similarity index 100% rename from Greedy Algorithms/Prims Minimum Spanning Tree.cpp rename to greedy_algorithms/Prims Minimum Spanning Tree.cpp diff --git a/Greedy Algorithms/huffman.cpp b/greedy_algorithms/huffman.cpp similarity index 100% rename from Greedy Algorithms/huffman.cpp rename to greedy_algorithms/huffman.cpp From ac1ba3a61333b47e8b29efd32b6c75050410f69c Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 28 Nov 2019 13:29:54 +0100 Subject: [PATCH 072/277] rename Others -> others (#648) * rename Others -> temp * rename Others -> others --- {Others => others}/Buzz_number.cpp | 0 {Others => others}/Decimal To Binary.cpp | 0 .../Decimal To Hexadecimal .cpp | 0 .../Decimal to Roman Numeral.cpp | 0 {Others => others}/GCD_of_n_numbers.cpp | 0 {Others => others}/Palindromeofnumber.cpp | 0 {Others => others}/Paranthesis Matching.cpp | 0 {Others => others}/Primality Test.cpp | 0 {Others => others}/Sparse matrix.cpp | 0 .../Strassen Matrix Multiplication.cpp | 0 {Others => others}/String Fibonacci.cpp | 0 {Others => others}/Tower of Hanoi.cpp | 0 {Others => others}/fibonacci.cpp | 0 {Others => others}/happy_number.cpp | 0 {Others => others}/pascal_triangle.cpp | 126 +++++++------- {Others => others}/sieve_of_Eratosthenes.cpp | 0 {Others => others}/smallest-circle.cpp | 0 {Others => others}/spiral_print.cpp | 156 +++++++++--------- .../vector_important_functions.cpp | 0 19 files changed, 141 insertions(+), 141 deletions(-) rename {Others => others}/Buzz_number.cpp (100%) rename {Others => others}/Decimal To Binary.cpp (100%) rename {Others => others}/Decimal To Hexadecimal .cpp (100%) rename {Others => others}/Decimal to Roman Numeral.cpp (100%) rename {Others => others}/GCD_of_n_numbers.cpp (100%) rename {Others => others}/Palindromeofnumber.cpp (100%) rename {Others => others}/Paranthesis Matching.cpp (100%) rename {Others => others}/Primality Test.cpp (100%) rename {Others => others}/Sparse matrix.cpp (100%) rename {Others => others}/Strassen Matrix Multiplication.cpp (100%) rename {Others => others}/String Fibonacci.cpp (100%) rename {Others => others}/Tower of Hanoi.cpp (100%) rename {Others => others}/fibonacci.cpp (100%) rename {Others => others}/happy_number.cpp (100%) rename {Others => others}/pascal_triangle.cpp (94%) rename {Others => others}/sieve_of_Eratosthenes.cpp (100%) rename {Others => others}/smallest-circle.cpp (100%) rename {Others => others}/spiral_print.cpp (94%) rename {Others => others}/vector_important_functions.cpp (100%) diff --git a/Others/Buzz_number.cpp b/others/Buzz_number.cpp similarity index 100% rename from Others/Buzz_number.cpp rename to others/Buzz_number.cpp diff --git a/Others/Decimal To Binary.cpp b/others/Decimal To Binary.cpp similarity index 100% rename from Others/Decimal To Binary.cpp rename to others/Decimal To Binary.cpp diff --git a/Others/Decimal To Hexadecimal .cpp b/others/Decimal To Hexadecimal .cpp similarity index 100% rename from Others/Decimal To Hexadecimal .cpp rename to others/Decimal To Hexadecimal .cpp diff --git a/Others/Decimal to Roman Numeral.cpp b/others/Decimal to Roman Numeral.cpp similarity index 100% rename from Others/Decimal to Roman Numeral.cpp rename to others/Decimal to Roman Numeral.cpp diff --git a/Others/GCD_of_n_numbers.cpp b/others/GCD_of_n_numbers.cpp similarity index 100% rename from Others/GCD_of_n_numbers.cpp rename to others/GCD_of_n_numbers.cpp diff --git a/Others/Palindromeofnumber.cpp b/others/Palindromeofnumber.cpp similarity index 100% rename from Others/Palindromeofnumber.cpp rename to others/Palindromeofnumber.cpp diff --git a/Others/Paranthesis Matching.cpp b/others/Paranthesis Matching.cpp similarity index 100% rename from Others/Paranthesis Matching.cpp rename to others/Paranthesis Matching.cpp diff --git a/Others/Primality Test.cpp b/others/Primality Test.cpp similarity index 100% rename from Others/Primality Test.cpp rename to others/Primality Test.cpp diff --git a/Others/Sparse matrix.cpp b/others/Sparse matrix.cpp similarity index 100% rename from Others/Sparse matrix.cpp rename to others/Sparse matrix.cpp diff --git a/Others/Strassen Matrix Multiplication.cpp b/others/Strassen Matrix Multiplication.cpp similarity index 100% rename from Others/Strassen Matrix Multiplication.cpp rename to others/Strassen Matrix Multiplication.cpp diff --git a/Others/String Fibonacci.cpp b/others/String Fibonacci.cpp similarity index 100% rename from Others/String Fibonacci.cpp rename to others/String Fibonacci.cpp diff --git a/Others/Tower of Hanoi.cpp b/others/Tower of Hanoi.cpp similarity index 100% rename from Others/Tower of Hanoi.cpp rename to others/Tower of Hanoi.cpp diff --git a/Others/fibonacci.cpp b/others/fibonacci.cpp similarity index 100% rename from Others/fibonacci.cpp rename to others/fibonacci.cpp diff --git a/Others/happy_number.cpp b/others/happy_number.cpp similarity index 100% rename from Others/happy_number.cpp rename to others/happy_number.cpp diff --git a/Others/pascal_triangle.cpp b/others/pascal_triangle.cpp similarity index 94% rename from Others/pascal_triangle.cpp rename to others/pascal_triangle.cpp index b6f762d97..101100018 100644 --- a/Others/pascal_triangle.cpp +++ b/others/pascal_triangle.cpp @@ -1,63 +1,63 @@ -#include - -using namespace std; - -void show_pascal(int **arr, int n) -{ - //pint Pascal's Triangle - for (int i = 0; i < n; ++i) - { - for (int j = 0; j < n + i; ++j) - { - if (arr[i][j] == 0) - cout << " "; - else - cout << arr[i][j]; - } - cout << endl; - } -} - -int **pascal_triangle(int **arr, int n) -{ - for (int i = 0; i < n; ++i) - { - for (int j = n - i - 1; j < n + i; ++j) - { - if (j == n - i - 1 || j == n + i - 1) - arr[i][j] = 1; //The edge of the Pascal triangle goes in 1 - else - arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j + 1]; - } - } - - return arr; -} - -int main() -{ - int n = 0; - - cout << "Set Pascal's Triangle Height" << endl; - cin >> n; - - //memory allocation (Assign two-dimensional array to store Pascal triangle) - int **arr = new int*[n]; - for (int i = 0; i < n; ++i) - { - arr[i] = new int[2 * n - 1]; - memset(arr[i], 0, sizeof(int)*(2 * n - 1)); - } - - pascal_triangle(arr, n); - show_pascal(arr, n); - - //deallocation - for (int i = 0; i < n; ++i) - { - delete[] arr[i]; - } - delete[] arr; - - return 0; -} +#include + +using namespace std; + +void show_pascal(int **arr, int n) +{ + //pint Pascal's Triangle + for (int i = 0; i < n; ++i) + { + for (int j = 0; j < n + i; ++j) + { + if (arr[i][j] == 0) + cout << " "; + else + cout << arr[i][j]; + } + cout << endl; + } +} + +int **pascal_triangle(int **arr, int n) +{ + for (int i = 0; i < n; ++i) + { + for (int j = n - i - 1; j < n + i; ++j) + { + if (j == n - i - 1 || j == n + i - 1) + arr[i][j] = 1; //The edge of the Pascal triangle goes in 1 + else + arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j + 1]; + } + } + + return arr; +} + +int main() +{ + int n = 0; + + cout << "Set Pascal's Triangle Height" << endl; + cin >> n; + + //memory allocation (Assign two-dimensional array to store Pascal triangle) + int **arr = new int*[n]; + for (int i = 0; i < n; ++i) + { + arr[i] = new int[2 * n - 1]; + memset(arr[i], 0, sizeof(int)*(2 * n - 1)); + } + + pascal_triangle(arr, n); + show_pascal(arr, n); + + //deallocation + for (int i = 0; i < n; ++i) + { + delete[] arr[i]; + } + delete[] arr; + + return 0; +} diff --git a/Others/sieve_of_Eratosthenes.cpp b/others/sieve_of_Eratosthenes.cpp similarity index 100% rename from Others/sieve_of_Eratosthenes.cpp rename to others/sieve_of_Eratosthenes.cpp diff --git a/Others/smallest-circle.cpp b/others/smallest-circle.cpp similarity index 100% rename from Others/smallest-circle.cpp rename to others/smallest-circle.cpp diff --git a/Others/spiral_print.cpp b/others/spiral_print.cpp similarity index 94% rename from Others/spiral_print.cpp rename to others/spiral_print.cpp index 1a843c8cd..e6e6899ef 100644 --- a/Others/spiral_print.cpp +++ b/others/spiral_print.cpp @@ -1,78 +1,78 @@ -#include -using namespace std; - -void genArray(int a[][10], int r, int c) -{ - - int value = 1; - for (int i = 0; i < r; i++) - { - for (int j = 0; j < c; j++) - { - a[i][j] = value; - cout << a[i][j] << " "; - value++; - } - cout << endl; - } -} -void spiralPrint(int a[][10], int r, int c) -{ - - int startRow = 0, endRow = r - 1; - int startCol = 0, endCol = c - 1; - int cnt = 0; - - while (startRow <= endRow && startCol <= endCol) - { - - ///Print start row - for (int i = startCol; i <= endCol; i++, cnt++) - { - cout << a[startRow][i] << " "; - } - startRow++; - - ///Print the end col - for (int i = startRow; i <= endRow; i++, cnt++) - { - cout << a[i][endCol] << " "; - } - endCol--; - - ///Print the end row - if (cnt == r * c) - { - break; - } - - for (int i = endCol; i >= startCol; i--, cnt++) - { - cout << a[endRow][i] << " "; - } - endRow--; - - ///Print the start Col - if (cnt == r * c) - { - break; - } - for (int i = endRow; i >= startRow; i--, cnt++) - { - cout << a[i][startCol] << " "; - } - startCol++; - } -} - -int main() -{ - int a[10][10]; - - int r, c; - cin >> r >> c; - genArray(a, r, c); - spiralPrint(a, r, c); - - return 0; -} +#include +using namespace std; + +void genArray(int a[][10], int r, int c) +{ + + int value = 1; + for (int i = 0; i < r; i++) + { + for (int j = 0; j < c; j++) + { + a[i][j] = value; + cout << a[i][j] << " "; + value++; + } + cout << endl; + } +} +void spiralPrint(int a[][10], int r, int c) +{ + + int startRow = 0, endRow = r - 1; + int startCol = 0, endCol = c - 1; + int cnt = 0; + + while (startRow <= endRow && startCol <= endCol) + { + + ///Print start row + for (int i = startCol; i <= endCol; i++, cnt++) + { + cout << a[startRow][i] << " "; + } + startRow++; + + ///Print the end col + for (int i = startRow; i <= endRow; i++, cnt++) + { + cout << a[i][endCol] << " "; + } + endCol--; + + ///Print the end row + if (cnt == r * c) + { + break; + } + + for (int i = endCol; i >= startCol; i--, cnt++) + { + cout << a[endRow][i] << " "; + } + endRow--; + + ///Print the start Col + if (cnt == r * c) + { + break; + } + for (int i = endRow; i >= startRow; i--, cnt++) + { + cout << a[i][startCol] << " "; + } + startCol++; + } +} + +int main() +{ + int a[10][10]; + + int r, c; + cin >> r >> c; + genArray(a, r, c); + spiralPrint(a, r, c); + + return 0; +} diff --git a/Others/vector_important_functions.cpp b/others/vector_important_functions.cpp similarity index 100% rename from Others/vector_important_functions.cpp rename to others/vector_important_functions.cpp From e3bdbb9e6f9cab8862014119aae14ed104275156 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 28 Nov 2019 13:30:19 +0100 Subject: [PATCH 073/277] rename Graph -> graph (#649) --- Graph/.DS_Store | Bin 6148 -> 0 bytes {Graph => graph}/BFS.cpp | 0 {Graph => graph}/DFS.cpp | 0 {Graph => graph}/DFS_with_stack.cc | 0 {Graph => graph}/Dijkstra.cpp | 0 {Graph => graph}/Kruskal.cpp | 0 {Graph => graph}/Topological-Sort.cpp | 0 {Graph => graph}/kosaraju.cpp | 0 {Graph => graph}/lca.cpp | 0 9 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 Graph/.DS_Store rename {Graph => graph}/BFS.cpp (100%) rename {Graph => graph}/DFS.cpp (100%) rename {Graph => graph}/DFS_with_stack.cc (100%) rename {Graph => graph}/Dijkstra.cpp (100%) rename {Graph => graph}/Kruskal.cpp (100%) rename {Graph => graph}/Topological-Sort.cpp (100%) rename {Graph => graph}/kosaraju.cpp (100%) rename {Graph => graph}/lca.cpp (100%) diff --git a/Graph/.DS_Store b/Graph/.DS_Store deleted file mode 100644 index 92db3084d0bc05cdd761a5c9c1f4e7d90ccb59d8..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHKF-`+P474EhBZeURiHz+t{6* z@ef<9@U_)vPHbak3s@^*LIQH5Ge}aD+ mYNH%satOeLt@!4wu5paIu5e5YI`TmW>L5T}WK!TS6!-vi<0jJp diff --git a/Graph/BFS.cpp b/graph/BFS.cpp similarity index 100% rename from Graph/BFS.cpp rename to graph/BFS.cpp diff --git a/Graph/DFS.cpp b/graph/DFS.cpp similarity index 100% rename from Graph/DFS.cpp rename to graph/DFS.cpp diff --git a/Graph/DFS_with_stack.cc b/graph/DFS_with_stack.cc similarity index 100% rename from Graph/DFS_with_stack.cc rename to graph/DFS_with_stack.cc diff --git a/Graph/Dijkstra.cpp b/graph/Dijkstra.cpp similarity index 100% rename from Graph/Dijkstra.cpp rename to graph/Dijkstra.cpp diff --git a/Graph/Kruskal.cpp b/graph/Kruskal.cpp similarity index 100% rename from Graph/Kruskal.cpp rename to graph/Kruskal.cpp diff --git a/Graph/Topological-Sort.cpp b/graph/Topological-Sort.cpp similarity index 100% rename from Graph/Topological-Sort.cpp rename to graph/Topological-Sort.cpp diff --git a/Graph/kosaraju.cpp b/graph/kosaraju.cpp similarity index 100% rename from Graph/kosaraju.cpp rename to graph/kosaraju.cpp diff --git a/Graph/lca.cpp b/graph/lca.cpp similarity index 100% rename from Graph/lca.cpp rename to graph/lca.cpp From 2c09d153348094fae35936324a4b36d304ed27d9 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 28 Nov 2019 13:30:50 +0100 Subject: [PATCH 074/277] rename Hashing -> hashing (#650) --- {Hashing => hashing}/Chaining.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Hashing => hashing}/Chaining.cpp (100%) diff --git a/Hashing/Chaining.cpp b/hashing/Chaining.cpp similarity index 100% rename from Hashing/Chaining.cpp rename to hashing/Chaining.cpp From 3fc7de16c0d16d4a1cbd802df51d310f176fd335 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 28 Nov 2019 13:31:18 +0100 Subject: [PATCH 075/277] rename Math -> math (#651) --- {Math => math}/Power_For_Huge_Num/Power_Huge.cpp | 0 {Math => math}/Prime_Factorization/README.md | 0 {Math => math}/Prime_Factorization/primefactorization.cpp | 0 {Math => math}/sieve_of_Eratosthenes.cpp | 0 4 files changed, 0 insertions(+), 0 deletions(-) rename {Math => math}/Power_For_Huge_Num/Power_Huge.cpp (100%) rename {Math => math}/Prime_Factorization/README.md (100%) rename {Math => math}/Prime_Factorization/primefactorization.cpp (100%) rename {Math => math}/sieve_of_Eratosthenes.cpp (100%) diff --git a/Math/Power_For_Huge_Num/Power_Huge.cpp b/math/Power_For_Huge_Num/Power_Huge.cpp similarity index 100% rename from Math/Power_For_Huge_Num/Power_Huge.cpp rename to math/Power_For_Huge_Num/Power_Huge.cpp diff --git a/Math/Prime_Factorization/README.md b/math/Prime_Factorization/README.md similarity index 100% rename from Math/Prime_Factorization/README.md rename to math/Prime_Factorization/README.md diff --git a/Math/Prime_Factorization/primefactorization.cpp b/math/Prime_Factorization/primefactorization.cpp similarity index 100% rename from Math/Prime_Factorization/primefactorization.cpp rename to math/Prime_Factorization/primefactorization.cpp diff --git a/Math/sieve_of_Eratosthenes.cpp b/math/sieve_of_Eratosthenes.cpp similarity index 100% rename from Math/sieve_of_Eratosthenes.cpp rename to math/sieve_of_Eratosthenes.cpp From cb1ed9a488e8de90a3913298b5f8935bdc927df0 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 28 Nov 2019 13:31:36 +0100 Subject: [PATCH 076/277] rename Search -> search (#652) --- {Search => search}/Binary Search.cpp | 0 {Search => search}/Interpolation Search.cpp | 0 {Search => search}/Linear Search.cpp | 0 {Search => search}/median_search.cpp | 0 {Search => search}/searching.cpp | 0 {Search => search}/ternary_search.cpp | 0 6 files changed, 0 insertions(+), 0 deletions(-) rename {Search => search}/Binary Search.cpp (100%) rename {Search => search}/Interpolation Search.cpp (100%) rename {Search => search}/Linear Search.cpp (100%) rename {Search => search}/median_search.cpp (100%) rename {Search => search}/searching.cpp (100%) rename {Search => search}/ternary_search.cpp (100%) diff --git a/Search/Binary Search.cpp b/search/Binary Search.cpp similarity index 100% rename from Search/Binary Search.cpp rename to search/Binary Search.cpp diff --git a/Search/Interpolation Search.cpp b/search/Interpolation Search.cpp similarity index 100% rename from Search/Interpolation Search.cpp rename to search/Interpolation Search.cpp diff --git a/Search/Linear Search.cpp b/search/Linear Search.cpp similarity index 100% rename from Search/Linear Search.cpp rename to search/Linear Search.cpp diff --git a/Search/median_search.cpp b/search/median_search.cpp similarity index 100% rename from Search/median_search.cpp rename to search/median_search.cpp diff --git a/Search/searching.cpp b/search/searching.cpp similarity index 100% rename from Search/searching.cpp rename to search/searching.cpp diff --git a/Search/ternary_search.cpp b/search/ternary_search.cpp similarity index 100% rename from Search/ternary_search.cpp rename to search/ternary_search.cpp From f8da1b06852e33cb999b3df3fda8326b01500e90 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 28 Nov 2019 13:32:03 +0100 Subject: [PATCH 077/277] rename Sorting -> sorting (#653) --- {Sorting => sorting}/BeadSort.cpp | 0 {Sorting => sorting}/BitonicSort.cpp | 0 {Sorting => sorting}/Bubble Sort.cpp | 0 {Sorting => sorting}/CocktailSelectionSort.cpp | 0 {Sorting => sorting}/CountingSortString.cpp | 0 {Sorting => sorting}/Counting_Sort.cpp | 0 {Sorting => sorting}/Heap Sort .cpp | 0 {Sorting => sorting}/Insertion Sort.cpp | 0 {Sorting => sorting}/Merge Sort.cpp | 0 {Sorting => sorting}/NumericStringSort.cpp | 0 {Sorting => sorting}/OddEven Sort.cpp | 0 {Sorting => sorting}/Quick Sort.cpp | 0 {Sorting => sorting}/Radix Sort.cpp | 0 {Sorting => sorting}/Selection Sort.cpp | 0 {Sorting => sorting}/Shell Sort.cpp | 0 {Sorting => sorting}/Slow Sort.cpp | 0 {Sorting => sorting}/Tim Sort.cpp | 0 {Sorting => sorting}/bucketSort.cpp | 0 {Sorting => sorting}/combsort.cpp | 0 19 files changed, 0 insertions(+), 0 deletions(-) rename {Sorting => sorting}/BeadSort.cpp (100%) rename {Sorting => sorting}/BitonicSort.cpp (100%) rename {Sorting => sorting}/Bubble Sort.cpp (100%) rename {Sorting => sorting}/CocktailSelectionSort.cpp (100%) rename {Sorting => sorting}/CountingSortString.cpp (100%) rename {Sorting => sorting}/Counting_Sort.cpp (100%) rename {Sorting => sorting}/Heap Sort .cpp (100%) rename {Sorting => sorting}/Insertion Sort.cpp (100%) rename {Sorting => sorting}/Merge Sort.cpp (100%) rename {Sorting => sorting}/NumericStringSort.cpp (100%) rename {Sorting => sorting}/OddEven Sort.cpp (100%) rename {Sorting => sorting}/Quick Sort.cpp (100%) rename {Sorting => sorting}/Radix Sort.cpp (100%) rename {Sorting => sorting}/Selection Sort.cpp (100%) rename {Sorting => sorting}/Shell Sort.cpp (100%) rename {Sorting => sorting}/Slow Sort.cpp (100%) rename {Sorting => sorting}/Tim Sort.cpp (100%) rename {Sorting => sorting}/bucketSort.cpp (100%) rename {Sorting => sorting}/combsort.cpp (100%) diff --git a/Sorting/BeadSort.cpp b/sorting/BeadSort.cpp similarity index 100% rename from Sorting/BeadSort.cpp rename to sorting/BeadSort.cpp diff --git a/Sorting/BitonicSort.cpp b/sorting/BitonicSort.cpp similarity index 100% rename from Sorting/BitonicSort.cpp rename to sorting/BitonicSort.cpp diff --git a/Sorting/Bubble Sort.cpp b/sorting/Bubble Sort.cpp similarity index 100% rename from Sorting/Bubble Sort.cpp rename to sorting/Bubble Sort.cpp diff --git a/Sorting/CocktailSelectionSort.cpp b/sorting/CocktailSelectionSort.cpp similarity index 100% rename from Sorting/CocktailSelectionSort.cpp rename to sorting/CocktailSelectionSort.cpp diff --git a/Sorting/CountingSortString.cpp b/sorting/CountingSortString.cpp similarity index 100% rename from Sorting/CountingSortString.cpp rename to sorting/CountingSortString.cpp diff --git a/Sorting/Counting_Sort.cpp b/sorting/Counting_Sort.cpp similarity index 100% rename from Sorting/Counting_Sort.cpp rename to sorting/Counting_Sort.cpp diff --git a/Sorting/Heap Sort .cpp b/sorting/Heap Sort .cpp similarity index 100% rename from Sorting/Heap Sort .cpp rename to sorting/Heap Sort .cpp diff --git a/Sorting/Insertion Sort.cpp b/sorting/Insertion Sort.cpp similarity index 100% rename from Sorting/Insertion Sort.cpp rename to sorting/Insertion Sort.cpp diff --git a/Sorting/Merge Sort.cpp b/sorting/Merge Sort.cpp similarity index 100% rename from Sorting/Merge Sort.cpp rename to sorting/Merge Sort.cpp diff --git a/Sorting/NumericStringSort.cpp b/sorting/NumericStringSort.cpp similarity index 100% rename from Sorting/NumericStringSort.cpp rename to sorting/NumericStringSort.cpp diff --git a/Sorting/OddEven Sort.cpp b/sorting/OddEven Sort.cpp similarity index 100% rename from Sorting/OddEven Sort.cpp rename to sorting/OddEven Sort.cpp diff --git a/Sorting/Quick Sort.cpp b/sorting/Quick Sort.cpp similarity index 100% rename from Sorting/Quick Sort.cpp rename to sorting/Quick Sort.cpp diff --git a/Sorting/Radix Sort.cpp b/sorting/Radix Sort.cpp similarity index 100% rename from Sorting/Radix Sort.cpp rename to sorting/Radix Sort.cpp diff --git a/Sorting/Selection Sort.cpp b/sorting/Selection Sort.cpp similarity index 100% rename from Sorting/Selection Sort.cpp rename to sorting/Selection Sort.cpp diff --git a/Sorting/Shell Sort.cpp b/sorting/Shell Sort.cpp similarity index 100% rename from Sorting/Shell Sort.cpp rename to sorting/Shell Sort.cpp diff --git a/Sorting/Slow Sort.cpp b/sorting/Slow Sort.cpp similarity index 100% rename from Sorting/Slow Sort.cpp rename to sorting/Slow Sort.cpp diff --git a/Sorting/Tim Sort.cpp b/sorting/Tim Sort.cpp similarity index 100% rename from Sorting/Tim Sort.cpp rename to sorting/Tim Sort.cpp diff --git a/Sorting/bucketSort.cpp b/sorting/bucketSort.cpp similarity index 100% rename from Sorting/bucketSort.cpp rename to sorting/bucketSort.cpp diff --git a/Sorting/combsort.cpp b/sorting/combsort.cpp similarity index 100% rename from Sorting/combsort.cpp rename to sorting/combsort.cpp From ab12ed4a14d48349e807bcdc87f5df67923999e9 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 28 Nov 2019 13:37:04 +0100 Subject: [PATCH 078/277] rename Backtracking -> backtracking (#654) --- {Backtracking => backtracking}/graph_coloring.cpp | 0 {Backtracking => backtracking}/knight_tour.cpp | 0 {Backtracking => backtracking}/n_queens.cpp | 0 {Backtracking => backtracking}/rat_maze.cpp | 0 {Backtracking => backtracking}/sudoku_solve.cpp | 0 5 files changed, 0 insertions(+), 0 deletions(-) rename {Backtracking => backtracking}/graph_coloring.cpp (100%) rename {Backtracking => backtracking}/knight_tour.cpp (100%) rename {Backtracking => backtracking}/n_queens.cpp (100%) rename {Backtracking => backtracking}/rat_maze.cpp (100%) rename {Backtracking => backtracking}/sudoku_solve.cpp (100%) diff --git a/Backtracking/graph_coloring.cpp b/backtracking/graph_coloring.cpp similarity index 100% rename from Backtracking/graph_coloring.cpp rename to backtracking/graph_coloring.cpp diff --git a/Backtracking/knight_tour.cpp b/backtracking/knight_tour.cpp similarity index 100% rename from Backtracking/knight_tour.cpp rename to backtracking/knight_tour.cpp diff --git a/Backtracking/n_queens.cpp b/backtracking/n_queens.cpp similarity index 100% rename from Backtracking/n_queens.cpp rename to backtracking/n_queens.cpp diff --git a/Backtracking/rat_maze.cpp b/backtracking/rat_maze.cpp similarity index 100% rename from Backtracking/rat_maze.cpp rename to backtracking/rat_maze.cpp diff --git a/Backtracking/sudoku_solve.cpp b/backtracking/sudoku_solve.cpp similarity index 100% rename from Backtracking/sudoku_solve.cpp rename to backtracking/sudoku_solve.cpp From 0174dad7057382b66bbc550e8a32e4136662aab6 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 28 Nov 2019 13:52:24 +0100 Subject: [PATCH 079/277] rename Operations on Datastructures -> operations_on_datastructures (#655) --- .../Array Left Rotation.cpp | 0 .../Array Right Rotation.cpp | 0 .../Circular Linked List.cpp | 0 .../Circular Queue Using Array.cpp | 0 .../Intersection_of_2_arrays.cpp | 0 .../Reverse a Linked List using Recusion.cpp | 0 .../Union_of_2_arrays.cpp | 0 .../selectionSortLinkedList.cpp | 316 +++++++++--------- 8 files changed, 158 insertions(+), 158 deletions(-) rename {Operations on Datastructures => operations_on_datastructures}/Array Left Rotation.cpp (100%) rename {Operations on Datastructures => operations_on_datastructures}/Array Right Rotation.cpp (100%) rename {Operations on Datastructures => operations_on_datastructures}/Circular Linked List.cpp (100%) rename {Operations on Datastructures => operations_on_datastructures}/Circular Queue Using Array.cpp (100%) rename {Operations on Datastructures => operations_on_datastructures}/Intersection_of_2_arrays.cpp (100%) rename {Operations on Datastructures => operations_on_datastructures}/Reverse a Linked List using Recusion.cpp (100%) rename {Operations on Datastructures => operations_on_datastructures}/Union_of_2_arrays.cpp (100%) rename {Operations on Datastructures => operations_on_datastructures}/selectionSortLinkedList.cpp (97%) diff --git a/Operations on Datastructures/Array Left Rotation.cpp b/operations_on_datastructures/Array Left Rotation.cpp similarity index 100% rename from Operations on Datastructures/Array Left Rotation.cpp rename to operations_on_datastructures/Array Left Rotation.cpp diff --git a/Operations on Datastructures/Array Right Rotation.cpp b/operations_on_datastructures/Array Right Rotation.cpp similarity index 100% rename from Operations on Datastructures/Array Right Rotation.cpp rename to operations_on_datastructures/Array Right Rotation.cpp diff --git a/Operations on Datastructures/Circular Linked List.cpp b/operations_on_datastructures/Circular Linked List.cpp similarity index 100% rename from Operations on Datastructures/Circular Linked List.cpp rename to operations_on_datastructures/Circular Linked List.cpp diff --git a/Operations on Datastructures/Circular Queue Using Array.cpp b/operations_on_datastructures/Circular Queue Using Array.cpp similarity index 100% rename from Operations on Datastructures/Circular Queue Using Array.cpp rename to operations_on_datastructures/Circular Queue Using Array.cpp diff --git a/Operations on Datastructures/Intersection_of_2_arrays.cpp b/operations_on_datastructures/Intersection_of_2_arrays.cpp similarity index 100% rename from Operations on Datastructures/Intersection_of_2_arrays.cpp rename to operations_on_datastructures/Intersection_of_2_arrays.cpp diff --git a/Operations on Datastructures/Reverse a Linked List using Recusion.cpp b/operations_on_datastructures/Reverse a Linked List using Recusion.cpp similarity index 100% rename from Operations on Datastructures/Reverse a Linked List using Recusion.cpp rename to operations_on_datastructures/Reverse a Linked List using Recusion.cpp diff --git a/Operations on Datastructures/Union_of_2_arrays.cpp b/operations_on_datastructures/Union_of_2_arrays.cpp similarity index 100% rename from Operations on Datastructures/Union_of_2_arrays.cpp rename to operations_on_datastructures/Union_of_2_arrays.cpp diff --git a/Operations on Datastructures/selectionSortLinkedList.cpp b/operations_on_datastructures/selectionSortLinkedList.cpp similarity index 97% rename from Operations on Datastructures/selectionSortLinkedList.cpp rename to operations_on_datastructures/selectionSortLinkedList.cpp index e5b840234..52363ceff 100644 --- a/Operations on Datastructures/selectionSortLinkedList.cpp +++ b/operations_on_datastructures/selectionSortLinkedList.cpp @@ -1,159 +1,159 @@ -#include -using namespace std; - -//node defined -class node -{ -public: - int data; - node *link; - node(int d) - { - data = d; - link = NULL; - } -}; - -//printing the linked list -void print(node *head) -{ - node *current = head; - while (current != NULL) - { - cout << current->data << " "; - current = current->link; - } - cout << endl; -} - -//creating the linked list with 'n' nodes -node *createlist(int n) -{ - node *head = NULL; - node *t = NULL; - for (int i = 0; i < n; i++) - { - node *temp = NULL; - int num; - cin >> num; - temp = new node(num); - if (head == NULL) - { - head = temp; - t = temp; - continue; - } - if (t->link == NULL) - t->link = temp; - t = temp; - } - return head; -} - -//performing selection sort on the linked list in an iterative manner -void my_selection_sort_linked_list(node *&head) -{ - node *min = head; //throughout the algorithm 'min' is used to denote the node with min value out of all the nodes left for scanning - //while scanning if we find a node 'X' with value lesser than min, - //then we update the pointers in such a way that 'X' becomes the predecessor of 'min' - node *current = min->link; // 'current' refers to the current node we are scanning - node *previous = min; //'previous' refers to the node that is previous to the current node - node *temp = NULL; // 'temp' in this algo is used to point to the last node of the sorted part of the linked list. - //eg. If at any time instance the state of the linked list is suppose 1->2->5->3->8->NULL - //then, we see that "1->2" is the sorted part of the LL, and therefore temp will be pointing to the last node of the sorted part,i.e,'2' - //We keep on arranging the Linked list in such a way that after each iteration the node with 'min' value is placed at its correct position. - //Eg. Let suppose initially we have 5->4->1->3->2->NULL - //After 1st iteration : 1->4->5->3->2->NULL and so on - - while (min->link != NULL) //so that all the nodes are scanned or until there exists a node - { - //pick the first node from the unsorted part and assume that it is the minimum and then start scanning from the next node - - while (current != NULL) //suppose you choose the min node to be X, then scan starts from the (X+1)th node until its NULL. current = (X+1)th node and min = X - { - if (current->data < min->data) //if the current node is smaller than the presumed node 'min' - { - if (temp == NULL) //temp stays null for the first iteration, therefore it symbolizes that we are scanning for the first time - { - if (previous == min) //if the 'previous' is pointing to the 'min' node - { - //Update the pointers - head = current; //update the head pointer with the current node - min->link = current->link; - current->link = previous; - min = current; - current = previous->link; - } - else //if the 'previous' is not pointing to the 'min' node - { - //Update the pointers - head = current; //update the head pointer with the current node - previous->link = current->link; - current->link = min; - min = current; - current = previous->link; - } - } - else //if 'temp' is not NULL, i.e., its not the 1st iteration - { - temp->link = current; - previous->link = current->link; - current->link = min; - min = current; - current = previous->link; - } - } - else //if the current node is greater than min, just move the previous and the current pointer a step further - { - previous = previous->link; - current = current->link; - } - } - - //update the pointers. Set 'temp' to the last node in the sorted part. Make 'min' move a step further so that 'min' points to the 1st node of the unsorted part - //start the iteration again - temp = min; - min = min->link; - previous = min; - current = min->link; - } -} - -// Test cases: - -// enter the no. of nodes : 5 -// 8 9 3 1 4 -// original list is : 8 9 3 1 4 -// sorted list is : 1 3 4 8 9 - -// enter the no. of nodes : 3 -// -1 -2 -3 -// original list is : -1 -2 -3 -// sorted list is : -3 -2 -1 - -// enter the no. of nodes : 8 -// 8 7 6 5 4 3 2 1 -// original list is : 8 7 6 5 4 3 2 1 -// sorted list is : 1 2 3 4 5 6 7 8 - -// enter the no. of nodes : 6 -// 5 3 4 1 -2 -4 -// original list is : 5 3 4 1 -2 -4 -// sorted list is : -4 -2 1 3 4 5 - -int main() -{ - node *head = NULL; - int n; - cout << "enter the no. of nodes : "; //taking input from user about the number of nodes in linked list - cin >> n; - if (n == 0) - return 0; - head = createlist(n); //creating the list - cout << "original list is : "; - print(head); //printing the original linked list - my_selection_sort_linked_list(head); //applying selection sort - cout << "sorted list is : "; - print(head); //printing the sorted linked list - return 0; +#include +using namespace std; + +//node defined +class node +{ +public: + int data; + node *link; + node(int d) + { + data = d; + link = NULL; + } +}; + +//printing the linked list +void print(node *head) +{ + node *current = head; + while (current != NULL) + { + cout << current->data << " "; + current = current->link; + } + cout << endl; +} + +//creating the linked list with 'n' nodes +node *createlist(int n) +{ + node *head = NULL; + node *t = NULL; + for (int i = 0; i < n; i++) + { + node *temp = NULL; + int num; + cin >> num; + temp = new node(num); + if (head == NULL) + { + head = temp; + t = temp; + continue; + } + if (t->link == NULL) + t->link = temp; + t = temp; + } + return head; +} + +//performing selection sort on the linked list in an iterative manner +void my_selection_sort_linked_list(node *&head) +{ + node *min = head; //throughout the algorithm 'min' is used to denote the node with min value out of all the nodes left for scanning + //while scanning if we find a node 'X' with value lesser than min, + //then we update the pointers in such a way that 'X' becomes the predecessor of 'min' + node *current = min->link; // 'current' refers to the current node we are scanning + node *previous = min; //'previous' refers to the node that is previous to the current node + node *temp = NULL; // 'temp' in this algo is used to point to the last node of the sorted part of the linked list. + //eg. If at any time instance the state of the linked list is suppose 1->2->5->3->8->NULL + //then, we see that "1->2" is the sorted part of the LL, and therefore temp will be pointing to the last node of the sorted part,i.e,'2' + //We keep on arranging the Linked list in such a way that after each iteration the node with 'min' value is placed at its correct position. + //Eg. Let suppose initially we have 5->4->1->3->2->NULL + //After 1st iteration : 1->4->5->3->2->NULL and so on + + while (min->link != NULL) //so that all the nodes are scanned or until there exists a node + { + //pick the first node from the unsorted part and assume that it is the minimum and then start scanning from the next node + + while (current != NULL) //suppose you choose the min node to be X, then scan starts from the (X+1)th node until its NULL. current = (X+1)th node and min = X + { + if (current->data < min->data) //if the current node is smaller than the presumed node 'min' + { + if (temp == NULL) //temp stays null for the first iteration, therefore it symbolizes that we are scanning for the first time + { + if (previous == min) //if the 'previous' is pointing to the 'min' node + { + //Update the pointers + head = current; //update the head pointer with the current node + min->link = current->link; + current->link = previous; + min = current; + current = previous->link; + } + else //if the 'previous' is not pointing to the 'min' node + { + //Update the pointers + head = current; //update the head pointer with the current node + previous->link = current->link; + current->link = min; + min = current; + current = previous->link; + } + } + else //if 'temp' is not NULL, i.e., its not the 1st iteration + { + temp->link = current; + previous->link = current->link; + current->link = min; + min = current; + current = previous->link; + } + } + else //if the current node is greater than min, just move the previous and the current pointer a step further + { + previous = previous->link; + current = current->link; + } + } + + //update the pointers. Set 'temp' to the last node in the sorted part. Make 'min' move a step further so that 'min' points to the 1st node of the unsorted part + //start the iteration again + temp = min; + min = min->link; + previous = min; + current = min->link; + } +} + +// Test cases: + +// enter the no. of nodes : 5 +// 8 9 3 1 4 +// original list is : 8 9 3 1 4 +// sorted list is : 1 3 4 8 9 + +// enter the no. of nodes : 3 +// -1 -2 -3 +// original list is : -1 -2 -3 +// sorted list is : -3 -2 -1 + +// enter the no. of nodes : 8 +// 8 7 6 5 4 3 2 1 +// original list is : 8 7 6 5 4 3 2 1 +// sorted list is : 1 2 3 4 5 6 7 8 + +// enter the no. of nodes : 6 +// 5 3 4 1 -2 -4 +// original list is : 5 3 4 1 -2 -4 +// sorted list is : -4 -2 1 3 4 5 + +int main() +{ + node *head = NULL; + int n; + cout << "enter the no. of nodes : "; //taking input from user about the number of nodes in linked list + cin >> n; + if (n == 0) + return 0; + head = createlist(n); //creating the list + cout << "original list is : "; + print(head); //printing the original linked list + my_selection_sort_linked_list(head); //applying selection sort + cout << "sorted list is : "; + print(head); //printing the sorted linked list + return 0; } \ No newline at end of file From 81b25e578d79a65e628bfc913a17c647bcbcf722 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 28 Nov 2019 14:07:34 +0100 Subject: [PATCH 080/277] rename Computer Oriented Statistical Methods -> computer_oriented_statistical_methods (#656) --- .../Bisection_method.CPP | 0 .../Gaussian_elimination.cpp | 0 .../Newton_Raphson.CPP | 0 .../Secant_method.CPP | 0 .../false-position.CPP | 0 .../successive_approximation.CPP | 0 6 files changed, 0 insertions(+), 0 deletions(-) rename {Computer Oriented Statistical Methods => computer_oriented_statistical_methods}/Bisection_method.CPP (100%) rename {Computer Oriented Statistical Methods => computer_oriented_statistical_methods}/Gaussian_elimination.cpp (100%) rename {Computer Oriented Statistical Methods => computer_oriented_statistical_methods}/Newton_Raphson.CPP (100%) rename {Computer Oriented Statistical Methods => computer_oriented_statistical_methods}/Secant_method.CPP (100%) rename {Computer Oriented Statistical Methods => computer_oriented_statistical_methods}/false-position.CPP (100%) rename {Computer Oriented Statistical Methods => computer_oriented_statistical_methods}/successive_approximation.CPP (100%) diff --git a/Computer Oriented Statistical Methods/Bisection_method.CPP b/computer_oriented_statistical_methods/Bisection_method.CPP similarity index 100% rename from Computer Oriented Statistical Methods/Bisection_method.CPP rename to computer_oriented_statistical_methods/Bisection_method.CPP diff --git a/Computer Oriented Statistical Methods/Gaussian_elimination.cpp b/computer_oriented_statistical_methods/Gaussian_elimination.cpp similarity index 100% rename from Computer Oriented Statistical Methods/Gaussian_elimination.cpp rename to computer_oriented_statistical_methods/Gaussian_elimination.cpp diff --git a/Computer Oriented Statistical Methods/Newton_Raphson.CPP b/computer_oriented_statistical_methods/Newton_Raphson.CPP similarity index 100% rename from Computer Oriented Statistical Methods/Newton_Raphson.CPP rename to computer_oriented_statistical_methods/Newton_Raphson.CPP diff --git a/Computer Oriented Statistical Methods/Secant_method.CPP b/computer_oriented_statistical_methods/Secant_method.CPP similarity index 100% rename from Computer Oriented Statistical Methods/Secant_method.CPP rename to computer_oriented_statistical_methods/Secant_method.CPP diff --git a/Computer Oriented Statistical Methods/false-position.CPP b/computer_oriented_statistical_methods/false-position.CPP similarity index 100% rename from Computer Oriented Statistical Methods/false-position.CPP rename to computer_oriented_statistical_methods/false-position.CPP diff --git a/Computer Oriented Statistical Methods/successive_approximation.CPP b/computer_oriented_statistical_methods/successive_approximation.CPP similarity index 100% rename from Computer Oriented Statistical Methods/successive_approximation.CPP rename to computer_oriented_statistical_methods/successive_approximation.CPP From 86f0bc936da5fad7d1c4173159da5db17855285c Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 28 Nov 2019 14:34:13 +0100 Subject: [PATCH 081/277] Flatten the math directory (#657) --- .github/workflows/cpplint_modified_files.yml | 8 ++++---- math/{Prime_Factorization => }/README.md | 0 .../Power_Huge.cpp => power_for_huge_numbers.cpp} | 0 .../primefactorization.cpp => prime_factorization.cpp} | 0 ...ieve_of_Eratosthenes.cpp => sieve_of_eratosthenes.cpp} | 0 5 files changed, 4 insertions(+), 4 deletions(-) rename math/{Prime_Factorization => }/README.md (100%) rename math/{Power_For_Huge_Num/Power_Huge.cpp => power_for_huge_numbers.cpp} (100%) rename math/{Prime_Factorization/primefactorization.cpp => prime_factorization.cpp} (100%) rename math/{sieve_of_Eratosthenes.cpp => sieve_of_eratosthenes.cpp} (100%) diff --git a/.github/workflows/cpplint_modified_files.yml b/.github/workflows/cpplint_modified_files.yml index d1d850c1d..dcf2499e6 100644 --- a/.github/workflows/cpplint_modified_files.yml +++ b/.github/workflows/cpplint_modified_files.yml @@ -30,19 +30,19 @@ jobs: print("cpplint:") print(subprocess.check_output(["cpplint"] + cpp_files).decode("utf-8")) - upper_files = [file for file in cpp_files if os.path.basename(file) != os.path.basename(file).lower()] + upper_files = [file for file in cpp_files if file != file.lower()] if upper_files: print("{} files contain uppercase characters:".format(len(upper_files))) print("\n".join(upper_files) + "\n") - space_files = [file for file in cpp_files if " " in os.path.basename(file) or "-" in file] + space_files = [file for file in cpp_files if " " in file or "-" in file] if space_files: print("{} files contain space or dash characters:".format(len(space_files))) print("\n".join(space_files) + "\n") - nodir_files = [file for file in cpp_files if os.sep not in file] + nodir_files = [file for file in cpp_files if file.count(os.sep) != 1] if nodir_files: - print("{} files are not in a directory:".format(len(nodir_files))) + print("{} files are not in one and only one directory:".format(len(nodir_files))) print("\n".join(nodir_files) + "\n") bad_files = len(upper_files + space_files + nodir_files) diff --git a/math/Prime_Factorization/README.md b/math/README.md similarity index 100% rename from math/Prime_Factorization/README.md rename to math/README.md diff --git a/math/Power_For_Huge_Num/Power_Huge.cpp b/math/power_for_huge_numbers.cpp similarity index 100% rename from math/Power_For_Huge_Num/Power_Huge.cpp rename to math/power_for_huge_numbers.cpp diff --git a/math/Prime_Factorization/primefactorization.cpp b/math/prime_factorization.cpp similarity index 100% rename from math/Prime_Factorization/primefactorization.cpp rename to math/prime_factorization.cpp diff --git a/math/sieve_of_Eratosthenes.cpp b/math/sieve_of_eratosthenes.cpp similarity index 100% rename from math/sieve_of_Eratosthenes.cpp rename to math/sieve_of_eratosthenes.cpp From e7a7ac32fce0166286a8ae6f9be07d09cce1eef3 Mon Sep 17 00:00:00 2001 From: Riot Date: Fri, 29 Nov 2019 01:25:28 +0100 Subject: [PATCH 082/277] struzik --- Search/exponential_search.cpp | 56 +++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Search/exponential_search.cpp diff --git a/Search/exponential_search.cpp b/Search/exponential_search.cpp new file mode 100644 index 000000000..b0f1d5aa3 --- /dev/null +++ b/Search/exponential_search.cpp @@ -0,0 +1,56 @@ +#include +#include +#include +using namespaces std; + +//-----------------Binary Search Algorithm(use by struziki algorithm//----------------- +//Time Complexity O(log n) where 'n' is the number of elements +//Worst Time Complexity O(log n) +//Best Time Complexity Ω(1) +//Space Complexity O(1) +//Auxiliary Space Complexity O(1) + +template inline Type* binary_search(Type *array, size_t size, Type key) {//Parameter List:Pointer to and array|size of array|key what you search + int32_t lower_index(0), upper_index(size - 1),middle_index; //lower_index => start of search range | upper_index => end of search range | middle_index => middle of search range + while (lower_index <= upper_index) + { + middle_index = floor((lower_index + upper_index) / 2); + if (*(array + middle_index) < key) lower_index = (middle_index + 1); //if the key is smaller than the middle of search range, we narrow the search range from up + else if (*(array + middle_index) > key) upper_index = (middle_index - 1);//if the key is bigger than the middle of search range, we narrow the search range from down + else return (array + middle_index); //the key has been found + } + return nullptr; +} + +//-----------------Struzik Search Algorithm(Exponential//----------------- +//Time Complexity O(log i)where i is the position of the search key in the list +//Worst Time Complexity O(log i) +//Best Time Complexity Ω(1) +//Space Complexity O(1) +//Auxiliary Space Complexity O(1) + +template Type* Struzik_Search(Type* array,size_t size,Type key) { //Parameter List: Pointer to an array(sorted)!You can use complex objectum, but in that case you have to overload '<>' operators!|size of array|key what you search + uint32_t block_front(0),block_size = size == 0 ? 0 : 1; //the start and end of the first block where the algorithm starts seach !if the size of array 0 than return null pointer + while (block_front != block_size) //when the start of block(block_front) and end of block(block_size) equal it means the key bigger than the last element of array and it return null pointer + { + if (*(array + block_size - 1) < key) {//if the key is bigger than the end of block we define a new block what is twice bigger than the previous + block_front = block_size; + (block_size * 2 - 1 < size) ? (block_size *= 2) : block_size = size;//if the end of new block bigger than size of array it takes the end of array + continue; + } + //when the algorithm delimit the block where the key shold be we do a binary search there + return binary_search(array + block_front, (block_size - block_front), key); + } + return nullptr; +} +int main(){ + + //----------------TEST CASES---------------- + int *sorted_array = new int[7]{ 7,10,15,23,70,105,203 }; + assert(Struzik_Search(sorted_array, 7, 0) == nullptr); //Key smaller than the first element of array + assert(Struzik_Search(sorted_array, 7, 1000) == nullptr); //Key bigger than the last element of array + assert(Struzik_Search(sorted_array, 7, 50) == nullptr); //Key between the elemenets of array + assert(Struzik_Search(sorted_array, 7, 7) == sorted_array);//Key is in the array !FOUND! + //----------------TEST CASES---------------- + return EXIT_SUCCESS; +} From 0c41877301e915eef04f945b5c1589896526cb57 Mon Sep 17 00:00:00 2001 From: Divide-et-impera-11 <54957167+Divide-et-impera-11@users.noreply.github.com> Date: Fri, 29 Nov 2019 02:48:14 +0100 Subject: [PATCH 083/277] Delete PlayfairCipher.cpp --- Others/PlayfairCipher.cpp | 83 --------------------------------------- 1 file changed, 83 deletions(-) delete mode 100644 Others/PlayfairCipher.cpp diff --git a/Others/PlayfairCipher.cpp b/Others/PlayfairCipher.cpp deleted file mode 100644 index fdb327cfc..000000000 --- a/Others/PlayfairCipher.cpp +++ /dev/null @@ -1,83 +0,0 @@ -#include -#include -#include -#define ENGLISH_ABC "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - -using namespace std; - -inline pair getCoordinate(char*code_table,const char character) { - for (uint8_t x(0); x < 5;x++) { - for (uint8_t y(0); y < 5;y++) { - if (*(code_table + (x * 5) + y) == character) - return make_pair(x, y); - } - } -} -string playfair(string str, string keyword) { - - char code_table[5][5]; - int32_t keyword_index(-1); - - string::iterator str_iter = str.begin(), keywor_iter = keyword.begin(); - - while (str_iter != str.end() || keywor_iter != keyword.end()) - { - if (str_iter != str.end()) { - if ((*str_iter = toupper(*str_iter)) >= 'A' && *str_iter <= 'Z') - str_iter++; - else str.erase(str_iter); - } - if (keywor_iter != keyword.end()) { - if ((*keywor_iter = toupper(*keywor_iter)) >= 'A' && *keywor_iter <= 'Z') - keywor_iter++; - else keyword.erase(keywor_iter); - } - } - if (str.length() == 0)return str; - - keyword.append(ENGLISH_ABC); - for (uint8_t x(0); x < 5;x++) { - for (uint8_t y(0); y < 5;y++) { - while (true) - { - if (keyword.find_first_of(keyword.at(++keyword_index)) == keyword_index){ - code_table[x][y] = keyword.at(keyword_index); - break; - } - } - } - } - - for (string::iterator iter = str.begin() + 1; iter != str.end(); iter+= iter == str.end() - 1 ? 1 : 2) { - if (*(iter - 1) == *iter) - str.insert(iter, 'x'); - } - if (str.length() % 2 != 0) str.append("x"); - - for (string::iterator iter = str.begin(); iter != str.end(); iter += 2) { - pair, pair> character_pair_coordinate; - character_pair_coordinate.first = getCoordinate(&code_table[0][0], *iter); - character_pair_coordinate.second = getCoordinate(&code_table[0][0], *(iter + 1)); - if (character_pair_coordinate.first.first == character_pair_coordinate.second.first) // x1 == x2 - { - *iter = (code_table[character_pair_coordinate.first.first][(character_pair_coordinate.first.second + 1) % 5]); - *(iter + 1) = (code_table[character_pair_coordinate.second.first][(character_pair_coordinate.second.second + 1) % 5]); - } - else if (character_pair_coordinate.first.second == character_pair_coordinate.second.second) //y1 == y2 - { - *iter = (code_table[(character_pair_coordinate.first.first + 1) % 5][character_pair_coordinate.first.second]); - *(iter + 1) = (code_table[(character_pair_coordinate.second.first + 1) % 5][character_pair_coordinate.second.second]); - } - else - { - *iter = (code_table[character_pair_coordinate.first.first ][character_pair_coordinate.second.second]); - *(iter + 1) = (code_table[character_pair_coordinate.second.first][character_pair_coordinate.first.second]); - } - } - - return str; -} -int main(){ - playfair("Welcome from Hungary!","playfair"); //return the encrypted text - return 0; -} From 969652b422a3f2c13438118b056f4a579373330f Mon Sep 17 00:00:00 2001 From: Divide-et-impera-11 <54957167+Divide-et-impera-11@users.noreply.github.com> Date: Fri, 29 Nov 2019 02:48:37 +0100 Subject: [PATCH 084/277] Delete matrix_layer_rotation.cpp --- .../matrix_layer_rotation.cpp | 52 ------------------- 1 file changed, 52 deletions(-) delete mode 100644 Operations on Datastructures/matrix_layer_rotation.cpp diff --git a/Operations on Datastructures/matrix_layer_rotation.cpp b/Operations on Datastructures/matrix_layer_rotation.cpp deleted file mode 100644 index 1056b2523..000000000 --- a/Operations on Datastructures/matrix_layer_rotation.cpp +++ /dev/null @@ -1,52 +0,0 @@ -#include -#include -using namespace std; -template inline void do_rotate(Type* rotated_matrix, const pair& position, const unsigned &row, const unsigned &columm, const uint8_t inside_row, const uint8_t inside_columm, const uint8_t rotation_position, const Type* const element) { - int*rotated_matrix_walker = (rotated_matrix + position.first * columm + (position.second)); - int offset = 1, element_index = -1; - while (true) - { - if (++element_index == rotation_position) { - *rotated_matrix_walker = *element; - return; - } - rotated_matrix_walker += offset; - if (rotated_matrix + ((position.first * columm) + position.second + inside_columm - 1) == rotated_matrix_walker) offset = columm; - else if (rotated_matrix + ((position.first * columm) + position.second + ((inside_row - 1) * columm) + inside_columm - 1) == rotated_matrix_walker) offset = -1; - else if (rotated_matrix + ((position.first * columm) + position.second + ((inside_row - 1) * columm)) == rotated_matrix_walker) offset = -1 * columm; - } -} -template Type* matrix_rotation(Type * const matrix, const unsigned row, const unsigned column, const unsigned rotation) { - pair position = make_pair(0, 0); - Type *rotated_matrix = new Type[row * column]; - int offset = 1; - int *matrix_walker = matrix; - uint8_t inside_row = row, inside_column = column; - int32_t array_lenght(0), element_index(0); - while (inside_row > 0 && inside_column > 0) - { - array_lenght = (2 * inside_column + ((inside_row - 2) * 2)); - do - { - do_rotate(rotated_matrix, position, row, column, inside_row, inside_column, (rotation + element_index) % array_lenght, matrix_walker); - matrix_walker += offset; - element_index++; - if (matrix + ((position.first * column) + position.second + inside_column - 1) == matrix_walker) offset = column; - else if (matrix + ((position.first * column) + position.second + ((inside_row - 1) * column) + inside_column - 1) == matrix_walker) offset = -1; - else if (matrix + ((position.first * column) + position.second + ((inside_row - 1) * column)) == matrix_walker) offset = -1 * column; - } while ((matrix + (position.first * column + position.second)) != matrix_walker); - position.first++; - position.second++; - inside_row -= 2; - inside_column -= 2; - offset = 1; - matrix_walker = matrix + (position.first * column) + (position.second); - } - return rotated_matrix; -} -int main() -{ - int *matrix = new int[16]{7,20,31,90,9,10,40,8,50,2,70,10,10,20,25,49}; - int*rotated_matrix = matrix_rotation(matrix,4,4,1); - return 0; -} From 895010d8a9f568789a19f32036c61e17702a4165 Mon Sep 17 00:00:00 2001 From: Divide-et-impera-11 <54957167+Divide-et-impera-11@users.noreply.github.com> Date: Fri, 29 Nov 2019 03:02:08 +0100 Subject: [PATCH 085/277] Update exponential_search.cpp --- Search/exponential_search.cpp | 60 ++++++++++++++++------------------- 1 file changed, 27 insertions(+), 33 deletions(-) diff --git a/Search/exponential_search.cpp b/Search/exponential_search.cpp index b0f1d5aa3..7a0349917 100644 --- a/Search/exponential_search.cpp +++ b/Search/exponential_search.cpp @@ -2,55 +2,49 @@ #include #include using namespaces std; - -//-----------------Binary Search Algorithm(use by struziki algorithm//----------------- -//Time Complexity O(log n) where 'n' is the number of elements -//Worst Time Complexity O(log n) -//Best Time Complexity Ω(1) -//Space Complexity O(1) -//Auxiliary Space Complexity O(1) - -template inline Type* binary_search(Type *array, size_t size, Type key) {//Parameter List:Pointer to and array|size of array|key what you search - int32_t lower_index(0), upper_index(size - 1),middle_index; //lower_index => start of search range | upper_index => end of search range | middle_index => middle of search range +//-----------------Binary Search Algorithm(use by Struzik algorithm)----------------- +// Time Complexity O(log n) where 'n' is the number of elements +// Worst Time Complexity O(log n) +// Best Time Complexity O(1) +// Space Complexity O(1) +// Auxiliary Space Complexity O(1) +template inline Type* binary_search(Type *array, size_t size, Type key) {//Parameter List:Pointer to an array|size of array|key what you search + int32_t lower_index(0), upper_index(size - 1),middle_index; //lower_index => start of search range|upper_index => end of search range while (lower_index <= upper_index) { middle_index = floor((lower_index + upper_index) / 2); - if (*(array + middle_index) < key) lower_index = (middle_index + 1); //if the key is smaller than the middle of search range, we narrow the search range from up - else if (*(array + middle_index) > key) upper_index = (middle_index - 1);//if the key is bigger than the middle of search range, we narrow the search range from down - else return (array + middle_index); //the key has been found + if (*(array + middle_index) < key) lower_index = (middle_index + 1); //narrow the search range from up + else if (*(array + middle_index) > key) upper_index = (middle_index - 1);//narrow the search range from down + else return (array + middle_index); //key has been found } return nullptr; } - -//-----------------Struzik Search Algorithm(Exponential//----------------- -//Time Complexity O(log i)where i is the position of the search key in the list -//Worst Time Complexity O(log i) -//Best Time Complexity Ω(1) -//Space Complexity O(1) -//Auxiliary Space Complexity O(1) - -template Type* Struzik_Search(Type* array,size_t size,Type key) { //Parameter List: Pointer to an array(sorted)!You can use complex objectum, but in that case you have to overload '<>' operators!|size of array|key what you search - uint32_t block_front(0),block_size = size == 0 ? 0 : 1; //the start and end of the first block where the algorithm starts seach !if the size of array 0 than return null pointer - while (block_front != block_size) //when the start of block(block_front) and end of block(block_size) equal it means the key bigger than the last element of array and it return null pointer +//-----------------Struzik Search Algorithm(Exponential)----------------- +// Time Complexity O(log i)where i is the position of the search key in the list +// Worst Time Complexity O(log i) +// Best Time Complexity O(1) +// Space Complexity O(1) +// Auxiliary Space Complexity O(1) +template Type* Struzik_Search(Type* array,size_t size,Type key) { // Parameter List:Pointer to an array|size of array|key what you search + uint32_t block_front(0),block_size = size == 0 ? 0 : 1; //block_front => start of search range|block_size => end of search range + while (block_front != block_size) //if key bigger than last element itt will be equal and return nullptr { if (*(array + block_size - 1) < key) {//if the key is bigger than the end of block we define a new block what is twice bigger than the previous block_front = block_size; (block_size * 2 - 1 < size) ? (block_size *= 2) : block_size = size;//if the end of new block bigger than size of array it takes the end of array continue; } - //when the algorithm delimit the block where the key shold be we do a binary search there - return binary_search(array + block_front, (block_size - block_front), key); + return binary_search(array + block_front, (block_size - block_front), key);//if delimit the block where the key shold be,do binary search } return nullptr; } int main(){ - - //----------------TEST CASES---------------- + // ----------------TEST CASES---------------- int *sorted_array = new int[7]{ 7,10,15,23,70,105,203 }; - assert(Struzik_Search(sorted_array, 7, 0) == nullptr); //Key smaller than the first element of array - assert(Struzik_Search(sorted_array, 7, 1000) == nullptr); //Key bigger than the last element of array - assert(Struzik_Search(sorted_array, 7, 50) == nullptr); //Key between the elemenets of array - assert(Struzik_Search(sorted_array, 7, 7) == sorted_array);//Key is in the array !FOUND! - //----------------TEST CASES---------------- + assert(Struzik_Search(sorted_array, 7, 0) == nullptr);// Key smaller than the first element of array + assert(Struzik_Search(sorted_array, 7, 1000) == nullptr);// Key bigger than the last element of array + assert(Struzik_Search(sorted_array, 7, 50) == nullptr);// Key between the elemenets of array + assert(Struzik_Search(sorted_array, 7, 7) == sorted_array);// Key is in the array !FOUND! + // ----------------TEST CASES---------------- return EXIT_SUCCESS; } From 51c26b85fe1f75e3ca1cd2e756dadf1fc0bf01a6 Mon Sep 17 00:00:00 2001 From: Divide-et-impera-11 <54957167+Divide-et-impera-11@users.noreply.github.com> Date: Sat, 30 Nov 2019 19:58:22 +0100 Subject: [PATCH 086/277] Update exponential_search.cpp --- Search/exponential_search.cpp | 45 +++++++++++++---------------------- 1 file changed, 16 insertions(+), 29 deletions(-) diff --git a/Search/exponential_search.cpp b/Search/exponential_search.cpp index 7a0349917..243c28c8b 100644 --- a/Search/exponential_search.cpp +++ b/Search/exponential_search.cpp @@ -1,50 +1,37 @@ +// Copyright 2020 Divide-et-impera-11 #include #include #include using namespaces std; -//-----------------Binary Search Algorithm(use by Struzik algorithm)----------------- -// Time Complexity O(log n) where 'n' is the number of elements -// Worst Time Complexity O(log n) -// Best Time Complexity O(1) -// Space Complexity O(1) -// Auxiliary Space Complexity O(1) -template inline Type* binary_search(Type *array, size_t size, Type key) {//Parameter List:Pointer to an array|size of array|key what you search - int32_t lower_index(0), upper_index(size - 1),middle_index; //lower_index => start of search range|upper_index => end of search range +template inline Type* binary_search(Type *array, size_t size, Type key){ + int32_t lower_index(0), upper_index(size - 1),middle_index; while (lower_index <= upper_index) { middle_index = floor((lower_index + upper_index) / 2); - if (*(array + middle_index) < key) lower_index = (middle_index + 1); //narrow the search range from up - else if (*(array + middle_index) > key) upper_index = (middle_index - 1);//narrow the search range from down - else return (array + middle_index); //key has been found + if (*(array + middle_index) < key) lower_index = (middle_index + 1); + else if (*(array + middle_index) > key) upper_index = (middle_index - 1); + else return (array + middle_index); } return nullptr; } -//-----------------Struzik Search Algorithm(Exponential)----------------- -// Time Complexity O(log i)where i is the position of the search key in the list -// Worst Time Complexity O(log i) -// Best Time Complexity O(1) -// Space Complexity O(1) -// Auxiliary Space Complexity O(1) -template Type* Struzik_Search(Type* array,size_t size,Type key) { // Parameter List:Pointer to an array|size of array|key what you search - uint32_t block_front(0),block_size = size == 0 ? 0 : 1; //block_front => start of search range|block_size => end of search range - while (block_front != block_size) //if key bigger than last element itt will be equal and return nullptr +template Type* Struzik_Search(Type* array,size_t size,Type key) { + uint32_t block_front(0),block_size = size == 0 ? 0 : 1; + while (block_front != block_size) { - if (*(array + block_size - 1) < key) {//if the key is bigger than the end of block we define a new block what is twice bigger than the previous + if (*(array + block_size - 1) < key) { block_front = block_size; - (block_size * 2 - 1 < size) ? (block_size *= 2) : block_size = size;//if the end of new block bigger than size of array it takes the end of array + (block_size * 2 - 1 < size) ? (block_size *= 2) : block_size = size; continue; } - return binary_search(array + block_front, (block_size - block_front), key);//if delimit the block where the key shold be,do binary search + return binary_search(array + block_front, (block_size - block_front), key); } return nullptr; } int main(){ - // ----------------TEST CASES---------------- int *sorted_array = new int[7]{ 7,10,15,23,70,105,203 }; - assert(Struzik_Search(sorted_array, 7, 0) == nullptr);// Key smaller than the first element of array - assert(Struzik_Search(sorted_array, 7, 1000) == nullptr);// Key bigger than the last element of array - assert(Struzik_Search(sorted_array, 7, 50) == nullptr);// Key between the elemenets of array - assert(Struzik_Search(sorted_array, 7, 7) == sorted_array);// Key is in the array !FOUND! - // ----------------TEST CASES---------------- + assert(Struzik_Search(sorted_array, 7, 0) == nullptr); + assert(Struzik_Search(sorted_array, 7, 1000) == nullptr); + assert(Struzik_Search(sorted_array, 7, 50) == nullptr); + assert(Struzik_Search(sorted_array, 7, 7) == sorted_array); return EXIT_SUCCESS; } From 36a3999f3edb82f6c62ab5f295fb27625b2a9b39 Mon Sep 17 00:00:00 2001 From: Divide-et-impera-11 <54957167+Divide-et-impera-11@users.noreply.github.com> Date: Sat, 30 Nov 2019 21:01:52 +0100 Subject: [PATCH 087/277] Update exponential_search.cpp --- Search/exponential_search.cpp | 44 +++++++++++++++++------------------ 1 file changed, 21 insertions(+), 23 deletions(-) diff --git a/Search/exponential_search.cpp b/Search/exponential_search.cpp index 243c28c8b..06f9ebf51 100644 --- a/Search/exponential_search.cpp +++ b/Search/exponential_search.cpp @@ -3,32 +3,30 @@ #include #include using namespaces std; -template inline Type* binary_search(Type *array, size_t size, Type key){ - int32_t lower_index(0), upper_index(size - 1),middle_index; - while (lower_index <= upper_index) - { - middle_index = floor((lower_index + upper_index) / 2); - if (*(array + middle_index) < key) lower_index = (middle_index + 1); - else if (*(array + middle_index) > key) upper_index = (middle_index - 1); - else return (array + middle_index); - } - return nullptr; +template inline Type* binary_s(Type *array, size_t size, Type key) { + int32_t lower_index(0), upper_index(size - 1), middle_index; + while (lower_index <= upper_index) { + middle_index = floor((lower_index + upper_index) / 2); + if (*(array + middle_index) < key) lower_index = (middle_index + 1); + else if (*(array + middle_index) > key)upper_index = (middle_index - 1); + else return (array + middle_index); + } + return nullptr; } -template Type* Struzik_Search(Type* array,size_t size,Type key) { - uint32_t block_front(0),block_size = size == 0 ? 0 : 1; - while (block_front != block_size) - { - if (*(array + block_size - 1) < key) { - block_front = block_size; - (block_size * 2 - 1 < size) ? (block_size *= 2) : block_size = size; - continue; - } - return binary_search(array + block_front, (block_size - block_front), key); +template Type* Struzik_Search(Type* array, size_t size, Type key) { + uint32_t block_front(0), block_size = size == 0 ? 0 : 1; + while (block_front != block_size) { + if (*(array + block_size - 1) < key) { + block_front = block_size; + (block_size * 2 - 1 < size) ? (block_size *= 2) : block_size = size; + continue; } - return nullptr; + return binary_s(array + block_front, (block_size - block_front), key); + } + return nullptr; } -int main(){ - int *sorted_array = new int[7]{ 7,10,15,23,70,105,203 }; +int main() { + int *sorted_array = new int[7]{7, 10, 15, 23, 70, 105, 203}; assert(Struzik_Search(sorted_array, 7, 0) == nullptr); assert(Struzik_Search(sorted_array, 7, 1000) == nullptr); assert(Struzik_Search(sorted_array, 7, 50) == nullptr); From 38fb290b88c0a6454237af6523b1a2d1bc6fe9e8 Mon Sep 17 00:00:00 2001 From: Divide-et-impera-11 <54957167+Divide-et-impera-11@users.noreply.github.com> Date: Sat, 30 Nov 2019 21:13:17 +0100 Subject: [PATCH 088/277] Update exponential_search.cpp --- Search/exponential_search.cpp | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/Search/exponential_search.cpp b/Search/exponential_search.cpp index 06f9ebf51..13ed28d6f 100644 --- a/Search/exponential_search.cpp +++ b/Search/exponential_search.cpp @@ -1,17 +1,17 @@ // Copyright 2020 Divide-et-impera-11 +#include #include #include -#include using namespaces std; template inline Type* binary_s(Type *array, size_t size, Type key) { - int32_t lower_index(0), upper_index(size - 1), middle_index; - while (lower_index <= upper_index) { - middle_index = floor((lower_index + upper_index) / 2); - if (*(array + middle_index) < key) lower_index = (middle_index + 1); - else if (*(array + middle_index) > key)upper_index = (middle_index - 1); - else return (array + middle_index); - } - return nullptr; +int32_t lower_index(0), upper_index(size - 1), middle_index; +while (lower_index <= upper_index) { + middle_index = floor((lower_index + upper_index) / 2); + if (*(array + middle_index) < key) lower_index = (middle_index + 1); + else if (*(array + middle_index) > key)upper_index = (middle_index - 1); + else return (array + middle_index); + } +return nullptr; } template Type* Struzik_Search(Type* array, size_t size, Type key) { uint32_t block_front(0), block_size = size == 0 ? 0 : 1; @@ -23,13 +23,13 @@ template Type* Struzik_Search(Type* array, size_t size, Type key) { } return binary_s(array + block_front, (block_size - block_front), key); } - return nullptr; +return nullptr; } int main() { - int *sorted_array = new int[7]{7, 10, 15, 23, 70, 105, 203}; - assert(Struzik_Search(sorted_array, 7, 0) == nullptr); - assert(Struzik_Search(sorted_array, 7, 1000) == nullptr); - assert(Struzik_Search(sorted_array, 7, 50) == nullptr); - assert(Struzik_Search(sorted_array, 7, 7) == sorted_array); - return EXIT_SUCCESS; + int *sorted_array = new int[7]{7, 10, 15, 23, 70, 105, 203}; + assert(Struzik_Search(sorted_array, 7, 0) == nullptr); + assert(Struzik_Search(sorted_array, 7, 1000) == nullptr); + assert(Struzik_Search(sorted_array, 7, 50) == nullptr); + assert(Struzik_Search(sorted_array, 7, 7) == sorted_array); +return EXIT_SUCCESS; } From f197fa38e3bcde5782291c7210b403cba84b11fc Mon Sep 17 00:00:00 2001 From: Divide-et-impera-11 <54957167+Divide-et-impera-11@users.noreply.github.com> Date: Sat, 30 Nov 2019 21:15:03 +0100 Subject: [PATCH 089/277] Update exponential_search.cpp --- Search/exponential_search.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Search/exponential_search.cpp b/Search/exponential_search.cpp index 13ed28d6f..90ce27409 100644 --- a/Search/exponential_search.cpp +++ b/Search/exponential_search.cpp @@ -26,10 +26,10 @@ template Type* Struzik_Search(Type* array, size_t size, Type key) { return nullptr; } int main() { - int *sorted_array = new int[7]{7, 10, 15, 23, 70, 105, 203}; - assert(Struzik_Search(sorted_array, 7, 0) == nullptr); - assert(Struzik_Search(sorted_array, 7, 1000) == nullptr); - assert(Struzik_Search(sorted_array, 7, 50) == nullptr); - assert(Struzik_Search(sorted_array, 7, 7) == sorted_array); +int *sorted_array = new int[7]{7, 10, 15, 23, 70, 105, 203}; +assert(Struzik_Search(sorted_array, 7, 0) == nullptr); +assert(Struzik_Search(sorted_array, 7, 1000) == nullptr); +assert(Struzik_Search(sorted_array, 7, 50) == nullptr); +assert(Struzik_Search(sorted_array, 7, 7) == sorted_array); return EXIT_SUCCESS; } From c1629a93909943794d77db3536a2c1ca2e3efa90 Mon Sep 17 00:00:00 2001 From: Divide-et-impera-11 <54957167+Divide-et-impera-11@users.noreply.github.com> Date: Sat, 30 Nov 2019 21:20:54 +0100 Subject: [PATCH 090/277] Update exponential_search.cpp --- Search/exponential_search.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Search/exponential_search.cpp b/Search/exponential_search.cpp index 90ce27409..1c12351a2 100644 --- a/Search/exponential_search.cpp +++ b/Search/exponential_search.cpp @@ -13,7 +13,7 @@ while (lower_index <= upper_index) { } return nullptr; } -template Type* Struzik_Search(Type* array, size_t size, Type key) { +template Type* struzik_search(Type* array, size_t size, Type key) { uint32_t block_front(0), block_size = size == 0 ? 0 : 1; while (block_front != block_size) { if (*(array + block_size - 1) < key) { @@ -27,9 +27,9 @@ return nullptr; } int main() { int *sorted_array = new int[7]{7, 10, 15, 23, 70, 105, 203}; -assert(Struzik_Search(sorted_array, 7, 0) == nullptr); -assert(Struzik_Search(sorted_array, 7, 1000) == nullptr); -assert(Struzik_Search(sorted_array, 7, 50) == nullptr); -assert(Struzik_Search(sorted_array, 7, 7) == sorted_array); -return EXIT_SUCCESS; +assert(struzik_search(sorted_array, 7, 0) == nullptr); +assert(struzik_search(sorted_array, 7, 1000) == nullptr); +assert(struzik_search(sorted_array, 7, 50) == nullptr); +assert(struzik_search(sorted_array, 7, 7) == sorted_array); +return 0; } From 51da734a423689f25a4488d9a68338a868d67672 Mon Sep 17 00:00:00 2001 From: Divide-et-impera-11 <54957167+Divide-et-impera-11@users.noreply.github.com> Date: Sat, 30 Nov 2019 21:27:08 +0100 Subject: [PATCH 091/277] Update exponential_search.cpp --- Search/exponential_search.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Search/exponential_search.cpp b/Search/exponential_search.cpp index 1c12351a2..f5302eee0 100644 --- a/Search/exponential_search.cpp +++ b/Search/exponential_search.cpp @@ -1,9 +1,9 @@ -// Copyright 2020 Divide-et-impera-11 +// copyright 2020 divide-et-impera-11 #include #include #include using namespaces std; -template inline Type* binary_s(Type *array, size_t size, Type key) { +template inline type* binary_s(type *array, size_t size, type key) { int32_t lower_index(0), upper_index(size - 1), middle_index; while (lower_index <= upper_index) { middle_index = floor((lower_index + upper_index) / 2); @@ -13,7 +13,7 @@ while (lower_index <= upper_index) { } return nullptr; } -template Type* struzik_search(Type* array, size_t size, Type key) { +template type* struzik_search(type* array, size_t size, type key) { uint32_t block_front(0), block_size = size == 0 ? 0 : 1; while (block_front != block_size) { if (*(array + block_size - 1) < key) { @@ -21,7 +21,7 @@ template Type* struzik_search(Type* array, size_t size, Type key) { (block_size * 2 - 1 < size) ? (block_size *= 2) : block_size = size; continue; } - return binary_s(array + block_front, (block_size - block_front), key); + return binary_s(array + block_front, (block_size - block_front), key); } return nullptr; } From 16007b980831ec4cd9221e4bcfdeed2d903197e5 Mon Sep 17 00:00:00 2001 From: Divide-et-impera-11 <54957167+Divide-et-impera-11@users.noreply.github.com> Date: Sat, 30 Nov 2019 21:32:32 +0100 Subject: [PATCH 092/277] Update exponential_search.cpp --- Search/exponential_search.cpp | 29 ----------------------------- 1 file changed, 29 deletions(-) diff --git a/Search/exponential_search.cpp b/Search/exponential_search.cpp index f5302eee0..0684bc602 100644 --- a/Search/exponential_search.cpp +++ b/Search/exponential_search.cpp @@ -1,35 +1,6 @@ // copyright 2020 divide-et-impera-11 -#include #include #include -using namespaces std; -template inline type* binary_s(type *array, size_t size, type key) { -int32_t lower_index(0), upper_index(size - 1), middle_index; -while (lower_index <= upper_index) { - middle_index = floor((lower_index + upper_index) / 2); - if (*(array + middle_index) < key) lower_index = (middle_index + 1); - else if (*(array + middle_index) > key)upper_index = (middle_index - 1); - else return (array + middle_index); - } -return nullptr; -} -template type* struzik_search(type* array, size_t size, type key) { - uint32_t block_front(0), block_size = size == 0 ? 0 : 1; - while (block_front != block_size) { - if (*(array + block_size - 1) < key) { - block_front = block_size; - (block_size * 2 - 1 < size) ? (block_size *= 2) : block_size = size; - continue; - } - return binary_s(array + block_front, (block_size - block_front), key); - } -return nullptr; -} int main() { -int *sorted_array = new int[7]{7, 10, 15, 23, 70, 105, 203}; -assert(struzik_search(sorted_array, 7, 0) == nullptr); -assert(struzik_search(sorted_array, 7, 1000) == nullptr); -assert(struzik_search(sorted_array, 7, 50) == nullptr); -assert(struzik_search(sorted_array, 7, 7) == sorted_array); return 0; } From 63f9fd2dc52f2ca721050a52057f86aa06f73ca7 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Sat, 30 Nov 2019 21:52:06 +0100 Subject: [PATCH 093/277] Search -> search --- {Search => search}/exponential_search.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Search => search}/exponential_search.cpp (100%) diff --git a/Search/exponential_search.cpp b/search/exponential_search.cpp similarity index 100% rename from Search/exponential_search.cpp rename to search/exponential_search.cpp From eeb7d5caa505129de9bcdcba442ee95f7a03dbfb Mon Sep 17 00:00:00 2001 From: Divide-et-impera-11 <54957167+Divide-et-impera-11@users.noreply.github.com> Date: Sat, 30 Nov 2019 22:41:18 +0100 Subject: [PATCH 094/277] Update exponential_search.cpp --- search/exponential_search.cpp | 43 ++++++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/search/exponential_search.cpp b/search/exponential_search.cpp index 0684bc602..e140d9df6 100644 --- a/search/exponential_search.cpp +++ b/search/exponential_search.cpp @@ -1,6 +1,47 @@ -// copyright 2020 divide-et-impera-11 +// Copyright 2020 Divide-et-Impera-11 +#include #include #include +using namespaces std; +// Binary Search Algorithm(use by struziki algorithm) +// Time Complexity O(log n) where 'n' is the number of elements +// Worst Time Complexity O(log n) +// Best Time Complexity Ω(1) +// Space Complexity O(1) +// Auxiliary Space Complexity O(1) +template inline Type* binary_s(Type *array, size_t size, Type key) { +int32_t lower_index(0), upper_index(size - 1), middle_index; +while (lower_index <= upper_index) { + middle_index = floor((lower_index + upper_index) / 2); + if (*(array + middle_index) < key) lower_index = (middle_index + 1); + else if (*(array + middle_index) > key)upper_index = (middle_index - 1); + else return (array + middle_index); + } +return nullptr; +} +// Struzik Search Algorithm(Exponential) +// Time Complexity O(log i)where i is the position of search key in the list +// Worst Time Complexity O(log i) +// Best Time Complexity Ω(1) +// Space Complexity O(1) +// Auxiliary Space Complexity O(1) +template Type* struzik_search(Type* array, size_t size, Type key) { + uint32_t block_front(0), block_size = size == 0 ? 0 : 1; + while (block_front != block_size) { + if (*(array + block_size - 1) < key) { + block_front = block_size; + (block_size * 2 - 1 < size) ? (block_size *= 2) : block_size = size; + continue; + } + return binary_s(array + block_front, (block_size - block_front), key); + } +return nullptr; +} int main() { +int *sorted_array = new int[7]{7, 10, 15, 23, 70, 105, 203}; +assert(struzik_search(sorted_array, 7, 0) == nullptr); +assert(struzik_search(sorted_array, 7, 1000) == nullptr); +assert(struzik_search(sorted_array, 7, 50) == nullptr); +assert(struzik_search(sorted_array, 7, 7) == sorted_array); return 0; } From 67fdd7b7356f2b9c56f5fa325e8d172f81e61785 Mon Sep 17 00:00:00 2001 From: Divide-et-impera-11 <54957167+Divide-et-impera-11@users.noreply.github.com> Date: Sat, 30 Nov 2019 22:56:10 +0100 Subject: [PATCH 095/277] Update exponential_search.cpp --- search/exponential_search.cpp | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/search/exponential_search.cpp b/search/exponential_search.cpp index e140d9df6..d217fce64 100644 --- a/search/exponential_search.cpp +++ b/search/exponential_search.cpp @@ -1,9 +1,9 @@ -// Copyright 2020 Divide-et-Impera-11 +// Copyright 2020 Divide-et-impera-11 #include #include #include using namespaces std; -// Binary Search Algorithm(use by struziki algorithm) +// Binary Search Algorithm(use by struzik algorithm) // Time Complexity O(log n) where 'n' is the number of elements // Worst Time Complexity O(log n) // Best Time Complexity Ω(1) @@ -25,6 +25,13 @@ return nullptr; // Best Time Complexity Ω(1) // Space Complexity O(1) // Auxiliary Space Complexity O(1) +/* Tha algorithm try to search the range where the key should be. +If it has been found we do a binary search there. +The range of the search grows by exponential every time. +If the key is larger than the last element of array, +the start of block(block_front) will be equal to the end of block(block_size) +and the algorithm return null ponter, +every other cases the algoritm return fom the loop. */ template Type* struzik_search(Type* array, size_t size, Type key) { uint32_t block_front(0), block_size = size == 0 ? 0 : 1; while (block_front != block_size) { @@ -38,10 +45,12 @@ template Type* struzik_search(Type* array, size_t size, Type key) { return nullptr; } int main() { +// TEST CASES int *sorted_array = new int[7]{7, 10, 15, 23, 70, 105, 203}; assert(struzik_search(sorted_array, 7, 0) == nullptr); assert(struzik_search(sorted_array, 7, 1000) == nullptr); assert(struzik_search(sorted_array, 7, 50) == nullptr); assert(struzik_search(sorted_array, 7, 7) == sorted_array); +// TEST CASES return 0; } From dbb23219b2e5622016f03dd1326e0ef0fca84c17 Mon Sep 17 00:00:00 2001 From: Divide-et-impera-11 <54957167+Divide-et-impera-11@users.noreply.github.com> Date: Sat, 30 Nov 2019 22:58:04 +0100 Subject: [PATCH 096/277] Update exponential_search.cpp --- search/exponential_search.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/search/exponential_search.cpp b/search/exponential_search.cpp index d217fce64..b8343fa02 100644 --- a/search/exponential_search.cpp +++ b/search/exponential_search.cpp @@ -45,12 +45,12 @@ template Type* struzik_search(Type* array, size_t size, Type key) { return nullptr; } int main() { -// TEST CASES +// TEST CASES int *sorted_array = new int[7]{7, 10, 15, 23, 70, 105, 203}; assert(struzik_search(sorted_array, 7, 0) == nullptr); assert(struzik_search(sorted_array, 7, 1000) == nullptr); assert(struzik_search(sorted_array, 7, 50) == nullptr); assert(struzik_search(sorted_array, 7, 7) == sorted_array); -// TEST CASES +// TEST CASES return 0; } From 5931f3d23436cc635d5ccaa41c462cc6603bcfe9 Mon Sep 17 00:00:00 2001 From: Divide-et-impera-11 <54957167+Divide-et-impera-11@users.noreply.github.com> Date: Sat, 30 Nov 2019 22:58:27 +0100 Subject: [PATCH 097/277] Update exponential_search.cpp --- search/exponential_search.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/search/exponential_search.cpp b/search/exponential_search.cpp index b8343fa02..55e376f51 100644 --- a/search/exponential_search.cpp +++ b/search/exponential_search.cpp @@ -45,12 +45,12 @@ template Type* struzik_search(Type* array, size_t size, Type key) { return nullptr; } int main() { -// TEST CASES +//TEST CASES int *sorted_array = new int[7]{7, 10, 15, 23, 70, 105, 203}; assert(struzik_search(sorted_array, 7, 0) == nullptr); assert(struzik_search(sorted_array, 7, 1000) == nullptr); assert(struzik_search(sorted_array, 7, 50) == nullptr); assert(struzik_search(sorted_array, 7, 7) == sorted_array); -// TEST CASES +//TEST CASES return 0; } From 3b6e05e68fa5cab8fd2e542d061fca0aa000b529 Mon Sep 17 00:00:00 2001 From: Divide-et-impera-11 <54957167+Divide-et-impera-11@users.noreply.github.com> Date: Sat, 30 Nov 2019 22:59:52 +0100 Subject: [PATCH 098/277] Update exponential_search.cpp --- search/exponential_search.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/search/exponential_search.cpp b/search/exponential_search.cpp index 55e376f51..b8343fa02 100644 --- a/search/exponential_search.cpp +++ b/search/exponential_search.cpp @@ -45,12 +45,12 @@ template Type* struzik_search(Type* array, size_t size, Type key) { return nullptr; } int main() { -//TEST CASES +// TEST CASES int *sorted_array = new int[7]{7, 10, 15, 23, 70, 105, 203}; assert(struzik_search(sorted_array, 7, 0) == nullptr); assert(struzik_search(sorted_array, 7, 1000) == nullptr); assert(struzik_search(sorted_array, 7, 50) == nullptr); assert(struzik_search(sorted_array, 7, 7) == sorted_array); -//TEST CASES +// TEST CASES return 0; } From 332d18a13f4909dca5e3c9e243165ad5639b3099 Mon Sep 17 00:00:00 2001 From: Divide-et-impera-11 <54957167+Divide-et-impera-11@users.noreply.github.com> Date: Sat, 30 Nov 2019 23:00:07 +0100 Subject: [PATCH 099/277] Update exponential_search.cpp From 6511946c3e8b9a4b689ed28a487de11050f13b17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8B=8F=E6=B7=9E=E4=B8=B0?= <50102735+Arctic2333@users.noreply.github.com> Date: Mon, 2 Dec 2019 11:01:18 +0800 Subject: [PATCH 100/277] hash_search --- search/hash_search.cpp | 82 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 search/hash_search.cpp diff --git a/search/hash_search.cpp b/search/hash_search.cpp new file mode 100644 index 000000000..7ed7e5628 --- /dev/null +++ b/search/hash_search.cpp @@ -0,0 +1,82 @@ +// Copyright 2020 Arctic2333 +#include +#include +#define MAX 6 +# define HASHMAX 5 +int data[MAX] = { 12, 160, 219, 522, 725, 9997}; +typedef struct list { + int key; + struct list * next; +} +node, * link; +node hashtab[HASHMAX]; +int counter = 1; +int h(int key) { + return key % HASHMAX; +} +void create_list(int key) { + link p, n; + int index; + n = (link) malloc(sizeof(node)); + n -> key = key; + n -> next = NULL; + index = h(key); + p = hashtab[index].next; + if (p != NULL) { + n -> next = p; + hashtab[index].next = n; + } else + hashtab[index].next = n; +} +int hash_search(int key) { + link pointer; + int index; + counter = 0; + index = h(key); + pointer = hashtab[index].next; + printf("data[%d]:", index); + while (pointer != NULL) { + counter++; + printf("data[%d]:", pointer -> next); + if (pointer -> key == key) + return 1; + else + pointer = pointer -> next; + } + return 0; +} +int main() { + link p; + int key, index, i; + index = 0; + printf("input data:"); + for (i = 0; i < HASHMAX; i++) + scanf("%d", & data[i]); + printf("\n"); + while (index < MAX) { + create_list(data[index]); + index++; + } + for (i = 0; i < HASHMAX; i++) { + printf("hashtab [%d]", i); + printf("n"); + p = hashtab[i].next; + while (p != NULL) { + printf("please int key:"); + if (p -> key > 0) + printf("[%d]", p -> key); + p = p -> next; + } + printf("\n"); + } + while (key != -1) { + printf("please input data\n"); + scanf("%d", & key); + if (hash_search(key)) + printf("search time = %d\n", counter); + else + printf("no found!\n"); + + } + return 0; +} From eb5899ed15d09c88a883e0c184dcf9ef6f2817f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8B=8F=E6=B7=9E=E4=B8=B0?= <50102735+Arctic2333@users.noreply.github.com> Date: Mon, 2 Dec 2019 11:10:17 +0800 Subject: [PATCH 101/277] hash_search --- search/hash_search.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/search/hash_search.cpp b/search/hash_search.cpp index 7ed7e5628..6d591f376 100644 --- a/search/hash_search.cpp +++ b/search/hash_search.cpp @@ -25,7 +25,8 @@ void create_list(int key) { if (p != NULL) { n -> next = p; hashtab[index].next = n; - } else + } + else hashtab[index].next = n; } int hash_search(int key) { @@ -76,7 +77,6 @@ int main() { printf("search time = %d\n", counter); else printf("no found!\n"); - } return 0; } From 4d9470555f546f38d3c5b4a024ab88d133d27114 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8B=8F=E6=B7=9E=E4=B8=B0?= <50102735+Arctic2333@users.noreply.github.com> Date: Mon, 2 Dec 2019 11:12:56 +0800 Subject: [PATCH 102/277] hash_search --- search/hash_search.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/search/hash_search.cpp b/search/hash_search.cpp index 6d591f376..cd122fe2c 100644 --- a/search/hash_search.cpp +++ b/search/hash_search.cpp @@ -25,8 +25,7 @@ void create_list(int key) { if (p != NULL) { n -> next = p; hashtab[index].next = n; - } - else + } else hashtab[index].next = n; } int hash_search(int key) { From 4f83abdb507eeebe5d1051c46d793b236da68ba2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8B=8F=E6=B7=9E=E4=B8=B0?= <50102735+Arctic2333@users.noreply.github.com> Date: Mon, 2 Dec 2019 11:16:03 +0800 Subject: [PATCH 103/277] hash_search --- search/hash_search.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/search/hash_search.cpp b/search/hash_search.cpp index cd122fe2c..68c361384 100644 --- a/search/hash_search.cpp +++ b/search/hash_search.cpp @@ -25,8 +25,8 @@ void create_list(int key) { if (p != NULL) { n -> next = p; hashtab[index].next = n; - } else - hashtab[index].next = n; + } else { + hashtab[index].next = n; } } int hash_search(int key) { link pointer; From 3db7cefdd94bb7edfe6230f9b8d38ad2d92a452e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8B=8F=E6=B7=9E=E4=B8=B0?= <50102735+Arctic2333@users.noreply.github.com> Date: Mon, 2 Dec 2019 11:20:55 +0800 Subject: [PATCH 104/277] hash_search --- search/hash_search.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/search/hash_search.cpp b/search/hash_search.cpp index 68c361384..a89d8566b 100644 --- a/search/hash_search.cpp +++ b/search/hash_search.cpp @@ -3,6 +3,8 @@ #include #define MAX 6 # define HASHMAX 5 +// Hash Search Algorithm +// Best Time Complexity Ω(1) int data[MAX] = { 12, 160, 219, 522, 725, 9997}; typedef struct list { int key; From 1d04ac5ae6827d8c6e9128038e427511a9c141d9 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Mon, 2 Dec 2019 16:41:32 +0100 Subject: [PATCH 105/277] .cpplint: filter=-legal/copyright ; linelength=80 --- .cpplint | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .cpplint diff --git a/.cpplint b/.cpplint new file mode 100644 index 000000000..8b90d4a39 --- /dev/null +++ b/.cpplint @@ -0,0 +1,5 @@ +# See: cpplint --help # for all options +# Also: cpplint.py --filter= # for all filters +# Use - to turn off the requirement for a copyright comment +filter=-legal/copyright +linelength=80 From 1e261cb8fe955245eaeea6f35182cfa93c6e1c84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8B=8F=E6=B7=9E=E4=B8=B0?= <50102735+Arctic2333@users.noreply.github.com> Date: Tue, 3 Dec 2019 00:13:51 +0800 Subject: [PATCH 106/277] add function definitions --- search/hash_search.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/search/hash_search.cpp b/search/hash_search.cpp index a89d8566b..6b0c0dbca 100644 --- a/search/hash_search.cpp +++ b/search/hash_search.cpp @@ -16,7 +16,10 @@ int counter = 1; int h(int key) { return key % HASHMAX; } -void create_list(int key) { +// In this algorithm, we use the method of division and reservation remainder to construct the hash function, +// and use the method of chain address to solve the conflict, that is, we link a chain list after the data, +// and store all the records whose keywords are synonyms in the same linear chain list. +void create_list(int key) { // Construct hash table link p, n; int index; n = (link) malloc(sizeof(node)); @@ -30,7 +33,7 @@ void create_list(int key) { } else { hashtab[index].next = n; } } -int hash_search(int key) { +int hash_search(int key) { // Hash lookup function link pointer; int index; counter = 0; @@ -55,11 +58,11 @@ int main() { for (i = 0; i < HASHMAX; i++) scanf("%d", & data[i]); printf("\n"); - while (index < MAX) { + while (index < MAX) { // Construct hash table create_list(data[index]); index++; } - for (i = 0; i < HASHMAX; i++) { + for (i = 0; i < HASHMAX; i++) { // Output hash table printf("hashtab [%d]", i); printf("n"); p = hashtab[i].next; From b9f65b81d73ce5a26e8d0a12a50853195ffa0762 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8B=8F=E6=B7=9E=E4=B8=B0?= <50102735+Arctic2333@users.noreply.github.com> Date: Tue, 3 Dec 2019 00:16:30 +0800 Subject: [PATCH 107/277] add function definitions --- search/hash_search.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/search/hash_search.cpp b/search/hash_search.cpp index 6b0c0dbca..0428341b6 100644 --- a/search/hash_search.cpp +++ b/search/hash_search.cpp @@ -16,9 +16,9 @@ int counter = 1; int h(int key) { return key % HASHMAX; } -// In this algorithm, we use the method of division and reservation remainder to construct the hash function, -// and use the method of chain address to solve the conflict, that is, we link a chain list after the data, -// and store all the records whose keywords are synonyms in the same linear chain list. +/* In this algorithm, we use the method of division and reservation remainder to construct the hash function, + and use the method of chain address to solve the conflict, that is, we link a chain list after the data, + and store all the records whose keywords are synonyms in the same linear chain list. */ void create_list(int key) { // Construct hash table link p, n; int index; From cacd1ebcba6d5b305909feac88abaf05dd6dd894 Mon Sep 17 00:00:00 2001 From: Bhaumik Mistry Date: Mon, 2 Dec 2019 13:03:29 -0500 Subject: [PATCH 108/277] Update CONTRIBUTION.md add new directory updates. --- CONTRIBUTION.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTION.md b/CONTRIBUTION.md index a9cb80f49..bed0ef9fc 100644 --- a/CONTRIBUTION.md +++ b/CONTRIBUTION.md @@ -38,7 +38,8 @@ my_new_cpp_class.cpp is correct format - File name validation will run on docker to ensure the validity. #### New Directory guidelines -- Use lowercase words with ``"_"`` as separator ( no spaces or '-' allowed ) +- We recommend adding files to existing directories as mush as possible. +- Use lowercase words with ``"_"`` as separator ( no spaces or ```"-"``` allowed ) - For instance ``` SomeNew Fancy-Category is incorrect @@ -80,4 +81,4 @@ Common prefixes: - Checkout our [pull request template](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/.github/pull_request_template.md) - Most importantly, - - Happy coding! \ No newline at end of file + - Happy coding! From d8f55f2715561560a9dd7b0e037153c5c7d0391b Mon Sep 17 00:00:00 2001 From: Bhaumik Mistry Date: Mon, 2 Dec 2019 13:07:27 -0500 Subject: [PATCH 109/277] Update CONTRIBUTION.md spell change for # new directory guidelines --- CONTRIBUTION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTION.md b/CONTRIBUTION.md index bed0ef9fc..828964936 100644 --- a/CONTRIBUTION.md +++ b/CONTRIBUTION.md @@ -38,7 +38,7 @@ my_new_cpp_class.cpp is correct format - File name validation will run on docker to ensure the validity. #### New Directory guidelines -- We recommend adding files to existing directories as mush as possible. +- We recommend adding files to existing directories as much as possible. - Use lowercase words with ``"_"`` as separator ( no spaces or ```"-"``` allowed ) - For instance ``` From a7ad4ee9c4622bc39917b745102646f729b245a5 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Tue, 3 Dec 2019 10:54:56 +0100 Subject: [PATCH 110/277] Update .cpplint --- .cpplint | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.cpplint b/.cpplint index 8b90d4a39..bda1801bf 100644 --- a/.cpplint +++ b/.cpplint @@ -1,5 +1,7 @@ +set noparent +filter=-legal/copyright +linelength=80 + # See: cpplint --help # for all options # Also: cpplint.py --filter= # for all filters # Use - to turn off the requirement for a copyright comment -filter=-legal/copyright -linelength=80 From 657ae4f7e494ce6b4a60e0c682b30233f18cb8ea Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Tue, 3 Dec 2019 11:24:26 +0100 Subject: [PATCH 111/277] Rename String/knuth_morris_pratt.cpp to strings/knuth_morris_pratt.cpp --- {String => strings}/knuth_morris_pratt.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {String => strings}/knuth_morris_pratt.cpp (100%) diff --git a/String/knuth_morris_pratt.cpp b/strings/knuth_morris_pratt.cpp similarity index 100% rename from String/knuth_morris_pratt.cpp rename to strings/knuth_morris_pratt.cpp From e25cd6c0c26cde52a091ddaeb416c0c9d9d067b3 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Tue, 3 Dec 2019 11:38:30 +0100 Subject: [PATCH 112/277] cpplint filter=-legal/copyright --- .github/workflows/cpplint_modified_files.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/cpplint_modified_files.yml b/.github/workflows/cpplint_modified_files.yml index dcf2499e6..7350f1fa2 100644 --- a/.github/workflows/cpplint_modified_files.yml +++ b/.github/workflows/cpplint_modified_files.yml @@ -28,7 +28,7 @@ jobs: sys.exit(0) print("cpplint:") - print(subprocess.check_output(["cpplint"] + cpp_files).decode("utf-8")) + print(subprocess.check_output(["cpplint", "filter=-legal/copyright"] + cpp_files).decode("utf-8")) upper_files = [file for file in cpp_files if file != file.lower()] if upper_files: From 9fb42721de07681ced4d991ec91f1e5db562a13e Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Tue, 3 Dec 2019 11:38:53 +0100 Subject: [PATCH 113/277] Delete .cpplint --- .cpplint | 7 ------- 1 file changed, 7 deletions(-) delete mode 100644 .cpplint diff --git a/.cpplint b/.cpplint deleted file mode 100644 index bda1801bf..000000000 --- a/.cpplint +++ /dev/null @@ -1,7 +0,0 @@ -set noparent -filter=-legal/copyright -linelength=80 - -# See: cpplint --help # for all options -# Also: cpplint.py --filter= # for all filters -# Use - to turn off the requirement for a copyright comment From f3da4bd7c66e175f15dc54a0373329d9c4c12f89 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Tue, 3 Dec 2019 12:06:19 +0100 Subject: [PATCH 114/277] cpplint --filter=-legal/copyright --- .github/workflows/cpplint_modified_files.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/cpplint_modified_files.yml b/.github/workflows/cpplint_modified_files.yml index 7350f1fa2..5671d34f3 100644 --- a/.github/workflows/cpplint_modified_files.yml +++ b/.github/workflows/cpplint_modified_files.yml @@ -28,7 +28,7 @@ jobs: sys.exit(0) print("cpplint:") - print(subprocess.check_output(["cpplint", "filter=-legal/copyright"] + cpp_files).decode("utf-8")) + print(subprocess.check_output(["cpplint", "--filter=-legal/copyright"] + cpp_files).decode("utf-8")) upper_files = [file for file in cpp_files if file != file.lower()] if upper_files: From 27c1e3958a7f24d2daf3abe0aa27ed9579a71145 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8B=8F=E6=B7=9E=E4=B8=B0?= <50102735+Arctic2333@users.noreply.github.com> Date: Wed, 4 Dec 2019 00:03:55 +0800 Subject: [PATCH 115/277] hash_search --- search/hash_search.cpp | 48 +++++++++++++++++++++++++++--------------- 1 file changed, 31 insertions(+), 17 deletions(-) diff --git a/search/hash_search.cpp b/search/hash_search.cpp index 0428341b6..372f5863e 100644 --- a/search/hash_search.cpp +++ b/search/hash_search.cpp @@ -1,11 +1,15 @@ // Copyright 2020 Arctic2333 #include #include -#define MAX 6 -# define HASHMAX 5 -// Hash Search Algorithm -// Best Time Complexity Ω(1) -int data[MAX] = { 12, 160, 219, 522, 725, 9997}; +#define MAX 6 // Determines how much data +# define HASHMAX 5 // Determines the length of the hash table +/** + * Hash Search Algorithm + * Best Time Complexity Ω(1) + * In this algorithm, we use the method of division and reservation remainder to construct the hash function, + * and use the method of chain address to solve the conflict, that is, we link a chain list after the data, + * and store all the records whose keywords are synonyms in the same linear chain list. */ +int data[MAX] = { 1, 10, 15, 5, 8, 7}; // test data typedef struct list { int key; struct list * next; @@ -13,12 +17,16 @@ typedef struct list { node, * link; node hashtab[HASHMAX]; int counter = 1; +/* int h(int key) + * Mode of hash detection : + * Division method */ int h(int key) { return key % HASHMAX; } -/* In this algorithm, we use the method of division and reservation remainder to construct the hash function, - and use the method of chain address to solve the conflict, that is, we link a chain list after the data, - and store all the records whose keywords are synonyms in the same linear chain list. */ +/* void create_list(int key) + * The same after the remainder will be added after the same hash header + * To avoid conflict, zipper method is used + * Insert elements into the linked list in the header */ void create_list(int key) { // Construct hash table link p, n; int index; @@ -33,6 +41,11 @@ void create_list(int key) { // Construct hash table } else { hashtab[index].next = n; } } +/* int hash_search(int key) + * Input the key to be searched, and get the hash header position through the H (int key) function, + * then one-dimensional linear search. + * If found @return element depth and number of searches + * If not found @return -1 */ int hash_search(int key) { // Hash lookup function link pointer; int index; @@ -42,7 +55,7 @@ int hash_search(int key) { // Hash lookup function printf("data[%d]:", index); while (pointer != NULL) { counter++; - printf("data[%d]:", pointer -> next); + printf("data[%d]:", pointer -> key); if (pointer -> key == key) return 1; else @@ -52,19 +65,16 @@ int hash_search(int key) { // Hash lookup function } int main() { link p; - int key, index, i; + int key, index, i; // Key is the value to be found index = 0; - printf("input data:"); - for (i = 0; i < HASHMAX; i++) - scanf("%d", & data[i]); - printf("\n"); + // You can write the input mode here while (index < MAX) { // Construct hash table create_list(data[index]); index++; } for (i = 0; i < HASHMAX; i++) { // Output hash table printf("hashtab [%d]", i); - printf("n"); + printf("\n"); p = hashtab[i].next; while (p != NULL) { printf("please int key:"); @@ -75,12 +85,16 @@ int main() { printf("\n"); } while (key != -1) { - printf("please input data\n"); - scanf("%d", & key); + // You can write the input mode here + // test key = 10 + key = 10; if (hash_search(key)) printf("search time = %d\n", counter); else printf("no found!\n"); + key = -1; // Exit test + /* The test sample is returned as: data[0]:data[5]:data[15]:data[10]:search time = 3 + * The search is successful. There are 10 in this set of data */ } return 0; } From bbea5ad5aa969386a033bcf168b3cc08a02804a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8B=8F=E6=B7=9E=E4=B8=B0?= <50102735+Arctic2333@users.noreply.github.com> Date: Wed, 4 Dec 2019 00:07:31 +0800 Subject: [PATCH 116/277] hash_seaarch --- search/hash_search.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/search/hash_search.cpp b/search/hash_search.cpp index 372f5863e..94d87b58a 100644 --- a/search/hash_search.cpp +++ b/search/hash_search.cpp @@ -2,7 +2,7 @@ #include #include #define MAX 6 // Determines how much data -# define HASHMAX 5 // Determines the length of the hash table +# define HASHMAX 5 // Determines the length of the hash table /** * Hash Search Algorithm * Best Time Complexity Ω(1) From 8b237946ba4259d1270c2b5c654414e07545550c Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 4 Dec 2019 04:47:11 +0100 Subject: [PATCH 117/277] doc: Add cpplint to CONTRIBUTION.md (#676) --- CONTRIBUTION.md | 58 +++++++++++++++++++++++++++++-------------------- 1 file changed, 34 insertions(+), 24 deletions(-) diff --git a/CONTRIBUTION.md b/CONTRIBUTION.md index 828964936..89985b6a5 100644 --- a/CONTRIBUTION.md +++ b/CONTRIBUTION.md @@ -1,31 +1,31 @@ # CONTRIBUTION GUIDELINES ## Before contributing -Welcome to [TheAlgorithms/c-plus-plus](https://github.com/TheAlgorithms/C-Plus-Plus)! Before sending your pull requests, make sure that you **read the whole guidelines**. If you have any doubt on the contribution guide, please feel free to state it clearly in [an issues](https://github.com/TheAlgorithms/C-Plus-Plus/issues/new/choose). +Welcome to [TheAlgorithms/C-Plus-Plus](https://github.com/TheAlgorithms/C-Plus-Plus)! Before submitting pull requests, please make sure that you have **read the whole guidelines**. If you have any doubts about this contribution guide, please open [an issue](https://github.com/TheAlgorithms/C-Plus-Plus/issues/new/choose) and clearly state your concerns. ## Contributing -### Contributor -We are very happy that you consider implementing algorithms and data structure for others! This repository is referenced and used by learners from all over the globe. Being one of our contributors, you agree and confirm that: - -- You did your work. - - No plagiarism allowed. Any plagiarized work will not be merged. -- Your work will be distributed under [MIT License](License) Once your pull request is merged. +### Contributor +We are very happy that you consider implementing algorithms and data structures for others! This repository is referred to and used by learners from around the globe. Being one of our contributors, you agree and confirm that: +- You did your own work. + - No plagiarism allowed. Any plagiarized work will not be merged. +- Your work will be distributed under [MIT License](License) once your pull request has been merged. - You submitted work fulfils or mostly fulfils our styles and standards. -**New implementation** New implementation are welcome! -**Improving comments** and **Adding test cases** are also highly welcome. +**New implementation** New implementation are welcome! +**Improving comments** and **adding tests** to existing algorithms are much appreciated. ### Making Changes #### Code -- Use the directory structure of the repository. +- Please use the directory structure of the repository. - File extension for code should be *.h *.cpp. -- Don't use **bits/stdc++.h** because this is quite Linux specific and slows down the compiler process. -- Avoid using **struct**. Instead use the **class** keyword. -- You can suggest any change in present algorithms(if needed). -- Strictly use snake_case (underscore_separated) in your file names, later to be used by a script. -- If you have modified/added code work, make sure the code compiles before submitting. -- **Be consistent in use of there guidelines when submitting** +- Don't use **bits/stdc++.h** because this is quite Linux specific and slows down the compilation process. +- Avoid using **struct** and instead use the **class** keyword. +- You can suggest reasonable changes to existing algorithms. +- Strictly use snake_case (underscore_separated) in filenames. +- If you have added or modified code, please make sure the code compiles before submitting. +- Our automated testing runs [__cpplint__](https://github.com/cpplint/cpplint) on all pull requests so please be sure that your code passes before submitting. +- **Be consistent in use of these guidelines.** #### New File Name guidelines - Use lowercase words with ``"_"`` as separator @@ -49,7 +49,7 @@ some_new_fancy_category is correct - File name validation will run on docker to ensure the validity. #### Commit Guidelines -- It is recommended to keep your changes grouped logically within individual commits. Contributors find it easier to review changes that are split across multiple commits. +- It is recommended to keep your changes grouped logically within individual commits. Contributors find it easier to understand changes that are logically spilt across multiple commits. Try to modify just one or two files in the same directory. Pull requests that span multiple directories are often rejected. ``` git add file_xyz.cpp git commit -m "your message" @@ -65,20 +65,30 @@ Common prefixes: - fix: A bug fix - feat: A new feature - docs: Documentation changes -- test: Adding missing tests or correcting existing tests +- test: Correct existing tests or add new ones #### Documentation -- Make sure you put comments in your code. -- Please avoid creating a new directories if at all possible. Try to fit your work into existing directory structure. If you want to create one, please check if the same category has been recently suggested or created by another pull request. -- If you have modified/added documentation work, ensure your language is concise and contains no grammar errors. -- Do not update the README.md along with other changes, first create an issue and link that issue with the pull request to suggest specific changes to README.md +- Make sure you put useful comments in your code. Do not comment things that are obvious. +- Please avoid creating new directories if at all possible. Try to fit your work into the existing directory structure. If you want to create a new directory, then please check if a similar category has been recently suggested or created by other pull requests. +- If you have modified/added documentation, please ensure that your language is concise and contains no grammar errors. +- Do not update README.md along with other changes, first create an issue and then link to that issue in your pull request to suggest specific changes required to README.md #### Test -- Make sure you add test cases and examples in the main-function. -- If you find any algorithm or document without tests please feel free to create issue of suggest changes. +- Make sure to add examples and test cases in your main() function. +- If you find any algorithm or document without tests, please feel free to create a pull request or issue describing suggested changes. ### Pull Requests - Checkout our [pull request template](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/.github/pull_request_template.md) +#### cpplint +To see if [__cpplint__](https://github.com/cpplint/cpplint) is already installed, do: +* `cpplint --version` # currently returns "cpplint 1.4.4" +If cpplint is ___not___ installed then do: +* `python3 -m pip install cpplint` # If that does not work then try... +* `py -m pip install cpplint` # If that does not work then try... +* `pip install cpplint` +Once cpplint is installed, test your file(s) with: +* `cpplint --filter=-legal my_file.cpp my_other_file.cpp` # Fix any issues and try again. + - Most importantly, - Happy coding! From b64e8fb2e1f1e124fc2370100ed1031e2c425079 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 4 Dec 2019 08:24:07 +0100 Subject: [PATCH 118/277] GitHub Action: Compile modified files with g++ (#677) * WIP: g++ backtracking/n_queens.cpp DO NOT MERGE. * g++ **/.py * g++ **/.cpp * g++ **/*.cpp * Compile modified files with g++ * Update cpplint_modified_files.yml * Compile modified files with g++ --- .github/workflows/cpplint_modified_files.yml | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/.github/workflows/cpplint_modified_files.yml b/.github/workflows/cpplint_modified_files.yml index 5671d34f3..41d6b5146 100644 --- a/.github/workflows/cpplint_modified_files.yml +++ b/.github/workflows/cpplint_modified_files.yml @@ -5,7 +5,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - - uses: actions/setup-python@v1 + - uses: actions/setup-python@v1 # Upgrade shell: python to Python 3.8 + - run: sudo update-alternatives --install /usr/bin/python python ${pythonLocation}/bin/python3.8 10 - run: python -m pip install cpplint - run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - run: git diff origin/master --name-only > git_diff.txt @@ -16,7 +17,7 @@ jobs: import subprocess import sys - print("Python {}.{}.{}".format(*sys.version_info)) # legacy Python :-( + print("Python {}.{}.{}".format(*sys.version_info)) # Python 3.8.0 with open("git_diff.txt") as in_file: modified_files = sorted(in_file.read().splitlines()) print("{} files were modified.".format(len(modified_files))) @@ -28,7 +29,12 @@ jobs: sys.exit(0) print("cpplint:") - print(subprocess.check_output(["cpplint", "--filter=-legal/copyright"] + cpp_files).decode("utf-8")) + subprocess.run(["cpplint", "--filter=-legal/copyright"] + cpp_files, check=True, text=True) + + print("g++:") + # compile_exts = tuple(".c .c++ .cc .cpp .cu .cxx".split()) + # compile_files = [file for file in cpp_files if file.lower().endswith(compile_exts)] + subprocess.run(["g++"] + cpp_files, check=True, text=True) upper_files = [file for file in cpp_files if file != file.lower()] if upper_files: From d16ae9350b95aa015017140fc6c0623711543779 Mon Sep 17 00:00:00 2001 From: Aditya Jain <34396222+adityajain1677@users.noreply.github.com> Date: Wed, 4 Dec 2019 13:17:48 +0530 Subject: [PATCH 119/277] Adding Kadane Algorithm (#606) * Adding Kadane Algorithm * std::cin and std::cout * Rename Dynamic Programming/kadane algorithm.cpp to dynamic_programming/kadane.cpp * Update kadane.cpp * Update kadane.cpp * // NOLINT --- dynamic_programming/kadane.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 dynamic_programming/kadane.cpp diff --git a/dynamic_programming/kadane.cpp b/dynamic_programming/kadane.cpp new file mode 100644 index 000000000..bf2aa76ac --- /dev/null +++ b/dynamic_programming/kadane.cpp @@ -0,0 +1,30 @@ +#include +#include + +int maxSubArraySum(int a[], int size) { + int max_so_far = INT_MIN, max_ending_here = 0; + + for (int i = 0; i < size; i++) { + max_ending_here = max_ending_here + a[i]; + if (max_so_far < max_ending_here) + max_so_far = max_ending_here; + + if (max_ending_here < 0) + max_ending_here = 0; + } + return max_so_far; +} + + +int main() { + int n, i; + std::cout << "Enter the number of elements \n"; + std::cin >> n; + int a[n]; // NOLINT + for (i = 0; i < n; i++) { + std::cin >> a[i]; + } + int max_sum = maxSubArraySum(a, n); + std::cout << "Maximum contiguous sum is " << max_sum; + return 0; +} From 0ce3226f008a0bc00307d7265c1be9f96f81a70d Mon Sep 17 00:00:00 2001 From: 5ur3 <43802815+5ur3@users.noreply.github.com> Date: Wed, 4 Dec 2019 12:05:08 +0400 Subject: [PATCH 120/277] Create PrimeNumbers.cpp (#607) * Create PrimeNumbers.cpp * Rename Math/PrimeNumbers/PrimeNumbers.cpp to math/prime_numbers.cpp * Trailing whitespace, std::cin, std::cout, std::endl * std::vector * std::vector again --- math/prime_numbers.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 math/prime_numbers.cpp diff --git a/math/prime_numbers.cpp b/math/prime_numbers.cpp new file mode 100644 index 000000000..7264ff528 --- /dev/null +++ b/math/prime_numbers.cpp @@ -0,0 +1,26 @@ +#include +#include + +std::vector primes(int max) { + max++; + std::vector res; + std::vector numbers(max, false); + for (int i = 2; i < max; i++) { + if (!numbers[i]) { + for (int j = i; j < max; j += i) + numbers[j] = true; + res.push_back(i); + } + } + return res; +} + +int main() { + std::cout << "Calculate primes up to:\n>> "; + int n; + std::cin >> n; + std::vector ans = primes(n); + for (int i = 0; i < ans.size(); i++) + std::cout << ans[i] << ' '; + std::cout << std::endl; +} From 525cafea949d33f841fa4daab8a28fe116cb5c2c Mon Sep 17 00:00:00 2001 From: Shrikar17 <54152124+Shrikar17@users.noreply.github.com> Date: Wed, 4 Dec 2019 13:54:48 +0530 Subject: [PATCH 121/277] Added factorisation technique (#604) * Added factorisation technique * Update and rename Math/hcf.txt to math/greatest_common_divisor.cpp * Update greatest_common_divisor.cpp --- math/greatest_common_divisor.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 math/greatest_common_divisor.cpp diff --git a/math/greatest_common_divisor.cpp b/math/greatest_common_divisor.cpp new file mode 100644 index 000000000..5601c4be9 --- /dev/null +++ b/math/greatest_common_divisor.cpp @@ -0,0 +1,27 @@ +// C++ program to find GCD of two numbers +#include + +// Recursive function to return gcd of a and b +int gcd(int a, int b) { + // Everything divides 0 + if (a == 0) + return b; + if (b == 0) + return a; + + // base case + if (a == b) + return a; + + // a is greater + if (a > b) + return gcd(a-b, b); + return gcd(a, b-a); +} + +// Driver program to test above function +int main() { + int a = 98, b = 56; + std::cout << "GCD of " << a << " and " << b << " is " << gcd(a, b); + return 0; +} From 3962de539f8e1aa77057d9b0cc78c79d45d7e2f1 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 5 Dec 2019 07:18:36 +0100 Subject: [PATCH 122/277] Update cpplint_modified_files.yml --- .github/workflows/cpplint_modified_files.yml | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/.github/workflows/cpplint_modified_files.yml b/.github/workflows/cpplint_modified_files.yml index 41d6b5146..f4b1e276e 100644 --- a/.github/workflows/cpplint_modified_files.yml +++ b/.github/workflows/cpplint_modified_files.yml @@ -1,3 +1,9 @@ +# GitHub Action that allows for gradual compliance with cpplint as only files added or +# modified are checked. +# 1. runs cpplint only on those files that have been modified vs. origin/master +# 2. compiles with g++ only on those files that have been modified vs. origin/master +# 3. Other optional filepath verifications can be commented out at the end of this file. + name: cpplint_modified_files on: [push, pull_request] jobs: @@ -5,7 +11,9 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - - uses: actions/setup-python@v1 # Upgrade shell: python to Python 3.8 + - uses: actions/setup-python@v1 + - shell: python # Show shell: python version and then upgrade shell: python to Python 3.8 + run: import sys ; print("Python {}.{}.{}".format(*sys.version_info)) # Legacy Python :-( - run: sudo update-alternatives --install /usr/bin/python python ${pythonLocation}/bin/python3.8 10 - run: python -m pip install cpplint - run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY From 7ef6fa0b33aace89f0916e59bf3d2da8e98df3ff Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 5 Dec 2019 08:13:36 +0100 Subject: [PATCH 123/277] Update cpplint_modified_files.yml --- .github/workflows/cpplint_modified_files.yml | 23 ++++++++++---------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/.github/workflows/cpplint_modified_files.yml b/.github/workflows/cpplint_modified_files.yml index f4b1e276e..d8fd59ad1 100644 --- a/.github/workflows/cpplint_modified_files.yml +++ b/.github/workflows/cpplint_modified_files.yml @@ -1,8 +1,9 @@ -# GitHub Action that allows for gradual compliance with cpplint as only files added or -# modified are checked. -# 1. runs cpplint only on those files that have been modified vs. origin/master -# 2. compiles with g++ only on those files that have been modified vs. origin/master -# 3. Other optional filepath verifications can be commented out at the end of this file. +# GitHub Action that enables a repo to achieve gradual compliance with cpplint by +# linting only those files that have been added or modified (vs. origin/master). +# 1. runs cpplint only on those files that have been modified vs. origin/master. +# 2. compiles with g++ only those files that have been modified vs. origin/master. +# 3. other optional filepath verifications may be commented out at the end of this file. +# From: https://github.com/cpplint/GitHub-Action-for-cpplint name: cpplint_modified_files on: [push, pull_request] @@ -12,7 +13,7 @@ jobs: steps: - uses: actions/checkout@v1 - uses: actions/setup-python@v1 - - shell: python # Show shell: python version and then upgrade shell: python to Python 3.8 + - shell: python # Show the version of shell: python and then upgrade shell: python to Python 3.8 run: import sys ; print("Python {}.{}.{}".format(*sys.version_info)) # Legacy Python :-( - run: sudo update-alternatives --install /usr/bin/python python ${pythonLocation}/bin/python3.8 10 - run: python -m pip install cpplint @@ -25,14 +26,14 @@ jobs: import subprocess import sys - print("Python {}.{}.{}".format(*sys.version_info)) # Python 3.8.0 + print("Python {}.{}.{}".format(*sys.version_info)) # Python 3.8 with open("git_diff.txt") as in_file: modified_files = sorted(in_file.read().splitlines()) print("{} files were modified.".format(len(modified_files))) cpp_exts = tuple(".c .c++ .cc .cpp .cu .cuh .cxx .h .h++ .hh .hpp .hxx".split()) cpp_files = [file for file in modified_files if file.lower().endswith(cpp_exts)] - print("{} C++ files were modified.".format(len(cpp_files))) + print(f"{len(cpp_files)} C++ files were modified.") if not cpp_files: sys.exit(0) @@ -46,17 +47,17 @@ jobs: upper_files = [file for file in cpp_files if file != file.lower()] if upper_files: - print("{} files contain uppercase characters:".format(len(upper_files))) + print(f"{len(upper_files)} files contain uppercase characters:") print("\n".join(upper_files) + "\n") space_files = [file for file in cpp_files if " " in file or "-" in file] if space_files: - print("{} files contain space or dash characters:".format(len(space_files))) + print(f"{len(space_files)} files contain space or dash characters:") print("\n".join(space_files) + "\n") nodir_files = [file for file in cpp_files if file.count(os.sep) != 1] if nodir_files: - print("{} files are not in one and only one directory:".format(len(nodir_files))) + print(f"{len(nodir_files)} files are not in one and only one directory:") print("\n".join(nodir_files) + "\n") bad_files = len(upper_files + space_files + nodir_files) From 0d8fbcc8e41c7a573c86bb8246c9b9900171ef71 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 5 Dec 2019 08:45:53 +0100 Subject: [PATCH 124/277] Update CONTRIBUTION.md --- CONTRIBUTION.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/CONTRIBUTION.md b/CONTRIBUTION.md index 89985b6a5..5e9526983 100644 --- a/CONTRIBUTION.md +++ b/CONTRIBUTION.md @@ -44,12 +44,12 @@ my_new_cpp_class.cpp is correct format ``` SomeNew Fancy-Category is incorrect some_new_fancy_category is correct - -- It will be used to dynamically create a directory of files and implementation. -- File name validation will run on docker to ensure the validity. +``` +- Filepaths will be used to dynamically create a directory of our algorithms. +- Filepath validation will run on GitHub Actions to ensure compliance. #### Commit Guidelines -- It is recommended to keep your changes grouped logically within individual commits. Contributors find it easier to understand changes that are logically spilt across multiple commits. Try to modify just one or two files in the same directory. Pull requests that span multiple directories are often rejected. +- It is recommended to keep your changes grouped logically within individual commits. Maintainers find it easier to understand changes that are logically spilt across multiple commits. Try to modify just one or two files in the same directory. Pull requests that span multiple directories are often rejected. ``` git add file_xyz.cpp git commit -m "your message" From 4717db2a08238dd3dff1bc6246896709fd522648 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 5 Dec 2019 09:21:08 +0100 Subject: [PATCH 125/277] clang-format --style=Google -i my_file.cpp --- CONTRIBUTION.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CONTRIBUTION.md b/CONTRIBUTION.md index 5e9526983..c99de6daf 100644 --- a/CONTRIBUTION.md +++ b/CONTRIBUTION.md @@ -90,5 +90,9 @@ If cpplint is ___not___ installed then do: Once cpplint is installed, test your file(s) with: * `cpplint --filter=-legal my_file.cpp my_other_file.cpp` # Fix any issues and try again. +The [__clang-format__](https://clang.llvm.org/docs/ClangFormat.html) tool can fix many but not all _cpplint_ issues. +* On Macs only: `brew install clang-format` # Only needs to be installed once. +* All platforms: `clang-format --style=Google -i my_file.cpp` + - Most importantly, - Happy coding! From 00a75bd58be79e416f701e0a2e37bca2159125de Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 5 Dec 2019 19:11:02 +0100 Subject: [PATCH 126/277] Update CONTRIBUTION.md --- CONTRIBUTION.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTION.md b/CONTRIBUTION.md index c99de6daf..73a02bbb7 100644 --- a/CONTRIBUTION.md +++ b/CONTRIBUTION.md @@ -90,9 +90,9 @@ If cpplint is ___not___ installed then do: Once cpplint is installed, test your file(s) with: * `cpplint --filter=-legal my_file.cpp my_other_file.cpp` # Fix any issues and try again. -The [__clang-format__](https://clang.llvm.org/docs/ClangFormat.html) tool can fix many but not all _cpplint_ issues. +The [__clang-format__](https://clang.llvm.org/docs/ClangFormat.html) tool can fix whitespace related _cpplint_ issues. * On Macs only: `brew install clang-format` # Only needs to be installed once. -* All platforms: `clang-format --style=Google -i my_file.cpp` +* All platforms: `clang-format -i -style="{IndentWidth: 4}" my_file.cpp` - Most importantly, - Happy coding! From 8b7b6b5f1d0ac251ea987cbe7d32d940af7b5ceb Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 5 Dec 2019 19:12:07 +0100 Subject: [PATCH 127/277] Update CONTRIBUTION.md --- CONTRIBUTION.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTION.md b/CONTRIBUTION.md index 73a02bbb7..adafa955a 100644 --- a/CONTRIBUTION.md +++ b/CONTRIBUTION.md @@ -94,5 +94,5 @@ The [__clang-format__](https://clang.llvm.org/docs/ClangFormat.html) tool can fi * On Macs only: `brew install clang-format` # Only needs to be installed once. * All platforms: `clang-format -i -style="{IndentWidth: 4}" my_file.cpp` -- Most importantly, - - Happy coding! +Most importantly, +- Happy coding! From 9f18647c739d5dafe9ddcc106cfa9f055ec1e88c Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 5 Dec 2019 22:05:29 +0100 Subject: [PATCH 128/277] Create .gitignore --- .gitignore | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..1a5f7b618 --- /dev/null +++ b/.gitignore @@ -0,0 +1,34 @@ +.DS_Store + +# Prerequisites +*.d + +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app From b53bdf16ecdea0491d1eb87069f67a87b3b6893c Mon Sep 17 00:00:00 2001 From: Kushagra Nigam Date: Fri, 6 Dec 2019 02:43:16 +0530 Subject: [PATCH 129/277] Matrix Exponentiation (#589) * Matrix Exponentiation * Update and rename Others/Matrix_Expo.cpp to others/matrix_exponentiation.cpp * Update matrix_exponentiation.cpp * clang-format -i -style="{BasedOnStyle: Google, IndentWidth: 4}" matrix_exponentiation.cpp * clang-format -i -style="{IndentWidth: 4}" matrix_exponentiation.cpp * Fix cpplint readability/braces issue * using std::cin; using std::cout; using std::vector; * added int_64 instead of long long * Minor changes * Update matrix_exponentiation.cpp --- .DS_Store | Bin 0 -> 6148 bytes Others/.DS_Store | Bin 0 -> 6148 bytes Others/a.out | Bin 0 -> 72920 bytes others/matrix_exponentiation.cpp | 119 +++++++++++++++++++++++++++++++ 4 files changed, 119 insertions(+) create mode 100644 .DS_Store create mode 100644 Others/.DS_Store create mode 100755 Others/a.out create mode 100644 others/matrix_exponentiation.cpp diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..ab5825a1870609ff8f986f1d3d79dfec591f7a6f GIT binary patch literal 6148 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

ucT#QhGP>E25P>oQ7@Kc0ZggOMA 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 IHDVb52lV}xl>h($ literal 0 HcmV?d00001 diff --git a/others/matrix_exponentiation.cpp b/others/matrix_exponentiation.cpp new file mode 100644 index 000000000..16a272988 --- /dev/null +++ b/others/matrix_exponentiation.cpp @@ -0,0 +1,119 @@ +/* +Matrix Exponentiation. +The problem can be solved with DP but constraints are high. +ai = bi (for i <= k) +ai = c1*ai-1 + c2*ai-2 + ... + ck*ai-k (for i > k) +Taking the example of Fibonacci series, K=2 +b1 = 1, b2=1 +c1 = 1, c2=1 +a = 0 1 1 2 .... +This way you can find the 10^18 fibonacci number%MOD. +I have given a general way to use it. The program takes the input of B and C +matrix. +Steps for Matrix Expo +1. Create vector F1 : which is the copy of B. +2. Create transpose matrix (Learn more about it on the internet) +3. Perform T^(n-1) [transpose matrix to the power n-1] +4. Multiply with F to get the last matrix of size (1xk). +The first element of this matrix is the required result. +*/ + +#include +using std::cin; +using std::cout; +using std::vector; + +#define ll int64_t +#define endl '\n' +#define pb push_back +#define MOD 1000000007 +ll ab(ll x) { return x > 0LL ? x : -x; } +ll k; +vector a, b, c; + +// To multiply 2 matrix +vector> multiply(vector> A, vector> B) { + vector> C(k + 1, vector(k + 1)); + for (ll i = 1; i <= k; i++) { + for (ll j = 1; j <= k; j++) { + for (ll z = 1; z <= k; z++) { + C[i][j] = (C[i][j] + (A[i][z] * B[z][j]) % MOD) % MOD; + } + } + } + return C; +} + +// computing power of a matrix +vector> power(vector> A, ll p) { + if (p == 1) + return A; + if (p % 2 == 1) { + return multiply(A, power(A, p - 1)); + } else { + vector> X = power(A, p / 2); + return multiply(X, X); + } +} + +// main function +ll ans(ll n) { + if (n == 0) + return 0; + if (n <= k) + return b[n - 1]; + // F1 + vector F1(k + 1); + for (ll i = 1; i <= k; i++) + F1[i] = b[i - 1]; + + // Transpose matrix + vector> T(k + 1, vector(k + 1)); + for (ll i = 1; i <= k; i++) { + for (ll j = 1; j <= k; j++) { + if (i < k) { + if (j == i + 1) + T[i][j] = 1; + else + T[i][j] = 0; + continue; + } + T[i][j] = c[k - j]; + } + } + // T^n-1 + T = power(T, n - 1); + + // T*F1 + ll res = 0; + for (ll i = 1; i <= k; i++) { + res = (res + (T[1][i] * F1[i]) % MOD) % MOD; + } + return res; +} + +// 1 1 2 3 5 + +int main() { + cin.tie(0); + cout.tie(0); + ll t; + cin >> t; + ll i, j, x; + while (t--) { + cin >> k; + for (i = 0; i < k; i++) { + cin >> x; + b.pb(x); + } + for (i = 0; i < k; i++) { + cin >> x; + c.pb(x); + } + cin >> x; + cout << ans(x) << endl; + b.clear(); + c.clear(); + } + return 0; +} From bc8e8dfc2ba73629cc1bc9ab2a12435a820b6655 Mon Sep 17 00:00:00 2001 From: Akshay Gupta <33252532+Akshay1910@users.noreply.github.com> Date: Fri, 6 Dec 2019 03:32:52 +0530 Subject: [PATCH 130/277] factorial.cpp (#561) * Create factorial.cpp * Update and rename Math/factorial.cpp to math/factorial.cpp * Update factorial.cpp * Update factorial.cpp --- math/factorial.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 math/factorial.cpp diff --git a/math/factorial.cpp b/math/factorial.cpp new file mode 100644 index 000000000..8b13eb52d --- /dev/null +++ b/math/factorial.cpp @@ -0,0 +1,17 @@ +// C++ program to find factorial of given number +#include + +// function to find factorial of given number +unsigned int factorial(unsigned int n) { + if (n == 0) + return 1; + return n * factorial(n - 1); +} + +// Driver code +int main() { + int num = 5; + std::cout << "Factorial of " << num << " is " << factorial(num) + << std::endl; + return 0; +} From 74611b7aad70682554aba9143f03a143cf3eb14b Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 5 Dec 2019 23:04:31 +0100 Subject: [PATCH 131/277] Delete .DS_Store --- Others/.DS_Store | Bin 6148 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 Others/.DS_Store diff --git a/Others/.DS_Store b/Others/.DS_Store deleted file mode 100644 index 5008ddfcf53c02e82d7eee2e57c38e5672ef89f6..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeH~Jr2S!425mzP>H1@V-^m;4Wg<&0T*E43hX&L&p$$qDprKhvt+--jT7}7np#A3 zem<@ulZcFPQ@L2!n>{z**++&mCkOWA81W14cNZlEfg7;MkzE(HCqgga^y>{tEnwC%0;vJ&^%eQ zLs35+`xjp>T0 Date: Thu, 5 Dec 2019 23:05:01 +0100 Subject: [PATCH 132/277] Delete a.out --- Others/a.out | Bin 72920 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100755 Others/a.out diff --git a/Others/a.out b/Others/a.out deleted file mode 100755 index e5b02df951910a479d772e544a08fd590417e63b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 72920 zcmeHw3wTu3)%M8+2$ymbEhv(;kpTLsI1b4G(cGF$Vz8)az!GB= zul4qM<)hSkL2E5qR1`EwQK_{StyPM*p-L z&f0sgwbx#I?X@rGoR!zU`Q%U+!^p@ojOCezVf01VgoKsL2jR{zjztI{1cSv>Pxqhe zpK~Uq+J6~#&=n#&BTzvwIM;v9Tze75ud$~Y0(U|(h0c;43`W9@kyzPyde`(oW03u3 zo+_hZ6C>MLZrRX)L1dU51f-=ati24_s2J2g1{%-JPMTc8iD zC%pwj^urLCXi^~lC@C0RTpg2|H@!TRVJR(f3}U0-73f!e84aa|tQPQd)@tuDHqF@38D1?!epF08Hy)#q>v(nRY z5Ol~((JSyJx+T#Hd)$qj~4Gu$wCZZM4fNZB>WcFuMzqoc>R`qY#5hX8IpoMam_`5*)~qCud6+^qI}`0WlJl{0MqYy1mdH| zlx^=H>^k9|UoTwq?=!oea#=poauJwhuWp8cK=<4?*+%9l-1kP%zY%CZ(dqMjouaN( zZvcVv*tQ) zXSNBYN|x3|!j)sDX&e;ic2BY60n&I}KS{)_mqt_F7@tXE7)nz+cl;TBhwDgzso#$L zj!58$1dd4H{|^bw3p9TiXuj+~pt*j3pvAv`!Deg9Y75xnKM=S*(7Yp1fSZv!7HnS4 zC7bs3W_-$SZi}w-VX}MKJ#R3k53jtuM0svB6~6}pE%WvVn%|_V7pP)3uAHTo#!5|{ zH+61FplM$t8n6liSRQD;rSb6L!+}=+Jw$MA9%iXle;eIzp!=3iC;tqWrcD`v=H~;g z^V*PmZ=m^AD)3V@00p|41ztjdd$>RgQU7D0`Gx2%RIYH^qD6!t)GJg?T?^9Ozu7>Tp5vz>lcMI2h~wkAzUQsfcPi?~nbdc>P~RMA-Wh1l2sHV(X6$+M5PG=@qTKTv zb+W<6QSTREav){;6e}#w64r!&luK(kX=0(#m|b-lA|N|D{0lYtg3;0#ReMMY~z*fL#8=;u0p>qWb{uS;+dRSZ#hG z@cci}oE?Eb!fKzfmF@#-6X(PD%Tdhg$v!H3i;OyYMm{0homl` zRNbC=>p=oJ+>%fK!xRCwMW-_^k!p*M=lhjR9pDInd+sK2lbVPq+M<1sESjPujH3Sw zt-h}(c7uI zmi~Lz5=QIFDrw%WTy>|eL_k}}TR2mzBHPKCgdM}GC9F1o6r57^f2hZ0qCa}YhqX) zmcvb~JZ#v%V7c<2R#{OR6;LH1-D2`WaO1$$l6(>h;S3MIYeOn_-+?Dn1UG zVxNCT$2$9cVoR!%q+QN57%LIS;AUrrxj1 zq90bPdmgeYl%z?~Nw9iOtixF&B#t@pRm!00PLX?-y97keCPXzUZlK$i{*W(~vgp}8 zoPlC*r9Huc=#D^ZkKWe#E8*QTaCi0jaW>awqx^ zT$TsYQAN5;itZ$KCAD?(Y?O@FQ`?&S2Qv0&FWc7k zEUK2?xE#QuEimzgy3UleH=9x{>wa?yO-1*67LD5n+&q+-$JE{yod#CD*8O)3@y@&4 zE3c*4WP2npA)h~hmD&rcDLH&mi}H;YE*`|a7Z*LfY6AD4pA^HR-NFd$7SJd4yP#t* zg$tq>(zwDps|E1{>Nac-TF88YJIpHYMQ1T1u-Dw5Y^(>M+}`781W6wkP#LwToP;_9 zOisWi^j2u}CY~2t{F{iY&>)if3$S|c3E%(DCB9Yed7O(qFy-nF9Yqb} zl(uLC6=?B;Y+KYo`po7R8Kh}dk?4yOGn=<)uopnuIX1s73yD{idVs>ToV|r=ra@)c z0dn0KTy4>Q#1fAnuISNN&Nl;*LnBD-$n+@6)!p-w|8NGX-bGY4m|7E+ruL(jpvOc* zbT62uuvmuNl-{tL5g&>|A+)}c{wPf*b~tNF4kjgq(_EahcQB`-<`bzNvK7GLVaa&= zf#*6h#ab&hde&NsG?NIlk)2nSwoS>g-1nw?%W)2FtuleJs0Z6vST|j^--vu)u??{0 z4BeUyxfZTapAgd~0R2&qAy2Ct|ED6x%cv6=#EuB)m|l1G`UP#VQ35)G>=l2F^uQAH z_vnJ?4kfRh))B7Bqi3|m#Xusfp`@^ts-T5%Y<#_fB%1+QPi2$=dH)35D#L2CiMnUO z)g4?~MiFS60$`nQnFmo#%dy%H$UU}z;nAvPX?81*`+C)3+UA%&keV!yIuV?U;Hrs5 zyDU2+TVz=crHZZ~anlrJnMIPxaxhh4m*pTN*<_hbWt1#`fd^K0S?1bXuMAEmW038K ziV}TvAL&|K^bj>8CQzl1qRA;q^!rLBwM3~36R)?)i@g{Ag=bs3_iW=@4?*s$S1hH7 zBc&f0q-6C0(gjd#Obaa8ygu0r&XR|AGmgdu+*^-IEPqX&6OP1Vpv0zq5P6xr zK*S?qkm4Q420(4ac;J;di|yUx7=6EK zH>pKZ9yZX4@UR<#5;uvUnN|j3g;?%vA8$qbEpxZo>!jZkP~lc|*Cya$_hy=+YpJ5v zd7mO_hqU!{YO9Q>HpRzQU~Q7@e5e3}F^qwnq^7Tv={`2~3}BGA-XAKusHQFYZzR)% zJ|Q-tlSpDMWV6*4J)P`QGmH+bO{}38<2iIpR|!$clID_DQbQK{&rnMBnKo(Br%|nv z(1r}dFvQlAe3pR7I>_f<82j6RwJy+lbTvk(xesn7YR#A!DUUmOr@H0-+rjr}*hSo4 z{|3ku!4GoG%fI_GHsnayFv}`=0ExF5g5$ZLw8wuNiKm!EMa{-Sp|!`0V3k^el^2-{ zu*u!MfRJ%SM7hyd0j$^*`KijsxgxV`p4#3+^|$14zwrY6Evn|{s(MUr{%DTIeB6#1 zW=tTneM09k<{5&yw_2mIv}qshN1NNCV_Ykoq@-i7aH_q+FYrt}W)O9SnSvSp5T%>; zXP~XLT7WFDj$#6&B-9N%MLa_YLx~$ApVK>VGA768zsW)|UF5gSB=^WBWxJ?zqGF47 z1zP)AL{Ghe>WX{sSwY=_dOs&2G+h=o>W3f?J>^oId;dPv!;2ec_bjTlnb@WNM#bEl z^+Zguy9-%5xi1PwZ((U~mi_|wZPEN=sO~LGEIXlG9tX4>U^_G=2Paj#l)1y0Xu9lx z5y|H)pua*wCLT!Vc!9P{`1pi`$;qUp#paA2Z-t%aXYt21BM{_ z*!l@__gYjq)%nf7si?!vM=3E`=3U2{C{|~lIYe(N!wRR>-#d_?PMo=bF@Q^$o__qO*8x_J@Lizn7k)U0amKexSKOEgk3( z$fV{bbMAM&_EAl3#@dHxh_>jT`w%5MWa7%6CUE3tI$o#4n29g+x)DdD*n`Ply@-`t zmA%f6dIf`EvXwV^V3s8{pD~O;2I%w5&h^Zp!g!EV+gI0IBqOrRlFa@QS zS)_2>PpF_R`UUHM8>=689lbw*=M&M*lwr{d+c<#TVKc)WGpLt!9ORm1(+I#LgZ_K}8WXx}zbr&a zDdIM;xAI6+!w_o7y?y2PcwsydLk3B0(PqFFead7Wcz?1NZ0k}5R0^x&{(IL`7w#<} z)J)=&Cki^hW9knBJ^Cfn*c^@Wm20`F2jN?{H?dJga)?>w7g3XLwH|l8hwiP!L>FkU z_l`PVi?k^O!=Ir=nzrt3QR91wK@_>1mCdxH%$r`ySa!^A8)UU5dzuV^tQ}wJZmM|v za*?NTy=%qtN7#5cR=vWAH*b@uBT(2hHFmvlUme^YH-gj{jjaRBRjJu5qRIo;d}c)! zmW>xy>CLb(uSFk?qiQa@Oe&T>b_(ZOJd}zV=?SP1nu6)qoReTFnl9U6L`I>#sIx7) zh*gzVkx)0DY6Gm6l{@Hl9q8t3R8r~YA}}Yq39_u4eUKDAm(rUzM~nE%y7^UCBw2Km zvsv(OXEi0g04Nq8(otN59)verWx#0<9?j~H$9iqt|oyVm0VRH52&>3U=N ziV=MXPc?#V2#Oz)U}p&#@TobT^f$lz92U(+^n6a+Qq=s3^__V76i}B!RxQ{dOo`jYTRGNQ4vp`+NO@773lAy=gSjIHl(z=((2wtG-rm z(#6!voFA1nx(}?X!~R`_cOyWHacW`^lO3JSJYUqjn9iX5XbG*c zEoWzWW{-Id0i|pPYB95H_3SNnZT4!3YB06g8BdsVSP#MOF{b|ipR9Un2Y0VjwB9B^L4!6rk;C%`nwEP>6e4a|7266~;L4Oia>Jlq;G} z45*{zBFdpfji;bj&*~1T*NozK= zGh>IBO3*sVb{=;bhJzH=W|Z`t)@K;*vU5Mqk$J_+?i zH>w((>sxuirgXr3(0vuF1Re3AV`x!Jv(5vQn9{m-xZ={3gC2Xf)kJKyVAC6qm0V}& zpDCr@Jeql|Lua!|N!y}tm?hjSooudtk3tqJ_Yi4yY)Sv$0F`Ycg1_WU8nF-p_iq!W zXoDxK%3Ql;acJa+z=^XR&;^Tf#f(YZ2=b5weHN9ZH=iN-$C~vBgK@q28YS9#)7A~> zdgsuMBpSNQNjSEVZ5_IHL&-07ljNc>le>7UCLMGf*s^p`Cwoi2MB8H>L?6H^ld3yt zH|auL2icV6_)KClrb)IodkDN4IB`8_S^^t>`(;){E%1~X7Rt?+9c->Y&~({Byhi*O z))!Y^cHr<~eAKma4Xt%sCl8&8HOKlax<7j6W_k^8Y+ob=S~^WHzy(_TM-oZvF~$KyDj!0~AuPvZE898ckR8pks@{xQb^j(@^&5y!JRF6MX+$8$NJ&+$1N zpUd(29ACikg&Z&BxQydP953PcB91FKuHv|c<64d*95-;>$nm8dFXQ-fj+b+M6~`+$ zzMA7z9ACrnwH#l^@oJ85 zujlx2j-TN8Nsc#g{4~cKIewPoO&q_#@fMC>;&>~^+c@6N@v9u~;P`cp-{AO7j(2kW zHplO9{4U44INr_i2ONLIag^hKaJ-M>e{#H^qo~oWpT9j(Z?3YCYkE(+y*4$>E{&MZxMNIHEW9d<46*WE|bSLw9G>-RpFBBi(JK zyNBowrt0vLEp+z;-QmXA^B~<_MtAqp-P?3`EAA*W=BI$nTP8v_0+w9-{b??)QxKLT z@Vnl+Kpf~=J^@Y^@~9q6AnXGIYcsAB>t6$FX#O6#2d-d}f2EB+Z3FqP~ z-P2BM2$x2xYjZ0?wTr{GxsfHIs@%#@W3aCL((s6phRQwdwBQ**;8avpm*Ok`x^Qg- zMDfF8Vg6-YT3j^8$Y|`{<<3t=qshH{bjeu_K}9R@?E{Amx4PSp4wZl7HU#IM0v6{{Sh^ z3O*j;^3NNel+0fL5H#_Q4&avozo7&8Yk)te1Na{Re~jP{OWOWH&h|ss`=yCL1JufZ z|4p0fzXddI@XPtp6uvt9pESQU>)Pz5PT6Oouyh6K;X?p>ZBulv*K`I?K@NV|XrxUK zsfU}gvaeD!h>v}^yP zSE^=^{yl-Dxq?4K;}7=2|B*tJa)kc{@XzT0|Ap8g7IpwX0{q?`z<&bx`(*rGq1!)f zvbuBhzsRp1*%(ILe&COemtP+*e5d>hF-hkM{zzTFT%C4gh^kofss0G?j}!b{N%yuN zG{WM>Kk&bi_RmR*FYT9M!0iWq52^nGjej)d;OCIve<3keKj~W`m>nhfpArs!IdAms_qN3oCpA&y0@Ye|b6sgx+ex#pv`5(04 z<6##6yzwEdIQ&WIv|6cuR8oA>Fnj&WfPcQ=r`7*J8qop#gTVin*pYPlZxS{peWiXA zf4Gd~6#8!&@UY^G&UyGC z@K*>vZu!@)@sG{y9Kk2+NlaU)Y{((PD@O_M(2!FH#em!9+*|F^4Vu>A-AJgHx-eggRsUAz1?0)MvPr`7+!A20Y21^>MJ50gb) z{gd$aPG`YS$9^vZ{_7&Y&3ZrEi`F^#dCBi7wV&nn5Af&9`sG4Kg8mHj!aols?D9JZ z{06}vqw(eHte+%o$Df45pfbUqmK2}X*LM76z+WWzY1u#E7j*#tAn@}AKR+q|r#SeZ zbQH#q;LlHrf0hG(8SqaN{B-npBk)h^Nc(}`Rq)g4ze)Yjqk^A~{FVX#kj%dqCY7I4 ze>VdEM5*7G6yIq-4+6he2jn*iM~z; z-4Xq~=igl9+VyWE@D~XF6y(y+8{eht9;^ z4}875QLc!2ge|f76*i zHUfX2;7>@Zf5f4E{2m1U2ZEoD{!W6?Y!m#4b^X5_uI{|n@3c_@8PzYO?0J0Sm!!2iAA zr*nRD5cvNi`03d1Nf6pE1V5emYZ>sD34U7o5Bw^@PiOsk5coe7d@P0e=RJQ?4RQUS zi}|Mm{4WE3b_eR;2>hL|s`H1m`XBf&2>x}3`sECyb0Yk_#_tN`$@rawBe~wfe>(H` zGT^@}^}`hN&s+Xjtj5WIBk-RRe6lC>^TwC?pA=pAKM4FM1wWUN@$<$f4&(YCgZ@^* z@59)M@Nw8`!Kdd)%YeUF@XIy+U&N9)|ex7$N@cRq?EXGcR|6>RKcHrxNNJkHPz=(hTin1r| z#h(Fgih#dK@ITf356x9~iS+sJC?cYuek6~6dR(-Z55j)~_+v$m$@S@iSmn4Q{C-%B zoFn*j>P0{AejI^Zdq2(vzF+W9XY54yG-B-dHv_*&@cSmk$3u)b{5ODqqTr{quJ4B> zT#n%9C9U6iu0I#}2Sg9j8Amq*e@_SS-vIvGf?t%B|4t}@_e-Q3xc||m9|?Xs@|z3% z9fD7*KKgm<4>sX({dY6)AMQx|fq%E)V`|`^cm2d+O#f&c_d}zX3;sn4Jpun+P=enR zvkfGYyN`IYK_2lyeuPsff7z@q9@!B0nz&j)_4;HRU9cL9I2 z;0KfT!?`FC>ql-s@Mopje$s;h7~01Q{zXaa_tt|l(D{MTNoPE)0e*kMPp2O~0DiYL zRIqdV9$&?#CGlT_2QudiG54rTU74 zMuLyQV|KdIf7qhyn|SSju7Qc_nuoItf+yoZkgm5&{u-(80=f3Xds>wLrR4X;K@7nk z2wpegXN}Z*x$s$hnku(j(tj-1$K^U(>aP(#8*!jSbf*YBU*M|-sq`8-KRI9Ebpn%@ zcfuQuvsSv^hIfhR+F9Ub0{4~cmpJC7{PR6y&bRlQMuhB=OqHaj>nIbUV$@B zx*msPf4cUTcHJ%M-$*~xnH%MwCiv?HDY%Eg#|S)5=)56#wYjR?kOAs?xyXBtwCh!A z2l-GYmvY!L|$VA?k{wPNx285zC0NpPl!AZ ziG1~W-{Zp1_Nl5qu*knIGESZmxzxz`n)L%!?pBd=NaVL!(g#ZUY#Ar73Y}e&UoGYT zOW+Mc=M=%)C~|yL_!%#9c}w~|Eai(tFLp_}J4IiQl76~R>K`Eecu4y3Dba(sMGwCc z`k#yZ9uU24lmj)gkbI4I_;A+nVgU5?YIr81dI63hAb^N+_=lob zWvs@nnevbTIaKyV0lvt<&4&W)B47q06K8<{LkZ^!0YU`aB0w<#j|%W30&)>ufGhvN z#_VfxM-;neBN{D5Pb1)L0frIqOW;wliwSr}fO82Lgs1^m{(&O=f@BTH&@wPA)$dGP z2zNe#7Yji5RFsRO2V=$020+D`%{l>aF^dyQA(V|vaYl&%>j}C~fNcc4h=BfAKj0k) zrC~fAs^e2B0qCBnCeGzjC}*6JH5EE-oGS@NB_#DD023gWjJE(#F8@{`Wf1Oug{$#9 z5gX^Al>A5t^gC>f%^E%rH`I7)cSbX!ZU{Fan9ZVl9tV7bi1Da7gf|x<<03?a7eO$t zLZBS}#cEaU{UK5*(@(koB>>&0En`ML5*?Ai5eXcTz!3=?k-!lN#7UsfV54TlStl76 z=1;rujHwrnnO2j-E2BPBg28iVmz3Am`R6nmXVtCFx)&Zf)h}bU%B-%a^EVpK^vHzr z>bl^tA)hR@$%)aD3MWFj)k;bg74Zf0po#OEtr5~>YGYD47_B>4RWk@B#= zxTM;sTa^<}x+GFiT3%(;_GVfok;2mI`iLPwMcqsna&wSYplYnHi@?KM<;>E#L4V2E zV5w2JynB2NWfjE@juus2QfVxYXC}C~u`yT^uC1%C3RRRxmIfR0jN07QeW#QyttboD zMd}v@7nWC*g=-C3S{p2}iNWCFs`_AQW23L2Dtt+h-OYvIoDQ6iQ;z6nHkO2DHv0X3 zUtXDVM+ZN4kViqV61^ZoY!96YQc2ifSv;#j32SzH2u#oS&zV(H7)%c}of>E4Lt&J< zcr)4~sfExxzi)i7Bv==&fE&eNbycvmx@M`DM!3*y z^rNTTDY&(9d@xv5U0WHd2$n~}wLCV8XF2#P@damsHDVbI`u)>=#L-w6nWaasrp8SJ zU1>Esm=kXDQ{={zfQxu4%V!q5l=sgr2|~sW$;}Ny<@~;}W#x+&g=@oArQu*?X-$}9 zH6d6s&BD`AcPk{O!zEbkHQ6x;;um(!Gf0(1<`gvDLtkwV)FY1(qF zK0SJ6?I7mTv+ZLiIRVUu`N8?@5S1rr=a8o{m5(vyD_9(k#Ac|NNZLVSBAlucmAN%3 z5t6CTmlUm_vbrH`F%XUZI61{st0bsrRBD(H4J!y&m04S(CthdCLUIwCTG6o!!;8zS z+{)@k`Z4RT@V*dnTf(xD=KK(Y;%g(4wLDIknxAw#y6SUaRWUe8N*x^XPSnnEShS;iWesP+?_ym{ubl zFDE_Gre-^IY1`mbGoHCibBMwV$y1$N5fYgIjZhFb;LY8wCr|Ae+`5+bDWb+|pV|qQ z^m$U*qFgd*+Lge$7DO+WSnC;Q9e|l}=D^e!VKxiocug5iHP3rMIbX|9%XU$DMMbbmq&rsU1|`|KysgBl8?o9LGw@pqcgT~ zGS7#d+f-j6CJWvXhwAFe7gu3bf^9^^H@>_o5?)-3qck=>IBlE{bI>S{ufHwBbhxjc5)2$Tm56&=`g2^|EUGBODi`c4?F*I2M|K zW8AuMFcb;W!Ao(YXXRs2c|A&+wZ|3$@j{@*j{U#&%+yEi$t-6h9|DnS_7;PO@+T17 zMDULPJG7*>`jQy`=}0V}map1^Sci|7*ldSIj!k>qS&%cov?3g;wJf>fBt5aFzHSLl z3QI4>a>cXj)aY^<-J%A_ry=DnKNRrnY#v^CidMJ3i{A0ZF=-nwsXktGJkUEA-IW)d zZa%zm$O;;U@qzT+r4pNArva(tnB~>qSp54+R5-kdquAn$(#Y%dP zqRx7)Ot~&9+~#tc5+`_3#6&-1ZfS+Rp3;i4$fBB{I+FF{5G;NoM;kpj1U*!z6-hM! z(~oXI@hle(=LVCs3+n_-zkXYtR-&GDUQ!#XL3e^Bo)6;q(q@Xg9Jl;GpW633aw0OL60lijYe3O)#=vfGLpFenZCXI-P(g{U6$vt zWQsxX9Wz7ud3J#$Sc9Xp(Y(Ug65N!kbA``3ANsZ=8z)@WF*HZ(So+nw3mPLWCh3$b z^OCxz#$tC+!$5QE05V(-t*eCE(U7zC0#ihyDGYNzrFUC;#Ztw49w4(-Gs`E~Kgoot zQR0~|peZbLaae6|$`@gk6>cmI*F?-mDR{o;ri&!sV!g)0i$e|}u(h-jBu#V?1b$gix`_pqbBqtRNuRZ`7^pPPOAjzYzAl z;l^^jq-fNw?@qKik>3^wVqadmgo(y-ut$!iZ;GYYhPg5-y_JYphAU}!0G3}y5Z_L8 z4jO|hao%h^*yUp5lkp+rU*i`VUym;}4v#l7E5T!9xU@bJ4lW6Y=*`55=NgmgTM#2h z$?d5Ok?*q^`Jsi4#^#LK#@37pl{o1tuc=rX>v88H6ixScb{Sh!eMuM_9KAtvmc#p^ zT?#@~b&baVbSa4#k9Nt*zUEjXEBh`)#;=bxjI0vly^PpPL&m*5W*PgAHZmi|KQcly zjTgHbSw7=%hOWU_o1JewGt$V$QQ03dU5|l{r%rG#RnXxuC&tcGjXw`Kd)yH=~p7iIZ_C3-;-g z?k>-JuIuITpyiG}agVsJ8E$0qF1a-u%`zVEnw9+$B$?S@+?TEQ-F>pMcT<{Xye-?= zH^!ek8#zSb&Q473nQpwZ{zdn=Q-D{xk2PNJ?lac*@;p;d~l+X)nGi{Nf_DC zjrUT>-E09z~}8=y=gV_?5=TN5{$NS0hD6 zk9DRN-qk%T`wn~)mUSjfq_LwjaR&|l<5B8*_~fkYCz0KW%6{Eh3AZ~-hn87vf=~HN2 z-7nwxTYsPN*&xgGVQd+iVBXq&s*zP`T-CLMtDBF9cXXL`|7asKeg(9yYy4vAVW{ST zJPh{-@cAY5b5mEy3B&NifmzwFQc|Pe_!}Eol4|6&$482IDs>WfxLzD*)0H6g`B`Iy0vm z+wsrU_X7{;f9s}SUAh|9r@`1uXfQG@M`va4r_#j4Aym|0G@+lb9SbV!DB8l&INYro zkLYoH;F`(r2|P?n0aZDKnqQ}^HTbqP6A7EU(>ec8{4eH-Nd5dYL=WOK*-U*l7wxX! zE?Yi4D|;=z2-gj~-w43I8at11JHIma=duPp(9=bO@Xx%Ig=y|Z=H{keZV&FTVUUM*4-d0F z^`s}BpAEM?gG5>5q0zAijQo0iE6mzAlhA=z;~Pj)zh3Bbtg!AGk(Ip>Nu6M_*7e32 z#GVt|e`NfNfpqw9{CZ$vy2teYjZy0QTnA&YrO&r=rhXUnt!*+Su=a9)2MiPi;Q;$B@mnV=deeE5G z5m#w!7#Y`3AD>FS^ITu_4($Jpxv&nz>8dFp=5hLuF}nSz1W&f!JgVK#;hs1l{%H;> z`5KM7X$qM6oT4355#2fs0(4o@U)fI<`9^Cl%n6lJdnV)de!T58t}HMzzw3S9l}DEt z4-bF=p9WUnq3EjV;3WQaDdXv*UCdKct^vEd^=Rxk&j=c~3}yTM=cCE2uECVehI9AP z4aPkqVP2<$_UaiVi->XMF|kFW&wxwlOmj(i<1s$tvG0?nTepkY8~csl9HSRNzZ+&` z={ITrbd33&WFuQeYUOKpzhLoYOa#=ZT8HLq8vS3%u9R#C6^cf9D`f~jbYAF_U&qTTo$8;jPs zBP2O|Gj<=B#@WuNuwZfY)Yd$WBdJxnsUAkH8PS1r$VZ@zNzZVN4aa+(%ebG={gUjl zqhH+)eqpBMXot^!&11541KdxJbbWl1YnDC;-Mi_>&^@!xw9ix?J;C*iJ*5MlCd`ss zehl4uop`~^BF0}%aEJk^zsNN@xlPmd_iNre(Pr^E6VvtDfwt*daEyKU2h3j%Z{N#F z|1QYN{`cwN_mKb@pZKTLHx6_@Xb6g@c`(XH@5k!gL!12gZN1NGw) zddd@fN`F08dt1%~($&R?9-`=VidLM3=xvIc<{bKHx%3bR34xn9F2b2dkV~+apS2lR>rVu_b7>VSj=fNRfrpI<9{5Q-5j-dvfOY*4c>Y*-O9sj)OFowxn z^PnHs%t!Prz9Y_zdwcuop*(NUOXH*^=+qUXv$8*+;v3;<1*RaSv(k0L98E}s7(1Q) z42Ea-*{E$lMeEPO%*G3kxDRvwGc5KRV1sepXuVFjX|%ac_&i_M317jazIqO*-F7ab zXDB*E(PQVKJ+8Zy=Z42`avnnuyU171{=0|IGFC(DKR6F`Kd0!W^AYVkA2r08k~>Do z%dYsy52n4+xDE2XegR59NYPUZfa3X?#%Ck)>|by=rOfM19MS&<%dy==%vwLp#2q6o z_0!7xbJYJCRekLRh@Pe>O3|G`MB6D^aUraf*Q=4nfl&$87pcE{7ai?b!N|h^dJ>OM zB=vfveJ==pg^nZi{~K>_esi+R>zT$UzO3wDUI;P15kmA0MZa5!=uL_aP;_T0q8BOp zilV#95WQN4uCsqY`Tl5UZ(B#fC+Ns`3HNh~)`SslplCNm`xhZPMA7Yw5xuz>gv3D6A&Rao zhf?cVJ@FeNe>zpYjAH!fRLi?M#)?98Q#nXIei5SW6#XwnTQ5d*a|NRNDOz6vdGH3J z*tj##<&BkSKJ_&3ppB37I`#t1TjR5`@2NtCv6g+8uXjX!JX`QX#}K{NV%#`3EBj$$ zz?cy{G{`yiw4rPW?gF=U!&I5)e!bG6s@R1bSp)hDB4faeLwZ&DejT%{(^K_ zvb--~JTneU!JneyyK50`rRc+2umH}DZG~yoKq`Xwyk5hwOY@bk*0D;B8&Jj#b!hqh5kxyE`a67#x!1a3oa_5m?}Ems zgn2LA;{mgSA8l?M-{J2*qu^*?JvjP91ERMm+I$J3T@>Bei0Ix%Bio4HkcoId$E$Co z`}K(NyXM%wy^bG%->_kS%f7zT16@DPJo)4i0|v|VeCTdyeWkY}k@AQWhfUAF&^Nr- zn2{&=3WuFDtml*yw`B~ST2Rn)?y!@N?=`a5@ngmm_$Hk6aK^C70|%cpDt~Bx?|%9H zMqQWD^Z3cRead_GoK|+6Z&p#yo}Xs)EIsA)zN1h{(Wn!AgD)D>r>Czd*z=+j@_Poi zn=au3aN5@s&=okkro^QJ>;FIV0KwUCZihoJ%70Gakpll&;86m?LZ&}O;6DgFL*UN@4hY-_{vnB zz;gxuslew5e1pK}3;dM87Ye*v;4*=`k5ct55x7v`3V|00TqE$+0!IXXP~b*^-w=42 zzy`c1QhSyQJX+ut0?!wCmB7mczEvULM6R2mYe>v=L?*ZtLU`|to>(i6j=Mw{zPEyPkR6wK=iaq+#q|Lvf_+7I``0&9QVUkR-Ja*v1Z6TbG(-5~H} z=rLF~-Vj*(>mJidmDhf|FBVw)@4ii7?Z^8gfwezxUuT7{{d)gYVC~;~y};Vf_h$lY zf8P_jD17bryHa57|NDA@wIA@`39S8r?-E%11@D%l=xP7pg#v3o;b#e~{e@Qxto?>x zC$RP(zFuJMNBnhxwLkIw0&BnGeY>jqwSVzEfwiCU*#c{S<3WM7-|9#_P_qVz}gRcRv$%Q`(vLeu=dNoR$%R) z{X>DZpY|cJyVPFoul*c>wcqyt5m@_ge@kHP$2|uIoA9+i_wfR2zwV6!Yya+t1=fDv z8~Q1H?eG0nfwkZFQAewM?f<<&VC@I~L4mbD_=5r;CH+1A7=^z>;5vcNhaQoAyi;K9 zFMf-_+Hd?P0&D;A1HP~5X+QE)1=jxL%LUec<*yT1`t13k25w>01TXe(HZEu=ZEqCb0Hf|DnLze|=ZH zeMR)OAN%0~Yk&4X7FheWzffT9-~Lj8wV(T&1=jxUw+XEM-20AK^=W_i7YMBV-ajI+ z_J4m+VC@J0*Z~S(`@^pgSo_6q7Fheo|Fyu{PyX8iYk&EjPf+x<-~4=mwg3DZ1lE4^ zpA}g9(?13O4}j#S{pv3iSo_s~Qef?0e+c}NQ+e%Y|0;pCzy0S0*8cW0q32Xy``y1n zVC{eZ9|CJX{No0x^4cH&)dFk3{7(q1{quh!u=dkmfOQPjr~UOe3atJ1UoWus-@jI1 z?Z^M$0&9Q%Lr+rlv|s-l1lIojcM7ci{0|?Z%4>iBrwgq8{$D4s_W%E)!216H;Ke`Y zU;jUV!9x|S|1ZD~1b!WI&VapGAh7;F0Zjty{}0eAu>Su5w=xW)jUVAZNHFG{{i_uG zu)w{W6}(>HJb`~hFl<#+%0Edk2=#&8AbJ}C9?KX<&?$0opJE{s=S$hFb+O? z7}1O2PiL5_P`?Fn@Ul4g>NxlYhGX=$#=$${;J+w*vppXw*sT9R9Ncv{x8Ka~9|w<7 zut{%x9Q-w!6+oDY@Dqet2t^2IAk0QM6QLO4EQC1-B?x$YYs^EKk8n1^ISBuSa4y1m z2YDMA@S7-12@VuU3K

ucT#QhGP>E25P>oQ7@Kc0ZggOMA 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 IHDVb52lV}xl>h($ From ad0d17564306311b9a384fb9c4429890a3f5ce0c Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Sat, 7 Dec 2019 08:11:10 +0100 Subject: [PATCH 133/277] Create build_directory_md.py (#678) * Create build_directory_md.py * Create build_directory_md.yml --- .github/build_directory_md.yml | 20 ++++++++++++ .github/scripts/build_directory_md.py | 44 +++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 .github/build_directory_md.yml create mode 100644 .github/scripts/build_directory_md.py diff --git a/.github/build_directory_md.yml b/.github/build_directory_md.yml new file mode 100644 index 000000000..0c41572dc --- /dev/null +++ b/.github/build_directory_md.yml @@ -0,0 +1,20 @@ +# The objective of this GitHub Action is to update the DIRECTORY.md file (if needed) +# when doing a git push +name: directory_writer +on: [push] +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + - uses: actions/setup-python@v1 + with: + python-version: 3.x + - name: Update DIRECTORY.md + run: | + .github/scripts/build_directory_md.py 2>&1 | tee DIRECTORY.md + git config --global user.name github-actions + git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' + git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY + git commit -am "updating DIRECTORY.md" || true + git push --force origin HEAD:$GITHUB_REF || true diff --git a/.github/scripts/build_directory_md.py b/.github/scripts/build_directory_md.py new file mode 100644 index 000000000..8c5c00235 --- /dev/null +++ b/.github/scripts/build_directory_md.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python3 + +import os +from typing import Iterator + +URL_BASE = "https://github.com/TheAlgorithms/C-Plus-Plus/blob/master" + + +def good_filepaths(top_dir: str = ".") -> Iterator[str]: + cpp_exts = tuple(".c .c++ .cc .cpp .cu .cuh .cxx .h .h++ .hh .hpp .hxx".split()) + for dirpath, dirnames, filenames in os.walk(top_dir): + dirnames[:] = [d for d in dirnames if d[0] not in "._"] + for filename in filenames: + if os.path.splitext(filename)[1].lower() in cpp_exts: + yield os.path.join(dirpath, filename).lstrip("./") + + +def md_prefix(i): + return f"{i * ' '}*" if i else "\n##" + + +def print_path(old_path: str, new_path: str) -> str: + old_parts = old_path.split(os.sep) + for i, new_part in enumerate(new_path.split(os.sep)): + if i + 1 > len(old_parts) or old_parts[i] != new_part: + if new_part: + print(f"{md_prefix(i)} {new_part.replace('_', ' ').title()}") + return new_path + + +def print_directory_md(top_dir: str = ".") -> None: + old_path = "" + for filepath in sorted(good_filepaths()): + filepath, filename = os.path.split(filepath) + if filepath != old_path: + old_path = print_path(old_path, filepath) + indent = (filepath.count(os.sep) + 1) if filepath else 0 + url = "/".join((URL_BASE, filepath, filename)).replace(" ", "%20") + filename = os.path.splitext(filename.replace("_", " ").title())[0] + print(f"{md_prefix(indent)} [{filename}]({url})") + + +if __name__ == "__main__": + print_directory_md(".") From f740e1e7a1e2ac07fb17bda46f204b232e0451dd Mon Sep 17 00:00:00 2001 From: Gleison Batista Date: Sat, 7 Dec 2019 04:21:23 -0300 Subject: [PATCH 134/277] Add minimax (#517) * Add minimax * Rename Backtracking/minimax.cpp to backtracking/minimax.cpp * Wrap a long line --- backtracking/minimax.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 backtracking/minimax.cpp diff --git a/backtracking/minimax.cpp b/backtracking/minimax.cpp new file mode 100644 index 000000000..e4fd9eb82 --- /dev/null +++ b/backtracking/minimax.cpp @@ -0,0 +1,27 @@ +#include +#include +#include + +using std::cout; +using std::endl; +using std::max; +using std::min; +using std::vector; + +int minimax(int depth, int node_index, bool is_max, vector scores, + int height) { + if (depth == height) + return scores[node_index]; + + int v1 = minimax(depth + 1, node_index * 2, !is_max, scores, height); + int v2 = minimax(depth + 1, node_index * 2 + 1, !is_max, scores, height); + + return is_max ? max(v1, v2) : min(v1, v2); +} + +int main() { + vector scores = { 90, 23, 6, 33, 21, 65, 123, 34423 }; + int height = log2(scores.size()); + + cout << "Optimal value: " << minimax(0, 0, true, scores, height) << endl; +} From 15f108ec4135d449923d27da79c01d49dbff1271 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Sat, 7 Dec 2019 08:22:09 +0100 Subject: [PATCH 135/277] Rename .github/build_directory_md.yml to .github/workflows/build_directory_md.yml --- .github/{ => workflows}/build_directory_md.yml | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .github/{ => workflows}/build_directory_md.yml (100%) diff --git a/.github/build_directory_md.yml b/.github/workflows/build_directory_md.yml similarity index 100% rename from .github/build_directory_md.yml rename to .github/workflows/build_directory_md.yml From 3a09cf7d889113f7486bbe36a281f95450c31381 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Sat, 7 Dec 2019 08:24:38 +0100 Subject: [PATCH 136/277] git add DIRECTORY.md --- .github/workflows/build_directory_md.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/build_directory_md.yml b/.github/workflows/build_directory_md.yml index 0c41572dc..4a5781f08 100644 --- a/.github/workflows/build_directory_md.yml +++ b/.github/workflows/build_directory_md.yml @@ -16,5 +16,6 @@ jobs: git config --global user.name github-actions git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY + git add DIRECTORY.md git commit -am "updating DIRECTORY.md" || true git push --force origin HEAD:$GITHUB_REF || true From a7f981508f47ff8a8a7eff9a37fb80a06398e4a0 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 7 Dec 2019 07:24:58 +0000 Subject: [PATCH 137/277] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 DIRECTORY.md diff --git a/DIRECTORY.md b/DIRECTORY.md new file mode 100644 index 000000000..b4e79a28b --- /dev/null +++ b/DIRECTORY.md @@ -0,0 +1 @@ +/home/runner/work/_temp/431a1a44-9c8f-4bab-b07f-41218a378bba.sh: line 1: .github/scripts/build_directory_md.py: Permission denied From 2458fea1da18ae3395c3c4613a19b6686f7eb677 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Sat, 7 Dec 2019 08:29:25 +0100 Subject: [PATCH 138/277] chmod +x build_directory_md.py (#679) * chmod +x build_directory_md.py * updating DIRECTORY.md --- .github/scripts/build_directory_md.py | 0 DIRECTORY.md | 152 +++++++++++++++++++++++++- 2 files changed, 151 insertions(+), 1 deletion(-) mode change 100644 => 100755 .github/scripts/build_directory_md.py diff --git a/.github/scripts/build_directory_md.py b/.github/scripts/build_directory_md.py old mode 100644 new mode 100755 diff --git a/DIRECTORY.md b/DIRECTORY.md index b4e79a28b..f2d518d31 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -1 +1,151 @@ -/home/runner/work/_temp/431a1a44-9c8f-4bab-b07f-41218a378bba.sh: line 1: .github/scripts/build_directory_md.py: Permission denied + +## Backtracking + * [Graph Coloring](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/graph_coloring.cpp) + * [Knight Tour](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/knight_tour.cpp) + * [Minimax](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/minimax.cpp) + * [N Queens](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/n_queens.cpp) + * [Rat Maze](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/rat_maze.cpp) + * [Sudoku Solve](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/sudoku_solve.cpp) + +## Computer Oriented Statistical Methods + * [Bisection Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/Bisection_method.CPP) + * [Gaussian Elimination](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/Gaussian_elimination.cpp) + * [Newton Raphson](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/Newton_Raphson.CPP) + * [Secant Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/Secant_method.CPP) + * [False-Position](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/false-position.CPP) + * [Successive Approximation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/successive_approximation.CPP) + +## Data Structure + * [Avltree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/AVLtree.cpp) + * [Binary Search Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Binary%20Search%20Tree.cpp) + * [Binaryheap](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Binaryheap.cpp) + * [Doubly Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Doubly%20Linked%20List.cpp) + * [Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Linked%20List.cpp) + * [List Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/List%20Array.cpp) + * [Morrisinorder](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/MorrisInorder.cpp) + * [Queue Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Queue%20Using%20Array.cpp) + * [Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Queue%20Using%20Linked%20List.cpp) + * [Stack Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Stack%20Using%20Array.cpp) + * [Stack Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Stack%20Using%20Linked%20List.cpp) + * [Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Tree.cpp) + * [Trietree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/TrieTree.cpp) + * [Circular Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/circular_Queue_using_Linked_List.cpp) + * [Linkedlist Implentation Usingarray](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/linkedList_implentation_usingArray.cpp) + +## Dynamic Programming + * [0-1 Knapsack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/0-1%20Knapsack.cpp) + * [Armstrong Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Armstrong%20Number.cpp) + * [Bellman-Ford](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Bellman-Ford.cpp) + * [Catalan-Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Catalan-Numbers.cpp) + * [Coin-Change](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Coin-Change.cpp) + * [Cut Rod](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Cut%20Rod.cpp) + * [Edit Distance](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Edit%20Distance.cpp) + * [Egg-Dropping-Puzzle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Egg-Dropping-Puzzle.cpp) + * [Fibonacci Bottom Up](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Fibonacci_Bottom_Up.cpp) + * [Fibonacci Top Down](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Fibonacci_Top_Down.cpp) + * [Floyd-Warshall](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Floyd-Warshall.cpp) + * [Longest Common Subsequence](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Longest%20Common%20Subsequence.cpp) + * [Longest Increasing Subsequence (Nlogn)](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Longest%20Increasing%20Subsequence%20(nlogn).cpp) + * [Longest Increasing Subsequence](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Longest%20Increasing%20Subsequence.cpp) + * [Matrix-Chain-Multiplication](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Matrix-Chain-Multiplication.cpp) + * [Kadane](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/kadane.cpp) + * [Longest Common String](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/longest_common_string.cpp) + +## Graph + * [Bfs](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/BFS.cpp) + * [Dfs](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/DFS.cpp) + * [Dfs With Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/DFS_with_stack.cc) + * [Dijkstra](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/Dijkstra.cpp) + * [Kruskal](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/Kruskal.cpp) + * [Topological-Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/Topological-Sort.cpp) + * [Kosaraju](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/kosaraju.cpp) + * [Lca](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/lca.cpp) + +## Greedy Algorithms + * [Dijkstra](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/Dijkstra.cpp) + * [Knapsack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/Knapsack.cpp) + * [Kruskals Minimum Spanning Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/Kruskals%20Minimum%20Spanning%20Tree.cpp) + * [Prims Minimum Spanning Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/Prims%20Minimum%20Spanning%20Tree.cpp) + * [Huffman](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/huffman.cpp) + +## Hashing + * [Chaining](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/Chaining.cpp) + +## Math + * [Factorial](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/factorial.cpp) + * [Greatest Common Divisor](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/greatest_common_divisor.cpp) + * [Power For Huge Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/power_for_huge_numbers.cpp) + * [Prime Factorization](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/prime_factorization.cpp) + * [Prime Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/prime_numbers.cpp) + * [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/sieve_of_eratosthenes.cpp) + +## Operations On Datastructures + * [Array Left Rotation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Array%20Left%20Rotation.cpp) + * [Array Right Rotation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Array%20Right%20Rotation.cpp) + * [Circular Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Circular%20Linked%20List.cpp) + * [Circular Queue Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Circular%20Queue%20Using%20Array.cpp) + * [Intersection Of 2 Arrays](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Intersection_of_2_arrays.cpp) + * [Reverse A Linked List Using Recusion](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Reverse%20a%20Linked%20List%20using%20Recusion.cpp) + * [Union Of 2 Arrays](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Union_of_2_arrays.cpp) + * [Selectionsortlinkedlist](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/selectionSortLinkedList.cpp) + +## Others + * [Buzz Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Buzz_number.cpp) + * [Decimal To Binary](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Decimal%20To%20Binary.cpp) + * [Decimal To Hexadecimal ](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Decimal%20To%20Hexadecimal%20.cpp) + * [Decimal To Roman Numeral](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Decimal%20to%20Roman%20Numeral.cpp) + * [Gcd Of N Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/GCD_of_n_numbers.cpp) + * [Palindromeofnumber](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Palindromeofnumber.cpp) + * [Paranthesis Matching](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Paranthesis%20Matching.cpp) + * [Primality Test](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Primality%20Test.cpp) + * [Sparse Matrix](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Sparse%20matrix.cpp) + * [Strassen Matrix Multiplication](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Strassen%20Matrix%20Multiplication.cpp) + * [String Fibonacci](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/String%20Fibonacci.cpp) + * [Tower Of Hanoi](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Tower%20of%20Hanoi.cpp) + * [Fibonacci](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/fibonacci.cpp) + * [Happy Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/happy_number.cpp) + * [Matrix Exponentiation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/matrix_exponentiation.cpp) + * [Pascal Triangle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/pascal_triangle.cpp) + * [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/sieve_of_Eratosthenes.cpp) + * [Smallest-Circle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/smallest-circle.cpp) + * [Spiral Print](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/spiral_print.cpp) + * [Vector Important Functions](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/vector_important_functions.cpp) + +## Range Queries + * [Fenwicktree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/FenwickTree.cpp) + * [Mo](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/MO.cpp) + * [Bit](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/bit.cpp) + * [Segtree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/segTree.cpp) + +## Search + * [Binary Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/Binary%20Search.cpp) + * [Interpolation Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/Interpolation%20Search.cpp) + * [Linear Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/Linear%20Search.cpp) + * [Exponential Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/exponential_search.cpp) + * [Median Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/median_search.cpp) + * [Searching](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/searching.cpp) + * [Ternary Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/ternary_search.cpp) + +## Sorting + * [Beadsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/BeadSort.cpp) + * [Bitonicsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/BitonicSort.cpp) + * [Bubble Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Bubble%20Sort.cpp) + * [Cocktailselectionsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/CocktailSelectionSort.cpp) + * [Countingsortstring](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/CountingSortString.cpp) + * [Counting Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Counting_Sort.cpp) + * [Heap Sort ](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Heap%20Sort%20.cpp) + * [Insertion Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Insertion%20Sort.cpp) + * [Merge Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Merge%20Sort.cpp) + * [Numericstringsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/NumericStringSort.cpp) + * [Oddeven Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/OddEven%20Sort.cpp) + * [Quick Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Quick%20Sort.cpp) + * [Radix Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Radix%20Sort.cpp) + * [Selection Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Selection%20Sort.cpp) + * [Shell Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Shell%20Sort.cpp) + * [Slow Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Slow%20Sort.cpp) + * [Tim Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Tim%20Sort.cpp) + * [Bucketsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/bucketSort.cpp) + * [Combsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/combsort.cpp) + +## Strings + * [Knuth Morris Pratt](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/strings/knuth_morris_pratt.cpp) From 4194b204f64aef8655bbfa7567bd7ef6ea3197ca Mon Sep 17 00:00:00 2001 From: Ajay Singh Date: Sat, 7 Dec 2019 13:03:23 +0530 Subject: [PATCH 139/277] Prime (#585) * Prime Here we can check prime upto 10^8 in O(1). It is very useful in Competitive programming. * Update and rename Math/Primeupto10^8.cpp to math/primes_up_to_10^8.cpp * long long -> int64 * cstdint::int64_t * int64_t * std::cin --- math/primes_up_to_10^8.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 math/primes_up_to_10^8.cpp diff --git a/math/primes_up_to_10^8.cpp b/math/primes_up_to_10^8.cpp new file mode 100644 index 000000000..db9b56cab --- /dev/null +++ b/math/primes_up_to_10^8.cpp @@ -0,0 +1,27 @@ +#include +#include + +char prime[100000000]; + +void Sieve(int64_t n) { + memset(prime, '1', sizeof(prime)); // intitize '1' to every index + prime[0] = '0'; // 0 is not prime + prime[1] = '0'; // 1 is not prime + for (int p = 2; p * p <= n; p++) { + if (prime[p] == '1') { + for (int i = p * p; i <= n; i += p) + prime[i] = '0'; // set all multiples of p to false + } + } +} + + +int main() { + Sieve(100000000); + int64_t n; + std::cin >> n; // 10006187 + if (prime[n] == '1') + std::cout << "YES\n"; + else + std::cout << "NO\n"; +} From 904796b6baf4eff86e87adc5e0fa7b0da240090d Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 7 Dec 2019 07:33:45 +0000 Subject: [PATCH 140/277] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index f2d518d31..bfe60901f 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -77,6 +77,7 @@ * [Power For Huge Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/power_for_huge_numbers.cpp) * [Prime Factorization](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/prime_factorization.cpp) * [Prime Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/prime_numbers.cpp) + * [Primes Up To 10^8](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/primes_up_to_10^8.cpp) * [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/sieve_of_eratosthenes.cpp) ## Operations On Datastructures From 08451b1c4ca0f86f2abfaa5accda9b341af8ffe9 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Sat, 7 Dec 2019 08:35:25 +0100 Subject: [PATCH 141/277] Delete .DS_Store --- .DS_Store | Bin 6148 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index ab5825a1870609ff8f986f1d3d79dfec591f7a6f..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHK!AiqG5S?wSZYyFALOtfENIpaV$UpFR zoY~zLYZY%I?GDVo+1Z&5^AdJ50Kn{Vrv_jE07oUv6><1RXq|LHa>`RcWVDAjiH6=F z^l<*R5Um~mkpX&l1=xok_z-`7f8KE5M{%|K&T{#}+WH3PC0^Pp-8%hn;>2z|j%;^y zO|x@1?t99<2*bh5cD+l#J82m^$6*k=e$X9>WWUqJkee$%=!6qH90#39?BmD<&WpU* zGRjF(uU5=@wU$=Qq|qSz;4n>#yu4RCI&I%QJSI=+^NS>v;rAzGTj3O5(U{eD?~H;$ z81&Fb@#}B~G4!DeBZ!u?_PH9r)Ia4&qh>%euzC!rGm~$wUg^4G&46a$7Y68jFi{CD zg_%Tgbl@Ob07UwY6oNMO5|m>qv=n9%aRr6RR79D|RExo6I{Hl&XDQ4i%5-3=`C#hF zOm!$sJRSEpMK~}^q8>E^nt^!+@^Wg>{eSXv|39CkXPN=cz)~^53QebJV@c|6T_}$3 vS`)R6N Date: Wed, 11 Dec 2019 17:53:41 +0530 Subject: [PATCH 142/277] Showing 153 is not an Armstrong number. (#680) * Update Armstrong Number.cpp * Update Armstrong Number.cpp * Update Armstrong Number.cpp * Update Armstrong Number.cpp * Rename Armstrong Number.cpp to armstrong_number.cpp * Update armstrong_number.cpp Showing 153 as not an Armstrong number. * Update armstrong_number.cpp --- ...rmstrong Number.cpp => armstrong_number.cpp} | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) rename dynamic_programming/{Armstrong Number.cpp => armstrong_number.cpp} (55%) diff --git a/dynamic_programming/Armstrong Number.cpp b/dynamic_programming/armstrong_number.cpp similarity index 55% rename from dynamic_programming/Armstrong Number.cpp rename to dynamic_programming/armstrong_number.cpp index 098c8c628..4dba89a27 100644 --- a/dynamic_programming/Armstrong Number.cpp +++ b/dynamic_programming/armstrong_number.cpp @@ -1,16 +1,17 @@ -//program to check whether a number is an armstrong number or not -#include -#include -int main() -{ +// Program to check whether a number is an armstrong number or not +#include + +using std::cout; +using std::cin; + +int main() { int n, k, d, s = 0; cout << "Enter a number:"; cin >> n; k = n; - while (k != 0) - { + while (k != 0) { d = k % 10; - s += (int)pow(d, 3); + s += d * d * d; k /= 10; } if (s == n) From 835a518a34828abf637b7d108f85eb5a573e17a0 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Wed, 11 Dec 2019 12:24:02 +0000 Subject: [PATCH 143/277] updating DIRECTORY.md --- DIRECTORY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index bfe60901f..8320c397b 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -34,7 +34,6 @@ ## Dynamic Programming * [0-1 Knapsack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/0-1%20Knapsack.cpp) - * [Armstrong Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Armstrong%20Number.cpp) * [Bellman-Ford](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Bellman-Ford.cpp) * [Catalan-Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Catalan-Numbers.cpp) * [Coin-Change](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Coin-Change.cpp) @@ -48,6 +47,7 @@ * [Longest Increasing Subsequence (Nlogn)](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Longest%20Increasing%20Subsequence%20(nlogn).cpp) * [Longest Increasing Subsequence](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Longest%20Increasing%20Subsequence.cpp) * [Matrix-Chain-Multiplication](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Matrix-Chain-Multiplication.cpp) + * [Armstrong Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/armstrong_number.cpp) * [Kadane](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/kadane.cpp) * [Longest Common String](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/longest_common_string.cpp) From e50d0ffffe8c5a886288952fd91c1213d4de4020 Mon Sep 17 00:00:00 2001 From: Eric Curtin Date: Mon, 16 Dec 2019 12:21:16 +0000 Subject: [PATCH 144/277] Use getchar over getch (#681) * Use getchar over getch getch in Windows specific. Now the code will compile and work on other platforms like Linux and macOS. * Update and rename Heap Sort .cpp to heap_sort .cpp * cpplint fixes * Rename heap_sort .cpp to heap_sort.cpp --- sorting/Heap Sort .cpp | 62 ------------------------------------------ sorting/heap_sort.cpp | 51 ++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 62 deletions(-) delete mode 100644 sorting/Heap Sort .cpp create mode 100644 sorting/heap_sort.cpp diff --git a/sorting/Heap Sort .cpp b/sorting/Heap Sort .cpp deleted file mode 100644 index f188a0ea9..000000000 --- a/sorting/Heap Sort .cpp +++ /dev/null @@ -1,62 +0,0 @@ -#include -#include -using namespace std; -void max_heapify(int *a, int i, int n) -{ - int j, temp; - temp = a[i]; - j = 2 * i; - while (j <= n) - { - if (j < n && a[j + 1] > a[j]) - j = j + 1; - if (temp > a[j]) - break; - else if (temp <= a[j]) - { - a[j / 2] = a[j]; - j = 2 * j; - } - } - a[j / 2] = temp; - return; -} -void heapsort(int *a, int n) -{ - int i, temp; - for (i = n; i >= 2; i--) - { - temp = a[i]; - a[i] = a[1]; - a[1] = temp; - max_heapify(a, 1, i - 1); - } -} -void build_maxheap(int *a, int n) -{ - int i; - for (i = n / 2; i >= 1; i--) - { - max_heapify(a, i, n); - } -} -int main() -{ - int n, i, x; - cout << "Enter number of elements of array\n"; - cin >> n; - int a[20]; - for (i = 1; i <= n; i++) - { - cout << "Enter Element " << (i) << endl; - cin >> a[i]; - } - build_maxheap(a, n); - heapsort(a, n); - cout << "Sorted Output\n"; - for (i = 1; i <= n; i++) - { - cout << a[i] << endl; - } - getch(); -} diff --git a/sorting/heap_sort.cpp b/sorting/heap_sort.cpp new file mode 100644 index 000000000..c72afc103 --- /dev/null +++ b/sorting/heap_sort.cpp @@ -0,0 +1,51 @@ +#include + +void max_heapify(int *a, int i, int n) { + int j, temp; + temp = a[i]; + j = 2 * i; + while (j <= n) { + if (j < n && a[j + 1] > a[j]) + j = j + 1; + if (temp > a[j]) { + break; + } else if (temp <= a[j]) { + a[j / 2] = a[j]; + j = 2 * j; + } + } + a[j / 2] = temp; + return; +} +void heapsort(int *a, int n) { + int i, temp; + for (i = n; i >= 2; i--) { + temp = a[i]; + a[i] = a[1]; + a[1] = temp; + max_heapify(a, 1, i - 1); + } +} +void build_maxheap(int *a, int n) { + int i; + for (i = n / 2; i >= 1; i--) { + max_heapify(a, i, n); + } +} +int main() { + int n, i, x; + std::cout << "Enter number of elements of array\n"; + std::cin >> n; + int a[20]; + for (i = 1; i <= n; i++) { + std::cout << "Enter Element " << (i) << endl; + std::cin >> a[i]; + } + build_maxheap(a, n); + heapsort(a, n); + std::cout << "Sorted Output\n"; + for (i = 1; i <= n; i++) { + std::cout << a[i] << endl; + } + std::getchar(); +} From 040b96f905b9cf6b1a168d519174adef483b0d6d Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 16 Dec 2019 12:21:36 +0000 Subject: [PATCH 145/277] updating DIRECTORY.md --- DIRECTORY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index 8320c397b..670d66bb4 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -134,7 +134,6 @@ * [Cocktailselectionsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/CocktailSelectionSort.cpp) * [Countingsortstring](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/CountingSortString.cpp) * [Counting Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Counting_Sort.cpp) - * [Heap Sort ](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Heap%20Sort%20.cpp) * [Insertion Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Insertion%20Sort.cpp) * [Merge Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Merge%20Sort.cpp) * [Numericstringsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/NumericStringSort.cpp) @@ -147,6 +146,7 @@ * [Tim Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Tim%20Sort.cpp) * [Bucketsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/bucketSort.cpp) * [Combsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/combsort.cpp) + * [Heap Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/heap_sort.cpp) ## Strings * [Knuth Morris Pratt](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/strings/knuth_morris_pratt.cpp) From 6e9f64db6abfef6fd5521b91a4134d360bf9f7c9 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 17 Dec 2019 16:19:12 +0000 Subject: [PATCH 146/277] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 670d66bb4..dee4aaa9e 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -123,6 +123,7 @@ * [Interpolation Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/Interpolation%20Search.cpp) * [Linear Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/Linear%20Search.cpp) * [Exponential Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/exponential_search.cpp) + * [Hash Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/hash_search.cpp) * [Median Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/median_search.cpp) * [Searching](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/searching.cpp) * [Ternary Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/ternary_search.cpp) From 78f500e8648d687a898ef55821de279def8558ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8B=8F=E6=B7=9E=E4=B8=B0?= <50102735+Arctic2333@users.noreply.github.com> Date: Thu, 19 Dec 2019 17:37:30 +0800 Subject: [PATCH 147/277] Repair warning: ISO C + + forbids converting a string constant to 'char *' [- wwrite strings] (#683) * Add header file * Add header file and regulate code style * Add header file and regulate code style * Do not use namespace using-directives. Use using-declarations instead. * Arctic2333 Add header file and regulate code style . Do not use namespace using-directives. Use using-declarations instead. * Repair warning: ISO C + + forbids converting a string constant to 'char *' [- wwrite strings] * Repair warning: ISO C + + forbids converting a string constant to 'char *' [- wwrite strings] * rename * RENAME * Repair warning: ISO C + + forbids converting a string constant to 'char *' [- wwrite strings] * char * -> string * Update and rename trietree.cpp to trie_tree.cpp * Delete TrieTree.cpp * char hello[] = "hello"; --- data_structure/TrieTree.cpp | 97 ------------------------------------ data_structure/trie_tree.cpp | 91 +++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+), 97 deletions(-) delete mode 100644 data_structure/TrieTree.cpp create mode 100644 data_structure/trie_tree.cpp diff --git a/data_structure/TrieTree.cpp b/data_structure/TrieTree.cpp deleted file mode 100644 index 2368a76aa..000000000 --- a/data_structure/TrieTree.cpp +++ /dev/null @@ -1,97 +0,0 @@ -#include -#include -#include -using namespace std; -// structure definition -typedef struct trie -{ - struct trie *arr[26]; - bool isEndofWord; -} trie; -// create a new node for trie -trie *createNode() -{ - trie *nn = new trie(); - for (int i = 0; i < 26; i++) - nn->arr[i] = NULL; - nn->isEndofWord = false; - return nn; -} - -// insert string into the trie -void insert(trie *root, char *str) -{ - for (int i = 0; i < strlen(str); i++) - { - int j = str[i] - 'a'; - if (root->arr[j]) - { - root = root->arr[j]; - } - else - { - root->arr[j] = createNode(); - root = root->arr[j]; - } - } - root->isEndofWord = true; -} - -// search a string exists inside the trie -bool search(trie *root, char *str, int index) -{ - if (index == strlen(str)) - { - if (!root->isEndofWord) - return false; - return true; - } - int j = str[index] - 'a'; - if (!root->arr[j]) - return false; - return search(root->arr[j], str, index + 1); -} -/* removes the string if it is not a prefix of any other - string, if it is then just sets the endofword to false, else - removes the given string*/ -bool deleteString(trie *root, char *str, int index) -{ - if (index == strlen(str)) - { - if (!root->isEndofWord) - return false; - root->isEndofWord = false; - for (int i = 0; i < 26; i++) - return false; - return true; - } - int j = str[index] - 'a'; - if (!root->arr[j]) - return false; - bool var = deleteString(root, str, index + 1); - if (var) - { - root->arr[j] = NULL; - if (root->isEndofWord) - return false; - else - { - int i; - for (i = 0; i < 26; i++) - if (root->arr[i]) - return false; - return true; - } - } -} - -int main() -{ - trie *root = createNode(); - insert(root, "hello"); - insert(root, "world"); - int a = search(root, "hello", 0); - int b = search(root, "word", 0); - printf("%d %d ", a, b); - return 0; -} \ No newline at end of file diff --git a/data_structure/trie_tree.cpp b/data_structure/trie_tree.cpp new file mode 100644 index 000000000..56cd25427 --- /dev/null +++ b/data_structure/trie_tree.cpp @@ -0,0 +1,91 @@ +#include +#include +#include +#include + +// structure definition +typedef struct trie { + struct trie * arr[26]; + bool isEndofWord; +} +trie; + +// create a new node for trie +trie * createNode() { + trie * nn = new trie(); + for (int i = 0; i < 26; i++) + nn -> arr[i] = NULL; + nn -> isEndofWord = false; + return nn; +} + +// insert string into the trie +void insert(trie * root, char * str) { + for (int i = 0; i < strlen(str); i++) { + int j = str[i] - 'a'; + if (root -> arr[j]) { + root = root -> arr[j]; + } else { + root -> arr[j] = createNode(); + root = root -> arr[j]; + } + } + root -> isEndofWord = true; +} + +// search a string exists inside the trie +bool search(trie * root, char * str, int index) { + if (index == strlen(str)) { + if (!root -> isEndofWord) + return false; + return true; + } + int j = str[index] - 'a'; + if (!root -> arr[j]) + return false; + return search(root -> arr[j], str, index + 1); +} + +/* removes the string if it is not a prefix of any other + string, if it is then just sets the endofword to false, else + removes the given string*/ +bool deleteString(trie * root, char * str, int index) { + if (index == strlen(str)) { + if (!root -> isEndofWord) + return false; + root -> isEndofWord = false; + for (int i = 0; i < 26; i++) + return false; + return true; + } + int j = str[index] - 'a'; + if (!root -> arr[j]) + return false; + bool + var = deleteString(root, str, index + 1); + if (var) { + root -> arr[j] = NULL; + if (root -> isEndofWord) { + return false; + } else { + int i; + for (i = 0; i < 26; i++) + if (root -> arr[i]) + return false; + return true; + } + } +} + +int main() { + trie * root = createNode(); + char hello[] = "hello"; + char world[] = "world"; + char word[] = "word"; + insert(root, hello); + insert(root, world); + int a = search(root, hello, 0); + int b = search(root, word, 0); + printf("%d %d ", a, b); + return 0; +} From 8e36a38729ee0ca4b467b8096a13603efdda256f Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 19 Dec 2019 09:37:52 +0000 Subject: [PATCH 148/277] updating DIRECTORY.md --- DIRECTORY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index dee4aaa9e..9caf75034 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -28,9 +28,9 @@ * [Stack Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Stack%20Using%20Array.cpp) * [Stack Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Stack%20Using%20Linked%20List.cpp) * [Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Tree.cpp) - * [Trietree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/TrieTree.cpp) * [Circular Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/circular_Queue_using_Linked_List.cpp) * [Linkedlist Implentation Usingarray](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/linkedList_implentation_usingArray.cpp) + * [Trie Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/trie_tree.cpp) ## Dynamic Programming * [0-1 Knapsack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/0-1%20Knapsack.cpp) From b5a074f1886463db682fd8281e31900aa838a34f Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 19 Dec 2019 12:48:43 +0100 Subject: [PATCH 149/277] trie_tree.cpp: #include --> (#684) * trie_tree.cpp: #include --> * std::string str --- data_structure/trie_tree.cpp | 37 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 19 deletions(-) diff --git a/data_structure/trie_tree.cpp b/data_structure/trie_tree.cpp index 56cd25427..2b84099e8 100644 --- a/data_structure/trie_tree.cpp +++ b/data_structure/trie_tree.cpp @@ -1,14 +1,14 @@ #include -#include #include + #include +#include // structure definition typedef struct trie { struct trie * arr[26]; bool isEndofWord; -} -trie; +} trie; // create a new node for trie trie * createNode() { @@ -20,8 +20,8 @@ trie * createNode() { } // insert string into the trie -void insert(trie * root, char * str) { - for (int i = 0; i < strlen(str); i++) { +void insert(trie * root, std::string str) { + for (int i = 0; i < str.length(); i++) { int j = str[i] - 'a'; if (root -> arr[j]) { root = root -> arr[j]; @@ -34,8 +34,8 @@ void insert(trie * root, char * str) { } // search a string exists inside the trie -bool search(trie * root, char * str, int index) { - if (index == strlen(str)) { +bool search(trie * root, std::string str, int index) { + if (index == str.length()) { if (!root -> isEndofWord) return false; return true; @@ -46,11 +46,13 @@ bool search(trie * root, char * str, int index) { return search(root -> arr[j], str, index + 1); } -/* removes the string if it is not a prefix of any other - string, if it is then just sets the endofword to false, else - removes the given string*/ -bool deleteString(trie * root, char * str, int index) { - if (index == strlen(str)) { +/* +removes the string if it is not a prefix of any other +string, if it is then just sets the endofword to false, else +removes the given string +*/ +bool deleteString(trie * root, std::string str, int index) { + if (index == str.length()) { if (!root -> isEndofWord) return false; root -> isEndofWord = false; @@ -79,13 +81,10 @@ bool deleteString(trie * root, char * str, int index) { int main() { trie * root = createNode(); - char hello[] = "hello"; - char world[] = "world"; - char word[] = "word"; - insert(root, hello); - insert(root, world); - int a = search(root, hello, 0); - int b = search(root, word, 0); + insert(root, "hello"); + insert(root, "world"); + int a = search(root, "hello", 0); + int b = search(root, "word", 0); printf("%d %d ", a, b); return 0; } From 944382a90a2b7b8fd121c7f4085d7f1f18ec28a8 Mon Sep 17 00:00:00 2001 From: achance6 <45263295+achance6@users.noreply.github.com> Date: Sat, 21 Dec 2019 03:17:08 -0500 Subject: [PATCH 150/277] feat: Implemented open addressing hash tables (#673) * feat: Implemented open addressing hash tables * fix: Find command and cpplint compliance --- hashing/double_hash_hash_table.cpp | 235 ++++++++++++++++++++++ hashing/linear_probing_hash_table.cpp | 226 +++++++++++++++++++++ hashing/quadratic_probing_hash_table.cpp | 239 +++++++++++++++++++++++ 3 files changed, 700 insertions(+) create mode 100644 hashing/double_hash_hash_table.cpp create mode 100644 hashing/linear_probing_hash_table.cpp create mode 100644 hashing/quadratic_probing_hash_table.cpp diff --git a/hashing/double_hash_hash_table.cpp b/hashing/double_hash_hash_table.cpp new file mode 100644 index 000000000..6030b7ff3 --- /dev/null +++ b/hashing/double_hash_hash_table.cpp @@ -0,0 +1,235 @@ +// Copyright 2019 + +#include +#include +#include +#include + +using std::endl; +using std::cout; +using std::cin; +using std::string; + +// fwd declarations +struct Entry; +bool putProber(Entry entry, int key); +bool searchingProber(Entry entry, int key); +void add(int key); + +// globals +int notPresent; +struct Entry* table; +int totalSize; +int tomb = -1; +int size; +bool rehashing; + +// Node that holds key +struct Entry { + explicit Entry(int key = notPresent) : key(key) {} + int key; +}; + +// Hash a key +int hashFxn(int key) { + std::hash hash; + return hash(key); +} + +// Used for second hash function +int otherHashFxn(int key) { + std::hash hash; + return 1 + (7 - (hash(key) % 7)); +} + +// Performs double hashing to resolve collisions +int doubleHash(int key, bool searching) { + int hash = static_cast(fabs(hashFxn(key))); + int i = 0; + Entry entry; + do { + int index = static_cast(fabs((hash + + (i * otherHashFxn(key))))) % totalSize; + entry = table[index]; + if (searching) { + if (entry.key == notPresent) { + return notPresent; + } + if (searchingProber(entry, key)) { + cout << "Found key!" << endl; + return index; + } + cout << "Found tombstone or equal hash, checking next" << endl; + i++; + } else { + if (putProber(entry, key)) { + if (!rehashing) cout << "Spot found!" << endl; + return index; + } + if (!rehashing) cout << "Spot taken, looking at next (next index:" + << " " << static_cast(fabs((hash + + (i * otherHashFxn(key))))) % totalSize << ")" << endl; + i++; + } + if (i == totalSize * 100) { + cout << "DoubleHash probe failed" << endl; + return notPresent; + } + } while (entry.key != notPresent); + return notPresent; +} + +// Finds empty spot +bool putProber(Entry entry, int key) { + if (entry.key == notPresent || entry.key == tomb) { + return true; + } + return false; +} + +// Looks for a matching key +bool searchingProber(Entry entry, int key) { + if (entry.key == key) return true; + return false; +} + +// Displays the table +void display() { + for (int i = 0; i < totalSize; i++) { + if (table[i].key == notPresent) { + cout << " Empty "; + } else if (table[i].key == tomb) { + cout << " Tomb "; + } else { + cout << " "; + cout << table[i].key; + cout << " "; + } + } + cout << endl; +} + +// Rehashes the table into a bigger table +void rehash() { + // Necessary so wall of add info isn't printed all at once + rehashing = true; + int oldSize = totalSize; + Entry* oldTable = table; + // Really this should use the next prime number greater than totalSize * 2 + table = new Entry[totalSize * 2]; + totalSize *= 2; + for (int i = 0; i < oldSize; i++) { + if (oldTable[i].key != -1 && oldTable[i].key != notPresent) { + size--; // Size stays the same (add increments size) + add(oldTable[i].key); + } + } + delete[] oldTable; + rehashing = false; + cout << "Table was rehashed, new size is: " << totalSize << endl; +} + +// Checks for load factor here +void add(int key) { + Entry * entry = new Entry(); + entry->key = key; + int index = doubleHash(key, false); + table[index] = *entry; + // Load factor greater than 0.5 causes resizing + if (++size/ static_cast(totalSize) >= 0.5) { + rehash(); + } +} + +// Removes key. Leaves tombstone upon removal. +void remove(int key) { + int index = doubleHash(key, true); + if (index == notPresent) { + cout << "key not found" << endl; + } + table[index].key = tomb; + cout << "Removal successful, leaving tombstone" << endl; + size--; +} + +// Information about the adding process +void addInfo(int key) { + cout << "Initial table: "; + display(); + cout << endl; + cout << "hash of " << key << " is " << hashFxn(key) + << " % " << totalSize << " == " << fabs(hashFxn(key) % totalSize); + cout << endl; + add(key); + cout << "New table: "; + display(); +} + +// Information about removal process +void removalInfo(int key) { + cout << "Initial table: "; + display(); + cout << endl; + cout << "hash of " << key << " is " << hashFxn(key) + << " % " << totalSize << " == " << hashFxn(key) % totalSize; + cout << endl; + remove(key); + cout << "New table: "; + display(); +} + +// I/O +int main(void) { + int cmd, hash, key; + cout << "Enter the initial size of Hash Table. = "; + cin >> totalSize; + table = new Entry[totalSize]; + bool loop = true; + while (loop) { + system("pause"); + cout << endl; + cout << "PLEASE CHOOSE -" << endl; + cout << "1. Add key. (Numeric only)" << endl; + cout << "2. Remove key." << endl; + cout << "3. Find key." << endl; + cout << "4. Generate Hash. (Numeric only)" << endl; + cout << "5. Display Hash table." << endl; + cout << "6. Exit." << endl; + cin >> cmd; + switch (cmd) { + case 1: + cout << "Enter key to add = "; + cin >> key; + addInfo(key); + break; + case 2: + cout << "Enter key to remove = "; + cin >> key; + removalInfo(key); + break; + case 3: { + cout << "Enter key to search = "; + cin >> key; + Entry entry = table[doubleHash(key, true)]; + if (entry.key == notPresent) { + cout << "Key not present"; + } + break; + } + case 4: + cout << "Enter element to generate hash = "; + cin >> key; + cout << "Hash of " << key << " is = " << fabs(hashFxn(key)); + break; + case 5: + display(); + break; + default: + loop = false; + break; + delete[] table; + } + cout << endl; + } + return 0; +} diff --git a/hashing/linear_probing_hash_table.cpp b/hashing/linear_probing_hash_table.cpp new file mode 100644 index 000000000..b00eb8641 --- /dev/null +++ b/hashing/linear_probing_hash_table.cpp @@ -0,0 +1,226 @@ +// Copyright 2019 + +#include +#include +#include +#include + +using std::endl; +using std::cout; +using std::cin; +using std::string; + +// fwd declarations +struct Entry; +bool putProber(Entry entry, int key); +bool searchingProber(Entry entry, int key); +void add(int key); + +// globals +int notPresent; +struct Entry* table; +int totalSize; +int tomb = -1; +int size; +bool rehashing; + +// Node that holds key +struct Entry { + explicit Entry(int key = notPresent) : key(key) {} + int key; +}; + +// Hash a key +int hashFxn(int key) { + std::hash hash; + return hash(key); +} + +// Performs linear probing to resolve collisions +int linearProbe(int key, bool searching) { + int hash = static_cast(fabs(hashFxn(key))); + int i = 0; + Entry entry; + do { + int index = static_cast(fabs((hash + i) % totalSize)); + entry = table[index]; + if (searching) { + if (entry.key == notPresent) { + return notPresent; + } + if (searchingProber(entry, key)) { + cout << "Found key!" << endl; + return index; + } + cout << "Found tombstone or equal hash, checking next" << endl; + i++; + } else { + if (putProber(entry, key)) { + if (!rehashing) cout << "Spot found!" << endl; + return index; + } + if (!rehashing) cout << "Spot taken, looking at next" << endl; + i++; + } + if (i == totalSize) { + cout << "Linear probe failed" << endl; + return notPresent; + } + } while (entry.key != notPresent); + return notPresent; +} + +// Finds empty spot +bool putProber(Entry entry, int key) { + if (entry.key == notPresent || entry.key == tomb) { + return true; + } + return false; +} + +// Looks for a matching key +bool searchingProber(Entry entry, int key) { + if (entry.key == key) return true; + return false; +} + +// Displays the table +void display() { + for (int i = 0; i < totalSize; i++) { + if (table[i].key == notPresent) { + cout << " Empty "; + } else if (table[i].key == tomb) { + cout << " Tomb "; + } else { + cout << " "; + cout << table[i].key; + cout << " "; + } + } + cout << endl; +} + +// Rehashes the table into a bigger table +void rehash() { + // Necessary so wall of add info isn't printed all at once + rehashing = true; + int oldSize = totalSize; + Entry* oldTable = table; + // Really this should use the next prime number greater than totalSize * 2 + table = new Entry[totalSize * 2]; + totalSize *= 2; + for (int i = 0; i < oldSize; i++) { + if (oldTable[i].key != -1 && oldTable[i].key != notPresent) { + size--; // Size stays the same (add increments size) + add(oldTable[i].key); + } + } + delete[] oldTable; + rehashing = false; + cout << "Table was rehashed, new size is: " << totalSize << endl; +} + +// Adds entry using linear probing. Checks for load factor here +void add(int key) { + Entry * entry = new Entry(); + entry->key = key; + int index = linearProbe(key, false); + table[index] = *entry; + // Load factor greater than 0.5 causes resizing + if (++size/ static_cast(totalSize) >= 0.5) { + rehash(); + } +} + +// Removes key. Leaves tombstone upon removal. +void remove(int key) { + int index = linearProbe(key, true); + if (index == notPresent) { + cout << "key not found" << endl; + } + cout << "Removal Successful, leaving tomb" << endl; + table[index].key = tomb; + size--; +} + +// Information about the adding process +void addInfo(int key) { + cout << "Initial table: "; + display(); + cout << endl; + cout << "hash of " << key << " is " << hashFxn(key) << " % " + << totalSize << " == " << fabs(hashFxn(key) % totalSize); + cout << endl; + add(key); + cout << "New table: "; + display(); +} + +// Information about removal process +void removalInfo(int key) { + cout << "Initial table: "; + display(); + cout << endl; + cout << "hash of " << key << " is " << hashFxn(key) + << " % " << totalSize << " == " << hashFxn(key) % totalSize; + cout << endl; + remove(key); + cout << "New table: "; + display(); +} + +// I/O +int main(void) { + int cmd, hash, key; + cout << "Enter the initial size of Hash Table. = "; + cin >> totalSize; + table = new Entry[totalSize]; + bool loop = true; + while (loop) { + system("pause"); + cout << endl; + cout << "PLEASE CHOOSE -" << endl; + cout << "1. Add key. (Numeric only)" << endl; + cout << "2. Remove key." << endl; + cout << "3. Find key." << endl; + cout << "4. Generate Hash. (Numeric only)" << endl; + cout << "5. Display Hash table." << endl; + cout << "6. Exit." << endl; + cin >> cmd; + switch (cmd) { + case 1: + cout << "Enter key to add = "; + cin >> key; + addInfo(key); + break; + case 2: + cout << "Enter key to remove = "; + cin >> key; + removalInfo(key); + break; + case 3: { + cout << "Enter key to search = "; + cin >> key; + Entry entry = table[linearProbe(key, true)]; + if (entry.key == notPresent) { + cout << "Key not present"; + } + break; + } + case 4: + cout << "Enter element to generate hash = "; + cin >> key; + cout << "Hash of " << key << " is = " << fabs(hashFxn(key)); + break; + case 5: + display(); + break; + default: + loop = false; + break; + delete[] table; + } + cout << endl; + } + return 0; +} diff --git a/hashing/quadratic_probing_hash_table.cpp b/hashing/quadratic_probing_hash_table.cpp new file mode 100644 index 000000000..44e2e3b9f --- /dev/null +++ b/hashing/quadratic_probing_hash_table.cpp @@ -0,0 +1,239 @@ +// Copyright 2019 + +#include +#include +#include +#include +#include + +using std::endl; +using std::cout; +using std::cin; +using std::string; + +// fwd declarations +struct Entry; +bool putProber(Entry entry, int key); +bool searchingProber(Entry entry, int key); +void add(int key); + +// globals +int notPresent; +struct Entry* table; +int totalSize; +int tomb = -1; +int size; +bool rehashing; + +// Node that holds key +struct Entry { + explicit Entry(int key = notPresent) : key(key) {} + int key; +}; + +// Hash a key +int hashFxn(int key) { + std::hash hash; + return hash(key); +} + +// Performs quadratic probing to resolve collisions +int quadraticProbe(int key, bool searching) { + int hash = static_cast(fabs(hashFxn(key))); + int i = 0; + Entry entry; + do { + int index = std::round(fabs((hash + + static_cast(std::round(std::pow(i, 2)))) % totalSize)); + entry = table[index]; + if (searching) { + if (entry.key == notPresent) { + return notPresent; + } + if (searchingProber(entry, key)) { + cout << "Found key!" << endl; + return index; + } + cout << "Found tombstone or equal hash, checking next" << endl; + i++; + } else { + if (putProber(entry, key)) { + if (!rehashing) cout << "Spot found!" << endl; + return index; + } + if (!rehashing) { + cout << "Spot taken, looking at next (next index = " << + std::round(fabs((hash + static_cast(std::round( + std::pow(i + 1, 2)))) % totalSize)) << endl; + } + i++; + } + if (i == totalSize * 100) { + cout << "Quadratic probe failed (infinite loop)" << endl; + return notPresent; + } + } while (entry.key != notPresent); + return notPresent; +} + +// Finds empty spot +bool putProber(Entry entry, int key) { + if (entry.key == notPresent || entry.key == tomb) { + return true; + } + return false; +} + +// Looks for a matching key +bool searchingProber(Entry entry, int key) { + if (entry.key == key) return true; + return false; +} + +// Helper +Entry find(int key) { + int index = quadraticProbe(key, true); + if (index == notPresent) return Entry(); + return table[index]; +} + +// Displays the table +void display() { + for (int i = 0; i < totalSize; i++) { + if (table[i].key == notPresent) { + cout << " Empty "; + } else if (table[i].key == tomb) { + cout << " Tomb "; + } else { + cout << " "; + cout << table[i].key; + cout << " "; + } + } + cout << endl; +} + +// Rehashes the table into a bigger table +void rehash() { + // Necessary so wall of add info isn't printed all at once + rehashing = true; + int oldSize = totalSize; + Entry* oldTable = table; + // Really this should use the next prime number greater than totalSize * 2 + table = new Entry[totalSize * 2]; + totalSize *= 2; + for (int i = 0; i < oldSize; i++) { + if (oldTable[i].key != -1 && oldTable[i].key != notPresent) { + size--; // Size stays the same (add increments size) + add(oldTable[i].key); + } + } + delete[] oldTable; + rehashing = false; + cout << "Table was rehashed, new size is: " << totalSize << endl; +} + +// Checks for load factor here +void add(int key) { + Entry * entry = new Entry(); + entry->key = key; + int index = quadraticProbe(key, false); + table[index] = *entry; + // Load factor greater than 0.5 causes resizing + if (++size/ static_cast(totalSize) >= 0.5) { + rehash(); + } +} + +// Removes key. Leaves tombstone upon removal. +void remove(int key) { + int index = quadraticProbe(key, true); + if (index == notPresent) { + cout << "key not found" << endl; + } + table[index].key = tomb; + cout << "Removal successful, leaving tombstone" << endl; + size--; +} + +// Information about the adding process +void addInfo(int key) { + cout << "Initial table: "; + display(); + cout << endl; + cout << "hash of " << key << " is " << hashFxn(key) << " % " + << totalSize << " == " << fabs(hashFxn(key) % totalSize); + cout << endl; + add(key); + cout << "New table: "; + display(); +} + +// Information about removal process +void removalInfo(int key) { + cout << "Initial table: "; + display(); + cout << endl; + cout << "hash of " << key << " is " << hashFxn(key) + << " % " << totalSize << " == " << hashFxn(key) % totalSize; + cout << endl; + remove(key); + cout << "New table: "; + display(); +} + +// I/O +int main(void) { + int cmd, hash, key; + cout << "Enter the initial size of Hash Table. = "; + cin >> totalSize; + table = new Entry[totalSize]; + bool loop = true; + while (loop) { + system("pause"); + cout << endl; + cout << "PLEASE CHOOSE -" << endl; + cout << "1. Add key. (Numeric only)" << endl; + cout << "2. Remove key." << endl; + cout << "3. Find key." << endl; + cout << "4. Generate Hash. (Numeric only)" << endl; + cout << "5. Display Hash table." << endl; + cout << "6. Exit." << endl; + cin >> cmd; + switch (cmd) { + case 1: + cout << "Enter key to add = "; + cin >> key; + addInfo(key); + break; + case 2: + cout << "Enter key to remove = "; + cin >> key; + removalInfo(key); + break; + case 3: { + cout << "Enter key to search = "; + cin >> key; + Entry entry = table[quadraticProbe(key, true)]; + if (entry.key == notPresent) { + cout << "Key not present"; + } + break; + } + case 4: + cout << "Enter element to generate hash = "; + cin >> key; + cout << "Hash of " << key << " is = " << fabs(hashFxn(key)); + break; + case 5: + display(); + break; + default: + loop = false; + break; + delete[] table; + } + cout << endl; + } + return 0; +} From 917c7109e54d47405f2e39b92142920d482e50c6 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 21 Dec 2019 08:17:30 +0000 Subject: [PATCH 151/277] updating DIRECTORY.md --- DIRECTORY.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 9caf75034..b580a2ad9 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -70,6 +70,9 @@ ## Hashing * [Chaining](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/Chaining.cpp) + * [Double Hash Hash Table](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/double_hash_hash_table.cpp) + * [Linear Probing Hash Table](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/linear_probing_hash_table.cpp) + * [Quadratic Probing Hash Table](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/quadratic_probing_hash_table.cpp) ## Math * [Factorial](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/factorial.cpp) From 19e6063705316bd5a410f3cd5cc42af8f44302f7 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Sun, 22 Dec 2019 15:17:51 +0100 Subject: [PATCH 152/277] WIP: Create build_directory_md_new.yml (#688) * Create build_directory_md_new.yml Try putting the Python code inside the Actions .yml file * Update build_directory_md_new.yml * with open("DIRECTORY.md", "w") as out_file: * out_file.write(build_directory_md(".")) * updating DIRECTORY.md * Update build_directory_md_new.yml * updating DIRECTORY.md * Delete build_directory_md.yml * Delete build_directory_md.py * Rename build_directory_md_new.yml to build_directory_md.yml * Update and rename build_directory_md.yml to update_directory_md.yml * for filename in sorted(filenames): * for filepath in sorted(good_filepaths(), key=str.lower): * updating DIRECTORY.md * Update update_directory_md.yml --- .github/scripts/build_directory_md.py | 44 -------------- .github/workflows/build_directory_md.yml | 21 ------- .github/workflows/update_directory_md.yml | 72 +++++++++++++++++++++++ DIRECTORY.md | 48 +++++++-------- 4 files changed, 96 insertions(+), 89 deletions(-) delete mode 100755 .github/scripts/build_directory_md.py delete mode 100644 .github/workflows/build_directory_md.yml create mode 100644 .github/workflows/update_directory_md.yml diff --git a/.github/scripts/build_directory_md.py b/.github/scripts/build_directory_md.py deleted file mode 100755 index 8c5c00235..000000000 --- a/.github/scripts/build_directory_md.py +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/env python3 - -import os -from typing import Iterator - -URL_BASE = "https://github.com/TheAlgorithms/C-Plus-Plus/blob/master" - - -def good_filepaths(top_dir: str = ".") -> Iterator[str]: - cpp_exts = tuple(".c .c++ .cc .cpp .cu .cuh .cxx .h .h++ .hh .hpp .hxx".split()) - for dirpath, dirnames, filenames in os.walk(top_dir): - dirnames[:] = [d for d in dirnames if d[0] not in "._"] - for filename in filenames: - if os.path.splitext(filename)[1].lower() in cpp_exts: - yield os.path.join(dirpath, filename).lstrip("./") - - -def md_prefix(i): - return f"{i * ' '}*" if i else "\n##" - - -def print_path(old_path: str, new_path: str) -> str: - old_parts = old_path.split(os.sep) - for i, new_part in enumerate(new_path.split(os.sep)): - if i + 1 > len(old_parts) or old_parts[i] != new_part: - if new_part: - print(f"{md_prefix(i)} {new_part.replace('_', ' ').title()}") - return new_path - - -def print_directory_md(top_dir: str = ".") -> None: - old_path = "" - for filepath in sorted(good_filepaths()): - filepath, filename = os.path.split(filepath) - if filepath != old_path: - old_path = print_path(old_path, filepath) - indent = (filepath.count(os.sep) + 1) if filepath else 0 - url = "/".join((URL_BASE, filepath, filename)).replace(" ", "%20") - filename = os.path.splitext(filename.replace("_", " ").title())[0] - print(f"{md_prefix(indent)} [{filename}]({url})") - - -if __name__ == "__main__": - print_directory_md(".") diff --git a/.github/workflows/build_directory_md.yml b/.github/workflows/build_directory_md.yml deleted file mode 100644 index 4a5781f08..000000000 --- a/.github/workflows/build_directory_md.yml +++ /dev/null @@ -1,21 +0,0 @@ -# The objective of this GitHub Action is to update the DIRECTORY.md file (if needed) -# when doing a git push -name: directory_writer -on: [push] -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v1 - - uses: actions/setup-python@v1 - with: - python-version: 3.x - - name: Update DIRECTORY.md - run: | - .github/scripts/build_directory_md.py 2>&1 | tee DIRECTORY.md - git config --global user.name github-actions - git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' - git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - git add DIRECTORY.md - git commit -am "updating DIRECTORY.md" || true - git push --force origin HEAD:$GITHUB_REF || true diff --git a/.github/workflows/update_directory_md.yml b/.github/workflows/update_directory_md.yml new file mode 100644 index 000000000..e8a7336e6 --- /dev/null +++ b/.github/workflows/update_directory_md.yml @@ -0,0 +1,72 @@ +# This GitHub Action updates the DIRECTORY.md file (if needed) when doing a git push +name: update_directory_md +on: [push] +jobs: + update_directory_md: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + - shell: python + run: import sys ; print("Python {}.{}.{}".format(*sys.version_info)) + - name: Upgrade to Python 3.8 + run: sudo update-alternatives --install /usr/bin/python python ${pythonLocation}/bin/python3.8 10 + - shell: python + run: import sys ; print("Python {}.{}.{}".format(*sys.version_info)) + - shell: python + run: | + import os + from typing import Iterator + + URL_BASE = "https://github.com/TheAlgorithms/C-Plus-Plus/blob/master" + g_output = [] + + + def good_filepaths(top_dir: str = ".") -> Iterator[str]: + cpp_exts = tuple(".c .c++ .cc .cpp .cu .cuh .cxx .h .h++ .hh .hpp .hxx".split()) + for dirpath, dirnames, filenames in os.walk(top_dir): + dirnames[:] = [d for d in dirnames if d[0] not in "._"] + for filename in filenames: + if os.path.splitext(filename)[1].lower() in cpp_exts: + yield os.path.join(dirpath, filename).lstrip("./") + + + def md_prefix(i): + return f"{i * ' '}*" if i else "\n##" + + + def print_path(old_path: str, new_path: str) -> str: + global g_output + old_parts = old_path.split(os.sep) + for i, new_part in enumerate(new_path.split(os.sep)): + if i + 1 > len(old_parts) or old_parts[i] != new_part: + if new_part: + g_output.append(f"{md_prefix(i)} {new_part.replace('_', ' ').title()}") + return new_path + + + def build_directory_md(top_dir: str = ".") -> str: + global g_output + old_path = "" + for filepath in sorted(good_filepaths(), key=str.lower): + filepath, filename = os.path.split(filepath) + if filepath != old_path: + old_path = print_path(old_path, filepath) + indent = (filepath.count(os.sep) + 1) if filepath else 0 + url = "/".join((URL_BASE, filepath, filename)).replace(" ", "%20") + filename = os.path.splitext(filename.replace("_", " ").title())[0] + g_output.append(f"{md_prefix(indent)} [{filename}]({url})") + return "\n".join(g_output) + + + with open("DIRECTORY.md", "w") as out_file: + out_file.write(build_directory_md(".") + "\n") + + - name: Update DIRECTORY.md + run: | + cat DIRECTORY.md + git config --global user.name github-actions + git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' + git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY + git add DIRECTORY.md + git commit -am "updating DIRECTORY.md" || true + git push --force origin HEAD:$GITHUB_REF || true diff --git a/DIRECTORY.md b/DIRECTORY.md index b580a2ad9..476d85137 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -9,18 +9,20 @@ ## Computer Oriented Statistical Methods * [Bisection Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/Bisection_method.CPP) + * [False-Position](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/false-position.CPP) * [Gaussian Elimination](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/Gaussian_elimination.cpp) * [Newton Raphson](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/Newton_Raphson.CPP) * [Secant Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/Secant_method.CPP) - * [False-Position](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/false-position.CPP) * [Successive Approximation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/successive_approximation.CPP) ## Data Structure * [Avltree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/AVLtree.cpp) * [Binary Search Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Binary%20Search%20Tree.cpp) * [Binaryheap](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Binaryheap.cpp) + * [Circular Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/circular_Queue_using_Linked_List.cpp) * [Doubly Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Doubly%20Linked%20List.cpp) * [Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Linked%20List.cpp) + * [Linkedlist Implentation Usingarray](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/linkedList_implentation_usingArray.cpp) * [List Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/List%20Array.cpp) * [Morrisinorder](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/MorrisInorder.cpp) * [Queue Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Queue%20Using%20Array.cpp) @@ -28,12 +30,11 @@ * [Stack Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Stack%20Using%20Array.cpp) * [Stack Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Stack%20Using%20Linked%20List.cpp) * [Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Tree.cpp) - * [Circular Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/circular_Queue_using_Linked_List.cpp) - * [Linkedlist Implentation Usingarray](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/linkedList_implentation_usingArray.cpp) * [Trie Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/trie_tree.cpp) ## Dynamic Programming * [0-1 Knapsack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/0-1%20Knapsack.cpp) + * [Armstrong Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/armstrong_number.cpp) * [Bellman-Ford](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Bellman-Ford.cpp) * [Catalan-Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Catalan-Numbers.cpp) * [Coin-Change](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Coin-Change.cpp) @@ -43,30 +44,29 @@ * [Fibonacci Bottom Up](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Fibonacci_Bottom_Up.cpp) * [Fibonacci Top Down](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Fibonacci_Top_Down.cpp) * [Floyd-Warshall](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Floyd-Warshall.cpp) + * [Kadane](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/kadane.cpp) * [Longest Common Subsequence](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Longest%20Common%20Subsequence.cpp) * [Longest Increasing Subsequence (Nlogn)](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Longest%20Increasing%20Subsequence%20(nlogn).cpp) * [Longest Increasing Subsequence](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Longest%20Increasing%20Subsequence.cpp) - * [Matrix-Chain-Multiplication](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Matrix-Chain-Multiplication.cpp) - * [Armstrong Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/armstrong_number.cpp) - * [Kadane](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/kadane.cpp) * [Longest Common String](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/longest_common_string.cpp) + * [Matrix-Chain-Multiplication](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Matrix-Chain-Multiplication.cpp) ## Graph * [Bfs](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/BFS.cpp) * [Dfs](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/DFS.cpp) * [Dfs With Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/DFS_with_stack.cc) * [Dijkstra](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/Dijkstra.cpp) - * [Kruskal](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/Kruskal.cpp) - * [Topological-Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/Topological-Sort.cpp) * [Kosaraju](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/kosaraju.cpp) + * [Kruskal](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/Kruskal.cpp) * [Lca](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/lca.cpp) + * [Topological-Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/Topological-Sort.cpp) ## Greedy Algorithms * [Dijkstra](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/Dijkstra.cpp) + * [Huffman](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/huffman.cpp) * [Knapsack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/Knapsack.cpp) * [Kruskals Minimum Spanning Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/Kruskals%20Minimum%20Spanning%20Tree.cpp) * [Prims Minimum Spanning Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/Prims%20Minimum%20Spanning%20Tree.cpp) - * [Huffman](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/huffman.cpp) ## Hashing * [Chaining](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/Chaining.cpp) @@ -90,43 +90,43 @@ * [Circular Queue Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Circular%20Queue%20Using%20Array.cpp) * [Intersection Of 2 Arrays](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Intersection_of_2_arrays.cpp) * [Reverse A Linked List Using Recusion](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Reverse%20a%20Linked%20List%20using%20Recusion.cpp) - * [Union Of 2 Arrays](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Union_of_2_arrays.cpp) * [Selectionsortlinkedlist](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/selectionSortLinkedList.cpp) + * [Union Of 2 Arrays](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Union_of_2_arrays.cpp) ## Others * [Buzz Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Buzz_number.cpp) * [Decimal To Binary](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Decimal%20To%20Binary.cpp) * [Decimal To Hexadecimal ](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Decimal%20To%20Hexadecimal%20.cpp) * [Decimal To Roman Numeral](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Decimal%20to%20Roman%20Numeral.cpp) + * [Fibonacci](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/fibonacci.cpp) * [Gcd Of N Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/GCD_of_n_numbers.cpp) + * [Happy Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/happy_number.cpp) + * [Matrix Exponentiation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/matrix_exponentiation.cpp) * [Palindromeofnumber](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Palindromeofnumber.cpp) * [Paranthesis Matching](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Paranthesis%20Matching.cpp) + * [Pascal Triangle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/pascal_triangle.cpp) * [Primality Test](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Primality%20Test.cpp) + * [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/sieve_of_Eratosthenes.cpp) + * [Smallest-Circle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/smallest-circle.cpp) * [Sparse Matrix](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Sparse%20matrix.cpp) + * [Spiral Print](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/spiral_print.cpp) * [Strassen Matrix Multiplication](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Strassen%20Matrix%20Multiplication.cpp) * [String Fibonacci](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/String%20Fibonacci.cpp) * [Tower Of Hanoi](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Tower%20of%20Hanoi.cpp) - * [Fibonacci](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/fibonacci.cpp) - * [Happy Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/happy_number.cpp) - * [Matrix Exponentiation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/matrix_exponentiation.cpp) - * [Pascal Triangle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/pascal_triangle.cpp) - * [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/sieve_of_Eratosthenes.cpp) - * [Smallest-Circle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/smallest-circle.cpp) - * [Spiral Print](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/spiral_print.cpp) * [Vector Important Functions](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/vector_important_functions.cpp) ## Range Queries + * [Bit](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/bit.cpp) * [Fenwicktree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/FenwickTree.cpp) * [Mo](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/MO.cpp) - * [Bit](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/bit.cpp) * [Segtree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/segTree.cpp) ## Search * [Binary Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/Binary%20Search.cpp) - * [Interpolation Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/Interpolation%20Search.cpp) - * [Linear Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/Linear%20Search.cpp) * [Exponential Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/exponential_search.cpp) * [Hash Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/hash_search.cpp) + * [Interpolation Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/Interpolation%20Search.cpp) + * [Linear Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/Linear%20Search.cpp) * [Median Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/median_search.cpp) * [Searching](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/searching.cpp) * [Ternary Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/ternary_search.cpp) @@ -135,9 +135,12 @@ * [Beadsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/BeadSort.cpp) * [Bitonicsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/BitonicSort.cpp) * [Bubble Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Bubble%20Sort.cpp) + * [Bucketsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/bucketSort.cpp) * [Cocktailselectionsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/CocktailSelectionSort.cpp) - * [Countingsortstring](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/CountingSortString.cpp) + * [Combsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/combsort.cpp) * [Counting Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Counting_Sort.cpp) + * [Countingsortstring](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/CountingSortString.cpp) + * [Heap Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/heap_sort.cpp) * [Insertion Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Insertion%20Sort.cpp) * [Merge Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Merge%20Sort.cpp) * [Numericstringsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/NumericStringSort.cpp) @@ -148,9 +151,6 @@ * [Shell Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Shell%20Sort.cpp) * [Slow Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Slow%20Sort.cpp) * [Tim Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Tim%20Sort.cpp) - * [Bucketsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/bucketSort.cpp) - * [Combsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/combsort.cpp) - * [Heap Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/heap_sort.cpp) ## Strings * [Knuth Morris Pratt](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/strings/knuth_morris_pratt.cpp) From 0e492fec2f6076405d8c9b56d051936563ca9b8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8B=8F=E6=B7=9E=E4=B8=B0?= <50102735+Arctic2333@users.noreply.github.com> Date: Sun, 22 Dec 2019 22:50:33 +0800 Subject: [PATCH 153/277] #include --> (#687) * #include --> * CPP --> cpp * Delete false-position.CPP * delete tab * delete CPP * Delete false-position.CPP * Delete false-position.cpp * create cpp * system("clear"); --- .../false-position.CPP | 49 ------------------- .../false-position.cpp | 35 +++++++++++++ 2 files changed, 35 insertions(+), 49 deletions(-) delete mode 100644 computer_oriented_statistical_methods/false-position.CPP create mode 100644 computer_oriented_statistical_methods/false-position.cpp diff --git a/computer_oriented_statistical_methods/false-position.CPP b/computer_oriented_statistical_methods/false-position.CPP deleted file mode 100644 index 847a74df1..000000000 --- a/computer_oriented_statistical_methods/false-position.CPP +++ /dev/null @@ -1,49 +0,0 @@ -#include -#include -#include - -float eq(float i) -{ - return (pow(i, 3) - (4 * i) - 9); // origial equation -} - -void main() -{ - float a, b, z, c, m, n; - clrscr(); - for (int i = 0; i < 100; i++) - { - z = eq(i); - if (z >= 0) - { - b = i; - a = --i; - goto START; - } - } - -START: - - cout << "\nFirst initial: " << a; - cout << "\nSecond initial: " << b; - for (i = 0; i < 100; i++) - { - - float h, d; - m = eq(a); - n = eq(b); - - c = ((a * n) - (b * m)) / (n - m); - a = c; - - z = eq(c); - if (z > 0 && z < 0.09) // stoping criteria - { - goto END; - } - } - -END: - cout << "\n\nRoot: " << c; - getch(); -} diff --git a/computer_oriented_statistical_methods/false-position.cpp b/computer_oriented_statistical_methods/false-position.cpp new file mode 100644 index 000000000..5e15e92cc --- /dev/null +++ b/computer_oriented_statistical_methods/false-position.cpp @@ -0,0 +1,35 @@ +#include +#include +#include +float eq(float i) { + return (pow(i, 3) - (4 * i) - 9); // origial equation +} +int main() { + float a, b, z, c, m, n; + system("clear"); + for (int i = 0; i < 100; i++) { + z = eq(i); + if (z >= 0) { + b = i; + a = --i; + goto START; + } + } + START: + std::cout << "\nFirst initial: " << a; + std::cout << "\nSecond initial: " << b; + for (int i = 0; i < 100; i++) { + float h, d; + m = eq(a); + n = eq(b); + c = ((a * n) - (b * m)) / (n - m); + a = c; + z = eq(c); + if (z > 0 && z < 0.09) { // stoping criteria + goto END; + } + } + END: + std::cout << "\n\nRoot: " << c; + system("pause"); +} From 79d50738f226a33403aa99fcab4e01a3ce3fbc1e Mon Sep 17 00:00:00 2001 From: Bahadir Altun Date: Thu, 26 Dec 2019 11:30:30 +0300 Subject: [PATCH 154/277] Add fast power (#691) * Add fast power Computes a^b in O(logN) time. * Change long long to int64_t * Update fast_power.cpp * Update fast_power.cpp * Add tests * Update sample tests * Update rand function * Remove extra-spaces --- math/fast_power.cpp | 79 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 math/fast_power.cpp diff --git a/math/fast_power.cpp b/math/fast_power.cpp new file mode 100644 index 000000000..4f6e02081 --- /dev/null +++ b/math/fast_power.cpp @@ -0,0 +1,79 @@ +#include +#include +#include +#include +#include +#include + +/* + Program that computes a^b in O(logN) time. + It is based on formula that: + case1) if b is even: a^b = a^(b/2) * a^(b/2) = (a^(b/2))ˆ2 + case2) if b is odd: a^b = a^((b-1)/2) * a^((b-1)/2) * a = (a^((b-1)/2))^2 * a + We can compute a^b recursively using above algorithm. +*/ + +double fast_power_recursive(int64_t a, int64_t b) { + // negative power. a^b = 1 / (a^-b) + if (b < 0) + return 1.0 / fast_power_recursive(a, -b); + + if (b == 0) return 1; + int64_t bottom = fast_power_recursive(a, b >> 1); + // Since it is integer division b/2 = (b-1)/2 where b is odd. + // Therefore, case2 is easily solved by integer division. + + int64_t result; + if ((b & 1) == 0) // case1 + result = bottom * bottom; + else // case2 + result = bottom * bottom * a; + return result; +} + +/* + Same algorithm with little different formula. + It still calculates in O(logN) +*/ +double fast_power_linear(int64_t a, int64_t b) { + // negative power. a^b = 1 / (a^-b) + if (b < 0) + return 1.0 / fast_power_linear(a, -b); + + double result = 1; + while (b) { + if (b & 1) result = result * a; + a = a * a; + b = b >> 1; + } + return result; +} + +int main() { + std::srand(time(NULL)); + std::ios_base::sync_with_stdio(false); + + std::cout << "Testing..." << std::endl; + for (int i = 0; i < 20; i++) { + unsigned int *rand1, *rand2; + int a = rand_r(rand1) % 20 - 10; + int b = rand_r(rand2) % 20 - 10; + std::cout << std::endl << "Calculating " << a << "^" << b << std::endl; + assert(fast_power_recursive(a, b) == std::pow(a, b)); + assert(fast_power_linear(a, b) == std::pow(a, b)); + + std::cout << "------ " << a << "^" << b << " = "<< + fast_power_recursive(a, b) << std::endl; + } + + int64_t a, b; + std::cin >> a >> b; + + std::cout << a << "^" << b << " = "<< + fast_power_recursive(a, b) << std::endl; + + std::cout << a << "^" << b << " = "<< + fast_power_linear(a, b) << std::endl; + + return 0; +} From 3c43f7c0e6bd0013181f51abf25b1cae33b93def Mon Sep 17 00:00:00 2001 From: Himani Negi Date: Fri, 27 Dec 2019 16:57:24 +0530 Subject: [PATCH 155/277] Add backtracking/nqueen_print_all_solutions.cpp (#622) * Add files via upload * Rename Backtracking/NQueen-PrintAllSolutions.cpp to backtracking/nqueen_print_all_solutions.cpp * clang-format -i -style="{IndentWidth: 4}" *.cpp * endl --> std::endl Co-authored-by: Christian Clauss --- backtracking/nqueen_print_all_solutions.cpp | 50 +++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 backtracking/nqueen_print_all_solutions.cpp diff --git a/backtracking/nqueen_print_all_solutions.cpp b/backtracking/nqueen_print_all_solutions.cpp new file mode 100644 index 000000000..e6736da1e --- /dev/null +++ b/backtracking/nqueen_print_all_solutions.cpp @@ -0,0 +1,50 @@ +#include +#define n 4 + +void PrintSol(int Board[n][n]) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + std::cout << Board[i][j] << " "; + } + std::cout << std::endl; + } + std::cout << std::endl; +} + +bool CanIMove(int Board[n][n], int row, int col) { + /// check in the row + for (int i = 0; i < col; i++) { + if (Board[row][i] == 1) + return false; + } + /// check the first diagonal + for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) { + if (Board[i][j] == 1) + return false; + } + /// check the second diagonal + for (int i = row, j = col; i <= n - 1 && j >= 0; i++, j--) { + if (Board[i][j] == 1) + return false; + } + return true; +} + +void NQueenSol(int Board[n][n], int col) { + if (col >= n) { + PrintSol(Board); + return; + } + for (int i = 0; i < n; i++) { + if (CanIMove(Board, i, col)) { + Board[i][col] = 1; + NQueenSol(Board, col + 1); + Board[i][col] = 0; + } + } +} + +int main() { + int Board[n][n] = {0}; + NQueenSol(Board, 0); +} From d099d8ee6048f473f48b0c211eeea2338bc7e70e Mon Sep 17 00:00:00 2001 From: cole Date: Sat, 28 Dec 2019 01:10:53 -0500 Subject: [PATCH 156/277] feat: add euclidean algorithm implementation of gcd --- math/greatest_common_divisor_euclidean.cpp | 48 ++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 math/greatest_common_divisor_euclidean.cpp diff --git a/math/greatest_common_divisor_euclidean.cpp b/math/greatest_common_divisor_euclidean.cpp new file mode 100644 index 000000000..c4812e45b --- /dev/null +++ b/math/greatest_common_divisor_euclidean.cpp @@ -0,0 +1,48 @@ +#include +#include +#include + +// will find the greatest common denominator of two ints integers +// Euclidean algorithm can be found here +// https://en.wikipedia.org/wiki/Euclidean_algorithm +int gcd(int num1, int num2) { + if (num1 <= 0 | num2 <= 0) { + throw std::domain_error("Euclidean algorithm domain is for ints > 0"); + } + + if (num1 == num2) { + return num1; + } + + int base_num = 0; + int previous_remainder = 1; + + if (num1 > num2) { + base_num = num1; + previous_remainder = num2; + } else { + base_num = num2; + previous_remainder = num1; + } + + while ((base_num % previous_remainder) != 0) { + int old_base = base_num; + base_num = previous_remainder; + previous_remainder = old_base % previous_remainder; + } + + return previous_remainder; +} + +int main() { + std::cout << "gcd of 120,7 is " << (gcd(120, 7)) << std::endl; + try { + std::cout << "gcd of -120,10 is " << gcd(-120, 10) << std::endl; + } catch (const std::domain_error &e) { + std::cout << "Error handling was successful" << std::endl; + } + std::cout << "gcd of 312,221 is " << (gcd(312, 221)) << std::endl; + std::cout << "gcd of 289,204 is " << (gcd(289, 204)) << std::endl; + + return 0; +} From 98143d9e3676d25b02f3af9a1d646f54a1d6d757 Mon Sep 17 00:00:00 2001 From: Eric Curtin Date: Sat, 4 Jan 2020 08:33:56 +0000 Subject: [PATCH 157/277] variable x is unused (#698) * variable x is unused * Use std::endl and a blank line between functions Co-authored-by: Christian Clauss --- sorting/heap_sort.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/sorting/heap_sort.cpp b/sorting/heap_sort.cpp index c72afc103..572f5b5ce 100644 --- a/sorting/heap_sort.cpp +++ b/sorting/heap_sort.cpp @@ -17,6 +17,7 @@ void max_heapify(int *a, int i, int n) { a[j / 2] = temp; return; } + void heapsort(int *a, int n) { int i, temp; for (i = n; i >= 2; i--) { @@ -26,26 +27,28 @@ void heapsort(int *a, int n) { max_heapify(a, 1, i - 1); } } + void build_maxheap(int *a, int n) { int i; for (i = n / 2; i >= 1; i--) { max_heapify(a, i, n); } } + int main() { - int n, i, x; + int n, i; std::cout << "Enter number of elements of array\n"; std::cin >> n; int a[20]; for (i = 1; i <= n; i++) { - std::cout << "Enter Element " << (i) << endl; + std::cout << "Enter Element " << (i) << std::endl; std::cin >> a[i]; } build_maxheap(a, n); heapsort(a, n); std::cout << "Sorted Output\n"; for (i = 1; i <= n; i++) { - std::cout << a[i] << endl; + std::cout << a[i] << std::endl; } std::getchar(); } From 59d5dcca1dcb7b83a8e461e109e2e8ddfbef6eeb Mon Sep 17 00:00:00 2001 From: Eric Curtin Date: Mon, 6 Jan 2020 11:23:29 +0000 Subject: [PATCH 158/277] heapsort implementation started at index 1 It is wasteful of the first element of the array, so start at 0. Also std:swap was re-implemented just use swap available in C++ library instead. --- sorting/heap_sort.cpp | 54 +++++++++++++++++++++---------------------- 1 file changed, 26 insertions(+), 28 deletions(-) diff --git a/sorting/heap_sort.cpp b/sorting/heap_sort.cpp index 572f5b5ce..9948bb821 100644 --- a/sorting/heap_sort.cpp +++ b/sorting/heap_sort.cpp @@ -1,54 +1,52 @@ +#include #include -void max_heapify(int *a, int i, int n) { - int j, temp; - temp = a[i]; - j = 2 * i; - while (j <= n) { - if (j < n && a[j + 1] > a[j]) - j = j + 1; - if (temp > a[j]) { - break; - } else if (temp <= a[j]) { - a[j / 2] = a[j]; - j = 2 * j; - } +void heapify(int *a, int i, int n) { + int largest = i; + const int l = 2 * i + 1; + const int r = 2 * i + 2; + + if (l < n && a[l] > a[largest]) + largest = l; + + if (r < n && a[r] > a[largest]) + largest = r; + + if (largest != i) { + std::swap(a[i], a[largest]); + heapify(a, n, largest); } - a[j / 2] = temp; - return; } void heapsort(int *a, int n) { - int i, temp; - for (i = n; i >= 2; i--) { - temp = a[i]; - a[i] = a[1]; - a[1] = temp; - max_heapify(a, 1, i - 1); + for (int i = n - 1; i >= 0; --i) { + std::swap(a[0], a[i]); + heapify(a, 0, i); } } void build_maxheap(int *a, int n) { - int i; - for (i = n / 2; i >= 1; i--) { - max_heapify(a, i, n); + for (int i = n / 2 - 1; i >= 0; --i) { + heapify(a, i, n); } } int main() { - int n, i; + int n; std::cout << "Enter number of elements of array\n"; std::cin >> n; int a[20]; - for (i = 1; i <= n; i++) { - std::cout << "Enter Element " << (i) << std::endl; + for (int i = 0; i < n; ++i) { + std::cout << "Enter Element " << i << std::endl; std::cin >> a[i]; } + build_maxheap(a, n); heapsort(a, n); std::cout << "Sorted Output\n"; - for (i = 1; i <= n; i++) { + for (int i = 0; i < n; ++i) { std::cout << a[i] << std::endl; } + std::getchar(); } From da6c0d8791b0a527a6f315fd70dc31cf1ff216e1 Mon Sep 17 00:00:00 2001 From: danghai Date: Tue, 7 Jan 2020 15:57:31 -0800 Subject: [PATCH 159/277] Add simple circular linkedlist --- data_structure/cll/cll.cpp | 127 ++++++++++++++++++++++++++++++++ data_structure/cll/cll.h | 45 +++++++++++ data_structure/cll/main_cll.cpp | 44 +++++++++++ data_structure/cll/makefile | 11 +++ 4 files changed, 227 insertions(+) create mode 100644 data_structure/cll/cll.cpp create mode 100644 data_structure/cll/cll.h create mode 100644 data_structure/cll/main_cll.cpp create mode 100644 data_structure/cll/makefile diff --git a/data_structure/cll/cll.cpp b/data_structure/cll/cll.cpp new file mode 100644 index 000000000..efc068f3c --- /dev/null +++ b/data_structure/cll/cll.cpp @@ -0,0 +1,127 @@ +/* + A simple class for Cicular Linear Linked List +*/ +#include "cll.h" +using namespace std; + +/* Constructor */ +cll::cll() +{ + head = NULL; + total = 0; +} + +cll::~cll() +{ + /* Desstructure, no need to fill */ +} + +/* Display a list. and total element */ +void cll::display() +{ + if (head == NULL) + cout << "List is empty !" << endl; + else + { + cout << "CLL list: "; + node *current = head; + for (int i = 0; i < total; i++) + { + cout << current->data << " -> "; + current = current ->next; + } + cout << head->data << endl; + cout << "Total element: "<< total <data = new_data; + newNode->next = NULL; + if(head==NULL) { + head = newNode; + head -> next = head; + } else { + node *current = head; + while (current -> next != head) { + current = current->next; + } + newNode->next = head; + current->next = newNode; + head = newNode; + } + total++; +} + +/* List insert a new value at head in list */ +void cll::insert_tail(int new_data) +{ + node *newNode; + newNode = new node; + newNode->data = new_data; + newNode->next = NULL; + if(head==NULL) { + head = newNode; + head -> next = head; + } else { + node *current = head; + while (current -> next != head) { + current = current->next; + } + current->next = newNode; + newNode->next = head; + } + total++; +} + +/* Get total element in list */ +int cll::get_size() +{ + return total; +} + + +/* Return true if the requested item (sent in as an argument) +is in the list, otherwise return false */ +bool cll::find_item(int item_to_find) +{ + if (head == NULL) { + cout << "List is empty !" << endl; + return false; + } else { + node *current = head; + while (current -> next != head) { + if (current->data == item_to_find) + return true; + current = current->next; + } + return false; + } +} + +/* Overloading method*/ +int cll::operator*() +{ + return head->data; +} + +/* Overload the pre-increment operator. + The iterator is advanced to the next node. */ +void cll::operator++() +{ + if (head == NULL) { + cout << "List is empty !" << endl; + } else { + node *current = head; + while (current -> next != head) { + current = current -> next; + } + current->next = head -> next; + head = head -> next; + } + total--; +} diff --git a/data_structure/cll/cll.h b/data_structure/cll/cll.h new file mode 100644 index 000000000..ae71dcd01 --- /dev/null +++ b/data_structure/cll/cll.h @@ -0,0 +1,45 @@ +/* + * Simple data structure CLL (Cicular Linear Linked List) + * */ +#include +#include +#include +#include + +#ifndef CLL_H +#define CLL_H +/*The data structure is a linear linked list of integers */ +struct node +{ + int data; + node * next; +}; + +class cll +{ + public: + cll(); /* Construct without parameter */ + ~cll(); + void display(); /* Show the list */ + + /****************************************************** + * Useful method for list + *******************************************************/ + void insert_front(int new_data); /* Insert a new value at head */ + void insert_tail(int new_data); /* Insert a new value at tail */ + int get_size(); /* Get total element in list */ + bool find_item(int item_to_find); /* Find an item in list */ + + /****************************************************** + * Overloading method for list + *******************************************************/ + int operator*(); /* Returns the info contained in head */ + /* Overload the pre-increment operator. + The iterator is advanced to the next node. */ + void operator++(); + + protected: + node * head; + int total; /* Total element in a list */ +}; +#endif diff --git a/data_structure/cll/main_cll.cpp b/data_structure/cll/main_cll.cpp new file mode 100644 index 000000000..15388b822 --- /dev/null +++ b/data_structure/cll/main_cll.cpp @@ -0,0 +1,44 @@ +#include "cll.h" +using namespace std; + +int main() +{ + /* Test CLL */ + cout << "----------- Test construct -----------" << endl; + cll list1; + list1.display(); + cout << "----------- Test insert front -----------" << endl; + list1.insert_front(5); + cout << "After insert 5 at front: "< Date: Wed, 8 Jan 2020 15:55:24 +0100 Subject: [PATCH 160/277] shell: bash -c "$RUNNER_TOOL_CACHE/Python/3.8.0/x64/python {0}" --- .github/workflows/update_directory_md.yml | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/.github/workflows/update_directory_md.yml b/.github/workflows/update_directory_md.yml index e8a7336e6..d0f31884e 100644 --- a/.github/workflows/update_directory_md.yml +++ b/.github/workflows/update_directory_md.yml @@ -8,11 +8,14 @@ jobs: - uses: actions/checkout@v1 - shell: python run: import sys ; print("Python {}.{}.{}".format(*sys.version_info)) - - name: Upgrade to Python 3.8 - run: sudo update-alternatives --install /usr/bin/python python ${pythonLocation}/bin/python3.8 10 - - shell: python + - # name: Upgrade to Python 3.8 + # run: sudo update-alternatives --install /usr/bin/python python ${pythonLocation}/bin/python3.8 10 + # shell: bash -c "$RUNNER_TOOL_CACHE/Python/3.8.0/x64/python {0}" + - shell: bash -c "$RUNNER_TOOL_CACHE/Python/3.8.0/x64/python {0}" run: import sys ; print("Python {}.{}.{}".format(*sys.version_info)) - shell: python + run: import sys ; print("Python {}.{}.{}".format(*sys.version_info)) + - shell: bash -c "$RUNNER_TOOL_CACHE/Python/3.8.0/x64/python {0}" run: | import os from typing import Iterator From 8d35f02fa4cdeff10d4c3d0e4012fed962bd7e9d Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 8 Jan 2020 17:46:38 +0100 Subject: [PATCH 161/277] Update update_directory_md.yml --- .github/workflows/update_directory_md.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/update_directory_md.yml b/.github/workflows/update_directory_md.yml index d0f31884e..07b670177 100644 --- a/.github/workflows/update_directory_md.yml +++ b/.github/workflows/update_directory_md.yml @@ -8,9 +8,9 @@ jobs: - uses: actions/checkout@v1 - shell: python run: import sys ; print("Python {}.{}.{}".format(*sys.version_info)) - - # name: Upgrade to Python 3.8 - # run: sudo update-alternatives --install /usr/bin/python python ${pythonLocation}/bin/python3.8 10 - # shell: bash -c "$RUNNER_TOOL_CACHE/Python/3.8.0/x64/python {0}" + #- name: Upgrade to Python 3.8 + # run: sudo update-alternatives --install /usr/bin/python python ${pythonLocation}/bin/python3.8 10 + # shell: bash -c "$RUNNER_TOOL_CACHE/Python/3.8.0/x64/python {0}" - shell: bash -c "$RUNNER_TOOL_CACHE/Python/3.8.0/x64/python {0}" run: import sys ; print("Python {}.{}.{}".format(*sys.version_info)) - shell: python From 339a4e57b79b91d4525950efdfdb6c08475ac667 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Wed, 8 Jan 2020 16:46:57 +0000 Subject: [PATCH 162/277] updating DIRECTORY.md --- DIRECTORY.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index 476d85137..acf8c55f4 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -4,12 +4,13 @@ * [Knight Tour](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/knight_tour.cpp) * [Minimax](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/minimax.cpp) * [N Queens](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/n_queens.cpp) + * [Nqueen Print All Solutions](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/nqueen_print_all_solutions.cpp) * [Rat Maze](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/rat_maze.cpp) * [Sudoku Solve](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/sudoku_solve.cpp) ## Computer Oriented Statistical Methods * [Bisection Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/Bisection_method.CPP) - * [False-Position](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/false-position.CPP) + * [False-Position](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/false-position.cpp) * [Gaussian Elimination](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/Gaussian_elimination.cpp) * [Newton Raphson](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/Newton_Raphson.CPP) * [Secant Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/Secant_method.CPP) @@ -20,6 +21,10 @@ * [Binary Search Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Binary%20Search%20Tree.cpp) * [Binaryheap](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Binaryheap.cpp) * [Circular Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/circular_Queue_using_Linked_List.cpp) + * Cll + * [Cll](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/cll/cll.cpp) + * [Cll](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/cll/cll.h) + * [Main Cll](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/cll/main_cll.cpp) * [Doubly Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Doubly%20Linked%20List.cpp) * [Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Linked%20List.cpp) * [Linkedlist Implentation Usingarray](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/linkedList_implentation_usingArray.cpp) @@ -76,6 +81,7 @@ ## Math * [Factorial](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/factorial.cpp) + * [Fast Power](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/fast_power.cpp) * [Greatest Common Divisor](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/greatest_common_divisor.cpp) * [Power For Huge Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/power_for_huge_numbers.cpp) * [Prime Factorization](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/prime_factorization.cpp) From 07af54d3b1f839072ef77bd17b49f9a80652306a Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 8 Jan 2020 17:53:20 +0100 Subject: [PATCH 163/277] Update update_directory_md.yml --- .github/workflows/update_directory_md.yml | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/.github/workflows/update_directory_md.yml b/.github/workflows/update_directory_md.yml index 07b670177..b006d1032 100644 --- a/.github/workflows/update_directory_md.yml +++ b/.github/workflows/update_directory_md.yml @@ -6,15 +6,10 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - - shell: python + - shell: python # Legacy Python 2.7.15 :-( run: import sys ; print("Python {}.{}.{}".format(*sys.version_info)) - #- name: Upgrade to Python 3.8 - # run: sudo update-alternatives --install /usr/bin/python python ${pythonLocation}/bin/python3.8 10 - # shell: bash -c "$RUNNER_TOOL_CACHE/Python/3.8.0/x64/python {0}" - shell: bash -c "$RUNNER_TOOL_CACHE/Python/3.8.0/x64/python {0}" run: import sys ; print("Python {}.{}.{}".format(*sys.version_info)) - - shell: python - run: import sys ; print("Python {}.{}.{}".format(*sys.version_info)) - shell: bash -c "$RUNNER_TOOL_CACHE/Python/3.8.0/x64/python {0}" run: | import os From 8304f5e0e4f5efd293ba1ae583e10100bf4cf37a Mon Sep 17 00:00:00 2001 From: Lakshika Parihar <31981299+lakshika1064@users.noreply.github.com> Date: Fri, 10 Jan 2020 04:22:44 +0530 Subject: [PATCH 164/277] Interpolation search method (#287) * Interpolation search method * Delete interpolation_search.cpp * interpolation Search in C++ This algorithm follow the way we search a name in a phone book or a word in a dictionary * Update interpolation_search.cpp * Update interpolation_search.cpp * Update interpolation_search.cpp * Update interpolation_search.cpp * Update interpolation_search.cpp * Update interpolation_search.cpp * Update interpolation_search.cpp * Update interpolation_search.cpp * Rename Search/interpolation_search.cpp to search/interpolation_search.cpp Co-authored-by: Christian Clauss --- search/interpolation_search.cpp | 36 +++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 search/interpolation_search.cpp diff --git a/search/interpolation_search.cpp b/search/interpolation_search.cpp new file mode 100644 index 000000000..afa9e7c50 --- /dev/null +++ b/search/interpolation_search.cpp @@ -0,0 +1,36 @@ +#include + +// function to search the value in an array using interpolation search +int search(int arr[], int value, int len) { + int low = 0, high, mid; + high = len-1; + while (arr[low] <= value && arr[high] >= value) { + mid = (low + ((value-arr[low])*(high-low)) / (arr[high]-arr[low])); + if (arr[mid] > value) + high = mid-1; + else if (arr[mid] < value) + low = mid+1; + else + return mid; + } + if (arr[low] == value) + return low; + return 0; +} + +int main() { + int n, value, array[100], re; + std::cout << "Enter the size of array(less than 100) : "; + std::cin >> n; + std::cout << "array in ascending (increasing) order : " << std::endl; + for (int i=0; i < n; i++) + std::cin >> array[i]; + std::cout << "Enter the value you want to search : "; + std::cin >> value; + re = search(array, value, n); + if (re == 0) + std::cout << "Entered value is not in the array" << std::endl; + else + std::cout << "The value is at the position " << re << std::endl; + return 0; + } From 181a5f1e89db78de5c71c3171c1ee17b616fe8b7 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 9 Jan 2020 22:53:01 +0000 Subject: [PATCH 165/277] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index acf8c55f4..c078f4641 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -132,6 +132,7 @@ * [Exponential Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/exponential_search.cpp) * [Hash Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/hash_search.cpp) * [Interpolation Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/Interpolation%20Search.cpp) + * [Interpolation Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/interpolation_search.cpp) * [Linear Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/Linear%20Search.cpp) * [Median Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/median_search.cpp) * [Searching](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/searching.cpp) From 513a7d3a7712630a3fd87406a2595a1d0b1c0ca9 Mon Sep 17 00:00:00 2001 From: Nishant Sharma <54657882+nisshar@users.noreply.github.com> Date: Sat, 11 Jan 2020 00:26:12 +0530 Subject: [PATCH 166/277] added fast_integer_input.cpp (#696) * added fast_integer_input.cpp * fixed white spaces * fixed white spaces * fixed std:: * fixed std:: * \n Co-authored-by: Christian Clauss --- others/fast_interger_input.cpp | 36 ++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 others/fast_interger_input.cpp diff --git a/others/fast_interger_input.cpp b/others/fast_interger_input.cpp new file mode 100644 index 000000000..3358fc8bb --- /dev/null +++ b/others/fast_interger_input.cpp @@ -0,0 +1,36 @@ +// Read integers in the fastest way in c plus plus +#include +void fastinput(int *number) { +// variable to indicate sign of input integer + bool negative = false; + register int c; + *number = 0; + + // extract current character from buffer + c = std::getchar(); + if (c == '-') { + // number is negative + negative = true; + + // extract the next character from the buffer + c = std::getchar(); + } + + // Keep on extracting characters if they are integers + // i.e ASCII Value lies from '0'(48) to '9' (57) + for (; (c > 47 && c < 58); c = std::getchar()) + *number = *number *10 + c - 48; + + // if scanned input has a negative sign, negate the + // value of the input number + if (negative) + *(number) *= -1; +} + +// Function Call +int main() { + int number; + fastinput(&number); + std::cout << number << "\n"; + return 0; +} From 02951f1e00508cb242a16c431889541b07a32a87 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 10 Jan 2020 18:56:26 +0000 Subject: [PATCH 167/277] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index c078f4641..7899c1313 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -104,6 +104,7 @@ * [Decimal To Binary](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Decimal%20To%20Binary.cpp) * [Decimal To Hexadecimal ](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Decimal%20To%20Hexadecimal%20.cpp) * [Decimal To Roman Numeral](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Decimal%20to%20Roman%20Numeral.cpp) + * [Fast Interger Input](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/fast_interger_input.cpp) * [Fibonacci](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/fibonacci.cpp) * [Gcd Of N Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/GCD_of_n_numbers.cpp) * [Happy Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/happy_number.cpp) From ad23bbdf702fb3de2d0466551e2fc5e3ae0ebeb1 Mon Sep 17 00:00:00 2001 From: danghai Date: Sun, 12 Jan 2020 16:53:13 -0800 Subject: [PATCH 168/277] Add a simple class stack, and example --- data_structure/stk/main.cpp | 55 ++++++++++++++ data_structure/stk/makefile | 13 ++++ data_structure/stk/stack.cpp | 114 ++++++++++++++++++++++++++++++ data_structure/stk/stack.h | 35 +++++++++ data_structure/stk/student.txt | 17 +++++ data_structure/stk/test_stack.cpp | 54 ++++++++++++++ 6 files changed, 288 insertions(+) create mode 100644 data_structure/stk/main.cpp create mode 100644 data_structure/stk/makefile create mode 100644 data_structure/stk/stack.cpp create mode 100644 data_structure/stk/stack.h create mode 100644 data_structure/stk/student.txt create mode 100644 data_structure/stk/test_stack.cpp diff --git a/data_structure/stk/main.cpp b/data_structure/stk/main.cpp new file mode 100644 index 000000000..2d6bbec56 --- /dev/null +++ b/data_structure/stk/main.cpp @@ -0,0 +1,55 @@ +/* + * This program reads a data file consisting of students' GPAs + * followed by their names. The program then prints the highest + * GPA and the names of the students with the highest GPA. + * It uses stack to store the names of the students + * Run: + * make all + * ./main student.txt + ************************************************************ + * */ +#include +#include +#include +#include +#include + +#include "stack.h" +#include "stack.cpp" + +using namespace std; + +int main(int argc, char * argv[]) { + double GPA; + double highestGPA; + string name; + + assert(argc == 2); + ifstream infile; + stack stk; + + infile.open(argv[1]); + cout << fixed << showpoint; + cout << setprecision(2); + infile >> GPA >> name; + highestGPA = GPA; + + while (infile) { + if (GPA > highestGPA) { + stk.clear(); + stk.push(name); + highestGPA = GPA; + } else if (GPA == highestGPA) { + stk.push(name); + } + infile >> GPA >> name; + } + cout << "Highest GPA: " << highestGPA < +#include +#include "stack.h" + +using namespace std; + +/* Default constructor*/ +template +stack::stack() +{ + stackTop = NULL; + size = 0; +} + +/* Destructor */ +template +stack::~stack() +{ +} + +/* Display for testing */ +template +void stack::display() +{ + node *current = stackTop; + cout << "Top --> "; + while(current != NULL) { + cout<data<< " "; + current = current -> next; + } + cout < +bool stack::isEmptyStack() +{ + return (stackTop == NULL); +} + +/* Clear stack */ +template +void stack::clear() +{ + stackTop = NULL; +} + +/* Add new item to the stack */ +template +void stack::push(Type item) +{ + node *newNode; + newNode = new node; + newNode->data = item; + newNode->next = stackTop; + stackTop = newNode; + size++; +} + +/* Return the top element of the stack */ +template +Type stack::top() +{ + assert(stackTop != NULL); + return stackTop->data; +} + +/* Remove the top element of the stack */ +template +void stack::pop() +{ + node *temp; + if(!isEmptyStack()) { + temp = stackTop; + stackTop = stackTop->next; + delete temp; + size--; + } else { + cout << "Stack is empty !" << endl; + } +} + +/* Operator "=" */ +template +stack stack::operator=(stack & otherStack) +{ + node *newNode, *current, *last; + + if (stackTop != NULL) /* If stack is no empty, make it empty */ + stackTop = NULL; + if (otherStack.stackTop == NULL) + stackTop = NULL; + else { + current = otherStack.stackTop; + stackTop = new node; + stackTop->data = current->data; + stackTop->next = NULL; + last = stackTop; + current = current ->next; + /* Copy the remaining stack */ + while (current != NULL) + { + newNode = new node; + newNode->data = current->data; + newNode->next = NULL; + last->next = newNode; + last = newNode; + current = current->next; + } + } + size = otherStack.size; + return *this; +} diff --git a/data_structure/stk/stack.h b/data_structure/stk/stack.h new file mode 100644 index 000000000..a93669482 --- /dev/null +++ b/data_structure/stk/stack.h @@ -0,0 +1,35 @@ +/* This class specifies the basic operation on a stack as a linked list */ +#ifndef STACK_H +#define STACK_H + +/* Definition of the node */ +template +struct node +{ + Type data; + node *next; +}; + +/* Definition of the stack class */ +template +class stack +{ + public: + void display(); /* Show stack */ + stack(); /* Default constructor*/ + ~stack(); /* Destructor */ + bool isEmptyStack(); /* Determine whether the stack is empty */ + void push (Type item); /* Add new item to the stack */ + Type top(); /* Return the top element of the stack */ + void pop(); /* Remove the top element of the stack */ + void clear(); + + stack operator=(stack & otherStack); + // Overload "=" the assignment operator. + private: + node *stackTop; /* Pointer to the stack */ + int size; +}; + +#endif + diff --git a/data_structure/stk/student.txt b/data_structure/stk/student.txt new file mode 100644 index 000000000..b7e3b9e79 --- /dev/null +++ b/data_structure/stk/student.txt @@ -0,0 +1,17 @@ +3.4 Tom +3.2 Kathy +2.5 Hoang +3.4 Tom +3.8 Randy +3.9 Kingston +3.8 Mickey +3.6 Peter +3.5 Donald +3.8 Cindy +3.7 Dome +3.9 Andy +3.8 Hai +3.9 Minnie +2.7 Gilda +3.9 Vinay +3.4 Hiral diff --git a/data_structure/stk/test_stack.cpp b/data_structure/stk/test_stack.cpp new file mode 100644 index 000000000..4703fc906 --- /dev/null +++ b/data_structure/stk/test_stack.cpp @@ -0,0 +1,54 @@ +#include +#include "stack.h" +#include "stack.cpp" + +using namespace std; + +int main() +{ + stack stk; + cout << "---------------------- Test construct ----------------------" << endl; + stk.display(); + cout << "---------------------- Test isEmptyStack ----------------------" << endl; + if(stk.isEmptyStack()) + cout << "PASS" < stk1; + cout << "stk current: "<< endl; + stk.display(); + cout << endl << "Assign stk1 = stk "<< endl; + stk1 = stk; + stk1.display(); + cout << endl<< "After pushing 8 9 10 into stk1:" < Date: Thu, 16 Jan 2020 15:21:12 -0800 Subject: [PATCH 169/277] Add a simple queue class --- data_structure/queue/makefile | 11 ++++ data_structure/queue/queue.cpp | 90 +++++++++++++++++++++++++++++ data_structure/queue/queue.h | 34 +++++++++++ data_structure/queue/test_queue.cpp | 38 ++++++++++++ data_structure/stk/makefile | 2 +- 5 files changed, 174 insertions(+), 1 deletion(-) create mode 100644 data_structure/queue/makefile create mode 100644 data_structure/queue/queue.cpp create mode 100644 data_structure/queue/queue.h create mode 100644 data_structure/queue/test_queue.cpp diff --git a/data_structure/queue/makefile b/data_structure/queue/makefile new file mode 100644 index 000000000..420909804 --- /dev/null +++ b/data_structure/queue/makefile @@ -0,0 +1,11 @@ +CC= g++ +CFLAGS = -c -Wall + +all: test_queue +queue.o: queue.cpp + $(CC) $(CFLAGS) queue.cpp +test_queue: queue.o + $(CC) test_queue.cpp queue.o -o queue + +clean: + rm *o queue diff --git a/data_structure/queue/queue.cpp b/data_structure/queue/queue.cpp new file mode 100644 index 000000000..728adfc18 --- /dev/null +++ b/data_structure/queue/queue.cpp @@ -0,0 +1,90 @@ +#include +#include +#include "queue.h" + +using namespace std; + +/* Default constructor*/ +template +queue::queue() +{ + queueFront = NULL; + queueRear = NULL; + size = 0; +} + +/* Destructor */ +template +queue::~queue() +{ +} + +/* Display for testing */ +template +void queue::display() +{ + node *current = queueFront; + cout << "Front --> "; + while(current != NULL) { + cout<data<< " "; + current = current -> next; + } + cout < +bool queue::isEmptyQueue() +{ + return (queueFront == NULL); +} + +/* Clear queue */ +template +void queue::clear() +{ + queueFront = NULL; +} + +/* Add new item to the queue */ +template +void queue::enQueue(Kind item) +{ + node *newNode; + newNode = new node; + newNode->data = item; + newNode->next = NULL; + if (queueFront == NULL) { + queueFront = newNode; + queueRear = newNode; + } else { + queueRear->next = newNode; + queueRear = queueRear->next; + } + size++; +} + +/* Return the top element of the queue */ +template +Kind queue::front() +{ + assert(queueFront != NULL); + return queueFront->data; +} + +/* Remove the element of the queue */ +template +void queue::deQueue() +{ + node *temp; + if(!isEmptyQueue()) { + temp = queueFront; + queueFront = queueFront->next; + delete temp; + size--; + } else { + cout << "Queue is empty !" << endl; + } +} + diff --git a/data_structure/queue/queue.h b/data_structure/queue/queue.h new file mode 100644 index 000000000..715def1ef --- /dev/null +++ b/data_structure/queue/queue.h @@ -0,0 +1,34 @@ +/* This class specifies the basic operation on a queue as a linked list */ +#ifndef QUEUE_H +#define QUEUE_H + +/* Definition of the node */ +template +struct node +{ + Kind data; + node *next; +}; + +/* Definition of the queue class */ +template +class queue +{ + public: + void display(); /* Show queue */ + queue(); /* Default constructor*/ + ~queue(); /* Destructor */ + bool isEmptyQueue(); /* Determine whether the queue is empty */ + void enQueue (Kind item); /* Add new item to the queue */ + Kind front(); /* Return the first element of the queue */ + void deQueue(); /* Remove the top element of the queue */ + void clear(); + + private: + node *queueFront; /* Pointer to the front of the queue */ + node *queueRear; /* Pointer to the rear of the queue */ + int size; +}; + +#endif + diff --git a/data_structure/queue/test_queue.cpp b/data_structure/queue/test_queue.cpp new file mode 100644 index 000000000..caf80318c --- /dev/null +++ b/data_structure/queue/test_queue.cpp @@ -0,0 +1,38 @@ +#include +#include +#include "queue.h" +#include "queue.cpp" + +using namespace std; + +int main() +{ + queue q; + cout << "---------------------- Test construct ----------------------" << endl; + q.display(); + cout << "---------------------- Test isEmptyQueue ----------------------" << endl; + if(q.isEmptyQueue()) + cout << "PASS" < Date: Thu, 16 Jan 2020 23:22:00 +0000 Subject: [PATCH 170/277] updating DIRECTORY.md --- DIRECTORY.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 7899c1313..f93547264 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -32,8 +32,17 @@ * [Morrisinorder](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/MorrisInorder.cpp) * [Queue Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Queue%20Using%20Array.cpp) * [Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Queue%20Using%20Linked%20List.cpp) + * Queue + * [Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue/queue.cpp) + * [Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue/queue.h) + * [Test Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue/test_queue.cpp) * [Stack Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Stack%20Using%20Array.cpp) * [Stack Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Stack%20Using%20Linked%20List.cpp) + * Stk + * [Main](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/main.cpp) + * [Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/stack.cpp) + * [Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/stack.h) + * [Test Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/test_stack.cpp) * [Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Tree.cpp) * [Trie Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/trie_tree.cpp) From c168638060c2755ef5e5450b8e827a4f44afa41b Mon Sep 17 00:00:00 2001 From: Leo Yang Date: Fri, 24 Jan 2020 23:14:25 -0600 Subject: [PATCH 171/277] feat: add union find algorithm (aka disjoint set) --- data_structure/disjoint_set.cpp | 69 +++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 data_structure/disjoint_set.cpp diff --git a/data_structure/disjoint_set.cpp b/data_structure/disjoint_set.cpp new file mode 100644 index 000000000..de5d1c0e0 --- /dev/null +++ b/data_structure/disjoint_set.cpp @@ -0,0 +1,69 @@ +#include +#include +using namespace std; + +vector root, rnk; + +void CreateSet(int n){ + root = vector (n+1); + rnk = vector (n+1, 1); + + for(int i = 1; i <= n; ++ i) { + root[i] = i; + } +} + +int Find(int x) { + if (root[x] == x) { + return x; + } + return root[x] = Find(root[x]); +} + +bool InSameUnion(int x, int y) { + return Find(x) == Find(y); +} + +void Union(int x, int y) { + int a = Find(x), b = Find(y); + if(a != b) { + if (rnk[a] < rnk[b]) { + root[a] = b; + } else if (rnk[a] > rnk[b]) { + root[b] = a; + } else { + root[a] = b; + ++ rnk[b]; + } + } +} + +int main() { + + // tests CreateSet & Find + + int n = 100; + CreateSet(n); + + for (int i = 1; i <= 100; ++ i) { + if (root[i] != i) { + cout << "Fail" << endl; + break; + } + } + + // tests InSameUnion & Union + + cout << "1 and 2 are initially not in the same subset" << endl; + if (InSameUnion(1, 2)) { + cout << "Fail" << endl; + } + + Union(1, 2); + cout << "1 and 2 are now in the same subset" << endl; + if (!InSameUnion(1, 2)) { + cout << "Fail" << endl; + } + + return 0; +} From 1c5b12323ab1dc3e5f2d8d7c108c267b0f801ccf Mon Sep 17 00:00:00 2001 From: Leo Yang Date: Fri, 24 Jan 2020 23:22:08 -0600 Subject: [PATCH 172/277] feat: add union find algorithm (aka disjoint set) --- data_structure/disjoint_set.cpp | 93 ++++++++++++++++----------------- 1 file changed, 44 insertions(+), 49 deletions(-) diff --git a/data_structure/disjoint_set.cpp b/data_structure/disjoint_set.cpp index de5d1c0e0..71b220ab9 100644 --- a/data_structure/disjoint_set.cpp +++ b/data_structure/disjoint_set.cpp @@ -1,69 +1,64 @@ #include #include -using namespace std; + +using std::cout; +using std::endl; +using std::vector; vector root, rnk; -void CreateSet(int n){ - root = vector (n+1); - rnk = vector (n+1, 1); - - for(int i = 1; i <= n; ++ i) { - root[i] = i; - } +void CreateSet(int n) { + root = vector (n+1); + rnk = vector (n+1, 1); + for (int i = 1; i <= n; ++i) { + root[i] = i; + } } int Find(int x) { - if (root[x] == x) { - return x; - } - return root[x] = Find(root[x]); + if (root[x] == x) { + return x; + } + return root[x] = Find(root[x]); } bool InSameUnion(int x, int y) { - return Find(x) == Find(y); + return Find(x) == Find(y); } void Union(int x, int y) { - int a = Find(x), b = Find(y); - if(a != b) { - if (rnk[a] < rnk[b]) { - root[a] = b; - } else if (rnk[a] > rnk[b]) { - root[b] = a; - } else { - root[a] = b; - ++ rnk[b]; - } + int a = Find(x), b = Find(y); + if (a != b) { + if (rnk[a] < rnk[b]) { + root[a] = b; + } else if (rnk[a] > rnk[b]) { + root[b] = a; + } else { + root[a] = b; + ++rnk[b]; } + } } int main() { - - // tests CreateSet & Find - - int n = 100; - CreateSet(n); - - for (int i = 1; i <= 100; ++ i) { - if (root[i] != i) { - cout << "Fail" << endl; - break; - } + // tests CreateSet & Find + int n = 100; + CreateSet(n); + for (int i = 1; i <= 100; ++i) { + if (root[i] != i) { + cout << "Fail" << endl; + break; } - - // tests InSameUnion & Union - - cout << "1 and 2 are initially not in the same subset" << endl; - if (InSameUnion(1, 2)) { - cout << "Fail" << endl; - } - - Union(1, 2); - cout << "1 and 2 are now in the same subset" << endl; - if (!InSameUnion(1, 2)) { - cout << "Fail" << endl; - } - - return 0; + } + // tests InSameUnion & Union + cout << "1 and 2 are initially not in the same subset" << endl; + if (InSameUnion(1, 2)) { + cout << "Fail" << endl; + } + Union(1, 2); + cout << "1 and 2 are now in the same subset" << endl; + if (!InSameUnion(1, 2)) { + cout << "Fail" << endl; + } + return 0; } From 9a1144dcd7e0bb279d42ab0438632e76070a4259 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Mon, 27 Jan 2020 22:20:24 +0100 Subject: [PATCH 173/277] cpplint_modified_files.yml: Remove GH Actions workaround --- .github/workflows/cpplint_modified_files.yml | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/.github/workflows/cpplint_modified_files.yml b/.github/workflows/cpplint_modified_files.yml index d8fd59ad1..e77c46de3 100644 --- a/.github/workflows/cpplint_modified_files.yml +++ b/.github/workflows/cpplint_modified_files.yml @@ -11,11 +11,8 @@ jobs: cpplint_modified_files: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v2 - uses: actions/setup-python@v1 - - shell: python # Show the version of shell: python and then upgrade shell: python to Python 3.8 - run: import sys ; print("Python {}.{}.{}".format(*sys.version_info)) # Legacy Python :-( - - run: sudo update-alternatives --install /usr/bin/python python ${pythonLocation}/bin/python3.8 10 - run: python -m pip install cpplint - run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - run: git diff origin/master --name-only > git_diff.txt From 5960fe1db3dcda2abf828cb11b9ea90b0cb2852c Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Mon, 27 Jan 2020 22:33:41 +0100 Subject: [PATCH 174/277] update_directory_md.yml: Remove GH Actions workaround --- .github/workflows/update_directory_md.yml | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/.github/workflows/update_directory_md.yml b/.github/workflows/update_directory_md.yml index b006d1032..1d63374b0 100644 --- a/.github/workflows/update_directory_md.yml +++ b/.github/workflows/update_directory_md.yml @@ -5,12 +5,10 @@ jobs: update_directory_md: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v1 - - shell: python # Legacy Python 2.7.15 :-( - run: import sys ; print("Python {}.{}.{}".format(*sys.version_info)) - - shell: bash -c "$RUNNER_TOOL_CACHE/Python/3.8.0/x64/python {0}" - run: import sys ; print("Python {}.{}.{}".format(*sys.version_info)) - - shell: bash -c "$RUNNER_TOOL_CACHE/Python/3.8.0/x64/python {0}" + - uses: actions/checkout@v2 + - uses: actions/setup-python@v1 + - name: update_directory_md + shell: python run: | import os from typing import Iterator From 05957b562c69399b866d88bc2454c8ed4d410d02 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Wed, 29 Jan 2020 22:15:00 +0000 Subject: [PATCH 175/277] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index f93547264..75bb66f19 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -25,6 +25,7 @@ * [Cll](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/cll/cll.cpp) * [Cll](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/cll/cll.h) * [Main Cll](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/cll/main_cll.cpp) + * [Disjoint Set](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/disjoint_set.cpp) * [Doubly Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Doubly%20Linked%20List.cpp) * [Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Linked%20List.cpp) * [Linkedlist Implentation Usingarray](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/linkedList_implentation_usingArray.cpp) From a8ef8a62d64c3bf9a06d344c5c563c8b13497acb Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Mon, 17 Feb 2020 14:04:32 +0100 Subject: [PATCH 176/277] git remote -v ; git branch --- .github/workflows/cpplint_modified_files.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/cpplint_modified_files.yml b/.github/workflows/cpplint_modified_files.yml index e77c46de3..d15724341 100644 --- a/.github/workflows/cpplint_modified_files.yml +++ b/.github/workflows/cpplint_modified_files.yml @@ -14,6 +14,8 @@ jobs: - uses: actions/checkout@v2 - uses: actions/setup-python@v1 - run: python -m pip install cpplint + - run: git remote -v + - run: git branch - run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - run: git diff origin/master --name-only > git_diff.txt - name: cpplint_modified_files From a606d9782d9de58480d796984f5f84b74537555d Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Sun, 1 Mar 2020 13:57:44 +0100 Subject: [PATCH 177/277] git diff origin/master --> git diff master --- .github/workflows/cpplint_modified_files.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/cpplint_modified_files.yml b/.github/workflows/cpplint_modified_files.yml index d15724341..130ea6bea 100644 --- a/.github/workflows/cpplint_modified_files.yml +++ b/.github/workflows/cpplint_modified_files.yml @@ -17,7 +17,7 @@ jobs: - run: git remote -v - run: git branch - run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - - run: git diff origin/master --name-only > git_diff.txt + - run: git diff master --name-only > git_diff.txt - name: cpplint_modified_files shell: python run: | From 616ad99a458b6434ec0bf037b77e2c3aec1190a9 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Sun, 1 Mar 2020 14:06:41 +0100 Subject: [PATCH 178/277] run: git diff origin/master --name-only > git_diff.txt --- .github/workflows/cpplint_modified_files.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/cpplint_modified_files.yml b/.github/workflows/cpplint_modified_files.yml index 130ea6bea..1524d65dc 100644 --- a/.github/workflows/cpplint_modified_files.yml +++ b/.github/workflows/cpplint_modified_files.yml @@ -16,8 +16,8 @@ jobs: - run: python -m pip install cpplint - run: git remote -v - run: git branch - - run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - - run: git diff master --name-only > git_diff.txt + #- run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY + - run: git diff origin/master --name-only > git_diff.txt - name: cpplint_modified_files shell: python run: | From 9a258f26a6d2d570c65d681e6ced0890075ffbda Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Sun, 1 Mar 2020 14:16:48 +0100 Subject: [PATCH 179/277] git diff master... --name-only > git_diff.txt --- .github/workflows/cpplint_modified_files.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/cpplint_modified_files.yml b/.github/workflows/cpplint_modified_files.yml index 1524d65dc..621fc8294 100644 --- a/.github/workflows/cpplint_modified_files.yml +++ b/.github/workflows/cpplint_modified_files.yml @@ -17,7 +17,7 @@ jobs: - run: git remote -v - run: git branch #- run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - - run: git diff origin/master --name-only > git_diff.txt + - run: git diff master... --name-only > git_diff.txt - name: cpplint_modified_files shell: python run: | From 95e5739cdef93262961b24f8b0eddc66218753eb Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Sun, 1 Mar 2020 14:20:39 +0100 Subject: [PATCH 180/277] git diff origin/master... --name-only > git_diff.txt --- .github/workflows/cpplint_modified_files.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/cpplint_modified_files.yml b/.github/workflows/cpplint_modified_files.yml index 621fc8294..b63348bb5 100644 --- a/.github/workflows/cpplint_modified_files.yml +++ b/.github/workflows/cpplint_modified_files.yml @@ -17,7 +17,7 @@ jobs: - run: git remote -v - run: git branch #- run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - - run: git diff master... --name-only > git_diff.txt + - run: git diff origin/master... --name-only > git_diff.txt - name: cpplint_modified_files shell: python run: | From 10cff7b97f373eaf87276ba0e9e3a43dfd0cc297 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Sun, 1 Mar 2020 14:36:47 +0100 Subject: [PATCH 181/277] git diff origin/master HEAD --name-onl --- .github/workflows/cpplint_modified_files.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/cpplint_modified_files.yml b/.github/workflows/cpplint_modified_files.yml index b63348bb5..6ca643266 100644 --- a/.github/workflows/cpplint_modified_files.yml +++ b/.github/workflows/cpplint_modified_files.yml @@ -17,7 +17,7 @@ jobs: - run: git remote -v - run: git branch #- run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - - run: git diff origin/master... --name-only > git_diff.txt + - run: git diff origin/master HEAD --name-only > git_diff.txt - name: cpplint_modified_files shell: python run: | From e13f4f4183b1e0f44d98487579d9a16511404b0f Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Sun, 1 Mar 2020 14:44:44 +0100 Subject: [PATCH 182/277] git diff --diff-filter=am --name-only master HEAD || true --- .github/workflows/cpplint_modified_files.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/cpplint_modified_files.yml b/.github/workflows/cpplint_modified_files.yml index 6ca643266..1ad2664fd 100644 --- a/.github/workflows/cpplint_modified_files.yml +++ b/.github/workflows/cpplint_modified_files.yml @@ -17,6 +17,10 @@ jobs: - run: git remote -v - run: git branch #- run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY + - run: git diff --diff-filter=am --name-only master HEAD || true + - run: git diff --name-only origin/master HEAD || true + - run: git diff --name-only upstream/master HEAD || true + - run: git diff origin/master HEAD --name-only || true - run: git diff origin/master HEAD --name-only > git_diff.txt - name: cpplint_modified_files shell: python From 562eb057d04a27cc44e3dad25f6414b05f1ce383 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Sun, 1 Mar 2020 15:03:32 +0100 Subject: [PATCH 183/277] actions/checkout@v1 # v2 is broken for git diff --- .github/workflows/cpplint_modified_files.yml | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/.github/workflows/cpplint_modified_files.yml b/.github/workflows/cpplint_modified_files.yml index 1ad2664fd..fde6f1d53 100644 --- a/.github/workflows/cpplint_modified_files.yml +++ b/.github/workflows/cpplint_modified_files.yml @@ -11,16 +11,12 @@ jobs: cpplint_modified_files: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v1 # v2 is broken for git diff - uses: actions/setup-python@v1 - run: python -m pip install cpplint - run: git remote -v - run: git branch - #- run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - - run: git diff --diff-filter=am --name-only master HEAD || true - - run: git diff --name-only origin/master HEAD || true - - run: git diff --name-only upstream/master HEAD || true - - run: git diff origin/master HEAD --name-only || true + - run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - run: git diff origin/master HEAD --name-only > git_diff.txt - name: cpplint_modified_files shell: python From ec0ac65aa19c6c2c903ca4eac3acc70e3972f213 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Sun, 1 Mar 2020 15:05:34 +0100 Subject: [PATCH 184/277] actions/checkout@v1 # v2 is broken for git diff --- .github/workflows/cpplint_modified_files.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/cpplint_modified_files.yml b/.github/workflows/cpplint_modified_files.yml index fde6f1d53..076a8bb89 100644 --- a/.github/workflows/cpplint_modified_files.yml +++ b/.github/workflows/cpplint_modified_files.yml @@ -17,7 +17,7 @@ jobs: - run: git remote -v - run: git branch - run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - - run: git diff origin/master HEAD --name-only > git_diff.txt + - run: git diff origin/master --name-only > git_diff.txt - name: cpplint_modified_files shell: python run: | From e755bee9071941258c6d6c1fc38268711757a461 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Sun, 1 Mar 2020 15:18:14 +0100 Subject: [PATCH 185/277] git diff --diff-filter=am --name-only origin/master --- .github/workflows/cpplint_modified_files.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/cpplint_modified_files.yml b/.github/workflows/cpplint_modified_files.yml index 076a8bb89..6455b2902 100644 --- a/.github/workflows/cpplint_modified_files.yml +++ b/.github/workflows/cpplint_modified_files.yml @@ -17,7 +17,7 @@ jobs: - run: git remote -v - run: git branch - run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - - run: git diff origin/master --name-only > git_diff.txt + - run: git diff --diff-filter=am --name-only origin/master > git_diff.txt - name: cpplint_modified_files shell: python run: | From 2f70c92e759c86300111ca1ad5c6badba8261651 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Sun, 1 Mar 2020 15:25:10 +0100 Subject: [PATCH 186/277] Update cpplint_modified_files.yml --- .github/workflows/cpplint_modified_files.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/cpplint_modified_files.yml b/.github/workflows/cpplint_modified_files.yml index 6455b2902..07a32ece9 100644 --- a/.github/workflows/cpplint_modified_files.yml +++ b/.github/workflows/cpplint_modified_files.yml @@ -17,7 +17,7 @@ jobs: - run: git remote -v - run: git branch - run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - - run: git diff --diff-filter=am --name-only origin/master > git_diff.txt + - run: git diff --diff-filter=dr --name-only origin/master > git_diff.txt - name: cpplint_modified_files shell: python run: | From ca068e5828548998be1962a7237c6b4447b544f0 Mon Sep 17 00:00:00 2001 From: Siddharth M <47861446+siddmohanty@users.noreply.github.com> Date: Sun, 1 Mar 2020 20:17:32 +0530 Subject: [PATCH 187/277] Measure time (#706) * Create measure_time_elapsed.cpp * add functionality to measure time elapsed of a code * cout --> std:cout * Update measure_time_elapsed.cpp * Update time_elapsed.cpp * Update measure_time_elapsed.cpp * std:cout << getTimeInMicroseconds() - starttime; * std:cout << getTimeInMicroseconds() - starttime; * Update measure_time_elapsed.cpp * Fix include order and use int64 * Remove trailing whitespace * Delete time_elapsed.cpp * int64_t * #include * long long * int64 * int64_t * __int64_t * std::cout and std::nullptr * #include Co-authored-by: Christian Clauss --- others/measure_time_elapsed.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 others/measure_time_elapsed.cpp diff --git a/others/measure_time_elapsed.cpp b/others/measure_time_elapsed.cpp new file mode 100644 index 000000000..d0830ab79 --- /dev/null +++ b/others/measure_time_elapsed.cpp @@ -0,0 +1,19 @@ +// To calculate the time taken by a code to execute +#include +#include + +__int64_t getTimeInMicroseconds() { + struct timeval start; + gettimeofday(&start, NULL); + return start.tv_sec * 1000000 + start.tv_usec; +} + +// write function sample(args) + +int main() { + // write code + __int64_t starttime = getTimeInMicroseconds(); + // sample(args) function run + // Any other functions (if present) run + std::cout << getTimeInMicroseconds() - starttime; +} From 798c652410237304308fd1abeeae0b7a9cc316e1 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 1 Mar 2020 14:47:47 +0000 Subject: [PATCH 188/277] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 75bb66f19..cfd10df70 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -119,6 +119,7 @@ * [Gcd Of N Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/GCD_of_n_numbers.cpp) * [Happy Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/happy_number.cpp) * [Matrix Exponentiation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/matrix_exponentiation.cpp) + * [Measure Time Elapsed](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/measure_time_elapsed.cpp) * [Palindromeofnumber](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Palindromeofnumber.cpp) * [Paranthesis Matching](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Paranthesis%20Matching.cpp) * [Pascal Triangle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/pascal_triangle.cpp) From ef0f8a15469468f5772f2356d765559451fa8047 Mon Sep 17 00:00:00 2001 From: Pooja Date: Sun, 1 Mar 2020 20:43:26 +0530 Subject: [PATCH 189/277] Create queue_using_array.cpp (#707) * Create queue_using_array.cpp * std::cout * clang-format -i -style="{IndentWidth: 4}" queue_using_array.cpp * Update queue_using_array.cpp * Update queue_using_array.cpp * Update queue_using_array.cpp * Update queue_using_array.cpp Co-authored-by: Christian Clauss --- data_structure/queue_using_array.cpp | 93 ++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 data_structure/queue_using_array.cpp diff --git a/data_structure/queue_using_array.cpp b/data_structure/queue_using_array.cpp new file mode 100644 index 000000000..ccd6e3cd6 --- /dev/null +++ b/data_structure/queue_using_array.cpp @@ -0,0 +1,93 @@ +/* + Write a program to implement Linear Queue using array. + + Functions to implement + Enqueue (Insertion) + Dequeue (Deletion) + +*/ +#include + +#define MAXSIZE 10 + +class Queue_Array { + int front; + int rear; + int size; + + public: + Queue_Array() { + front = -1; + rear = -1; + size = MAXSIZE; + } + int *arr = new int[size]; + void enqueue(int); + int dequeue(); + void display(); +}; + +void Queue_Array::enqueue(int ele) { + if (rear == size - 1) { + std::cout << "\nStack is full"; + } else if (front == -1 && rear == -1) { + front = rear = 0; + arr[rear] = ele; + } else if (rear < size) { + rear++; + arr[rear] = ele; + } +} + +int Queue_Array::dequeue() { + int d; + if (front == -1) { + std::cout << "\nstack is empty "; + return 0; + } else if (front == rear) { + d = arr[front]; + front = rear = -1; + } else { + d = arr[front++]; + } + + return d; +} + +void Queue_Array::display() { + if (front == -1) { + std::cout << "\nStack is empty"; + } else { + for (int i = front; i <= rear; i++) + std::cout << arr[i] << " "; + } +} + +int main() { + int op, data; + + Queue_Array ob; + + std::cout << "\n1. enqueue(Insertion) "; + std::cout << "\n2. dequeue(Deletion)"; + std::cout << "\n3. Display"; + std::cout << "\n4. Exit"; + while (1) { + std::cout << "\nEnter your choice "; + std::cin >> op; + if (op == 1) { + std::cout << "Enter data "; + std::cin >> data; + ob.enqueue(data); + } else if (op == 2) { + data = ob.dequeue(); + std::cout << "\ndequeue element is:\t" << data; + } else if (op == 3) { + ob.display(); + } else if (op == 4) { + exit(0); + } else { + std::cout << "\nWrong choice "; + } + } +} From e1fce9e2bf7e82d699cdc9dc475e86cf4f206b9a Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 1 Mar 2020 15:13:43 +0000 Subject: [PATCH 190/277] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index cfd10df70..7ebc5505d 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -37,6 +37,7 @@ * [Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue/queue.cpp) * [Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue/queue.h) * [Test Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue/test_queue.cpp) + * [Queue Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue_using_array.cpp) * [Stack Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Stack%20Using%20Array.cpp) * [Stack Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Stack%20Using%20Linked%20List.cpp) * Stk From 665503810592f625522ba738f7193b457d6e45dd Mon Sep 17 00:00:00 2001 From: Perukii <57752033+Perukii@users.noreply.github.com> Date: Sat, 7 Mar 2020 16:20:08 +0900 Subject: [PATCH 191/277] feat : added library sort (#710) * added library_sort.cpp * added library_sort.cpp * format * format * modified the code * feat : added library sort --- .vscode/settings.json | 67 ++++++++++++++++++++++++++++++ sorting/library_sort.cpp | 90 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 157 insertions(+) create mode 100644 .vscode/settings.json create mode 100644 sorting/library_sort.cpp diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 000000000..8b117a5fd --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,67 @@ +{ + "files.associations": { + "array": "cpp", + "atomic": "cpp", + "*.tcc": "cpp", + "bitset": "cpp", + "cctype": "cpp", + "cfenv": "cpp", + "chrono": "cpp", + "cinttypes": "cpp", + "clocale": "cpp", + "cmath": "cpp", + "codecvt": "cpp", + "complex": "cpp", + "condition_variable": "cpp", + "csetjmp": "cpp", + "csignal": "cpp", + "cstdarg": "cpp", + "cstddef": "cpp", + "cstdint": "cpp", + "cstdio": "cpp", + "cstdlib": "cpp", + "cstring": "cpp", + "ctime": "cpp", + "cuchar": "cpp", + "cwchar": "cpp", + "cwctype": "cpp", + "deque": "cpp", + "forward_list": "cpp", + "list": "cpp", + "unordered_map": "cpp", + "unordered_set": "cpp", + "vector": "cpp", + "exception": "cpp", + "fstream": "cpp", + "functional": "cpp", + "future": "cpp", + "initializer_list": "cpp", + "iomanip": "cpp", + "iosfwd": "cpp", + "iostream": "cpp", + "istream": "cpp", + "limits": "cpp", + "memory": "cpp", + "mutex": "cpp", + "new": "cpp", + "numeric": "cpp", + "optional": "cpp", + "ostream": "cpp", + "ratio": "cpp", + "scoped_allocator": "cpp", + "shared_mutex": "cpp", + "sstream": "cpp", + "stdexcept": "cpp", + "streambuf": "cpp", + "string_view": "cpp", + "system_error": "cpp", + "thread": "cpp", + "type_traits": "cpp", + "tuple": "cpp", + "typeindex": "cpp", + "typeinfo": "cpp", + "utility": "cpp", + "valarray": "cpp", + "algorithm": "cpp" + } +} \ No newline at end of file diff --git a/sorting/library_sort.cpp b/sorting/library_sort.cpp new file mode 100644 index 000000000..6f1ab6245 --- /dev/null +++ b/sorting/library_sort.cpp @@ -0,0 +1,90 @@ +#include +#include + +void librarySort(int *index, int n) { + int lib_size, index_pos, + *gaps, // gaps + *library[2]; // libraries + + bool target_lib, *numbered; + + for (int i = 0; i < 2; i++) + library[i] = new int[n]; + + gaps = new int[n + 1]; + numbered = new bool[n + 1]; + + lib_size = 1; + index_pos = 1; + target_lib = 0; + library[target_lib][0] = index[0]; + + while (index_pos < n) { + // binary search + int insert = std::distance( + library[target_lib], + std::lower_bound(library[target_lib], + library[target_lib] + lib_size, index[index_pos])); + + // if there is no gap to insert a new index ... + + if (numbered[insert] == true) { + int prov_size = 0, next_target_lib = !target_lib; + + // update library and clear gaps + + for (int i = 0; i <= n; i++) { + if (numbered[i] == true) { + library[next_target_lib][prov_size] = gaps[i]; + prov_size++; + numbered[i] = false; + } + + if (i <= lib_size) { + library[next_target_lib][prov_size] = + library[target_lib][i]; + prov_size++; + } + } + + target_lib = next_target_lib; + lib_size = prov_size - 1; + } else { + numbered[insert] = true; + gaps[insert] = index[index_pos]; + index_pos++; + } + } + + int index_pos_for_output = 0; + for (int i = 0; index_pos_for_output < n; i++) { + if (numbered[i] == true) { + // std::cout << gaps[i] << std::endl; + index[index_pos_for_output] = gaps[i]; + index_pos_for_output++; + } + + if (i < lib_size) { + // std::cout << library[target_lib][i] << std::endl; + index[index_pos_for_output] = library[target_lib][i]; + index_pos_for_output++; + } + } +} + +int main() { + // ---example-- + int index_ex[] = {-6, 5, 9, 1, 9, 1, 0, 1, -8, 4, -12}; + int n_ex = sizeof(index_ex) / sizeof(index_ex[0]); + + librarySort(index_ex, n_ex); + std::cout << "sorted array :" << std::endl; + for (int i = 0; i < n_ex; i++) + std::cout << index_ex[i] << " "; + std::cout << std::endl; + + /* --output-- + sorted array : + -12 -8 -6 0 1 1 1 4 5 9 9 + */ +} From 795dbad02ea4829a928cfecb625be6bff283ceab Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 7 Mar 2020 07:20:22 +0000 Subject: [PATCH 192/277] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 7ebc5505d..898e78826 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -162,6 +162,7 @@ * [Countingsortstring](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/CountingSortString.cpp) * [Heap Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/heap_sort.cpp) * [Insertion Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Insertion%20Sort.cpp) + * [Library Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/library_sort.cpp) * [Merge Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Merge%20Sort.cpp) * [Numericstringsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/NumericStringSort.cpp) * [Oddeven Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/OddEven%20Sort.cpp) From 4e79d1b068f321ab8ba6a9fbb217b38fffff07cb Mon Sep 17 00:00:00 2001 From: Pooja Date: Sun, 8 Mar 2020 13:27:51 +0530 Subject: [PATCH 193/277] Create queue_using_linkedlist.cpp --- data_structure/queue_using_linkedlist.cpp | 97 +++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 data_structure/queue_using_linkedlist.cpp diff --git a/data_structure/queue_using_linkedlist.cpp b/data_structure/queue_using_linkedlist.cpp new file mode 100644 index 000000000..a27d3db37 --- /dev/null +++ b/data_structure/queue_using_linkedlist.cpp @@ -0,0 +1,97 @@ +/* + Write a program to implement Queue using linkedlist. +*/ +#include + + +struct linkedlist{ + int data; + linkedlist *next; + +}; +class stack_linkedList{ + public: + linkedlist *front; + linkedlist *rear; + + stack_linkedList(){ + front=rear=NULL; + } + void enqueue(int); + int dequeue(); + void display(); + +}; +void stack_linkedList::enqueue(int ele){ + + linkedlist *temp=new linkedlist(); + temp->data=ele; + temp->next=NULL; + + if(front==NULL) + front=rear=temp; + else{ + rear->next=temp; + rear=temp; + } +} +int stack_linkedList::dequeue(){ + linkedlist *temp; + int ele; + if(front==NULL) + std::cout<<"\nStack is empty"; + else{ + temp=front; + ele=temp->data; + if(front==rear) //if length of queue is 1; + rear=rear->next; + front=front->next; + delete(temp); + } + return ele; +} +void stack_linkedList::display(){ + + if(front==NULL) + std::cout<<"\nStack is empty"; + + else { + + linkedlist *temp; + temp=front; + while(temp!=NULL){ + std::cout<data<<" "; + temp=temp->next; + } + } +} + +int main(){ + + int op,data; + stack_linkedList ob; + std::cout<<"\n1. enqueue(Insertion) "; + std::cout<<"\n2. dequeue(Deletion)"; + std::cout<<"\n3. Display"; + std::cout<<"\n4. Exit"; + + while(1){ + std::cout<<"\nEnter your choice "; + std::cin>>op; + if(op==1) + { + std::cout<<"Enter data "; + std::cin>>data; + ob.enqueue(data); + } + else if(op==2) + data=ob.dequeue(); + else if(op==3) + ob.display(); + else if(op==4) + exit(0); + else + std::cout<<"\nWrong choice "; + + } +} From 7be8986c118686144d1d633a768017463f984b91 Mon Sep 17 00:00:00 2001 From: Mann Mehta <44433995+mann2108@users.noreply.github.com> Date: Sun, 29 Mar 2020 17:18:49 +0530 Subject: [PATCH 194/277] Added eulers totient function in math --- math/eulers_totient_function.cpp | 48 ++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 math/eulers_totient_function.cpp diff --git a/math/eulers_totient_function.cpp b/math/eulers_totient_function.cpp new file mode 100644 index 000000000..1d1d75edf --- /dev/null +++ b/math/eulers_totient_function.cpp @@ -0,0 +1,48 @@ +#include + +using namespace std; +typedef long long int ll; + +/** + +Euler Totient Function also know as phi function. + +phi(n) = phi(p1^a1).phi(p2^a2)... +where p1, p2,... are prime factor of n. + +3 Euler's Property: +1. phi(prime_no) = prime_no-1 +2. phi(prime_no^k) = (prime_no^k - prime_no^(k-1)) +3. phi(a,b) = phi(a). phi(b) where a and b are relative primes. + +Applying this 3 property on the first equation. +phi(n) = n. (1-1/p1). (1-1/p2). ... +where p1,p2... are prime factors. + +Hence Implementation in O(sqrt(n)). + +*/ + +ll phiFunction(ll n){ + ll res = n; + for(ll i=2;i*i<=n;i++){ + if(n%i==0){ + while(n%i==0){ + n/=i; + } + res-=res/i; + } + } + if(n>1)res-=res/n; + return res; +} + +int main(){ + ll t; + cin>>t; + while(t--){ + ll n; + cin>>n; + cout< Date: Sun, 29 Mar 2020 17:26:45 +0530 Subject: [PATCH 195/277] modifed the spaces and code structure --- math/eulers_totient_function.cpp | 31 +++++++++++++------------------ 1 file changed, 13 insertions(+), 18 deletions(-) diff --git a/math/eulers_totient_function.cpp b/math/eulers_totient_function.cpp index 1d1d75edf..5b0f7c869 100644 --- a/math/eulers_totient_function.cpp +++ b/math/eulers_totient_function.cpp @@ -1,7 +1,6 @@ #include using namespace std; -typedef long long int ll; /** @@ -23,26 +22,22 @@ Hence Implementation in O(sqrt(n)). */ -ll phiFunction(ll n){ - ll res = n; - for(ll i=2;i*i<=n;i++){ - if(n%i==0){ - while(n%i==0){ - n/=i; +int phiFunction (int n ) { + int result = n ; + for ( ll i=2 ; i*i <= n ; i++ ) { + if ( n%i == 0 ) { + while ( n%i == 0 ) { + n /= i ; } - res-=res/i; + result -= result/i ; } } - if(n>1)res-=res/n; - return res; + if ( n > 1 ) result -= result/n ; + return result ; } -int main(){ - ll t; - cin>>t; - while(t--){ - ll n; - cin>>n; - cout<> n ; + cout << phiFunction ( n ) << endl ; } From ea362365545154fbae1302fded6bf234e3c7810c Mon Sep 17 00:00:00 2001 From: Mann Mehta <44433995+mann2108@users.noreply.github.com> Date: Sun, 29 Mar 2020 17:31:34 +0530 Subject: [PATCH 196/277] modified the spaces before braces --- math/eulers_totient_function.cpp | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/math/eulers_totient_function.cpp b/math/eulers_totient_function.cpp index 5b0f7c869..63058063c 100644 --- a/math/eulers_totient_function.cpp +++ b/math/eulers_totient_function.cpp @@ -22,22 +22,22 @@ Hence Implementation in O(sqrt(n)). */ -int phiFunction (int n ) { - int result = n ; - for ( ll i=2 ; i*i <= n ; i++ ) { - if ( n%i == 0 ) { - while ( n%i == 0 ) { - n /= i ; +int phiFunction(int n) { + int result = n; + for (ll i=2; i*i <= n; i++) { + if (n%i == 0) { + while (n%i == 0) { + n /= i; } - result -= result/i ; + result -= result/i; } } - if ( n > 1 ) result -= result/n ; - return result ; + if (n > 1) result -= result/n; + return result; } int main() { - int n ; - cin >> n ; - cout << phiFunction ( n ) << endl ; + int n; + cin >> n; + cout << phiFunction(n) << endl; } From 022e2f02e7b01c4ac5e34be2fc38a3255f83b509 Mon Sep 17 00:00:00 2001 From: Mann Mehta <44433995+mann2108@users.noreply.github.com> Date: Sun, 29 Mar 2020 17:36:33 +0530 Subject: [PATCH 197/277] modified by removing namespace using-directive --- math/eulers_totient_function.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/math/eulers_totient_function.cpp b/math/eulers_totient_function.cpp index 63058063c..f05c7dab4 100644 --- a/math/eulers_totient_function.cpp +++ b/math/eulers_totient_function.cpp @@ -1,6 +1,5 @@ -#include - -using namespace std; +/// C++ Program to find Euler Totient Function +#include /** @@ -22,6 +21,7 @@ Hence Implementation in O(sqrt(n)). */ +/// Function to caculate euler totient function int phiFunction(int n) { int result = n; for (ll i=2; i*i <= n; i++) { @@ -38,6 +38,6 @@ int phiFunction(int n) { int main() { int n; - cin >> n; - cout << phiFunction(n) << endl; + std::cin >> n; + std::cout << phiFunction(n) << endl; } From 1d6492bf333dcd18a0e11805810a6da2b8e57f24 Mon Sep 17 00:00:00 2001 From: Mann Mehta <44433995+mann2108@users.noreply.github.com> Date: Sun, 29 Mar 2020 17:39:39 +0530 Subject: [PATCH 198/277] resolve compilation error --- math/eulers_totient_function.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/math/eulers_totient_function.cpp b/math/eulers_totient_function.cpp index f05c7dab4..8165f030e 100644 --- a/math/eulers_totient_function.cpp +++ b/math/eulers_totient_function.cpp @@ -24,7 +24,7 @@ Hence Implementation in O(sqrt(n)). /// Function to caculate euler totient function int phiFunction(int n) { int result = n; - for (ll i=2; i*i <= n; i++) { + for (int i=2; i*i <= n; i++) { if (n%i == 0) { while (n%i == 0) { n /= i; @@ -39,5 +39,5 @@ int phiFunction(int n) { int main() { int n; std::cin >> n; - std::cout << phiFunction(n) << endl; + std::cout << phiFunction(n); } From 58f6815aadf37b55f6d89bf298975f04a52aeddb Mon Sep 17 00:00:00 2001 From: John Law Date: Tue, 31 Mar 2020 23:26:32 +0200 Subject: [PATCH 199/277] Format Euler's Totient --- math/eulers_totient_function.cpp | 48 +++++++++++++++----------------- 1 file changed, 23 insertions(+), 25 deletions(-) diff --git a/math/eulers_totient_function.cpp b/math/eulers_totient_function.cpp index 8165f030e..31ced5a51 100644 --- a/math/eulers_totient_function.cpp +++ b/math/eulers_totient_function.cpp @@ -1,38 +1,36 @@ /// C++ Program to find Euler Totient Function #include -/** +/* + * Euler Totient Function is also known as phi function. + * phi(n) = phi(p1^a1).phi(p2^a2)... + * where p1, p2,... are prime factors of n. + * 3 Euler's properties: + * 1. phi(prime_no) = prime_no-1 + * 2. phi(prime_no^k) = (prime_no^k - prime_no^(k-1)) + * 3. phi(a,b) = phi(a). phi(b) where a and b are relative primes. + * Applying this 3 properties on the first equation. + * phi(n) = n. (1-1/p1). (1-1/p2). ... + * where p1,p2... are prime factors. + * Hence Implementation in O(sqrt(n)). + * phi(100) = 40 + * phi(1) = 1 + * phi(17501) = 15120 + * phi(1420) = 560 + */ -Euler Totient Function also know as phi function. - -phi(n) = phi(p1^a1).phi(p2^a2)... -where p1, p2,... are prime factor of n. - -3 Euler's Property: -1. phi(prime_no) = prime_no-1 -2. phi(prime_no^k) = (prime_no^k - prime_no^(k-1)) -3. phi(a,b) = phi(a). phi(b) where a and b are relative primes. - -Applying this 3 property on the first equation. -phi(n) = n. (1-1/p1). (1-1/p2). ... -where p1,p2... are prime factors. - -Hence Implementation in O(sqrt(n)). - -*/ - -/// Function to caculate euler totient function +// Function to caculate Euler's totient phi int phiFunction(int n) { int result = n; - for (int i=2; i*i <= n; i++) { - if (n%i == 0) { - while (n%i == 0) { + for (int i = 2; i * i <= n; i++) { + if (n % i == 0) { + while (n % i == 0) { n /= i; } - result -= result/i; + result -= result / i; } } - if (n > 1) result -= result/n; + if (n > 1) result -= result / n; return result; } From ae9e75bf8b167a066fc4d91b59f956ee53478b74 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 31 Mar 2020 21:29:20 +0000 Subject: [PATCH 200/277] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 898e78826..061d35009 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -91,6 +91,7 @@ * [Quadratic Probing Hash Table](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/quadratic_probing_hash_table.cpp) ## Math + * [Eulers Totient Function](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/eulers_totient_function.cpp) * [Factorial](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/factorial.cpp) * [Fast Power](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/fast_power.cpp) * [Greatest Common Divisor](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/greatest_common_divisor.cpp) From 70ac13f4a0fc15f987d3874112dfdeab0af388ac Mon Sep 17 00:00:00 2001 From: Mann Mehta <44433995+mann2108@users.noreply.github.com> Date: Thu, 2 Apr 2020 04:03:22 +0530 Subject: [PATCH 201/277] added binary_exponent.cpp --- math/binary_exponent.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 math/binary_exponent.cpp diff --git a/math/binary_exponent.cpp b/math/binary_exponent.cpp new file mode 100644 index 000000000..0f9d442a5 --- /dev/null +++ b/math/binary_exponent.cpp @@ -0,0 +1,25 @@ +/// C++ Program to find Binary Exponent recursively. + +#include +/* + * Calculating a^b in O(log(b)) by converting b in binary no. + * Binary exponentiation (also known as exponentiation by squaring) + * is a trick which allows to calculate an using only O(logn) multiplications + * (instead of O(n) multiplications required by the naive approach). +*/ + +int binExpo(int a,int b) { + if (b == 0) return 1; + int res = binExpo(a,b/2); + if (b%2) return res*res*a; + else return res*res; +} + +int main() { + int a,b; + /// Give two nos as a^b (where '^' denotes power exponent operation + std::cin >> a >> b; + ///Result of a^b + std::cout << binExpo(a,b) << endl; +} + From c7a50927b74e76e511f70253a4828f57fa9c581c Mon Sep 17 00:00:00 2001 From: Mann Mehta <44433995+mann2108@users.noreply.github.com> Date: Thu, 2 Apr 2020 04:07:01 +0530 Subject: [PATCH 202/277] resolve compile error --- math/binary_exponent.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/math/binary_exponent.cpp b/math/binary_exponent.cpp index 0f9d442a5..512365c4a 100644 --- a/math/binary_exponent.cpp +++ b/math/binary_exponent.cpp @@ -20,6 +20,6 @@ int main() { /// Give two nos as a^b (where '^' denotes power exponent operation std::cin >> a >> b; ///Result of a^b - std::cout << binExpo(a,b) << endl; + std::cout << binExpo(a,b) << std::endl; } From 55ff267e5ea7bfc5ee7bd5102d6bab2fdccd8b83 Mon Sep 17 00:00:00 2001 From: Mann Mehta <44433995+mann2108@users.noreply.github.com> Date: Thu, 2 Apr 2020 04:09:04 +0530 Subject: [PATCH 203/277] Added comments --- math/binary_exponent.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/math/binary_exponent.cpp b/math/binary_exponent.cpp index 512365c4a..c193b79b9 100644 --- a/math/binary_exponent.cpp +++ b/math/binary_exponent.cpp @@ -1,4 +1,4 @@ -/// C++ Program to find Binary Exponent recursively. +///C++ Program to find Binary Exponent recursively. #include /* @@ -8,6 +8,7 @@ * (instead of O(n) multiplications required by the naive approach). */ +///Function to calculate exponent in O(log(n)) using binary exponent. int binExpo(int a,int b) { if (b == 0) return 1; int res = binExpo(a,b/2); From 48287888973106ee513219eb60a1c70a01e42cf1 Mon Sep 17 00:00:00 2001 From: Mann Mehta <44433995+mann2108@users.noreply.github.com> Date: Thu, 2 Apr 2020 04:10:26 +0530 Subject: [PATCH 204/277] Resolve type error --- math/binary_exponent.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/math/binary_exponent.cpp b/math/binary_exponent.cpp index c193b79b9..a8f45e3c5 100644 --- a/math/binary_exponent.cpp +++ b/math/binary_exponent.cpp @@ -18,7 +18,7 @@ int binExpo(int a,int b) { int main() { int a,b; - /// Give two nos as a^b (where '^' denotes power exponent operation + /// Give two nos as a^b (where '^' denotes power exponent operation) std::cin >> a >> b; ///Result of a^b std::cout << binExpo(a,b) << std::endl; From 7b19550f7fb14ba340bf162936f95ab39eca22b6 Mon Sep 17 00:00:00 2001 From: Mann Mehta <44433995+mann2108@users.noreply.github.com> Date: Thu, 2 Apr 2020 04:28:03 +0530 Subject: [PATCH 205/277] format binary_exponent.cpp --- math/binary_exponent.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/math/binary_exponent.cpp b/math/binary_exponent.cpp index a8f45e3c5..bd9c1ce38 100644 --- a/math/binary_exponent.cpp +++ b/math/binary_exponent.cpp @@ -1,4 +1,4 @@ -///C++ Program to find Binary Exponent recursively. +/// C++ Program to find Binary Exponent recursively. #include /* @@ -8,7 +8,7 @@ * (instead of O(n) multiplications required by the naive approach). */ -///Function to calculate exponent in O(log(n)) using binary exponent. +/// Function to calculate exponent in O(log(n)) using binary exponent. int binExpo(int a,int b) { if (b == 0) return 1; int res = binExpo(a,b/2); @@ -20,7 +20,7 @@ int main() { int a,b; /// Give two nos as a^b (where '^' denotes power exponent operation) std::cin >> a >> b; - ///Result of a^b + /// Result of a^b std::cout << binExpo(a,b) << std::endl; } From 3bb191c116a72d5ce7b6742dc04545a0078f11ab Mon Sep 17 00:00:00 2001 From: Mann Mehta <44433995+mann2108@users.noreply.github.com> Date: Thu, 2 Apr 2020 04:31:44 +0530 Subject: [PATCH 206/277] resolve format error --- math/binary_exponent.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/math/binary_exponent.cpp b/math/binary_exponent.cpp index bd9c1ce38..7ca388451 100644 --- a/math/binary_exponent.cpp +++ b/math/binary_exponent.cpp @@ -9,18 +9,18 @@ */ /// Function to calculate exponent in O(log(n)) using binary exponent. -int binExpo(int a,int b) { +int binExpo(int a, int b) { if (b == 0) return 1; - int res = binExpo(a,b/2); + int res = binExpo(a, b/2); if (b%2) return res*res*a; else return res*res; } int main() { - int a,b; + int a, b; /// Give two nos as a^b (where '^' denotes power exponent operation) std::cin >> a >> b; /// Result of a^b - std::cout << binExpo(a,b) << std::endl; + std::cout << binExpo(a, b) << std::endl; } From 331fce2203a1074ed39375f4c31eb3cb7211cf3b Mon Sep 17 00:00:00 2001 From: Mann Mehta <44433995+mann2108@users.noreply.github.com> Date: Thu, 2 Apr 2020 04:34:47 +0530 Subject: [PATCH 207/277] resolve else clause formatting error --- math/binary_exponent.cpp | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/math/binary_exponent.cpp b/math/binary_exponent.cpp index 7ca388451..8f7a90ca8 100644 --- a/math/binary_exponent.cpp +++ b/math/binary_exponent.cpp @@ -10,10 +10,16 @@ /// Function to calculate exponent in O(log(n)) using binary exponent. int binExpo(int a, int b) { - if (b == 0) return 1; + if (b == 0) { + return 1; + } int res = binExpo(a, b/2); - if (b%2) return res*res*a; - else return res*res; + if (b%2) { + return res*res*a; + } + else { + return res*res; + } } int main() { @@ -23,4 +29,3 @@ int main() { /// Result of a^b std::cout << binExpo(a, b) << std::endl; } - From 085c6943a0c860cd051f2556c6791df4e7cf46ac Mon Sep 17 00:00:00 2001 From: Mann Mehta <44433995+mann2108@users.noreply.github.com> Date: Thu, 2 Apr 2020 04:37:16 +0530 Subject: [PATCH 208/277] resolve else clause braces error --- math/binary_exponent.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/math/binary_exponent.cpp b/math/binary_exponent.cpp index 8f7a90ca8..5c71ca97c 100644 --- a/math/binary_exponent.cpp +++ b/math/binary_exponent.cpp @@ -16,8 +16,7 @@ int binExpo(int a, int b) { int res = binExpo(a, b/2); if (b%2) { return res*res*a; - } - else { + } else { return res*res; } } From bcb3677f7811b9cd78e88974c5a5ddb21e615d27 Mon Sep 17 00:00:00 2001 From: Mann Mehta Date: Sat, 4 Apr 2020 17:28:19 +0530 Subject: [PATCH 209/277] Update math/binary_exponent.cpp Co-Authored-By: John Law --- math/binary_exponent.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/math/binary_exponent.cpp b/math/binary_exponent.cpp index 5c71ca97c..c9ed944d8 100644 --- a/math/binary_exponent.cpp +++ b/math/binary_exponent.cpp @@ -2,7 +2,7 @@ #include /* - * Calculating a^b in O(log(b)) by converting b in binary no. + * Calculate a^b in O(log(b)) by converting b to a binary number * Binary exponentiation (also known as exponentiation by squaring) * is a trick which allows to calculate an using only O(logn) multiplications * (instead of O(n) multiplications required by the naive approach). From 1d4a67c6ea07b12c5d0b6683dcf402ebce9c914d Mon Sep 17 00:00:00 2001 From: Mann Mehta Date: Sat, 4 Apr 2020 17:29:11 +0530 Subject: [PATCH 210/277] Update math/binary_exponent.cpp Co-Authored-By: John Law --- math/binary_exponent.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/math/binary_exponent.cpp b/math/binary_exponent.cpp index c9ed944d8..8fb9ec1a8 100644 --- a/math/binary_exponent.cpp +++ b/math/binary_exponent.cpp @@ -23,7 +23,7 @@ int binExpo(int a, int b) { int main() { int a, b; - /// Give two nos as a^b (where '^' denotes power exponent operation) + /// Give two numbers a, b std::cin >> a >> b; /// Result of a^b std::cout << binExpo(a, b) << std::endl; From a82e679f2e4de379df42ef24da031c4ea0d1c143 Mon Sep 17 00:00:00 2001 From: Mann Mehta <44433995+mann2108@users.noreply.github.com> Date: Sat, 4 Apr 2020 18:11:57 +0530 Subject: [PATCH 211/277] Updated with changes in math/binary_exponent.cpp --- math/binary_exponent.cpp | 46 +++++++++++++++++++++++++++++++++------- 1 file changed, 38 insertions(+), 8 deletions(-) diff --git a/math/binary_exponent.cpp b/math/binary_exponent.cpp index 8fb9ec1a8..808a36ce8 100644 --- a/math/binary_exponent.cpp +++ b/math/binary_exponent.cpp @@ -1,14 +1,21 @@ -/// C++ Program to find Binary Exponent recursively. +/// C++ Program to find Binary Exponent Iteratively and Recursively. #include /* - * Calculate a^b in O(log(b)) by converting b to a binary number - * Binary exponentiation (also known as exponentiation by squaring) - * is a trick which allows to calculate an using only O(logn) multiplications - * (instead of O(n) multiplications required by the naive approach). + * Calculate a^b in O(log(b)) by converting b to a binary number. + * Binary exponentiation is also known as exponentiation by squaring. + * NOTE : This is a far better approach compared to naive method which provide O(b) operations. + * Example: + * 10 in base 2 is 1010. + * 2^10 = 2^(1010) = 2^8 * 2^2 + * 2^1 = 2 + * 2^2 = (2^1)^2 = 2^2 = 4 + * 2^4 = (2^2)^2 = 4^2 = 16 + * 2^8 = (2^4)^2 = 16^2 = 256 + * Hence to calculate 2^10 we only need to multiply 2^8 and 2^2 skipping 2^1 and 2^4. */ -/// Function to calculate exponent in O(log(n)) using binary exponent. +/// Recursive function to calculate exponent in O(log(n)) using binary exponent. int binExpo(int a, int b) { if (b == 0) { return 1; @@ -21,10 +28,33 @@ int binExpo(int a, int b) { } } +/// Iterative function to calculate exponent in O(log(n)) using binary exponent. +int binExpo_alt(int a, int b) { + int res = 1; + while (b>0) { + if (b%2) { + res = res*a; + } + a = a*a; + b /= 2; + } + return res; +} + int main() { int a, b; /// Give two numbers a, b std::cin >> a >> b; - /// Result of a^b - std::cout << binExpo(a, b) << std::endl; + if (a==0 && b==0) { + std::cout << "Math error" << std::endl; + } else if (b<0) { + std::cout << "Exponent must be positive !!" << std::endl; + } else { + int resRecurse = binExpo(a, b); + /// int resIterate = binExpo_alt(a, b); + + /// Result of a^b (where '^' denotes exponentiation) + std::cout << resRecurse << std::endl; + /// std::cout << resIterate << std::endl; + } } From 8219e124a7ccd9b01cb2932a0c7f4ec4318e4c46 Mon Sep 17 00:00:00 2001 From: Mann Mehta <44433995+mann2108@users.noreply.github.com> Date: Sat, 4 Apr 2020 18:16:40 +0530 Subject: [PATCH 212/277] Resolve typo errors --- math/binary_exponent.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/math/binary_exponent.cpp b/math/binary_exponent.cpp index 808a36ce8..b4551da25 100644 --- a/math/binary_exponent.cpp +++ b/math/binary_exponent.cpp @@ -31,7 +31,7 @@ int binExpo(int a, int b) { /// Iterative function to calculate exponent in O(log(n)) using binary exponent. int binExpo_alt(int a, int b) { int res = 1; - while (b>0) { + while (b > 0) { if (b%2) { res = res*a; } @@ -45,9 +45,9 @@ int main() { int a, b; /// Give two numbers a, b std::cin >> a >> b; - if (a==0 && b==0) { + if (a == 0 && b == 0) { std::cout << "Math error" << std::endl; - } else if (b<0) { + } else if (b < 0) { std::cout << "Exponent must be positive !!" << std::endl; } else { int resRecurse = binExpo(a, b); From e2f218da0cef3c53b8ec770a261a6ea0fb51b46f Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 4 Apr 2020 15:02:02 +0000 Subject: [PATCH 213/277] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 061d35009..a68f12cbc 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -91,6 +91,7 @@ * [Quadratic Probing Hash Table](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/quadratic_probing_hash_table.cpp) ## Math + * [Binary Exponent](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/binary_exponent.cpp) * [Eulers Totient Function](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/eulers_totient_function.cpp) * [Factorial](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/factorial.cpp) * [Fast Power](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/fast_power.cpp) From 98c7558087b2d33a267696bee13c5511c6a9e22a Mon Sep 17 00:00:00 2001 From: Stepfen Shawn Date: Sun, 12 Apr 2020 21:16:18 +0800 Subject: [PATCH 214/277] Update the copyright year --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index 38c6144c1..1f8bce116 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2019 TheAlgorithms +Copyright (c) 2020 TheAlgorithms Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal From 877125eb8acff2dc638f3e95451e28f6d93f81bb Mon Sep 17 00:00:00 2001 From: Mann Mehta <44433995+mann2108@users.noreply.github.com> Date: Wed, 15 Apr 2020 03:00:23 +0530 Subject: [PATCH 215/277] Added number-of-divisors.cpp in math directory --- math/number-of-divisors.cpp | 47 +++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 math/number-of-divisors.cpp diff --git a/math/number-of-divisors.cpp b/math/number-of-divisors.cpp new file mode 100644 index 000000000..fd2d40707 --- /dev/null +++ b/math/number-of-divisors.cpp @@ -0,0 +1,47 @@ +/// C++ Program to calculate number of divisors. + +#include +#include + +/** + * This algorithm use the prime factorization approach. + * Any number can be written in multiplication of its prime factors. + * Let N = P1^E1 * P2^E2 ... Pk^Ek + * Therefore. number-of-divisors(N) = (E1+1) * (E2+1) ... (Ek+1). + * Where P1, P2 ... Pk are prime factors and E1, E2 ... Ek are exponents respectively. + * + * Example:- N=36 + * 36 = (3^2 * 2^2) + * numbe-of-divisors(36) = (2+1) * (2+1) = 9. + * list of divisors of 36 = 1, 2, 3, 4, 6, 9, 12, 18, 36. +**/ + +int number_of_divisors(int n) { + std::vector prime_exponent_count; + for (int i=2; i*i <= n; i++) { + int prime_count = 0; + while (n % i == 0) { + prime_count += 1; + n /= i; + } + if (prime_count != 0) { + prime_exponent_count.push_back(prime_count); + } + } + int divisors_count = 1; + // If n is prime at that time vector prime_exponent_count will remain empty. + for (int i=0; i> n; + std::cout << number_of_divisors(n) << std::endl; +} From 5ee32c63de337d260456fb625e35b8ffa13fadad Mon Sep 17 00:00:00 2001 From: Mann Mehta <44433995+mann2108@users.noreply.github.com> Date: Wed, 15 Apr 2020 03:08:49 +0530 Subject: [PATCH 216/277] Resolve typo errors --- math/number-of-divisors.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/math/number-of-divisors.cpp b/math/number-of-divisors.cpp index fd2d40707..1b87b3e5b 100644 --- a/math/number-of-divisors.cpp +++ b/math/number-of-divisors.cpp @@ -12,7 +12,7 @@ * * Example:- N=36 * 36 = (3^2 * 2^2) - * numbe-of-divisors(36) = (2+1) * (2+1) = 9. + * number-of-divisors(36) = (2+1) * (2+1) = 9. * list of divisors of 36 = 1, 2, 3, 4, 6, 9, 12, 18, 36. **/ @@ -30,10 +30,10 @@ int number_of_divisors(int n) { } int divisors_count = 1; // If n is prime at that time vector prime_exponent_count will remain empty. - for (int i=0; i Date: Wed, 15 Apr 2020 03:13:10 +0530 Subject: [PATCH 217/277] Renamed file name to number_of_divisors.cpp from number-of-divisors.cpp --- math/{number-of-divisors.cpp => number_of_divisors.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename math/{number-of-divisors.cpp => number_of_divisors.cpp} (100%) diff --git a/math/number-of-divisors.cpp b/math/number_of_divisors.cpp similarity index 100% rename from math/number-of-divisors.cpp rename to math/number_of_divisors.cpp From 4da35f1edf90e531a44aab300f2d59af331c1546 Mon Sep 17 00:00:00 2001 From: Mann Mehta <44433995+mann2108@users.noreply.github.com> Date: Wed, 15 Apr 2020 09:10:00 +0530 Subject: [PATCH 218/277] Modified number_of_divisors.cpp --- math/number_of_divisors.cpp | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/math/number_of_divisors.cpp b/math/number_of_divisors.cpp index 1b87b3e5b..5bf1e717a 100644 --- a/math/number_of_divisors.cpp +++ b/math/number_of_divisors.cpp @@ -12,11 +12,11 @@ * * Example:- N=36 * 36 = (3^2 * 2^2) - * number-of-divisors(36) = (2+1) * (2+1) = 9. - * list of divisors of 36 = 1, 2, 3, 4, 6, 9, 12, 18, 36. + * number_of_positive_divisors(36) = (2+1) * (2+1) = 9. + * list of positive divisors of 36 = 1, 2, 3, 4, 6, 9, 12, 18, 36. **/ -int number_of_divisors(int n) { +int number_of_positive_divisors(int n) { std::vector prime_exponent_count; for (int i=2; i*i <= n; i++) { int prime_count = 0; @@ -28,20 +28,28 @@ int number_of_divisors(int n) { prime_exponent_count.push_back(prime_count); } } + if(n > 1) { + prime_exponent_count.push_back(1); + } + int divisors_count = 1; - // If n is prime at that time vector prime_exponent_count will remain empty. + for (int i=0; i < prime_exponent_count.size(); i++) { divisors_count = divisors_count * (prime_exponent_count[i]+1); } - if (divisors_count == 1 && n != 1) { - // Prime number has exactly 2 divisors 1 and itself. - divisors_count = 2; - } + return divisors_count; } int main() { int n; std::cin >> n; - std::cout << number_of_divisors(n) << std::endl; + if(n < 0) { + n = -n; + } + if(n == 0) { + std::cout << "All non-zero numbers are divisors of 0 !" << std::endl; + } else { + std::cout << "Number of positive divisors is : " << number_of_positive_divisors(n) << std::endl; + } } From 30ee76234725af798b9a18cc316bde3e4f77db76 Mon Sep 17 00:00:00 2001 From: Mann Mehta <44433995+mann2108@users.noreply.github.com> Date: Wed, 15 Apr 2020 09:11:53 +0530 Subject: [PATCH 219/277] Renamed to number_of_positive_divisors.cpp from number_of_divisors.cpp --- math/{number_of_divisors.cpp => number_of_positive_divisors.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename math/{number_of_divisors.cpp => number_of_positive_divisors.cpp} (100%) diff --git a/math/number_of_divisors.cpp b/math/number_of_positive_divisors.cpp similarity index 100% rename from math/number_of_divisors.cpp rename to math/number_of_positive_divisors.cpp From 583264da0f721cbeb6d8a8a1ea18e74e955708b9 Mon Sep 17 00:00:00 2001 From: Mann Mehta <44433995+mann2108@users.noreply.github.com> Date: Wed, 15 Apr 2020 09:14:50 +0530 Subject: [PATCH 220/277] Resolve errors --- math/number_of_positive_divisors.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/math/number_of_positive_divisors.cpp b/math/number_of_positive_divisors.cpp index 5bf1e717a..461c0ca82 100644 --- a/math/number_of_positive_divisors.cpp +++ b/math/number_of_positive_divisors.cpp @@ -28,7 +28,7 @@ int number_of_positive_divisors(int n) { prime_exponent_count.push_back(prime_count); } } - if(n > 1) { + if (n > 1) { prime_exponent_count.push_back(1); } @@ -44,12 +44,13 @@ int number_of_positive_divisors(int n) { int main() { int n; std::cin >> n; - if(n < 0) { + if (n < 0) { n = -n; } - if(n == 0) { + if (n == 0) { std::cout << "All non-zero numbers are divisors of 0 !" << std::endl; } else { - std::cout << "Number of positive divisors is : " << number_of_positive_divisors(n) << std::endl; + std::cout << "Number of positive divisors is : "; + std::cout << number_of_positive_divisors(n) << std::endl; } } From 2d54bfa1e3c1c175a99cc1129e191ae8bd6c24d9 Mon Sep 17 00:00:00 2001 From: Mann Mehta <44433995+mann2108@users.noreply.github.com> Date: Wed, 15 Apr 2020 09:23:00 +0530 Subject: [PATCH 221/277] Modified description --- math/number_of_positive_divisors.cpp | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/math/number_of_positive_divisors.cpp b/math/number_of_positive_divisors.cpp index 461c0ca82..48ab63c36 100644 --- a/math/number_of_positive_divisors.cpp +++ b/math/number_of_positive_divisors.cpp @@ -10,10 +10,20 @@ * Therefore. number-of-divisors(N) = (E1+1) * (E2+1) ... (Ek+1). * Where P1, P2 ... Pk are prime factors and E1, E2 ... Ek are exponents respectively. * - * Example:- N=36 + * Example:- + * N = 36 * 36 = (3^2 * 2^2) * number_of_positive_divisors(36) = (2+1) * (2+1) = 9. * list of positive divisors of 36 = 1, 2, 3, 4, 6, 9, 12, 18, 36. + * + * Similarly if N is -36 at that time number of positive divisors remain same. + * + * Example:- + * N = -36 + * -36 = -1 * (3^2 * 2^2) + * number_of_positive_divisors(-36) = (2+1) * (2+1) = 9. + * list of positive divisors of -36 = 1, 2, 3, 4, 6, 9, 12, 18, 36. + * **/ int number_of_positive_divisors(int n) { From 273c3e6ffc225a7cc17710a6bf96456e36859e91 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 16 Apr 2020 06:35:46 +0000 Subject: [PATCH 222/277] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index a68f12cbc..db60543ff 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -96,6 +96,7 @@ * [Factorial](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/factorial.cpp) * [Fast Power](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/fast_power.cpp) * [Greatest Common Divisor](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/greatest_common_divisor.cpp) + * [Greatest Common Divisor Euclidean](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/greatest_common_divisor_euclidean.cpp) * [Power For Huge Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/power_for_huge_numbers.cpp) * [Prime Factorization](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/prime_factorization.cpp) * [Prime Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/prime_numbers.cpp) From db7bb002b0889a10405a17c6a1963c79a76e3f70 Mon Sep 17 00:00:00 2001 From: 1pierres1u <1pierres1u@gmail.com> Date: Thu, 16 Apr 2020 06:32:46 -0400 Subject: [PATCH 223/277] feat: add brute force string searching (#694) * feat: add brute force string searching algorithm * feat: add brute force string searching algorithm --- strings/brute_force_string_searching.cpp | 52 ++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 strings/brute_force_string_searching.cpp diff --git a/strings/brute_force_string_searching.cpp b/strings/brute_force_string_searching.cpp new file mode 100644 index 000000000..3288b36b0 --- /dev/null +++ b/strings/brute_force_string_searching.cpp @@ -0,0 +1,52 @@ +#include +#include +#include + +using std::string; + +int brute_force(string text, string pattern); +std::vector> test_set = { + // {text, pattern, expected output} + {"a", "aa", "-1"}, + {"a", "a", "0"}, + {"ba", "b", "0"}, + {"bba", "bb", "0"}, + {"bbca", "c", "2"}, + {"ab", "b", "1"} +}; + +int main() { + for (size_t i = 0 ; i < test_set.size(); i++) { + int output = brute_force(test_set[i][0], test_set[i][1]); + if (std::to_string(output) == test_set[i][2]) + std::cout << "success\n"; + else + std::cout << "failure\n"; + } + return 0; +} + +/* + *@description Find a pattern in a string by comparing the pattern + * to every substring. + *@param text Any string that might contain the pattern. + *@param pattern String that we are searching for. + *@return Index where the pattern starts in the text or + * -1 if the pattern was not found. + */ + +int brute_force(string text, string pattern) { + size_t pat_l = pattern.length(); + size_t txt_l = text.length(); + int index = -1; + if (pat_l <= txt_l) { + for (size_t i = 0; i < txt_l-pat_l+1; i++) { + string s = text.substr(i, pat_l); + if (s == pattern) { + index = i; + break; + } + } + } + return index; +} From 48822d41a1b078577d011245b8e77c9f0abb1626 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 16 Apr 2020 10:33:07 +0000 Subject: [PATCH 224/277] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index db60543ff..d43ec0763 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -177,4 +177,5 @@ * [Tim Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Tim%20Sort.cpp) ## Strings + * [Brute Force String Searching](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/strings/brute_force_string_searching.cpp) * [Knuth Morris Pratt](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/strings/knuth_morris_pratt.cpp) From 9bfecf247375cab1a48290f71b05780e90db189d Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 16 Apr 2020 14:18:23 +0000 Subject: [PATCH 225/277] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index d43ec0763..4bce1d7b8 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -97,6 +97,7 @@ * [Fast Power](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/fast_power.cpp) * [Greatest Common Divisor](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/greatest_common_divisor.cpp) * [Greatest Common Divisor Euclidean](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/greatest_common_divisor_euclidean.cpp) + * [Number Of Positive Divisors](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/number_of_positive_divisors.cpp) * [Power For Huge Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/power_for_huge_numbers.cpp) * [Prime Factorization](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/prime_factorization.cpp) * [Prime Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/prime_numbers.cpp) From 8f3efd170fe447dbc5b15593020f9b574020fc3d Mon Sep 17 00:00:00 2001 From: nikhil kala Date: Fri, 17 Apr 2020 18:27:25 +0530 Subject: [PATCH 226/277] Delete eulerTotient.cpp already present --- Math/eulerTotient.cpp | 37 ------------------------------------- 1 file changed, 37 deletions(-) delete mode 100644 Math/eulerTotient.cpp diff --git a/Math/eulerTotient.cpp b/Math/eulerTotient.cpp deleted file mode 100644 index c71219641..000000000 --- a/Math/eulerTotient.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include -#include -using namespace std; - -/* -this function calculate euler totien function -*/ - -long long eulerTotient(long long n){ - - if(n == 1) return 1; - long long result = 1LL; - long long temp = n; - for(int i = 2; i <= floor(sqrt(n)) + 10; i++) { - if( temp % i == 0) { - int j = 0; - while(temp % i == 0){ - j ++; - temp /= i; - } - result = result * pow(i,j-1) * (i-1); - } - } - - if(temp == n){ - return n-1; - } - - return result; -} - -int main(){ - long long n; - cin >> n; - cout << eulerTotient(n); - -} \ No newline at end of file From 179dc38927145bf91fb0b326bafca6e24994632c Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 17 Apr 2020 13:00:33 +0000 Subject: [PATCH 227/277] updating DIRECTORY.md --- DIRECTORY.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 4bce1d7b8..d9ae84a3b 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -93,6 +93,11 @@ ## Math * [Binary Exponent](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/binary_exponent.cpp) * [Eulers Totient Function](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/eulers_totient_function.cpp) + +## Math + * [Extendedeuclidian](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/Math/extendedEuclidian.cpp) + +## Math * [Factorial](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/factorial.cpp) * [Fast Power](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/fast_power.cpp) * [Greatest Common Divisor](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/greatest_common_divisor.cpp) From 1e45e2e227a2f9a60c55cba41f1caac0aaf05fba Mon Sep 17 00:00:00 2001 From: nikhil kala Date: Fri, 17 Apr 2020 18:31:45 +0530 Subject: [PATCH 228/277] Revert "added Euler totient function" --- Math/extendedEuclidian.cpp | 51 -------------------------------------- 1 file changed, 51 deletions(-) delete mode 100644 Math/extendedEuclidian.cpp diff --git a/Math/extendedEuclidian.cpp b/Math/extendedEuclidian.cpp deleted file mode 100644 index ad9846a87..000000000 --- a/Math/extendedEuclidian.cpp +++ /dev/null @@ -1,51 +0,0 @@ -#include -#include - -using namespace std; - -/* - for numbers a, b returns x, y such as x * a + y * b = gcd(a,b) -*/ - -pair extendedEuclidian(int a, int b) { - int a_old = a, b_old = b; - if(a < b) swap(a,b); - - int x = 0, y = 1, old_x = 1, old_y = 0; - - int quotient, residue; - while (b) { - quotient = a / b; - residue = a % b; - - a = b; - b = residue; - - int temp; - - temp = x; - x = old_x - quotient * x; - old_x = temp; - - - temp = y; - y = old_y - quotient * y; - old_y = temp; - } - - if(b_old > a_old) swap(old_x, old_y); - - return make_pair(old_x, old_y); - -} - -int main() { - - int a, b; - cin >> a >> b; - pair result = extendedEuclidian(a, b); - - cout<< result.first << " " << result.second; - - -} \ No newline at end of file From f51c5e11ef180e040834bf4d57a9a06868e1cbbb Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 17 Apr 2020 13:02:35 +0000 Subject: [PATCH 229/277] updating DIRECTORY.md --- DIRECTORY.md | 5 ----- 1 file changed, 5 deletions(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index d9ae84a3b..4bce1d7b8 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -93,11 +93,6 @@ ## Math * [Binary Exponent](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/binary_exponent.cpp) * [Eulers Totient Function](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/eulers_totient_function.cpp) - -## Math - * [Extendedeuclidian](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/Math/extendedEuclidian.cpp) - -## Math * [Factorial](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/factorial.cpp) * [Fast Power](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/fast_power.cpp) * [Greatest Common Divisor](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/greatest_common_divisor.cpp) From 7a697b96ebcfcedf0c860114f2b9aafafe9b6664 Mon Sep 17 00:00:00 2001 From: Mann Mehta <44433995+mann2108@users.noreply.github.com> Date: Fri, 17 Apr 2020 23:22:10 +0530 Subject: [PATCH 230/277] Added tree_height.cpp in dynamic_programming directory --- dynamic_programming/tree_height.cpp | 67 +++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 dynamic_programming/tree_height.cpp diff --git a/dynamic_programming/tree_height.cpp b/dynamic_programming/tree_height.cpp new file mode 100644 index 000000000..2ef9f6b6b --- /dev/null +++ b/dynamic_programming/tree_height.cpp @@ -0,0 +1,67 @@ +/// C++ Program to find height of the tree using bottom0-up DP. + +/** + * Given a rooted tree with node 1. + * Task is to find the height of the tree. +**/ + +#include +#include + + +/// global declarations + +/// no of nodes max limit. +const int MAX = 1e5; + +/// adjacency list +std::vector adj[MAX]; + +std::vector visited; +std::vector dp; + +void dp_with_dfs(int u) { + visited[u] = true; + int child_height = 1; + for (int v : adj[u]) { + if (!visited[v]) { + dp_with_dfs(v); + + /// selected maximum subtree height from all childs. + child_height = std::max(child_height, dp[v]+1); + } + } + + /// assigned the max child height to current visited node. + dp[u] = child_height; +} + +int main(){ + + /// number of nodes + int n; + std::cin >> n; + + int u,v; + + /// a valid tree contains exactly n-1 edges where n denotes the nodes. + for (int i=0; i < n-1; i++) { + std::cin >> u >> v; + + /// undirected tree u -> v and v -> u. + adj[u].push_back(v); + adj[v].push_back(u); + } + + /// initialize all nodes as unvisited. + visited.assign(n+1,false); + + /// initialize depth of all nodes to 0. + dp.assign(n+1,0); + + /// call to dp_with_dfs which will initialize the height of all nodes in dp vector. + dp_with_dfs (1); + + std::cout << dp[1] << std::endl; +} + From 3235335a6065805c5860dd4c72fbcf816ceac376 Mon Sep 17 00:00:00 2001 From: Mann Mehta <44433995+mann2108@users.noreply.github.com> Date: Fri, 17 Apr 2020 23:33:28 +0530 Subject: [PATCH 231/277] Modified with typo errors --- dynamic_programming/tree_height.cpp | 35 ++++++++++++----------------- 1 file changed, 14 insertions(+), 21 deletions(-) diff --git a/dynamic_programming/tree_height.cpp b/dynamic_programming/tree_height.cpp index 2ef9f6b6b..fb3025039 100644 --- a/dynamic_programming/tree_height.cpp +++ b/dynamic_programming/tree_height.cpp @@ -1,22 +1,24 @@ -/// C++ Program to find height of the tree using bottom0-up DP. +/// C++ Program to find height of the tree using bottom - up DP. /** * Given a rooted tree with node 1. * Task is to find the height of the tree. + * Example: - + * 4 + * 1 2 + * 1 3 + * 2 4 + * Height of the tree : - 3 **/ #include #include - /// global declarations - /// no of nodes max limit. const int MAX = 1e5; - /// adjacency list std::vector adj[MAX]; - std::vector visited; std::vector dp; @@ -31,37 +33,28 @@ void dp_with_dfs(int u) { child_height = std::max(child_height, dp[v]+1); } } - /// assigned the max child height to current visited node. dp[u] = child_height; } -int main(){ - +int main() { /// number of nodes int n; std::cin >> n; - - int u,v; - - /// a valid tree contains exactly n-1 edges where n denotes the nodes. + int u, v; + /// Tree contains exactly n-1 edges where n denotes the nodes. for (int i=0; i < n-1; i++) { std::cin >> u >> v; - /// undirected tree u -> v and v -> u. adj[u].push_back(v); adj[v].push_back(u); } - /// initialize all nodes as unvisited. - visited.assign(n+1,false); - + visited.assign(n+1, false); /// initialize depth of all nodes to 0. - dp.assign(n+1,0); - - /// call to dp_with_dfs which will initialize the height of all nodes in dp vector. + dp.assign(n+1, 0); + /// function call which will initialize the height of all nodes. dp_with_dfs (1); - - std::cout << dp[1] << std::endl; + std::cout << "Height of the Tree : " << dp[1] << std::endl; } From a3b2f4d17e24b169f3e47650284af1580662d0e0 Mon Sep 17 00:00:00 2001 From: Mann Mehta <44433995+mann2108@users.noreply.github.com> Date: Fri, 17 Apr 2020 23:35:39 +0530 Subject: [PATCH 232/277] Fixed presentation error around brackets --- dynamic_programming/tree_height.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dynamic_programming/tree_height.cpp b/dynamic_programming/tree_height.cpp index fb3025039..1207d89a6 100644 --- a/dynamic_programming/tree_height.cpp +++ b/dynamic_programming/tree_height.cpp @@ -25,7 +25,7 @@ std::vector dp; void dp_with_dfs(int u) { visited[u] = true; int child_height = 1; - for (int v : adj[u]) { + for(int v : adj[u]) { if (!visited[v]) { dp_with_dfs(v); @@ -43,7 +43,7 @@ int main() { std::cin >> n; int u, v; /// Tree contains exactly n-1 edges where n denotes the nodes. - for (int i=0; i < n-1; i++) { + for(int i=0; i < n-1; i++) { std::cin >> u >> v; /// undirected tree u -> v and v -> u. adj[u].push_back(v); From ff8a511413301d165b41d30502faa16d09e0e464 Mon Sep 17 00:00:00 2001 From: Mann Mehta <44433995+mann2108@users.noreply.github.com> Date: Fri, 17 Apr 2020 23:37:29 +0530 Subject: [PATCH 233/277] Fixed presentation error around brackets --- dynamic_programming/tree_height.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/dynamic_programming/tree_height.cpp b/dynamic_programming/tree_height.cpp index 1207d89a6..fe9b48130 100644 --- a/dynamic_programming/tree_height.cpp +++ b/dynamic_programming/tree_height.cpp @@ -25,7 +25,7 @@ std::vector dp; void dp_with_dfs(int u) { visited[u] = true; int child_height = 1; - for(int v : adj[u]) { + for (int v : adj[u]) { if (!visited[v]) { dp_with_dfs(v); @@ -43,7 +43,7 @@ int main() { std::cin >> n; int u, v; /// Tree contains exactly n-1 edges where n denotes the nodes. - for(int i=0; i < n-1; i++) { + for (int i = 0; i < n-1; i++) { std::cin >> u >> v; /// undirected tree u -> v and v -> u. adj[u].push_back(v); @@ -54,7 +54,7 @@ int main() { /// initialize depth of all nodes to 0. dp.assign(n+1, 0); /// function call which will initialize the height of all nodes. - dp_with_dfs (1); + dp_with_dfs(1); std::cout << "Height of the Tree : " << dp[1] << std::endl; } From 5a2238d8ef0d2029db66751a8f6d56af463987c2 Mon Sep 17 00:00:00 2001 From: Mann Mehta <44433995+mann2108@users.noreply.github.com> Date: Fri, 17 Apr 2020 23:41:59 +0530 Subject: [PATCH 234/277] Modified comments --- dynamic_programming/tree_height.cpp | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/dynamic_programming/tree_height.cpp b/dynamic_programming/tree_height.cpp index fe9b48130..18a02e68e 100644 --- a/dynamic_programming/tree_height.cpp +++ b/dynamic_programming/tree_height.cpp @@ -1,6 +1,6 @@ -/// C++ Program to find height of the tree using bottom - up DP. +// C++ Program to find height of the tree using bottom - up DP. -/** +/* * Given a rooted tree with node 1. * Task is to find the height of the tree. * Example: - @@ -9,15 +9,15 @@ * 1 3 * 2 4 * Height of the tree : - 3 -**/ +*/ #include #include -/// global declarations -/// no of nodes max limit. +// global declarations +// no of nodes max limit. const int MAX = 1e5; -/// adjacency list +// adjacency list std::vector adj[MAX]; std::vector visited; std::vector dp; @@ -29,31 +29,31 @@ void dp_with_dfs(int u) { if (!visited[v]) { dp_with_dfs(v); - /// selected maximum subtree height from all childs. + // selected maximum subtree height from all child. child_height = std::max(child_height, dp[v]+1); } } - /// assigned the max child height to current visited node. + // assigned the max child height to current visited node. dp[u] = child_height; } int main() { - /// number of nodes + // number of nodes int n; std::cin >> n; int u, v; - /// Tree contains exactly n-1 edges where n denotes the nodes. + // Tree contains exactly n-1 edges where n denotes the nodes. for (int i = 0; i < n-1; i++) { std::cin >> u >> v; - /// undirected tree u -> v and v -> u. + // undirected tree u -> v and v -> u. adj[u].push_back(v); adj[v].push_back(u); } - /// initialize all nodes as unvisited. + // initialize all nodes as unvisited. visited.assign(n+1, false); - /// initialize depth of all nodes to 0. + // initialize depth of all nodes to 0. dp.assign(n+1, 0); - /// function call which will initialize the height of all nodes. + // function call which will initialize the height of all nodes. dp_with_dfs(1); std::cout << "Height of the Tree : " << dp[1] << std::endl; } From f659bcc9fce6d62a97bd08d941f4ba0aaac811a5 Mon Sep 17 00:00:00 2001 From: stepfencurryxiao Date: Sat, 18 Apr 2020 10:43:43 +0800 Subject: [PATCH 235/277] Don't use bits/stdc++.h --- backtracking/knight_tour.cpp | 2 +- computer_oriented_statistical_methods/Gaussian_elimination.cpp | 2 +- dynamic_programming/Cut Rod.cpp | 2 +- dynamic_programming/Fibonacci_Bottom_Up.cpp | 2 +- dynamic_programming/Fibonacci_Top_Down.cpp | 2 +- dynamic_programming/Longest Increasing Subsequence (nlogn).cpp | 2 +- dynamic_programming/longest_common_string.cpp | 2 +- graph/BFS.cpp | 2 +- graph/DFS.cpp | 2 +- graph/Kruskal.cpp | 2 +- graph/lca.cpp | 3 ++- others/matrix_exponentiation.cpp | 2 +- range_queries/MO.cpp | 2 +- range_queries/bit.cpp | 2 +- range_queries/segTree.cpp | 3 ++- sorting/Tim Sort.cpp | 2 +- 16 files changed, 18 insertions(+), 16 deletions(-) diff --git a/backtracking/knight_tour.cpp b/backtracking/knight_tour.cpp index f1bc9f72f..fbb8a6f96 100644 --- a/backtracking/knight_tour.cpp +++ b/backtracking/knight_tour.cpp @@ -1,4 +1,4 @@ -#include +#include # define n 8 /** diff --git a/computer_oriented_statistical_methods/Gaussian_elimination.cpp b/computer_oriented_statistical_methods/Gaussian_elimination.cpp index 7f0a1832b..58e634505 100644 --- a/computer_oriented_statistical_methods/Gaussian_elimination.cpp +++ b/computer_oriented_statistical_methods/Gaussian_elimination.cpp @@ -1,4 +1,4 @@ -#include +#include using namespace std; int main() diff --git a/dynamic_programming/Cut Rod.cpp b/dynamic_programming/Cut Rod.cpp index 826332a23..afca3dced 100644 --- a/dynamic_programming/Cut Rod.cpp +++ b/dynamic_programming/Cut Rod.cpp @@ -3,7 +3,7 @@ contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces.*/ -#include +#include using namespace std; int cutrod(int p[], int n) { diff --git a/dynamic_programming/Fibonacci_Bottom_Up.cpp b/dynamic_programming/Fibonacci_Bottom_Up.cpp index a72a6c895..ab5b5b41f 100644 --- a/dynamic_programming/Fibonacci_Bottom_Up.cpp +++ b/dynamic_programming/Fibonacci_Bottom_Up.cpp @@ -1,4 +1,4 @@ -#include +#include using namespace std; int fib(int n) { diff --git a/dynamic_programming/Fibonacci_Top_Down.cpp b/dynamic_programming/Fibonacci_Top_Down.cpp index 449aefbdc..9d76366f7 100644 --- a/dynamic_programming/Fibonacci_Top_Down.cpp +++ b/dynamic_programming/Fibonacci_Top_Down.cpp @@ -1,4 +1,4 @@ -#include +#include using namespace std; int arr[1000000]; int fib(int n) diff --git a/dynamic_programming/Longest Increasing Subsequence (nlogn).cpp b/dynamic_programming/Longest Increasing Subsequence (nlogn).cpp index 56dcca969..5ee24e6a7 100644 --- a/dynamic_programming/Longest Increasing Subsequence (nlogn).cpp +++ b/dynamic_programming/Longest Increasing Subsequence (nlogn).cpp @@ -2,7 +2,7 @@ // in O(n log n) // tested on : https://cses.fi/problemset/task/1145/ -#include +#include using namespace std; int LIS(int arr[], int n) diff --git a/dynamic_programming/longest_common_string.cpp b/dynamic_programming/longest_common_string.cpp index e18b9eb01..c1e89d6db 100644 --- a/dynamic_programming/longest_common_string.cpp +++ b/dynamic_programming/longest_common_string.cpp @@ -1,4 +1,4 @@ -#include +#include using namespace std; int max(int a,int b) diff --git a/graph/BFS.cpp b/graph/BFS.cpp index 51efaed8c..e4e12886b 100644 --- a/graph/BFS.cpp +++ b/graph/BFS.cpp @@ -1,4 +1,4 @@ -#include +#include using namespace std; class graph { diff --git a/graph/DFS.cpp b/graph/DFS.cpp index 8df8c478b..656711ac8 100644 --- a/graph/DFS.cpp +++ b/graph/DFS.cpp @@ -1,4 +1,4 @@ -#include +#include using namespace std; int v = 4; void DFSUtil_(int graph[4][4], bool visited[], int s) diff --git a/graph/Kruskal.cpp b/graph/Kruskal.cpp index 6210c2895..21b04ce49 100644 --- a/graph/Kruskal.cpp +++ b/graph/Kruskal.cpp @@ -1,4 +1,4 @@ -#include "bits/stdc++.h" +#include //#include //using namespace boost::multiprecision; const int mx = 1e6 + 5; diff --git a/graph/lca.cpp b/graph/lca.cpp index a69a1a5b3..9c7be456e 100644 --- a/graph/lca.cpp +++ b/graph/lca.cpp @@ -1,4 +1,5 @@ -#include +//#include +#include using namespace std; // Find the lowest common ancestor using binary lifting in O(nlogn) diff --git a/others/matrix_exponentiation.cpp b/others/matrix_exponentiation.cpp index 16a272988..25c411dda 100644 --- a/others/matrix_exponentiation.cpp +++ b/others/matrix_exponentiation.cpp @@ -18,7 +18,7 @@ Steps for Matrix Expo The first element of this matrix is the required result. */ -#include +#include using std::cin; using std::cout; using std::vector; diff --git a/range_queries/MO.cpp b/range_queries/MO.cpp index 44a0883e3..7172bd632 100644 --- a/range_queries/MO.cpp +++ b/range_queries/MO.cpp @@ -1,4 +1,4 @@ -#include "bits/stdc++.h" +#include using namespace std; const int N = 1e6 + 5; int a[N], bucket[N], cnt[N]; diff --git a/range_queries/bit.cpp b/range_queries/bit.cpp index 449177a77..e5e36ed24 100644 --- a/range_queries/bit.cpp +++ b/range_queries/bit.cpp @@ -1,5 +1,5 @@ // Binary Indexed Tree. -#include +#include using namespace std; diff --git a/range_queries/segTree.cpp b/range_queries/segTree.cpp index d3d27a526..ee81453e1 100644 --- a/range_queries/segTree.cpp +++ b/range_queries/segTree.cpp @@ -1,4 +1,5 @@ -#include +//#include +#incldue #define MAX 4000000 using namespace std; typedef long long ll; diff --git a/sorting/Tim Sort.cpp b/sorting/Tim Sort.cpp index a97a123a1..14d3a04d0 100644 --- a/sorting/Tim Sort.cpp +++ b/sorting/Tim Sort.cpp @@ -1,5 +1,5 @@ // C++ program to perform TimSort. -#include +#include using namespace std; const int RUN = 32; From f4c936d8be2fe3cc99f7c4bbaa84c2edb262bf44 Mon Sep 17 00:00:00 2001 From: Mann Mehta Date: Sat, 18 Apr 2020 08:17:56 +0530 Subject: [PATCH 236/277] Update dynamic_programming/tree_height.cpp Co-Authored-By: Christian Clauss --- dynamic_programming/tree_height.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/dynamic_programming/tree_height.cpp b/dynamic_programming/tree_height.cpp index 18a02e68e..b9142b117 100644 --- a/dynamic_programming/tree_height.cpp +++ b/dynamic_programming/tree_height.cpp @@ -29,7 +29,7 @@ void dp_with_dfs(int u) { if (!visited[v]) { dp_with_dfs(v); - // selected maximum subtree height from all child. + // select maximum sub-tree height from all children. child_height = std::max(child_height, dp[v]+1); } } @@ -57,4 +57,3 @@ int main() { dp_with_dfs(1); std::cout << "Height of the Tree : " << dp[1] << std::endl; } - From e4fa1dbcaff547dbb14febd704b3acf218b32d3d Mon Sep 17 00:00:00 2001 From: faizan Ahamed Date: Sun, 19 Apr 2020 18:49:08 +0530 Subject: [PATCH 237/277] Create stairs_pattern.cpp --- others/stairs_pattern.cpp | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 others/stairs_pattern.cpp diff --git a/others/stairs_pattern.cpp b/others/stairs_pattern.cpp new file mode 100644 index 000000000..fcc768016 --- /dev/null +++ b/others/stairs_pattern.cpp @@ -0,0 +1,38 @@ +/* +This program is use to print the following pattern + ** + ** + **** + **** + ****** + ****** +******** +******** +where number of pairs line is given by user +*/ +#include +using namespace std; +int main() +{ + int l, st = 2, x, r, z, n, sp; + cout << "enter Index "; + cin >> x; + z = x; + for (r = 1; r <= x; r++) + { + z = z - 1; + for (n = 1; n <= 2; n++) + { + for (sp = 1; sp <= z; sp++) + { + cout << " "; + } + for (l = 1; l <= st; l++) + { + cout << "*"; + } + cout << endl; + } + st = st + 2; + } +} From e15dd6ec99c14efff4b9fd4f5fc6c4c040d22993 Mon Sep 17 00:00:00 2001 From: faizan Ahamed Date: Sun, 19 Apr 2020 20:23:48 +0530 Subject: [PATCH 238/277] Update stairs_pattern.cpp --- others/stairs_pattern.cpp | 40 +++++++++++++++++---------------------- 1 file changed, 17 insertions(+), 23 deletions(-) diff --git a/others/stairs_pattern.cpp b/others/stairs_pattern.cpp index fcc768016..07ebc7571 100644 --- a/others/stairs_pattern.cpp +++ b/others/stairs_pattern.cpp @@ -12,27 +12,21 @@ where number of pairs line is given by user */ #include using namespace std; -int main() -{ - int l, st = 2, x, r, z, n, sp; - cout << "enter Index "; - cin >> x; - z = x; - for (r = 1; r <= x; r++) - { - z = z - 1; - for (n = 1; n <= 2; n++) - { - for (sp = 1; sp <= z; sp++) - { - cout << " "; - } - for (l = 1; l <= st; l++) - { - cout << "*"; - } - cout << endl; - } - st = st + 2; - } +int main(){ +int l, st = 2, x, r, z, n, sp; +std::cout << "enter Index "; +std::cin >> x; +z = x; +for (r = 1; r <= x; r++){ +z = z - 1; +for (n = 1; n <= 2; n++){ +for (sp = 1; sp <= z; sp++){ +std::cout << " "; } +for (l = 1; l <= st; l++){ +std::cout << "*"; +} +std::cout <<"\n"; +} +st = st + 2; +}} From 2b01decae19a35c93af94a10b6bd61973a3e7708 Mon Sep 17 00:00:00 2001 From: faizan Ahamed Date: Sun, 19 Apr 2020 20:24:28 +0530 Subject: [PATCH 239/277] Update stairs_pattern.cpp --- others/stairs_pattern.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/others/stairs_pattern.cpp b/others/stairs_pattern.cpp index 07ebc7571..e4fdba79f 100644 --- a/others/stairs_pattern.cpp +++ b/others/stairs_pattern.cpp @@ -11,7 +11,6 @@ This program is use to print the following pattern where number of pairs line is given by user */ #include -using namespace std; int main(){ int l, st = 2, x, r, z, n, sp; std::cout << "enter Index "; From 9ac7981fed8260be2df07d35651b6b79d6775d3c Mon Sep 17 00:00:00 2001 From: faizan Ahamed Date: Sun, 19 Apr 2020 20:39:06 +0530 Subject: [PATCH 240/277] Update stairs_pattern.cpp --- others/stairs_pattern.cpp | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/others/stairs_pattern.cpp b/others/stairs_pattern.cpp index e4fdba79f..c93782805 100644 --- a/others/stairs_pattern.cpp +++ b/others/stairs_pattern.cpp @@ -8,21 +8,20 @@ This program is use to print the following pattern ****** ******** ******** -where number of pairs line is given by user -*/ -#include -int main(){ +where number of pairs line is given by user */ +#include +int main() { int l, st = 2, x, r, z, n, sp; std::cout << "enter Index "; std::cin >> x; z = x; -for (r = 1; r <= x; r++){ +for (r = 1; r <= x; r++) { z = z - 1; -for (n = 1; n <= 2; n++){ -for (sp = 1; sp <= z; sp++){ +for (n = 1; n <= 2; n++) { +for (sp = 1; sp <= z; sp++) { std::cout << " "; } -for (l = 1; l <= st; l++){ +for (l = 1; l <= st; l++) { std::cout << "*"; } std::cout <<"\n"; From c2316e1efcb59d7d349b4dc09471e3eece59b5b0 Mon Sep 17 00:00:00 2001 From: faizan Ahamed Date: Sun, 19 Apr 2020 20:50:42 +0530 Subject: [PATCH 241/277] Update stairs_pattern.cpp --- others/stairs_pattern.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/others/stairs_pattern.cpp b/others/stairs_pattern.cpp index c93782805..36c106bb2 100644 --- a/others/stairs_pattern.cpp +++ b/others/stairs_pattern.cpp @@ -8,7 +8,8 @@ This program is use to print the following pattern ****** ******** ******** -where number of pairs line is given by user */ +where number of pairs line is given by user +*/ #include int main() { int l, st = 2, x, r, z, n, sp; From 039ca7bdea9fe931e929bfc802f108bcdc536e98 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Sun, 19 Apr 2020 17:48:48 +0200 Subject: [PATCH 242/277] Update others/stairs_pattern.cpp --- others/stairs_pattern.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/others/stairs_pattern.cpp b/others/stairs_pattern.cpp index 36c106bb2..281446a2f 100644 --- a/others/stairs_pattern.cpp +++ b/others/stairs_pattern.cpp @@ -10,7 +10,7 @@ This program is use to print the following pattern ******** where number of pairs line is given by user */ -#include +#include int main() { int l, st = 2, x, r, z, n, sp; std::cout << "enter Index "; From 86dad95364c782e86d09bbe867342c67fe4e44c4 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 20 Apr 2020 10:05:31 +0000 Subject: [PATCH 243/277] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 4bce1d7b8..7f7fc460e 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -133,6 +133,7 @@ * [Smallest-Circle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/smallest-circle.cpp) * [Sparse Matrix](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Sparse%20matrix.cpp) * [Spiral Print](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/spiral_print.cpp) + * [Stairs Pattern](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/stairs_pattern.cpp) * [Strassen Matrix Multiplication](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Strassen%20Matrix%20Multiplication.cpp) * [String Fibonacci](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/String%20Fibonacci.cpp) * [Tower Of Hanoi](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Tower%20of%20Hanoi.cpp) From 1ff60ebf205b58b2332cf7f7da711b3d732999f9 Mon Sep 17 00:00:00 2001 From: Mann Mehta Date: Mon, 20 Apr 2020 16:45:13 +0530 Subject: [PATCH 244/277] Update dynamic_programming/tree_height.cpp Co-Authored-By: Christian Clauss --- dynamic_programming/tree_height.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dynamic_programming/tree_height.cpp b/dynamic_programming/tree_height.cpp index b9142b117..8c5242ccd 100644 --- a/dynamic_programming/tree_height.cpp +++ b/dynamic_programming/tree_height.cpp @@ -22,7 +22,7 @@ std::vector adj[MAX]; std::vector visited; std::vector dp; -void dp_with_dfs(int u) { +void depth_first_search(int u) { visited[u] = true; int child_height = 1; for (int v : adj[u]) { From 847bfd6527620fd780b4f8d9bd569ce990586d38 Mon Sep 17 00:00:00 2001 From: Mann Mehta Date: Mon, 20 Apr 2020 17:04:32 +0530 Subject: [PATCH 245/277] Update tree_height.cpp --- dynamic_programming/tree_height.cpp | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/dynamic_programming/tree_height.cpp b/dynamic_programming/tree_height.cpp index 8c5242ccd..e9039c5a1 100644 --- a/dynamic_programming/tree_height.cpp +++ b/dynamic_programming/tree_height.cpp @@ -27,7 +27,7 @@ void depth_first_search(int u) { int child_height = 1; for (int v : adj[u]) { if (!visited[v]) { - dp_with_dfs(v); + depth_first_search(v); // select maximum sub-tree height from all children. child_height = std::max(child_height, dp[v]+1); @@ -39,21 +39,24 @@ void depth_first_search(int u) { int main() { // number of nodes - int n; - std::cin >> n; + int no_of_nodes; + std::cout << "Enter number of nodes of the tree : " << std::endl; + std::cin >> no_of_nodes; + // u,v denotes an undirected edge of tree. int u, v; // Tree contains exactly n-1 edges where n denotes the nodes. - for (int i = 0; i < n-1; i++) { + std::cout << "Enter edges of the tree : " << std::endl; + for (int i = 0; i < no_of_nodes-1; i++) { std::cin >> u >> v; // undirected tree u -> v and v -> u. adj[u].push_back(v); adj[v].push_back(u); } // initialize all nodes as unvisited. - visited.assign(n+1, false); + visited.assign(no_of_nodes+1, false); // initialize depth of all nodes to 0. - dp.assign(n+1, 0); + dp.assign(no_of_nodes+1, 0); // function call which will initialize the height of all nodes. - dp_with_dfs(1); + depth_first_search(1); std::cout << "Height of the Tree : " << dp[1] << std::endl; } From 6faf95adfd92e9cbea4d60deb61fa530531b2305 Mon Sep 17 00:00:00 2001 From: John Law Date: Mon, 20 Apr 2020 20:31:48 +0200 Subject: [PATCH 246/277] Update example --- dynamic_programming/tree_height.cpp | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/dynamic_programming/tree_height.cpp b/dynamic_programming/tree_height.cpp index e9039c5a1..095d79f7b 100644 --- a/dynamic_programming/tree_height.cpp +++ b/dynamic_programming/tree_height.cpp @@ -1,4 +1,4 @@ -// C++ Program to find height of the tree using bottom - up DP. +// C++ Program to find height of the tree using bottom-up dynamic programming. /* * Given a rooted tree with node 1. @@ -8,7 +8,14 @@ * 1 2 * 1 3 * 2 4 - * Height of the tree : - 3 + * which can be represented as + * 1 + * / \ + * 2 3 + * | + * 4 + * + * Height of the tree : - 2 */ #include @@ -42,6 +49,7 @@ int main() { int no_of_nodes; std::cout << "Enter number of nodes of the tree : " << std::endl; std::cin >> no_of_nodes; + // u,v denotes an undirected edge of tree. int u, v; // Tree contains exactly n-1 edges where n denotes the nodes. From 2893c222f078051f44d8b2b23ab21677f2aa8925 Mon Sep 17 00:00:00 2001 From: John Law Date: Mon, 20 Apr 2020 20:34:04 +0200 Subject: [PATCH 247/277] Fix cpplint --- dynamic_programming/tree_height.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dynamic_programming/tree_height.cpp b/dynamic_programming/tree_height.cpp index 095d79f7b..a43f91a56 100644 --- a/dynamic_programming/tree_height.cpp +++ b/dynamic_programming/tree_height.cpp @@ -49,7 +49,7 @@ int main() { int no_of_nodes; std::cout << "Enter number of nodes of the tree : " << std::endl; std::cin >> no_of_nodes; - + // u,v denotes an undirected edge of tree. int u, v; // Tree contains exactly n-1 edges where n denotes the nodes. From f36be23cb238908c2e74637dac1df806cfba01ee Mon Sep 17 00:00:00 2001 From: John Law Date: Mon, 20 Apr 2020 20:37:57 +0200 Subject: [PATCH 248/277] Enhance readability --- dynamic_programming/tree_height.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/dynamic_programming/tree_height.cpp b/dynamic_programming/tree_height.cpp index a43f91a56..6acc15959 100644 --- a/dynamic_programming/tree_height.cpp +++ b/dynamic_programming/tree_height.cpp @@ -46,24 +46,24 @@ void depth_first_search(int u) { int main() { // number of nodes - int no_of_nodes; + int number_of_nodes; std::cout << "Enter number of nodes of the tree : " << std::endl; - std::cin >> no_of_nodes; + std::cin >> number_of_nodes; - // u,v denotes an undirected edge of tree. + // u, v denotes an undirected edge of tree. int u, v; - // Tree contains exactly n-1 edges where n denotes the nodes. + // Tree contains exactly n-1 edges where n denotes the number of nodes. std::cout << "Enter edges of the tree : " << std::endl; - for (int i = 0; i < no_of_nodes-1; i++) { + for (int i = 0; i < number_of_nodes - 1; i++) { std::cin >> u >> v; // undirected tree u -> v and v -> u. adj[u].push_back(v); adj[v].push_back(u); } // initialize all nodes as unvisited. - visited.assign(no_of_nodes+1, false); + visited.assign(number_of_nodes+1, false); // initialize depth of all nodes to 0. - dp.assign(no_of_nodes+1, 0); + dp.assign(number_of_nodes+1, 0); // function call which will initialize the height of all nodes. depth_first_search(1); std::cout << "Height of the Tree : " << dp[1] << std::endl; From a3268742f3b30bdb8d12bf38b81b32212df731b7 Mon Sep 17 00:00:00 2001 From: faizan Ahamed Date: Tue, 21 Apr 2020 00:45:22 +0530 Subject: [PATCH 249/277] Create searching_of_element_in_dynamic_Array.cpp --- .../searching_of_element_in_dynamic_Array.cpp | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 dynamic_programming/searching_of_element_in_dynamic_Array.cpp diff --git a/dynamic_programming/searching_of_element_in_dynamic_Array.cpp b/dynamic_programming/searching_of_element_in_dynamic_Array.cpp new file mode 100644 index 000000000..23b2b1066 --- /dev/null +++ b/dynamic_programming/searching_of_element_in_dynamic_Array.cpp @@ -0,0 +1,67 @@ +/* +this program is use to find any elemet in any row with variable array size +aplication of pointer is use in it +important point start from here to: +the index value of array can be go to 1 to 100000 +check till array[1000] +end here +how to work example: +Question: +number of array 2 +quarry 3 +array 1 is {1 2 3 4 5} +array 2 is {6 7} +i) what is 2nd element in 1st array +ii) what is 1st element in 2nd array +iii) what is 5th element in 1st array +output: +Enter Number of array you want to Store : 2 +Enter Number of Question or Quary you want to do Related to Array : 3 +Enter number of element in 1 rows : 5 +Enter the element of Array 1 2 3 4 5 +Enter number of element in 2 rows : 2 +Enter the element of Array 6 7 +enter the number of row which element You want to find : 1 +enter the position of element which You want to find : 2 +The element is 2 +enter the number of row which element You want to find : 2 +enter the position of element which You want to find : 1 +The element is 6 +enter the number of row which element You want to find : 1 +enter the position of element which You want to find : 5 +The element is 5 +*/ +#include +int main() { +long long int r, mr = 0, x, q, i, z; +std::cout << "Enter Number of array you want to Store :"; +std::cin >> x; +std::cout << "Enter Number of Question or Quary you want to do Related to Array :"; +std::cin >> q; +//create a Array in run time because use can change the size of each array which he/she is going to store +//create a 2D array +int** ar = new int* [x](); +for (r = 0; r < x; r++) { +std::cout << "Enter number of element in " << r + 1 << " rows :"; +std::cin >> mr; +//creating a 1D array +int* ac = new int[mr](); +std::cout << "Enter the element of Array "; +for (i = 0; i < mr; i++) { +//entering the value of rows in array in Horizontal +std::cin >> ac[i]; +} +//Change the position of Array so that new arrays entery will be done +ar[r] = ac; +} +for (z = 0; z < q; z++) { +long int r1 = 0, q1 = 0; +std::cout << "enter the number of row which element You want to find :"; +std::cin >> r1; +r1 = r1 - 1; +std::cout << "enter the position of element which You want to find :"; +std::cin>> q1; +q1 = q1 - 1; +//use this to find desire position of element in desire array +std::cout <<"The element is "<< ar[r1][q1] < Date: Tue, 21 Apr 2020 01:03:38 +0530 Subject: [PATCH 250/277] Update searching_of_element_in_dynamic_Array.cpp --- .../searching_of_element_in_dynamic_Array.cpp | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/dynamic_programming/searching_of_element_in_dynamic_Array.cpp b/dynamic_programming/searching_of_element_in_dynamic_Array.cpp index 23b2b1066..d7799d37e 100644 --- a/dynamic_programming/searching_of_element_in_dynamic_Array.cpp +++ b/dynamic_programming/searching_of_element_in_dynamic_Array.cpp @@ -33,35 +33,36 @@ The element is 5 */ #include int main() { -long long int r, mr = 0, x, q, i, z; +int64_t r, mr = 0, x, q, i, z; std::cout << "Enter Number of array you want to Store :"; std::cin >> x; std::cout << "Enter Number of Question or Quary you want to do Related to Array :"; std::cin >> q; -//create a Array in run time because use can change the size of each array which he/she is going to store -//create a 2D array +// create a Array in run time because use can +// change the size of each array which he/she is going to store +// create a 2D array int** ar = new int* [x](); for (r = 0; r < x; r++) { std::cout << "Enter number of element in " << r + 1 << " rows :"; std::cin >> mr; -//creating a 1D array +// creating a 1D array int* ac = new int[mr](); std::cout << "Enter the element of Array "; for (i = 0; i < mr; i++) { -//entering the value of rows in array in Horizontal +// entering the value of rows in array in Horizontal std::cin >> ac[i]; } -//Change the position of Array so that new arrays entery will be done +// Change the position of Array so that new arrays entery will be done ar[r] = ac; } for (z = 0; z < q; z++) { -long int r1 = 0, q1 = 0; +int64_t r1 = 0, q1 = 0; std::cout << "enter the number of row which element You want to find :"; std::cin >> r1; r1 = r1 - 1; std::cout << "enter the position of element which You want to find :"; std::cin>> q1; q1 = q1 - 1; -//use this to find desire position of element in desire array +// use this to find desire position of element in desire array std::cout <<"The element is "<< ar[r1][q1] < Date: Tue, 21 Apr 2020 01:07:37 +0530 Subject: [PATCH 251/277] Update searching_of_element_in_dynamic_Array.cpp --- dynamic_programming/searching_of_element_in_dynamic_Array.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/dynamic_programming/searching_of_element_in_dynamic_Array.cpp b/dynamic_programming/searching_of_element_in_dynamic_Array.cpp index d7799d37e..86243c9e7 100644 --- a/dynamic_programming/searching_of_element_in_dynamic_Array.cpp +++ b/dynamic_programming/searching_of_element_in_dynamic_Array.cpp @@ -36,7 +36,9 @@ int main() { int64_t r, mr = 0, x, q, i, z; std::cout << "Enter Number of array you want to Store :"; std::cin >> x; -std::cout << "Enter Number of Question or Quary you want to do Related to Array :"; +std::cout << "Enter Number of "; +std::cout<<"Question or Quary you "; +std::cout<<"want to do Related to Array :"; std::cin >> q; // create a Array in run time because use can // change the size of each array which he/she is going to store From db53fd1cf7b7061d509fc84690f17096f36ca622 Mon Sep 17 00:00:00 2001 From: faizan Ahamed Date: Tue, 21 Apr 2020 01:09:01 +0530 Subject: [PATCH 252/277] Update searching_of_element_in_dynamic_Array.cpp --- dynamic_programming/searching_of_element_in_dynamic_Array.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dynamic_programming/searching_of_element_in_dynamic_Array.cpp b/dynamic_programming/searching_of_element_in_dynamic_Array.cpp index 86243c9e7..436088aea 100644 --- a/dynamic_programming/searching_of_element_in_dynamic_Array.cpp +++ b/dynamic_programming/searching_of_element_in_dynamic_Array.cpp @@ -37,8 +37,8 @@ int64_t r, mr = 0, x, q, i, z; std::cout << "Enter Number of array you want to Store :"; std::cin >> x; std::cout << "Enter Number of "; -std::cout<<"Question or Quary you "; -std::cout<<"want to do Related to Array :"; +std::cout << "Question or Quary you "; +std::cout << "want to do Related to Array :"; std::cin >> q; // create a Array in run time because use can // change the size of each array which he/she is going to store From 15146a35fd5e98fb4f1eaefe4248f83efb3fa73f Mon Sep 17 00:00:00 2001 From: faizan Ahamed Date: Tue, 21 Apr 2020 01:12:58 +0530 Subject: [PATCH 253/277] Update searching_of_element_in_dynamic_Array.cpp --- dynamic_programming/searching_of_element_in_dynamic_Array.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dynamic_programming/searching_of_element_in_dynamic_Array.cpp b/dynamic_programming/searching_of_element_in_dynamic_Array.cpp index 436088aea..c13de8e06 100644 --- a/dynamic_programming/searching_of_element_in_dynamic_Array.cpp +++ b/dynamic_programming/searching_of_element_in_dynamic_Array.cpp @@ -63,7 +63,7 @@ std::cout << "enter the number of row which element You want to find :"; std::cin >> r1; r1 = r1 - 1; std::cout << "enter the position of element which You want to find :"; -std::cin>> q1; +std::cin >> q1; q1 = q1 - 1; // use this to find desire position of element in desire array std::cout <<"The element is "<< ar[r1][q1] < Date: Tue, 21 Apr 2020 01:18:18 +0530 Subject: [PATCH 254/277] Rename searching_of_element_in_dynamic_Array.cpp to searching_of_element_in_dynamic_array.cpp --- ...ynamic_Array.cpp => searching_of_element_in_dynamic_array.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename dynamic_programming/{searching_of_element_in_dynamic_Array.cpp => searching_of_element_in_dynamic_array.cpp} (100%) diff --git a/dynamic_programming/searching_of_element_in_dynamic_Array.cpp b/dynamic_programming/searching_of_element_in_dynamic_array.cpp similarity index 100% rename from dynamic_programming/searching_of_element_in_dynamic_Array.cpp rename to dynamic_programming/searching_of_element_in_dynamic_array.cpp From 7320fbe6c003e03a7ede89cbd7bfbf1360f24e11 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 21 Apr 2020 13:13:18 +0000 Subject: [PATCH 255/277] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 7f7fc460e..c00df4136 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -66,6 +66,7 @@ * [Longest Increasing Subsequence](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Longest%20Increasing%20Subsequence.cpp) * [Longest Common String](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/longest_common_string.cpp) * [Matrix-Chain-Multiplication](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Matrix-Chain-Multiplication.cpp) + * [Tree Height](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/tree_height.cpp) ## Graph * [Bfs](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/BFS.cpp) From 52782f57f65ac1c92b2b465a661e5b295fff4e46 Mon Sep 17 00:00:00 2001 From: Faizan Ahamed Date: Tue, 21 Apr 2020 20:23:36 +0530 Subject: [PATCH 256/277] Update searching_of_element_in_dynamic_array.cpp --- .../searching_of_element_in_dynamic_array.cpp | 70 +++++++++++-------- 1 file changed, 39 insertions(+), 31 deletions(-) diff --git a/dynamic_programming/searching_of_element_in_dynamic_array.cpp b/dynamic_programming/searching_of_element_in_dynamic_array.cpp index c13de8e06..b4403d05c 100644 --- a/dynamic_programming/searching_of_element_in_dynamic_array.cpp +++ b/dynamic_programming/searching_of_element_in_dynamic_array.cpp @@ -1,37 +1,39 @@ /* -this program is use to find any elemet in any row with variable array size -aplication of pointer is use in it -important point start from here to: -the index value of array can be go to 1 to 100000 -check till array[1000] -end here -how to work example: -Question: -number of array 2 -quarry 3 -array 1 is {1 2 3 4 5} -array 2 is {6 7} -i) what is 2nd element in 1st array -ii) what is 1st element in 2nd array -iii) what is 5th element in 1st array -output: -Enter Number of array you want to Store : 2 -Enter Number of Question or Quary you want to do Related to Array : 3 -Enter number of element in 1 rows : 5 -Enter the element of Array 1 2 3 4 5 -Enter number of element in 2 rows : 2 -Enter the element of Array 6 7 -enter the number of row which element You want to find : 1 -enter the position of element which You want to find : 2 -The element is 2 -enter the number of row which element You want to find : 2 -enter the position of element which You want to find : 1 -The element is 6 -enter the number of row which element You want to find : 1 -enter the position of element which You want to find : 5 -The element is 5 +*this program is use to find any elemet in any row with variable array size +*aplication of pointer is use in it +*important point start from here to: +*the index value of array can be go to 1 to 100000 +*check till array[1000] +*end here +*how to work example: +**Question: +***number of array 2 +***quarry 3 +***array 1 is {1 2 3 4 5} +***array 2 is {6 7} +****i) what is 2nd element in 1st array +****ii) what is 1st element in 2nd array +****iii) what is 5th element in 1st array +*****output: +*****Enter Number of array you want to Store : 2 +*****Enter Number of Question or Quary you want to do Related to Array : 3 +*****Enter number of element in 1 rows : 5 +*****Enter the element of Array 1 2 3 4 5 +*****Enter number of element in 2 rows : 2 +*****Enter the element of Array 6 7 +*****enter the number of row which element You want to find : 1 +*****enter the position of element which You want to find : 2 +*****The element is 2 +*****enter the number of row which element You want to find : 2 +*****enter the position of element which You want to find : 1 +*****The element is 6 +*****enter the number of row which element You want to find : 1 +*****enter the position of element which You want to find : 5 +*****The element is 5 */ #include +// this is main fuction +// *** int main() { int64_t r, mr = 0, x, q, i, z; std::cout << "Enter Number of array you want to Store :"; @@ -44,12 +46,16 @@ std::cin >> q; // change the size of each array which he/she is going to store // create a 2D array int** ar = new int* [x](); +// this for loop is use for entering different variable size array +// *** for (r = 0; r < x; r++) { std::cout << "Enter number of element in " << r + 1 << " rows :"; std::cin >> mr; // creating a 1D array int* ac = new int[mr](); std::cout << "Enter the element of Array "; +// this for loop is use for storing values in array +// *** for (i = 0; i < mr; i++) { // entering the value of rows in array in Horizontal std::cin >> ac[i]; @@ -57,6 +63,8 @@ std::cin >> ac[i]; // Change the position of Array so that new arrays entery will be done ar[r] = ac; } +// this for loop is use for display result of querry +// *** for (z = 0; z < q; z++) { int64_t r1 = 0, q1 = 0; std::cout << "enter the number of row which element You want to find :"; From 56413a542d6441e1b10a7aef87b890f0aa21b964 Mon Sep 17 00:00:00 2001 From: Pooja Date: Tue, 21 Apr 2020 21:25:55 +0530 Subject: [PATCH 257/277] Update queue_using_linkedlist.cpp --- data_structure/queue_using_linkedlist.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/data_structure/queue_using_linkedlist.cpp b/data_structure/queue_using_linkedlist.cpp index a27d3db37..8bc130c27 100644 --- a/data_structure/queue_using_linkedlist.cpp +++ b/data_structure/queue_using_linkedlist.cpp @@ -94,4 +94,5 @@ int main(){ std::cout<<"\nWrong choice "; } + return 0; } From ae1c2a243fea3e650b53aef9ba7a6badfa9bbc0c Mon Sep 17 00:00:00 2001 From: Faizan Ahamed Date: Tue, 21 Apr 2020 21:30:57 +0530 Subject: [PATCH 258/277] Update searching_of_element_in_dynamic_array.cpp --- .../searching_of_element_in_dynamic_array.cpp | 89 ++++++++++--------- 1 file changed, 48 insertions(+), 41 deletions(-) diff --git a/dynamic_programming/searching_of_element_in_dynamic_array.cpp b/dynamic_programming/searching_of_element_in_dynamic_array.cpp index b4403d05c..840af3e66 100644 --- a/dynamic_programming/searching_of_element_in_dynamic_array.cpp +++ b/dynamic_programming/searching_of_element_in_dynamic_array.cpp @@ -32,47 +32,54 @@ *****The element is 5 */ #include + // this is main fuction // *** -int main() { -int64_t r, mr = 0, x, q, i, z; -std::cout << "Enter Number of array you want to Store :"; -std::cin >> x; -std::cout << "Enter Number of "; -std::cout << "Question or Quary you "; -std::cout << "want to do Related to Array :"; -std::cin >> q; -// create a Array in run time because use can -// change the size of each array which he/she is going to store -// create a 2D array -int** ar = new int* [x](); -// this for loop is use for entering different variable size array -// *** -for (r = 0; r < x; r++) { -std::cout << "Enter number of element in " << r + 1 << " rows :"; -std::cin >> mr; -// creating a 1D array -int* ac = new int[mr](); -std::cout << "Enter the element of Array "; -// this for loop is use for storing values in array -// *** -for (i = 0; i < mr; i++) { -// entering the value of rows in array in Horizontal -std::cin >> ac[i]; +int main() +{ + int64_t r, mr = 0, x, q, i, z; + std::cout << "Enter Number of array you want to Store :"; + std::cin >> x; + std::cout << "Enter Number of "; + std::cout << "Question or Quary you "; + std::cout << "want to do Related to Array :"; + std::cin >> q; + + // create a Array in run time because use can + // change the size of each array which he/she is going to store + // create a 2D array + int** ar = new int* [x](); + + // this for loop is use for entering different variable size array + // *** + for (r = 0; r < x; r++) { + std::cout << "Enter number of element in " << r + 1 << " rows :"; + std::cin >> mr; + // creating a 1D array + int* ac = new int[mr](); + std::cout << "Enter the element of Array "; + + // this for loop is use for storing values in array + // *** + for (i = 0; i < mr; i++) { + // entering the value of rows in array in Horizontal + std::cin >> ac[i]; + } + // Change the position of Array so that new arrays entery will be done + ar[r] = ac; + } + + // this for loop is use for display result of querry + // *** + for (z = 0; z < q; z++) { + int64_t r1 = 0, q1 = 0; + std::cout << "enter the number of row which element You want to find :"; + std::cin >> r1; + r1 = r1 - 1; + std::cout << "enter the position of element which You want to find :"; + std::cin >> q1; + q1 = q1 - 1; + // use this to find desire position of element in desire array + std::cout <<"The element is "<< ar[r1][q1] <> r1; -r1 = r1 - 1; -std::cout << "enter the position of element which You want to find :"; -std::cin >> q1; -q1 = q1 - 1; -// use this to find desire position of element in desire array -std::cout <<"The element is "<< ar[r1][q1] < Date: Tue, 21 Apr 2020 21:53:25 +0530 Subject: [PATCH 259/277] Update searching_of_element_in_dynamic_array.cpp --- .../searching_of_element_in_dynamic_array.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/dynamic_programming/searching_of_element_in_dynamic_array.cpp b/dynamic_programming/searching_of_element_in_dynamic_array.cpp index 840af3e66..377d61428 100644 --- a/dynamic_programming/searching_of_element_in_dynamic_array.cpp +++ b/dynamic_programming/searching_of_element_in_dynamic_array.cpp @@ -64,10 +64,11 @@ int main() for (i = 0; i < mr; i++) { // entering the value of rows in array in Horizontal std::cin >> ac[i]; - } + } + // Change the position of Array so that new arrays entery will be done ar[r] = ac; - } + } // this for loop is use for display result of querry // *** @@ -81,5 +82,5 @@ int main() q1 = q1 - 1; // use this to find desire position of element in desire array std::cout <<"The element is "<< ar[r1][q1] < Date: Tue, 21 Apr 2020 21:55:39 +0530 Subject: [PATCH 260/277] Update searching_of_element_in_dynamic_array.cpp --- dynamic_programming/searching_of_element_in_dynamic_array.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/dynamic_programming/searching_of_element_in_dynamic_array.cpp b/dynamic_programming/searching_of_element_in_dynamic_array.cpp index 377d61428..1a0a61a15 100644 --- a/dynamic_programming/searching_of_element_in_dynamic_array.cpp +++ b/dynamic_programming/searching_of_element_in_dynamic_array.cpp @@ -35,8 +35,7 @@ // this is main fuction // *** -int main() -{ +int main() { int64_t r, mr = 0, x, q, i, z; std::cout << "Enter Number of array you want to Store :"; std::cin >> x; From d2164cbe43cdf8c1d1a2507fa482c613a57b1347 Mon Sep 17 00:00:00 2001 From: Faizan Ahamed Date: Tue, 21 Apr 2020 22:09:03 +0530 Subject: [PATCH 261/277] Update searching_of_element_in_dynamic_array.cpp --- .../searching_of_element_in_dynamic_array.cpp | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/dynamic_programming/searching_of_element_in_dynamic_array.cpp b/dynamic_programming/searching_of_element_in_dynamic_array.cpp index 1a0a61a15..ff260bebd 100644 --- a/dynamic_programming/searching_of_element_in_dynamic_array.cpp +++ b/dynamic_programming/searching_of_element_in_dynamic_array.cpp @@ -43,12 +43,10 @@ int main() { std::cout << "Question or Quary you "; std::cout << "want to do Related to Array :"; std::cin >> q; - // create a Array in run time because use can // change the size of each array which he/she is going to store // create a 2D array int** ar = new int* [x](); - // this for loop is use for entering different variable size array // *** for (r = 0; r < x; r++) { @@ -57,7 +55,6 @@ int main() { // creating a 1D array int* ac = new int[mr](); std::cout << "Enter the element of Array "; - // this for loop is use for storing values in array // *** for (i = 0; i < mr; i++) { @@ -65,18 +62,17 @@ int main() { std::cin >> ac[i]; } - // Change the position of Array so that new arrays entery will be done + // Change the position of Array so that new arrays entery will be done ar[r] = ac; } - // this for loop is use for display result of querry // *** for (z = 0; z < q; z++) { int64_t r1 = 0, q1 = 0; - std::cout << "enter the number of row which element You want to find :"; + std::cout << "enter the number of row which element You want to find :"; std::cin >> r1; r1 = r1 - 1; - std::cout << "enter the position of element which You want to find :"; + std::cout << "enter the position of element which You want to find :"; std::cin >> q1; q1 = q1 - 1; // use this to find desire position of element in desire array From 6d1b9da209652a000fce9d1edab5ff76ed128d7b Mon Sep 17 00:00:00 2001 From: Faizan Ahamed Date: Tue, 21 Apr 2020 22:12:58 +0530 Subject: [PATCH 262/277] Update searching_of_element_in_dynamic_array.cpp --- dynamic_programming/searching_of_element_in_dynamic_array.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/dynamic_programming/searching_of_element_in_dynamic_array.cpp b/dynamic_programming/searching_of_element_in_dynamic_array.cpp index ff260bebd..9c3f62578 100644 --- a/dynamic_programming/searching_of_element_in_dynamic_array.cpp +++ b/dynamic_programming/searching_of_element_in_dynamic_array.cpp @@ -61,8 +61,7 @@ int main() { // entering the value of rows in array in Horizontal std::cin >> ac[i]; } - - // Change the position of Array so that new arrays entery will be done + // Change the position of Array so that new arrays entery will be done ar[r] = ac; } // this for loop is use for display result of querry From 5149a9f55015fd5796528fce097f4ed54d37728c Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Wed, 22 Apr 2020 00:19:29 +0000 Subject: [PATCH 263/277] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index c00df4136..bd6249d7b 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -38,6 +38,7 @@ * [Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue/queue.h) * [Test Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue/test_queue.cpp) * [Queue Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue_using_array.cpp) + * [Queue Using Linkedlist](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue_using_linkedlist.cpp) * [Stack Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Stack%20Using%20Array.cpp) * [Stack Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Stack%20Using%20Linked%20List.cpp) * Stk From 6a3c002977bb29de6758194485eeb6763f7f9563 Mon Sep 17 00:00:00 2001 From: Faizan Ahamed Date: Wed, 22 Apr 2020 11:02:19 +0530 Subject: [PATCH 264/277] Update dynamic_programming/searching_of_element_in_dynamic_array.cpp Co-Authored-By: Christian Clauss --- .../searching_of_element_in_dynamic_array.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/dynamic_programming/searching_of_element_in_dynamic_array.cpp b/dynamic_programming/searching_of_element_in_dynamic_array.cpp index 9c3f62578..38ddc1336 100644 --- a/dynamic_programming/searching_of_element_in_dynamic_array.cpp +++ b/dynamic_programming/searching_of_element_in_dynamic_array.cpp @@ -68,10 +68,12 @@ int main() { // *** for (z = 0; z < q; z++) { int64_t r1 = 0, q1 = 0; - std::cout << "enter the number of row which element You want to find :"; + std::cout << "enter the number of row which element you want to \ + find :"; std::cin >> r1; r1 = r1 - 1; - std::cout << "enter the position of element which You want to find :"; + std::cout << "enter the position of element which you want to \ + find :"; std::cin >> q1; q1 = q1 - 1; // use this to find desire position of element in desire array From 21be8043ceaefdc8efec85dfa5b5e34906780a99 Mon Sep 17 00:00:00 2001 From: Faizan Ahamed Date: Wed, 22 Apr 2020 11:11:02 +0530 Subject: [PATCH 265/277] Update searching_of_element_in_dynamic_array.cpp --- .../searching_of_element_in_dynamic_array.cpp | 30 +++++++++---------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/dynamic_programming/searching_of_element_in_dynamic_array.cpp b/dynamic_programming/searching_of_element_in_dynamic_array.cpp index 38ddc1336..9ee48dded 100644 --- a/dynamic_programming/searching_of_element_in_dynamic_array.cpp +++ b/dynamic_programming/searching_of_element_in_dynamic_array.cpp @@ -62,21 +62,19 @@ int main() { std::cin >> ac[i]; } // Change the position of Array so that new arrays entery will be done - ar[r] = ac; + ar[r] = ac; + } + // this for loop is use for display result of querry + // *** + for (z = 0; z < q; z++) { + int64_t r1 = 0, q1 = 0; + std::cout << "enter the number of row which element you want to find :"; + std::cin >> r1; + r1 = r1 - 1; + std::cout << "enter the position of element which you want to find :"; + std::cin >> q1; + q1 = q1 - 1; + // use this to find desire position of element in desire array + std::cout <<"The element is "<< ar[r1][q1] <> r1; - r1 = r1 - 1; - std::cout << "enter the position of element which you want to \ - find :"; - std::cin >> q1; - q1 = q1 - 1; - // use this to find desire position of element in desire array - std::cout <<"The element is "<< ar[r1][q1] < Date: Wed, 22 Apr 2020 11:44:47 +0300 Subject: [PATCH 266/277] fix: reverse check for empty list --- data_structure/Linked List.cpp | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/data_structure/Linked List.cpp b/data_structure/Linked List.cpp index cf976e3a5..646d69dc0 100644 --- a/data_structure/Linked List.cpp +++ b/data_structure/Linked List.cpp @@ -100,17 +100,19 @@ void show() void reverse() { node *first = start; - node *second = first->next; - while (second != NULL) - { - node *tem = second->next; - second->next = first; - first = second; - second = tem; - } + if (first != NULL){ + node *second = first->next; + while (second != NULL) + { + node *tem = second->next; + second->next = first; + first = second; + second = tem; + } - start->next = NULL; - start = first; + start->next = NULL; + start = first; + } } int main() From d2760d1e5450e488c38688bfa6a6eaa1a1136b5f Mon Sep 17 00:00:00 2001 From: Marian Gusatu <45270790+mariangusatu@users.noreply.github.com> Date: Wed, 22 Apr 2020 11:56:01 +0300 Subject: [PATCH 267/277] Update Linked List.cpp fix: reverse check for empty list + converting tabs to spaces --- data_structure/Linked List.cpp | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/data_structure/Linked List.cpp b/data_structure/Linked List.cpp index 646d69dc0..49e739a3c 100644 --- a/data_structure/Linked List.cpp +++ b/data_structure/Linked List.cpp @@ -101,15 +101,14 @@ void reverse() { node *first = start; if (first != NULL){ - node *second = first->next; - while (second != NULL) - { - node *tem = second->next; - second->next = first; - first = second; - second = tem; - } - + node *second = first->next; + while (second != NULL) + { + node *tem = second->next; + second->next = first; + first = second; + second = tem; + } start->next = NULL; start = first; } From 15a030201da2d665b0d119ca908f73c407e82928 Mon Sep 17 00:00:00 2001 From: Marian Gusatu <45270790+mariangusatu@users.noreply.github.com> Date: Wed, 22 Apr 2020 12:09:27 +0300 Subject: [PATCH 268/277] Update Linked List.cpp fix: reverse check for empty list + from tabs to spaces --- data_structure/Linked List.cpp | 237 +++++++++++++++++---------------- 1 file changed, 120 insertions(+), 117 deletions(-) diff --git a/data_structure/Linked List.cpp b/data_structure/Linked List.cpp index 49e739a3c..d7177805f 100644 --- a/data_structure/Linked List.cpp +++ b/data_structure/Linked List.cpp @@ -1,106 +1,104 @@ #include using namespace std; - struct node { - int val; - node *next; + int val; + node *next; }; node *start; void insert(int x) { - node *t = start; - if (start != NULL) - { - while (t->next != NULL) - { - t = t->next; - } - node *n = new node; - t->next = n; - n->val = x; - n->next = NULL; - } - else - { - node *n = new node; - n->val = x; - n->next = NULL; - start = n; - } + node *t = start; + if (start != NULL) + { + while (t->next != NULL) + { + t = t->next; + } + node *n = new node; + t->next = n; + n->val = x; + n->next = NULL; + } + else + { + node *n = new node; + n->val = x; + n->next = NULL; + start = n; + } } void remove(int x) { + if (start == NULL) + { + cout << "\nLinked List is empty\n"; + return; + } + else if (start->val == x) + { + node *temp = start; + start = start->next; + delete temp; + return; + } + + node *temp = start, *parent = start; - if (start == NULL) - { - cout << "\nLinked List is empty\n"; - return; - } - else if (start->val == x) - { - node *temp = start; - start = start->next; - delete temp; - return; - } - - node *temp = start, *parent = start; - - while (temp != NULL && temp->val != x) - { - parent = temp; - temp = temp->next; - } - - if (temp == NULL) - { - cout << endl - << x << " not found in list\n"; - return; - } + while (temp != NULL && temp->val != x) + { + parent = temp; + temp = temp->next; + } + if (temp == NULL) + { + cout << endl << x << " not found in list\n"; + return; + } + parent->next = temp->next; - delete temp; + delete temp; } void search(int x) { - node *t = start; - int found = 0; - while (t != NULL) - { - if (t->val == x) - { - cout << "\nFound"; - found = 1; - break; - } - t = t->next; - } - if (found == 0) - { - cout << "\nNot Found"; - } + node *t = start; + int found = 0; + while (t != NULL) + { + if (t->val == x) + { + cout << "\nFound"; + found = 1; + break; + } + t = t->next; + } + if (found == 0) + { + cout << "\nNot Found"; + } } void show() { - node *t = start; - while (t != NULL) - { - cout << t->val << "\t"; - t = t->next; - } + node *t = start; + while (t != NULL) + { + cout << t->val << "\t"; + t = t->next; + } } void reverse() { - node *first = start; - if (first != NULL){ + node *first = start; + if (first != NULL) + { node *second = first->next; while (second != NULL) { @@ -109,53 +107,58 @@ void reverse() first = second; second = tem; } - start->next = NULL; - start = first; + start->next = NULL; + start = first; + } + else + { + cout<<"\nEmpty list"; + } } int main() { - int choice, x; - do - { - cout << "\n1. Insert"; - cout << "\n2. Delete"; - cout << "\n3. Search"; - cout << "\n4. Print"; - cout << "\n5. Reverse"; - cout << "\n0. Exit"; - cout << "\n\nEnter you choice : "; - cin >> choice; - switch (choice) - { - case 1: - cout << "\nEnter the element to be inserted : "; - cin >> x; - insert(x); - break; - case 2: - cout << "\nEnter the element to be removed : "; - cin >> x; - remove(x); - break; - case 3: - cout << "\nEnter the element to be searched : "; - cin >> x; - search(x); - break; - case 4: - show(); - cout << "\n"; - break; - case 5: - cout << "The reversed list: \n"; - reverse(); - show(); - cout << "\n"; - break; - } - } while (choice != 0); + int choice, x; + do + { + cout << "\n1. Insert"; + cout << "\n2. Delete"; + cout << "\n3. Search"; + cout << "\n4. Print"; + cout << "\n5. Reverse"; + cout << "\n0. Exit"; + cout << "\n\nEnter you choice : "; + cin >> choice; + switch (choice) + { + case 1: + cout << "\nEnter the element to be inserted : "; + cin >> x; + insert(x); + break; + case 2: + cout << "\nEnter the element to be removed : "; + cin >> x; + remove(x); + break; + case 3: + cout << "\nEnter the element to be searched : "; + cin >> x; + search(x); + break; + case 4: + show(); + cout << "\n"; + break; + case 5: + cout << "The reversed list: \n"; + reverse(); + show(); + cout << "\n"; + break; + } + } while (choice != 0); - return 0; + return 0; } From 9c508e4fbb09845bfbc465124c8e62bbcfa1e4eb Mon Sep 17 00:00:00 2001 From: Marian Gusatu <45270790+mariangusatu@users.noreply.github.com> Date: Wed, 22 Apr 2020 12:18:56 +0300 Subject: [PATCH 269/277] Update Linked List.cpp fix: reverse check for empty list + cpplint coding style --- data_structure/Linked List.cpp | 82 ++++++++++++---------------------- 1 file changed, 28 insertions(+), 54 deletions(-) diff --git a/data_structure/Linked List.cpp b/data_structure/Linked List.cpp index d7177805f..14e59f47a 100644 --- a/data_structure/Linked List.cpp +++ b/data_structure/Linked List.cpp @@ -1,29 +1,23 @@ #include -using namespace std; -struct node -{ + +struct node { int val; node *next; }; node *start; -void insert(int x) -{ +void insert(int x) { node *t = start; - if (start != NULL) - { - while (t->next != NULL) - { + if (start != NULL) { + while (t->next != NULL) { t = t->next; } node *n = new node; t->next = n; n->val = x; n->next = NULL; - } - else - { + } else { node *n = new node; n->val = x; n->next = NULL; @@ -31,77 +25,62 @@ void insert(int x) } } -void remove(int x) -{ - if (start == NULL) - { +void remove(int x) { + if (start == NULL) { cout << "\nLinked List is empty\n"; return; - } - else if (start->val == x) - { + } else if (start->val == x) { node *temp = start; start = start->next; delete temp; return; } - + node *temp = start, *parent = start; - while (temp != NULL && temp->val != x) - { + while (temp != NULL && temp->val != x) { parent = temp; temp = temp->next; } - if (temp == NULL) - { + if (temp == NULL) { cout << endl << x << " not found in list\n"; return; } - - parent->next = temp->next; + + parent->next = temp->next; delete temp; } -void search(int x) -{ +void search(int x) { node *t = start; int found = 0; - while (t != NULL) - { - if (t->val == x) - { + while (t != NULL) { + if (t->val == x) { cout << "\nFound"; found = 1; break; } t = t->next; } - if (found == 0) - { + if (found == 0) { cout << "\nNot Found"; } } -void show() -{ +void show() { node *t = start; - while (t != NULL) - { + while (t != NULL) { cout << t->val << "\t"; t = t->next; } } -void reverse() -{ +void reverse() { node *first = start; - if (first != NULL) - { + if (first != NULL) { node *second = first->next; - while (second != NULL) - { + while (second != NULL) { node *tem = second->next; second->next = first; first = second; @@ -110,18 +89,14 @@ void reverse() start->next = NULL; start = first; } - else - { + else { cout<<"\nEmpty list"; - - } + } } -int main() -{ +int main() { int choice, x; - do - { + do { cout << "\n1. Insert"; cout << "\n2. Delete"; cout << "\n3. Search"; @@ -130,8 +105,7 @@ int main() cout << "\n0. Exit"; cout << "\n\nEnter you choice : "; cin >> choice; - switch (choice) - { + switch (choice) { case 1: cout << "\nEnter the element to be inserted : "; cin >> x; From 248c335bf53744b7f16f75d599d46a9d685ea74c Mon Sep 17 00:00:00 2001 From: Marian Gusatu <45270790+mariangusatu@users.noreply.github.com> Date: Wed, 22 Apr 2020 12:21:48 +0300 Subject: [PATCH 270/277] Update Linked List.cpp fix: reverse check for empty list + cpp lint final coding style --- data_structure/Linked List.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/data_structure/Linked List.cpp b/data_structure/Linked List.cpp index 14e59f47a..1d8557ba9 100644 --- a/data_structure/Linked List.cpp +++ b/data_structure/Linked List.cpp @@ -88,9 +88,8 @@ void reverse() { } start->next = NULL; start = first; - } - else { - cout<<"\nEmpty list"; + } else { + cout << "\nEmpty list"; } } From 7be0b8deb3016e263ea1ab7b1243c614a2e96fb6 Mon Sep 17 00:00:00 2001 From: Marian Gusatu <45270790+mariangusatu@users.noreply.github.com> Date: Wed, 22 Apr 2020 12:26:03 +0300 Subject: [PATCH 271/277] Update Linked List.cpp fix: reverse check for empty list + cpplint coding style --- data_structure/Linked List.cpp | 46 +++++++++++++++++----------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/data_structure/Linked List.cpp b/data_structure/Linked List.cpp index 1d8557ba9..4fcb471c3 100644 --- a/data_structure/Linked List.cpp +++ b/data_structure/Linked List.cpp @@ -27,7 +27,7 @@ void insert(int x) { void remove(int x) { if (start == NULL) { - cout << "\nLinked List is empty\n"; + std::cout << "\nLinked List is empty\n"; return; } else if (start->val == x) { node *temp = start; @@ -44,7 +44,7 @@ void remove(int x) { } if (temp == NULL) { - cout << endl << x << " not found in list\n"; + std::cout << endl << x << " not found in list\n"; return; } @@ -57,21 +57,21 @@ void search(int x) { int found = 0; while (t != NULL) { if (t->val == x) { - cout << "\nFound"; + std::cout << "\nFound"; found = 1; break; } t = t->next; } if (found == 0) { - cout << "\nNot Found"; + std::cout << "\nNot Found"; } } void show() { node *t = start; while (t != NULL) { - cout << t->val << "\t"; + std::cout << t->val << "\t"; t = t->next; } } @@ -89,46 +89,46 @@ void reverse() { start->next = NULL; start = first; } else { - cout << "\nEmpty list"; + std::cout << "\nEmpty list"; } } int main() { int choice, x; do { - cout << "\n1. Insert"; - cout << "\n2. Delete"; - cout << "\n3. Search"; - cout << "\n4. Print"; - cout << "\n5. Reverse"; - cout << "\n0. Exit"; - cout << "\n\nEnter you choice : "; - cin >> choice; + std::cout << "\n1. Insert"; + std::cout << "\n2. Delete"; + std::cout << "\n3. Search"; + std::cout << "\n4. Print"; + std::cout << "\n5. Reverse"; + std::cout << "\n0. Exit"; + std::cout << "\n\nEnter you choice : "; + std::cin >> choice; switch (choice) { case 1: - cout << "\nEnter the element to be inserted : "; - cin >> x; + std::cout << "\nEnter the element to be inserted : "; + std::cin >> x; insert(x); break; case 2: - cout << "\nEnter the element to be removed : "; - cin >> x; + std::cout << "\nEnter the element to be removed : "; + std::cin >> x; remove(x); break; case 3: - cout << "\nEnter the element to be searched : "; - cin >> x; + std::cout << "\nEnter the element to be searched : "; + std::cin >> x; search(x); break; case 4: show(); - cout << "\n"; + std::cout << "\n"; break; case 5: - cout << "The reversed list: \n"; + std::cout << "The reversed list: \n"; reverse(); show(); - cout << "\n"; + std::cout << "\n"; break; } } while (choice != 0); From 2edf620f7c7b2e8b17f04f5bcab7b822c1a1b076 Mon Sep 17 00:00:00 2001 From: Marian Gusatu <45270790+mariangusatu@users.noreply.github.com> Date: Wed, 22 Apr 2020 12:29:33 +0300 Subject: [PATCH 272/277] Update Linked List.cpp fix: reverse check for empty list + cpplint coding style --- data_structure/Linked List.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data_structure/Linked List.cpp b/data_structure/Linked List.cpp index 4fcb471c3..2af3f82a3 100644 --- a/data_structure/Linked List.cpp +++ b/data_structure/Linked List.cpp @@ -44,7 +44,7 @@ void remove(int x) { } if (temp == NULL) { - std::cout << endl << x << " not found in list\n"; + std::cout << std::endl << x << " not found in list\n"; return; } From d999b480e59995aa08c397ea4ba8482edcfd5e2d Mon Sep 17 00:00:00 2001 From: Marian Gusatu <45270790+mariangusatu@users.noreply.github.com> Date: Wed, 22 Apr 2020 12:33:03 +0300 Subject: [PATCH 273/277] Rename Linked List.cpp to linked_list.cpp fix: reverse check for empty list + cpplint identation --- data_structure/{Linked List.cpp => linked_list.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename data_structure/{Linked List.cpp => linked_list.cpp} (100%) diff --git a/data_structure/Linked List.cpp b/data_structure/linked_list.cpp similarity index 100% rename from data_structure/Linked List.cpp rename to data_structure/linked_list.cpp From 5856bc09181b3ef8387be1e9ea5c9aeb5ccc99f4 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Wed, 22 Apr 2020 12:34:03 +0000 Subject: [PATCH 274/277] updating DIRECTORY.md --- DIRECTORY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index bd6249d7b..9fb0bf77c 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -27,7 +27,7 @@ * [Main Cll](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/cll/main_cll.cpp) * [Disjoint Set](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/disjoint_set.cpp) * [Doubly Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Doubly%20Linked%20List.cpp) - * [Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Linked%20List.cpp) + * [Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/linked_list.cpp) * [Linkedlist Implentation Usingarray](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/linkedList_implentation_usingArray.cpp) * [List Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/List%20Array.cpp) * [Morrisinorder](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/MorrisInorder.cpp) From b2799b6fbbe8dd614ccd27bf96016a294adad5ff Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Wed, 22 Apr 2020 12:53:26 +0000 Subject: [PATCH 275/277] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 9fb0bf77c..c819e99f5 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -67,6 +67,7 @@ * [Longest Increasing Subsequence](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Longest%20Increasing%20Subsequence.cpp) * [Longest Common String](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/longest_common_string.cpp) * [Matrix-Chain-Multiplication](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Matrix-Chain-Multiplication.cpp) + * [Searching Of Element In Dynamic Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/searching_of_element_in_dynamic_array.cpp) * [Tree Height](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/tree_height.cpp) ## Graph From 367b98181074caee9b10b6a21fa91bc7cb0eee63 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 22 Apr 2020 16:06:51 +0200 Subject: [PATCH 276/277] Reduce code in linked_list.cpp @mariangusatu Your review please. --- data_structure/linked_list.cpp | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/data_structure/linked_list.cpp b/data_structure/linked_list.cpp index 2af3f82a3..dd6536abb 100644 --- a/data_structure/linked_list.cpp +++ b/data_structure/linked_list.cpp @@ -14,15 +14,13 @@ void insert(int x) { t = t->next; } node *n = new node; - t->next = n; - n->val = x; - n->next = NULL; + t->next = n; } else { node *n = new node; - n->val = x; - n->next = NULL; start = n; } + n->val = x; + n->next = NULL; } void remove(int x) { From a9cbc06fd745b54b333fb669cb322991da31409f Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 22 Apr 2020 16:09:12 +0200 Subject: [PATCH 277/277] Update linked_list.cpp --- data_structure/linked_list.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/data_structure/linked_list.cpp b/data_structure/linked_list.cpp index dd6536abb..64cad14f9 100644 --- a/data_structure/linked_list.cpp +++ b/data_structure/linked_list.cpp @@ -9,18 +9,18 @@ node *start; void insert(int x) { node *t = start; + node *n = new node; + n->val = x; + n->next = NULL; if (start != NULL) { while (t->next != NULL) { t = t->next; } - node *n = new node; t->next = n; } else { - node *n = new node; start = n; } - n->val = x; - n->next = NULL; + } void remove(int x) {