├── .DS_Store ├── BasicBitmaskingOperations.cpp ├── BinarySearchTree.c ├── BitManipulation.md ├── CONTRIBUTING.md ├── Data Structures in JAVA ├── .DS_Store └── GeeksForGeeks │ ├── .DS_Store │ └── Sorts.java ├── Data Structures ├── BFS.cpp ├── BinaryTree.java ├── LinkedList │ ├── Loop in LL.cpp │ └── linked.cpp ├── SegmentTrees.c ├── VectorErase.cpp ├── VectorSort.cpp ├── heap.java ├── kruskals.cpp ├── queue.cpp └── stack.cpp ├── Dijkstra'sShortestPathAlgorithm.cpp ├── Games ├── Maze.cpp ├── Snake.cpp ├── flappy bird │ ├── flappy bird.cbp │ ├── flappy bird.layout │ ├── main.cpp │ └── obj │ │ └── Debug │ │ └── main.o └── tic tac toe │ ├── bin │ └── Debug │ │ └── tic tac toe.exe │ ├── main.cpp │ ├── obj │ └── Debug │ │ └── main.o │ ├── tic tac toe.cbp │ └── tic tac toe.layout ├── General ├── Day Of Week.c ├── Diophantine_Equation.cpp ├── Fast_Exponentiation.cpp ├── Modular Exponentation.cpp ├── Prime Factors.py ├── Prime.cpp ├── Segmented Sieve.cpp ├── fibonacci.java ├── linearRecurssion.cpp ├── palindrome.java ├── sieve of eratosthenes.cpp └── sorted_rotatedarray.cpp ├── Greedy └── Greedy.java ├── Insertion_Deletion_in_array ├── Insertion_sorting.cpp ├── Linked_list.cpp ├── PULL_REQUEST_TEMPLATE.md ├── README 2019 Hactoberfest 2019.md ├── README.md ├── Search ├── Binary_Search.cpp ├── Linear_Search.cpp └── Ternary_Search.cpp ├── Solutions to Known Problems ├── CODECHEF_DIVSUBS ├── SPOJ_FAVDICE.cpp ├── SPOJ_FIBOSUM.cpp ├── between two sets.cpp ├── cats and mouse.cpp ├── electronics shop.cpp └── sock merchant.cpp ├── Sorting ├── Bubble_Sort.cpp ├── HeapSort.c ├── Recursive_insertionsort.cpp ├── bubble-sort.py ├── bubblesort_recursion.cpp ├── ins_sort.cpp ├── merge_2arrays.cpp ├── merge_sort.cpp ├── quick_sort.java ├── selection_sort.cpp └── selectionsort.java ├── Strings └── Anagram.java ├── coinchange.cpp ├── dist_from_source.cpp ├── fast_expo.cpp ├── snackdown2019-OnlineQualifier ├── Chef and Operations.md ├── Chef and Semi-Primes.md ├── FidingTeammates.md ├── Qualifying to Pre-Elimination.md └── Spread the Word.md └── tbbfs.cpp /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IOSD/Algo/910c3123034352318b74dfac1d168ed8373d4989/.DS_Store -------------------------------------------------------------------------------- /BasicBitmaskingOperations.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Function for extracting ith bit of a number 5 | int extractBit(int n, int i){ 6 | int mask = 1<>n>>i; 29 | 30 | cout<<"The "< 3 | #include 4 | 5 | struct node 6 | { 7 | int key; 8 | struct node *left, *right; 9 | }; 10 | 11 | // A utility function to create a new BST node 12 | struct node *newNode(int item) 13 | { 14 | struct node *temp = (struct node *)malloc(sizeof(struct node)); 15 | temp->key = item; 16 | temp->left = temp->right = NULL; 17 | return temp; 18 | } 19 | 20 | // A utility function to print elements in inorderoid inorder(struct node *root) 21 | { 22 | if (root != NULL) 23 | { 24 | inorder(root->left); 25 | printf("%d \n", root->key); 26 | inorder(root->right); 27 | } 28 | } 29 | 30 | /* A utility function to insert a new node with given key in BST */ 31 | struct node* insert(struct node* node, int x) 32 | { 33 | if (node == NULL) return newNode(x); 34 | 35 | /] 36 | if (x < node->key) 37 | node->left = insert(node->left, x); 38 | else if (x > node->key) 39 | node->right = insert(node->right, x); 40 | 41 | return node; 42 | } 43 | 44 | // Main Function 45 | int main() 46 | { 47 | struct node *root = NULL; 48 | root = insert(root, 50); 49 | insert(root, 30); 50 | insert(root, 20); 51 | insert(root, 40); 52 | insert(root, 70); 53 | insert(root, 60); 54 | insert(root, 80); 55 | //print tree 56 | inorder(root); 57 | 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /BitManipulation.md: -------------------------------------------------------------------------------- 1 | ## Bit Manipulation: 2 | N = 616310 = (6×103) + (1×102) + (6×101) + (3×100)
3 | In base 2 (binary) instead of 10's power we represent in 2's power. To convert keep dividing number by two and append remainder to a string. In the end reverse the string. 4 | 5 | AND = A.B
6 | OR = A + B
7 | NOT = 1 - A = !A
8 | XOR = A!B + !AB
9 | 10 | Moore's Law:
11 | !(A + B) = A!.B!
12 | !(A.B) = A! + B! 13 | 14 | XNOR = !XOR = (A + B!).(A! + B)
15 | NOR = !OR = A!.B!
16 | NAND = !AND = A! + B!
17 | 18 | > If XOR of two numbers/string/any data is 0 then both are same. 19 | 20 | If between two number there's a bit difference of exactly one by XOR then it is called Gray Code. It is used in signal detection to check if there's any wrong signal. 21 |
22 | 23 | | Type | Size (bit) | Range | 24 | | ------------- |:-------------|:-----------------------------------| 25 | | Bit | 1 | 0 or 1 | 26 | | Nibble | 4 | 0 to 24-1 | 27 | | Byte | 8 | 0 to 28-1 | 28 | | Word | 16 | 0 to 216-1 | 29 | | Double | 32 | 0 to 232-1 | 30 | | Qword | 64 | 0 to 264-1 | 31 | 32 |
33 | 34 | Gb (Gigabits), GB (Gigabytes), Gib (103 bits), GiB (103 bytes) 35 | 36 | Hexadecimals: **0xAABBCCDD**
37 | Different colors represent a byte (AA 1 byte). Nibble has 4 bits i.e. 24 so a hexadecimal value which is from 0-15 (10 - A, B, C, D, E, F) 38 | 39 | Least Significant Bit (LSB) & Most Significant Bit (MSB): 99 in binary (MSB part)01100011(LSB part) so in MSB 01100011 in LSB 11000110
40 | Endiness (Storing data in memory) : Little Endian (LSB), Big Endian (MSB) 41 | >We use LSB 42 | 43 | Finding ith bit:
44 | ```c++ 45 | X(1<<4) >> 4 46 | output: 47 | 010x00 48 | 00010x 49 | 000x00 50 | x 51 | ``` 52 | 53 | 1's Complement: Toggling every bit ~
54 | 2's Complement:
55 | -X = !X + 1
56 | X = !(-X-1) 57 | 58 |
59 | 60 | | Decimal | Binary | Hexadecimal | Decimal | Binary | Hexadecimal | 61 | | ------------- |:-------------|:-------------| :------------ |:-------------|:-------------| 62 | | 0 | 0000 | 0x0 | 0 | 0000 | 0x9 | 63 | | 1 | 0001 | 0x1 | -1 | 1111 | 0xA | 64 | | 2 | 0010 | 0x2 | -2 | 1110 | 0xB | 65 | | 3 | 0011 | 0x3 | -3 | 1101 | 0xC | 66 | | 4 | 0100 | 0x4 | -4 | 1011 | 0xD | 67 | | 5 | 0101 | 0x5 | -5 | 1011 | 0xE | 68 | | 6 | 0110 | 0x6 | -6 | 1010 | 0xF | 69 | | 7 | 0111 | 0x7 | -7 | 1001 | 0x7 | 70 | | 8 | 1000 | 0x8 | -8 | 1000 | 0x8 | 71 | 72 | 1 in 8th first value means it's a negative number which is not true so range is -8 to 7 only 73 |
74 | 75 | ```c++ 76 | 0000111110110011 77 | // << 3 yields: 78 | 0111110110011000 79 | // >> 3 yields: 80 | 0000000111110110 81 | 82 | // Multiplication 83 | i * 8; // normal 84 | i << 3; // bitwise [8 = 2^3, so use 3] 85 | 86 | // Division 87 | i / 16; // normal 88 | i >> 4; // bitwise [16 = 2^4, so use 4] 89 | 90 | // Modulus 91 | i % 4; // normal 92 | i & 3; // bitwise [4 = 1 << 2, apply ((1 << 2) - 1), so use 3] 93 | i % 2^i = n & (2^i - 1) 94 | 95 | Bitwise shifts << >> shouldn't be used on negative numbers. 96 | ``` 97 | ```c 98 | /* 99 | Booth's Multiplication Algo: (01011 x 01011) 100 | 01011 x 1 = 01011 101 | 010110 x 1 = 010110 102 | 0101100 x 0 = 0000000 103 | 01011000 x 1 = 01011000 104 | 1111001 105 | */ 106 | 107 | int mul(int a, int b) 108 | { 109 | int ans = 0; 110 | for (int i = 0 ; i < 32; i++) 111 | { 112 | if (b & 1) ans += a; 113 | b = b>>1; 114 | a = a<<1; 115 | } 116 | return ans; 117 | } 118 | ``` 119 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 |

Contributing Guidelines

2 | 3 |

Thanks for taking the time to contribute to this project. Before making PRs, please note the following:

4 | 5 |

A few norms you should follow

6 |
    7 |
  • Proper intendation is must!
  • 8 |
  • Include ample comments so that code is understandable and easy to follow.
  • 9 |
  • Mention the complexity of a function in a comment.
  • 10 |
      11 |
    • Time complexity :
    • 12 |
    • Space complexity :
    • 13 |
    14 |
  • Place your code in right directory.
  • 15 |
  • Give your files names that are relevant and meaningful.
  • 16 |
17 | 18 |

You may add your solved questions on spoj, codechef, hackerearth, hackerrank, leetcode and codeforces.

19 |
    20 |
  • First line of your code must begin with a comment mentioning the link of the question
  • 21 |
  • Place the solutions in seperate folder "ques" in relevant directory
  • 22 |
23 | 24 |

Best Practices for opening a Pull Request

25 |
    26 |
  • Give the PR a meaningful name.
  • 27 |
  • For e.g. 'Fixes #(issue-number): PR name, fixing the particular bug' (without commas)
  • 28 |
  • There should be always 1 commit for 1 PR.
  • 29 |
  • If there are more than 1 commit in a PR, squash them.
  • 30 |
  • Pull Request details should be descriptive.
  • 31 |
  • Commit message should meaningful.
  • 32 |
