formatting source-code for 153fb7b8a5

This commit is contained in:
github-actions
2020-05-30 04:02:09 +00:00
parent 92fe9495ec
commit 8a2de9842b
175 changed files with 1671 additions and 3460 deletions

View File

@@ -7,8 +7,7 @@ void printSolution(int color[]);
/* A utility function to check if the current color assignment /* A utility function to check if the current color assignment
is safe for vertex v */ is safe for vertex v */
bool isSafe(int v, bool graph[V][V], int color[], int c) bool isSafe(int v, bool graph[V][V], int color[], int c) {
{
for (int i = 0; i < V; i++) for (int i = 0; i < V; i++)
if (graph[v][i] && c == color[i]) if (graph[v][i] && c == color[i])
return false; return false;
@@ -16,22 +15,18 @@ bool isSafe(int v, bool graph[V][V], int color[], int c)
} }
/* A recursive utility function to solve m coloring problem */ /* A recursive utility function to solve m coloring problem */
void graphColoring(bool graph[V][V], int m, int color[], int v) void graphColoring(bool graph[V][V], int m, int color[], int v) {
{
/* base case: If all vertices are assigned a color then /* base case: If all vertices are assigned a color then
return true */ return true */
if (v == V) if (v == V) {
{
printSolution(color); printSolution(color);
return; return;
} }
/* Consider this vertex v and try different colors */ /* Consider this vertex v and try different colors */
for (int c = 1; c <= m; c++) for (int c = 1; c <= m; c++) {
{
/* Check if assignment of color c to v is fine*/ /* Check if assignment of color c to v is fine*/
if (isSafe(v, graph, color, c)) if (isSafe(v, graph, color, c)) {
{
color[v] = c; color[v] = c;
/* recur to assign colors to rest of the vertices */ /* recur to assign colors to rest of the vertices */
@@ -45,16 +40,14 @@ void graphColoring(bool graph[V][V], int m, int color[], int v)
} }
/* A utility function to print solution */ /* A utility function to print solution */
void printSolution(int color[]) void printSolution(int color[]) {
{
printf(" Following are the assigned colors \n"); printf(" Following are the assigned colors \n");
for (int i = 0; i < V; i++) printf(" %d ", color[i]); for (int i = 0; i < V; i++) printf(" %d ", color[i]);
printf("\n"); printf("\n");
} }
// driver program to test above function // driver program to test above function
int main() int main() {
{
/* Create following graph and test whether it is 3 colorable /* Create following graph and test whether it is 3 colorable
(3)---(2) (3)---(2)
| / | | / |

View File

@@ -9,8 +9,7 @@ using std::min;
using std::vector; using std::vector;
int minimax(int depth, int node_index, bool is_max, vector<int> scores, int minimax(int depth, int node_index, bool is_max, vector<int> scores,
int height) int height) {
{
if (depth == height) if (depth == height)
return scores[node_index]; return scores[node_index];
@@ -20,8 +19,7 @@ int minimax(int depth, int node_index, bool is_max, vector<int> scores,
return is_max ? max(v1, v2) : min(v1, v2); return is_max ? max(v1, v2) : min(v1, v2);
} }
int main() int main() {
{
vector<int> scores = {90, 23, 6, 33, 21, 65, 123, 34423}; vector<int> scores = {90, 23, 6, 33, 21, 65, 123, 34423};
int height = log2(scores.size()); int height = log2(scores.size());

View File

@@ -2,18 +2,15 @@
#define N 4 #define N 4
using namespace std; using namespace std;
void printSolution(int board[N][N]) void printSolution(int board[N][N]) {
{
cout << "\n"; cout << "\n";
for (int i = 0; i < N; i++) for (int i = 0; i < N; i++) {
{
for (int j = 0; j < N; j++) cout << "" << board[i][j]; for (int j = 0; j < N; j++) cout << "" << board[i][j];
cout << "\n"; cout << "\n";
} }
} }
bool isSafe(int board[N][N], int row, int col) bool isSafe(int board[N][N], int row, int col) {
{
int i, j; int i, j;
/* Check this row on left side */ /* Check this row on left side */
@@ -34,22 +31,18 @@ bool isSafe(int board[N][N], int row, int col)
return true; return true;
} }
void solveNQ(int board[N][N], int col) void solveNQ(int board[N][N], int col) {
{ if (col >= N) {
if (col >= N)
{
printSolution(board); printSolution(board);
return; return;
} }
/* Consider this column and try placing /* Consider this column and try placing
this queen in all rows one by one */ this queen in all rows one by one */
for (int i = 0; i < N; i++) for (int i = 0; i < N; i++) {
{
/* Check if queen can be placed on /* Check if queen can be placed on
board[i][col] */ board[i][col] */
if (isSafe(board, i, col)) if (isSafe(board, i, col)) {
{
/* Place this queen in board[i][col] */ /* Place this queen in board[i][col] */
// cout<<"\n"<<col<<"can place"<<i; // cout<<"\n"<<col<<"can place"<<i;
board[i][col] = 1; board[i][col] = 1;
@@ -62,8 +55,7 @@ void solveNQ(int board[N][N], int col)
} }
} }
int main() int main() {
{
int board[N][N] = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}; int board[N][N] = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}};
solveNQ(board, 0); solveNQ(board, 0);

View File

@@ -2,18 +2,14 @@
#define n 4 #define n 4
#define inc_loop(var, start, stop) for (int var = start; var <= stop; var++) #define inc_loop(var, start, stop) for (int var = start; var <= stop; var++)
#define dec_loop(var, start, stop) for (int var = start; var >= stop; var--) #define dec_loop(var, start, stop) for (int var = start; var >= stop; var--)
void PrintSol(int Board[n][n]) void PrintSol(int Board[n][n]) {
{ inc_loop(i, 0, n - 1) {
inc_loop(i, 0, n - 1)
{
inc_loop(j, 0, n - 1) std::cout << Board[i][j] << " "; inc_loop(j, 0, n - 1) std::cout << Board[i][j] << " ";
std::cout << std::endl; std::cout << std::endl;
} }
std::cout << std::endl; std::cout << std::endl;
if (n % 2 == 0 || (n % 2 == 1 && Board[n / 2 + 1][0] != 1)) if (n % 2 == 0 || (n % 2 == 1 && Board[n / 2 + 1][0] != 1)) {
{ inc_loop(i, 0, n - 1) {
inc_loop(i, 0, n - 1)
{
dec_loop(j, n - 1, 0) std::cout << Board[i][j] << " "; dec_loop(j, n - 1, 0) std::cout << Board[i][j] << " ";
std::cout << std::endl; std::cout << std::endl;
} }
@@ -21,40 +17,32 @@ void PrintSol(int Board[n][n])
} }
} }
bool CanIMove(int Board[n][n], int row, int col) bool CanIMove(int Board[n][n], int row, int col) {
{
/// check in the row /// check in the row
inc_loop(i, 0, col - 1) inc_loop(i, 0, col - 1) {
{
if (Board[row][i] == 1) if (Board[row][i] == 1)
return false; return false;
} }
/// check the first diagonal /// check the first diagonal
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
{
if (Board[i][j] == 1) if (Board[i][j] == 1)
return false; return false;
} }
/// check the second diagonal /// check the second diagonal
for (int i = row, j = col; i <= n - 1 && j >= 0; i++, j--) for (int i = row, j = col; i <= n - 1 && j >= 0; i++, j--) {
{
if (Board[i][j] == 1) if (Board[i][j] == 1)
return false; return false;
} }
return true; return true;
} }
void NQueenSol(int Board[n][n], int col) void NQueenSol(int Board[n][n], int col) {
{ if (col >= n) {
if (col >= n)
{
PrintSol(Board); PrintSol(Board);
return; return;
} }
inc_loop(i, 0, n - 1) inc_loop(i, 0, n - 1) {
{ if (CanIMove(Board, i, col)) {
if (CanIMove(Board, i, col))
{
Board[i][col] = 1; Board[i][col] = 1;
NQueenSol(Board, col + 1); NQueenSol(Board, col + 1);
Board[i][col] = 0; Board[i][col] = 0;
@@ -62,27 +50,19 @@ void NQueenSol(int Board[n][n], int col)
} }
} }
int main() int main() {
{
int Board[n][n] = {0}; int Board[n][n] = {0};
if (n % 2 == 0) if (n % 2 == 0) {
{ inc_loop(i, 0, n / 2 - 1) {
inc_loop(i, 0, n / 2 - 1) if (CanIMove(Board, i, 0)) {
{
if (CanIMove(Board, i, 0))
{
Board[i][0] = 1; Board[i][0] = 1;
NQueenSol(Board, 1); NQueenSol(Board, 1);
Board[i][0] = 0; Board[i][0] = 0;
} }
} }
} } else {
else inc_loop(i, 0, n / 2) {
{ if (CanIMove(Board, i, 0)) {
inc_loop(i, 0, n / 2)
{
if (CanIMove(Board, i, 0))
{
Board[i][0] = 1; Board[i][0] = 1;
NQueenSol(Board, 1); NQueenSol(Board, 1);
Board[i][0] = 0; Board[i][0] = 0;

View File

@@ -1,12 +1,9 @@
#include <iostream> #include <iostream>
#define n 4 #define n 4
void PrintSol(int Board[n][n]) void PrintSol(int Board[n][n]) {
{ for (int i = 0; i < n; i++) {
for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) {
{
for (int j = 0; j < n; j++)
{
std::cout << Board[i][j] << " "; std::cout << Board[i][j] << " ";
} }
std::cout << std::endl; std::cout << std::endl;
@@ -14,40 +11,32 @@ void PrintSol(int Board[n][n])
std::cout << std::endl; std::cout << std::endl;
} }
bool CanIMove(int Board[n][n], int row, int col) bool CanIMove(int Board[n][n], int row, int col) {
{
/// check in the row /// check in the row
for (int i = 0; i < col; i++) for (int i = 0; i < col; i++) {
{
if (Board[row][i] == 1) if (Board[row][i] == 1)
return false; return false;
} }
/// check the first diagonal /// check the first diagonal
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
{
if (Board[i][j] == 1) if (Board[i][j] == 1)
return false; return false;
} }
/// check the second diagonal /// check the second diagonal
for (int i = row, j = col; i <= n - 1 && j >= 0; i++, j--) for (int i = row, j = col; i <= n - 1 && j >= 0; i++, j--) {
{
if (Board[i][j] == 1) if (Board[i][j] == 1)
return false; return false;
} }
return true; return true;
} }
void NQueenSol(int Board[n][n], int col) void NQueenSol(int Board[n][n], int col) {
{ if (col >= n) {
if (col >= n)
{
PrintSol(Board); PrintSol(Board);
return; return;
} }
for (int i = 0; i < n; i++) for (int i = 0; i < n; i++) {
{ if (CanIMove(Board, i, col)) {
if (CanIMove(Board, i, col))
{
Board[i][col] = 1; Board[i][col] = 1;
NQueenSol(Board, col + 1); NQueenSol(Board, col + 1);
Board[i][col] = 0; Board[i][col] = 0;
@@ -55,8 +44,7 @@ void NQueenSol(int Board[n][n], int col)
} }
} }
int main() int main() {
{
int Board[n][n] = {0}; int Board[n][n] = {0};
NQueenSol(Board, 0); NQueenSol(Board, 0);
} }

View File

@@ -12,36 +12,28 @@
using namespace std; using namespace std;
int solveMaze(int currposrow, int currposcol, int maze[size][size], int solveMaze(int currposrow, int currposcol, int maze[size][size],
int soln[size][size]) int soln[size][size]) {
{ if ((currposrow == size - 1) && (currposcol == size - 1)) {
if ((currposrow == size - 1) && (currposcol == size - 1))
{
soln[currposrow][currposcol] = 1; soln[currposrow][currposcol] = 1;
for (int i = 0; i < size; ++i) for (int i = 0; i < size; ++i) {
{ for (int j = 0; j < size; ++j) {
for (int j = 0; j < size; ++j)
{
cout << soln[i][j]; cout << soln[i][j];
} }
cout << endl; cout << endl;
} }
return 1; return 1;
} } else {
else
{
soln[currposrow][currposcol] = 1; soln[currposrow][currposcol] = 1;
// if there exist a solution by moving one step ahead in a collumn // if there exist a solution by moving one step ahead in a collumn
if ((currposcol < size - 1) && maze[currposrow][currposcol + 1] == 1 && if ((currposcol < size - 1) && maze[currposrow][currposcol + 1] == 1 &&
solveMaze(currposrow, currposcol + 1, maze, soln)) solveMaze(currposrow, currposcol + 1, maze, soln)) {
{
return 1; return 1;
} }
// if there exists a solution by moving one step ahead in a row // if there exists a solution by moving one step ahead in a row
if ((currposrow < size - 1) && maze[currposrow + 1][currposcol] == 1 && if ((currposrow < size - 1) && maze[currposrow + 1][currposcol] == 1 &&
solveMaze(currposrow + 1, currposcol, maze, soln)) solveMaze(currposrow + 1, currposcol, maze, soln)) {
{
return 1; return 1;
} }
@@ -51,17 +43,14 @@ int solveMaze(int currposrow, int currposcol, int maze[size][size],
} }
} }
int main(int argc, char const *argv[]) int main(int argc, char const *argv[]) {
{
int maze[size][size] = { int maze[size][size] = {
{1, 0, 1, 0}, {1, 0, 1, 1}, {1, 0, 0, 1}, {1, 1, 1, 1}}; {1, 0, 1, 0}, {1, 0, 1, 1}, {1, 0, 0, 1}, {1, 1, 1, 1}};
int soln[size][size]; int soln[size][size];
for (int i = 0; i < size; ++i) for (int i = 0; i < size; ++i) {
{ for (int j = 0; j < size; ++j) {
for (int j = 0; j < size; ++j)
{
soln[i][j] = 0; soln[i][j] = 0;
} }
} }

View File

@@ -3,13 +3,10 @@ using namespace std;
/// N=9; /// N=9;
int n = 9; int n = 9;
bool isPossible(int mat[][9], int i, int j, int no) bool isPossible(int mat[][9], int i, int j, int no) {
{
/// Row or col nahin hona chahiye /// Row or col nahin hona chahiye
for (int x = 0; x < n; x++) for (int x = 0; x < n; x++) {
{ if (mat[x][j] == no || mat[i][x] == no) {
if (mat[x][j] == no || mat[i][x] == no)
{
return false; return false;
} }
} }
@@ -18,12 +15,9 @@ bool isPossible(int mat[][9], int i, int j, int no)
int sx = (i / 3) * 3; int sx = (i / 3) * 3;
int sy = (j / 3) * 3; int sy = (j / 3) * 3;
for (int x = sx; x < sx + 3; x++) for (int x = sx; x < sx + 3; x++) {
{ for (int y = sy; y < sy + 3; y++) {
for (int y = sy; y < sy + 3; y++) if (mat[x][y] == no) {
{
if (mat[x][y] == no)
{
return false; return false;
} }
} }
@@ -31,58 +25,46 @@ bool isPossible(int mat[][9], int i, int j, int no)
return true; return true;
} }
void printMat(int mat[][9]) void printMat(int mat[][9]) {
{ for (int i = 0; i < n; i++) {
for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) {
{
for (int j = 0; j < n; j++)
{
cout << mat[i][j] << " "; cout << mat[i][j] << " ";
if ((j + 1) % 3 == 0) if ((j + 1) % 3 == 0) {
{
cout << '\t'; cout << '\t';
} }
} }
if ((i + 1) % 3 == 0) if ((i + 1) % 3 == 0) {
{
cout << endl; cout << endl;
} }
cout << endl; cout << endl;
} }
} }
bool solveSudoku(int mat[][9], int i, int j) bool solveSudoku(int mat[][9], int i, int j) {
{
/// Base Case /// Base Case
if (i == 9) if (i == 9) {
{
/// Solve kr chuke hain for 9 rows already /// Solve kr chuke hain for 9 rows already
printMat(mat); printMat(mat);
return true; return true;
} }
/// Crossed the last Cell in the row /// Crossed the last Cell in the row
if (j == 9) if (j == 9) {
{
return solveSudoku(mat, i + 1, 0); return solveSudoku(mat, i + 1, 0);
} }
/// Blue Cell - Skip /// Blue Cell - Skip
if (mat[i][j] != 0) if (mat[i][j] != 0) {
{
return solveSudoku(mat, i, j + 1); return solveSudoku(mat, i, j + 1);
} }
/// White Cell /// White Cell
/// Try to place every possible no /// Try to place every possible no
for (int no = 1; no <= 9; no++) for (int no = 1; no <= 9; no++) {
{ if (isPossible(mat, i, j, no)) {
if (isPossible(mat, i, j, no))
{
/// Place the no - assuming solution aa jayega /// Place the no - assuming solution aa jayega
mat[i][j] = no; mat[i][j] = no;
bool aageKiSolveHui = solveSudoku(mat, i, j + 1); bool aageKiSolveHui = solveSudoku(mat, i, j + 1);
if (aageKiSolveHui) if (aageKiSolveHui) {
{
return true; return true;
} }
/// Nahin solve hui /// Nahin solve hui
@@ -94,8 +76,7 @@ bool solveSudoku(int mat[][9], int i, int j)
return false; return false;
} }
int main() int main() {
{
int mat[9][9] = {{5, 3, 0, 0, 7, 0, 0, 0, 0}, {6, 0, 0, 1, 9, 5, 0, 0, 0}, int mat[9][9] = {{5, 3, 0, 0, 7, 0, 0, 0, 0}, {6, 0, 0, 1, 9, 5, 0, 0, 0},
{0, 9, 8, 0, 0, 0, 0, 6, 0}, {8, 0, 0, 0, 6, 0, 0, 0, 3}, {0, 9, 8, 0, 0, 0, 0, 6, 0}, {8, 0, 0, 0, 6, 0, 0, 0, 3},
{4, 0, 0, 8, 0, 3, 0, 0, 1}, {7, 0, 0, 0, 2, 0, 0, 0, 6}, {4, 0, 0, 8, 0, 3, 0, 0, 1}, {7, 0, 0, 0, 2, 0, 0, 0, 6},

View File

@@ -23,36 +23,29 @@
/** define \f$f(x)\f$ to find root for /** define \f$f(x)\f$ to find root for
*/ */
static double eq(double i) static double eq(double i) {
{
return (std::pow(i, 3) - (4 * i) - 9); // original equation return (std::pow(i, 3) - (4 * i) - 9); // original equation
} }
/** get the sign of any given number */ /** get the sign of any given number */
template <typename T> template <typename T>
int sgn(T val) int sgn(T val) {
{
return (T(0) < val) - (val < T(0)); return (T(0) < val) - (val < T(0));
} }
/** main function */ /** main function */
int main() int main() {
{
double a = -1, b = 1, x, z; double a = -1, b = 1, x, z;
int i; int i;
// loop to find initial intervals a, b // loop to find initial intervals a, b
for (int i = 0; i < MAX_ITERATIONS; i++) for (int i = 0; i < MAX_ITERATIONS; i++) {
{
z = eq(a); z = eq(a);
x = eq(b); x = eq(b);
if (sgn(z) == sgn(x)) if (sgn(z) == sgn(x)) { // same signs, increase interval
{ // same signs, increase interval
b++; b++;
a--; a--;
} } else { // if opposite signs, we got our interval
else
{ // if opposite signs, we got our interval
break; break;
} }
} }
@@ -61,19 +54,15 @@ int main()
std::cout << "\nSecond initial: " << b; std::cout << "\nSecond initial: " << b;
// start iterations // start iterations
for (i = 0; i < MAX_ITERATIONS; i++) for (i = 0; i < MAX_ITERATIONS; i++) {
{
x = (a + b) / 2; x = (a + b) / 2;
z = eq(x); z = eq(x);
std::cout << "\n\nz: " << z << "\t[" << a << " , " << b std::cout << "\n\nz: " << z << "\t[" << a << " , " << b
<< " | Bisect: " << x << "]"; << " | Bisect: " << x << "]";
if (z < 0) if (z < 0) {
{
a = x; a = x;
} } else {
else
{
b = x; b = x;
} }

View File

@@ -25,36 +25,29 @@
/** define \f$f(x)\f$ to find root for /** define \f$f(x)\f$ to find root for
*/ */
static double eq(double i) static double eq(double i) {
{
return (std::pow(i, 3) - (4 * i) - 9); // origial equation return (std::pow(i, 3) - (4 * i) - 9); // origial equation
} }
/** get the sign of any given number */ /** get the sign of any given number */
template <typename T> template <typename T>
int sgn(T val) int sgn(T val) {
{
return (T(0) < val) - (val < T(0)); return (T(0) < val) - (val < T(0));
} }
/** main function */ /** main function */
int main() int main() {
{
double a = -1, b = 1, x, z, m, n, c; double a = -1, b = 1, x, z, m, n, c;
int i; int i;
// loop to find initial intervals a, b // loop to find initial intervals a, b
for (int i = 0; i < MAX_ITERATIONS; i++) for (int i = 0; i < MAX_ITERATIONS; i++) {
{
z = eq(a); z = eq(a);
x = eq(b); x = eq(b);
if (sgn(z) == sgn(x)) if (sgn(z) == sgn(x)) { // same signs, increase interval
{ // same signs, increase interval
b++; b++;
a--; a--;
} } else { // if opposite signs, we got our interval
else
{ // if opposite signs, we got our interval
break; break;
} }
} }
@@ -62,8 +55,7 @@ int main()
std::cout << "\nFirst initial: " << a; std::cout << "\nFirst initial: " << a;
std::cout << "\nSecond initial: " << b; std::cout << "\nSecond initial: " << b;
for (i = 0; i < MAX_ITERATIONS; i++) for (i = 0; i < MAX_ITERATIONS; i++) {
{
m = eq(a); m = eq(a);
n = eq(b); n = eq(b);
@@ -72,8 +64,7 @@ int main()
a = c; a = c;
z = eq(c); z = eq(c);
if (std::abs(z) < EPSILON) if (std::abs(z) < EPSILON) { // stoping criteria
{ // stoping criteria
break; break;
} }
} }

View File

@@ -6,8 +6,7 @@
#include <iostream> #include <iostream>
/** Main function */ /** Main function */
int main() int main() {
{
int mat_size, i, j, step; int mat_size, i, j, step;
std::cout << "Matrix size: "; std::cout << "Matrix size: ";
@@ -15,8 +14,7 @@ int main()
// create a 2D matrix by dynamic memory allocation // create a 2D matrix by dynamic memory allocation
double **mat = new double *[mat_size + 1], **x = new double *[mat_size]; double **mat = new double *[mat_size + 1], **x = new double *[mat_size];
for (i = 0; i <= mat_size; i++) for (i = 0; i <= mat_size; i++) {
{
mat[i] = new double[mat_size + 1]; mat[i] = new double[mat_size + 1];
if (i < mat_size) if (i < mat_size)
x[i] = new double[mat_size + 1]; x[i] = new double[mat_size + 1];
@@ -24,20 +22,16 @@ int main()
// get the matrix elements from user // get the matrix elements from user
std::cout << std::endl << "Enter value of the matrix: " << std::endl; std::cout << std::endl << "Enter value of the matrix: " << std::endl;
for (i = 0; i < mat_size; i++) for (i = 0; i < mat_size; i++) {
{ for (j = 0; j <= mat_size; j++) {
for (j = 0; j <= mat_size; j++)
{
std::cin >> std::cin >>
mat[i][j]; // Enter (mat_size*mat_size) value of the matrix. mat[i][j]; // Enter (mat_size*mat_size) value of the matrix.
} }
} }
// perform Gaussian elimination // perform Gaussian elimination
for (step = 0; step < mat_size - 1; step++) for (step = 0; step < mat_size - 1; step++) {
{ for (i = step; i < mat_size - 1; i++) {
for (i = step; i < mat_size - 1; i++)
{
double a = (mat[i + 1][step] / mat[step][step]); double a = (mat[i + 1][step] / mat[step][step]);
for (j = step; j <= mat_size; j++) for (j = step; j <= mat_size; j++)
@@ -47,10 +41,8 @@ int main()
std::cout << std::endl std::cout << std::endl
<< "Matrix using Gaussian Elimination method: " << std::endl; << "Matrix using Gaussian Elimination method: " << std::endl;
for (i = 0; i < mat_size; i++) for (i = 0; i < mat_size; i++) {
{ for (j = 0; j <= mat_size; j++) {
for (j = 0; j <= mat_size; j++)
{
x[i][j] = mat[i][j]; x[i][j] = mat[i][j];
std::cout << mat[i][j] << " "; std::cout << mat[i][j] << " ";
} }
@@ -58,11 +50,9 @@ int main()
} }
std::cout << std::endl std::cout << std::endl
<< "Value of the Gaussian Elimination method: " << std::endl; << "Value of the Gaussian Elimination method: " << std::endl;
for (i = mat_size - 1; i >= 0; i--) for (i = mat_size - 1; i >= 0; i--) {
{
double sum = 0; double sum = 0;
for (j = mat_size - 1; j > i; j--) for (j = mat_size - 1; j > i; j--) {
{
x[i][j] = x[j][j] * x[i][j]; x[i][j] = x[j][j] * x[i][j];
sum = x[i][j] + sum; sum = x[i][j] + sum;
} }
@@ -74,8 +64,7 @@ int main()
std::cout << "x" << i << "= " << x[i][i] << std::endl; std::cout << "x" << i << "= " << x[i][i] << std::endl;
} }
for (i = 0; i <= mat_size; i++) for (i = 0; i <= mat_size; i++) {
{
delete[] mat[i]; delete[] mat[i];
if (i < mat_size) if (i < mat_size)
delete[] x[i]; delete[] x[i];

View File

@@ -21,21 +21,18 @@
/** define \f$f(x)\f$ to find root for /** define \f$f(x)\f$ to find root for
*/ */
static double eq(double i) static double eq(double i) {
{
return (std::pow(i, 3) - (4 * i) - 9); // original equation return (std::pow(i, 3) - (4 * i) - 9); // original equation
} }
/** define the derivative function \f$f'(x)\f$ /** define the derivative function \f$f'(x)\f$
*/ */
static double eq_der(double i) static double eq_der(double i) {
{
return ((3 * std::pow(i, 2)) - 4); // derivative of equation return ((3 * std::pow(i, 2)) - 4); // derivative of equation
} }
/** Main function */ /** Main function */
int main() int main() {
{
std::srand(std::time(nullptr)); // initialize randomizer std::srand(std::time(nullptr)); // initialize randomizer
double z, c = std::rand() % 100, m, n; double z, c = std::rand() % 100, m, n;
@@ -44,8 +41,7 @@ int main()
std::cout << "\nInitial approximation: " << c; std::cout << "\nInitial approximation: " << c;
// start iterations // start iterations
for (i = 0; i < MAX_ITERATIONS; i++) for (i = 0; i < MAX_ITERATIONS; i++) {
{
m = eq(c); m = eq(c);
n = eq_der(c); n = eq_der(c);

View File

@@ -16,13 +16,11 @@
*/ */
template <typename T> template <typename T>
std::ostream &operator<<(std::ostream &out, std::ostream &operator<<(std::ostream &out,
std::vector<std::vector<T>> const &v) std::vector<std::vector<T>> const &v) {
{
const int width = 10; const int width = 10;
const char separator = ' '; const char separator = ' ';
for (size_t row = 0; row < v.size(); row++) for (size_t row = 0; row < v.size(); row++) {
{
for (size_t col = 0; col < v[row].size(); col++) for (size_t col = 0; col < v[row].size(); col++)
out << std::left << std::setw(width) << std::setfill(separator) out << std::left << std::setw(width) << std::setfill(separator)
<< v[row][col]; << v[row][col];
@@ -36,8 +34,7 @@ std::ostream &operator<<(std::ostream &out,
* operator to print a vector * operator to print a vector
*/ */
template <typename T> template <typename T>
std::ostream &operator<<(std::ostream &out, std::vector<T> const &v) std::ostream &operator<<(std::ostream &out, std::vector<T> const &v) {
{
const int width = 15; const int width = 15;
const char separator = ' '; const char separator = ' ';
@@ -53,8 +50,7 @@ std::ostream &operator<<(std::ostream &out, std::vector<T> const &v)
* \returns 1 if true, 0 if false * \returns 1 if true, 0 if false
*/ */
template <typename T> template <typename T>
inline bool is_square(std::vector<std::vector<T>> const &A) inline bool is_square(std::vector<std::vector<T>> const &A) {
{
// Assuming A is square matrix // Assuming A is square matrix
size_t N = A.size(); size_t N = A.size();
for (size_t i = 0; i < N; i++) for (size_t i = 0; i < N; i++)
@@ -72,8 +68,7 @@ inline bool is_square(std::vector<std::vector<T>> const &A)
**/ **/
template <typename T> template <typename T>
std::vector<std::vector<T>> operator*(std::vector<std::vector<T>> const &A, std::vector<std::vector<T>> operator*(std::vector<std::vector<T>> const &A,
std::vector<std::vector<T>> const &B) std::vector<std::vector<T>> const &B) {
{
// Number of rows in A // Number of rows in A
size_t N_A = A.size(); size_t N_A = A.size();
// Number of columns in B // Number of columns in B
@@ -81,18 +76,15 @@ std::vector<std::vector<T>> operator*(std::vector<std::vector<T>> const &A,
std::vector<std::vector<T>> result(N_A); std::vector<std::vector<T>> result(N_A);
if (A[0].size() != B.size()) if (A[0].size() != B.size()) {
{
std::cerr << "Number of columns in A != Number of rows in B (" std::cerr << "Number of columns in A != Number of rows in B ("
<< A[0].size() << ", " << B.size() << ")" << std::endl; << A[0].size() << ", " << B.size() << ")" << std::endl;
return result; return result;
} }
for (size_t row = 0; row < N_A; row++) for (size_t row = 0; row < N_A; row++) {
{
std::vector<T> v(N_B); std::vector<T> v(N_B);
for (size_t col = 0; col < N_B; col++) for (size_t col = 0; col < N_B; col++) {
{
v[col] = static_cast<T>(0); v[col] = static_cast<T>(0);
for (size_t j = 0; j < B.size(); j++) for (size_t j = 0; j < B.size(); j++)
v[col] += A[row][j] * B[j][col]; v[col] += A[row][j] * B[j][col];
@@ -109,22 +101,19 @@ std::vector<std::vector<T>> operator*(std::vector<std::vector<T>> const &A,
*/ */
template <typename T> template <typename T>
std::vector<T> operator*(std::vector<std::vector<T>> const &A, std::vector<T> operator*(std::vector<std::vector<T>> const &A,
std::vector<T> const &B) std::vector<T> const &B) {
{
// Number of rows in A // Number of rows in A
size_t N_A = A.size(); size_t N_A = A.size();
std::vector<T> result(N_A); std::vector<T> result(N_A);
if (A[0].size() != B.size()) if (A[0].size() != B.size()) {
{
std::cerr << "Number of columns in A != Number of rows in B (" std::cerr << "Number of columns in A != Number of rows in B ("
<< A[0].size() << ", " << B.size() << ")" << std::endl; << A[0].size() << ", " << B.size() << ")" << std::endl;
return result; return result;
} }
for (size_t row = 0; row < N_A; row++) for (size_t row = 0; row < N_A; row++) {
{
result[row] = static_cast<T>(0); result[row] = static_cast<T>(0);
for (size_t j = 0; j < B.size(); j++) result[row] += A[row][j] * B[j]; for (size_t j = 0; j < B.size(); j++) result[row] += A[row][j] * B[j];
} }
@@ -137,15 +126,13 @@ std::vector<T> operator*(std::vector<std::vector<T>> const &A,
* \returns resultant vector * \returns resultant vector
*/ */
template <typename T> template <typename T>
std::vector<float> operator*(float const scalar, std::vector<T> const &A) std::vector<float> operator*(float const scalar, std::vector<T> const &A) {
{
// Number of rows in A // Number of rows in A
size_t N_A = A.size(); size_t N_A = A.size();
std::vector<float> result(N_A); std::vector<float> result(N_A);
for (size_t row = 0; row < N_A; row++) for (size_t row = 0; row < N_A; row++) {
{
result[row] += A[row] * static_cast<float>(scalar); result[row] += A[row] * static_cast<float>(scalar);
} }
@@ -157,8 +144,7 @@ std::vector<float> operator*(float const scalar, std::vector<T> const &A)
* \returns resultant vector * \returns resultant vector
*/ */
template <typename T> template <typename T>
std::vector<float> operator*(std::vector<T> const &A, float const scalar) std::vector<float> operator*(std::vector<T> const &A, float const scalar) {
{
// Number of rows in A // Number of rows in A
size_t N_A = A.size(); size_t N_A = A.size();
@@ -175,8 +161,7 @@ std::vector<float> operator*(std::vector<T> const &A, float const scalar)
* \returns resultant vector * \returns resultant vector
*/ */
template <typename T> template <typename T>
std::vector<float> operator/(std::vector<T> const &A, float const scalar) std::vector<float> operator/(std::vector<T> const &A, float const scalar) {
{
return (1.f / scalar) * A; return (1.f / scalar) * A;
} }
@@ -185,15 +170,13 @@ std::vector<float> operator/(std::vector<T> const &A, float const scalar)
* \returns resultant vector * \returns resultant vector
*/ */
template <typename T> template <typename T>
std::vector<T> operator-(std::vector<T> const &A, std::vector<T> const &B) std::vector<T> operator-(std::vector<T> const &A, std::vector<T> const &B) {
{
// Number of rows in A // Number of rows in A
size_t N = A.size(); size_t N = A.size();
std::vector<T> result(N); std::vector<T> result(N);
if (B.size() != N) if (B.size() != N) {
{
std::cerr << "Vector dimensions shouldbe identical!" << std::endl; std::cerr << "Vector dimensions shouldbe identical!" << std::endl;
return A; return A;
} }
@@ -208,15 +191,13 @@ std::vector<T> operator-(std::vector<T> const &A, std::vector<T> const &B)
* \returns resultant vector * \returns resultant vector
*/ */
template <typename T> template <typename T>
std::vector<T> operator+(std::vector<T> const &A, std::vector<T> const &B) std::vector<T> operator+(std::vector<T> const &A, std::vector<T> const &B) {
{
// Number of rows in A // Number of rows in A
size_t N = A.size(); size_t N = A.size();
std::vector<T> result(N); std::vector<T> result(N);
if (B.size() != N) if (B.size() != N) {
{
std::cerr << "Vector dimensions shouldbe identical!" << std::endl; std::cerr << "Vector dimensions shouldbe identical!" << std::endl;
return A; return A;
} }
@@ -233,30 +214,26 @@ std::vector<T> operator+(std::vector<T> const &A, std::vector<T> const &B)
**/ **/
template <typename T> template <typename T>
std::vector<std::vector<float>> get_inverse( std::vector<std::vector<float>> get_inverse(
std::vector<std::vector<T>> const &A) std::vector<std::vector<T>> const &A) {
{
// Assuming A is square matrix // Assuming A is square matrix
size_t N = A.size(); size_t N = A.size();
std::vector<std::vector<float>> inverse(N); std::vector<std::vector<float>> inverse(N);
for (size_t row = 0; row < N; row++) for (size_t row = 0; row < N; row++) {
{
// preallocatae a resultant identity matrix // preallocatae a resultant identity matrix
inverse[row] = std::vector<float>(N); inverse[row] = std::vector<float>(N);
for (size_t col = 0; col < N; col++) for (size_t col = 0; col < N; col++)
inverse[row][col] = (row == col) ? 1.f : 0.f; inverse[row][col] = (row == col) ? 1.f : 0.f;
} }
if (!is_square(A)) if (!is_square(A)) {
{
std::cerr << "A must be a square matrix!" << std::endl; std::cerr << "A must be a square matrix!" << std::endl;
return inverse; return inverse;
} }
// preallocatae a temporary matrix identical to A // preallocatae a temporary matrix identical to A
std::vector<std::vector<float>> temp(N); std::vector<std::vector<float>> temp(N);
for (size_t row = 0; row < N; row++) for (size_t row = 0; row < N; row++) {
{
std::vector<float> v(N); std::vector<float> v(N);
for (size_t col = 0; col < N; col++) for (size_t col = 0; col < N; col++)
v[col] = static_cast<float>(A[row][col]); v[col] = static_cast<float>(A[row][col]);
@@ -264,27 +241,22 @@ std::vector<std::vector<float>> get_inverse(
} }
// start transformations // start transformations
for (size_t row = 0; row < N; row++) for (size_t row = 0; row < N; row++) {
{ for (size_t row2 = row; row2 < N && temp[row][row] == 0; row2++) {
for (size_t row2 = row; row2 < N && temp[row][row] == 0; row2++)
{
// this to ensure diagonal elements are not 0 // this to ensure diagonal elements are not 0
temp[row] = temp[row] + temp[row2]; temp[row] = temp[row] + temp[row2];
inverse[row] = inverse[row] + inverse[row2]; inverse[row] = inverse[row] + inverse[row2];
} }
for (size_t col2 = row; col2 < N && temp[row][row] == 0; col2++) for (size_t col2 = row; col2 < N && temp[row][row] == 0; col2++) {
{
// this to further ensure diagonal elements are not 0 // this to further ensure diagonal elements are not 0
for (size_t row2 = 0; row2 < N; row2++) for (size_t row2 = 0; row2 < N; row2++) {
{
temp[row2][row] = temp[row2][row] + temp[row2][col2]; temp[row2][row] = temp[row2][row] + temp[row2][col2];
inverse[row2][row] = inverse[row2][row] + inverse[row2][col2]; inverse[row2][row] = inverse[row2][row] + inverse[row2][col2];
} }
} }
if (temp[row][row] == 0) if (temp[row][row] == 0) {
{
// Probably a low-rank matrix and hence singular // Probably a low-rank matrix and hence singular
std::cerr << "Low-rank matrix, no inverse!" << std::endl; std::cerr << "Low-rank matrix, no inverse!" << std::endl;
return inverse; return inverse;
@@ -295,8 +267,7 @@ std::vector<std::vector<float>> get_inverse(
temp[row] = temp[row] / divisor; temp[row] = temp[row] / divisor;
inverse[row] = inverse[row] / divisor; inverse[row] = inverse[row] / divisor;
// Row transformations // Row transformations
for (size_t row2 = 0; row2 < N; row2++) for (size_t row2 = 0; row2 < N; row2++) {
{
if (row2 == row) if (row2 == row)
continue; continue;
float factor = temp[row2][row]; float factor = temp[row2][row];
@@ -313,12 +284,11 @@ std::vector<std::vector<float>> get_inverse(
* \returns resultant matrix * \returns resultant matrix
**/ **/
template <typename T> template <typename T>
std::vector<std::vector<T>> get_transpose(std::vector<std::vector<T>> const &A) std::vector<std::vector<T>> get_transpose(
{ std::vector<std::vector<T>> const &A) {
std::vector<std::vector<T>> result(A[0].size()); std::vector<std::vector<T>> result(A[0].size());
for (size_t row = 0; row < A[0].size(); row++) for (size_t row = 0; row < A[0].size(); row++) {
{
std::vector<T> v(A.size()); std::vector<T> v(A.size());
for (size_t col = 0; col < A.size(); col++) v[col] = A[col][row]; for (size_t col = 0; col < A.size(); col++) v[col] = A[col][row];
@@ -336,8 +306,7 @@ std::vector<std::vector<T>> get_transpose(std::vector<std::vector<T>> const &A)
*/ */
template <typename T> template <typename T>
std::vector<float> fit_OLS_regressor(std::vector<std::vector<T>> const &X, std::vector<float> fit_OLS_regressor(std::vector<std::vector<T>> const &X,
std::vector<T> const &Y) std::vector<T> const &Y) {
{
// NxF // NxF
std::vector<std::vector<T>> X2 = X; std::vector<std::vector<T>> X2 = X;
for (size_t i = 0; i < X2.size(); i++) for (size_t i = 0; i < X2.size(); i++)
@@ -368,12 +337,10 @@ std::vector<float> fit_OLS_regressor(std::vector<std::vector<T>> const &X,
template <typename T> template <typename T>
std::vector<float> predict_OLS_regressor(std::vector<std::vector<T>> const &X, std::vector<float> predict_OLS_regressor(std::vector<std::vector<T>> const &X,
std::vector<float> const &beta /**< */ std::vector<float> const &beta /**< */
) ) {
{
std::vector<float> result(X.size()); std::vector<float> result(X.size());
for (size_t rows = 0; rows < X.size(); rows++) for (size_t rows = 0; rows < X.size(); rows++) {
{
// -> start with constant term // -> start with constant term
result[rows] = beta[X[0].size()]; result[rows] = beta[X[0].size()];
for (size_t cols = 0; cols < X[0].size(); cols++) for (size_t cols = 0; cols < X[0].size(); cols++)
@@ -386,8 +353,7 @@ std::vector<float> predict_OLS_regressor(std::vector<std::vector<T>> const &X,
/** /**
* main function * main function
*/ */
int main() int main() {
{
size_t N, F; size_t N, F;
std::cout << "Enter number of features: "; std::cout << "Enter number of features: ";
@@ -404,8 +370,7 @@ int main()
<< "Enter training data. Per sample, provide features ad one output." << "Enter training data. Per sample, provide features ad one output."
<< std::endl; << std::endl;
for (size_t rows = 0; rows < N; rows++) for (size_t rows = 0; rows < N; rows++) {
{
std::vector<float> v(F); std::vector<float> v(F);
std::cout << "Sample# " << rows + 1 << ": "; std::cout << "Sample# " << rows + 1 << ": ";
for (size_t cols = 0; cols < F; cols++) for (size_t cols = 0; cols < F; cols++)
@@ -426,8 +391,7 @@ int main()
std::vector<std::vector<float>> data2(T); std::vector<std::vector<float>> data2(T);
// vector<float> Y2(T); // vector<float> Y2(T);
for (size_t rows = 0; rows < T; rows++) for (size_t rows = 0; rows < T; rows++) {
{
std::cout << "Sample# " << rows + 1 << ": "; std::cout << "Sample# " << rows + 1 << ": ";
std::vector<float> v(F); std::vector<float> v(F);
for (size_t cols = 0; cols < F; cols++) std::cin >> v[cols]; for (size_t cols = 0; cols < F; cols++) std::cin >> v[cols];

View File

@@ -17,13 +17,11 @@ static float eq(float y) { return (3 * y) - cos(y) - 2; }
static float eqd(float y) { return 0.5 * (cos(y) + 2); } static float eqd(float y) { return 0.5 * (cos(y) + 2); }
/** Main function */ /** Main function */
int main() int main() {
{
float y, x1, x2, x3, sum, s, a, f1, f2, gd; float y, x1, x2, x3, sum, s, a, f1, f2, gd;
int i, n; int i, n;
for (i = 0; i < 10; i++) for (i = 0; i < 10; i++) {
{
sum = eq(y); sum = eq(y);
std::cout << "value of equation at " << i << " " << sum << "\n"; std::cout << "value of equation at " << i << " " << sum << "\n";
y++; y++;
@@ -33,8 +31,7 @@ int main()
std::cout << "enter the no iteration to perform->\n"; std::cout << "enter the no iteration to perform->\n";
std::cin >> n; std::cin >> n;
for (i = 0; i <= n; i++) for (i = 0; i <= n; i++) {
{
x2 = eqd(x1); x2 = eqd(x1);
std::cout << "\nenter the x2->" << x2; std::cout << "\nenter the x2->" << x2;
x1 = x2; x1 = x2;

View File

@@ -3,8 +3,7 @@
using namespace std; using namespace std;
typedef struct node typedef struct node {
{
int data; int data;
int height; int height;
struct node *left; struct node *left;
@@ -15,8 +14,7 @@ int max(int a, int b) { return a > b ? a : b; }
// Returns a new Node // Returns a new Node
node *createNode(int data) node *createNode(int data) {
{
node *nn = new node(); node *nn = new node();
nn->data = data; nn->data = data;
nn->height = 0; nn->height = 0;
@@ -27,8 +25,7 @@ node *createNode(int data)
// Returns height of tree // Returns height of tree
int height(node *root) int height(node *root) {
{
if (root == NULL) if (root == NULL)
return 0; return 0;
return 1 + max(height(root->left), height(root->right)); return 1 + max(height(root->left), height(root->right));
@@ -40,8 +37,7 @@ int getBalance(node *root) { return height(root->left) - height(root->right); }
// Returns Node after Right Rotation // Returns Node after Right Rotation
node *rightRotate(node *root) node *rightRotate(node *root) {
{
node *t = root->left; node *t = root->left;
node *u = t->right; node *u = t->right;
t->right = root; t->right = root;
@@ -51,8 +47,7 @@ node *rightRotate(node *root)
// Returns Node after Left Rotation // Returns Node after Left Rotation
node *leftRotate(node *root) node *leftRotate(node *root) {
{
node *t = root->right; node *t = root->right;
node *u = t->left; node *u = t->left;
t->left = root; t->left = root;
@@ -62,8 +57,7 @@ node *leftRotate(node *root)
// Returns node with minimum value in the tree // Returns node with minimum value in the tree
node *minValue(node *root) node *minValue(node *root) {
{
if (root->left == NULL) if (root->left == NULL)
return root; return root;
return minValue(root->left); return minValue(root->left);
@@ -71,8 +65,7 @@ node *minValue(node *root)
// Balanced Insertion // Balanced Insertion
node *insert(node *root, int item) node *insert(node *root, int item) {
{
node *nn = createNode(item); node *nn = createNode(item);
if (root == NULL) if (root == NULL)
return nn; return nn;
@@ -81,14 +74,11 @@ node *insert(node *root, int item)
else else
root->right = insert(root->right, item); root->right = insert(root->right, item);
int b = getBalance(root); int b = getBalance(root);
if (b > 1) if (b > 1) {
{
if (getBalance(root->left) < 0) if (getBalance(root->left) < 0)
root->left = leftRotate(root->left); // Left-Right Case root->left = leftRotate(root->left); // Left-Right Case
return rightRotate(root); // Left-Left Case return rightRotate(root); // Left-Left Case
} } else if (b < -1) {
else if (b < -1)
{
if (getBalance(root->right) > 0) if (getBalance(root->right) > 0)
root->right = rightRotate(root->right); // Right-Left Case root->right = rightRotate(root->right); // Right-Left Case
return leftRotate(root); // Right-Right Case return leftRotate(root); // Right-Right Case
@@ -98,8 +88,7 @@ node *insert(node *root, int item)
// Balanced Deletion // Balanced Deletion
node *deleteNode(node *root, int key) node *deleteNode(node *root, int key) {
{
if (root == NULL) if (root == NULL)
return root; return root;
if (key < root->data) if (key < root->data)
@@ -107,18 +96,14 @@ node *deleteNode(node *root, int key)
else if (key > root->data) else if (key > root->data)
root->right = deleteNode(root->right, key); root->right = deleteNode(root->right, key);
else else {
{
// Node to be deleted is leaf node or have only one Child // Node to be deleted is leaf node or have only one Child
if (!root->right) if (!root->right) {
{
node *temp = root->left; node *temp = root->left;
delete (root); delete (root);
root = NULL; root = NULL;
return temp; return temp;
} } else if (!root->left) {
else if (!root->left)
{
node *temp = root->right; node *temp = root->right;
delete (root); delete (root);
root = NULL; root = NULL;
@@ -135,12 +120,10 @@ node *deleteNode(node *root, int key)
// LevelOrder (Breadth First Search) // LevelOrder (Breadth First Search)
void levelOrder(node *root) void levelOrder(node *root) {
{
queue<node *> q; queue<node *> q;
q.push(root); q.push(root);
while (!q.empty()) while (!q.empty()) {
{
root = q.front(); root = q.front();
cout << root->data << " "; cout << root->data << " ";
q.pop(); q.pop();
@@ -151,8 +134,7 @@ void levelOrder(node *root)
} }
} }
int main() int main() {
{
// Testing AVL Tree // Testing AVL Tree
node *root = NULL; node *root = NULL;
int i; int i;

View File

@@ -1,15 +1,13 @@
#include <iostream> #include <iostream>
using namespace std; using namespace std;
struct node struct node {
{
int val; int val;
node *left; node *left;
node *right; node *right;
}; };
struct queue struct queue {
{
node *t[100]; node *t[100];
int front; int front;
int rear; int rear;
@@ -21,107 +19,71 @@ void enqueue(node *n) { q.t[q.rear++] = n; }
node *dequeue() { return (q.t[q.front++]); } node *dequeue() { return (q.t[q.front++]); }
void Insert(node *n, int x) void Insert(node *n, int x) {
{ if (x < n->val) {
if (x < n->val) if (n->left == NULL) {
{
if (n->left == NULL)
{
node *temp = new node; node *temp = new node;
temp->val = x; temp->val = x;
temp->left = NULL; temp->left = NULL;
temp->right = NULL; temp->right = NULL;
n->left = temp; n->left = temp;
} } else {
else
{
Insert(n->left, x); Insert(n->left, x);
} }
} } else {
else if (n->right == NULL) {
{
if (n->right == NULL)
{
node *temp = new node; node *temp = new node;
temp->val = x; temp->val = x;
temp->left = NULL; temp->left = NULL;
temp->right = NULL; temp->right = NULL;
n->left = temp; n->left = temp;
} } else {
else
{
Insert(n->right, x); Insert(n->right, x);
} }
} }
} }
int findMaxInLeftST(node *n) int findMaxInLeftST(node *n) {
{ while (n->right != NULL) {
while (n->right != NULL)
{
n = n->right; n = n->right;
} }
return n->val; return n->val;
} }
void Remove(node *p, node *n, int x) void Remove(node *p, node *n, int x) {
{ if (n->val == x) {
if (n->val == x) if (n->right == NULL && n->left == NULL) {
{ if (x < p->val) {
if (n->right == NULL && n->left == NULL)
{
if (x < p->val)
{
p->right = NULL; p->right = NULL;
} } else {
else
{
p->left = NULL; p->left = NULL;
} }
} } else if (n->right == NULL) {
else if (n->right == NULL) if (x < p->val) {
{
if (x < p->val)
{
p->right = n->left; p->right = n->left;
} } else {
else
{
p->left = n->left; p->left = n->left;
} }
} } else if (n->left == NULL) {
else if (n->left == NULL) if (x < p->val) {
{
if (x < p->val)
{
p->right = n->right; p->right = n->right;
} } else {
else
{
p->left = n->right; p->left = n->right;
} }
} } else {
else
{
int y = findMaxInLeftST(n->left); int y = findMaxInLeftST(n->left);
n->val = y; n->val = y;
Remove(n, n->right, y); Remove(n, n->right, y);
} }
} } else if (x < n->val) {
else if (x < n->val)
{
Remove(n, n->left, x); Remove(n, n->left, x);
} } else {
else
{
Remove(n, n->right, x); Remove(n, n->right, x);
} }
} }
void BFT(node *n) void BFT(node *n) {
{ if (n != NULL) {
if (n != NULL)
{
cout << n->val << " "; cout << n->val << " ";
enqueue(n->left); enqueue(n->left);
enqueue(n->right); enqueue(n->right);
@@ -129,38 +91,31 @@ void BFT(node *n)
} }
} }
void Pre(node *n) void Pre(node *n) {
{ if (n != NULL) {
if (n != NULL)
{
cout << n->val << " "; cout << n->val << " ";
Pre(n->left); Pre(n->left);
Pre(n->right); Pre(n->right);
} }
} }
void In(node *n) void In(node *n) {
{ if (n != NULL) {
if (n != NULL)
{
In(n->left); In(n->left);
cout << n->val << " "; cout << n->val << " ";
In(n->right); In(n->right);
} }
} }
void Post(node *n) void Post(node *n) {
{ if (n != NULL) {
if (n != NULL)
{
Post(n->left); Post(n->left);
Post(n->right); Post(n->right);
cout << n->val << " "; cout << n->val << " ";
} }
} }
int main() int main() {
{
q.front = 0; q.front = 0;
q.rear = 0; q.rear = 0;
int value; int value;
@@ -171,8 +126,7 @@ int main()
root->val = value; root->val = value;
root->left = NULL; root->left = NULL;
root->right = NULL; root->right = NULL;
do do {
{
cout << "\n1. Insert"; cout << "\n1. Insert";
cout << "\n2. Delete"; cout << "\n2. Delete";
cout << "\n3. Breadth First"; cout << "\n3. Breadth First";
@@ -183,8 +137,7 @@ int main()
cout << "\nEnter Your Choice : "; cout << "\nEnter Your Choice : ";
cin >> ch; cin >> ch;
int x; int x;
switch (ch) switch (ch) {
{
case 1: case 1:
cout << "\nEnter the value to be Inserted : "; cout << "\nEnter the value to be Inserted : ";
cin >> x; cin >> x;

View File

@@ -7,8 +7,7 @@ using namespace std;
void swap(int *x, int *y); void swap(int *x, int *y);
// A class for Min Heap // A class for Min Heap
class MinHeap class MinHeap {
{
int *harr; // pointer to array of elements in heap int *harr; // pointer to array of elements in heap
int capacity; // maximum possible size of min heap int capacity; // maximum possible size of min heap
int heap_size; // Current number of elements in min heap int heap_size; // Current number of elements in min heap
@@ -44,18 +43,15 @@ class MinHeap
}; };
// Constructor: Builds a heap from a given array a[] of given size // Constructor: Builds a heap from a given array a[] of given size
MinHeap::MinHeap(int cap) MinHeap::MinHeap(int cap) {
{
heap_size = 0; heap_size = 0;
capacity = cap; capacity = cap;
harr = new int[cap]; harr = new int[cap];
} }
// Inserts a new key 'k' // Inserts a new key 'k'
void MinHeap::insertKey(int k) void MinHeap::insertKey(int k) {
{ if (heap_size == capacity) {
if (heap_size == capacity)
{
cout << "\nOverflow: Could not insertKey\n"; cout << "\nOverflow: Could not insertKey\n";
return; return;
} }
@@ -66,8 +62,7 @@ void MinHeap::insertKey(int k)
harr[i] = k; harr[i] = k;
// Fix the min heap property if it is violated // Fix the min heap property if it is violated
while (i != 0 && harr[parent(i)] > harr[i]) while (i != 0 && harr[parent(i)] > harr[i]) {
{
swap(&harr[i], &harr[parent(i)]); swap(&harr[i], &harr[parent(i)]);
i = parent(i); i = parent(i);
} }
@@ -75,23 +70,19 @@ void MinHeap::insertKey(int k)
// Decreases value of key at index 'i' to new_val. It is assumed that // Decreases value of key at index 'i' to new_val. It is assumed that
// new_val is smaller than harr[i]. // new_val is smaller than harr[i].
void MinHeap::decreaseKey(int i, int new_val) void MinHeap::decreaseKey(int i, int new_val) {
{
harr[i] = new_val; harr[i] = new_val;
while (i != 0 && harr[parent(i)] > harr[i]) while (i != 0 && harr[parent(i)] > harr[i]) {
{
swap(&harr[i], &harr[parent(i)]); swap(&harr[i], &harr[parent(i)]);
i = parent(i); i = parent(i);
} }
} }
// Method to remove minimum element (or root) from min heap // Method to remove minimum element (or root) from min heap
int MinHeap::extractMin() int MinHeap::extractMin() {
{
if (heap_size <= 0) if (heap_size <= 0)
return INT_MAX; return INT_MAX;
if (heap_size == 1) if (heap_size == 1) {
{
heap_size--; heap_size--;
return harr[0]; return harr[0];
} }
@@ -107,16 +98,14 @@ int MinHeap::extractMin()
// This function deletes key at index i. It first reduced value to minus // This function deletes key at index i. It first reduced value to minus
// infinite, then calls extractMin() // infinite, then calls extractMin()
void MinHeap::deleteKey(int i) void MinHeap::deleteKey(int i) {
{
decreaseKey(i, INT_MIN); decreaseKey(i, INT_MIN);
extractMin(); extractMin();
} }
// A recursive method to heapify a subtree with the root at given index // A recursive method to heapify a subtree with the root at given index
// This method assumes that the subtrees are already heapified // This method assumes that the subtrees are already heapified
void MinHeap::MinHeapify(int i) void MinHeap::MinHeapify(int i) {
{
int l = left(i); int l = left(i);
int r = right(i); int r = right(i);
int smallest = i; int smallest = i;
@@ -124,24 +113,21 @@ void MinHeap::MinHeapify(int i)
smallest = l; smallest = l;
if (r < heap_size && harr[r] < harr[smallest]) if (r < heap_size && harr[r] < harr[smallest])
smallest = r; smallest = r;
if (smallest != i) if (smallest != i) {
{
swap(&harr[i], &harr[smallest]); swap(&harr[i], &harr[smallest]);
MinHeapify(smallest); MinHeapify(smallest);
} }
} }
// A utility function to swap two elements // A utility function to swap two elements
void swap(int *x, int *y) void swap(int *x, int *y) {
{
int temp = *x; int temp = *x;
*x = *y; *x = *y;
*y = temp; *y = temp;
} }
// Driver program to test above functions // Driver program to test above functions
int main() int main() {
{
MinHeap h(11); MinHeap h(11);
h.insertKey(3); h.insertKey(3);
h.insertKey(2); h.insertKey(2);

View File

@@ -1,24 +1,20 @@
#include <iostream> #include <iostream>
using namespace std; using namespace std;
struct node struct node {
{
int data; int data;
struct node *next; struct node *next;
}; };
class Queue class Queue {
{
node *front; node *front;
node *rear; node *rear;
public: public:
Queue() Queue() {
{
front = NULL; front = NULL;
rear = NULL; rear = NULL;
} }
void createNode(int val) void createNode(int val) {
{
node *ptr; node *ptr;
node *nn; node *nn;
nn = new node; nn = new node;
@@ -28,14 +24,10 @@ class Queue
front = nn; front = nn;
rear = nn; rear = nn;
} }
void enqueue(int val) void enqueue(int val) {
{ if (front == NULL || rear == NULL) {
if (front == NULL || rear == NULL)
{
createNode(val); createNode(val);
} } else {
else
{
node *ptr; node *ptr;
node *nn; node *nn;
ptr = front; ptr = front;
@@ -46,19 +38,16 @@ class Queue
rear = nn; rear = nn;
} }
} }
void dequeue() void dequeue() {
{
node *n; node *n;
n = front; n = front;
front = front->next; front = front->next;
delete (n); delete (n);
} }
void traverse() void traverse() {
{
node *ptr; node *ptr;
ptr = front; ptr = front;
do do {
{
cout << ptr->data << " "; cout << ptr->data << " ";
ptr = ptr->next; ptr = ptr->next;
} while (ptr != rear->next); } while (ptr != rear->next);
@@ -66,8 +55,7 @@ class Queue
cout << endl; cout << endl;
} }
}; };
int main(void) int main(void) {
{
Queue q; Queue q;
q.enqueue(10); q.enqueue(10);
q.enqueue(20); q.enqueue(20);

View File

@@ -5,25 +5,22 @@
using namespace std; using namespace std;
/* Constructor */ /* Constructor */
cll::cll() cll::cll() {
{
head = NULL; head = NULL;
total = 0; total = 0;
} }
cll::~cll() { /* Desstructure, no need to fill */ } cll::~cll() { /* Desstructure, no need to fill */
}
/* Display a list. and total element */ /* Display a list. and total element */
void cll::display() void cll::display() {
{
if (head == NULL) if (head == NULL)
cout << "List is empty !" << endl; cout << "List is empty !" << endl;
else else {
{
cout << "CLL list: "; cout << "CLL list: ";
node *current = head; node *current = head;
for (int i = 0; i < total; i++) for (int i = 0; i < total; i++) {
{
cout << current->data << " -> "; cout << current->data << " -> ";
current = current->next; current = current->next;
} }
@@ -33,22 +30,17 @@ void cll::display()
} }
/* List insert a new value at head in list */ /* List insert a new value at head in list */
void cll::insert_front(int new_data) void cll::insert_front(int new_data) {
{
node *newNode; node *newNode;
newNode = new node; newNode = new node;
newNode->data = new_data; newNode->data = new_data;
newNode->next = NULL; newNode->next = NULL;
if (head == NULL) if (head == NULL) {
{
head = newNode; head = newNode;
head->next = head; head->next = head;
} } else {
else
{
node *current = head; node *current = head;
while (current->next != head) while (current->next != head) {
{
current = current->next; current = current->next;
} }
newNode->next = head; newNode->next = head;
@@ -59,22 +51,17 @@ void cll::insert_front(int new_data)
} }
/* List insert a new value at head in list */ /* List insert a new value at head in list */
void cll::insert_tail(int new_data) void cll::insert_tail(int new_data) {
{
node *newNode; node *newNode;
newNode = new node; newNode = new node;
newNode->data = new_data; newNode->data = new_data;
newNode->next = NULL; newNode->next = NULL;
if (head == NULL) if (head == NULL) {
{
head = newNode; head = newNode;
head->next = head; head->next = head;
} } else {
else
{
node *current = head; node *current = head;
while (current->next != head) while (current->next != head) {
{
current = current->next; current = current->next;
} }
current->next = newNode; current->next = newNode;
@@ -88,18 +75,13 @@ int cll::get_size() { return total; }
/* Return true if the requested item (sent in as an argument) /* Return true if the requested item (sent in as an argument)
is in the list, otherwise return false */ is in the list, otherwise return false */
bool cll::find_item(int item_to_find) bool cll::find_item(int item_to_find) {
{ if (head == NULL) {
if (head == NULL)
{
cout << "List is empty !" << endl; cout << "List is empty !" << endl;
return false; return false;
} } else {
else
{
node *current = head; node *current = head;
while (current->next != head) while (current->next != head) {
{
if (current->data == item_to_find) if (current->data == item_to_find)
return true; return true;
current = current->next; current = current->next;
@@ -113,17 +95,12 @@ int cll::operator*() { return head->data; }
/* Overload the pre-increment operator. /* Overload the pre-increment operator.
The iterator is advanced to the next node. */ The iterator is advanced to the next node. */
void cll::operator++() void cll::operator++() {
{ if (head == NULL) {
if (head == NULL)
{
cout << "List is empty !" << endl; cout << "List is empty !" << endl;
} } else {
else
{
node *current = head; node *current = head;
while (current->next != head) while (current->next != head) {
{
current = current->next; current = current->next;
} }
current->next = head->next; current->next = head->next;

View File

@@ -9,14 +9,12 @@
#ifndef CLL_H #ifndef CLL_H
#define CLL_H #define CLL_H
/*The data structure is a linear linked list of integers */ /*The data structure is a linear linked list of integers */
struct node struct node {
{
int data; int data;
node* next; node* next;
}; };
class cll class cll {
{
public: public:
cll(); /* Construct without parameter */ cll(); /* Construct without parameter */
~cll(); ~cll();

View File

@@ -1,8 +1,7 @@
#include "cll.h" #include "cll.h"
using namespace std; using namespace std;
int main() int main() {
{
/* Test CLL */ /* Test CLL */
cout << "----------- Test construct -----------" << endl; cout << "----------- Test construct -----------" << endl;
cll list1; cll list1;

View File

@@ -7,20 +7,16 @@ using std::vector;
vector<int> root, rnk; vector<int> root, rnk;
void CreateSet(int n) void CreateSet(int n) {
{
root = vector<int>(n + 1); root = vector<int>(n + 1);
rnk = vector<int>(n + 1, 1); rnk = vector<int>(n + 1, 1);
for (int i = 1; i <= n; ++i) for (int i = 1; i <= n; ++i) {
{
root[i] = i; root[i] = i;
} }
} }
int Find(int x) int Find(int x) {
{ if (root[x] == x) {
if (root[x] == x)
{
return x; return x;
} }
return root[x] = Find(root[x]); return root[x] = Find(root[x]);
@@ -28,50 +24,38 @@ int Find(int x)
bool InSameUnion(int x, int y) { return Find(x) == Find(y); } bool InSameUnion(int x, int y) { return Find(x) == Find(y); }
void Union(int x, int y) void Union(int x, int y) {
{
int a = Find(x), b = Find(y); int a = Find(x), b = Find(y);
if (a != b) if (a != b) {
{ if (rnk[a] < rnk[b]) {
if (rnk[a] < rnk[b])
{
root[a] = b; root[a] = b;
} } else if (rnk[a] > rnk[b]) {
else if (rnk[a] > rnk[b])
{
root[b] = a; root[b] = a;
} } else {
else
{
root[a] = b; root[a] = b;
++rnk[b]; ++rnk[b];
} }
} }
} }
int main() int main() {
{
// tests CreateSet & Find // tests CreateSet & Find
int n = 100; int n = 100;
CreateSet(n); CreateSet(n);
for (int i = 1; i <= 100; ++i) for (int i = 1; i <= 100; ++i) {
{ if (root[i] != i) {
if (root[i] != i)
{
cout << "Fail" << endl; cout << "Fail" << endl;
break; break;
} }
} }
// tests InSameUnion & Union // tests InSameUnion & Union
cout << "1 and 2 are initially not in the same subset" << endl; cout << "1 and 2 are initially not in the same subset" << endl;
if (InSameUnion(1, 2)) if (InSameUnion(1, 2)) {
{
cout << "Fail" << endl; cout << "Fail" << endl;
} }
Union(1, 2); Union(1, 2);
cout << "1 and 2 are now in the same subset" << endl; cout << "1 and 2 are now in the same subset" << endl;
if (!InSameUnion(1, 2)) if (!InSameUnion(1, 2)) {
{
cout << "Fail" << endl; cout << "Fail" << endl;
} }
return 0; return 0;

View File

@@ -2,15 +2,13 @@
#include <cstdlib> #include <cstdlib>
#include <iostream> #include <iostream>
struct node struct node {
{
int val; int val;
node *prev; node *prev;
node *next; node *next;
} * start; } * start;
class double_linked_list class double_linked_list {
{
public: public:
double_linked_list() { start = NULL; } double_linked_list() { start = NULL; }
void insert(int x); void insert(int x);
@@ -20,13 +18,10 @@ class double_linked_list
void reverseShow(); void reverseShow();
}; };
void double_linked_list::insert(int x) void double_linked_list::insert(int x) {
{
node *t = start; node *t = start;
if (start != NULL) if (start != NULL) {
{ while (t->next != NULL) {
while (t->next != NULL)
{
t = t->next; t = t->next;
} }
node *n = new node; node *n = new node;
@@ -34,9 +29,7 @@ void double_linked_list::insert(int x)
n->prev = t; n->prev = t;
n->val = x; n->val = x;
n->next = NULL; n->next = NULL;
} } else {
else
{
node *n = new node; node *n = new node;
n->val = x; n->val = x;
n->prev = NULL; n->prev = NULL;
@@ -45,91 +38,69 @@ void double_linked_list::insert(int x)
} }
} }
void double_linked_list::remove(int x) void double_linked_list::remove(int x) {
{
node *t = start; node *t = start;
while (t != NULL && t->val != x) while (t != NULL && t->val != x) {
{
t = t->next; t = t->next;
} }
if (t == NULL) if (t == NULL) {
{
return; return;
} }
if (t->prev == NULL) if (t->prev == NULL) {
{ if (t->next == NULL) {
if (t->next == NULL)
{
start = NULL; start = NULL;
} } else {
else
{
start = t->next; start = t->next;
start->prev = NULL; start->prev = NULL;
} }
} } else if (t->next == NULL) {
else if (t->next == NULL)
{
t->prev->next = NULL; t->prev->next = NULL;
} } else {
else
{
t->prev->next = t->next; t->prev->next = t->next;
t->next->prev = t->prev; t->next->prev = t->prev;
} }
delete t; delete t;
} }
void double_linked_list::search(int x) void double_linked_list::search(int x) {
{
node *t = start; node *t = start;
int found = 0; int found = 0;
while (t != NULL) while (t != NULL) {
{ if (t->val == x) {
if (t->val == x)
{
std::cout << "\nFound"; std::cout << "\nFound";
found = 1; found = 1;
break; break;
} }
t = t->next; t = t->next;
} }
if (found == 0) if (found == 0) {
{
std::cout << "\nNot Found"; std::cout << "\nNot Found";
} }
} }
void double_linked_list::show() void double_linked_list::show() {
{
node *t = start; node *t = start;
while (t != NULL) while (t != NULL) {
{
std::cout << t->val << "\t"; std::cout << t->val << "\t";
t = t->next; t = t->next;
} }
} }
void double_linked_list::reverseShow() void double_linked_list::reverseShow() {
{
node *t = start; node *t = start;
while (t != NULL && t->next != NULL) while (t != NULL && t->next != NULL) {
{
t = t->next; t = t->next;
} }
while (t != NULL) while (t != NULL) {
{
std::cout << t->val << "\t"; std::cout << t->val << "\t";
t = t->prev; t = t->prev;
} }
} }
int main() int main() {
{
int choice, x; int choice, x;
double_linked_list ob; double_linked_list ob;
do do {
{
std::cout << "\n1. Insert"; std::cout << "\n1. Insert";
std::cout << "\n2. Delete"; std::cout << "\n2. Delete";
std::cout << "\n3. Search"; std::cout << "\n3. Search";
@@ -137,8 +108,7 @@ int main()
std::cout << "\n5. Reverse print"; std::cout << "\n5. Reverse print";
std::cout << "\n\nEnter you choice : "; std::cout << "\n\nEnter you choice : ";
std::cin >> choice; std::cin >> choice;
switch (choice) switch (choice) {
{
case 1: case 1:
std::cout << "\nEnter the element to be inserted : "; std::cout << "\nEnter the element to be inserted : ";
std::cin >> x; std::cin >> x;

View File

@@ -1,42 +1,32 @@
#include <iostream> #include <iostream>
struct node struct node {
{
int val; int val;
node *next; node *next;
}; };
node *start; node *start;
void insert(int x) void insert(int x) {
{
node *t = start; node *t = start;
node *n = new node; node *n = new node;
n->val = x; n->val = x;
n->next = NULL; n->next = NULL;
if (start != NULL) if (start != NULL) {
{ while (t->next != NULL) {
while (t->next != NULL)
{
t = t->next; t = t->next;
} }
t->next = n; t->next = n;
} } else {
else
{
start = n; start = n;
} }
} }
void remove(int x) void remove(int x) {
{ if (start == NULL) {
if (start == NULL)
{
std::cout << "\nLinked List is empty\n"; std::cout << "\nLinked List is empty\n";
return; return;
} } else if (start->val == x) {
else if (start->val == x)
{
node *temp = start; node *temp = start;
start = start->next; start = start->next;
delete temp; delete temp;
@@ -45,14 +35,12 @@ void remove(int x)
node *temp = start, *parent = start; node *temp = start, *parent = start;
while (temp != NULL && temp->val != x) while (temp != NULL && temp->val != x) {
{
parent = temp; parent = temp;
temp = temp->next; temp = temp->next;
} }
if (temp == NULL) if (temp == NULL) {
{
std::cout << std::endl << x << " not found in list\n"; std::cout << std::endl << x << " not found in list\n";
return; return;
} }
@@ -61,44 +49,35 @@ void remove(int x)
delete temp; delete temp;
} }
void search(int x) void search(int x) {
{
node *t = start; node *t = start;
int found = 0; int found = 0;
while (t != NULL) while (t != NULL) {
{ if (t->val == x) {
if (t->val == x)
{
std::cout << "\nFound"; std::cout << "\nFound";
found = 1; found = 1;
break; break;
} }
t = t->next; t = t->next;
} }
if (found == 0) if (found == 0) {
{
std::cout << "\nNot Found"; std::cout << "\nNot Found";
} }
} }
void show() void show() {
{
node *t = start; node *t = start;
while (t != NULL) while (t != NULL) {
{
std::cout << t->val << "\t"; std::cout << t->val << "\t";
t = t->next; t = t->next;
} }
} }
void reverse() void reverse() {
{
node *first = start; node *first = start;
if (first != NULL) if (first != NULL) {
{
node *second = first->next; node *second = first->next;
while (second != NULL) while (second != NULL) {
{
node *tem = second->next; node *tem = second->next;
second->next = first; second->next = first;
first = second; first = second;
@@ -106,18 +85,14 @@ void reverse()
} }
start->next = NULL; start->next = NULL;
start = first; start = first;
} } else {
else
{
std::cout << "\nEmpty list"; std::cout << "\nEmpty list";
} }
} }
int main() int main() {
{
int choice, x; int choice, x;
do do {
{
std::cout << "\n1. Insert"; std::cout << "\n1. Insert";
std::cout << "\n2. Delete"; std::cout << "\n2. Delete";
std::cout << "\n3. Search"; std::cout << "\n3. Search";
@@ -126,8 +101,7 @@ int main()
std::cout << "\n0. Exit"; std::cout << "\n0. Exit";
std::cout << "\n\nEnter you choice : "; std::cout << "\n\nEnter you choice : ";
std::cin >> choice; std::cin >> choice;
switch (choice) switch (choice) {
{
case 1: case 1:
std::cout << "\nEnter the element to be inserted : "; std::cout << "\nEnter the element to be inserted : ";
std::cin >> x; std::cin >> x;

View File

@@ -7,18 +7,15 @@
#include <iostream> #include <iostream>
using namespace std; using namespace std;
struct Node struct Node {
{
int data; int data;
int next; int next;
}; };
Node AvailArray[100]; // array that will act as nodes of a linked list. Node AvailArray[100]; // array that will act as nodes of a linked list.
int head = -1; int head = -1;
int avail = 0; int avail = 0;
void initialise_list() void initialise_list() {
{ for (int i = 0; i <= 98; i++) {
for (int i = 0; i <= 98; i++)
{
AvailArray[i].next = i + 1; AvailArray[i].next = i + 1;
} }
AvailArray[99].next = -1; // indicating the end of the linked list. AvailArray[99].next = -1; // indicating the end of the linked list.
@@ -50,12 +47,10 @@ void insertAtTheBeginning(int data) // The function will insert the given data
head = newNode; head = newNode;
} }
void insertAtTheEnd(int data) void insertAtTheEnd(int data) {
{
int newNode = getnode(); int newNode = getnode();
int temp = head; int temp = head;
while (AvailArray[temp].next != -1) while (AvailArray[temp].next != -1) {
{
temp = AvailArray[temp].next; temp = AvailArray[temp].next;
} }
// temp is now pointing to the end node. // temp is now pointing to the end node.
@@ -64,11 +59,9 @@ void insertAtTheEnd(int data)
AvailArray[temp].next = newNode; AvailArray[temp].next = newNode;
} }
void display() void display() {
{
int temp = head; int temp = head;
while (temp != -1) while (temp != -1) {
{
cout << AvailArray[temp].data << "->"; cout << AvailArray[temp].data << "->";
temp = AvailArray[temp].next; temp = AvailArray[temp].next;
} }
@@ -76,20 +69,17 @@ void display()
; ;
} }
int main() int main() {
{
initialise_list(); initialise_list();
int x, y, z; int x, y, z;
for (;;) for (;;) {
{
cout << "1. Insert At The Beginning" << endl; cout << "1. Insert At The Beginning" << endl;
cout << "2. Insert At The End" << endl; cout << "2. Insert At The End" << endl;
cout << "3. Display" << endl; cout << "3. Display" << endl;
cout << "4.Exit" << endl; cout << "4.Exit" << endl;
cout << "Enter Your choice" << endl; cout << "Enter Your choice" << endl;
cin >> z; cin >> z;
switch (z) switch (z) {
{
case 1: case 1:
cout << "Enter the number you want to enter" << endl; cout << "Enter the number you want to enter" << endl;
cin >> x; cin >> x;

View File

@@ -1,16 +1,13 @@
#include <iostream> #include <iostream>
using namespace std; using namespace std;
struct list struct list {
{
int data[50]; int data[50];
int top = 0; int top = 0;
bool isSorted = false; bool isSorted = false;
int BinarySearch(int *array, int first, int last, int x) int BinarySearch(int *array, int first, int last, int x) {
{ if (last < first) {
if (last < first)
{
return -1; return -1;
} }
int mid = (first + last) / 2; int mid = (first + last) / 2;
@@ -22,12 +19,9 @@ struct list
return (BinarySearch(array, mid + 1, last, x)); return (BinarySearch(array, mid + 1, last, x));
} }
int LinarSearch(int *array, int x) int LinarSearch(int *array, int x) {
{ for (int i = 0; i < top; i++) {
for (int i = 0; i < top; i++) if (array[i] == x) {
{
if (array[i] == x)
{
return i; return i;
} }
} }
@@ -35,41 +29,31 @@ struct list
return -1; return -1;
} }
int Search(int x) int Search(int x) {
{
int pos = -1; int pos = -1;
if (isSorted) if (isSorted) {
{
pos = BinarySearch(data, 0, top - 1, x); pos = BinarySearch(data, 0, top - 1, x);
} }
else else {
{
pos = LinarSearch(data, x); pos = LinarSearch(data, x);
} }
if (pos != -1) if (pos != -1) {
{
cout << "\nElement found at position : " << pos; cout << "\nElement found at position : " << pos;
} } else {
else
{
cout << "\nElement not found"; cout << "\nElement not found";
} }
return pos; return pos;
} }
void Sort() void Sort() {
{
int i, j, pos; int i, j, pos;
for (i = 0; i < top; i++) for (i = 0; i < top; i++) {
{
int min = data[i]; int min = data[i];
for (j = i + 1; j < top; j++) for (j = i + 1; j < top; j++) {
{ if (data[j] < min) {
if (data[j] < min)
{
pos = j; pos = j;
min = data[pos]; min = data[pos];
} }
@@ -82,40 +66,30 @@ struct list
isSorted = true; isSorted = true;
} }
void insert(int x) void insert(int x) {
{ if (!isSorted) {
if (!isSorted) if (top == 49) {
{
if (top == 49)
{
cout << "\nOverflow"; cout << "\nOverflow";
} } else {
else
{
data[top] = x; data[top] = x;
top++; top++;
} }
} }
else else {
{
int pos = 0; int pos = 0;
for (int i = 0; i < top - 1; i++) for (int i = 0; i < top - 1; i++) {
{ if (data[i] <= x && x <= data[i + 1]) {
if (data[i] <= x && x <= data[i + 1])
{
pos = i + 1; pos = i + 1;
break; break;
} }
} }
if (pos == 0) if (pos == 0) {
{
pos = top - 1; pos = top - 1;
} }
for (int i = top; i > pos; i--) for (int i = top; i > pos; i--) {
{
data[i] = data[i - 1]; data[i] = data[i - 1];
} }
top++; top++;
@@ -123,33 +97,27 @@ struct list
} }
} }
void Remove(int x) void Remove(int x) {
{
int pos = Search(x); int pos = Search(x);
cout << "\n" << data[pos] << " deleted"; cout << "\n" << data[pos] << " deleted";
for (int i = pos; i < top; i++) for (int i = pos; i < top; i++) {
{
data[i] = data[i + 1]; data[i] = data[i + 1];
} }
top--; top--;
} }
void Show() void Show() {
{ for (int i = 0; i < top; i++) {
for (int i = 0; i < top; i++)
{
cout << data[i] << "\t"; cout << data[i] << "\t";
} }
} }
}; };
int main() int main() {
{
list L; list L;
int choice; int choice;
int x; int x;
do do {
{
cout << "\n1.Insert"; cout << "\n1.Insert";
cout << "\n2.Delete"; cout << "\n2.Delete";
cout << "\n3.Search"; cout << "\n3.Search";
@@ -157,8 +125,7 @@ int main()
cout << "\n5.Print"; cout << "\n5.Print";
cout << "\n\nEnter Your Choice : "; cout << "\n\nEnter Your Choice : ";
cin >> choice; cin >> choice;
switch (choice) switch (choice) {
{
case 1: case 1:
cout << "\nEnter the element to be inserted : "; cout << "\nEnter the element to be inserted : ";
cin >> x; cin >> x;

View File

@@ -7,39 +7,32 @@
using namespace std; using namespace std;
struct Btree struct Btree {
{
int data; int data;
struct Btree *left; // Pointer to left subtree struct Btree *left; // Pointer to left subtree
struct Btree *right; // Pointer to right subtree struct Btree *right; // Pointer to right subtree
}; };
void insert(Btree **root, int d) void insert(Btree **root, int d) {
{
Btree *nn = new Btree(); // Creating new node Btree *nn = new Btree(); // Creating new node
nn->data = d; nn->data = d;
nn->left = NULL; nn->left = NULL;
nn->right = NULL; nn->right = NULL;
if (*root == NULL) if (*root == NULL) {
{
*root = nn; *root = nn;
return; return;
} } else {
else
{
queue<Btree *> q; queue<Btree *> q;
// Adding root node to queue // Adding root node to queue
q.push(*root); q.push(*root);
while (!q.empty()) while (!q.empty()) {
{
Btree *node = q.front(); Btree *node = q.front();
// Removing parent node from queue // Removing parent node from queue
q.pop(); q.pop();
if (node->left) if (node->left)
// Adding left child of removed node to queue // Adding left child of removed node to queue
q.push(node->left); q.push(node->left);
else else {
{
// Adding new node if no left child is present // Adding new node if no left child is present
node->left = nn; node->left = nn;
return; return;
@@ -47,8 +40,7 @@ void insert(Btree **root, int d)
if (node->right) if (node->right)
// Adding right child of removed node to queue // Adding right child of removed node to queue
q.push(node->right); q.push(node->right);
else else {
{
// Adding new node if no right child is present // Adding new node if no right child is present
node->right = nn; node->right = nn;
return; return;
@@ -57,36 +49,29 @@ void insert(Btree **root, int d)
} }
} }
void morrisInorder(Btree *root) void morrisInorder(Btree *root) {
{
Btree *curr = root; Btree *curr = root;
Btree *temp; Btree *temp;
while (curr) while (curr) {
{ if (curr->left == NULL) {
if (curr->left == NULL)
{
cout << curr->data << " "; cout << curr->data << " ";
// If left of current node is NULL then curr is shifted to right // If left of current node is NULL then curr is shifted to right
curr = curr->right; curr = curr->right;
} } else {
else
{
// Left of current node is stored in temp // Left of current node is stored in temp
temp = curr->left; temp = curr->left;
// Moving to extreme right of temp // Moving to extreme right of temp
while (temp->right && temp->right != curr) temp = temp->right; while (temp->right && temp->right != curr) temp = temp->right;
// If extreme right is null it is made to point to currrent node // If extreme right is null it is made to point to currrent node
// (will be used for backtracking) // (will be used for backtracking)
if (temp->right == NULL) if (temp->right == NULL) {
{
temp->right = curr; temp->right = curr;
// current node is made to point its left subtree // current node is made to point its left subtree
curr = curr->left; curr = curr->left;
} }
// If extreme right already points to currrent node it it set to // If extreme right already points to currrent node it it set to
// null // null
else if (temp->right == curr) else if (temp->right == curr) {
{
cout << curr->data << " "; cout << curr->data << " ";
temp->right = NULL; temp->right = NULL;
// current node is made to point its right subtree // current node is made to point its right subtree
@@ -96,8 +81,7 @@ void morrisInorder(Btree *root)
} }
} }
int main() int main() {
{
// Testing morrisInorder funtion // Testing morrisInorder funtion
Btree *root = NULL; Btree *root = NULL;
int i; int i;

View File

@@ -6,8 +6,7 @@ using namespace std;
/* Default constructor*/ /* Default constructor*/
template <class Kind> template <class Kind>
queue<Kind>::queue() queue<Kind>::queue() {
{
queueFront = NULL; queueFront = NULL;
queueRear = NULL; queueRear = NULL;
size = 0; size = 0;
@@ -15,18 +14,14 @@ queue<Kind>::queue()
/* Destructor */ /* Destructor */
template <class Kind> template <class Kind>
queue<Kind>::~queue() queue<Kind>::~queue() {}
{
}
/* Display for testing */ /* Display for testing */
template <class Kind> template <class Kind>
void queue<Kind>::display() void queue<Kind>::display() {
{
node<Kind> *current = queueFront; node<Kind> *current = queueFront;
cout << "Front --> "; cout << "Front --> ";
while (current != NULL) while (current != NULL) {
{
cout << current->data << " "; cout << current->data << " ";
current = current->next; current = current->next;
} }
@@ -36,33 +31,27 @@ void queue<Kind>::display()
/* Determine whether the queue is empty */ /* Determine whether the queue is empty */
template <class Kind> template <class Kind>
bool queue<Kind>::isEmptyQueue() bool queue<Kind>::isEmptyQueue() {
{
return (queueFront == NULL); return (queueFront == NULL);
} }
/* Clear queue */ /* Clear queue */
template <class Kind> template <class Kind>
void queue<Kind>::clear() void queue<Kind>::clear() {
{
queueFront = NULL; queueFront = NULL;
} }
/* Add new item to the queue */ /* Add new item to the queue */
template <class Kind> template <class Kind>
void queue<Kind>::enQueue(Kind item) void queue<Kind>::enQueue(Kind item) {
{
node<Kind> *newNode; node<Kind> *newNode;
newNode = new node<Kind>; newNode = new node<Kind>;
newNode->data = item; newNode->data = item;
newNode->next = NULL; newNode->next = NULL;
if (queueFront == NULL) if (queueFront == NULL) {
{
queueFront = newNode; queueFront = newNode;
queueRear = newNode; queueRear = newNode;
} } else {
else
{
queueRear->next = newNode; queueRear->next = newNode;
queueRear = queueRear->next; queueRear = queueRear->next;
} }
@@ -71,26 +60,21 @@ void queue<Kind>::enQueue(Kind item)
/* Return the top element of the queue */ /* Return the top element of the queue */
template <class Kind> template <class Kind>
Kind queue<Kind>::front() Kind queue<Kind>::front() {
{
assert(queueFront != NULL); assert(queueFront != NULL);
return queueFront->data; return queueFront->data;
} }
/* Remove the element of the queue */ /* Remove the element of the queue */
template <class Kind> template <class Kind>
void queue<Kind>::deQueue() void queue<Kind>::deQueue() {
{
node<Kind> *temp; node<Kind> *temp;
if (!isEmptyQueue()) if (!isEmptyQueue()) {
{
temp = queueFront; temp = queueFront;
queueFront = queueFront->next; queueFront = queueFront->next;
delete temp; delete temp;
size--; size--;
} } else {
else
{
cout << "Queue is empty !" << endl; cout << "Queue is empty !" << endl;
} }
} }

View File

@@ -4,16 +4,14 @@
/* Definition of the node */ /* Definition of the node */
template <class Kind> template <class Kind>
struct node struct node {
{
Kind data; Kind data;
node<Kind> *next; node<Kind> *next;
}; };
/* Definition of the queue class */ /* Definition of the queue class */
template <class Kind> template <class Kind>
class queue class queue {
{
public: public:
void display(); /* Show queue */ void display(); /* Show queue */
queue(); /* Default constructor*/ queue(); /* Default constructor*/

View File

@@ -5,8 +5,7 @@
using namespace std; using namespace std;
int main() int main() {
{
queue<string> q; queue<string> q;
cout << "---------------------- Test construct ----------------------" cout << "---------------------- Test construct ----------------------"
<< endl; << endl;

View File

@@ -10,15 +10,13 @@
#define MAXSIZE 10 #define MAXSIZE 10
class Queue_Array class Queue_Array {
{
int front; int front;
int rear; int rear;
int size; int size;
public: public:
Queue_Array() Queue_Array() {
{
front = -1; front = -1;
rear = -1; rear = -1;
size = MAXSIZE; size = MAXSIZE;
@@ -29,59 +27,42 @@ class Queue_Array
void display(); void display();
}; };
void Queue_Array::enqueue(int ele) void Queue_Array::enqueue(int ele) {
{ if (rear == size - 1) {
if (rear == size - 1)
{
std::cout << "\nStack is full"; std::cout << "\nStack is full";
} } else if (front == -1 && rear == -1) {
else if (front == -1 && rear == -1)
{
front = rear = 0; front = rear = 0;
arr[rear] = ele; arr[rear] = ele;
} } else if (rear < size) {
else if (rear < size)
{
rear++; rear++;
arr[rear] = ele; arr[rear] = ele;
} }
} }
int Queue_Array::dequeue() int Queue_Array::dequeue() {
{
int d; int d;
if (front == -1) if (front == -1) {
{
std::cout << "\nstack is empty "; std::cout << "\nstack is empty ";
return 0; return 0;
} } else if (front == rear) {
else if (front == rear)
{
d = arr[front]; d = arr[front];
front = rear = -1; front = rear = -1;
} } else {
else
{
d = arr[front++]; d = arr[front++];
} }
return d; return d;
} }
void Queue_Array::display() void Queue_Array::display() {
{ if (front == -1) {
if (front == -1)
{
std::cout << "\nStack is empty"; std::cout << "\nStack is empty";
} } else {
else
{
for (int i = front; i <= rear; i++) std::cout << arr[i] << " "; for (int i = front; i <= rear; i++) std::cout << arr[i] << " ";
} }
} }
int main() int main() {
{
int op, data; int op, data;
Queue_Array ob; Queue_Array ob;
@@ -90,31 +71,21 @@ int main()
std::cout << "\n2. dequeue(Deletion)"; std::cout << "\n2. dequeue(Deletion)";
std::cout << "\n3. Display"; std::cout << "\n3. Display";
std::cout << "\n4. Exit"; std::cout << "\n4. Exit";
while (1) while (1) {
{
std::cout << "\nEnter your choice "; std::cout << "\nEnter your choice ";
std::cin >> op; std::cin >> op;
if (op == 1) if (op == 1) {
{
std::cout << "Enter data "; std::cout << "Enter data ";
std::cin >> data; std::cin >> data;
ob.enqueue(data); ob.enqueue(data);
} } else if (op == 2) {
else if (op == 2)
{
data = ob.dequeue(); data = ob.dequeue();
std::cout << "\ndequeue element is:\t" << data; std::cout << "\ndequeue element is:\t" << data;
} } else if (op == 3) {
else if (op == 3)
{
ob.display(); ob.display();
} } else if (op == 4) {
else if (op == 4)
{
exit(0); exit(0);
} } else {
else
{
std::cout << "\nWrong choice "; std::cout << "\nWrong choice ";
} }
} }

View File

@@ -5,30 +5,22 @@ int queue[10];
int front = 0; int front = 0;
int rear = 0; int rear = 0;
void Enque(int x) void Enque(int x) {
{ if (rear == 10) {
if (rear == 10)
{
cout << "\nOverflow"; cout << "\nOverflow";
} } else {
else
{
queue[rear++] = x; queue[rear++] = x;
} }
} }
void Deque() void Deque() {
{ if (front == rear) {
if (front == rear)
{
cout << "\nUnderflow"; cout << "\nUnderflow";
} }
else else {
{
cout << "\n" << queue[front++] << " deleted"; cout << "\n" << queue[front++] << " deleted";
for (int i = front; i < rear; i++) for (int i = front; i < rear; i++) {
{
queue[i - front] = queue[i]; queue[i - front] = queue[i];
} }
rear = rear - front; rear = rear - front;
@@ -36,36 +28,27 @@ void Deque()
} }
} }
void show() void show() {
{ for (int i = front; i < rear; i++) {
for (int i = front; i < rear; i++)
{
cout << queue[i] << "\t"; cout << queue[i] << "\t";
} }
} }
int main() int main() {
{
int ch, x; int ch, x;
do do {
{
cout << "\n1. Enque"; cout << "\n1. Enque";
cout << "\n2. Deque"; cout << "\n2. Deque";
cout << "\n3. Print"; cout << "\n3. Print";
cout << "\nEnter Your Choice : "; cout << "\nEnter Your Choice : ";
cin >> ch; cin >> ch;
if (ch == 1) if (ch == 1) {
{
cout << "\nInsert : "; cout << "\nInsert : ";
cin >> x; cin >> x;
Enque(x); Enque(x);
} } else if (ch == 2) {
else if (ch == 2)
{
Deque(); Deque();
} } else if (ch == 3) {
else if (ch == 3)
{
show(); show();
} }
} while (ch != 0); } while (ch != 0);

View File

@@ -1,18 +1,15 @@
#include <iostream> #include <iostream>
using namespace std; using namespace std;
struct node struct node {
{
int val; int val;
node *next; node *next;
}; };
node *front, *rear; node *front, *rear;
void Enque(int x) void Enque(int x) {
{ if (rear == NULL) {
if (rear == NULL)
{
node *n = new node; node *n = new node;
n->val = x; n->val = x;
n->next = NULL; n->next = NULL;
@@ -20,8 +17,7 @@ void Enque(int x)
front = n; front = n;
} }
else else {
{
node *n = new node; node *n = new node;
n->val = x; n->val = x;
n->next = NULL; n->next = NULL;
@@ -30,14 +26,10 @@ void Enque(int x)
} }
} }
void Deque() void Deque() {
{ if (rear == NULL && front == NULL) {
if (rear == NULL && front == NULL)
{
cout << "\nUnderflow"; cout << "\nUnderflow";
} } else {
else
{
node *t = front; node *t = front;
cout << "\n" << t->val << " deleted"; cout << "\n" << t->val << " deleted";
front = front->next; front = front->next;
@@ -47,38 +39,29 @@ void Deque()
} }
} }
void show() void show() {
{
node *t = front; node *t = front;
while (t != NULL) while (t != NULL) {
{
cout << t->val << "\t"; cout << t->val << "\t";
t = t->next; t = t->next;
} }
} }
int main() int main() {
{
int ch, x; int ch, x;
do do {
{
cout << "\n1. Enque"; cout << "\n1. Enque";
cout << "\n2. Deque"; cout << "\n2. Deque";
cout << "\n3. Print"; cout << "\n3. Print";
cout << "\nEnter Your Choice : "; cout << "\nEnter Your Choice : ";
cin >> ch; cin >> ch;
if (ch == 1) if (ch == 1) {
{
cout << "\nInsert : "; cout << "\nInsert : ";
cin >> x; cin >> x;
Enque(x); Enque(x);
} } else if (ch == 2) {
else if (ch == 2)
{
Deque(); Deque();
} } else if (ch == 3) {
else if (ch == 3)
{
show(); show();
} }
} while (ch != 0); } while (ch != 0);

View File

@@ -3,13 +3,11 @@
*/ */
#include <iostream> #include <iostream>
struct linkedlist struct linkedlist {
{
int data; int data;
linkedlist *next; linkedlist *next;
}; };
class stack_linkedList class stack_linkedList {
{
public: public:
linkedlist *front; linkedlist *front;
linkedlist *rear; linkedlist *rear;
@@ -19,28 +17,24 @@ class stack_linkedList
int dequeue(); int dequeue();
void display(); void display();
}; };
void stack_linkedList::enqueue(int ele) void stack_linkedList::enqueue(int ele) {
{
linkedlist *temp = new linkedlist(); linkedlist *temp = new linkedlist();
temp->data = ele; temp->data = ele;
temp->next = NULL; temp->next = NULL;
if (front == NULL) if (front == NULL)
front = rear = temp; front = rear = temp;
else else {
{
rear->next = temp; rear->next = temp;
rear = temp; rear = temp;
} }
} }
int stack_linkedList::dequeue() int stack_linkedList::dequeue() {
{
linkedlist *temp; linkedlist *temp;
int ele; int ele;
if (front == NULL) if (front == NULL)
std::cout << "\nStack is empty"; std::cout << "\nStack is empty";
else else {
{
temp = front; temp = front;
ele = temp->data; ele = temp->data;
if (front == rear) // if length of queue is 1; if (front == rear) // if length of queue is 1;
@@ -50,25 +44,21 @@ int stack_linkedList::dequeue()
} }
return ele; return ele;
} }
void stack_linkedList::display() void stack_linkedList::display() {
{
if (front == NULL) if (front == NULL)
std::cout << "\nStack is empty"; std::cout << "\nStack is empty";
else else {
{
linkedlist *temp; linkedlist *temp;
temp = front; temp = front;
while (temp != NULL) while (temp != NULL) {
{
std::cout << temp->data << " "; std::cout << temp->data << " ";
temp = temp->next; temp = temp->next;
} }
} }
} }
int main() int main() {
{
int op, data; int op, data;
stack_linkedList ob; stack_linkedList ob;
std::cout << "\n1. enqueue(Insertion) "; std::cout << "\n1. enqueue(Insertion) ";
@@ -76,17 +66,14 @@ int main()
std::cout << "\n3. Display"; std::cout << "\n3. Display";
std::cout << "\n4. Exit"; std::cout << "\n4. Exit";
while (1) while (1) {
{
std::cout << "\nEnter your choice "; std::cout << "\nEnter your choice ";
std::cin >> op; std::cin >> op;
if (op == 1) if (op == 1) {
{
std::cout << "Enter data "; std::cout << "Enter data ";
std::cin >> data; std::cin >> data;
ob.enqueue(data); ob.enqueue(data);
} } else if (op == 2)
else if (op == 2)
data = ob.dequeue(); data = ob.dequeue();
else if (op == 3) else if (op == 3)
ob.display(); ob.display();

View File

@@ -4,69 +4,50 @@ using namespace std;
int *stack; int *stack;
int top = 0, size; int top = 0, size;
void push(int x) void push(int x) {
{ if (top == size) {
if (top == size)
{
cout << "\nOverflow"; cout << "\nOverflow";
} } else {
else
{
stack[top++] = x; stack[top++] = x;
} }
} }
void pop() void pop() {
{ if (top == 0) {
if (top == 0)
{
cout << "\nUnderflow"; cout << "\nUnderflow";
} } else {
else
{
cout << "\n" << stack[--top] << " deleted"; cout << "\n" << stack[--top] << " deleted";
} }
} }
void show() void show() {
{ for (int i = 0; i < top; i++) {
for (int i = 0; i < top; i++)
{
cout << stack[i] << "\n"; cout << stack[i] << "\n";
} }
} }
void topmost() { cout << "\nTopmost element: " << stack[top - 1]; } void topmost() { cout << "\nTopmost element: " << stack[top - 1]; }
int main() int main() {
{
cout << "\nEnter Size of stack : "; cout << "\nEnter Size of stack : ";
cin >> size; cin >> size;
stack = new int[size]; stack = new int[size];
int ch, x; int ch, x;
do do {
{
cout << "\n1. Push"; cout << "\n1. Push";
cout << "\n2. Pop"; cout << "\n2. Pop";
cout << "\n3. Print"; cout << "\n3. Print";
cout << "\n4. Print topmost element:"; cout << "\n4. Print topmost element:";
cout << "\nEnter Your Choice : "; cout << "\nEnter Your Choice : ";
cin >> ch; cin >> ch;
if (ch == 1) if (ch == 1) {
{
cout << "\nInsert : "; cout << "\nInsert : ";
cin >> x; cin >> x;
push(x); push(x);
} } else if (ch == 2) {
else if (ch == 2)
{
pop(); pop();
} } else if (ch == 3) {
else if (ch == 3)
{
show(); show();
} } else if (ch == 4) {
else if (ch == 4)
{
topmost(); topmost();
} }
} while (ch != 0); } while (ch != 0);

View File

@@ -1,30 +1,24 @@
#include <iostream> #include <iostream>
using namespace std; using namespace std;
struct node struct node {
{
int val; int val;
node *next; node *next;
}; };
node *top; node *top;
void push(int x) void push(int x) {
{
node *n = new node; node *n = new node;
n->val = x; n->val = x;
n->next = top; n->next = top;
top = n; top = n;
} }
void pop() void pop() {
{ if (top == NULL) {
if (top == NULL)
{
cout << "\nUnderflow"; cout << "\nUnderflow";
} } else {
else
{
node *t = top; node *t = top;
cout << "\n" << t->val << " deleted"; cout << "\n" << t->val << " deleted";
top = top->next; top = top->next;
@@ -32,38 +26,29 @@ void pop()
} }
} }
void show() void show() {
{
node *t = top; node *t = top;
while (t != NULL) while (t != NULL) {
{
cout << t->val << "\n"; cout << t->val << "\n";
t = t->next; t = t->next;
} }
} }
int main() int main() {
{
int ch, x; int ch, x;
do do {
{
cout << "\n1. Push"; cout << "\n1. Push";
cout << "\n2. Pop"; cout << "\n2. Pop";
cout << "\n3. Print"; cout << "\n3. Print";
cout << "\nEnter Your Choice : "; cout << "\nEnter Your Choice : ";
cin >> ch; cin >> ch;
if (ch == 1) if (ch == 1) {
{
cout << "\nInsert : "; cout << "\nInsert : ";
cin >> x; cin >> x;
push(x); push(x);
} } else if (ch == 2) {
else if (ch == 2)
{
pop(); pop();
} } else if (ch == 3) {
else if (ch == 3)
{
show(); show();
} }
} while (ch != 0); } while (ch != 0);

View File

@@ -19,8 +19,7 @@
using namespace std; using namespace std;
int main(int argc, char* argv[]) int main(int argc, char* argv[]) {
{
double GPA; double GPA;
double highestGPA; double highestGPA;
string name; string name;
@@ -35,24 +34,19 @@ int main(int argc, char* argv[])
infile >> GPA >> name; infile >> GPA >> name;
highestGPA = GPA; highestGPA = GPA;
while (infile) while (infile) {
{ if (GPA > highestGPA) {
if (GPA > highestGPA)
{
stk.clear(); stk.clear();
stk.push(name); stk.push(name);
highestGPA = GPA; highestGPA = GPA;
} } else if (GPA == highestGPA) {
else if (GPA == highestGPA)
{
stk.push(name); stk.push(name);
} }
infile >> GPA >> name; infile >> GPA >> name;
} }
cout << "Highest GPA: " << highestGPA << endl; cout << "Highest GPA: " << highestGPA << endl;
cout << "Students the highest GPA are: " << endl; cout << "Students the highest GPA are: " << endl;
while (!stk.isEmptyStack()) while (!stk.isEmptyStack()) {
{
cout << stk.top() << endl; cout << stk.top() << endl;
stk.pop(); stk.pop();
} }

View File

@@ -6,26 +6,21 @@ using namespace std;
/* Default constructor*/ /* Default constructor*/
template <class Type> template <class Type>
stack<Type>::stack() stack<Type>::stack() {
{
stackTop = NULL; stackTop = NULL;
size = 0; size = 0;
} }
/* Destructor */ /* Destructor */
template <class Type> template <class Type>
stack<Type>::~stack() stack<Type>::~stack() {}
{
}
/* Display for testing */ /* Display for testing */
template <class Type> template <class Type>
void stack<Type>::display() void stack<Type>::display() {
{
node<Type> *current = stackTop; node<Type> *current = stackTop;
cout << "Top --> "; cout << "Top --> ";
while (current != NULL) while (current != NULL) {
{
cout << current->data << " "; cout << current->data << " ";
current = current->next; current = current->next;
} }
@@ -35,22 +30,19 @@ void stack<Type>::display()
/* Determine whether the stack is empty */ /* Determine whether the stack is empty */
template <class Type> template <class Type>
bool stack<Type>::isEmptyStack() bool stack<Type>::isEmptyStack() {
{
return (stackTop == NULL); return (stackTop == NULL);
} }
/* Clear stack */ /* Clear stack */
template <class Type> template <class Type>
void stack<Type>::clear() void stack<Type>::clear() {
{
stackTop = NULL; stackTop = NULL;
} }
/* Add new item to the stack */ /* Add new item to the stack */
template <class Type> template <class Type>
void stack<Type>::push(Type item) void stack<Type>::push(Type item) {
{
node<Type> *newNode; node<Type> *newNode;
newNode = new node<Type>; newNode = new node<Type>;
newNode->data = item; newNode->data = item;
@@ -61,42 +53,35 @@ void stack<Type>::push(Type item)
/* Return the top element of the stack */ /* Return the top element of the stack */
template <class Type> template <class Type>
Type stack<Type>::top() Type stack<Type>::top() {
{
assert(stackTop != NULL); assert(stackTop != NULL);
return stackTop->data; return stackTop->data;
} }
/* Remove the top element of the stack */ /* Remove the top element of the stack */
template <class Type> template <class Type>
void stack<Type>::pop() void stack<Type>::pop() {
{
node<Type> *temp; node<Type> *temp;
if (!isEmptyStack()) if (!isEmptyStack()) {
{
temp = stackTop; temp = stackTop;
stackTop = stackTop->next; stackTop = stackTop->next;
delete temp; delete temp;
size--; size--;
} } else {
else
{
cout << "Stack is empty !" << endl; cout << "Stack is empty !" << endl;
} }
} }
/* Operator "=" */ /* Operator "=" */
template <class Type> template <class Type>
stack<Type> stack<Type>::operator=(stack<Type> &otherStack) stack<Type> stack<Type>::operator=(stack<Type> &otherStack) {
{
node<Type> *newNode, *current, *last; node<Type> *newNode, *current, *last;
if (stackTop != NULL) /* If stack is no empty, make it empty */ if (stackTop != NULL) /* If stack is no empty, make it empty */
stackTop = NULL; stackTop = NULL;
if (otherStack.stackTop == NULL) if (otherStack.stackTop == NULL)
stackTop = NULL; stackTop = NULL;
else else {
{
current = otherStack.stackTop; current = otherStack.stackTop;
stackTop = new node<Type>; stackTop = new node<Type>;
stackTop->data = current->data; stackTop->data = current->data;
@@ -104,8 +89,7 @@ stack<Type> stack<Type>::operator=(stack<Type> &otherStack)
last = stackTop; last = stackTop;
current = current->next; current = current->next;
/* Copy the remaining stack */ /* Copy the remaining stack */
while (current != NULL) while (current != NULL) {
{
newNode = new node<Type>; newNode = new node<Type>;
newNode->data = current->data; newNode->data = current->data;
newNode->next = NULL; newNode->next = NULL;

View File

@@ -4,16 +4,14 @@
/* Definition of the node */ /* Definition of the node */
template <class Type> template <class Type>
struct node struct node {
{
Type data; Type data;
node<Type> *next; node<Type> *next;
}; };
/* Definition of the stack class */ /* Definition of the stack class */
template <class Type> template <class Type>
class stack class stack {
{
public: public:
void display(); /* Show stack */ void display(); /* Show stack */
stack(); /* Default constructor*/ stack(); /* Default constructor*/

View File

@@ -4,8 +4,7 @@
using namespace std; using namespace std;
int main() int main() {
{
stack<int> stk; stack<int> stk;
cout << "---------------------- Test construct ----------------------" cout << "---------------------- Test construct ----------------------"
<< endl; << endl;

View File

@@ -2,17 +2,14 @@
#include <list> #include <list>
using namespace std; using namespace std;
struct node struct node {
{
int val; int val;
node *left; node *left;
node *right; node *right;
}; };
void CreateTree(node *curr, node *n, int x, char pos) void CreateTree(node *curr, node *n, int x, char pos) {
{ if (n != NULL) {
if (n != NULL)
{
char ch; char ch;
cout << "\nLeft or Right of " << n->val << " : "; cout << "\nLeft or Right of " << n->val << " : ";
cin >> ch; cin >> ch;
@@ -20,32 +17,25 @@ void CreateTree(node *curr, node *n, int x, char pos)
CreateTree(n, n->left, x, ch); CreateTree(n, n->left, x, ch);
else if (ch == 'r') else if (ch == 'r')
CreateTree(n, n->right, x, ch); CreateTree(n, n->right, x, ch);
} } else {
else
{
node *t = new node; node *t = new node;
t->val = x; t->val = x;
t->left = NULL; t->left = NULL;
t->right = NULL; t->right = NULL;
if (pos == 'l') if (pos == 'l') {
{
curr->left = t; curr->left = t;
} } else if (pos == 'r') {
else if (pos == 'r')
{
curr->right = t; curr->right = t;
} }
} }
} }
void BFT(node *n) void BFT(node *n) {
{
list<node *> queue; list<node *> queue;
queue.push_back(n); queue.push_back(n);
while (!queue.empty()) while (!queue.empty()) {
{
n = queue.front(); n = queue.front();
cout << n->val << " "; cout << n->val << " ";
queue.pop_front(); queue.pop_front();
@@ -57,38 +47,31 @@ void BFT(node *n)
} }
} }
void Pre(node *n) void Pre(node *n) {
{ if (n != NULL) {
if (n != NULL)
{
cout << n->val << " "; cout << n->val << " ";
Pre(n->left); Pre(n->left);
Pre(n->right); Pre(n->right);
} }
} }
void In(node *n) void In(node *n) {
{ if (n != NULL) {
if (n != NULL)
{
In(n->left); In(n->left);
cout << n->val << " "; cout << n->val << " ";
In(n->right); In(n->right);
} }
} }
void Post(node *n) void Post(node *n) {
{ if (n != NULL) {
if (n != NULL)
{
Post(n->left); Post(n->left);
Post(n->right); Post(n->right);
cout << n->val << " "; cout << n->val << " ";
} }
} }
int main() int main() {
{
int value; int value;
int ch; int ch;
node *root = new node; node *root = new node;
@@ -97,8 +80,7 @@ int main()
root->val = value; root->val = value;
root->left = NULL; root->left = NULL;
root->right = NULL; root->right = NULL;
do do {
{
cout << "\n1. Insert"; cout << "\n1. Insert";
cout << "\n2. Breadth First"; cout << "\n2. Breadth First";
cout << "\n3. Preorder Depth First"; cout << "\n3. Preorder Depth First";
@@ -107,8 +89,7 @@ int main()
cout << "\nEnter Your Choice : "; cout << "\nEnter Your Choice : ";
cin >> ch; cin >> ch;
switch (ch) switch (ch) {
{
case 1: case 1:
int x; int x;
char pos; char pos;

View File

@@ -5,15 +5,13 @@
#include <string> #include <string>
// structure definition // structure definition
typedef struct trie typedef struct trie {
{
struct trie* arr[26]; struct trie* arr[26];
bool isEndofWord; bool isEndofWord;
} trie; } trie;
// create a new node for trie // create a new node for trie
trie* createNode() trie* createNode() {
{
trie* nn = new trie(); trie* nn = new trie();
for (int i = 0; i < 26; i++) nn->arr[i] = NULL; for (int i = 0; i < 26; i++) nn->arr[i] = NULL;
nn->isEndofWord = false; nn->isEndofWord = false;
@@ -21,17 +19,12 @@ trie* createNode()
} }
// insert string into the trie // insert string into the trie
void insert(trie* root, std::string str) void insert(trie* root, std::string str) {
{ for (int i = 0; i < str.length(); i++) {
for (int i = 0; i < str.length(); i++)
{
int j = str[i] - 'a'; int j = str[i] - 'a';
if (root->arr[j]) if (root->arr[j]) {
{
root = root->arr[j]; root = root->arr[j];
} } else {
else
{
root->arr[j] = createNode(); root->arr[j] = createNode();
root = root->arr[j]; root = root->arr[j];
} }
@@ -40,10 +33,8 @@ void insert(trie* root, std::string str)
} }
// search a string exists inside the trie // search a string exists inside the trie
bool search(trie* root, std::string str, int index) bool search(trie* root, std::string str, int index) {
{ if (index == str.length()) {
if (index == str.length())
{
if (!root->isEndofWord) if (!root->isEndofWord)
return false; return false;
return true; return true;
@@ -59,10 +50,8 @@ removes the string if it is not a prefix of any other
string, if it is then just sets the endofword to false, else string, if it is then just sets the endofword to false, else
removes the given string removes the given string
*/ */
bool deleteString(trie* root, std::string str, int index) bool deleteString(trie* root, std::string str, int index) {
{ if (index == str.length()) {
if (index == str.length())
{
if (!root->isEndofWord) if (!root->isEndofWord)
return false; return false;
root->isEndofWord = false; root->isEndofWord = false;
@@ -73,15 +62,11 @@ bool deleteString(trie* root, std::string str, int index)
if (!root->arr[j]) if (!root->arr[j])
return false; return false;
bool var = deleteString(root, str, index + 1); bool var = deleteString(root, str, index + 1);
if (var) if (var) {
{
root->arr[j] = NULL; root->arr[j] = NULL;
if (root->isEndofWord) if (root->isEndofWord) {
{
return false; return false;
} } else {
else
{
int i; int i;
for (i = 0; i < 26; i++) for (i = 0; i < 26; i++)
if (root->arr[i]) if (root->arr[i])
@@ -91,8 +76,7 @@ bool deleteString(trie* root, std::string str, int index)
} }
} }
int main() int main() {
{
trie* root = createNode(); trie* root = createNode();
insert(root, "hello"); insert(root, "hello");
insert(root, "world"); insert(root, "world");

View File

@@ -28,13 +28,10 @@ using namespace std;
// } // }
//} //}
int Knapsack(int capacity, int n, int weight[], int value[]) int Knapsack(int capacity, int n, int weight[], int value[]) {
{
int res[20][20]; int res[20][20];
for (int i = 0; i < n + 1; ++i) for (int i = 0; i < n + 1; ++i) {
{ for (int j = 0; j < capacity + 1; ++j) {
for (int j = 0; j < capacity + 1; ++j)
{
if (i == 0 || j == 0) if (i == 0 || j == 0)
res[i][j] = 0; res[i][j] = 0;
else if (weight[i - 1] <= j) else if (weight[i - 1] <= j)
@@ -48,20 +45,17 @@ int Knapsack(int capacity, int n, int weight[], int value[])
// cout<<"\n"; // cout<<"\n";
return res[n][capacity]; return res[n][capacity];
} }
int main() int main() {
{
int n; int n;
cout << "Enter number of items: "; cout << "Enter number of items: ";
cin >> n; cin >> n;
int weight[n], value[n]; int weight[n], value[n];
cout << "Enter weights: "; cout << "Enter weights: ";
for (int i = 0; i < n; ++i) for (int i = 0; i < n; ++i) {
{
cin >> weight[i]; cin >> weight[i];
} }
cout << "Enter values: "; cout << "Enter values: ";
for (int i = 0; i < n; ++i) for (int i = 0; i < n; ++i) {
{
cin >> value[i]; cin >> value[i];
} }
int capacity; int capacity;

View File

@@ -4,14 +4,12 @@
using std::cin; using std::cin;
using std::cout; using std::cout;
int main() int main() {
{
int n, k, d, s = 0; int n, k, d, s = 0;
cout << "Enter a number:"; cout << "Enter a number:";
cin >> n; cin >> n;
k = n; k = n;
while (k != 0) while (k != 0) {
{
d = k % 10; d = k % 10;
s += d * d * d; s += d * d * d;
k /= 10; k /= 10;

View File

@@ -4,33 +4,28 @@
using namespace std; using namespace std;
// Wrapper class for storing an edge // Wrapper class for storing an edge
class Edge class Edge {
{
public: public:
int src, dst, weight; int src, dst, weight;
}; };
// Wrapper class for storing a graph // Wrapper class for storing a graph
class Graph class Graph {
{
public: public:
int vertexNum, edgeNum; int vertexNum, edgeNum;
Edge *edges; Edge *edges;
// Constructs a graph with V vertices and E edges // Constructs a graph with V vertices and E edges
Graph(int V, int E) Graph(int V, int E) {
{
this->vertexNum = V; this->vertexNum = V;
this->edgeNum = E; this->edgeNum = E;
this->edges = (Edge *)malloc(E * sizeof(Edge)); this->edges = (Edge *)malloc(E * sizeof(Edge));
} }
// Adds the given edge to the graph // Adds the given edge to the graph
void addEdge(int src, int dst, int weight) void addEdge(int src, int dst, int weight) {
{
static int edgeInd = 0; static int edgeInd = 0;
if (edgeInd < this->edgeNum) if (edgeInd < this->edgeNum) {
{
Edge newEdge; Edge newEdge;
newEdge.src = src; newEdge.src = src;
newEdge.dst = dst; newEdge.dst = dst;
@@ -41,11 +36,9 @@ class Graph
}; };
// Utility function to print distances // Utility function to print distances
void print(int dist[], int V) void print(int dist[], int V) {
{
cout << "\nVertex Distance" << endl; cout << "\nVertex Distance" << endl;
for (int i = 0; i < V; i++) for (int i = 0; i < V; i++) {
{
if (dist[i] != INT_MAX) if (dist[i] != INT_MAX)
cout << i << "\t" << dist[i] << endl; cout << i << "\t" << dist[i] << endl;
else else
@@ -56,8 +49,7 @@ void print(int dist[], int V)
// The main function that finds the shortest path from given source // The main function that finds the shortest path from given source
// to all other vertices using Bellman-Ford.It also detects negative // to all other vertices using Bellman-Ford.It also detects negative
// weight cycle // weight cycle
void BellmanFord(Graph graph, int src) void BellmanFord(Graph graph, int src) {
{
int V = graph.vertexNum; int V = graph.vertexNum;
int E = graph.edgeNum; int E = graph.edgeNum;
int dist[V]; int dist[V];
@@ -70,8 +62,7 @@ void BellmanFord(Graph graph, int src)
// Calculate shortest path distance from source to all edges // Calculate shortest path distance from source to all edges
// A path can contain maximum (|V|-1) edges // A path can contain maximum (|V|-1) edges
for (int i = 0; i <= V - 1; i++) for (int i = 0; i <= V - 1; i++)
for (int j = 0; j < E; j++) for (int j = 0; j < E; j++) {
{
int u = graph.edges[j].src; int u = graph.edges[j].src;
int v = graph.edges[j].dst; int v = graph.edges[j].dst;
int w = graph.edges[j].weight; int w = graph.edges[j].weight;
@@ -81,14 +72,12 @@ void BellmanFord(Graph graph, int src)
} }
// Iterate inner loop once more to check for negative cycle // Iterate inner loop once more to check for negative cycle
for (int j = 0; j < E; j++) for (int j = 0; j < E; j++) {
{
int u = graph.edges[j].src; int u = graph.edges[j].src;
int v = graph.edges[j].dst; int v = graph.edges[j].dst;
int w = graph.edges[j].weight; int w = graph.edges[j].weight;
if (dist[u] != INT_MAX && dist[u] + w < dist[v]) if (dist[u] != INT_MAX && dist[u] + w < dist[v]) {
{
cout << "Graph contains negative weight cycle. Hence, shortest " cout << "Graph contains negative weight cycle. Hence, shortest "
"distance not guaranteed." "distance not guaranteed."
<< endl; << endl;
@@ -102,8 +91,7 @@ void BellmanFord(Graph graph, int src)
} }
// Driver Function // Driver Function
int main() int main() {
{
int V, E, gsrc; int V, E, gsrc;
int src, dst, weight; int src, dst, weight;
cout << "Enter number of vertices: "; cout << "Enter number of vertices: ";
@@ -111,8 +99,7 @@ int main()
cout << "Enter number of edges: "; cout << "Enter number of edges: ";
cin >> E; cin >> E;
Graph G(V, E); Graph G(V, E);
for (int i = 0; i < E; i++) for (int i = 0; i < E; i++) {
{
cout << "\nEdge " << i + 1 << "\nEnter source: "; cout << "\nEdge " << i + 1 << "\nEnter source: ";
cin >> src; cin >> src;
cout << "Enter destination: "; cout << "Enter destination: ";

View File

@@ -11,8 +11,7 @@ using namespace std;
int *cat; // global array to hold catalan numbers int *cat; // global array to hold catalan numbers
unsigned long int catalan_dp(int n) unsigned long int catalan_dp(int n) {
{
/** Using the tabulation technique in dynamic programming, /** Using the tabulation technique in dynamic programming,
this function computes the first `n+1` Catalan numbers this function computes the first `n+1` Catalan numbers
@@ -29,8 +28,7 @@ unsigned long int catalan_dp(int n)
cat[0] = cat[1] = 1; cat[0] = cat[1] = 1;
// Compute the remaining numbers from index 2 to index n, using tabulation // Compute the remaining numbers from index 2 to index n, using tabulation
for (int i = 2; i <= n; i++) for (int i = 2; i <= n; i++) {
{
cat[i] = 0; cat[i] = 0;
for (int j = 0; j < i; j++) for (int j = 0; j < i; j++)
cat[i] += cat[j] * cat[i - j - 1]; // applying the definition here cat[i] += cat[j] * cat[i - j - 1]; // applying the definition here
@@ -40,8 +38,7 @@ unsigned long int catalan_dp(int n)
return cat[n]; return cat[n];
} }
int main(int argc, char *argv[]) int main(int argc, char *argv[]) {
{
int n; int n;
cout << "Enter n: "; cout << "Enter n: ";
cin >> n; cin >> n;
@@ -49,8 +46,7 @@ int main(int argc, char *argv[])
cat = new int[n + 1]; cat = new int[n + 1];
cout << "Catalan numbers from 0 to " << n << " are:\n"; cout << "Catalan numbers from 0 to " << n << " are:\n";
for (int i = 0; i <= n; i++) for (int i = 0; i <= n; i++) {
{
cout << "catalan (" << i << ") = " << catalan_dp(i) << endl; cout << "catalan (" << i << ") = " << catalan_dp(i) << endl;
// NOTE: Since `cat` is a global array, calling `catalan_dp` // NOTE: Since `cat` is a global array, calling `catalan_dp`
// repeatedly will not recompute the the values already computed // repeatedly will not recompute the the values already computed

View File

@@ -3,8 +3,7 @@
using namespace std; using namespace std;
// Function to find the Minimum number of coins required to get Sum S // Function to find the Minimum number of coins required to get Sum S
int findMinCoins(int arr[], int n, int N) int findMinCoins(int arr[], int n, int N) {
{
// dp[i] = no of coins required to get a total of i // dp[i] = no of coins required to get a total of i
int dp[N + 1]; int dp[N + 1];
@@ -12,15 +11,13 @@ int findMinCoins(int arr[], int n, int N)
dp[0] = 0; dp[0] = 0;
for (int i = 1; i <= N; i++) for (int i = 1; i <= N; i++) {
{
// initialize minimum number of coins needed to infinity // initialize minimum number of coins needed to infinity
dp[i] = INT_MAX; dp[i] = INT_MAX;
int res = INT_MAX; int res = INT_MAX;
// do for each coin // do for each coin
for (int c = 0; c < n; c++) for (int c = 0; c < n; c++) {
{
if (i - arr[c] >= if (i - arr[c] >=
0) // check if coins doesn't become negative by including it 0) // check if coins doesn't become negative by including it
res = dp[i - arr[c]]; res = dp[i - arr[c]];
@@ -36,8 +33,7 @@ int findMinCoins(int arr[], int n, int N)
return dp[N]; return dp[N];
} }
int main() int main() {
{
// No of Coins We Have // No of Coins We Have
int arr[] = {1, 2, 3, 4}; int arr[] = {1, 2, 3, 4};
int n = sizeof(arr) / sizeof(arr[0]); int n = sizeof(arr) / sizeof(arr[0]);

View File

@@ -5,23 +5,19 @@ the pieces.*/
#include <iostream> #include <iostream>
using namespace std; using namespace std;
int cutrod(int p[], int n) int cutrod(int p[], int n) {
{
int r[n + 1]; int r[n + 1];
r[0] = 0; r[0] = 0;
for (int j = 0; j < n; j++) for (int j = 0; j < n; j++) {
{
int q = INT_MIN; int q = INT_MIN;
for (int i = 0; i <= j; i++) for (int i = 0; i <= j; i++) {
{
q = max(q, p[i] + r[j - i]); q = max(q, p[i] + r[j - i]);
} }
r[j + 1] = q; r[j + 1] = q;
} }
return r[n]; return r[n];
} }
int main() int main() {
{
int price[] = {1, 5, 8, 9, 10, 17, 17, 20, 24, 30, 31, 32, 33, 34, 35, int price[] = {1, 5, 8, 9, 10, 17, 17, 20, 24, 30, 31, 32, 33, 34, 35,
36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50}; 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50};
cout << cutrod(price, 30); cout << cutrod(price, 30);

View File

@@ -22,8 +22,7 @@ int min(int x, int y, int z) { return min(min(x, y), z); }
* str1 to str2. * str1 to str2.
* O(3^m) * O(3^m)
*/ */
int editDist(string str1, string str2, int m, int n) int editDist(string str1, string str2, int m, int n) {
{
if (m == 0) if (m == 0)
return n; return n;
if (n == 0) if (n == 0)
@@ -45,16 +44,13 @@ int editDist(string str1, string str2, int m, int n)
/* A DP based program /* A DP based program
* O(m x n) * O(m x n)
*/ */
int editDistDP(string str1, string str2, int m, int n) int editDistDP(string str1, string str2, int m, int n) {
{
// Create Table for SubProblems // Create Table for SubProblems
int dp[m + 1][n + 1]; int dp[m + 1][n + 1];
// Fill d[][] in bottom up manner // Fill d[][] in bottom up manner
for (int i = 0; i <= m; i++) for (int i = 0; i <= m; i++) {
{ for (int j = 0; j <= n; j++) {
for (int j = 0; j <= n; j++)
{
// If str1 empty. Then add all of str2 // If str1 empty. Then add all of str2
if (i == 0) if (i == 0)
dp[i][j] = j; dp[i][j] = j;
@@ -78,8 +74,7 @@ int editDistDP(string str1, string str2, int m, int n)
return dp[m][n]; return dp[m][n];
} }
int main() int main() {
{
string str1 = "sunday"; string str1 = "sunday";
string str2 = "saturday"; string str2 = "saturday";

View File

@@ -6,30 +6,24 @@
#include <iostream> #include <iostream>
using namespace std; using namespace std;
int eggDrop(int n, int k) int eggDrop(int n, int k) {
{
int eggFloor[n + 1][k + 1]; int eggFloor[n + 1][k + 1];
int result; int result;
for (int i = 1; i <= n; i++) for (int i = 1; i <= n; i++) {
{
eggFloor[i][1] = 1; // n eggs..1 Floor eggFloor[i][1] = 1; // n eggs..1 Floor
eggFloor[i][0] = 0; // n eggs..0 Floor eggFloor[i][0] = 0; // n eggs..0 Floor
} }
// Only one egg available // Only one egg available
for (int j = 1; j <= k; j++) for (int j = 1; j <= k; j++) {
{
eggFloor[1][j] = j; eggFloor[1][j] = j;
} }
for (int i = 2; i <= n; i++) for (int i = 2; i <= n; i++) {
{ for (int j = 2; j <= k; j++) {
for (int j = 2; j <= k; j++)
{
eggFloor[i][j] = INT_MAX; eggFloor[i][j] = INT_MAX;
for (int x = 1; x <= j; x++) for (int x = 1; x <= j; x++) {
{
// 1+max(eggBreak[one less egg, lower floors], // 1+max(eggBreak[one less egg, lower floors],
// eggDoesntBreak[same # of eggs, upper floors]); // eggDoesntBreak[same # of eggs, upper floors]);
result = 1 + max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]); result = 1 + max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]);
@@ -42,8 +36,7 @@ int eggDrop(int n, int k)
return eggFloor[n][k]; return eggFloor[n][k];
} }
int main() int main() {
{
int n, k; int n, k;
cout << "Enter number of eggs and floors: "; cout << "Enter number of eggs and floors: ";
cin >> n >> k; cin >> n >> k;

View File

@@ -1,20 +1,17 @@
#include <iostream> #include <iostream>
using namespace std; using namespace std;
int fib(int n) int fib(int n) {
{
int res[3]; int res[3];
res[0] = 0; res[0] = 0;
res[1] = 1; res[1] = 1;
for (int i = 2; i <= n; i++) for (int i = 2; i <= n; i++) {
{
res[2] = res[1] + res[0]; res[2] = res[1] + res[0];
res[0] = res[1]; res[0] = res[1];
res[1] = res[2]; res[1] = res[2];
} }
return res[1]; return res[1];
} }
int main(int argc, char const *argv[]) int main(int argc, char const *argv[]) {
{
int n; int n;
cout << "Enter n: "; cout << "Enter n: ";
cin >> n; cin >> n;

View File

@@ -1,10 +1,8 @@
#include <iostream> #include <iostream>
using namespace std; using namespace std;
int arr[1000000]; int arr[1000000];
int fib(int n) int fib(int n) {
{ if (arr[n] == -1) {
if (arr[n] == -1)
{
if (n <= 1) if (n <= 1)
arr[n] = n; arr[n] = n;
else else
@@ -12,13 +10,11 @@ int fib(int n)
} }
return arr[n]; return arr[n];
} }
int main(int argc, char const *argv[]) int main(int argc, char const *argv[]) {
{
int n; int n;
cout << "Enter n: "; cout << "Enter n: ";
cin >> n; cin >> n;
for (int i = 0; i < n + 1; ++i) for (int i = 0; i < n + 1; ++i) {
{
arr[i] = -1; arr[i] = -1;
} }
cout << "Fibonacci number is " << fib(n) << endl; cout << "Fibonacci number is " << fib(n) << endl;

View File

@@ -1,12 +1,10 @@
#include <climits> #include <climits>
#include <iostream> #include <iostream>
int maxSubArraySum(int a[], int size) int maxSubArraySum(int a[], int size) {
{
int max_so_far = INT_MIN, max_ending_here = 0; int max_so_far = INT_MIN, max_ending_here = 0;
for (int i = 0; i < size; i++) for (int i = 0; i < size; i++) {
{
max_ending_here = max_ending_here + a[i]; max_ending_here = max_ending_here + a[i];
if (max_so_far < max_ending_here) if (max_so_far < max_ending_here)
max_so_far = max_ending_here; max_so_far = max_ending_here;
@@ -17,14 +15,12 @@ int maxSubArraySum(int a[], int size)
return max_so_far; return max_so_far;
} }
int main() int main() {
{
int n, i; int n, i;
std::cout << "Enter the number of elements \n"; std::cout << "Enter the number of elements \n";
std::cin >> n; std::cin >> n;
int a[n]; // NOLINT int a[n]; // NOLINT
for (i = 0; i < n; i++) for (i = 0; i < n; i++) {
{
std::cin >> a[i]; std::cin >> a[i];
} }
int max_sum = maxSubArraySum(a, n); int max_sum = maxSubArraySum(a, n);

View File

@@ -3,8 +3,7 @@ using namespace std;
int max(int a, int b) { return (a > b) ? a : b; } int max(int a, int b) { return (a > b) ? a : b; }
int main() int main() {
{
char str1[] = "DEFBCD"; char str1[] = "DEFBCD";
char str2[] = "ABDEFJ"; char str2[] = "ABDEFJ";
int i, j, k; int i, j, k;
@@ -13,10 +12,8 @@ int main()
// cout<<n<<" "<<m<<"\n"; // cout<<n<<" "<<m<<"\n";
int a[m][n]; int a[m][n];
for (i = 0; i < m; i++) for (i = 0; i < m; i++) {
{ for (j = 0; j < n; j++) {
for (j = 0; j < n; j++)
{
if (i == 0 || j == 0) if (i == 0 || j == 0)
a[i][j] = 0; a[i][j] = 0;
@@ -37,12 +34,9 @@ int main()
int ma = -1; int ma = -1;
int indi, indj; int indi, indj;
for (i = 0; i < m; i++) for (i = 0; i < m; i++) {
{ for (j = 0; j < n; j++) {
for (j = 0; j < n; j++) if (a[i][j] > ma) {
{
if (a[i][j] > ma)
{
ma = a[i][j]; ma = a[i][j];
indi = i; indi = i;
indj = j; indj = j;

View File

@@ -2,69 +2,50 @@
#include <iostream> #include <iostream>
using namespace std; using namespace std;
void Print(int trace[20][20], int m, int n, string a) void Print(int trace[20][20], int m, int n, string a) {
{ if (m == 0 || n == 0) {
if (m == 0 || n == 0)
{
return; return;
} }
if (trace[m][n] == 1) if (trace[m][n] == 1) {
{
Print(trace, m - 1, n - 1, a); Print(trace, m - 1, n - 1, a);
cout << a[m - 1]; cout << a[m - 1];
} } else if (trace[m][n] == 2) {
else if (trace[m][n] == 2)
{
Print(trace, m - 1, n, a); Print(trace, m - 1, n, a);
} } else if (trace[m][n] == 3) {
else if (trace[m][n] == 3)
{
Print(trace, m, n - 1, a); Print(trace, m, n - 1, a);
} }
} }
int lcs(string a, string b) int lcs(string a, string b) {
{
int m = a.length(), n = b.length(); int m = a.length(), n = b.length();
int res[m + 1][n + 1]; int res[m + 1][n + 1];
int trace[20][20]; int trace[20][20];
// fills up the arrays with zeros. // fills up the arrays with zeros.
for (int i = 0; i < m + 1; i++) for (int i = 0; i < m + 1; i++) {
{ for (int j = 0; j < n + 1; j++) {
for (int j = 0; j < n + 1; j++)
{
res[i][j] = 0; res[i][j] = 0;
trace[i][j] = 0; trace[i][j] = 0;
} }
} }
for (int i = 0; i < m + 1; ++i) for (int i = 0; i < m + 1; ++i) {
{ for (int j = 0; j < n + 1; ++j) {
for (int j = 0; j < n + 1; ++j) if (i == 0 || j == 0) {
{
if (i == 0 || j == 0)
{
res[i][j] = 0; res[i][j] = 0;
trace[i][j] = 0; trace[i][j] = 0;
} }
else if (a[i - 1] == b[j - 1]) else if (a[i - 1] == b[j - 1]) {
{
res[i][j] = 1 + res[i - 1][j - 1]; res[i][j] = 1 + res[i - 1][j - 1];
trace[i][j] = 1; // 1 means trace the matrix in upper left trace[i][j] = 1; // 1 means trace the matrix in upper left
// diagonal direction. // diagonal direction.
} } else {
else if (res[i - 1][j] > res[i][j - 1]) {
{
if (res[i - 1][j] > res[i][j - 1])
{
res[i][j] = res[i - 1][j]; res[i][j] = res[i - 1][j];
trace[i][j] = trace[i][j] =
2; // 2 means trace the matrix in upwards direction. 2; // 2 means trace the matrix in upwards direction.
} } else {
else
{
res[i][j] = res[i][j - 1]; res[i][j] = res[i][j - 1];
trace[i][j] = trace[i][j] =
3; // means trace the matrix in left direction. 3; // means trace the matrix in left direction.
@@ -76,8 +57,7 @@ int lcs(string a, string b)
return res[m][n]; return res[m][n];
} }
int main() int main() {
{
string a, b; string a, b;
cin >> a >> b; cin >> a >> b;
cout << lcs(a, b); cout << lcs(a, b);

View File

@@ -1,37 +1,30 @@
// Program to calculate length of longest increasing subsequence in an array // Program to calculate length of longest increasing subsequence in an array
#include <bits/stdc++.h> #include <bits/stdc++.h>
using namespace std; using namespace std;
int LIS(int a[], int n) int LIS(int a[], int n) {
{
int lis[n]; int lis[n];
for (int i = 0; i < n; ++i) for (int i = 0; i < n; ++i) {
{
lis[i] = 1; lis[i] = 1;
} }
for (int i = 0; i < n; ++i) for (int i = 0; i < n; ++i) {
{ for (int j = 0; j < i; ++j) {
for (int j = 0; j < i; ++j)
{
if (a[i] > a[j] && lis[i] < lis[j] + 1) if (a[i] > a[j] && lis[i] < lis[j] + 1)
lis[i] = lis[j] + 1; lis[i] = lis[j] + 1;
} }
} }
int res = 0; int res = 0;
for (int i = 0; i < n; ++i) for (int i = 0; i < n; ++i) {
{
res = max(res, lis[i]); res = max(res, lis[i]);
} }
return res; return res;
} }
int main(int argc, char const *argv[]) int main(int argc, char const *argv[]) {
{
int n; int n;
cout << "Enter size of array: "; cout << "Enter size of array: ";
cin >> n; cin >> n;
int a[n]; int a[n];
cout << "Enter array elements: "; cout << "Enter array elements: ";
for (int i = 0; i < n; ++i) for (int i = 0; i < n; ++i) {
{
cin >> a[i]; cin >> a[i];
} }
cout << LIS(a, n) << endl; cout << LIS(a, n) << endl;

View File

@@ -5,24 +5,19 @@
#include <iostream> #include <iostream>
using namespace std; using namespace std;
int LIS(int arr[], int n) int LIS(int arr[], int n) {
{
set<int> active; // The current built LIS. set<int> active; // The current built LIS.
active.insert(arr[0]); active.insert(arr[0]);
// Loop through every element. // Loop through every element.
for (int i = 1; i < n; ++i) for (int i = 1; i < n; ++i) {
{
auto get = active.lower_bound(arr[i]); auto get = active.lower_bound(arr[i]);
if (get == active.end()) if (get == active.end()) {
{
active.insert(arr[i]); active.insert(arr[i]);
} // current element is the greatest so LIS increases by 1. } // current element is the greatest so LIS increases by 1.
else else {
{
int val = *get; // we find the position where arr[i] will be in the int val = *get; // we find the position where arr[i] will be in the
// LIS. If it is in the LIS already we do nothing // LIS. If it is in the LIS already we do nothing
if (val > arr[i]) if (val > arr[i]) {
{
// else we remove the bigger element and add a smaller element // else we remove the bigger element and add a smaller element
// (which is arr[i]) and continue; // (which is arr[i]) and continue;
active.erase(get); active.erase(get);
@@ -32,15 +27,13 @@ int LIS(int arr[], int n)
} }
return active.size(); // size of the LIS. return active.size(); // size of the LIS.
} }
int main(int argc, char const* argv[]) int main(int argc, char const* argv[]) {
{
int n; int n;
cout << "Enter size of array: "; cout << "Enter size of array: ";
cin >> n; cin >> n;
int a[n]; int a[n];
cout << "Enter array elements: "; cout << "Enter array elements: ";
for (int i = 0; i < n; ++i) for (int i = 0; i < n; ++i) {
{
cin >> a[i]; cin >> a[i];
} }
cout << LIS(a, n) << endl; cout << LIS(a, n) << endl;

View File

@@ -9,8 +9,7 @@ int dp[MAX][MAX];
// Function to find the most efficient way to multiply the given sequence of // Function to find the most efficient way to multiply the given sequence of
// matrices // matrices
int MatrixChainMultiplication(int dim[], int i, int j) int MatrixChainMultiplication(int dim[], int i, int j) {
{
// base case: one matrix // base case: one matrix
if (j <= i + 1) if (j <= i + 1)
return 0; return 0;
@@ -21,13 +20,11 @@ int MatrixChainMultiplication(int dim[], int i, int j)
// if dp[i][j] is not calculated (calculate it!!) // if dp[i][j] is not calculated (calculate it!!)
if (dp[i][j] == 0) if (dp[i][j] == 0) {
{
// take the minimum over each possible position at which the // take the minimum over each possible position at which the
// sequence of matrices can be split // sequence of matrices can be split
for (int k = i + 1; k <= j - 1; k++) for (int k = i + 1; k <= j - 1; k++) {
{
// recur for M[i+1]..M[k] to get a i x k matrix // recur for M[i+1]..M[k] to get a i x k matrix
int cost = MatrixChainMultiplication(dim, i, k); int cost = MatrixChainMultiplication(dim, i, k);
@@ -48,8 +45,7 @@ int MatrixChainMultiplication(int dim[], int i, int j)
} }
// main function // main function
int main() int main() {
{
// Matrix i has Dimensions dim[i-1] & dim[i] for i=1..n // Matrix i has Dimensions dim[i-1] & dim[i] for i=1..n
// input is 10 x 30 matrix, 30 x 5 matrix, 5 x 60 matrix // input is 10 x 30 matrix, 30 x 5 matrix, 5 x 60 matrix
int dim[] = {10, 30, 5, 60}; int dim[] = {10, 30, 5, 60};

View File

@@ -35,8 +35,7 @@
// this is main fuction // this is main fuction
// *** // ***
int main() int main() {
{
int64_t r, mr = 0, x, q, i, z; int64_t r, mr = 0, x, q, i, z;
std::cout << "Enter Number of array you want to Store :"; std::cout << "Enter Number of array you want to Store :";
std::cin >> x; std::cin >> x;
@@ -50,8 +49,7 @@ int main()
int** ar = new int*[x](); int** ar = new int*[x]();
// this for loop is use for entering different variable size array // this for loop is use for entering different variable size array
// *** // ***
for (r = 0; r < x; r++) for (r = 0; r < x; r++) {
{
std::cout << "Enter number of element in " << r + 1 << " rows :"; std::cout << "Enter number of element in " << r + 1 << " rows :";
std::cin >> mr; std::cin >> mr;
// creating a 1D array // creating a 1D array
@@ -59,8 +57,7 @@ int main()
std::cout << "Enter the element of Array "; std::cout << "Enter the element of Array ";
// this for loop is use for storing values in array // this for loop is use for storing values in array
// *** // ***
for (i = 0; i < mr; i++) for (i = 0; i < mr; i++) {
{
// entering the value of rows in array in Horizontal // entering the value of rows in array in Horizontal
std::cin >> ac[i]; std::cin >> ac[i];
} }
@@ -69,8 +66,7 @@ int main()
} }
// this for loop is use for display result of querry // this for loop is use for display result of querry
// *** // ***
for (z = 0; z < q; z++) for (z = 0; z < q; z++) {
{
int64_t r1 = 0, q1 = 0; int64_t r1 = 0, q1 = 0;
std::cout << "enter the number of row which element you want to find :"; std::cout << "enter the number of row which element you want to find :";
std::cin >> r1; std::cin >> r1;

View File

@@ -29,14 +29,11 @@ std::vector<int> adj[MAX];
std::vector<bool> visited; std::vector<bool> visited;
std::vector<int> dp; std::vector<int> dp;
void depth_first_search(int u) void depth_first_search(int u) {
{
visited[u] = true; visited[u] = true;
int child_height = 1; int child_height = 1;
for (int v : adj[u]) for (int v : adj[u]) {
{ if (!visited[v]) {
if (!visited[v])
{
depth_first_search(v); depth_first_search(v);
// select maximum sub-tree height from all children. // select maximum sub-tree height from all children.
@@ -47,8 +44,7 @@ void depth_first_search(int u)
dp[u] = child_height; dp[u] = child_height;
} }
int main() int main() {
{
// number of nodes // number of nodes
int number_of_nodes; int number_of_nodes;
std::cout << "Enter number of nodes of the tree : " << std::endl; std::cout << "Enter number of nodes of the tree : " << std::endl;
@@ -58,8 +54,7 @@ int main()
int u, v; int u, v;
// Tree contains exactly n-1 edges where n denotes the number of nodes. // Tree contains exactly n-1 edges where n denotes the number of nodes.
std::cout << "Enter edges of the tree : " << std::endl; std::cout << "Enter edges of the tree : " << std::endl;
for (int i = 0; i < number_of_nodes - 1; i++) for (int i = 0; i < number_of_nodes - 1; i++) {
{
std::cin >> u >> v; std::cin >> u >> v;
// undirected tree u -> v and v -> u. // undirected tree u -> v and v -> u.
adj[u].push_back(v); adj[u].push_back(v);

View File

@@ -1,7 +1,6 @@
#include <iostream> #include <iostream>
using namespace std; using namespace std;
class graph class graph {
{
int v; int v;
list<int> *adj; list<int> *adj;
@@ -11,56 +10,46 @@ class graph
void printgraph(); void printgraph();
void bfs(int s); void bfs(int s);
}; };
graph::graph(int v) graph::graph(int v) {
{
this->v = v; this->v = v;
this->adj = new list<int>[v]; this->adj = new list<int>[v];
} }
void graph::addedge(int src, int dest) void graph::addedge(int src, int dest) {
{
src--; src--;
dest--; dest--;
adj[src].push_back(dest); adj[src].push_back(dest);
// adj[dest].push_back(src); // adj[dest].push_back(src);
} }
void graph::printgraph() void graph::printgraph() {
{ for (int i = 0; i < this->v; i++) {
for (int i = 0; i < this->v; i++)
{
cout << "Adjacency list of vertex " << i + 1 << " is \n"; cout << "Adjacency list of vertex " << i + 1 << " is \n";
list<int>::iterator it; list<int>::iterator it;
for (it = adj[i].begin(); it != adj[i].end(); ++it) for (it = adj[i].begin(); it != adj[i].end(); ++it) {
{
cout << *it + 1 << " "; cout << *it + 1 << " ";
} }
cout << endl; cout << endl;
} }
} }
void graph::bfs(int s) void graph::bfs(int s) {
{
bool *visited = new bool[this->v + 1]; bool *visited = new bool[this->v + 1];
memset(visited, false, sizeof(bool) * (this->v + 1)); memset(visited, false, sizeof(bool) * (this->v + 1));
visited[s] = true; visited[s] = true;
list<int> q; list<int> q;
q.push_back(s); q.push_back(s);
list<int>::iterator it; list<int>::iterator it;
while (!q.empty()) while (!q.empty()) {
{
int u = q.front(); int u = q.front();
cout << u << " "; cout << u << " ";
q.pop_front(); q.pop_front();
for (it = adj[u].begin(); it != adj[u].end(); ++it) for (it = adj[u].begin(); it != adj[u].end(); ++it) {
{ if (visited[*it] == false) {
if (visited[*it] == false)
{
visited[*it] = true; visited[*it] = true;
q.push_back(*it); q.push_back(*it);
} }
} }
} }
} }
int main() int main() {
{
graph g(4); graph g(4);
g.addedge(1, 2); g.addedge(1, 2);
g.addedge(2, 3); g.addedge(2, 3);

View File

@@ -10,28 +10,22 @@
using std::cout; using std::cout;
using std::min; using std::min;
using std::vector; using std::vector;
class Solution class Solution {
{
vector<vector<int>> graph; vector<vector<int>> graph;
vector<int> in_time, out_time; vector<int> in_time, out_time;
int timer; int timer;
vector<vector<int>> bridge; vector<vector<int>> bridge;
vector<bool> visited; vector<bool> visited;
void dfs(int current_node, int parent) void dfs(int current_node, int parent) {
{
visited.at(current_node) = true; visited.at(current_node) = true;
in_time[current_node] = out_time[current_node] = timer++; in_time[current_node] = out_time[current_node] = timer++;
for (auto& itr : graph[current_node]) for (auto& itr : graph[current_node]) {
{ if (itr == parent) {
if (itr == parent)
{
continue; continue;
} }
if (!visited[itr]) if (!visited[itr]) {
{
dfs(itr, current_node); dfs(itr, current_node);
if (out_time[itr] > in_time[current_node]) if (out_time[itr] > in_time[current_node]) {
{
bridge.push_back({itr, current_node}); bridge.push_back({itr, current_node});
} }
} }
@@ -41,15 +35,13 @@ class Solution
public: public:
vector<vector<int>> search_bridges(int n, vector<vector<int>> search_bridges(int n,
const vector<vector<int>>& connections) const vector<vector<int>>& connections) {
{
timer = 0; timer = 0;
graph.resize(n); graph.resize(n);
in_time.assign(n, 0); in_time.assign(n, 0);
visited.assign(n, false); visited.assign(n, false);
out_time.assign(n, 0); out_time.assign(n, 0);
for (auto& itr : connections) for (auto& itr : connections) {
{
graph.at(itr[0]).push_back(itr[1]); graph.at(itr[0]).push_back(itr[1]);
graph.at(itr[1]).push_back(itr[0]); graph.at(itr[1]).push_back(itr[0]);
} }
@@ -57,8 +49,7 @@ class Solution
return bridge; return bridge;
} }
}; };
int main(void) int main(void) {
{
Solution s1; Solution s1;
int number_of_node = 5; int number_of_node = 5;
vector<vector<int>> node; vector<vector<int>> node;
@@ -81,8 +72,7 @@ int main(void)
*/ */
vector<vector<int>> bridges = s1.search_bridges(number_of_node, node); vector<vector<int>> bridges = s1.search_bridges(number_of_node, node);
cout << bridges.size() << " bridges found!\n"; cout << bridges.size() << " bridges found!\n";
for (auto& itr : bridges) for (auto& itr : bridges) {
{
cout << itr[0] << " --> " << itr[1] << '\n'; cout << itr[0] << " --> " << itr[1] << '\n';
} }
return 0; return 0;

View File

@@ -3,8 +3,7 @@
using std::vector; using std::vector;
class graph class graph {
{
private: private:
vector<vector<int>> adj; vector<vector<int>> adj;
int connected_components; int connected_components;
@@ -14,48 +13,39 @@ class graph
public: public:
explicit graph(int n) : adj(n, vector<int>()) { connected_components = 0; } explicit graph(int n) : adj(n, vector<int>()) { connected_components = 0; }
void addEdge(int, int); void addEdge(int, int);
int getConnectedComponents() int getConnectedComponents() {
{
depth_first_search(); depth_first_search();
return connected_components; return connected_components;
} }
}; };
void graph::addEdge(int u, int v) void graph::addEdge(int u, int v) {
{
adj[u - 1].push_back(v - 1); adj[u - 1].push_back(v - 1);
adj[v - 1].push_back(u - 1); adj[v - 1].push_back(u - 1);
} }
void graph::depth_first_search() void graph::depth_first_search() {
{
int n = adj.size(); int n = adj.size();
vector<bool> visited(n, false); vector<bool> visited(n, false);
for (int i = 0; i < n; i++) for (int i = 0; i < n; i++) {
{ if (!visited[i]) {
if (!visited[i])
{
explore(i, visited); explore(i, visited);
connected_components++; connected_components++;
} }
} }
} }
void graph::explore(int u, vector<bool> &visited) void graph::explore(int u, vector<bool> &visited) {
{
visited[u] = true; visited[u] = true;
for (auto v : adj[u]) for (auto v : adj[u]) {
{ if (!visited[v]) {
if (!visited[v])
{
explore(v, visited); explore(v, visited);
} }
} }
} }
int main() int main() {
{
graph g(4); graph g(4);
g.addEdge(1, 2); g.addEdge(1, 2);
g.addEdge(3, 2); g.addEdge(3, 2);

View File

@@ -5,28 +5,23 @@
int N; // denotes number of nodes; int N; // denotes number of nodes;
std::vector<int> parent; std::vector<int> parent;
std::vector<int> siz; std::vector<int> siz;
void make_set() void make_set() { // function the initialize every node as it's own parent
{ // function the initialize every node as it's own parent for (int i = 1; i <= N; i++) {
for (int i = 1; i <= N; i++)
{
parent[i] = i; parent[i] = i;
siz[i] = 1; siz[i] = 1;
} }
} }
// To find the component where following node belongs to // To find the component where following node belongs to
int find_set(int v) int find_set(int v) {
{
if (v == parent[v]) if (v == parent[v])
return v; return v;
return parent[v] = find_set(parent[v]); return parent[v] = find_set(parent[v]);
} }
void union_sets(int a, int b) void union_sets(int a, int b) { // To join 2 components to belong to one
{ // To join 2 components to belong to one
a = find_set(a); a = find_set(a);
b = find_set(b); b = find_set(b);
if (a != b) if (a != b) {
{
if (siz[a] < siz[b]) if (siz[a] < siz[b])
std::swap(a, b); std::swap(a, b);
parent[b] = a; parent[b] = a;
@@ -34,8 +29,7 @@ void union_sets(int a, int b)
} }
} }
int no_of_connected_components() int no_of_connected_components() { // To find total no of connected components
{ // To find total no of connected components
std::set<int> temp; // temp set to count number of connected components std::set<int> temp; // temp set to count number of connected components
for (int i = 1; i <= N; i++) temp.insert(find_set(i)); for (int i = 1; i <= N; i++) temp.insert(find_set(i));
return temp.size(); return temp.size();
@@ -43,16 +37,14 @@ int no_of_connected_components()
// All critical/corner cases have been taken care of. // All critical/corner cases have been taken care of.
// Input your required values: (not hardcoded) // Input your required values: (not hardcoded)
int main() int main() {
{
std::cin >> N; std::cin >> N;
parent.resize(N + 1); parent.resize(N + 1);
siz.resize(N + 1); siz.resize(N + 1);
make_set(); make_set();
int edges; int edges;
std::cin >> edges; // no of edges in the graph std::cin >> edges; // no of edges in the graph
while (edges--) while (edges--) {
{
int node_a, node_b; int node_a, node_b;
std::cin >> node_a >> node_b; std::cin >> node_a >> node_b;
union_sets(node_a, node_b); union_sets(node_a, node_b);

View File

@@ -1,28 +1,23 @@
#include <iostream> #include <iostream>
using namespace std; using namespace std;
int v = 4; int v = 4;
void DFSUtil_(int graph[4][4], bool visited[], int s) void DFSUtil_(int graph[4][4], bool visited[], int s) {
{
visited[s] = true; visited[s] = true;
cout << s << " "; cout << s << " ";
for (int i = 0; i < v; i++) for (int i = 0; i < v; i++) {
{ if (graph[s][i] == 1 && visited[i] == false) {
if (graph[s][i] == 1 && visited[i] == false)
{
DFSUtil_(graph, visited, i); DFSUtil_(graph, visited, i);
} }
} }
} }
void DFS_(int graph[4][4], int s) void DFS_(int graph[4][4], int s) {
{
bool visited[v]; bool visited[v];
memset(visited, 0, sizeof(visited)); memset(visited, 0, sizeof(visited));
DFSUtil_(graph, visited, s); DFSUtil_(graph, visited, s);
} }
int main() int main() {
{
int graph[4][4] = {{0, 1, 1, 0}, {0, 0, 1, 0}, {1, 0, 0, 1}, {0, 0, 0, 1}}; int graph[4][4] = {{0, 1, 1, 0}, {0, 0, 1, 0}, {1, 0, 0, 1}, {0, 0, 0, 1}};
cout << "DFS: "; cout << "DFS: ";
DFS_(graph, 2); DFS_(graph, 2);

View File

@@ -11,8 +11,7 @@ using namespace std;
int checked[999] = {WHITE}; int checked[999] = {WHITE};
void dfs(const list<int> lista[], int start) void dfs(const list<int> lista[], int start) {
{
stack<int> stack; stack<int> stack;
int checked[999] = {WHITE}; int checked[999] = {WHITE};
@@ -20,33 +19,28 @@ void dfs(const list<int> lista[], int start)
stack.push(start); stack.push(start);
checked[start] = GREY; checked[start] = GREY;
while (!stack.empty()) while (!stack.empty()) {
{
int act = stack.top(); int act = stack.top();
stack.pop(); stack.pop();
if (checked[act] == GREY) if (checked[act] == GREY) {
{
cout << act << ' '; cout << act << ' ';
for (auto it = lista[act].begin(); it != lista[act].end(); ++it) for (auto it = lista[act].begin(); it != lista[act].end(); ++it) {
{
stack.push(*it); stack.push(*it);
if (checked[*it] != BLACK) if (checked[*it] != BLACK)
checked[*it] = GREY; checked[*it] = GREY;
} }
checked[act] = BLACK; //nodo controllato checked[act] = BLACK; // nodo controllato
} }
} }
} }
int main() int main() {
{
int u, w; int u, w;
int n; int n;
cin >> n; cin >> n;
list<int> lista[INF]; list<int> lista[INF];
for (int i = 0; i < n; ++i) for (int i = 0; i < n; ++i) {
{
cin >> u >> w; cin >> u >> w;
lista[u].push_back(w); lista[u].push_back(w);
} }

View File

@@ -6,8 +6,7 @@ using namespace std;
#define INF 10000010 #define INF 10000010
vector<pair<int, int>> graph[5 * 100001]; vector<pair<int, int>> graph[5 * 100001];
int dis[5 * 100001]; int dis[5 * 100001];
int dij(vector<pair<int, int>> *v, int s, int *dis) int dij(vector<pair<int, int>> *v, int s, int *dis) {
{
priority_queue<pair<int, int>, vector<pair<int, int>>, priority_queue<pair<int, int>, vector<pair<int, int>>,
greater<pair<int, int>>> greater<pair<int, int>>>
pq; pq;
@@ -15,28 +14,23 @@ int dij(vector<pair<int, int>> *v, int s, int *dis)
pq.push(make_pair(0, s)); pq.push(make_pair(0, s));
dis[s] = 0; dis[s] = 0;
int u; int u;
while (!pq.empty()) while (!pq.empty()) {
{
u = (pq.top()).second; u = (pq.top()).second;
pq.pop(); pq.pop();
for (vector<pair<int, int>>::iterator it = v[u].begin(); for (vector<pair<int, int>>::iterator it = v[u].begin();
it != v[u].end(); it++) it != v[u].end(); it++) {
{ if (dis[u] + it->first < dis[it->second]) {
if (dis[u] + it->first < dis[it->second])
{
dis[it->second] = dis[u] + it->first; dis[it->second] = dis[u] + it->first;
pq.push(make_pair(dis[it->second], it->second)); pq.push(make_pair(dis[it->second], it->second));
} }
} }
} }
} }
int main() int main() {
{
int m, n, l, x, y, s; int m, n, l, x, y, s;
// n--> number of nodes , m --> number of edges // n--> number of nodes , m --> number of edges
cin >> n >> m; cin >> n >> m;
for (int i = 0; i < m; i++) for (int i = 0; i < m; i++) {
{
// input edges. // input edges.
scanf("%d%d%d", &x, &y, &l); scanf("%d%d%d", &x, &y, &l);
graph[x].push_back(make_pair(l, y)); graph[x].push_back(make_pair(l, y));

View File

@@ -13,10 +13,8 @@ using namespace std;
* @param V : vertices * @param V : vertices
* @return void * @return void
**/ **/
void print(vector<int> a[], int V) void print(vector<int> a[], int V) {
{ for (int i = 0; i < V; i++) {
for (int i = 0; i < V; i++)
{
if (!a[i].empty()) if (!a[i].empty())
cout << "i=" << i << "-->"; cout << "i=" << i << "-->";
for (int j = 0; j < a[i].size(); j++) cout << a[i][j] << " "; for (int j = 0; j < a[i].size(); j++) cout << a[i][j] << " ";
@@ -33,11 +31,9 @@ void print(vector<int> a[], int V)
* @param adj[] : array of vectors to represent graph * @param adj[] : array of vectors to represent graph
* @return void * @return void
**/ **/
void push_vertex(int v, stack<int> &st, bool vis[], vector<int> adj[]) void push_vertex(int v, stack<int> &st, bool vis[], vector<int> adj[]) {
{
vis[v] = true; vis[v] = true;
for (auto i = adj[v].begin(); i != adj[v].end(); i++) for (auto i = adj[v].begin(); i != adj[v].end(); i++) {
{
if (vis[*i] == false) if (vis[*i] == false)
push_vertex(*i, st, vis, adj); push_vertex(*i, st, vis, adj);
} }
@@ -51,12 +47,10 @@ void push_vertex(int v, stack<int> &st, bool vis[], vector<int> adj[])
* @param grev[] : graph with reversed edges * @param grev[] : graph with reversed edges
* @return void * @return void
**/ **/
void dfs(int v, bool vis[], vector<int> grev[]) void dfs(int v, bool vis[], vector<int> grev[]) {
{
vis[v] = true; vis[v] = true;
// cout<<v<<" "; // cout<<v<<" ";
for (auto i = grev[v].begin(); i != grev[v].end(); i++) for (auto i = grev[v].begin(); i != grev[v].end(); i++) {
{
if (vis[*i] == false) if (vis[*i] == false)
dfs(*i, vis, grev); dfs(*i, vis, grev);
} }
@@ -72,21 +66,17 @@ no SCCs i.e. none(0) or there will be x no. of SCCs (x>0)) i.e. it returns the
count of (number of) strongly connected components (SCCs) in the graph. count of (number of) strongly connected components (SCCs) in the graph.
(variable 'count_scc' within function) (variable 'count_scc' within function)
**/ **/
int kosaraju(int V, vector<int> adj[]) int kosaraju(int V, vector<int> adj[]) {
{
bool vis[V] = {}; bool vis[V] = {};
stack<int> st; stack<int> st;
for (int v = 0; v < V; v++) for (int v = 0; v < V; v++) {
{
if (vis[v] == false) if (vis[v] == false)
push_vertex(v, st, vis, adj); push_vertex(v, st, vis, adj);
} }
// making new graph (grev) with reverse edges as in adj[]: // making new graph (grev) with reverse edges as in adj[]:
vector<int> grev[V]; vector<int> grev[V];
for (int i = 0; i < V + 1; i++) for (int i = 0; i < V + 1; i++) {
{ for (auto j = adj[i].begin(); j != adj[i].end(); j++) {
for (auto j = adj[i].begin(); j != adj[i].end(); j++)
{
grev[*j].push_back(i); grev[*j].push_back(i);
} }
} }
@@ -95,12 +85,10 @@ int kosaraju(int V, vector<int> adj[])
// reinitialise visited to 0 // reinitialise visited to 0
for (int i = 0; i < V; i++) vis[i] = false; for (int i = 0; i < V; i++) vis[i] = false;
int count_scc = 0; int count_scc = 0;
while (!st.empty()) while (!st.empty()) {
{
int t = st.top(); int t = st.top();
st.pop(); st.pop();
if (vis[t] == false) if (vis[t] == false) {
{
dfs(t, vis, grev); dfs(t, vis, grev);
count_scc++; count_scc++;
} }
@@ -112,12 +100,10 @@ int kosaraju(int V, vector<int> adj[])
// All critical/corner cases have been taken care of. // All critical/corner cases have been taken care of.
// Input your required values: (not hardcoded) // Input your required values: (not hardcoded)
int main() int main() {
{
int t; int t;
cin >> t; cin >> t;
while (t--) while (t--) {
{
int a, b; // a->number of nodes, b->directed edges. int a, b; // a->number of nodes, b->directed edges.
cin >> a >> b; cin >> a >> b;
int m, n; int m, n;

View File

@@ -24,47 +24,39 @@ typedef long long ll;
cin.tie(NULL); \ cin.tie(NULL); \
cout.tie(NULL); cout.tie(NULL);
using namespace std; using namespace std;
void in(int &x) void in(int &x) {
{
register int c = gc(); register int c = gc();
x = 0; x = 0;
int neg = 0; int neg = 0;
for (; ((c < 48 || c > 57) && c != '-'); c = gc()) for (; ((c < 48 || c > 57) && c != '-'); c = gc())
; ;
if (c == '-') if (c == '-') {
{
neg = 1; neg = 1;
c = gc(); c = gc();
} }
for (; c > 47 && c < 58; c = gc()) for (; c > 47 && c < 58; c = gc()) {
{
x = (x << 1) + (x << 3) + c - 48; x = (x << 1) + (x << 3) + c - 48;
} }
if (neg) if (neg)
x = -x; x = -x;
} }
void out(int n) void out(int n) {
{
int N = n, rev, count = 0; int N = n, rev, count = 0;
rev = N; rev = N;
if (N == 0) if (N == 0) {
{
pc('0'); pc('0');
return; return;
} }
while ((rev % 10) == 0) while ((rev % 10) == 0) {
{
count++; count++;
rev /= 10; rev /= 10;
} }
rev = 0; rev = 0;
while (N != 0) while (N != 0) {
{
rev = (rev << 3) + (rev << 1) + N % 10; rev = (rev << 3) + (rev << 1) + N % 10;
N /= 10; N /= 10;
} }
while (rev != 0) while (rev != 0) {
{
pc(rev % 10 + '0'); pc(rev % 10 + '0');
rev /= 10; rev /= 10;
} }
@@ -72,53 +64,43 @@ void out(int n)
} }
ll parent[mx], arr[mx], node, edge; ll parent[mx], arr[mx], node, edge;
vector<pair<ll, pair<ll, ll>>> v; vector<pair<ll, pair<ll, ll>>> v;
void initial() void initial() {
{
int i; int i;
rep(i, node + edge) parent[i] = i; rep(i, node + edge) parent[i] = i;
} }
int root(int i) int root(int i) {
{ while (parent[i] != i) {
while (parent[i] != i)
{
parent[i] = parent[parent[i]]; parent[i] = parent[parent[i]];
i = parent[i]; i = parent[i];
} }
return i; return i;
} }
void join(int x, int y) void join(int x, int y) {
{
int root_x = root(x); // Disjoint set union by rank int root_x = root(x); // Disjoint set union by rank
int root_y = root(y); int root_y = root(y);
parent[root_x] = root_y; parent[root_x] = root_y;
} }
ll kruskal() ll kruskal() {
{
ll mincost = 0, i, x, y; ll mincost = 0, i, x, y;
rep(i, edge) rep(i, edge) {
{
x = v[i].second.first; x = v[i].second.first;
y = v[i].second.second; y = v[i].second.second;
if (root(x) != root(y)) if (root(x) != root(y)) {
{
mincost += v[i].first; mincost += v[i].first;
join(x, y); join(x, y);
} }
} }
return mincost; return mincost;
} }
int main() int main() {
{
fast; fast;
while (1) while (1) {
{
int i, j, from, to, cost, totalcost = 0; int i, j, from, to, cost, totalcost = 0;
cin >> node >> edge; // Enter the nodes and edges cin >> node >> edge; // Enter the nodes and edges
if (node == 0 && edge == 0) if (node == 0 && edge == 0)
break; // Enter 0 0 to break out break; // Enter 0 0 to break out
initial(); // Initialise the parent array initial(); // Initialise the parent array
rep(i, edge) rep(i, edge) {
{
cin >> from >> to >> cost; cin >> from >> to >> cost;
v.pb(mp(cost, mp(from, to))); v.pb(mp(cost, mp(from, to)));
totalcost += cost; totalcost += cost;

View File

@@ -7,19 +7,16 @@ using namespace std;
// Resource : https://cp-algorithms.com/graph/lca_binary_lifting.html // Resource : https://cp-algorithms.com/graph/lca_binary_lifting.html
const int N = 1005; const int N = 1005;
const int LG = log2(N) + 1; const int LG = log2(N) + 1;
struct lca struct lca {
{
int n; int n;
vector<int> adj[N]; // Graph vector<int> adj[N]; // Graph
int up[LG][N]; // build this table int up[LG][N]; // build this table
int level[N]; // get the levels of all of them int level[N]; // get the levels of all of them
lca(int n_) : n(n_) lca(int n_) : n(n_) {
{
memset(up, -1, sizeof(up)); memset(up, -1, sizeof(up));
memset(level, 0, sizeof(level)); memset(level, 0, sizeof(level));
for (int i = 0; i < n - 1; ++i) for (int i = 0; i < n - 1; ++i) {
{
int a, b; int a, b;
cin >> a >> b; cin >> a >> b;
a--; a--;
@@ -31,77 +28,59 @@ struct lca
dfs(0, -1); dfs(0, -1);
build(); build();
} }
void verify() void verify() {
{ for (int i = 0; i < n; ++i) {
for (int i = 0; i < n; ++i)
{
cout << i << " : level: " << level[i] << endl; cout << i << " : level: " << level[i] << endl;
} }
cout << endl; cout << endl;
for (int i = 0; i < LG; ++i) for (int i = 0; i < LG; ++i) {
{
cout << "Power:" << i << ": "; cout << "Power:" << i << ": ";
for (int j = 0; j < n; ++j) for (int j = 0; j < n; ++j) {
{
cout << up[i][j] << " "; cout << up[i][j] << " ";
} }
cout << endl; cout << endl;
} }
} }
void build() void build() {
{ for (int i = 1; i < LG; ++i) {
for (int i = 1; i < LG; ++i) for (int j = 0; j < n; ++j) {
{ if (up[i - 1][j] != -1) {
for (int j = 0; j < n; ++j)
{
if (up[i - 1][j] != -1)
{
up[i][j] = up[i - 1][up[i - 1][j]]; up[i][j] = up[i - 1][up[i - 1][j]];
} }
} }
} }
} }
void dfs(int node, int par) void dfs(int node, int par) {
{
up[0][node] = par; up[0][node] = par;
for (auto i : adj[node]) for (auto i : adj[node]) {
{ if (i != par) {
if (i != par)
{
level[i] = level[node] + 1; level[i] = level[node] + 1;
dfs(i, node); dfs(i, node);
} }
} }
} }
int query(int u, int v) int query(int u, int v) {
{
u--; u--;
v--; v--;
if (level[v] > level[u]) if (level[v] > level[u]) {
{
swap(u, v); swap(u, v);
} }
// u is at the bottom. // u is at the bottom.
int dist = level[u] - level[v]; int dist = level[u] - level[v];
// Go up this much distance // Go up this much distance
for (int i = LG - 1; i >= 0; --i) for (int i = LG - 1; i >= 0; --i) {
{ if (dist & (1 << i)) {
if (dist & (1 << i))
{
u = up[i][u]; u = up[i][u];
} }
} }
if (u == v) if (u == v) {
{
return u; return u;
} }
assert(level[u] == level[v]); assert(level[u] == level[v]);
for (int i = LG - 1; i >= 0; --i) for (int i = LG - 1; i >= 0; --i) {
{ if (up[i][u] != up[i][v]) {
if (up[i][u] != up[i][v])
{
u = up[i][u]; u = up[i][u];
v = up[i][v]; v = up[i][v];
} }
@@ -111,8 +90,7 @@ struct lca
} }
}; };
int main() int main() {
{
int n; // number of nodes in the tree. int n; // number of nodes in the tree.
lca l(n); // will take the input in the format given lca l(n); // will take the input in the format given
// n-1 edges of the form // n-1 edges of the form

View File

@@ -15,8 +15,7 @@
#include <vector> #include <vector>
// std::max capacity of node in graph // std::max capacity of node in graph
const int MAXN = 505; const int MAXN = 505;
class Graph class Graph {
{
int residual_capacity[MAXN][MAXN]; int residual_capacity[MAXN][MAXN];
int capacity[MAXN][MAXN]; // used while checking the flow of edge int capacity[MAXN][MAXN]; // used while checking the flow of edge
int total_nodes; int total_nodes;
@@ -25,26 +24,21 @@ class Graph
std::vector<std::tuple<int, int, int> > edge_participated; std::vector<std::tuple<int, int, int> > edge_participated;
std::bitset<MAXN> visited; std::bitset<MAXN> visited;
int max_flow = 0; int max_flow = 0;
bool bfs(int source, int sink) bool bfs(int source, int sink) { // to find the augmented - path
{ // to find the augmented - path
memset(parent, -1, sizeof(parent)); memset(parent, -1, sizeof(parent));
visited.reset(); visited.reset();
std::queue<int> q; std::queue<int> q;
q.push(source); q.push(source);
bool is_path_found = false; bool is_path_found = false;
while (q.empty() == false && is_path_found == false) while (q.empty() == false && is_path_found == false) {
{
int current_node = q.front(); int current_node = q.front();
visited.set(current_node); visited.set(current_node);
q.pop(); q.pop();
for (int i = 0; i < total_nodes; ++i) for (int i = 0; i < total_nodes; ++i) {
{ if (residual_capacity[current_node][i] > 0 && !visited[i]) {
if (residual_capacity[current_node][i] > 0 && !visited[i])
{
visited.set(i); visited.set(i);
parent[i] = current_node; parent[i] = current_node;
if (i == sink) if (i == sink) {
{
return true; return true;
} }
q.push(i); q.push(i);
@@ -56,32 +50,26 @@ class Graph
public: public:
Graph() { memset(residual_capacity, 0, sizeof(residual_capacity)); } Graph() { memset(residual_capacity, 0, sizeof(residual_capacity)); }
void set_graph(void) void set_graph(void) {
{
std::cin >> total_nodes >> total_edges >> source >> sink; std::cin >> total_nodes >> total_edges >> source >> sink;
for (int start, destination, capacity_, i = 0; i < total_edges; ++i) for (int start, destination, capacity_, i = 0; i < total_edges; ++i) {
{
std::cin >> start >> destination >> capacity_; std::cin >> start >> destination >> capacity_;
residual_capacity[start][destination] = capacity_; residual_capacity[start][destination] = capacity_;
capacity[start][destination] = capacity_; capacity[start][destination] = capacity_;
} }
} }
void ford_fulkerson(void) void ford_fulkerson(void) {
{ while (bfs(source, sink)) {
while (bfs(source, sink))
{
int current_node = sink; int current_node = sink;
int flow = std::numeric_limits<int>::max(); int flow = std::numeric_limits<int>::max();
while (current_node != source) while (current_node != source) {
{
int parent_ = parent[current_node]; int parent_ = parent[current_node];
flow = std::min(flow, residual_capacity[parent_][current_node]); flow = std::min(flow, residual_capacity[parent_][current_node]);
current_node = parent_; current_node = parent_;
} }
current_node = sink; current_node = sink;
max_flow += flow; max_flow += flow;
while (current_node != source) while (current_node != source) {
{
int parent_ = parent[current_node]; int parent_ = parent[current_node];
residual_capacity[parent_][current_node] -= flow; residual_capacity[parent_][current_node] -= flow;
residual_capacity[current_node][parent_] += flow; residual_capacity[current_node][parent_] += flow;
@@ -89,14 +77,11 @@ class Graph
} }
} }
} }
void print_flow_info(void) void print_flow_info(void) {
{ for (int i = 0; i < total_nodes; ++i) {
for (int i = 0; i < total_nodes; ++i) for (int j = 0; j < total_nodes; ++j) {
{ if (capacity[i][j] &&
for (int j = 0; j < total_nodes; ++j) residual_capacity[i][j] < capacity[i][j]) {
{
if (capacity[i][j] && residual_capacity[i][j] < capacity[i][j])
{
edge_participated.push_back(std::make_tuple( edge_participated.push_back(std::make_tuple(
i, j, capacity[i][j] - residual_capacity[i][j])); i, j, capacity[i][j] - residual_capacity[i][j]));
} }
@@ -106,8 +91,7 @@ class Graph
<< "\nEdge present in flow: " << edge_participated.size() << "\nEdge present in flow: " << edge_participated.size()
<< '\n'; << '\n';
std::cout << "\nSource\tDestination\tCapacity\total_nodes"; std::cout << "\nSource\tDestination\tCapacity\total_nodes";
for (auto& edge_data : edge_participated) for (auto& edge_data : edge_participated) {
{
int source, destination, capacity_; int source, destination, capacity_;
std::tie(source, destination, capacity_) = edge_data; std::tie(source, destination, capacity_) = edge_data;
std::cout << source << "\t" << destination << "\t\t" << capacity_ std::cout << source << "\t" << destination << "\t\t" << capacity_
@@ -115,8 +99,7 @@ class Graph
} }
} }
}; };
int main(void) int main(void) {
{
/* /*
Input Graph: (for testing ) Input Graph: (for testing )
4 5 0 3 4 5 0 3

View File

@@ -9,8 +9,7 @@ typedef std::pair<int, int> PII;
bool marked[MAX]; bool marked[MAX];
std::vector<PII> adj[MAX]; std::vector<PII> adj[MAX];
int prim(int x) int prim(int x) {
{
// priority queue to maintain edges with respect to weights // priority queue to maintain edges with respect to weights
std::priority_queue<PII, std::vector<PII>, std::greater<PII> > Q; std::priority_queue<PII, std::vector<PII>, std::greater<PII> > Q;
int y; int y;
@@ -18,8 +17,7 @@ int prim(int x)
PII p; PII p;
Q.push(std::make_pair(0, x)); Q.push(std::make_pair(0, x));
while (!Q.empty()) while (!Q.empty()) {
{
// Select the edge with minimum weight // Select the edge with minimum weight
p = Q.top(); p = Q.top();
Q.pop(); Q.pop();
@@ -29,8 +27,7 @@ int prim(int x)
continue; continue;
minimumCost += p.first; minimumCost += p.first;
marked[x] = true; marked[x] = true;
for (int i = 0; i < adj[x].size(); ++i) for (int i = 0; i < adj[x].size(); ++i) {
{
y = adj[x][i].second; y = adj[x][i].second;
if (marked[y] == false) if (marked[y] == false)
Q.push(adj[x][i]); Q.push(adj[x][i]);
@@ -39,8 +36,7 @@ int prim(int x)
return minimumCost; return minimumCost;
} }
int main() int main() {
{
int nodes, edges, x, y; int nodes, edges, x, y;
int weight, minimumCost; int weight, minimumCost;
@@ -49,8 +45,7 @@ int main()
return 0; return 0;
// Edges with their nodes & weight // Edges with their nodes & weight
for (int i = 0; i < edges; ++i) for (int i = 0; i < edges; ++i) {
{
std::cin >> x >> y >> weight; std::cin >> x >> y >> weight;
adj[x].push_back(std::make_pair(weight, y)); adj[x].push_back(std::make_pair(weight, y));
adj[y].push_back(std::make_pair(weight, x)); adj[y].push_back(std::make_pair(weight, x));

View File

@@ -8,44 +8,37 @@ vector<vector<int>> G;
vector<bool> visited; vector<bool> visited;
vector<int> ans; vector<int> ans;
void dfs(int v) void dfs(int v) {
{
visited[v] = true; visited[v] = true;
for (int u : G[v]) for (int u : G[v]) {
{
if (!visited[u]) if (!visited[u])
dfs(u); dfs(u);
} }
ans.push_back(v); ans.push_back(v);
} }
void topological_sort() void topological_sort() {
{
visited.assign(n, false); visited.assign(n, false);
ans.clear(); ans.clear();
for (int i = 0; i < n; ++i) for (int i = 0; i < n; ++i) {
{
if (!visited[i]) if (!visited[i])
dfs(i); dfs(i);
} }
reverse(ans.begin(), ans.end()); reverse(ans.begin(), ans.end());
} }
int main() int main() {
{
cout << "Enter the number of vertices and the number of directed edges\n"; cout << "Enter the number of vertices and the number of directed edges\n";
cin >> n >> m; cin >> n >> m;
int x, y; int x, y;
G.resize(n, vector<int>()); G.resize(n, vector<int>());
for (int i = 0; i < n; ++i) for (int i = 0; i < n; ++i) {
{
cin >> x >> y; cin >> x >> y;
x--, y--; // to convert 1-indexed to 0-indexed x--, y--; // to convert 1-indexed to 0-indexed
G[x].push_back(y); G[x].push_back(y);
} }
topological_sort(); topological_sort();
cout << "Topological Order : \n"; cout << "Topological Order : \n";
for (int v : ans) for (int v : ans) {
{
cout << v + 1 cout << v + 1
<< ' '; // converting zero based indexing back to one based. << ' '; // converting zero based indexing back to one based.
} }

View File

@@ -6,8 +6,7 @@
int *topoSortKahn(int N, std::vector<int> adj[]); int *topoSortKahn(int N, std::vector<int> adj[]);
int main() int main() {
{
int nodes, edges; int nodes, edges;
std::cin >> edges >> nodes; std::cin >> edges >> nodes;
if (edges == 0 || nodes == 0) if (edges == 0 || nodes == 0)
@@ -20,36 +19,29 @@ int main()
// 6 6 // 6 6
// 5 0 5 2 2 3 4 0 4 1 1 3 // 5 0 5 2 2 3 4 0 4 1 1 3
for (int i = 0; i < edges; i++) for (int i = 0; i < edges; i++) {
{
std::cin >> u >> v; std::cin >> u >> v;
graph[u].push_back(v); graph[u].push_back(v);
} }
int *topo = topoSortKahn(nodes, graph); int *topo = topoSortKahn(nodes, graph);
// topologically sorted nodes // topologically sorted nodes
for (int i = 0; i < nodes; i++) for (int i = 0; i < nodes; i++) {
{
std::cout << topo[i] << " "; std::cout << topo[i] << " ";
} }
} }
int *topoSortKahn(int V, std::vector<int> adj[]) int *topoSortKahn(int V, std::vector<int> adj[]) {
{
std::vector<bool> vis(V + 1, false); std::vector<bool> vis(V + 1, false);
std::vector<int> deg(V + 1, 0); std::vector<int> deg(V + 1, 0);
for (int i = 0; i < V; i++) for (int i = 0; i < V; i++) {
{ for (int j = 0; j < adj[i].size(); j++) {
for (int j = 0; j < adj[i].size(); j++)
{
deg[adj[i][j]]++; deg[adj[i][j]]++;
} }
} }
std::queue<int> q; std::queue<int> q;
for (int i = 0; i < V; i++) for (int i = 0; i < V; i++) {
{ if (deg[i] == 0) {
if (deg[i] == 0)
{
q.push(i); q.push(i);
vis[i] = true; vis[i] = true;
} }
@@ -57,19 +49,15 @@ int *topoSortKahn(int V, std::vector<int> adj[])
int *arr = new int[V + 1]; int *arr = new int[V + 1];
memset(arr, 0, V + 1); memset(arr, 0, V + 1);
int count = 0; int count = 0;
while (!q.empty()) while (!q.empty()) {
{
int cur = q.front(); int cur = q.front();
q.pop(); q.pop();
arr[count] = cur; arr[count] = cur;
count++; count++;
for (int i = 0; i < adj[cur].size(); i++) for (int i = 0; i < adj[cur].size(); i++) {
{ if (!vis[adj[cur][i]]) {
if (!vis[adj[cur][i]])
{
deg[adj[cur][i]]--; deg[adj[cur][i]]--;
if (deg[adj[cur][i]] == 0) if (deg[adj[cur][i]] == 0) {
{
q.push(adj[cur][i]); q.push(adj[cur][i]);
vis[adj[cur][i]] = true; vis[adj[cur][i]] = true;
} }

View File

@@ -4,27 +4,22 @@
using namespace std; using namespace std;
// Wrapper class for storing a graph // Wrapper class for storing a graph
class Graph class Graph {
{
public: public:
int vertexNum; int vertexNum;
int **edges; int **edges;
// Constructs a graph with V vertices and E edges // Constructs a graph with V vertices and E edges
Graph(const int V) Graph(const int V) {
{
// initializes the array edges. // initializes the array edges.
this->edges = new int *[V]; this->edges = new int *[V];
for (int i = 0; i < V; i++) for (int i = 0; i < V; i++) {
{
edges[i] = new int[V]; edges[i] = new int[V];
} }
// fills the array with zeros. // fills the array with zeros.
for (int i = 0; i < V; i++) for (int i = 0; i < V; i++) {
{ for (int j = 0; j < V; j++) {
for (int j = 0; j < V; j++)
{
edges[i][j] = 0; edges[i][j] = 0;
} }
} }
@@ -33,19 +28,15 @@ class Graph
} }
// Adds the given edge to the graph // Adds the given edge to the graph
void addEdge(int src, int dst, int weight) void addEdge(int src, int dst, int weight) {
{
this->edges[src][dst] = weight; this->edges[src][dst] = weight;
} }
}; };
// Utility function to find minimum distance vertex in mdist // Utility function to find minimum distance vertex in mdist
int minDistance(int mdist[], bool vset[], int V) int minDistance(int mdist[], bool vset[], int V) {
{
int minVal = INT_MAX, minInd = 0; int minVal = INT_MAX, minInd = 0;
for (int i = 0; i < V; i++) for (int i = 0; i < V; i++) {
{ if (!vset[i] && (mdist[i] < minVal)) {
if (!vset[i] && (mdist[i] < minVal))
{
minVal = mdist[i]; minVal = mdist[i];
minInd = i; minInd = i;
} }
@@ -55,11 +46,9 @@ int minDistance(int mdist[], bool vset[], int V)
} }
// Utility function to print distances // Utility function to print distances
void print(int dist[], int V) void print(int dist[], int V) {
{
cout << "\nVertex Distance" << endl; cout << "\nVertex Distance" << endl;
for (int i = 0; i < V; i++) for (int i = 0; i < V; i++) {
{
if (dist[i] < INT_MAX) if (dist[i] < INT_MAX)
cout << i << "\t" << dist[i] << endl; cout << i << "\t" << dist[i] << endl;
else else
@@ -70,16 +59,14 @@ void print(int dist[], int V)
// The main function that finds the shortest path from given source // The main function that finds the shortest path from given source
// to all other vertices using Dijkstra's Algorithm.It doesn't work on negative // to all other vertices using Dijkstra's Algorithm.It doesn't work on negative
// weights // weights
void Dijkstra(Graph graph, int src) void Dijkstra(Graph graph, int src) {
{
int V = graph.vertexNum; int V = graph.vertexNum;
int mdist[V]; // Stores updated distances to vertex int mdist[V]; // Stores updated distances to vertex
bool vset[V]; // vset[i] is true if the vertex i included bool vset[V]; // vset[i] is true if the vertex i included
// in the shortest path tree // in the shortest path tree
// Initialise mdist and vset. Set distance of source as zero // Initialise mdist and vset. Set distance of source as zero
for (int i = 0; i < V; i++) for (int i = 0; i < V; i++) {
{
mdist[i] = INT_MAX; mdist[i] = INT_MAX;
vset[i] = false; vset[i] = false;
} }
@@ -87,17 +74,14 @@ void Dijkstra(Graph graph, int src)
mdist[src] = 0; mdist[src] = 0;
// iterate to find shortest path // iterate to find shortest path
for (int count = 0; count < V - 1; count++) for (int count = 0; count < V - 1; count++) {
{
int u = minDistance(mdist, vset, V); int u = minDistance(mdist, vset, V);
vset[u] = true; vset[u] = true;
for (int v = 0; v < V; v++) for (int v = 0; v < V; v++) {
{
if (!vset[v] && graph.edges[u][v] && if (!vset[v] && graph.edges[u][v] &&
mdist[u] + graph.edges[u][v] < mdist[v]) mdist[u] + graph.edges[u][v] < mdist[v]) {
{
mdist[v] = mdist[u] + graph.edges[u][v]; mdist[v] = mdist[u] + graph.edges[u][v];
} }
} }
@@ -107,8 +91,7 @@ void Dijkstra(Graph graph, int src)
} }
// Driver Function // Driver Function
int main() int main() {
{
int V, E, gsrc; int V, E, gsrc;
int src, dst, weight; int src, dst, weight;
cout << "Enter number of vertices: "; cout << "Enter number of vertices: ";
@@ -116,8 +99,7 @@ int main()
cout << "Enter number of edges: "; cout << "Enter number of edges: ";
cin >> E; cin >> E;
Graph G(V); Graph G(V);
for (int i = 0; i < E; i++) for (int i = 0; i < E; i++) {
{
cout << "\nEdge " << i + 1 << "\nEnter source: "; cout << "\nEdge " << i + 1 << "\nEnter source: ";
cin >> src; cin >> src;
cout << "Enter destination: "; cout << "Enter destination: ";
@@ -126,12 +108,9 @@ int main()
cin >> weight; cin >> weight;
// makes sure source and destionation are in the proper bounds. // makes sure source and destionation are in the proper bounds.
if (src >= 0 && src < V && dst >= 0 && dst < V) if (src >= 0 && src < V && dst >= 0 && dst < V) {
{
G.addEdge(src, dst, weight); G.addEdge(src, dst, weight);
} } else {
else
{
cout << "source and/or destination out of bounds" << endl; cout << "source and/or destination out of bounds" << endl;
i--; i--;
continue; continue;

View File

@@ -4,8 +4,7 @@
using namespace std; using namespace std;
// A Huffman tree node // A Huffman tree node
struct MinHeapNode struct MinHeapNode {
{
// One of the input characters // One of the input characters
char data; char data;
@@ -26,8 +25,7 @@ struct MinHeapNode
// For comparison of // For comparison of
// two heap nodes (needed in min heap) // two heap nodes (needed in min heap)
struct compare struct compare {
{
bool operator()(MinHeapNode* l, MinHeapNode* r) bool operator()(MinHeapNode* l, MinHeapNode* r)
{ {
@@ -37,8 +35,7 @@ struct compare
// Prints huffman codes from // Prints huffman codes from
// the root of Huffman Tree. // the root of Huffman Tree.
void printCodes(struct MinHeapNode* root, string str) void printCodes(struct MinHeapNode* root, string str) {
{
if (!root) if (!root)
return; return;
@@ -51,8 +48,7 @@ void printCodes(struct MinHeapNode* root, string str)
// The main function that builds a Huffman Tree and // The main function that builds a Huffman Tree and
// print codes by traversing the built Huffman Tree // print codes by traversing the built Huffman Tree
void HuffmanCodes(char data[], int freq[], int size) void HuffmanCodes(char data[], int freq[], int size) {
{
struct MinHeapNode *left, *right, *top; struct MinHeapNode *left, *right, *top;
// Create a min heap & inserts all characters of data[] // Create a min heap & inserts all characters of data[]
@@ -62,8 +58,7 @@ void HuffmanCodes(char data[], int freq[], int size)
minHeap.push(new MinHeapNode(data[i], freq[i])); minHeap.push(new MinHeapNode(data[i], freq[i]));
// Iterate while size of heap doesn't become 1 // Iterate while size of heap doesn't become 1
while (minHeap.size() != 1) while (minHeap.size() != 1) {
{
// Extract the two minimum // Extract the two minimum
// freq items from min heap // freq items from min heap
left = minHeap.top(); left = minHeap.top();
@@ -93,8 +88,7 @@ void HuffmanCodes(char data[], int freq[], int size)
} }
// Driver program to test above functions // Driver program to test above functions
int main() int main() {
{
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f'}; char arr[] = {'a', 'b', 'c', 'd', 'e', 'f'};
int freq[] = {5, 9, 12, 13, 16, 45}; int freq[] = {5, 9, 12, 13, 16, 45};

View File

@@ -1,25 +1,21 @@
#include <iostream> #include <iostream>
using namespace std; using namespace std;
struct Item struct Item {
{
int weight; int weight;
int profit; int profit;
}; };
float profitPerUnit(Item x) { return (float)x.profit / (float)x.weight; } float profitPerUnit(Item x) { return (float)x.profit / (float)x.weight; }
int partition(Item arr[], int low, int high) int partition(Item arr[], int low, int high) {
{
Item pivot = arr[high]; // pivot Item pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element int i = (low - 1); // Index of smaller element
for (int j = low; j < high; j++) for (int j = low; j < high; j++) {
{
// If current element is smaller than or // If current element is smaller than or
// equal to pivot // equal to pivot
if (profitPerUnit(arr[j]) <= profitPerUnit(pivot)) if (profitPerUnit(arr[j]) <= profitPerUnit(pivot)) {
{
i++; // increment index of smaller element i++; // increment index of smaller element
Item temp = arr[i]; Item temp = arr[i];
arr[i] = arr[j]; arr[i] = arr[j];
@@ -32,10 +28,8 @@ int partition(Item arr[], int low, int high)
return (i + 1); return (i + 1);
} }
void quickSort(Item arr[], int low, int high) void quickSort(Item arr[], int low, int high) {
{ if (low < high) {
if (low < high)
{
int p = partition(arr, low, high); int p = partition(arr, low, high);
quickSort(arr, low, p - 1); quickSort(arr, low, p - 1);
@@ -43,8 +37,7 @@ void quickSort(Item arr[], int low, int high)
} }
} }
int main() int main() {
{
cout << "\nEnter the capacity of the knapsack : "; cout << "\nEnter the capacity of the knapsack : ";
float capacity; float capacity;
cin >> capacity; cin >> capacity;
@@ -52,8 +45,7 @@ int main()
int n; int n;
cin >> n; cin >> n;
Item itemArray[n]; Item itemArray[n];
for (int i = 0; i < n; i++) for (int i = 0; i < n; i++) {
{
cout << "\nEnter the weight and profit of item " << i + 1 << " : "; cout << "\nEnter the weight and profit of item " << i + 1 << " : ";
cin >> itemArray[i].weight; cin >> itemArray[i].weight;
cin >> itemArray[i].profit; cin >> itemArray[i].profit;
@@ -65,17 +57,13 @@ int main()
float maxProfit = 0; float maxProfit = 0;
int i = n; int i = n;
while (capacity > 0 && --i >= 0) while (capacity > 0 && --i >= 0) {
{ if (capacity >= itemArray[i].weight) {
if (capacity >= itemArray[i].weight)
{
maxProfit += itemArray[i].profit; maxProfit += itemArray[i].profit;
capacity -= itemArray[i].weight; capacity -= itemArray[i].weight;
cout << "\n\t" << itemArray[i].weight << "\t" cout << "\n\t" << itemArray[i].weight << "\t"
<< itemArray[i].profit; << itemArray[i].profit;
} } else {
else
{
maxProfit += profitPerUnit(itemArray[i]) * capacity; maxProfit += profitPerUnit(itemArray[i]) * capacity;
cout << "\n\t" << capacity << "\t" cout << "\n\t" << capacity << "\t"
<< profitPerUnit(itemArray[i]) * capacity; << profitPerUnit(itemArray[i]) * capacity;

View File

@@ -11,16 +11,12 @@ int graph[V][V] = {{0, 4, 1, 4, INFINITY, INFINITY},
{INFINITY, 3, 1, 5, 0, INFINITY}, {INFINITY, 3, 1, 5, 0, INFINITY},
{INFINITY, INFINITY, INFINITY, 7, INFINITY, 0}}; {INFINITY, INFINITY, INFINITY, 7, INFINITY, 0}};
void findMinimumEdge() void findMinimumEdge() {
{ for (int i = 0; i < V; i++) {
for (int i = 0; i < V; i++)
{
int min = INFINITY; int min = INFINITY;
int minIndex = 0; int minIndex = 0;
for (int j = 0; j < V; j++) for (int j = 0; j < V; j++) {
{ if (graph[i][j] != 0 && graph[i][j] < min) {
if (graph[i][j] != 0 && graph[i][j] < min)
{
min = graph[i][j]; min = graph[i][j];
minIndex = j; minIndex = j;
} }
@@ -29,8 +25,7 @@ void findMinimumEdge()
} }
} }
int main() int main() {
{
findMinimumEdge(); findMinimumEdge();
return 0; return 0;
} }

View File

@@ -6,8 +6,7 @@ using namespace std;
int graph[V][V] = {{0, 5, 1, 2}, {5, 0, 3, 3}, {1, 3, 0, 4}, {2, 3, 4, 0}}; int graph[V][V] = {{0, 5, 1, 2}, {5, 0, 3, 3}, {1, 3, 0, 4}, {2, 3, 4, 0}};
struct mst struct mst {
{
bool visited; bool visited;
int key; int key;
int near; int near;
@@ -15,10 +14,8 @@ struct mst
mst MST_Array[V]; mst MST_Array[V];
void initilize() void initilize() {
{ for (int i = 0; i < V; i++) {
for (int i = 0; i < V; i++)
{
MST_Array[i].visited = false; MST_Array[i].visited = false;
MST_Array[i].key = INFINITY; // considering INFINITY as inifinity MST_Array[i].key = INFINITY; // considering INFINITY as inifinity
MST_Array[i].near = i; MST_Array[i].near = i;
@@ -27,17 +24,13 @@ void initilize()
MST_Array[0].key = 0; MST_Array[0].key = 0;
} }
void updateNear() void updateNear() {
{ for (int v = 0; v < V; v++) {
for (int v = 0; v < V; v++)
{
int min = INFINITY; int min = INFINITY;
int minIndex = 0; int minIndex = 0;
for (int i = 0; i < V; i++) for (int i = 0; i < V; i++) {
{
if (MST_Array[i].key < min && MST_Array[i].visited == false && if (MST_Array[i].key < min && MST_Array[i].visited == false &&
MST_Array[i].key != INFINITY) MST_Array[i].key != INFINITY) {
{
min = MST_Array[i].key; min = MST_Array[i].key;
minIndex = i; minIndex = i;
} }
@@ -45,12 +38,9 @@ void updateNear()
MST_Array[minIndex].visited = true; MST_Array[minIndex].visited = true;
for (int i = 0; i < V; i++) for (int i = 0; i < V; i++) {
{ if (graph[minIndex][i] != 0 && graph[minIndex][i] < INFINITY) {
if (graph[minIndex][i] != 0 && graph[minIndex][i] < INFINITY) if (graph[minIndex][i] < MST_Array[i].key) {
{
if (graph[minIndex][i] < MST_Array[i].key)
{
MST_Array[i].key = graph[minIndex][i]; MST_Array[i].key = graph[minIndex][i];
MST_Array[i].near = minIndex; MST_Array[i].near = minIndex;
} }
@@ -59,17 +49,14 @@ void updateNear()
} }
} }
void show() void show() {
{ for (int i = 0; i < V; i++) {
for (int i = 0; i < V; i++)
{
cout << i << " - " << MST_Array[i].near << "\t" cout << i << " - " << MST_Array[i].near << "\t"
<< graph[i][MST_Array[i].near] << "\n"; << graph[i][MST_Array[i].near] << "\n";
} }
} }
int main() int main() {
{
initilize(); initilize();
updateNear(); updateNear();
show(); show();

View File

@@ -2,51 +2,39 @@
#include <iostream> #include <iostream>
using namespace std; using namespace std;
struct Node struct Node {
{
int data; int data;
struct Node *next; struct Node *next;
} * head[100], *curr; } * head[100], *curr;
void init() void init() {
{
for (int i = 0; i < 100; i++) head[i] = NULL; for (int i = 0; i < 100; i++) head[i] = NULL;
} }
void add(int x, int h) void add(int x, int h) {
{
struct Node *temp = new Node; struct Node *temp = new Node;
temp->data = x; temp->data = x;
temp->next = NULL; temp->next = NULL;
if (!head[h]) if (!head[h]) {
{
head[h] = temp; head[h] = temp;
curr = head[h]; curr = head[h];
} } else {
else
{
curr = head[h]; curr = head[h];
while (curr->next) curr = curr->next; while (curr->next) curr = curr->next;
curr->next = temp; curr->next = temp;
} }
} }
void display(int mod) void display(int mod) {
{
struct Node *temp; struct Node *temp;
int i; int i;
for (i = 0; i < mod; i++) for (i = 0; i < mod; i++) {
{ if (!head[i]) {
if (!head[i])
{
cout << "Key " << i << " is empty" << endl; cout << "Key " << i << " is empty" << endl;
} } else {
else
{
cout << "Key " << i << " has values = "; cout << "Key " << i << " has values = ";
temp = head[i]; temp = head[i];
while (temp->next) while (temp->next) {
{
cout << temp->data << " "; cout << temp->data << " ";
temp = temp->next; temp = temp->next;
} }
@@ -58,19 +46,16 @@ void display(int mod)
int hash(int x, int mod) { return x % mod; } int hash(int x, int mod) { return x % mod; }
void find(int x, int h) void find(int x, int h) {
{
struct Node *temp = head[h]; struct Node *temp = head[h];
if (!head[h]) if (!head[h]) {
{
cout << "Element not found"; cout << "Element not found";
return; return;
} }
while (temp->data != x && temp->next) temp = temp->next; while (temp->data != x && temp->next) temp = temp->next;
if (temp->next) if (temp->next)
cout << "Element found"; cout << "Element found";
else else {
{
if (temp->data == x) if (temp->data == x)
cout << "Element found"; cout << "Element found";
else else
@@ -78,15 +63,13 @@ void find(int x, int h)
} }
} }
int main(void) int main(void) {
{
init(); init();
int c, x, mod, h; int c, x, mod, h;
cout << "Enter the size of Hash Table. = "; cout << "Enter the size of Hash Table. = ";
cin >> mod; cin >> mod;
bool loop = true; bool loop = true;
while (loop) while (loop) {
{
cout << endl; cout << endl;
cout << "PLEASE CHOOSE -" << endl; cout << "PLEASE CHOOSE -" << endl;
cout << "1. Add element." << endl; cout << "1. Add element." << endl;
@@ -95,8 +78,7 @@ int main(void)
cout << "4. Display Hash table." << endl; cout << "4. Display Hash table." << endl;
cout << "5. Exit." << endl; cout << "5. Exit." << endl;
cin >> c; cin >> c;
switch (c) switch (c) {
{
case 1: case 1:
cout << "Enter element to add = "; cout << "Enter element to add = ";
cin >> x; cin >> x;

View File

@@ -25,55 +25,44 @@ int size;
bool rehashing; bool rehashing;
// Node that holds key // Node that holds key
struct Entry struct Entry {
{
explicit Entry(int key = notPresent) : key(key) {} explicit Entry(int key = notPresent) : key(key) {}
int key; int key;
}; };
// Hash a key // Hash a key
int hashFxn(int key) int hashFxn(int key) {
{
std::hash<int> hash; std::hash<int> hash;
return hash(key); return hash(key);
} }
// Used for second hash function // Used for second hash function
int otherHashFxn(int key) int otherHashFxn(int key) {
{
std::hash<int> hash; std::hash<int> hash;
return 1 + (7 - (hash(key) % 7)); return 1 + (7 - (hash(key) % 7));
} }
// Performs double hashing to resolve collisions // Performs double hashing to resolve collisions
int doubleHash(int key, bool searching) int doubleHash(int key, bool searching) {
{
int hash = static_cast<int>(fabs(hashFxn(key))); int hash = static_cast<int>(fabs(hashFxn(key)));
int i = 0; int i = 0;
Entry entry; Entry entry;
do do {
{
int index = static_cast<int>(fabs((hash + (i * otherHashFxn(key))))) % int index = static_cast<int>(fabs((hash + (i * otherHashFxn(key))))) %
totalSize; totalSize;
entry = table[index]; entry = table[index];
if (searching) if (searching) {
{ if (entry.key == notPresent) {
if (entry.key == notPresent)
{
return notPresent; return notPresent;
} }
if (searchingProber(entry, key)) if (searchingProber(entry, key)) {
{
cout << "Found key!" << endl; cout << "Found key!" << endl;
return index; return index;
} }
cout << "Found tombstone or equal hash, checking next" << endl; cout << "Found tombstone or equal hash, checking next" << endl;
i++; i++;
} } else {
else if (putProber(entry, key)) {
{
if (putProber(entry, key))
{
if (!rehashing) if (!rehashing)
cout << "Spot found!" << endl; cout << "Spot found!" << endl;
return index; return index;
@@ -87,8 +76,7 @@ int doubleHash(int key, bool searching)
<< ")" << endl; << ")" << endl;
i++; i++;
} }
if (i == totalSize * 100) if (i == totalSize * 100) {
{
cout << "DoubleHash probe failed" << endl; cout << "DoubleHash probe failed" << endl;
return notPresent; return notPresent;
} }
@@ -97,38 +85,28 @@ int doubleHash(int key, bool searching)
} }
// Finds empty spot // Finds empty spot
bool putProber(Entry entry, int key) bool putProber(Entry entry, int key) {
{ if (entry.key == notPresent || entry.key == tomb) {
if (entry.key == notPresent || entry.key == tomb)
{
return true; return true;
} }
return false; return false;
} }
// Looks for a matching key // Looks for a matching key
bool searchingProber(Entry entry, int key) bool searchingProber(Entry entry, int key) {
{
if (entry.key == key) if (entry.key == key)
return true; return true;
return false; return false;
} }
// Displays the table // Displays the table
void display() void display() {
{ for (int i = 0; i < totalSize; i++) {
for (int i = 0; i < totalSize; i++) if (table[i].key == notPresent) {
{
if (table[i].key == notPresent)
{
cout << " Empty "; cout << " Empty ";
} } else if (table[i].key == tomb) {
else if (table[i].key == tomb)
{
cout << " Tomb "; cout << " Tomb ";
} } else {
else
{
cout << " "; cout << " ";
cout << table[i].key; cout << table[i].key;
cout << " "; cout << " ";
@@ -138,8 +116,7 @@ void display()
} }
// Rehashes the table into a bigger table // Rehashes the table into a bigger table
void rehash() void rehash() {
{
// Necessary so wall of add info isn't printed all at once // Necessary so wall of add info isn't printed all at once
rehashing = true; rehashing = true;
int oldSize = totalSize; int oldSize = totalSize;
@@ -147,10 +124,8 @@ void rehash()
// Really this should use the next prime number greater than totalSize * 2 // Really this should use the next prime number greater than totalSize * 2
table = new Entry[totalSize * 2]; table = new Entry[totalSize * 2];
totalSize *= 2; totalSize *= 2;
for (int i = 0; i < oldSize; i++) for (int i = 0; i < oldSize; i++) {
{ if (oldTable[i].key != -1 && oldTable[i].key != notPresent) {
if (oldTable[i].key != -1 && oldTable[i].key != notPresent)
{
size--; // Size stays the same (add increments size) size--; // Size stays the same (add increments size)
add(oldTable[i].key); add(oldTable[i].key);
} }
@@ -161,25 +136,21 @@ void rehash()
} }
// Checks for load factor here // Checks for load factor here
void add(int key) void add(int key) {
{
Entry* entry = new Entry(); Entry* entry = new Entry();
entry->key = key; entry->key = key;
int index = doubleHash(key, false); int index = doubleHash(key, false);
table[index] = *entry; table[index] = *entry;
// Load factor greater than 0.5 causes resizing // Load factor greater than 0.5 causes resizing
if (++size / static_cast<double>(totalSize) >= 0.5) if (++size / static_cast<double>(totalSize) >= 0.5) {
{
rehash(); rehash();
} }
} }
// Removes key. Leaves tombstone upon removal. // Removes key. Leaves tombstone upon removal.
void remove(int key) void remove(int key) {
{
int index = doubleHash(key, true); int index = doubleHash(key, true);
if (index == notPresent) if (index == notPresent) {
{
cout << "key not found" << endl; cout << "key not found" << endl;
} }
table[index].key = tomb; table[index].key = tomb;
@@ -188,8 +159,7 @@ void remove(int key)
} }
// Information about the adding process // Information about the adding process
void addInfo(int key) void addInfo(int key) {
{
cout << "Initial table: "; cout << "Initial table: ";
display(); display();
cout << endl; cout << endl;
@@ -202,8 +172,7 @@ void addInfo(int key)
} }
// Information about removal process // Information about removal process
void removalInfo(int key) void removalInfo(int key) {
{
cout << "Initial table: "; cout << "Initial table: ";
display(); display();
cout << endl; cout << endl;
@@ -216,15 +185,13 @@ void removalInfo(int key)
} }
// I/O // I/O
int main(void) int main(void) {
{
int cmd, hash, key; int cmd, hash, key;
cout << "Enter the initial size of Hash Table. = "; cout << "Enter the initial size of Hash Table. = ";
cin >> totalSize; cin >> totalSize;
table = new Entry[totalSize]; table = new Entry[totalSize];
bool loop = true; bool loop = true;
while (loop) while (loop) {
{
system("pause"); system("pause");
cout << endl; cout << endl;
cout << "PLEASE CHOOSE -" << endl; cout << "PLEASE CHOOSE -" << endl;
@@ -235,8 +202,7 @@ int main(void)
cout << "5. Display Hash table." << endl; cout << "5. Display Hash table." << endl;
cout << "6. Exit." << endl; cout << "6. Exit." << endl;
cin >> cmd; cin >> cmd;
switch (cmd) switch (cmd) {
{
case 1: case 1:
cout << "Enter key to add = "; cout << "Enter key to add = ";
cin >> key; cin >> key;
@@ -247,13 +213,11 @@ int main(void)
cin >> key; cin >> key;
removalInfo(key); removalInfo(key);
break; break;
case 3: case 3: {
{
cout << "Enter key to search = "; cout << "Enter key to search = ";
cin >> key; cin >> key;
Entry entry = table[doubleHash(key, true)]; Entry entry = table[doubleHash(key, true)];
if (entry.key == notPresent) if (entry.key == notPresent) {
{
cout << "Key not present"; cout << "Key not present";
} }
break; break;

View File

@@ -25,47 +25,37 @@ int size;
bool rehashing; bool rehashing;
// Node that holds key // Node that holds key
struct Entry struct Entry {
{
explicit Entry(int key = notPresent) : key(key) {} explicit Entry(int key = notPresent) : key(key) {}
int key; int key;
}; };
// Hash a key // Hash a key
int hashFxn(int key) int hashFxn(int key) {
{
std::hash<int> hash; std::hash<int> hash;
return hash(key); return hash(key);
} }
// Performs linear probing to resolve collisions // Performs linear probing to resolve collisions
int linearProbe(int key, bool searching) int linearProbe(int key, bool searching) {
{
int hash = static_cast<int>(fabs(hashFxn(key))); int hash = static_cast<int>(fabs(hashFxn(key)));
int i = 0; int i = 0;
Entry entry; Entry entry;
do do {
{
int index = static_cast<int>(fabs((hash + i) % totalSize)); int index = static_cast<int>(fabs((hash + i) % totalSize));
entry = table[index]; entry = table[index];
if (searching) if (searching) {
{ if (entry.key == notPresent) {
if (entry.key == notPresent)
{
return notPresent; return notPresent;
} }
if (searchingProber(entry, key)) if (searchingProber(entry, key)) {
{
cout << "Found key!" << endl; cout << "Found key!" << endl;
return index; return index;
} }
cout << "Found tombstone or equal hash, checking next" << endl; cout << "Found tombstone or equal hash, checking next" << endl;
i++; i++;
} } else {
else if (putProber(entry, key)) {
{
if (putProber(entry, key))
{
if (!rehashing) if (!rehashing)
cout << "Spot found!" << endl; cout << "Spot found!" << endl;
return index; return index;
@@ -74,8 +64,7 @@ int linearProbe(int key, bool searching)
cout << "Spot taken, looking at next" << endl; cout << "Spot taken, looking at next" << endl;
i++; i++;
} }
if (i == totalSize) if (i == totalSize) {
{
cout << "Linear probe failed" << endl; cout << "Linear probe failed" << endl;
return notPresent; return notPresent;
} }
@@ -84,38 +73,28 @@ int linearProbe(int key, bool searching)
} }
// Finds empty spot // Finds empty spot
bool putProber(Entry entry, int key) bool putProber(Entry entry, int key) {
{ if (entry.key == notPresent || entry.key == tomb) {
if (entry.key == notPresent || entry.key == tomb)
{
return true; return true;
} }
return false; return false;
} }
// Looks for a matching key // Looks for a matching key
bool searchingProber(Entry entry, int key) bool searchingProber(Entry entry, int key) {
{
if (entry.key == key) if (entry.key == key)
return true; return true;
return false; return false;
} }
// Displays the table // Displays the table
void display() void display() {
{ for (int i = 0; i < totalSize; i++) {
for (int i = 0; i < totalSize; i++) if (table[i].key == notPresent) {
{
if (table[i].key == notPresent)
{
cout << " Empty "; cout << " Empty ";
} } else if (table[i].key == tomb) {
else if (table[i].key == tomb)
{
cout << " Tomb "; cout << " Tomb ";
} } else {
else
{
cout << " "; cout << " ";
cout << table[i].key; cout << table[i].key;
cout << " "; cout << " ";
@@ -125,8 +104,7 @@ void display()
} }
// Rehashes the table into a bigger table // Rehashes the table into a bigger table
void rehash() void rehash() {
{
// Necessary so wall of add info isn't printed all at once // Necessary so wall of add info isn't printed all at once
rehashing = true; rehashing = true;
int oldSize = totalSize; int oldSize = totalSize;
@@ -134,10 +112,8 @@ void rehash()
// Really this should use the next prime number greater than totalSize * 2 // Really this should use the next prime number greater than totalSize * 2
table = new Entry[totalSize * 2]; table = new Entry[totalSize * 2];
totalSize *= 2; totalSize *= 2;
for (int i = 0; i < oldSize; i++) for (int i = 0; i < oldSize; i++) {
{ if (oldTable[i].key != -1 && oldTable[i].key != notPresent) {
if (oldTable[i].key != -1 && oldTable[i].key != notPresent)
{
size--; // Size stays the same (add increments size) size--; // Size stays the same (add increments size)
add(oldTable[i].key); add(oldTable[i].key);
} }
@@ -148,25 +124,21 @@ void rehash()
} }
// Adds entry using linear probing. Checks for load factor here // Adds entry using linear probing. Checks for load factor here
void add(int key) void add(int key) {
{
Entry* entry = new Entry(); Entry* entry = new Entry();
entry->key = key; entry->key = key;
int index = linearProbe(key, false); int index = linearProbe(key, false);
table[index] = *entry; table[index] = *entry;
// Load factor greater than 0.5 causes resizing // Load factor greater than 0.5 causes resizing
if (++size / static_cast<double>(totalSize) >= 0.5) if (++size / static_cast<double>(totalSize) >= 0.5) {
{
rehash(); rehash();
} }
} }
// Removes key. Leaves tombstone upon removal. // Removes key. Leaves tombstone upon removal.
void remove(int key) void remove(int key) {
{
int index = linearProbe(key, true); int index = linearProbe(key, true);
if (index == notPresent) if (index == notPresent) {
{
cout << "key not found" << endl; cout << "key not found" << endl;
} }
cout << "Removal Successful, leaving tomb" << endl; cout << "Removal Successful, leaving tomb" << endl;
@@ -175,8 +147,7 @@ void remove(int key)
} }
// Information about the adding process // Information about the adding process
void addInfo(int key) void addInfo(int key) {
{
cout << "Initial table: "; cout << "Initial table: ";
display(); display();
cout << endl; cout << endl;
@@ -189,8 +160,7 @@ void addInfo(int key)
} }
// Information about removal process // Information about removal process
void removalInfo(int key) void removalInfo(int key) {
{
cout << "Initial table: "; cout << "Initial table: ";
display(); display();
cout << endl; cout << endl;
@@ -203,15 +173,13 @@ void removalInfo(int key)
} }
// I/O // I/O
int main(void) int main(void) {
{
int cmd, hash, key; int cmd, hash, key;
cout << "Enter the initial size of Hash Table. = "; cout << "Enter the initial size of Hash Table. = ";
cin >> totalSize; cin >> totalSize;
table = new Entry[totalSize]; table = new Entry[totalSize];
bool loop = true; bool loop = true;
while (loop) while (loop) {
{
system("pause"); system("pause");
cout << endl; cout << endl;
cout << "PLEASE CHOOSE -" << endl; cout << "PLEASE CHOOSE -" << endl;
@@ -222,8 +190,7 @@ int main(void)
cout << "5. Display Hash table." << endl; cout << "5. Display Hash table." << endl;
cout << "6. Exit." << endl; cout << "6. Exit." << endl;
cin >> cmd; cin >> cmd;
switch (cmd) switch (cmd) {
{
case 1: case 1:
cout << "Enter key to add = "; cout << "Enter key to add = ";
cin >> key; cin >> key;
@@ -234,13 +201,11 @@ int main(void)
cin >> key; cin >> key;
removalInfo(key); removalInfo(key);
break; break;
case 3: case 3: {
{
cout << "Enter key to search = "; cout << "Enter key to search = ";
cin >> key; cin >> key;
Entry entry = table[linearProbe(key, true)]; Entry entry = table[linearProbe(key, true)];
if (entry.key == notPresent) if (entry.key == notPresent) {
{
cout << "Key not present"; cout << "Key not present";
} }
break; break;

View File

@@ -26,54 +26,43 @@ int size;
bool rehashing; bool rehashing;
// Node that holds key // Node that holds key
struct Entry struct Entry {
{
explicit Entry(int key = notPresent) : key(key) {} explicit Entry(int key = notPresent) : key(key) {}
int key; int key;
}; };
// Hash a key // Hash a key
int hashFxn(int key) int hashFxn(int key) {
{
std::hash<int> hash; std::hash<int> hash;
return hash(key); return hash(key);
} }
// Performs quadratic probing to resolve collisions // Performs quadratic probing to resolve collisions
int quadraticProbe(int key, bool searching) int quadraticProbe(int key, bool searching) {
{
int hash = static_cast<int>(fabs(hashFxn(key))); int hash = static_cast<int>(fabs(hashFxn(key)));
int i = 0; int i = 0;
Entry entry; Entry entry;
do do {
{
int index = std::round(fabs( int index = std::round(fabs(
(hash + static_cast<int>(std::round(std::pow(i, 2)))) % totalSize)); (hash + static_cast<int>(std::round(std::pow(i, 2)))) % totalSize));
entry = table[index]; entry = table[index];
if (searching) if (searching) {
{ if (entry.key == notPresent) {
if (entry.key == notPresent)
{
return notPresent; return notPresent;
} }
if (searchingProber(entry, key)) if (searchingProber(entry, key)) {
{
cout << "Found key!" << endl; cout << "Found key!" << endl;
return index; return index;
} }
cout << "Found tombstone or equal hash, checking next" << endl; cout << "Found tombstone or equal hash, checking next" << endl;
i++; i++;
} } else {
else if (putProber(entry, key)) {
{
if (putProber(entry, key))
{
if (!rehashing) if (!rehashing)
cout << "Spot found!" << endl; cout << "Spot found!" << endl;
return index; return index;
} }
if (!rehashing) if (!rehashing) {
{
cout << "Spot taken, looking at next (next index = " cout << "Spot taken, looking at next (next index = "
<< std::round(fabs((hash + static_cast<int>(std::round( << std::round(fabs((hash + static_cast<int>(std::round(
std::pow(i + 1, 2)))) % std::pow(i + 1, 2)))) %
@@ -82,8 +71,7 @@ int quadraticProbe(int key, bool searching)
} }
i++; i++;
} }
if (i == totalSize * 100) if (i == totalSize * 100) {
{
cout << "Quadratic probe failed (infinite loop)" << endl; cout << "Quadratic probe failed (infinite loop)" << endl;
return notPresent; return notPresent;
} }
@@ -92,26 +80,22 @@ int quadraticProbe(int key, bool searching)
} }
// Finds empty spot // Finds empty spot
bool putProber(Entry entry, int key) bool putProber(Entry entry, int key) {
{ if (entry.key == notPresent || entry.key == tomb) {
if (entry.key == notPresent || entry.key == tomb)
{
return true; return true;
} }
return false; return false;
} }
// Looks for a matching key // Looks for a matching key
bool searchingProber(Entry entry, int key) bool searchingProber(Entry entry, int key) {
{
if (entry.key == key) if (entry.key == key)
return true; return true;
return false; return false;
} }
// Helper // Helper
Entry find(int key) Entry find(int key) {
{
int index = quadraticProbe(key, true); int index = quadraticProbe(key, true);
if (index == notPresent) if (index == notPresent)
return Entry(); return Entry();
@@ -119,20 +103,13 @@ Entry find(int key)
} }
// Displays the table // Displays the table
void display() void display() {
{ for (int i = 0; i < totalSize; i++) {
for (int i = 0; i < totalSize; i++) if (table[i].key == notPresent) {
{
if (table[i].key == notPresent)
{
cout << " Empty "; cout << " Empty ";
} } else if (table[i].key == tomb) {
else if (table[i].key == tomb)
{
cout << " Tomb "; cout << " Tomb ";
} } else {
else
{
cout << " "; cout << " ";
cout << table[i].key; cout << table[i].key;
cout << " "; cout << " ";
@@ -142,8 +119,7 @@ void display()
} }
// Rehashes the table into a bigger table // Rehashes the table into a bigger table
void rehash() void rehash() {
{
// Necessary so wall of add info isn't printed all at once // Necessary so wall of add info isn't printed all at once
rehashing = true; rehashing = true;
int oldSize = totalSize; int oldSize = totalSize;
@@ -151,10 +127,8 @@ void rehash()
// Really this should use the next prime number greater than totalSize * 2 // Really this should use the next prime number greater than totalSize * 2
table = new Entry[totalSize * 2]; table = new Entry[totalSize * 2];
totalSize *= 2; totalSize *= 2;
for (int i = 0; i < oldSize; i++) for (int i = 0; i < oldSize; i++) {
{ if (oldTable[i].key != -1 && oldTable[i].key != notPresent) {
if (oldTable[i].key != -1 && oldTable[i].key != notPresent)
{
size--; // Size stays the same (add increments size) size--; // Size stays the same (add increments size)
add(oldTable[i].key); add(oldTable[i].key);
} }
@@ -165,25 +139,21 @@ void rehash()
} }
// Checks for load factor here // Checks for load factor here
void add(int key) void add(int key) {
{
Entry* entry = new Entry(); Entry* entry = new Entry();
entry->key = key; entry->key = key;
int index = quadraticProbe(key, false); int index = quadraticProbe(key, false);
table[index] = *entry; table[index] = *entry;
// Load factor greater than 0.5 causes resizing // Load factor greater than 0.5 causes resizing
if (++size / static_cast<double>(totalSize) >= 0.5) if (++size / static_cast<double>(totalSize) >= 0.5) {
{
rehash(); rehash();
} }
} }
// Removes key. Leaves tombstone upon removal. // Removes key. Leaves tombstone upon removal.
void remove(int key) void remove(int key) {
{
int index = quadraticProbe(key, true); int index = quadraticProbe(key, true);
if (index == notPresent) if (index == notPresent) {
{
cout << "key not found" << endl; cout << "key not found" << endl;
} }
table[index].key = tomb; table[index].key = tomb;
@@ -192,8 +162,7 @@ void remove(int key)
} }
// Information about the adding process // Information about the adding process
void addInfo(int key) void addInfo(int key) {
{
cout << "Initial table: "; cout << "Initial table: ";
display(); display();
cout << endl; cout << endl;
@@ -206,8 +175,7 @@ void addInfo(int key)
} }
// Information about removal process // Information about removal process
void removalInfo(int key) void removalInfo(int key) {
{
cout << "Initial table: "; cout << "Initial table: ";
display(); display();
cout << endl; cout << endl;
@@ -220,15 +188,13 @@ void removalInfo(int key)
} }
// I/O // I/O
int main(void) int main(void) {
{
int cmd, hash, key; int cmd, hash, key;
cout << "Enter the initial size of Hash Table. = "; cout << "Enter the initial size of Hash Table. = ";
cin >> totalSize; cin >> totalSize;
table = new Entry[totalSize]; table = new Entry[totalSize];
bool loop = true; bool loop = true;
while (loop) while (loop) {
{
system("pause"); system("pause");
cout << endl; cout << endl;
cout << "PLEASE CHOOSE -" << endl; cout << "PLEASE CHOOSE -" << endl;
@@ -239,8 +205,7 @@ int main(void)
cout << "5. Display Hash table." << endl; cout << "5. Display Hash table." << endl;
cout << "6. Exit." << endl; cout << "6. Exit." << endl;
cin >> cmd; cin >> cmd;
switch (cmd) switch (cmd) {
{
case 1: case 1:
cout << "Enter key to add = "; cout << "Enter key to add = ";
cin >> key; cin >> key;
@@ -251,13 +216,11 @@ int main(void)
cin >> key; cin >> key;
removalInfo(key); removalInfo(key);
break; break;
case 3: case 3: {
{
cout << "Enter key to search = "; cout << "Enter key to search = ";
cin >> key; cin >> key;
Entry entry = table[quadraticProbe(key, true)]; Entry entry = table[quadraticProbe(key, true)];
if (entry.key == notPresent) if (entry.key == notPresent) {
{
cout << "Key not present"; cout << "Key not present";
} }
break; break;

View File

@@ -25,32 +25,24 @@
/// Recursive function to calculate exponent in \f$O(\log(n))\f$ using binary /// Recursive function to calculate exponent in \f$O(\log(n))\f$ using binary
/// exponent. /// exponent.
int binExpo(int a, int b) int binExpo(int a, int b) {
{ if (b == 0) {
if (b == 0)
{
return 1; return 1;
} }
int res = binExpo(a, b / 2); int res = binExpo(a, b / 2);
if (b % 2) if (b % 2) {
{
return res * res * a; return res * res * a;
} } else {
else
{
return res * res; return res * res;
} }
} }
/// Iterative function to calculate exponent in \f$O(\log(n))\f$ using binary /// Iterative function to calculate exponent in \f$O(\log(n))\f$ using binary
/// exponent. /// exponent.
int binExpo_alt(int a, int b) int binExpo_alt(int a, int b) {
{
int res = 1; int res = 1;
while (b > 0) while (b > 0) {
{ if (b % 2) {
if (b % 2)
{
res = res * a; res = res * a;
} }
a = a * a; a = a * a;
@@ -60,21 +52,15 @@ int binExpo_alt(int a, int b)
} }
/// Main function /// Main function
int main() int main() {
{
int a, b; int a, b;
/// Give two numbers a, b /// Give two numbers a, b
std::cin >> a >> b; std::cin >> a >> b;
if (a == 0 && b == 0) if (a == 0 && b == 0) {
{
std::cout << "Math error" << std::endl; std::cout << "Math error" << std::endl;
} } else if (b < 0) {
else if (b < 0)
{
std::cout << "Exponent must be positive !!" << std::endl; std::cout << "Exponent must be positive !!" << std::endl;
} } else {
else
{
int resRecurse = binExpo(a, b); int resRecurse = binExpo(a, b);
/// int resIterate = binExpo_alt(a, b); /// int resIterate = binExpo_alt(a, b);

View File

@@ -13,11 +13,9 @@
/** Compute double factorial using iterative method /** Compute double factorial using iterative method
*/ */
uint64_t double_factorial_iterative(uint64_t n) uint64_t double_factorial_iterative(uint64_t n) {
{
uint64_t res = 1; uint64_t res = 1;
for (uint64_t i = n;; i -= 2) for (uint64_t i = n;; i -= 2) {
{
if (i == 0 || i == 1) if (i == 0 || i == 1)
return res; return res;
res *= i; res *= i;
@@ -28,16 +26,14 @@ uint64_t double_factorial_iterative(uint64_t n)
/** Compute double factorial using resursive method. /** Compute double factorial using resursive method.
* <br/>Recursion can be costly for large numbers. * <br/>Recursion can be costly for large numbers.
*/ */
uint64_t double_factorial_recursive(uint64_t n) uint64_t double_factorial_recursive(uint64_t n) {
{
if (n <= 1) if (n <= 1)
return 1; return 1;
return n * double_factorial_recursive(n - 2); return n * double_factorial_recursive(n - 2);
} }
/// main function /// main function
int main() int main() {
{
uint64_t n; uint64_t n;
std::cin >> n; std::cin >> n;
assert(n >= 0); assert(n >= 0);

View File

@@ -29,15 +29,11 @@
/** Function to caculate Euler's totient phi /** Function to caculate Euler's totient phi
*/ */
uint64_t phiFunction(uint64_t n) uint64_t phiFunction(uint64_t n) {
{
uint64_t result = n; uint64_t result = n;
for (uint64_t i = 2; i * i <= n; i++) for (uint64_t i = 2; i * i <= n; i++) {
{ if (n % i == 0) {
if (n % i == 0) while (n % i == 0) {
{
while (n % i == 0)
{
n /= i; n /= i;
} }
result -= result / i; result -= result / i;
@@ -49,15 +45,11 @@ uint64_t phiFunction(uint64_t n)
} }
/// Main function /// Main function
int main(int argc, char *argv[]) int main(int argc, char *argv[]) {
{
uint64_t n; uint64_t n;
if (argc < 2) if (argc < 2) {
{
std::cout << "Enter the number: "; std::cout << "Enter the number: ";
} } else {
else
{
n = strtoull(argv[1], nullptr, 10); n = strtoull(argv[1], nullptr, 10);
} }
std::cin >> n; std::cin >> n;

View File

@@ -21,8 +21,7 @@
* @param[in] quotient unsigned * @param[in] quotient unsigned
*/ */
template <typename T, typename T2> template <typename T, typename T2>
inline void update_step(T *r, T *r0, const T2 quotient) inline void update_step(T *r, T *r0, const T2 quotient) {
{
T temp = *r; T temp = *r;
*r = *r0 - (quotient * temp); *r = *r0 - (quotient * temp);
*r0 = temp; *r0 = temp;
@@ -39,8 +38,7 @@ inline void update_step(T *r, T *r0, const T2 quotient)
* @param[out] y signed * @param[out] y signed
*/ */
template <typename T1, typename T2> template <typename T1, typename T2>
void extendedEuclid_1(T1 A, T1 B, T1 *GCD, T2 *x, T2 *y) void extendedEuclid_1(T1 A, T1 B, T1 *GCD, T2 *x, T2 *y) {
{
if (B > A) if (B > A)
std::swap(A, B); // Ensure that A >= B std::swap(A, B); // Ensure that A >= B
@@ -48,8 +46,7 @@ void extendedEuclid_1(T1 A, T1 B, T1 *GCD, T2 *x, T2 *y)
T2 t = 1, t0 = 0; T2 t = 1, t0 = 0;
T1 r = B, r0 = A; T1 r = B, r0 = A;
while (r != 0) while (r != 0) {
{
T1 quotient = r0 / r; T1 quotient = r0 / r;
update_step(&r, &r0, quotient); update_step(&r, &r0, quotient);
update_step(&s, &s0, quotient); update_step(&s, &s0, quotient);
@@ -70,19 +67,15 @@ void extendedEuclid_1(T1 A, T1 B, T1 *GCD, T2 *x, T2 *y)
* @param[in,out] y signed * @param[in,out] y signed
*/ */
template <typename T, typename T2> template <typename T, typename T2>
void extendedEuclid(T A, T B, T *GCD, T2 *x, T2 *y) void extendedEuclid(T A, T B, T *GCD, T2 *x, T2 *y) {
{
if (B > A) if (B > A)
std::swap(A, B); // Ensure that A >= B std::swap(A, B); // Ensure that A >= B
if (B == 0) if (B == 0) {
{
*GCD = A; *GCD = A;
*x = 1; *x = 1;
*y = 0; *y = 0;
} } else {
else
{
extendedEuclid(B, A % B, GCD, x, y); extendedEuclid(B, A % B, GCD, x, y);
T2 temp = *x; T2 temp = *x;
*x = *y; *x = *y;
@@ -91,8 +84,7 @@ void extendedEuclid(T A, T B, T *GCD, T2 *x, T2 *y)
} }
/// Main function /// Main function
int main() int main() {
{
uint32_t a, b, gcd; uint32_t a, b, gcd;
int32_t x, y; int32_t x, y;
std::cin >> a >> b; std::cin >> a >> b;

View File

@@ -5,16 +5,14 @@
#include <iostream> #include <iostream>
/** function to find factorial of given number */ /** function to find factorial of given number */
unsigned int factorial(unsigned int n) unsigned int factorial(unsigned int n) {
{
if (n == 0) if (n == 0)
return 1; return 1;
return n * factorial(n - 1); return n * factorial(n - 1);
} }
/** Main function */ /** Main function */
int main() int main() {
{
int num = 5; int num = 5;
std::cout << "Factorial of " << num << " is " << factorial(num) std::cout << "Factorial of " << num << " is " << factorial(num)
<< std::endl; << std::endl;

View File

@@ -23,8 +23,7 @@
* algorithm implementation for \f$a^b\f$ * algorithm implementation for \f$a^b\f$
*/ */
template <typename T> template <typename T>
double fast_power_recursive(T a, T b) double fast_power_recursive(T a, T b) {
{
// negative power. a^b = 1 / (a^-b) // negative power. a^b = 1 / (a^-b)
if (b < 0) if (b < 0)
return 1.0 / fast_power_recursive(a, -b); return 1.0 / fast_power_recursive(a, -b);
@@ -48,15 +47,13 @@ double fast_power_recursive(T a, T b)
It still calculates in \f$O(\log N)\f$ It still calculates in \f$O(\log N)\f$
*/ */
template <typename T> template <typename T>
double fast_power_linear(T a, T b) double fast_power_linear(T a, T b) {
{
// negative power. a^b = 1 / (a^-b) // negative power. a^b = 1 / (a^-b)
if (b < 0) if (b < 0)
return 1.0 / fast_power_linear(a, -b); return 1.0 / fast_power_linear(a, -b);
double result = 1; double result = 1;
while (b) while (b) {
{
if (b & 1) if (b & 1)
result = result * a; result = result * a;
a = a * a; a = a * a;
@@ -68,14 +65,12 @@ double fast_power_linear(T a, T b)
/** /**
* Main function * Main function
*/ */
int main() int main() {
{
std::srand(std::time(nullptr)); std::srand(std::time(nullptr));
std::ios_base::sync_with_stdio(false); std::ios_base::sync_with_stdio(false);
std::cout << "Testing..." << std::endl; std::cout << "Testing..." << std::endl;
for (int i = 0; i < 20; i++) for (int i = 0; i < 20; i++) {
{
int a = std::rand() % 20 - 10; int a = std::rand() % 20 - 10;
int b = std::rand() % 20 - 10; int b = std::rand() % 20 - 10;
std::cout << std::endl << "Calculating " << a << "^" << b << std::endl; std::cout << std::endl << "Calculating " << a << "^" << b << std::endl;

View File

@@ -14,8 +14,7 @@
/** /**
* Recursively compute sequences * Recursively compute sequences
*/ */
int fibonacci(unsigned int n) int fibonacci(unsigned int n) {
{
/* If the input is 0 or 1 just return the same /* If the input is 0 or 1 just return the same
This will set the first 2 values of the sequence */ This will set the first 2 values of the sequence */
if (n <= 1) if (n <= 1)
@@ -26,8 +25,7 @@ int fibonacci(unsigned int n)
} }
/// Main function /// Main function
int main() int main() {
{
int n; int n;
std::cin >> n; std::cin >> n;
assert(n >= 0); assert(n >= 0);

View File

@@ -26,8 +26,7 @@ const uint64_t MAX = 93;
uint64_t f[MAX] = {0}; uint64_t f[MAX] = {0};
/** Algorithm */ /** Algorithm */
uint64_t fib(uint64_t n) uint64_t fib(uint64_t n) {
{
if (n == 0) if (n == 0)
return 0; return 0;
if (n == 1 || n == 2) if (n == 1 || n == 2)
@@ -44,11 +43,9 @@ uint64_t fib(uint64_t n)
} }
/** Main function */ /** Main function */
int main() int main() {
{
// Main Function // Main Function
for (uint64_t i = 1; i < 93; i++) for (uint64_t i = 1; i < 93; i++) {
{
std::cout << i << " th fibonacci number is " << fib(i) << std::endl; std::cout << i << " th fibonacci number is " << fib(i) << std::endl;
} }
return 0; return 0;

View File

@@ -20,13 +20,11 @@
* \f[f(n)=f(n-1)+f(n-2)\f] * \f[f(n)=f(n-1)+f(n-2)\f]
* and returns the result as a large_number type. * and returns the result as a large_number type.
*/ */
large_number fib(uint64_t n) large_number fib(uint64_t n) {
{
large_number f0(1); large_number f0(1);
large_number f1(1); large_number f1(1);
do do {
{
large_number f2 = f1; large_number f2 = f1;
f1 += f0; f1 += f0;
f0 = f2; f0 = f2;
@@ -36,15 +34,11 @@ large_number fib(uint64_t n)
return f1; return f1;
} }
int main(int argc, char *argv[]) int main(int argc, char *argv[]) {
{
uint64_t N; uint64_t N;
if (argc == 2) if (argc == 2) {
{
N = strtoull(argv[1], NULL, 10); N = strtoull(argv[1], NULL, 10);
} } else {
else
{
std::cout << "Enter N: "; std::cout << "Enter N: ";
std::cin >> N; std::cin >> N;
} }

View File

@@ -12,34 +12,27 @@
/** /**
* algorithm * algorithm
*/ */
int gcd(int num1, int num2) int gcd(int num1, int num2) {
{ if (num1 <= 0 | num2 <= 0) {
if (num1 <= 0 | num2 <= 0)
{
throw std::domain_error("Euclidean algorithm domain is for ints > 0"); throw std::domain_error("Euclidean algorithm domain is for ints > 0");
} }
if (num1 == num2) if (num1 == num2) {
{
return num1; return num1;
} }
int base_num = 0; int base_num = 0;
int previous_remainder = 1; int previous_remainder = 1;
if (num1 > num2) if (num1 > num2) {
{
base_num = num1; base_num = num1;
previous_remainder = num2; previous_remainder = num2;
} } else {
else
{
base_num = num2; base_num = num2;
previous_remainder = num1; previous_remainder = num1;
} }
while ((base_num % previous_remainder) != 0) while ((base_num % previous_remainder) != 0) {
{
int old_base = base_num; int old_base = base_num;
base_num = previous_remainder; base_num = previous_remainder;
previous_remainder = old_base % previous_remainder; previous_remainder = old_base % previous_remainder;
@@ -51,15 +44,11 @@ int gcd(int num1, int num2)
/** /**
* Main function * Main function
*/ */
int main() int main() {
{
std::cout << "gcd of 120,7 is " << (gcd(120, 7)) << std::endl; std::cout << "gcd of 120,7 is " << (gcd(120, 7)) << std::endl;
try try {
{
std::cout << "gcd of -120,10 is " << gcd(-120, 10) << std::endl; std::cout << "gcd of -120,10 is " << gcd(-120, 10) << std::endl;
} } catch (const std::domain_error &e) {
catch (const std::domain_error &e)
{
std::cout << "Error handling was successful" << std::endl; std::cout << "Error handling was successful" << std::endl;
} }
std::cout << "gcd of 312,221 is " << (gcd(312, 221)) << std::endl; std::cout << "gcd of 312,221 is " << (gcd(312, 221)) << std::endl;

View File

@@ -12,12 +12,10 @@
* @param[in] a array of integers to compute GCD for * @param[in] a array of integers to compute GCD for
* @param[in] n number of integers in array `a` * @param[in] n number of integers in array `a`
*/ */
int gcd(int *a, int n) int gcd(int *a, int n) {
{
int j = 1; // to access all elements of the array starting from 1 int j = 1; // to access all elements of the array starting from 1
int gcd = a[0]; int gcd = a[0];
while (j < n) while (j < n) {
{
if (a[j] % gcd == 0) // value of gcd is as needed so far if (a[j] % gcd == 0) // value of gcd is as needed so far
j++; // so we check for next element j++; // so we check for next element
else else
@@ -27,8 +25,7 @@ int gcd(int *a, int n)
} }
/** Main function */ /** Main function */
int main() int main() {
{
int n; int n;
std::cout << "Enter value of n:" << std::endl; std::cout << "Enter value of n:" << std::endl;
std::cin >> n; std::cin >> n;

View File

@@ -11,15 +11,12 @@
/** /**
* algorithm * algorithm
*/ */
int gcd(int num1, int num2) int gcd(int num1, int num2) {
{ if (num1 <= 0 | num2 <= 0) {
if (num1 <= 0 | num2 <= 0)
{
throw std::domain_error("Euclidean algorithm domain is for ints > 0"); throw std::domain_error("Euclidean algorithm domain is for ints > 0");
} }
if (num1 == num2) if (num1 == num2) {
{
return num1; return num1;
} }
@@ -42,15 +39,11 @@ int gcd(int num1, int num2)
/** /**
* Main function * Main function
*/ */
int main() int main() {
{
std::cout << "gcd of 120,7 is " << (gcd(120, 7)) << std::endl; std::cout << "gcd of 120,7 is " << (gcd(120, 7)) << std::endl;
try try {
{
std::cout << "gcd of -120,10 is " << gcd(-120, 10) << std::endl; std::cout << "gcd of -120,10 is " << gcd(-120, 10) << std::endl;
} } catch (const std::domain_error &e) {
catch (const std::domain_error &e)
{
std::cout << "Error handling was successful" << std::endl; std::cout << "Error handling was successful" << std::endl;
} }
std::cout << "gcd of 312,221 is " << (gcd(312, 221)) << std::endl; std::cout << "gcd of 312,221 is " << (gcd(312, 221)) << std::endl;

View File

@@ -13,8 +13,7 @@
/** Test implementation for 10! Result must be 3628800. /** Test implementation for 10! Result must be 3628800.
* @returns True if test pass else False * @returns True if test pass else False
*/ */
bool test1() bool test1() {
{
std::cout << "---- Check 1\t"; std::cout << "---- Check 1\t";
unsigned int i, number = 10; unsigned int i, number = 10;
large_number result; large_number result;
@@ -24,18 +23,15 @@ bool test1()
const char *known_reslt = "3628800"; const char *known_reslt = "3628800";
/* check 1 */ /* check 1 */
if (strlen(known_reslt) != result.num_digits()) if (strlen(known_reslt) != result.num_digits()) {
{
std::cerr << "Result lengths dont match! " << strlen(known_reslt) std::cerr << "Result lengths dont match! " << strlen(known_reslt)
<< " != " << result.num_digits() << std::endl; << " != " << result.num_digits() << std::endl;
return false; return false;
} }
const size_t N = result.num_digits(); const size_t N = result.num_digits();
for (i = 0; i < N; i++) for (i = 0; i < N; i++) {
{ if (known_reslt[i] != result.digit_char(i)) {
if (known_reslt[i] != result.digit_char(i))
{
std::cerr << i << "^th digit mismatch! " << known_reslt[i] std::cerr << i << "^th digit mismatch! " << known_reslt[i]
<< " != " << result.digit_char(i) << std::endl; << " != " << result.digit_char(i) << std::endl;
return false; return false;
@@ -54,8 +50,7 @@ bool test1()
* ``` * ```
* @returns True if test pass else False * @returns True if test pass else False
*/ */
bool test2() bool test2() {
{
std::cout << "---- Check 2\t"; std::cout << "---- Check 2\t";
unsigned int i, number = 100; unsigned int i, number = 100;
large_number result; large_number result;
@@ -68,18 +63,15 @@ bool test2()
"000000000000000000"; "000000000000000000";
/* check 1 */ /* check 1 */
if (strlen(known_reslt) != result.num_digits()) if (strlen(known_reslt) != result.num_digits()) {
{
std::cerr << "Result lengths dont match! " << strlen(known_reslt) std::cerr << "Result lengths dont match! " << strlen(known_reslt)
<< " != " << result.num_digits() << std::endl; << " != " << result.num_digits() << std::endl;
return false; return false;
} }
const size_t N = result.num_digits(); const size_t N = result.num_digits();
for (i = 0; i < N; i++) for (i = 0; i < N; i++) {
{ if (known_reslt[i] != result.digit_char(i)) {
if (known_reslt[i] != result.digit_char(i))
{
std::cerr << i << "^th digit mismatch! " << known_reslt[i] std::cerr << i << "^th digit mismatch! " << known_reslt[i]
<< " != " << result.digit_char(i) << std::endl; << " != " << result.digit_char(i) << std::endl;
return false; return false;
@@ -93,16 +85,12 @@ bool test2()
/** /**
* Main program * Main program
**/ **/
int main(int argc, char *argv[]) int main(int argc, char *argv[]) {
{
int number, i; int number, i;
if (argc == 2) if (argc == 2) {
{
number = atoi(argv[1]); number = atoi(argv[1]);
} } else {
else
{
std::cout << "Enter the value of n(n starts from 0 ): "; std::cout << "Enter the value of n(n starts from 0 ): ";
std::cin >> number; std::cin >> number;
} }

View File

@@ -20,8 +20,7 @@
* digit to the number, perform multiplication of * digit to the number, perform multiplication of
* large number with long unsigned integers. * large number with long unsigned integers.
**/ **/
class large_number class large_number {
{
public: public:
/**< initializer with value = 1 */ /**< initializer with value = 1 */
large_number() { _digits.push_back(1); } large_number() { _digits.push_back(1); }
@@ -36,11 +35,9 @@ class large_number
// } // }
/**< initializer from an integer */ /**< initializer from an integer */
explicit large_number(int n) explicit large_number(int n) {
{
int carry = n; int carry = n;
do do {
{
add_digit(carry % 10); add_digit(carry % 10);
carry /= 10; carry /= 10;
} while (carry != 0); } while (carry != 0);
@@ -53,10 +50,8 @@ class large_number
explicit large_number(std::vector<unsigned char> &vec) : _digits(vec) {} explicit large_number(std::vector<unsigned char> &vec) : _digits(vec) {}
/**< initializer from a string */ /**< initializer from a string */
explicit large_number(char const *number_str) explicit large_number(char const *number_str) {
{ for (size_t i = strlen(number_str); i > 0; i--) {
for (size_t i = strlen(number_str); i > 0; i--)
{
unsigned char a = number_str[i - 1] - '0'; unsigned char a = number_str[i - 1] - '0';
if (a >= 0 && a <= 9) if (a >= 0 && a <= 9)
_digits.push_back(a); _digits.push_back(a);
@@ -66,55 +61,48 @@ class large_number
/** /**
* Function to check implementation * Function to check implementation
**/ **/
static bool test() static bool test() {
{
std::cout << "------ Checking `large_number` class implementations\t" std::cout << "------ Checking `large_number` class implementations\t"
<< std::endl; << std::endl;
large_number a(40); large_number a(40);
// 1. test multiplication // 1. test multiplication
a *= 10; a *= 10;
if (a != large_number(400)) if (a != large_number(400)) {
{
std::cerr << "\tFailed 1/6 (" << a << "!=400)" << std::endl; std::cerr << "\tFailed 1/6 (" << a << "!=400)" << std::endl;
return false; return false;
} }
std::cout << "\tPassed 1/6..."; std::cout << "\tPassed 1/6...";
// 2. test compound addition with integer // 2. test compound addition with integer
a += 120; a += 120;
if (a != large_number(520)) if (a != large_number(520)) {
{
std::cerr << "\tFailed 2/6 (" << a << "!=520)" << std::endl; std::cerr << "\tFailed 2/6 (" << a << "!=520)" << std::endl;
return false; return false;
} }
std::cout << "\tPassed 2/6..."; std::cout << "\tPassed 2/6...";
// 3. test compound multiplication again // 3. test compound multiplication again
a *= 10; a *= 10;
if (a != large_number(5200)) if (a != large_number(5200)) {
{
std::cerr << "\tFailed 3/6 (" << a << "!=5200)" << std::endl; std::cerr << "\tFailed 3/6 (" << a << "!=5200)" << std::endl;
return false; return false;
} }
std::cout << "\tPassed 3/6..."; std::cout << "\tPassed 3/6...";
// 4. test increment (prefix) // 4. test increment (prefix)
++a; ++a;
if (a != large_number(5201)) if (a != large_number(5201)) {
{
std::cerr << "\tFailed 4/6 (" << a << "!=5201)" << std::endl; std::cerr << "\tFailed 4/6 (" << a << "!=5201)" << std::endl;
return false; return false;
} }
std::cout << "\tPassed 4/6..."; std::cout << "\tPassed 4/6...";
// 5. test increment (postfix) // 5. test increment (postfix)
a++; a++;
if (a != large_number(5202)) if (a != large_number(5202)) {
{
std::cerr << "\tFailed 5/6 (" << a << "!=5202)" << std::endl; std::cerr << "\tFailed 5/6 (" << a << "!=5202)" << std::endl;
return false; return false;
} }
std::cout << "\tPassed 5/6..."; std::cout << "\tPassed 5/6...";
// 6. test addition with another large number // 6. test addition with another large number
a = a + large_number("7000000000000000000000000000000"); a = a + large_number("7000000000000000000000000000000");
if (a != large_number("7000000000000000000000000005202")) if (a != large_number("7000000000000000000000000005202")) {
{
std::cerr << "\tFailed 6/6 (" << a std::cerr << "\tFailed 6/6 (" << a
<< "!=7000000000000000000000000005202)" << std::endl; << "!=7000000000000000000000000005202)" << std::endl;
return false; return false;
@@ -126,10 +114,8 @@ class large_number
/** /**
* add a digit at MSB to the large number * add a digit at MSB to the large number
**/ **/
void add_digit(unsigned int value) void add_digit(unsigned int value) {
{ if (value > 9) {
if (value > 9)
{
std::cerr << "digit > 9!!\n"; std::cerr << "digit > 9!!\n";
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
@@ -149,16 +135,14 @@ class large_number
**/ **/
inline unsigned char &operator[](size_t n) { return this->_digits[n]; } inline unsigned char &operator[](size_t n) { return this->_digits[n]; }
inline const unsigned char &operator[](size_t n) const inline const unsigned char &operator[](size_t n) const {
{
return this->_digits[n]; return this->_digits[n];
} }
/** /**
* operator overload to compare two numbers * operator overload to compare two numbers
**/ **/
friend std::ostream &operator<<(std::ostream &out, const large_number &a) friend std::ostream &operator<<(std::ostream &out, const large_number &a) {
{
for (size_t i = a.num_digits(); i > 0; i--) for (size_t i = a.num_digits(); i > 0; i--)
out << static_cast<int>(a[i - 1]); out << static_cast<int>(a[i - 1]);
return out; return out;
@@ -167,8 +151,7 @@ class large_number
/** /**
* operator overload to compare two numbers * operator overload to compare two numbers
**/ **/
friend bool operator==(large_number const &a, large_number const &b) friend bool operator==(large_number const &a, large_number const &b) {
{
size_t N = a.num_digits(); size_t N = a.num_digits();
if (N != b.num_digits()) if (N != b.num_digits())
return false; return false;
@@ -181,16 +164,14 @@ class large_number
/** /**
* operator overload to compare two numbers * operator overload to compare two numbers
**/ **/
friend bool operator!=(large_number const &a, large_number const &b) friend bool operator!=(large_number const &a, large_number const &b) {
{
return !(a == b); return !(a == b);
} }
/** /**
* operator overload to increment (prefix) * operator overload to increment (prefix)
**/ **/
large_number &operator++() large_number &operator++() {
{
(*this) += 1; (*this) += 1;
return *this; return *this;
} }
@@ -198,8 +179,7 @@ class large_number
/** /**
* operator overload to increment (postfix) * operator overload to increment (postfix)
**/ **/
large_number &operator++(int) large_number &operator++(int) {
{
static large_number tmp(_digits); static large_number tmp(_digits);
++(*this); ++(*this);
return tmp; return tmp;
@@ -208,15 +188,13 @@ class large_number
/** /**
* operator overload to add * operator overload to add
**/ **/
large_number &operator+=(large_number n) large_number &operator+=(large_number n) {
{
// if adding with another large_number // if adding with another large_number
large_number *b = reinterpret_cast<large_number *>(&n); large_number *b = reinterpret_cast<large_number *>(&n);
const size_t max_L = std::max(this->num_digits(), b->num_digits()); const size_t max_L = std::max(this->num_digits(), b->num_digits());
unsigned int carry = 0; unsigned int carry = 0;
size_t i; size_t i;
for (i = 0; i < max_L || carry != 0; i++) for (i = 0; i < max_L || carry != 0; i++) {
{
if (i < b->num_digits()) if (i < b->num_digits())
carry += (*b)[i]; carry += (*b)[i];
if (i < this->num_digits()) if (i < this->num_digits())
@@ -238,8 +216,7 @@ class large_number
* operator overload to perform addition * operator overload to perform addition
**/ **/
template <class T> template <class T>
friend large_number &operator+(const large_number &a, const T &b) friend large_number &operator+(const large_number &a, const T &b) {
{
static large_number c = a; static large_number c = a;
c += b; c += b;
return c; return c;
@@ -248,8 +225,7 @@ class large_number
/** /**
* assignment operator * assignment operator
**/ **/
large_number &operator=(const large_number &b) large_number &operator=(const large_number &b) {
{
this->_digits = b._digits; this->_digits = b._digits;
return *this; return *this;
} }
@@ -258,8 +234,7 @@ class large_number
* operator overload to increment * operator overload to increment
**/ **/
template <class T> template <class T>
large_number &operator*=(const T n) large_number &operator*=(const T n) {
{
static_assert(std::is_integral<T>::value, static_assert(std::is_integral<T>::value,
"Must be integer addition unsigned integer types."); "Must be integer addition unsigned integer types.");
this->multiply(n); this->multiply(n);
@@ -269,8 +244,7 @@ class large_number
/** /**
* returns i^th digit as an ASCII character * returns i^th digit as an ASCII character
**/ **/
const char digit_char(size_t i) const const char digit_char(size_t i) const {
{
return _digits[num_digits() - i - 1] + '0'; return _digits[num_digits() - i - 1] + '0';
} }
@@ -280,8 +254,7 @@ class large_number
* store the result in the same large number * store the result in the same large number
**/ **/
template <class T> template <class T>
void multiply(const T n) void multiply(const T n) {
{
static_assert(std::is_integral<T>::value, static_assert(std::is_integral<T>::value,
"Can only have integer types."); "Can only have integer types.");
// assert(!(std::is_signed<T>::value)); //, "Implemented only for // assert(!(std::is_signed<T>::value)); //, "Implemented only for
@@ -289,24 +262,19 @@ class large_number
size_t i; size_t i;
uint64_t carry = 0, temp; uint64_t carry = 0, temp;
for (i = 0; i < this->num_digits(); i++) for (i = 0; i < this->num_digits(); i++) {
{
temp = (*this)[i] * n; temp = (*this)[i] * n;
temp += carry; temp += carry;
if (temp < 10) if (temp < 10) {
{
carry = 0; carry = 0;
} } else {
else
{
carry = temp / 10; carry = temp / 10;
temp = temp % 10; temp = temp % 10;
} }
(*this)[i] = temp; (*this)[i] = temp;
} }
while (carry != 0) while (carry != 0) {
{
this->add_digit(carry % 10); this->add_digit(carry % 10);
carry /= 10; carry /= 10;
} }

View File

@@ -49,14 +49,11 @@
/** Recursive function to calculate exponent in \f$O(\log n)\f$ using binary /** Recursive function to calculate exponent in \f$O(\log n)\f$ using binary
* exponent. * exponent.
*/ */
int64_t binExpo(int64_t a, int64_t b, int64_t m) int64_t binExpo(int64_t a, int64_t b, int64_t m) {
{
a %= m; a %= m;
int64_t res = 1; int64_t res = 1;
while (b > 0) while (b > 0) {
{ if (b % 2) {
if (b % 2)
{
res = res * a % m; res = res * a % m;
} }
a = a * a % m; a = a * a % m;
@@ -68,18 +65,12 @@ int64_t binExpo(int64_t a, int64_t b, int64_t m)
/** Prime check in \f$O(\sqrt{m})\f$ time. /** Prime check in \f$O(\sqrt{m})\f$ time.
*/ */
bool isPrime(int64_t m) bool isPrime(int64_t m) {
{ if (m <= 1) {
if (m <= 1)
{
return false; return false;
} } else {
else for (int64_t i = 2; i * i <= m; i++) {
{ if (m % i == 0) {
for (int64_t i = 2; i * i <= m; i++)
{
if (m % i == 0)
{
return false; return false;
} }
} }
@@ -90,21 +81,17 @@ bool isPrime(int64_t m)
/** /**
* Main function * Main function
*/ */
int main() int main() {
{
int64_t a, m; int64_t a, m;
// Take input of a and m. // Take input of a and m.
std::cout << "Computing ((a^(-1))%(m)) using Fermat's Little Theorem"; std::cout << "Computing ((a^(-1))%(m)) using Fermat's Little Theorem";
std::cout << std::endl << std::endl; std::cout << std::endl << std::endl;
std::cout << "Give input 'a' and 'm' space separated : "; std::cout << "Give input 'a' and 'm' space separated : ";
std::cin >> a >> m; std::cin >> a >> m;
if (isPrime(m)) if (isPrime(m)) {
{
std::cout << "The modular inverse of a with mod m is (a^(m-2)) : "; std::cout << "The modular inverse of a with mod m is (a^(m-2)) : ";
std::cout << binExpo(a, m - 2, m) << std::endl; std::cout << binExpo(a, m - 2, m) << std::endl;
} } else {
else
{
std::cout << "m must be a prime number."; std::cout << "m must be a prime number.";
std::cout << std::endl; std::cout << std::endl;
} }

View File

@@ -31,31 +31,25 @@ respectively.
/** /**
* Algorithm * Algorithm
*/ */
int number_of_positive_divisors(int n) int number_of_positive_divisors(int n) {
{
std::vector<int> prime_exponent_count; std::vector<int> prime_exponent_count;
for (int i = 2; i * i <= n; i++) for (int i = 2; i * i <= n; i++) {
{
int prime_count = 0; int prime_count = 0;
while (n % i == 0) while (n % i == 0) {
{
prime_count += 1; prime_count += 1;
n /= i; n /= i;
} }
if (prime_count != 0) if (prime_count != 0) {
{
prime_exponent_count.push_back(prime_count); prime_exponent_count.push_back(prime_count);
} }
} }
if (n > 1) if (n > 1) {
{
prime_exponent_count.push_back(1); prime_exponent_count.push_back(1);
} }
int divisors_count = 1; int divisors_count = 1;
for (int i = 0; i < prime_exponent_count.size(); i++) for (int i = 0; i < prime_exponent_count.size(); i++) {
{
divisors_count = divisors_count * (prime_exponent_count[i] + 1); divisors_count = divisors_count * (prime_exponent_count[i] + 1);
} }
@@ -65,20 +59,15 @@ int number_of_positive_divisors(int n)
/** /**
* Main function * Main function
*/ */
int main() int main() {
{
int n; int n;
std::cin >> n; std::cin >> n;
if (n < 0) if (n < 0) {
{
n = -n; n = -n;
} }
if (n == 0) if (n == 0) {
{
std::cout << "All non-zero numbers are divisors of 0 !" << std::endl; std::cout << "All non-zero numbers are divisors of 0 !" << std::endl;
} } else {
else
{
std::cout << "Number of positive divisors is : "; std::cout << "Number of positive divisors is : ";
std::cout << number_of_positive_divisors(n) << std::endl; std::cout << number_of_positive_divisors(n) << std::endl;
} }

View File

@@ -22,15 +22,13 @@
* @param res large number representation using array * @param res large number representation using array
* @param res_size number of digits in `res` * @param res_size number of digits in `res`
*/ */
int multiply(int x, int res[], int res_size) int multiply(int x, int res[], int res_size) {
{
// Initialize carry // Initialize carry
int carry = 0; int carry = 0;
// One by one multiply n with // One by one multiply n with
// individual digits of res[] // individual digits of res[]
for (int i = 0; i < res_size; i++) for (int i = 0; i < res_size; i++) {
{
int prod = res[i] * x + carry; int prod = res[i] * x + carry;
// Store last digit of // Store last digit of
@@ -43,8 +41,7 @@ int multiply(int x, int res[], int res_size)
// Put carry in res and // Put carry in res and
// increase result size // increase result size
while (carry) while (carry) {
{
res[res_size] = carry % 10; res[res_size] = carry % 10;
carry = carry / 10; carry = carry / 10;
res_size++; res_size++;
@@ -56,11 +53,9 @@ int multiply(int x, int res[], int res_size)
* @param x base * @param x base
* @param n exponent * @param n exponent
*/ */
void power(int x, int n) void power(int x, int n) {
{
// printing value "1" for power = 0 // printing value "1" for power = 0
if (n == 0) if (n == 0) {
{
std::cout << "1"; std::cout << "1";
return; return;
} }
@@ -70,8 +65,7 @@ void power(int x, int n)
int temp = x; int temp = x;
// Initialize result // Initialize result
while (temp != 0) while (temp != 0) {
{
res[res_size++] = temp % 10; res[res_size++] = temp % 10;
temp = temp / 10; temp = temp / 10;
} }
@@ -85,8 +79,7 @@ void power(int x, int n)
} }
/** Main function */ /** Main function */
int main() int main() {
{
int exponent, base; int exponent, base;
std::cout << "Enter base "; std::cout << "Enter base ";
std::cin >> base; std::cin >> base;

View File

@@ -20,43 +20,35 @@ std::vector<std::pair<int, int>> factors;
/** Calculating prime number upto a given range /** Calculating prime number upto a given range
*/ */
void SieveOfEratosthenes(int N) void SieveOfEratosthenes(int N) {
{
// initializes the array isprime // initializes the array isprime
memset(isprime, true, sizeof isprime); memset(isprime, true, sizeof isprime);
for (int i = 2; i <= N; i++) for (int i = 2; i <= N; i++) {
{ if (isprime[i]) {
if (isprime[i])
{
for (int j = 2 * i; j <= N; j += i) isprime[j] = false; for (int j = 2 * i; j <= N; j += i) isprime[j] = false;
} }
} }
for (int i = 2; i <= N; i++) for (int i = 2; i <= N; i++) {
{
if (isprime[i]) if (isprime[i])
prime_numbers.push_back(i); prime_numbers.push_back(i);
} }
} }
/** Prime factorization of a number */ /** Prime factorization of a number */
void prime_factorization(int num) void prime_factorization(int num) {
{
int number = num; int number = num;
for (int i = 0; prime_numbers[i] <= num; i++) for (int i = 0; prime_numbers[i] <= num; i++) {
{
int count = 0; int count = 0;
// termination condition // termination condition
if (number == 1) if (number == 1) {
{
break; break;
} }
while (number % prime_numbers[i] == 0) while (number % prime_numbers[i] == 0) {
{
count++; count++;
number = number / prime_numbers[i]; number = number / prime_numbers[i];
} }
@@ -67,8 +59,7 @@ void prime_factorization(int num)
} }
/** Main program */ /** Main program */
int main() int main() {
{
int num; int num;
std::cout << "\t\tComputes the prime factorization\n\n"; std::cout << "\t\tComputes the prime factorization\n\n";
std::cout << "Type in a number: "; std::cout << "Type in a number: ";
@@ -79,8 +70,7 @@ int main()
prime_factorization(num); prime_factorization(num);
// Prime factors with their powers in the given number in new line // Prime factors with their powers in the given number in new line
for (auto it : factors) for (auto it : factors) {
{
std::cout << it.first << " " << it.second << std::endl; std::cout << it.first << " " << it.second << std::endl;
} }

Some files were not shown because too many files have changed in this diff Show More