├── .vscode ├── c_cpp_properties.json ├── launch.json └── settings.json ├── 2-3treeOptimised.cpp ├── Armstrong_Number.cpp ├── Array-Implementation.cpp ├── ArrayComparison.cpp ├── BFS Tree traversal cpp ├── BInaryTreeMaximumPathSum.cpp ├── Backtracking(N-Queen problem).cpp ├── BinaryInsertionSort.cpp ├── BinarySearch.py ├── BinarySearchIterative.py ├── Breadth_first_search_Traversal.cpp ├── Bubble_Sort.cpp ├── Bubble_sort.py ├── CelebrityProblem.cpp ├── CheckPalindrome.cpp ├── Counting Subarrays Problem ├── DIGITREM Problem of Codechef ├── DiameterOfTree.cpp ├── Dobble_Game.py ├── Electricity_Bill.cpp ├── EqualiseArray.cpp ├── Factorial.cpp ├── FindMedianInAStream.cpp ├── Finding missing element.cpp ├── FizzBuzz.py ├── Floyd Warshall Algorithm.cpp ├── GenerateAllSubsetsofArray.cpp ├── Heap-sort.cpp ├── Input-in-array.cpp ├── Insertion sort.cpp ├── InsertionSort.cpp ├── Interpolation.py ├── InterpolationSearch.py ├── Jump_search.cpp ├── KClosestPointToOrigin.cpp ├── KMP_algo.cpp ├── Kadane's.cpp ├── KadaneAlgo.cpp ├── Knapsack.cpp ├── LCAofBST.cpp ├── Largest-sum-contiguous-subarray.cpp ├── LinearSearch.py ├── Longest_Arithmetic_sum.cpp ├── Longest_Common_Subsequence.py ├── MaximumAreaofIsland.cpp ├── Median_of_2sorted-arrays.cpp ├── MergeSort.cpp ├── MergeSort_using_pragma_openmp.cpp ├── ModularExponentiation.cpp ├── Multiple Missing elements.cpp ├── N-Queen Problem.cpp ├── N_doors_problem.py ├── Number Mirror.c ├── PancakeSort.cpp ├── Pancake_sorting.cpp ├── Prims_algo.cpp ├── QuickSort.cpp ├── README.md ├── RadixSort.c ├── Radix_sort.cpp ├── RatInMaze.cpp ├── Recursively_Delete_adjacent_Duplicates.cpp ├── Remove nth node from end of linked list.cpp ├── Reverse a Linked List ├── Reverse_matrix.cpp ├── Rock_Snake_Paper_Scissor.py ├── RotateALinkedList.cpp ├── Roulette-Game.py ├── STACK using array.cpp ├── ShellSort.cpp ├── Shell_Sort ├── SlidingWindowMaximum.cpp ├── Sliding_window_algorithm.cpp ├── Snake & Ladder.cpp ├── Snake_Game.py ├── Spiral_traversal.cpp ├── Spiral_traversal.exe ├── TowerOfHanoi.java ├── Tower_of_Hanaoi_puzzle.py ├── TrappingRainWater.cpp ├── Try ├── UniqueBInarySearchTree ├── Words from phone digit.cpp ├── allsortings.cpp ├── balanced_brackets.cpp ├── balanced_paranthesis.cpp ├── binSearch.cpp ├── bin_sort.py ├── binary search.cpp ├── binarysearchwithpointers.c ├── bowtie.py ├── bubble sort.cpp ├── bubble sort.py ├── bubble_sort.c ├── circularLinkedList.cpp ├── class and object.cpp ├── copyingArrays.cpp ├── count_distinct_elements.cpp ├── detobi.cpp ├── dijkstra-SingleSourceShortestPath.cpp ├── doubly linked list.cpp ├── dutch_National_Flag.cpp ├── factorial ├── fileHandling.cpp ├── flippingalbits.cpp ├── heap-sort.cpp ├── hellouser.py ├── inclusion_exclusion.cpp ├── insertion.py ├── intersectionnode.cpp ├── josephus.cpp ├── keylogger.py ├── kruskal.cpp ├── leap year ├── left_pattern.py ├── linear-search.cpp ├── linear.py ├── linearsearch.cpp ├── linked list.cpp ├── longest awesome string.cpp ├── longest_subarray_sum.cpp ├── longestpalindromicsubstring.cpp ├── luhn_algo.cpp ├── macros.cpp ├── matrixColumnExchange.cpp ├── matrixFlip.cpp ├── matrix_chain_multiplication.cpp ├── maxAreaHistogram.cpp ├── merge.py ├── mergesort.cpp ├── minCostPath.cpp ├── minMax.cpp ├── mystery_number.cpp ├── number_swap.cpp ├── palindrome.cpp ├── pointer.cpp ├── pointerToPointers.cpp ├── pointers.cpp ├── pointersAndArrays.cpp ├── prime number ├── prims_algo.cpp ├── quadratic roots ├── quicksort.cpp ├── reverse-array.cpp ├── search_2D_Array.cpp ├── search_2D_Array.exe ├── selection.py ├── selectionSort.cpp ├── shortest path visiting all nodes.cpp ├── shortest_superstring.cpp ├── sieveoferatosthenes.cpp ├── simple_text_editor.cpp ├── simplecalculatorswitchcase.cpp ├── smallestpositivemissingnumber.cpp ├── stackUsingLL.cpp ├── sticker_to_spell.cpp ├── structures.cpp ├── threesum.cpp ├── tic tac toe.cpp ├── transposeOfMatrix.cpp ├── tree_dsa.cpp ├── two sum.cpp ├── union_elements.cpp ├── valid binary tree.cpp └── vowel-consonent /.vscode/c_cpp_properties.json: -------------------------------------------------------------------------------- 1 | { 2 | "configurations": [ 3 | { 4 | "name": "windows-gcc-x86", 5 | "includePath": [ 6 | "${workspaceFolder}/**" 7 | ], 8 | "compilerPath": "C:\\MinGW\\bin\\gcc.exe", 9 | "cStandard": "${default}", 10 | "cppStandard": "${default}", 11 | "intelliSenseMode": "windows-gcc-x86", 12 | "compilerArgs": [ 13 | "-Wall", 14 | "-Wextra", 15 | "-Wpedantic" 16 | ] 17 | } 18 | ], 19 | "version": 4 20 | } -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "C/C++ Runner: Debug Session", 6 | "type": "cppdbg", 7 | "request": "launch", 8 | "args": [], 9 | "stopAtEntry": false, 10 | "cwd": "c:\\Users\\GuruNanak\\Desktop\\Hacktober2021-cpp-py", 11 | "environment": [], 12 | "program": "c:\\Users\\GuruNanak\\Desktop\\Hacktober2021-cpp-py\\build\\Debug\\outDebug", 13 | "internalConsoleOptions": "openOnSessionStart", 14 | "MIMode": "gdb", 15 | "miDebuggerPath": "C:\\MinGW\\bin\\gdb.exe", 16 | "externalConsole": false, 17 | "setupCommands": [ 18 | { 19 | "description": "Enable pretty-printing for gdb", 20 | "text": "-enable-pretty-printing", 21 | "ignoreFailures": true 22 | } 23 | ] 24 | } 25 | ] 26 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "C_Cpp_Runner.cCompilerPath": "C:\\MinGW\\bin\\gcc.exe", 3 | "C_Cpp_Runner.cppCompilerPath": "C:\\MinGW\\bin\\g++.exe", 4 | "C_Cpp_Runner.debuggerPath": "C:\\MinGW\\bin\\gdb.exe", 5 | "C_Cpp_Runner.makePath": "C:\\MinGW\\bin\\make.exe", 6 | "C_Cpp_Runner.warnings": [ 7 | "-Wall", 8 | "-Wextra", 9 | "-Wpedantic" 10 | ], 11 | "C_Cpp_Runner.compilerArgs": [], 12 | "C_Cpp_Runner.includePaths": [], 13 | "C_Cpp_Runner.linkerArgs": [], 14 | "C_Cpp_Runner.cStandard": "", 15 | "C_Cpp_Runner.cppStandard": "", 16 | "C_Cpp_Runner.excludeSearch": [], 17 | "C_Cpp_Runner.enableWarnings": true, 18 | "C_Cpp_Runner.warningsAsError": false 19 | } -------------------------------------------------------------------------------- /Armstrong_Number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int number,n; 6 | cout<<"Enter Number:"; 7 | cin>>number; 8 | n=number; 9 | 10 | int sum=0; 11 | while(n!=0) 12 | { 13 | int t=n%10; 14 | n/=10; 15 | sum+=(t*t*t); 16 | 17 | } 18 | if(sum==number) 19 | { 20 | cout<<"Armstrong Number"< 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | void insert(int a[], int n, int ele, int pos) 7 | { 8 | for (int i = n; i >= pos; i--) 9 | { 10 | a[i+1] = a[i]; 11 | } 12 | a[pos] = ele; 13 | } 14 | void del(int a[], int n, int pos) 15 | { 16 | for (int i = pos; i <=n; i++) 17 | a[i] = a[i+1]; 18 | } 19 | 20 | int search(int a[], int n, int key) 21 | { 22 | int t = 0; 23 | for (int i = 0; i < n; i++) 24 | { 25 | if (a[i] == key) 26 | cout << key << " Is At Index : " << i << endl; 27 | return 0; 28 | } 29 | cout << "Not Found In Array "; 30 | return 0; 31 | } 32 | void PRINT(int A[], int n) 33 | { 34 | for (int i = 0; i < n; i++) 35 | { 36 | cout << A[i]<< " "; 37 | } 38 | } 39 | 40 | int main() 41 | { 42 | int i, n, pos, ele, key; 43 | int A[100]; 44 | int c; 45 | int size; 46 | cout << "Enter Size:"; 47 | cin >> n; 48 | cout << "Enter The Elements:" << endl; 49 | for (i = 0; i < n; i++) 50 | { 51 | cin >> A[i]; 52 | } 53 | int iteration = 0; 54 | while (iteration >= 0) 55 | { 56 | cout << "Enter Your Choice"<> c; 60 | if (c == 1) 61 | { 62 | cout<<"Search Element In Array"<> key; 65 | search(A, n, key); 66 | } 67 | if (c == 2) 68 | { 69 | cout<<"Insert Element In Array"<> ele >> pos; 72 | insert(A, n, ele, pos); 73 | n++; 74 | PRINT(A, n); 75 | iteration++; 76 | cout << endl; 77 | } 78 | if (c == 3) 79 | { 80 | cout<<"Delete Element From Array"<> pos; 83 | del(A, n, pos); 84 | n--; 85 | PRINT(A, n); 86 | iteration++; 87 | cout << endl; 88 | } 89 | if (c == 0) 90 | { 91 | return 0; 92 | } 93 | } 94 | return 0; 95 | } 96 | -------------------------------------------------------------------------------- /ArrayComparison.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | int array1[5], array2[5], i, count = 0; 6 | cout << "Enter elements of first Array:\n"; 7 | for(i = 0; i < 5; i++){ 8 | cin >> array1[i]; 9 | } 10 | cout << "Enter elements of second Array:\n"; 11 | for(i = 0; i < 5; i++){ 12 | cin >> array2[i]; 13 | } 14 | for(i = 0; i < 5; i++){ 15 | if(array1[i] != array2[i]){ 16 | cout << "array item does not match at index " << i << ".\n"; 17 | count++; 18 | } 19 | } 20 | if(count == 0){ 21 | cout << "arrays match each other"; 22 | } 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /BFS Tree traversal cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | // This class represents a directed graph using 7 | // adjacency list representation 8 | class Graph 9 | { 10 | int V; // No. of vertices 11 | 12 | // Pointer to an array containing adjacency 13 | // lists 14 | list *adj; 15 | public: 16 | Graph(int V); // Constructor 17 | 18 | // function to add an edge to graph 19 | void addEdge(int v, int w); 20 | 21 | // prints BFS traversal from a given source s 22 | void BFS(int s); 23 | }; 24 | 25 | Graph::Graph(int V) 26 | { 27 | this->V = V; 28 | adj = new list[V]; 29 | } 30 | 31 | void Graph::addEdge(int v, int w) 32 | { 33 | adj[v].push_back(w); // Add w to v’s list. 34 | } 35 | 36 | void Graph::BFS(int s) 37 | { 38 | // Mark all the vertices as not visited 39 | bool *visited = new bool[V]; 40 | for(int i = 0; i < V; i++) 41 | visited[i] = false; 42 | 43 | // Create a queue for BFS 44 | list queue; 45 | 46 | // Mark the current node as visited and enqueue it 47 | visited[s] = true; 48 | queue.push_back(s); 49 | 50 | // 'i' will be used to get all adjacent 51 | // vertices of a vertex 52 | list::iterator i; 53 | 54 | while(!queue.empty()) 55 | { 56 | // Dequeue a vertex from queue and print it 57 | s = queue.front(); 58 | cout << s << " "; 59 | queue.pop_front(); 60 | 61 | // Get all adjacent vertices of the dequeued 62 | // vertex s. If a adjacent has not been visited, 63 | // then mark it visited and enqueue it 64 | for (i = adj[s].begin(); i != adj[s].end(); ++i) 65 | { 66 | if (!visited[*i]) 67 | { 68 | visited[*i] = true; 69 | queue.push_back(*i); 70 | } 71 | } 72 | } 73 | } 74 | 75 | // Driver program to test methods of graph class 76 | int main() 77 | { 78 | // Create a graph given in the above diagram 79 | Graph g(4); 80 | g.addEdge(0, 1); 81 | g.addEdge(0, 2); 82 | g.addEdge(1, 2); 83 | g.addEdge(2, 0); 84 | g.addEdge(2, 3); 85 | g.addEdge(3, 3); 86 | 87 | cout << "Following is Breadth First Traversal " 88 | << "(starting from vertex 2) \n"; 89 | g.BFS(2); 90 | 91 | return 0; 92 | } 93 | -------------------------------------------------------------------------------- /BInaryTreeMaximumPathSum.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int sum = INT_MIN; 15 | int findSum(TreeNode* root){ 16 | if(root==NULL) 17 | return 0; 18 | 19 | int ls = findSum(root->left); 20 | int rs = findSum(root->right); 21 | ls = max(ls,0); 22 | rs = max(rs, 0); 23 | int cs = ls + rs + root->val; 24 | sum = max(sum, cs); 25 | 26 | return max(ls, rs) + root->val; 27 | 28 | } 29 | int maxPathSum(TreeNode* root) { 30 | findSum(root); 31 | return sum; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Backtracking(N-Queen problem).cpp: -------------------------------------------------------------------------------- 1 | #define N 4 2 | #include 3 | #include 4 | 5 | { 6 | for (int i = 0; i < N; i++) { 7 | for (int j = 0; j < N; j++) 8 | printf(" %d ", board[i][j]); 9 | printf("\n"); 10 | } 11 | } 12 | 13 | bool isSafe(int board[N][N], int row, int col) 14 | { 15 | int i, j; 16 | 17 | for (i = 0; i < col; i++) 18 | if (board[row][i]) 19 | return false; 20 | 21 | for (i = row, j = col; i >= 0 && j >= 0; i--, j--) 22 | if (board[i][j]) 23 | return false; 24 | 25 | for (i = row, j = col; j >= 0 && i < N; i++, j--) 26 | if (board[i][j]) 27 | return false; 28 | 29 | return true; 30 | } 31 | 32 | bool solveNQUtil(int board[N][N], int col) 33 | { 34 | if (col >= N) 35 | return true; 36 | 37 | for (int i = 0; i < N; i++) { 38 | 39 | if (isSafe(board, i, col)) { 40 | 41 | board[i][col] = 1; 42 | 43 | if (solveNQUtil(board, col + 1)) 44 | return true; 45 | 46 | board[i][col] = 0; // BACKTRACK 47 | } 48 | } 49 | 50 | return false; 51 | } 52 | 53 | bool solveNQ() 54 | { 55 | int board[N][N] = { { 0, 0, 0, 0 }, 56 | { 0, 0, 0, 0 }, 57 | { 0, 0, 0, 0 }, 58 | { 0, 0, 0, 0 } }; 59 | 60 | if (solveNQUtil(board, 0) == false) { 61 | printf("Solution does not exist"); 62 | return false; 63 | } 64 | 65 | printSolution(board); 66 | return true; 67 | } 68 | 69 | int main() 70 | { 71 | solveNQ(); 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /BinaryInsertionSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int binarySearch(int arr[], int item, int low, int high) { 4 | if (high <= low) 5 | return (item > arr[low])? (low + 1): low; 6 | int mid = (low + high)/2; 7 | if(item == arr[mid]) 8 | return mid+1; 9 | if(item > arr[mid]) 10 | return binarySearch(arr, item, mid+1, high); 11 | return binarySearch(arr, item, low, mid-1); 12 | } 13 | void BinaryInsertionSort(int arr[], int n) { 14 | int i, loc, j, k, selected; 15 | for (i = 1; i < n; ++i) { 16 | j = i - 1; 17 | selected = arr[i]; 18 | loc = binarySearch(arr, selected, 0, j); 19 | while (j >= loc) { 20 | arr[j+1] = arr[j]; 21 | j--; 22 | } 23 | arr[j+1] = selected; 24 | } 25 | } 26 | int main() { 27 | int arr[] = {12, 56, 1, 67, 45, 8, 82, 16, 63, 23}; 28 | int n = sizeof(arr)/sizeof(arr[0]), i; 29 | BinaryInsertionSort(arr, n); 30 | cout<<"Sorted array is : \n"; 31 | for (i = 0; i < n; i++) 32 | cout< 4 | 5 | # 1. Compare x with the middle element. 6 | # 2. If x matches with the middle element, we return the mid index. 7 | # 3. Else If x is greater than the mid element, then x can only lie in the right half subarray after the mid element. So we recur for the right half. 8 | # 4. Else (x is smaller) recur for the left half 9 | 10 | 11 | def binarySearch (arr, l, r, x): 12 | if r >= l: 13 | mid = l + (r - l) // 2 14 | if arr[mid] == x: 15 | return mid 16 | elif arr[mid] > x: 17 | return binarySearch(arr, l, mid-1, x) 18 | else: 19 | return binarySearch(arr, mid + 1, r, x) 20 | else: 21 | return -1 22 | 23 | arr = [ 10, 34, 56, 73, 98 ] 24 | x = 34 25 | 26 | result = binarySearch(arr, 0, len(arr)-1, x) 27 | 28 | if result != -1: 29 | print ("Element is present at index % d" % result) 30 | else: 31 | print ("Element is not present in array") 32 | -------------------------------------------------------------------------------- /BinarySearchIterative.py: -------------------------------------------------------------------------------- 1 | # Algorithm for recursive binary search. 2 | 3 | # Steps (Array should be sorted) -> 4 | 5 | # 1. Compare x with the middle element. 6 | # 2. If x matches with the middle element, we return the mid index. 7 | # 3. Else If x is greater than the mid element, then x can only lie in the right half subarray after the mid element. So we recur for the right half. 8 | # 4. Else (x is smaller) recur for the left half 9 | 10 | def binarySearch(arr, l, r, x): 11 | while l <= r: 12 | mid = l + (r - l) // 2; 13 | if arr[mid] == x: 14 | return mid 15 | elif arr[mid] < x: 16 | l = mid + 1 17 | else: 18 | r = mid - 1 19 | return -1 20 | 21 | 22 | arr = [ 10, 34, 56, 73, 98 ] 23 | x = 34 24 | 25 | result = binarySearch(arr, 0, len(arr)-1, x) 26 | 27 | if result != -1: 28 | print ("Element is present at index % d" % result) 29 | else: 30 | print ("Element is not present in array") 31 | -------------------------------------------------------------------------------- /Breadth_first_search_Traversal.cpp: -------------------------------------------------------------------------------- 1 | //this program is about bfs that is breadth first search in C++ 2 | 3 | // Breadth-first search (BFS) is an algorithm that is used to graph data or searching tree or traversing structures. ... This algorithm selects a single node (initial or source point) in a graph and then visits all the nodes adjacent to the selected node. Remember, BFS accesses these nodes one by one. 4 | 5 | //all header files included 6 | #include 7 | using namespace std; 8 | const int N = 1e5 + 2; 9 | bool vis[N]; 10 | //making an adjacency list 11 | vector adj[N]; 12 | 13 | int main() 14 | { 15 | cout<<"----------------------------THIS PROGRAM IS ABOUT DOING BREADTH-FIRST-SEARCH-ON-GRAPH----------------------------"<> n; 26 | cout << "Enter the number of edges you want in the graph: "; 27 | cin >> m; 28 | 29 | //taking inputs about the edges or the edge between the pair of vertices 30 | cout<> x >> y; 35 | adj[x].push_back(y); 36 | adj[y].push_back(x); 37 | } 38 | //defining a data structure called queue to store the visited vertices 39 | queue q; 40 | q.push(1); 41 | vis[1] = true; 42 | cout<<"The bfs of the graph is as follows: "<::iterator it; 50 | for (it = adj[node].begin(); it != adj[node].end(); it++) 51 | { 52 | if (!vis[*it]) 53 | { 54 | vis[*it] = 1; 55 | q.push(*it); 56 | } 57 | } 58 | } 59 | 60 | return 0; 61 | } -------------------------------------------------------------------------------- /Bubble_Sort.cpp: -------------------------------------------------------------------------------- 1 | /* This is a cpp program to sort an array 2 | using Bubble sort in ascending order , 3 | you can enter the number of elements in the array of your choice 4 | and also the elements of your choice*/ 5 | 6 | #include 7 | using namespace std; 8 | void Bubble(int arr[], int n){ 9 | if (n == 1) 10 | return; 11 | for (int i=0; i arr[i+1]) 13 | swap(arr[i], arr[i+1]); //swap elements 14 | Bubble(arr, n-1); 15 | } 16 | main() { 17 | int n; 18 | cout<<"Enter the number of elements:\n"; 19 | cin>>n; 20 | int arr[n]; 21 | for(int i=0;i>arr[i]; 25 | } 26 | int no = sizeof(arr)/sizeof(arr[0]); 27 | cout << "Sorted Sequence "; 28 | Bubble(arr, no); 29 | for(int i = 0; i temp[b+1]): 7 | temp[b], temp[b+1] = temp[b+1], temp[b] 8 | return temp 9 | array = [10,9,8,3,4] 10 | print("Sorted array is ",bubble_sort(array)) 11 | -------------------------------------------------------------------------------- /CelebrityProblem.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | 6 | // } Driver Code Ends 7 | class Solution 8 | { 9 | public: 10 | priority_queue max_h; 11 | priority_queue,greater> min_h; 12 | int top=9999999; 13 | //Function to insert heap. 14 | void insertHeap(int &num) 15 | { 16 | if(max_h.empty() && min_h.empty() && top==9999999) 17 | top=num; 18 | else if(num>top) 19 | { 20 | if(min_h.size()>max_h.size()) 21 | { 22 | max_h.push(top); 23 | min_h.push(num); 24 | top=min_h.top(); 25 | min_h.pop(); 26 | } 27 | else 28 | { 29 | min_h.push(num); 30 | } 31 | } 32 | else if(nummax_h.size()) 53 | { 54 | max_h.push(num); 55 | } 56 | else 57 | { 58 | min_h.push(num); 59 | } 60 | } 61 | } 62 | 63 | //Function to balance heaps. 64 | void balanceHeaps() 65 | { 66 | 67 | } 68 | 69 | //Function to return Median. 70 | double getMedian() 71 | { 72 | if(max_h.size()==min_h.size()) 73 | return top; 74 | else if(max_h.size()>min_h.size()) 75 | { 76 | int k=max_h.top(); 77 | return ((k+top)*1.0)/2; 78 | } 79 | else { 80 | int k=min_h.top(); 81 | return ((k+top)*1.0)/2; 82 | } 83 | return top; 84 | } 85 | }; 86 | 87 | 88 | // { Driver Code Starts. 89 | 90 | int main() 91 | { 92 | int n, x; 93 | int t; 94 | cin>>t; 95 | while(t--) 96 | { 97 | Solution ob; 98 | cin >> n; 99 | for(int i = 1;i<= n; ++i) 100 | { 101 | cin >> x; 102 | ob.insertHeap(x); 103 | cout << floor(ob.getMedian()) << endl; 104 | } 105 | } 106 | return 0; 107 | } // } Driver Code Ends 108 | -------------------------------------------------------------------------------- /CheckPalindrome.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | #include 6 | 7 | bool helper(char input[], int start, int end) 8 | { 9 | if (start >= end) 10 | { 11 | return true; 12 | } 13 | if (input[start] != input[end]) 14 | { 15 | return false; 16 | } 17 | bool smallcheck = helper(input, start + 1, end - 1); 18 | return smallcheck; 19 | } 20 | 21 | bool checkPalindrome(char input[]) 22 | { 23 | int len = strlen(input); 24 | int start = 0, end = len - 1; 25 | return helper(input, start + 1, end - 1); 26 | } 27 | 28 | int main() 29 | { 30 | char input[50]; 31 | cin >> input; 32 | 33 | if (checkPalindrome(input)) 34 | { 35 | cout << "true" << endl; 36 | } 37 | else 38 | { 39 | cout << "false" << endl; 40 | } 41 | } -------------------------------------------------------------------------------- /Counting Subarrays Problem: -------------------------------------------------------------------------------- 1 | Problem : 2 | 3 | Given an array A of N non-negative numbers and you are also given non-negative number B. 4 | 5 | You need to find the number of subarrays in A having sum less than B. We may assume that there is no overflow. 6 | 7 | 8 | Solution : 9 | 10 | int Solution::solve(vector &A, int B) { 11 | int n = A.size(); 12 | 13 | long long a[n]; 14 | a[0] = A[0]; 15 | 16 | for(int i = 1; i < n; i++){ 17 | a[i] = a[i-1] + A[i]; 18 | } 19 | 20 | int l, e, mid, ans = 0; 21 | for(int i = 0; i < n; i++){ 22 | l = i; 23 | e = n-1; 24 | while(l < e){ 25 | mid = (l+e)/2; 26 | if(a[mid] - a[i] + (long long)A[i] >= B){ 27 | e = mid; 28 | } 29 | else{ 30 | l = mid+1; 31 | } 32 | } 33 | if(a[l] - a[i] + (long long)A[i] >= B) ans += l-i; 34 | else ans += l-i+1; 35 | } 36 | 37 | return ans; 38 | } 39 | -------------------------------------------------------------------------------- /DIGITREM Problem of Codechef: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int t; 7 | cin >> t; 8 | while(t--) 9 | { 10 | long long int a,b; 11 | cin>>a>>b; 12 | string s = to_string(a); 13 | int len = s.size(); 14 | if(b==0) 15 | { 16 | int idx = len; 17 | for(int i =0; i < len; i++) 18 | { 19 | if(s[i]=='0') 20 | { 21 | s[i]='1'; 22 | idx = i; 23 | break; 24 | } 25 | } 26 | for(int i = idx+1; i < len; i++) 27 | { 28 | s[i] = '1'; 29 | } 30 | } 31 | else if(b == 9) 32 | { 33 | if(s[0]==9) 34 | { 35 | for(int i=0;i= 0; j--) 49 | { 50 | if(s[j] <= '7') 51 | { 52 | s[j]++; 53 | idx=j; 54 | goto cvv; 55 | } 56 | } 57 | for(int i=0;i 7 | using namespace std; 8 | 9 | struct node { 10 | int data; 11 | struct node *left, *right; 12 | }; 13 | 14 | struct node* newNode(int data); 15 | 16 | int max(int a, int b) { return (a > b) ? a : b; } 17 | 18 | int height(struct node* node); 19 | 20 | int diameter(struct node* tree) 21 | { 22 | // base case where tree is empty 23 | if (tree == NULL) 24 | return 0; 25 | 26 | // get the height of left and right sub-trees 27 | int lheight = height(tree->left); 28 | int rheight = height(tree->right); 29 | 30 | // get the diameter of left and right sub-trees 31 | int ldiameter = diameter(tree->left); 32 | int rdiameter = diameter(tree->right); 33 | 34 | // Return max of following three 35 | // 1) Diameter of left subtree 36 | // 2) Diameter of right subtree 37 | // 3) Height of left subtree + height of right subtree + 1 38 | return max(lheight + rheight + 1, 39 | max(ldiameter, rdiameter)); 40 | } 41 | 42 | // UTILITY FUNCTIONS TO TEST diameter() FUNCTION 43 | 44 | // The function Compute the "height" of a tree. Height is 45 | // the number f nodes along the longest path from the root 46 | // node down to the farthest leaf node. 47 | int height(struct node* node) 48 | { 49 | // base case tree is empty 50 | if (node == NULL) 51 | return 0; 52 | 53 | // If tree is not empty then height = 1 + max of left 54 | // height and right heights 55 | return 1 + max(height(node->left), height(node->right)); 56 | } 57 | 58 | 59 | struct node* newNode(int data) 60 | { 61 | struct node* node 62 | = (struct node*)malloc(sizeof(struct node)); 63 | node->data = data; 64 | node->left = NULL; 65 | node->right = NULL; 66 | 67 | return (node); 68 | } 69 | 70 | int main(){ 71 | struct node* root = newNode(1); 72 | root->left = newNode(2); 73 | root->right = newNode(3); 74 | root->left->left = newNode(4); 75 | root->left->right = newNode(5); 76 | 77 | cout << "Diameter of the given binary tree is " << 78 | diameter(root); 79 | 80 | return 0; 81 | } 82 | -------------------------------------------------------------------------------- /Dobble_Game.py: -------------------------------------------------------------------------------- 1 | import string 2 | import random 3 | symbbols = [] 4 | symbols = list(string.ascii_letters) 5 | card1 = [0]*5 6 | card2 = [0]*5 7 | pos1 = random.randint(0,4) 8 | pos2 = random.randint(0,4) 9 | print(pos1) 10 | print(pos2) 11 | samesymbol = random.choice(symbols) 12 | symbols.remove(samesymbol) 13 | if(pos1==pos2): 14 | card2[pos1] = samesymbol 15 | card1[pos1] = samesymbol 16 | else: 17 | card1[pos1] = samesymbol 18 | card2[pos2] = samesymbol 19 | card1[pos2] = random.choice(symbols) 20 | symbols.remove(card1[pos2]) 21 | card2[pos1] = random.choice(symbols) 22 | symbols.remove(card2[pos1]) 23 | i = 0 24 | while(i<5): 25 | if(i!=pos1 and i!=pos2): 26 | alphabet1 = random.choice(symbols) 27 | symbols.remove(alphabet1) 28 | alphabet2 = random.choice(symbols) 29 | symbols.remove(alphabet2) 30 | card1[i] = alphabet1 31 | card2[i] = alphabet2 32 | i = i+1 33 | print(card1) 34 | print(card2) 35 | ch = input("Spot the similar symbol = ") 36 | if(ch==samesymbol): 37 | print("Right") 38 | else: 39 | print("Wrong") 40 | -------------------------------------------------------------------------------- /Electricity_Bill.cpp: -------------------------------------------------------------------------------- 1 | // This Is To calculate proper Electricity Billl. 2 | #include 3 | #include 4 | using namespace std; 5 | int main() 6 | { 7 | int x, Fix; 8 | float U, R1, R2, R3, R4, F, E; 9 | clrscr(); 10 | Fix = 30; 11 | F = 1.90; 12 | E = 0.15; 13 | // All The Charges As Per Your Bill Instruction Given At Back Side 14 | // Bill Charges Varies For Limis Of Total Used Units 15 | // U- Unit Used In One Month 16 | // x- The Used Total Units Of Electricity in 2 Months 17 | // Fix- The Fix Amount As Per Home Power Load 18 | // F- The Fuel Charge Per Unit 19 | // E- Electric Duty Per Unit 20 | // R1- Electricity Charge 21 | // R2- Fuel Charge 22 | // R3- Total Electric Duty 23 | // R4- Total Value Of Your Electricity Bill 24 | cout << "Used Unit Of Electricity"; 25 | cin >> x; 26 | U = x / 2; 27 | if (U <= 50) 28 | { 29 | R1 = 3.05 * U; 30 | R2 = x * F; 31 | R3 = (Fix + R1 + R2) * E; 32 | R4 = (Fix + R1 + R2 + R3); 33 | cout<<"Your Electricity Bill Amount Is"< 50 & U < 100) 36 | { 37 | R1 = 2 * ((3.50 * (U - 50)) + 152.5); 38 | R2 = x * F; 39 | R3 = (Fix + R1 + R2) * E; 40 | R4 = (Fix + R1 + R2 + R3); 41 | cout<<"Your Electricity Bill Amount Is"< 100 & U < 250) 44 | { 45 | R1 = 2 * ((4.15 * (U - 100)) + 327.5); 46 | R2 = x * F; 47 | R3 = (Fix + R1 + R2) * E; 48 | R4 = (Fix + R1 + R2 + R3); 49 | cout<<"Your Electricity Bill Amount Is"< 2 | using namespace std; 3 | int equalizeArray(vector arr) 4 | { 5 | vectorx(101,0); 6 | int ctr{}; 7 | for (int i = 0; i < arr.size(); i++) 8 | { 9 | x[arr[i]]++; 10 | } 11 | for (int i = 0; i < 101; i++) 12 | { 13 | if (x[i] > ctr) 14 | { 15 | ctr = x[i]; 16 | } 17 | } 18 | return arr.size()-ctr; 19 | } 20 | int main() 21 | { 22 | #ifndef ONLINE_JUDGE 23 | freopen("input.txt", "r", stdin); 24 | freopen("output.txt", "w", stdout); 25 | #endif 26 | int n; 27 | cin >> n; 28 | vector arr(n); 29 | for (int i = 0; i < n; i++) 30 | { 31 | cin >> arr[i]; 32 | } 33 | cout << equalizeArray(arr); 34 | 35 | return 0; 36 | } -------------------------------------------------------------------------------- /Factorial.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | We have to take input from user and then have to calculate its factorial , but we have a restriction, 3 | we have to use recursion concept for calculating Factorial of entered numbere 4 | */ 5 | #include 6 | using namespace std; 7 | int factorial(int x){ 8 | if(x>1) 9 | x=x*(factorial(x-1)); 10 | else 11 | return 1; 12 | } 13 | 14 | int main(){ 15 | int number; 16 | cout<<"Enter a number: "; 17 | cin>>number; 18 | if(number>0){ 19 | cout<<"Factoral of "< 2 | using namespace std; 3 | 4 | 5 | 6 | // } Driver Code Ends 7 | class Solution 8 | { 9 | public: 10 | priority_queue max_h; 11 | priority_queue,greater> min_h; 12 | int top=9999999; 13 | //Function to insert heap. 14 | void insertHeap(int &num) 15 | { 16 | if(max_h.empty() && min_h.empty() && top==9999999) 17 | top=num; 18 | else if(num>top) 19 | { 20 | if(min_h.size()>max_h.size()) 21 | { 22 | max_h.push(top); 23 | min_h.push(num); 24 | top=min_h.top(); 25 | min_h.pop(); 26 | } 27 | else 28 | { 29 | min_h.push(num); 30 | } 31 | } 32 | else if(nummax_h.size()) 53 | { 54 | max_h.push(num); 55 | } 56 | else 57 | { 58 | min_h.push(num); 59 | } 60 | } 61 | } 62 | 63 | //Function to balance heaps. 64 | void balanceHeaps() 65 | { 66 | 67 | } 68 | 69 | //Function to return Median. 70 | double getMedian() 71 | { 72 | if(max_h.size()==min_h.size()) 73 | return top; 74 | else if(max_h.size()>min_h.size()) 75 | { 76 | int k=max_h.top(); 77 | return ((k+top)*1.0)/2; 78 | } 79 | else { 80 | int k=min_h.top(); 81 | return ((k+top)*1.0)/2; 82 | } 83 | return top; 84 | } 85 | }; 86 | 87 | 88 | // { Driver Code Starts. 89 | 90 | int main() 91 | { 92 | int n, x; 93 | int t; 94 | cin>>t; 95 | while(t--) 96 | { 97 | Solution ob; 98 | cin >> n; 99 | for(int i = 1;i<= n; ++i) 100 | { 101 | cin >> x; 102 | ob.insertHeap(x); 103 | cout << floor(ob.getMedian()) << endl; 104 | } 105 | } 106 | return 0; 107 | } // } Driver Code Ends 108 | -------------------------------------------------------------------------------- /Finding missing element.cpp: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | 3 | Online C++ Compiler. 4 | Code, Compile, Run and Debug C++ program online. 5 | Write your code in this editor and press "Run" button to compile and execute it. 6 | 7 | *******************************************************************************/ 8 | 9 | #include 10 | 11 | using namespace std; 12 | 13 | int main() 14 | { 15 | int n,i; 16 | int arr[100]; 17 | cin>>n; 18 | for(i=0;i>arr[i]; 21 | } 22 | 23 | 24 | int f,l,diff=0; 25 | f=arr[0]; 26 | diff=f-0; 27 | for(i=0;i 3 | using namespace std; 4 | 5 | // Number of vertices in the graph 6 | #define V 4 7 | 8 | /* Define Infinite as a large enough 9 | value.This value will be used for 10 | vertices not connected to each other */ 11 | #define INF 99999 12 | 13 | // A function to print the solution matrix 14 | void printSolution(int dist[][V]); 15 | 16 | // Solves the all-pairs shortest path 17 | // problem using Floyd Warshall algorithm 18 | void floydWarshall(int graph[][V]) 19 | { 20 | /* dist[][] will be the output matrix 21 | that will finally have the shortest 22 | distances between every pair of vertices */ 23 | int dist[V][V], i, j, k; 24 | 25 | /* Initialize the solution matrix same 26 | as input graph matrix. Or we can say 27 | the initial values of shortest distances 28 | are based on shortest paths considering 29 | no intermediate vertex. */ 30 | for (i = 0; i < V; i++) 31 | for (j = 0; j < V; j++) 32 | dist[i][j] = graph[i][j]; 33 | 34 | /* Add all vertices one by one to 35 | the set of intermediate vertices. 36 | ---> Before start of an iteration, 37 | we have shortest distances between all 38 | pairs of vertices such that the 39 | shortest distances consider only the 40 | vertices in set {0, 1, 2, .. k-1} as 41 | intermediate vertices. 42 | ----> After the end of an iteration, 43 | vertex no. k is added to the set of 44 | intermediate vertices and the set becomes {0, 1, 2, .. 45 | k} */ 46 | for (k = 0; k < V; k++) { 47 | // Pick all vertices as source one by one 48 | for (i = 0; i < V; i++) { 49 | // Pick all vertices as destination for the 50 | // above picked source 51 | for (j = 0; j < V; j++) { 52 | // If vertex k is on the shortest path from 53 | // i to j, then update the value of 54 | // dist[i][j] 55 | if (dist[i][j] > (dist[i][k] + dist[k][j]) 56 | && (dist[k][j] != INF 57 | && dist[i][k] != INF)) 58 | dist[i][j] = dist[i][k] + dist[k][j]; 59 | } 60 | } 61 | } 62 | 63 | // Print the shortest distance matrix 64 | printSolution(dist); 65 | } 66 | 67 | /* A utility function to print solution */ 68 | void printSolution(int dist[][V]) 69 | { 70 | cout << "The following matrix shows the shortest " 71 | "distances" 72 | " between every pair of vertices \n"; 73 | for (int i = 0; i < V; i++) { 74 | for (int j = 0; j < V; j++) { 75 | if (dist[i][j] == INF) 76 | cout << "INF" 77 | << " "; 78 | else 79 | cout << dist[i][j] << " "; 80 | } 81 | cout << endl; 82 | } 83 | } 84 | 85 | // Driver code 86 | int main() 87 | { 88 | /* Let us create the following weighted graph 89 | 10 90 | (0)------->(3) 91 | | /|\ 92 | 5 | | 93 | | | 1 94 | \|/ | 95 | (1)------->(2) 96 | 3 */ 97 | int graph[V][V] = { { 0, 5, INF, 10 }, 98 | { INF, 0, 3, INF }, 99 | { INF, INF, 0, 1 }, 100 | { INF, INF, INF, 0 } }; 101 | 102 | // Print the solution 103 | floydWarshall(graph); 104 | return 0; 105 | } 106 | -------------------------------------------------------------------------------- /GenerateAllSubsetsofArray.cpp: -------------------------------------------------------------------------------- 1 | 2 | /*Given an integer array nums of unique elements, return all possible subsets (the power set). 3 | 4 | The solution set must not contain duplicate subsets. Return the solution in any order. 5 | 6 | Example 1: 7 | 8 | Input: nums = [1,2,3] 9 | Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] 10 | Example 2: 11 | 12 | Input: nums = [0] 13 | Output: [[],[0]]*/ 14 | 15 | #include 16 | #include 17 | using namespace std; 18 | 19 | vector> subsets(vector& nums) { 20 | 21 | vector>ans; 22 | int n = nums.size(); 23 | 24 | for(int i=0;i<(1<v; 27 | for(int j=0;j>n; 45 | 46 | vectorinput; 47 | 48 | for(int i=0;i>ele; 52 | input.push_back(ele); 53 | } 54 | 55 | vector> ans = subsets(input); 56 | 57 | for(int i=0;i 2 | using namespace std; 3 | 4 | // function to heapify the tree 5 | void heapify(int arr[], int n, int root) 6 | { 7 | int largest = root; // root is the largest element 8 | int l = 2*root + 1; // left = 2*root + 1 9 | int r = 2*root + 2; // right = 2*root + 2 10 | 11 | // If left child is larger than root 12 | if (l < n && arr[l] > arr[largest]) 13 | largest = l; 14 | 15 | // If right child is larger than largest so far 16 | if (r < n && arr[r] > arr[largest]) 17 | largest = r; 18 | 19 | // If largest is not root 20 | if (largest != root) 21 | { 22 | //swap root and largest 23 | swap(arr[root], arr[largest]); 24 | 25 | // Recursively heapify the sub-tree 26 | heapify(arr, n, largest); 27 | } 28 | } 29 | 30 | // implementing heap sort 31 | void heapSort(int arr[], int n) 32 | { 33 | // build heap 34 | for (int i = n / 2 - 1; i >= 0; i--) 35 | heapify(arr, n, i); 36 | 37 | // extracting elements from heap one by one 38 | for (int i=n-1; i>=0; i--) 39 | { 40 | // Move current root to end 41 | swap(arr[0], arr[i]); 42 | 43 | // again call max heapify on the reduced heap 44 | heapify(arr, i, 0); 45 | } 46 | } 47 | 48 | /* print contents of array - utility function */ 49 | void displayArray(int arr[], int n) 50 | { 51 | for (int i=0; i 2 | using namespace std; 3 | 4 | int main(){ 5 | int x[100] , input, i = 0, j = 0; 6 | cout << "enter array elements (-1 will terminate)\n"; 7 | while(input != -1){ 8 | cin >> input; 9 | x[i] = input; 10 | i++; 11 | } 12 | cout << "Entered Elements are:\n"; 13 | while(x[j] != -1){ 14 | cout << x[j] << "\n"; 15 | j++; 16 | } 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /Insertion sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void display(int *array, int size) { 4 | for(int i = 0; i 0 && array[j-1]>key) { 14 | array[j] = array[j-1]; 15 | j--; 16 | } 17 | array[j] = key; 18 | } 19 | } 20 | int main() { 21 | int n; 22 | cout << "Enter the number of elements: "; 23 | cin >> n; 24 | int arr[n]; 25 | cout << "Enter elements:" << endl; 26 | for(int i = 0; i> arr[i]; 28 | } 29 | insertionSort(arr, n); 30 | cout << "Array after Sorting: "; 31 | display(arr, n); 32 | } 33 | -------------------------------------------------------------------------------- /InsertionSort.cpp: -------------------------------------------------------------------------------- 1 | Insertion sort Implementation in C++: 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | //member functions declaration 9 | void insertionSort(int arr[], int length); 10 | void printArray(int array[], int size); 11 | 12 | // main function 13 | int main() 14 | { 15 | int array[6] = {5, 1, 6, 2, 4, 3}; 16 | // calling insertion sort function to sort the array 17 | insertionSort(array, 6); 18 | return 0; 19 | } 20 | 21 | void insertionSort(int arr[], int length) 22 | { 23 | int i, j, key; 24 | for (i = 1; i < length; i++) 25 | { 26 | key = arr[i]; 27 | j = i-1; 28 | 29 | while (j >= 0 && arr[j] >key) 30 | { 31 | arr[j+1] = arr[j]; 32 | j--; 33 | } 34 | arr[j +1] = key; 35 | 36 | } 37 | cout << "Sorted Array: "; 38 | // print the sorted array 39 | printArray(arr, length); 40 | } 41 | 42 | // function to print the given array 43 | void printArray(int array[], int size) 44 | { 45 | int j; 46 | for (j = 0; j < size; j++) 47 | { 48 | cout <<" "<< array[j]; 49 | } 50 | cout << endl; 51 | } 52 | -------------------------------------------------------------------------------- /Interpolation.py: -------------------------------------------------------------------------------- 1 | def intpolsearch(values,x ): 2 | idx0 = 0 3 | idxn = (len(values) - 1) 4 | while idx0 <= idxn and x >= values[idx0] and x <= values[idxn]: 5 | # Find the mid point 6 | mid = idx0 +\ 7 | int(((float(idxn - idx0)/( values[idxn] - values[idx0])) 8 | * ( x - values[idx0]))) 9 | # Compare the value at mid point with search value 10 | if values[mid] == x: 11 | return "Found "+str(x)+" at index "+str(mid) 12 | if values[mid] < x: 13 | idx0 = mid + 1 14 | return "Searched element not in the list" 15 | 16 | l = [2, 6, 11, 19, 27, 31, 45, 121] 17 | print(intpolsearch(l, 2)) -------------------------------------------------------------------------------- /InterpolationSearch.py: -------------------------------------------------------------------------------- 1 | # Algorithm for InterPolation Search 2 | 3 | # Steps -> 4 | 5 | # Formula: 6 | 7 | # The idea of formula is to return higher value of pos 8 | # when element to be searched is closer to arr[hi]. And 9 | # smaller value when closer to arr[lo] 10 | # pos = lo + [ (x-arr[lo])*(hi-lo) / (arr[hi]-arr[Lo]) ] 11 | 12 | # arr[] ==> Array where elements need to be searched 13 | # x ==> Element to be searched 14 | # lo ==> Starting index in arr[] 15 | # hi ==> Ending index in arr[] 16 | 17 | # Rest of the Interpolation algorithm is the same except the above partition logic. 18 | # Step1: In a loop, calculate the value of 'pos' using the probe position formula. 19 | # Step2: If it is a match, return the index of the item, and exit. 20 | # Step3: If the item is less than arr[pos], calculate the probe position of the left sub-array. Otherwise calculate the same in the right sub-array. 21 | # Step4: Repeat until a match is found or the sub-array reduces to zero. 22 | # Below is the implementation of algorithm. 23 | 24 | # Python3 program to implement 25 | # interpolation search 26 | # with recursion 27 | 28 | # If x is present in arr[0..n-1], then 29 | # returns index of it, else returns -1. 30 | 31 | 32 | def interpolationSearch(arr, lo, hi, x): 33 | if (lo <= hi and x >= arr[lo] and x <= arr[hi]): 34 | pos = lo + ((hi - lo) // (arr[hi] - arr[lo]) * (x - arr[lo])) 35 | if arr[pos] == x: 36 | return pos 37 | if arr[pos] < x: 38 | return interpolationSearch(arr, pos + 1, hi, x) 39 | if arr[pos] > x: 40 | return interpolationSearch(arr, lo, pos - 1, x) 41 | return -1 42 | 43 | arr = [10, 12, 13, 16, 18, 19, 20, 21, 22, 23, 24, 33, 35, 42, 47] 44 | n = len(arr) 45 | 46 | x = 18 47 | index = interpolationSearch(arr, 0, n - 1, x) 48 | 49 | if index != -1: 50 | print("Element found at index", index) 51 | else: 52 | print("Element not found") -------------------------------------------------------------------------------- /Jump_search.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to implement Jump Search 2 | 3 | #include 4 | using namespace std; 5 | 6 | int jumpSearch(int arr[], int x, int n) 7 | { 8 | // Finding block size to be jumped 9 | int step = sqrt(n); 10 | 11 | // Finding the block where element is 12 | // present (if it is present) 13 | int prev = 0; 14 | while (arr[min(step, n)-1] < x) 15 | { 16 | prev = step; 17 | step += sqrt(n); 18 | if (prev >= n) 19 | return -1; 20 | } 21 | 22 | // Doing a linear search for x in block 23 | // beginning with prev. 24 | while (arr[prev] < x) 25 | { 26 | prev++; 27 | 28 | // If we reached next block or end of 29 | // array, element is not present. 30 | if (prev == min(step, n)) 31 | return -1; 32 | } 33 | // If element is found 34 | if (arr[prev] == x) 35 | return prev; 36 | 37 | return -1; 38 | } 39 | 40 | // Driver program to test function 41 | int main() 42 | { 43 | int arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 44 | 34, 55, 89, 144, 233, 377, 610 }; 45 | int x = 55; 46 | int n = sizeof(arr) / sizeof(arr[0]); 47 | 48 | // Find the index of 'x' using Jump Search 49 | int index = jumpSearch(arr, x, n); 50 | 51 | // Print the index where 'x' is located 52 | cout << "\nNumber " << x << " is at index " << index; 53 | return 0; 54 | } 55 | 56 | -------------------------------------------------------------------------------- /KClosestPointToOrigin.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Point { 4 | public: 5 | int x; 6 | int y; 7 | int distance; 8 | Point(int x, int y, int distance) { 9 | this->x = x; 10 | this->y = y; 11 | this->distance = distance; 12 | } 13 | }; 14 | 15 | struct comparator { 16 | bool operator() (Point &a, Point &b) { 17 | return (b.distance > a.distance); 18 | } 19 | }; 20 | 21 | class KClosestPointToOrigin { 22 | public: 23 | 24 | vector> kClosest(vector>& points, int k) { 25 | priority_queue, comparator> maxHeap; 26 | 27 | for(int i = 0; i < k; i++) { 28 | int x = points[i][0]; 29 | int y = points[i][1]; 30 | int distance = x*x + y*y; 31 | Point p = Point(x, y, distance); 32 | maxHeap.push(p); 33 | } 34 | 35 | for(int i = k; i < points.size(); i++) { 36 | 37 | int x = points[i][0]; 38 | int y = points[i][1]; 39 | int distance = x*x + y*y; 40 | if(distance < maxHeap.top().distance) { 41 | maxHeap.pop(); 42 | maxHeap.push(Point(x, y, distance)); 43 | } 44 | } 45 | 46 | vector> ans(k,{0,0}); 47 | int i = 0; 48 | while(!maxHeap.empty()) { 49 | Point p = maxHeap.top(); 50 | maxHeap.pop(); 51 | ans[i][0] = p.x; 52 | ans[i][1] = p.y; 53 | i += 1; 54 | } 55 | return ans; 56 | 57 | } 58 | }; 59 | -------------------------------------------------------------------------------- /KMP_algo.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for implementation of KMP pattern searching algorithm 2 | #include 3 | 4 | void computeLPSArray(char* pat, int M, int* lps); 5 | 6 | void KMPSearch(char* pat, char* txt) 7 | { 8 | int M = strlen(pat); 9 | int N = strlen(txt); 10 | 11 | int lps[M]; 12 | 13 | computeLPSArray(pat, M, lps); 14 | 15 | int i = 0; 16 | int j = 0; 17 | while (i < N) { 18 | if (pat[j] == txt[i]) { 19 | j++; 20 | i++; 21 | } 22 | 23 | if (j == M) { 24 | printf("Found pattern at index %d ", i - j); 25 | j = lps[j - 1]; 26 | } 27 | 28 | else if (i < N && pat[j] != txt[i]) { 29 | if (j != 0) 30 | j = lps[j - 1]; 31 | else 32 | i = i + 1; 33 | } 34 | } 35 | } 36 | 37 | void computeLPSArray(char* pat, int M, int* lps) 38 | { 39 | int len = 0; 40 | 41 | lps[0] = 0; // lps[0] is always 0 42 | 43 | int i = 1; 44 | while (i < M) { 45 | if (pat[i] == pat[len]) { 46 | len++; 47 | lps[i] = len; 48 | i++; 49 | } 50 | else 51 | { 52 | if (len != 0) { 53 | len = lps[len - 1]; 54 | 55 | } 56 | else 57 | { 58 | lps[i] = 0; 59 | i++; 60 | } 61 | } 62 | } 63 | } 64 | 65 | int main() 66 | { 67 | char txt[] = "ABABDABACDABABCABAB"; 68 | char pat[] = "ABABCABAB"; 69 | KMPSearch(pat, txt); 70 | return 0; 71 | } 72 | 73 | //Output: 74 | //Found pattern at index 10 75 | -------------------------------------------------------------------------------- /Kadane's.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int maxSubArraySum(int a[], int size) 6 | { 7 | int max_so_far = INT_MIN, max_ending_here = 0; 8 | 9 | for (int i = 0; i < size; i++) 10 | { 11 | max_ending_here = max_ending_here + a[i]; 12 | if (max_so_far < max_ending_here) 13 | max_so_far = max_ending_here; 14 | 15 | if (max_ending_here < 0) 16 | max_ending_here = 0; 17 | } 18 | return max_so_far; 19 | } 20 | int main() 21 | { 22 | int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; 23 | int n = sizeof(a)/sizeof(a[0]); 24 | int max_sum = maxSubArraySum(a, n); 25 | cout << "Maximum contiguous sum is " << max_sum; 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /KadaneAlgo.cpp: -------------------------------------------------------------------------------- 1 | long long maxSubarraySum(int arr[], int n){ 2 | 3 | // Your code here 4 | long long sum = arr[0],best = arr[0], x; 5 | for(int i = 1;i 2 | #include 3 | #include 4 | 5 | int max(int a, int b) { return (a > b) ? a: b; } 6 | int knapSack(int W, int wt[], int val[], int n){ 7 | if (n == 0 || W == 0) 8 | return 0; 9 | if (wt[n - 1] > W) 10 | return knapSack(W, wt, val, n - 1); 11 | else 12 | return max(val[n - 1]+ knapSack(W - wt[n - 1],wt, val, n - 1),knapSack(W, wt, val, n - 1)); 13 | } 14 | 15 | int main() 16 | { 17 | clrscr(); 18 | int val[100]; 19 | int w[100]; 20 | int n; 21 | cout<<"Enter the number of elements"<>n; 23 | cout<<"Enter the weights and values"<>w[i]; 26 | cin>>val[i]; 27 | } 28 | int W; 29 | cout<<"Enter the maximum weight"<>W; 31 | cout << knapSack(W, w, val, n); 32 | getch(); 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /LCAofBST.cpp: -------------------------------------------------------------------------------- 1 | //cpp program 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | template 7 | class BinaryTreeNode { 8 | public: 9 | T data; 10 | BinaryTreeNode* left; 11 | BinaryTreeNode* right; 12 | 13 | BinaryTreeNode(T data) { 14 | this->data = data; 15 | left = NULL; 16 | right = NULL; 17 | } 18 | ~BinaryTreeNode() { 19 | if (left) delete left; 20 | if (right) delete right; 21 | } 22 | }; 23 | 24 | 25 | int lcaInBST(BinaryTreeNode* root , int val1 , int val2){ 26 | if(root==NULL) 27 | return 0; 28 | if(root->data==val1 || root->data==val2) 29 | return root->data; 30 | int a=lcaInBST(root->left,val1,val2); 31 | int b=lcaInBST(root->right,val1,val2); 32 | if(a==0 && b!=0) 33 | return b; 34 | else if(a!=0 && b==0) 35 | return a; 36 | else if(a==0 && b==0) 37 | return 0; 38 | else 39 | return root->data; 40 | } 41 | 42 | 43 | BinaryTreeNode* takeInput() { 44 | int rootData; 45 | 46 | cin >> rootData; 47 | if (rootData == -1) { 48 | return NULL; 49 | } 50 | BinaryTreeNode* root = new BinaryTreeNode(rootData); 51 | queue*> q; 52 | q.push(root); 53 | while (!q.empty()) { 54 | BinaryTreeNode* currentNode = q.front(); 55 | q.pop(); 56 | int leftChild, rightChild; 57 | 58 | cin >> leftChild; 59 | if (leftChild != -1) { 60 | BinaryTreeNode* leftNode = new BinaryTreeNode(leftChild); 61 | currentNode->left = leftNode; 62 | q.push(leftNode); 63 | } 64 | 65 | cin >> rightChild; 66 | if (rightChild != -1) { 67 | BinaryTreeNode* rightNode = 68 | new BinaryTreeNode(rightChild); 69 | currentNode->right = rightNode; 70 | q.push(rightNode); 71 | } 72 | } 73 | 74 | return root; 75 | } 76 | 77 | int main() { 78 | BinaryTreeNode* root = takeInput(); 79 | int a, b; 80 | cin >> a >> b; 81 | cout << lcaInBST(root, a, b); 82 | delete root; 83 | } 84 | -------------------------------------------------------------------------------- /Largest-sum-contiguous-subarray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | // } Driver Code Ends 6 | class Solution{ 7 | public: 8 | // arr: input array 9 | // n: size of array 10 | //Function to find the sum of contiguous subarray with maximum sum. 11 | long long maxSubarraySum(int arr[], int n){ 12 | 13 | // Your code here 14 | long long int max_so_far=arr[0]; 15 | long long int max_ending_here=arr[0]; 16 | for(int i=1;iarr[i]) 19 | { 20 | max_ending_here=max_ending_here+arr[i]; 21 | 22 | } 23 | else 24 | max_ending_here=arr[i]; 25 | max_so_far=max(max_so_far,max_ending_here); 26 | } 27 | return max_so_far; 28 | 29 | } 30 | }; 31 | 32 | // { Driver Code Starts. 33 | 34 | int main() 35 | { 36 | int t,n; 37 | 38 | cin>>t; //input testcases 39 | while(t--) //while testcases exist 40 | { 41 | 42 | cin>>n; //input size of array 43 | 44 | int a[n]; 45 | 46 | for(int i=0;i>a[i]; //inputting elements of array 48 | 49 | Solution ob; 50 | 51 | cout << ob.maxSubarraySum(a, n) << endl; 52 | } 53 | } 54 | // } Driver Code Ends -------------------------------------------------------------------------------- /LinearSearch.py: -------------------------------------------------------------------------------- 1 | # Algorithm for Linear Search in Python 2 | 3 | # Steps -> 4 | # 1. Start from the leftmost element of arr[] and one by one compare it with each element of arr[]. 5 | # 2. If element matches with an element, return the index. 6 | # 3. If element does not match with any of elements, return -1. 7 | 8 | array = [8, 14, 15, 17, 20, 2, 4, 6, 9, 18] 9 | 10 | def linearSearch(array, key): 11 | for i in range(len(array)): 12 | if array[i] == key: 13 | return i 14 | return -1 15 | 16 | x = linearSearch(array, 4) 17 | print(x) -------------------------------------------------------------------------------- /Longest_Arithmetic_sum.cpp: -------------------------------------------------------------------------------- 1 | // WAP To Find The Length Of The Longest Arithmetic Array In Given Array. 2 | 3 | // An arithmetic array is an array that contains at least two integers and 4 | // the differences between consecutive integers are equal. 5 | // pd -> Common Past Difference 6 | // curr -> Current Length of Array 7 | // max -> length Of The Arithmetic Array. 8 | // Example:- 2 3 4 5 3 1 -1 -3 -5 -7 9 | // For Above Example {2,3,4,5} & {5,3,1,-1,-3,-5,-7} Are in Arithmetic Sequence. 10 | // Length Of Longest Arithmetic Array is:- 7 11 | 12 | #include 13 | #include 14 | #include 15 | using namespace std; 16 | 17 | int main() 18 | { 19 | int n; 20 | cout<<"Enter Length Of The Array:-"; 21 | cin>> n; 22 | int A[n]; 23 | cout<< "Enter The Elements Of The Array."<> A[i]; 27 | } 28 | int pd; 29 | int curr=1; // First Element Always Count In Arithmetic Array. 30 | int ans=0; 31 | pd= A[1]-A[0]; 32 | for(int i=0;i int: 7 | 8 | m = len(text2) 9 | n = len(text1) 10 | 11 | memo = [[0 for j in range(m+1)] for i in range(n+1)] 12 | 13 | for i in range(n-1,-1,-1): 14 | for j in range(m-1,-1,-1): 15 | 16 | if text1[i] == text2[j]: 17 | memo[i][j] = 1 + memo[i+1][j+1] 18 | 19 | else: 20 | memo[i][j] = max(memo[i+1][j],memo[i][j+1]) 21 | 22 | return memo[0][0] 23 | -------------------------------------------------------------------------------- /MaximumAreaofIsland.cpp: -------------------------------------------------------------------------------- 1 | /*Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. 2 | 3 | Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.) 4 | 5 | Example 1: 6 | 7 | [[0,0,1,0,0,0,0,1,0,0,0,0,0], 8 | [0,0,0,0,0,0,0,1,1,1,0,0,0], 9 | [0,1,1,0,1,0,0,0,0,0,0,0,0], 10 | [0,1,0,0,1,1,0,0,1,0,1,0,0], 11 | [0,1,0,0,1,1,0,0,1,1,1,0,0], 12 | [0,0,0,0,0,0,0,0,0,0,1,0,0], 13 | [0,0,0,0,0,0,0,1,1,1,0,0,0], 14 | [0,0,0,0,0,0,0,1,1,0,0,0,0]] 15 | 16 | Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally. 17 | 18 | Example 2: 19 | 20 | [[0,0,0,0,0,0,0,0]] 21 | 22 | Given the above grid, return 0. 23 | 24 | Note: The length of each dimension in the given grid does not exceed 50.*/ 25 | 26 | 27 | // mark as 2 for visited 28 | // time=0(nm) 29 | // space=0(1) 30 | 31 | #include 32 | #include 33 | using namespace std; 34 | 35 | void dfs(vector>& grid,int row,int col,int n,int m,int &temp) 36 | { 37 | if (row<0 || row>=n || col<0 || col>=m || grid[row][col]==2 || grid[row][col]==0) 38 | { 39 | return; 40 | } 41 | grid[row][col]=2; // if not 2 nor 0 it will be 1,so make it visited by marking 2 42 | temp+=1; // increase area by 1 43 | dfs(grid,row+1,col,n,m,temp);//traversing all the four directions of each cell 44 | dfs(grid,row-1,col,n,m,temp); 45 | dfs(grid,row,col+1,n,m,temp); 46 | dfs(grid,row,col-1,n,m,temp); 47 | } 48 | 49 | int maxAreaOfIsland(vector>& grid) { 50 | int n=grid.size(); 51 | int m=grid[0].size(); 52 | int ans=0; 53 | for(int i=0;i>row>>col; 74 | 75 | vector> grid(row , vector (col)); 76 | 77 | for(int i=0;i>grid[i][j]; 82 | } 83 | } 84 | 85 | cout<<"Maximum area of Island : "< 4 | using namespace std; 5 | 6 | /* This function returns median of ar1[] and ar2[]. 7 | Assumption in this function: 8 | Both ar1[] and ar2[] are sorted arrays */ 9 | int getMedian(int ar1[], int ar2[], int n, int m) 10 | { 11 | int i = 0; /* Current index of input array ar1[] */ 12 | int j = 0; /* Current index of input array ar2[] */ 13 | int count; 14 | int m1 = -1, m2 = -1; 15 | 16 | // Since there are (n+m) elements, 17 | // There are following two cases 18 | // if n+m is odd then the middle 19 | //index is median i.e. (m+n)/2 20 | if((m + n) % 2 == 1) 21 | { 22 | for (count = 0; count <= (n + m)/2; count++) 23 | { 24 | if(i != n && j != m) 25 | { 26 | m1 = (ar1[i] > ar2[j]) ? ar2[j++] : ar1[i++]; 27 | } 28 | else if(i < n) 29 | { 30 | m1 = ar1[i++]; 31 | } 32 | // for case when j ar2[j]) ? ar2[j++] : ar1[i++]; 52 | } 53 | else if(i < n) 54 | { 55 | m1 = ar1[i++]; 56 | } 57 | // for case when j 2 | using namespace std; 3 | 4 | // Merge two subarrays of array[]. 5 | // First subarray : arr[begin..mid] 6 | // Second subarray : arr[mid+1..end] 7 | void merge(int array[], int const left, int const mid, int const right) 8 | { 9 | auto const subArrayOne = mid - left + 1; 10 | auto const subArrayTwo = right - mid; 11 | 12 | // Create temp arrays 13 | auto *leftArray = new int[subArrayOne], 14 | *rightArray = new int[subArrayTwo]; 15 | 16 | // Copy data to temp array leftArray[] and rightArray[] 17 | for (auto i = 0; i < subArrayOne; i++) 18 | leftArray[i] = array[left + i]; 19 | for (auto j = 0; j < subArrayTwo; j++) 20 | rightArray[j] = array[mid + 1 + j]; 21 | 22 | auto indexOfSubArrayOne = 0, // Initial index of first sub-array 23 | indexOfSubArrayTwo = 0; // Initial index of second sub-array 24 | int indexOfMergedArray = left; // Initial index of merged array 25 | 26 | // Merge the temp arrays back into array[left..right] 27 | while (indexOfSubArrayOne < subArrayOne && indexOfSubArrayTwo < subArrayTwo) { 28 | if (leftArray[indexOfSubArrayOne] <= rightArray[indexOfSubArrayTwo]) { 29 | array[indexOfMergedArray] = leftArray[indexOfSubArrayOne]; 30 | indexOfSubArrayOne++; 31 | } 32 | else { 33 | array[indexOfMergedArray] = rightArray[indexOfSubArrayTwo]; 34 | indexOfSubArrayTwo++; 35 | } 36 | indexOfMergedArray++; 37 | } 38 | // Copying the remaining elements of left[] 39 | while (indexOfSubArrayOne < subArrayOne) { 40 | array[indexOfMergedArray] = leftArray[indexOfSubArrayOne]; 41 | indexOfSubArrayOne++; 42 | indexOfMergedArray++; 43 | } 44 | // Copy the remaining elements of right[] 45 | while (indexOfSubArrayTwo < subArrayTwo) { 46 | array[indexOfMergedArray] = rightArray[indexOfSubArrayTwo]; 47 | indexOfSubArrayTwo++; 48 | indexOfMergedArray++; 49 | } 50 | } 51 | 52 | // begin is for left index and end is 53 | // right index of the sub-array 54 | // of arr to be sorted */ 55 | void mergeSort(int array[], int const begin, int const end) 56 | { 57 | if (begin >= end) 58 | return; 59 | 60 | auto mid = begin + (end - begin) / 2; 61 | mergeSort(array, begin, mid); 62 | mergeSort(array, mid + 1, end); 63 | merge(array, begin, mid, end); 64 | } 65 | 66 | // print array 67 | void printArray(int arr[], int size) 68 | { 69 | for (auto i = 0; i < size; i++) 70 | cout << arr[i] << " "; 71 | } 72 | 73 | 74 | int main() 75 | { 76 | int arr[] = { 21, 31, 13, 4, 8, 9 }; 77 | auto arr_size = sizeof(arr) / sizeof(arr[0]); 78 | 79 | cout << "Array: \n"; 80 | printArray(arr, arr_size); 81 | 82 | mergeSort(arr, 0, arr_size - 1); 83 | 84 | cout << "\nSorted array: \n"; 85 | printArray(arr, arr_size); 86 | return 0; 87 | } 88 | 89 | -------------------------------------------------------------------------------- /MergeSort_using_pragma_openmp.cpp: -------------------------------------------------------------------------------- 1 | 2 | #pragma GCC optimization ("O3") 3 | #pragma GCC optimization ("unroll-loops") 4 | #include 5 | using namespace std; 6 | typedef long long int ll; //g++ ll.cpp -o ll.exe 7 | typedef long double ld; 8 | typedef pair iii; //all elements to 0 .\ll.exe 9 | const ll mod =1e9+7; 10 | 11 | void mergeSortRecursive(vector& v, unsigned long left, unsigned long right) 12 | { 13 | if (left < right) 14 | { 15 | if (right-left >= 8) 16 | { 17 | unsigned long mid = (left+right)/2; 18 | #pragma omp taskgroup 19 | { 20 | #pragma omp task shared(v) untied if(right-left >= (1<<14)) 21 | mergeSortRecursive(v, left, mid); 22 | #pragma omp task shared(v) untied if(right-left >= (1<<14)) 23 | mergeSortRecursive(v, mid+1, right); 24 | #pragma omp taskyield 25 | } 26 | inplace_merge(v.begin()+left, v.begin()+mid+1, v.begin()+right+1); 27 | }else 28 | { 29 | sort(v.begin()+left, v.begin()+right+1); 30 | } 31 | } 32 | } 33 | 34 | 35 | 36 | void mergeSort(vector& v) { 37 | #pragma omp parallel 38 | #pragma omp single 39 | mergeSortRecursive(v, 0, v.size()-1); 40 | } 41 | 42 | 43 | int main() 44 | { 45 | #ifndef ONLINE_JUDGE 46 | freopen("input.txt", "r", stdin); 47 | freopen("output.txt", "w", stdout); 48 | #endif 49 | ios_base::sync_with_stdio(0); 50 | cin.tie(0); cout.tie(0); 51 | 52 | vector v(6); 53 | 54 | 55 | v[0]=0.9; 56 | v[1]=1457.6; 57 | v[2]=565.5; 58 | v[3]=45.5; 59 | v[4]=0.58; 60 | v[5]=68.547; 61 | mergeSort(v); 62 | 63 | for(int i=0;i<6;i++) 64 | cout< 2 | using namespace std; 3 | #define M 1000000007 4 | 5 | // Normal Method Complexity - O(n) 6 | // Complexity - O(logn) 7 | // Modular Exponention 8 | long long int calculatepower(long long int A, long long int B) 9 | { 10 | if (B == 0) 11 | return 1; 12 | 13 | else if (B % 2 == 0) 14 | return calculatepower((A * A) % M, B >> 1) % M; 15 | else 16 | return (A * calculatepower((A * A) % M, B >> 1) % M ); 17 | } 18 | 19 | int main() 20 | { 21 | cout << calculatepower(2, 10); 22 | return 0; 23 | -------------------------------------------------------------------------------- /Multiple Missing elements.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int n; 8 | cout<<"Enter size"<>n; 10 | 11 | 12 | cout<<"Enter array elements"<>arr[i]; 18 | } 19 | 20 | int max=0; 21 | 22 | for(i=0;imax) 25 | { 26 | max=arr[i]; 27 | } 28 | } 29 | 30 | int hash[max]; 31 | for(i=0;i 3 | #include 4 | 5 | 6 | void printSolution(int board[N][N]) 7 | { 8 | for (int i = 0; i < N; i++) { 9 | for (int j = 0; j < N; j++) 10 | printf(" %d ", board[i][j]); 11 | printf("\n"); 12 | } 13 | } 14 | 15 | bool isSafe(int board[N][N], int row, int col) 16 | { 17 | int i, j; 18 | 19 | for (i = 0; i < col; i++) 20 | if (board[row][i]) 21 | return false; 22 | for (i = row, j = col; i >= 0 && j >= 0; i--, j--) 23 | if (board[i][j]) 24 | return false; 25 | 26 | for (i = row, j = col; j >= 0 && i < N; i++, j--) 27 | if (board[i][j]) 28 | return false; 29 | 30 | return true; 31 | } 32 | 33 | bool solveNQUtil(int board[N][N], int col) 34 | { 35 | if (col >= N) 36 | return true; 37 | 38 | 39 | for (int i = 0; i < N; i++) { 40 | if (isSafe(board, i, col)) { 41 | board[i][col] = 1; 42 | if (solveNQUtil(board, col + 1)) 43 | return true; 44 | 45 | board[i][col] = 0; 46 | } 47 | } 48 | return false; 49 | } 50 | 51 | 52 | bool solveNQ() 53 | { 54 | int board[N][N] = { { 0, 0, 0, 0 }, 55 | { 0, 0, 0, 0 }, 56 | { 0, 0, 0, 0 }, 57 | { 0, 0, 0, 0 } }; 58 | 59 | if (solveNQUtil(board, 0) == false) { 60 | printf("Solution does not exist"); 61 | return false; 62 | } 63 | 64 | printSolution(board); 65 | return true; 66 | } 67 | 68 | 69 | int main() 70 | { 71 | solveNQ(); 72 | return 0; 73 | } -------------------------------------------------------------------------------- /N_doors_problem.py: -------------------------------------------------------------------------------- 1 | def toggle(n): 2 | if doors[n]==1: 3 | doors[n]=0 4 | else: 5 | doors[n]=1 6 | n=int(input('Enter the no. of doors available: ')) 7 | m=int(input('Enter the no. of persons: ')) 8 | doors=[0]*n 9 | for i in range(1,m+1): 10 | j=i 11 | while j<=n: 12 | toggle(j-1) 13 | j=j+i 14 | for x in range(n): 15 | if doors[x]==1: 16 | print(x+1,end=" ") 17 | -------------------------------------------------------------------------------- /Number Mirror.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(void) 4 | { 5 | int a; 6 | scanf("%d", &a); 7 | printf("%d",a); 8 | return 0; 9 | } 10 | 11 | -------------------------------------------------------------------------------- /PancakeSort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to 2 | // sort array using 3 | // pancake sort 4 | #include 5 | using namespace std; 6 | 7 | /* Reverses arr[0..i] */ 8 | void flip(int arr[], int i) 9 | { 10 | int temp, start = 0; 11 | while (start < i) 12 | { 13 | temp = arr[start]; 14 | arr[start] = arr[i]; 15 | arr[i] = temp; 16 | start++; 17 | i--; 18 | } 19 | } 20 | 21 | // Returns index of the 22 | // maximum element in 23 | // arr[0..n-1] 24 | int findMax(int arr[], int n) 25 | { 26 | int mi, i; 27 | for (mi = 0, i = 0; i < n; ++i) 28 | if (arr[i] > arr[mi]) 29 | mi = i; 30 | return mi; 31 | } 32 | 33 | // The main function that 34 | // sorts given array using 35 | // flip operations 36 | void pancakeSort(int *arr, int n) 37 | { 38 | // Start from the complete 39 | // array and one by one 40 | // reduce current size 41 | // by one 42 | for (int curr_size = n; curr_size > 1; 43 | --curr_size) 44 | { 45 | // Find index of the 46 | // maximum element in 47 | // arr[0..curr_size-1] 48 | int mi = findMax(arr, curr_size); 49 | 50 | // Move the maximum 51 | // element to end of 52 | // current array if 53 | // it's not already 54 | // at the end 55 | if (mi != curr_size-1) 56 | { 57 | // To move at the end, 58 | // first move maximum 59 | // number to beginning 60 | flip(arr, mi); 61 | 62 | // Now move the maximum 63 | // number to end by 64 | // reversing current array 65 | flip(arr, curr_size-1); 66 | } 67 | } 68 | } 69 | 70 | // A utility function to print 71 | // n array of size n 72 | void printArray(int arr[], int n) 73 | { 74 | for (int i = 0; i < n; ++i) 75 | cout<< arr[i]<<" "; 76 | } 77 | 78 | // Driver program to test above function 79 | int main() 80 | { 81 | int arr[] = {23, 10, 20, 11, 12, 6, 7}; 82 | int n = sizeof(arr)/sizeof(arr[0]); 83 | 84 | pancakeSort(arr, n); 85 | 86 | cout<<"Sorted Array "< 5 | using namespace std; 6 | 7 | /* Reverses arr[0..i] */ 8 | void flip(int arr[], int i) 9 | { 10 | int temp, start = 0; 11 | while (start < i) 12 | { 13 | temp = arr[start]; 14 | arr[start] = arr[i]; 15 | arr[i] = temp; 16 | start++; 17 | i--; 18 | } 19 | } 20 | 21 | // Returns index of the 22 | // maximum element in 23 | // arr[0..n-1] 24 | int findMax(int arr[], int n) 25 | { 26 | int mi, i; 27 | for (mi = 0, i = 0; i < n; ++i) 28 | if (arr[i] > arr[mi]) 29 | mi = i; 30 | return mi; 31 | } 32 | 33 | // The main function that 34 | // sorts given array using 35 | // flip operations 36 | void pancakeSort(int *arr, int n) 37 | { 38 | // Start from the complete 39 | // array and one by one 40 | // reduce current size 41 | // by one 42 | for (int curr_size = n; curr_size > 1; 43 | --curr_size) 44 | { 45 | // Find index of the 46 | // maximum element in 47 | // arr[0..curr_size-1] 48 | int mi = findMax(arr, curr_size); 49 | 50 | // Move the maximum 51 | // element to end of 52 | // current array if 53 | // it's not already 54 | // at the end 55 | if (mi != curr_size-1) 56 | { 57 | // To move at the end, 58 | // first move maximum 59 | // number to beginning 60 | flip(arr, mi); 61 | 62 | // Now move the maximum 63 | // number to end by 64 | // reversing current array 65 | flip(arr, curr_size-1); 66 | } 67 | } 68 | } 69 | 70 | // A utility function to print 71 | // n array of size n 72 | void printArray(int arr[], int n) 73 | { 74 | for (int i = 0; i < n; ++i) 75 | cout<< arr[i]<<" "; 76 | } 77 | 78 | // Driver program to test above function 79 | int main() 80 | { 81 | int arr[] = {23, 10, 20, 11, 12, 6, 7}; 82 | int n = sizeof(arr)/sizeof(arr[0]); 83 | 84 | pancakeSort(arr, n); 85 | 86 | cout<<"Sorted Array "< 2 | using namespace std; 3 | 4 | int findMinVertex(bool *visited,int *weights,int v) 5 | { 6 | int minVertex=-1; 7 | for(int i=0;i>v>>e; 71 | 72 | int **edges = new int*[v]; 73 | for(int i=0;i>f>>s>>weight; 85 | edges[f][s] = weight; 86 | edges[s][f] = weight; 87 | } 88 | 89 | prims(edges,v); 90 | 91 | for(int i=0;i 2 | using namespace std; 3 | 4 | void swap(int* a, int* b) 5 | { 6 | int t = *a; 7 | *a = *b; 8 | *b = t; 9 | } 10 | int partition (int arr[], int low, int high) 11 | { 12 | int pivot = arr[high]; 13 | int i = (low - 1); 14 | 15 | for (int j = low; j <= high - 1; j++) 16 | { 17 | if (arr[j] < pivot) 18 | { 19 | i++; 20 | swap(&arr[i], &arr[j]); 21 | } 22 | } 23 | swap(&arr[i + 1], &arr[high]); 24 | return (i + 1); 25 | } 26 | 27 | void quickSort(int arr[], int low, int high) 28 | { 29 | if (low < high) 30 | { 31 | int pi = partition(arr, low, high); 32 | 33 | quickSort(arr, low, pi - 1); 34 | quickSort(arr, pi + 1, high); 35 | } 36 | } 37 | 38 | void printArray(int arr[], int size) 39 | { 40 | int i; 41 | for (i = 0; i < size; i++) 42 | cout << arr[i] << " "; 43 | cout << endl; 44 | } 45 | 46 | int main() 47 | { 48 | int arr[] = {10, 7, 8, 9, 1, 5}; 49 | int n = sizeof(arr) / sizeof(arr[0]); 50 | quickSort(arr, 0, n - 1); 51 | cout << "Sorted array: \n"; 52 | printArray(arr, n); 53 | return 0; 54 | } 55 | 56 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Hacktober2021-cpp-py 2 | ![hackto](https://user-images.githubusercontent.com/47898529/135893494-f19e3caf-aa3e-46f4-8c5d-15690d260c3f.PNG) 3 | 4 | Contribution for HacktoberFest 2021 Accepted 5 | 6 | Contribute your Code with Proper problem statement/Title 7 | 8 | *Fork this Repository , Mark it Star , Upload Your file(make sure it is not already present in the repo) , Contribute and then create a Pull Request* 9 | 10 | Follow the above steps Only then your PR will be merged . 11 | 12 | Happy Contributing !! 13 | -------------------------------------------------------------------------------- /RadixSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | int get_max (int a[], int n){ 3 | int max = a[0]; 4 | for (int i = 1; i < n; i++) 5 | if (a[i] > max) 6 | max = a[i]; 7 | return max; 8 | } 9 | void radix_sort (int a[], int n){ 10 | int bucket[10][10], bucket_cnt[10]; 11 | int i, j, k, r, NOP = 0, divisor = 1, lar, pass; 12 | lar = get_max (a, n); 13 | while (lar > 0){ 14 | NOP++; 15 | lar /= 10; 16 | } 17 | for (pass = 0; pass < NOP; pass++){ 18 | for (i = 0; i < 10; i++){ 19 | bucket_cnt[i] = 0; 20 | } 21 | for (i = 0; i < n; i++){ 22 | r = (a[i] / divisor) % 10; 23 | bucket[r][bucket_cnt[r]] = a[i]; 24 | bucket_cnt[r] += 1; 25 | } 26 | i = 0; 27 | for (k = 0; k < 10; k++){ 28 | for (j = 0; j < bucket_cnt[k]; j++){ 29 | a[i] = bucket[k][j]; 30 | i++; 31 | } 32 | } 33 | divisor *= 10; 34 | printf ("After pass %d : ", pass + 1); 35 | for (i = 0; i < n; i++) 36 | printf ("%d ", a[i]); 37 | printf ("\n"); 38 | } 39 | } 40 | int main (){ 41 | int i, n, a[10]; 42 | printf ("Enter the number of items to be sorted: "); 43 | scanf ("%d", &n); 44 | printf ("Enter items: "); 45 | for (i = 0; i < n; i++){ 46 | scanf ("%d", &a[i]); 47 | } 48 | radix_sort (a, n); 49 | printf ("Sorted items : "); 50 | for (i = 0; i < n; i++) 51 | printf ("%d ", a[i]); 52 | printf ("\n"); 53 | return 0; 54 | } -------------------------------------------------------------------------------- /Radix_sort.cpp: -------------------------------------------------------------------------------- 1 | // C++ implementation of Radix Sort 2 | #include 3 | using namespace std; 4 | 5 | // A utility function to get maximum value in arr[] 6 | int getMax(int arr[], int n) 7 | { 8 | int mx = arr[0]; 9 | for (int i = 1; i < n; i++) 10 | if (arr[i] > mx) 11 | mx = arr[i]; 12 | return mx; 13 | } 14 | 15 | // A function to do counting sort of arr[] according to 16 | // the digit represented by exp. 17 | void countSort(int arr[], int n, int exp) 18 | { 19 | int output[n]; // output array 20 | int i, count[10] = { 0 }; 21 | 22 | // Store count of occurrences in count[] 23 | for (i = 0; i < n; i++) 24 | count[(arr[i] / exp) % 10]++; 25 | 26 | // Change count[i] so that count[i] now contains actual 27 | // position of this digit in output[] 28 | for (i = 1; i < 10; i++) 29 | count[i] += count[i - 1]; 30 | 31 | // Build the output array 32 | for (i = n - 1; i >= 0; i--) { 33 | output[count[(arr[i] / exp) % 10] - 1] = arr[i]; 34 | count[(arr[i] / exp) % 10]--; 35 | } 36 | 37 | // Copy the output array to arr[], so that arr[] now 38 | // contains sorted numbers according to current digit 39 | for (i = 0; i < n; i++) 40 | arr[i] = output[i]; 41 | } 42 | 43 | // The main function to that sorts arr[] of size n using 44 | // Radix Sort 45 | void radixsort(int arr[], int n) 46 | { 47 | // Find the maximum number to know number of digits 48 | int m = getMax(arr, n); 49 | 50 | // Do counting sort for every digit. Note that instead 51 | // of passing digit number, exp is passed. exp is 10^i 52 | // where i is current digit number 53 | for (int exp = 1; m / exp > 0; exp *= 10) 54 | countSort(arr, n, exp); 55 | } 56 | 57 | // A utility function to print an array 58 | void print(int arr[], int n) 59 | { 60 | for (int i = 0; i < n; i++) 61 | cout << arr[i] << " "; 62 | } 63 | 64 | int main() 65 | { 66 | int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 }; 67 | int n = sizeof(arr) / sizeof(arr[0]); 68 | 69 | // Function Call 70 | radixsort(arr, n); 71 | print(arr, n); 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /RatInMaze.cpp: -------------------------------------------------------------------------------- 1 | /*A maze is in the form of a 2D matrix in which some cells/blocks are blocked. One of the cells is termed as a source cell, from where we have to start. 2 | And another one of them is termed as a destination cell, where wehave to reach. 3 | We have to find a path from the source to the destination without moving into any of the blocked cells. 4 | A picture of an unsolved maze is shown below, where grey cells denote the dead ends and white cells denote the cells which can be accessed. 5 | */ 6 | 7 | 8 | #include 9 | using namespace std; 10 | 11 | //It will check if we can move to next cell of matrix or not 12 | bool isSafe(int **arr,int x,int y,int n) 13 | { 14 | if(x>n; 53 | 54 | //dynamically alloted space to 2D array 55 | int** arr = new int *[n]; 56 | 57 | for(int i=0;i>arr[i][j]; 67 | } 68 | } 69 | 70 | //resultant 2D array 71 | 72 | int** solve = new int *[n]; 73 | 74 | for(int i=0;i 2 | using namespace std; 3 | string temp = ""; 4 | bool check(string s) 5 | { 6 | if (s.length() == 1 || s.length()==0) 7 | { 8 | return true; 9 | } 10 | int i = 0; 11 | while (s[i] != s[i + 1]) 12 | { 13 | if (i == s.length() - 2) 14 | return true; 15 | i++; 16 | } 17 | return false; 18 | } 19 | 20 | string remove(string s, int i = 0) 21 | { 22 | static int count; 23 | if (s == "") 24 | return ""; 25 | if (i == s.length()) 26 | { 27 | if (count == i - 1) 28 | temp.pop_back(); 29 | 30 | string final = ""; 31 | final = temp; 32 | 33 | temp.clear(); 34 | if (check(final)) 35 | { 36 | return final; 37 | } 38 | else 39 | { 40 | return remove(final); 41 | } 42 | } 43 | if (i == 0) 44 | { count =-1; 45 | temp.push_back(s[i]); 46 | } 47 | 48 | else if (s[i] == s[i - 1]) 49 | { 50 | count = i; 51 | } 52 | else 53 | { 54 | if (count == i - 1) 55 | temp.pop_back(); 56 | temp.push_back(s[i]); 57 | } 58 | return remove(s, i + 1); 59 | } 60 | int main() 61 | { 62 | #ifndef ONLINE_JUDGE 63 | freopen("input.txt", "r", stdin); 64 | freopen("output.txt", "w", stdout); 65 | #endif 66 | int t; 67 | cin >> t; 68 | while (t--) 69 | { 70 | string s; 71 | cin >> s; 72 | string f1 = remove(s); 73 | cout< 2 | 3 | // Definition for singly-linked list. 4 | struct ListNode { 5 | int val; 6 | ListNode *next; 7 | ListNode(int x) : val(x), next(NULL) {} 8 | }; 9 | 10 | class Solution { 11 | public: 12 | ListNode* removeNthFromEnd(ListNode* head, int n) { 13 | ListNode *dummy = new ListNode(); 14 | dummy -> next = head; 15 | ListNode *slow, *fast = dummy; 16 | 17 | for(int i = 1; i next; 19 | } 20 | while(fast -> next != NULL){ 21 | fast = fast -> next; 22 | slow = slow -> next; 23 | } 24 | slow -> next = slow ->next -> next; 25 | return dummy -> next; 26 | } 27 | }; 28 | 29 | /* 30 | 1 -> 2 -> 3 -> 7 -> 4 -> 5 -> 6 31 | n = 4 32 | retrun 33 | 1 -> 2 -> 3 -> 4 -> 5 -> 6 34 | for this problem, we take two pointers, and first iterate the fast one ahead to n 35 | and than iterate both fast and slow by one till fast points to the last node 36 | at this point the slow pointer is pointing at n-size which the node we have to renmove 37 | so, to remove slow -> next = slow -> next -> next 38 | and then we return the list. 39 | We introduce a dummy node for edge case, incase we have to remove head 40 | */ 41 | -------------------------------------------------------------------------------- /Reverse a Linked List: -------------------------------------------------------------------------------- 1 | ListNode* reverse(ListNode *node,ListNode *prev) 2 | { 3 | if(node==NULL) 4 | { 5 | return prev; 6 | } 7 | 8 | ListNode *store = node->next; 9 | node->next = prev; 10 | return reverse(store,node); 11 | } 12 | 13 | void main() 14 | { 15 | ListNode *head; //g=Given linked list 16 | reverse(head,NULL); 17 | } 18 | -------------------------------------------------------------------------------- /Reverse_matrix.cpp: -------------------------------------------------------------------------------- 1 | // C++ implementation to print 2 | // reverse wave form of matrix 3 | #include 4 | using namespace std; 5 | 6 | #define R 4 7 | #define C 4 8 | 9 | // function to print reverse wave 10 | // form for a given matrix 11 | void WavePrint(int m, int n, int arr[R][C]) 12 | { 13 | int i, j = n - 1, wave = 1; 14 | 15 | /* m - Ending row index 16 | n - Ending column index 17 | i, j - Iterator 18 | wave - for Direction 19 | wave = 1 - Wave direction down 20 | wave = 0 - Wave direction up */ 21 | while (j >= 0) { 22 | 23 | // Check whether to go in 24 | // upward or downward 25 | if (wave == 1) { 26 | 27 | // Print the element of the matrix 28 | // downward since the value of wave = 1 29 | for (i = 0; i < m; i++) 30 | cout << arr[i][j] << " "; 31 | 32 | wave = 0; 33 | j--; 34 | } 35 | else { 36 | 37 | // Print the elements of the 38 | // matrix upward since the value 39 | // of wave = 0 40 | for (i = m - 1; i >= 0; i--) 41 | cout << arr[i][j] << " "; 42 | 43 | wave = 1; 44 | j--; 45 | } 46 | } 47 | } 48 | 49 | // driver function 50 | int main() 51 | { 52 | int arr[R][C] = { { 1, 2, 3, 4 }, 53 | { 5, 6, 7, 8 }, 54 | { 9, 10, 11, 12 }, 55 | { 13, 14, 15, 16 } }; 56 | WavePrint(R, C, arr); 57 | 58 | return 0; 59 | } 60 | 61 | // output- 62 | // 4 8 12 16 15 11 7 3 2 6 10 14 13 9 5 1 63 | -------------------------------------------------------------------------------- /Rock_Snake_Paper_Scissor.py: -------------------------------------------------------------------------------- 1 | import random 2 | import tkinter 3 | 4 | stats = [] 5 | 6 | 7 | def get_winner(call): 8 | if random.random() <= (1 / 3): 9 | throw = "rock" 10 | elif (1 / 3) < random.random() <= (2 / 3): 11 | throw = "scissors" 12 | else: 13 | throw = "paper" 14 | 15 | if (throw == "rock" and call == "paper") or (throw == "paper" and call == "scissors") \ 16 | or (throw == "scissors" and call == "rock"): 17 | stats.append('W') 18 | result = "You won!" 19 | elif throw == call: 20 | stats.append('D') 21 | result = "It's a draw" 22 | else: 23 | stats.append('L') 24 | result = "You lost!" 25 | 26 | global output 27 | output.config(text="Computer did: " + throw + "\n" + result) 28 | 29 | 30 | def pass_s(): 31 | get_winner("scissors") 32 | 33 | 34 | def pass_r(): 35 | get_winner("rock") 36 | 37 | 38 | def pass_p(): 39 | get_winner("paper") 40 | 41 | 42 | window = tkinter.Tk() 43 | 44 | scissors = tkinter.Button(window, text="Scissors", bg="#ff9999", padx=10, pady=5, command=pass_s, width=20) 45 | rock = tkinter.Button(window, text="Rock", bg="#80ff80", padx=10, pady=5, command=pass_r, width=20) 46 | paper = tkinter.Button(window, text="Paper", bg="#3399ff", padx=10, pady=5, command=pass_p, width=20) 47 | output = tkinter.Label(window, width=20, fg="red", text="What's your call?") 48 | 49 | scissors.pack(side="left") 50 | rock.pack(side="left") 51 | paper.pack(side="left") 52 | output.pack(side="right") 53 | window.mainloop() 54 | 55 | for i in stats: print(i, end=" ") 56 | if stats.count('L') > stats.count('W'): 57 | result = "\nYou loose the series." 58 | elif stats.count('L') == stats.count('W'): 59 | result = "\nSeries ended in a draw." 60 | else: 61 | result = "\nYou win the series." 62 | 63 | print(result) 64 | -------------------------------------------------------------------------------- /RotateALinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node { 5 | int data; 6 | struct Node *next; 7 | Node(int x) { 8 | data = x; 9 | next = NULL; 10 | } 11 | }; 12 | 13 | 14 | // } Driver Code Ends 15 | /* 16 | 17 | struct Node { 18 | int data; 19 | struct Node *next; 20 | Node(int x) { 21 | data = x; 22 | next = NULL; 23 | } 24 | }; 25 | 26 | */ 27 | 28 | class Solution 29 | { 30 | public: 31 | //Function to rotate a linked list. 32 | Node* rotate(Node* head, int k) 33 | { 34 | Node *a,*b; 35 | a=head; 36 | while(a->next!=NULL) 37 | a=a->next; 38 | 39 | k--; 40 | 41 | b=head; 42 | head=b->next; 43 | a->next=b; 44 | a=a->next; 45 | while(k--) 46 | { 47 | b=head; 48 | head=b->next; 49 | a->next=b; 50 | a=a->next; 51 | } 52 | 53 | a->next=NULL; 54 | return head; 55 | } 56 | }; 57 | 58 | 59 | 60 | // { Driver Code Starts. 61 | 62 | void printList(Node *n) 63 | { 64 | while (n != NULL) 65 | { 66 | cout<< n->data << " "; 67 | n = n->next; 68 | } 69 | cout<< endl; 70 | } 71 | 72 | int main() 73 | { 74 | int t; 75 | cin>>t; 76 | while(t--) 77 | { 78 | int n, val, k; 79 | cin>>n; 80 | 81 | cin>> val; 82 | Node *head = new Node(val); 83 | Node *tail = head; 84 | 85 | for(int i=0; i> val; 88 | tail->next = new Node(val); 89 | tail = tail->next; 90 | } 91 | 92 | cin>> k; 93 | 94 | Solution ob; 95 | head = ob.rotate(head,k); 96 | printList(head); 97 | } 98 | return 1; 99 | } 100 | // } Driver Code Ends 101 | -------------------------------------------------------------------------------- /Roulette-Game.py: -------------------------------------------------------------------------------- 1 | """ 2 | Roulette-Game: 3 | Python program simulates the game of roulette. In roulette, a wheel spins 4 | and yields a number between 1 and 49 when a ball drops into a numbered slot. 5 | The initial amount is monitored throughout the game and will be reminded to 6 | the player after each guess. If the amount goes zero, then the game ends. 7 | """ 8 | from random import randint 9 | 10 | totalAmount=1000 #total amount invested 11 | 12 | while totalAmount > 0: 13 | print("Welcome !!!\nYou have", totalAmount,"€. Good Luck !!\n_________________________________") 14 | selectedNumber=int(input("\nOn which number do you want to bet ?")) 15 | 16 | x=0 17 | x=selectNumber 18 | if x < 0 or x > 49: 19 | print("You have to bet a number between 0 and 49") 20 | 21 | bettingAmount=int(input("How much do you want to bet on this number?")) 22 | numberOutput = randint(0, 49) # line to use to generate a random number between 0 and 49 23 | print("\nThe number output is",numberOutput) 24 | 25 | if numberOutput == selectedNumber: 26 | print("You Win!!!\n_________________________________") 27 | 28 | else: 29 | print("Sorry but you lost, try again !") 30 | totalAmount-=bettingAmount 31 | print("\nYou now have",totalAmount,"€ left\n_________________________________") 32 | 33 | if totalAmount==0: 34 | print("Sorry but you don't have enough money to continue !\nThe game is now ending !") 35 | -------------------------------------------------------------------------------- /STACK using array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define MAX 10 3 | using namespace std; 4 | 5 | class Stack 6 | { 7 | int stack[MAX]; 8 | int top; 9 | public: 10 | Stack() { 11 | top=-1; 12 | } 13 | int push(int e); 14 | 15 | 16 | int pop() 17 | { 18 | if(top<0) 19 | { 20 | cout<<"Stack Underflow\n"; 21 | return 0; 22 | } 23 | top--; 24 | return(stack[top+1]); 25 | } 26 | 27 | int traverse() 28 | { 29 | for(int i=top;i>=0;i--) 30 | cout<=MAX) 37 | { 38 | cout<<"Stack Overflow\n"; 39 | return 0; 40 | } 41 | top++; 42 | stack[top]=e; 43 | } 44 | int main() 45 | { 46 | int n=0,e=0; 47 | Stack s; 48 | while(1) 49 | { 50 | cout<<"1.Push 2.Pop 3.Traverse 4.Exit\n"; 51 | cin>>n; 52 | switch(n) 53 | { 54 | case 1: 55 | cin>>e; 56 | s.push(e); 57 | break; 58 | case 2: 59 | s.pop(); 60 | break; 61 | case 3: 62 | s.traverse(); 63 | break; 64 | case 4: 65 | return 0; 66 | default: 67 | cout<<"Please choose b/w 1/2/3/4\n"; 68 | } 69 | } 70 | 71 | } 72 | 73 | -------------------------------------------------------------------------------- /ShellSort.cpp: -------------------------------------------------------------------------------- 1 | // Shell Sort in C++ programming 2 | 3 | #include 4 | using namespace std; 5 | 6 | // Shell sort 7 | void shellSort(int array[], int n) { 8 | // Rearrange elements at each n/2, n/4, n/8, ... intervals 9 | for (int interval = n / 2; interval > 0; interval /= 2) { 10 | for (int i = interval; i < n; i += 1) { 11 | int temp = array[i]; 12 | int j; 13 | for (j = i; j >= interval && array[j - interval] > temp; j -= interval) { 14 | array[j] = array[j - interval]; 15 | } 16 | array[j] = temp; 17 | } 18 | } 19 | } 20 | 21 | // Print an array 22 | void printArray(int array[], int size) { 23 | int i; 24 | for (i = 0; i < size; i++) 25 | cout << array[i] << " "; 26 | cout << endl; 27 | } 28 | 29 | // Driver code 30 | int main() { 31 | int data[] = {9, 8, 3, 7, 5, 6, 4, 1}; 32 | int size = sizeof(data) / sizeof(data[0]); 33 | shellSort(data, size); 34 | cout << "Sorted array: \n"; 35 | printArray(data, size); 36 | } 37 | -------------------------------------------------------------------------------- /Shell_Sort: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | // A function implementing Shell sort. 6 | void ShellSort(int a[], int n) 7 | { 8 | int i, j, k, temp; 9 | // Gap 'i' between index of the element to be compared, initially n/2. 10 | for(i = n/2; i > 0; i = i/2) 11 | { 12 | for(j = i; j < n; j++) 13 | { 14 | for(k = j-i; k >= 0; k = k-i) 15 | { 16 | // If value at higher index is greater, then break the loop. 17 | if(a[k+i] >= a[k]) 18 | break; 19 | // Switch the values otherwise. 20 | else 21 | { 22 | temp = a[k]; 23 | a[k] = a[k+i]; 24 | a[k+i] = temp; 25 | } 26 | } 27 | } 28 | } 29 | } 30 | int main() 31 | { 32 | int n, i; 33 | cout<<"\nEnter the number of data element to be sorted: "; 34 | cin>>n; 35 | 36 | int arr[n]; 37 | for(i = 0; i < n; i++) 38 | { 39 | cout<<"Enter element "<>arr[i]; 41 | } 42 | 43 | ShellSort(arr, n); 44 | 45 | // Printing the sorted data. 46 | cout<<"\nSorted Data "; 47 | for (i = 0; i < n; i++) 48 | cout<<"->"< 52 | #include 53 | #include 54 | using namespace std; 55 | 56 | vector maxSlidingWindow(vector& nums, int k) { 57 | // front elem is max of every window 58 | //time=0(n) 59 | vector ans; 60 | deque q; // deque for window 61 | q.push_back(0); // putting index in deque 62 | for(int i=1;inums[q.back()]) // if elem is greater than prev ones,pop the prev ones out as front should always be greater in window 65 | { 66 | q.pop_back(); 67 | } 68 | q.push_back(i); // if less directly push or push after popping elem 69 | } 70 | for(int i=k;inums[q.back()]) 79 | { 80 | q.pop_back(); 81 | } 82 | q.push_back(i); 83 | } 84 | int val=q.front(); // for last window 85 | ans.push_back(nums[val]); 86 | return ans; 87 | 88 | } 89 | 90 | int main() 91 | { 92 | int n,k; 93 | cin>>n; 94 | 95 | vector nums; 96 | 97 | for(int i=0;i>ele; 101 | nums.push_back(ele); 102 | } 103 | cin>>k; 104 | vectorans; 105 | ans=maxSlidingWindow(nums,k); 106 | 107 | for(int i=0;i 2 | using namespace std; 3 | 4 | // Returns maximum sum in a subarray of size k. 5 | int maxSum(int arr[], int n, int k) 6 | { 7 | // Initialize result 8 | int max_sum = INT_MIN; 9 | 10 | // Consider all blocks starting with i. 11 | for (int i = 0; i < n - k + 1; i++) { 12 | int current_sum = 0; 13 | for (int j = 0; j < k; j++) 14 | current_sum = current_sum + arr[i + j]; 15 | 16 | // Update result if required. 17 | max_sum = max(current_sum, max_sum); 18 | } 19 | 20 | return max_sum; 21 | } 22 | int main() 23 | { 24 | int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 }; 25 | int k = 4; 26 | int n = sizeof(arr) / sizeof(arr[0]); 27 | cout << maxSum(arr, n, k); 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /Snake & Ladder.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find minimum number of dice throws required to 2 | // reach last cell from first cell of a given snake and ladder 3 | // board 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | // An entry in queue used in BFS 9 | struct queueEntry 10 | { 11 | int v; // Vertex number 12 | int dist; // Distance of this vertex from source 13 | }; 14 | 15 | // This function returns minimum number of dice throws required to 16 | // Reach last cell from 0'th cell in a snake and ladder game. 17 | // move[] is an array of size N where N is no. of cells on board 18 | // If there is no snake or ladder from cell i, then move[i] is -1 19 | // Otherwise move[i] contains cell to which snake or ladder at i 20 | // takes to. 21 | int getMinDiceThrows(int move[], int N) 22 | { 23 | // The graph has N vertices. Mark all the vertices as 24 | // not visited 25 | bool *visited = new bool[N]; 26 | for (int i = 0; i < N; i++) 27 | visited[i] = false; 28 | 29 | // Create a queue for BFS 30 | queue q; 31 | 32 | // Mark the node 0 as visited and enqueue it. 33 | visited[0] = true; 34 | queueEntry s = {0, 0}; // distance of 0't vertex is also 0 35 | q.push(s); // Enqueue 0'th vertex 36 | 37 | // Do a BFS starting from vertex at index 0 38 | queueEntry qe; // A queue entry (qe) 39 | while (!q.empty()) 40 | { 41 | qe = q.front(); 42 | int v = qe.v; // vertex no. of queue entry 43 | 44 | // If front vertex is the destination vertex, 45 | // we are done 46 | if (v == N-1) 47 | break; 48 | 49 | // Otherwise dequeue the front vertex and enqueue 50 | // its adjacent vertices (or cell numbers reachable 51 | // through a dice throw) 52 | q.pop(); 53 | for (int j=v+1; j<=(v+6) && jsnk_length: 104 | del snk_list[0] 105 | 106 | if head in snk_list[:-1]: 107 | game_over = True 108 | 109 | if snake_x<0 or snake_x>screen_width-20 or snake_y<50 or snake_y>screen_height-20: 110 | game_over = True 111 | plot_snake(gameWindow, black, snk_list, snake_size) 112 | pygame.display.update() 113 | clock.tick(fps) 114 | pygame.quit() 115 | quit() 116 | gameloop() 117 | -------------------------------------------------------------------------------- /Spiral_traversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | /*top right 5 | 6 | 00 01 02 03 7 | 8 | 10 11 12 13 9 | 10 | 20 21 22 23 11 | 12 | 30 31 32 33 13 | 14 | left bottom 15 | 16 | 17 | 18 | 19 | */ 20 | int main() 21 | { 22 | int n, m; 23 | cout << "Enter the row size :- \n"; 24 | cin >> n; 25 | cout << "Enter the coulumn size \n"; 26 | cin >> m; 27 | int a[n][m]; 28 | cout << "Enter the arrat \n"; 29 | for (int i = 0; i < n; i++) 30 | { 31 | for (int j = 0; j < m; j++) 32 | { 33 | cin >> a[i][j]; 34 | } 35 | } 36 | int top = 0, bottom = n - 1, right = m - 1, left = 0; 37 | while (top <= bottom and left <= right) 38 | { //TOP ROW 39 | for (int i = left; i <= right; i++) 40 | { 41 | cout << a[top][i] << " "; 42 | } 43 | top++; 44 | //RIGHT COULUMN 45 | for (int i = top; i <= bottom; i++) 46 | { 47 | cout << a[i][right] << " "; 48 | } 49 | right--; 50 | //BOTTOM ROW(reverse) 51 | if (top <= bottom) 52 | { 53 | for (int i = right; i >= left; i--) 54 | { 55 | cout << a[bottom][i] << " "; 56 | } 57 | bottom--; 58 | } 59 | //LEFT COULUMN(reverse) 60 | if (left <= right) 61 | { 62 | for (int i = bottom; i >= top; i--) 63 | { 64 | cout << a[i][left] << " "; 65 | } 66 | left++; 67 | ; 68 | } 69 | } 70 | return 0; 71 | } -------------------------------------------------------------------------------- /Spiral_traversal.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/piyush-kash/Hacktober2021-cpp-py/ea6d6f30a9d5b28069ff5ed19a5ba57dee529daf/Spiral_traversal.exe -------------------------------------------------------------------------------- /TowerOfHanoi.java: -------------------------------------------------------------------------------- 1 | package Recursion; 2 | 3 | public class TowerOfHanoi { 4 | 5 | public static void Toi(int disk,int Source,int Auxiliary,int destination) { 6 | if(disk==0) { 7 | return; 8 | } 9 | Toi(disk-1, Source, destination, Auxiliary); 10 | System.out.println("Move Disk 1 from Rod "+ Source + " to Rod " + destination); 11 | Toi(disk-1, Auxiliary, Source, destination); 12 | } 13 | public static void main(String[] args) { 14 | Toi(2, 1, 2, 3); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /Tower_of_Hanaoi_puzzle.py: -------------------------------------------------------------------------------- 1 | // Python3 Concept: TOWER OF HANAOI PUZZLE 2 | 3 | Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: 4 | 5 | --Only one disk can be moved at a time. 6 | --Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. 7 | --No disk may be placed on top of a smaller disk. 8 | 9 | PYTHON CODE 10 | # Recursive Python function to solve tower of hanoi 11 | 12 | def TowerOfHanoi(n , from_rod, to_rod, aux_rod): 13 | if n == 1: 14 | print("Move disk 1 from rod",from_rod,"to rod",to_rod) 15 | return 16 | TowerOfHanoi(n-1, from_rod, aux_rod, to_rod) 17 | print("Move disk",n,"from rod",from_rod,"to rod",to_rod) 18 | TowerOfHanoi(n-1, aux_rod, to_rod, from_rod) 19 | 20 | # Driver code 21 | n = 4 22 | TowerOfHanoi(n, 'A', 'C', 'B') 23 | # A, C, B are the name of rods 24 | -------------------------------------------------------------------------------- /TrappingRainWater.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int trap(vector& height) { 4 | int n = height.size(); 5 | int leftMax[n]; 6 | int rightMax[n]; 7 | int m = 0; 8 | for(int i = 0; i < n; i++) { 9 | m = max(m, height[i]); 10 | leftMax[i] = m; 11 | } 12 | m = 0; 13 | for(int i = n - 1; i >= 0; i--) { 14 | m = max(m, height[i]); 15 | rightMax[i] = m; 16 | } 17 | int ans = 0; 18 | for(int i = 0; i < n; i++) { 19 | ans += min(leftMax[i], rightMax[i]) - height[i]; 20 | } 21 | return ans; 22 | } 23 | }; -------------------------------------------------------------------------------- /Try: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /UniqueBInarySearchTree: -------------------------------------------------------------------------------- 1 | /** Given A, generate all structurally unique BST’s (binary search trees) that store values 1...A. ***/ 2 | 3 | 4 | class Binary{ 5 | public: 6 | 7 | vector generate(int Start, int End) 8 | { 9 | vector v; 10 | 11 | if(Start > End) 12 | { 13 | v.push_back(NULL); 14 | return v; 15 | } 16 | 17 | if(Start == End) 18 | { 19 | v.push_back(new TreeNode(Start)); 20 | return v; 21 | } 22 | 23 | for(auto i=Start; i<=End; i++) 24 | { 25 | vector lft = generate(Start, i-1); 26 | vector rgt = generate(i+1, End); 27 | 28 | for(auto l : lft) 29 | { 30 | for(auto r : rgt) 31 | { 32 | TreeNode *root = new TreeNode(i); 33 | 34 | root->left = l; 35 | root->right = r; 36 | 37 | v.push_back(root); 38 | } 39 | } 40 | } 41 | return v; 42 | } 43 | 44 | vector generateTrees(int n) 45 | { 46 | 47 | if(n == 0) 48 | return vector(); 49 | else 50 | return generate(1, n); 51 | } 52 | }; 53 | 54 | -------------------------------------------------------------------------------- /Words from phone digit.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void solve(vector v,string res,string m[],int i) 4 | { 5 | if(i== v.size()-1) 6 | { 7 | int j=0; 8 | while(m[v[i]][j]!='\0') 9 | { 10 | cout<& v) 27 | { 28 | string m[]={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; 29 | solve(v,"",m,0); 30 | } 31 | int main() 32 | { 33 | int n; 34 | cin>>n; 35 | vector v(n); 36 | for(int i=0;i>v[i]; 38 | generatestrings(v); 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /balanced_brackets.cpp: -------------------------------------------------------------------------------- 1 | //CHEQUE on Balanced Brackets 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | bool isbalance(string s) 8 | { 9 | stack st; 10 | for (int it = 0; it < s.size(); it++) 11 | { 12 | if (s[it] == '(' || s[it] == '{' || s[it] == '[') 13 | { 14 | st.push(s[it]); 15 | } 16 | else 17 | { 18 | if (st.empty()) 19 | { 20 | return false; 21 | } 22 | char x = st.top(); 23 | st.pop(); 24 | if (x == '(' && s[it] == ')' || x == '[' && s[it] == ']' || x == '{' && s[it] == '}') 25 | { 26 | continue; 27 | } 28 | else 29 | { 30 | return false; 31 | } 32 | } 33 | } 34 | return st.empty(); 35 | } 36 | 37 | int main() 38 | { 39 | string s; 40 | cout << "Enter Strings of brackets : "; 41 | cin >> s; 42 | if (isbalance(s)) 43 | { 44 | cout << "TRUE"; 45 | } 46 | else 47 | { 48 | cout << "FALSE"; 49 | } 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /balanced_paranthesis.cpp: -------------------------------------------------------------------------------- 1 | // Check For Balanced Paranthesis in a string 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | bool matching(char a, char b) 8 | { 9 | return((a=='(' && b==')')) || ((a=='{') && b=='}') || ((a=='[' && b==']')); 10 | } 11 | bool isBalanced(string str) 12 | { 13 | stacks; 14 | for(int i=0;i>str; 37 | isBalanced(str); 38 | return 0; 39 | } -------------------------------------------------------------------------------- /binSearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int binSearch(int arr[5], int search){ 5 | int m = 5/2, k = search; 6 | if(arr[m] == k) 7 | { 8 | return m; 9 | } 10 | else 11 | { 12 | if(arr[m] > k){ 13 | m = (m + 5) / 2; 14 | binSearch(arr, k); 15 | } 16 | if(arr[m] < search){ 17 | m = (1 + m) / 2; 18 | binSearch(arr, k); 19 | } 20 | } 21 | return 0; 22 | } 23 | int main(){ 24 | int array[5] = {1,2,3,4,5}; 25 | cout << binSearch(array, 6); 26 | } 27 | 28 | -------------------------------------------------------------------------------- /bin_sort.py: -------------------------------------------------------------------------------- 1 | # This is bin sor algorithm 2 | 3 | MIN_BUCKET = 0 4 | MAX_BUCKET = 15 5 | 6 | 7 | def bucket_sort(aList): 8 | buckets = list() 9 | for i in range(MIN_BUCKET, MAX_BUCKET + 1): 10 | buckets.append(None) 11 | 12 | for i in aList: 13 | buckets[aList[i]] = aList[i] 14 | 15 | x = 0 16 | for i in range(MIN_BUCKET, MAX_BUCKET + 1): 17 | if buckets[i] is not None: 18 | aList[x] = buckets[i] 19 | x += 1 20 | 21 | return aList 22 | 23 | 24 | if __name__ == '__main__': 25 | from random import shuffle 26 | l = range(15) 27 | lcopy = l[:] 28 | shuffle(l) 29 | print('Unsorted') 30 | print l 31 | assert l != lcopy 32 | print('Sorted') 33 | l = bucket_sort(l) 34 | print l 35 | assert l == lcopy 36 | -------------------------------------------------------------------------------- /binary search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | int main(){ 6 | int n; 7 | cin>>n; 8 | int a[100]; 9 | for(int i=0; i>a[i]; 12 | } 13 | int key; 14 | cin>>key; 15 | int s=0; 16 | int e = n-1; 17 | int mid; 18 | 19 | while(skey){ 26 | e = mid - 1; 27 | } 28 | else{ 29 | s = mid + 1; 30 | } 31 | } 32 | if(s>e){ 33 | return -1; 34 | } 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /binarysearchwithpointers.c: -------------------------------------------------------------------------------- 1 | // A binary search C program using pointers. 2 | #include 3 | int binarysearch(int *arr, int ele, int *ptrlast, int **ptr_to_value); 4 | void main() 5 | { int arr[20],n,i; 6 | int found,value; 7 | int *ptrlast,*ptr_to_value; 8 | int ele; 9 | ptr_to_value=NULL; 10 | printf("Enter the number of elements"); 11 | scanf("%d",&n); 12 | printf("Enter the elements"); 13 | for(i=0;i*midptr) 28 | { firstptr=midptr+1; 29 | } 30 | else if(ele<*midptr) 31 | { 32 | lastptr=midptr-1; 33 | } 34 | else 35 | { 36 | firstptr=lastptr+1; 37 | } 38 | 39 | 40 | } 41 | *ptr_to_value=midptr; 42 | return(ele==*midptr); 43 | 44 | } 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /bowtie.py: -------------------------------------------------------------------------------- 1 | /* 2 | BowTie Pattern: 3 | Complete the given method solve that takes as parameter an integer n and prints a formation like the examples below. 4 | 5 | Hint: Is there a relation between row number and the number of *? What about row number and number of .? 6 | 7 | Example Input: 1 8 | Example Output: 9 | 10 | *.* 11 | *** 12 | *.* 13 | 14 | Example Input: 5 15 | Example Output: 16 | 17 | *.........* 18 | **.......** 19 | ***.....*** 20 | ****...**** 21 | *****.***** 22 | *********** 23 | *****.***** 24 | ****...**** 25 | ***.....*** 26 | **.......** 27 | *.........* 28 | 29 | 30 | */ 31 | 32 | def solve(n): 33 | # write your code here 34 | col=2*n+1 35 | #for i in range(1,n+1): 36 | for r in range(1,n+1): 37 | for c in range(1,col+1): 38 | if(r>=c or c>=(col-r+1)): 39 | print("*",end="") 40 | 41 | else: 42 | print(".",end="") 43 | print() 44 | #print() 45 | for i in range(col): 46 | print("*",end="") 47 | print() 48 | for r in range(n,0,-1): 49 | for c in range(1,col+1): 50 | if(r>=c or c>=(col-r+1)): 51 | print("*",end="") 52 | else: 53 | print(".",end="") 54 | print() 55 | print() -------------------------------------------------------------------------------- /bubble sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | void bubbleSort(int arr[], int n) 6 | { 7 | int i, j; 8 | bool swapp; 9 | for (i = 0; i < n-1; i++) 10 | { 11 | swapp = false; 12 | for (j = 0; j < n-i-1; j++) 13 | { 14 | if (arr[j] > arr[j+1]) 15 | { 16 | swap(arr[j], arr[j+1]); 17 | swapp = true; 18 | } 19 | } 20 | if (swapp == false) 21 | break; 22 | } 23 | } 24 | void printArray(int arr[], int n) 25 | { 26 | int i; 27 | for (i=0; i < n; i++) 28 | cout<>n; 33 | int arr[1000000]; 34 | for(int i=0;i>arr[i]; 36 | } 37 | bubbleSort(arr, n); 38 | printArray(arr, n); 39 | return 0; 40 | } 41 | © 2020 GitHub, Inc. 42 | -------------------------------------------------------------------------------- /bubble sort.py: -------------------------------------------------------------------------------- 1 | def bubblesort(list): 2 | 3 | # Swap the elements to arrange in order 4 | for iter_num in range(len(list)-1,0,-1): 5 | for idx in range(iter_num): 6 | if list[idx]>list[idx+1]: 7 | temp = list[idx] 8 | list[idx] = list[idx+1] 9 | list[idx+1] = temp 10 | list = [19,2,31,45,6,11,121,27] 11 | bubblesort(list) 12 | print(list) -------------------------------------------------------------------------------- /bubble_sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int i,j,size; 5 | printf("Enter the size of the array\n"); 6 | scanf("%d",&size); 7 | int arr[100]; 8 | 9 | printf("Enter array elements\n"); 10 | for(i=0;iarr[j+1]) 21 | { 22 | temp=arr[j]; 23 | arr[j]=arr[j+1]; 24 | arr[j+1]=temp; 25 | } 26 | } 27 | } 28 | 29 | printf("Sorted array is \n"); 30 | for(i=0;i 2 | 3 | using namespace std; 4 | 5 | class node 6 | { 7 | public: 8 | int data; 9 | node* next; 10 | }; 11 | node* head = NULL; 12 | node* last = NULL; 13 | 14 | void insertInEmpty(node* head, int data) 15 | { 16 | node* newNode = new node(); 17 | head = newNode; 18 | newNode->data = data; 19 | newNode->next = head; 20 | last = head; 21 | } 22 | 23 | void AtBeg(node* head, int value) 24 | { 25 | node* newNode = new node(); 26 | newNode->data = value; 27 | if(head == NULL) 28 | { 29 | newNode->data = value; 30 | newNode->next = head; 31 | last = head; 32 | } 33 | else 34 | { 35 | newNode->next = head; 36 | head = newNode; 37 | 38 | } 39 | } 40 | 41 | void AtEnd(node* head, int value) 42 | { 43 | // node* temp = head->next; 44 | node* t = head; 45 | while(t->next != head) 46 | { 47 | t = t->next; 48 | } 49 | node* newNode = new node(); 50 | newNode->data = value; 51 | newNode->next = t->next; 52 | t->next = newNode; 53 | } 54 | 55 | void atPos(node* head, int pos, int value) 56 | { 57 | node* newNode = new node(); 58 | if(head == NULL) 59 | { 60 | head = newNode; 61 | newNode->data = value; 62 | newNode->next = head; 63 | return; 64 | } 65 | int p = 0; 66 | node* t = head; 67 | while(p < pos-1) 68 | { 69 | t = t->next; 70 | p++; 71 | } 72 | newNode->data = value; 73 | newNode->next = t->next; 74 | t->next = newNode; 75 | } 76 | 77 | void printList(node *head) 78 | { 79 | node *t = head; 80 | while(t->next != head) 81 | { 82 | cout << t->data << " "; 83 | t = t->next; 84 | } 85 | cout << t->data << " "; 86 | } 87 | 88 | 89 | int main() 90 | { 91 | while(1) 92 | { 93 | cout << "\n1. Insert\n"; 94 | cout << "\n2. Display\n"; 95 | cout << "\n3. Exit\n"; 96 | int c; 97 | cout << "Enter your choice: "; 98 | cin >> c; 99 | switch(c) 100 | { 101 | case 1: 102 | { 103 | int value, pos; 104 | cout << "Enter the value you want to insert: "; 105 | cin >> value; 106 | cout << "Enter the position at which you want to insert: "; 107 | cin >> pos; 108 | atPos(head, pos, value); 109 | break; 110 | } 111 | case 2: 112 | { 113 | printList(head); 114 | break; 115 | } 116 | default: 117 | { 118 | cout << "\nEnter a valid choice\n"; 119 | } 120 | } 121 | } 122 | } -------------------------------------------------------------------------------- /class and object.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | class newclass{ 6 | private: 7 | bool atend; 8 | public: 9 | string name; 10 | string presence; 11 | int age; 12 | int rollNum; 13 | int setAttendance(int x){ 14 | if(x){ 15 | atend = true; 16 | } 17 | else{ 18 | atend = false; 19 | } 20 | return 0; 21 | } 22 | int getAttendance(){ 23 | return atend; 24 | } 25 | }; 26 | class teacher: public newclass{ 27 | }; 28 | int i, attend, num; 29 | teacher maths; 30 | cout << "Name of Maths Teacher:" << endl; 31 | cin >> maths.name; 32 | cout << "is the teacher present?" << endl; 33 | cin >> attend; 34 | maths.setAttendance(attend); 35 | if(maths.getAttendance()){ 36 | maths.presence = "present"; 37 | } else{ 38 | maths.presence = "absent"; 39 | } 40 | cout << "The Teacher is " << maths.presence << endl; 41 | cout << "Enter the number of students in class:" << endl; 42 | cin >> num; 43 | string attendance[num]; 44 | newclass stud[num]; 45 | for(i = 0; i < num; i++){ 46 | cout << "Enter the name of student number " << i+1 << endl; 47 | cin >> stud[i].name; 48 | cout << "Enter the age of student number " << i+1 << endl; 49 | cin >> stud[i].age; 50 | stud[i].rollNum = i+1; 51 | } 52 | for(i = 0; i < num; i++){ 53 | cout << "is " << stud[i].name << " present?" << endl; 54 | cin >> attend; 55 | stud[i].setAttendance(attend); 56 | if(stud[i].getAttendance()){ 57 | stud[i].presence = "present"; 58 | } else{ 59 | stud[i].presence = "absent"; 60 | } 61 | } 62 | for(i = 0; i < num; i++){ 63 | cout << "Roll Number " << stud[i].rollNum << " " << stud[i].name << " of age " << stud[i].age << " is " << stud[i].presence; 64 | 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /copyingArrays.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | int i; 6 | int array[10] = {1,2,3,4,5,6,67,7,8,1}, array2[10]; 7 | for(i = 0; i < 10; i ++){ 8 | array2[i] = array[i]; 9 | cout << array2[i]; 10 | } 11 | return 0; 12 | } 13 | -------------------------------------------------------------------------------- /count_distinct_elements.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int countDistinct(int a[],int n) 4 | { 5 | unordered_set s; 6 | for(int i=0;i s(a,n); 19 | // return s.size(); 20 | // } 21 | 22 | int main() 23 | { 24 | int n; 25 | cin>>n; 26 | int a[n]; 27 | for(int i=0;i>a[i]; 30 | } 31 | 32 | cout< 2 | using namespace std; 3 | int main() 4 | { 5 | int a[10], n, i; 6 | cout<<"Enter the number to convert: "; 7 | cin>>n; 8 | for(i=0; n>0; i++) 9 | { 10 | a[i]=n%2; 11 | n= n/2; 12 | } 13 | cout<<"Binary of the given number= "; 14 | for(i=i-1 ;i>=0 ;i--) 15 | { 16 | cout< 4 | #define INF 10000 5 | 6 | using namespace std; 7 | 8 | class Graph { 9 | map>> m; 10 | bool isDirected; 11 | 12 | public: 13 | Graph(bool directs) { 14 | isDirected = directs; 15 | } 16 | 17 | void addEdge(int v1, int v2, int weight) { 18 | m[v1].push_back(make_pair(v2, weight)); 19 | if (!isDirected) m[v2].push_back(make_pair(v1, weight)); 20 | } 21 | 22 | void print() { 23 | cout << "Graph represented as adjacency list:\n"; 24 | for (auto member : m) { 25 | cout << member.first << " --> "; 26 | for (auto i : member.second) { 27 | cout << " (" << i.first << ", " << i.second << ")"; 28 | } 29 | cout << "\n"; 30 | } 31 | cout << "\n"; 32 | } 33 | 34 | void DijkstraPath(int source) { 35 | unordered_map distance; 36 | for (auto element : m) { 37 | distance[element.first] = INT_MAX; 38 | } 39 | 40 | set> newset; // (Distance, Node) 41 | 42 | distance[source] = 0; 43 | newset.insert(make_pair(0, source)); 44 | 45 | while (!newset.empty()) { 46 | auto pair = *(newset.begin()); // get first pair 47 | int element = pair.second; 48 | int dist = pair.first; 49 | newset.erase(newset.begin()); 50 | 51 | for (auto cpair : m[element]) { 52 | if (dist + cpair.second < distance[cpair.first]) { 53 | int destination = cpair.first; 54 | auto first = newset.find(make_pair(distance[destination], destination)); 55 | 56 | if (first != newset.end()) newset.erase(first); 57 | distance[destination] = dist + cpair.second; 58 | newset.insert(make_pair(distance[destination], destination)); 59 | } 60 | } 61 | } 62 | 63 | cout << "Dijkstra distances: " 64 | << "\n"; 65 | for (auto dist : distance) { 66 | cout << dist.first << " -> " << dist.second << "\n"; 67 | } 68 | } 69 | }; 70 | 71 | int main() { 72 | bool isDirected = false; 73 | Graph g(isDirected); 74 | g.addEdge(1, 2, 1); 75 | g.addEdge(1, 4, 7); 76 | g.addEdge(1, 3, 4); 77 | g.addEdge(4, 3, 2); 78 | g.addEdge(3, 2, 1); 79 | g.print(); 80 | g.DijkstraPath(1); 81 | return 0; 82 | } -------------------------------------------------------------------------------- /doubly linked list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class node 5 | { 6 | public: 7 | int data; 8 | node* front; 9 | node* back; 10 | }; 11 | 12 | node* top=NULL; 13 | 14 | int q=0; 15 | 16 | int insert(int pos,int k) 17 | { 18 | node* temp=new node(); 19 | temp->data=k; 20 | temp->front=NULL; 21 | temp->back=NULL; 22 | if(top==NULL) 23 | { 24 | top=temp; 25 | return 0; 26 | } 27 | else if(pos==1) 28 | { 29 | temp->back=top; 30 | top=temp; 31 | return 0; 32 | } 33 | node* temp1=new node(); 34 | temp1=top; 35 | for(int i=0;iback; 37 | node* temp2=temp1; 38 | temp2=temp2->back; 39 | temp->front=temp1; 40 | temp->back=temp2; 41 | temp1->back=temp; 42 | if(temp2!=NULL) 43 | temp2->front=temp; 44 | return 0; 45 | } 46 | 47 | int del(int pos) 48 | { 49 | node* temp = new node(); 50 | temp=top; 51 | if(top==NULL) 52 | { 53 | cout<<"List Empty\n"; 54 | return 0; 55 | } 56 | else if(pos==1&&temp->back==NULL) 57 | { 58 | top=NULL; 59 | return 0; 60 | } 61 | else if(pos==1) 62 | { 63 | temp=temp->back; 64 | temp->front=NULL; 65 | top=temp; 66 | return 0; 67 | } 68 | node* temp1=new node(); 69 | temp1=top; 70 | for(int i=0;iback; 72 | temp=temp1->back; 73 | if(temp->back==NULL) 74 | { 75 | temp1->back=NULL; 76 | return 0; 77 | } 78 | temp=temp->back; 79 | temp1->back=temp; 80 | temp->front=temp1; 81 | return 0; 82 | } 83 | 84 | int traverse() 85 | { 86 | node* temp=new node(); 87 | temp=top; 88 | if(top==NULL) 89 | { 90 | cout<<"List Empty"; 91 | return 0; 92 | } 93 | while(temp!=NULL) 94 | { 95 | cout<data<<" "; 96 | temp=temp->back; 97 | } 98 | cout<>n; 108 | switch(n) 109 | { 110 | case 1: 111 | cout<<"Enter no to be inserted and position(1 based index)\n"; 112 | cin>>a>>b; 113 | insert(b,a); 114 | q++; 115 | break; 116 | case 2: 117 | cout<<"Enter position to be deleted(1 based index)\n"; 118 | cin>>a; 119 | del(a); 120 | q--; 121 | break; 122 | case 3: 123 | traverse(); 124 | break; 125 | case 4: 126 | return 0; 127 | } 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /dutch_National_Flag.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to sort an array using dutch national flag algorithm 2 | // with 0, 1 and 2 in a single pass 3 | 4 | #include 5 | using namespace std; 6 | 7 | // Function to sort the input array, 8 | // the array is assumed 9 | // to have values in {0, 1, 2} 10 | void sort012(int a[], int arr_size) 11 | { 12 | int lo = 0; 13 | int hi = arr_size - 1; 14 | int mid = 0; 15 | 16 | // Iterate till all the elements 17 | // are sorted 18 | while (mid <= hi) { 19 | switch (a[mid]) { 20 | 21 | // If the element is 0 22 | case 0: 23 | swap(a[lo++], a[mid++]); 24 | break; 25 | 26 | // If the element is 1 . 27 | case 1: 28 | mid++; 29 | break; 30 | 31 | // If the element is 2 32 | case 2: 33 | swap(a[mid], a[hi--]); 34 | break; 35 | } 36 | } 37 | } 38 | 39 | // Function to print array arr[] 40 | void printArray(int arr[], int arr_size) 41 | { 42 | // Iterate and print every element 43 | for (int i = 0; i < arr_size; i++) 44 | cout << arr[i] << " "; 45 | } 46 | 47 | // Driver Code 48 | int main() 49 | { 50 | int arr[] = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 }; 51 | int n = sizeof(arr) / sizeof(arr[0]); 52 | 53 | sort012(arr, n); 54 | 55 | cout << "array after segregation "; 56 | 57 | printArray(arr, n); 58 | 59 | return 0; 60 | } 61 | 62 | // Input: {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1} 63 | // Output: {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2} 64 | -------------------------------------------------------------------------------- /factorial: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int n; 6 | long double factorial = 1.0; 7 | 8 | cout << "Enter a positive integer: "; 9 | cin >> n; 10 | 11 | if (n < 0) 12 | cout << "Error! Factorial of a negative number doesn't exist."; 13 | else { 14 | for(int i = 1; i <= n; ++i) { 15 | factorial *= i; 16 | } 17 | cout << "Factorial of " << n << " = " << factorial; 18 | } 19 | 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /fileHandling.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main(){ 6 | string myText; 7 | ifstream MyFile("newfile.txt"); 8 | while(getline(MyFile, myText)){ 9 | cout << myText; 10 | } 11 | 12 | MyFile.close(); 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /flippingalbits.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Let us consider a set of numbers p1,p2,…..,pn such that they are co-prime. Our objective is to find an unknown,x, given the following data: 3 | 4 | x= a1 mod p1 meaning that x gives remainder a1 when divided by p1 5 | 6 | x=a2 mod p2 x gives remainder a2 when divided by p2 7 | 8 | …… 9 | 10 | x= an mod pn 11 | 12 | with this information, we are supposed to determine x. We will see shortly, however, that multiple values of x are possible which satisfy the given constraints. Note that the solution does not always exist as the constraints may be contradicting. 13 | 14 | EFFICIENT METHOD 15 | 16 | Let us take an example to understand the problem more deeply. 17 | 18 | Say, 19 | 20 | 1.x= 3 mod 4 21 | 22 | 2.x= 5 mod 6 23 | 24 | 3.x= 2 mod 5 25 | 26 | We will start the manual calculation with the first statement. 27 | 28 | 1.x= 3 mod 4. Now when we take natural numbers, we can see that 3, 7, 11,15,… and so on can satisfy this. Or, in other words, all numbers from 3 as we add 4 will satisfy this condition. Let us call this a 3(+4 ) set. 29 | 30 | Now let us take the second statement and filter out the possible numbers from the existing set of 3(+4) numbers. 31 | 32 | 2.x= 5 mod 6. The first number from the 3 (+4) set to satisfy this is 11, then we have 23, and so on. We can see that the common difference has become 12 which is the LCM of 6 and 4. Also notice that we haven’t checked all the natural numbers that satisfy this condition this time, only the ones in the previous set. This will reduce the number of checkings we have to do. 33 | 34 | So now the set becomes 11 (+12) set. 35 | 36 | To this let us add the final condition. 37 | 38 | 3.x= 2 mod 5. If we do this similarly we can check that 47 is the first number in the 11(+12 ) set that satisfies this condition. Now we can calculate the common difference as LCM of 5,12 which is 60. So the final set is 47 (+60 ). 39 | 40 | The solution is 47, 107,167, etc. as all these numbers will satisfy the conditions. As we have discussed there are multiple solutions possible in this scenario. But generally we take the least number as the solution as we have done in the brute force method. 41 | 42 | Let us now see the c++ code for this. 43 | */ 44 | #include 45 | #include 46 | using namespace std; 47 | int gcd(int n1, int n2) // calculating gcd using eucledian's formula 48 | { 49 | if (n2 == 0) 50 | return n1; 51 | return gcd(n2, n1 % n2); 52 | } 53 | int lcm(int n1, int n2) 54 | { //caculating lcm using the formula: lcm x gcd = n1 x n2 55 | int gc, lc; 56 | gc = gcd(n1, n2); 57 | lc = n1 * n2 / gc; 58 | return lc; 59 | } 60 | int main() 61 | { 62 | int x, cd, i, p, r, n; 63 | int cnt, flag; // we use this to count the max checks, we can keep it as much as we want 64 | vector pr, rem; 65 | cin >> n; // number of inputs 66 | for (i = 0; i < n; i++) 67 | { 68 | cin >> p >> r; 69 | pr.push_back(p); 70 | rem.push_back(r); 71 | } 72 | x = rem[0]; // let us say the first number will be the starting and 73 | cd = pr[0]; // the first remainder will be the common difference like we saw in the example 74 | for (i = 1; i < n; i++) 75 | { 76 | cnt = 0; 77 | flag = 0; 78 | while (cnt < 100000) // Here we have taken a max value for 10^5 because we are dealing with large numbers 79 | { 80 | if (x % pr[i] == rem[i]) // condition for finding the next start value 81 | { 82 | flag = 1; 83 | break; 84 | } 85 | x = x + cd; 86 | } 87 | if (flag == 0) // This means that no number until cnt range has matched the condition. 88 | { 89 | cout << "No solution."; // Hence no solution is possible 90 | return 0; 91 | } 92 | cd = lcm(pr[i], cd); // updating the cd 93 | } 94 | cout << x << " " << cd; 95 | return 0; 96 | } -------------------------------------------------------------------------------- /heap-sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void heapify(int arr[], int n, int i) { 6 | 7 | int temp; 8 | 9 | int largest = i; 10 | 11 | int l = 2 * i + 1; 12 | 13 | int r = 2 * i + 2; 14 | 15 | if (l < n && arr[l] > arr[largest]) 16 | 17 | largest = l; 18 | 19 | if (r < n && arr[r] > arr[largest]) 20 | 21 | largest = r; 22 | 23 | if (largest != i) { 24 | 25 | temp = arr[i]; 26 | 27 | arr[i] = arr[largest]; 28 | 29 | arr[largest] = temp; 30 | 31 | heapify(arr, n, largest); 32 | 33 | } 34 | 35 | } 36 | 37 | void heapSort(int arr[], int n) { 38 | 39 | int temp; 40 | 41 | for (int i = n / 2 - 1; i >= 0; i--) 42 | 43 | heapify(arr, n, i); 44 | 45 | for (int i = n - 1; i >= 0; i--) { 46 | 47 | temp = arr[0]; 48 | 49 | arr[0] = arr[i]; 50 | 51 | arr[i] = temp; 52 | 53 | heapify(arr, i, 0); 54 | 55 | } 56 | 57 | } 58 | 59 | int main() { 60 | 61 | int arr[] = { 20, 7, 1, 54, 10, 15, 90, 23, 77, 25}; 62 | 63 | int n = 10; 64 | 65 | int i; 66 | 67 | cout<<"Given array is: "< 2 | using namespace std; 3 | 4 | int divisible(int num,int a,int b) 5 | { 6 | int c1=num/a; 7 | int c2=num/b; 8 | int c3=num/(a*b); 9 | 10 | return c1+c2-c3; 11 | } 12 | 13 | int main() 14 | { 15 | int num; 16 | int d1,d2; 17 | cout<<"Enter number"<>num; 19 | cout<<"Enter d1 and d2"<>d1>>d2; 21 | 22 | int res=divisible(num,d1,d2); 23 | cout<<"Number of factor==>"< nxt_element) and (j >= 0): 7 | InputList[j+1] = InputList[j] 8 | j=j-1 9 | InputList[j+1] = nxt_element 10 | list = [19,2,31,45,30,11,121,27] 11 | insertion_sort(list) 12 | print(list) -------------------------------------------------------------------------------- /intersectionnode.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class node{ 5 | public: 6 | int data; 7 | node* next; 8 | 9 | node(int val) 10 | { 11 | data=val; 12 | next=NULL; 13 | } 14 | }; 15 | void insertAtTail(node* &head,int val) 16 | { 17 | if(head==NULL) 18 | { 19 | insertAtHead(head,val); 20 | return; 21 | } 22 | node* n=new node(val); 23 | node* temp=head; 24 | while(temp->next!=NULL) 25 | { 26 | temp=temp->next; 27 | } 28 | temp->next=n; 29 | } 30 | void insertAtHead(node* &head,int val) 31 | { 32 | node* n=new node(val); 33 | n->next=head; 34 | if(head!=NULL) 35 | { 36 | head=n; 37 | } 38 | } 39 | void intersect(node* &head1,node* &head2,int pos) 40 | { 41 | node* temp1=head1; 42 | while(pos) 43 | { 44 | if(temp1==NULL) 45 | pos--; 46 | } 47 | } 48 | void display(node* &head) 49 | { 50 | node* temp=head; 51 | while(temp!=NULL) 52 | { 53 | cout<data<<"-> "; 54 | temp=temp->next; 55 | } 56 | cout<next; 66 | } 67 | return l; 68 | } 69 | 70 | 71 | 72 | int main() 73 | { 74 | node* head1=NULL; 75 | node* head2=NULL; 76 | insertAtTail(head1,1); 77 | insertAtTail(head1,2); 78 | insertAtTail(head1,3); 79 | insertAtTail(head1,4); 80 | insertAtTail(head1,5); 81 | insertAtTail(head1,6); 82 | insertAtTail(head2,9); 83 | insertAtTail(head2,10); 84 | intersect(head1,head2,5); 85 | 86 | 87 | 88 | } 89 | -------------------------------------------------------------------------------- /josephus.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int jos(int n, int k) 5 | { 6 | if(n==1) 7 | { 8 | return 0; 9 | } 10 | return (jos(n-1,k)+k)%n; 11 | } 12 | int main() 13 | { 14 | int n,k; 15 | cin>>n,k; 16 | cout<= 10: 18 | count = 0 19 | write_file(keys) 20 | keys = [] 21 | 22 | def write_file(keys) : 23 | with open("log.txt", "a") as f: 24 | for key in keys: 25 | k = str(key).replace("'","") 26 | if k.find("space") > 0: 27 | f.write('\n') 28 | elif k.find("Key") == -1: 29 | f.write(k) 30 | 31 | 32 | 33 | def on_release(key): 34 | if key == Key.esc: 35 | return False 36 | 37 | 38 | 39 | with Listener(on_press=on_press, on_release=on_release) as listener: 40 | listener.join() 41 | 42 | -------------------------------------------------------------------------------- /kruskal.cpp: -------------------------------------------------------------------------------- 1 | //kruskal algo using union find and path compression 2 | //use ideone https://ideone.com/PYw5b6 gfg 3 | #include 4 | using namespace std; 5 | 6 | struct node 7 | { 8 | int start; 9 | int end; 10 | int weight; 11 | }; 12 | 13 | auto comp = [](node a, node b) { return (a.weight) < (b.weight); }; 14 | multiset s(comp); 15 | vector > :: iterator itr; 16 | int arr[100]; 17 | 18 | int addedge() 19 | { 20 | int a=0,b=0,c=0,i=0,j=0,n=0; 21 | cout<<"Enter number of edges"; 22 | cin>>n; 23 | cout<<"Enter start node, end node and weight"; 24 | for(int i=0;i>a>>b>>c; 27 | node n; 28 | n.start=a; 29 | n.end=b; 30 | n.weight=c; 31 | s.insert(n); 32 | } 33 | } 34 | 35 | 36 | int root(int i) 37 | { 38 | while(arr[i]>0) 39 | i=arr[i]; 40 | return i; 41 | } 42 | 43 | int find(int a,int b) 44 | { 45 | if(root(a)!=root(b)) 46 | return 1; 47 | else 48 | return 0; 49 | } 50 | 51 | int union1(int a,int b)//a(child)->b(parent) 52 | { 53 | int a1=root(a); 54 | int a2=root(b); 55 | if(a1==a2)return 0;//if both parent same, no operation 56 | int flag=0; 57 | if(abs(arr[a1])>abs(arr[a2])) 58 | { 59 | arr[a2]=a1; 60 | arr[a1]--; 61 | flag=1; 62 | } 63 | else 64 | { 65 | arr[a1]=a2; 66 | arr[a2]--; 67 | flag=2; 68 | } 69 | if(find(a,b)==1) 70 | {if(flag==1) 71 | { 72 | arr[a1]=a2; 73 | arr[a2]--; 74 | return 0; 75 | } 76 | else 77 | { 78 | arr[a2]=a1; 79 | arr[a1]--; 80 | return 0; 81 | }} 82 | else 83 | return 1; 84 | } 85 | 86 | 87 | int kruskal(int n) 88 | { 89 | int i=0; 90 | auto it=s.begin(); 91 | while(i>n; 108 | kruskal(n); 109 | return 0; 110 | } 111 | -------------------------------------------------------------------------------- /leap year: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int year; 6 | 7 | cout << "Enter a year: "; 8 | cin >> year; 9 | 10 | if (year % 4 == 0) { 11 | if (year % 100 == 0) { 12 | if (year % 400 == 0) 13 | cout << year << " is a leap year."; 14 | else 15 | cout << year << " is not a leap year."; 16 | } 17 | else 18 | cout << year << " is a leap year."; 19 | } 20 | else 21 | cout << year << " is not a leap year."; 22 | 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /left_pattern.py: -------------------------------------------------------------------------------- 1 | n = int(input("n: ")) 2 | 3 | while (n < 1): 4 | n = int(input("n: ")) 5 | 6 | for i in range(n): 7 | print(((n - i - 1) * " ") + ((i + 1) * "#")) 8 | -------------------------------------------------------------------------------- /linear-search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int linearSearch(int* arr, int length, int value){ 4 | for(int i=0; i 2 | using namespace std; 3 | 4 | int search(int arr[], int a, int b) 5 | { 6 | int i; 7 | for (i = 0; i < a; i++) 8 | if (arr[i] == b) 9 | return i; 10 | return -1; 11 | } 12 | int main(void) 13 | { 14 | int arr[] = { 2, 3, 4, 10, 40 }; 15 | int b = 10; 16 | int a = sizeof(arr) / sizeof(arr[0]); 17 | int result = search(arr, a, b); 18 | (result == -1)? cout << "Element not found": cout << "Element found " << result; 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /linked list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class node 5 | { 6 | public: 7 | int key; 8 | node* next; 9 | }; 10 | 11 | node* top=NULL; 12 | 13 | int q=0; 14 | 15 | int insert(int pos,int data) 16 | { 17 | node* temp=new node();//temp will bw used to make new node, malloc not needed in c++ 18 | temp->key=data; 19 | temp->next=NULL; 20 | if(pos==1) 21 | { 22 | node* temp1=new node(); 23 | temp1=top; 24 | temp->next=temp1; 25 | top=temp; 26 | return 0; 27 | } 28 | if(pos>q+1)//no of elementsnext=NULL; 36 | top=temp; 37 | return 0; 38 | } 39 | 40 | node* temp1=new node();//for traversing 41 | temp1=top;//temp1 is 1st node and not top 42 | for(int i=0;inext; 44 | temp->next=temp1->next;//temp1 is currently the node before pos 45 | temp1->next=temp; 46 | } 47 | 48 | int del(int pos) 49 | { 50 | node* temp=new node(); 51 | temp=top; 52 | if(pos==1) 53 | { 54 | temp=temp->next; 55 | top=temp; 56 | return 0; 57 | } 58 | for(int i=0;inext; 60 | node* temp1=new node(); 61 | temp1=temp->next; 62 | temp->next=temp1->next; 63 | } 64 | 65 | int traverse() 66 | { 67 | if(q==0) 68 | { 69 | cout<<"List Empty\n"; 70 | return 0; 71 | } 72 | node* temp=new node(); 73 | temp=top; 74 | while(temp!=NULL) 75 | { 76 | cout<key<<" "; 77 | temp=temp->next; 78 | } 79 | cout<>n; 89 | switch(n) 90 | { 91 | case 1: 92 | cout<<"Enter no to be inserted and position(1 based index)"; 93 | cin>>a>>b; 94 | insert(b,a); 95 | q++; 96 | break; 97 | case 2: 98 | cout<<"Enter position to be deleted(1 based index)"; 99 | cin>>a; 100 | del(a); 101 | q--; 102 | break; 103 | case 3: 104 | traverse(); 105 | break; 106 | case 4: 107 | return 0; 108 | } 109 | } 110 | } 111 | 112 | -------------------------------------------------------------------------------- /longest awesome string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestAwesome(string s) { 4 | static const int ALPHABET_SIZE = 10; 5 | int result = 0, mask = 0; 6 | vector lookup(1 << ALPHABET_SIZE, s.length()); 7 | lookup[0] = -1; 8 | for (int i = 0; i < s.length(); ++i) { 9 | mask ^= 1 << (s[i] - '0'); 10 | if (lookup[mask] == s.length()) { 11 | lookup[mask] = i; 12 | } 13 | result = max(result, i - lookup[mask]); // no middle 14 | for (int d = 0; d < ALPHABET_SIZE; ++d) { 15 | result = max(result, i - lookup[mask ^ (1 << d)]); // as middle 16 | } 17 | lookup[mask] = min(lookup[mask], i); 18 | } 19 | return result; 20 | } 21 | }; -------------------------------------------------------------------------------- /longest_subarray_sum.cpp: -------------------------------------------------------------------------------- 1 | // Longest Subarray with given Sum 2 | #include 3 | using namespace std; 4 | 5 | int longestSum(int a[],int n,int sum) 6 | { 7 | unordered_map m; 8 | int pre_sum=0, res=0; 9 | for(int i=0;i>n; 32 | int a[n]; 33 | for(int i=0;i>a[i]; 36 | } 37 | int sum; 38 | cin>>sum; 39 | cout< hlen(n); 14 | for (int i = 0; i < n; ++i) { 15 | if (i < right) hlen[i] = min(right-i, hlen[2*center-i]); 16 | while (0 <= i-1-hlen[i] && i+1+hlen[i] < n && ss[i-1-hlen[i]] == ss[i+1+hlen[i]]) ++hlen[i]; 17 | if (right < i+hlen[i]) center = i, right = i+hlen[i]; 18 | } 19 | 20 | int ii = 0, xx = 0; 21 | for (int i = 0; i < n; ++i) 22 | if (xx < hlen[i]) ii = i, xx = hlen[i]; 23 | return s.substr((ii-xx)/2, xx); 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /luhn_algo.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to implement Luhn algorithm 2 | #include 3 | using namespace std; 4 | 5 | // Returns true if given card number is valid 6 | bool checkLuhn(const string& cardNo) 7 | { 8 | int nDigits = cardNo.length(); 9 | 10 | int nSum = 0, isSecond = false; 11 | for (int i = nDigits - 1; i >= 0; i--) { 12 | 13 | int d = cardNo[i] - '0'; 14 | 15 | if (isSecond == true) 16 | d = d * 2; 17 | 18 | // We add two digits to handle 19 | // cases that make two digits after 20 | // doubling 21 | nSum += d / 10; 22 | nSum += d % 10; 23 | 24 | isSecond = !isSecond; 25 | } 26 | return (nSum % 10 == 0); 27 | } 28 | 29 | // Driver code 30 | int main() 31 | { 32 | string cardNo = "79927398713"; 33 | if (checkLuhn(cardNo)) 34 | printf("This is a valid card"); 35 | else 36 | printf("This is not a valid card"); 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /macros.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "myMath.h" 3 | #define SQUARE(x,y) (x) * (y) 4 | using namespace std; 5 | int main(){ 6 | cout << SQUARE(2+2,4) << endl; 7 | count << sum(3,3)<< endl; 8 | count << << endl; 9 | count << << endl; 10 | count << << endl; 11 | } 12 | -------------------------------------------------------------------------------- /matrixColumnExchange.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | int array[5][5], i, j; 6 | cout << "Matrix Column Flip\nEnter Matrix elements:\n"; 7 | for(i = 0; i < 5; i++){ 8 | for(j = 0; j < 5; j++){ 9 | cout << "a" << i+1<> array[i][j]; 11 | } 12 | } 13 | cout << "Entered Matrix\n"; 14 | for(i = 0; i < 5; i++){ 15 | for(j = 0; j < 5; j++){ 16 | cout << array[i][j] << "\t"; 17 | } 18 | cout << "\n"; 19 | } 20 | cout << "Flipped Matrix\n"; 21 | for(i = 0; i < 5; i++){ 22 | for(j = 4; j >= 0; j--){ 23 | cout << array[i][j] << "\t"; 24 | } 25 | cout << "\n"; 26 | } 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /matrixFlip.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | cout << "Matrix Row Flip:\nEnter Matrix Elements\n"; 6 | int array[2][3], i, j; 7 | for(i = 0; i < 2; i++){ 8 | for(j = 0; j < 3; j++){ 9 | cout << "a" << i+1 << j+1 << ": "; 10 | cin >> array[i][j]; 11 | } 12 | } 13 | cout << "original matrix\n"; 14 | for(i = 0; i < 2; i++){ 15 | for(j = 0; j < 3; j++){ 16 | cout << array[i][j] << "\t"; 17 | } 18 | cout << "\n"; 19 | } 20 | cout << "Flipped matrix\n"; 21 | for(i = 1; i >= 0; i--){ 22 | for(j = 0; j < 3; j++){ 23 | cout << array[i][j] << "\t"; 24 | } 25 | cout << "\n"; 26 | } 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /matrix_chain_multiplication.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | // Initial Template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | // User function Template for C++ 9 | 10 | class Solution{ 11 | public: 12 | int matrixMultiplication(int n, int arr[]) 13 | { 14 | int dp[n][n]; 15 | for(int i=0; i>t; 37 | while(t--){ 38 | int N; 39 | cin>>N; 40 | int arr[N]; 41 | for(int i = 0;i < N;i++) 42 | cin>>arr[i]; 43 | 44 | Solution ob; 45 | cout< 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int a[] = {6, 2, 5, 4, 5, 1, 6}; 7 | int n = sizeof(a) / sizeof(a[0]); 8 | 9 | //we have to find max area of rectangle in hiostogram (pepcoding vid) 10 | 11 | //for solving we will have to find the nearest shorter element to the curr element on both side 12 | //as if side elements are greater than curr, then they would contribute in rectangle but the width will stop as soon as 13 | // we encounter shorter height on both sides 14 | 15 | stack s; 16 | 17 | s.push(n - 1); 18 | 19 | int rb[n]; // next shorter element on right 20 | rb[n - 1] = n - 1; 21 | 22 | for (int i = n - 2; i >= 0; i--) 23 | { 24 | 25 | while (s.size() > 0 && a[i] < a[s.top()]) 26 | s.pop(); 27 | 28 | if (s.size() == 0) 29 | rb[i] = n; 30 | else 31 | rb[i] = s.top(); 32 | 33 | s.push(i); 34 | } 35 | 36 | int lb[n]; //next shorter element on left 37 | lb[0] = -1; 38 | 39 | for (int i = 1; i < n; i++) 40 | { 41 | while (s.size() > 0 && a[i] < a[s.top()]) 42 | s.pop(); 43 | 44 | if (s.size() == 0) 45 | lb[i] = -1; 46 | else 47 | lb[i] = s.top(); 48 | 49 | s.push(i); 50 | } 51 | 52 | int maxArea = 0; 53 | for (int i = 0; i < n; i++) 54 | { 55 | int width = rb[i] - lb[i] - 1; 56 | int h = a[i]; 57 | int currArea = h * width; 58 | 59 | if (currArea > maxArea) 60 | maxArea = currArea; 61 | } 62 | cout << maxArea; 63 | } -------------------------------------------------------------------------------- /merge.py: -------------------------------------------------------------------------------- 1 | def merge_sort(unsorted_list): 2 | if len(unsorted_list) <= 1: 3 | return unsorted_list 4 | # Find the middle point and devide it 5 | middle = len(unsorted_list) // 2 6 | left_list = unsorted_list[:middle] 7 | right_list = unsorted_list[middle:] 8 | 9 | left_list = merge_sort(left_list) 10 | right_list = merge_sort(right_list) 11 | return list(merge(left_list, right_list)) 12 | 13 | # Merge the sorted halves 14 | def merge(left_half,right_half): 15 | res = [] 16 | while len(left_half) != 0 and len(right_half) != 0: 17 | if left_half[0] < right_half[0]: 18 | res.append(left_half[0]) 19 | left_half.remove(left_half[0]) 20 | else: 21 | res.append(right_half[0]) 22 | right_half.remove(right_half[0]) 23 | if len(left_half) == 0: 24 | res = res + right_half 25 | else: 26 | res = res + left_half 27 | return res 28 | unsorted_list = [64, 34, 25, 12, 22, 11, 90] 29 | print(merge_sort(unsorted_list)) -------------------------------------------------------------------------------- /mergesort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for Merge Sort 2 | #include 3 | using namespace std; 4 | 5 | // Merges two subarrays of array[]. 6 | // First subarray is arr[begin..mid] 7 | // Second subarray is arr[mid+1..end] 8 | void merge(int array[], int const left, int const mid, int const right) 9 | { 10 | auto const subArrayOne = mid - left + 1; 11 | auto const subArrayTwo = right - mid; 12 | 13 | // Create temp arrays 14 | auto *leftArray = new int[subArrayOne], 15 | *rightArray = new int[subArrayTwo]; 16 | 17 | // Copy data to temp arrays leftArray[] and rightArray[] 18 | for (auto i = 0; i < subArrayOne; i++) 19 | leftArray[i] = array[left + i]; 20 | for (auto j = 0; j < subArrayTwo; j++) 21 | rightArray[j] = array[mid + 1 + j]; 22 | 23 | auto indexOfSubArrayOne = 0, // Initial index of first sub-array 24 | indexOfSubArrayTwo = 0; // Initial index of second sub-array 25 | int indexOfMergedArray = left; // Initial index of merged array 26 | 27 | // Merge the temp arrays back into array[left..right] 28 | while (indexOfSubArrayOne < subArrayOne && indexOfSubArrayTwo < subArrayTwo) { 29 | if (leftArray[indexOfSubArrayOne] <= rightArray[indexOfSubArrayTwo]) { 30 | array[indexOfMergedArray] = leftArray[indexOfSubArrayOne]; 31 | indexOfSubArrayOne++; 32 | } 33 | else { 34 | array[indexOfMergedArray] = rightArray[indexOfSubArrayTwo]; 35 | indexOfSubArrayTwo++; 36 | } 37 | indexOfMergedArray++; 38 | } 39 | // Copy the remaining elements of 40 | // left[], if there are any 41 | while (indexOfSubArrayOne < subArrayOne) { 42 | array[indexOfMergedArray] = leftArray[indexOfSubArrayOne]; 43 | indexOfSubArrayOne++; 44 | indexOfMergedArray++; 45 | } 46 | // Copy the remaining elements of 47 | // right[], if there are any 48 | while (indexOfSubArrayTwo < subArrayTwo) { 49 | array[indexOfMergedArray] = rightArray[indexOfSubArrayTwo]; 50 | indexOfSubArrayTwo++; 51 | indexOfMergedArray++; 52 | } 53 | } 54 | 55 | // begin is for left index and end is 56 | // right index of the sub-array 57 | // of arr to be sorted */ 58 | void mergeSort(int array[], int const begin, int const end) 59 | { 60 | if (begin >= end) 61 | return; // Returns recursively 62 | 63 | auto mid = begin + (end - begin) / 2; 64 | mergeSort(array, begin, mid); 65 | mergeSort(array, mid + 1, end); 66 | merge(array, begin, mid, end); 67 | } 68 | 69 | // UTILITY FUNCTIONS 70 | // Function to print an array 71 | void printArray(int A[], int size) 72 | { 73 | for (auto i = 0; i < size; i++) 74 | cout << A[i] << " "; 75 | } 76 | 77 | // Driver code 78 | int main() 79 | { 80 | int arr[] = { 12, 11, 13, 5, 6, 7 }; 81 | auto arr_size = sizeof(arr) / sizeof(arr[0]); 82 | 83 | cout << "Given array is \n"; 84 | printArray(arr, arr_size); 85 | 86 | mergeSort(arr, 0, arr_size - 1); 87 | 88 | cout << "\nSorted array is \n"; 89 | printArray(arr, arr_size); 90 | return 0; 91 | } 92 | 93 | // This code is contributed by Mayank Tyagi 94 | // This code was revised by Joshua Estes 95 | -------------------------------------------------------------------------------- /minCostPath.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | //DP 5 | int minCostPath_3(int **input,int m,int n) 6 | { 7 | int **matrix = new int*[m]; 8 | for(int i=0;i=0;j--) 17 | { 18 | matrix[m-1][j] = matrix[m-1][j+1] + input[m-1][j]; 19 | } 20 | 21 | //fill last column (bottom to top) 22 | for(int i = m-2;i>=0;i--) 23 | { 24 | matrix[i][n-1] = matrix[i+1][n-1] + input[i][n-1]; 25 | } 26 | 27 | //Fill remaining cells 28 | for(int i=m-2;i>=0;i--) 29 | { 30 | for(int j=n-2;j>=0;j--) 31 | { 32 | matrix[i][j] = min(matrix[i][j+1],min(matrix[i+1][j+1],matrix[i+1][j])) + input[i][j]; 33 | } 34 | } 35 | 36 | return matrix[0][0]; 37 | 38 | } 39 | 40 | //Memoisation 41 | int helper(int **input,int m,int n,int i,int j,int **matrix) 42 | { 43 | if(i==m-1 && j==n-1) 44 | { 45 | return input[i][j]; 46 | } 47 | if(i>=m || j>=n) return INT_MAX; 48 | if(matrix[i][j]!=-1) return matrix[i][j]; 49 | 50 | int x = helper(input,m,n,i+1,j,matrix); 51 | int y = helper(input,m,n,i+1,j+1,matrix); 52 | int z = helper(input,m,n,i,j+1,matrix); 53 | 54 | matrix[i][j] = min(x,min(y,z))+input[i][j]; 55 | return matrix[i][j]; 56 | } 57 | 58 | int minCostPath_2(int **input,int m,int n) 59 | { 60 | int **matrix = new int*[m]; 61 | for(int i=0;i=m || j>=n) 90 | { 91 | return INT_MAX; 92 | } 93 | 94 | int x = helper(input,m,n,i+1,j); 95 | int y = helper(input,m,n,i+1,j+1); 96 | int z = helper(input,m,n,i,j+1); 97 | 98 | return min(x,min(y,z))+input[i][j]; 99 | } 100 | int minCostPath(int **input, int m, int n) 101 | { 102 | return helper(input,m,n,0,0); 103 | } 104 | 105 | int main() 106 | { 107 | int **arr, n, m; 108 | cin >> n >> m; 109 | arr = new int *[n]; 110 | for (int i = 0; i < n; i++) 111 | { 112 | arr[i] = new int[m]; 113 | } 114 | for (int i = 0; i < n; i++) 115 | { 116 | for (int j = 0; j < m; j++) 117 | { 118 | cin >> arr[i][j]; 119 | } 120 | } 121 | cout << minCostPath(arr, n, m) << endl; 122 | cout << minCostPath_2(arr, n, m) << endl; 123 | cout << minCostPath_3(arr, n, m) << endl; 124 | } 125 | -------------------------------------------------------------------------------- /minMax.cpp: -------------------------------------------------------------------------------- 1 | // Program to find maximum and minimum of 2 | // two numbers without using loop and any 3 | // condition. 4 | #include 5 | 6 | int main () 7 | { 8 | int a = 30, b = 20; 9 | printf("max number = %d\n", ((a + b) + abs(a - b)) / 2); 10 | printf("min number= %d", ((a + b) - abs(a - b)) / 2); 11 | return 0; 12 | } 13 | 14 | 15 | //output 16 | // max number = 30 17 | // min number = 20 18 | -------------------------------------------------------------------------------- /mystery_number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | cout<<"Find the Mystery Number!"<>first_number; 9 | if (first_number == 5) { 10 | cout<<"Congratulations you find the mistery number!"; 11 | return 0; 12 | } 13 | else (first_number != 5); 14 | cout<<"The number is not Mystery Number, please try again"<>second_number; 19 | if (second_number == 5) { 20 | cout<<"Congratulations you find the mistery number!"; 21 | return 0; 22 | } 23 | else (second_number != 5) ; 24 | cout<<"The number is not Mystery Number, please try again"<>third_number; 29 | if (third_number == 5) { 30 | cout<<"Congratulations you find the mistery number!"; 31 | return 0; 32 | } 33 | else (second_number != 5) ; 34 | cout<<"The number is not Mystery Number, your chance has run out, the answer is 5"< 2 | using namespace std; 3 | 4 | void swap(int*a,int*b) 5 | { 6 | int temp; 7 | temp = *a; 8 | *b=*a; 9 | *b=temp; 10 | } 11 | int main() 12 | 13 | 14 | 15 | { 16 | int a,b,temp; 17 | cout<<"Enter first number: "<>a; 19 | cout<<"Enter second number: "<>b; 21 | swap(a,b); 22 | cout<<"swapped number 1 is "< 2 | using namespace std; 3 | int main() 4 | { 5 | int n,r,sum=0,temp; 6 | cout<<"Enter the Number="; 7 | cin>>n; 8 | temp=n; 9 | while(n>0) 10 | { 11 | r=n%10; 12 | sum=(sum*10)+r; 13 | n=n/10; 14 | } 15 | if(temp==sum) 16 | cout<<"Number is Palindrome."; 17 | else 18 | cout<<"Number is not Palindrome."; 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /pointer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main(){ 6 | long long a = 50; 7 | long long *ptr = &a; 8 | cout << "&a " << &a << "\n"; 9 | cout << "a " << a << "\n"; 10 | cout << "*ptr "<<*ptr<<"\n"; 11 | cout << "ptr " << ptr << "\n"; 12 | ptr = &a; 13 | cout << "*ptr " << *ptr << "\n"; 14 | cout << "ptr " << ptr << "\n"; 15 | *ptr = a; 16 | cout << "*ptr " << *ptr << "\n"; 17 | cout << "ptr " << ptr << "\n"; 18 | 19 | cout << "&ptr " << &ptr << "\n"; 20 | cout << "sizeof(ptr) " << sizeof(ptr) << "\n"; 21 | cout << "sizeof(*ptr) " << sizeof(*ptr) << "\n"; 22 | cout << "sizeof(&ptr) " << sizeof(&ptr) << "\n"; 23 | cout << "sizeof(a) " << sizeof(a) << "\n"; 24 | //cout << "sizeof(a) " << sizeof(*a) << "\n"; 25 | cout << "sizeof(&a) " << sizeof(&a) << "\n"; 26 | 27 | } -------------------------------------------------------------------------------- /pointerToPointers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | int main(){ 6 | int array[5][5], i, j; 7 | for(i = 0; i < 5; i++){ 8 | for(j = 0; j < 5; j++){ 9 | array[i][j] = j+1; 10 | } 11 | } 12 | for(i = 0; i < 5; i++){ 13 | for(j = 0; j < 5; j++){ 14 | cout << array[i][j]<< "\t"; 15 | } 16 | cout << endl<< endl; 17 | } 18 | cout << *(*(array+3)+3); 19 | int *arrayptr, **multiptr; 20 | arrayptr = &*array[0]; 21 | cout <<*arrayptr< 2 | using namespace std; 3 | int main(){ 4 | int x = 5; 5 | int *xptr; 6 | xptr = &x; 7 | cout << "x = " << x < 2 | using namespace std; 3 | 4 | bool checkPrimeNumber(int); 5 | 6 | int main() { 7 | int n; 8 | 9 | cout << "Enter a positive integer: "; 10 | cin >> n; 11 | 12 | if (checkPrimeNumber(n)) 13 | cout << n << " is a prime number."; 14 | else 15 | cout << n << " is not a prime number."; 16 | return 0; 17 | } 18 | 19 | bool checkPrimeNumber(int n) { 20 | bool isPrime = true; 21 | 22 | // 0 and 1 are not prime numbers 23 | if (n == 0 || n == 1) { 24 | isPrime = false; 25 | } 26 | else { 27 | for (int i = 2; i <= n / 2; ++i) { 28 | if (n % i == 0) { 29 | isPrime = false; 30 | break; 31 | } 32 | } 33 | } 34 | return isPrime; 35 | } 36 | -------------------------------------------------------------------------------- /prims_algo.cpp: -------------------------------------------------------------------------------- 1 | // A C++ program for Prim's Minimum 2 | // Spanning Tree (MST) algorithm. The program is 3 | // for adjacency matrix representation of the graph 4 | #include 5 | using namespace std; 6 | 7 | // Number of vertices in the graph 8 | #define V 5 9 | 10 | // A utility function to find the vertex with 11 | // minimum key value, from the set of vertices 12 | // not yet included in MST 13 | int minKey(int key[], bool mstSet[]) 14 | { 15 | // Initialize min value 16 | int min = INT_MAX, min_index; 17 | 18 | for (int v = 0; v < V; v++) 19 | if (mstSet[v] == false && key[v] < min) 20 | min = key[v], min_index = v; 21 | 22 | return min_index; 23 | } 24 | 25 | // A utility function to print the 26 | // constructed MST stored in parent[] 27 | void printMST(int parent[], int graph[V][V]) 28 | { 29 | cout<<"Edge \tWeight\n"; 30 | for (int i = 1; i < V; i++) 31 | cout< 2 | #include 3 | using namespace std; 4 | 5 | int main() { 6 | 7 | float a, b, c, x1, x2, discriminant, realPart, imaginaryPart; 8 | cout << "Enter coefficients a, b and c: "; 9 | cin >> a >> b >> c; 10 | discriminant = b*b - 4*a*c; 11 | 12 | if (discriminant > 0) { 13 | x1 = (-b + sqrt(discriminant)) / (2*a); 14 | x2 = (-b - sqrt(discriminant)) / (2*a); 15 | cout << "Roots are real and different." << endl; 16 | cout << "x1 = " << x1 << endl; 17 | cout << "x2 = " << x2 << endl; 18 | } 19 | 20 | else if (discriminant == 0) { 21 | cout << "Roots are real and same." << endl; 22 | x1 = -b/(2*a); 23 | cout << "x1 = x2 =" << x1 << endl; 24 | } 25 | 26 | else { 27 | realPart = -b/(2*a); 28 | imaginaryPart =sqrt(-discriminant)/(2*a); 29 | cout << "Roots are complex and different." << endl; 30 | cout << "x1 = " << realPart << "+" << imaginaryPart << "i" << endl; 31 | cout << "x2 = " << realPart << "-" << imaginaryPart << "i" << endl; 32 | } 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /quicksort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | 6 | int Partition(int arr[],int lb,int ub) 7 | { 8 | int pivot=arr[lb]; 9 | int start=lb; 10 | int end=ub; 11 | int temp=0; 12 | 13 | while (startpivot) 20 | { 21 | end--; 22 | } 23 | 24 | if(end>start) 25 | { 26 | temp=0; 27 | temp=arr[start]; 28 | arr[start]=arr[end]; 29 | arr[end]=temp; 30 | } 31 | 32 | 33 | } 34 | 35 | temp=0; 36 | temp=arr[lb]; 37 | arr[lb]=arr[end]; 38 | arr[end]=temp; 39 | 40 | return end; 41 | 42 | } 43 | 44 | 45 | void Quicksort(int arr[],int lb,int ub) 46 | { 47 | int loc=0; 48 | if (lb>n; 61 | int arr[100]; 62 | 63 | cout<<"Enter array elements\n"; 64 | int i; 65 | for(i=0;i>arr[i]; 68 | } 69 | 70 | Quicksort(arr,0,n-1); 71 | 72 | cout<<"Sorted array"< 4 | using namespace std; 5 | int main(){ 6 | int n,a[n],b[n]; 7 | cout<<"Enter the size of an array\n"; 8 | cin>>n; 9 | cout<<"Enter the elements\n"; 10 | for(int i=0;i>a[i]; 12 | b[n-1-i]=a[i]; 13 | } 14 | cout<<"Reverse elements are : "; 15 | for(int j=0;j 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int n, m; 8 | cout << "Enter the row size :- \n"; 9 | cin >> n; 10 | cout << "Enter the coulumn size \n"; 11 | cin >> m; 12 | int a[n][m]; 13 | 14 | cout << "Enter the arrat \n"; 15 | for (int i = 0; i < n; i++) 16 | { 17 | for (int j = 0; j < m; j++) 18 | { 19 | cin >> a[i][j]; 20 | } 21 | } 22 | int x; 23 | cout << "Enter the element you want to search in array\n"; 24 | cin >> x; 25 | int right = m - 1, top = 0, bottom = n - 1, left = 0; 26 | bool f = 0; 27 | int i = 0, j = m - 1; 28 | for (int i = right; i >= 0; i--) 29 | { 30 | if (x < a[top][right]) 31 | { 32 | right--; 33 | } 34 | if (x == a[top][right]) 35 | { 36 | f = 1; 37 | cout << "Found at " 38 | << "(" << top << "," << right << ")"; 39 | break; 40 | } 41 | if (x > a[top][right]) 42 | { 43 | top++; 44 | } 45 | } 46 | 47 | if (f == 0) 48 | cout << "The element not found"; 49 | 50 | return 0; 51 | } -------------------------------------------------------------------------------- /search_2D_Array.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/piyush-kash/Hacktober2021-cpp-py/ea6d6f30a9d5b28069ff5ed19a5ba57dee529daf/search_2D_Array.exe -------------------------------------------------------------------------------- /selection.py: -------------------------------------------------------------------------------- 1 | def selection_sort(input_list): 2 | for idx in range(len(input_list)): 3 | min_idx = idx 4 | for j in range( idx +1, len(input_list)): 5 | if input_list[min_idx] > input_list[j]: 6 | min_idx = j 7 | # Swap the minimum value with the compared value 8 | input_list[idx], input_list[min_idx] = input_list[min_idx], input_list[idx] 9 | l = [19,2,31,45,30,11,121,27] 10 | selection_sort(l) 11 | print(l) -------------------------------------------------------------------------------- /selectionSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void swapping(int &a, int &b) { //swap the content of a and b 4 | int temp; 5 | temp = a; 6 | a = b; 7 | b = temp; 8 | } 9 | void display(int *array, int size) { 10 | for(int i = 0; i> n; 29 | int arr[n]; //create an array with given number of elements 30 | cout << "Enter elements:" << endl; 31 | for(int i = 0; i> arr[i]; 33 | } 34 | cout << "Array before Sorting: "; 35 | display(arr, n); 36 | selectionSort(arr, n); 37 | cout << "Array after Sorting: "; 38 | display(arr, n); 39 | } -------------------------------------------------------------------------------- /shortest path visiting all nodes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void print_vector(vector v){ 4 | cout << "["; 5 | for(int i = 0; i >& graph){ 13 | queue > q; 14 | int n = graph.size(); 15 | int req = (1 << n) - 1; 16 | map > visited; 17 | for (int i = 0; i < n; i++) { 18 | q.push({ 0 | (1 << i), i }); 19 | } 20 | if (n == 1) 21 | return 0; 22 | for (int lvl = 1; !q.empty(); lvl++) { 23 | int sz = q.size(); 24 | while (sz--) { 25 | vector curr = q.front(); 26 | q.pop(); 27 | for (int i = 0; i < graph[curr[1]].size(); i++) { 28 | int u = graph[curr[1]][i]; 29 | int newMask = (curr[0] | (1 << u)); 30 | if (newMask == req) 31 | return lvl; 32 | if (visited[u].count(newMask)) 33 | continue; 34 | visited[u].insert(newMask); 35 | q.push({ newMask, u }); 36 | } 37 | } 38 | } 39 | return -1; 40 | } 41 | }; 42 | main(){ 43 | Solution ob; 44 | vector> v = {{1},{0,2,4},{1,3,4},{2},{1,2}}; 45 | cout << (ob.shortestPathLength(v)); 46 | } -------------------------------------------------------------------------------- /shortest_superstring.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string shortestSuperstring(vector& A) { 4 | const int n = A.size(); 5 | vector> overlaps(n, vector(n)); 6 | for (int i = 0; i < n; ++i) { 7 | for (int j = 0; j < n; ++j) { 8 | for (int l = min(A[i].length(), A[j].length()); 9 | l >= 0; --l) { 10 | if (A[i].substr(A[i].length() - l) == A[j].substr(0, l)) { 11 | overlaps[i][j] = l; 12 | break; 13 | } 14 | } 15 | } 16 | } 17 | 18 | vector> dp(1 << n, vector(n)); 19 | vector> prev(1 << n, vector(n, -1)); 20 | for (int mask = 1; mask < 1 << n; ++mask) { 21 | for (int bit = 0; bit < n; ++bit) { 22 | if (((mask >> bit) & 1) == 0) { 23 | continue; 24 | } 25 | auto prev_mask = mask ^ (1 << bit); 26 | for (int i = 0; i < n; ++i) { 27 | if (((prev_mask >> i) & 1) == 0) { 28 | continue; 29 | } 30 | auto value = dp[prev_mask][i] + overlaps[i][bit]; 31 | if (value > dp[mask][bit]) { 32 | dp[mask][bit] = value; 33 | prev[mask][bit] = i; 34 | } 35 | } 36 | } 37 | } 38 | 39 | int bit = -1; 40 | for (int i = 0; i < n; ++i) { 41 | if (bit == -1 || 42 | dp.back()[i] > dp.back()[bit]) { 43 | bit = i; 44 | } 45 | } 46 | vector words; 47 | for (int mask = (1 << n) - 1; bit != -1;) { 48 | words.emplace_back(bit); 49 | tie(mask, bit) = make_pair(mask ^ (1 << bit), 50 | prev[mask][bit]); 51 | } 52 | reverse(words.begin(), words.end()); 53 | unordered_set lookup(words.begin(), words.end()); 54 | for (int i = 0; i < n; ++i) { 55 | if (!lookup.count(i)) { 56 | words.emplace_back(i); 57 | } 58 | } 59 | 60 | auto result = A[words[0]]; 61 | for (int i = 1; i < words.size(); ++i) { 62 | auto overlap = overlaps[words[i - 1]][words[i]]; 63 | result += A[words[i]].substr(overlap); 64 | } 65 | return result; 66 | } 67 | }; -------------------------------------------------------------------------------- /sieveoferatosthenes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void SieveOfEratosthenes(int n) 5 | { 6 | 7 | bool prime[n + 1]; 8 | memset(prime, true, sizeof(prime)); 9 | 10 | for (int i = 2; i * i <= n; i++) 11 | { 12 | 13 | if (prime[i] == true) 14 | { 15 | 16 | for (int j = i * i; j <= n; j += i) 17 | prime[j] = false; 18 | } 19 | } 20 | 21 | // Print all prime numbers 22 | for (int i = 2; i <= n; i++) 23 | if (prime[i]) 24 | cout << i << " "; 25 | } 26 | 27 | 28 | int main() 29 | { 30 | int n; 31 | cin>>n; 32 | cout << "prime numbers smaller than or equal to"<< n<<":"<< endl; 33 | SieveOfEratosthenes(n); 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /simple_text_editor.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define ll long long 3 | using namespace std; 4 | int main() 5 | { 6 | ll q,t,k; 7 | string w,s=""; 8 | vector v; 9 | cin>>q; 10 | while(q--) 11 | { 12 | cin>>t; 13 | 14 | if(t==1) 15 | { 16 | cin>>w; 17 | s=s+w; 18 | v.push_back(s); 19 | } 20 | else if(t==2) 21 | { 22 | cin>>k; 23 | s=s.substr(0,s.length()-k); 24 | v.push_back(s); 25 | } 26 | else if(t==3) 27 | { 28 | cin>>k; 29 | cout< 2 | using namespace std; 3 | int main() 4 | { 5 | float n1,n2; 6 | cout<<"Input 2 nos.: "; 7 | cin>>n1>>n2; 8 | char op; 9 | cout<<"Input an operator"; 10 | cin>>op; 11 | 12 | switch (op) 13 | { 14 | case '+': 15 | cout< 4 | using namespace std; 5 | 6 | /* Utility to swap to integers */ 7 | void swap(int* a, int* b) 8 | { 9 | int temp; 10 | temp = *a; 11 | *a = *b; 12 | *b = temp; 13 | } 14 | 15 | /* Utility function that puts all 16 | non-positive (0 and negative) numbers on left 17 | side of arr[] and return count of such numbers */ 18 | int segregate(int arr[], int size) 19 | { 20 | int j = 0, i; 21 | for (i = 0; i < size; i++) { 22 | if (arr[i] <= 0) { 23 | swap(&arr[i], &arr[j]); 24 | 25 | // increment count of 26 | // non-positive integers 27 | j++; 28 | } 29 | } 30 | 31 | return j; 32 | } 33 | 34 | /* Find the smallest positive missing number 35 | in an array that contains all positive integers */ 36 | int findMissingPositive(int arr[], int size) 37 | { 38 | int i; 39 | 40 | // Mark arr[i] as visited by 41 | // making arr[arr[i] - 1] negative. 42 | // Note that 1 is subtracted 43 | // because index start 44 | // from 0 and positive numbers start from 1 45 | for (i = 0; i < size; i++) { 46 | if (abs(arr[i]) - 1 < size && arr[abs(arr[i]) - 1] > 0) 47 | arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1]; 48 | } 49 | 50 | // Return the first index 51 | // value at which is positive 52 | for (i = 0; i < size; i++) 53 | if (arr[i] > 0) 54 | 55 | // 1 is added because 56 | // indexes start from 0 57 | return i + 1; 58 | 59 | return size + 1; 60 | } 61 | 62 | /* Find the smallest positive missing 63 | number in an array that contains 64 | both positive and negative integers */ 65 | int findMissing(int arr[], int size) 66 | { 67 | 68 | // First separate positive 69 | // and negative numbers 70 | int shift = segregate(arr, size); 71 | 72 | // Shift the array and call 73 | // findMissingPositive for 74 | // positive part 75 | return findMissingPositive(arr + shift, 76 | size - shift); 77 | } 78 | 79 | // Driver code 80 | int main() 81 | { 82 | int arr[] = { 0, 10, 2, -10, -20 }; 83 | int arr_size = sizeof(arr) / sizeof(arr[0]); 84 | int missing = findMissing(arr, arr_size); 85 | cout << "The smallest positive missing number is " << missing; 86 | return 0; 87 | } 88 | 89 | // This is code is contributed by rathbhupendra 90 | -------------------------------------------------------------------------------- /stackUsingLL.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node { 5 | public: 6 | int data; 7 | Node *next; 8 | 9 | Node(int data) { 10 | this->data = data; 11 | next = NULL; 12 | } 13 | }; 14 | 15 | 16 | class Stack { 17 | Node *head; 18 | int size; // number of elements prsent in stack 19 | 20 | public : 21 | 22 | Stack() { 23 | head=NULL; 24 | size=0; 25 | } 26 | 27 | int getSize() { 28 | return size; 29 | } 30 | 31 | bool isEmpty() { 32 | return head==NULL; 33 | } 34 | 35 | void push(int element) { 36 | Node *newNode=new Node (element); 37 | if(head==NULL) 38 | head=newNode; 39 | else{ 40 | newNode->next=head; 41 | head=newNode; 42 | } 43 | 44 | size++; 45 | } 46 | 47 | int pop() { 48 | // Return 0 if stack is empty. Don't display any other message 49 | if(isEmpty()) 50 | return -1; 51 | else{ 52 | int ans=head->data; 53 | Node *temp=head; 54 | head=head->next; 55 | delete temp; 56 | size--; 57 | return ans; 58 | } 59 | } 60 | 61 | int top() { 62 | // Return 0 if stack is empty. Don't display any other message 63 | if(isEmpty()) 64 | return -1; 65 | else 66 | return head->data; 67 | } 68 | 69 | 70 | 71 | }; 72 | 73 | int main() { 74 | Stack st; 75 | 76 | int q; 77 | cin >> q; 78 | 79 | while (q--) { 80 | int choice, input; 81 | cin >> choice; 82 | switch (choice) { 83 | case 1: 84 | cin >> input; 85 | st.push(input); 86 | break; 87 | case 2: 88 | cout << st.pop() << "\n"; 89 | break; 90 | case 3: 91 | cout << st.top() << "\n"; 92 | break; 93 | case 4: 94 | cout << st.getSize() << "\n"; 95 | break; 96 | default: 97 | cout << ((st.isEmpty()) ? "true\n" : "false\n"); 98 | break; 99 | } 100 | } 101 | } -------------------------------------------------------------------------------- /sticker_to_spell.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minStickers(vector& stickers, string target) { 4 | vector> sticker_counts(stickers.size(), vector(26)); 5 | unordered_map dp; 6 | for (int i = 0; i < stickers.size(); ++i) { 7 | for (const auto& c : stickers[i]) { 8 | ++sticker_counts[i][c - 'a']; 9 | } 10 | } 11 | dp[""] = 0; 12 | return minStickersHelper(sticker_counts, target, &dp); 13 | } 14 | 15 | private: 16 | int minStickersHelper(const vector>& sticker_counts, const string& target, 17 | unordered_map *dp) { 18 | if (dp->count(target)) { 19 | return (*dp)[target]; 20 | } 21 | int result = numeric_limits::max(); 22 | vector target_count(26); 23 | for (const auto& c : target) { 24 | ++target_count[c - 'a']; 25 | } 26 | for (const auto& sticker_count : sticker_counts) { 27 | if (sticker_count[target[0] - 'a'] == 0) { 28 | continue; 29 | } 30 | string new_target; 31 | for (int i = 0; i < target_count.size(); ++i) { 32 | if (target_count[i] - sticker_count[i] > 0) { 33 | new_target += string(target_count[i] - sticker_count[i], 'a' + i); 34 | } 35 | } 36 | if (new_target.length() != target.length()) { 37 | int num = minStickersHelper(sticker_counts, new_target, dp); 38 | if (num != -1) { 39 | result = min(result, 1 + num); 40 | } 41 | } 42 | } 43 | (*dp)[target] = (result == numeric_limits::max()) ? -1 : result; 44 | return (*dp)[target]; 45 | } 46 | }; -------------------------------------------------------------------------------- /structures.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct student 5 | { 6 | char name[20]; 7 | int age; 8 | float gpa; 9 | }; 10 | 11 | int main(){ 12 | student s1; 13 | cin >> s1.name; 14 | cout << s1.name; 15 | } 16 | -------------------------------------------------------------------------------- /threesum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | vector> threeSum(vector& nums,int n) { 6 | vector>v; 7 | sort(nums.begin(),nums.end()); 8 | 9 | for(int i=0;i0 && nums[i]!=nums[i-1])) 12 | { 13 | int low=i+1,high=n-1; 14 | int sum=0-nums[i]; 15 | while(lowans; 20 | ans.push_back(nums[i]); 21 | ans.push_back(nums[low]); 22 | ans.push_back(nums[high]); 23 | v.push_back(ans); 24 | while(low>t; 41 | while(t--) 42 | { 43 | int n; 44 | cin>>n; 45 | vectora(n); 46 | for(int i=0;i>a[i]; 49 | } 50 | vector>final_ans=threeSum(a,n); 51 | int sz=final_ans.size(); 52 | int m=final_ans[0].size(); 53 | for(int i=0;i 3 | #include 4 | using namespace std; 5 | //Array for the board 6 | char board[3][3] = {{'1','2','3'},{'4','5','6'},{'7','8','9'}}; 7 | //Variable Declaration 8 | int choice; 9 | int row,column; 10 | char turn = 'X'; 11 | bool draw = false; 12 | 13 | //Function to show the current status of the gaming board 14 | 15 | void display_board(){ 16 | 17 | //Rander Game Board LAYOUT 18 | 19 | cout<<"PLAYER - 1 [X]t PLAYER - 2 [O]nn"; 20 | cout<<"tt | | n"; 21 | cout<<"tt "<> choice; 44 | 45 | //switch case to get which row and column will be update 46 | 47 | switch(choice){ 48 | case 1: row=0; column=0; break; 49 | case 2: row=0; column=1; break; 50 | case 3: row=0; column=2; break; 51 | case 4: row=1; column=0; break; 52 | case 5: row=1; column=1; break; 53 | case 6: row=1; column=2; break; 54 | case 7: row=2; column=0; break; 55 | case 8: row=2; column=1; break; 56 | case 9: row=2; column=2; break; 57 | default: 58 | cout<<"Invalid Move"; 59 | } 60 | 61 | if(turn == 'X' && board[row][column] != 'X' && board[row][column] != 'O'){ 62 | //updating the position for 'X' symbol if 63 | //it is not already occupied 64 | board[row][column] = 'X'; 65 | turn = 'O'; 66 | }else if(turn == 'O' && board[row][column] != 'X' && board[row][column] != 'O'){ 67 | //updating the position for 'O' symbol if 68 | //it is not already occupied 69 | board[row][column] = 'O'; 70 | turn = 'X'; 71 | }else { 72 | //if input position already filled 73 | cout<<"Box already filled!n Please choose another!!nn"; 74 | player_turn(); 75 | } 76 | /* Ends */ 77 | display_board(); 78 | } 79 | 80 | //Function to get the game status e.g. GAME WON, GAME DRAW GAME IN CONTINUE MODE 81 | 82 | bool gameover(){ 83 | //checking the win for Simple Rows and Simple Column 84 | for(int i=0; i<3; i++) 85 | if(board[i][0] == board[i][1] && board[i][0] == board[i][2] || board[0][i] == board[1][i] && board[0][i] == board[2][i]) 86 | return false; 87 | 88 | //checking the win for both diagonal 89 | 90 | if(board[0][0] == board[1][1] && board[0][0] == board[2][2] || board[0][2] == board[1][1] && board[0][2] == board[2][0]) 91 | return false; 92 | 93 | //Checking the game is in continue mode or not 94 | for(int i=0; i<3; i++) 95 | for(int j=0; j<3; j++) 96 | if(board[i][j] != 'X' && board[i][j] != 'O') 97 | return true; 98 | 99 | //Checking the if game already draw 100 | draw = true; 101 | return false; 102 | } 103 | 104 | //Program Main Method 105 | 106 | int main() 107 | { 108 | cout<<"tttT I C K -- T A C -- T O E -- G A M Ettt"; 109 | cout<<"nttttFOR 2 PLAYERSnttt"; 110 | while(gameover()){ 111 | display_board(); 112 | player_turn(); 113 | gameover(); 114 | } 115 | if(turn == 'X' && draw == false){ 116 | cout<<"nnCongratulations!Player with 'X' has won the game"; 117 | } 118 | else if(turn == 'O' && draw == false){ 119 | cout<<"nnCongratulations!Player with 'O' has won the game"; 120 | } 121 | else 122 | cout<<"nnGAME DRAW!!!nn"; 123 | } -------------------------------------------------------------------------------- /transposeOfMatrix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | int array[2][3], i, j, swap, array2[3][2]; 6 | cout << "Matrix Transpose:\nEnter Matrix Elements\n"; 7 | for(i = 0; i < 2; i++){ 8 | for(j = 0; j < 3; j++){ 9 | cout << "a" << i+1 << j+1 << ": "; 10 | cin >> array[i][j]; 11 | } 12 | } 13 | cout << "original matrix:\n"; 14 | for(i = 0; i < 2; i++){ 15 | for(j = 0; j < 3; j++){ 16 | cout < 2 | using namespace std; 3 | #define fast ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); 4 | typedef long long ll; 5 | const ll mod=1e9+7; 6 | //<------disjoint set-union------> 7 | vectorparent,size; 8 | void make_set(int v) { 9 | parent[v] = v; 10 | size[v] = 1; 11 | } 12 | 13 | void union_sets(int a, int b) { 14 | a = find_set(a); 15 | b = find_set(b); 16 | if (a != b) { 17 | if (size[a] < size[b]) 18 | swap(a, b); 19 | parent[b] = a; 20 | size[a] += size[b]; 21 | } 22 | } 23 | 24 | int find_set(int v) { 25 | if (v == parent[v]) 26 | return v; 27 | return find_set(parent[v]); 28 | } 29 | 30 | //<-----------fenwick tree---------> 31 | struct FenwickTree { 32 | vector bit; // binary indexed tree 33 | int n; 34 | 35 | FenwickTree(int n) { 36 | this->n = n; 37 | bit.assign(n, 0); 38 | } 39 | 40 | FenwickTree(vector a) : FenwickTree(a.size()) { 41 | for (size_t i = 0; i < a.size(); i++) 42 | add(i, a[i]); 43 | } 44 | 45 | int sum(int r) { 46 | int ret = 0; 47 | for (; r >= 0; r = (r & (r + 1)) - 1) 48 | ret += bit[r]; 49 | return ret; 50 | } 51 | 52 | int sum(int l, int r) { 53 | return sum(r) - sum(l - 1); 54 | } 55 | 56 | void add(int idx, int delta) { 57 | for (; idx < n; idx = idx | (idx + 1)) 58 | bit[idx] += delta; 59 | } 60 | }; 61 | 62 | //<-------------square root decomposition--------------> 63 | 64 | void sqrt_decmpO(){ 65 | //input data 66 | int n; 67 | vector a (n); 68 | 69 | // preprocessing 70 | int len = (int) sqrt (n + .0) + 1; // size of the block and the number of blocks 71 | vector b (len); 72 | for (int i=0; i 95 | int MAXN; 96 | int n; 97 | vectort(4*MAXN); 98 | void build(int a[], int v, int tl, int tr) { 99 | if (tl == tr) { 100 | t[v] = a[tl]; 101 | } else { 102 | int tm = (tl + tr) / 2; 103 | build(a, v*2, tl, tm); 104 | build(a, v*2+1, tm+1, tr); 105 | t[v] = t[v*2] + t[v*2+1]; 106 | } 107 | } 108 | int sum(int v, int tl, int tr, int l, int r) { 109 | if (l > r) 110 | return 0; 111 | if (l == tl && r == tr) { 112 | return t[v]; 113 | } 114 | int tm = (tl + tr) / 2; 115 | return sum(v*2, tl, tm, l, min(r, tm)) 116 | + sum(v*2+1, tm+1, tr, max(l, tm+1), r); 117 | } 118 | void update(int v, int tl, int tr, int pos, int new_val) { 119 | if (tl == tr) { 120 | t[v] = new_val; 121 | } else { 122 | int tm = (tl + tr) / 2; 123 | if (pos <= tm) 124 | update(v*2, tl, tm, pos, new_val); 125 | else 126 | update(v*2+1, tm+1, tr, pos, new_val); 127 | t[v] = t[v*2] + t[v*2+1]; 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /two sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& nums, int target) { 4 | int a=0; 5 | int b=0; 6 | for(int i=0;i 4 | using namespace std; 5 | 6 | void uni(int a[],int b[],int m,int n) // int uni(int a[],int b[],int m,int n) --to return size 7 | { 8 | unordered_set s; 9 | for(int i=0;i>m; 27 | int a[m]; 28 | for(int i=0;i>a[i]; 31 | } 32 | int n; 33 | cin>>n; 34 | int b[n]; 35 | for(int i=0;i>b[i]; 38 | } 39 | uni(a,b,m,n); 40 | return 0; 41 | 42 | } -------------------------------------------------------------------------------- /valid binary tree.cpp: -------------------------------------------------------------------------------- 1 | var isValidBST = function (root) { 2 | 3 | 4 | function helper(node, min, max) { 5 | if (!node) return true; 6 | 7 | if (node.val <= min || node.val >= max) return false; 8 | 9 | let left = helper(node.left, min, node.val); 10 | let right = helper(node.right, node.val, max) 11 | 12 | return left && right 13 | 14 | } 15 | 16 | return helper(root, -Infinity, Infinity) 17 | }; -------------------------------------------------------------------------------- /vowel-consonent: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | char c; 6 | bool isLowercaseVowel, isUppercaseVowel; 7 | 8 | cout << "Enter an alphabet: "; 9 | cin >> c; 10 | 11 | // evaluates to 1 (true) if c is a lowercase vowel 12 | isLowercaseVowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); 13 | 14 | // evaluates to 1 (true) if c is an uppercase vowel 15 | isUppercaseVowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'); 16 | 17 | // show error message if c is not an alphabet 18 | if (!isalpha(c)) 19 | printf("Error! Non-alphabetic character."); 20 | else if (isLowercaseVowel || isUppercaseVowel) 21 | cout << c << " is a vowel."; 22 | else 23 | cout << c << " is a consonant."; 24 | 25 | return 0; 26 | } 27 | --------------------------------------------------------------------------------