Merge branch 'master' into circular-linked-list

This commit is contained in:
David Leal 2021-10-30 20:37:29 -05:00 committed by GitHub
commit 06f11f1edc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
22 changed files with 1235 additions and 558 deletions

View File

@ -124,6 +124,7 @@
* [Hamiltons Cycle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/hamiltons_cycle.cpp) * [Hamiltons Cycle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/hamiltons_cycle.cpp)
* [Hopcroft Karp](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/hopcroft_karp.cpp) * [Hopcroft Karp](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/hopcroft_karp.cpp)
* [Is Graph Bipartite](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/is_graph_bipartite.cpp) * [Is Graph Bipartite](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/is_graph_bipartite.cpp)
* [Is Graph Bipartite2](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/is_graph_bipartite2.cpp)
* [Kosaraju](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/kosaraju.cpp) * [Kosaraju](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/kosaraju.cpp)
* [Kruskal](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/kruskal.cpp) * [Kruskal](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/kruskal.cpp)
* [Lowest Common Ancestor](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/lowest_common_ancestor.cpp) * [Lowest Common Ancestor](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/lowest_common_ancestor.cpp)
@ -217,6 +218,7 @@
* [Sum Of Binomial Coefficient](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/sum_of_binomial_coefficient.cpp) * [Sum Of Binomial Coefficient](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/sum_of_binomial_coefficient.cpp)
* [Sum Of Digits](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/sum_of_digits.cpp) * [Sum Of Digits](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/sum_of_digits.cpp)
* [Vector Cross Product](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/vector_cross_product.cpp) * [Vector Cross Product](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/vector_cross_product.cpp)
* [Volume](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/volume.cpp)
## Numerical Methods ## Numerical Methods
* [Bisection Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/bisection_method.cpp) * [Bisection Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/bisection_method.cpp)
@ -338,7 +340,7 @@
* [Radix Sort2](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/radix_sort2.cpp) * [Radix Sort2](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/radix_sort2.cpp)
* [Random Pivot Quick Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/random_pivot_quick_sort.cpp) * [Random Pivot Quick Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/random_pivot_quick_sort.cpp)
* [Recursive Bubble Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/recursive_bubble_sort.cpp) * [Recursive Bubble Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/recursive_bubble_sort.cpp)
* [Selection Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/selection_sort.cpp) * [Selection Sort Iterative](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/selection_sort_iterative.cpp)
* [Selection Sort Recursive](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/selection_sort_recursive.cpp) * [Selection Sort Recursive](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/selection_sort_recursive.cpp)
* [Shell Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/shell_sort.cpp) * [Shell Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/shell_sort.cpp)
* [Shell Sort2](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/shell_sort2.cpp) * [Shell Sort2](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/shell_sort2.cpp)

View File

