diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index ba59610a8..000000000 Binary files a/.DS_Store and /dev/null differ diff --git a/.gitignore b/.gitignore index 49eac9d72..45c150536 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,3 @@ -.sass-cache/ -_site/ - +_site +.sass-cache +.jekyll-metadata diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md deleted file mode 100644 index d5c5fcaee..000000000 --- a/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,46 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -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. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a professional setting - -## Our Responsibilities - -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. - -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. - -## Scope - -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. - -## Enforcement - -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. - -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. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 852b8944e..000000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,22 +0,0 @@ -# Contribution guidelines - -First of all, thanks for thinking of contributing to this project. :smile: - -Before sending a Pull Request, please make sure that you're assigned the task on a GitHub issue. - -- If a relevant issue already exists, discuss on the issue and get it assigned to yourself on GitHub. -- If no relevant issue exists, open a new issue and get it assigned to yourself on GitHub. - -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. - -While making a Pull Request, please take care of the following rules: - -- Make sure the master branch of your forked repo is not any commits ahead than the original master repository. -- Create a new branch from master in the forked repository. Updated your changes in that branch and not in master. -- Include only one algorithm in each pull request. A PR containing more than one algorithm *will not be merged*. -- Write your algorithm in a language other coders are mostly acquainted with i.e. `C`/`C++`/`Python`/`Java`. Any -other language will be accepted only after discussion with the maintainers. -- When writing the algorithm's code, please include a small `readme.md` file in the folder briefly explaining the -algorithm. Make sure your `readme.md` provides a clear understanding of the algorithm to a new-comer. Explanation -should be given in not more than 300 characters -- Write the name of the algorithm you added and the language you used in the title while making the PR. diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md deleted file mode 100644 index 6a0b26c4a..000000000 --- a/CONTRIBUTORS.md +++ /dev/null @@ -1,23 +0,0 @@ -### List of Contributors - -#### KWOC - -Thanks for all your contributions :heart: :octocat: - - -[prateekiiest](https://github.com/prateekiiest) : KWOC Mentor - - -| Github username | Pull Request | Status | -| ------------- |:-------------:| -----:| -|[Ankitr19](https://github.com/Ankitr19)| [#203](https://github.com/codeIIEST/Algorithms/pull/203) |OPEN| -|[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 | -|[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 | -|[Rahul Arulkumaran](https://github.com/rahulkumaran)| [#206](https://github.com/codeIIEST/Algorithms/pull/206), [#207](https://github.com/codeIIEST/Algorithms/pull/207) | OPEN | -|[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 | -| [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| -| [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| -|[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| -|[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 | -|[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 | - diff --git a/Competitive Coding/Backtrack/Sudoku.cpp b/Competitive Coding/Backtrack/Sudoku.cpp deleted file mode 100644 index 0d53fe259..000000000 --- a/Competitive Coding/Backtrack/Sudoku.cpp +++ /dev/null @@ -1,132 +0,0 @@ -// A Backtracking program in C++ to solve Sudoku problem -#include - -// UNASSIGNED is used for empty cells in sudoku grid -#define UNASSIGNED 0 - -// N is used for size of Sudoku grid. Size will be NxN -#define N 9 - -// This function finds an entry in grid that is still unassigned -bool FindUnassignedLocation(int grid[N][N], int &row, int &col); - -// Checks whether it will be legal to assign num to the given row,col -bool isSafe(int grid[N][N], int row, int col, int num); - -/* Takes a partially filled-in grid and attempts to assign values to - all unassigned locations in such a way to meet the requirements - for Sudoku solution (non-duplication across rows, columns, and boxes) */ -bool SolveSudoku(int grid[N][N]) -{ - int row, col; - - // If there is no unassigned location, we are done - if (!FindUnassignedLocation(grid, row, col)) - return true; // success! - - // consider digits 1 to 9 - for (int num = 1; num <= 9; num++) - { - // if looks promising - if (isSafe(grid, row, col, num)) - { - // make tentative assignment - grid[row][col] = num; - - // return, if success, yay! - if (SolveSudoku(grid)) - return true; - - // failure, unmake & try again - grid[row][col] = UNASSIGNED; - } - } - return false; // this triggers backtracking -} - -/* Searches the grid to find an entry that is still unassigned. If - found, the reference parameters row, col will be set the location - that is unassigned, and true is returned. If no unassigned entries - remain, false is returned. */ -bool FindUnassignedLocation(int grid[N][N], int &row, int &col) -{ - for (row = 0; row < N; row++) - for (col = 0; col < N; col++) - if (grid[row][col] == UNASSIGNED) - return true; - return false; -} - -/* Returns a boolean which indicates whether any assigned entry - in the specified row matches the given number. */ -bool UsedInRow(int grid[N][N], int row, int num) -{ - for (int col = 0; col < N; col++) - if (grid[row][col] == num) - return true; - return false; -} - -/* Returns a boolean which indicates whether any assigned entry - in the specified column matches the given number. */ -bool UsedInCol(int grid[N][N], int col, int num) -{ - for (int row = 0; row < N; row++) - if (grid[row][col] == num) - return true; - return false; -} - -/* Returns a boolean which indicates whether any assigned entry - within the specified 3x3 box matches the given number. */ -bool UsedInBox(int grid[N][N], int boxStartRow, int boxStartCol, int num) -{ - for (int row = 0; row < 3; row++) - for (int col = 0; col < 3; col++) - if (grid[row+boxStartRow][col+boxStartCol] == num) - return true; - return false; -} - -/* Returns a boolean which indicates whether it will be legal to assign - num to the given row,col location. */ -bool isSafe(int grid[N][N], int row, int col, int num) -{ - /* Check if 'num' is not already placed in current row, - current column and current 3x3 box */ - return !UsedInRow(grid, row, num) && - !UsedInCol(grid, col, num) && - !UsedInBox(grid, row - row%3 , col - col%3, num); -} - -/* A utility function to print grid */ -void printGrid(int grid[N][N]) -{ - for (int row = 0; row < N; row++) - { - for (int col = 0; col < N; col++) - printf("%2d", grid[row][col]); - printf("\n"); - } -} - -/* Driver Program to test above functions */ -int main() -{ - // 0 means unassigned cells - int grid[N][N] = {{3, 0, 6, 5, 0, 8, 4, 0, 0}, - {5, 2, 0, 0, 0, 0, 0, 0, 0}, - {0, 8, 7, 0, 0, 0, 0, 3, 1}, - {0, 0, 3, 0, 1, 0, 0, 8, 0}, - {9, 0, 0, 8, 6, 3, 0, 0, 5}, - {0, 5, 0, 0, 9, 0, 6, 0, 0}, - {1, 3, 0, 0, 0, 0, 2, 5, 0}, - {0, 0, 0, 0, 0, 0, 0, 7, 4}, - {0, 0, 5, 2, 0, 6, 3, 0, 0}}; - if (SolveSudoku(grid) == true) - printGrid(grid); - else - printf("No solution exists"); - - return 0; -} diff --git a/Competitive Coding/Backtrack/nQueen.cpp b/Competitive Coding/Backtrack/nQueen.cpp deleted file mode 100644 index 26a98a8ab..000000000 --- a/Competitive Coding/Backtrack/nQueen.cpp +++ /dev/null @@ -1,104 +0,0 @@ -/* C/C++ program to solve N Queen Problem using backtracking */ -#define N 4 -#include - -/* A utility function to print solution */ -void printSolution(int board[N][N]) -{ - for (int i = 0; i < N; i++) - { - for (int j = 0; j < N; j++) - printf(" %d ", board[i][j]); - printf("\n"); - } -} - -/* A utility function to check if a queen can - be placed on board[row][col]. Note that this - function is called when "col" queens are - already placed in columns from 0 to col -1. - So we need to check only left side for - attacking queens */ -bool isSafe(int board[N][N], int row, int col) -{ - int i, j; - - /* Check this row on left side */ - for (i = 0; i < col; i++) - if (board[row][i]) - return false; - - /* Check upper diagonal on left side */ - for (i=row, j=col; i>=0 && j>=0; i--, j--) - if (board[i][j]) - return false; - - /* Check lower diagonal on left side */ - for (i=row, j=col; j>=0 && i= N) - return true; - - /* Consider this column and try placing this queen in all rows one by one */ - for (int i = 0; i < N; i++) - { - /* Check if queen can be placed on board[i][col] */ - if ( isSafe(board, i, col) ) - { - /* Place this queen in board[i][col] */ - board[i][col] = 1; - - /* recur to place rest of the queens */ - if ( solveNQUtil(board, col + 1) ) - return true; - - /* If placing queen in board[i][col] doesn't lead to a solution, then remove queen from board[i][col] */ - board[i][col] = 0; // BACKTRACK - } - } - - /* If queen can not be place in any row in this colum col then return false */ - return false; -} - -/* This function solves the N Queen problem using - Backtracking. It mainly uses solveNQUtil() to - solve the problem. It returns false if queens - cannot be placed, otherwise return true and - prints placement of queens in the form of 1s. - Please note that there may be more than one - solutions, this function prints one of the - feasible solutions.*/ -bool solveNQ() -{ - int board[N][N] = { {0, 0, 0, 0}, - {0, 0, 0, 0}, - {0, 0, 0, 0}, - {0, 0, 0, 0} - }; - - if ( solveNQUtil(board, 0) == false ) - { - printf("Solution does not exist"); - return false; - } - - printSolution(board); - return true; -} - -// driver program to test above function -int main() -{ - solveNQ(); - return 0; -} diff --git a/Competitive Coding/Bitwise Operations/.DS_Store b/Competitive Coding/Bitwise Operations/.DS_Store deleted file mode 100644 index 472092042..000000000 Binary files a/Competitive Coding/Bitwise Operations/.DS_Store and /dev/null differ diff --git a/Competitive Coding/Bitwise Operations/Count_One/count_one.cpp b/Competitive Coding/Bitwise Operations/Count_One/count_one.cpp deleted file mode 100644 index 41d816147..000000000 --- a/Competitive Coding/Bitwise Operations/Count_One/count_one.cpp +++ /dev/null @@ -1,17 +0,0 @@ -//Program to count the no of 1's in the binary representation of a given decimal number using Bitwise Operations. -#include -using namespace std; - -int main() -{ - int x=4; - int count=0;//Variable to store the number of 1's in the decimal representation of x - - while(x) - { - x=x&(x-1); - count++; - } - - cout<<"The number of 1's in the decimal representation of "< -using namespace std; - -int main() { - long N; - cin>>N; - largest_power(N);} -void largest_power(long N) - { - //changing all right side bits to 1. - N = N| (N>>1); - N = N| (N>>2); - N = N| (N>>4); - N = N| (N>>8); - - - //as now the number is 2 * x-1, where x is required answer, so adding 1 and dividing it by - 2. - printf((N+1)>>1; - - } \ No newline at end of file diff --git a/Competitive Coding/Bitwise Operations/Largest_power_of_2/readme.md b/Competitive Coding/Bitwise Operations/Largest_power_of_2/readme.md deleted file mode 100644 index 8d9e308e8..000000000 --- a/Competitive Coding/Bitwise Operations/Largest_power_of_2/readme.md +++ /dev/null @@ -1,13 +0,0 @@ -# Finding the largest power of 2 (most significant bit in binary form), which is less than or -equal to the given number N. - -Let’s say binary form of a N is {1111}base2 which is equal to 15. -15 = 2^4-1, where 4 is the number of bits in N. - -This property can be used to find the largest power of 2 less than or equal to N. How? -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. -Example: -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. -So lets change all the right side bits of the most significant bit to 1. Now the number changes to -{11111} = 31 = 2 * 16 -1 = Y (let’s say). -Now the required answer is (Y+1)>>1 or (Y+1)/2. diff --git a/Competitive Coding/Bitwise Operations/Power_of_Two/power_of_two.cpp b/Competitive Coding/Bitwise Operations/Power_of_Two/power_of_two.cpp deleted file mode 100644 index 99a14cfcb..000000000 --- a/Competitive Coding/Bitwise Operations/Power_of_Two/power_of_two.cpp +++ /dev/null @@ -1,13 +0,0 @@ -//Program to count the NUMBER OF 1's in the binary representation of a decimal number -#include -using namespace std; - -int main() -{ - int num=256;//Number to be checked whether is a power of 2 or not - - if (num && !(num & (num - 1)))//Checking the required condition as explained. - cout< -using namespace std; - -int main() -{ - int n,i; - printf("Enter a number:\n"); - scanf("%d",&n); - printf("Enter bit to be checked:\n"); - scanf("%d",&i); - if( n & (1 << i) ) - printf("The %dth bit is set in %d",i,n); - else - printf("The %dth bit is not set in %d",i,n); - return 0; -} \ No newline at end of file diff --git a/Competitive Coding/Bitwise Operations/ith_bit_set/readme.md b/Competitive Coding/Bitwise Operations/ith_bit_set/readme.md deleted file mode 100644 index d52d3f278..000000000 --- a/Competitive Coding/Bitwise Operations/ith_bit_set/readme.md +++ /dev/null @@ -1,12 +0,0 @@ -#Check whether the ith bit is set in a number using Bitwise Operations - -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. - -Using Left shift operator, we can write 2^i as 1 << i . - -Example: -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 . -{10100} & {100} = {100} = 2^2 = 4(non-zero number), which means it’s 2nd bit is set. - - - diff --git a/Competitive Coding/Bitwise Operations/readme.md b/Competitive Coding/Bitwise Operations/readme.md deleted file mode 100644 index d32f23dec..000000000 --- a/Competitive Coding/Bitwise Operations/readme.md +++ /dev/null @@ -1,37 +0,0 @@ -#Bitwise Operations -In some cases, a programmer has to go beyond the level of int,float,etc. More deeply a programmer has to understan the -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. -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. - -#Bitwise Operations -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: - -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. -N = 5 = (101)2 -~N = ~5 = ~(101)2 = (010)2 = 2 - -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. -A = 5 = (101)2 , B = 3 = (011)2 A & B = (101)2 & (011)2= (001)2 = 1 - -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. -A = 5 = (101)2 , B = 3 = (011)2 -A | B = (101)2 | (011)2 = (111)2 = 7 - -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. -A = 5 = (101)2 , B = 3 = (011)2 -A ^ B = (101)2 ^ (011)2 = (110)2 = 6 - -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 - -( if we are shifting k bits ). -1 << 1 = 2 = 21 -1 << 2 = 4 = 22 1 << 3 = 8 = 23 -1 << 4 = 16 = 24 -… -1 << n = 2n - -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 ). -4 >> 1 = 2 -6 >> 1 = 3 -5 >> 1 = 2 -16 >> 4 = 1 diff --git a/Competitive Coding/Data Structures/Queue/queue.class b/Competitive Coding/Data Structures/Queue/queue.class deleted file mode 100644 index d4831508b..000000000 Binary files a/Competitive Coding/Data Structures/Queue/queue.class and /dev/null differ diff --git a/Competitive Coding/Data Structures/Queue/queue.java b/Competitive Coding/Data Structures/Queue/queue.java deleted file mode 100644 index 6b20f68ec..000000000 --- a/Competitive Coding/Data Structures/Queue/queue.java +++ /dev/null @@ -1,132 +0,0 @@ -package Data_Structures; -import java.util.*; -class Queue -{ - private int q[], front, rear, size; - - - /***** Constructor to initialize queue *****/ - queue(int n) - { //Begin constructor - size = n; - front = -1; - rear = -1; - q = new int[size]; - - for(int i = 0; i "); - - for(int i = front; i <= rear; i++) - System.out.print(q[i]+"\t"); - - System.out.println("<--- rear"); - - } - } //End display() - - - - - public static void main(String args[]) - { //Begin main() - - Scanner sc = new Scanner(System.in); - System.out.println("Enter the size of the queue"); - int n = sc.nextInt(); - - queue q1 = new queue(n); - - int choice; - do - { //Begin do - System.out.println("\nEnter:\n1. Insert\n2. Delete\n3. Display"); - choice = sc.nextInt(); - switch(choice) - { //Begin switch - case 1: System.out.println("\nEnter an element to insert"); - int element = sc.nextInt(); - q1.insert(element); - break; - - case 2: q1.delete(); - break; - - case 3: q1.display(); - break; - - default: System.out.println("Wrong choice. Exitting."); - break; - } //End switch - } //End do - while(choice >= 1 && choice <= 3); - } //End main() -} //End class diff --git a/Competitive Coding/Data Structures/Stack/stack.class b/Competitive Coding/Data Structures/Stack/stack.class deleted file mode 100644 index 5a35d9f53..000000000 Binary files a/Competitive Coding/Data Structures/Stack/stack.class and /dev/null differ diff --git a/Competitive Coding/Data Structures/Stack/stack.java b/Competitive Coding/Data Structures/Stack/stack.java deleted file mode 100644 index cbb27d6f0..000000000 --- a/Competitive Coding/Data Structures/Stack/stack.java +++ /dev/null @@ -1,130 +0,0 @@ -package Data_Structures -import java.util.*; -class stack -{ //Begin class - - int top = -1, size, s[]; - - - /*****Constructor to initialise the stack *****/ - stack(int n) - { //Begin constructor - size = n; - - s = new int[size]; - for(int i = 0; i < size; i++) - { //Begin for - s[i] = 0; - } //End for - } //End constructor - - - - /***** Fucntion to insert/push item to stack *****/ - private void push(int item) - { //Begin push() - - if(top == (size-1)) //Checks if stack is full - { //Begin if - System.out.println("Stack overflow"); - } //End if - - else //Element is entered to the stack when there is place - { //Begin else - top++; - s[top] = item; - } //End else - - } //End push() - - - - /***** Function to delete/pop an item (topmost element) from stack *****/ - private void pop() - { //Begin pop() - - if(top == -1) //Checks if stack is empty - { //Begin if - System.out.println("Stack underflow"); - } //End if - - else - { //Begin else - System.out.println("Item deleted is:\t"+s[top]); - top--; - } //End else - } //End pop() - - - /***** Function to peep (show the topmost element in stack) *****/ - private void peep() - { //Begin peep() - if(top == -1) - System.out.println("No element to peep"); - - else - System.out.println("Peep: top ---> "+s[top]); - } //End peep() - - - - /***** Function to display the elements of stack *****/ - private void display() - { //Begin display() - - if(top == -1) - { //Begin if - System.out.println("No elements in stack"); - } //End if - - else - { //Begin else - - System.out.print("Elements of the stack: top---> "); - for(int i=top; i>=0; i--) - { - System.out.print(s[i]+"\t"); - } - System.out.println(); - } //End else - } //End display() - - - /***** main fucntion *****/ - public static void main(String args[]) - { //Begin main() - - Scanner sc = new Scanner(System.in); - System.out.println("Enter the size of the stack"); - int n = sc.nextInt(); - - stack st = new stack(n); - - int choice; - do - { //Begin do - System.out.println("\nEnter:\n1. Push\n2. Pop\n3. Peep\n4. Display"); - choice = sc.nextInt(); - switch(choice) - { //Begin switch - case 1: System.out.println("\nEnter an element to push"); - int element = sc.nextInt(); - st.push(element); - break; - - case 2: st.pop(); - break; - - case 3: st.peep(); - break; - - case 4: st.display(); - break; - - default: System.out.println("Wrong choice. Exitting!"); - break; - } //End switch - } //End do - while(choice >= 1 && choice <= 4); - } //End main() -} //End class diff --git a/Competitive Coding/Dynamic Programming/0-1Knapsack/knapsack.java b/Competitive Coding/Dynamic Programming/0-1Knapsack/knapsack.java deleted file mode 100644 index c7bae600d..000000000 --- a/Competitive Coding/Dynamic Programming/0-1Knapsack/knapsack.java +++ /dev/null @@ -1,70 +0,0 @@ -import java.util.*; - - -class Knapsack -{ - - // A function to return maximum of two integers - static int maximum(int a, int b) - { - if(a>b) - return a; - else - return b; - - } - - // Returns the maximum value that can be put in a knapsack of capacity W - static int knapSack(int W, int wt[], int val[], int n) - { - int i, w; - int K[][] = new int[n+1][W+1]; - - // Build table K[][] in bottom up manner - for (i = 0; i <= n; i++) - { - for (w = 0; w <= W; w++) - { - if (i==0 || w==0) - K[i][w] = 0; - else if (wt[i-1] <= w) - K[i][w] = maximum(val[i-1] + K[i-1][w-wt[i-1]] , K[i1][w]); - else - K[i][w] = K[i-1][w]; - } - } - - Return K[n][W]; - } - - - - public static void main(String args[]) - { - - Scanner s=new Scanner(System.in); - System.out.println(“Enter number of objects”); - int n=s.nextInt(); - int val[]=new int[n]; - int wt[] = new int[n]; - System.out.println(“Enter values of objects”); - - - for(int i=0;i - -using namespace std; - -int main() -{ - int M;//Variable to store the number of different currency values. - cout<<"Enter the number of denominations : "; - cin>>M;//Inputting the number of different currency value from user. - cout<>arr[i];//Inputting the value of each currency from user. - } - cout<>N;//Inputting the number of cents from user. - cout< -using namespace std; -const int inf=0x3fffffff; -#define Min(a,b) (a>test ; - while(test--) - { - cin>>a; - cin>>b; - cin>>z; - cin>>x; - cin>>c; - lena = strlen(a) ; - lenb = strlen(b) ; - if((lena-lenb)*z > c || (lenb-lena)*z > c ) - { - cout<<"-1\n"; - continue ; - } - if( (z == 0) ) - { - cout<<"0\n" ; - continue ; - } - if( (x == 0) ) - { - cout< c) - previous_dp[i] = inf ; - else - previous_dp[i] = i*z ; - } - fr(i,1,lena+1) - { - alpha = Max((i-c),0) ; - if( alpha > 0) - { - current_dp[alpha-1] = inf ; - } - alpha -= 1 ; - temp = Min((i+c+1),(lenb+1)); - fr(j,alpha+1,temp) - { - if(j == 0) - { - current_dp[j] = i*z ; - } - else - { - 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)); - } - } - fr(j,alpha,temp) - { - previous_dp[j] = current_dp[j] ; - } - } - if(current_dp[lenb] > c) - cout<<"-1\n"; - else - cout< -using namespace std; -#define Min(a,b) (a>test ; - while(test--) - { - cin>>a; - cin>>b; - lena = strlen(a) ; - lenb = strlen(b) ; - dp[lena+1][lenb+1]; - fr(i,0,lena+1) - { - fr(j,0,lenb+1) - { - if( i == 0 ) - { - dp[i][j] = j ; - } - else if( j == 0 ) - { - dp[i][j] = i ; - } - else - { - 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)); - } - cout< -using namespace std; -#define lli long long int -#define infinite 0xffff -#define Min(a,b) (((a)<(b))?(a):(b)) -#define Max(a,b) (((a)>(b))?(a):(b)) -#define fr(i,j,s) for(i = j ; i < s ; i++) -#define ifr(i,j,s) for(i = j ; i >= s , i--) -void lcs(char * a, char *b) -{ - lli lena,lenb,i,j,count; - lena=strlen(a); - lenb=strlen(b); - char record[lena+1][lenb+1]; - //Code to generate the map - fr(i,0,lena+1) - { - fr(j,0,lenb+1) - { - if(i==0 || j==0) - { - record[i][j]=0; - } - else if(a[i-1]==b[j-1]) - { - record[i][j]=record[i-1][j-1]+1; - } - else - { - record[i][j] = Max(record[i-1][j],record[i][j-1]); - } - } - } - //Code to find the subsequence - i = lena; - j = lenb; - char sub[record[lena][lenb]]; - lli index = record[i][j]-1; - while( i > 0 && j > 0 ) - { - if(a[i-1]==b[j-1]) - { - sub[index]=a[i-1]; - i--; - j--; - index--; - } - else if(Max(record[i-1][j],record[i][j-1]) == record[i-1][j]) - { - i--; - } - else - { - j--; - } - } - fr(i,0,record[lena][lenb]) - { - cout<>str1; - cin>>str2; - lcs(str1,str2); - return 0; -} diff --git a/Competitive Coding/Dynamic Programming/Longest Increasing Subsequence/lis_n_log_n.cpp b/Competitive Coding/Dynamic Programming/Longest Increasing Subsequence/lis_n_log_n.cpp deleted file mode 100644 index 3c4e5e862..000000000 --- a/Competitive Coding/Dynamic Programming/Longest Increasing Subsequence/lis_n_log_n.cpp +++ /dev/null @@ -1,67 +0,0 @@ -#include -using namespace std; -#define lli long long int -#define infinite 0xffff -#define Min(a,b) (((a)<(b))?(a):(b)) -#define Max(a,b) (((a)>(b))?(a):(b)) -#define fr(i,j,s) for(i = j ; i < s ; i++) -#define ifr(i,j,s) for(i = j ; i >= s ; i--) -lli binary_LookUp(lli * record ,lli a , lli len , lli val) -{ - while(len-a > 1) - { - lli m = a + (len-a)/2; - if(record[m]>=val) - { - len = m ; - } - else - { - a = m ; - } - } - return len ; -} -void lis(lli * a, lli n) -{ - lli i,j,count,index; - lli record[n]; - //Code to generate the map - record[0]=a[0]; - lli len = 1 ; - fr(i,1,n) - { - if(a[i] record[len-1]) - { - record[len] = a[i]; - len++; - } - else - { - index=binary_LookUp(record,-1,len-1,a[i]); - record[index] = a[i]; - } - } - cout<>n; - lli a[n]; - fr(i,0,n) - { - cin>>a[i]; - } - lis(a,n); - return 0; -} diff --git a/Competitive Coding/Dynamic Programming/Longest Increasing Subsequence/lis_n_squared_sol.cpp b/Competitive Coding/Dynamic Programming/Longest Increasing Subsequence/lis_n_squared_sol.cpp deleted file mode 100644 index a998012e9..000000000 --- a/Competitive Coding/Dynamic Programming/Longest Increasing Subsequence/lis_n_squared_sol.cpp +++ /dev/null @@ -1,73 +0,0 @@ -#include -using namespace std; -#define lli long long int -#define infinite 0xffff -#define Min(a,b) (((a)<(b))?(a):(b)) -#define Max(a,b) (((a)>(b))?(a):(b)) -#define fr(i,j,s) for(i = j ; i < s ; i++) -#define ifr(i,j,s) for(i = j ; i >= s ; i--) -void lis(lli * a, lli n) -{ - lli i,j,count; - lli record[n]; - //Code to generate the map - fr(i,0,n) - { - record[i] = 0 ; - } - fr(i,0,n) - { - fr(j,0,i) - { - if( (a[i]>a[j]) && (record[i]<(record[j]+1)) ) - { - record[i]=record[j]+1; - } - } - } - lli max = 0; - lli index = 0 ; - fr(i,0,n) - { - //cout<>n; - lli a[n]; - fr(i,0,n) - { - cin>>a[i]; - } - lis(a,n); - return 0; -} diff --git a/Competitive Coding/Dynamic Programming/Maximum Subarray Sum/Maximum Subarray Sum Readme.md b/Competitive Coding/Dynamic Programming/Maximum Subarray Sum/Maximum Subarray Sum Readme.md deleted file mode 100644 index b2ad25618..000000000 --- a/Competitive Coding/Dynamic Programming/Maximum Subarray Sum/Maximum Subarray Sum Readme.md +++ /dev/null @@ -1,20 +0,0 @@ -Problem : To find the maximum subarray sum. - -Language used : C++ - -Input : An integer array given by the user. - -Output : A single integer denoting the maximum subarray sum. - -Algorithm Paradigm : Dynamic Programming. - -Time Complexity : Linear - -Space Complexity : Constant - -Working :- - -We are traversing the array and storing the sum of contiguous elements in sum variable. -As the value of sum reaches its maximum value that value is stored in max_so_far variable. -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. - diff --git a/Competitive Coding/Dynamic Programming/Maximum Subarray Sum/Maximum Subarray Sum.cpp b/Competitive Coding/Dynamic Programming/Maximum Subarray Sum/Maximum Subarray Sum.cpp deleted file mode 100644 index 6e34e3242..000000000 --- a/Competitive Coding/Dynamic Programming/Maximum Subarray Sum/Maximum Subarray Sum.cpp +++ /dev/null @@ -1,35 +0,0 @@ -//Code to find the maximum subarray sum using dynamin programming in c++. -#include - -using namespace std; - -int main() -{ - int n; - cout<<"Enter the size of the array : ";//Inputting the size of the array. - cin>>n; - cout<>arr[i];//Inputting the values in the array. - } - - int max_so_far=-99999;//It will store the maximum subarray sum. - int sum=0;//It will store the sum of the different subarrays. - - for(int i=0;imax_so_far) - max_so_far=sum; - if(sum<0) - sum=0; - } - - cout<<"The maximum subarray sum is : "< -using namespace std; - -int MaxSumIncrsSubseq(int arr[],int n) -{ - int i,j,mx=0; - 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. - for(i=0;iarr[j] - 2.)MSIS[i]arr[j] && MSIS[i] -#include - -// A utility function to get the maximum of two integers -int max(int a, int b) - { - return (a > b)? a : b; - } - - - /* Returns the best obtainable price for a rod of length n and - price[] as prices of different pieces */ -int DPcutRod(int price[], int n) -{ - int val[n+1]; - val[0] = 0; - int i, j; - for (i = 1; i<=n; i++) - { - int max_val = INT_MIN; - // Recursively cut the rod in different pieces and compare different - // configurations - for (j = 0; j < i; j++) - max_val = max(max_val, price[j] + val[i-j-1]); - val[i] = max_val; - } - return val[n]; -} - -int main() -{ - int n; - printf("Enter rod length\n"); - scanf("%d",&n); - int arr[n],i; - printf("Enter prices for lengths 1 to n\n"); - for(i=0;i -#include - -using namespace std; - -int main(){ - std::ios::sync_with_stdio(false); - /* - We can easily observe that the optimum solution of the minimum - cost at any row i is only dependent on the cost at row i-1 and - the current row elements. Thus if we only store these two arrays - of length c, We have reduced space from n*m to 2*m. - */ - - int i, j, r, c; - printf("Enter no of rows and no of cols\n"); - cin>>r>>c; //take input of the rows and columns from user. - int cost[c], dp[c]; - int x; - /* - Since for the first row the minimum cost is the only cost possible - required to get there, we directly calculate it. - */ - printf("Enter a R X C array\n"); - - for(i=0; i>cost[i]; - if(i>0) cost[i] = cost[i] + cost[i-1]; - } - /* - For the subsequent rows, the optimised cost for each cell in the - previous row has been stored in the array cost[] and the optimised - cost for the present row is stored in the array dp[]. - */ - for(i=1; i>x; - if(j==0) - dp[j] = cost[j] + x; - else{ - dp[j] = x + min(dp[j-1], min(cost[j-1], cost[j])); - } - } - /* - After dp[] has been found entirely, we copy its elements to - cost[] and continue the iteration. - */ - for(j=0; (j 0 and n == 0 -isSubsetSum(set, n, sum) = true, if sum == 0 - -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] diff --git a/Competitive Coding/Dynamic Programming/subsetSum/subsetSum.cpp b/Competitive Coding/Dynamic Programming/subsetSum/subsetSum.cpp deleted file mode 100644 index 58de312a1..000000000 --- a/Competitive Coding/Dynamic Programming/subsetSum/subsetSum.cpp +++ /dev/null @@ -1,45 +0,0 @@ -#include - -// Returns true if there is a subset of a[] with sun equal to given sum -bool DP(int set[], int n, int sum) -{ - // The value of subset[i][j] will be true if there is a -// subset of set[0..j-1] with sum equal to i - bool subset[n+1][sum+1]; - // If sum is 0, then answer is true - for (int i = 0; i <= n; i++) - subset[i][0] = true; - // If sum is not 0 and set is empty, then answer is false - for (int i = 1; i <= sum; i++) - subset[0][i] = false; - // Fill the subset table in botton up manner - for (int i = 1; i <= n; i++) - { - for (int j = 1; j <= sum; j++) - { - if(j= set[i-1]) - subset[i][j] = subset[i-1][j] || - subset[i - 1][j-set[i-1]]; - } - } - return subset[n][sum]; -} - -int main() -{ - int n; - int sum; - printf("Enter no of elements of array and desired sum\n"); - scanf("%d%d",&n,&sum); - int i,a[n]; - printf("Enter the array\n"); - for(i=0;i -using namespace std; -int main() -{ - printf("Enter no of test cases\n"); - int t; cin >> t; - int i2, i3, i5; - i2 = i3 = i5 = 0; - int ugly[500];// To store ugly numbers - ugly[0] = 1; - for (int i = 1; i < 500; ++i) { - ugly[i] = min(ugly[i2]*2, min(ugly[i3]*3, ugly[i5]*5));//get minimum of possible solutions - ugly[i] != ugly[i2]*2 ? : i2++; // next_mulitple_of_2 = ugly[i2]*2; - ugly[i] != ugly[i3]*3? : i3++; // next_mulitple_of_3 = ugly[i3]*3 - ugly[i] != ugly[i5]*5 ? : i5++; // next_mulitple_of_5 = ugly[i5]*5; - } - int n; - while(t--) { - printf("Enter 'n' for the nth ugly number\n"); - cin >> n; - cout << ugly[n-1] << endl; - } - return 0; -} diff --git a/Competitive Coding/Geometry/Convex hull/convex hull jarvis march.cpp b/Competitive Coding/Geometry/Convex hull/convex hull jarvis march.cpp deleted file mode 100644 index bd162f83b..000000000 --- a/Competitive Coding/Geometry/Convex hull/convex hull jarvis march.cpp +++ /dev/null @@ -1,121 +0,0 @@ -#include -using namespace std; -#define fastio ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0) -#define md 1000000007 -#define ll long long int -#define vi vector -#define vll vector -#define pb push_back -#define all(c) (c).begin(),(c).end() -template< class T > T max2(const T &a,const T &b) {return (a < b ? b : a);} -template< class T > T min2(const T &a,const T &b) {return (a > b ? b : a);} -template< class T > T max3(const T &a, const T &b, const T &c) { return max2(a, max2(b, c)); } -template< class T > T min3(const T &a, const T &b, const T &c) { return min2(a, min2(b, c)); } -template< class T > T gcd(const T a, const T b) { return (b ? gcd(b, a%b) : a); } -template< class T > T lcm(const T a, const T b) { return (a / gcd(a, b) * b); } -template< class T > T mod(const T &a, const T &b) { return (a < b ? a : a % b); } -typedef pair pi; -typedef struct -{ - int x; - int y; -}point; -int crossprod(point points[],int a,int b,int c)//This function calculates the crossproduct of the given two vectors . one vector is ab and other is ac. -{ - point current = points[a]; - point target = points[b]; - point temp = points[c]; - int y1 = target.y-current.y; - int x1 = target.x-current.x; - int x2 = temp.x-current.x; - int y2 = temp.y-current.y; - return y2*x1-x2*y1; -} -int closer(point points[],int a,int b,int c)//This function calculates the closer of the given two points from a and returns the index of the closer one. -{ - point current = points[a]; - point target = points[b]; - point temp = points[c]; - double dist1 = sqrt((current.x-target.x)*(current.x-target.x)-(current.y-target.y)*(current.y-target.y)); - double dist2 = sqrt((current.x-temp.x)*(current.x-temp.x)-(current.y-temp.y)*(current.y-temp.y)); - if(dist1>n; - point points[n]; - for(int i=0;i>points[i].x>>points[i].y; - } - //now we look for the leftmost point - int index=0,mini=100000; - for(int i=0;i result; - - result.insert(index);//we add the left most point in the result array - int current = index;//now our index becomes the index to the current point - vi colinear; - while(true) - { - int target = 0 ;//consider the starting target to be point with index zero - for(int i=1;i 0)//If the cross prod value is greater than zero than this means that we the point i is in the left side of the line segement that passes through the target and current so now the target needs to be changed. - { - - target = i; - colinear.clear();//we also need to clear the colinear array as the target itself is changed. - } - if(val == 0) - { - int close = closer(points,current,target,i);//This gives the index of the closer point. - if(close == target) - target = i; - colinear.pb(close); - } - } - } - int len = colinear.size(); - for(int k = 0;k :: iterator i= result.begin(); -for(;i!=result.end();++i) -{ - cout< -using namespace std; - -#define ll long long int -/*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 -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 -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 -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 -we have found a cycle*/ -typedef struct -{ - ll src; - ll dest; -}edge; -class Graph -{ -private: - ll vertex; - ll edges; - vector edgearray; - vector parent; - vector rank; - list *array; -public: - Graph(ll vertices=0,ll edge=0) - :vertex(vertices),edges(edge) - { - array= new list[vertex]; - parent.assign(vertex,-1); - rank.assign(vertex,0); - } - Graph(const Graph &g2) - { - vertex=g2.vertex; - edges=g2.edges; - array= new list[vertex]; - parent.assign(vertex,-1); - rank.assign(vertex,0); - } - ll find(ll v) - { - if(parent[v]==-1) - return v; - else - find(parent[v]); - } - void unions(ll x,ll y) - { - ll xroot=find(x); - ll yroot=find(y); - if(rank[xroot]>rank[yroot]) - parent[yroot]=xroot; - else - if(rank[yroot]>rank[xroot]) - parent[xroot]=yroot; - else - { - parent[xroot]=yroot; - rank[yroot]++; - } - } - ll iscycle(ll x,ll y) - { - - ll xroot=find(x); - ll yroot=find(y); - if(xroot==yroot) - return 1; - else - { - unions(x,y); - return 0; - } - } - void addedge(ll v1,ll v2) - { - array[v1].push_back(v2); - array[v2].push_back(v1); - edge temp; - temp.src=v1; - temp.dest=v2; - edgearray.push_back(temp); - } - -}; -int main() -{ - ll vertex;ll edges,v1,v2; - cin>>vertex>>edges; - Graph g(vertex,edges); - for(ll i=0;i>v1>>v2; - g.addedge(v1,v2); - } -} diff --git a/Competitive Coding/Graphs/Detecting cycles/detecting-cycles_readme.md b/Competitive Coding/Graphs/Detecting cycles/detecting-cycles_readme.md deleted file mode 100644 index 9c3e6b4ed..000000000 --- a/Competitive Coding/Graphs/Detecting cycles/detecting-cycles_readme.md +++ /dev/null @@ -1,59 +0,0 @@ -# Disjoint-set - -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". -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. -Forests can be represented compactly in memory as arrays in which parents are indicated by their array index. - -# MAKE SET - -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. -The MakeSet operation has O(1) time complexity. -Pseudocode: - -function MakeSet(x) - if x is not already present: - add x to the disjoint-set tree - x.parent := x - x.rank := 0 - -![alt text](https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRkmVdlJLBBEPsQUbG3igzyitb6PDbqCuVbVtQzc009uyLX65U-) - -# FIND -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. -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. - -Pseudocode: - -function Find(x) - if x.parent != x - x.parent := Find(x.parent) - return x.parent - -![alt text](https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRptXJI8DhupTU5GNaF5qKZX94VPYB7GTiXkYMTadEGRuFMS5PKtg) - -# UNION - -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. -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. -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. -Pseudocode: - -function Union(x, y) - xRoot := Find(x) - yRoot := Find(y) - - // x and y are already in the same set - if xRoot == yRoot - return - - // x and y are not in same set, so we merge them - if xRoot.rank < yRoot.rank - xRoot.parent := yRoot - else if xRoot.rank > yRoot.rank - yRoot.parent := xRoot - else - //Arbitrarily make one root the new parent - yRoot.parent := xRoot - xRoot.rank := xRoot.rank + 1 - -![alt text](https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSZkZmlExRXCYS-k3TO9dSM0dH_Ql2WuiB-VTIGj6090KEI0Jmjjw) diff --git a/Competitive Coding/Graphs/Graph_Search/BreadthFirstSearch/Breadth_First_Search.cpp b/Competitive Coding/Graphs/Graph_Search/BreadthFirstSearch/Breadth_First_Search.cpp deleted file mode 100644 index 40dbc452a..000000000 --- a/Competitive Coding/Graphs/Graph_Search/BreadthFirstSearch/Breadth_First_Search.cpp +++ /dev/null @@ -1,61 +0,0 @@ -#include -using namespace std; - -vectorVisited; -vector< vector >Graph; - -void edge(int a,int b) -{ - Graph[a].push_back(b); //for directed - - //If undirected graph is there, then add the following line - // Graph[b].push_back(a); -} - -void BreadthFirstSearch(int u) -{ - queueq; - q.push(u); - Visited[u]=true; - - while(!q.empty()) - { - int f=q.front(); - q.pop(); - - cout<>n>>e; - Visited.assign(n,false); - Graph.assign(n,vector()); - - int a,b; - for(int i=0;i>a>>b; - edge(a,b); - } - - for(int i=0;i -using namespace std; - -void addEdge(vectoradj[],int u,int v) -{ - //For undirected graph - adj[u].push_back(v); - adj[v].push_back(u); -} - -void DFSUtil(int u,vectoradj[],vector&visited) -{ - visited[u]=true; - cout<adj[],int V) -{ - vectorvisited(V,false); - for(int u=0;u adj[V]; - addEdge(adj, 0, 1); - addEdge(adj, 0, 4); - addEdge(adj, 1, 2); - addEdge(adj, 1, 3); - addEdge(adj, 1, 4); - addEdge(adj, 2, 3); - addEdge(adj, 3, 4); - DFS(adj, V); - cout<<"\n"; - return 0; -} \ No newline at end of file diff --git a/Competitive Coding/Graphs/Graph_Search/DepthFIrstSearch/README.md b/Competitive Coding/Graphs/Graph_Search/DepthFIrstSearch/README.md deleted file mode 100644 index cf1bd8d06..000000000 --- a/Competitive Coding/Graphs/Graph_Search/DepthFIrstSearch/README.md +++ /dev/null @@ -1,38 +0,0 @@ -## Depth-first search (DFS) - 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 - ----- -![](https://upload.wikimedia.org/wikipedia/commons/7/7f/Depth-First-Search.gif) ----- -This is the algorithm for Depth First Search in a given graph. - -* We take a starting vertex , and push all its adjacent vertexes in a stack. -* 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. -* After executing the code, we will get the vertex visited in a depth first manner. - -Some real life applications of DFS are as follows: -1) For an unweighted graph, DFS traversal of the graph produces the minimum spanning tree and all pair shortest path tree. - -2) Detecting cycle in a graph -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) - -3) Path Finding -We can specialize the DFS algorithm to find a path between two given vertices u and z. -i) Call DFS(G, u) with u as the start vertex. -ii) Use a stack S to keep track of the path between the start vertex and the current vertex. -iii) As soon as destination vertex z is encountered, return the path as the -contents of the stack - -See this for details. - -4) Topological Sorting -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]. - -5) To test if a graph is bipartite -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. - -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) - -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.) - -[more info](https://en.wikipedia.org/wiki/Depth-first_search) diff --git a/Competitive Coding/Graphs/Shortest Path/Bellman Ford/Bellman_Ford.cpp b/Competitive Coding/Graphs/Shortest Path/Bellman Ford/Bellman_Ford.cpp deleted file mode 100644 index c23d4fda6..000000000 --- a/Competitive Coding/Graphs/Shortest Path/Bellman Ford/Bellman_Ford.cpp +++ /dev/null @@ -1,119 +0,0 @@ -#include -using namespace std; - -struct Edge -{ - int src,dest,weight; -}; - -struct Graph -{ - int V,E; - struct Edge* edge; -}; - -struct Graph* buildGraph(int V,int E) -{ - struct Graph* graph=new Graph; - graph->V=V; - graph->E=E; - graph->edge=new Edge[E]; - return graph; -} - -void PrintSoln(int dist[],int n) -{ - cout<<"Vertex Distance from source\n"; - for(int i=0;iV; - int E=graph->E; - int dist[V]; - - for(int i=0;iedge[j].src; - int v=graph->edge[j].dest; - int weight=graph->edge[j].weight; - if(dist[u]!=INT_MAX && (dist[u]+weightedge[i].src; - int v=graph->edge[i].dest; - int weight=graph->edge[i].weight; - if(dist[u]!=INT_MAX && (dist[u] + weight < dist[v])) - cout<<"Graph contains negative weight cycle\n"; - } - PrintSoln(dist,V); -} - -int main() -{ - int V = 5; // Number of vertices in graph - int E = 8; // Number of edges in graph - struct Graph* graph = buildGraph(V, E); - - // add edge 0-1 - graph->edge[0].src = 0; - graph->edge[0].dest = 1; - graph->edge[0].weight = -1; - - // add edge 0-2 - graph->edge[1].src = 0; - graph->edge[1].dest = 2; - graph->edge[1].weight = 4; - - // add edge 1-2 - graph->edge[2].src = 1; - graph->edge[2].dest = 2; - graph->edge[2].weight = 3; - - // add edge 1-3 - graph->edge[3].src = 1; - graph->edge[3].dest = 3; - graph->edge[3].weight = 2; - - // add edge 1-4 - graph->edge[4].src = 1; - graph->edge[4].dest = 4; - graph->edge[4].weight = 2; - - // add edge 3-2 - graph->edge[5].src = 3; - graph->edge[5].dest = 2; - graph->edge[5].weight = 5; - - // add edge 3-1 - graph->edge[6].src = 3; - graph->edge[6].dest = 1; - graph->edge[6].weight = 1; - - // add edge 4-3 - graph->edge[7].src = 4; - graph->edge[7].dest = 3; - graph->edge[7].weight = -3; - - BellmanFord(graph, 0); - - return 0; -} diff --git a/Competitive Coding/Graphs/Shortest Path/Bellman Ford/readme.md b/Competitive Coding/Graphs/Shortest Path/Bellman Ford/readme.md deleted file mode 100644 index 1934049a2..000000000 --- a/Competitive Coding/Graphs/Shortest Path/Bellman Ford/readme.md +++ /dev/null @@ -1,13 +0,0 @@ -## Bellman Ford Algorithm - -#### Description -This is a dynamic programming based algorithm, this algorithm gives shortest distance from a particular source in a graph to all its other vertices. - ---------- -![](http://users.informatik.uni-halle.de/~jopsi/dssea/bellman_ford.gif) - ------------ -#### Working -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. - -[More info](https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm) diff --git a/Competitive Coding/Graphs/Shortest Path/Floyd Warshall/Floyd_Warshall.cpp b/Competitive Coding/Graphs/Shortest Path/Floyd Warshall/Floyd_Warshall.cpp deleted file mode 100644 index 12e68a158..000000000 --- a/Competitive Coding/Graphs/Shortest Path/Floyd Warshall/Floyd_Warshall.cpp +++ /dev/null @@ -1,57 +0,0 @@ -#include -using namespace std; -#define lli long long int -#define infinite numeric_limits::max() -#define Min(a,b) ((a)<(b)?(a):(b)) -#define Max(a,b) ((a)>(b)?(a):(b)) -#define fr(i,j,s) for(i = j ; i < s ; i++) -#define ifr(i,j,s) for(i = j ; i >= s , i--) -void floydWasrshall(lli G[][400],int V) -{ - int u , v , w; - fr(u,0,V) - { - fr(v,0,V) - { - fr(w,0,V) - { - if(G[v][u]+G[u][w] < G[v][w]) - G[v][w] = G[v][u]+G[u][w] ; - } - } - } -} -int main(void) -{ - int test,v,e,a,b,i,j; - lli wt; - cin>>v>>e; - int ed = 0; - lli graph[400][400]; - int temp = e ; - fr(i,0,v) - { - fr(j,0,v) - { - graph[i][j] = infinite ; - if(i==j) - graph[i][j] = 0; - } - } - while(e--) - { - cin>>a>>b>>wt; - graph[a-1][b-1] = wt; - } - lli q ; - cin>>q; - floydWasrshall(graph,v); - while(q--) - { - cin>>a>>b; - if(graph[a-1][b-1] == infinite ) - graph[a-1][b-1] = -1 ; - cout< -using namespace std; -#define lli long long int -#define infinite 0xffff -#define Min(a,b) ((a)<(b)?(a):(b)) -#define Max(a,b) ((a)>(b)?(a):(b)) -#define fr(i,j,s) for(i = j ; i < s ; i++) -#define ifr(i,j,s) for(i = j ; i >= s , i--) -struct adjListNode -{ - int dest; - int wt; - struct adjListNode *next; -}; -struct adjList -{ - struct adjListNode *head; -}; -struct Graph -{ - int V ; - struct adjList *array; -}; -struct adjListNode * newAdjNode(int dest, int wt) -{ - struct adjListNode *newNode = (struct adjListNode* )malloc(sizeof(struct adjListNode)); - newNode->dest = dest; - newNode->wt = wt; - newNode->next = NULL ; - return newNode; -} -struct Graph* createGraph(int V,int E) -{ - int i ; - struct Graph* G = (struct Graph *)malloc(sizeof(struct Graph)); - G->V = V ; - G->array = (struct adjList*)malloc(E*sizeof(struct adjList)); - fr(i,0,V) - { - G->array[i].head = NULL ; - } - return G ; -} -void addEdge(struct Graph *G,int src, int dest, int wt) -{ - struct adjListNode*temp=newAdjNode(dest,wt); - temp->next=G->array[src].head; - G->array[src].head=temp; - - temp=newAdjNode(src,wt); - temp->next=G->array[dest].head; - G->array[dest].head=temp; -} -struct MinHeapNode -{ - int v; - int dist; -}; -struct MinHeap -{ - int size; - int capacity; - int *pos; - struct MinHeapNode **array; -}; -struct MinHeapNode* newMinHeapNode(int v, int dist) -{ - struct MinHeapNode* minHeapNode = - (struct MinHeapNode*) malloc(sizeof(struct MinHeapNode)); - minHeapNode->v = v; - minHeapNode->dist = dist; - return minHeapNode; -} -struct MinHeap* createMinHeap(int capacity) -{ - struct MinHeap* minHeap = - (struct MinHeap*) malloc(sizeof(struct MinHeap)); - minHeap->pos = (int *)malloc(capacity * sizeof(int)); - minHeap->size = 0; - minHeap->capacity = capacity; - minHeap->array = - (struct MinHeapNode**) malloc(capacity * sizeof(struct MinHeapNode*)); - return minHeap; -} -void swapMinHeapNode(struct MinHeapNode** a, struct MinHeapNode** b) -{ - struct MinHeapNode* t = *a; - *a = *b; - *b = t; -} -void minHeapify(struct MinHeap* minHeap, int idx) -{ - int smallest, left, right; - smallest = idx; - left = 2 * idx + 1; - right = 2 * idx + 2; - - if (left < minHeap->size && - minHeap->array[left]->dist < minHeap->array[smallest]->dist ) - smallest = left; - - if (right < minHeap->size && - minHeap->array[right]->dist < minHeap->array[smallest]->dist ) - smallest = right; - - if (smallest != idx) - { - MinHeapNode *smallestNode = minHeap->array[smallest]; - MinHeapNode *idxNode = minHeap->array[idx]; - - minHeap->pos[smallestNode->v] = idx; - minHeap->pos[idxNode->v] = smallest; - - swapMinHeapNode(&minHeap->array[smallest], &minHeap->array[idx]); - - minHeapify(minHeap, smallest); - } -} - -int isEmpty(struct MinHeap* minHeap) -{ - return minHeap->size == 0; -} - -struct MinHeapNode* extractMin(struct MinHeap* minHeap) -{ - if (isEmpty(minHeap)) - return NULL; - - struct MinHeapNode* root = minHeap->array[0]; - - struct MinHeapNode* lastNode = minHeap->array[minHeap->size - 1]; - minHeap->array[0] = lastNode; - - minHeap->pos[root->v] = minHeap->size-1; - minHeap->pos[lastNode->v] = 0; - - --minHeap->size; - minHeapify(minHeap, 0); - - return root; -} - -void decreaseKey(struct MinHeap* minHeap, int v, int dist) -{ - int i = minHeap->pos[v]; - - minHeap->array[i]->dist = dist; - - while (i && minHeap->array[i]->dist < minHeap->array[(i - 1) / 2]->dist) - { - minHeap->pos[minHeap->array[i]->v] = (i-1)/2; - minHeap->pos[minHeap->array[(i-1)/2]->v] = i; - swapMinHeapNode(&minHeap->array[i], &minHeap->array[(i - 1) / 2]); - i = (i - 1) / 2; - } -} - -bool isInMinHeap(struct MinHeap *minHeap, int v) -{ - if (minHeap->pos[v] < minHeap->size) - return true; - return false; -} -void printarr(int dist[], int v , int src) -{ - int i ; - fr(i,0,v) - { - if(i==src) - continue; - if(dist[i] == infinite) - dist[i] = -1 ; - cout<V; - int dist[V]; - struct MinHeap * minHeap = createMinHeap(V); - fr(i,0,V) - { - dist[i] = infinite ; - minHeap->array[i] = newMinHeapNode(i,dist[i]); - minHeap->pos[i] = i ; - } - minHeap->array[src] = newMinHeapNode(src,dist[src]) ; - minHeap->pos[src] = src ; - dist[src] = 0 ; - decreaseKey(minHeap,src,dist[src]); - minHeap->size = V ; - while(!isEmpty(minHeap)) - { - struct MinHeapNode* minHeapNode = extractMin(minHeap); - int u = minHeapNode->v; - struct adjListNode* pCrawl = G->array[u].head; - while (pCrawl != NULL) - { - int v = pCrawl->dest; - if (isInMinHeap(minHeap, v) && dist[u] != INT_MAX && pCrawl->wt + dist[u] < dist[v]) - { - dist[v] = dist[u] + pCrawl->wt; - decreaseKey(minHeap, v, dist[v]); - } - pCrawl = pCrawl->next; - } - } - printarr(dist,V,src); -} -int main(void) -{ - int test,v,e,a,b,wt; - cin>>test; - while(test--) - { - cin>>v>>e; - struct Graph* G = createGraph(v,e); - while(e--) - { - cin>>a>>b>>wt; - addEdge(G,a-1,b-1,wt); - } - cin>>a; - dijsktra(G,a-1); - } - return 0; -} diff --git a/Competitive Coding/Graphs/Topological Sort/readme.md b/Competitive Coding/Graphs/Topological Sort/readme.md deleted file mode 100644 index 9bf95a32d..000000000 --- a/Competitive Coding/Graphs/Topological Sort/readme.md +++ /dev/null @@ -1,21 +0,0 @@ -### Topological Sort - --------------------------------------- - -#### Algorithm Steps - - -MAX holds the maximum number of vertices possible in the graph, if you want more than 100 vertices chnge the value of MAX on line 4. -The first function called in the main is the create_graph(), which creates i.e. stores every edge along with its direction present in the graph. - -After this we calculate the in degree for each vertex and store it in the array indegree[i]. -If for any vertex the in-degree is 0 , it signifies that all the prerequisites of that vertex are considered and it is safe to be added in the queue. - -Then a loop continues till the queue is empty or count==total vertices. -Inside the loop a vertex is deleted from the queue and all the outgoing edges are considered ,as the indegree of all the destination vertices with this particular vertex(deleted vertex) as origin is decremented by 1. - -After the loop is completed it is checked if the count==total vertices. - -If yes a proper topological sort obtained is printed else it can be concluded that there exists a cycle in the graph and topological sort can't be obtained. - - diff --git a/Competitive Coding/Graphs/Topological Sort/topological.cpp b/Competitive Coding/Graphs/Topological Sort/topological.cpp deleted file mode 100644 index f1c81430f..000000000 --- a/Competitive Coding/Graphs/Topological Sort/topological.cpp +++ /dev/null @@ -1,148 +0,0 @@ -#include -#include - -#define MAX 100 - -void create_graph(); -void add(int vertex); -int del(); -int isEmpty(); -int find_indegree_of_vertex(int vertex); - -int total_vertices; -int adjacent_matrix[MAX][MAX]; -int queue[MAX]; -int front = -1; -int rear = -1; - -int main() -{ - int i, count, topological_sort[MAX], indegree[MAX]; - create_graph(); - //calculating the in-degree for all vertices. - for(i = 0; i < total_vertices; i++) - { - indegree[i] = find_indegree_of_vertex(i); - if(indegree[i] == 0) - { - add(i); - } - } - count = 0; - while(!isEmpty() && count < total_vertices) - { - int vertex = del(); - topological_sort[++count] = vertex; - for(i = 0; i < total_vertices; i++) - { - if(adjacent_matrix[vertex][i] == 1) - { - adjacent_matrix[vertex][i] = 0; - indegree[i] = indegree[i] - 1; - if(indegree[i] == 0) - { - add(i); - } - } - } - } - //count < number of vertices implies all vertices could not be covered as there exists a cycle. - if(count < total_vertices) - { - printf("Graph is Cyclic. Therefore, Topological Ordering Not Possible\n"); - exit(1); - } - printf("Topological Order of Vertices\n"); - for(i = 1; i <= count; i++) - { - printf("%3d", topological_sort[i]); - } - printf("\n"); - return 0; -} -// Function to add a vertex in the queue -void add(int vertex) -{ - if(rear == MAX - 1) - { - printf("Queue Overflow\n"); - } - else - { - if (front == -1) - { - front = 0; - } - rear = rear + 1; - queue[rear] = vertex ; - } -} -//Queue is empty or not -int isEmpty() -{ - if(front == -1 || front > rear ) - { - return 1; - } - else - { - return 0; - } -} -//Delete the front element of the queue -int del() -{ - - if (front == -1 || front > rear) - { - printf("Queue Underflow\n"); - exit(1); - } - else - { - int element = queue[front]; - front = front+1; - return element; - } -} -//Calculate the in-degree of the vertex -int find_indegree_of_vertex(int vertex) -{ - int count, total_indegree = 0; - for(count = 0; count < total_vertices; count++) - { - if(adjacent_matrix[count][vertex] == 1) - { - total_indegree++; - } - } - return total_indegree; -} -//Generate the required graph -void create_graph() -{ - int count, maximum_edges, origin_vertex, destination_vertex; - printf("Enter number of vertices:\t"); - scanf("%d", &total_vertices); - //Maximum edges possible with fixed number of vertices. - maximum_edges = total_vertices * (total_vertices - 1); - for(count = 1; count <= maximum_edges; count++) - { - printf("Enter Edge [%d] co-ordinates (-1 -1 to quit)\n", count); - printf("Enter Origin Vertex:\t"); - scanf("%d", &origin_vertex); - printf("Enter Destination Vertex:\t"); - scanf("%d", &destination_vertex); - if((origin_vertex == -1) && (destination_vertex == -1)) - { - break; - } - if(origin_vertex >= total_vertices || destination_vertex >= total_vertices || origin_vertex < 0 || destination_vertex < 0) - { - printf("Edge Co-ordinates are Invalid\n"); - count--; - } - else - adjacent_matrix[origin_vertex][destination_vertex] = 1; - } -} diff --git a/Competitive Coding/Greedy/Huffman Coding/Huffman_Coding.py b/Competitive Coding/Greedy/Huffman Coding/Huffman_Coding.py deleted file mode 100644 index 3273104df..000000000 --- a/Competitive Coding/Greedy/Huffman Coding/Huffman_Coding.py +++ /dev/null @@ -1,58 +0,0 @@ -string = 'BCAADDDCCACACAC' - - -# Creating tree nodes -class NodeTree(object): - - def __init__(self, left=None, right=None): - self.left = left - self.right = right - - def children(self): - return (self.left, self.right) - - def nodes(self): - return (self.left, self.right) - - def __str__(self): - return '%s_%s' % (self.left, self.right) - - -# Main function implementing huffman coding -def huffman_code_tree(node, left=True, binString=''): - if type(node) is str: - return {node: binString} - (l, r) = node.children() - d = dict() - d.update(huffman_code_tree(l, True, binString + '0')) - d.update(huffman_code_tree(r, False, binString + '1')) - return d - - -# Calculating frequency -freq = {} -for c in string: - if c in freq: - freq[c] += 1 - else: - freq[c] = 1 - -freq = sorted(freq.items(), key=lambda x: x[1], reverse=True) - -nodes = freq - -while len(nodes) > 1: - (key1, c1) = nodes[-1] - (key2, c2) = nodes[-2] - nodes = nodes[:-2] - node = NodeTree(key1, key2) - nodes.append((node, c1 + c2)) - - nodes = sorted(nodes, key=lambda x: x[1], reverse=True) - -huffmanCode = huffman_code_tree(nodes[0][0]) - -print(' Char | Huffman code ') -print('----------------------') -for (char, frequency) in freq: - print(' %-4r |%12s' % (char, huffmanCode[char])) diff --git a/Competitive Coding/Greedy/Huffman Coding/Readme.md b/Competitive Coding/Greedy/Huffman Coding/Readme.md deleted file mode 100644 index 767167e53..000000000 --- a/Competitive Coding/Greedy/Huffman Coding/Readme.md +++ /dev/null @@ -1,18 +0,0 @@ -Python Implementation of Huffman Coding using Greedy Approach. -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. -It follows a Greedy approach since it deals with generating minimum length prefix-free binary codes. -It uses variable-length encoding scheme for assigning binary codes to characters depending on how frequently they occur in the given text. -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. -It follows this procedure: - - -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) - -Repeat Steps 3 to 5 while heap has more than one node - -Extract two nodes, say x and y, with minimum frequency from the heap - -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) - -Add z to min heap - -Last node in the heap is the root of Huffman tree diff --git a/Competitive Coding/Greedy/Knapsack/README.md b/Competitive Coding/Greedy/Knapsack/README.md deleted file mode 100644 index 1ae6579ca..000000000 --- a/Competitive Coding/Greedy/Knapsack/README.md +++ /dev/null @@ -1,22 +0,0 @@ -# 0-1 Knapsack Problem -------------------------- -![](https://upload.wikimedia.org/wikipedia/commons/f/fd/Knapsack.svg) - - 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. - - ## Applications - ----------------------------- - Knapsack problems appear in real-world decision-making processes in a wide variety of fields: - * Finding the least wasteful way to cut raw materials - * Selection of investments and portfolios - * Selection of assets for asset-backed securitization - * Generating keys for the Merkle–Hellman cryptosystems - -## Computational Complexity - -------- - * The decision problem form of the knapsack problem is NP-complete - * The optimization problem is NP-hard - * There is a pseudo-polynomial time algorithm using dynamic programming - * Many cases that arise in practice, and "random instances" from some distributions, can nonetheless be solved exactly - - ![More info](https://en.wikipedia.org/wiki/Knapsack_problem) diff --git a/Competitive Coding/Greedy/Knapsack/knapsack.cpp b/Competitive Coding/Greedy/Knapsack/knapsack.cpp deleted file mode 100644 index ddc175650..000000000 --- a/Competitive Coding/Greedy/Knapsack/knapsack.cpp +++ /dev/null @@ -1,44 +0,0 @@ -// This C++ program solves the 0-1 knapsack problem. A very famous Dynamic Programming problem. -#include -using namespace std; -typedef long long ll; - -ll knapsack(ll V[], ll W[], ll n, ll maxWeight) -{ - ll K[n + 1][maxWeight + 1]; // Declaring the table for dynamic programming. - for(ll i = 0; i <= n; i++) - { - for(ll j = 0; j <= maxWeight; j++) - { - if(i == 0 || j == 0) - K[i][j] = 0; //Covering the base cases. - - else if(W[i - 1] <= j)// If the weight of the element is less than the capacity. - 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. - - else - K[i][j] = K[i - 1][j]; // If the weight of the element is more than the capacity, then leave this element. - } - } - return K[n][maxWeight]; -} - -int main() -{ - ll n; - cout << "Enter the value of n (The number of elements)." << endl; - cin >> n; - ll V[n], W[n]; - cout << "Enter " << n << " space separated integers denoting the values." << endl; - for(ll i = 0; i < n; i++) - cin >> V[i]; - cout << "Enter " << n << " space separated integers denoting the weights." << endl; - for(ll i = 0; i < n; i++) - cin >> W[i]; - ll maxWeight; - cout << "Enter the value of the capacity of the knapsack" << endl; - cin >> maxWeight; - cout << "The maximum total value obtained with the following knapsack" << endl; - cout << knapsack(V, W, n, maxWeight) << endl; - return 0; -} diff --git a/Competitive Coding/Linked List/Linked_Lists_based_on_Arrays/LInked_List_Operations_[Array].cpp b/Competitive Coding/Linked List/Linked_Lists_based_on_Arrays/LInked_List_Operations_[Array].cpp deleted file mode 100644 index 0d988587a..000000000 --- a/Competitive Coding/Linked List/Linked_Lists_based_on_Arrays/LInked_List_Operations_[Array].cpp +++ /dev/null @@ -1,146 +0,0 @@ -#include -#include -template -class LinearList -{ - private: - int length; - int MaxSize; - T *element; - public: - explicit LinearList(int MaxLinearSize=10); //To create a Linked List [A Constructor] - LinearList(const LinearList &L); //A Copy Constructor - ~LinearList(){delete[]element;} //To delete the Linked List from the memory [A Destructor] - int isEmpty()const{return length==0;} //To check if the Linked List is empty - int Length()const{return length;} //To find the length of a Linked List - int Find(int k,T&x)const; //To get the Value at the given position of the Linked List - int Search(const T&x)const; //To check if an element is present in the Linked List - void Delete(int k,T&x); //To delete a specific element from a Linked List - void Insert(int k,const T&x); //To insert an element onto a Linked List - void Output()const; //To display the Linked List -}; - template -LinearList::LinearList(int MaxListSize) -{ - MaxSize=MaxListSize; - element=new T[MaxSize]; - length=0; -} -template -int LinearList::Find(int k,T&x)const -{ - if(k<1||k>length) - return 0; - x=element[k-1]; - return 1; -} -template -int LinearList::Search(const T&x)const -{ - for(int i=0;i -void LinearList::Delete(int k,T&x) -{ - if(Find(k,x)) - { - for(int i=k;i -void LinearList::Insert(int k,const T&x) -{ - if(k<0||k>length) - cout<<"out of bounds\n"; - if(length==MaxSize) - cout<<"no memory\n"; - for(int i=length-1;i>=k;i--) - element[i+1]=element[i]; - element[k]=x; - length++; -} -template -void LinearList::Output()const -{ - if(isEmpty()) - cout<<"list is empty\n"; - else - for(int i=0;i obj; - do - { - menu(); - cout<<"enter choice\t"; - cin>>ch; - switch(ch) { - case 1: - len=obj.Length(); - if(len==0) - cout<<"List is empty\n"; - else - cout<<"length of linearlist is "<>k>>x; - p=obj.Find(k,x); - if(p==1) - cout<<"found"<>x; - p=obj.Search(x); - if(p) - cout<<"searching is sucessful and found at"<>k>>x; - obj.Delete(k,x); - break; - case 5: - cout<<"enter k,x(index and value)\n"; - cin>>k>>x; - obj.Insert(k,x); - break; - case 6: - cout<<"elements in the list are:\n\n"; - obj.Output(); - break; - default: - cout<<"invalid choice\n"; - break; - } } while(ch>=1&&ch<=6); - getch(); -} \ No newline at end of file diff --git a/Competitive Coding/Linked List/Linked_Lists_based_on_Arrays/README.md b/Competitive Coding/Linked List/Linked_Lists_based_on_Arrays/README.md deleted file mode 100644 index f8b986b4e..000000000 --- a/Competitive Coding/Linked List/Linked_Lists_based_on_Arrays/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# Linked List operations - -**This folder contains files that have the following algorithms** - - 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) - - * 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) - * 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) - * 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) - * 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) - * 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) - * 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) \ No newline at end of file diff --git a/Competitive Coding/Linked List/Linked_Lists_based_on_POINTERS/Linked_List_operation.cpp b/Competitive Coding/Linked List/Linked_Lists_based_on_POINTERS/Linked_List_operation.cpp deleted file mode 100644 index 4ac5dfacc..000000000 --- a/Competitive Coding/Linked List/Linked_Lists_based_on_POINTERS/Linked_List_operation.cpp +++ /dev/null @@ -1,438 +0,0 @@ -//Pointer based implementation of Linklist -//All basic operations. -#include -using namespace std; -struct node{ - int d; - node* next; -}; - - -class linklist{ - private: - node* start; - - public: - linklist(); - void append(int ); - void add_beg(int ); - void add_middle(int); - void add_after(int , int ); - void display(); - void del_middle(); - int count(); - void del(int ); - void sort(); - linklist reverse(); - void merge(linklist, linklist); -}; -//Default constructor -linklist :: linklist() -{ - //Initialize start with NULL - start= NULL; -} - -//Add element at last of the list -void linklist::append(int x) -{ - //Creating the new node - node* temp = new node; - - //assigning the data in the node - temp->d=x; - - //putting next of the node to NULL - temp->next= NULL; - - //If list is empty - if(start== NULL) - { - start= temp; - } - else - { - node* t; - t= start; - - //this will find the pointer to last node of the list - while(t->next!= NULL) - { - t=t->next; - } - - //update the last node's next pointer with the pointer to the new node - t->next= temp; - } -} - -//Add element at the begining of the list -void linklist::add_beg(int x) -{ - //creating new node - node* temp= new node; - - //assigning the data in the node - temp->d= x; - - //putting nexy of the node to the NULL - temp->next= NULL; - - //If list is empty - if(start==NULL) - { - start= temp; - } - else - { - //update the next of current node with start - temp->next= start; - - //updating start - start= temp; - } -} - -//returns the number of nodes in the linklist. -int linklist::count() -{ - int count=0; - - //create temporary node - //assigned it with start - node* temp= start; - - //traverse the whole list - while(temp!=NULL) - { - //updating count - count++; - //updating temp - temp=temp->next; - } - return count; -} - -//Add element at the middle of the list -void linklist::add_middle(int x) -{ - //total number of nodes in the list - int len=count(); - - int n; - node* t = start; - - //creating new node and assigning the values - node* temp= new node; - temp->d=x; - temp->next=NULL; - - //if list has even numbers of node, then add it at len/2 - if(len%2==0) - n=len/2; - else - n=((len/2)+1); - - //if the list is empty - if(n==0) - { - start=temp; - return; - } - - //traversing to the n'th node - for(int i=1;inext; - } - //updating temp - temp->next=t->next; - t->next=temp; - return; -} - -//Add element after specific position -void linklist::add_after(int pos, int x) -{ - //creating new node and assigning values in it - node* temp= new node; - temp->d=x; - temp->next=NULL; - - node* t = start; - int len=count(); - - //if entered position is greater then number of node present in list - if(pos>len) - { - cout<<"Invalid Position To Add Data"<next; - } - - temp->next= t->next; - t->next= temp; - } -} - -//Display all the contains of linklist. -void linklist::display() -{ - node* t; - t= start; - - while(t!= NULL) - { - cout<d<next; - } -} - -//Delete the middle element from the list -void linklist::del_middle() -{ - int n, len=0; - node* t= start; - - //counting total number of nodes - len=count(); - - //if even numbers of nodes are there in the list - if(len%2==0) - n= len/2; - else - n=(len/2)+1; - - //if list is empty - if(n==0) - { - cout<<"List is empty"; - return; - } - - //if there is only 1 element i.e. only start node is there - if(n==1&& len==1) - { - delete start; - start=NULL; - return; - } - - //if 2 nodes are present in the list - if(n==1&& len==2) - { - delete start; - start=t->next; - return; - } - else //more than two nodes are there in the list - { - //traversed to middle node - for(int i=1;inext; - } - node* t1=t->next; - t->next=t->next->next; - delete t1; - } - } - - - -//Delete a specific element from the list. -void linklist::del(int x) -{ - //creating temporary node - node* temp = start; - node* t1; - - //if start node is that node - if(start->d== x) - { - t1=start->next; - delete start; - start= t1; - } - else - { - int flag=0; - //traversing to that node - while(temp->next!=NULL) - { - if(temp->next->d== x) - { - t1= temp->next->next; - delete temp->next; - temp->next = t1; - flag=1; - break; - } - - temp= temp->next; - } - //if the value is not present in the list - if(flag==0) - cout<<"Error: Element Not Found"<d>t->d) - { - swap(current_node->d,t->d); - } - t=t->next; - } - temp=temp->next; - } -} - -//takes two sorted list in increasing order and merge them. -void linklist::merge(linklist h, linklist k) -{ - //creating two node pointer and initialized with it by start pointers - node* t1 = h.start; - node* t2 = k.start; - - //traversing till the end of any list - while(t1!= NULL && t2!= NULL) - { - if(t1->d < t2->d) - { - node* temp = new node; - temp->d= t1->d; - temp->next= NULL; - if(start== NULL) - { - start = temp; - } - else - { - node* t; - t= start; - while(t->next!= NULL) - { - t=t->next; - } - t->next= temp; - } - t1= t1->next; - } - else - { - node* temp = new node; - temp->d= t2->d; - temp->next= NULL; - if(start== NULL) - { - start = temp; - } - else - { - node* t; - t= start; - while(t->next!= NULL) - { - t=t->next; - } - t->next= temp; - } - t2= t2->next; - } - } - - //merge remaining nodes of list 1 if any - while(t1!=NULL) - { - node* temp = new node; - temp->d= t1->d; - temp->next= NULL; - node* t; - t= start; - while(t->next!= NULL) - { - t=t->next; - } - t->next= temp; - t1= t1->next; - } - - //merge remaining nodes of list 2 if any - while(t2!=NULL) - { - node* temp = new node; - temp->d= t2->d; - temp->next= NULL; - node* t; - t= start; - while(t->next!= NULL) - { - t=t->next; - } - t->next= temp; - t2=t2->next; - } - -} - -//Reverse the elements of the linklist -linklist linklist::reverse() -{ - //reverse the linklist - node* t=start; - linklist temp; - for(int i=1;i<=count();i++) - { - //adding the elements from the last to the new linklist - temp.add_beg(t->d); - t=t->next; - } - return temp; -} - -//Main function -int main() -{ - linklist l; - l.append(5); - l.append(54); - l.append(64); - l.append(55); - l.add_beg(56); - l.add_beg(88); - l.add_after(5, 23); - l.add_after(2, 6); - l.del(98); - l.del(45); - l.add_middle(5); - l.del_middle(); - - l.display(); - l=l.reverse(); - cout<<"Reversed linklist data"< -using namespace std; - -struct Node{ - int data; - Node* next; -}; - -Node* head=NULL;//Head is declared globally to avoid repeated passing between funcitons - -/*Hash Table to keep track of data in linked list. - The first and second column will keep track of postive - and negative numbers respectively*/ -bool hasht[1000001][2]={0}; - -void Insert(int value)//Function to insert a node at the beginning of the list -{ - Node* newnode=new Node; - newnode->data=value; - newnode->next=head; - head=newnode; -} -void print() -{ - Node* temp=head; - while(temp->next!=NULL)//Printing upto the second last element to avoid '->' at the end - { - cout<data<<"->"; - temp=temp->next; - } - cout<data<<"\n"; -} - -void Remove_Duplicates() -{ - Node* prev=NULL; - Node* temp=head; - - while(temp!=NULL)//Traversing upto the last node in the linked list - { - if(temp->data>=0)//Checking for +ve numbers - { - if(hasht[temp->data][0]==1)//If the number already visited - prev->next=temp->next; //Delete the element by pointing prev to next of current(temp) - else - { - hasht[temp->data][0]=1; //If not visited, mark visited by making the entry to 1 in the hash table - prev=temp; - } - temp=temp->next; - } - else{ //Block for negative numbers - {if(hasht[abs(temp->data)][1]==1) - prev->next=temp->next; - else - { - hasht[abs(temp->data)][1]=1; - prev=temp; - } - temp=temp->next; - } - - } -} -} - - -int main() -{ - //Creating the linked list - Insert(5); - Insert(4); - Insert(7); - Insert(5); - Insert(4); - Insert(5); - Insert(53); - Insert(8); - Insert(45); - Insert(52); - Insert(6); - Insert(100); - Insert(8); - Insert(5); - Insert(25); - Insert(6); - cout<<"Linked List with duplicates:::\n"; - print();//Printing the linked list before removing the duplicate elements - - Remove_Duplicates();//Calling the remove duplicates function - cout<<"\nLinked Lists after duplicates removed:::\n"; - print();//Calling the print function after deleting redundant elements - - } - diff --git a/Competitive Coding/Math/Catalan_Numbers/README.md b/Competitive Coding/Math/Catalan_Numbers/README.md deleted file mode 100644 index fb09e9e5f..000000000 --- a/Competitive Coding/Math/Catalan_Numbers/README.md +++ /dev/null @@ -1,25 +0,0 @@ -The two different programs in this folder contain the same implementation! -The programs basically are a python implementation of the Catalan Numbers. -They're similar to Fibonacci (very slightly) - -The two different implementations vary only in terms of time taken!
-Basically we can implement in 3 different ways!
- -* Recursively - `Exponential time complexity`
-* Dynamic Programming - `O(n^2)`
-* Binomial Coefficient - `O(n)`

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

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