33 | -------------------------------------------------------------------------------- /Data Structures in JAVA/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IOSD/Algo/910c3123034352318b74dfac1d168ed8373d4989/Data Structures in JAVA/.DS_Store -------------------------------------------------------------------------------- /Data Structures in JAVA/GeeksForGeeks/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IOSD/Algo/910c3123034352318b74dfac1d168ed8373d4989/Data Structures in JAVA/GeeksForGeeks/.DS_Store -------------------------------------------------------------------------------- /Data Structures in JAVA/GeeksForGeeks/Sorts.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Sorts { 4 | 5 | public static Scanner sc = new Scanner(System.in); 6 | 7 | public static void main(String[] args) { 8 | 9 | // alterNateSort(); 10 | // sortAbsoluteDiff(); 11 | sort2DArrayByCol(new int[][]{{3,4,5,6},{1,2,3,4},{6,7,8,9},{9,0,1,2}},4); 12 | } 13 | 14 | public static void alterNateSort() { 15 | int t = sc.nextInt(); 16 | int[] arr = new int[t]; 17 | 18 | for (int i=0;i list = new ArrayList(); 36 | 37 | for (int i=0;i() { 48 | @Override 49 | public int compare(int[] ar1,int[] ar2) { 50 | if (ar1[col-1] > ar2[col-1]) { 51 | return 1; 52 | } else { 53 | return -1; 54 | } 55 | } 56 | }); 57 | 58 | for (int i=0;i 2 | #include 3 | 4 | /* 5 | time complexity : O(V+E) 6 | space complexity : O(V) 7 | 8 | V = Vertecies 9 | E = Edges 10 | */ 11 | 12 | using namespace std; 13 | // create Graph class 14 | class Graph 15 | { 16 | int v; 17 | list *adj; 18 | 19 | public: 20 | // constructor 21 | Graph(int v); 22 | // add edge function 23 | void addEdge(int v, int w); 24 | // bfs function 25 | void bfs(int s); 26 | }; 27 | Graph::Graph(int v) 28 | { 29 | this->v = v; 30 | adj = new list[v]; 31 | } 32 | 33 | void Graph::addEdge(int v, int w) 34 | { 35 | adj[v].push_back(w); 36 | } 37 | 38 | void Graph::bfs(int s) 39 | { 40 | bool *visited = new bool[v]; 41 | for (int i = 0; i < v; i++) 42 | { 43 | visited[i] = false; 44 | } 45 | 46 | list queue; 47 | visited[s] = true; 48 | queue.push_back(s); 49 | // create a list iterator 50 | list::iterator i; 51 | while (!queue.empty()) 52 | { 53 | s = queue.front(); 54 | cout << s << " "; 55 | queue.pop_front(); 56 | for (i = adj[s].begin(); i != adj[s].end(); i++) 57 | { 58 | if (!visited[*i]) 59 | { 60 | visited[*i] = true; 61 | queue.push_back(*i); 62 | } 63 | } 64 | } 65 | } 66 | 67 | int main() 68 | { 69 | // Create a graph 70 | Graph g(4); 71 | g.addEdge(0, 1); 72 | g.addEdge(0, 2); 73 | g.addEdge(1, 2); 74 | g.addEdge(2, 0); 75 | g.addEdge(2, 3); 76 | g.addEdge(3, 3); 77 | // perform bfs 78 | g.bfs(0); 79 | 80 | return 0; 81 | } -------------------------------------------------------------------------------- /Data Structures/BinaryTree.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | 4 | public class BinaryTree { 5 | 6 | public int max_level = 0; 7 | 8 | public class Node implements Comparable { 9 | int data; 10 | Node left; 11 | Node right; 12 | Node rightNext; 13 | Node(int data,Node left,Node right,Node rightNext) { 14 | this.data = data; 15 | this.left = left; 16 | this.right = right; 17 | this.rightNext = rightNext; 18 | } 19 | 20 | public String toString() { 21 | String retVal = ""; 22 | 23 | if (this.left != null) { 24 | retVal += this.left.data + " => "; 25 | } 26 | 27 | retVal += this.data; 28 | 29 | if (this.right != null) { 30 | retVal += " <= " + this.right.data; 31 | } 32 | 33 | retVal += "\n"; 34 | 35 | if (this.left != null) { 36 | retVal += this.left.toString(); 37 | } 38 | if (this.right != null) { 39 | retVal += this.right.toString(); 40 | } 41 | 42 | return retVal; 43 | } 44 | 45 | public int compareTo(Node other) { 46 | return this.data - other.data; 47 | } 48 | } 49 | 50 | public class QItem { 51 | Node node; 52 | int hd; 53 | 54 | QItem(Node node,int hd) { 55 | this.hd = hd; 56 | this.node = node; 57 | } 58 | } 59 | 60 | Node root; 61 | int size; 62 | int min; 63 | int max; 64 | ArrayList path = new ArrayList(); 65 | 66 | public BinaryTree(boolean takeInput) { 67 | if (takeInput) { 68 | Scanner scn = new Scanner(System.in); 69 | this.root = this.takeInput(scn, null, false); 70 | } 71 | } 72 | 73 | private Node takeInput(Scanner scn, Node parentNode, boolean isParentsLeftChild) { 74 | if (parentNode == null) { 75 | System.out.println("Please enter the data for root: "); 76 | } else { 77 | if (isParentsLeftChild) { 78 | System.out.println("Please enter the data for left child of " + parentNode.data); 79 | } else { 80 | System.out.println("Please enter the data for right child of " + parentNode.data); 81 | } 82 | } 83 | 84 | int cData = scn.nextInt(); 85 | Node child = new Node(cData, null, null, null); 86 | this.size++; 87 | 88 | System.out.println("Do you have a left child for " + child.data); 89 | boolean isChildsLeft = scn.nextBoolean(); 90 | 91 | if (isChildsLeft) { 92 | child.left = this.takeInput(scn, child, true); 93 | } 94 | 95 | System.out.println("Do you have a right child for " + child.data); 96 | boolean isChildsRight = scn.nextBoolean(); 97 | 98 | if (isChildsRight) { 99 | child.right = this.takeInput(scn, child, false); 100 | } 101 | 102 | return child; 103 | } 104 | 105 | public void display() { 106 | System.out.println(this); 107 | } 108 | 109 | public String toString() { 110 | return this.root.toString(); 111 | } 112 | 113 | public int size() { 114 | return size(this.root); 115 | } 116 | 117 | private int size(Node root1) { 118 | int retVal=0; 119 | if(root1 == null) { 120 | return retVal; 121 | } 122 | 123 | retVal += size(root1.left); 124 | retVal += size(root1.right); 125 | 126 | return retVal; 127 | } 128 | 129 | public void preOrderTraversal() { 130 | preOrderTraversal(this.root); 131 | System.out.println(); 132 | } 133 | 134 | private void preOrderTraversal(Node root1) { 135 | if(root1 == null) { 136 | return; 137 | } 138 | 139 | System.out.print(root1.data + " "); 140 | 141 | System.out.println("Item yet to travel to the left"); 142 | preOrderTraversal(root1.left); 143 | System.out.println("Item moving towards right"); 144 | preOrderTraversal(root1.right); 145 | System.out.println("Item turning back from right"); 146 | } 147 | 148 | 149 | 150 | public void leftView() { 151 | int h = height(this.root); 152 | leftView(this.root,1); 153 | System.out.println(); 154 | } 155 | 156 | private void leftView(Node root1,int a) { 157 | if(root1 == null) { 158 | return; 159 | } 160 | 161 | if(max_level < a) { 162 | System.out.println(root1.data + " "); 163 | max_level = a; 164 | } 165 | 166 | leftView(root1.left,a+1); 167 | leftView(root1.right,a+1); 168 | } 169 | 170 | public void height() { 171 | System.out.println(height(this.root)); 172 | } 173 | 174 | private int height(Node root1) { 175 | if(root1 == null) { 176 | return -1; 177 | } 178 | int h1 = height(root1.left) + 1; 179 | int h2 = height(root1.right) + 1; 180 | if(h1 > h2) { 181 | return h1; 182 | } else { 183 | return h2; 184 | } 185 | } 186 | 187 | public void isBST() { 188 | boolean b = isBST(this.root,Integer.MIN_VALUE,Integer.MAX_VALUE); 189 | System.out.println(b); 190 | } 191 | 192 | private boolean isBST(Node root1,int min,int max) { 193 | if (root1 == null) { 194 | return true; 195 | } 196 | 197 | if (root1.data < min||root1.data > max) { 198 | return false; 199 | } 200 | 201 | boolean left = isBST(root1.left,min,root1.data); 202 | boolean right = isBST(root1.right,root1.data,max); 203 | return left&&right; 204 | } 205 | 206 | private void printVerticalLine(Node root1,int lineno,int hd) { 207 | if(root1 == null) { 208 | return; 209 | } 210 | 211 | if(hd == lineno) { 212 | System.out.print(root1.data + " "); 213 | } 214 | printVerticalLine(root1.left,lineno,hd-1); 215 | printVerticalLine(root1.right,lineno,hd+1); 216 | } 217 | 218 | private void findMinMax(Node root1,int hd) { 219 | if(root1 == null) { 220 | return; 221 | } 222 | 223 | if(hd < min) { 224 | min = hd; 225 | } 226 | if(hd > max) { 227 | max = hd; 228 | } 229 | 230 | findMinMax(root1.left,hd-1); 231 | findMinMax(root1.right,hd+1); 232 | } 233 | 234 | public void verticalTraversal() { 235 | 236 | findMinMax(this.root,0); 237 | System.out.println("Min : " + min + " Max : " + max); 238 | 239 | for(int i=this.min;i max) { 280 | max = hd; 281 | System.out.print(root1.data + " "); 282 | } 283 | 284 | TopView(root1.left,min,max,hd-1); 285 | TopView(root1.right,min,max,hd+1); 286 | } 287 | 288 | public void verticalOrder() { 289 | LinkedList list = new LinkedList(); 290 | QItem item = new QItem(this.root,0); 291 | list.addLast(item); 292 | TreeMap> map = new TreeMap>(); 293 | 294 | while (!list.isEmpty()) { 295 | QItem q = list.removeFirst(); 296 | if (!map.containsKey(q.hd)) { 297 | ArrayList arr = new ArrayList<>(); 298 | arr.add(q.node.data); 299 | map.put(q.hd,arr); 300 | } else { 301 | map.get(q.hd).add(q.node.data); 302 | } 303 | if (q.node.left!=null) { 304 | list.addLast(new QItem(q.node.left,q.hd-1)); 305 | } 306 | if (q.node.right!=null) { 307 | list.addLast(new QItem(q.node.right,q.hd+1)); 308 | } 309 | } 310 | 311 | for (Map.Entry> entry: map.entrySet()) { 312 | for (int a : entry.getValue()) { 313 | System.out.print(a + " "); 314 | } 315 | System.out.println(); 316 | } 317 | } 318 | 319 | public void TopView2() { 320 | LinkedList list = new LinkedList(); 321 | QItem qtem = new QItem(this.root,0); 322 | list.addLast(qtem); 323 | HashMap map = new HashMap(); 324 | 325 | while(!list.isEmpty()) { 326 | QItem item = list.removeFirst(); 327 | int hd = item.hd; 328 | Node node = item.node; 329 | 330 | // System.out.println("Horizontal Distance : " + node.data); 331 | 332 | if(!map.containsKey(hd)) { 333 | map.put(hd,hd); 334 | System.out.print(node.data + " "); 335 | } 336 | 337 | if(node.left!=null) { 338 | list.addLast(new QItem(node.left,hd-1)); 339 | } 340 | if(node.right!=null) { 341 | list.addLast(new QItem(node.right,hd+1)); 342 | } 343 | } 344 | } 345 | 346 | public void BottomView() { 347 | LinkedList list = new LinkedList(); 348 | HashMap map = new HashMap(); 349 | 350 | list.addLast(new QItem(this.root,0)); 351 | while(!list.isEmpty()) { 352 | QItem item = list.removeFirst(); 353 | Node node = item.node; 354 | int hd = item.hd; 355 | 356 | map.put(hd,node.data); 357 | 358 | if(node.left!=null) { 359 | list.addLast(new QItem(node.left,hd-1)); 360 | } 361 | if(node.right!=null) { 362 | list.addLast(new QItem(node.right,hd+1)); 363 | } 364 | } 365 | 366 | for(Map.Entry set : map.entrySet()) { 367 | System.out.print(set.getValue() + " "); 368 | } 369 | System.out.println(); 370 | } 371 | 372 | public void LevelOrder() { 373 | LinkedList list1 = new LinkedList(); 374 | LinkedList list2 = new LinkedList(); 375 | 376 | list1.addLast(this.root); 377 | while(!list1.isEmpty()) { 378 | Node node = list1.removeFirst(); 379 | 380 | if(node.left!=null) { 381 | list2.addLast(node.left); 382 | } 383 | if(node.right!=null) { 384 | list2.addLast(node.right); 385 | } 386 | 387 | System.out.print(node.data + " "); 388 | if(list1.isEmpty()) { 389 | list1 = list2; 390 | System.out.println(); 391 | list2 = new LinkedList(); 392 | } 393 | } 394 | } 395 | 396 | public void LevelSpiral() { 397 | LinkedList list1 = new LinkedList(); 398 | LinkedList list2 = new LinkedList(); 399 | 400 | list1.addLast(this.root); 401 | int i=0; 402 | Node node; 403 | while(!list1.isEmpty()) { 404 | if(i%2 == 0) { 405 | node = list1.removeFirst(); 406 | } else { 407 | node = list1.removeLast(); 408 | } 409 | 410 | if(i%2 == 0) { 411 | if(node.left!=null) { 412 | list2.addLast(node.left); 413 | } 414 | if(node.right!=null) { 415 | list2.addLast(node.right); 416 | } 417 | } else { 418 | if(node.right!=null) { 419 | list2.addFirst(node.right); 420 | } 421 | if(node.left!=null) { 422 | list2.addFirst(node.left); 423 | } 424 | } 425 | 426 | System.out.print(node.data + " "); 427 | 428 | if(list1.isEmpty()) { 429 | System.out.println(); 430 | list1 = list2; 431 | list2 = new LinkedList(); 432 | i++; 433 | } 434 | } 435 | } 436 | 437 | public void connectSameLevel() { 438 | LinkedList list1 = new LinkedList(); 439 | 440 | list1.addLast(this.root); 441 | list1.addLast(null); 442 | while(!list1.isEmpty()) { 443 | Node node = list1.removeFirst(); 444 | 445 | if(node!=null) { 446 | node.rightNext = list1.getFirst(); 447 | 448 | if(node.left!=null) { 449 | list1.addLast(node.left); 450 | } 451 | if(node.right!=null) { 452 | list1.addLast(node.right); 453 | } 454 | } else if (!list1.isEmpty()) { 455 | list1.addLast(null); 456 | } 457 | 458 | } 459 | } 460 | 461 | public void treetoDLL() { 462 | /* 463 | inorder traversal type : 464 | 465 | inorder(root.left); 466 | linkedlist.add(root); 467 | inorder(root.right); 468 | 469 | define the add function of the DLL in 470 | such a way that it automatically creates the DLL 471 | */ 472 | } 473 | 474 | public boolean findNode(int a) { 475 | return findNode(this.root,a,false); 476 | } 477 | 478 | private boolean findNode(Node root,int a,boolean b) { 479 | if(root == null) { 480 | return b; 481 | } 482 | 483 | if(root.data == a) { 484 | b = true; 485 | return b; 486 | } 487 | 488 | b = findNode(root.left,a,b); 489 | b = findNode(root.right,a,b); 490 | return b; 491 | } 492 | 493 | public void storePath(int data) { 494 | storePath(this.root,data); 495 | for(int a : path) { 496 | System.out.print(a + " "); 497 | } 498 | } 499 | 500 | private void storePath(Node root1, int data) { 501 | if(root1 == null) { 502 | return; 503 | } 504 | 505 | path.add(root1.data); 506 | if(root1.data == data) { 507 | return; 508 | } 509 | if(root1.left!=null && findNode(root1.left,data,false)) { 510 | storePath(root1.left,data); 511 | } else if(root1.right!=null) { 512 | storePath(root1.right,data); 513 | } 514 | } 515 | 516 | public void printAllPaths() { 517 | 518 | path = new ArrayList(); 519 | printAllPaths(this.root); 520 | } 521 | 522 | private void printAllPaths(Node root1) { 523 | if(root1 == null) { 524 | return; 525 | } 526 | path.add(root1.data); 527 | if(root1.left == null && root1.right == null) { 528 | for(int a : path) { 529 | System.out.print(a + " "); 530 | } 531 | System.out.println(); 532 | } 533 | printAllPaths(root1.left); 534 | printAllPaths(root1.right); 535 | path.remove(path.size()-1); 536 | } 537 | 538 | public void AllPaths (int B) { 539 | ArrayList> list = returnPaths(this.root,B, 540 | new ArrayList>(), new ArrayList()); 541 | 542 | for (ArrayList list1 : list) { 543 | for (int i:list1) { 544 | System.out.print(i + " "); 545 | } 546 | System.out.println(); 547 | } 548 | } 549 | 550 | private ArrayList> returnPaths(Node root1,int B, 551 | ArrayList> result, ArrayList path) { 552 | if(root1 == null) { 553 | return result; 554 | } 555 | path.add(root1.data); 556 | if(root1.left == null && root1.right == null) { 557 | int sum = 0; 558 | for(int a : path) { 559 | sum += a; 560 | } 561 | if (sum == B) 562 | result.add(path); 563 | } 564 | result = returnPaths(root1.left,B,result,path); 565 | result = returnPaths(root1.right,B,result,path); 566 | path.remove(path.size()-1); 567 | return result; 568 | } 569 | 570 | public void duplicateNode() { 571 | duplicateNode(this.root); 572 | } 573 | 574 | private void duplicateNode(Node root1) { 575 | if(root1 == null) { 576 | return; 577 | } 578 | Node node; 579 | if(root1.left!=null) { 580 | node = root1.left; 581 | root1.left = new Node(root1.data,node,null,null); 582 | } else { 583 | root1.left = new Node(root1.data,null,null,null); 584 | } 585 | duplicateNode(root1.left.left); 586 | duplicateNode(root1.right); 587 | } 588 | 589 | public void checkSum(int n) { 590 | ArrayList list = new ArrayList<>(); 591 | list = checkSum(this.root,list); 592 | Collections.sort(list); 593 | System.out.println(list); 594 | int i = 0; 595 | int j = list.size(); 596 | while(i n) { 598 | j--; 599 | } else if(list.get(i) + list.get(j-1) < n){ 600 | i++; 601 | } else if(list.get(i) + list.get(j-1) == n){ 602 | System.out.println("true"); 603 | break; 604 | } 605 | } 606 | } 607 | 608 | private ArrayList checkSum(Node root1,ArrayList list) { 609 | if(root1 == null) { 610 | return list; 611 | } 612 | list.add(root1.data); 613 | list = checkSum(root1.left,list); 614 | list = checkSum(root1.right,list); 615 | return list; 616 | } 617 | 618 | public void largestBST() { 619 | Node node = largestBST(this.root); 620 | System.out.println(node.data); 621 | } 622 | 623 | private Node largestBST(Node root1) { 624 | if(root1.right == null && root1.left == null) { 625 | return root1; 626 | } 627 | 628 | if(root1.left!=null) { 629 | if(root1.data < root1.left.data) { 630 | root1 = root1.left; 631 | root1 = largestBST(root1); 632 | } 633 | } 634 | if(root1.right!=null) { 635 | if(root1.data > root1.right.data) { 636 | root1 = root1.right; 637 | root1 = largestBST(root1); 638 | } 639 | } 640 | 641 | return root1; 642 | } 643 | 644 | public void sumAtMaxDepth() { 645 | Node root1 = this.root; 646 | 647 | LinkedList list1 = new LinkedList<>(); 648 | LinkedList list2 = new LinkedList<>(); 649 | list1.addLast(root1); 650 | ArrayList sumList = new ArrayList(); 651 | sumList.add(root1.data); 652 | int sum = 0; 653 | while (!list1.isEmpty()) { 654 | Node p = list1.removeFirst(); 655 | 656 | if (p.left != null) { 657 | list2.add(p.left); 658 | sum += p.left.data; 659 | } 660 | 661 | if (p.right != null) { 662 | list2.add(p.right); 663 | sum += p.right.data; 664 | } 665 | 666 | if (list1.isEmpty()) { 667 | list1 = list2; 668 | list2 = new LinkedList(); 669 | sumList.add(sum); 670 | sum = 0; 671 | } 672 | } 673 | System.out.println(sumList.get(sumList.size()-2)); 674 | } 675 | 676 | /* 677 | NOT WORKING 678 | */ 679 | // public void sumLeafAtMinDepth() { 680 | // Node root1 = this.root; 681 | // LinkedList list = new LinkedList(); 682 | // list.addLast(root1); 683 | // boolean f = false; 684 | // int sum = 0; 685 | // while (!f) { 686 | // int size = list.size(); 687 | // while (size > 0) { 688 | // Node p = list.removeFirst(); 689 | 690 | // if (p.left == null && p.right == null) { 691 | // sum += p.data; 692 | // f = true; 693 | // } 694 | // else { 695 | // if (p.left != null) { 696 | // list.add(root1.left); 697 | // } 698 | // if (p.right != null) { 699 | // list.add(root1.right); 700 | // } 701 | // } 702 | // size -= 1; 703 | // } 704 | // } 705 | // System.out.println(sum); 706 | // } 707 | 708 | int countSubtreesWithSumX(int x) { 709 | return countSubTreeHelper(this.root,x,0); 710 | } 711 | 712 | int countSubTreeHelper(Node root,int x,int count) { 713 | if (root == null) { 714 | return count; 715 | } 716 | 717 | int sum = getSum(root,x); 718 | if (sum == x) { 719 | count += 1; 720 | } 721 | 722 | count = countSubTreeHelper(root.left,x,count); 723 | count = countSubTreeHelper(root.right,x,count); 724 | return count; 725 | } 726 | 727 | int getSum(Node node,int sum) { 728 | if (node == null) { 729 | return 0; 730 | } 731 | 732 | int left = getSum(node.left,sum); 733 | int right = getSum(node.right,sum); 734 | 735 | return node.data + left + right; 736 | } 737 | 738 | class TreeProp { 739 | boolean isBST; 740 | int max; 741 | int min; 742 | int size; 743 | } 744 | 745 | public void makeLeafLinkedList() { 746 | Node prevNode = null; 747 | prevNode = makeLeafLinkedList(this.root,null); 748 | while (prevNode!=null) { 749 | System.out.println(prevNode); 750 | prevNode = prevNode.right; 751 | } 752 | } 753 | 754 | private Node makeLeafLinkedList(Node node,Node prevNode) { 755 | if (node == null) { 756 | return prevNode; 757 | } 758 | 759 | prevNode = makeLeafLinkedList(node.left,prevNode); 760 | if (node.left == null && node.right == null) { 761 | if (prevNode == null) { 762 | prevNode = node; 763 | } else { 764 | prevNode.right = node; 765 | prevNode = node; 766 | } 767 | } 768 | prevNode = makeLeafLinkedList(node.right,prevNode); 769 | return prevNode; 770 | } 771 | } -------------------------------------------------------------------------------- /Data Structures/LinkedList/Loop in LL.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node { 5 | int data; 6 | struct Node* next; 7 | int flag; 8 | }; 9 | 10 | void push(struct Node** head_ref, int new_data) 11 | { 12 | struct Node* new_node = new Node; 13 | new_node->data = new_data; 14 | 15 | new_node->flag = 0; 16 | new_node->next = (*head_ref); 17 | 18 | (*head_ref) = new_node; 19 | } 20 | 21 | bool detectLoop(struct Node* h) 22 | { 23 | while (h != NULL) { 24 | if (h->flag == 1) 25 | return true; 26 | 27 | h->flag = 1; 28 | 29 | h = h->next; 30 | } 31 | 32 | return false; 33 | } 34 | 35 | int main() 36 | { 37 | struct Node* head = NULL; 38 | 39 | push(&head, 20); 40 | push(&head, 4); 41 | push(&head, 15); 42 | push(&head, 10); 43 | 44 | head->next->next->next->next = head; 45 | 46 | if (detectLoop(head)) 47 | cout << "Loop found"; 48 | else 49 | cout << "No Loop"; 50 | 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /Data Structures/LinkedList/linked.cpp: -------------------------------------------------------------------------------- 1 | //linked_list_insertion 2 | //conmplexity : O(n) 3 | 4 | #include 5 | #include 6 | struct link 7 | { int n; 8 | link *next; //self referential pointer 9 | }*h,*ptr,*tmp; 10 | 11 | void main() 12 | { clrscr(); 13 | int choice,i=0; 14 | cout<<"Linked list:\n"; 15 | cout<<"Add elements\n"; 16 | h=new link; //dynamic initialisation of element in linked list 17 | h->next=NULL; 18 | 19 | ptr=h; 20 | for(;i<4;i++) 21 | { cout<<"Enter no.:\n"; 22 | cin>>ptr->n; 23 | if(i<4) 24 | { ptr->next=new link; //dynamic initialisation of element in linked list 25 | ptr->next->next=NULL; 26 | } 27 | ptr=ptr->next; 28 | } 29 | 30 | ptr=h; 31 | for(i=0;i<4;i++) 32 | { cout<n; 33 | ptr=ptr->next; 34 | cout<<"\t"; 35 | } 36 | cout<<"\n\nWHERE TO ADD MORE No: "; 37 | cout<<"\n1.BEGINNING\n2.END\n"; 38 | cout<<"Enter your choice :"; 39 | cin>>choice; 40 | 41 | tmp=new link; 42 | tmp->next=NULL; 43 | cout<<"ENTER THE No.: "; 44 | cin>>tmp->n; 45 | 46 | if(choice==1) //add element in beginning 47 | { ptr=h; 48 | tmp->next=ptr; 49 | ptr=tmp; 50 | cout<<"THIS IS AT THE BEGINGING: \n" ; 51 | 52 | for(i=0;i<5;i++) 53 | { cout<n; 54 | cout<<"\t"; 55 | ptr=ptr->next; 56 | } 57 | } 58 | 59 | else if(choice==2) //add element in the end of list 60 | { 61 | ptr=h; 62 | cout<<"Insertion at the end: \n"; 63 | 64 | for(i=0;i<5;i++) 65 | { if(ptr->next==NULL) 66 | { ptr->next=tmp; 67 | tmp->next=NULL; 68 | } 69 | ptr=ptr->next; 70 | } 71 | 72 | ptr=h; 73 | for(i=0;i<5;i++) 74 | { cout<n<<"\t"; 75 | ptr=ptr->next; 76 | } 77 | } 78 | 79 | else 80 | cout<<"WRONG CHOICE\n"; 81 | } -------------------------------------------------------------------------------- /Data Structures/SegmentTrees.c: -------------------------------------------------------------------------------- 1 | // C program to show segment tree operations like construction, query 2 | // and update 3 | #include 4 | #include 5 | 6 | // A utility function to get the middle index from corner indexes. 7 | int getMid(int s, int e) { return s + (e -s)/2; } 8 | 9 | /* A recursive function to get the sum of values in given range 10 | of the array. The following are parameters for this function. 11 | 12 | st --> Pointer to segment tree 13 | si --> Index of current node in the segment tree. Initially 14 | 0 is passed as root is always at index 0 15 | ss & se --> Starting and ending indexes of the segment represented 16 | by current node, i.e., st[si] 17 | qs & qe --> Starting and ending indexes of query range */ 18 | int getSumUtil(int *st, int ss, int se, int qs, int qe, int si) 19 | { 20 | // If segment of this node is a part of given range, then return 21 | // the sum of the segment 22 | if (qs <= ss && qe >= se) 23 | return st[si]; 24 | 25 | // If segment of this node is outside the given range 26 | if (se < qs || ss > qe) 27 | return 0; 28 | 29 | // If a part of this segment overlaps with the given range 30 | int mid = getMid(ss, se); 31 | return getSumUtil(st, ss, mid, qs, qe, 2*si+1) + 32 | getSumUtil(st, mid+1, se, qs, qe, 2*si+2); 33 | } 34 | 35 | /* A recursive function to update the nodes which have the given 36 | index in their range. The following are parameters 37 | st, si, ss and se are same as getSumUtil() 38 | i --> index of the element to be updated. This index is 39 | in input array. 40 | diff --> Value to be added to all nodes which have i in range */ 41 | void updateValueUtil(int *st, int ss, int se, int i, int diff, int si) 42 | { 43 | // Base Case: If the input index lies outside the range of 44 | // this segment 45 | if (i < ss || i > se) 46 | return; 47 | 48 | // If the input index is in range of this node, then update 49 | // the value of the node and its children 50 | st[si] = st[si] + diff; 51 | if (se != ss) 52 | { 53 | int mid = getMid(ss, se); 54 | updateValueUtil(st, ss, mid, i, diff, 2*si + 1); 55 | updateValueUtil(st, mid+1, se, i, diff, 2*si + 2); 56 | } 57 | } 58 | 59 | // The function to update a value in input array and segment tree. 60 | // It uses updateValueUtil() to update the value in segment tree 61 | void updateValue(int arr[], int *st, int n, int i, int new_val) 62 | { 63 | // Check for erroneous input index 64 | if (i < 0 || i > n-1) 65 | { 66 | printf("Invalid Input"); 67 | return; 68 | } 69 | 70 | // Get the difference between new value and old value 71 | int diff = new_val - arr[i]; 72 | 73 | // Update the value in array 74 | arr[i] = new_val; 75 | 76 | // Update the values of nodes in segment tree 77 | updateValueUtil(st, 0, n-1, i, diff, 0); 78 | } 79 | 80 | // Return sum of elements in range from index qs (quey start) 81 | // to qe (query end). It mainly uses getSumUtil() 82 | int getSum(int *st, int n, int qs, int qe) 83 | { 84 | // Check for erroneous input values 85 | if (qs < 0 || qe > n-1 || qs > qe) 86 | { 87 | printf("Invalid Input"); 88 | return -1; 89 | } 90 | 91 | return getSumUtil(st, 0, n-1, qs, qe, 0); 92 | } 93 | 94 | // A recursive function that constructs Segment Tree for array[ss..se]. 95 | // si is index of current node in segment tree st 96 | int constructSTUtil(int arr[], int ss, int se, int *st, int si) 97 | { 98 | // If there is one element in array, store it in current node of 99 | // segment tree and return 100 | if (ss == se) 101 | { 102 | st[si] = arr[ss]; 103 | return arr[ss]; 104 | } 105 | 106 | // If there are more than one elements, then recur for left and 107 | // right subtrees and store the sum of values in this node 108 | int mid = getMid(ss, se); 109 | st[si] = constructSTUtil(arr, ss, mid, st, si*2+1) + 110 | constructSTUtil(arr, mid+1, se, st, si*2+2); 111 | return st[si]; 112 | } 113 | 114 | /* Function to construct segment tree from given array. This function 115 | allocates memory for segment tree and calls constructSTUtil() to 116 | fill the allocated memory */ 117 | int *constructST(int arr[], int n) 118 | { 119 | // Allocate memory for segment tree 120 | 121 | //Height of segment tree 122 | int x = (int)(ceil(log2(n))); 123 | 124 | //Maximum size of segment tree 125 | int max_size = 2*(int)pow(2, x) - 1; 126 | 127 | // Allocate memory 128 | int *st = new int[max_size]; 129 | 130 | // Fill the allocated memory st 131 | constructSTUtil(arr, 0, n-1, st, 0); 132 | 133 | // Return the constructed segment tree 134 | return st; 135 | } 136 | 137 | // Main 138 | int main() 139 | { 140 | int arr[] = {0, 2, 5, 6, 10, 13}; 141 | int n = sizeof(arr)/sizeof(arr[0]); 142 | 143 | // Build segment tree from given array 144 | int *st = constructST(arr, n); 145 | 146 | // Print sum of values in array from index 1 to 3 147 | printf("Sum of values in given range = %dn", 148 | getSum(st, n, 1, 3)); 149 | 150 | // Update: set arr[1] = 10 and update corresponding 151 | // segment tree nodes 152 | updateValue(arr, st, n, 1, 10); 153 | 154 | // Find sum after the value is updated 155 | printf("Updated sum of values in given range = %dn", 156 | getSum(st, n, 1, 3)); 157 | return 0; 158 | } 159 | -------------------------------------------------------------------------------- /Data Structures/VectorErase.cpp: -------------------------------------------------------------------------------- 1 | //C++ program to perform an erase in a vector 2 | //You are provided with a vector of integers. 3 | //Then, you are given queries. For the first query, you are provided with integer, 4 | //which denotes a position in the vector. The value at this position in the vector needs to be erased. 5 | //The next query consists of integers denoting a range of the positions in the vector. 6 | //The elements which fall under that range should be removed. 7 | //The second query is performed on the updated vector which we get after performing the first query. 8 | 9 | //problem statement link: https://www.hackerrank.com/challenges/vector-erase/problem 10 | 11 | 32 lines (29 sloc) 582 Bytes 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | using namespace std; 18 | 19 | 20 | int main() { 21 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 22 | int n; 23 | vector v; 24 | cin>>n; 25 | for(int i=0;i> num; 28 | v.push_back(num); 29 | } 30 | int x; 31 | cin>>x; 32 | v.erase(v.begin()+x-1); 33 | int a,b; 34 | cin>>a>>b; 35 | v.erase(v.begin()+a-1,v.begin()+b-1); 36 | int s = v.size(); 37 | cout< 5 | #include 6 | #include 7 | #include 8 | #include 9 | using namespace std; 10 | 11 | 12 | int main() { 13 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 14 | vector v; 15 | int k; 16 | cin>> k; 17 | for(int j=0;j>num; 20 | v.push_back(num); 21 | } 22 | sort(v.begin(),v.end()); 23 | int s = v.size(); 24 | for(int i=0;i= 0;i--) { 20 | // maxHeapify(arr,i,n); 21 | // } 22 | 23 | // arr = heapSort(arr); 24 | 25 | // for (int i=0;i=0;i--) { 39 | 40 | int temp = arr[i]; 41 | arr[i] = arr[0]; 42 | arr[0] = temp; 43 | maxHeapify(arr,0,i); 44 | } 45 | return arr; 46 | } 47 | 48 | public static void maxHeapify(int[] arr,int i, int last) { 49 | int l = 2*i + 1; 50 | int r = 2*i + 2; 51 | int largest = i; 52 | 53 | if (l < last && arr[largest] < arr[l]) { 54 | largest = l; 55 | } 56 | if (r < last && arr[largest] < arr[r]) { 57 | largest = r; 58 | } 59 | 60 | if (largest != i) { 61 | int temp = arr[largest]; 62 | arr[largest] = arr[i]; 63 | arr[i] = temp; 64 | 65 | maxHeapify(arr,largest,last); 66 | } 67 | } 68 | 69 | public static void kthSmallest(int[] arr,int k) { 70 | 71 | for (int i = k/2-1;i >= 0;i--) { 72 | maxHeapify(arr,i,k); 73 | } 74 | 75 | for (int i = k;i < arr.length;i++) { 76 | if (arr[i] < arr[0]) { 77 | int temp = arr[0]; 78 | arr[0] = arr[i]; 79 | arr[i] = temp; 80 | } 81 | maxHeapify(arr,0,k); 82 | } 83 | System.out.println(arr[0]); 84 | } 85 | 86 | public static void printKLargest(int[] arr, int k) { 87 | 88 | int n = arr.length; 89 | for (int i = (arr.length/2 - 1);i >= 0;i--) { 90 | maxHeapify(arr,i,n); 91 | } 92 | 93 | for (int i=0;i queue = new PriorityQueue(); 114 | 115 | for (int i=1;i<=arr.length;i++) { 116 | for (int j=i;j<=arr.length;j++) { 117 | int x = sum[j] - arr[i-1]; 118 | 119 | if (queue.size() < k) { 120 | queue.add(x); 121 | } else { 122 | if (x > queue.peek()) { 123 | queue.poll(); 124 | queue.add(x); 125 | } 126 | } 127 | } 128 | } 129 | 130 | System.out.println(queue.poll()); 131 | } 132 | 133 | public static void minProductk(int[] arr,int k) { 134 | 135 | int n = arr.length; 136 | // use min heap 137 | } 138 | 139 | static class item { 140 | int val; 141 | int idx1; 142 | int idx2; 143 | item (int val,int idx1,int idx2) { 144 | this.val = val; 145 | this.idx1 = idx1; 146 | this.idx2 = idx2; 147 | } 148 | } 149 | 150 | 151 | // TO DO 152 | public static void kMaxSumCombinations (int k) { 153 | 154 | PriorityQueue q = new PriorityQueue(k ,new Comparator() { 155 | 156 | @Override 157 | public int compare(item i1,item i2) { 158 | if (i1.val > i2.val) 159 | return 1; 160 | else 161 | return -1; 162 | } 163 | }); 164 | 165 | int n = sc.nextInt(); 166 | int[] arr = new int[n]; 167 | int[] ar = new int[n]; 168 | 169 | for (int i=0;i q = new PriorityQueue(); 207 | 208 | for (int i=0;i list = new ArrayList(); 213 | for (int i=k+1;i 4 | #include 5 | #include 6 | 7 | // a structure to represent a weighted edge in graph 8 | struct Edge 9 | { 10 | int src, dest, weight; 11 | }; 12 | 13 | // a structure to represent a connected, undirected 14 | // and weighted graph 15 | struct Graph 16 | { 17 | // V-> Number of vertices, E-> Number of edges 18 | int V, E; 19 | 20 | // graph is represented as an array of edges. 21 | // Since the graph is undirected, the edge 22 | // from src to dest is also edge from dest 23 | // to src. Both are counted as 1 edge here. 24 | struct Edge* edge; 25 | }; 26 | 27 | // Creates a graph with V vertices and E edges 28 | struct Graph* createGraph(int V, int E) 29 | { 30 | struct Graph* graph = new Graph; 31 | graph->V = V; 32 | graph->E = E; 33 | 34 | graph->edge = new Edge[E]; 35 | 36 | return graph; 37 | } 38 | 39 | // A structure to represent a subset for union-find 40 | struct subset 41 | { 42 | int parent; 43 | int rank; 44 | }; 45 | 46 | // A utility function to find set of an element i 47 | // (uses path compression technique) 48 | int find(struct subset subsets[], int i) 49 | { 50 | // find root and make root as parent of i 51 | // (path compression) 52 | if (subsets[i].parent != i) 53 | subsets[i].parent = find(subsets, subsets[i].parent); 54 | 55 | return subsets[i].parent; 56 | } 57 | 58 | // A function that does union of two sets of x and y 59 | // (uses union by rank) 60 | void Union(struct subset subsets[], int x, int y) 61 | { 62 | int xroot = find(subsets, x); 63 | int yroot = find(subsets, y); 64 | 65 | // Attach smaller rank tree under root of high 66 | // rank tree (Union by Rank) 67 | if (subsets[xroot].rank < subsets[yroot].rank) 68 | subsets[xroot].parent = yroot; 69 | else if (subsets[xroot].rank > subsets[yroot].rank) 70 | subsets[yroot].parent = xroot; 71 | 72 | // If ranks are same, then make one as root and 73 | // increment its rank by one 74 | else 75 | { 76 | subsets[yroot].parent = xroot; 77 | subsets[xroot].rank++; 78 | } 79 | } 80 | 81 | // Compare two edges according to their weights. 82 | // Used in qsort() for sorting an array of edges 83 | int myComp(const void* a, const void* b) 84 | { 85 | struct Edge* a1 = (struct Edge*)a; 86 | struct Edge* b1 = (struct Edge*)b; 87 | return a1->weight > b1->weight; 88 | } 89 | 90 | // The main function to construct MST using Kruskal's algorithm 91 | void KruskalMST(struct Graph* graph) 92 | { 93 | int V = graph->V; 94 | struct Edge result[V]; // Tnis will store the resultant MST 95 | int e = 0; // An index variable, used for result[] 96 | int i = 0; // An index variable, used for sorted edges 97 | 98 | // Step 1: Sort all the edges in non-decreasing 99 | // order of their weight. If we are not allowed to 100 | // change the given graph, we can create a copy of 101 | // array of edges 102 | qsort(graph->edge, graph->E, sizeof(graph->edge[0]), myComp); 103 | 104 | // Allocate memory for creating V ssubsets 105 | struct subset *subsets = 106 | (struct subset*) malloc( V * sizeof(struct subset) ); 107 | 108 | // Create V subsets with single elements 109 | for (int v = 0; v < V; ++v) 110 | { 111 | subsets[v].parent = v; 112 | subsets[v].rank = 0; 113 | } 114 | 115 | // Number of edges to be taken is equal to V-1 116 | while (e < V - 1) 117 | { 118 | // Step 2: Pick the smallest edge. And increment 119 | // the index for next iteration 120 | struct Edge next_edge = graph->edge[i++]; 121 | 122 | int x = find(subsets, next_edge.src); 123 | int y = find(subsets, next_edge.dest); 124 | 125 | // If including this edge does't cause cycle, 126 | // include it in result and increment the index 127 | // of result for next edge 128 | if (x != y) 129 | { 130 | result[e++] = next_edge; 131 | Union(subsets, x, y); 132 | } 133 | // Else discard the next_edge 134 | } 135 | 136 | // print the contents of result[] to display the 137 | // built MST 138 | printf("Following are the edges in the constructed MST\n"); 139 | for (i = 0; i < e; ++i) 140 | printf("%d -- %d == %d\n", result[i].src, result[i].dest, 141 | result[i].weight); 142 | return; 143 | } 144 | 145 | // Driver program to test above functions 146 | int main() 147 | { 148 | /* Let us create following weighted graph 149 | 10 150 | 0--------1 151 | | \ | 152 | 6| 5\ |15 153 | | \ | 154 | 2--------3 155 | 4 */ 156 | int V = 4; // Number of vertices in graph 157 | int E = 5; // Number of edges in graph 158 | struct Graph* graph = createGraph(V, E); 159 | 160 | 161 | // add edge 0-1 162 | graph->edge[0].src = 0; 163 | graph->edge[0].dest = 1; 164 | graph->edge[0].weight = 10; 165 | 166 | // add edge 0-2 167 | graph->edge[1].src = 0; 168 | graph->edge[1].dest = 2; 169 | graph->edge[1].weight = 6; 170 | 171 | // add edge 0-3 172 | graph->edge[2].src = 0; 173 | graph->edge[2].dest = 3; 174 | graph->edge[2].weight = 5; 175 | 176 | // add edge 1-3 177 | graph->edge[3].src = 1; 178 | graph->edge[3].dest = 3; 179 | graph->edge[3].weight = 15; 180 | 181 | // add edge 2-3 182 | graph->edge[4].src = 2; 183 | graph->edge[4].dest = 3; 184 | graph->edge[4].weight = 4; 185 | 186 | KruskalMST(graph); 187 | 188 | return 0; 189 | } 190 | -------------------------------------------------------------------------------- /Data Structures/queue.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | struct node 5 | { int number; 6 | node *next; //self referential node 7 | }; 8 | node *add_Q(node *rear, int val); //fuction to add elements in queue 9 | node *del_Q(node *front, int &val); //fuction to delete elements from queue 10 | void show_Q(node *front); //fuction to show elements in queue 11 | void main() 12 | { clrscr(); 13 | node *front, *rear; 14 | int val; 15 | int choice; 16 | char ch; 17 | front =NULL; 18 | rear = NULL; 19 | do 20 | { cout << "\n\t Main Menu"; //menu showing choices to the user 21 | cout << "\n\t1. ADD TO Queue"; 22 | cout << "\n\t2. DELETE from Queue"; 23 | cout << "\n\t3.SHOW Queue"; 24 | cout << "\n\t4. Exit from Menu"; 25 | cout << "\n\nEnter Your choice: "; 26 | cin >> choice; 27 | switch (choice) //input of choice from user 28 | { case 1:do 29 | { cout << "Enter the value to be added in the queue: "; 30 | cin >> val; 31 | rear = add_Q(rear, val); //call the add_Q() function to add element in the end 32 | if (front == NULL) 33 | front = rear; 34 | cout << "Do you want to add more element ?: "; 35 | cin >> ch; 36 | } while (ch == 'Y'||ch=='y'); 37 | break; 38 | case 2: do 39 | { front = del_Q(front, val); //call the del_Q() function to delete element from the front 40 | if (front == NULL) 41 | rear = front; 42 | if (val != -1) 43 | cout << "Value deleted from Queue is " << val; 44 | cout << "\nDo you want to delete more element ? "; 45 | cin >> ch; 46 | } while (ch== 'Y'||ch=='y'); 47 | break; 48 | case 3:show_Q(front); //call the show_Q() 49 | break; 50 | case 4:exit(0); 51 | } 52 | }while (choice != 4); 53 | } 54 | node *add_Q(node *rear, int val) 55 | { node *temp; 56 | temp = new node; //dynamic initialisation of element in queue 57 | temp->number = val; 58 | temp->next = NULL; 59 | rear->next = temp; 60 | rear = temp; 61 | return (rear); 62 | } 63 | node *del_Q(node *front, int &val) 64 | { node *temp; 65 | clrscr(); 66 | if (front == NULL) 67 | { cout << "Queue Empty "; 68 | val = -1; 69 | 70 | } 71 | else 72 | { temp = front; 73 | front = front->next; 74 | val = temp->number; 75 | temp->next = NULL; 76 | delete temp; //deleting the allocated memory to first element of queue 77 | } 78 | return (front); 79 | } 80 | void show_Q(node *front) 81 | { node *temp; 82 | temp = front; 83 | clrscr(); 84 | cout << "The Queue values are: "; 85 | while (temp != NULL) 86 | { cout<<"\t"<number; 87 | temp = temp->next; 88 | } 89 | } -------------------------------------------------------------------------------- /Data Structures/stack.cpp: -------------------------------------------------------------------------------- 1 | //Stack_Code 2 | // Complexity: O(1) 3 | 4 | #include 5 | #include 6 | #include 7 | struct node 8 | { //declaring a structure 9 | int number; 10 | node *next; //self referential pointer 11 | }; 12 | node *push(node *top, int val); //fuction to push element into stack 13 | node *pop(node *top); //fuction to pop element from stack 14 | void show_Stack(node *top); 15 | int main() 16 | { 17 | node *top; 18 | int tnumber, choice; 19 | char ch; 20 | top = NULL; 21 | clrscr(); 22 | do //menu showing choices to the user 23 | { cout << "\n\t Main Menu"; 24 | cout << "\n\t1. ADD TO Stack"; 25 | cout << "\n\t2. DELETE from Stack"; 26 | cout << "\n\t3. SHOW Stack"; 27 | cout << "\n\t4. Exit from Menu"; 28 | cout << "\n\nEnter your choice : "; 29 | cin >> choice; //input of choice from user 30 | switch (choice) 31 | { case 1: do 32 | { cout << "Enter the no. : "; 33 | cin >> tnumber; 34 | top = push(top, tnumber); //call the push() function 35 | cout << "Do you want to add more elements ?: "; 36 | cin >>ch; 37 | } while (ch== 'Y'||ch=='y'); 38 | break; 39 | 40 | case 2: do 41 | { top = pop(top); //call the pop() function 42 | cout << "\nDo you want to delete more elements ?: "; 43 | cin >>ch; 44 | } while (ch== 'Y'||ch=='y'); 45 | break; 46 | 47 | case 3: show_Stack(top); //call the show_Stack() function 48 | break; 49 | 50 | case 4: exit(0); 51 | } 52 | }while (choice != 4); 53 | return 0; 54 | } 55 | 56 | node *push(node *top, int val) 57 | { node *temp; 58 | temp = new node; //dynamic initialisation of element in stack 59 | temp->number = val; 60 | temp->next = NULL; 61 | if(top ==NULL) 62 | top = temp; 63 | else 64 | { temp->next = top; 65 | top = temp; 66 | } 67 | return(top); 68 | } 69 | node *pop(node *top) 70 | { node *temp; 71 | if (top == NULL ) 72 | { cout << "Stack Empty "; 73 | exit(0); 74 | } 75 | else 76 | { temp = top; 77 | top = top->next; 78 | temp->next = NULL; 79 | cout << "\n\tPopped Number is : " << temp->number; 80 | delete temp; //deleting the allocated memory to top element of stack 81 | } 82 | return (top); 83 | } 84 | void show_Stack(node *top) 85 | { node *temp; 86 | temp = top; 87 | clrscr(); 88 | cout << "The values are \n"; 89 | while (temp != NULL) 90 | { 91 | cout<number << "\t"; 92 | temp = temp->next; 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /Dijkstra'sShortestPathAlgorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | template 5 | 6 | 7 | // Code for Templated Graph 8 | class Graph{ 9 | unordered_map>> m; 10 | 11 | public: 12 | 13 | void addEdge(T node1, T node2, int weight=1, bool bidir=true){ 14 | m[node1].push_back( make_pair(node2,weight)); 15 | if(bidir) 16 | m[node2].push_back( make_pair(node1,weight)); 17 | } 18 | 19 | void printAdjList(){ 20 | for(auto i: m){ 21 | cout< "; 22 | for(auto j:i.second) 23 | cout<<"("< distanceFromSrcNode; 33 | for(auto i:m) // Setting initial distanceFromSrcNode values for all nodes to be infinite 34 | distanceFromSrcNode[i.first] = INT_MAX; 35 | distanceFromSrcNode[src] = 0; // Setting initial distanceFromSrcNode values for src node to be zero 36 | 37 | set> s; 38 | s.insert( make_pair(0,src) ); 39 | 40 | while(!s.empty()){ 41 | auto firtsPairInSet = *(s.begin()) ; 42 | T node = firtsPairInSet.second; 43 | int distanceOfParentFromSrc = firtsPairInSet.first; 44 | s.erase(s.begin()); // In each iteration distanceFromSrcNode of a node is calculated and that node is erased from set 45 | 46 | for(auto neighbourPair: m[node]){ 47 | T neighbour = neighbourPair.first; 48 | if( distanceOfParentFromSrc + neighbourPair.second < distanceFromSrcNode[neighbour]){ 49 | 50 | auto foundAt = s.find( make_pair(distanceFromSrcNode[neighbour],neighbour) ); // takes O(1) time 51 | 52 | //Removing the old pair if found 53 | if(foundAt != s.end()) 54 | s.erase(foundAt); // takes O(logN) time 55 | 56 | //Adding new pair with updated distance from src node 57 | distanceFromSrcNode[neighbour] = distanceOfParentFromSrc + neighbourPair.second ; 58 | s.insert(make_pair(distanceFromSrcNode[neighbour],neighbour)); 59 | } 60 | } 61 | } 62 | 63 | for(auto i:distanceFromSrcNode) 64 | cout<<"Distance of "< g; 69 | g.addEdge(1,2); 70 | g.addEdge(1,3); 71 | g.addEdge(1,4); 72 | g.addEdge(2,3); 73 | g.addEdge(3,4); 74 | g.printAdjList(); 75 | g.dijkstra(1); 76 | return 0; 77 | } 78 | -------------------------------------------------------------------------------- /Games/Maze.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | //If game is playing, it won't if player terminated it or has won 7 | bool Playing = true; 8 | 9 | //Initial x & y position of player 10 | int x = 1; 11 | int y = 8; 12 | //Maze information . is for obstacle nothing is for walkable path & > is for goal 13 | char Map[10][20] = 14 | { 15 | {'.','.','.','.', '.', '.', '.', '.', '.', '.','.','.','.', '.', '.', '.', '.', '.'}, 16 | {'.',' ',' ',' ', '.', ' ', ' ', ' ',' ','.',' ', ' ', ' ', ' ', ' ', ' ', ' ', '.'}, 17 | {'.','.','.',' ', '.', ' ', ' ', '.','.','.','.', '.', ' ', ' ', ' ', ' ', ' ', '.'}, 18 | {'.',' ',' ',' ', ' ', '.', '.', ' ',' ',' ',' ', ' ', ' ', ' ', '.', ' ', ' ', '.'}, 19 | {'.',' ',' ','.', '.', '.', '.', ' ',' ',' ',' ', '.', '.', '.', '.', '.', ' ', '.'}, 20 | {'.',' ',' ','.', ' ', ' ', '.', ' ',' ',' ',' ', ' ', ' ', '.', ' ', '.', ' ', '.'}, 21 | {'.',' ',' ','.', ' ', ' ', '.', '.',' ',' ','.', '.', '.', '.', ' ', '.', ' ', '.'}, 22 | {'.',' ','.','.', ' ', ' ', ' ', ' ',' ','.','.', ' ', ' ', '.', '.', '.', ' ', '.'}, 23 | {'.',' ',' ',' ', ' ', ' ', ' ', '.',' ',' ','.', ' ', ' ', ' ', ' ', ' ', ' ', '>'}, 24 | {'.','.','.','.', '.', '.', '.', '.', '.', '.','.','.','.', '.', '.', '.', '.', '.'} 25 | }; 26 | 27 | void GameWon () 28 | { 29 | //Stop playing since player won and print that he won 30 | Playing = false; 31 | cout << "\n\n\n"; 32 | cout << "A WINNER IS YOU :)"; 33 | } 34 | 35 | void Refresh () 36 | { 37 | //Give 100 line spacing for refreshing 38 | cout << string( 100, '\n' ); 39 | cout << "Use arrow key to move around & Esc to quit" << Map[y][x] << "\n"; 40 | for (int i=0; i<10; i++) 41 | { 42 | for (int j=0; j<20; j++) 43 | { 44 | if (i == y && j == x) cout << '*'; 45 | else cout << Map[i][j]; 46 | } 47 | cout << "\n"; 48 | } 49 | if (Map[y][x] == '>') GameWon(); 50 | } 51 | 52 | bool Pressed1 = false; 53 | bool Pressed2 = false; 54 | bool Pressed3 = false; 55 | bool Pressed4 = false; 56 | int main () 57 | { 58 | //Refresh in starting 59 | Refresh(); 60 | //While game is playing 61 | while(Playing) 62 | { 63 | //If escape is pressed stop playing 64 | if(GetKeyState(VK_ESCAPE) < 0) Playing = false; 65 | 66 | //If up button pressed check if there isn't any obstacle if no then change y pos and refresh 67 | if(GetKeyState(VK_UP) < 0) 68 | { 69 | if (Map[y-1][x] != '.' && !Pressed1) 70 | { 71 | y--; 72 | Refresh(); 73 | } 74 | Pressed1 = true; 75 | } 76 | else Pressed1 = false; 77 | 78 | //If down button pressed check if there isn't any obstacle if no then change y pos and refresh 79 | if(GetKeyState(VK_DOWN) < 0) 80 | { 81 | if (Map[y+1][x] != '.' && !Pressed2) 82 | { 83 | y++; 84 | Refresh(); 85 | } 86 | Pressed2 = true; 87 | } 88 | else Pressed2 = false; 89 | 90 | //If left button pressed check if there isn't any obstacle if no then change x pos and refresh 91 | if(GetKeyState(VK_LEFT) < 0) 92 | { 93 | if (Map[y][x-1] != '.' && !Pressed3) 94 | { 95 | x--; 96 | Refresh(); 97 | } 98 | Pressed3 = true; 99 | } 100 | else Pressed3 = false; 101 | 102 | //If right button pressed check if there isn't any obstacle if no then change x pos and refresh 103 | if(GetKeyState(VK_RIGHT) < 0) 104 | { 105 | if (Map[y][x+1] != '.' && !Pressed4) 106 | { 107 | x++; 108 | Refresh(); 109 | } 110 | Pressed4 = true; 111 | } 112 | else Pressed4 = false; 113 | } 114 | 115 | return(0); 116 | } -------------------------------------------------------------------------------- /Games/Snake.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void run(); 5 | void printMap(); 6 | void initMap(); 7 | void move(int dx, int dy); 8 | void update(); 9 | void changeDirection(char key); 10 | void clearScreen(); 11 | void generateFood(); 12 | 13 | char getMapValue(int value); 14 | 15 | // Map dimensions 16 | const int mapwidth = 20; 17 | const int mapheight = 20; 18 | 19 | const int size = mapwidth * mapheight; 20 | 21 | // The tile values for the map 22 | int map[size]; 23 | 24 | // Snake head details 25 | int headxpos; 26 | int headypos; 27 | int direction; 28 | 29 | // Amount of food the snake has (How long the body is) 30 | int food = 3; 31 | 32 | // Determine if game is running 33 | bool running; 34 | 35 | int main() 36 | { 37 | run(); 38 | return 0; 39 | } 40 | 41 | // Main game function 42 | void run() 43 | { 44 | // Initialize the map 45 | initMap(); 46 | running = true; 47 | while (running) { 48 | // If a key is pressed 49 | if (kbhit()) { 50 | // Change to direction determined by key pressed 51 | changeDirection(getch()); 52 | } 53 | // Upate the map 54 | update(); 55 | 56 | // Clear the screen 57 | clearScreen(); 58 | 59 | // Print the map 60 | printMap(); 61 | 62 | // wait 0.5 seconds 63 | _sleep(500); 64 | } 65 | 66 | // Print out game over text 67 | std::cout << "\t\t!!!Game over!" << std::endl << "\t\tYour score is: " << food; 68 | 69 | // Stop console from closing instantly 70 | std::cin.ignore(); 71 | } 72 | 73 | // Changes snake direction from input 74 | void changeDirection(char key) { 75 | /* 76 | W 77 | A + D 78 | S 79 | 80 | 1 81 | 4 + 2 82 | 3 83 | */ 84 | switch (key) { 85 | case 'w': 86 | if (direction != 2) direction = 0; 87 | break; 88 | case 'd': 89 | if (direction != 3) direction = 1; 90 | break; 91 | case 's': 92 | if (direction != 4) direction = 2; 93 | break; 94 | case 'a': 95 | if (direction != 5) direction = 3; 96 | break; 97 | } 98 | } 99 | 100 | // Moves snake head to new location 101 | void move(int dx, int dy) { 102 | // determine new head position 103 | int newx = headxpos + dx; 104 | int newy = headypos + dy; 105 | 106 | // Check if there is food at location 107 | if (map[newx + newy * mapwidth] == -2) { 108 | // Increase food value (body length) 109 | food++; 110 | 111 | // Generate new food on map 112 | generateFood(); 113 | } 114 | 115 | // Check location is free 116 | else if (map[newx + newy * mapwidth] != 0) { 117 | running = false; 118 | } 119 | 120 | // Move head to new location 121 | headxpos = newx; 122 | headypos = newy; 123 | map[headxpos + headypos * mapwidth] = food + 1; 124 | 125 | } 126 | 127 | // Clears screen 128 | void clearScreen() { 129 | // Clear the screen 130 | system("cls"); 131 | } 132 | 133 | // Generates new food on map 134 | void generateFood() { 135 | int x = 0; 136 | int y = 0; 137 | do { 138 | // Generate random x and y values within the map 139 | x = rand() % (mapwidth - 2) + 1; 140 | y = rand() % (mapheight - 2) + 1; 141 | 142 | // If location is not free try again 143 | } while (map[x + y * mapwidth] != 0); 144 | 145 | // Place new food 146 | map[x + y * mapwidth] = -2; 147 | } 148 | 149 | // Updates the map 150 | void update() { 151 | // Move in direction indicated 152 | switch (direction) { 153 | case 0: move(-1, 0); 154 | break; 155 | case 1: move(0, 1); 156 | break; 157 | case 2: move(1, 0); 158 | break; 159 | case 3: move(0, -1); 160 | break; 161 | } 162 | 163 | // Reduce snake values on map by 1 164 | for (int i = 0; i < size; i++) { 165 | if (map[i] > 0) map[i]--; 166 | } 167 | } 168 | 169 | // Initializes map 170 | void initMap() 171 | { 172 | // Places the initual head location in middle of map 173 | headxpos = mapwidth / 2; 174 | headypos = mapheight / 2; 175 | map[headxpos + headypos * mapwidth] = 1; 176 | 177 | // Places top and bottom walls 178 | for (int x = 0; x < mapwidth; ++x) { 179 | map[x] = -1; 180 | map[x + (mapheight - 1) * mapwidth] = -1; 181 | } 182 | 183 | // Places left and right walls 184 | for (int y = 0; y < mapheight; y++) { 185 | map[0 + y * mapwidth] = -1; 186 | map[(mapwidth - 1) + y * mapwidth] = -1; 187 | } 188 | 189 | // Generates first food 190 | generateFood(); 191 | } 192 | 193 | // Prints the map to console 194 | void printMap() 195 | { 196 | for (int x = 0; x < mapwidth; ++x) { 197 | for (int y = 0; y < mapheight; ++y) { 198 | // Prints the value at current x,y location 199 | std::cout << getMapValue(map[x + y * mapwidth]); 200 | } 201 | // Ends the line for next x value 202 | std::cout << std::endl; 203 | } 204 | } 205 | 206 | // Returns graphical character for display from map value 207 | char getMapValue(int value) 208 | { 209 | // Returns a part of snake body 210 | if (value > 0) return 'o'; 211 | 212 | switch (value) { 213 | // Return wall 214 | case -1: return 'X'; 215 | // Return food 216 | case -2: return 'O'; 217 | } 218 | } 219 | -------------------------------------------------------------------------------- /Games/flappy bird/flappy bird.cbp: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 43 | 44 | -------------------------------------------------------------------------------- /Games/flappy bird/flappy bird.layout: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Games/flappy bird/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | 11 | ifstream inp; //data file reading and writing operators 12 | ofstream outp; 13 | 14 | char c[30][21]; //variable for storing screen particles (pixels) 15 | int n[30][21]; //variable for checking 16 | int highscore; 17 | int contr,tuk=0,score=0,t=0,bt=0,birdx=0,birdy=0; //variaous variables for certain operations 18 | bool err; //boolean for error detection 19 | 20 | void game(); //various functions 21 | void screen(); 22 | void pipes(); 23 | void bird(); 24 | bool gameover(); 25 | void checkscore(); 26 | void help(); 27 | void menu(); 28 | void endgame(); 29 | void credits(); 30 | 31 | int main() 32 | { 33 | srand(time(0)); //seeding random number gen, we will need it later; 34 | inp.open("/Program Files/FlappyBird/options.txt"); //opening file in which highscore is stored 35 | if(inp.is_open()) //if file opens successfully, it reads the highscore 36 | { 37 | inp>>highscore; 38 | inp.close(); 39 | err=false; //error will be false, because file opened successfully 40 | } 41 | else 42 | { 43 | highscore=0; //if file doesnt exist, highscore will be 0, and err will be true 44 | err=true; 45 | } 46 | 47 | int a=0,b; 48 | char sl; //selection variable 49 | while(1) //loop for repeating actions after each start 50 | { 51 | if(a==0) goto play; 52 | if(a>0) //if you play not the first time, it will ask you if you want to play 53 | { 54 | score=0; 55 | cout<<"Do you want to play again? [y/n] "; 56 | cin>>sl; 57 | if(sl=='n') goto quit; 58 | else goto play; 59 | } 60 | play: 61 | menu(); //calling menu function 62 | cin>>sl; 63 | switch(sl) //menu selections 64 | { 65 | case '1': 66 | { 67 | game(); //if you choose play, it calls function game 68 | break; 69 | } 70 | case '2': //other selections-other functions 71 | { 72 | help(); 73 | goto play; 74 | break; 75 | } 76 | case '3': 77 | { 78 | credits(); 79 | goto play; 80 | break; 81 | } 82 | case '4': 83 | { 84 | goto quit; //exits game 85 | break; 86 | } 87 | default: 88 | { 89 | goto play; 90 | break; 91 | } 92 | } 93 | a++; //variable for checking how many times you've played 94 | } 95 | quit: 96 | { 97 | cout<<"I quit."; //stops game, app closes. 98 | } 99 | 100 | return 0; 101 | } 102 | 103 | void game() //function for playing game 104 | { 105 | int x,y; 106 | char s; 107 | for(y=0;y<21;y++) //setting screen 108 | { 109 | for(x=0;x<30;x++) 110 | { 111 | if(y<20) 112 | { 113 | c[x][y]=' '; 114 | n[x][y]=0; 115 | } 116 | if(y==20) 117 | { 118 | c[x][y]='-'; 119 | n[x][y]=2; 120 | } 121 | } 122 | } 123 | c[10][10]='*'; //in these coordinates will be our bird, marked * 124 | screen(); //calls func for showin screen 125 | while(1) //loop starts, actual gameplay begins 126 | { 127 | s='~'; //default control variable 128 | Sleep(0.2*1000); //this sets how fast everyhing moves 129 | t++; //this is a variable for storing 'time',or how many times a loop passed 130 | if(kbhit()) //if key is pressed, certain operations are done for bird to move up. 131 | { 132 | s=getch(); //gets what key is pressed 133 | if(s!='~') tuk=1; //if it is not default, then 'tuk' will be equal to 1, meaning that bird will fly up 134 | } 135 | for(x=0;x<30;x++) //just setting ground 136 | { 137 | c[x][20]='-'; 138 | n[x][20]=2; 139 | } 140 | bird(); //cals bird move function 141 | checkscore(); //checks score 142 | if(gameover()==true) goto gameEnd; //checks if bird hits pipes, if yes, game ends 143 | pipes(); //spawns and moves pipes 144 | if(score>highscore) highscore=score; //i think this is clear 145 | screen(); //finally, calls screen function to show enerything. 146 | 147 | if(tuk>0) tuk++; //if key is pressed, bird will fly up 2 times. 148 | if(tuk==3) tuk=0; //after that, bird falls 149 | } 150 | gameEnd: //ends game 151 | { 152 | if(score>highscore) highscore=score; 153 | if(err==false) //if hi-score file exists, it writes your new highscore there. 154 | { 155 | outp.open("/Program Files/FlappyBird/options.txt"); 156 | outp<0) 211 | { 212 | c[x-1][y]='|'; 213 | n[x-1][y]=2; 214 | c[x][y]=' '; 215 | n[x][y]=0; 216 | } 217 | if(x==0) //if screen ends (x=0) pipe will dissapear, to prevent errors 218 | { 219 | c[x][y]=' '; 220 | n[x][y]=0; 221 | } 222 | } 223 | } 224 | } 225 | } 226 | } 227 | 228 | void bird() //bird movement function! 229 | { 230 | int x,y; 231 | if(tuk>0) //if key is pressed, bird moves up 232 | { 233 | bt=0; 234 | for(y=0;y<20;y++) //loops for finding bird coordinates 235 | { 236 | for(x=0;x<30;x++) 237 | { 238 | if(c[x][y]=='*') 239 | { 240 | if(y>0) 241 | { 242 | c[x][y-1]='*'; //bird moves up by 1; 243 | c[x][y]=' '; 244 | birdx=x; //sets bird x coordinate 245 | birdy=y-1; //sets bird y coord 246 | return; //retuns to game func 247 | } 248 | } 249 | } 250 | } 251 | } 252 | else //if no key is pressed, bird falls 253 | { 254 | bt++; 255 | for(y=0;y<20;y++) 256 | { 257 | for(x=0;x<30;x++) 258 | { 259 | if(c[x][y]=='*') 260 | { 261 | if(y<20) //if bird is not on the ground 262 | { 263 | if(bt<3) //if bird time is lower that 3, it falls 1 pixel 264 | { 265 | c[x][y+1]='*'; 266 | c[x][y]=' '; 267 | birdx=x; 268 | birdy=y+1; 269 | return; 270 | } 271 | else if(bt>2 && bt<5) //more time has passed, faster bird falls (acceleration) 272 | { 273 | c[x][y+2]='*'; 274 | c[x][y]=' '; 275 | birdx=x; 276 | birdy=y+2; 277 | return; 278 | } 279 | else if(bt>4) 280 | { 281 | c[x][y+3]='*'; 282 | c[x][y]=' '; 283 | birdx=x; 284 | birdy=y+3; 285 | return; 286 | } 287 | } 288 | else 289 | { 290 | return; //if bird is already on the ground, function returns to check for game over. 291 | } 292 | } 293 | } 294 | } 295 | } 296 | } 297 | -------------------------------------------------------------------------------- /Games/flappy bird/obj/Debug/main.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IOSD/Algo/910c3123034352318b74dfac1d168ed8373d4989/Games/flappy bird/obj/Debug/main.o -------------------------------------------------------------------------------- /Games/tic tac toe/bin/Debug/tic tac toe.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IOSD/Algo/910c3123034352318b74dfac1d168ed8373d4989/Games/tic tac toe/bin/Debug/tic tac toe.exe -------------------------------------------------------------------------------- /Games/tic tac toe/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | char square[10] = {'o','1','2','3','4','5','6','7','8','9'}; 5 | 6 | int checkwin(); 7 | void board(); 8 | 9 | int main() 10 | { 11 | int player = 1,i,choice; 12 | 13 | char mark; 14 | do 15 | { 16 | board(); 17 | player=(player%2)?1:2; 18 | 19 | cout << "Player " << player << ", enter a number: "; 20 | cin >> choice; 21 | 22 | mark=(player == 1) ? 'X' : 'O'; 23 | 24 | if (choice == 1 && square[1] == '1') 25 | 26 | square[1] = mark; 27 | else if (choice == 2 && square[2] == '2') 28 | 29 | square[2] = mark; 30 | else if (choice == 3 && square[3] == '3') 31 | 32 | square[3] = mark; 33 | else if (choice == 4 && square[4] == '4') 34 | 35 | square[4] = mark; 36 | else if (choice == 5 && square[5] == '5') 37 | 38 | square[5] = mark; 39 | else if (choice == 6 && square[6] == '6') 40 | 41 | square[6] = mark; 42 | else if (choice == 7 && square[7] == '7') 43 | 44 | square[7] = mark; 45 | else if (choice == 8 && square[8] == '8') 46 | 47 | square[8] = mark; 48 | else if (choice == 9 && square[9] == '9') 49 | 50 | square[9] = mark; 51 | else 52 | { 53 | cout<<"Invalid move "; 54 | 55 | player--; 56 | cin.ignore(); 57 | cin.get(); 58 | } 59 | i=checkwin(); 60 | 61 | player++; 62 | }while(i==-1); 63 | board(); 64 | if(i==1) 65 | 66 | cout<<"==>\aPlayer "<<--player<<" win "; 67 | else 68 | cout<<"==>\aGame draw"; 69 | 70 | cin.ignore(); 71 | cin.get(); 72 | return 0; 73 | } 74 | 75 | /********************************************* 76 | 77 | FUNCTION TO RETURN GAME STATUS 78 | 1 FOR GAME IS OVER WITH RESULT 79 | -1 FOR GAME IS IN PROGRESS 80 | O GAME IS OVER AND NO RESULT 81 | **********************************************/ 82 | 83 | int checkwin() 84 | { 85 | if (square[1] == square[2] && square[2] == square[3]) 86 | 87 | return 1; 88 | else if (square[4] == square[5] && square[5] == square[6]) 89 | 90 | return 1; 91 | else if (square[7] == square[8] && square[8] == square[9]) 92 | 93 | return 1; 94 | else if (square[1] == square[4] && square[4] == square[7]) 95 | 96 | return 1; 97 | else if (square[2] == square[5] && square[5] == square[8]) 98 | 99 | return 1; 100 | else if (square[3] == square[6] && square[6] == square[9]) 101 | 102 | return 1; 103 | else if (square[1] == square[5] && square[5] == square[9]) 104 | 105 | return 1; 106 | else if (square[3] == square[5] && square[5] == square[7]) 107 | 108 | return 1; 109 | else if (square[1] != '1' && square[2] != '2' && square[3] != '3' 110 | && square[4] != '4' && square[5] != '5' && square[6] != '6' 111 | && square[7] != '7' && square[8] != '8' && square[9] != '9') 112 | 113 | return 0; 114 | else 115 | return -1; 116 | } 117 | 118 | 119 | /******************************************************************* 120 | FUNCTION TO DRAW BOARD OF TIC TAC TOE WITH PLAYERS MARK 121 | ********************************************************************/ 122 | 123 | 124 | void board() 125 | { 126 | cout << "\n\n\tTic Tac Toe\n\n"; 127 | 128 | cout << "Player 1 (X) - Player 2 (O)" << endl << endl; 129 | cout << endl; 130 | 131 | cout << " | | " << endl; 132 | cout << " " << square[1] << " | " << square[2] << " | " << square[3] << endl; 133 | 134 | cout << "_____|_____|_____" << endl; 135 | cout << " | | " << endl; 136 | 137 | cout << " " << square[4] << " | " << square[5] << " | " << square[6] << endl; 138 | 139 | cout << "_____|_____|_____" << endl; 140 | cout << " | | " << endl; 141 | 142 | cout << " " << square[7] << " | " << square[8] << " | " << square[9] << endl; 143 | 144 | cout << " | | " << endl << endl; 145 | } 146 | -------------------------------------------------------------------------------- /Games/tic tac toe/obj/Debug/main.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IOSD/Algo/910c3123034352318b74dfac1d168ed8373d4989/Games/tic tac toe/obj/Debug/main.o -------------------------------------------------------------------------------- /Games/tic tac toe/tic tac toe.cbp: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 42 | 43 | -------------------------------------------------------------------------------- /Games/tic tac toe/tic tac toe.layout: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /General/Day Of Week.c: -------------------------------------------------------------------------------- 1 | // Program to find Day Of Week using Sakamoto's algorithm 2 | /* 3 | Let us start with the simple scenario in which leap years did not exist and every year had 365 days. 4 | Knowing what day January 1 falls on a certain year, it is easy to find which day any other date falls. 5 | This is how you go about it : January has 31 = 7 × 4 + 3 days, so February 1 will fall on the day which follows three days after January 1. 6 | Similarly, March 1 will fall on the day three days after the day corresponding to January 1, April 1 will fall 6 days after, and so on. 7 | Thus, the first days of each month are offset with respect to January 1 by the array {0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5}. 8 | This array is essentially what t[] is. Notice that it is slightly different from the t[] given in the question, but that is due to leap 9 | years and will be explained later. Once the day corresponding to the first date of the month is known, finding the day for any other date 10 | is just a matter of addition. 11 | 12 | Since 365 = 7 × 52 + 1, the day corresponding to a given date will become incremented by 1 every year. 13 | For example, July 14, 2014 is a Monday and July 14, 2015 will be a Tuesday. Hence adding the difference between year numbers allows us 14 | to switch from the day of a reference year to any other year. 15 | */ 16 | 17 | // Detailed information about the algorithm can be found here: https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week 18 | 19 | #include 20 | 21 | int dayofweek(int d, int m, int y) 22 | { 23 | static int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4}; 24 | y -= m < 3; 25 | return (y + y / 4 - y / 100 + y / 400 + t[m - 1] + d) % 7; 26 | } 27 | 28 | int main() 29 | { 30 | int y, m, d; 31 | printf("Which year: "); 32 | scanf("%d", &y); 33 | printf("Which month: "); 34 | scanf("%d", &m); 35 | printf("Which date: "); 36 | scanf("%d", &d); 37 | int day = dayofweek(d, m, y); 38 | 39 | switch (day) 40 | { 41 | case 0: 42 | printf("Sunday"); 43 | break; 44 | case 1: 45 | printf("Monday"); 46 | break; 47 | case 2: 48 | printf("Tuesday"); 49 | break; 50 | case 3: 51 | printf("Wednesday"); 52 | break; 53 | case 4: 54 | printf("Thursday"); 55 | break; 56 | case 5: 57 | printf("Friday"); 58 | break; 59 | case 6: 60 | printf("Saturday"); 61 | break; 62 | } 63 | return 0; 64 | } -------------------------------------------------------------------------------- /General/Diophantine_Equation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int A,B,C; 5 | 6 | int gcd(int a, int b) 7 | { 8 | if (b==0) return a; 9 | else return gcd(b,a%b); 10 | } 11 | 12 | int d,x,y; 13 | void extended_Euclid(int a,int b) 14 | { 15 | if (b==0) 16 | { 17 | d = a; 18 | x = C; 19 | y = 0; 20 | } 21 | else 22 | { 23 | extended_Euclid(b,a%b); 24 | int temp = x; 25 | x = y; 26 | y = temp - ( (a/b)*y ); 27 | } 28 | } 29 | 30 | int main() 31 | { 32 | cout<<"Equation is of the form : ax + by = c"<>A; 34 | cout<<"Enter coeff of y "; cin>>B; 35 | cout<<"Enter c "; cin>>C; 36 | 37 | int hcf = gcd(A,B); 38 | 39 | if ( C % hcf != 0 ) 40 | { 41 | cout<<"Integral solution not possible"; 42 | return 0; 43 | } 44 | A = A/hcf; B = B/hcf; C = C/hcf; 45 | extended_Euclid(A,B); 46 | 47 | cout<<"Solution to the equation is -> x : "< 2 | using namespace std; 3 | 4 | typedef long long int ll; 5 | 6 | ll fastExpo(int x,int n) 7 | { 8 | if (n==0) return 1; 9 | if (n & 1) 10 | return fastExpo(x,n-1) * x; 11 | int y = fastExpo(x,n/2); 12 | return y*y; 13 | } 14 | 15 | int main() 16 | { 17 | int base,power; 18 | cin>>base>>power; 19 | cout< 2 | using namespace std ; 3 | 4 | int power(int x, unsigned int y, int p) 5 | { 6 | int res = 1; // Initialize result 7 | 8 | x = x % p; // Update x if it is more than or 9 | // equal to p 10 | 11 | while (y > 0) 12 | { 13 | // If y is odd, multiply x with result 14 | if (y & 1) 15 | res = (res*x) % p; 16 | 17 | // y must be even now 18 | y = y>>1; // y = y/2 19 | x = (x*x) % p; 20 | } 21 | return res; 22 | } 23 | 24 | int main() 25 | { 26 | int x = 2; 27 | int y = 5; 28 | int p = 13; 29 | cout << "Power is " << power(x, y, p); 30 | return 0; 31 | } -------------------------------------------------------------------------------- /General/Prime Factors.py: -------------------------------------------------------------------------------- 1 | # Python program to print prime factors 2 | 3 | import math 4 | 5 | # A function to print all prime factors of 6 | # a given number n 7 | def primeFactors(n): 8 | 9 | # Print the number of two's that divide n 10 | while n % 2 == 0: 11 | print 2, 12 | n = n / 2 13 | 14 | # n must be odd at this point 15 | # so a skip of 2 ( i = i + 2) can be used 16 | for i in range(3,int(math.sqrt(n))+1,2): 17 | 18 | # while i divides n , print i ad divide n 19 | while n % i== 0: 20 | print i, 21 | n = n / i 22 | 23 | # Condition if n is a prime 24 | # number greater than 2 25 | if n > 2: 26 | print n 27 | 28 | # Driver Program to test above function 29 | 30 | n = 315 31 | primeFactors(n) 32 | -------------------------------------------------------------------------------- /General/Prime.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n, i; 7 | bool isPrime = true; 8 | 9 | cout << "Enter a positive integer: "; 10 | cin >> n; 11 | 12 | for(i = 2; i <= n / 2; ++i) 13 | { 14 | if(n % i == 0) 15 | { 16 | isPrime = false; 17 | break; 18 | } 19 | } 20 | if (isPrime) 21 | cout << "This is a prime number"; 22 | else 23 | cout << "This is not a prime number"; 24 | 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /General/Segmented Sieve.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | void simpleSieve(int limit, vector &prime) 6 | { 7 | bool mark[limit+1]; 8 | memset(mark, true, sizeof(mark)); 9 | 10 | for (int p=2; p*p prime; 37 | simpleSieve(limit, prime); 38 | 39 | int low = limit; 40 | int high = 2*limit; 41 | 42 | while (low < n) 43 | { 44 | bool mark[limit+1]; 45 | memset(mark, true, sizeof(mark)); 46 | 47 | for (int i = 0; i < prime.size(); i++) 48 | { 49 | int loLim = floor(low/prime[i]) * prime[i]; 50 | if (loLim < low) 51 | loLim += prime[i]; 52 | 53 | for (int j=loLim; j= n) high = n; 66 | } 67 | } 68 | 69 | // Driver program to test above function 70 | int main() 71 | { 72 | int n = 100; 73 | cout << "Primes smaller than " << n << ":n"; 74 | segmentedSieve(n); 75 | return 0; 76 | } 77 | -------------------------------------------------------------------------------- /General/fibonacci.java: -------------------------------------------------------------------------------- 1 | package git; 2 | 3 | 4 | import java.util.*; 5 | // time complexity = O(n) 6 | // space complexity = O(n) 7 | public class fibonacci{ 8 | public static void main(String args[]) { 9 | int r=0,s=1,t; 10 | Scanner input = new Scanner(System.in); 11 | System.out.println("Enter the number of terms till which you want to find fibonacci series"); 12 | int n= input.nextInt(); //number input is taken from user 13 | 14 | System.out.print(r+" "+s); // first two numbers of the series are always printed 15 | 16 | for(int i=2;i 3 | using namespace std; 4 | 5 | typedef long long ll; 6 | typedef unsigned long long ull; 7 | typedef unsigned long long int ulli; 8 | #define flash ios_base::sync_with_stdio(false); cin.tie(NULL); 9 | #define mat(x, y, name) vector< vector > name (x, vector(y)); 10 | #define printMat(name) for (int i = 0; i < name.size(); i++) {for (int j = 0; j < res[i].size(); j++) cout << res[i][j] << " "; cout << endl;} 11 | 12 | #define MOD 98765431 13 | 14 | vector< vector > matMul(vector< vector > A, vector< vector > B) 15 | { 16 | vector< vector > C(A.size(), vector(B[0].size())); 17 | for (int i = 0; i < A.size(); i++) 18 | { 19 | for (int j = 0; j < B[0].size(); j++) 20 | { 21 | C[i][j] = 0; 22 | for (int k = 0; k < B.size(); k++) 23 | C[i][j] = (C[i][j] + ((A[i][k] * B[k][j]) % MOD)) % MOD; 24 | } 25 | } 26 | return C; 27 | } 28 | 29 | vector< vector > matPow(vector< vector > A, int p) 30 | { 31 | if (p == 1) 32 | return A; 33 | if (p&1) 34 | return matMul(A, matPow(A, p-1)); 35 | else 36 | { 37 | vector< vector > C = matPow(A, p/2); 38 | return matMul(C, C); 39 | } 40 | } 41 | 42 | int main() 43 | { 44 | flash; 45 | 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /General/palindrome.java: -------------------------------------------------------------------------------- 1 | package git; 2 | import java.util.*; 3 | 4 | // Time Complexity: O(n^3) 5 | // Space Complexity: O(n) 6 | 7 | public class palindrome { 8 | public static void main(String args[]) { 9 | int r=0,sum=0,temp; 10 | Scanner input = new Scanner(System.in); 11 | System.out.println("Enter the number you want to be checked for pallindrome"); 12 | int n = input.nextInt(); //to take the input for "n" 13 | temp=n; 14 | 15 | while(n>0) { 16 | r=n%10; // TO FIND REMAINDER 17 | sum=(sum*10)+r; 18 | n=n/10; //TO REMOVE DIGIT AT ONE PLACE IN "n" 19 | 20 | } 21 | if(temp==sum) 22 | System.out.println("the number is a PALLINDROME"); 23 | else 24 | System.out.println("the number is NOT a PALLINDROME"); 25 | 26 | 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /General/sieve of eratosthenes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | 6 | void find_primes(bool sieve[], unsigned long long int size) 7 | { 8 | // by definition 0 and 1 are not prime numbers 9 | sieve[0] = false; 10 | sieve[1] = false; 11 | 12 | // all numbers <= max are potential candidates for primes 13 | for (unsigned int i = 2; i <= size; ++i) 14 | { 15 | sieve[i] = true; 16 | } 17 | 18 | // loop through the first prime numbers < sqrt(max) (suggested by the algorithm) 19 | unsigned int first_prime = 2; 20 | for (unsigned int i = first_prime; i <= std::sqrt(double(size)); ++i) 21 | { 22 | // find multiples of primes till < max 23 | if (sieve[i] = true) 24 | { 25 | // mark as composite: i^2 + n * i 26 | for (unsigned int j = i * i; j <= size; j += i) 27 | { 28 | sieve[j] = false; 29 | } 30 | } 31 | } 32 | } 33 | void print_primes(bool sieve[], unsigned long long int size) 34 | { 35 | // all the indexes of the array marked as true are primes 36 | for (unsigned long long int i = 0; i <= size; ++i) 37 | { 38 | if (sieve[i] == true) 39 | { 40 | std::cout << i <<" "; 41 | } 42 | } 43 | } 44 | //TIME COMPLEXITY-O(nlog(log(n))) 45 | //SPACE COMPLEXITY-O(n) 46 | 47 | int main(){ 48 | unsigned long long int n; 49 | cin>>n; 50 | bool sieve[n]; 51 | find_primes(sieve,n); 52 | print_primes(sieve,n); 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /General/sorted_rotatedarray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | ///program to find the pivot element in a sorted rotated array 4 | ///time complexity= O(log(n)) 5 | ///space complexity = O(1) 6 | ///method used = BINARY SEARCH 7 | int main() 8 | 9 | { 10 | int n;int *arr; 11 | cin>>n; 12 | arr=new int[n]; //dynamic initialization of the array 13 | for(int i=0;i>arr[i]; //input for the array 15 | 16 | int s=0,e=n-1;int mid; 17 | while(s<=e) 18 | { 19 | cout<<"pivot is at index "; 20 | 21 | mid=(s+e)/2; 22 | if((arr[mid]>arr[mid+1])&&(mids)) 25 | {cout<=arr[mid])) 28 | e=mid-1; 29 | 30 | else 31 | e=mid+1; 32 | 33 | } 34 | 35 | if(s>e) 36 | cout<<"pivot does not exist"; 37 | 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /Greedy/Greedy.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Greedy { 4 | 5 | public static void ActivitySelection() { 6 | Scanner sc = new Scanner(System.in); 7 | int t = sc.nextInt(); 8 | int[][] arr; 9 | int n; 10 | 11 | class Activity { 12 | int stime; 13 | int ftime; 14 | Activity(int stime,int ftime) { 15 | this.stime = stime; 16 | this.ftime = ftime; 17 | } 18 | } 19 | 20 | class sortByftime implements Comparator { 21 | public int compare(Activity a,Activity b) { 22 | return a.ftime - b.ftime; 23 | } 24 | } 25 | 26 | Activity[] act; 27 | 28 | for(int i=0;i act[j-1].ftime) { 50 | count++; 51 | } 52 | } 53 | System.out.println(count); 54 | } 55 | 56 | } 57 | 58 | public static void Nmeetingroom() { 59 | Scanner sc = new Scanner(System.in); 60 | int t = sc.nextInt(); 61 | 62 | class Meetings { 63 | int stime; 64 | int ftime; 65 | int idx; 66 | Meetings(int stime,int ftime,int idx) { 67 | this.stime = stime; 68 | this.ftime = ftime; 69 | this.idx = idx; 70 | } 71 | } 72 | 73 | class sortByftime implements Comparator { 74 | public int compare(Meetings a,Meetings b) { 75 | return a.ftime - b.ftime; 76 | } 77 | } 78 | 79 | int n; 80 | Meetings[] meets; 81 | int[][] arr; 82 | 83 | for(int i=0;i fm.ftime) { 103 | System.out.print(meets[j].idx + " "); 104 | fm = meets[j]; 105 | } 106 | } 107 | System.out.println(); 108 | } 109 | } 110 | 111 | public static void CoinPiles() { 112 | Scanner sc = new Scanner(System.in); 113 | int t = sc.nextInt(); 114 | int n; 115 | int k; 116 | int[] arr; 117 | for(int i=0;i b) { 133 | sum += arr[j] - b; 134 | System.out.println(arr[j]-b); 135 | } 136 | } 137 | System.out.println(sum); 138 | } 139 | } 140 | 141 | public static void NotesDenomination() { 142 | Scanner sc = new Scanner(System.in); 143 | int t = sc.nextInt(); 144 | int n; 145 | int k=0; 146 | int[] arr = {1,2,5,10,20,50,100,500,1000}; 147 | for(int i=0;i0) { 151 | for(int j=0;j n) { 153 | l = arr[j-1]; 154 | k=1; 155 | break; 156 | } 157 | } 158 | int m=0; 159 | if (k==0) { 160 | l = arr[arr.length-1]; 161 | } 162 | m=n/l; 163 | n = n%l; 164 | for(int j=0;j 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | 8 | int queue[10], front, rear, ch, i; 9 | char ans; 10 | front=rear=-1; 11 | do 12 | { 13 | cout<<"Press 1 to insert"<>ch; 18 | switch(ch) 19 | { 20 | case 1: 21 | if(front==-1) 22 | { 23 | front=0; 24 | } 25 | rear=rear+1; 26 | if(rear>9) 27 | { 28 | cout<<"can not insert"<>queue[rear]; 35 | } 36 | break; 37 | case 2: 38 | if(front==-1) 39 | { 40 | cout<<"can not delete"<rear) 47 | { 48 | front=rear=-1; 49 | } 50 | } 51 | break; 52 | case 3: 53 | if(front==-1) 54 | { 55 | cout<<"can not display"<>ans; 70 | } 71 | while(ans=='y'); 72 | 73 | } 74 | -------------------------------------------------------------------------------- /Insertion_sorting.cpp: -------------------------------------------------------------------------------- 1 | //Sachin Singla 2 | 3 | #include 4 | using namespace std; 5 | 6 | int main(){ 7 | int n; //n is the number of elements entered by the user 8 | cin >> n; 9 | int arr[100]; //User must enter less than 100 elements 10 | 11 | //input n elements from the user 12 | for(int i = 0; i < n; ++i) 13 | cin >> arr[i]; 14 | 15 | //INSERTION SORT 16 | //sort all elements from [1, N-1] 17 | for(int i = 1; i < n ; ++i){ 18 | int curEle = arr[i]; 19 | int st = i - 1; //st is the start of the range towards left 20 | 21 | while(st >= 0){ 22 | if (arr[st] > curEle){ 23 | arr[st + 1] = arr[st]; //shifting 24 | --st; //move to left 25 | } 26 | 27 | else{ 28 | break; 29 | //means we have found an element smaller than curEle 30 | //which is located at st 31 | //It means the curEle must be inserted at st+1 32 | } 33 | } 34 | 35 | arr[st + 1] = curEle; 36 | } 37 | 38 | //We have thus sorted the array effectively 39 | for(int i = 0; i < n; ++i) cout << arr[i] << " "; 40 | 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /Linked_list.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | class Node{ 6 | public: 7 | int data; 8 | Node * next; 9 | 10 | Node(int d){ 11 | data = d; 12 | next = NULL; 13 | } 14 | }; 15 | 16 | Node * createLL(){ 17 | 18 | Node * head = NULL; 19 | Node * tail = NULL; 20 | int x; 21 | 22 | while(true){ 23 | cin >> x; 24 | if (x == -1) break; 25 | 26 | Node * newNode = new Node(x); //ctor auto invoked 27 | if (head == NULL){ 28 | //this means newNode is the first Node 29 | head = newNode; 30 | tail = newNode; 31 | } 32 | else { 33 | //some node(s) already exists 34 | 35 | tail->next = newNode; 36 | tail = tail->next; 37 | } 38 | } 39 | 40 | return head; 41 | } 42 | 43 | void printLL(Node * head){ 44 | Node * cur = head; 45 | while(cur != NULL){ 46 | cout << cur->data << "-->"; 47 | cur = cur->next; 48 | } 49 | cout << endl; 50 | } 51 | 52 | int main(){ 53 | Node * head = createLL(); 54 | printLL(head); 55 | } 56 | -------------------------------------------------------------------------------- /PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | Fixes # 7 | 8 | #### Checklist 9 | 10 | - [ ] I have read the [Contribution Guide] and my PR follows them. 11 | - [ ] My branch is up-to-date with the master branch. 12 | - [ ] I have added tests that prove my fix is effective or that my feature works 13 | - [ ] I have added necessary documentation (if appropriate) 14 | - [ ] The contents added are completelt original and have no copyright issues. 15 | 16 | #### Short description of what this resolves: 17 | 18 | 19 | #### Changes proposed in this pull request: 20 | 21 | - 22 | - 23 | - 24 | -------------------------------------------------------------------------------- /README 2019 Hactoberfest 2019.md: -------------------------------------------------------------------------------- 1 | This Repositery is open for developers to contribute into hacktoberfest 2019. Please visit http://iosd.tech for details of the organisation. 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Algo 2 | 3 | 4 | ## Overview: 5 | This repo is a conglomeration of algorithms for competitive programming, data structure, sorting and related areas. It currently features C/C++, Python and some Java implementations. It contains many advanced algorithms like greedy, graph traversal algorithms, including Dijkstra's algorithm and Floyd Warshal algorithm, and data structures like queues, stacks, and binary search trees. Contributions are highly prized. 6 | 7 | Use this repo to study or review your knowledge, coontributee for hacktober fest 2021 and don't forget to star and collaborate! 8 | 9 | ## Contents: 10 | 11 | ### Search Algorithms 12 | - Linear Search 13 | - binary search 14 | - Ternary search 15 | 16 | ### Sorting Algorithms 17 | 18 | - Bubble Sort 19 | - Selection Sort 20 | - Insertion sort 21 | - Merge sort 22 | - Quick sort 23 | - Radix sort 24 | - Bogo sort 25 | 26 | ### Shortest Path Algorithms 27 | 28 | - Dijkstra 29 | - Floyd Warshall 30 | 31 | ### Common Data Structures 32 | 33 | - heap 34 | - queue 35 | - stack 36 | - Array 37 | - Linked List 38 | 39 | ## Languages Used: 40 | 41 | - C++ 42 | - python 43 | - Java 44 | - C 45 | - More to come 46 | 47 | ## How to contribute: 48 | 49 | Please comment your code thoroughly as to make it possible for anyone to understand. 50 | If possible, check your code using unit tests. 51 | Avoid all the bad implementations, make your code as clean as possible. 52 | After that, find the folder that fits the category of your code and submit a PR. 53 | *Star* this repo if the information here is useful to you. 54 | 55 | ### Please have a look at these : 56 | - [CONTRIBUTING.md](https://github.com/IOSD/Algo/blob/master/CONTRIBUTING.md) for quick quidelines 57 | -------------------------------------------------------------------------------- /Search/Binary_Search.cpp: -------------------------------------------------------------------------------- 1 | //BINARY SEARCH ALGORITHM 2 | #include 3 | 4 | using namespace std; 5 | 6 | int binsearch(int a[],int n,int no) //FUNCTION FOR BINARY SEARCH TAKING ARRAY, SIZE AND NO. TO BE SEARCHED AS ARGUMENTS 7 | { 8 | int pos=-1,beg=0,last=n-1,mid; 9 | while(beg<=last) 10 | { 11 | mid=(beg+last)/2; 12 | if(a[mid]==no) 13 | { 14 | pos=mid; 15 | break; 16 | } 17 | if(a[mid]>no) 18 | last=mid-1; 19 | else 20 | beg=mid+1; 21 | } 22 | return(pos); 23 | } 24 | 25 | //TIME COMPLEXITY : O(log n) 26 | //SPACE COMPLEXITY : O(1) 27 | 28 | int main() 29 | { 30 | int *b,n,no; 31 | cout<<"Enter NO. of elements:"; 32 | cin>>n; //NO. OF ELEMENTS 33 | b=new int[n]; //DYNAMIC INITIALISATION OF ARRAY 34 | for(int i=0;i>b[i]; 36 | cout<<"\nEnter NO. to be searched:"; 37 | cin>>no; //NO. TO BE SEARCHED 38 | no=binsearch(b,n,no); //CALLING FUNCTION BINSEARCH 39 | if(no==-1) 40 | cout<<"\nNO. not found."; 41 | else 42 | cout<<"\nNO. found at position:"< 3 | using namespace std; 4 | int linsearch(int a[],int b,int c) //FUNCTION FOR LINEAR SEARCH TAKING ARRAY , SIZE, NO TO FIND AS ARGUMENTS 5 | { 6 | for(int i=0;i>n; //INPUT OF NO OF ENTRIES IN ARRAY 19 | arr=new int[n]; //DYNAMIC INITIALISATION OF ARRAY 20 | for(int i=0;i>arr[i]; //INPUT OF ARRAY 23 | } 24 | cout<<"ENTER NO TO BE SEARCHED"; 25 | cin>>k; //NO TO BE SEARCHED 26 | k=linsearch(arr,n,k); //CALLING OF FUCTION LINSEARCH 27 | if(k==-1) // IF RETURNS -1 -> NOT FOUND ELSE PRINTING POSITION 28 | cout<<"NOT FOUND"; 29 | else 30 | cout<<"POSITON : "< 2 | #include 3 | 4 | using namespace std; 5 | 6 | int TernarySearch(int L[], int left, int right, int key) 7 | { 8 | if (right - left > 0) 9 | { 10 | // calculate first pivot 11 | int midFirst = left + (right - left) / 3; 12 | 13 | // calculate second pivot 14 | int midSecond = midFirst + (right - left) / 3; 15 | 16 | // Does first pivot has the key 17 | if (L[midFirst] == key) 18 | return midFirst; 19 | 20 | // Does second pivot has the key 21 | if (L[midSecond] == key) 22 | return midSecond; 23 | 24 | // find next segment where search moves 25 | if (L[midFirst] > key) 26 | return TernarySearch(L, left, midFirst, key); 27 | 28 | if (L[midSecond] < key) 29 | return TernarySearch(L, midSecond + 1, right, key); 30 | 31 | return TernarySearch(L, midFirst, midSecond, key); 32 | } 33 | else 34 | return -1; // Not Found 35 | } 36 | 37 | int main() 38 | { 39 | int L[] = {0, 1, 2, 3, 4, 5, 8, 13, 21, 34, 55}; 40 | int left = 0; 41 | int right = sizeof(L) / sizeof(L[0]); 42 | 43 | int key; 44 | cin >> key; 45 | 46 | int x; 47 | if ((x = TernarySearch(L, left, right, key)) == -1) 48 | cout << "Key doesn't exist" << endl; 49 | else 50 | cout << "The position of Key is " << x << endl; 51 | 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /Solutions to Known Problems/CODECHEF_DIVSUBS: -------------------------------------------------------------------------------- 1 | //Divisible Subset 2 | //https://www.codechef.com/status/DIVSUBS 3 | //Divsub is a famous programming question. The idea is pigeonhole princliple. 4 | //Example: 3 4 3 5 2 3 5 | //Naive approach is by exponential time finding pairs with 1 element only then 2 element only and so on. 6 | //Any such problem can be illustrated as (1+x^3)(1+x^4)(1+x^3)(1+x^5)(1+x^2)(1+x^3) solving this will give terms having powers of all subsets we just need to apply % N = 0. 7 | //It can be solved in O(NlogN) by Fast Fourier Transform or simply in O(N^2) 8 | //https://www.youtube.com/watch?v=QQQpOa3aXew 9 | //Itterate all array elements and apply % N and record it in the array of vector below. 10 | //0 1 2 3 4 5 11 | // 0 12 | //Then 4 13 | //0 1 2 3 4 5 14 | // 1 15 | //Then in 4 to 3 so 4 + 3 % N 16 | //0 1 2 3 4 5 17 | // 0,1 0 1 18 | //and so on. 19 | //a[] = 3 4 3 5 2 3 20 | //b[] = 0 3 7 10 15 17 20 21 | //b[] = 0 3 1 4 3 5 2 22 | //temp[] = 2 6 1,4 3 5 23 | //This is pigeonhole senerio in every case any temp arr will have two element. end - start i.e. 4 - 1 = 3 so 3 elements that are 2nd 3rd and 4th (4 + 3 + 5) % 6 = 0 24 | #include 25 | using namespace std; 26 | 27 | #define MOD 1000000000 28 | typedef long long ll; 29 | typedef unsigned long long ull; 30 | 31 | int main() 32 | { 33 | ios_base::sync_with_stdio(false); 34 | cin.tie(NULL); 35 | 36 | int t; 37 | cin >> t; 38 | while(t--) 39 | { 40 | int n; 41 | cin >> n; 42 | int a[n]; 43 | for (int i = 0; i < n; i++) cin >> a[i]; 44 | 45 | ll b[n + 1]; 46 | b[0] = 0; 47 | vector temp[n]; 48 | temp[b[0] % n].push_back(0); 49 | for(int i=1; i<=n; i++) 50 | { 51 | b[i] = b[i - 1] + a[i - 1]; 52 | temp[b[i] % n].push_back(i); 53 | } 54 | ll start, end; 55 | for(int i=0; i=2 ) 58 | { 59 | start = temp[i][0]; 60 | end = temp[i][1]; 61 | } 62 | } 63 | cout << (end - start) << endl; 64 | for(int i = start + 1; i <= end; i++) 65 | cout << i << " "; 66 | 67 | cout << endl; 68 | } 69 | return 0; 70 | } 71 | -------------------------------------------------------------------------------- /Solutions to Known Problems/SPOJ_FAVDICE.cpp: -------------------------------------------------------------------------------- 1 | //Favourite Dice 2 | //https://www.spoj.com/problems/FAVDICE/ 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | ios_base::sync_with_stdio(false); 9 | cin.tie(NULL); 10 | int t; 11 | cin >> t; 12 | while(t--) 13 | { 14 | double n; 15 | cin >> n; 16 | double ans = 0; 17 | for (int i = 1; i <= n; i++) ans += (double)1/i; 18 | ans *= n; 19 | cout << ans << endl; 20 | } 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /Solutions to Known Problems/SPOJ_FIBOSUM.cpp: -------------------------------------------------------------------------------- 1 | //Fibonacci Sum 2 | //https://www.spoj.com/problems/FIBOSUM/ 3 | //This question wants the user to calculate Fibonacci with in a range. A naive approach will be to simply use the 4 | //relation F(N) = F(N - 1) + F(N - 2) to find the nth fibonacci and the itterate over the range. A better approach will be to derrive 5 | //a recurence relation of the fibonacci series. Refer this link for mathematics behind it https://www.youtube.com/watch?v=WT_TGxQrV1k&t=214s 6 | //Even now itterating to find the sum for fibbonaci will give us TLE because of large constraints. 7 | //So there's an observation to get TLE fixed. 1, 1, 2, 3, 5, 8, 13, 21, 34. The observation is Sum till Nth fibonacci is F(n+2) - 1 8 | //This observation is true throughout. Now calculating sum within range from n to m will be sum till m minus sum till n 9 | 10 | #include 11 | using namespace std; 12 | 13 | typedef long long int lli; 14 | #define mat(x, y, name) vector< vector > name (x, vector(y)); 15 | 16 | lli MOD = 1000000007; 17 | 18 | vector< vector > matMul(vector< vector > A, vector< vector > B) 19 | { 20 | vector< vector > C(A.size(), vector(B[0].size())); 21 | for (int i = 0; i < A.size(); i++) 22 | { 23 | for (int j = 0; j < B[0].size(); j++) 24 | { 25 | C[i][j] = 0; 26 | for (int k = 0; k < B.size(); k++) 27 | C[i][j] = (C[i][j] + ((A[i][k] * B[k][j]) % MOD)) % MOD; 28 | } 29 | } 30 | return C; 31 | } 32 | 33 | vector< vector > matPow(vector< vector > A, int p) 34 | { 35 | if (p == 1) 36 | return A; 37 | if (p&1) 38 | return matMul(A, matPow(A, p-1)); 39 | else 40 | { 41 | vector< vector > C = matPow(A, p/2); 42 | return matMul(C, C); 43 | } 44 | } 45 | 46 | int main() 47 | { 48 | ios_base::sync_with_stdio(false); 49 | cin.tie(NULL); 50 | 51 | mat(2, 1, F); 52 | mat(2, 2, T); 53 | T[0][0] = 0; 54 | T[0][1] = 1; 55 | T[1][0] = 1; 56 | T[1][1] = 1; 57 | F[0][0] = 1; 58 | F[1][0] = 1; 59 | int t; 60 | cin >> t; 61 | while(t--) 62 | { 63 | lli n, m; 64 | cin >> n >> m; 65 | lli minSum = (n == 0) ? 0 : ((matMul(matPow(T, n), F)[0][0]) - 1) % MOD; 66 | lli maxSum = (m == 0) ? 0 : ((matMul(matPow(T, m+1), F)[0][0]) - 1) % MOD; 67 | lli ans = (maxSum - minSum) % MOD; 68 | if (ans < 0) 69 | { 70 | ans += MOD; 71 | ans = ans % MOD; 72 | } 73 | cout << ans << endl; 74 | } 75 | return 0; 76 | } 77 | -------------------------------------------------------------------------------- /Solutions to Known Problems/between two sets.cpp: -------------------------------------------------------------------------------- 1 | 2 | //https://www.hackerrank.com/challenges/between-two-sets/problem 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | using namespace std; 10 | 11 | 12 | int main() { 13 | int n,m,count=0,flag=0; 14 | int arr1[10],arr2[10]; 15 | cin>>n; 16 | cin>>m; 17 | for(int i=0;i>arr1[i]; 20 | } 21 | for(int i=0;i>arr2[i]; 24 | } 25 | int max=arr1[0]; 26 | int min=arr2[0]; 27 | for(int i=0;imax) 30 | max=arr1[i]; 31 | } 32 | for(int i=0;i 4 | #include 5 | #include 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | 11 | int main() { 12 | int q; 13 | int arr[100][3]; 14 | cin>>q; 15 | for(int i=0;i>arr[i][j]; 20 | } 21 | } 22 | for(int i=0;iabs(arr[i][1]-arr[i][2])) 25 | cout<<"Cat B\n"; 26 | else if(abs(arr[i][0]-arr[i][2]) 2 | #include 3 | //https://www.hackerrank.com/challenges/electronics-shop/problem 4 | 5 | #include 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | 11 | int main() { 12 | long int s,n,m,arrn[100000],arrm[100000]; 13 | long int ans=-1; 14 | cin>>s; 15 | cin>>n; 16 | cin>>m; 17 | long int i=0; 18 | for(;i>arrn[i]; 21 | } 22 | long int j=0; 23 | for(;j>arrm[j]; 26 | } 27 | long int k=0; 28 | long int l=0; 29 | for(;kans&&(arrn[k]+arrm[l])<=s) 34 | ans=arrn[k]+arrm[l]; 35 | } 36 | } 37 | cout< 4 | #include 5 | #include 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | int main() { 11 | int arr[100],total,count=0; 12 | cin>>total; 13 | for(int i=0;i>arr[i]; 15 | for(int j=0;j 3 | using namespace std; 4 | 5 | void bsort(int a[],int n) 6 | int t; 7 | for(int i=1;i>n; //NO. OF ELEMENTS 25 | b=new int[n]; //DYNAMIC INITIALISATION OF ARRAY 26 | cout<<"\nEnter the array:"; 27 | for(int i=0;i>b[i]; 29 | bsort(b,n); //CALLING FUNCTION SSORT 30 | cout<<"\nSorted Array:"; 31 | for(int i=0;i 3 | using namespace std; 4 | 5 | // To heapify a subtree rooted with node i which is 6 | // an index in arr[]. n is size of heap 7 | void heapify(int arr[], int n, int i) 8 | { 9 | int largest = i; // Initialize largest as root 10 | int l = 2*i + 1; // left = 2*i + 1 11 | int r = 2*i + 2; // right = 2*i + 2 12 | 13 | // If left child is larger than root 14 | if (l < n && arr[l] > arr[largest]) 15 | largest = l; 16 | 17 | // If right child is larger than largest so far 18 | if (r < n && arr[r] > arr[largest]) 19 | largest = r; 20 | 21 | // If largest is not root 22 | if (largest != i) 23 | { 24 | swap(arr[i], arr[largest]); 25 | 26 | // Recursively heapify the affected sub-tree 27 | heapify(arr, n, largest); 28 | } 29 | } 30 | 31 | // main function to do heap sort 32 | void heapSort(int arr[], int n) 33 | { 34 | // Build heap (rearrange array) 35 | for (int i = n / 2 - 1; i >= 0; i--) 36 | heapify(arr, n, i); 37 | 38 | // One by one extract an element from heap 39 | for (int i=n-1; i>=0; i--) 40 | { 41 | // Move current root to end 42 | swap(arr[0], arr[i]); 43 | 44 | // call max heapify on the reduced heap 45 | heapify(arr, i, 0); 46 | } 47 | } 48 | 49 | /* A utility function to print array of size n */ 50 | void printArray(int arr[], int n) 51 | { 52 | for (int i=0; i 2 | using namespace std; 3 | ///program to sort an array using insertion sort recursively 4 | ///time complexity= O(n) 5 | ///space complexity = O(1) extra space 6 | 7 | // Recursive function to sort an array using 8 | // insertion sort 9 | void insertionSortRecursive(int arr[], int n) 10 | { 11 | // Base case 12 | if (n <= 1) 13 | return; 14 | 15 | // Sort first n-1 elements 16 | insertionSortRecursive( arr, n-1 ); 17 | 18 | // Insert last element at its correct position 19 | // in sorted array. 20 | int last = arr[n-1]; 21 | int j = n-2; 22 | 23 | /* Move elements of arr[0..i-1], that are 24 | greater than key, to one position ahead 25 | of their current position */ 26 | while (j >= 0 && arr[j] > last) 27 | { 28 | arr[j+1] = arr[j]; 29 | j--; 30 | } 31 | arr[j+1] = last; 32 | } 33 | int main() 34 | 35 | { 36 | int *arr;int n; 37 | cin>>n; 38 | arr=new int[n]; ///dynamic initialization of array 39 | for(int j=0;j>arr[j]; 41 | 42 | insertionSortRecursive(arr, n); 43 | for(int i=0;i arr[j + 1]: 6 | arr[j], arr[j + 1] = arr[j + 1], arr[j] 7 | -------------------------------------------------------------------------------- /Sorting/bubblesort_recursion.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void bubbleSort(int arr[], int n) 4 | { 5 | // Base case 6 | if (n == 1) 7 | return; 8 | 9 | // One pass of bubble sort. After 10 | // this pass, the largest element 11 | // is moved (or bubbled) to end. 12 | for (int i=0; i arr[i+1]) 14 | swap(arr[i], arr[i+1]); 15 | 16 | // Largest element is fixed, 17 | // recur for remaining array 18 | bubbleSort(arr, n-1); 19 | } 20 | int main() 21 | 22 | { 23 | int n;int *arr; 24 | cin>>n; 25 | arr=new int[n]; //dynamic initialization of the array 26 | for(int i=0;i>arr[i]; 28 | bubbleSort(arr,n); 29 | printf("Sorted array : \n"); 30 | for(int j=0;j 3 | #include //ADDING CLIMITS TO GET INT_MIN VALUE 4 | using namespace std; 5 | 6 | void inssort(int a[],int n) //FUNCTION INSERTION SORT TAKING ARGUMENTS ARRAY & SIZE - N 7 | { int i,j; 8 | a[0]=INT_MIN; //GIVING FIRST ELEMENT OF ARRAY MINIMUM VALUE 9 | for(i=1;i<=n;i++) 10 | { 11 | int t=a[i]; 12 | j=i-1; 13 | while(t>n; // TAKING INPUT OF SIZE OF ARRAY 30 | a=new int[n+1]; 31 | for(int i=1;i<=n;i++) //INPUT OF ARRAY 32 | { 33 | cin>>a[i]; 34 | } 35 | inssort(a,n); //CALLING INSERTION SORT FUNCTION 36 | cout< 2 | using namespace std; 3 | ///program to merge two arrays 4 | ///time complexity= O(n) 5 | ///space complexity = O(1) extra space 6 | 7 | 8 | /* Merges array N[] of size n into array mPlusN[] 9 | of size m+n*/ 10 | int merge(int mPlusN[], int N[], int m, int n) 11 | { 12 | int i = n; /* Current index of i/p part of mPlusN[]*/ 13 | int j = 0; /* Current index of N[]*/ 14 | int k = 0; /* Current index of of output mPlusN[]*/ 15 | while (k < (m+n)) 16 | { 17 | /* Take an element from mPlusN[] if 18 | a) value of the picked element is smaller and we have 19 | not reached end of it 20 | b) We have reached end of N[] */ 21 | if ((i < (m+n) && mPlusN[i] <= N[j]) || (j == n)) 22 | { 23 | mPlusN[k] = mPlusN[i]; 24 | k++; 25 | i++; 26 | } 27 | else // Otherwise take element from N[] 28 | { 29 | mPlusN[k] = N[j]; 30 | k++; 31 | j++; 32 | } 33 | } 34 | } 35 | int main() 36 | 37 | { 38 | /* Initialize arrays */ 39 | int mPlusN[] = {2, 8,NA,NA,NA, 13,NA, 15, 20}; 40 | int N[] = {5, 7, 9, 25}; 41 | int n = sizeof(N)/sizeof(N[0]); 42 | int m = sizeof(mPlusN)/sizeof(mPlusN[0]) - n; 43 | 44 | 45 | /*Merge N[] into mPlusN[] */ 46 | merge(mPlusN, N, m, n); 47 | 48 | /* Print the resultant mPlusN */ 49 | 50 | for(int i=0;i<(m+n);i++) 51 | cout< 3 | using namespace std; 4 | void selsort(int a[],int n) //SELSORT TO ARRANGE INPUT OF ARRAY IN ASCENDING 5 | { for(int i=0;ia[j]) 8 | { //SWAPPING OF VALUES 9 | a[i]=a[i]+a[j]; 10 | a[j]=a[i]-a[j]; 11 | a[i]=a[i]-a[j]; 12 | } 13 | } 14 | } 15 | } 16 | void merge_sort(int a[],int b[],int c[],int n1,int n2,int ch)//MERGE SORT TAKING ARGUMENT OF 3 ARRAY SIZE OF A & B AND CHOICE, 17 | { int i,j,k; 18 | if(ch==1) //CHECKING ASCENDING OR DESCENDING 19 | { for(i=0,j=0,k=0;(k<(n1+n2))&&(i-1)&&(j>-1);k++) 46 | { if(a[i]>n1; 77 | a=new int[n1]; 78 | for(int i=0;i>a[i]; 81 | } 82 | selsort(a,n1); //SORTING OF ARRAY 1 83 | 84 | cout<<"\n\n"; 85 | cout<<"Enter units in 2st array :"; 86 | cin>>n2; 87 | b=new int[n2]; 88 | for(int i=0;i>b[i]; 91 | } 92 | selsort(b,n2); //SORTING OF ARRAY 2 93 | 94 | c=new int[(n1+n2)]; //DYNAMIC INIT. OF ARRAY 3 95 | cout<<"Enter Option 1-Ascending 2-Descending"; 96 | cin>>ch; //INPUT OF CHOICE 97 | merge_sort(a,b,c,n1,n2,ch); //CALLING OF merge)_sort 98 | for(int i=0;i<(n1+n2);i++) 99 | { 100 | cout<= high) 23 | return; 24 | 25 | int left = low; 26 | int right = high; 27 | int mid = (left + high) / 2; 28 | int pivot = a[mid]; 29 | while (left <= right) { 30 | while (a[left] < pivot) { 31 | left++; 32 | } 33 | 34 | while (a[right] > pivot) { 35 | right--; 36 | } 37 | 38 | if (left <= right) { 39 | int temp = a[right]; 40 | a[right] = a[left]; 41 | a[left] = temp; 42 | } 43 | 44 | left++; 45 | right--; 46 | } 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /Sorting/selection_sort.cpp: -------------------------------------------------------------------------------- 1 | //Selection Sort 2 | // Time Complexity: O(n^2) 3 | // Space Complexity: O(1) 4 | 5 | #include 6 | using namespace std; 7 | 8 | void selectsort(int p[], int size) 9 | { //function for selection sort, taking array and its size as arguments 10 | int min,pos,temp; 11 | for(int t=0; t<(size-1); t++) 12 | { min=p[t]; 13 | pos=t; 14 | 15 | for( int j=t+1; j>n; //no. of elements in array user want to enter 36 | cout<<"\nEnter the elements:\n"; 37 | for( i=0; i>m[i]; //taking number as input from user 40 | } 41 | 42 | selectsort(m,n); //call selectsort function 43 | cout<<"\nSorted Array:\n"; 44 | for( i=0; i 2 | using namespace std; 3 | 4 | ///Coin Change Problem 5 | ///Top Down DP 6 | int dp[100] = {0}; 7 | int coinWaysTD(int amt,int coins[],int n){ 8 | if(amt==0){ 9 | dp[0] = 1; 10 | return 1; 11 | } 12 | ///Recursive Case 13 | int ans = 0; 14 | 15 | if(dp[amt]!=0){ 16 | return dp[amt]; 17 | } 18 | for(int i=0;i=0){ 20 | ans += coinWaysTD(amt-coins[i],coins,n); 21 | } 22 | } 23 | ///Store and return for the first time 24 | dp[amt] = ans; 25 | return ans; 26 | } 27 | 28 | ///Bottom Up DP 29 | int coinWaysBU(int amt,int coins[],int n){ 30 | int dp[100] = {0}; 31 | dp[0] = 1; 32 | 33 | for(int i=1;i<=amt;i++){ 34 | for(int j=0;j=0){ 36 | dp[i] += dp[i-coins[j]]; 37 | } 38 | } 39 | } 40 | return dp[amt]; 41 | } 42 | 43 | 44 | int main(){ 45 | 46 | int coins[] = {1,2,3,8}; 47 | int amount = 3; 48 | cout< 3 | #define mp pair 4 | using namespace std; 5 | 6 | int debugg=0; 7 | class Node{ 8 | public: 9 | int dist; 10 | vector > next;//first contains city index .. second contains distance 11 | 12 | void clear(){ 13 | dist=INT_MAX; 14 | next.clear(); 15 | } 16 | } node[100002]; 17 | 18 | struct priority_fxn{ 19 | bool operator() (int a,int b){ 20 | return node[a].dist > node[b].dist; 21 | } 22 | }; 23 | void dijakstra(int source){ 24 | int n,d,temp; 25 | priority_queue,priority_fxn> q; 26 | 27 | //init queue 28 | node[source].dist=0; 29 | q.push(source); 30 | 31 | while(!q.empty()){ 32 | temp=q.top(); 33 | for(auto elem : node[temp].next){ 34 | n=elem.first; 35 | d=elem.second; 36 | if(node[n].dist > node[temp].dist + d){ 37 | node[n].dist = node[temp].dist + d; 38 | q.push(n); 39 | } 40 | } 41 | q.pop(); 42 | } 43 | } 44 | 45 | int main(){ 46 | int t,a,b,c,n,p; 47 | cin>>t; 48 | while(t--){ 49 | cin>>n>>p; 50 | for(int i=1;i<=n;i++) 51 | node[i].clear(); 52 | while(p--){ 53 | cin>>a>>b>>c; 54 | node[a].next.push_back(mp(b,c)); 55 | node[b].next.push_back(mp(a,c)); 56 | } 57 | dijakstra(1); 58 | if(node[n].dist==INT_MAX)cout<<"NONE"< 3 | using namespace std; 4 | 5 | long long int FastExpo(int b, int p) 6 | { 7 | /if the power is 0 return 1 8 | if(!p) 9 | { 10 | return 1; 11 | } 12 | 13 | /if power is odd, then power is reduce by 1 to make odd and base is multiplied seprately 14 | if(p%2!=0) 15 | { 16 | return FastExpo(b,p-1)*b; 17 | } 18 | 19 | int res=FastExpo(b,p/2); 20 | return res*res; 21 | } 22 | 23 | int main() 24 | { 25 | int base,power; 26 | cin>>base>>power; 27 | 28 | cout< 0) { 12 | int n = s.nextInt(); 13 | int[] a = new int[n]; 14 | int[] b = new int[n]; 15 | for (int i = 0; i < n; i++) { 16 | a[i] = s.nextInt(); 17 | } 18 | for (int i = 0; i < n; i++) { 19 | int temp = s.nextInt(); 20 | b[i] = temp - a[i]; 21 | if (b[i] < 0) 22 | temp2 = false; 23 | } 24 | 25 | 26 | // if(n==2){ 27 | // 28 | // } 29 | // else if(n==1){ 30 | // 31 | // } 32 | 33 | if(n==1 || n==2 ) 34 | { 35 | boolean temp3 = true; 36 | for(int i =0;i 1) 23 | ++cnt; 24 | 25 | return cnt == 2 ? 1 : 0; 26 | } 27 | } 28 | 29 | static int semiprime(int n) { 30 | if (checkSemiprime(n) != 0) 31 | return 1; 32 | else 33 | return 0; 34 | } 35 | 36 | public static void main(String[] args) { 37 | 38 | Scanner s = new Scanner(System.in); 39 | int t = s.nextInt(); 40 | while (t-- > 0) { 41 | int n = s.nextInt(); 42 | 43 | int i = 0; 44 | int j = n; 45 | int ans = 0; 46 | while (i <= n / 2) { 47 | int x = semiprime(i); 48 | int y = semiprime(j); 49 | // System.out.println(x + " " + y); 50 | 51 | if (x == 1 && y == 1) { 52 | System.out.println("YES"); 53 | ans = 1; 54 | break; 55 | } 56 | i++; 57 | j--; 58 | 59 | } 60 | if (ans == 0) { 61 | System.out.println("NO"); 62 | } 63 | } 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /snackdown2019-OnlineQualifier/FidingTeammates.md: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Collections; 3 | import java.util.HashMap; 4 | import java.util.Scanner; 5 | import java.util.Set; 6 | 7 | class q5 { 8 | public static int h = 1000000007; 9 | 10 | public static void main(String[] args) { 11 | // TODO Auto-generated method stub 12 | Scanner s = new Scanner(System.in); 13 | int t = s.nextInt(); 14 | while (t-- > 0) { 15 | int n = s.nextInt(); 16 | 17 | HashMap abc = new HashMap(); 18 | long arr[] = new long[n + 1]; 19 | arr[2] = 1; 20 | for (int i = 4; i <= n; i = i + 2) { 21 | arr[i] =( ((i - 1)%h) * (arr[i - 2]%h))%h; 22 | } 23 | for (int i = 0; i < n; i++) { 24 | int c = s.nextInt(); 25 | if (!abc.containsKey(c)) { 26 | abc.put(c, (long)1); 27 | } else { 28 | abc.put(c, abc.get(c) + 1); 29 | } 30 | 31 | } 32 | 33 | Set res = abc.keySet(); 34 | 35 | long ans = 1; 36 | ArrayList a = new ArrayList<>(); 37 | for (int values : res) { 38 | a.add(values); 39 | } 40 | 41 | Collections.sort(a,Collections.reverseOrder()); 42 | 43 | for (int i = 0; i < a.size(); i++) { 44 | 45 | if (abc.get(a.get(i)) % 2 == 0) { 46 | ans = ((ans%h) * (arr[(int)(abc.get(a.get(i))+0)]%h))%h; 47 | ans=ans%h; 48 | } else { 49 | ans = (((ans%h) * ((arr[(int)(abc.get(a.get(i)) + 1)])%h)%h) * (abc.get(a.get(i + 1))%h))%h; 50 | abc.put(a.get(i + 1), abc.get(a.get(i + 1)) - 1); 51 | if (abc.get(a.get(i + 1)) == 0) { 52 | abc.remove(a.get(i + 1)); 53 | a.remove(i + 1); 54 | } 55 | ans = ans % h; 56 | } 57 | } 58 | ans = ans % h; 59 | System.out.println(ans%h); 60 | 61 | } 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /snackdown2019-OnlineQualifier/Qualifying to Pre-Elimination.md: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Scanner; 3 | 4 | class pre_elim { 5 | 6 | public static void main(String[] args) { 7 | // TODO Auto-generated method stub 8 | 9 | Scanner s = new Scanner(System.in); 10 | int t = s.nextInt(); 11 | while (t-- > 0) { 12 | int n = s.nextInt(); 13 | int k = s.nextInt(); 14 | int[] a = new int[n]; 15 | for (int i = 0; i < n; i++) { 16 | int x = s.nextInt(); 17 | a[i] = -x; 18 | } 19 | Arrays.sort(a); 20 | for (int i = 0; i < n; i++){ 21 | a[i] = -a[i]; 22 | } 23 | int c = 0; 24 | for (int i = 0; i < n; i++) { 25 | if (a[i] >= a[k-1]) { 26 | c++; 27 | } 28 | } 29 | System.out.println(c); 30 | } 31 | 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /snackdown2019-OnlineQualifier/Spread the Word.md: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | class spreadword2 { 4 | public static void main(String[] args) { 5 | // TODO Auto-generated method stub 6 | Scanner s = new Scanner(System.in); 7 | int t = s.nextInt(); 8 | while (t-- > 0) { 9 | int n = s.nextInt(); 10 | long[] a = new long[n+1]; 11 | a[0] = 0; 12 | for (int i = 1; i <= n; i++) { 13 | int temp = s.nextInt(); 14 | a[i] = a[i-1] + temp; 15 | } 16 | int i=1 , ans=0; 17 | long k=1; 18 | while(k 4 | #define dout if(debugg) cout<<" " 5 | using namespace std; 6 | 7 | int debugg = 1; 8 | class Node{ 9 | public: 10 | vector adj; 11 | int visited; 12 | 13 | Node(){ 14 | clear(); 15 | } 16 | void clear(){ 17 | visited = 0; 18 | adj.clear(); 19 | } 20 | }; 21 | 22 | void dfs_rec(vector &node,int a){ 23 | cout< &node,int a){ 32 | for(auto &i : node){ 33 | i.visited=0; 34 | } 35 | 36 | node[a].visited=1; 37 | dfs_rec(node,a); 38 | 39 | cout< &node,int a){ 43 | for(auto &i : node) 44 | i.visited=0; 45 | 46 | queue q; 47 | q.push(a); 48 | node[a].visited=1; 49 | 50 | while(!q.empty()){ 51 | int temp = q.front(); 52 | for(auto i : node[temp].adj){ 53 | if(node[i].visited==0){ 54 | node[i].visited=1; 55 | q.push(i); 56 | } 57 | } 58 | q.pop(); 59 | cout<>t; 67 | for(int x=1; x<=t; x++){ 68 | int n; 69 | cin>>n; 70 | vector node(n+1); 71 | 72 | for(int i=1; i<=n; i++){//insert adj nodes 73 | int m,faltu; 74 | cin>>faltu>>m; 75 | while(m--){ 76 | cin>>temp; 77 | node[i].adj.push_back(temp); 78 | } 79 | } 80 | 81 | cout<<"graph "<>a>>type; 85 | if(a==0)break; 86 | 87 | if(type) 88 | bfs(node,a); 89 | else 90 | dfs(node,a); 91 | } 92 | } 93 | } 94 | --------------------------------------------------------------------------------