From 1d1cb672ae92ec6f8fde2739b56c90aa7fbe49af Mon Sep 17 00:00:00 2001 From: exploringcodes <72728328+exploringcodes@users.noreply.github.com> Date: Wed, 14 Oct 2020 14:48:49 +0530 Subject: [PATCH 001/147] Create Billing systems --- Billing systems | 68 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Billing systems diff --git a/Billing systems b/Billing systems new file mode 100644 index 00000000..1610e2bf --- /dev/null +++ b/Billing systems @@ -0,0 +1,68 @@ +#include +using namespace std; + +double getUnitprice(int itemCode); + +int main(){ + + double invoice[10][4]; + int i=0; char more; char date[100]; + + cout << "\n\n********* Here are the Item prices for your information********** \n\nItem code\tUnitPrice\n\n1\t100\n2\t200\n3\t300\nInvalidCode\t0\n\n"; + cout << "Enter the date: "; + cin >> date; + + do { + + cout << "\n\nItem code: "; + cin >> invoice[i][0]; + cout << "Quantity : "; + cin >> invoice[i][1]; + + invoice[i][2] = getUnitprice(invoice[i][0]); + invoice[i][3] = invoice[i][1] * invoice[i][2]; + + cout << "Do you have any other items to be entered next (y/n) ? "; + cin >> more; + + i++; + } while(more == 'y'); + + + cout << "\n\n-----------------------------\n\n"; + cout << "Date : " << date << "\n\n"; + + cout << "ItemCode|Quantity|UnitPrice|TotalPrice\n\n"; + int tot=0; + for(int k=0; k Date: Wed, 14 Oct 2020 15:01:14 +0530 Subject: [PATCH 002/147] Create Bucket sort --- Bucket sort | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Bucket sort diff --git a/Bucket sort b/Bucket sort new file mode 100644 index 00000000..8d8b255a --- /dev/null +++ b/Bucket sort @@ -0,0 +1,40 @@ +#include +#include +#include +using namespace std; +void display(float *array, int size) { + for(int i = 0; i bucket[size]; + for(int i = 0; i> n; + float arr[n]; //create an array with given number of elements + cout << "Enter elements:" << endl; + for(int i = 0; i> arr[i]; + } + cout << "Array before Sorting: "; + display(arr, n); + bucketSort(arr, n); + cout << "Array after Sorting: "; + display(arr, n); +} From e905e21a47ae2f19e27d3fa99fcac6c22538c66f Mon Sep 17 00:00:00 2001 From: Vivek Dubey <72728328+VivekDubey9@users.noreply.github.com> Date: Sat, 2 Oct 2021 07:20:02 +0530 Subject: [PATCH 003/147] dijsltra for shortest path --- dijsktra's algorithm | 94 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 dijsktra's algorithm diff --git a/dijsktra's algorithm b/dijsktra's algorithm new file mode 100644 index 00000000..259ad39f --- /dev/null +++ b/dijsktra's algorithm @@ -0,0 +1,94 @@ +// A C++ program for Dijkstra's single source shortest path algorithm. +// The program is for adjacency matrix representation of the graph +#include +using namespace std; +#include + +// Number of vertices in the graph +#define V 9 + +// A utility function to find the vertex with minimum distance value, from +// the set of vertices not yet included in shortest path tree +int minDistance(int dist[], bool sptSet[]) +{ + + // Initialize min value + int min = INT_MAX, min_index; + + for (int v = 0; v < V; v++) + if (sptSet[v] == false && dist[v] <= min) + min = dist[v], min_index = v; + + return min_index; +} + +// A utility function to print the constructed distance array +void printSolution(int dist[]) +{ + cout <<"Vertex \t Distance from Source" << endl; + for (int i = 0; i < V; i++) + cout << i << " \t\t"< Date: Sat, 2 Oct 2021 07:29:44 +0530 Subject: [PATCH 004/147] Create quick sort cpp --- quick sort cpp | 73 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 quick sort cpp diff --git a/quick sort cpp b/quick sort cpp new file mode 100644 index 00000000..c077bd4e --- /dev/null +++ b/quick sort cpp @@ -0,0 +1,73 @@ +/* C implementation QuickSort */ +#include + +// A utility function to swap two elements +void swap(int* a, int* b) +{ + int t = *a; + *a = *b; + *b = t; +} + +/* This function takes last element as pivot, places +the pivot element at its correct position in sorted + array, and places all smaller (smaller than pivot) +to left of pivot and all greater elements to right +of pivot */ +int partition (int arr[], int low, int high) +{ + int pivot = arr[high]; // pivot + int i = (low - 1); // Index of smaller element + + for (int j = low; j <= high- 1; j++) + { + // If current element is smaller than or + // equal to pivot + if (arr[j] <= pivot) + { + i++; // increment index of smaller element + swap(&arr[i], &arr[j]); + } + } + swap(&arr[i + 1], &arr[high]); + return (i + 1); +} + +/* The main function that implements QuickSort +arr[] --> Array to be sorted, +low --> Starting index, +high --> Ending index */ +void quickSort(int arr[], int low, int high) +{ + if (low < high) + { + /* pi is partitioning index, arr[p] is now + at right place */ + int pi = partition(arr, low, high); + + // Separately sort elements before + // partition and after partition + quickSort(arr, low, pi - 1); + quickSort(arr, pi + 1, high); + } +} + +/* 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[] = {10, 7, 8, 9, 1, 5}; + int n = sizeof(arr)/sizeof(arr[0]); + quickSort(arr, 0, n-1); + printf("Sorted array: \n"); + printArray(arr, n); + return 0; +} From e815a1618c396d67fcd7193b4b1980f110edbf3f Mon Sep 17 00:00:00 2001 From: Vishwajeet Date: Sat, 2 Oct 2021 08:01:52 +0530 Subject: [PATCH 005/147] Added Count Inversion Algorithm --- Count_inversion.cpp | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Count_inversion.cpp diff --git a/Count_inversion.cpp b/Count_inversion.cpp new file mode 100644 index 00000000..98d2badd --- /dev/null +++ b/Count_inversion.cpp @@ -0,0 +1,35 @@ +//The number of switches required to make an array sorted is termed as inversion count +#include + +using namespace std; + +int CountInversion(int a[], int n) +{ + int i, j, count = 0; + for(i = 0; i < n; i++) + { + for(j = i+1; j < n; j++) + if(a[i] > a[j]) + count++; + } + return count; +} + +int main() +{ + int n, i; + cout<<"\nEnter the number of data element: "; + cin>>n; + + int arr[n]; + for(i = 0; i < n; i++) + { + cout<<"Enter element "<>arr[i]; + } + + // Printing the number of inversion in the array. + cout<<"\nThe number of inversion in the array: "< Date: Sat, 2 Oct 2021 08:26:09 +0530 Subject: [PATCH 006/147] Added Cyclic Sort --- cyclicsort.cpp | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 cyclicsort.cpp diff --git a/cyclicsort.cpp b/cyclicsort.cpp new file mode 100644 index 00000000..ee55c5c4 --- /dev/null +++ b/cyclicsort.cpp @@ -0,0 +1,76 @@ +#include +using namespace std; + + +void cycleSort(int arr[], int n) +{ + // count number of memory writes + int writes = 0; + + // traverse array elements and put it to on + // the right place + for (int cycle_start = 0; cycle_start <= n - 2; cycle_start++) { + // initialize item as starting point + int item = arr[cycle_start]; + + // Find position where we put the item. We basically + // count all smaller elements on right side of item. + int pos = cycle_start; + for (int i = cycle_start + 1; i < n; i++) + if (arr[i] < item) + pos++; + + // If item is already in correct position + if (pos == cycle_start) + continue; + + // ignore all duplicate elements + while (item == arr[pos]) + pos += 1; + + // put the item to it's right position + if (pos != cycle_start) { + swap(item, arr[pos]); + writes++; + } + + // Rotate rest of the cycle + while (pos != cycle_start) { + pos = cycle_start; + + // Find position where we put the element + for (int i = cycle_start + 1; i < n; i++) + if (arr[i] < item) + pos += 1; + + // ignore all duplicate elements + while (item == arr[pos]) + pos += 1; + + // put the item to it's right position + if (item != arr[pos]) { + swap(item, arr[pos]); + writes++; + } + } + } + + +} + + +int main() +{ + int n; cin >> n; + int arr[] = {0}; + for(int i=0;i> arr[i]; + } + + cycleSort(arr, n); + + cout << "After sort : " << endl; + for (int i = 0; i < n; i++) + cout << arr[i] << " "; + return 0; +} \ No newline at end of file From 378008ffb14ab549c99ebd36454497ab9f38e87a Mon Sep 17 00:00:00 2001 From: Vishwajeet Date: Sat, 2 Oct 2021 08:28:11 +0530 Subject: [PATCH 007/147] Added Bubble sort Algorithm --- bubblesort.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 bubblesort.cpp diff --git a/bubblesort.cpp b/bubblesort.cpp new file mode 100644 index 00000000..3a957228 --- /dev/null +++ b/bubblesort.cpp @@ -0,0 +1,24 @@ +#include +using namespace std; + +int main() +{ + cout<<"Enter 10 numbers"<>arr[i]; + } + for(int i=1; i<10; i++){ + for(int j=0; j<10-i; j++){ + if(arr[j]>arr[j+1]){ + int temp= arr[j+1]; + arr[j+1]= arr[j]; + arr[j]= temp; + } + } + } + cout<<"array after sorting"< Date: Sat, 2 Oct 2021 09:04:50 +0530 Subject: [PATCH 008/147] Added a graph data structure. --- transposegraph.cpp | 56 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 transposegraph.cpp diff --git a/transposegraph.cpp b/transposegraph.cpp new file mode 100644 index 00000000..acd5397a --- /dev/null +++ b/transposegraph.cpp @@ -0,0 +1,56 @@ +// CPP program to find transpose of a graph. +#include +using namespace std; + +// function to add an edge from vertex source to vertex dest +void addEdge(vector adj[], int src, int dest) +{ + adj[src].push_back(dest); +} + +// function to print adjacency list of a graph +void displayGraph(vector adj[], int v) +{ + for (int i = 0; i < v; i++) { + cout << i << "--> "; + for (int j = 0; j < adj[i].size(); j++) + cout << adj[i][j] << " "; + cout << "\n"; + } +} + + +void transposeGraph(vector adj[], + vector transpose[], int v) +{ + // traverse the adjacency list of given graph and + // for each edge (u, v) add an edge (v, u) in the + // transpose graph's adjacency list + for (int i = 0; i < v; i++) + for (int j = 0; j < adj[i].size(); j++) + addEdge(transpose, adj[i][j], i); +} + +int main() +{ + int v = 5; + vector adj[v]; + addEdge(adj, 0, 1); + addEdge(adj, 0, 4); + addEdge(adj, 0, 3); + addEdge(adj, 2, 0); + addEdge(adj, 3, 2); + addEdge(adj, 4, 1); + addEdge(adj, 4, 3); + + // Finding transpose of graph represented + // by adjacency list adj[] + vector transpose[v]; + transposeGraph(adj, transpose, v); + + // displaying adjacency list of transpose + // graph i.e. b + displayGraph(transpose, v); + + return 0; +} \ No newline at end of file From 6e87a6cfcebbaa4ce301fa3ccafedc9fe561f105 Mon Sep 17 00:00:00 2001 From: Rajeev Date: Sat, 2 Oct 2021 09:28:46 +0530 Subject: [PATCH 009/147] Codeforceessolutionto 1009B --- codesforces1009B.cpp | 65 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 codesforces1009B.cpp diff --git a/codesforces1009B.cpp b/codesforces1009B.cpp new file mode 100644 index 00000000..981d2b38 --- /dev/null +++ b/codesforces1009B.cpp @@ -0,0 +1,65 @@ +#include +using namespace std; + +int main() { + string s; + cin >> s; + bool found = true; + int two = -1; + for (int i = 0; i < s.size(); i++) { + if (s[i] == '2') { + two = i; + break; + } + } + string ans = ""; + if (two != -1) { + int zeros = 0, onesbefore = 0; + for (int i = 0; i < two; i++) { + if (s[i] == '0') { + zeros++; + } else { + onesbefore++; + } + } + while (zeros--) { + ans += string(1, '0'); + } + while (onesbefore--) { + ans += string(1, '1'); + } + int onesafter = 0; + for (int i = 0; i < s.size(); i++) { + if (i > two and s[i] == '1') { + onesafter++; + } + } + while (onesafter--) { + ans += string(1, '1'); + } + ans += string(1, '2'); + for (int i = two + 1; i < s.size(); i++) { + if (s[i] != '1') { + ans += string(1, s[i]); + } + } + } else { + ans = ""; + int zeros = 0, ones = 0; + for (int i = 0; i < s.size(); i++) { + if (s[i] == '0') { + zeros++; + } else { + ones++; + } + } + while (zeros--) { + ans += string(1, '0'); + } + while (ones--) { + ans += string(1, '1'); + } + } + cout << ans << endl; + return 0; +} \ No newline at end of file From 4184c2e3ca435681ebd64ce5abbd2a45ac804b7e Mon Sep 17 00:00:00 2001 From: A Thithiesha Mahabaduge <64262646+Thithiesha@users.noreply.github.com> Date: Sat, 2 Oct 2021 11:30:52 +0530 Subject: [PATCH 010/147] Cpp program to Kruskal's Algorithm Added a working cpp program Kruskal's Algorithm. (Minimum Spanning Tree). View the hacker rank problem statement using the following link, https://www.hackerrank.com/challenges/kruskalmstrsub/problem --- kruskal.cpp | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 kruskal.cpp diff --git a/kruskal.cpp b/kruskal.cpp new file mode 100644 index 00000000..e6069fc2 --- /dev/null +++ b/kruskal.cpp @@ -0,0 +1,68 @@ +#include +#include +#include +using namespace std; +int link[5000]; +int size[5000]; +int fun(int k) +{ + while(k!=link[k]) + { + k=link[k]; + } return k; +} +int main() +{ + priority_queue > q; + tuple t; + int N; int M; + cin>>N>>M; + int x; int y; int z; + for(int i=0; i>x>>y>>z; + q.push(make_tuple(-z,x,y)); + } + + for(int i=0; i(t)); + y=get<1>(t); + z=get<2>(t); + aa=fun(y); + bb=fun(z); + if(aa==bb) + { + continue; + } + else if(size[aa]>size[bb]) + { + link[bb]=aa; + } + else if(size[bb]>size[aa]) + { + link[aa]=bb; + } + else if(size[bb]==size[aa]) + { + if(aa>bb) + { + link[bb]=aa; + } + else if(aa Date: Sun, 3 Oct 2021 14:41:45 +0530 Subject: [PATCH 011/147] Create Binary search --- Binary search | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Binary search diff --git a/Binary search b/Binary search new file mode 100644 index 00000000..05ba7527 --- /dev/null +++ b/Binary search @@ -0,0 +1,36 @@ +#include + +using namespace std; +int binary(int arr[],int p,int q,int x){ + int mid; + mid=(p+q)/2; + if(p<=q){ + if(arr[mid]==x){ + return mid; +} + else if(arr[mid]>x){ + binary(arr,mid+1,q,x); + } + else{ + binary(arr,p,mid-1,x); + } + } + + return -1; +} + +int main() +{ + int m,n,i,x,s,r; + cin>>r>>x; + m=0,n=r-1; + int a[r]; + for(i=0;i>a[i]; + s=binary(a,m,n,x); + cout<<"searching element is present in index "< Date: Mon, 4 Oct 2021 21:34:55 +0530 Subject: [PATCH 012/147] Create Quotient_and_Remainder --- Quotient_and_Remainder | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Quotient_and_Remainder diff --git a/Quotient_and_Remainder b/Quotient_and_Remainder new file mode 100644 index 00000000..628d6fac --- /dev/null +++ b/Quotient_and_Remainder @@ -0,0 +1,21 @@ +#include +using namespace std; + +int main() +{ + int divisor, dividend, quotient, remainder; + + cout << "Enter dividend: "; + cin >> dividend; + + cout << "Enter divisor: "; + cin >> divisor; + + quotient = dividend / divisor; + remainder = dividend % divisor; + + cout << "Quotient = " << quotient << endl; + cout << "Remainder = " << remainder; + + return 0; +} From 1866eea89ded757d6c42c2d45500d8553545f798 Mon Sep 17 00:00:00 2001 From: hinata027 <72518752+hinata027@users.noreply.github.com> Date: Tue, 5 Oct 2021 01:19:41 +0530 Subject: [PATCH 013/147] Create Treeheight.cpp --- Treeheight.cpp | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Treeheight.cpp diff --git a/Treeheight.cpp b/Treeheight.cpp new file mode 100644 index 00000000..f2433d37 --- /dev/null +++ b/Treeheight.cpp @@ -0,0 +1,49 @@ +#include +using namespace std; + +class node +{ + public: + int data; + node* left; + node* right; +}; + +int maxDepth(node* node) +{ + if (node == NULL) + return 0; + else + { + int lDepth = maxDepth(node->left); + int rDepth = maxDepth(node->right); + + if (lDepth > rDepth) + return(lDepth + 1); + else return(rDepth + 1); + } +} + +node* newNode(int data) +{ + node* Node = new node(); + Node->data = data; + Node->left = NULL; + Node->right = NULL; + + return(Node); +} + +int main() +{ + node *root = newNode(1); + + root->left = newNode(4); + root->right = newNode(8); + root->left->left = newNode(14); + root->left->right = newNode(15); + + cout << "Height of tree : " << maxDepth(root); + return 0; +} + From ac18402ddd79d1e5bdbc307c55668b70e0291650 Mon Sep 17 00:00:00 2001 From: Ashutosh Mittal Date: Tue, 5 Oct 2021 01:32:33 +0530 Subject: [PATCH 014/147] selection sort --- selectionsort.cpp | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 selectionsort.cpp diff --git a/selectionsort.cpp b/selectionsort.cpp new file mode 100644 index 00000000..94349169 --- /dev/null +++ b/selectionsort.cpp @@ -0,0 +1,33 @@ +#include +using namespace std; +int main() +{ + int n; + cin >> n; + int arr[n]; + for (int i = 0; i < n; i++) + + { + cin >> arr[i]; + } + for (int i = 0; i < n - 1; i++) + { + for (int j = i + 1; j < n; j++) + { + if (arr[j] < arr[i]) + { + /* code */ + int temp = arr[j]; + arr[j] = arr[i]; + arr[i] = temp; + } + } + } + for (int i = 0; i < n; i++) + { + /* code */ + cout << arr[i] << " "; + }cout< Date: Tue, 5 Oct 2021 01:35:43 +0530 Subject: [PATCH 015/147] merge sort --- mergesort.cpp | 85 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 mergesort.cpp diff --git a/mergesort.cpp b/mergesort.cpp new file mode 100644 index 00000000..fe0f8d8e --- /dev/null +++ b/mergesort.cpp @@ -0,0 +1,85 @@ +//merge sort// +#include +using namespace std; +void merge(int a[], int n, int lb, int mid, int ub) +{ + int i = lb; + int j = mid + 1; + int k = lb; + int temp[n]; + while (i <= mid && j <= ub) + { + if (a[i] <= a[j]) + { + temp[k] = a[i]; + i++; + } + else + { + temp[k] = a[j]; + j++; + } + k++; + } + if (i > mid) + { + while (j <= ub) + { + + temp[k] = a[j]; + j++; + k++; + } + } + else + { + while (i <= mid) + { + + temp[k] = a[i]; + i++; + k++; + } + } + for (int k = lb; k <= ub; k++) + { + a[k] = temp[k]; + } +} +void mergesort(int a[], int n, int lb, int ub) +{ + if (lb < ub) + { + + int mid = (lb + ub) / 2; + mergesort(a, n, lb, mid); + mergesort(a, n, mid + 1, ub); + merge(a, n, lb, mid, ub); + } + else + return; +} +int main() +{ + int n; + cout << "ENTER THE SIZE OF AN ARRAY" << endl; + cin >> n; + int a[n]; + for (int i = 0; i < n; i++) + { + cin >> a[i]; + } + cout << "DISPLAYING ORIGINAL ARRAY" << endl; + for (int i = 0; i < n; i++) + { + cout << a[i] << " " << endl; + } + mergesort(a, n, 0, n - 1); + cout << "DISPLAYING SORTED ARRAY" << endl; + for (int i = 0; i < n; i++) + { + cout << a[i] << " " << endl; + } + + return 0; +} \ No newline at end of file From 1aa318837a2fb61d42a982aab105a02a6768a1f0 Mon Sep 17 00:00:00 2001 From: Manpreet Singh <57037790+msromi@users.noreply.github.com> Date: Tue, 5 Oct 2021 02:40:36 +0530 Subject: [PATCH 016/147] Create Radix sort --- Radix sort | 73 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 Radix sort diff --git a/Radix sort b/Radix sort new file mode 100644 index 00000000..36cae2fe --- /dev/null +++ b/Radix sort @@ -0,0 +1,73 @@ +#include +using namespace std; + +// A utility function to get maximum value in arr[] +int getMax(int arr[], int n) +{ + int mx = arr[0]; + for (int i = 1; i < n; i++) + if (arr[i] > mx) + mx = arr[i]; + return mx; +} + +// A function to do counting sort of arr[] according to +// the digit represented by exp. +void countSort(int arr[], int n, int exp) +{ + int output[n]; // output array + int i, count[10] = { 0 }; + + // Store count of occurrences in count[] + for (i = 0; i < n; i++) + count[(arr[i] / exp) % 10]++; + + // Change count[i] so that count[i] now contains actual + // position of this digit in output[] + for (i = 1; i < 10; i++) + count[i] += count[i - 1]; + + // Build the output array + for (i = n - 1; i >= 0; i--) { + output[count[(arr[i] / exp) % 10] - 1] = arr[i]; + count[(arr[i] / exp) % 10]--; + } + + // Copy the output array to arr[], so that arr[] now + // contains sorted numbers according to current digit + for (i = 0; i < n; i++) + arr[i] = output[i]; +} + +// The main function to that sorts arr[] of size n using +// Radix Sort +void radixsort(int arr[], int n) +{ + // Find the maximum number to know number of digits + int m = getMax(arr, n); + + // Do counting sort for every digit. Note that instead + // of passing digit number, exp is passed. exp is 10^i + // where i is current digit number + for (int exp = 1; m / exp > 0; exp *= 10) + countSort(arr, n, exp); +} + +// A utility function to print an array +void print(int arr[], int n) +{ + for (int i = 0; i < n; i++) + cout << arr[i] << " "; +} + +// Driver Code +int main() +{ + int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 }; + int n = sizeof(arr) / sizeof(arr[0]); + + // Function Call + radixsort(arr, n); + print(arr, n); + return 0; +} From b945f5d5a3e373a6be525503c6700192e0ddca06 Mon Sep 17 00:00:00 2001 From: Shivam Jindal <64001994+Shivamjindal1@users.noreply.github.com> Date: Tue, 5 Oct 2021 09:56:36 +0530 Subject: [PATCH 017/147] Create Prime_factors.cpp --- Prime_factors.cpp | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Prime_factors.cpp diff --git a/Prime_factors.cpp b/Prime_factors.cpp new file mode 100644 index 00000000..8caa9d9c --- /dev/null +++ b/Prime_factors.cpp @@ -0,0 +1,46 @@ +// C++ program to print all prime factors +#include +using namespace std; + +# include + + +// A function to print all prime +// factors of a given number n +void primeFactors(int n) +{ + // Print the number of 2s that divide n + while (n % 2 == 0) + { + cout << 2 << " "; + n = n/2; + } + + // n must be odd at this point. So we can skip + // one element (Note i = i +2) + for (int i = 3; i <= sqrt(n); i = i + 2) + { + // While i divides n, print i and divide n + while (n % i == 0) + { + cout << i << " "; + n = n/i; + } + } + + // This condition is to handle the case when n + // is a prime number greater than 2 + if (n > 2) + cout << n << " "; +} + +/* Driver code */ +int main() +{ + int n; + cout<<"Enter the value of number:\n"; + cin>>n; + primeFactors(n); + return 0; +} + From 9eddd00e213fbc3e896c11b699af86a620e2fc7b Mon Sep 17 00:00:00 2001 From: Sanya Ramchandani Date: Tue, 5 Oct 2021 12:26:27 +0530 Subject: [PATCH 018/147] Create Stock_Span_Problem.cpp --- Stock_Span_Problem.cpp | 45 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Stock_Span_Problem.cpp diff --git a/Stock_Span_Problem.cpp b/Stock_Span_Problem.cpp new file mode 100644 index 00000000..84db281d --- /dev/null +++ b/Stock_Span_Problem.cpp @@ -0,0 +1,45 @@ +// C++ program for a linear time solution for stock +// span problem without using stack +#include +#include +using namespace std; + +// An efficient method to calculate stock span values +// implementing the same idea without using stack +void calculateSpan(int A[], int n, int ans[]) +{ + // Span value of first element is always 1 + ans[0] = 1; + + // Calculate span values for rest of the elements + for (int i = 1; i < n; i++) { + int counter = 1; + while ((i - counter) >= 0 && A[i] >= A[i - counter]) { + counter += ans[i - counter]; + } + ans[i] = counter; + } +} + +// A utility function to print elements of array +void printArray(int arr[], int n) +{ + for (int i = 0; i < n; i++) + cout << arr[i] << " "; +} + +// Driver program to test above function +int main() +{ + int price[] = { 10, 4, 5, 90, 120, 80 }; + int n = sizeof(price) / sizeof(price[0]); + int S[n]; + + // Fill the span values in array S[] + calculateSpan(price, n, S); + + // print the calculated span values + printArray(S, n); + + return 0; +} From bead3c767116dc50e524471a48f57ff865384472 Mon Sep 17 00:00:00 2001 From: Sanya Ramchandani Date: Tue, 5 Oct 2021 12:29:20 +0530 Subject: [PATCH 019/147] Create MinimumPlatforms.cpp --- MinimumPlatforms.cpp | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 MinimumPlatforms.cpp diff --git a/MinimumPlatforms.cpp b/MinimumPlatforms.cpp new file mode 100644 index 00000000..d2f61603 --- /dev/null +++ b/MinimumPlatforms.cpp @@ -0,0 +1,43 @@ +// C++ program to find minimum number of platforms +// required on a railway station +#include +using namespace std; + +int minPlatform(int arrival[], int departure[], int n) +{ + + // as time range from 0 to 2359 in 24 hour clock, + // we declare an array for values from 0 to 2360 + int platform[2361] = {0}; + int requiredPlatform = 1; + for (int i = 0; i < n; i++) { + + // increment the platforms for arrival + ++platform[arrival[i]]; + + // once train departs we decrease the platform count + --platform[departure[i] + 1]; + } + + // We are running loop till 2361 because maximum time value + // in a day can be 23:60 + for (int i = 1; i < 2361; i++) { + + // taking cumulative sum of platform give us required + // number of platform fro every minute + platform[i] = platform[i] + platform[i - 1]; + requiredPlatform = max(requiredPlatform, platform[i]); + } + return requiredPlatform; +} + +// Driver code +int main() +{ + int arr[] = { 900, 940, 950, 1100, 1500, 1800 }; + int dep[] = { 910, 1200, 1120, 1130, 1900, 2000 }; + int n = sizeof(arr) / sizeof(arr[0]); + cout << "Minimum Number of Platforms Required = " + << minPlatform(arr, dep, n); + return 0; +} From 6a3fc744de01fad2376cfef62b50e5fb2ed30894 Mon Sep 17 00:00:00 2001 From: Hics0000 <76846893+Hics0000@users.noreply.github.com> Date: Tue, 5 Oct 2021 13:57:01 +0530 Subject: [PATCH 020/147] To check leap yes\ar or not --- leap year or not.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 leap year or not.cpp diff --git a/leap year or not.cpp b/leap year or not.cpp new file mode 100644 index 00000000..17a4d660 --- /dev/null +++ b/leap year or not.cpp @@ -0,0 +1,18 @@ + + +#include +using namespace std; +int main() +{ + int yr; + cout<<"Enter the Year: "; + cin>>yr; + if((yr%4==0) && (yr%100!=0)) + cout<<"\nIt is a Leap Year"; + else if(yr%400==0) + cout<<"\nIt is a Leap Year"; + else + cout<<"\nIt is not a Leap Year"; + cout< Date: Tue, 5 Oct 2021 22:26:34 +0530 Subject: [PATCH 021/147] Create farthest_buildings.cpp --- farthest_buildings.cpp | 45 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 farthest_buildings.cpp diff --git a/farthest_buildings.cpp b/farthest_buildings.cpp new file mode 100644 index 00000000..c21d229c --- /dev/null +++ b/farthest_buildings.cpp @@ -0,0 +1,45 @@ +class Solution { +public: + int furthestBuilding(vector& heights, int br, int lad) { + priority_queue,greater> que; + int i=0; + int diff; + while(que.size()0) + { + if(!que.empty() && que.top() Date: Wed, 6 Oct 2021 01:46:45 +0200 Subject: [PATCH 022/147] Create fibonacciDP.cpp --- fibonacciDP.cpp | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 fibonacciDP.cpp diff --git a/fibonacciDP.cpp b/fibonacciDP.cpp new file mode 100644 index 00000000..3a1780f5 --- /dev/null +++ b/fibonacciDP.cpp @@ -0,0 +1,40 @@ +// C++ Program to find n'th fibonacci Number in +// with O(Log n) arithmetic operations +#include +using namespace std; + +const int MAX = 1000; + +// Create an array for memoization +int f[MAX] = {0}; + +// Returns n'th fibonacci number using table f[] +int fib(int n) +{ + // Base cases + if (n == 0) + return 0; + if (n == 1 || n == 2) + return (f[n] = 1); + + // If fib(n) is already computed + if (f[n]) + return f[n]; + + int k = (n & 1)? (n+1)/2 : n/2; + + // Applying above formula [Note value n&1 is 1 + // if n is odd, else 0. + f[n] = (n & 1)? (fib(k)*fib(k) + fib(k-1)*fib(k-1)) + : (2*fib(k-1) + fib(k))*fib(k); + + return f[n]; +} + +/* Driver program to test above function */ +int main() +{ + int n = 9; + printf("%d ", fib(n)); + return 0; +} From cbb5857e5cec4976683e38abe3b12ba22a885df1 Mon Sep 17 00:00:00 2001 From: Tharindu Rewatha <60292980+TharinduRewatha@users.noreply.github.com> Date: Wed, 6 Oct 2021 08:29:11 +0530 Subject: [PATCH 023/147] Create Bitonic Sort --- Bitonic Sort | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Bitonic Sort diff --git a/Bitonic Sort b/Bitonic Sort new file mode 100644 index 00000000..58a3e3d3 --- /dev/null +++ b/Bitonic Sort @@ -0,0 +1,59 @@ + +#include +using namespace std; + +void compAndSwap(int a[], int i, int j, int dir) +{ + if (dir==(a[i]>a[j])) + swap(a[i],a[j]); +} + +void bitonicMerge(int a[], int low, int cnt, int dir) +{ + if (cnt>1) + { + int k = cnt/2; + for (int i=low; i1) + { + int k = cnt/2; + + // sort in ascending order since dir here is 1 + bitonicSort(a, low, k, 1); + + // sort in descending order since dir here is 0 + bitonicSort(a, low+k, k, 0); + + // Will merge whole sequence in ascending order + // since dir=1. + bitonicMerge(a,low, cnt, dir); + } +} + +void sort(int a[], int N, int up) +{ + bitonicSort(a,0, N, up); +} + +// Driver code +int main() +{ + int a[]= {3, 7, 4, 8, 6, 2, 1, 5}; + int N = sizeof(a)/sizeof(a[0]); + + int up = 1; // means sort in ascending order + sort(a, N, up); + + printf("Sorted array: \n"); + for (int i=0; i Date: Wed, 6 Oct 2021 08:41:48 +0530 Subject: [PATCH 024/147] Create Bubble sorting --- Bubble sorting | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Bubble sorting diff --git a/Bubble sorting b/Bubble sorting new file mode 100644 index 00000000..89e04123 --- /dev/null +++ b/Bubble sorting @@ -0,0 +1,22 @@ +def bubbleSort(a): + + + for i in range(len(a)): + + + for j in range(0, len(a) - i - 1): + + + if a[j] > a[j + 1]: + + temp = a[j] + a[j] = a[j+1] + a[j+1] = temp + + +data = [-44, 45, 0, 85, -30] + +bubbleSort(data) + +print('Sorted Array in Ascending Order:') +print(data) From eb8da5fb6db21a1edcb19f11e8647970695662d8 Mon Sep 17 00:00:00 2001 From: dashingsaikat <48173982+dashingsaikat@users.noreply.github.com> Date: Wed, 6 Oct 2021 10:11:16 +0530 Subject: [PATCH 025/147] Create Implementation of AVL Tree --- Implementation of AVL Tree | 190 +++++++++++++++++++++++++++++++++++++ 1 file changed, 190 insertions(+) create mode 100644 Implementation of AVL Tree diff --git a/Implementation of AVL Tree b/Implementation of AVL Tree new file mode 100644 index 00000000..acd879c5 --- /dev/null +++ b/Implementation of AVL Tree @@ -0,0 +1,190 @@ +#include +#include +#include +#include +#define pow2(n) (1 << (n)) +using namespace std; +struct avl { + int d; + struct avl *l; + struct avl *r; +}*r; +class avl_tree { + public: + int height(avl *); + int difference(avl *); + avl *rr_rotat(avl *); + avl *ll_rotat(avl *); + avl *lr_rotat(avl*); + avl *rl_rotat(avl *); + avl * balance(avl *); + avl * insert(avl*, int); + void show(avl*, int); + void inorder(avl *); + void preorder(avl *); + void postorder(avl*); + avl_tree() { + r = NULL; + } +}; +int avl_tree::height(avl *t) { + int h = 0; + if (t != NULL) { + int l_height = height(t->l); + int r_height = height(t->r); + int max_height = max(l_height, r_height); + h = max_height + 1; + } + return h; +} +int avl_tree::difference(avl *t) { + int l_height = height(t->l); + int r_height = height(t->r); + int b_factor = l_height - r_height; + return b_factor; +} +avl *avl_tree::rr_rotat(avl *parent) { + avl *t; + t = parent->r; + parent->r = t->l; + t->l = parent; + cout<<"Right-Right Rotation"; + return t; +} +avl *avl_tree::ll_rotat(avl *parent) { + avl *t; + t = parent->l; + parent->l = t->r; + t->r = parent; + cout<<"Left-Left Rotation"; + return t; +} +avl *avl_tree::lr_rotat(avl *parent) { + avl *t; + t = parent->l; + parent->l = rr_rotat(t); + cout<<"Left-Right Rotation"; + return ll_rotat(parent); +} +avl *avl_tree::rl_rotat(avl *parent) { + avl *t; + t = parent->r; + parent->r = ll_rotat(t); + cout<<"Right-Left Rotation"; + return rr_rotat(parent); +} +avl *avl_tree::balance(avl *t) { + int bal_factor = difference(t); + if (bal_factor > 1) { + if (difference(t->l) > 0) + t = ll_rotat(t); + else + t = lr_rotat(t); + } else if (bal_factor < -1) { + if (difference(t->r) > 0) + t = rl_rotat(t); + else + t = rr_rotat(t); + } + return t; +} +avl *avl_tree::insert(avl *r, int v) { + if (r == NULL) { + r = new avl; + r->d = v; + r->l = NULL; + r->r = NULL; + return r; + } else if (v< r->d) { + r->l = insert(r->l, v); + r = balance(r); + } else if (v >= r->d) { + r->r = insert(r->r, v); + r = balance(r); + } return r; +} +void avl_tree::show(avl *p, int l) { + int i; + if (p != NULL) { + show(p->r, l+ 1); + cout<<" "; + if (p == r) + cout << "Root -> "; + for (i = 0; i < l&& p != r; i++) + cout << " "; + cout << p->d; + show(p->l, l + 1); + } +} +void avl_tree::inorder(avl *t) { + if (t == NULL) + return; + inorder(t->l); + cout << t->d << " "; + inorder(t->r); +} +void avl_tree::preorder(avl *t) { + if (t == NULL) + return; + cout << t->d << " "; + preorder(t->l); + preorder(t->r); +} +void avl_tree::postorder(avl *t) { + if (t == NULL) + return; + postorder(t ->l); + postorder(t ->r); + cout << t->d << " "; +} +int main() { + int c, i; + avl_tree avl; + while (1) { + cout << "1.Insert Element into the tree" << endl; + cout << "2.show Balanced AVL Tree" << endl; + cout << "3.InOrder traversal" << endl; + cout << "4.PreOrder traversal" << endl; + cout << "5.PostOrder traversal" << endl; + cout << "6.Exit" << endl; + cout << "Enter your Choice: "; + cin >> c; + switch (c) { + case 1: + cout << "Enter value to be inserted: "; + cin >> i; + r = avl.insert(r, i); + break; + case 2: + if (r == NULL) { + cout << "Tree is Empty" << endl; + continue; + } + cout << "Balanced AVL Tree:" << endl; + avl.show(r, 1); + cout< Date: Wed, 6 Oct 2021 10:14:50 +0530 Subject: [PATCH 026/147] Create Reverse_words_in_a_String.cpp --- Reverse_words_in_a_String.cpp | 38 +++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Reverse_words_in_a_String.cpp diff --git a/Reverse_words_in_a_String.cpp b/Reverse_words_in_a_String.cpp new file mode 100644 index 00000000..38f86e26 --- /dev/null +++ b/Reverse_words_in_a_String.cpp @@ -0,0 +1,38 @@ +#include +using namespace std; + +void reverse(string& s, int low, int high){ + while(low < high){ + swap(s[low],s[high]); + low++; + high--; + } +} +string reverseString(string str){ + str.insert(str.end(), ' '); + int start =0; + int n =str.length(); + for(int end=0; end Date: Wed, 6 Oct 2021 12:08:43 +0530 Subject: [PATCH 027/147] Counting Sort added --- countSort.cpp | 52 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 countSort.cpp diff --git a/countSort.cpp b/countSort.cpp new file mode 100644 index 00000000..f90f67dd --- /dev/null +++ b/countSort.cpp @@ -0,0 +1,52 @@ +//The O(N) sort. +//Note: Only limited to small positive integers only. +//Input: Given an array. +//Output: Print the sorted array. +//Time Complexity: O(N) + +#include +using namespace std; + +void countSort(int arr[], int n) +{ + int k = arr[0]; + for(int i=0;i=0;i--) + { + output[--countArray[arr[i]]] = arr[i]; + } + + for(int i=0;i Date: Wed, 6 Oct 2021 12:44:28 +0530 Subject: [PATCH 028/147] Create Pattern.cpp --- Pattern.cpp | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Pattern.cpp diff --git a/Pattern.cpp b/Pattern.cpp new file mode 100644 index 00000000..664869d8 --- /dev/null +++ b/Pattern.cpp @@ -0,0 +1,68 @@ +#include +// #include +#include + +using namespace std; + +int pattern(int n){ + int c; + cout<<"Enter 0 if you want triangle\nEnter 1 if you want reverse triangle "; + cin>>c; + if (c==0) + { + for (int i = 0; i < n; i++) + { + for (int j = 0; j < i+1; j++) + { + cout<<"*"; + } + cout<<"\n"; + } + } + else if (c==1) + { + for (int i = n; i > 0; i--) + { + for (int j = i; j > 0; j--) + { + cout<<"*"; + } + cout<<"\n"; + } + } + else + { + cout<<"Invalid Input"; + return -1; + } + return 1; +} + +int main(){ + while (true) + { + int no_of_lines; + cout<<"Enter no of lines you want in pattern "; + cin>>no_of_lines; + if (no_of_lines>0) + { + int result=pattern(no_of_lines); + // if (result!=-1){ + // break; + // } + } + else + { + cout<<"Invalid input"; + } + + int Choice; + cout<<"Continue printing another pattern?? -- Press any no\nExit Program -- 0 "; + cin>>Choice; + if (Choice==0){ + cout<<"Thanks For Using Our Program!!!"< Date: Wed, 6 Oct 2021 14:05:39 +0530 Subject: [PATCH 029/147] Create RecursiveBinarySearch.cpp --- RecursiveBinarySearch.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 RecursiveBinarySearch.cpp diff --git a/RecursiveBinarySearch.cpp b/RecursiveBinarySearch.cpp new file mode 100644 index 00000000..43c54f3d --- /dev/null +++ b/RecursiveBinarySearch.cpp @@ -0,0 +1,28 @@ + +#include +using namespace std; +int binarysearch(int arr[],int l,int r,int x){ + if( r >= l){ + int mid =l + (r - 1)/2; + + if(arr[mid]==x) + return mid; + + if(arr[mid] > x) + return binarysearch(arr,l,mid -1 ,x); + + return binarysearch(arr,mid+1,r,x); + } + return -1; +} +int main() +{ + int a[] = { 2, 3, 4, 10, 40 }; + int x = 10; + int n = sizeof(a) / sizeof(a[0]); + int result = binarysearch(a, 0, n - 1, x); + (result == -1) ? cout << "Element is not present in array" + : cout << "Element is present at index " << result; + return 0; +} + From bf553b39ba7df47e5e9736cde39f866dc11f62a0 Mon Sep 17 00:00:00 2001 From: Kesha_Shah <62072707+18CE112@users.noreply.github.com> Date: Wed, 6 Oct 2021 16:13:51 +0530 Subject: [PATCH 030/147] Created code for checksum --- checksum.cpp | 254 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 254 insertions(+) create mode 100644 checksum.cpp diff --git a/checksum.cpp b/checksum.cpp new file mode 100644 index 00000000..89b6aa3c --- /dev/null +++ b/checksum.cpp @@ -0,0 +1,254 @@ +#include +#include +using namespace std; +class A +{ + public: + int a[4][8]; +int cs[8]={0,0,0,0,0,0,0,0}; +int carry=0; +int carry1=0; + + + void input() + { + cout<<"enter the bit stream "<>a[i][j]; + } + } +for(int i=0;i<4;i++) +{ + for(int j=7;j>=0;j--) + { + if(cs[j]==1 && a[i][j]==1&&carry==0) + { + cs[j]=0; + carry=1; + } + else if(cs[j]==1 && a[i][j]==1 && carry==1) + { + cs[j]=1; + carry=1; + } + else if(cs[j]==1 && a[i][j]==0 && carry==1) + { + cs[j]=0; + carry=1; + } + else if(cs[j]==0 && a[i][j]==1 && carry==1) + { + cs[j]=0; + carry=1; + } + else if(cs[j]==1 && a[i][j]==0 && carry==0) + { + cs[j]=1; + carry=0; + } + else if(cs[j]==0 && a[i][j]==1 && carry==0) + { + cs[j]=1; + carry=0; + } + else if(cs[j]==0 && a[i][j]==0 && carry==1) + { + cs[j]=1; + carry=0; + } + else if(cs[j]==0 && a[i][j]==0 && carry==0) + { + cs[j]=0; + carry=0; + } + } + if(carry==1) + { + carry1=carry; + for(int j=7;j>=0;j--) + { + if(cs[j]==1 && carry1==1) + { + cs[j]=0; + carry1=1; + } + else if(cs[j]==0 && carry1==1) + { + cs[j]=1; + carry1=0; + } + else if(cs[j]==1 && carry1==0) + { + cs[j]=1; + carry1=0; + } + else if(cs[j]==0 && carry1==0) + { + cs[j]=0; + carry1=0; + } + carry=0; + } + } +} +cout<<"the final result"<>a; + switch (a) + { + case 1: + { + cmd(); + break; + } +case 2: + { + ofstream files; + files.open("checksumfile.txt"); + int a[4][8]; +int cs[]={0,0,0,0,0,0,0,0}; +int carry=0; +int carry1=0; + cout<<"enter the bit stream "<>a[i][j]; + } + } +for(int i=0;i<4;i++) +{ + for(int j=7;j>=0;j--) + { + if(cs[j]==1 && a[i][j]==1&&carry==0) + { + cs[j]=0; + carry=1; + } + else if(cs[j]==1 && a[i][j]==1 && carry==1) + { + cs[j]=1; + carry=1; + } + else if(cs[j]==1 && a[i][j]==0 && carry==1) + { + cs[j]=0; + carry=1; + } + else if(cs[j]==0 && a[i][j]==1 && carry==1) + { + cs[j]=0; + carry=1; + } + else if(cs[j]==1 && a[i][j]==0 && carry==0) + { + cs[j]=1; + carry=0; + } + else if(cs[j]==0 && a[i][j]==1 && carry==0) + { + cs[j]=1; + carry=0; + } + else if(cs[j]==0 && a[i][j]==0 && carry==1) + { + cs[j]=1; + carry=0; + } + else if(cs[j]==0 && a[i][j]==0 && carry==0) + { + cs[j]=0; + carry=0; + } + } + if(carry==1) + { + carry1=carry; + for(int j=7;j>=0;j--) + { + if(cs[j]==1 && carry1==1) + { + cs[j]=0; + carry1=1; + } + else if(cs[j]==0 && carry1==1) + { + cs[j]=1; + carry1=0; + } + else if(cs[j]==1 && carry1==0) + { + cs[j]=1; + carry1=0; + } + else if(cs[j]==0 && carry1==0) + { + cs[j]=0; + carry1=0; + } + carry=0; + } + } +} +files<<"the final result"< Date: Wed, 6 Oct 2021 18:18:34 +0530 Subject: [PATCH 031/147] Programs Added By @ProgrammerShri --- ...-Youtube-Practice-Problem-Contest-Solution | 1 + Find Missing Element.cpp | 25 ++++ Jump_game.cpp | 21 +++ ValidParenthesis.cpp | 92 ++++++++++++++ Valid_Parenthesis.cpp | 120 ++++++++++++++++++ balanced_binary_tree.cpp | 22 ++++ binarySearch.cpp | 45 +++++++ binarytodecimal.cpp | 33 +++++ decimaltobinary.cpp | 20 +++ insertion_sort_linked_list.cpp | 15 +++ sorting.cpp | 97 ++++++++++++++ two_sum.cpp | 21 +++ 12 files changed, 512 insertions(+) create mode 160000 CodeChef-Youtube-Practice-Problem-Contest-Solution create mode 100644 Find Missing Element.cpp create mode 100644 Jump_game.cpp create mode 100644 ValidParenthesis.cpp create mode 100644 Valid_Parenthesis.cpp create mode 100644 balanced_binary_tree.cpp create mode 100644 binarySearch.cpp create mode 100644 binarytodecimal.cpp create mode 100644 decimaltobinary.cpp create mode 100644 insertion_sort_linked_list.cpp create mode 100644 sorting.cpp create mode 100644 two_sum.cpp diff --git a/CodeChef-Youtube-Practice-Problem-Contest-Solution b/CodeChef-Youtube-Practice-Problem-Contest-Solution new file mode 160000 index 00000000..246be171 --- /dev/null +++ b/CodeChef-Youtube-Practice-Problem-Contest-Solution @@ -0,0 +1 @@ +Subproject commit 246be1711ffecb01114e5e986e25ba17a0bb0b00 diff --git a/Find Missing Element.cpp b/Find Missing Element.cpp new file mode 100644 index 00000000..ca0caa83 --- /dev/null +++ b/Find Missing Element.cpp @@ -0,0 +1,25 @@ +void sort(int arr[],int n){ + for (int i = 0; i < n; ++i) + { + for (int j = i + 1; j < n; ++j) + { + if (arr[i] > arr[j]) + { + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + } + } +} +int getMissingElement(int* a,int a_size,int* b ,int b_size){ + sort(a,a_size); + sort(b,b_size); + for (int i = 0; i < b_size; i++) + { + if(a[i] != b[i]){ + return a[i]; + } + } + return a[a_size-1]; +} diff --git a/Jump_game.cpp b/Jump_game.cpp new file mode 100644 index 00000000..530ea4bd --- /dev/null +++ b/Jump_game.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int jump(vector& nums) { + int cur = 0, prev = 0, count = 0; + for(int i = 0; i < nums.size()-1; ++i) + { + //find the current max step + cur = max(cur, i+nums[i]); + //check if reach the top + if(cur >= nums.size()-1) + return count+1; + //if pass the previous step, then jump + if(i == prev) + { + prev = cur; + ++count; + } + } + return count; + } +}; diff --git a/ValidParenthesis.cpp b/ValidParenthesis.cpp new file mode 100644 index 00000000..d3188622 --- /dev/null +++ b/ValidParenthesis.cpp @@ -0,0 +1,92 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace std; +#define ll long long int +#define ld long double +#define mod 1000000007 +#define endl "\n" +#define vi vector +#define vs vector +#define pii pair +#define ump unordered_map +#define mp map +#define pq_max priority_queue +#define pq_min priority_queue +#define ff first +#define ss second +#define mid(l,r) (l+(r-l)/2) +#define loop(i,a,b) for(int i=(a); i <=(b);i++) +#define looprev(i,a,b) for(int i=(a); i >=(b);i--) +#define clr(val) memset(val,0,sizeof(val)) +#define what_is(x) cerr << #x << " is " << x << endl; +#define OJ \ + freopen("input.txt", "r", stdin); \ + freopen("output.txt", "w", stdout); +#define FIO ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); + +bool Balanced(string exp){ + + stack st; + char p; + + for(int i = 0; i < exp.length(); i++){ + + if (exp[i] == '(' || exp[i] == '[' || exp[i] == '{'){ + st.push(exp[i]); + continue; + } + if (st.empty()){ + return false; + } + + switch (exp[i]) + { + case ')': + p = st.top(); + st.pop(); + if (p == '{' || p == '['){ + return false; + } + break; + case ']': + p = st.top(); + st.pop(); + if (p == '{' || p == '('){ + return false; + } + break; + case '}': + p = st.top(); + st.pop(); + if (p == '[' || p == '('){ + return false; + } + break; + } + } + return (st.empty()); +} + +int main() +{ + string s; //()[]{} ()[} + cin>>s; + + if (Balanced(s)){ + cout<<"Balanced"; + } + else{ + cout<<"Not Balanced"; + } + +return 0; + +} diff --git a/Valid_Parenthesis.cpp b/Valid_Parenthesis.cpp new file mode 100644 index 00000000..75dfa86c --- /dev/null +++ b/Valid_Parenthesis.cpp @@ -0,0 +1,120 @@ +/*Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid or not . + +An input string is valid if: + + a) Open brackets must be closed by the same type of brackets. + b) Open brackets must be closed in the correct order. +*/ + +#include +using namespace std; +#define ll long long int +#define pb push_back +#define mp make_pair +#define pf push_front + +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + cout.tie(NULL); + + //Declaring a string variable named 's': + string s; + //Declaring a bool variable to store the value and initializing it as true + bool result = true; + cout << "Enter a string containing"; + cout << "(" + << ")" + << "{" + << "}" + << "[" + << "]" << endl; + + //Taking the string of brackets as input + cin >> s; + + //Declaring a stack of type char, since each of the bracket as individual are treated as characters: + stack st; + + //Traversing through the length of the string: + for (int i = 0; i < s.length(); i++) + { + //checking the the character at the ith index is '(' / '{' / '[' + //in either case we need to push it in the stack + + if (s[i] == '(' || s[i] == '{' || s[i] == '[') + st.push(s[i]); + + //checking the condition when the character is neither of the opening bracket + + else + { + + if (s[i] == ')') + { + //checking if the stack is empty or the top of the stack is not the corresponding opening bracket of the closing bracket + + if (st.empty() || st.top() != '(') + //In that case the string is invalid. + result = false; + else + //If the top of the stack matches with the corresponding opening bracket, then + //we're supposed to pop it out of the stack since it is a valid pair + st.pop(); + } + else if (s[i] == '}') + { + //checking if the stack is empty or the top of the stack is not the corresponding opening bracket of the closing bracket + + if (st.empty() || st.top() != '{') + //In that case the string is invalid. + result = false; + else + //If the top of the stack matches with the corresponding opening bracket, then + //we're supposed to pop it out of the stack since it is a valid pair + st.pop(); + } + else if (s[i] == ']') + { + //checking if the stack is empty or the top of the stack is not the corresponding opening bracket of the closing bracket + + if (st.empty() || st.top() != '[') + //In that case the string is invalid. + result = false; + else + //If the top of the stack matches with the corresponding opening bracket, then + //we're supposed to pop it out of the stack since it is a valid pair + st.pop(); + } + } + } + + //For the condition where the string contains only opening brackets, the value of result would have been true + //which would have given us a wrong answer. + + //Checking if the value of result is true and the stack is not empty in that case the string is invalid + + if (result && (!st.empty())) + result = false; + + if (result) + //if value of result is true, it's a valid string + cout << "Valid String" << endl; + + else + //else it's an invalid string + cout << "Invalid String" << endl; +} + +/*Time complexity of this program would be : O(n), where n is the length of the string + +EXPLANATION: +We traversed through the length of the string only once, at the cost of O(n), +the cost of pushing element into the stack and popping them is O(1) + +Hence, the overall time complexity of this code is O(n)! + + + +*/ diff --git a/balanced_binary_tree.cpp b/balanced_binary_tree.cpp new file mode 100644 index 00000000..b798ba91 --- /dev/null +++ b/balanced_binary_tree.cpp @@ -0,0 +1,22 @@ +class Solution { +public: +bool isBalanced(Node* root) { +return height(root)!= -1; + +} +int height(Node *root){ + if(root==NULL){ + return 0; + } + int leftHeight = height(root->left); + if(leftHeight==-1) + return -1; + int rightHeight = height(root->right); + if(rightHeight ==-1) + return -1; + if(abs(leftHeight - rightHeight)>1) + return -1; + return max(leftHeight , rightHeight) + 1; +} + +}; diff --git a/binarySearch.cpp b/binarySearch.cpp new file mode 100644 index 00000000..b19a2f35 --- /dev/null +++ b/binarySearch.cpp @@ -0,0 +1,45 @@ +#include +#include +using namespace std; +int s; +int binarySearch(int arr[],int i, int j) +{ + int a=1,b=0; + int mid=(i+j)/2; + while(iarr[mid]) + { + return binarySearch(arr,mid+1,j); + } + if(s>n; + int arr[n]; + cout<<"enter array elements: "<>arr[i]; + } + sort(arr,arr+n); + cout<<"enter element to search: "; + cin>>s; + result=binarySearch(arr,0,n-1); + if(result==1) + cout<<"element is present"; + else + cout<<"element is not present"; +} diff --git a/binarytodecimal.cpp b/binarytodecimal.cpp new file mode 100644 index 00000000..8ceff0aa --- /dev/null +++ b/binarytodecimal.cpp @@ -0,0 +1,33 @@ +// C++ program to convert binary to decimal +#include +using namespace std; + +// Function to convert binary to decimal +int binaryToDecimal(int n) +{ + int num = n; + int dec_value = 0; + + // Initializing base value to 1, i.e 2^0 + int base = 1; + + int temp = num; + while (temp) { + int last_digit = temp % 10; + temp = temp / 10; + + dec_value += last_digit * base; + + base = base * 2; + } + + return dec_value; +} + +// Driver program to test above function +int main() +{ + int num = 10101001; + + cout << binaryToDecimal(num) << endl; +} diff --git a/decimaltobinary.cpp b/decimaltobinary.cpp new file mode 100644 index 00000000..97798789 --- /dev/null +++ b/decimaltobinary.cpp @@ -0,0 +1,20 @@ +#include +using namespace std; + +string decimal_to_binary(int n) +{ + string ans; + while(n>0){ + int current_bit = n&1; + ans+=current_bit+'0'; + n>>=1; + } + reverse(ans.begin(),ans.end()); + return ans; +} +int main() +{ + string binary = decimal_to_binary(244); + cout << binary << endl; + return 0; +} diff --git a/insertion_sort_linked_list.cpp b/insertion_sort_linked_list.cpp new file mode 100644 index 00000000..d49fc2e8 --- /dev/null +++ b/insertion_sort_linked_list.cpp @@ -0,0 +1,15 @@ +ListNode* insertionSortList(ListNode* head) { + if (head == nullptr || head->next == NULL) + return head; + ListNode *h = insertionSortList(head->next); + if (head->val <= h->val) { + head->next = h; + return head; + } + ListNode *node = h; + while (node->next && head->val > node->next->val) + node = node->next; + head->next = node->next; + node->next = head; + return h; +} diff --git a/sorting.cpp b/sorting.cpp new file mode 100644 index 00000000..18be1c6f --- /dev/null +++ b/sorting.cpp @@ -0,0 +1,97 @@ +#include +using namespace std; +void display(int ar[],int n) +{ + for(int i=0;iar[j+1]) + { + temp=ar[j]; + ar[j]=ar[j+1]; + ar[j+1]=temp; + }}}} +void Insertion(int ar[], int n) +{ int key=0; + for( int i=1;i=0&& key>ch; + if(ch=='Y'||ch=='y') + { + int i,m,n; + cout<<"\n Enter your choice: \n 1.Selection sort\n 2.Bubble sort\n 3.Insertion sort"<>m; + cout<<"\n Enter the size of the array:"<>n; + int ar[n]; + cout<<"\n Enter the elements:"<>ar[i]; + } + switch(m) + { + case 1: + Selection(ar,n); + cout<<"\n Sorted array after Selection sort is:"< twoSum(vector& nums, int target) { + + + unordered_map hash; + vector result; + for (int i = 0; i < nums.size(); i++) + if (hash.count(target - nums[i])) + { + result.push_back(hash[target - nums[i]]); + result.push_back(i); + return result; + } + else + hash[nums[i]] = i; + return result; +} + + +}; From 4d1d45fd9812b2af19698863f71e6372378a58fb Mon Sep 17 00:00:00 2001 From: prashantkalokhe <82570721+prashantkalokhe@users.noreply.github.com> Date: Wed, 6 Oct 2021 22:41:48 +0530 Subject: [PATCH 032/147] Function Overloading Function Overloading Hacktoberfest 2021 --- Function Overloading | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Function Overloading diff --git a/Function Overloading b/Function Overloading new file mode 100644 index 00000000..213433d9 --- /dev/null +++ b/Function Overloading @@ -0,0 +1,27 @@ +#include +using namespace std; +class Addition { +public: + int ADD(int X,int Y) // Function with parameter + { + return X+Y; // this function is performing addition of two Integer value + } + int ADD() { // Function with same name but without parameter + string a= "HELLO"; + string b="SAM"; // in this function concatenation is performed + string c= a+b; + cout< Date: Wed, 6 Oct 2021 22:46:29 +0530 Subject: [PATCH 033/147] Operator Overloading Operator Overloading Hacktoberfest 2021 --- Operator Overloading | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Operator Overloading diff --git a/Operator Overloading b/Operator Overloading new file mode 100644 index 00000000..8fbbc639 --- /dev/null +++ b/Operator Overloading @@ -0,0 +1,33 @@ +#include +using namespace std; +class A +{ + + string x; + public: + A(){} + A(string i) + { + x=i; + } + void operator+(A); + void display(); +}; + +void A:: operator+(A a) +{ + + string m = x+a.x; + cout<<"The result of the addition of two objects is : "< Date: Thu, 7 Oct 2021 08:29:45 +0530 Subject: [PATCH 034/147] Create Recursive factorials --- Recursive factorials | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Recursive factorials diff --git a/Recursive factorials b/Recursive factorials new file mode 100644 index 00000000..ce502222 --- /dev/null +++ b/Recursive factorials @@ -0,0 +1,23 @@ +// C++ code to implement factorial +#include +using namespace std; + +// Factorial function +int f(int n) +{ + // Stop condition + if (n == 0 || n == 1) + return 1; + + // Recursive condition + else + return n * f(n - 1); +} + +// Driver code +int main() +{ + int n = 5; + cout<<"factorial of "< Date: Thu, 7 Oct 2021 08:31:15 +0530 Subject: [PATCH 035/147] Create howrecursionworks --- howrecursionworks | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 howrecursionworks diff --git a/howrecursionworks b/howrecursionworks new file mode 100644 index 00000000..8bcc6d4e --- /dev/null +++ b/howrecursionworks @@ -0,0 +1,23 @@ +// A C++ program to demonstrate working of +// recursion +#include +using namespace std; + +void printFun(int test) +{ + if (test < 1) + return; + else { + cout << test << " "; + printFun(test - 1); // statement 2 + cout << test << " "; + return; + } +} + +// Driver Code +int main() +{ + int test = 3; + printFun(test); +} From b4fa79a0f305c1d1a8076258c7b14661772170c9 Mon Sep 17 00:00:00 2001 From: falsecodes <92069207+falsecodes@users.noreply.github.com> Date: Thu, 7 Oct 2021 08:33:28 +0530 Subject: [PATCH 036/147] Create jump search cpp --- jump search cpp | 55 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 jump search cpp diff --git a/jump search cpp b/jump search cpp new file mode 100644 index 00000000..35bc92e6 --- /dev/null +++ b/jump search cpp @@ -0,0 +1,55 @@ +// C++ program to implement Jump Search + +#include +using namespace std; + +int jumpSearch(int arr[], int x, int n) +{ + // Finding block size to be jumped + int step = sqrt(n); + + // Finding the block where element is + // present (if it is present) + int prev = 0; + while (arr[min(step, n)-1] < x) + { + prev = step; + step += sqrt(n); + if (prev >= n) + return -1; + } + + // Doing a linear search for x in block + // beginning with prev. + while (arr[prev] < x) + { + prev++; + + // If we reached next block or end of + // array, element is not present. + if (prev == min(step, n)) + return -1; + } + // If element is found + if (arr[prev] == x) + return prev; + + return -1; +} + +// Driver program to test function +int main() +{ + int arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, + 34, 55, 89, 144, 233, 377, 610 }; + int x = 55; + int n = sizeof(arr) / sizeof(arr[0]); + + // Find the index of 'x' using Jump Search + int index = jumpSearch(arr, x, n); + + // Print the index where 'x' is located + cout << "\nNumber " << x << " is at index " << index; + return 0; +} + From 38dde7660f93c5d433ccb23df28998749532c67d Mon Sep 17 00:00:00 2001 From: falsecodes <92069207+falsecodes@users.noreply.github.com> Date: Thu, 7 Oct 2021 08:34:44 +0530 Subject: [PATCH 037/147] Create fibonacci search --- fibonacci search | 76 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 fibonacci search diff --git a/fibonacci search b/fibonacci search new file mode 100644 index 00000000..892c123a --- /dev/null +++ b/fibonacci search @@ -0,0 +1,76 @@ +// C program for Fibonacci Search +#include + +// Utility function to find minimum of two elements +int min(int x, int y) { return (x <= y) ? x : y; } + +/* Returns index of x if present, else returns -1 */ +int fibMonaccianSearch(int arr[], int x, int n) +{ + /* Initialize fibonacci numbers */ + int fibMMm2 = 0; // (m-2)'th Fibonacci No. + int fibMMm1 = 1; // (m-1)'th Fibonacci No. + int fibM = fibMMm2 + fibMMm1; // m'th Fibonacci + + /* fibM is going to store the smallest Fibonacci + Number greater than or equal to n */ + while (fibM < n) { + fibMMm2 = fibMMm1; + fibMMm1 = fibM; + fibM = fibMMm2 + fibMMm1; + } + + // Marks the eliminated range from front + int offset = -1; + + /* while there are elements to be inspected. Note that + we compare arr[fibMm2] with x. When fibM becomes 1, + fibMm2 becomes 0 */ + while (fibM > 1) { + // Check if fibMm2 is a valid location + int i = min(offset + fibMMm2, n - 1); + + /* If x is greater than the value at index fibMm2, + cut the subarray array from offset to i */ + if (arr[i] < x) { + fibM = fibMMm1; + fibMMm1 = fibMMm2; + fibMMm2 = fibM - fibMMm1; + offset = i; + } + + /* If x is greater than the value at index fibMm2, + cut the subarray after i+1 */ + else if (arr[i] > x) { + fibM = fibMMm2; + fibMMm1 = fibMMm1 - fibMMm2; + fibMMm2 = fibM - fibMMm1; + } + + /* element found. return index */ + else + return i; + } + + /* comparing the last element with x */ + if (fibMMm1 && arr[offset + 1] == x) + return offset + 1; + + /*element not found. return -1 */ + return -1; +} + +/* driver function */ +int main(void) +{ + int arr[] + = { 10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100,235}; + int n = sizeof(arr) / sizeof(arr[0]); + int x = 235; + int ind = fibMonaccianSearch(arr, x, n); +if(ind>=0) + printf("Found at index: %d",ind); +else + printf("%d isn't present in the array",x); + return 0; +} From 7516368e09a0a8ffb5e713903c609dd657053c4f Mon Sep 17 00:00:00 2001 From: Ashutosh Mittal Date: Thu, 7 Oct 2021 09:53:09 +0530 Subject: [PATCH 038/147] Merge sort --- merge_sort.cpp | 85 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 merge_sort.cpp diff --git a/merge_sort.cpp b/merge_sort.cpp new file mode 100644 index 00000000..fe0f8d8e --- /dev/null +++ b/merge_sort.cpp @@ -0,0 +1,85 @@ +//merge sort// +#include +using namespace std; +void merge(int a[], int n, int lb, int mid, int ub) +{ + int i = lb; + int j = mid + 1; + int k = lb; + int temp[n]; + while (i <= mid && j <= ub) + { + if (a[i] <= a[j]) + { + temp[k] = a[i]; + i++; + } + else + { + temp[k] = a[j]; + j++; + } + k++; + } + if (i > mid) + { + while (j <= ub) + { + + temp[k] = a[j]; + j++; + k++; + } + } + else + { + while (i <= mid) + { + + temp[k] = a[i]; + i++; + k++; + } + } + for (int k = lb; k <= ub; k++) + { + a[k] = temp[k]; + } +} +void mergesort(int a[], int n, int lb, int ub) +{ + if (lb < ub) + { + + int mid = (lb + ub) / 2; + mergesort(a, n, lb, mid); + mergesort(a, n, mid + 1, ub); + merge(a, n, lb, mid, ub); + } + else + return; +} +int main() +{ + int n; + cout << "ENTER THE SIZE OF AN ARRAY" << endl; + cin >> n; + int a[n]; + for (int i = 0; i < n; i++) + { + cin >> a[i]; + } + cout << "DISPLAYING ORIGINAL ARRAY" << endl; + for (int i = 0; i < n; i++) + { + cout << a[i] << " " << endl; + } + mergesort(a, n, 0, n - 1); + cout << "DISPLAYING SORTED ARRAY" << endl; + for (int i = 0; i < n; i++) + { + cout << a[i] << " " << endl; + } + + return 0; +} \ No newline at end of file From 87ff4fadf83a816695ad74d969df72411a4da26f Mon Sep 17 00:00:00 2001 From: Ashutosh Mittal Date: Thu, 7 Oct 2021 09:57:40 +0530 Subject: [PATCH 039/147] merge two sorted linkedlist --- merge_twosortedll.cpp | 122 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 merge_twosortedll.cpp diff --git a/merge_twosortedll.cpp b/merge_twosortedll.cpp new file mode 100644 index 00000000..0a56d994 --- /dev/null +++ b/merge_twosortedll.cpp @@ -0,0 +1,122 @@ +#include +using namespace std; +class node +{ +public: + int data; + node *next; + node(int data) + { + this->data = data; + next = NULL; + } +}; +node *takeinput_better() +{ + int data; + + cin >> data; + node *head = NULL; + node *tail = NULL; + + while (data != -1) + { + node *newnode = new node(data); + if (head == NULL) + { + head = newnode; + tail = newnode; + } + else + { + tail->next = newnode; + tail = tail->next; + } + + cin >> data; + } + return head; +} +node *merge_twosortedlist(node *x, node *y) +{ + node *finalhead = NULL; + node *finaltail = NULL; + + if (x->data < y->data) + { + finalhead = x; + finaltail = x; + x = x->next; + while (x != NULL && y != NULL) + { + if (x->data > y->data) + { + finaltail->next = y; + finaltail = finaltail->next; + + y = y->next; + } + else + { + finaltail->next = x; + finaltail = finaltail->next; + x = x->next; + } + } + + } + + else if (x->data > y->data) + { + finalhead = y; + finaltail = y; + y = y->next; + while (x != NULL && y != NULL) + { + if (x->data > y->data) + { + finaltail->next = y; + finaltail = finaltail->next; + + y = y->next; + } + else + { + finaltail->next = x; + finaltail = finaltail->next; + + x = x->next; + } + } + } + + + if (y == NULL) + { + finaltail->next = x; + } + else + { + finaltail->next = y; + } + return finalhead; +} +void print(node *head) +{ + while (head != NULL) + { + cout << head->data << " "; + head = head->next; + } +} +int main() +{ + node *x = takeinput_better(); + print(x); + cout< Date: Thu, 7 Oct 2021 15:15:09 +0530 Subject: [PATCH 040/147] Create Ping Pong Game --- Ping Pong Game | 84 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 Ping Pong Game diff --git a/Ping Pong Game b/Ping Pong Game new file mode 100644 index 00000000..5945f78e --- /dev/null +++ b/Ping Pong Game @@ -0,0 +1,84 @@ +from random import choice, random +from turtle import * + +from freegames import vector + + +def value(): + "Randomly generate value between (-5, -3) or (3, 5)." + return (3 + random() * 2) * choice([1, -1]) + + +ball = vector(0, 0) +aim = vector(value(), value()) +state = {1: 0, 2: 0} + + +def move(player, change): + "Move player position by change." + state[player] += change + + +def rectangle(x, y, width, height): + "Draw rectangle at (x, y) with given width and height." + up() + goto(x, y) + down() + begin_fill() + for count in range(2): + forward(width) + left(90) + forward(height) + left(90) + end_fill() + + +def draw(): + "Draw game and move pong ball." + clear() + rectangle(-200, state[1], 10, 50) + rectangle(190, state[2], 10, 50) + + ball.move(aim) + x = ball.x + y = ball.y + + up() + goto(x, y) + dot(10) + update() + + if y < -200 or y > 200: + aim.y = -aim.y + + if x < -185: + low = state[1] + high = state[1] + 50 + + if low <= y <= high: + aim.x = -aim.x + else: + return + + if x > 185: + low = state[2] + high = state[2] + 50 + + if low <= y <= high: + aim.x = -aim.x + else: + return + + ontimer(draw, 50) + + +setup(420, 420, 370, 0) +hideturtle() +tracer(False) +listen() +onkey(lambda: move(1, 20), 'w') +onkey(lambda: move(1, -20), 's') +onkey(lambda: move(2, 20), 'i') +onkey(lambda: move(2, -20), 'k') +draw() +done() From 9d48939bc873b6fdf3734a4817535eebdfdefd0c Mon Sep 17 00:00:00 2001 From: pratham-web <73058103+pratham-web@users.noreply.github.com> Date: Thu, 7 Oct 2021 15:17:02 +0530 Subject: [PATCH 041/147] Create game --- game | 84 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 game diff --git a/game b/game new file mode 100644 index 00000000..5945f78e --- /dev/null +++ b/game @@ -0,0 +1,84 @@ +from random import choice, random +from turtle import * + +from freegames import vector + + +def value(): + "Randomly generate value between (-5, -3) or (3, 5)." + return (3 + random() * 2) * choice([1, -1]) + + +ball = vector(0, 0) +aim = vector(value(), value()) +state = {1: 0, 2: 0} + + +def move(player, change): + "Move player position by change." + state[player] += change + + +def rectangle(x, y, width, height): + "Draw rectangle at (x, y) with given width and height." + up() + goto(x, y) + down() + begin_fill() + for count in range(2): + forward(width) + left(90) + forward(height) + left(90) + end_fill() + + +def draw(): + "Draw game and move pong ball." + clear() + rectangle(-200, state[1], 10, 50) + rectangle(190, state[2], 10, 50) + + ball.move(aim) + x = ball.x + y = ball.y + + up() + goto(x, y) + dot(10) + update() + + if y < -200 or y > 200: + aim.y = -aim.y + + if x < -185: + low = state[1] + high = state[1] + 50 + + if low <= y <= high: + aim.x = -aim.x + else: + return + + if x > 185: + low = state[2] + high = state[2] + 50 + + if low <= y <= high: + aim.x = -aim.x + else: + return + + ontimer(draw, 50) + + +setup(420, 420, 370, 0) +hideturtle() +tracer(False) +listen() +onkey(lambda: move(1, 20), 'w') +onkey(lambda: move(1, -20), 's') +onkey(lambda: move(2, 20), 'i') +onkey(lambda: move(2, -20), 'k') +draw() +done() From 09c7c8050a83b2e0f79910fe976ce3bf79b3662d Mon Sep 17 00:00:00 2001 From: Varun Sunil Pathak <83233491+pathakvsp1@users.noreply.github.com> Date: Thu, 7 Oct 2021 17:44:21 +0530 Subject: [PATCH 042/147] updated ll_Deletion.cpp --- ll_deletion.cpp | 104 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 ll_deletion.cpp diff --git a/ll_deletion.cpp b/ll_deletion.cpp new file mode 100644 index 00000000..03cc3754 --- /dev/null +++ b/ll_deletion.cpp @@ -0,0 +1,104 @@ +// A complete working C++ program to +// demonstrate deletion in singly +// linked list with class +#include +using namespace std; + +// A linked list node +class Node{ +public: + int data; + Node* next; +}; + +// Given a reference (pointer to pointer) +// to the head of a list and an int, +// inserts a new node on the front of the +// list. +void push(Node** head_ref, int new_data) +{ + Node* new_node = new Node(); + new_node->data = new_data; + new_node->next = (*head_ref); + (*head_ref) = new_node; +} + +// Given a reference (pointer to pointer) +// to the head of a list and a key, deletes +// the first occurrence of key in linked list +void deleteNode(Node** head_ref, int key) +{ + + // Store head node + Node* temp = *head_ref; + Node* prev = NULL; + + // If head node itself holds + // the key to be deleted + if (temp != NULL && temp->data == key) + { + *head_ref = temp->next; // Changed head + delete temp; // free old head + return; + } + + // Else Search for the key to be deleted, + // keep track of the previous node as we + // need to change 'prev->next' */ + else + { + while (temp != NULL && temp->data != key) + { + prev = temp; + temp = temp->next; + } + + // If key was not present in linked list + if (temp == NULL) + return; + + // Unlink the node from linked list + prev->next = temp->next; + + // Free memory + delete temp; + } +} + +// This function prints contents of +// linked list starting from the +// given node +void printList(Node* node) +{ + while (node != NULL) + { + cout << node->data << " "; + node = node->next; + } +} + +// Driver code +int main() +{ + + // Start with the empty list + Node* head = NULL; + + // Add elements in linked list + push(&head, 7); + push(&head, 1); + push(&head, 3); + push(&head, 2); + + puts("Created Linked List: "); + printList(head); + + deleteNode(&head, 1); + puts("\nLinked List after Deletion of 1: "); + + printList(head); + + return 0; +} + +// This code is contributed by pathakvsp1 From 73f9ad589a32d36081467acc52303c3b716ceffd Mon Sep 17 00:00:00 2001 From: PallaviPareek <50631982+PallaviPareek@users.noreply.github.com> Date: Thu, 7 Oct 2021 18:13:24 +0530 Subject: [PATCH 043/147] perfect_number.cpp --- perfect_number.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 perfect_number.cpp diff --git a/perfect_number.cpp b/perfect_number.cpp new file mode 100644 index 00000000..29f806c1 --- /dev/null +++ b/perfect_number.cpp @@ -0,0 +1,20 @@ +#include + +using namespace std; +int main() +{ + int num, i, sum=0; + cout<<"Enter a Number: "; + cin>>num; + for(i=1; i Date: Thu, 7 Oct 2021 19:00:51 +0530 Subject: [PATCH 044/147] Create scientific calculator in python --- scientific calculator in python | 368 ++++++++++++++++++++++++++++++++ 1 file changed, 368 insertions(+) create mode 100644 scientific calculator in python diff --git a/scientific calculator in python b/scientific calculator in python new file mode 100644 index 00000000..ff7874db --- /dev/null +++ b/scientific calculator in python @@ -0,0 +1,368 @@ + # Scientific Calculator + +from tkinter import * +import math +import tkinter.messagebox + +root = Tk() +root.title("Scientific Calculator") +root.configure(background='white') +root.resizable(width=False, height=False) +root.geometry("480x568+450+90") + +calc = Frame(root) +calc.grid() + + +class Calc(): + def __init__(self): + self.total = 0 + self.current = '' + self.input_value = True + self.check_sum = False + self.op = '' + self.result = False + + def numberEnter(self, num): + self.result = False + firstnum = txtDisplay.get() + secondnum = str(num) + if self.input_value: + self.current = secondnum + self.input_value = False + else: + if secondnum == '.': + if secondnum in firstnum: + return + self.current = firstnum + secondnum + self.display(self.current) + + def sum_of_total(self): + self.result = True + self.current = float(self.current) + if self.check_sum == True: + self.valid_function() + else: + self.total = float(txtDisplay.get()) + + def display(self, value): + txtDisplay.delete(0, END) + txtDisplay.insert(0, value) + + def valid_function(self): + if self.op == "add": + self.total += self.current + if self.op == "sub": + self.total -= self.current + if self.op == "multi": + self.total *= self.current + if self.op == "divide": + self.total /= self.current + if self.op == "mod": + self.total %= self.current + self.input_value = True + self.check_sum = False + self.display(self.total) + + def operation(self, op): + self.current = float(self.current) + if self.check_sum: + self.valid_function() + elif not self.result: + self.total = self.current + self.input_value = True + self.check_sum = True + self.op = op + self.result = False + + def Clear_Entry(self): + self.result = False + self.current = "0" + self.display(0) + self.input_value = True + + def All_Clear_Entry(self): + self.Clear_Entry() + self.total = 0 + + def pi(self): + self.result = False + self.current = math.pi + self.display(self.current) + + def tau(self): + self.result = False + self.current = math.tau + self.display(self.current) + + def e(self): + self.result = False + self.current = math.e + self.display(self.current) + + def mathPM(self): + self.result = False + self.current = -(float(txtDisplay.get())) + self.display(self.current) + + def squared(self): + self.result = False + self.current = math.sqrt(float(txtDisplay.get())) + self.display(self.current) + + def cos(self): + self.result = False + self.current = math.cos(math.radians(float(txtDisplay.get()))) + self.display(self.current) + + def cosh(self): + self.result = False + self.current = math.cosh(math.radians(float(txtDisplay.get()))) + self.display(self.current) + + def tan(self): + self.result = False + self.current = math.tan(math.radians(float(txtDisplay.get()))) + self.display(self.current) + + def tanh(self): + self.result = False + self.current = math.tanh(math.radians(float(txtDisplay.get()))) + self.display(self.current) + + def sin(self): + self.result = False + self.current = math.sin(math.radians(float(txtDisplay.get()))) + self.display(self.current) + + def sinh(self): + self.result = False + self.current = math.sinh(math.radians(float(txtDisplay.get()))) + self.display(self.current) + + def log(self): + self.result = False + self.current = math.log(float(txtDisplay.get())) + self.display(self.current) + + def exp(self): + self.result = False + self.current = math.exp(float(txtDisplay.get())) + self.display(self.current) + + def acosh(self): + self.result = False + self.current = math.acosh(float(txtDisplay.get())) + self.display(self.current) + + def asinh(self): + self.result = False + self.current = math.asinh(float(txtDisplay.get())) + self.display(self.current) + + def expm1(self): + self.result = False + self.current = math.expm1(float(txtDisplay.get())) + self.display(self.current) + + def lgamma(self): + self.result = False + self.current = math.lgamma(float(txtDisplay.get())) + self.display(self.current) + + def degrees(self): + self.result = False + self.current = math.degrees(float(txtDisplay.get())) + self.display(self.current) + + def log2(self): + self.result = False + self.current = math.log2(float(txtDisplay.get())) + self.display(self.current) + + def log10(self): + self.result = False + self.current = math.log10(float(txtDisplay.get())) + self.display(self.current) + + def log1p(self): + self.result = False + self.current = math.log1p(float(txtDisplay.get())) + self.display(self.current) + + +added_value = Calc() + + + +txtDisplay = Entry(calc, font=('Helvetica', 20, 'bold'), bg='black', fg='white', bd=30, + width=28, justify=RIGHT) +txtDisplay.grid(row=0, column=0, columnspan=4, pady=1) +txtDisplay.insert(0, "0") + + + +numberpad = "789456123" +i = 0 +btn = [] +for j in range(2, 5): + for k in range(3): + btn.append(Button(calc, width=6, height=2, bg='white', fg='black', font=('Helvetica', 20, 'bold'), + bd=4, text=numberpad[i])) + btn[i].grid(row=j, column=k, pady=1) + btn[i]["command"] = lambda x=numberpad[i]: added_value.numberEnter(x) + i += 1 + + +btnClear = Button(calc, text=chr(67), width=6, height=2, bg='black', fg='white', font=('Helvetica', 20, 'bold') + , bd=4, command=added_value.Clear_Entry).grid(row=1, column=0, pady=1) + +btnAllClear = Button(calc, text=chr(67) + chr(69), width=6, height=2, bg='black', fg='white', font=('Helvetica' + , 20, 'bold'), bd=4, + command=added_value.All_Clear_Entry).grid(row=1, column=1, pady=1) + +btnsq = Button(calc, text="\u221A", width=6, height=2, bg='black', fg='white', font=('Helvetica', 20, 'bold'), + bd=4, command=added_value.squared).grid(row=1, column=2, pady=1) + +btnAdd = Button(calc, text="+", width=6, height=2, bg='black', fg='white', font=('Helvetica', 20, 'bold'), + bd=4, command=lambda: added_value.operation("add") + ).grid(row=1, column=3, pady=1) + +btnSub = Button(calc, text="-", width=6, height=2, bg='black', fg='white', font=('Helvetica', 20, 'bold'), + bd=4, command=lambda: added_value.operation("sub") + ).grid(row=2, column=3, pady=1) + +btnMul = Button(calc, text="x", width=6, height=2, bg='black', fg='white', font=('Helvetica', 20, 'bold'), + bd=4, command=lambda: added_value.operation("multi") + ).grid(row=3, column=3, pady=1) + +btnDiv = Button(calc, text="/", width=6, height=2, bg='black', fg='white', font=('Helvetica', 20, 'bold'), + bd=4, command=lambda: added_value.operation("divide") + ).grid(row=4, column=3, pady=1) + +btnZero = Button(calc, text="0", width=6, height=2, bg='white', fg='black', font=('Helvetica', 20, 'bold'), + bd=4, command=lambda: added_value.numberEnter(0) + ).grid(row=5, column=0, pady=1) + +btnDot = Button(calc, text=".", width=6, height=2, bg='black', fg='white', font=('Helvetica', 20, 'bold'), + bd=4, command=lambda: added_value.numberEnter(".") + ).grid(row=5, column=1, pady=1) +btnPM = Button(calc, text=chr(177), width=6, height=2, bg='black', fg='white', font=('Helvetica', 20, 'bold'), + bd=4, command=added_value.mathPM).grid(row=5, column=2, pady=1) + +btnEquals = Button(calc, text="=", width=6, height=2, bg='black', fg='white', font=('Helvetica', 20, 'bold'), + bd=4, command=added_value.sum_of_total).grid(row=5, column=3, pady=1) + + + +btnPi = Button(calc, text="pi", width=6, height=2, bg='white', fg='black', font=('Helvetica', 20, 'bold'), + bd=4, command=added_value.pi).grid(row=1, column=4, pady=1) + +btnCos = Button(calc, text="Cos", width=6, height=2, bg='white', fg='black', font=('Helvetica', 20, 'bold'), + bd=4, command=added_value.cos).grid(row=1, column=5, pady=1) + +btntan = Button(calc, text="tan", width=6, height=2, bg='white', fg='black', font=('Helvetica', 20, 'bold'), + bd=4, command=added_value.tan).grid(row=1, column=6, pady=1) + +btnsin = Button(calc, text="sin", width=6, height=2, bg='white', fg='black', font=('Helvetica', 20, 'bold'), + bd=4, command=added_value.sin).grid(row=1, column=7, pady=1) + + +btn2Pi = Button(calc, text="2pi", width=6, height=2, bg='white', fg='black', font=('Helvetica', 20, 'bold'), + bd=4, command=added_value.tau).grid(row=2, column=4, pady=1) + +btnCosh = Button(calc, text="Cosh", width=6, height=2, bg='white', fg='black', font=('Helvetica', 20, 'bold'), + bd=4, command=added_value.cosh).grid(row=2, column=5, pady=1) + +btntanh = Button(calc, text="tanh", width=6, height=2, bg='white', fg='black', font=('Helvetica', 20, 'bold'), + bd=4, command=added_value.tanh).grid(row=2, column=6, pady=1) + +btnsinh = Button(calc, text="sinh", width=6, height=2, bg='white', fg='black', font=('Helvetica', 20, 'bold'), + bd=4, command=added_value.sinh).grid(row=2, column=7, pady=1) + + +btnlog = Button(calc, text="log", width=6, height=2, bg='white', fg='black', font=('Helvetica', 20, 'bold'), + bd=4, command=added_value.log).grid(row=3, column=4, pady=1) + +btnExp = Button(calc, text="exp", width=6, height=2, bg='white', fg='black', font=('Helvetica', 20, 'bold'), + bd=4, command=added_value.exp).grid(row=3, column=5, pady=1) + +btnMod = Button(calc, text="Mod", width=6, height=2, bg='white', fg='black', font=('Helvetica', 20, 'bold'), + bd=4, command=lambda: added_value.operation("mod") + ).grid(row=3, column=6, pady=1) + +btnE = Button(calc, text="e", width=6, height=2, bg='white', fg='black', font=('Helvetica', 20, 'bold'), + bd=4, command=added_value.e).grid(row=3, column=7, pady=1) + + +btnlog10 = Button(calc, text="log10", width=6, height=2, bg='white', fg='black', font=('Helvetica', 20, 'bold') + , bd=4, command=added_value.log10).grid(row=4, column=4, pady=1) + +btncos = Button(calc, text="log1p", width=6, height=2, bg='white', fg='black', font=('Helvetica', 20, 'bold'), + bd=4, command=added_value.log1p).grid(row=4, column=5, pady=1) + +btnexpm1 = Button(calc, text="expm1", width=6, height=2, bg='white', fg='black', font=('Helvetica', 20, 'bold') + , bd=4, command=added_value.expm1).grid(row=4, column=6, pady=1) + +btngamma = Button(calc, text="gamma", width=6, height=2, bg='white', fg='black', font=('Helvetica', 20, 'bold') + , bd=4, command=added_value.lgamma).grid(row=4, column=7, pady=1) + + + +btnlog2 = Button(calc, text="log2", width=6, height=2, bg='white', fg='black', font=('Helvetica', 20, 'bold'), + bd=4, command=added_value.log2).grid(row=5, column=4, pady=1) + +btndeg = Button(calc, text="deg", width=6, height=2, bg='white', fg='black', font=('Helvetica', 20, 'bold'), + bd=4, command=added_value.degrees).grid(row=5, column=5, pady=1) + +btnacosh = Button(calc, text="acosh", width=6, height=2, bg='white', fg='black', font=('Helvetica', 20, 'bold'), + bd=4, command=added_value.acosh).grid(row=5, column=6, pady=1) + +btnasinh = Button(calc, text="asinh", width=6, height=2, bg='white', fg='black', font=('Helvetica', 20, 'bold'), + bd=4, command=added_value.asinh).grid(row=5, column=7, pady=1) + +lblDisplay = Label(calc, text="Scientific Calculator", font=('Helvetica', 30, 'bold'), + bg='black', fg='white', justify=CENTER) +lblDisplay.grid(row=0, column=4, columnspan=4) + + + +def iExit(): + iExit = tkinter.messagebox.askyesno("Scientific Calculator", "Do you want to exit ?") + if iExit > 0: + root.destroy() + return + + +def Scientific(): + root.resizable(width=False, height=False) + root.geometry("944x568+0+0") + + +def Standard(): + root.resizable(width=False, height=False) + root.geometry("480x568+0+0") + + + +menubar = Menu(calc) + + +filemenu = Menu(menubar, tearoff=0) +menubar.add_cascade(label='File', menu=filemenu) +filemenu.add_command(label="Standard", command=Standard) +filemenu.add_command(label="Scientific", command=Scientific) +filemenu.add_separator() +filemenu.add_command(label="Exit", command=iExit) + + +editmenu = Menu(menubar, tearoff=0) +menubar.add_cascade(label='Edit', menu=editmenu) +editmenu.add_command(label="Cut") +editmenu.add_command(label="Copy") +editmenu.add_separator() +editmenu.add_command(label="Paste") + +root.config(menu=menubar) + +root.mainloop() From ffe3c5039750b3932c4a514bf018176414d5c8bd Mon Sep 17 00:00:00 2001 From: Hiten Date: Fri, 8 Oct 2021 11:45:03 +0530 Subject: [PATCH 045/147] sparse matrix c++ --- sparse_matrix.cpp | 94 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 sparse_matrix.cpp diff --git a/sparse_matrix.cpp b/sparse_matrix.cpp new file mode 100644 index 00000000..ff8b71a7 --- /dev/null +++ b/sparse_matrix.cpp @@ -0,0 +1,94 @@ +#include +using namespace std; + +int main() +{ + int n,m,i,j,k=1,count=0; + cout<<"Enter value of n"<>n; + cout<<"Enter value of m"<>m; + int M1[n][m], M2[10][3]; + cout<<"Enter the matrix"<>M1[i][j]; + } + } + + for(i=0;i +// using namespace std; + +// int main() +// { +// int n,i,j,k=1,count=0; +// cout<<"Enter value of n"<>n; +// int M1[n][n], M2[10][3]; +// cout<<"Enter the matrix"<>M1[i][j]; +// } +// } + +// for(i=0;i Date: Fri, 8 Oct 2021 19:13:17 +0530 Subject: [PATCH 046/147] Create healthy_programmer.py This is a mini python project which is developed as part of learning python course. This is a simple notification system based program which only runs in between office hours(i.e. in between 9:00 am to 5:00 pm). Some of the features of this project:- it will remind user to drink water in every 20 minutes. will remind user to exercise his/her body in every 30 minutes. will remind user for eyes exercise in every 45 minutes. this project contains three mp3 files for sounds of notifications and one program file. --- healthy_programmer.py | 62 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 healthy_programmer.py diff --git a/healthy_programmer.py b/healthy_programmer.py new file mode 100644 index 00000000..0e8029d8 --- /dev/null +++ b/healthy_programmer.py @@ -0,0 +1,62 @@ +from pygame import mixer + +from datetime import datetime +import time + +def musiconloop(file, stopper): + mixer.init() + mixer.music.load(file) + mixer.music.play() + while True: + a = input() + if a == stopper: + mixer.music.stop() + break + +def log_now(msg): + with open("mylogs.txt", "a") as f: + f.write(f"{msg} {datetime.now()}\n") + +def IsOfficeTime(currenttime): + if currenttime > '09:00:00' and currenttime < '17:00:01': + return True + else: + print("Sorry we only play this application in office hours i.e. in between 9 am to 5 pm ") + return False + +if __name__ == '__main__': + # musiconloop("water.mp3", "stop") + init_water = time.time() + init_eyes = time.time() + init_exercise = time.time() + currenttime = time.strftime('%H:%M:%S') + watersecs = 20*60 # Every 20 minutes + exesecs = 30*60 # Every 30 minutes + eyessecs = 45*60 # Every 45 minutes + SleepTime = 60 # Time gap of 1 minute after each task is performed + + while (IsOfficeTime(currenttime)): + + if time.time() - init_water > watersecs: + print("Water Drinking time. Enter 'D' to stop the alarm.") + musiconloop('water.mp3', 'D') + init_water = time.time() + log_now("Drank water at") + time.sleep(SleepTime) + + if time.time() - init_eyes > eyessecs: + print("Eyes exercise time. Enter 'E' to stop the alarm.") + musiconloop('rush.mp3','E') + init_eyes = time.time() + log_now("Eyes exercise done at") + time.sleep(SleepTime) + + if time.time() - init_exercise > exesecs: + print("Body Exercise time. Enter 'B' to stop the alarm.") + musiconloop('physical-exercise.mp3','B') + init_exercise = time.time() + log_now("Body exercise done at") + time.sleep(SleepTime) + + time.sleep(SleepTime) + currenttime = time.strftime('%H:%M:%S') From d53ef1170612fc9762935ce3fe1f91d6d41afe54 Mon Sep 17 00:00:00 2001 From: Harshit Paneri <82382478+harshit-paneri@users.noreply.github.com> Date: Sat, 9 Oct 2021 00:12:28 +0530 Subject: [PATCH 047/147] update perfect no accept by PR --- perfect_no.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 perfect_no.cpp diff --git a/perfect_no.cpp b/perfect_no.cpp new file mode 100644 index 00000000..51cf7a59 --- /dev/null +++ b/perfect_no.cpp @@ -0,0 +1,29 @@ +#include + +using namespace std; + +int main() +{ + int number, i, sum = 0; + + cout << "Please Enter the Number to check for Perfect = "; + cin >> number; + + for(i = 1 ; i < number ; i++) + { + if(number % i == 0) + { + sum = sum + i; + } + } + + if(number == sum) + { + cout << number << " is a Perfect Number"; + } + else + { + cout << number << " is Not a Perfect Number"; + } + return 0; +} \ No newline at end of file From 23e5c6b412a4d2adbd8abb464ce4f27dc5f1d955 Mon Sep 17 00:00:00 2001 From: Omar AbdulRahman <58887202+omarr45@users.noreply.github.com> Date: Fri, 8 Oct 2021 20:51:51 +0200 Subject: [PATCH 048/147] Create KnapsackRecursive.cpp --- KnapsackRecursive.cpp | 48 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 KnapsackRecursive.cpp diff --git a/KnapsackRecursive.cpp b/KnapsackRecursive.cpp new file mode 100644 index 00000000..0c39871c --- /dev/null +++ b/KnapsackRecursive.cpp @@ -0,0 +1,48 @@ +/* A Naive recursive implementation of +0-1 Knapsack problem */ +#include +using namespace std; + +// A utility function that returns +// maximum of two integers +int max(int a, int b) { return (a > b) ? a : b; } + +// Returns the maximum value that +// can be put in a knapsack of capacity W +int knapSack(int W, int wt[], int val[], int n) +{ + + // Base Case + if (n == 0 || W == 0) + return 0; + + // If weight of the nth item is more + // than Knapsack capacity W, then + // this item cannot be included + // in the optimal solution + if (wt[n - 1] > W) + return knapSack(W, wt, val, n - 1); + + // Return the maximum of two cases: + // (1) nth item included + // (2) not included + else + return max( + val[n - 1] + + knapSack(W - wt[n - 1], + wt, val, n - 1), + knapSack(W, wt, val, n - 1)); +} + +// Driver code +int main() +{ + int val[] = { 60, 100, 120 }; + int wt[] = { 10, 20, 30 }; + int W = 50; + int n = sizeof(val) / sizeof(val[0]); + cout << knapSack(W, wt, val, n); + return 0; +} + +// This code is contributed by rathbhupendra From 48fd3a2b5cdd37c09a2798e6c4a78a98a98ce722 Mon Sep 17 00:00:00 2001 From: Omar AbdulRahman <58887202+omarr45@users.noreply.github.com> Date: Fri, 8 Oct 2021 20:55:04 +0200 Subject: [PATCH 049/147] Create KnapsackRec.cpp --- KnapsackRec.cpp | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 KnapsackRec.cpp diff --git a/KnapsackRec.cpp b/KnapsackRec.cpp new file mode 100644 index 00000000..0c39871c --- /dev/null +++ b/KnapsackRec.cpp @@ -0,0 +1,48 @@ +/* A Naive recursive implementation of +0-1 Knapsack problem */ +#include +using namespace std; + +// A utility function that returns +// maximum of two integers +int max(int a, int b) { return (a > b) ? a : b; } + +// Returns the maximum value that +// can be put in a knapsack of capacity W +int knapSack(int W, int wt[], int val[], int n) +{ + + // Base Case + if (n == 0 || W == 0) + return 0; + + // If weight of the nth item is more + // than Knapsack capacity W, then + // this item cannot be included + // in the optimal solution + if (wt[n - 1] > W) + return knapSack(W, wt, val, n - 1); + + // Return the maximum of two cases: + // (1) nth item included + // (2) not included + else + return max( + val[n - 1] + + knapSack(W - wt[n - 1], + wt, val, n - 1), + knapSack(W, wt, val, n - 1)); +} + +// Driver code +int main() +{ + int val[] = { 60, 100, 120 }; + int wt[] = { 10, 20, 30 }; + int W = 50; + int n = sizeof(val) / sizeof(val[0]); + cout << knapSack(W, wt, val, n); + return 0; +} + +// This code is contributed by rathbhupendra From 27acde6f6eb892681e24a6cc7946f1236f5b580b Mon Sep 17 00:00:00 2001 From: melonwall <73346879+melonwall@users.noreply.github.com> Date: Sat, 9 Oct 2021 10:56:04 +0530 Subject: [PATCH 050/147] Create anagram.cpp --- anagram.cpp | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 anagram.cpp diff --git a/anagram.cpp b/anagram.cpp new file mode 100644 index 00000000..c87c77b6 --- /dev/null +++ b/anagram.cpp @@ -0,0 +1,58 @@ +#include +using namespace std; + + +bool isAnagram(string str1, string str2) +{ + + int str1_size=str1.size(); + int str2_size=str2.size(); + int flag=0; + mapm; + + for(int i=0;i>str1>>str2; + bool result; + result=isAnagram(str1,str2); + if(result) + cout<<"Yes"; + else + cout<<"No"; + + return 0; +} From 8e00d2ad52f28cf0385a37ef44654e0346ceb253 Mon Sep 17 00:00:00 2001 From: khushimehta12 <58066257+khushimehta12@users.noreply.github.com> Date: Sat, 9 Oct 2021 11:05:47 +0530 Subject: [PATCH 051/147] Programm for FCFS --- Program for FCFS | 58 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Program for FCFS diff --git a/Program for FCFS b/Program for FCFS new file mode 100644 index 00000000..54f5c3f7 --- /dev/null +++ b/Program for FCFS @@ -0,0 +1,58 @@ +#include +using namespace std; +int main() { + int bt[20],p[20],wt[20],tat[20],pr[20],i,j,n,total=0,pos,temp,avg_wt,avg_tat; + cout<<"Enter Total Number of Process:"; + cin>>n; + cout<<"nEnter Burst Time and Priorityn"; + for (i=0;i>bt[i]; + cout<<"Priority:"; + cin>>pr[i]; + p[i]=i+1; + //contains process number + } + //sorting burst time, priority and process number in ascending order using selection sort + for (i=0;i Date: Sat, 9 Oct 2021 17:49:01 +0530 Subject: [PATCH 053/147] Create remove nth node from end of the list --- remove nth node from end of the list | 36 ++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 remove nth node from end of the list diff --git a/remove nth node from end of the list b/remove nth node from end of the list new file mode 100644 index 00000000..e6574bf9 --- /dev/null +++ b/remove nth node from end of the list @@ -0,0 +1,36 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* removeNthFromEnd(ListNode* head, int n) { + ListNode* slow=head; + ListNode* fast=head; + for(int i=0;inext; + if(fast==NULL) + { + head=head->next; + return head; + } + while(fast->next!=NULL) + { + fast=fast->next; + slow=slow->next; + } + { + + slow->next=slow->next->next; + + return head; + } + + } +}; From d2c155a2fea6e02fbe1d757dfafe809e56ed2dae Mon Sep 17 00:00:00 2001 From: Ujjwal Dhakal <68050149+ujjwalnp@users.noreply.github.com> Date: Sat, 9 Oct 2021 20:44:20 +0545 Subject: [PATCH 054/147] Create AnagramOfStrings.java I created the program in java for finding anagram of string for hactoberfest challenge. --- AnagramOfStrings.java | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 AnagramOfStrings.java diff --git a/AnagramOfStrings.java b/AnagramOfStrings.java new file mode 100644 index 00000000..b3d34767 --- /dev/null +++ b/AnagramOfStrings.java @@ -0,0 +1,35 @@ +# This is the code for finding anagram of the string in java + + +import java.util.Scanner; +public class AnagramOfStrings { + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.print("Enter first string : "); + String a = sc.nextLine(); + System.out.print("Enter second string : "); + String b = sc.nextLine(); + + boolean isAnagram = false; + boolean visited[] = new boolean[b.length()]; + + if (a.length()==b.length()) { + for (int i=0; i Date: Sun, 10 Oct 2021 02:10:39 +0530 Subject: [PATCH 055/147] Created avoid_flood_leetcode_sol --- avoid-flood-in-the-city.cpp | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 avoid-flood-in-the-city.cpp diff --git a/avoid-flood-in-the-city.cpp b/avoid-flood-in-the-city.cpp new file mode 100644 index 00000000..6a1767fe --- /dev/null +++ b/avoid-flood-in-the-city.cpp @@ -0,0 +1,33 @@ + +// Time: O(nlogn) +// Space: O(n) + +class Solution { +public: + vector avoidFlood(vector& rains) { + unordered_map> lookup; + for (int i = rains.size() - 1; i >= 0; --i) { + lookup[rains[i]].emplace_back(i); + } + vector result; + priority_queue, greater> min_heap; + for (int i = 0; i < rains.size(); ++i) { + if (rains[i]) { + if (lookup[rains[i]].size() >= 2) { + lookup[rains[i]].pop_back(); + min_heap.emplace(lookup[rains[i]].back()); + } + result.emplace_back(-1); + } else if (!min_heap.empty()) { + int j = min_heap.top(); min_heap.pop(); + if (j < i) { + return {}; + } + result.emplace_back(rains[j]); + } else { + result.emplace_back(1); + } + } + return min_heap.empty() ? result : vector(); + } +}; From 2e269a5bbcdbb328d5df0d20f463a44ccae42292 Mon Sep 17 00:00:00 2001 From: NIHAL AHMAD Date: Sun, 10 Oct 2021 10:30:20 +0530 Subject: [PATCH 056/147] 3 Sum Solution --- 3sum.cpp | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 3sum.cpp diff --git a/3sum.cpp b/3sum.cpp new file mode 100644 index 00000000..899d65e9 --- /dev/null +++ b/3sum.cpp @@ -0,0 +1,43 @@ + +// 3 SUM Solution + + +class Solution { +public: + vector> threeSum(vector& nums) { + int N = nums.size(); + vector> result; + if (N < 2) { + result; + } + sort(begin(nums), end(nums)); + for (int i = 0; i < N - 2 && nums[i] <= 0; i++) { + if (i > 0 && nums[i] == nums[i - 1]) { + continue; + } + int j = i + 1; + int k = N - 1; + while (j < k) { + int sum = nums[i] + nums[j] + nums[k]; + if (sum < 0) { + j++; + } + else if (sum > 0) { + k--; + } + else { + result.push_back({nums[i], nums[j], nums[k]}); + k--; + while (j < k && nums[k] == nums[k + 1]) { + k--; + } + j++; + while (j < k && nums[j] == nums[j - 1]) { + j++; + } + } + } + } + return result; + } +}; From 806bf412ac24e580fb60165c5509c198043a1112 Mon Sep 17 00:00:00 2001 From: Ayush Kushwaha <72184951+me-ayush@users.noreply.github.com> Date: Sun, 10 Oct 2021 11:01:29 +0530 Subject: [PATCH 057/147] Good Binary String --- good binary string.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 good binary string.py diff --git a/good binary string.py b/good binary string.py new file mode 100644 index 00000000..f05c96b2 --- /dev/null +++ b/good binary string.py @@ -0,0 +1,19 @@ + +def largestMagicalString(n): + cnt = 0 + p = 0 + res=[] + for i in range(len(n)): + if n[i] == '0': + cnt += 1 + else: + cnt -= 1 + if cnt == 0: + m = largestMagicalString(n[p+1:i]) + res.append("1"+m+"0") + p=p+1 + res.sort(reverse=True) + return "".join(res) + +n = input() +print(largestMagicalString(n)) From e7d84b39e7062392d44d0e9953bd4da9acaacc0f Mon Sep 17 00:00:00 2001 From: Ayush Kushwaha <72184951+me-ayush@users.noreply.github.com> Date: Sun, 10 Oct 2021 11:03:28 +0530 Subject: [PATCH 058/147] Sign-In Sign-Out --- sign in and sign out.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 sign in and sign out.py diff --git a/sign in and sign out.py b/sign in and sign out.py new file mode 100644 index 00000000..d0964137 --- /dev/null +++ b/sign in and sign out.py @@ -0,0 +1,20 @@ +n, maxSpan = map(int, list(input().split())) +d= {} +while n>0: + i, t, a = map(str, list(input().split())) + i = int(i) + t = int(t) + if i not in d: + d[i] = [t, 1] + else: + x = d[i][0] + x = abs(x-t) + d[i] = [x, d[i][1]+1] + n-=1 + +l = [] +for j,i in d.items(): + if i[1]==2 and i[0] Date: Sun, 10 Oct 2021 11:05:01 +0530 Subject: [PATCH 059/147] added a heapsort c++ file It's a heap sort sorting technique file coded in c++ language --- heap_short.cpp | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 heap_short.cpp diff --git a/heap_short.cpp b/heap_short.cpp new file mode 100644 index 00000000..38bdfe64 --- /dev/null +++ b/heap_short.cpp @@ -0,0 +1,63 @@ +// C++ program for implementation of Heap Sort +#include +using namespace std; + +void heapify(int arr[], int n, int i) +{ + int largest = i; // Initialize largest as root + int l = 2 * i + 1; // left = 2*i + 1 + int r = 2 * i + 2; // right = 2*i + 2 + + + if (l < n && arr[l] > arr[largest]) + largest = l; + + + if (r < n && arr[r] > arr[largest]) + largest = r; + + + if (largest != i) { + swap(arr[i], arr[largest]); + + + heapify(arr, n, largest); + } +} + +void heapSort(int arr[], int n) +{ + + for (int i = n / 2 - 1; i >= 0; i--) + heapify(arr, n, i); + + + for (int i = n - 1; i >= 0; i--) { + + swap(arr[0], arr[i]); + + + heapify(arr, i, 0); + } +} + + +void printArray(int arr[], int n) +{ + for (int i = 0; i < n; ++i) + cout << arr[i] << " "; + cout << "\n"; +} + + +int main() +{ + int arr[] = { 12, 11, 13, 5, 6, 7 }; + int n = sizeof(arr) / sizeof(arr[0]); + + heapSort(arr, n); + + cout << "Sorted array is \n"; + printArray(arr, n); +} + From 2e40166a17d509ab154147358b793a6ea524afd5 Mon Sep 17 00:00:00 2001 From: Jiyan Patil <76421551+jiyanpatil07@users.noreply.github.com> Date: Sun, 10 Oct 2021 14:17:21 +0530 Subject: [PATCH 060/147] Create construct-quad-tree.cpp --- construct-quad-tree.cpp | 54 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 construct-quad-tree.cpp diff --git a/construct-quad-tree.cpp b/construct-quad-tree.cpp new file mode 100644 index 00000000..c080431e --- /dev/null +++ b/construct-quad-tree.cpp @@ -0,0 +1,54 @@ +// Time: O(n) +// Space: O(h) + +/* +// Definition for a QuadTree node. +class Node { +public: + bool val; + bool isLeaf; + Node* topLeft; + Node* topRight; + Node* bottomLeft; + Node* bottomRight; + Node() {} + Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) { + val = _val; + isLeaf = _isLeaf; + topLeft = _topLeft; + topRight = _topRight; + bottomLeft = _bottomLeft; + bottomRight = _bottomRight; + } +}; +*/ +class Solution { +public: + Node* construct(vector>& grid) { + if (grid.empty()) { + return nullptr; + } + return dfs(grid, 0, 0, grid.size()); + } + +private: + Node* dfs(const vector>& grid, + int x, int y, int l) { + if (l == 1) { + return new Node(grid[x][y] == 1, true, nullptr, nullptr, nullptr, nullptr); + } + int half = l / 2; + auto topLeftNode = dfs(grid, x, y, half); + auto topRightNode = dfs(grid, x, y + half, half); + auto bottomLeftNode = dfs(grid, x + half, y, half); + auto bottomRightNode = dfs(grid, x + half, y + half, half); + if (topLeftNode->isLeaf && topRightNode->isLeaf && + bottomLeftNode->isLeaf && bottomRightNode->isLeaf && + topLeftNode->val == topRightNode->val && + topRightNode->val == bottomLeftNode->val && + bottomLeftNode->val == bottomRightNode->val) { + return new Node(topLeftNode->val, true, nullptr, nullptr, nullptr, nullptr); + } + return new Node(true, false, topLeftNode, topRightNode, bottomLeftNode, bottomRightNode); + } +}; From d0ee33a79834dacd6b2881dd9aa3c0b63d138b76 Mon Sep 17 00:00:00 2001 From: Tejas Nopany <61219536+tejasnopany@users.noreply.github.com> Date: Sun, 10 Oct 2021 16:42:47 +0530 Subject: [PATCH 061/147] Calculator.cpp Added a simple calculator C++ program --- Calculator.cpp | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Calculator.cpp diff --git a/Calculator.cpp b/Calculator.cpp new file mode 100644 index 00000000..6287cb57 --- /dev/null +++ b/Calculator.cpp @@ -0,0 +1,38 @@ +#include +using namespace std; + +int main() { + char op; + float num1, num2; + + cout << "Enter operator: +, -, *, /: "; + cin >> op; + + cout << "Enter two operands: "; + cin >> num1 >> num2; + + switch(op) { + case '+': + cout << num1 << " + " << num2 << " = " << num1 + num2; + break; + + case '-': + cout << num1 << " - " << num2 << " = " << num1 - num2; + break; + + case '*': + cout << num1 << " * " << num2 << " = " << num1 * num2; + break; + + case '/': + cout << num1 << " / " << num2 << " = " << num1 / num2; + break; + + default: + cout << "Error! operator is not correct"; + break; + } + + return 0; +} + From 004a7c402b10e1d9d5434c5d43db86a4662a2341 Mon Sep 17 00:00:00 2001 From: PaarthAgarwal <86092410+PaarthAgarwal@users.noreply.github.com> Date: Sun, 10 Oct 2021 17:10:41 +0530 Subject: [PATCH 062/147] Created a program to rotate a LinkedList --- rotateLinkedList.cpp | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 rotateLinkedList.cpp diff --git a/rotateLinkedList.cpp b/rotateLinkedList.cpp new file mode 100644 index 00000000..07a3c1f8 --- /dev/null +++ b/rotateLinkedList.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + ListNode* rotateRight(ListNode* head, int k) { + if(!head){ + return NULL; + } + ListNode* temp=head; + int count=0; + while(temp){ + temp=temp->next; + count++; + } + k=k%count; + if(k==0){ + return head; + } + k=count-k; + k--; + temp=head; + ListNode* prev; + while(k--){ + temp=temp->next; + } + prev=temp->next; + temp->next=NULL; + ListNode* q=prev; + while(prev->next){ + prev=prev->next; + } + prev->next=head; + return q; + } +}; From 846b2d18eed53b644b63c7b7d5b2ebdcc909478d Mon Sep 17 00:00:00 2001 From: saurav sharma Date: Sun, 10 Oct 2021 22:26:09 +0530 Subject: [PATCH 063/147] Added a heap sort program using C++ language. --- Heap sort.cpp | 60 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Heap sort.cpp diff --git a/Heap sort.cpp b/Heap sort.cpp new file mode 100644 index 00000000..a9f4336e --- /dev/null +++ b/Heap sort.cpp @@ -0,0 +1,60 @@ + +#include +using namespace std; + +void heapify(int arr[], int n, int i) +{ + int largest = i; + int l = 2 * i + 1; + int r = 2 * i + 2; + + + if (l < n && arr[l] > arr[largest]) + largest = l; + + + if (r < n && arr[r] > arr[largest]) + largest = r; + + + if (largest != i) { + swap(arr[i], arr[largest]); + + heapify(arr, n, largest); + } +} +void heapSort(int arr[], int n) +{ + + for (int i = n / 2 - 1; i >= 0; i--) + heapify(arr, n, i); + + + for (int i = n - 1; i >= 0; i--) { + + swap(arr[0], arr[i]); + + + heapify(arr, i, 0); + } +} + + +void printArray(int arr[], int n) +{ + for (int i = 0; i < n; ++i) + cout << arr[i] << " "; + cout << "\n"; +} + + +int main() +{ + int arr[] = { 12, 11, 13, 5, 6, 7 }; + int n = sizeof(arr) / sizeof(arr[0]); + + heapSort(arr, n); + + cout << "Sorted array is \n"; + printArray(arr, n); +} \ No newline at end of file From f73a87ee3f340d50926f7881bd83de3e30a99367 Mon Sep 17 00:00:00 2001 From: Utkarsh Kashyap <69443104+mrgentlemanus@users.noreply.github.com> Date: Mon, 11 Oct 2021 08:39:07 +0530 Subject: [PATCH 064/147] Added Heap Sort --- Heap_Sort.cpp | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Heap_Sort.cpp diff --git a/Heap_Sort.cpp b/Heap_Sort.cpp new file mode 100644 index 00000000..a017dae3 --- /dev/null +++ b/Heap_Sort.cpp @@ -0,0 +1,51 @@ +#include +using namespace std; + +void display(int *array, int size) { + for(int i = 1; i<=size; i++) + cout << array[i] << " "; + cout << endl; +} + +void heapify(int *array, int n) { + int i, par, l, r, node; + // create max heap + + for(i = 1; i<= n; i++) { + node = i; par = (int)node/2; + while(par >= 1) { + //if new node bigger than parent, then swap + if(array[par] < array[node]) + swap(array[par], array[node]); + node = par; + par = (int)node/2;//update parent to check + } + } +} + +void heapSort(int *array, int n) { + int i; + + for(i = n; i>= 1; i--) { + heapify(array, i);//heapify each time + swap(array[1], array[i]);//swap last element with first + } +} + +int main() { + int n; + cout << "Enter the number of elements: "; + cin >> n; + int arr[n+1]; //effective index starts from i = 1. + cout << "Enter elements:" << endl; + + for(int i = 1; i<=n; i++) { + cin >> arr[i]; + } + + cout << "Array before Sorting: "; + display(arr, n); + heapSort(arr, n); + cout << "Array after Sorting: "; + display(arr, n); +} \ No newline at end of file From da8d5d8cad604a8147cce872dbf9f068238538d8 Mon Sep 17 00:00:00 2001 From: PaarthAgarwal <86092410+PaarthAgarwal@users.noreply.github.com> Date: Mon, 11 Oct 2021 13:45:43 +0530 Subject: [PATCH 065/147] Create sort_a_stack_using_recursion.cpp --- sort_a_stack_using_recursion.cpp | 106 +++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 sort_a_stack_using_recursion.cpp diff --git a/sort_a_stack_using_recursion.cpp b/sort_a_stack_using_recursion.cpp new file mode 100644 index 00000000..9f5ebfcd --- /dev/null +++ b/sort_a_stack_using_recursion.cpp @@ -0,0 +1,106 @@ +// C++ program to sort a stack using recursion +#include +using namespace std; + +struct stack { + int data; + struct stack* next; +}; + +// initialize stack +void initStack(struct stack** s) { *s = NULL; } + +// check if stack is empty +int isEmpty(struct stack* s) +{ + if (s == NULL) + return 1; + return 0; +} + +// push an item to stack +void push(struct stack** s, int x) +{ + struct stack* p = (struct stack*)malloc(sizeof(*p)); + + if (p == NULL) { + printf(stderr, "Memory allocation failed.\n"); + return; + } + + p->data = x; + p->next = *s; + *s = p; +} + +// remove an item from stack +int pop(struct stack** s) +{ + int x; + struct stack* temp; + + x = (*s)->data; + temp = *s; + (*s) = (*s)->next; + free(temp); + + return x; +} + +// find top item +int top(struct stack* s) { return (s->data); } + +void sortedInsert(struct stack** s, int x) +{ + if (isEmpty(*s) or x > top(*s)) { + push(s, x); + return; + } + int temp = pop(s); + sortedInsert(s, x); + push(s, temp); +} + +// to sort stack +void sortStack(struct stack** s) +{ + if (!isEmpty(*s)) { + + int x = pop(s); + sortStack(s); + sortedInsert(s, x); + } +} + +// to print contents of stack +void printStack(struct stack* s) +{ + while (s) { + cout << s->data << " "; + s = s->next; + } + cout << "\n"; +} + +int main() +{ + struct stack* top; + + initStack(&top); + push(&top, 30); + push(&top, -5); + push(&top, 18); + push(&top, 14); + push(&top, -3); + + cout << "Stack elements before sorting:\n"; + printStack(top); + + sortStack(&top); + cout << "\n"; + + cout << "Stack elements after sorting:\n"; + printStack(top); + + return 0; +} From 014e23c329e81f1df8731ffc21ceb3ea7874fbca Mon Sep 17 00:00:00 2001 From: Saurabh Kumar singh Date: Mon, 11 Oct 2021 18:16:22 +0530 Subject: [PATCH 066/147] Create Vector_STL.cpp --- Vector_STL.cpp | 222 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 222 insertions(+) create mode 100644 Vector_STL.cpp diff --git a/Vector_STL.cpp b/Vector_STL.cpp new file mode 100644 index 00000000..249a351a --- /dev/null +++ b/Vector_STL.cpp @@ -0,0 +1,222 @@ +//Vector + +begin() – Returns an iterator pointing to the first element in the vector +end() – Returns an iterator pointing to the theoretical element that follows the last element in the vector +rbegin() – Returns a reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first element +rend() – Returns a reverse iterator pointing to the theoretical element preceding the first element in the vector (considered as reverse end) + +// C++ program to illustrate the iterators in vector +#include +#include + +using namespace std; + +int main() +{ + vector g1; + + for (int i = 1; i <= 5; i++) + g1.push_back(i); + + cout << "Output of begin and end: "; + for (auto i = g1.begin(); i != g1.end(); ++i) + cout << *i << " "; + + cout << "\nOutput of rbegin and rend: "; + for (auto ir = g1.rbegin(); ir != g1.rend(); ++ir) + cout << *ir << " "; + + return 0; +} +Output: +Output of begin and end: 1 2 3 4 5 +Output of rbegin and rend: 5 4 3 2 1 + +size() – Returns the number of elements in the vector. +max_size() – Returns the maximum number of elements that the vector can hold. +resize(n) – Resizes the container so that it contains ‘n’ elements. +empty() – Returns whether the container is empty. +shrink_to_fit() – Reduces the capacity of the container to fit its size and destroys all elements beyond the capacity. +reserve() – Requests that the vector capacity be at least enough to contain n elements. + +// C++ program to illustrate the capacity function in vector +#include +#include + +using namespace std; + +int main() +{ + vector g1; + + for (int i = 1; i <= 5; i++) + g1.push_back(i); + + cout << "Size : " << g1.size(); + cout << "\nMax_Size : " << g1.max_size(); + + // resizes the vector size to 4 + g1.resize(4); + + // prints the vector size after resize() + cout << "\nSize : " << g1.size(); + + // checks if the vector is empty or not + if (g1.empty() == false) + cout << "\nVector is not empty"; + else + cout << "\nVector is empty"; + + // Shrinks the vector + g1.shrink_to_fit(); + cout << "\nVector elements are: "; + for (auto it = g1.begin(); it != g1.end(); it++) + cout << *it << " "; + + return 0; +} +Output: +Size : 5 +Max_Size : 4611686018427387903 +Size : 4 +Vector is not empty +Vector elements are: 1 2 3 4 + +reference operator [g] – Returns a reference to the element at position ‘g’ in the vector +at(g) – Returns a reference to the element at position ‘g’ in the vector +front() – Returns a reference to the first element in the vector +back() – Returns a reference to the last element in the vector + +// C++ program to illustrate the element accesser in vector +#include +using namespace std; + +int main() +{ + vector g1; + + for (int i = 1; i <= 10; i++) + g1.push_back(i * 10); + + cout << "\nReference operator [g] : g1[2] = " << g1[2]; + + cout << "\nat : g1.at(4) = " << g1.at(4); + + cout << "\nfront() : g1.front() = " << g1.front(); + + cout << "\nback() : g1.back() = " << g1.back(); + + return 0; +} +Output: +Reference operator [g] : g1[2] = 30 +at : g1.at(4) = 50 +front() : g1.front() = 10 +back() : g1.back() = 100 + +assign() – It assigns new value to the vector elements by replacing old ones +push_back() – It push the elements into a vector from the back +pop_back() – It is used to pop or remove elements from a vector from the back. +insert() – It inserts new elements before the element at the specified position +erase() – It is used to remove elements from a container from the specified position or range. +swap() – It is used to swap the contents of one vector with another vector of same type. Sizes may differ. +clear() – It is used to remove all the elements of the vector container +emplace() – It extends the container by inserting new element at position +emplace_back() – It is used to insert a new element into the vector container, the new element is added to the end of the vector +. + + +// C++ program to illustrate the Modifiers in vector +#include +#include +using namespace std; + +int main() +{ + // Assign vector + vector v; + + // fill the array with 10 five times + v.assign(5, 10); + + cout << "The vector elements are: "; + for (int i = 0; i < v.size(); i++) + cout << v[i] << " "; + + // inserts 15 to the last position + v.push_back(15); + int n = v.size(); + cout << "\nThe last element is: " << v[n - 1]; + + // removes last element + v.pop_back(); + + // prints the vector + cout << "\nThe vector elements are: "; + for (int i = 0; i < v.size(); i++) + cout << v[i] << " "; + + // inserts 5 at the beginning + v.insert(v.begin(), 5); + + cout << "\nThe first element is: " << v[0]; + + // removes the first element + v.erase(v.begin()); + + cout << "\nThe first element is: " << v[0]; + + // inserts at the beginning + v.emplace(v.begin(), 5); + cout << "\nThe first element is: " << v[0]; + + // Inserts 20 at the end + v.emplace_back(20); + n = v.size(); + cout << "\nThe last element is: " << v[n - 1]; + + // erases the vector + v.clear(); + cout << "\nVector size after erase(): " << v.size(); + + // two vector to perform swap + vector v1, v2; + v1.push_back(1); + v1.push_back(2); + v2.push_back(3); + v2.push_back(4); + + cout << "\n\nVector 1: "; + for (int i = 0; i < v1.size(); i++) + cout << v1[i] << " "; + + cout << "\nVector 2: "; + for (int i = 0; i < v2.size(); i++) + cout << v2[i] << " "; + + // Swaps v1 and v2 + v1.swap(v2); + + cout << "\nAfter Swap \nVector 1: "; + for (int i = 0; i < v1.size(); i++) + cout << v1[i] << " "; + + cout << "\nVector 2: "; + for (int i = 0; i < v2.size(); i++) + cout << v2[i] << " "; +} +Output: +The vector elements are: 10 10 10 10 10 +The last element is: 15 +The vector elements are: 10 10 10 10 10 +The first element is: 5 +The first element is: 10 +The first element is: 5 +The last element is: 20 +Vector size after erase(): 0 + +Vector 1: 1 2 +Vector 2: 3 4 +After Swap +Vector 1: 3 4 +Vector 2: 1 2 From a1b5b0c2a0e025a0c093b4881b2b5b35ad210d87 Mon Sep 17 00:00:00 2001 From: Saurabh Kumar singh Date: Mon, 11 Oct 2021 18:25:37 +0530 Subject: [PATCH 067/147] Create KMP_search_algorithm.cpp --- KMP_search_algorithm.cpp | 82 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 KMP_search_algorithm.cpp diff --git a/KMP_search_algorithm.cpp b/KMP_search_algorithm.cpp new file mode 100644 index 00000000..f109d733 --- /dev/null +++ b/KMP_search_algorithm.cpp @@ -0,0 +1,82 @@ +// C++ program for implementation of KMP pattern searching algorithm +#include + +void computeLPSArray(char* pat, int M, int* lps); + +void KMPSearch(char* pat, char* txt) +{ + int M = strlen(pat); + int N = strlen(txt); + + // create lps[] that will hold the longest prefix suffix + // values for pattern + int lps[M]; + + computeLPSArray(pat, M, lps); + + int i = 0; // index for txt[] + int j = 0; // index for pat[] + while (i < N) { + if (pat[j] == txt[i]) { + j++; + i++; + } + + if (j == M) { + printf("Found pattern at index %d ", i - j); + j = lps[j - 1]; + } + + else if (i < N && pat[j] != txt[i]) { + if (j != 0) + j = lps[j - 1]; + else + i = i + 1; + } + } +} + +void computeLPSArray(char* pat, int M, int* lps) +{ + // length of the previous longest prefix suffix + int len = 0; + + lps[0] = 0; // lps[0] is always 0 + + // the loop calculates lps[i] for i = 1 to M-1 + int i = 1; + while (i < M) { + if (pat[i] == pat[len]) { + len++; + lps[i] = len; + i++; + } + else + { + // This is tricky. Consider the example. + // AAACAAAA and i = 7. The idea is similar + // to search step. + if (len != 0) { + len = lps[len - 1]; + + // Also, note that we do not increment i here + } + else // if (len == 0) + { + lps[i] = 0; + i++; + } + } + } +} + +int main() +{ + char txt[] = "ABABDABACDABABCABAB"; + char pat[] = "ABABCABAB"; + KMPSearch(pat, txt); + return 0; +} + +//Output: +//Found pattern at index 10 From e99b631ae4f18ac727113dff1826b1e634a7e33b Mon Sep 17 00:00:00 2001 From: melonwall <73346879+melonwall@users.noreply.github.com> Date: Tue, 12 Oct 2021 18:10:27 +0530 Subject: [PATCH 068/147] Create palindrome.cpp --- palindrome.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 palindrome.cpp diff --git a/palindrome.cpp b/palindrome.cpp new file mode 100644 index 00000000..df77f543 --- /dev/null +++ b/palindrome.cpp @@ -0,0 +1,19 @@ +#include +using namespace std; + +int main() { + // your code goes here + + int n,sum=0; + cin>>n; + int temp=n; + while(n>0){ + sum=(sum*10)+n%10; + n=n/10; + } + if (sum==temp) + cout< Date: Tue, 12 Oct 2021 18:12:01 +0530 Subject: [PATCH 069/147] Create insertion_sort.cpp --- insertion_sort.cpp | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 insertion_sort.cpp diff --git a/insertion_sort.cpp b/insertion_sort.cpp new file mode 100644 index 00000000..1a2c6128 --- /dev/null +++ b/insertion_sort.cpp @@ -0,0 +1,40 @@ +#include +using namespace std; + +void inSort(int *arr, int n) +{ + int key,j; + for (int i=1;i=0 && arr[j]>key) + { + arr[j+1]=arr[j]; + j=j-1; + } + arr[j+1]=key; + + } + + for(int i=0;i>n; + for(int i=0;i>arr[i]; + + inSort(arr,n); + + + return 0; +} From 71382d2c5938fd1ad00b2dc0e7b3e3b2b9f2c15f Mon Sep 17 00:00:00 2001 From: melonwall <73346879+melonwall@users.noreply.github.com> Date: Tue, 12 Oct 2021 18:13:49 +0530 Subject: [PATCH 070/147] Create reverse_number.cpp --- reverse_number.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 reverse_number.cpp diff --git a/reverse_number.cpp b/reverse_number.cpp new file mode 100644 index 00000000..51ea4f48 --- /dev/null +++ b/reverse_number.cpp @@ -0,0 +1,18 @@ +#include +using namespace std; + + +void reverseNum(int n){ + while(n>0){ + cout<>n; + reverseNum(n); + return 0; +} From 07cf8ead59ec1870b2210386cba808e4f90c10a4 Mon Sep 17 00:00:00 2001 From: Jyotsana Singh <73690777+jyotsana279@users.noreply.github.com> Date: Tue, 12 Oct 2021 20:48:34 +0530 Subject: [PATCH 071/147] Create Hangman game.cpp --- Hangman game.cpp | 131 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 131 insertions(+) create mode 100644 Hangman game.cpp diff --git a/Hangman game.cpp b/Hangman game.cpp new file mode 100644 index 00000000..ab68345f --- /dev/null +++ b/Hangman game.cpp @@ -0,0 +1,131 @@ +#include +#include +#include +#include +using namespace std; + +int NUM_TRY=3; +int checkGuess (char, string, string&); +void main_menu(); +string message = "Play!"; + + +int main(int argc, char *argv[]) +{ + string name; + char letter; + string month; + + + string months[] = + { + "january", + "february", + "march", + "april", + "may", + "june", + "july", + "august", + "september", + "october", + "november", + "december" + }; + + srand(time(NULL)); + int n=rand()% 12; + month=months[n]; + + + string hide_m(month.length(),'X'); + + + + + while (NUM_TRY!=0) + { + main_menu(); + cout << "\n\n\t\t\t\t" << hide_m; + cout << "\n\n\t\t\t\tGuess a letter: "; + cin >> letter; + + if (checkGuess(letter, month, hide_m)==0) + { + message = "Incorrect letter."; + NUM_TRY = NUM_TRY - 1; + } + else + { + message = "NICE! You guess a letter"; + } + + + + if (month==hide_m) + { + message = "Congratulations! You got it!"; + main_menu(); + cout << "\n\t\t\t\tThe month is : " << month << endl; + break; + } + } + if(NUM_TRY == 0) + { + message = "NOOOOOOO!...you've been hanged."; + main_menu(); + cout << "\n\t\t\t\tThe month was : " << month << endl; + } + cin.ignore(); + cin.get(); + return 0; +} + + +int checkGuess (char guess, string secretmonth, string &guessmonth) +{ + int i; + int matches=0; + int len=secretmonth.length(); + for (i = 0; i< len; i++) + { + + if (guess == guessmonth[i]) + return 0; + + if (guess == secretmonth[i]) + { + guessmonth[i] = guess; + matches++; + } + } + return matches; +} + +void main_menu() +{ + system("color 05"); + system("cls"); + cout<<"\t\t\t\t*\t*"; + + cout<<"\t\t\t\t**\t**"; + cout<<"\t\t\t\t***\t***"; + cout<<"\t\t\t\t****\t****"; + cout<<"\t\t\t\t*****\t*****"; + cout<<"\t\t\t\t******\t******"; + cout<<"\t\t\t\t*******\t*******"; + cout<<"\t\t\t\t*******\t*******"; + cout<<"\t\t\t\t******\t******"; + cout<<"\t\t\t\t*****\t*****"; + cout<<"\t\t\t\t****\t****"; + cout<<"\t\t\t\t***\t***"; + cout<<"\t\t\t\t**\t**"; + cout<<"\t\t\t\t*\t*"; + + cout<<"\t\t@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"; + cout<<"\n\t\t\t\tHangman Game!"; + cout << "\n\t\tYou have " << NUM_TRY << " tries to try and guess the month."; + cout<<"\n\n\t\t\t\t"+message; + cout<<"\n\t\t@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n"; + +} From 9bb80ae93486e8748ae1271d255b5eda821f9cdd Mon Sep 17 00:00:00 2001 From: gandhimayank-web <92392011+gandhimayank-web@users.noreply.github.com> Date: Tue, 12 Oct 2021 22:31:52 +0530 Subject: [PATCH 072/147] Create Modern --- Modern | 75 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 Modern diff --git a/Modern b/Modern new file mode 100644 index 00000000..71ba3964 --- /dev/null +++ b/Modern @@ -0,0 +1,75 @@ +Hi + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Bye From eec36a0856e69b149ea14c8595e7e1a3aa9848bf Mon Sep 17 00:00:00 2001 From: Ayushi <92251474+Ayushi912@users.noreply.github.com> Date: Tue, 12 Oct 2021 22:43:56 +0530 Subject: [PATCH 073/147] Create rainwatertrapping.cpp --- rainwatertrapping.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 rainwatertrapping.cpp diff --git a/rainwatertrapping.cpp b/rainwatertrapping.cpp new file mode 100644 index 00000000..0fa63d11 --- /dev/null +++ b/rainwatertrapping.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int trap(vector& height) { + int n=height.size(); + int left=0,right=n-1; + int res=0; + int maxleft=0,maxright=0; + while(left<=right){ + if(height[left]<=height[right]){ + if(height[left]>=maxleft) + maxleft=height[left]; + else + res+=maxleft-height[left]; + left++; + }else{ + if(height[right]>=maxright) + maxright=height[right]; + else + res+=maxright-height[right]; + right--; + } + } + return res; + } +}; From 1563b4fc79b594140cc5a5a40115daacc4551bd6 Mon Sep 17 00:00:00 2001 From: Ayushi <92251474+Ayushi912@users.noreply.github.com> Date: Tue, 12 Oct 2021 22:46:48 +0530 Subject: [PATCH 074/147] Create sudokusolver.cpp --- sudokusolver.cpp | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 sudokusolver.cpp diff --git a/sudokusolver.cpp b/sudokusolver.cpp new file mode 100644 index 00000000..9273219e --- /dev/null +++ b/sudokusolver.cpp @@ -0,0 +1,42 @@ +class Solution { +public: + void solveSudoku(vector>& board) { + solve(board); + } + + bool solve(vector>& board){ + for(int i = 0; i < board.size(); i++){ + for(int j = 0; j < board[0].size(); j++){ + if(board[i][j] == '.'){ + for(char c = '1'; c <= '9'; c++){ + if(isValid(board, i, j, c)){ + board[i][j] = c; + + if(solve(board)) + return true; + else + board[i][j] = '.'; + } + } + + return false; + } + } + } + return true; + } + + bool isValid(vector>& board, int row, int col, char c){ + for(int i = 0; i < 9; i++) { + if(board[i][col] == c) + return false; + + if(board[row][i] == c) + return false; + + if(board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c) + return false; + } + return true; + } +}; From 4105677936357b5fcc22f62d64ea4900fc3f136c Mon Sep 17 00:00:00 2001 From: Akhil sv <73875875+Akhilsv@users.noreply.github.com> Date: Wed, 13 Oct 2021 00:45:55 +0530 Subject: [PATCH 075/147] Create quotient_and_remainder --- quotient_and_remainder | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 quotient_and_remainder diff --git a/quotient_and_remainder b/quotient_and_remainder new file mode 100644 index 00000000..628d6fac --- /dev/null +++ b/quotient_and_remainder @@ -0,0 +1,21 @@ +#include +using namespace std; + +int main() +{ + int divisor, dividend, quotient, remainder; + + cout << "Enter dividend: "; + cin >> dividend; + + cout << "Enter divisor: "; + cin >> divisor; + + quotient = dividend / divisor; + remainder = dividend % divisor; + + cout << "Quotient = " << quotient << endl; + cout << "Remainder = " << remainder; + + return 0; +} From c9f41c67c6e62b65117ca4bcebcd25aacd228f6e Mon Sep 17 00:00:00 2001 From: Alan Biju <67945306+Alan-Biju@users.noreply.github.com> Date: Wed, 13 Oct 2021 00:46:22 +0530 Subject: [PATCH 076/147] reverse the string code --- reverse.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 reverse.cpp diff --git a/reverse.cpp b/reverse.cpp new file mode 100644 index 00000000..4640b014 --- /dev/null +++ b/reverse.cpp @@ -0,0 +1,29 @@ +#include +using namespace std; + +//recursive function +void reverse(string &str, int i){ + //Base condition - when index exceeds string length + if(i == str.length()) + return; + + //extract character + char ch = str[i]; + //recusively call for next character + reverse(str, i+1); + //reassign in reverse order + str[str.length()-i-1] = ch; +} + +int main() +{ + //Input string + string str = "Pencil Programmer"; + + //start recirsive funtion from first index + reverse(str, 0); + + //output the string + cout << str; + return 0; +} From 2ac7389e2178ea0936c9435efa84553ad00875e4 Mon Sep 17 00:00:00 2001 From: Akhil sv <73875875+Akhilsv@users.noreply.github.com> Date: Wed, 13 Oct 2021 00:46:30 +0530 Subject: [PATCH 077/147] Rename Quotient_and_Remainder to Quotient_and_Remainder.cpp --- Quotient_and_Remainder => Quotient_and_Remainder.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Quotient_and_Remainder => Quotient_and_Remainder.cpp (100%) diff --git a/Quotient_and_Remainder b/Quotient_and_Remainder.cpp similarity index 100% rename from Quotient_and_Remainder rename to Quotient_and_Remainder.cpp From 9d552ae50571003ee3ae6704bcb4ed08618d41c8 Mon Sep 17 00:00:00 2001 From: Ujjwal Dhakal <68050149+ujjwalnp@users.noreply.github.com> Date: Wed, 13 Oct 2021 21:56:37 +0545 Subject: [PATCH 078/147] Create MatrixAddition.java I created this Java program to add two matrix of any size of m*n. I created this pull request for the hacktoberfest challenge. --- MatrixAddition.java | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 MatrixAddition.java diff --git a/MatrixAddition.java b/MatrixAddition.java new file mode 100644 index 00000000..03bb6bdb --- /dev/null +++ b/MatrixAddition.java @@ -0,0 +1,43 @@ +package arrays; +import java.util.Scanner; +public class MatrixAddition { + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.println("Welcome ! to addition program of matrix of same dimensions"); + System.out.print("Enter matrix type : "); + int rows = sc.nextInt(), columns = sc.nextInt(); + + int matrixA[][] = new int [rows][columns]; + int matrixB[][] = new int [rows][columns]; + + System.out.println("Enter matrix A"); + for (int i=0; i Date: Wed, 13 Oct 2021 21:58:24 +0545 Subject: [PATCH 079/147] Create BubbleSort.java I created the simple program of bubble sort algorithm. I created this pull request for Hactoberfest challenge. --- BubbleSort.java | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 BubbleSort.java diff --git a/BubbleSort.java b/BubbleSort.java new file mode 100644 index 00000000..d42d48f6 --- /dev/null +++ b/BubbleSort.java @@ -0,0 +1,32 @@ +package arrays; + +public class BubbleSort { + + public static void main(String[] args) { + int a[] = {3, 1, -2, 7, 4, 0}; + int n = a.length; + + for (int i=0; i Date: Wed, 13 Oct 2021 22:02:00 +0545 Subject: [PATCH 080/147] Create YearMonthDay.java This program takes input for user in days like : 150 days and gives and output in the formatted terms like : 0 years 5 months 0 days I created this program for Hacktoberfest-2021 challenge. Hope you like my work ! --- YearMonthDay.java | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 YearMonthDay.java diff --git a/YearMonthDay.java b/YearMonthDay.java new file mode 100644 index 00000000..42c96381 --- /dev/null +++ b/YearMonthDay.java @@ -0,0 +1,23 @@ +package clz; +import java.util.Scanner; +public class YearMonthDay { + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.print("Enter Days : "); + int n = sc.nextInt(); + + int year = n/365; + System.out.print("Your result is : "+year+" years "); + int year_rem = n%365; + + int month = year_rem/30; + System.out.print(month+" months "); + int month_rem = year_rem%30; + + System.out.println(month_rem+" days."); + + sc.close(); + } + +} From 52747afcfe934772526feeb36a8d661d7784c8d6 Mon Sep 17 00:00:00 2001 From: Gavindu Chirandi Alwis <76090683+Gavindu99-A@users.noreply.github.com> Date: Wed, 13 Oct 2021 11:18:58 -0700 Subject: [PATCH 081/147] Update Recursive factorials --- Recursive factorials | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/Recursive factorials b/Recursive factorials index ce502222..3249fc58 100644 --- a/Recursive factorials +++ b/Recursive factorials @@ -1,23 +1,24 @@ -// C++ code to implement factorial -#include +/#include using namespace std; -// Factorial function -int f(int n) +int factorial(int n); + +int main() { - // Stop condition - if (n == 0 || n == 1) - return 1; + int n; + + cout << "Enter a positive integer: "; + cin >> n; - // Recursive condition - else - return n * f(n - 1); + cout << "Factorial of " << n << " = " << factorial(n); + + return 0; } -// Driver code -int main() +int factorial(int n) { - int n = 5; - cout<<"factorial of "< 1) + return n * factorial(n - 1); + else + return 1; } From 205320d6241cd3d582235943e1ca47894cc3651e Mon Sep 17 00:00:00 2001 From: Gavindu Chirandi Alwis <76090683+Gavindu99-A@users.noreply.github.com> Date: Wed, 13 Oct 2021 12:17:19 -0700 Subject: [PATCH 082/147] Update Prime_factors.cpp --- Prime_factors.cpp | 71 ++++++++++++++++++++--------------------------- 1 file changed, 30 insertions(+), 41 deletions(-) diff --git a/Prime_factors.cpp b/Prime_factors.cpp index 8caa9d9c..61bdd808 100644 --- a/Prime_factors.cpp +++ b/Prime_factors.cpp @@ -1,46 +1,35 @@ -// C++ program to print all prime factors -#include -using namespace std; - -# include - - -// A function to print all prime -// factors of a given number n -void primeFactors(int n) -{ - // Print the number of 2s that divide n - while (n % 2 == 0) - { - cout << 2 << " "; - n = n/2; - } +#include - // n must be odd at this point. So we can skip - // one element (Note i = i +2) - for (int i = 3; i <= sqrt(n); i = i + 2) - { - // While i divides n, print i and divide n - while (n % i == 0) - { - cout << i << " "; - n = n/i; - } - } - - // This condition is to handle the case when n - // is a prime number greater than 2 - if (n > 2) - cout << n << " "; -} +using namespace std; -/* Driver code */ int main() { - int n; - cout<<"Enter the value of number:\n"; - cin>>n; - primeFactors(n); - return 0; + int number, i = 1, j, count; + + cout << "\nPlease Enter the Number to find the Prime Factors = "; + cin >> number; + + while (i <= number) + { + count = 0; + if(number % i == 0) + { + j = 1; + while(j <= i) + { + if(i % j == 0) + { + count++; + } + j++; + } + if(count == 2) + { + cout << i << " is a Prime Factor\n"; + } + } + i++; + } + + return 0; } - From 7fdd474f09ea20bc4200334d895cc4cc582b80c0 Mon Sep 17 00:00:00 2001 From: Gavindu Chirandi Alwis <76090683+Gavindu99-A@users.noreply.github.com> Date: Wed, 13 Oct 2021 12:23:31 -0700 Subject: [PATCH 083/147] Update Bubble sorting --- Bubble sorting | 51 ++++++++++++++++++++++++++++---------------------- 1 file changed, 29 insertions(+), 22 deletions(-) diff --git a/Bubble sorting b/Bubble sorting index 89e04123..483dc185 100644 --- a/Bubble sorting +++ b/Bubble sorting @@ -1,22 +1,29 @@ -def bubbleSort(a): - - - for i in range(len(a)): - - - for j in range(0, len(a) - i - 1): - - - if a[j] > a[j + 1]: - - temp = a[j] - a[j] = a[j+1] - a[j+1] = temp - - -data = [-44, 45, 0, 85, -30] - -bubbleSort(data) - -print('Sorted Array in Ascending Order:') -print(data) +#include +using namespace std; +int main () +{ + int i, j,temp,pass=0; + int a[10] = {10,2,0,14,43,25,18,1,5,45}; + cout <<"Input list ...\n"; + for(i = 0; i<10; i++) { + cout < Date: Wed, 13 Oct 2021 12:30:51 -0700 Subject: [PATCH 084/147] Update fibonacciDP.cpp --- fibonacciDP.cpp | 54 ++++++++++++++++--------------------------------- 1 file changed, 17 insertions(+), 37 deletions(-) diff --git a/fibonacciDP.cpp b/fibonacciDP.cpp index 3a1780f5..cb212a0c 100644 --- a/fibonacciDP.cpp +++ b/fibonacciDP.cpp @@ -1,40 +1,20 @@ -// C++ Program to find n'th fibonacci Number in -// with O(Log n) arithmetic operations -#include +#include using namespace std; - -const int MAX = 1000; - -// Create an array for memoization -int f[MAX] = {0}; - -// Returns n'th fibonacci number using table f[] -int fib(int n) -{ - // Base cases - if (n == 0) - return 0; - if (n == 1 || n == 2) - return (f[n] = 1); - - // If fib(n) is already computed - if (f[n]) - return f[n]; - - int k = (n & 1)? (n+1)/2 : n/2; - - // Applying above formula [Note value n&1 is 1 - // if n is odd, else 0. - f[n] = (n & 1)? (fib(k)*fib(k) + fib(k-1)*fib(k-1)) - : (2*fib(k-1) + fib(k))*fib(k); - - return f[n]; +int fib(int x) { + if((x==1)||(x==0)) { + return(x); + }else { + return(fib(x-1)+fib(x-2)); + } } - -/* Driver program to test above function */ -int main() -{ - int n = 9; - printf("%d ", fib(n)); - return 0; +int main() { + int x , i=0; + cout << "Enter the number of terms of series : "; + cin >> x; + cout << "\nFibonnaci Series : "; + while(i < x) { + cout << " " << fib(i); + i++; + } + return 0; } From d2ede7ea2b992b03c2e080e5d4fbdda020add880 Mon Sep 17 00:00:00 2001 From: Harekrushna Date: Thu, 14 Oct 2021 11:09:12 +0530 Subject: [PATCH 085/147] Create Tree from Postorder and Inorder --- Tree from Postorder and Inorder | 122 ++++++++++++++++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 Tree from Postorder and Inorder diff --git a/Tree from Postorder and Inorder b/Tree from Postorder and Inorder new file mode 100644 index 00000000..c7c2bb54 --- /dev/null +++ b/Tree from Postorder and Inorder @@ -0,0 +1,122 @@ +Given inorder and postorder traversals of a Binary Tree in the arrays in[] and post[] respectively. The task is to construct the binary tree from these traversals. + + + +Example 1: + +Input: +N = 8 +in[] = 4 8 2 5 1 6 3 7 +post[] =8 4 5 2 6 7 3 1 +Output: 1 2 4 8 5 3 6 7 +Explanation: For the given postorder and +inorder traversal of tree the resultant +binary tree will be + 1 + / \ + 2 3 + / \ / \ + 4 5 6 7 + \ + 8 + + + +Example 2: + +Input: +N = 5 +in[] = 9 5 2 3 4 +post[] = 5 9 3 4 2 +Output: 2 9 5 4 3 +Explanation: +the resultant binary tree will be + 2 + / \ + 9 4 + \ / + 5 3 + + + +Your Task: +You do not need to read input or print anything. Complete the function buildTree() which takes the inorder, postorder traversals and the number of nodes in the tree as input parameters +and returns the root node of the newly constructed Binary Tree. The generated output contains the preorder traversal of the constructed tree. + + +Expected Time Complexity: O(N2) +Expected Auxiliary Space: O(N) + + + +Constraints: +1 <= N <= 103 +1 <= in[i], post[i] <= 10^3 + +Solution : + +/* Tree node structure + +struct Node +{ + int data; + struct Node* left; + struct Node* right; + + Node(int x){ + data = x; + left = right = NULL; + } +};*/ + +//Function to return a tree created from postorder and inoreder traversals. + +Node* newNode(int data); + +Node* buildUtil(int in[], int post[], int inStrt, + int inEnd, int* pIndex, unordered_map& mp) +{ + // Base case + if (inStrt > inEnd) + return NULL; + + /* Pick current node from Postorder traversal + using postIndex and decrement postIndex */ + int curr = post[*pIndex]; + Node* node = newNode(curr); + (*pIndex)--; + + /* If this node has no children then return */ + if (inStrt == inEnd) + return node; + + /* Else find the index of this node in Inorder + traversal */ + int iIndex = mp[curr]; + + /* Using index in Inorder traversal, construct + left and right subtress */ + node->right = buildUtil(in, post, iIndex + 1, + inEnd, pIndex, mp); + node->left = buildUtil(in, post, inStrt, + iIndex - 1, pIndex, mp); + + return node; +} + +Node *buildTree(int in[], int post[], int len) { + unordered_map mp; + for (int i = 0; i < len; i++) + mp[in[i]] = i; + + int index = len - 1; // Index in postorder + return buildUtil(in, post, 0, len - 1, &index, mp); +} + +Node* newNode(int data) +{ + Node* node = (Node*)malloc(sizeof(Node)); + node->data = data; + node->left = node->right = NULL; + return (node); +} From 21d327c8a72e26c17de1bad94d0718874735c845 Mon Sep 17 00:00:00 2001 From: Anay Gawate <70628601+anay2310@users.noreply.github.com> Date: Thu, 14 Oct 2021 16:37:15 +0530 Subject: [PATCH 086/147] Updated READ.md to make more sense of it --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 4c46033c..7a416166 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,4 @@ # Competitive-Programming-Algos -C++ implementation of algorithms learned and used while competitive programming +This repository is all about: +Implementation of C++ algorithms learned and used while doing competitive programming. +You can freely add your implementations or just make the earlier ones better From 475de228066d520fb7419f5c3e31dd5899683404 Mon Sep 17 00:00:00 2001 From: Shrinanda Maity <71083483+ShrinandaMaity@users.noreply.github.com> Date: Thu, 14 Oct 2021 19:26:16 +0530 Subject: [PATCH 087/147] Map app using js --- Map-using-JavaScript-main.zip | Bin 0 -> 3174 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Map-using-JavaScript-main.zip diff --git a/Map-using-JavaScript-main.zip b/Map-using-JavaScript-main.zip new file mode 100644 index 0000000000000000000000000000000000000000..ebb1b0ad7a4055d3cf911c08fd772fd2226749af GIT binary patch literal 3174 zcma);cUV(P8i!A4hF+BD(nJ9Z0s@8(A|+A-NGQ^jgdn|1C`u0kp-2^^cLJfq4J8zj zjvyc?0*QqpqEr<{M9Sjz?sYBK-8s+9bN+hgn{(zj^BU+-(=Y&E8a*D4`19qjfeWAq z;7E5-FHZ+oJ5g<VkA|J#B163xKdCc1VNo0ECBje2_iBmoD&IfFVpp z9S#$7LH|t>;Q!Th|KWrGERgCGUSyRD0AADmFFwl4!5J-Pb!8SO72AB$6MznH(A#-Yt!rq8n8 zmkD2-4F#tb>f7``^wpsbstxV8kbJySbLxx*#M6`3bWzO;P>}!Cyvu!P)xQYd( zb=Szvh3}@L<8z<`nag}`C(>*SV2AtOD3}0x4S_4m%e}3=GL76l8AYQ0e64=^7U$(a z2!|d)HZ9~tB4r~S(JW$}-drSb+Bf}H#6p53`q~n^P`ZecX#l9e9!qhqMyPo^HP8T#B_&6*GH)vxV@7KpT=VG}V zESe#%&4ya_8xLzQxXP>W1nancZah%h^bFHF`iSCIRp}(I?atu9#&)OcnZhZ=xq3hG z>Ep>uWf@_erTX13bMwj#(=S%OU>&qLc+F6Gi50YHHB5aAJbg99oO-PEg|TI=!q9s* zp@&maP?ep8=|TH!xy2CHIsM9UT)`!Q{-AK*6xZiUlr4x(5OH;feKTgAzK3|Ygsj|zICeg zC><;Iq}grD+6bd}jFyopW(iuHu*tbL{g1#SNk2`J@YxzE8eG~+c8GWHPMvHfW$}ZD z=b;GFa)c{+sqH}b%H&cTv!_g51Sx1aN|`+18hz+;h4kRI{|bhBroodccs{VrX}9jx z^yg2HU83d*e%GID)lTkydjIHf)1oV7#m7QqH!cg|W9hQx(!#v~B26wr(mrFir z%Z%FDXuRfdI%7tjmrrJR&Hs~EbAX@U=j$%T>weE!BIb9Tl-*coYy4haCL?^FqPB|y zUKuz1tEtYyKXN3(V?lrWL3Z1va0JJp5tRMqCQQE}!zChO95VZ+L%Vm}wP}`OX_-S| z^tS9-`;3>3nZ>BL8-|Tuw16C~hpMtIO42EESLr+XPpT`zv=Q_w2x;c*$1j4Z#U~tF zJ7t7}adDGe{Evz}vH^BeyD4TBbi&Jj^vb$$)WfVQ>I^4EDJ~i4YHX*e}mzqXsGcWHvkDj!i%0<8@j7Q>_MoF<6 zocTHbT#3F{SC;z0DRAbzBhGM=>D+J}XPuTXiHjb(f!DyJE~IPJcQ^+CH!(Mk9}!oZ zo>oKNJJMwlsn&oD{5C zw%*R7LlUtc!-dkM;BDY03xb3S&EO;Z%Q><{g>hlg4ifW%59unL4QuG8_HnNq-L7ta z0E*nH24B71haNFH#hKF2KSmRu=Sy3d6P>5c(U!M?qv5WzSy80BZE@nREfx{jl7~Ez zMpbg@hR}y|-ooee;e|Bl&d4w#TVy#ySM95gPfQb*nMN>^8Bes-$gxp%UTt=*f+3)j zJV6i?4Uwnr&r>Zpz9upaMyBuZnf2TccoR?0dxmB+s`K6pb`klkv6jhhLs7bUF4F{5 zQ~uGqS|V&cu~BHo_Vp1lh#*8zssV~&xvoa*K|Ezw$hg#<>^o#U>64OeKFpBNb7{V0)!rhMR^eUl18ZH zZc>!Ojww0lUQpK#==-xRl(+1HI|u;6zyNUc|2W$mzd6C6v6WjW|ABz|HY^4nj1N;< zT~uBoy`~oErH@_#SiupY0izhxPJS+2 z_>FxVf`O9PIYcdZPAd&{Qk1BP^F=mQG z`zSBuKfIaZIFO9XA4v~ ztK?AT?6XSTpZDD)SkCv8rW+UT=ajfAIogyyeio|KY@F1lbO$id0qxn_KMUtq_hkD^ zL4W0gKk4W9z#j$l3u$j_>@}6W{?EXlb@W@QzgEvL%&+9U-;#e8(I3e_-p$|0Wa{75 z{EM6VNA!=;_=c|E3(G%$j<4wd3W|Xa?VfT20PWsG+FQ2U-akA6prys3Xr!#IjqDk; gjRaIuRz^--?u^708)+mI1r?WqO327bL2Xh02HSK_F#rGn literal 0 HcmV?d00001 From f52881bff3f987df1a1e6f6b65bed4dbd3d5a4d6 Mon Sep 17 00:00:00 2001 From: saurav sharma Date: Thu, 14 Oct 2021 23:40:29 +0530 Subject: [PATCH 088/147] added a palindrom number program using C++ language --- palindrom.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 palindrom.cpp diff --git a/palindrom.cpp b/palindrom.cpp new file mode 100644 index 00000000..9d061683 --- /dev/null +++ b/palindrom.cpp @@ -0,0 +1,20 @@ +#include +using namespace std; +int main() +{ + int n,r,sum=0,temp; + cout<<"Enter the Number="; + cin>>n; + temp=n; + while(n>0) +{ + r=n%10; + sum=(sum*10)+r; + n=n/10; +} +if(temp==sum) +cout<<"Number is Palindrome."; +else +cout<<"Number is not Palindrome."; + return 0; +} \ No newline at end of file From d6b12477019a90de5372a6a40a68fea6fe74873f Mon Sep 17 00:00:00 2001 From: saurav sharma Date: Thu, 14 Oct 2021 23:44:40 +0530 Subject: [PATCH 089/147] Added a Armstrong Number program using C++ language. --- Armstrong Number.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Armstrong Number.cpp diff --git a/Armstrong Number.cpp b/Armstrong Number.cpp new file mode 100644 index 00000000..9426ee80 --- /dev/null +++ b/Armstrong Number.cpp @@ -0,0 +1,20 @@ +#include +using namespace std; +int main() +{ +int n,r,sum=0,temp; +cout<<"Enter the Number= "; +cin>>n; +temp=n; +while(n>0) +{ +r=n%10; +sum=sum+(r*r*r); +n=n/10; +} +if(temp==sum) +cout<<"Armstrong Number."< Date: Fri, 15 Oct 2021 11:32:48 +0530 Subject: [PATCH 090/147] prints all subsequence of entered string --- string subsequence | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 string subsequence diff --git a/string subsequence b/string subsequence new file mode 100644 index 00000000..5708242c --- /dev/null +++ b/string subsequence @@ -0,0 +1,34 @@ +#include +#define fst ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); +#define ll long long int +#include + +using namespace std; + +int subq(string input,string output[]){ + if(input.empty()) { + output[0]=""; + return 1; + } + string smallstring = input.substr(1); + int smallOutputsize = subq(smallstring,output); + for (int i = 0; i < smallOutputsize; i++) + { + output[i+smallOutputsize]=input[0]+output[i]; + } + return 2*smallOutputsize; +} + +int main(){ + string input; + cin>>input; + string* output = new string[1000]; + int count=subq(input,output); + for (int i = 0; i < count; i++) + { + cout< Date: Fri, 15 Oct 2021 12:04:50 +0530 Subject: [PATCH 091/147] Added a linear search program using C++ language --- Linear_search.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Linear_search.cpp diff --git a/Linear_search.cpp b/Linear_search.cpp new file mode 100644 index 00000000..c70a3393 --- /dev/null +++ b/Linear_search.cpp @@ -0,0 +1,22 @@ +#include +using namespace std; +int main() +{ + int arr[10], i, num, index; + cout<<"Enter 10 Numbers: "; + for(i=0; i<10; i++) + cin>>arr[i]; + cout<<"\nEnter a Number to Search: "; + cin>>num; + for(i=0; i<10; i++) + { + if(arr[i]==num) + { + index = i; + break; + } + } + cout<<"\nFound at Index No."< Date: Fri, 15 Oct 2021 14:45:22 +0530 Subject: [PATCH 092/147] Updated AnagramOfStrings.java to show how it works Defined what is Anagram & how program works --- AnagramOfStrings.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/AnagramOfStrings.java b/AnagramOfStrings.java index b3d34767..6875c13b 100644 --- a/AnagramOfStrings.java +++ b/AnagramOfStrings.java @@ -1,5 +1,9 @@ # This is the code for finding anagram of the string in java +//Anagram : a word or phrase that is made by arranging the letters of another word or phrase in a different order +//Example: "Worth" is an anagram of ‘throw’. +//This java anagram program compares the letters of both words/strings entered and then shows +//wheather they are anagram of each other or not import java.util.Scanner; public class AnagramOfStrings { @@ -26,8 +30,8 @@ public static void main(String[] args) { }if (!isAnagram) break; } } - if (isAnagram) System.out.println("anagram"); - else System.out.println("not anagram"); + if (isAnagram) System.out.println("an anagram"); + else System.out.println("not an anagram"); } } From 20b2d6876f754f0b6bb023b37ed77c34a620d696 Mon Sep 17 00:00:00 2001 From: Anay Gawate <70628601+anay2310@users.noreply.github.com> Date: Fri, 15 Oct 2021 14:51:03 +0530 Subject: [PATCH 093/147] Defined what is bubble sort in java --- BubbleSort.java | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/BubbleSort.java b/BubbleSort.java index d42d48f6..68f5c9ee 100644 --- a/BubbleSort.java +++ b/BubbleSort.java @@ -1,3 +1,14 @@ + + +//WHAT IS BUBBLE SORT: +//Bubble Sort is one of the simplest sorting techniques in Java to sort the array elements. +//The swapping of elements continues until the array is sorted and no more swapping is required. +//We can also sort the elements in the descending order in which the smallest element goes at the end of the array in each iteration. +//THIS EXPLAINATION IS PROVIDED TO HELP BEGGINNER'S UNDERSTAND THE CODE + + + + package arrays; public class BubbleSort { From b09ca84de798237a6a785ac21059ec315370c5f2 Mon Sep 17 00:00:00 2001 From: Anay Gawate <70628601+anay2310@users.noreply.github.com> Date: Fri, 15 Oct 2021 14:56:58 +0530 Subject: [PATCH 094/147] Defined MATRIX ADDITION --- MatrixAddition.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/MatrixAddition.java b/MatrixAddition.java index 03bb6bdb..cf9fbd36 100644 --- a/MatrixAddition.java +++ b/MatrixAddition.java @@ -1,3 +1,10 @@ + +//WHAT IS MATRIX ADDITION ? +//In mathematics, matrix addition is the operation of adding two matrices by adding the corresponding entries together. +//However, there are other operations which could also be considered addition for matrices, such as the direct sum and the Kronecker sum. + + + package arrays; import java.util.Scanner; public class MatrixAddition { From 200e2b4708c521d7cb76f031e78e7dea6f6d28d9 Mon Sep 17 00:00:00 2001 From: Anay Gawate <70628601+anay2310@users.noreply.github.com> Date: Fri, 15 Oct 2021 15:03:46 +0530 Subject: [PATCH 095/147] Updated the definition for recursive factorial program --- Recursive factorials | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Recursive factorials b/Recursive factorials index 3249fc58..2d3cb898 100644 --- a/Recursive factorials +++ b/Recursive factorials @@ -1,3 +1,9 @@ +/*A recursive function is a nonleaf function that calls itself. +The factorial function can be written as a recursive function call. +Recall that factorial(n) = n × (n – 1) × (n – 2) × … × 2 × 1. +The factorial function can be rewritten recursively as factorial(n) = n × factorial(n – 1).*/ + + /#include using namespace std; From 6b036446604517b1c97ae681306322c368152bb2 Mon Sep 17 00:00:00 2001 From: Nitya Prakash <43900148+nityaprakash10@users.noreply.github.com> Date: Fri, 15 Oct 2021 19:48:08 +0530 Subject: [PATCH 096/147] Create Transpose.cpp --- Transpose.cpp | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Transpose.cpp diff --git a/Transpose.cpp b/Transpose.cpp new file mode 100644 index 00000000..88b3e2e0 --- /dev/null +++ b/Transpose.cpp @@ -0,0 +1,46 @@ +#include +using namespace std; + +int main() { + int a[10][10], transpose[10][10], row, column, i, j; + + cout << "Enter rows and columns of matrix: "; + cin >> row >> column; + + cout << "\nEnter elements of matrix: " << endl; + + // Storing matrix elements + for (int i = 0; i < row; ++i) { + for (int j = 0; j < column; ++j) { + cout << "Enter element a" << i + 1 << j + 1 << ": "; + cin >> a[i][j]; + } + } + + // Printing the a matrix + cout << "\nEntered Matrix: " << endl; + for (int i = 0; i < row; ++i) { + for (int j = 0; j < column; ++j) { + cout << " " << a[i][j]; + if (j == column - 1) + cout << endl << endl; + } + } + + // Computing transpose of the matrix + for (int i = 0; i < row; ++i) + for (int j = 0; j < column; ++j) { + transpose[j][i] = a[i][j]; + } + + // Printing the transpose + cout << "\nTranspose of Matrix: " << endl; + for (int i = 0; i < column; ++i) + for (int j = 0; j < row; ++j) { + cout << " " << transpose[i][j]; + if (j == row - 1) + cout << endl << endl; + } + + return 0; +} From b09d5c9946ef62e8868244699a059215fc81c82c Mon Sep 17 00:00:00 2001 From: Nitya Prakash <43900148+nityaprakash10@users.noreply.github.com> Date: Fri, 15 Oct 2021 19:51:55 +0530 Subject: [PATCH 097/147] Create swap.cpp --- swap.cpp | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 swap.cpp diff --git a/swap.cpp b/swap.cpp new file mode 100644 index 00000000..c4703e6a --- /dev/null +++ b/swap.cpp @@ -0,0 +1,31 @@ +#include +using namespace std; + +void cyclicSwap(int *a, int *b, int *c); + +int main() +{ + int a, b, c; + + cout << "Enter value of a, b and c respectively: "; + cin >> a >> b >> c; + + cout << "Value before swapping: " << endl; + cout << "a, b and c respectively are: " << a << ", " << b << ", " << c << endl; + + cyclicSwap(&a, &b, &c); + + cout << "Value after swapping numbers in cycle: " << endl; + cout << "a, b and c respectively are: " << a << ", " << b << ", " << c << endl; + + return 0; +} + +void cyclicSwap(int *a, int *b, int *c) +{ + int temp; + temp = *b; + *b = *a; + *a = *c; + *c = temp; +} From def61ae8cda9b5bea983fa144de691ac3471077e Mon Sep 17 00:00:00 2001 From: CypherAk007 <71595919+CypherAk007@users.noreply.github.com> Date: Fri, 15 Oct 2021 22:30:24 +0530 Subject: [PATCH 098/147] Create bubbleSort --- bubbleSort | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 bubbleSort diff --git a/bubbleSort b/bubbleSort new file mode 100644 index 00000000..c6320f7b --- /dev/null +++ b/bubbleSort @@ -0,0 +1,31 @@ +import java.util.Scanner; + +public class BubbleSort_006 { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + // int n = a.length; + System.out.println("Enter the No. of elements you want to sort : "); + int m = sc.nextInt(); + int a[] = new int[m]; + System.out.println("Enter the elements :"); + for (int i = 0; i < m; i++) { + a[i] = sc.nextInt(); + } + + for (int i = 0; i < (m - 1); i++) { + for (int j = 0; j < (m - 1); j++) { + if (a[j + 1] < a[j]) { + int temp = a[j + 1]; + a[j + 1] = a[j]; + a[j] = temp; + } + } + } + + for (int item : a) { + System.out.print(item + " "); + } + sc.close(); + } +} From 0eaccbb8863e2b5bab46ea75c623e35aa3cddd3d Mon Sep 17 00:00:00 2001 From: CypherAk007 <71595919+CypherAk007@users.noreply.github.com> Date: Fri, 15 Oct 2021 22:33:11 +0530 Subject: [PATCH 099/147] Create SelectionSort --- SelectionSort | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 SelectionSort diff --git a/SelectionSort b/SelectionSort new file mode 100644 index 00000000..85f88464 --- /dev/null +++ b/SelectionSort @@ -0,0 +1,36 @@ +import java.util.Scanner; + +public class SelectionSort_009 {// search for the smallest ele andswap it with 1st element + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + // int n = a.length; + System.out.println("Enter the No. of elements you want to sort : "); + int m = sc.nextInt(); + int a[] = new int[m]; + System.out.println("Enter the elements :"); + for (int i = 0; i < m; i++) { + a[i] = sc.nextInt(); + } + + for (int i = 0; i < m - 1; i++) { + int minInd = i; + for (int j = i; j < m; j++) { + if (a[j] < a[minInd]) { + minInd = j; + + } + + } + int temp = a[i]; + a[i] = a[minInd]; + a[minInd] = temp; + } + + for (int e : a) { + System.out.print(e + " "); + } + sc.close(); + } + +} From 315298f156b7f1771dd46226bdea7e1edb76bcd4 Mon Sep 17 00:00:00 2001 From: CypherAk007 <71595919+CypherAk007@users.noreply.github.com> Date: Fri, 15 Oct 2021 22:34:13 +0530 Subject: [PATCH 100/147] Create stingReverse --- stingReverse | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 stingReverse diff --git a/stingReverse b/stingReverse new file mode 100644 index 00000000..7004e99c --- /dev/null +++ b/stingReverse @@ -0,0 +1,15 @@ +public class ReverseString_012 { + public static void main(String[] args) { + String sentence = " Java is oop lang "; + String sen = sentence.trim(); + String noSpaceStr = sen.replaceAll("\\s+", ","); + // using built in method(\s+ will match one or more whitespace characters) + String allSen[] = noSpaceStr.split(","); + + for (int i = allSen.length - 1; i >= 0; i--) { + + System.out.print(allSen[i] + " "); + + } + } +} From 15f9ebde83fa4493d1b77b50b801d4c3114c1567 Mon Sep 17 00:00:00 2001 From: CypherAk007 <71595919+CypherAk007@users.noreply.github.com> Date: Fri, 15 Oct 2021 22:36:02 +0530 Subject: [PATCH 101/147] Create optimizedbubblesort --- optimizedbubblesort | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 optimizedbubblesort diff --git a/optimizedbubblesort b/optimizedbubblesort new file mode 100644 index 00000000..78581206 --- /dev/null +++ b/optimizedbubblesort @@ -0,0 +1,37 @@ +import java.util.Scanner; + +public class BubbleSortOptimized_007 { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + // int n = a.length; + System.out.println("Enter the No. of elements you want to sort : "); + int m = sc.nextInt(); + int a[] = new int[m]; + System.out.println("Enter the elements :"); + for (int i = 0; i < m; i++) { + a[i] = sc.nextInt(); + } + + for (int i = 0; i < (m - 1); i++) { + boolean sorted = true;// if the elements are already sorted. + + for (int j = 0; j < (m - 1 - i); j++) {// runs last,bit1,bit2... + if (a[j + 1] < a[j]) { + int temp = a[j + 1]; + a[j + 1] = a[j]; + a[j] = temp; + + sorted = false; + } + } + if (sorted) + break; + } + + for (int item : a) { + System.out.print(item + " "); + } + sc.close(); + } +} From d0d68639705fcf20ade4bb318847dc81550939ef Mon Sep 17 00:00:00 2001 From: 982danish <72152484+982danish@users.noreply.github.com> Date: Sat, 16 Oct 2021 00:33:19 +0530 Subject: [PATCH 102/147] Create Divide and Conquer DP Divide and Conquer Competitive Programming --- Divide and Conquer DP | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Divide and Conquer DP diff --git a/Divide and Conquer DP b/Divide and Conquer DP new file mode 100644 index 00000000..7beec22e --- /dev/null +++ b/Divide and Conquer DP @@ -0,0 +1,35 @@ +int m, n; +vector dp_before(n), dp_cur(n); + +long long C(int i, int j); + +// compute dp_cur[l], ... dp_cur[r] (inclusive) +void compute(int l, int r, int optl, int optr) { + if (l > r) + return; + + int mid = (l + r) >> 1; + pair best = {LLONG_MAX, -1}; + + for (int k = optl; k <= min(mid, optr); k++) { + best = min(best, {(k ? dp_before[k - 1] : 0) + C(k, mid), k}); + } + + dp_cur[mid] = best.first; + int opt = best.second; + + compute(l, mid - 1, optl, opt); + compute(mid + 1, r, opt, optr); +} + +int solve() { + for (int i = 0; i < n; i++) + dp_before[i] = C(0, i); + + for (int i = 1; i < m; i++) { + compute(0, n - 1, 0, n - 1); + dp_before = dp_cur; + } + + return dp_before[n - 1]; +} From b0389027151b863a3ee93fa0ea0b731fcb4db00b Mon Sep 17 00:00:00 2001 From: 982danish <72152484+982danish@users.noreply.github.com> Date: Sat, 16 Oct 2021 01:07:01 +0530 Subject: [PATCH 103/147] Create Binomial Coefficients --- Binomial Coefficients | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 Binomial Coefficients diff --git a/Binomial Coefficients b/Binomial Coefficients new file mode 100644 index 00000000..99b96297 --- /dev/null +++ b/Binomial Coefficients @@ -0,0 +1,8 @@ +const int maxn = ...; +int C[maxn + 1][maxn + 1]; +C[0][0] = 1; +for (int n = 1; n <= maxn; ++n) { + C[n][0] = C[n][n] = 1; + for (int k = 1; k < n; ++k) + C[n][k] = C[n - 1][k - 1] + C[n - 1][k]; +} From b67f40e3a289b142a28ef4d591ba281ed77e76c6 Mon Sep 17 00:00:00 2001 From: 982danish <72152484+982danish@users.noreply.github.com> Date: Sat, 16 Oct 2021 01:08:37 +0530 Subject: [PATCH 104/147] Create The Inclusion-Exclusion Principle --- The Inclusion-Exclusion Principle | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 The Inclusion-Exclusion Principle diff --git a/The Inclusion-Exclusion Principle b/The Inclusion-Exclusion Principle new file mode 100644 index 00000000..d1ff2537 --- /dev/null +++ b/The Inclusion-Exclusion Principle @@ -0,0 +1,27 @@ +int n; +bool good[MAXN]; +int deg[MAXN], cnt[MAXN]; + +long long solve() { + memset (good, 1, sizeof good); + memset (deg, 0, sizeof deg); + memset (cnt, 0, sizeof cnt); + + long long ans_bad = 0; + for (int i=2; i<=n; ++i) { + if (good[i]) { + if (deg[i] == 0) deg[i] = 1; + for (int j=1; i*j<=n; ++j) { + if (j > 1 && deg[i] == 1) + if (j % i == 0) + good[i*j] = false; + else + ++deg[i*j]; + cnt[i*j] += (n / i) * (deg[i]%2==1 ? +1 : -1); + } + } + ans_bad += (cnt[i] - 1) * 1ll * (n-1 - cnt[i]); + } + + return (n-1) * 1ll * (n-2) * (n-3) / 6 - ans_bad / 2; +} From 85aca5746b1b6db289468e8052cd902a7adde3d9 Mon Sep 17 00:00:00 2001 From: 982danish <72152484+982danish@users.noreply.github.com> Date: Sat, 16 Oct 2021 01:09:31 +0530 Subject: [PATCH 105/147] Create Ternary Search --- Ternary Search | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Ternary Search diff --git a/Ternary Search b/Ternary Search new file mode 100644 index 00000000..8fa17967 --- /dev/null +++ b/Ternary Search @@ -0,0 +1,14 @@ +double ternary_search(double l, double r) { + double eps = 1e-9; //set the error limit here + while (r - l > eps) { + double m1 = l + (r - l) / 3; + double m2 = r - (r - l) / 3; + double f1 = f(m1); //evaluates the function at m1 + double f2 = f(m2); //evaluates the function at m2 + if (f1 < f2) + l = m1; + else + r = m2; + } + return f(l); //return the maximum of f(x) in [l, r] +} From 8a6cc7628173b37b11624a632f5be6725fac79b6 Mon Sep 17 00:00:00 2001 From: MadNMaxx <57186119+madnmaxx@users.noreply.github.com> Date: Sat, 16 Oct 2021 11:14:08 +0530 Subject: [PATCH 106/147] Create frequency_of_chars.cpp --- frequency_of_chars.cpp | 152 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 152 insertions(+) create mode 100644 frequency_of_chars.cpp diff --git a/frequency_of_chars.cpp b/frequency_of_chars.cpp new file mode 100644 index 00000000..c3a503ae --- /dev/null +++ b/frequency_of_chars.cpp @@ -0,0 +1,152 @@ +#include +#include +#include +main() +{ + int ch,i,j,k,l,fc[50][2],flag; + char line[50],fw[50][50]; + clrscr(); + do + { + printf("\n<1> Input a line"); + printf("\n<2> Number of characters"); + printf("\n<3> Number of words"); + printf("\n<4> Number of vowals"); + printf("\n<5> Frequency of characters"); + printf("\n<6> Frequency of words"); + printf("\n<7> Exit\n"); + do + { + printf("\n enter your choice "); + scanf("%d",&ch); + }while(ch>7 || ch<1); + switch (ch) + { + case 1: //input a line + printf("\n Enter a line "); + scanf("\n%[^\n]",line); + break; + case 2: //number of characters + j=0; + for(i=0;i64 && line[i]<93) + ++j; + else + if(line[i]>96 && line[i]<123) + ++j; + } + printf("total number of characters are %d",j); + break; + case 3: //number of words + j=0; + for(i=0;i1) + fw[k][0]='\0'; + } + } + if(fc[0][0]>0) + { + flag=0; + do + { + printf("%c",fw[i][flag]); + } while(fw[i][flag++]!='\0'); + if(fw[i][0]!='\0') + printf("%d\n",fc[0][0]); + } + fc[0][0]=0; + } + break; + } + }while(ch!=7); + printf("\n\n i will wait for your mails "); + getch(); + return ; +} From dbff08e61245a7de0912302d3f05e85aa09251bc Mon Sep 17 00:00:00 2001 From: MadNMaxx <57186119+madnmaxx@users.noreply.github.com> Date: Sat, 16 Oct 2021 11:18:18 +0530 Subject: [PATCH 107/147] Create multiply_two_matrices.cpp --- multiply_two_matrices.cpp | 242 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 242 insertions(+) create mode 100644 multiply_two_matrices.cpp diff --git a/multiply_two_matrices.cpp b/multiply_two_matrices.cpp new file mode 100644 index 00000000..7c2e0880 --- /dev/null +++ b/multiply_two_matrices.cpp @@ -0,0 +1,242 @@ +# include +# include +# include + + + + class Matrix + { + private: + float matrix_a[3][3]; + float matrix_b[3][3]; + float matrix_c[3][3]; + + public: + Matrix( ); + + void get_matrix_a( ); + void get_matrix_b( ); + void multiply_matrices( ); + void show_result_Matrix( ); + }; + + + + + Matrix::Matrix( ) + { + for(int i=0;i<3;i++) + { + for(int j=0;j<3;j++) + { + matrix_a[i][j]=0; + matrix_b[i][j]=0; + matrix_c[i][j]=0; + } + } + + gotoxy(1,1); + cout<<"*********************************************"< Date: Sat, 16 Oct 2021 11:20:32 +0530 Subject: [PATCH 108/147] Create binary_search_tree.cpp --- binary_search_tree.cpp | 286 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 286 insertions(+) create mode 100644 binary_search_tree.cpp diff --git a/binary_search_tree.cpp b/binary_search_tree.cpp new file mode 100644 index 00000000..853e1eea --- /dev/null +++ b/binary_search_tree.cpp @@ -0,0 +1,286 @@ +#include +#include +using namespace std; + +class BinarySearchTree +{ + private: + struct tree_node + { + tree_node* left; + tree_node* right; + int data; + }; + tree_node* root; + public: + BinarySearchTree() + { + root = NULL; + } + bool isEmpty() const { return root==NULL; } + void print_inorder(); + void inorder(tree_node*); + void print_preorder(); + void preorder(tree_node*); + void print_postorder(); + void postorder(tree_node*); + void insert(int); + void remove(int); +}; + +// Smaller elements go left +// larger elements go right +void BinarySearchTree::insert(int d) +{ + tree_node* t = new tree_node; + tree_node* parent; + t->data = d; + t->left = NULL; + t->right = NULL; + parent = NULL; + // is this a new tree? + if(isEmpty()) root = t; + else + { + //Note: ALL insertions are as leaf nodes + tree_node* curr; + curr = root; + // Find the Node's parent + while(curr) + { + parent = curr; + if(t->data > curr->data) curr = curr->right; + else curr = curr->left; + } + + if(t->data < parent->data) + parent->left = t; + else + parent->right = t; + } +} + +void BinarySearchTree::remove(int d) +{ + //Locate the element + bool found = false; + if(isEmpty()) + { + cout<<" This Tree is empty! "<data == d) + { + found = true; + break; + } + else + { + parent = curr; + if(d>curr->data) curr = curr->right; + else curr = curr->left; + } + } + if(!found) + { + cout<<" Data not found! "<left == NULL && curr->right != NULL)|| (curr->left != NULL +&& curr->right == NULL)) + { + if(curr->left == NULL && curr->right != NULL) + { + if(parent->left == curr) + { + parent->left = curr->right; + delete curr; + } + else + { + parent->right = curr->right; + delete curr; + } + } + else // left child present, no right child + { + if(parent->left == curr) + { + parent->left = curr->left; + delete curr; + } + else + { + parent->right = curr->left; + delete curr; + } + } + return; + } + + //We're looking at a leaf node + if( curr->left == NULL && curr->right == NULL) + { + if(parent->left == curr) parent->left = NULL; + else parent->right = NULL; + delete curr; + return; + } + + + //Node with 2 children + // replace node with smallest value in right subtree + if (curr->left != NULL && curr->right != NULL) + { + tree_node* chkr; + chkr = curr->right; + if((chkr->left == NULL) && (chkr->right == NULL)) + { + curr = chkr; + delete chkr; + curr->right = NULL; + } + else // right child has children + { + //if the node's right child has a left child + // Move all the way down left to locate smallest element + + if((curr->right)->left != NULL) + { + tree_node* lcurr; + tree_node* lcurrp; + lcurrp = curr->right; + lcurr = (curr->right)->left; + while(lcurr->left != NULL) + { + lcurrp = lcurr; + lcurr = lcurr->left; + } + curr->data = lcurr->data; + delete lcurr; + lcurrp->left = NULL; + } + else + { + tree_node* tmp; + tmp = curr->right; + curr->data = tmp->data; + curr->right = tmp->right; + delete tmp; + } + + } + return; + } + +} + +void BinarySearchTree::print_inorder() +{ + inorder(root); +} + +void BinarySearchTree::inorder(tree_node* p) +{ + if(p != NULL) + { + if(p->left) inorder(p->left); + cout<<" "<data<<" "; + if(p->right) inorder(p->right); + } + else return; +} + +void BinarySearchTree::print_preorder() +{ + preorder(root); +} + +void BinarySearchTree::preorder(tree_node* p) +{ + if(p != NULL) + { + cout<<" "<data<<" "; + if(p->left) preorder(p->left); + if(p->right) preorder(p->right); + } + else return; +} + +void BinarySearchTree::print_postorder() +{ + postorder(root); +} + +void BinarySearchTree::postorder(tree_node* p) +{ + if(p != NULL) + { + if(p->left) postorder(p->left); + if(p->right) postorder(p->right); + cout<<" "<data<<" "; + } + else return; +} + +int main() +{ + BinarySearchTree b; + int ch,tmp,tmp1; + while(1) + { + cout<>ch; + switch(ch) + { + case 1 : cout<<" Enter Number to be inserted : "; + cin>>tmp; + b.insert(tmp); + break; + case 2 : cout<>tmp1; + b.remove(tmp1); + break; + case 6 : system("pause"); + return 0; + break; + } + } +} From 8fbe02794d00fe01a6466415b83faf917cf4faa4 Mon Sep 17 00:00:00 2001 From: Rohit Paiya Date: Sat, 16 Oct 2021 11:38:41 +0530 Subject: [PATCH 109/147] added a flappy bird game. A game made in python. --- flappy_bird_game.py | 222 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 222 insertions(+) create mode 100644 flappy_bird_game.py diff --git a/flappy_bird_game.py b/flappy_bird_game.py new file mode 100644 index 00000000..42ddd172 --- /dev/null +++ b/flappy_bird_game.py @@ -0,0 +1,222 @@ +import random # For generating random numbers +import sys # We will use sys.exit to exit the program +import pygame +from pygame.locals import * # Basic pygame imports + +# Global Variables for the game +FPS = 32 +SCREENWIDTH = 289 +SCREENHEIGHT = 511 +SCREEN = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT)) +GROUNDY = SCREENHEIGHT * 0.8 +GAME_SPRITES = {} +GAME_SOUNDS = {} +PLAYER = 'gallery/sprites/bird.png' +BACKGROUND = 'gallery/sprites/background.png' +PIPE = 'gallery/sprites/pipe.png' + +def welcomeScreen(): + """ + Shows welcome images on the screen + """ + + playerx = int(SCREENWIDTH/5) + playery = int((SCREENHEIGHT - GAME_SPRITES['player'].get_height())/2) + messagex = int((SCREENWIDTH - GAME_SPRITES['message'].get_width())/2) + messagey = int(SCREENHEIGHT*0.13) + basex = 0 + while True: + for event in pygame.event.get(): + # if user clicks on cross button, close the game + if event.type == QUIT or (event.type==KEYDOWN and event.key == K_ESCAPE): + pygame.quit() + sys.exit() + + # If the user presses space or up key, start the game for them + elif event.type==KEYDOWN and (event.key==K_SPACE or event.key == K_UP): + return + else: + SCREEN.blit(GAME_SPRITES['background'], (0, 0)) + SCREEN.blit(GAME_SPRITES['player'], (playerx, playery)) + SCREEN.blit(GAME_SPRITES['message'], (messagex,messagey )) + SCREEN.blit(GAME_SPRITES['base'], (basex, GROUNDY)) + pygame.display.update() + FPSCLOCK.tick(FPS) + +def mainGame(): + score = 0 + playerx = int(SCREENWIDTH/5) + playery = int(SCREENWIDTH/2) + basex = 0 + + # Create 2 pipes for blitting on the screen + newPipe1 = getRandomPipe() + newPipe2 = getRandomPipe() + + # my List of upper pipes + upperPipes = [ + {'x': SCREENWIDTH+200, 'y':newPipe1[0]['y']}, + {'x': SCREENWIDTH+200+(SCREENWIDTH/2), 'y':newPipe2[0]['y']}, + ] + # my List of lower pipes + lowerPipes = [ + {'x': SCREENWIDTH+200, 'y':newPipe1[1]['y']}, + {'x': SCREENWIDTH+200+(SCREENWIDTH/2), 'y':newPipe2[1]['y']}, + ] + + pipeVelX = -4 + + playerVelY = -9 + playerMaxVelY = 10 + playerMinVelY = -8 + playerAccY = 1 + + playerFlapAccv = -8 # velocity while flapping + playerFlapped = False # It is true only when the bird is flapping + + + while True: + for event in pygame.event.get(): + if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): + pygame.quit() + sys.exit() + if event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP): + if playery > 0: + playerVelY = playerFlapAccv + playerFlapped = True + GAME_SOUNDS['wing'].play() + + + crashTest = isCollide(playerx, playery, upperPipes, lowerPipes) # This function will return true if the player is crashed + if crashTest: + return + + #check for score + playerMidPos = playerx + GAME_SPRITES['player'].get_width()/2 + for pipe in upperPipes: + pipeMidPos = pipe['x'] + GAME_SPRITES['pipe'][0].get_width()/2 + if pipeMidPos<= playerMidPos < pipeMidPos +4: + score +=1 + print(f"Your score is {score}") + GAME_SOUNDS['point'].play() + + + if playerVelY GROUNDY - 25 or playery<0: + GAME_SOUNDS['hit'].play() + return True + + for pipe in upperPipes: + pipeHeight = GAME_SPRITES['pipe'][0].get_height() + if(playery < pipeHeight + pipe['y'] and abs(playerx - pipe['x']) < GAME_SPRITES['pipe'][0].get_width()): + GAME_SOUNDS['hit'].play() + return True + + for pipe in lowerPipes: + if (playery + GAME_SPRITES['player'].get_height() > pipe['y']) and abs(playerx - pipe['x']) < GAME_SPRITES['pipe'][0].get_width(): + GAME_SOUNDS['hit'].play() + return True + + return False + +def getRandomPipe(): + """ + Generate positions of two pipes(one bottom straight and one top rotated ) for blitting on the screen + """ + pipeHeight = GAME_SPRITES['pipe'][0].get_height() + offset = SCREENHEIGHT/3 + y2 = offset + random.randrange(0, int(SCREENHEIGHT - GAME_SPRITES['base'].get_height() - 1.2 *offset)) + pipeX = SCREENWIDTH + 10 + y1 = pipeHeight - y2 + offset + pipe = [ + {'x': pipeX, 'y': -y1}, #upper Pipe + {'x': pipeX, 'y': y2} #lower Pipe + ] + return pipe + + + + + + +if __name__ == "__main__": + # This will be the main point from where our game will start + pygame.init() # Initialize all pygame's modules + FPSCLOCK = pygame.time.Clock() + pygame.display.set_caption('Flappy Bird by Rohit Paiya') + GAME_SPRITES['numbers'] = ( + pygame.image.load('gallery/sprites/0.png').convert_alpha(), + pygame.image.load('gallery/sprites/1.png').convert_alpha(), + pygame.image.load('gallery/sprites/2.png').convert_alpha(), + pygame.image.load('gallery/sprites/3.png').convert_alpha(), + pygame.image.load('gallery/sprites/4.png').convert_alpha(), + pygame.image.load('gallery/sprites/5.png').convert_alpha(), + pygame.image.load('gallery/sprites/6.png').convert_alpha(), + pygame.image.load('gallery/sprites/7.png').convert_alpha(), + pygame.image.load('gallery/sprites/8.png').convert_alpha(), + pygame.image.load('gallery/sprites/9.png').convert_alpha(), + ) + + GAME_SPRITES['message'] =pygame.image.load('gallery/sprites/message.jpeg').convert_alpha() + GAME_SPRITES['base'] =pygame.image.load('gallery/sprites/base.png').convert_alpha() + GAME_SPRITES['pipe'] =(pygame.transform.rotate(pygame.image.load( PIPE).convert_alpha(), 180), + pygame.image.load(PIPE).convert_alpha() + ) + + # Game sounds + GAME_SOUNDS['die'] = pygame.mixer.Sound('gallery/audio/die.wav') + GAME_SOUNDS['hit'] = pygame.mixer.Sound('gallery/audio/hit.wav') + GAME_SOUNDS['point'] = pygame.mixer.Sound('gallery/audio/point.wav') + GAME_SOUNDS['swoosh'] = pygame.mixer.Sound('gallery/audio/swoosh.wav') + GAME_SOUNDS['wing'] = pygame.mixer.Sound('gallery/audio/wing.wav') + + GAME_SPRITES['background'] = pygame.image.load(BACKGROUND).convert() + GAME_SPRITES['player'] = pygame.image.load(PLAYER).convert_alpha() + + while True: + welcomeScreen() # Shows welcome screen to the user until he presses a button + mainGame() # This is the main game function \ No newline at end of file From a4af7c7d1840a7c8e765c5ce8650c2631ce07edd Mon Sep 17 00:00:00 2001 From: Pranay-Gupta <69376775+Pranay-Gupta@users.noreply.github.com> Date: Sun, 17 Oct 2021 10:43:31 +0530 Subject: [PATCH 110/147] Create reverseLinkedList.cpp --- reverseLinkedList.cpp | 79 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 reverseLinkedList.cpp diff --git a/reverseLinkedList.cpp b/reverseLinkedList.cpp new file mode 100644 index 00000000..cbc51d6c --- /dev/null +++ b/reverseLinkedList.cpp @@ -0,0 +1,79 @@ +// Iterative C++ program to reverse +// a linked list +#include +using namespace std; + +/* Link list node */ +struct Node { + int data; + struct Node* next; + Node(int data) + { + this->data = data; + next = NULL; + } +}; + +struct LinkedList { + Node* head; + LinkedList() { head = NULL; } + + /* Function to reverse the linked list */ + void reverse() + { + // Initialize current, previous and + // next pointers + Node* current = head; + Node *prev = NULL, *next = NULL; + + while (current != NULL) { + // Store next + next = current->next; + + // Reverse current node's pointer + current->next = prev; + + // Move pointers one position ahead. + prev = current; + current = next; + } + head = prev; + } + + /* Function to print linked list */ + void print() + { + struct Node* temp = head; + while (temp != NULL) { + cout << temp->data << " "; + temp = temp->next; + } + } + + void push(int data) + { + Node* temp = new Node(data); + temp->next = head; + head = temp; + } +}; + +/* Driver code*/ +int main() +{ + /* Start with the empty list */ + LinkedList ll; + ll.push(20); + ll.push(4); + ll.push(15); + ll.push(85); + + cout << "Given linked list\n"; + ll.print(); + + ll.reverse(); + + cout << "\nReversed Linked list \n"; + ll.print(); + return 0; +} From 5b3a3cbb8bd2dfdacfbb2f83a82cc1864382d575 Mon Sep 17 00:00:00 2001 From: Pranay-Gupta <69376775+Pranay-Gupta@users.noreply.github.com> Date: Sun, 17 Oct 2021 11:02:20 +0530 Subject: [PATCH 111/147] Delete reverseLinkedList.cpp --- reverseLinkedList.cpp | 79 ------------------------------------------- 1 file changed, 79 deletions(-) delete mode 100644 reverseLinkedList.cpp diff --git a/reverseLinkedList.cpp b/reverseLinkedList.cpp deleted file mode 100644 index cbc51d6c..00000000 --- a/reverseLinkedList.cpp +++ /dev/null @@ -1,79 +0,0 @@ -// Iterative C++ program to reverse -// a linked list -#include -using namespace std; - -/* Link list node */ -struct Node { - int data; - struct Node* next; - Node(int data) - { - this->data = data; - next = NULL; - } -}; - -struct LinkedList { - Node* head; - LinkedList() { head = NULL; } - - /* Function to reverse the linked list */ - void reverse() - { - // Initialize current, previous and - // next pointers - Node* current = head; - Node *prev = NULL, *next = NULL; - - while (current != NULL) { - // Store next - next = current->next; - - // Reverse current node's pointer - current->next = prev; - - // Move pointers one position ahead. - prev = current; - current = next; - } - head = prev; - } - - /* Function to print linked list */ - void print() - { - struct Node* temp = head; - while (temp != NULL) { - cout << temp->data << " "; - temp = temp->next; - } - } - - void push(int data) - { - Node* temp = new Node(data); - temp->next = head; - head = temp; - } -}; - -/* Driver code*/ -int main() -{ - /* Start with the empty list */ - LinkedList ll; - ll.push(20); - ll.push(4); - ll.push(15); - ll.push(85); - - cout << "Given linked list\n"; - ll.print(); - - ll.reverse(); - - cout << "\nReversed Linked list \n"; - ll.print(); - return 0; -} From deb0bc7301c8c6289a14084b6aaaa434bdabc7ad Mon Sep 17 00:00:00 2001 From: Pranay-Gupta <69376775+Pranay-Gupta@users.noreply.github.com> Date: Sun, 17 Oct 2021 11:03:05 +0530 Subject: [PATCH 112/147] Create reverseLinkedListIter.cpp --- reverseLinkedListIter.cpp | 79 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 reverseLinkedListIter.cpp diff --git a/reverseLinkedListIter.cpp b/reverseLinkedListIter.cpp new file mode 100644 index 00000000..cbc51d6c --- /dev/null +++ b/reverseLinkedListIter.cpp @@ -0,0 +1,79 @@ +// Iterative C++ program to reverse +// a linked list +#include +using namespace std; + +/* Link list node */ +struct Node { + int data; + struct Node* next; + Node(int data) + { + this->data = data; + next = NULL; + } +}; + +struct LinkedList { + Node* head; + LinkedList() { head = NULL; } + + /* Function to reverse the linked list */ + void reverse() + { + // Initialize current, previous and + // next pointers + Node* current = head; + Node *prev = NULL, *next = NULL; + + while (current != NULL) { + // Store next + next = current->next; + + // Reverse current node's pointer + current->next = prev; + + // Move pointers one position ahead. + prev = current; + current = next; + } + head = prev; + } + + /* Function to print linked list */ + void print() + { + struct Node* temp = head; + while (temp != NULL) { + cout << temp->data << " "; + temp = temp->next; + } + } + + void push(int data) + { + Node* temp = new Node(data); + temp->next = head; + head = temp; + } +}; + +/* Driver code*/ +int main() +{ + /* Start with the empty list */ + LinkedList ll; + ll.push(20); + ll.push(4); + ll.push(15); + ll.push(85); + + cout << "Given linked list\n"; + ll.print(); + + ll.reverse(); + + cout << "\nReversed Linked list \n"; + ll.print(); + return 0; +} From 6aa2024ba6546fed0dd41a6d264d7faa97f9c6e8 Mon Sep 17 00:00:00 2001 From: Afeefa Ahmad <75202156+afeefaahmad@users.noreply.github.com> Date: Sun, 17 Oct 2021 11:21:30 +0530 Subject: [PATCH 113/147] Create sum of array [Hackererank] --- sum of array [Hackererank] | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 sum of array [Hackererank] diff --git a/sum of array [Hackererank] b/sum of array [Hackererank] new file mode 100644 index 00000000..972e73b6 --- /dev/null +++ b/sum of array [Hackererank] @@ -0,0 +1,19 @@ +//This program is impemented in C language. +#include +#include +#include +#include +#define N 1000 + +int main() { + int x[N],n,i,t; + scanf("%d",&n); + for(i=0;i Date: Sun, 17 Oct 2021 12:06:14 +0530 Subject: [PATCH 114/147] Create Palindromic partitioning --- Palindromic partitioning | 75 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 Palindromic partitioning diff --git a/Palindromic partitioning b/Palindromic partitioning new file mode 100644 index 00000000..92b94ab9 --- /dev/null +++ b/Palindromic partitioning @@ -0,0 +1,75 @@ +// { Driver Code Starts +// Initial Template for c++ + +#include +using namespace std; + + // } Driver Code Ends +// User function Template for C++ + +class Solution{ +public: +int t[502][502]; +bool ispalindrome(string &str,int i,int j) +{ + while(i=j) + return 0; + if(ispalindrome(st,i,j)==true) + return 0; + if(t[i][j]!=-1) + return t[i][j]; + int temp; + int ans=INT_MAX; + for(int k=i;k>t; + while(t--){ + string str; + cin>>str; + + Solution ob; + cout< Date: Sun, 17 Oct 2021 18:01:26 +0530 Subject: [PATCH 115/147] Create nextsmallerelement.cpp --- nextsmallerelement.cpp | 64 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 nextsmallerelement.cpp diff --git a/nextsmallerelement.cpp b/nextsmallerelement.cpp new file mode 100644 index 00000000..3d846479 --- /dev/null +++ b/nextsmallerelement.cpp @@ -0,0 +1,64 @@ +//Problem Statement: +// Given an array, print the Next Smaller Element (NSE) for every element. +// The NSE for an element x is the first smaller element on the right side of x in array. +// Elements for which no smaller element exist (on right side), consider NSE as -1. + +#include +using namespace std; + +// prints NSE for elements of array arr[] of size n + +void printNSE(int arr[], int n) +{ + stack > s; + vector ans(n); + + // iterate for rest of the elements + for (int i = 0; i < n; i++) { + int next = arr[i]; + + // if stack is empty then this element can't be NSE + // for any other element, so just push it to stack + // so that we can find NSE for it, and continue + if (s.empty()) { + s.push({ next, i }); + continue; + } + + // while stack is not empty and the top element is + // greater than next + // a) NSE for top is next, use top's index to + // maintain original order + // b) pop the top element from stack + + while (!s.empty() && s.top().first > next) { + ans[s.top().second] = next; + s.pop(); + } + + // push next to stack so that we can find NSE for it + + s.push({ next, i }); + } + + // After iterating over the loop, the remaining elements + // in stack do not have any NSE, so set -1 for them + + while (!s.empty()) { + ans[s.top().second] = -1; + s.pop(); + } + + for (int i = 0; i < n; i++) { + cout << arr[i] << " ---> " << ans[i] << endl; + } +} + +// Driver program to test above functions +int main() +{ + int arr[] = { 11, 13, 21, 3 }; + int n = sizeof(arr) / sizeof(arr[0]); + printNSE(arr, n); + return 0; +} From e95375d4f1ebcd109641640316ee85fef632bf04 Mon Sep 17 00:00:00 2001 From: ujjwal-shukla <89790891+ujjwal-shukla@users.noreply.github.com> Date: Sun, 17 Oct 2021 18:34:03 +0530 Subject: [PATCH 116/147] Create Longest Common Subsequence --- Longest Common Subsequence | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Longest Common Subsequence diff --git a/Longest Common Subsequence b/Longest Common Subsequence new file mode 100644 index 00000000..e8d900ae --- /dev/null +++ b/Longest Common Subsequence @@ -0,0 +1,23 @@ +def lcs(s1 , s2): +m, n = len(s1), len(s2) +prev, cur = [0]*(n+1), [0]*(n+1) +for i in range(1, m+1): + for j in range(1, n+1): + if s1[i-1] == s2[j-1]: + cur[j] = 1 + prev[j-1] + else: + if cur[j-1] > prev[j]: + cur[j] = cur[j-1] + else: + cur[j] = prev[j] + cur, prev = prev, cur +return prev[n] + +#end of function lcs + + +# Driver program to test the above function +s1 = "AGGTAB" +s2 = "GXTXAYB" +print("Length of LCS is ", lcs(s1, s2)) +# BY ujjwal-shukla From f9a51d740efcaa26224124cd735f5368715f6cae Mon Sep 17 00:00:00 2001 From: ujjwal-shukla <89790891+ujjwal-shukla@users.noreply.github.com> Date: Sun, 17 Oct 2021 18:36:02 +0530 Subject: [PATCH 117/147] Create Topological Sort --- Topological Sort | 108 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 Topological Sort diff --git a/Topological Sort b/Topological Sort new file mode 100644 index 00000000..55a76bca --- /dev/null +++ b/Topological Sort @@ -0,0 +1,108 @@ +// A C++ program to print topological +// sorting of a DAG +#include +#include +#include +using namespace std; + +// Class to represent a graph +class Graph { + // No. of vertices' + int V; + + // Pointer to an array containing adjacency listsList + list* adj; + + // A function used by topologicalSort + void topologicalSortUtil(int v, bool visited[], + stack& Stack); + +public: + // Constructor + Graph(int V); + + // function to add an edge to graph + void addEdge(int v, int w); + + // prints a Topological Sort of + // the complete graph + void topologicalSort(); +}; + +Graph::Graph(int V) +{ + this->V = V; + adj = new list[V]; +} + +void Graph::addEdge(int v, int w) +{ + // Add w to v’s list. + adj[v].push_back(w); +} + +// A recursive function used by topologicalSort +void Graph::topologicalSortUtil(int v, bool visited[], + stack& Stack) +{ + // Mark the current node as visited. + visited[v] = true; + + // Recur for all the vertices + // adjacent to this vertex + list::iterator i; + for (i = adj[v].begin(); i != adj[v].end(); ++i) + if (!visited[*i]) + topologicalSortUtil(*i, visited, Stack); + + // Push current vertex to stack + // which stores result + Stack.push(v); +} + +// The function to do Topological Sort. +// It uses recursive topologicalSortUtil() +void Graph::topologicalSort() +{ + stack Stack; + + // Mark all the vertices as not visited + bool* visited = new bool[V]; + for (int i = 0; i < V; i++) + visited[i] = false; + + // Call the recursive helper function + // to store Topological + // Sort starting from all + // vertices one by one + for (int i = 0; i < V; i++) + if (visited[i] == false) + topologicalSortUtil(i, visited, Stack); + + // Print contents of stack + while (Stack.empty() == false) { + cout << Stack.top() << " "; + Stack.pop(); + } +} + +// Driver Code +int main() +{ + // Create a graph given in the above diagram + Graph g(6); + g.addEdge(5, 2); + g.addEdge(5, 0); + g.addEdge(4, 0); + g.addEdge(4, 1); + g.addEdge(2, 3); + g.addEdge(3, 1); + + cout << "Following is a Topological Sort of the given " + "graph \n"; + + // Function Call + g.topologicalSort(); + + return 0; +} From d9669bb99c06a9fc3a2f741828c7b1c43081aba8 Mon Sep 17 00:00:00 2001 From: ujjwal-shukla <89790891+ujjwal-shukla@users.noreply.github.com> Date: Sun, 17 Oct 2021 18:38:55 +0530 Subject: [PATCH 118/147] Create Longest Path in a Matrix --- Longest Path in a Matrix | 72 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 Longest Path in a Matrix diff --git a/Longest Path in a Matrix b/Longest Path in a Matrix new file mode 100644 index 00000000..1f86119b --- /dev/null +++ b/Longest Path in a Matrix @@ -0,0 +1,72 @@ +// C++ program to find the longest path in a matrix +// with given constraints +#include +#define n 3 +using namespace std; + +// Returns length of the longest path beginning with mat[i][j]. +// This function mainly uses lookup table dp[n][n] +int findLongestFromACell(int i, int j, int mat[n][n], int dp[n][n]) +{ + if (i < 0 || i >= n || j < 0 || j >= n) + return 0; + + // If this subproblem is already solved + if (dp[i][j] != -1) + return dp[i][j]; + + // To store the path lengths in all the four directions + int x = INT_MIN, y = INT_MIN, z = INT_MIN, w = INT_MIN; + + // Since all numbers are unique and in range from 1 to n*n, + // there is atmost one possible direction from any cell + if (j < n - 1 && ((mat[i][j] + 1) == mat[i][j + 1])) + x = 1 + findLongestFromACell(i, j + 1, mat, dp); + + if (j > 0 && (mat[i][j] + 1 == mat[i][j - 1])) + y = 1 + findLongestFromACell(i, j - 1, mat, dp); + + if (i > 0 && (mat[i][j] + 1 == mat[i - 1][j])) + z = 1 + findLongestFromACell(i - 1, j, mat, dp); + + if (i < n - 1 && (mat[i][j] + 1 == mat[i + 1][j])) + w = 1 + findLongestFromACell(i + 1, j, mat, dp); + + // If none of the adjacent fours is one greater we will take 1 + // otherwise we will pick maximum from all the four directions + return dp[i][j] = max(x, max(y, max(z, max(w, 1)))); +} + +// Returns length of the longest path beginning with any cell +int finLongestOverAll(int mat[n][n]) +{ + int result = 1; // Initialize result + + // Create a lookup table and fill all entries in it as -1 + int dp[n][n]; + memset(dp, -1, sizeof dp); + + // Compute longest path beginning from all cells + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (dp[i][j] == -1) + findLongestFromACell(i, j, mat, dp); + + // Update result if needed + result = max(result, dp[i][j]); + } + } + + return result; +} + +// Driver program +int main() +{ + int mat[n][n] = { { 1, 2, 9 }, + { 5, 3, 8 }, + { 4, 6, 7 } }; + cout << "Length of the longest path is " + << finLongestOverAll(mat); + return 0; +} From 63109989a0f4e6d7b02d8382764c344b3b8d7293 Mon Sep 17 00:00:00 2001 From: ujjwal-shukla <89790891+ujjwal-shukla@users.noreply.github.com> Date: Sun, 17 Oct 2021 18:42:31 +0530 Subject: [PATCH 119/147] Create Longest Increasing Subsequence --- Longest Increasing Subsequence | 67 ++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Longest Increasing Subsequence diff --git a/Longest Increasing Subsequence b/Longest Increasing Subsequence new file mode 100644 index 00000000..ce6beaa2 --- /dev/null +++ b/Longest Increasing Subsequence @@ -0,0 +1,67 @@ +/* A Naive C++ recursive implementation +of LIS problem */ +#include +using namespace std; + +/* To make use of recursive calls, this +function must return two things: +1) Length of LIS ending with element arr[n-1]. + We use max_ending_here for this purpose +2) Overall maximum as the LIS may end with + an element before arr[n-1] max_ref is + used this purpose. +The value of LIS of full array of size n +is stored in *max_ref which is our final result +*/ +int _lis(int arr[], int n, int* max_ref) +{ + /* Base case */ + if (n == 1) + return 1; + + // 'max_ending_here' is length of LIS + // ending with arr[n-1] + int res, max_ending_here = 1; + + /* Recursively get all LIS ending with arr[0], + arr[1] ... arr[n-2]. If arr[i-1] is smaller + than arr[n-1], and max ending with arr[n-1] + needs to be updated, then update it */ + for (int i = 1; i < n; i++) { + res = _lis(arr, i, max_ref); + if (arr[i - 1] < arr[n - 1] + && res + 1 > max_ending_here) + max_ending_here = res + 1; + } + + // Compare max_ending_here with the overall + // max. And update the overall max if needed + if (*max_ref < max_ending_here) + *max_ref = max_ending_here; + + // Return length of LIS ending with arr[n-1] + return max_ending_here; +} + +// The wrapper function for _lis() +int lis(int arr[], int n) +{ + // The max variable holds the result + int max = 1; + + // The function _lis() stores its result in max + _lis(arr, n, &max); + + // returns max + return max; +} + +/* Driver program to test above function */ +int main() +{ + int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 }; + int n = sizeof(arr) / sizeof(arr[0]); + cout <<"Length of lis is "<< lis(arr, n); + return 0; +} +// This code is contributed by ujjwal-shukla From 9507e4155f8e15d673192558b19d342363392092 Mon Sep 17 00:00:00 2001 From: ujjwal-shukla <89790891+ujjwal-shukla@users.noreply.github.com> Date: Sun, 17 Oct 2021 18:46:01 +0530 Subject: [PATCH 120/147] Create KMP algorithm --- KMP algorithm | 88 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 KMP algorithm diff --git a/KMP algorithm b/KMP algorithm new file mode 100644 index 00000000..de32d673 --- /dev/null +++ b/KMP algorithm @@ -0,0 +1,88 @@ +// C++ program for implementation of KMP pattern searching +// algorithm +#include + +void computeLPSArray(char* pat, int M, int* lps); + +// Prints occurrences of txt[] in pat[] +void KMPSearch(char* pat, char* txt) +{ + int M = strlen(pat); + int N = strlen(txt); + + // create lps[] that will hold the longest prefix suffix + // values for pattern + int lps[M]; + + // Preprocess the pattern (calculate lps[] array) + computeLPSArray(pat, M, lps); + + int i = 0; // index for txt[] + int j = 0; // index for pat[] + while (i < N) { + if (pat[j] == txt[i]) { + j++; + i++; + } + + if (j == M) { + printf("Found pattern at index %d ", i - j); + j = lps[j - 1]; + } + + // mismatch after j matches + else if (i < N && pat[j] != txt[i]) { + // Do not match lps[0..lps[j-1]] characters, + // they will match anyway + if (j != 0) + j = lps[j - 1]; + else + i = i + 1; + } + } +} + +// Fills lps[] for given patttern pat[0..M-1] +void computeLPSArray(char* pat, int M, int* lps) +{ + // length of the previous longest prefix suffix + int len = 0; + + lps[0] = 0; // lps[0] is always 0 + + // the loop calculates lps[i] for i = 1 to M-1 + int i = 1; + while (i < M) { + if (pat[i] == pat[len]) { + len++; + lps[i] = len; + i++; + } + else // (pat[i] != pat[len]) + { + // This is tricky. Consider the example. + // AAACAAAA and i = 7. The idea is similar + // to search step. + if (len != 0) { + len = lps[len - 1]; + + // Also, note that we do not increment + // i here + } + else // if (len == 0) + { + lps[i] = 0; + i++; + } + } + } +} + +// Driver program to test above function +int main() +{ + char txt[] = "ABABDABACDABABCABAB"; + char pat[] = "ABABCABAB"; + KMPSearch(pat, txt); + return 0; +} From 07968dd6e8e9a3341c80f1ed7410ed6ce8ec1dde Mon Sep 17 00:00:00 2001 From: Gavindu Chirandi Alwis <76090683+Gavindu99-A@users.noreply.github.com> Date: Sun, 17 Oct 2021 09:56:15 -0700 Subject: [PATCH 121/147] add two matrixes --- MatrixAddition.java | 95 ++++++++++++++++++++++----------------------- 1 file changed, 47 insertions(+), 48 deletions(-) diff --git a/MatrixAddition.java b/MatrixAddition.java index cf9fbd36..2cf4b4c0 100644 --- a/MatrixAddition.java +++ b/MatrixAddition.java @@ -1,50 +1,49 @@ +#include +using namespace std; -//WHAT IS MATRIX ADDITION ? -//In mathematics, matrix addition is the operation of adding two matrices by adding the corresponding entries together. -//However, there are other operations which could also be considered addition for matrices, such as the direct sum and the Kronecker sum. - - - -package arrays; -import java.util.Scanner; -public class MatrixAddition { - - public static void main(String[] args) { - Scanner sc = new Scanner(System.in); - System.out.println("Welcome ! to addition program of matrix of same dimensions"); - System.out.print("Enter matrix type : "); - int rows = sc.nextInt(), columns = sc.nextInt(); - - int matrixA[][] = new int [rows][columns]; - int matrixB[][] = new int [rows][columns]; - - System.out.println("Enter matrix A"); - for (int i=0; i> r; + + cout << "Enter number of columns (between 1 and 100): "; + cin >> c; + + cout << endl << "Enter elements of 1st matrix: " << endl; + + // first matrix + for(i = 0; i < r; ++i) + for(j = 0; j < c; ++j) + { + cout << "Enter element a" << i + 1 << j + 1 << " : "; + cin >> a[i][j]; + } + // second matrix + cout << endl << "Enter elements of 2nd matrix: " << endl; + for(i = 0; i < r; ++i) + for(j = 0; j < c; ++j) + { + cout << "Enter element b" << i + 1 << j + 1 << " : "; + cin >> b[i][j]; + } + + // Adding Two matrices + for(i = 0; i < r; ++i) + for(j = 0; j < c; ++j) + sum[i][j] = a[i][j] + b[i][j]; + + // Displaying new matrix + cout << endl << "Sum of two matrix is: " << endl; + for(i = 0; i < r; ++i) + for(j = 0; j < c; ++j) + { + cout << sum[i][j] << " "; + if(j == c - 1) + cout << endl; + } + + return 0; +} From 29c99d08cb0d401ffadeda40592476c21e2320a6 Mon Sep 17 00:00:00 2001 From: Midhun Mohanan <60269061+TheGr4yhAt@users.noreply.github.com> Date: Mon, 18 Oct 2021 10:22:34 +0530 Subject: [PATCH 122/147] Create prime.cpp --- prime.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 prime.cpp diff --git a/prime.cpp b/prime.cpp new file mode 100644 index 00000000..9299b76d --- /dev/null +++ b/prime.cpp @@ -0,0 +1,29 @@ +#include +using namespace std; + +int main() { + int i, n; + bool isPrime = true; + + cout << "Enter a positive integer: "; + cin >> n; + + // 0 and 1 are not prime numbers + if (n == 0 || n == 1) { + isPrime = false; + } + else { + for (i = 2; i <= n / 2; ++i) { + if (n % i == 0) { + isPrime = false; + break; + } + } + } + if (isPrime) + cout << n << " is a prime number"; + else + cout << n << " is not a prime number"; + + return 0; +} From a340c99c98bead8124b402b7980179e35c8bfc55 Mon Sep 17 00:00:00 2001 From: Midhun Mohanan <60269061+TheGr4yhAt@users.noreply.github.com> Date: Mon, 18 Oct 2021 10:31:31 +0530 Subject: [PATCH 123/147] Create add 2 numbers --- add 2 numbers | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 add 2 numbers diff --git a/add 2 numbers b/add 2 numbers new file mode 100644 index 00000000..2b66319d --- /dev/null +++ b/add 2 numbers @@ -0,0 +1,17 @@ +#include +using namespace std; + +int main() { + double num1, num2, product; + cout << "Enter two numbers: "; + + // stores two floating point numbers in num1 and num2 respectively + cin >> num1 >> num2; + + // performs multiplication and stores the result in product variable + product = num1 * num2; + + cout << "Product = " << product; + + return 0; +} From e7326c63b9e0a4b8add3ec737fd08a13f7fd06fa Mon Sep 17 00:00:00 2001 From: Midhun Mohanan <60269061+TheGr4yhAt@users.noreply.github.com> Date: Mon, 18 Oct 2021 10:34:53 +0530 Subject: [PATCH 124/147] Create bubble_sort.cpp --- bubble_sort.cpp | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 bubble_sort.cpp diff --git a/bubble_sort.cpp b/bubble_sort.cpp new file mode 100644 index 00000000..c0345f16 --- /dev/null +++ b/bubble_sort.cpp @@ -0,0 +1,44 @@ +// C++ program for implementation of Bubble sort +#include +using namespace std; + +void swap(int *xp, int *yp) +{ + int temp = *xp; + *xp = *yp; + *yp = temp; +} + +// A function to implement bubble sort +void bubbleSort(int arr[], int n) +{ + int i, j; + for (i = 0; i < n-1; i++) + + // Last i elements are already in place + for (j = 0; j < n-i-1; j++) + if (arr[j] > arr[j+1]) + swap(&arr[j], &arr[j+1]); +} + +/* Function to print an array */ +void printArray(int arr[], int size) +{ + int i; + for (i = 0; i < size; i++) + cout << arr[i] << " "; + cout << endl; +} + +// Driver code +int main() +{ + int arr[] = {64, 34, 25, 12, 22, 11, 90}; + int n = sizeof(arr)/sizeof(arr[0]); + bubbleSort(arr, n); + cout<<"Sorted array: \n"; + printArray(arr, n); + return 0; +} + +// This code is contributed by midhun From ffbbba54e0c4bb8f4fdd0ee6314b5ed97af63f43 Mon Sep 17 00:00:00 2001 From: Midhun Mohanan <60269061+TheGr4yhAt@users.noreply.github.com> Date: Mon, 18 Oct 2021 10:48:23 +0530 Subject: [PATCH 125/147] Create sorted array.cpp --- sorted array.cpp | 52 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 sorted array.cpp diff --git a/sorted array.cpp b/sorted array.cpp new file mode 100644 index 00000000..49b1eda9 --- /dev/null +++ b/sorted array.cpp @@ -0,0 +1,52 @@ +// C++ program to merge two sorted arrays/ +#include +using namespace std; + +// Merge arr1[0..n1-1] and arr2[0..n2-1] into +// arr3[0..n1+n2-1] +void mergeArrays(int arr1[], int arr2[], int n1, + int n2, int arr3[]) +{ + int i = 0, j = 0, k = 0; + + // Traverse both array + while (i Date: Mon, 18 Oct 2021 21:25:55 +0530 Subject: [PATCH 126/147] Create Ceiling sum.cpp --- Ceiling sum.cpp | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Ceiling sum.cpp diff --git a/Ceiling sum.cpp b/Ceiling sum.cpp new file mode 100644 index 00000000..f7ea5d9c --- /dev/null +++ b/Ceiling sum.cpp @@ -0,0 +1,36 @@ +#include +using namespace std ; + +#define ff first +#define ss second +#define ull unsigned long long +#define mod 1000000007 +#define inf 1e18 +#define w(x) int x;cin>>x;while(x--) +#define f(x,y) for( x=0;x>a>>b; + s1=ceil((b-(a-1))/2)+ceil(((a-1)-a)/2); + s2=ceil((b-(a+1))/2)+ceil(((a+1)-a)/2); + // cout<<"i is "<b){ + x=s1; + } + else{ + x=s2; + } cout< Date: Mon, 18 Oct 2021 23:41:14 +0530 Subject: [PATCH 127/147] Create reverse_string.py --- reverse_string.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 reverse_string.py diff --git a/reverse_string.py b/reverse_string.py new file mode 100644 index 00000000..dd96dd23 --- /dev/null +++ b/reverse_string.py @@ -0,0 +1,15 @@ + +s=input("Enter string to be reversed: ") +def reverse(s): + if len(s) == 0: + return s + else: + return reverse(s[1:]) + s[0] + +s = "Geeksforgeeks" + +print ("The original string is : ",end="") +print (s) + +print ("The reversed string(using recursion) is : ",end="") +print (reverse(s)) From b24adae1f4e5b1f42dc756a68c864a597798bf23 Mon Sep 17 00:00:00 2001 From: Ayush Mishra <56979401+red-shadow18@users.noreply.github.com> Date: Mon, 18 Oct 2021 23:54:51 +0530 Subject: [PATCH 128/147] Create Number Guessing Game --- Number Guessing Game | 48 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Number Guessing Game diff --git a/Number Guessing Game b/Number Guessing Game new file mode 100644 index 00000000..c952fd65 --- /dev/null +++ b/Number Guessing Game @@ -0,0 +1,48 @@ +""" Number Guessing Game +---------------------------------------- +""" +import random +attempts_list = [] +def show_score(): + if len(attempts_list) <= 0: + print("There is currently no high score, it's yours for the taking!") + else: + print("The current high score is {} attempts".format(min(attempts_list))) +def start_game(): + random_number = int(random.randint(1, 10)) + print("Hello traveler! Welcome to the game of guesses!") + player_name = input("What is your name? ") + wanna_play = input("Hi, {}, would you like to play the guessing game? (Enter Yes/No) ".format(player_name)) + // Where the show_score function USED to be + attempts = 0 + show_score() + while wanna_play.lower() == "yes": + try: + guess = input("Pick a number between 1 and 10 ") + if int(guess) < 1 or int(guess) > 10: + raise ValueError("Please guess a number within the given range") + if int(guess) == random_number: + print("Nice! You got it!") + attempts += 1 + attempts_list.append(attempts) + print("It took you {} attempts".format(attempts)) + play_again = input("Would you like to play again? (Enter Yes/No) ") + attempts = 0 + show_score() + random_number = int(random.randint(1, 10)) + if play_again.lower() == "no": + print("That's cool, have a good one!") + break + elif int(guess) > random_number: + print("It's lower") + attempts += 1 + elif int(guess) < random_number: + print("It's higher") + attempts += 1 + except ValueError as err: + print("Oh no!, that is not a valid value. Try again...") + print("({})".format(err)) + else: + print("That's cool, have a good one!") +if __name__ == '__main__': + start_game() From eafea85f6c8331da1b69cc912899a70a345ee733 Mon Sep 17 00:00:00 2001 From: Abhinav Kumar Gupta <84512702+alhad-balak@users.noreply.github.com> Date: Tue, 19 Oct 2021 00:56:54 +0530 Subject: [PATCH 129/147] Create Longest Common Subsequence Used Dynamic programming to longest common subsequence between two strings of the same case. --- LongestCommonSubsequence.cpp | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 LongestCommonSubsequence.cpp diff --git a/LongestCommonSubsequence.cpp b/LongestCommonSubsequence.cpp new file mode 100644 index 00000000..e523a8e6 --- /dev/null +++ b/LongestCommonSubsequence.cpp @@ -0,0 +1,32 @@ +#include +using namespace std; +//Longest Common SubSequence +#define f(i, a, b) for (int i = a; i < b; i++) +#define vi vector + +int solve(string s1, string s2, vector> &dp) +{ + int n = s1.size() + 1, m = s2.size() + 1; + f(i, 1, n) + { + f(j, 1, m) + { + if (s1[i - 1] == s2[j - 1]) + dp[i][j] = 1 + dp[i - 1][j - 1]; + else + dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); + } + } + + return dp[n - 1][m - 1]; +} +int main() +{ + + string s1, s2; + cin >> s1 >> s2; + int n = s1.size() + 1, m = s2.size() + 1; + vector> dp(n, vector(m, 0)); + cout <<"Longest Common SubSequence: "<< solve(s1, s2, dp) << endl; + return 0; +} \ No newline at end of file From 7febe1f3b5e75da675e704c0604190f129c773e2 Mon Sep 17 00:00:00 2001 From: Abhinav Kumar Gupta <84512702+alhad-balak@users.noreply.github.com> Date: Tue, 19 Oct 2021 01:03:21 +0530 Subject: [PATCH 130/147] Create Kth Symbol Grammar Solved Kth Symbol in Grammar using recursion. In kth Symbol-in-grammar, Build a table of n rows (that indexed from 1). Let's start by writing 0 in the 1st row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10. In the kth (column) symbol in the nth row of a table of n rows is the required answer. --- KthGrammar.cpp | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 KthGrammar.cpp diff --git a/KthGrammar.cpp b/KthGrammar.cpp new file mode 100644 index 00000000..5011fe6a --- /dev/null +++ b/KthGrammar.cpp @@ -0,0 +1,34 @@ +#include +#include +using namespace std; + +int kgrammar(int n, int k) +{ + int i; + if (k > pow(2, n - 1) || k<1) + return -1; + else + { + if (n == 1) + return 1; + + int l = (k / 2) + (k % 2); + i = kgrammar(n - 1, l); + bool num; + if (k % 2 == 0) + num = 0; + else + num = 0; + if (i == 0) + return num; + else + return !num; + } +} +int main() +{ + int n,k; + cin>>n>>k; + cout << kgrammar(n,k); + return 0; +} \ No newline at end of file From facf2aab52647f323132e672e132e8a7f87258d4 Mon Sep 17 00:00:00 2001 From: Abhinav Kumar Gupta <84512702+alhad-balak@users.noreply.github.com> Date: Tue, 19 Oct 2021 01:05:40 +0530 Subject: [PATCH 131/147] Create Tower of Hanoi Solved the tower of Hanoi puzzle using recursion. The Tower of Hanoi is a mathematical game or puzzle consisting of three rods and a number of disks of various diameters, which can slide onto any rod. --- TowerOfHanoi.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 TowerOfHanoi.cpp diff --git a/TowerOfHanoi.cpp b/TowerOfHanoi.cpp new file mode 100644 index 00000000..1727ef0e --- /dev/null +++ b/TowerOfHanoi.cpp @@ -0,0 +1,29 @@ +#include +using namespace std; + +int ToH(int n, char s = 'S', char d = 'D', char h = 'H') //Represented as No. of plate, Source's plate, destination's plate, helper's plate +{ + static int count = 0; + if (n == 1) + { + cout << "Moving " << n << "th plate from " << s << " to " << d << ".\n"; + count++; + return 0; + } + ToH(n - 1, s, h, d); + cout << "Moving " << n << "th plate from " << s << " to " << d << ".\n"; + count++; + ToH(n - 1, h, d, s); + return count; +} + +int main() +{ + int num; + cout<<"Total number of Plates: "; + cin>>num; + long long int cnt = ToH(num); + cout<<"\nFor "< Date: Tue, 19 Oct 2021 02:10:51 +0530 Subject: [PATCH 132/147] Create Graph_BFS --- Graph_BFS | 105 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 Graph_BFS diff --git a/Graph_BFS b/Graph_BFS new file mode 100644 index 00000000..dc28950e --- /dev/null +++ b/Graph_BFS @@ -0,0 +1,105 @@ +#include +using namespace std; + +#define ll long long +#define pb push_back +#define mp make_pair +#define pr pair +#define vt vector +#define mii map +#define pqb priority_queue +#define pqs priority_queue > +#define mod 1000000007 +#define inf 1e18 +#define w(x) int x; cin>>x; while(x--) + +void print(int** edges, int n, int sv, bool* visited) { + cout << sv << "\n"; + visited[sv] = true; + for (int i = 0; i < n; ++i) + { + if (i == sv) { + continue; + } + if (edges[sv][i] == 1) +{ if (visited[i]) { + continue; + } + print(edges, n, i, visited); + } + } +} + + +void printBFS(int** edges, int n, int sv) { + queue pendingVertices; + bool * visited = new bool[n]; + for (int i = 0; i < n; ++i) + { + visited[i] = false; + } + pendingVertices.push(sv); + visited[sv] = true; + while (!pendingVertices.empty()) { + int currvertex = pendingVertices.front(); + pendingVertices.pop(); + cout << currvertex << "\n"; + for (int i = 0; i < n; ++i) + { + if (i == currvertex) { + continue; + } + if (edges[currvertex][i] == 1 && !visited[i]) { + pendingVertices.push(i); + visited[i] = true; + } + } + } +} + +void solve() +{ + ios_base::sync_with_stdio(0); cin.tie(0); +#ifndef ONLINE_JUDGE + freopen("input.txt", "r", stdin); + freopen("output.txt", "w", stdout); +#endif + int n, e; cin >> n >> e; + int** edges = new int*[n]; + for (int i = 0; i < n; ++i) + { + edges[i] = new int[n]; + for (int j = 0; j < n; ++j) + { + edges[i][j] = 0; + } + } + for (int i = 0; i < e; ++i) + { + int f, s; cin >> f >> s; + edges[f][s] = 1; + edges[s][f] = 1; + } + bool* visited = new bool[n]; + for (int i = 0; i < n; ++i) + { + visited[i] = false; + } + //print(edges, n, 0, visited); + printBFS(edges, n, 0); + delete [] visited; + for (int i = 0; i < n; ++i) + { + delete [] edges[i]; + } + delete [] edges; + + + +} + +int main() +{ + solve(); + return 0; +} From 51f1fe941862c8301175de84c3400cbf25c73628 Mon Sep 17 00:00:00 2001 From: Saurabh Siddharth <82315193+Sau2001rabh@users.noreply.github.com> Date: Tue, 19 Oct 2021 03:32:41 +0530 Subject: [PATCH 133/147] Boruvka's algorithm MST Solved problem of minimum spanning tree of a given connected, undirected and weighted graph using a greedy algorithm named Boruvka's algorithm. --- boruvka's-algorithm.cpp | 168 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 168 insertions(+) create mode 100644 boruvka's-algorithm.cpp diff --git a/boruvka's-algorithm.cpp b/boruvka's-algorithm.cpp new file mode 100644 index 00000000..0266e16a --- /dev/null +++ b/boruvka's-algorithm.cpp @@ -0,0 +1,168 @@ +#include + +struct Edge +{ + int src, dest, weight; +}; + +struct Graph +{ + int V, E; + Edge* edge; +}; + +struct subset +{ + int parent; + int rank; +}; + +int find(struct subset subsets[], int i); +void Union(struct subset subsets[], int x, int y); + + +void boruvkaMST(struct Graph* graph) +{ + int V = graph->V, E = graph->E; + Edge *edge = graph->edge; + + struct subset *subsets = new subset[V]; + + int *cheapest = new int[V]; + + for (int v = 0; v < V; ++v) + { + subsets[v].parent = v; + subsets[v].rank = 0; + cheapest[v] = -1; + } + + int numTrees = V; + int MSTweight = 0; + + while (numTrees > 1) + { + for (int v = 0; v < V; ++v) + { + cheapest[v] = -1; + } + for (int i=0; i edge[i].weight) + cheapest[set1] = i; + + if (cheapest[set2] == -1 || + edge[cheapest[set2]].weight > edge[i].weight) + cheapest[set2] = i; + } + } + + + for (int i=0; iV = V; + graph->E = E; + graph->edge = new Edge[E]; + return graph; +} + +int find(struct subset subsets[], int i) +{ + if (subsets[i].parent != i) + subsets[i].parent = + find(subsets, subsets[i].parent); + + return subsets[i].parent; +} + +void Union(struct subset subsets[], int x, int y) +{ + int xroot = find(subsets, x); + int yroot = find(subsets, y); + + if (subsets[xroot].rank < subsets[yroot].rank) + subsets[xroot].parent = yroot; + else if (subsets[xroot].rank > subsets[yroot].rank) + subsets[yroot].parent = xroot; + else + { + subsets[yroot].parent = xroot; + subsets[xroot].rank++; + } +} + +int main() +{ + int V = 4; // Number of vertices in graph + int E = 5; // Number of edges in graph + struct Graph* graph = createGraph(V, E); + + + // add edge 0-1 + graph->edge[0].src = 0; + graph->edge[0].dest = 1; + graph->edge[0].weight = 10; + + // add edge 0-2 + graph->edge[1].src = 0; + graph->edge[1].dest = 2; + graph->edge[1].weight = 6; + + // add edge 0-3 + graph->edge[2].src = 0; + graph->edge[2].dest = 3; + graph->edge[2].weight = 5; + + // add edge 1-3 + graph->edge[3].src = 1; + graph->edge[3].dest = 3; + graph->edge[3].weight = 15; + + // add edge 2-3 + graph->edge[4].src = 2; + graph->edge[4].dest = 3; + graph->edge[4].weight = 4; + + boruvkaMST(graph); + + return 0; +} + + +/*Output: +Edge 0-3 included in MST +Edge 0-1 included in MST +Edge 2-3 included in MST +Weight of MST is 19*/ \ No newline at end of file From ad8e6db6d05e15dec8e75c4df595757cf11c5e63 Mon Sep 17 00:00:00 2001 From: shangchi9 <92801644+shangchi9@users.noreply.github.com> Date: Tue, 19 Oct 2021 20:10:19 +0530 Subject: [PATCH 134/147] Create floyd_warshall.cpp --- floyd_warshall.cpp | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 floyd_warshall.cpp diff --git a/floyd_warshall.cpp b/floyd_warshall.cpp new file mode 100644 index 00000000..b416d178 --- /dev/null +++ b/floyd_warshall.cpp @@ -0,0 +1,43 @@ +#include +#include +using namespace std; + +#define INF 10000 + +vector> floyd_warshall(vector> graph){ + + vector> dist(graph); + int V = graph.size(); + + for(int k=0;k> graph = { + {0,INF,-2,INF}, + {4,0,3,INF}, + {INF,INF,0,2}, + {INF,-1,INF,0} + }; + + auto result = floyd_warshall(graph); + + for(int i=0;i Date: Tue, 19 Oct 2021 22:00:12 +0530 Subject: [PATCH 135/147] added sort array with squares cpp code --- Sort array with squares.cpp | 39 +++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Sort array with squares.cpp diff --git a/Sort array with squares.cpp b/Sort array with squares.cpp new file mode 100644 index 00000000..5fb5a424 --- /dev/null +++ b/Sort array with squares.cpp @@ -0,0 +1,39 @@ +vector Solution::solve(vector &arr) { + int mid=0; + for(int i=0;i=0) + { + mid=i; + break; + } + } + int i=mid-1,j=mid; + vectorres(arr.size()); + int k=0; + while(i>=0 && j=0) + { + res[k++]=arr[i]*arr[i]; + i--; + } + while(j Date: Tue, 19 Oct 2021 22:07:40 +0530 Subject: [PATCH 136/147] Added find permutation --- Find Permutation.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Find Permutation.cpp diff --git a/Find Permutation.cpp b/Find Permutation.cpp new file mode 100644 index 00000000..76706bba --- /dev/null +++ b/Find Permutation.cpp @@ -0,0 +1,21 @@ +vector Solution::findPerm(const string A, int B) { + + vector res; + int max = B; + int min =1; + for(int i=B-2 ; i>=0 ; i--){ + if(A[i] == 'I'){ + res.push_back(max); + max--; + } + else{ + res.push_back(min); + min++; + } + } + res.push_back(max); + reverse(res.begin(),res.end()); + return res; + + +} From 7599fe89613c9e5b77d37e5f910deb21f857b643 Mon Sep 17 00:00:00 2001 From: tanishaPandey-2019 <68120087+tanishaPandey-2019@users.noreply.github.com> Date: Tue, 19 Oct 2021 22:12:41 +0530 Subject: [PATCH 137/147] Added code for Total Moves For Bishop --- Total Moves For Bishop.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Total Moves For Bishop.cpp diff --git a/Total Moves For Bishop.cpp b/Total Moves For Bishop.cpp new file mode 100644 index 00000000..352a0768 --- /dev/null +++ b/Total Moves For Bishop.cpp @@ -0,0 +1,11 @@ +int Solution::solve(int A, int B) { + + int c = 0; + + c = c + min(8 - A,8 - B); + c = c + min(8 - A, B -1); + c += min(A - 1, 8 - B); + c += min(A - 1, B - 1); + + return c; +} From 71e1798e35e999cba4279fc5fa097534265ca53e Mon Sep 17 00:00:00 2001 From: Mitanshu Holkar Date: Tue, 19 Oct 2021 22:37:54 +0530 Subject: [PATCH 138/147] Create FloydWarshall.cpp --- FloydWarshall.cpp | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 FloydWarshall.cpp diff --git a/FloydWarshall.cpp b/FloydWarshall.cpp new file mode 100644 index 00000000..cbe2dcde --- /dev/null +++ b/FloydWarshall.cpp @@ -0,0 +1,47 @@ +#include +using namespace std; + +#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); +#define int long long +#define endl "\n" + +const int INF = 1e18; +const int MAXN = 1005; +int dist[MAXN][MAXN]; + +int n, m; + +int32_t main() +{ + cin>>n>>m; + for(int i = 1; i<=m; i++) + { + int u, v, d; + cin>>u>>v>>d; + + dist[u][v] = d; + dist[v][u] = d; + } + + for(int i = 1; i<=n; i++) + { + for(int j = 1; j<=n; j++) + { + if(i == j) dist[i][j] = 0; + else if(dist[i][j] == 0) dist[i][j] = INF; + } + } + + for(int k = 1; k<=n; k++) + { + for(int i = 1; i<=n; i++) + { + for(int j = 1; j<=n; j++) + { + dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]); + } + } + } + + // dist matrix will give you all pair shortest path possible in graph +} From 99211a00103d85b0f6e00c2401a674925e7ec269 Mon Sep 17 00:00:00 2001 From: Mitanshu Holkar Date: Tue, 19 Oct 2021 22:42:35 +0530 Subject: [PATCH 139/147] Create Prim's_Algo.cpp --- Prim's_Algo.cpp | 80 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 Prim's_Algo.cpp diff --git a/Prim's_Algo.cpp b/Prim's_Algo.cpp new file mode 100644 index 00000000..c64e0563 --- /dev/null +++ b/Prim's_Algo.cpp @@ -0,0 +1,80 @@ +// Prim's Algorithm in C++ + +#include +#include +using namespace std; + +#define INF 9999999 + +// number of vertices in grapj +#define V 5 + +// create a 2d array of size 5x5 +//for adjacency matrix to represent graph + +int G[V][V] = { + {0, 9, 75, 0, 0}, + {9, 0, 95, 19, 42}, + {75, 95, 0, 51, 66}, + {0, 19, 51, 0, 31}, + {0, 42, 66, 31, 0}}; + +int main() { + int no_edge; // number of edge + + // create a array to track selected vertex + // selected will become true otherwise false + int selected[V]; + + // set selected false initially + memset(selected, false, sizeof(selected)); + + // set number of edge to 0 + no_edge = 0; + + // the number of egde in minimum spanning tree will be + // always less than (V -1), where V is number of vertices in + //graph + + // choose 0th vertex and make it true + selected[0] = true; + + int x; // row number + int y; // col number + + // print for edge and weight + cout << "Edge" + << " : " + << "Weight"; + cout << endl; + while (no_edge < V - 1) { + //For every vertex in the set S, find the all adjacent vertices + // , calculate the distance from the vertex selected at step 1. + // if the vertex is already in the set S, discard it otherwise + //choose another vertex nearest to selected vertex at step 1. + + int min = INF; + x = 0; + y = 0; + + for (int i = 0; i < V; i++) { + if (selected[i]) { + for (int j = 0; j < V; j++) { + if (!selected[j] && G[i][j]) { // not in selected and there is an edge + if (min > G[i][j]) { + min = G[i][j]; + x = i; + y = j; + } + } + } + } + } + cout << x << " - " << y << " : " << G[x][y]; + cout << endl; + selected[y] = true; + no_edge++; + } + + return 0; +} From ec35457735613da148b04ca24b706617d97ea734 Mon Sep 17 00:00:00 2001 From: Shivam0507Dubey <91928163+Shivam0507Dubey@users.noreply.github.com> Date: Wed, 20 Oct 2021 09:24:43 +0530 Subject: [PATCH 140/147] Create ternary search --- ternary search | 88 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 ternary search diff --git a/ternary search b/ternary search new file mode 100644 index 00000000..3b028ee3 --- /dev/null +++ b/ternary search @@ -0,0 +1,88 @@ +// C++ program to illustrate +// recursive approach to ternary search +#include +using namespace std; + +// Function to perform Ternary Search +int ternarySearch(int l, int r, int key, int ar[]) +{ + if (r >= l) { + + // Find the mid1 and mid2 + int mid1 = l + (r - l) / 3; + int mid2 = r - (r - l) / 3; + + // Check if key is present at any mid + if (ar[mid1] == key) { + return mid1; + } + if (ar[mid2] == key) { + return mid2; + } + + // Since key is not present at mid, + // check in which region it is present + // then repeat the Search operation + // in that region + if (key < ar[mid1]) { + + // The key lies in between l and mid1 + return ternarySearch(l, mid1 - 1, key, ar); + } + else if (key > ar[mid2]) { + + // The key lies in between mid2 and r + return ternarySearch(mid2 + 1, r, key, ar); + } + else { + + // The key lies in between mid1 and mid2 + return ternarySearch(mid1 + 1, mid2 - 1, key, ar); + } + } + + // Key not found + return -1; +} + +// Driver code +int main() +{ + int l, r, p, key; + + // Get the array + // Sort the array if not sorted + int ar[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + + // Starting index + l = 0; + + // length of array + r = 9; + + // Checking for 5 + + // Key to be searched in the array + key = 5; + + // Search the key using ternarySearch + p = ternarySearch(l, r, key, ar); + + // Print the result + cout << "Index of " << key + << " is " << p << endl; + + // Checking for 50 + + // Key to be searched in the array + key = 50; + + // Search the key using ternarySearch + p = ternarySearch(l, r, key, ar); + + // Print the result + cout << "Index of " << key + << " is " << p << endl; +} + + From b3ba5908547b176a9fe8884236df176674bba07f Mon Sep 17 00:00:00 2001 From: Shivam0507Dubey <91928163+Shivam0507Dubey@users.noreply.github.com> Date: Wed, 20 Oct 2021 09:26:46 +0530 Subject: [PATCH 141/147] Create lucas theorem --- lucas theorem | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 lucas theorem diff --git a/lucas theorem b/lucas theorem new file mode 100644 index 00000000..ab50f9b9 --- /dev/null +++ b/lucas theorem @@ -0,0 +1,57 @@ +// A Lucas Theorem based solution to compute nCr % p +#include +using namespace std; + +// Returns nCr % p. In this Lucas Theorem based program, +// this function is only called for n < p and r < p. +int nCrModpDP(int n, int r, int p) +{ + // The array C is going to store last row of + // pascal triangle at the end. And last entry + // of last row is nCr + int C[r+1]; + memset(C, 0, sizeof(C)); + + C[0] = 1; // Top row of Pascal Triangle + + // One by constructs remaining rows of Pascal + // Triangle from top to bottom + for (int i = 1; i <= n; i++) + { + // Fill entries of current row using previous + // row values + for (int j = min(i, r); j > 0; j--) + + // nCj = (n-1)Cj + (n-1)C(j-1); + C[j] = (C[j] + C[j-1])%p; + } + return C[r]; +} + +// Lucas Theorem based function that returns nCr % p +// This function works like decimal to binary conversion +// recursive function. First we compute last digits of +// n and r in base p, then recur for remaining digits +int nCrModpLucas(int n, int r, int p) +{ +// Base case +if (r==0) + return 1; + +// Compute last digits of n and r in base p +int ni = n%p, ri = r%p; + +// Compute result for last digits computed above, and +// for remaining digits. Multiply the two results and +// compute the result of multiplication in modulo p. +return (nCrModpLucas(n/p, r/p, p) * // Last digits of n and r + nCrModpDP(ni, ri, p)) % p; // Remaining digits +} + +// Driver program +int main() +{ + int n = 1000, r = 900, p = 13; + cout << "Value of nCr % p is " << nCrModpLucas(n, r, p); + return 0; +} From 7fd1a6de1476b0bd7d6ed0e4ca6b625732e17f05 Mon Sep 17 00:00:00 2001 From: Shivam0507Dubey <91928163+Shivam0507Dubey@users.noreply.github.com> Date: Wed, 20 Oct 2021 09:28:18 +0530 Subject: [PATCH 142/147] Create sieve of eratosthenes --- sieve of eratosthenes | 49 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 sieve of eratosthenes diff --git a/sieve of eratosthenes b/sieve of eratosthenes new file mode 100644 index 00000000..ba18e646 --- /dev/null +++ b/sieve of eratosthenes @@ -0,0 +1,49 @@ +// C++ program to print all primes +// smaller than or equal to +// n using Sieve of Eratosthenes +#include +using namespace std; + +void SieveOfEratosthenes(int n) +{ + // Create a boolean array + // "prime[0..n]" and initialize + // all entries it as true. + // A value in prime[i] will + // finally be false if i is + // Not a prime, else true. + bool prime[n + 1]; + memset(prime, true, sizeof(prime)); + + for (int p = 2; p * p <= n; p++) + { + // If prime[p] is not changed, + // then it is a prime + if (prime[p] == true) + { + // Update all multiples + // of p greater than or + // equal to the square of it + // numbers which are multiple + // of p and are less than p^2 + // are already been marked. + for (int i = p * p; i <= n; i += p) + prime[i] = false; + } + } + + // Print all prime numbers + for (int p = 2; p <= n; p++) + if (prime[p]) + cout << p << " "; +} + +// Driver Code +int main() +{ + int n = 30; + cout << "Following are the prime numbers smaller " + << " than or equal to " << n << endl; + SieveOfEratosthenes(n); + return 0; +} From e3b90cea049c8897db0ec410e9a89c1f8e88971b Mon Sep 17 00:00:00 2001 From: Shivam0507Dubey <91928163+Shivam0507Dubey@users.noreply.github.com> Date: Wed, 20 Oct 2021 09:29:13 +0530 Subject: [PATCH 143/147] Create segmented sieve --- segmented sieve | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 segmented sieve diff --git a/segmented sieve b/segmented sieve new file mode 100644 index 00000000..70d5feeb --- /dev/null +++ b/segmented sieve @@ -0,0 +1,31 @@ +// This functions finds all primes smaller than 'limit' +// using simple sieve of eratosthenes. +void simpleSieve(int limit) +{ + // Create a boolean array "mark[0..limit-1]" and + // initialize all entries of it as true. A value + // in mark[p] will finally be false if 'p' is Not + // a prime, else true. + bool mark[limit]; + for(int i = 0; i Date: Sat, 23 Oct 2021 18:33:44 -0500 Subject: [PATCH 144/147] Add files via upload --- README_es.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 README_es.md diff --git a/README_es.md b/README_es.md new file mode 100644 index 00000000..6af1631e --- /dev/null +++ b/README_es.md @@ -0,0 +1,7 @@ +# Algoritmos competitivos de programación + +Este repositorio es acerca de: + +Implementación de algoritmos aprendidos en C++ y utilizados mientras se realiza programación competitiva. + +Puedes agregar libremente tus implementaciones o simplemente mejorar las anteriores. \ No newline at end of file From 8f9226574c1d5d4fe00e85e0ffec9b1e83e485c0 Mon Sep 17 00:00:00 2001 From: DevGDL <88908162+devGuadalajara@users.noreply.github.com> Date: Sat, 23 Oct 2021 18:53:22 -0500 Subject: [PATCH 145/147] Add files via upload Added greddy algorithms minimumCoins.cpp minimumProductSubset.cpp statusCheck.cpp --- minimumCoins.cpp | 41 ++++++++++ minimumProductSubset.cpp | 59 ++++++++++++++ statusCheck.cpp | 164 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 264 insertions(+) create mode 100644 minimumCoins.cpp create mode 100644 minimumProductSubset.cpp create mode 100644 statusCheck.cpp diff --git a/minimumCoins.cpp b/minimumCoins.cpp new file mode 100644 index 00000000..e231d251 --- /dev/null +++ b/minimumCoins.cpp @@ -0,0 +1,41 @@ +// Given a value V and the list of available denomination of money, +// find minimum number of coins and/or notes needed to make the change. + +#include +using namespace std; + +// All denominations of Indian Currency +int deno[] = { 1, 2, 5, 10, 20, + 50, 100, 500, 1000 }; +int n = sizeof(deno) / sizeof(deno[0]); + +vector calculate(int V) +{ + sort(deno, deno + n); + vector ans; + + for (int i = n - 1; i >= 0; i--) { + + while (V >= deno[i]) { + V -= deno[i]; + ans.push_back(deno[i]); + } + } + return ans; + //for (int i = 0; i < ans.size(); i++) + //cout << ans[i] << " "; +} + +int main() +{ + int n; + cout<<"Enter the monitory value: "; + cin>>n; + cout << "Following is minimal number of change for " << n + << ": "; + vector ans = calculate(n); + for(auto i: ans) + cout< +using namespace std; + +int calculate(int a[], int n) +{ + if (n == 1) + return a[0]; + + int max_neg = INT_MIN; + int min_pos = INT_MAX; + int count_neg = 0, count_zero = 0; + int prod = 1; + for (int i = 0; i < n; i++) { + + + if (a[i] == 0) { + count_zero++; + continue; + } + + if (a[i] < 0) { + count_neg++; + max_neg = max(max_neg, a[i]); + } + + if (a[i] > 0) + min_pos = min(min_pos, a[i]); + + prod = prod * a[i]; + } + + if (count_zero == n || + (count_neg == 0 && count_zero > 0)) + return 0; + + if (count_neg == 0) + return min_pos; + + if (!(count_neg & 1) && count_neg != 0) { + prod = prod / max_neg; + } + + return prod; +} + +int main() +{ + int n; + cout<<"Enter size of array: "; + cin>>n; + int a[n]; + cout<<"\nEnter array elements: "; + for(int i=0;i>a[i]; + cout << "\nAnswer: "< + +using namespace std; + +void swap(int* a, int* b){ + int t = *a; + *a = *b; + *b = t; +} + +void swapc(char* a, char* b){ + char t = *a; + *a = *b; + *b = t; +} + +void heapify(int start[], int finish[], char status[], int n, int i){ + int largest = i; + int l = 2*i + 1; + int r = 2*i + 2; + + if (l < n && finish[l] > finish[largest]) + largest = l; + + if (r < n && finish[r] > finish[largest]) + largest = r; + + if (largest != i){ + swap(&finish[i], &finish[largest]); + swap(&start[i], &start[largest]); + swapc(&status[i], &status[largest]); + heapify(start, finish, status, n, largest); + } +} + +void sort(int start[], int finish[], char status[], int n){ + for (int i = n / 2 - 1; i >= 0; i--) + heapify(start, finish, status, n, i); + + for (int i=n-1; i>=0; i--){ + swap(&finish[0], &finish[i]); + swap(&start[0], &start[i]); + swapc(&status[0], &status[i]); + heapify(start, finish, status, i, 0); + } +} + +int maxFinishTime(int finish[], int n){ + int max = 0; + for(int i=0;i max) + max = finish[i]; + return max; +} + +int status_check(int s[], int f[], char st[], int n) { + + //find the maximum finish time among all process + int N = maxFinishTime(f, n) + 1; + + //count stores whether status_check() is invoked, if yes count[i] = 1, else count[i] = 0 + int count[N]; + + //initialize count to 0 initially + for(int i=0;i=0;k--){ + if(count[k] == 1){ + lastStatusCheck = k; + break; + } + } + + if(pid[i] == 0){ + count[f[i]] = 1; + timeF = f[i]; + pid[i] = 1; + pid[j] = 1; + } + + else if(pid[j] == 0 && timeF != lastStatusCheck){ + count[f[j]] = 1; + timeF = f[j]; + pid[j] = 1; + } + } + + //overlap + else if(f[i] >= s[j] && s[i] != s[j]){ + //if status is S i.e. 'Sensitive' apply status_check() + if(timeF < f[i]){ + count[f[i]] = 1; + timeF = f[j]; + pid[i] = 1; + pid[j] = 1; + } + } + + //no overlap + else{ + if(timeF < f[i] && s[i] != s[j]){ + count[f[i]] = 1; + timeF = f[i]; + pid[i] = 1; + pid[j] = 1; + } + } + i++; + } + cout<>n; + int start[n]; + int finish[n]; + char status[n]; + for(int i=0;i>start[i] >> finish[i] >> status[i]; + } + + //sort in non-decreasing order of finish time + sort(start, finish, status, n); + + //check for conflict + int check = status_check(start, finish, status, n); + + cout<<"Number of times status_check() is invoked is %d"< Date: Sat, 23 Oct 2021 18:57:56 -0500 Subject: [PATCH 146/147] Add files via upload image-proccesing Algos --- RGBtoGrey.cpp | 21 ++++++++++++++++++ blurImage.cpp | 31 ++++++++++++++++++++++++++ createColoredImage.cpp | 48 ++++++++++++++++++++++++++++++++++++++++ createGaussianFilter.cpp | 43 +++++++++++++++++++++++++++++++++++ 4 files changed, 143 insertions(+) create mode 100644 RGBtoGrey.cpp create mode 100644 blurImage.cpp create mode 100644 createColoredImage.cpp create mode 100644 createGaussianFilter.cpp diff --git a/RGBtoGrey.cpp b/RGBtoGrey.cpp new file mode 100644 index 00000000..d99b2b86 --- /dev/null +++ b/RGBtoGrey.cpp @@ -0,0 +1,21 @@ +#include + +using namespace std; +using namespace cv; + +int main() +{ + Mat RGBimage=("cat.jpg"); + Mat Greyimage(RGBimage.rows,RGBimage.cols,CV_8UC1); + for(int i=0;i(i,j)=(RGBimage.at(i,j)[0]+RGBimage.at(i,j)[1]+RGBimage.at(i,j)[2])/3; + } + } + imshow("RGBimage",RGBimage); + imshow("Greyimage",Greyimage); + waitKey(0); + return 0; +} diff --git a/blurImage.cpp b/blurImage.cpp new file mode 100644 index 00000000..5bf60524 --- /dev/null +++ b/blurImage.cpp @@ -0,0 +1,31 @@ +// Using OpenCV to blur an image. + +#include +#include +#include +#include +#include + +using namespace cv; +using namespace std; + +int main() +{ + Mat image = imread("jeep.jpg", CV_LOAD_IMAGE_UNCHANGED); + + // Check for no data + if (! image.data ) + { + cout << "Could not open or find the image.\n"; + return -1; // unsuccessful + } + + blur(image,image,Size(10,10)); + + namedWindow( "jeep", CV_WINDOW_AUTOSIZE ); + imshow( "jeep", image ); + + waitKey(0); + + return 0; +} diff --git a/createColoredImage.cpp b/createColoredImage.cpp new file mode 100644 index 00000000..25a33a2e --- /dev/null +++ b/createColoredImage.cpp @@ -0,0 +1,48 @@ +// Create a coloured image in C++ using OpenCV. + +#include "opencv2/highgui/highgui.hpp" +using namespace cv; +using namespace std; + +int main() +{ + // To create an image + // CV_8UC3 depicts : (3 channels,8 bit image depth + // Height = 500 pixels, Width = 1000 pixels + // (0, 0, 100) assigned for Blue, Green and Red + // plane respectively. + // So the image will appear red as the red + // component is set to 100. + Mat img(500, 1000, CV_8UC3, Scalar(0,0, 100)); + + // check whether the image is loaded or not + if (img.empty()) + { + cout << "\n Image not created. You" + " have done something wrong. \n"; + return -1; // Unsuccessful. + } + + // first argument: name of the window + // second argument: flag- types: + // WINDOW_NORMAL If this is set, the user can + // resize the window. + // WINDOW_AUTOSIZE If this is set, the window size + // is automatically adjusted to fit + // the displayed image, and you cannot + // change the window size manually. + // WINDOW_OPENGL If this is set, the window will be + // created with OpenGL support. + namedWindow("A_good_name", CV_WINDOW_AUTOSIZE); + + // first argument: name of the window + // second argument: image to be shown(Mat object) + imshow("A_good_name", img); + + waitKey(0); //wait infinite time for a keypress + + // destroy the window with the name, "MyWindow" + destroyWindow("A_good_name"); + + return 0; +} diff --git a/createGaussianFilter.cpp b/createGaussianFilter.cpp new file mode 100644 index 00000000..0e7ab6f9 --- /dev/null +++ b/createGaussianFilter.cpp @@ -0,0 +1,43 @@ +// Generate Gaussian filter + +#include +#include +#include +using namespace std; + +// Function to create Gaussian filter +void FilterCreation(double GKernel[][5]) +{ + // intialising standard deviation to 1.0 + double sigma = 1.0; + double r, s = 2.0 * sigma * sigma; + + // sum is for normalization + double sum = 0.0; + + // generating 5x5 kernel + for (int x = -2; x <= 2; x++) { + for (int y = -2; y <= 2; y++) { + r = sqrt(x * x + y * y); + GKernel[x + 2][y + 2] = (exp(-(r * r) / s)) / (M_PI * s); + sum += GKernel[x + 2][y + 2]; + } + } + + // normalising the Kernel + for (int i = 0; i < 5; ++i) + for (int j = 0; j < 5; ++j) + GKernel[i][j] /= sum; +} + +int main() +{ + double GKernel[5][5]; + FilterCreation(GKernel); + + for (int i = 0; i < 5; ++i) { + for (int j = 0; j < 5; ++j) + cout << GKernel[i][j] << "\t"; + cout << endl; + } +} From 8fa857a1ab6b09e0baee852b65e1ce5d565258ee Mon Sep 17 00:00:00 2001 From: DevGDL <88908162+devGuadalajara@users.noreply.github.com> Date: Sat, 23 Oct 2021 19:27:41 -0500 Subject: [PATCH 147/147] Disjoint Set Union algos --- naive_dsu.cpp | 75 +++++++++++++++++++++++++++++++++ path_compression_in_dsu.cpp | 75 +++++++++++++++++++++++++++++++++ union_by_rank_in_dsu.cpp | 84 +++++++++++++++++++++++++++++++++++++ union_by_size_in_dsu.cpp | 81 +++++++++++++++++++++++++++++++++++ 4 files changed, 315 insertions(+) create mode 100644 naive_dsu.cpp create mode 100644 path_compression_in_dsu.cpp create mode 100644 union_by_rank_in_dsu.cpp create mode 100644 union_by_size_in_dsu.cpp diff --git a/naive_dsu.cpp b/naive_dsu.cpp new file mode 100644 index 00000000..5686fcc0 --- /dev/null +++ b/naive_dsu.cpp @@ -0,0 +1,75 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace std; +const int MAX_SIZE = 1e5+7; //It can be increased to maximum global size available +int parent[MAX_SIZE]; + +void make_set(int val) +{ + parent[val] = val; +} + +int find_parent(int val) +{ + while (parent[val] != val) { + parent[val] = parent[parent[val]]; + val = parent[val]; + } + return val; +} + +void union_set(int x, int y) +{ + x = find_parent(x); + y = find_parent(y); + if(x != y) + { + parent[y] = x; + } +} + +int main() +{ + int n = 5; + int elements[n]; + for(int i=0;i +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace std; +const int MAX_SIZE = 1e5+7; //It can be increased to maximum global size available +int parent[MAX_SIZE]; + +void make_set(int val) +{ + parent[val] = val; +} + +int find_parent_path_compression(int val) +{ + if(val == parent[val]) + { + return val; + } + return parent[val] = find_parent_path_compression(parent[val]); +} + +void union_set(int x, int y) +{ + x = find_parent_path_compression(x); + y = find_parent_path_compression(y); + if(x != y) + { + parent[y] = x; + } +} + +int main() +{ + int n = 5; + int elements[n]; + for(int i=0;i +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace std; +const int MAX_SIZE = 1e5+7; //It can be increased to maximum global size available +int parent[MAX_SIZE]; +int rank_v[MAX_SIZE]; + +void make_set(int val) +{ + parent[val] = val; + rank_v[val] = 0; +} +int find_parent_path_compression(int val) +{ + if(val == parent[val]) + { + return val; + } + return parent[val] = find_parent_path_compression(parent[val]); +} + +void union_set(int x, int y) +{ + x = find_parent_path_compression(x); + y = find_parent_path_compression(y); + if(x != y) + { + if(rank_v[x] +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace std; +const int MAX_SIZE = 1e5+7; //It can be increased to maximum global size available +int parent[MAX_SIZE]; +int size_v[MAX_SIZE]; + +void make_set(int val) +{ + parent[val] = val; + size_v[val] = 1; +} +int find_parent_path_compression(int val) +{ + if(val == parent[val]) + { + return val; + } + return parent[val] = find_parent_path_compression(parent[val]); +} + +void union_set(int x, int y) +{ + x = find_parent_path_compression(x); + y = find_parent_path_compression(y); + if(x != y) + { + if(size_v[x]