diff --git a/dynamic_programming/Unbounded_0_1_Knapsack.cpp b/dynamic_programming/Unbounded_0_1_Knapsack.cpp new file mode 100644 index 000000000..96588fe39 --- /dev/null +++ b/dynamic_programming/Unbounded_0_1_Knapsack.cpp @@ -0,0 +1,151 @@ +/** + * @file + * @brief Implementation of the Unbounded 0/1 Knapsack Problem + * + * @details + * The Unbounded 0/1 Knapsack problem allows taking unlimited quantities of each item. + * The goal is to maximize the total value without exceeding the given knapsack capacity. + * Unlike the 0/1 knapsack, where each item can be taken only once, in this variation, + * any item can be picked any number of times as long as the total weight stays within + * the knapsack's capacity. + * + * Given a set of N items, each with a weight and a value, represented by the arrays + * `wt` and `val` respectively, and a knapsack with a weight limit W, the task is to + * fill the knapsack to maximize the total value. + * + * @note weight and value of items is greater than zero + * + * ### Algorithm + * The approach uses dynamic programming to build a solution iteratively. + * A 2D array is used for memoization to store intermediate results, allowing + * the function to avoid redundant calculations. + * + * @author [Sanskruti Yeole](https://github.com/yeolesanskruti) + * @see dynamic_programming/0_1_knapsack.cpp + */ + +#include // Standard input-output stream +#include // Standard library for using dynamic arrays (vectors) +#include // For using assert function to validate test cases +#include // For fixed-width integer types like std::uint16_t + +/** + * @namespace dynamic_programming + * @brief Namespace for dynamic programming algorithms + */ +namespace dynamic_programming { + +/** + * @namespace Knapsack + * @brief Implementation of unbounded 0-1 knapsack problem + */ +namespace unbounded_knapsack { + +/** + * @brief Recursive function to calculate the maximum value obtainable using + * an unbounded knapsack approach. + * + * @param i Current index in the value and weight vectors. + * @param W Remaining capacity of the knapsack. + * @param val Vector of values corresponding to the items. + * @note "val" data type can be changed according to the size of the input. + * @param wt Vector of weights corresponding to the items. + * @note "wt" data type can be changed according to the size of the input. + * @param dp 2D vector for memoization to avoid redundant calculations. + * @return The maximum value that can be obtained for the given index and capacity. + */ +std::uint16_t KnapSackFilling(std::uint16_t i, std::uint16_t W, + const std::vector& val, + const std::vector& wt, + std::vector>& dp) { + if (i == 0) { + if (wt[0] <= W) { + return (W / wt[0]) * val[0]; // Take as many of the first item as possible + } else { + return 0; // Can't take the first item + } + } + if (dp[i][W] != -1) return dp[i][W]; // Return result if available + + int nottake = KnapSackFilling(i - 1, W, val, wt, dp); // Value without taking item i + int take = 0; + if (W >= wt[i]) { + take = val[i] + KnapSackFilling(i, W - wt[i], val, wt, dp); // Value taking item i + } + return dp[i][W] = std::max(take, nottake); // Store and return the maximum value +} + +/** + * @brief Wrapper function to initiate the unbounded knapsack calculation. + * + * @param N Number of items. + * @param W Maximum weight capacity of the knapsack. + * @param val Vector of values corresponding to the items. + * @param wt Vector of weights corresponding to the items. + * @return The maximum value that can be obtained for the given capacity. + */ +std::uint16_t unboundedKnapsack(std::uint16_t N, std::uint16_t W, + const std::vector& val, + const std::vector& wt) { + if(N==0)return 0; // Expect 0 since no items + std::vector> dp(N, std::vector(W + 1, -1)); // Initialize memoization table + return KnapSackFilling(N - 1, W, val, wt, dp); // Start the calculation +} + +} // unbounded_knapsack + +} // dynamic_programming + +/** + * @brief self test implementation + * @return void + */ +static void tests() { + // Test Case 1 + std::uint16_t N1 = 4; // Number of items + std::vector wt1 = {1, 3, 4, 5}; // Weights of the items + std::vector val1 = {6, 1, 7, 7}; // Values of the items + std::uint16_t W1 = 8; // Maximum capacity of the knapsack + // Test the function and assert the expected output + assert(unboundedKnapsack(N1, W1, val1, wt1) == 48); + std::cout << "Maximum Knapsack value " << unboundedKnapsack(N1, W1, val1, wt1) << std::endl; + + // Test Case 2 + std::uint16_t N2 = 3; // Number of items + std::vector wt2 = {10, 20, 30}; // Weights of the items + std::vector val2 = {60, 100, 120}; // Values of the items + std::uint16_t W2 = 5; // Maximum capacity of the knapsack + // Test the function and assert the expected output + assert(unboundedKnapsack(N2, W2, val2, wt2) == 0); + std::cout << "Maximum Knapsack value " << unboundedKnapsack(N2, W2, val2, wt2) << std::endl; + + // Test Case 3 + std::uint16_t N3 = 3; // Number of items + std::vector wt3 = {2, 4, 6}; // Weights of the items + std::vector val3 = {5, 11, 13};// Values of the items + std::uint16_t W3 = 27;// Maximum capacity of the knapsack + // Test the function and assert the expected output + assert(unboundedKnapsack(N3, W3, val3, wt3) == 27); + std::cout << "Maximum Knapsack value " << unboundedKnapsack(N3, W3, val3, wt3) << std::endl; + + // Test Case 4 + std::uint16_t N4 = 0; // Number of items + std::vector wt4 = {}; // Weights of the items + std::vector val4 = {}; // Values of the items + std::uint16_t W4 = 10; // Maximum capacity of the knapsack + assert(unboundedKnapsack(N4, W4, val4, wt4) == 0); + std::cout << "Maximum Knapsack value for empty arrays: " << unboundedKnapsack(N4, W4, val4, wt4) << std::endl; + + std::cout << "All test cases passed!" << std::endl; + +} + +/** + * @brief main function + * @return 0 on successful exit + */ +int main() { + tests(); // Run self test implementation + return 0; +} + diff --git a/graph/topological_sort.cpp b/graph/topological_sort.cpp index 5de8ed69e..6ff81b473 100644 --- a/graph/topological_sort.cpp +++ b/graph/topological_sort.cpp @@ -1,50 +1,189 @@ -#include -#include -#include +/** + * @file + * @brief [Topological Sort + * Algorithm](https://en.wikipedia.org/wiki/Topological_sorting) + * @details + * Topological sorting of a directed graph is a linear ordering or its vertices + * such that for every directed edge (u,v) from vertex u to vertex v, u comes + * before v in the oredering. + * + * A topological sort is possible only in a directed acyclic graph (DAG). + * This file contains code of finding topological sort using Kahn's Algorithm + * which involves using Depth First Search technique + */ -int number_of_vertices, - number_of_edges; // For number of Vertices (V) and number of edges (E) -std::vector> graph; -std::vector visited; -std::vector topological_order; +#include // For std::reverse +#include // For assert +#include // For IO operations +#include // For std::stack +#include // For std::invalid_argument +#include // For std::vector -void dfs(int v) { - visited[v] = true; - for (int u : graph[v]) { - if (!visited[u]) { - dfs(u); +/** + * @namespace graph + * @brief Graph algorithms + */ +namespace graph { + +/** + * @namespace topological_sort + * @brief Topological Sort Algorithm + */ +namespace topological_sort { +/** + * @class Graph + * @brief Class that represents a directed graph and provides methods for + * manipulating the graph + */ +class Graph { + private: + int n; // Number of nodes + std::vector> adj; // Adjacency list representation + + public: + /** + * @brief Constructor for the Graph class + * @param nodes Number of nodes in the graph + */ + Graph(int nodes) : n(nodes), adj(nodes) {} + + /** + * @brief Function that adds an edge between two nodes or vertices of graph + * @param u Start node of the edge + * @param v End node of the edge + */ + void addEdge(int u, int v) { adj[u].push_back(v); } + + /** + * @brief Get the adjacency list of the graph + * @returns A reference to the adjacency list + */ + const std::vector>& getAdjacencyList() const { + return adj; + } + + /** + * @brief Get the number of nodes in the graph + * @returns The number of nodes + */ + int getNumNodes() const { return n; } +}; + +/** + * @brief Function to perform Depth First Search on the graph + * @param v Starting vertex for depth-first search + * @param visited Array representing whether each node has been visited + * @param graph Adjacency list of the graph + * @param s Stack containing the vertices for topological sorting + */ +void dfs(int v, std::vector& visited, + const std::vector>& graph, std::stack& s) { + visited[v] = 1; + for (int neighbour : graph[v]) { + if (!visited[neighbour]) { + dfs(neighbour, visited, graph, s); } } - topological_order.push_back(v); + s.push(v); } -void topological_sort() { - visited.assign(number_of_vertices, false); - topological_order.clear(); - for (int i = 0; i < number_of_vertices; ++i) { +/** + * @brief Function to get the topological sort of the graph + * @param g Graph object + * @returns A vector containing the topological order of nodes + */ +std::vector topologicalSort(const Graph& g) { + int n = g.getNumNodes(); + const auto& adj = g.getAdjacencyList(); + std::vector visited(n, 0); + std::stack s; + + for (int i = 0; i < n; i++) { if (!visited[i]) { - dfs(i); + dfs(i, visited, adj, s); } } - reverse(topological_order.begin(), topological_order.end()); -} -int main() { - std::cout - << "Enter the number of vertices and the number of directed edges\n"; - std::cin >> number_of_vertices >> number_of_edges; - int x = 0, y = 0; - graph.resize(number_of_vertices, std::vector()); - for (int i = 0; i < number_of_edges; ++i) { - std::cin >> x >> y; - x--, y--; // to convert 1-indexed to 0-indexed - graph[x].push_back(y); + + std::vector ans; + while (!s.empty()) { + int elem = s.top(); + s.pop(); + ans.push_back(elem); } - topological_sort(); - std::cout << "Topological Order : \n"; - for (int v : topological_order) { - std::cout << v + 1 - << ' '; // converting zero based indexing back to one based. + + if (ans.size() < n) { // Cycle detected + throw std::invalid_argument("cycle detected in graph"); + } + return ans; +} +} // namespace topological_sort +} // namespace graph + +/** + * @brief Self-test implementation + * @returns void + */ +static void test() { + // Test 1 + std::cout << "Testing for graph 1\n"; + int n_1 = 6; + graph::topological_sort::Graph graph1(n_1); + graph1.addEdge(4, 0); + graph1.addEdge(5, 0); + graph1.addEdge(5, 2); + graph1.addEdge(2, 3); + graph1.addEdge(3, 1); + graph1.addEdge(4, 1); + std::vector ans_1 = graph::topological_sort::topologicalSort(graph1); + std::vector expected_1 = {5, 4, 2, 3, 1, 0}; + std::cout << "Topological Sorting Order: "; + for (int i : ans_1) { + std::cout << i << " "; } std::cout << '\n'; + assert(ans_1 == expected_1); + std::cout << "Test Passed\n\n"; + + // Test 2 + std::cout << "Testing for graph 2\n"; + int n_2 = 5; + graph::topological_sort::Graph graph2(n_2); + graph2.addEdge(0, 1); + graph2.addEdge(0, 2); + graph2.addEdge(1, 2); + graph2.addEdge(2, 3); + graph2.addEdge(1, 3); + graph2.addEdge(2, 4); + std::vector ans_2 = graph::topological_sort::topologicalSort(graph2); + std::vector expected_2 = {0, 1, 2, 4, 3}; + std::cout << "Topological Sorting Order: "; + for (int i : ans_2) { + std::cout << i << " "; + } + std::cout << '\n'; + assert(ans_2 == expected_2); + std::cout << "Test Passed\n\n"; + + // Test 3 - Graph with cycle + std::cout << "Testing for graph 3\n"; + int n_3 = 3; + graph::topological_sort::Graph graph3(n_3); + graph3.addEdge(0, 1); + graph3.addEdge(1, 2); + graph3.addEdge(2, 0); + try { + graph::topological_sort::topologicalSort(graph3); + } catch (std::invalid_argument& err) { + assert(std::string(err.what()) == "cycle detected in graph"); + } + std::cout << "Test Passed\n"; +} + +/** + * @brief Main function + * @returns 0 on exit + */ +int main() { + test(); // run self test implementations return 0; } diff --git a/math/sieve_of_eratosthenes.cpp b/math/sieve_of_eratosthenes.cpp index e011b6c00..e003706d1 100644 --- a/math/sieve_of_eratosthenes.cpp +++ b/math/sieve_of_eratosthenes.cpp @@ -1,6 +1,7 @@ /** * @file - * @brief Get list of prime numbers using Sieve of Eratosthenes + * @brief Prime Numbers using [Sieve of + * Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) * @details * Sieve of Eratosthenes is an algorithm that finds all the primes * between 2 and N. @@ -11,21 +12,39 @@ * @see primes_up_to_billion.cpp prime_numbers.cpp */ -#include -#include -#include +#include /// for assert +#include /// for IO operations +#include /// for std::vector /** - * This is the function that finds the primes and eliminates the multiples. + * @namespace math + * @brief Mathematical algorithms + */ +namespace math { +/** + * @namespace sieve_of_eratosthenes + * @brief Functions for finding Prime Numbers using Sieve of Eratosthenes + */ +namespace sieve_of_eratosthenes { +/** + * @brief Function to sieve out the primes + * @details + * This function finds all the primes between 2 and N using the Sieve of + * Eratosthenes algorithm. It starts by assuming all numbers (except zero and + * one) are prime and then iteratively marks the multiples of each prime as + * non-prime. + * * Contains a common optimization to start eliminating multiples of * a prime p starting from p * p since all of the lower multiples * have been already eliminated. - * @param N number of primes to check - * @return is_prime a vector of `N + 1` booleans identifying if `i`^th number is a prime or not + * @param N number till which primes are to be found + * @return is_prime a vector of `N + 1` booleans identifying if `i`^th number is + * a prime or not */ std::vector sieve(uint32_t N) { - std::vector is_prime(N + 1, true); - is_prime[0] = is_prime[1] = false; + std::vector is_prime(N + 1, true); // Initialize all as prime numbers + is_prime[0] = is_prime[1] = false; // 0 and 1 are not prime numbers + for (uint32_t i = 2; i * i <= N; i++) { if (is_prime[i]) { for (uint32_t j = i * i; j <= N; j += i) { @@ -37,9 +56,10 @@ std::vector sieve(uint32_t N) { } /** - * This function prints out the primes to STDOUT - * @param N number of primes to check - * @param is_prime a vector of `N + 1` booleans identifying if `i`^th number is a prime or not + * @brief Function to print the prime numbers + * @param N number till which primes are to be found + * @param is_prime a vector of `N + 1` booleans identifying if `i`^th number is + * a prime or not */ void print(uint32_t N, const std::vector &is_prime) { for (uint32_t i = 2; i <= N; i++) { @@ -50,23 +70,53 @@ void print(uint32_t N, const std::vector &is_prime) { std::cout << std::endl; } +} // namespace sieve_of_eratosthenes +} // namespace math + /** - * Test implementations + * @brief Self-test implementations + * @return void */ -void tests() { - // 0 1 2 3 4 5 6 7 8 9 10 - std::vector ans{false, false, true, true, false, true, false, true, false, false, false}; - assert(sieve(10) == ans); +static void tests() { + std::vector is_prime_1 = + math::sieve_of_eratosthenes::sieve(static_cast(10)); + std::vector is_prime_2 = + math::sieve_of_eratosthenes::sieve(static_cast(20)); + std::vector is_prime_3 = + math::sieve_of_eratosthenes::sieve(static_cast(100)); + + std::vector expected_1{false, false, true, true, false, true, + false, true, false, false, false}; + assert(is_prime_1 == expected_1); + + std::vector expected_2{false, false, true, true, false, true, + false, true, false, false, false, true, + false, true, false, false, false, true, + false, true, false}; + assert(is_prime_2 == expected_2); + + std::vector expected_3{ + false, false, true, true, false, true, false, true, false, false, + false, true, false, true, false, false, false, true, false, true, + false, false, false, true, false, false, false, false, false, true, + false, true, false, false, false, false, false, true, false, false, + false, true, false, true, false, false, false, true, false, false, + false, false, false, true, false, false, false, false, false, true, + false, true, false, false, false, false, false, true, false, false, + false, true, false, true, false, false, false, false, false, true, + false, false, false, true, false, false, false, false, false, true, + false, false, false, false, false, false, false, true, false, false, + false}; + assert(is_prime_3 == expected_3); + + std::cout << "All tests have passed successfully!\n"; } /** - * Main function + * @brief Main function + * @returns 0 on exit */ int main() { tests(); - - uint32_t N = 100; - std::vector is_prime = sieve(N); - print(N, is_prime); return 0; }