diff --git a/DIRECTORY.md b/DIRECTORY.md index 3a0b61323..7f073a5ad 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -20,6 +20,7 @@ * [Find Non Repeating Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/bit_manipulation/find_non_repeating_number.cpp) * [Hamming Distance](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/bit_manipulation/hamming_distance.cpp) * [Set Kth Bit](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/bit_manipulation/set_kth_bit.cpp) + * [Travelling Salesman Using Bit Manipulation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/bit_manipulation/travelling_salesman_using_bit_manipulation.cpp) ## Ciphers * [A1Z26 Cipher](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/ciphers/a1z26_cipher.cpp) @@ -56,7 +57,8 @@ * [Linkedlist Implentation Usingarray](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/data_structures/linkedlist_implentation_usingarray.cpp) * [List Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/data_structures/list_array.cpp) * [Morrisinorder](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/data_structures/morrisinorder.cpp) - * [Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/data_structures/queue.h) + * [Node](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/data_structures/node.hpp) + * [Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/data_structures/queue.hpp) * [Queue Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/data_structures/queue_using_array.cpp) * [Queue Using Array2](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/data_structures/queue_using_array2.cpp) * [Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/data_structures/queue_using_linked_list.cpp) @@ -81,6 +83,7 @@ ## Divide And Conquer * [Karatsuba Algorithm For Fast Multiplication](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/divide_and_conquer/karatsuba_algorithm_for_fast_multiplication.cpp) + * [Strassen Matrix Multiplication](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/divide_and_conquer/strassen_matrix_multiplication.cpp) ## Dynamic Programming * [0 1 Knapsack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/dynamic_programming/0_1_knapsack.cpp) @@ -109,6 +112,7 @@ * [Partition Problem](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/dynamic_programming/partition_problem.cpp) * [Searching Of Element In Dynamic Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/dynamic_programming/searching_of_element_in_dynamic_array.cpp) * [Shortest Common Supersequence](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/dynamic_programming/shortest_common_supersequence.cpp) + * [Subset Sum](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/dynamic_programming/subset_sum.cpp) * [Tree Height](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/dynamic_programming/tree_height.cpp) * [Word Break](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/dynamic_programming/word_break.cpp) @@ -145,6 +149,7 @@ * [Spirograph](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/graphics/spirograph.cpp) ## Greedy Algorithms + * [Boruvkas Minimum Spanning Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/greedy_algorithms/boruvkas_minimum_spanning_tree.cpp) * [Dijkstra](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/greedy_algorithms/dijkstra.cpp) * [Huffman](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/greedy_algorithms/huffman.cpp) * [Jumpgame](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/greedy_algorithms/jumpgame.cpp) @@ -170,6 +175,7 @@ * [Vector Ops](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/machine_learning/vector_ops.hpp) ## Math + * [Aliquot Sum](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/math/aliquot_sum.cpp) * [Approximate Pi](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/math/approximate_pi.cpp) * [Area](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/math/area.cpp) * [Armstrong Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/math/armstrong_number.cpp) diff --git a/bit_manipulation/travelling_salesman_using_bit_manipulation.cpp b/bit_manipulation/travelling_salesman_using_bit_manipulation.cpp new file mode 100644 index 000000000..31243ed29 --- /dev/null +++ b/bit_manipulation/travelling_salesman_using_bit_manipulation.cpp @@ -0,0 +1,141 @@ +/** + * @file + * @brief Implementation to + * [Travelling Salesman problem using bit-masking] + * (https://www.geeksforgeeks.org/travelling-salesman-problem-set-1/) + * + * @details + * Given the distance/cost(as and adjacency matrix) between each city/node to + * the other city/node , the problem is to find the shortest possible route that + * visits every city exactly once and returns to the starting point or we can + * say the minimum cost of whole tour. + * + * Explanation: + * INPUT -> You are given with a adjacency matrix A = {} which contains the + * distance between two cities/node. + * + * OUTPUT -> Minimum cost of whole tour from starting point + * + * Worst Case Time Complexity: O(n^2 * 2^n) + * Space complexity: O(n) + * @author [Utkarsh Yadav](https://github.com/Rytnix) + */ +#include /// for std::min +#include /// for assert +#include /// for IO operations +#include /// for limits of integral types +#include /// for std::vector + +/** + * @namespace bit_manipulation + * @brief Bit manipulation algorithms + */ +namespace bit_manipulation { +/** + * @namespace travellingSalesman_bitmanipulation + * @brief Functions for the [Travelling Salesman + * Bitmask](https://www.geeksforgeeks.org/travelling-salesman-problem-set-1/) + * implementation + */ +namespace travelling_salesman_using_bit_manipulation { +/** + * @brief The function implements travellingSalesman using bitmanipulation + * @param dist is the cost to reach between two cities/nodes + * @param setOfCitites represents the city in bit form.\ + * @param city is taken to track the current city movement. + * @param n is the no of citys . + * @param dp vector is used to keep a record of state to avoid the + * recomputation. + * @returns minimum cost of traversing whole nodes/cities from starting point + * back to starting point + */ +std::uint64_t travelling_salesman_using_bit_manipulation( + std::vector> + dist, // dist is the adjacency matrix containing the distance. + // setOfCities as a bit represent the cities/nodes. Ex: if + // setOfCities = 2 => 0010(in binary) means representing the + // city/node B if city/nodes are represented as D->C->B->A. + std::uint64_t setOfCities, + std::uint64_t city, // city is taken to track our current city/node + // movement,where we are currently. + std::uint64_t n, // n is the no of cities we have. + std::vector> + &dp) // dp is taken to memorize the state to avoid recomputition +{ + // base case; + if (setOfCities == (1 << n) - 1) { // we have covered all the cities + return dist[city][0]; // return the cost from the current city to the + // original city. + } + + if (dp[setOfCities][city] != -1) { + return dp[setOfCities][city]; + } + // otherwise try all possible options + uint64_t ans = 2147483647; + for (int choice = 0; choice < n; choice++) { + // check if the city is visited or not. + if ((setOfCities & (1 << choice)) == + 0) { // this means that this perticular city is not visited. + std::uint64_t subProb = + dist[city][choice] + + travelling_salesman_using_bit_manipulation( + dist, setOfCities | (1 << choice), choice, n, dp); + // Here we are doing a recursive call to tsp with the updated set of + // city/node and choice which tells that where we are currently. + ans = std::min(ans, subProb); + } + } + dp[setOfCities][city] = ans; + return ans; +} +} // namespace travelling_salesman_using_bit_manipulation +} // namespace bit_manipulation + +/** + * @brief Self-test implementations + * @returns void + */ +static void test() { + // 1st test-case + std::vector> dist = { + {0, 20, 42, 35}, {20, 0, 30, 34}, {42, 30, 0, 12}, {35, 34, 12, 0}}; + uint32_t V = dist.size(); + std::vector> dp(1 << V, std::vector(V, -1)); + assert(bit_manipulation::travelling_salesman_using_bit_manipulation:: + travelling_salesman_using_bit_manipulation(dist, 1, 0, V, dp) == + 97); + std::cout << "1st test-case: passed!" + << "\n"; + + // 2nd test-case + dist = {{0, 5, 10, 15}, {5, 0, 20, 30}, {10, 20, 0, 35}, {15, 30, 35, 0}}; + V = dist.size(); + std::vector> dp1(1 << V, + std::vector(V, -1)); + assert(bit_manipulation::travelling_salesman_using_bit_manipulation:: + travelling_salesman_using_bit_manipulation(dist, 1, 0, V, dp1) == + 75); + std::cout << "2nd test-case: passed!" + << "\n"; + // 3rd test-case + dist = {{0, 10, 15, 20}, {10, 0, 35, 25}, {15, 35, 0, 30}, {20, 25, 30, 0}}; + V = dist.size(); + std::vector> dp2(1 << V, + std::vector(V, -1)); + assert(bit_manipulation::travelling_salesman_using_bit_manipulation:: + travelling_salesman_using_bit_manipulation(dist, 1, 0, V, dp2) == + 80); + + std::cout << "3rd test-case: passed!" + << "\n"; +} + +/** + * @brief Main function + * @returns 0 on exit + */ +int main() { + test(); // run self-test implementations + return 0; +} diff --git a/data_structures/node.hpp b/data_structures/node.hpp new file mode 100644 index 000000000..ff920299b --- /dev/null +++ b/data_structures/node.hpp @@ -0,0 +1,46 @@ +/** + * @file + * @brief Provides Node class and related utilities + **/ +#ifndef DATA_STRUCTURES_NODE_HPP_ +#define DATA_STRUCTURES_NODE_HPP_ + +#include /// for std::cout +#include /// for std::shared_ptr +#include /// for std::vector + +/** Definition of the node as a linked-list + * \tparam ValueType type of data nodes of the linked list should contain + */ +template +struct Node { + using value_type = ValueType; + ValueType data = {}; + std::shared_ptr> next = {}; +}; + +template +void traverse(const Node* const inNode, const Action& action) { + if (inNode) { + action(*inNode); + traverse(inNode->next.get(), action); + } +} + +template +void display_all(const Node* const inNode) { + traverse(inNode, + [](const Node& curNode) { std::cout << curNode.data << " "; }); +} + +template +std::vector push_all_to_vector( + const Node* const inNode, const std::size_t expected_size = 0) { + std::vector res; + res.reserve(expected_size); + traverse(inNode, + [&res](const Node& curNode) { res.push_back(curNode.data); }); + return res; +} + +#endif // DATA_STRUCTURES_NODE_HPP_ diff --git a/data_structures/queue.h b/data_structures/queue.h deleted file mode 100644 index 3cb551741..000000000 --- a/data_structures/queue.h +++ /dev/null @@ -1,88 +0,0 @@ -/* This class specifies the basic operation on a queue as a linked list */ -#ifndef DATA_STRUCTURES_QUEUE_H_ -#define DATA_STRUCTURES_QUEUE_H_ - -#include -#include - -/** Definition of the node */ -template -struct node { - Kind data; - node *next; -}; - -/** Definition of the queue class */ -template -class queue { - public: - /** Show queue */ - void display() { - node *current = queueFront; - std::cout << "Front --> "; - while (current != NULL) { - std::cout << current->data << " "; - current = current->next; - } - std::cout << std::endl; - std::cout << "Size of queue: " << size << std::endl; - } - - /** Default constructor*/ - queue() { - queueFront = NULL; - queueRear = NULL; - size = 0; - } - - /** Destructor */ - ~queue() {} - - /** Determine whether the queue is empty */ - bool isEmptyQueue() { return (queueFront == NULL); } - - /** Add new item to the queue */ - void enQueue(Kind item) { - node *newNode; - newNode = new node; - newNode->data = item; - newNode->next = NULL; - if (queueFront == NULL) { - queueFront = newNode; - queueRear = newNode; - } else { - queueRear->next = newNode; - queueRear = queueRear->next; - } - size++; - } - - /** Return the first element of the queue */ - Kind front() { - assert(queueFront != NULL); - return queueFront->data; - } - - /** Remove the top element of the queue */ - void deQueue() { - node *temp; - if (!isEmptyQueue()) { - temp = queueFront; - queueFront = queueFront->next; - delete temp; - size--; - } else { - std::cout << "Queue is empty !" << std::endl; - } - } - - /** Clear queue */ - void clear() { queueFront = NULL; } - - private: - node *queueFront; /**< Pointer to the front of the queue */ - node *queueRear; /**< Pointer to the rear of the queue */ - int size; -}; - -#endif // DATA_STRUCTURES_QUEUE_H_ diff --git a/data_structures/queue.hpp b/data_structures/queue.hpp new file mode 100644 index 000000000..cd358a6ef --- /dev/null +++ b/data_structures/queue.hpp @@ -0,0 +1,104 @@ +/* This class specifies the basic operation on a queue as a linked list */ +#ifndef DATA_STRUCTURES_QUEUE_HPP_ +#define DATA_STRUCTURES_QUEUE_HPP_ + +#include "node.hpp" + +/** Definition of the queue class */ +template +class queue { + using node_type = Node; + + public: + using value_type = ValueType; + /** + * @brief prints the queue into the std::cout + */ + void display() const { + std::cout << "Front --> "; + display_all(this->queueFront.get()); + std::cout << '\n'; + std::cout << "Size of queue: " << size << '\n'; + } + + /** + * @brief converts the queue into the std::vector + * @return std::vector containning all of the elements of the queue in the + * same order + */ + std::vector toVector() const { + return push_all_to_vector(this->queueFront.get(), this->size); + } + + private: + /** + * @brief throws an exception if queue is empty + * @exception std::invalid_argument if queue is empty + */ + void ensureNotEmpty() const { + if (isEmptyQueue()) { + throw std::invalid_argument("Queue is empty."); + } + } + + public: + /** + * @brief checks if the queue has no elements + * @return true if the queue is empty, false otherwise + */ + bool isEmptyQueue() const { return (queueFront == nullptr); } + + /** + * @brief inserts a new item into the queue + */ + void enQueue(const value_type& item) { + auto newNode = std::make_shared(); + newNode->data = item; + newNode->next = nullptr; + if (isEmptyQueue()) { + queueFront = newNode; + queueRear = newNode; + } else { + queueRear->next = newNode; + queueRear = queueRear->next; + } + ++size; + } + + /** + * @return the first element of the queue + * @exception std::invalid_argument if queue is empty + */ + value_type front() const { + ensureNotEmpty(); + return queueFront->data; + } + + /** + * @brief removes the first element from the queue + * @exception std::invalid_argument if queue is empty + */ + void deQueue() { + ensureNotEmpty(); + queueFront = queueFront->next; + --size; + } + + /** + * @brief removes all elements from the queue + */ + void clear() { + queueFront = nullptr; + queueRear = nullptr; + size = 0; + } + + private: + std::shared_ptr queueFront = + {}; /**< Pointer to the front of the queue */ + std::shared_ptr queueRear = + {}; /**< Pointer to the rear of the queue */ + std::size_t size = 0; +}; + +#endif // DATA_STRUCTURES_QUEUE_HPP_ diff --git a/data_structures/stack.hpp b/data_structures/stack.hpp index 419a07c67..84336453a 100644 --- a/data_structures/stack.hpp +++ b/data_structures/stack.hpp @@ -7,28 +7,9 @@ #ifndef DATA_STRUCTURES_STACK_HPP_ #define DATA_STRUCTURES_STACK_HPP_ -#include /// for IO operations -#include /// for std::shared_ptr #include /// for std::invalid_argument -#include /// for std::vector -/** Definition of the node as a linked-list - * \tparam ValueType type of data nodes of the linked list should contain - */ -template -struct node { - ValueType data = {}; ///< data at current node - std::shared_ptr> next = - {}; ///< pointer to the next ::node instance -}; - -template -void traverse(const Node* const inNode, const Action& action) { - if (inNode) { - action(*inNode); - traverse(inNode->next.get(), action); - } -} +#include "node.hpp" /// for Node /** Definition of the stack class * \tparam value_type type of data nodes of the linked list in the stack should @@ -42,20 +23,13 @@ class stack { /** Show stack */ void display() const { std::cout << "Top --> "; - traverse(stackTop.get(), [](const node& inNode) { - std::cout << inNode.data << " "; - }); - std::cout << std::endl; + display_all(this->stackTop.get()); + std::cout << '\n'; std::cout << "Size of stack: " << size << std::endl; } std::vector toVector() const { - std::vector res; - res.reserve(this->size); - traverse(stackTop.get(), [&res](const node& inNode) { - res.push_back(inNode.data); - }); - return res; + return push_all_to_vector(this->stackTop.get(), this->size); } private: @@ -71,7 +45,7 @@ class stack { /** Add new item to the stack */ void push(const value_type& item) { - auto newNode = std::make_shared>(); + auto newNode = std::make_shared>(); newNode->data = item; newNode->next = stackTop; stackTop = newNode; @@ -98,7 +72,7 @@ class stack { } private: - std::shared_ptr> stackTop = + std::shared_ptr> stackTop = {}; /**< Pointer to the stack */ std::size_t size = 0; ///< size of stack }; diff --git a/data_structures/test_queue.cpp b/data_structures/test_queue.cpp index 387ccf2f7..d0fa3502e 100644 --- a/data_structures/test_queue.cpp +++ b/data_structures/test_queue.cpp @@ -1,41 +1,93 @@ -#include -#include +#include /// for assert +#include /// for std::cout -#include "./queue.h" +#include "./queue.hpp" + +template +void testConstructedQueueIsEmpty() { + const queue curQueue; + assert(curQueue.isEmptyQueue()); +} + +void testEnQueue() { + queue curQueue; + curQueue.enQueue(10); + assert(curQueue.toVector() == std::vector({10})); + curQueue.enQueue(20); + assert(curQueue.toVector() == std::vector({10, 20})); + curQueue.enQueue(30); + curQueue.enQueue(40); + assert(curQueue.toVector() == std::vector({10, 20, 30, 40})); +} + +void testDeQueue() { + queue curQueue; + curQueue.enQueue(10); + curQueue.enQueue(20); + curQueue.enQueue(30); + + curQueue.deQueue(); + assert(curQueue.toVector() == std::vector({20, 30})); + + curQueue.deQueue(); + assert(curQueue.toVector() == std::vector({30})); + + curQueue.deQueue(); + assert(curQueue.isEmptyQueue()); +} + +void testFront() { + queue curQueue; + curQueue.enQueue(10); + assert(curQueue.front() == 10); + curQueue.enQueue(20); + assert(curQueue.front() == 10); +} + +void testQueueAfterClearIsEmpty() { + queue curQueue; + curQueue.enQueue(10); + curQueue.enQueue(20); + curQueue.enQueue(30); + curQueue.clear(); + assert(curQueue.isEmptyQueue()); +} + +void testFrontThrowsAnInvalidArgumentWhenQueueEmpty() { + const queue curQueue; + bool wasException = false; + try { + curQueue.front(); + } catch (const std::invalid_argument&) { + wasException = true; + } + assert(wasException); +} + +void testDeQueueThrowsAnInvalidArgumentWhenQueueEmpty() { + queue curQueue; + bool wasException = false; + try { + curQueue.deQueue(); + } catch (const std::invalid_argument&) { + wasException = true; + } + assert(wasException); +} int main() { - queue q; - std::cout << "---------------------- Test construct ----------------------" - << std::endl; - q.display(); - std::cout - << "---------------------- Test isEmptyQueue ----------------------" - << std::endl; - if (q.isEmptyQueue()) - std::cout << "PASS" << std::endl; - else - std::cout << "FAIL" << std::endl; - std::cout << "---------------------- Test enQueue ----------------------" - << std::endl; - std::cout << "After Hai, Jeff, Tom, Jkingston go into queue: " << std::endl; - q.enQueue("Hai"); - q.enQueue("Jeff"); - q.enQueue("Tom"); - q.enQueue("Jkingston"); - q.display(); - std::cout << "---------------------- Test front ----------------------" - << std::endl; - std::string value = q.front(); - if (value == "Hai") - std::cout << "PASS" << std::endl; - else - std::cout << "FAIL" << std::endl; - std::cout << "---------------------- Test deQueue ----------------------" - << std::endl; - q.display(); - q.deQueue(); - q.deQueue(); - std::cout << "After Hai, Jeff left the queue: " << std::endl; - q.display(); + testConstructedQueueIsEmpty(); + testConstructedQueueIsEmpty(); + testConstructedQueueIsEmpty>(); + + testEnQueue(); + testDeQueue(); + + testQueueAfterClearIsEmpty(); + + testFrontThrowsAnInvalidArgumentWhenQueueEmpty(); + testDeQueueThrowsAnInvalidArgumentWhenQueueEmpty(); + + std::cout << "All tests pass!\n"; return 0; } diff --git a/data_structures/test_stack.cpp b/data_structures/test_stack.cpp index dfff0b50e..81039e796 100644 --- a/data_structures/test_stack.cpp +++ b/data_structures/test_stack.cpp @@ -157,7 +157,7 @@ void testAssign() { assert(stackB.toVector() == otherExpectedDataB); } -void testTopThrowsAnvalidArgumentWhenStackEmpty() { +void testTopThrowsAnInvalidArgumentWhenStackEmpty() { const stack curStack; bool wasException = false; try { @@ -168,7 +168,7 @@ void testTopThrowsAnvalidArgumentWhenStackEmpty() { assert(wasException); } -void testPopThrowsAnvalidArgumentWhenStackEmpty() { +void testPopThrowsAnInvalidArgumentWhenStackEmpty() { stack curStack; bool wasException = false; try { @@ -195,8 +195,8 @@ int main() { testAssign(); - testTopThrowsAnvalidArgumentWhenStackEmpty(); - testPopThrowsAnvalidArgumentWhenStackEmpty(); + testTopThrowsAnInvalidArgumentWhenStackEmpty(); + testPopThrowsAnInvalidArgumentWhenStackEmpty(); std::cout << "All tests pass!\n"; return 0; diff --git a/divide_and_conquer/strassen_matrix_multiplication.cpp b/divide_and_conquer/strassen_matrix_multiplication.cpp new file mode 100644 index 000000000..47498c966 --- /dev/null +++ b/divide_and_conquer/strassen_matrix_multiplication.cpp @@ -0,0 +1,471 @@ +/** + * @brief [Strassen's + * algorithm](https://en.wikipedia.org/wiki/Strassen_algorithm) is one of the + * methods for multiplying two matrices. It is one of the faster algorithms for + * larger matrices than naive multiplication method. + * + * It involves dividing each matrices into 4 blocks, given they are evenly + * divisible, and are combined with new defined matrices involving 7 matrix + * multiplications instead of eight, yielding O(n^2.8073) complexity. + * + * @author [AshishYUO](https://github.com/AshishYUO) + */ +#include /// For assert operation +#include /// For std::chrono; time measurement +#include /// For I/O operations +#include /// For std::tuple +#include /// For creating dynamic arrays + +/** + * @namespace divide_and_conquer + * @brief Divide and Conquer algorithms + */ +namespace divide_and_conquer { + +/** + * @namespace strassens_multiplication + * @brief Namespace for performing strassen's multiplication + */ +namespace strassens_multiplication { + +/// Complement of 0 is a max integer. +constexpr size_t MAX_SIZE = ~0ULL; +/** + * @brief Matrix class. + */ +template ::value || std::is_floating_point::value, + bool>::type> +class Matrix { + std::vector> _mat; + + public: + /** + * @brief Constructor + * @tparam Integer ensuring integers are being evaluated and not other + * data types. + * @param size denoting the size of Matrix as size x size + */ + template ::value, Integer>::type> + explicit Matrix(const Integer size) { + for (size_t i = 0; i < size; ++i) { + _mat.emplace_back(std::vector(size, 0)); + } + } + + /** + * @brief Constructor + * @tparam Integer ensuring integers are being evaluated and not other + * data types. + * @param rows denoting the total rows of Matrix + * @param cols denoting the total elements in each row of Matrix + */ + template ::value, Integer>::type> + Matrix(const Integer rows, const Integer cols) { + for (size_t i = 0; i < rows; ++i) { + _mat.emplace_back(std::vector(cols, 0)); + } + } + + /** + * @brief Get the matrix shape + * @returns pair of integer denoting total rows and columns + */ + inline std::pair size() const { + return {_mat.size(), _mat[0].size()}; + } + + /** + * @brief returns the address of the element at ith place + * (here ith row of the matrix) + * @tparam Integer any valid integer + * @param index index which is requested + * @returns the address of the element (here ith row or array) + */ + template ::value, Integer>::type> + inline std::vector &operator[](const Integer index) { + return _mat[index]; + } + + /** + * @brief Creates a new matrix and returns a part of it. + * @param row_start start of the row + * @param row_end end of the row + * @param col_start start of the col + * @param col_end end of the column + * @returns A slice of (row_end - row_start) x (col_end - col_start) size of + * array starting from row_start row and col_start column + */ + Matrix slice(const size_t row_start, const size_t row_end = MAX_SIZE, + const size_t col_start = MAX_SIZE, + const size_t col_end = MAX_SIZE) const { + const size_t h_size = + (row_end != MAX_SIZE ? row_end : _mat.size()) - row_start; + const size_t v_size = (col_end != MAX_SIZE ? col_end : _mat[0].size()) - + (col_start != MAX_SIZE ? col_start : 0); + Matrix result = Matrix(h_size, v_size); + + const size_t v_start = (col_start != MAX_SIZE ? col_start : 0); + for (size_t i = 0; i < h_size; ++i) { + for (size_t j = 0; j < v_size; ++j) { + result._mat[i][j] = _mat[i + row_start][j + v_start]; + } + } + return result; + } + + /** + * @brief Horizontally stack the matrix (one after the other) + * @tparam Number any type of number + * @param other the other matrix: note that this array is not modified + * @returns void, but modifies the current array + */ + template ::value || + std::is_floating_point::value, + Number>::type> + void h_stack(const Matrix &other) { + assert(_mat.size() == other._mat.size()); + for (size_t i = 0; i < other._mat.size(); ++i) { + for (size_t j = 0; j < other._mat[i].size(); ++j) { + _mat[i].push_back(other._mat[i][j]); + } + } + } + + /** + * @brief Horizontally stack the matrix (current matrix above the other) + * @tparam Number any type of number (Integer or floating point) + * @param other the other matrix: note that this array is not modified + * @returns void, but modifies the current array + */ + template ::value || + std::is_floating_point::value, + Number>::type> + void v_stack(const Matrix &other) { + assert(_mat[0].size() == other._mat[0].size()); + for (size_t i = 0; i < other._mat.size(); ++i) { + _mat.emplace_back(std::vector(other._mat[i].size())); + for (size_t j = 0; j < other._mat[i].size(); ++j) { + _mat.back()[j] = other._mat[i][j]; + } + } + } + + /** + * @brief Add two matrices and returns a new matrix + * @tparam Number any real value to add + * @param other Other matrix to add to this + * @returns new matrix + */ + template ::value || + std::is_floating_point::value, + bool>::type> + Matrix operator+(const Matrix &other) const { + assert(this->size() == other.size()); + Matrix C = Matrix(_mat.size(), _mat[0].size()); + for (size_t i = 0; i < _mat.size(); ++i) { + for (size_t j = 0; j < _mat[i].size(); ++j) { + C._mat[i][j] = _mat[i][j] + other._mat[i][j]; + } + } + return C; + } + + /** + * @brief Add another matrices to current matrix + * @tparam Number any real value to add + * @param other Other matrix to add to this + * @returns reference of current matrix + */ + template ::value || + std::is_floating_point::value, + bool>::type> + Matrix &operator+=(const Matrix &other) const { + assert(this->size() == other.size()); + for (size_t i = 0; i < _mat.size(); ++i) { + for (size_t j = 0; j < _mat[i].size(); ++j) { + _mat[i][j] += other._mat[i][j]; + } + } + return this; + } + + /** + * @brief Subtract two matrices and returns a new matrix + * @tparam Number any real value to multiply + * @param other Other matrix to subtract to this + * @returns new matrix + */ + template ::value || + std::is_floating_point::value, + bool>::type> + Matrix operator-(const Matrix &other) const { + assert(this->size() == other.size()); + Matrix C = Matrix(_mat.size(), _mat[0].size()); + for (size_t i = 0; i < _mat.size(); ++i) { + for (size_t j = 0; j < _mat[i].size(); ++j) { + C._mat[i][j] = _mat[i][j] - other._mat[i][j]; + } + } + return C; + } + + /** + * @brief Subtract another matrices to current matrix + * @tparam Number any real value to Subtract + * @param other Other matrix to Subtract to this + * @returns reference of current matrix + */ + template ::value || + std::is_floating_point::value, + bool>::type> + Matrix &operator-=(const Matrix &other) const { + assert(this->size() == other.size()); + for (size_t i = 0; i < _mat.size(); ++i) { + for (size_t j = 0; j < _mat[i].size(); ++j) { + _mat[i][j] -= other._mat[i][j]; + } + } + return this; + } + + /** + * @brief Multiply two matrices and returns a new matrix + * @tparam Number any real value to multiply + * @param other Other matrix to multiply to this + * @returns new matrix + */ + template ::value || + std::is_floating_point::value, + bool>::type> + inline Matrix operator*(const Matrix &other) const { + assert(_mat[0].size() == other._mat.size()); + auto size = this->size(); + const size_t row = size.first, col = size.second; + // Main condition for applying strassen's method: + // 1: matrix should be a square matrix + // 2: matrix should be of even size (mat.size() % 2 == 0) + return (row == col && (row & 1) == 0) + ? this->strassens_multiplication(other) + : this->naive_multiplication(other); + } + + /** + * @brief Multiply matrix with a number and returns a new matrix + * @tparam Number any real value to multiply + * @param other Other real number to multiply to current matrix + * @returns new matrix + */ + template ::value || + std::is_floating_point::value, + bool>::type> + inline Matrix operator*(const Number other) const { + Matrix C = Matrix(_mat.size(), _mat[0].size()); + for (size_t i = 0; i < _mat.size(); ++i) { + for (size_t j = 0; j < _mat[i].size(); ++j) { + C._mat[i][j] = _mat[i][j] * other; + } + } + return C; + } + + /** + * @brief Multiply a number to current matrix + * @tparam Number any real value to multiply + * @param other Other matrix to multiply to this + * @returns reference of current matrix + */ + template ::value || + std::is_floating_point::value, + bool>::type> + Matrix &operator*=(const Number other) const { + for (size_t i = 0; i < _mat.size(); ++i) { + for (size_t j = 0; j < _mat[i].size(); ++j) { + _mat[i][j] *= other; + } + } + return this; + } + + /** + * @brief Naive multiplication performed on this + * @tparam Number any real value to multiply + * @param other Other matrix to multiply to this + * @returns new matrix + */ + template ::value || + std::is_floating_point::value, + bool>::type> + Matrix naive_multiplication(const Matrix &other) const { + Matrix C = Matrix(_mat.size(), other._mat[0].size()); + + for (size_t i = 0; i < _mat.size(); ++i) { + for (size_t k = 0; k < _mat[0].size(); ++k) { + for (size_t j = 0; j < other._mat[0].size(); ++j) { + C._mat[i][j] += _mat[i][k] * other._mat[k][j]; + } + } + } + return C; + } + + /** + * @brief Strassens method of multiplying two matrices + * References: https://en.wikipedia.org/wiki/Strassen_algorithm + * @tparam Number any real value to multiply + * @param other Other matrix to multiply to this + * @returns new matrix + */ + template ::value || + std::is_floating_point::value, + bool>::type> + Matrix strassens_multiplication(const Matrix &other) const { + const size_t size = _mat.size(); + // Base case: when a matrix is small enough for faster naive + // multiplication, or the matrix is of odd size, then go with the naive + // multiplication route; + // else; go with the strassen's method. + if (size <= 64ULL || (size & 1ULL)) { + return this->naive_multiplication(other); + } else { + const Matrix + A = this->slice(0ULL, size >> 1, 0ULL, size >> 1), + B = this->slice(0ULL, size >> 1, size >> 1, size), + C = this->slice(size >> 1, size, 0ULL, size >> 1), + D = this->slice(size >> 1, size, size >> 1, size), + E = other.slice(0ULL, size >> 1, 0ULL, size >> 1), + F = other.slice(0ULL, size >> 1, size >> 1, size), + G = other.slice(size >> 1, size, 0ULL, size >> 1), + H = other.slice(size >> 1, size, size >> 1, size); + + Matrix P1 = A.strassens_multiplication(F - H); + Matrix P2 = (A + B).strassens_multiplication(H); + Matrix P3 = (C + D).strassens_multiplication(E); + Matrix P4 = D.strassens_multiplication(G - E); + Matrix P5 = (A + D).strassens_multiplication(E + H); + Matrix P6 = (B - D).strassens_multiplication(G + H); + Matrix P7 = (A - C).strassens_multiplication(E + F); + + // Building final matrix C11 would be + // [ | ] + // [ C11 | C12 ] + // C = [ ____ | ____ ] + // [ | ] + // [ C21 | C22 ] + // [ | ] + + Matrix C11 = P5 + P4 - P2 + P6; + Matrix C12 = P1 + P2; + Matrix C21 = P3 + P4; + Matrix C22 = P1 + P5 - P3 - P7; + + C21.h_stack(C22); + C11.h_stack(C12); + C11.v_stack(C21); + + return C11; + } + } + + /** + * @brief Compares two matrices if each of them are equal or not + * @param other other matrix to compare + * @returns whether they are equal or not + */ + bool operator==(const Matrix &other) const { + if (_mat.size() != other._mat.size() || + _mat[0].size() != other._mat[0].size()) { + return false; + } + for (size_t i = 0; i < _mat.size(); ++i) { + for (size_t j = 0; j < _mat[i].size(); ++j) { + if (_mat[i][j] != other._mat[i][j]) { + return false; + } + } + } + return true; + } + + friend std::ostream &operator<<(std::ostream &out, const Matrix &mat) { + for (auto &row : mat._mat) { + for (auto &elem : row) { + out << elem << " "; + } + out << "\n"; + } + return out << "\n"; + } +}; + +} // namespace strassens_multiplication + +} // namespace divide_and_conquer + +/** + * @brief Self-test implementations + * @returns void + */ +static void test() { + const size_t s = 512; + auto matrix_demo = + divide_and_conquer::strassens_multiplication::Matrix(s, s); + + for (size_t i = 0; i < s; ++i) { + for (size_t j = 0; j < s; ++j) { + matrix_demo[i][j] = i + j; + } + } + + auto matrix_demo2 = + divide_and_conquer::strassens_multiplication::Matrix(s, s); + for (size_t i = 0; i < s; ++i) { + for (size_t j = 0; j < s; ++j) { + matrix_demo2[i][j] = 2 + i + j; + } + } + + auto start = std::chrono::system_clock::now(); + auto Mat3 = matrix_demo2 * matrix_demo; + auto end = std::chrono::system_clock::now(); + + std::chrono::duration time = (end - start); + std::cout << "Strassen time: " << time.count() << "s" << std::endl; + + start = std::chrono::system_clock::now(); + auto conf = matrix_demo2.naive_multiplication(matrix_demo); + end = std::chrono::system_clock::now(); + + time = end - start; + std::cout << "Normal time: " << time.count() << "s" << std::endl; + + // std::cout << Mat3 << conf << std::endl; + assert(Mat3 == conf); +} + +/** + * @brief main function + * @returns 0 on exit + */ +int main() { + test(); // run self-test implementation + return 0; +} diff --git a/dynamic_programming/subset_sum.cpp b/dynamic_programming/subset_sum.cpp new file mode 100644 index 000000000..ef3953a82 --- /dev/null +++ b/dynamic_programming/subset_sum.cpp @@ -0,0 +1,123 @@ +/** + * @file + * @brief Implements [Sub-set sum problem] + * (https://en.wikipedia.org/wiki/Subset_sum_problem) algorithm, which tells + * whether a subset with target sum exists or not. + * + * @details + * In this problem, we use dynamic programming to find if we can pull out a + * subset from an array whose sum is equal to a given target sum. The overall + * time complexity of the problem is O(n * targetSum) where n is the size of + * the array. For example, array = [1, -10, 2, 31, -6], targetSum = -14. + * Output: true => We can pick subset [-10, 2, -6] with sum as + * (-10) + 2 + (-6) = -14. + * @author [KillerAV](https://github.com/KillerAV) + */ + +#include /// for std::assert +#include /// for IO operations +#include /// for unordered map +#include /// for std::vector + +/** + * @namespace dynamic_programming + * @brief Dynamic Programming algorithms + */ +namespace dynamic_programming { + +/** + * @namespace subset_sum + * @brief Functions for [Sub-set sum problem] + * (https://en.wikipedia.org/wiki/Subset_sum_problem) algorithm + */ +namespace subset_sum { + +/** + * Recursive function using dynamic programming to find if the required sum + * subset exists or not. + * @param arr input array + * @param targetSum the target sum of the subset + * @param dp the map storing the results + * @returns true/false based on if the target sum subset exists or not. + */ +bool subset_sum_recursion(const std::vector &arr, int targetSum, + std::vector> *dp, + int index = 0) { + if (targetSum == 0) { // Found a valid subset with required sum. + return true; + } + if (index == arr.size()) { // End of array + return false; + } + + if ((*dp)[index].count(targetSum)) { // Answer already present in map + return (*dp)[index][targetSum]; + } + + bool ans = + subset_sum_recursion(arr, targetSum - arr[index], dp, index + 1) || + subset_sum_recursion(arr, targetSum, dp, index + 1); + (*dp)[index][targetSum] = ans; // Save ans in dp map. + return ans; +} + +/** + * Function implementing subset sum algorithm using top-down approach + * @param arr input array + * @param targetSum the target sum of the subset + * @returns true/false based on if the target sum subset exists or not. + */ +bool subset_sum_problem(const std::vector &arr, const int targetSum) { + size_t n = arr.size(); + std::vector> dp(n); + return subset_sum_recursion(arr, targetSum, &dp); +} +} // namespace subset_sum +} // namespace dynamic_programming + +/** + * @brief Test Function + * @return void + */ +static void test() { + // custom input vector + std::vector> custom_input_arr(3); + custom_input_arr[0] = std::vector{1, -10, 2, 31, -6}; + custom_input_arr[1] = std::vector{2, 3, 4}; + custom_input_arr[2] = std::vector{0, 1, 0, 1, 0}; + + std::vector custom_input_target_sum(3); + custom_input_target_sum[0] = -14; + custom_input_target_sum[1] = 10; + custom_input_target_sum[2] = 2; + + // calculated output vector by pal_part Function + std::vector calculated_output(3); + + for (int i = 0; i < 3; i++) { + calculated_output[i] = + dynamic_programming::subset_sum::subset_sum_problem( + custom_input_arr[i], custom_input_target_sum[i]); + } + + // expected output vector + std::vector expected_output{true, false, true}; + + // Testing implementation via assert function + // It will throw error if any of the expected test fails + // Else it will give nothing + for (int i = 0; i < 3; i++) { + assert(expected_output[i] == calculated_output[i]); + } + + std::cout << "All tests passed successfully!\n"; +} + +/** + * @brief Main function + * @returns 0 on exit + */ +int main() { + test(); // execute the test + return 0; +} diff --git a/greedy_algorithms/boruvkas_minimum_spanning_tree.cpp b/greedy_algorithms/boruvkas_minimum_spanning_tree.cpp new file mode 100644 index 000000000..ff8bcb124 --- /dev/null +++ b/greedy_algorithms/boruvkas_minimum_spanning_tree.cpp @@ -0,0 +1,227 @@ +/** + * @author [Jason Nardoni](https://github.com/JNardoni) + * @file + * + * @brief + * [Borůvkas Algorithm](https://en.wikipedia.org/wiki/Borůvka's_algorithm) to + *find the Minimum Spanning Tree + * + * + * @details + * Boruvka's algorithm is a greepy algorithm to find the MST by starting with + *small trees, and combining them to build bigger ones. + * 1. Creates a group for every vertex. + * 2. looks through each edge of every vertex for the smallest weight. Keeps + *track of the smallest edge for each of the current groups. + * 3. Combine each group with the group it shares its smallest edge, adding the + *smallest edge to the MST. + * 4. Repeat step 2-3 until all vertices are combined into a single group. + * + * It assumes that the graph is connected. Non-connected edges can be + *represented using 0 or INT_MAX + * + */ + +#include /// for assert +#include /// for INT_MAX +#include /// for IO operations +#include /// for std::vector + +/** + * @namespace greedy_algorithms + * @brief Greedy Algorithms + */ +namespace greedy_algorithms { +/** + * @namespace boruvkas_minimum_spanning_tree + * @brief Functions for the [Borůvkas + * Algorithm](https://en.wikipedia.org/wiki/Borůvka's_algorithm) implementation + */ +namespace boruvkas_minimum_spanning_tree { +/** + * @brief Recursively returns the vertex's parent at the root of the tree + * @param parent the array that will be checked + * @param v vertex to find parent of + * @returns the parent of the vertex + */ +int findParent(std::vector> parent, const int v) { + if (parent[v].first != v) { + parent[v].first = findParent(parent, parent[v].first); + } + + return parent[v].first; +} + +/** + * @brief the implementation of boruvka's algorithm + * @param adj a graph adjancency matrix stored as 2d vectors. + * @returns the MST as 2d vectors + */ +std::vector> boruvkas(std::vector> adj) { + size_t size = adj.size(); + size_t total_groups = size; + + if (size <= 1) { + return adj; + } + + // Stores the current Minimum Spanning Tree. As groups are combined, they + // are added to the MST + std::vector> MST(size, std::vector(size, INT_MAX)); + for (int i = 0; i < size; i++) { + MST[i][i] = 0; + } + + // Step 1: Create a group for each vertex + + // Stores the parent of the vertex and its current depth, both initialized + // to 0 + std::vector> parent(size, std::make_pair(0, 0)); + + for (int i = 0; i < size; i++) { + parent[i].first = + i; // Sets parent of each vertex to itself, depth remains 0 + } + + // Repeat until all are in a single group + while (total_groups > 1) { + std::vector> smallest_edge( + size, std::make_pair(-1, -1)); // Pairing: start node, end node + + // Step 2: Look throught each vertex for its smallest edge, only using + // the right half of the adj matrix + for (int i = 0; i < size; i++) { + for (int j = i + 1; j < size; j++) { + if (adj[i][j] == INT_MAX || adj[i][j] == 0) { // No connection + continue; + } + + // Finds the parents of the start and end points to make sure + // they arent in the same group + int parentA = findParent(parent, i); + int parentB = findParent(parent, j); + + if (parentA != parentB) { + // Grabs the start and end points for the first groups + // current smallest edge + int start = smallest_edge[parentA].first; + int end = smallest_edge[parentA].second; + + // If there is no current smallest edge, or the new edge is + // smaller, records the new smallest + if (start == -1 || adj[i][j] < adj[start][end]) { + smallest_edge[parentA].first = i; + smallest_edge[parentA].second = j; + } + + // Does the same for the second group + start = smallest_edge[parentB].first; + end = smallest_edge[parentB].second; + + if (start == -1 || adj[j][i] < adj[start][end]) { + smallest_edge[parentB].first = j; + smallest_edge[parentB].second = i; + } + } + } + } + + // Step 3: Combine the groups based off their smallest edge + + for (int i = 0; i < size; i++) { + // Makes sure the smallest edge exists + if (smallest_edge[i].first != -1) { + // Start and end points for the groups smallest edge + int start = smallest_edge[i].first; + int end = smallest_edge[i].second; + + // Parents of the two groups - A is always itself + int parentA = i; + int parentB = findParent(parent, end); + + // Makes sure the two nodes dont share the same parent. Would + // happen if the two groups have been + // merged previously through a common shortest edge + if (parentA == parentB) { + continue; + } + + // Tries to balance the trees as much as possible as they are + // merged. The parent of the shallower + // tree will be pointed to the parent of the deeper tree. + if (parent[parentA].second < parent[parentB].second) { + parent[parentB].first = parentA; // New parent + parent[parentB].second++; // Increase depth + } else { + parent[parentA].first = parentB; + parent[parentA].second++; + } + // Add the connection to the MST, using both halves of the adj + // matrix + MST[start][end] = adj[start][end]; + MST[end][start] = adj[end][start]; + total_groups--; // one fewer group + } + } + } + return MST; +} + +/** + * @brief counts the sum of edges in the given tree + * @param adj 2D vector adjacency matrix + * @returns the int size of the tree + */ +int test_findGraphSum(std::vector> adj) { + size_t size = adj.size(); + int sum = 0; + + // Moves through one side of the adj matrix, counting the sums of each edge + for (int i = 0; i < size; i++) { + for (int j = i + 1; j < size; j++) { + if (adj[i][j] < INT_MAX) { + sum += adj[i][j]; + } + } + } + return sum; +} +} // namespace boruvkas_minimum_spanning_tree +} // namespace greedy_algorithms + +/** + * @brief Self-test implementations + * @returns void + */ +static void tests() { + std::cout << "Starting tests...\n\n"; + std::vector> graph = { + {0, 5, INT_MAX, 3, INT_MAX}, {5, 0, 2, INT_MAX, 5}, + {INT_MAX, 2, 0, INT_MAX, 3}, {3, INT_MAX, INT_MAX, 0, INT_MAX}, + {INT_MAX, 5, 3, INT_MAX, 0}, + }; + std::vector> MST = + greedy_algorithms::boruvkas_minimum_spanning_tree::boruvkas(graph); + assert(greedy_algorithms::boruvkas_minimum_spanning_tree::test_findGraphSum( + MST) == 13); + std::cout << "1st test passed!" << std::endl; + + graph = {{0, 2, 0, 6, 0}, + {2, 0, 3, 8, 5}, + {0, 3, 0, 0, 7}, + {6, 8, 0, 0, 9}, + {0, 5, 7, 9, 0}}; + MST = greedy_algorithms::boruvkas_minimum_spanning_tree::boruvkas(graph); + assert(greedy_algorithms::boruvkas_minimum_spanning_tree::test_findGraphSum( + MST) == 16); + std::cout << "2nd test passed!" << std::endl; +} + +/** + * @brief Main function + * @returns 0 on exit + */ +int main() { + tests(); // run self-test implementations + return 0; +} diff --git a/math/aliquot_sum.cpp b/math/aliquot_sum.cpp new file mode 100644 index 000000000..79be25571 --- /dev/null +++ b/math/aliquot_sum.cpp @@ -0,0 +1,68 @@ +/** + * @file + * @brief Program to return the [Aliquot + * Sum](https://en.wikipedia.org/wiki/Aliquot_sum) of a number + * + * \details + * The Aliquot sum s(n) of a non-negative integer n is the sum of all + * proper divisors of n, that is, all the divisors of n, other than itself. + * For example, the Aliquot sum of 18 = 1 + 2 + 3 + 6 + 9 = 21 + * + * @author [SpiderMath](https://github.com/SpiderMath) + */ + +#include /// for assert +#include /// for IO operations + +/** + * @brief Mathematical algorithms + * @namespace math + */ +namespace math { +/** + * Function to return the aliquot sum of a number + * @param num The input number + */ +uint64_t aliquot_sum(const uint64_t num) { + if (num == 0 || num == 1) { + return 0; // The aliquot sum for 0 and 1 is 0 + } + + uint64_t sum = 0; + + for (uint64_t i = 1; i <= num / 2; i++) { + if (num % i == 0) { + sum += i; + } + } + + return sum; +} +} // namespace math + +/** + * @brief Self-test implementations + * @returns void + */ +static void test() { + // Aliquot sum of 10 is 1 + 2 + 5 = 8 + assert(math::aliquot_sum(10) == 8); + // Aliquot sum of 15 is 1 + 3 + 5 = 9 + assert(math::aliquot_sum(15) == 9); + // Aliquot sum of 1 is 0 + assert(math::aliquot_sum(1) == 0); + // Aliquot sum of 97 is 1 (the aliquot sum of a prime number is 1) + assert(math::aliquot_sum(97) == 1); + + std::cout << "All the tests have successfully passed!\n"; +} + +/** + * @brief Main function + * @returns 0 on exit + */ +int main() { + test(); // run the self-test implementations + + return 0; +} diff --git a/range_queries/sparse_table.cpp b/range_queries/sparse_table.cpp old mode 100755 new mode 100644 index 465532f3b..4f13945ba --- a/range_queries/sparse_table.cpp +++ b/range_queries/sparse_table.cpp @@ -1,21 +1,23 @@ /** * @file sparse_table.cpp - * @brief Implementation of [Sparse Table](https://en.wikipedia.org/wiki/Range_minimum_query) data structure + * @brief Implementation of [Sparse + * Table](https://en.wikipedia.org/wiki/Range_minimum_query) data structure * * @details * Sparse Table is a data structure, that allows answering range queries. - * It can answer most range queries in O(logn), but its true power is answering range minimum queries - * or equivalent range maximum queries). For those queries it can compute the answer in O(1) time. + * It can answer most range queries in O(logn), but its true power is answering + * range minimum queries or equivalent range maximum queries). For those queries + * it can compute the answer in O(1) time. * * * Running Time Complexity \n * * Build : O(NlogN) \n * * Range Query : O(1) \n -*/ + */ -#include +#include #include #include -#include +#include /** * @namespace range_queries @@ -26,19 +28,19 @@ namespace range_queries { * @namespace sparse_table * @brief Range queries using sparse-tables */ - namespace sparse_table { +namespace sparse_table { /** * This function precomputes intial log table for further use. * @param n value of the size of the input array * @return corresponding vector of the log table */ -template +template std::vector computeLogs(const std::vector& A) { int n = A.size(); std::vector logs(n); logs[1] = 0; - for (int i = 2 ; i < n ; i++) { - logs[i] = logs[i/2] + 1; + for (int i = 2; i < n; i++) { + logs[i] = logs[i / 2] + 1; } return logs; } @@ -50,19 +52,20 @@ std::vector computeLogs(const std::vector& A) { * @param logs array of the log table * @return created sparse table data structure */ -template -std::vector > buildTable(const std::vector& A, const std::vector& logs) { +template +std::vector > buildTable(const std::vector& A, + const std::vector& logs) { int n = A.size(); - std::vector > table(20, std::vector(n+5, 0)); + std::vector > table(20, std::vector(n + 5, 0)); int curLen = 0; - for (int i = 0 ; i <= logs[n] ; i++) { + for (int i = 0; i <= logs[n]; i++) { curLen = 1 << i; - for (int j = 0 ; j + curLen < n ; j++) { + for (int j = 0; j + curLen < n; j++) { if (curLen == 1) { table[i][j] = A[j]; - } - else { - table[i][j] = std::min(table[i-1][j], table[i-1][j + curLen/2]); + } else { + table[i][j] = + std::min(table[i - 1][j], table[i - 1][j + curLen / 2]); } } } @@ -77,14 +80,15 @@ std::vector > buildTable(const std::vector& A, const std::vect * @param table sparse table data structure for the input array * @return minimum value for the [beg, end] range for the input array */ -template -int getMinimum(int beg, int end, const std::vector& logs, const std::vector >& table) { +template +int getMinimum(int beg, int end, const std::vector& logs, + const std::vector >& table) { int p = logs[end - beg + 1]; int pLen = 1 << p; return std::min(table[p][beg], table[p][end - pLen + 1]); } -} -} // namespace range_queries +} // namespace sparse_table +} // namespace range_queries /** * Main function @@ -92,10 +96,10 @@ int getMinimum(int beg, int end, const std::vector& logs, const std::vector A{1, 2, 0, 3, 9}; std::vector logs = range_queries::sparse_table::computeLogs(A); - std::vector > table = range_queries::sparse_table::buildTable(A, logs); + std::vector > table = + range_queries::sparse_table::buildTable(A, logs); assert(range_queries::sparse_table::getMinimum(0, 0, logs, table) == 1); assert(range_queries::sparse_table::getMinimum(0, 4, logs, table) == 0); assert(range_queries::sparse_table::getMinimum(2, 4, logs, table) == 0); return 0; } -