diff --git a/3SumClosest.cpp b/3SumClosest.cpp new file mode 100644 index 0000000..bc4f4d2 --- /dev/null +++ b/3SumClosest.cpp @@ -0,0 +1,39 @@ +// Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. + +// Return the sum of the three integers. + +// You may assume that each input would have exactly one solution. + +// https://leetcode.com/problems/3sum-closest/ + +// Example 1: + +// Input: nums = [-1,2,1,-4], target = 1 +// Output: 2 +// Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). + + + +int threeSumClosest(vector& nums, int target) { + if(nums.size() < 3) return 0; + int closest = nums[0]+nums[1]+nums[2]; + sort(nums.begin(), nums.end()); + for(int first = 0 ; first < nums.size()-2 ; ++first) { + if(first > 0 && nums[first] == nums[first-1]) continue; + int second = first+1; + int third = nums.size()-1; + while(second < third) { + int curSum = nums[first]+nums[second]+nums[third]; + if(curSum == target) return curSum; + if(abs(target-curSum) target) { + --third; + } else { + ++second; + } + } + } + return closest; +} diff --git a/4Sum.cpp b/4Sum.cpp new file mode 100644 index 0000000..5e1811d --- /dev/null +++ b/4Sum.cpp @@ -0,0 +1,80 @@ +// Question- + +// Suppose we have an array of numbers. It stores n integers, there are four elements a, b, c and d in the array. We have another target value, such that a + b + c + d = target. Find all unique quadruplets in the array which satisfies the situation. So if the array is like [-1,0,1,2,0,-2] and target is 0, then the result will be [[-1, 0, 0, 1],[-2, -1, 1, 2], [-2, 0, 0, 2]] +// Input- +// [1,0,-1,0,-2,2] +// 0 +// Output- +// [[1,2,-1,-2],[0,2,0,-2],[0,1,0,-1]] + + + +#include +using namespace std; + + +class Solution { +public: + void addAll(vector < vector >& res, vector < vector >& temp){ + for(int i = 0; i < temp.size(); i++)res.push_back(temp[i]); + } + vector> fourSum(vector& nums, int target) { + sort(nums.begin(), nums.end()); + return kSum(nums, 0, 4, target); + } + vector < vector > kSum(vector & arr, int start, int k, int target){ + vector < vector > res; + if(k == 2){ + int left = start; + int right = arr.size() - 1; + vector temp(2); + while(left < right){ + if(arr[left] + arr[right] == target){ + temp[0] = arr[left]; + temp[1] = arr[right]; + res.push_back(temp); + while(left < right && arr[left] == arr[left + 1])left++; + while(left < right && arr[right] == arr[right - 1])right--; + left++; + right--; + } + else if(arr[left] + arr[right] > target)right--; + else left ++; + } + } + else{ + for(int i = start; i < (int)arr.size() - k + 1; i++){ + if(i > start && arr[i] == arr[i - 1])continue; + vector < vector > temp = kSum(arr, i + 1, k - 1, target - arr[i]); + for(int j = 0; j < temp.size(); j++){ + temp[j].push_back(arr[i]); + } + addAll(res, temp); + } + } + return res; + } +}; + + + +void print_vector(vector > v){ + cout << "["; + for(int i = 0; i v = {1,0,-1,0,-2,2}; + print_vector(ob.fourSum(v, 0)); +} diff --git a/4_Sum.cpp b/4_Sum.cpp new file mode 100644 index 0000000..ef2c579 --- /dev/null +++ b/4_Sum.cpp @@ -0,0 +1,92 @@ + + /*this code is edited by batrakeshav10 + sir please accept my pull request and guide me, + so that i can win hactoberfest tshirt */ +// Question- + +/* Suppose we have an array of numbers. It stores n integers, there are four elements a, b, c and d in the array. We have another target value, such that a + b + c + d = target. Find all the unique quadruplets in the array which satisfies the situation. So if the array is like [-1,0,1,2,0,-2] and target is 0, then the result will be [[-1, 0, 0, 1],[-2, -1, 1, 2], [-2, 0, 0, 2]] + Input- + [1,0,-1,0,-2,2] + 0 + Output +[[1,2,-1,-2],[0,2,0,-2],[0,1,0,-1]] */ + + + +#include +using namespace std; + + +class Solution { +public: + void addAll(vector < vector >& res, vector < vector >& temp){ + for(int i = 0; i < temp.size(); i++)res.push_back(temp[i]); + } + vector> fourSum(vector& nums, int target) { + sort(nums.begin(), nums.end()); + return kSum(nums, 0, 4, target); + } + vector < vector > kSum(vector & arr, int start, int k, int target){ + vector < vector > res; + if(k == 2){ + int left = start; + int right = arr.size() - 1; + vector temp(2); + while(left < right){ + if(arr[left] + arr[right] == target){ + temp[0] = arr[left]; + temp[1] = arr[right]; + res.push_back(temp); + while(left < right && arr[left] == arr[left + 1]){left++;} + while(left < right && arr[right] == arr[right - 1]){right--;} + left++; + right--; + } + + /*this code is edited by batrakeshav10 + sir please accept my pull request and guide me, + so that i can win hactoberfest tshirt */ + else if(arr[left] + arr[right] > target)right--; + else left ++; + } + } + else{ + for(int i = start; i < (int)arr.size() - k + 1; i++){ + if(i > start && arr[i] == arr[i - 1])continue; + vector < vector > temp = kSum(arr, i + 1, k - 1, target - arr[i]); + for(int j = 0; j < temp.size(); j++){ + temp[j].push_back(arr[i]); + } + addAll(res, temp); + } + } + return res; + } +}; + + + +void print_vector(vector > v){ + cout << "["; + for(int i = 0; i v = {1,0,-1,0,-2,2}; + print_vector(ob.fourSum(v, 0)); +} + + /*this code is edited by batrakeshav10 + sir please accept my pull request and guide me, + so that i can win hactoberfest tshirt */ diff --git a/Armstrongnumber.java b/Armstrongnumber.java new file mode 100644 index 0000000..141dda7 --- /dev/null +++ b/Armstrongnumber.java @@ -0,0 +1,22 @@ +//finding armstrong number in java +public class Armstrong { + + public static void main(String[] args) { + + int number = 371, originalNumber, remainder, result = 0; + + originalNumber = number; + + while (originalNumber != 0) + { + remainder = originalNumber % 10; + result += Math.pow(remainder, 3); + originalNumber /= 10; + } + + if(result == number) + System.out.println(number + " is an Armstrong number."); + else + System.out.println(number + " is not an Armstrong number."); + } +} diff --git a/Array_Rotate.c b/Array_Rotate.c new file mode 100644 index 0000000..60f788a --- /dev/null +++ b/Array_Rotate.c @@ -0,0 +1,34 @@ +#include + +void rotate(int arr[], int n) +{ + int x = arr[n - 1], i; + for (i = n - 1; i > 0; i--) + arr[i] = arr[i - 1]; + arr[0] = x; +} + +int main() +{ + int size, i; + printf("Enter Size : "); + scanf("%d", &size); + int arr[size]; + printf("Enter Array Elements : "); + for (i = 0; i < size; i++) + { + scanf("%d", &arr[i]); + } + + printf("Given array is\n"); + for (i = 0; i < size; i++) + printf("%d ", arr[i]); + + rotate(arr, size); + + printf("\nRotated array is\n"); + for (i = 0; i < size; i++) + printf("%d ", arr[i]); + + return 0; +} diff --git a/AvlTree.cpp b/AvlTree.cpp new file mode 100644 index 0000000..5e843cd --- /dev/null +++ b/AvlTree.cpp @@ -0,0 +1,193 @@ + +#include +using namespace std; + +class Node { + public: + int key; + Node *left; + Node *right; + int height; +}; + +int max(int a, int b); + +int height(Node *N) { + if (N == NULL) + return 0; + return N->height; +} + +int max(int a, int b) { + return (a > b) ? a : b; +} + +Node *newNode(int key) { + Node *node = new Node(); + node->key = key; + node->left = NULL; + node->right = NULL; + node->height = 1; + return (node); +} + +Node *rightRotate(Node *y) { + Node *x = y->left; + Node *T2 = x->right; + x->right = y; + y->left = T2; + y->height = max(height(y->left), + height(y->right)) + + 1; + x->height = max(height(x->left), + height(x->right)) + + 1; + return x; +} + +Node *leftRotate(Node *x) { + Node *y = x->right; + Node *T2 = y->left; + y->left = x; + x->right = T2; + x->height = max(height(x->left), + height(x->right)) + + 1; + y->height = max(height(y->left), + height(y->right)) + + 1; + return y; +} + +int getBalanceFactor(Node *N) { + if (N == NULL) + return 0; + return height(N->left) - + height(N->right); +} + +// Insert a node +Node *insertNode(Node *node, int key) { + + if (node == NULL) + return (newNode(key)); + if (key < node->key) + node->left = insertNode(node->left, key); + else if (key > node->key) + node->right = insertNode(node->right, key); + else + return node; + + node->height = 1 + max(height(node->left), + height(node->right)); + int balanceFactor = getBalanceFactor(node); + if (balanceFactor > 1) { + if (key < node->left->key) { + return rightRotate(node); + } else if (key > node->left->key) { + node->left = leftRotate(node->left); + return rightRotate(node); + } + } + if (balanceFactor < -1) { + if (key > node->right->key) { + return leftRotate(node); + } else if (key < node->right->key) { + node->right = rightRotate(node->right); + return leftRotate(node); + } + } + return node; +} + + +Node *nodeWithMimumValue(Node *node) { + Node *current = node; + while (current->left != NULL) + current = current->left; + return current; +} + + +Node *deleteNode(Node *root, int key) { + + if (root == NULL) + return root; + if (key < root->key) + root->left = deleteNode(root->left, key); + else if (key > root->key) + root->right = deleteNode(root->right, key); + else { + if ((root->left == NULL) || + (root->right == NULL)) { + Node *temp = root->left ? root->left : root->right; + if (temp == NULL) { + temp = root; + root = NULL; + } else + *root = *temp; + free(temp); + } else { + Node *temp = nodeWithMimumValue(root->right); + root->key = temp->key; + root->right = deleteNode(root->right, + temp->key); + } + } + + if (root == NULL) + return root; + + root->height = 1 + max(height(root->left), + height(root->right)); + int balanceFactor = getBalanceFactor(root); + if (balanceFactor > 1) { + if (getBalanceFactor(root->left) >= 0) { + return rightRotate(root); + } else { + root->left = leftRotate(root->left); + return rightRotate(root); + } + } + if (balanceFactor < -1) { + if (getBalanceFactor(root->right) <= 0) { + return leftRotate(root); + } else { + root->right = rightRotate(root->right); + return leftRotate(root); + } + } + return root; +} + +void printTree(Node *root, string indent, bool last) { + if (root != nullptr) { + cout << indent; + if (last) { + cout << "R----"; + indent += " "; + } else { + cout << "L----"; + indent += "| "; + } + cout << root->key << endl; + printTree(root->left, indent, false); + printTree(root->right, indent, true); + } +} + +int main() { + Node *root = NULL; + root = insertNode(root, 33); + root = insertNode(root, 13); + root = insertNode(root, 53); + root = insertNode(root, 9); + root = insertNode(root, 21); + root = insertNode(root, 61); + root = insertNode(root, 8); + root = insertNode(root, 11); + printTree(root, "", true); + root = deleteNode(root, 13); + cout << "After deleting " << endl; + printTree(root, "", true); +} diff --git a/BST using preorder traversal.cpp b/BST using preorder traversal.cpp new file mode 100644 index 0000000..cc8d18c --- /dev/null +++ b/BST using preorder traversal.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + TreeNode* solve(vector& preorder,int mini,int maxi,int &i){ + if(i>=preorder.size()){ + return NULL; + } + if(preorder[i]maxi){ + return NULL; + } + TreeNode* root=new TreeNode(preorder[i++]); + root->left=solve(preorder,mini,root->val,i); + root->right=solve(preorder,root->val,maxi,i); + return root; + } + TreeNode* bstFromPreorder(vector& preorder) { + int mini=INT_MIN; + int maxi=INT_MAX; + int i=0; + + return solve(preorder,mini,maxi,i); + } +}; \ No newline at end of file diff --git a/Binary_Array_sorting.c b/Binary_Array_sorting.c new file mode 100644 index 0000000..e4b7102 --- /dev/null +++ b/Binary_Array_sorting.c @@ -0,0 +1,56 @@ +// { Driver Code Starts +//Initial template for C++ + +#include +using namespace std; + + // } Driver Code Ends +//User function template for C++ + +// binArray is an array that consists only 0s and 1s +// return sorted binary array +class Solution{ + public: + vector SortBinaryArray(vector binArray) + { + // Your code goes here + int oneInd = -1; + for(int ind=0; ind>t; + + while(t--) + { + int n; + cin>>n; + vector binArray(n); + + for(int i = 0; i < n; i++) + cin>>binArray[i]; + Solution ob; + vector result = ob.SortBinaryArray(binArray); + for(int i=0; i arr[j]){ + //swap elements + temp = arr[j-1]; + arr[j-1] = arr[j]; + arr[j] = temp; + } + + } + } + + } + public static void main(String[] args) { + int arr[] ={3,60,35,2,45,320,5}; + + System.out.println("Array Before Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + System.out.println(); + + bubbleSort(arr);//sorting array elements using bubble sort + + System.out.println("Array After Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + + } +} \ No newline at end of file diff --git a/BubbleSortProgram.java b/BubbleSortProgram.java new file mode 100644 index 0000000..f91b7c5 --- /dev/null +++ b/BubbleSortProgram.java @@ -0,0 +1,35 @@ +public class BubbleSortExampleJava { + static void bubbleSort(int[] arr) { + int n = arr.length; + int temp = 0; + for(int i=0; i < n; i++){ + for(int j=1; j < (n-i); j++){ + if(arr[j-1] > arr[j]){ + //swap elements + temp = arr[j-1]; + arr[j-1] = arr[j]; + arr[j] = temp; + } + + } + } + + } + public static void main(String[] args) { + int arr[] ={3,60,35,2,45,320,5}; + + System.out.println("Array Before Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + System.out.println(); + + bubbleSort(arr);//sorting array elements using bubble sort + + System.out.println("Array After Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + + } +} \ No newline at end of file diff --git a/Bucket-sort.cpp b/Bucket-sort.cpp new file mode 100644 index 0000000..76f719a --- /dev/null +++ b/Bucket-sort.cpp @@ -0,0 +1,36 @@ +#include +#include +#include +using namespace std; + +void bucketSort(float arr[], int n) +{ + + vector b[n]; + + for (int i = 0; i < n; i++) { + int bi = n * arr[i]; + b[bi].push_back(arr[i]); + } + + for (int i = 0; i < n; i++) + sort(b[i].begin(), b[i].end()); + + int index = 0; + for (int i = 0; i < n; i++) + for (int j = 0; j < b[i].size(); j++) + arr[index++] = b[i][j]; +} + +int main() +{ + float arr[] + = { 0.8, 0.5, 0.6, 0.1, 0.6, 0.3 }; + int n = sizeof(arr) / sizeof(arr[0]); + bucketSort(arr, n); + + cout << "Sorted array : \n"; + for (int i = 0; i < n; i++) + cout << arr[i] << " "; + return 0; +} \ No newline at end of file diff --git a/Building_roads_cses(connected_components).cpp b/Building_roads_cses(connected_components).cpp new file mode 100644 index 0000000..8ae20aa --- /dev/null +++ b/Building_roads_cses(connected_components).cpp @@ -0,0 +1,77 @@ +#include +using namespace std; +#define ll long long int +#define sz(x) x.size() +#define pb push_back +#define pb2 pop_back +#define ff first +#define ss second +#define lb lower_bound +#define ub upper_bound +#define bend(x) x.begin(), x.end() +#define vi vector +#define mapp map +#define sett set +#define ve vector +#define un_m unordered_map +#define f(i, a, b) for (i = a; i < b; i++) +#define f2(i, a) for (auto i = a.begin(); i != a.end(); i++) +#define MAXN 10000001 + +#define mp make_pair +#define in(t) scanf("%lld",&t) +#define out(t) printf("%lld",t) + +const unsigned int moduli = 1000000007; + + +ll vis[1000001]; +vi v[1000001]; +vi l; + +void dfs(ll n) { + vis[n] = 1; + for (auto a : v[n]) { + if (!vis[a]) { + dfs(a); + } + } +} + +void sol() { + ll d = 0, ds, e = 0, x, n, k; + ll i, j, tt = 0, w = 0, t; + ll ans = 0, cnt = 0, sum = 0; + ll m; + cin >> n >> m; + f(i, 0, m) { + cin >> d >> e; + v[d].pb(e); + v[e].pb(d); + } + f(i, 1, n + 1) { + if (!vis[i]) l.pb(i), dfs(i), ans++; + } + cout << ans - 1 << endl; + cnt = l[0]; + if (ans > 1) + f(i, 1, ans) { + ds = l[i]; + cout << cnt << " " << ds << endl; + cnt = ds; + } + +} + +// driver function +int main() { + + ll tc; + //cin >> tc; + //while (tc--) { + sol(); + cout << endl; + // } + + return 0; +} \ No newline at end of file diff --git a/C#/RadianDegreeConverter.cs b/C#/RadianDegreeConverter.cs new file mode 100644 index 0000000..3a638a8 --- /dev/null +++ b/C#/RadianDegreeConverter.cs @@ -0,0 +1,26 @@ +using System; + +namespace Conversions +{ + public static class RadianDegreeConverter + { + /// + /// Converts given degree to radian + /// + /// + /// + public static double DegreeToRadian(double degree) + { + return degree * (Math.PI / 180); + } + + /// + /// Converts given radian to degree + /// + /// + public static double RadianToDegree(double radian) + { + return radian * (180 / Math.PI); + } + } +} \ No newline at end of file diff --git a/C/BST_from_preorder_in_c.c b/C/BST_from_preorder_in_c.c new file mode 100644 index 0000000..dde8e33 --- /dev/null +++ b/C/BST_from_preorder_in_c.c @@ -0,0 +1,97 @@ +/****************************************************************************** + + Given a distinct sequence of keys representing the + preorder sequence of a binary search tree (BST), construct a BST from it.it. + +*******************************************************************************/ + +#include +#include + +// Data structure to store a binary tree node +struct Node +{ + int key; + struct Node *left, *right; +}; + +// Function to create a new binary tree node having a given key +struct Node* newNode(int key) +{ + struct Node* node = (struct Node*)malloc(sizeof(struct Node)); + node->key = key; + node->left = node->right = NULL; + + return node; +} + +// Recursive function to perform inorder traversal on a given binary tree +void inorder(struct Node* root) +{ + if (root == NULL) { + return; + } + + inorder(root->left); + printf("%d ", root->key); + inorder(root->right); +} + +// Recursive function to build a BST from a preorder sequence. +struct Node* constructBST(int preorder[], int start, int end) +{ + // base case + if (start > end) { + return NULL; + } + + // Construct the root node of the subtree formed by keys of the + // preorder sequence in range `[start, end]` + struct Node* node = newNode(preorder[start]); + + // search the index of the first element in the current range of preorder + // sequence larger than the root node's value + int i; + for (i = start; i <= end; i++) + { + if (preorder[i] > node->key) { + break; + } + } + + // recursively construct the left subtree + node->left = constructBST(preorder, start + 1, i - 1); + + // recursively construct the right subtree + node->right = constructBST(preorder, i, end); + + // return current node + return node; +} + +int main(void) +{ + /* Construct the following BST + 15 + / \ + / \ + 10 20 + / \ / \ + / \ / \ + 8 12 16 25 + */ + + int preorder[] = { 15, 10, 8, 12, 20, 16, 25 }; + int n = sizeof(preorder)/sizeof(preorder[0]); + + // construct the BST + struct Node* root = constructBST(preorder, 0, n - 1); + + // print the BST + printf("Inorder traversal of BST is "); + + // inorder on the BST always returns a sorted sequence + inorder(root); + + return 0; +} diff --git a/C/PostfixEvaluation.c b/C/PostfixEvaluation.c new file mode 100644 index 0000000..2d86707 --- /dev/null +++ b/C/PostfixEvaluation.c @@ -0,0 +1,96 @@ +/* +Given a postfix expression in digits(only from 0-9), evaluate it and get the answer using stack. +Test Case +i.) 65*3+ (ans - 33) +ii.) 245+* (ans - 18) + +Short Algorithm +---> Include all the required libraries +---> Make the function push and pop +---> read the postfix expression and read till the end +---> find the result and push it in the stack +---> call the function whatever required for finding the result +---> pop the result in a variable and print it +*/ + +//Including Libraries +#include +#include +#include + +//Global Declarations +int size = 50; +char input[50]; +int arr[50]; +int top = -1; + +//Function Declarations +int pop(); +void push(); + +//Main Function +int main() +{ + int i, x, y, res; + char c; + int ans; + printf("Enter the Postfix Expression: "); + scanf("%s", &input); + for(i = 0; input[i] != '\0'; i++) + { + c = input[i]; + // if(isalpha(c) == 0) //it cannot accept alphabets, only digits + // { + // printf("\nWrong Input! Enter only digits for the solution\n"); + // } + if(isdigit(c)) //check for digits and then pushing the value + { + push(c - 48); //pushing the actual value in the expression by subtracting the ASCII value of 0 + } + else if(c == '+' || c == '-' || c == '*' || c == '/') + { + y = pop(); + x = pop(); + switch(c) //for finding the results + { + case '+': res = x + y; break; + case '-': res = x - y; break; + case '*': res = x * y; break; + case '/': res = x / y; break; + } + push(res); //pushing in the array + } + } + ans = pop(); //popping the final answer + printf("\nThe Postfix Expression is: %d", ans); + return 0; +} + +//Function Implementation +void push(int a) +{ + if (top < size - 1) + { + arr[++top] = a; //incrementing the top position and then inserting the element + } + else + { + printf("\nStack Overflow\n"); + exit(0); + } +} +int pop() +{ + int a; + if (top > -1) + { + a = arr[top]; //popping the element + arr[top--] = -1; + return a; //returning the element + } + else + { + printf("\nNo Element There\n"); + exit(0); + } +} \ No newline at end of file diff --git a/C/QueueOperations.c b/C/QueueOperations.c new file mode 100644 index 0000000..32d657e --- /dev/null +++ b/C/QueueOperations.c @@ -0,0 +1,148 @@ +/* +Write a Menu - Driven Program for the user to use the simple operations of Queue +using the concept of arrays. +Basic Functions are: + i.) enqueue - add an element to the tail of a queue + ii.) dequeue - remove an element from the head of a queue + iii.) first - examine the element at the head of the queue + iv.) isfull - examine the queue is full or not + v.) isempty - examine the queue is empty or not + vi.) size - determines the number of elements in the queue + +Short Algorithm +---> +*/ + +//Including Libraries +#include +#include + +//Global Variable Declaration +int max = 4 + 1; +int frnt = -1; +int back = -1; +int arr[4+1]; + +//Function Declarations +void enqueue(); +void dequeue(); +void disp(); +void first(); +void isfull(); +void isempty(); +void size(); + +//Main Function +int main() +{ + int opt; + while(1) + { + printf("\nBasic Operations on Queue\n"); + printf("1_Enqueue \n2_Dequeue \n3_Display \n4_First \n5_IsFull \n6_IsEmpty \n7_Size \n8_Exit"); + printf("\nEnter Your Choice: "); + scanf("%d", &opt); + switch(opt) + { + case 1: enqueue(); break; + case 2: dequeue(); break; + case 3: disp(); break; + case 4: first(); break; + case 5: isfull(); break; + case 6: isempty(); break; + case 7: size(); break; + case 8: exit(0); //printf("You are ending the program"); return 0; + default: printf("\nInvalid Choice\n"); + } + } + return 0; +} + +//Function Implementation +void enqueue() //Enqueue Function - For inserting at the end +{ + int inp; + if(back == max - 1) + { + printf("\nQueue Overflow\n"); + } + else + { + if(frnt == -1) {frnt = 0;} + printf("\nEnter Element to be inserted: "); + scanf("%d", &inp); + back++; + arr[back] = inp; + } +} + +void dequeue() //Dequeue Function - For deleting at the start +{ + if(frnt == -1 || frnt > back) + { + printf("\nNo Elements There\n"); + } + else + { + printf("\nThe Dequeued elements is: %d\n", arr[frnt]); + frnt++; + } +} + +void disp() //Display Function - For displaying all the elements +{ + int i; + if(frnt == -1) + { + printf("\nNo Element There\n"); + } + else + { + printf("\nElements present in the queue are: \n"); + for(i = frnt; i <= back; i++) + { + printf("%d\n ", arr[i]); + } + } +} + +void first() //First Function - For displaying the first element in the queue +{ + if(frnt == -1 || frnt > back) + { + printf("\nNo Element There\n"); + } + else + { + printf("\nThe First element is: %d\n", arr[frnt]); + } +} + +void isfull() //isfull Function - For checking the queue is full or not +{ + if(back == max) + { + printf("\nThe Queue is Full\n"); + } + else + { + printf("\nThe Queue is not Full\n"); + } +} + +void isempty() //isempty Function - For checking the queue is empty or not +{ + if(frnt == -1 || frnt > back) + { + printf("\nThe Queue is Empty\n"); + } + else + { + printf("\nThe Queue is not Empty\n"); + } +} + +void size() //Size Function - Gets the number of elements in the array +{ + printf("\nThe Number of elements in the array are: %d\n",back+1); +} \ No newline at end of file diff --git a/C/QuickSort.c b/C/QuickSort.c new file mode 100644 index 0000000..9965fd0 --- /dev/null +++ b/C/QuickSort.c @@ -0,0 +1,50 @@ +#include +void swap(int *a, int *b) +{ + int t = *a; + *a = *b; + *b = t; +} +int partition(int array[], int low, int high) +{ + int pivot = array[high]; + int i = (low - 1); + for (int j = low; j < high; j++) + { + if (array[j] <= pivot) + { + i++; + swap(&array[i], &array[j]); + } + } + + swap(&array[i + 1], &array[high]); + return (i + 1); +} +void quicksort(int array[], int low, int high) +{ + if (low < high) + { + int pi = partition(array, low, high); + quicksort(array, low, pi - 1); + quicksort(array, pi + 1, high); + } +} +void printArray(int array[], int size) +{ + for (int i = 0; i < size; ++i) + { + printf("%d", array[i]); + } + printf("\n"); +} +int main() +{ + int data[] = {8, 7, 2, 1, 0, 9, 6}; + int n = sizeof(data) / sizeof(data[0]); + printf("unsorted Array \n"); + printArray(data, n); + quicksort(data, 0, n - 1); + printf("sorted array in ascending order :\n"); + printArray(data, n); +} diff --git a/C/StackUsingLinkedList.c b/C/StackUsingLinkedList.c new file mode 100644 index 0000000..4925205 --- /dev/null +++ b/C/StackUsingLinkedList.c @@ -0,0 +1,110 @@ +/* +Write a Program to implement Stack using Linked List. +Function to be included: +--> Push +--> Pop +--> Display +*/ + +//Including Libraries +#include +#include + +//Function Declaration +void push(); +void pop(); +void disp(); + +//Creating structure +struct node +{ + int data; + struct node *frnt; +}; +struct node *head; + +//Main Function +int main() +{ + int opt; + while(1) + { + printf("\nOperations of Stack using Linked List\n"); + printf("1_Push \n2_Pop \n3_Display \n4_Exit"); + printf("\nEnter the option: "); + scanf("%d", &opt); + switch(opt) + { + case 1: push(); break; + case 2: pop(); break; + case 3: disp(); break; + case 4: exit(0); + default: printf("\nInvalid Choice\n"); + } + } +} + +//Function Implementation +void push() +{ + int ele; + struct node *ptr; + ptr = (struct node *)malloc(sizeof(struct node)); + if(ptr == NULL) + { + printf("\nMemory Allocation Failed\n"); + } + else + { + printf("\nEnter Element to be inserted at end: "); + scanf("%d", &ele); + ptr->data = ele; + if(head == NULL) + { + ptr->frnt = NULL; + head = ptr; + } + else + { + ptr->data = ele; + ptr->frnt = head; + head = ptr; + } + } +} + +void pop() +{ + struct node *ptr; + if(head == NULL) + { + printf("\nNo Elements There\n"); + } + else + { + ptr = head; + head = ptr->frnt; + printf("\nElement removed is: %d\n", ptr->data); + free(ptr); + } +} + +void disp() +{ + struct node *ptr; + ptr = head; + if(ptr == NULL) + { + printf("\nNo Elements There\n"); + } + else + { + printf("\nThe Values are: "); + while (ptr!=NULL) + { + printf("%d ",ptr->data); + ptr = ptr -> frnt; + } + printf("\n"); + } +} \ No newline at end of file diff --git a/C/binary_search.c b/C/binary_search.c new file mode 100644 index 0000000..5aad9b4 --- /dev/null +++ b/C/binary_search.c @@ -0,0 +1,40 @@ +#include +#include +void main() +{ +int a[10],i,n,low,high,mid,item; +clrscr(); +printf("Enter the number of elements in the array); +scanf("%d",&n); +printf("Enter the elements in the array"); +for(i=0;ihigh) +{ +printf("The element is not found"); +} +getch(); +} diff --git a/C/c codes/all functios.c b/C/c codes/all functios.c new file mode 100644 index 0000000..19a1a11 --- /dev/null +++ b/C/c codes/all functios.c @@ -0,0 +1,60 @@ +#include"stdio.h" //standard library or header file +void add(); // function prototye +int sub(); // function prototye +void div(int a,int b); // function prototye +int mul(int a,int b); // function prototye = when writing user defined fun below main +void main() +{ int a,b,c; + add(); // 1 + c=sub(); + printf("\n substraction is %d",c); + int sub(); + + printf("\n enter first no "); + scanf("%d",&a); + printf("\n enter second no "); + scanf("%d",&b); + div(a,b); + + printf("\n enter first no "); + scanf("%d",&a); + printf("\n enter second no "); + scanf("%d",&b); + c=mul(a,b); //call of function + printf("\n multiplication is %d",c); +} +void add() +{ int a,b,c; + printf("\n enter first no "); //void as return type and zero parameter + scanf("%d",&a); + printf("\n enter second no "); + scanf("%d",&b); + c=a+b; + printf("\n addition is %d",c); +} +int sub() +{ int a,b,c; + printf("\n enter first no "); + scanf("%d",&a); //int as return type and zero parameter + printf("\n enter second no "); + scanf("%d",&b); + c=a-b; + return c; +} +void div(int a,int b) //function prototype +{ + int c; //void as return type and parameter = input to main fun + c=a/b; + printf("\n division is %d",c); + +} +int mul(int a,int b) //function prototype +{ + int c; //int as return type and parameter + c=a*b; + return c; + + +} + + diff --git a/C/c codes/array max.c b/C/c codes/array max.c new file mode 100644 index 0000000..f967398 --- /dev/null +++ b/C/c codes/array max.c @@ -0,0 +1,24 @@ +#include //header file +void main() //main function +{ + int i,arr[5],num1,num2; //declaration of variable + for(i=1;i<=5;i++) // for loop is use for to take numbers from user + { + printf("enter your %d number",i); + scanf("%d",&arr[i]); + } printf("your enter nmubers\n"); + for(i=1;i<=5;i++) //for loop is use for to print numbers that give by user + printf("%d\n",arr[i]); + for(i=1;i<=5;i++) //for loop is use for to find max number + { + if (num1<=arr[i]) + num1=arr[i]; + } + for(i=1;i<=5;i++) //for loop is use for to find min number + { + if (num2>=arr[i]) + num2=arr[i]; + } + printf("\n max number is %d",num1); //to print max number + printf("\n min number is %d",num2); //to print min number +} diff --git a/C/c codes/array sum.c b/C/c codes/array sum.c new file mode 100644 index 0000000..0635f93 --- /dev/null +++ b/C/c codes/array sum.c @@ -0,0 +1,25 @@ +#include +void main() + +{ +int p,i,sum=0,n[p]; + +printf("enter your choice of number you want for addition = "); +scanf("\n%d",&p); +printf("enter your %d numbers\n",p); +for(i=1;i<=p;i++) +{ + scanf("\n%d",&n[i]); + +} +for(i=1;i<=p;i++) +{ + printf("\n %d",n[i]); +} +for(i=1;i<=p;i++) +{ + sum=n[i]+sum; +} +printf("\n\t addition of your %d numbers is %d",p,sum); +} + diff --git a/C/c codes/fibonacci by recursion.c b/C/c codes/fibonacci by recursion.c new file mode 100644 index 0000000..67860ee --- /dev/null +++ b/C/c codes/fibonacci by recursion.c @@ -0,0 +1,42 @@ +// function to find the nth fibonacci +#include +int main() +{ + int n = 0,m,i; + printf("enter value of m "); + scanf("%d",&m); + for(i=0;i + void main () + { + int i,j,k,a[5] ; + + for (i=0;i<5;i++) + { + scanf("\n%d",&a[i]); + } + for (i=0;i<5;i++) + { + printf("\n%d",a[i]); + } + + printf("\n enter key "); + scanf("\n%d",&j); + + for (i=0;i<5;i++) + { + if (j==a[i]) + { + k=0; + break; + } + else + { + k=1; + } } + + if (k==0) + { + printf("\n found"); + + } + + else{ + + printf("\n not found");} + + +} diff --git a/C/c codes/functions.c b/C/c codes/functions.c new file mode 100644 index 0000000..9988647 --- /dev/null +++ b/C/c codes/functions.c @@ -0,0 +1,22 @@ +#include +void add(); +void sub(); +void main() // grp of statement executed only when it is called +{ + printf("\n inside main fun"); + + add(); + sub (); //calling of fun |imp| at time of call it starts executing from add funcion and then back to previous + + printf("\n hello"); + +} +void add() // not called function so not printed zero parameter fun def or body +{ + printf("\n inside add fun"); //calling itself will recursive +} +void sub () // not called function so not printed zero parameter +{ + printf("\n inside sub fun"); + +} // fun prototype = void add(); write above main function diff --git a/C/c codes/loop all.c b/C/c codes/loop all.c new file mode 100644 index 0000000..3b42bdb --- /dev/null +++ b/C/c codes/loop all.c @@ -0,0 +1,101 @@ +/*#include +void main() +{ + int i,n; + printf("enter number "); + scanf("\n%d",&n); + + for(i=0;i<=n;i++) + { + printf("\t%d",i); + } + } + */ + +/*#include +void main() +{ + int i,n; + printf("enter number "); + scanf("\n%d",&n); + + i=0; + while(i<=n) + { + printf("\t%d",i); + i++; + } + + + +}*/ + + + + +/*#include +void main() +{ + int i,n; + printf("enter number "); + scanf("\n%d",&n); + + i=1; + do + { + printf("\t%d",i); + i++; + } + while(i<=n); ///semicolon required + + }*/ + + //reverse + +/*#include +void main() +{ + int i,n; + printf("enter number "); + scanf("\n%d",&n); + + for(i=n;i>=1;i--) + { + printf("\t%d",i); + } + }*/ + +/* #include +void main() +{ + int i,n; + printf("enter number "); + scanf("\n%d",&n); + + i=n; + while(i>=1) + { + printf("\t%d",i); + i--; +}}*/ + + +/*#include +void main() +{ + int i,n; + printf("enter number "); + scanf("\n%d",&n); + + i=n; + do + { + printf("\t%d",i); + i--; + } + while(i>=1);}*/ + + + + + diff --git a/C/c codes/matrix arry.c b/C/c codes/matrix arry.c new file mode 100644 index 0000000..d7e3232 --- /dev/null +++ b/C/c codes/matrix arry.c @@ -0,0 +1,30 @@ +#include +void main() +{ +int row,col; + float a[2][2]; //2d dimensional array + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + scanf("%f",&a[row][col]); + } + + } + printf("\n\n\n\n"); + + for (row=0;row<2;row++) + + { + + for (col=0;col<2;col++) + { + + printf("%2.f\t",a[row][col]); + } printf("\n"); + + } + + printf("\n"); +} diff --git a/C/c codes/matrix mul.c b/C/c codes/matrix mul.c new file mode 100644 index 0000000..184fe4e --- /dev/null +++ b/C/c codes/matrix mul.c @@ -0,0 +1,73 @@ +#include +void main() +{ +int row,col; + int a[2][2],b[2][2],c[col][row],k; //2d dimensional array + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + scanf("%d",&a[row][col]); + } + + } + printf("\n\n\n\n"); + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + printf("%d\t",a[row][col]); + } + printf("\n"); + + } + + printf("\n"); + + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + scanf("%d",&b[row][col]); + } + + } + printf("\n\n\n\n"); + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + printf("%d\t",b[row][col]); + } + printf("\n"); + + } + + printf("\n"); + + + printf("multiplication is"); + + printf("\n\n\n\n"); + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + c[row][col]=0; + + for (k=0;k<2;k++) + { + c[row][col] = c[row][col] + (a[row][k]*b[k][col]); + } + printf("%d\t",c[row][col]); + } + printf("\n"); + } + + +} diff --git a/C/c codes/matrix substra.c b/C/c codes/matrix substra.c new file mode 100644 index 0000000..ae148bc --- /dev/null +++ b/C/c codes/matrix substra.c @@ -0,0 +1,68 @@ +#include +void main() +{ +int row,col; + int a[2][2],addition; //2d dimensional array + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + scanf("%d",&a[row][col]); + } + + } + printf("\n\n\n\n"); + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + printf("%d\t",a[row][col]); + } + printf("\n"); + + } + + printf("\n"); + + int b[2][2]; //2d dimensional array + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + scanf("%d",&b[row][col]); + } + + } + printf("\n\n\n\n"); + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + printf("%d\t",b[row][col]); + } + printf("\n"); + + } + + printf("\n"); + + + printf("substraction is"); + + printf("\n\n\n\n"); + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + printf("%d\t",a[row][col]-b[row][col]); + } + printf("\n"); + } + + +} diff --git a/C/c codes/mtrice addition.c b/C/c codes/mtrice addition.c new file mode 100644 index 0000000..9faacf7 --- /dev/null +++ b/C/c codes/mtrice addition.c @@ -0,0 +1,68 @@ +#include +int main() +{ +int row,col; + int a[2][2],addition; //2d dimensional array + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + scanf("%d",&a[row][col]); + } + + } + printf("\n\n\n\n"); + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + printf("%d\t",a[row][col]); + } + printf("\n"); + + } + + printf("\n"); + + int b[2][2]; //2d dimensional array + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + scanf("%d",&b[row][col]); + } + + } + printf("\n\n\n\n"); + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + printf("%d\t",b[row][col]); + } + printf("\n"); + + } + + printf("\n"); + + + printf("addition is"); + + printf("\n\n\n\n"); + + for (row=0;row<2;row++) + { + for (col=0;col<2;col++) + { + printf("%d\t",a[row][col]+b[row][col]); + } + printf("\n"); + } + + +} diff --git a/C/c codes/pointer madam pr 27 apr.c b/C/c codes/pointer madam pr 27 apr.c new file mode 100644 index 0000000..4258d45 --- /dev/null +++ b/C/c codes/pointer madam pr 27 apr.c @@ -0,0 +1,80 @@ +#include +int ptr_addition (); +int ptr_substraction (); +int ptr_increment (); +int ptr_decrement (); +void main () +{ ptr_addition (); + ptr_substraction (); + ptr_increment (); + ptr_decrement (); +} + +int ptr_addition () +{ + int n = 4 ; + int *ptr1; + ptr1=&n; + printf("\n pointer before addition = %d",ptr1); + + ptr1 = ptr1 + 3; + printf("\n pointer after addition = %d\n",ptr1); + + return 0; +} + +int ptr_substraction () +{ + int m = 4 ; + int *ptr2; + ptr2=&m; + printf("\n pointer before substractio = %d",ptr2); + + ptr2 = ptr2 - 3; + printf("\n pointer after substractio = %d\n",ptr2); + + return 0; +} + +int ptr_increment () +{ + int var[] = {10,100,200}; + int i,*ptr3; + ptr3=var; + + for(i=0;i<3;i++) + { + printf("\n address of var[%d] = %d",i,ptr3); + printf("\n value of var[%d] = %d",i,*ptr3); + ptr3++; + } + printf("\n"); +} + + +int ptr_decrement () +{ + int var[] = {10,100,200}; + int i,*ptr4; + ptr4=&var[2]; + + for(i=3;i>0;i--) + { + printf("\n address of var[%d] = %d",i,ptr4); + printf("\n value of var[%d] = %d",i,*ptr4); + ptr4--; + } + printf("\n"); +} + + + + + + + + + + + + diff --git a/C/c codes/pointers pr.c b/C/c codes/pointers pr.c new file mode 100644 index 0000000..e96a175 --- /dev/null +++ b/C/c codes/pointers pr.c @@ -0,0 +1,325 @@ +#include +#include + +/*void main () +{ + int a=10; + int* ptr=&a; + + printf("\n%d",&a); + printf("\n%d",ptr); + printf("\n%d",*ptr); + printf("\n%d",&ptr); +}*/ + + +/*void main () // by 2 variables +{ + int a=5, b=10,c,d; + + printf("\n value of a = %d",a); + printf("\n value of b %d",b); + + c=a; d=b; a=b; b=c; + + printf("\n value of a %d",a); + printf("\n value of b %d",b); + +}*/ + +/* +void main () // by no variables +{ + int a=5, b=10; + + printf("\n value of a = %d",a); + printf("\n value of b %d",b); + a=a+b; + b=a-b; + a=a-b; + printf("\n value of a %d",a); + printf("\n value of b %d",b); + +} +*/ + + +/* +void swap(int a,int b); +void main () // by no variables +{ + int a=0, b=0; + + scanf("%d",&a); + printf("\n value of a = %d\n",a); + scanf("%d",&b); + printf("\n value of b %d",b); + + swap(a,b); + +} +void swap(int a,int b) +{ + a=a+b; + b=a-b; + a=a-b; + + printf("\n value of a %d",a); + printf("\n value of b %d",b); + +}*/ + + +/* +// call by value +void swap(int a,int b); +void main () // by no variables +{ + int a=0, b=0; + + scanf("%d",&a); + printf("\n value of a = %d\n",a); + scanf("%d",&b); + printf("\n value of b %d",b); + + swap(a,b); //will print same values as main fun drawback of call by value will not swap in main function + + + printf("\n value of a %d",a); + printf("\n value of b %d",b); + +} +void swap(int a,int b) +{ + a=a+b; + b=a-b; + a=a-b; + +}*/ + +/* +// call by reference with one variable +void swap(int* a,int* b); +void main () +{ + int a=0, b=0; + + scanf("%d",&a); + printf(" a before swap outside fun = %d\n",a); + scanf("%d",&b); + printf(" b before swap outside fun = %d\n",b); + + swap(&a,&b); + + + printf("\n a after swap outside fun %d\n",a); + printf("\n b after swap outside fun %d\n",b); + +} +void swap(int* a,int* b) +{ + printf(" a before swap in fun = %d\n",*a); + printf(" b before swap in fun = %d\n",*b); + int c; + c=*a; + *a=*b; + *b=c; + printf("\n a after swap in fun %d\n",*a); + printf("\n b after swap in fun %d\n",*b); +} +*/ + + + +/* +void swap(int* a,int* b); ///by no variable +void main () +{ + int a=0, b=0; + + scanf("%d",&a); + printf(" a before swap outside fun = %d\n",a); + scanf("%d",&b); + printf(" b before swap outside fun = %d\n",b); + + swap(&a,&b); + + + printf("\n a after swap outside fun %d\n",a); + printf("\n b after swap outside fun %d\n",b); + +} +void swap(int* a,int* b) +{ + printf(" a before swap in fun = %d\n",*a); + printf(" b before swap in fun = %d\n",*b); + *a=*a+*b; + *b=*a-*b; + *a=*a-*b; + printf("\n a after swap in fun %d\n",*a); + printf("\n b after swap in fun %d\n",*b); +} + + +void main () + { + +int a[5]={1,2,3,4,5}; +int i; + +for(i=0;i<5;i++) +{ + printf("%d",a[i]); +} + +}*/ + + +/* +void main () + { + +int a[5]={1,2,3,4,5}; +int i, *ptr=a; + +for(i=0;i<5;i++) +{ + printf("%d\n",*ptr); + *ptr++; +} + +}*/ + + + /* //code for forward n reverse printing of array by pointers. +void main () + { + +int a[5]={1,2,3,4,5}; +int i, *ptr=a; + +for(i=0;i<5;i++) +{ + printf("%d\t",*ptr); + ptr++; +} + printf("\n\n"); + ptr = &a[4]; +for(i=0;i<5;i++) +{ + printf("%d\t",*ptr); + ptr--; +} + +}*/ + + + + + + // code for forward n reverse printing of my name by pointers +void main () +{ +char a[5000]; +printf("enter your name "); +gets(a); + +int l=strlen(a),i; +char *ptr=&a[0]; + +for(i=0;i +void add(int *a,int *b); +void sub(int *a,int *b); +void mul(int *a,int *b); +void div(int *a,int *b); +void main() +{ + int a,b; + printf("enter values of a and b "); + scanf("%d %d",&a,&b); + + add (&a,&b); + sub (&a,&b); + mul (&a,&b); + div (&a,&b); + +} +void add(int *a,int *b) +{ + int c; + c=*a+*b; + printf("addition is %d\n",c); +} +void sub(int *a,int *b) +{ + int c; + c=*a-*b; + printf("substraction is %d\n",c); +} +void mul(int *a,int *b) +{ + int c; + c=*a * *b; + printf("multiplition is %d\n",c); +} +void div(int *a,int *b) +{ + int c; + c=*a / *b; + printf("division is %d\n",c); +} diff --git a/C/c codes/recursion.c b/C/c codes/recursion.c new file mode 100644 index 0000000..b5c72ae --- /dev/null +++ b/C/c codes/recursion.c @@ -0,0 +1,60 @@ +#include + +//void display( int a); +//// recursion = calling by own goes infinite imp = termiation +//void main() +//{ int a=0; +// display(a); +//} +//void display( int a) +//{ +// while(a<2) //termination +// { a++; +// printf("hello\t"); +// display(a); //recursive +// +// } +// +//} + + +int main() +{ + int a = 0,result = 0; + printf("enter values of a "); + scanf("%d",&a); + result = fact (a); + printf("%d",result); + return 0; +} +int fact(int a) +{ + if(a==0) + return 1; + return a*fact(a-1); //recursive call +} + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/C/c codes/revise fun para.c b/C/c codes/revise fun para.c new file mode 100644 index 0000000..73d6de1 --- /dev/null +++ b/C/c codes/revise fun para.c @@ -0,0 +1,44 @@ +#include"stdio.h" +float sub(); +void add(); +void mul(); +void main() +{ +int a=100; +int b=200; +scanf("%d",&a); +scanf("%d",&b); +float c; +c=sub(a,b); //1 + + printf("\n%f",c); +add(a,b);//2 +mul(); //3 +} + +//1.function with other (int , float) return type and two parameter +float sub(int ab, int ba) +{ +int d; +float k; +k=ab-ba; +return k; +} + +//2.function with void return type and two parameter +void add(int a, int b) +{ +int c; +c=a+b; +printf("\n%d",c); //300 +} + +//3.function with void return type and no parameter +void mul() +{ +int a=100; +int b=200; +int c; +c=a*b; +printf("\n%d",c); +} diff --git a/C/c codes/str cmp.c b/C/c codes/str cmp.c new file mode 100644 index 0000000..a570a8a --- /dev/null +++ b/C/c codes/str cmp.c @@ -0,0 +1,36 @@ +#include +#include + +void main() +{ + char n1[100] ; + char n2[100]; + + printf("\n enter your first name "); + scanf("%s",n1); + printf("\n%s",n1); + + printf("\n enter your last name "); + scanf("%s",n2); + printf("\n%s",n2); + + int res; + res = strcmp (n1,n2); //alphabates are considered by lexicographic order (dictionary order) + + if(res==0) + { + printf("\n both are equal "); + } + else if(res>0) + { + printf("\n first is greater "); + } + else if(res<0) + { + printf("\n first is smaller "); + } + + + + +} diff --git a/C/c codes/str conversion.c b/C/c codes/str conversion.c new file mode 100644 index 0000000..9ae3038 --- /dev/null +++ b/C/c codes/str conversion.c @@ -0,0 +1,62 @@ +#include +#include + +void main() +{ +// int i; +// char n1[5]="harsh"; +// printf("\n \t original name is %s",n1); +// printf("\n"); +// +// for(i=0;i<5;i++) +// { +// printf("\n%d",n1[i]); +// } +// printf("\n"); +// for(i=0;i<5;i++) +// { +// n1[i]=n1[i]+32; +// printf("\n%d",n1[i]); +// +// } +// printf("\n"); +// printf("\n \t converted name is %s",n1); + + + + + + // lower to upper + int i; + char n1[20]; + + printf("\n enter your string "); + scanf("%s",n1); + int l=strlen(n1); + +// puts(n); + + printf("\n \t original string is %s",n1); + printf("\n"); + + for(i=0;i +#include +// //stringcopy without strcpy +//void main() +// +//{ +// int i,l=0; +// char n1[20]; +// +// +// printf("\n enter your string "); +// scanf("%s",n1); +// +// for(i=0;n1[i]!='\0';i++) +// { +// l++; +// } +// printf("\n\t %d",l); +//} + + + + + + + + + + + + + + + +//own function call in void baki all own fun madhe + +//void stringlength(); +//void main() +// +//{ +// stringlength(); +//} +//void stringlength() +//{ +// int i,l=0; +// char n1[20]; +// printf("\n enter your string "); +// scanf("%s",n1); +// +// for(i=0;n1[i]!='\0';i++) +// { +// l++; +// } +// printf("\n\t %d",l); +//} + + + + + + + +//// parameter with return type + +//int stringlength(char n1[]); +//void main() +// +//{ +// int i,l=0; +// char n1[20]; +// printf("\n enter your string "); +// scanf("%s",n1); +// l=stringlength(n1); +// printf("\n\t string length is %d",l); +//} +//int stringlength(char n1[]) +//{ +// int i,l=0; +// +// +// for(i=0;n1[i]!='\0';i++) +// { +// l++; +// } +// return l; +//} + + + + +// its by str function we want it without using strcpy = by own function + +// void main() +// { +// char name[10] ; +// char name1[10]; +// +// scanf("%s",name); +// printf("\n%s",name); +// +// strcpy(name1,name) ; //to copy name from one string to another (destination , source) +// printf("\n name1 is %s",name1); +// printf("\n name is %s",name); +//} + + + +/* own function=to copy name from one string to another +void main() +{ + int i; + char n1[20],n2[20]; + + printf("\n enter your string "); + scanf("%s",n1); + printf("\n entered string is = %s",n1); + + for(i=0;n1[i]!='\0';i++) + { + n2[i]=n1[i]; + + } + printf("\n copied string is = %s",n2); + +}*/ + + + + +/* // by parameter +void stringcopy(char n2[20],char n1[20]); +void main() +{ + int i; + char n1[20],n2[20]; + + printf("\n enter your string "); + scanf("%s",n1); + printf("\n entered string is = %s",n1); + stringcopy(n2,n1); + printf("\n copied string is = %s",n2); + +} +void stringcopy(char n2[],char n1[]) +{ int i; + for(i=0;n1[i]!='\0';i++) + { + n2[i]=n1[i]; + } +} +*/ + + + + + +/// own function=to put one str after other +/* +void stringconcatination(char n2[],char n1[]); +void main() +{ + char f[20],c[20]; + + printf("\n enter first string "); + scanf("%s",f); + printf("\n entered string is = %s",f); + + printf("\n enter second string "); + scanf("%s",c); + printf("\n entered string is = %s",c); + + stringconcatination(f,c); + printf("\n new string is = %s",f); + +} +void stringconcatination(char f[],char c[]) +{ int i,j; + for(i=0;i +#include + +void main() +{ + char name[1024]="mitaoe hii"; //string array always end with \o + +// char n1='A'; + printf("%d",name); //%d = will print ascii value + printf("\n%c",name); //%c character value + +// printf("%c",name[4]); //to print single character +// +// scanf("%s",name); +// printf("\n%s",name); + + + +/* char name[15]; + char n1='q',n2='Q'; + printf("\n enter your name "); + scanf("%s",name); + printf("\n name is %s",name); + printf("\nascii value q is %d\nascii value Q is %d",n1,n2); +*/ + + + + +// 1) string length +/* char name[6]; + scanf("%s",name); + int l = strlen(name); //to calcuate length of string + printf("\n string length is %d",l); +*/ + + + +// 2) string copy +/* char name[10] ; + char name1[10]; + + scanf("%s",name); + printf("\n%s",name); + + strcpy(name1,name) ; //to copy name from one string to another (destination , source) + printf("\n name1 is %s",name1); + printf("\n name is %s",name); + + + + + +// 3) string compare + +/* char n1[10] ; + char n2[10]; + + printf("\n enter your first name "); + scanf("%s",n1); + printf("\n%s",n1); + printf("\n enter your last name "); + scanf("%s",n2); + printf("\n%s",n2); + + //alphabates are considered by lexicographic order (dictionary order) + int res = strcmp(n1,n2); // name character array //to compare values all equal = 1 , first smaller -1 , first larger +1 + + // int res = strcmp("mit","mit"); // string // can give directly also + //printf("%d",res); //%d as 0,-1,+1 + + if(res==0) + { + printf("\n both are equal "); + } + else if(res>0) + { + printf("\n first is greater "); + } + else if(res<0) + { + printf("\n first is smaller "); + } +*/ + + + + + + +// 4) string concatination + +/* char n1[10] ; + char n2[10]; + + printf("\n enter your first name "); + scanf("%s",n1); + printf("\n%s\n",n1); + printf("\n enter your last name "); + scanf("%s",n2); + printf("\n%s\n",n2); + + strcat(n1,n2); //strng concatination = attatch one strng to other + printf("\n output concatination is %s",n1); + + int l=strlen(n1); + printf("\n\n length of output concatination is %d",l); +*/ + + + +// 5) string reverse +/* char n1[10] ; + printf("\n enter your first name "); + scanf("%s",n1); + printf("\n%s\n",n1); + strrev(n1); + printf("\n output reverse is %s",n1); +*/ + + + +// 6) sub string + /*char n1[10]; + char n2[10]; + + printf("\n enter your first name "); + scanf("%s",n1); + printf("\n%s\n",n1); + printf("\n enter your last name "); + scanf("%s",n2); + printf("\n%s\n",n2); + +// strstr(n1,n2) // (n1 = to where ,n2 = to whom) + if(strstr(n1,n2)==NULL) // 0 CHALEGA KYA ?????????????????????????????????????? + { + printf("\n SUBSTRING NOT AVAILABLE"); + } + else + { + printf("\n SUBSTRING AVAILABLE"); + }*/ + + + + + + + + + + + +} diff --git a/C/c codes/struct by sir.c b/C/c codes/struct by sir.c new file mode 100644 index 0000000..b474050 --- /dev/null +++ b/C/c codes/struct by sir.c @@ -0,0 +1,51 @@ +#include +//struct stu +//{ +// int rno; //4 +// int prn; //4 +//}; +//int main() +//{ +// struct stu s1; +// struct stu s2; +// +// printf("enter roll no and prn no for student 1 \n"); +// scanf("%d\t %d",&s1.rno,&s1.prn); +// printf("enter roll no and prn no for student 2 \n"); +// scanf("%d\t %d",&s2.rno,&s2.prn); +// +// printf("roll no = %d\t prn no = %d\n ",s1.rno,s1.prn); +// +// printf("roll no = %d\t prn no = %d\n",s2.rno,s2.prn); +// +// printf("size of s1 is %d",sizeof(s1)); +// +// return 0; +//} + + + +struct stu +{ + int rno; //4 + int prn; //4 +}; +int main() +{ + struct stu s[3]; //array of objects + int i; + + for(i=0;i<3;i++) + { + printf("enter roll no and prn no for student %d \n",i+1); + scanf("%d",&s[i].rno); + scanf("%d",&s[i].prn); + } + for(i=0;i<3;i++) + { + printf(" roll no and prn no for student %d \n",i+1); + printf("\t%d\n",s[i].rno); + printf("\t%d\n",s[i].prn); + } + return 0; +} diff --git a/C/c codes/switch fun all.c b/C/c codes/switch fun all.c new file mode 100644 index 0000000..d68f6d7 --- /dev/null +++ b/C/c codes/switch fun all.c @@ -0,0 +1,182 @@ +/* name = harshwardhan prakash tilekar + division = A + batch = A1 + roll no = 108 + practical 10 = Write a program in C using functions to display addition, subtraction, multiplication, division of two numbers. +*/ + +#include"stdio.h" //standard library or header file +void add(); // function prototye +int sub(); // function prototye +void div(int a,int b); // function prototye +int mul(int a,int b); // function prototye + +void main() // system defined main function + +{ int a,b,c,choice,sub(); //declaration of variable + + printf("MENU"); // menu + printf("\n 1) ADDITION "); // option for ADDITION + printf("\n 2) SUBSTRACITION "); // option for SUBSTRACITION + printf("\n 3) DIVISION "); // option for DIVISION + printf("\n 4) MULTIPLICATION "); // option for MULTIPLICATION + do{ + + printf("\n ENTER YOUR CHOICE "); // printf statement for asking user's choice + scanf("%d",&choice); // scanf statement take and store value from user + + switch (choice) // switch cases for choice + { case 1 : + add(); //calling of function + break; // end of case + + case 2 : + + c=sub(); //calling of function + printf("\n substraction is %d",c); //printf function for printing results + break; // end of case + + case 3 : + printf("\n enter first no "); + scanf("%d",&a); + printf("\n enter second no "); + scanf("%d",&b); + div(a,b); //calling of function + break; // end of case + + case 4 : + printf("\n enter first no "); + scanf("%d",&a); + printf("\n enter second no "); + scanf("%d",&b); + c=mul(a,b); //calling of function + printf("\n multiplication is %d",c); //printf function for printing results + break; // end of case + + default: + printf(" invalid choice !!! "); // printf statement for printing invalid choice + break; + }}while(choice!=4);} + + +void add() //function definition and functon body +{ int a,b,c; + printf("\n enter first no "); + scanf("%d",&a); + printf("\n enter second no "); + scanf("%d",&b); + c=a+b; //mathematical expression for addition + printf("\n addition is %d",c); //printf function for printing results +} +//function with int return type +int sub() //function definition and functon body +{ int a,b,c; + printf("\n enter first no "); + scanf("%d",&a); + printf("\n enter second no "); + scanf("%d",&b); + c=a-b; //mathematical expression for substraction + return c; //return type +} +//function with two parameter +void div(int a,int b) //function definition and functon body +{ + int c; + c=a/b; //mathematical expression for division + printf("\n division is %d",c); //printf function for printing results + +} +//function with int return type and two parameter +int mul(int a,int b) //function definition and functon body +{ + int c; + c=a*b; //mathematical expression for multiplication + return c; //return type + +} + + + +/* +case 1 = +MENU + 1) ADDITION + 2) SUBSTRACITION + 3) DIVISION + 4) MULTIPLICATION + ENTER YOUR CHOICE 1 + + enter first no 10 + + enter second no 20 + + addition is 30 +-------------------------------- +Process exited after 6.085 seconds with return value 16 +Press any key to continue . . . + +case 2 = +MENU + 1) ADDITION + 2) SUBSTRACITION + 3) DIVISION + 4) MULTIPLICATION + ENTER YOUR CHOICE 2 + + enter first no 10 + + enter second no 5 + + substraction is 5 +-------------------------------- +Process exited after 4.903 seconds with return value 19 +Press any key to continue . . . + +case 3 = +MENU + 1) ADDITION + 2) SUBSTRACITION + 3) DIVISION + 4) MULTIPLICATION + ENTER YOUR CHOICE 3 + + enter first no 200 + + enter second no 5 + + division is 40 +-------------------------------- +Process exited after 5.113 seconds with return value 16 +Press any key to continue . . . + +case 4 = +MENU + 1) ADDITION + 2) SUBSTRACITION + 3) DIVISION + 4) MULTIPLICATION + ENTER YOUR CHOICE 4 + + enter first no 200 + + enter second no 5 + + multiplication is 1000 +-------------------------------- +Process exited after 5.673 seconds with return value 24 +Press any key to continue . . . + +case 5 = +MENU + 1) ADDITION + 2) SUBSTRACITION + 3) DIVISION + 4) MULTIPLICATION + ENTER YOUR CHOICE 5 + invalid choice !!! +-------------------------------- +Process exited after 1.677 seconds with return value 21 +Press any key to continue . . . + +*/ + diff --git a/C/c codes/trans matrix.c b/C/c codes/trans matrix.c new file mode 100644 index 0000000..01375e6 --- /dev/null +++ b/C/c codes/trans matrix.c @@ -0,0 +1,41 @@ +#include +void main() +{ +int row,col; + int a[3][3],addition; //2d dimensional array + + for (row=0;row<3;row++) + { + for (col=0;col<3;col++) + { + scanf("%d",&a[row][col]); + } + + } + printf("\n\n\n\n"); + + for (row=0;row<3;row++) + { + for (col=0;col<3;col++) + { + printf("%d\t",a[row][col]); + } + printf("\n"); + + } + + printf("transpose of matrix is"); + + printf("\n\n\n\n"); + + for (row=0;row<3;row++) + { + for (col=0;col<3;col++) + { + printf("%d\t",a[col][row]); + } + printf("\n"); + + } + +} diff --git a/C/readme.md b/C/readme.md new file mode 100644 index 0000000..8adea76 --- /dev/null +++ b/C/readme.md @@ -0,0 +1 @@ +This following folder contains data structures and algorithms in C programming language. diff --git a/C/stack_array.c b/C/stack_array.c new file mode 100644 index 0000000..93eb88a --- /dev/null +++ b/C/stack_array.c @@ -0,0 +1,120 @@ +#include +#include +#include +#include +struct stack +{ + int size; + int *arr; +}; +bool isEmpty(int top) +{ + if (top == -1) + { + return 1; + } + return 0; +} +bool isFull(int top, struct stack *st) +{ + if (top == st->size - 1) + { + return 1; + } + return 0; +} +int create(struct stack *st) +{ + st->arr = (int *)malloc((st->size) * sizeof(int)); + printf("\nEnter the number of values you want to add in stack : "); + int val; + scanf("%d", &val); + getchar(); + int i = 0; + printf("\nEnter the values you want to add : \n"); + for (i = 0; i < val; i++) + { + scanf("%d", &st->arr[i]); + getchar(); + } + return i - 1; +} +int push(struct stack *st, int top) +{ + if (isFull(top, st)) + { + printf("\nStack overflowed !!!!"); + return top; + } + else + { + top++; + printf("\nEnter the value you want to push in : "); + scanf("%d", &st->arr[top]); + getchar(); + return top; + } +} +int pop(struct stack *st, int top) +{ + if (isEmpty(top)) + { + printf("\nStack underflowed!!!!"); + return top; + } + else + { + printf("\nElement poped out is : %d", st->arr[top]); + top--; + return top; + } +} +void display(int top, struct stack *st) +{ + if (isEmpty(top)) + { + printf("\nStack is empty nothing to display"); + } + else + { + printf("\nStack elements are : \n"); + for (int i = 0; i < top + 1; i++) + { + printf("%d\t", st->arr[i]); + } + } +} +int main() +{ + struct stack *s = (struct stack *)malloc(sizeof(struct stack)); + printf("\nEnter the size of array : "); + scanf("%d", &s->size); + getchar(); + int top = -1; + top = create(s); + int loop = 1; + while (loop) + { + printf("\nEnter your choice : \n1.'A' for pushing \n2.'B' for poping\n3.'C' for exit/display stack : \n"); + char choice; + scanf("%c", &choice); + getchar(); + switch (choice) + { + case 'A': + top = push(s, top); + display(top, s); + break; + case 'B': + top = pop(s, top); + display(top ,s); + break; + case 'C': + display(top, s); + loop = 0; + break; + } + } + + return 0; +} \ No newline at end of file diff --git a/C/twoDigitSum_and_divide.c b/C/twoDigitSum_and_divide.c new file mode 100644 index 0000000..66370e7 --- /dev/null +++ b/C/twoDigitSum_and_divide.c @@ -0,0 +1,29 @@ + #include +void main() +{ + int number= 10; + int t , rem, sum=0; + + + + // printf("%d",sum); + + for(int i=1 ; i<=1000; i++) + { + if(i%number==0 && i!=number) + { + t=i; + while(t!=0) + { + rem = t%10; + sum=sum+rem; + t=t/10; + } + if(sum==number) + { + printf("%d\n",i); + } + } + + } +} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..d6613c8 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,2 @@ +this repository is only for algorithms in which you can upload any language's algorithms which will useful for many other people. +happy coading 👨‍💻. diff --git a/CPP/3sum.cpp b/CPP/3sum.cpp new file mode 100644 index 0000000..a7a4b5a --- /dev/null +++ b/CPP/3sum.cpp @@ -0,0 +1,39 @@ +// 15. 3Sum Leetcode +// problem:https://leetcode.com/problems/3sum/ +class Solution { +public: + vector> threeSum(vector& nums) + { + int n=nums.size(); + sort(nums.begin(),nums.end()); + vector>v; + if(n<3) return v; + // we use set because we do not need duplicate pairs + set >s; + // consider it as 2sum in a loop + for(int i=0;i0&&nums[i]!=nums[i-1])) + { + while(lt) --r; + } + } + } + for(auto it=s.begin();it!=s.end();++it){ + v.push_back(*it); + } + return v; + } +}; diff --git a/CPP/4sum.cpp b/CPP/4sum.cpp new file mode 100644 index 0000000..62233e4 --- /dev/null +++ b/CPP/4sum.cpp @@ -0,0 +1,143 @@ +// C++ program to find four +// elements with the given sum +#include + +using namespace std; + +// Function to find 4 elements that add up to +// given sum + +void fourSum(int X, int arr[], map> Map, int N) +{ + + int temp[N]; + + + // Iterate from 0 to temp.length + + for (int i = 0; i < N; i++) + + temp[i] = 0; + + + // Iterate from 0 to arr.length + + for (int i = 0; i < N - 1; i++) + + { + + + // Iterate from i + 1 to arr.length + + for (int j = i + 1; j < N; j++) + + { + + + // Store curr_sum = arr[i] + arr[j] + + int curr_sum = arr[i] + arr[j]; + + + // Check if X - curr_sum if present + + // in map + + if (Map.find(X - curr_sum) != Map.end()) + + { + + + // Store pair having map value + + // X - curr_sum + + pair p = Map[X - curr_sum]; + + + if (p.first != i && p.second != i + + && p.first != j && p.second != j + + && temp[p.first] == 0 + + && temp[p.second] == 0 && temp[i] == 0 + + && temp[j] == 0) + + { + + + // Print the output + + cout << arr[i] << "," << arr[j] << + + "," << arr[p.first] << "," << arr[p.second]; + + temp[p.second] = 1; + + temp[i] = 1; + + temp[j] = 1; + + break; + + } + + } + + } + + } +} + +// Program for two Sum + +map> twoSum(int nums[], int N) +{ + + map> Map; + + for (int i = 0; i < N - 1; i++) + + { + + for (int j = i + 1; j < N; j++) + + { + + Map[nums[i] + nums[j]].first = i; + + Map[nums[i] + nums[j]].second = j; + + } + + } + + return Map; +} + +// Driver code + +int main() +{ + + int arr[] = { 10, 20, 30, 40, 1, 2 }; + + int n = sizeof(arr) / sizeof(arr[0]); + + int X = 91; + + map> Map = twoSum(arr, n); + + + + // Function call + + fourSum(X, arr, Map, n); + + + return 0; +} diff --git a/CPP/Bike helmet tilt.dev b/CPP/Bike helmet tilt.dev new file mode 100644 index 0000000..c6a18be --- /dev/null +++ b/CPP/Bike helmet tilt.dev @@ -0,0 +1,51 @@ +[Project] +filename=Bike helmet tilt.dev +name=Project1 +Type=1 +Ver=2 +ObjFiles= +Includes= +Libs= +PrivateResource= +ResourceIncludes= +MakeIncludes= +Compiler= +CppCompiler= +Linker= +IsCpp=1 +Icon= +ExeOutput= +ObjectOutput= +LogOutput= +LogOutputEnabled=0 +OverrideOutput=0 +OverrideOutputName= +HostApplication= +UseCustomMakefile=0 +CustomMakefile= +CommandLine= +Folders= +IncludeVersionInfo=0 +SupportXPThemes=0 +CompilerSet=0 +CompilerSettings=0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;8;0;0;0 + +[VersionInfo] +Major=1 +Minor=0 +Release=0 +Build=0 +LanguageID=1033 +CharsetID=1252 +CompanyName= +FileVersion= +FileDescription=Developed using the Dev-C++ IDE +InternalName= +LegalCopyright= +LegalTrademarks= +OriginalFilename= +ProductName= +ProductVersion= +AutoIncBuildNr=0 +SyncProduct=1 + diff --git a/CPP/CODE FOR FINDING THE TOTAL NO. OF OCCURENCE OF ANY NO. IN SORTED ARRAY USING BINARY SEARCH b/CPP/CODE FOR FINDING THE TOTAL NO. OF OCCURENCE OF ANY NO. IN SORTED ARRAY USING BINARY SEARCH new file mode 100644 index 0000000..1ed586b --- /dev/null +++ b/CPP/CODE FOR FINDING THE TOTAL NO. OF OCCURENCE OF ANY NO. IN SORTED ARRAY USING BINARY SEARCH @@ -0,0 +1,102 @@ + + //CODE FOR FINDING THE TOTAL NO. OF OCCURENCES OF ANY NO. IN SORTED ARRAY USING BINARY SEARCH + + +#include +using namespace std; + + //FUNTION FOR FINDING THE FIRST MOST OCCURANCE OF A NUMBER + int first_occurence(int arr[],int n,int key) + { + int start=0,end=n-1,mid,first_index; + mid=start + (end-start)/2; + + + while(start<=end) + { + if(arr[mid]==key) + { + first_index=mid; + end=mid-1 ; + } + if(arr[mid]key) + { + end=mid-1; + } + + mid=start + (end-start)/2; + + } + + return first_index; + + + } + + + //FUNTION FOR FINDING THE LAST MOST OCCURANCE OF A NUMBER + int last_occurence(int arr[],int n,int key) + { + int start=0,end=n-1,mid,last_index; + mid=start + (end-start)/2; + + + while(start<=end) + { + if(arr[mid]==key) + { + last_index=mid; + start=mid+1 ; + } + if(arr[mid]key) + { + end=mid-1; + } + + mid=start + (end-start)/2; + + } + + return last_index; + + + } + + +int main() { + int n; + cout<<"ENTER THE LENGTH OF THE ARRAY"<>n; + + int arr[n],key,first_index,last_index; + + + cout<<"ENTER THE ELEMENTS OF SORTED ARRAY"<>arr[i]; + } + + cout<<"ENTER THE ELEMENT/KEY WHOSE OCCURANCE YOU WANT TO FIND"<>key; + + first_index=first_occurence(arr,n,key); //CALLING OF first_occurence FUNCTION + + last_index=last_occurence(arr,n,key); //CALLING OF last_occurence FUNCTION + + cout<<"NO. OF OCCURENCE OF "< +#define MAX 5 +using namespace std; + + +class Queue +{ + public: + int que[MAX]; + int front,rear; + int data; + + Queue() + { + front=-1; + rear=-1; + } + + bool isEmpty() + { + if(front==-1) + { + return true; + } + + else + { + return false; + } + } + + bool isFull() + { + if( (front==0 && rear==MAX-1) || (front==rear+1) ) + { + return true; + } + + else + { + return false; + } + } + + + void enqueue(); + void dequeue(); + void display(); + +}; + +void Queue :: enqueue() +{ + if(isFull()) + { + cout<<"\nQueue is Full\n"; + } + + else + { + cout<<"\nEnter element in queue: "; + cin>>data; + + if(front==-1) + { + front=rear=0; + } + + else + { + rear=(rear+1)%MAX; + } + + que[rear]=data; + } + +} + + +void Queue :: dequeue() +{ + if(isEmpty()) + { + cout<<"\nCan't perform delete operation\n"; + } + + else + { + int item=que[front]; + + if(front==rear) + { + front=rear=-1; + } + + else + { + front=(front+1)% MAX; + } + } +} + +void Queue :: display() +{ + int f=front; + int r=rear; + + + if(isEmpty()) + { + cout<<"\nQueue is empty"; + } + + if(f <= r) + { + while (f <= r) + { + cout<<"| "<>ch; + + switch(ch) + { + + case 1: + q.enqueue(); + q.display(); + + break; + + case 2: + q.dequeue(); + q.display(); + + break; + + case 3: + q.display(); + break; + + default: + cout<<"\nSorry!!! you have entered wrong choice"; + } + + cout<<"\n\nDo you want to continue (y/n): "; + cin>>start; + + } + + cout<<"\nThank you!!!"; + + return 0; +} diff --git a/CPP/Concatenation_of_consecutive_binary.cpp b/CPP/Concatenation_of_consecutive_binary.cpp new file mode 100644 index 0000000..685f35b --- /dev/null +++ b/CPP/Concatenation_of_consecutive_binary.cpp @@ -0,0 +1,38 @@ + +/*Approach: + +Iterate through the numbers from 1 to n and add the binary representation of each number to the answer. +ans = ans<<(number of bits in the binary representation of the current number) + binary representation of the current number.*/ + + + +#include + +using namespace std; +typedef long long ll; +class Solution { +public: + int concatenatedBinary(int n) { + const unsigned int m = 1000000007; + + ll res = 1,sum=0; + for(ll j=2;j<=n;j++){ + ll i=j,c=0; + while(i){ + c++; + i= i >> 1; + + }res = ((res << c)+j) %m; + + } + return res; + + } +}; +int main() { + Solution S; + int n; + std::cout << "Enter value n" << std::endl; + std::cin >> n; + std::cout << S.concatenatedBinary(n) << std::endl; +} diff --git "a/CPP/Dijkstra\342\200\231s Shortest Path Algorithm.cpp" "b/CPP/Dijkstra\342\200\231s Shortest Path Algorithm.cpp" new file mode 100644 index 0000000..4d4ce6e --- /dev/null +++ "b/CPP/Dijkstra\342\200\231s Shortest Path Algorithm.cpp" @@ -0,0 +1,103 @@ +#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\t\t" << dist[i] << endl; +} + +// Function that implements Dijkstra's single source +// shortest path algorithm for a graph represented using +// adjacency matrix representation +void dijkstra(int graph[V][V], int src) +{ + int dist[V]; // The output array. dist[i] will hold the + // shortest + // distance from src to i + + bool sptSet[V]; // sptSet[i] will be true if vertex i is + // included in shortest + // path tree or shortest distance from src to i is + // finalized + + // Initialize all distances as INFINITE and stpSet[] as + // false + for (int i = 0; i < V; i++) + dist[i] = INT_MAX, sptSet[i] = false; + + // Distance of source vertex from itself is always 0 + dist[src] = 0; + + // Find shortest path for all vertices + for (int count = 0; count < V - 1; count++) { + // Pick the minimum distance vertex from the set of + // vertices not yet processed. u is always equal to + // src in the first iteration. + int u = minDistance(dist, sptSet); + + // Mark the picked vertex as processed + sptSet[u] = true; + + // Update dist value of the adjacent vertices of the + // picked vertex. + for (int v = 0; v < V; v++) + + // Update dist[v] only if is not in sptSet, + // there is an edge from u to v, and total + // weight of path from src to v through u is + // smaller than current value of dist[v] + if (!sptSet[v] && graph[u][v] + && dist[u] != INT_MAX + && dist[u] + graph[u][v] < dist[v]) + dist[v] = dist[u] + graph[u][v]; + } + + // print the constructed distance array + printSolution(dist); +} + +// driver's code +int main() +{ + + /* Let us create the example graph discussed above */ + int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, + { 4, 0, 8, 0, 0, 0, 0, 11, 0 }, + { 0, 8, 0, 7, 0, 4, 0, 0, 2 }, + { 0, 0, 7, 0, 9, 14, 0, 0, 0 }, + { 0, 0, 0, 9, 0, 10, 0, 0, 0 }, + { 0, 0, 4, 14, 10, 0, 2, 0, 0 }, + { 0, 0, 0, 0, 0, 2, 0, 1, 6 }, + { 8, 11, 0, 0, 0, 0, 1, 0, 7 }, + { 0, 0, 2, 0, 0, 0, 6, 7, 0 } }; + + // Function call + dijkstra(graph, 0); + + return 0; +} + diff --git a/CPP/FractionalKnapsack.cpp b/CPP/FractionalKnapsack.cpp new file mode 100644 index 0000000..b010496 --- /dev/null +++ b/CPP/FractionalKnapsack.cpp @@ -0,0 +1,87 @@ +// C++ program to solve fractional Knapsack Problem +#include + +using namespace std; + +// Structure for an item which stores weight & corresponding value of Item +struct Item { + int value, weight; + + // Constructor + Item(int value, int weight) + : value(value), weight(weight) + { + } +}; + +// Comparison function to sort Item according to val/weight ratio +bool cmp(struct Item a, struct Item b) +{ + double r1 = (double)a.value / a.weight; + double r2 = (double)b.value / b.weight; + return r1 > r2; +} + +// Main greedy function to solve problem +double fractionalKnapsack(struct Item arr[], + int N, int size) +{ + // Sort Item on basis of ratio + sort(arr, arr + size, cmp); + + // Current weight in knapsack + int curWeight = 0; + + // Result (value in Knapsack) + double finalvalue = 0.0; + + // Looping through all Items + for (int i = 0; i < size; i++) { + + // If adding Item won't overflow, + // add it completely + if (curWeight + arr[i].weight <= N) { + curWeight += arr[i].weight; + finalvalue += arr[i].value; + } + + // If we can't add current Item, + // add fractional part of it + else { + int remain = N - curWeight; + finalvalue += arr[i].value + * ((double)remain + / arr[i].weight); + + break; + } + } + + // Returning final value + return finalvalue; +} + +// Driver Code +int main() +{ + // Weight of knapsack + int N = 60; + + // Given weights and values as a pairs + Item arr[] = { { 100, 10 }, + { 280, 40 }, + { 120, 20 }, + { 120, 24 } }; + + int size = sizeof(arr) / sizeof(arr[0]); + + // Function Call + cout << "Maximum profit earned = " + << fractionalKnapsack(arr, N, size); + return 0; +} + + +Output: +Maximum profit earned = 440 + diff --git a/CPP/Group_Anagrams.cpp b/CPP/Group_Anagrams.cpp new file mode 100644 index 0000000..e13c0d4 --- /dev/null +++ b/CPP/Group_Anagrams.cpp @@ -0,0 +1,21 @@ +//49:- Group Anagrams +// https://leetcode.com/problems/group-anagrams/ + +vector> groupAnagrams(vector& strs) { + unordered_map>mp; + for(auto x:strs){ + string a=x; + sort(x.begin(),x.end()); + mp[x].push_back(a); + } + + + vector>v; + //sort(strs.begin(),strs.end()); + + for(auto it:mp){ + v.push_back(it.second); + } + return v; + + } diff --git a/Hanoi Algorithm b/CPP/Hanoi Algorithm similarity index 100% rename from Hanoi Algorithm rename to CPP/Hanoi Algorithm diff --git a/CPP/Heap-sort.cpp b/CPP/Heap-sort.cpp new file mode 100644 index 0000000..b1575c7 --- /dev/null +++ b/CPP/Heap-sort.cpp @@ -0,0 +1,57 @@ + #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/CPP/Is_Graph_Bipartite b/CPP/Is_Graph_Bipartite new file mode 100644 index 0000000..49abad9 --- /dev/null +++ b/CPP/Is_Graph_Bipartite @@ -0,0 +1,29 @@ +//785. Is Graph Bipartite? +//https://leetcode.com/problems/is-graph-bipartite/ + +class Solution { +public: + bool dfs(int node,vector>& adj,vector&color){ + if(color[node]==-1) color[node]=1; + for(auto it :adj[node]){ + + if(color[it]==-1){ + color[it]=1-color[node]; + if(dfs(it,adj,color)==false ) return false; + } + else if(color[node]==color[it]) return false; + } + return true; + } + bool isBipartite(vector>& graph) { + int n= graph.size(); + vectorcolor(n,-1); + for(int i=0;i +using namespace std; + +int maxSubArraySum(int a[], int size) +{ + int max_so_far = INT_MIN, max_ending_here = 0; + + for (int i = 0; i < size; i++) { + max_ending_here = max_ending_here + a[i]; + if (max_so_far < max_ending_here) + max_so_far = max_ending_here; + + if (max_ending_here < 0) + max_ending_here = 0; + } + return max_so_far; +} + +// Driver Code +int main() +{ + int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; + int n = sizeof(a) / sizeof(a[0]); + + // Function Call + int max_sum = maxSubArraySum(a, n); + cout << "Maximum contiguous sum is " << max_sum; + return 0; +} diff --git a/CPP/Kosaraju using dfs.cpp b/CPP/Kosaraju using dfs.cpp new file mode 100644 index 0000000..879e7f7 --- /dev/null +++ b/CPP/Kosaraju using dfs.cpp @@ -0,0 +1,126 @@ +#include +#include +#include +using namespace std; + +class Graph +{ + int V; // No. of vertices + list *adj; // An array of adjacency lists + + // A recursive function to print DFS + // starting from v + void DFSUtil(int v, bool visited[]); +public: + // Constructor and Destructor + Graph(int V) { this->V = V; adj = new list[V];} + ~Graph() { delete [] adj; } + + // Method to add an edge + void addEdge(int v, int w); + + // The main function that returns true if the + // graph is strongly connected, otherwise false + bool isSC(); + + // Function that returns reverse (or transpose) + // of this graph + Graph getTranspose(); +}; + +// A recursive function to print DFS starting from v +void Graph::DFSUtil(int v, bool visited[]) +{ + // Mark the current node as visited and print it + 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]) + DFSUtil(*i, visited); +} + +// Function that returns reverse (or transpose) of this graph +Graph Graph::getTranspose() +{ + Graph g(V); + for (int v = 0; v < V; v++) + { + // Recur for all the vertices adjacent to this vertex + list::iterator i; + for(i = adj[v].begin(); i != adj[v].end(); ++i) + { + g.adj[*i].push_back(v); + } + } + return g; +} + +void Graph::addEdge(int v, int w) +{ + adj[v].push_back(w); // Add w to v’s list. +} + +// The main function that returns true if graph +// is strongly connected +bool Graph::isSC() +{ + // St1p 1: Mark all the vertices as not visited + // (For first DFS) + bool visited[V]; + for (int i = 0; i < V; i++) + visited[i] = false; + + // Step 2: Do DFS traversal starting from first vertex. + DFSUtil(0, visited); + + // If DFS traversal doesn’t visit all vertices, + // then return false. + for (int i = 0; i < V; i++) + if (visited[i] == false) + return false; + + // Step 3: Create a reversed graph + Graph gr = getTranspose(); + + // Step 4: Mark all the vertices as not visited + // (For second DFS) + for(int i = 0; i < V; i++) + visited[i] = false; + + // Step 5: Do DFS for reversed graph starting from + // first vertex. Starting Vertex must be same starting + // point of first DFS + gr.DFSUtil(0, visited); + + // If all vertices are not visited in second DFS, then + // return false + for (int i = 0; i < V; i++) + if (visited[i] == false) + return false; + + return true; +} + +// Driver program to test above functions +int main() +{ + // Create graphs given in the above diagrams + Graph g1(5); + g1.addEdge(0, 1); + g1.addEdge(1, 2); + g1.addEdge(2, 3); + g1.addEdge(3, 0); + g1.addEdge(2, 4); + g1.addEdge(4, 2); + g1.isSC()? cout << "Yes\n" : cout << "No\n"; + + Graph g2(4); + g2.addEdge(0, 1); + g2.addEdge(1, 2); + g2.addEdge(2, 3); + g2.isSC()? cout << "Yes\n" : cout << "No\n"; + + return 0; +} diff --git a/CPP/LONGEST-INCREASING-SUBSEQUENCE.cpp b/CPP/LONGEST-INCREASING-SUBSEQUENCE.cpp new file mode 100644 index 0000000..63965e1 --- /dev/null +++ b/CPP/LONGEST-INCREASING-SUBSEQUENCE.cpp @@ -0,0 +1,40 @@ +/* Dynamic Programming C/C++ implementation of LIS problem */ +#include +#include + +/* lis() returns the length of the longest increasing + subsequence in arr[] of size n */ +int lis(int arr[], int n) +{ + int *lis, i, j, max = 0; + lis = (int*)malloc(sizeof(int) * n); + + /* Initialize LIS values for all indexes */ + for (i = 0; i < n; i++) + lis[i] = 1; + + /* Compute optimized LIS values in bottom up manner */ + for (i = 1; i < n; i++) + for (j = 0; j < i; j++) + if (arr[i] > arr[j] && lis[i] < lis[j] + 1) + lis[i] = lis[j] + 1; + + /* Pick maximum of all LIS values */ + for (i = 0; i < n; i++) + if (max < lis[i]) + max = lis[i]; + + /* Free memory to avoid memory leak */ + free(lis); + + 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]); + printf("Length of lis is %d\n", lis(arr, n)); + return 0; +} diff --git a/CPP/LinkedList.cpp b/CPP/LinkedList.cpp new file mode 100644 index 0000000..69a5ffb --- /dev/null +++ b/CPP/LinkedList.cpp @@ -0,0 +1,70 @@ +//Program to detect loop in a linked list using fast and slow pointers + +#include +using namespace std; + +/* Link list node */ +struct Node { + int data; + struct Node* next; +}; + +void push(struct Node** head_ref, int new_data) +{ + /* allocate node */ + struct Node* new_node = new Node; + + /* put in the data */ + new_node->data = new_data; + + /* link the old list off the new node */ + new_node->next = (*head_ref); + + /* move the head to point to the new node */ + (*head_ref) = new_node; +} + +// Returns true if there is a loop in linked list +// else returns false. +bool detectLoop(struct Node* h) +{ + unordered_set s; + while (h != NULL) { + // If this node is already present + // in hashmap it means there is a cycle + // (Because you will be encountering the + // node for the second time). + if (s.find(h) != s.end()) + return true; + + // If we are seeing the node for + // the first time, insert it in hash + s.insert(h); + + h = h->next; + } + + return false; +} + +/* Driver program to test above function*/ +int main() +{ + /* Start with the empty list */ + struct Node* head = NULL; + + push(&head, 20); + push(&head, 4); + push(&head, 15); + push(&head, 10); + + /* Create a loop for testing */ + head->next->next->next->next = head; + + if (detectLoop(head)) + cout << "Loop found"; + else + cout << "No Loop"; + + return 0; +} diff --git a/CPP/Longest Consecutive Sequence.cpp b/CPP/Longest Consecutive Sequence.cpp new file mode 100644 index 0000000..8c37118 --- /dev/null +++ b/CPP/Longest Consecutive Sequence.cpp @@ -0,0 +1,45 @@ +class Solution { +public: + int longestConsecutive(vector& nums) { + int n=nums.size(); + // unordered_sets; + // for(int i=0;i +using namespace std; + +int dp[1001][1001]; +bool rec(int i,int j,string &s){ + if(i==j) + return dp[i][j]=1; + if(i>j) + return 1; + if(dp[i][j]!=-1) + return dp[i][j]; + if(s[i]==s[j]){ + return dp[i][j]= rec(i+1,j-1,s); + } + else + return dp[i][j]=0; + +} +string longestPalindrome(string s) { + int n=s.size(),i, j; + for(i=0;ians) + in=i,ij=j,ans=(j-i+1); + } + } + return s.substr(in,ij-in+1); +} + +int main() +{ + string str; + cin>>str; + cout< minInterval(vector>& intervals, vector& queries) { + sort(intervals.begin(), intervals.end(), [&](const vector &x, const vector &y) { + return x[1] - x[0] < y[1] - y[0]; + }); + int i, n = queries.size(); + vector ret(n, -1); + set> st; + for(i=0; ifirst <= end) { + auto it2 = next(it); + ret[it->second] = end - start + 1; + st.erase(it); + it = it2; + } + } + return ret; + } +}; diff --git a/CPP/N-ary Tree Level Order Traversal.cpp b/CPP/N-ary Tree Level Order Traversal.cpp new file mode 100644 index 0000000..b8749b9 --- /dev/null +++ b/CPP/N-ary Tree Level Order Traversal.cpp @@ -0,0 +1,55 @@ +/* +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val) { + val = _val; + } + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; +*/ + +class Solution { +public: + vector> levelOrder(Node* root) { + vector>v; + queueq; + q.push(root); + if(root==nullptr) + return v; + while(1) + { + int sz=q.size(); + if(sz==0) + return v; + vectordata; + while(sz>0) + { + Node* temp=q.front(); + q.pop(); + data.push_back(temp->val); + for(Node* ch : temp->children) + q.push(ch); + // if(temp->children!= nullptr) + // q.push(temp->children); + // if(temp->right!=nullptr) + // q.push(temp->right); + sz--; + + } + v.push_back(data); + + } + return v; + + } +}; \ No newline at end of file diff --git a/CPP/Nodes which are not part of any cycle in a Directed Graph b/CPP/Nodes which are not part of any cycle in a Directed Graph new file mode 100644 index 0000000..f2d7455 --- /dev/null +++ b/CPP/Nodes which are not part of any cycle in a Directed Graph @@ -0,0 +1,174 @@ + +#include +using namespace std; + +class Graph { + + // No. of vertices + int V; + + // Stores the Adjacency List + list* adj; + bool printNodesNotInCycleUtil( + int v, bool visited[], bool* rs, + bool* cyclePart); + +public: + // Constructor + Graph(int V); + + // Member Functions + void addEdge(int v, int w); + void printNodesNotInCycle(); +}; + +// Function to initialize the graph +Graph::Graph(int V) +{ + this->V = V; + adj = new list[V]; +} + +// Function that adds directed edges +// between node v with node w +void Graph::addEdge(int v, int w) +{ + adj[v].push_back(w); +} + +// Function to perform DFS Traversal +// and return true if current node v +// formes cycle +bool Graph::printNodesNotInCycleUtil( + int v, bool visited[], + bool* recStack, bool* cyclePart) +{ + + // If node v is unvisited + if (visited[v] == false) { + + // Mark the current node as + // visited and part of + // recursion stack + visited[v] = true; + recStack[v] = true; + + // Traverse the Adjacency + // List of current node v + for (auto& child : adj[v]) { + + // If child node is unvisited + if (!visited[child] + && printNodesNotInCycleUtil( + child, visited, + recStack, cyclePart)) { + + // If child node is a part + // of cycle node + cyclePart[child] = 1; + return true; + } + + // If child node is visited + else if (recStack[child]) { + cyclePart[child] = 1; + return true; + } + } + } + + // Remove vertex from recursion stack + recStack[v] = false; + return false; +} + +// Function that print the nodes for +// the given directed graph that are +// not present in any cycle +void Graph::printNodesNotInCycle() +{ + + // Stores the visited node + bool* visited = new bool[V]; + + // Stores nodes in recursion stack + bool* recStack = new bool[V]; + + // Stores the nodes that are + // part of any cycle + bool* cyclePart = new bool[V]; + + for (int i = 0; i < V; i++) { + visited[i] = false; + recStack[i] = false; + cyclePart[i] = false; + } + + // Traverse each node + for (int i = 0; i < V; i++) { + + // If current node is unvisited + if (!visited[i]) { + + // Perform DFS Traversal + if (printNodesNotInCycleUtil( + i, visited, recStack, + cyclePart)) { + + // Mark as cycle node + // if it return true + cyclePart[i] = 1; + } + } + } + + // Traverse the cyclePart[] + for (int i = 0; i < V; i++) { + + // If node i is not a part + // of any cycle + if (cyclePart[i] == 0) { + cout << i << " "; + } + } +} + +// Function that print the nodes for +// the given directed graph that are +// not present in any cycle +void solve(int N, int E, + int Edges[][2]) +{ + + // Initialize the graph g + Graph g(N); + + // Create a directed Graph + for (int i = 0; i < E; i++) { + g.addEdge(Edges[i][0], + Edges[i][1]); + } + + // Function Call + g.printNodesNotInCycle(); +} + +// Driver Code +int main() +{ + // Given Number of nodes + int N = 6; + + // Given Edges + int E = 7; + + int Edges[][2] = { { 0, 1 }, { 0, 2 }, + { 1, 3 }, { 2, 1 }, + { 2, 5 }, { 3, 0 }, + { 4, 5 } }; + + // Function Call + solve(N, E, Edges); + + return 0; +} diff --git "a/CPP/Prim\342\200\231s Algorithm.cpp" "b/CPP/Prim\342\200\231s Algorithm.cpp" new file mode 100644 index 0000000..49d81de --- /dev/null +++ "b/CPP/Prim\342\200\231s Algorithm.cpp" @@ -0,0 +1,90 @@ +#include +using namespace std; +int main() +{ + int n; + char c = 'a'; + cout << "enter number of nodes"; + cin >> n; + int g[n][n]; + int stree[n][3]; + for (int i = 0; i < n; i++) + stree[i][0] = stree[i][1] = stree[i][2] = -1; + cout << "enter graph egdes 0 for no egde and weight for edge\n"; + for (int i = 0; i < n; i++) + { + for (int j = i; j < n; j++) + { + g[i][j] = 0; + if (i != j) + { + cout << "(" << ((char)(c + i)) << "," << (char)(c + j) << "):-"; + cin >> g[i][j]; + g[j][i] = g[i][j]; + } + } + } + cout << "\t "; + for (int i = 0; i < n; i++) + cout << (char)(c + i) << "\t"; + for (int i = 0; i < n; i++) + { + cout << endl + << (char)(c + i) << "\t "; + for (int j = 0; j < n; j++) + { + if (g[i][j] != 0) + cout << "|" << g[i][j]; + else + cout << "|-"; + cout << "\t"; + } + } + // root node + stree[0][0] = stree[0][1] = 0; + stree[0][2] = 1; + // making stree + int counter = 0, i = 0; + while (counter < n) + { + for (int k = 0; k < n; k++) + { + if (g[i][k] != 0) + { + if (stree[k][0] == -1 && stree[k][2] != 1) + { + stree[k][0] = i; + stree[k][1] = g[i][k]; + } + else + { + if (stree[k][1] > g[i][k] && stree[k][2] != 1) + { + stree[k][0] = i; + stree[k][1] = g[i][k]; + } + } + } + } + int temp = -1; + for (int k = 0; k < n; k++) + { + if (stree[k][2] != 1 && stree[k][0] != -1) + { + if (temp == -1) + temp = k; + else + { + if (stree[temp][1] > stree[k][1]) + temp = k; + } + } + } + i = temp; + stree[i][2] = 1; + counter++; + } + for (i = 0; i < n; i++) + cout << endl + << (char)(c + i) << ":-" << (char)(c + stree[i][0]) << "," << stree[i][1]; +} \ No newline at end of file diff --git a/CPP/Queue using Array.cpp b/CPP/Queue using Array.cpp new file mode 100644 index 0000000..8d7ba03 --- /dev/null +++ b/CPP/Queue using Array.cpp @@ -0,0 +1,158 @@ +#include +#define MAX 10 +using namespace std; + + +class Queue +{ + public: + int que[MAX]; + int front,rear; + int data; + + Queue() + { + front=-1; + rear=-1; + } + + bool isEmpty() + { + if(front==-1) + { + return true; + } + + else + { + return false; + } + } + + bool isFull() + { + if(rear==MAX-1) + { + return true; + } + + else + { + return false; + } + } + + + void enqueue(); + void dequeue(); + void display(); + +}; + +void Queue :: enqueue() +{ + if(isFull()) + { + cout<<"\nQueue is Full"; + } + + else + { + cout<<"\nEnter element in queue: "; + cin>>data; + + rear++; + que[rear]=data; + + if(front==-1) + { + front=0; + } + } + +} + + +void Queue :: dequeue() +{ + if(isEmpty()) + { + cout<<"\nCan't perform delete operation\n"; + } + + else + { + int item=que[front]; + + if(front==rear) + { + front=rear=-1; + } + + else + { + front++; + } + } +} + +void Queue :: display() +{ + + if(isEmpty()) + { + cout<<"\nQueue is empty"; + } + + else + { + for(int i=front;i<=rear;i++) + { + cout<<"| "<>ch; + + switch(ch) + { + + case 1: + q.enqueue(); + q.display(); + + break; + + case 2: + q.dequeue(); + q.display(); + + break; + + default: + cout<<"\nSorry!!! you have entered wrong choice"; + } + + cout<<"\n\nDo you want to continue (y/n): "; + cin>>start; + + } + + cout<<"\nThank you!!!"; + + return 0; +} diff --git a/CPP/Quick_Sort.cpp b/CPP/Quick_Sort.cpp new file mode 100644 index 0000000..5e164a4 --- /dev/null +++ b/CPP/Quick_Sort.cpp @@ -0,0 +1,83 @@ +// Quick Sort + +# include +using namespace std; + + +// Function to swap elements of array +void swap(int arr[], int a, int b) +{ + int temp = arr[a]; + arr[a] = arr[b]; + arr[b] = temp; + return; +} + + +// Function to partition around pivot, i.e, separate smaller and greater numbers into two arrays +// and return correct index of pivot +int partition(int arr[], int l, int r) +{ + // select pivot element, here, last element of array + int pivot = arr[r]; + // i = points to last number in array less than pivot + int i = l-1; + + // traverse array from l'th to r-1'th element + for (int j=l; j> n; + + int arr[n]; + cout << "\nEnter numbers to be sorted : " << endl; + for (int i=0; i> arr[i]; + } + + // Perform Quick Sort + quick_sort(arr, 0, n-1); + + // Output Sorted array + cout << "\nSorted Numbers : " << endl; + for (int i=0; i +using namespace std; +#define ll long long int +#define sz(x) x.size() +#define pb push_back +#define pb2 pop_back +#define ff first +#define ss second +#define lb lower_bound +#define ub upper_bound +#define bend(x) x.begin(), x.end() +#define vi vector +#define mapp map +#define sett set +#define ve vector +#define un_m unordered_map +#define f(i, a, b) for (i = a; i < b; i++) +#define f2(i, x) for (i = a.begin(); i != a.end(); i++) +#define maxxx INT32_MAX +#define mp make_pair +/* +const unsigned int moduli = 1000000007; +ll gcd(ll a, ll b) +{ + if (b == 0) + return a; + return gcd(b, a % b); +} +*/ +/* +ll getIndex(vector v, ll K) +{ + auto it = find(v.begin(), v.end(), K); + + if (it != v.end()) { + + ll index = distance(v.begin(), it); + return index; + } + + return -1; + +} +*/ +/* +string d2b(ll N) +{ + + // To store the binary number + ll B_Number = 0; + ll cnt = 0; + while (N != 0) { + ll rem = N % 2; + ll c = pow(10, cnt); + B_Number += rem * c; + N /= 2; + + // Count used to store exponent value + cnt++; + } Pattern found at index 0 + + return to_string(B_Number); +} */ +void solution() +{ + +// ll n,m,k; + + string aa,s,t; + cin>>s>>t; + aa=s; + ll code=0,code2=0; + ll l1=s.length(); + ll l2=t.length(); + vi v; + s+="#"; + s+=t; + //cout<0 && t[i]!=t[tt]) + tt=pi[tt-1]; + + if(t[i]==t[tt]) + tt++; + + pi[i]=tt; + } + + ll cnt = 0, prev = 0; + ll n=t.length(); +/* f(i,0,n) + { + tt=prev; + while(tt>0 && s[i]!=s[tt]) + tt=pi[tt-1]; + if(s[i]==t[tt]) + tt++; + prev=tt; + if(tt==l2) + { + aa.pb(i+1); + cnt++; + } + }*/ + + for(i=0;i> tc; + while (tc--) + { + solution(); + cout << endl; + } + + return 0; +} +/* +ll power(ll x,ll y) +{ + //(x^y)%MOD + ll ans=1,s=x; + while(y){ + if(y&1){ + ans*=s; + ans%=moduli; + } + s*=s; + s%=moduli; + y>>=1; + } + return ans; +} + + +*/ diff --git a/CPP/Reverse_linked_list.cpp b/CPP/Reverse_linked_list.cpp new file mode 100644 index 0000000..0ff73cf --- /dev/null +++ b/CPP/Reverse_linked_list.cpp @@ -0,0 +1,27 @@ +/** + * 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* reverseList(ListNode* head) { + ListNode* prev = NULL; + ListNode* nxt = NULL; + ListNode* temp = head; + + while(temp != NULL) + { + nxt = temp->next; + temp->next = prev; + prev = temp; + temp = nxt; + } + return prev; + } +}; diff --git a/CPP/SLL(practice with info).cpp b/CPP/SLL(practice with info).cpp new file mode 100644 index 0000000..9d88cce --- /dev/null +++ b/CPP/SLL(practice with info).cpp @@ -0,0 +1,365 @@ + +#include +using namespace std; + +class node +{ + public: + int data; + node* next; +}; + +class list +{ + public: + node* head; + int len; + + list() //Default constructor + { + head==NULL; + len=0; + + } + +void create(); +void display(); +void insert(int pos,int data); +void search(int info); +void del(int info); +void update(int info,int new_data); + +}; + +void list :: create() +{ + node *temp,*ptr; + int add; + + do + { + temp=new node; + cout<<"Enter your data: "; + cin>>temp->data; + temp->next=NULL; + len++; + + if(head==NULL) + { + head=temp; + } + + else + { + ptr=head; + while(ptr->next!=NULL) + { + ptr=ptr->next; + + } + ptr->next=temp; + } + + cout<<"If you want to add more nodes enter 1: "; + cin>>add; + + } while(add==1); + +} + + +void list :: display() +{ + node *ptr; + ptr=head; + + + while(ptr!=NULL) + { + + cout<data<<" ->"; + ptr=ptr->next; + } + cout<<"NULL"; + +} + + +void list :: insert(int pos,int data) +{ + + if(pos==1) + { + + node *temp,*ptr; + temp=new node; + temp->data=data; + + temp->next=head; + head=temp; + + + } + + else if(pos>len) + { + + node *temp,*ptr; + temp=new node; + temp->data=data; + + + ptr=head; + while(ptr->next!=NULL) + { + ptr=ptr->next; + + } + ptr->next=temp; + + } + + else + { + node *temp,*ptr; + temp=new node; + temp->data=data; + + + ptr=head; + + for(int i=1;i<(pos-1);i++) + { + ptr=ptr->next; + + } + + temp->next=ptr->next; + ptr->next=temp; + + + + } + +} + +void list :: search(int info) +{ + node *ptr; + ptr=head; + int flag=0,count=1; + + while(ptr!=NULL) + { + if(ptr->data==info) + { + flag=1; + break; + } + + else + { + ptr=ptr->next; + } + count++; + + } + + if(flag==1) + { + cout<<"Your data has been found at pos: "<data==info) + { + if(curr==head) + { + head=head->next; + delete curr; + flag=1; + cout<<"\nData has been deleted successfully!!!"; + len--; + break; + } + + if(curr->next==NULL) + { + prev->next=NULL; + delete curr; + flag=1; + cout<<"\nData has been deleted successfully!!!"; + len--; + break; + } + + else + { + prev->next=curr->next; + delete curr; + flag=1; + cout<<"\nData has been deleted successfully!!!"; + len--; + break; + } + break; + } + + else + { + prev=curr; + curr=curr->next; + } + + + + + } + + if(flag==0) + { + cout<<"\nSorry!!! data not found"; + } +} + + + + +void list :: update(int info,int new_data) //using info +{ + node *ptr; + ptr=head; + int flag=0; + + while(ptr!=NULL) + { + if(ptr->data==info) + { + if(ptr==head) + { + ptr->data=new_data; + flag=1; + break; + } + + + if(ptr->next==NULL) + { + ptr->data=new_data; + flag=1; + break; + } + + else + { + ptr->data=new_data; + flag=1; + break; + } + } + + else + { + ptr=ptr->next; + } + + } + + + if(flag==0) + { + cout<<"\nSorry!!! data not found"; + } + + +} + + + +int main() +{ + int pos,ch,start=1,data,info,new_data; + node n; + list l; + l.create(); + cout<<"\n"; + l.display(); + + cout<<"\n\n1)Insert\n2)Search\n3)Delete\n4)Update\n5)Exit"; + + while(start==1) + { + cout<<"\n\nEnter your choice: "; + cin>>ch; + + switch(ch) + { + + case 1: + cout<<"\nEnter position where you want to insert data: "; + cin>>pos; + cout<<"Enter data: "; + cin>>data; + l.insert(pos,data); + cout<<"\nData inserted successfully!!!\n"; + l.display(); + break; + + + case 2: + cout<<"Enter data to search: "; + cin>>info; + l.search(info); + break; + + case 3: + cout<<"Enter data that you want to delete: "; + cin>>info; + + l.del(info); + cout<<"\n"; + l.display(); + break; + + case 4: + cout<<"Enter data that you want to update: "; + cin>>info; + cout<<"Enter new data: "; + cin>>new_data; + l.update(info,new_data); + cout<<"\n"; + l.display(); + break; + + case 5: + cout<<"\nThankyou!!!"; + break; + + default: + cout<<"\nSorry!!! you have entered wrong choice"; + } + + cout<<"\n\nPress 1 to contionue or press any key to exit: "; + cin>>start; + + } + + cout<<"\nThankyou!!!"; + + return 0; +} diff --git a/CPP/Search_an_element_in_a_sorted_and_rotated_Array.cpp b/CPP/Search_an_element_in_a_sorted_and_rotated_Array.cpp new file mode 100644 index 0000000..2912dc9 --- /dev/null +++ b/CPP/Search_an_element_in_a_sorted_and_rotated_Array.cpp @@ -0,0 +1,82 @@ +// C++ Program to search an element +// in a sorted and pivoted array + +#include +using namespace std; + +// Standard Binary Search function +int binarySearch(int arr[], int low, int high, int key) +{ + if (high < low) + return -1; + + int mid = (low + high) / 2; + if (key == arr[mid]) + return mid; + + if (key > arr[mid]) + return binarySearch(arr, (mid + 1), high, key); + + return binarySearch(arr, low, (mid - 1), key); +} + +// Function to get pivot. For array 3, 4, 5, 6, 1, 2 +// it returns 3 (index of 6) +int findPivot(int arr[], int low, int high) +{ + // Base cases + if (high < low) + return -1; + if (high == low) + return low; + + // low + (high - low)/2; + int mid = (low + high) / 2; + if (mid < high && arr[mid] > arr[mid + 1]) + return mid; + + if (mid > low && arr[mid] < arr[mid - 1]) + return (mid - 1); + + if (arr[low] >= arr[mid]) + return findPivot(arr, low, mid - 1); + + return findPivot(arr, mid + 1, high); +} + +// Searches an element key in a pivoted +// sorted array arr[] of size n +int pivotedBinarySearch(int arr[], int n, int key) +{ + int pivot = findPivot(arr, 0, n - 1); + + // If we didn't find a pivot, + // then array is not rotated at all + if (pivot == -1) + return binarySearch(arr, 0, n - 1, key); + + // If we found a pivot, then first compare with pivot + // and then search in two subarrays around pivot + if (arr[pivot] == key) + return pivot; + + if (arr[0] <= key) + return binarySearch(arr, 0, pivot - 1, key); + + return binarySearch(arr, pivot + 1, n - 1, key); +} + +// Driver program to check above functions +int main() +{ + // Let us search 3 in below array + int arr1[] = { 5, 6, 7, 8, 9, 10, 1, 2, 3 }; + int n = sizeof(arr1) / sizeof(arr1[0]); + int key = 3; + + // Function calling + cout << "Index of the element is : " + << pivotedBinarySearch(arr1, n, key); + + return 0; +} diff --git a/CPP/Selection sort.cpp b/CPP/Selection sort.cpp new file mode 100644 index 0000000..4fc7282 --- /dev/null +++ b/CPP/Selection sort.cpp @@ -0,0 +1,75 @@ +#include +#define size 4 +using namespace std; + +class select +{ + public: + int arr[size]; + + void get_data(); + void display(); + void selection_sort(); + +}; + +void select::get_data() +{ + for(int i=0;i>arr[i]; + + } +} + +void select::display() +{ + cout<<"\nSorted data \n\n"; + for(int i=0;i +using namespace std; +#define pb push_back +typedef long long ll; +typedef unsigned long int ull; + +int main() +{ + int n = 1e5 + 10; + vector cp(n, true); + cp[0] = cp[1] = false; + + for (int i = 2; i < n; i++) + { + if (cp[i]) + { + for (int j = i * 2; j < n; j += i) + { + cp[j] = false; + } + } + } + + int num; + cin >> num; + + if (cp[num]) + cout << "prime"; + else if(!cp[num]) + cout << "not prime"; +} \ No newline at end of file diff --git a/CPP/Single-Linked-List/readme.md b/CPP/Single-Linked-List/readme.md new file mode 100644 index 0000000..ce95b8f --- /dev/null +++ b/CPP/Single-Linked-List/readme.md @@ -0,0 +1,42 @@ +**Single Linked List** + + +**Single linked list is a sequence of elements in which every element has link to its next element in the sequence.** + +In any single linked list, the individual element is called as "Node". Every "Node" contains two fields, data field, and the next field. The data field is used to store actual value of the node and next field is used to store the address of next node in the sequence. + +The graphical representation of a node in a single linked list is as follows... + +![alt text](http://www.btechsmartclass.com/data_structures/ds_images/Linked_List_Node.png) + +**Example** + +![alt text](http://www.btechsmartclass.com/data_structures/ds_images/Linked_List_Example.png) + +**Operations on Single Linked List** + +The following operations are performed on a Single Linked List + +**1.Insertion** + +**2.Deletion** + +**3.Display** + +Before we implement actual operations, first we need to set up an empty list. First, perform the following steps before implementing actual operations. + +Step 1 - Include all the header files which are used in the program. + +Step 2 - Declare all the user defined functions. + +Step 3 - Define a Node structure with two members data and next + +Step 4 - Define a Node pointer 'head' and set it to NULL. + +Step 5 - Implement the main method by displaying operations menu and make suitable function calls in the main method to perform user selected operation. + +**Output** + + +![image](https://user-images.githubusercontent.com/103835667/193409700-2bb264c0-022a-4fe3-8acc-99853bc4ade9.png) + diff --git a/CPP/Single-Linked-List/singlelinkedlist.cpp b/CPP/Single-Linked-List/singlelinkedlist.cpp new file mode 100644 index 0000000..739d1a4 --- /dev/null +++ b/CPP/Single-Linked-List/singlelinkedlist.cpp @@ -0,0 +1,174 @@ +#include +using namespace std; + +// Node class to represent +// a node of the linked list. +class Node { +public: + int data; + Node* next; + + // Default constructor + Node() + { + data = 0; + next = NULL; + } + + // Parameterised Constructor + Node(int data) + { + this->data = data; + this->next = NULL; + } +}; + +// Linked list class to +// implement a linked list. +class Linkedlist { + Node* head; + +public: + // Default constructor + Linkedlist() { head = NULL; } + + // Function to insert a + // node at the end of the + // linked list. + void insertNode(int); + + // Function to print the + // linked list. + void printList(); + + // Function to delete the + // node at given position + void deleteNode(int); +}; + +// Function to delete the +// node at given position +void Linkedlist::deleteNode(int nodeOffset) +{ + Node *temp1 = head, *temp2 = NULL; + int ListLen = 0; + + if (head == NULL) { + cout << "List empty." << endl; + return; + } + + // Find length of the linked-list. + while (temp1 != NULL) { + temp1 = temp1->next; + ListLen++; + } + + // Check if the position to be + // deleted is less than the length + // of the linked list. + if (ListLen < nodeOffset) { + cout << "Index out of range" + << endl; + return; + } + + // Declare temp1 + temp1 = head; + + // Deleting the head. + if (nodeOffset == 1) { + + // Update head + head = head->next; + delete temp1; + return; + } + + // Traverse the list to + // find the node to be deleted. + while (nodeOffset-- > 1) { + + // Update temp2 + temp2 = temp1; + + // Update temp1 + temp1 = temp1->next; + } + + // Change the next pointer + // of the previous node. + temp2->next = temp1->next; + + // Delete the node + delete temp1; +} + +// Function to insert a new node. +void Linkedlist::insertNode(int data) +{ + // Create the new Node. + Node* newNode = new Node(data); + + // Assign to head + if (head == NULL) { + head = newNode; + return; + } + + // Traverse till end of list + Node* temp = head; + while (temp->next != NULL) { + + // Update temp + temp = temp->next; + } + + // Insert at the last. + temp->next = newNode; +} + +// Function to print the +// nodes of the linked list. +void Linkedlist::printList() +{ + Node* temp = head; + + // Check for empty list. + if (head == NULL) { + cout << "List empty" << endl; + return; + } + + // Traverse the list. + while (temp != NULL) { + cout << temp->data << " "; + temp = temp->next; + } +} + +// Driver Code +int main() +{ + Linkedlist list; + + // Inserting nodes + list.insertNode(1); + list.insertNode(2); + list.insertNode(3); + list.insertNode(4); + + cout << "Elements of the list are: "; + + // Print the list + list.printList(); + cout << endl; + + // Delete node at position 2. + list.deleteNode(2); + + cout << "Elements of the list are: "; + list.printList(); + cout << endl; + return 0; +} diff --git a/CPP/Student DBMS.cpp b/CPP/Student DBMS.cpp new file mode 100644 index 0000000..495fd12 --- /dev/null +++ b/CPP/Student DBMS.cpp @@ -0,0 +1,4144 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + My-caption-Cpp/Student DBMS.cpp at main · Ankit-gurjar/My-caption-Cpp + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ Skip to content + + + + + + + + + + + + + + +
+ +
+ + + + + + + +
+ + + + + +
+ + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + +
+ +
+ + + + Ankit-gurjar  /   + My-caption-Cpp  /   + +
+
+ + + +
+ + +
+
+ Clear Command Palette +
+
+ + + +
+
+ Tip: + Type # to search pull requests +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type # to search issues +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type # to search discussions +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type ! to search projects +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type @ to search teams +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type @ to search people and organizations +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type > to activate command mode +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Go to your accessibility settings to change your keyboard shortcuts +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type author:@me to search your content +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type is:pr to filter to pull requests +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type is:issue to filter to issues +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type is:project to filter to projects +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type is:open to filter to open content +
+
+ Type ? for help and tips +
+
+
+ +
+ +
+
+ We’ve encountered an error and some results aren't available at this time. Type a new search or try again later. +
+
+ + No results matched your search + + + + + + + + + + +
+ + + + + Search for issues and pull requests + + # + + + + Search for issues, pull requests, discussions, and projects + + # + + + + Search for organizations, repositories, and users + + @ + + + + Search for projects + + ! + + + + Search for files + + / + + + + Activate command mode + + > + + + + Search your issues, pull requests, and discussions + + # author:@me + + + + Search your issues, pull requests, and discussions + + # author:@me + + + + Filter to pull requests + + # is:pr + + + + Filter to issues + + # is:issue + + + + Filter to discussions + + # is:discussion + + + + Filter to projects + + # is:project + + + + Filter to open issues, pull requests, and discussions + + # is:open + + + + + + + + + + + + + + + + +
+
+
+ +
+ + + + + + + + + + +
+ + +
+
+
+ + + + + + + + + +
+ +
+ +
+ +
+ + + + / + + My-caption-Cpp + + + Public +
+ + +
+ +
    + +
  • +
    +
    +
    +
  • + + +
  • + +
    + + + + + Unwatch + + + + + 1 + + + +
    +
    +

    Notifications

    + +
    + +
    +
    + + + + + + + + +
    + + +
    + + + + + Get push notifications on iOS or Android. + +
    +
    +
    +
    + + + + +
    +
    +
    + + + +
  • + +
  • +
    + +
    + + + +
    + +
    +
    + + + + + + + +
    + +
    +
    +
    +
    +
  • + +
  • + + +
    +
    + + +
    +
    + +
    + + + +
    + +
    +
    + + + + + + + +
    + +
    +
    +
    +
    +
    +
  • + + + +
+ +
+ +
+
+ + + + +
+ + + + + +
+ Open in github.dev + Open in a new github.dev tab + + + + + + +
+ + +
+ + + + + + + + +Permalink + +
+ +
+
+ + + main + + + + +
+
+
+ Switch branches/tags + +
+ + + +
+ +
+ +
+ + +
+ +
+ + + + + + + + + + + + + + + +
+ + +
+
+
+
+ +
+ +
+ + + Go to file + +
+ + + + +
+
+
+ + + + + + + + + +
+ +
+
+ + + + +
+ + Latest commit + ff210a6 + Oct 24, 2021 + + + + + + History + + +
+
+ +
+ +
+
+ + + 1 + + contributor + + +
+ +

+ Users who have contributed to this file +

+
+ + + + + + +
+
+
+
+ + + + + + + + + + + + + +
+ +
+ + +
+ + 286 lines (245 sloc) + + 6.34 KB +
+ +
+ + + + +
+ +
+
+
+
+ +
+ +
+
+
+ + + +
+ + + + + + + + + +
+ + +
+ +
+
+ +
+ +
+
+ + + +
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
// Include all the necessary libraries.
#include <fstream>
#include <iostream>
#include <stdio.h>
#include <string.h>
+
using namespace std;
+
int main()
{
// Considering the max length of data entered (name) to
// be 15.
char data[15];
int n = 0, option = 0, count_n = 0;
// This is the initial mark alloted to a subject.
string empty = "00";
string proctor = "";
// Name of the file in which DB is stored.
ifstream f("Example.txt");
string line;
+
// The following for loop counts the total number of
// lines in the file.
for (int i = 0; std::getline(f, line); ++i) {
count_n++;
}
+
while (option != 6) {
// This prints out all the available options in the
// DB
cout << "\nAvailable operations: \n1. Add New "
"Students\n2."
<< "Student Login\n3. Faculty Login\n4. "
"Proctor Login\n5. Admin View\n"
<< "6. Exit\nEnter option: ";
cin >> option;
+
if (option == 1) {
cout << "Enter the number of students: ";
cin >> n;
+
count_n = count_n + n;
+
for (int i = 0; i < n; i++) {
ofstream outfile;
outfile.open("Example.txt", ios::app);
// The entire data of a single student is
// stored line-by-line.
cout << "Enter your registration number: ";
cin >> data;
outfile << data << "\t";
+
cout << "Enter your name: ";
cin >> data;
int len = strlen(data);
+
while (len < 15) {
data[len] = ' ';
len = len + 1;
}
outfile << data << "\t";
// Inserting empty data initially into the
// file
outfile << empty << "\t";
outfile << empty << "\t";
+
cout << "Enter your proctor ID: ";
cin >> proctor;
+
outfile << proctor << endl;
}
}
+
else if (option == 2) {
char regno[9];
cout << "Enter your registration number: ";
cin >> regno;
ifstream infile;
int check = 0;
infile.open("Example.txt", ios::in);
+
// This loop prints out the data according to
// the registration number specified.
while (infile >> data) {
if (strcmp(data, regno) == 0) {
cout
<< "\nRegistration Number: " << data
<< endl;
infile >> data;
cout << "Name: " << data << endl;
+
infile >> data;
cout << "CSE1001 mark: " << data
<< endl;
+
infile >> data;
cout << "CSE1002 mark: " << data
<< endl;
+
infile >> data;
cout << "Proctor ID: " << data << endl;
+
infile.close();
check = 1;
}
}
+
if (check == 0) {
cout << "No such registration number found!"
<< endl;
}
}
+
// This loop is used to view and add marks to the
// database of a student.
else if (option == 3) {
char subcode[7];
cout << "Enter your subject code: ";
cin >> subcode;
string code1 = "CSE1001", code2 = "CSE1002",
mark = "";
ifstream infile;
int check = 0;
+
cout << "\nAvailable operations: \n1. Add data "
"about marks\n"
<< "2. View data\nEnter option: ";
cin >> option;
+
if (option == 1) {
cout
<< "Warning! You would need to add mark"
<< "details for all the students!"
<< endl;
for (int i = 0; i < count_n; i++) {
fstream file("Example.txt");
+
// The seek in file has been done
// according to the length
// of the data being inserted. It needs
// to adjusted accordingly for diffferent
// lengths of data.
+
if (strcmp(subcode, code1.c_str())
== 0) {
file.seekp(26 + 37 * i,
std::ios_base::beg);
cout << "Enter the mark of student#"
<< (i + 1) << " : ";
cin >> mark;
file.write(mark.c_str(), 2);
}
+
if (strcmp(subcode, code2.c_str())
== 0) {
file.seekp(29 + 37 * i,
std::ios_base::beg);
cout << "Enter the mark of student#"
<< (i + 1) << " : ";
cin >> mark;
file.write(mark.c_str(), 2);
}
}
}
+
// This loop is used to view marks of a student.
// The extra infile commands have been used to
// get a specific mark only since the data has
// been seperated by a tabspace.
+
else if (option == 2) {
infile.open("Example.txt", ios::in);
if (strcmp(subcode, code1.c_str()) == 0) {
cout << "Registration number - Marks\n"
<< endl;
while (infile >> data) {
cout << data;
infile >> data;
infile >> data;
cout << " - " << data << endl;
infile >> data;
infile >> data;
check = 1;
}
}
+
infile.close();
infile.open("Example.txt", ios::in);
+
if (strcmp(subcode, code2.c_str()) == 0) {
cout << "Registration number - Marks\n"
<< endl;
while (infile >> data) {
cout << data;
infile >> data;
infile >> data;
infile >> data;
cout << " - " << data << endl;
infile >> data;
check = 1;
}
}
}
+
infile.close();
+
if (check == 0) {
cout << "No such subject code found!"
<< endl;
}
}
+
// This loop displays all the details of students
// under the same proctor ID.
+
else if (option == 4) {
char procid[7];
cout << "Enter your proctor ID: ";
cin >> procid;
int check = 0;
char temp1[100], temp2[100], temp3[100];
char temp4[100], id[100];
ifstream infile;
infile.open("Example.txt", ios::in);
+
while (infile >> temp1) {
infile >> temp2;
infile >> temp3;
infile >> temp4;
infile >> id;
+
if (strcmp(id, procid) == 0) {
cout << "\nRegistration Number: "
<< temp1 << endl;
cout << "Name: " << temp2 << endl;
cout << "CSE1001 Mark: " << temp3
<< endl;
cout << "CSE1002 Mark: " << temp4
<< endl;
check = 1;
}
}
+
if (check == 0) {
cout << "No such proctor ID found!" << endl;
}
}
+
// This loop acts as an admin view to see all the
// data in the file.
+
else if (option == 5) {
char password[25];
cout << "Enter the admin password: ";
cin >> password;
+
// This variable value can be changed according
// to your requirement of the administrator
// password.
+
string admin_pass = "admin";
+
if (strcmp(password, admin_pass.c_str()) == 0) {
cout << "Reg No. "
"\tName\tCSE1001\tCSE1002\tProctor "
"ID"
<< endl;
ifstream infile;
infile.open("Example.txt", ios::in);
char data[20];
+
while (infile >> data) {
cout << data << "\t";
infile >> data;
cout << data << "\t";
infile >> data;
cout << data << "\t";
infile >> data;
cout << data << "\t";
infile >> data;
cout << data << endl;
}
}
}
}
}
+
+ + + +
+ +
+ + + + +
+ + +
+ + +
+
+ + +
+ +
+ + +
+ +
+ + +
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + diff --git a/CPP/Subarray sum equal to k.cpp b/CPP/Subarray sum equal to k.cpp new file mode 100644 index 0000000..6c7a9ea --- /dev/null +++ b/CPP/Subarray sum equal to k.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int subarraySum(vector& nums, int k) { + unordered_map mp; + int sum=0; + int ans =0 ; + for(int i=0;i + +using namespace std; + +#define N 9 + +void print(int arr[N][N]) +{ + for (int i = 0; i < N; i++) + { + for (int j = 0; j < N; j++) + cout << arr[i][j] << " "; + cout << endl; + } +} + +bool isSafe(int grid[N][N], int row, + int col, int num) +{ + + for (int x = 0; x <= 8; x++) + if (grid[row][x] == num) + return false; + for (int x = 0; x <= 8; x++) + if (grid[x][col] == num) + return false; + int startRow = row - row % 3, + startCol = col - col % 3; + + for (int i = 0; i < 3; i++) + for (int j = 0; j < 3; j++) + if (grid[i + startRow][j + + startCol] == num) + return false; + + return true; +} + +bool solveSudoku(int grid[N][N], int row, int col) +{ + if (row == N - 1 && col == N) + return true; + if (col == N) { + row++; + col = 0; + } + if (grid[row][col] > 0) + return solveSudoku(grid, row, col + 1); + + for (int num = 1; num <= N; num++) + { + if (isSafe(grid, row, col, num)) + { + grid[row][col] = num; + + if (solveSudoku(grid, row, col + 1)) + return true; + } + grid[row][col] = 0; + } + return false; +} + +int main() +{ + int grid[N][N] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, + { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, + { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, + { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, + { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, + { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, + { 0, 0, 5, 2, 0, 6, 3, 0, 0 } }; + + if (solveSudoku(grid, 0, 0)) + print(grid); + else + cout << "no solution exists " << endl; + + return 0; +} diff --git a/CPP/The_Skyline_Problem.cpp b/CPP/The_Skyline_Problem.cpp new file mode 100644 index 0000000..a8150ed --- /dev/null +++ b/CPP/The_Skyline_Problem.cpp @@ -0,0 +1,59 @@ +//218. The Skyline Problem +//https://leetcode.com/problems/the-skyline-problem/ + +//Code + +bool compare(vector& a, vector& b) { + if(a[0] == b[0]) return a[1] < b[1]; + else return a[0] < b[0]; +} +class Solution { +public: + vector> getSkyline(vector>& arr) { + vector> ans; + vector> dir; + + for(auto it : arr){ + dir.push_back({it[0],-it[2]}); + dir.push_back({it[1],it[2]}); + } + + sort(dir.begin(),dir.end(),compare); + + priority_queue pq; + + int maxVal = 0; + pq.push(0); + + int n = dir.size(); + unordered_map mp; + for(int i=0; i=0){ + mp[v]++; + while(mp[pq.top()]>0){ + mp[pq.top()]--; + pq.pop(); + } + if(pq.empty()){ + if(i==n-1 || dir[i+1][0]!=dir[i][0]){ + ans.push_back({dir[i][0],0}); + maxVal = 0; + } + } + else if(pq.top()maxVal){ + maxVal = pq.top(); + ans.push_back({dir[i][0], maxVal}); + } + } + } + return ans; + } +}; diff --git a/CPP/Transpose_of_Matrix.cpp b/CPP/Transpose_of_Matrix.cpp new file mode 100644 index 0000000..c067c73 --- /dev/null +++ b/CPP/Transpose_of_Matrix.cpp @@ -0,0 +1,28 @@ +#include +using namespace std; + +int main() { + int a[10][10], transpose[10][10], row, column, i, j; + + cout << "Enter rows and columns of matrix: "; + cin >> row >> column; + + cout << "\nEnter elements of matrix: " << endl; + + // Storing matrix elements + for (int i = 0; i < row; ++i) { + for (int j = 0; j < column; ++j) { + cout << "Enter element a" << i + 1 << j + 1 << ": "; + cin >> a[i][j]; + } + } + + // Printing the a matrix + cout << "\nEntered Matrix: " << endl; + for (int i = 0; i < row; ++i) { + for (int j = 0; j < column; ++j) { + cout << " " << a[i][j]; + if (j == column - 1) + cout << endl << endl; + } + } diff --git a/CPP/activity_selection.cpp b/CPP/activity_selection.cpp new file mode 100644 index 0000000..66b0239 --- /dev/null +++ b/CPP/activity_selection.cpp @@ -0,0 +1,32 @@ +#include +using namespace std; +struct Activity{ + int start,finish; +}; +bool ActivityCompare(Activity s1, Activity s2){ + return (s1.finish < s2.finish); +} +void printMaxActivities(Activity arr[],int n){ + sort(arr, arr+n, ActivityCompare); + + cout << "Following activities are selected n"; + + int i = 0; + cout << "(" << arr[i].start << ", " << arr[i].finish << "), "; + + for (int j = 1; j < n; j++) + { + if (arr[j].start >= arr[i].finish) + { + cout << "(" << arr[j].start << ", " + << arr[j].finish << "), "; + i = j; + } + } +} +int main(){ + Activity arr[] = {{5, 9}, {1, 2}, {3, 4}, {0, 6},{5, 7}, {8, 9}}; + int n = sizeof(arr)/sizeof(arr[0]); + printMaxActivities(arr, n); + return 0; +} \ No newline at end of file diff --git a/CPP/antiDiagonalPattern.cpp b/CPP/antiDiagonalPattern.cpp new file mode 100644 index 0000000..a88c4b3 --- /dev/null +++ b/CPP/antiDiagonalPattern.cpp @@ -0,0 +1,60 @@ +#include +using namespace std; + + +vector antiDiagonalPattern(vector>&matrix) + { + vector>arr; + int n = matrix.size(); + int m= matrix[0].size(); + + for(int j = 0;jtemp; + for(auto x : arr){ + int i = x.first; + int j = x.second; + + while(i=0){ + temp.push_back(matrix[i][j]); + i++; + j--; + } + } + return temp; + } + + + +void print(vector&arr){ + for(auto x : arr){ + + cout<>matrix; + int n; + cin>>n; + for(int i = 0;itemp; + for(int j = 0;j>val; + temp.push_back(val); + } + matrix.push_back(temp); + } + vectorans; + ans = antiDiagonalPattern(matrix); + cout<<"AntiDiagonal Pattern : \n"; + print(ans); + return 0; +} + diff --git a/CPP/bal_paranthesis.cpp b/CPP/bal_paranthesis.cpp new file mode 100644 index 0000000..fe94b23 --- /dev/null +++ b/CPP/bal_paranthesis.cpp @@ -0,0 +1,45 @@ +#include +#include +using namespace std; + +int main() +{ + string s="{()}]["; + + stack st; + int flag=0; + + for(int i=0;i +using namespace std; + +int main() +{ + string str; + cout << "enter string"<> str; + string str_rev; + for (int i = str.size() - 1; i >= 0; i--) + { + str_rev.push_back(str[i]); + } + cout< +using namespace std; + +// Class to represent a graph +class Graph { + int V; // No. of vertices' + + // Pointer to an array containing adjacency list + list* adj; + +public: + Graph(int V); // Constructor + + // function to add an edge to graph + void addEdge(int u, int v); + + // Returns true if there is a cycle in the graph + // else false. + bool isCycle(); +}; + +Graph::Graph(int V) +{ + this->V = V; + adj = new list[V]; +} + +void Graph::addEdge(int u, int v) +{ + adj[u].push_back(v); +} + +// This function returns true if there is a cycle +// in directed graph, else returns false. +bool Graph::isCycle() +{ + // Create a vector to store indegrees of all + // vertices. Initialize all indegrees as 0. + vector in_degree(V, 0); + + // Traverse adjacency lists to fill indegrees of + // vertices. This step takes O(V+E) time + for (int u = 0; u < V; u++) { + for (auto v : adj[u]) + in_degree[v]++; + } + + // Create an queue and enqueue all vertices with + // indegree 0 + queue q; + for (int i = 0; i < V; i++) + if (in_degree[i] == 0) + q.push(i); + + // Initialize count of visited vertices + // 1 For src Node + int cnt = 1; + + // Create a vector to store result (A topological + // ordering of the vertices) + vector top_order; + + // One by one dequeue vertices from queue and enqueue + // adjacents if indegree of adjacent becomes 0 + while (!q.empty()) { + + // Extract front of queue (or perform dequeue) + // and add it to topological order + int u = q.front(); + q.pop(); + top_order.push_back(u); + + // Iterate through all its neighbouring nodes + // of dequeued node u and decrease their in-degree + // by 1 + list::iterator itr; + for (itr = adj[u].begin(); itr != adj[u].end(); itr++) + + // If in-degree becomes zero, add it to queue + if (--in_degree[*itr] == 0) + { + q.push(*itr); + //while we are pushing elements to the queue we will incrementing the cnt + cnt++; + } + + + } + + // Check if there was a cycle + if (cnt != V) + return true; + else + return false; +} + +// Driver program to test above functions +int main() +{ + // Create a graph given in the above diagram + Graph g(6); + g.addEdge(0, 1); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(3, 4); + g.addEdge(4, 5); + + if (g.isCycle()) + cout << "Yes"; + else + cout << "No"; + + return 0; +} diff --git a/CPP/dfs.cpp b/CPP/dfs.cpp new file mode 100644 index 0000000..0c4b412 --- /dev/null +++ b/CPP/dfs.cpp @@ -0,0 +1,58 @@ +#include +using namespace std; + +// Graph class represents a directed graph +// using adjacency list representation +class Graph { +public: + map visited; + map > adj; + + // function to add an edge to graph + void addEdge(int v, int w); + + // DFS traversal of the vertices + // reachable from v + void DFS(int v); +}; + +void Graph::addEdge(int v, int w) +{ + adj[v].push_back(w); // Add w to v’s list. +} + +void Graph::DFS(int v) +{ + // Mark the current node as visited and + // print it + visited[v] = true; + cout << v << " "; + + // 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]) + DFS(*i); +} + +// Driver's code +int main() +{ + // Create a graph given in the above diagram + Graph g; + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(2, 3); + g.addEdge(3, 3); + + cout << "Following is Depth First Traversal" + " (starting from vertex 2) \n"; + + // Function call + g.DFS(2); + + return 0; +} diff --git a/CPP/floyd_marshall.cpp b/CPP/floyd_marshall.cpp new file mode 100644 index 0000000..9168553 --- /dev/null +++ b/CPP/floyd_marshall.cpp @@ -0,0 +1,51 @@ +// Floyd-Warshall Algorithm in C++ + +#include +using namespace std; + +// defining the number of vertices +#define nV 4 + +#define INF 999 + +void printMatrix(int matrix[][nV]); + +// Implementing floyd warshall algorithm +void floydWarshall(int graph[][nV]) { + int matrix[nV][nV], i, j, k; + + for (i = 0; i < nV; i++) + for (j = 0; j < nV; j++) + matrix[i][j] = graph[i][j]; + + // Adding vertices individually + for (k = 0; k < nV; k++) { + for (i = 0; i < nV; i++) { + for (j = 0; j < nV; j++) { + if (matrix[i][k] + matrix[k][j] < matrix[i][j]) + matrix[i][j] = matrix[i][k] + matrix[k][j]; + } + } + } + printMatrix(matrix); +} + +void printMatrix(int matrix[][nV]) { + for (int i = 0; i < nV; i++) { + for (int j = 0; j < nV; j++) { + if (matrix[i][j] == INF) + printf("%4s", "INF"); + else + printf("%4d", matrix[i][j]); + } + printf("\n"); + } +} + +int main() { + int graph[nV][nV] = {{0, 3, INF, 5}, + {2, 0, INF, 4}, + {INF, 1, 0, INF}, + {INF, INF, 2, 0}}; + floydWarshall(graph); +} \ No newline at end of file diff --git a/CPP/generateParentheses.cpp b/CPP/generateParentheses.cpp new file mode 100644 index 0000000..6235dc0 --- /dev/null +++ b/CPP/generateParentheses.cpp @@ -0,0 +1,27 @@ +/* +Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. +Input: n = 3 +Output: ["((()))","(()())","(())()","()(())","()()()"] + +*/ + +class Solution { +public: + + void solve(vector &res, string s, int left, int right ){ + if(left==0 && right==0){ + res.push_back(s); + return; + } + + if(left>0) solve(res, s+"(", left-1, right); + if(right>left) solve(res, s+")", left, right-1); + + } + + vector generateParenthesis(int n) { + vector res; + solve(res, "", n, n); + return res; + } +}; diff --git a/CPP/hashing.cpp b/CPP/hashing.cpp new file mode 100644 index 0000000..4ff2033 --- /dev/null +++ b/CPP/hashing.cpp @@ -0,0 +1,135 @@ +#include +#include +#include +#include + +#define SIZE 20 + +struct DataItem { + int data; + int key; +}; + +struct DataItem* hashArray[SIZE]; +struct DataItem* dummyItem; +struct DataItem* item; + +int hashCode(int key) { + return key % SIZE; +} + +struct DataItem *search(int key) { + //get the hash + int hashIndex = hashCode(key); + + //move in array until an empty + while(hashArray[hashIndex] != NULL) { + + if(hashArray[hashIndex]->key == key) + return hashArray[hashIndex]; + + //go to next cell + ++hashIndex; + + //wrap around the table + hashIndex %= SIZE; + } + + return NULL; +} + +void insert(int key,int data) { + + struct DataItem *item = (struct DataItem*) malloc(sizeof(struct DataItem)); + item->data = data; + item->key = key; + + //get the hash + int hashIndex = hashCode(key); + + //move in array until an empty or deleted cell + while(hashArray[hashIndex] != NULL && hashArray[hashIndex]->key != -1) { + //go to next cell + ++hashIndex; + + //wrap around the table + hashIndex %= SIZE; + } + + hashArray[hashIndex] = item; +} + +struct DataItem* delete(struct DataItem* item) { + int key = item->key; + + //get the hash + int hashIndex = hashCode(key); + + //move in array until an empty + while(hashArray[hashIndex] != NULL) { + + if(hashArray[hashIndex]->key == key) { + struct DataItem* temp = hashArray[hashIndex]; + + //assign a dummy item at deleted position + hashArray[hashIndex] = dummyItem; + return temp; + } + + //go to next cell + ++hashIndex; + + //wrap around the table + hashIndex %= SIZE; + } + + return NULL; +} + +void display() { + int i = 0; + + for(i = 0; ikey,hashArray[i]->data); + else + printf(" ~~ "); + } + + printf("\n"); +} + +int main() { + dummyItem = (struct DataItem*) malloc(sizeof(struct DataItem)); + dummyItem->data = -1; + dummyItem->key = -1; + + insert(1, 20); + insert(2, 70); + insert(42, 80); + insert(4, 25); + insert(12, 44); + insert(14, 32); + insert(17, 11); + insert(13, 78); + insert(37, 97); + + display(); + item = search(37); + + if(item != NULL) { + printf("Element found: %d\n", item->data); + } else { + printf("Element not found\n"); + } + + delete(item); + item = search(37); + + if(item != NULL) { + printf("Element found: %d\n", item->data); + } else { + printf("Element not found\n"); + } +} diff --git a/CPP/inclusion and exclusion.cpp b/CPP/inclusion and exclusion.cpp new file mode 100644 index 0000000..e53797e --- /dev/null +++ b/CPP/inclusion and exclusion.cpp @@ -0,0 +1,245 @@ +#include +#include +using namespace std; + +class sport +{ + public: + int hockey[20],cricket[20],football[20]; + int n1,n2,n3,count,count1,count2,count3,intersection; + void get_set1_info(); + void get_set2_info(); + void get_set3_info(); + + void display(int arr[]); + void intersection_2_teams(); + void intersection_3_teams(); + void union_2_teams(); + void union_3_teams(); + +}; + +void sport::get_set1_info() +{ + cout<<"\nEnter total no of players in Hockey team : "; + cin>>n1; + cout<<"\nEnter jersey no : \n"; + for(int i=0;i>hockey[i]; + cout<<"\t"; + + } +} + +void sport::get_set2_info() +{ + cout<<"\nEnter total no of players in Cricket team : "; + cin>>n2; + cout<<"\nEnter jersey no :\n "; + for(int i=0;i>cricket[i]; + cout<<"\t"; + + } +} + +void sport::get_set3_info() +{ + cout<<"\nEnter total no of players in Football team : "; + cin>>n3; + cout<<"\nEnter jersey no : \n"; + for(int i=0;i>football[i]; + cout<<"\t"; + + } +} + + +void sport::display(int arr[]) +{ + + for(int i=0;in2) + { + for(int i=0;in2) + { + for(int i=0;in3) + { + for(int i=0;in3) + { + for(int i=0;i +#define MAX 100 +char st[100]; +int top = -1; +char str[100]; +char str1[100]; + +int findchar(char ch) +{ + if (ch == '-' || ch == '+' || ch == '*' || ch == '/' || ch == '%' || ch == '^' || ch == '&') + { + return 1; + } + else + return 0; +} + +int precedence(char ch) +{ + if (ch == '^' || ch == '&') + { + return 3; + } + else if (ch == '*' || ch == '/') + { + return 2; + } + else if (ch == '+' || ch == '-') + { + return 1; + } + else if (ch == '(') + { + return -1; + } + return 0; +} + +char pop() +{ + if (top == -1) + { + return -1; + } + else + { + return st[top--]; + // top--; + } +} + +void push(char ch) +{ + // top++; + st[++top] = ch; +} + +int main() +{ + int i, j = 0, k; + printf("Enter the infix expression :\n"); + scanf("%s", str); + printf("It's postfix Expression is :\n"); + + for (i = 0; str[i] != '\0'; i++) + { + if (str[i] == '(') + { + push(str[i]); + } + else if (str[i] == ')') + { + for (k = top; st[top] != '('; k--) + { + // str1[j] = pop(); + // j++; + printf("%c", pop()); + } + pop(); + } + else if (!findchar(str[i])) + { + // str1[j] = str[i]; + // j++; + + printf("%c", str[i]); + } + else if (precedence(str[i])) + { + if (precedence(st[top]) == -1) + { + push(str[i]); + } + else if ((top != -1) && (precedence(st[top]) != -1) && precedence(str[i]) <= precedence(st[top])) + { + printf("%c", pop()); + + if (precedence(str[i]) <= precedence(st[top])) + { + printf("%c", pop()); + } + if (precedence(str[i]) <= precedence(st[top])) + { + printf("%c", pop()); + } + push(str[i]); + } + + else if (precedence(str[i]) > precedence(st[top])) + { + push(str[i]); + } + } + } + + while (top >= 0) + { + printf("%c", pop()); + } + printf("\n"); + + return 0; +} diff --git a/insertion sort b/CPP/insertion sort similarity index 100% rename from insertion sort rename to CPP/insertion sort diff --git a/CPP/invertBinaryTree.cpp b/CPP/invertBinaryTree.cpp new file mode 100644 index 0000000..b5bd92d --- /dev/null +++ b/CPP/invertBinaryTree.cpp @@ -0,0 +1,28 @@ +/** +Input: root = [4,2,7,1,3,6,9] +Output: [4,7,2,9,6,3,1] + + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ + +class Solution { +public: + TreeNode* invertTree(TreeNode* root) { + if(!root) return NULL; + + TreeNode* rTree = invertTree(root->right); + TreeNode* lTree = invertTree(root->left); + + root->left = rTree; + root->right = lTree; + return root; + } +}; diff --git a/CPP/kadane.cpp b/CPP/kadane.cpp new file mode 100644 index 0000000..45fa5bc --- /dev/null +++ b/CPP/kadane.cpp @@ -0,0 +1,30 @@ +// C++ program to print largest contiguous array sum +#include +#include +using namespace std; + +int maxSubArraySum(int a[], int size) +{ + int max_so_far = INT_MIN, max_ending_here = 0; + + for (int i = 0; i < size; i++) + { + max_ending_here = max_ending_here + a[i]; + if (max_so_far < max_ending_here) + max_so_far = max_ending_here; + + if (max_ending_here < 0) + max_ending_here = 0; + } + return max_so_far; +} + +/*Driver program to test maxSubArraySum*/ +int main() +{ + int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; + int n = sizeof(a)/sizeof(a[0]); + int max_sum = maxSubArraySum(a, n); + cout << "Maximum contiguous sum is " << max_sum; + return 0; +} diff --git a/CPP/kadanes.cpp b/CPP/kadanes.cpp new file mode 100644 index 0000000..33cf57a --- /dev/null +++ b/CPP/kadanes.cpp @@ -0,0 +1,21 @@ +//KADANE,S ALGORITHM +#include +#define pb push_back +#define ll long long int +#define all(x) x.begin(), x.end() +using namespace std; + + int maxSubarraySum(int arr[], int n){ + + int local_max=0; + int global_max=INT_MIN; + + for(int i=0;iglobal_max) + global_max=local_max; + } + return global_max; + +} diff --git a/CPP/kosaraju using bfs.cpp b/CPP/kosaraju using bfs.cpp new file mode 100644 index 0000000..862197b --- /dev/null +++ b/CPP/kosaraju using bfs.cpp @@ -0,0 +1,145 @@ +#include +using namespace std; + +class Graph +{ + int V; // No. of vertices + list *adj; // An array of adjacency lists + + // A recursive function to print DFS starting from v + void BFSUtil(int v, bool visited[]); +public: + + // Constructor and Destructor + Graph(int V) { this->V = V; adj = new list[V];} + ~Graph() { delete [] adj; } + + // Method to add an edge + void addEdge(int v, int w); + + // The main function that returns true if the + // graph is strongly connected, otherwise false + bool isSC(); + + // Function that returns reverse (or transpose) + // of this graph + Graph getTranspose(); +}; + +// A recursive function to print DFS starting from v +void Graph::BFSUtil(int v, bool visited[]) +{ + // Create a queue for BFS + list queue; + + // Mark the current node as visited and enqueue it + visited[v] = true; + queue.push_back(v); + + // 'i' will be used to get all adjacent vertices + // of a vertex + list::iterator i; + + while (!queue.empty()) + { + // Dequeue a vertex from queue + v = queue.front(); + queue.pop_front(); + + // Get all adjacent vertices of the dequeued vertex s + // If a adjacent has not been visited, then mark it + // visited and enqueue it + for (i = adj[v].begin(); i != adj[v].end(); ++i) + { + if (!visited[*i]) + { + visited[*i] = true; + queue.push_back(*i); + } + } + } +} + +// Function that returns reverse (or transpose) of this graph +Graph Graph::getTranspose() +{ + Graph g(V); + for (int v = 0; v < V; v++) + { + // Recur for all the vertices adjacent to this vertex + list::iterator i; + for (i = adj[v].begin(); i != adj[v].end(); ++i) + g.adj[*i].push_back(v); + } + return g; +} + +void Graph::addEdge(int v, int w) +{ + adj[v].push_back(w); // Add w to v’s list. +} + +// The main function that returns true if graph +// is strongly connected +bool Graph::isSC() +{ + // Step 1: Mark all the vertices as not + // visited (For first BFS) + bool visited[V]; + for (int i = 0; i < V; i++) + visited[i] = false; + + // Step 2: Do BFS traversal starting + // from first vertex. + BFSUtil(0, visited); + + // If BFS traversal doesn’t visit all + // vertices, then return false. + for (int i = 0; i < V; i++) + if (visited[i] == false) + return false; + + // Step 3: Create a reversed graph + Graph gr = getTranspose(); + + // Step 4: Mark all the vertices as not + // visited (For second BFS) + for(int i = 0; i < V; i++) + visited[i] = false; + + // Step 5: Do BFS for reversed graph + // starting from first vertex. + // Starting Vertex must be same starting + // point of first DFS + gr.BFSUtil(0, visited); + + // If all vertices are not visited in + // second DFS, then return false + for (int i = 0; i < V; i++) + if (visited[i] == false) + return false; + + return true; +} + +// Driver program to test above functions +int main() +{ + // Create graphs given in the above diagrams + Graph g1(5); + g1.addEdge(0, 1); + g1.addEdge(1, 2); + g1.addEdge(2, 3); + g1.addEdge(3, 0); + g1.addEdge(2, 4); + g1.addEdge(4, 2); + g1.isSC()? cout << "Yes\n" : cout << "No\n"; + + Graph g2(4); + g2.addEdge(0, 1); + g2.addEdge(1, 2); + g2.addEdge(2, 3); + g2.isSC()? cout << "Yes\n" : cout << "No\n"; + + return 0; +} diff --git a/CPP/kruskal.cpp b/CPP/kruskal.cpp new file mode 100644 index 0000000..1672c32 --- /dev/null +++ b/CPP/kruskal.cpp @@ -0,0 +1,93 @@ +// Kruskal's algorithm in C++ + +#include +#include +#include +using namespace std; + +#define edge pair + +class Graph +{ +private: + vector > G; // graph + vector > T; // mst + int *parent; + int V; // number of vertices/nodes in graph +public: + Graph(int V){ + parent = new int[V]; + + // i 0 1 2 3 4 5 + // parent[i] 0 1 2 3 4 5 + for (int i = 0; i < V; i++) + parent[i] = i; + + G.clear(); + T.clear(); +} + void AddWeightedEdge(int u, int v, int w){ + G.push_back(make_pair(w, edge(u, v))); +} + int find_set(int i){ + // If i is the parent of itself + if (i == parent[i]) + return i; + else + return find_set(parent[i]); +} + void union_set(int u, int v){ + parent[u] = parent[v]; +} + void kruskal(){ + int i, uRep, vRep; + sort(G.begin(), G.end()); // increasing weight + for (i = 0; i < G.size(); i++) + { + uRep = find_set(G[i].second.first); + vRep = find_set(G[i].second.second); + if (uRep != vRep) + { + T.push_back(G[i]); // add to tree + union_set(uRep, vRep); + } + } +} + void print(){ + cout << "Edge :" + << " Weight" << endl; + for (int i = 0; i < T.size(); i++) + { + cout << T[i].second.first << " - " << T[i].second.second << " : " + << T[i].first; + cout << endl; + } +} +}; + + +int main() +{ + Graph g(6); + + g.AddWeightedEdge(0, 1, 4); + g.AddWeightedEdge(0, 2, 4); + g.AddWeightedEdge(1, 2, 2); + g.AddWeightedEdge(1, 0, 4); + g.AddWeightedEdge(2, 0, 4); + g.AddWeightedEdge(2, 1, 2); + g.AddWeightedEdge(2, 3, 3); + g.AddWeightedEdge(2, 5, 2); + g.AddWeightedEdge(2, 4, 4); + g.AddWeightedEdge(3, 2, 3); + g.AddWeightedEdge(3, 4, 3); + g.AddWeightedEdge(4, 2, 4); + g.AddWeightedEdge(4, 3, 3); + g.AddWeightedEdge(5, 2, 2); + g.AddWeightedEdge(5, 4, 3); + + g.kruskal(); + + g.print(); + return 0; +} \ No newline at end of file diff --git a/CPP/largestBST.cpp b/CPP/largestBST.cpp new file mode 100644 index 0000000..c895ca9 --- /dev/null +++ b/CPP/largestBST.cpp @@ -0,0 +1,65 @@ +#include +#include +using namespace std; +struct node{ + int data; + node *left,*right; + node(int val){ + data = val; + left = NULL; + right = NULL; + + } +}; +struct info{ + int size; + int max; + int min; + int ans; + bool isBST; +}; +info largestBST(node* root){ + if(root == NULL){ + return {0,INT_MIN,INT_MAX,0,true}; //directly typecasting the value in structure info + } + if(root->left == NULL && root->right == NULL){ + return {1,root->data,root->data,1,true}; //for leaf node + } + + info leftInfo = largestBST(root->left); //calling for left subtree + info rightInfo = largestBST(root->right); //calling for right subtree + + info curr; + curr.size = (1+leftInfo.size+rightInfo.size); + //if left and right subtree are bst then only check for current node, otherwise it's meaningless + + if(leftInfo.isBST && rightInfo.isBST && leftInfo.max < root->data && rightInfo.min > root->data){ + curr.min = min(leftInfo.min,min(rightInfo.min,root->data)); + curr.max = max(rightInfo.max,max(leftInfo.max,root->data)); + curr.ans = curr.size; + curr.isBST = true; + return curr; + } + curr.ans = max(leftInfo.ans,rightInfo.ans); + curr.isBST = false; + return curr; + + +} + +int main(){ + /* + 5 + / \ + 3 6 + / \ + 2 4 + */ + node* root = new node(5); + root->left =new node(3); + //root->left->left =new node(2); + root->left->right =new node(4); + root->right = new node(6); + cout<<"largest bst size : "< +using namespace std; + +/* A binary tree node has data, +pointer to left child +and a pointer to right child */ +class node { +public: + int data; + node *left, *right; +}; + +/* Function prototypes */ +void printCurrentLevel(node* root, int level); +int height(node* node); +node* newNode(int data); + +/* Function to print level +order traversal a tree*/ +void printLevelOrder(node* root) +{ + int h = height(root); + int i; + for (i = 1; i <= h; i++) + printCurrentLevel(root, i); +} + +/* Print nodes at a current level */ +void printCurrentLevel(node* root, int level) +{ + if (root == NULL) + return; + if (level == 1) + cout << root->data << " "; + else if (level > 1) { + printCurrentLevel(root->left, level - 1); + printCurrentLevel(root->right, level - 1); + } +} + +/* Compute the "height" of a tree -- the number of + nodes along the longest path from the root node + down to the farthest leaf node.*/ +int height(node* node) +{ + if (node == NULL) + return 0; + else { + /* compute the height of each subtree */ + int lheight = height(node->left); + int rheight = height(node->right); + + /* use the larger one */ + if (lheight > rheight) { + return (lheight + 1); + } + else { + return (rheight + 1); + } + } +} + +/* Helper function that allocates +a new node with the given data and +NULL left and right pointers. */ +node* newNode(int data) +{ + node* Node = new node(); + Node->data = data; + Node->left = NULL; + Node->right = NULL; + + return (Node); +} + +/* Driver code*/ +int main() +{ + node* root = newNode(1); + root->left = newNode(2); + root->right = newNode(3); + root->left->left = newNode(4); + root->left->right = newNode(5); + + cout << "Level Order traversal of binary tree is \n"; + printLevelOrder(root); + + return 0; +} + diff --git a/linear search b/CPP/linear search similarity index 100% rename from linear search rename to CPP/linear search diff --git a/link list insertion operations b/CPP/link list insertion operations similarity index 100% rename from link list insertion operations rename to CPP/link list insertion operations diff --git a/CPP/linkedListCycle.cpp b/CPP/linkedListCycle.cpp new file mode 100644 index 0000000..01ce102 --- /dev/null +++ b/CPP/linkedListCycle.cpp @@ -0,0 +1,23 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + bool hasCycle(ListNode *head) { + if(!head || !head->next) return 0; + ListNode* fast=head, *slow=head; + while(fast && fast->next){ + fast=fast->next->next; + slow=slow->next; + + if(fast==slow) + return 1; + } + return 0; + } +}; diff --git a/CPP/maxSum.cpp b/CPP/maxSum.cpp new file mode 100644 index 0000000..770fd46 --- /dev/null +++ b/CPP/maxSum.cpp @@ -0,0 +1,34 @@ +// C++ program to maximize the sum of difference +// between consecutive elements in circular array +#include +using namespace std; + +// Return the maximum Sum of difference between +// consecutive elements. +int maxSum(int arr[], int n) +{ + int sum = 0; + + // Sorting the array. + sort(arr, arr + n); + + // Subtracting a1, a2, a3,....., a(n/2)-1, an/2 + // twice and adding a(n/2)+1, a(n/2)+2, a(n/2)+3,. + // ...., an - 1, an twice. + for (int i = 0; i < n/2; i++) + { + sum -= (2 * arr[i]); + sum += (2 * arr[n - i - 1]); + } + + return sum; +} + +// Driver Program +int main() +{ + int arr[] = { 4, 2, 1, 8 }; + int n = sizeof(arr)/sizeof(arr[0]); + cout << maxSum(arr, n) << endl; + return 0; +} diff --git a/CPP/max_subarrray.cpp b/CPP/max_subarrray.cpp new file mode 100644 index 0000000..492a355 --- /dev/null +++ b/CPP/max_subarrray.cpp @@ -0,0 +1,69 @@ +// A Divide and Conquer based program for maximum subarray +// sum problem +#include +#include + +// A utility function to find maximum of two integers +int max(int a, int b) { return (a > b) ? a : b; } + +// A utility function to find maximum of three integers +int max(int a, int b, int c) { return max(max(a, b), c); } + +// Find the maximum possible sum in arr[] auch that arr[m] +// is part of it +int maxCrossingSum(int arr[], int l, int m, int h) +{ + // Include elements on left of mid. + int sum = 0; + int left_sum = INT_MIN; + for (int i = m; i >= l; i--) { + sum = sum + arr[i]; + if (sum > left_sum) + left_sum = sum; + } + + // Include elements on right of mid + sum = 0; + int right_sum = INT_MIN; + for (int i = m + 1; i <= h; i++) { + sum = sum + arr[i]; + if (sum > right_sum) + right_sum = sum; + } + + // Return sum of elements on left and right of mid + // returning only left_sum + right_sum will fail for + // [-2, 1] + return max(left_sum + right_sum, left_sum, right_sum); +} + +// Returns sum of maximum sum subarray in aa[l..h] +int maxSubArraySum(int arr[], int l, int h) +{ + // Base Case: Only one element + if (l == h) + return arr[l]; + + // Find middle point + int m = (l + h) / 2; + + /* Return maximum of following three possible cases + a) Maximum subarray sum in left half + b) Maximum subarray sum in right half + c) Maximum subarray sum such that the subarray + crosses the midpoint */ + return max(maxSubArraySum(arr, l, m), + maxSubArraySum(arr, m + 1, h), + maxCrossingSum(arr, l, m, h)); +} + +/*Driver program to test maxSubArraySum*/ +int main() +{ + int arr[] = { 2, 3, 4, 5, 7 }; + int n = sizeof(arr) / sizeof(arr[0]); + int max_sum = maxSubArraySum(arr, 0, n - 1); + printf("Maximum contiguous sum is %d\n", max_sum); + getchar(); + return 0; +} diff --git a/Merge short algorithm b/CPP/merge-sort.cpp similarity index 100% rename from Merge short algorithm rename to CPP/merge-sort.cpp diff --git a/CPP/minimizingCoins.cpp b/CPP/minimizingCoins.cpp new file mode 100644 index 0000000..ec77ab4 --- /dev/null +++ b/CPP/minimizingCoins.cpp @@ -0,0 +1,66 @@ +#include +using namespace std; +#define ll long long int +#define sz(x) x.size() +#define pb push_back +#define pb2 pop_back +#define ff first +#define ss second +#define lb lower_bound +#define ub upper_bound +#define bend(x) x.begin(), x.end() +#define vi vector +#define mapp map +#define sett set +#define ve vector +#define un_m unordered_map +#define f(i, a, b) for (i = a; i < b; i++) +#define f2(i, x) for (i = a.begin(); i != a.end(); i++) +#define maxxx INT32_MAX +#define mp make_pair +#define in(t) scanf("%lld",&t) +#define out(t) printf("%lld",t) + +const unsigned int moduli = 1000000007; + + +void sol() +{ + ll d=0,ds,e=0,x,n,k; + ll i,j,tt=0,t; + ll cnt=0,sum=0; + + cin>>n>>x; + ll a[n]; + f(i,0,n) cin>>a[i]; + + ll dp[x+1]; + + f(i,0,x+1) dp[i]=INT_MAX; + + dp[0]=0; + f(i,1,n+1) + { + f(j,0,x+1) + { + if(j-a[i-1] >= 0) + dp[j]=min( dp[j-a[i-1]] + 1 , dp[j]); + } + } + if(dp[x]==INT_MAX) cout<<-1; + else cout<> tc; + // while (tc--) + // { + sol(); + cout << endl; + // } + + return 0; +} \ No newline at end of file diff --git a/CPP/minimum_extraction.cpp b/CPP/minimum_extraction.cpp new file mode 100644 index 0000000..5cfd470 --- /dev/null +++ b/CPP/minimum_extraction.cpp @@ -0,0 +1,29 @@ +#include +using namespace std; +#define MAX 10000 +#define ll long long +int main() { + int tt; + cin>>tt; + while(tt--) { + ll n; + cin>>n; + ll arr[n]; + for(int i=0;i>arr[i]; + } + sort(arr,arr+n); + ll curr = 0; + ll ans = arr[0]; + for(int i=0;i=0) + curr+=arr[i]; + else + curr += arr[i]; + ans = max(ans , arr[i+1] - curr); + arr[i+1] -= curr; + } + cout< +using namespace std; + +#define ROW_1 4 +#define COL_1 4 + +#define ROW_2 4 +#define COL_2 4 + +void print(string display, vector> matrix, + int start_row, int start_column, int end_row, + int end_column) +{ + cout << endl + << display << " =>" << endl; + for (int i = start_row; i <= end_row; i++) + { + for (int j = start_column; j <= end_column; j++) + { + cout << setw(10); + cout << matrix[i][j]; + } + cout << endl; + } + cout << endl; + return; +} + +void add_matrix(vector> matrix_A, + vector> matrix_B, + vector> &matrix_C, + int split_index) +{ + for (auto i = 0; i < split_index; i++) + for (auto j = 0; j < split_index; j++) + matrix_C[i][j] = matrix_A[i][j] + matrix_B[i][j]; +} + +vector> +multiply_matrix(vector> matrix_A, + vector> matrix_B) +{ + int col_1 = matrix_A[0].size(); + int row_1 = matrix_A.size(); + int col_2 = matrix_B[0].size(); + int row_2 = matrix_B.size(); + + if (col_1 != row_2) + { + cout << "\nError: The number of columns in Matrix " + "A must be equal to the number of rows in " + "Matrix B\n"; + return {}; + } + + vector result_matrix_row(col_2, 0); + vector> result_matrix(row_1, + result_matrix_row); + + if (col_1 == 1) + result_matrix[0][0] = matrix_A[0][0] * matrix_B[0][0]; + else + { + int split_index = col_1 / 2; + + vector row_vector(split_index, 0); + vector> result_matrix_00(split_index, + row_vector); + vector> result_matrix_01(split_index, + row_vector); + vector> result_matrix_10(split_index, + row_vector); + vector> result_matrix_11(split_index, + row_vector); + + vector> a00(split_index, row_vector); + vector> a01(split_index, row_vector); + vector> a10(split_index, row_vector); + vector> a11(split_index, row_vector); + vector> b00(split_index, row_vector); + vector> b01(split_index, row_vector); + vector> b10(split_index, row_vector); + vector> b11(split_index, row_vector); + + for (auto i = 0; i < split_index; i++) + for (auto j = 0; j < split_index; j++) + { + a00[i][j] = matrix_A[i][j]; + a01[i][j] = matrix_A[i][j + split_index]; + a10[i][j] = matrix_A[split_index + i][j]; + a11[i][j] = matrix_A[i + split_index] + [j + split_index]; + b00[i][j] = matrix_B[i][j]; + b01[i][j] = matrix_B[i][j + split_index]; + b10[i][j] = matrix_B[split_index + i][j]; + b11[i][j] = matrix_B[i + split_index] + [j + split_index]; + } + + add_matrix(multiply_matrix(a00, b00), + multiply_matrix(a01, b10), + result_matrix_00, split_index); + add_matrix(multiply_matrix(a00, b01), + multiply_matrix(a01, b11), + result_matrix_01, split_index); + add_matrix(multiply_matrix(a10, b00), + multiply_matrix(a11, b10), + result_matrix_10, split_index); + add_matrix(multiply_matrix(a10, b01), + multiply_matrix(a11, b11), + result_matrix_11, split_index); + + for (auto i = 0; i < split_index; i++) + for (auto j = 0; j < split_index; j++) + { + result_matrix[i][j] = result_matrix_00[i][j]; + result_matrix[i][j + split_index] = result_matrix_01[i][j]; + result_matrix[split_index + i][j] = result_matrix_10[i][j]; + result_matrix[i + split_index] + [j + split_index] = result_matrix_11[i][j]; + } + + result_matrix_00.clear(); + result_matrix_01.clear(); + result_matrix_10.clear(); + result_matrix_11.clear(); + a00.clear(); + a01.clear(); + a10.clear(); + a11.clear(); + b00.clear(); + b01.clear(); + b10.clear(); + b11.clear(); + } + return result_matrix; +} + +int main() +{ + vector> matrix_A = {{1, 1, 1, 1}, + {2, 2, 2, 2}, + {3, 3, 3, 3}, + {2, 2, 2, 2}}; + + print("Array A", matrix_A, 0, 0, ROW_1 - 1, COL_1 - 1); + + vector> matrix_B = {{1, 1, 1, 1}, + {2, 2, 2, 2}, + {3, 3, 3, 3}, + {2, 2, 2, 2}}; + + print("Array B", matrix_B, 0, 0, ROW_2 - 1, COL_2 - 1); + + vector> result_matrix( + multiply_matrix(matrix_A, matrix_B)); + + print("Result Array", result_matrix, 0, 0, ROW_1 - 1, + COL_2 - 1); +} diff --git a/CPP/n Queen problem.cpp b/CPP/n Queen problem.cpp new file mode 100644 index 0000000..05cf6b0 --- /dev/null +++ b/CPP/n Queen problem.cpp @@ -0,0 +1,98 @@ +//N Queen problem + +//The n-queens puzzle is the problem of placing n queens on a (n*n) chessboard such that no two queens can attack each other. +//Given an integer n, find all distinct solutions to the n-queens puzzle. + +#include +using namespace std; + +void addSolution(vector > &board , vector > &ans , int n){ + vector temp; + + for(int i = 0 ;i > &board , int n ){ + int x = row; + int y = col; + while(y>= 0){ + if(board[x][y] == 1){ + return false; + + } + y--; + } + x= row; + y = col; + while(y>=0 && x>=0){ + if(board[x][y]==1){ + return false; + } + x--; + y--; + } + x= row; + y= col; + while(y>=0 && x > &ans , vector > &board , int n){ + if(col == n){ + addSolution(board , ans , n); + return ; + } + + for(int row= 0 ; row< n; row++){ + + if(isSafe(row, col , board, n)){ + board[row][col] = 1; + nQueen(col+1 , ans, board, n); + board[row][col] = 0 ; + + } + } +} + +int main(){ + int n ; + cout<<"Enter the number of queens: "<>n; + + vector> board(n,vector(n,0)); + vector> ans; + + nQueen(0 , ans , board , n); + + + if(ans.size() == 0){ + cout<<"not possible"< + +using namespace std; +#define N 4 +/* ld is an array where its indices indicate row-col+N-1 + + (N-1) is for shifting the difference to store negative + + indices */ + +int ld[30] = { 0 }; +/* rd is an array where its indices indicate row+col + + and used to check whether a queen can be placed on + + right diagonal or not*/ + +int rd[30] = { 0 }; +/*column array where its indices indicates column and + + used to check whether a queen can be placed in that + + row or not*/ + +int cl[30] = { 0 }; +/* A utility function to print solution */ + +void printSolution(int board[N][N]) +{ + + for (int i = 0; i < N; i++) { + + for (int j = 0; j < N; j++) + + cout<<" "<< board[i][j]<<" "; + + cout<= N) + + return true; + + + + /* Consider this column and try placing + + this queen in all rows one by one */ + + for (int i = 0; i < N; i++) { + + /* Check if the queen can be placed on + + board[i][col] */ + + /* A check if a queen can be placed on + + board[row][col].We just need to check + + ld[row-col+n-1] and rd[row+coln] where + + ld and rd are for left and right + + diagonal respectively*/ + + if ((ld[i - col + N - 1] != 1 && rd[i + col] != 1) && cl[i] != 1) { + + /* Place this queen in board[i][col] */ + + board[i][col] = 1; + + ld[i - col + N - 1] = rd[i + col] = cl[i] = 1; + + + + /* recur to place rest of the queens */ + + if (solveNQUtil(board, col + 1)) + + return true; + + + + /* If placing queen in board[i][col] + + doesn't lead to a solution, then + + remove queen from board[i][col] */ + + board[i][col] = 0; // BACKTRACK + + ld[i - col + N - 1] = rd[i + col] = cl[i] = 0; + + } + + } + + + + /* If the queen cannot be placed in any row in + + this column col then return false */ + + return false; +} +/* This function solves the N Queen problem using + + Backtracking. It mainly uses solveNQUtil() to + + solve the problem. It returns false if queens + + cannot be placed, otherwise, return true and + + prints placement of queens in the form of 1s. + + Please note that there may be more than one + + solutions, this function prints one of the + + feasible solutions.*/ + +bool solveNQ() +{ + + int board[N][N] = { { 0, 0, 0, 0 }, + + { 0, 0, 0, 0 }, + + { 0, 0, 0, 0 }, + + { 0, 0, 0, 0 } }; + + + + if (solveNQUtil(board, 0) == false) { + + cout<<"Solution does not exist"; + + return false; + + } + + + + printSolution(board); + + return true; +} + + +// driver program to test above function + +int main() +{ + + solveNQ(); + + return 0; +} diff --git a/CPP/permutations.cpp b/CPP/permutations.cpp new file mode 100644 index 0000000..8ab10c9 --- /dev/null +++ b/CPP/permutations.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + void rec(int pos, vector &nums, vector> &ans){ + if(pos == nums.size()){ + ans.push_back(nums); + } + else{ + for(int i=pos; i> permute(vector& nums) { + vector>ans; + rec(0,nums,ans); + return ans; + } +}; diff --git a/CPP/poi_dyn_str.cpp b/CPP/poi_dyn_str.cpp new file mode 100644 index 0000000..b98eff1 --- /dev/null +++ b/CPP/poi_dyn_str.cpp @@ -0,0 +1,47 @@ +//Dynamic memory allocation for strings +#include +#include +using namespace std; +int main() +{ + char name[20]; + char *p;//char pointer + int l,i; + + cout<<"\n enter string :"; + cin>> name; + l=strlen(name); + p = new char[l+1]; //dynamic memory allocation (Base address of memory) + + for(i=0;name[i]!='\0';i++) + { + p[i]=name[i]; + //*(p+i)= name[i]; + + }//end of for + + p[i]='\0';//end of string + + cout<<"\n Copied Sring :"< +using namespace std; +#define endl "\n" +class Queue{ + private: + int front; + int rear; + char arr[4]; + + public: + Queue() { + front = -1; + rear = -1; + for (int i = 0; i < 5; i++) { + arr[i] = 0; + } + } + + bool isEmpty() { + if (front == -1 && rear == -1) + return true; + else + return false; + } + + bool isFull(){ + if(rear==4) + return true; + else + return false; + } + + void enqueue(int val){ + if(isFull()){ + cout<<"Queue Full"<> value; + s1.enqueue(value); + + cout<<"Enter second char"<> value; + s1.enqueue(value); + + cout<<"Enter third char"<> value; + s1.enqueue(value); + + cout<<"Enter fourth char"<> value; + s1.enqueue(value); + + s1.display(); + + s1.dequeue(); + s1.display(); + + s1.dequeue(); + s1.display(); + + s1.dequeue(); + s1.display(); + + s1.dequeue(); + s1.dequeue(); + + return 0; +} \ No newline at end of file diff --git a/CPP/radixSort.cpp b/CPP/radixSort.cpp new file mode 100644 index 0000000..432ae3b --- /dev/null +++ b/CPP/radixSort.cpp @@ -0,0 +1,75 @@ +// C++ implementation of Radix Sort + +#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/CPP/ratInAMaze.cpp b/CPP/ratInAMaze.cpp new file mode 100644 index 0000000..194a5cd --- /dev/null +++ b/CPP/ratInAMaze.cpp @@ -0,0 +1,148 @@ +// C++ program to solve Rat in a Maze problem using +// backtracking +#include + +using namespace std; +// Maze size +#define N 4 + + +bool solveMazeUtil(int maze[N][N], int x, int y,int sol[N][N]); + +// A utility function to print solution matrix sol[N][N] + +void printSolution(int sol[N][N]) +{ + + for (int i = 0; i < N; i++) { + + for (int j = 0; j < N; j++) + + cout<<" "<= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1) + + return true; + + return false; +} + +// This function solves the Maze problem using Backtracking. +// It mainly uses solveMazeUtil() to solve the problem. It +// returns false if no path is possible, otherwise return +// true and prints the path in the form of 1s. Please note +// that there may be more than one solutions, this function +// prints one of the feasible solutions. + +bool solveMaze(int maze[N][N]) +{ + + int sol[N][N] = { { 0, 0, 0, 0 }, + + { 0, 0, 0, 0 }, + + { 0, 0, 0, 0 }, + + { 0, 0, 0, 0 } }; + + if (solveMazeUtil(maze, 0, 0, sol) == false) { + + cout<<"Solution doesn't exist"; + + return false; + + } + + printSolution(sol); + + return true; +} + +// A recursive utility function to solve Maze problem + +bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]) +{ + + // if (x, y is goal) return true + + if (x == N - 1 && y == N - 1 && maze[x][y] == 1) { + + sol[x][y] = 1; + + return true; + + } + + // Check if maze[x][y] is valid + + if (isSafe(maze, x, y) == true) { + + // Check if the current block is already part of + + // solution path. + + if (sol[x][y] == 1) + + return false; + + // mark x, y as part of solution path + + sol[x][y] = 1; + + /* Move forward in x direction */ + + if (solveMazeUtil(maze, x + 1, y, sol) == true) + + return true; + + // If moving in x direction doesn't give solution + + // then Move down in y direction + + if (solveMazeUtil(maze, x, y + 1, sol) == true) + + return true; + + // If none of the above movements work then + + // BACKTRACK: unmark x, y as part of solution path + + sol[x][y] = 0; + + return false; + + } + + return false; +} + +// driver program to test above function + +int main() +{ + + int maze[N][N] = { { 1, 0, 0, 0 }, + + { 1, 1, 0, 1 }, + + { 0, 1, 0, 0 }, + + { 1, 1, 1, 1 } }; + + solveMaze(maze); + + return 0; +} diff --git a/Selection sort b/CPP/selection-sort.cpp similarity index 100% rename from Selection sort rename to CPP/selection-sort.cpp diff --git a/singly link list b/CPP/singly-linked-list.cpp similarity index 100% rename from singly link list rename to CPP/singly-linked-list.cpp diff --git a/stack all operation b/CPP/stack all operation similarity index 100% rename from stack all operation rename to CPP/stack all operation diff --git a/CPP/stack-oprations/STL-stack.cpp b/CPP/stack-oprations/STL-stack.cpp new file mode 100644 index 0000000..f0539ff --- /dev/null +++ b/CPP/stack-oprations/STL-stack.cpp @@ -0,0 +1,18 @@ +#include +#include +using namespace std; + +int main() { + // create a stack of strings + stack languages; + + // add element to the Stack + languages.push("C++"); + languages.push("Java"); + languages.push("Python"); + + // print top element + cout << languages.top(); + + return 0; +} diff --git a/CPP/stack-oprations/add-element.cpp b/CPP/stack-oprations/add-element.cpp new file mode 100644 index 0000000..3573127 --- /dev/null +++ b/CPP/stack-oprations/add-element.cpp @@ -0,0 +1,23 @@ +#include +#include +using namespace std; + +int main() { + + // create a stack of strings + stack colors; + + // push elements into the stack + colors.push("Red"); + colors.push("Orange"); + + cout << "Stack: "; + + // print elements of stack + while(!colors.empty()) { + cout << colors.top() << ", "; + colors.pop(); + } + + return 0; +} diff --git a/CPP/stack-oprations/readme.md b/CPP/stack-oprations/readme.md new file mode 100644 index 0000000..620d77a --- /dev/null +++ b/CPP/stack-oprations/readme.md @@ -0,0 +1,47 @@ +

Stack and its basic Operations

+ +First, let us see the properties of data structures that we already do know and build-up our concepts towards the stack. + +-Array: Its a random-access container, meaning any element of this container can be accessed instantly + +-Linked List: It's a sequential-access container, meaning that elements of this data structure can only be accessed sequentially + +→ Following a similar definition,A stack is a container where only the top element can be accessed or operated upon. + +*A Stack is a data structure following the LIFO(Last In, First Out) principle.* +
+

+ Material Bread logo +

+

+If you have trouble visualizing stacks, just assume a stack of books. + +1.In a stack of books, you can only see the top book + +2.If you want to access any other book, you would first need to remove the books on top of it + +3.The bottom-most book in the stack was put first and can only be removed at the last after all books on top of it have been removed. + +

+ Material Bread logo +

+ + +***

PUSH Operation

*** + +Push operation refers to inserting an element in the stack. Since there’s only one position at which the new element can be inserted — Top of the stack, the new element is inserted at the top of the stack. + +***

POP Operation

*** +Pop operation refers to the removal of an element. Again, since we only have access to the element at the top of the stack, there’s only one element that we can remove. We just remove the top of the stack. Note: We can also choose to return the value of the popped element back, its completely at the choice of the programmer to implement this. + +***

PEEK Operation

*** + +Peek operation allows the user to see the element on the top of the stack. The stack is not modified in any manner in this operation. + +***

isEmpty: Check if stack is empty or not

*** + +To prevent performing operations on an empty stack, the programmer is required to internally maintain the size of the stack which will be updated during push and pop operations accordingly. isEmpty() conventionally returns a boolean value: True if size is 0, else False. + + + + diff --git a/CPP/stack-oprations/remove-element.cpp b/CPP/stack-oprations/remove-element.cpp new file mode 100644 index 0000000..ba4c731 --- /dev/null +++ b/CPP/stack-oprations/remove-element.cpp @@ -0,0 +1,42 @@ +#include +#include +using namespace std; + +// function prototype for display_stack utility +void display_stack(stack st); + +int main() { + + // create a stack of strings + stack colors; + + // push elements into the stack + colors.push("Red"); + colors.push("Orange"); + colors.push("Blue"); + + cout << "Initial Stack: "; + // print elements of stack + display_stack(colors); + + // removes "Blue" as it was inserted last + colors.pop(); + + cout << "Final Stack: "; + + // print elements of stack + display_stack(colors); + + return 0; +} + +// utility function to display stack elements +void display_stack(stack st) { + + while(!st.empty()) { + cout << st.top() << ", "; + st.pop(); + } + + cout << endl; +} diff --git a/CPP/tree.cpp b/CPP/tree.cpp new file mode 100644 index 0000000..610f2f9 --- /dev/null +++ b/CPP/tree.cpp @@ -0,0 +1,264 @@ +#include +using namespace std; + +class Node { +private: + int data; + Node *left; + Node * right; + +public: + Node(int data) { + this->data = data; + left = NULL; + right = NULL; + } + + int getData() { + return data; + } + + Node *getLeft() { + return left; + } + + Node *setLeft(Node *node) { + return left = node; + } + + Node *getRight() { + return right; + } + + Node *setRight(Node *node) { + return right = node; + } +}; + +class Tree { +private: + Node *root; +public: + Tree() { + root = NULL; + } + + Node *getRoot() { + return root; + } + + void insert(int data) { + if (root == NULL) { + root = new Node(data); + } else { + auxInsert(root, data); + } + } + + void auxInsert(Node *node, int data) { + if (data < node->getData()) { + if (node->getLeft() == NULL) { + Node *new_node = new Node(data); + node->setLeft(new_node); + } else { + auxInsert(node->getLeft(), data); + } + } else { + if (node->getRight() == NULL) { + Node *new_node = new Node(data); + node->setRight(new_node); + } else { + auxInsert(node->getRight(), data); + } + } + } + + void pre_order(Node *node) { + cout << node->getData() << " "; + if (node->getLeft() != NULL) { + pre_order(node->getLeft()); + } + if (node->getRight() != NULL) { + pre_order(node->getRight()); + } + } + + Node *findNode(Node *node, int element) { + if (node == nullptr) return nullptr; + if (node->getData() == element) return node; + + Node *nodeFound = findNode(node->getLeft(), element); + if (nodeFound != nullptr) return nodeFound; + + return findNode(node->getRight(), element); + } + + void getLeaf(Node *node) { + if (node->getLeft() == NULL && node->getRight() == NULL) { + cout << node->getData() << endl; + } else { + if (node->getLeft() != NULL) { + getLeaf(node->getLeft()); + } + if (node->getRight() != NULL) { + getLeaf(node->getRight()); + } + } + } + + void getGrade(Node *node, int element) { + Node *nodeFound = findNode(node, element); + + if (nodeFound == 0) { + cout << "Are you kidding my brother? type an existing node pls"; + } else { + if (nodeFound->getLeft() == NULL && nodeFound->getRight() == NULL ) { + cout << "Grade is 0"; + } else if (nodeFound->getLeft() != NULL && nodeFound->getRight() != NULL) { + cout << "Grade is 2"; + } else { + cout << "Grade is 1"; + } + } + } + + void getAllGrade(Node *node) { + if (node->getRight() == NULL && node->getLeft() == NULL) { + cout << node->getData() << ": 0" << endl; + } else if (node->getRight() != NULL && node->getLeft() != NULL) { + cout << node->getData() << ": 2" << endl; + if (node->getLeft() != NULL) { + getAllGrade(node->getLeft()); + } + if (node->getRight() != NULL) { + getAllGrade(node->getRight()); + } + } else { + cout << node->getData() << ": 1" << endl; + if(node->getRight() != NULL) { + getAllGrade(node->getRight()); + } else { + getAllGrade(node->getLeft()); + } + } + } + + int getNodeHeight(Node *node) { + int leftHeigt = -1; + int rightHeigt = -1; + + if(root != NULL) { + if (node->getLeft() != NULL) { + leftHeigt = getNodeHeight(node->getLeft()); + } + if (node->getRight() != NULL) { + rightHeigt = getNodeHeight(node->getRight()); + } + + return max(leftHeigt, rightHeigt) + 1; + } + return 0; + } + + int getHeight(Node *node, int element) { + Node *nodeFound = findNode(node, element); + + if (nodeFound == NULL) { + cout << "Are you kidding my brother? type an existing node pls"; + } else { + return getNodeHeight(nodeFound); + } + return 0; + } + + void getAllHeights(Node *node) { + if (node == NULL) { + cout << "Are you kidding my brother? type an existing node pls"; + } else { + cout << node->getData() << ": " << getNodeHeight(node) << endl; + if (node->getLeft() != NULL) { + getAllHeights(node->getLeft()); + } + if (node->getRight() != NULL) { + getAllHeights(node->getRight()); + } + + } + } + + void getAncestors(Node *node, int ancestors) { + if (node == NULL) { + cout << ""; + } else { + cout << node->getData() << ": " << ancestors << endl; + + if (node->getLeft() != NULL || node->getRight() != NULL) { + getAncestors(node->getLeft(), ancestors + 1); + getAncestors(node->getRight(), ancestors + 1); + } + } + } + + void getAllDepths(Node *node) { + if (node == NULL) { + cout << "Are you kidding my brother? type an existing node pls"; + } else { + getAncestors(node, 0); + } + } + + void getSubtree(Node *node) { + if (node == NULL) { + cout << "Are you kidding my brother? type an existing node pls"; + } else { + pre_order(node); + } + } + + void getAllSubtrees(Node *node) { + if (node == NULL) { + cout << "Are you kidding my brother? type an existing node pls"; + } else { + pre_order(node); + cout << endl; + if (node->getLeft()) { + getAllSubtrees(node->getLeft()); + } + if (node->getRight()) { + getAllSubtrees(node->getRight()); + } + } + } +}; + +int main() { + Tree t = Tree(); + + t.insert(10); + t.insert(8); + t.insert(9); + t.insert(12); + t.insert(11); + t.insert(14); + t.insert(20); + t.insert(13); + t.insert(7); + + cout << "a) "; + t.pre_order(t.getRoot()); + cout << endl << "b) "; + t.getLeaf(t.getRoot()); + cout << endl << "c) "; + //t.getGrade(t.getRoot(), 10); + t.getAllGrade(t.getRoot()); + cout << endl << "d) "; + t.getAllHeights(t.getRoot()); + cout << endl << "e,f) "; + //cout << t.getDepth(t.getRoot()); + t.getAllDepths(t.getRoot()); + cout << endl << "g) "; + //t.getSubtree(t.getRoot(), 14); + t.getAllSubtrees(t.getRoot()); + + return 0; +} diff --git a/CPP/undir to SCC.cpp b/CPP/undir to SCC.cpp new file mode 100644 index 0000000..12f06e8 --- /dev/null +++ b/CPP/undir to SCC.cpp @@ -0,0 +1,152 @@ + +#include +using namespace std; + +// To store the assigned Edges +vector > ans; + +// Flag variable to check Bridges +int flag = 1; + +// Function to implement DFS Traversal +int dfs(vector adj[], + int* order, int* bridge_detect, + bool* mark, int v, int l) +{ + + // Mark the current node as visited + mark[v] = 1; + + // Update the order of node v + order[v] = order[l] + 1; + + // Update the bridge_detect for node v + bridge_detect[v] = order[v]; + + // Traverse the adjacency list of + // Node v + for (int i = 0; i < adj[v].size(); i++) { + int u = adj[v][i]; + + // Ignores if same edge is traversed + if (u == l) { + continue; + } + + // Ignores the edge u --> v as + // v --> u is already processed + if (order[v] < order[u]) { + continue; + } + + // Finds a back Edges, cycle present + if (mark[u]) { + + // Update the bridge_detect[v] + bridge_detect[v] + = min(order[u], + bridge_detect[v]); + } + + // Else DFS traversal for current + // node in the adjacency list + else { + + dfs(adj, order, bridge_detect, + mark, u, v); + } + + // Update the bridge_detect[v] + bridge_detect[v] + = min(bridge_detect[u], + bridge_detect[v]); + + // Store the current directed Edge + ans.push_back(make_pair(v, u)); + } + + // Condition for Bridges + if (bridge_detect[v] == order[v] + && l != 0) { + flag = 0; + } + + // Return flag + return flag; +} + +// Function to print the direction +// of edges to make graph SCCs +void convert(vector adj[], int n) +{ + + // Arrays to store the visited, + // bridge_detect and order of + // Nodes + int order[n] = { 0 }; + int bridge_detect[n] = { 0 }; + bool mark[n]; + + // Initialise marks[] as false + memset(mark, false, sizeof(mark)); + + // DFS Traversal from vertex 1 + int flag = dfs(adj, order, + bridge_detect, + mark, 1, 0); + + // If flag is zero, then Bridge + // is present in the graph + if (flag == 0) { + cout << "-1"; + } + + // Else print the direction of + // Edges assigned + else { + for (auto& it : ans) { + cout << it.first << "->" + << it.second << '\n'; + } + } +} + +// Function to create graph +void createGraph(int Edges[][2], + vector adj[], + int M) +{ + + // Traverse the Edges + for (int i = 0; i < M; i++) { + + int u = Edges[i][0]; + int v = Edges[i][1]; + + // Push the edges in an + // adjacency list + adj[u].push_back(v); + adj[v].push_back(u); + } +} + +// Driver Code +int main() +{ + // N vertices and M Edges + int N = 5, M = 6; + int Edges[M][2] + = { { 0, 1 }, { 0, 2 }, + { 1, 2 }, { 1, 4 }, + { 2, 3 }, { 3, 4 } }; + + // To create Adjacency List + vector adj[N]; + + // Create an undirected graph + createGraph(Edges, adj, M); + + // Function Call + convert(adj, N); + return 0; +} diff --git a/CPP/wildcardmatching.cpp b/CPP/wildcardmatching.cpp new file mode 100644 index 0000000..fea93de --- /dev/null +++ b/CPP/wildcardmatching.cpp @@ -0,0 +1,86 @@ +// C++ program to implement wildcard +// pattern matching algorithm +#include +using namespace std; + +// Function that matches input str with +// given wildcard pattern +bool strmatch(char str[], char pattern[], int n, int m) +{ + // empty pattern can only match with + // empty string + if (m == 0) + return (n == 0); + + // lookup table for storing results of + // subproblems + bool lookup[n + 1][m + 1]; + + // initialize lookup table to false + memset(lookup, false, sizeof(lookup)); + + // empty pattern can match with empty string + lookup[0][0] = true; + + // Only '*' can match with empty string + for (int j = 1; j <= m; j++) + if (pattern[j - 1] == '*') + lookup[0][j] = lookup[0][j - 1]; + + // fill the table in bottom-up fashion + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= m; j++) { + // Two cases if we see a '*' + // a) We ignore ‘*’ character and move + // to next character in the pattern, + // i.e., ‘*’ indicates an empty sequence. + // b) '*' character matches with ith + // character in input + if (pattern[j - 1] == '*') + lookup[i][j] + = lookup[i][j - 1] || lookup[i - 1][j]; + + // Current characters are considered as + // matching in two cases + // (a) current character of pattern is '?' + // (b) characters actually match + else if (pattern[j - 1] == '?' + || str[i - 1] == pattern[j - 1]) + lookup[i][j] = lookup[i - 1][j - 1]; + + // If characters don't match + else + lookup[i][j] = false; + } + } + + return lookup[n][m]; +} + +int main() +{ + char str[] = "baaabab"; + char pattern[] = "*****ba*****ab"; + // char pattern[] = "ba*****ab"; + // char pattern[] = "ba*ab"; + // char pattern[] = "a*ab"; + // char pattern[] = "a*****ab"; + // char pattern[] = "*a*****ab"; + // char pattern[] = "ba*ab****"; + // char pattern[] = "****"; + // char pattern[] = "*"; + // char pattern[] = "aa?ab"; + // char pattern[] = "b*b"; + // char pattern[] = "a*a"; + // char pattern[] = "baaabab"; + // char pattern[] = "?baaabab"; + // char pattern[] = "*baaaba*"; + + if (strmatch(str, pattern, strlen(str), + strlen(pattern))) + cout << "Yes" << endl; + else + cout << "No" << endl; + + return 0; +} diff --git a/CQueue.java b/CQueue.java new file mode 100644 index 0000000..800cdca --- /dev/null +++ b/CQueue.java @@ -0,0 +1,110 @@ +public class CQueue { + int SIZE = 5; // Size of Circular Queue + int front, rear; + int items[] = new int[SIZE]; + + CQueue() { + front = -1; + rear = -1; + } + + // Check if the queue is full + boolean isFull() { + if (front == 0 && rear == SIZE - 1) { + return true; + } + if (front == rear + 1) { + return true; + } + return false; + } + + // Check if the queue is empty + boolean isEmpty() { + if (front == -1) + return true; + else + return false; + } + + // Adding an element + void enQueue(int element) { + if (isFull()) { + System.out.println("Queue is full"); + } else { + if (front == -1) + front = 0; + rear = (rear + 1) % SIZE; + items[rear] = element; + System.out.println("Inserted " + element); + } + } + + // Removing an element + int deQueue() { + int element; + if (isEmpty()) { + System.out.println("Queue is empty"); + return (-1); + } else { + element = items[front]; + if (front == rear) { + front = -1; + rear = -1; + } /* Q has only one element, so we reset the queue after deleting it. */ + else { + front = (front + 1) % SIZE; + } + return (element); + } + } + + void display() { + /* Function to display status of Circular Queue */ + int i; + if (isEmpty()) { + System.out.println("Empty Queue"); + } else { + System.out.println("Front -> " + front); + System.out.println("Items -> "); + for (i = front; i != rear; i = (i + 1) % SIZE) + System.out.print(items[i] + " "); + System.out.println(items[i]); + System.out.println("Rear -> " + rear); + } + } + + public static void main(String[] args) { + + CQueue q = new CQueue(); + + // Fails because front = -1 + q.deQueue(); + + q.enQueue(1); + q.enQueue(2); + q.enQueue(3); + q.enQueue(4); + q.enQueue(5); + + // Fails to enqueue because front == 0 && rear == SIZE - 1 + q.enQueue(6); + + q.display(); + + int elem = q.deQueue(); + + if (elem != -1) { + System.out.println("Deleted Element is " + elem); + } + q.display(); + + q.enQueue(7); + + q.display(); + + // Fails to enqueue because front == rear + 1 + q.enQueue(8); + } + +} diff --git a/Count-sort.cpp b/Count-sort.cpp new file mode 100644 index 0000000..524fb38 --- /dev/null +++ b/Count-sort.cpp @@ -0,0 +1,34 @@ +#include +#include +using namespace std; +#define RANGE 255 + +void countSort(char arr[]) +{ + char output[strlen(arr)]; + + int count[RANGE + 1], i; + memset(count, 0, sizeof(count)); + for (i = 0; arr[i]; ++i) + ++count[arr[i]]; + + for (i = 1; i <= RANGE; ++i) + count[i] += count[i - 1]; + for (i = 0; arr[i]; ++i) { + output[count[arr[i]] - 1] = arr[i]; + --count[arr[i]]; + } + + for (i = 0; arr[i]; ++i) + arr[i] = output[i]; +} + +int main() +{ + char arr[] = "harshkashiwal"; + + countSort(arr); + + cout << "Sorted array" << arr; + return 0; +} \ No newline at end of file diff --git a/Dice.py b/Dice.py new file mode 100644 index 0000000..eae21d9 --- /dev/null +++ b/Dice.py @@ -0,0 +1,13 @@ +import random + +#Dice Roller + +print("Initially number on Dice is: {0}".format(random.randint(1,6))) + +C = int(input("To Roll Dice Press any number or To Exit Press 0---> ")) + +while C !=0: + print("Number on Dice is: {0}".format(random.randint(1,6))) + + C = int(input("To Roll Dice Press 1 or To Exit Press 0---> ")) + diff --git a/First and last binary search .cpp b/First and last binary search .cpp new file mode 100644 index 0000000..8e77beb --- /dev/null +++ b/First and last binary search .cpp @@ -0,0 +1,66 @@ +#include +using namespace std; +int firstOcurrence(int arr[], int n, int key) +{ + int s = 0; + int e = n - 1; + int mid = s + (e - s) / 2; + int ans = -1; + + while (s <= e) + { + if (arr[mid] == key) + { + ans = mid; + e = mid - 1; + } + else if (key > arr[mid]) // go to right part + { + s = mid + 1; + } + else if (key < arr[mid]) // go to left part + { + e = mid - 1; + } + mid = s + (e - s) / 2; + } +} +int lastOcurrence(int arr[], int n, int key) +{ + int s = 0; + int e = n - 1; + int mid = s + (e - s) / 2; + int ans = -1; + + while (s <= e) + { + if (arr[mid] == key) + { + ans = mid; + s = mid + 1; + } + else if (key > arr[mid]) // Right wale part mei jaana h + { + s = mid + 1; + } + else if (key < arr[mid]) // Left wale part mei jaana h + { + e = mid - 1; + } + mid = s + (e - s) / 2; + } +} + +int main() +{ + int arr[4] = {3, 4, 5, 1}; + int ans = PeakElement(arr, 4); + cout << ans << endl; + // int arr[8] = {1, 2, 3, 3, 3, 3, 3, 5}; + // cout << "First Occurrence of 3 is at index : " << firstOcurrence(arr, 8, 3) << endl; + // cout << "Last Occurence of 3 is at index : " << lastOcurrence(arr, 8, 3) << endl; + // int totalCount = (lastOcurrence(arr, 8, 3) - firstOcurrence(arr, 8, 3)); + // cout << totalCount << endl; + + return 0; +} \ No newline at end of file diff --git a/First and last occurance binary search b/First and last occurance binary search new file mode 100644 index 0000000..57770ef --- /dev/null +++ b/First and last occurance binary search @@ -0,0 +1,56 @@ +#include +using namespace std; +int firstOcc(vector& arr, int n, int key) { + + int s = 0, e = n-1; + int mid = s + (e-s)/2; + int ans = -1; + while(s<=e) { + + if(arr[mid] == key){ + ans = mid; + e = mid - 1; + } + else if(key > arr[mid]) {//Right me jao + s = mid + 1; + } + else if(key < arr[mid]) {//left me jao + e = mid - 1; + } + + mid = s + (e-s)/2; + } + return ans; +} + +int lastOcc(vector& arr, int n, int key) { + + int s = 0, e = n-1; + int mid = s + (e-s)/2; + int ans = -1; + while(s<=e) { + + if(arr[mid] == key){ + ans = mid; + s = mid + 1; + } + else if(key > arr[mid]) {//Right me jao + s = mid + 1; + } + else if(key < arr[mid]) {//left me jao + e = mid - 1; + } + + mid = s + (e-s)/2; + } + return ans; +} + +pair firstAndLastPosition(vector& arr, int n, int k) +{ + pair p; + p.first = firstOcc(arr, n, k); + p.second = lastOcc(arr, n, k); + + return p; +} diff --git a/GCD_of_Number.cpp b/GCD_of_Number.cpp new file mode 100644 index 0000000..1653781 --- /dev/null +++ b/GCD_of_Number.cpp @@ -0,0 +1,32 @@ +/****************************************************************************** + + Online C++ Compiler. + Code, Compile, Run and Debug C++ program online. +Write your code in this editor and press "Run" button to compile and execute it. + +*******************************************************************************/ + +#include + +using namespace std; + +int main() +{ + int m,n,i; + cout<<"Enter 2 number to find GCD:"; + cin>>m>>n; + while(m != n) + { + if(m>n) + { + m=m-n; + } + else + { + n=n-m; + } + } + cout<=0;i--) + { + hepify(a,n,i); + } + for(int i=n-1;i>=0;i--) { + + int temp=a[0]; + a[0]=a[i]; + a[i]=temp; + + hepify(a,i,0); + } + } + + + + + + static void hepify(int a[],int n,int i) + { + int larest; + + int left=(2*i)+1; + int right=(2*i)+2; + + if(lefta[i]) + { + larest=left; + } + else{ + larest=i; + } + if(righta[larest]) + { + larest=right; + } + if(larest!=i) + { + int temp; + temp=a[i]; + a[i]=a[larest]; + a[larest]=temp; + + hepify(a,n,larest); + } + } + + static void display(int a[]) + { + for(int i=0;i +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); +} diff --git a/Insertionsort.cpp b/Insertionsort.cpp new file mode 100644 index 0000000..34ba1c0 --- /dev/null +++ b/Insertionsort.cpp @@ -0,0 +1,33 @@ + // code of the insertion sort +#include +using namespace std; + int main() + { + int n; + cout<<"Enter the size of the array you want to sort"<>n; + int arr[n]; + cout<<"Enter the elements of the array"<>arr[i]; + } + int j,temp=0; + for(int i=1;i=0&&arr[j]>temp) + { + arr[j+1]=arr[j]; + j--; + } + arr[j+1]=temp; + } + for(int i=0;i= boardSize || y < 0 || y >= boardSize ||board[x][y] != EMPTY){ +return INVALIDMOVE; +} + +board[x][y] = symbol; +count++; + +// Check Row +if(board[x][0] == board[x][1] && board[x][0] == board[x][2]){ +return symbol == p1Symbol ? PLAYER1WINS :PLAYER2WINS; +} +// Check Col +if(board[0][y] == board[1][y] && board[0][y] == board[2][y]){ +return symbol == p1Symbol ? PLAYER1WINS :PLAYER2WINS; +} +// First Diagonal +if(board[0][0] != EMPTY && board[0][0] == board[1][1] && board[0][0] == board[2][2]){ +return symbol == p1Symbol ? PLAYER1WINS :PLAYER2WINS; +} +// Second Diagonal +if(board[0][2] != EMPTY && board[0][2] == board[1][1] && board[0][2] == board[2][0]){ +return symbol == p1Symbol ? PLAYER1WINS :PLAYER2WINS; +} + +if(count == boardSize * boardSize){ +return DRAW; +} +return INCOMPLETE; +} +public void print() { +System.out.println("---------------"); +for(int i =0; i < boardSize; i++){ +for(int j =0; j < boardSize; j++){ +System.out.print("| " + board[i][j] + " |"); +} +System.out.println(); +} +System.out.println(); +System.out.println("---------------"); +} +} \ No newline at end of file diff --git a/Java Games/Gameplay.java b/Java Games/Gameplay.java new file mode 100644 index 0000000..4379d97 --- /dev/null +++ b/Java Games/Gameplay.java @@ -0,0 +1,130 @@ +import javax.swing.*; +import javax.swing.Timer; + +import java.awt.*; +import java.awt.event.*; +import java.sql.Time; +import java.util.*; + +public class Gameplay extends JPanel implements KeyListener, ActionListener { + private boolean play = false; + private int score = 0; + private int totalBricks = 21; + private Timer timer; + private int delay = 4; + private int playerX = 310; + private int ballposX = 120; + private int ballposY = 350; + private int ballXdir = -1; + private int ballYdir = -2; + private MapGenerator map; + + public Gameplay() { + map=new MapGenerator(3, 7); + addKeyListener(this); + setFocusable(true); + setFocusTraversalKeysEnabled(false); + timer = new Timer(delay, this); + timer.start(); + + } + + public void paint(Graphics g) { + // background + g.setColor(Color.black); + g.fillRect(1, 1, 692, 592); + // borders + g.setColor(Color.yellow); + g.fillRect(0, 0, 3, 592); + g.fillRect(0, 0, 692, 3); + g.fillRect(691, 0, 3, 592); + // map + map.draw((Graphics2D) g); + // the paddle + g.setColor(Color.green); + g.fillRect(playerX, 500, 100, 8); + // the ball + g.setColor(Color.red); + g.fillOval(ballposX, ballposY, 20, 20); + g.dispose(); + + } + + @Override + public void actionPerformed(ActionEvent e) { + timer.start(); + if (play) { + if (new Rectangle(ballposX, ballposY, 20, 20).intersects(playerX, 500, 100, 8)) { + ballYdir = -ballYdir; + } + for(int i=0;i0){ + int brickX=j*map.brickwidth+80; + int brickY=i*map.brickheight+50; + int brickwidth=map.brickwidth; + int brickheight=map.brickheight; + Rectangle rect=new Rectangle(brickX,brickY,brickwidth,brickheight); + Rectangle ballRect=new Rectangle(ballposX,ballposY,20,20); + Rectangle brickRect=rect; + if(ballRect.intersects(brickRect)){ + // map.setBrick(0,i,j); + totalBricks--; + score+=5; + } + } + } + } + ballposX += ballXdir; + ballposY += ballYdir; + if (ballposX < 0) { + ballXdir = -ballXdir; + } + if (ballposY < 0) { + ballYdir = -ballYdir; + } + if (ballposX > 670) { + ballXdir = -ballXdir; + } + } + repaint(); + } + + @Override + public void keyTyped(KeyEvent e) { + } + + @Override + public void keyPressed(KeyEvent e) { + } + + @Override + public void keyReleased(KeyEvent e) { + if (e.getKeyCode() == e.VK_RIGHT) { + if (playerX >= 580) { + playerX = 580; + } else { + moveRight(); + } + } + if (e.getKeyCode() == e.VK_LEFT) { + if (playerX < 10) { + playerX = 10; + } else { + moveLeft(); + } + } + } + + public void moveRight() { + play = true; + playerX += 20; + + } + + public void moveLeft() { + play = true; + playerX -= 20; + + } +} diff --git a/Java Games/Main.java b/Java Games/Main.java new file mode 100644 index 0000000..93899b1 --- /dev/null +++ b/Java Games/Main.java @@ -0,0 +1,14 @@ +import javax.swing.JFrame; + +public class Main{ + public static void main(String[] args){ + JFrame obj=new JFrame(); + Gameplay gameplay=new Gameplay(); + obj.setBounds(10,10,700,600); + obj.setTitle("Breakout ball"); + obj.setResizable(false); + obj.setVisible(true); + obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + obj.add(gameplay); + } +} \ No newline at end of file diff --git a/Java Games/MapGenerator.java b/Java Games/MapGenerator.java new file mode 100644 index 0000000..cd4e7fa --- /dev/null +++ b/Java Games/MapGenerator.java @@ -0,0 +1,33 @@ +import java.awt.*; + +public class MapGenerator { + public int map[][]; + public int brickwidth; + public int brickheight; + + public MapGenerator(int row, int col) { + map = new int[row][col]; + for (int i = 0; i < map.length; i++) { + for (int j = 0; j < map[0].length; j++) { + map[i][j] = 1; + } + } + brickwidth = 540 / col; + brickheight = 150 / row; + + } + + public void draw(Graphics2D g) { + for (int i = 0; i < map.length; i++) { + for (int j = 0; j < map[0].length; j++) { + if(map[i][j]>0){ + g.setColor(Color.white); + g.fillRect(j*brickwidth+80,i*brickheight+50,brickwidth,brickheight); + g.setStroke(new BasicStroke(3)); + g.setColor(Color.BLACK); + g.drawRect(j*brickwidth+80,i*brickheight+50,brickwidth,brickheight); + } + } + } + } +} diff --git a/Java Games/Player.java b/Java Games/Player.java new file mode 100644 index 0000000..1b8caa5 --- /dev/null +++ b/Java Games/Player.java @@ -0,0 +1,33 @@ +package tictactoe; + +public class Player { + +private String name; +private char symbol; + +public Player(String name, char symbol) { +setName(name); +setSymbol(symbol); +} + +public void setName(String name) { + +if(!name.isEmpty()) { +this.name = name; +} +} + +public String getName() { +return this.name; +} + +public void setSymbol(char symbol) { + if(symbol != '\0') { +this. symbol = symbol; +} +} + +public char getSymbol() { +return this.symbol; +} +} \ No newline at end of file diff --git a/Java Games/SimpleSnake.java b/Java Games/SimpleSnake.java new file mode 100644 index 0000000..babcbf8 --- /dev/null +++ b/Java Games/SimpleSnake.java @@ -0,0 +1,319 @@ +package Sb; + +import java.awt.*; +import java.awt.event.*; +import static java.lang.String.format; +import java.util.*; +import java.util.List; +import javax.swing.*; + +public class SimpleSnake extends JPanel implements Runnable { + enum Dir { + up(0, -1), right(1, 0), down(0, 1), left(-1, 0); + + Dir(int x, int y) { + this.x = x; this.y = y; + } + + final int x, y; + } + + static final Random rand = new Random(); + static final int WALL = -1; + static final int MAX_ENERGY = 1500; + + volatile boolean gameOver = true; + + Thread gameThread; + int score, hiScore; + int nRows = 44; + int nCols = 64; + Dir dir; + int energy; + + int[][] grid; + List snake, treats; + Font smallFont; + + public SimpleSnake() { + setPreferredSize(new Dimension(640, 440)); + setBackground(Color.WHITE); + setFont(new Font("TimesNewRoman", Font.BOLD, 48)); + setFocusable(true); + + smallFont = getFont().deriveFont(Font.BOLD, 18); + initGrid(); + + addMouseListener( + new MouseAdapter() { + @Override + public void mousePressed(MouseEvent e) { + if (gameOver) { + startNewGame(); + repaint(); + } + } + }); + + addKeyListener( + new KeyAdapter() { + + @Override + public void keyPressed(KeyEvent e) { + + switch (e.getKeyCode()) { + + case KeyEvent.VK_UP: + if (dir != Dir.down) + dir = Dir.up; + break; + + case KeyEvent.VK_LEFT: + if (dir != Dir.right) + dir = Dir.left; + break; + + case KeyEvent.VK_RIGHT: + if (dir != Dir.left) + dir = Dir.right; + break; + + case KeyEvent.VK_DOWN: + if (dir != Dir.up) + dir = Dir.down; + break; + } + repaint(); + } + }); + } + + void startNewGame() { + gameOver = false; + + stop(); + initGrid(); + treats = new LinkedList<>(); + + dir = Dir.left; + energy = MAX_ENERGY; + + if (score > hiScore) + hiScore = score; + score = 0; + + snake = new ArrayList<>(); + for (int x = 0; x < 7; x++) + snake.add(new Point(nCols / 2 + x, nRows / 2)); + + do + addTreat(); + while(treats.isEmpty()); + + (gameThread = new Thread(this)).start(); + } + + void stop() { + if (gameThread != null) { + Thread tmp = gameThread; + gameThread = null; + tmp.interrupt(); + } + } + + void initGrid() { + grid = new int[nRows][nCols]; + for (int r = 0; r < nRows; r++) { + for (int c = 0; c < nCols; c++) { + if (c == 0 || c == nCols - 1 || r == 0 || r == nRows - 1) + grid[r][c] = WALL; + } + } + } + + @Override + public void run() { + + while (Thread.currentThread() == gameThread) { + + try { + Thread.sleep(Math.max(75 - score, 25)); + } catch (InterruptedException e) { + return; + } + + if (energyUsed() || hitsWall() || hitsSnake()) { + gameOver(); + } else { + if (eatsTreat()) { + score++; + energy = MAX_ENERGY; + growSnake(); + } + moveSnake(); + addTreat(); + } + repaint(); + } + } + + boolean energyUsed() { + energy -= 10; + return energy <= 0; + } + + boolean hitsWall() { + Point head = snake.get(0); + int nextCol = head.x + dir.x; + int nextRow = head.y + dir.y; + return grid[nextRow][nextCol] == WALL; + } + + boolean hitsSnake() { + Point head = snake.get(0); + int nextCol = head.x + dir.x; + int nextRow = head.y + dir.y; + for (Point p : snake) + if (p.x == nextCol && p.y == nextRow) + return true; + return false; + } + + boolean eatsTreat() { + Point head = snake.get(0); + int nextCol = head.x + dir.x; + int nextRow = head.y + dir.y; + for (Point p : treats) + if (p.x == nextCol && p.y == nextRow) { + return treats.remove(p); + } + return false; + } + + void gameOver() { + gameOver = true; + stop(); + } + + void moveSnake() { + for (int i = snake.size() - 1; i > 0; i--) { + Point p1 = snake.get(i - 1); + Point p2 = snake.get(i); + p2.x = p1.x; + p2.y = p1.y; + } + Point head = snake.get(0); + head.x += dir.x; + head.y += dir.y; + } + + void growSnake() { + Point tail = snake.get(snake.size() - 1); + int x = tail.x + dir.x; + int y = tail.y + dir.y; + snake.add(new Point(x, y)); + } + + void addTreat() { + if (treats.size() < 3) { + + if (rand.nextInt(10) == 0) { // 1 in 10 + + if (rand.nextInt(4) != 0) { // 3 in 4 + int x, y; + while (true) { + + x = rand.nextInt(nCols); + y = rand.nextInt(nRows); + if (grid[y][x] != 0) + continue; + + Point p = new Point(x, y); + if (snake.contains(p) || treats.contains(p)) + continue; + + treats.add(p); + break; + } + } else if (treats.size() > 1) + treats.remove(0); + } + } + } + + void drawGrid(Graphics2D g) { + g.setColor(Color.black); + for (int r = 0; r < nRows; r++) { + for (int c = 0; c < nCols; c++) { + if (grid[r][c] == WALL) + g.fillRect(c * 10, r * 10, 10, 10); + } + } + } + + void drawSnake(Graphics2D g) { + g.setColor(Color.red); + for (Point p : snake) + g.fillRect(p.x * 10, p.y * 10, 10, 10); + + g.setColor(energy < 500 ? Color.red : Color.orange); + Point head = snake.get(0); + g.fillRect(head.x * 10, head.y * 10, 10, 10); + } + + void drawTreats(Graphics2D g) { + g.setColor(Color.green); + for (Point p : treats) + g.fillRect(p.x * 10, p.y * 10, 10, 10); + } + + void drawStartScreen(Graphics2D g) { + g.setColor(Color.red); + g.setFont(getFont()); + g.drawString("SNAKE", 240, 190); + g.setColor(Color.orange); + g.setFont(smallFont); + g.drawString("(Click To START)", 250, 240); + } + + void drawScore(Graphics2D g) { + int h = getHeight(); + g.setFont(smallFont); + g.setColor(getForeground()); + String s = format("Hi-Score: %d Score: %d", hiScore, score); + g.drawString(s, 30, h - 30); + g.drawString(format("Energy: %d", energy), getWidth() - 150, h - 30); + } + + @Override + public void paintComponent(Graphics gg) { + super.paintComponent(gg); + Graphics2D g = (Graphics2D) gg; + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + + drawGrid(g); + + if (gameOver) { + drawStartScreen(g); + } else { + drawSnake(g); + drawTreats(g); + drawScore(g); + } + } + + public static void main(String[] args) { + SwingUtilities.invokeLater( + () -> { + JFrame mainFrame = new JFrame(); + mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + mainFrame.setTitle("SNAKE"); + mainFrame.setResizable(true); + mainFrame.add(new SimpleSnake(), BorderLayout.CENTER); + mainFrame.pack(); + mainFrame.setLocationRelativeTo(null); + mainFrame.setVisible(true); + }); + } +} diff --git a/AreaOfCircle.java b/Java/AreaOfCircle.java similarity index 100% rename from AreaOfCircle.java rename to Java/AreaOfCircle.java diff --git a/BMI.java b/Java/BMI.java similarity index 100% rename from BMI.java rename to Java/BMI.java diff --git a/Java/BinarySearch.java b/Java/BinarySearch.java new file mode 100644 index 0000000..eeffdf1 --- /dev/null +++ b/Java/BinarySearch.java @@ -0,0 +1,65 @@ +import java.util.Scanner; + +/* + * Java Program to implement binary search without using recursion + */ +public class BinarySearch { + + public static void main(String[] args) { + + Scanner commandReader = new Scanner(System.in); + System.out.println("Welcome to Java Program to perform + binary search on int array"); + System.out.println("Enter total number of elements : "); + int length = commandReader.nextInt(); + int[] input = new int[length]; + + System.out.printf("Enter %d integers %n", length); + for (int i = 0; i < length; i++) { + input[i] = commandReader.nextInt(); + } + + System.out.println("Please enter number to be searched in array + (sorted order)"); + int key = commandReader.nextInt(); + + int index = performBinarySearch(input, key); + + if (index == -1) { + System.out.printf("Sorry, %d is not found in array %n", key); + } else { + System.out.printf("%d is found in array at index %d %n", key, + index); + } + + commandReader.close(); + + } + + /** + * Java method to perform binary search. It accept an integer array and a + * number and return the index of number in the array. If number doesn't + * exists in array then it return -1 + * + * @param input + * @param number + * @return index of given number in array or -1 if not found + */ + public static int performBinarySearch(int[] input, int number) { + int low = 0; + int high = input.length - 1; + + while (high >= low) { + int middle = (low + high) / 2; + if (input[middle] == number) { + return middle; + } else if (input[middle] < number) { + low = middle + 1; + } else if (input[middle] > number) { + high = middle - 1; + } + } + return -1; + } + +} diff --git a/Java/Combination.java b/Java/Combination.java new file mode 100644 index 0000000..1298621 --- /dev/null +++ b/Java/Combination.java @@ -0,0 +1,52 @@ +package com.thealgorithms.backtracking; + +import java.util.*; + +/** + * Finds all permutations of given array + * @author Alan Piao (https://github.com/cpiao3) + */ +public class Combination { + private static int length; + /** + * Find all combinations of given array using backtracking + * @param arr the array. + * @param n length of combination + * @param the type of elements in the array. + * @return a list of all combinations of length n. If n == 0, return null. + */ + public static List> combination(T[] arr, int n) { + if (n == 0) { + return null; + } + length = n; + T[] array = arr.clone(); + Arrays.sort(array); + List> result = new LinkedList<>(); + backtracking(array, 0, new TreeSet(), result); + return result; + } + /** + * Backtrack all possible combinations of a given array + * @param arr the array. + * @param index the starting index. + * @param currSet set that tracks current combination + * @param result the list contains all combination. + * @param the type of elements in the array. + */ + private static void backtracking(T[] arr, int index, TreeSet currSet, List> result) { + if (index + length - currSet.size() > arr.length) return; + if (length - 1 == currSet.size()) { + for (int i = index; i < arr.length; i++) { + currSet.add(arr[i]); + result.add((TreeSet) currSet.clone()); + currSet.remove(arr[i]); + } + } + for (int i = index; i < arr.length; i++) { + currSet.add(arr[i]); + backtracking(arr, i + 1, currSet, result); + currSet.remove(arr[i]); + } + } +} diff --git a/ConMetToFeet.java b/Java/ConMetToFeet.java similarity index 100% rename from ConMetToFeet.java rename to Java/ConMetToFeet.java diff --git a/Java/CycleSort.java b/Java/CycleSort.java new file mode 100644 index 0000000..32b7e77 --- /dev/null +++ b/Java/CycleSort.java @@ -0,0 +1,52 @@ +// java program to check implement cycle sort +import java.util.*; +public class MissingNumber { + public static void main(String[] args) + { + int[] arr = { 3, 2, 4, 5, 1 }; + int n = arr.length; + System.out.println("Before sort :"); + System.out.println(Arrays.toString(arr)); + CycleSort(arr, n); + + } + + static void CycleSort(int[] arr, int n) + { + int i = 0; + while (i < n) { + // as array is of 1 based indexing so the + // correct position or index number of each + // element is element-1 i.e. 1 will be at 0th + // index similarly 2 correct index will 1 so + // on... + int correctpos = arr[i] - 1; + if (arr[i] < n && arr[i] != arr[correctpos]) { + // if array element should be lesser than + // size and array element should not be at + // its correct position then only swap with + // its correct position or index value + swap(arr, i, correctpos); + } + else { + // if element is at its correct position + // just increment i and check for remaining + // array elements + i++; + } + } + System.out.println("After sort : "); + System.out.print(Arrays.toString(arr)); + + + } + + static void swap(int[] arr, int i, int correctpos) + { + // swap elements with their correct indexes + int temp = arr[i]; + arr[i] = arr[correctpos]; + arr[correctpos] = temp; + } +} +// this code is contributed by Sanket Jaiswal diff --git a/Java/Determinant_of_Matrix.java b/Java/Determinant_of_Matrix.java new file mode 100644 index 0000000..bf856b9 --- /dev/null +++ b/Java/Determinant_of_Matrix.java @@ -0,0 +1,94 @@ +// Java program to find Determinant of a matrix +class GFG { + + // Dimension of input square matrix + static final int N = 4; + + // Function to get determinant of matrix + static int determinantOfMatrix(int mat[][], int n) + { + int num1, num2, det = 1, index, + total = 1; // Initialize result + + // temporary array for storing row + int[] temp = new int[n + 1]; + + // loop for traversing the diagonal elements + for (int i = 0; i < n; i++) { + index = i; // initialize the index + + // finding the index which has non zero value + while (mat[index][i] == 0 && index < n) { + index++; + } + if (index == n) // if there is non zero element + { + // the determinant of matrix as zero + continue; + } + if (index != i) { + // loop for swaping the diagonal element row + // and index row + for (int j = 0; j < n; j++) { + swap(mat, index, j, i, j); + } + // determinant sign changes when we shift + // rows go through determinant properties + det = (int)(det * Math.pow(-1, index - i)); + } + + // storing the values of diagonal row elements + for (int j = 0; j < n; j++) { + temp[j] = mat[i][j]; + } + + // traversing every row below the diagonal + // element + for (int j = i + 1; j < n; j++) { + num1 = temp[i]; // value of diagonal element + num2 = mat[j] + [i]; // value of next row element + + // traversing every column of row + // and multiplying to every row + for (int k = 0; k < n; k++) { + // multiplying to make the diagonal + // element and next row element equal + mat[j][k] = (num1 * mat[j][k]) + - (num2 * temp[k]); + } + total = total * num1; // Det(kA)=kDet(A); + } + } + + // multiplying the diagonal elements to get + // determinant + for (int i = 0; i < n; i++) { + det = det * mat[i][i]; + } + return (det / total); // Det(kA)/k=Det(A); + } + + static int[][] swap(int[][] arr, int i1, int j1, int i2, + int j2) + { + int temp = arr[i1][j1]; + arr[i1][j1] = arr[i2][j2]; + arr[i2][j2] = temp; + return arr; + } + + // Driver code + public static void main(String[] args) + { + int mat[][] = { { 1, 0, 2, -1 }, + { 3, 0, 0, 5 }, + { 2, 1, 4, -3 }, + { 1, 0, 5, 0 } }; + + // Function call + System.out.printf( + "Determinant of the matrix is : %d", + determinantOfMatrix(mat, N)); + } +} diff --git a/Java/FloodFill.java b/Java/FloodFill.java new file mode 100644 index 0000000..d7842a6 --- /dev/null +++ b/Java/FloodFill.java @@ -0,0 +1,69 @@ +package com.thealgorithms.backtracking; + +/** + * Java program for Flood fill algorithm. + * @author Akshay Dubey (https://github.com/itsAkshayDubey) + */ +public class FloodFill { + + /** + * Get the color at the given co-odrinates of a 2D image + * + * @param image The image to be filled + * @param x The x co-ordinate of which color is to be obtained + * @param y The y co-ordinate of which color is to be obtained + */ + + public static int getPixel(int[][] image, int x, int y) { + + return image[x][y]; + + } + + /** + * Put the color at the given co-odrinates of a 2D image + * + * @param image The image to be filed + * @param x The x co-ordinate at which color is to be filled + * @param y The y co-ordinate at which color is to be filled + */ + public static void putPixel(int[][] image, int x, int y, int newColor) { + + image[x][y] = newColor; + + } + + + /** + * Fill the 2D image with new color + * + * @param image The image to be filed + * @param x The x co-ordinate at which color is to be filled + * @param y The y co-ordinate at which color is to be filled + * @param newColor The new color which to be filled in the image + * @param oldColor The old color which is to be replaced in the image + * @return + */ + public static void floodFill(int[][] image, int x, int y, int newColor, int oldColor) { + + if(x < 0 || x >= image.length) return; + if(y < 0 || y >= image[x].length) return; + if(getPixel(image, x, y) != oldColor) return; + + putPixel(image, x, y, newColor); + + /* Recursively check for horizontally & vertically adjacent coordinates */ + floodFill(image, x + 1, y, newColor, oldColor); + floodFill(image, x - 1, y, newColor, oldColor); + floodFill(image, x, y + 1, newColor, oldColor); + floodFill(image, x, y - 1, newColor, oldColor); + + /* Recursively check for diagonally adjacent coordinates */ + floodFill(image, x + 1, y - 1, newColor, oldColor); + floodFill(image, x - 1, y + 1, newColor, oldColor); + floodFill(image, x + 1, y + 1, newColor, oldColor); + floodFill(image, x - 1, y - 1, newColor, oldColor); + + } + +} \ No newline at end of file diff --git a/Java/LinearSearch.java b/Java/LinearSearch.java new file mode 100644 index 0000000..a6aa4b7 --- /dev/null +++ b/Java/LinearSearch.java @@ -0,0 +1,66 @@ +import javax.swing.*; + +public class BuscaLinear { + + public static void linearSearchNumber(int[] listaNum, int numDigitado) { + int i = 0; + + while(true) { + if (numDigitado == listaNum[i]) { + JOptionPane.showMessageDialog(null, "O número " + numDigitado + " está na posição: " + i); + break; + } else if(numDigitado != listaNum[i]) { + i++; + } + } + } + + + public static void linearSearchString(String[] listaString, String strDigitada) { + int i = 0; + + while(!listaString[i].equals(strDigitada)) { + i++; + } + + if(listaString[i].equals(strDigitada)) { + JOptionPane.showMessageDialog(null, "A palavra '"+ strDigitada + "' está na posição: " + i); + } + } + + + public static void main(String[] args) { + int opc; + + int[] listaNum = new int[5]; + String[] listaString = new String[5]; + Object[] options = {"Número", "String"}; + + opc = JOptionPane.showOptionDialog(null, "Escolha o tipo de lista que deseja criar:", "Busca Linear", + JOptionPane.DEFAULT_OPTION, JOptionPane.DEFAULT_OPTION, null, options, options[0]); + + switch (opc){ + case 0: + + for(int i = 0; i < listaNum.length; i++) { + listaNum[i] = Integer.parseInt(JOptionPane.showInputDialog("Digite o " + (i+1) +"/5 número: ")); + } + int numDigitado = Integer.parseInt(JOptionPane.showInputDialog("Qual número deseja Buscar: ")); + + linearSearchNumber(listaNum, numDigitado); + + break; + + case 1: + + for(int i = 0; i < listaString.length; i++) { + listaString[i] = JOptionPane.showInputDialog("Digite a " + (i+1) +"/5 palavra: "); + } + String strDigitada = JOptionPane.showInputDialog("Qual palavra deseja Buscar: "); + + linearSearchString(listaString, strDigitada); + + break; + } + } +} diff --git a/Java/Main.class b/Java/Main.class new file mode 100644 index 0000000..bbba926 Binary files /dev/null and b/Java/Main.class differ diff --git a/Java/MergeSortInPlace.java b/Java/MergeSortInPlace.java new file mode 100644 index 0000000..4b4833c --- /dev/null +++ b/Java/MergeSortInPlace.java @@ -0,0 +1,66 @@ + +import java.util.Arrays; + +public class MergeSortInPlace { + + public static void main(String[] args) { + + int[]arr={4,6,7,4,3,1,1}; + MergeSortInPla(arr,0,arr.length); + System.out.println(Arrays.toString(arr)); + } + + private static void MergeSortInPla(int[] arr, int s, int e) { + if (e-s==1) + return; + + int m=s+(e-s)/2; + MergeSortInPla(arr,s,m); + MergeSortInPla(arr,m,e); + + Merge(arr, s,m,e); + } + + private static void Merge(int[] arr, int s, int m, int e) { + + int [] ans=new int[e-s]; + int i=s; + int j=m; + int index=0; + + while (i max) + max = a[i]; + } + return max; //maximum element from the array + } + + void countingSort(int a[], int n, int place) // function to implement counting + + sort + { + int[] output = new int[n+1]; + int[] count = new int[10]; + + // Calculate count of elements + for (int i = 0; i < n; i++) + count[(a[i] / place) % 10]++; + + // Calculate cumulative frequency + for (int i = 1; i < 10; i++) + count[i] += count[i - 1]; + + // Place the elements in sorted order + for (int i = n - 1; i >= 0; i--) { + output[count[(a[i] / place) % 10] - 1] = a[i]; + count[(a[i] / place) % 10]--; + } + + for (int i = 0; i < n; i++) + a[i] = output[i]; + } + + // function to implement radix sort + void radixsort(int a[], int n) { + + // get maximum element from array + int max = getMax(a, n); + + // Apply counting sort to sort elements based on place value + for (int place = 1; max / place > 0; place *= 10) + countingSort(a, n, place); + } + + // function to print array elements + void printArray(int a[], int n) { + for (int i = 0; i < n; ++i) + System.out.print(a[i] + " "); + } + + public static void main(String args[]) { + int a[] = {151, 259, 360, 91, 115, 706, 34, 858, 2}; + int n = a.length; + RadixSort r1 = new RadixSort(); + System.out.print("Before sorting array elements are - \n"); + r1.printArray(a,n); + r1.radixsort(a, n); + System.out.print("\n\nAfter applying Radix sort, the array elements are - + + \n"); + r1.printArray(a, n); + } + } \ No newline at end of file diff --git a/Java/ShellSort.java b/Java/ShellSort.java new file mode 100644 index 0000000..0a0db3c --- /dev/null +++ b/Java/ShellSort.java @@ -0,0 +1,42 @@ +import java.util.Arrays; +import java.util.Scanner; + +public class ShellSort { + + public static void main(String[] args) { + + Scanner sc=new Scanner(System.in); + System.out.println("Enter Length:- "); + int l=sc.nextInt(); + int [] arr=new int[l]; + + for(int i=0;i0; gap/=2) + { + for (int i=gap; i=gap && arr[j-gap]>t ; j-=gap) + { + arr[j]=arr[j-gap]; + } + arr[j]=t; + } + } + } +} diff --git a/Java/SortingusingSort.java b/Java/SortingusingSort.java new file mode 100644 index 0000000..f5248c7 --- /dev/null +++ b/Java/SortingusingSort.java @@ -0,0 +1,21 @@ +import java.util.ArrayList; +import java.util.Collections; + +class Main { + public static void main(String[] args) { + + + ArrayList numbers = new ArrayList<>(); + + + numbers.add(4); + numbers.add(2); + numbers.add(3); + System.out.println("Unsorted ArrayList: " + numbers); + + + Collections.sort(numbers); + System.out.println("Sorted ArrayList: " + numbers); + + } +} diff --git a/Java/TripletSumProgramUsingHashing.java b/Java/TripletSumProgramUsingHashing.java new file mode 100644 index 0000000..1c50c01 --- /dev/null +++ b/Java/TripletSumProgramUsingHashing.java @@ -0,0 +1,42 @@ +import java.util.*; + +class GFG { + + static boolean find3Numbers(int A[],int arr_size, int sum) + { + + for (int i = 0; i < arr_size - 2; i++) { + + // Find pair in subarray A[i+1..n-1] + // with sum equal to sum - A[i] + HashSet s = new HashSet(); + int curr_sum = sum - A[i]; + for (int j = i + 1; j < arr_size; j++) + { + if (s.contains(curr_sum - A[j])) + { + System.out.printf("Triplet is %d, + %d, %d", A[i], + A[j], curr_sum - A[j]); + return true; + } + s.add(A[j]); + } + } + + + return false; + } + + /* Driver code */ + public static void main(String[] args) + { + int A[] = { 1, 4, 45, 6, 10, 8 }; + int sum = 22; + int arr_size = A.length; + + find3Numbers(A, arr_size, sum); + } +} + + diff --git a/Java/algorithms.java b/Java/algorithms.java new file mode 100644 index 0000000..f98d595 --- /dev/null +++ b/Java/algorithms.java @@ -0,0 +1,35 @@ +// Java program for implementation of Bubble Sort +class BubbleSort { + void bubbleSort(int arr[]) + { + int n = arr.length; + for (int i = 0; i < n - 1; i++) + for (int j = 0; j < n - i - 1; j++) + if (arr[j] > arr[j + 1]) { + // swap arr[j+1] and arr[j] + int temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + } + } + + /* Prints the array */ + void printArray(int arr[]) + { + int n = arr.length; + for (int i = 0; i < n; ++i) + System.out.print(arr[i] + " "); + System.out.println(); + } + + // Driver method to test above + public static void main(String args[]) + { + BubbleSort ob = new BubbleSort(); + int arr[] = { 64, 34, 25, 12, 22, 11, 90 }; + ob.bubbleSort(arr); + System.out.println("Sorted array"); + ob.printArray(arr); + } +} +/* This code is contributed by Rajat Mishra */ diff --git a/Java/bubble_sort.java b/Java/bubble_sort.java new file mode 100644 index 0000000..ae1ceaa --- /dev/null +++ b/Java/bubble_sort.java @@ -0,0 +1,35 @@ +public class BubbleSortExample { + static void bubbleSort(int[] arr) { + int n = arr.length; + int temp = 0; + for(int i=0; i < n; i++){ + for(int j=1; j < (n-i); j++){ + if(arr[j-1] > arr[j]){ + //swap elements + temp = arr[j-1]; + arr[j-1] = arr[j]; + arr[j] = temp; + } + + } + } + + } + public static void main(String[] args) { + int arr[] ={3,60,35,2,45,320,5}; + + System.out.println("Array Before Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + System.out.println(); + + bubbleSort(arr);//sorting array elements using bubble sort + + System.out.println("Array After Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + + } +} \ No newline at end of file diff --git a/Java/bubblesort.java b/Java/bubblesort.java new file mode 100644 index 0000000..436662e --- /dev/null +++ b/Java/bubblesort.java @@ -0,0 +1,35 @@ +public class BubbleSortExample { + static void bubbleSort(int[] arr) { + int n = arr.length; + int temp = 0; + for(int i=0; i < n; i++){ + for(int j=1; j < (n-i); j++){ + if(arr[j-1] > arr[j]){ + //swap elements + temp = arr[j-1]; + arr[j-1] = arr[j]; + arr[j] = temp; + } + + } + } + + } + public static void main(String[] args) { + int arr[] ={3,60,35,2,45,320,5}; + + System.out.println("Array Before Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + System.out.println(); + + bubbleSort(arr);//sorting array elements using bubble sort + + System.out.println("Array After Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + + } +} diff --git a/Java/bubbley.java b/Java/bubbley.java new file mode 100644 index 0000000..436662e --- /dev/null +++ b/Java/bubbley.java @@ -0,0 +1,35 @@ +public class BubbleSortExample { + static void bubbleSort(int[] arr) { + int n = arr.length; + int temp = 0; + for(int i=0; i < n; i++){ + for(int j=1; j < (n-i); j++){ + if(arr[j-1] > arr[j]){ + //swap elements + temp = arr[j-1]; + arr[j-1] = arr[j]; + arr[j] = temp; + } + + } + } + + } + public static void main(String[] args) { + int arr[] ={3,60,35,2,45,320,5}; + + System.out.println("Array Before Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + System.out.println(); + + bubbleSort(arr);//sorting array elements using bubble sort + + System.out.println("Array After Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + + } +} diff --git a/Java/bucketsort.java b/Java/bucketsort.java new file mode 100644 index 0000000..ecd7e3a --- /dev/null +++ b/Java/bucketsort.java @@ -0,0 +1,39 @@ +import java.util.*; +public class Main +{ +public static int[] bucketsort(int[] array, int maximum_value) +{ +//creating an empty array called newbucket which is considered as bucket array +int[] newbucket = new int[maximum_value + 1]; +//creating another empty array called sorted_array to store the result array +int[] sorted_array = new int[array.length]; +//traversing through the input array to add each element to the bucket array +for (int a= 0; a maximum_value) +maximum_value = array[d]; +return maximum_value; +} +//main function is called within which we display the resulting array +public static void main(String args[]) +{ +int[] array ={100, 90, 80, 70, 60, 50, 40, 30, 20, 10}; +int maximum_value = maximumValue(array); +System.out.print("\nThe elements of the array to be sorted are:\n "); +System.out.println(Arrays.toString(array)); +System.out.print("\nThe elements of the sorted array sorted using bucket sort algorithm are:\n "); +System.out.println(Arrays.toString(bucketsort(array,maximum_value))); +} +} \ No newline at end of file diff --git a/Java/complex-string.java b/Java/complex-string.java new file mode 100644 index 0000000..690c8b0 --- /dev/null +++ b/Java/complex-string.java @@ -0,0 +1,19 @@ +public class StringComparison { + public static void main(String a[]){ + String str = "JavaTpoint is a great website to acquire knowledge"; + StringBuffer obj = + new StringBuffer("JavaTpoint is a great website to acquire knowledge"); + if(str.contentEquals(obj)){ + System.out.println("The content of the string is equal"); + } else { + System.out.println("The content of the string is not equal"); + } + StringBuffer obj1 = + new StringBuffer("It is another string"); + if(str.contentEquals(obj1)){ + System.out.println("The content of the string is equal"); + } else { + System.out.println("The content of the string is not equal"); + } + } +} diff --git a/Java/countingSort.java b/Java/countingSort.java new file mode 100644 index 0000000..6dbd2da --- /dev/null +++ b/Java/countingSort.java @@ -0,0 +1,52 @@ +// Java implementation of Counting Sort +class CountingSort { + void sort(char arr[]) + { + int n = arr.length; + + // The output character array that will have sorted arr + char output[] = new char[n]; + + // Create a count array to store count of individual + // characters and initialize count array as 0 + int count[] = new int[256]; + for (int i = 0; i < 256; ++i) + count[i] = 0; + + // store count of each character + for (int i = 0; i < n; ++i) + ++count[arr[i]]; + + // Change count[i] so that count[i] now contains actual + // position of this character in output array + for (int i = 1; i <= 255; ++i) + count[i] += count[i - 1]; + + // Build the output character array + // To make it stable we are operating in reverse order. + for (int i = n - 1; i >= 0; i--) { + output[count[arr[i]] - 1] = arr[i]; + --count[arr[i]]; + } + + // Copy the output array to arr, so that arr now + // contains sorted characters + for (int i = 0; i < n; ++i) + arr[i] = output[i]; + } + + // Driver method + public static void main(String args[]) + { + CountingSort ob = new CountingSort(); + char arr[] = { 'g', 'e', 'e', 'k', 's', 'f', 'o', + 'r', 'g', 'e', 'e', 'k', 's' }; + + ob.sort(arr); + + System.out.print("Sorted character array is "); + for (int i = 0; i < arr.length; ++i) + System.out.print(arr[i]); + } +} +/*This code is contributed by Rajat Mishra */ diff --git a/Java/heapsort.java b/Java/heapsort.java new file mode 100644 index 0000000..3d31a22 --- /dev/null +++ b/Java/heapsort.java @@ -0,0 +1,74 @@ +package Sorting; + +public class heapify { + + public void sort(int a[]) + { + int n=a.length; + for(int i=(n/2)-1;i>=0;i--) + { + hepify(a,n,i); + } + for(int i=n-1;i>=0;i--) { + + int temp=a[0]; + a[0]=a[i]; + a[i]=temp; + + hepify(a,i,0); + } + } + + + + + + static void hepify(int a[],int n,int i) + { + int larest; + + int left=(2*i)+1; + int right=(2*i)+2; + + if(lefta[i]) + { + larest=left; + } + else{ + larest=i; + } + if(righta[larest]) + { + larest=right; + } + if(larest!=i) + { + int temp; + temp=a[i]; + a[i]=a[larest]; + a[larest]=temp; + + hepify(a,n,larest); + } + } + + static void display(int a[]) + { + for(int i=0;i 0 ? "Yes" : "No"); + System.out.println(capitalize(A) + " " + capitalize(B)); + } + + private static String capitalize(String word) { + return word.substring(0, 1).toUpperCase() + word.substring(1, word.length()); + } +} \ No newline at end of file diff --git a/Java/merge.java b/Java/merge.java new file mode 100644 index 0000000..0741042 --- /dev/null +++ b/Java/merge.java @@ -0,0 +1,106 @@ +// C++ program for Merge Sort +#include +using namespace std; + +// Merges two subarrays of array[]. +// First subarray is arr[begin..mid] +// Second subarray is arr[mid+1..end] +void merge(int array[], int const left, int const mid, + int const right) +{ + auto const subArrayOne = mid - left + 1; + auto const subArrayTwo = right - mid; + + // Create temp arrays + auto *leftArray = new int[subArrayOne], + *rightArray = new int[subArrayTwo]; + + // Copy data to temp arrays leftArray[] and rightArray[] + for (auto i = 0; i < subArrayOne; i++) + leftArray[i] = array[left + i]; + for (auto j = 0; j < subArrayTwo; j++) + rightArray[j] = array[mid + 1 + j]; + + auto indexOfSubArrayOne + = 0, // Initial index of first sub-array + indexOfSubArrayTwo + = 0; // Initial index of second sub-array + int indexOfMergedArray + = left; // Initial index of merged array + + // Merge the temp arrays back into array[left..right] + while (indexOfSubArrayOne < subArrayOne + && indexOfSubArrayTwo < subArrayTwo) { + if (leftArray[indexOfSubArrayOne] + <= rightArray[indexOfSubArrayTwo]) { + array[indexOfMergedArray] + = leftArray[indexOfSubArrayOne]; + indexOfSubArrayOne++; + } + else { + array[indexOfMergedArray] + = rightArray[indexOfSubArrayTwo]; + indexOfSubArrayTwo++; + } + indexOfMergedArray++; + } + // Copy the remaining elements of + // left[], if there are any + while (indexOfSubArrayOne < subArrayOne) { + array[indexOfMergedArray] + = leftArray[indexOfSubArrayOne]; + indexOfSubArrayOne++; + indexOfMergedArray++; + } + // Copy the remaining elements of + // right[], if there are any + while (indexOfSubArrayTwo < subArrayTwo) { + array[indexOfMergedArray] + = rightArray[indexOfSubArrayTwo]; + indexOfSubArrayTwo++; + indexOfMergedArray++; + } + delete[] leftArray; + delete[] rightArray; +} + +// begin is for left index and end is +// right index of the sub-array +// of arr to be sorted */ +void mergeSort(int array[], int const begin, int const end) +{ + if (begin >= end) + return; // Returns recursively + + auto mid = begin + (end - begin) / 2; + mergeSort(array, begin, mid); + mergeSort(array, mid + 1, end); + merge(array, begin, mid, end); +} + +// UTILITY FUNCTIONS +// Function to print an array +void printArray(int A[], int size) +{ + for (auto i = 0; i < size; i++) + cout << A[i] << " "; +} + +// Driver code +int main() +{ + int arr[] = { 12, 11, 13, 5, 6, 7 }; + auto arr_size = sizeof(arr) / sizeof(arr[0]); + + cout << "Given array is \n"; + printArray(arr, arr_size); + + mergeSort(arr, 0, arr_size - 1); + + cout << "\nSorted array is \n"; + printArray(arr, arr_size); + return 0; +} + +// This code is contributed by Mayank Tyagi +// This code was revised by Joshua Estes diff --git a/Java/mergeSort.class b/Java/mergeSort.class new file mode 100644 index 0000000..a4529d7 Binary files /dev/null and b/Java/mergeSort.class differ diff --git a/Java/mergeSort.java b/Java/mergeSort.java new file mode 100644 index 0000000..e41958d --- /dev/null +++ b/Java/mergeSort.java @@ -0,0 +1,68 @@ +import java.util.Arrays; + +class mergeSort { + + static void merge(int array[], int p, int q, int r) { + + int n1 = q - p + 1; + int n2 = r - q; + + int L[] = new int[n1]; + int M[] = new int[n2]; + + for (int i = 0; i < n1; i++) + L[i] = array[p + i]; + for (int j = 0; j < n2; j++) + M[j] = array[q + 1 + j]; + + int i, j, k; + i = 0; + j = 0; + k = p; + + while (i < n1 && j < n2) { + if (L[i] <= M[j]) { + array[k] = L[i]; + i++; + } else { + array[k] = M[j]; + j++; + } + k++; + } + + while (i < n1) { + array[k] = L[i]; + i++; + k++; + } + + while (j < n2) { + array[k] = M[j]; + j++; + k++; + } + } + + static void mergeSort(int array[], int left, int right) { + if (left < right) { + + int mid = (left + right) / 2; + + mergeSort(array, left, mid); + mergeSort(array, mid + 1, right); + + merge(array, left, mid, right); + } + } + + public static void main(String args[]) { + + int[] array = { 5, 2, 3, 4, 1, 6 }; + + mergeSort(array, 0, array.length - 1); + + System.out.println("Sorted Array:"); + System.out.println(Arrays.toString(array)); + } +} diff --git a/Java/recursion.java b/Java/recursion.java new file mode 100644 index 0000000..7870d8b --- /dev/null +++ b/Java/recursion.java @@ -0,0 +1,158 @@ +import java.util.ArrayList; +public class Recursion { + public static void main(String[] args) { + int[] arr={1,2,3,4,5,6,6}; //7 i=7-1 6 + int target=123456; + System.out.println((findallindex(arr,6,0))); +// int digits=(int)(Math.log10(target))+1; +// System.out.println(digits); + } + + public static int fibo(int n) { + if (n<2) { + return n; + } + return fibo(n-1)+fibo(n-2); + } + + public static int bs(int[] arr,int target) { + int s=0; + int e=arr.length - 1; + while(starget) { + e=mid-1; + } + if (arr[mid]e) { + return -1; + } + + if (targetarr[mid]) { + return BSusingRecusrsion(arr, target, s = mid + 1, e); + } + return mid; + } + + public static int sumofn(int n) { + if (n<=1) { + return 1; + } + + return n+sumofn(n-1); + } + + public static int fact(int n) { + if (n<=1) { + return 1; + } + return n*fact(n-1); + + } + + public static int max(int[] nums,int i,int max) { + if (i==nums.length) { + return max; + } + + if (nums[i]>max) { + max=nums[i]; + } + return max(nums,++i,max); + } + + public static int sumofDigits(int n) { + if(n%10==n) { + return n; + } + return sumofDigits(n/10) + n%10; + } + + public static int reverseDigit(int n) { + int rev=0; + while(n!=0) { + rev=(rev*10)+(n%10); + n/=10; + } + return rev; + } + static int rev=0; + static int i=0; + public static int revusingRecursion(int n) { + if (n==0) + { + return rev; + } + rev=(rev*10)+(n%10); + n/=10; + return revusingRecursion(n); + } + + public static Boolean sortedarr(int[] nums) + { + if (i>=nums.length-1) { + return true; + } + + if (nums[i]<=nums[i+1]) { + i++; + return sortedarr(nums); + } + return false; + + } + + public static Boolean sorted(int[] nums,int j) { + if (i>=nums.length-1) { + return true; + } + return (nums[j]<=nums[j+1] && sorted(nums,++i)); + + + } + + public static int linearSearchUsingRecursion(int[] nums,int target) { + if (nums[i]==target ) { + return i; + } + i+=1; + return linearSearchUsingRecursion(nums,target); + + } + + + static ArrayList indexNos = new ArrayList(); + public static ArrayList findallindex(int[] nums,int target,int i ) { + if (i==nums.length-1) { + return indexNos; + } + if (nums[i]==target) { + indexNos.add(i); + } + return findallindex(nums,target,i+=1); + + } + + + +} + diff --git a/Javascript/binarySearch.js b/Javascript/binarySearch.js new file mode 100644 index 0000000..b0c3a4f --- /dev/null +++ b/Javascript/binarySearch.js @@ -0,0 +1,28 @@ +let iterativeFunction = function (arr, x) { + + let start = 0 + let end = arr.length-1 + + while (start<=end){ + + let mid = Math.floor((start + end)/2); + + if (arr[mid]===x) return true; + + else if (arr[mid] < x) + start = mid + 1; + else + end = mid - 1; + } + + return false; +} + +let arr = [1, 3, 5, 7, 8, 9]; +let x = 5; + +if (iterativeFunction(arr, x)) + console.log('Element found!') +else { + console.log('Element not found!') +} diff --git a/Javascript/bubbleSort.js b/Javascript/bubbleSort.js new file mode 100644 index 0000000..76c82ba --- /dev/null +++ b/Javascript/bubbleSort.js @@ -0,0 +1,32 @@ +function bubbleSort(arr){ + + let i, j; + let len = arr.length; + + let isSwapped = false; + + for(i =0; i < len; i++){ + + isSwapped = false; + + for(j = 0; j < len; j++){ + if(arr[j] > arr[j + 1]){ + var temp = arr[j] + arr[j] = arr[j+1]; + arr[j+1] = temp; + isSwapped = true; + } + } + + if(!isSwapped){ + break; + } + } + + console.log(arr) +} + + +const arr = [243, 45, 23, 356, 3, 5346, 35, 5]; + +bubbleSort(arr) diff --git a/Javascript/bucketsort.js b/Javascript/bucketsort.js new file mode 100644 index 0000000..dbd5d9a --- /dev/null +++ b/Javascript/bucketsort.js @@ -0,0 +1,28 @@ +const bucketSort = (arr, n = arr.length) => { + //Create a bucket array + let bucket = new Array(n); + + //Add bucket group + for(let i = 0; i < n; i++){ + bucket[i] = []; + } + + //Add the elements in a same range in bucket + for(let i = 0; i < n; i++){ + let bucketIndex = Math.floor(arr[i]) * n; + bucket[bucketIndex].push(arr[i]); + } + + //Sort each bucket separately + for(let i = 0; i < n; i++){ + bucket[i].sort(); + } + + // Get the sorted array + let index = 0; + for (let i = 0; i < n; i++) { + for (let j = 0, size = bucket[i].length; j < size; j++) { + arr[index++] = bucket[i][j]; + } + } +} diff --git a/Javascript/filter.js b/Javascript/filter.js new file mode 100644 index 0000000..f13e1c0 --- /dev/null +++ b/Javascript/filter.js @@ -0,0 +1,9 @@ +const users = [ + { name: 'Ada Lovelace', premium: true }, + { name: 'Grace Hopper', premium: false }, + { name: 'Alan Turing', premium: true }, + { name: 'Linus Torvalds', premium: false }, + { name: 'Margaret Hamilton', premium: true } + ] + const premiumUser = users.filter(user => user.premium) + console.log(premiumUser) diff --git a/Javascript/getProviderName.js b/Javascript/getProviderName.js new file mode 100644 index 0000000..5b3768d --- /dev/null +++ b/Javascript/getProviderName.js @@ -0,0 +1,15 @@ +let input = 'arie@hacktober.com' +let provider = ''; + +for (let i = 0; i < input.length; i++) { + if (input[i - 1] === '@') { + for (let j = i; j < input.length; j++) { + if (input[j] === '.') { + break; + } + provider += input[j]; + } + break; + } +} +console.log(`Your email provider is ${provider}`); diff --git a/Javascript/heapsort.js b/Javascript/heapsort.js new file mode 100644 index 0000000..acde722 --- /dev/null +++ b/Javascript/heapsort.js @@ -0,0 +1,93 @@ +//Heap sort algorithm in Javascript using Max-heap + +const maxHeapify = (arr, n, i) => { + let largest = i; + let l = 2 * i + 1; //left child index + let r = 2 * i + 2; //right child index + + //If left child is smaller than root + if (l < n && arr[l] > arr[largest]) { + largest = l; + } + + // If right child is smaller than smallest so far + if (r < n && arr[r] > arr[largest]) { + largest = r; + } + + // If smallest is not root + if (largest != i) { + let temp = arr[i]; + arr[i] = arr[largest]; + arr[largest] = temp; + + // Recursively heapify the affected sub-tree + maxHeapify(arr, n, largest); + } +} + + // main function to do heap sort + const heapSort = (arr, n) => { + // Build heap (rearrange array) + for (let i = parseInt(n / 2 - 1); i >= 0; i--) { + maxHeapify(arr, n, i); + } + + // One by one extract an element from heap + for (let i = n - 1; i >= 0; i--) { + // Move current root to end + let temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; + + // call max heapify on the reduced heap + maxHeapify(arr, i, 0); + } + } + + // Sort in descending order using Heap sort and Min-heap + + const minHeapify = (arr, n, i) => { + let smallest = i; + let l = 2 * i + 1; //left child index + let r = 2 * i + 2; //right child index + + //If left child is smaller than root + if (l < n && arr[l] < arr[smallest]) { + smallest = l; + } + + // If right child is smaller than smallest so far + if (r < n && arr[r] < arr[smallest]) { + smallest = r; + } + + // If smallest is not root + if (smallest != i) { + let temp = arr[i]; + arr[i] = arr[smallest]; + arr[smallest] = temp; + + // Recursively heapify the affected sub-tree + minHeapify(arr, n, smallest); + } +} + + // main function to do heap sort + const heapSort = (arr, n) => { + // Build heap (rearrange array) + for (let i = parseInt(n / 2 - 1); i >= 0; i--) { + minHeapify(arr, n, i); + } + + // One by one extract an element from heap + for (let i = n - 1; i >= 0; i--) { + // Move current root to end + let temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; + + // call max heapify on the reduced heap + minHeapify(arr, i, 0); + } + } diff --git a/Javascript/linearSearch.js b/Javascript/linearSearch.js new file mode 100644 index 0000000..64cfab6 --- /dev/null +++ b/Javascript/linearSearch.js @@ -0,0 +1,13 @@ +const array = [3, 8, 12, 6, 10, 2]; + +function checkForN(arr, n) { + for(let i = 0; i < array.length; i++) { + if (n === array[i]) { + return `${true} ${n} exists at index ${i}`; + } + } + + return `${false} ${n} does not exist in the given array.`; +} + +checkForN(array, 10); \ No newline at end of file diff --git a/Javascript/pascalTriangle.js b/Javascript/pascalTriangle.js new file mode 100644 index 0000000..4fda019 --- /dev/null +++ b/Javascript/pascalTriangle.js @@ -0,0 +1,30 @@ +const generate = (numRows) => { + let triangle = [[1], [1,1]] + + if(numRows === 0){ + return [] + }else if(numRows == 1){ + return [[1]] + }else if(numRows == 2){ + return [[1], [1,1]] + }else{ + for(let i = 2; i < numRows; i++){ + addRow(triangle) + } + } + return triangle +} + +const addRow = (triangle) => { + let previous = triangle[triangle.length - 1] + let newRow = [1] + for(let i = 0; i < previous.length - 1; i++){ + let current = previous[i] + let next = previous[i+1] + newRow.push(current + next) + } + newRow.push(1) + return triangle.push(newRow) +} + +console.log(generate(10)) diff --git a/Javascript/quicksort.js b/Javascript/quicksort.js new file mode 100644 index 0000000..c7e5488 --- /dev/null +++ b/Javascript/quicksort.js @@ -0,0 +1,28 @@ +function quick_Sort(origArray) { + if (origArray.length <= 1) { + return origArray; + } else { + + var left = []; + var right = []; + var newArray = []; + var pivot = origArray.pop(); + var length = origArray.length; + + for (var i = 0; i < length; i++) { + if (origArray[i] <= pivot) { + left.push(origArray[i]); + } else { + right.push(origArray[i]); + } + } + + return newArray.concat(quick_Sort(left), pivot, quick_Sort(right)); + } +} + +var myArray = [3, 0, 2, 5, -1, 4, 1 ]; + +console.log("Original array: " + myArray); +var sortedArray = quick_Sort(myArray); +console.log("Sorted array: " + sortedArray); diff --git a/Javascript/radixSort.js b/Javascript/radixSort.js new file mode 100644 index 0000000..288d4a8 --- /dev/null +++ b/Javascript/radixSort.js @@ -0,0 +1,16 @@ +function radixSort(array) { + let maxCount = maxDigits(array); + + for(let i = 0; i < maxCount; i++) { + let digits = Array.from({length: 10}, () => []); + + for(let j = 0; j < array.length; j++) { + let lastDigit = getDigit(array[j], i); + digits[lastDigit].push(array[j]); + } + + array = [].concat(...digits); + } + + return array; +} \ No newline at end of file diff --git a/Javascript/selectionSort.js b/Javascript/selectionSort.js new file mode 100644 index 0000000..2527c73 --- /dev/null +++ b/Javascript/selectionSort.js @@ -0,0 +1,18 @@ +function selectionSort(arr) { + let min; + for (let i = 0; i < arr.length; i++) { + // Assume a minimum value + min = i; + for (let j = i + 1; j < arr.length; j++) { + if (arr[j] < arr[min]) { + min = j; + } + } + + // Swap if new minimun value found + if (min !== i) { + [arr[i], arr[min]] = [arr[min], arr[i]]; + } + } + return arr; +} \ No newline at end of file diff --git a/Krushkals_algorithm_in_java b/Krushkals_algorithm_in_java new file mode 100644 index 0000000..e0b75ef --- /dev/null +++ b/Krushkals_algorithm_in_java @@ -0,0 +1,187 @@ +// Java program for Kruskal's algorithm to find Minimum Spanning Tree of a given connected, undirected and weighted graph + +import java.io.*; +import java.lang.*; +import java.util.*; + +class Graph { + + // A class to represent a graph edge + class Edge implements Comparable { + int src, dest, weight; + + // Comparator function used for + // sorting edgesbased on their weight + public int compareTo(Edge compareEdge) + { + return this.weight - compareEdge.weight; + } + }; + + // A class to represent a subset for + // union-find + class subset { + int parent, rank; + }; + + int V, E; // V-> no. of vertices & E->no.of edges + Edge edge[]; // collection of all edges + + // Creates a graph with V vertices and E edges + Graph(int v, int e) + { + V = v; + E = e; + edge = new Edge[E]; + for (int i = 0; i < e; ++i) + edge[i] = new Edge(); + } + + // A utility function to find set of an + // element i (uses path compression technique) + int find(subset subsets[], int i) + { + // find root and make root as parent of i + // (path compression) + if (subsets[i].parent != i) + subsets[i].parent + = find(subsets, subsets[i].parent); + + return subsets[i].parent; + } + + // A function that does union of two sets + // of x and y (uses union by rank) + void Union(subset subsets[], int x, int y) + { + int xroot = find(subsets, x); + int yroot = find(subsets, y); + + // Attach smaller rank tree under root + // of high rank tree (Union by Rank) + if (subsets[xroot].rank < subsets[yroot].rank) + subsets[xroot].parent = yroot; + else if (subsets[xroot].rank > subsets[yroot].rank) + subsets[yroot].parent = xroot; + + // If ranks are same, then make one as + // root and increment its rank by one + else { + subsets[yroot].parent = xroot; + subsets[xroot].rank++; + } + } + + // The main function to construct MST using Kruskal's + // algorithm + void KruskalMST() + { + // This will store the resultant MST + Edge result[] = new Edge[V]; + + // An index variable, used for result[] + int e = 0; + + // An index variable, used for sorted edges + int i = 0; + for (i = 0; i < V; ++i) + result[i] = new Edge(); + + // Step 1: Sort all the edges in non-decreasing + // order of their weight. If we are not allowed to + // change the given graph, we can create a copy of + // array of edges + Arrays.sort(edge); + + // Allocate memory for creating V subsets + subset subsets[] = new subset[V]; + for (i = 0; i < V; ++i) + subsets[i] = new subset(); + + // Create V subsets with single elements + for (int v = 0; v < V; ++v) { + subsets[v].parent = v; + subsets[v].rank = 0; + } + + i = 0; // Index used to pick next edge + + // Number of edges to be taken is equal to V-1 + while (e < V - 1) { + // Step 2: Pick the smallest edge. And increment + // the index for next iteration + Edge next_edge = edge[i++]; + + int x = find(subsets, next_edge.src); + int y = find(subsets, next_edge.dest); + + // If including this edge doesn't cause cycle, + // include it in result and increment the index + // of result for next edge + if (x != y) { + result[e++] = next_edge; + Union(subsets, x, y); + } + // Else discard the next_edge + } + + // print the contents of result[] to display + // the built MST + System.out.println("Following are the edges in " + + "the constructed MST"); + int minimumCost = 0; + for (i = 0; i < e; ++i) { + System.out.println(result[i].src + " -- " + + result[i].dest + + " == " + result[i].weight); + minimumCost += result[i].weight; + } + System.out.println("Minimum Cost Spanning Tree " + + minimumCost); + } + + // Driver's Code + public static void main(String[] args) + { + + /* Let us create following weighted graph + 10 + 0--------1 + | \ | + 6| 5\ |15 + | \ | + 2--------3 + 4 */ + int V = 4; // Number of vertices in graph + int E = 5; // Number of edges in graph + Graph graph = new Graph(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; + + // Function call + graph.KruskalMST(); + } +} diff --git a/Leap.cpp b/Leap.cpp new file mode 100644 index 0000000..3ac7217 --- /dev/null +++ b/Leap.cpp @@ -0,0 +1,49 @@ +#include + +int main() { + + int year; + + printf("Enter a year: "); + + scanf("%d", &year); + + // leap year if perfectly divisible by 400 + + if (year % 400 == 0) { + + printf("%d is a leap year.", year); + + } + + // not a leap year if divisible by 100 + + // but not divisible by 400 + + else if (year % 100 == 0) { + + printf("%d is not a leap year.", year); + + } + + // leap year if not divisible by 100 + + // but divisible by 4 + + else if (year % 4 == 0) { + + printf("%d is a leap year.", year); + + } + + // all other years are not leap years + + else { + + printf("%d is not a leap year.", year); + + } + + return 0; + +} diff --git a/Linear Search b/Linear Search new file mode 100644 index 0000000..50f03c7 --- /dev/null +++ b/Linear Search @@ -0,0 +1,38 @@ +class GFG { + + // Function for linear search + public static int search(int arr[], int x) + { + int n = arr.length; + + // Traverse array arr[] + for (int i = 0; i < n; i++) { + + // If element found then + // return that index + if (arr[i] == x) + return i; + } + return -1; + } + + // Driver Code + public static void main(String args[]) + { + // Given arr[] + int arr[] = { 2, 3, 4, 10, 40 }; + + // Element to search + int x = 10; + + // Function Call + int result = search(arr, x); + if (result == -1) + System.out.print( + "Element is not present in array"); + else + System.out.print("Element is present" + + " at index " + + result); + } +} diff --git a/Maximum width of binary tree.cpp b/Maximum width of binary tree.cpp new file mode 100644 index 0000000..f6a7763 --- /dev/null +++ b/Maximum width of binary tree.cpp @@ -0,0 +1,42 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int widthOfBinaryTree(TreeNode* root) { + if(!root) + return 0; + int ans = 0; + queue> q; + q.push({root,0}); + while(!q.empty()){ + int size=q.size(); + int mini=q.front().second; + int first,last; + for(int itr = 0; itrleft) + q.push({temp->left,cur_id*2+1}); + if(temp->right) + q.push({temp->right,cur_id*2+2}); + } + ans = max(ans, (last-first+1)); + } + return ans; + } +}; \ No newline at end of file diff --git a/Merge_sort.cpp b/Merge_sort.cpp new file mode 100644 index 0000000..802e48f --- /dev/null +++ b/Merge_sort.cpp @@ -0,0 +1,75 @@ +#include +using namespace std ; + +class Solution { +public: + void merge(int arr[], int l, int mid, int r) + { + int i = l ; // starting index of left half of arr + int j = mid + 1; // starting index of right half of arr + int f = l ; // index used to transfer elements in temporary array + int temp[100000] ; // temporary array + + //storing elements in the temporary array in a sorted manner// + + while (i <= mid && j <= r) { + if (arr[i] < arr[j]) { + temp[f] = arr[i] ; + i++ ; + } + else { + temp[f] = arr[j] ; + j++ ; + } + f++ ; + } + + // if elements on the left half are still left // + + if (i > mid) { + while (j <= r) { + temp[f] = arr[j] ; + f++ ; j++ ; + } + } + else { + // if elements on the right half are still left // + while (i <= mid) { + temp[f] = arr[i] ; + f++ ; i++ ; + } + } + + // transfering all elements from temporary to arr // + for (int f = l ; f <= r; f++) { + arr[f] = temp[f] ; + } + } + void mergeSort(int arr[], int l, int r) + { + if (l < r) { + int mid = (l + r) / 2 ; + mergeSort(arr, l, mid) ; // left half + mergeSort(arr, mid + 1, r) ; // right half + merge(arr, l, mid, r) ; // merging sorted halves + } + } +}; +int main() { + + int arr[] = {9, 4, 7, 6, 3, 1, 5} ; + int n = 7; + + Solution obj ; + cout << "Before Sorting Array: "< +using namespace std; +class Solution { +public: + bool checkInclusion(string s1, string s2) { + vector cnt1(26), cnt2(26); + for(int i = 0; i < s1.size(); i++)cnt1[s1[i] - 'a']++; + int j = 0; + int required = s1.size(); + for(int i = 0; i < s2.size(); i++){ + char x = s2[i]; + cnt2[x - 'a']++; + if(cnt1[x - 'a'] && cnt2[x - 'a'] <= cnt1[x - 'a']) required--; + while(j <= i && cnt2[s2[j] - 'a'] - 1 >= cnt1[s2[j] - 'a']){ + cnt2[s2[j] - 'a']--; + j++; + } + if(i - j + 1 == s1.size() && required == 0){ + return true; + } + } + return false; + } +}; +main(){ + Solution ob; + cout << (ob.checkInclusion("abc", "findcab")); +} diff --git a/Product.java b/Product.java new file mode 100644 index 0000000..5b208b4 --- /dev/null +++ b/Product.java @@ -0,0 +1,39 @@ +import java.util.*; + +class Product +{ + public static void main(String arg[]) + { + Scanner sc = new Scanner(System.in); + + int [][] a = new int[3][3]; + System.out.println("enter the integers:"); + for(int i=0;i<3;i++) + { + for(int j=0;j<3;j++) + { + a[i][j] = sc.nextInt(); + } + } + + for(int i=0;i<3;i++) + { + for(int j=0;j<3;j++) + { + System.out.print(""+a[i][j]); + } + + System.out.print("\n"); + } + System.out.println("transpose is:"); + for(int j=0;j<3;j++) + { + for(int i=0;i<3;i++) + { + System.out.print(""+a[i][j]); + + } + System.out.print("\n"); + } + } +} \ No newline at end of file diff --git a/Python/1_Singly_Linked_List.py b/Python/1_Singly_Linked_List.py new file mode 100644 index 0000000..461e640 --- /dev/null +++ b/Python/1_Singly_Linked_List.py @@ -0,0 +1,115 @@ +#Node Datatype creation +from os import remove + + +class Node: + def __init__(self,data): #Initialization + self.data = data #assigning data + self.next = None #assigning the next pointer to be null + +class SingleLinkedList: + def __init__(self): + self.head = None #assigning the head to be null + + def insertion_at_beg(self, newNode): + if self.head: #if head pointer is not empty + temp = self.head + self.head = newNode + self.head.next = temp + else: #if head pointer is empty + self.head = newNode + + def insertion_at_end(self,newNode): + if self.head: #if head pointer is not empty + temp = self.head #copy the head pointer + while temp.next != None: #traverse through the list till the end + temp = temp.next + temp.next = newNode #assign the new node in the last + newNode.next = None #make the next pointer to be null + else: #if head pointer is empty + self.head = newNode #assign the node as the head node + + def deletion_at_beg(self): + if self.head: + self.head = self.head.next + else: + print("No elements are present") + + def deletion_at_end(self): + if self.head: #if head pointer is not empty + if self.head.next == None: + self.head = None + else: + temp = self.head + while temp.next.next != None: + temp = temp.next + temp.next = None + else: + print("No elements are present") + + def reverse(self): + if self.head: #if head pointer is not empty + previous = self.head + current = self.head.next + self.head = self.head.next + + previous.next = None + while self.head != None: + self.head = self.head.next + current.next = previous + previous = current + current = self.head + + self.head = previous + + print("List Reversed") + else: #if head pointer is empty + print("List Empty") + + def display(self): + ptr = self.head + if ptr == None: #when the head is empty + print("No Elements Present") + else: #print the values present + print("The Values are: ") + while ptr != None: #traverse till end of the list + print(ptr.data, end = "->") + ptr = ptr.next + print("Null") + + + +# Linked List class contains a Node object +class LinkedList: + + # Function to initialize head + def __init__(self): + self.head = None + + # This function prints contents of linked list + # starting from head + def printList(self): + temp = self.head + while (temp): + print(temp.data) + temp = temp.next + +if __name__ == "__main__": + listObject = SingleLinkedList() + listObject.insertion_at_end(Node(1)) + listObject.insertion_at_end(Node(2)) + listObject.insertion_at_end(Node(3)) + listObject.insertion_at_end(Node(4)) + listObject.insertion_at_end(Node(5)) + listObject.insertion_at_end(Node(6)) + listObject.insertion_at_end(Node(7)) + listObject.display() + listObject.reverse() + listObject.display() + listObject.deletion_at_beg() + listObject.display() + listObject.insertion_at_beg(Node(8)) + listObject.insertion_at_beg(Node(10)) + listObject.display() + listObject.deletion_at_end() + listObject.display() diff --git a/Python/AVLTree.py b/Python/AVLTree.py new file mode 100644 index 0000000..5461deb --- /dev/null +++ b/Python/AVLTree.py @@ -0,0 +1,105 @@ +class treeNode(object): + def __init__(self, value): + self.value = value + self.l = None + self.r = None + self.h = 1 + +class AVLTree(object): + + def insert(self, root, key): + + if not root: + return treeNode(key) + elif key < root.value: + root.l = self.insert(root.l, key) + else: + root.r = self.insert(root.r, key) + + root.h = 1 + max(self.getHeight(root.l), + self.getHeight(root.r)) + + b = self.getBal(root) + + if b > 1 and key < root.l.value: + return self.rRotate(root) + + if b < -1 and key > root.r.value: + return self.lRotate(root) + + if b > 1 and key > root.l.value: + root.l = self.lRotate(root.l) + return self.rRotate(root) + + if b < -1 and key < root.r.value: + root.r = self.rRotate(root.r) + return self.lRotate(root) + + return root + + def lRotate(self, z): + + y = z.r + T2 = y.l + + y.l = z + z.r = T2 + + z.h = 1 + max(self.getHeight(z.l), + self.getHeight(z.r)) + y.h = 1 + max(self.getHeight(y.l), + self.getHeight(y.r)) + + return y + + def rRotate(self, z): + + y = z.l + T3 = y.r + + y.r = z + z.l = T3 + + z.h = 1 + max(self.getHeight(z.l), + self.getHeight(z.r)) + y.h = 1 + max(self.getHeight(y.l), + self.getHeight(y.r)) + + return y + + def getHeight(self, root): + if not root: + return 0 + + return root.h + + def getBal(self, root): + if not root: + return 0 + + return self.getHeight(root.l) - self.getHeight(root.r) + + def preOrder(self, root): + + if not root: + return + + print("{0} ".format(root.value), end="") + self.preOrder(root.l) + self.preOrder(root.r) + +Tree = AVLTree() +root = None + +root = Tree.insert(root, 1) +root = Tree.insert(root, 2) +root = Tree.insert(root, 3) +root = Tree.insert(root, 4) +root = Tree.insert(root, 5) +root = Tree.insert(root, 6) + +# Preorder Traversal +print("Preorder traversal of the", + "constructed AVL tree is") +Tree.preOrder(root) +print() diff --git a/Python/Basic.py b/Python/Basic.py new file mode 100644 index 0000000..316f831 --- /dev/null +++ b/Python/Basic.py @@ -0,0 +1,29 @@ +import pygame +pygame.init() + +#creating window +gamewindow = pygame.display.set_mode((600,400)) +pygame.display.set_caption("Flappy bird") + +# creating specific variables + +exit_game = False +game_over = False + +# creating game loop + +while not exit_game: + for event in pygame.event.get(): + if event.type == pygame.QUIT: + exit_game = True + if event.type == pygame.KEYDOWN: + if event.key == pygame.K_RIGHT: + print("your pressed right arrow key") + if event.key == pygame.K_LEFT: + print("your pressed Left arrow key") + if event.key == pygame.K_UP: + print("your pressed up arrow key") + if event.key == pygame.K_DOWN: + print("you pressed down arrow key") +pygame.quit() +quit() \ No newline at end of file diff --git a/Python/BinarySearch.py b/Python/BinarySearch.py new file mode 100644 index 0000000..542cd31 --- /dev/null +++ b/Python/BinarySearch.py @@ -0,0 +1,52 @@ +''' +Binary Search +''' + +class BinarySearch: + def __init__(self, arr, val): + self.arr = arr + self.val = val + + def bubsortArray(self): + for i in range(len(self.arr)): + for j in range(len(self.arr)-1): + if self.arr[i] < self.arr[j]: + self.arr[i], self.arr[j] = self.arr[j], self.arr[i] + return self.arr + + def selectsortArray(self): + for i in range(len(self.arr)): + for j in range(i+1, len(self.arr)): + if self.arr[i] > self.arr[j]: + self.arr[j], self.arr[i] = self.arr[i], self.arr[j] + return self.arr + + def insertsortArray(self): + for i in range(len(self.arr)): + for j in range(i ,0 , -1): + if self.arr[j] < self.arr[j-1]: + self.arr[j], self.arr[j-1] = self.arr[j-1], self.arr[j] + return self.arr + + def binarySearch(self): + # self.arr = self.bubsortArray() + # self.arr = self.selectsortArray() + self.arr = self.insertsortArray() + beg = 0 + end = len(self.arr)-1 + mid = 0 + + while beg < end: + mid = (beg + end)//2 + if self.arr[mid] == self.val: + return mid+1 + elif self.arr[mid] < self.val: + beg = mid+1 + else: + end = mid-1 + + return -1 + +if __name__ == "__main__": + obj = BinarySearch([4,1,7,3,8,2,9,5,6], 5) + print("Element not present." if obj.binarySearch == -1 else f"Element found at position: {obj.binarySearch()}.") \ No newline at end of file diff --git a/Python/Calculater.py b/Python/Calculater.py new file mode 100644 index 0000000..fece818 --- /dev/null +++ b/Python/Calculater.py @@ -0,0 +1,83 @@ +import tkinter as tk + +window=tk.Tk() +window.title('TK CALCULATOR') + +eqn=" " + +def btnprs(btn): + global eqn + + if(btn=='c'): + eqn='0' + + elif(btn=='='): + result=eval(eqn) + eqn=str(result) + + else: + if(eqn=='0'): + eqn=' ' + + + eqn=eqn+btn + + label2.config(text=eqn) + + +label1=tk.Label(window,text='Tk Calcutator',fg='black',font='HELVITICA 15 bold') +label1.grid(row=0,columnspan=8,padx=5,pady=3) + +label2=tk.Label(window,text='0',bg='white',font='HELVITICA 15 bold',width=15,height=1) +label2.grid(row=1,columnspan=8,padx=5,pady=3) + + +buttons=[tk.Button for i in range(16)] + +buttons[0]=tk.Button(window,text='1',font='HELVITICA 12 bold',width=2,height=1,command=lambda:btnprs('1')) +buttons[0].grid(row=2,column=0,padx=8,pady=8) + +buttons[1]=tk.Button(window,text='2',font='HELVITICA 12 bold',width=2,height=1,command=lambda:btnprs('2')) +buttons[1].grid(row=2,column=1,padx=8,pady=8) + +buttons[2]=tk.Button(window,text='3',font='HELVITICA 12 bold',width=2,height=1,command=lambda:btnprs('3')) +buttons[2].grid(row=2,column=2,padx=8,pady=8) + +buttons[3]=tk.Button(window,text='+',font='HELVITICA 12 bold',width=2,height=1,command=lambda:btnprs('+')) +buttons[3].grid(row=2,column=3,padx=8,pady=8) + +buttons[4]=tk.Button(window,text='4',font='HELVITICA 12 bold',width=2,height=1,command=lambda:btnprs('4')) +buttons[4].grid(row=3,column=0,padx=8,pady=8) + +buttons[5]=tk.Button(window,text='5',font='HELVITICA 12 bold',width=2,height=1,command=lambda:btnprs('5')) +buttons[5].grid(row=3,column=1,padx=8,pady=8) + +buttons[6]=tk.Button(window,text='6',font='HELVITICA 12 bold',width=2,height=1,command=lambda:btnprs('6')) +buttons[6].grid(row=3,column=2,padx=8,pady=8) + +buttons[7]=tk.Button(window,text='-',font='HELVITICA 12 bold',width=2,height=1,command=lambda:btnprs('-')) +buttons[7].grid(row=3,column=3,padx=8,pady=8) + +buttons[8]=tk.Button(window,text='7',font='HELVITICA 12 bold',width=2,height=1,command=lambda:btnprs('7')) +buttons[8].grid(row=4,column=0,padx=8,pady=8) + +buttons[9]=tk.Button(window,text='8',font='HELVITICA 12 bold',width=2,height=1,command=lambda:btnprs('8')) +buttons[9].grid(row=4,column=1,padx=8,pady=8) + +buttons[10]=tk.Button(window,text='9',font='HELVITICA 12 bold',width=2,height=1,command=lambda:btnprs('9')) +buttons[10].grid(row=4,column=2,padx=8,pady=8) + +buttons[11]=tk.Button(window,text='X',font='HELVITICA 12 bold',width=2,height=1,command=lambda:btnprs('*')) +buttons[11].grid(row=4,column=3,padx=8,pady=8) + +buttons[12]=tk.Button(window,text='C',font='HELVITICA 12 bold',width=2,height=1,bg='red',command=lambda:btnprs('c')) +buttons[12].grid(row=5,column=0,padx=8,pady=8) + +buttons[13]=tk.Button(window,text='0',font='HELVITICA 12 bold',width=2,height=1,command=lambda:btnprs('0')) +buttons[13].grid(row=5,column=1,padx=8,pady=8) + +buttons[14]=tk.Button(window,text='=',font='HELVITICA 12 bold',width=2,height=1,bg='light green',command=lambda:btnprs('=')) +buttons[14].grid(row=5,column=2,padx=8,pady=8) + +buttons[15]=tk.Button(window,text='/',font='HELVITICA 12 bold',width=2,height=1,command=lambda:btnprs('/')) +buttons[15].grid(row=5,column=3,padx=8,pady=8) diff --git a/Python/HeapSort.py b/Python/HeapSort.py new file mode 100644 index 0000000..ec2646a --- /dev/null +++ b/Python/HeapSort.py @@ -0,0 +1,58 @@ +# To heapify subtree rooted at index i. +# n is size of heap + + +def heapify(arr, n, i): + largest = i # Initialize largest as root + l = 2 * i + 1 # left = 2*i + 1 + r = 2 * i + 2 # right = 2*i + 2 + + # See if left child of root exists and is + # greater than root + + if l < n and arr[i] < arr[l]: + largest = l + + # See if right child of root exists and is + # greater than root + + if r < n and arr[largest] < arr[r]: + largest = r + + # Change root, if needed + + if largest != i: + (arr[i], arr[largest]) = (arr[largest], arr[i]) # swap + + # Heapify the root. + + heapify(arr, n, largest) + + +# The main function to sort an array of given size + +def heapSort(arr): + n = len(arr) + + # Build a maxheap. + # Since last parent will be at ((n//2)-1) we can start at that location. + + for i in range(n // 2 - 1, -1, -1): + heapify(arr, n, i) + + # One by one extract elements + + for i in range(n - 1, 0, -1): + (arr[i], arr[0]) = (arr[0], arr[i]) # swap + heapify(arr, i, 0) + + +# Driver code to test above + +arr = [12, 11, 13, 5, 6, 7, ] +heapSort(arr) +n = len(arr) +print('Sorted array is') +for i in range(n): + print(arr[i]) + diff --git a/Python/InterpolationSearch.py b/Python/InterpolationSearch.py new file mode 100644 index 0000000..1f64c17 --- /dev/null +++ b/Python/InterpolationSearch.py @@ -0,0 +1,26 @@ +def interpolation_search(arr, x): + low = 0 + high = len(arr) - 1 + while low <= high and x >= arr[low] and x <= arr[high]: + if low == high: + if arr[low] == x: + return low + return -1 + pos = low + int(((float(high - low) / (arr[high] - arr[low])) * (x - arr[low]))) + if arr[pos] == x: + return pos + if arr[pos] < x: + low = pos + 1 + else: + high = pos - 1 + return -1 + + +if __name__ == '__main__': + arr = [12, 11, 13, 5, 6, 7] + x = 11 + result = interpolation_search(arr, x) + if result != -1: + print("Element is present at index", str(result)) + else: + print("Element is not present in array") diff --git a/Python/JumpSearch.py b/Python/JumpSearch.py new file mode 100644 index 0000000..88d3c4f --- /dev/null +++ b/Python/JumpSearch.py @@ -0,0 +1,27 @@ +def jump_search(arr, x): + n = len(arr) + step = math.sqrt(n) + prev = 0 + while arr[int(min(step, n) - 1)] < x: + prev = step + step += math.sqrt(n) + if prev >= n: + return -1 + while arr[int(prev)] < x: + prev += 1 + if prev == min(step, n): + return -1 + if arr[int(prev)] == x: + return prev + return -1 + + + +if __name__ == '__main__': + arr = [12, 11, 13, 5, 6, 7] + x = 11 + result = jump_search(arr, x) + if result != -1: + print("Element is present at index", str(result)) + else: + print("Element is not present in array") diff --git a/Python/MergeSort.py b/Python/MergeSort.py new file mode 100644 index 0000000..096e841 --- /dev/null +++ b/Python/MergeSort.py @@ -0,0 +1,44 @@ +# create Merge sort algorithm + + +def merge_sort(arr): + if len(arr) > 1: + mid = len(arr) // 2 + left = arr[:mid] + right = arr[mid:] + + merge_sort(left) + merge_sort(right) + + i = j = k = 0 + + while i < len(left) and j < len(right): + if left[i] < right[j]: + arr[k] = left[i] + i += 1 + else: + arr[k] = right[j] + j += 1 + k += 1 + + while i < len(left): + arr[k] = left[i] + i += 1 + k += 1 + + while j < len(right): + arr[k] = right[j] + j += 1 + k += 1 + + + +if __name__ == '__main__': + arr = [12, 11, 13, 5, 6, 7] + merge_sort(arr) + print(arr) + + +# Output + +[5, 6, 7, 11, 12, 13] diff --git a/Python/Operations_On_Stack.py b/Python/Operations_On_Stack.py new file mode 100644 index 0000000..a0169fc --- /dev/null +++ b/Python/Operations_On_Stack.py @@ -0,0 +1,88 @@ +''' +Operations on Stack +''' + +arr = [] + +# def input_elements(n): +# for i in range(0,n): +# ele = int(input(f"Enter {i+1} element: ")) +# arr.append(ele) + +def push(): + if(len(arr) == n): + print("Stack Overflow") + else: + ele = int(input("Enter Value to be inserted: ")) + arr.append(ele) + +def pop(): + if(len(arr) == 0): + print("No Elements There") + else: + print(f"Popped element is: {arr.pop()}") + #del arr[n-1] + +def disp(): + if(len(arr) == 0): + print("No Elements There") + else: + print(f"Array elements are: {arr}") + #print(arr) + +def peek(): + if(len(arr) == 0): + print("No Elements There") + else: + print(f"Array elements are: {arr[-1]}") + +def isFull(): + if(len(arr) == n): + print("Stack Overflow") + else: + print("Stack not full") + +def isEmpty(): + if(len(arr) == 0): + print("Empty Stack") + else: + print("Stack has elements") + +def size(): + print(f"Size of array is: {len(arr)}") + + +print("Basic Operations on Stack") +n = int(input("Enter size of array: ")) + +while(True): + print("\n") + print("1_Push in Stack") + print("2_Pop from Stack") + print("3_Display the Stack") + print("4_Peek from Stack") + print("5_IsFull Stack") + print("6_IsEmpty Stack") + print("7_Size") + print("8_Exit") + + opt = int(input("\nEnter your choice: ")) + + if(opt == 1): + push() + elif(opt == 2): + pop() + elif(opt == 3): + disp() + elif(opt == 4): + peek() + elif(opt == 5): + isFull() + elif(opt == 6): + isEmpty() + elif(opt == 7): + size() + elif(opt == 8): + exit() + else: + print("Invalid Choice") \ No newline at end of file diff --git a/Python/QuickSort.py b/Python/QuickSort.py new file mode 100644 index 0000000..6a87250 --- /dev/null +++ b/Python/QuickSort.py @@ -0,0 +1,13 @@ +def quick_sort(arr): + if len(arr) > 1: + pivot = arr[0] + left = [i for i in arr[1:] if i <= pivot] + right = [i for i in arr[1:] if i > pivot] + return quick_sort(left) + [pivot] + quick_sort(right) + else: + return arr + + +if __name__ == '__main__': + arr = [12, 11, 13, 5, 6, 7] + print(quick_sort(arr)) diff --git a/Python/SequencialSearch.py b/Python/SequencialSearch.py new file mode 100644 index 0000000..2354e75 --- /dev/null +++ b/Python/SequencialSearch.py @@ -0,0 +1,18 @@ +def seq_search(arr, x): + for i in range(len(arr)): + if arr[i] == x: + return i + return -1 + + + +if __name__ == '__main__': + + arr = [12, 11, 13, 5, 6, 7] + x = 11 + result = seq_search(arr, x) + if result != -1: + print("Element is present at index", str(result)) + else: + print("Element is not present in array") + diff --git a/Python/binary_search.py b/Python/binary_search.py new file mode 100644 index 0000000..f67f9ec --- /dev/null +++ b/Python/binary_search.py @@ -0,0 +1,43 @@ +import random + + +l = [] + +for i in range(32): + l.append(random.randint(1,100)) + +l.sort() +print(l) +k = int(input("enter value of k:")) +def binary_search(l,k): + + b=0 + end=len(l)-1 + + + while(end-b>1): + mid=(end+b)//2 + + if(l[mid]==k): + print("1") + return 1 + if(l[mid]>k): + end=mid-1 + if(l[mid] arr[j + 1]: + swapped = True + arr[j], arr[j + 1] = arr[j + 1], arr[j] + + if not swapped: + # if we haven't needed to make a single swap, we + # can just exit the main loop. + return + + +# Driver code to test above +arr = [64, 34, 25, 12, 22, 11, 90] + +bubbleSort(arr) + +print("Sorted array is:") +for i in range(len(arr)): + print("% d" % arr[i], end=" ") diff --git a/Python/dfs.py b/Python/dfs.py new file mode 100644 index 0000000..fb0e43a --- /dev/null +++ b/Python/dfs.py @@ -0,0 +1,23 @@ +# DFS algorithm in Python + + +# DFS algorithm +def dfs(graph, start, visited=None): + if visited is None: + visited = set() + visited.add(start) + + print(start) + + for next in graph[start] - visited: + dfs(graph, next, visited) + return visited + + +graph = {'0': set(['1', '2']), + '1': set(['0', '3', '4']), + '2': set(['0']), + '3': set(['1']), + '4': set(['2', '3'])} + +dfs(graph, '0') diff --git a/Python/fibonacci.py b/Python/fibonacci.py new file mode 100644 index 0000000..e63c049 --- /dev/null +++ b/Python/fibonacci.py @@ -0,0 +1,15 @@ +def fibonacci(n): + l=[] + for i in range(n): + if(i==0): + l.append(0) + elif(i==1): + l.append(1) + else: + l.append(l[i-1]+l[i-2]) + return l + # return a list of fibonacci numbers + +if __name__ == '__main__': + n = int(input())#number of terms + print(fibonacci(n)) \ No newline at end of file diff --git a/Python/insta_amazon_snapchat_facebook.txt b/Python/insta_amazon_snapchat_facebook.txt new file mode 100644 index 0000000..4aabec3 --- /dev/null +++ b/Python/insta_amazon_snapchat_facebook.txt @@ -0,0 +1,87 @@ +import requests +import trio +import httpx +from ignorant.modules.social_media.instagram import instagram +from ignorant.modules.shopping.amazon import amazon + +phone__number = int(input("Enter the phone number: ")) +url = "https://accounts.snapchat.com/accounts/validate_phone_number" +cookies = { + "xsrf_token":'BtpZ6sL9OenEJJYbQXFEsg' + } +headers = { + "accept": "*/*", + "accept-encoding": "gzip, deflate, br", + "accept-language": "ar,en;q=0.9,en-US;q=0.8", + "content-type": "application/x-www-form-urlencoded; charset=utf-8", + "sec-fetch-dest": "empty", + "sec-fetch-mode": "same-origin", + "sec-fetch-site": "same-origin", + "user-agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Mobile Safari/537.36" + } +data = {"phone_country_code":"IN","phone_number":phone__number,"xsrf_token":"BtpZ6sL9OenEJJYbQXFEsg"} +req = requests.post(url,data=data,headers=headers,cookies=cookies).json() +text = str(req) + #print(text) +if text.find('OK')>=0: + print(f"{phone__number}==> Not Exist In Snapchat") +else: + print(f"{phone__number}==> Exist In Snapchat") +email = phone__number +x = requests.Session() + +h={"origin": "https://www.facebook.com","referer":"https://www.facebook.com/login/identify/?ctx=recover&ars=facebook_login&from_login_screen=0","sec-fetch-dest": "empty","sec-fetch-mode": "cors","sec-fetch-site": "same-origin","sec-gpc": "1","user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.72 Safari/537.36"} +r = x.get("https://m.facebook.com/login",headers=h) +a = r.text.split('type="hidden" name="jazoest" value="', 1)[1] +jaz = a.split('"', 1)[0] +b = r.text.split(' Exist In Facebook") +else: + print(f"{email}==> Not Exist In Facebook") +async def main(): + phone=phone__number + country_code="91" + client = httpx.AsyncClient() + out = [] + await instagram(phone, country_code, client, out) + y=str(out) + if "True" in y: + print(f"{email}==>> Exist In Instagram") + else : + print(f"{email}==>> Not Exist In Instagram") + # print(y) + await amazon(phone, country_code, client, out) + z=str(out) + if "True" in z: + print(f"{email}==>> Exist In Amazon") + else : + print(f"{email}==>> Not Exist To Amazon") + await client.aclose() +trio.run(main) diff --git a/Python/is_palindrome.py b/Python/is_palindrome.py new file mode 100644 index 0000000..4776a5f --- /dev/null +++ b/Python/is_palindrome.py @@ -0,0 +1,28 @@ +def is_palindrome(s: str) -> bool: + """ + Determine whether the string is palindrome + :param s: + :return: Boolean + >>> is_palindrome("a man a plan a canal panama".replace(" ", "")) + True + >>> is_palindrome("Hello") + False + >>> is_palindrome("Able was I ere I saw Elba") + True + >>> is_palindrome("racecar") + True + >>> is_palindrome("Mr. Owl ate my metal worm?") + True + """ + # Since Punctuation, capitalization, and spaces are usually ignored while checking + # Palindrome, we first remove them from our string. + s = "".join([character for character in s.lower() if character.isalnum()]) + return s == s[::-1] + + +if __name__ == "__main__": + s = input("Enter string to determine whether its palindrome or not: ").strip() + if is_palindrome(s): + print("Given string is palindrome") + else: + print("Given string is not palindrome") diff --git a/practical1.py b/Python/math-basic.py similarity index 100% rename from practical1.py rename to Python/math-basic.py diff --git a/Python/plagrismDetector.py b/Python/plagrismDetector.py new file mode 100644 index 0000000..9a5a3c6 --- /dev/null +++ b/Python/plagrismDetector.py @@ -0,0 +1,8 @@ +from difflib import SequenceMatcher + +with open("1.txt") as f1, open("2.txt") as f2: + f1Data = f1.read() + f2Data = f2.read() + similarity = SequenceMaster(None, f1Data, f2Data).ratio() + print(similarity*100) + diff --git a/Python/reverseInteger.py b/Python/reverseInteger.py new file mode 100644 index 0000000..9289ede --- /dev/null +++ b/Python/reverseInteger.py @@ -0,0 +1,21 @@ +class Solution: + def reverse(self, x: int) -> int: + + f=0 + if(x<0): + f=1 + x=abs(x) + rev=0 + while(x!=0): + d=x%10 + x//=10 + rev=rev*10+d + + if -abs(rev)<= -2147483648 and rev >= 2147483647: + return 0 + + if(f==1): + # print(-abs(rev)) + return -abs(rev) + + return rev \ No newline at end of file diff --git a/Python/sorting_list_with_recursion.py b/Python/sorting_list_with_recursion.py new file mode 100644 index 0000000..493ef82 --- /dev/null +++ b/Python/sorting_list_with_recursion.py @@ -0,0 +1,17 @@ +def mini(L): + mini = L[0] + for i in range(len(L)): + if (L[i] < mini): + mini = L[i] + return mini + +def sort(L): + if (L==[]) or (len(L)==1): + return L + m = mini(L) + L.remove(m) + return [m]+sort(L) + +n = list(map(int,input().split(","))) + +print(sort(n)) \ No newline at end of file diff --git a/Python/tic-tac-toe.py b/Python/tic-tac-toe.py new file mode 100644 index 0000000..ca0a9d8 --- /dev/null +++ b/Python/tic-tac-toe.py @@ -0,0 +1,190 @@ +import tkinter as tk +from itertools import cycle +from tkinter import font +from typing import NamedTuple + +class Player(NamedTuple): + label: str + color: str + +class Move(NamedTuple): + row: int + col: int + label: str = "" + +BOARD_SIZE = 3 +DEFAULT_PLAYERS = ( + Player(label="X", color="blue"), + Player(label="O", color="green"), +) + +class TicTacToeGame: + def __init__(self, players=DEFAULT_PLAYERS, board_size=BOARD_SIZE): + self._players = cycle(players) + self.board_size = board_size + self.current_player = next(self._players) + self.winner_combo = [] + self._current_moves = [] + self._has_winner = False + self._winning_combos = [] + self._setup_board() + + def _setup_board(self): + self._current_moves = [ + [Move(row, col) for col in range(self.board_size)] + for row in range(self.board_size) + ] + self._winning_combos = self._get_winning_combos() + + def _get_winning_combos(self): + rows = [ + [(move.row, move.col) for move in row] + for row in self._current_moves + ] + columns = [list(col) for col in zip(*rows)] + first_diagonal = [row[i] for i, row in enumerate(rows)] + second_diagonal = [col[j] for j, col in enumerate(reversed(columns))] + return rows + columns + [first_diagonal, second_diagonal] + + def toggle_player(self): + """Return a toggled player.""" + self.current_player = next(self._players) + + def is_valid_move(self, move): + """Return True if move is valid, and False otherwise.""" + row, col = move.row, move.col + move_was_not_played = self._current_moves[row][col].label == "" + no_winner = not self._has_winner + return no_winner and move_was_not_played + + def process_move(self, move): + """Process the current move and check if it's a win.""" + row, col = move.row, move.col + self._current_moves[row][col] = move + for combo in self._winning_combos: + results = set(self._current_moves[n][m].label for n, m in combo) + is_win = (len(results) == 1) and ("" not in results) + if is_win: + self._has_winner = True + self.winner_combo = combo + break + + def has_winner(self): + """Return True if the game has a winner, and False otherwise.""" + return self._has_winner + + def is_tied(self): + """Return True if the game is tied, and False otherwise.""" + no_winner = not self._has_winner + played_moves = ( + move.label for row in self._current_moves for move in row + ) + return no_winner and all(played_moves) + + def reset_game(self): + """Reset the game state to play again.""" + for row, row_content in enumerate(self._current_moves): + for col, _ in enumerate(row_content): + row_content[col] = Move(row, col) + self._has_winner = False + self.winner_combo = [] + +class TicTacToeBoard(tk.Tk): + def __init__(self, game): + super().__init__() + self.title("Tic-Tac-Toe Game") + self._cells = {} + self._game = game + self._create_menu() + self._create_board_display() + self._create_board_grid() + + def _create_menu(self): + menu_bar = tk.Menu(master=self) + self.config(menu=menu_bar) + file_menu = tk.Menu(master=menu_bar) + file_menu.add_command(label="Play Again", command=self.reset_board) + file_menu.add_separator() + file_menu.add_command(label="Exit", command=quit) + menu_bar.add_cascade(label="File", menu=file_menu) + + def _create_board_display(self): + display_frame = tk.Frame(master=self) + display_frame.pack(fill=tk.X) + self.display = tk.Label( + master=display_frame, + text="Ready?", + font=font.Font(size=28, weight="bold"), + ) + self.display.pack() + + def _create_board_grid(self): + grid_frame = tk.Frame(master=self) + grid_frame.pack() + for row in range(self._game.board_size): + self.rowconfigure(row, weight=1, minsize=50) + self.columnconfigure(row, weight=1, minsize=75) + for col in range(self._game.board_size): + button = tk.Button( + master=grid_frame, + text="", + font=font.Font(size=36, weight="bold"), + fg="black", + width=3, + height=2, + highlightbackground="lightblue", + ) + self._cells[button] = (row, col) + button.bind("", self.play) + button.grid(row=row, column=col, padx=5, pady=5, sticky="nsew") + + def play(self, event): + """Handle a player's move.""" + clicked_btn = event.widget + row, col = self._cells[clicked_btn] + move = Move(row, col, self._game.current_player.label) + if self._game.is_valid_move(move): + self._update_button(clicked_btn) + self._game.process_move(move) + if self._game.is_tied(): + self._update_display(msg="Tied game!", color="red") + elif self._game.has_winner(): + self._highlight_cells() + msg = f'Player "{self._game.current_player.label}" won!' + color = self._game.current_player.color + self._update_display(msg, color) + else: + self._game.toggle_player() + msg = f"{self._game.current_player.label}'s turn" + self._update_display(msg) + + def _update_button(self, clicked_btn): + clicked_btn.config(text=self._game.current_player.label) + clicked_btn.config(fg=self._game.current_player.color) + + def _update_display(self, msg, color="black"): + self.display["text"] = msg + self.display["fg"] = color + + def _highlight_cells(self): + for button, coordinates in self._cells.items(): + if coordinates in self._game.winner_combo: + button.config(highlightbackground="red") + + def reset_board(self): + """Reset the game's board to play again.""" + self._game.reset_game() + self._update_display(msg="Ready?") + for button in self._cells.keys(): + button.config(highlightbackground="lightblue") + button.config(text="") + button.config(fg="black") + +def main(): + """Create the game's board and run its main loop.""" + game = TicTacToeGame() + board = TicTacToeBoard(game) + board.mainloop() + +if __name__ == "__main__": + main() diff --git a/Python/triangle.py b/Python/triangle.py new file mode 100644 index 0000000..5ba10fd --- /dev/null +++ b/Python/triangle.py @@ -0,0 +1,6 @@ +rows = int(input("Enter number of rows: ")) + +for i in range(rows): + for j in range(i+1): + print(j+1, end=" ") + print("\n") \ No newline at end of file diff --git a/Python/web-scrapping.py b/Python/web-scrapping.py new file mode 100644 index 0000000..5ab7bc2 --- /dev/null +++ b/Python/web-scrapping.py @@ -0,0 +1,6 @@ +import requests +from bs4 import BeautifulSoup + +page = requests.get('http://corona.sumselprov.go.id/index.php?module=home&id=1') + +print(page.content) \ No newline at end of file diff --git a/Python/ytviddownloader.py b/Python/ytviddownloader.py new file mode 100644 index 0000000..beab1a4 --- /dev/null +++ b/Python/ytviddownloader.py @@ -0,0 +1,30 @@ +from tkinter import * +from pytube import YouTube + +window = Tk() +window.geometry("600x700") +window.config(bg="red") +window.title("Youtube Video Downloader by Tharuka") + +youtube_logo = PhotoImage(file="yt.png") +window.iconphoto(False, youtube_logo) + +Label(window, text="Video Downloader", font=("Arial 30 bold"), bg="lightgreen").pack(padx=5, pady=50) + +video_link = StringVar() + +Label(window, text="Enter the Link : ", font=("Arial",25,"bold")).place(x=170, y=150) + +Entry_link = Entry(window, width=50, font=35 , textvariable=video_link, bd=4).place(x=60, y=200) + +def video_download(): + video_url = YouTube(str(video_link.get())) + videos = video_url.streams.first() + videos.download() + + Label(window, text="Download Completed !!!", font=("Arial",35,"bold"),bg="lightpink",fg="Black").place(x=60, y=350) + Label(window, text="Check out Download Folder", font=("Arial", 30, "bold"), bg="yellow").place(x=60, y=400) + +Button(window, text=".DOWNLOAD.", font=("Arial", 25, "bold"), bg="lightblue", command=video_download).place(x=180, y=300) + +window.mainloop() diff --git a/Quicksort.cpp b/Quicksort.cpp new file mode 100644 index 0000000..d5b5523 --- /dev/null +++ b/Quicksort.cpp @@ -0,0 +1,57 @@ +#include +using namespace std; +void swap(int *x,int *y) +{ + int temp; + temp=*x; + *x=*y; + *y=temp; +} +int partition(int arr[],int lb,int ub) +{ +int pivot=arr[lb]; +int start=lb; +int end=ub; +while(startpivot) +{ + end--; +} +if(start Please use latest pull and create file under specific language. \ No newline at end of file diff --git a/Radix-sort.cpp b/Radix-sort.cpp new file mode 100644 index 0000000..a7c2e8f --- /dev/null +++ b/Radix-sort.cpp @@ -0,0 +1,55 @@ +#include +using namespace std; + +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; +} + +void countSort(int arr[], int n, int exp) +{ + int output[n]; + int i, count[10] = { 0 }; + + for (i = 0; i < n; i++) + count[(arr[i] / exp) % 10]++; + + for (i = 1; i < 10; i++) + count[i] += count[i - 1]; + + for (i = n - 1; i >= 0; i--) { + output[count[(arr[i] / exp) % 10] - 1] = arr[i]; + count[(arr[i] / exp) % 10]--; + } + + for (i = 0; i < n; i++) + arr[i] = output[i]; +} + +void radixsort(int arr[], int n) +{ + int m = getMax(arr, n); + + for (int exp = 1; m / exp > 0; exp *= 10) + countSort(arr, n, exp); +} + +void print(int arr[], int n) +{ + for (int i = 0; i < n; i++) + cout << arr[i] << " "; +} + +int main() +{ + int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 }; + int n = sizeof(arr) / sizeof(arr[0]); + + radixsort(arr, n); + print(arr, n); + return 0; +} \ No newline at end of file diff --git a/Radix-sort.exe b/Radix-sort.exe new file mode 100644 index 0000000..c2a9ea9 Binary files /dev/null and b/Radix-sort.exe differ diff --git a/ReverseOfArray.java b/ReverseOfArray.java new file mode 100644 index 0000000..9430ecf --- /dev/null +++ b/ReverseOfArray.java @@ -0,0 +1,38 @@ +public class GFG { + + static void rvereseArray(int arr[], + int start, int end) + { + int temp; + + while (start < end) + { + temp = arr[start]; + arr[start] = arr[end]; + arr[end] = temp; + start++; + end--; + } + } + + static void printArray(int arr[], + int size) + { + for (int i = 0; i < size; i++) + System.out.print(arr[i] + " "); + + System.out.println(); + } + + + public static void main(String args[]) { + + int arr[] = {1, 2, 3, 4, 5, 6}; + printArray(arr, 6); + rvereseArray(arr, 0, 5); + System.out.print("Reversed array is \n"); + printArray(arr, 6); + + } +} + diff --git a/Sedgwik.cpp b/Sedgwik.cpp new file mode 100644 index 0000000..548f08e --- /dev/null +++ b/Sedgwik.cpp @@ -0,0 +1,2506 @@ + +C++ Programs from Algorithms 2nd edition + +Copyright 1992. Addison-Wesley Publishing Company, Inc. +All Rights Reserved. + + +-------------------------------- +CHAPTER 1 Introduction + + +-------------------------------- +CHAPTER 2 C++ (and C) + +#include +int gcd(int u, int v) + { + int t; + while (u > 0) + { + if (u < v) { t = u; u = v; v = t; } + u = u - v; + } + return v; + } +main() + { + int x, y; + while (cin >> x && cin >> y) + if (x>0 && y>0) cout << x << ' ' << y << ' ' + << gcd(x,y) << '\n'; + } + +-------------------------------- +CHAPTER 3 Elementary Data Structures + +const int N = 1000; +main() + { + int i, j, a[N+1]; + for (a[1] = 0, i = 2; i <= N; i++) a[i] = 1; + for (i = 2; i <= N/2; i++) + for (j = 2; j <= N/i; j++) + a[i*j] = 0; + for (i = 1; i <= N; i++) + if (a[i]) cout << i << ' '; + cout << '\n'; + } + + struct node + { int key; struct node *next; }; + + struct node *head, *z; + head = new node; z = new node; + head->next = z; z->next = z; + +struct node + { int key; struct node *next; }; +main() + { + int i, N, M; + struct node *t, *x; + cin >> N >> M; + t = new node; t->key = 1; x = t; + for (i = 2; i <= N; i++) + { + t->next = new node; + t = t->next; t->key = i; + } + t->next = x; + while (t != t->next) + { + for (i = 1; i < M; i++) t = t->next; + cout << t->next->key << ' '; + x = t->next; t->next = x->next; + delete x; + } + cout << t->key << '\n'; + } + + key[x] = v; next[x] = next[t]; next[t] = x++; + +class Stack + { + private: + itemType *stack; + int p; + public: + Stack(int max=100) + { stack = new itemType[max]; p = 0; } + ~Stack() + { delete stack; } + inline void push(itemType v) + { stack[p++] = v; } + inline itemType pop() + { return stack[--p]; } + inline int empty() + { return !p; } + }; + + char c; Stack acc(50); int x; + while (cin.get(c)) + { + x = 0; + while (c == ' ') cin.get(c); + if (c == '+') x = acc.pop() + acc.pop(); + if (c == '*') x = acc.pop() * acc.pop(); + while (c>='0' && c<='9') + { x = 10*x + (c-'0'); cin.get(c); } + acc.push(x); + } + cout << acc.pop() << '\n'; + + char c; Stack save(50); + while (cin.get(c)) + { + if (c == ')') cout.put(save.pop()); + if (c == '+') save.push(c); + if (c == '*') save.push(c); + while (c>='0' && c<='9') + { cout.put(c); cin.get(c); } + if (c != '(') cout << ' '; + } + cout << '\n'; + +class Stack + { + public: + Stack(int max); + ~Stack(); + void push(itemType v); + itemType pop(); + int empty(); + private: + struct node + { itemType key; struct node *next; }; + struct node *head, *z; + }; + +Stack::Stack(int max) + { + head = new node; z = new node; + head->next = z; z->next = z; + } +Stack::~Stack() + { + struct node *t = head; + while (t != z) + { head = t; t = t->next; delete head; } + } + +void Stack::push(itemType v) + { + struct node *t = new node; + t->key = v; t->next = head->next; + head->next = t; + } +itemType Stack::pop() + { + itemType x; + struct node *t = head->next; + head->next = t->next; x = t->key; + delete t; return x; + } +int Stack::empty() + { return head->next == z; } + +void Queue::put(itemType v) + { + queue[tail++] = v; + if (tail > size) tail = 0; + } +itemType Queue::get() + { + itemType t = queue[head++]; + if (head > size) head = 0; + return t; + } +int Queue::empty() + { return head == tail; } + + +-------------------------------- +CHAPTER 4 Trees + + struct node + { char info; struct node *l, *r; }; + struct node *x, *z; + + char c; Stack stack(50); + z = new node; z->l = z; z->r = z; + while (cin.get(c)) + { + while (c == ' ') cin.get(c); + x = new node; + x->info = c; x->l = z; x->r = z; + if (c=='+' || c=='*') + { x->r = stack.pop(); x->l = stack.pop(); } + stack.push(x); + } + +traverse(struct node *t) + { + stack.push(t); + while (!stack.empty()) + { + t = stack.pop(); visit(t); + if (t->r != z) stack.push(t->r); + if (t->l != z) stack.push(t->l); + } + } + +traverse(struct node *t) + { + queue.put(t); + while (!queue.empty()) + { + t = queue.get(); visit(t); + if (t->l != z) queue.put(t->l); + if (t->r != z) queue.put(t->r); + } + } + + +-------------------------------- +CHAPTER 5 Recursion + +int factorial(int N) + { + if (N == 0) return 1; + return N * factorial(N-1); + } + +int fibonacci(int N) + { + if (N <= 1) return 1; + return fibonacci(N-1) + fibonacci(N-2); + } + +const int max = 25; +int fibonacci(int N) + { + int i, F[max]; + F[0] = 1; F[1] = 1; + for (i = 2; i <= max; i++) + F[i] = F[i-1] + F[i-2]; + return F[N]; + } + +rule(int l, int r, int h) + { + int m = (l+r)/2; + if (h > 0) + { + mark(m,h); + rule(l,m,h-1); + rule(m,r,h-1); + } + } + +rule(0,8,3) + mark(4,3 ) + rule(0,4,2) + mark(2,2) + rule(0,2,1) + mark(1,1) + rule(0,1,0) + rule(1,2,0) + rule(2,4,1) + mark(3,1) + rule(2,3,0) + rule(3,4,0) + rule(4,8,2) + mark(6,2) + rule(4,6,1) + mark(5,1) + rule(4,5,0) + rule(5,6,0) + rule(6,8,1) + mark(7,1) + rule(6,7,0) + +rule(0,8,3) + rule(0,4,2) + rule(0,2,1) + rule(0,1,0) + mark(1,1) + rule(1,2,0) + mark(2,2) + rule(2,4,1) + rule(2,3,0) + mark(3,1) + rule(3,4,0) + mark(4,3 ) + rule(4,8,2) + rule(4,6,1) + rule(4,5,0) + mark(5,1) + rule(5,6,0) + mark(6,2) + rule(6,8,1) + rule(6,7,0) + mark(7,1) + +rule(int l, int r, int h) + { + int i, j, t; + for (i = 1,j = 1; i <= h; i++,j+=j) + for (t = 0; t <= (l+r)/j; t++) + mark(l+j+t*(j+j),i); + } + +star(int x, int y, int r) + { + if (r > 0) + { + star(x-r,y+r,r/2); + star(x+r,y+r,r/2); + star(x-r,y-r,r/2); + star(x+r,y-r,r/2); + box(x,y,r); + } + } + +traverse(struct node *t) + { + if (t != z) + { + traverse(t->l); + visit(t); + traverse(t->r); + } + } + +visit(struct node *t) + { t->x = ++x; t->y = y; } +traverse(struct node *t) + { + y++; + if (t != z) + { + traverse(t->l); + visit(t); + traverse(t->r) + } + y--; + } + +traverse(struct node *t) + { + if (t != z) + { + visit(t); + traverse(t->l); + traverse(t->r); + } + } + +traverse(struct node *t) + { + l: if (t == z) goto x; + visit(t); + traverse(t->l); + t = t->r; + goto l; + x: ; + } + +traverse(struct node *t) + { + l: if (t == z) goto s; + visit(t); + stack.push(t); t = t->l; goto l; + r: t = t->r; goto l; + s: if (stack.empty()) goto x; + t = stack.pop(); goto r; + x: ; + } + +traverse(struct node *t) + { + l: while (t != z) + { + visit(t); + stack.push(t->r); t = t->l; + } + if (stack.empty()) goto x; + t = stack.pop(); goto l; + x: ; + } + +traverse(struct node *t) + { + stack.push(t); + while (!stack.empty()) + { + t = stack.pop(); + while (t != z) + { + visit(t); + stack.push(t->r); + t = t->l; + } + } + } + +traverse(struct node *t) + { + stack.push(t); + while (!stack.empty()) + { + t = stack.pop(); + if (t != z) + { + visit(t); + stack.push(t->r); + stack.push(t->l); + } + } + } + +traverse(struct node *t) + { + stack.push(t); + while (!stack.empty()) + { + t = stack.pop(); visit(t); + if (t->r != z) stack.push(t->r); + if (t->l != z) stack.push(t->l); + } + } + + +-------------------------------- +CHAPTER 6 Analysis of Algorithms + + +-------------------------------- +CHAPTER 7 Implementation of Algorithms + + +-------------------------------- +CHAPTER 8 Elementary Sorting Methods + +inline void swap(itemType a[], int i, int j) + { itemType t = a[i]; a[i] = a[j]; a[j] = t; } +sort3(itemType a[], int N) + { + if (a[1] > a[2]) swap(a, 1, 2); + if (a[1] > a[3]) swap(a, 1, 3); + if (a[2] > a[3]) swap(a, 2, 3); + } +const int maxN = 100; +main() + { + int N, i; itemType v, a[maxN+1]; + N = 0; while (cin >> v) a[++N] = v; + a[0] = 0; + sort3(a, N); + for (i = 1; i <= N; i++) cout << a[i] << ' '; + cout << '\n'; + } + +void selection(itemType a[], int N) + { + int i, j, min; + for (i = 1; i < N; i++) + { + min = i; + for (j = i+1; j <= N; j++) + if (a[j] < a[min]) min = j; + swap(a, min, i); + } + } + +void insertion(itemType a[], int N) + { + int i, j; itemType v; + for (i = 2; i <= N; i++) + { + v = a[i]; j = i; + while (a[j-1] > v) + { a[j] = a[j-1]; j--; } + a[j] = v; + } + } + +void bubble(itemType a[], int N) + { + int i, j; + for (i = N; i >= 1; i--) + for (j = 2; j <= i; j++) + if (a[j-1] > a[j]) swap(a, j-1, j); + } + +void insertion(itemType a[], int p[], int N) + { + int i, j; itemType v; + for (i = 0; i <= N; i++) p[i] = i; + for (i = 2; i <= N; i++) + { + v = p[i]; j = i; + while (a[p[j-1]] > a[v]) + { p[j] = p[j-1]; j--; } + p[j] = v; + } + } + +void insitu(itemType a[], int p[], int N) + { + int i, j, k; itemType t; + for (i = 1; i <= N; i++) + if (p[i] != i) + { + t = a[i]; k = i; + do + { + j = k; a[j] = a[p[j]]; + k = p[j]; p[j] = j; + } + while (k != i); + a[j] = t; + } + } + +void insertion(itemType a[], itemType *p[], int N) + { + int i, j; itemType *v; + for (i = 0; i <= N; i++) p[i] = &a[i]; + for (i = 2; i <= N; i++) + { + v = p[i]; j = i; + while (*p[j-1] > *v) + { p[j] = p[j-1]; j--; } + p[j] = v; + } + } + +void shellsort(itemType a[], int N) + { + int i, j, h; itemType v; + for (h = 1; h <= N/9; h = 3*h+1) ; + for ( ; h > 0; h /= 3) + for (i = h+1; i <= N; i += 1) + { + v = a[i]; j = i; + while (j>h && a[j-h]>v) + { a[j] = a[j-h]; j -= h; } + a[j] = v; + } + } + +for (j = 0; j < M; j++) count[j] = 0; +for (i = 1; i <= N; i++) count[a[i]]++; +for (j = 1; j < M; j++) count[j] += count[j-1]; +for (i = N; i >= 1; i--) b[count[a[i]]--] = a[i]; +for (i = 1; i <= N; i++) a[i] = b[i]; + + +-------------------------------- +CHAPTER 9 Quicksort + +void quicksort(itemType a[], int l, int r) + { + int i; + if (r > l) + { + i = partition(a, l, r); + quicksort(a, l, i-1); + quicksort(a, i+1, r); + } + } + +void quicksort(itemType a[], int l, int r) + { + int i, j; itemType v; + if (r > l) + { + v = a[r]; i = l-1; j = r; + for (;;) + { + while (a[++i] < v) ; + while (a[--j] > v) ; + if (i >= j) break; + swap(a, i, j); + } + swap(a, i, r); + quicksort(a, l, i-1); + quicksort(a, i+1, r); + } + } + +void quicksort(itemType a[], int l, int r) + { + int i; Stack sf(50); + for (;;) + { + while (r > l) + { + i = partition(a, l, r); + if (i-l > r-i) + { sf.push(l); sf.push(i-1); l = i+1; } + else + { sf.push(i+1); sf.push(r); r = i-1; } + } + if (sf.empty()) break; + r = sf.pop(); l = sf.pop(); + } + } + +void select(itemType a[], int l, int r, int k) + { + int i; + if (r > l) + { + i = partition(a, l, r); + if (i > l+k-1) select(a, l, i-1, k); + if (i < l+k-1) select(a, i+1, r, k-i); + } + } + +void select(itemType a[], int N, int k) + { + int i, j, l, r; itemType v; + l = 1; r = N; + while (r > l) + { + v = a[r]; i = l-1; j = r; + for (;;) + { + while (a[++i] < v) ; + while (a[--j] > v) ; + if (i >= j) break; + swap(a, i, j); + } + swap(a, i, r); + if (i >= k) r = i-1; + if (i <= k) l = i+1; + } + } + + +-------------------------------- +CHAPTER 10 Radix Sorting + +class bitskey + { + private: + int x; + public: + bitskey& operator=(int i) + { x = i; return *this; } + inline unsigned bits(int k, int j) + { return (x >> k) & ~(~0 << j); } + }; +typedef bitskey itemType; + +void radixexchange(itemType a[], int l, int r, int b) + { + int i, j; itemType t; + if (r>l && b>=0) + { + i = l; j = r; + while (j != i) + { + while (!a[i].bits(b, 1) && ii) j--; + swap(a, i, j); + } + if (!a[r].bits(b, 1)) j++; + radixexchange(a, l, j-1, b-1); + radixexchange(a, j, r, b-1); + } + } + +void straightradix(itemType a[], itemType b[], int N) + { + int i, j, pass, count[M-1]; + for (pass = 0; pass < w/m; pass++) + { + for (j = 0; j < M; j++) count[j] = 0; + for (i = 1; i <= N; i++) + count[a[i].bits(pass*m, m)]++; + for (j = 1; j < M; j++) + count[j] += count[j-1]; + for (i = N; i >= 1; i--) + b[count[a[i].bits(pass*m, m)]--] = a[i]; + for (i = 1; i <= N; i++) a[i] = b[i]; + } + } + + +-------------------------------- +CHAPTER 11 Priority Queues + +class PQ + { + private: + itemType *a; + int N; + public: + PQ(int max) + { a = new itemType[max]; N = 0; } + ~PQ() + { delete a; } + void insert(itemType v) + { a[++N] = v; } + itemType remove() + { + int j, max = 1; + for (j = 2; j <= N; j++) + if (a[j] > a[max]) max = j; + swap(a, max, N); + return a[N--]; + } + }; + +void PQ::upheap(int k) + { + itemType v; + v = a[k]; a[0] = itemMAX; + while (a[k/2] <= v) + { a[k] = a[k/2]; k = k/2; } + a[k] = v; + } +void PQ::insert(itemType v) + { a[++N] = v; upheap(N); } + +void PQ::downheap(int k) + { + int j; itemType v; + v = a[k]; + while (k <= N/2) + { + j = k+k; + if (j= a[j]) break; + a[k] = a[j]; k = j; + } + a[k] = v; + } + +itemType PQ::remove() + { + itemType v = a[1]; + a[1] = a[N--]; + downheap(1); + return v; + } + +itemType PQ::replace(itemType v) + { + a[0] = v; + downheap(0); + return a[0]; + } + +void heapsort(itemType a[], int N) + { + int i; PQ heap(N); + for (i = 1; i <= N; i++) heap.insert(a[i]); + for (i = N; i >= 1; i--) a[i] = heap.remove(); + } + +void heapsort(itemType a[], int N) + { + int k; + for (k = N/2; k >= 1; k--) + downheap(a, N, k); + while (N > 1) + { swap(a, 1, N); downheap(a, --N, 1); } + } + +class PQ + { + private: + itemType *a; int *p, *info; + int N; + public: + PQ(int size) + { a = new itemType[size]; + p = new int[size]; + info = new int[size]; N = 0; } + ~PQ() + { delete a; delete p; delete info; } + void insert(int x, itemType v) + { a[++N] = v; p[x] = N; info[N] = x; } + void change(int x, itemType v) + { a[p[x]] = v; } + int remove() // remove smallest + { + int j, min = 1; + for (j = 2; j <= N; j++) + if (a[j] < a[min]) min = j; + swap(a, min, N); swap(info, min, N); + p[info[min]] = min; + return info[N--]; + } + int empty() + { return (N <= 0); } + }; + +PQ::PQ(itemType *array, int size) + { + int k; + p = new itemType[size]; q = new itemType[size]; + a = array; N = size; + for (k = 1; k <= N; k++) { p[k] = k; q[k] = k; } + for (k = N/2; k >= 1; k--) downheap(k); + } + +void PQ::downheap(int k) + { + int j, v; + v = p[k]; + while (k <= N/2) + { + j = k+k; + if (j=a[p[j]]) break; + p[k] = p[j]; q[p[j]] = k; k = j; + } + p[k] = v; q[v] = k; + } + + +-------------------------------- +CHAPTER 12 Mergesort + +i = 1; j = 1; +a[M+1] = itemMAX; b[N+1] = itemMAX; +for (k = 1; k <= M+N; k++) + c[k] = (a[i]key <= b->key) + { c->next = a; c = a; a = a->next; } + else + { c->next = b; c = b; b = b->next; } + while (c != z); + c = z->next; z->next = z; + return c; + } + +void mergesort(itemType a[], int l, int r) + { + int i, j, k, m; + if (r > l) + { + m = (r+l)/2; + mergesort(a, l, m); + mergesort(a, m+1, r); + for (i = m+1; i > l; i--) b[i-1] = a[i-1]; + for (j = m; j < r; j++) b[r+m-j] = a[j+1]; + for (k = l; k <= r; k++) + a[k] = (b[i]next != z) + { + a = c; b = c->next->next->next; + while (b != z) + { c = c->next; b = b->next->next; } + b = c->next; c->next = z; + return merge(mergesort(a), mergesort(b)); + } + return c; + } + +struct node *mergesort(struct node *c) + { + int i, N; + struct node *a, *b, *head, *todo, *t; + head = new node; + head->next = c; a = z; + for (N = 1; a != head->next; N = N+N) + { + todo = head->next; c = head; + while (todo != z) + { + t = todo; a = t; + for (i = 1; i < N; i++) t = t->next; + b = t->next; t->next = z; t = b; + for (i = 1; i < N; i++) t = t->next; + todo = t->next; t->next = z; + c->next = merge(a, b); + for (i = 1; i <= N+N; i++) c = c->next; + } + } + return head->next; + } + + +-------------------------------- +CHAPTER 13 External Sorting + + +-------------------------------- +CHAPTER 14 Elementary Searching Methods + +class Dict + { + private: + struct node + { itemType key; infoType info; }; + struct node *a; + int N; + public: + Dict(int max) + { a = new node[max]; N = 0; } + ~Dict() + { delete a; } + infoType search(itemType v); + void insert(itemType v, infoType info); + }; +infoType Dict::search(itemType v) // Sequential + { + int x = N+1; + a[0].key = v; a[0].info = infoNIL; + while (v != a[--x].key) ; + return a[x].info; + } +void Dict::insert(itemType v, infoType info) + { a[++N].key = v; a[N].info = info; } + +class Dict + { + private: + struct node + { itemType key; infoType info; + struct node *next; + node(itemType k, infoType i, struct node *n) + { key = k; info = i; next = n; }; + }; + struct node *head, *z; + public: + Dict(int max) + { + z = new node(itemMAX, infoNIL, 0); + head = new node(0, 0, z); + } + ~Dict(); + infoType search(itemType v); + void insert(itemType v, infoType info); + }; + +infoType Dict::search(itemType v) // Sorted list + { + struct node *t = head; + while (v > t->key) t = t->next; + return (v = t->key) ? t->info : z->info; + } + +void Dict::insert(itemType v, infoType info) + { + struct node *x, *t = head; + while (v > t->next->key) t = t->next; + x = new node(v, info, t->next); + t->next = x; + } + +infoType Dict::search(itemType v) // Binary search + { + int l = 1; int r = N; int x; + while (r >= l) + { + x = (l+r)/2; + if (v == a[x].key) return a[x].info; + if (v < a[x].key) r = x-1; else l = x+1; + } + return infoNIL; + } + +class Dict + { + private: + struct node + { itemType key; infoType info; + struct node *l, *r; + node(itemType k, infoType i, + struct node *ll, struct node *rr) + { key = k; info = i; l = ll; r = rr; }; + }; + struct node *head, *z; + public: + Dict(int max) + { z = new node( 0, infoNIL, 0, 0); + head = new node(itemMIN, 0, 0, z); } + ~Dict(); + infoType search(itemType v); + void insert(itemType v, infoType info); + }; + +infoType Dict::search(itemType v) + { + struct node *x = head->r; + z->key = v; + while (v != x->key) + x = (v < x->key) ? x->l : x->r; + return x->info; + } + +void Dict::insert(itemType v, infoType info) + { + struct node *p, *x; + p = head; x = head->r; + while (x != z) + { p = x; x = (v < x->key) ? x->l : x->r; } + x = new node(v, info, z, z); + if (v < p->key) p->l = x; else p->r = x; + } + +void Dict::treeprint(struct node *x) + { + if (x != z) + { + treeprint(x->l); + printnode(x); + treeprint(x->r); + } + } + +void Dict::remove(itemType v) + { + struct node *c, *p, *x, *t; + z->key = v; + p = head; x = head->r; + while (v != x->key) + { p = x; x = (v < x->key) ? x->l : x->r; } + t = x; + if (t->r == z) x = x->l; + else if (t->r->l == z) { x = x->r; x->l = t->l; } + else + { + c = x->r; while (c->l->l != z) c = c->l; + x = c->l; c->l = x->r; + x->l = t->l; x->r = t->r; + } + delete t; + if (v < p->key) p->l = x; else p->r = x; + } + + +-------------------------------- +CHAPTER 15 Balanced Trees + +void Dict::insert(itemType v, infoType info) + { + x = head; p = head; g = head; + while (x != z) + { + gg = g; g = p; p = x; + x = (v < x->key) ? x->l : x->r; + if (x->l->b && x->r->b) split(v); + } + x = new node(v, info, 1, z, z); + if (v < p->key) p->l = x; else p->r = x; + split(v); head->r->b = black; + } + +struct node *rotate(itemType v, struct node *y) + { + struct node *c, *gc; + c = (v < y->key) ? y->l : y->r; + if (v < c->key) + { gc = c->l; c->l = gc->r; gc->r = c; } + else + { gc = c->r; c->r = gc->l; gc->l = c; } + if (v < y->key) y->l = gc; else y->r = gc; + return gc; + } + +void split(itemType v) + { + x->b = red; x->l->b = black; x->r->b = black; + if (p->b) + { + g->b = red; + if (vkey != vkey) p = rotate(v, g); + x = rotate(v, gg); + x->b = black; + } + } + + Dict(int max) + { + z = new node( 0, infoNIL, black, 0, 0); + z->l = z; z->r = z; + head = new node(itemMIN, 0, black, 0, z); + } + + +-------------------------------- +CHAPTER 16 Hashing + +unsigned stringkey::hash(int M) + { + int h; char *t = v; + for (h = 0; *t; t++) + h = (64*h + *t) % M; + return h; + } + +Dict::Dict(int sz) + { + M = sz; + z = new node; z->next = z; z->info = infoNIL; + heads = new node*[M]; + for (int i = 0; i < M; i++) + { heads[i] = new node; heads[i]->next = z; } + } + +class Dict + { + private: + struct node + { itemType key; infoType info; + node() { key = " "; info = infoNIL; } + }; + struct node *a; + int M; + public: + Dict(int sz) + { M = sz; a = new node[M]; } + int search(itemType v); + void insert(itemType v, infoType info) + { + int x = v.hash(M); + while (a[x].info != infoNIL) x = (x+1) % M; + a[x].key = v; a[x].info = info; + } + }; + + +-------------------------------- +CHAPTER 17 Radix Searching + +infoType Dict::search(itemType v) // Digital tree + { + struct node *x = head; + int b = itemType::maxb; + z->key = v; + while (v != x->key) + x = (v.bits(b--, 1)) ? x->r : x->l; + return x->info; + } + +void Dict::insert(itemType v, infoType info) + { + struct node *p, *x = head; + int b = itemType::maxb; + while (x != z) + { + p = x; + x = (v.bits(b--, 1)) ? x->r : x->l; + } + x = new node; + x->key = v; x->info = info; x->l = z; x->r = z; + if (v.bits(b+1, 1)) p->r = x; else p->l = x; + } + +infoType Dict::search(itemType v) // Patricia tree + { + struct node *p, *x; + p = head; x = head->l; + while (p->b > x->b) + { + p = x; + x = (bits(v, x->b, 1)) ? x->r : x->l; + } + if (v != x->key) return infoNIL; + return x->info; + } + +void Dict::insert(itemType v, infoType info) + { + struct node *p, *t, *x; + int i = maxb; + p = head; t = head->l; + while (p->b > t->b) + { p = t; t = (bits(v, t->b, 1)) ? t->r : t->l; } + if (v == t->key) return; + while (bits(t->key, i, 1) == bits(v, i, 1)) i--; + p = head; x = head->l; + while (p->b > x->b && x->b > i) + { p = x; x = (bits(v, x->b, 1)) ? x->r : x->l; } + t = new node; + t->key = v; t->info = info; t->b = i; + t->l = (bits(v, t->b, 1)) ? x : t; + t->r = (bits(v, t->b, 1)) ? t : x; + if (bits(v, p->b, 1)) p->r = t; else p->l = t; + } + + +-------------------------------- +CHAPTER 18 External Searching + + +-------------------------------- +CHAPTER 19 String Searching + +int brutesearch(char *p, char *a) + { + int i, j, M = strlen(p), N = strlen(a); + for (i = 0, j = 0; j < M && i < N; i++, j++) + if (a[i] != p[j]) { i -= j-1; j = -1; } + if (j == M) return i-M; else return i; + } + +int kmpsearch(char *p, char *a) + { + int i, j, M = strlen(p), N = strlen(a); + initnext(p); + for (i = 0, j = 0; j < M && i < N; i++, j++) + while ((j >= 0) && (a[i] != p[j])) j = next[j]; + if (j == M) return i-M; else return i; + } + +initnext(char *p) + { + int i, j, M = strlen(p); + next[0] = -1; + for (i = 0, j = -1; i < M; i++, j++, next[i] = j) + while ((j >= 0) && (p[i] != p[j])) j = next[j]; + } + +int kmpsearch(char *a) + { + int i = -1; +sm: i++; +s0: if (a[i] != '1') goto sm; i++; +s1: if (a[i] != '0') goto s0; i++; +s2: if (a[i] != '1') goto s0; i++; +s3: if (a[i] != '0') goto s1; i++; +s4: if (a[i] != '0') goto s2; i++; +s5: if (a[i] != '1') goto s0; i++; +s6: if (a[i] != '1') goto s1; i++; +s7: if (a[i] != '1') goto s1; i++; + return i-8; + } + +next[i] = (p[i] == p[j]) ? next[j] : j + +int mischarsearch(char *p, char *a) + { + int i, j, t, M = strlen(p), N = strlen(a); + initskip(p); + for (i = M-1, j = M-1; j > 0; i--, j--) + while (a[i] != p[j]) + { + t = skip[index(a[i])]; + i += (M-j > t) ? M-j : t; + if (i >= N) return N; + j = M-1; + } + return i; + } + +const int q = 33554393; +const int d = 32; +int rksearch(char *p, char *a) + { + int i, dM = 1, h1 = 0, h2 = 0; + int M = strlen(p), N = strlen(a); + for (i = 1; i < M; i++) dM = (d*dM) % q; + for (i = 0; i < M; i++) + { + h1 = (h1*d+index(p[i])) % q; + h2 = (h2*d+index(a[i])) % q; + } + for (i = 0; h1 != h2; i++) + { + h2 = (h2+d*q-index(a[i])*dM) % q; + h2 = (h2*d+index(a[i+M])) % q; + if (i > N-M) return N; + } + return i; + } + + +-------------------------------- +CHAPTER 20 Pattern Matching + +const int scan = -1; +int match(char *a) + { + int n1, n2; Deque dq(100); + int j = 0, N = strlen(a), state = next1[0]; + dq.put(scan); + while (state) + { + if (state == scan) { j++; dq.put(scan); } + else if (ch[state] == a[j]) + dq.put(next1[state]); + else if (ch[state] == ' ') + { + n1 = next1[state]; n2 = next2[state]; + dq.push(n1); if (n1 != n2) dq.push(n2); + } + if (dq.empty() || j==N) return 0; + state = dq.pop(); + } + return j; + } + + +-------------------------------- +CHAPTER 21 Parsing + +expression() + { + term(); + if (p[j] == '+') + { j++; expression(); } + } + +term() + { + factor(); + if ((p[j] == '(') || letter(p[j])) term(); + } + +factor() + { + if (p[j] == '(') + { + j++; expression(); + if (p[j] == ')') j++; else error(); + } + else if (letter(p[j])) j++; else error(); + if (p[j] == '*') j++; + } + +expression + term + factor + ( + expression + term + factor A * + term + factor B + + + expression + term + factor A + term + factor C + ) + term + factor D + +badexpression(); + { + if (letter(p[j])) j++; else + { + badexpression(); + if (p[j] == '+') { j++; term(); } + else error(); + } + } + + +int expression() + { + int t1,t2,r; + t1 = term(); r = t1; + if (p[j] == '+') + { + j++; state++; + t2 = state; r = t2; state++; + setstate(t2, ' ', expression(), t1); + setstate(t2-1, ' ', state, state); + } + return r; + } + +int term() + { + int t, r; + r = factor(); + if ((p[j] == '(') || letter(p[j])) t = term(); + return r; + } + +int factor() + { + int t1, t2, r; + t1 = state; + if (p[j] == '(') + { + j++; t2 = expression(); + if (p[j] == ')') j++; else error(); + } + else if (letter(p[j])) + { + setstate(state, p[j], state+1, state+1); + t2 = state; j++; state++; + } + else error(); + if (p[j] != '*') r = t2; else + { + setstate(state, ' ', state+1, t2); + r = state; next1[t1-1] = state; + j++; state++; + } + return r; + } + +void matchall(char *a) + { + j = 0; state = 1; + next1[0] = expression(); + setstate(0, ' ', next1[0], next1[0]); + setstate(state, ' ', 0, 0); + while (*a) cout << match(a++) << ' '; + cout << '\n'; + } + + +-------------------------------- +CHAPTER 22 File Compression + + for (i = 0; i <= 26; i++) count[i] = 0; + for (i = 0; i < M; i++) count[index(a[i])]++; + + for (i = 0; i <= 26; i++) + if (count[i]) pq.insert(count[i], i); + for ( ; !pq.empty(); i++) + { + t1 = pq.remove(); t2 = pq.remove(); + dad[i] = 0; dad[t1] = i; dad[t2] = -i; + count[i] = count[t1] + count[t2]; + if (!pq.empty()) pq.insert(count[i], i); + } + +for (k = 0; k <= 26; k++) + { + i = 0; x = 0; j = 1; + if (count[k]) + for (t=dad[k]; t; t=dad[t], j+=j, i++) + if (t < 0) { x += j; t = -t; } + code[k] = x; len[k] = i; + } + +for (j = 0; j < M; j++) + for (i = len[index(a[j])]; i > 0; i--) + cout << ((code[index(a[j])] >> i-1) & 1); + + +-------------------------------- +CHAPTER 23 Cryptology + + +-------------------------------- +CHAPTER 24 Elementary Geometric Methods + +struct point { int x, y; char c; }; +struct line { struct point p1, p2; }; +struct point polygon[Nmax]; + +int ccw(struct point p0, + struct point p1, + struct point p2 ) + { + int dx1, dx2, dy1, dy2; + dx1 = p1.x - p0.x; dy1 = p1.y - p0.y; + dx2 = p2.x - p0.x; dy2 = p2.y - p0.y; + if (dx1*dy2 > dy1*dx2) return +1; + if (dx1*dy2 < dy1*dx2) return -1; + if ((dx1*dx2 < 0) || (dy1*dy2 < 0)) return -1; + if ((dx1*dx1+dy1*dy1) < (dx2*dx2+dy2*dy2)) + return +1; + return 0; + } + +int intersect(struct line l1, struct line l2) + { + return ((ccw(l1.p1, l1.p2, l2.p1) + *ccw(l1.p1, l1.p2, l2.p2)) <= 0) + && ((ccw(l2.p1, l2.p2, l1.p1) + *ccw(l2.p1, l2.p2, l1.p2)) <= 0); + } + +float theta(struct point p1, struct point p2) + { + int dx, dy, ax, ay; + float t; + dx = p2.x - p1.x; ax = abs(dx); + dy = p2.y - p1.y; ay = abs(dy); + t = (ax+ay == 0) ? 0 : (float) dy/(ax+ay); + if (dx < 0) t = 2-t; else if (dy < 0) t = 4+t; + return t*90.0; + } + +int inside(struct point t, struct point p[], int N) + { + int i, count = 0, j = 0; + struct line lt,lp; + p[0] = p[N]; p[N+1] = p[1]; + lt.p1 = t; lt.p2 = t; lt.p2.x = INT_MAX; + for (i = 1; i <= N; i++) + { + lp.p1= p[i]; lp.p2 = p[i]; + if (!intersect(lp,lt)) + { + lp.p2 = p[j]; j = i; + if (intersect(lp,lt)) count++; + } + } + return count & 1; + } + + +-------------------------------- +CHAPTER 25 Finding the Convex Hull + +int wrap(point p[], int N) + { + int i, min, M; + float th, v; + for (min = 0, i = 1; i < N; i++) + if (p[i].y < p[min].y) min = i; + p[N] = p[min]; th = 0.0; + for (M = 0; M < N; M++) + { + swap(p, M, min); + min = N; v = th; th = 360.0; + for (i = M+1; i <= N; i++) + if (theta(p[M], p[i]) > v) + if (theta(p[M], p[i]) < th) + { min = i; th = theta(p[M], p[min]); } + if (min == N) return M; + } + } + +int grahamscan(point p[], int N) + { + int i, min, M; + for (min = 1, i = 2; i <= N; i++) + if (p[i].y < p[min].y) min = i; + for (i = 1; i <= N; i++) + if (p[i].y == p[min].y) + if (p[i].x > p[min].x) min = i; + swap(p, 1, min); + shellsort(p, N); + p[0] = p[N]; + for (M = 3, i = 4; i <= N; i++) + { + while (ccw(p[M], p[M-1], p[i]) >= 0) M--; + M++; swap(p, i, M); + } + return M; + } + + +-------------------------------- +CHAPTER 26 Range Searching + +int range(int v1, int v2) + { return ranger(head->r, v1, v2); } +int ranger(struct node *t, int v1, int v2) + { + int tx1, tx2, count = 0; + if (t == z) return 0; + tx1 = (t->key >= v1); + tx2 = (t->key <= v2); + if (tx1) count += ranger(t->l, v1, v2); + if (tx1 && tx2) count++; + if (tx2) count += ranger(t->r, v1, v2); + return count; + } + +class Range + { + private: + struct node + { struct point p; struct node *next; }; + struct node *grid[maxG][maxG]; + struct node *z; + public: + Range(); + void insert(struct point p); + int search(rect range); + }; +Range::Range() + { + int i, j; + z = new node; + for (i = 0; i <= maxG; i++) + for (j = 0; j <= maxG; j++) + grid[i][j] = z; + } +void Range::insert(struct point p) + { + struct node *t = new node; + t->p = p; t->next = grid[p.x/size][p.y/size]; + grid[p.x/size][p.y/size] = t; + } + +int Range::search(struct rect range) // Grid method + { + struct node *t; + int i, j, count = 0; + for (i = range.x1/size; i <= range.x2/size; i++) + for (j = range.y1/size; j <= range.y2/size; j++) + for (t = grid[i][j]; t != z; t = t->next) + if (insiderect(t->p, range)) count++; + return count; + } + +class Range + { + private: + struct node + { struct point p; struct node *l, *r; }; + struct node *z, *head; + struct point dummy; + int searchr(struct node *t, + struct rect range, int d); + public: + Range(); + void insert(struct point p); + int search(rect range); + }; + +void Range::insert(struct point p) // 2D tree + { + struct node *f, *t; int d, td; + for (d = 0, t = head; t != z; d !=d) + { + td = d ? (p.x < t->p.x) : (p.y < t->p.y); + f = t; t = td ? t->l : t->r; + } + t = new node; t->p = p; t->l = z; t->r = z; + if (td) f->l = t; else f->r = t; + } + +int Range::search(struct rect range) // 2D tree + { return searchr(head->r, range, 1); } +int Range::searchr(struct node *t, + struct rect range, int d) + { + int t1, t2, tx1, tx2, ty1, ty2, count = 0; + if (t == z) return 0; + tx1 = range.x1 < t->p.x; tx2 = t->p.x <= range.x2; + ty1 = range.y1 < t->p.y; ty2 = t->p.y <= range.y2; + t1 = d ? tx1 : ty1; t2 = d ? tx2 : ty2; + if (t1) count += searchr(t->l, range, !d); + if (insiderect(t->p, range)) count++; + if (t2) count += searchr(t->r, range, !d); + return count; + } + + +-------------------------------- +CHAPTER 27 Geometric Intersection + +Dict Xtree(Nmax), Ytree(Nmax); +struct line lines[Nmax]; +int count = 0; +int intersections() + { + int x1, y1, x2, y2, N; + for (N = 1; cin >> x1 >> y1 >> x2 >> y2; N++) + { + lines[N].p1.x = x1; lines[N].p1.y = y1; + lines[N].p2.x = x2; lines[N].p2.y = y2; + Ytree.insert(y1, N); + if (y2 != y1) Ytree.insert(y2, N); + } + Ytree.traverse(); + return count; + } + +void Dict::visit(itemType v, infoType info) + { + int t, x1, x2, y1, y2; + x1 = lines[info].p1.x; y1 = lines[info].p1.y; + x2 = lines[info].p2.x; y2 = lines[info].p2.y; + if (x2 < x1) { t = x2; x2 = x1; x1 = t; } + if (y2 < y1) { t = y2; y2 = y1; y1 = t; } + if (v == y1) + Xtree.insert(x1, info); + if (v == y2) + { + Xtree.remove(x1, info); + count += Xtree.range(x1, x2); + } + } + + +-------------------------------- +CHAPTER 28 Closest-Point Problems + +int comp(struct node *t) + { return (pass == 1) ? t->p.x : t->p.y; } +struct node *merge(struct node *a, struct node *b) + { + struct node *c; + c = z; + do + if (comp(a) < comp(b)) + { c->next = a; c = a; a = a->next; } + else + { c->next = b; c = b; b = b->next; } + while (c != z); + c = z->next; z->next = z; + return c; + } + +check(struct point p1, struct point p2) + { + float dist; + if ((p1.y != z->p.y) && (p2.y != z->p.y)) + { + dist = sqrt((p1.x-p2.x)*(p1.x-p2.x) + +(p1.y-p2.y)*(p1.y-p2.y)); + if (dist < min) + { min = dist; cp1 = p1; cp2 = p2; }; + } + } + +struct node *sort(struct node *c, int N) + { + int i; + struct node *a, *b; + float middle; + struct point p1, p2, p3, p4; + if (c->next == z) return c; + a = c; + for (i = 2; i <= N/2; i++) c = c->next; + b = c->next; c->next = z; + if (pass == 2) middle = b->p.x; + c = merge(sort(a, N/2), sort(b, N-(N/2))); + if (pass == 2) + { + p1 = z->p; p2 = z->p; p3 = z->p; p4 = z->p; + for (a = c; a != z; a = a->next) + if (fabs(a->p.x - middle) < min) + { + check(a->p, p1); + check(a->p, p2); + check(a->p, p3); + check(a->p, p4); + p1 = p2; p2 = p3; p3 = p4; p4 = a->p; + } + } + return c; + } + +z = new node; z->p.x = max; + z->p.y = max; z->next = z; +h = new node; h->next = readlist(); +min = max; +pass = 1; h->next = sort(h->next, N); +pass = 2; h->next = sort(h->next, N); + + +-------------------------------- +CHAPTER 29 Elementary Graph Algorithms + +int V, E; +int a[maxV][maxV]; + +void adjmatrix() + { + int j, x, y; + cin >> V >> E; + for (x = 1; x <= V; x++) + for (y = 1; y <= V; y++) a[x][y] = 0; + for (x = 1; x <= V; x++) a[x][x] = 1; + for (j = 1; j <= E; j++) + { + cin >> v1 >> v2; + x = index(v1); y = index(v2); + a[x][y] = 1; a[y][x] = 1; + } + } + +struct node + { int v; struct node *next; }; +int V, E; +struct node *adj[maxV], *z; + +void adjlist() + { + int j, x, y; struct node *t; + cin >> V >> E; + z = new node; z->next = z; + for (j = 1; j <= V; j++) adj[j] = z; + for (j = 1; j <= E; j++) + { + cin >> v1 >> v2; + x = index(v1); y = index(v2); + t = new node; + t->v = x; t->next = adj[y]; adj[y] = t; + t = new node; + t->v = y; t->next = adj[x]; adj[x] = t; + } + } + +void search() + { + int k; + for (k = 1; k <= V; k++) val[k] = unseen; + for (k = 1; k <= V; k++) + if (val[k] == unseen) visit(k); + } + +void visit(int k) // DFS, adjacency lists + { + struct node *t; + val[k] = ++id; + for (t = adj[k]; t != z; t = t->next) + if (val[t->v] == unseen) visit(t->v); + } + +void visit(int k) // DFS, adjacency matrix + { + int t; + val[k] = ++id; + for (t = 1; t <= V; t++) + if (a[k][t] != 0) + if (val[t] == unseen) visit(t); + } + +Stack stack(maxV); +void visit(int k) // non-recursive DFS, adj lists + { + struct node *t; + stack.push(k); + while (!stack.empty()) + { + k = stack.pop(); val[k] = ++id; + for (t = adj[k]; t != z; t = t->next) + if (val[t->v] == unseen) + { stack.push(t->v); val[t->v] = -1; } + } + } + +Queue queue(maxV); +void visit(int k) // BFS, adjacency lists + { + struct node *t; + queue.put(k); + while (!queue.empty()) + { + k = queue.get(); val[k] = ++id; + for (t = adj[k]; t != z; t = t->next) + if (val[t->v] == unseen) + { queue.put(t->v); val[t->v] = -1; } + } + } + + +-------------------------------- +CHAPTER 30 Connectivity + +int visit(int k) // DFS to find articulation points + { + struct node *t; + int m, min; + val[k] = ++id; + min = id; + for (t = adj[k]; t != z; t = t->next) + if (val[t->v] == unseen) + { + m = visit(t->v); + if (m < min) min = m; + if (m >= val[k]) cout << name(k); + } + else if (val[t->v] < min) min = val[t->v]; + return min; + } + +class EQ + { + private: + int *dad; + public: + EQ(int size); + int find(int x, int y, int doit); + }; + +int EQ::find(int x, int y, int doit) + { + int i = x, j = y; + while (dad[i] > 0) i = dad[i]; + while (dad[j] > 0) j = dad[j]; + if (doit && (i != j)) dad[j] = i; + return (i != j); + } + +int EQ::find(int x, int y, int doit) + { + int t, i = x, j = y; + while (dad[i] > 0) i = dad[i]; + while (dad[j] > 0) j = dad[j]; + while (dad[x] > 0) + { t = x; x = dad[x]; dad[t] = i; } + while (dad[y] > 0) + { t = y; y = dad[y]; dad[t] = j; } + if (doit && (i != j)) + if (dad[j] < dad[i]) + { dad[j] += dad[i] - 1; dad[i] = j; } + else + { dad[i] += dad[j] - 1; dad[j] = i; } + return (i != j); + } + + +-------------------------------- +CHAPTER 31 Weighted Graphs + +PQ pq(maxV); +visit(int k) // PFS, adjacency lists + { + struct node *t; + if (pq.update(k, -unseen) != 0) dad[k] = 0; + while (!pq.empty()) + { + id++; k = pq.remove(); val[k] = -val[k]; + if (val[k] == -unseen) val[k] = 0; + for (t = adj[k]; t != z; t = t->next) + if (val[t->v] < 0) + if (pq.update(t->v, priority)) + { + val[t->v] = -(priority); + dad[t->v] = k; + } + } + } + + +void kruskal() + { + int i, m, V, E; + struct edge + { char v1, v2; int w; }; + struct edge e[maxE]; + PQ pq(maxE); EQ eq(maxE); + cin >> V >> E; + for (i = 1; i <= E; i++) + cin >> e[i].v1 >> e[i].v2 >> e[i].w; + for (i = 1; i <= E; i++) + pq.insert(i, e[i].w); + for (i = 0; i < V-1; ) + { + if (pq.empty()) break; else m = pq.remove(); + if (eq.find(index(e[m].v1),index(e[m].v2),1)) + { cout << e[m].v1 << e[m].v2 << ' '; i++; }; + } + } + +void search() // PFS, adjacency matrix + { + int k, t, min = 0; + for (k = 1; k <= V; k++) + { val[k] = unseen; dad[k] = 0; } + val[0] = unseen-1; + for (k = 1; k != 0; k = min, min = 0) + { + val[k] = -val[k]; + if (val[k] == -unseen) val[k] = 0; + for (t = 1; t <= V; t++) + if (val[t] < 0) + { + if (a[k][t] && (val[t] < -priority)) + { val[t] = -priority; dad[t] = k; } + if (val[t] > val[min]) min = t; + } + } + } + + +-------------------------------- +CHAPTER 32 Directed Graphs + +for (k = 1; k <= V; k++) + { + id = 0; + for (j = 1; j <= V; j++) val[j] = 0; + visit(k); + cout >> '\n'; + } + +for (y = 1; y <= V; y++) + for (x = 1; x <= V; x++) + if (a[x][y]) + for (j = 1; j <= V; j++) + if (a[y][j]) a[x][j] = 1; + +for (y = 1; y <= V; y++) + for (x = 1; x <= V; x++) + if (a[x][y]) + for (j = 1; j <= V; j++) + if (a[y][j] > 0) + if (!a[x][j] || (a[x][y]+a[y][j] < a[x][j])) + a[x][j] = a[x][y] + a[y][j]; + +Stack stack(maxV); +int visit(int k) // DFS to find strong components + { + struct node *t; int m, min; + val[k] = ++id; min = id; + stack.push(k); + for (t = adj[k]; t != z; t = t->next) + { + m = (!val[t->v]) ? visit(t->v) : val[t->v]; + if (m < min) min = m; + } + if (min == val[k]) + { + do + { + m = stack.pop(); cout << m; + val[m] = V+1; + } + while (m != k); + cout << '\n'; + } + return min; + } + + +-------------------------------- +CHAPTER 33 Network Flow + + priority = -flow[k][t]; + if (size[k][t] > 0) priority += size[k][t]; + if (priority > val[k]) priority = val[k]; + +for (;;) + { + if (!search(1,V)) break; + y = V; x = dad[V]; + while (x != 0) + { + flow[x][y] = flow[x][y]+val[V]; + flow[y][x] = -flow[x][y]; + y = x; x = dad[y]; + } + } + + +-------------------------------- +CHAPTER 34 Matching + +for (m = 1; m <= N; m++) + { + for (s = m; s != 0;) + { + next[s]++; w = prefer[s][next[s]]; + if (rank[w][s] < rank[w][fiancee[w]]) + { t = fiancee[w]; fiancee[w] = s; s = t; } + } + } + + +-------------------------------- +CHAPTER 35 Random Numbers + +a[0] = seed; +for (i = 1; i <= N; i++) + a[i] = (a[i-1]*b+1) % m; + +#include +const int m = 100000000; +const int m1 = 10000; +int mult(int p, int q) + { + int p1, p0, q1, q0; + p1 = p/m1; p0 = p%m1; + q1 = q/m1; q0 = q%m1; + return (((p0*q1+p1*q0) % m1)*m1+p0*q0) % m; + } +class Random + { + private: + int a; + public: + Random(int seed) + { a = seed; } + int next() + { const int b = 31415821; + a = (mult(a, b) + 1) % m; + return a; + } + }; +main() + { + int i, N; Random x(1234567); + cin >> N; + for (i = 1; i <= N; i++) + cout << x.next() << ' '; + cout << '\n'; + } + + + int badnext(int r) + { const int b = 31415821; + a = (mult(a, b) + 1) % m; + return a % r; + } + + int next(int r) + { const int b = 31415821; + a = (mult(a, b) + 1) % m; + return ((a/m1)*r)/m1; + } + +class Random + { + private: + int a[55], j; + public: + Random(int seed); + int next(int r) + { + j = (j+1) % 55; + a[j] = (a[(j+23) % 55]+a[(j+54) % 55]) % m; + return ((a[j]/m1)*r)/m1; + } + }; + +Random:: Random(int seed) + { const int b = 31415821; + a[0] = seed; + for (j = 1; j <= 54; j++) + a[j] = (mult(a[j-1], b) + 1) % m; + } + +float chisquare(int N, int r) + { + int i, t, f[rmax]; Random x(1234567); + for (i = 0; i < r; i++) f[i] = 0; + for (i = 0; i < N; i++) f[x.next(r)]++; + for (i = 0, t = 0; i < r; i++) t += f[i]*f[i]; + return (float) ((r*t/N) - N); + } + + +-------------------------------- +CHAPTER 36 Arithmetic + +for (i = 0; i < N; i++) r[i] = p[i]+q[i]; + +for (i = 0; i < 2*N-1; i++) r[i] = 0; +for (i = 0; i < N; i++) + for (j = 0; j < N; j++) + r[i+j] += p[i]*q[j]; + +struct node *add(struct node *p, struct node *q) + { + struct node *t; + t = z; z->c = 0; + while ((p != z) && (q != z)) + { + t->next = new node; + t = t->next; t->c = p->c + q->c; + p = p->next; q = q->next; + } + t->next = z; t = z->next; z->next = z; + return t; + } + +struct node + { int c; int j; struct node *next; }; + +struct node *insert(struct node *t, int c, int j) + { + t->next = new node; + t = t->next; t->c = c; t->j = j; + return t; + } + +struct node *add(struct node *p, struct node *q) + { + struct node *t; + t = z; z->c = 0; z->j = maxN; + while ((p !=z) || (q != z)) + { + if ((p->j == q->j) && ((p->c + q->c) != 0)) + { + t = insert(t, p->c+q->c, p->j); + p = p->next; q = q->next; + } + else if (p->j < q->j) + { t = insert(t, p->c, p->j); p = p->next; } + else if (q->j < p->j) + { t = insert(t, q->c, q->j); q = q->next; } + } + t->next = z; t = z->next; z->next = z; + return t; + } + +y = p[N]; +for (i = N-1; i >= 0; i--) y = x*y + p[i]; + +float *mult(float p[], float q[], int N) + { + float pl[N/2], ql[N/2], ph[N/2], qh[N/2], + t1[N/2], t2[N/2]; + float r[2*N-2], rl[N], rm[N], rh[N]; + int i, N2; + if (N == 1) + { r[0] = p[0]*q[0]; return (float *) r; } + for (i = 0; i < N/2; i++) + { pl[i] = p[i]; ql[i] = q[i]; } + for (i = N/2; i < N; i++) + { ph[i-N/2] = p[i]; qh[i-N/2] = q[i]; } + for (i = 0; i < N/2; i++) t1[i] = pl[i]+ph[i]; + for (i = 0; i < N/2; i++) t2[i] = ql[i]+qh[i]; + rm = mult(t1, t2, N/2); + rl = mult(pl, ql, N/2); + rh = mult(ph, qh, N/2); + for (i = 0; i < N-1; i++) r[i] = rl[i]; + r[N-1] = 0; + for (i = 0; i < N-1; i++) r[N+i] = rh[i]; + for (i = 0; i < N-1; i++) + r[N/2+i] += rm[i] - (rl[i]+rh[i]); + return (float *) r; + } + + for (i = 0; i < N; i++) + for (j = 0; j < N; j++) + for (k = 0, r[i][j] = 0; k < N; k++) + r[i][j] += p[i][k]*q[k][j]; + + +-------------------------------- +CHAPTER 37 Gaussian Elimination + +for (i = 1; i <= N; i++) + for (j = i+1; j <= N; j++) + for (k = N+1; k >= i; k--) + a[j][k] -= a[i][k]*a[j][i]/a[i][i]; + +eliminate() + { + int i, j, k, max; + float t; + for (i = 1; i <= N; i++) + { + max = i; + for (j = i+1; j <= N; j++) + if (abs(a[j][i]) > abs(a[max][i])) max = j; + for (k = i; k <= N+1; k++) + { t = a[i][k]; + a[i][k] = a[max][k]; + a[max][k] = t; } + for (j = i+1; j <= N; j++) + for (k = N+1; k >= i; k--) + a[j][k] -= a[i][k]*a[j][i]/a[i][i]; + } + } + +substitute() + { + int j, k; + float t; + for (j = N; j >= 1; j--) + { + t = 0.0; + for (k = j+1; k <= N; k++) t += a[j][k]*x[k]; + x[j] = (a[j][N+1]-t)/a[j][j]; + } + } + + for (i = 1; i < N; i++) + { + a[i+1][N+1] -= a[i][N+1]*a[i+1][i]/a[i][i]; + a[i+1][i+1] -= a[i][i+1]*a[i+1][i]/a[i][i]; + } + for (j = N; j >= 1; j--) + x[j] = (a[j][N+1]-a[j][j+1]*x[j+1])/a[j][j]; + + +-------------------------------- +CHAPTER 38 Curve Fitting + +makespline(float x[], float y[], int N) + { + for (i = 2; i < N; i++) d[i] = 2*(x[i+1]-x[i-1]); + for (i = 1; i < N; i++) u[i] = x[i+1]-x[i]; + for (i = 2; i < N; i++) + w[i] = 6.0*((y[i+1]-y[i])/u[i] + -(y[i]-y[i-1])/u[i-1]); + p[1] = 0.0; p[N] = 0.0; + for (i = 2; i < N-1; i++) + { + w[i+1] = w[i+1] - w[i]*u[i]/d[i]; + d[i+1] = d[i+1] - u[i]*u[i]/d[i]; + } + for (i = N-1; i > 1; i--) + p[i] = (w[i]-u[i]*p[i+1])/d[i]; + } + +float f(float x) + { return x*x*x - x; } +float eval(float v) + { + float t; int i = 1; + while (v > x[i+1]) i++; + t = (v-x[i])/u[i]; + return t*y[i+1]+(1-t)*y[i] + + u[i]*u[i]*(f(t)*p[i+1]+f(1-t)*p[i])/6.0; + } + +for (i = 1; i <= M; i++) + for (j = 1; j <= M+1; j++) + { + t = 0.0; + for (k = 1; k <= N; k++) + t += f[i][k]*f[j][k]; + a[i][j] = t; + } + + +-------------------------------- +CHAPTER 39 Integration + +for (i = N; i > 0; i--) p[i] = p[i-1]/i; p[0] = 0; + +double intrect(double a, double b, int N) + { + int i; double r = 0; double w = (b-a)/N; + for (i = 1; i <= N; i++) r += w*f(a-w/2+i*w); + return r; + } + +double inttrap(double a, double b, int N) + { + int i; double t = 0; double w = (b-a)/N; + for (i = 1; i <= N; i++) + t += w*(f(a+(i-1)*w)+f(a+i*w))/2; + return t; + } + +double intsimp(double a, double b, int N) + { + int i; double s = 0; double w = (b-a)/N; + for (i = 1; i <= N; i++) + s += w*(f(a+(i-1)*w) + + 4*f(a-w/2+i*w) + + f(a+i*w))/6; + return s; + } + +double adapt(double a, double b) + { + double x = intsimp(a, b, 10); + if (fabs(x - intsimp(a, b, 5)) > tolerance) + return adapt(a, (a+b)/2) + adapt((a+b)/2, b); + return x; + } + + +-------------------------------- +CHAPTER 40 Parallel Algorithms + + +-------------------------------- +CHAPTER 41 The Fast Fourier Transform + +eval(p, outN, 0); +eval(q, outN, 0); +for (i = 0; i <= outN; i++) r[i] = p[i]*q[i]; +eval(r, outN, 0); +for (i = 1; i <= N; i++) + { t = r[i]; r[i] = r[outN+1-i]; r[outN+1-i] = t; } +for (i = 0; i <= outN; i++) r[i] = r[i]/(outN+1); + +eval(complex p[], int N, int k) + { + int i, j; + if (N == 1) + { + p0 = p[k]; p1 = p[k+1]; + p[k] = p0+p1; p[k+1] = p0-p1; + } + else + { + for (i = 0; i <= N/2; i++) + { + j = k+2*i; + t[i] = p[j]; t[i+1+N/2] = p[j+1]; + } + for (i = 0; i <= N; i++) p[k+i] = t[i]; + eval(p, N/2, k); + eval(p, N/2, (k+1+N)/2); + j = (outN+1)/(N+1); + for (i = 0; i <= N/2; i++) + { + p0 = w[i*j]*p[k+(N/2)+1+i]; + t[i] = p[k+i]+p0; + t[i+(N/2)+1] = p[k+i]-p0; + } + for (i = 0; i <= N; i++) p[k+i] = t[i]; + } + } + + +-------------------------------- +CHAPTER 42 Dynamic Programming + +for (j = 1; j <= N; j++) + { + for (i = 1; i <= M; i++) + if (i >= size[j]) + if (cost[i] < cost[i-size[j]]+val[j]) + { + cost[i] = cost[i-size[j]]+val[j]; + best[i] = j; + } + } + +for (i = 1; i <= N; i++) + for (j = i+1; j <= N; j++) cost[i][j] = INT_MAX; +for (i = 1; i <= N; i++) cost[i][i] = 0; +for (j = 1; j < N; j++) + for (i = 1; i <= N-j; i++) + for (k = i+1; k <= i+j; k++) + { + t = cost[i][k-1]+cost[k][i+j] + +r[i]*r[k]*r[i+j+1]; + if (t < cost[i][i+j]) + { cost[i][i+j] = t; best[i][i+j] = k; } + } + +order(int i, int j) + { + if (i == j) cout >> name(i); else + { + cout >> '('; + order(i, best[i][j]-1); order(best[i][j], j); + cout >> ')'; + } + } + +for (i = 1; i <= N; i++) + for (j = i+1; j <= N+1; j++) cost[i][j] = INT_MAX; +for (i = 1; i <= N; i++) cost[i][i] = f[i]; +for (i = 1; i <= N+1; i++) cost[i][i-1] = 0; +for (j = 1; j <= N-1; j++) + for (i = 1; i <= N-j; i++) + { + for (k = i; k <= i+j; k++) + { + t = cost[i][k-1]+cost[k+1][i+j]; + if (t < cost[i][i+j]) + { cost[i][i+j] = t; best[i][i+j] = k; } + } + for (k = i; k <= i+j; cost[i][i+j] += f[k++]) ; + } + + +-------------------------------- +CHAPTER 43 Linear Programming + +pivot(int p, int q) + { + int j, k; + for (j = 0; j <= N; j++) + for (k = M+1; k >= 1; k--) + if (j!=p && k!=q) + a[j][k] = a[j][k]-a[p][k]*a[j][q]/a[p][q]; + for (j = 0; j <= N; j++) + if (j != p) a[j][q] = 0; + for (k = 1; k <= M+1; k++) + if (k != q) a[p][k] = a[p][k]/a[p][q]; + a[p][q] = 1; + } + +for (;;) + { + for (q = 0; (q<=M+1) && (a[0][q]>=0); q++) ; + for (p = 0; (p<=N+1) && (a[p][q]<=0); p++) ; + if (q>M || p>N) break; + for (i = p+1; i <= N; i++) + if (a[i][q] > 0) + if (a[i][M+1]/a[i][q] < a[p][M+1]/a[p][q]) + p = i; + pivot(p,q); + } + + +-------------------------------- +CHAPTER 44 Exhaustive Search + +visit(int k) + { + int t; + val[k] = ++id; + for (t = 1; t <= V; t++) + if (a[k][t]) + if (val[t] == 0) visit(t); + id--; val[k] = 0; + } + +visit(int k) + { + int t; + val[k] = ++id; + if (id == V) writeperm(); + for (t = 1; t <= V; t++) + if (val[t] == 0) visit(t); + id--; val[k] = 0; + } + + +-------------------------------- +CHAPTER 45 NP-Complete Problems + diff --git a/Selection..py b/Selection..py new file mode 100644 index 0000000..ae9438e --- /dev/null +++ b/Selection..py @@ -0,0 +1,24 @@ +# Selection sort in Python + + +def selectionSort(array, size): + + for step in range(size): + min_idx = step + + for i in range(step + 1, size): + + # to sort in descending order, change > to < in this line + # select the minimum element in each loop + if array[i] < array[min_idx]: + min_idx = i + + # put min at the correct position + (array[step], array[min_idx]) = (array[min_idx], array[step]) + + +data = [-2, 45, 0, 11, -9] +size = len(data) +selectionSort(data, size) +print('Sorted Array in Ascending Order:') +print(data) diff --git a/Shell-sort.cpp b/Shell-sort.cpp new file mode 100644 index 0000000..2f33202 --- /dev/null +++ b/Shell-sort.cpp @@ -0,0 +1,41 @@ +#include +using namespace std; + +int shellSort(int arr[], int n) +{ + for (int gap = n/2; gap > 0; gap /= 2) + { + for (int i = gap; i < n; i += 1) + { + int temp = arr[i]; + int j; + for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) + arr[j] = arr[j - gap]; + + arr[j] = temp; + } + } + return 0; +} + +void printArray(int arr[], int n) +{ + for (int i=0; i +using namespace std; +int lengthOfLongestSubstring(string s) { + unordered_map mp; + int i=0,j=0; + int maxm=0; + while(j>t; + cout<<"The length of longest substring is : "< +using namespace std; + +int main() +{ + string str[10], temp; + + cout << "Enter 10 words: " << endl; + for(int i = 0; i < 10; ++i) + { + getline(cin, str[i]); + } + + // Use Bubble Sort to arrange words + for (int i = 0; i < 9; ++i) { + for (int j = 0; j < 9 - i; ++j) { + if (str[j] > str[j + 1]) { + temp = str[j]; + str[j] = str[j + 1]; + str[j + 1] = temp; + } + } + } + + cout << "In lexicographical order: " << endl; + + for(int i = 0; i < 10; ++i) + { + cout << str[i] << endl; + } + return 0; +} diff --git a/SumWithoutMOD.java b/SumWithoutMOD.java new file mode 100644 index 0000000..bb71684 --- /dev/null +++ b/SumWithoutMOD.java @@ -0,0 +1,14 @@ +import java.util.*; +public class SumWithoutMOD{ + int summation(String s) + { + int sum=0; + for(int i=0;i + +Login form Design + +
+ +Login Here +
+

Username

+ +

Password

+ + +Lost your password?
+Don't have an account?
+
+
+ + + \ No newline at end of file diff --git a/binary_conversion.c b/binary_conversion.c new file mode 100644 index 0000000..e661efa --- /dev/null +++ b/binary_conversion.c @@ -0,0 +1,24 @@ +#include +#include +#include + +void main() +{ + int n,i=0,z,j; + scanf("%d",&n); + int *a = (int*)malloc(sizeof(int)); + + while(n>0) + { + z=n%2; + a[i]=z; + i++; + n/=2; + } + i--; + while(i>=0) + { + printf("%d",a[i]); + i--; + } +} \ No newline at end of file diff --git a/binary_conversions1.c b/binary_conversions1.c new file mode 100644 index 0000000..eb4c6a1 --- /dev/null +++ b/binary_conversions1.c @@ -0,0 +1,26 @@ +#include +#include +#include + +void main() +{ + int n,i=0,z,j; + scanf("%d",&n); + int *a = (int*)malloc(sizeof(int)); + + while(n>0) + { + z=n%2; + a[i]=z; + i++; + n/=2; + } + i--; + while(i>=0) + { + printf("%d",a[i]); + i--; + } +} +Footer +© 2022 GitHub, Inc. diff --git a/bintodecimal (2020_12_18 18_56_42 UTC).c b/bintodecimal (2020_12_18 18_56_42 UTC).c new file mode 100644 index 0000000..a692ec8 --- /dev/null +++ b/bintodecimal (2020_12_18 18_56_42 UTC).c @@ -0,0 +1,21 @@ +#include +#include +#include + +int main() +{ +long int a,b,x=0,i,n; +int d; +float e; +printf("enter binary number\n"); +scanf("%ld",&n); + +for (i=0;n!=0;++i) +{ + a=n%10; + x=a+(pow(2,i))+x; + n=n/10; +} +printf("%ld",x); + return 0; +} \ No newline at end of file diff --git a/breadthfirstsearch c++.txt b/breadthfirstsearch c++.txt new file mode 100644 index 0000000..b5f934f --- /dev/null +++ b/breadthfirstsearch c++.txt @@ -0,0 +1,88 @@ +// Program to print BFS traversal from a given +// source vertex. BFS(int s) traverses vertices +// reachable from s. +#include +using namespace std; + +// This class represents a directed graph using +// adjacency list representation +class Graph +{ + int V; // No. of vertices + + // Pointer to an array containing adjacency + // lists + vector> adj; +public: + Graph(int V); // Constructor + + // function to add an edge to graph + void addEdge(int v, int w); + + // prints BFS traversal from a given source s + void BFS(int s); +}; + +Graph::Graph(int V) +{ + this->V = V; + adj.resize(V); +} + +void Graph::addEdge(int v, int w) +{ + adj[v].push_back(w); // Add w to v’s list. +} + +void Graph::BFS(int s) +{ + // Mark all the vertices as not visited + vector visited; + visited.resize(V,false); + + // Create a queue for BFS + list queue; + + // Mark the current node as visited and enqueue it + visited[s] = true; + queue.push_back(s); + + while(!queue.empty()) + { + // Dequeue a vertex from queue and print it + s = queue.front(); + cout << s << " "; + queue.pop_front(); + + // Get all adjacent vertices of the dequeued + // vertex s. If a adjacent has not been visited, + // then mark it visited and enqueue it + for (auto adjecent: adj[s]) + { + if (!visited[adjecent]) + { + visited[adjecent] = true; + queue.push_back(adjecent); + } + } + } +} + +// Driver program to test methods of graph class +int main() +{ + // Create a graph given in the above diagram + Graph g(4); + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(2, 3); + g.addEdge(3, 3); + + cout << "Following is Breadth First Traversal " + << "(starting from vertex 2) \n"; + g.BFS(2); + + return 0; +} diff --git a/bst.cpp b/bst.cpp new file mode 100644 index 0000000..6bcb688 --- /dev/null +++ b/bst.cpp @@ -0,0 +1,57 @@ +#include +using namespace std; + +class Node { + public: + int data; + Node* left; + Node* right; + + // Val is the key or the value that + // has to be added to the data part + Node(int val) + { + data = val; + + // Left and right child for node + // will be initialized to null + left = NULL; + right = NULL; + } +}; + +int main() +{ + + /*create root*/ + Node* root = new Node(1); + /* following is the tree after above statement + + 1 + / \ + NULL NULL + */ + + root->left = new Node(2); + root->right = new Node(3); + /* 2 and 3 become left and right children of 1 + 1 + / \ + 2 3 + / \ / \ + NULL NULL NULL NULL + */ + + root->left->left = new Node(4); + /* 4 becomes left child of 2 + 1 + / \ + 2 3 + / \ / \ + 4 NULL NULL NULL + / \ + NULL NULL + */ + + return 0; +} \ No newline at end of file diff --git a/bubble_sort.py b/bubble_sort.py new file mode 100644 index 0000000..19c8763 --- /dev/null +++ b/bubble_sort.py @@ -0,0 +1,23 @@ +def bubblesort(arr): + n=len(arr) + swapped = False + for i in range (n-1): + + for j in range (0,n-i-1): + + if arr[j]>arr[j+1]: + swapped = True + temp=arr[j] + arr[j]=arr[j+1] + arr[j+1]=temp + + if not swapped: + return + + + +arr=[23,21,34,32,12,10,10] +bubblesort(arr) +print("Sorted array :") +for i in range(len(arr)): + print(arr[i],end=" ") \ No newline at end of file diff --git a/calculate number of nodes dfs method.txt b/calculate number of nodes dfs method.txt new file mode 100644 index 0000000..4d739b2 --- /dev/null +++ b/calculate number of nodes dfs method.txt @@ -0,0 +1,87 @@ +// C++ program for the above approach + +#include +using namespace std; + +// Function to return the count of nodes +// in the path from source to destination +int dfs(int src, int dest, int* vis, + vector* adj) +{ + + // Mark the node visited + vis[src] = 1; + + // If dest is reached + if (src == dest) { + return 1; + } + + // Traverse all adjacent nodes + for (int u : adj[src]) { + + // If not already visited + if (!vis[u]) { + + int temp = dfs(u, dest, vis, adj); + + // If there is path, then + // include the current node + if (temp != 0) { + + return temp + 1; + } + } + } + + // Return 0 if there is no path + // between src and dest through + // the current node + return 0; +} + +// Function to return the +// count of nodes between two +// given vertices of the acyclic Graph +int countNodes(int V, int E, int src, int dest, + int edges[][2]) +{ + // Initialize an adjacency list + vector adj[V + 1]; + + // Populate the edges in the list + for (int i = 0; i < E; i++) { + adj[edges[i][0]].push_back(edges[i][1]); + adj[edges[i][1]].push_back(edges[i][0]); + } + + // Mark all the nodes as not visited + int vis[V + 1] = { 0 }; + + // Count nodes in the path from src to dest + int count = dfs(src, dest, vis, adj); + + // Return the nodes between src and dest + return count - 2; +} + +// Driver Code +int main() +{ + // Given number of vertices and edges + int V = 8, E = 7; + + // Given source and destination vertices + int src = 5, dest = 2; + + // Given edges + int edges[][2] + = { { 1, 4 }, { 4, 5 }, + { 4, 2 }, { 2, 6 }, + { 6, 3 }, { 2, 7 }, + { 3, 8 } }; + + cout << countNodes(V, E, src, dest, edges); + + return 0; +} diff --git a/charisalphabet (2020_12_18 18_56_42 UTC).c b/charisalphabet (2020_12_18 18_56_42 UTC).c new file mode 100644 index 0000000..f627650 --- /dev/null +++ b/charisalphabet (2020_12_18 18_56_42 UTC).c @@ -0,0 +1,21 @@ +//char is alphabet or not +#include +int main() +{ + char c; + printf("enter a\n"); + scanf("%c", &c); + + // if (c >= 'a' && c <= 'z' || c >= 'A' && c <= "Z") + // { + // printf("CAHARCTER IS ALPHABET"); + // } + + // else + // { + // printf("NO CAHARCTER IS NOT AN ALPHABET"); + // } + (c >= 'a' && c <= 'z' || c >= 'A' && c <= "Z") ? printf("Character is Alphabet") : printf("NOT AN ALPHABET"); + + return 0; +} diff --git a/ck.c b/ck.c new file mode 100644 index 0000000..4b39d09 --- /dev/null +++ b/ck.c @@ -0,0 +1,21 @@ + + +#include + +int main () +{ + int a; + printf ("Enter number for which you want table = "); + scanf ("%d",&a); + printf (" %d x 1 = %d\n",a, a*1); + printf (" %d x 2 = %d\n",a, a*2); + printf (" %d x 3 = %d\n",a, a*3); + printf (" %d x 4 = %d\n",a, a*4); + printf (" %d x 5 = %d\n",a, a*5); + printf (" %d x 6 = %d\n",a, a*6); + printf (" %d x 7 = %d\n",a, a*7); + printf (" %d x 8 = %d\n",a, a*8); + printf (" %d x 9 = %d\n",a, a*9); + printf (" %d x 10 = %d\n",a, a*10); + return 0; +} diff --git a/count total number of occurances of element in the sorted array in java b/count total number of occurances of element in the sorted array in java new file mode 100644 index 0000000..06c0ff0 --- /dev/null +++ b/count total number of occurances of element in the sorted array in java @@ -0,0 +1,30 @@ +public int count(int[] arr, int target) { + int left = binarySearch(arr, target, true); + if (left < 0) return 0; + int right = binarySearch(arr, target, false); + return right - left + 1; +} + +private int binarySearch(int[] arr, int target, boolean leftmost) { + int lo = 0; + int hi = arr.length - 1; + int idx = -1; + while (lo <= hi) { + int mid = (lo + hi) >>> 1; // avoid overflow. same as (lo + hi) / 2 + + if (target > arr[mid]) { + lo = mid + 1; + } else if (target < arr[mid]) { + hi = mid - 1; + } else { + idx = mid; + if (leftmost) { + hi = mid - 1; + } else { + lo = mid + 1; + } + } + } + return idx; +} + diff --git a/counting_sort.cpp b/counting_sort.cpp new file mode 100644 index 0000000..28d219b --- /dev/null +++ b/counting_sort.cpp @@ -0,0 +1,43 @@ +#include +#include +using namespace std; + +void counting_sort(int a[],int n){ + //Largest Element + int largest = 0; + + for(int i=0;i freq(largest+1,0); + + //Update the freq array + for(int i=0;i0){ + a[j] = i; + freq[i]--; + j++; + } + } + return; +} + +int main(){ + + int arr[] = {88, 97, 10, 12, 15, 1, 5, 6, 12, 5, 8}; + int n = sizeof(arr) / sizeof(int); + counting_sort(arr, n); + + for (int i = 0; i < n; i++) { + cout << arr[i] << " "; + } + return 0; +} \ No newline at end of file diff --git a/countingsort.cpp b/countingsort.cpp new file mode 100644 index 0000000..5ac531e --- /dev/null +++ b/countingsort.cpp @@ -0,0 +1,56 @@ +#include +using namespace std; +void countsort(int a[],int n) +{ + int b[n];int max=a[0],min=a[0]; + for(int i=0;ia[i]) + min=a[i]; + } + int range=max-min+1; + int f[range]; + for(int i=0;i=0;i--) + { + int pos=f[a[i]-min]-1; + b[pos]=a[i]; + f[a[i]-min]--; + } + for(int i=0;i>n; + int a[n]; + for(int i=0;i>a[i]; + } + countsort(a,n); + + return 0; +} \ No newline at end of file diff --git a/dataManipulation.java b/dataManipulation.java new file mode 100644 index 0000000..efb481a --- /dev/null +++ b/dataManipulation.java @@ -0,0 +1,34 @@ +import java.util.Collections; +import java.util.ArrayList; + +class Main { + public static void main(String[] args) { + // Creating an ArrayList + ArrayList numbers = new ArrayList<>(); + numbers.add(1); + numbers.add(2); + System.out.println("ArrayList1: " + numbers); + + // Using reverse() + Collections.reverse(numbers); + System.out.println("Reversed ArrayList1: " + numbers); + + // Using swap() + Collections.swap(numbers, 0, 1); + System.out.println("ArrayList1 using swap(): " + numbers); + + ArrayList newNumbers = new ArrayList<>(); + + // Using addAll + newNumbers.addAll(numbers); + System.out.println("ArrayList2 using addAll(): " + newNumbers); + + // Using fill() + Collections.fill(numbers, 0); + System.out.println("ArrayList1 using fill(): " + numbers); + + // Using copy() + Collections.copy(newNumbers, numbers); + System.out.println("ArrayList2 using copy(): " + newNumbers); + } +} diff --git a/depthfirsstsearch c++.txt b/depthfirsstsearch c++.txt new file mode 100644 index 0000000..c00bec8 --- /dev/null +++ b/depthfirsstsearch c++.txt @@ -0,0 +1,62 @@ +// C++ program to print DFS traversal from +// a given vertex in a given graph +#include +using namespace std; + +// Graph class represents a directed graph +// using adjacency list representation +class Graph { +public: + map visited; + map > adj; + + // function to add an edge to graph + void addEdge(int v, int w); + + // DFS traversal of the vertices + // reachable from v + void DFS(int v); +}; + +void Graph::addEdge(int v, int w) +{ + adj[v].push_back(w); // Add w to v’s list. +} + +void Graph::DFS(int v) +{ + // Mark the current node as visited and + // print it + visited[v] = true; + cout << v << " "; + + // 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]) + DFS(*i); +} + +// Driver's code +int main() +{ + // Create a graph given in the above diagram + Graph g; + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(2, 3); + g.addEdge(3, 3); + + cout << "Following is Depth First Traversal" + " (starting from vertex 2) \n"; + + // Function call + g.DFS(2); + + return 0; +} + +// improved by Vishnudev C diff --git a/doubleLinkedList.cpp b/doubleLinkedList.cpp new file mode 100644 index 0000000..4d890a9 --- /dev/null +++ b/doubleLinkedList.cpp @@ -0,0 +1,136 @@ +#include +using namespace std; + +template +struct DoubleLinkedList{ + struct Node{ + T data; + Node *next; + Node *prev; + }; + + Node *n=NULL, *head=NULL, *tail=NULL, *x=NULL; + + void addNewNode(T i){ + n = new Node; + n->data = i; + n->prev = NULL; + head = n; + tail = n; + tail->next = NULL; + } + + void addNodeLast(T i){ + n = new Node; + n->data = i; + n->prev = tail; + tail->next = n; + tail = n; + tail->next = NULL; + } + + void addNodeFront(T i){ + n = new Node; + n->data = i; + n->next = head; + head->prev = n; + n->prev = NULL; + head = n; + } + + void addNodeMiddle(T i, T j){ + x = head; + while(x->data != j) x = x->next; + n = new Node; + n->data = i; + n->next = x->next; + x->next = n; + n->prev = x; + x = n->next; + x->prev = n; + } + + void addData(T i){ + if(head == NULL) + addNewNode(i); + else + addNodeLast(i); + } + + void readDataFront(){ + x = head; + while(x!=NULL){ + cout << x->data << " "; + x = x->next; + } + } + + void readDataLast(){ + x = tail; + while(x!=NULL){ + cout << x->data << " "; + x = x->prev; + } + } + + void deleteDataFront(){ + x = head; + head = head->next; + delete(x); + x = NULL; + head->prev = NULL; + } + + void deleteDataMiddle(T i){ + Node *temp = NULL; + x = head; + while(x->data != i){ + temp = x; + x = x->next; + } + temp->next = x->next; + temp = x->next; + temp->prev = x->prev; + delete(x); + x = NULL; + } + + void deleteDataLast(){ + x = tail; + tail = tail->prev; + delete(x); + x = NULL; + tail->next = NULL; + } + + + bool searchData(T i){ + x = head; + while(x!=NULL){ + if (i == x->data) return true; + x = x->next; + } + return false; + } + + void DeleteData(T i){ + if(!cariData(i)) return; + + if (i == head->data) + deleteDataFront(); + else if (i == tail->data) + deleteDataLast(); + else + deleteDataMiddle(i); + } +}; +int main(){ + DoubleLinkedList list; + list.addData("Hasan"); + list.addData("budi"); + list.addData("Taufiq"); + list.addData("Andi"); + list.readDataFront(); + cout << endl; + list.readDataLast(); +} diff --git a/factorial2.cpp b/factorial2.cpp new file mode 100644 index 0000000..17a4da1 --- /dev/null +++ b/factorial2.cpp @@ -0,0 +1,25 @@ +// Factorial of n = 1*2*3*...*n + +#include +using namespace std; + +int factorial(int); + +int main() { + int n, result; + + cout << "Enter a non-negative number: "; + cin >> n; + + result = factorial(n); + cout << "Factorial of " << n << " = " << result; + return 0; +} + +int factorial(int n) { + if (n > 1) { + return n * factorial(n - 1); + } else { + return 1; + } +} diff --git a/fds 2.ipynb b/fds 2.ipynb new file mode 100644 index 0000000..43dafa5 --- /dev/null +++ b/fds 2.ipynb @@ -0,0 +1,540 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "f8649652", + "metadata": {}, + "source": [ + "# functions/module in python" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "1d1a7c97", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "value of n=4\n", + "16.0\n" + ] + } + ], + "source": [ + "#write a function which finds square of a number\n", + "def fun(n):\n", + " return (n*n)\n", + "n=input(\"value of n=\")\n", + "n=float(n)\n", + "c=fun(n) #--> function call\n", + "print(c)" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "c58237ec", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "value of n=2\n", + "16.0\n" + ] + } + ], + "source": [ + "#nesting of function call\n", + "def fun(n):\n", + " return (n*n)\n", + "n=input(\"value of n=\")\n", + "n=float(n)\n", + "c=fun(fun(n)) #--> nesting of function call\n", + "print(c)" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "5737c287", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "4\n" + ] + } + ], + "source": [ + "#another way to the same problem\n", + "def fun(n):\n", + " print(n*n)\n", + "fun(2)" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "id": "42340b13", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "a=4\n", + "b=8\n", + "c=9\n", + "d=2\n", + "9\n" + ] + } + ], + "source": [ + "#write a function to find maximum number between four numbers\n", + "def max(x,y):\n", + " if x>y:\n", + " return(x)\n", + " else: \n", + " return(y)\n", + "a=input(\"a=\")\n", + "b=input(\"b=\")\n", + "c=input(\"c=\")\n", + "d=input(\"d=\")\n", + "\n", + "a=int(a)\n", + "b=int(b)\n", + "c=int(c)\n", + "d=int(d)\n", + "\n", + "m=max(a,b)\n", + "m=max(m,c)\n", + "m=max(m,d)\n", + "\n", + "print (m)\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "id": "db402092", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "welcome to python\n" + ] + } + ], + "source": [ + "#develop a function which prints welcome to python\n", + "def fun():\n", + " print(\"welcome to python\")\n", + "fun() " + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "id": "6fa968de", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "100\n" + ] + } + ], + "source": [ + "def f1(x):\n", + " x=x+1\n", + " print(x)\n", + "f1(99) " + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "id": "6a907c54", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[100, 20, 30, 40, 50]\n" + ] + } + ], + "source": [ + "def f2(x):\n", + " x[0]=100\n", + "\n", + "a=[10,20,30,40,50]\n", + "f2(a)\n", + "print(a)" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "829a1135", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "(10, 20, 30)\n" + ] + } + ], + "source": [ + "#variable number of parameters\n", + "def f3(*args):\n", + " print(args)\n", + "\n", + "f3(10,20,30) " + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "e19231e4", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "16\n" + ] + } + ], + "source": [ + "#lambda function\n", + "z=lambda x:x*x\n", + "print(z(4))" + ] + }, + { + "cell_type": "markdown", + "id": "feb0be9c", + "metadata": {}, + "source": [ + "whenever a function has another function as parameter ,it is known as higher order function,example-> filter(function,list), here function is a parameter" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "4859f994", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[10, 2, 8]\n" + ] + } + ], + "source": [ + "#application of lambda function -> they are used in higher order function\n", + "# write a function to separate even numbers from a given list of numbers\n", + "# a=[10,2,13,7,15,8]\n", + "\n", + "a=[10,2,13,7,15,8]\n", + "b=list(filter(lambda x:x%2==0,a)) #of form filter(fun,list)\n", + "print(b)" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "8848a3c5", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[13, 7, 15]\n" + ] + } + ], + "source": [ + "#for odd numbers\n", + "a=[10,2,13,7,15,8]\n", + "b=list(filter(lambda x:x%2!=0,a)) \n", + "print(b)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "3ccf89af", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[75, 66, 99, 100]\n" + ] + } + ], + "source": [ + "#given a list a,create a list b which contains all the numbers>50\n", + "a=[15,75,66,99,2,36,100]\n", + "b=list(filter(lambda x:x>=50,a))\n", + "print(b)" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "469887f6", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[75, 66, 99, 100]\n" + ] + } + ], + "source": [ + "#another way to do the same question\n", + "a=[15,75,66,99,2,36,100]\n", + "b=[]\n", + "for x in a:\n", + " if x>50:\n", + " b.append(x)\n", + "print(b) " + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "cb2ecaaf", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[100, 900, 4, 49, 64, 16]\n" + ] + } + ], + "source": [ + "# map function -> higher order function\n", + "# create a list using function which contains squares of all the\n", + "#numbers given a list\n", + "a=[10,30,2,7,8,4]\n", + "b=list(map(lambda x:x**2,a))\n", + "print(b)" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "558c0edd", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[11, 22, 33, 44, 55]\n" + ] + } + ], + "source": [ + "#given list a and b,create a c list which contains a+b\n", + "a=[1,2,3,4,5]\n", + "b=[10,20,30,40,50] #if there is less no. of elements,that no. is printed\n", + "c=list(map(lambda x,y:x+y,a,b))\n", + "print(c)" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "6f48b469", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 4, 9, 16, 25]\n" + ] + } + ], + "source": [ + "#we can use a named function instead of lambda\n", + "def square(x):\n", + " return x*x\n", + "a=[1,2,3,4,5]\n", + "b=list(map(square,a))\n", + "print(b)" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "61a635f9", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "60\n" + ] + } + ], + "source": [ + "# create a program to add many numbers ,using variable number of parameters\n", + "def sum(*args):\n", + " s=0\n", + " for x in args:\n", + " s=s+x\n", + " return s\n", + "print(sum(10,50))\n" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "6ba8470d", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "70\n" + ] + } + ], + "source": [ + "#using positional and variable number of parameters together\n", + "def sum(x,y,*args):\n", + " s=0\n", + " s=x+y\n", + " for e in args:\n", + " s=s+e\n", + " return s\n", + "print(sum(10,20,40))\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "0be12c73", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "10 20 (30, 40) 50 70 {'m': 60, 'n': 90}\n" + ] + } + ], + "source": [ + "def fun(x,y,*args,p,q,**kwargs): #**kwargs is used to print dict\n", + " print(x,y,args,p,q,kwargs)\n", + "fun(10,20,30,40,p=50,q=70,m=60,n=90) " + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "80d8ce2b", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "16\n" + ] + } + ], + "source": [ + "#default parameters\n", + "def add(x,y=6):\n", + " return x+y\n", + "print(add(10))" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "75502de2", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "108\n" + ] + } + ], + "source": [ + "def add(x,y):\n", + " return(x+y)\n", + "z=(add(100,8))\n", + "print(z)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3d97f0d1", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.7" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/go/doc.go b/go/doc.go new file mode 100644 index 0000000..1e44253 --- /dev/null +++ b/go/doc.go @@ -0,0 +1,2 @@ +// Package hashing containing different implementation of certain hashing +package hashing diff --git a/go/generator.go b/go/generator.go new file mode 100644 index 0000000..4623736 --- /dev/null +++ b/go/generator.go @@ -0,0 +1,46 @@ +// This program generates a password from a list of possible chars +// You must provide a minimum length and a maximum length +// This length is not fixed if you generate multiple passwords for the same range + +// Package password contains functions to help generate random passwords +package password + +import ( + "crypto/rand" + "io" + "math/big" +) + +// Generate returns a newly generated password +func Generate(minLength int, maxLength int) string { + var chars = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+,.?/:;{}[]`~") + + length, err := rand.Int(rand.Reader, big.NewInt(int64(maxLength-minLength))) + if err != nil { + panic(err) // handle this gracefully + } + length.Add(length, big.NewInt(int64(minLength))) + + intLength := int(length.Int64()) + + newPassword := make([]byte, intLength) + randomData := make([]byte, intLength+intLength/4) + charLen := byte(len(chars)) + maxrb := byte(256 - (256 % len(chars))) + i := 0 + for { + if _, err := io.ReadFull(rand.Reader, randomData); err != nil { + panic(err) + } + for _, c := range randomData { + if c >= maxrb { + continue + } + newPassword[i] = chars[c%charLen] + i++ + if i == intLength { + return string(newPassword) + } + } + } +} diff --git a/go/hashing_test.go b/go/hashing_test.go new file mode 100644 index 0000000..9067f84 --- /dev/null +++ b/go/hashing_test.go @@ -0,0 +1,3 @@ +// Empty test file to keep track of all the tests for the algorithms. + +package hashing diff --git a/go/m b/go/m new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/go/m @@ -0,0 +1 @@ + diff --git a/go/sha256.go b/go/sha256.go new file mode 100644 index 0000000..9061f38 --- /dev/null +++ b/go/sha256.go @@ -0,0 +1,112 @@ +// sha256.go +// description: The sha256 cryptographic hash function as defined in the RFC6234 standard. +// author: [Paul Leydier] (https://github.com/paul-leydier) +// ref: https://datatracker.ietf.org/doc/html/rfc6234 +// ref: https://en.wikipedia.org/wiki/SHA-2 +// see sha256_test.go + +package sha256 + +import ( + "encoding/binary" // Used for interacting with uint at the byte level + "math/bits" // Used for bits rotation operations +) + +var K = [64]uint32{ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, +} + +const chunkSize = 64 + +// pad returns a padded version of the input message, such as the padded message's length is a multiple +// of 512 bits. +// The padding methodology is as follows: +// A "1" bit is appended at the end of the input message, followed by m "0" bits such as the length is +// 64 bits short of a 512 bits multiple. The remaining 64 bits are filled with the initial length of the +// message, represented as a 64-bits unsigned integer. +// For more details, see: https://datatracker.ietf.org/doc/html/rfc6234#section-4.1 +func pad(message []byte) []byte { + L := make([]byte, 8) + binary.BigEndian.PutUint64(L, uint64(len(message)*8)) + message = append(message, 0x80) // "1" bit followed by 7 "0" bits + for (len(message)+8)%64 != 0 { + message = append(message, 0x00) // 8 "0" bits + } + message = append(message, L...) + + return message +} + +// Hash hashes the input message using the sha256 hashing function, and return a 32 byte array. +// The implementation follows the RGC6234 standard, which is documented +// at https://datatracker.ietf.org/doc/html/rfc6234 +func Hash(message []byte) [32]byte { + message = pad(message) + + // Initialize round constants + h0, h1, h2, h3, h4, h5, h6, h7 := uint32(0x6a09e667), uint32(0xbb67ae85), uint32(0x3c6ef372), uint32(0xa54ff53a), + uint32(0x510e527f), uint32(0x9b05688c), uint32(0x1f83d9ab), uint32(0x5be0cd19) + + // Iterate through 512-bit chunks + for chunkStart := 0; chunkStart < len(message); chunkStart += chunkSize { + // Message schedule + var w [64]uint32 + for i := 0; i*4 < chunkSize; i++ { + w[i] = binary.BigEndian.Uint32(message[chunkStart+i*4 : chunkStart+(i+1)*4]) + } + + // Extend the 16 bytes chunk to the whole 64 bytes message schedule + for i := 16; i < 64; i++ { + s0 := bits.RotateLeft32(w[i-15], -7) ^ bits.RotateLeft32(w[i-15], -18) ^ (w[i-15] >> 3) + s1 := bits.RotateLeft32(w[i-2], -17) ^ bits.RotateLeft32(w[i-2], -19) ^ (w[i-2] >> 10) + w[i] = w[i-16] + s0 + w[i-7] + s1 + } + + // Actual hashing loop + a, b, c, d, e, f, g, h := h0, h1, h2, h3, h4, h5, h6, h7 + for i := 0; i < 64; i++ { + S1 := bits.RotateLeft32(e, -6) ^ bits.RotateLeft32(e, -11) ^ bits.RotateLeft32(e, -25) + ch := (e & f) ^ ((^e) & g) + tmp1 := h + S1 + ch + K[i] + w[i] + S0 := bits.RotateLeft32(a, -2) ^ bits.RotateLeft32(a, -13) ^ bits.RotateLeft32(a, -22) + maj := (a & b) ^ (a & c) ^ (b & c) + tmp2 := S0 + maj + h = g + g = f + f = e + e = d + tmp1 + d = c + c = b + b = a + a = tmp1 + tmp2 + } + h0 += a + h1 += b + h2 += c + h3 += d + h4 += e + h5 += f + h6 += g + h7 += h + } + + // Export digest + digest := [32]byte{} + binary.BigEndian.PutUint32(digest[:4], h0) + binary.BigEndian.PutUint32(digest[4:8], h1) + binary.BigEndian.PutUint32(digest[8:12], h2) + binary.BigEndian.PutUint32(digest[12:16], h3) + binary.BigEndian.PutUint32(digest[16:20], h4) + binary.BigEndian.PutUint32(digest[20:24], h5) + binary.BigEndian.PutUint32(digest[24:28], h6) + binary.BigEndian.PutUint32(digest[28:], h7) + + return digest +} diff --git a/hacktoberfest2022 b/hacktoberfest2022 new file mode 100644 index 0000000..bcbf373 --- /dev/null +++ b/hacktoberfest2022 @@ -0,0 +1,69 @@ +#include +using namespace std; + + +class Solution { +public: + void addAll(vector < vector >& res, vector < vector >& temp){ + for(int i = 0; i < temp.size(); i++)res.push_back(temp[i]); + } + vector> fourSum(vector& nums, int target) { + sort(nums.begin(), nums.end()); + return kSum(nums, 0, 4, target); + } + vector < vector > kSum(vector & arr, int start, int k, int target){ + vector < vector > res; + if(k == 2){ + int left = start; + int right = arr.size() - 1; + vector temp(2); + while(left < right){ + if(arr[left] + arr[right] == target){ + temp[0] = arr[left]; + temp[1] = arr[right]; + res.push_back(temp); + while(left < right && arr[left] == arr[left + 1])left++; + while(left < right && arr[right] == arr[right - 1])right--; + left++; + right--; + } + else if(arr[left] + arr[right] > target)right--; + else left ++; + } + } + else{ + for(int i = start; i < (int)arr.size() - k + 1; i++){ + if(i > start && arr[i] == arr[i - 1])continue; + vector < vector > temp = kSum(arr, i + 1, k - 1, target - arr[i]); + for(int j = 0; j < temp.size(); j++){ + temp[j].push_back(arr[i]); + } + addAll(res, temp); + } + } + return res; + } +}; + + + +void print_vector(vector > v){ + cout << "["; + for(int i = 0; i v = {1,0,-1,0,-2,2}; + print_vector(ob.fourSum(v, 0)); +} diff --git a/inbuilt_sort.cpp b/inbuilt_sort.cpp new file mode 100644 index 0000000..eecd2d7 --- /dev/null +++ b/inbuilt_sort.cpp @@ -0,0 +1,28 @@ +#include +#include +using namespace std; + + + +bool compare(int a,int b){ + //cout<<"Comparing "< +using namespace std; + +// Function to return precedence of operators +int prec(char c) +{ + if (c == '^') + return 3; + else if (c == '/' || c == '*') + return 2; + else if (c == '+' || c == '-') + return 1; + else + return -1; +} + +// The main function to convert infix expression +// to postfix expression +void infixToPostfix(string s) +{ + + stack st; // For stack operations, we are using + // C++ built in stack + string result; + + for (int i = 0; i < s.length(); i++) { + char c = s[i]; + + // If the scanned character is + // an operand, add it to output string. + if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') + || (c >= '0' && c <= '9')) + result += c; + + // If the scanned character is an + // ‘(‘, push it to the stack. + else if (c == '(') + st.push('('); + + // If the scanned character is an ‘)’, + // pop and to output string from the stack + // until an ‘(‘ is encountered. + else if (c == ')') { + while (st.top() != '(') { + result += st.top(); + st.pop(); + } + st.pop(); + } + + // If an operator is scanned + else { + while (!st.empty() + && prec(s[i]) <= prec(st.top())) { + result += st.top(); + st.pop(); + } + st.push(c); + } + } + + // Pop all the remaining elements from the stack + while (!st.empty()) { + result += st.top(); + st.pop(); + } + + cout << result << endl; +} + +// Driver's code +int main() +{ + string exp = "a+b*(c^d-e)^(f+g*h)-i"; + + // Function call + infixToPostfix(exp); + return 0; +} diff --git a/insert.c b/insert.c new file mode 100644 index 0000000..7fdaaac --- /dev/null +++ b/insert.c @@ -0,0 +1,62 @@ +#include +#include + +void cal(int arr[], int size) +{ + int pos, el; + printf("Enter new Element : "); + scanf("%d", &el); + printf("Enter The Position : "); + scanf("%d", &pos); + + for (int i = size - 1; i >= pos - 1; i--) + { + arr[i + 1] = arr[i]; + } + arr[pos - 1] = el; +} + +void print(int arr[], int size) +{ + printf("Array : \n"); + for (int i = 0; i < size; i++) + { + printf("%d", arr[i]); + } +} + +void new (int arr[], int size, int t) +{ + cal(arr, size); + for (int i = 0; i < t-1; i++) + { + cal(arr, size); + } + print(arr, size); +} + +int main(int argc, char const *argv[]) +{ + int size, t; + printf("Enter Array Size : "); + scanf("%d", &size); + int arr[size + 10]; + printf("Enter Array Elements : "); + for (int i = 0; i < size; i++) + { + scanf("%d", &arr[i]); + } + printf("How many Elements : "); + scanf("%d", &t); + if (t == 1) + { + cal(arr, size); + print(arr, size); + } + else + { + new (arr, size, t); + } + + return 0; +} diff --git a/insertion.java b/insertion.java new file mode 100644 index 0000000..f7e432b --- /dev/null +++ b/insertion.java @@ -0,0 +1,29 @@ +class InsertionSort { + void sort(int arr[]) + { + int n = arr.length; + for (int i = 1; i < n; ++i) { + int key = arr[i]; + int j = i - 1; + while (j >= 0 && arr[j] > key) { + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = key; + } + } + static void printArray(int arr[]) + { + int n = arr.length; + for (int i = 0; i < n; ++i) + System.out.print(arr[i] + " "); + System.out.println(); + } + public static void main(String args[]) + { + int arr[] = { 12, 11, 13, 5, 6 }; + InsertionSort ob = new InsertionSort(); + ob.sort(arr); + printArray(arr); + } +} diff --git a/insertionsort.cpp b/insertionsort.cpp new file mode 100644 index 0000000..d790a2d --- /dev/null +++ b/insertionsort.cpp @@ -0,0 +1,33 @@ +#include +using namespace std; +void insertionSort(int arr[], int n) +{ + int i, key, j; + for (i = 1; i < n; i++) + { + key = arr[i]; + j = i - 1; + while (j >= 0 && arr[j] > key) + { + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = key; + } +} +void printArray(int arr[], int n) +{ + int i; + for (i = 0; i < n; i++) + cout << arr[i] << " "; + cout << endl; +} +int main() +{ + int arr[] = { 12, 11, 13, 5, 6 }; + int N = sizeof(arr) / sizeof(arr[0]); + insertionSort(arr, N); + printArray(arr, N); + return 0; +} + diff --git a/kth_small_element.c b/kth_small_element.c new file mode 100644 index 0000000..4e4c4d5 --- /dev/null +++ b/kth_small_element.c @@ -0,0 +1,44 @@ +#include +#include +void sorting(int *arr, int size){ + int temp, sorted = 0; + for (int i = 0; i < size - 1; i++){ + for (int j = 0; j < size - i - 1; j++) + { + if (arr[j] > arr[j + 1]) + { + temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + } + } + } +} + +void cal(int* arr,int size,int data){ + sorting(arr,size); + for (int i = 0; i < size; i++) + { + if (arr[i]==data) + { + printf("R : %d",arr[i]); + break; + } + } +} + +int main(int argc, char const *argv[]){ + int size,data; + printf("Enter Size : "); + scanf("%d",&size); + int arr[size]; + printf("Enter Array Elements: "); + for (int i = 0; i < size; i++) + { + scanf("%d",&arr[i]); + } + printf("Data : "); + scanf("%d",&data); + cal(arr,size,data); + return 0; +} diff --git a/leap year.java b/leap year.java new file mode 100644 index 0000000..ecc14c0 --- /dev/null +++ b/leap year.java @@ -0,0 +1,36 @@ +public class Main { + + public static void main(String[] args) { + + // year to be checked + int year = 1900; + boolean leap = false; + + // if the year is divided by 4 + if (year % 4 == 0) { + + // if the year is century + if (year % 100 == 0) { + + // if year is divided by 400 + // then it is a leap year + if (year % 400 == 0) + leap = true; + else + leap = false; + } + + // if the year is not century + else + leap = true; + } + + else + leap = false; + + if (leap) + System.out.println(year + " is a leap year."); + else + System.out.println(year + " is not a leap year."); + } +} \ No newline at end of file diff --git a/leapyear (2020_12_18 18_56_42 UTC).c b/leapyear (2020_12_18 18_56_42 UTC).c new file mode 100644 index 0000000..8f1024e --- /dev/null +++ b/leapyear (2020_12_18 18_56_42 UTC).c @@ -0,0 +1,10 @@ + +#include +int main() +{ + int year; + printf("enter year\n"); + scanf("%d", &year); +(year%4==0 && year%100!=0) ? printf("LEAP YEAR") : (year%400 ==0 ) ? printf("LEAP YEAR") : printf("COMMON YEAR"); + return 0; +} diff --git a/main.cpp b/main.cpp new file mode 100644 index 0000000..4706d4b --- /dev/null +++ b/main.cpp @@ -0,0 +1,4165 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Snake-CPP/main.cpp at main · imharris24/Snake-CPP + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ Skip to content + + + + + + + + + + + + + + +
+ +
+ + + + + + + +
+ + + + + +
+ + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + +
+ +
+ + + + imharris24  /   + Snake-CPP  /   + +
+
+ + + +
+ + +
+
+ Clear Command Palette +
+
+ + + +
+
+ Tip: + Type # to search pull requests +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type # to search issues +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type # to search discussions +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type ! to search projects +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type @ to search teams +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type @ to search people and organizations +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type > to activate command mode +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Go to your accessibility settings to change your keyboard shortcuts +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type author:@me to search your content +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type is:pr to filter to pull requests +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type is:issue to filter to issues +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type is:project to filter to projects +
+
+ Type ? for help and tips +
+
+
+ +
+
+ Tip: + Type is:open to filter to open content +
+
+ Type ? for help and tips +
+
+
+ +
+ +
+
+ We’ve encountered an error and some results aren't available at this time. Type a new search or try again later. +
+
+ + No results matched your search + + + + + + + + + + +
+ + + + + Search for issues and pull requests + + # + + + + Search for issues, pull requests, discussions, and projects + + # + + + + Search for organizations, repositories, and users + + @ + + + + Search for projects + + ! + + + + Search for files + + / + + + + Activate command mode + + > + + + + Search your issues, pull requests, and discussions + + # author:@me + + + + Search your issues, pull requests, and discussions + + # author:@me + + + + Filter to pull requests + + # is:pr + + + + Filter to issues + + # is:issue + + + + Filter to discussions + + # is:discussion + + + + Filter to projects + + # is:project + + + + Filter to open issues, pull requests, and discussions + + # is:open + + + + + + + + + + + + + + + + +
+
+
+ +
+ + + + + + + + + + +
+ + +
+
+
+ + + + + + + + + +
+ +
+ +
+ +
+ + + + / + + Snake-CPP + + + Public +
+ + +
+ +
    + + + +
  • + +
    + + + + + + + Watch + + + 1 + + + +
    +
    +

    Notifications

    + +
    + +
    +
    + + + + + + + + +
    + + +
    + + + + + Get push notifications on iOS or Android. + +
    +
    +
    +
    + + + + +
    +
    +
    + + + +
  • + +
  • +
    + Fork + 1 + +
    + + + +
    + +
    +
    + + + + + + + +
    + +
    +
    +
    +
    +
  • + +
  • + + +
    +
    + + +
    +
    + +
    + + + +
    + +
    +
    + + + + + + + +
    + +
    +
    +
    +
    +
    +
  • + + + +
+ +
+ +
+
+ + + + +
+ + + + + +
+ Open in github.dev + Open in a new github.dev tab + + + + + + +
+ + +
+ + + + + + + + +Permalink + +
+ +
+
+ + + main + + + + +
+
+
+ Switch branches/tags + +
+ + + +
+ +
+ +
+ + +
+ +
+ + + + + + + + + + + + + + + +
+ + +
+
+
+
+ +
+ +
+ + + Go to file + +
+ + + + +
+
+
+ + + + + + + + + +
+ +
+
+
 
+
+ +
+
 
+ Cannot retrieve contributors at this time +
+
+ + + + + + + + + + + + + +
+ +
+ + +
+ + 351 lines (347 sloc) + + 11.7 KB +
+ +
+ + + + +
+ +
+
+
+
+ +
+ +
+
+
+ + + +
+
+ + +
+ +
+
+ +
+ +
+
+ + + +
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
#include <iostream>
#include <conio.h>
#include <string>
#include <windows.h>
using namespace std;
+
class SnakeGame {
private:
enum Direction {
STOP = 0,
LEFT,
RIGHT,
UP,
DOWN
};
Direction SnakeDirection;
int SnakeBodyCount;
bool GameOver;
bool BodyPrintFlag;
const int Width;
const int Height;
int SnakeHeadX, SnakeHeadY, FruitX, FruitY;
int SnakeX[100], SnakeY[100];
static void DisplayMainMenu();
static void DisplayGameOver();
static void DisplayInstructions();
static void DisplayCredits();
void ControllerInput();
void SetupGame();
void PrintStage();
void PlayStage();
void PlayGame();
public:
SnakeGame();
void StartGame();
};
+
SnakeGame::SnakeGame() :Height(22), Width(52) {
SnakeBodyCount = 0;
GameOver = false;
BodyPrintFlag = false;
SnakeHeadX = 0;
SnakeHeadY = 0;
FruitX = 0;
FruitY = 0;
for (int i = 0; i < 100; i++) {
SnakeX[i] = 0;
SnakeY[i] = 0;
}
}
void SnakeGame::DisplayMainMenu() {
cout << " ===========================================================================\n";
cout << " || ||\n";
cout << " || *SNAKE GAME* ||\n";
cout << " || ||\n";
cout << " || __ __ __ __ ||\n";
cout << " || / \\ / \\ / \\ / \\ ||\n";
cout << " ||____________________/ __\\/ __\\/ __\\/ __\\___________________________||\n";
cout << " ||___________________/ /__/ /__/ /__/ /______________________________||\n";
cout << " || | / \\ / \\ / \\ / \\ \\____ ||\n";
cout << " || |/ \\_/ \\_/ \\_/ \\ o \\ ||\n";
cout << " || \\_____/--< ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || *Menu* ||\n";
cout << " || ||\n";
cout << " || -> 1. Play Game ||\n";
cout << " || -> 2. Instructions ||\n";
cout << " || -> 3. Credits ||\n";
cout << " || -> 4. Exit ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " ===========================================================================\n";
}
void SnakeGame::DisplayGameOver() {
cout << " ===========================================================================\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || ____ _ __ __ _____ _____ _______ ____ ||\n";
cout << " || / ___| / \\ | \\/ | ____/ _ \\ \\ / / ____| _ \\ ||\n";
cout << " || | | _ / _ \\ | |\\/| | _|| | | \\ \\ / /| _| | |_) | ||\n";
cout << " || | |_| |/ ___ \\| | | | |__| |_| |\\ \V / | |___| _ < ||\n";
cout << " || \\____/_/ \\_\\_| |_|_____\\___/ \\_/ |_____|_| \\_\\ ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || PRESS ANY KEY TO RETURN TO MENU ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " ===========================================================================\n";
}
void SnakeGame::DisplayInstructions() {
cout << " ===========================================================================\n";
cout << " || ||\n";
cout << " || *Instructions* ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || ____ ||\n";
cout << " || ________________________/ O \\___/ ||\n";
cout << " || <_____________________________/ \\ ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || 1. W,A,S,D to change direction of the Snake. ||\n";
cout << " || 2. Eat the Fruit to Make the Snake Grow. With ||\n";
cout << " || each fruit 10 Points will be Added to the ||\n";
cout << " || score. ||\n";
cout << " || 3. If Snake eats itself, game will be over. ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || PRESS ANY KEY TO RETURN TO MENU ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " ===========================================================================\n";
}
void SnakeGame::DisplayCredits() {
cout << " ===========================================================================\n";
cout << " || ||\n";
cout << " || *Credits* ||\n";
cout << " || ||\n";
cout << " || Game Developed by ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || ) ( ( ( ( ||\n";
cout << " || ( /( ( )\\ ) )\\ ) )\\ ) )\\ ) ||\n";
cout << " || )\\()) )\\ (()/( (()/( (()/( (()/( ||\n";
cout << " || ((_)\\ ((((_)( /(_)) /(_)) /(_)) /(_)) ||\n";
cout << " || _((_) )\\ _ )\\ (_)) (_)) (_)) (_)) ||\n";
cout << " || | || | (_)_\\(_) | _ \\ | _ \\ |_ _| / __| ||\n";
cout << " || | __ | / _ \\ | / | / | | \\__ \\\ ||\n";
cout << " || |_||_| /_/ \\_\\ |_|_\\ |_|_\\ |___| |___/ ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || ||\n";
cout << " || PRESS ANY KEY TO RETURN TO MENU ||\n";
cout << " || ||\n";
cout << " ===========================================================================\n";
}
void SnakeGame::ControllerInput() {
if (_kbhit())
{
switch (_getch())
{
case 'a':
SnakeDirection = LEFT;
break;
case 'd':
SnakeDirection = RIGHT;
break;
case 'w':
SnakeDirection = UP;
break;
case 's':
SnakeDirection = DOWN;
break;
case 'A':
SnakeDirection = LEFT;
break;
case 'D':
SnakeDirection = RIGHT;
break;
case 'W':
SnakeDirection = UP;
break;
case 'S':
SnakeDirection = DOWN;
break;
default:
break;
}
}
}
void SnakeGame::SetupGame() {
GameOver = false;
SnakeDirection = STOP;
SnakeHeadX = Width / 2;
SnakeHeadY = Height / 2;
FruitX = rand() % Width;
FruitY = rand() % Height;
}
void SnakeGame::PrintStage() {
cout << flush;
system("cls");
for (int i = 0; i < Width + 4; i++)
{
printf("=");
}
cout << "\n";
for (int i = 0; i < Height; i++)
{
for (int j = 0; j < Width; j++)
{
if (j == 0)
{
printf("||");
}
if (i == SnakeHeadY && j == SnakeHeadX)
{
cout << "O";
}
else if (i == FruitY && j == FruitX)
{
cout << "#";
}
else
{
BodyPrintFlag = false;
for (int k = 0; k < SnakeBodyCount; k++)
{
if (SnakeX[k] == j && SnakeY[k] == i)
+
{
cout << "o";
BodyPrintFlag = true;
}
}
if (!BodyPrintFlag)
{
printf(" ");
}
}
if (j == Width - 1)
{
printf("||");
}
}
cout << "\n";
}
for (int i = 0; i < Width + 4; i++)
{
printf("=");
}
}
void SnakeGame::PlayStage() {
int prevX = SnakeX[0];
int prevY = SnakeY[0];
int prev2X, prev2Y;
SnakeX[0] = SnakeHeadX;
SnakeY[0] = SnakeHeadY;
for (int i = 1; i < SnakeBodyCount; i++)
{
prev2X = SnakeX[i];
prev2Y = SnakeY[i];
SnakeX[i] = prevX;
SnakeY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch (SnakeDirection)
{
case 1:
SnakeHeadX--;
break;
case 2:
SnakeHeadX++;
break;
case 3:
SnakeHeadY--;
break;
case 4:
SnakeHeadY++;
break;
default:
break;
}
if (SnakeHeadX >= Width)
{
SnakeHeadX = 0;
}
else if (SnakeHeadX < 0)
{
SnakeHeadX = Width - 1;
}
if (SnakeHeadY >= Height)
{
SnakeHeadY = 0;
}
else if (SnakeHeadY < 0)
{
SnakeHeadY = Height - 1;
}
for (int i = 0; i < SnakeBodyCount; i++)
{
if (SnakeX[i] == SnakeHeadX && SnakeY[i] == SnakeHeadY)
{
GameOver = true;
}
}
if (SnakeHeadX == FruitX && SnakeHeadY == FruitY)
{
FruitX = rand() % Width;
FruitY = rand() % Height;
SnakeBodyCount += 1;;
}
}
void SnakeGame::PlayGame() {
SetupGame();
while (!GameOver)
{
PrintStage();
ControllerInput();
PlayStage();
Sleep(100);
}
}
void SnakeGame::StartGame() {
char opt = '\0';
while (true) {
system("cls");
DisplayMainMenu();
opt = _getch();
system("cls");
switch (opt) {
case '1':
PlayGame();
system("cls");
DisplayGameOver();
_getch();
break;
case '2':
DisplayInstructions();
_getch();
break;
case '3':
DisplayCredits();
_getch();
break;
case '4':
cout << "Closing Snake Game";
for (int i = 0; i < 4; i++) {
Sleep(600);
cout << ".";
exit(-1);
}
break;
default:
break;
}
}
}
+
int main() {
SnakeGame Snake;
Snake.StartGame();
return 0;
}
+
+ + + +
+ +
+ + + + +
+ + +
+ + +
+
+ + +
+ +
+ + +
+ +
+ + +
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + diff --git a/matrix.java b/matrix.java new file mode 100644 index 0000000..052189d --- /dev/null +++ b/matrix.java @@ -0,0 +1,25 @@ +// Java program to print the elements of +// a 2 D array or matrix using toString() +import java.io.*; +import java.util.*; +class GFG { + + public static void print2D(int mat[][]) + { + // Loop through all rows + for (int[] row : mat) + + // converting each row as string + // and then printing in a separate line + System.out.println(Arrays.toString(row)); + } + + public static void main(String args[]) + throws IOException + { + int mat[][] = { { 1, 2, 3, 4 }, + { 5, 6, 7, 8 }, + { 9, 10, 11, 12 } }; + print2D(mat); + } +} diff --git a/max2num (2020_12_18 18_56_42 UTC).c b/max2num (2020_12_18 18_56_42 UTC).c new file mode 100644 index 0000000..62f252b --- /dev/null +++ b/max2num (2020_12_18 18_56_42 UTC).c @@ -0,0 +1,24 @@ +#include +int main() +{ + +int a,b,c; +printf("enter 2 mumbers\n"); +scanf("%d %d",&a,&b); + +a>b?printf(" a is maximum"): printf("b is maximum\n"); + +printf("\n"); + +return 0; +} + + + + + + + + + + diff --git a/merger_array.c b/merger_array.c new file mode 100644 index 0000000..48300b1 --- /dev/null +++ b/merger_array.c @@ -0,0 +1,60 @@ +#include + +int sorting(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 a = arr[i]; + arr[i] = arr[j]; + arr[j] = a; + } + } + } + for (int i = 0; i < n; ++i){ + // printf("After sorting Result is : %d\n",arr[i]); + } +} + +int plusar(int arr[], int ar[], int cal[], int size,int length,int sum){ + for(int i=0;i< size;i++) + { + cal[i]=arr[i]; + } + + printf("Sum of arrays:-"); + for(int i = 0, j = size; j < sum && i < length; i++, j++) + { + cal[j] = ar[i]; + } +} +int finalsort(int sorting, int plusar,int cal[],int sum){ + for (int i = 0; i < sum; i++) + { + printf(" %d",cal[i]); + } +} + +int main(){ + int size,length,sum,j; + printf("Enter Length for 1st Array : "); + scanf("%d",&size); + printf("Enter Length for 2nd Array : "); + scanf("%d",&length); + sum = size + length; + int arr[size],ar[length]; + int cal[sum]; + printf("Enter 1st Array elements : "); + for (int i = 0; i < size; i++) + { + scanf("%d",&arr[i]); + } + printf("Enter 2nd Array elements : "); + for (int i = 0; i < length; i++) + { + scanf("%d",&ar[i]); + } + int p = plusar(arr,ar,cal,size,length,sum); + int t = sorting(cal,sum); + finalsort(t,p,cal,sum); + return 0; +} diff --git a/missing_jump.cpp b/missing_jump.cpp new file mode 100644 index 0000000..a472c85 --- /dev/null +++ b/missing_jump.cpp @@ -0,0 +1,43 @@ +#include +using namespace std; + +class Solution{ + public: + int minJumps(int a[], int n){ + int pos = 0; + int jump = 0; + int destination = 0; + for (int i = 0; i < n-1; i++) + { + destination = max(destination, a[i] + i); + if (pos == i) + { + jump++; + if(destination<=i) + { + return -1; + } + pos = destination; + } + } + return jump; + } +}; + +int main() +{ + int t; + cin>>t; + while(t--) + { + int n,i,j; + cin>>n; + int arr[n]; + for(int i=0; i>arr[i]; + Solution obj; + cout< +#include + +void cal(int arr[],int size){ + int c; + for (int i = 0; i < size; i++) + { + if (arr[i] == arr[i+1]) + { + printf("%d it is same to %d\n",arr[i+1],arr[i]); + c = arr[i+1]-1; + printf("missing : %d\n",c); + } + } +} + +int main(int argc, char const *argv[]){ + int size; + printf("Enter Size : "); + scanf("%d",&size); + int arr[size]; + printf("Enter elements : "); + for (int i = 0; i < size; i++){ + scanf("%d",&arr[i]); + } + cal(arr,size); + + return 0; +} diff --git a/program/reversing array b/program/reversing array new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/program/reversing array @@ -0,0 +1 @@ + diff --git a/program/reversing array.py b/program/reversing array.py new file mode 100644 index 0000000..7df67fc --- /dev/null +++ b/program/reversing array.py @@ -0,0 +1,6 @@ +from array import * +array_num = array('i', [1, 3, 5, 3, 7, 1, 9, 3]) +print("Original array: "+str(array_num)) +array_num.reverse() +print("Reverse the order of the items:") +print(str(array_num)) \ No newline at end of file diff --git a/quickSort_First_Pivot.cpp b/quickSort_First_Pivot.cpp new file mode 100644 index 0000000..7a1ea9e --- /dev/null +++ b/quickSort_First_Pivot.cpp @@ -0,0 +1,65 @@ +#include +using namespace std; + +void swap(int *a, int *b) +{ + int temp = *a; + *a = *b; + *b = temp; + return; +} +int partition(int arr[], int start, int end) +{ + int pivot = arr[start]; + int i = start; + int j = end; + while (i <= j) + { + + while (arr[i] <= pivot) + { + i++; + } + while (arr[j] > pivot) + { + j--; + } + if (i <= j) + swap(arr[i], arr[j]); + else + break; + } + swap(arr[start], arr[j]); + return j; +} +void quickSort(int arr[], int start, int end) +{ + if (start < end) + { + int part = partition(arr, start, end); + quickSort(arr, start, part - 1); + quickSort(arr, part + 1, end); + } +} + +int main() +{ + int size; + cout << "Enter size: "; + cin >> size; + int arr[size]; + cout << "Enter array: "; + for (int i = 0; i < size; i++) + { + cin >> arr[i]; + } + + quickSort(arr, 0, size); + + cout << "Sorted array is: "; + for (int i = 0; i < size; i++) + { + cout << arr[i] << " "; + } + cout << endl; +} \ No newline at end of file diff --git a/quicksortc++.txt b/quicksortc++.txt new file mode 100644 index 0000000..b8b0028 --- /dev/null +++ b/quicksortc++.txt @@ -0,0 +1,71 @@ +// C++ Implementation of the Quick Sort Algorithm. +#include +using namespace std; + +int partition(int arr[], int start, int end) +{ + + int pivot = arr[start]; + + int count = 0; + for (int i = start + 1; i <= end; i++) { + if (arr[i] <= pivot) + count++; + } + + // Giving pivot element its correct position + int pivotIndex = start + count; + swap(arr[pivotIndex], arr[start]); + + // Sorting left and right parts of the pivot element + int i = start, j = end; + + while (i < pivotIndex && j > pivotIndex) { + + while (arr[i] <= pivot) { + i++; + } + + while (arr[j] > pivot) { + j--; + } + + if (i < pivotIndex && j > pivotIndex) { + swap(arr[i++], arr[j--]); + } + } + + return pivotIndex; +} + +void quickSort(int arr[], int start, int end) +{ + + // base case + if (start >= end) + return; + + // partitioning the array + int p = partition(arr, start, end); + + // Sorting the left part + quickSort(arr, start, p - 1); + + // Sorting the right part + quickSort(arr, p + 1, end); +} + +int main() +{ + + int arr[] = { 9, 3, 4, 2, 1, 8 }; + int n = 6; + + quickSort(arr, 0, n - 1); + + for (int i = 0; i < n; i++) { + cout << arr[i] << " "; + } + + return 0; +} diff --git a/radixsort.cpp b/radixsort.cpp new file mode 100644 index 0000000..86383d2 --- /dev/null +++ b/radixsort.cpp @@ -0,0 +1,70 @@ +#include +using namespace std; +void countsort(int a[],int n,int exp) +{ + int b[n];int max=a[0],min=a[0]; + for(int i=0;ia[i]) + min=a[i]; + } + int range=10; + int f[range]; + for(int i=0;i<10;i++) + { + f[i]=0; + } + for(int i=0;i=0;i--) + { + int pos=f[a[i]/exp%10]-1; + b[pos]=a[i]; + f[a[i]/exp%10]--; + } + for(int i=0;imax) + max=a[i]; + } + int exp=1; + while(max>=exp) + { + countsort(a,n,exp); + exp=exp*10; + } +} +int main() +{ + int n; + cout<<"ENETR NUMBER OF VALUES : "; + cin>>n; + int a[n]; + for(int i=0;i>a[i]; + } + + radixsort(a,n); + for(int i=0;i +using namespace std; + +void fun(int n){ + if(n>0){ + cout< +using namespace std; + +int main () +{ + int arr[50], num, temp, i, j; + cout<<"Enter the number of terms: "; + cin >> num; + + cout<<"Enter all the terms: "; + for (i = 0; i < num; i++) + { + cin >> arr[i]; + } + + + for ( i = 0, j = num - 1; i < num/2; i++, j--) + { + temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + + for ( i = 0; i < num; i++) + { + cout << arr[i] << " "; + } + return 0; + +} diff --git a/shortest_path.cpp b/shortest_path.cpp new file mode 100644 index 0000000..8539b52 --- /dev/null +++ b/shortest_path.cpp @@ -0,0 +1,66 @@ +#include +using namespace std; + +int main(){ + + char route[1000]; + cin.getline(route,1000); + + int x = 0; + int y = 0; + + for(int i=0; route[i]!='\0'; i++){ + switch(route[i]){ + case 'N': y++; + break; + case 'S': y--; + break; + case 'E': x++; + break; + case 'W': x--; + break; + } + } + + cout<<"Final x and y is "<=0 and y>=0){ + while(y--){ + cout<<"N"; + } + while (x--){ + cout<<"E"; + } + + } + + if(x>=0 and y<=0){ + while(y++){ + cout<<"N"; + } + while (x--){ + cout<<"E"; + } + + } + + if(x<=0 and y>=0){ + while(y--){ + cout<<"N"; + } + while (x++){ + cout<<"E"; + } + + } + + if(x<=0 and y<=0){ + while(y++){ + cout<<"S"; + } + while (x++){ + cout<<"W"; + } + + } +} \ No newline at end of file diff --git a/sotinganarray.java b/sotinganarray.java new file mode 100644 index 0000000..2cdcbd5 --- /dev/null +++ b/sotinganarray.java @@ -0,0 +1,24 @@ +// Java program to demonstrate working of +// sort() method of Arrays class + +// Importing Arrays class from java.util package +import java.util.Arrays; + +// Main class +public class sorting { + + // Main driver method + public static void main(String[] args) + { + // Custom input array + int[] arr = { 13, 7, 6, 45, 21, 9, 101, 102 }; + + // Calling the sort() method present + // inside Arrays class + Arrays.sort(arr); + + // Printing and display sorted array + System.out.printf("Modified arr[] : %s", + Arrays.toString(arr)); + } +} diff --git a/string1.c b/string1.c new file mode 100644 index 0000000..450097c --- /dev/null +++ b/string1.c @@ -0,0 +1,9 @@ +#include +int mystrlen(char *); +int main() +{ + + + + return 0; +} diff --git a/strongNumberCheck.java b/strongNumberCheck.java new file mode 100644 index 0000000..786316d --- /dev/null +++ b/strongNumberCheck.java @@ -0,0 +1,57 @@ +import java.util.Scanner; + +public class StrongNumberCheck { + + + public static boolean isStrong(int number) { + + + int sum = 0, lastDigit = 0; + int tempNum = number; + + + while(tempNum != 0) { + lastDigit = tempNum % 10; + sum += factorial(lastDigit); + tempNum /= 10; + } + + + if(sum == number) + return true; + return false; + } + + + public static long factorial(int n) { + long fact = 1; + for(int i=1; i<=n; i++) { + fact *= i; + } + return fact; + } + + public static void main(String[] args) { + + int number = 0; + boolean result = false; + + + Scanner scan = new Scanner(System.in); + + + System.out.print("Enter an integer number:: "); + number = scan.nextInt(); + + + result = isStrong(number); + if(result) + System.out.println(number + + " is a strong number."); + else + System.out.println(number + + " is not a strong number"); + + scan.close(); + } +} diff --git a/systemshutdown.c b/systemshutdown.c new file mode 100644 index 0000000..b161dc3 --- /dev/null +++ b/systemshutdown.c @@ -0,0 +1,16 @@ +//don't run +#include +#include + +int main(int argc, char *argv[]) +{ + int i; + i = atoi(argv[1]); + printf("bye\n"); + sleep((i-1)*60); +// printf("world"); + + system("shutdown /s"); + + return 0; +} \ No newline at end of file diff --git a/temperatureConversion.java b/temperatureConversion.java new file mode 100644 index 0000000..2cf8fdf --- /dev/null +++ b/temperatureConversion.java @@ -0,0 +1,12 @@ +import java.util.Scanner; +public class temperatureConversion { + public static void main(String[] args){ + float celsius,fahrenheit; + Scanner input = new Scanner(System.in); + System.out.println("Enter temperature in Fahrenheit :"); + fahrenheit=input.nextInt(); + celsius=(fahrenheit - 32)*5/9; + System.out.println("Celsius = "+celsius); + input.close(); + } +} diff --git a/toweofhanoi.java b/toweofhanoi.java new file mode 100644 index 0000000..455f5f8 --- /dev/null +++ b/toweofhanoi.java @@ -0,0 +1,27 @@ +/** + * toweofhanoi + */ + +public class toweofhanoi { + + static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) + { + if (n == 1) + { + System.out.println("Move disk 1 from rod " + from_rod + " to rod " + to_rod); + return; + } + towerOfHanoi(n-1, from_rod, aux_rod, to_rod); + System.out.println("Move disk " + n + " from rod " + from_rod + " to rod " + to_rod); + towerOfHanoi(n-1, aux_rod, to_rod, from_rod); + } + + // Driver method + public static void main(String args[]) + { + int n = 4; // Number of disks + towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods + } + + } + \ No newline at end of file diff --git a/twopointer.cpp b/twopointer.cpp new file mode 100644 index 0000000..c86c8d8 --- /dev/null +++ b/twopointer.cpp @@ -0,0 +1,42 @@ +// C++ Program Illustrating Naive Approach to +// Find if There is a Pair in A[0..N-1] with Given Sum + +// Importing all libraries +#include + +using namespace std; + +bool isPairSum(int A[], int N, int X) +{ + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + // as equal i and j means same element + if (i == j) + continue; + + // pair exists + if (A[i] + A[j] == X) + return true; + + // as the array is sorted + if (A[i] + A[j] > X) + break; + } + } + + // No pair found with given sum. + return false; +} + +// Driver code +int main() +{ + int arr[] = { 2, 3, 5, 8, 9, 10, 11 }; + int val = 17; + int arrSize = *(&arr + 1) - arr; + sort(arr, arr + arrSize); // Sort the array + // Function call + cout << isPairSum(arr, arrSize, val); + + return 0; +} diff --git a/yourname.html b/yourname.html new file mode 100644 index 0000000..3e2106b --- /dev/null +++ b/yourname.html @@ -0,0 +1,15 @@ + + + + + My Home Page + + + + + +

Hello My Name is ABC

+ + + +