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; + } +}; diff --git a/AnagramOfStrings.java b/AnagramOfStrings.java new file mode 100644 index 00000000..6875c13b --- /dev/null +++ b/AnagramOfStrings.java @@ -0,0 +1,39 @@ +# 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 { + + 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 +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."< +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 + +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 "< +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 +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 < +#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); +} 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; +} + 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< + +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: "< 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]; +} 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/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; + + +} 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 +} 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< +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; +} 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"; + +} 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 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 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<& 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/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; +} 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 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 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 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 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."< 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 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 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; +} 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 diff --git a/Map-using-JavaScript-main.zip b/Map-using-JavaScript-main.zip new file mode 100644 index 00000000..ebb1b0ad Binary files /dev/null and b/Map-using-JavaScript-main.zip differ diff --git a/MatrixAddition.java b/MatrixAddition.java new file mode 100644 index 00000000..2cf4b4c0 --- /dev/null +++ b/MatrixAddition.java @@ -0,0 +1,49 @@ +#include +using namespace std; + +int main() +{ + int r, c, a[100][100], b[100][100], sum[100][100], i, j; + + cout << "Enter number of rows (between 1 and 100): "; + cin >> 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; +} 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; +} diff --git a/Modern b/Modern new file mode 100644 index 00000000..71ba3964 --- /dev/null +++ b/Modern @@ -0,0 +1,75 @@ +Hi + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Bye 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() 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 : "< +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< +// #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!!!"< 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() 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; +} diff --git a/Prime_factors.cpp b/Prime_factors.cpp new file mode 100644 index 00000000..61bdd808 --- /dev/null +++ b/Prime_factors.cpp @@ -0,0 +1,35 @@ +#include + +using namespace std; + +int main() +{ + 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; +} 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> dividend; + + cout << "Enter divisor: "; + cin >> divisor; + + quotient = dividend / divisor; + remainder = dividend % divisor; + + cout << "Quotient = " << quotient << endl; + cout << "Remainder = " << remainder; + + return 0; +} 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 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 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/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; +} diff --git a/Recursive factorials b/Recursive factorials new file mode 100644 index 00000000..2d3cb898 --- /dev/null +++ b/Recursive factorials @@ -0,0 +1,30 @@ +/*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; + +int factorial(int n); + +int main() +{ + int n; + + cout << "Enter a positive integer: "; + cin >> n; + + cout << "Factorial of " << n << " = " << factorial(n); + + return 0; +} + +int factorial(int n) +{ + if(n > 1) + return n * factorial(n - 1); + else + return 1; +} 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; +} + 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 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 +#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; +} 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] +} 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; +} 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; +} 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; +} 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 "< +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; +} 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); +} 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; +} + 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/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 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(); + } + +} 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; +} 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; +} 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(); + } +}; 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/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; + } + } +} 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/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/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 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(); + } +} 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 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"< +#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"< +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 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); + } +}; 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 +#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; + } +} 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 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/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"<& heights, int br, int lad) { + priority_queue,greater> que; + int i=0; + int diff; + while(que.size()0) + { + if(!que.empty() && que.top() + +// 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; +} diff --git a/fibonacciDP.cpp b/fibonacciDP.cpp new file mode 100644 index 00000000..cb212a0c --- /dev/null +++ b/fibonacciDP.cpp @@ -0,0 +1,20 @@ +#include +using namespace std; +int fib(int x) { + if((x==1)||(x==0)) { + return(x); + }else { + return(fib(x-1)+fib(x-2)); + } +} +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; +} 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 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 +#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 ; +} 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() 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)) 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') 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); +} + 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); +} 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; +} 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/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; +} + 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 +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< +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 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; +} 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 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< +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 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: "< +# 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<<"*********************************************"< +#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 +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; +} 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(); + } +} 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 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< +#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 + +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 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 +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; +} 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; +} 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; +} 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; + } +}; 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; + } + + } +}; 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; +} 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; +} 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; +} 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)) 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; + } +}; 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() 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 +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< +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; +} 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] +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; +} 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 +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:"< +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 + +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"<= 0; i--) { + + System.out.print(allSen[i] + " "); + + } + } +} 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<>& 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; + } +}; 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 +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; +} 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; +} + + 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 diff --git a/two_sum.cpp b/two_sum.cpp new file mode 100644 index 00000000..8096ce4e --- /dev/null +++ b/two_sum.cpp @@ -0,0 +1,21 @@ +class Solution { +public: +vector 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; +} + + +}; diff --git a/union_by_rank_in_dsu.cpp b/union_by_rank_in_dsu.cpp new file mode 100644 index 00000000..46e79571 --- /dev/null +++ b/union_by_rank_in_dsu.cpp @@ -0,0 +1,84 @@ +#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]; +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]