From cc2749e8b1f876d2355bfb62cc6bc4d34c465115 Mon Sep 17 00:00:00 2001 From: Avinash Kumar Date: Tue, 2 Oct 2018 07:41:58 +0100 Subject: [PATCH 01/54] intro added --- README.md | 3 ++- introduction to compititive programing | 32 ++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3e7c458..b010b8b 100644 --- a/README.md +++ b/README.md @@ -1 +1,2 @@ -# Algorithm \ No newline at end of file +# Algorithm +# \ No newline at end of file diff --git a/introduction to compititive programing b/introduction to compititive programing index 8b13789..1898cff 100644 --- a/introduction to compititive programing +++ b/introduction to compititive programing @@ -1 +1,33 @@ +Programming language: + Most popular Programming languages used in contests are C++ , Python, and Java + +C++ code template + + #include + + using namespace std; + int main() + { + //solution comes here + } + +Input and output is sometimes a bottleneck in program. +The following lines at the beginning of the code make input and output more efficient: + + ios::sync_with_stdio(0); + cin.tie(0) + +Note that the newline "\n" works faster than endl , because endl always causes a flush operation. + + +Sometimes the program should read a whole line from the input, possibly containning spaces. This can +be accomplished by using the getline functon + + string s; + getline(cin, s); + +if the amount of data is unknows, the following loop is useful: + while(cin >> x){ + //code + } From bdd68651fa0ad4c8780e0e8f48905e000e82c7fd Mon Sep 17 00:00:00 2001 From: Avinash Kumar Date: Tue, 2 Oct 2018 09:43:34 +0100 Subject: [PATCH 02/54] Working with no. added --- working with numbers.txt | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 working with numbers.txt diff --git a/working with numbers.txt b/working with numbers.txt new file mode 100644 index 0000000..dc0506e --- /dev/null +++ b/working with numbers.txt @@ -0,0 +1,15 @@ +Modular arithmetic + (a+b)mod m= (a mod m + b mod m) mod m + (a-b)mod m= (a mod m - b mod m) mod m + (a*b)mod m= (a mod m * b mod m) mod m + + +For example, the following code calculate n! , the factorial of n, modulo m: + + long long x=1 + for(int i=2; i<= n; i++) + { + x=(x*i)%m; + } + cout< Date: Tue, 2 Oct 2018 10:56:01 +0100 Subject: [PATCH 03/54] Create Shortening code --- Shortening code | 1 + 1 file changed, 1 insertion(+) create mode 100644 Shortening code diff --git a/Shortening code b/Shortening code new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/Shortening code @@ -0,0 +1 @@ + From 78f01b4d41b91bf99b015bac5284b08623593d04 Mon Sep 17 00:00:00 2001 From: Avinash Kumar Date: Tue, 2 Oct 2018 10:57:05 +0100 Subject: [PATCH 04/54] Rename working with numbers.txt to working with numbers --- working with numbers.txt => working with numbers | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename working with numbers.txt => working with numbers (100%) diff --git a/working with numbers.txt b/working with numbers similarity index 100% rename from working with numbers.txt rename to working with numbers From 8d3b0795f41742b0a3c25e5f8eaa40f282f29074 Mon Sep 17 00:00:00 2001 From: Avinash Date: Tue, 2 Oct 2018 18:20:25 +0530 Subject: [PATCH 05/54] add dynamic array --- Dynamic array | 31 ++++++++++++ README.md | 2 +- introduction to compititive programing | 66 +++++++++++++------------- working with numbers.txt | 30 ++++++------ 4 files changed, 80 insertions(+), 49 deletions(-) create mode 100644 Dynamic array diff --git a/Dynamic array b/Dynamic array new file mode 100644 index 0000000..6dcf8e8 --- /dev/null +++ b/Dynamic array @@ -0,0 +1,31 @@ +A dynamic array +is an array whose size can be changed during the execution of +the program. The most popular dynamic array in C++ is the +vector +structure, +which can be used almost like an ordinary array. +The following code creates an empty vector and adds three elements to it: + + vector v; + v.push_back(3); // [3] + v.push_back(2); // [3,2] + v.push_back(5); // [3,2, + +A shorter way to iterate through a vector is as follows: + for (auto x : v) { + cout << x << "\n"; + } + +The function back returns the last element in the vector, and the function pop_back +removes the last element + +The following code creates a vector with five elements: + vector v = {2,4,2,5,1}; + +Another way to create a vector is to give the number of elements and the +initial value for each element: + // size 10, initial value 0 + vector v(10); + + // size 10, initial value 5 + vector v(10, 5) \ No newline at end of file diff --git a/README.md b/README.md index b010b8b..b9e40b9 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,2 @@ -# Algorithm +# Algorithm # \ No newline at end of file diff --git a/introduction to compititive programing b/introduction to compititive programing index 1898cff..028808c 100644 --- a/introduction to compititive programing +++ b/introduction to compititive programing @@ -1,33 +1,33 @@ -Programming language: - Most popular Programming languages used in contests are C++ , Python, and Java - -C++ code template - - #include - - using namespace std; - int main() - { - //solution comes here - } - -Input and output is sometimes a bottleneck in program. -The following lines at the beginning of the code make input and output more efficient: - - ios::sync_with_stdio(0); - cin.tie(0) - -Note that the newline "\n" works faster than endl , because endl always causes a flush operation. - - -Sometimes the program should read a whole line from the input, possibly containning spaces. This can -be accomplished by using the getline functon - - string s; - getline(cin, s); - -if the amount of data is unknows, the following loop is useful: - while(cin >> x){ - //code - } - +Programming language: + Most popular Programming languages used in contests are C++ , Python, and Java + +C++ code template + + #include + + using namespace std; + int main() + { + //solution comes here + } + +Input and output is sometimes a bottleneck in program. +The following lines at the beginning of the code make input and output more efficient: + + ios::sync_with_stdio(0); + cin.tie(0) + +Note that the newline "\n" works faster than endl , because endl always causes a flush operation. + + +Sometimes the program should read a whole line from the input, possibly containning spaces. This can +be accomplished by using the getline functon + + string s; + getline(cin, s); + +if the amount of data is unknows, the following loop is useful: + while(cin >> x){ + //code + } + diff --git a/working with numbers.txt b/working with numbers.txt index dc0506e..2035503 100644 --- a/working with numbers.txt +++ b/working with numbers.txt @@ -1,15 +1,15 @@ -Modular arithmetic - (a+b)mod m= (a mod m + b mod m) mod m - (a-b)mod m= (a mod m - b mod m) mod m - (a*b)mod m= (a mod m * b mod m) mod m - - -For example, the following code calculate n! , the factorial of n, modulo m: - - long long x=1 - for(int i=2; i<= n; i++) - { - x=(x*i)%m; - } - cout< Date: Tue, 2 Oct 2018 18:57:02 +0530 Subject: [PATCH 06/54] Create merge sort --- merge sort | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 merge sort diff --git a/merge sort b/merge sort new file mode 100644 index 0000000..e187069 --- /dev/null +++ b/merge sort @@ -0,0 +1,80 @@ +->Merge sort Introduction + +The strategy behind Merge Sort is to change the problem of sorting into the problem of merging two sorted sub-lists into one. +If the two halves of the array were sorted, then merging them carefully could complete the sort of the entire list. + +MergeSort(first, last) +{ + if (first < last) + { + mid = (first+last)/2; + + MergeSort(first,mid); + MergeSort(mid+1,last); + Merge(first,mid+1,last); + } +} + +Merge Sort is a "recursive" algorithm because it accomplishes its task by calling itself on a smaller version of the problem (only half of the list). For example, if the array had 2 entries, Merge Sort would begin by calling itself for item 1. Since there is only one element, that sub-list is sorted and it can go on to call itself in item 2. Since that also has only one item, it is sorted and now Merge Sort can merge those two sub-lists into one sorted list of size two. + +As another example, Merge Sort on 4 entries would run as follows: + +MergeSort items 1 - 4 would call: + + MergeSort items 1-2: + MergeSort item 1 (sorted) + MergeSort item 2 (sorted) + Merge lists 1 and 2 + MergeSort items 3-4: + MergeSort item 3 (sorted) + MergeSort item 4 (sorted) + Merge lists 3 and 4 + Merge lists 1-2 and 3-4 + +The real problem is how to merge the two sub-lists. While it can be done in the original array, the algorithm is much simpler if it uses a separate array to hold the portion that has been merged and then copies the merged data back into the original array. The basic philosophy of the merge is to determine which sub-list starts with the smallest data and copy that item into the merged list and move on to the next item in the sub-list. + +merge(first, mid, last) +{ + k=0; /* k keeps track of how many entries in the temp array */ + /* are full */ + i=first; /* i keeps track of the lowest entry in the first */ + /* sub-list which hasn't been copied into temp */ + j=mid; /* j keeps track of the lowest entry in the first */ + /* sub-list which hasn't been copied into temp */ + while ((i < mid) && (j < = last)) + /* This loop will continue until one of the sublists is empty */ + { + if (data[i] < data[j]) + { + temp[k]=data[i]; + i++; + k++; + } + else + { + temp[k]=data[j]; + j++; + k++; + } + } + /* copy the rest of the sublist that wasn't empty into the temp array */ + while (i < mid) + { + temp[k]=data[i]; + i++; + k++; + } + while (j < = last) + { + temp[k]=data[j]; + j++; + k++; + } + /* Now copy the temporary array back into the original array */ + for (m=0;m <=last-first;m++) + { + j=first+m; + data[j] = temp[i]; + } + + From fd611b2bc056e9982a15341704afe8b43e07fe0e Mon Sep 17 00:00:00 2001 From: swapnilshikhar <31812555+swapnilshikhar@users.noreply.github.com> Date: Tue, 2 Oct 2018 19:12:15 +0530 Subject: [PATCH 07/54] Create Warshall --- Warshall | 201 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 201 insertions(+) create mode 100644 Warshall diff --git a/Warshall b/Warshall new file mode 100644 index 0000000..375eee5 --- /dev/null +++ b/Warshall @@ -0,0 +1,201 @@ +=> Warshall's algorithm + +Warshall's algorithm determines whether there is a path between any two nodes in the graph. +It does not give the number of the paths between two nodes. + +Idea: Compute all paths containing node 1, then all paths containing nodes 1 or 2 or 1 and 2, and so on, +until we compute all paths with intermediate nodes selected from the set {1, 2, … n}. + +Here we compute a sequence of matrices P(0), P(1) ,…, P(n) such that P(0) = A, P(n) = P, the path matrix, +and P(r) shows all paths with intermediate nodes selected from the set of nodes {1, 2, 3, …, r}. + +# The algorithm can be defined recursively: + +Let P(0) = A. +Let P(r) is a matrix such that: + +pik(r) = 1 if and only if there is a path connecting nodes i and k through one or more of nodes {1, 2, …, r} + +pik(r) = 0 otherwise + +Let P(r+1) is the matrix where + +pik(r+1) = 1 if and only if there is a path connecting nodes i and k through one or more of nodes {1, 2, …, r, r+1} + +pik(r+1) = 0 otherwise + +P(r+1) can be obtained from P(r) in the following way: + +If pik(r) = 1 then pik(r+1) := 1 + +Else pik(r+1) := p i r+1(r) * p r+1 k(r) + +As a result we have: + +pik(r+1) = 1 if and only if there is a path connecting nodes i and k and containing intermediate nodes selected from +the set {1, 2, 3, .. r+1} + +pik(r+1) = 0 otherwise. + +# Correctness of the algorithm + +a) Suppose pik(r+1) = 1. This is possible only if + + pik(r) = 1, which by the definition of P(r) means that there is a path between nodes i and k, + with intermediate nodes selected from {1, 2, … r}, or: + + Both pi,r+1(r) and pr+1,k(r) are equal to 1. + + pi,r+1(r) = 1 means that there is a path from node i to node r+1 containing intermediate nodes selected from the + set {1, 2, 3, .. r} + + pr+1,k(r) = 1 means that there is a path from node r+1 to node k containing intermediate nodes selected from the + set {1, 2, 3, .. r} + + Thus, there is a path from node i to node r+1 and from node r+1 to node k. Hence there is a path from i to k + through r+1, i.e. its intermediate nodes are selected from the set {1, 2, 3, .. r+1} + + Therefore, if pi,k(r+1) = 1 then there is a path from i to k with its intermediate nodes selected from the + set {1, 2, 3, .. r+1} + +b) Suppose now that there is a path from node i to node k with its intermediate nodes selected from the +set {1, 2, 3, .. r+1} + +Consider two cases + + r+1 is not in the path connecting i and k. Then the path is selected from {1,2, .. , r} by the definition of P(r). + pik (r) = 1 (see (b) above), hence pik(r+1) = 1 + + r+1 is in the path connecting i> and k. Then there is a path connecting i and r+1, and a path connecting r+1 and k. + Hence pi,r+1(r) and p r+1,k (r) are equal to 1. + Therefore, pi,r+1(r) * p r+1,k(r) = 1 + Therefore pik(r+1) = 1. + +Warshall's algorithm requires O(n3) operations: +O(n2) to obtain each P(r) and the calculations are done for r = 1, 2, .., n + +Example + +Adjacency matrix A: + + + 1 2 3 4 5 + 1 0 1 1 0 0 + 2 0 0 0 1 0 + 3 0 0 0 1 1 + 4 0 0 0 0 1 + 5 0 1 0 0 0 + +P(0) = A, i.e. this is the matrix showing paths with no intermediate nodes. P(1) is the matrix containing all paths +from P(0) plus all paths with 1 as intermediate node. + +Its elements are computed in the following way: + +pij(1) = 1 if pij(0) = 1 + +Else pij(1) = pi1(0) * p1j(0) + +Thus for all elements that are 0 in P(0), we compute the products of the elements in the first column and the first +row of P(0). Since all elements in the first column are 0, the products will be 0, so P(1) will be the same as P(0). + +P(1) = + + 1 2 3 4 5 + 1 0 1 1 0 0 + 2 0 0 0 1 0 + 3 0 0 0 1 1 + 4 0 0 0 0 1 + 5 0 1 0 0 0 + +P(2) will contain all paths computed in P(1) plus all paths that contain 2 as an intermediate node + +pij(2) = 1 if pij(1) = 1 + +Else pij(2) = pi2(1) * p2j(1) + +Here we compute the products of the second column and the second row. The second column contains two non-zero elements, +and the second row contains one non-zero element, thus the non-zero products will be: + +p14(2) = p12(1) * p24(1) , p54(2) = p52(1) * p24(1) + +P(2) = + + 1 2 3 4 5 + 1 0 1 1 1 0 + 2 0 0 0 1 0 + 3 0 0 0 1 1 + 4 0 0 0 0 1 + 5 0 1 0 1 0 + +The new paths are the paths connecting nodes 1 and 4 through node 2, and nodes 5 and 4 through node 2. + +Next we compute P(3), looking for paths that have intermediate nodes among {1, 2, 3}. + +pij(3) = 1 if pij(2) = 1 + +Else pij(3) = pi3(2) * p3j(2) + +Here we look at the products of the elements in the third column and the third row. The non-zero products are: +p14(3) = p13(2) * p34(2) , p15(3) = p13(2) * p35(2) + +Note that p14(2) = 1, which means that we have already found a path between nodes 1 and 2. +The new path computed here is the path connecting nodes 1 and 5 through node 3. + +P(3) = + + 1 2 3 4 5 + 1 0 1 1 1 1 + 2 0 0 0 1 0 + 3 0 0 0 1 1 + 4 0 0 0 0 1 + 5 0 1 0 1 0 + +Next we compute P(4), looking for paths that have intermediate nodes among {1, 2, 3, 4}. + +pij(4) = 1 if pij(3) = 1 + +Else pij(4) = pi4(3) * p4j(3) + +Here we find the products of the elements in the fourth column and fourth row. The non-zero products are: + +p15(4) = p14(3) * p45(3) +p25(4) = p24(3) * p45(3) +p35(4) = p34(3) * p45(3) +p55(4) = p54(3) * p45(3) + +Only p25(4) and p55(4) give new paths, connecting nodes 2 and 5 through node 4, and node 5 to itself through node 4. +Thus we have + +P(4) = + + 1 2 3 4 5 + 1 0 1 1 1 1 + 2 0 0 0 1 1 + 3 0 0 0 1 1 + 4 0 0 0 0 1 + 5 0 1 0 1 1 + +Finally, we compute P(5) + +pij(5) = 1 if pij(4) = 1 + +Else pij(5) = pi5(4) * p5j(4) + +The fifth column contains five non-zero elements, and the fifth row contains three non-zero elements, hence +fifteen products will be not equal to zero. The new paths are given by the elements: +p22(5) - connecting 2 to itself through node 5 +p32(5) - connecting 3 and 2 through node 5 +p42(5) - connecting 4 and 2 through node 5 +p44(5) - connecting 4 to itself through node 5 + +P(5) = + + 1 2 3 4 5 + 1 0 1 1 1 1 + 2 0 1 0 1 1 + 3 0 1 0 1 1 + 4 0 1 0 1 1 + 5 0 1 0 1 1 + +The matrix shows that no node is connected to node 1. Except node 1, no other node is connected to node 3. +Node 1 is connected to all nodes except to itself. All nodes are connected to 2, 4, and 5. From 7403fe6b0fdd4d169441deef52ce8cf4ddf4c072 Mon Sep 17 00:00:00 2001 From: swapnilshikhar <31812555+swapnilshikhar@users.noreply.github.com> Date: Tue, 2 Oct 2018 19:29:21 +0530 Subject: [PATCH 08/54] Update Warshall --- Warshall | 73 ++++++++++++++++++++++++++++---------------------------- 1 file changed, 36 insertions(+), 37 deletions(-) diff --git a/Warshall b/Warshall index 375eee5..f37c754 100644 --- a/Warshall +++ b/Warshall @@ -78,13 +78,12 @@ Example Adjacency matrix A: - - 1 2 3 4 5 - 1 0 1 1 0 0 - 2 0 0 0 1 0 - 3 0 0 0 1 1 - 4 0 0 0 0 1 - 5 0 1 0 0 0 + 1 2 3 4 5 + 1 0 1 1 0 0 + 2 0 0 0 1 0 + 3 0 0 0 1 1 + 4 0 0 0 0 1 + 5 0 1 0 0 0 P(0) = A, i.e. this is the matrix showing paths with no intermediate nodes. P(1) is the matrix containing all paths from P(0) plus all paths with 1 as intermediate node. @@ -100,12 +99,12 @@ row of P(0). Since all elements in the first column are 0, the products will be P(1) = - 1 2 3 4 5 - 1 0 1 1 0 0 - 2 0 0 0 1 0 - 3 0 0 0 1 1 - 4 0 0 0 0 1 - 5 0 1 0 0 0 + 1 2 3 4 5 + 1 0 1 1 0 0 + 2 0 0 0 1 0 + 3 0 0 0 1 1 + 4 0 0 0 0 1 + 5 0 1 0 0 0 P(2) will contain all paths computed in P(1) plus all paths that contain 2 as an intermediate node @@ -120,12 +119,12 @@ p14(2) = p12(1) * p24(1) , p54(2) = p52(1) * p24(1) P(2) = - 1 2 3 4 5 - 1 0 1 1 1 0 - 2 0 0 0 1 0 - 3 0 0 0 1 1 - 4 0 0 0 0 1 - 5 0 1 0 1 0 + 1 2 3 4 5 + 1 0 1 1 1 0 + 2 0 0 0 1 0 + 3 0 0 0 1 1 + 4 0 0 0 0 1 + 5 0 1 0 1 0 The new paths are the paths connecting nodes 1 and 4 through node 2, and nodes 5 and 4 through node 2. @@ -143,12 +142,12 @@ The new path computed here is the path connecting nodes 1 and 5 through node 3. P(3) = - 1 2 3 4 5 - 1 0 1 1 1 1 - 2 0 0 0 1 0 - 3 0 0 0 1 1 - 4 0 0 0 0 1 - 5 0 1 0 1 0 + 1 2 3 4 5 + 1 0 1 1 1 1 + 2 0 0 0 1 0 + 3 0 0 0 1 1 + 4 0 0 0 0 1 + 5 0 1 0 1 0 Next we compute P(4), looking for paths that have intermediate nodes among {1, 2, 3, 4}. @@ -168,12 +167,12 @@ Thus we have P(4) = - 1 2 3 4 5 - 1 0 1 1 1 1 - 2 0 0 0 1 1 - 3 0 0 0 1 1 - 4 0 0 0 0 1 - 5 0 1 0 1 1 + 1 2 3 4 5 + 1 0 1 1 1 1 + 2 0 0 0 1 1 + 3 0 0 0 1 1 + 4 0 0 0 0 1 + 5 0 1 0 1 1 Finally, we compute P(5) @@ -190,12 +189,12 @@ p44(5) - connecting 4 to itself through node 5 P(5) = - 1 2 3 4 5 - 1 0 1 1 1 1 - 2 0 1 0 1 1 - 3 0 1 0 1 1 - 4 0 1 0 1 1 - 5 0 1 0 1 1 + 1 2 3 4 5 + 1 0 1 1 1 1 + 2 0 1 0 1 1 + 3 0 1 0 1 1 + 4 0 1 0 1 1 + 5 0 1 0 1 1 The matrix shows that no node is connected to node 1. Except node 1, no other node is connected to node 3. Node 1 is connected to all nodes except to itself. All nodes are connected to 2, 4, and 5. From 804788f4876588aed11a6609f0e0f019fee47bfa Mon Sep 17 00:00:00 2001 From: Pradyumna Date: Wed, 3 Oct 2018 00:24:25 +0530 Subject: [PATCH 09/54] Create bubble sort --- bubble sort | 1 + 1 file changed, 1 insertion(+) create mode 100644 bubble sort diff --git a/bubble sort b/bubble sort new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/bubble sort @@ -0,0 +1 @@ + From 2f0ab943a390cf9f4223cf1dd1c83b069227d60e Mon Sep 17 00:00:00 2001 From: Pradyumna Date: Wed, 3 Oct 2018 00:24:52 +0530 Subject: [PATCH 10/54] Create binary serach --- binary serach | 1 + 1 file changed, 1 insertion(+) create mode 100644 binary serach diff --git a/binary serach b/binary serach new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/binary serach @@ -0,0 +1 @@ + From 2f35f14fd5b77f618a493afea0beac6dbfbf6add Mon Sep 17 00:00:00 2001 From: Pradyumna Date: Wed, 3 Oct 2018 01:13:45 +0530 Subject: [PATCH 11/54] Update bubble sort --- bubble sort | 62 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/bubble sort b/bubble sort index 8b13789..ab5948b 100644 --- a/bubble sort +++ b/bubble sort @@ -1 +1,63 @@ +The process of arranging the given elements so that they are in ascending order or descending order is called SORTING.For example consider +the unsorted elements: + 12,1,34,54,23 + +After sorting them in ascending order,we get the following list: + + 1,12,23,34,54 +After sorting them in descending order,we get the following list: + + 54,34,23,12,1 +DESIGN OF BUBBLE SORT: +step 1.Identify parameters of function:Given an array a consisting of n elements we have to sort them in ascending order.So + + |-----------------------------| + |parameters are:int a[],int n | + |-----------------------------| +step 2.Return type:Our intention is only to sort numbers.Hence,we are not returning any value.So, + + |----------------| + |return type:void| + |----------------| +step 3.Designing the body of the function.This is the simplest and easiest sorting technique.In this,the two successive items A[i] and + A[i+1] are exchanged whwnever A[i]>=A[i+1]. + For example,consider the elements shown below: + 50,40,30,20,10 +The elements can be sorted as shown below: + + | 1ST PASS | 2ND PASS | 3RD PASS | 4TH pass + A[0]=50<-|40 40 40 40<- |30 30 30<- |20 20 |10 + A[1]=40<-|50<- 30 30 40<- |40<- 20 20<- |30<- 10 |20 + A[2]=30 |30<- 50<- 20 20 |20<- 40<- 10 |10<- 30 |30 + A[3]=20 |20 20<- 50<- 10 |10 10<- 40 |40 40 |40 + A[4]=10 |10 10 10<- 50 |50 50 50 |50 50 |50 + | | | | + Given | 50 sinks to bottom | 40 sinks to |30 sinks |20 sinks to + Array | after pass 1 | pass 2 |to bottom |bottom + after pass 3 + +Observe that after each pass,the larger values sinks to the bottom of the array and hence it is called sinking sort.Also observe that +at the end of each pass smaller values gradually "BUBBLE" their way upward to the top and hence called 'BUBBLE SORT'. + +ALGORITHM FOR BUBBLE SORT: + + ALGORITHM BubbleSort(a[],n) + for j<-1 to n-1 do + for i<-0 to n-j-1 do + if(a[i]>a[i+1]) + temp<--a[i] + a[i]<--a[i+1] + a[i+1]<--temp + end if + end for + end for + + + + + + + + + From 896e09a3341fea1f0c30305cd736ab834295cd16 Mon Sep 17 00:00:00 2001 From: Avinash Kumar Date: Wed, 3 Oct 2018 01:16:53 +0530 Subject: [PATCH 12/54] Create bfs --- bfs | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 bfs diff --git a/bfs b/bfs new file mode 100644 index 0000000..213101c --- /dev/null +++ b/bfs @@ -0,0 +1,47 @@ +Breadth First Search + +This can be throught of as being like Dijkstra's algorithm for shortest paths, but with every edge having the same length. However it is a lot simpler and doesn't need any data structures. We just keep a tree (the breadth first search tree), a list of nodes to be added to the tree, and markings (Boolean variables) on the vertices to tell whether they are in the tree or list. + +Algorithm + +breadth first search: + unmark all vertices + choose some starting vertex x + mark x + list L = x + tree T = x + while L nonempty + choose some vertex v from front of list + visit v + for each unmarked neighbor w + mark w + add it to end of list + add edge vw to T + +It's very important that you remove vertices from the other end of the list than the one you add them to, so that the list acts as a queue (fifo storage) rather than a stack (lifo). The "visit v" step would be filled out later depending on what you are using BFS for, just like the tree traversals usually involve doing something at each vertex that is not specified as part of the basic algorithm. If a vertex has several unmarked neighbors, it would be equally correct to visit them in any order. Probably the easiest method to implement would be simply to visit them in the order the adjacency list for v is stored in. + +Let's prove some basic facts about this algorithm. First, each vertex is clearly marked at most once, added to the list at most once (since that happens only when it's marked), and therefore removed from the list at most once. Since the time to process a vertex is proportional to the length of its adjacency list, the total time for the whole algorithm is O(m). + +Next, let's look at the tree T constructed by the algorithm. Why is it a tree? If you think of each edge vw as pointing "upward" from w to v, then each edge points from a vertex visited later to one visited earlier. Following successive edges upwards can only get stopped at x (which has no edge going upward from it) so every vertex in T has a path to x. This means that T is at least a connected subgraph of G. Now let's prove that it's a tree. A tree is just a connected and acyclic graph, so we need only to show that T has no cycles. In any cycle, no matter how you orient the edges so that one direction is "upward" and the other "downward", there is always a "bottom" vertex having two upward edges out of it. But in T, each vertex has at most one upward edge, so T can have no cycles. Therefore T really is a tree. It is known as a breadth first search tree. + +We also want to know that T is a spanning tree, i.e. that if the graph is connected (every vertex has some path to the root x) then every vertex will occur somewhere in T. We can prove this by induction on the length of the shortest path to x. If v has a path of length k, starting v-w-...-x, then w has a path of length k-1, and by induction would be included in T. But then when we visited w we would have seen edge vw, and if v were not already in the tree it would have been added. + +Breadth first traversal of G corresponds to some kind of tree traversal on T. But it isn't preorder, postorder, or even inorder traversal. Instead, the traversal goes a level at a time, left to right within a level (where a level is defined simply in terms of distance from the root of the tree). For instance, the following tree is drawn with vertices numbered in an order that might be followed by breadth first search: + + 1 + / | \ + 2 3 4 + / \ | + 5 6 7 + | / | \ + 8 9 10 11 + +The proof that vertices are in this order by breadth first search goes by induction on the level number. By the induction hypothesis, BFS lists all vertices at level k-1 before those at level k. Therefore it will place into L all vertices at level k before all those of level k+1, and therefore so list those of level k before those of level k+1. (This really is a proof even though it sounds like circular reasoning.) + +Breadth first search trees have a nice property: Every edge of G can be classified into one of three groups. Some edges are in T themselves. Some connect two vertices at the same level of T. And the remaining ones connect two vertices on two adjacent levels. It is not possible for an edge to skip a level. + +Therefore, the breadth first search tree really is a shortest path tree starting from its root. Every vertex has a path to the root, with path length equal to its level (just follow the tree itself), and no path can skip a level so this really is a shortest path. + +Breadth first search has several uses in other graph algorithms, but most are too complicated to explain in detail here. One is as part of an algorithm for matching, which is a problem in which you want to pair up the n vertices of a graph by n/2 edges. If you have a partial matching, pairing up only some of the vertices, you can extend it by finding an alternating path connecting two unmatched vertices; this is a path in which every other edge is part of the partial matching. If you remove those edges in the path from the matching, and add the other path edges back into the matching, you get a matching with one more edge. Alternating paths can be found using a version of breadth first search. + +A second use of breadth first search arises in certain pattern matching problems. For instance, if you're looking for a small subgraph such as a triangle as part of a larger graph, you know that every vertex in the triangle has to be connected by an edge to every other vertex. Since no edge can skip levels in the BFS tree, you can divide the problem into subproblems, in which you look for the triangle in pairs of adjacent levels of the tree. This sort of problem, in which you look for a small graph as part of a larger one, is known as subgraph isomorphism. In a recent paper, I used this idea to solve many similar pattern-matching problems in linear time. From 505d3c2da69df52809065e172d9023c2030ab5a2 Mon Sep 17 00:00:00 2001 From: Avinash Kumar Date: Tue, 2 Oct 2018 21:10:18 +0100 Subject: [PATCH 13/54] create dfs (#9) --- dfs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 dfs diff --git a/dfs b/dfs new file mode 100644 index 0000000..0af337e --- /dev/null +++ b/dfs @@ -0,0 +1,34 @@ +Depth first search +Depth first search is another way of traversing graphs, which is closely related to preorder traversal of a tree. Recall that preorder traversal simply visits each node before its children. It is most easy to program as a recursive routine: + + preorder(node v) + { + visit(v); + for each child w of v + preorder(w); + } + +To turn this into a graph traversal algorithm, we basically replace "child" by "neighbor". But to prevent infinite loops, we only want to visit each vertex once. Just like in BFS we can use marks to keep track of the vertices that have already been visited, and not visit them again. Also, just like in BFS, we can use this search to build a spanning tree with certain useful properties. + + dfs(vertex v) + { + visit(v); + for each neighbor w of v + if w is unvisited + { + dfs(w); + add edge vw to tree T + } + } + +The overall depth first search algorithm then simply initializes a set of markers so we can tell which vertices are visited, chooses a starting vertex x, initializes tree T to x, and calls dfs(x). Just like in breadth first search, if a vertex has several neighbors it would be equally correct to go through them in any order. I didn't simply say "for each unvisited neighbor of v" because it is very important to delay the test for whether a vertex is visited until the recursive calls for previous neighbors are finished. + +The proof that this produces a spanning tree (the depth first search tree) is essentially the same as that for BFS, so I won't repeat it. However while the BFS tree is typically "short and bushy", the DFS tree is typically "long and stringy". + +Just like we did for BFS, we can use DFS to classify the edges of G into types. Either an edge vw is in the DFS tree itself, v is an ancestor of w, or w is an ancestor of v. (These last two cases should be thought of as a single type, since they only differ by what order we look at the vertices in.) What this means is that if v and w are in different subtrees of v, we can't have an edge from v to w. This is because if such an edge existed and (say) v were visited first, then the only way we would avoid adding vw to the DFS tree would be if w were visited during one of the recursive calls from v, but then v would be an ancestor of w. + +As an example of why this property might be useful, let's prove the following fact: in any graph G, either G has some path of length at least k. or G has O(kn) edges. + +Proof: look at the longest path in the DFS tree. If it has length at least k, we're done. Otherwise, since each edge connects an ancestor and a descendant, we can bound the number of edges by counting the total number of ancestors of each descendant, but if the longest path is shorter than k, each descendant has at most k-1 ancestors. So there can be at most (k-1)n edges. + +This fact can be used as part of an algorithm for finding long paths in G, another subgraph isomorphism problem closely related to the traveling salesman problem. If k is a small constant (like say 5) you can find paths of length k in linear time (measured as a function of n). But measured as a function of k, the time is exponential, which isn't surprising because this problem is closely related to the traveling salesman problem. For more on this particular problem, see Michael R. Fellows and Michael A. Langston, "On search, decision and the efficiency of polynomial-time algorithms", 21st ACM Symp. Theory of Computing, 1989, pp. 501-512. From a43dfe884963c91369961e94485f2854aa3a76ea Mon Sep 17 00:00:00 2001 From: swapnilshikhar <31812555+swapnilshikhar@users.noreply.github.com> Date: Wed, 3 Oct 2018 13:43:04 +0530 Subject: [PATCH 14/54] Create Introduction to algorithm complexity --- Introduction to algorithm complexity | 193 +++++++++++++++++++++++++++ 1 file changed, 193 insertions(+) create mode 100644 Introduction to algorithm complexity diff --git a/Introduction to algorithm complexity b/Introduction to algorithm complexity new file mode 100644 index 0000000..a0fa814 --- /dev/null +++ b/Introduction to algorithm complexity @@ -0,0 +1,193 @@ +When we solve a problem by creating an algorithm, we have different ways to do it, and can apply several strategies. +As a result we can arrive at different algorithmic solutions. +From a computational point of view, it’s necessary to have a mechanism to compare one solution to another. +This way, we can learn beforehand how different algorithms for the same problem will behave —this is especially true for +big problems. + +Algorithm complexity is a theoretical metric that is applied to algorithms in order to measure them. +It’s a basic and important concept for all programmers, but at the same time, it’s often unknown. + +It is said to be a difficult issue, but that’s not strictly true. Algorithm complexity is a tricky matter but just +from a theoretical point of view. The study and measurement of the complexity of algorithms only requires some mathematical +skills and the application of some specific techniques —nothing that a software engineer isn’t already used to. + +-> Introduction + +Understanding the complexity of algorithms is important because it will allow us to choose from them in an educated and +informed manner. We will see that we won’t always select the least complex, but rather the one that suits us best for +the problem we want to solve. + +Just as in meteorology, an algorithm has many variables that we need to break apart and study, +in order to calculate the big picture, or as the metaphor goes, be able to say “it’s going to rain today”. + +There are two main measurements for algorithm complexity: time and space (in memory). + +# Space complexity is much less important nowadays because computers have so much more power. + +# Time however is a much more scarce resource. So, every time that you see “complexity”, people are referring to the +“time complexity” of an algorithm. + +-> The size of a problem + +The underlying idea behind the concept of time complexity of an algorithm is, basically, measuring how much time it takes +to successfully solve the problem. + +An algorithm is typically an input that is transformed into an output after taking a series of steps. +So, imagine some sorting algorithm for an array… will it take the same time to sort a 100-element array than one +with 1,000,000 elements? Obviously not. The algorithm will perform the same task regardless of the length of the array, +but the length will directly impact the time it takes to finish. + +In that sense, we need to start talking about the size of a problem. That size is a set of values that can be derived +from the input, and that size will change the final time the algorithm will take to finish. + +Algorithm complexity will then be calculated based on the size of a problem. In the sorting array case, +we only have one size that matters: the array length and we can call it n. +Algorithm complexity is a function + +If we have an array with n elements, how much time will it take for our algorithm to finish? +Well, it depends on two things: the value that n has for each case and the computer that will execute the algorithm. +If those two variables always change the final time, we need to come up with a simplification that allow us just to +compare algorithms that aren’t based on the size of an input or different computers. + +Instead of measuring time, we will measure the amount of instructions that the computer will need to execute the algorithm, +and we will assume that every instruction is executed in a constant amount of time. + +Notice that we can allow that simplification because what we really need to know is how the necessary amount of +instructions to solve the problem grow, based on the size of the input. That is what algorithm complexity is all about. + +Let’s see an example. Consider the following pseudo code: + +1 function (n) { +2 var a, j, k; +3 +4 for j = 1 up to j = n { +5 a = a + j; +6 j++; +7 } +8 +9 for k = n up to k = 1 { +10 a = a - 1; +11 a = a * 2; +12 k--; +13 } +14 +15 return a; +16 } + +In this algorithm there are two loops. The first one, starting on line 4 is executed n times and inside of it, +there are two instructions. That means that lines 5 and 6 are executed n times each, that is 2n. + +Inside the second loop, starting on line 9, we can find three other instructions: lines 10, 11 and 12. +As that loop is executed n times too, it will perform 3n instructions inside of it. Finally, line 15 is executed +just one time. + +How many instructions are executed in this algorithm? Let’s add: 2n + 3n + 1, that is 5n+1. So, we can say that the +complexity of that algorithm is 5n+1 because that is the amount of instructions it will execute for a problem of size n. + +If we picture 5n+1 as a function and check the graph, we’ll notice that it is a straight line. + + +We can clearly see that the time this algorithm takes grows linearly to the size of the input. + +Imagine now that we have those two nested loops: + + +1 for j = 1 up to j = n { +2 a = a + j; +3 for k = n up to k = 1 { +4 a = a - 1; +5 a = a * 2; +6 k--; +7 } +8 } + + + +Line 2 will be executed n times. Lines 4, 5 and 6 will be executed n times but the loop starting on line 3 will be +executed n times as well. So, how many times will those lines be executed? That’s right, 3n x n. So the final complexity +of this new code is now n + 3n2. + +If we look at the graph of the function we can clearly see that the time it takes will now increase much faster for +larger sizes. + +That is because now the function isn’t linear but rather quadratic. + +Best case, worst case + +In both examples above, the algorithm complexity is fully dependent of the size of the problem. But that’s not true for +all algorithms. Think about finding an element in an array. Is it the same if the desired element is the first one, +the one in the middle, or the last one? What about a sorting algorithm: is it the same if the array is already sorted? + +In many algorithms, it’s not only the size of the input that impacts on the complexity, but also the content itself. + +To express that, we use a specific notation: the “Big-O”. We will say that the “find an element in an array” algorithm +has a worst-case complexity of O(n). The “O” comes from the Greek letter Omicron and was introduced by the mathematician +Paul Gustav Heinrich Bachmann in 1894, years before the first computer was ever thought about! + +In the opposite fashion, we can say the the best-case complexity of the algorithm is Ω(1) (the desired element is the +first one). That is the Omega notation. + +By convention, when we say “complexity” we almost always refer to the worst-case scenario. +Complexity orders + +Those examples were really simple, but imagine algorithms in the real world. Those algorithms can be really big! +How can we simplify them? + +Let’s say that the complexity of some algorithms are O(10n+3), O(32n+12) and O(56n+1). What do they have in common? +They are all linear functions. Now think about another algorithm whose complexity is O(5n2 + 3n + 2). Its complexity +is quadratic. If we compare the graphs of those function we can realize that they have very different growth patterns, +as we’ve seen before. + +With that context, we can group all the complexities that grow in the same way in the same bag, and we’ll have many bags. +To each of those bags we’ll call them complexity order. In a more formal way, for all the functions that we group in the +same bag or complexity order we can find an asymptote, that when multiplied by a value will superiorly bound our function +when dealing with the worst case. + +That is, all linear complexities will be bound by a variation of n, all quadratic complexities will be bound by a variation +of n2, and so on. + +As you can see, the complexity concept is completely simplified if we just think about complexity orders: instead of +counting the amount of line executions of an algorithm we just need to find the ones that are most executed. +That is, if we have a line or a set of lines that are executed n3 it doesn’t matter if all the other lines are executed +less times. + +Why? Because, let’s say the final complexity is O(n3 + 2n + 5), we can be sure that for any value of n, and even in the +worst case, the final value of the function won’t ever be higher than c n3, with c being a constant bigger than 1, +because we can always find a c for which the function superiorly bounds the complexity of our algorithms. +Most common complexity orders + +# O(1) → constant +These are all algorithms that finish in a constant time, regardless of the size of the input. +Example: finding the biggest of two numbers. + +# O(log n) → logarithmic +These are all algorithms where the execution time grows logarithmically. There aren’t many, and they are usually +good algorithms because they imply that they take less instructions than the size of their input. +Example: some cool sorting algorithms + +# O(n) → linear +Execution time grows linearly according to input size. Example: finding the biggest number in an array. + +# O(n log n) → linearithmic +This is not such a bad complexity for an algorithm. It’s higher than linear but much smaller than quadratic. +Example: Quicksort algorithm. + +# O(nc) with c > 1 → polynomial +Here lie most of the algorithms. When c equals 2 it’s called quadratic, when it’s 3 it’s called cubic and the generic +name is simply “polynomial”. This is the last acceptable order (as long as c is small enough) where we can be +sure that a computer can solve those algorithms within a sustainable timeframe. + +# O(cn) with c > 1 → exponential +It seems similar to the previous one but it’s not: it’s much, much worse as it grows faster. + +# O(n!) → factorial +It’s the typical complexity of those algorithms that try every possible combination. Think about brute-force password +cracking and the time it can take to finish. + +# O(nn) –> combinatory +Worst complexity ever. It grows so fast that even for small values of n the problem becomes impossible to manage. + +Those last three complexities are called non polynomial complexities (NP) and the rest are called polynomial (P). +Although it may seem strange, there is a lot of discussion on whether P = NP. This is the biggest question of computer +science. If us humans discover it’s true, it would mean that for every existing problem of the universe there is a +polynomic way to solve them. From be50472acce220103522b9e3898b1d3dd07a8867 Mon Sep 17 00:00:00 2001 From: swapnilshikhar <31812555+swapnilshikhar@users.noreply.github.com> Date: Wed, 3 Oct 2018 13:53:29 +0530 Subject: [PATCH 15/54] Create P and NP classes --- P and NP classes | 66 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 P and NP classes diff --git a/P and NP classes b/P and NP classes new file mode 100644 index 0000000..7c05da0 --- /dev/null +++ b/P and NP classes @@ -0,0 +1,66 @@ +-> In Computer Science, many problems are solved where the objective is to maximize or minimize some values, +whereas in other problems we try to find whether there is a solution or not. Hence, the problems can be categorized as +follows − + +-> Optimization Problem +Optimization problems are those for which the objective is to maximize or minimize some values. For example, + 1.)Finding the minimum number of colors needed to color a given graph. + 2.)Finding the shortest path between two vertices in a graph. + +-> Decision Problem +There are many problems for which the answer is a Yes or a No. These types of problems are known as decision problems. +For example, + 1.)Whether a given graph can be colored by only 4-colors. + 2.)Finding Hamiltonian cycle in a graph is not a decision problem, whereas checking a graph is Hamiltonian or + not is a decision problem. + +-> What is Language? +Every decision problem can have only two answers, yes or no. Hence, a decision problem may belong to a language if +it provides an answer ‘yes’ for a specific input. A language is the totality of inputs for which the answer is Yes. +Most of the algorithms discussed in the previous chapters are polynomial time algorithms. + +# For input size n, if worst-case time complexity of an algorithm is O(nk), where k is a constant, the algorithm is +a polynomial time algorithm. + +Algorithms such as Matrix Chain Multiplication, Single Source Shortest Path, All Pair Shortest Path, Minimum Spanning Tree, +etc. run in polynomial time. However there are many problems, such as traveling salesperson, optimal graph coloring, +Hamiltonian cycles, finding the longest path in a graph, and satisfying a Boolean formula, for which no polynomial time +algorithms is known. These problems belong to an interesting class of problems, called the NP-Complete problems, +whose status is unknown. + +-> In this context, we can categorize the problems as follows − + +1.) P-Class +The class P consists of those problems that are solvable in polynomial time, i.e. these problems can be solved in time O(nk) +in worst-case, where k is constant. + +These problems are called tractable, while others are called intractable or superpolynomial. + +Formally, an algorithm is polynomial time algorithm, if there exists a polynomial p(n) such that the algorithm can +solve any instance of size n in a time O(p(n)). + +Problem requiring Ω(n50) time to solve are essentially intractable for large n. Most known polynomial time algorithm +run in time O(nk) for fairly low value of k. +The advantages in considering the class of polynomial-time algorithms is that all reasonable deterministic single +processor model of computation can be simulated on each other with at most a polynomial slow-d + +2.) NP-Class +The class NP consists of those problems that are verifiable in polynomial time. NP is the class of decision problems +for which it is easy to check the correctness of a claimed answer, with the aid of a little extra information. +Hence, we aren’t asking for a way to find a solution, but only to verify that an alleged solution really is correct. + +Every problem in this class can be solved in exponential time using exhaustive search. + +# P versus NP +Every decision problem that is solvable by a deterministic polynomial time algorithm is also solvable by a polynomial +time non-deterministic algorithm. + +All problems in P can be solved with polynomial time algorithms, whereas all problems in NP - P are intractable. + +It is not known whether P = NP. However, many problems are known in NP with the property that if they belong to P, +then it can be proved that P = NP. + +If P ≠ NP, there are problems in NP that are neither in P nor in NP-Complete. + +The problem belongs to class P if it’s easy to find a solution for the problem. +The problem belongs to NP, if it’s easy to check a solution that may have been very tedious to find. From b153e46aa181cd2234d7bfb5a8d849c82406432f Mon Sep 17 00:00:00 2001 From: swapnilshikhar <31812555+swapnilshikhar@users.noreply.github.com> Date: Wed, 3 Oct 2018 14:01:24 +0530 Subject: [PATCH 16/54] Update P and NP classes --- P and NP classes | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/P and NP classes b/P and NP classes index 7c05da0..b98a5c4 100644 --- a/P and NP classes +++ b/P and NP classes @@ -33,12 +33,10 @@ whose status is unknown. 1.) P-Class The class P consists of those problems that are solvable in polynomial time, i.e. these problems can be solved in time O(nk) in worst-case, where k is constant. - These problems are called tractable, while others are called intractable or superpolynomial. Formally, an algorithm is polynomial time algorithm, if there exists a polynomial p(n) such that the algorithm can solve any instance of size n in a time O(p(n)). - Problem requiring Ω(n50) time to solve are essentially intractable for large n. Most known polynomial time algorithm run in time O(nk) for fairly low value of k. The advantages in considering the class of polynomial-time algorithms is that all reasonable deterministic single @@ -48,9 +46,9 @@ processor model of computation can be simulated on each other with at most a pol The class NP consists of those problems that are verifiable in polynomial time. NP is the class of decision problems for which it is easy to check the correctness of a claimed answer, with the aid of a little extra information. Hence, we aren’t asking for a way to find a solution, but only to verify that an alleged solution really is correct. - Every problem in this class can be solved in exponential time using exhaustive search. + # P versus NP Every decision problem that is solvable by a deterministic polynomial time algorithm is also solvable by a polynomial time non-deterministic algorithm. From 5bbc0555446ee01c0953b45fc5d3c131cfd9dc63 Mon Sep 17 00:00:00 2001 From: swapnilshikhar <31812555+swapnilshikhar@users.noreply.github.com> Date: Wed, 3 Oct 2018 21:28:38 +0530 Subject: [PATCH 17/54] Create 0-1 Knapsack --- 0-1 Knapsack | 77 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 0-1 Knapsack diff --git a/0-1 Knapsack b/0-1 Knapsack new file mode 100644 index 0000000..0e3510a --- /dev/null +++ b/0-1 Knapsack @@ -0,0 +1,77 @@ +-> In 0-1 Knapsack, items cannot be broken which means the thief should take the item as a whole or should leave it. +This is reason behind calling it as 0-1 Knapsack. +Hence, in case of 0-1 Knapsack, the value of xi can be either 0 or 1, where other constraints remain the same. + +-> 0-1 Knapsack cannot be solved by Greedy approach. Greedy approach does not ensure an optimal solution. +In many instances, Greedy approach may give an optimal solution. + +# The following examples will establish our statement. + +-> Example-1 +Let us consider that the capacity of the knapsack is W = 25 and the items are as shown in the following table. + +Item A B C D +Profit 24 18 18 10 +Weight 24 10 10 7 + +Without considering the profit per unit weight (pi/wi), if we apply Greedy approach to solve this problem, +first item A will be selected as it will contribute maximum profit among all the elements. + +After selecting item A, no more item will be selected. Hence, for this given set of items total profit is 24. +Whereas, the optimal solution can be achieved by selecting items, B and C, where the total profit is 18 + 18 = 36. + +-> Example-2 +Instead of selecting the items based on the overall benefit, in this example the items are selected based on ratio pi/wi. +Let us consider that the capacity of the knapsack is W = 60 and the items are as shown in the following table. + +Item A B C +Price 100 280 120 +Weight 10 40 20 +Ratio 10 7 6 + +Using the Greedy approach, first item A is selected. Then, the next item B is chosen. +Hence, the total profit is 100 + 280 = 380. However, the optimal solution of this instance can be achieved by selecting +items, B and C, where the total profit is 280 + 120 = 400. + +Hence, it can be concluded that Greedy approach may not give an optimal solution. + +-> To solve 0-1 Knapsack, Dynamic Programming approach is required. + +# Problem Statement +A thief is robbing a store and can carry a maximal weight of W into his knapsack. +There are n items and weight of ith item is wi and the profit of selecting this item is pi. +What items should the thief take? + +-> Dynamic-Programming Approach +Let i be the highest-numbered item in an optimal solution S for W dollars. Then S' = S - {i} is an optimal solution +for W - wi dollars and the value to the solution S is Vi plus the value of the sub-problem. + +We can express this fact in the following formula: define c[i, w] to be the solution for items 1,2, … , i and +the maximum weight w. + +The algorithm takes the following inputs + The maximum weight W + The number of items n + The two sequences v = and w = + +Dynamic-0-1-knapsack (v, w, n, W) +for w = 0 to W do + c[0, w] = 0 +for i = 1 to n do + c[i, 0] = 0 + for w = 1 to W do + if wi ≤ w then + if vi + c[i-1, w-wi] then + c[i, w] = vi + c[i-1, w-wi] + else c[i, w] = c[i-1, w] + else + c[i, w] = c[i-1, w] + +The set of items to take can be deduced from the table, starting at c[n, w] and tracing backwards where the optimal +values came from. + +If c[i, w] = c[i-1, w], then item i is not part of the solution, and we continue tracing with c[i-1, w]. +Otherwise, item i is part of the solution, and we continue tracing with c[i-1, w-W]. + +-> Analysis +This algorithm takes θ(n, w) times as table c has (n + 1).(w + 1) entries, where each entry requires θ(1) time to compute. From bad2bf2834faf344eb757c8b516349dfa94793f6 Mon Sep 17 00:00:00 2001 From: Subhashreemurugaraj <43822391+Subhashreemurugaraj@users.noreply.github.com> Date: Wed, 3 Oct 2018 22:14:19 +0530 Subject: [PATCH 18/54] Add binary search --- binary search | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 binary search diff --git a/binary search b/binary search new file mode 100644 index 0000000..3c26515 --- /dev/null +++ b/binary search @@ -0,0 +1,6 @@ +Binary search is a technique to search an item thereby finding its position in a sorted array. +It basically divides the sorted array into two parts by comparing the item with the middle element. +If it matches then the position is returned. +Else it continues searching in either of the two parts depending on its value. +This process continues and each time the item is compared with the updated mid value. +If mid value is not returned after the process ends then item is not found. From 67e77594ea7258ce18f98f73b5fdbd6115495762 Mon Sep 17 00:00:00 2001 From: Avinash Kumar Date: Wed, 3 Oct 2018 23:04:17 +0530 Subject: [PATCH 19/54] create folder for old one --- Old/abs | 1 + 1 file changed, 1 insertion(+) create mode 100644 Old/abs diff --git a/Old/abs b/Old/abs new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/Old/abs @@ -0,0 +1 @@ + From 3f35ae067d89560b27f3c9c9b9555bb60f4c8c9f Mon Sep 17 00:00:00 2001 From: techhubmvit <43720986+techhubmvit@users.noreply.github.com> Date: Wed, 3 Oct 2018 23:09:17 +0530 Subject: [PATCH 20/54] Rename 0-1 Knapsack to 0-1 Knapsack.md --- 0-1 Knapsack => 0-1 Knapsack.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename 0-1 Knapsack => 0-1 Knapsack.md (100%) diff --git a/0-1 Knapsack b/0-1 Knapsack.md similarity index 100% rename from 0-1 Knapsack rename to 0-1 Knapsack.md From a5efcd2b3edf76801e3224c0b00aee8a6685fbc5 Mon Sep 17 00:00:00 2001 From: techhubmvit <43720986+techhubmvit@users.noreply.github.com> Date: Wed, 3 Oct 2018 23:11:37 +0530 Subject: [PATCH 21/54] Rename 0-1 Knapsack.md to Old/0-1 Knapsack.md --- 0-1 Knapsack.md => Old/0-1 Knapsack.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename 0-1 Knapsack.md => Old/0-1 Knapsack.md (100%) diff --git a/0-1 Knapsack.md b/Old/0-1 Knapsack.md similarity index 100% rename from 0-1 Knapsack.md rename to Old/0-1 Knapsack.md From 2a29612ba23bb53aacdf1db3781f6dc4a5aeb42a Mon Sep 17 00:00:00 2001 From: Akshat Jaipuria <38358340+akshatjaipuria@users.noreply.github.com> Date: Thu, 4 Oct 2018 17:21:17 +0530 Subject: [PATCH 22/54] Minimum of 3 numbers --- Minimum of 3 | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Minimum of 3 diff --git a/Minimum of 3 b/Minimum of 3 new file mode 100644 index 0000000..933985c --- /dev/null +++ b/Minimum of 3 @@ -0,0 +1,18 @@ +#include + +int smallest(int x, int y, int z) +{ + int c = 0; + while ( x && y && z ) + { + x--; y--; z--; c++; + } + return c; +} + +int main() +{ + int x = 12, y = 15, z = 5; + printf("Minimum of 3 numbers is %d", smallest(x, y, z)); + return 0; +} From 18c6ace49b74e407f0e27386b53738121e59613b Mon Sep 17 00:00:00 2001 From: Aditya Raman <32497523+ramanaditya@users.noreply.github.com> Date: Thu, 4 Oct 2018 19:21:25 +0530 Subject: [PATCH 23/54] Create fibonacci.py --- Fibonacci/fibonacci.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Fibonacci/fibonacci.py diff --git a/Fibonacci/fibonacci.py b/Fibonacci/fibonacci.py new file mode 100644 index 0000000..99adac7 --- /dev/null +++ b/Fibonacci/fibonacci.py @@ -0,0 +1,13 @@ +# Uses python3 + +import sys + +def calc_fib(n): + fib_list = list(range(0,n+1)) + for i in range(2,n+1): + fib_list[i] = fib_list[i-1] + fib_list[i-2] + return fib_list[n] + + +a = int(input()) +print(calc_fib(a)) From 7acbb3b63c7e433b957e12d6228492a6b24bf6cd Mon Sep 17 00:00:00 2001 From: Aditya Raman <32497523+ramanaditya@users.noreply.github.com> Date: Thu, 4 Oct 2018 19:26:45 +0530 Subject: [PATCH 24/54] Rename Fibonacci series to fibonacci/Fibonacci series --- Fibonacci series => fibonacci/Fibonacci series | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Fibonacci series => fibonacci/Fibonacci series (100%) diff --git a/Fibonacci series b/fibonacci/Fibonacci series similarity index 100% rename from Fibonacci series rename to fibonacci/Fibonacci series From 743d8abc2845dce96db13feb7d6aed108bde6a1c Mon Sep 17 00:00:00 2001 From: Aditya Raman <32497523+ramanaditya@users.noreply.github.com> Date: Thu, 4 Oct 2018 19:27:36 +0530 Subject: [PATCH 25/54] Rename Fibonacci/fibonacci.py to fibonacci/fibonacci.py --- {Fibonacci => fibonacci}/fibonacci.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Fibonacci => fibonacci}/fibonacci.py (100%) diff --git a/Fibonacci/fibonacci.py b/fibonacci/fibonacci.py similarity index 100% rename from Fibonacci/fibonacci.py rename to fibonacci/fibonacci.py From c75fcd75aee3e5728295b664da7ec5d300e66c95 Mon Sep 17 00:00:00 2001 From: ChakreshNayak <31802626+ChakreshNayak@users.noreply.github.com> Date: Thu, 4 Oct 2018 21:28:07 +0530 Subject: [PATCH 26/54] Reversal algorithm of array --- Reversal algorithm for array rotation | 46 +++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Reversal algorithm for array rotation diff --git a/Reversal algorithm for array rotation b/Reversal algorithm for array rotation new file mode 100644 index 0000000..913fcf1 --- /dev/null +++ b/Reversal algorithm for array rotation @@ -0,0 +1,46 @@ +// C++ program for reversal algorithm +// of array rotation +#include +using namespace std; + +/*Function to reverse arr[] from index start to end*/ +void rvereseArray(int arr[], int start, int end) +{ + while (start < end) + { + int temp = arr[start]; + arr[start] = arr[end]; + arr[end] = temp; + start++; + end--; + } +} + +/* Function to left rotate arr[] of size n by d */ +void leftRotate(int arr[], int d, int n) +{ + rvereseArray(arr, 0, d-1); + rvereseArray(arr, d, n-1); + rvereseArray(arr, 0, n-1); +} + +// Function to print an array +void printArray(int arr[], int size) +{ + for (int i = 0; i < size; i++) + cout << arr[i] << " "; +} + +/* Driver program to test above functions */ +int main() +{ + int arr[] = {1, 2, 3, 4, 5, 6, 7}; + int n = sizeof(arr)/sizeof(arr[0]); + int d = 2; + + // Function calling + leftRotate(arr, d, n); + printArray(arr, n); + + return 0; +} From e114443d50536127dbf3c65b40615a81a89baeac Mon Sep 17 00:00:00 2001 From: Pradyumna Date: Fri, 5 Oct 2018 19:27:17 +0530 Subject: [PATCH 27/54] Create Horner Method --- Horner Method | 1 + 1 file changed, 1 insertion(+) create mode 100644 Horner Method diff --git a/Horner Method b/Horner Method new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/Horner Method @@ -0,0 +1 @@ + From 2174559650ab5b621df250358a89cad7b6f3c134 Mon Sep 17 00:00:00 2001 From: Pradyumna Date: Fri, 5 Oct 2018 20:04:43 +0530 Subject: [PATCH 28/54] Update Horner Method --- Horner Method | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/Horner Method b/Horner Method index 8b13789..f3b48a7 100644 --- a/Horner Method +++ b/Horner Method @@ -1 +1,44 @@ +HORNER METHOD: +It is one of the most preferred methods to evaluate a polynomial because of its simple approach and lesser arithmetic operations. + DESIGN: +We can give the general form of the polynomial equation by: + a0x^0 + a1x^1 + a2x^2 +......anx^n +In general,given the polynomial of the form, + a0x^0 + a1x^1 + a2x^2 + .......+ an-2x^n-2 + an-1x^n-1 + anx^n + We can rearrange this as shown below: + a0 + x(a1 + x(a2 + x(a3 + x(a4+...............x(an-4 + x(an-3 + x(an-2 + x(an-1 + xan))))....)))) +The above representation requires only 'n' multiplications and 'n' additions there by number of computations can be reduced and efficiency +can be improved.This method of solving the polynomial is called HORNER'S method of evaluating polynomial. +The equation can be written in reverse as shown below: +((((anx + an-1)x + an-2)x + an-3)x....+ a3)x + a2)x + a1)x + a0 +This can be generally written as : +sum + a0 +In general,we can write sum =(sum + ai)x for i=n-1,n-2,.....3,2,1 +The partial algorithm can be written as: + + sum = a[n]*x + for i= n-1 down to 1 + sum = (sum + a[i]) * x + end for + sum = sum + a[0]; + +The complete c function can be written as: + + double evaluate(double a[],int n,double x) + { + double sum; + int i; + .................................. + sum = a[n] * x; + .................................. + for(i=n-1;i>=1;i--) + { + sum = (sum + a[i]) * x; + } + .................................. + sum = sum + a[0]; + .................................. + return sum; + } + From cfa4c6cc17d8e50b189b0c3d545fe608954c4cec Mon Sep 17 00:00:00 2001 From: Subhashreemurugaraj <43822391+Subhashreemurugaraj@users.noreply.github.com> Date: Mon, 8 Oct 2018 21:36:38 +0530 Subject: [PATCH 29/54] Create selection sort --- selection sort | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 selection sort diff --git a/selection sort b/selection sort new file mode 100644 index 0000000..b0ffb9a --- /dev/null +++ b/selection sort @@ -0,0 +1,4 @@ +Selection sort is a sorting technique whose main idea is to select the smallest element in the unsorted array repeatedly. +The smallest element of unsorted array selected is swapped with the first element of the unsorted array. +If there are n elements then the array can be sorted in n-1 passes. +In each pass, the smallest element of unsorted array is exchanged with first element of unsorted array. From c371ce1a87f3e7bbf7020c8505379c69e8e20e57 Mon Sep 17 00:00:00 2001 From: Subhashreemurugaraj <43822391+Subhashreemurugaraj@users.noreply.github.com> Date: Mon, 8 Oct 2018 22:12:57 +0530 Subject: [PATCH 30/54] Create recursion --- recursion | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 recursion diff --git a/recursion b/recursion new file mode 100644 index 0000000..6aebf9a --- /dev/null +++ b/recursion @@ -0,0 +1,6 @@ +A fuction calling itself in its own body is called a recursive fuction. +Few recursive fuctions are factorial function,ackermann fuction,tower of hanoi,fibonacci series. +A recursive function has two parts. +i)base condition or terminating condition: there must be a reachable condition for function termination otherwise the fuction will be invoked endlessly. +ii)recursive call: the solution is divided into simpler parts. The result is obtained by combining the solutions of all these simpler parts. +Thus, one can say recursion is an example of divide and conquer method. From ca2535e71711432efd0510edf56826ffdf9e7196 Mon Sep 17 00:00:00 2001 From: Subhashreemurugaraj <43822391+Subhashreemurugaraj@users.noreply.github.com> Date: Mon, 8 Oct 2018 22:48:48 +0530 Subject: [PATCH 31/54] Create Ackermann function --- Ackermann function | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 Ackermann function diff --git a/Ackermann function b/Ackermann function new file mode 100644 index 0000000..8d81d56 --- /dev/null +++ b/Ackermann function @@ -0,0 +1,6 @@ +Ackermann function A(m,n) is a function with two parameters m and n. Both m and n are non negative integers.It uses the concept of recursion. +It is defined as follows: +i)If m=0, then A(m,n)=n+1 +ii)If m!=0 and n=0, then A(m,n)=A(m-1,1) +iii)If m!=0 and n!=0, then A(m,n)=A(m-1,A(m,n-1) +Ackermann function grows quickly. From aa63e61f430b907bc4b2b777e8495b543f5e7f84 Mon Sep 17 00:00:00 2001 From: Subhashreemurugaraj <43822391+Subhashreemurugaraj@users.noreply.github.com> Date: Mon, 8 Oct 2018 23:09:14 +0530 Subject: [PATCH 32/54] Create linear search --- linear search | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 linear search diff --git a/linear search b/linear search new file mode 100644 index 0000000..7591cec --- /dev/null +++ b/linear search @@ -0,0 +1,6 @@ +Let arr be an array comprising of n elements.The objective is to search for a given key in arr. +We compare the key with each element of arr.If found ,the position of the element is returned. +At the end of this process,if key not found in arr then -1 is returned. +This method which traverses arr sequentially to search key is known as linear search. +In the main function, if key found then the position is printed. +Otherwise, unsuccessful search is printed. From 5a0df3af14293331f543be633d210448ef212bc3 Mon Sep 17 00:00:00 2001 From: Subhashreemurugaraj <43822391+Subhashreemurugaraj@users.noreply.github.com> Date: Mon, 8 Oct 2018 23:30:08 +0530 Subject: [PATCH 33/54] Create concatenation --- concatenation | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 concatenation diff --git a/concatenation b/concatenation new file mode 100644 index 0000000..ff06a30 --- /dev/null +++ b/concatenation @@ -0,0 +1,2 @@ +concatenation is combining two strings one after the other. +For example, if "honey" and "bee" are two strings then the concatenated string would be "honeybee". From 386a05b4064bd18843e07ef8ae59a29fa82430f5 Mon Sep 17 00:00:00 2001 From: Arun Kumar <33377005+aroonkp@users.noreply.github.com> Date: Thu, 11 Oct 2018 22:07:40 +0530 Subject: [PATCH 34/54] Add files via upload --- bruteForce.txt | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 bruteForce.txt diff --git a/bruteForce.txt b/bruteForce.txt new file mode 100644 index 0000000..128437e --- /dev/null +++ b/bruteForce.txt @@ -0,0 +1,38 @@ +Brute Force algorithm: + +Description: + +The brute force algorithm consists in checking, at all positions in the text between 0 and n-m, whether an occurrence of the pattern starts there or not. Then, after each attempt, it shifts the pattern by exactly one position to the right. + +The brute force algorithm requires no preprocessing phase, and a constant extra space in addition to the pattern and the text. During the searching phase the text character comparisons can be done in any order. The time complexity of this searching phase is O(mn) (when searching for am-1b in an for instance). The expected number of text character comparisons is 2n. + + + +The C code: + +void BF(char *x, int m, char *y, int n) { + int i, j; + + /* Searching */ + for (j = 0; j <= n - m; ++j) { + for (i = 0; i < m && x[i] == y[i + j]; ++i); + if (i >= m) + OUTPUT(j); + } +} + + +This algorithm can be rewriting to give a more efficient algorithm in practice as follows: + +#define EOS '\0' + +void BF(char *x, int m, char *y, int n) { + char *yb; + /* Searching */ + for (yb = y; *y != EOS; ++y) + if (memcmp(x, y, m) == 0) + OUTPUT(y - yb); +} + + + From c08565759afde874bafaf5a6332874dcc6c0b1f0 Mon Sep 17 00:00:00 2001 From: Arun Kumar <33377005+aroonkp@users.noreply.github.com> Date: Thu, 11 Oct 2018 23:07:21 +0530 Subject: [PATCH 35/54] Create TopologicalSorting --- TopologicalSorting | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 TopologicalSorting diff --git a/TopologicalSorting b/TopologicalSorting new file mode 100644 index 0000000..6f7fd46 --- /dev/null +++ b/TopologicalSorting @@ -0,0 +1,28 @@ +int * topoSort(vector graph[], int N) +{ + int indegree[N] = {0}; + int* topo = new int[N+1]; + + for(int j = 0;j:: iterator i; + for(i = graph[j].begin();i!=graph[j].end();++i){ + indegree[*i]++; + } + } + queue q; + for(int i=0;i:: iterator i; + for(i = graph[top].begin();i!=graph[top].end();++i){ + indegree[*i]--; + if(indegree[*i] == 0) q.push(*i); + } + } + return topo; +} From adc785da53430d423fc8ef7abf557112e1f97049 Mon Sep 17 00:00:00 2001 From: Arun Kumar <33377005+aroonkp@users.noreply.github.com> Date: Thu, 11 Oct 2018 23:08:39 +0530 Subject: [PATCH 36/54] Create SudokuSolver --- SudokuSolver | 102 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 SudokuSolver diff --git a/SudokuSolver b/SudokuSolver new file mode 100644 index 0000000..f77cae9 --- /dev/null +++ b/SudokuSolver @@ -0,0 +1,102 @@ +#include +using namespace std; +///N=9; +int n=9; + + +bool isPossible(int mat[][9],int i,int j,int no){ + ///Row or col nahin hona chahiye + for(int x=0;x Date: Mon, 15 Oct 2018 00:59:17 +0530 Subject: [PATCH 37/54] =?UTF-8?q?Create=20Dijkstra=E2=80=99s=20shortest=20?= =?UTF-8?q?path=20algorithm?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...stra\342\200\231s shortest path algorithm" | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 "Dijkstra\342\200\231s shortest path algorithm" diff --git "a/Dijkstra\342\200\231s shortest path algorithm" "b/Dijkstra\342\200\231s shortest path algorithm" new file mode 100644 index 0000000..225554b --- /dev/null +++ "b/Dijkstra\342\200\231s shortest path algorithm" @@ -0,0 +1,21 @@ +Dijkstra’s algorithm is very similar to Prim’s algorithm for minimum spanning tree. Like Prim’s MST, we generate a +SPT (shortest path tree) with given source as root. We maintain two sets, one set contains vertices included in shortest +path tree, other set includes vertices not yet included in shortest path tree. At every step of the algorithm, we find +a vertex which is in the other set (set of not yet included) and has a minimum distance from the source. + +Below are the detailed steps used in Dijkstra’s algorithm to find the shortest path from a single source vertex to all +other vertices in the given graph. + +Algorithm +1) Create a set sptSet (shortest path tree set) that keeps track of vertices included in shortest path tree, i.e., +whose minimum distance from source is calculated and finalized. Initially, this set is empty. +2) Assign a distance value to all vertices in the input graph. Initialize all distance values as INFINITE. +Assign distance value as 0 for the source vertex so that it is picked first. +3) While sptSet doesn’t include all vertices +….a) Pick a vertex u which is not there in sptSet and has minimum distance value. +….b) Include u to sptSet. +….c) Update distance value of all adjacent vertices of u. To update the distance values, iterate through all + adjacent vertices. For every adjacent vertex v, if sum of distance value of u (from source) and weight of + edge u-v, is less than the distance value of v, then update the distance value of v. + + From a83cfec5cc978d853fc082d8200c84c108c71dbc Mon Sep 17 00:00:00 2001 From: Akshat Jaipuria <38358340+akshatjaipuria@users.noreply.github.com> Date: Mon, 15 Oct 2018 23:04:21 +0530 Subject: [PATCH 38/54] Create Binary Search --- Binary Search | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Binary Search diff --git a/Binary Search b/Binary Search new file mode 100644 index 0000000..3ec3518 --- /dev/null +++ b/Binary Search @@ -0,0 +1,44 @@ +class BinarySearch +{ + // Returns index of x if it is present in arr[], + // else return -1 + int binarySearch(int arr[], int x) + { + int l = 0, r = arr.length - 1; + while (l <= r) + { + int m = l + (r-l)/2; + + // Check if x is present at mid + if (arr[m] == x) + return m; + + // If x greater, ignore left half + if (arr[m] < x) + l = m + 1; + + // If x is smaller, ignore right half + else + r = m - 1; + } + + // if we reach here, then element was + // not present + return -1; + } + + // Driver method to test above + public static void main(String args[]) + { + BinarySearch ob = new BinarySearch(); + int arr[] = {2, 3, 4, 10, 40}; + int n = arr.length; + int x = 10; + int result = ob.binarySearch(arr, x); + if (result == -1) + System.out.println("Element not present"); + else + System.out.println("Element found at " + + "index " + result); + } +} From 4f66c527f47c81ff6c9e1049194621c7c81b6b39 Mon Sep 17 00:00:00 2001 From: hrishikesh verma Date: Tue, 16 Oct 2018 17:09:14 +0530 Subject: [PATCH 39/54] Create Job Sequencing Problem --- Job Sequencing Problem | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Job Sequencing Problem diff --git a/Job Sequencing Problem b/Job Sequencing Problem new file mode 100644 index 0000000..605132d --- /dev/null +++ b/Job Sequencing Problem @@ -0,0 +1,30 @@ +greedy algorithm + +Given an array of jobs where every job has a deadline and associated profit if the job is finished before the deadline. +It is also given that every job takes single unit of time, so the minimum possible deadline for any job is 1. How to +maximize total profit if only one job can be scheduled at a time. + +Example: + +Input: Five Jobs with following deadlines and profits + JobID Deadline Profit + a 2 100 + b 1 19 + c 2 27 + d 1 25 + e 3 15 +Output: Following is maximum profit sequence of jobs + c, a, e + + A Simple Solution is to generate all subsets of given set of jobs and check individual subset for feasibility of jobs in + that subset. Keep track of maximum profit among all feasible subsets. The time complexity of this solution is exponential. + + This is a standard Greedy Algorithm problem. Following is algorithm. +1) Sort all jobs in decreasing order of profit. +2) Initialize the result sequence as first job in sorted jobs. +3) Do following for remaining n-1 jobs +.......a) If the current job can fit in the current result sequence + without missing the deadline, add current job to the result. + Else ignore the current job. + +Time Complexity of the above algo is O(n2). From b7bae6de71856720dd9b7fd69bf901fd9754ae02 Mon Sep 17 00:00:00 2001 From: hrishikesh verma Date: Tue, 16 Oct 2018 17:15:49 +0530 Subject: [PATCH 40/54] Create huffman coding --- huffman coding | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 huffman coding diff --git a/huffman coding b/huffman coding new file mode 100644 index 0000000..68cf13e --- /dev/null +++ b/huffman coding @@ -0,0 +1,31 @@ +Huffman coding is a lossless data compression algorithm. The idea is to assign variable-length codes to input characters, +lengths of the assigned codes are based on the frequencies of corresponding characters. The most frequent character gets +the smallest code and the least frequent character gets the largest code. + +The variable-length codes assigned to input characters are Prefix Codes, means the codes (bit sequences) are assigned in +such a way that the code assigned to one character is not prefix of code assigned to any other character. This is how Huffman +Coding makes sure that there is no ambiguity when decoding the generated bit stream. + + Let us understand prefix codes with a counter example. Let there be four characters a, b, c and d, and their corresponding + variable length codes be 00, 01, 0 and 1. This coding leads to ambiguity because code assigned to c is prefix of codes + assigned to a and b. If the compressed bit stream is 0001, the de-compressed output may be “cccd” or “ccb” or “acd” or “ab”. + + See this for applications of Huffman Coding. + +There are mainly two major parts in Huffman Coding +1) Build a Huffman Tree from input characters. +2) Traverse the Huffman Tree and assign codes to characters. + +Steps to build Huffman Tree +Input is array of unique characters along with their frequency of occurrences and output is Huffman Tree. + +1. Create a leaf node for each unique character and build a min heap of all leaf nodes (Min Heap is used as a priority queue. +The value of frequency field is used to compare two nodes in min heap. Initially, the least frequent character is at root) + +2. Extract two nodes with the minimum frequency from the min heap. + +3. Create a new internal node with frequency equal to the sum of the two nodes frequencies. Make the first extracted node as +its left child and the other extracted node as its right child. Add this node to the min heap. + +4. Repeat steps#2 and #3 until the heap contains only one node. The remaining node is the root node and the tree is complete. + From eee1e87c324411b19dbfeab60c0f4632aaef83f1 Mon Sep 17 00:00:00 2001 From: hrishikesh verma Date: Tue, 16 Oct 2018 17:24:39 +0530 Subject: [PATCH 41/54] Create n queen problem --- n queen problem | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 n queen problem diff --git a/n queen problem b/n queen problem new file mode 100644 index 0000000..f508d69 --- /dev/null +++ b/n queen problem @@ -0,0 +1,44 @@ +We have discussed Knight’s tour and Rat in a Maze problems in Set 1 and Set 2 respectively. Let us discuss N Queen as another +example problem that can be solved using Backtracking. + +The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example, +following is a solution for 4 Queen problem. + +The expected output is a binary matrix which has 1s for the blocks where queens are placed. For example, following is the +output matrix for above 4 queen solution. + { 0, 1, 0, 0} + { 0, 0, 0, 1} + { 1, 0, 0, 0} + { 0, 0, 1, 0} + +***Naive Algorithm +Generate all possible configurations of queens on board and print a configuration that satisfies the given constraints. + +while there are untried configurations +{ + generate the next configuration + if queens don't attack in this configuration then + { + print this configuration; + } +} + +***Backtracking Algorithm +The idea is to place queens one by one in different columns, starting from the leftmost column. When we place a queen in a +column, we check for clashes with already placed queens. In the current column, if we find a row for which there is no clash, +we mark this row and column as part of the solution. If we do not find such a row due to clashes then we backtrack and +return false. + +1) Start in the leftmost column +2) If all queens are placed + return true +3) Try all rows in the current column. Do following for every tried row. + a) If the queen can be placed safely in this row then mark this [row, + column] as part of the solution and recursively check if placing + queen here leads to a solution. + b) If placing the queen in [row, column] leads to a solution then return + true. + c) If placing queen doesn't lead to a solution then umark this [row, + column] (Backtrack) and go to step (a) to try other rows. +3) If all rows have been tried and nothing worked, return false to trigger + backtracking. From 9f54db06144ae448bd2399d9cd85790f3749f5eb Mon Sep 17 00:00:00 2001 From: hrishikesh verma Date: Tue, 16 Oct 2018 17:30:58 +0530 Subject: [PATCH 42/54] Create Hamiltonian Cycle --- Hamiltonian Cycle | 53 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Hamiltonian Cycle diff --git a/Hamiltonian Cycle b/Hamiltonian Cycle new file mode 100644 index 0000000..c2951ef --- /dev/null +++ b/Hamiltonian Cycle @@ -0,0 +1,53 @@ +Hamiltonian Path in an undirected graph is a path that visits each vertex exactly once. A Hamiltonian cycle (or Hamiltonian +circuit) is a Hamiltonian Path such that there is an edge (in graph) from the last vertex to the first vertex of the Hamiltonian +Path. Determine whether a given graph contains Hamiltonian Cycle or not. If it contains, then print the path. Following are the +input and output of the required function. + +Input: +A 2D array graph[V][V] where V is the number of vertices in graph and graph[V][V] is adjacency matrix representation of the +graph. A value graph[i][j] is 1 if there is a direct edge from i to j, otherwise graph[i][j] is 0. + +Output: +An array path[V] that should contain the Hamiltonian Path. path[i] should represent the ith vertex in the Hamiltonian Path. +The code should also return false if there is no Hamiltonian Cycle in the graph. + +For example, a Hamiltonian Cycle in the following graph is {0, 1, 2, 4, 3, 0}. There are more Hamiltonian Cycles in the graph +like {0, 3, 4, 2, 1, 0} + +(0)--(1)--(2) + | / \ | + | / \ | + | / \ | +(3)-------(4) + +And the following graph doesn’t contain any Hamiltonian Cycle. + +(0)--(1)--(2) + | / \ | + | / \ | + | / \ | +(3) (4) + + +Naive Algorithm +Generate all possible configurations of vertices and print a configuration that satisfies the given constraints. +There will be n! (n factorial) configurations. + +while there are untried conflagrations +{ + generate the next configuration + if ( there are edges between two consecutive vertices of this + configuration and there is an edge from the last vertex to + the first ). + { + print this configuration; + break; + } +} + + + +Backtracking Algorithm +Create an empty path array and add vertex 0 to it. Add other vertices, starting from the vertex 1. Before adding a vertex, +check for whether it is adjacent to the previously added vertex and not already added. If we find such a vertex, we add the +vertex as part of the solution. If we do not find a vertex then we return false. From 825827a48b951672aca0c922c776afee315bccac Mon Sep 17 00:00:00 2001 From: itsabhi16 <32833933+itsabhi16@users.noreply.github.com> Date: Wed, 17 Oct 2018 17:24:09 +0530 Subject: [PATCH 43/54] Add Tsp --- Tsp | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Tsp diff --git a/Tsp b/Tsp new file mode 100644 index 0000000..f276e40 --- /dev/null +++ b/Tsp @@ -0,0 +1,7 @@ +1) Consider city 1 as the starting and ending point. +2) Generate all (n-1)! Permutations of cities. +3) Calculate cost of every permutation and keep track of minimum cost permutation. +4) Return the permutation with minimum cost. + +Time Complexity: Θ(n!) + From 77fbff4908b99dc77098c8c0b83e6d31ec673be7 Mon Sep 17 00:00:00 2001 From: Ruchika Jain <31808822+ruchika-jain@users.noreply.github.com> Date: Wed, 17 Oct 2018 21:20:50 +0530 Subject: [PATCH 44/54] Update selection sort --- selection sort | 73 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/selection sort b/selection sort index b0ffb9a..d021782 100644 --- a/selection sort +++ b/selection sort @@ -2,3 +2,76 @@ Selection sort is a sorting technique whose main idea is to select the smallest The smallest element of unsorted array selected is swapped with the first element of the unsorted array. If there are n elements then the array can be sorted in n-1 passes. In each pass, the smallest element of unsorted array is exchanged with first element of unsorted array. +The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array. + +1) The subarray which is already sorted. +2) Remaining subarray which is unsorted. + +In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray. +For example, +arr[] = 64 25 12 22 11 + +// Find the minimum element in arr[0...4] +// and place it at beginning +11 25 12 22 64 + +// Find the minimum element in arr[1...4] +// and place it at beginning of arr[1...4] +11 12 25 22 64 + +// Find the minimum element in arr[2...4] +// and place it at beginning of arr[2...4] +11 12 22 25 64 + +// Find the minimum element in arr[3...4] +// and place it at beginning of arr[3...4] +11 12 22 25 64 + +// C program for implementation of selection sort +#include + +void swap(int *xp, int *yp) +{ + int temp = *xp; + *xp = *yp; + *yp = temp; +} + +void selectionSort(int arr[], int n) +{ + int i, j, min_idx; + + // One by one move boundary of unsorted subarray + for (i = 0; i < n-1; i++) + { + // Find the minimum element in unsorted array + min_idx = i; + for (j = i+1; j < n; j++) + if (arr[j] < arr[min_idx]) + min_idx = j; + + // Swap the found minimum element with the first element + swap(&arr[min_idx], &arr[i]); + } +} + +/* Function to print an array */ +void printArray(int arr[], int size) +{ + int i; + for (i=0; i < size; i++) + printf("%d ", arr[i]); + printf("\n"); +} + +// Driver program to test above functions +int main() +{ + int arr[] = {64, 25, 12, 22, 11}; + int n = sizeof(arr)/sizeof(arr[0]); + selectionSort(arr, n); + printf("Sorted array: \n"); + printArray(arr, n); + return 0; +} + From db53e0c7d40ca28a9ebce5ce6cd8b080e88e6d52 Mon Sep 17 00:00:00 2001 From: Barkha Date: Tue, 23 Oct 2018 22:57:00 +0530 Subject: [PATCH 45/54] Finding Kth Smallest/Largest Element in Unsorted Array --- find.txt | 91 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 find.txt diff --git a/find.txt b/find.txt new file mode 100644 index 0000000..19f5787 --- /dev/null +++ b/find.txt @@ -0,0 +1,91 @@ +K’th Smallest/Largest Element in Unsorted Array + +Given an array and a number k where k is smaller than the size of the array, we need to find the k’th smallest element in the given array. It is given that all array elements are distinct. + +Examples: + +Input: arr[] = {7, 10, 4, 3, 20, 15} + k = 3 +Output: 7 + +Input: arr[] = {7, 10, 4, 3, 20, 15} + k = 4 +Output: 10 + + +// C++ implementation of randomized quickSelect +#include +#include +#include +using namespace std; + +int randomPartition(int arr[], int l, int r); + +// This function returns k'th smallest element in arr[l..r] using +// QuickSort based method. ASSUMPTION: ELEMENTS IN ARR[] ARE DISTINCT +int kthSmallest(int arr[], int l, int r, int k) +{ + // If k is smaller than number of elements in array + if (k > 0 && k <= r - l + 1) + { + // Partition the array around a random element and + // get position of pivot element in sorted array + int pos = randomPartition(arr, l, r); + + // If position is same as k + if (pos-l == k-1) + return arr[pos]; + if (pos-l > k-1) // If position is more, recur for left subarray + return kthSmallest(arr, l, pos-1, k); + + // Else recur for right subarray + return kthSmallest(arr, pos+1, r, k-pos+l-1); + } + + // If k is more than the number of elements in the array + return INT_MAX; +} + +void swap(int *a, int *b) +{ + int temp = *a; + *a = *b; + *b = temp; +} + +// Standard partition process of QuickSort(). It considers the last +// element as pivot and moves all smaller element to left of it and +// greater elements to right. This function is used by randomPartition() +int partition(int arr[], int l, int r) +{ + int x = arr[r], i = l; + for (int j = l; j <= r - 1; j++) + { + if (arr[j] <= x) + { + swap(&arr[i], &arr[j]); + i++; + } + } + swap(&arr[i], &arr[r]); + return i; +} + +// Picks a random pivot element between l and r and partitions +// arr[l..r] around the randomly picked element using partition() +int randomPartition(int arr[], int l, int r) +{ + int n = r-l+1; + int pivot = rand() % n; + swap(&arr[l + pivot], &arr[r]); + return partition(arr, l, r); +} + +// Driver program to test above methods +int main() +{ + int arr[] = {12, 3, 5, 7, 4, 19, 26}; + int n = sizeof(arr)/sizeof(arr[0]), k = 3; + cout << "K'th smallest element is " << kthSmallest(arr, 0, n-1, k); + return 0; +} From 0dfe921fc897c287cc66f66e5008ba006459c304 Mon Sep 17 00:00:00 2001 From: Barkha Date: Tue, 23 Oct 2018 23:20:55 +0530 Subject: [PATCH 46/54] Finding Kth greatest/smallest number in unsorted array --- find.txt => finding.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename find.txt => finding.txt (96%) diff --git a/find.txt b/finding.txt similarity index 96% rename from find.txt rename to finding.txt index 19f5787..d917910 100644 --- a/find.txt +++ b/finding.txt @@ -18,7 +18,7 @@ Output: 10 #include #include using namespace std; - + int randomPartition(int arr[], int l, int r); // This function returns k'th smallest element in arr[l..r] using From 04011202632d0ab8d4227dca60261dfc066cb850 Mon Sep 17 00:00:00 2001 From: rakeshgupta9764 Date: Fri, 26 Oct 2018 18:46:18 +0530 Subject: [PATCH 47/54] Add Roots of Unity --- Roots of Unity | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 Roots of Unity diff --git a/Roots of Unity b/Roots of Unity new file mode 100644 index 0000000..7c47fbe --- /dev/null +++ b/Roots of Unity @@ -0,0 +1,76 @@ +