@ -17,29 +17,38 @@
* @author [Anup Kumar Panwar](https://github.com/AnupKumarPanwar) * @author [Anup Kumar Panwar](https://github.com/AnupKumarPanwar)
* @author [David Leal](https://github.com/Panquesito7) * @author [David Leal](https://github.com/Panquesito7)
*/ */
#include <array>
#include <iostream> #include <array> /// for std::array
#include <vector> #include <iostream> /// for IO operations
#include <vector> /// for std::vector
/** /**
* @namespace * @namespace backtracking
* @brief Backtracking algorithms * @brief Backtracking algorithms
*/ */
namespace backtracking { namespace backtracking {
/** A utility function to print solution /**
* @namespace graph_coloring
* @brief Functions for the [Graph
* Coloring](https://en.wikipedia.org/wiki/Graph_coloring) algorithm,
*/
namespace graph_coloring {
/**
* @brief A utility function to print the solution
* @tparam V number of vertices in the graph * @tparam V number of vertices in the graph
* @param color array of colors assigned to the nodes * @param color array of colors assigned to the nodes
*/ */
template <size_t V> template <size_t V>
void printSolution(const std::array<int, V>& color) { void printSolution(const std::array<int, V>& color) {
std::cout << "Following are the assigned colors" << std::endl; std::cout << "Following are the assigned colors\n";
for (auto& col : color) { for (auto& col : color) {
std::cout << col; std::cout << col;
} }
std::cout << std::endl; std::cout << "\n";
} }
/** A utility function to check if the current color assignment is safe for /**
* @brief Utility function to check if the current color assignment is safe for
* vertex v * vertex v
* @tparam V number of vertices in the graph * @tparam V number of vertices in the graph
* @param v index of graph vertex to check * @param v index of graph vertex to check
@ -60,7 +69,8 @@ bool isSafe(int v, const std::array<std::array<int, V>, V>& graph,
return true; return true;
} }
/** A recursive utility function to solve m coloring problem /**
* @brief Recursive utility function to solve m coloring problem
* @tparam V number of vertices in the graph * @tparam V number of vertices in the graph
* @param graph matrix of graph nonnectivity * @param graph matrix of graph nonnectivity
* @param m number of colors * @param m number of colors
@ -74,28 +84,30 @@ void graphColoring(const std::array<std::array<int, V>, V>& graph, int m,
// base case: // base case:
// If all vertices are assigned a color then return true // If all vertices are assigned a color then return true
if (v == V) { if (v == V) {
backtracking::printSolution<V>(color); printSolution<V>(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 (backtracking::isSafe<V>(v, graph, color, c)) { if (isSafe<V>(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
backtracking::graphColoring<V>(graph, m, color, v + 1); graphColoring<V>(graph, m, color, v + 1);
// If assigning color c doesn't lead to a solution then remove it // If assigning color c doesn't lead to a solution then remove it
color[v] = 0; color[v] = 0;
} }
} }
} }
} // namespace graph_coloring
} // namespace backtracking } // namespace backtracking
/** /**
* Main function * @brief Main function
* @returns 0 on exit
*/ */
int main() { int main() {
// Create following graph and test whether it is 3 colorable // Create following graph and test whether it is 3 colorable
@ -113,6 +125,6 @@ int main() {
int m = 3; // Number of colors int m = 3; // Number of colors
std::array<int, V> color{}; std::array<int, V> color{};
backtracking::graphColoring<V>(graph, m, color, 0); backtracking::graph_coloring::graphColoring<V>(graph, m, color, 0);
return 0; return 0;
} }

View File

@ -1,6 +1,7 @@
/** /**
* @file * @file
* @brief [Knight's tour](https://en.wikipedia.org/wiki/Knight%27s_tour) algorithm * @brief [Knight's tour](https://en.wikipedia.org/wiki/Knight%27s_tour)
* algorithm
* *
* @details * @details
* A knight's tour is a sequence of moves of a knight on a chessboard * A knight's tour is a sequence of moves of a knight on a chessboard
@ -12,92 +13,102 @@
* @author [Nikhil Arora](https://github.com/nikhilarora068) * @author [Nikhil Arora](https://github.com/nikhilarora068)
* @author [David Leal](https://github.com/Panquesito7) * @author [David Leal](https://github.com/Panquesito7)
*/ */
#include <iostream> #include <array> /// for std::array
#include <array> #include <iostream> /// for IO operations
/** /**
* @namespace backtracking * @namespace backtracking
* @brief Backtracking algorithms * @brief Backtracking algorithms
*/ */
namespace backtracking { namespace backtracking {
/** /**
* A utility function to check if i,j are valid indexes for N*N chessboard * @namespace knight_tour
* @tparam V number of vertices in array * @brief Functions for the [Knight's
* @param x current index in rows * tour](https://en.wikipedia.org/wiki/Knight%27s_tour) algorithm
* @param y current index in columns */
* @param sol matrix where numbers are saved namespace knight_tour {
* @returns `true` if .... /**
* @returns `false` if .... * A utility function to check if i,j are valid indexes for N*N chessboard
*/ * @tparam V number of vertices in array
template <size_t V> * @param x current index in rows
bool issafe(int x, int y, const std::array <std::array <int, V>, V>& sol) { * @param y current index in columns
return (x < V && x >= 0 && y < V && y >= 0 && sol[x][y] == -1); * @param sol matrix where numbers are saved
} * @returns `true` if ....
* @returns `false` if ....
/** */
* Knight's tour algorithm template <size_t V>
* @tparam V number of vertices in array bool issafe(int x, int y, const std::array<std::array<int, V>, V> &sol) {
* @param x current index in rows return (x < V && x >= 0 && y < V && y >= 0 && sol[x][y] == -1);
* @param y current index in columns }
* @param mov movement to be done
* @param sol matrix where numbers are saved
* @param xmov next move of knight (x coordinate)
* @param ymov next move of knight (y coordinate)
* @returns `true` if solution exists
* @returns `false` if solution does not exist
*/
template <size_t V>
bool solve(int x, int y, int mov, std::array <std::array <int, V>, V> &sol,
const std::array <int, V> &xmov, std::array <int, V> &ymov) {
int k, xnext, ynext;
if (mov == V * V) {
return true;
}
for (k = 0; k < V; k++) {
xnext = x + xmov[k];
ynext = y + ymov[k];
if (backtracking::issafe<V>(xnext, ynext, sol)) {
sol[xnext][ynext] = mov;
if (backtracking::solve<V>(xnext, ynext, mov + 1, sol, xmov, ymov) == true) {
return true;
}
else {
sol[xnext][ynext] = -1;
}
}
}
return false;
}
} // namespace backtracking
/** /**
* Main function * Knight's tour algorithm
* @tparam V number of vertices in array
* @param x current index in rows
* @param y current index in columns
* @param mov movement to be done
* @param sol matrix where numbers are saved
* @param xmov next move of knight (x coordinate)
* @param ymov next move of knight (y coordinate)
* @returns `true` if solution exists
* @returns `false` if solution does not exist
*/
template <size_t V>
bool solve(int x, int y, int mov, std::array<std::array<int, V>, V> &sol,
const std::array<int, V> &xmov, std::array<int, V> &ymov) {
int k = 0, xnext = 0, ynext = 0;
if (mov == V * V) {
return true;
}
for (k = 0; k < V; k++) {
xnext = x + xmov[k];
ynext = y + ymov[k];
if (issafe<V>(xnext, ynext, sol)) {
sol[xnext][ynext] = mov;
if (solve<V>(xnext, ynext, mov + 1, sol, xmov, ymov) == true) {
return true;
} else {
sol[xnext][ynext] = -1;
}
}
}
return false;
}
} // namespace knight_tour
} // namespace backtracking
/**
* @brief Main function
* @returns 0 on exit
*/ */
int main() { int main() {
const int n = 8; const int n = 8;
std::array <std::array <int, n>, n> sol = { 0 }; std::array<std::array<int, n>, n> sol = {0};
int i, j; int i = 0, j = 0;
for (i = 0; i < n; i++) { for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) { sol[i][j] = -1; } for (j = 0; j < n; j++) {
sol[i][j] = -1;
}
} }
std::array <int, n> xmov = { 2, 1, -1, -2, -2, -1, 1, 2 }; std::array<int, n> xmov = {2, 1, -1, -2, -2, -1, 1, 2};
std::array <int, n> ymov = { 1, 2, 2, 1, -1, -2, -2, -1 }; std::array<int, n> ymov = {1, 2, 2, 1, -1, -2, -2, -1};
sol[0][0] = 0; sol[0][0] = 0;
bool flag = backtracking::solve<n>(0, 0, 1, sol, xmov, ymov); bool flag = backtracking::knight_tour::solve<n>(0, 0, 1, sol, xmov, ymov);
if (flag == false) { if (flag == false) {
std::cout << "Error: Solution does not exist\n"; std::cout << "Error: Solution does not exist\n";
} } else {
else {
for (i = 0; i < n; i++) { for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) { std::cout << sol[i][j] << " "; } for (j = 0; j < n; j++) {
std::cout << sol[i][j] << " ";
}
std::cout << "\n"; std::cout << "\n";
} }
} }

View File

@ -6,33 +6,34 @@
* @details * @details
* Minimax (sometimes MinMax, MM or saddle point) is a decision rule used in * Minimax (sometimes MinMax, MM or saddle point) is a decision rule used in
* artificial intelligence, decision theory, game theory, statistics, * artificial intelligence, decision theory, game theory, statistics,
* and philosophy for minimizing the possible loss for a worst case (maximum loss) scenario. * and philosophy for minimizing the possible loss for a worst case (maximum
* When dealing with gains, it is referred to as "maximin"to maximize the minimum gain. * loss) scenario. When dealing with gains, it is referred to as "maximin"to
* Originally formulated for two-player zero-sum game theory, covering both the cases where players take * maximize the minimum gain. Originally formulated for two-player zero-sum game
* alternate moves and those where they make simultaneous moves, it has also been extended to more * theory, covering both the cases where players take alternate moves and those
* complex games and to general decision-making in the presence of uncertainty. * where they make simultaneous moves, it has also been extended to more complex
* * games and to general decision-making in the presence of uncertainty.
*
* @author [Gleison Batista](https://github.com/gleisonbs) * @author [Gleison Batista](https://github.com/gleisonbs)
* @author [David Leal](https://github.com/Panquesito7) * @author [David Leal](https://github.com/Panquesito7)
*/ */
#include <algorithm> #include <algorithm> /// for std::max, std::min
#include <cmath> #include <array> /// for std::array
#include <iostream> #include <cmath> /// for log2
#include <array> #include <iostream> /// for IO operations
/** /**
* @namespace backtracking * @namespace backtracking
* @brief Backtracking algorithms * @brief Backtracking algorithms
*/ */
namespace backtracking { namespace backtracking {
/** /**
* Check which number is the maximum/minimum in the array * @brief Check which is the maximum/minimum number in the array
* @param depth current depth in game tree * @param depth current depth in game tree
* @param node_index current index in array * @param node_index current index in array
* @param is_max if current index is the longest number * @param is_max if current index is the longest number
* @param scores saved numbers in array * @param scores saved numbers in array
* @param height maximum height for game tree * @param height maximum height for game tree
* @return maximum or minimum number * @returns the maximum or minimum number
*/ */
template <size_t T> template <size_t T>
int minimax(int depth, int node_index, bool is_max, int minimax(int depth, int node_index, bool is_max,
@ -46,16 +47,17 @@ int minimax(int depth, int node_index, bool is_max,
return is_max ? std::max(v1, v2) : std::min(v1, v2); return is_max ? std::max(v1, v2) : std::min(v1, v2);
} }
} // namespace backtracking } // namespace backtracking
/** /**
* Main function * @brief Main function
* @returns 0 on exit
*/ */
int main() { int main() {
std::array<int, 8> scores = {90, 23, 6, 33, 21, 65, 123, 34423}; std::array<int, 8> scores = {90, 23, 6, 33, 21, 65, 123, 34423};
double height = log2(scores.size()); double height = log2(scores.size());
std::cout << "Optimal value: " << backtracking::minimax(0, 0, true, scores, height) std::cout << "Optimal value: "
<< std::endl; << backtracking::minimax(0, 0, true, scores, height) << std::endl;
return 0; return 0;
} }

View File

@ -15,115 +15,114 @@
* @author [David Leal](https://github.com/Panquesito7) * @author [David Leal](https://github.com/Panquesito7)
* *
*/ */
#include <iostream>
#include <array> #include <array>
#include <iostream>
/** /**
* @namespace backtracking * @namespace backtracking
* @brief Backtracking algorithms * @brief Backtracking algorithms
*/ */
namespace backtracking { namespace backtracking {
/** /**
* @namespace n_queens * @namespace n_queens
* @brief Functions for [Eight Queens](https://en.wikipedia.org/wiki/Eight_queens_puzzle) puzzle. * @brief Functions for [Eight
*/ * Queens](https://en.wikipedia.org/wiki/Eight_queens_puzzle) puzzle.
namespace n_queens { */
/** namespace n_queens {
* Utility function to print matrix /**
* @tparam n number of matrix size * Utility function to print matrix
* @param board matrix where numbers are saved * @tparam n number of matrix size
*/ * @param board matrix where numbers are saved
template <size_t n> */
void printSolution(const std::array<std::array<int, n>, n> &board) { template <size_t n>
std::cout << "\n"; void printSolution(const std::array<std::array<int, n>, n> &board) {
for (int i = 0; i < n; i++) { std::cout << "\n";
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 << "\n"; std::cout << "\n";
}
} }
}
/** /**
* Check if a queen can be placed on matrix * Check if a queen can be placed on matrix
* @tparam n number of matrix size * @tparam n number of matrix size
* @param board matrix where numbers are saved * @param board matrix where numbers are saved
* @param row current index in rows * @param row current index in rows
* @param col current index in columns * @param col current index in columns
* @returns `true` if queen can be placed on matrix * @returns `true` if queen can be placed on matrix
* @returns `false` if queen can't be placed on matrix * @returns `false` if queen can't be placed on matrix
*/ */
template <size_t n> template <size_t n>
bool isSafe(const std::array<std::array<int, n>, n> &board, const int &row, bool isSafe(const std::array<std::array<int, n>, n> &board, const int &row,
const int &col) { const int &col) {
int i = 0, j = 0; int i = 0, j = 0;
// Check this row on left side // Check this row on left side
for (i = 0; i < col; i++) { for (i = 0; i < col; i++) {
if (board[row][i]) { if (board[row][i]) {
return false; return false;
} }
}
// Check upper diagonal on left side
for (i = row, j = col; i >= 0 && j >= 0; i--, j--) {
if (board[i][j]) {
return false;
}
}
// Check lower diagonal on left side
for (i = row, j = col; j >= 0 && i < n; i++, j--) {
if (board[i][j]) {
return false;
}
}
return true;
} }
/** // Check upper diagonal on left side
* Solve n queens problem for (i = row, j = col; i >= 0 && j >= 0; i--, j--) {
* @tparam n number of matrix size if (board[i][j]) {
* @param board matrix where numbers are saved return false;
* @param col current index in columns }
*/ }
template <size_t n> // Check lower diagonal on left side
void solveNQ(std::array<std::array<int, n>, n> board, const int &col) { for (i = row, j = col; j >= 0 && i < n; i++, j--) {
if (col >= n) { if (board[i][j]) {
return false;
}
}
return true;
}
/**
* Solve n queens problem
* @tparam n number of matrix size
* @param board matrix where numbers are saved
* @param col current index in columns
*/
template <size_t n>
void solveNQ(std::array<std::array<int, n>, n> board, const int &col) {
if (col >= n) {
printSolution<n>(board); printSolution<n>(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 // Check if queen can be placed
// on board[i][col] // on board[i][col]
if (isSafe<n>(board, i, col)) { if (isSafe<n>(board, i, col)) {
// Place this queen in matrix // Place this queen in matrix
board[i][col] = 1; board[i][col] = 1;
// Recursive to place rest of the queens // Recursive to place rest of the queens
solveNQ<n>(board, col + 1); solveNQ<n>(board, col + 1);
board[i][col] = 0; // backtrack board[i][col] = 0; // backtrack
} }
}
} }
} // namespace n_queens }
} // namespace backtracking } // namespace n_queens
} // namespace backtracking
/** /**
* Main function * @brief Main function
* @returns 0 on exit
*/ */
int main() { int main() {
const int n = 4; const int n = 4;
std::array<std::array<int, n>, n> board = { std::array<std::array<int, n>, n> board = {
std::array<int, n>({0, 0, 0, 0}), std::array<int, n>({0, 0, 0, 0}), std::array<int, n>({0, 0, 0, 0}),
std::array<int, n>({0, 0, 0, 0}), std::array<int, n>({0, 0, 0, 0}), std::array<int, n>({0, 0, 0, 0})};
std::array<int, n>({0, 0, 0, 0}),
std::array<int, n>({0, 0, 0, 0})
};
backtracking::n_queens::solveNQ<n>(board, 0); backtracking::n_queens::solveNQ<n>(board, 0);
return 0; return 0;
} }

View File

@ -111,7 +111,7 @@ int main() {
std::array<std::array<int, n>, n> board{}; std::array<std::array<int, n>, n> board{};
if (n % 2 == 0) { if (n % 2 == 0) {
for (int i = 0; i <= n / 2 - 1; i++) { // 😎 for (int i = 0; i <= n / 2 - 1; i++) {
if (backtracking::n_queens_optimized::CanIMove(board, i, 0)) { if (backtracking::n_queens_optimized::CanIMove(board, i, 0)) {
board[i][0] = 1; board[i][0] = 1;
backtracking::n_queens_optimized::NQueenSol(board, 1); backtracking::n_queens_optimized::NQueenSol(board, 1);
@ -119,7 +119,7 @@ int main() {
} }
} }
} else { } else {
for (int i = 0; i <= n / 2; i++) { // 😏 for (int i = 0; i <= n / 2; i++) {
if (backtracking::n_queens_optimized::CanIMove(board, i, 0)) { if (backtracking::n_queens_optimized::CanIMove(board, i, 0)) {
board[i][0] = 1; board[i][0] = 1;
backtracking::n_queens_optimized::NQueenSol(board, 1); backtracking::n_queens_optimized::NQueenSol(board, 1);

View File

@ -1,14 +1,14 @@
/** /**
* @file * @file
* @brief [Eight Queens](https://en.wikipedia.org/wiki/Eight_queens_puzzle) * @brief [Eight Queens](https://en.wikipedia.org/wiki/Eight_queens_puzzle)
* puzzle, printing all solutions * puzzle, printing all solutions
* *
* @author [Himani Negi](https://github.com/Himani2000) * @author [Himani Negi](https://github.com/Himani2000)
* @author [David Leal](https://github.com/Panquesito7) * @author [David Leal](https://github.com/Panquesito7)
* *
*/ */
#include <iostream> #include <array> /// for std::array
#include <array> #include <iostream> /// for IO operations
/** /**
* @namespace backtracking * @namespace backtracking
@ -17,12 +17,13 @@
namespace backtracking { namespace backtracking {
/** /**
* @namespace n_queens_all_solutions * @namespace n_queens_all_solutions
* @brief Functions for [Eight * @brief Functions for the [Eight
* Queens](https://en.wikipedia.org/wiki/Eight_queens_puzzle) puzzle with all solutions. * Queens](https://en.wikipedia.org/wiki/Eight_queens_puzzle) puzzle with all
* solutions.
*/ */
namespace n_queens_all_solutions { namespace n_queens_all_solutions {
/** /**
* Utility function to print matrix * @brief Utility function to print matrix
* @tparam n number of matrix size * @tparam n number of matrix size
* @param board matrix where numbers are saved * @param board matrix where numbers are saved
*/ */
@ -38,7 +39,7 @@ void PrintSol(const std::array<std::array<int, n>, n>& board) {
} }
/** /**
* Check if a queen can be placed on matrix * @brief Check if a queen can be placed on the matrix
* @tparam n number of matrix size * @tparam n number of matrix size
* @param board matrix where numbers are saved * @param board matrix where numbers are saved
* @param row current index in rows * @param row current index in rows
@ -47,7 +48,8 @@ void PrintSol(const std::array<std::array<int, n>, n>& board) {
* @returns `false` if queen can't be placed on matrix * @returns `false` if queen can't be placed on matrix
*/ */
template <size_t n> template <size_t n>
bool CanIMove(const std::array<std::array<int, n>, n>& board, int row, int col) { bool CanIMove(const std::array<std::array<int, n>, n>& board, 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) {
@ -70,7 +72,7 @@ bool CanIMove(const std::array<std::array<int, n>, n>& board, int row, int col)
} }
/** /**
* Solve n queens problem * @brief Main function to solve the N Queens problem
* @tparam n number of matrix size * @tparam n number of matrix size
* @param board matrix where numbers are saved * @param board matrix where numbers are saved
* @param col current index in columns * @param col current index in columns
@ -89,11 +91,12 @@ void NQueenSol(std::array<std::array<int, n>, n> board, int col) {
} }
} }
} }
} // namespace n_queens_all_solutions } // namespace n_queens_all_solutions
} // namespace backtracking } // namespace backtracking
/** /**
* Main function * @brief Main function
* @returns 0 on exit
*/ */
int main() { int main() {
const int n = 4; const int n = 4;

View File

@ -16,9 +16,9 @@
* @author [David Leal](https://github.com/Panquesito7) * @author [David Leal](https://github.com/Panquesito7)
*/ */
#include <array> #include <array> /// for std::array
#include <iostream> #include <cassert> /// for assert
#include <cassert> #include <iostream> /// for IO operations
/** /**
* @namespace backtracking * @namespace backtracking
@ -39,12 +39,14 @@ namespace rat_maze {
* @param currposcol current position in columns * @param currposcol current position in columns
* @param maze matrix where numbers are saved * @param maze matrix where numbers are saved
* @param soln matrix to problem solution * @param soln matrix to problem solution
* @returns 0 on end * @returns `true` if there exists a solution to move one step ahead in a column
* or in a row
* @returns `false` for the backtracking part
*/ */
template <size_t size> template <size_t size>
bool solveMaze(int currposrow, int currposcol, bool solveMaze(int currposrow, int currposcol,
const std::array<std::array<int, size>, size> &maze, const std::array<std::array<int, size>, size> &maze,
std::array<std::array<int, size>, size> soln) { std::array<std::array<int, size>, size> soln) {
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) {
@ -78,10 +80,10 @@ bool solveMaze(int currposrow, int currposcol,
} // namespace backtracking } // namespace backtracking
/** /**
* @brief Test implementations * @brief Self-test implementations
* @returns void * @returns void
*/ */
static void test(){ static void test() {
const int size = 4; const int size = 4;
std::array<std::array<int, size>, size> maze = { std::array<std::array<int, size>, size> maze = {
std::array<int, size>{1, 0, 1, 0}, std::array<int, size>{1, 0, 1, 1}, std::array<int, size>{1, 0, 1, 0}, std::array<int, size>{1, 0, 1, 1},
@ -96,8 +98,8 @@ static void test(){
} }
} }
int currposrow = 0; // Current position in rows int currposrow = 0; // Current position in the rows
int currposcol = 0; // Current position in columns int currposcol = 0; // Current position in the columns
assert(backtracking::rat_maze::solveMaze<size>(currposrow, currposcol, maze, assert(backtracking::rat_maze::solveMaze<size>(currposrow, currposcol, maze,
soln) == 1); soln) == 1);
@ -108,6 +110,6 @@ static void test(){
* @returns 0 on exit * @returns 0 on exit
*/ */
int main() { int main() {
test(); // run the tests test(); // run self-test implementations
return 0; return 0;
} }

View File

@ -3,155 +3,171 @@
* @brief [Sudoku Solver](https://en.wikipedia.org/wiki/Sudoku) algorithm. * @brief [Sudoku Solver](https://en.wikipedia.org/wiki/Sudoku) algorithm.
* *
* @details * @details
* Sudoku (, sūdoku, digit-single) (/suːˈdoʊkuː/, /-ˈdɒk-/, /-/, originally called * Sudoku (, sūdoku, digit-single) (/suːˈdoʊkuː/, /-ˈdɒk-/, /-/,
* Number Place) is a logic-based, combinatorial number-placement puzzle. * originally called Number Place) is a logic-based, combinatorial
* In classic sudoku, the objective is to fill a 9×9 grid with digits so that each column, * number-placement puzzle. In classic sudoku, the objective is to fill a 9×9
* each row, and each of the nine 3×3 subgrids that compose the grid (also called "boxes", "blocks", or "regions") * grid with digits so that each column, each row, and each of the nine 3×3
* subgrids that compose the grid (also called "boxes", "blocks", or "regions")
* contain all of the digits from 1 to 9. The puzzle setter provides a * contain all of the digits from 1 to 9. The puzzle setter provides a
* partially completed grid, which for a well-posed puzzle has a single solution. * partially completed grid, which for a well-posed puzzle has a single
* solution.
* *
* @author [DarthCoder3200](https://github.com/DarthCoder3200) * @author [DarthCoder3200](https://github.com/DarthCoder3200)
* @author [David Leal](https://github.com/Panquesito7) * @author [David Leal](https://github.com/Panquesito7)
*/ */
#include <iostream> #include <array> /// for assert
#include <array> #include <iostream> /// for IO operations
/** /**
* @namespace backtracking * @namespace backtracking
* @brief Backtracking algorithms * @brief Backtracking algorithms
*/ */
namespace backtracking { namespace backtracking {
/** /**
* Checks if it's possible to place a number 'no' * @namespace sudoku_solver
* @tparam V number of vertices in the array * @brief Functions for the [Sudoku
* @param mat matrix where numbers are saved * Solver](https://en.wikipedia.org/wiki/Sudoku) implementation
* @param i current index in rows */
* @param j current index in columns namespace sudoku_solver {
* @param no number to be added in matrix /**
* @param n number of times loop will run * @brief Check if it's possible to place a number (`no` parameter)
* @returns `true` if 'mat' is different from 'no' * @tparam V number of vertices in the array
* @returns `false` if 'mat' equals to 'no' * @param mat matrix where numbers are saved
*/ * @param i current index in rows
template <size_t V> * @param j current index in columns
bool isPossible(const std::array <std::array <int, V>, V> &mat, int i, int j, int no, int n) { * @param no number to be added in matrix
/// 'no' shouldn't be present in either row i or column j * @param n number of times loop will run
for (int x = 0; x < n; x++) { * @returns `true` if 'mat' is different from 'no'
if (mat[x][j] == no || mat[i][x] == no) { * @returns `false` if 'mat' equals to 'no'
*/
template <size_t V>
bool isPossible(const std::array<std::array<int, V>, V> &mat, int i, int j,
int no, int n) {
/// `no` shouldn't be present in either row i or column j
for (int x = 0; x < n; x++) {
if (mat[x][j] == no || mat[i][x] == no) {
return false;
}
}
/// `no` shouldn't be present in the 3*3 subgrid
int sx = (i / 3) * 3;
int sy = (j / 3) * 3;
for (int x = sx; x < sx + 3; x++) {
for (int y = sy; y < sy + 3; y++) {
if (mat[x][y] == no) {
return false; return false;
} }
} }
}
/// 'no' shouldn't be present in the 3*3 subgrid return true;
int sx = (i / 3) * 3; }
int sy = (j / 3) * 3; /**
* @brief Utility function to print the matrix
for (int x = sx; x < sx + 3; x++) { * @tparam V number of vertices in array
for (int y = sy; y < sy + 3; y++) { * @param mat matrix where numbers are saved
if (mat[x][y] == no) { * @param starting_mat copy of mat, required by printMat for highlighting the
return false; * differences
} * @param n number of times loop will run
* @return void
*/
template <size_t V>
void printMat(const std::array<std::array<int, V>, V> &mat,
const std::array<std::array<int, V>, V> &starting_mat, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (starting_mat[i][j] != mat[i][j]) {
std::cout << "\033[93m" << mat[i][j] << "\033[0m"
<< " ";
} else {
std::cout << mat[i][j] << " ";
}
if ((j + 1) % 3 == 0) {
std::cout << '\t';
} }
} }
if ((i + 1) % 3 == 0) {
return true;
}
/**
* Utility function to print matrix
* @tparam V number of vertices in array
* @param mat matrix where numbers are saved
* @param starting_mat copy of mat, required by printMat for highlighting the differences
* @param n number of times loop will run
* @return void
*/
template <size_t V>
void printMat(const std::array <std::array <int, V>, V> &mat, const std::array <std::array <int, V>, V> &starting_mat, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (starting_mat[i][j] != mat[i][j]) {
std::cout << "\033[93m" << mat[i][j] << "\033[0m" << " ";
} else {
std::cout << mat[i][j] << " ";
}
if ((j + 1) % 3 == 0) {
std::cout << '\t';
}
}
if ((i + 1) % 3 == 0) {
std::cout << std::endl;
}
std::cout << std::endl; std::cout << std::endl;
} }
std::cout << std::endl;
} }
}
/**
* Sudoku algorithm
* @tparam V number of vertices in array
* @param mat matrix where numbers are saved
* @param starting_mat copy of mat, required by printMat for highlighting the differences
* @param i current index in rows
* @param j current index in columns
* @returns `true` if 'no' was placed
* @returns `false` if 'no' was not placed
*/
template <size_t V>
bool solveSudoku(std::array <std::array <int, V>, V> &mat, const std::array <std::array <int, V>, V> &starting_mat, int i, int j) {
/// Base Case
if (i == 9) {
/// Solved for 9 rows already
backtracking::printMat<V>(mat, starting_mat, 9);
return true;
}
/// Crossed the last Cell in the row
if (j == 9) {
return backtracking::solveSudoku<V>(mat, starting_mat, i + 1, 0);
}
/// Blue Cell - Skip
if (mat[i][j] != 0) {
return backtracking::solveSudoku<V>(mat, starting_mat, i, j + 1);
}
/// White Cell
/// Try to place every possible no
for (int no = 1; no <= 9; no++) {
if (backtracking::isPossible<V>(mat, i, j, no, 9)) {
/// Place the 'no' - assuming a solution will exist
mat[i][j] = no;
bool solution_found = backtracking::solveSudoku<V>(mat, starting_mat, i, j + 1);
if (solution_found) {
return true;
}
/// Couldn't find a solution
/// loop will place the next no.
}
}
/// Solution couldn't be found for any of the numbers provided
mat[i][j] = 0;
return false;
}
} // namespace backtracking
/** /**
* Main function * @brief Main function to implement the Sudoku algorithm
* @tparam V number of vertices in array
* @param mat matrix where numbers are saved
* @param starting_mat copy of mat, required by printMat for highlighting the
* differences
* @param i current index in rows
* @param j current index in columns
* @returns `true` if 'no' was placed
* @returns `false` if 'no' was not placed
*/
template <size_t V>
bool solveSudoku(std::array<std::array<int, V>, V> &mat,
const std::array<std::array<int, V>, V> &starting_mat, int i,
int j) {
/// Base Case
if (i == 9) {
/// Solved for 9 rows already
printMat<V>(mat, starting_mat, 9);
return true;
}
/// Crossed the last Cell in the row
if (j == 9) {
return solveSudoku<V>(mat, starting_mat, i + 1, 0);
}
/// Blue Cell - Skip
if (mat[i][j] != 0) {
return solveSudoku<V>(mat, starting_mat, i, j + 1);
}
/// White Cell
/// Try to place every possible no
for (int no = 1; no <= 9; no++) {
if (isPossible<V>(mat, i, j, no, 9)) {
/// Place the 'no' - assuming a solution will exist
mat[i][j] = no;
bool solution_found = solveSudoku<V>(mat, starting_mat, i, j + 1);
if (solution_found) {
return true;
}
/// Couldn't find a solution
/// loop will place the next `no`.
}
}
/// Solution couldn't be found for any of the numbers provided
mat[i][j] = 0;
return false;
}
} // namespace sudoku_solver
} // namespace backtracking
/**
* @brief Main function
* @returns 0 on exit
*/ */
int main() { int main() {
const int V = 9; const int V = 9;
std::array <std::array <int, V>, V> mat = { std::array<std::array<int, V>, V> mat = {
std::array <int, V> {5, 3, 0, 0, 7, 0, 0, 0, 0}, std::array<int, V>{5, 3, 0, 0, 7, 0, 0, 0, 0},
std::array <int, V> {6, 0, 0, 1, 9, 5, 0, 0, 0}, std::array<int, V>{6, 0, 0, 1, 9, 5, 0, 0, 0},
std::array <int, V> {0, 9, 8, 0, 0, 0, 0, 6, 0}, std::array<int, V>{0, 9, 8, 0, 0, 0, 0, 6, 0},
std::array <int, V> {8, 0, 0, 0, 6, 0, 0, 0, 3}, std::array<int, V>{8, 0, 0, 0, 6, 0, 0, 0, 3},
std::array <int, V> {4, 0, 0, 8, 0, 3, 0, 0, 1}, std::array<int, V>{4, 0, 0, 8, 0, 3, 0, 0, 1},
std::array <int, V> {7, 0, 0, 0, 2, 0, 0, 0, 6}, std::array<int, V>{7, 0, 0, 0, 2, 0, 0, 0, 6},
std::array <int, V> {0, 6, 0, 0, 0, 0, 2, 8, 0}, std::array<int, V>{0, 6, 0, 0, 0, 0, 2, 8, 0},
std::array <int, V> {0, 0, 0, 4, 1, 9, 0, 0, 5}, std::array<int, V>{0, 0, 0, 4, 1, 9, 0, 0, 5},
std::array <int, V> {0, 0, 0, 0, 8, 0, 0, 7, 9} std::array<int, V>{0, 0, 0, 0, 8, 0, 0, 7, 9}};
};
backtracking::printMat<V>(mat, mat, 9); backtracking::sudoku_solver::printMat<V>(mat, mat, 9);
std::cout << "Solution " << std::endl; std::cout << "Solution " << std::endl;
std::array <std::array <int, V>, V> starting_mat = mat; std::array<std::array<int, V>, V> starting_mat = mat;
backtracking::solveSudoku<V>(mat, starting_mat, 0, 0); backtracking::sudoku_solver::solveSudoku<V>(mat, starting_mat, 0, 0);
return 0; return 0;
} }

View File

@ -5,7 +5,8 @@
* integer. * integer.
* *
* @details * @details
* We are given an integer number. We need to calculate the number of set bits in it. * We are given an integer number. We need to calculate the number of set bits
* in it.
* *
* A binary number consists of two digits. They are 0 & 1. Digit 1 is known as * A binary number consists of two digits. They are 0 & 1. Digit 1 is known as
* set bit in computer terms. * set bit in computer terms.
@ -15,7 +16,7 @@
* @author [Prashant Thakur](https://github.com/prashant-th18) * @author [Prashant Thakur](https://github.com/prashant-th18)
*/ */
#include <cassert> /// for assert #include <cassert> /// for assert
#include <iostream> /// for IO operations #include <iostream> /// for IO operations
/** /**
* @namespace bit_manipulation * @namespace bit_manipulation
* @brief Bit manipulation algorithms * @brief Bit manipulation algorithms
@ -33,21 +34,21 @@ namespace count_of_set_bits {
* @param n is the number whose set bit will be counted * @param n is the number whose set bit will be counted
* @returns total number of set-bits in the binary representation of number `n` * @returns total number of set-bits in the binary representation of number `n`
*/ */
std::uint64_t countSetBits(std :: int64_t n) { // int64_t is preferred over int so that std::uint64_t countSetBits(
// no Overflow can be there. std ::int64_t n) { // int64_t is preferred over int so that
// no Overflow can be there.
int count = 0; // "count" variable is used to count number of set-bits('1') in int count = 0; // "count" variable is used to count number of set-bits('1')
// binary representation of number 'n' // in binary representation of number 'n'
while (n != 0) while (n != 0) {
{
++count; ++count;
n = (n & (n - 1)); n = (n & (n - 1));
} }
return count; return count;
// Why this algorithm is better than the standard one? // Why this algorithm is better than the standard one?
// Because this algorithm runs the same number of times as the number of // Because this algorithm runs the same number of times as the number of
// set-bits in it. Means if my number is having "3" set bits, then this while loop // set-bits in it. Means if my number is having "3" set bits, then this
// will run only "3" times!! // while loop will run only "3" times!!
} }
} // namespace count_of_set_bits } // namespace count_of_set_bits
} // namespace bit_manipulation } // namespace bit_manipulation

View File

@ -22,7 +22,8 @@
*/ */
namespace ciphers { namespace ciphers {
/** \namespace atbash /** \namespace atbash
* \brief Functions for the [Atbash Cipher](https://en.wikipedia.org/wiki/Atbash) implementation * \brief Functions for the [Atbash
* Cipher](https://en.wikipedia.org/wiki/Atbash) implementation
*/ */
namespace atbash { namespace atbash {
std::map<char, char> atbash_cipher_map = { std::map<char, char> atbash_cipher_map = {
@ -43,7 +44,7 @@ std::map<char, char> atbash_cipher_map = {
* @param text Plaintext to be encrypted * @param text Plaintext to be encrypted
* @returns encoded or decoded string * @returns encoded or decoded string
*/ */
std::string atbash_cipher(std::string text) { std::string atbash_cipher(const std::string& text) {
std::string result; std::string result;
for (char letter : text) { for (char letter : text) {
result += atbash_cipher_map[letter]; result += atbash_cipher_map[letter];

View File

@ -184,7 +184,7 @@ static void test1() {
* @returns void * @returns void
*/ */
static void test2() { static void test2() {
// the minimum, maximum, and size of the set // the minimum, maximum, and size of the set
uint64_t n = 10; ///< number of items uint64_t n = 10; ///< number of items
dsu d(n + 1); ///< object of class disjoint sets dsu d(n + 1); ///< object of class disjoint sets
// set 1 // set 1

View File

@ -3,13 +3,14 @@
* @details * @details
* Using 2 Queues inside the Stack class, we can easily implement Stack * Using 2 Queues inside the Stack class, we can easily implement Stack
* data structure with heavy computation in push function. * data structure with heavy computation in push function.
* *
* References used: [StudyTonight](https://www.studytonight.com/data-structures/stack-using-queue) * References used:
* [StudyTonight](https://www.studytonight.com/data-structures/stack-using-queue)
* @author [tushar2407](https://github.com/tushar2407) * @author [tushar2407](https://github.com/tushar2407)
*/ */
#include <iostream> /// for IO operations #include <cassert> /// for assert
#include <queue> /// for queue data structure #include <iostream> /// for IO operations
#include <cassert> /// for assert #include <queue> /// for queue data structure
/** /**
* @namespace data_strcutres * @namespace data_strcutres
@ -18,66 +19,59 @@
namespace data_structures { namespace data_structures {
/** /**
* @namespace stack_using_queue * @namespace stack_using_queue
* @brief Functions for the [Stack Using Queue](https://www.studytonight.com/data-structures/stack-using-queue) implementation * @brief Functions for the [Stack Using
* Queue](https://www.studytonight.com/data-structures/stack-using-queue)
* implementation
*/ */
namespace stack_using_queue { namespace stack_using_queue {
/**
* @brief Stack Class implementation for basic methods of Stack Data Structure.
*/
struct Stack {
std::queue<int64_t> main_q; ///< stores the current state of the stack
std::queue<int64_t> auxiliary_q; ///< used to carry out intermediate
///< operations to implement stack
uint32_t current_size = 0; ///< stores the current size of the stack
/** /**
* @brief Stack Class implementation for basic methods of Stack Data Structure. * Returns the top most element of the stack
* @returns top element of the queue
*/ */
struct Stack int top() { return main_q.front(); }
{
std::queue<int64_t> main_q; ///< stores the current state of the stack
std::queue<int64_t> auxiliary_q; ///< used to carry out intermediate operations to implement stack
uint32_t current_size = 0; ///< stores the current size of the stack
/**
* Returns the top most element of the stack
* @returns top element of the queue
*/
int top()
{
return main_q.front();
}
/** /**
* @brief Inserts an element to the top of the stack. * @brief Inserts an element to the top of the stack.
* @param val the element that will be inserted into the stack * @param val the element that will be inserted into the stack
* @returns void * @returns void
*/ */
void push(int val) void push(int val) {
{ auxiliary_q.push(val);
auxiliary_q.push(val); while (!main_q.empty()) {
while(!main_q.empty()) auxiliary_q.push(main_q.front());
{
auxiliary_q.push(main_q.front());
main_q.pop();
}
swap(main_q, auxiliary_q);
current_size++;
}
/**
* @brief Removes the topmost element from the stack
* @returns void
*/
void pop()
{
if(main_q.empty()) {
return;
}
main_q.pop(); main_q.pop();
current_size--;
} }
swap(main_q, auxiliary_q);
current_size++;
}
/** /**
* @brief Utility function to return the current size of the stack * @brief Removes the topmost element from the stack
* @returns current size of stack * @returns void
*/ */
int size() void pop() {
{ if (main_q.empty()) {
return current_size; return;
} }
}; main_q.pop();
current_size--;
}
/**
* @brief Utility function to return the current size of the stack
* @returns current size of stack
*/
int size() { return current_size; }
};
} // namespace stack_using_queue } // namespace stack_using_queue
} // namespace data_structures } // namespace data_structures
@ -85,30 +79,29 @@ namespace stack_using_queue {
* @brief Self-test implementations * @brief Self-test implementations
* @returns void * @returns void
*/ */
static void test() static void test() {
{
data_structures::stack_using_queue::Stack s; data_structures::stack_using_queue::Stack s;
s.push(1); /// insert an element into the stack s.push(1); /// insert an element into the stack
s.push(2); /// insert an element into the stack s.push(2); /// insert an element into the stack
s.push(3); /// insert an element into the stack s.push(3); /// insert an element into the stack
assert(s.size()==3); /// size should be 3 assert(s.size() == 3); /// size should be 3
assert(s.top()==3); /// topmost element in the stack should be 3 assert(s.top() == 3); /// topmost element in the stack should be 3
s.pop(); /// remove the topmost element from the stack s.pop(); /// remove the topmost element from the stack
assert(s.top()==2); /// topmost element in the stack should now be 2 assert(s.top() == 2); /// topmost element in the stack should now be 2
s.pop(); /// remove the topmost element from the stack s.pop(); /// remove the topmost element from the stack
assert(s.top()==1); assert(s.top() == 1);
s.push(5); /// insert an element into the stack s.push(5); /// insert an element into the stack
assert(s.top()==5); /// topmost element in the stack should now be 5 assert(s.top() == 5); /// topmost element in the stack should now be 5
s.pop(); /// remove the topmost element from the stack s.pop(); /// remove the topmost element from the stack
assert(s.top()==1); /// topmost element in the stack should now be 1 assert(s.top() == 1); /// topmost element in the stack should now be 1
assert(s.size()==1); /// size should be 1 assert(s.size() == 1); /// size should be 1
} }
/** /**
@ -119,8 +112,7 @@ static void test()
* declared above. * declared above.
* @returns 0 on exit * @returns 0 on exit
*/ */
int main() int main() {
{
test(); // run self-test implementations test(); // run self-test implementations
return 0; return 0;
} }

View File

@ -0,0 +1,134 @@
/**
* @brief Check whether a given graph is bipartite or not
* @details
* A bipartite graph is the one whose nodes can be divided into two
* disjoint sets in such a way that the nodes in a set are not
* connected to each other at all, i.e. no intra-set connections.
* The only connections that exist are that of inter-set,
* i.e. the nodes from one set are connected to a subset of nodes
* in the other set.
* In this implementation, using a graph in the form of adjacency
* list, check whether the given graph is a bipartite or not.
*
* References used: [GeeksForGeeks](https://www.geeksforgeeks.org/bipartite-graph/)
* @author [tushar2407](https://github.com/tushar2407)
*/
#include <iostream> /// for IO operations
#include <queue> /// for queue data structure
#include <vector> /// for vector data structure
#include <cassert> /// for assert
/**
* @namespace graph
* @brief Graphical algorithms
*/
namespace graph {
/**
* @brief function to check whether the passed graph is bipartite or not
* @param graph is a 2D matrix whose rows or the first index signify the node
* and values in that row signify the nodes it is connected to
* @param index is the valus of the node currently under observation
* @param visited is the vector which stores whether a given node has been
* traversed or not yet
* @returns boolean
*/
bool checkBipartite(
const std::vector<std::vector<int64_t>> &graph,
int64_t index,
std::vector<int64_t> *visited
)
{
std::queue<int64_t> q; ///< stores the neighbouring node indexes in squence
/// of being reached
q.push(index); /// insert the current node into the queue
(*visited)[index] = 1; /// mark the current node as travelled
while(q.size())
{
int64_t u = q.front();
q.pop();
for(uint64_t i=0;i<graph[u].size();i++)
{
int64_t v = graph[u][i]; ///< stores the neighbour of the current node
if(!(*visited)[v]) /// check whether the neighbour node is
/// travelled already or not
{
(*visited)[v] = ((*visited)[u]==1)?-1:1; /// colour the neighbouring node with
/// different colour than the current node
q.push(v); /// insert the neighbouring node into the queue
}
else if((*visited)[v] == (*visited)[u]) /// if both the current node and its neighbour
/// has the same state then it is not a bipartite graph
{
return false;
}
}
}
return true; /// return true when all the connected nodes of the current
/// nodes are travelled and satisify all the above conditions
}
/**
* @brief returns true if the given graph is bipartite else returns false
* @param graph is a 2D matrix whose rows or the first index signify the node
* and values in that row signify the nodes it is connected to
* @returns booleans
*/
bool isBipartite(const std::vector<std::vector<int64_t>> &graph)
{
std::vector<int64_t> visited(graph.size()); ///< stores boolean values
/// which signify whether that node had been visited or not
for(uint64_t i=0;i<graph.size();i++)
{
if(!visited[i]) /// if the current node is not visited then check
/// whether the sub-graph of that node is a bipartite or not
{
if(!checkBipartite(graph, i, &visited))
{
return false;
}
}
}
return true;
}
} // namespace graph
/**
* @brief Self-test implementations
* @returns void
*/
static void test()
{
std::vector<std::vector<int64_t>> graph = {
{1,3},
{0,2},
{1,3},
{0,2}
};
assert(graph::isBipartite(graph) == true); /// check whether the above
/// defined graph is indeed bipartite
std::vector<std::vector<int64_t>> graph_not_bipartite = {
{1,2,3},
{0,2},
{0,1,3},
{0,2}
};
assert(graph::isBipartite(graph_not_bipartite) == false); /// check whether
/// the above defined graph is indeed bipartite
std::cout << "All tests have successfully passed!\n";
}
/**
* @brief Main function
* Instantitates a dummy graph of a small size with
* a few edges between random nodes.
* On applying the algorithm, it checks if the instantiated
* graph is bipartite or not.
* @returns 0 on exit
*/
int main()
{
test(); // run self-test implementations
return 0;
}

View File

@ -1,17 +1,19 @@
/** /**
* @file * @file
* @brief Implementations for the [area](https://en.wikipedia.org/wiki/Area) of various shapes * @brief Implementations for the [area](https://en.wikipedia.org/wiki/Area) of
* @details The area of a shape is the amount of 2D space it takes up. * various shapes
* All shapes have a formula to get the area of any given shape. * @details The area of a shape is the amount of 2D space it takes up.
* All shapes have a formula to get the area of any given shape.
* These implementations support multiple return types. * These implementations support multiple return types.
* *
* @author [Focusucof](https://github.com/Focusucof) * @author [Focusucof](https://github.com/Focusucof)
*/ */
#define _USE_MATH_DEFINES #define _USE_MATH_DEFINES
#include <cmath> /// for M_PI definition and pow()
#include <cstdint> /// for uint16_t datatype
#include <iostream> /// for IO operations
#include <cassert> /// for assert #include <cassert> /// for assert
#include <cmath> /// for M_PI definition and pow()
#include <cmath>
#include <cstdint> /// for uint16_t datatype
#include <iostream> /// for IO operations
/** /**
* @namespace math * @namespace math
@ -115,25 +117,25 @@ T cylinder_surface_area(T radius, T height) {
*/ */
static void test() { static void test() {
// I/O variables for testing // I/O variables for testing
uint16_t int_length; // 16 bit integer length input uint16_t int_length = 0; // 16 bit integer length input
uint16_t int_width; // 16 bit integer width input uint16_t int_width = 0; // 16 bit integer width input
uint16_t int_base; // 16 bit integer base input uint16_t int_base = 0; // 16 bit integer base input
uint16_t int_height; // 16 bit integer height input uint16_t int_height = 0; // 16 bit integer height input
uint16_t int_expected; // 16 bit integer expected output uint16_t int_expected = 0; // 16 bit integer expected output
uint16_t int_area; // 16 bit integer output uint16_t int_area = 0; // 16 bit integer output
float float_length; // float length input float float_length = NAN; // float length input
float float_expected; // float expected output float float_expected = NAN; // float expected output
float float_area; // float output float float_area = NAN; // float output
double double_length; // double length input double double_length = NAN; // double length input
double double_width; // double width input double double_width = NAN; // double width input
double double_radius; // double radius input double double_radius = NAN; // double radius input
double double_height; // double height input double double_height = NAN; // double height input
double double_expected; // double expected output double double_expected = NAN; // double expected output
double double_area; // double output double double_area = NAN; // double output
// 1st test // 1st test
int_length = 5; int_length = 5;
int_expected = 25; int_expected = 25;
int_area = math::square_area(int_length); int_area = math::square_area(int_length);
@ -201,7 +203,9 @@ static void test() {
// 6th test // 6th test
double_radius = 6; double_radius = 6;
double_expected = 113.09733552923255; // rounded down because the double datatype truncates after 14 decimal places double_expected =
113.09733552923255; // rounded down because the double datatype
// truncates after 14 decimal places
double_area = math::circle_area(double_radius); double_area = math::circle_area(double_radius);
std::cout << "AREA OF A CIRCLE" << std::endl; std::cout << "AREA OF A CIRCLE" << std::endl;
@ -239,7 +243,8 @@ static void test() {
// 9th test // 9th test
double_radius = 10.0; double_radius = 10.0;
double_expected = 1256.6370614359172; // rounded down because the whole value gets truncated double_expected = 1256.6370614359172; // rounded down because the whole
// value gets truncated
double_area = math::sphere_surface_area(double_radius); double_area = math::sphere_surface_area(double_radius);
std::cout << "SURFACE AREA OF A SPHERE" << std::endl; std::cout << "SURFACE AREA OF A SPHERE" << std::endl;

View File

@ -1,29 +1,34 @@
/** /**
* @file * @file
* @brief [Monte Carlo Integration](https://en.wikipedia.org/wiki/Monte_Carlo_integration) * @brief [Monte Carlo
* Integration](https://en.wikipedia.org/wiki/Monte_Carlo_integration)
* *
* @details * @details
* In mathematics, Monte Carlo integration is a technique for numerical integration using random numbers. * In mathematics, Monte Carlo integration is a technique for numerical
* It is a particular Monte Carlo method that numerically computes a definite integral. * integration using random numbers. It is a particular Monte Carlo method that
* While other algorithms usually evaluate the integrand at a regular grid, Monte Carlo randomly chooses points at which the integrand is evaluated. * numerically computes a definite integral. While other algorithms usually
* This method is particularly useful for higher-dimensional integrals. * evaluate the integrand at a regular grid, Monte Carlo randomly chooses points
* at which the integrand is evaluated. This method is particularly useful for
* higher-dimensional integrals.
* *
* This implementation supports arbitrary pdfs. * This implementation supports arbitrary pdfs.
* These pdfs are sampled using the [Metropolis-Hastings algorithm](https://en.wikipedia.org/wiki/MetropolisHastings_algorithm). * These pdfs are sampled using the [Metropolis-Hastings
* This can be swapped out by every other sampling techniques for example the inverse method. * algorithm](https://en.wikipedia.org/wiki/MetropolisHastings_algorithm). This
* Metropolis-Hastings was chosen because it is the most general and can also be extended for a higher dimensional sampling space. * can be swapped out by every other sampling techniques for example the inverse
* method. Metropolis-Hastings was chosen because it is the most general and can
* also be extended for a higher dimensional sampling space.
* *
* @author [Domenic Zingsheim](https://github.com/DerAndereDomenic) * @author [Domenic Zingsheim](https://github.com/DerAndereDomenic)
*/ */
#define _USE_MATH_DEFINES /// for M_PI on windows #define _USE_MATH_DEFINES /// for M_PI on windows
#include <cmath> /// for math functions #include <cmath> /// for math functions
#include <cstdint> /// for fixed size data types #include <cstdint> /// for fixed size data types
#include <ctime> /// for time to initialize rng #include <ctime> /// for time to initialize rng
#include <functional> /// for function pointers #include <functional> /// for function pointers
#include <iostream> /// for std::cout #include <iostream> /// for std::cout
#include <random> /// for random number generation #include <random> /// for random number generation
#include <vector> /// for std::vector #include <vector> /// for std::vector
/** /**
* @namespace math * @namespace math
@ -32,25 +37,34 @@
namespace math { namespace math {
/** /**
* @namespace monte_carlo * @namespace monte_carlo
* @brief Functions for the [Monte Carlo Integration](https://en.wikipedia.org/wiki/Monte_Carlo_integration) implementation * @brief Functions for the [Monte Carlo
* Integration](https://en.wikipedia.org/wiki/Monte_Carlo_integration)
* implementation
*/ */
namespace monte_carlo { namespace monte_carlo {
using Function = std::function<double(double&)>; /// short-hand for std::functions used in this implementation using Function = std::function<double(
double&)>; /// short-hand for std::functions used in this implementation
/** /**
* @brief Generate samples according to some pdf * @brief Generate samples according to some pdf
* @details This function uses Metropolis-Hastings to generate random numbers. It generates a sequence of random numbers by using a markov chain. * @details This function uses Metropolis-Hastings to generate random numbers.
* Therefore, we need to define a start_point and the number of samples we want to generate. * It generates a sequence of random numbers by using a markov chain. Therefore,
* Because the first samples generated by the markov chain may not be distributed according to the given pdf, one can specify how many samples * we need to define a start_point and the number of samples we want to
* generate. Because the first samples generated by the markov chain may not be
* distributed according to the given pdf, one can specify how many samples
* should be discarded before storing samples. * should be discarded before storing samples.
* @param start_point The starting point of the markov chain * @param start_point The starting point of the markov chain
* @param pdf The pdf to sample * @param pdf The pdf to sample
* @param num_samples The number of samples to generate * @param num_samples The number of samples to generate
* @param discard How many samples should be discarded at the start * @param discard How many samples should be discarded at the start
* @returns A vector of size num_samples with samples distributed according to the pdf * @returns A vector of size num_samples with samples distributed according to
* the pdf
*/ */
std::vector<double> generate_samples(const double& start_point, const Function& pdf, const uint32_t& num_samples, const uint32_t& discard = 100000) { std::vector<double> generate_samples(const double& start_point,
const Function& pdf,
const uint32_t& num_samples,
const uint32_t& discard = 100000) {
std::vector<double> samples; std::vector<double> samples;
samples.reserve(num_samples); samples.reserve(num_samples);
@ -61,19 +75,19 @@ std::vector<double> generate_samples(const double& start_point, const Function&
std::normal_distribution<double> normal(0.0, 1.0); std::normal_distribution<double> normal(0.0, 1.0);
generator.seed(time(nullptr)); generator.seed(time(nullptr));
for(uint32_t t = 0; t < num_samples + discard; ++t) { for (uint32_t t = 0; t < num_samples + discard; ++t) {
// Generate a new proposal according to some mutation strategy. // Generate a new proposal according to some mutation strategy.
// This is arbitrary and can be swapped. // This is arbitrary and can be swapped.
double x_dash = normal(generator) + x_t; double x_dash = normal(generator) + x_t;
double acceptance_probability = std::min(pdf(x_dash)/pdf(x_t), 1.0); double acceptance_probability = std::min(pdf(x_dash) / pdf(x_t), 1.0);
double u = uniform(generator); double u = uniform(generator);
// Accept "new state" according to the acceptance_probability // Accept "new state" according to the acceptance_probability
if(u <= acceptance_probability) { if (u <= acceptance_probability) {
x_t = x_dash; x_t = x_dash;
} }
if(t >= discard) { if (t >= discard) {
samples.push_back(x_t); samples.push_back(x_t);
} }
} }
@ -92,13 +106,17 @@ std::vector<double> generate_samples(const double& start_point, const Function&
* @param function The function to integrate * @param function The function to integrate
* @param pdf The pdf to sample * @param pdf The pdf to sample
* @param num_samples The number of samples used to approximate the integral * @param num_samples The number of samples used to approximate the integral
* @returns The approximation of the integral according to 1/N \sum_{i}^N f(x_i) / p(x_i) * @returns The approximation of the integral according to 1/N \sum_{i}^N f(x_i)
* / p(x_i)
*/ */
double integral_monte_carlo(const double& start_point, const Function& function, const Function& pdf, const uint32_t& num_samples = 1000000) { double integral_monte_carlo(const double& start_point, const Function& function,
const Function& pdf,
const uint32_t& num_samples = 1000000) {
double integral = 0.0; double integral = 0.0;
std::vector<double> samples = generate_samples(start_point, pdf, num_samples); std::vector<double> samples =
generate_samples(start_point, pdf, num_samples);
for(double sample : samples) { for (double sample : samples) {
integral += function(sample) / pdf(sample); integral += function(sample) / pdf(sample);
} }
@ -113,8 +131,13 @@ double integral_monte_carlo(const double& start_point, const Function& function,
* @returns void * @returns void
*/ */
static void test() { static void test() {
std::cout << "Disclaimer: Because this is a randomized algorithm," << std::endl; std::cout << "Disclaimer: Because this is a randomized algorithm,"
std::cout << "it may happen that singular samples deviate from the true result." << std::endl << std::endl;; << std::endl;
std::cout
<< "it may happen that singular samples deviate from the true result."
<< std::endl
<< std::endl;
;
math::monte_carlo::Function f; math::monte_carlo::Function f;
math::monte_carlo::Function pdf; math::monte_carlo::Function pdf;
@ -122,60 +145,58 @@ static void test() {
double lower_bound = 0, upper_bound = 0; double lower_bound = 0, upper_bound = 0;
/* \int_{-2}^{2} -x^2 + 4 dx */ /* \int_{-2}^{2} -x^2 + 4 dx */
f = [&](double& x) { f = [&](double& x) { return -x * x + 4.0; };
return -x*x + 4.0;
};
lower_bound = -2.0; lower_bound = -2.0;
upper_bound = 2.0; upper_bound = 2.0;
pdf = [&](double& x) { pdf = [&](double& x) {
if(x >= lower_bound && x <= -1.0) { if (x >= lower_bound && x <= -1.0) {
return 0.1; return 0.1;
} }
if(x <= upper_bound && x >= 1.0) { if (x <= upper_bound && x >= 1.0) {
return 0.1; return 0.1;
} }
if(x > -1.0 && x < 1.0) { if (x > -1.0 && x < 1.0) {
return 0.4; return 0.4;
} }
return 0.0; return 0.0;
}; };
integral = math::monte_carlo::integral_monte_carlo((upper_bound - lower_bound) / 2.0, f, pdf); integral = math::monte_carlo::integral_monte_carlo(
(upper_bound - lower_bound) / 2.0, f, pdf);
std::cout << "This number should be close to 10.666666: " << integral << std::endl; std::cout << "This number should be close to 10.666666: " << integral
<< std::endl;
/* \int_{0}^{1} e^x dx */ /* \int_{0}^{1} e^x dx */
f = [&](double& x) { f = [&](double& x) { return std::exp(x); };
return std::exp(x);
};
lower_bound = 0.0; lower_bound = 0.0;
upper_bound = 1.0; upper_bound = 1.0;
pdf = [&](double& x) { pdf = [&](double& x) {
if(x >= lower_bound && x <= 0.2) { if (x >= lower_bound && x <= 0.2) {
return 0.1; return 0.1;
} }
if(x > 0.2 && x <= 0.4) { if (x > 0.2 && x <= 0.4) {
return 0.4; return 0.4;
} }
if(x > 0.4 && x < upper_bound) { if (x > 0.4 && x < upper_bound) {
return 1.5; return 1.5;
} }
return 0.0; return 0.0;
}; };
integral = math::monte_carlo::integral_monte_carlo((upper_bound - lower_bound) / 2.0, f, pdf); integral = math::monte_carlo::integral_monte_carlo(
(upper_bound - lower_bound) / 2.0, f, pdf);
std::cout << "This number should be close to 1.7182818: " << integral << std::endl; std::cout << "This number should be close to 1.7182818: " << integral
<< std::endl;
/* \int_{-\infty}^{\infty} sinc(x) dx, sinc(x) = sin(pi * x) / (pi * x) /* \int_{-\infty}^{\infty} sinc(x) dx, sinc(x) = sin(pi * x) / (pi * x)
This is a difficult integral because of its infinite domain. This is a difficult integral because of its infinite domain.
Therefore, it may deviate largely from the expected result. Therefore, it may deviate largely from the expected result.
*/ */
f = [&](double& x) { f = [&](double& x) { return std::sin(M_PI * x) / (M_PI * x); };
return std::sin(M_PI * x) / (M_PI * x);
};
pdf = [&](double& x) { pdf = [&](double& x) {
return 1.0 / std::sqrt(2.0 * M_PI) * std::exp(-x * x / 2.0); return 1.0 / std::sqrt(2.0 * M_PI) * std::exp(-x * x / 2.0);
@ -183,7 +204,8 @@ static void test() {
integral = math::monte_carlo::integral_monte_carlo(0.0, f, pdf, 10000000); integral = math::monte_carlo::integral_monte_carlo(0.0, f, pdf, 10000000);
std::cout << "This number should be close to 1.0: " << integral << std::endl; std::cout << "This number should be close to 1.0: " << integral
<< std::endl;
} }
/** /**

238
math/volume.cpp Normal file
View File

@ -0,0 +1,238 @@
/**
* @file
* @brief Implmentations for the [volume](https://en.wikipedia.org/wiki/Volume)
* of various 3D shapes.
* @details The volume of a 3D shape is the amount of 3D space that the shape
* takes up. All shapes have a formula to get the volume of any given shape.
* These implementations support multiple return types.
*
* @author [Focusucof](https://github.com/Focusucof)
*/
#include <cassert> /// for assert
#include <cmath> /// for std::pow
#include <cstdint> /// for std::uint32_t
#include <iostream> /// for IO operations
/**
* @namespace math
* @brief Mathematical algorithms
*/
namespace math {
/**
* @brief The volume of a [cube](https://en.wikipedia.org/wiki/Cube)
* @param length The length of the cube
* @returns The volume of the cube
*/
template <typename T>
T cube_volume(T length) {
return std::pow(length, 3);
}
/**
* @brief The volume of a
* [rectangular](https://en.wikipedia.org/wiki/Cuboid) prism
* @param length The length of the base rectangle
* @param width The width of the base rectangle
* @param height The height of the rectangular prism
* @returns The volume of the rectangular prism
*/
template <typename T>
T rect_prism_volume(T length, T width, T height) {
return length * width * height;
}
/**
* @brief The volume of a [cone](https://en.wikipedia.org/wiki/Cone)
* @param radius The radius of the base circle
* @param height The height of the cone
* @param PI The definition of the constant PI
* @returns The volume of the cone
*/
template <typename T>
T cone_volume(T radius, T height, double PI = 3.14) {
return std::pow(radius, 2) * PI * height / 3;
}
/**
* @brief The volume of a
* [triangular](https://en.wikipedia.org/wiki/Triangular_prism) prism
* @param base The length of the base triangle
* @param height The height of the base triangles
* @param depth The depth of the triangular prism (the height of the whole
* prism)
* @returns The volume of the triangular prism
*/
template <typename T>
T triangle_prism_volume(T base, T height, T depth) {
return base * height * depth / 2;
}
/**
* @brief The volume of a
* [pyramid](https://en.wikipedia.org/wiki/Pyramid_(geometry))
* @param length The length of the base shape (or base for triangles)
* @param width The width of the base shape (or height for triangles)
* @param height The height of the pyramid
* @returns The volume of the pyramid
*/
template <typename T>
T pyramid_volume(T length, T width, T height) {
return length * width * height / 3;
}
/**
* @brief The volume of a [sphere](https://en.wikipedia.org/wiki/Sphere)
* @param radius The radius of the sphere
* @param PI The definition of the constant PI
* @returns The volume of the sphere
*/
template <typename T>
T sphere_volume(T radius, double PI = 3.14) {
return PI * std::pow(radius, 3) * 4 / 3;
}
/**
* @brief The volume of a [cylinder](https://en.wikipedia.org/wiki/Cylinder)
* @param radius The radius of the base circle
* @param height The height of the cylinder
* @param PI The definition of the constant PI
* @returns The volume of the cylinder
*/
template <typename T>
T cylinder_volume(T radius, T height, double PI = 3.14) {
return PI * std::pow(radius, 2) * height;
}
} // namespace math
/**
* @brief Self-test implementations
* @returns void
*/
static void test() {
// Input variables
uint32_t int_length = 0; // 32 bit integer length input
uint32_t int_width = 0; // 32 bit integer width input
uint32_t int_base = 0; // 32 bit integer base input
uint32_t int_height = 0; // 32 bit integer height input
uint32_t int_depth = 0; // 32 bit integer depth input
double double_radius = NAN; // double radius input
double double_height = NAN; // double height input
// Output variables
uint32_t int_expected = 0; // 32 bit integer expected output
uint32_t int_volume = 0; // 32 bit integer output
double double_expected = NAN; // double expected output
double double_volume = NAN; // double output
// 1st test
int_length = 5;
int_expected = 125;
int_volume = math::cube_volume(int_length);
std::cout << "VOLUME OF A CUBE" << std::endl;
std::cout << "Input Length: " << int_length << std::endl;
std::cout << "Expected Output: " << int_expected << std::endl;
std::cout << "Output: " << int_volume << std::endl;
assert(int_volume == int_expected);
std::cout << "TEST PASSED" << std::endl << std::endl;
// 2nd test
int_length = 4;
int_width = 3;
int_height = 5;
int_expected = 60;
int_volume = math::rect_prism_volume(int_length, int_width, int_height);
std::cout << "VOLUME OF A RECTANGULAR PRISM" << std::endl;
std::cout << "Input Length: " << int_length << std::endl;
std::cout << "Input Width: " << int_width << std::endl;
std::cout << "Input Height: " << int_height << std::endl;
std::cout << "Expected Output: " << int_expected << std::endl;
std::cout << "Output: " << int_volume << std::endl;
assert(int_volume == int_expected);
std::cout << "TEST PASSED" << std::endl << std::endl;
// 3rd test
double_radius = 5;
double_height = 7;
double_expected = 183.16666666666666; // truncated to 14 decimal places
double_volume = math::cone_volume(double_radius, double_height);
std::cout << "VOLUME OF A CONE" << std::endl;
std::cout << "Input Radius: " << double_radius << std::endl;
std::cout << "Input Height: " << double_height << std::endl;
std::cout << "Expected Output: " << double_expected << std::endl;
std::cout << "Output: " << double_volume << std::endl;
assert(double_volume == double_expected);
std::cout << "TEST PASSED" << std::endl << std::endl;
// 4th test
int_base = 3;
int_height = 4;
int_depth = 5;
int_expected = 30;
int_volume = math::triangle_prism_volume(int_base, int_height, int_depth);
std::cout << "VOLUME OF A TRIANGULAR PRISM" << std::endl;
std::cout << "Input Base: " << int_base << std::endl;
std::cout << "Input Height: " << int_height << std::endl;
std::cout << "Input Depth: " << int_depth << std::endl;
std::cout << "Expected Output: " << int_expected << std::endl;
std::cout << "Output: " << int_volume << std::endl;
assert(int_volume == int_expected);
std::cout << "TEST PASSED" << std::endl << std::endl;
// 5th test
int_length = 10;
int_width = 3;
int_height = 5;
int_expected = 50;
int_volume = math::pyramid_volume(int_length, int_width, int_height);
std::cout << "VOLUME OF A PYRAMID" << std::endl;
std::cout << "Input Length: " << int_length << std::endl;
std::cout << "Input Width: " << int_width << std::endl;
std::cout << "Input Height: " << int_height << std::endl;
std::cout << "Expected Output: " << int_expected << std::endl;
std::cout << "Output: " << int_volume << std::endl;
assert(int_volume == int_expected);
std::cout << "TEST PASSED" << std::endl << std::endl;
// 6th test
double_radius = 3;
double_expected = 113.04;
double_volume = math::sphere_volume(double_radius);
std::cout << "VOLUME OF A SPHERE" << std::endl;
std::cout << "Input Radius: " << double_radius << std::endl;
std::cout << "Expected Output: " << double_expected << std::endl;
std::cout << "Output: " << double_volume << std::endl;
assert(double_volume == double_expected);
std::cout << "TEST PASSED" << std::endl << std::endl;
// 7th test
double_radius = 5;
double_height = 2;
double_expected = 157;
double_volume = math::cylinder_volume(double_radius, double_height);
std::cout << "VOLUME OF A CYLINDER" << std::endl;
std::cout << "Input Radius: " << double_radius << std::endl;
std::cout << "Input Height: " << double_height << std::endl;
std::cout << "Expected Output: " << double_expected << std::endl;
std::cout << "Output: " << double_volume << std::endl;
assert(double_volume == double_expected);
std::cout << "TEST PASSED" << std::endl << std::endl;
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main() {
test(); // run self-test implementations
return 0;
}

View File

@ -1,31 +1,174 @@
#include <iostream> /**
using namespace std; * @file
* @brief Implementation for the [Array Left
* Rotation](https://www.javatpoint.com/program-to-left-rotate-the-elements-of-an-array)
* algorithm.
* @details Shifting an array to the left involves moving each element of the
* array so that it occupies a position of a certain shift value before its
* current one. This implementation uses a result vector and does not mutate the
* input.
* @author [Alvin](https://github.com/polarvoid)
*/
#include <cassert> /// for assert
#include <iostream> /// for IO operations
#include <vector> /// for std::vector
/**
* @namespace operations_on_datastructures
* @brief Operations on Data Structures
*/
namespace operations_on_datastructures {
/**
* @brief Prints the values of a vector sequentially, ending with a newline
* character.
* @param array Reference to the array to be printed
* @returns void
*/
void print(const std::vector<int32_t> &array) {
for (int32_t i : array) {
std::cout << i << " "; /// Print each value in the array
}
std::cout << "\n"; /// Print newline
}
/**
* @brief Shifts the given vector to the left by the shift amount and returns a
* new vector with the result. The original vector is not mutated.
* @details Shifts the values of the vector, by creating a new vector and adding
* values from the shift index to the end, then appending the rest of the
* elements from the start of the vector.
* @param array A reference to the input std::vector
* @param shift The amount to be shifted to the left
* @returns A std::vector with the shifted values
*/
std::vector<int32_t> shift_left(const std::vector<int32_t> &array,
size_t shift) {
if (array.size() <= shift) {
return {}; ///< We got an invalid shift, return empty array
}
std::vector<int32_t> res(array.size()); ///< Result array
for (size_t i = shift; i < array.size(); i++) {
res[i - shift] = array[i]; ///< Add values after the shift index
}
for (size_t i = 0; i < shift; i++) {
res[array.size() - shift + i] =
array[i]; ///< Add the values from the start
}
return res;
}
} // namespace operations_on_datastructures
/**
* @namespace tests
* @brief Testcases to check Union of Two Arrays.
*/
namespace tests {
using operations_on_datastructures::print;
using operations_on_datastructures::shift_left;
/**
* @brief A Test to check an simple case
* @returns void
*/
void test1() {
std::cout << "TEST CASE 1\n";
std::cout << "Initialized arr = {1, 2, 3, 4, 5}\n";
std::cout << "Expected result: {3, 4, 5, 1, 2}\n";
std::vector<int32_t> arr = {1, 2, 3, 4, 5};
std::vector<int32_t> res = shift_left(arr, 2);
std::vector<int32_t> expected = {3, 4, 5, 1, 2};
assert(res == expected);
print(res); ///< Should print 3 4 5 1 2
std::cout << "TEST PASSED!\n\n";
}
/**
* @brief A Test to check an empty vector
* @returns void
*/
void test2() {
std::cout << "TEST CASE 2\n";
std::cout << "Initialized arr = {}\n";
std::cout << "Expected result: {}\n";
std::vector<int32_t> arr = {};
std::vector<int32_t> res = shift_left(arr, 2);
std::vector<int32_t> expected = {};
assert(res == expected);
print(res); ///< Should print empty newline
std::cout << "TEST PASSED!\n\n";
}
/**
* @brief A Test to check an invalid shift value
* @returns void
*/
void test3() {
std::cout << "TEST CASE 3\n";
std::cout << "Initialized arr = {1, 2, 3, 4, 5}\n";
std::cout << "Expected result: {}\n";
std::vector<int32_t> arr = {1, 2, 3, 4, 5};
std::vector<int32_t> res = shift_left(arr, 7); ///< 7 > 5
std::vector<int32_t> expected = {};
assert(res == expected);
print(res); ///< Should print empty newline
std::cout << "TEST PASSED!\n\n";
}
/**
* @brief A Test to check a very large input
* @returns void
*/
void test4() {
std::cout << "TEST CASE 4\n";
std::cout << "Initialized arr = {2, 4, ..., 420}\n";
std::cout << "Expected result: {4, 6, ..., 420, 2}\n";
std::vector<int32_t> arr;
for (int i = 1; i <= 210; i++) {
arr.push_back(i * 2);
}
print(arr);
std::vector<int32_t> res = shift_left(arr, 1);
std::vector<int32_t> expected;
for (int i = 1; i < 210; i++) {
expected.push_back(arr[i]);
}
expected.push_back(2);
assert(res == expected);
print(res); ///< Should print {4, 6, ..., 420, 2}
std::cout << "TEST PASSED!\n\n";
}
/**
* @brief A Test to check a shift of zero
* @returns void
*/
void test5() {
std::cout << "TEST CASE 5\n";
std::cout << "Initialized arr = {1, 2, 3, 4, 5}\n";
std::cout << "Expected result: {1, 2, 3, 4, 5}\n";
std::vector<int32_t> arr = {1, 2, 3, 4, 5};
std::vector<int32_t> res = shift_left(arr, 0);
assert(res == arr);
print(res); ///< Should print 1 2 3 4 5
std::cout << "TEST PASSED!\n\n";
}
} // namespace tests
/**
* @brief Function to test the correctness of shift_left() function
* @returns void
*/
static void test() {
tests::test1();
tests::test2();
tests::test3();
tests::test4();
tests::test5();
}
/**
* @brief main function
* @returns 0 on exit
*/
int main() { int main() {
int n, k; test(); // run self-test implementations
cout << "Enter size of array=\t";
cin >> n;
cout << "Enter Number of indeces u want to rotate the array to left=\t";
cin >> k;
int a[n];
cout << "Enter elements of array=\t";
for (int i = 0; i < n; i++) {
cin >> a[i];
}
int temp = 0;
for (int i = 0; i < k; i++) {
temp = a[0];
for (int j = 0; j < n; j++) {
if (j == n - 1) {
a[n - 1] = temp;
} else {
a[j] = a[j + 1];
}
}
}
cout << "Your rotated array is=\t";
for (int j = 0; j < n; j++) {
cout << a[j] << " ";
}
getchar();
return 0; return 0;
} }

View File

@ -7,6 +7,7 @@
* in the first array, combined with all of the unique elements of a second * in the first array, combined with all of the unique elements of a second
* array. This implementation uses ordered arrays, and an algorithm to correctly * array. This implementation uses ordered arrays, and an algorithm to correctly
* order them and return the result as a new array (vector). * order them and return the result as a new array (vector).
* @see intersection_of_two_arrays.cpp
* @author [Alvin](https://github.com/polarvoid) * @author [Alvin](https://github.com/polarvoid)
*/ */

View File

@ -144,7 +144,7 @@ void update(std::vector<int64_t> *segtree, std::vector<int64_t> *lazy,
* @returns void * @returns void
*/ */
static void test() { static void test() {
int64_t max = static_cast<int64_t>(2 * pow(2, ceil(log2(7))) - 1); auto max = static_cast<int64_t>(2 * pow(2, ceil(log2(7))) - 1);
assert(max == 15); assert(max == 15);
std::vector<int64_t> arr{1, 2, 3, 4, 5, 6, 7}, lazy(max), segtree(max); std::vector<int64_t> arr{1, 2, 3, 4, 5, 6, 7}, lazy(max), segtree(max);
@ -172,7 +172,7 @@ int main() {
uint64_t n = 0; uint64_t n = 0;
std::cin >> n; std::cin >> n;
uint64_t max = static_cast<uint64_t>(2 * pow(2, ceil(log2(n))) - 1); auto max = static_cast<uint64_t>(2 * pow(2, ceil(log2(n))) - 1);
std::vector<int64_t> arr(n), lazy(max), segtree(max); std::vector<int64_t> arr(n), lazy(max), segtree(max);
int choice = 0; int choice = 0;

View File

@ -1,33 +0,0 @@
// Selection Sort
#include <iostream>
using namespace std;
int main() {
int Array[6];
cout << "\nEnter any 6 Numbers for Unsorted Array : ";
// Input
for (int i = 0; i < 6; i++) {
cin >> Array[i];
}
// Selection Sorting
for (int i = 0; i < 6; i++) {
int min = i;
for (int j = i + 1; j < 6; j++) {
if (Array[j] < Array[min]) {
min = j; // Finding the smallest number in Array
}
}
int temp = Array[i];
Array[i] = Array[min];
Array[min] = temp;
}
// Output
cout << "\nSorted Array : ";
for (int i = 0; i < 6; i++) {
cout << Array[i] << "\t";
}
}

View File

@ -0,0 +1,126 @@
/******************************************************************************
* @file
* @brief Implementation of the [Selection
* sort](https://en.wikipedia.org/wiki/Selection_sort) implementation using
* swapping
* @details
* The selection sort algorithm divides the input vector into two parts: a
* sorted subvector of items which is built up from left to right at the front
* (left) of the vector, and a subvector of the remaining unsorted items that
* occupy the rest of the vector. Initially, the sorted subvector is empty, and
* the unsorted subvector is the entire input vector. The algorithm proceeds by
* finding the smallest (or largest, depending on the sorting order) element in
* the unsorted subvector, exchanging (swapping) it with the leftmost unsorted
* element (putting it in sorted order), and moving the subvector boundaries one
* element to the right.
*
* ### Implementation
*
* SelectionSort
* The algorithm divides the input vector into two parts: the subvector of items
* already sorted, which is built up from left to right. Initially, the sorted
* subvector is empty and the unsorted subvector is the entire input vector. The
* algorithm proceeds by finding the smallest element in the unsorted subvector,
* exchanging (swapping) it with the leftmost unsorted element (putting it in
* sorted order), and moving the subvector boundaries one element to the right.
*
* @author [Lajat Manekar](https://github.com/Lazeeez)
* @author Unknown author
*******************************************************************************/
#include <algorithm> /// for std::is_sorted
#include <cassert> /// for std::assert
#include <iostream> /// for IO operations
#include <vector> /// for std::vector
/******************************************************************************
* @namespace sorting
* @brief Sorting algorithms
*******************************************************************************/
namespace sorting {
/******************************************************************************
* @brief The main function which implements Selection sort
* @param arr vector to be sorted
* @param len length of vector to be sorted
* @returns @param array resultant sorted vector
*******************************************************************************/
std::vector<uint64_t> selectionSort(const std::vector<uint64_t> &arr,
uint64_t len) {
std::vector<uint64_t> array(
arr.begin(),
arr.end()); // declare a vector in which result will be stored
for (uint64_t it = 0; it < len; ++it) {
uint64_t min = it; // set min value
for (uint64_t it2 = it + 1; it2 < len; ++it2) {
if (array[it2] < array[min]) { // check which element is smaller
min = it2; // store index of smallest element to min
}
}
if (min != it) { // swap if min does not match to i
uint64_t tmp = array[min];
array[min] = array[it];
array[it] = tmp;
}
}
return array; // return sorted vector
}
} // namespace sorting
/*******************************************************************************
* @brief Self-test implementations
* @returns void
*******************************************************************************/
static void test() {
// testcase #1
// [1, 0, 0, 1, 1, 0, 2, 1] returns [0, 0, 0, 1, 1, 1, 1, 2]
std::vector<uint64_t> vector1 = {1, 0, 0, 1, 1, 0, 2, 1};
uint64_t vector1size = vector1.size();
std::cout << "1st test... ";
std::vector<uint64_t> result_test1;
result_test1 = sorting::selectionSort(vector1, vector1size);
assert(std::is_sorted(result_test1.begin(), result_test1.end()));
std::cout << "Passed" << std::endl;
// testcase #2
// [19, 22, 540, 241, 156, 140, 12, 1] returns [1, 12, 19, 22, 140, 156,
// 241,540]
std::vector<uint64_t> vector2 = {19, 22, 540, 241, 156, 140, 12, 1};
uint64_t vector2size = vector2.size();
std::cout << "2nd test... ";
std::vector<uint64_t> result_test2;
result_test2 = sorting::selectionSort(vector2, vector2size);
assert(std::is_sorted(result_test2.begin(), result_test2.end()));
std::cout << "Passed" << std::endl;
// testcase #3
// [11, 20, 30, 41, 15, 60, 82, 15] returns [11, 15, 15, 20, 30, 41, 60, 82]
std::vector<uint64_t> vector3 = {11, 20, 30, 41, 15, 60, 82, 15};
uint64_t vector3size = vector3.size();
std::cout << "3rd test... ";
std::vector<uint64_t> result_test3;
result_test3 = sorting::selectionSort(vector3, vector3size);
assert(std::is_sorted(result_test3.begin(), result_test3.end()));
std::cout << "Passed" << std::endl;
// testcase #4
// [1, 9, 11, 546, 26, 65, 212, 14, -11] returns [-11, 1, 9, 11, 14, 26, 65,
// 212, 546]
std::vector<uint64_t> vector4 = {1, 9, 11, 546, 26, 65, 212, 14};
uint64_t vector4size = vector2.size();
std::cout << "4th test... ";
std::vector<uint64_t> result_test4;
result_test4 = sorting::selectionSort(vector4, vector4size);
assert(std::is_sorted(result_test4.begin(), result_test4.end()));
std::cout << "Passed" << std::endl;
}
/*******************************************************************************
* @brief Main function
* @returns 0 on exit
*******************************************************************************/
int main() {
test(); // run self-test implementations
return 0;
}