├── .DS_Store ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── CONTRIBUTORS.md ├── Competitive Coding ├── Backtrack │ ├── Sudoku.cpp │ └── nQueen.cpp ├── Bitwise Operations │ ├── .DS_Store │ ├── Count_One │ │ ├── count_one.cpp │ │ └── readme.md │ ├── Largest_power_of_2 │ │ ├── Largest_power_2.cpp │ │ └── readme.md │ ├── Power_of_Two │ │ ├── power_of_two.cpp │ │ └── readme.md │ ├── ith_bit_set │ │ ├── ith_bit_set.cpp │ │ └── readme.md │ └── readme.md ├── Data Structures │ ├── Queue │ │ ├── queue.class │ │ └── queue.java │ └── Stack │ │ ├── stack.class │ │ └── stack.java ├── Dynamic Programming │ ├── 0-1Knapsack │ │ ├── knapsack.java │ │ └── readme.md │ ├── Coin Change │ │ ├── Coin Change Readme.md │ │ └── Coin Change.cpp │ ├── Edit Distance │ │ ├── CODECHEF_seatsr.cpp │ │ ├── SPOJ_edist.cpp │ │ └── readme.md │ ├── Longest Common Subsequence │ │ └── lcs.cpp │ ├── Longest Increasing Subsequence │ │ ├── lis_n_log_n.cpp │ │ └── lis_n_squared_sol.cpp │ ├── Maximum Subarray Sum │ │ ├── Maximum Subarray Sum Readme.md │ │ └── Maximum Subarray Sum.cpp │ ├── Maximum Sum Increasing Subsequence │ │ ├── Maximum_sum_increasing_subsequence.cpp │ │ └── Maximum_sum_increasing_subsequence.md │ ├── cutRod │ │ ├── Readme.md │ │ └── cutRod.c │ ├── minCostPath │ │ ├── Readme.md │ │ └── minCostPath.cpp │ ├── subsetSum │ │ ├── Readme.md │ │ └── subsetSum.cpp │ └── uglyNumbers │ │ ├── Readme.md │ │ └── uglyNumbers.cpp ├── Geometry │ └── Convex hull │ │ ├── convex hull jarvis march.cpp │ │ └── readme.md ├── Graphs │ ├── Detecting cycles │ │ ├── detecting-cycles.cpp │ │ └── detecting-cycles_readme.md │ ├── Graph_Search │ │ ├── BreadthFirstSearch │ │ │ ├── Breadth_First_Search.cpp │ │ │ └── README.md │ │ └── DepthFIrstSearch │ │ │ ├── Depth_First_Search.cpp │ │ │ └── README.md │ ├── Shortest Path │ │ ├── Bellman Ford │ │ │ ├── Bellman_Ford.cpp │ │ │ └── readme.md │ │ ├── Floyd Warshall │ │ │ ├── Floyd_Warshall.cpp │ │ │ └── README.md │ │ └── dijsktra │ │ │ ├── README.md │ │ │ └── dijsktra_implementation.cpp │ └── Topological Sort │ │ ├── readme.md │ │ └── topological.cpp ├── Greedy │ ├── Huffman Coding │ │ ├── Huffman_Coding.py │ │ └── Readme.md │ └── Knapsack │ │ ├── README.md │ │ └── knapsack.cpp ├── Linked List │ ├── Linked_Lists_based_on_Arrays │ │ ├── LInked_List_Operations_[Array].cpp │ │ └── README.md │ └── Linked_Lists_based_on_POINTERS │ │ ├── Linked_List_operation.cpp │ │ ├── README.md │ │ └── Removing_duplicates_from_Linked_List.cpp ├── Math │ ├── Catalan_Numbers │ │ ├── README.md │ │ ├── catalan_binomial.py │ │ └── catalan_recursive.py │ ├── Chinese Remainder Theorem │ │ ├── Modular multiplicative inverse.md │ │ ├── README.md │ │ ├── code.cpp │ │ └── code_MMI.cpp │ ├── FFT │ │ ├── FastFourierTransform.cpp │ │ └── README.md │ ├── LuckyNumber │ │ ├── README.md │ │ └── code.cpp │ ├── Primality Test │ │ ├── Fermat Method │ │ │ ├── README.md │ │ │ └── SrcCode.cpp │ │ └── Optimized School Method │ │ │ ├── README.md │ │ │ └── SrcCode.cpp │ ├── Project_Euler │ │ ├── Problem_21 │ │ │ ├── P21.class │ │ │ ├── P21.java │ │ │ └── README.md │ │ ├── README.md │ │ ├── amicable_pair(prob 21).java │ │ ├── fractal.py │ │ ├── p21.class │ │ └── sum_of_divisors.py │ ├── SieveOfEratosthenes │ │ ├── SieveOfEratosthenes.md │ │ └── Sieve_Of_Eratosthenes.cpp │ ├── checkOverflow │ │ ├── README.md │ │ └── checkOverflow.cpp │ └── kthPrimeFactor │ │ ├── README.md │ │ └── kthPrimeFactor.cpp ├── Search │ ├── Binary Search │ │ └── Binary_Search.c │ ├── Interpolation Search │ │ └── interpolation_search.c │ ├── Linear Search │ │ └── linear_search.c │ └── README.md ├── Sorting │ ├── Bubble Sort │ │ ├── bubble_sort.c │ │ └── bubble_sort.cpp │ ├── Counting_Sort │ │ └── counting_sort.cpp │ ├── Heap Sort │ │ ├── HeapSort.cpp │ │ ├── Readme.md │ │ └── Sorting_heapsort_anim.gif │ ├── Insertion_Sort │ │ └── insertion_sort.c │ ├── Merge_Sort │ │ └── Merge_Sort.c │ ├── Quick_Sort │ │ └── Quick_Sort.c │ ├── README.md │ ├── Radix_Sort │ │ └── Radix_sorting.cpp │ ├── Selection_Sort │ │ └── selection_sort.c │ └── Shell_Sort │ │ └── shellsort.py ├── Strings │ └── String Search │ │ ├── Knuth-Morris-Pratt_Algorithm.cpp │ │ ├── Manachar_algorithm │ │ ├── manachar_algorithm.py │ │ └── manchar_algorithm.md │ │ ├── Z-algorithm │ │ ├── Readme.md │ │ └── z-algorithm.cpp │ │ └── boyer_moore_algo └── Tree │ ├── Binary Indexed Tree │ ├── Reference.txt │ ├── SPOJ_ctrick.cpp │ ├── SPOJ_invcnt.cpp │ ├── binary_indexed_tree.cpp │ └── range_query_range_update │ │ └── SPOJ_horrible.cpp │ ├── Binary Tree │ ├── Lowest_common_ancestor │ │ ├── Readme.md │ │ └── lowest_common_ancestor.cpp │ ├── inorder_traversal │ │ ├── Readme.md │ │ └── inorder_traversal.cpp │ ├── level_order_traversal.c │ ├── postorder_traversal │ │ ├── postorder_traversal.cpp │ │ └── readme.md │ ├── preorder_traversal │ │ ├── preorder_traversal.cpp │ │ └── readme.md │ └── segment-trees │ │ ├── segment-trees.cpp │ │ └── segment-trees_readme.md │ └── Minimum Spanning Tree │ ├── Kruskal │ └── KruskalMST.cpp │ ├── Prims │ └── Prims.cpp │ └── readme.md ├── GFG Articles └── prateekiiest │ └── article.md ├── Graphics Algos ├── Car Animation │ ├── README.md │ └── car.c ├── README.md └── robo.c ├── ISSUE_TEMPLATE.md ├── LICENSE ├── Machine learning ├── gradient descent │ ├── LinearReg.m │ ├── README.md │ └── gradient.png ├── EXPONENTIAL REGRESSION ├── LINEAR REGRESSION └── polynomial regression ├── PULL_REQUEST_TEMPLATE.md ├── README.md ├── Security Algorithms └── Cryptography │ ├── Atbash_Cipher │ ├── Atbash_Cipher.cpp │ └── README.md │ ├── MorseCode │ ├── REAdME.md │ ├── morseCode_decoder.cpp │ ├── morseCode_generator.cpp │ └── morse_decoder_output.png │ └── RSA Algortihm │ ├── CaesarCipher │ └── Python │ │ └── Caesarcipher.py │ ├── README.md │ └── rsa.py ├── _config.yml ├── algocodeiiest.jpg └── test.md /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codeIIEST/Algorithms/85e3fee94db88b644a102898f889c97083191d35/.DS_Store -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .sass-cache/ 2 | _site/ 3 | 4 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at codeiiest@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution guidelines 2 | 3 | First of all, thanks for thinking of contributing to this project. :smile: 4 | 5 | Before sending a Pull Request, please make sure that you're assigned the task on a GitHub issue. 6 | 7 | - If a relevant issue already exists, discuss on the issue and get it assigned to yourself on GitHub. 8 | - If no relevant issue exists, open a new issue and get it assigned to yourself on GitHub. 9 | 10 | Please proceed with a Pull Request only after you're assigned. It'd be sad if your Pull Request (and your hardwork) isn't accepted just because it isn't ideologically compatible. 11 | 12 | While making a Pull Request, please take care of the following rules: 13 | 14 | - Make sure the master branch of your forked repo is not any commits ahead than the original master repository. 15 | - Create a new branch from master in the forked repository. Updated your changes in that branch and not in master. 16 | - Include only one algorithm in each pull request. A PR containing more than one algorithm *will not be merged*. 17 | - Write your algorithm in a language other coders are mostly acquainted with i.e. `C`/`C++`/`Python`/`Java`. Any 18 | other language will be accepted only after discussion with the maintainers. 19 | - When writing the algorithm's code, please include a small `readme.md` file in the folder briefly explaining the 20 | algorithm. Make sure your `readme.md` provides a clear understanding of the algorithm to a new-comer. Explanation 21 | should be given in not more than 300 characters 22 | - Write the name of the algorithm you added and the language you used in the title while making the PR. 23 | -------------------------------------------------------------------------------- /CONTRIBUTORS.md: -------------------------------------------------------------------------------- 1 | ### List of Contributors 2 | 3 | #### KWOC 4 | 5 | Thanks for all your contributions :heart: :octocat: 6 | 7 | 8 | [prateekiiest](https://github.com/prateekiiest) : KWOC Mentor 9 | 10 | 11 | | Github username | Pull Request | Status | 12 | | ------------- |:-------------:| -----:| 13 | |[Ankitr19](https://github.com/Ankitr19)| [#203](https://github.com/codeIIEST/Algorithms/pull/203) |OPEN| 14 | |[Rahul Arulkumaran](https://github.com/rahulkumaran)| [#46](https://github.com/codeIIEST/Algorithms/pull/46), [#66](https://github.com/codeIIEST/Algorithms/pull/66), [#88](https://github.com/codeIIEST/Algorithms/pull/88), [#89](https://github.com/codeIIEST/Algorithms/pull/89), [#90](https://github.com/codeIIEST/Algorithms/pull/90), [#93](https://github.com/codeIIEST/Algorithms/pull/93), [#159](https://github.com/codeIIEST/Algorithms/pull/159) | CLOSED | 15 | |[Rahul Arulkumaran](https://github.com/rahulkumaran)| [#94](https://github.com/codeIIEST/Algorithms/pull/94), [#95](https://github.com/codeIIEST/Algorithms/pull/95), [#112](https://github.com/codeIIEST/Algorithms/pull/112), [#151](https://github.com/codeIIEST/Algorithms/pull/151), [#174](https://github.com/codeIIEST/Algorithms/pull/174) | MERGED | 16 | |[Rahul Arulkumaran](https://github.com/rahulkumaran)| [#206](https://github.com/codeIIEST/Algorithms/pull/206), [#207](https://github.com/codeIIEST/Algorithms/pull/207) | OPEN | 17 | |[Abhishek Nalla](https://github.com/abhisheknalla)| [#129](https://github.com/codeIIEST/Algorithms/pull/129) ,[#147](https://github.com/codeIIEST/Algorithms/pull/147) [#204](https://github.com/codeIIEST/Algorithms/pull/204)| MERGED | 18 | | [Zanark ( Debashish Mishra )](https://github.com/Zanark) | [PR #222](https://github.com/codeIIEST/Algorithms/pull/222) , [PR #146](https://github.com/codeIIEST/Algorithms/pull/146) , [PR #225](https://github.com/codeIIEST/Algorithms/pull/225) , [PR #135](https://github.com/codeIIEST/Algorithms/pull/135) | CLOSED , MERGED , MERGED , CLOSED| 19 | | [d3v3sh5ingh](https://github.com/D3v3sh5ingh) | [PR #126](https://github.com/codeIIEST/Algorithms/pull/126) , [PR #161](https://github.com/codeIIEST/Algorithms/pull/161) | Closed , MERGED| 20 | |[AdvikEshan( Nitish Kumar Tiwari )](https://github.com/AdvikEshan)| [PR #97](https://github.com/codeIIEST/Algorithms/pull/97),[PR #192](https://github.com/codeIIEST/Algorithms/pull/192), [PR #258](https://github.com/codeIIEST/Algorithms/pull/258)|Merged,Merged,Merged| 21 | |[imVivekGupta](https://github.com/imVivekGupta)|[#173](https://github.com/codeIIEST/Algorithms/pull/173), [#182](https://github.com/codeIIEST/Algorithms/pull/182), [#218](https://github.com/codeIIEST/Algorithms/pull/218), [#230](https://github.com/codeIIEST/Algorithms/pull/230) | MERGED | 22 | |[Priyangshuyogi](https://github.com/Priyangshuyogi)| [#188](https://github.com/codeIIEST/Algorithms/pull/188), [#227](https://github.com/codeIIEST/Algorithms/pull/227), [#251](https://github.com/codeIIEST/Algorithms/pull/251)| MERGED , MERGED , OPEN | 23 | 24 | -------------------------------------------------------------------------------- /Competitive Coding/Backtrack/nQueen.cpp: -------------------------------------------------------------------------------- 1 | /* C/C++ program to solve N Queen Problem using backtracking */ 2 | #define N 4 3 | #include 4 | 5 | /* A utility function to print solution */ 6 | void printSolution(int board[N][N]) 7 | { 8 | for (int i = 0; i < N; i++) 9 | { 10 | for (int j = 0; j < N; j++) 11 | printf(" %d ", board[i][j]); 12 | printf("\n"); 13 | } 14 | } 15 | 16 | /* A utility function to check if a queen can 17 | be placed on board[row][col]. Note that this 18 | function is called when "col" queens are 19 | already placed in columns from 0 to col -1. 20 | So we need to check only left side for 21 | attacking queens */ 22 | bool isSafe(int board[N][N], int row, int col) 23 | { 24 | int i, j; 25 | 26 | /* Check this row on left side */ 27 | for (i = 0; i < col; i++) 28 | if (board[row][i]) 29 | return false; 30 | 31 | /* Check upper diagonal on left side */ 32 | for (i=row, j=col; i>=0 && j>=0; i--, j--) 33 | if (board[i][j]) 34 | return false; 35 | 36 | /* Check lower diagonal on left side */ 37 | for (i=row, j=col; j>=0 && i= N) 49 | return true; 50 | 51 | /* Consider this column and try placing this queen in all rows one by one */ 52 | for (int i = 0; i < N; i++) 53 | { 54 | /* Check if queen can be placed on board[i][col] */ 55 | if ( isSafe(board, i, col) ) 56 | { 57 | /* Place this queen in board[i][col] */ 58 | board[i][col] = 1; 59 | 60 | /* recur to place rest of the queens */ 61 | if ( solveNQUtil(board, col + 1) ) 62 | return true; 63 | 64 | /* If placing queen in board[i][col] doesn't lead to a solution, then remove queen from board[i][col] */ 65 | board[i][col] = 0; // BACKTRACK 66 | } 67 | } 68 | 69 | /* If queen can not be place in any row in this colum col then return false */ 70 | return false; 71 | } 72 | 73 | /* This function solves the N Queen problem using 74 | Backtracking. It mainly uses solveNQUtil() to 75 | solve the problem. It returns false if queens 76 | cannot be placed, otherwise return true and 77 | prints placement of queens in the form of 1s. 78 | Please note that there may be more than one 79 | solutions, this function prints one of the 80 | feasible solutions.*/ 81 | bool solveNQ() 82 | { 83 | int board[N][N] = { {0, 0, 0, 0}, 84 | {0, 0, 0, 0}, 85 | {0, 0, 0, 0}, 86 | {0, 0, 0, 0} 87 | }; 88 | 89 | if ( solveNQUtil(board, 0) == false ) 90 | { 91 | printf("Solution does not exist"); 92 | return false; 93 | } 94 | 95 | printSolution(board); 96 | return true; 97 | } 98 | 99 | // driver program to test above function 100 | int main() 101 | { 102 | solveNQ(); 103 | return 0; 104 | } 105 | -------------------------------------------------------------------------------- /Competitive Coding/Bitwise Operations/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codeIIEST/Algorithms/85e3fee94db88b644a102898f889c97083191d35/Competitive Coding/Bitwise Operations/.DS_Store -------------------------------------------------------------------------------- /Competitive Coding/Bitwise Operations/Count_One/count_one.cpp: -------------------------------------------------------------------------------- 1 | //Program to count the no of 1's in the binary representation of a given decimal number using Bitwise Operations. 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int x=4; 8 | int count=0;//Variable to store the number of 1's in the decimal representation of x 9 | 10 | while(x) 11 | { 12 | x=x&(x-1); 13 | count++; 14 | } 15 | 16 | cout<<"The number of 1's in the decimal representation of "< 2 | using namespace std; 3 | 4 | int main() { 5 | long N; 6 | cin>>N; 7 | largest_power(N);} 8 | void largest_power(long N) 9 | { 10 | //changing all right side bits to 1. 11 | N = N| (N>>1); 12 | N = N| (N>>2); 13 | N = N| (N>>4); 14 | N = N| (N>>8); 15 | 16 | 17 | //as now the number is 2 * x-1, where x is required answer, so adding 1 and dividing it by 18 | 2. 19 | printf((N+1)>>1; 20 | 21 | } -------------------------------------------------------------------------------- /Competitive Coding/Bitwise Operations/Largest_power_of_2/readme.md: -------------------------------------------------------------------------------- 1 | # Finding the largest power of 2 (most significant bit in binary form), which is less than or 2 | equal to the given number N. 3 | 4 | Let’s say binary form of a N is {1111}base2 which is equal to 15. 5 | 15 = 2^4-1, where 4 is the number of bits in N. 6 | 7 | This property can be used to find the largest power of 2 less than or equal to N. How? 8 | If we somehow, change all the bits which are at right side of the most significant bit of N to 1, then the number will become x + (x-1) = 2 * x -1 , where x is the required answer. 9 | Example: 10 | Let’s say N = 21 = {10101}, here most significant bit is the 4th one. (counting from 0th digit) and so the answer should be 16. 11 | So lets change all the right side bits of the most significant bit to 1. Now the number changes to 12 | {11111} = 31 = 2 * 16 -1 = Y (let’s say). 13 | Now the required answer is (Y+1)>>1 or (Y+1)/2. 14 | -------------------------------------------------------------------------------- /Competitive Coding/Bitwise Operations/Power_of_Two/power_of_two.cpp: -------------------------------------------------------------------------------- 1 | //Program to count the NUMBER OF 1's in the binary representation of a decimal number 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int num=256;//Number to be checked whether is a power of 2 or not 8 | 9 | if (num && !(num & (num - 1)))//Checking the required condition as explained. 10 | cout< 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n,i; 7 | printf("Enter a number:\n"); 8 | scanf("%d",&n); 9 | printf("Enter bit to be checked:\n"); 10 | scanf("%d",&i); 11 | if( n & (1 << i) ) 12 | printf("The %dth bit is set in %d",i,n); 13 | else 14 | printf("The %dth bit is not set in %d",i,n); 15 | return 0; 16 | } -------------------------------------------------------------------------------- /Competitive Coding/Bitwise Operations/ith_bit_set/readme.md: -------------------------------------------------------------------------------- 1 | #Check whether the ith bit is set in a number using Bitwise Operations 2 | 3 | Let’s say we have a number N, and to check whether it’s ith bit is set or not, we can AND it with the number 2^i . The binary form of 2^i contains only ith bit as set (or 1), else every bit is 0 there. When we will AND it with N, and if the ith bit of N is set, then it will return a non zero number (2^i to be specific), else 0 will be returned. 4 | 5 | Using Left shift operator, we can write 2^i as 1 << i . 6 | 7 | Example: 8 | Let’s say N = 20 = {10100}2. Now let’s check if it’s 2nd bit is set or not(starting from 0). For that, we have to AND it with 2^2 = 1<<2 = {100}base 2 . 9 | {10100} & {100} = {100} = 2^2 = 4(non-zero number), which means it’s 2nd bit is set. 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /Competitive Coding/Bitwise Operations/readme.md: -------------------------------------------------------------------------------- 1 | #Bitwise Operations 2 | In some cases, a programmer has to go beyond the level of int,float,etc. More deeply a programmer has to understan the 3 | importance of bits and operations related to that.Data Compression, Encryption, etc are some of the important applications of bit operations and manipulation. Bitwise operations are faster and more closer to the system. 4 | We all know that 1 byte comprises of 8 bits and any integer or character can be represented using bits in computers, which we call its binary form(contains only 1 or 0) or in its base 2 form. 5 | 6 | #Bitwise Operations 7 | There are different bitwise operations used in the bit manipulation. These bit operations operate on the individual bits of the bit patterns. Bit operations are fast and can be used in optimizing time complexity. Some common bit operators are: 8 | 9 | NOT ( ~ ): Bitwise NOT is an unary operator that flips the bits of the number i.e., if the ith bit is 0, it will change it to 1 and vice versa. Bitwise NOT is nothing but simply the one’s complement of a number. Lets take an example. 10 | N = 5 = (101)2 11 | ~N = ~5 = ~(101)2 = (010)2 = 2 12 | 13 | AND ( & ): Bitwise AND is a binary operator that operates on two equal-length bit patterns. If both bits in the compared position of the bit patterns are 1, the bit in the resulting bit pattern is 1, otherwise 0. 14 | A = 5 = (101)2 , B = 3 = (011)2 A & B = (101)2 & (011)2= (001)2 = 1 15 | 16 | OR ( | ): Bitwise OR is also a binary operator that operates on two equal-length bit patterns, similar to bitwise AND. If both bits in the compared position of the bit patterns are 0, the bit in the resulting bit pattern is 0, otherwise 1. 17 | A = 5 = (101)2 , B = 3 = (011)2 18 | A | B = (101)2 | (011)2 = (111)2 = 7 19 | 20 | XOR ( ^ ): Bitwise XOR also takes two equal-length bit patterns. If both bits in the compared position of the bit patterns are 0 or 1, the bit in the resulting bit pattern is 0, otherwise 1. 21 | A = 5 = (101)2 , B = 3 = (011)2 22 | A ^ B = (101)2 ^ (011)2 = (110)2 = 6 23 | 24 | Left Shift ( << ): Left shift operator is a binary operator which shift the some number of bits, in the given bit pattern, to the left and append 0 at the end. Left shift is equivalent to multiplying the bit pattern with 2k 25 | 26 | ( if we are shifting k bits ). 27 | 1 << 1 = 2 = 21 28 | 1 << 2 = 4 = 22 1 << 3 = 8 = 23 29 | 1 << 4 = 16 = 24 30 | … 31 | 1 << n = 2n 32 | 33 | Right Shift ( >> ): Right shift operator is a binary operator which shift the some number of bits, in the given bit pattern, to the right and append 1 at the end. Right shift is equivalent to dividing the bit pattern with 2k ( if we are shifting k bits ). 34 | 4 >> 1 = 2 35 | 6 >> 1 = 3 36 | 5 >> 1 = 2 37 | 16 >> 4 = 1 38 | -------------------------------------------------------------------------------- /Competitive Coding/Data Structures/Queue/queue.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codeIIEST/Algorithms/85e3fee94db88b644a102898f889c97083191d35/Competitive Coding/Data Structures/Queue/queue.class -------------------------------------------------------------------------------- /Competitive Coding/Data Structures/Queue/queue.java: -------------------------------------------------------------------------------- 1 | package Data_Structures; 2 | import java.util.*; 3 | class Queue 4 | { 5 | private int q[], front, rear, size; 6 | 7 | 8 | /***** Constructor to initialize queue *****/ 9 | queue(int n) 10 | { //Begin constructor 11 | size = n; 12 | front = -1; 13 | rear = -1; 14 | q = new int[size]; 15 | 16 | for(int i = 0; i "); 87 | 88 | for(int i = front; i <= rear; i++) 89 | System.out.print(q[i]+"\t"); 90 | 91 | System.out.println("<--- rear"); 92 | 93 | } 94 | } //End display() 95 | 96 | 97 | 98 | 99 | public static void main(String args[]) 100 | { //Begin main() 101 | 102 | Scanner sc = new Scanner(System.in); 103 | System.out.println("Enter the size of the queue"); 104 | int n = sc.nextInt(); 105 | 106 | queue q1 = new queue(n); 107 | 108 | int choice; 109 | do 110 | { //Begin do 111 | System.out.println("\nEnter:\n1. Insert\n2. Delete\n3. Display"); 112 | choice = sc.nextInt(); 113 | switch(choice) 114 | { //Begin switch 115 | case 1: System.out.println("\nEnter an element to insert"); 116 | int element = sc.nextInt(); 117 | q1.insert(element); 118 | break; 119 | 120 | case 2: q1.delete(); 121 | break; 122 | 123 | case 3: q1.display(); 124 | break; 125 | 126 | default: System.out.println("Wrong choice. Exitting."); 127 | break; 128 | } //End switch 129 | } //End do 130 | while(choice >= 1 && choice <= 3); 131 | } //End main() 132 | } //End class 133 | -------------------------------------------------------------------------------- /Competitive Coding/Data Structures/Stack/stack.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codeIIEST/Algorithms/85e3fee94db88b644a102898f889c97083191d35/Competitive Coding/Data Structures/Stack/stack.class -------------------------------------------------------------------------------- /Competitive Coding/Data Structures/Stack/stack.java: -------------------------------------------------------------------------------- 1 | package Data_Structures 2 | import java.util.*; 3 | class stack 4 | { //Begin class 5 | 6 | int top = -1, size, s[]; 7 | 8 | 9 | /*****Constructor to initialise the stack *****/ 10 | stack(int n) 11 | { //Begin constructor 12 | size = n; 13 | 14 | s = new int[size]; 15 | for(int i = 0; i < size; i++) 16 | { //Begin for 17 | s[i] = 0; 18 | } //End for 19 | } //End constructor 20 | 21 | 22 | 23 | /***** Fucntion to insert/push item to stack *****/ 24 | private void push(int item) 25 | { //Begin push() 26 | 27 | if(top == (size-1)) //Checks if stack is full 28 | { //Begin if 29 | System.out.println("Stack overflow"); 30 | } //End if 31 | 32 | else //Element is entered to the stack when there is place 33 | { //Begin else 34 | top++; 35 | s[top] = item; 36 | } //End else 37 | 38 | } //End push() 39 | 40 | 41 | 42 | /***** Function to delete/pop an item (topmost element) from stack *****/ 43 | private void pop() 44 | { //Begin pop() 45 | 46 | if(top == -1) //Checks if stack is empty 47 | { //Begin if 48 | System.out.println("Stack underflow"); 49 | } //End if 50 | 51 | else 52 | { //Begin else 53 | System.out.println("Item deleted is:\t"+s[top]); 54 | top--; 55 | } //End else 56 | } //End pop() 57 | 58 | 59 | /***** Function to peep (show the topmost element in stack) *****/ 60 | private void peep() 61 | { //Begin peep() 62 | if(top == -1) 63 | System.out.println("No element to peep"); 64 | 65 | else 66 | System.out.println("Peep: top ---> "+s[top]); 67 | } //End peep() 68 | 69 | 70 | 71 | /***** Function to display the elements of stack *****/ 72 | private void display() 73 | { //Begin display() 74 | 75 | if(top == -1) 76 | { //Begin if 77 | System.out.println("No elements in stack"); 78 | } //End if 79 | 80 | else 81 | { //Begin else 82 | 83 | System.out.print("Elements of the stack: top---> "); 84 | for(int i=top; i>=0; i--) 85 | { 86 | System.out.print(s[i]+"\t"); 87 | } 88 | System.out.println(); 89 | } //End else 90 | } //End display() 91 | 92 | 93 | /***** main fucntion *****/ 94 | public static void main(String args[]) 95 | { //Begin main() 96 | 97 | Scanner sc = new Scanner(System.in); 98 | System.out.println("Enter the size of the stack"); 99 | int n = sc.nextInt(); 100 | 101 | stack st = new stack(n); 102 | 103 | int choice; 104 | do 105 | { //Begin do 106 | System.out.println("\nEnter:\n1. Push\n2. Pop\n3. Peep\n4. Display"); 107 | choice = sc.nextInt(); 108 | switch(choice) 109 | { //Begin switch 110 | case 1: System.out.println("\nEnter an element to push"); 111 | int element = sc.nextInt(); 112 | st.push(element); 113 | break; 114 | 115 | case 2: st.pop(); 116 | break; 117 | 118 | case 3: st.peep(); 119 | break; 120 | 121 | case 4: st.display(); 122 | break; 123 | 124 | default: System.out.println("Wrong choice. Exitting!"); 125 | break; 126 | } //End switch 127 | } //End do 128 | while(choice >= 1 && choice <= 4); 129 | } //End main() 130 | } //End class 131 | -------------------------------------------------------------------------------- /Competitive Coding/Dynamic Programming/0-1Knapsack/knapsack.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | 4 | class Knapsack 5 | { 6 | 7 | // A function to return maximum of two integers 8 | static int maximum(int a, int b) 9 | { 10 | if(a>b) 11 | return a; 12 | else 13 | return b; 14 | 15 | } 16 | 17 | // Returns the maximum value that can be put in a knapsack of capacity W 18 | static int knapSack(int W, int wt[], int val[], int n) 19 | { 20 | int i, w; 21 | int K[][] = new int[n+1][W+1]; 22 | 23 | // Build table K[][] in bottom up manner 24 | for (i = 0; i <= n; i++) 25 | { 26 | for (w = 0; w <= W; w++) 27 | { 28 | if (i==0 || w==0) 29 | K[i][w] = 0; 30 | else if (wt[i-1] <= w) 31 | K[i][w] = maximum(val[i-1] + K[i-1][w-wt[i-1]] , K[i1][w]); 32 | else 33 | K[i][w] = K[i-1][w]; 34 | } 35 | } 36 | 37 | Return K[n][W]; 38 | } 39 | 40 | 41 | 42 | public static void main(String args[]) 43 | { 44 | 45 | Scanner s=new Scanner(System.in); 46 | System.out.println(“Enter number of objects”); 47 | int n=s.nextInt(); 48 | int val[]=new int[n]; 49 | int wt[] = new int[n]; 50 | System.out.println(“Enter values of objects”); 51 | 52 | 53 | for(int i=0;i 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | int M;//Variable to store the number of different currency values. 9 | cout<<"Enter the number of denominations : "; 10 | cin>>M;//Inputting the number of different currency value from user. 11 | cout<>arr[i];//Inputting the value of each currency from user. 18 | } 19 | cout<>N;//Inputting the number of cents from user. 24 | cout< 3 | using namespace std; 4 | const int inf=0x3fffffff; 5 | #define Min(a,b) (a>test ; 16 | while(test--) 17 | { 18 | cin>>a; 19 | cin>>b; 20 | cin>>z; 21 | cin>>x; 22 | cin>>c; 23 | lena = strlen(a) ; 24 | lenb = strlen(b) ; 25 | if((lena-lenb)*z > c || (lenb-lena)*z > c ) 26 | { 27 | cout<<"-1\n"; 28 | continue ; 29 | } 30 | if( (z == 0) ) 31 | { 32 | cout<<"0\n" ; 33 | continue ; 34 | } 35 | if( (x == 0) ) 36 | { 37 | cout< c) 43 | previous_dp[i] = inf ; 44 | else 45 | previous_dp[i] = i*z ; 46 | } 47 | fr(i,1,lena+1) 48 | { 49 | alpha = Max((i-c),0) ; 50 | if( alpha > 0) 51 | { 52 | current_dp[alpha-1] = inf ; 53 | } 54 | alpha -= 1 ; 55 | temp = Min((i+c+1),(lenb+1)); 56 | fr(j,alpha+1,temp) 57 | { 58 | if(j == 0) 59 | { 60 | current_dp[j] = i*z ; 61 | } 62 | else 63 | { 64 | current_dp[j] = Min(Min(previous_dp[j] + z , current_dp[j-1] + z ) , previous_dp[j-1]+(a[i-1] == b[j-1] ? 0 : x)); 65 | } 66 | } 67 | fr(j,alpha,temp) 68 | { 69 | previous_dp[j] = current_dp[j] ; 70 | } 71 | } 72 | if(current_dp[lenb] > c) 73 | cout<<"-1\n"; 74 | else 75 | cout< 2 | using namespace std; 3 | #define Min(a,b) (a>test ; 12 | while(test--) 13 | { 14 | cin>>a; 15 | cin>>b; 16 | lena = strlen(a) ; 17 | lenb = strlen(b) ; 18 | dp[lena+1][lenb+1]; 19 | fr(i,0,lena+1) 20 | { 21 | fr(j,0,lenb+1) 22 | { 23 | if( i == 0 ) 24 | { 25 | dp[i][j] = j ; 26 | } 27 | else if( j == 0 ) 28 | { 29 | dp[i][j] = i ; 30 | } 31 | else 32 | { 33 | dp[i][j]=Min(Min(dp[i-1][j]+1,dp[i][j-1]+1),dp[i-1][j-1]+(a[i-1]==b[j-1]?0:100)); 34 | } 35 | cout< 3 | using namespace std; 4 | #define lli long long int 5 | #define infinite 0xffff 6 | #define Min(a,b) (((a)<(b))?(a):(b)) 7 | #define Max(a,b) (((a)>(b))?(a):(b)) 8 | #define fr(i,j,s) for(i = j ; i < s ; i++) 9 | #define ifr(i,j,s) for(i = j ; i >= s , i--) 10 | void lcs(char * a, char *b) 11 | { 12 | lli lena,lenb,i,j,count; 13 | lena=strlen(a); 14 | lenb=strlen(b); 15 | char record[lena+1][lenb+1]; 16 | //Code to generate the map 17 | fr(i,0,lena+1) 18 | { 19 | fr(j,0,lenb+1) 20 | { 21 | if(i==0 || j==0) 22 | { 23 | record[i][j]=0; 24 | } 25 | else if(a[i-1]==b[j-1]) 26 | { 27 | record[i][j]=record[i-1][j-1]+1; 28 | } 29 | else 30 | { 31 | record[i][j] = Max(record[i-1][j],record[i][j-1]); 32 | } 33 | } 34 | } 35 | //Code to find the subsequence 36 | i = lena; 37 | j = lenb; 38 | char sub[record[lena][lenb]]; 39 | lli index = record[i][j]-1; 40 | while( i > 0 && j > 0 ) 41 | { 42 | if(a[i-1]==b[j-1]) 43 | { 44 | sub[index]=a[i-1]; 45 | i--; 46 | j--; 47 | index--; 48 | } 49 | else if(Max(record[i-1][j],record[i][j-1]) == record[i-1][j]) 50 | { 51 | i--; 52 | } 53 | else 54 | { 55 | j--; 56 | } 57 | } 58 | fr(i,0,record[lena][lenb]) 59 | { 60 | cout<>str1; 70 | cin>>str2; 71 | lcs(str1,str2); 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /Competitive Coding/Dynamic Programming/Longest Increasing Subsequence/lis_n_log_n.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define lli long long int 4 | #define infinite 0xffff 5 | #define Min(a,b) (((a)<(b))?(a):(b)) 6 | #define Max(a,b) (((a)>(b))?(a):(b)) 7 | #define fr(i,j,s) for(i = j ; i < s ; i++) 8 | #define ifr(i,j,s) for(i = j ; i >= s ; i--) 9 | lli binary_LookUp(lli * record ,lli a , lli len , lli val) 10 | { 11 | while(len-a > 1) 12 | { 13 | lli m = a + (len-a)/2; 14 | if(record[m]>=val) 15 | { 16 | len = m ; 17 | } 18 | else 19 | { 20 | a = m ; 21 | } 22 | } 23 | return len ; 24 | } 25 | void lis(lli * a, lli n) 26 | { 27 | lli i,j,count,index; 28 | lli record[n]; 29 | //Code to generate the map 30 | record[0]=a[0]; 31 | lli len = 1 ; 32 | fr(i,1,n) 33 | { 34 | if(a[i] record[len-1]) 39 | { 40 | record[len] = a[i]; 41 | len++; 42 | } 43 | else 44 | { 45 | index=binary_LookUp(record,-1,len-1,a[i]); 46 | record[index] = a[i]; 47 | } 48 | } 49 | cout<>n; 60 | lli a[n]; 61 | fr(i,0,n) 62 | { 63 | cin>>a[i]; 64 | } 65 | lis(a,n); 66 | return 0; 67 | } 68 | -------------------------------------------------------------------------------- /Competitive Coding/Dynamic Programming/Longest Increasing Subsequence/lis_n_squared_sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define lli long long int 4 | #define infinite 0xffff 5 | #define Min(a,b) (((a)<(b))?(a):(b)) 6 | #define Max(a,b) (((a)>(b))?(a):(b)) 7 | #define fr(i,j,s) for(i = j ; i < s ; i++) 8 | #define ifr(i,j,s) for(i = j ; i >= s ; i--) 9 | void lis(lli * a, lli n) 10 | { 11 | lli i,j,count; 12 | lli record[n]; 13 | //Code to generate the map 14 | fr(i,0,n) 15 | { 16 | record[i] = 0 ; 17 | } 18 | fr(i,0,n) 19 | { 20 | fr(j,0,i) 21 | { 22 | if( (a[i]>a[j]) && (record[i]<(record[j]+1)) ) 23 | { 24 | record[i]=record[j]+1; 25 | } 26 | } 27 | } 28 | lli max = 0; 29 | lli index = 0 ; 30 | fr(i,0,n) 31 | { 32 | //cout<>n; 66 | lli a[n]; 67 | fr(i,0,n) 68 | { 69 | cin>>a[i]; 70 | } 71 | lis(a,n); 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /Competitive Coding/Dynamic Programming/Maximum Subarray Sum/Maximum Subarray Sum Readme.md: -------------------------------------------------------------------------------- 1 | Problem : To find the maximum subarray sum. 2 | 3 | Language used : C++ 4 | 5 | Input : An integer array given by the user. 6 | 7 | Output : A single integer denoting the maximum subarray sum. 8 | 9 | Algorithm Paradigm : Dynamic Programming. 10 | 11 | Time Complexity : Linear 12 | 13 | Space Complexity : Constant 14 | 15 | Working :- 16 | 17 | We are traversing the array and storing the sum of contiguous elements in sum variable. 18 | As the value of sum reaches its maximum value that value is stored in max_so_far variable. 19 | And as the value of sum becomes negative,we are setting the value of sum again to 0 as now its time to look for another subarray as the net sum of the elements of the previous subarray became negative. 20 | 21 | -------------------------------------------------------------------------------- /Competitive Coding/Dynamic Programming/Maximum Subarray Sum/Maximum Subarray Sum.cpp: -------------------------------------------------------------------------------- 1 | //Code to find the maximum subarray sum using dynamin programming in c++. 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | int n; 9 | cout<<"Enter the size of the array : ";//Inputting the size of the array. 10 | cin>>n; 11 | cout<>arr[i];//Inputting the values in the array. 18 | } 19 | 20 | int max_so_far=-99999;//It will store the maximum subarray sum. 21 | int sum=0;//It will store the sum of the different subarrays. 22 | 23 | for(int i=0;imax_so_far) 27 | max_so_far=sum; 28 | if(sum<0) 29 | sum=0; 30 | } 31 | 32 | cout<<"The maximum subarray sum is : "< 2 | using namespace std; 3 | 4 | int MaxSumIncrsSubseq(int arr[],int n) 5 | { 6 | int i,j,mx=0; 7 | int MSIS[n]; //An array of initial size as that of the original array to store the maximum sum of the increasing subsequence till that point. 8 | for(i=0;iarr[j] 15 | 2.)MSIS[i]arr[j] && MSIS[i] 2 | #include 3 | 4 | // A utility function to get the maximum of two integers 5 | int max(int a, int b) 6 | { 7 | return (a > b)? a : b; 8 | } 9 | 10 | 11 | /* Returns the best obtainable price for a rod of length n and 12 | price[] as prices of different pieces */ 13 | int DPcutRod(int price[], int n) 14 | { 15 | int val[n+1]; 16 | val[0] = 0; 17 | int i, j; 18 | for (i = 1; i<=n; i++) 19 | { 20 | int max_val = INT_MIN; 21 | // Recursively cut the rod in different pieces and compare different 22 | // configurations 23 | for (j = 0; j < i; j++) 24 | max_val = max(max_val, price[j] + val[i-j-1]); 25 | val[i] = max_val; 26 | } 27 | return val[n]; 28 | } 29 | 30 | int main() 31 | { 32 | int n; 33 | printf("Enter rod length\n"); 34 | scanf("%d",&n); 35 | int arr[n],i; 36 | printf("Enter prices for lengths 1 to n\n"); 37 | for(i=0;i 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main(){ 7 | std::ios::sync_with_stdio(false); 8 | /* 9 | We can easily observe that the optimum solution of the minimum 10 | cost at any row i is only dependent on the cost at row i-1 and 11 | the current row elements. Thus if we only store these two arrays 12 | of length c, We have reduced space from n*m to 2*m. 13 | */ 14 | 15 | int i, j, r, c; 16 | printf("Enter no of rows and no of cols\n"); 17 | cin>>r>>c; //take input of the rows and columns from user. 18 | int cost[c], dp[c]; 19 | int x; 20 | /* 21 | Since for the first row the minimum cost is the only cost possible 22 | required to get there, we directly calculate it. 23 | */ 24 | printf("Enter a R X C array\n"); 25 | 26 | for(i=0; i>cost[i]; 28 | if(i>0) cost[i] = cost[i] + cost[i-1]; 29 | } 30 | /* 31 | For the subsequent rows, the optimised cost for each cell in the 32 | previous row has been stored in the array cost[] and the optimised 33 | cost for the present row is stored in the array dp[]. 34 | */ 35 | for(i=1; i>x; 38 | if(j==0) 39 | dp[j] = cost[j] + x; 40 | else{ 41 | dp[j] = x + min(dp[j-1], min(cost[j-1], cost[j])); 42 | } 43 | } 44 | /* 45 | After dp[] has been found entirely, we copy its elements to 46 | cost[] and continue the iteration. 47 | */ 48 | for(j=0; (j 0 and n == 0 19 | isSubsetSum(set, n, sum) = true, if sum == 0 20 | 21 | We can solve the problem in Pseudo-polynomial time using Dynamic programming. We create a boolean 2D table subset[][] and fill it in bottom up manner. The value of subset[i][j] will be true if there is a subset of set[0..j-1] with sum equal to i., otherwise false. Finally, we return subset[sum][n] 22 | -------------------------------------------------------------------------------- /Competitive Coding/Dynamic Programming/subsetSum/subsetSum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Returns true if there is a subset of a[] with sun equal to given sum 4 | bool DP(int set[], int n, int sum) 5 | { 6 | // The value of subset[i][j] will be true if there is a 7 | // subset of set[0..j-1] with sum equal to i 8 | bool subset[n+1][sum+1]; 9 | // If sum is 0, then answer is true 10 | for (int i = 0; i <= n; i++) 11 | subset[i][0] = true; 12 | // If sum is not 0 and set is empty, then answer is false 13 | for (int i = 1; i <= sum; i++) 14 | subset[0][i] = false; 15 | // Fill the subset table in botton up manner 16 | for (int i = 1; i <= n; i++) 17 | { 18 | for (int j = 1; j <= sum; j++) 19 | { 20 | if(j= set[i-1]) 23 | subset[i][j] = subset[i-1][j] || 24 | subset[i - 1][j-set[i-1]]; 25 | } 26 | } 27 | return subset[n][sum]; 28 | } 29 | 30 | int main() 31 | { 32 | int n; 33 | int sum; 34 | printf("Enter no of elements of array and desired sum\n"); 35 | scanf("%d%d",&n,&sum); 36 | int i,a[n]; 37 | printf("Enter the array\n"); 38 | for(i=0;i 2 | using namespace std; 3 | int main() 4 | { 5 | printf("Enter no of test cases\n"); 6 | int t; cin >> t; 7 | int i2, i3, i5; 8 | i2 = i3 = i5 = 0; 9 | int ugly[500];// To store ugly numbers 10 | ugly[0] = 1; 11 | for (int i = 1; i < 500; ++i) { 12 | ugly[i] = min(ugly[i2]*2, min(ugly[i3]*3, ugly[i5]*5));//get minimum of possible solutions 13 | ugly[i] != ugly[i2]*2 ? : i2++; // next_mulitple_of_2 = ugly[i2]*2; 14 | ugly[i] != ugly[i3]*3? : i3++; // next_mulitple_of_3 = ugly[i3]*3 15 | ugly[i] != ugly[i5]*5 ? : i5++; // next_mulitple_of_5 = ugly[i5]*5; 16 | } 17 | int n; 18 | while(t--) { 19 | printf("Enter 'n' for the nth ugly number\n"); 20 | cin >> n; 21 | cout << ugly[n-1] << endl; 22 | } 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /Competitive Coding/Geometry/Convex hull/readme.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codeIIEST/Algorithms/85e3fee94db88b644a102898f889c97083191d35/Competitive Coding/Geometry/Convex hull/readme.md -------------------------------------------------------------------------------- /Competitive Coding/Graphs/Detecting cycles/detecting-cycles.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define ll long long int 5 | /*In this algorithm we use union and find method to find the existance of cycles in the graph. we have alocated a parent array , each node for a vertex. now 6 | we write parent of that vertex in that node. first we do a find for root of the src and dest vertex of the edge which is to be checked weather it forms a 7 | cycle or not, then we do the union of that two in a specific way if they have a different root. If the rank of a vertex is greater than the other than it becomes the parent of other 8 | thid process decreaces the size of our tree. If the two vertex whose rooots are found have same root then it is clear that it will form a cycle hence we say that 9 | we have found a cycle*/ 10 | typedef struct 11 | { 12 | ll src; 13 | ll dest; 14 | }edge; 15 | class Graph 16 | { 17 | private: 18 | ll vertex; 19 | ll edges; 20 | vector edgearray; 21 | vector parent; 22 | vector rank; 23 | list *array; 24 | public: 25 | Graph(ll vertices=0,ll edge=0) 26 | :vertex(vertices),edges(edge) 27 | { 28 | array= new list[vertex]; 29 | parent.assign(vertex,-1); 30 | rank.assign(vertex,0); 31 | } 32 | Graph(const Graph &g2) 33 | { 34 | vertex=g2.vertex; 35 | edges=g2.edges; 36 | array= new list[vertex]; 37 | parent.assign(vertex,-1); 38 | rank.assign(vertex,0); 39 | } 40 | ll find(ll v) 41 | { 42 | if(parent[v]==-1) 43 | return v; 44 | else 45 | find(parent[v]); 46 | } 47 | void unions(ll x,ll y) 48 | { 49 | ll xroot=find(x); 50 | ll yroot=find(y); 51 | if(rank[xroot]>rank[yroot]) 52 | parent[yroot]=xroot; 53 | else 54 | if(rank[yroot]>rank[xroot]) 55 | parent[xroot]=yroot; 56 | else 57 | { 58 | parent[xroot]=yroot; 59 | rank[yroot]++; 60 | } 61 | } 62 | ll iscycle(ll x,ll y) 63 | { 64 | 65 | ll xroot=find(x); 66 | ll yroot=find(y); 67 | if(xroot==yroot) 68 | return 1; 69 | else 70 | { 71 | unions(x,y); 72 | return 0; 73 | } 74 | } 75 | void addedge(ll v1,ll v2) 76 | { 77 | array[v1].push_back(v2); 78 | array[v2].push_back(v1); 79 | edge temp; 80 | temp.src=v1; 81 | temp.dest=v2; 82 | edgearray.push_back(temp); 83 | } 84 | 85 | }; 86 | int main() 87 | { 88 | ll vertex;ll edges,v1,v2; 89 | cin>>vertex>>edges; 90 | Graph g(vertex,edges); 91 | for(ll i=0;i>v1>>v2; 94 | g.addedge(v1,v2); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /Competitive Coding/Graphs/Detecting cycles/detecting-cycles_readme.md: -------------------------------------------------------------------------------- 1 | # Disjoint-set 2 | 3 | A disjoint-set forest consists of a number of elements each of which stores an id, a parent pointer, and, in efficient algorithms, a value called the "rank". 4 | The parent pointers of elements are arranged to form one or more trees, each representing a set. If an element's parent pointer points to no other element, then the element is the root of a tree and is the representative member of its set. A set may consist of only a single element. However, if the element has a parent, the element is part of whatever set is identified by following the chain of parents upwards until a representative element (one without a parent) is reached at the root of the tree. 5 | Forests can be represented compactly in memory as arrays in which parents are indicated by their array index. 6 | 7 | # MAKE SET 8 | 9 | The MakeSet operation makes a new set by creating a new element with a unique id, a rank of 0, and a parent pointer to itself. The parent pointer to itself indicates that the element is the representative member of its own set. 10 | The MakeSet operation has O(1) time complexity. 11 | Pseudocode: 12 | 13 | function MakeSet(x) 14 | if x is not already present: 15 | add x to the disjoint-set tree 16 | x.parent := x 17 | x.rank := 0 18 | 19 | ![alt text](https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRkmVdlJLBBEPsQUbG3igzyitb6PDbqCuVbVtQzc009uyLX65U-) 20 | 21 | # FIND 22 | Find(x) follows the chain of parent pointers from x upwards through the tree until an element is reached whose parent is itself. This element is the root of the tree and is the representative member of the set to which x belongs, and may be x itself. 23 | Path compression, is a way of flattening the structure of the tree whenever Find is used on it. Since each element visited on the way to a root is part of the same set, all of these visited elements can be reattached directly to the root. The resulting tree is much flatter, speeding up future operations not only on these elements, but also on those referencing them. 24 | 25 | Pseudocode: 26 | 27 | function Find(x) 28 | if x.parent != x 29 | x.parent := Find(x.parent) 30 | return x.parent 31 | 32 | ![alt text](https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRptXJI8DhupTU5GNaF5qKZX94VPYB7GTiXkYMTadEGRuFMS5PKtg) 33 | 34 | # UNION 35 | 36 | Union(x,y) uses Find to determine the roots of the trees x and y belong to. If the roots are distinct, the trees are combined by attaching the root of one to the root of the other. If this is done naively, such as by always making x a child of y, the height of the trees can grow as {\displaystyle O(n)} O(n). To prevent this union by rank is used. 37 | Union by rank always attaches the shorter tree to the root of the taller tree. Thus, the resulting tree is no taller than the originals unless they were of equal height, in which case the resulting tree is taller by one node. 38 | To implement union by rank, each element is associated with a rank. Initially a set has one element and a rank of zero. If two sets are unioned and have the same rank, the resulting set's rank is one larger; otherwise, if two sets are unioned and have different ranks, the resulting set's rank is the larger of the two. Ranks are used instead of height or depth because path compression will change the trees' heights over time. 39 | Pseudocode: 40 | 41 | function Union(x, y) 42 | xRoot := Find(x) 43 | yRoot := Find(y) 44 | 45 | // x and y are already in the same set 46 | if xRoot == yRoot 47 | return 48 | 49 | // x and y are not in same set, so we merge them 50 | if xRoot.rank < yRoot.rank 51 | xRoot.parent := yRoot 52 | else if xRoot.rank > yRoot.rank 53 | yRoot.parent := xRoot 54 | else 55 | //Arbitrarily make one root the new parent 56 | yRoot.parent := xRoot 57 | xRoot.rank := xRoot.rank + 1 58 | 59 | ![alt text](https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSZkZmlExRXCYS-k3TO9dSM0dH_Ql2WuiB-VTIGj6090KEI0Jmjjw) 60 | -------------------------------------------------------------------------------- /Competitive Coding/Graphs/Graph_Search/BreadthFirstSearch/Breadth_First_Search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | vectorVisited; 5 | vector< vector >Graph; 6 | 7 | void edge(int a,int b) 8 | { 9 | Graph[a].push_back(b); //for directed 10 | 11 | //If undirected graph is there, then add the following line 12 | // Graph[b].push_back(a); 13 | } 14 | 15 | void BreadthFirstSearch(int u) 16 | { 17 | queueq; 18 | q.push(u); 19 | Visited[u]=true; 20 | 21 | while(!q.empty()) 22 | { 23 | int f=q.front(); 24 | q.pop(); 25 | 26 | cout<>n>>e; 43 | Visited.assign(n,false); 44 | Graph.assign(n,vector()); 45 | 46 | int a,b; 47 | for(int i=0;i>a>>b; 50 | edge(a,b); 51 | } 52 | 53 | for(int i=0;i 2 | using namespace std; 3 | 4 | void addEdge(vectoradj[],int u,int v) 5 | { 6 | //For undirected graph 7 | adj[u].push_back(v); 8 | adj[v].push_back(u); 9 | } 10 | 11 | void DFSUtil(int u,vectoradj[],vector&visited) 12 | { 13 | visited[u]=true; 14 | cout<adj[],int V) 23 | { 24 | vectorvisited(V,false); 25 | for(int u=0;u adj[V]; 38 | addEdge(adj, 0, 1); 39 | addEdge(adj, 0, 4); 40 | addEdge(adj, 1, 2); 41 | addEdge(adj, 1, 3); 42 | addEdge(adj, 1, 4); 43 | addEdge(adj, 2, 3); 44 | addEdge(adj, 3, 4); 45 | DFS(adj, V); 46 | cout<<"\n"; 47 | return 0; 48 | } -------------------------------------------------------------------------------- /Competitive Coding/Graphs/Graph_Search/DepthFIrstSearch/README.md: -------------------------------------------------------------------------------- 1 | ## Depth-first search (DFS) 2 | An algorithm for traversing or searching tree or graph data structures. One starts at the root (selecting some arbitrary node as the root in the case of a graph) and explores as far as possible along each branch before backtracking 3 | 4 | ---- 5 | ![](https://upload.wikimedia.org/wikipedia/commons/7/7f/Depth-First-Search.gif) 6 | ---- 7 | This is the algorithm for Depth First Search in a given graph. 8 | 9 | * We take a starting vertex , and push all its adjacent vertexes in a stack. 10 | * Now we pop an element from a stack and push all its vertexes in the stack , and we also mark down these vertexes as visited. 11 | * After executing the code, we will get the vertex visited in a depth first manner. 12 | 13 | Some real life applications of DFS are as follows: 14 | 1) For an unweighted graph, DFS traversal of the graph produces the minimum spanning tree and all pair shortest path tree. 15 | 16 | 2) Detecting cycle in a graph 17 | A graph has cycle if and only if we see a back edge during DFS. So we can run DFS for the graph and check for back edges. (See this for details) 18 | 19 | 3) Path Finding 20 | We can specialize the DFS algorithm to find a path between two given vertices u and z. 21 | i) Call DFS(G, u) with u as the start vertex. 22 | ii) Use a stack S to keep track of the path between the start vertex and the current vertex. 23 | iii) As soon as destination vertex z is encountered, return the path as the 24 | contents of the stack 25 | 26 | See this for details. 27 | 28 | 4) Topological Sorting 29 | Topological Sorting is mainly used for scheduling jobs from the given dependencies among jobs. In computer science, applications of this type arise in instruction scheduling, ordering of formula cell evaluation when recomputing formula values in spreadsheets, logic synthesis, determining the order of compilation tasks to perform in makefiles, data serialization, and resolving symbol dependencies in linkers [2]. 30 | 31 | 5) To test if a graph is bipartite 32 | We can augment either BFS or DFS when we first discover a new vertex, color it opposited its parents, and for each other edge, check it doesn’t link two vertices of the same color. The first vertex in any connected component can be red or black! See this for details. 33 | 34 | 6) Finding Strongly Connected Components of a graph A directed graph is called strongly connected if there is a path from each vertex in the graph to every other vertex. (See this for DFS based algo for finding Strongly Connected Components) 35 | 36 | 7) Solving puzzles with only one solution, such as mazes. (DFS can be adapted to find all solutions to a maze by only including nodes on the current path in the visited set.) 37 | 38 | [more info](https://en.wikipedia.org/wiki/Depth-first_search) 39 | -------------------------------------------------------------------------------- /Competitive Coding/Graphs/Shortest Path/Bellman Ford/Bellman_Ford.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Edge 5 | { 6 | int src,dest,weight; 7 | }; 8 | 9 | struct Graph 10 | { 11 | int V,E; 12 | struct Edge* edge; 13 | }; 14 | 15 | struct Graph* buildGraph(int V,int E) 16 | { 17 | struct Graph* graph=new Graph; 18 | graph->V=V; 19 | graph->E=E; 20 | graph->edge=new Edge[E]; 21 | return graph; 22 | } 23 | 24 | void PrintSoln(int dist[],int n) 25 | { 26 | cout<<"Vertex Distance from source\n"; 27 | for(int i=0;iV; 36 | int E=graph->E; 37 | int dist[V]; 38 | 39 | for(int i=0;iedge[j].src; 50 | int v=graph->edge[j].dest; 51 | int weight=graph->edge[j].weight; 52 | if(dist[u]!=INT_MAX && (dist[u]+weightedge[i].src; 62 | int v=graph->edge[i].dest; 63 | int weight=graph->edge[i].weight; 64 | if(dist[u]!=INT_MAX && (dist[u] + weight < dist[v])) 65 | cout<<"Graph contains negative weight cycle\n"; 66 | } 67 | PrintSoln(dist,V); 68 | } 69 | 70 | int main() 71 | { 72 | int V = 5; // Number of vertices in graph 73 | int E = 8; // Number of edges in graph 74 | struct Graph* graph = buildGraph(V, E); 75 | 76 | // add edge 0-1 77 | graph->edge[0].src = 0; 78 | graph->edge[0].dest = 1; 79 | graph->edge[0].weight = -1; 80 | 81 | // add edge 0-2 82 | graph->edge[1].src = 0; 83 | graph->edge[1].dest = 2; 84 | graph->edge[1].weight = 4; 85 | 86 | // add edge 1-2 87 | graph->edge[2].src = 1; 88 | graph->edge[2].dest = 2; 89 | graph->edge[2].weight = 3; 90 | 91 | // add edge 1-3 92 | graph->edge[3].src = 1; 93 | graph->edge[3].dest = 3; 94 | graph->edge[3].weight = 2; 95 | 96 | // add edge 1-4 97 | graph->edge[4].src = 1; 98 | graph->edge[4].dest = 4; 99 | graph->edge[4].weight = 2; 100 | 101 | // add edge 3-2 102 | graph->edge[5].src = 3; 103 | graph->edge[5].dest = 2; 104 | graph->edge[5].weight = 5; 105 | 106 | // add edge 3-1 107 | graph->edge[6].src = 3; 108 | graph->edge[6].dest = 1; 109 | graph->edge[6].weight = 1; 110 | 111 | // add edge 4-3 112 | graph->edge[7].src = 4; 113 | graph->edge[7].dest = 3; 114 | graph->edge[7].weight = -3; 115 | 116 | BellmanFord(graph, 0); 117 | 118 | return 0; 119 | } 120 | -------------------------------------------------------------------------------- /Competitive Coding/Graphs/Shortest Path/Bellman Ford/readme.md: -------------------------------------------------------------------------------- 1 | ## Bellman Ford Algorithm 2 | 3 | #### Description 4 | This is a dynamic programming based algorithm, this algorithm gives shortest distance from a particular source in a graph to all its other vertices. 5 | 6 | --------- 7 | ![](http://users.informatik.uni-halle.de/~jopsi/dssea/bellman_ford.gif) 8 | 9 | ----------- 10 | #### Working 11 | We initialize the distance of source as '0' and all other vertices as 'INFINITE'. Now if the number of vertices in a graph is 'V' , then all the vertices are processed 'V-1' times, at each iteration for an edge 'uv' if 'dist[v]>dist[u]+weight of uv' , then update dist[v]=dist[u]+weight of uv. 12 | 13 | [More info](https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm) 14 | -------------------------------------------------------------------------------- /Competitive Coding/Graphs/Shortest Path/Floyd Warshall/Floyd_Warshall.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define lli long long int 4 | #define infinite numeric_limits::max() 5 | #define Min(a,b) ((a)<(b)?(a):(b)) 6 | #define Max(a,b) ((a)>(b)?(a):(b)) 7 | #define fr(i,j,s) for(i = j ; i < s ; i++) 8 | #define ifr(i,j,s) for(i = j ; i >= s , i--) 9 | void floydWasrshall(lli G[][400],int V) 10 | { 11 | int u , v , w; 12 | fr(u,0,V) 13 | { 14 | fr(v,0,V) 15 | { 16 | fr(w,0,V) 17 | { 18 | if(G[v][u]+G[u][w] < G[v][w]) 19 | G[v][w] = G[v][u]+G[u][w] ; 20 | } 21 | } 22 | } 23 | } 24 | int main(void) 25 | { 26 | int test,v,e,a,b,i,j; 27 | lli wt; 28 | cin>>v>>e; 29 | int ed = 0; 30 | lli graph[400][400]; 31 | int temp = e ; 32 | fr(i,0,v) 33 | { 34 | fr(j,0,v) 35 | { 36 | graph[i][j] = infinite ; 37 | if(i==j) 38 | graph[i][j] = 0; 39 | } 40 | } 41 | while(e--) 42 | { 43 | cin>>a>>b>>wt; 44 | graph[a-1][b-1] = wt; 45 | } 46 | lli q ; 47 | cin>>q; 48 | floydWasrshall(graph,v); 49 | while(q--) 50 | { 51 | cin>>a>>b; 52 | if(graph[a-1][b-1] == infinite ) 53 | graph[a-1][b-1] = -1 ; 54 | cout< 2 | #include 3 | 4 | #define MAX 100 5 | 6 | void create_graph(); 7 | void add(int vertex); 8 | int del(); 9 | int isEmpty(); 10 | int find_indegree_of_vertex(int vertex); 11 | 12 | int total_vertices; 13 | int adjacent_matrix[MAX][MAX]; 14 | int queue[MAX]; 15 | int front = -1; 16 | int rear = -1; 17 | 18 | int main() 19 | { 20 | int i, count, topological_sort[MAX], indegree[MAX]; 21 | create_graph(); 22 | //calculating the in-degree for all vertices. 23 | for(i = 0; i < total_vertices; i++) 24 | { 25 | indegree[i] = find_indegree_of_vertex(i); 26 | if(indegree[i] == 0) 27 | { 28 | add(i); 29 | } 30 | } 31 | count = 0; 32 | while(!isEmpty() && count < total_vertices) 33 | { 34 | int vertex = del(); 35 | topological_sort[++count] = vertex; 36 | for(i = 0; i < total_vertices; i++) 37 | { 38 | if(adjacent_matrix[vertex][i] == 1) 39 | { 40 | adjacent_matrix[vertex][i] = 0; 41 | indegree[i] = indegree[i] - 1; 42 | if(indegree[i] == 0) 43 | { 44 | add(i); 45 | } 46 | } 47 | } 48 | } 49 | //count < number of vertices implies all vertices could not be covered as there exists a cycle. 50 | if(count < total_vertices) 51 | { 52 | printf("Graph is Cyclic. Therefore, Topological Ordering Not Possible\n"); 53 | exit(1); 54 | } 55 | printf("Topological Order of Vertices\n"); 56 | for(i = 1; i <= count; i++) 57 | { 58 | printf("%3d", topological_sort[i]); 59 | } 60 | printf("\n"); 61 | return 0; 62 | } 63 | // Function to add a vertex in the queue 64 | void add(int vertex) 65 | { 66 | if(rear == MAX - 1) 67 | { 68 | printf("Queue Overflow\n"); 69 | } 70 | else 71 | { 72 | if (front == -1) 73 | { 74 | front = 0; 75 | } 76 | rear = rear + 1; 77 | queue[rear] = vertex ; 78 | } 79 | } 80 | //Queue is empty or not 81 | int isEmpty() 82 | { 83 | if(front == -1 || front > rear ) 84 | { 85 | return 1; 86 | } 87 | else 88 | { 89 | return 0; 90 | } 91 | } 92 | //Delete the front element of the queue 93 | int del() 94 | { 95 | 96 | if (front == -1 || front > rear) 97 | { 98 | printf("Queue Underflow\n"); 99 | exit(1); 100 | } 101 | else 102 | { 103 | int element = queue[front]; 104 | front = front+1; 105 | return element; 106 | } 107 | } 108 | //Calculate the in-degree of the vertex 109 | int find_indegree_of_vertex(int vertex) 110 | { 111 | int count, total_indegree = 0; 112 | for(count = 0; count < total_vertices; count++) 113 | { 114 | if(adjacent_matrix[count][vertex] == 1) 115 | { 116 | total_indegree++; 117 | } 118 | } 119 | return total_indegree; 120 | } 121 | //Generate the required graph 122 | void create_graph() 123 | { 124 | int count, maximum_edges, origin_vertex, destination_vertex; 125 | printf("Enter number of vertices:\t"); 126 | scanf("%d", &total_vertices); 127 | //Maximum edges possible with fixed number of vertices. 128 | maximum_edges = total_vertices * (total_vertices - 1); 129 | for(count = 1; count <= maximum_edges; count++) 130 | { 131 | printf("Enter Edge [%d] co-ordinates (-1 -1 to quit)\n", count); 132 | printf("Enter Origin Vertex:\t"); 133 | scanf("%d", &origin_vertex); 134 | printf("Enter Destination Vertex:\t"); 135 | scanf("%d", &destination_vertex); 136 | if((origin_vertex == -1) && (destination_vertex == -1)) 137 | { 138 | break; 139 | } 140 | if(origin_vertex >= total_vertices || destination_vertex >= total_vertices || origin_vertex < 0 || destination_vertex < 0) 141 | { 142 | printf("Edge Co-ordinates are Invalid\n"); 143 | count--; 144 | } 145 | else 146 | adjacent_matrix[origin_vertex][destination_vertex] = 1; 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /Competitive Coding/Greedy/Huffman Coding/Huffman_Coding.py: -------------------------------------------------------------------------------- 1 | string = 'BCAADDDCCACACAC' 2 | 3 | 4 | # Creating tree nodes 5 | class NodeTree(object): 6 | 7 | def __init__(self, left=None, right=None): 8 | self.left = left 9 | self.right = right 10 | 11 | def children(self): 12 | return (self.left, self.right) 13 | 14 | def nodes(self): 15 | return (self.left, self.right) 16 | 17 | def __str__(self): 18 | return '%s_%s' % (self.left, self.right) 19 | 20 | 21 | # Main function implementing huffman coding 22 | def huffman_code_tree(node, left=True, binString=''): 23 | if type(node) is str: 24 | return {node: binString} 25 | (l, r) = node.children() 26 | d = dict() 27 | d.update(huffman_code_tree(l, True, binString + '0')) 28 | d.update(huffman_code_tree(r, False, binString + '1')) 29 | return d 30 | 31 | 32 | # Calculating frequency 33 | freq = {} 34 | for c in string: 35 | if c in freq: 36 | freq[c] += 1 37 | else: 38 | freq[c] = 1 39 | 40 | freq = sorted(freq.items(), key=lambda x: x[1], reverse=True) 41 | 42 | nodes = freq 43 | 44 | while len(nodes) > 1: 45 | (key1, c1) = nodes[-1] 46 | (key2, c2) = nodes[-2] 47 | nodes = nodes[:-2] 48 | node = NodeTree(key1, key2) 49 | nodes.append((node, c1 + c2)) 50 | 51 | nodes = sorted(nodes, key=lambda x: x[1], reverse=True) 52 | 53 | huffmanCode = huffman_code_tree(nodes[0][0]) 54 | 55 | print(' Char | Huffman code ') 56 | print('----------------------') 57 | for (char, frequency) in freq: 58 | print(' %-4r |%12s' % (char, huffmanCode[char])) 59 | -------------------------------------------------------------------------------- /Competitive Coding/Greedy/Huffman Coding/Readme.md: -------------------------------------------------------------------------------- 1 | Python Implementation of Huffman Coding using Greedy Approach. 2 | Huffman Coding is a technique of compressing data to reduce its size without loss of data. It is generally useful to compress the data in which there are frequently occurring characters. 3 | It follows a Greedy approach since it deals with generating minimum length prefix-free binary codes. 4 | It uses variable-length encoding scheme for assigning binary codes to characters depending on how frequently they occur in the given text. 5 | Priority Queue is used for building the Huffman tree such that the character that occurs most frequently is assigned the smallest code and the one that occurs least frequently gets the largest code. 6 | It follows this procedure: - 7 | 8 | Create a leaf node for each character and build a min heap using all the nodes (The frequency value is used to compare two nodes in min heap) 9 | 10 | Repeat Steps 3 to 5 while heap has more than one node 11 | 12 | Extract two nodes, say x and y, with minimum frequency from the heap 13 | 14 | Create a new internal node z with x as its left child and y as its right child. Also frequency(z)= frequency(x)+frequency(y) 15 | 16 | Add z to min heap 17 | 18 | Last node in the heap is the root of Huffman tree 19 | -------------------------------------------------------------------------------- /Competitive Coding/Greedy/Knapsack/README.md: -------------------------------------------------------------------------------- 1 | # 0-1 Knapsack Problem 2 | ------------------------- 3 | ![](https://upload.wikimedia.org/wikipedia/commons/f/fd/Knapsack.svg) 4 | 5 | The knapsack problem or **rucksack problem** is a problem in *combinatorial optimization* : Given a set of items, each with a weight and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible. It derives its name from the problem faced by someone who is constrained by a fixed-size knapsack and must fill it with the most valuable items. 6 | 7 | ## Applications 8 | ----------------------------- 9 | Knapsack problems appear in real-world decision-making processes in a wide variety of fields: 10 | * Finding the least wasteful way to cut raw materials 11 | * Selection of investments and portfolios 12 | * Selection of assets for asset-backed securitization 13 | * Generating keys for the Merkle–Hellman cryptosystems 14 | 15 | ## Computational Complexity 16 | -------- 17 | * The decision problem form of the knapsack problem is NP-complete 18 | * The optimization problem is NP-hard 19 | * There is a pseudo-polynomial time algorithm using dynamic programming 20 | * Many cases that arise in practice, and "random instances" from some distributions, can nonetheless be solved exactly 21 | 22 | ![More info](https://en.wikipedia.org/wiki/Knapsack_problem) 23 | -------------------------------------------------------------------------------- /Competitive Coding/Greedy/Knapsack/knapsack.cpp: -------------------------------------------------------------------------------- 1 | // This C++ program solves the 0-1 knapsack problem. A very famous Dynamic Programming problem. 2 | #include 3 | using namespace std; 4 | typedef long long ll; 5 | 6 | ll knapsack(ll V[], ll W[], ll n, ll maxWeight) 7 | { 8 | ll K[n + 1][maxWeight + 1]; // Declaring the table for dynamic programming. 9 | for(ll i = 0; i <= n; i++) 10 | { 11 | for(ll j = 0; j <= maxWeight; j++) 12 | { 13 | if(i == 0 || j == 0) 14 | K[i][j] = 0; //Covering the base cases. 15 | 16 | else if(W[i - 1] <= j)// If the weight of the element is less than the capacity. 17 | K[i][j] = max(V[i - 1] + K[i - 1][j - W[i - 1]], K[i - 1][j]);// Then take the maximum of the value of this element or the leave this element. 18 | 19 | else 20 | K[i][j] = K[i - 1][j]; // If the weight of the element is more than the capacity, then leave this element. 21 | } 22 | } 23 | return K[n][maxWeight]; 24 | } 25 | 26 | int main() 27 | { 28 | ll n; 29 | cout << "Enter the value of n (The number of elements)." << endl; 30 | cin >> n; 31 | ll V[n], W[n]; 32 | cout << "Enter " << n << " space separated integers denoting the values." << endl; 33 | for(ll i = 0; i < n; i++) 34 | cin >> V[i]; 35 | cout << "Enter " << n << " space separated integers denoting the weights." << endl; 36 | for(ll i = 0; i < n; i++) 37 | cin >> W[i]; 38 | ll maxWeight; 39 | cout << "Enter the value of the capacity of the knapsack" << endl; 40 | cin >> maxWeight; 41 | cout << "The maximum total value obtained with the following knapsack" << endl; 42 | cout << knapsack(V, W, n, maxWeight) << endl; 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /Competitive Coding/Linked List/Linked_Lists_based_on_Arrays/README.md: -------------------------------------------------------------------------------- 1 | # Linked List operations 2 | 3 | **This folder contains files that have the following algorithms** 4 | 5 | 1. All BASIC Linked List operations on a Linked List based on **Arrays**     [File Link](https://github.com/Zanark/Algorithms/blob/f65f98acd93a2d5b2bfc96c56e35998a7ab8be50/Competitive%20Coding/Linked%20List/Linked_Lists_based_on_Arrays/LInked_List_Operations_%5BArray%5D.cpp#L1) 6 | 7 | * To insert an element onto a Linked List     [Code](https://github.com/Zanark/Algorithms/blob/f65f98acd93a2d5b2bfc96c56e35998a7ab8be50/Competitive%20Coding/Linked%20List/Linked_Lists_based_on_Arrays/LInked_List_Operations_%5BArray%5D.cpp#L57-L67) 8 | * To delete a specific element from a Linked List     [Code](https://github.com/Zanark/Algorithms/blob/f65f98acd93a2d5b2bfc96c56e35998a7ab8be50/Competitive%20Coding/Linked%20List/Linked_Lists_based_on_Arrays/LInked_List_Operations_%5BArray%5D.cpp#L45-L55) 9 | * To check if an element is present in the Linked List     [Code](https://github.com/Zanark/Algorithms/blob/f65f98acd93a2d5b2bfc96c56e35998a7ab8be50/Competitive%20Coding/Linked%20List/Linked_Lists_based_on_Arrays/LInked_List_Operations_%5BArray%5D.cpp#L37-L43) 10 | * To get the Value at the given position of the Linked List     [Code](https://github.com/Zanark/Algorithms/blob/f65f98acd93a2d5b2bfc96c56e35998a7ab8be50/Competitive%20Coding/Linked%20List/Linked_Lists_based_on_Arrays/LInked_List_Operations_%5BArray%5D.cpp#L29-L35) 11 | * To find the length of a Linked List     [Code](https://github.com/Zanark/Algorithms/blob/f65f98acd93a2d5b2bfc96c56e35998a7ab8be50/Competitive%20Coding/Linked%20List/Linked_Lists_based_on_Arrays/LInked_List_Operations_%5BArray%5D.cpp#L14) 12 | * To display the Linked List     [Code](https://github.com/Zanark/Algorithms/blob/f65f98acd93a2d5b2bfc96c56e35998a7ab8be50/Competitive%20Coding/Linked%20List/Linked_Lists_based_on_Arrays/LInked_List_Operations_%5BArray%5D.cpp#L69-L76) -------------------------------------------------------------------------------- /Competitive Coding/Linked List/Linked_Lists_based_on_POINTERS/README.md: -------------------------------------------------------------------------------- 1 | # Linked List operations 2 | 3 | **This folder contains files that have the following algorithms** 4 | 5 | 1. All BASIC Linked List operations on a Linked List based on **Pointers**     [File Link](https://github.com/codeIIEST/Algorithms/blob/1cc9b4bc30bf8ed5beddca9b55c68a217dc4002b/Competitive%20Coding/Linked%20List/Linked_List_operation.cpp#L1) 6 | 7 | * Adding elements at the *end* of a Linked List. [Code](https://github.com/codeIIEST/Algorithms/blob/1cc9b4bc30bf8ed5beddca9b55c68a217dc4002b/Competitive%20Coding/Linked%20List/Linked_List_operation.cpp#L36-L67) 8 | * Adding elements at the *begining* of a Linked List. [Code](https://github.com/codeIIEST/Algorithms/blob/1cc9b4bc30bf8ed5beddca9b55c68a217dc4002b/Competitive%20Coding/Linked%20List/Linked_List_operation.cpp#L69-L94) 9 | * Finding the *number of nodes* in a Linked List. [Code](https://github.com/codeIIEST/Algorithms/blob/1cc9b4bc30bf8ed5beddca9b55c68a217dc4002b/Competitive%20Coding/Linked%20List/Linked_List_operation.cpp#L96-L114) 10 | * Adding an element at the *middle (Mid-point Position)* of a Linked List. [Code](https://github.com/codeIIEST/Algorithms/blob/1cc9b4bc30bf8ed5beddca9b55c68a217dc4002b/Competitive%20Coding/Linked%20List/Linked_List_operation.cpp#L116-L152) 11 | * Adding elements at a *specific position* of a Linked List. [Code](https://github.com/codeIIEST/Algorithms/blob/1cc9b4bc30bf8ed5beddca9b55c68a217dc4002b/Competitive%20Coding/Linked%20List/Linked_List_operation.cpp#L154-L180) 12 | * Displaying elements of a Linked List. [Code](https://github.com/codeIIEST/Algorithms/blob/1cc9b4bc30bf8ed5beddca9b55c68a217dc4002b/Competitive%20Coding/Linked%20List/Linked_List_operation.cpp#L182-L193) 13 | * Deleting the element at the *middle (Mid-point Position)* of the Linked List. [Code](https://github.com/codeIIEST/Algorithms/blob/1cc9b4bc30bf8ed5beddca9b55c68a217dc4002b/Competitive%20Coding/Linked%20List/Linked_List_operation.cpp#L195-L243) 14 | * Deleting a *specific element* from a Linked List. [Code](https://github.com/codeIIEST/Algorithms/blob/1cc9b4bc30bf8ed5beddca9b55c68a217dc4002b/Competitive%20Coding/Linked%20List/Linked_List_operation.cpp#L247-L282) 15 | * Sorting the Linked List *[Increasing order]*. [Code](https://github.com/codeIIEST/Algorithms/blob/1cc9b4bc30bf8ed5beddca9b55c68a217dc4002b/Competitive%20Coding/Linked%20List/Linked_List_operation.cpp#L284-L307) 16 | * Merging two Sorted *[Increasing order]* Linked Lists. [Code](https://github.com/codeIIEST/Algorithms/blob/1cc9b4bc30bf8ed5beddca9b55c68a217dc4002b/Competitive%20Coding/Linked%20List/Linked_List_operation.cpp#L309-L395) 17 | * Reversing a Linked List. [Code](https://github.com/codeIIEST/Algorithms/blob/1cc9b4bc30bf8ed5beddca9b55c68a217dc4002b/Competitive%20Coding/Linked%20List/Linked_List_operation.cpp#L397-L410) 18 | 19 | 2. Removing Duplicate Elements from an Unsorted Linked List.    [File Link](https://github.com/codeIIEST/Algorithms/blob/1cc9b4bc30bf8ed5beddca9b55c68a217dc4002b/Competitive%20Coding/Linked%20List/Removing_duplicates_from_Linked_List.cpp#L1) -------------------------------------------------------------------------------- /Competitive Coding/Linked List/Linked_Lists_based_on_POINTERS/Removing_duplicates_from_Linked_List.cpp: -------------------------------------------------------------------------------- 1 | /*Removing Duplicate Elements from an unsorted linked list 2 | Technique Used:Maintain a hash table of data values. We simply iterate 3 | through the linked list and add the values to the hash table. If we 4 | encounter a duplicate element we simply remove it by changing pointers. 5 | Time Complexity-O(n), where n is the total number of elements in the 6 | linked list.*/ 7 | 8 | #include 9 | using namespace std; 10 | 11 | struct Node{ 12 | int data; 13 | Node* next; 14 | }; 15 | 16 | Node* head=NULL;//Head is declared globally to avoid repeated passing between funcitons 17 | 18 | /*Hash Table to keep track of data in linked list. 19 | The first and second column will keep track of postive 20 | and negative numbers respectively*/ 21 | bool hasht[1000001][2]={0}; 22 | 23 | void Insert(int value)//Function to insert a node at the beginning of the list 24 | { 25 | Node* newnode=new Node; 26 | newnode->data=value; 27 | newnode->next=head; 28 | head=newnode; 29 | } 30 | void print() 31 | { 32 | Node* temp=head; 33 | while(temp->next!=NULL)//Printing upto the second last element to avoid '->' at the end 34 | { 35 | cout<data<<"->"; 36 | temp=temp->next; 37 | } 38 | cout<data<<"\n"; 39 | } 40 | 41 | void Remove_Duplicates() 42 | { 43 | Node* prev=NULL; 44 | Node* temp=head; 45 | 46 | while(temp!=NULL)//Traversing upto the last node in the linked list 47 | { 48 | if(temp->data>=0)//Checking for +ve numbers 49 | { 50 | if(hasht[temp->data][0]==1)//If the number already visited 51 | prev->next=temp->next; //Delete the element by pointing prev to next of current(temp) 52 | else 53 | { 54 | hasht[temp->data][0]=1; //If not visited, mark visited by making the entry to 1 in the hash table 55 | prev=temp; 56 | } 57 | temp=temp->next; 58 | } 59 | else{ //Block for negative numbers 60 | {if(hasht[abs(temp->data)][1]==1) 61 | prev->next=temp->next; 62 | else 63 | { 64 | hasht[abs(temp->data)][1]=1; 65 | prev=temp; 66 | } 67 | temp=temp->next; 68 | } 69 | 70 | } 71 | } 72 | } 73 | 74 | 75 | int main() 76 | { 77 | //Creating the linked list 78 | Insert(5); 79 | Insert(4); 80 | Insert(7); 81 | Insert(5); 82 | Insert(4); 83 | Insert(5); 84 | Insert(53); 85 | Insert(8); 86 | Insert(45); 87 | Insert(52); 88 | Insert(6); 89 | Insert(100); 90 | Insert(8); 91 | Insert(5); 92 | Insert(25); 93 | Insert(6); 94 | cout<<"Linked List with duplicates:::\n"; 95 | print();//Printing the linked list before removing the duplicate elements 96 | 97 | Remove_Duplicates();//Calling the remove duplicates function 98 | cout<<"\nLinked Lists after duplicates removed:::\n"; 99 | print();//Calling the print function after deleting redundant elements 100 | 101 | } 102 | 103 | -------------------------------------------------------------------------------- /Competitive Coding/Math/Catalan_Numbers/README.md: -------------------------------------------------------------------------------- 1 | The two different programs in this folder contain the same implementation! 2 | The programs basically are a python implementation of the Catalan Numbers. 3 | They're similar to Fibonacci (very slightly) 4 | 5 | The two different implementations vary only in terms of time taken!
6 | Basically we can implement in 3 different ways!
7 | 8 | * Recursively - `Exponential time complexity`
9 | * Dynamic Programming - `O(n^2)`
10 | * Binomial Coefficient - `O(n)`