+Any complex number is said to be root of unity if it gives 1 when raised to some power. + +nth root of unity is any complex number such that it gives 1 when raised to the power n. +

+ +
+Mathematically, 
+An nth root of unity, where n is a positive integer 
+(i.e. n = 1, 2, 3, …) is a number z satisfying the
+equation 
+
+z^n  = 1
+or , 
+z^n - 1 = 0
+
+ +

+We can use the De Moivre’s formula here. +

+ +
+( Cos x + i Sin x )^k = Cos kx + i Sin kx
+
+Setting x = 2*pi/n, we can obtain all the nth roots 
+of unity, using the fact that Nth roots are set of 
+numbers given by,
+
+Cos (2*pi*k/n) + i Sin(2*pi*k/n)
+Where, 0 <= k < n
+
+ +

+Using the above fact we can easily print all the nth roots of unity ! +Below is a C program for the same. +

+ + +#include +#include + + +// A C program to print n'th roots of unity + + +// This function receives an integer n , and prints +// all the nth roots of unity +void printRoots(int n) +{ + // theta = 2*pi/n + double theta = M_PI*2/n; + + // print all nth roots with 6 significant digits + for(int k=0; k= 0? printf(" + i "): printf(" - i "); + printf("%.6f\n", fabs(img)); + } +} + +// Driver function to check the program +int main() +{ + printRoots(1); + printf("\n"); + printRoots(2); + printf("\n"); + printRoots(3); + return 0; +} From f0bca7e246f328280d98541957c6c03813c8e97c Mon Sep 17 00:00:00 2001 From: rakeshgupta9764 Date: Fri, 26 Oct 2018 18:54:44 +0530 Subject: [PATCH 48/54] Add Roots of Unity --- Roots of Unity | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/Roots of Unity b/Roots of Unity index 7c47fbe..d1ec466 100644 --- a/Roots of Unity +++ b/Roots of Unity @@ -1,10 +1,7 @@ -

