diff --git a/Algorithms/Backtracking/Hamiltonian Cycle.cpp b/Algorithms/Backtracking/Hamiltonian Cycle.cpp new file mode 100644 index 0000000..908b8d8 --- /dev/null +++ b/Algorithms/Backtracking/Hamiltonian Cycle.cpp @@ -0,0 +1,157 @@ +// This program detects any Hamiltonian Cycle in a graph + +#include +using namespace std; + +// Number of vertices in the graph +#define V 5 + +void printSolution(int path[]); + +/* A utility function to check if +the vertex v can be added at index 'pos' +in the Hamiltonian Cycle constructed +so far (stored in 'path[]') */ +bool isSafe(int v, bool graph[V][V], + int path[], int pos) +{ + /* Check if this vertex is an adjacent + vertex of the previously added vertex. */ + if (graph [path[pos - 1]][ v ] == 0) + return false; + + /* Check if the vertex has already been included. + This step can be optimized by creating + an array of size V */ + for (int i = 0; i < pos; i++) + if (path[i] == v) + return false; + + return true; +} + +/* A recursive utility function +to solve hamiltonian cycle problem */ +bool hamCycleUtil(bool graph[V][V], + int path[], int pos) +{ + /* base case: If all vertices are + included in Hamiltonian Cycle */ + if (pos == V) + { + // And if there is an edge from the + // last included vertex to the first vertex + if (graph[path[pos - 1]][path[0]] == 1) + return true; + else + return false; + } + + // Try different vertices as a next candidate + // in Hamiltonian Cycle. We don't try for 0 as + // we included 0 as starting point in hamCycle() + for (int v = 1; v < V; v++) + { + /* Check if this vertex can be added + // to Hamiltonian Cycle */ + if (isSafe(v, graph, path, pos)) + { + path[pos] = v; + + /* recur to construct rest of the path */ + if (hamCycleUtil (graph, path, pos + 1) == true) + return true; + + /* If adding vertex v doesn't lead to a solution, + then remove it */ + path[pos] = -1; + } + } + + /* If no vertex can be added to + Hamiltonian Cycle constructed so far, + then return false */ + return false; +} + +/* It mainly uses hamCycleUtil() to +solve the problem. It returns false if there is no +Hamiltonian Cycle possible, otherwise return true +and prints the path.*/ +bool hamCycle(bool graph[V][V]) +{ + int *path = new int[V]; + for (int i = 0; i < V; i++) + path[i] = -1; + + /* Let us put vertex 0 as the first vertex in the path. + If there is a Hamiltonian Cycle, then the path can be + started from any point of the cycle as the graph is undirected */ + path[0] = 0; + if (hamCycleUtil(graph, path, 1) == false ) + { + cout << "\nSolution does not exist"; + return false; + } + + printSolution(path); + return true; +} + +/* A utility function to print solution */ +void printSolution(int path[]) +{ + cout << "Solution Exists:" + " Following is one Hamiltonian Cycle \n"; + for (int i = 0; i < V; i++) + cout << path[i] << " "; + + // Let us print the first vertex again + // to show the complete cycle + cout << path[0] << " "; + cout << endl; +} + +// Driver Code +int main() +{ + /* Let us create the following graph + (0)--(1)--(2) + | / \ | + | / \ | + | / \ | + (3)-------(4) */ + bool graph1[V][V] = {{0, 1, 0, 1, 0}, + {1, 0, 1, 1, 1}, + {0, 1, 0, 0, 1}, + {1, 1, 0, 0, 1}, + {0, 1, 1, 1, 0}}; + + // Print the solution + hamCycle(graph1); + + /* Let us create the following graph + (0)--(1)--(2) + | / \ | + | / \ | + | / \ | + (3) (4) */ + bool graph2[V][V] = {{0, 1, 0, 1, 0}, + {1, 0, 1, 1, 1}, + {0, 1, 0, 0, 1}, + {1, 1, 0, 0, 0}, + {0, 1, 1, 0, 0}}; + + // Print the solution + hamCycle(graph2); + + return 0; +} + + +/*Output: +Solution Exists: Following is one Hamiltonian Cycle + 0 1 2 4 3 0 + +Solution does not exist +*/ diff --git a/Algorithms/Backtracking/M Coloring Problem.cpp b/Algorithms/Backtracking/M Coloring Problem.cpp new file mode 100644 index 0000000..58a5b08 --- /dev/null +++ b/Algorithms/Backtracking/M Coloring Problem.cpp @@ -0,0 +1,109 @@ +/* To determine if an undirected graph can be colored with atmost m colors +such that no two adjacent vertices are colored with the same color */ + +#include + +// Number of vertices in the graph +#define V 4 + +void printSolution(int color[]); + +/* A utility function to check whether the edge exists or not +(i.e, graph[v][i]==1). If exist then checks whether the color to +be filled in the new vertex(c is sent in the parameter) is already +used by its adjacent vertices(i-->adj vertices) or not (i.e, color[i]==c) */ + +bool isSafe (int v, bool graph[V][V], int color[], int c) +{ + for (int i = 0; i < V; i++) + if (graph[v][i] && c == color[i]) + return false; + return true; +} + +/* A recursive utility function to solve m coloring problem */ +bool graphColoringUtil(bool graph[V][V], int m, int color[], int v) +{ + /* base case: If all vertices are assigned a color then + return true */ + if (v == V) + return true; + + /* Consider this vertex v and try different colors */ + for (int c = 1; c <= m; c++) + { + /* Check if assignment of color c to v is fine*/ + if (isSafe(v, graph, color, c)) + { + color[v] = c; + + /* recur to assign colors to rest of the vertices */ + if (graphColoringUtil (graph, m, color, v+1) == true) + return true; + + /* If assigning color c doesn't lead to a solution + then remove it */ + color[v] = 0; + } + } + + /* If no color can be assigned to this vertex then return false */ + return false; +} + +/* This function returns false if the m colors cannot be assigned, otherwise return true and +prints assignments of colors to all vertices. */ +bool graphColoring(bool graph[V][V], int m) +{ + // Initialize all color values as 0. This initialization is needed + // correct functioning of isSafe() + int color[V]; + for (int i = 0; i < V; i++) + color[i] = 0; + + // Call graphColoringUtil() for vertex 0 + if (graphColoringUtil(graph, m, color, 0) == false) + { + cout<<"Solution does not exist"; + return false; + } + + // Print the solution + printSolution(color); + return true; +} + +/* A utility function to print solution */ +void printSolution(int color[]) +{ + cout<<"Solution Exists:Following are the assigned colors \n"; + for (int i = 0; i < V; i++) + cout<<" "< +#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]. */ +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; i++, j--) + if (board[i][j]) + return false; + + return true; +} + +/* A recursive utility function to solve N +Queen problem */ +bool solveNQUtil(int board[N][N], int col) +{ + /* base case: If all queens are placed + then return true */ + if (col >= N) + return true; + + /* Consider this column and try placing + this queen in all rows one by one */ + for (int i = 0; i < N; i++) { + /* Check if the queen can be placed on + board[i][col] */ + 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 the queen cannot be placed in any row in + this colum col then return false */ + return false; +} + +/* This function returns false if queens +cannot be placed, otherwise, return true and +prints placement of queens in the form of 1s.*/ +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; +} + + +/*Output: + 0 0 1 0 + 1 0 0 0 + 0 0 0 1 + 0 1 0 0 +*/ diff --git a/Algorithms/Backtracking/Rat in a Maze.cpp b/Algorithms/Backtracking/Rat in a Maze.cpp new file mode 100644 index 0000000..02bdeab --- /dev/null +++ b/Algorithms/Backtracking/Rat in a Maze.cpp @@ -0,0 +1,97 @@ +#include + +// Maze size +#define N 4 + +bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]); + +/* A utility function to print solution matrix sol[N][N] */ +void printSolution(int sol[N][N]) +{ + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) + cout<<" "<= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1) + return true; + + return false; +} + +/* This function sreturns false if no +path is possible, otherwise return true and prints the path in the +form of 1s.*/ +bool solveMaze(int maze[N][N]) +{ + int sol[N][N] = { { 0, 0, 0, 0 }, + { 0, 0, 0, 0 }, + { 0, 0, 0, 0 }, + { 0, 0, 0, 0 } }; + + if (solveMazeUtil(maze, 0, 0, sol) == false) { + cout<<"Solution doesn't exist"; + return false; + } + + printSolution(sol); + return true; +} + +/* A recursive utility function to solve Maze problem */ +bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]) +{ + // if (x, y is goal) return true + if (x == N - 1 && y == N - 1) { + sol[x][y] = 1; + return true; + } + + // Check if maze[x][y] is valid + if (isSafe(maze, x, y) == true) { + // mark x, y as part of solution path + sol[x][y] = 1; + + /* Move forward in x direction */ + if (solveMazeUtil(maze, x + 1, y, sol) == true) + return true; + + /* If moving in x direction doesn't give solution then + Move down in y direction */ + if (solveMazeUtil(maze, x, y + 1, sol) == true) + return true; + + /* If none of the above movements work then BACKTRACK: + unmark x, y as part of solution path */ + sol[x][y] = 0; + return false; + } + + return false; +} + +// driver program to test above function +int main() +{ + int maze[N][N] = { { 1, 0, 0, 0 }, + { 1, 1, 0, 1 }, + { 0, 1, 0, 0 }, + { 1, 1, 1, 1 } }; + + solveMaze(maze); + return 0; +} + + +/* Output: + 1 0 0 0 + 1 1 0 0 + 0 1 0 0 + 0 1 1 1 +*/ diff --git a/Algorithms/Backtracking/Sudoku.cpp b/Algorithms/Backtracking/Sudoku.cpp new file mode 100644 index 0000000..8b481e9 --- /dev/null +++ b/Algorithms/Backtracking/Sudoku.cpp @@ -0,0 +1,161 @@ +#include +using namespace std; + +// UNASSIGNED is used for empty cells in sudoku grid +#define UNASSIGNED 0 + +// N is used for the 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 +an 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 +an 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 +an 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) && + grid[row][col] == UNASSIGNED; +} + +/* 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++) + cout << grid[row][col] << " "; + cout << endl; + } +} + +// Driver Code +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 + cout << "No solution exists"; + + return 0; +} + + +/* Output: + 3 1 6 5 7 8 4 9 2 + 5 2 9 1 3 4 7 6 8 + 4 8 7 6 2 9 5 3 1 + 2 6 3 4 1 5 9 8 7 + 9 7 4 8 6 3 1 2 5 + 8 5 1 7 9 2 6 4 3 + 1 3 8 9 4 7 2 5 6 + 6 9 2 3 5 1 8 7 4 + 7 4 5 2 8 6 3 1 9 +*/ diff --git a/Algorithms/Balanced_paranthesis_optimized.py b/Algorithms/Balanced_paranthesis_optimized.py new file mode 100644 index 0000000..572ec16 --- /dev/null +++ b/Algorithms/Balanced_paranthesis_optimized.py @@ -0,0 +1,26 @@ +# Optimized Python3 code to Check for balanced parentheses in an expression +open_list = ["[","{","("] +close_list = ["]","}",")"] + +# Function to check parentheses +def check(myStr): + stack = [] + for i in myStr: + if i in open_list: + stack.append(i) + elif i in close_list: + pos = close_list.index(i) + if ((len(stack) > 0) and + (open_list[pos] == stack[len(stack)-1])): + stack.pop() + else: + return "Unbalanced" + if len(stack) == 0: + return "Balanced" + +# Driver code +string = "{[]{()}}" +print(string,"-", check(string)) + +string = "[{}{})(]" +print(string,"-", check(string)) diff --git a/Algorithms/Circular_Queue/CircularQueue.cpp b/Algorithms/Circular_Queue/CircularQueue.cpp new file mode 100644 index 0000000..9734a45 --- /dev/null +++ b/Algorithms/Circular_Queue/CircularQueue.cpp @@ -0,0 +1,117 @@ +#include +using namespace std; + +struct Queue +{ + int rear, front; + int size; + char *arr; + Queue(int s) + { + front = rear = -1; + size = s; + arr = new char[s]; + } + void enQueue(char value); + char deQueue(); + void displayQueue(); +}; +void Queue::enQueue(char value) +{ + if ((front == 0 && rear == size-1) ||(rear == (front-1)%(size-1))) + { + cout<<"\nQueue is Full"; + return; + } + else if (front == -1) + { + front = rear = 0; + arr[rear] = value; + } + + else if (rear == size-1 && front != 0) + { + rear = 0; + arr[rear] = value; + } + + else + { + rear++; + arr[rear] = value; + } +} + +char Queue::deQueue() +{ + if (front == -1) + { + cout<<"\nQueue is Empty"; + return INT_MIN; + } + char data = arr[front]; + arr[front] = -1; + if (front == rear) + { + front = -1; + rear = -1; + } + else if (front == size-1) + { + front = 0; + } + else + { + front++; + } + return data; +} + +void Queue::displayQueue() +{ + if (front == -1) + { + cout<<"\nQueue is Empty"; + return; + } + cout<<"\nElements in Circular Queue are: "; + if (rear >= front) + { + for (int i = front; i <= rear; i++) + cout<>choice; + if(choice==1) + { + char a; + cin>>a; + q.enQueue(a); + q.displayQueue(); + } + else if(choice==2) + { + cout<<"\nDeleted value = "< +using namespace std; + +#define ll long long +#define INF 1000000007 + +long long f[100001]; + +ll pow(ll a, ll b, ll MOD) +{ + ll x=1,y=a; + while(b > 0) + { + if(b%2 == 1) + { + x=(x*y); + if(x>MOD) x%=MOD; + } + y = (y*y); + if(y>MOD) y%=MOD; + b /= 2; + } + return x; +} +/* Modular Multiplicative Inverse + Using Euler's Theorem + a^(phi(m)) = 1 (mod m) + a^(-1) = a^(m-2) (mod m) */ +ll InverseEuler(ll n, ll MOD) +{ + return pow(n,MOD-2,MOD); +} + +ll C(ll n, ll r, ll MOD) +{ + + return (f[n]*((InverseEuler(f[r], MOD) * InverseEuler(f[n-r], MOD)) % MOD)) % MOD; +} + +int main(){ + f[0] = 1; + for(int i = 1 ; i <= 100000 ; i++) + f[i] = (f[i-1]*i)%INF; + ll n,r,ans; + cout<<"Enter the value of N\n"; + cin>>n; + cout<<"Enter the value of R\n"; + cin>>r; + ans=C(n,r,INF); + cout<<"The value of nCr for numbers "< Represent no of test cases. +// 5 +// 1 2 3 -2 5 +// 4 +// -1 -2 -3 -4 + +// Sample Output: 9 +// -1 + + +#include +using namespace std; + +int kadanes(int arr[],int a) +{ + int current=arr[0]; + int global=arr[0]; + for(int i=1;icurrent+arr[i]) + current=arr[i]; + else + current=(current+arr[i]); + + if(current>global) + global=current; + } + + return global; +} + +int main() { + int testcase; + cin>>testcase; + while(testcase--) + { + int size; + cin>>size; + int arr[size]; + for(int i=0;i>arr[i]; + + cout< +using namespace std; + +class Graph { + + int v; + int e; + int matrix[10][10]; + +public: + Graph(int v, int e); + void addEdge(int start, int e); + void DFS(int start, vector& flags); + void BFS(int start); +}; + +Graph::Graph(int vertices, int edges) +{ + v = vertices; + e = edges; + for (int row = 0; row < v; row++) { + for (int column = 0; column < v; column++) { + matrix[row][column] = 0; + } + } +} +void Graph::addEdge(int start, int end) +{ + matrix[start][end] = 1; + matrix[end][start] = 1; +} +void Graph::DFS(int start, vector& flags) +{ + cout << start << " "; + flags[start] = true; + for (int i = 0; i < v; i++) { + if (matrix[start][i] == 1 && (!flags[i])) { + DFS(i, flags); + } + } +} +void Graph::BFS(int start) +{ + vector flags(v, false); + vector q; + q.push_back(start); + flags[start] = true; + int vis; + cout<<"BFS: "; + while (!q.empty()) { + vis = q[0]; + cout << vis << " "; + q.erase(q.begin()); + for (int i = 0; i < v; i++) { + if (matrix[vis][i] == 1 && (!flags[i])) + { + q.push_back(i); + flags[i] = true; + } + } + } +} +int main() +{ + int v = 5, e = 4; + Graph G(v, e); + G.addEdge(0, 1); + G.addEdge(1, 2); + G.addEdge(1, 3); + G.addEdge(2, 4); + vector flags(v, false); + cout<<"DFS: " ; + G.DFS(0, flags); + cout< +using namespace std; +void addEdge(vector adj[], int u, int v) +{ + adj[u].push_back(v); + adj[v].push_back(u); +} +void DFSUtil(int u, vector adj[], + vector &visited) +{ + visited[u] = true; + cout << u << " "; + for (int i=0; i adj[], int V) +{ + vector visited(V, false); + for (int u=0; u>V>>edge; + + vector *adj = new vector[V+1]; + + for(int i=0;i>x>>y; + addEdge(adj,x,y); + } + cout<<"The order of the depth first search traversal is "; + DFS(adj, V); + return 0; +} \ No newline at end of file diff --git a/Algorithms/Graphs/Detect_Cycle_In_Undirected_Graph.cpp b/Algorithms/Graphs/Detect_Cycle_In_Undirected_Graph.cpp new file mode 100644 index 0000000..99c5b27 --- /dev/null +++ b/Algorithms/Graphs/Detect_Cycle_In_Undirected_Graph.cpp @@ -0,0 +1,80 @@ +// C++ program to detect cycle in an undirected graph using BFS. +#include +using namespace std; + +void addEdge(vector adj[], int u, int v) +{ + adj[u].push_back(v); + adj[v].push_back(u); +} + +bool isCyclicConntected(vector adj[], int VertexToBeVisited,int NoOfVertices, vector& visited) +{ + // Set parent vertex for every vertex as -1. + vector parent(NoOfVertices, -1); + + // Create a queue for BFS + queue queue; + + // Mark the current node as visited and enqueue it + visited[VertexToBeVisited] = true; + queue.push(VertexToBeVisited); + + while (!queue.empty()) { + + // Dequeue a vertex from queue and print it + int u = queue.front(); + queue.pop(); + + for (auto v : adj[u]) + { + if (!visited[v]) + { + visited[v] = true; + queue.push(v); + parent[v] = u; + } + else if (parent[u] != v) + return true; + } + } + return false; +} + +bool isCyclicDisconntected(vector adj[], int V) +{ + // Mark all the vertices as not visited + vector visited(V, false); + for (int i = 0; i < V; i++) + if (!visited[i] && isCyclicConntected(adj, i,V, visited)) + return true; + return false; +} + +// Driver program to test methods of graph class +int main() +{ + cout<<"enter the number of vertices : "; + int no_of_variables ; + cin>>no_of_variables; + //adj[V] is 2D vector to store the connection between 2 vertices + int vertex1,vertex2; + vector adj[no_of_variables]; + do{ + char ch; + cout<<"Enter Edge Details :\n"; + cout<<"Enter Vertex 1 : "; + cin>>vertex1; + cout<<"Enter Vertex 2 : "; + cin>>vertex2; + addEdge(adj,vertex1,vertex2); + cout<<"wanna add more edges(y/n):"; + cin>>ch; + }while(ch!='y'); + if (isCyclicDisconntected(adj, no_of_variables)) + cout << "Yes"; + else + cout << "No"; + + return 0; +} diff --git a/Algorithms/Graphs/Dijkstra's Algorithm.cpp b/Algorithms/Graphs/Dijkstra's Algorithm.cpp new file mode 100644 index 0000000..7875a96 --- /dev/null +++ b/Algorithms/Graphs/Dijkstra's Algorithm.cpp @@ -0,0 +1,115 @@ +/* + Dijkstra's algorithm (or Dijkstra's Shortest Path First algorithm, SPF algorithm) is an algorithm for finding the + shortest paths between nodes in a weighted graph, which may represent, for example, mobile or road networks. + It can be implemented in C++ using : + 1) Adjacency matrix representation + 2) Adjacency List representation (using vector STL of C++) + 3) Set STL of C++ + 4) PriorityQueue STL of C++ + This code is implementation of Dijkstra's algorithm using Adjacency list representation for Undirected weighted graph. + When to use Dijkstra's algorithm and Floyd Warshall algorithm ? + -> Dijkstra's algorithm is for single source and multiple destinations . + -> Floyd Warshall algorithm is for multiple sources and multiple destinations . +*/ + + +/* +SAMPLE OUTPUT : +Enter number of vertices +4 +Enter number of edges +5 +Undirected weighted graph +Enter all edges one by one +Format for input : vertex1 vertex2 weight +1 2 2 +1 3 10 +1 4 4 +2 3 2 +4 2 15 +Enter the source vertex +2 + Source Destination Shortest Distance + 2 1 2 + 2 2 0 + 2 3 2 + 2 4 6 +*/ + +#include +using namespace std; +#define MAXN 1111 +#define INF 999999999 +vector< pair >v[MAXN]; + +vector djikstras(int source, int no_of_vertices) { + vector dist(no_of_vertices, INF); + set< pair > queue; + vector visited(no_of_vertices, false); + dist[source] = 0; + visited[source] = true; + queue.insert(make_pair(dist[source], source)); + + while(!queue.empty()) { + pair front_p = *(queue.begin()); + queue.erase(queue.begin()); + int cur_dist = front_p.first; + int node = front_p.second; + + for(int i=0; i cur_dist + weight) { + if(queue.find(make_pair(dist[to], to)) != queue.end()) { + queue.erase(make_pair(dist[to], to)); + } + dist[to] = cur_dist + weight; + queue.insert(make_pair(dist[to], to)); + } + } + } + return dist; +} + +int main() { + cout<<"\nEnter number of vertices\n"; + int no_of_vertices; cin >> no_of_vertices; + + cout<<"\nEnter number of edges\n"; + int no_of_edges; cin >> no_of_edges; + + /* + Input the edges of undirected weighed graph + Format for input : + vertex1 vertex2 weight + */ + + cout<<"\nUndirected weighted graph "; + + cout<<"\nEnter all edges one by one " + <<"\nFormat for input : vertex1 vertex2 weight\n"; + for(int i=0; i> vertex1 >> vertex2 >> weight; + vertex1--, vertex2--; + v[vertex1].push_back(make_pair(vertex2, weight)); + v[vertex2].push_back(make_pair(vertex1, weight)); + } + + /* + Source vertex is that vertex from where shortest distance to all other vertices is to be found + */ + + cout<<"\nEnter the source vertex\n"; + int source; cin >> source; + source --; + vector dist = djikstras(source, no_of_vertices); + + cout<<"\n"; + cout< + +using namespace std; + +int findset(int p[], int x){ + if(x!=p[x]){ + p[x]=findset(p,p[x]); + } + return p[x]; +} + +void unionset(int p[],int r[],int a,int b){ + int x=findset(p,a); + int y=findset(p,b); + if(x!=y){ + if(r[x]>n>>m; + int x,y,w; + vector>> E; + for(int i=0;i>x>>y>>w; + E.push_back({w,{x-1,y-1}}); + } + sort(E.begin(),E.end()); + int p[n],r[n]; + for(int i=0;i v; + for(int i=0;i +using namespace std; +#define MAX5 100010 +#define pb push_back +int dist[MAX5]; +bool visit[MAX5]; +vector vec[MAX5]; +queue q; +void bfs(int src) +{ + memset(visit,0,sizeof(visit)); + dist[src]=0; + q.push(src); + while(q.size()!=0) + { + int p=q.front(); + cout<>nodes>>edges; + cout<<"Enter edges between nodes"<<'\n'; + for(int i=0;i>x>>y; + vec[x].pb(y); + vec[y].pb(x); + } + cout<<"Enter Source node"<<'\n'; + int src; + cin>>src; + cout<<"The nodes are:"<<'\n'; + bfs(src); + cout<<'\n'; + cout<<"Distance of each node starting from source:"<<'\n'; + for(int i=1;i<=nodes;i++) + { + cout<<"Distance of node"<<" "< +#include +#include + +using namespace std; + +class Graph +{ + int V; // No. of vertices + list *adj; // Pointer to an array containing adjacency lists + bool isCyclicUtil(int v, bool visited[], bool *rs); // used by isCyclic() +public: + Graph(int V); // Constructor + void addEdge(int v, int w); // to add an edge to graph + bool isCyclic(); // returns true if there is a cycle in this graph +}; + +Graph::Graph(int V) +{ + this->V = V; + adj = new list[V]; +} + +void Graph::addEdge(int v, int w) +{ + adj[v].push_back(w); // Add w to v�s list. +} + +// This function is a variation of DFSUtil() in https://www.geeksforgeeks.org/archives/18212 +bool Graph::isCyclicUtil(int v, bool visited[], bool *recStack) +{ + if(visited[v] == false) + { + // Mark the current node as visited and part of recursion stack + visited[v] = true; + recStack[v] = true; + + // Recur for all the vertices adjacent to this vertex + list::iterator i; + for(i = adj[v].begin(); i != adj[v].end(); ++i) + { + if ( !visited[*i] && isCyclicUtil(*i, visited, recStack) ) + return true; + else if (recStack[*i]) + return true; + } + + } + recStack[v] = false; // remove the vertex from recursion stack + return false; +} + +// Returns true if the graph contains a cycle, else false. +// This function is a variation of DFS() in https://www.geeksforgeeks.org/archives/18212 +bool Graph::isCyclic() +{ + // Mark all the vertices as not visited and not part of recursion + // stack + bool *visited = new bool[V]; + bool *recStack = new bool[V]; + for(int i = 0; i < V; i++) + { + visited[i] = false; + recStack[i] = false; + } + + // Call the recursive helper function to detect cycle in different + // DFS trees + for(int i = 0; i < V; i++) + if (isCyclicUtil(i, visited, recStack)) + return true; + + return false; +} + +int main() +{ + // Create a graph given in the above diagram + int n,m,a,b,i; + cout<<"Enter the number of vertices\n"; + cin>>n; + cout<<"Enter the number of edges\n"; + cin>>m; + Graph g1(n); + for(i=0;i>a>>b; + g1.addEdge(a,b); + } + + if(g1.isCyclic()) + cout << "Graph contains cycle"; + else + cout << "Graph doesn't contain cycle"; + return 0; +} diff --git a/Algorithms/Graphs/cycle_in_undirected_graph.cpp b/Algorithms/Graphs/cycle_in_undirected_graph.cpp new file mode 100644 index 0000000..486051d --- /dev/null +++ b/Algorithms/Graphs/cycle_in_undirected_graph.cpp @@ -0,0 +1,117 @@ +// A C++ Program to detect cycle in an undirected graph +// Language Used: C++ +// Output: This algorithm will give the output that whether the graph has cycle or not +// Sample Input: +// Enter the number of vertices +/* 5 + Enter the number of edges + 5 + Enter edge no 1 + 1 0 + Enter edge no 2 + 0 2 + Enter edge no 3 + 2 1 + Enter edge no 4 + 0 3 + Enter edge no 5 + 3 4 */ +// Sample output: +// Graph contains cycle +// Sample Output: +// The value of nCr for numbers 5 and 3 is 10 +// Author:Aditya Kothari + +#include +#include +#include +using namespace std; + +// Class for an undirected graph +class Graph +{ + int V; // No. of vertices + list *adj; // Pointer to an array containing adjacency lists + bool isCyclicUtil(int v, bool visited[], int parent); +public: + Graph(int V); // Constructor + void addEdge(int v, int w); // to add an edge to graph + bool isCyclic(); // returns true if there is a cycle +}; + +Graph::Graph(int V) +{ + this->V = V; + adj = new list[V]; +} + +void Graph::addEdge(int v, int w) +{ + adj[v].push_back(w); // Add w to vs list. + adj[w].push_back(v); // Add v to ws list. +} + +// A recursive function that uses visited[] and parent to detect +// cycle in subgraph reachable from vertex v. +bool Graph::isCyclicUtil(int v, bool visited[], int parent) +{ + // Mark the current node as visited + visited[v] = true; + + // Recur for all the vertices adjacent to this vertex + list::iterator i; + for (i = adj[v].begin(); i != adj[v].end(); ++i) + { + // If an adjacent is not visited, then recur for that adjacent + if (!visited[*i]) + { + if (isCyclicUtil(*i, visited, v)) + return true; + } + + // If an adjacent is visited and not parent of current vertex, + // then there is a cycle. + else if (*i != parent) + return true; + } + return false; +} + +// Returns true if the graph contains a cycle, else false. +bool Graph::isCyclic() +{ + // Mark all the vertices as not visited and not part of recursion + // stack + bool *visited = new bool[V]; + for (int i = 0; i < V; i++) + visited[i] = false; + + // Call the recursive helper function to detect cycle in different + // DFS trees + for (int u = 0; u < V; u++) + if (!visited[u]) // Don't recur for u if it is already visited + if (isCyclicUtil(u, visited, -1)) + return true; + + return false; +} + +// Driver program to test above functions +int main() +{ + int n,m,a,b,i; + cout<<"Enter the number of vertices\n"; + cin>>n; + cout<<"Enter the number of edges\n"; + cin>>m; + Graph g1(n); + for(i=0;i>a>>b; + g1.addEdge(a,b); + } + g1.isCyclic()? cout << "Graph contains cycle\n": + cout << "Graph doesn't contain cycle\n"; + return 0; +} diff --git a/Algorithms/Graphs/depth_first_search.cpp b/Algorithms/Graphs/depth_first_search.cpp new file mode 100644 index 0000000..417803b --- /dev/null +++ b/Algorithms/Graphs/depth_first_search.cpp @@ -0,0 +1,48 @@ +//Graph Traversal Algorithm +//Assumption: Graph has only one component and undirected +//Depth First Traversal algorithm to traverse all nodes of a graph +//Language Used: C++ +//author: namanvats + +#include +using namespace std; +typedef long long int ll; +ll visit[100000]; +vector vec[10000]; +void initial() +{ + //This function sets the visit array to zero. + //Visit array will be used to make sure which nodes have been visited or not. + for(int i=0;i<100000;i++) + visit[i]=0; +} +void dfs(int s) +{ + visit[s]=1; + cout<>nodes>>edges; + for(int i=0;i>x>>y; + vec[x].push_back(y); + vec[y].push_back(x); + } + cout<<"Enter Source node:"<<'\n'; + int source; + cin>>source; + cout<<"The Nodes is DFS order of traversal are as follows:"<<'\n'; + dfs(source); + return 0; +} diff --git a/Algorithms/Last_Men_Standing/README.md b/Algorithms/Last_Men_Standing/README.md new file mode 100644 index 0000000..cf29e92 --- /dev/null +++ b/Algorithms/Last_Men_Standing/README.md @@ -0,0 +1,19 @@ +# **Last Men Standing** +A king gathers all his men in the kingdom who are to be sentenced to death for their crimes. He gathers all the criminals in a circle and gives his sword to one man. The man with the sword kills the man to his left and passes the sword to the dead man's left. Find the last two men standing.
**The user inputs the number of criminals(N).**
For simplicity, assume that the criminals are numbered in the anticlockwise direction and there are more than 2 prisoners. + +## **How to solve?** +The basic solution or the first thing that comes to the mind upon reading the problem statement is to use either an array or better, a circular linked list as our answers will vary depending on whether **N** is even or odd. But if we look closely, we will find a pattern which can easily be represented as a mathematical formula and hence can be reduced to be solved in linear or constant time and space. + +## **Input Format** +The input consists of one line.\ +There will be a single integer N, which is the number of criminals. +## **Output Format** +The criminal number(s) that stay alive. + +## **Sample Input** +9 +## **Sample Output** +3   7 + +## **Time Complexity** +The time complexity is linear for large values of N (as we are using only one loop). It can be considered to be almost constant for small values of N. diff --git a/Algorithms/Last_Men_Standing/last_men.cpp b/Algorithms/Last_Men_Standing/last_men.cpp new file mode 100644 index 0000000..f6cf284 --- /dev/null +++ b/Algorithms/Last_Men_Standing/last_men.cpp @@ -0,0 +1,27 @@ +#include + +using namespace std; + +void last_two_alive(int n) +{ int first = 1, last = n, turn = 1; + if(n == 3) + cout<3) + { + if(n%2 != 0) + first += turn * 2; + else + last -= turn; + turn *= 2; + n = n/2; + } + cout<>no_of_criminals; + last_two_alive(no_of_criminals); + return 0; + } diff --git a/Algorithms/Linked_List/Floyd_cycle_detection.cpp b/Algorithms/Linked_List/Floyd_cycle_detection.cpp new file mode 100644 index 0000000..41c50c9 --- /dev/null +++ b/Algorithms/Linked_List/Floyd_cycle_detection.cpp @@ -0,0 +1,67 @@ +//Detect Cycle in a linked list using Floyd’s Cycle Detection Algorithm +//It uses 2 pointer(one fast and one slow) to detect the cycle +#include +#include +using namespace std; + +//Declaration of linked list node +struct Node +{ + int data; + Node* next; +}; + +//Function to push a node +void push(Node*& head, int data) +{ + Node* newNode = new Node; + + newNode->data = data; + newNode->next = head; + head = newNode; +} + + +//Floyd’s cycle detection function +bool isCycle(Node *head) +{ + // There are two pointers + Node *first = head, *second = head; + + while (second && second->next) + { + //move first poiner by one pointer + first = first->next; + + //move second pointer by two pointers + second = second->next->next; + + //linked list contains a cycle if they meet + if (first == second) + return true; + } + + return false; +} + + +int main() +{ + //Sample input + int data[] = { 1, 2, 3, 4, 5 }; + int n = sizeof(data) / sizeof(data[0]); + + Node* head = nullptr; + for (int i = n - 1; i >= 0; i--) + push(head, data[i]); + + + if (isCycle(head)) + cout << "Cycle Found"; + else + cout << "No Cycle Found"; + + //No cycle found + //Sample output + return 0; +} \ No newline at end of file diff --git a/Algorithms/Mathematical/catalan_numbers.cpp b/Algorithms/Mathematical/catalan_numbers.cpp new file mode 100644 index 0000000..4fa62c0 --- /dev/null +++ b/Algorithms/Mathematical/catalan_numbers.cpp @@ -0,0 +1,60 @@ +//Algorithm's Name: Catalan Number + +/* +Explanation: +The Input takes an integer N and the output is the Nth Catalan Number. +Catalan Numbers are (2nCn)/(n+1) where C is thee binomial coefficient. +These are special types of numbers which denotes the pattern in many competitive coding contests. +These numbers were found by Belgian mathematician Catalan. +In Input give which Catalan number you want to find. +The function catalan_number computes it and returns the result which is printed. +For more information on Catalan Numbers:https://en.wikipedia.org/wiki/Catalan_number +*/ + + +#include +#define MOD 1000000007 +#define MOD9 1000000009 +#define forr(i,p,n) for(ll i=p;i= MOD) { + catalan[i] -= MOD; + } + } + } + return catalan[catalan_number_to_be_found]; +} + + +int main(){ + ios::sync_with_stdio(0); + cin.tie(0);cout.tie(0); +ll catalan_number_to_be_found; +cin>>catalan_number_to_be_found; +ll answer=catalan_number(catalan_number_to_be_found); +cout< +#define MOD 1000000007 +#define MOD9 1000000009 +#define forr(i,p,n) for(ll i=p;i 1) + result -= result / euler_totient_for_n; + return result; +} + + +int main(){ + ios::sync_with_stdio(0); + cin.tie(0);cout.tie(0); +ll euler_totient_for_n; +cin>>euler_totient_for_n; +ll answer=EulerTotient(euler_totient_for_n); +cout< +#define MOD 1000000007 +#define MOD9 1000000009 +#define forr(i,p,n) for(ll i=p;i>= 1) + { + if (k & 1) r = r * n%p; + n = n * n%p; + } + return r; + } + + + + + +int main(){ + ios::sync_with_stdio(0); + cin.tie(0);cout.tie(0); + ll a,b,c; + cin>>a>>b>>c; + ll ans=fast_power(a,b,c); + cout< +int InterpolationSearch(int A[], int n, int x){ + int low =0; + int high =n-1; + while (low<=high){ + int mid = low + (((high-1)*(x-A[low]))/(A[high]-A[low])); + if(x==A[mid]) + return mid; // Found x, return (exit) + else if (x +using namespace std; + +int main() +{ + int total_size; + + cout<<"Enter the size of array\n"; + cin>>total_size; + + int arr[total_size],iter,key,flag=0,pos; + + cout<<"Enter the elements of array\n"; + for(iter = 0; iter < total_size; iter++) + { + cin>>arr[iter]; + } + + cout<<"Enter the element to be searched\n"; + cin>>key; + + for(iter = 0; iter < total_size; iter++) + { + if(arr[iter] == key) + { + flag = 1; + pos = iter; + } + } + + if(flag == 1) + cout<<"Key found at position "< +using namespace std; + +// A iterative binary search function. It returns +// location of x in given array arr[l..r] if present, +// otherwise -1 +int binarySearch(int arr[], int l, int r, int x) +{ + while (l <= r) { + int m = l + (r - l) / 2; + + // Check if x is present at mid + if (arr[m] == x) + return m; + + // If x greater, ignore left half + if (arr[m] < x) + l = m + 1; + + // If x is smaller, ignore right half + else + r = m - 1; + } + + // if we reach here, then element was + // not present + return -1; +} + + +int main(void) +{ + int array[] = { 2, 3, 4, 10, 40 }; + int target = 10; + int size = sizeof(array) / sizeof(array[0]); + int result = binarySearch(array, 0, size - 1, target); + (result == -1) ? cout << "Element is not present in array" + : cout << "Element is present at index " << result; + return 0; +} \ No newline at end of file diff --git a/Algorithms/Searching/jumpsearch.cpp b/Algorithms/Searching/jumpsearch.cpp new file mode 100644 index 0000000..504427f --- /dev/null +++ b/Algorithms/Searching/jumpsearch.cpp @@ -0,0 +1,54 @@ +// C++ program to implement Jump Search + +#include +using namespace std; + +int jumpSearch(int arr[], int x, int n) +{ + // Finding block size to be jumped + int step = sqrt(n); + + // Finding the block where element is + // present (if it is present) + int prev = 0; + while (arr[min(step, n)-1] < x) + { + prev = step; + step += sqrt(n); + if (prev >= n) + return -1; + } + + // Doing a linear search for x in block + // beginning with prev. + while (arr[prev] < x) + { + prev++; + + // If we reached next block or end of + // array, element is not present. + if (prev == min(step, n)) + return -1; + } + // If element is found + if (arr[prev] == x) + return prev; + + return -1; +} + +// Driver program to test function +int main() +{ + int arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, + 34, 55, 89, 144, 233, 377, 610 }; + int x = 55; + int n = sizeof(arr) / sizeof(arr[0]); + + // Find the index of 'x' using Jump Search + int index = jumpSearch(arr, x, n); + + // Print the index where 'x' is located + cout << "\nNumber " << x << " is at index " << index; + return 0; +} \ No newline at end of file diff --git a/Algorithms/Sorting/ShellSort.cpp b/Algorithms/Sorting/ShellSort.cpp new file mode 100644 index 0000000..b1766cc --- /dev/null +++ b/Algorithms/Sorting/ShellSort.cpp @@ -0,0 +1,26 @@ +#include +void shellSort(int array[], int n){ + for (int gap = n/2; gap > 0; gap /= 2){ + for (int i = gap; i < n; i += 1) { + int temp = array[i]; + int j; + for (j = i; j >= gap && array[j - gap] > temp; j -= gap){ + array[j] = array[j - gap]; + } + array[j] = temp; + } + } +} +void printArray(int array[], int size){ + for(int i=0; i +using namespace std; + +void swap(int *xp, int *yp) +{ + int temp = *xp; + *xp = *yp; + *yp = temp; +} + +// A function to implement bubble sort +void bubbleSort(int arr[], int n) +{ + int i, j; + for (i = 0; i < n-1; i++) + + // Last i elements are already in place + for (j = 0; j < n-i-1; j++) + if (arr[j] > arr[j+1]) + swap(&arr[j], &arr[j+1]); +} + +/* Function to print an array */ +void printArray(int arr[], int size) +{ + int i; + for (i = 0; i < size; i++) + cout << arr[i] << " "; + cout << endl; +} + +// Driver code +int main() +{ + int arr[] = {64, 34, 25, 12, 22, 11, 90}; + int n = sizeof(arr)/sizeof(arr[0]); + bubbleSort(arr, n); + cout<<"Sorted array: \n"; + printArray(arr, n); + return 0; +} + +// This code is contributed by rathbhupendra diff --git a/Algorithms/Sorting/heap_sort.cpp b/Algorithms/Sorting/heap_sort.cpp new file mode 100644 index 0000000..97a4784 --- /dev/null +++ b/Algorithms/Sorting/heap_sort.cpp @@ -0,0 +1,69 @@ +//Heap Sort Algorithm +//Language Used: C++ +//Heap Sort algorithm to sort array of elements in ascending order +//Input Format: First line contains size of array, second line contains array elements +//Output Format: Output contains only one line i.e., sorted array of elements +//Sample Input: 5 +// 5 6 4 3 2 +//Sample Output: 2 3 4 5 6 +//author:sarthakeddy + +#include +using namespace std; +#define ll long long + +//Creation of heap using heapify function +void heapify(ll *arr, ll n, ll i) +{ + ll largest=i; + ll left=(2*i + 1); + ll right=(2*i + 2); + + // Find the largest element among root and it's left and right child + if(left < n && arr[left] > arr[largest]) + largest=left; + + if(right < n && arr[right] > arr[largest]) + largest=right; + + if(largest != i) // If largest element is not in root then make largest as root + // and reheapify + { + swap(arr[i],arr[largest]); + heapify(arr,n,largest); + } +} + +//Sorting of array using heap sort +void heapsort(ll *arr, ll n) +{ + for(ll i=n/2-1;i>=0;i--) //Firstly, make heap using heapify + heapify(arr,n,i); + + for(ll i=n-1;i>=0;i--) + { + swap(arr[0],arr[i]); // Swap first and last element as root is largest element + heapify(arr,i,0); // Reheapify array with size reduced + } +} + +void printarray(ll *arr, ll n) +{ + for(ll i=0; i>n; + ll arr[n],i; + cout<<"Enter the elemnts in array\n"; + for(i=0;i>arr[i]; + heapsort(arr, n); + cout<<"Sorted array after heap sort is\n"; + printarray(arr, n); +} \ No newline at end of file diff --git a/Algorithms/Sorting/insertion_sort.cpp b/Algorithms/Sorting/insertion_sort.cpp new file mode 100644 index 0000000..5553d1c --- /dev/null +++ b/Algorithms/Sorting/insertion_sort.cpp @@ -0,0 +1,47 @@ +// C++ program for insertion sort +#include +using namespace std; + +/* Function to sort an array using insertion sort*/ +void insertionSort(int arr[], int n) +{ + int i, key, j; + for (i = 1; i < n; i++) + { + key = arr[i]; + j = i - 1; + + /* Move elements of arr[0..i-1], that are + greater than key, to one position ahead + of their current position */ + while (j >= 0 && arr[j] > key) + { + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = key; + } +} + +// A utility function to print an array of size n +void printArray(int arr[], int n) +{ + int i; + for (i = 0; i < n; i++) + cout << arr[i] << " "; + cout << endl; +} + +/* Driver code */ +int main() +{ + int arr[] = { 12, 11, 13, 5, 6 }; + int n = sizeof(arr) / sizeof(arr[0]); + + insertionSort(arr, n); + printArray(arr, n); + + return 0; +} + +// This is code is contributed by rathbhupendra diff --git a/Algorithms/Sorting/merge_sort.cpp b/Algorithms/Sorting/merge_sort.cpp new file mode 100644 index 0000000..006386a --- /dev/null +++ b/Algorithms/Sorting/merge_sort.cpp @@ -0,0 +1,40 @@ +// Program for implementation of merge sort in c++ +// function msort() calls itself recurively while the function merge() merges two arrays + + +#include +using namespace std; + +void merge(int *a, int p,int q,int r){ + int left[q-p+2], right[r-q+1]; + left[q-p+1] = 99999, right[r-q] = 99999; + for(int l = 0; l<=q-p; l++) + left[l] = a[p+l]; + for(int k = 0; kright[k]){ + a[i] = right[k]; + k++; + } + else{ + a[i] = left[l]; + l++; + } + } +} +void msort(int *a, int p, int r){ + if(p +using namespace std; + +// A utility function to swap two elements +void swap(int* ax, int* bx) +{ + int temp = *ax; + *ax = *bx; + *bx = temp; +} + +// Function to create the partition of Array from Low to High +int partition (int arr[], int low, int high) +{ + int pivot = arr[high]; + int index = (low - 1); + + for (int jx = low; jx <= high - 1; jx++) + { + if (arr[jx] < pivot) + { + index++; + swap(&arr[index], &arr[jx]); + } + } + swap(&arr[index + 1], &arr[high]); + return (index + 1); +} + +// Function to implement QuickSort +void quickSort(int arr[], int low, int high) +{ + if (low < high) + { + int pi = partition(arr, low, high); + + quickSort(arr, low, pi - 1); + quickSort(arr, pi + 1, high); + } +} + +// Function to print an array +void printArray(int arr[], int size) +{ + int index; + for (index = 0; index < size; index++) + cout << arr[index] << " "; + cout << endl; +} + +// Driver Code +int main() +{ + int num, index; + cout<<"Enter number of elements"; + cin>>num; + int arr[num]; + cout<<"Enter elements"<>arr[index]; + quickSort(arr, 0, num - 1); + cout << "Sorted array: "; + printArray(arr, num); + return 0; +} + diff --git a/Algorithms/Sorting/radix sort.cpp b/Algorithms/Sorting/radix sort.cpp new file mode 100644 index 0000000..f95f8de --- /dev/null +++ b/Algorithms/Sorting/radix sort.cpp @@ -0,0 +1,95 @@ +// C++ implementation of Radix Sort +// Sample input: +//Enter the number of data element to be sorted: 4 +//Element 1: 45 +//Element 2: 96 +//Element 3: 22 +//Element 4: 61 +// Sample output: +//Sorted data: +// 22 45 61 96 +#include +using namespace std; + +// A utility function to get maximum value in arr[] +int getMax(int arr[], int n) +{ + int mx = arr[0]; + for (int i = 1; i < n; i++) + if (arr[i] > mx) + mx = arr[i]; + return mx; +} + +// A function to do counting sort of arr[] according to +// the digit represented by exp. +void countSort(int arr[], int num, int exp) +{ + int output[num]; // output array + int i, count[10] = {0}; + + // Store count of occurrences in count[] + for (i = 0; i < num; i++) + count[ (arr[i]/exp)%10 ]++; + + // Change count[i] so that count[i] now contains actual + // position of this digit in output[] + for (i = 1; i < 10; i++) + count[i] += count[i - 1]; + + // Build the output array + for (i = num - 1; i >= 0; i--) + { + output[count[ (arr[i]/exp)%10 ] - 1] = arr[i]; + count[ (arr[i]/exp)%10 ]--; + } + + // Copy the output array to arr[], so that arr[] now + // contains sorted numbers according to current digit + for (i = 0; i < num; i++) + arr[i] = output[i]; +} + +// The main function to that sorts arr[] of size n using +// Radix Sort +void radixsort(int arr[], int num) +{ + // Find the maximum number to know number of digits + int max = getMax(arr, num); + + // Do counting sort for every digit. Note that instead + // of passing digit number, exp is passed. exp is 10^i + // where i is current digit number + for (int exp = 1; max/exp > 0; exp *= 10) + countSort(arr, num, exp); +} + +// A utility function to print an array +void print(int arr[], int num) +{ + for (int i = 0; i < num; i++) + cout << arr[i] << " "; +} + +// Driver program to test above functions +int main() +{ + int num, i; + cout<<"\nEnter the number of data element to be sorted: "; + cin>>num; + + int arr[num]; + for(i = 0; i < num; i++) + { + cout<<"Enter element "<>arr[i]; + } + + radixsort(arr, num); + + // Printing the sorted data. + cout<<"\nSorted Data "; + for (i = 0; i < num; i++) + cout<<" "< +using namespace std; + +void swap(int *xp, int *yp) +{ + int temp = *xp; + *xp = *yp; + *yp = temp; +} + +void selectionSort(int arr[], int n) +{ + int i, j, min_idx; + + // One by one move boundary of unsorted subarray + for (i = 0; i < n-1; i++) + { + // Find the minimum element in unsorted array + min_idx = i; + for (j = i+1; j < n; j++) + if (arr[j] < arr[min_idx]) + min_idx = j; + + // Swap the found minimum element with the first element + swap(&arr[min_idx], &arr[i]); + } +} + +/* Function to print an array */ +void printArray(int arr[], int size) +{ + int i; + for (i=0; i < size; i++) + cout << arr[i] << " "; + cout << endl; +} + +// Driver program to test above functions +int main() +{ + int arr[] = {64, 25, 12, 22, 11}; + int n = sizeof(arr)/sizeof(arr[0]); + selectionSort(arr, n); + cout << "Sorted array: \n"; + printArray(arr, n); + return 0; +} + +// This is code is contributed by rathbhupendra diff --git a/Algorithms/Sorting/tree_sort.cpp b/Algorithms/Sorting/tree_sort.cpp new file mode 100644 index 0000000..c25cbc8 --- /dev/null +++ b/Algorithms/Sorting/tree_sort.cpp @@ -0,0 +1,83 @@ +//Tree Sort Algorithm +//Language Used: C++ +//Tree Sort Algorithm uses Inorder Traversal of a Binary Search Tree to sort elements in ascending order +//Input Format: First line contains size of array, second line contains array elements +//Output Format: Output contains only one line i.e., sorted array of elements +//Sample Input: 5 +// 3 9 0 1 5 +//Sample Output: 0 1 3 5 9 +//author: adiXcodr + +#include +using namespace std; + +struct Node +{ + int key; + struct Node *left, *right; +}; + +// Create New Node +struct Node *newNode(int item) +{ + struct Node *temp = new Node; + temp->key = item; + temp->left = temp->right = NULL; + return temp; +} + +// Storing Inorder traversal in array +void storeSorted(Node *root, int arr[], int &inx) +{ + if (root != NULL) + { + storeSorted(root->left, arr, inx); + arr[inx++] = root->key; + storeSorted(root->right, arr, inx); + } +} + +//Inserting Value to tree +Node* insert(Node* node, int key) +{ + + if (node == NULL) + return newNode(key); + + if (key < node->key) + node->left = insert(node->left, key); + else if (key > node->key) + node->right = insert(node->right, key); + + return node; +} + + +void treeSort(int arr[], int len) +{ + struct Node *root = NULL; + root = insert(root, arr[0]); + + for (int inx=1; inx>len; + int arr[len]; + cout<<"Enter The Elements "; + for (int inx=0; inx>arr[inx]; + treeSort(arr, len); + cout<<"Sorted:\n"; + for (int inx=0; inx + + +import java.util.*; + +class EvaluatePostfixExpression{ + + public static int evaluate(int first,int second,char operator) + { + switch(operator) + { + case '+': + return first+second; + case '-': + return second-first; + case '*': + return first*second; + case '/': + return second/first; + default: + return 0; + } + + } + + public static void main (String[] args) + { + Scanner scan = new Scanner(System.in); + int testcase = scan.nextInt(); + while(testcase -- > 0) + { + String postfix = scan.next(); + Stackstack = new Stack(); + for(int i=0;i 0) + { + String infix = scan.next(); + infix+=")"; + + Stackstack = new Stack(); + stack.push('('); + + String postfix=""; + int i=0; + while(!stack.isEmpty()) + { + if( infix.charAt(i)=='(' ) + stack.push('('); + else if( infix.charAt(i)==')' ) + { + while( stack.peek()!='(' ) + { + postfix+=stack.pop(); + } + stack.pop(); + } + else if( Character.isLetter( infix.charAt(i) ) ) + { + postfix+=infix.charAt(i); + } + else + { + while( precision(stack.peek()) >= precision( infix.charAt(i) ) ) + { + postfix+=stack.pop(); + } + stack.push( infix.charAt(i) ); + } + + i++; + } + + + System.out.println(postfix); + + } + } +} diff --git a/Algorithms/Stack/NextLarger.java b/Algorithms/Stack/NextLarger.java new file mode 100644 index 0000000..06e8477 --- /dev/null +++ b/Algorithms/Stack/NextLarger.java @@ -0,0 +1,77 @@ + + + +import java.util.*; + +class NextLarger{ + public static void main(String[] args) + { + Scanner scan = new Scanner(System.in); + int testcases = scan.nextInt(); + while(testcases -- > 0) + { + int size = scan.nextInt(); + int array[] = new int[size]; + + for(int i=0;istack = new Stack(); + stack.push(array[size-1]); + + for(int i=size-2;i>=0;i--) + { + while(!stack.isEmpty() && stack.peek()<=array[i]) + { + stack.pop(); + } + if(!stack.isEmpty() && stack.peek()>array[i]) + { + result[index++]=stack.peek(); + } + else + { + result[index++]=-1; + } + stack.push(array[i]); + } + + for(int i=index-1;i>=0;i--) + { + if(i==0) + System.out.print(result[i]); + else + System.out.print(result[i]+" "); + } + + System.out.println(); + } + } +} diff --git a/Algorithms/Stack/infix_to_postfix.cpp b/Algorithms/Stack/infix_to_postfix.cpp new file mode 100644 index 0000000..01ebceb --- /dev/null +++ b/Algorithms/Stack/infix_to_postfix.cpp @@ -0,0 +1,84 @@ +//Infix to Postfix Converter +//Language Used: C++ +//Infix to Postfix Converter Algorithm uses Stack to convert given Infix expression to Postfix +//Input Format: Input contains only one line i.e., Infix Expression +//Output Format: Output contains only one line i.e., Postfix Expression +//Sample Input: 3*(7-9) +//Sample Output: 379-* +//author: adiXcodr + +#include +#include +#include +using namespace std; + + + string removeSpaces(string str) //Removes spaces from input + { + str.erase(remove(str.begin(), str.end(), ' '), str.end()); + return str; + } + + bool isOperator(char opr) + { + return (!isalpha(opr) && !isdigit(opr)); + } + + int getPriority(char opr) //Checks Priority of operators + { + if (opr == '-' || opr == '+') + return 1; + else if (opr == '*' || opr == '/') + return 2; + else if (opr == '^') + return 3; + return 0; + } + + string infixToPostfix(string infix) //Conversion + { + infix = '(' + infix + ')'; + int len = infix.size(); + stack char_stack; + string output; + + for (int inx = 0; inx < len; inx++) { + if (isalpha(infix[inx]) || isdigit(infix[inx])) + output += infix[inx]; + else if (infix[inx] == '(') + char_stack.push('('); + else if (infix[inx] == ')') { + while (char_stack.top() != '(') { + output += char_stack.top(); + char_stack.pop(); + } + char_stack.pop(); + } + else { + + if (isOperator(char_stack.top())) { + while (getPriority(infix[inx]) + <= getPriority(char_stack.top())) { + output += char_stack.top(); + char_stack.pop(); + } + char_stack.push(infix[inx]); + } + } + } + return output; + } + + + + int main() + { + string infix; + cout<<"Enter Infix expression here : "; + getline(cin,infix); + if(infix.size()>=1){ + infix=removeSpaces(infix); + cout<<"Postfix : "< +#include +#include +using namespace std; + + + string removeSpaces(string str) //Removes Spaces from input + { + str.erase(remove(str.begin(), str.end(), ' '), str.end()); + return str; + } + + bool isOperator(char opr) + { + return (!isalpha(opr) && !isdigit(opr)); + } + + int getPriority(char opr) //Checks Priority of operators + { + if (opr == '-' || opr == '+') + return 1; + else if (opr == '*' || opr == '/') + return 2; + else if (opr == '^') + return 3; + return 0; + } + + string infixToPrefix(string infix) //Converts Infix to Prefix +{ + // stack for operators. + stack operators; + + // stack for operands. + stack operands; + + for (int inx = 0; inx < infix.length(); inx++) { + + if (infix[inx] == '(') { + operators.push(infix[inx]); + } + + else if (infix[inx] == ')') { + while (!operators.empty() && + operators.top() != '(') { + + string op1 = operands.top(); + operands.pop(); + + string op2 = operands.top(); + operands.pop(); + + char op = operators.top(); + operators.pop(); + + string tmp = op + op2 + op1; + operands.push(tmp); + } + + operators.pop(); + } + + + else if (!isOperator(infix[inx])) { + operands.push(string(1, infix[inx])); + } + + + else { + while (!operators.empty() && + getPriority(infix[inx]) <= + getPriority(operators.top())) { + + string op1 = operands.top(); + operands.pop(); + + string op2 = operands.top(); + operands.pop(); + + char op = operators.top(); + operators.pop(); + + string tmp = op + op2 + op1; + operands.push(tmp); + } + + operators.push(infix[inx]); + } + } + + + while (!operators.empty()) { + string op1 = operands.top(); + operands.pop(); + + string op2 = operands.top(); + operands.pop(); + + char op = operators.top(); + operators.pop(); + + string tmp = op + op2 + op1; + operands.push(tmp); + } + + return operands.top(); + } + + + int main() + { + string infix; + cout<<"Enter Infix expression here : "; + getline(cin,infix); + if(infix.size()>=1){ + infix=removeSpaces(infix); + cout<<"Prefix : "< +using namespace std; +int top=-1,size=10; +int main() +{ + int A[10],a; + char ch='y'; + while(ch!='n'||ch!='N') + { + cout<<"1. Push "; + cout<<"\n2. Pop "; + cout<<"\n3. Display Last Element \nEnter Choice : "; + cin>>a; + if(a==1) + { + cout<<"Enter Element : "<>A[++top]; + } + else + { + cout<<"Stack FULL"<>ch; + } +} diff --git a/Algorithms/Strassen.cpp b/Algorithms/Strassen.cpp new file mode 100644 index 0000000..764cbbf --- /dev/null +++ b/Algorithms/Strassen.cpp @@ -0,0 +1,280 @@ +// CPP program to implement Strassen’s Matrix +// Multiplication Algorithm +#include +using namespace std; +typedef long long lld; + +/* Strassen's Algorithm for matrix multiplication +Complexity: O(n^2.808) */ + +inline lld** MatrixMultiply(lld** a, lld** b, int n, int l, int m) +{ + lld** c = new lld*[n]; + for (int i = 0; i < n; i++) + c[i] = new lld[m]; + + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + c[i][j] = 0; + for (int k = 0; k < l; k++) { + c[i][j] += a[i][k] * b[k][j]; + } + } + } + return c; +} + +inline lld** Strassen(lld** a, lld** b, int n, int l, int m) +{ + if (n == 1 || l == 1 || m == 1) + return MatrixMultiply(a, b, n, l, m); + + lld** c = new lld*[n]; + for (int i = 0; i < n; i++) + c[i] = new lld[m]; + + int adjN = (n >> 1) + (n & 1); + int adjL = (l >> 1) + (l & 1); + int adjM = (m >> 1) + (m & 1); + + lld**** As = new lld***[2]; + for (int x = 0; x < 2; x++) { + As[x] = new lld**[2]; + for (int y = 0; y < 2; y++) { + As[x][y] = new lld*[adjN]; + for (int i = 0; i < adjN; i++) { + As[x][y][i] = new lld[adjL]; + for (int j = 0; j < adjL; j++) { + int I = i + (x & 1) * adjN; + int J = j + (y & 1) * adjL; + As[x][y][i][j] = (I < n && J < l) ? a[I][J] : 0; + } + } + } + } + + lld**** Bs = new lld***[2]; + for (int x = 0; x < 2; x++) { + Bs[x] = new lld**[2]; + for (int y = 0; y < 2; y++) { + Bs[x][y] = new lld*[adjN]; + for (int i = 0; i < adjL; i++) { + Bs[x][y][i] = new lld[adjM]; + for (int j = 0; j < adjM; j++) { + int I = i + (x & 1) * adjL; + int J = j + (y & 1) * adjM; + Bs[x][y][i][j] = (I < l && J < m) ? b[I][J] : 0; + } + } + } + } + + lld*** s = new lld**[10]; + for (int i = 0; i < 10; i++) { + switch (i) { + case 0: + s[i] = new lld*[adjL]; + for (int j = 0; j < adjL; j++) { + s[i][j] = new lld[adjM]; + for (int k = 0; k < adjM; k++) { + s[i][j][k] = Bs[0][1][j][k] - Bs[1][1][j][k]; + } + } + break; + case 1: + s[i] = new lld*[adjN]; + for (int j = 0; j < adjN; j++) { + s[i][j] = new lld[adjL]; + for (int k = 0; k < adjL; k++) { + s[i][j][k] = As[0][0][j][k] + As[0][1][j][k]; + } + } + break; + case 2: + s[i] = new lld*[adjN]; + for (int j = 0; j < adjN; j++) { + s[i][j] = new lld[adjL]; + for (int k = 0; k < adjL; k++) { + s[i][j][k] = As[1][0][j][k] + As[1][1][j][k]; + } + } + break; + case 3: + s[i] = new lld*[adjL]; + for (int j = 0; j < adjL; j++) { + s[i][j] = new lld[adjM]; + for (int k = 0; k < adjM; k++) { + s[i][j][k] = Bs[1][0][j][k] - Bs[0][0][j][k]; + } + } + break; + case 4: + s[i] = new lld*[adjN]; + for (int j = 0; j < adjN; j++) { + s[i][j] = new lld[adjL]; + for (int k = 0; k < adjL; k++) { + s[i][j][k] = As[0][0][j][k] + As[1][1][j][k]; + } + } + break; + case 5: + s[i] = new lld*[adjL]; + for (int j = 0; j < adjL; j++) { + s[i][j] = new lld[adjM]; + for (int k = 0; k < adjM; k++) { + s[i][j][k] = Bs[0][0][j][k] + Bs[1][1][j][k]; + } + } + break; + case 6: + s[i] = new lld*[adjN]; + for (int j = 0; j < adjN; j++) { + s[i][j] = new lld[adjL]; + for (int k = 0; k < adjL; k++) { + s[i][j][k] = As[0][1][j][k] - As[1][1][j][k]; + } + } + break; + case 7: + s[i] = new lld*[adjL]; + for (int j = 0; j < adjL; j++) { + s[i][j] = new lld[adjM]; + for (int k = 0; k < adjM; k++) { + s[i][j][k] = Bs[1][0][j][k] + Bs[1][1][j][k]; + } + } + break; + case 8: + s[i] = new lld*[adjN]; + for (int j = 0; j < adjN; j++) { + s[i][j] = new lld[adjL]; + for (int k = 0; k < adjL; k++) { + s[i][j][k] = As[0][0][j][k] - As[1][0][j][k]; + } + } + break; + case 9: + s[i] = new lld*[adjL]; + for (int j = 0; j < adjL; j++) { + s[i][j] = new lld[adjM]; + for (int k = 0; k < adjM; k++) { + s[i][j][k] = Bs[0][0][j][k] + Bs[0][1][j][k]; + } + } + break; + } + } + + lld*** p = new lld**[7]; + p[0] = Strassen(As[0][0], s[0], adjN, adjL, adjM); + p[1] = Strassen(s[1], Bs[1][1], adjN, adjL, adjM); + p[2] = Strassen(s[2], Bs[0][0], adjN, adjL, adjM); + p[3] = Strassen(As[1][1], s[3], adjN, adjL, adjM); + p[4] = Strassen(s[4], s[5], adjN, adjL, adjM); + p[5] = Strassen(s[6], s[7], adjN, adjL, adjM); + p[6] = Strassen(s[8], s[9], adjN, adjL, adjM); + + for (int i = 0; i < adjN; i++) { + for (int j = 0; j < adjM; j++) { + c[i][j] = p[4][i][j] + p[3][i][j] - p[1][i][j] + p[5][i][j]; + if (j + adjM < m) + c[i][j + adjM] = p[0][i][j] + p[1][i][j]; + if (i + adjN < n) + c[i + adjN][j] = p[2][i][j] + p[3][i][j]; + if (i + adjN < n && j + adjM < m) + c[i + adjN][j + adjM] = p[4][i][j] + p[0][i][j] - p[2][i][j] - p[6][i][j]; + } + } + + for (int x = 0; x < 2; x++) { + for (int y = 0; y < 2; y++) { + for (int i = 0; i < adjN; i++) { + delete[] As[x][y][i]; + } + delete[] As[x][y]; + } + delete[] As[x]; + } + delete[] As; + + for (int x = 0; x < 2; x++) { + for (int y = 0; y < 2; y++) { + for (int i = 0; i < adjL; i++) { + delete[] Bs[x][y][i]; + } + delete[] Bs[x][y]; + } + delete[] Bs[x]; + } + delete[] Bs; + + for (int i = 0; i < 10; i++) { + switch (i) { + case 0: + case 3: + case 5: + case 7: + case 9: + for (int j = 0; j < adjL; j++) { + delete[] s[i][j]; + } + break; + case 1: + case 2: + case 4: + case 6: + case 8: + for (int j = 0; j < adjN; j++) { + delete[] s[i][j]; + } + break; + } + delete[] s[i]; + } + delete[] s; + + for (int i = 0; i < 7; i++) { + for (int j = 0; j < (n >> 1); j++) { + delete[] p[i][j]; + } + delete[] p[i]; + } + delete[] p; + + return c; +} + +int main() +{ + lld** matA; + matA = new lld*[2]; + for (int i = 0; i < 2; i++) + matA[i] = new lld[3]; + matA[0][0] = 1; + matA[0][1] = 2; + matA[0][2] = 3; + matA[1][0] = 4; + matA[1][1] = 5; + matA[1][2] = 6; + + lld** matB; + matB = new lld*[3]; + for (int i = 0; i < 3; i++) + matB[i] = new lld[2]; + matB[0][0] = 7; + matB[0][1] = 8; + matB[1][0] = 9; + matB[1][1] = 10; + matB[2][0] = 11; + matB[2][1] = 12; + + lld** matC = Strassen(matA, matB, 2, 3, 2); + for (int i = 0; i < 2; i++) { + for (int j = 0; j < 2; j++) { + printf("%lld ", matC[i][j]); + } + printf("\n"); + } + + return 0; +} diff --git a/Algorithms/String_Hashing/count_substr.cpp b/Algorithms/String_Hashing/count_substr.cpp new file mode 100644 index 0000000..3c55cd3 --- /dev/null +++ b/Algorithms/String_Hashing/count_substr.cpp @@ -0,0 +1,45 @@ +//Counting Substrings of String Algorithm +//Language Used: C++ +//Counting Different Substrings in a given string in N^2 time complexity. +//Input Format: First and only line of input contains input string +//Output Format: Output contains Count of substrings and different substrings +//Sample Input: abbaa +//Sample Output: Number of different substrings is 12 +// Different substrings are +// a aa ab abb abba abbaa b ba baa bb bba bbaa +//author:sarthakeddy + +#include +using namespace std; +#define ll long long + +void printsubstring(string s) +{ + set str; + ll n=s.length(); + + for(ll i=0;i>s; + printsubstring(s); + return 0; +} diff --git a/Algorithms/String_Hashing/manacher.cpp b/Algorithms/String_Hashing/manacher.cpp new file mode 100644 index 0000000..a21445f --- /dev/null +++ b/Algorithms/String_Hashing/manacher.cpp @@ -0,0 +1,65 @@ +//Manacher Algorithm +//Language Used: C++ +//Manacher algorithm to find longest palindromic substring in linear time complexity +//Input Format: First and only line of input contains input string +//Output Format: Output contains only one line i.e., longest palindromic substring +//Sample Input: malayamalayalamala +//Sample Output: malayalam +//author:sarthakeddy + +#include +using namespace std; +#define ll long long + +void find_longest_palindromic_substring(string s) +{ + ll n=s.length(); + n=2*n + 1; + ll len[n]; + len[0]=0; + len[1]=1; + ll center,right,i,left,max_length,max_center,start,end,diff; + center=1; + right=2; + max_center=max_length=0; + start=end=diff=-1; + + for(i=2;i 0) + len[i]=min(len[left] , diff); + + while((( i+len[i] < n ) && ( i-len[i] > 0 )) && ( ((i+len[i]+1)%2 == 0) || (s[(i+len[i]+1)/2] == s[(i-len[i]-1)/2]))) + len[i]++; + + if(len[i] > max_length) + { + max_length=len[i]; + max_center=i; + } + + if(i+len[i] > right) + { + center=i; + right=i+len[i]; + } + } + + start = (max_center - max_length)/2; + end=start+max_length-1; + for(i=start;i<=end;i++) + cout<>s; + find_longest_palindromic_substring(s); + return 0; +} \ No newline at end of file diff --git a/Algorithms/String_Hashing/rabin_karp.cpp b/Algorithms/String_Hashing/rabin_karp.cpp new file mode 100644 index 0000000..9cf15f9 --- /dev/null +++ b/Algorithms/String_Hashing/rabin_karp.cpp @@ -0,0 +1,62 @@ +//Rabin Karp Algorithm +//Language Used: C++ +//Rabin Karp algorithm to search for a pttern in a string in linear time complexity +//Input Format: First line contains text, second line contains pattern to be searched +//Output Format: Output contains only one line i.e., starting index of found string else not found +//Sample Input: abbababab +// abab +//Sample Output: Pattern found starting from 3 index +//author:sarthakeddy + +#include +using namespace std; +#define ll long long + +void search(string pattern, string text, ll prime) +{ + ll pat_len=pattern.length(); + ll text_len=text.length(); + ll hash_text=0, hash_pat=0, h=1; + ll i,j; + + for(i=0; i>text; + cout<<"Enter the pattern to be searched\n"; + cin>>pattern; + search(pattern,text,101); +} \ No newline at end of file diff --git a/Algorithms/String_Hashing/z-algorithm.cpp b/Algorithms/String_Hashing/z-algorithm.cpp new file mode 100644 index 0000000..e390e9d --- /dev/null +++ b/Algorithms/String_Hashing/z-algorithm.cpp @@ -0,0 +1,65 @@ +//Description: This is an algorithm to find a word in the input string. The word can be a part of another word. +//Example. "ring" word is found the sentence "String is a data type in C++." + +#include +#include +#include +using namespace std; +bool zAlgorithm(string pattern, string target) +{ + string s = pattern + '$' + target; + int n = s.length(); + vector z(n, 0); + int goal = pattern.length(); + int r = 0, l = 0, i; + for (int k = 1; k < n; k++) + { + if (k > r) + { + for (i = k; i < n && s[i] == s[i - k]; i++); + if (i > k) + { + z[k] = i - k; + l = k; + r = i - 1; + } + } + else + { + int kt = k - l, b = r - k + 1; + if (z[kt] > b) + { + for (i = r + 1; i < n && s[i] == s[i - k]; i++); + z[k] = i - k; + l = k; + r = i - 1; + } + } + if (z[k] == goal) + return true; + } + return false; +} + +int main() +{ + string tar; + string pat; + cin< + +int main() +{ + char msg[100],ch[5]; + int step=0; + int i,len=0; + std::cout<<"Enter encrypted message: "; + std::cin>>msg; + std::cout<<"Enter \"CLUE\": "; + std::cin>>ch; + step = (-1) * ((ch[0])-'C'); + len = strlen(msg); + std::cout<<"Decoded message is .....\n"; + for(i=0;i=0) //Right Shift + { + if((char(msg[i]+step) >= 'A') && (char(msg[i]+step) <='Z')) + std::cout<'Z') + std::cout<= 'A') && (char(msg[i]-step) <='Z')) + std::cout<'Z') + std::cout< +using namespace std; +int gcd(int i,int number) +{ + if(number==0) + return i; + return gcd(number,i%number); +} +int fun(int number) +{ + int result=0; + for(int i=1;i>number; + cout< +using namespace std; +void primeFactor(int number) +{ + while(number%2==0) + { + number=number/2; + cout<<"2"<<" "; + } + for(int i=3;i<=sqrt(number);i=i+2) + { + while(number%i==0) + { + cout<2) + cout<>number; + primeFactor(number); + return 0; +} diff --git a/Algorithms/mathematical_algorithm/GCD_by_Euclidean_algorithm.cpp b/Algorithms/mathematical_algorithm/GCD_by_Euclidean_algorithm.cpp new file mode 100644 index 0000000..507b49b --- /dev/null +++ b/Algorithms/mathematical_algorithm/GCD_by_Euclidean_algorithm.cpp @@ -0,0 +1,46 @@ +// GCD OR HCF of two numbers is the largest number that divides both of them + +//C++ program for calculating GCD BY EUCLIDEAN ALGORITHM +#include +using namespace std; +//First Method +//GCD of two number does not change if smaller number is subtracted from a bigger number +int Euclidean(int number1,int number2) +{ + if(number1==0) + return number2; + if(number2==0) + return number1; + //base case + if(number1==number2) + return number1; + //a is greater + if(number1>number2) + { + return Euclidean(number1-number2,number2); + } + else + return Euclidean(number1,number2-number1); +} +//Second Method +int Euclidean1(int number1,int number2) +{ + if(number2==0) + return number1; + return Euclidean1(number2,number1%number2); +} + +//Driver Code +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); cout.tie(NULL); + int number1,number2; + cout<<"Enter both number's:"<>number1>>number2; + //First Method + cout< +using namespace std; +int gcd(int number1,int number2) +{ + if(number2==0) + return number1; + return gcd(number2,number1%number2); +} +int LCM(int number1,int number2) +{ + return (number1*number2)/gcd(number1,number2); +} + +//Driver Code +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(); cout.tie(NULL); + int number1,number2; + cout<<"Enter the both number's:"<>number1>>number2; + cout<=3 +//Base cases: +//f(0)=0, f(1)=1, f(2)=1; + +//C++ program for MATRIX EXPONENTIATION +#include +using namespace std; + +//A utility function to multiply two matrices +//arr1[] and arr2[] . multiplication result is stored back in arr1[] +void multiply(int arr1[3][3],int arr2[3][3]) +{ + int mul[3][3]; + for(int i=0;i<3;i++) + { + for(int j=0;j<3;j++) + { + mul[i][j]=0; + for(int k=0;k<3;k++) + { + mul[i][j]+=arr1[i][k]*arr2[k][j]; + } + } + } + //storing the multiplication result in arr1[] + for(int i=0;i<3;i++) + for(int j=0;j<3;j++) + arr1[i][j]=mul[i][j]; +} + +// function to compute f raise to power number-2 +int power(int f[3][3],int number) +{ + int m[3][3]={{1,1,1},{1,0,0},{0,1,0}}; + // multiply with the initial value + if(number==1) + return f[0][0]+f[0][1]; + power(f,number/2); + multiply(f,f); + if(number%2!=0) + multiply(f,m); + + return f[0][0]+f[0][1]; +} +int findNth(int number) +{ + int f[3][3]={{1,1,1},{1,0,0},{0,1,0}}; + //base case + if(number==0) + return 0; + if(number==1||number==2) + return 1; + + return power(f,number-2); +} + +//Driver Code +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); cout.tie(NULL); + int number; + cout<<"Enter the number:"<>number; + cout<<"Value is: "< +using namespace std; +void pigeonholeSort(int *arr,int total_number) +{ + int minimum=arr[0], maximum=arr[0]; + for(int i=1;imaximum) + maximum=arr[i]; + } + int range = maximum-minimum+1; + vector holes[range]; + for(int i=0;i::iterator it; + for(it=holes[i].begin();it!=holes[i].end();++it) + { + arr[index++]=*it; + } + } +} + +// Driver Code +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); cout.tie(NULL); + int total_number; + cout<<"Enter the total number which are present in the array:"<>total_number; + int arr[total_number]; + cout<<"Enter the element in the array:"<>arr[i]; + pigeonholeSort(arr,total_number); + cout<<"Sorted Array is:"< +using namespace std; +void Sieve(int number) +{ + bool prime[number+1]; + memset(prime, true, sizeof(prime)); + for(int i=2; i*i<=number;i++) + { + //if prime[i] is not changed , then it is a prime + if(prime[i]==true) + { + for(int j=i*i; j<=number;j+=i) + { + prime[j]=false; + } + } + } + for(int p=2;p<=number;p++) + { + if(prime[p]) + cout<>number; + Sieve(number); + return 0; +} diff --git a/Algorithms/number_theory/large_factorial.c b/Algorithms/number_theory/large_factorial.c new file mode 100644 index 0000000..6d260b8 --- /dev/null +++ b/Algorithms/number_theory/large_factorial.c @@ -0,0 +1,68 @@ +#include + +int a[20000]; //this program can only compute factorials + //with 20,000 or less digits but the range +int main() //can be increased by changing 20,000 with +{ //a larger number less than 10,000,000 + int T,n,j,g,f; + scanf("%d",&T); //input no. of test cases + for(int i=0;i1;) + { + f++; + a[g+f]=a[g+f-1]/10; + a[g+f-1]=a[g+f-1]%10; + } + } + g+=f; + for(j=9;j<=n;j++) + { + for(int k=1;k<=g;k++) + { + a[k]=a[k]*j; + if(k-3>0) + { + a[k]+=a[k-3]/1000; + a[k-3]=a[k-3]%1000; + a[k-1]+=a[k-3]/100; + a[k-3]=a[k-3]%100; + a[k-2]+=a[k-3]/10; + a[k-3]=a[k-3]%10; + } + } + + a[g]+=a[g-2]/100; + a[g-2]=a[g-2]%100; + a[g-1]+=a[g-2]/10; + a[g-2]=a[g-2]%10; + + a[g]+=a[g-1]/10; + a[g-1]=a[g-1]%10; + + for(f=0;a[g+f]/10>=1;) + { + f++; + a[g+f]=a[g+f-1]/10; + a[g+f-1]=a[g+f-1]%10; + } + g=g+f; + } + + for(j=g;j>0;j--) printf("%d",a[j]); //printing the output + printf("\n"); //in the form of an array + } + return 0; +} diff --git a/Algorithms/search_algorithms/binary_search.cpp b/Algorithms/search_algorithms/binary_search.cpp new file mode 100644 index 0000000..1d3de9e --- /dev/null +++ b/Algorithms/search_algorithms/binary_search.cpp @@ -0,0 +1,43 @@ +// C++ program to implement recursive Binary Search +#include +using namespace std; + +// A recursive binary search function. It returns +// location of x in given array arr[l..r] is present, +// otherwise -1 +int binarySearch(int arr[], int l, int r, int x) +{ + if (r >= l) { + int mid = l + (r - l) / 2; + + // If the element is present at the middle + // itself + if (arr[mid] == x) + return mid; + + // If element is smaller than mid, then + // it can only be present in left subarray + if (arr[mid] > x) + return binarySearch(arr, l, mid - 1, x); + + // Else the element can only be present + // in right subarray + return binarySearch(arr, mid + 1, r, x); + } + + // We reach here when element is not + // present in array + return -1; +} + +int main() +{ + int arr[] = { 20, 30, 4, 10, 40 }; + int n = 5; + int x = 10; //Element to be searched... + int result = binarySearch(arr, 0, n - 1, x); + (result == -1) ? cout<<"Element is not present in array" + : cout<<"Element is present at index "< + +using namespace std; + +// a structure to represent a weighted edge in graph +struct Edge { + int src, dest, weight; +}; + +// a structure to represent a connected, directed and +// weighted graph +struct Graph { + // V-> Number of vertices, E-> Number of edges + int V, E; + + // graph is represented as an array of edges. + struct Edge* edge; +}; + +// Creates a graph with V vertices and E edges +struct Graph* createGraph(int V, int E) +{ + struct Graph* graph = new Graph; + graph->V = V; + graph->E = E; + graph->edge = new Edge[E]; + return graph; +} + +// A utility function used to print the solution +void printArr(int dist[], int n) +{ + printf("Vertex Distance from Source\n"); + for (int i = 0; i < n; ++i) + printf("%d \t\t %d\n", i, dist[i]); +} + +// The main function that finds shortest distances from src to +// all other vertices using Bellman-Ford algorithm. The function +// also detects negative weight cycle +void BellmanFord(struct Graph* graph, int src) +{ + int V = graph->V; + int E = graph->E; + int dist[V]; + + // Step 1: Initialize distances from src to all other vertices + // as INFINITE + for (int i = 0; i < V; i++) + dist[i] = INT_MAX; + dist[src] = 0; + + // Step 2: Relax all edges |V| - 1 times. A simple shortest + // path from src to any other vertex can have at-most |V| - 1 + // edges + for (int i = 1; i <= V - 1; i++) { + for (int j = 0; j < E; j++) { + int u = graph->edge[j].src; + int v = graph->edge[j].dest; + int weight = graph->edge[j].weight; + if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) + dist[v] = dist[u] + weight; + } + } + + // Step 3: check for negative-weight cycles. The above step + // guarantees shortest distances if graph doesn't contain + // negative weight cycle. If we get a shorter path, then there + // is a cycle. + for (int i = 0; i < E; i++) { + int u = graph->edge[i].src; + int v = graph->edge[i].dest; + int weight = graph->edge[i].weight; + if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) { + printf("Graph contains negative weight cycle"); + return; // If negative cycle is detected, simply return + } + } + + printArr(dist, V); + + return; +} + +// Driver program to test above functions +int main() +{ + int V ; // Number of vertices in graph + int E ; // Number of edges in graph + int s,d,w; + cout << "Enter the number of vertices and edges.\n"; + cin >> V >> E; + + struct Graph* graph = createGraph(V, E); + + for(int i=0;i> s >> d >> w; + graph->edge[i].src = s; + graph->edge[i].dest = d; + graph->edge[i].weight = w; + } + + BellmanFord(graph, 0); + + return 0; +} + +/* +SAMPLE INPUT : +Enter the number of vertices and edges. +5 8 +Enter the source vertex, destination vertex and the edge weight. +0 1 -1 +Enter the source vertex, destination vertex and the edge weight. +0 2 4 +Enter the source vertex, destination vertex and the edge weight. +1 2 3 +Enter the source vertex, destination vertex and the edge weight. +1 3 2 +Enter the source vertex, destination vertex and the edge weight. +1 4 2 +Enter the source vertex, destination vertex and the edge weight. +3 2 5 +Enter the source vertex, destination vertex and the edge weight. +3 1 1 +Enter the source vertex, destination vertex and the edge weight. +4 3 -3 + +SAMPLE OUTPUT : +Vertex Distance from Source +0 0 +1 -1 +2 2 +3 -2 +4 1 + +*/ diff --git a/EgyptianFractions.cpp b/EgyptianFractions.cpp new file mode 100644 index 0000000..9ab374c --- /dev/null +++ b/EgyptianFractions.cpp @@ -0,0 +1,52 @@ +/* Algorithm Name-EgyptianFractions*/ +/* Any fraction (numerator/denominator) can be expressed as a sum of positive distinct unit fractions. Unit fractions are fractions with numerator 1. +For example fraction 6/14 can be expressed as 1/3,1/11,1/231. +Procedure to find Egyptian Fraction is if numerator < denominator then first egyptian fraction is "1/quotient" where quotient is equal to Math.ceil(denominatoir/numerator). +The next the Egyptian Fraction will be founded by changing the original fraction (numerator/denominator) to numerator/denominator-1/quotient. +Sample Input +Enter numerator and denominator +6 +14 +Sample Output +1/3 +1/11 +1/231 +*/ + +#include + +using namespace std; + +int main() +{ int numerator,denominator,quotient; + cout<<"Enter numerator and denominator"; + cout<<"\n"; + cin>> numerator>>denominator; + while(numerator>denominator) + numerator=numerator%denominator; + while(denominator>numerator && numerator>0 && denominator>0) + { + if(numerator==1) + { + cout<<"1/"< + +using namespace std; + +int kadMax(int arr[], int size) +{ + int final_max = INT_MIN, current_max = 0; //INT_MIN = MOST NEGATIVE INTEGER + + for(int i = 0; i < size; i++) + { + //Iterate over Array adding each element to current max + current_max = current_max + arr[i]; + + //finalMax updated when less than currentMax + if(final_max < current_max) + final_max = current_max; + + //If currentMax becomes negative it is reassigned value 0 + if(current_max < 0) + current_max = 0; + } + + return final_max; +} + +int main() +{ + int len, ans; + + cout << "Enter length of Array : "; + + cin >> len; + + int ar[len]; + + cout<<"Enter elements of Array\n"; + + for(int i = 0; i < len; i++) //Array Input + cin >> ar[i]; + + ans = kadMax(ar, len); //Function calling + + cout< +[M Coloring Problem](https://github.com/SubhradeepSS/nwoc_algorithms/blob/master/Algorithms/Backtracking/M%20Coloring%20Problem.cpp)
+[N Queen Problem](https://github.com/SubhradeepSS/nwoc_algorithms/blob/master/Algorithms/Backtracking/N%20Queen%20Problem.cpp)
+[Rat in a Maze](https://github.com/SubhradeepSS/nwoc_algorithms/blob/master/Algorithms/Backtracking/Rat%20in%20a%20Maze.cpp)
+[Sudoku](https://github.com/SubhradeepSS/nwoc_algorithms/blob/master/Algorithms/Backtracking/Sudoku.cpp) + + +### Bellman Ford Algorithm +[Bellman Ford Algorithm](Bellman_Ford/BellmanFord.cpp) + +### Circular Queue +[Circular Queue](Algorithms/Circular_Queue/CircularQueue.cpp) + +### Graphs +[Breadth First Search](Algorithms/Graphs/breadth_first_search.cpp)
+[Depth First Search](Algorithms/Graphs/DFS_BFS_in_Graphs.cpp)
+[Detect Cycle in Undirected Graph](Algorithms/Graphs/Detect_Cycle_In_Undirected_Graph.cpp)
+[Dijkstra](Algorithms/Graphs/Dijkstra's%20Algorithm.cpp)
+[Kruskal](Algorithms/Graphs/Kruskal's%20Algorithm.cpp) + +### Greedy Algorithm +[Egyptian Fraction](EgyptianFractions.cpp) + +### Kadane Algorithm +[Kadane Algorithm](Kadane/kadane.cpp) + + +### Last Men Standing +[Last Men Standing](Algorithms/Last_Men_Standing) + +### Prims Algorithm +[Prims Algorithm](prims_algorithm.cpp) + +### Sample algorithm +[disjoint set union](Algorithms/disjoint_set_union.cpp)
+[Floyd cycle detection](Algorithms/Linked_List/Floyd_cycle_detection.cpp) + +### Searching Algorithms +[Binary Search](Algorithms/Searching/binarysearch.cpp)
+[Jump Search](Algorithms/Searching/jumpsearch.cpp)
+[Linear Search](Algorithms/Searching/Linear_Search.cpp) + +### Graph Algorithm +[breadth first search](Algorithms/Graphs/breadth_first_search.cpp)
+[Depth first Search](Algorithms/Graphs/Depth_first_search/depth_first_search.cpp) + + +### Sorting algorithm +[Bubble Sort](Algorithms/Sorting/bubble_sort.cpp)
+[Heap Sort](Algorithms/Sorting/heap_sort.cpp)
+[Insertion Sort](Algorithms/Sorting/insertion_sort.cpp)
+[Selection Sort](Algorithms/Sorting/selection_sort.cpp)
+[Shell Sort](Algorithms/Sorting/ShellSort.cpp) +[Merge Sort](Algorithms/Sorting/merge_sort.cpp)
+[Radix Sort](Algorithms/Sorting/radix%20sort.cpp)
+[Selection Sort](Algorithms/Sorting/selection_sort.cpp) + +### Stacks +[Implementation](Algorithms/Stacks/Stack%20in%20Array.cpp)
+[Infix to Postfix](Algorithms/Stack/InfixToPostfix.java)
+[Postfix](Algorithms/Stack/EvaluatePostfixExpression.txt) + +### Strings +[Substitution Cipher](https://github.com/NJACKWinterOfCode/nwoc_algorithms/tree/master/Algorithms/Substitution_Cipher) + + + +### String Hashing +[Count Substring](Algorithms/String_Hashing/count_substr.cpp)
+[Rabin Karp Algorithm](Algorithms/String_Hashing/rabin_karp.cpp)
+[Manacher Algorithm](Algorithms/String_Hashing/manacher.cpp)
+[Z Algorithm](Algorithms/String_Hashing/z-algorithm.cpp)
+ +### Tower Of Hanoi +[Tower of Hanoi](towerofhanoi.c) + diff --git a/depth_first_search.cpp b/depth_first_search.cpp new file mode 100644 index 0000000..7198b57 --- /dev/null +++ b/depth_first_search.cpp @@ -0,0 +1,50 @@ +#include +using namespace std; +void addEdge(vector adj[], int u, int v) +{ + adj[u].push_back(v); + adj[v].push_back(u); +} +void DFSUtil(int u, vector adj[], + vector &visited) +{ + visited[u] = true; + cout << u << " "; + for (int i=0; i adj[], int V) +{ + vector visited(V, false); + for (int u=0; u>V>>edge; + + vector *adj = new vector[V+1]; + + for(int i=0;i>x>>y; + addEdge(adj,x,y); + } + cout<<"The order of the depth first search traversal is "; + DFS(adj, V); + return 0; +} \ No newline at end of file diff --git a/instructions.md b/instructions.md index dd76113..4fa3ae8 100644 --- a/instructions.md +++ b/instructions.md @@ -23,13 +23,6 @@ All algorithms must be implemented in C++. 1. Make a folder for your algorithm. The folder name should be descriptive. Use underscores instead of spaces. 2. Put your program in that folder. Keep the program name as similar as possible to the folder name. -3. Add documentation for your program.Algorithms without a basic documentation (description, input/output format, sample input/output) will **not** be accepted. See [disjoint_set_union.cpp](Algorithms/disjoint_set_union/disjoint_set_union.cpp) for example. +3. Add documentation for your program.Algorithms without a basic documentation (description, input/output format, sample input/output) will **not** be accepted. See [README.md](https://github.com/NJACKWinterOfCode/nwoc_algorithms/tree/master/Algorithms/Substitution_Cipher) for correct example. 4. Update the List of Algorithms in [README](README.md) with your algorithm. 5. Commit and push the changes, then submit a Pull Request. - -### Implementing an algorithm in another language - -1. Put your algorithm in the corresponding algorithm folder. -2. Update the corresponding README. -3. Commit and push the changes, then submit a Pull Request. - diff --git a/prims_algorithm.cpp b/prims_algorithm.cpp new file mode 100644 index 0000000..2d32efe --- /dev/null +++ b/prims_algorithm.cpp @@ -0,0 +1,73 @@ + +/* Prim's Algorithm for finding Minimum Spanning Tree + +Sample Input is already given in main function: + + graph[V][V] = { { 0, 2, 0, 6, 0 }, + { 2, 0, 3, 8, 5 }, + { 0, 3, 0, 0, 7 }, + { 6, 8, 0, 0, 9 }, + { 0, 5, 7, 9, 0 } }; + +Sample Output: + +Edge Value +1 - 0 2 +2 - 1 3 +3 - 0 6 +4 - 1 5 +*/ +#include +using namespace std; + +//V is the number of vertices +#define V 5 + +//Function for finding MST using Prims Algorithm + +void primMST(int graph[V][V]) +{ + //parent is used to store the index position + //key is used to store the value + + int parent[V],key[V]; + + //All key values are initialized to maximum integer value + + for(int i=0;i +void TowerOfHanoi(int size, char c1, char c2, char c3) +{ + if(size==1) + { + printf("%d Disc transferred from %c to %c \n", size, c1, c3); + } + else{ + TowerOfHanoi(size-1,c1,c3,c2); + printf("%d Transfer Disc From %c TO %c\n",size,c1,c3); + TowerOfHanoi(size-1,c2,c1,c3); + } +} +void main() +{ + TowerOfHanoi(3,'s','m','d'); +}