11 | 12 | Each of the above 3 implementations have a descending order of time complexities from (1) to (3)

13 | 14 | The Binomial implementation has the best time complexity while the Recursive implementation has the worst time complexity
15 | In this folder we have the Binomial and Recursive implementations of Catalan Numbers.

16 | 17 | Catalan Numbers have a lot of applications in Combinatorics. Some of them are listed below: 18 | * Cn is the number of standard Young tableaux whose diagram is a 2-by-n rectangle. In other words, it is the number of ways the numbers 1, 2, ..., 2n can be arranged in a 2-by-n rectangle so that each row and each column is increasing. As such, the formula can be derived as a special case of the hook-length formula. 19 | * Cn is the number of ways that the vertices of a convex 2n-gon can be paired so that the line segments joining paired vertices do not intersect. This is precisely the condition that guarantees that the paired edges can be identified (sewn together) to form a closed surface of genus zero (a topological 2-sphere). 20 | * Cn is the number of semiorders on n unlabeled items. 21 | * In chemical engineering Cn-1 is the number of possible separation sequences which can separate a mixture of n components.

22 | 23 | ### Sources : 24 | (1) Click [here](https://www.geeksforgeeks.org/program-nth-catalan-number/) to know more about Catalan number implementations and its theory.
25 | (2) Click [here](https://en.wikipedia.org/wiki/Catalan_number) to know more about the applicatations of Catalan Numbers in Combinatorics 26 | -------------------------------------------------------------------------------- /Competitive Coding/Math/Catalan_Numbers/catalan_binomial.py: -------------------------------------------------------------------------------- 1 | def binCoeff(n, k): #Finds the binomial coefficient 2 | if (k > n - k): #As binCoeff(n,k)=binCoeff(n,n-k) 3 | k = n - k 4 | res = 1 #Initialising Result 5 | for i in range(k): 6 | res = res * (n - i) 7 | res = res / (i + 1) 8 | return res #The binomial coefficient is returned 9 | 10 | def catalan(n): #Function that finds catalan numbers 11 | c = binCoeff(2*n, n) #Finding value of c by calling the binCoeff function 12 | return c/(n + 1) #This is the final catalan number 13 | 14 | if __name__=='__main__': 15 | print "The 10th catalan number is:",catalan(9) 16 | -------------------------------------------------------------------------------- /Competitive Coding/Math/Catalan_Numbers/catalan_recursive.py: -------------------------------------------------------------------------------- 1 | def catalan_numbers(n): 2 | if n <=1 : #The result will be 1, if the function takes an argument that's equal to or less than 1 3 | return 1 4 | res = 0 #Result has been initialised to 0 5 | for i in range(n): 6 | res += catalan_numbers(i) * catalan_numbers(n-i-1) #The recursive function call 7 | return res 8 | 9 | if __name__=='__main__': 10 | print "The 10th catalan number is:",catalan(9) 11 | -------------------------------------------------------------------------------- /Competitive Coding/Math/Chinese Remainder Theorem/Modular multiplicative inverse.md: -------------------------------------------------------------------------------- 1 | Given two integers ‘a’ and ‘m’, find modular multiplicative inverse of ‘a’ under modulo ‘m’. 2 | 3 | The modular multiplicative inverse is an integer ‘x’ such that. 4 | 5 | a x ≡ 1 (mod m) 6 | 7 | The value of x should be in {0, 1, 2, … m-1}, i.e., in the ring of integer modulo m. 8 | 9 | The multiplicative inverse of “a modulo m” exists if and only if a and m are relatively prime (i.e., if gcd(a, m) = 1). 10 | 11 | Examples: 12 | 13 | Input: a = 3, m = 11 14 | 15 | Output: 4 16 | 17 | Since (4x3) mod 11 = 1, 18 | 4 is modulo inverse of 3 19 | 20 | One might think, 15 also as a valid output as "(15x3) mod 11" 21 | is also 1, but 15 is not in ring {0, 1, 2, ... 10}, so not 22 | valid. 23 | 24 | Input: a = 10, m = 17 25 | 26 | Output: 12 27 | 28 | Since (10x12) mod 17 = 1, 12 is modulo inverse of 3 29 | 30 | -------------------------------------------------------------------------------- /Competitive Coding/Math/Chinese Remainder Theorem/README.md: -------------------------------------------------------------------------------- 1 | The Chinese remainder theorem is a theorem of number theory, which states that if one knows the remainders of the Euclidean division of an 2 | integer n by several integers, then one can determine uniquely the remainder of the division of n by the product of these integers, under 3 | the condition that the divisors are pairwise coprime. 4 | SAY......... 5 | We are given two arrays num[0..k-1] and rem[0..k-1]. 6 | In num[0..k-1], every pair is coprime (gcd for every pair is 1).We need to find minimum positive number x such that: 7 | 8 | x % num[0] = rem[0], 9 | x % num[1] = rem[1], 10 | ....................... 11 | x % num[k-1] = rem[k-1] 12 | 13 | Basically, we are given k numbers which are pairwise coprime, and given remainders of these numbers when an unknown number x is divided 14 | by them. We need to find the minimum possible value of x that produces given remainders. 15 | 16 | Examples: 17 | 18 | Input: num[] = {5, 7}, rem[] = {1, 3} 19 | 20 | Output: 31 21 | 22 | Explanation: 23 | 24 | 31 is the smallest number such that: 25 | 26 | (1) When we divide it by 5, we get remainder 1. 27 | 28 | (2) When we divide it by 7, we get remainder 3. 29 | 30 | Input: num[] = {3, 4, 5}, rem[] = {2, 3, 1} 31 | 32 | Output: 11 33 | 34 | Explanation: 35 | 36 | 11 is the smallest number such that: 37 | 38 | (1) When we divide it by 3, we get remainder 2. 39 | 40 | (2) When we divide it by 4, we get remainder 3. 41 | 42 | (3) When we divide it by 5, we get remainder 1. 43 | 44 | //////// The solution is based on below formula.\\\\\\\\\\\\ 45 | 46 | 47 | x = ( ∑ (rem[i]*pp[i]*inv[i]) ) % prod 48 | Where 0 <= i <= n-1 49 | 50 | rem[i] is given array of remainders 51 | 52 | prod is product of all given numbers 53 | prod = num[0] * num[1] * ... * num[k-1] 54 | 55 | pp[i] is product of all but num[i] 56 | pp[i] = prod / num[i] 57 | 58 | inv[i] = Modular Multiplicative Inverse of pp[i] with respect to num[i] 59 | 60 | /// I have explained the Modular multiplicative inverse method by Extended Euclidean algorithms in another file 61 | (Named : Modular multiplicative inverse)./// 62 | 63 | ///////WORKING PROCESS\\\\\\\ 64 | 65 | Example: 66 | 67 | Let us take below example to understand the solution 68 | 69 | num[] = {3, 4, 5} 70 | 71 | rem[] = {2, 3, 1} 72 | 73 | prod = 60 74 | 75 | pp[] = {20, 15, 12} 76 | 77 | inv[] = {2, 3, 3} { (20X2)%3 = 1, (15X3)%4 = 1 78 | (12X3)%5 = 1} 79 | 80 | x = (rem[0]*pp[0]*inv[0] + rem[1]*pp[1]*inv[1] + rem[2]*pp[2]*inv[2]) % prod 81 | 82 | = (2*20*2 + 3*15*3 + 1*12*3) % 60 83 | 84 | = (40 + 135 + 36) % 60 85 | 86 | = 11 87 | 88 | -------------------------------------------------------------------------------- /Competitive Coding/Math/Chinese Remainder Theorem/code.cpp: -------------------------------------------------------------------------------- 1 | Below is C++ implementation of above formula. We can use Extended Euclid based method(Described in the folder) discussed here to find inverse modulo. 2 | 3 | // A C++ program to demonstrate working of Chinise remainder Theorem 4 | 5 | // Returns modulo inverse of a with respect to m using extended Euclid Algorithm. 6 | 7 | #include 8 | using namespace std; 9 | int inv(int a, int m) 10 | { 11 | int m0 = m, t, q; 12 | int x0 = 0, x1 = 1; 13 | 14 | if (m == 1) 15 | return 0; 16 | 17 | // Application of extended Euclid Algorithm 18 | while (a > 1) 19 | { 20 | // q is quotient 21 | q = a / m; 22 | 23 | t = m; 24 | 25 | // m is remainder 26 | m = a % m, a = t; 27 | 28 | t = x0; 29 | 30 | x0 = x1 - q * x0; 31 | 32 | x1 = t; 33 | } 34 | 35 | // Make x1 positive 36 | if (x1 < 0) 37 | x1 += m0; 38 | 39 | return x1; 40 | } 41 | 42 | // k is size of num[] and rem[]. Returns the smallest 43 | // number x such that: 44 | // x % num[0] = rem[0], 45 | // x % num[1] = rem[1], 46 | // .................. 47 | // x % num[k-2] = rem[k-1] 48 | // Assumption: Numbers in num[] are pairwise coprime i.e(gcd for every pair is 1) 49 | 50 | int findMinX(int num[], int rem[], int k) 51 | { 52 | // Compute product of all numbers 53 | int prod = 1; 54 | for (int i = 0; i < k; i++) 55 | prod *= num[i]; 56 | 57 | // Initialize result 58 | int result = 0; 59 | 60 | // Apply above formula 61 | for (int i = 0; i < k; i++) 62 | { 63 | int pp = prod / num[i]; 64 | result += rem[i] * inv(pp, num[i]) * pp; 65 | } 66 | 67 | return result % prod; 68 | } 69 | 70 | // Main method 71 | 72 | int main(void) 73 | { 74 | int num[] = {3, 4, 5}; 75 | int rem[] = {2, 3, 1}; 76 | int k = sizeof(num)/sizeof(num[0]); 77 | cout << "x is " << findMinX(num, rem, k); 78 | return 0; 79 | } 80 | 81 | Output: 82 | 83 | x is 11 84 | -------------------------------------------------------------------------------- /Competitive Coding/Math/Chinese Remainder Theorem/code_MMI.cpp: -------------------------------------------------------------------------------- 1 | // Iterative C++ program to find modular inverse using extended Euclid algorithm. 2 | // Returns modulo inverse of a with respect to m using extended Euclid Algorithm. 3 | //Time Complexity of this method is O(Log m). 4 | // Assumption: a and m are coprimes, i.e., gcd(a, m) = 1 5 | 6 | #include 7 | int modInverse(int a, int m) 8 | { 9 | int m0 = m, t, q; 10 | int x0 = 0, x1 = 1; 11 | 12 | if (m == 1) 13 | return 0; 14 | 15 | while (a > 1) 16 | { 17 | // q is quotient 18 | q = a / m; 19 | 20 | t = m; 21 | 22 | // m is remainder 23 | m = a % m, a = t; 24 | 25 | t = x0; 26 | 27 | x0 = x1 - q * x0; 28 | 29 | x1 = t; 30 | } 31 | 32 | // Make x1 positive 33 | if (x1 < 0) 34 | x1 += m0; 35 | 36 | return x1; 37 | } 38 | 39 | // Main method 40 | int main() 41 | { 42 | int a = 3, m = 11; 43 | 44 | printf("Modular multiplicative inverse is %d\n", 45 | modInverse(a, m)); 46 | return 0; 47 | } 48 | 49 | Output: 50 | Modular multiplicative inverse is 4. 51 | -------------------------------------------------------------------------------- /Competitive Coding/Math/FFT/FastFourierTransform.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // For storing complex values of nth roots 5 | // of unity we use complex 6 | typedef complex cd; 7 | 8 | // Recursive function of FFT 9 | vector fft(vector& a) 10 | { 11 | int n = a.size(); 12 | 13 | // if input contains just one element 14 | if (n == 1) 15 | return vector(1, a[0]); 16 | 17 | // For storing n complex nth roots of unity 18 | vector w(n); 19 | for (int i = 0; i < n; i++) { 20 | double alpha = 2 * M_PI * i / n; 21 | w[i] = cd(cos(alpha), sin(alpha)); 22 | } 23 | 24 | vector A0(n / 2), A1(n / 2); 25 | for (int i = 0; i < n / 2; i++) { 26 | 27 | // even indexed coefficients 28 | A0[i] = a[i * 2]; 29 | 30 | // odd indexed coefficients 31 | A1[i] = a[i * 2 + 1]; 32 | } 33 | 34 | // Recursive call for even indexed coefficients 35 | vector y0 = fft(A0); 36 | 37 | // Recursive call for odd indexed coefficients 38 | vector y1 = fft(A1); 39 | 40 | // for storing values of y0, y1, y2, ..., yn-1. 41 | vector y(n); 42 | 43 | for (int k = 0; k < n / 2; k++) { 44 | y[k] = y0[k] + w[k] * y1[k]; 45 | y[k + n / 2] = y0[k] - w[k] * y1[k]; 46 | } 47 | return y; 48 | } 49 | 50 | // Driver code 51 | int main() 52 | { 53 | vector a{1, 2, 3, 4}; 54 | vector b = fft(a); 55 | for (int i = 0; i < 4; i++) 56 | cout << b[i] << endl; 57 | 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /Competitive Coding/Math/FFT/README.md: -------------------------------------------------------------------------------- 1 | Given two polynomial A(x) and B(x), find the product C(x) = A(x)*B(x). 2 | 3 | A coefficient representation of a polynomial Ax is a = a0, a1, …, an-1. 4 | • Example- 5 | A(x) = 6x^3 + 7x^2 - 10x + 9 6 | B(x) = -2x^3 + 4x - 5 7 | Coefficient representation of A(x) = (9, -10, 7, 6) 8 | Coefficient representation of B(x) = (-5, 4, 0, -2) 9 | 10 | Input : 11 | A[] = {9, -10, 7, 6} 12 | B[] = {-5, 4, 0, -2} 13 | Output : 14 | -12x^6 - 14x^5 + 44x^4 - 20x^3 -75x^2 + 86x - 45 15 | 16 | We can do better, if we represent the polynomial in another form. 17 | yes 18 | 19 | Idea is to represent polynomial in point-value form and then compute the product. A point-value representation of a polynomial A(x) of degree-bound n is a set of n point-value pairs is{ (x0, y0), (x1, y1), …, (xn-1, yn-1)} such that all of the xi are distinct and yi = A(xi) for i = 0, 1, …, n-1. 20 | 21 | 22 | -------------------------------------------------------------------------------- /Competitive Coding/Math/LuckyNumber/README.md: -------------------------------------------------------------------------------- 1 | Lucky Numbers----- 2 | Lucky numbers are subset of integers. 3 | 4 | Take the set of integers 5 | 1,2,3,4,5,6,7,8,9,10,11,12,14,15,16,17,18,19,…… 6 | 7 | First, delete every second number, we get following reduced set. 8 | 1,3,5,7,9,11,13,15,17,19,………… 9 | 10 | Now, delete every third number, we get 11 | 1, 3, 7, 9, 13, 15, 19,….…. 12 | 13 | Continue this process indefinitely…… 14 | Any number that does not get deleted due to above process is called “lucky”. 15 | 16 | Therefore, set of lucky numbers is 1, 3, 7, 13,……… 17 | -------------------------------------------------------------------------------- /Competitive Coding/Math/LuckyNumber/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define bool int 3 | 4 | 5 | bool isLucky(int n) /* Returns 1 if n is a lucky no. ohterwise returns 0*/ 6 | { 7 | static int counter = 2; 8 | 9 | 10 | int next_position = n; /*variable next_position is just for readability of 11 | the program we can remove it and use n only */ 12 | if(counter > n) 13 | return 1; 14 | if(n%counter == 0) 15 | return 0; 16 | 17 | 18 | next_position -= next_position/counter; /*calculate next position of input no*/ 19 | 20 | counter++; 21 | return isLucky(next_position); 22 | } 23 | 24 | int main() 25 | { 26 | int x = 5; 27 | if( isLucky(x) ) 28 | printf("%d is a lucky no.", x); 29 | else 30 | printf("%d is not a lucky no.", x); 31 | getchar(); 32 | } 33 | 34 | /*output*/ 35 | Output: 36 | 5 is not a lucky no. 37 | -------------------------------------------------------------------------------- /Competitive Coding/Math/Primality Test/Fermat Method/README.md: -------------------------------------------------------------------------------- 1 | Given a number n, check if it is prime or not. This method is a probabilistic method and is based on below Fermat’s Little Theorem. 2 | 3 | Fermat's Little Theorem: 4 | If n is a prime number, then for every a, 1 <= a < n, 5 | 6 | a^n-1 ~ 1 mod (n) 7 | OR 8 | a^n-1 % n ~ 1 9 | 10 | 11 | Example: 12 | 13 | Since 5 is prime, 2^4 ≡ 1 (mod 5) [or 2^4%5 = 1], 14 | 15 | 3^4 ≡ 1 (mod 5) and 4^4 ≡ 1 (mod 5). 16 | 17 | Since 7 is prime, 2^6 ≡ 1 (mod 7), 18 | 19 | 3^6 ≡ 1 (mod 7), 4^6 ≡ 1 (mod 7) 20 | 5^6 ≡ 1 (mod 7) and 6^6 ≡ 1 (mod 7). 21 | 22 | We will take help of this Fermat's Little Theorem as a function to calculate a no is prime or not. 23 | -------------------------------------------------------------------------------- /Competitive Coding/Math/Primality Test/Fermat Method/SrcCode.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | /* Iterative Function to calculate (a^n)%p in O(logy) */ 6 | int power(int a, unsigned int n, int p) 7 | { 8 | int res = 1; // Initialize result 9 | a = a % p; // Update 'a' if 'a' >= p 10 | 11 | while (n > 0) 12 | { 13 | // If n is odd, multiply 'a' with result 14 | if (n & 1) 15 | res = (res*a) % p; 16 | 17 | // n must be even now 18 | n = n>>1; // n = n/2 19 | a = (a*a) % p; 20 | } 21 | return res; 22 | } 23 | 24 | // If n is prime, then always returns true, If n is 25 | // composite than returns false with high probability 26 | // Higher value of k increases probability of correct result. 27 | 28 | bool isPrime(unsigned int n, int k) 29 | { 30 | // Corner cases 31 | if (n <= 1 || n == 4) return false; 32 | if (n <= 3) return true; 33 | 34 | // Try k times 35 | while (k>0) 36 | { 37 | // Pick a random number in [2..n-2] 38 | // Above corner cases make sure that n > 4 39 | int a = 2 + rand()%(n-4); 40 | 41 | // Fermat's little theorem 42 | if (power(a, n-1, n) != 1) 43 | return false; 44 | 45 | k--; 46 | } 47 | 48 | return true; 49 | } 50 | 51 | // Driver Program 52 | int main() 53 | { 54 | int k = 3; 55 | isPrime(11, k)? cout << " true\n": cout << " false\n"; 56 | isPrime(15, k)? cout << " true\n": cout << " false\n"; 57 | return 0; 58 | } 59 | 60 | 61 | Output: 62 | 63 | true 64 | false 65 | -------------------------------------------------------------------------------- /Competitive Coding/Math/Primality Test/Optimized School Method/README.md: -------------------------------------------------------------------------------- 1 | Given a positive integer, check if the number is prime or not. A prime is a natural number greater than 1 that has no 2 | positive divisors other than 1 and itself. 3 | 4 | Examples of first few prime numbers are {2, 3, 5, 7,...} 5 | 6 | Examples: 7 | 8 | **Input:** n = 11 9 | 10 | **Output:** true 11 | 12 | **Input:** n = 15 13 | 14 | **Output:** false 15 | 16 | **Input:** n = 1 17 | 18 | **Output:** false 19 | 20 | A simple solution is to iterate through all numbers from 2 to n-1 and for every number check if it divides n. If we find 21 | any number that divides, we return false. Instead of checking till n, we can check till √n because a larger factor of n 22 | must be a multiple of smaller factor that has been already checked. The algorithm can be improved further by observing 23 | that all primes are of the form 6k ± 1, with the exception of 2 and 3. This is because all integers can be expressed 24 | as (6k + i) for some integer k and for i = ?1, 0, 1, 2, 3, or 4; 2 divides (6k + 0), (6k + 2), (6k + 4); and 3 divides 25 | (6k + 3). So a more efficient method is to test if n is divisible by 2 or 3, then to check through all the numbers of 26 | form 6k ± 1. 27 | 28 | Time complexity of this solution is O(root(n)). 29 | -------------------------------------------------------------------------------- /Competitive Coding/Math/Primality Test/Optimized School Method/SrcCode.cpp: -------------------------------------------------------------------------------- 1 | // A optimized school method based C++ program to check if a number is prime or not. 2 | 3 | #include 4 | using namespace std; 5 | 6 | bool isPrime(int n) 7 | { 8 | // Corner cases 9 | if (n <= 1) return false; 10 | if (n <= 3) return true; 11 | 12 | // This is checked so that we can skip 13 | // middle five numbers in below loop 14 | if (n%2 == 0 || n%3 == 0) return false; 15 | 16 | for (int i=5; i*i<=n; i=i+6) 17 | if (n%i == 0 || n%(i+2) == 0) 18 | return false; 19 | 20 | return true; 21 | } 22 | 23 | 24 | // Driver Program 25 | int main() 26 | { 27 | isPrime(23)? cout << " true\n": cout << " false\n";//use of ternary operator 28 | isPrime(35)? cout << " true\n": cout << " false\n"; 29 | return 0; 30 | } 31 | 32 | Output: 33 | 34 | true 35 | false 36 | -------------------------------------------------------------------------------- /Competitive Coding/Math/Project_Euler/Problem_21/P21.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codeIIEST/Algorithms/85e3fee94db88b644a102898f889c97083191d35/Competitive Coding/Math/Project_Euler/Problem_21/P21.class -------------------------------------------------------------------------------- /Competitive Coding/Math/Project_Euler/Problem_21/P21.java: -------------------------------------------------------------------------------- 1 | package problem_21; 2 | class P21 3 | { //Begin class 4 | 5 | 6 | /***** Function to calculate the sum of proper divisors or factors *****/ 7 | public static int sumFactors(int num) 8 | { //Begin sumFactors() 9 | int sum = 0; 10 | 11 | for(int i = 1; i 2 | using namespace std; 3 | 4 | vector SieveOfEratosthenes(int n) 5 | { 6 | bool prime[n+1]; //To mark those numbers which are prime, prime numbers will be marked by a 'True' 7 | memset(prime,true,sizeof(prime)); 8 | vectorPrimes; 9 | /* 10 | In this nested loop , we start from the value 2, and marked all its multiple which are less then or equal to n, 11 | similarly for 3,4,5....upto n. The logic is simple, since every number which are multiple of 2 are having 2 as a 12 | factor other then 1 and the number itself, similarly for all other numbers. 13 | */ 14 | for(int p=2;p*p<=n;p++) 15 | { 16 | if(prime[p]==true) 17 | { 18 | for(int i=p*2;i<=n;i+=p) 19 | { 20 | prime[i]=false; 21 | } 22 | } 23 | } 24 | /* Pushing all the prime numbers in one container. */ 25 | for(int p=2;p<=n;p++) 26 | { 27 | if(prime[p]) 28 | { 29 | Primes.push_back(p); 30 | } 31 | } 32 | return Primes; 33 | } 34 | 35 | int main() 36 | { 37 | int n; 38 | cout<<"Enter the number upto which prime numbers are to be found\n"; 39 | cin>>n; 40 | vector result; 41 | result = SieveOfEratosthenes(n); 42 | for(int i=0;i 4 | using namespace std; 5 | // Function to check whether there is 6 | // overflow in a * b or not. Ittreturns 7 | // true if there is overflow. 8 | bool isOverflow(long long a, long long b) 9 | { 10 | // Check if either of them is zero 11 | if (a == 0 || b == 0) 12 | return false; 13 | 14 | long long result = a * b; 15 | if (a == result / b) 16 | return false; 17 | else 18 | return true; 19 | } 20 | 21 | int main() 22 | { 23 | long long a; 24 | long long b; 25 | scanf("%lld%lld",&a,&b); 26 | if (isOverflow(a, b)) 27 | cout << "Yes"; 28 | else 29 | cout << "No"; 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /Competitive Coding/Math/kthPrimeFactor/README.md: -------------------------------------------------------------------------------- 1 | Given two numbers n and k, print k-th prime factor among all prime factors of n. For example, if the input number is 15 and k is 2, then output should be “5”. And if the k is 3, then output should be “-1” (there are less than k prime factors). 2 | 3 | 4 | A Simple Solution is to first find prime factors of n. While finding prime factors, keep track of count. If count becomes k, we return current prime factor. 5 | 6 | 7 | -------------------------------------------------------------------------------- /Competitive Coding/Math/kthPrimeFactor/kthPrimeFactor.cpp: -------------------------------------------------------------------------------- 1 | // Program to print kth prime factor 2 | # include 3 | using namespace std; 4 | 5 | // A function to generate prime factors of a 6 | // given number n and return k-th prime factor 7 | 8 | int kPrimeFactor(int n, int k) 9 | { 10 | // Find the number of 2's that divide k 11 | while (n%2 == 0) 12 | { 13 | k--; 14 | n = n/2; 15 | if (k == 0) 16 | return 2; 17 | } 18 | // n must be odd at this point. So we can skip 19 | // one element (Note i = i +2) 20 | for (int i = 3; i <= sqrt(n); i = i+2) 21 | { 22 | // While i divides n, store i and divide n 23 | while (n%i == 0) 24 | { 25 | if (k == 1) 26 | return i; 27 | 28 | k--; 29 | n = n/i; 30 | } 31 | } 32 | // This condition is to handle the case where 33 | // n is a prime number greater than 2 34 | if (n > 2 && k == 1) 35 | return n; 36 | 37 | return -1; 38 | } 39 | 40 | int main() 41 | { 42 | int n, k; 43 | scanf("%d%d",&n,&k); 44 | cout << kPrimeFactor(n, k) << endl; 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /Competitive Coding/Search/Binary Search/Binary_Search.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | 6 | int n_terms, *arr, item, i, j, mid, top, bottom; 7 | 8 | 9 | 10 | printf("Enter how many elements you want:\n"); // no of elements 11 | scanf("%d", &n_terms); 12 | arr = (int*)malloc(sizeof(int)*n_terms); 13 | printf("Enter the %d elements in ascending order\n", n_terms); 14 | for (i = 0; i < n_terms; i++) { 15 | scanf("%d", &arr[i]); 16 | } 17 | 18 | printf("\nEnter the item to search\n"); // Target element to be searched 19 | scanf("%d", &item); 20 | bottom = 1; 21 | top = n_terms; 22 | 23 | do { 24 | mid = bottom + (top - bottom)/2 ; // same as (bottom + top / 2) but considers overflow condition when bottom + top might be larger than int 25 | if (item < arr[mid]) 26 | top = mid - 1; // Here we are dividing the array into two equal parts 27 | else if (item > arr[mid]) /* if target element > mid part of array , we do the search in the upper part of the array 28 | else search in the lower part */ 29 | bottom = mid + 1; 30 | } while (item != arr[mid] && bottom <= top); 31 | 32 | if (item == arr[mid]) { 33 | printf("Binary search successfull!!\n"); 34 | printf("%d found in position: %d\n", item, mid + 1); 35 | } else { 36 | printf("Search failed\n%d not found\n", item); 37 | } 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /Competitive Coding/Search/Interpolation Search/interpolation_search.c: -------------------------------------------------------------------------------- 1 | // C program to implement interpolation search 2 | #include 3 | 4 | // If x is present in arr[0..n-1], then returns 5 | // index of it, else returns -1. 6 | int interpolationSearch(int arr[], int n, int x) 7 | { 8 | // Find indexes of two corners 9 | int lo = 0, hi = (n - 1); 10 | 11 | // Since array is sorted, an element present 12 | // in array must be in range defined by corner 13 | while (lo <= hi && x >= arr[lo] && x <= arr[hi]) 14 | { 15 | // Probing the position with keeping 16 | // uniform distribution in mind. 17 | int pos = lo + (((double)(hi-lo) / 18 | (arr[hi]-arr[lo]))*(x - arr[lo])); 19 | 20 | // Condition of target found 21 | if (arr[pos] == x) 22 | return pos; 23 | 24 | // If x is larger, x is in upper part 25 | if (arr[pos] < x) 26 | lo = pos + 1; 27 | 28 | // If x is smaller, x is in lower part 29 | else 30 | hi = pos - 1; 31 | } 32 | return -1; 33 | } 34 | 35 | // Driver Code 36 | int main() 37 | { 38 | // Array of items on which search will 39 | // be conducted. 40 | 41 | int n; 42 | int arr[] 43 | scanf("%d",&n); 44 | for(i=0;i 2 | #include 3 | int main() 4 | { 5 | int *array, search, c, n_terms; 6 | 7 | printf("Enter the number of elements in array\n"); 8 | scanf("%d",&n_terms); // Total no of elements 9 | 10 | array = (int*)malloc(sizeof(int)*n_terms); 11 | printf("Enter %d integer(s)\n", n_terms); 12 | 13 | for (c = 0; c < n_terms; c++) 14 | scanf("%d", &array[c]); // Reading the elements 15 | 16 | printf("Enter the number to search\n"); // Target element to be searched 17 | scanf("%d", &search); 18 | 19 | for (c = 0; c < n_terms; c++) 20 | { 21 | if (array[c] == search) /* if required element found */ 22 | { 23 | printf("%d is present at location %d.\n", search, c+1); 24 | break; 25 | } 26 | } 27 | if (c == n_terms) 28 | printf("%d is not present in array.\n", search); // Element not found 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /Competitive Coding/Search/README.md: -------------------------------------------------------------------------------- 1 | ## Search Algorithms 2 | 3 | ### Linear 4 | ![alt text](https://camo.githubusercontent.com/c05ad3f2178af2f16ebe2c04eb122e1e0c6a055b/687474703a2f2f7777772e7475746f7269616c73706f696e742e636f6d2f646174615f737472756374757265735f616c676f726974686d732f696d616765732f6c696e6561725f7365617263682e676966) 5 | 6 | From [Wikipedia](https://en.wikipedia.org/wiki/Linear_search): linear search or sequential search is a method for finding a target value within a list. It sequentially checks each element of the list for the target value until a match is found or until all the elements have been searched. 7 | Linear search runs in at worst linear time and makes at most n comparisons, where n is the length of the list. 8 | 9 | __Properties__ 10 | * Worst case performance O(n) 11 | * Best case performance O(1) 12 | * Average case performance O(n) 13 | * Worst case space complexity O(1) iterative 14 | 15 | ### Binary 16 | ![alt text](https://camo.githubusercontent.com/1cd853b57885449a176810b3e967167fb9fbf3b3/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f662f66372f42696e6172795f7365617263685f696e746f5f61727261792e706e67) 17 | 18 | From [Wikipedia](https://en.wikipedia.org/wiki/Binary_search_algorithm): Binary search, also known as half-interval search or logarithmic search, is a search algorithm that finds the position of a target value within a sorted array. It compares the target value to the middle element of the array; if they are unequal, the half in which the target cannot lie is eliminated and the search continues on the remaining half until it is successful. 19 | 20 | __Properties__ 21 | * Worst case performance O(log n) 22 | * Best case performance O(1) 23 | * Average case performance O(log n) 24 | * Worst case space complexity O(1) 25 | 26 | ### Interpolation 27 | Interpolation search is an improved version of binary search algorithm. 28 | 29 | ![alt text](https://qph.ec.quoracdn.net/main-qimg-02f1f050de01608b9b1f2f27155d1b17) 30 | 31 | Even when the data is sorted, binary search does not take advantage of that to probe the position of desired data. 32 | Position Probing in Interpolation 33 | SearchInterpolation search search a particular item by computing the probe position. Initially probe position is the position of the middle most item of the collection.If middle item is greater than item then probe position is again calculated in the sub-array to the right of the middle item other wise item is search in sub-array to the left of the middle item. This process continues on sub-array as well until the size of subarray reduces to zero. 34 | 35 | 36 | __Properties__ 37 | * Worst case performance O(n) 38 | * Best case performance O(1) 39 | * Average case performance O(log(logn)) 40 | * Worst case space cmplexity O(1) 41 | -------------------------------------------------------------------------------- /Competitive Coding/Sorting/Bubble Sort/bubble_sort.c: -------------------------------------------------------------------------------- 1 | 2 | // BUBBLE SORT 3 | 4 | #include 5 | 6 | void swap(int*,int*); 7 | 8 | void bubblesort(int arr[], int size) 9 | { 10 | int i, j; 11 | for (i = 0; i < size - 1; i++) // Function where the actual algorithm is implemented 12 | { 13 | for (j = 0; j < size - i - 1; j++) 14 | { 15 | if (arr[j] > arr[j+1]) 16 | swap(&arr[j], &arr[j+1]); 17 | 18 | } 19 | } 20 | } 21 | void swap(int *a, int *b) 22 | { 23 | int temp; // Function for swapping two variables 24 | temp = *a; 25 | *a = *b; 26 | *b = temp; 27 | } 28 | int main() 29 | { 30 | int array[100], i, size; 31 | printf("How many numbers you want to sort: "); // Enter the numbers to sort 32 | 33 | scanf("%d", &size); 34 | 35 | printf("\nEnter %d numbers : ", size); 36 | for (i = 0; i < size; i++) 37 | scanf("%d", &array[i]); 38 | bubblesort(array, size); 39 | printf("\nSorted array is "); 40 | 41 | for (i = 0; i < size; i++) 42 | printf(" %d ", array[i]); 43 | printf(" "); 44 | return 0; 45 | 46 | } 47 | -------------------------------------------------------------------------------- /Competitive Coding/Sorting/Bubble Sort/bubble_sort.cpp: -------------------------------------------------------------------------------- 1 | /* Part of Cosmos by OpenGenus Foundation */ 2 | #include 3 | #include 4 | #include 5 | 6 | void bubble_sort(std::vector &v) 7 | { 8 | for(int i=0; i < v.size(); ++i) 9 | for(int j=i+1; j < v.size(); ++j) 10 | { 11 | if (v[i] > v[j]) 12 | std::swap(v[i],v[j]); 13 | } 14 | } 15 | int main() 16 | { 17 | std::vector input_array; 18 | std::cout<<"Enter the number of items in the array: "; 19 | int array_size; 20 | std::cin>>array_size; 21 | for(int i=0;i>input_number; 24 | input_array.push_back(input_number); 25 | } 26 | bubble_sort(input_array); 27 | for(auto x :input_array) 28 | std::cout< 3 | #include 4 | #define RANGE 255 5 | 6 | 7 | void countSort(char arr[]) 8 | { 9 | 10 | char output[strlen(arr)]; 11 | 12 | // Create a count array to store count of inidividul 13 | 14 | int count[RANGE + 1], i; 15 | memset(count, 0, sizeof(count)); 16 | 17 | for(i = 0; arr[i]; ++i) 18 | ++count[arr[i]]; 19 | 20 | for (i = 1; i <= RANGE; ++i) 21 | count[i] += count[i-1]; 22 | 23 | // Build the output character array 24 | for (i = 0; arr[i]; ++i) 25 | { 26 | output[count[arr[i]]-1] = arr[i]; 27 | --count[arr[i]]; 28 | } 29 | 30 | // Copy the output array to arr, so that arr now 31 | // contains sorted characters 32 | for (i = 0; arr[i]; ++i) 33 | arr[i] = output[i]; 34 | } 35 | 36 | 37 | int main() 38 | { 39 | char arr[] = "chirayu";//"jain"; 40 | 41 | countSort(arr); 42 | 43 | printf("Sorted character array is %s", arr); 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /Competitive Coding/Sorting/Heap Sort/HeapSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define rep(i,a,b,c) for(i=a;ib;i+=c) 5 | 6 | //--------------------------------------Heapify 7 | void max_heapify(int *a, int i, int n) 8 | { 9 | int l=2*i+1; 10 | int r=2*i+2; 11 | int largest=0; 12 | if(l<=n and a[l]>a[i]) 13 | largest=l; 14 | else 15 | largest=i; 16 | if(r<=n and a[r]>a[largest]) 17 | largest=r; 18 | if(largest!=i) 19 | { 20 | swap(a[largest],a[i]); 21 | max_heapify(a,largest,n); 22 | } 23 | } 24 | //---------------------------------Build max Heap 25 | void build_maxheap(int *a, int n) 26 | { 27 | int i; 28 | repp(i,n/2,-1,-1) 29 | { 30 | max_heapify(a,i,n); 31 | } 32 | } 33 | 34 | //-----------------------------------HeapSort 35 | void heapsort(int *a, int n) 36 | { 37 | int i; 38 | build_maxheap(a,n); 39 | repp(i,n,-1,-1) 40 | { 41 | swap(a[0],a[i]); 42 | n--; 43 | max_heapify(a,0,n); 44 | } 45 | } 46 | 47 | int main() 48 | { 49 | int n, i, x; 50 | cout<<"Enter no of elements of array\n"; 51 | cin>>n; 52 | 53 | //Dynamic Memory Allocation 54 | int *dynamic; 55 | dynamic = new int[n]; 56 | 57 | //Input Of Elements 58 | cout<<"Enter the elements of array :\n"; 59 | rep(i,0,n,1) 60 | cin>>dynamic[i]; 61 | 62 | heapsort(dynamic,n-1); 63 | //Sorted Array using heap sort 64 | cout<< "Sorted Sequence is : " ; 65 | 66 | rep(i,0,n,1) 67 | cout<< dynamic[i]<<"\t"; 68 | delete []dynamic; 69 | } -------------------------------------------------------------------------------- /Competitive Coding/Sorting/Heap Sort/Readme.md: -------------------------------------------------------------------------------- 1 | ## Documentation for HeapSort 2 | * Heap sort is a comparison based sorting technique based on Binary Heap data structure. 3 | * Heapsort is an in-place algorithm, but it is not a stable sort. 4 | * Heap Sort is one of the best sorting methods being in-place and with no quadratic worst-case scenarios. 5 | * In max-heaps, maximum element will always be at the root. Heap Sort uses this property of heap to sort the array. 6 | 7 | Heap sort algorithm is divided into two basic parts : 8 | 9 | * Creating a Heap of the unsorted list. 10 | 11 | * Then a sorted array is created by repeatedly removing the largest/smallest element from the heap, and inserting it into the array. 12 | 13 | * The heap is reconstructed after each removal. 14 | 15 | ### Complexity of HeapSort 16 | 17 | Here, Time complexity of heapify is O(logn) and time complexity of BUILD-MAX-HEAP(A) is O(n) and we run max_heapify N−1 times in heap_sort function, therefore complexity of heap_sort function in each case (Best, worst and average) is O(nlogn). 18 | 19 | * Time Complexity: O(nlogn) 20 | 21 | * Space Complexity: O(1) 22 | 23 | 24 | -------------------------------------------------------------------------------- /Competitive Coding/Sorting/Heap Sort/Sorting_heapsort_anim.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codeIIEST/Algorithms/85e3fee94db88b644a102898f889c97083191d35/Competitive Coding/Sorting/Heap Sort/Sorting_heapsort_anim.gif -------------------------------------------------------------------------------- /Competitive Coding/Sorting/Insertion_Sort/insertion_sort.c: -------------------------------------------------------------------------------- 1 | // INSERTION SORT 2 | 3 | #include 4 | 5 | int main(){ 6 | 7 | int i,j,s,temp,a[20]; 8 | 9 | printf("Enter total elements: "); 10 | scanf("%d",&s); 11 | 12 | printf("Enter %d elements: ",s); 13 | for(i=0;i=0) && (temp 3 | #include 4 | 5 | // Function to Merge Arrays L and R into A. 6 | // lefCount = number of elements in L 7 | // rightCount = number of elements in R. 8 | void Merge(int *A,int *L,int leftCount,int *R,int rightCount) { 9 | int i,j,k; 10 | 11 | // i - to mark the index of left aubarray (L) 12 | // j - to mark the index of right sub-raay (R) 13 | // k - to mark the index of merged subarray (A) 14 | i = 0; j = 0; k =0; 15 | 16 | while(i 2 | #include 3 | 4 | 5 | //quick Sort function to Sort Integer array list 6 | void quicksort(int array[], int firstIndex, int lastIndex) 7 | { 8 | //declaaring index variables 9 | int pivotIndex, temp, index1, index2; 10 | 11 | if(firstIndex < lastIndex) 12 | { 13 | //assigning first element index as pivot element 14 | pivotIndex = firstIndex; 15 | index1 = firstIndex; 16 | index2 = lastIndex; 17 | 18 | //Sorting in Ascending order with quick sort 19 | while(index1 < index2) 20 | { 21 | while(array[index1] <= array[pivotIndex] && index1 < lastIndex) 22 | { 23 | index1++; 24 | } 25 | while(array[index2]>array[pivotIndex]) 26 | { 27 | index2--; 28 | } 29 | 30 | if(index1 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | namespace alg { 12 | /** 13 | * couting sort 14 | */ 15 | static void radix_(int byte, const unsigned N, const uint32_t *source, uint32_t *dest) { 16 | unsigned count[256]; 17 | unsigned index[256]; 18 | memset(count, 0, sizeof (count)); 19 | 20 | unsigned i; 21 | for(i=0; i>(byte*8))&0xff]++; 23 | 24 | index[0]=0; 25 | for(i=1; i<256; ++i) 26 | index[i] = index[i-1] + count[i-1]; 27 | 28 | for(i=0; i>(byte*8))&0xff]++] = source[i]; 30 | } 31 | 32 | /** 33 | * radix sort a given unsigned 32-bit integer array of size N 34 | */ 35 | static void radix_sort(uint32_t *source, const unsigned N) { 36 | uint32_t * temp = new uint32_t[N]; 37 | radix_(0, N, source, temp); 38 | radix_(1, N, temp, source); 39 | radix_(2, N, source, temp); 40 | radix_(3, N, temp, source); 41 | 42 | delete [] temp; 43 | } 44 | 45 | /** 46 | * check whether the array is in order 47 | */ 48 | static void check_order(const uint32_t *data, unsigned N) { 49 | for(--N ; N > 0; --N, ++data) 50 | assert(data[0] <= data[1]); 51 | } 52 | } 53 | 54 | #endif // 55 | 56 | 57 | -------------------------------------------------------------------------------- /Competitive Coding/Sorting/Selection_Sort/selection_sort.c: -------------------------------------------------------------------------------- 1 | #Selection Sort 2 | 3 | #include 4 | int main(){ 5 | 6 | int s,i,j,temp,a[20]; 7 | 8 | printf("Enter total elements: "); // total no of elements 9 | scanf("%d",&s); 10 | 11 | printf("Enter %d elements: ",s); // the elements 12 | for(i=0;ia[j]){ 18 | temp=a[i]; // Compare between 2 consecutive elements and swap them if they are not in ascending order 19 | a[i]=a[j]; 20 | a[j]=temp; 21 | } 22 | } 23 | } 24 | 25 | printf("After sorting is: "); 26 | for(i=0;i 0): #Condition runs until there's a gap 12 | for startposition in range(sublistcount): 13 | gapInsertionSort(test,startposition,sublistcount) 14 | print("After increments of size",sublistcount,"The list is",test) 15 | sublistcount = sublistcount // 2 #value os sublistcount changes after every iteration 16 | 17 | def gapInsertionSort(test,start,gap): #Function which sorts the sublists 18 | for i in range(start+gap,len(test),gap): 19 | currentvalue = test[i] 20 | position = i 21 | while(position>=gap and test[position-gap]>currentvalue): 22 | test[position]=test[position-gap] #changes in values occurs here due to sorting 23 | position = position-gap 24 | test[position]=currentvalue 25 | 26 | if __name__=="__main__": 27 | test = [99,109,29,89,44,98,20,55,31] 28 | shellSort(test) 29 | print test 30 | -------------------------------------------------------------------------------- /Competitive Coding/Strings/String Search/Knuth-Morris-Pratt_Algorithm.cpp: -------------------------------------------------------------------------------- 1 | //C++ code to find a pattern in a given text using KMP algorithm in linear time. 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | string text; 9 | string pattern; 10 | 11 | cin>>text;//inputting text 12 | cout<>pattern;//inputting pattern 15 | cout<text_length)//if pattern_length is greater than text it is not possible to find pattern in text. 21 | { 22 | cout<<"Not Found"<= 0: 6 | if string[index + length] == string[index - length]: 7 | length += 1 8 | else: 9 | break 10 | return length - 1 11 | 12 | def interleave(string): 13 | ret = [] 14 | for s in string: 15 | ret.extend(['#', s]) 16 | ret.append('#') 17 | return ''.join(ret) 18 | ''' Find longest palindrome number ''' 19 | def manacher(string): 20 | right = 0 21 | center = 0 22 | string = interleave(string) 23 | P = map(lambda e: 0, xrange(len(string))) 24 | for i in xrange(1, len(string)): 25 | mirror = 2*center - i 26 | if i + P[mirror] <= right and mirror >= len(string) - i: 27 | P[i] = P[mirror] 28 | else: 29 | plength = get_palindrome_length(string, i) 30 | P[i] = plength 31 | if plength > 1: 32 | center = int(i) 33 | right = center + plength 34 | return [e/2 for e in P] 35 | ''' Return the palindrome sub-string ''' 36 | def get_palindrome_number(string): 37 | return sum(manacher(string)) 38 | -------------------------------------------------------------------------------- /Competitive Coding/Strings/String Search/Manachar_algorithm/manchar_algorithm.md: -------------------------------------------------------------------------------- 1 | # Manachar's Algorithm 2 | 3 | Manacher's algorithm is a very handy algorithm with a short implementation that 4 | can make many programming tasks, such as finding the number of palindromic substrings 5 | or finding the longest palindromic substring, very easy and efficient. The running 6 | time of Manacher's algorithm is *O(N)* where *N* is the length of the input string. 7 | 8 | ## Implementation 9 | 10 | Let: 11 | 12 | 1. s be a string of N characters 13 | 14 | 2. s2 be a derived string of s, comprising N * 2 + 1 elements, with each element 15 | corresponding to one of the following: the N characters in s, the N-1 boundaries 16 | among characters, and the boundaries before and after the first and last character 17 | respectively 18 | 19 | 3. A boundary in s2 is equal to any other boundary in s2 with respect to element 20 | matching in palindromic length determination 21 | 22 | 4. p be an array of palindromic span for each element in s2, from center to either 23 | outermost element, where each boundary is counted towards the length of a palindrome 24 | (e.g. a palindrome that is three elements long has a palindromic span of 1) 25 | 26 | 5. c be the position of the center of the palindrome currently known to include a 27 | boundary closest to the right end of s2 (i.e., the length of the palindrome = p[c]*2+1) 28 | 29 | 6. r be the position of the right-most boundary of this palindrome (i.e., r = c + p[c]) 30 | 31 | 7. i be the position of an element (i.e., a character or boundary) in s2 whose palindromic 32 | span is being determined, with i always to the right of c 33 | 34 | 8. i2 be the mirrored position of i around c (e.g., {i, i2} = {6, 4}, {7, 3}, {8, 2},… when c = 5 (i.e., i2 = c * 2 - i) 35 | -------------------------------------------------------------------------------- /Competitive Coding/Strings/String Search/Z-algorithm/Readme.md: -------------------------------------------------------------------------------- 1 | # Z Algorithm 2 | 3 | This algorithm finds all occurrences of a pattern in a text in linear time. Let length of text be n and of pattern be m, then total time taken is O(m + n) with linear space complexity. Now we can see that both time and space complexity is same as KMP algorithm but this algorithm is Simpler to understand. 4 | 5 | In this algorithm, we construct a Z array. 6 | 7 | # What is Z array? 8 | 9 | For a string str[0..n-1], Z array is of same length as string. An element Z[i] of Z array stores length of the longest substring starting from str[i] which is also a prefix of str[0..n-1]. The first entry of Z array is meaning less as complete string is always prefix of itself. 10 | Example: 11 | Index 0 1 2 3 4 5 6 7 8 9 10 11 12 | Text a a b c a a b x a a a z 13 | Z values X 1 0 0 3 1 0 0 2 2 1 0 14 | 15 | # How to construct Z array? 16 | 17 | The idea is to maintain an interval [L, R] which is the interval with max R 18 | such that [L,R] is prefix substring (substring which is also prefix). 19 | 20 | Steps for maintaining this interval are as follows – 21 | 22 | 1) If i > R then there is no prefix substring that starts before i and 23 | ends after i, so we reset L and R and compute new [L,R] by comparing 24 | str[0..] to str[i..] and get Z[i] (= R-L+1). 25 | 26 | 2) If i <= R then let K = i-L, now Z[i] >= min(Z[K], R-i+1) because 27 | str[i..] matches with str[K..] for atleast R-i+1 characters (they are in 28 | [L,R] interval which we know is a prefix substring). 29 | Now two sub cases arise – 30 | a) If Z[K] < R-i+1 then there is no prefix substring starting at 31 | str[i] (otherwise Z[K] would be larger) so Z[i] = Z[K] and 32 | interval [L,R] remains same. 33 | b) If Z[K] >= R-i+1 then it is possible to extend the [L,R] interval 34 | thus we will set L as i and start matching from str[R] onwards and 35 | get new R then we will update interval [L,R] and calculate Z[i] (=R-L+1) 36 | 37 | The algorithm runs in linear time because we never compare character less than R and with matching we increase R by one so there are at most T comparisons. In mismatch case, mismatch happen only once for each i (because of which R stops), that’s another at most T comparison making overall linear complexity. 38 | -------------------------------------------------------------------------------- /Competitive Coding/Strings/String Search/Z-algorithm/z-algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define fastio ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0) 4 | #define md 1000000007 5 | #define ll long long int 6 | #define vi vector 7 | #define vll vector 8 | #define pb push_back 9 | #define all(c) (c).begin(),(c).end() 10 | template< class T > T max2(const T &a,const T &b) {return (a < b ? b : a);} 11 | template< class T > T min2(const T &a,const T &b) {return (a > b ? b : a);} 12 | template< class T > T max3(const T &a, const T &b, const T &c) { return max2(a, max2(b, c)); } 13 | template< class T > T min3(const T &a, const T &b, const T &c) { return min2(a, min2(b, c)); } 14 | template< class T > T gcd(const T a, const T b) { return (b ? gcd(b, a%b) : a); } 15 | template< class T > T lcm(const T a, const T b) { return (a / gcd(a, b) * b); } 16 | template< class T > T mod(const T &a, const T &b) { return (a < b ? a : a % b); } 17 | typedef pair pi; 18 | int main() 19 | { 20 | fastio; 21 | string txt; 22 | string pat; 23 | getline(cin,txt);//getline() reads the complete line in contrary to the traditional cin function which reads just the string before any spaces 24 | getline(cin,pat); 25 | int n = txt.length(); 26 | int pat_len = pat.length(); 27 | string str = pat + "$" + txt;//This is the new string that is formed after merging the pattern, '$' and txt string . we can use any other symbol instead of '$'.I have used dollar sign because it occurs rarely in the txt string 28 | 29 | int len = n+pat_len +1;//length of the total output string 30 | int z_val[len]={0}; 31 | int left =0;//left index of the z box 32 | int right =0;//right index of the z box 33 | int count=0;//count of the match 34 | for(int i=1;i1) 38 | { 39 | left =i; 40 | right = i + count-2; 41 | } 42 | 43 | 44 | if(count<=1) 45 | { 46 | count=0; 47 | for(int j=0;j 2 | # include 3 | # include 4 | # define NO_OF_CHARS 256 5 | 6 | int 7 | max(int a, int b) 8 | { 9 | return ((a > b) ? a: b); 10 | } 11 | 12 | 13 | void 14 | badCharHeuristic(char *str, int size, 15 | int badchar[NO_OF_CHARS]) 16 | { 17 | int i; 18 | 19 | for (i = 0; i < NO_OF_CHARS; i++) 20 | badchar[i] = -1; 21 | 22 | 23 | for (i = 0; i < size; i++) 24 | badchar[(int) str[i]] = i; 25 | } 26 | 27 | void 28 | search(char *txt, char *pat) 29 | { 30 | int m = strlen(pat); 31 | int n = strlen(txt); 32 | 33 | int badchar[NO_OF_CHARS]; 34 | badCharHeuristic(pat, m, badchar); 35 | int s = 0; 36 | while (s <= (n - m)) { 37 | int j = m-1; 38 | while(j >= 0 && pat[j] == txt[s+j]) 39 | j--; 40 | if (j < 0) { 41 | printf("\n pattern occurs at shift = %d", s); 42 | s += (s+m < n) ? m-badchar[txt[s+m]] : 1; 43 | 44 | } else 45 | s += max(1, j - badchar[txt[s+j]]); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Competitive Coding/Tree/Binary Indexed Tree/Reference.txt: -------------------------------------------------------------------------------- 1 | Here are some websites/blogs which inspired and motivated this concept in me. 2 | https://kartikkukreja.wordpress.com/2013/12/02/range-updates-with-bit-fenwick-tree/ 3 | http://zobayer.blogspot.in/2013/11/various-usage-of-bit.html 4 | -------------------------------------------------------------------------------- /Competitive Coding/Tree/Binary Indexed Tree/SPOJ_ctrick.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | #define lli long long int 8 | #define Min(a,b) (a 0){ 18 | sum += T[index] ; 19 | index = index - (index&(-1*index)); 20 | } 21 | return sum ; 22 | } 23 | void update(lli T[] , lli n , lli index , lli value ){ 24 | index++; 25 | while(index <= n){ 26 | T[index] += value ; 27 | index = index + (index&(-1*index)); 28 | } 29 | } 30 | lli * binary_indexed_tree(lli n){ 31 | lli i ; 32 | lli* T =(lli *) malloc(sizeof(lli)*200002) ; 33 | for(i = 1 ; i <= n+1 ; i++) 34 | { 35 | T[i] = 0 ; 36 | } 37 | for(i = 0 ; i < n ; i++) 38 | { 39 | update(T,n,i,1) ; 40 | } 41 | return T ; 42 | } 43 | void renew(lli* T,lli n) 44 | { 45 | lli i ; 46 | for(i = 1 ; i <= n+1 ; i++) 47 | { 48 | T[i] = 0 ; 49 | } 50 | for(i = 0 ; i < n ; i++) 51 | { 52 | update(T,n,i,1) ; 53 | } 54 | } 55 | 56 | lli modified_binary_search(lli * T, lli val, lli start , lli end) 57 | { 58 | lli mid = (start+end)/2 ; 59 | lli mid_sum = sum(T,mid) ; 60 | if((mid_sum == val)&&(hash_array_mod[mid+1] == 0)) 61 | return mid; 62 | else if( (mid_sum > val) || ((mid_sum == val)&&(hash_array_mod[mid+1] != 0)) ) 63 | { 64 | return modified_binary_search(T,val,start,mid-1); 65 | } 66 | else 67 | { 68 | return modified_binary_search(T,val,mid+1,end); 69 | } 70 | } 71 | int main() { 72 | lli test,n,i,j,ans,current_pos,next_pos_sum,next_pos,count,free_space_total; 73 | lli a[200002]; 74 | cin>>test; 75 | lli* T = binary_indexed_tree(n); 76 | while(test--) 77 | { 78 | cin>>n; 79 | //cin>>query; 80 | if(n == 1) 81 | { 82 | cout<<"1"< 3 | #include 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | #define lli long long int 9 | #define Min(a,b) (a s ; i--) 13 | 14 | //lli sum( lli index) : returns of arr[index]+arr[index-1]..arr[0] 15 | 16 | //void update( lli n , lli index , lli value ) : adds v to arr[index] 17 | 18 | 19 | lli T[100002]={0} ; 20 | lli sum(lli index){ 21 | lli sum = 0; 22 | index+=1; 23 | while(index > 0){ 24 | sum += T[index] ; 25 | index = index - (index&(-1*index)); 26 | } 27 | return sum ; 28 | } 29 | void update(lli n , lli index , lli value ){ 30 | index++; 31 | while(index <= n){ 32 | T[index] += value ; 33 | index = index + (index&(-1*index)); 34 | } 35 | } 36 | void binary_indexed_tree(lli *a, lli n){ 37 | lli i ; 38 | for(i = 1 ; i <= n+1 ; i++) 39 | { 40 | T[i] = 0 ; 41 | } 42 | //To be Uncommented as per the need 43 | /*for(i = 0 ; i < n ; i++) 44 | { 45 | update(n,i,a[i]) ; 46 | }*/ 47 | } 48 | int main() { 49 | lli test,n,i,j,inversions,position,option,ans,p,q,v; 50 | lli arr[100002]; 51 | lli brr[100002]; 52 | cin>>test; 53 | while(test--) 54 | { 55 | inversions = 0; 56 | cin>>n; 57 | fr(i,0,n) 58 | { 59 | cin>>arr[i]; 60 | brr[i] = arr[i] ; 61 | } 62 | sort(brr,brr+n); 63 | fr(i,0,n) 64 | { 65 | position = ( lli )(lower_bound(brr,brr+n,arr[i])-brr); 66 | arr[i] = position+1 ; 67 | } 68 | binary_indexed_tree(arr,n); 69 | ufr(i,n-1,-1) 70 | { 71 | inversions += sum(arr[i]-1); 72 | update(n,arr[i],1); 73 | } 74 | cout< 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | #define lli long long int 8 | #define Min(a,b) (a 0){ 16 | sum += T[index] ; 17 | index = index - (index&(-1*index)); 18 | } 19 | return sum ; 20 | } 21 | void update(lli n , lli index , lli value ){ 22 | index++; 23 | while(index <= n){ 24 | T[index] += value ; 25 | index = index + (index&(-1*index)); 26 | } 27 | } 28 | lli * binary_indexed_tree(lli *a, lli n){ 29 | lli i ; 30 | for(i = 1 ; i <= n+1 ; i++) 31 | { 32 | T[i] = 0 ; 33 | } 34 | for(i = 0 ; i < n ; i++) 35 | { 36 | update(n,i,a[i]) ; 37 | } 38 | return T ; 39 | } 40 | int main() { 41 | lli test,n,i,j,query,option,ans,p,q,v; 42 | lli arr[200002]; 43 | cin>>test; 44 | while(test--) 45 | { 46 | cin>>n; 47 | cin>>query; 48 | fr(i,0,n) 49 | { 50 | arr[i] = 0; 51 | } 52 | binary_indexed_tree(arr,n); 53 | while(query--) 54 | { 55 | cin>>option>>p>>q ; 56 | p--; 57 | q--; 58 | if(option == 0) 59 | { 60 | cin>>v; 61 | update(n,p,v); 62 | if(q != n-1) 63 | update(n,q+1,-1*v); 64 | } 65 | else 66 | { 67 | if(p == 0) 68 | ans = sum(q); 69 | else 70 | ans = sum(q)-sum(p-1) ; 71 | cout< 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | #define lli long long int 8 | #define Min(a,b) (a 0){ 16 | sum += T[index] ; 17 | index = index - (index&(-1*index)); 18 | } 19 | return sum ; 20 | } 21 | void update(lli T[] , lli n , lli index , lli value ){ 22 | index++; 23 | while(index <= n){ 24 | T[index] += value ; 25 | index = index + (index&(-1*index)); 26 | } 27 | } 28 | lli * binary_indexed_tree(lli n){ 29 | lli i ; 30 | lli* T =(lli *) malloc(sizeof(lli)*200002) ; 31 | for(i = 1 ; i <= n+1 ; i++) 32 | { 33 | T[i] = 0 ; 34 | } 35 | // for(i = 0 ; i < n ; i++) 36 | // { 37 | // update(T,n,i,a[i]) ; 38 | // } 39 | return T ; 40 | } 41 | int main() { 42 | lli test,n,i,j,query,option,ans,p,q,v; 43 | lli arr[200002]; 44 | cin>>test; 45 | while(test--) 46 | { 47 | cin>>n; 48 | cin>>query; 49 | fr(i,0,n) 50 | { 51 | arr[i] = 0; 52 | } 53 | lli* T1 = binary_indexed_tree(n); 54 | lli* T2 = binary_indexed_tree(n); 55 | while(query--) 56 | { 57 | cin>>option>>p>>q ; 58 | p--; 59 | q--; 60 | if(option == 0) 61 | { 62 | cin>>v; 63 | update(T1,n,p,v); 64 | update(T1,n,q+1,-v); 65 | update(T2,n,p,v*(p-1)); 66 | update(T2,n,q+1,-v*q); 67 | } 68 | else 69 | { 70 | ans = sum(T1,q)*q-sum(T2,q)-sum(T1,p-1)*(p-1)+sum(T2,p-1) ; 71 | cout< 5 | #include 6 | /*Creating the structure of binary tree node having data amd pointers to left 7 | and right child*/ 8 | typedef struct Node 9 | { 10 | int data; 11 | struct Node* left; 12 | struct Node* right; 13 | 14 | }T; 15 | //Function Prototypes 16 | T* newnode(int); 17 | void LevelOrder(T*); 18 | T* printGivenLevel(T*,int); 19 | int height(T*); 20 | 21 | int main() 22 | { 23 | T* root=newnode(1);//Creating the tree 24 | root->left=newnode(3); 25 | root->right=newnode(5); 26 | root->left->left=newnode(6); 27 | root->right->right=newnode(4); 28 | root->left->right=newnode(12); 29 | LevelOrder(root); 30 | 31 | } 32 | //Function to allocates a new node, and initiales the left and right child with NULL 33 | T* newnode(int value) 34 | { 35 | T* temp=(T*)malloc(sizeof(T)); 36 | temp->data=value; 37 | temp->left=NULL; 38 | temp->right=NULL; 39 | return temp; 40 | 41 | } 42 | //Function that drives the level order traversal of the tree 43 | void LevelOrder(T* root) 44 | { 45 | int level; 46 | for(level=1;level<=height(root);level++) 47 | {printGivenLevel(root,level);} 48 | } 49 | /*Computes the height of the tree, which is the length of path from the root to 50 | to the deepest leaf node*/ 51 | int height(T* root) 52 | { 53 | if(root==NULL) 54 | return 0; 55 | int lh=height(root->left); 56 | int rh=height(root->right); 57 | 58 | return lh>rh?lh+1:rh+1; 59 | } 60 | 61 | //Prints the nodes in each level of the tree 62 | T* printGivenLevel(T* root,int level) 63 | { 64 | if(root==NULL)return NULL; 65 | if(level==1)printf("%d ",root->data); 66 | else{ 67 | printGivenLevel(root->left,level-1); 68 | printGivenLevel(root->right,level-1); 69 | 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /Competitive Coding/Tree/Binary Tree/postorder_traversal/readme.md: -------------------------------------------------------------------------------- 1 | # Postorder Traversal 2 | 3 | ![alt text](https://www.java2blog.com/wp-content/uploads/2014/07/PostOrderTraversalBinaryTree-1.jpg) 4 | 5 | Algorithm Postorder(tree) 6 | * Traverse the left subtree, i.e., call Postorder(left-subtree) 7 | * Traverse the right subtree, i.e., call Postorder(right-subtree) 8 | * Visit the root. 9 | -------------------------------------------------------------------------------- /Competitive Coding/Tree/Binary Tree/preorder_traversal/readme.md: -------------------------------------------------------------------------------- 1 | # Preorder Traversal 2 | 3 | ![alt text](https://javabeat.net/wp-content/uploads/2013/11/BST_Preorder.jpg) 4 | 5 | Algorithm Preorder(tree) 6 | * Visit the root. 7 | * Traverse the left subtree, i.e., call Preorder(left-subtree) 8 | * Traverse the right subtree, i.e., call Preorder(right-subtree) 9 | -------------------------------------------------------------------------------- /Competitive Coding/Tree/Binary Tree/segment-trees/segment-trees_readme.md: -------------------------------------------------------------------------------- 1 | # Segment Trees 2 | In Computer science, a segment tree is a tree data structure used for storing information about intervals, or segments. It allows querying which of the stored segments contain a given point. It is, in principle, a static structure; that is, it's a structure that cannot be modified once it's built. A similar data structure is the interval tree. 3 | 4 | A segment tree for a set I of n intervals uses O(n log n) storage and can be built in O(n log n) time. Segment trees support searching for all the intervals that contain a query point in O(log n + k), k being the number of retrieved intervals or segments.[1] 5 | Applications of the segment tree are in the areas of computational geometry, and geographic information systems. 6 | The segment tree can be generalized to higher dimension spaces as well. 7 | 8 | Below is a example of segment tree: 9 | 10 | ![alt text](http://www.geeksforgeeks.org/wp-content/uploads/segment-tree1.png) 11 | 12 | # SEGMENT TREES DESCRIPTION 13 | Given a set I of intervals, or segments, a segment tree T for I is structured as follows: 14 | T is a binary tree. 15 | Its leaves correspond to the elementary intervals induced by the endpoints in I, in an ordered way: the leftmost leaf corresponds to the leftmost interval, and so on. The elementary interval corresponding to a leaf v is denoted Int(v). 16 | 17 | The internal nodes of T correspond to intervals that are the union of elementary intervals: the interval Int(N) corresponding to node N is the union of the intervals corresponding to the leaves of the tree rooted at N. That implies that Int(N) is the union of the intervals of its two children. 18 | 19 | Each node or leaf v in T stores the interval Int(v) and a set of intervals, in some data structure. This canonical subset of node v contains the intervals [x, x′] from I such that [x, x′] contains Int(v) and does not contain Int(parent(v)). That is, each node in T stores the segments that span through its interval, but do not span through the interval of its parent. 20 | 21 | # Construction of Segment trees 22 | This section describes the construction of a segment tree in a one-dimensional space. 23 | A segment tree from the set of segments I, can be built as follows. First, the endpoints of the intervals in I are sorted. The elementary intervals are obtained from that. Then, a balanced binary tree is built on the elementary intervals, and for each node v it is determined the interval Int(v) it represents. It remains to compute the canonical subsets for the nodes. To achieve this, the intervals in I are inserted one by one into the segment tree. An interval X = [x, x′] can be inserted in a subtree rooted at T, using the following procedure: 24 | 25 | * If Int(T) is contained in X then store X at T, and finish. 26 | Else: 27 | * If X intersects the interval of the left child of T, then insert X in that child, recursively. 28 | * If X intersects the interval of the right child of T, then insert X in that child, recursively. 29 | The complete construction operation takes O(nlogn) time, n being the number of segments in I. 30 | 31 | # Query 32 | This section describes the query operation of a segment tree in a one-dimensional space. 33 | A query for a segment tree, receives a point qx(should be one of the leaves of tree), and retrieves a list of all the segments stored which contain the point qx. 34 | Formally stated; given a node (subtree) v and a query point qx, the query can be done using the following algorithm: 35 | 36 | Report all the intervals in I(v). 37 | * If v is not a leaf: 38 | * If qx is in Int(left child of v) then 39 | Perform a query in the left child of v. 40 | * If qx is in Int(right child of v) then 41 | Perform a query in the right child of v. 42 | 43 | In a segment tree that contains n intervals, those containing a given query point can be reported in O(logn + k) time, where k is the number of reported intervals. 44 | -------------------------------------------------------------------------------- /Competitive Coding/Tree/Minimum Spanning Tree/Kruskal/KruskalMST.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define lli long long int 4 | #define infinite numeric_limits::max() 5 | #define Min(a,b) ((a)<(b)?(a):(b)) 6 | #define Max(a,b) ((a)>(b)?(a):(b)) 7 | #define fr(i,j,s) for(i = j ; i < s ; i++) 8 | #define ifr(i,j,s) for(i = j ; i >= s , i--) 9 | struct edge 10 | { 11 | lli wt; 12 | int src; 13 | int dest; 14 | }; 15 | struct Graph 16 | { 17 | int V; 18 | int E; 19 | struct edge* array; 20 | }; 21 | struct sub 22 | { 23 | int parent; 24 | int rank; 25 | }; 26 | bool comp(struct edge &a, struct edge &b) 27 | { 28 | return ((a.wt)<(b.wt)); 29 | } 30 | int find(struct sub subset[], int i) 31 | { 32 | if(subset[i].parent != i) 33 | { 34 | subset[i].parent = find(subset,subset[i].parent); 35 | } 36 | return subset[i].parent ; 37 | } 38 | void Union(struct sub subset[] , int x, int y) 39 | { 40 | int xfather = find(subset,x); 41 | int yfather = find(subset,y); 42 | if(subset[xfather].rankV = V ; 57 | G->E = E ; 58 | G->array = (struct edge*)malloc(E*sizeof(struct edge)); 59 | return G ; 60 | } 61 | void KruskalMST(struct Graph *G) 62 | { 63 | int i ; 64 | int V = G->V ; 65 | int E = G->E ; 66 | lli sum = 0 ; 67 | struct sub subset[G->V]; 68 | fr(i,0,V) 69 | { 70 | subset[i].parent = i ; 71 | subset[i].rank = 0 ; 72 | } 73 | sort(G->array, (G->array)+G->E,comp); 74 | fr(i,0,E) 75 | { 76 | int x = find(subset,G->array[i].src); 77 | int y = find(subset,G->array[i].dest); 78 | if(x==y) 79 | continue; 80 | else 81 | { 82 | Union(subset,G->array[i].src,G->array[i].dest); 83 | sum+=G->array[i].wt; 84 | } 85 | } 86 | cout<>v>>e; 93 | struct Graph* G = createGraph(v,e); 94 | int ed = 0; 95 | int temp = e ; 96 | while(e--) 97 | { 98 | cin>>a>>b>>wt; 99 | G->array[ed].src=a-1; 100 | G->array[ed].dest=b-1; 101 | G->array[ed].wt=wt; 102 | ed++; 103 | } 104 | cin>>a; 105 | KruskalMST(G); 106 | return 0; 107 | } 108 | -------------------------------------------------------------------------------- /Competitive Coding/Tree/Minimum Spanning Tree/readme.md: -------------------------------------------------------------------------------- 1 | ## Minimum spanning tree ## 2 | 3 | A minimum spanning tree (MST) or minimum weight spanning tree is a subset of the edges of 4 | a connected, edge-weighted (un)directed graph that connects all the vertices together, 5 | without any cycles and with the minimum possible total edge weight. 6 | 7 | That is, it is a spanning tree whose sum of edge weights is as small as possible. 8 | 9 |

10 | 11 |

12 | 13 | > Properties : 14 | * A connected graph G can have more than one spanning tree. 15 | * All possible spanning trees of graph G, have the same number of edges and vertices. 16 | * Removing one edge from the spanning tree will make the graph disconnected, i.e. the spanning tree is minimally connected. 17 | * Adding one edge to the spanning tree will create a circuit or loop, i.e. the spanning tree is maximally acyclic. 18 | * A spanning tree does not have cycles and it cannot be disconnected. 19 | 20 | > Mathematical Properties of Spanning Tree : 21 | * Spanning tree has n-1 edges, where n is the number of nodes (vertices). 22 | * From a complete graph, by removing maximum e - n + 1 edges, we can construct a spanning tree. 23 | * A complete undirected graph can have maximum n^(n-2) number of spanning trees. 24 | 25 | > Application of Minimum spanning tree :- 26 | * Design of networks in telephone, electrical, hydraulic, TV cable, computer, road etc. 27 | * Cluster Analysis 28 | * Traveling salesman problem 29 | * Handwriting recognition 30 | 31 | > There are two most important & famous spanning tree algorithm : 32 | 1. Kruskal's Algorithm 33 | 2. Prim's Algorithm 34 | -------------------------------------------------------------------------------- /GFG Articles/prateekiiest/article.md: -------------------------------------------------------------------------------- 1 | GFG link 2 | -------------------------------------------------------------------------------- /Graphics Algos/Car Animation/README.md: -------------------------------------------------------------------------------- 1 | The car.c file is a program which shows an animation of a moving car. 2 | It has been drawn using the line function in the graphics library. 3 | 4 | line(x1,y1,x2,y2) 5 | where, x1,y1 ---- starting points of line 6 | and x2,y2 ------- ending points of the line. 7 | 8 | The animation takes place by the concept of translation. 9 | We've put the car in a for loop incrementing the values of x co-ordinates of all the line functions by i 10 | 11 | The final out put will look this way! 12 | 13 | ![screenshot from 2017-12-16 15-52-31](https://user-images.githubusercontent.com/26206171/34069730-d0f448d6-e27c-11e7-9a34-17603028a4ec.png) 14 | ![screenshot from 2017-12-16 15-52-35](https://user-images.githubusercontent.com/26206171/34069731-d5130948-e27c-11e7-882e-2d9ca7c00f0b.png) 15 | ![screenshot from 2017-12-16 15-52-37](https://user-images.githubusercontent.com/26206171/34069732-d5d02c76-e27c-11e7-99ba-7138d97e4877.png) 16 | ![screenshot from 2017-12-16 15-52-40](https://user-images.githubusercontent.com/26206171/34069733-d80b1ae6-e27c-11e7-96b5-715bf9601b95.png) 17 | -------------------------------------------------------------------------------- /Graphics Algos/Car Animation/car.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int gd = DETECT, gm; 7 | int i, maxx, midy; 8 | 9 | /* initialize graphic mode */ 10 | initgraph(&gd, &gm, "NULL"); 11 | /* maximum pixel in horizontal axis */ 12 | maxx = getmaxx(); 13 | /* mid pixel in vertical axis */ 14 | midy = getmaxy()/2; 15 | 16 | for (i=0; i < maxx-150; i=i+5) /* loop is run for showing the animation */ 17 | { 18 | /* clears screen */ 19 | cleardevice(); 20 | 21 | /* draw a white road */ 22 | setcolor(WHITE); /* color of the road */ 23 | line(0, midy + 37, maxx, midy + 37); 24 | 25 | /* Draw Car */ 26 | setcolor(YELLOW); /* color of the car body */ 27 | 28 | /* car body */ 29 | line(i, midy + 23, i, midy); /* draws the left most line parallel to y-axis */ 30 | line(i, midy, 40 + i, midy - 20); 31 | line(40 + i, midy - 20, 80 + i, midy - 20); /* draws the roof of the car*/ 32 | line(80 + i, midy - 20, 100 + i, midy); /* draws the front mirror part of the car */ 33 | line(100 + i, midy, 120 + i, midy); 34 | line(120 + i, midy, 120 + i, midy + 23); 35 | line(0 + i, midy + 23, 18 + i, midy + 23); 36 | arc(30 + i, midy + 23, 0, 180, 12); /* draws the arc to accomodate the wheels */ 37 | line(42 + i, midy + 23, 78 + i, midy + 23); 38 | arc(90 + i, midy + 23, 0, 180, 12); /* draws the arc to accomodate the wheels */ 39 | line(102 + i, midy + 23, 120 + i, midy + 23); 40 | /* car body ends */ 41 | 42 | /* Draw Windows */ 43 | /* left window */ 44 | line(28 + i, midy, 43 + i, midy - 15); /* left part of left window */ 45 | line(43 + i, midy - 15, 57 + i, midy - 15); /* roof of the left window */ 46 | line(57 + i, midy - 15, 57 + i, midy); /* right part of left window */ 47 | line(57 + i, midy, 28 + i, midy); /* bottom part of the left window */ 48 | /* left window ends */ 49 | 50 | /* right window */ 51 | line(62 + i, midy - 15, 77 + i, midy - 15); /* left part of right window */ 52 | line(77 + i, midy - 15, 92 + i, midy); /* roof of the rightt window */ 53 | line(92 + i, midy, 62 + i, midy); /* right part of right window */ 54 | line(62 + i, midy, 62 + i, midy - 15); /* bottom part of the right window */ 55 | /* right window ends */ 56 | 57 | floodfill(5 + i, midy + 22, YELLOW); /* fills the whole car body with yellow color */ 58 | 59 | setcolor(BLUE); /* color of the wheels */ 60 | /* Draw Wheels */ 61 | circle(30 + i, midy + 25, 9); 62 | circle(90 + i, midy + 25, 9); 63 | floodfill(30 + i, midy + 25, BLUE); /* fills the left wheel with blue color */ 64 | floodfill(90 + i, midy + 25, BLUE); /* fills the right wheel with blue color */ 65 | 66 | /* Add delay of 0.1 milli seconds */ 67 | delay(100); /* to observe the animation */ 68 | } 69 | 70 | getch(); 71 | closegraph(); 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /Graphics Algos/README.md: -------------------------------------------------------------------------------- 1 | ## GRAPHICS ALGORITHMS 2 | 3 | This is a folder which contains graphics algorithms and their implementations. 4 | 5 | ### Robo.c 6 | 7 | The robo.c program is a program which helps you in drawing a robot. 8 | The robot is drawn around a reference point. The DDA Line Algorithm was used in making the program. 9 | The DDA Line algorithm exists inside the program in a function so you can have a look at what the DDA line algorithm is, 10 | inside this program itself.

11 | The image below shows the Output of the program! 12 | 13 | ![picture](https://user-images.githubusercontent.com/26206171/33807711-e08a11ca-de00-11e7-8635-78aa0f8a2884.png) 14 | -------------------------------------------------------------------------------- /Graphics Algos/robo.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | float FX,FY,BX,BY,ax,bx,ay,by; 4 | 5 | void DDALine(float x1,float y1,float x2,float y2) 6 | { 7 | float x,y,dx,dy,step; 8 | if(x1>x2 || y1>y2) 9 | { 10 | x1=x1+x2;x2=x1-x2;x1=x1-x2; // x1 x2 swap 11 | y1=y1+y2;y2=y1-y2;y1=y1-y2; // y1 y2 swap 12 | } 13 | dx=abs(x2-x1); //finding the positive difference between x1 and x2 14 | dy=abs(y2-y1); //finding positive difference between y1 and y2 15 | if(dx>=dy) 16 | step=dx; 17 | else 18 | step=dy; 19 | dx/=step; 20 | dy/=step; 21 | x=x1; 22 | y=y1; 23 | for(int i=0;i<=step;i++) 24 | { 25 | putpixel(x,y,WHITE); 26 | x+=dx; 27 | y+=dy; 28 | } 29 | } 30 | void DDARect(float x1,float y1,float x2,float y2) //Creating a rectangle using dda line 31 | { 32 | DDALine(x1,y1,x2,y1); 33 | DDALine(x2,y1,x2,y2); 34 | DDALine(x2,y2,x1,y2); 35 | DDALine(x1,y1,x1,y2); 36 | } 37 | void main( ) 38 | { 39 | BX=320; BY=240; FX=BX; FY=BY-60; //BX and BY are some constants to make sure we place the robo somewhere in the centre of screen 40 | int gd=DETECT,gm; // FX and FY are translating constants to make sure all parts of the body are drawns 41 | initgraph(&gd,&gm,"NULL"); 42 | //--Head 43 | //Cap 44 | circle(FX,FY-40,5); 45 | DDARect(FX-2.5,FY-25,FX+2.5,FY-35); 46 | arc(FX,FY-20,180,360,5); 47 | //Face 48 | DDARect(FX-20,FY+20,FX+20,FY-20);//Face Outline 49 | DDARect(FX-15,FY,FX-5,FY-10);//Left Eye 50 | DDARect(FX+5,FY,FX+15,FY-10);//Right Eye 51 | //Mouth 52 | DDARect(FX-10,FY+15,FX+10,FY+10); 53 | //TEETH 54 | DDARect(FX-2,FY+15,FX+2,FY+10); 55 | DDARect(FX-6,FY+15,FX+6,FY+10); 56 | //LEFT_EAR 57 | DDARect(FX-25,FY,FX-20,FY-10); 58 | DDARect(FX-30,FY-2.5,FX-25,FY-7.5); 59 | //RIGHT_EAR 60 | DDARect(FX+25,FY,FX+20,FY-10); 61 | DDARect(FX+25,FY-2.5,FX+30,FY-7.5); 62 | DDARect(BX-5,BY-30,BX+5,BY-40);//Neck 63 | //--BODY 64 | DDARect(BX-30,BY+30,BX+30,BY-30); // Body Outline 65 | DDARect(BX-20,BY+15,BX+20,BY-20); // Inner Square 66 | DDARect(BX-25,BY+70,BX-10,BY+30); // Left Leg 67 | arc(BX-17.5,BY+70,180,360,7.5); // Left Foot 68 | DDARect(BX+25,BY+70,BX+10,BY+30); // Right Leg 69 | arc(BX+17.5,BY+70,180,360,7.5); // Right Foot 70 | //Left_Hand 71 | ax=BX-47,ay=BY-5; //ax and bx become relative points to draw both hands 72 | bx=BX-47,by=BY+5; 73 | for(int i=0;i<10;i++) 74 | { 75 | putpixel(ax,ay,WHITE); 76 | putpixel(bx,by,WHITE); 77 | ax+=1.7; 78 | bx+=1.7; 79 | ay-=1; 80 | by-=1; 81 | } 82 | circle(BX-47,BY,5); 83 | //Right_Hand 84 | DDALine(BX+47,BY-5,BX+30,BY-15); 85 | DDALine(BX+47,BY+5,BX+30,BY-5); 86 | circle(BX+47,BY,5); 87 | ax=BX+47,ay=BY-5; 88 | bx=BX+47,by=BY+5; 89 | //END 90 | delay(5000); 91 | getch(); 92 | } 93 | -------------------------------------------------------------------------------- /ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## DESCRIPTION 4 | 5 | Please provide a short, clear description of the problem 6 | 7 | ## STEPS TO REPRODUCE 8 | 9 | Please list the steps to reproduce the above problem 10 | 11 | ## EXPECTED OUTCOME 12 | 13 | What did you expect to happen 14 | 15 | ## ACTUAL OUTCOME 16 | 17 | What actually happened 18 | 19 | ### Proposed Solution [optional] 20 | 21 | If you know how to solve the above, please provide details here. 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 codeIIEST 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Machine learning/ gradient descent/LinearReg.m: -------------------------------------------------------------------------------- 1 | %Gradient desecent for Linear regression model 2 | %used for training theta(parameter) 3 | %LinearReg train theta vector using training dataset 4 | %X is matrix m rows i.e. number of training examples 5 | % and n columns i.e. number of features. 6 | %y is vector of size m, containing actual values from dataset 7 | 8 | %Loading data 9 | data = load('filename.txt'); 10 | dim=size(data); 11 | num_row=dim(1,1); 12 | num_col=dim(1,2); 13 | 14 | for i=1:(num_col-1) 15 | if(i==1) 16 | X=data(:,1); 17 | else 18 | X=[X , data(:,i)]; 19 | end 20 | end; 21 | 22 | y=data(:,num_col); 23 | 24 | %adding a biased term in X matrix 25 | X=[ones(m,1) X]; 26 | 27 | %initialization of theta 28 | theta=zeros(size(X,2),1); 29 | 30 | %number of features 31 | num_fea=size(X,2) 32 | 33 | %numbers of training examples 34 | m=length(y); 35 | 36 | %Gradient desecent 37 | for j=1: max_iter 38 | h=(X*theta-y); 39 | for i=1: num_fea 40 | theta(i)=theta(i)-(learning_rate*(X(:,i)'*h)/m); 41 | end 42 | end 43 | -------------------------------------------------------------------------------- /Machine learning/ gradient descent/README.md: -------------------------------------------------------------------------------- 1 | # **Gradient desecent for linear regression** 2 | Gradient descent is one of most used algorithm in Machine Learning.Gradient descent is a first-order iterative optimization algorithm for finding the minimum of a function. To find a local minimum of a function using gradient descent. 3 | 4 | # Example 5 | ![image](gradient.png) 6 | 7 | Supoose we are at any point, and we want to minimize the cost function. Thus this can be achieve by taking derivative of cost function. 8 | The slope of the tangent will give a direction in which the value is decreases. Thus this algorithm make steps down the function. 9 | The size of each step is determine by the learning rate. 10 | 11 | # **Gradient descent for linear regression** 12 | In this model, gradient descent is used to calculating the theta vector(or parameter vector). Once the parameter vector is calculated using 13 | training examples, we can predict the output of unknown input. 14 | -------------------------------------------------------------------------------- /Machine learning/ gradient descent/gradient.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codeIIEST/Algorithms/85e3fee94db88b644a102898f889c97083191d35/Machine learning/ gradient descent/gradient.png -------------------------------------------------------------------------------- /Machine learning/EXPONENTIAL REGRESSION: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | #define f float 5 | void exponential(f x[], f y[], int n){ 6 | f Y[n],sumx=0,sumy=0,sumxy=0,sumx2=0; 7 | double a,b,A; 8 | for(int i=0;i<=n-1;i++) 9 | { 10 | Y[i]=log(y[i]); 11 | } 12 | for(int i=0;i<=n-1;i++) 13 | { 14 | sumx=sumx +x[i]; 15 | sumx2=sumx2 +x[i]*x[i]; 16 | sumy=sumy +Y[i]; 17 | sumxy=sumxy +x[i]*Y[i]; 18 | 19 | } 20 | A=((sumx2*sumy -sumx*sumxy)*1.0/(n*sumx2-sumx*sumx)*1.0); 21 | b=((n*sumxy-sumx*sumy)*1.0/(n*sumx2-sumx*sumx)*1.0); 22 | a=exp(A); 23 | printf("\n The curve is Y= %4.3fe^%4.3fX",a,b); 24 | } 25 | 26 | int main() 27 | { 28 | int i,n; 29 | cout<<"welcome to linear regression\n"; 30 | cout<<"enter number of data you want to enter\n"; 31 | cin>>n; 32 | f x[n],y[n]; 33 | cout<<"enter x variables\n"; 34 | for(i=0;i>x[i]; 35 | cout<<"enter y variables\n"; 36 | for(i=0;i>y[i]; 37 | exponential(x,y,n); 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /Machine learning/LINEAR REGRESSION: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | #define f float 5 | void linear(f x[],f y[],int n) 6 | { 7 | f cx=0,cy=0,sumxy=0,sumx2=0; 8 | double a,b; 9 | for(int i=0;i<=n-1;i++) 10 | { 11 | cx=cx+x[i]; 12 | sumx2=sumx2 +x[i]*x[i]; 13 | cy=cy+y[i]; 14 | sumxy=sumxy +x[i]*y[i]; 15 | 16 | } 17 | a=((sumx2*cy -cx*sumxy)*1.0/(n*sumx2-cx*cx)*1.0); 18 | b=((n*sumxy-cx*cy)*1.0/(n*sumx2-cx*cx)*1.0); 19 | printf("\n\nThe line is Y=%3.3f +%3.3f X",a,b); 20 | } 21 | int main() 22 | { 23 | int i,n; 24 | cout<<"welcome to linear regression\n"; 25 | cout<<"enter number of data you want to enter\n"; 26 | cin>>n; 27 | f x[n],y[n]; 28 | cout<<"enter x variables\n"; 29 | for(i=0;i>x[i]; 30 | cout<<"enter y variables\n"; 31 | for(i=0;i>y[i]; 32 | linear(x,y,n); 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /Machine learning/polynomial regression: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | #define f float 5 | void poly(float x[], float y[], int N){ 6 | int n; 7 | cout << "\nPlease enter the degress:\n"; 8 | cin >> n; 9 | 10 | double X[2*n+1]; //Array that will store the values of sigma(xi),sigma(xi^2),sigma(xi^3)....sigma(xi^2n) 11 | for (int i=0;i<2*n+1;i++) 12 | { 13 | X[i]=0; 14 | for (int j=0;j=0;i--) //back-substitution 50 | { //x is an array whose values correspond to the values of x,y,z.. 51 | a[i]=B[i][n]; //make the variable to be calculated equal to the rhs of the last equation 52 | for (int j=0;j>n; 71 | f x[n],y[n]; 72 | cout<<"enter x variables\n"; 73 | for(i=0;i>x[i]; 74 | cout<<"enter y variables\n"; 75 | for(i=0;i>y[i]; 76 | poly(x,y,n); 77 | return 0; 78 | } 79 | -------------------------------------------------------------------------------- /PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Thank you for your contribution. Please provide the details requested below. 2 | 3 | ## ISSUE NUMBER 4 | 5 | Please provide a link to the issue this pull request addresses. 6 | 7 | ## SHORT DESCRIPTION 8 | 9 | Please provide a short description of the changes. 10 | 11 | ## TESTING 12 | 13 | Please provide the necessary steps to test the solution. 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Algorithms 3 | 4 | 5 |
6 | 7 | [![Codacy Badge](https://api.codacy.com/project/badge/Grade/027cc235e9024d4da77ebd358ca7becf)](https://www.codacy.com/app/prateekkol21/Algorithms?utm_source=github.com&utm_medium=referral&utm_content=codeIIEST/Algorithms&utm_campaign=badger) [![Build status](https://ci.appveyor.com/api/projects/status/i6utrnqnasqguk2i?svg=true)](https://ci.appveyor.com/project/prateekiiest/algorithms) 8 | 9 | 10 | [![Join the chat at https://gitter.im/codeIIEST/Algorithms](https://badges.gitter.im/codeIIEST/Algorithms.svg)](https://gitter.im/codeIIEST/Algorithms?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) 11 | 12 | ---------------------------------------------------------------------------------------------- 13 | 14 | 15 | ![](https://github.com/codeIIEST/Algorithms/blob/master/algocodeiiest.jpg) 16 | 17 | ### About the Project 18 | 19 | This repository contains some of the most **intriguing and awesome algorithms** of daily life implemented in languages primarily in C/C++/Java/Python. 20 | 21 | -------------------------------------------------------------- 22 | 23 | ### Project Details 24 | The entire project is divided into 4 parts 25 | 26 | * Competitive Coding Algorithms and Data Structures 27 | * Security Algorithms 28 | * Machine Learning Algorithms 29 | * Statistical / Mathematical Algorithms 30 | 31 | ----------------------------------------------------------------- 32 | 33 | ### Contributing 34 | 35 | We would always encourage contribution from new developers. We hope with your contributions the project ecosystem will evolve much more in the future. 36 | 37 | For more details please see the [Contributing Guidelines](https://github.com/codeIIEST/Algorithms/blob/master/CONTRIBUTING.md). 38 | 39 | We maintain a curated list of issues under the [issues page](https://github.com/codeIIEST/Algorithms/issues). We encourage to start working with them. Please join the gitter channel for any doubts. 40 | 41 | --------------------------------------------------- 42 | 43 | ### Maintainers 44 | 45 | * [Manumeral](https://github.com/manumeral) 46 | * [smitbose](https://github.com/smitbose) 47 | 48 | -------------------------------------------------------------------------------- /Security Algorithms/Cryptography/Atbash_Cipher/Atbash_Cipher.cpp: -------------------------------------------------------------------------------- 1 | //Atbash cipher 2 | #include 3 | using namespace std; 4 | 5 | //Function that convert the message. 6 | string atbash(string msg) 7 | { 8 | /*This function takes msg as input and 9 | map it to its reverse alphabatically order.*/ 10 | 11 | string cipher; 12 | for(int i=0;i='A' && msg[i]<='Z') 17 | cipher=cipher+(char)('Z'-(msg[i]-'A')); 18 | else 19 | cipher=cipher+(char)('z'-(msg[i]-'a')); 20 | } 21 | return cipher; 22 | } 23 | 24 | //Main program. 25 | int main() 26 | { 27 | string text; 28 | cout<<"Enter the message to encrypt/decrypt---"<>text; 30 | cout<<"Converted message---"< 3 | #include 4 | #include 5 | #include //For map data structure 6 | using namespace std; 7 | 8 | //function for creating map structure 9 | map createMap() 10 | { 11 | // Decalaring map structure and Defination of map 12 | map decrypt; 13 | decrypt[".-"] = "A"; 14 | decrypt["-..."] = "B"; 15 | decrypt["-.-."] = "C"; 16 | decrypt["-.."] = "D"; 17 | decrypt["."] = "E"; 18 | decrypt["..-."] = "F"; 19 | decrypt["--."] = "G"; 20 | decrypt["...."] = "H"; 21 | decrypt[".."] = "I"; 22 | decrypt[".---"] = "J"; 23 | decrypt["-.-"] = "K"; 24 | decrypt[".-.."] = "L"; 25 | decrypt["--"] = "M"; 26 | decrypt["-."] = "N"; 27 | decrypt["---"] = "O"; 28 | decrypt[".--."] = "P"; 29 | decrypt["--.-"] = "Q"; 30 | decrypt[".-."] = "R"; 31 | decrypt["..."] = "S"; 32 | decrypt["-"] = "T"; 33 | decrypt["..-"] = "U"; 34 | decrypt["...-"] = "V"; 35 | decrypt[".--"] = "W"; 36 | decrypt["-..-"] = "X"; 37 | decrypt["-.--"] = "Y"; 38 | decrypt["--.."] = "Z"; 39 | decrypt[".----"] = "1"; 40 | decrypt["..---"] = "2"; 41 | decrypt["...--"] = "3"; 42 | decrypt["....-"] = "4"; 43 | decrypt["....."] = "5"; 44 | decrypt["-...."] = "6"; 45 | decrypt["--..."] = "7"; 46 | decrypt["---.."] = "8"; 47 | decrypt["---."] = "9"; 48 | decrypt["-----"] = "0"; 49 | return decrypt; 50 | } 51 | 52 | map decrypt=createMap(); 53 | // decryption Function 54 | void decryption(string msg) 55 | { 56 | string plain = "", tempPlain; 57 | for (int i = 0; i < msg.size(); i++) 58 | { 59 | if (msg[i] != ' ' && msg[i] != '\t' && msg[i] != '\n') 60 | { 61 | tempPlain.append(1, msg[i]); 62 | } 63 | if ( msg[i] == ' ' || i==msg.size()-1) 64 | { 65 | plain=plain +decrypt[tempPlain]; 66 | tempPlain=""; 67 | } 68 | if(msg[i] == '\t' || msg[i] =='\n') 69 | { 70 | plain=plain +decrypt[tempPlain]; 71 | tempPlain=""; 72 | plain += " "; 73 | 74 | } 75 | } 76 | cout <<"Decrypted Code=:"<< plain<=65 and ascii_vals_enc[i]<=90): 13 | ascii_vals_enc[i] = 65 + (ascii_vals_enc[i] + key - 91)%26 #If the values in the list are greater than 65 and 90, we get it back b/w 65 and 90 14 | encrypt_string = ''.join(chr(i) for i in ascii_vals_enc) # To get the encrypted string using the list of manipulated ASCII vals 15 | return encrypt_string 16 | 17 | def decrypt(message,key): 18 | ascii_vals_dec=[ord(c) for c in message] 19 | for i in range(0,len(ascii_vals_dec)): 20 | if(ascii_vals_dec[i]>=65 and ascii_vals_dec[i]<=90): 21 | ascii_vals_dec[i] = 90 - (90 - ascii_vals_dec[i] + key )%26 22 | decrypt_string = ''.join(chr(i) for i in ascii_vals_dec) # To get the decrypted string using the list of manipulated ASCII vals 23 | return decrypt_string 24 | 25 | def caesar_cipher(): 26 | #message_enc = raw_input("Enter text to be encrypted:") #Can be used to give custom strings 27 | message_enc ="CODING IS FUN" #string to be encrypted 28 | encrypt_string = encrypt(message_enc,key) #Calling the function to encrypt the string 29 | print "The string to be encrypted is: ",message_enc 30 | print "THe encrypted string is: ",encrypt_string 31 | print "----------------------------------------" 32 | #message_dec = raw_input("Enter text to be encrypted:") #Can be used to give custom strings 33 | message_dec ="M PSZI GSHMRK" #string to be decrypted 34 | decrypt_string = decrypt(message_dec,key) #Calling the function to decrypt the string 35 | print "The string to be decrypted is: ",message_dec 36 | print "THe decrypted string is: ",decrypt_string 37 | 38 | if __name__=="__main__": 39 | #key = int(raw_input("By what value do you want to shift?")) #Can be used to give custom key values 40 | key = 4 41 | caesar_cipher() 42 | -------------------------------------------------------------------------------- /Security Algorithms/Cryptography/RSA Algortihm/README.md: -------------------------------------------------------------------------------- 1 | ## RSA 2 | One of the first public-key cryptosystems and is widely used for secure data transmission. In such a cryptosystem, the encryption key is public and it is different from the decryption key which is kept secret (private). In RSA, this asymmetry is based on the practical difficulty of the factorization of the product of two large prime numbers, the **factoring problem**. 3 | 4 | #### Designers 5 | Ron Rivest, Adi Shamir, and Leonard Adleman 6 | 7 | --------------- 8 | 9 | ![](https://globlib4u.files.wordpress.com/2013/10/image1_e.gif) 10 | -------------- 11 | #### Operation 12 | 13 | A basic principle behind RSA is the observation that it is practical to find three very large positive integers e, d and n such that with modular exponentiation for all integer m (with 0 ≤ m < n): 14 | ** (m^e)^d ~ m mod n ** 15 | and that even knowing e and n or even m it can be extremely difficult to find d. 16 | 17 | [More info](https://en.wikipedia.org/wiki/RSA_(cryptosystem)) 18 | -------------------------------------------------------------------------------- /Security Algorithms/Cryptography/RSA Algortihm/rsa.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | 4 | ''' 5 | Euclid's algorithm for determining the greatest common divisor 6 | Use iteration to make it faster for larger integers 7 | ''' 8 | def gcd(a, b): 9 | while b != 0: 10 | a, b = b, a % b 11 | return a 12 | 13 | ''' 14 | Euclid's extended algorithm for finding the multiplicative inverse of two numbers 15 | ''' 16 | def multiplicative_inverse(e, phi): 17 | d = 0 18 | x1 = 0 19 | x2 = 1 20 | y1 = 1 21 | temp_phi = phi 22 | 23 | while e > 0: 24 | temp1 = temp_phi/e 25 | temp2 = temp_phi - temp1 * e 26 | temp_phi = e 27 | e = temp2 28 | 29 | x = x2- temp1* x1 30 | y = d - temp1 * y1 31 | 32 | x2 = x1 33 | x1 = x 34 | d = y1 35 | y1 = y 36 | 37 | if temp_phi == 1: 38 | return d + phi 39 | 40 | ''' 41 | Tests to see if a number is prime. 42 | ''' 43 | def is_prime(num): 44 | if num == 2: 45 | return True 46 | if num < 2 or num % 2 == 0: 47 | return False 48 | for n in xrange(3, int(num**0.5)+2, 2): 49 | if num % n == 0: 50 | return False 51 | return True 52 | 53 | def generate_keypair(p, q): 54 | if not (is_prime(p) and is_prime(q)): 55 | raise ValueError('Both numbers must be prime.') 56 | elif p == q: 57 | raise ValueError('p and q cannot be equal') 58 | #n = pq 59 | n = p * q 60 | 61 | #Phi is the totient of n 62 | phi = (p-1) * (q-1) 63 | 64 | #Choose an integer e such that e and phi(n) are coprime 65 | e = random.randrange(1, phi) 66 | 67 | #Use Euclid's Algorithm to verify that e and phi(n) are comprime 68 | g = gcd(e, phi) 69 | while g != 1: 70 | e = random.randrange(1, phi) 71 | g = gcd(e, phi) 72 | 73 | #Use Extended Euclid's Algorithm to generate the private key 74 | d = multiplicative_inverse(e, phi) 75 | 76 | #Return public and private keypair 77 | #Public key is (e, n) and private key is (d, n) 78 | return ((e, n), (d, n)) 79 | 80 | def encrypt(pk, plaintext): 81 | #Unpack the key into it's components 82 | key, n = pk 83 | #Convert each letter in the plaintext to numbers based on the character using a^b mod m 84 | cipher = [(ord(char) ** key) % n for char in plaintext] 85 | #Return the array of bytes 86 | return cipher 87 | 88 | def decrypt(pk, ciphertext): 89 | #Unpack the key into its components 90 | key, n = pk 91 | #Generate the plaintext based on the ciphertext and key using a^b mod m 92 | plain = [chr((char ** key) % n) for char in ciphertext] 93 | #Return the array of bytes as a string 94 | return ''.join(plain) 95 | 96 | 97 | if __name__ == '__main__': 98 | ''' 99 | Detect if the script is being run directly by the user 100 | ''' 101 | print "RSA Encrypter/ Decrypter" 102 | p = int(raw_input("Enter a prime number (17, 19, 23, etc): ")) 103 | q = int(raw_input("Enter another prime number (Not one you entered above): ")) 104 | print "Generating your public/private keypairs now . . ." 105 | public, private = generate_keypair(p, q) 106 | print "Your public key is ", public ," and your private key is ", private 107 | message = raw_input("Enter a message to encrypt with your private key: ") 108 | encrypted_msg = encrypt(private, message) 109 | print "Your encrypted message is: " 110 | print ''.join(map(lambda x: str(x), encrypted_msg)) 111 | print "Decrypting message with public key ", public ," . . ." 112 | print "Your message is:" 113 | print decrypt(public, encrypted_msg) 114 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-architect 2 | encoding: UTF-8 3 | -------------------------------------------------------------------------------- /algocodeiiest.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codeIIEST/Algorithms/85e3fee94db88b644a102898f889c97083191d35/algocodeiiest.jpg -------------------------------------------------------------------------------- /test.md: -------------------------------------------------------------------------------- 1 | # tsting 2 | --------------------------------------------------------------------------------