Any complex number is said to be root of unity if it gives 1 when raised to some power. nth root of unity is any complex number such that it gives 1 when raised to the power n. -

-
 Mathematically, 
 An nth root of unity, where n is a positive integer 
 (i.e. n = 1, 2, 3, …) is a number z satisfying the
@@ -13,13 +10,9 @@ equation
 z^n  = 1
 or , 
 z^n - 1 = 0
-
-

We can use the De Moivre’s formula here. -

-
 ( Cos x + i Sin x )^k = Cos kx + i Sin kx
 
 Setting x = 2*pi/n, we can obtain all the nth roots 
@@ -28,12 +21,9 @@ numbers given by,
 
 Cos (2*pi*k/n) + i Sin(2*pi*k/n)
 Where, 0 <= k < n
-
-

Using the above fact we can easily print all the nth roots of unity ! Below is a C program for the same. -

#include From 887595fd26cb8c5a417f428e5b414cea159a0876 Mon Sep 17 00:00:00 2001 From: rakeshgupta9764 Date: Fri, 26 Oct 2018 19:32:48 +0530 Subject: [PATCH 49/54] Create Find remainder without using % operator --- ...mainder without using modulo or % operator | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Find remainder without using modulo or % operator diff --git a/Find remainder without using modulo or % operator b/Find remainder without using modulo or % operator new file mode 100644 index 0000000..3695a29 --- /dev/null +++ b/Find remainder without using modulo or % operator @@ -0,0 +1,55 @@ +Given two numbers ‘num’ and ‘divisor’, find remainder when ‘num’ is divided by ‘divisor’. +The use of modulo or % operator is not allowed. + +Examples : + +Input: num = 100, divisor = 7 +Output: 2 + +Input: num = 30, divisor = 9 +Output: 3 + +The idea is simple, we run a loop to find the largest multiple of ‘divisor’ that is smaller than or equal to ‘num’. +Once we find such a multiple, we subtract the multiple from ‘num’ to find the divisor. + + +// C++ program to find remainder without using modulo operator +#include +using namespace std; + +// This function returns remainder of num/divisor without +// using % (modulo) operator +int getRemainder(int num, int divisor) +{ + // Handle divisor equals to 0 case + if (divisor == 0) + { + cout << "Error: divisor can't be zero \n"; + return -1; + } + + // Handle negative values + if (divisor < 0) divisor = -divisor; + if (num < 0) num = -num; + + // Find the largest product of 'divisor' that is smaller + // than or equal to 'num' + int i = 1; + int product = 0; + while (product <= num) + { + product = divisor * i; + i++; + } + + // return remainder + return num - (product - divisor); +} + +// Driver program to test above functions +int main() +{ + // cout << 100 %0; + cout << getRemainder(100, 7); + return 0; +} From c7999be96fa2c3c8b3aaeed4faf0d0882bb2657f Mon Sep 17 00:00:00 2001 From: rakeshgupta9764 Date: Fri, 26 Oct 2018 20:13:17 +0530 Subject: [PATCH 50/54] Create Basic Euclidean Algorithm for GCD --- Basic Euclidean Algorithm for GCD | 45 +++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Basic Euclidean Algorithm for GCD diff --git a/Basic Euclidean Algorithm for GCD b/Basic Euclidean Algorithm for GCD new file mode 100644 index 0000000..9f7a991 --- /dev/null +++ b/Basic Euclidean Algorithm for GCD @@ -0,0 +1,45 @@ +The algorithm is based on below facts. + +If we subtract smaller number from larger (we reduce larger number), GCD doesn’t change. So if we keep subtracting repeatedly the larger of two, we end up with GCD. +Now instead of subtraction, if we divide smaller number, the algorithm stops when we find remainder 0. +Below is a recursive function to evaluate gcd using Euclid’s algorithm. + + + +// C++ program to demonstrate +// Basic Euclidean Algorithm +#include +using namespace std; + +// Function to return +// gcd of a and b +int gcd(int a, int b) +{ + if (a == 0) + return b; + return gcd(b % a, a); +} + + +int main() +{ + int a = 10, b = 15; + cout << "GCD(" << a << ", " + << b << ") = " << gcd(a, b) + << endl; + a = 35, b = 10; + cout << "GCD(" << a << ", " + << b << ") = " << gcd(a, b) + << endl; + a = 31, b = 2; + cout << "GCD(" << a << ", " + << b << ") = " << gcd(a, b) + << endl; + return 0; +} + + +Output: +GCD(10, 15) = 5 +GCD(35, 10) = 5 +GCD(31, 2) = 1 From f740a486f15f6a7a36298617d235419bf8b019ec Mon Sep 17 00:00:00 2001 From: rakeshgupta9764 Date: Fri, 26 Oct 2018 20:15:41 +0530 Subject: [PATCH 51/54] Extended Euclidean Algorithm --- Extended Euclidean Algorithm | 62 ++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Extended Euclidean Algorithm diff --git a/Extended Euclidean Algorithm b/Extended Euclidean Algorithm new file mode 100644 index 0000000..8172808 --- /dev/null +++ b/Extended Euclidean Algorithm @@ -0,0 +1,62 @@ +Extended Euclidean Algorithm: +Extended Euclidean algorithm also finds integer coefficients x and y such that: + + ax + by = gcd(a, b) +Examples: + +Input: a = 30, b = 20 +Output: gcd = 10 + x = 1, y = -1 +(Note that 30*1 + 20*(-1) = 10) + +Input: a = 35, b = 15 +Output: gcd = 5 + x = 1, y = -2 +(Note that 10*0 + 5*1 = 5) +The extended Euclidean algorithm updates results of gcd(a, b) using the results calculated by recursive call gcd(b%a, a). Let values of x and y calculated by the recursive call be x1 and y1. x and y are updated using below expressions. + + +x = y1 - ⌊b/a⌋ * x1 +y = x1 + + +// C program to demonstrate working of extended +// Euclidean Algorithm +#include + +// C function for extended Euclidean Algorithm +int gcdExtended(int a, int b, int *x, int *y) +{ + // Base Case + if (a == 0) + { + *x = 0; + *y = 1; + return b; + } + + int x1, y1; // To store results of recursive call + int gcd = gcdExtended(b%a, a, &x1, &y1); + + // Update x and y using results of recursive + // call + *x = y1 - (b/a) * x1; + *y = x1; + + return gcd; +} + + +int main() +{ + int x, y; + int a = 35, b = 15; + int g = gcdExtended(a, b, &x, &y); + printf("gcd(%d, %d) = %d", a, b, g); + return 0; +} + + + +Output : +gcd(35, 15) = 5 From 9a90627fa7fb0d8a5fa9a94ab7a8285a57fcd607 Mon Sep 17 00:00:00 2001 From: Mohit Sinha Date: Sat, 27 Oct 2018 12:05:03 +0530 Subject: [PATCH 52/54] AM Series --- Ackermann function | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/Ackermann function b/Ackermann function index 8d81d56..8934c02 100644 --- a/Ackermann function +++ b/Ackermann function @@ -4,3 +4,22 @@ i)If m=0, then A(m,n)=n+1 ii)If m!=0 and n=0, then A(m,n)=A(m-1,1) iii)If m!=0 and n!=0, then A(m,n)=A(m-1,A(m,n-1) Ackermann function grows quickly. + +#include + +int ackermann(int m, int n) +{ + if (!m) return n + 1; + if (!n) return ackermann(m - 1, 1); + return ackermann(m - 1, ackermann(m, n - 1)); +} + +int main() +{ + int m, n; + for (m = 0; m <= 4; m++) + for (n = 0; n < 6 - m; n++) + printf("A(%d, %d) = %d\n", m, n, ackermann(m, n)); + + return 0; +} \ No newline at end of file From 658ae371e7392ff6b4923153d62609772db3ed95 Mon Sep 17 00:00:00 2001 From: Akash Date: Sat, 27 Oct 2018 15:22:50 +0530 Subject: [PATCH 53/54] added a code --- binary search | 44 ++++++++++++++++++++++++++++++++++++++------ 1 file changed, 38 insertions(+), 6 deletions(-) diff --git a/binary search b/binary search index 3c26515..c561a68 100644 --- a/binary search +++ b/binary search @@ -1,6 +1,38 @@ -Binary search is a technique to search an item thereby finding its position in a sorted array. -It basically divides the sorted array into two parts by comparing the item with the middle element. -If it matches then the position is returned. -Else it continues searching in either of the two parts depending on its value. -This process continues and each time the item is compared with the updated mid value. -If mid value is not returned after the process ends then item is not found. +#include + +int main() +{ + int c, first, last, middle, n, search, array[100]; + + printf("Enter number of elements\n"); + scanf("%d",&n); + + printf("Enter %d integers\n", n); + + for (c = 0; c < n; c++) + scanf("%d",&array[c]); + + printf("Enter value to find\n"); + scanf("%d", &search); + + first = 0; + last = n - 1; + middle = (first+last)/2; + + while (first <= last) { + if (array[middle] < search) + first = middle + 1; + else if (array[middle] == search) { + printf("%d found at location %d.\n", search, middle+1); + break; + } + else + last = middle - 1; + + middle = (first + last)/2; + } + if (first > last) + printf("Not found! %d isn't present in the list.\n", search); + + return 0; +} \ No newline at end of file From dddc9de4c2b23526b9949ed6a1b5f3087e7fe115 Mon Sep 17 00:00:00 2001 From: akhilkasetty <34038673+akhilkasetty@users.noreply.github.com> Date: Sun, 28 Oct 2018 15:11:59 +0530 Subject: [PATCH 54/54] Create upper and lower triangle matrix --- upper and lower triangle matrix | 63 +++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 upper and lower triangle matrix diff --git a/upper and lower triangle matrix b/upper and lower triangle matrix new file mode 100644 index 0000000..c814ba7 --- /dev/null +++ b/upper and lower triangle matrix @@ -0,0 +1,63 @@ + +// Java program to print Lower +// triangular and Upper triangular +// matrix of an array +class GFG +{ + // method to form lower + // triangular matrix + static void lower(int matrix[][], + int row, int col) + { + int i, j; + for (i = 0; i < row; i++) + { + for (j = 0; j < col; j++) + { + if (i < j) + { + System.out.print("0" + " "); + } + else + System.out.print(matrix[i][j] + " "); + } + System.out.println(); + } + } + + // Method to form upper + // triangular matrix + static void upper(int matrix[][], + int row, int col) + { + int i, j; + for (i = 0; i < row; i++) + { + for (j = 0; j < col; j++) + { + if (i > j) + { + System.out.print("0" + " "); + } + else + System.out.print(matrix[i][j] + " "); + } + System.out.println(); + } + } + + // Driver Code + public static void main(String args[]) + { + int matrix[][] = {{1, 2, 3}, + {4, 5, 6}, + {7, 8, 9}}; + int row = 3, col = 3; + + System.out.println("Lower triangular matrix: "); + lower(matrix, row, col); + + System.out.println("Upper triangular matrix: "); + upper(matrix, row, col); + } +}