- -Catalan Numbers have a lot of applications in Combinatorics. Some of them are listed below: -* 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. -* 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). -* Cn is the number of semiorders on n unlabeled items. -* In chemical engineering Cn-1 is the number of possible separation sequences which can separate a mixture of n components.

- -### Sources : -(1) Click [here](https://www.geeksforgeeks.org/program-nth-catalan-number/) to know more about Catalan number implementations and its theory.
-(2) Click [here](https://en.wikipedia.org/wiki/Catalan_number) to know more about the applicatations of Catalan Numbers in Combinatorics diff --git a/Competitive Coding/Math/Catalan_Numbers/catalan_binomial.py b/Competitive Coding/Math/Catalan_Numbers/catalan_binomial.py deleted file mode 100644 index dca151dd7..000000000 --- a/Competitive Coding/Math/Catalan_Numbers/catalan_binomial.py +++ /dev/null @@ -1,15 +0,0 @@ -def binCoeff(n, k): #Finds the binomial coefficient - if (k > n - k): #As binCoeff(n,k)=binCoeff(n,n-k) - k = n - k - res = 1 #Initialising Result - for i in range(k): - res = res * (n - i) - res = res / (i + 1) - return res #The binomial coefficient is returned - -def catalan(n): #Function that finds catalan numbers - c = binCoeff(2*n, n) #Finding value of c by calling the binCoeff function - return c/(n + 1) #This is the final catalan number - -if __name__=='__main__': - print "The 10th catalan number is:",catalan(9) diff --git a/Competitive Coding/Math/Catalan_Numbers/catalan_recursive.py b/Competitive Coding/Math/Catalan_Numbers/catalan_recursive.py deleted file mode 100644 index fef4313a4..000000000 --- a/Competitive Coding/Math/Catalan_Numbers/catalan_recursive.py +++ /dev/null @@ -1,10 +0,0 @@ -def catalan_numbers(n): - if n <=1 : #The result will be 1, if the function takes an argument that's equal to or less than 1 - return 1 - res = 0 #Result has been initialised to 0 - for i in range(n): - res += catalan_numbers(i) * catalan_numbers(n-i-1) #The recursive function call - return res - -if __name__=='__main__': - print "The 10th catalan number is:",catalan(9) diff --git a/Competitive Coding/Math/Chinese Remainder Theorem/Modular multiplicative inverse.md b/Competitive Coding/Math/Chinese Remainder Theorem/Modular multiplicative inverse.md deleted file mode 100644 index 13d2b4d28..000000000 --- a/Competitive Coding/Math/Chinese Remainder Theorem/Modular multiplicative inverse.md +++ /dev/null @@ -1,29 +0,0 @@ -Given two integers ‘a’ and ‘m’, find modular multiplicative inverse of ‘a’ under modulo ‘m’. - -The modular multiplicative inverse is an integer ‘x’ such that. - - a x ≡ 1 (mod m) - -The value of x should be in {0, 1, 2, … m-1}, i.e., in the ring of integer modulo m. - -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). - -Examples: - -Input: a = 3, m = 11 - -Output: 4 - -Since (4x3) mod 11 = 1, -4 is modulo inverse of 3 - -One might think, 15 also as a valid output as "(15x3) mod 11" -is also 1, but 15 is not in ring {0, 1, 2, ... 10}, so not -valid. - -Input: a = 10, m = 17 - -Output: 12 - -Since (10x12) mod 17 = 1, 12 is modulo inverse of 3 - diff --git a/Competitive Coding/Math/Chinese Remainder Theorem/README.md b/Competitive Coding/Math/Chinese Remainder Theorem/README.md deleted file mode 100644 index 5157446a5..000000000 --- a/Competitive Coding/Math/Chinese Remainder Theorem/README.md +++ /dev/null @@ -1,87 +0,0 @@ -The Chinese remainder theorem is a theorem of number theory, which states that if one knows the remainders of the Euclidean division of an -integer n by several integers, then one can determine uniquely the remainder of the division of n by the product of these integers, under -the condition that the divisors are pairwise coprime. -SAY......... -We are given two arrays num[0..k-1] and rem[0..k-1]. -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: - - x % num[0] = rem[0], - x % num[1] = rem[1], - ....................... - x % num[k-1] = rem[k-1] - -Basically, we are given k numbers which are pairwise coprime, and given remainders of these numbers when an unknown number x is divided -by them. We need to find the minimum possible value of x that produces given remainders. - -Examples: - -Input: num[] = {5, 7}, rem[] = {1, 3} - -Output: 31 - -Explanation: - -31 is the smallest number such that: - - (1) When we divide it by 5, we get remainder 1. - - (2) When we divide it by 7, we get remainder 3. - -Input: num[] = {3, 4, 5}, rem[] = {2, 3, 1} - -Output: 11 - -Explanation: - -11 is the smallest number such that: - - (1) When we divide it by 3, we get remainder 2. - - (2) When we divide it by 4, we get remainder 3. - - (3) When we divide it by 5, we get remainder 1. - - //////// The solution is based on below formula.\\\\\\\\\\\\ - - -x = ( ∑ (rem[i]*pp[i]*inv[i]) ) % prod - Where 0 <= i <= n-1 - -rem[i] is given array of remainders - -prod is product of all given numbers -prod = num[0] * num[1] * ... * num[k-1] - -pp[i] is product of all but num[i] -pp[i] = prod / num[i] - -inv[i] = Modular Multiplicative Inverse of pp[i] with respect to num[i] - -/// I have explained the Modular multiplicative inverse method by Extended Euclidean algorithms in another file -(Named : Modular multiplicative inverse)./// - -///////WORKING PROCESS\\\\\\\ - -Example: - -Let us take below example to understand the solution - - num[] = {3, 4, 5} - - rem[] = {2, 3, 1} - - prod = 60 - - pp[] = {20, 15, 12} - - inv[] = {2, 3, 3} { (20X2)%3 = 1, (15X3)%4 = 1 - (12X3)%5 = 1} - - x = (rem[0]*pp[0]*inv[0] + rem[1]*pp[1]*inv[1] + rem[2]*pp[2]*inv[2]) % prod - - = (2*20*2 + 3*15*3 + 1*12*3) % 60 - - = (40 + 135 + 36) % 60 - - = 11 - diff --git a/Competitive Coding/Math/Chinese Remainder Theorem/code.cpp b/Competitive Coding/Math/Chinese Remainder Theorem/code.cpp deleted file mode 100644 index 5fb074f9f..000000000 --- a/Competitive Coding/Math/Chinese Remainder Theorem/code.cpp +++ /dev/null @@ -1,83 +0,0 @@ -Below is C++ implementation of above formula. We can use Extended Euclid based method(Described in the folder) discussed here to find inverse modulo. - -// A C++ program to demonstrate working of Chinise remainder Theorem - -// Returns modulo inverse of a with respect to m using extended Euclid Algorithm. - -#include -using namespace std; -int inv(int a, int m) -{ - int m0 = m, t, q; - int x0 = 0, x1 = 1; - - if (m == 1) - return 0; - - // Application of extended Euclid Algorithm - while (a > 1) - { - // q is quotient - q = a / m; - - t = m; - - // m is remainder - m = a % m, a = t; - - t = x0; - - x0 = x1 - q * x0; - - x1 = t; - } - - // Make x1 positive - if (x1 < 0) - x1 += m0; - - return x1; -} - -// k is size of num[] and rem[]. Returns the smallest -// number x such that: -// x % num[0] = rem[0], -// x % num[1] = rem[1], -// .................. -// x % num[k-2] = rem[k-1] -// Assumption: Numbers in num[] are pairwise coprime i.e(gcd for every pair is 1) - -int findMinX(int num[], int rem[], int k) -{ - // Compute product of all numbers - int prod = 1; - for (int i = 0; i < k; i++) - prod *= num[i]; - - // Initialize result - int result = 0; - - // Apply above formula - for (int i = 0; i < k; i++) - { - int pp = prod / num[i]; - result += rem[i] * inv(pp, num[i]) * pp; - } - - return result % prod; -} - -// Main method - -int main(void) -{ - int num[] = {3, 4, 5}; - int rem[] = {2, 3, 1}; - int k = sizeof(num)/sizeof(num[0]); - cout << "x is " << findMinX(num, rem, k); - return 0; -} - -Output: - -x is 11 diff --git a/Competitive Coding/Math/Chinese Remainder Theorem/code_MMI.cpp b/Competitive Coding/Math/Chinese Remainder Theorem/code_MMI.cpp deleted file mode 100644 index b905ff5f3..000000000 --- a/Competitive Coding/Math/Chinese Remainder Theorem/code_MMI.cpp +++ /dev/null @@ -1,50 +0,0 @@ -// Iterative C++ program to find modular inverse using extended Euclid algorithm. -// Returns modulo inverse of a with respect to m using extended Euclid Algorithm. -//Time Complexity of this method is O(Log m). -// Assumption: a and m are coprimes, i.e., gcd(a, m) = 1 - -#include -int modInverse(int a, int m) -{ - int m0 = m, t, q; - int x0 = 0, x1 = 1; - - if (m == 1) - return 0; - - while (a > 1) - { - // q is quotient - q = a / m; - - t = m; - - // m is remainder - m = a % m, a = t; - - t = x0; - - x0 = x1 - q * x0; - - x1 = t; - } - - // Make x1 positive - if (x1 < 0) - x1 += m0; - - return x1; -} - -// Main method -int main() -{ - int a = 3, m = 11; - - printf("Modular multiplicative inverse is %d\n", - modInverse(a, m)); - return 0; -} - -Output: -Modular multiplicative inverse is 4. diff --git a/Competitive Coding/Math/FFT/FastFourierTransform.cpp b/Competitive Coding/Math/FFT/FastFourierTransform.cpp deleted file mode 100644 index b91701aad..000000000 --- a/Competitive Coding/Math/FFT/FastFourierTransform.cpp +++ /dev/null @@ -1,59 +0,0 @@ -#include -using namespace std; - -// For storing complex values of nth roots -// of unity we use complex -typedef complex cd; - -// Recursive function of FFT -vector fft(vector& a) -{ - int n = a.size(); - - // if input contains just one element - if (n == 1) - return vector(1, a[0]); - - // For storing n complex nth roots of unity - vector w(n); - for (int i = 0; i < n; i++) { - double alpha = 2 * M_PI * i / n; - w[i] = cd(cos(alpha), sin(alpha)); - } - - vector A0(n / 2), A1(n / 2); - for (int i = 0; i < n / 2; i++) { - - // even indexed coefficients - A0[i] = a[i * 2]; - - // odd indexed coefficients - A1[i] = a[i * 2 + 1]; - } - - // Recursive call for even indexed coefficients - vector y0 = fft(A0); - - // Recursive call for odd indexed coefficients - vector y1 = fft(A1); - - // for storing values of y0, y1, y2, ..., yn-1. - vector y(n); - - for (int k = 0; k < n / 2; k++) { - y[k] = y0[k] + w[k] * y1[k]; - y[k + n / 2] = y0[k] - w[k] * y1[k]; - } - return y; -} - -// Driver code -int main() -{ - vector a{1, 2, 3, 4}; - vector b = fft(a); - for (int i = 0; i < 4; i++) - cout << b[i] << endl; - - return 0; -} diff --git a/Competitive Coding/Math/FFT/README.md b/Competitive Coding/Math/FFT/README.md deleted file mode 100644 index 55ce41fda..000000000 --- a/Competitive Coding/Math/FFT/README.md +++ /dev/null @@ -1,21 +0,0 @@ -Given two polynomial A(x) and B(x), find the product C(x) = A(x)*B(x). - -A coefficient representation of a polynomial Ax is a = a0, a1, …, an-1. -• Example- -A(x) = 6x^3 + 7x^2 - 10x + 9 -B(x) = -2x^3 + 4x - 5 - Coefficient representation of A(x) = (9, -10, 7, 6) - Coefficient representation of B(x) = (-5, 4, 0, -2) - -Input : - A[] = {9, -10, 7, 6} - B[] = {-5, 4, 0, -2} -Output : - -12x^6 - 14x^5 + 44x^4 - 20x^3 -75x^2 + 86x - 45 - -We can do better, if we represent the polynomial in another form. -yes - -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. - - diff --git a/Competitive Coding/Math/LuckyNumber/README.md b/Competitive Coding/Math/LuckyNumber/README.md deleted file mode 100644 index aea738544..000000000 --- a/Competitive Coding/Math/LuckyNumber/README.md +++ /dev/null @@ -1,16 +0,0 @@ -Lucky Numbers----- -Lucky numbers are subset of integers. - -Take the set of integers -1,2,3,4,5,6,7,8,9,10,11,12,14,15,16,17,18,19,…… - -First, delete every second number, we get following reduced set. -1,3,5,7,9,11,13,15,17,19,………… - -Now, delete every third number, we get -1, 3, 7, 9, 13, 15, 19,….…. - -Continue this process indefinitely…… -Any number that does not get deleted due to above process is called “lucky”. - -Therefore, set of lucky numbers is 1, 3, 7, 13,……… diff --git a/Competitive Coding/Math/LuckyNumber/code.cpp b/Competitive Coding/Math/LuckyNumber/code.cpp deleted file mode 100644 index 873a4ee9d..000000000 --- a/Competitive Coding/Math/LuckyNumber/code.cpp +++ /dev/null @@ -1,36 +0,0 @@ -#include -#define bool int - - -bool isLucky(int n) /* Returns 1 if n is a lucky no. ohterwise returns 0*/ -{ - static int counter = 2; - - - int next_position = n; /*variable next_position is just for readability of - the program we can remove it and use n only */ - if(counter > n) - return 1; - if(n%counter == 0) - return 0; - - - next_position -= next_position/counter; /*calculate next position of input no*/ - - counter++; - return isLucky(next_position); -} - -int main() -{ - int x = 5; - if( isLucky(x) ) - printf("%d is a lucky no.", x); - else - printf("%d is not a lucky no.", x); - getchar(); -} - -/*output*/ -Output: -5 is not a lucky no. diff --git a/Competitive Coding/Math/Primality Test/Fermat Method/README.md b/Competitive Coding/Math/Primality Test/Fermat Method/README.md deleted file mode 100644 index 0eb2a8741..000000000 --- a/Competitive Coding/Math/Primality Test/Fermat Method/README.md +++ /dev/null @@ -1,22 +0,0 @@ -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. - -Fermat's Little Theorem: -If n is a prime number, then for every a, 1 <= a < n, - -a^n-1 ~ 1 mod (n) - OR -a^n-1 % n ~ 1 - - -Example: - - Since 5 is prime, 2^4 ≡ 1 (mod 5) [or 2^4%5 = 1], - - 3^4 ≡ 1 (mod 5) and 4^4 ≡ 1 (mod 5). - - Since 7 is prime, 2^6 ≡ 1 (mod 7), - - 3^6 ≡ 1 (mod 7), 4^6 ≡ 1 (mod 7) - 5^6 ≡ 1 (mod 7) and 6^6 ≡ 1 (mod 7). - -We will take help of this Fermat's Little Theorem as a function to calculate a no is prime or not. diff --git a/Competitive Coding/Math/Primality Test/Fermat Method/SrcCode.cpp b/Competitive Coding/Math/Primality Test/Fermat Method/SrcCode.cpp deleted file mode 100644 index 9e011608d..000000000 --- a/Competitive Coding/Math/Primality Test/Fermat Method/SrcCode.cpp +++ /dev/null @@ -1,64 +0,0 @@ - -#include -using namespace std; - -/* Iterative Function to calculate (a^n)%p in O(logy) */ -int power(int a, unsigned int n, int p) -{ - int res = 1; // Initialize result - a = a % p; // Update 'a' if 'a' >= p - - while (n > 0) - { - // If n is odd, multiply 'a' with result - if (n & 1) - res = (res*a) % p; - - // n must be even now - n = n>>1; // n = n/2 - a = (a*a) % p; - } - return res; -} - -// If n is prime, then always returns true, If n is -// composite than returns false with high probability -// Higher value of k increases probability of correct result. - -bool isPrime(unsigned int n, int k) -{ - // Corner cases - if (n <= 1 || n == 4) return false; - if (n <= 3) return true; - - // Try k times - while (k>0) - { - // Pick a random number in [2..n-2] - // Above corner cases make sure that n > 4 - int a = 2 + rand()%(n-4); - - // Fermat's little theorem - if (power(a, n-1, n) != 1) - return false; - - k--; - } - - return true; -} - -// Driver Program -int main() -{ - int k = 3; - isPrime(11, k)? cout << " true\n": cout << " false\n"; - isPrime(15, k)? cout << " true\n": cout << " false\n"; - return 0; -} - - -Output: - -true -false diff --git a/Competitive Coding/Math/Primality Test/Optimized School Method/README.md b/Competitive Coding/Math/Primality Test/Optimized School Method/README.md deleted file mode 100644 index 0bf8c2b10..000000000 --- a/Competitive Coding/Math/Primality Test/Optimized School Method/README.md +++ /dev/null @@ -1,28 +0,0 @@ -Given a positive integer, check if the number is prime or not. A prime is a natural number greater than 1 that has no -positive divisors other than 1 and itself. - -Examples of first few prime numbers are {2, 3, 5, 7,...} - -Examples: - -**Input:** n = 11 - -**Output:** true - -**Input:** n = 15 - -**Output:** false - -**Input:** n = 1 - -**Output:** false - -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 -any number that divides, we return false. Instead of checking till n, we can check till √n because a larger factor of n -must be a multiple of smaller factor that has been already checked. The algorithm can be improved further by observing -that all primes are of the form 6k ± 1, with the exception of 2 and 3. This is because all integers can be expressed -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 -(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 -form 6k ± 1. - -Time complexity of this solution is O(root(n)). diff --git a/Competitive Coding/Math/Primality Test/Optimized School Method/SrcCode.cpp b/Competitive Coding/Math/Primality Test/Optimized School Method/SrcCode.cpp deleted file mode 100644 index a12867135..000000000 --- a/Competitive Coding/Math/Primality Test/Optimized School Method/SrcCode.cpp +++ /dev/null @@ -1,35 +0,0 @@ -// A optimized school method based C++ program to check if a number is prime or not. - -#include -using namespace std; - -bool isPrime(int n) -{ - // Corner cases - if (n <= 1) return false; - if (n <= 3) return true; - - // This is checked so that we can skip - // middle five numbers in below loop - if (n%2 == 0 || n%3 == 0) return false; - - for (int i=5; i*i<=n; i=i+6) - if (n%i == 0 || n%(i+2) == 0) - return false; - - return true; -} - - -// Driver Program -int main() -{ - isPrime(23)? cout << " true\n": cout << " false\n";//use of ternary operator - isPrime(35)? cout << " true\n": cout << " false\n"; - return 0; -} - -Output: - -true -false diff --git a/Competitive Coding/Math/Project_Euler/Problem_21/P21.class b/Competitive Coding/Math/Project_Euler/Problem_21/P21.class deleted file mode 100644 index d63cf4872..000000000 Binary files a/Competitive Coding/Math/Project_Euler/Problem_21/P21.class and /dev/null differ diff --git a/Competitive Coding/Math/Project_Euler/Problem_21/P21.java b/Competitive Coding/Math/Project_Euler/Problem_21/P21.java deleted file mode 100644 index ebb296391..000000000 --- a/Competitive Coding/Math/Project_Euler/Problem_21/P21.java +++ /dev/null @@ -1,48 +0,0 @@ -package problem_21; -class P21 -{ //Begin class - - - /***** Function to calculate the sum of proper divisors or factors *****/ - public static int sumFactors(int num) - { //Begin sumFactors() - int sum = 0; - - for(int i = 1; i -using namespace std; - -vector SieveOfEratosthenes(int n) -{ - bool prime[n+1]; //To mark those numbers which are prime, prime numbers will be marked by a 'True' - memset(prime,true,sizeof(prime)); - vectorPrimes; - /* - In this nested loop , we start from the value 2, and marked all its multiple which are less then or equal to n, - similarly for 3,4,5....upto n. The logic is simple, since every number which are multiple of 2 are having 2 as a - factor other then 1 and the number itself, similarly for all other numbers. - */ - for(int p=2;p*p<=n;p++) - { - if(prime[p]==true) - { - for(int i=p*2;i<=n;i+=p) - { - prime[i]=false; - } - } - } - /* Pushing all the prime numbers in one container. */ - for(int p=2;p<=n;p++) - { - if(prime[p]) - { - Primes.push_back(p); - } - } - return Primes; -} - -int main() -{ - int n; - cout<<"Enter the number upto which prime numbers are to be found\n"; - cin>>n; - vector result; - result = SieveOfEratosthenes(n); - for(int i=0;i -using namespace std; -// Function to check whether there is -// overflow in a * b or not. Ittreturns -// true if there is overflow. -bool isOverflow(long long a, long long b) -{ - // Check if either of them is zero - if (a == 0 || b == 0) - return false; - - long long result = a * b; - if (a == result / b) - return false; - else - return true; -} - -int main() -{ - long long a; - long long b; - scanf("%lld%lld",&a,&b); - if (isOverflow(a, b)) - cout << "Yes"; - else - cout << "No"; - return 0; -} diff --git a/Competitive Coding/Math/kthPrimeFactor/README.md b/Competitive Coding/Math/kthPrimeFactor/README.md deleted file mode 100644 index 8d24320b7..000000000 --- a/Competitive Coding/Math/kthPrimeFactor/README.md +++ /dev/null @@ -1,6 +0,0 @@ -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). - - -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. - - diff --git a/Competitive Coding/Math/kthPrimeFactor/kthPrimeFactor.cpp b/Competitive Coding/Math/kthPrimeFactor/kthPrimeFactor.cpp deleted file mode 100644 index d647abacf..000000000 --- a/Competitive Coding/Math/kthPrimeFactor/kthPrimeFactor.cpp +++ /dev/null @@ -1,46 +0,0 @@ -// Program to print kth prime factor -# include -using namespace std; - -// A function to generate prime factors of a -// given number n and return k-th prime factor - -int kPrimeFactor(int n, int k) -{ - // Find the number of 2's that divide k - while (n%2 == 0) - { - k--; - n = n/2; - if (k == 0) - return 2; - } - // n must be odd at this point. So we can skip - // one element (Note i = i +2) - for (int i = 3; i <= sqrt(n); i = i+2) - { - // While i divides n, store i and divide n - while (n%i == 0) - { - if (k == 1) - return i; - - k--; - n = n/i; - } - } - // This condition is to handle the case where - // n is a prime number greater than 2 - if (n > 2 && k == 1) - return n; - - return -1; -} - -int main() -{ - int n, k; - scanf("%d%d",&n,&k); - cout << kPrimeFactor(n, k) << endl; - return 0; -} diff --git a/Competitive Coding/Search/Binary Search/Binary_Search.c b/Competitive Coding/Search/Binary Search/Binary_Search.c deleted file mode 100644 index 3f6b21e52..000000000 --- a/Competitive Coding/Search/Binary Search/Binary_Search.c +++ /dev/null @@ -1,39 +0,0 @@ -#include -#include - -int main() { - - int n_terms, *arr, item, i, j, mid, top, bottom; - - - - printf("Enter how many elements you want:\n"); // no of elements - scanf("%d", &n_terms); - arr = (int*)malloc(sizeof(int)*n_terms); - printf("Enter the %d elements in ascending order\n", n_terms); - for (i = 0; i < n_terms; i++) { - scanf("%d", &arr[i]); - } - - printf("\nEnter the item to search\n"); // Target element to be searched - scanf("%d", &item); - bottom = 1; - top = n_terms; - - do { - mid = bottom + (top - bottom)/2 ; // same as (bottom + top / 2) but considers overflow condition when bottom + top might be larger than int - if (item < arr[mid]) - top = mid - 1; // Here we are dividing the array into two equal parts - else if (item > arr[mid]) /* if target element > mid part of array , we do the search in the upper part of the array - else search in the lower part */ - bottom = mid + 1; - } while (item != arr[mid] && bottom <= top); - - if (item == arr[mid]) { - printf("Binary search successfull!!\n"); - printf("%d found in position: %d\n", item, mid + 1); - } else { - printf("Search failed\n%d not found\n", item); - } - return 0; -} diff --git a/Competitive Coding/Search/Interpolation Search/interpolation_search.c b/Competitive Coding/Search/Interpolation Search/interpolation_search.c deleted file mode 100644 index 77f9a48c7..000000000 --- a/Competitive Coding/Search/Interpolation Search/interpolation_search.c +++ /dev/null @@ -1,59 +0,0 @@ -// C program to implement interpolation search -#include - -// If x is present in arr[0..n-1], then returns -// index of it, else returns -1. -int interpolationSearch(int arr[], int n, int x) -{ - // Find indexes of two corners - int lo = 0, hi = (n - 1); - - // Since array is sorted, an element present - // in array must be in range defined by corner - while (lo <= hi && x >= arr[lo] && x <= arr[hi]) - { - // Probing the position with keeping - // uniform distribution in mind. - int pos = lo + (((double)(hi-lo) / - (arr[hi]-arr[lo]))*(x - arr[lo])); - - // Condition of target found - if (arr[pos] == x) - return pos; - - // If x is larger, x is in upper part - if (arr[pos] < x) - lo = pos + 1; - - // If x is smaller, x is in lower part - else - hi = pos - 1; - } - return -1; -} - -// Driver Code -int main() -{ - // Array of items on which search will - // be conducted. - - int n; - int arr[] - scanf("%d",&n); - for(i=0;i -#include -int main() -{ - int *array, search, c, n_terms; - - printf("Enter the number of elements in array\n"); - scanf("%d",&n_terms); // Total no of elements - - array = (int*)malloc(sizeof(int)*n_terms); - printf("Enter %d integer(s)\n", n_terms); - - for (c = 0; c < n_terms; c++) - scanf("%d", &array[c]); // Reading the elements - - printf("Enter the number to search\n"); // Target element to be searched - scanf("%d", &search); - - for (c = 0; c < n_terms; c++) - { - if (array[c] == search) /* if required element found */ - { - printf("%d is present at location %d.\n", search, c+1); - break; - } - } - if (c == n_terms) - printf("%d is not present in array.\n", search); // Element not found - - return 0; -} diff --git a/Competitive Coding/Search/README.md b/Competitive Coding/Search/README.md deleted file mode 100644 index 2f9e9e225..000000000 --- a/Competitive Coding/Search/README.md +++ /dev/null @@ -1,40 +0,0 @@ -## Search Algorithms - -### Linear -![alt text](https://camo.githubusercontent.com/c05ad3f2178af2f16ebe2c04eb122e1e0c6a055b/687474703a2f2f7777772e7475746f7269616c73706f696e742e636f6d2f646174615f737472756374757265735f616c676f726974686d732f696d616765732f6c696e6561725f7365617263682e676966) - -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. - Linear search runs in at worst linear time and makes at most n comparisons, where n is the length of the list. - -__Properties__ -* Worst case performance O(n) -* Best case performance O(1) -* Average case performance O(n) -* Worst case space complexity O(1) iterative - -### Binary -![alt text](https://camo.githubusercontent.com/1cd853b57885449a176810b3e967167fb9fbf3b3/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f662f66372f42696e6172795f7365617263685f696e746f5f61727261792e706e67) - -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. - -__Properties__ -* Worst case performance O(log n) -* Best case performance O(1) -* Average case performance O(log n) -* Worst case space complexity O(1) - -### Interpolation -Interpolation search is an improved version of binary search algorithm. - -![alt text](https://qph.ec.quoracdn.net/main-qimg-02f1f050de01608b9b1f2f27155d1b17) - -Even when the data is sorted, binary search does not take advantage of that to probe the position of desired data. -Position Probing in Interpolation -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. - - -__Properties__ -* Worst case performance O(n) -* Best case performance O(1) -* Average case performance O(log(logn)) -* Worst case space cmplexity O(1) diff --git a/Competitive Coding/Sorting/Bubble Sort/bubble_sort.c b/Competitive Coding/Sorting/Bubble Sort/bubble_sort.c deleted file mode 100644 index 8f47b721f..000000000 --- a/Competitive Coding/Sorting/Bubble Sort/bubble_sort.c +++ /dev/null @@ -1,46 +0,0 @@ - -// BUBBLE SORT - -#include - -void swap(int*,int*); - -void bubblesort(int arr[], int size) -{ - int i, j; - for (i = 0; i < size - 1; i++) // Function where the actual algorithm is implemented - { - for (j = 0; j < size - i - 1; j++) - { - if (arr[j] > arr[j+1]) - swap(&arr[j], &arr[j+1]); - - } - } -} -void swap(int *a, int *b) -{ - int temp; // Function for swapping two variables - temp = *a; - *a = *b; - *b = temp; -} -int main() -{ - int array[100], i, size; - printf("How many numbers you want to sort: "); // Enter the numbers to sort - - scanf("%d", &size); - - printf("\nEnter %d numbers : ", size); - for (i = 0; i < size; i++) - scanf("%d", &array[i]); - bubblesort(array, size); - printf("\nSorted array is "); - - for (i = 0; i < size; i++) - printf(" %d ", array[i]); - printf(" "); - return 0; - -} diff --git a/Competitive Coding/Sorting/Bubble Sort/bubble_sort.cpp b/Competitive Coding/Sorting/Bubble Sort/bubble_sort.cpp deleted file mode 100644 index 42634a7ce..000000000 --- a/Competitive Coding/Sorting/Bubble Sort/bubble_sort.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/* Part of Cosmos by OpenGenus Foundation */ -#include -#include -#include - -void bubble_sort(std::vector &v) -{ - for(int i=0; i < v.size(); ++i) - for(int j=i+1; j < v.size(); ++j) - { - if (v[i] > v[j]) - std::swap(v[i],v[j]); - } -} -int main() -{ - std::vector input_array; - std::cout<<"Enter the number of items in the array: "; - int array_size; - std::cin>>array_size; - for(int i=0;i>input_number; - input_array.push_back(input_number); - } - bubble_sort(input_array); - for(auto x :input_array) - std::cout< -#include -#define RANGE 255 - - -void countSort(char arr[]) -{ - - char output[strlen(arr)]; - - // Create a count array to store count of inidividul - - int count[RANGE + 1], i; - memset(count, 0, sizeof(count)); - - for(i = 0; arr[i]; ++i) - ++count[arr[i]]; - - for (i = 1; i <= RANGE; ++i) - count[i] += count[i-1]; - - // Build the output character array - for (i = 0; arr[i]; ++i) - { - output[count[arr[i]]-1] = arr[i]; - --count[arr[i]]; - } - - // Copy the output array to arr, so that arr now - // contains sorted characters - for (i = 0; arr[i]; ++i) - arr[i] = output[i]; -} - - -int main() -{ - char arr[] = "chirayu";//"jain"; - - countSort(arr); - - printf("Sorted character array is %s", arr); - return 0; -} diff --git a/Competitive Coding/Sorting/Heap Sort/HeapSort.cpp b/Competitive Coding/Sorting/Heap Sort/HeapSort.cpp deleted file mode 100644 index 53660adb8..000000000 --- a/Competitive Coding/Sorting/Heap Sort/HeapSort.cpp +++ /dev/null @@ -1,69 +0,0 @@ -#include -using namespace std; -#define rep(i,a,b,c) for(i=a;ib;i+=c) - -//--------------------------------------Heapify -void max_heapify(int *a, int i, int n) -{ - int l=2*i+1; - int r=2*i+2; - int largest=0; - if(l<=n and a[l]>a[i]) - largest=l; - else - largest=i; - if(r<=n and a[r]>a[largest]) - largest=r; - if(largest!=i) - { - swap(a[largest],a[i]); - max_heapify(a,largest,n); - } -} -//---------------------------------Build max Heap -void build_maxheap(int *a, int n) -{ - int i; - repp(i,n/2,-1,-1) - { - max_heapify(a,i,n); - } -} - -//-----------------------------------HeapSort -void heapsort(int *a, int n) -{ - int i; - build_maxheap(a,n); - repp(i,n,-1,-1) - { - swap(a[0],a[i]); - n--; - max_heapify(a,0,n); - } -} - -int main() -{ - int n, i, x; - cout<<"Enter no of elements of array\n"; - cin>>n; - - //Dynamic Memory Allocation - int *dynamic; - dynamic = new int[n]; - - //Input Of Elements - cout<<"Enter the elements of array :\n"; - rep(i,0,n,1) - cin>>dynamic[i]; - - heapsort(dynamic,n-1); - //Sorted Array using heap sort - cout<< "Sorted Sequence is : " ; - - rep(i,0,n,1) - cout<< dynamic[i]<<"\t"; - delete []dynamic; -} \ No newline at end of file diff --git a/Competitive Coding/Sorting/Heap Sort/Readme.md b/Competitive Coding/Sorting/Heap Sort/Readme.md deleted file mode 100644 index 0aa0582b8..000000000 --- a/Competitive Coding/Sorting/Heap Sort/Readme.md +++ /dev/null @@ -1,23 +0,0 @@ -## Documentation for HeapSort -* Heap sort is a comparison based sorting technique based on Binary Heap data structure. -* Heapsort is an in-place algorithm, but it is not a stable sort. -* Heap Sort is one of the best sorting methods being in-place and with no quadratic worst-case scenarios. -* In max-heaps, maximum element will always be at the root. Heap Sort uses this property of heap to sort the array. - -Heap sort algorithm is divided into two basic parts : - -* Creating a Heap of the unsorted list. - -* Then a sorted array is created by repeatedly removing the largest/smallest element from the heap, and inserting it into the array. - -* The heap is reconstructed after each removal. - -### Complexity of HeapSort - -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). - -* Time Complexity: O(nlogn) - -* Space Complexity: O(1) - - diff --git a/Competitive Coding/Sorting/Heap Sort/Sorting_heapsort_anim.gif b/Competitive Coding/Sorting/Heap Sort/Sorting_heapsort_anim.gif deleted file mode 100644 index f73ccf2ce..000000000 Binary files a/Competitive Coding/Sorting/Heap Sort/Sorting_heapsort_anim.gif and /dev/null differ diff --git a/Competitive Coding/Sorting/Insertion_Sort/insertion_sort.c b/Competitive Coding/Sorting/Insertion_Sort/insertion_sort.c deleted file mode 100644 index 6a07cfc5f..000000000 --- a/Competitive Coding/Sorting/Insertion_Sort/insertion_sort.c +++ /dev/null @@ -1,31 +0,0 @@ -// INSERTION SORT - -#include - -int main(){ - - int i,j,s,temp,a[20]; - - printf("Enter total elements: "); - scanf("%d",&s); - - printf("Enter %d elements: ",s); - for(i=0;i=0) && (temp -#include - -// Function to Merge Arrays L and R into A. -// lefCount = number of elements in L -// rightCount = number of elements in R. -void Merge(int *A,int *L,int leftCount,int *R,int rightCount) { - int i,j,k; - - // i - to mark the index of left aubarray (L) - // j - to mark the index of right sub-raay (R) - // k - to mark the index of merged subarray (A) - i = 0; j = 0; k =0; - - while(i -#include - - -//quick Sort function to Sort Integer array list -void quicksort(int array[], int firstIndex, int lastIndex) -{ - //declaaring index variables - int pivotIndex, temp, index1, index2; - - if(firstIndex < lastIndex) - { - //assigning first element index as pivot element - pivotIndex = firstIndex; - index1 = firstIndex; - index2 = lastIndex; - - //Sorting in Ascending order with quick sort - while(index1 < index2) - { - while(array[index1] <= array[pivotIndex] && index1 < lastIndex) - { - index1++; - } - while(array[index2]>array[pivotIndex]) - { - index2--; - } - - if(index1 -#include -#include -#include -#include -#include - -namespace alg { - /** - * couting sort - */ - static void radix_(int byte, const unsigned N, const uint32_t *source, uint32_t *dest) { - unsigned count[256]; - unsigned index[256]; - memset(count, 0, sizeof (count)); - - unsigned i; - for(i=0; i>(byte*8))&0xff]++; - - index[0]=0; - for(i=1; i<256; ++i) - index[i] = index[i-1] + count[i-1]; - - for(i=0; i>(byte*8))&0xff]++] = source[i]; - } - - /** - * radix sort a given unsigned 32-bit integer array of size N - */ - static void radix_sort(uint32_t *source, const unsigned N) { - uint32_t * temp = new uint32_t[N]; - radix_(0, N, source, temp); - radix_(1, N, temp, source); - radix_(2, N, source, temp); - radix_(3, N, temp, source); - - delete [] temp; - } - - /** - * check whether the array is in order - */ - static void check_order(const uint32_t *data, unsigned N) { - for(--N ; N > 0; --N, ++data) - assert(data[0] <= data[1]); - } -} - -#endif // - - diff --git a/Competitive Coding/Sorting/Selection_Sort/selection_sort.c b/Competitive Coding/Sorting/Selection_Sort/selection_sort.c deleted file mode 100644 index 0e045928c..000000000 --- a/Competitive Coding/Sorting/Selection_Sort/selection_sort.c +++ /dev/null @@ -1,30 +0,0 @@ -#Selection Sort - -#include -int main(){ - - int s,i,j,temp,a[20]; - - printf("Enter total elements: "); // total no of elements - scanf("%d",&s); - - printf("Enter %d elements: ",s); // the elements - for(i=0;ia[j]){ - temp=a[i]; // Compare between 2 consecutive elements and swap them if they are not in ascending order - a[i]=a[j]; - a[j]=temp; - } - } - } - - printf("After sorting is: "); - for(i=0;i 0): #Condition runs until there's a gap - for startposition in range(sublistcount): - gapInsertionSort(test,startposition,sublistcount) - print("After increments of size",sublistcount,"The list is",test) - sublistcount = sublistcount // 2 #value os sublistcount changes after every iteration - -def gapInsertionSort(test,start,gap): #Function which sorts the sublists - for i in range(start+gap,len(test),gap): - currentvalue = test[i] - position = i - while(position>=gap and test[position-gap]>currentvalue): - test[position]=test[position-gap] #changes in values occurs here due to sorting - position = position-gap - test[position]=currentvalue - -if __name__=="__main__": - test = [99,109,29,89,44,98,20,55,31] - shellSort(test) - print test diff --git a/Competitive Coding/Strings/String Search/Knuth-Morris-Pratt_Algorithm.cpp b/Competitive Coding/Strings/String Search/Knuth-Morris-Pratt_Algorithm.cpp deleted file mode 100644 index b635585f7..000000000 --- a/Competitive Coding/Strings/String Search/Knuth-Morris-Pratt_Algorithm.cpp +++ /dev/null @@ -1,80 +0,0 @@ -//C++ code to find a pattern in a given text using KMP algorithm in linear time. -#include - -using namespace std; - -int main() -{ - string text; - string pattern; - - cin>>text;//inputting text - cout<>pattern;//inputting pattern - cout<text_length)//if pattern_length is greater than text it is not possible to find pattern in text. - { - cout<<"Not Found"<= 0: - if string[index + length] == string[index - length]: - length += 1 - else: - break - return length - 1 - -def interleave(string): - ret = [] - for s in string: - ret.extend(['#', s]) - ret.append('#') - return ''.join(ret) -''' Find longest palindrome number ''' -def manacher(string): - right = 0 - center = 0 - string = interleave(string) - P = map(lambda e: 0, xrange(len(string))) - for i in xrange(1, len(string)): - mirror = 2*center - i - if i + P[mirror] <= right and mirror >= len(string) - i: - P[i] = P[mirror] - else: - plength = get_palindrome_length(string, i) - P[i] = plength - if plength > 1: - center = int(i) - right = center + plength - return [e/2 for e in P] -''' Return the palindrome sub-string ''' -def get_palindrome_number(string): - return sum(manacher(string)) diff --git a/Competitive Coding/Strings/String Search/Manachar_algorithm/manchar_algorithm.md b/Competitive Coding/Strings/String Search/Manachar_algorithm/manchar_algorithm.md deleted file mode 100644 index 0e1d258a7..000000000 --- a/Competitive Coding/Strings/String Search/Manachar_algorithm/manchar_algorithm.md +++ /dev/null @@ -1,34 +0,0 @@ -# Manachar's Algorithm - -Manacher's algorithm is a very handy algorithm with a short implementation that -can make many programming tasks, such as finding the number of palindromic substrings -or finding the longest palindromic substring, very easy and efficient. The running -time of Manacher's algorithm is *O(N)* where *N* is the length of the input string. - -## Implementation - -Let: - -1. s be a string of N characters - -2. s2 be a derived string of s, comprising N * 2 + 1 elements, with each element -corresponding to one of the following: the N characters in s, the N-1 boundaries -among characters, and the boundaries before and after the first and last character -respectively - -3. A boundary in s2 is equal to any other boundary in s2 with respect to element -matching in palindromic length determination - -4. p be an array of palindromic span for each element in s2, from center to either -outermost element, where each boundary is counted towards the length of a palindrome -(e.g. a palindrome that is three elements long has a palindromic span of 1) - -5. c be the position of the center of the palindrome currently known to include a -boundary closest to the right end of s2 (i.e., the length of the palindrome = p[c]*2+1) - -6. r be the position of the right-most boundary of this palindrome (i.e., r = c + p[c]) - -7. i be the position of an element (i.e., a character or boundary) in s2 whose palindromic -span is being determined, with i always to the right of c - -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) diff --git a/Competitive Coding/Strings/String Search/Z-algorithm/Readme.md b/Competitive Coding/Strings/String Search/Z-algorithm/Readme.md deleted file mode 100644 index 4c339a4cc..000000000 --- a/Competitive Coding/Strings/String Search/Z-algorithm/Readme.md +++ /dev/null @@ -1,37 +0,0 @@ -# Z Algorithm - -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. - -In this algorithm, we construct a Z array. - -# What is Z array? - -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. -Example: -Index 0 1 2 3 4 5 6 7 8 9 10 11 -Text a a b c a a b x a a a z -Z values X 1 0 0 3 1 0 0 2 2 1 0 - -# How to construct Z array? - -The idea is to maintain an interval [L, R] which is the interval with max R -such that [L,R] is prefix substring (substring which is also prefix). - -Steps for maintaining this interval are as follows – - -1) If i > R then there is no prefix substring that starts before i and - ends after i, so we reset L and R and compute new [L,R] by comparing - str[0..] to str[i..] and get Z[i] (= R-L+1). - -2) If i <= R then let K = i-L, now Z[i] >= min(Z[K], R-i+1) because - str[i..] matches with str[K..] for atleast R-i+1 characters (they are in - [L,R] interval which we know is a prefix substring). - Now two sub cases arise – - a) If Z[K] < R-i+1 then there is no prefix substring starting at - str[i] (otherwise Z[K] would be larger) so Z[i] = Z[K] and - interval [L,R] remains same. - b) If Z[K] >= R-i+1 then it is possible to extend the [L,R] interval - thus we will set L as i and start matching from str[R] onwards and - get new R then we will update interval [L,R] and calculate Z[i] (=R-L+1) - -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. diff --git a/Competitive Coding/Strings/String Search/Z-algorithm/z-algorithm.cpp b/Competitive Coding/Strings/String Search/Z-algorithm/z-algorithm.cpp deleted file mode 100644 index f1f8bbd2a..000000000 --- a/Competitive Coding/Strings/String Search/Z-algorithm/z-algorithm.cpp +++ /dev/null @@ -1,84 +0,0 @@ -#include -using namespace std; -#define fastio ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0) -#define md 1000000007 -#define ll long long int -#define vi vector -#define vll vector -#define pb push_back -#define all(c) (c).begin(),(c).end() -template< class T > T max2(const T &a,const T &b) {return (a < b ? b : a);} -template< class T > T min2(const T &a,const T &b) {return (a > b ? b : a);} -template< class T > T max3(const T &a, const T &b, const T &c) { return max2(a, max2(b, c)); } -template< class T > T min3(const T &a, const T &b, const T &c) { return min2(a, min2(b, c)); } -template< class T > T gcd(const T a, const T b) { return (b ? gcd(b, a%b) : a); } -template< class T > T lcm(const T a, const T b) { return (a / gcd(a, b) * b); } -template< class T > T mod(const T &a, const T &b) { return (a < b ? a : a % b); } -typedef pair pi; -int main() -{ - fastio; - string txt; - string pat; - getline(cin,txt);//getline() reads the complete line in contrary to the traditional cin function which reads just the string before any spaces - getline(cin,pat); - int n = txt.length(); - int pat_len = pat.length(); - 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 - - int len = n+pat_len +1;//length of the total output string - int z_val[len]={0}; - int left =0;//left index of the z box - int right =0;//right index of the z box - int count=0;//count of the match - for(int i=1;i1) - { - left =i; - right = i + count-2; - } - - - if(count<=1) - { - count=0; - for(int j=0;j -# include -# include -# define NO_OF_CHARS 256 - -int -max(int a, int b) -{ - return ((a > b) ? a: b); -} - - -void -badCharHeuristic(char *str, int size, - int badchar[NO_OF_CHARS]) -{ - int i; - - for (i = 0; i < NO_OF_CHARS; i++) - badchar[i] = -1; - - - for (i = 0; i < size; i++) - badchar[(int) str[i]] = i; -} - -void -search(char *txt, char *pat) -{ - int m = strlen(pat); - int n = strlen(txt); - - int badchar[NO_OF_CHARS]; - badCharHeuristic(pat, m, badchar); - int s = 0; - while (s <= (n - m)) { - int j = m-1; - while(j >= 0 && pat[j] == txt[s+j]) - j--; - if (j < 0) { - printf("\n pattern occurs at shift = %d", s); - s += (s+m < n) ? m-badchar[txt[s+m]] : 1; - - } else - s += max(1, j - badchar[txt[s+j]]); - } -} diff --git a/Competitive Coding/Tree/Binary Indexed Tree/Reference.txt b/Competitive Coding/Tree/Binary Indexed Tree/Reference.txt deleted file mode 100644 index e7a6004fd..000000000 --- a/Competitive Coding/Tree/Binary Indexed Tree/Reference.txt +++ /dev/null @@ -1,3 +0,0 @@ -Here are some websites/blogs which inspired and motivated this concept in me. -https://kartikkukreja.wordpress.com/2013/12/02/range-updates-with-bit-fenwick-tree/ -http://zobayer.blogspot.in/2013/11/various-usage-of-bit.html diff --git a/Competitive Coding/Tree/Binary Indexed Tree/SPOJ_ctrick.cpp b/Competitive Coding/Tree/Binary Indexed Tree/SPOJ_ctrick.cpp deleted file mode 100644 index 54660c92a..000000000 --- a/Competitive Coding/Tree/Binary Indexed Tree/SPOJ_ctrick.cpp +++ /dev/null @@ -1,116 +0,0 @@ -#include -#include -#include -#include -#include -using namespace std; -#define lli long long int -#define Min(a,b) (a 0){ - sum += T[index] ; - index = index - (index&(-1*index)); - } - return sum ; -} -void update(lli T[] , lli n , lli index , lli value ){ - index++; - while(index <= n){ - T[index] += value ; - index = index + (index&(-1*index)); - } -} -lli * binary_indexed_tree(lli n){ - lli i ; - lli* T =(lli *) malloc(sizeof(lli)*200002) ; - for(i = 1 ; i <= n+1 ; i++) - { - T[i] = 0 ; - } - for(i = 0 ; i < n ; i++) - { - update(T,n,i,1) ; - } - return T ; -} -void renew(lli* T,lli n) -{ - lli i ; - for(i = 1 ; i <= n+1 ; i++) - { - T[i] = 0 ; - } - for(i = 0 ; i < n ; i++) - { - update(T,n,i,1) ; - } -} - -lli modified_binary_search(lli * T, lli val, lli start , lli end) -{ - lli mid = (start+end)/2 ; - lli mid_sum = sum(T,mid) ; - if((mid_sum == val)&&(hash_array_mod[mid+1] == 0)) - return mid; - else if( (mid_sum > val) || ((mid_sum == val)&&(hash_array_mod[mid+1] != 0)) ) - { - return modified_binary_search(T,val,start,mid-1); - } - else - { - return modified_binary_search(T,val,mid+1,end); - } -} -int main() { - lli test,n,i,j,ans,current_pos,next_pos_sum,next_pos,count,free_space_total; - lli a[200002]; - cin>>test; - lli* T = binary_indexed_tree(n); - while(test--) - { - cin>>n; - //cin>>query; - if(n == 1) - { - cout<<"1"< -#include -#include -#include -#include -using namespace std; -#define lli long long int -#define Min(a,b) (a s ; i--) - -//lli sum( lli index) : returns of arr[index]+arr[index-1]..arr[0] - -//void update( lli n , lli index , lli value ) : adds v to arr[index] - - -lli T[100002]={0} ; -lli sum(lli index){ - lli sum = 0; - index+=1; - while(index > 0){ - sum += T[index] ; - index = index - (index&(-1*index)); - } - return sum ; -} -void update(lli n , lli index , lli value ){ - index++; - while(index <= n){ - T[index] += value ; - index = index + (index&(-1*index)); - } -} -void binary_indexed_tree(lli *a, lli n){ - lli i ; - for(i = 1 ; i <= n+1 ; i++) - { - T[i] = 0 ; - } - //To be Uncommented as per the need - /*for(i = 0 ; i < n ; i++) - { - update(n,i,a[i]) ; - }*/ -} -int main() { - lli test,n,i,j,inversions,position,option,ans,p,q,v; - lli arr[100002]; - lli brr[100002]; - cin>>test; - while(test--) - { - inversions = 0; - cin>>n; - fr(i,0,n) - { - cin>>arr[i]; - brr[i] = arr[i] ; - } - sort(brr,brr+n); - fr(i,0,n) - { - position = ( lli )(lower_bound(brr,brr+n,arr[i])-brr); - arr[i] = position+1 ; - } - binary_indexed_tree(arr,n); - ufr(i,n-1,-1) - { - inversions += sum(arr[i]-1); - update(n,arr[i],1); - } - cout< -#include -#include -#include -#include -using namespace std; -#define lli long long int -#define Min(a,b) (a 0){ - sum += T[index] ; - index = index - (index&(-1*index)); - } - return sum ; -} -void update(lli n , lli index , lli value ){ - index++; - while(index <= n){ - T[index] += value ; - index = index + (index&(-1*index)); - } -} -lli * binary_indexed_tree(lli *a, lli n){ - lli i ; - for(i = 1 ; i <= n+1 ; i++) - { - T[i] = 0 ; - } - for(i = 0 ; i < n ; i++) - { - update(n,i,a[i]) ; - } - return T ; -} -int main() { - lli test,n,i,j,query,option,ans,p,q,v; - lli arr[200002]; - cin>>test; - while(test--) - { - cin>>n; - cin>>query; - fr(i,0,n) - { - arr[i] = 0; - } - binary_indexed_tree(arr,n); - while(query--) - { - cin>>option>>p>>q ; - p--; - q--; - if(option == 0) - { - cin>>v; - update(n,p,v); - if(q != n-1) - update(n,q+1,-1*v); - } - else - { - if(p == 0) - ans = sum(q); - else - ans = sum(q)-sum(p-1) ; - cout< -#include -#include -#include -#include -using namespace std; -#define lli long long int -#define Min(a,b) (a 0){ - sum += T[index] ; - index = index - (index&(-1*index)); - } - return sum ; -} -void update(lli T[] , lli n , lli index , lli value ){ - index++; - while(index <= n){ - T[index] += value ; - index = index + (index&(-1*index)); - } -} -lli * binary_indexed_tree(lli n){ - lli i ; - lli* T =(lli *) malloc(sizeof(lli)*200002) ; - for(i = 1 ; i <= n+1 ; i++) - { - T[i] = 0 ; - } - // for(i = 0 ; i < n ; i++) - // { - // update(T,n,i,a[i]) ; - // } - return T ; -} -int main() { - lli test,n,i,j,query,option,ans,p,q,v; - lli arr[200002]; - cin>>test; - while(test--) - { - cin>>n; - cin>>query; - fr(i,0,n) - { - arr[i] = 0; - } - lli* T1 = binary_indexed_tree(n); - lli* T2 = binary_indexed_tree(n); - while(query--) - { - cin>>option>>p>>q ; - p--; - q--; - if(option == 0) - { - cin>>v; - update(T1,n,p,v); - update(T1,n,q+1,-v); - update(T2,n,p,v*(p-1)); - update(T2,n,q+1,-v*q); - } - else - { - ans = sum(T1,q)*q-sum(T2,q)-sum(T1,p-1)*(p-1)+sum(T2,p-1) ; - cout< -#include -using namespace std; -#define nullptr 0 -typedef struct elem -{ - int val; - struct elem* leftchild; - struct elem* rightchild; - struct elem* parent; -}node;//This is the node for the binary tree. Each element in the binary tree contains a value, a pointer to left child,right child and parent. -class BinaryTree -{ -private: - int n=0; - node* root=nullptr; -public: - void insert(int x)//Insert function first searches for the place where the node can be inserted and then it inserts it there. - { - - if(n==0) - { - root=new node; - root->val=x; - root->leftchild=nullptr; - root->rightchild=nullptr; - root->parent=nullptr; - } - else - { - node* temp=root; - node* newnode=searchnode(x,temp); - if(x>newnode->val) - { - newnode->rightchild=new node; - newnode->rightchild->val=x; - newnode->rightchild->parent=newnode; - newnode->rightchild->leftchild=nullptr; - newnode->rightchild->rightchild=nullptr; - } - else - { - newnode->leftchild=new node; - newnode->leftchild->val=x; - newnode->leftchild->parent=newnode; - newnode->leftchild->leftchild=nullptr; - newnode->leftchild->rightchild=nullptr; - } - - } - n++; - - } - - node* searchnode(int x,node* temproot)//The search function searches for the node whose value is equal to the value it is searching for.It takes O(log n) as it is proportional to the height of the binary tree. - { - - if(temproot->valrightchild!=nullptr) - searchnode(x,temproot->rightchild); - else - return temproot; - } - else - { - if(temproot->val>x)//If value if larger it goes to the left child - { - if(temproot->leftchild!=nullptr) - searchnode(x,temproot->leftchild); - else - return temproot; - } - else - { - if(temproot->val==x)//It returns the value when it is equal - return temproot; - } - } - - } - void printtree(node* temp) - { - if(temp==nullptr) - return; - else - { - printtree(temp->leftchild); - cout<val; - printtree(temp->rightchild); - } - }//This is the function to print the tree. It prints the tree in a sorted order. - node* giveroot() - { - return root; - }//This function returns the pointer to root - node* LCA(node* temp,int val1,int val2)//Here the temp node is a root node. - { - if (temp==nullptr)//If the root node is null then return that node - return temp; - if(temp->val==val1 || temp->val==val2)//If it equals to any of the value than it should be the lowest common ancestor of that sub tree so, it should be returned. - return temp; - else - { - node* left = LCA(temp->leftchild,val1,val2);//If it is not equal to any of the value than we go to its child to look for those value. - node* right = LCA(temp->rightchild,val1,val2); - if(left!=nullptr && right!=nullptr)//if both right and left are some different value than null than that must be the lowest common ancestor in that subtree. - return temp; - else - { - if(left==nullptr && right==nullptr)//If both are null it means that there is no node of that value in the sub tree whose root is the given temp - return nullptr; - else - { - if(left==nullptr)//If any one of the value is null and other is not than the non-null value has to be the lowest common ancestor. - return right; - else - return left; - } - } - } - } - -}; -int main() -{ - int n; - cin>>n; - BinaryTree bst; - for(int i=0;i>temp; - bst.insert(temp); - } - node* temp=bst.giveroot(); - - // bst.printtree(temp); - //temp = bst.giveroot(); - int val1,val2; - cin>>val1>>val2; - node* lca=bst.LCA(temp,val1,val2); - cout<<"lowest common ancestor of the given nodes is "<val< -#include -using namespace std; -#define nullptr 0 -typedef struct elem -{ - int val; - struct elem* leftchild; - struct elem* rightchild; - struct elem* parent; -}node;//This is the node for the binary tree. Each element in the binary tree contains a value, a pointer to left child,right child and parent. -class BinaryTree -{ -private: - int n=0; - node* root=nullptr; -public: - void insert(int x)//Insert function first searches for the place where the node can be inserted and then it inserts it there. - { - - if(n==0) - { - root=new node; - root->val=x; - root->leftchild=nullptr; - root->rightchild=nullptr; - root->parent=nullptr; - } - else - { - node* temp=root; - node* newnode=searchnode(x,temp); - if(x>newnode->val) - { - newnode->rightchild=new node; - newnode->rightchild->val=x; - newnode->rightchild->parent=newnode; - newnode->rightchild->leftchild=nullptr; - newnode->rightchild->rightchild=nullptr; - } - else - { - newnode->leftchild=new node; - newnode->leftchild->val=x; - newnode->leftchild->parent=newnode; - newnode->leftchild->leftchild=nullptr; - newnode->leftchild->rightchild=nullptr; - } - - } - n++; - - } - - node* searchnode(int x,node* temproot)//The search function searches for the node whose value is equal to the value it is searching for.It takes O(log n) as it is proportional to the height of the binary tree. - { - - if(temproot->valrightchild!=nullptr) - searchnode(x,temproot->rightchild); - else - return temproot; - } - else - { - if(temproot->val>x)//If value if larger it goes to the left child - { - if(temproot->leftchild!=nullptr) - searchnode(x,temproot->leftchild); - else - return temproot; - } - else - { - if(temproot->val==x)//It returns the value when it is equal - return temproot; - } - } - - } - void printtree(node* temp) - { - if(temp==nullptr) - return; - else - { - printtree(temp->leftchild); - cout<val; - printtree(temp->rightchild); - } - }//This is the function to print the tree. It prints the tree in a sorted order. - node* giveroot() - { - return root; - }//This function returns the pointer to root - void inorder_traversal(node* temp) - { - if(temp==nullptr) - return ; - else - { - inorder_traversal(temp->leftchild); - cout<val<rightchild); - } - } - -}; -int main() -{ - int n; - cin>>n; - BinaryTree bst; - for(int i=0;i>temp; - bst.insert(temp); - } - node* temp=bst.giveroot(); - - // bst.printtree(temp); - //temp = bst.giveroot(); - bst.inorder_traversal(temp); - -} - - - - - - diff --git a/Competitive Coding/Tree/Binary Tree/level_order_traversal.c b/Competitive Coding/Tree/Binary Tree/level_order_traversal.c deleted file mode 100644 index acf9569de..000000000 --- a/Competitive Coding/Tree/Binary Tree/level_order_traversal.c +++ /dev/null @@ -1,71 +0,0 @@ -/*C programme for Level Order Traversal of a Binary Search Tree - Approach- Recursive*/ - -#include -#include -/*Creating the structure of binary tree node having data amd pointers to left - and right child*/ -typedef struct Node -{ - int data; - struct Node* left; - struct Node* right; - -}T; -//Function Prototypes -T* newnode(int); -void LevelOrder(T*); -T* printGivenLevel(T*,int); -int height(T*); - -int main() -{ - T* root=newnode(1);//Creating the tree - root->left=newnode(3); - root->right=newnode(5); - root->left->left=newnode(6); - root->right->right=newnode(4); - root->left->right=newnode(12); - LevelOrder(root); - -} -//Function to allocates a new node, and initiales the left and right child with NULL -T* newnode(int value) -{ - T* temp=(T*)malloc(sizeof(T)); - temp->data=value; - temp->left=NULL; - temp->right=NULL; - return temp; - -} -//Function that drives the level order traversal of the tree -void LevelOrder(T* root) -{ - int level; - for(level=1;level<=height(root);level++) - {printGivenLevel(root,level);} -} -/*Computes the height of the tree, which is the length of path from the root to - to the deepest leaf node*/ -int height(T* root) -{ - if(root==NULL) - return 0; - int lh=height(root->left); - int rh=height(root->right); - - return lh>rh?lh+1:rh+1; -} - -//Prints the nodes in each level of the tree -T* printGivenLevel(T* root,int level) -{ - if(root==NULL)return NULL; - if(level==1)printf("%d ",root->data); - else{ - printGivenLevel(root->left,level-1); - printGivenLevel(root->right,level-1); - - } -} diff --git a/Competitive Coding/Tree/Binary Tree/postorder_traversal/postorder_traversal.cpp b/Competitive Coding/Tree/Binary Tree/postorder_traversal/postorder_traversal.cpp deleted file mode 100644 index eec9c12ff..000000000 --- a/Competitive Coding/Tree/Binary Tree/postorder_traversal/postorder_traversal.cpp +++ /dev/null @@ -1,135 +0,0 @@ -#include -#include -using namespace std; -#define nullptr 0 -typedef struct elem -{ - int val; - struct elem* leftchild; - struct elem* rightchild; - struct elem* parent; -}node;//This is the node for the binary tree. Each element in the binary tree contains a value, a pointer to left child,right child and parent. -class BinaryTree -{ -private: - int n=0; - node* root=nullptr; -public: - void insert(int x)//Insert function first searches for the place where the node can be inserted and then it inserts it there. - { - - if(n==0) - { - root=new node; - root->val=x; - root->leftchild=nullptr; - root->rightchild=nullptr; - root->parent=nullptr; - } - else - { - node* temp=root; - node* newnode=searchnode(x,temp); - if(x>newnode->val) - { - newnode->rightchild=new node; - newnode->rightchild->val=x; - newnode->rightchild->parent=newnode; - newnode->rightchild->leftchild=nullptr; - newnode->rightchild->rightchild=nullptr; - } - else - { - newnode->leftchild=new node; - newnode->leftchild->val=x; - newnode->leftchild->parent=newnode; - newnode->leftchild->leftchild=nullptr; - newnode->leftchild->rightchild=nullptr; - } - - } - n++; - - } - - node* searchnode(int x,node* temproot)//The search function searches for the node whose value is equal to the value it is searching for.It takes O(log n) as it is proportional to the height of the binary tree. - { - - if(temproot->valrightchild!=nullptr) - searchnode(x,temproot->rightchild); - else - return temproot; - } - else - { - if(temproot->val>x)//If value if larger it goes to the left child - { - if(temproot->leftchild!=nullptr) - searchnode(x,temproot->leftchild); - else - return temproot; - } - else - { - if(temproot->val==x)//It returns the value when it is equal - return temproot; - } - } - - } - void printtree(node* temp) - { - if(temp==nullptr) - return; - else - { - printtree(temp->leftchild); - cout<val; - printtree(temp->rightchild); - } - }//This is the function to print the tree. It prints the tree in a sorted order. - node* giveroot() - { - return root; - }//This function returns the pointer to root - - void postorder_traversal(node* temp) - { - if(temp==nullptr) - return ; - else - { - postorder_traversal(temp->leftchild); - postorder_traversal(temp->rightchild); - cout<val<>n; - BinaryTree bst; - for(int i=0;i>temp; - bst.insert(temp); - } - node* temp=bst.giveroot(); - - // bst.printtree(temp); - //temp = bst.giveroot(); - //bst.inorder_traversal(temp); - bst.preorder_traversal(temp); -} - - - - - - diff --git a/Competitive Coding/Tree/Binary Tree/postorder_traversal/readme.md b/Competitive Coding/Tree/Binary Tree/postorder_traversal/readme.md deleted file mode 100644 index 81fad41ab..000000000 --- a/Competitive Coding/Tree/Binary Tree/postorder_traversal/readme.md +++ /dev/null @@ -1,8 +0,0 @@ -# Postorder Traversal - -![alt text](https://www.java2blog.com/wp-content/uploads/2014/07/PostOrderTraversalBinaryTree-1.jpg) - -Algorithm Postorder(tree) - * Traverse the left subtree, i.e., call Postorder(left-subtree) - * Traverse the right subtree, i.e., call Postorder(right-subtree) - * Visit the root. diff --git a/Competitive Coding/Tree/Binary Tree/preorder_traversal/preorder_traversal.cpp b/Competitive Coding/Tree/Binary Tree/preorder_traversal/preorder_traversal.cpp deleted file mode 100644 index 5c7f4d30c..000000000 --- a/Competitive Coding/Tree/Binary Tree/preorder_traversal/preorder_traversal.cpp +++ /dev/null @@ -1,133 +0,0 @@ -#include -#include -using namespace std; -#define nullptr 0 -typedef struct elem -{ - int val; - struct elem* leftchild; - struct elem* rightchild; - struct elem* parent; -}node;//This is the node for the binary tree. Each element in the binary tree contains a value, a pointer to left child,right child and parent. -class BinaryTree -{ -private: - int n=0; - node* root=nullptr; -public: - void insert(int x)//Insert function first searches for the place where the node can be inserted and then it inserts it there. - { - - if(n==0) - { - root=new node; - root->val=x; - root->leftchild=nullptr; - root->rightchild=nullptr; - root->parent=nullptr; - } - else - { - node* temp=root; - node* newnode=searchnode(x,temp); - if(x>newnode->val) - { - newnode->rightchild=new node; - newnode->rightchild->val=x; - newnode->rightchild->parent=newnode; - newnode->rightchild->leftchild=nullptr; - newnode->rightchild->rightchild=nullptr; - } - else - { - newnode->leftchild=new node; - newnode->leftchild->val=x; - newnode->leftchild->parent=newnode; - newnode->leftchild->leftchild=nullptr; - newnode->leftchild->rightchild=nullptr; - } - - } - n++; - - } - - node* searchnode(int x,node* temproot)//The search function searches for the node whose value is equal to the value it is searching for.It takes O(log n) as it is proportional to the height of the binary tree. - { - - if(temproot->valrightchild!=nullptr) - searchnode(x,temproot->rightchild); - else - return temproot; - } - else - { - if(temproot->val>x)//If value if larger it goes to the left child - { - if(temproot->leftchild!=nullptr) - searchnode(x,temproot->leftchild); - else - return temproot; - } - else - { - if(temproot->val==x)//It returns the value when it is equal - return temproot; - } - } - - } - void printtree(node* temp) - { - if(temp==nullptr) - return; - else - { - printtree(temp->leftchild); - cout<val; - printtree(temp->rightchild); - } - }//This is the function to print the tree. It prints the tree in a sorted order. - node* giveroot() - { - return root; - }//This function returns the pointer to root - void preorder_traversal(node* temp) - { - if(temp==nullptr) - return ; - else - { - cout<val<leftchild); - preorder_traversal(temp->rightchild); - } - } - -}; -int main() -{ - int n; - cin>>n; - BinaryTree bst; - for(int i=0;i>temp; - bst.insert(temp); - } - node* temp=bst.giveroot(); - - // bst.printtree(temp); - //temp = bst.giveroot(); - //bst.inorder_traversal(temp); - bst.preorder_traversal(temp); -} - - - - - - diff --git a/Competitive Coding/Tree/Binary Tree/preorder_traversal/readme.md b/Competitive Coding/Tree/Binary Tree/preorder_traversal/readme.md deleted file mode 100644 index 830c585ed..000000000 --- a/Competitive Coding/Tree/Binary Tree/preorder_traversal/readme.md +++ /dev/null @@ -1,8 +0,0 @@ -# Preorder Traversal - -![alt text](https://javabeat.net/wp-content/uploads/2013/11/BST_Preorder.jpg) - -Algorithm Preorder(tree) - * Visit the root. - * Traverse the left subtree, i.e., call Preorder(left-subtree) - * Traverse the right subtree, i.e., call Preorder(right-subtree) diff --git a/Competitive Coding/Tree/Binary Tree/segment-trees/segment-trees.cpp b/Competitive Coding/Tree/Binary Tree/segment-trees/segment-trees.cpp deleted file mode 100644 index 706f1d569..000000000 --- a/Competitive Coding/Tree/Binary Tree/segment-trees/segment-trees.cpp +++ /dev/null @@ -1,136 +0,0 @@ -/*A c++ program for segment tree range query*/ - -#include -using namespace std; -#define fastio ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0) -#define md 1000000007 -#define ll long long int -#define vi vector -#define vll vector -#define pb push_back -#define all(c) (c).begin(),(c).end() -template< class T > T max2(const T &a,const T &b) {return (a < b ? b : a);} -template< class T > T min2(const T &a,const T &b) {return (a > b ? b : a);} -template< class T > T max3(const T &a, const T &b, const T &c) { return max2(a, max2(b, c)); } -template< class T > T min3(const T &a, const T &b, const T &c) { return min2(a, min2(b, c)); } -template< class T > T gcd(const T a, const T b) { return (b ? gcd(b, a%b) : a); } -template< class T > T lcm(const T a, const T b) { return (a / gcd(a, b) * b); } -template< class T > T mod(const T &a, const T &b) { return (a < b ? a : a % b); } -typedef pair pi; -/*this program is designed for range sum type of query , this program can be also modified for the minimum of max query by changing the few command lines, -directions to where to make changes are given in the program, but please do not rely on them completely*/ -class segmenttree -{ -private: - ll n;//size of the original array - vector tree; -public: - segmenttree(ll a[],ll size) - { - n=size; - ll node=0; - ll left=0; - ll right=size-1; - tree.assign(1000000,0); - buildtree(a, node, left, right); - - } - void buildtree(ll a[],int node,ll left,ll right) - { - if(left==right) - { - tree[node]=a[left]; - } - else - { - ll mid=(left+right)/2; - buildtree(a,2*node+1,left,mid); - buildtree(a,2*node+2,mid+1,right); - tree[node]=tree[2*node+1]+tree[2*node+2];//this tree is for the sum in the given range query , this line can be modified according to the need for - //example, if we have to find the minimum in the given range we can accordingly change the line of command; - } - - } - void updateutil(ll a[],ll x,ll pos,ll left,ll right,ll node)//give the val to be updated and the pos where to update. pos should be with respect to the original array. - { - if(left==right) - { - a[pos]=x; - tree[node]=x; - } - else - { - ll mid=(left+right)/2; - if(pos<=mid) - { - updateutil(a,x,pos,left,mid,2*node+1); - } - else - updateutil(a,x,pos,mid+1,right,2*node+2); - tree[node]=tree[2*node+1]+tree[2*node+2];//this line can be changed accordingly for a different query - } - } - void update(ll a[],ll x,ll pos) - { - updateutil(a,x,pos-1,0,n-1,0); - } - void printtree() - { - for(ll i=0;i<2*n-1;i++) - cout<=right) - { - return queryutil(left,right,l,mid,2*node+1); - } - if(left>mid) - { - return queryutil(left,right,mid+1,r,2*node+2); - } - if(left<=mid && right>mid) - { - return queryutil(left,mid,l,mid,2*node+1)+queryutil(mid+1,right,mid+1,r,2*node+2);//this line can be changed for minimum or maximum query - - } - } - else - return 0; - - } - } - ll query(ll left,ll right) - { - return queryutil(left-1,right-1,0,n-1,0); - } - -}; -int main() -{ - ll n; - cin>>n; - ll a[n]; - for(ll i=0;i>a[i]; - } - segmenttree segtree(a,n); - segtree.printtree(); - /* - segtree.update(a,7,5);//position here is the normal position that is , the counting starts from 1 and not from 0 - segtree.update(a,4,3); - segtree.prlltree();*/ - // cout< -using namespace std; -#define lli long long int -#define infinite numeric_limits::max() -#define Min(a,b) ((a)<(b)?(a):(b)) -#define Max(a,b) ((a)>(b)?(a):(b)) -#define fr(i,j,s) for(i = j ; i < s ; i++) -#define ifr(i,j,s) for(i = j ; i >= s , i--) -struct edge -{ - lli wt; - int src; - int dest; -}; -struct Graph -{ - int V; - int E; - struct edge* array; -}; -struct sub -{ - int parent; - int rank; -}; -bool comp(struct edge &a, struct edge &b) -{ - return ((a.wt)<(b.wt)); -} -int find(struct sub subset[], int i) -{ - if(subset[i].parent != i) - { - subset[i].parent = find(subset,subset[i].parent); - } - return subset[i].parent ; -} -void Union(struct sub subset[] , int x, int y) -{ - int xfather = find(subset,x); - int yfather = find(subset,y); - if(subset[xfather].rankV = V ; - G->E = E ; - G->array = (struct edge*)malloc(E*sizeof(struct edge)); - return G ; -} -void KruskalMST(struct Graph *G) -{ - int i ; - int V = G->V ; - int E = G->E ; - lli sum = 0 ; - struct sub subset[G->V]; - fr(i,0,V) - { - subset[i].parent = i ; - subset[i].rank = 0 ; - } - sort(G->array, (G->array)+G->E,comp); - fr(i,0,E) - { - int x = find(subset,G->array[i].src); - int y = find(subset,G->array[i].dest); - if(x==y) - continue; - else - { - Union(subset,G->array[i].src,G->array[i].dest); - sum+=G->array[i].wt; - } - } - cout<>v>>e; - struct Graph* G = createGraph(v,e); - int ed = 0; - int temp = e ; - while(e--) - { - cin>>a>>b>>wt; - G->array[ed].src=a-1; - G->array[ed].dest=b-1; - G->array[ed].wt=wt; - ed++; - } - cin>>a; - KruskalMST(G); - return 0; -} diff --git a/Competitive Coding/Tree/Minimum Spanning Tree/Prims/Prims.cpp b/Competitive Coding/Tree/Minimum Spanning Tree/Prims/Prims.cpp deleted file mode 100644 index ac5c467cf..000000000 --- a/Competitive Coding/Tree/Minimum Spanning Tree/Prims/Prims.cpp +++ /dev/null @@ -1,225 +0,0 @@ -#include -using namespace std; -#define lli long long int -#define infinite numeric_limits::max() -#define Min(a,b) ((a)<(b)?(a):(b)) -#define Max(a,b) ((a)>(b)?(a):(b)) -#define fr(i,j,s) for(i = j ; i < s ; i++) -#define ifr(i,j,s) for(i = j ; i >= s , i--) -struct adjListNode -{ - int dest; - int wt; - struct adjListNode *next; -}; -struct adjList -{ - struct adjListNode *head; -}; -struct Graph -{ - int V ; - struct adjList *array; -}; -struct adjListNode * newAdjNode(int dest, int wt) -{ - struct adjListNode *newNode = (struct adjListNode* )malloc(sizeof(struct adjListNode)); - newNode->dest = dest; - newNode->wt = wt; - newNode->next = NULL ; - return newNode; -} -struct Graph* createGraph(int V,int E) -{ - int i ; - struct Graph* G = (struct Graph *)malloc(sizeof(struct Graph)); - G->V = V ; - G->array = (struct adjList*)malloc(E*sizeof(struct adjList)); - fr(i,0,V) - { - G->array[i].head = NULL ; - } - return G ; -} -void addEdge(struct Graph *G,int src, int dest, int wt) -{ - struct adjListNode*temp=newAdjNode(dest,wt); - temp->next=G->array[src].head; - G->array[src].head=temp; - - temp=newAdjNode(src,wt); - temp->next=G->array[dest].head; - G->array[dest].head=temp; -} -struct MinHeapNode -{ - int v; - lli dist; -}; -struct MinHeap -{ - int size; - int capacity; - int *pos; - struct MinHeapNode **array; -}; -struct MinHeapNode* newMinHeapNode(int v, lli dist) -{ - struct MinHeapNode* minHeapNode = - (struct MinHeapNode*) malloc(sizeof(struct MinHeapNode)); - minHeapNode->v = v; - minHeapNode->dist = dist; - return minHeapNode; -} -struct MinHeap* createMinHeap(int capacity) -{ - struct MinHeap* minHeap = - (struct MinHeap*) malloc(sizeof(struct MinHeap)); - minHeap->pos = (int *)malloc(capacity * sizeof(int)); - minHeap->size = 0; - minHeap->capacity = capacity; - minHeap->array = - (struct MinHeapNode**) malloc(capacity * sizeof(struct MinHeapNode*)); - return minHeap; -} -void swapMinHeapNode(struct MinHeapNode** a, struct MinHeapNode** b) -{ - struct MinHeapNode* t = *a; - *a = *b; - *b = t; -} -void minHeapify(struct MinHeap* minHeap, int idx) -{ - int smallest, left, right; - smallest = idx; - left = 2 * idx + 1; - right = 2 * idx + 2; - - if (left < minHeap->size && - minHeap->array[left]->dist < minHeap->array[smallest]->dist ) - smallest = left; - - if (right < minHeap->size && - minHeap->array[right]->dist < minHeap->array[smallest]->dist ) - smallest = right; - - if (smallest != idx) - { - MinHeapNode *smallestNode = minHeap->array[smallest]; - MinHeapNode *idxNode = minHeap->array[idx]; - - minHeap->pos[smallestNode->v] = idx; - minHeap->pos[idxNode->v] = smallest; - - swapMinHeapNode(&minHeap->array[smallest], &minHeap->array[idx]); - - minHeapify(minHeap, smallest); - } -} - -int isEmpty(struct MinHeap* minHeap) -{ - return minHeap->size == 0; -} - -struct MinHeapNode* extractMin(struct MinHeap* minHeap) -{ - if (isEmpty(minHeap)) - return NULL; - - struct MinHeapNode* root = minHeap->array[0]; - - struct MinHeapNode* lastNode = minHeap->array[minHeap->size - 1]; - minHeap->array[0] = lastNode; - - minHeap->pos[root->v] = minHeap->size-1; - minHeap->pos[lastNode->v] = 0; - - --minHeap->size; - minHeapify(minHeap, 0); - - return root; -} - -void decreaseKey(struct MinHeap* minHeap, int v, lli dist) -{ - int i = minHeap->pos[v]; - - minHeap->array[i]->dist = dist; - - while (i && minHeap->array[i]->dist < minHeap->array[(i - 1) / 2]->dist) - { - minHeap->pos[minHeap->array[i]->v] = (i-1)/2; - minHeap->pos[minHeap->array[(i-1)/2]->v] = i; - swapMinHeapNode(&minHeap->array[i], &minHeap->array[(i - 1) / 2]); - i = (i - 1) / 2; - } -} - -bool isInMinHeap(struct MinHeap *minHeap, int v) -{ - if (minHeap->pos[v] < minHeap->size) - return true; - return false; -} -void PrimMST(struct Graph*G,int src) -{ - lli i,j; - int V = G->V; - lli dist[V],parent[V],sto[V]; - struct MinHeap * minHeap = createMinHeap(V); - fr(i,0,V) - { - if(i==src) - continue; - parent[i] = -1 ; - sto[i] = -1 ; - dist[i] = infinite ; - minHeap->array[i] = newMinHeapNode(i,dist[i]); - minHeap->pos[i] = i ; - } - dist[src] = 0 ; - minHeap->array[src] = newMinHeapNode(src,dist[src]) ; - minHeap->pos[src] = src ; - minHeap->size = V ; - lli sum=0; - while(!isEmpty(minHeap)) - { - struct MinHeapNode* minHeapNode = extractMin(minHeap); - int u = minHeapNode->v; - struct adjListNode* pCrawl = G->array[u].head; - while (pCrawl != NULL) - { - int v = pCrawl->dest; - if (isInMinHeap(minHeap, v) && (pCrawl->wt < dist[v])) - { - parent[v] = u ; - if(dist[v] != infinite) - sum -= (dist[v]-pCrawl->wt) ; - else - sum+=pCrawl->wt; - dist[v] =pCrawl->wt; - decreaseKey(minHeap, v, dist[v]); - } - pCrawl = pCrawl->next; - } - } - fr(i,0,V) - cout<>v>>e; - struct Graph* G = createGraph(v,e); - while(e--) - { - cin>>a>>b>>wt; - addEdge(G,a-1,b-1,wt); - } - cin>>a; - PrimMST(G,0); - return 0; -} diff --git a/Competitive Coding/Tree/Minimum Spanning Tree/readme.md b/Competitive Coding/Tree/Minimum Spanning Tree/readme.md deleted file mode 100644 index dfeb89ec3..000000000 --- a/Competitive Coding/Tree/Minimum Spanning Tree/readme.md +++ /dev/null @@ -1,33 +0,0 @@ -## Minimum spanning tree ## - -A minimum spanning tree (MST) or minimum weight spanning tree is a subset of the edges of -a connected, edge-weighted (un)directed graph that connects all the vertices together, -without any cycles and with the minimum possible total edge weight. - -That is, it is a spanning tree whose sum of edge weights is as small as possible. - -

- -

- -> Properties : -* A connected graph G can have more than one spanning tree. -* All possible spanning trees of graph G, have the same number of edges and vertices. -* Removing one edge from the spanning tree will make the graph disconnected, i.e. the spanning tree is minimally connected. -* Adding one edge to the spanning tree will create a circuit or loop, i.e. the spanning tree is maximally acyclic. -* A spanning tree does not have cycles and it cannot be disconnected. - -> Mathematical Properties of Spanning Tree : -* Spanning tree has n-1 edges, where n is the number of nodes (vertices). -* From a complete graph, by removing maximum e - n + 1 edges, we can construct a spanning tree. -* A complete undirected graph can have maximum n^(n-2) number of spanning trees. - -> Application of Minimum spanning tree :- -* Design of networks in telephone, electrical, hydraulic, TV cable, computer, road etc. -* Cluster Analysis -* Traveling salesman problem -* Handwriting recognition - -> There are two most important & famous spanning tree algorithm : -1. Kruskal's Algorithm -2. Prim's Algorithm diff --git a/GFG Articles/prateekiiest/article.md b/GFG Articles/prateekiiest/article.md deleted file mode 100644 index 341e6a1ee..000000000 --- a/GFG Articles/prateekiiest/article.md +++ /dev/null @@ -1 +0,0 @@ -GFG link diff --git a/Gemfile b/Gemfile new file mode 100644 index 000000000..5202882a2 --- /dev/null +++ b/Gemfile @@ -0,0 +1,24 @@ +source "https://rubygems.org" +ruby RUBY_VERSION + +# Hello! This is where you manage which Jekyll version is used to run. +# When you want to use a different version, change it below, save the +# file and run `bundle install`. Run Jekyll with `bundle exec`, like so: +# +# bundle exec jekyll serve +# +# This will help ensure the proper Jekyll version is running. +# Happy Jekylling! +gem "jekyll", "3.3.1" + +# This is the default theme for new Jekyll sites. You may change this to anything you like. +gem "minima", "~> 2.0" + +# If you want to use GitHub Pages, remove the "gem "jekyll"" above and +# uncomment the line below. To upgrade, run `bundle update github-pages`. +# gem "github-pages", group: :jekyll_plugins + +# If you have any plugins, put them here! +group :jekyll_plugins do + gem "jekyll-feed", "~> 0.6" +end diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 000000000..5274988a4 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,56 @@ +GEM + remote: https://rubygems.org/ + specs: + addressable (2.5.0) + public_suffix (~> 2.0, >= 2.0.2) + colorator (1.1.0) + ffi (1.9.14) + forwardable-extended (2.6.0) + jekyll (3.3.1) + addressable (~> 2.4) + colorator (~> 1.0) + jekyll-sass-converter (~> 1.0) + jekyll-watch (~> 1.1) + kramdown (~> 1.3) + liquid (~> 3.0) + mercenary (~> 0.3.3) + pathutil (~> 0.9) + rouge (~> 1.7) + safe_yaml (~> 1.0) + jekyll-feed (0.8.0) + jekyll (~> 3.3) + jekyll-sass-converter (1.5.0) + sass (~> 3.4) + jekyll-watch (1.5.0) + listen (~> 3.0, < 3.1) + kramdown (1.13.1) + liquid (3.0.6) + listen (3.0.8) + rb-fsevent (~> 0.9, >= 0.9.4) + rb-inotify (~> 0.9, >= 0.9.7) + mercenary (0.3.6) + minima (2.1.0) + jekyll (~> 3.3) + pathutil (0.14.0) + forwardable-extended (~> 2.6) + public_suffix (2.0.4) + rb-fsevent (0.9.8) + rb-inotify (0.9.7) + ffi (>= 0.5.0) + rouge (1.11.1) + safe_yaml (1.0.4) + sass (3.4.23) + +PLATFORMS + ruby + +DEPENDENCIES + jekyll (= 3.3.1) + jekyll-feed (~> 0.6) + minima (~> 2.0) + +RUBY VERSION + ruby 2.4.1p111 + +BUNDLED WITH + 1.15.1 diff --git a/Graphics Algos/Car Animation/README.md b/Graphics Algos/Car Animation/README.md deleted file mode 100644 index 850b210dd..000000000 --- a/Graphics Algos/Car Animation/README.md +++ /dev/null @@ -1,16 +0,0 @@ -The car.c file is a program which shows an animation of a moving car. -It has been drawn using the line function in the graphics library. - - line(x1,y1,x2,y2) - where, x1,y1 ---- starting points of line - and x2,y2 ------- ending points of the line. - -The animation takes place by the concept of translation. -We've put the car in a for loop incrementing the values of x co-ordinates of all the line functions by i - -The final out put will look this way! - -![screenshot from 2017-12-16 15-52-31](https://user-images.githubusercontent.com/26206171/34069730-d0f448d6-e27c-11e7-9a34-17603028a4ec.png) -![screenshot from 2017-12-16 15-52-35](https://user-images.githubusercontent.com/26206171/34069731-d5130948-e27c-11e7-882e-2d9ca7c00f0b.png) -![screenshot from 2017-12-16 15-52-37](https://user-images.githubusercontent.com/26206171/34069732-d5d02c76-e27c-11e7-99ba-7138d97e4877.png) -![screenshot from 2017-12-16 15-52-40](https://user-images.githubusercontent.com/26206171/34069733-d80b1ae6-e27c-11e7-96b5-715bf9601b95.png) diff --git a/Graphics Algos/Car Animation/car.c b/Graphics Algos/Car Animation/car.c deleted file mode 100644 index b3f9fe40d..000000000 --- a/Graphics Algos/Car Animation/car.c +++ /dev/null @@ -1,73 +0,0 @@ -#include -#include - -int main() -{ - int gd = DETECT, gm; - int i, maxx, midy; - - /* initialize graphic mode */ - initgraph(&gd, &gm, "NULL"); - /* maximum pixel in horizontal axis */ - maxx = getmaxx(); - /* mid pixel in vertical axis */ - midy = getmaxy()/2; - - for (i=0; i < maxx-150; i=i+5) /* loop is run for showing the animation */ - { - /* clears screen */ - cleardevice(); - - /* draw a white road */ - setcolor(WHITE); /* color of the road */ - line(0, midy + 37, maxx, midy + 37); - - /* Draw Car */ - setcolor(YELLOW); /* color of the car body */ - - /* car body */ - line(i, midy + 23, i, midy); /* draws the left most line parallel to y-axis */ - line(i, midy, 40 + i, midy - 20); - line(40 + i, midy - 20, 80 + i, midy - 20); /* draws the roof of the car*/ - line(80 + i, midy - 20, 100 + i, midy); /* draws the front mirror part of the car */ - line(100 + i, midy, 120 + i, midy); - line(120 + i, midy, 120 + i, midy + 23); - line(0 + i, midy + 23, 18 + i, midy + 23); - arc(30 + i, midy + 23, 0, 180, 12); /* draws the arc to accomodate the wheels */ - line(42 + i, midy + 23, 78 + i, midy + 23); - arc(90 + i, midy + 23, 0, 180, 12); /* draws the arc to accomodate the wheels */ - line(102 + i, midy + 23, 120 + i, midy + 23); - /* car body ends */ - - /* Draw Windows */ - /* left window */ - line(28 + i, midy, 43 + i, midy - 15); /* left part of left window */ - line(43 + i, midy - 15, 57 + i, midy - 15); /* roof of the left window */ - line(57 + i, midy - 15, 57 + i, midy); /* right part of left window */ - line(57 + i, midy, 28 + i, midy); /* bottom part of the left window */ - /* left window ends */ - - /* right window */ - line(62 + i, midy - 15, 77 + i, midy - 15); /* left part of right window */ - line(77 + i, midy - 15, 92 + i, midy); /* roof of the rightt window */ - line(92 + i, midy, 62 + i, midy); /* right part of right window */ - line(62 + i, midy, 62 + i, midy - 15); /* bottom part of the right window */ - /* right window ends */ - - floodfill(5 + i, midy + 22, YELLOW); /* fills the whole car body with yellow color */ - - setcolor(BLUE); /* color of the wheels */ - /* Draw Wheels */ - circle(30 + i, midy + 25, 9); - circle(90 + i, midy + 25, 9); - floodfill(30 + i, midy + 25, BLUE); /* fills the left wheel with blue color */ - floodfill(90 + i, midy + 25, BLUE); /* fills the right wheel with blue color */ - - /* Add delay of 0.1 milli seconds */ - delay(100); /* to observe the animation */ - } - - getch(); - closegraph(); - return 0; -} diff --git a/Graphics Algos/README.md b/Graphics Algos/README.md deleted file mode 100644 index 06bdcea3b..000000000 --- a/Graphics Algos/README.md +++ /dev/null @@ -1,13 +0,0 @@ -## GRAPHICS ALGORITHMS - -This is a folder which contains graphics algorithms and their implementations. - -### Robo.c - -The robo.c program is a program which helps you in drawing a robot. -The robot is drawn around a reference point. The DDA Line Algorithm was used in making the program. -The DDA Line algorithm exists inside the program in a function so you can have a look at what the DDA line algorithm is, -inside this program itself.

-The image below shows the Output of the program! - -![picture](https://user-images.githubusercontent.com/26206171/33807711-e08a11ca-de00-11e7-8635-78aa0f8a2884.png) diff --git a/Graphics Algos/robo.c b/Graphics Algos/robo.c deleted file mode 100644 index dacdcf688..000000000 --- a/Graphics Algos/robo.c +++ /dev/null @@ -1,92 +0,0 @@ -#include - -float FX,FY,BX,BY,ax,bx,ay,by; - -void DDALine(float x1,float y1,float x2,float y2) -{ - float x,y,dx,dy,step; - if(x1>x2 || y1>y2) - { - x1=x1+x2;x2=x1-x2;x1=x1-x2; // x1 x2 swap - y1=y1+y2;y2=y1-y2;y1=y1-y2; // y1 y2 swap - } - dx=abs(x2-x1); //finding the positive difference between x1 and x2 - dy=abs(y2-y1); //finding positive difference between y1 and y2 - if(dx>=dy) - step=dx; - else - step=dy; - dx/=step; - dy/=step; - x=x1; - y=y1; - for(int i=0;i<=step;i++) - { - putpixel(x,y,WHITE); - x+=dx; - y+=dy; - } -} -void DDARect(float x1,float y1,float x2,float y2) //Creating a rectangle using dda line -{ - DDALine(x1,y1,x2,y1); - DDALine(x2,y1,x2,y2); - DDALine(x2,y2,x1,y2); - DDALine(x1,y1,x1,y2); -} -void main( ) -{ - 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 - int gd=DETECT,gm; // FX and FY are translating constants to make sure all parts of the body are drawns - initgraph(&gd,&gm,"NULL"); - //--Head - //Cap - circle(FX,FY-40,5); - DDARect(FX-2.5,FY-25,FX+2.5,FY-35); - arc(FX,FY-20,180,360,5); - //Face - DDARect(FX-20,FY+20,FX+20,FY-20);//Face Outline - DDARect(FX-15,FY,FX-5,FY-10);//Left Eye - DDARect(FX+5,FY,FX+15,FY-10);//Right Eye - //Mouth - DDARect(FX-10,FY+15,FX+10,FY+10); - //TEETH - DDARect(FX-2,FY+15,FX+2,FY+10); - DDARect(FX-6,FY+15,FX+6,FY+10); - //LEFT_EAR - DDARect(FX-25,FY,FX-20,FY-10); - DDARect(FX-30,FY-2.5,FX-25,FY-7.5); - //RIGHT_EAR - DDARect(FX+25,FY,FX+20,FY-10); - DDARect(FX+25,FY-2.5,FX+30,FY-7.5); - DDARect(BX-5,BY-30,BX+5,BY-40);//Neck - //--BODY - DDARect(BX-30,BY+30,BX+30,BY-30); // Body Outline - DDARect(BX-20,BY+15,BX+20,BY-20); // Inner Square - DDARect(BX-25,BY+70,BX-10,BY+30); // Left Leg - arc(BX-17.5,BY+70,180,360,7.5); // Left Foot - DDARect(BX+25,BY+70,BX+10,BY+30); // Right Leg - arc(BX+17.5,BY+70,180,360,7.5); // Right Foot - //Left_Hand - ax=BX-47,ay=BY-5; //ax and bx become relative points to draw both hands - bx=BX-47,by=BY+5; - for(int i=0;i<10;i++) - { - putpixel(ax,ay,WHITE); - putpixel(bx,by,WHITE); - ax+=1.7; - bx+=1.7; - ay-=1; - by-=1; - } - circle(BX-47,BY,5); - //Right_Hand - DDALine(BX+47,BY-5,BX+30,BY-15); - DDALine(BX+47,BY+5,BX+30,BY-5); - circle(BX+47,BY,5); - ax=BX+47,ay=BY-5; - bx=BX+47,by=BY+5; - //END - delay(5000); - getch(); -} diff --git a/ISSUE_TEMPLATE.md b/ISSUE_TEMPLATE.md deleted file mode 100644 index 72c6ae063..000000000 --- a/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,21 +0,0 @@ - - -## DESCRIPTION - -Please provide a short, clear description of the problem - -## STEPS TO REPRODUCE - -Please list the steps to reproduce the above problem - -## EXPECTED OUTCOME - -What did you expect to happen - -## ACTUAL OUTCOME - -What actually happened - -### Proposed Solution [optional] - -If you know how to solve the above, please provide details here. diff --git a/LICENSE b/LICENSE deleted file mode 100644 index a65e6c7ef..000000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2017 codeIIEST - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/Machine learning/ gradient descent/LinearReg.m b/Machine learning/ gradient descent/LinearReg.m deleted file mode 100644 index 7b16d110a..000000000 --- a/Machine learning/ gradient descent/LinearReg.m +++ /dev/null @@ -1,42 +0,0 @@ -%Gradient desecent for Linear regression model -%used for training theta(parameter) -%LinearReg train theta vector using training dataset -%X is matrix m rows i.e. number of training examples -% and n columns i.e. number of features. -%y is vector of size m, containing actual values from dataset - -%Loading data -data = load('filename.txt'); -dim=size(data); -num_row=dim(1,1); -num_col=dim(1,2); - -for i=1:(num_col-1) - if(i==1) - X=data(:,1); - else - X=[X , data(:,i)]; - end -end; - -y=data(:,num_col); - -%adding a biased term in X matrix -X=[ones(m,1) X]; - -%initialization of theta -theta=zeros(size(X,2),1); - -%number of features -num_fea=size(X,2) - -%numbers of training examples -m=length(y); - -%Gradient desecent -for j=1: max_iter - h=(X*theta-y); - for i=1: num_fea - theta(i)=theta(i)-(learning_rate*(X(:,i)'*h)/m); - end -end diff --git a/Machine learning/ gradient descent/README.md b/Machine learning/ gradient descent/README.md deleted file mode 100644 index 302349944..000000000 --- a/Machine learning/ gradient descent/README.md +++ /dev/null @@ -1,13 +0,0 @@ -# **Gradient desecent for linear regression** -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. - -# Example -![image](gradient.png) - -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. -The slope of the tangent will give a direction in which the value is decreases. Thus this algorithm make steps down the function. -The size of each step is determine by the learning rate. - -# **Gradient descent for linear regression** -In this model, gradient descent is used to calculating the theta vector(or parameter vector). Once the parameter vector is calculated using -training examples, we can predict the output of unknown input. diff --git a/Machine learning/ gradient descent/gradient.png b/Machine learning/ gradient descent/gradient.png deleted file mode 100644 index 5ff8b0a14..000000000 Binary files a/Machine learning/ gradient descent/gradient.png and /dev/null differ diff --git a/Machine learning/EXPONENTIAL REGRESSION b/Machine learning/EXPONENTIAL REGRESSION deleted file mode 100644 index 72656117a..000000000 --- a/Machine learning/EXPONENTIAL REGRESSION +++ /dev/null @@ -1,39 +0,0 @@ -#include -#include -using namespace std; -#define f float -void exponential(f x[], f y[], int n){ - f Y[n],sumx=0,sumy=0,sumxy=0,sumx2=0; - double a,b,A; - for(int i=0;i<=n-1;i++) - { - Y[i]=log(y[i]); - } - for(int i=0;i<=n-1;i++) - { - sumx=sumx +x[i]; - sumx2=sumx2 +x[i]*x[i]; - sumy=sumy +Y[i]; - sumxy=sumxy +x[i]*Y[i]; - - } - A=((sumx2*sumy -sumx*sumxy)*1.0/(n*sumx2-sumx*sumx)*1.0); - b=((n*sumxy-sumx*sumy)*1.0/(n*sumx2-sumx*sumx)*1.0); - a=exp(A); - printf("\n The curve is Y= %4.3fe^%4.3fX",a,b); -} - -int main() -{ -int i,n; -cout<<"welcome to linear regression\n"; -cout<<"enter number of data you want to enter\n"; -cin>>n; -f x[n],y[n]; -cout<<"enter x variables\n"; -for(i=0;i>x[i]; -cout<<"enter y variables\n"; -for(i=0;i>y[i]; - exponential(x,y,n); -return 0; -} diff --git a/Machine learning/LINEAR REGRESSION b/Machine learning/LINEAR REGRESSION deleted file mode 100644 index 29f6a0003..000000000 --- a/Machine learning/LINEAR REGRESSION +++ /dev/null @@ -1,34 +0,0 @@ -#include -#include -using namespace std; -#define f float -void linear(f x[],f y[],int n) -{ - f cx=0,cy=0,sumxy=0,sumx2=0; - double a,b; - for(int i=0;i<=n-1;i++) - { - cx=cx+x[i]; - sumx2=sumx2 +x[i]*x[i]; - cy=cy+y[i]; - sumxy=sumxy +x[i]*y[i]; - - } - a=((sumx2*cy -cx*sumxy)*1.0/(n*sumx2-cx*cx)*1.0); - b=((n*sumxy-cx*cy)*1.0/(n*sumx2-cx*cx)*1.0); - printf("\n\nThe line is Y=%3.3f +%3.3f X",a,b); -} -int main() -{ -int i,n; -cout<<"welcome to linear regression\n"; -cout<<"enter number of data you want to enter\n"; -cin>>n; -f x[n],y[n]; -cout<<"enter x variables\n"; -for(i=0;i>x[i]; -cout<<"enter y variables\n"; -for(i=0;i>y[i]; - linear(x,y,n); -return 0; -} diff --git a/Machine learning/polynomial regression b/Machine learning/polynomial regression deleted file mode 100644 index 08e43ae64..000000000 --- a/Machine learning/polynomial regression +++ /dev/null @@ -1,78 +0,0 @@ -#include -#include -using namespace std; -#define f float -void poly(float x[], float y[], int N){ - int n; - cout << "\nPlease enter the degress:\n"; - cin >> n; - - double X[2*n+1]; //Array that will store the values of sigma(xi),sigma(xi^2),sigma(xi^3)....sigma(xi^2n) - for (int i=0;i<2*n+1;i++) - { - X[i]=0; - for (int j=0;j=0;i--) //back-substitution - { //x is an array whose values correspond to the values of x,y,z.. - a[i]=B[i][n]; //make the variable to be calculated equal to the rhs of the last equation - for (int j=0;j>n; -f x[n],y[n]; -cout<<"enter x variables\n"; -for(i=0;i>x[i]; -cout<<"enter y variables\n"; -for(i=0;i>y[i]; - poly(x,y,n); -return 0; -} diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index 2e8b632b8..000000000 --- a/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,13 +0,0 @@ -Thank you for your contribution. Please provide the details requested below. - -## ISSUE NUMBER - -Please provide a link to the issue this pull request addresses. - -## SHORT DESCRIPTION - -Please provide a short description of the changes. - -## TESTING - -Please provide the necessary steps to test the solution. diff --git a/README.md b/README.md deleted file mode 100644 index 2f4643d21..000000000 --- a/README.md +++ /dev/null @@ -1,47 +0,0 @@ - -# Algorithms - - -
- -[![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) - - -[![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) - ----------------------------------------------------------------------------------------------- - - -![](https://github.com/codeIIEST/Algorithms/blob/master/algocodeiiest.jpg) - -### About the Project - -This repository contains some of the most **intriguing and awesome algorithms** of daily life implemented in languages primarily in C/C++/Java/Python. - --------------------------------------------------------------- - -### Project Details -The entire project is divided into 4 parts - -* Competitive Coding Algorithms and Data Structures -* Security Algorithms -* Machine Learning Algorithms -* Statistical / Mathematical Algorithms - ------------------------------------------------------------------ - -### Contributing - -We would always encourage contribution from new developers. We hope with your contributions the project ecosystem will evolve much more in the future. - -For more details please see the [Contributing Guidelines](https://github.com/codeIIEST/Algorithms/blob/master/CONTRIBUTING.md). - -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. - ---------------------------------------------------- - -### Maintainers - -* [Manumeral](https://github.com/manumeral) -* [smitbose](https://github.com/smitbose) - diff --git a/Security Algorithms/Cryptography/Atbash_Cipher/Atbash_Cipher.cpp b/Security Algorithms/Cryptography/Atbash_Cipher/Atbash_Cipher.cpp deleted file mode 100644 index c86d1a04a..000000000 --- a/Security Algorithms/Cryptography/Atbash_Cipher/Atbash_Cipher.cpp +++ /dev/null @@ -1,31 +0,0 @@ -//Atbash cipher -#include -using namespace std; - -//Function that convert the message. -string atbash(string msg) -{ - /*This function takes msg as input and - map it to its reverse alphabatically order.*/ - - string cipher; - for(int i=0;i='A' && msg[i]<='Z') - cipher=cipher+(char)('Z'-(msg[i]-'A')); - else - cipher=cipher+(char)('z'-(msg[i]-'a')); - } - return cipher; -} - -//Main program. -int main() -{ - string text; - cout<<"Enter the message to encrypt/decrypt---"<>text; - cout<<"Converted message---"< -#include -#include -#include //For map data structure -using namespace std; - -//function for creating map structure -map createMap() -{ - // Decalaring map structure and Defination of map - map decrypt; - decrypt[".-"] = "A"; - decrypt["-..."] = "B"; - decrypt["-.-."] = "C"; - decrypt["-.."] = "D"; - decrypt["."] = "E"; - decrypt["..-."] = "F"; - decrypt["--."] = "G"; - decrypt["...."] = "H"; - decrypt[".."] = "I"; - decrypt[".---"] = "J"; - decrypt["-.-"] = "K"; - decrypt[".-.."] = "L"; - decrypt["--"] = "M"; - decrypt["-."] = "N"; - decrypt["---"] = "O"; - decrypt[".--."] = "P"; - decrypt["--.-"] = "Q"; - decrypt[".-."] = "R"; - decrypt["..."] = "S"; - decrypt["-"] = "T"; - decrypt["..-"] = "U"; - decrypt["...-"] = "V"; - decrypt[".--"] = "W"; - decrypt["-..-"] = "X"; - decrypt["-.--"] = "Y"; - decrypt["--.."] = "Z"; - decrypt[".----"] = "1"; - decrypt["..---"] = "2"; - decrypt["...--"] = "3"; - decrypt["....-"] = "4"; - decrypt["....."] = "5"; - decrypt["-...."] = "6"; - decrypt["--..."] = "7"; - decrypt["---.."] = "8"; - decrypt["---."] = "9"; - decrypt["-----"] = "0"; - return decrypt; -} - -map decrypt=createMap(); -// decryption Function -void decryption(string msg) -{ - string plain = "", tempPlain; - for (int i = 0; i < msg.size(); i++) - { - if (msg[i] != ' ' && msg[i] != '\t' && msg[i] != '\n') - { - tempPlain.append(1, msg[i]); - } - if ( msg[i] == ' ' || i==msg.size()-1) - { - plain=plain +decrypt[tempPlain]; - tempPlain=""; - } - if(msg[i] == '\t' || msg[i] =='\n') - { - plain=plain +decrypt[tempPlain]; - tempPlain=""; - plain += " "; - - } - } - cout <<"Decrypted Code=:"<< plain<=65 and ascii_vals_enc[i]<=90): - 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 - encrypt_string = ''.join(chr(i) for i in ascii_vals_enc) # To get the encrypted string using the list of manipulated ASCII vals - return encrypt_string - -def decrypt(message,key): - ascii_vals_dec=[ord(c) for c in message] - for i in range(0,len(ascii_vals_dec)): - if(ascii_vals_dec[i]>=65 and ascii_vals_dec[i]<=90): - ascii_vals_dec[i] = 90 - (90 - ascii_vals_dec[i] + key )%26 - decrypt_string = ''.join(chr(i) for i in ascii_vals_dec) # To get the decrypted string using the list of manipulated ASCII vals - return decrypt_string - -def caesar_cipher(): - #message_enc = raw_input("Enter text to be encrypted:") #Can be used to give custom strings - message_enc ="CODING IS FUN" #string to be encrypted - encrypt_string = encrypt(message_enc,key) #Calling the function to encrypt the string - print "The string to be encrypted is: ",message_enc - print "THe encrypted string is: ",encrypt_string - print "----------------------------------------" - #message_dec = raw_input("Enter text to be encrypted:") #Can be used to give custom strings - message_dec ="M PSZI GSHMRK" #string to be decrypted - decrypt_string = decrypt(message_dec,key) #Calling the function to decrypt the string - print "The string to be decrypted is: ",message_dec - print "THe decrypted string is: ",decrypt_string - -if __name__=="__main__": - #key = int(raw_input("By what value do you want to shift?")) #Can be used to give custom key values - key = 4 - caesar_cipher() diff --git a/Security Algorithms/Cryptography/RSA Algortihm/README.md b/Security Algorithms/Cryptography/RSA Algortihm/README.md deleted file mode 100644 index 43bbd62b6..000000000 --- a/Security Algorithms/Cryptography/RSA Algortihm/README.md +++ /dev/null @@ -1,17 +0,0 @@ -## RSA - 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**. - -#### Designers -Ron Rivest, Adi Shamir, and Leonard Adleman - ---------------- - -![](https://globlib4u.files.wordpress.com/2013/10/image1_e.gif) --------------- -#### Operation - -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): -** (m^e)^d ~ m mod n ** -and that even knowing e and n or even m it can be extremely difficult to find d. - -[More info](https://en.wikipedia.org/wiki/RSA_(cryptosystem)) diff --git a/Security Algorithms/Cryptography/RSA Algortihm/rsa.py b/Security Algorithms/Cryptography/RSA Algortihm/rsa.py deleted file mode 100644 index 3199e6bfc..000000000 --- a/Security Algorithms/Cryptography/RSA Algortihm/rsa.py +++ /dev/null @@ -1,113 +0,0 @@ -import random - - -''' -Euclid's algorithm for determining the greatest common divisor -Use iteration to make it faster for larger integers -''' -def gcd(a, b): - while b != 0: - a, b = b, a % b - return a - -''' -Euclid's extended algorithm for finding the multiplicative inverse of two numbers -''' -def multiplicative_inverse(e, phi): - d = 0 - x1 = 0 - x2 = 1 - y1 = 1 - temp_phi = phi - - while e > 0: - temp1 = temp_phi/e - temp2 = temp_phi - temp1 * e - temp_phi = e - e = temp2 - - x = x2- temp1* x1 - y = d - temp1 * y1 - - x2 = x1 - x1 = x - d = y1 - y1 = y - - if temp_phi == 1: - return d + phi - -''' -Tests to see if a number is prime. -''' -def is_prime(num): - if num == 2: - return True - if num < 2 or num % 2 == 0: - return False - for n in xrange(3, int(num**0.5)+2, 2): - if num % n == 0: - return False - return True - -def generate_keypair(p, q): - if not (is_prime(p) and is_prime(q)): - raise ValueError('Both numbers must be prime.') - elif p == q: - raise ValueError('p and q cannot be equal') - #n = pq - n = p * q - - #Phi is the totient of n - phi = (p-1) * (q-1) - - #Choose an integer e such that e and phi(n) are coprime - e = random.randrange(1, phi) - - #Use Euclid's Algorithm to verify that e and phi(n) are comprime - g = gcd(e, phi) - while g != 1: - e = random.randrange(1, phi) - g = gcd(e, phi) - - #Use Extended Euclid's Algorithm to generate the private key - d = multiplicative_inverse(e, phi) - - #Return public and private keypair - #Public key is (e, n) and private key is (d, n) - return ((e, n), (d, n)) - -def encrypt(pk, plaintext): - #Unpack the key into it's components - key, n = pk - #Convert each letter in the plaintext to numbers based on the character using a^b mod m - cipher = [(ord(char) ** key) % n for char in plaintext] - #Return the array of bytes - return cipher - -def decrypt(pk, ciphertext): - #Unpack the key into its components - key, n = pk - #Generate the plaintext based on the ciphertext and key using a^b mod m - plain = [chr((char ** key) % n) for char in ciphertext] - #Return the array of bytes as a string - return ''.join(plain) - - -if __name__ == '__main__': - ''' - Detect if the script is being run directly by the user - ''' - print "RSA Encrypter/ Decrypter" - p = int(raw_input("Enter a prime number (17, 19, 23, etc): ")) - q = int(raw_input("Enter another prime number (Not one you entered above): ")) - print "Generating your public/private keypairs now . . ." - public, private = generate_keypair(p, q) - print "Your public key is ", public ," and your private key is ", private - message = raw_input("Enter a message to encrypt with your private key: ") - encrypted_msg = encrypt(private, message) - print "Your encrypted message is: " - print ''.join(map(lambda x: str(x), encrypted_msg)) - print "Decrypting message with public key ", public ," . . ." - print "Your message is:" - print decrypt(public, encrypted_msg) diff --git a/_config.yml b/_config.yml index 922b6eda4..6e6db2ee7 100644 --- a/_config.yml +++ b/_config.yml @@ -1,2 +1,32 @@ -theme: jekyll-theme-architect -encoding: UTF-8 +# Welcome to Jekyll! +# +# This config file is meant for settings that affect your whole blog, values +# which you are expected to set up once and rarely edit after that. If you find +# yourself editing this file very often, consider using Jekyll's data files +# feature for the data you need to update frequently. +# +# For technical reasons, this file is *NOT* reloaded automatically when you use +# 'bundle exec jekyll serve'. If you change this file, please restart the server process. + +# Site settings +# These are used to personalize your new site. If you look in the HTML files, +# you will see them accessed via {{ site.title }}, {{ site.email }}, and so on. +# You can create any custom variable you would like, and they will be accessible +# in the templates via {{ site.myvariable }}. +title: Algorithms +email: your-email@domain.com +description: > # this means to ignore newlines until "baseurl:" + A repository of some popular algorithms +baseurl: "/Algorithms" # the subpath of your site, e.g. /blog +url: "" # the base hostname & protocol for your site, e.g. http://example.com +twitter_username: +github_username: codeIIEST + +# Build settings +markdown: kramdown +theme: minima +gems: + - jekyll-feed +exclude: + - Gemfile + - Gemfile.lock diff --git a/_includes/disqus_comments.html b/_includes/disqus_comments.html new file mode 100644 index 000000000..87fa30942 --- /dev/null +++ b/_includes/disqus_comments.html @@ -0,0 +1,20 @@ +{% if page.comments != false and jekyll.environment == "production" %} + +
+ + +{% endif %} diff --git a/_includes/footer.html b/_includes/footer.html new file mode 100644 index 000000000..41a768091 --- /dev/null +++ b/_includes/footer.html @@ -0,0 +1,19 @@ +
+ +
+ +
+ + + +
diff --git a/_includes/google-analytics.html b/_includes/google-analytics.html new file mode 100644 index 000000000..eb2a692a5 --- /dev/null +++ b/_includes/google-analytics.html @@ -0,0 +1,11 @@ + + diff --git a/_includes/head.html b/_includes/head.html new file mode 100644 index 000000000..99b698fc8 --- /dev/null +++ b/_includes/head.html @@ -0,0 +1,16 @@ + + + + + + {% if page.title %}{{ page.title | escape }}{% else %}{{ site.title | escape }}{% endif %} + + + + + + + {% if jekyll.environment == 'production' and site.google_analytics %} + {% include google-analytics.html %} + {% endif %} + diff --git a/_includes/header.html b/_includes/header.html new file mode 100644 index 000000000..df0de2527 --- /dev/null +++ b/_includes/header.html @@ -0,0 +1,27 @@ + diff --git a/_includes/icon-github.html b/_includes/icon-github.html new file mode 100644 index 000000000..e501a16b1 --- /dev/null +++ b/_includes/icon-github.html @@ -0,0 +1 @@ +{% include icon-github.svg %}{{ include.username }} diff --git a/_includes/icon-github.svg b/_includes/icon-github.svg new file mode 100644 index 000000000..e6c5f6dfd --- /dev/null +++ b/_includes/icon-github.svg @@ -0,0 +1 @@ + diff --git a/_includes/icon-twitter.html b/_includes/icon-twitter.html new file mode 100644 index 000000000..e623dbd6e --- /dev/null +++ b/_includes/icon-twitter.html @@ -0,0 +1 @@ +{{ include.username }} diff --git a/_includes/icon-twitter.svg b/_includes/icon-twitter.svg new file mode 100644 index 000000000..efc0ecf67 --- /dev/null +++ b/_includes/icon-twitter.svg @@ -0,0 +1 @@ + diff --git a/_layouts/.home.html.swp b/_layouts/.home.html.swp new file mode 100644 index 000000000..a60ba3eb9 Binary files /dev/null and b/_layouts/.home.html.swp differ diff --git a/_layouts/default.html b/_layouts/default.html new file mode 100644 index 000000000..52085bfa2 --- /dev/null +++ b/_layouts/default.html @@ -0,0 +1,20 @@ + + + + {% include head.html %} + + + + {% include header.html %} + +
+
+ {{ content }} +
+
+ + {% include footer.html %} + + + + diff --git a/_layouts/home.html b/_layouts/home.html new file mode 100644 index 000000000..12823b1f4 --- /dev/null +++ b/_layouts/home.html @@ -0,0 +1,43 @@ +--- +layout: default +--- + +
+ +

Categories

+ {% assign searchurl="/pages/searching.html" %} + {% assign sorturl="/pages/sorting.html" %} + {% assign stackurl="/pages/stackq.html" %} + {% assign treeurl="/pages/trees.html" %} + {% assign graphurl="/pages/graph.html" %} + {% assign dpurl="/pages/dp.html" %} + {% assign otherurl="/pages/others.html" %} +
+

Searching

+ Searching an element from a set of elements +
+
+

Sorting

+ Sorting a set of elements in a particular order +
+
+

Stack and Queue

+ Algorithms that require FIFO or LIFO processing +
+
+

Trees

+ Segment trees, BITs and other algorithms for interval processing and searching +
+
+

Graphs

+ Modelling real life problems as a set of vertices and links between them +
+
+

Greedy and Dynamic Programming

+ Solving a bigger problem through solution of subproblems +
+
+

Others

+ Any algorithm that doesn't come under the above categories +
+
diff --git a/_layouts/page.html b/_layouts/page.html new file mode 100644 index 000000000..01e4b2a93 --- /dev/null +++ b/_layouts/page.html @@ -0,0 +1,14 @@ +--- +layout: default +--- +
+ +
+

{{ page.title | escape }}

+
+ +
+ {{ content }} +
+ +
diff --git a/_layouts/post.html b/_layouts/post.html new file mode 100644 index 000000000..ddce7bf45 --- /dev/null +++ b/_layouts/post.html @@ -0,0 +1,18 @@ +--- +layout: default +--- +
+ +
+

{{ page.title | escape }}

+ +
+
+
+ {{ content }} +
+ + {% if site.disqus.shortname %} + {% include disqus_comments.html %} + {% endif %} +
diff --git a/_posts/dpgreedy/.gitkeep b/_posts/dpgreedy/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/_posts/graph/.gitkeep b/_posts/graph/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/_posts/others/.gitkeep b/_posts/others/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/_posts/search/.gitkeep b/_posts/search/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/_posts/sort/.gitkeep b/_posts/sort/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/_posts/stackq/.gitkeep b/_posts/stackq/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/_posts/tree/.gitkeep b/_posts/tree/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/_sass/minima.scss b/_sass/minima.scss new file mode 100644 index 000000000..5372652f4 --- /dev/null +++ b/_sass/minima.scss @@ -0,0 +1,44 @@ +// Define defaults for each variable. + +$base-font-family: "Helvetica Neue", Helvetica, Arial, sans-serif !default; +$base-font-size: 16px !default; +$base-font-weight: 400 !default; +$small-font-size: $base-font-size * 0.875 !default; +$base-line-height: 1.5 !default; + +$spacing-unit: 30px !default; + +$text-color: #111 !default; +$background-color: #fdfdfd !default; +$brand-color: #2a7ae2 !default; + +$grey-color: #828282 !default; +$grey-color-light: lighten($grey-color, 40%) !default; +$grey-color-dark: darken($grey-color, 25%) !default; + +// Width of the content area +$content-width: 800px !default; + +$on-palm: 600px !default; +$on-laptop: 800px !default; + +// Use media queries like this: +// @include media-query($on-palm) { +// .wrapper { +// padding-right: $spacing-unit / 2; +// padding-left: $spacing-unit / 2; +// } +// } +@mixin media-query($device) { + @media screen and (max-width: $device) { + @content; + } +} + +// Import partials. +@import + "minima/base", + "minima/layout", + "minima/syntax-highlighting", + "minima/tabs" +; diff --git a/_sass/minima/_base.scss b/_sass/minima/_base.scss new file mode 100644 index 000000000..06bc9ae14 --- /dev/null +++ b/_sass/minima/_base.scss @@ -0,0 +1,198 @@ +/** + * Reset some basic elements + */ +body, h1, h2, h3, h4, h5, h6, +p, blockquote, pre, hr, +dl, dd, ol, ul, figure { + margin: 0; + padding: 0; +} + + + +/** + * Basic styling + */ +body { + font: $base-font-weight #{$base-font-size}/#{$base-line-height} $base-font-family; + color: $text-color; + background-color: $background-color; + -webkit-text-size-adjust: 100%; + -webkit-font-feature-settings: "kern" 1; + -moz-font-feature-settings: "kern" 1; + -o-font-feature-settings: "kern" 1; + font-feature-settings: "kern" 1; + font-kerning: normal; +} + + + +/** + * Set `margin-bottom` to maintain vertical rhythm + */ +h1, h2, h3, h4, h5, h6, +p, blockquote, pre, +ul, ol, dl, figure, +%vertical-rhythm { + margin-bottom: $spacing-unit / 2; +} + + + +/** + * Images + */ +img { + max-width: 100%; + vertical-align: middle; +} + + + +/** + * Figures + */ +figure > img { + display: block; +} + +figcaption { + font-size: $small-font-size; +} + + + +/** + * Lists + */ +ul, ol { + margin-left: $spacing-unit; +} + +li { + > ul, + > ol { + margin-bottom: 0; + } +} + + + +/** + * Headings + */ +h1, h2, h3, h4, h5, h6 { + font-weight: $base-font-weight; +} + + + +/** + * Links + */ +a { + color: $brand-color; + text-decoration: none; + + &:visited { + color: darken($brand-color, 15%); + } + + &:hover { + color: $text-color; + text-decoration: underline; + } +} + + + +/** + * Blockquotes + */ +blockquote { + color: $grey-color; + border-left: 4px solid $grey-color-light; + padding-left: $spacing-unit / 2; + font-size: 18px; + letter-spacing: -1px; + font-style: italic; + + > :last-child { + margin-bottom: 0; + } +} + + + +/** + * Code formatting + */ +pre, +code { + font-size: 15px; + border: 1px solid $grey-color-light; + border-radius: 3px; + background-color: #eef; +} + +code { + padding: 1px 5px; +} + +pre { + padding: 8px 12px; + overflow-x: auto; + + > code { + border: 0; + padding-right: 0; + padding-left: 0; + } +} + + + +/** + * Wrapper + */ +.wrapper { + max-width: -webkit-calc(#{$content-width} - (#{$spacing-unit} * 2)); + max-width: calc(#{$content-width} - (#{$spacing-unit} * 2)); + margin-right: auto; + margin-left: auto; + padding-right: $spacing-unit; + padding-left: $spacing-unit; + @extend %clearfix; + + @include media-query($on-laptop) { + max-width: -webkit-calc(#{$content-width} - (#{$spacing-unit})); + max-width: calc(#{$content-width} - (#{$spacing-unit})); + padding-right: $spacing-unit / 2; + padding-left: $spacing-unit / 2; + } +} + + + +/** + * Clearfix + */ +%clearfix:after { + content: ""; + display: table; + clear: both; +} + + + +/** + * Icons + */ +.icon > svg { + display: inline-block; + vertical-align: middle; + + path { + fill: $grey-color; + } +} diff --git a/_sass/minima/_layout.scss b/_sass/minima/_layout.scss new file mode 100644 index 000000000..852b4e742 --- /dev/null +++ b/_sass/minima/_layout.scss @@ -0,0 +1,262 @@ +/** + * Site header + */ +.site-header { + border-top: 5px solid $grey-color-dark; + border-bottom: 1px solid $grey-color-light; + min-height: 56px; + + // Positioning context for the mobile navigation icon + position: relative; +} + +.site-title { + font-size: 26px; + font-weight: 300; + line-height: 56px; + letter-spacing: -1px; + margin-bottom: 0; + float: left; + + &, + &:visited { + color: $grey-color-dark; + } +} + +.site-nav { + float: right; + line-height: 56px; + + .menu-icon { + display: none; + } + + .page-link { + color: $text-color; + line-height: $base-line-height; + + // Gaps between nav items, but not on the last one + &:not(:last-child) { + margin-right: 20px; + } + } + + @include media-query($on-palm) { + position: absolute; + top: 9px; + right: $spacing-unit / 2; + background-color: $background-color; + border: 1px solid $grey-color-light; + border-radius: 5px; + text-align: right; + + .menu-icon { + display: block; + float: right; + width: 36px; + height: 26px; + line-height: 0; + padding-top: 10px; + text-align: center; + + > svg path { + fill: $grey-color-dark; + } + } + + .trigger { + clear: both; + display: none; + } + + &:hover .trigger { + display: block; + padding-bottom: 5px; + } + + .page-link { + display: block; + padding: 5px 10px; + + &:not(:last-child) { + margin-right: 0; + } + margin-left: 20px; + } + } +} + + + +/** + * Site footer + */ +.site-footer { + border-top: 1px solid $grey-color-light; + padding: $spacing-unit 0; +} + +.footer-heading { + font-size: 18px; + margin-bottom: $spacing-unit / 2; +} + +.contact-list, +.social-media-list { + list-style: none; + margin-left: 0; +} + +.footer-col-wrapper { + font-size: 15px; + color: $grey-color; + margin-left: -$spacing-unit / 2; + @extend %clearfix; +} + +.footer-col { + float: left; + margin-bottom: $spacing-unit / 2; + padding-left: $spacing-unit / 2; +} + +.footer-col-1 { + text-align: left; + width: -webkit-calc(25% - (#{$spacing-unit} / 2)); + width: calc(25% - (#{$spacing-unit} / 2)); +} + +.footer-col-2 { + text-align: center; + width: -webkit-calc(50% - (#{$spacing-unit} / 2)); + width: calc(50% - (#{$spacing-unit} / 2)); +} + +.footer-col-3 { + text-align: right; + width: -webkit-calc(25% - (#{$spacing-unit} / 2)); + width: calc(25% - (#{$spacing-unit} / 2)); +} + +@include media-query($on-laptop) { + .footer-col-1, + .footer-col-2 { + width: -webkit-calc(50% - (#{$spacing-unit} / 2)); + width: calc(50% - (#{$spacing-unit} / 2)); + } + + .footer-col-3 { + width: -webkit-calc(100% - (#{$spacing-unit} / 2)); + width: calc(100% - (#{$spacing-unit} / 2)); + } +} + +@include media-query($on-palm) { + .footer-col { + float: none; + width: -webkit-calc(100% - (#{$spacing-unit} / 2)); + width: calc(100% - (#{$spacing-unit} / 2)); + } +} + + + +/** + * Page content + */ +.page-content { + padding: $spacing-unit 0; +} + +.page-heading { + font-size: 20px; +} + +.post-list { + margin-left: 0; + list-style: none; + + > li { + margin-bottom: $spacing-unit; + } + h2 + { + margin: 15px 0px 0px 0px; + } +} + +.post-meta { + font-size: $small-font-size; + color: $grey-color; + //margin-bottom: 5px; + float: left; +} + +.post-author { + font-size: $small-font-size; + color: $grey-color; + //margin-bottom: 5px; + float: right; +} + +.post-link { + display: block; + font-size: 24px; +} + +.post-excerpt { + float: left; +} + +/** + * Posts + */ +.post { + p { + margin: 0px; + } +} + +.post-header { + margin-bottom: $spacing-unit; +} + +.post-title { + font-size: 30px; + letter-spacing: -1px; + line-height: 1; + font-weight: 800; + @include media-query($on-laptop) { + font-size: 36px; + } +} + +.post-content { + margin-bottom: $spacing-unit; + float: left; + padding-top: 15px; + h2 { + font-size: 32px; + + @include media-query($on-laptop) { + font-size: 28px; + } + } + + h3 { + font-size: 26px; + + @include media-query($on-laptop) { + font-size: 22px; + } + } + + h4 { + font-size: 20px; + + @include media-query($on-laptop) { + font-size: 18px; + } + } +} diff --git a/_sass/minima/_syntax-highlighting.scss b/_sass/minima/_syntax-highlighting.scss new file mode 100644 index 000000000..bccdb8995 --- /dev/null +++ b/_sass/minima/_syntax-highlighting.scss @@ -0,0 +1,71 @@ +/** + * Syntax highlighting styles + */ +.highlight { + background: #fff; + @extend %vertical-rhythm; + + .highlighter-rouge & { + background: #eef; + } + + .c { color: #998; font-style: italic } // Comment + .err { color: #a61717; background-color: #e3d2d2 } // Error + .k { font-weight: bold } // Keyword + .o { font-weight: bold } // Operator + .cm { color: #998; font-style: italic } // Comment.Multiline + .cp { color: #999; font-weight: bold } // Comment.Preproc + .c1 { color: #998; font-style: italic } // Comment.Single + .cs { color: #999; font-weight: bold; font-style: italic } // Comment.Special + .gd { color: #000; background-color: #fdd } // Generic.Deleted + .gd .x { color: #000; background-color: #faa } // Generic.Deleted.Specific + .ge { font-style: italic } // Generic.Emph + .gr { color: #a00 } // Generic.Error + .gh { color: #999 } // Generic.Heading + .gi { color: #000; background-color: #dfd } // Generic.Inserted + .gi .x { color: #000; background-color: #afa } // Generic.Inserted.Specific + .go { color: #888 } // Generic.Output + .gp { color: #555 } // Generic.Prompt + .gs { font-weight: bold } // Generic.Strong + .gu { color: #aaa } // Generic.Subheading + .gt { color: #a00 } // Generic.Traceback + .kc { font-weight: bold } // Keyword.Constant + .kd { font-weight: bold } // Keyword.Declaration + .kp { font-weight: bold } // Keyword.Pseudo + .kr { font-weight: bold } // Keyword.Reserved + .kt { color: #458; font-weight: bold } // Keyword.Type + .m { color: #099 } // Literal.Number + .s { color: #d14 } // Literal.String + .na { color: #008080 } // Name.Attribute + .nb { color: #0086B3 } // Name.Builtin + .nc { color: #458; font-weight: bold } // Name.Class + .no { color: #008080 } // Name.Constant + .ni { color: #800080 } // Name.Entity + .ne { color: #900; font-weight: bold } // Name.Exception + .nf { color: #900; font-weight: bold } // Name.Function + .nn { color: #555 } // Name.Namespace + .nt { color: #000080 } // Name.Tag + .nv { color: #008080 } // Name.Variable + .ow { font-weight: bold } // Operator.Word + .w { color: #bbb } // Text.Whitespace + .mf { color: #099 } // Literal.Number.Float + .mh { color: #099 } // Literal.Number.Hex + .mi { color: #099 } // Literal.Number.Integer + .mo { color: #099 } // Literal.Number.Oct + .sb { color: #d14 } // Literal.String.Backtick + .sc { color: #d14 } // Literal.String.Char + .sd { color: #d14 } // Literal.String.Doc + .s2 { color: #d14 } // Literal.String.Double + .se { color: #d14 } // Literal.String.Escape + .sh { color: #d14 } // Literal.String.Heredoc + .si { color: #d14 } // Literal.String.Interpol + .sx { color: #d14 } // Literal.String.Other + .sr { color: #009926 } // Literal.String.Regex + .s1 { color: #d14 } // Literal.String.Single + .ss { color: #990073 } // Literal.String.Symbol + .bp { color: #999 } // Name.Builtin.Pseudo + .vc { color: #008080 } // Name.Variable.Class + .vg { color: #008080 } // Name.Variable.Global + .vi { color: #008080 } // Name.Variable.Instance + .il { color: #099 } // Literal.Number.Integer.Long +} diff --git a/_sass/minima/tabs.scss b/_sass/minima/tabs.scss new file mode 100644 index 000000000..19e12582f --- /dev/null +++ b/_sass/minima/tabs.scss @@ -0,0 +1,26 @@ +div +{ + .category + { + border: 0px solid; + border-radius: 7px; + float: left; + text-align: left; + width: -webkit-calc(80%); + width: calc(80%); + background: rgba(227,222,222,0.5); + padding: 10px 5px 10px 20px; + box-shadow: 5px 5px 2px #888888; + margin: 5px 10% 5px 10%; + font-size: 12px; + h3 { + margin: 0px; + } + } + .category:hover + { + width: -webkit-calc(82%); + width: calc(82%); + padding: 11px 5px 11px 21px; + } +} diff --git a/about.md b/about.md new file mode 100644 index 000000000..fb074a698 --- /dev/null +++ b/about.md @@ -0,0 +1,11 @@ +--- +layout: page +title: About +permalink: /about/ +--- + +This repository was created to list some popular algorithms, include tutorials, study materials and contain some implementations, to help students prepare for competitive coding events like ACM ICPC and also for placements. This website contains tutorials for various algorithms and for the corresponding implementation you can check out the repository [Algorithms](https://github.com/codeIIEST/Algorithms) under our [Github Organization](https://github.com/codeIIEST). + +Also, this repository is currently growing, and we want this to always grow, including more and more algorithm implementations. So, you are free to contribute your implementations, making sure they are well documented for the reader to understand. + +Happy Coding! diff --git a/algocodeiiest.jpg b/algocodeiiest.jpg deleted file mode 100644 index 48351fc92..000000000 Binary files a/algocodeiiest.jpg and /dev/null differ diff --git a/index.md b/index.md new file mode 100644 index 000000000..1eb5d6724 --- /dev/null +++ b/index.md @@ -0,0 +1,6 @@ +--- +# You don't need to edit this file, it's empty on purpose. +# Edit theme's home layout instead if you wanna make some changes +# See: https://jekyllrb.com/docs/themes/#overriding-theme-defaults +layout: home +--- diff --git a/pages/dp.html b/pages/dp.html new file mode 100644 index 000000000..da7fadaf4 --- /dev/null +++ b/pages/dp.html @@ -0,0 +1,27 @@ +--- +layout: default +--- + +
+ + + + +
    + {% for post in site.categories.dpgreedy %} +
  • +

    + {{ post.title | escape }} +

    + +
    +
    + {{ post.content | strip_html | truncatewords: 30 }} +
    +
    + Continue Reading... +
  • + {% endfor %} +
+ +
diff --git a/pages/graph.html b/pages/graph.html new file mode 100644 index 000000000..99fdf9b74 --- /dev/null +++ b/pages/graph.html @@ -0,0 +1,27 @@ +--- +layout: default +--- + +
+ + + + +
    + {% for post in site.categories.graph %} +
  • +

    + {{ post.title | escape }} +

    + +
    +
    + {{ post.content | strip_html | truncatewords: 30 }} +
    +
    + Continue Reading... +
  • + {% endfor %} +
+ +
diff --git a/pages/others.html b/pages/others.html new file mode 100644 index 000000000..6a1b26ea8 --- /dev/null +++ b/pages/others.html @@ -0,0 +1,27 @@ +--- +layout: default +--- + +
+ + + + +
    + {% for post in site.categories.others %} +
  • +

    + {{ post.title | escape }} +

    + +
    +
    + {{ post.content | strip_html | truncatewords: 30 }} +
    +
    + Continue Reading... +
  • + {% endfor %} +
+ +
diff --git a/pages/searching.html b/pages/searching.html new file mode 100644 index 000000000..d101bdd1e --- /dev/null +++ b/pages/searching.html @@ -0,0 +1,27 @@ +--- +layout: default +--- + +
+ + + + +
    + {% for post in site.categories.search %} +
  • +

    + {{ post.title | escape }} +

    + +
    +
    + {{ post.content | strip_html | truncatewords: 30 }} +
    +
    + Continue Reading... +
  • + {% endfor %} +
+ +
diff --git a/pages/sorting.html b/pages/sorting.html new file mode 100644 index 000000000..1010a068c --- /dev/null +++ b/pages/sorting.html @@ -0,0 +1,27 @@ +--- +layout: default +--- + +
+ + + + +
    + {% for post in site.categories.sort %} +
  • +

    + {{ post.title | escape }} +

    + +
    +
    + {{ post.content | strip_html | truncatewords: 30 }} +
    +
    + Continue Reading... +
  • + {% endfor %} +
+ +
diff --git a/pages/stackq.html b/pages/stackq.html new file mode 100644 index 000000000..e24008024 --- /dev/null +++ b/pages/stackq.html @@ -0,0 +1,27 @@ +--- +layout: default +--- + +
+ + + + +
    + {% for post in site.categories.stackq %} +
  • +

    + {{ post.title | escape }} +

    + +
    +
    + {{ post.content | strip_html | truncatewords: 30 }} +
    +
    + Continue Reading... +
  • + {% endfor %} +
+ +
diff --git a/pages/trees.html b/pages/trees.html new file mode 100644 index 000000000..ce31425dd --- /dev/null +++ b/pages/trees.html @@ -0,0 +1,27 @@ +--- +layout: default +--- + +
+ + + + +
    + {% for post in site.categories.tree %} +
  • +

    + {{ post.title | escape }} +

    + +
    +
    + {{ post.content | strip_html | truncatewords: 30 }} +
    +
    + Continue Reading... +
  • + {% endfor %} +
+ +
diff --git a/test.md b/test.md deleted file mode 100644 index cdb2ced67..000000000 --- a/test.md +++ /dev/null @@ -1 +0,0 @@ -# tsting