diff --git a/CMakeLists.txt b/CMakeLists.txt index f812d2c9a..25e8dc4a4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -31,8 +31,9 @@ if(DOXYGEN_FOUND) set(DOXYGEN_CREATE_SUBDIRS YES) set(DOXYGEN_EXTRACT_PRIVATE YES) set(DOCYGEN_GENERATE_TREEVIEW YES) - set(DOXYGEN_STRIP_CODE_COMMENTS NO) set(DOXYGEN_GENERATE_TREEVIEW YES) + set(DOXYGEN_STRIP_CODE_COMMENTS NO) + set(DOXYGEN_EXT_LINKS_IN_WINDOW YES) set(DOXYGEN_BUILTIN_STL_SUPPORT YES) set(DOXYGEN_CLANG_ASSISTED_PARSING YES) set(DOXYGEN_FILE_PATTERNS *.cpp *.h *.hpp *.md) @@ -72,6 +73,7 @@ add_subdirectory(strings) add_subdirectory(sorting) add_subdirectory(geometry) add_subdirectory(probability) +add_subdirectory(data_structures) add_subdirectory(machine_learning) add_subdirectory(numerical_methods) diff --git a/DIRECTORY.md b/DIRECTORY.md index 3bca579f6..bdfa2c951 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -10,38 +10,39 @@ * [Rat Maze](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/rat_maze.cpp) * [Sudoku Solve](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/sudoku_solve.cpp) -## Data Structure - * [Avltree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/avltree.cpp) - * [Binary Search Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/binary_search_tree.cpp) - * [Binaryheap](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/binaryheap.cpp) - * [Circular Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/circular_queue_using_linked_list.cpp) +## Data Structures + * [Avltree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/avltree.cpp) + * [Binary Search Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/binary_search_tree.cpp) + * [Binaryheap](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/binaryheap.cpp) + * [Circular Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/circular_queue_using_linked_list.cpp) * Cll - * [Cll](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/cll/cll.cpp) - * [Cll](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/cll/cll.h) - * [Main Cll](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/cll/main_cll.cpp) - * [Disjoint Set](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/disjoint_set.cpp) - * [Doubly Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/doubly_linked_list.cpp) - * [Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/linked_list.cpp) - * [Linkedlist Implentation Usingarray](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/linkedlist_implentation_usingarray.cpp) - * [List Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/list_array.cpp) - * [Morrisinorder](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/morrisinorder.cpp) + * [Cll](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/cll/cll.cpp) + * [Cll](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/cll/cll.h) + * [Main Cll](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/cll/main_cll.cpp) + * [Disjoint Set](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/disjoint_set.cpp) + * [Doubly Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/doubly_linked_list.cpp) + * [Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/linked_list.cpp) + * [Linkedlist Implentation Usingarray](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/linkedlist_implentation_usingarray.cpp) + * [List Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/list_array.cpp) + * [Morrisinorder](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/morrisinorder.cpp) * Queue - * [Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue/queue.cpp) - * [Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue/queue.h) - * [Test Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue/test_queue.cpp) - * [Queue Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue_using_array.cpp) - * [Queue Using Array2](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue_using_array2.cpp) - * [Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue_using_linked_list.cpp) - * [Queue Using Linkedlist](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue_using_linkedlist.cpp) - * [Stack Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stack_using_array.cpp) - * [Stack Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stack_using_linked_list.cpp) + * [Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/queue/queue.cpp) + * [Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/queue/queue.h) + * [Test Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/queue/test_queue.cpp) + * [Queue Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/queue_using_array.cpp) + * [Queue Using Array2](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/queue_using_array2.cpp) + * [Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/queue_using_linked_list.cpp) + * [Queue Using Linkedlist](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/queue_using_linkedlist.cpp) + * [Stack Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/stack_using_array.cpp) + * [Stack Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/stack_using_linked_list.cpp) * Stk - * [Main](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/main.cpp) - * [Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/stack.cpp) - * [Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/stack.h) - * [Test Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/test_stack.cpp) - * [Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/tree.cpp) - * [Trie Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/trie_tree.cpp) + * [Main](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/stk/main.cpp) + * [Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/stk/stack.cpp) + * [Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/stk/stack.h) + * [Test Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/stk/test_stack.cpp) + * [Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/tree.cpp) + * [Trie Modern](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/trie_modern.cpp) + * [Trie Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/trie_tree.cpp) ## Dynamic Programming * [0 1 Knapsack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/0_1_knapsack.cpp) @@ -72,6 +73,7 @@ * [Bridge Finding With Tarjan Algorithm](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/bridge_finding_with_tarjan_algorithm.cpp) * [Connected Components](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/connected_components.cpp) * [Connected Components With Dsu](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/connected_components_with_dsu.cpp) + * [Cycle Check Directed Graph](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/cycle_check_directed_graph.cpp) * [Dfs](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/dfs.cpp) * [Dfs With Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/dfs_with_stack.cpp) * [Dijkstra](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/dijkstra.cpp) diff --git a/README.md b/README.md index df39ee554..8dd6a92df 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,10 @@ # The Algorithms - C++ # {#mainpage} -[![contributions welcome](https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square)](https://github.com/kvedala/C-Plus-Plus/blob/master/CONTRIBUTION.md)  +![contributions welcome](https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square)] ![GitHub repo size](https://img.shields.io/github/repo-size/kvedala/C-Plus-Plus?color=red&style=flat-square) ![GitHub closed pull requests](https://img.shields.io/github/issues-pr-closed/kvedala/C-Plus-Plus?color=green&style=flat-square) -![Doxygen CI](https://github.com/kvedala/C-Plus-Plus/workflows/Doxygen%20CI/badge.svg) -![cpplint](https://github.com/kvedala/C-Plus-Plus/workflows/cpplint_modified_files/badge.svg) -![C/C++ CI](https://github.com/kvedala/C-Plus-Plus/workflows/C/C++%20CI/badge.svg) +![Doxygen CI](https://github.com/kvedala/C-Plus-Plus/workflows/Doxygen%20CI/badge.svg) +![Awesome CI](https://github.com/kvedala/C-Plus-Plus/workflows/Awesome%20CI%20Workflow/badge.svg) [Online Documentation](https://kvedala.github.io/C-Plus-Plus). @@ -15,4 +14,4 @@ Click on [Files menu](https://kvedala.github.io/C-Plus-Plus/files.html) to see t The implementations are for learning purpose. They may be less efficient than the implementation in the standard library. ### Contribute Guidelines -Read our [Contribution Guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTION.md) before you contribute. +Read our [Contribution Guidelines](https://github.com/kvedala/C-Plus-Plus/blob/master/CONTRIBUTION.md) before you contribute. diff --git a/data_structure/linkedlist_implentation_usingarray.cpp b/data_structure/linkedlist_implentation_usingarray.cpp deleted file mode 100644 index a078bef16..000000000 --- a/data_structure/linkedlist_implentation_usingarray.cpp +++ /dev/null @@ -1,104 +0,0 @@ -/* The difference between the pointer implementation of linked list and array - implementation of linked list: - 1. The NULL is represented by -1; - 2. Limited size. (in the following case it is 100 nodes at max). But we can - reuse the nodes that are to be deleted by again linking it bacj to the list. -*/ - -#include -using namespace std; -struct Node { - int data; - int next; -}; -Node AvailArray[100]; // array that will act as nodes of a linked list. -int head = -1; -int avail = 0; -void initialise_list() { - for (int i = 0; i <= 98; i++) { - AvailArray[i].next = i + 1; - } - AvailArray[99].next = -1; // indicating the end of the linked list. -} - -int getnode() // This will return the index of the first free node present in - // the avail list -{ - int NodeIndexToBeReturned = avail; - avail = AvailArray[avail].next; - return NodeIndexToBeReturned; -} - -void freeNode( - int nodeToBeDeleted) // This function when called will delete the node with - // the index presented as an argument, and will put - // back that node into the array. -{ - AvailArray[nodeToBeDeleted].next = avail; - avail = nodeToBeDeleted; -} - -void insertAtTheBeginning(int data) // The function will insert the given data - // into the front of the linked list. -{ - int newNode = getnode(); - AvailArray[newNode].data = data; - AvailArray[newNode].next = head; - head = newNode; -} - -void insertAtTheEnd(int data) { - int newNode = getnode(); - int temp = head; - while (AvailArray[temp].next != -1) { - temp = AvailArray[temp].next; - } - // temp is now pointing to the end node. - AvailArray[newNode].data = data; - AvailArray[newNode].next = -1; - AvailArray[temp].next = newNode; -} - -void display() { - int temp = head; - while (temp != -1) { - cout << AvailArray[temp].data << "->"; - temp = AvailArray[temp].next; - } - cout << "-1" << endl; - ; -} - -int main() { - initialise_list(); - int x, y, z; - for (;;) { - cout << "1. Insert At The Beginning" << endl; - cout << "2. Insert At The End" << endl; - cout << "3. Display" << endl; - cout << "4.Exit" << endl; - cout << "Enter Your choice" << endl; - cin >> z; - switch (z) { - case 1: - cout << "Enter the number you want to enter" << endl; - cin >> x; - insertAtTheBeginning(x); - break; - case 2: - cout << "Enter the number you want to enter" << endl; - cin >> y; - insertAtTheEnd(y); - break; - case 3: - cout << "The linked list contains the following element in order" - << endl; - display(); - break; - case 4: - exit(0); - default: - cout << "The entered choice is not correct" << endl; - } - } -} diff --git a/data_structure/stack_using_array.cpp b/data_structure/stack_using_array.cpp deleted file mode 100644 index 5dd7ac98e..000000000 --- a/data_structure/stack_using_array.cpp +++ /dev/null @@ -1,56 +0,0 @@ -#include -using namespace std; - -int *stack; -int top = 0, size; - -void push(int x) { - if (top == size) { - cout << "\nOverflow"; - } else { - stack[top++] = x; - } -} - -void pop() { - if (top == 0) { - cout << "\nUnderflow"; - } else { - cout << "\n" << stack[--top] << " deleted"; - } -} - -void show() { - for (int i = 0; i < top; i++) { - cout << stack[i] << "\n"; - } -} - -void topmost() { cout << "\nTopmost element: " << stack[top - 1]; } -int main() { - cout << "\nEnter Size of stack : "; - cin >> size; - stack = new int[size]; - int ch, x; - do { - cout << "\n1. Push"; - cout << "\n2. Pop"; - cout << "\n3. Print"; - cout << "\n4. Print topmost element:"; - cout << "\nEnter Your Choice : "; - cin >> ch; - if (ch == 1) { - cout << "\nInsert : "; - cin >> x; - push(x); - } else if (ch == 2) { - pop(); - } else if (ch == 3) { - show(); - } else if (ch == 4) { - topmost(); - } - } while (ch != 0); - - return 0; -} diff --git a/data_structures/CMakeLists.txt b/data_structures/CMakeLists.txt new file mode 100644 index 000000000..7840c8349 --- /dev/null +++ b/data_structures/CMakeLists.txt @@ -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/data_structures") + +endforeach( testsourcefile ${APP_SOURCES} ) diff --git a/data_structure/avltree.cpp b/data_structures/avltree.cpp similarity index 77% rename from data_structure/avltree.cpp rename to data_structures/avltree.cpp index f38133c05..836f0f667 100644 --- a/data_structure/avltree.cpp +++ b/data_structures/avltree.cpp @@ -1,8 +1,15 @@ +/** + * \file + * \brief A simple tree implementation using nodes + * + * \todo update code to use C++ STL library features and OO structure + * \warning This program is a poor implementation and does not utilize any of + * the C++ STL features. + */ +#include #include #include -using namespace std; - typedef struct node { int data; int height; @@ -10,10 +17,7 @@ typedef struct node { struct node *right; } node; -int max(int a, int b) { return a > b ? a : b; } - -// Returns a new Node - +/** Create and return a new Node */ node *createNode(int data) { node *nn = new node(); nn->data = data; @@ -23,20 +27,17 @@ node *createNode(int data) { return nn; } -// Returns height of tree - +/** Returns height of tree */ int height(node *root) { if (root == NULL) return 0; - return 1 + max(height(root->left), height(root->right)); + return 1 + std::max(height(root->left), height(root->right)); } -// Returns difference between height of left and right subtree - +/** Returns difference between height of left and right subtree */ int getBalance(node *root) { return height(root->left) - height(root->right); } -// Returns Node after Right Rotation - +/** Returns Node after Right Rotation */ node *rightRotate(node *root) { node *t = root->left; node *u = t->right; @@ -45,8 +46,7 @@ node *rightRotate(node *root) { return t; } -// Returns Node after Left Rotation - +/** Returns Node after Left Rotation */ node *leftRotate(node *root) { node *t = root->right; node *u = t->left; @@ -55,16 +55,14 @@ node *leftRotate(node *root) { return t; } -// Returns node with minimum value in the tree - +/** Returns node with minimum value in the tree */ node *minValue(node *root) { if (root->left == NULL) return root; return minValue(root->left); } -// Balanced Insertion - +/** Balanced Insertion */ node *insert(node *root, int item) { node *nn = createNode(item); if (root == NULL) @@ -86,8 +84,7 @@ node *insert(node *root, int item) { return root; } -// Balanced Deletion - +/** Balanced Deletion */ node *deleteNode(node *root, int key) { if (root == NULL) return root; @@ -118,14 +115,13 @@ node *deleteNode(node *root, int key) { return root; } -// LevelOrder (Breadth First Search) - +/** LevelOrder (Breadth First Search) */ void levelOrder(node *root) { - queue q; + std::queue q; q.push(root); while (!q.empty()) { root = q.front(); - cout << root->data << " "; + std::cout << root->data << " "; q.pop(); if (root->left) q.push(root->left); @@ -134,18 +130,19 @@ void levelOrder(node *root) { } } +/** Main function */ int main() { // Testing AVL Tree node *root = NULL; int i; for (i = 1; i <= 7; i++) root = insert(root, i); - cout << "LevelOrder: "; + std::cout << "LevelOrder: "; levelOrder(root); root = deleteNode(root, 1); // Deleting key with value 1 - cout << "\nLevelOrder: "; + std::cout << "\nLevelOrder: "; levelOrder(root); root = deleteNode(root, 4); // Deletin key with value 4 - cout << "\nLevelOrder: "; + std::cout << "\nLevelOrder: "; levelOrder(root); return 0; } diff --git a/data_structure/binary_search_tree.cpp b/data_structures/binary_search_tree.cpp similarity index 73% rename from data_structure/binary_search_tree.cpp rename to data_structures/binary_search_tree.cpp index c3a74f385..947bb53d8 100644 --- a/data_structure/binary_search_tree.cpp +++ b/data_structures/binary_search_tree.cpp @@ -1,5 +1,12 @@ +/** + * \file + * \brief A simple tree implementation using structured nodes + * + * \todo update code to use C++ STL library features and OO structure + * \warning This program is a poor implementation - C style - and does not + * utilize any of the C++ STL features. + */ #include -using namespace std; struct node { int val; @@ -84,7 +91,7 @@ void Remove(node *p, node *n, int x) { void BFT(node *n) { if (n != NULL) { - cout << n->val << " "; + std::cout << n->val << " "; enqueue(n->left); enqueue(n->right); BFT(dequeue()); @@ -93,7 +100,7 @@ void BFT(node *n) { void Pre(node *n) { if (n != NULL) { - cout << n->val << " "; + std::cout << n->val << " "; Pre(n->left); Pre(n->right); } @@ -102,7 +109,7 @@ void Pre(node *n) { void In(node *n) { if (n != NULL) { In(n->left); - cout << n->val << " "; + std::cout << n->val << " "; In(n->right); } } @@ -111,7 +118,7 @@ void Post(node *n) { if (n != NULL) { Post(n->left); Post(n->right); - cout << n->val << " "; + std::cout << n->val << " "; } } @@ -121,31 +128,31 @@ int main() { int value; int ch; node *root = new node; - cout << "\nEnter the value of root node :"; - cin >> value; + std::cout << "\nEnter the value of root node :"; + std::cin >> value; root->val = value; root->left = NULL; root->right = NULL; do { - cout << "\n1. Insert"; - cout << "\n2. Delete"; - cout << "\n3. Breadth First"; - cout << "\n4. Preorder Depth First"; - cout << "\n5. Inorder Depth First"; - cout << "\n6. Postorder Depth First"; + std::cout << "\n1. Insert" + << "\n2. Delete" + << "\n3. Breadth First" + << "\n4. Preorder Depth First" + << "\n5. Inorder Depth First" + << "\n6. Postorder Depth First"; - cout << "\nEnter Your Choice : "; - cin >> ch; + std::cout << "\nEnter Your Choice : "; + std::cin >> ch; int x; switch (ch) { case 1: - cout << "\nEnter the value to be Inserted : "; - cin >> x; + std::cout << "\nEnter the value to be Inserted : "; + std::cin >> x; Insert(root, x); break; case 2: - cout << "\nEnter the value to be Deleted : "; - cin >> x; + std::cout << "\nEnter the value to be Deleted : "; + std::cin >> x; Remove(root, root, x); break; case 3: @@ -162,4 +169,6 @@ int main() { break; } } while (ch != 0); + + return 0; } diff --git a/data_structure/binaryheap.cpp b/data_structures/binaryheap.cpp similarity index 56% rename from data_structure/binaryheap.cpp rename to data_structures/binaryheap.cpp index a31d87674..72e56e91a 100644 --- a/data_structure/binaryheap.cpp +++ b/data_structures/binaryheap.cpp @@ -1,48 +1,52 @@ -// A C++ program to demonstrate common Binary Heap Operations +/** + * \file + * \brief A C++ program to demonstrate common Binary Heap Operations + */ #include #include -using namespace std; +#include -// Prototype of a utility function to swap two integers -void swap(int *x, int *y); - -// A class for Min Heap +/** A class for Min Heap */ class MinHeap { - int *harr; // pointer to array of elements in heap - int capacity; // maximum possible size of min heap - int heap_size; // Current number of elements in min heap + int *harr; ///< pointer to array of elements in heap + int capacity; ///< maximum possible size of min heap + int heap_size; ///< Current number of elements in min heap + public: - // Constructor + /** Constructor + * \param[in] capacity initial heap capacity + */ MinHeap(int capacity); - // to heapify a subtree with the root at given index + /** to heapify a subtree with the root at given index + */ void MinHeapify(int); int parent(int i) { return (i - 1) / 2; } - // to get index of left child of node at index i + /** to get index of left child of node at index i */ int left(int i) { return (2 * i + 1); } - // to get index of right child of node at index i + /** to get index of right child of node at index i */ int right(int i) { return (2 * i + 2); } - // to extract the root which is the minimum element + /** to extract the root which is the minimum element */ int extractMin(); - // Decreases key value of key at index i to new_val + /** Decreases key value of key at index i to new_val */ void decreaseKey(int i, int new_val); - // Returns the minimum key (key at root) from min heap + /** Returns the minimum key (key at root) from min heap */ int getMin() { return harr[0]; } - // Deletes a key stored at index i + /** Deletes a key stored at index i */ void deleteKey(int i); - // Inserts a new key 'k' + /** Inserts a new key 'k' */ void insertKey(int k); }; -// Constructor: Builds a heap from a given array a[] of given size +/** Constructor: Builds a heap from a given array a[] of given size */ MinHeap::MinHeap(int cap) { heap_size = 0; capacity = cap; @@ -52,7 +56,7 @@ MinHeap::MinHeap(int cap) { // Inserts a new key 'k' void MinHeap::insertKey(int k) { if (heap_size == capacity) { - cout << "\nOverflow: Could not insertKey\n"; + std::cout << "\nOverflow: Could not insertKey\n"; return; } @@ -63,17 +67,18 @@ void MinHeap::insertKey(int k) { // Fix the min heap property if it is violated while (i != 0 && harr[parent(i)] > harr[i]) { - swap(&harr[i], &harr[parent(i)]); + std::swap(harr[i], harr[parent(i)]); i = parent(i); } } -// Decreases value of key at index 'i' to new_val. It is assumed that -// new_val is smaller than harr[i]. +/** Decreases value of key at index 'i' to new_val. It is assumed that new_val + * is smaller than harr[i]. + */ void MinHeap::decreaseKey(int i, int new_val) { harr[i] = new_val; while (i != 0 && harr[parent(i)] > harr[i]) { - swap(&harr[i], &harr[parent(i)]); + std::swap(harr[i], harr[parent(i)]); i = parent(i); } } @@ -96,15 +101,17 @@ int MinHeap::extractMin() { return root; } -// This function deletes key at index i. It first reduced value to minus -// infinite, then calls extractMin() +/** This function deletes key at index i. It first reduced value to minus + * infinite, then calls extractMin() + */ void MinHeap::deleteKey(int i) { decreaseKey(i, INT_MIN); extractMin(); } -// A recursive method to heapify a subtree with the root at given index -// This method assumes that the subtrees are already heapified +/** A recursive method to heapify a subtree with the root at given index + * This method assumes that the subtrees are already heapified + */ void MinHeap::MinHeapify(int i) { int l = left(i); int r = right(i); @@ -114,18 +121,11 @@ void MinHeap::MinHeapify(int i) { if (r < heap_size && harr[r] < harr[smallest]) smallest = r; if (smallest != i) { - swap(&harr[i], &harr[smallest]); + std::swap(harr[i], harr[smallest]); MinHeapify(smallest); } } -// A utility function to swap two elements -void swap(int *x, int *y) { - int temp = *x; - *x = *y; - *y = temp; -} - // Driver program to test above functions int main() { MinHeap h(11); @@ -136,9 +136,9 @@ int main() { h.insertKey(5); h.insertKey(4); h.insertKey(45); - cout << h.extractMin() << " "; - cout << h.getMin() << " "; + std::cout << h.extractMin() << " "; + std::cout << h.getMin() << " "; h.decreaseKey(2, 1); - cout << h.getMin(); + std::cout << h.getMin(); return 0; } diff --git a/data_structure/circular_queue_using_linked_list.cpp b/data_structures/circular_queue_using_linked_list.cpp similarity index 91% rename from data_structure/circular_queue_using_linked_list.cpp rename to data_structures/circular_queue_using_linked_list.cpp index b6a471044..5d6484ce3 100644 --- a/data_structure/circular_queue_using_linked_list.cpp +++ b/data_structures/circular_queue_using_linked_list.cpp @@ -1,5 +1,4 @@ #include -using namespace std; struct node { int data; @@ -48,11 +47,10 @@ class Queue { node *ptr; ptr = front; do { - cout << ptr->data << " "; + std::cout << ptr->data << " "; ptr = ptr->next; } while (ptr != rear->next); - cout << front->data; - cout << endl; + std::cout << front->data << std::endl; } }; int main(void) { diff --git a/data_structure/cll/cll.cpp b/data_structures/cll/cll.cpp similarity index 100% rename from data_structure/cll/cll.cpp rename to data_structures/cll/cll.cpp diff --git a/data_structure/cll/cll.h b/data_structures/cll/cll.h similarity index 100% rename from data_structure/cll/cll.h rename to data_structures/cll/cll.h diff --git a/data_structure/cll/main_cll.cpp b/data_structures/cll/main_cll.cpp similarity index 100% rename from data_structure/cll/main_cll.cpp rename to data_structures/cll/main_cll.cpp diff --git a/data_structure/cll/makefile b/data_structures/cll/makefile similarity index 100% rename from data_structure/cll/makefile rename to data_structures/cll/makefile diff --git a/data_structure/disjoint_set.cpp b/data_structures/disjoint_set.cpp similarity index 100% rename from data_structure/disjoint_set.cpp rename to data_structures/disjoint_set.cpp diff --git a/data_structure/doubly_linked_list.cpp b/data_structures/doubly_linked_list.cpp similarity index 100% rename from data_structure/doubly_linked_list.cpp rename to data_structures/doubly_linked_list.cpp diff --git a/data_structure/linked_list.cpp b/data_structures/linked_list.cpp similarity index 100% rename from data_structure/linked_list.cpp rename to data_structures/linked_list.cpp diff --git a/data_structures/linkedlist_implentation_usingarray.cpp b/data_structures/linkedlist_implentation_usingarray.cpp new file mode 100644 index 000000000..75d400d72 --- /dev/null +++ b/data_structures/linkedlist_implentation_usingarray.cpp @@ -0,0 +1,114 @@ +/** + * \file + * \brief Linked list implementation using Arrays + * + * The difference between the pointer implementation of linked list and array + * implementation of linked list: + * 1. The NULL is represented by -1; + * 2. Limited size. (in the following case it is 100 nodes at max). But we can + * reuse the nodes that are to be deleted by again linking it bacj to the list. + */ + +#include + +struct Node { + int data; + int next; +}; + +Node AvailArray[100]; ///< array that will act as nodes of a linked list. + +int head = -1; +int avail = 0; +void initialise_list() { + for (int i = 0; i <= 98; i++) { + AvailArray[i].next = i + 1; + } + AvailArray[99].next = -1; // indicating the end of the linked list. +} + +/** This will return the index of the first free node present in the avail list + */ +int getnode() { + int NodeIndexToBeReturned = avail; + avail = AvailArray[avail].next; + return NodeIndexToBeReturned; +} + +/** This function when called will delete the node with + * the index presented as an argument, and will put + * back that node into the array. + */ +void freeNode(int nodeToBeDeleted) { + AvailArray[nodeToBeDeleted].next = avail; + avail = nodeToBeDeleted; +} + +/** The function will insert the given data + * into the front of the linked list. + */ +void insertAtTheBeginning(int data) { + int newNode = getnode(); + AvailArray[newNode].data = data; + AvailArray[newNode].next = head; + head = newNode; +} + +void insertAtTheEnd(int data) { + int newNode = getnode(); + int temp = head; + while (AvailArray[temp].next != -1) { + temp = AvailArray[temp].next; + } + // temp is now pointing to the end node. + AvailArray[newNode].data = data; + AvailArray[newNode].next = -1; + AvailArray[temp].next = newNode; +} + +void display() { + int temp = head; + while (temp != -1) { + std::cout << AvailArray[temp].data << "->"; + temp = AvailArray[temp].next; + } + std::cout << "-1" << std::endl; +} + +/** Main function */ +int main() { + initialise_list(); + int x, y, z; + for (;;) { + std::cout << "1. Insert At The Beginning" << std::endl; + std::cout << "2. Insert At The End" << std::endl; + std::cout << "3. Display" << std::endl; + std::cout << "4.Exit" << std::endl; + std::cout << "Enter Your choice" << std::endl; + std::cin >> z; + switch (z) { + case 1: + std::cout << "Enter the number you want to enter" << std::endl; + std::cin >> x; + insertAtTheBeginning(x); + break; + case 2: + std::cout << "Enter the number you want to enter" << std::endl; + std::cin >> y; + insertAtTheEnd(y); + break; + case 3: + std::cout + << "The linked list contains the following element in order" + << std::endl; + display(); + break; + case 4: + return 0; + default: + std::cout << "The entered choice is not correct" << std::endl; + } + } + + return 0; +} diff --git a/data_structure/list_array.cpp b/data_structures/list_array.cpp similarity index 100% rename from data_structure/list_array.cpp rename to data_structures/list_array.cpp diff --git a/data_structure/morrisinorder.cpp b/data_structures/morrisinorder.cpp similarity index 100% rename from data_structure/morrisinorder.cpp rename to data_structures/morrisinorder.cpp diff --git a/data_structure/queue/makefile b/data_structures/queue/makefile similarity index 100% rename from data_structure/queue/makefile rename to data_structures/queue/makefile diff --git a/data_structure/queue/queue.cpp b/data_structures/queue/queue.cpp similarity index 100% rename from data_structure/queue/queue.cpp rename to data_structures/queue/queue.cpp diff --git a/data_structure/queue/queue.h b/data_structures/queue/queue.h similarity index 100% rename from data_structure/queue/queue.h rename to data_structures/queue/queue.h diff --git a/data_structure/queue/test_queue.cpp b/data_structures/queue/test_queue.cpp similarity index 100% rename from data_structure/queue/test_queue.cpp rename to data_structures/queue/test_queue.cpp diff --git a/data_structure/queue_using_array.cpp b/data_structures/queue_using_array.cpp similarity index 100% rename from data_structure/queue_using_array.cpp rename to data_structures/queue_using_array.cpp diff --git a/data_structure/queue_using_array2.cpp b/data_structures/queue_using_array2.cpp similarity index 100% rename from data_structure/queue_using_array2.cpp rename to data_structures/queue_using_array2.cpp diff --git a/data_structure/queue_using_linked_list.cpp b/data_structures/queue_using_linked_list.cpp similarity index 100% rename from data_structure/queue_using_linked_list.cpp rename to data_structures/queue_using_linked_list.cpp diff --git a/data_structure/queue_using_linkedlist.cpp b/data_structures/queue_using_linkedlist.cpp similarity index 100% rename from data_structure/queue_using_linkedlist.cpp rename to data_structures/queue_using_linkedlist.cpp diff --git a/data_structures/stack_using_array.cpp b/data_structures/stack_using_array.cpp new file mode 100644 index 000000000..36be9eb39 --- /dev/null +++ b/data_structures/stack_using_array.cpp @@ -0,0 +1,55 @@ +#include + +int *stack; +int top = 0, stack_size; + +void push(int x) { + if (top == stack_size) { + std::cout << "\nOverflow"; + } else { + stack[top++] = x; + } +} + +void pop() { + if (top == 0) { + std::cout << "\nUnderflow"; + } else { + std::cout << "\n" << stack[--top] << " deleted"; + } +} + +void show() { + for (int i = 0; i < top; i++) { + std::cout << stack[i] << "\n"; + } +} + +void topmost() { std::cout << "\nTopmost element: " << stack[top - 1]; } +int main() { + std::cout << "\nEnter stack_size of stack : "; + std::cin >> stack_size; + stack = new int[stack_size]; + int ch, x; + do { + std::cout << "\n1. Push"; + std::cout << "\n2. Pop"; + std::cout << "\n3. Print"; + std::cout << "\n4. Print topmost element:"; + std::cout << "\nEnter Your Choice : "; + std::cin >> ch; + if (ch == 1) { + std::cout << "\nInsert : "; + std::cin >> x; + push(x); + } else if (ch == 2) { + pop(); + } else if (ch == 3) { + show(); + } else if (ch == 4) { + topmost(); + } + } while (ch != 0); + + return 0; +} diff --git a/data_structure/stack_using_linked_list.cpp b/data_structures/stack_using_linked_list.cpp similarity index 100% rename from data_structure/stack_using_linked_list.cpp rename to data_structures/stack_using_linked_list.cpp diff --git a/data_structure/stk/main.cpp b/data_structures/stk/main.cpp similarity index 100% rename from data_structure/stk/main.cpp rename to data_structures/stk/main.cpp diff --git a/data_structure/stk/makefile b/data_structures/stk/makefile similarity index 100% rename from data_structure/stk/makefile rename to data_structures/stk/makefile diff --git a/data_structure/stk/stack.cpp b/data_structures/stk/stack.cpp similarity index 100% rename from data_structure/stk/stack.cpp rename to data_structures/stk/stack.cpp diff --git a/data_structure/stk/stack.h b/data_structures/stk/stack.h similarity index 100% rename from data_structure/stk/stack.h rename to data_structures/stk/stack.h diff --git a/data_structure/stk/student.txt b/data_structures/stk/student.txt similarity index 100% rename from data_structure/stk/student.txt rename to data_structures/stk/student.txt diff --git a/data_structure/stk/test_stack.cpp b/data_structures/stk/test_stack.cpp similarity index 100% rename from data_structure/stk/test_stack.cpp rename to data_structures/stk/test_stack.cpp diff --git a/data_structure/tree.cpp b/data_structures/tree.cpp similarity index 100% rename from data_structure/tree.cpp rename to data_structures/tree.cpp diff --git a/data_structures/trie_modern.cpp b/data_structures/trie_modern.cpp new file mode 100644 index 000000000..c2eba30e0 --- /dev/null +++ b/data_structures/trie_modern.cpp @@ -0,0 +1,168 @@ +/** + * @file + * + * Copyright 2020 @author Anmol3299 + * \brief A basic implementation of trie class to store only lower-case strings. + */ +#include // for io operations +#include // for std::shared_ptr<> +#include // for std::string class + +/** + * A basic implementation of trie class to store only lower-case strings. + * You can extend the implementation to all the ASCII characters by changing the + * value of @ ALPHABETS to 128. + */ +class Trie { + private: + static constexpr size_t ALPHABETS = 26; + + /** + * Structure of trie node. + * This struct doesn't need a constructor as we are initializing using + * intializer list which is more efficient than if we had done so with + * constructor. + */ + struct TrieNode { + // An array of pointers of size 26 which tells if a character of word is + // present or not. + std::shared_ptr character[ALPHABETS]{nullptr}; + + bool isEndOfWord{false}; + }; + + /** + * Function to check if a node has some children which can form words. + * @param node whose character array of pointers need to be checked for + * children. + * @return `true` if a child is found + * @return `false` if a child is not found + */ + inline static bool hasChildren(std::shared_ptr node) { + for (size_t i = 0; i < ALPHABETS; i++) { + if (node->character[i]) { + return true; + } + } + return false; + } + + /** + * A recursive helper function to remove a word from the trie. First, it + * recursively traverses to the location of last character of word in the + * trie. However, if the word is not found, the function returns a runtime + * error. Upon successfully reaching the last character of word in trie, if + * sets the isEndOfWord to false and deletes the node if and only if it has + * no children, else it returns the current node. + * @param word is the string which needs to be removed from trie. + * @param curr is the current node we are at. + * @param index is the index of the @word we are at. + * @return if current node has childern, it returns @ curr, else it returns + * nullptr. + * @throw a runtime error in case @ word is not found in the trie. + */ + std::shared_ptr removeWordHelper(const std::string& word, + std::shared_ptr curr, + size_t index) { + if (word.size() == index) { + if (curr->isEndOfWord) { + curr->isEndOfWord = false; + } + if (hasChildren(curr)) { + return curr; + } + return nullptr; + } + + size_t idx = word[index] - 'a'; + + // Throw a runtime error in case the user enters a word which is not + // present in the trie. + if (!curr->character[idx]) { + throw std::runtime_error(std::move(std::string("Word not found."))); + } + + curr->character[idx] = + removeWordHelper(word, curr->character[idx], index + 1); + + // This if condition checks if the node has some childern. + // The 1st if check, i.e. (curr->character[idx]) is checked specifically + // because if the older string is a prefix of some other string, then, + // there would be no need to check all 26 characters. Example- str1 = + // abbey, str2 = abbex and we want to delete string "abbey", then in + // this case, there would be no need to check all characters for the + // chars a,b,b. + if (curr->character[idx] || hasChildren(curr)) { + return curr; + } + return nullptr; + } + + public: + /// constructor to initialise the root of the trie. + Trie() : m_root(std::make_shared()) {} + + /** + * Insert a word into the trie. + * @param word which needs to be inserted into the string. + */ + void insert(const std::string& word) { + auto curr = m_root; + for (char ch : word) { + size_t index = ch - 'a'; + + // if a node for current word is not already present in trie, create + // a new node for it. + if (!curr->character[index]) { + curr->character[index] = std::make_shared(); + } + + curr = curr->character[index]; + } + curr->isEndOfWord = true; + } + + /** + * Search if a word is present in trie or not. + * @param word which is needed to be searched in the trie. + * @return True if the word is found in trie and isEndOfWord is set to true. + * @return False if word is not found in trie or isEndOfWord is set to + * false. + */ + bool search(const std::string& word) { + auto curr = m_root; + for (char ch : word) { + size_t index = ch - 'a'; + + // if any node for a character is not found, then return that the + // word cannot be formed. + if (!curr->character[index]) { + return false; + } + curr = curr->character[index]; + } + return curr->isEndOfWord; + } + + // Function to remove the word which calls the helper function. + void removeWord(const std::string& word) { + m_root = removeWordHelper(word, m_root, 0); + } + + private: + // data member to store the root of the trie. + std::shared_ptr m_root; +}; + +/** + * Main function + */ +int main() { + Trie trie; + trie.insert("hel"); + trie.insert("hello"); + trie.removeWord("hel"); + std::cout << trie.search("hello") << '\n'; + + return 0; +} diff --git a/data_structure/trie_tree.cpp b/data_structures/trie_tree.cpp similarity index 100% rename from data_structure/trie_tree.cpp rename to data_structures/trie_tree.cpp diff --git a/graph/cycle_check_directed_graph.cpp b/graph/cycle_check_directed_graph.cpp new file mode 100644 index 000000000..0f7b84cd3 --- /dev/null +++ b/graph/cycle_check_directed_graph.cpp @@ -0,0 +1,302 @@ +/** + * Copyright 2020 + * @file cycle_check_directed graph.cpp + * + * @brief BFS and DFS algorithms to check for cycle in a directed graph. + * + * @author Anmol3299 + * contact: mittalanmol22@gmail.com + * + */ + +#include // for std::cout +#include // for std::queue +#include // for throwing errors +#include // for std::remove_reference_t +#include // for std::unordered_map +#include // for std::move +#include // for std::vector + +/** + * Implementation of non-weighted directed edge of a graph. + * + * The source vertex of the edge is labelled "src" and destination vertex is + * labelled "dest". + */ +struct Edge { + unsigned int src; + unsigned int dest; + + Edge() = delete; + ~Edge() = default; + Edge(Edge&&) = default; + Edge& operator=(Edge&&) = default; + Edge(Edge const&) = default; + Edge& operator=(Edge const&) = default; + + /** Set the source and destination of the vertex. + * + * @param source is the source vertex of the edge. + * @param destination is the destination vertex of the edge. + */ + Edge(unsigned int source, unsigned int destination) + : src(source), dest(destination) {} +}; + +using AdjList = std::unordered_map>; + +/** + * Implementation of graph class. + * + * The graph will be represented using Adjacency List representation. + * This class contains 2 data members "m_vertices" & "m_adjList" used to + * represent the number of vertices and adjacency list of the graph + * respectively. The vertices are labelled 0 - (m_vertices - 1). + */ +class Graph { + public: + Graph() : m_vertices(0), m_adjList({}) {} + ~Graph() = default; + Graph(Graph&&) = default; + Graph& operator=(Graph&&) = default; + Graph(Graph const&) = default; + Graph& operator=(Graph const&) = default; + + /** Create a graph from vertices and adjacency list. + * + * @param vertices specify the number of vertices the graph would contain. + * @param adjList is the adjacency list representation of graph. + */ + Graph(unsigned int vertices, AdjList const& adjList) + : m_vertices(vertices), m_adjList(adjList) {} + + /** Create a graph from vertices and adjacency list. + * + * @param vertices specify the number of vertices the graph would contain. + * @param adjList is the adjacency list representation of graph. + */ + Graph(unsigned int vertices, AdjList&& adjList) + : m_vertices(std::move(vertices)), m_adjList(std::move(adjList)) {} + + /** Create a graph from vertices and a set of edges. + * + * Adjacency list of the graph would be created from the set of edges. If + * the source or destination of any edge has a value greater or equal to + * number of vertices, then it would throw a range_error. + * + * @param vertices specify the number of vertices the graph would contain. + * @param edges is a vector of edges. + */ + Graph(unsigned int vertices, std::vector const& edges) + : m_vertices(vertices) { + for (auto const& edge : edges) { + if (edge.src >= vertices || edge.dest >= vertices) { + throw std::range_error( + "Either src or dest of edge out of range"); + } + m_adjList[edge.src].emplace_back(edge.dest); + } + } + + /** Return a const reference of the adjacency list. + * + * @return const reference to the adjacency list + */ + std::remove_reference_t const& getAdjList() const { + return m_adjList; + } + + /** + * @return number of vertices in the graph. + */ + std::remove_reference_t const& getVertices() const { + return m_vertices; + } + + /** Add vertices in the graph. + * + * @param num is the number of vertices to be added. It adds 1 vertex by + * default. + * + */ + void addVertices(unsigned int num = 1) { m_vertices += num; } + + /** Add an edge in the graph. + * + * @param edge that needs to be added. + */ + void addEdge(Edge const& edge) { + if (edge.src >= m_vertices || edge.dest >= m_vertices) { + throw std::range_error("Either src or dest of edge out of range"); + } + m_adjList[edge.src].emplace_back(edge.dest); + } + + /** Add an Edge in the graph + * + * @param source is source vertex of the edge. + * @param destination is the destination vertex of the edge. + */ + void addEdge(unsigned int source, unsigned int destination) { + if (source >= m_vertices || destination >= m_vertices) { + throw std::range_error( + "Either source or destination of edge out of range"); + } + m_adjList[source].emplace_back(destination); + } + + private: + unsigned int m_vertices; + AdjList m_adjList; +}; + +class CycleCheck { + private: + enum nodeStates : uint8_t { not_visited = 0, in_stack, visited }; + + /** Helper function of "isCyclicDFS". + * + * @param adjList is the adjacency list representation of some graph. + * @param state is the state of the nodes of the graph. + * @param node is the node being evaluated. + * + * @return true if graph has a cycle, else false. + */ + static bool isCyclicDFSHelper(AdjList const& adjList, + std::vector* state, + unsigned int node) { + // Add node "in_stack" state. + (*state)[node] = in_stack; + + // If the node has children, then recursively visit all children of the + // node. + if (auto const& it = adjList.find(node); it != adjList.end()) { + for (auto child : it->second) { + // If state of child node is "not_visited", evaluate that child + // for presence of cycle. + if (auto state_of_child = (*state)[child]; + state_of_child == not_visited) { + if (isCyclicDFSHelper(adjList, state, child)) { + return true; + } + } else if (state_of_child == in_stack) { + // If child node was "in_stack", then that means that there + // is a cycle in the graph. Return true for presence of the + // cycle. + return true; + } + } + } + + // Current node has been evaluated for the presence of cycle and had no + // cycle. Mark current node as "visited". + (*state)[node] = visited; + // Return that current node didn't result in any cycles. + return false; + } + + public: + /** Driver function to check if a graph has a cycle. + * + * This function uses DFS to check for cycle in the graph. + * + * @param graph which needs to be evaluated for the presence of cycle. + * @return true if a cycle is detected, else false. + */ + static bool isCyclicDFS(Graph const& graph) { + /** State of the node. + * + * It is a vector of "nodeStates" which represents the state node is in. + * It can take only 3 values: "not_visited", "in_stack", and "visited". + * + * Initially, all nodes are in "not_visited" state. + */ + std::vector state(graph.getVertices(), not_visited); + + // Start visiting each node. + for (auto node = 0; node < graph.getVertices(); node++) { + // If a node is not visited, only then check for presence of cycle. + // There is no need to check for presence of cycle for a visited + // node as it has already been checked for presence of cycle. + if (state[node] == not_visited) { + // Check for cycle. + if (isCyclicDFSHelper(graph.getAdjList(), &state, node)) { + return true; + } + } + } + + // All nodes have been safely traversed, that means there is no cycle in + // the graph. Return false. + return false; + } + + /** Check if a graph has cycle or not. + * + * This function uses BFS to check if a graph is cyclic or not. + * + * @param graph which needs to be evaluated for the presence of cycle. + * @return true if a cycle is detected, else false. + */ + static bool isCyclicBFS(Graph const& graph) { + AdjList graphAjdList = graph.getAdjList(); + + std::vector indegree(graph.getVertices(), 0); + // Calculate the indegree i.e. the number of incident edges to the node. + for (auto const& [parent, children] : graphAjdList) { + for (auto const& child : children) { + indegree[child]++; + } + } + + std::queue can_be_solved; + for (auto node = 0; node < graph.getVertices(); node++) { + // If a node doesn't have any input edges, then that node will + // definately not result in a cycle and can be visited safely. + if (!indegree[node]) { + can_be_solved.emplace(node); + } + } + + // Vertices that need to be traversed. + auto remain = graph.getVertices(); + // While there are safe nodes that we can visit. + while (!can_be_solved.empty()) { + auto front = can_be_solved.front(); + // Visit the node. + can_be_solved.pop(); + // Decrease number of nodes that need to be traversed. + remain--; + + // Visit all the children of the visited node. + if (auto it = graphAjdList.find(front); it != graphAjdList.end()) { + for (auto child : it->second) { + // Check if we can visited the node safely. + if (--indegree[child] == 0) { + // if node can be visited safely, then add that node to + // the visit queue. + can_be_solved.emplace(child); + } + } + } + } + + // If there are still nodes that we can't visit, then it means that + // there is a cycle and return true, else return false. + return !(remain == 0); + } +}; + +/** + * Main function. + */ +int main() { + // Instantiate the graph. + Graph g(7, std::vector{{0, 1}, {1, 2}, {2, 0}, {2, 5}, {3, 5}}); + // Check for cycle using BFS method. + std::cout << CycleCheck::isCyclicBFS(g) << '\n'; + + // Check for cycle using DFS method. + std::cout << CycleCheck::isCyclicDFS(g) << '\n'; + return 0; +} diff --git a/machine_learning/kohonen_som_trace.cpp b/machine_learning/kohonen_som_trace.cpp index f2da7d183..4929eaef3 100644 --- a/machine_learning/kohonen_som_trace.cpp +++ b/machine_learning/kohonen_som_trace.cpp @@ -130,7 +130,6 @@ void update_weights(const std::valarray &x, * * \param[in] X data set * \param[in,out] W weights matrix - * \param[in] D temporary vector to store distances * \param[in] alpha_min terminal value of alpha */ void kohonen_som_tracer(const std::vector> &X, diff --git a/numerical_methods/durand_kerner_roots.cpp b/numerical_methods/durand_kerner_roots.cpp index 70288d2c5..80464412a 100644 --- a/numerical_methods/durand_kerner_roots.cpp +++ b/numerical_methods/durand_kerner_roots.cpp @@ -18,11 +18,14 @@ * ``` * Sample implementation results to compute approximate roots of the equation * \f$x^4-1=0\f$:\n - * ![Error - * evolution](https://raw.githubusercontent.com/kvedala/C-Plus-Plus/docs/images/numerical_methods/durand_kerner_error.svg) - * - * ![Roots - * evolution](https://raw.githubusercontent.com/kvedala/C-Plus-Plus/docs/images/numerical_methods/durand_kerner_roots.svg) + * Error evolution during root approximations computed every
+ * iteration. Roots evolution - shows the initial approximation of the
+ * roots and their convergence to a final approximation along with the iterative
+ * approximations */ #include @@ -52,7 +55,7 @@ std::complex poly_function(const std::valarray &coeffs, int n; // #ifdef _OPENMP - // #pragma omp parallel for reduction(+ : real, imag) + // #pragma omp target teams distribute reduction(+ : real, imag) // #endif for (n = 0; n < coeffs.size(); n++) { std::complex tmp = @@ -132,7 +135,6 @@ std::pair durand_kerner_algo( bool break_loop = false; while (!check_termination(tol_condition) && iter < INT16_MAX && !break_loop) { - std::complex delta = 0; tol_condition = 0; iter++; break_loop = false; @@ -175,9 +177,10 @@ std::pair durand_kerner_algo( if (break_loop) break; - if (log_file.is_open()) + if (log_file.is_open()) { for (n = 0; n < roots->size(); n++) log_file << complex_str((*roots)[n]) << ","; + } #if defined(DEBUG) || !defined(NDEBUG) if (iter % 500 == 0) {