chore: import upstream snapshot with attribution
Awesome CI Workflow / Code Formatter (push) Has been cancelled
Awesome CI Workflow / Compile checks (macOS-latest) (push) Has been cancelled
Awesome CI Workflow / Compile checks (ubuntu-latest) (push) Has been cancelled
Awesome CI Workflow / Compile checks (windows-latest) (push) Has been cancelled
Awesome CI Workflow / Code Formatter (push) Has been cancelled
Awesome CI Workflow / Compile checks (macOS-latest) (push) Has been cancelled
Awesome CI Workflow / Compile checks (ubuntu-latest) (push) Has been cancelled
Awesome CI Workflow / Compile checks (windows-latest) (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
# If necessary, use the RELATIVE flag, otherwise each source file may be listed
|
||||
# with full pathname. RELATIVE may makes it easier to extract an executable name
|
||||
# automatically.
|
||||
file( GLOB APP_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp )
|
||||
# file( GLOB APP_SOURCES ${CMAKE_SOURCE_DIR}/*.c )
|
||||
# AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR} APP_SOURCES)
|
||||
foreach( testsourcefile ${APP_SOURCES} )
|
||||
# I used a simple string replace, to cut off .cpp.
|
||||
string( REPLACE ".cpp" "" testname ${testsourcefile} )
|
||||
add_executable( ${testname} ${testsourcefile} )
|
||||
|
||||
set_target_properties(${testname} PROPERTIES LINKER_LANGUAGE CXX)
|
||||
if(OpenMP_CXX_FOUND)
|
||||
target_link_libraries(${testname} OpenMP::OpenMP_CXX)
|
||||
endif()
|
||||
install(TARGETS ${testname} DESTINATION "bin/backtracking")
|
||||
|
||||
endforeach( testsourcefile ${APP_SOURCES} )
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* @file
|
||||
* @brief Well-formed [Generated
|
||||
* Parentheses](https://leetcode.com/explore/interview/card/top-interview-questions-medium/109/backtracking/794/) with all combinations.
|
||||
*
|
||||
* @details a sequence of parentheses is well-formed if each opening parentheses
|
||||
* has a corresponding closing parenthesis
|
||||
* and the closing parentheses are correctly ordered
|
||||
*
|
||||
* @author [Giuseppe Coco](https://github.com/WoWS17)
|
||||
|
||||
*/
|
||||
|
||||
#include <cassert> /// for assert
|
||||
#include <iostream> /// for I/O operation
|
||||
#include <vector> /// for vector container
|
||||
|
||||
/**
|
||||
* @brief Backtracking algorithms
|
||||
* @namespace backtracking
|
||||
*/
|
||||
namespace backtracking {
|
||||
/**
|
||||
* @brief generate_parentheses class
|
||||
*/
|
||||
class generate_parentheses {
|
||||
private:
|
||||
std::vector<std::string> res; ///< Contains all possible valid patterns
|
||||
|
||||
void makeStrings(std::string str, int n, int closed, int open);
|
||||
|
||||
public:
|
||||
std::vector<std::string> generate(int n);
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief function that adds parenthesis to the string.
|
||||
*
|
||||
* @param str string build during backtracking
|
||||
* @param n number of pairs of parentheses
|
||||
* @param closed number of closed parentheses
|
||||
* @param open number of open parentheses
|
||||
*/
|
||||
|
||||
void generate_parentheses::makeStrings(std::string str, int n,
|
||||
int closed, int open) {
|
||||
if (closed > open) // We can never have more closed than open
|
||||
return;
|
||||
|
||||
if ((str.length() == 2 * n) &&
|
||||
(closed != open)) { // closed and open must be the same
|
||||
return;
|
||||
}
|
||||
|
||||
if (str.length() == 2 * n) {
|
||||
res.push_back(str);
|
||||
return;
|
||||
}
|
||||
|
||||
makeStrings(str + ')', n, closed + 1, open);
|
||||
makeStrings(str + '(', n, closed, open + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief wrapper interface
|
||||
*
|
||||
* @param n number of pairs of parentheses
|
||||
* @return all well-formed pattern of parentheses
|
||||
*/
|
||||
std::vector<std::string> generate_parentheses::generate(int n) {
|
||||
backtracking::generate_parentheses::res.clear();
|
||||
std::string str = "(";
|
||||
generate_parentheses::makeStrings(str, n, 0, 1);
|
||||
return res;
|
||||
}
|
||||
} // namespace backtracking
|
||||
|
||||
/**
|
||||
* @brief Self-test implementations
|
||||
* @returns void
|
||||
*/
|
||||
static void test() {
|
||||
int n = 0;
|
||||
std::vector<std::string> patterns;
|
||||
backtracking::generate_parentheses p;
|
||||
|
||||
n = 1;
|
||||
patterns = {{"()"}};
|
||||
assert(p.generate(n) == patterns);
|
||||
|
||||
n = 3;
|
||||
patterns = {{"()()()"}, {"()(())"}, {"(())()"}, {"(()())"}, {"((()))"}};
|
||||
|
||||
assert(p.generate(n) == patterns);
|
||||
|
||||
n = 4;
|
||||
patterns = {{"()()()()"}, {"()()(())"}, {"()(())()"}, {"()(()())"},
|
||||
{"()((()))"}, {"(())()()"}, {"(())(())"}, {"(()())()"},
|
||||
{"(()()())"}, {"(()(()))"}, {"((()))()"}, {"((())())"},
|
||||
{"((()()))"}, {"(((())))"}};
|
||||
assert(p.generate(n) == patterns);
|
||||
|
||||
std::cout << "All tests passed\n";
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Main function
|
||||
* @returns 0 on exit
|
||||
*/
|
||||
int main() {
|
||||
test(); // run self-test implementations
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
/**
|
||||
* @file
|
||||
* @brief prints the assigned colors
|
||||
* using [Graph Coloring](https://en.wikipedia.org/wiki/Graph_coloring)
|
||||
* algorithm
|
||||
*
|
||||
* @details
|
||||
* In graph theory, graph coloring is a special case of graph labeling;
|
||||
* it is an assignment of labels traditionally called "colors" to elements of a
|
||||
* graph subject to certain constraints. In its simplest form, it is a way of
|
||||
* coloring the vertices of a graph such that no two adjacent vertices are of
|
||||
* the same color; this is called a vertex coloring. Similarly, an edge coloring
|
||||
* assigns a color to each edge so that no two adjacent edges are of the same
|
||||
* color, and a face coloring of a planar graph assigns a color to each face or
|
||||
* region so that no two faces that share a boundary have the same color.
|
||||
*
|
||||
* @author [Anup Kumar Panwar](https://github.com/AnupKumarPanwar)
|
||||
* @author [David Leal](https://github.com/Panquesito7)
|
||||
*/
|
||||
|
||||
#include <array> /// for std::array
|
||||
#include <iostream> /// for IO operations
|
||||
|
||||
/**
|
||||
* @namespace backtracking
|
||||
* @brief Backtracking algorithms
|
||||
*/
|
||||
namespace backtracking {
|
||||
/**
|
||||
* @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
|
||||
* @param color array of colors assigned to the nodes
|
||||
*/
|
||||
template <size_t V>
|
||||
void printSolution(const std::array<int, V>& color) {
|
||||
std::cout << "Following are the assigned colors\n";
|
||||
for (auto& col : color) {
|
||||
std::cout << col;
|
||||
}
|
||||
std::cout << "\n";
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Utility function to check if the current color assignment is safe for
|
||||
* vertex v
|
||||
* @tparam V number of vertices in the graph
|
||||
* @param v index of graph vertex to check
|
||||
* @param graph matrix of graph nonnectivity
|
||||
* @param color vector of colors assigned to the graph nodes/vertices
|
||||
* @param c color value to check for the node `v`
|
||||
* @returns `true` if the color is safe to be assigned to the node
|
||||
* @returns `false` if the color is not safe to be assigned to the node
|
||||
*/
|
||||
template <size_t V>
|
||||
bool isSafe(int v, const std::array<std::array<int, V>, V>& graph,
|
||||
const std::array<int, V>& color, int c) {
|
||||
for (int i = 0; i < V; i++) {
|
||||
if (graph[v][i] && c == color[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Recursive utility function to solve m coloring problem
|
||||
* @tparam V number of vertices in the graph
|
||||
* @param graph matrix of graph nonnectivity
|
||||
* @param m number of colors
|
||||
* @param [in,out] color description // used in,out to notify in documentation
|
||||
* that this parameter gets modified by the function
|
||||
* @param v index of graph vertex to check
|
||||
*/
|
||||
template <size_t V>
|
||||
void graphColoring(const std::array<std::array<int, V>, V>& graph, int m,
|
||||
std::array<int, V> color, int v) {
|
||||
// base case:
|
||||
// If all vertices are assigned a color then return true
|
||||
if (v == V) {
|
||||
printSolution<V>(color);
|
||||
return;
|
||||
}
|
||||
|
||||
// Consider this vertex v and try different colors
|
||||
for (int c = 1; c <= m; c++) {
|
||||
// Check if assignment of color c to v is fine
|
||||
if (isSafe<V>(v, graph, color, c)) {
|
||||
color[v] = c;
|
||||
|
||||
// recur to assign colors to rest of the vertices
|
||||
graphColoring<V>(graph, m, color, v + 1);
|
||||
|
||||
// If assigning color c doesn't lead to a solution then remove it
|
||||
color[v] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace graph_coloring
|
||||
} // namespace backtracking
|
||||
|
||||
/**
|
||||
* @brief Main function
|
||||
* @returns 0 on exit
|
||||
*/
|
||||
int main() {
|
||||
// Create following graph and test whether it is 3 colorable
|
||||
// (3)---(2)
|
||||
// | / |
|
||||
// | / |
|
||||
// | / |
|
||||
// (0)---(1)
|
||||
|
||||
const int V = 4; // number of vertices in the graph
|
||||
std::array<std::array<int, V>, V> graph = {
|
||||
std::array<int, V>({0, 1, 1, 1}), std::array<int, V>({1, 0, 1, 0}),
|
||||
std::array<int, V>({1, 1, 0, 1}), std::array<int, V>({1, 0, 1, 0})};
|
||||
|
||||
int m = 3; // Number of colors
|
||||
std::array<int, V> color{};
|
||||
|
||||
backtracking::graph_coloring::graphColoring<V>(graph, m, color, 0);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
/**
|
||||
* @file
|
||||
* @brief [Knight's tour](https://en.wikipedia.org/wiki/Knight%27s_tour)
|
||||
* algorithm
|
||||
*
|
||||
* @details
|
||||
* A knight's tour is a sequence of moves of a knight on a chessboard
|
||||
* such that the knight visits every square only once. If the knight
|
||||
* ends on a square that is one knight's move from the beginning
|
||||
* square (so that it could tour the board again immediately, following
|
||||
* the same path, the tour is closed; otherwise, it is open.
|
||||
*
|
||||
* @author [Nikhil Arora](https://github.com/nikhilarora068)
|
||||
* @author [David Leal](https://github.com/Panquesito7)
|
||||
*/
|
||||
#include <array> /// for std::array
|
||||
#include <iostream> /// for IO operations
|
||||
|
||||
/**
|
||||
* @namespace backtracking
|
||||
* @brief Backtracking algorithms
|
||||
*/
|
||||
namespace backtracking {
|
||||
/**
|
||||
* @namespace knight_tour
|
||||
* @brief Functions for the [Knight's
|
||||
* tour](https://en.wikipedia.org/wiki/Knight%27s_tour) algorithm
|
||||
*/
|
||||
namespace knight_tour {
|
||||
/**
|
||||
* A utility function to check if i,j are valid indexes for N*N chessboard
|
||||
* @tparam V number of vertices in array
|
||||
* @param x current index in rows
|
||||
* @param y current index in columns
|
||||
* @param sol matrix where numbers are saved
|
||||
* @returns `true` if ....
|
||||
* @returns `false` if ....
|
||||
*/
|
||||
template <size_t V>
|
||||
bool issafe(int x, int y, const std::array<std::array<int, V>, V> &sol) {
|
||||
return (x < V && x >= 0 && y < V && y >= 0 && sol[x][y] == -1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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() {
|
||||
const int n = 8;
|
||||
std::array<std::array<int, n>, n> sol = {0};
|
||||
|
||||
int i = 0, j = 0;
|
||||
for (i = 0; i < n; i++) {
|
||||
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> ymov = {1, 2, 2, 1, -1, -2, -2, -1};
|
||||
|
||||
sol[0][0] = 0;
|
||||
|
||||
bool flag = backtracking::knight_tour::solve<n>(0, 0, 1, sol, xmov, ymov);
|
||||
if (flag == false) {
|
||||
std::cout << "Error: Solution does not exist\n";
|
||||
} else {
|
||||
for (i = 0; i < n; i++) {
|
||||
for (j = 0; j < n; j++) {
|
||||
std::cout << sol[i][j] << " ";
|
||||
}
|
||||
std::cout << "\n";
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
/*
|
||||
* @brief [Magic sequence](https://www.csplib.org/Problems/prob019/)
|
||||
* implementation
|
||||
*
|
||||
* @details Solve the magic sequence problem with backtracking
|
||||
*
|
||||
* "A magic sequence of length $n$ is a sequence of integers $x_0
|
||||
* \ldots x_{n-1}$ between $0$ and $n-1$, such that for all $i$
|
||||
* in $0$ to $n-1$, the number $i$ occurs exactly $x_i$ times in
|
||||
* the sequence. For instance, $6,2,1,0,0,0,1,0,0,0$ is a magic
|
||||
* sequence since $0$ occurs $6$ times in it, $1$ occurs twice, etc."
|
||||
* Quote taken from the [CSPLib](https://www.csplib.org/Problems/prob019/)
|
||||
* website
|
||||
*
|
||||
* @author [Jxtopher](https://github.com/Jxtopher)
|
||||
*/
|
||||
|
||||
#include <algorithm> /// for std::count
|
||||
#include <cassert> /// for assert
|
||||
#include <iostream> /// for IO operations
|
||||
#include <list> /// for std::list
|
||||
#include <numeric> /// for std::accumulate
|
||||
#include <vector> /// for std::vector
|
||||
|
||||
/**
|
||||
* @namespace backtracking
|
||||
* @brief Backtracking algorithms
|
||||
*/
|
||||
namespace backtracking {
|
||||
/**
|
||||
* @namespace magic_sequence
|
||||
* @brief Functions for the [Magic
|
||||
* sequence](https://www.csplib.org/Problems/prob019/) implementation
|
||||
*/
|
||||
namespace magic_sequence {
|
||||
using sequence_t =
|
||||
std::vector<unsigned int>; ///< Definition of the sequence type
|
||||
/**
|
||||
* @brief Print the magic sequence
|
||||
* @param s working memory for the sequence
|
||||
*/
|
||||
void print(const sequence_t& s) {
|
||||
for (const auto& item : s) std::cout << item << " ";
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Check if the sequence is magic
|
||||
* @param s working memory for the sequence
|
||||
* @returns true if it's a magic sequence
|
||||
* @returns false if it's NOT a magic sequence
|
||||
*/
|
||||
bool is_magic(const sequence_t& s) {
|
||||
for (unsigned int i = 0; i < s.size(); i++) {
|
||||
if (std::count(s.cbegin(), s.cend(), i) != s[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Sub-solutions filtering
|
||||
* @param s working memory for the sequence
|
||||
* @param depth current depth in tree
|
||||
* @returns true if the sub-solution is valid
|
||||
* @returns false if the sub-solution is NOT valid
|
||||
*/
|
||||
bool filtering(const sequence_t& s, unsigned int depth) {
|
||||
return std::accumulate(s.cbegin(), s.cbegin() + depth,
|
||||
static_cast<unsigned int>(0)) <= s.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Solve the Magic Sequence problem
|
||||
* @param s working memory for the sequence
|
||||
* @param ret list of the valid magic sequences
|
||||
* @param depth current depth in the tree
|
||||
*/
|
||||
void solve(sequence_t* s, std::list<sequence_t>* ret, unsigned int depth = 0) {
|
||||
if (depth == s->size()) {
|
||||
if (is_magic(*s)) {
|
||||
ret->push_back(*s);
|
||||
}
|
||||
} else {
|
||||
for (unsigned int i = 0; i < s->size(); i++) {
|
||||
(*s)[depth] = i;
|
||||
if (filtering(*s, depth + 1)) {
|
||||
solve(s, ret, depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace magic_sequence
|
||||
} // namespace backtracking
|
||||
|
||||
/**
|
||||
* @brief Self-test implementations
|
||||
* @returns void
|
||||
*/
|
||||
static void test() {
|
||||
// test a valid magic sequence
|
||||
backtracking::magic_sequence::sequence_t s_magic = {6, 2, 1, 0, 0,
|
||||
0, 1, 0, 0, 0};
|
||||
assert(backtracking::magic_sequence::is_magic(s_magic));
|
||||
|
||||
// test a non-valid magic sequence
|
||||
backtracking::magic_sequence::sequence_t s_not_magic = {5, 2, 1, 0, 0,
|
||||
0, 1, 0, 0, 0};
|
||||
assert(!backtracking::magic_sequence::is_magic(s_not_magic));
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Main function
|
||||
* @returns 0 on exit
|
||||
*/
|
||||
int main() {
|
||||
test(); // run self-test implementations
|
||||
|
||||
// solve magic sequences of size 2 to 11 and print the solutions
|
||||
for (unsigned int i = 2; i < 12; i++) {
|
||||
std::cout << "Solution for n = " << i << std::endl;
|
||||
// valid magic sequence list
|
||||
std::list<backtracking::magic_sequence::sequence_t> list_of_solutions;
|
||||
// initialization of a sequence
|
||||
backtracking::magic_sequence::sequence_t s1(i, i);
|
||||
// launch of solving the problem
|
||||
backtracking::magic_sequence::solve(&s1, &list_of_solutions);
|
||||
// print solutions
|
||||
for (const auto& item : list_of_solutions) {
|
||||
backtracking::magic_sequence::print(item);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* @file
|
||||
* @brief returns which is the longest/shortest number
|
||||
* using [minimax](https://en.wikipedia.org/wiki/Minimax) algorithm
|
||||
*
|
||||
* @details
|
||||
* Minimax (sometimes MinMax, MM or saddle point) is a decision rule used in
|
||||
* artificial intelligence, decision theory, game theory, statistics,
|
||||
* and philosophy for minimizing the possible loss for a worst case (maximum
|
||||
* loss) scenario. When dealing with gains, it is referred to as "maximin"—to
|
||||
* maximize the minimum gain. Originally formulated for two-player zero-sum game
|
||||
* theory, covering both the cases where players take alternate moves and those
|
||||
* 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 [David Leal](https://github.com/Panquesito7)
|
||||
*/
|
||||
#include <algorithm> /// for std::max, std::min
|
||||
#include <array> /// for std::array
|
||||
#include <cmath> /// for log2
|
||||
#include <iostream> /// for IO operations
|
||||
|
||||
/**
|
||||
* @namespace backtracking
|
||||
* @brief Backtracking algorithms
|
||||
*/
|
||||
namespace backtracking {
|
||||
/**
|
||||
* @brief Check which is the maximum/minimum number in the array
|
||||
* @param depth current depth in game tree
|
||||
* @param node_index current index in array
|
||||
* @param is_max if current index is the longest number
|
||||
* @param scores saved numbers in array
|
||||
* @param height maximum height for game tree
|
||||
* @returns the maximum or minimum number
|
||||
*/
|
||||
template <size_t T>
|
||||
int minimax(int depth, int node_index, bool is_max,
|
||||
const std::array<int, T> &scores, double height) {
|
||||
if (depth == height) {
|
||||
return scores[node_index];
|
||||
}
|
||||
|
||||
int v1 = minimax(depth + 1, node_index * 2, !is_max, scores, height);
|
||||
int v2 = minimax(depth + 1, node_index * 2 + 1, !is_max, scores, height);
|
||||
|
||||
return is_max ? std::max(v1, v2) : std::min(v1, v2);
|
||||
}
|
||||
} // namespace backtracking
|
||||
|
||||
/**
|
||||
* @brief Main function
|
||||
* @returns 0 on exit
|
||||
*/
|
||||
int main() {
|
||||
std::array<int, 8> scores = {90, 23, 6, 33, 21, 65, 123, 34423};
|
||||
double height = log2(scores.size());
|
||||
|
||||
std::cout << "Optimal value: "
|
||||
<< backtracking::minimax(0, 0, true, scores, height) << std::endl;
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* @file
|
||||
* @brief [Eight Queens](https://en.wikipedia.org/wiki/Eight_queens_puzzle)
|
||||
* puzzle
|
||||
*
|
||||
* @details
|
||||
* The **eight queens puzzle** is the problem of placing eight chess queens on
|
||||
* an 8×8 chessboard so that no two queens threaten each other; thus, a solution
|
||||
* requires that no two queens share the same row, column, or diagonal. The
|
||||
* eight queens puzzle is an example of the more general **n queens problem** of
|
||||
* placing n non-attacking queens on an n×n chessboard, for which solutions
|
||||
* exist for all natural numbers n with the exception of n = 2 and n = 3.
|
||||
*
|
||||
* @author Unknown author
|
||||
* @author [David Leal](https://github.com/Panquesito7)
|
||||
*
|
||||
*/
|
||||
#include <array>
|
||||
#include <iostream>
|
||||
|
||||
/**
|
||||
* @namespace backtracking
|
||||
* @brief Backtracking algorithms
|
||||
*/
|
||||
namespace backtracking {
|
||||
/**
|
||||
* @namespace n_queens
|
||||
* @brief Functions for [Eight
|
||||
* Queens](https://en.wikipedia.org/wiki/Eight_queens_puzzle) puzzle.
|
||||
*/
|
||||
namespace n_queens {
|
||||
/**
|
||||
* Utility function to print matrix
|
||||
* @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) {
|
||||
std::cout << "\n";
|
||||
for (int i = 0; i < n; i++) {
|
||||
for (int j = 0; j < n; j++) {
|
||||
std::cout << "" << board[i][j] << " ";
|
||||
}
|
||||
std::cout << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a queen can be placed on matrix
|
||||
* @tparam n number of matrix size
|
||||
* @param board matrix where numbers are saved
|
||||
* @param row current index in rows
|
||||
* @param col current index in columns
|
||||
* @returns `true` if queen can be placed on matrix
|
||||
* @returns `false` if queen can't be placed on matrix
|
||||
*/
|
||||
template <size_t n>
|
||||
bool isSafe(const std::array<std::array<int, n>, n> &board, const int &row,
|
||||
const int &col) {
|
||||
int i = 0, j = 0;
|
||||
|
||||
// Check this row on left side
|
||||
for (i = 0; i < col; i++) {
|
||||
if (board[row][i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Check upper diagonal on left side
|
||||
for (i = row, j = col; i >= 0 && j >= 0; i--, j--) {
|
||||
if (board[i][j]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// Check lower diagonal on left side
|
||||
for (i = row, j = col; j >= 0 && i < n; i++, j--) {
|
||||
if (board[i][j]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
return;
|
||||
}
|
||||
|
||||
// Consider this column and try placing
|
||||
// this queen in all rows one by one
|
||||
for (int i = 0; i < n; i++) {
|
||||
// Check if queen can be placed
|
||||
// on board[i][col]
|
||||
if (isSafe<n>(board, i, col)) {
|
||||
// Place this queen in matrix
|
||||
board[i][col] = 1;
|
||||
|
||||
// Recursive to place rest of the queens
|
||||
solveNQ<n>(board, col + 1);
|
||||
|
||||
board[i][col] = 0; // backtrack
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace n_queens
|
||||
} // namespace backtracking
|
||||
|
||||
/**
|
||||
* @brief Main function
|
||||
* @returns 0 on exit
|
||||
*/
|
||||
int main() {
|
||||
const int n = 4;
|
||||
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})};
|
||||
|
||||
backtracking::n_queens::solveNQ<n>(board, 0);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
/**
|
||||
* @file
|
||||
* @brief [N queens](https://en.wikipedia.org/wiki/Eight_queens_puzzle) all
|
||||
* optimized
|
||||
*
|
||||
* @author [Sombit Bose](https://github.com/deadshotsb)
|
||||
* @author [David Leal](https://github.com/Panquesito7)
|
||||
*/
|
||||
|
||||
#include <array>
|
||||
#include <iostream>
|
||||
|
||||
/**
|
||||
* @namespace backtracking
|
||||
* @brief Backtracking algorithms
|
||||
*/
|
||||
namespace backtracking {
|
||||
/**
|
||||
* @namespace n_queens_optimized
|
||||
* @brief Functions for [Eight
|
||||
* Queens](https://en.wikipedia.org/wiki/Eight_queens_puzzle) puzzle optimized.
|
||||
*/
|
||||
namespace n_queens_optimized {
|
||||
/**
|
||||
* Utility function to print matrix
|
||||
* @tparam n number of matrix size
|
||||
* @param board matrix where numbers are saved
|
||||
*/
|
||||
template <size_t n>
|
||||
void PrintSol(const std::array<std::array<int, n>, n> &board) {
|
||||
for (int i = 0; i < n; i++) {
|
||||
for (int j = 0; j < n; j++) {
|
||||
std::cout << board[i][j] << " ";
|
||||
}
|
||||
std::cout << std::endl;
|
||||
}
|
||||
std::cout << std::endl;
|
||||
if (n % 2 == 0 || (n % 2 == 1 && board[n / 2 + 1][0] != 1)) {
|
||||
for (int i = 0; i < n; i++) {
|
||||
for (int j = 0; j < n; j++) {
|
||||
std::cout << board[j][i] << " ";
|
||||
}
|
||||
std::cout << std::endl;
|
||||
}
|
||||
std::cout << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a queen can be placed on matrix
|
||||
* @tparam n number of matrix size
|
||||
* @param board matrix where numbers are saved
|
||||
* @param row current index in rows
|
||||
* @param col current index in columns
|
||||
* @returns `true` if queen can be placed on matrix
|
||||
* @returns `false` if queen can't be placed on matrix
|
||||
*/
|
||||
template <size_t n>
|
||||
bool CanIMove(const std::array<std::array<int, n>, n> &board, int row,
|
||||
int col) {
|
||||
/// check in the row
|
||||
for (int i = 0; i <= col; i++) {
|
||||
if (board[row][i] == 1) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/// check the first diagonal
|
||||
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
|
||||
if (board[i][j] == 1) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/// check the second diagonal
|
||||
for (int i = row, j = col; i <= n - 1 && j >= 0; i++, j--) {
|
||||
if (board[i][j] == 1) {
|
||||
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 NQueenSol(std::array<std::array<int, n>, n> board, int col) {
|
||||
if (col >= n) {
|
||||
PrintSol<n>(board);
|
||||
return;
|
||||
}
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (CanIMove<n>(board, i, col)) {
|
||||
board[i][col] = 1;
|
||||
NQueenSol<n>(board, col + 1);
|
||||
board[i][col] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace n_queens_optimized
|
||||
} // namespace backtracking
|
||||
|
||||
/**
|
||||
* @brief Main function
|
||||
* @returns 0 on exit
|
||||
*/
|
||||
int main() {
|
||||
const int n = 4;
|
||||
std::array<std::array<int, n>, n> board{};
|
||||
|
||||
if (n % 2 == 0) {
|
||||
for (int i = 0; i <= n / 2 - 1; i++) {
|
||||
if (backtracking::n_queens_optimized::CanIMove(board, i, 0)) {
|
||||
board[i][0] = 1;
|
||||
backtracking::n_queens_optimized::NQueenSol(board, 1);
|
||||
board[i][0] = 0;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (int i = 0; i <= n / 2; i++) {
|
||||
if (backtracking::n_queens_optimized::CanIMove(board, i, 0)) {
|
||||
board[i][0] = 1;
|
||||
backtracking::n_queens_optimized::NQueenSol(board, 1);
|
||||
board[i][0] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* @file
|
||||
* @brief [Eight Queens](https://en.wikipedia.org/wiki/Eight_queens_puzzle)
|
||||
* puzzle, printing all solutions
|
||||
*
|
||||
* @author [Himani Negi](https://github.com/Himani2000)
|
||||
* @author [David Leal](https://github.com/Panquesito7)
|
||||
*
|
||||
*/
|
||||
#include <array> /// for std::array
|
||||
#include <iostream> /// for IO operations
|
||||
|
||||
/**
|
||||
* @namespace backtracking
|
||||
* @brief Backtracking algorithms
|
||||
*/
|
||||
namespace backtracking {
|
||||
/**
|
||||
* @namespace n_queens_all_solutions
|
||||
* @brief Functions for the [Eight
|
||||
* Queens](https://en.wikipedia.org/wiki/Eight_queens_puzzle) puzzle with all
|
||||
* solutions.
|
||||
*/
|
||||
namespace n_queens_all_solutions {
|
||||
/**
|
||||
* @brief Utility function to print matrix
|
||||
* @tparam n number of matrix size
|
||||
* @param board matrix where numbers are saved
|
||||
*/
|
||||
template <size_t n>
|
||||
void PrintSol(const std::array<std::array<int, n>, n>& board) {
|
||||
for (int i = 0; i < n; i++) {
|
||||
for (int j = 0; j < n; j++) {
|
||||
std::cout << board[i][j] << " ";
|
||||
}
|
||||
std::cout << std::endl;
|
||||
}
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Check if a queen can be placed on the matrix
|
||||
* @tparam n number of matrix size
|
||||
* @param board matrix where numbers are saved
|
||||
* @param row current index in rows
|
||||
* @param col current index in columns
|
||||
* @returns `true` if queen can be placed on matrix
|
||||
* @returns `false` if queen can't be placed on matrix
|
||||
*/
|
||||
template <size_t n>
|
||||
bool CanIMove(const std::array<std::array<int, n>, n>& board, int row,
|
||||
int col) {
|
||||
/// check in the row
|
||||
for (int i = 0; i < col; i++) {
|
||||
if (board[row][i] == 1) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/// check the first diagonal
|
||||
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
|
||||
if (board[i][j] == 1) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/// check the second diagonal
|
||||
for (int i = row, j = col; i <= n - 1 && j >= 0; i++, j--) {
|
||||
if (board[i][j] == 1) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Main function to solve the 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 NQueenSol(std::array<std::array<int, n>, n> board, int col) {
|
||||
if (col >= n) {
|
||||
PrintSol(board);
|
||||
return;
|
||||
}
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (CanIMove(board, i, col)) {
|
||||
board[i][col] = 1;
|
||||
NQueenSol(board, col + 1);
|
||||
board[i][col] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace n_queens_all_solutions
|
||||
} // namespace backtracking
|
||||
|
||||
/**
|
||||
* @brief Main function
|
||||
* @returns 0 on exit
|
||||
*/
|
||||
int main() {
|
||||
const int n = 4;
|
||||
std::array<std::array<int, n>, n> board{0};
|
||||
|
||||
backtracking::n_queens_all_solutions::NQueenSol(board, 0);
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* @file
|
||||
* @brief Implements [Rat in a
|
||||
* Maze](https://www.codesdope.com/blog/article/backtracking-to-
|
||||
* solve-a-rat-in-a-maze-c-java-pytho/) algorithm
|
||||
*
|
||||
* @details
|
||||
* A Maze is given as N*N binary matrix of blocks where source block is the
|
||||
* upper left most block i.e., maze[0][0] and destination block is lower
|
||||
* rightmost block i.e., maze[N-1][N-1]. A rat starts from source and has to
|
||||
* reach destination. The rat can move only in two directions: forward and down.
|
||||
* In the maze matrix, 0 means the block is dead end and 1 means the block can
|
||||
* be used in the path from source to destination.
|
||||
*
|
||||
* @author [Vaibhav Thakkar](https://github.com/vaithak)
|
||||
* @author [David Leal](https://github.com/Panquesito7)
|
||||
*/
|
||||
|
||||
#include <array> /// for std::array
|
||||
#include <cassert> /// for assert
|
||||
#include <iostream> /// for IO operations
|
||||
|
||||
/**
|
||||
* @namespace backtracking
|
||||
* @brief Backtracking algorithms
|
||||
*/
|
||||
namespace backtracking {
|
||||
/**
|
||||
* @namespace rat_maze
|
||||
* @brief Functions for [Rat in a
|
||||
* Maze](https://www.codesdope.com/blog/article/backtracking-to-
|
||||
* solve-a-rat-in-a-maze-c-java-pytho/) algorithm
|
||||
*/
|
||||
namespace rat_maze {
|
||||
/**
|
||||
* @brief Solve rat maze problem
|
||||
* @tparam size number of matrix size
|
||||
* @param currposrow current position in rows
|
||||
* @param currposcol current position in columns
|
||||
* @param maze matrix where numbers are saved
|
||||
* @param soln matrix to problem solution
|
||||
* @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>
|
||||
bool solveMaze(int currposrow, int currposcol,
|
||||
const std::array<std::array<int, size>, size> &maze,
|
||||
std::array<std::array<int, size>, size> soln) {
|
||||
if ((currposrow == size - 1) && (currposcol == size - 1)) {
|
||||
soln[currposrow][currposcol] = 1;
|
||||
for (int i = 0; i < size; ++i) {
|
||||
for (int j = 0; j < size; ++j) {
|
||||
std::cout << soln[i][j] << " ";
|
||||
}
|
||||
std::cout << std::endl;
|
||||
}
|
||||
return true;
|
||||
} else {
|
||||
soln[currposrow][currposcol] = 1;
|
||||
|
||||
// if there exist a solution by moving one step ahead in a column
|
||||
if ((currposcol < size - 1) && maze[currposrow][currposcol + 1] == 1 &&
|
||||
solveMaze(currposrow, currposcol + 1, maze, soln)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// if there exists a solution by moving one step ahead in a row
|
||||
if ((currposrow < size - 1) && maze[currposrow + 1][currposcol] == 1 &&
|
||||
solveMaze(currposrow + 1, currposcol, maze, soln)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// the backtracking part
|
||||
soln[currposrow][currposcol] = 0;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} // namespace rat_maze
|
||||
} // namespace backtracking
|
||||
|
||||
/**
|
||||
* @brief Self-test implementations
|
||||
* @returns void
|
||||
*/
|
||||
static void test() {
|
||||
const int size = 4;
|
||||
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, 0, 1}, std::array<int, size>{1, 1, 1, 1}};
|
||||
|
||||
std::array<std::array<int, size>, size> soln{};
|
||||
|
||||
// Backtracking: setup matrix solution to zero
|
||||
for (int i = 0; i < size; ++i) {
|
||||
for (int j = 0; j < size; ++j) {
|
||||
soln[i][j] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
int currposrow = 0; // Current position in the rows
|
||||
int currposcol = 0; // Current position in the columns
|
||||
|
||||
assert(backtracking::rat_maze::solveMaze<size>(currposrow, currposcol, maze,
|
||||
soln) == 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Main function
|
||||
* @returns 0 on exit
|
||||
*/
|
||||
int main() {
|
||||
test(); // run self-test implementations
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* @file
|
||||
* @brief [Subset-sum](https://en.wikipedia.org/wiki/Subset_sum_problem) (only
|
||||
* continuous subsets) problem
|
||||
* @details We are given an array and a sum value. The algorithms find all
|
||||
* the subarrays of that array with sum equal to the given sum and return such
|
||||
* subarrays count. This approach will have \f$O(n)\f$ time complexity and
|
||||
* \f$O(n)\f$ space complexity. NOTE: In this problem, we are only referring to
|
||||
* the continuous subsets as subarrays everywhere. Subarrays can be created
|
||||
* using deletion operation at the end of the front of an array only. The parent
|
||||
* array is also counted in subarrays having 0 number of deletion operations.
|
||||
*
|
||||
* @author [Swastika Gupta](https://github.com/Swastyy)
|
||||
*/
|
||||
|
||||
#include <cassert> /// for assert
|
||||
#include <cstdint>
|
||||
#include <iostream> /// for IO operations
|
||||
#include <unordered_map> /// for unordered_map
|
||||
#include <vector> /// for std::vector
|
||||
|
||||
/**
|
||||
* @namespace backtracking
|
||||
* @brief Backtracking algorithms
|
||||
*/
|
||||
namespace backtracking {
|
||||
/**
|
||||
* @namespace subarray_sum
|
||||
* @brief Functions for the [Subset
|
||||
* sum](https://en.wikipedia.org/wiki/Subset_sum_problem) implementation
|
||||
*/
|
||||
namespace subarray_sum {
|
||||
/**
|
||||
* @brief The main function that implements the count of the subarrays
|
||||
* @param sum is the required sum of any subarrays
|
||||
* @param in_arr is the input array
|
||||
* @returns count of the number of subsets with required sum
|
||||
*/
|
||||
uint64_t subarray_sum(int64_t sum, const std::vector<int64_t> &in_arr) {
|
||||
int64_t nelement = in_arr.size();
|
||||
int64_t count_of_subset = 0;
|
||||
int64_t current_sum = 0;
|
||||
std::unordered_map<int64_t, int64_t>
|
||||
sumarray; // to store the subarrays count
|
||||
// frequency having some sum value
|
||||
|
||||
for (int64_t i = 0; i < nelement; i++) {
|
||||
current_sum += in_arr[i];
|
||||
|
||||
if (current_sum == sum) {
|
||||
count_of_subset++;
|
||||
}
|
||||
// If in case current_sum is greater than the required sum
|
||||
if (sumarray.find(current_sum - sum) != sumarray.end()) {
|
||||
count_of_subset += (sumarray[current_sum - sum]);
|
||||
}
|
||||
sumarray[current_sum]++;
|
||||
}
|
||||
return count_of_subset;
|
||||
}
|
||||
} // namespace subarray_sum
|
||||
} // namespace backtracking
|
||||
|
||||
/**
|
||||
* @brief Self-test implementations
|
||||
* @returns void
|
||||
*/
|
||||
static void test() {
|
||||
// 1st test
|
||||
std::cout << "1st test ";
|
||||
std::vector<int64_t> array1 = {-7, -3, -2, 5, 8}; // input array
|
||||
assert(
|
||||
backtracking::subarray_sum::subarray_sum(0, array1) ==
|
||||
1); // first argument in subarray_sum function is the required sum and
|
||||
// second is the input array, answer is the subarray {(-3,-2,5)}
|
||||
std::cout << "passed" << std::endl;
|
||||
|
||||
// 2nd test
|
||||
std::cout << "2nd test ";
|
||||
std::vector<int64_t> array2 = {1, 2, 3, 3};
|
||||
assert(backtracking::subarray_sum::subarray_sum(6, array2) ==
|
||||
2); // here we are expecting 2 subsets which sum up to 6 i.e.
|
||||
// {(1,2,3),(3,3)}
|
||||
std::cout << "passed" << std::endl;
|
||||
|
||||
// 3rd test
|
||||
std::cout << "3rd test ";
|
||||
std::vector<int64_t> array3 = {1, 1, 1, 1};
|
||||
assert(backtracking::subarray_sum::subarray_sum(1, array3) ==
|
||||
4); // here we are expecting 4 subsets which sum up to 1 i.e.
|
||||
// {(1),(1),(1),(1)}
|
||||
std::cout << "passed" << std::endl;
|
||||
|
||||
// 4rd test
|
||||
std::cout << "4th test ";
|
||||
std::vector<int64_t> array4 = {3, 3, 3, 3};
|
||||
assert(backtracking::subarray_sum::subarray_sum(6, array4) ==
|
||||
3); // here we are expecting 3 subsets which sum up to 6 i.e.
|
||||
// {(3,3),(3,3),(3,3)}
|
||||
std::cout << "passed" << std::endl;
|
||||
|
||||
// 5th test
|
||||
std::cout << "5th test ";
|
||||
std::vector<int64_t> array5 = {};
|
||||
assert(backtracking::subarray_sum::subarray_sum(6, array5) ==
|
||||
0); // here we are expecting 0 subsets which sum up to 6 i.e. we
|
||||
// cannot select anything from an empty array
|
||||
std::cout << "passed" << std::endl;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Main function
|
||||
* @returns 0 on exit
|
||||
*/
|
||||
int main() {
|
||||
test(); // run self-test implementations
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* @file
|
||||
* @brief Implementation of the [Subset
|
||||
* Sum](https://en.wikipedia.org/wiki/Subset_sum_problem) problem.
|
||||
* @details
|
||||
* We are given an array and a sum value. The algorithm finds all
|
||||
* the subsets of that array with sum equal to the given sum and return such
|
||||
* subsets count. This approach will have exponential time complexity.
|
||||
* @author [Swastika Gupta](https://github.com/Swastyy)
|
||||
*/
|
||||
|
||||
#include <cassert> /// for assert
|
||||
#include <cstdint>
|
||||
#include <iostream> /// for IO operations
|
||||
#include <vector> /// for std::vector
|
||||
|
||||
/**
|
||||
* @namespace backtracking
|
||||
* @brief Backtracking algorithms
|
||||
*/
|
||||
namespace backtracking {
|
||||
/**
|
||||
* @namespace Subsets
|
||||
* @brief Functions for the [Subset
|
||||
* Sum](https://en.wikipedia.org/wiki/Subset_sum_problem) problem.
|
||||
*/
|
||||
namespace subset_sum {
|
||||
/**
|
||||
* @brief The main function implements count of subsets
|
||||
* @param sum is the required sum of any subset
|
||||
* @param in_arr is the input array
|
||||
* @returns count of the number of subsets with required sum
|
||||
*/
|
||||
uint64_t number_of_subsets(int32_t sum, const std::vector<int32_t> &in_arr) {
|
||||
int32_t nelement = in_arr.size();
|
||||
uint64_t count_of_subset = 0;
|
||||
|
||||
for (int32_t i = 0; i < (1 << (nelement)); i++) {
|
||||
int32_t check = 0;
|
||||
for (int32_t j = 0; j < nelement; j++) {
|
||||
if (i & (1 << j)) {
|
||||
check += (in_arr[j]);
|
||||
}
|
||||
}
|
||||
if (check == sum) {
|
||||
count_of_subset++;
|
||||
}
|
||||
}
|
||||
return count_of_subset;
|
||||
}
|
||||
} // namespace subset_sum
|
||||
} // namespace backtracking
|
||||
|
||||
/**
|
||||
* @brief Test implementations
|
||||
* @returns void
|
||||
*/
|
||||
static void test() {
|
||||
// 1st test
|
||||
std::cout << "1st test ";
|
||||
std::vector<int32_t> array1 = {-7, -3, -2, 5, 8}; // input array
|
||||
assert(backtracking::subset_sum::number_of_subsets(0, array1) ==
|
||||
2); // first argument in subset_sum function is the required sum and
|
||||
// second is the input array
|
||||
std::cout << "passed" << std::endl;
|
||||
|
||||
// 2nd test
|
||||
std::cout << "2nd test ";
|
||||
std::vector<int32_t> array2 = {1, 2, 3, 3};
|
||||
assert(backtracking::subset_sum::number_of_subsets(6, array2) ==
|
||||
3); // here we are expecting 3 subsets which sum up to 6 i.e.
|
||||
// {(1,2,3),(1,2,3),(3,3)}
|
||||
std::cout << "passed" << std::endl;
|
||||
|
||||
// 3rd test
|
||||
std::cout << "3rd test ";
|
||||
std::vector<int32_t> array3 = {1, 1, 1, 1};
|
||||
assert(backtracking::subset_sum::number_of_subsets(1, array3) ==
|
||||
4); // here we are expecting 4 subsets which sum up to 1 i.e.
|
||||
// {(1),(1),(1),(1)}
|
||||
std::cout << "passed" << std::endl;
|
||||
|
||||
// 4th test
|
||||
std::cout << "4th test ";
|
||||
std::vector<int32_t> array4 = {3, 3, 3, 3};
|
||||
assert(backtracking::subset_sum::number_of_subsets(6, array4) ==
|
||||
6); // here we are expecting 6 subsets which sum up to 6 i.e.
|
||||
// {(3,3),(3,3),(3,3),(3,3),(3,3),(3,3)}
|
||||
std::cout << "passed" << std::endl;
|
||||
|
||||
// Test 5
|
||||
std::cout << "5th test ";
|
||||
std::vector<int32_t> array5 = {};
|
||||
assert(backtracking::subset_sum::number_of_subsets(6, array5) ==
|
||||
0); // here we are expecting 0 subsets which sum up to 6 i.e. we
|
||||
// cannot select anything from an empty array
|
||||
std::cout << "passed" << std::endl;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Main function
|
||||
* @returns 0 on exit
|
||||
*/
|
||||
int main() {
|
||||
test(); // run self-test implementations
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
/**
|
||||
* @file
|
||||
* @brief [Sudoku Solver](https://en.wikipedia.org/wiki/Sudoku) algorithm.
|
||||
*
|
||||
* @details
|
||||
* Sudoku (数独, sūdoku, digit-single) (/suːˈdoʊkuː/, /-ˈdɒk-/, /sə-/,
|
||||
* originally called Number Place) is a logic-based, combinatorial
|
||||
* number-placement puzzle. In classic sudoku, the objective is to fill a 9×9
|
||||
* 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
|
||||
* partially completed grid, which for a well-posed puzzle has a single
|
||||
* solution.
|
||||
*
|
||||
* @author [DarthCoder3200](https://github.com/DarthCoder3200)
|
||||
* @author [David Leal](https://github.com/Panquesito7)
|
||||
*/
|
||||
#include <array> /// for assert
|
||||
#include <iostream> /// for IO operations
|
||||
|
||||
/**
|
||||
* @namespace backtracking
|
||||
* @brief Backtracking algorithms
|
||||
*/
|
||||
namespace backtracking {
|
||||
/**
|
||||
* @namespace sudoku_solver
|
||||
* @brief Functions for the [Sudoku
|
||||
* Solver](https://en.wikipedia.org/wiki/Sudoku) implementation
|
||||
*/
|
||||
namespace sudoku_solver {
|
||||
/**
|
||||
* @brief Check if it's possible to place a number (`no` parameter)
|
||||
* @tparam V number of vertices in the array
|
||||
* @param mat matrix where numbers are saved
|
||||
* @param i current index in rows
|
||||
* @param j current index in columns
|
||||
* @param no number to be added in matrix
|
||||
* @param n number of times loop will run
|
||||
* @returns `true` if 'mat' is different from '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 true;
|
||||
}
|
||||
/**
|
||||
* @brief Utility function to print the 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;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @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() {
|
||||
const int V = 9;
|
||||
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>{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>{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>{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, 0, 0, 4, 1, 9, 0, 0, 5},
|
||||
std::array<int, V>{0, 0, 0, 0, 8, 0, 0, 7, 9}};
|
||||
|
||||
backtracking::sudoku_solver::printMat<V>(mat, mat, 9);
|
||||
std::cout << "Solution " << std::endl;
|
||||
std::array<std::array<int, V>, V> starting_mat = mat;
|
||||
backtracking::sudoku_solver::solveSudoku<V>(mat, starting_mat, 0, 0);
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
/**
|
||||
* @file
|
||||
* @brief Implementation of the [Wildcard
|
||||
* Matching](https://www.geeksforgeeks.org/wildcard-pattern-matching/) problem.
|
||||
* @details
|
||||
* Given a matching string and a pattern, implement wildcard pattern
|
||||
* matching with support for `?` and `*`. `?` matches any single character.
|
||||
* `*` matches any sequence of characters (including the empty sequence).
|
||||
* The matching should cover the entire matching string (not partial). The task
|
||||
* is to determine if the pattern matches with the matching string
|
||||
* @author [Swastika Gupta](https://github.com/Swastyy)
|
||||
*/
|
||||
|
||||
#include <cassert> /// for assert
|
||||
#include <cstdint>
|
||||
#include <iostream> /// for IO operations
|
||||
#include <vector> /// for std::vector
|
||||
|
||||
/**
|
||||
* @namespace backtracking
|
||||
* @brief Backtracking algorithms
|
||||
*/
|
||||
namespace backtracking {
|
||||
/**
|
||||
* @namespace wildcard_matching
|
||||
* @brief Functions for the [Wildcard
|
||||
* Matching](https://www.geeksforgeeks.org/wildcard-pattern-matching/) problem.
|
||||
*/
|
||||
namespace wildcard_matching {
|
||||
/**
|
||||
* @brief The main function implements if pattern can be matched with given
|
||||
* string
|
||||
* @param s is the given matching string
|
||||
* @param p is the given pattern
|
||||
* @param pos1 is the starting index
|
||||
* @param pos2 is the last index
|
||||
* @returns 1 if pattern matches with matching string otherwise 0
|
||||
*/
|
||||
std::vector<std::vector<int64_t>> dpTable(1000, std::vector<int64_t>(1000, -1));
|
||||
bool wildcard_matching(std::string s, std::string p, uint32_t pos1,
|
||||
uint32_t pos2) {
|
||||
uint32_t n = s.length();
|
||||
uint32_t m = p.length();
|
||||
// matching is successfull if both strings are done
|
||||
if (pos1 == n && pos2 == m) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// matching is unsuccessfull if pattern is not finished but matching string
|
||||
// is
|
||||
if (pos1 != n && pos2 == m) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// all the remaining characters of patterns must be * inorder to match with
|
||||
// finished string
|
||||
if (pos1 == n && pos2 != m) {
|
||||
while (pos2 < m && p[pos2] == '*') {
|
||||
pos2++;
|
||||
}
|
||||
|
||||
return pos2 == m;
|
||||
}
|
||||
|
||||
// if already calculted for these positions
|
||||
if (dpTable[pos1][pos2] != -1) {
|
||||
return dpTable[pos1][pos2];
|
||||
}
|
||||
|
||||
// if the characters are same just go ahead in both the string
|
||||
if (s[pos1] == p[pos2]) {
|
||||
return dpTable[pos1][pos2] =
|
||||
wildcard_matching(s, p, pos1 + 1, pos2 + 1);
|
||||
}
|
||||
|
||||
else {
|
||||
// can only single character
|
||||
if (p[pos2] == '?') {
|
||||
return dpTable[pos1][pos2] =
|
||||
wildcard_matching(s, p, pos1 + 1, pos2 + 1);
|
||||
}
|
||||
// have choice either to match one or more charcters
|
||||
else if (p[pos2] == '*') {
|
||||
return dpTable[pos1][pos2] =
|
||||
wildcard_matching(s, p, pos1, pos2 + 1) ||
|
||||
wildcard_matching(s, p, pos1 + 1, pos2);
|
||||
}
|
||||
// not possible to match
|
||||
else {
|
||||
return dpTable[pos1][pos2] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace wildcard_matching
|
||||
} // namespace backtracking
|
||||
|
||||
/**
|
||||
* @brief Self-test implementations
|
||||
* @returns void
|
||||
*/
|
||||
static void test() {
|
||||
// 1st test
|
||||
std::cout << "1st test ";
|
||||
std::string matching1 = "baaabab";
|
||||
std::string pattern1 = "*****ba*****ab";
|
||||
assert(backtracking::wildcard_matching::wildcard_matching(matching1,
|
||||
pattern1, 0, 0) ==
|
||||
1); // here the pattern matches with given string
|
||||
std::cout << "passed" << std::endl;
|
||||
|
||||
// 2nd test
|
||||
std::cout << "2nd test ";
|
||||
std::string matching2 = "baaabab";
|
||||
std::string pattern2 = "ba*****ab";
|
||||
assert(backtracking::wildcard_matching::wildcard_matching(matching2,
|
||||
pattern2, 0, 0) ==
|
||||
1); // here the pattern matches with given string
|
||||
std::cout << "passed" << std::endl;
|
||||
|
||||
// 3rd test
|
||||
std::cout << "3rd test ";
|
||||
std::string matching3 = "baaabab";
|
||||
std::string pattern3 = "ba*ab";
|
||||
assert(backtracking::wildcard_matching::wildcard_matching(matching3,
|
||||
pattern3, 0, 0) ==
|
||||
1); // here the pattern matches with given string
|
||||
std::cout << "passed" << std::endl;
|
||||
|
||||
// 4th test
|
||||
std::cout << "4th test ";
|
||||
std::string matching4 = "baaabab";
|
||||
std::string pattern4 = "a*ab";
|
||||
assert(backtracking::wildcard_matching::wildcard_matching(matching4,
|
||||
pattern4, 0, 0) ==
|
||||
1); // here the pattern matches with given string
|
||||
std::cout << "passed" << std::endl;
|
||||
|
||||
// 5th test
|
||||
std::cout << "5th test ";
|
||||
std::string matching5 = "baaabab";
|
||||
std::string pattern5 = "aa?ab";
|
||||
assert(backtracking::wildcard_matching::wildcard_matching(matching5,
|
||||
pattern5, 0, 0) ==
|
||||
1); // here the pattern matches with given string
|
||||
std::cout << "passed" << std::endl;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Main function
|
||||
* @returns 0 on exit
|
||||
*/
|
||||
int main() {
|
||||
test(); // run self-test implementations
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user