From cf3c8fae9f7d8ecee710a8ead1e9bb11ffc099f9 Mon Sep 17 00:00:00 2001 From: Debashis Nandi Date: Fri, 12 Jun 2026 01:38:32 +0530 Subject: [PATCH 01/13] feat: repo restructure --- CMakeLists.txt | 3 --- include/0006_BitwiseAlgorithms/CMakeLists.txt | 0 include/CMakeLists.txt | 6 ------ src/0001_Basics/CMakeLists.txt | 6 +++++- src/0001_Basics/Node.cc | 2 +- .../0001_Basics => src/0001_basics/headers}/Node.h | 0 src/0002_Tree/0001_BinarySearchTree.cc | 2 +- src/0002_Tree/CMakeLists.txt | 6 +++++- .../0002_tree/headers}/0001_BinarySearchTree.h | 0 src/0003_Graph/0001_BreadthFirstSearch.cc | 2 +- src/0003_Graph/0002_DepthFirstSearch.cc | 2 +- src/0003_Graph/0003_TopologicalSort.cc | 2 +- src/0003_Graph/0004_StronglyConnectedComponents.cc | 2 +- src/0003_Graph/0005_HamiltonianPathAndCycle.cc | 2 +- src/0003_Graph/0006_EulerianPathAndCircuit.cc | 2 +- .../0007_MinimumSpanningTreeKruskalAlgorithm.cc | 2 +- .../0008_MinimumSpanningTreePrimAlgorithm.cc | 2 +- .../0009_SingleSourceShortestPathBellmanFord.cc | 2 +- .../0010_DirectedAcyclicGraphShortestPath.cc | 2 +- .../0011_SingleSourceShortestPathDijkstra.cc | 2 +- .../0012_DifferenceConstraintsShortestPaths.cc | 2 +- .../0013_AllPairsShortestPathsFloydWarshall.cc | 2 +- .../0014_AllPairsShortestPathsJohnson.cc | 2 +- src/0003_Graph/0015_MaximumFlowFordFulkerson.cc | 2 +- src/0003_Graph/0016_MaximumFlowEdmondsKarp.cc | 2 +- src/0003_Graph/0017_MaximumBipartiteMatching.cc | 2 +- .../0018_MaximumFlowGoldbergGenericPushRelabel.cc | 2 +- src/0003_Graph/0019_MaximumFlowRelabelToFront.cc | 2 +- src/0003_Graph/CMakeLists.txt | 6 +++++- .../0003_graph/headers}/0001_BreadthFirstSearch.h | 0 .../0003_graph/headers}/0002_DepthFirstSearch.h | 0 .../0003_graph/headers}/0003_TopologicalSort.h | 0 .../headers}/0004_StronglyConnectedComponents.h | 0 .../headers}/0005_HamiltonianPathAndCycle.h | 0 .../headers}/0006_EulerianPathAndCircuit.h | 0 .../0007_MinimumSpanningTreeKruskalAlgorithm.h | 0 .../0008_MinimumSpanningTreePrimAlgorithm.h | 0 .../0009_SingleSourceShortestPathBellmanFord.h | 0 .../0010_DirectedAcyclicGraphShortestPath.h | 0 .../0011_SingleSourceShortestPathDijkstra.h | 0 .../0012_DifferenceConstraintsShortestPaths.h | 0 .../0013_AllPairsShortestPathsFloydWarshall.h | 0 .../headers}/0014_AllPairsShortestPathsJohnson.h | 0 .../headers}/0015_MaximumFlowFordFulkerson.h | 0 .../headers}/0016_MaximumFlowEdmondsKarp.h | 0 .../headers}/0017_MaximumBipartiteMatching.h | 0 .../0018_MaximumFlowGoldbergGenericPushRelabel.h | 0 .../headers}/0019_MaximumFlowRelabelToFront.h | 0 src/0004_GreedyAlgorithms/CMakeLists.txt | 0 .../0001_FibonacciNumber.cc | 2 +- .../0002_TribonacciNumber.cc | 2 +- .../0003_ClimbingStairs.cc | 2 +- .../0004_MinimumCostClimbingStairs.cc | 2 +- .../0005_HouseRobber1.cc | 2 +- .../0006_HouseRobber2.cc | 2 +- .../0007_DecodeWays.cc | 2 +- .../0008_TilingProblem.cc | 2 +- .../0009_FriendsPairingProblem.cc | 2 +- .../0010_WaysToCoverDistance.cc | 2 +- .../0011_CountWaysToReachNthStairIncludeOrder.cc | 2 +- .../0012_CountWaysToReachNthStairExcludeOrder.cc | 2 +- .../0013_KnapsackProblem.cc | 2 +- .../0014_SubsetSumProblem.cc | 2 +- .../0015_CountSubsetsForSum.cc | 2 +- .../0016_PartitionEqualSubsetSum.cc | 2 +- .../0017_TargetSum.cc | 2 +- .../CMakeLists.txt | 6 +++++- .../headers}/0001_FibonacciNumber.h | 0 .../headers}/0002_TribonacciNumber.h | 0 .../headers}/0003_ClimbingStairs.h | 0 .../headers}/0004_MinimumCostClimbingStairs.h | 0 .../headers}/0005_HouseRobber1.h | 0 .../headers}/0006_HouseRobber2.h | 0 .../headers}/0007_DecodeWays.h | 0 .../headers}/0008_TilingProblem.h | 0 .../headers}/0009_FriendsPairingProblem.h | 0 .../headers}/0010_WaysToCoverDistance.h | 0 .../0011_CountWaysToReachNthStairIncludeOrder.h | 0 .../0012_CountWaysToReachNthStairExcludeOrder.h | 0 .../headers}/0013_KnapsackProblem.h | 0 .../headers}/0014_SubsetSumProblem.h | 0 .../headers}/0015_CountSubsetsForSum.h | 0 .../headers}/0016_PartitionEqualSubsetSum.h | 0 .../headers}/0017_TargetSum.h | 0 .../0005_greedy_algorithms}/CMakeLists.txt | 0 src/0006_BitwiseAlgorithms/CMakeLists.txt | 0 .../0006_bitwise_algorithms}/CMakeLists.txt | 0 src/CMakeLists.txt | 12 ++++++------ tests/0000_CommonUtilities/CMakeLists.txt | 0 .../0000_common_utilities}/CMakeLists.txt | 0 .../UnitTestHelper.h | 0 tests/0001_Basics/NodeTest.cc | 2 +- tests/0002_Tree/0001_BinarySearchTreeTest.cc | 4 ++-- tests/0003_Graph/0001_BreadthFirstSearchTest.cc | 4 ++-- tests/0003_Graph/0002_DepthFirstSearchTest.cc | 4 ++-- tests/0003_Graph/0003_TopologicalSortTest.cc | 4 ++-- .../0004_StronglyConnectedComponentsTest.cc | 4 ++-- .../0003_Graph/0005_HamiltonianPathAndCycleTest.cc | 4 ++-- .../0003_Graph/0006_EulerianPathAndCircuitTest.cc | 4 ++-- ...0007_MinimumSpanningTreeKruskalAlgorithmTest.cc | 4 ++-- .../0008_MinimumSpanningTreePrimAlgorithmTest.cc | 4 ++-- ...0009_SingleSourceShortestPathBellmanFordTest.cc | 4 ++-- .../0010_DirectedAcyclicGraphShortestPathTest.cc | 4 ++-- .../0011_SingleSourceShortestPathDijkstraTest.cc | 4 ++-- .../0012_DifferenceConstraintsShortestPathsTest.cc | 4 ++-- .../0013_AllPairsShortestPathsFloydWarshallTest.cc | 4 ++-- .../0014_AllPairsShortestPathsJohnsonTest.cc | 4 ++-- .../0015_MaximumFlowFordFulkersonTest.cc | 4 ++-- .../0003_Graph/0016_MaximumFlowEdmondsKarpTest.cc | 4 ++-- .../0017_MaximumBipartiteMatchingTest.cc | 4 ++-- ...18_MaximumFlowGoldbergGenericPushRelabelTest.cc | 4 ++-- .../0019_MaximumFlowRelabelToFrontTest.cc | 4 ++-- tests/0004_GreedyAlgorithms/CMakeLists.txt | 0 .../0001_FibonacciNumberTest.cc | 2 +- .../0002_TribonacciNumberTest.cc | 2 +- .../0003_ClimbingStairsTest.cc | 2 +- .../0004_MinimumCostClimbingStairsTest.cc | 2 +- .../0005_HouseRobber1Test.cc | 2 +- .../0006_HouseRobber2Test.cc | 2 +- .../0007_DecodeWaysTest.cc | 2 +- .../0008_TilingProblemTest.cc | 2 +- .../0009_FriendsPairingProblemTest.cc | 2 +- .../0010_WaysToCoverDistanceTest.cc | 2 +- ...011_CountWaysToReachNthStairIncludeOrderTest.cc | 2 +- ...012_CountWaysToReachNthStairExcludeOrderTest.cc | 2 +- .../0013_KnapsackProblemTest.cc | 2 +- .../0014_SubsetSumProblemTest.cc | 2 +- .../0015_CountSubsetsForSumTest.cc | 2 +- .../0016_PartitionEqualSubsetSumTest.cc | 2 +- .../0017_TargetSumTest.cc | 2 +- .../CMakeLists.txt | 0 .../0005_greedy_algorithms}/CMakeLists.txt | 0 tests/0006_BitwiseAlgorithms/CMakeLists.txt | 0 .../0006_bitwise_algorithms}/CMakeLists.txt | 0 tests/CMakeLists.txt | 14 +++++++------- 135 files changed, 129 insertions(+), 122 deletions(-) delete mode 100644 include/0006_BitwiseAlgorithms/CMakeLists.txt delete mode 100644 include/CMakeLists.txt rename {include/0001_Basics => src/0001_basics/headers}/Node.h (100%) rename {include/0002_Tree => src/0002_tree/headers}/0001_BinarySearchTree.h (100%) rename {include/0003_Graph => src/0003_graph/headers}/0001_BreadthFirstSearch.h (100%) rename {include/0003_Graph => src/0003_graph/headers}/0002_DepthFirstSearch.h (100%) rename {include/0003_Graph => src/0003_graph/headers}/0003_TopologicalSort.h (100%) rename {include/0003_Graph => src/0003_graph/headers}/0004_StronglyConnectedComponents.h (100%) rename {include/0003_Graph => src/0003_graph/headers}/0005_HamiltonianPathAndCycle.h (100%) rename {include/0003_Graph => src/0003_graph/headers}/0006_EulerianPathAndCircuit.h (100%) rename {include/0003_Graph => src/0003_graph/headers}/0007_MinimumSpanningTreeKruskalAlgorithm.h (100%) rename {include/0003_Graph => src/0003_graph/headers}/0008_MinimumSpanningTreePrimAlgorithm.h (100%) rename {include/0003_Graph => src/0003_graph/headers}/0009_SingleSourceShortestPathBellmanFord.h (100%) rename {include/0003_Graph => src/0003_graph/headers}/0010_DirectedAcyclicGraphShortestPath.h (100%) rename {include/0003_Graph => src/0003_graph/headers}/0011_SingleSourceShortestPathDijkstra.h (100%) rename {include/0003_Graph => src/0003_graph/headers}/0012_DifferenceConstraintsShortestPaths.h (100%) rename {include/0003_Graph => src/0003_graph/headers}/0013_AllPairsShortestPathsFloydWarshall.h (100%) rename {include/0003_Graph => src/0003_graph/headers}/0014_AllPairsShortestPathsJohnson.h (100%) rename {include/0003_Graph => src/0003_graph/headers}/0015_MaximumFlowFordFulkerson.h (100%) rename {include/0003_Graph => src/0003_graph/headers}/0016_MaximumFlowEdmondsKarp.h (100%) rename {include/0003_Graph => src/0003_graph/headers}/0017_MaximumBipartiteMatching.h (100%) rename {include/0003_Graph => src/0003_graph/headers}/0018_MaximumFlowGoldbergGenericPushRelabel.h (100%) rename {include/0003_Graph => src/0003_graph/headers}/0019_MaximumFlowRelabelToFront.h (100%) delete mode 100644 src/0004_GreedyAlgorithms/CMakeLists.txt rename src/{0005_DynamicProgramming => 0004_dynamic_programming}/0001_FibonacciNumber.cc (87%) rename src/{0005_DynamicProgramming => 0004_dynamic_programming}/0002_TribonacciNumber.cc (89%) rename src/{0005_DynamicProgramming => 0004_dynamic_programming}/0003_ClimbingStairs.cc (88%) rename src/{0005_DynamicProgramming => 0004_dynamic_programming}/0004_MinimumCostClimbingStairs.cc (93%) rename src/{0005_DynamicProgramming => 0004_dynamic_programming}/0005_HouseRobber1.cc (94%) rename src/{0005_DynamicProgramming => 0004_dynamic_programming}/0006_HouseRobber2.cc (97%) rename src/{0005_DynamicProgramming => 0004_dynamic_programming}/0007_DecodeWays.cc (96%) rename src/{0005_DynamicProgramming => 0004_dynamic_programming}/0008_TilingProblem.cc (91%) rename src/{0005_DynamicProgramming => 0004_dynamic_programming}/0009_FriendsPairingProblem.cc (92%) rename src/{0005_DynamicProgramming => 0004_dynamic_programming}/0010_WaysToCoverDistance.cc (93%) rename src/{0005_DynamicProgramming => 0004_dynamic_programming}/0011_CountWaysToReachNthStairIncludeOrder.cc (91%) rename src/{0005_DynamicProgramming => 0004_dynamic_programming}/0012_CountWaysToReachNthStairExcludeOrder.cc (95%) rename src/{0005_DynamicProgramming => 0004_dynamic_programming}/0013_KnapsackProblem.cc (97%) rename src/{0005_DynamicProgramming => 0004_dynamic_programming}/0014_SubsetSumProblem.cc (97%) rename src/{0005_DynamicProgramming => 0004_dynamic_programming}/0015_CountSubsetsForSum.cc (95%) rename src/{0005_DynamicProgramming => 0004_dynamic_programming}/0016_PartitionEqualSubsetSum.cc (96%) rename src/{0005_DynamicProgramming => 0004_dynamic_programming}/0017_TargetSum.cc (96%) rename src/{0005_DynamicProgramming => 0004_dynamic_programming}/CMakeLists.txt (86%) rename {include/0005_DynamicProgramming => src/0004_dynamic_programming/headers}/0001_FibonacciNumber.h (100%) rename {include/0005_DynamicProgramming => src/0004_dynamic_programming/headers}/0002_TribonacciNumber.h (100%) rename {include/0005_DynamicProgramming => src/0004_dynamic_programming/headers}/0003_ClimbingStairs.h (100%) rename {include/0005_DynamicProgramming => src/0004_dynamic_programming/headers}/0004_MinimumCostClimbingStairs.h (100%) rename {include/0005_DynamicProgramming => src/0004_dynamic_programming/headers}/0005_HouseRobber1.h (100%) rename {include/0005_DynamicProgramming => src/0004_dynamic_programming/headers}/0006_HouseRobber2.h (100%) rename {include/0005_DynamicProgramming => src/0004_dynamic_programming/headers}/0007_DecodeWays.h (100%) rename {include/0005_DynamicProgramming => src/0004_dynamic_programming/headers}/0008_TilingProblem.h (100%) rename {include/0005_DynamicProgramming => src/0004_dynamic_programming/headers}/0009_FriendsPairingProblem.h (100%) rename {include/0005_DynamicProgramming => src/0004_dynamic_programming/headers}/0010_WaysToCoverDistance.h (100%) rename {include/0005_DynamicProgramming => src/0004_dynamic_programming/headers}/0011_CountWaysToReachNthStairIncludeOrder.h (100%) rename {include/0005_DynamicProgramming => src/0004_dynamic_programming/headers}/0012_CountWaysToReachNthStairExcludeOrder.h (100%) rename {include/0005_DynamicProgramming => src/0004_dynamic_programming/headers}/0013_KnapsackProblem.h (100%) rename {include/0005_DynamicProgramming => src/0004_dynamic_programming/headers}/0014_SubsetSumProblem.h (100%) rename {include/0005_DynamicProgramming => src/0004_dynamic_programming/headers}/0015_CountSubsetsForSum.h (100%) rename {include/0005_DynamicProgramming => src/0004_dynamic_programming/headers}/0016_PartitionEqualSubsetSum.h (100%) rename {include/0005_DynamicProgramming => src/0004_dynamic_programming/headers}/0017_TargetSum.h (100%) rename {include/0001_Basics => src/0005_greedy_algorithms}/CMakeLists.txt (100%) delete mode 100644 src/0006_BitwiseAlgorithms/CMakeLists.txt rename {include/0002_Tree => src/0006_bitwise_algorithms}/CMakeLists.txt (100%) delete mode 100644 tests/0000_CommonUtilities/CMakeLists.txt rename {include/0003_Graph => tests/0000_common_utilities}/CMakeLists.txt (100%) rename tests/{0000_CommonUtilities => 0000_common_utilities}/UnitTestHelper.h (100%) delete mode 100644 tests/0004_GreedyAlgorithms/CMakeLists.txt rename tests/{0005_DynamicProgramming => 0004_dynamic_programming}/0001_FibonacciNumberTest.cc (89%) rename tests/{0005_DynamicProgramming => 0004_dynamic_programming}/0002_TribonacciNumberTest.cc (89%) rename tests/{0005_DynamicProgramming => 0004_dynamic_programming}/0003_ClimbingStairsTest.cc (89%) rename tests/{0005_DynamicProgramming => 0004_dynamic_programming}/0004_MinimumCostClimbingStairsTest.cc (90%) rename tests/{0005_DynamicProgramming => 0004_dynamic_programming}/0005_HouseRobber1Test.cc (92%) rename tests/{0005_DynamicProgramming => 0004_dynamic_programming}/0006_HouseRobber2Test.cc (94%) rename tests/{0005_DynamicProgramming => 0004_dynamic_programming}/0007_DecodeWaysTest.cc (93%) rename tests/{0005_DynamicProgramming => 0004_dynamic_programming}/0008_TilingProblemTest.cc (91%) rename tests/{0005_DynamicProgramming => 0004_dynamic_programming}/0009_FriendsPairingProblemTest.cc (97%) rename tests/{0005_DynamicProgramming => 0004_dynamic_programming}/0010_WaysToCoverDistanceTest.cc (97%) rename tests/{0005_DynamicProgramming => 0004_dynamic_programming}/0011_CountWaysToReachNthStairIncludeOrderTest.cc (90%) rename tests/{0005_DynamicProgramming => 0004_dynamic_programming}/0012_CountWaysToReachNthStairExcludeOrderTest.cc (90%) rename tests/{0005_DynamicProgramming => 0004_dynamic_programming}/0013_KnapsackProblemTest.cc (95%) rename tests/{0005_DynamicProgramming => 0004_dynamic_programming}/0014_SubsetSumProblemTest.cc (91%) rename tests/{0005_DynamicProgramming => 0004_dynamic_programming}/0015_CountSubsetsForSumTest.cc (91%) rename tests/{0005_DynamicProgramming => 0004_dynamic_programming}/0016_PartitionEqualSubsetSumTest.cc (90%) rename tests/{0005_DynamicProgramming => 0004_dynamic_programming}/0017_TargetSumTest.cc (95%) rename tests/{0005_DynamicProgramming => 0004_dynamic_programming}/CMakeLists.txt (100%) rename {include/0004_GreedyAlgorithms => tests/0005_greedy_algorithms}/CMakeLists.txt (100%) delete mode 100644 tests/0006_BitwiseAlgorithms/CMakeLists.txt rename {include/0005_DynamicProgramming => tests/0006_bitwise_algorithms}/CMakeLists.txt (100%) diff --git a/CMakeLists.txt b/CMakeLists.txt index 159e956..d919238 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -19,9 +19,6 @@ if(CLANG_TIDY_EXE) ) endif() -include_directories(${CMAKE_SOURCE_DIR}/include) - -add_subdirectory(include) add_subdirectory(src) cmake_policy(SET CMP0135 NEW) diff --git a/include/0006_BitwiseAlgorithms/CMakeLists.txt b/include/0006_BitwiseAlgorithms/CMakeLists.txt deleted file mode 100644 index e69de29..0000000 diff --git a/include/CMakeLists.txt b/include/CMakeLists.txt deleted file mode 100644 index 65d79e1..0000000 --- a/include/CMakeLists.txt +++ /dev/null @@ -1,6 +0,0 @@ -add_subdirectory(0001_Basics) -add_subdirectory(0002_Tree) -add_subdirectory(0003_Graph) -add_subdirectory(0004_GreedyAlgorithms) -add_subdirectory(0005_DynamicProgramming) -add_subdirectory(0006_BitwiseAlgorithms) \ No newline at end of file diff --git a/src/0001_Basics/CMakeLists.txt b/src/0001_Basics/CMakeLists.txt index 199222f..477c6cd 100644 --- a/src/0001_Basics/CMakeLists.txt +++ b/src/0001_Basics/CMakeLists.txt @@ -4,4 +4,8 @@ set(0001BASICS_SOURCES ) # Create a library target -add_library(0001BASICS ${0001BASICS_SOURCES}) \ No newline at end of file +add_library(0001BASICS ${0001BASICS_SOURCES}) + +target_include_directories(0001BASICS PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}/headers +) \ No newline at end of file diff --git a/src/0001_Basics/Node.cc b/src/0001_Basics/Node.cc index 6a377d5..df1effa 100644 --- a/src/0001_Basics/Node.cc +++ b/src/0001_Basics/Node.cc @@ -1,4 +1,4 @@ -#include <0001_Basics/Node.h> +#include "Node.h" Node::Node() { diff --git a/include/0001_Basics/Node.h b/src/0001_basics/headers/Node.h similarity index 100% rename from include/0001_Basics/Node.h rename to src/0001_basics/headers/Node.h diff --git a/src/0002_Tree/0001_BinarySearchTree.cc b/src/0002_Tree/0001_BinarySearchTree.cc index 36e3489..ba78751 100644 --- a/src/0002_Tree/0001_BinarySearchTree.cc +++ b/src/0002_Tree/0001_BinarySearchTree.cc @@ -1,4 +1,4 @@ -#include <0002_Tree/0001_BinarySearchTree.h> +#include "0001_BinarySearchTree.h" #include #include using namespace std; diff --git a/src/0002_Tree/CMakeLists.txt b/src/0002_Tree/CMakeLists.txt index cc7027a..5508146 100644 --- a/src/0002_Tree/CMakeLists.txt +++ b/src/0002_Tree/CMakeLists.txt @@ -4,4 +4,8 @@ set(0002TREE_SOURCES ) # Create a library target -add_library(0002TREE ${0002TREE_SOURCES}) \ No newline at end of file +add_library(0002TREE ${0002TREE_SOURCES}) + +target_include_directories(0002TREE PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}/headers +) \ No newline at end of file diff --git a/include/0002_Tree/0001_BinarySearchTree.h b/src/0002_tree/headers/0001_BinarySearchTree.h similarity index 100% rename from include/0002_Tree/0001_BinarySearchTree.h rename to src/0002_tree/headers/0001_BinarySearchTree.h diff --git a/src/0003_Graph/0001_BreadthFirstSearch.cc b/src/0003_Graph/0001_BreadthFirstSearch.cc index d16271a..9a8b1ac 100644 --- a/src/0003_Graph/0001_BreadthFirstSearch.cc +++ b/src/0003_Graph/0001_BreadthFirstSearch.cc @@ -1,4 +1,4 @@ -#include <0003_Graph/0001_BreadthFirstSearch.h> +#include "0001_BreadthFirstSearch.h" #include #include #include diff --git a/src/0003_Graph/0002_DepthFirstSearch.cc b/src/0003_Graph/0002_DepthFirstSearch.cc index 873fe65..3cbc49a 100644 --- a/src/0003_Graph/0002_DepthFirstSearch.cc +++ b/src/0003_Graph/0002_DepthFirstSearch.cc @@ -1,4 +1,4 @@ -#include <0003_Graph/0002_DepthFirstSearch.h> +#include "0002_DepthFirstSearch.h" #include #include #include diff --git a/src/0003_Graph/0003_TopologicalSort.cc b/src/0003_Graph/0003_TopologicalSort.cc index 5cf20c2..3d4d1cb 100644 --- a/src/0003_Graph/0003_TopologicalSort.cc +++ b/src/0003_Graph/0003_TopologicalSort.cc @@ -1,4 +1,4 @@ -#include <0003_Graph/0003_TopologicalSort.h> +#include "0003_TopologicalSort.h" #include #include #include diff --git a/src/0003_Graph/0004_StronglyConnectedComponents.cc b/src/0003_Graph/0004_StronglyConnectedComponents.cc index f3d8efe..7a99e34 100644 --- a/src/0003_Graph/0004_StronglyConnectedComponents.cc +++ b/src/0003_Graph/0004_StronglyConnectedComponents.cc @@ -1,4 +1,4 @@ -#include <0003_Graph/0004_StronglyConnectedComponents.h> +#include "0004_StronglyConnectedComponents.h" #include #include #include diff --git a/src/0003_Graph/0005_HamiltonianPathAndCycle.cc b/src/0003_Graph/0005_HamiltonianPathAndCycle.cc index 1466b2a..bfa99b5 100644 --- a/src/0003_Graph/0005_HamiltonianPathAndCycle.cc +++ b/src/0003_Graph/0005_HamiltonianPathAndCycle.cc @@ -1,4 +1,4 @@ -#include <0003_Graph/0005_HamiltonianPathAndCycle.h> +#include "0005_HamiltonianPathAndCycle.h" using namespace std; namespace HamiltonianPathAndCycle diff --git a/src/0003_Graph/0006_EulerianPathAndCircuit.cc b/src/0003_Graph/0006_EulerianPathAndCircuit.cc index 88f4cd9..ee132ca 100644 --- a/src/0003_Graph/0006_EulerianPathAndCircuit.cc +++ b/src/0003_Graph/0006_EulerianPathAndCircuit.cc @@ -1,4 +1,4 @@ -#include <0003_Graph/0006_EulerianPathAndCircuit.h> +#include "0006_EulerianPathAndCircuit.h" #include #include using namespace std; diff --git a/src/0003_Graph/0007_MinimumSpanningTreeKruskalAlgorithm.cc b/src/0003_Graph/0007_MinimumSpanningTreeKruskalAlgorithm.cc index 90d3d8f..20bea2b 100644 --- a/src/0003_Graph/0007_MinimumSpanningTreeKruskalAlgorithm.cc +++ b/src/0003_Graph/0007_MinimumSpanningTreeKruskalAlgorithm.cc @@ -1,4 +1,4 @@ -#include <0003_Graph/0007_MinimumSpanningTreeKruskalAlgorithm.h> +#include "0007_MinimumSpanningTreeKruskalAlgorithm.h" #include #include using namespace std; diff --git a/src/0003_Graph/0008_MinimumSpanningTreePrimAlgorithm.cc b/src/0003_Graph/0008_MinimumSpanningTreePrimAlgorithm.cc index 83340b8..1b36027 100644 --- a/src/0003_Graph/0008_MinimumSpanningTreePrimAlgorithm.cc +++ b/src/0003_Graph/0008_MinimumSpanningTreePrimAlgorithm.cc @@ -1,4 +1,4 @@ -#include <0003_Graph/0008_MinimumSpanningTreePrimAlgorithm.h> +#include "0008_MinimumSpanningTreePrimAlgorithm.h" #include using namespace std; diff --git a/src/0003_Graph/0009_SingleSourceShortestPathBellmanFord.cc b/src/0003_Graph/0009_SingleSourceShortestPathBellmanFord.cc index 5b036ac..b059b74 100644 --- a/src/0003_Graph/0009_SingleSourceShortestPathBellmanFord.cc +++ b/src/0003_Graph/0009_SingleSourceShortestPathBellmanFord.cc @@ -1,4 +1,4 @@ -#include <0003_Graph/0009_SingleSourceShortestPathBellmanFord.h> +#include "0009_SingleSourceShortestPathBellmanFord.h" #include #include using namespace std; diff --git a/src/0003_Graph/0010_DirectedAcyclicGraphShortestPath.cc b/src/0003_Graph/0010_DirectedAcyclicGraphShortestPath.cc index a0d1ab2..8f4cd81 100644 --- a/src/0003_Graph/0010_DirectedAcyclicGraphShortestPath.cc +++ b/src/0003_Graph/0010_DirectedAcyclicGraphShortestPath.cc @@ -1,4 +1,4 @@ -#include <0003_Graph/0010_DirectedAcyclicGraphShortestPath.h> +#include "0010_DirectedAcyclicGraphShortestPath.h" #include #include using namespace std; diff --git a/src/0003_Graph/0011_SingleSourceShortestPathDijkstra.cc b/src/0003_Graph/0011_SingleSourceShortestPathDijkstra.cc index d84e844..e796e37 100644 --- a/src/0003_Graph/0011_SingleSourceShortestPathDijkstra.cc +++ b/src/0003_Graph/0011_SingleSourceShortestPathDijkstra.cc @@ -1,4 +1,4 @@ -#include <0003_Graph/0011_SingleSourceShortestPathDijkstra.h> +#include "0011_SingleSourceShortestPathDijkstra.h" #include #include using namespace std; diff --git a/src/0003_Graph/0012_DifferenceConstraintsShortestPaths.cc b/src/0003_Graph/0012_DifferenceConstraintsShortestPaths.cc index 91bbdfd..8764ba6 100644 --- a/src/0003_Graph/0012_DifferenceConstraintsShortestPaths.cc +++ b/src/0003_Graph/0012_DifferenceConstraintsShortestPaths.cc @@ -1,4 +1,4 @@ -#include <0003_Graph/0012_DifferenceConstraintsShortestPaths.h> +#include "0012_DifferenceConstraintsShortestPaths.h" #include using namespace std; diff --git a/src/0003_Graph/0013_AllPairsShortestPathsFloydWarshall.cc b/src/0003_Graph/0013_AllPairsShortestPathsFloydWarshall.cc index d3eeea6..ffd51d9 100644 --- a/src/0003_Graph/0013_AllPairsShortestPathsFloydWarshall.cc +++ b/src/0003_Graph/0013_AllPairsShortestPathsFloydWarshall.cc @@ -1,4 +1,4 @@ -#include <0003_Graph/0013_AllPairsShortestPathsFloydWarshall.h> +#include "0013_AllPairsShortestPathsFloydWarshall.h" #include using namespace std; diff --git a/src/0003_Graph/0014_AllPairsShortestPathsJohnson.cc b/src/0003_Graph/0014_AllPairsShortestPathsJohnson.cc index 05d1df2..e9f9ab2 100644 --- a/src/0003_Graph/0014_AllPairsShortestPathsJohnson.cc +++ b/src/0003_Graph/0014_AllPairsShortestPathsJohnson.cc @@ -1,4 +1,4 @@ -#include <0003_Graph/0014_AllPairsShortestPathsJohnson.h> +#include "0014_AllPairsShortestPathsJohnson.h" #include using namespace std; diff --git a/src/0003_Graph/0015_MaximumFlowFordFulkerson.cc b/src/0003_Graph/0015_MaximumFlowFordFulkerson.cc index d7c41ed..dd8d48d 100644 --- a/src/0003_Graph/0015_MaximumFlowFordFulkerson.cc +++ b/src/0003_Graph/0015_MaximumFlowFordFulkerson.cc @@ -1,4 +1,4 @@ -#include <0003_Graph/0015_MaximumFlowFordFulkerson.h> +#include "0015_MaximumFlowFordFulkerson.h" #include using namespace std; diff --git a/src/0003_Graph/0016_MaximumFlowEdmondsKarp.cc b/src/0003_Graph/0016_MaximumFlowEdmondsKarp.cc index 25340fe..627a2a6 100644 --- a/src/0003_Graph/0016_MaximumFlowEdmondsKarp.cc +++ b/src/0003_Graph/0016_MaximumFlowEdmondsKarp.cc @@ -1,4 +1,4 @@ -#include <0003_Graph/0016_MaximumFlowEdmondsKarp.h> +#include "0016_MaximumFlowEdmondsKarp.h" #include #include using namespace std; diff --git a/src/0003_Graph/0017_MaximumBipartiteMatching.cc b/src/0003_Graph/0017_MaximumBipartiteMatching.cc index 18224a2..7c55ce6 100644 --- a/src/0003_Graph/0017_MaximumBipartiteMatching.cc +++ b/src/0003_Graph/0017_MaximumBipartiteMatching.cc @@ -1,4 +1,4 @@ -#include <0003_Graph/0017_MaximumBipartiteMatching.h> +#include "0017_MaximumBipartiteMatching.h" #include #include using namespace std; diff --git a/src/0003_Graph/0018_MaximumFlowGoldbergGenericPushRelabel.cc b/src/0003_Graph/0018_MaximumFlowGoldbergGenericPushRelabel.cc index 23f7923..63c1475 100644 --- a/src/0003_Graph/0018_MaximumFlowGoldbergGenericPushRelabel.cc +++ b/src/0003_Graph/0018_MaximumFlowGoldbergGenericPushRelabel.cc @@ -1,4 +1,4 @@ -#include <0003_Graph/0018_MaximumFlowGoldbergGenericPushRelabel.h> +#include "0018_MaximumFlowGoldbergGenericPushRelabel.h" #include using namespace std; diff --git a/src/0003_Graph/0019_MaximumFlowRelabelToFront.cc b/src/0003_Graph/0019_MaximumFlowRelabelToFront.cc index d50176d..034f5bf 100644 --- a/src/0003_Graph/0019_MaximumFlowRelabelToFront.cc +++ b/src/0003_Graph/0019_MaximumFlowRelabelToFront.cc @@ -1,4 +1,4 @@ -#include <0003_Graph/0019_MaximumFlowRelabelToFront.h> +#include "0019_MaximumFlowRelabelToFront.h" #include #include using namespace std; diff --git a/src/0003_Graph/CMakeLists.txt b/src/0003_Graph/CMakeLists.txt index 0b9177d..02f8a77 100644 --- a/src/0003_Graph/CMakeLists.txt +++ b/src/0003_Graph/CMakeLists.txt @@ -23,4 +23,8 @@ set(0003GRAPH_SOURCES ) # Create a library target -add_library(0003GRAPH ${0003GRAPH_SOURCES}) \ No newline at end of file +add_library(0003GRAPH ${0003GRAPH_SOURCES}) + +target_include_directories(0003GRAPH PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}/headers +) \ No newline at end of file diff --git a/include/0003_Graph/0001_BreadthFirstSearch.h b/src/0003_graph/headers/0001_BreadthFirstSearch.h similarity index 100% rename from include/0003_Graph/0001_BreadthFirstSearch.h rename to src/0003_graph/headers/0001_BreadthFirstSearch.h diff --git a/include/0003_Graph/0002_DepthFirstSearch.h b/src/0003_graph/headers/0002_DepthFirstSearch.h similarity index 100% rename from include/0003_Graph/0002_DepthFirstSearch.h rename to src/0003_graph/headers/0002_DepthFirstSearch.h diff --git a/include/0003_Graph/0003_TopologicalSort.h b/src/0003_graph/headers/0003_TopologicalSort.h similarity index 100% rename from include/0003_Graph/0003_TopologicalSort.h rename to src/0003_graph/headers/0003_TopologicalSort.h diff --git a/include/0003_Graph/0004_StronglyConnectedComponents.h b/src/0003_graph/headers/0004_StronglyConnectedComponents.h similarity index 100% rename from include/0003_Graph/0004_StronglyConnectedComponents.h rename to src/0003_graph/headers/0004_StronglyConnectedComponents.h diff --git a/include/0003_Graph/0005_HamiltonianPathAndCycle.h b/src/0003_graph/headers/0005_HamiltonianPathAndCycle.h similarity index 100% rename from include/0003_Graph/0005_HamiltonianPathAndCycle.h rename to src/0003_graph/headers/0005_HamiltonianPathAndCycle.h diff --git a/include/0003_Graph/0006_EulerianPathAndCircuit.h b/src/0003_graph/headers/0006_EulerianPathAndCircuit.h similarity index 100% rename from include/0003_Graph/0006_EulerianPathAndCircuit.h rename to src/0003_graph/headers/0006_EulerianPathAndCircuit.h diff --git a/include/0003_Graph/0007_MinimumSpanningTreeKruskalAlgorithm.h b/src/0003_graph/headers/0007_MinimumSpanningTreeKruskalAlgorithm.h similarity index 100% rename from include/0003_Graph/0007_MinimumSpanningTreeKruskalAlgorithm.h rename to src/0003_graph/headers/0007_MinimumSpanningTreeKruskalAlgorithm.h diff --git a/include/0003_Graph/0008_MinimumSpanningTreePrimAlgorithm.h b/src/0003_graph/headers/0008_MinimumSpanningTreePrimAlgorithm.h similarity index 100% rename from include/0003_Graph/0008_MinimumSpanningTreePrimAlgorithm.h rename to src/0003_graph/headers/0008_MinimumSpanningTreePrimAlgorithm.h diff --git a/include/0003_Graph/0009_SingleSourceShortestPathBellmanFord.h b/src/0003_graph/headers/0009_SingleSourceShortestPathBellmanFord.h similarity index 100% rename from include/0003_Graph/0009_SingleSourceShortestPathBellmanFord.h rename to src/0003_graph/headers/0009_SingleSourceShortestPathBellmanFord.h diff --git a/include/0003_Graph/0010_DirectedAcyclicGraphShortestPath.h b/src/0003_graph/headers/0010_DirectedAcyclicGraphShortestPath.h similarity index 100% rename from include/0003_Graph/0010_DirectedAcyclicGraphShortestPath.h rename to src/0003_graph/headers/0010_DirectedAcyclicGraphShortestPath.h diff --git a/include/0003_Graph/0011_SingleSourceShortestPathDijkstra.h b/src/0003_graph/headers/0011_SingleSourceShortestPathDijkstra.h similarity index 100% rename from include/0003_Graph/0011_SingleSourceShortestPathDijkstra.h rename to src/0003_graph/headers/0011_SingleSourceShortestPathDijkstra.h diff --git a/include/0003_Graph/0012_DifferenceConstraintsShortestPaths.h b/src/0003_graph/headers/0012_DifferenceConstraintsShortestPaths.h similarity index 100% rename from include/0003_Graph/0012_DifferenceConstraintsShortestPaths.h rename to src/0003_graph/headers/0012_DifferenceConstraintsShortestPaths.h diff --git a/include/0003_Graph/0013_AllPairsShortestPathsFloydWarshall.h b/src/0003_graph/headers/0013_AllPairsShortestPathsFloydWarshall.h similarity index 100% rename from include/0003_Graph/0013_AllPairsShortestPathsFloydWarshall.h rename to src/0003_graph/headers/0013_AllPairsShortestPathsFloydWarshall.h diff --git a/include/0003_Graph/0014_AllPairsShortestPathsJohnson.h b/src/0003_graph/headers/0014_AllPairsShortestPathsJohnson.h similarity index 100% rename from include/0003_Graph/0014_AllPairsShortestPathsJohnson.h rename to src/0003_graph/headers/0014_AllPairsShortestPathsJohnson.h diff --git a/include/0003_Graph/0015_MaximumFlowFordFulkerson.h b/src/0003_graph/headers/0015_MaximumFlowFordFulkerson.h similarity index 100% rename from include/0003_Graph/0015_MaximumFlowFordFulkerson.h rename to src/0003_graph/headers/0015_MaximumFlowFordFulkerson.h diff --git a/include/0003_Graph/0016_MaximumFlowEdmondsKarp.h b/src/0003_graph/headers/0016_MaximumFlowEdmondsKarp.h similarity index 100% rename from include/0003_Graph/0016_MaximumFlowEdmondsKarp.h rename to src/0003_graph/headers/0016_MaximumFlowEdmondsKarp.h diff --git a/include/0003_Graph/0017_MaximumBipartiteMatching.h b/src/0003_graph/headers/0017_MaximumBipartiteMatching.h similarity index 100% rename from include/0003_Graph/0017_MaximumBipartiteMatching.h rename to src/0003_graph/headers/0017_MaximumBipartiteMatching.h diff --git a/include/0003_Graph/0018_MaximumFlowGoldbergGenericPushRelabel.h b/src/0003_graph/headers/0018_MaximumFlowGoldbergGenericPushRelabel.h similarity index 100% rename from include/0003_Graph/0018_MaximumFlowGoldbergGenericPushRelabel.h rename to src/0003_graph/headers/0018_MaximumFlowGoldbergGenericPushRelabel.h diff --git a/include/0003_Graph/0019_MaximumFlowRelabelToFront.h b/src/0003_graph/headers/0019_MaximumFlowRelabelToFront.h similarity index 100% rename from include/0003_Graph/0019_MaximumFlowRelabelToFront.h rename to src/0003_graph/headers/0019_MaximumFlowRelabelToFront.h diff --git a/src/0004_GreedyAlgorithms/CMakeLists.txt b/src/0004_GreedyAlgorithms/CMakeLists.txt deleted file mode 100644 index e69de29..0000000 diff --git a/src/0005_DynamicProgramming/0001_FibonacciNumber.cc b/src/0004_dynamic_programming/0001_FibonacciNumber.cc similarity index 87% rename from src/0005_DynamicProgramming/0001_FibonacciNumber.cc rename to src/0004_dynamic_programming/0001_FibonacciNumber.cc index 417140c..47073aa 100644 --- a/src/0005_DynamicProgramming/0001_FibonacciNumber.cc +++ b/src/0004_dynamic_programming/0001_FibonacciNumber.cc @@ -1,4 +1,4 @@ -#include <0005_DynamicProgramming/0001_FibonacciNumber.h> +#include "0001_FibonacciNumber.h" namespace FibonacciNumber { diff --git a/src/0005_DynamicProgramming/0002_TribonacciNumber.cc b/src/0004_dynamic_programming/0002_TribonacciNumber.cc similarity index 89% rename from src/0005_DynamicProgramming/0002_TribonacciNumber.cc rename to src/0004_dynamic_programming/0002_TribonacciNumber.cc index 8e3c95c..84a4c59 100644 --- a/src/0005_DynamicProgramming/0002_TribonacciNumber.cc +++ b/src/0004_dynamic_programming/0002_TribonacciNumber.cc @@ -1,4 +1,4 @@ -#include <0005_DynamicProgramming/0002_TribonacciNumber.h> +#include "0002_TribonacciNumber.h" namespace TribonacciNumber { diff --git a/src/0005_DynamicProgramming/0003_ClimbingStairs.cc b/src/0004_dynamic_programming/0003_ClimbingStairs.cc similarity index 88% rename from src/0005_DynamicProgramming/0003_ClimbingStairs.cc rename to src/0004_dynamic_programming/0003_ClimbingStairs.cc index 3dfdba6..6e365f8 100644 --- a/src/0005_DynamicProgramming/0003_ClimbingStairs.cc +++ b/src/0004_dynamic_programming/0003_ClimbingStairs.cc @@ -1,4 +1,4 @@ -#include <0005_DynamicProgramming/0003_ClimbingStairs.h> +#include "0003_ClimbingStairs.h" using namespace std; namespace ClimbingStairs diff --git a/src/0005_DynamicProgramming/0004_MinimumCostClimbingStairs.cc b/src/0004_dynamic_programming/0004_MinimumCostClimbingStairs.cc similarity index 93% rename from src/0005_DynamicProgramming/0004_MinimumCostClimbingStairs.cc rename to src/0004_dynamic_programming/0004_MinimumCostClimbingStairs.cc index d6b4cc1..661afc4 100644 --- a/src/0005_DynamicProgramming/0004_MinimumCostClimbingStairs.cc +++ b/src/0004_dynamic_programming/0004_MinimumCostClimbingStairs.cc @@ -1,4 +1,4 @@ -#include <0005_DynamicProgramming/0004_MinimumCostClimbingStairs.h> +#include "0004_MinimumCostClimbingStairs.h" #include namespace MinimumCostClimbingStairs diff --git a/src/0005_DynamicProgramming/0005_HouseRobber1.cc b/src/0004_dynamic_programming/0005_HouseRobber1.cc similarity index 94% rename from src/0005_DynamicProgramming/0005_HouseRobber1.cc rename to src/0004_dynamic_programming/0005_HouseRobber1.cc index 3bb1e18..2e3fb7f 100644 --- a/src/0005_DynamicProgramming/0005_HouseRobber1.cc +++ b/src/0004_dynamic_programming/0005_HouseRobber1.cc @@ -1,4 +1,4 @@ -#include <0005_DynamicProgramming/0005_HouseRobber1.h> +#include "0005_HouseRobber1.h" namespace HouseRobber1 { diff --git a/src/0005_DynamicProgramming/0006_HouseRobber2.cc b/src/0004_dynamic_programming/0006_HouseRobber2.cc similarity index 97% rename from src/0005_DynamicProgramming/0006_HouseRobber2.cc rename to src/0004_dynamic_programming/0006_HouseRobber2.cc index 42b4603..cbefdda 100644 --- a/src/0005_DynamicProgramming/0006_HouseRobber2.cc +++ b/src/0004_dynamic_programming/0006_HouseRobber2.cc @@ -1,4 +1,4 @@ -#include <0005_DynamicProgramming/0006_HouseRobber2.h> +#include "0006_HouseRobber2.h" namespace HouseRobber2 { diff --git a/src/0005_DynamicProgramming/0007_DecodeWays.cc b/src/0004_dynamic_programming/0007_DecodeWays.cc similarity index 96% rename from src/0005_DynamicProgramming/0007_DecodeWays.cc rename to src/0004_dynamic_programming/0007_DecodeWays.cc index 23464f5..bf93270 100644 --- a/src/0005_DynamicProgramming/0007_DecodeWays.cc +++ b/src/0004_dynamic_programming/0007_DecodeWays.cc @@ -1,4 +1,4 @@ -#include <0005_DynamicProgramming/0007_DecodeWays.h> +#include "0007_DecodeWays.h" namespace DecodeWays { diff --git a/src/0005_DynamicProgramming/0008_TilingProblem.cc b/src/0004_dynamic_programming/0008_TilingProblem.cc similarity index 91% rename from src/0005_DynamicProgramming/0008_TilingProblem.cc rename to src/0004_dynamic_programming/0008_TilingProblem.cc index 4b7e50d..d447c8d 100644 --- a/src/0005_DynamicProgramming/0008_TilingProblem.cc +++ b/src/0004_dynamic_programming/0008_TilingProblem.cc @@ -1,4 +1,4 @@ -#include <0005_DynamicProgramming/0008_TilingProblem.h> +#include "0008_TilingProblem.h" namespace TilingProblem { diff --git a/src/0005_DynamicProgramming/0009_FriendsPairingProblem.cc b/src/0004_dynamic_programming/0009_FriendsPairingProblem.cc similarity index 92% rename from src/0005_DynamicProgramming/0009_FriendsPairingProblem.cc rename to src/0004_dynamic_programming/0009_FriendsPairingProblem.cc index 4a3db08..fbea63f 100644 --- a/src/0005_DynamicProgramming/0009_FriendsPairingProblem.cc +++ b/src/0004_dynamic_programming/0009_FriendsPairingProblem.cc @@ -1,4 +1,4 @@ -#include <0005_DynamicProgramming/0009_FriendsPairingProblem.h> +#include "0009_FriendsPairingProblem.h" namespace FriendsPairingProblem { diff --git a/src/0005_DynamicProgramming/0010_WaysToCoverDistance.cc b/src/0004_dynamic_programming/0010_WaysToCoverDistance.cc similarity index 93% rename from src/0005_DynamicProgramming/0010_WaysToCoverDistance.cc rename to src/0004_dynamic_programming/0010_WaysToCoverDistance.cc index 5c3e90a..b2f0bce 100644 --- a/src/0005_DynamicProgramming/0010_WaysToCoverDistance.cc +++ b/src/0004_dynamic_programming/0010_WaysToCoverDistance.cc @@ -1,4 +1,4 @@ -#include <0005_DynamicProgramming/0010_WaysToCoverDistance.h> +#include "0010_WaysToCoverDistance.h" namespace WaysToCoverDistance { diff --git a/src/0005_DynamicProgramming/0011_CountWaysToReachNthStairIncludeOrder.cc b/src/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrder.cc similarity index 91% rename from src/0005_DynamicProgramming/0011_CountWaysToReachNthStairIncludeOrder.cc rename to src/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrder.cc index 42c20ba..f4467e2 100644 --- a/src/0005_DynamicProgramming/0011_CountWaysToReachNthStairIncludeOrder.cc +++ b/src/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrder.cc @@ -1,4 +1,4 @@ -#include <0005_DynamicProgramming/0011_CountWaysToReachNthStairIncludeOrder.h> +#include "0011_CountWaysToReachNthStairIncludeOrder.h" namespace CountWaysToReachNthStairIncludeOrder { diff --git a/src/0005_DynamicProgramming/0012_CountWaysToReachNthStairExcludeOrder.cc b/src/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrder.cc similarity index 95% rename from src/0005_DynamicProgramming/0012_CountWaysToReachNthStairExcludeOrder.cc rename to src/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrder.cc index 9b39bf8..0e71a69 100644 --- a/src/0005_DynamicProgramming/0012_CountWaysToReachNthStairExcludeOrder.cc +++ b/src/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrder.cc @@ -1,4 +1,4 @@ -#include <0005_DynamicProgramming/0012_CountWaysToReachNthStairExcludeOrder.h> +#include "0012_CountWaysToReachNthStairExcludeOrder.h" namespace CountWaysToReachNthStairExcludeOrder { diff --git a/src/0005_DynamicProgramming/0013_KnapsackProblem.cc b/src/0004_dynamic_programming/0013_KnapsackProblem.cc similarity index 97% rename from src/0005_DynamicProgramming/0013_KnapsackProblem.cc rename to src/0004_dynamic_programming/0013_KnapsackProblem.cc index d012a44..e9e5ba2 100644 --- a/src/0005_DynamicProgramming/0013_KnapsackProblem.cc +++ b/src/0004_dynamic_programming/0013_KnapsackProblem.cc @@ -1,4 +1,4 @@ -#include <0005_DynamicProgramming/0013_KnapsackProblem.h> +#include "0013_KnapsackProblem.h" namespace KnapsackProblem { diff --git a/src/0005_DynamicProgramming/0014_SubsetSumProblem.cc b/src/0004_dynamic_programming/0014_SubsetSumProblem.cc similarity index 97% rename from src/0005_DynamicProgramming/0014_SubsetSumProblem.cc rename to src/0004_dynamic_programming/0014_SubsetSumProblem.cc index d3e60cd..7f558ba 100644 --- a/src/0005_DynamicProgramming/0014_SubsetSumProblem.cc +++ b/src/0004_dynamic_programming/0014_SubsetSumProblem.cc @@ -1,4 +1,4 @@ -#include <0005_DynamicProgramming/0014_SubsetSumProblem.h> +#include "0014_SubsetSumProblem.h" namespace SubsetSumProblem { diff --git a/src/0005_DynamicProgramming/0015_CountSubsetsForSum.cc b/src/0004_dynamic_programming/0015_CountSubsetsForSum.cc similarity index 95% rename from src/0005_DynamicProgramming/0015_CountSubsetsForSum.cc rename to src/0004_dynamic_programming/0015_CountSubsetsForSum.cc index a8ddfd2..64d75b6 100644 --- a/src/0005_DynamicProgramming/0015_CountSubsetsForSum.cc +++ b/src/0004_dynamic_programming/0015_CountSubsetsForSum.cc @@ -1,4 +1,4 @@ -#include <0005_DynamicProgramming/0015_CountSubsetsForSum.h> +#include "0015_CountSubsetsForSum.h" namespace CountSubsetsForSum { diff --git a/src/0005_DynamicProgramming/0016_PartitionEqualSubsetSum.cc b/src/0004_dynamic_programming/0016_PartitionEqualSubsetSum.cc similarity index 96% rename from src/0005_DynamicProgramming/0016_PartitionEqualSubsetSum.cc rename to src/0004_dynamic_programming/0016_PartitionEqualSubsetSum.cc index 883b599..2db0dab 100644 --- a/src/0005_DynamicProgramming/0016_PartitionEqualSubsetSum.cc +++ b/src/0004_dynamic_programming/0016_PartitionEqualSubsetSum.cc @@ -1,4 +1,4 @@ -#include <0005_DynamicProgramming/0016_PartitionEqualSubsetSum.h> +#include "0016_PartitionEqualSubsetSum.h" namespace PartitionEqualSubsetSum { diff --git a/src/0005_DynamicProgramming/0017_TargetSum.cc b/src/0004_dynamic_programming/0017_TargetSum.cc similarity index 96% rename from src/0005_DynamicProgramming/0017_TargetSum.cc rename to src/0004_dynamic_programming/0017_TargetSum.cc index 2ae4891..c92fe77 100644 --- a/src/0005_DynamicProgramming/0017_TargetSum.cc +++ b/src/0004_dynamic_programming/0017_TargetSum.cc @@ -1,4 +1,4 @@ -#include <0005_DynamicProgramming/0017_TargetSum.h> +#include "0017_TargetSum.h" namespace TargetSum { diff --git a/src/0005_DynamicProgramming/CMakeLists.txt b/src/0004_dynamic_programming/CMakeLists.txt similarity index 86% rename from src/0005_DynamicProgramming/CMakeLists.txt rename to src/0004_dynamic_programming/CMakeLists.txt index adf0747..b063b19 100644 --- a/src/0005_DynamicProgramming/CMakeLists.txt +++ b/src/0004_dynamic_programming/CMakeLists.txt @@ -21,4 +21,8 @@ set(0005DYNAMICPROGRAMMING_SOURCES ) # Create a library target -add_library(0005DYNAMICPROGRAMMING ${0005DYNAMICPROGRAMMING_SOURCES}) \ No newline at end of file +add_library(0005DYNAMICPROGRAMMING ${0005DYNAMICPROGRAMMING_SOURCES}) + +target_include_directories(0005DYNAMICPROGRAMMING PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}/headers +) \ No newline at end of file diff --git a/include/0005_DynamicProgramming/0001_FibonacciNumber.h b/src/0004_dynamic_programming/headers/0001_FibonacciNumber.h similarity index 100% rename from include/0005_DynamicProgramming/0001_FibonacciNumber.h rename to src/0004_dynamic_programming/headers/0001_FibonacciNumber.h diff --git a/include/0005_DynamicProgramming/0002_TribonacciNumber.h b/src/0004_dynamic_programming/headers/0002_TribonacciNumber.h similarity index 100% rename from include/0005_DynamicProgramming/0002_TribonacciNumber.h rename to src/0004_dynamic_programming/headers/0002_TribonacciNumber.h diff --git a/include/0005_DynamicProgramming/0003_ClimbingStairs.h b/src/0004_dynamic_programming/headers/0003_ClimbingStairs.h similarity index 100% rename from include/0005_DynamicProgramming/0003_ClimbingStairs.h rename to src/0004_dynamic_programming/headers/0003_ClimbingStairs.h diff --git a/include/0005_DynamicProgramming/0004_MinimumCostClimbingStairs.h b/src/0004_dynamic_programming/headers/0004_MinimumCostClimbingStairs.h similarity index 100% rename from include/0005_DynamicProgramming/0004_MinimumCostClimbingStairs.h rename to src/0004_dynamic_programming/headers/0004_MinimumCostClimbingStairs.h diff --git a/include/0005_DynamicProgramming/0005_HouseRobber1.h b/src/0004_dynamic_programming/headers/0005_HouseRobber1.h similarity index 100% rename from include/0005_DynamicProgramming/0005_HouseRobber1.h rename to src/0004_dynamic_programming/headers/0005_HouseRobber1.h diff --git a/include/0005_DynamicProgramming/0006_HouseRobber2.h b/src/0004_dynamic_programming/headers/0006_HouseRobber2.h similarity index 100% rename from include/0005_DynamicProgramming/0006_HouseRobber2.h rename to src/0004_dynamic_programming/headers/0006_HouseRobber2.h diff --git a/include/0005_DynamicProgramming/0007_DecodeWays.h b/src/0004_dynamic_programming/headers/0007_DecodeWays.h similarity index 100% rename from include/0005_DynamicProgramming/0007_DecodeWays.h rename to src/0004_dynamic_programming/headers/0007_DecodeWays.h diff --git a/include/0005_DynamicProgramming/0008_TilingProblem.h b/src/0004_dynamic_programming/headers/0008_TilingProblem.h similarity index 100% rename from include/0005_DynamicProgramming/0008_TilingProblem.h rename to src/0004_dynamic_programming/headers/0008_TilingProblem.h diff --git a/include/0005_DynamicProgramming/0009_FriendsPairingProblem.h b/src/0004_dynamic_programming/headers/0009_FriendsPairingProblem.h similarity index 100% rename from include/0005_DynamicProgramming/0009_FriendsPairingProblem.h rename to src/0004_dynamic_programming/headers/0009_FriendsPairingProblem.h diff --git a/include/0005_DynamicProgramming/0010_WaysToCoverDistance.h b/src/0004_dynamic_programming/headers/0010_WaysToCoverDistance.h similarity index 100% rename from include/0005_DynamicProgramming/0010_WaysToCoverDistance.h rename to src/0004_dynamic_programming/headers/0010_WaysToCoverDistance.h diff --git a/include/0005_DynamicProgramming/0011_CountWaysToReachNthStairIncludeOrder.h b/src/0004_dynamic_programming/headers/0011_CountWaysToReachNthStairIncludeOrder.h similarity index 100% rename from include/0005_DynamicProgramming/0011_CountWaysToReachNthStairIncludeOrder.h rename to src/0004_dynamic_programming/headers/0011_CountWaysToReachNthStairIncludeOrder.h diff --git a/include/0005_DynamicProgramming/0012_CountWaysToReachNthStairExcludeOrder.h b/src/0004_dynamic_programming/headers/0012_CountWaysToReachNthStairExcludeOrder.h similarity index 100% rename from include/0005_DynamicProgramming/0012_CountWaysToReachNthStairExcludeOrder.h rename to src/0004_dynamic_programming/headers/0012_CountWaysToReachNthStairExcludeOrder.h diff --git a/include/0005_DynamicProgramming/0013_KnapsackProblem.h b/src/0004_dynamic_programming/headers/0013_KnapsackProblem.h similarity index 100% rename from include/0005_DynamicProgramming/0013_KnapsackProblem.h rename to src/0004_dynamic_programming/headers/0013_KnapsackProblem.h diff --git a/include/0005_DynamicProgramming/0014_SubsetSumProblem.h b/src/0004_dynamic_programming/headers/0014_SubsetSumProblem.h similarity index 100% rename from include/0005_DynamicProgramming/0014_SubsetSumProblem.h rename to src/0004_dynamic_programming/headers/0014_SubsetSumProblem.h diff --git a/include/0005_DynamicProgramming/0015_CountSubsetsForSum.h b/src/0004_dynamic_programming/headers/0015_CountSubsetsForSum.h similarity index 100% rename from include/0005_DynamicProgramming/0015_CountSubsetsForSum.h rename to src/0004_dynamic_programming/headers/0015_CountSubsetsForSum.h diff --git a/include/0005_DynamicProgramming/0016_PartitionEqualSubsetSum.h b/src/0004_dynamic_programming/headers/0016_PartitionEqualSubsetSum.h similarity index 100% rename from include/0005_DynamicProgramming/0016_PartitionEqualSubsetSum.h rename to src/0004_dynamic_programming/headers/0016_PartitionEqualSubsetSum.h diff --git a/include/0005_DynamicProgramming/0017_TargetSum.h b/src/0004_dynamic_programming/headers/0017_TargetSum.h similarity index 100% rename from include/0005_DynamicProgramming/0017_TargetSum.h rename to src/0004_dynamic_programming/headers/0017_TargetSum.h diff --git a/include/0001_Basics/CMakeLists.txt b/src/0005_greedy_algorithms/CMakeLists.txt similarity index 100% rename from include/0001_Basics/CMakeLists.txt rename to src/0005_greedy_algorithms/CMakeLists.txt diff --git a/src/0006_BitwiseAlgorithms/CMakeLists.txt b/src/0006_BitwiseAlgorithms/CMakeLists.txt deleted file mode 100644 index e69de29..0000000 diff --git a/include/0002_Tree/CMakeLists.txt b/src/0006_bitwise_algorithms/CMakeLists.txt similarity index 100% rename from include/0002_Tree/CMakeLists.txt rename to src/0006_bitwise_algorithms/CMakeLists.txt diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 65d79e1..708289d 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,6 +1,6 @@ -add_subdirectory(0001_Basics) -add_subdirectory(0002_Tree) -add_subdirectory(0003_Graph) -add_subdirectory(0004_GreedyAlgorithms) -add_subdirectory(0005_DynamicProgramming) -add_subdirectory(0006_BitwiseAlgorithms) \ No newline at end of file +add_subdirectory(0001_basics) +add_subdirectory(0002_tree) +add_subdirectory(0003_graph) +add_subdirectory(0004_dynamic_programming) +add_subdirectory(0005_greedy_algorithms) +add_subdirectory(0006_bitwise_algorithms) \ No newline at end of file diff --git a/tests/0000_CommonUtilities/CMakeLists.txt b/tests/0000_CommonUtilities/CMakeLists.txt deleted file mode 100644 index e69de29..0000000 diff --git a/include/0003_Graph/CMakeLists.txt b/tests/0000_common_utilities/CMakeLists.txt similarity index 100% rename from include/0003_Graph/CMakeLists.txt rename to tests/0000_common_utilities/CMakeLists.txt diff --git a/tests/0000_CommonUtilities/UnitTestHelper.h b/tests/0000_common_utilities/UnitTestHelper.h similarity index 100% rename from tests/0000_CommonUtilities/UnitTestHelper.h rename to tests/0000_common_utilities/UnitTestHelper.h diff --git a/tests/0001_Basics/NodeTest.cc b/tests/0001_Basics/NodeTest.cc index 35d9c36..ca38297 100644 --- a/tests/0001_Basics/NodeTest.cc +++ b/tests/0001_Basics/NodeTest.cc @@ -1,5 +1,5 @@ #include -#include <0001_Basics/Node.h> +#include "Node.h" // Demonstrate some basic assertions. namespace NodeTesting diff --git a/tests/0002_Tree/0001_BinarySearchTreeTest.cc b/tests/0002_Tree/0001_BinarySearchTreeTest.cc index 34bf139..d99a30e 100644 --- a/tests/0002_Tree/0001_BinarySearchTreeTest.cc +++ b/tests/0002_Tree/0001_BinarySearchTreeTest.cc @@ -1,7 +1,7 @@ #include #include -#include <0002_Tree/0001_BinarySearchTree.h> -#include "../0000_CommonUtilities/UnitTestHelper.h" +#include "0001_BinarySearchTree.h" +#include "../0000_common_utilities/UnitTestHelper.h" namespace BinarySearchTree { diff --git a/tests/0003_Graph/0001_BreadthFirstSearchTest.cc b/tests/0003_Graph/0001_BreadthFirstSearchTest.cc index ed66cb7..c0beb81 100644 --- a/tests/0003_Graph/0001_BreadthFirstSearchTest.cc +++ b/tests/0003_Graph/0001_BreadthFirstSearchTest.cc @@ -1,7 +1,7 @@ #include #include -#include <0003_Graph/0001_BreadthFirstSearch.h> -#include "../0000_CommonUtilities/UnitTestHelper.h" +#include "../../src/0003_graph/headers/0001_BreadthFirstSearch.h" +#include "../0000_common_utilities/UnitTestHelper.h" namespace BreadthFirstSearch { diff --git a/tests/0003_Graph/0002_DepthFirstSearchTest.cc b/tests/0003_Graph/0002_DepthFirstSearchTest.cc index d1179b3..c96c55e 100644 --- a/tests/0003_Graph/0002_DepthFirstSearchTest.cc +++ b/tests/0003_Graph/0002_DepthFirstSearchTest.cc @@ -1,6 +1,6 @@ #include -#include <0003_Graph/0002_DepthFirstSearch.h> -#include "../0000_CommonUtilities/UnitTestHelper.h" +#include "0002_DepthFirstSearch.h" +#include "../0000_common_utilities/UnitTestHelper.h" namespace DepthFirstSearch { diff --git a/tests/0003_Graph/0003_TopologicalSortTest.cc b/tests/0003_Graph/0003_TopologicalSortTest.cc index a1812e0..6ad277e 100644 --- a/tests/0003_Graph/0003_TopologicalSortTest.cc +++ b/tests/0003_Graph/0003_TopologicalSortTest.cc @@ -1,6 +1,6 @@ #include -#include <0003_Graph/0003_TopologicalSort.h> -#include "../0000_CommonUtilities/UnitTestHelper.h" +#include "0003_TopologicalSort.h" +#include "../0000_common_utilities/UnitTestHelper.h" namespace TopologicalSort { diff --git a/tests/0003_Graph/0004_StronglyConnectedComponentsTest.cc b/tests/0003_Graph/0004_StronglyConnectedComponentsTest.cc index f881993..f8ede7f 100644 --- a/tests/0003_Graph/0004_StronglyConnectedComponentsTest.cc +++ b/tests/0003_Graph/0004_StronglyConnectedComponentsTest.cc @@ -1,6 +1,6 @@ #include -#include <0003_Graph/0004_StronglyConnectedComponents.h> -#include "../0000_CommonUtilities/UnitTestHelper.h" +#include "0004_StronglyConnectedComponents.h" +#include "../0000_common_utilities/UnitTestHelper.h" namespace StronglyConnectedComponents { diff --git a/tests/0003_Graph/0005_HamiltonianPathAndCycleTest.cc b/tests/0003_Graph/0005_HamiltonianPathAndCycleTest.cc index 44f4f94..33c351e 100644 --- a/tests/0003_Graph/0005_HamiltonianPathAndCycleTest.cc +++ b/tests/0003_Graph/0005_HamiltonianPathAndCycleTest.cc @@ -1,6 +1,6 @@ #include -#include <0003_Graph/0005_HamiltonianPathAndCycle.h> -#include "../0000_CommonUtilities/UnitTestHelper.h" +#include "0005_HamiltonianPathAndCycle.h" +#include "../0000_common_utilities/UnitTestHelper.h" namespace HamiltonianPathAndCycle { diff --git a/tests/0003_Graph/0006_EulerianPathAndCircuitTest.cc b/tests/0003_Graph/0006_EulerianPathAndCircuitTest.cc index 9ff5df4..a163a5c 100644 --- a/tests/0003_Graph/0006_EulerianPathAndCircuitTest.cc +++ b/tests/0003_Graph/0006_EulerianPathAndCircuitTest.cc @@ -1,6 +1,6 @@ #include -#include <0003_Graph/0006_EulerianPathAndCircuit.h> -#include "../0000_CommonUtilities/UnitTestHelper.h" +#include "0006_EulerianPathAndCircuit.h" +#include "../0000_common_utilities/UnitTestHelper.h" namespace EulerianPathAndCircuit { diff --git a/tests/0003_Graph/0007_MinimumSpanningTreeKruskalAlgorithmTest.cc b/tests/0003_Graph/0007_MinimumSpanningTreeKruskalAlgorithmTest.cc index a8b1d27..5736b79 100644 --- a/tests/0003_Graph/0007_MinimumSpanningTreeKruskalAlgorithmTest.cc +++ b/tests/0003_Graph/0007_MinimumSpanningTreeKruskalAlgorithmTest.cc @@ -1,6 +1,6 @@ #include -#include <0003_Graph/0007_MinimumSpanningTreeKruskalAlgorithm.h> -#include "../0000_CommonUtilities/UnitTestHelper.h" +#include "0007_MinimumSpanningTreeKruskalAlgorithm.h" +#include "../0000_common_utilities/UnitTestHelper.h" namespace MinimumSpanningTreeKruskalAlgorithm { diff --git a/tests/0003_Graph/0008_MinimumSpanningTreePrimAlgorithmTest.cc b/tests/0003_Graph/0008_MinimumSpanningTreePrimAlgorithmTest.cc index a159546..251c654 100644 --- a/tests/0003_Graph/0008_MinimumSpanningTreePrimAlgorithmTest.cc +++ b/tests/0003_Graph/0008_MinimumSpanningTreePrimAlgorithmTest.cc @@ -1,6 +1,6 @@ #include -#include <0003_Graph/0008_MinimumSpanningTreePrimAlgorithm.h> -#include "../0000_CommonUtilities/UnitTestHelper.h" +#include "0008_MinimumSpanningTreePrimAlgorithm.h" +#include "../0000_common_utilities/UnitTestHelper.h" namespace MinimumSpanningTreePrimAlgorithm { diff --git a/tests/0003_Graph/0009_SingleSourceShortestPathBellmanFordTest.cc b/tests/0003_Graph/0009_SingleSourceShortestPathBellmanFordTest.cc index fa3d41c..fc84901 100644 --- a/tests/0003_Graph/0009_SingleSourceShortestPathBellmanFordTest.cc +++ b/tests/0003_Graph/0009_SingleSourceShortestPathBellmanFordTest.cc @@ -1,6 +1,6 @@ #include -#include <0003_Graph/0009_SingleSourceShortestPathBellmanFord.h> -#include "../0000_CommonUtilities/UnitTestHelper.h" +#include "0009_SingleSourceShortestPathBellmanFord.h" +#include "../0000_common_utilities/UnitTestHelper.h" namespace SingleSourceShortestPathBellmanFord { diff --git a/tests/0003_Graph/0010_DirectedAcyclicGraphShortestPathTest.cc b/tests/0003_Graph/0010_DirectedAcyclicGraphShortestPathTest.cc index 8f5da5e..50d7086 100644 --- a/tests/0003_Graph/0010_DirectedAcyclicGraphShortestPathTest.cc +++ b/tests/0003_Graph/0010_DirectedAcyclicGraphShortestPathTest.cc @@ -1,6 +1,6 @@ #include -#include <0003_Graph/0010_DirectedAcyclicGraphShortestPath.h> -#include "../0000_CommonUtilities/UnitTestHelper.h" +#include "0010_DirectedAcyclicGraphShortestPath.h" +#include "../0000_common_utilities/UnitTestHelper.h" namespace DirectedAcyclicGraphShortestPath { diff --git a/tests/0003_Graph/0011_SingleSourceShortestPathDijkstraTest.cc b/tests/0003_Graph/0011_SingleSourceShortestPathDijkstraTest.cc index 01c9012..5460b1b 100644 --- a/tests/0003_Graph/0011_SingleSourceShortestPathDijkstraTest.cc +++ b/tests/0003_Graph/0011_SingleSourceShortestPathDijkstraTest.cc @@ -1,6 +1,6 @@ #include -#include <0003_Graph/0011_SingleSourceShortestPathDijkstra.h> -#include "../0000_CommonUtilities/UnitTestHelper.h" +#include "0011_SingleSourceShortestPathDijkstra.h" +#include "../0000_common_utilities/UnitTestHelper.h" namespace SingleSourceShortestPathDijkstra { diff --git a/tests/0003_Graph/0012_DifferenceConstraintsShortestPathsTest.cc b/tests/0003_Graph/0012_DifferenceConstraintsShortestPathsTest.cc index 256def7..152dd0d 100644 --- a/tests/0003_Graph/0012_DifferenceConstraintsShortestPathsTest.cc +++ b/tests/0003_Graph/0012_DifferenceConstraintsShortestPathsTest.cc @@ -1,6 +1,6 @@ #include -#include <0003_Graph/0012_DifferenceConstraintsShortestPaths.h> -#include"../0000_CommonUtilities/UnitTestHelper.h" +#include "0012_DifferenceConstraintsShortestPaths.h" +#include"../0000_common_utilities/UnitTestHelper.h" using namespace std; namespace DifferenceConstraintsShortestPaths diff --git a/tests/0003_Graph/0013_AllPairsShortestPathsFloydWarshallTest.cc b/tests/0003_Graph/0013_AllPairsShortestPathsFloydWarshallTest.cc index 8efada0..17a5045 100644 --- a/tests/0003_Graph/0013_AllPairsShortestPathsFloydWarshallTest.cc +++ b/tests/0003_Graph/0013_AllPairsShortestPathsFloydWarshallTest.cc @@ -1,6 +1,6 @@ #include -#include <0003_Graph/0013_AllPairsShortestPathsFloydWarshall.h> -#include"../0000_CommonUtilities/UnitTestHelper.h" +#include "0013_AllPairsShortestPathsFloydWarshall.h" +#include "../0000_common_utilities/UnitTestHelper.h" using namespace std; namespace AllPairsShortestPathsFloydWarshall diff --git a/tests/0003_Graph/0014_AllPairsShortestPathsJohnsonTest.cc b/tests/0003_Graph/0014_AllPairsShortestPathsJohnsonTest.cc index 8f5a84b..66a63a1 100644 --- a/tests/0003_Graph/0014_AllPairsShortestPathsJohnsonTest.cc +++ b/tests/0003_Graph/0014_AllPairsShortestPathsJohnsonTest.cc @@ -1,6 +1,6 @@ #include -#include <0003_Graph/0014_AllPairsShortestPathsJohnson.h> -#include"../0000_CommonUtilities/UnitTestHelper.h" +#include "0014_AllPairsShortestPathsJohnson.h" +#include"../0000_common_utilities/UnitTestHelper.h" using namespace std; namespace AllPairsShortestPathsJohnson diff --git a/tests/0003_Graph/0015_MaximumFlowFordFulkersonTest.cc b/tests/0003_Graph/0015_MaximumFlowFordFulkersonTest.cc index bd864e5..117bfc2 100644 --- a/tests/0003_Graph/0015_MaximumFlowFordFulkersonTest.cc +++ b/tests/0003_Graph/0015_MaximumFlowFordFulkersonTest.cc @@ -1,6 +1,6 @@ #include -#include <0003_Graph/0015_MaximumFlowFordFulkerson.h> -#include "../0000_CommonUtilities/UnitTestHelper.h" +#include "0015_MaximumFlowFordFulkerson.h" +#include "../0000_common_utilities/UnitTestHelper.h" namespace MaximumFlowFordFulkerson { diff --git a/tests/0003_Graph/0016_MaximumFlowEdmondsKarpTest.cc b/tests/0003_Graph/0016_MaximumFlowEdmondsKarpTest.cc index c9d8175..5d3177a 100644 --- a/tests/0003_Graph/0016_MaximumFlowEdmondsKarpTest.cc +++ b/tests/0003_Graph/0016_MaximumFlowEdmondsKarpTest.cc @@ -1,6 +1,6 @@ #include -#include <0003_Graph/0016_MaximumFlowEdmondsKarp.h> -#include "../0000_CommonUtilities/UnitTestHelper.h" +#include "0016_MaximumFlowEdmondsKarp.h" +#include "../0000_common_utilities/UnitTestHelper.h" namespace MaximumFlowEdmondsKarp { diff --git a/tests/0003_Graph/0017_MaximumBipartiteMatchingTest.cc b/tests/0003_Graph/0017_MaximumBipartiteMatchingTest.cc index 0149332..d556e28 100644 --- a/tests/0003_Graph/0017_MaximumBipartiteMatchingTest.cc +++ b/tests/0003_Graph/0017_MaximumBipartiteMatchingTest.cc @@ -1,6 +1,6 @@ #include -#include <0003_Graph/0017_MaximumBipartiteMatching.h> -#include "../0000_CommonUtilities/UnitTestHelper.h" +#include "0017_MaximumBipartiteMatching.h" +#include "../0000_common_utilities/UnitTestHelper.h" namespace MaximumBipartiteMatching { diff --git a/tests/0003_Graph/0018_MaximumFlowGoldbergGenericPushRelabelTest.cc b/tests/0003_Graph/0018_MaximumFlowGoldbergGenericPushRelabelTest.cc index 814ed74..283cab0 100644 --- a/tests/0003_Graph/0018_MaximumFlowGoldbergGenericPushRelabelTest.cc +++ b/tests/0003_Graph/0018_MaximumFlowGoldbergGenericPushRelabelTest.cc @@ -1,6 +1,6 @@ #include -#include <0003_Graph/0018_MaximumFlowGoldbergGenericPushRelabel.h> -#include "../0000_CommonUtilities/UnitTestHelper.h" +#include "0018_MaximumFlowGoldbergGenericPushRelabel.h" +#include "../0000_common_utilities/UnitTestHelper.h" namespace MaximumFlowGoldbergGenericPushRelabel { diff --git a/tests/0003_Graph/0019_MaximumFlowRelabelToFrontTest.cc b/tests/0003_Graph/0019_MaximumFlowRelabelToFrontTest.cc index bbd3e4b..a73b89d 100644 --- a/tests/0003_Graph/0019_MaximumFlowRelabelToFrontTest.cc +++ b/tests/0003_Graph/0019_MaximumFlowRelabelToFrontTest.cc @@ -1,6 +1,6 @@ #include -#include <0003_Graph/0019_MaximumFlowRelabelToFront.h> -#include "../0000_CommonUtilities/UnitTestHelper.h" +#include "0019_MaximumFlowRelabelToFront.h" +#include "../0000_common_utilities/UnitTestHelper.h" using namespace std; namespace MaximumFlowRelabelToFront diff --git a/tests/0004_GreedyAlgorithms/CMakeLists.txt b/tests/0004_GreedyAlgorithms/CMakeLists.txt deleted file mode 100644 index e69de29..0000000 diff --git a/tests/0005_DynamicProgramming/0001_FibonacciNumberTest.cc b/tests/0004_dynamic_programming/0001_FibonacciNumberTest.cc similarity index 89% rename from tests/0005_DynamicProgramming/0001_FibonacciNumberTest.cc rename to tests/0004_dynamic_programming/0001_FibonacciNumberTest.cc index 09f5f83..1fdd9a4 100644 --- a/tests/0005_DynamicProgramming/0001_FibonacciNumberTest.cc +++ b/tests/0004_dynamic_programming/0001_FibonacciNumberTest.cc @@ -1,5 +1,5 @@ #include -#include <0005_DynamicProgramming/0001_FibonacciNumber.h> +#include "0001_FibonacciNumber.h" using namespace std; namespace FibonacciNumber diff --git a/tests/0005_DynamicProgramming/0002_TribonacciNumberTest.cc b/tests/0004_dynamic_programming/0002_TribonacciNumberTest.cc similarity index 89% rename from tests/0005_DynamicProgramming/0002_TribonacciNumberTest.cc rename to tests/0004_dynamic_programming/0002_TribonacciNumberTest.cc index 94ecca5..d25c394 100644 --- a/tests/0005_DynamicProgramming/0002_TribonacciNumberTest.cc +++ b/tests/0004_dynamic_programming/0002_TribonacciNumberTest.cc @@ -1,5 +1,5 @@ #include -#include <0005_DynamicProgramming/0002_TribonacciNumber.h> +#include "0002_TribonacciNumber.h" using namespace std; namespace TribonacciNumber diff --git a/tests/0005_DynamicProgramming/0003_ClimbingStairsTest.cc b/tests/0004_dynamic_programming/0003_ClimbingStairsTest.cc similarity index 89% rename from tests/0005_DynamicProgramming/0003_ClimbingStairsTest.cc rename to tests/0004_dynamic_programming/0003_ClimbingStairsTest.cc index f992682..0504cbc 100644 --- a/tests/0005_DynamicProgramming/0003_ClimbingStairsTest.cc +++ b/tests/0004_dynamic_programming/0003_ClimbingStairsTest.cc @@ -1,5 +1,5 @@ #include -#include <0005_DynamicProgramming/0003_ClimbingStairs.h> +#include "0003_ClimbingStairs.h" namespace ClimbingStairs { diff --git a/tests/0005_DynamicProgramming/0004_MinimumCostClimbingStairsTest.cc b/tests/0004_dynamic_programming/0004_MinimumCostClimbingStairsTest.cc similarity index 90% rename from tests/0005_DynamicProgramming/0004_MinimumCostClimbingStairsTest.cc rename to tests/0004_dynamic_programming/0004_MinimumCostClimbingStairsTest.cc index acfb98b..b488105 100644 --- a/tests/0005_DynamicProgramming/0004_MinimumCostClimbingStairsTest.cc +++ b/tests/0004_dynamic_programming/0004_MinimumCostClimbingStairsTest.cc @@ -1,5 +1,5 @@ #include -#include <0005_DynamicProgramming/0004_MinimumCostClimbingStairs.h> +#include "0004_MinimumCostClimbingStairs.h" namespace MinimumCostClimbingStairs { diff --git a/tests/0005_DynamicProgramming/0005_HouseRobber1Test.cc b/tests/0004_dynamic_programming/0005_HouseRobber1Test.cc similarity index 92% rename from tests/0005_DynamicProgramming/0005_HouseRobber1Test.cc rename to tests/0004_dynamic_programming/0005_HouseRobber1Test.cc index 71c0af8..d3f6312 100644 --- a/tests/0005_DynamicProgramming/0005_HouseRobber1Test.cc +++ b/tests/0004_dynamic_programming/0005_HouseRobber1Test.cc @@ -1,5 +1,5 @@ #include -#include <0005_DynamicProgramming/0005_HouseRobber1.h> +#include "0005_HouseRobber1.h" namespace HouseRobber1 { diff --git a/tests/0005_DynamicProgramming/0006_HouseRobber2Test.cc b/tests/0004_dynamic_programming/0006_HouseRobber2Test.cc similarity index 94% rename from tests/0005_DynamicProgramming/0006_HouseRobber2Test.cc rename to tests/0004_dynamic_programming/0006_HouseRobber2Test.cc index c485d4c..e37c346 100644 --- a/tests/0005_DynamicProgramming/0006_HouseRobber2Test.cc +++ b/tests/0004_dynamic_programming/0006_HouseRobber2Test.cc @@ -1,5 +1,5 @@ #include -#include <0005_DynamicProgramming/0006_HouseRobber2.h> +#include "0006_HouseRobber2.h" namespace HouseRobber2 { diff --git a/tests/0005_DynamicProgramming/0007_DecodeWaysTest.cc b/tests/0004_dynamic_programming/0007_DecodeWaysTest.cc similarity index 93% rename from tests/0005_DynamicProgramming/0007_DecodeWaysTest.cc rename to tests/0004_dynamic_programming/0007_DecodeWaysTest.cc index 2cd183b..cf81a98 100644 --- a/tests/0005_DynamicProgramming/0007_DecodeWaysTest.cc +++ b/tests/0004_dynamic_programming/0007_DecodeWaysTest.cc @@ -1,5 +1,5 @@ #include -#include <0005_DynamicProgramming/0007_DecodeWays.h> +#include "0007_DecodeWays.h" namespace DecodeWays { diff --git a/tests/0005_DynamicProgramming/0008_TilingProblemTest.cc b/tests/0004_dynamic_programming/0008_TilingProblemTest.cc similarity index 91% rename from tests/0005_DynamicProgramming/0008_TilingProblemTest.cc rename to tests/0004_dynamic_programming/0008_TilingProblemTest.cc index fa5c504..bbcbb79 100644 --- a/tests/0005_DynamicProgramming/0008_TilingProblemTest.cc +++ b/tests/0004_dynamic_programming/0008_TilingProblemTest.cc @@ -1,5 +1,5 @@ #include -#include <0005_DynamicProgramming/0008_TilingProblem.h> +#include "0008_TilingProblem.h" namespace TilingProblem { diff --git a/tests/0005_DynamicProgramming/0009_FriendsPairingProblemTest.cc b/tests/0004_dynamic_programming/0009_FriendsPairingProblemTest.cc similarity index 97% rename from tests/0005_DynamicProgramming/0009_FriendsPairingProblemTest.cc rename to tests/0004_dynamic_programming/0009_FriendsPairingProblemTest.cc index b1d2332..11376ac 100644 --- a/tests/0005_DynamicProgramming/0009_FriendsPairingProblemTest.cc +++ b/tests/0004_dynamic_programming/0009_FriendsPairingProblemTest.cc @@ -1,5 +1,5 @@ #include -#include <0005_DynamicProgramming/0009_FriendsPairingProblem.h> +#include "0009_FriendsPairingProblem.h" namespace FriendsPairingProblem { diff --git a/tests/0005_DynamicProgramming/0010_WaysToCoverDistanceTest.cc b/tests/0004_dynamic_programming/0010_WaysToCoverDistanceTest.cc similarity index 97% rename from tests/0005_DynamicProgramming/0010_WaysToCoverDistanceTest.cc rename to tests/0004_dynamic_programming/0010_WaysToCoverDistanceTest.cc index fac6df5..7e7f0c9 100644 --- a/tests/0005_DynamicProgramming/0010_WaysToCoverDistanceTest.cc +++ b/tests/0004_dynamic_programming/0010_WaysToCoverDistanceTest.cc @@ -1,5 +1,5 @@ #include -#include <0005_DynamicProgramming/0010_WaysToCoverDistance.h> +#include "0010_WaysToCoverDistance.h" namespace WaysToCoverDistance { diff --git a/tests/0005_DynamicProgramming/0011_CountWaysToReachNthStairIncludeOrderTest.cc b/tests/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrderTest.cc similarity index 90% rename from tests/0005_DynamicProgramming/0011_CountWaysToReachNthStairIncludeOrderTest.cc rename to tests/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrderTest.cc index 82c49be..8a9830c 100644 --- a/tests/0005_DynamicProgramming/0011_CountWaysToReachNthStairIncludeOrderTest.cc +++ b/tests/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrderTest.cc @@ -1,5 +1,5 @@ #include -#include <0005_DynamicProgramming/0011_CountWaysToReachNthStairIncludeOrder.h> +#include "0011_CountWaysToReachNthStairIncludeOrder.h" namespace CountWaysToReachNthStairIncludeOrder { diff --git a/tests/0005_DynamicProgramming/0012_CountWaysToReachNthStairExcludeOrderTest.cc b/tests/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrderTest.cc similarity index 90% rename from tests/0005_DynamicProgramming/0012_CountWaysToReachNthStairExcludeOrderTest.cc rename to tests/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrderTest.cc index 63aaf6d..2a67ce3 100644 --- a/tests/0005_DynamicProgramming/0012_CountWaysToReachNthStairExcludeOrderTest.cc +++ b/tests/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrderTest.cc @@ -1,5 +1,5 @@ #include -#include <0005_DynamicProgramming/0012_CountWaysToReachNthStairExcludeOrder.h> +#include "0012_CountWaysToReachNthStairExcludeOrder.h" namespace CountWaysToReachNthStairExcludeOrder { diff --git a/tests/0005_DynamicProgramming/0013_KnapsackProblemTest.cc b/tests/0004_dynamic_programming/0013_KnapsackProblemTest.cc similarity index 95% rename from tests/0005_DynamicProgramming/0013_KnapsackProblemTest.cc rename to tests/0004_dynamic_programming/0013_KnapsackProblemTest.cc index 5a8b870..94d3e84 100644 --- a/tests/0005_DynamicProgramming/0013_KnapsackProblemTest.cc +++ b/tests/0004_dynamic_programming/0013_KnapsackProblemTest.cc @@ -1,5 +1,5 @@ #include -#include <0005_DynamicProgramming/0013_KnapsackProblem.h> +#include "0013_KnapsackProblem.h" namespace KnapsackProblem { diff --git a/tests/0005_DynamicProgramming/0014_SubsetSumProblemTest.cc b/tests/0004_dynamic_programming/0014_SubsetSumProblemTest.cc similarity index 91% rename from tests/0005_DynamicProgramming/0014_SubsetSumProblemTest.cc rename to tests/0004_dynamic_programming/0014_SubsetSumProblemTest.cc index fb6e4b6..aeee852 100644 --- a/tests/0005_DynamicProgramming/0014_SubsetSumProblemTest.cc +++ b/tests/0004_dynamic_programming/0014_SubsetSumProblemTest.cc @@ -1,5 +1,5 @@ #include -#include <0005_DynamicProgramming/0014_SubsetSumProblem.h> +#include "0014_SubsetSumProblem.h" namespace SubsetSumProblem { diff --git a/tests/0005_DynamicProgramming/0015_CountSubsetsForSumTest.cc b/tests/0004_dynamic_programming/0015_CountSubsetsForSumTest.cc similarity index 91% rename from tests/0005_DynamicProgramming/0015_CountSubsetsForSumTest.cc rename to tests/0004_dynamic_programming/0015_CountSubsetsForSumTest.cc index 6b110d1..ba1fa7f 100644 --- a/tests/0005_DynamicProgramming/0015_CountSubsetsForSumTest.cc +++ b/tests/0004_dynamic_programming/0015_CountSubsetsForSumTest.cc @@ -1,5 +1,5 @@ #include -#include<0005_DynamicProgramming/0015_CountSubsetsForSum.h> +#include"0015_CountSubsetsForSum.h" namespace CountSubsetsForSum { diff --git a/tests/0005_DynamicProgramming/0016_PartitionEqualSubsetSumTest.cc b/tests/0004_dynamic_programming/0016_PartitionEqualSubsetSumTest.cc similarity index 90% rename from tests/0005_DynamicProgramming/0016_PartitionEqualSubsetSumTest.cc rename to tests/0004_dynamic_programming/0016_PartitionEqualSubsetSumTest.cc index 026b05f..2bfa292 100644 --- a/tests/0005_DynamicProgramming/0016_PartitionEqualSubsetSumTest.cc +++ b/tests/0004_dynamic_programming/0016_PartitionEqualSubsetSumTest.cc @@ -1,5 +1,5 @@ #include -#include <0005_DynamicProgramming/0016_PartitionEqualSubsetSum.h> +#include "0016_PartitionEqualSubsetSum.h" namespace PartitionEqualSubsetSum { diff --git a/tests/0005_DynamicProgramming/0017_TargetSumTest.cc b/tests/0004_dynamic_programming/0017_TargetSumTest.cc similarity index 95% rename from tests/0005_DynamicProgramming/0017_TargetSumTest.cc rename to tests/0004_dynamic_programming/0017_TargetSumTest.cc index 242b1d2..ab3fbf4 100644 --- a/tests/0005_DynamicProgramming/0017_TargetSumTest.cc +++ b/tests/0004_dynamic_programming/0017_TargetSumTest.cc @@ -1,5 +1,5 @@ #include -#include <0005_DynamicProgramming/0017_TargetSum.h> +#include "0017_TargetSum.h" namespace TargetSum { diff --git a/tests/0005_DynamicProgramming/CMakeLists.txt b/tests/0004_dynamic_programming/CMakeLists.txt similarity index 100% rename from tests/0005_DynamicProgramming/CMakeLists.txt rename to tests/0004_dynamic_programming/CMakeLists.txt diff --git a/include/0004_GreedyAlgorithms/CMakeLists.txt b/tests/0005_greedy_algorithms/CMakeLists.txt similarity index 100% rename from include/0004_GreedyAlgorithms/CMakeLists.txt rename to tests/0005_greedy_algorithms/CMakeLists.txt diff --git a/tests/0006_BitwiseAlgorithms/CMakeLists.txt b/tests/0006_BitwiseAlgorithms/CMakeLists.txt deleted file mode 100644 index e69de29..0000000 diff --git a/include/0005_DynamicProgramming/CMakeLists.txt b/tests/0006_bitwise_algorithms/CMakeLists.txt similarity index 100% rename from include/0005_DynamicProgramming/CMakeLists.txt rename to tests/0006_bitwise_algorithms/CMakeLists.txt diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 82c38df..41d781c 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,7 +1,7 @@ -add_subdirectory(0000_CommonUtilities) -add_subdirectory(0001_Basics) -add_subdirectory(0002_Tree) -add_subdirectory(0003_Graph) -add_subdirectory(0004_GreedyAlgorithms) -add_subdirectory(0005_DynamicProgramming) -add_subdirectory(0006_BitwiseAlgorithms) \ No newline at end of file +add_subdirectory(0000_common_utilities) +add_subdirectory(0001_basics) +add_subdirectory(0002_tree) +add_subdirectory(0003_graph) +add_subdirectory(0004_dynamic_programming) +add_subdirectory(0005_greedy_algorithms) +add_subdirectory(0006_bitwise_algorithms) \ No newline at end of file From 1754e3007bcffeefad43d274dc93d404f07d47f4 Mon Sep 17 00:00:00 2001 From: Debashis Nandi Date: Fri, 12 Jun 2026 01:49:32 +0530 Subject: [PATCH 02/13] feat: removed all files --- .clang-tidy | 27 -- .github/ISSUE_TEMPLATE/bug_report.md | 28 -- .github/labeler.yaml | 51 --- .github/pull_request_template.md | 28 -- .github/release.yaml | 56 --- .github/workflows/auto-labeler.yaml | 36 -- .github/workflows/deploy.yaml | 160 -------- .github/workflows/validate.yaml | 130 ------- .gitignore | 3 - CMakeLists.txt | 35 -- CMakePresets.json | 61 --- CODE_OF_CONDUCT.md | 127 ------- CONTRIBUTING.md | 1 - LICENSE | 21 -- README.md | 21 -- SECURITY.md | 1 - src/0001_Basics/CMakeLists.txt | 11 - src/0001_Basics/Node.cc | 6 - src/0001_basics/headers/Node.h | 8 - src/0002_Tree/0001_BinarySearchTree.cc | 349 ------------------ src/0002_Tree/CMakeLists.txt | 11 - src/0002_tree/headers/0001_BinarySearchTree.h | 49 --- src/0003_Graph/0001_BreadthFirstSearch.cc | 86 ----- src/0003_Graph/0002_DepthFirstSearch.cc | 80 ---- src/0003_Graph/0003_TopologicalSort.cc | 150 -------- .../0004_StronglyConnectedComponents.cc | 121 ------ .../0005_HamiltonianPathAndCycle.cc | 114 ------ src/0003_Graph/0006_EulerianPathAndCircuit.cc | 212 ----------- ...007_MinimumSpanningTreeKruskalAlgorithm.cc | 108 ------ .../0008_MinimumSpanningTreePrimAlgorithm.cc | 85 ----- ...009_SingleSourceShortestPathBellmanFord.cc | 108 ------ .../0010_DirectedAcyclicGraphShortestPath.cc | 124 ------- .../0011_SingleSourceShortestPathDijkstra.cc | 113 ------ ...0012_DifferenceConstraintsShortestPaths.cc | 133 ------- ...0013_AllPairsShortestPathsFloydWarshall.cc | 104 ------ .../0014_AllPairsShortestPathsJohnson.cc | 217 ----------- .../0015_MaximumFlowFordFulkerson.cc | 139 ------- src/0003_Graph/0016_MaximumFlowEdmondsKarp.cc | 144 -------- .../0017_MaximumBipartiteMatching.cc | 263 ------------- ...8_MaximumFlowGoldbergGenericPushRelabel.cc | 172 --------- .../0019_MaximumFlowRelabelToFront.cc | 169 --------- src/0003_Graph/CMakeLists.txt | 30 -- .../headers/0001_BreadthFirstSearch.h | 35 -- .../headers/0002_DepthFirstSearch.h | 37 -- src/0003_graph/headers/0003_TopologicalSort.h | 42 --- .../0004_StronglyConnectedComponents.h | 43 --- .../headers/0005_HamiltonianPathAndCycle.h | 40 -- .../headers/0006_EulerianPathAndCircuit.h | 43 --- ...0007_MinimumSpanningTreeKruskalAlgorithm.h | 46 --- .../0008_MinimumSpanningTreePrimAlgorithm.h | 42 --- ...0009_SingleSourceShortestPathBellmanFord.h | 44 --- .../0010_DirectedAcyclicGraphShortestPath.h | 51 --- .../0011_SingleSourceShortestPathDijkstra.h | 55 --- .../0012_DifferenceConstraintsShortestPaths.h | 43 --- .../0013_AllPairsShortestPathsFloydWarshall.h | 24 -- .../0014_AllPairsShortestPathsJohnson.h | 66 ---- .../headers/0015_MaximumFlowFordFulkerson.h | 29 -- .../headers/0016_MaximumFlowEdmondsKarp.h | 28 -- .../headers/0017_MaximumBipartiteMatching.h | 41 -- ...18_MaximumFlowGoldbergGenericPushRelabel.h | 31 -- .../headers/0019_MaximumFlowRelabelToFront.h | 31 -- .../0001_FibonacciNumber.cc | 28 -- .../0002_TribonacciNumber.cc | 33 -- .../0003_ClimbingStairs.cc | 29 -- .../0004_MinimumCostClimbingStairs.cc | 48 --- .../0005_HouseRobber1.cc | 44 --- .../0006_HouseRobber2.cc | 95 ----- .../0007_DecodeWays.cc | 61 --- .../0008_TilingProblem.cc | 42 --- .../0009_FriendsPairingProblem.cc | 39 -- .../0010_WaysToCoverDistance.cc | 52 --- ...11_CountWaysToReachNthStairIncludeOrder.cc | 44 --- ...12_CountWaysToReachNthStairExcludeOrder.cc | 53 --- .../0013_KnapsackProblem.cc | 78 ---- .../0014_SubsetSumProblem.cc | 71 ---- .../0015_CountSubsetsForSum.cc | 55 --- .../0016_PartitionEqualSubsetSum.cc | 75 ---- .../0017_TargetSum.cc | 70 ---- src/0004_dynamic_programming/CMakeLists.txt | 28 -- .../headers/0001_FibonacciNumber.h | 23 -- .../headers/0002_TribonacciNumber.h | 23 -- .../headers/0003_ClimbingStairs.h | 24 -- .../headers/0004_MinimumCostClimbingStairs.h | 25 -- .../headers/0005_HouseRobber1.h | 25 -- .../headers/0006_HouseRobber2.h | 28 -- .../headers/0007_DecodeWays.h | 32 -- .../headers/0008_TilingProblem.h | 25 -- .../headers/0009_FriendsPairingProblem.h | 46 --- .../headers/0010_WaysToCoverDistance.h | 47 --- ...011_CountWaysToReachNthStairIncludeOrder.h | 42 --- ...012_CountWaysToReachNthStairExcludeOrder.h | 44 --- .../headers/0013_KnapsackProblem.h | 34 -- .../headers/0014_SubsetSumProblem.h | 34 -- .../headers/0015_CountSubsetsForSum.h | 34 -- .../headers/0016_PartitionEqualSubsetSum.h | 36 -- .../headers/0017_TargetSum.h | 45 --- src/0005_greedy_algorithms/CMakeLists.txt | 0 src/0006_bitwise_algorithms/CMakeLists.txt | 0 src/CMakeLists.txt | 6 - tests/0000_common_utilities/CMakeLists.txt | 0 tests/0000_common_utilities/UnitTestHelper.h | 183 --------- tests/0001_Basics/CMakeLists.txt | 31 -- tests/0001_Basics/NodeTest.cc | 12 - tests/0002_Tree/0001_BinarySearchTreeTest.cc | 91 ----- tests/0002_Tree/CMakeLists.txt | 32 -- .../0003_Graph/0001_BreadthFirstSearchTest.cc | 45 --- tests/0003_Graph/0002_DepthFirstSearchTest.cc | 177 --------- tests/0003_Graph/0003_TopologicalSortTest.cc | 116 ------ .../0004_StronglyConnectedComponentsTest.cc | 102 ----- .../0005_HamiltonianPathAndCycleTest.cc | 33 -- .../0006_EulerianPathAndCircuitTest.cc | 32 -- ...MinimumSpanningTreeKruskalAlgorithmTest.cc | 45 --- ...08_MinimumSpanningTreePrimAlgorithmTest.cc | 45 --- ...SingleSourceShortestPathBellmanFordTest.cc | 104 ------ ...10_DirectedAcyclicGraphShortestPathTest.cc | 29 -- ...11_SingleSourceShortestPathDijkstraTest.cc | 31 -- ..._DifferenceConstraintsShortestPathsTest.cc | 40 -- ..._AllPairsShortestPathsFloydWarshallTest.cc | 36 -- .../0014_AllPairsShortestPathsJohnsonTest.cc | 44 --- .../0015_MaximumFlowFordFulkersonTest.cc | 64 ---- .../0016_MaximumFlowEdmondsKarpTest.cc | 64 ---- .../0017_MaximumBipartiteMatchingTest.cc | 35 -- ...ximumFlowGoldbergGenericPushRelabelTest.cc | 35 -- .../0019_MaximumFlowRelabelToFrontTest.cc | 36 -- tests/0003_Graph/CMakeLists.txt | 50 --- .../0001_FibonacciNumberTest.cc | 34 -- .../0002_TribonacciNumberTest.cc | 34 -- .../0003_ClimbingStairsTest.cc | 33 -- .../0004_MinimumCostClimbingStairsTest.cc | 33 -- .../0005_HouseRobber1Test.cc | 33 -- .../0006_HouseRobber2Test.cc | 48 --- .../0007_DecodeWaysTest.cc | 47 --- .../0008_TilingProblemTest.cc | 33 -- .../0009_FriendsPairingProblemTest.cc | 91 ----- .../0010_WaysToCoverDistanceTest.cc | 117 ------ ...ountWaysToReachNthStairIncludeOrderTest.cc | 33 -- ...ountWaysToReachNthStairExcludeOrderTest.cc | 33 -- .../0013_KnapsackProblemTest.cc | 53 --- .../0014_SubsetSumProblemTest.cc | 35 -- .../0015_CountSubsetsForSumTest.cc | 35 -- .../0016_PartitionEqualSubsetSumTest.cc | 33 -- .../0017_TargetSumTest.cc | 50 --- tests/0004_dynamic_programming/CMakeLists.txt | 49 --- tests/0005_greedy_algorithms/CMakeLists.txt | 0 tests/0006_bitwise_algorithms/CMakeLists.txt | 0 tests/CMakeLists.txt | 7 - 146 files changed, 8524 deletions(-) delete mode 100644 .clang-tidy delete mode 100644 .github/ISSUE_TEMPLATE/bug_report.md delete mode 100644 .github/labeler.yaml delete mode 100644 .github/pull_request_template.md delete mode 100644 .github/release.yaml delete mode 100644 .github/workflows/auto-labeler.yaml delete mode 100644 .github/workflows/deploy.yaml delete mode 100644 .github/workflows/validate.yaml delete mode 100644 .gitignore delete mode 100644 CMakeLists.txt delete mode 100644 CMakePresets.json delete mode 100644 CODE_OF_CONDUCT.md delete mode 100644 CONTRIBUTING.md delete mode 100644 LICENSE delete mode 100644 README.md delete mode 100644 SECURITY.md delete mode 100644 src/0001_Basics/CMakeLists.txt delete mode 100644 src/0001_Basics/Node.cc delete mode 100644 src/0001_basics/headers/Node.h delete mode 100644 src/0002_Tree/0001_BinarySearchTree.cc delete mode 100644 src/0002_Tree/CMakeLists.txt delete mode 100644 src/0002_tree/headers/0001_BinarySearchTree.h delete mode 100644 src/0003_Graph/0001_BreadthFirstSearch.cc delete mode 100644 src/0003_Graph/0002_DepthFirstSearch.cc delete mode 100644 src/0003_Graph/0003_TopologicalSort.cc delete mode 100644 src/0003_Graph/0004_StronglyConnectedComponents.cc delete mode 100644 src/0003_Graph/0005_HamiltonianPathAndCycle.cc delete mode 100644 src/0003_Graph/0006_EulerianPathAndCircuit.cc delete mode 100644 src/0003_Graph/0007_MinimumSpanningTreeKruskalAlgorithm.cc delete mode 100644 src/0003_Graph/0008_MinimumSpanningTreePrimAlgorithm.cc delete mode 100644 src/0003_Graph/0009_SingleSourceShortestPathBellmanFord.cc delete mode 100644 src/0003_Graph/0010_DirectedAcyclicGraphShortestPath.cc delete mode 100644 src/0003_Graph/0011_SingleSourceShortestPathDijkstra.cc delete mode 100644 src/0003_Graph/0012_DifferenceConstraintsShortestPaths.cc delete mode 100644 src/0003_Graph/0013_AllPairsShortestPathsFloydWarshall.cc delete mode 100644 src/0003_Graph/0014_AllPairsShortestPathsJohnson.cc delete mode 100644 src/0003_Graph/0015_MaximumFlowFordFulkerson.cc delete mode 100644 src/0003_Graph/0016_MaximumFlowEdmondsKarp.cc delete mode 100644 src/0003_Graph/0017_MaximumBipartiteMatching.cc delete mode 100644 src/0003_Graph/0018_MaximumFlowGoldbergGenericPushRelabel.cc delete mode 100644 src/0003_Graph/0019_MaximumFlowRelabelToFront.cc delete mode 100644 src/0003_Graph/CMakeLists.txt delete mode 100644 src/0003_graph/headers/0001_BreadthFirstSearch.h delete mode 100644 src/0003_graph/headers/0002_DepthFirstSearch.h delete mode 100644 src/0003_graph/headers/0003_TopologicalSort.h delete mode 100644 src/0003_graph/headers/0004_StronglyConnectedComponents.h delete mode 100644 src/0003_graph/headers/0005_HamiltonianPathAndCycle.h delete mode 100644 src/0003_graph/headers/0006_EulerianPathAndCircuit.h delete mode 100644 src/0003_graph/headers/0007_MinimumSpanningTreeKruskalAlgorithm.h delete mode 100644 src/0003_graph/headers/0008_MinimumSpanningTreePrimAlgorithm.h delete mode 100644 src/0003_graph/headers/0009_SingleSourceShortestPathBellmanFord.h delete mode 100644 src/0003_graph/headers/0010_DirectedAcyclicGraphShortestPath.h delete mode 100644 src/0003_graph/headers/0011_SingleSourceShortestPathDijkstra.h delete mode 100644 src/0003_graph/headers/0012_DifferenceConstraintsShortestPaths.h delete mode 100644 src/0003_graph/headers/0013_AllPairsShortestPathsFloydWarshall.h delete mode 100644 src/0003_graph/headers/0014_AllPairsShortestPathsJohnson.h delete mode 100644 src/0003_graph/headers/0015_MaximumFlowFordFulkerson.h delete mode 100644 src/0003_graph/headers/0016_MaximumFlowEdmondsKarp.h delete mode 100644 src/0003_graph/headers/0017_MaximumBipartiteMatching.h delete mode 100644 src/0003_graph/headers/0018_MaximumFlowGoldbergGenericPushRelabel.h delete mode 100644 src/0003_graph/headers/0019_MaximumFlowRelabelToFront.h delete mode 100644 src/0004_dynamic_programming/0001_FibonacciNumber.cc delete mode 100644 src/0004_dynamic_programming/0002_TribonacciNumber.cc delete mode 100644 src/0004_dynamic_programming/0003_ClimbingStairs.cc delete mode 100644 src/0004_dynamic_programming/0004_MinimumCostClimbingStairs.cc delete mode 100644 src/0004_dynamic_programming/0005_HouseRobber1.cc delete mode 100644 src/0004_dynamic_programming/0006_HouseRobber2.cc delete mode 100644 src/0004_dynamic_programming/0007_DecodeWays.cc delete mode 100644 src/0004_dynamic_programming/0008_TilingProblem.cc delete mode 100644 src/0004_dynamic_programming/0009_FriendsPairingProblem.cc delete mode 100644 src/0004_dynamic_programming/0010_WaysToCoverDistance.cc delete mode 100644 src/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrder.cc delete mode 100644 src/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrder.cc delete mode 100644 src/0004_dynamic_programming/0013_KnapsackProblem.cc delete mode 100644 src/0004_dynamic_programming/0014_SubsetSumProblem.cc delete mode 100644 src/0004_dynamic_programming/0015_CountSubsetsForSum.cc delete mode 100644 src/0004_dynamic_programming/0016_PartitionEqualSubsetSum.cc delete mode 100644 src/0004_dynamic_programming/0017_TargetSum.cc delete mode 100644 src/0004_dynamic_programming/CMakeLists.txt delete mode 100644 src/0004_dynamic_programming/headers/0001_FibonacciNumber.h delete mode 100644 src/0004_dynamic_programming/headers/0002_TribonacciNumber.h delete mode 100644 src/0004_dynamic_programming/headers/0003_ClimbingStairs.h delete mode 100644 src/0004_dynamic_programming/headers/0004_MinimumCostClimbingStairs.h delete mode 100644 src/0004_dynamic_programming/headers/0005_HouseRobber1.h delete mode 100644 src/0004_dynamic_programming/headers/0006_HouseRobber2.h delete mode 100644 src/0004_dynamic_programming/headers/0007_DecodeWays.h delete mode 100644 src/0004_dynamic_programming/headers/0008_TilingProblem.h delete mode 100644 src/0004_dynamic_programming/headers/0009_FriendsPairingProblem.h delete mode 100644 src/0004_dynamic_programming/headers/0010_WaysToCoverDistance.h delete mode 100644 src/0004_dynamic_programming/headers/0011_CountWaysToReachNthStairIncludeOrder.h delete mode 100644 src/0004_dynamic_programming/headers/0012_CountWaysToReachNthStairExcludeOrder.h delete mode 100644 src/0004_dynamic_programming/headers/0013_KnapsackProblem.h delete mode 100644 src/0004_dynamic_programming/headers/0014_SubsetSumProblem.h delete mode 100644 src/0004_dynamic_programming/headers/0015_CountSubsetsForSum.h delete mode 100644 src/0004_dynamic_programming/headers/0016_PartitionEqualSubsetSum.h delete mode 100644 src/0004_dynamic_programming/headers/0017_TargetSum.h delete mode 100644 src/0005_greedy_algorithms/CMakeLists.txt delete mode 100644 src/0006_bitwise_algorithms/CMakeLists.txt delete mode 100644 src/CMakeLists.txt delete mode 100644 tests/0000_common_utilities/CMakeLists.txt delete mode 100644 tests/0000_common_utilities/UnitTestHelper.h delete mode 100644 tests/0001_Basics/CMakeLists.txt delete mode 100644 tests/0001_Basics/NodeTest.cc delete mode 100644 tests/0002_Tree/0001_BinarySearchTreeTest.cc delete mode 100644 tests/0002_Tree/CMakeLists.txt delete mode 100644 tests/0003_Graph/0001_BreadthFirstSearchTest.cc delete mode 100644 tests/0003_Graph/0002_DepthFirstSearchTest.cc delete mode 100644 tests/0003_Graph/0003_TopologicalSortTest.cc delete mode 100644 tests/0003_Graph/0004_StronglyConnectedComponentsTest.cc delete mode 100644 tests/0003_Graph/0005_HamiltonianPathAndCycleTest.cc delete mode 100644 tests/0003_Graph/0006_EulerianPathAndCircuitTest.cc delete mode 100644 tests/0003_Graph/0007_MinimumSpanningTreeKruskalAlgorithmTest.cc delete mode 100644 tests/0003_Graph/0008_MinimumSpanningTreePrimAlgorithmTest.cc delete mode 100644 tests/0003_Graph/0009_SingleSourceShortestPathBellmanFordTest.cc delete mode 100644 tests/0003_Graph/0010_DirectedAcyclicGraphShortestPathTest.cc delete mode 100644 tests/0003_Graph/0011_SingleSourceShortestPathDijkstraTest.cc delete mode 100644 tests/0003_Graph/0012_DifferenceConstraintsShortestPathsTest.cc delete mode 100644 tests/0003_Graph/0013_AllPairsShortestPathsFloydWarshallTest.cc delete mode 100644 tests/0003_Graph/0014_AllPairsShortestPathsJohnsonTest.cc delete mode 100644 tests/0003_Graph/0015_MaximumFlowFordFulkersonTest.cc delete mode 100644 tests/0003_Graph/0016_MaximumFlowEdmondsKarpTest.cc delete mode 100644 tests/0003_Graph/0017_MaximumBipartiteMatchingTest.cc delete mode 100644 tests/0003_Graph/0018_MaximumFlowGoldbergGenericPushRelabelTest.cc delete mode 100644 tests/0003_Graph/0019_MaximumFlowRelabelToFrontTest.cc delete mode 100644 tests/0003_Graph/CMakeLists.txt delete mode 100644 tests/0004_dynamic_programming/0001_FibonacciNumberTest.cc delete mode 100644 tests/0004_dynamic_programming/0002_TribonacciNumberTest.cc delete mode 100644 tests/0004_dynamic_programming/0003_ClimbingStairsTest.cc delete mode 100644 tests/0004_dynamic_programming/0004_MinimumCostClimbingStairsTest.cc delete mode 100644 tests/0004_dynamic_programming/0005_HouseRobber1Test.cc delete mode 100644 tests/0004_dynamic_programming/0006_HouseRobber2Test.cc delete mode 100644 tests/0004_dynamic_programming/0007_DecodeWaysTest.cc delete mode 100644 tests/0004_dynamic_programming/0008_TilingProblemTest.cc delete mode 100644 tests/0004_dynamic_programming/0009_FriendsPairingProblemTest.cc delete mode 100644 tests/0004_dynamic_programming/0010_WaysToCoverDistanceTest.cc delete mode 100644 tests/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrderTest.cc delete mode 100644 tests/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrderTest.cc delete mode 100644 tests/0004_dynamic_programming/0013_KnapsackProblemTest.cc delete mode 100644 tests/0004_dynamic_programming/0014_SubsetSumProblemTest.cc delete mode 100644 tests/0004_dynamic_programming/0015_CountSubsetsForSumTest.cc delete mode 100644 tests/0004_dynamic_programming/0016_PartitionEqualSubsetSumTest.cc delete mode 100644 tests/0004_dynamic_programming/0017_TargetSumTest.cc delete mode 100644 tests/0004_dynamic_programming/CMakeLists.txt delete mode 100644 tests/0005_greedy_algorithms/CMakeLists.txt delete mode 100644 tests/0006_bitwise_algorithms/CMakeLists.txt delete mode 100644 tests/CMakeLists.txt diff --git a/.clang-tidy b/.clang-tidy deleted file mode 100644 index b797f75..0000000 --- a/.clang-tidy +++ /dev/null @@ -1,27 +0,0 @@ -Checks: > - readability-identifier-naming - -WarningsAsErrors: '*' - -HeaderFilterRegex: '(include/.*|source/.*)' - -CheckOptions: - # Private member variables - - key: readability-identifier-naming.PrivateMemberPrefix - value: _ - - key: readability-identifier-naming.PrivateMemberCase - value: camelBack - - # Member function (non-static, non-const, non-virtual) - - key: readability-identifier-naming.MethodCase - value: CamelCase - - # Class names - - key: readability-identifier-naming.ClassCase - value: CamelCase - - # Optional, but ensures errors are reported instead of silently skipped - - key: readability-identifier-naming.IgnoreFailures - value: false - - key: readability-identifier-naming.IgnoreFailedSplit - value: false \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index bfe83ee..0000000 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,28 +0,0 @@ -## Bug Report - -### Describe the Bug -_A clear and concise description of what the bug is._ - -### Steps to Reproduce -_Steps to reproduce the behavior:_ -1. Go to `path/to/file.cpp` -2. Run the test case: `./test_case_name` -3. Observe the error - -### Expected Behavior -_A clear and concise description of what you expected to happen._ - -### Screenshots/Outputs -_If applicable, add screenshots or log output to help explain the issue._ - -### Environment (please complete the following information): -- **OS:** [e.g., Windows, macOS, Linux] -- **Compiler:** [e.g., GCC 11, Clang 14, MSVC] -- **CMake Version:** [if applicable] -- **Any other relevant setup details** - -### Possible Fix (Optional) -_If you have an idea of how to fix it, mention it here._ - -### Additional Context -_Add any other context about the problem here._ diff --git a/.github/labeler.yaml b/.github/labeler.yaml deleted file mode 100644 index dae837a..0000000 --- a/.github/labeler.yaml +++ /dev/null @@ -1,51 +0,0 @@ -# Data Structures and Algorithms: These labels group include, src, and tests by their specific topic -basics: - - changed-files: - - any-glob-to-any-file: 'include/0001_Basics/**' - - any-glob-to-any-file: 'src/0001_Basics/**' - - any-glob-to-any-file: 'tests/0001_Basics/**' -tree: - - changed-files: - - any-glob-to-any-file: 'include/0002_Tree/**' - - any-glob-to-any-file: 'src/0002_Tree/**' - - any-glob-to-any-file: 'tests/0002_Tree/**' -graph: - - changed-files: - - any-glob-to-any-file: 'include/0003_Graph/**' - - any-glob-to-any-file: 'src/0003_Graph/**' - - any-glob-to-any-file: 'tests/0003_Graph/**' -greedy-algorithms: - - changed-files: - - any-glob-to-any-file: 'include/0004_GreedyAlgorithms/**' - - any-glob-to-any-file: 'src/0004_GreedyAlgorithms/**' - - any-glob-to-any-file: 'tests/0004_GreedyAlgorithms/**' -dynamic-programming: - - changed-files: - - any-glob-to-any-file: 'include/0005_DynamicProgramming/**' - - any-glob-to-any-file: 'src/0005_DynamicProgramming/**' - - any-glob-to-any-file: 'tests/0005_DynamicProgramming/**' -bitwise-algorithms: - - changed-files: - - any-glob-to-any-file: 'include/0006_BitwiseAlgorithms/**' - - any-glob-to-any-file: 'src/0006_BitwiseAlgorithms/**' - - any-glob-to-any-file: 'tests/0006_BitwiseAlgorithms/**' - -# Build System: Only fires when every changed file is a CMakeLists.txt -build: - - changed-files: - - all-globs-to-all-files: '**/CMakeLists.txt' - -# Testing Utils: Catches the helper files in tests/0000_CommonUtilities -test-utils: - - changed-files: - - any-glob-to-any-file: 'tests/0000_CommonUtilities/**' - -# Tooling: Github workflows -workflows: - - changed-files: - - any-glob-to-any-file: '.github/**' - -# Documentation: Root level MD files -documentation: - - changed-files: - - any-glob-to-any-file: '*.md' \ No newline at end of file diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md deleted file mode 100644 index b9581fa..0000000 --- a/.github/pull_request_template.md +++ /dev/null @@ -1,28 +0,0 @@ -### Pull Request Guidelines - -1. **feature → release:** Please provide a description of the solution or fix. The `auto-labeler` bot will automatically label this PR based on the files changed. -2. **release → main:** **Please select the version bump type**, release notes will be auto-generated from the merged feature PRs. - -### feature to release -*(Fill this out when merging a feature branch into a release branch)* - -**Description Category** -- [ ] Basics -- [ ] Tree -- [ ] Graph -- [ ] GreedyAlgorithms -- [ ] DynamicProgramming -- [ ] BitwiseAlgorithms - -**Notes** - - - - -### release to main -*(Fill this out ONLY when merging a release branch into main)* - -**Version Bump Type** -- [ ] Major -- [ ] Minor -- [ ] Patch \ No newline at end of file diff --git a/.github/release.yaml b/.github/release.yaml deleted file mode 100644 index f4ee77d..0000000 --- a/.github/release.yaml +++ /dev/null @@ -1,56 +0,0 @@ -template: | - ### datastructures-algorithms — release v$RESOLVED_VERSION - $CHANGES - - **Full Changelog:** https://github.com/$OWNER/$REPOSITORY/compare/$PREVIOUS_TAG...v$RESOLVED_VERSION - -change-template: '- $TITLE [#$NUMBER]' - -categories: - - title: 'Basics' - labels: - - 'basics' - - - title: 'Tree' - labels: - - 'tree' - - - title: 'Graph' - labels: - - 'graph' - - - title: 'Greedy Algorithms' - labels: - - 'greedy-algorithms' - - - title: 'Dynamic Programming' - labels: - - 'dynamic-programming' - - - title: 'Bitwise Algorithms' - labels: - - 'bitwise-algorithms' - - - title: 'Build System (CMake)' - labels: - - 'build' - - - title: 'Testing Utilities' - labels: - - 'test-utils' - - - title: 'Workflows Updated' - labels: - - 'workflows' - - - title: 'Documentation' - labels: - - 'documentation' - -exclude-labels: - - 'skip-changelog' - -# Convert "## Title" to "**Title**" -replacers: - - search: '/^## (.*)$/gm' - replace: '**$1**' \ No newline at end of file diff --git a/.github/workflows/auto-labeler.yaml b/.github/workflows/auto-labeler.yaml deleted file mode 100644 index df13bc0..0000000 --- a/.github/workflows/auto-labeler.yaml +++ /dev/null @@ -1,36 +0,0 @@ -name: auto-labeler - -# Run this on every PR open or update -on: - pull_request: - types: [opened, synchronize, reopened] - -permissions: - contents: read - # Required to add labels - pull-requests: write - -jobs: - assign-labels: - runs-on: ubuntu-latest - steps: - - name: Checkout Repository - uses: actions/checkout@v4 - # 1. Standard File-based Labeler (Contest vs Problemset) - - name: Assign Labels Based on Changes - id: labeler - uses: actions/labeler@v5 - with: - # This tells it to look at your .github/labeler.yaml - configuration-path: .github/labeler.yaml - repo-token: "${{ secrets.GITHUB_TOKEN }}" - sync-labels: true - - # 2. NEW: Branch-based Labeler (Ignore Release Branches) - - name: Label Release PRs to Skip Changelog - # Only run if the source branch starts with 'release/' - if: startsWith(github.head_ref, 'release/') - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - gh pr edit ${{ github.event.pull_request.number }} --add-label "skip-changelog" \ No newline at end of file diff --git a/.github/workflows/deploy.yaml b/.github/workflows/deploy.yaml deleted file mode 100644 index 9f024d9..0000000 --- a/.github/workflows/deploy.yaml +++ /dev/null @@ -1,160 +0,0 @@ -name: deploy - -# Triggers only when a PR to 'main' is closed -on: - pull_request: - types: [closed] - branches: - - 'main' - -permissions: - contents: write # Required to push tags and create releases - pull-requests: read # Required to read PR body for checkboxes - -jobs: - # job 1: Deployment Validation - # Verifies the PR is merged, comes from a release/* branch, and has a bump type. - deployment-validation: - runs-on: ubuntu-latest - # Define outputs to pass to the next job - outputs: - bump_type: ${{ steps.get_bump_type.outputs.bump_type }} - - steps: - - name: Verify Merge and Branch Policy - run: | - IS_MERGED="${{ github.event.pull_request.merged }}" - HEAD_REF="${{ github.event.pull_request.head.ref }}" - - echo "PR Merged: $IS_MERGED" - echo "Source Branch: $HEAD_REF" - - # 1. Check if PR was actually merged (not just closed) - if [[ "$IS_MERGED" != "true" ]]; then - echo "::notice::PR was closed without merging. Skipping release." - exit 1 - fi - - # 2. Check if source branch starts with 'release/' - if [[ "$HEAD_REF" != release/* ]]; then - echo "::error::Invalid source branch. Releases must originate from 'release/*' branches." - exit 1 - fi - - echo "Branch policy checks passed." - - - name: Determine Version Bump Type - id: get_bump_type - env: - PR_BODY: ${{ github.event.pull_request.body }} - run: | - # Check checkboxes in PR Body: [x] Major, [x] Minor, etc. - if echo "$PR_BODY" | grep -q '\[x\] Major'; then - echo "bump_type=major" >> $GITHUB_OUTPUT - echo "Detected bump: MAJOR" - elif echo "$PR_BODY" | grep -q '\[x\] Minor'; then - echo "bump_type=minor" >> $GITHUB_OUTPUT - echo "Detected bump: MINOR" - elif echo "$PR_BODY" | grep -q '\[x\] Patch'; then - echo "bump_type=patch" >> $GITHUB_OUTPUT - echo "Detected bump: PATCH" - else - echo "::error::No version bump detected. Please check [x] Major, [x] Minor, or [x] Patch in the PR body." - exit 1 - fi - - # job 2: Create GitHub Tag and Release - create-github-tag-and-release: - needs: deployment-validation - runs-on: ubuntu-latest - env: - BUMP_TYPE: ${{ needs.deployment-validation.outputs.bump_type }} - - steps: - - name: Checkout main branch - uses: actions/checkout@v4 - with: - ref: 'main' - fetch-depth: 0 # Crucial for calculating history/tags - - - name: Configure Git - run: | - git config --global user.name "github-actions[bot]" - git config --global user.email "github-actions[bot]@users.noreply.github.com" - - # Step A: Find the existing tag - - name: Get Latest Tag - id: get_latest_tag - run: | - # 1. Fetch all tags - git fetch --tags - - # 2. Find latest tag (Sort by version number, take top) - LATEST_TAG=$(git tag --list 'v*.*.*' --sort=-v:refname | head -n 1) - - if [ -z "$LATEST_TAG" ]; then - echo "No previous tags found. Defaulting to v0.0.0" - LATEST_TAG="v0.0.0" - fi - - echo "Latest Tag: $LATEST_TAG" - - # Expose this variable to the next step - echo "latest_tag=$LATEST_TAG" >> $GITHUB_OUTPUT - - # Step B: Do the math - - name: Calculate New Tag - id: calc_new_tag - env: - # Pull the tag from the previous step - LATEST_TAG: ${{ steps.get_latest_tag.outputs.latest_tag }} - # Assuming BUMP_TYPE is set in the Job 'env' as per previous context - run: | - echo "Base Tag: $LATEST_TAG" - echo "Bump Type: $BUMP_TYPE" - - # 1. Parse Version - VERSION=${LATEST_TAG#v} # Remove 'v' - IFS='.' read -r -a parts <<< "$VERSION" - MAJOR=${parts[0]} - MINOR=${parts[1]} - PATCH=${parts[2]} - - # 2. Increment - case "$BUMP_TYPE" in - "major") MAJOR=$((MAJOR + 1)); MINOR=0; PATCH=0 ;; - "minor") MINOR=$((MINOR + 1)); PATCH=0 ;; - "patch") PATCH=$((PATCH + 1)) ;; - esac - - NEW_TAG="v${MAJOR}.${MINOR}.${PATCH}" - - echo "new_tag=$NEW_TAG" >> $GITHUB_OUTPUT - echo "New tag will be: $NEW_TAG" - - - name: Create and push new Git tag - run: | - NEW_TAG=${{ steps.calc_new_tag.outputs.new_tag }} - MERGE_COMMIT_SHA=${{ github.event.pull_request.merge_commit_sha }} - - echo "Tagging commit $MERGE_COMMIT_SHA as $NEW_TAG" - git tag $NEW_TAG $MERGE_COMMIT_SHA - git push origin $NEW_TAG - - # Step D: Generate Auto-Notes and Publish - - name: Create GitHub Release - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - uses: release-drafter/release-drafter@v6 - with: - # Uses your .github/release.yaml to categorize changes - config-name: release.yaml - - # We force it to use the tag you just calculated and pushed - tag: ${{ steps.calc_new_tag.outputs.new_tag }} - name: "${{ steps.calc_new_tag.outputs.new_tag }}" - version: ${{ steps.calc_new_tag.outputs.new_tag }} - - # This makes it a real release (not a draft) - publish: true - \ No newline at end of file diff --git a/.github/workflows/validate.yaml b/.github/workflows/validate.yaml deleted file mode 100644 index 47a55f5..0000000 --- a/.github/workflows/validate.yaml +++ /dev/null @@ -1,130 +0,0 @@ -name: validate - -on: - pull_request: - types: [opened, synchronize] - branches: - - 'release/*' - - 'main' - -jobs: - # job 1: Policy Check - validate-branch-policy: - runs-on: ubuntu-latest - steps: - - name: Verify Branch Strategy - run: | - HEAD="${{ github.head_ref }}" - BASE="${{ github.base_ref }}" - echo "Verifying path: $HEAD -> $BASE" - - if [[ "$HEAD" == feature/* && "$BASE" == release/* ]]; then - echo "Pull Request is allowed: $HEAD -> $BASE." - exit 0 - elif [[ "$HEAD" == release/* && "$BASE" == main ]]; then - echo "Pull Request is allowed: $HEAD -> $BASE." - exit 0 - else - echo "::error::Invalid Pull Request from '$HEAD' -> '$BASE'." - echo "Allowed: 'feature/*'->'release/*' OR 'release/*'->'main'." - exit 1 - fi - - # job 2: Static Analysis - lint-code: - needs: validate-branch-policy - runs-on: windows-latest - steps: - - name: Checkout code - uses: actions/checkout@v4 - - - name: Setup MSVC - uses: ilammy/msvc-dev-cmd@v1 - with: - arch: x64 - - - name: Install dependencies - shell: pwsh - run: | - choco install cmake --no-progress -y - choco install ninja --no-progress -y - choco install llvm --no-progress -y - - - name: Configure CMake - shell: pwsh - run: cmake -S . -B build -G "Ninja" -DCMAKE_EXPORT_COMPILE_COMMANDS=ON - - - name: Run clang-tidy - shell: pwsh - run: | - clang-tidy --version - $files = Get-ChildItem -Recurse -Path src -Include *.cpp,*.cc,*.cxx -File - $failed = $false - # These source/.* files would be checked using .clang-tidy maintained at projectroot - foreach ($file in $files) { - Write-Host "Checking $($file.FullName)" - clang-tidy -p build "$($file.FullName)" --warnings-as-errors=* - if ($LASTEXITCODE -ne 0) { $failed = $true } - } - if ($failed) { Write-Error "Clang-tidy failed."; exit 1 } - - # job 3: Build Project - build-project: - needs: lint-code - runs-on: windows-latest - steps: - - name: Checkout code - uses: actions/checkout@v4 - - - name: Setup MSVC - uses: ilammy/msvc-dev-cmd@v1 - with: - arch: x64 - - - name: Install dependencies - shell: pwsh - run: | - choco install cmake --no-progress -y - choco install ninja --no-progress -y - - - name: Configure CMake - shell: pwsh - run: cmake -S . -B build -G "Ninja" - - - name: Build - shell: pwsh - run: cmake --build build --config Release - - # Upload the build directory so the Test job can use it - - name: Upload Build Artifacts - uses: actions/upload-artifact@v4 - with: - name: build-artifacts - path: build/ - retention-days: 1 - - # job 4: Run all Tests - run-all-tests: - needs: build-project - runs-on: windows-latest - steps: - - name: Checkout code - # We need the source code because CTest might look for source files referenced in tests - uses: actions/checkout@v4 - - - name: Install dependencies - shell: pwsh - # We only need CMake (for ctest) here. Ninja/LLVM usually not needed unless tests invoke them. - run: choco install cmake --no-progress -y - - - name: Download Build Artifacts - uses: actions/download-artifact@v4 - with: - name: build-artifacts - path: build - - - name: Run tests - shell: pwsh - # -C Release is crucial if it's a multi-config generator, though Ninja is single-config. - # Good practice to keep it for consistency. - run: ctest --test-dir build --output-on-failure -C Release \ No newline at end of file diff --git a/.gitignore b/.gitignore deleted file mode 100644 index ccdf92f..0000000 --- a/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -.vs/ -.vscode/ -artifact/ \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt deleted file mode 100644 index d919238..0000000 --- a/CMakeLists.txt +++ /dev/null @@ -1,35 +0,0 @@ -cmake_minimum_required (VERSION 3.10) -project ("datastructures-algorithms") - -set(CMAKE_CXX_STANDARD 14) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_EXPORT_COMPILE_COMMANDS ON) - - -# .clang-tidy setup -find_program(CLANG_TIDY_EXE NAMES "clang-tidy") -if(CLANG_TIDY_EXE) - message(STATUS "clang-tidy found: ${CLANG_TIDY_EXE}") - set(CLANG_TIDY_COMMAND - "${CLANG_TIDY_EXE}" - "--config-file=${CMAKE_SOURCE_DIR}/.clang-tidy" - "--extra-arg-before=-Wno-unknown-warning-option" - "--extra-arg-before=-Wno-c++98-compat-pedantic" - "--quiet" - ) -endif() - -add_subdirectory(src) - -cmake_policy(SET CMP0135 NEW) -include(FetchContent) -FetchContent_Declare( - googletest - URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip -) - -# For Windows: Prevent overriding the parent project's compiler/linker settings -set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) - -enable_testing() -add_subdirectory(tests) \ No newline at end of file diff --git a/CMakePresets.json b/CMakePresets.json deleted file mode 100644 index 71f41cb..0000000 --- a/CMakePresets.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "version": 3, - "configurePresets": [ - { - "name": "windows-base", - "hidden": true, - "generator": "Ninja", - "binaryDir": "${sourceDir}/artifact/build/${presetName}", - "installDir": "${sourceDir}/artifact/install/${presetName}", - "cacheVariables": { - "CMAKE_C_COMPILER": "cl.exe", - "CMAKE_CXX_COMPILER": "cl.exe" - }, - "condition": { - "type": "equals", - "lhs": "${hostSystemName}", - "rhs": "Windows" - } - }, - { - "name": "x64-debug", - "displayName": "x64 Debug", - "inherits": "windows-base", - "architecture": { - "value": "x64", - "strategy": "external" - }, - "cacheVariables": { - "CMAKE_BUILD_TYPE": "Debug" - } - }, - { - "name": "x64-release", - "displayName": "x64 Release", - "inherits": "x64-debug", - "cacheVariables": { - "CMAKE_BUILD_TYPE": "Release" - } - }, - { - "name": "x86-debug", - "displayName": "x86 Debug", - "inherits": "windows-base", - "architecture": { - "value": "x86", - "strategy": "external" - }, - "cacheVariables": { - "CMAKE_BUILD_TYPE": "Debug" - } - }, - { - "name": "x86-release", - "displayName": "x86 Release", - "inherits": "x86-debug", - "cacheVariables": { - "CMAKE_BUILD_TYPE": "Release" - } - } - ] -} diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md deleted file mode 100644 index 3f705c7..0000000 --- a/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,127 +0,0 @@ -## Contributor Covenant Code of Conduct - -### Our Pledge - -We as members, contributors, and leaders pledge to make participation in our -community a harassment-free experience for everyone, regardless of age, body -size, visible or invisible disability, ethnicity, sex characteristics, gender -identity and expression, level of experience, education, socio-economic status, -nationality, personal appearance, race, religion, or sexual identity -and orientation. - -We pledge to act and interact in ways that contribute to an open, welcoming, -diverse, inclusive, and healthy community. - -### Our Standards - -Examples of behavior that contributes to a positive environment for our -community include: - -* Demonstrating empathy and kindness toward other people -* Being respectful of differing opinions, viewpoints, and experiences -* Giving and gracefully accepting constructive feedback -* Accepting responsibility and apologizing to those affected by our mistakes, - and learning from the experience -* Focusing on what is best not just for us as individuals, but for the - overall community - -Examples of unacceptable behavior include: - -* The use of sexualized language or imagery, and sexual attention or - advances of any kind -* Trolling, insulting or derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or email - address, without their explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -### Enforcement Responsibilities - -Community leaders are responsible for clarifying and enforcing our standards of -acceptable behavior and will take appropriate and fair corrective action in -response to any behavior that they deem inappropriate, threatening, offensive, -or harmful. - -Community leaders have the right and responsibility to remove, edit, or reject -comments, commits, code, wiki edits, issues, and other contributions that are -not aligned to this Code of Conduct, and will communicate reasons for moderation -decisions when appropriate. - -### Scope - -This Code of Conduct applies within all community spaces, and also applies when -an individual is officially representing the community in public spaces. -Examples of representing our community include using an official e-mail address, -posting via an official social media account, or acting as an appointed -representative at an online or offline event. - -### Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported to the community leaders responsible for enforcement at. -All complaints will be reviewed and investigated promptly and fairly. - -All community leaders are obligated to respect the privacy and security of the -reporter of any incident. - -### Enforcement Guidelines - -Community leaders will follow these Community Impact Guidelines in determining -the consequences for any action they deem in violation of this Code of Conduct: - -#### 1. Correction - -**Community Impact**: Use of inappropriate language or other behavior deemed -unprofessional or unwelcome in the community. - -**Consequence**: A private, written warning from community leaders, providing -clarity around the nature of the violation and an explanation of why the -behavior was inappropriate. A public apology may be requested. - -#### 2. Warning - -**Community Impact**: A violation through a single incident or series -of actions. - -**Consequence**: A warning with consequences for continued behavior. No -interaction with the people involved, including unsolicited interaction with -those enforcing the Code of Conduct, for a specified period of time. This -includes avoiding interactions in community spaces as well as external channels -like social media. Violating these terms may lead to a temporary or -permanent ban. - -#### 3. Temporary Ban - -**Community Impact**: A serious violation of community standards, including -sustained inappropriate behavior. - -**Consequence**: A temporary ban from any sort of interaction or public -communication with the community for a specified period of time. No public or -private interaction with the people involved, including unsolicited interaction -with those enforcing the Code of Conduct, is allowed during this period. -Violating these terms may lead to a permanent ban. - -#### 4. Permanent Ban - -**Community Impact**: Demonstrating a pattern of violation of community -standards, including sustained inappropriate behavior, harassment of an -individual, or aggression toward or disparagement of classes of individuals. - -**Consequence**: A permanent ban from any sort of public interaction within -the community. - -### Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], -version 2.0, available at -https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. - -Community Impact Guidelines were inspired by [Mozilla's code of conduct -enforcement ladder](https://github.com/mozilla/diversity). - -[homepage]: https://www.contributor-covenant.org - -For answers to common questions about this code of conduct, see the FAQ at -https://www.contributor-covenant.org/faq. Translations are available at -https://www.contributor-covenant.org/translations. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 68a2127..0000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1 +0,0 @@ -## This project is for academic purpose, no contributions are expected right now. diff --git a/LICENSE b/LICENSE deleted file mode 100644 index fd336ec..0000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2025 Debashis Nandi - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/README.md b/README.md deleted file mode 100644 index bd633b7..0000000 --- a/README.md +++ /dev/null @@ -1,21 +0,0 @@ -## Data Structures and Algorithms - -This repository contains a collection of **data structures and algorithms** implemented in **C++**. It is designed to provide efficient solutions to common algorithmic problems while adhering to clean coding practices and modular design. - -### Features - -- **Data Structures and Algorithms:** Implementations of data structures and algorithms based on the concepts from the book ***Introduction to Algorithms by Cormen, Leiserson, Rivest, and Stein (CLRS).*** -- **Modular Design:** Code is organized into manageable modules for better readability and reusability. -- **Testing:** - - Built with **CMake** as the build system for ease of compilation and dependency management. - - **Google Test** framework is integrated for comprehensive unit testing to ensure code correctness. - -### Folder Structure - -```plain text -datastructures-algorithms -├── include # Header Files -├── src # Implementation of the solutions -├── tests # Unit tests for implemented solutions -└── CMakeLists.txt # CMake configuration file -``` diff --git a/SECURITY.md b/SECURITY.md deleted file mode 100644 index 206769a..0000000 --- a/SECURITY.md +++ /dev/null @@ -1 +0,0 @@ -## Security Policy diff --git a/src/0001_Basics/CMakeLists.txt b/src/0001_Basics/CMakeLists.txt deleted file mode 100644 index 477c6cd..0000000 --- a/src/0001_Basics/CMakeLists.txt +++ /dev/null @@ -1,11 +0,0 @@ -# Specify the source files -set(0001BASICS_SOURCES - Node.cc -) - -# Create a library target -add_library(0001BASICS ${0001BASICS_SOURCES}) - -target_include_directories(0001BASICS PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/headers -) \ No newline at end of file diff --git a/src/0001_Basics/Node.cc b/src/0001_Basics/Node.cc deleted file mode 100644 index df1effa..0000000 --- a/src/0001_Basics/Node.cc +++ /dev/null @@ -1,6 +0,0 @@ -#include "Node.h" - -Node::Node() -{ - value = 8; -} \ No newline at end of file diff --git a/src/0001_basics/headers/Node.h b/src/0001_basics/headers/Node.h deleted file mode 100644 index dcee809..0000000 --- a/src/0001_basics/headers/Node.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -class Node -{ -public: - int value; - Node(); -}; \ No newline at end of file diff --git a/src/0002_Tree/0001_BinarySearchTree.cc b/src/0002_Tree/0001_BinarySearchTree.cc deleted file mode 100644 index ba78751..0000000 --- a/src/0002_Tree/0001_BinarySearchTree.cc +++ /dev/null @@ -1,349 +0,0 @@ -#include "0001_BinarySearchTree.h" -#include -#include -using namespace std; - -namespace BinarySearchTree -{ - Node::Node(int data, Node* parent, Node* left, Node* right) - { - this->data = data; - this->parent = parent; - this->left = left; - this->right = right; - } - - BinarySearchTree::BinarySearchTree() - { - this->_root = nullptr; - } - - - void BinarySearchTree::InsertBinarySearchTreeNode(Node* node) - { - Node* nodeY = nullptr; - Node* nodeX = this->_root; - while (nodeX != nullptr) - { - nodeY = nodeX; - if (node->data < nodeX->data) - { - nodeX = nodeX->left; - } - else - { - nodeX = nodeX->right; - } - } - node->parent = nodeY; - if (nodeY == nullptr) - { - this->_root = node; - } - else if (node->data < nodeY->data) - { - nodeY->left = node; - } - else - { - nodeY->right = node; - } - } - - Node* BinarySearchTree::FindBinarySearchTreeNode(int value) - { - Node* node = this->_root; - while (node != nullptr) - { - if (value < node->data) - { - node = node->left; - } - else if (value > node->data) - { - node = node->right; - } - else - { - break; - } - } - return node; - } - - Node* BinarySearchTree::FindBinarySearchTreeMinimumValueNode(Node* node) - { - while (node->left != nullptr) - { - node = node->left; - } - return node; - } - - Node* BinarySearchTree::FindBinarySearchTreeMaximumValueNode(Node* node) - { - while (node->right != nullptr) - { - node = node->right; - } - return node; - } - - Node* BinarySearchTree::FindSuccessorBinarySearchTreeNode(Node* node) - { - if (node->right != nullptr) - { - return this->FindBinarySearchTreeMinimumValueNode(node->right); - } - Node* nodeY = node->parent; - while (nodeY != nullptr && node == nodeY->right) - { - node = nodeY; - nodeY = nodeY->parent; - } - return nodeY; - } - - Node* BinarySearchTree::FindPredecessorBinarySearchTreeNode(Node* node) - { - if (node->left != nullptr) - { - return this->FindBinarySearchTreeMaximumValueNode(node->left); - } - Node* nodeY = node->parent; - while (nodeY != nullptr && node == nodeY->left) - { - node = nodeY; - nodeY = nodeY->parent; - } - return nodeY; - } - - void BinarySearchTree::TransplantBinarySearchTreeNode(Node* nodeU, Node* nodeV) - { - if (nodeU->parent == nullptr) - { - this->_root = nodeV; - } - else if (nodeU == nodeU->parent->left) - { - nodeU->parent->left = nodeV; - } - else - { - nodeU->parent->right = nodeV; - } - - if (nodeV != nullptr) - { - nodeV->parent = nodeU->parent; - } - } - - void BinarySearchTree::DeleteBinarySearchTreeNode(Node* node) - { - if (node->left == nullptr) - { - this->TransplantBinarySearchTreeNode(node, node->right); - } - else if (node->right == nullptr) - { - this->TransplantBinarySearchTreeNode(node, node->left); - } - else - { - Node* nodeY = this->FindBinarySearchTreeMinimumValueNode(node->right); - if (nodeY->parent != node) - { - this->TransplantBinarySearchTreeNode(nodeY, nodeY->right); - nodeY->right = node->right; - nodeY->right->parent = nodeY; - } - this->TransplantBinarySearchTreeNode(node, nodeY); - nodeY->left = node->left; - nodeY->left->parent = nodeY; - delete node; - } - } - - void BinarySearchTree::RecursiveInorderTraversal(Node* node, vector& result) - { - if (node == nullptr) - { - return; - } - this->RecursiveInorderTraversal(node->left, result); - result.push_back(node->data); - this->RecursiveInorderTraversal(node->right, result); - } - - void BinarySearchTree::RecursivePreorderTraversal(Node* node, vector& result) - { - if (node == nullptr) - { - return; - } - result.push_back(node->data); - this->RecursivePreorderTraversal(node->left, result); - this->RecursivePreorderTraversal(node->right, result); - } - - void BinarySearchTree::RecursivePostorderTraversal(Node* node, vector& result) - { - if (node == nullptr) - { - return; - } - this->RecursivePostorderTraversal(node->left, result); - this->RecursivePostorderTraversal(node->right, result); - result.push_back(node->data); - } - - void BinarySearchTree::MorrisInorderTraversal(Node* node, vector& result) - { - while (node != nullptr) - { - if (node->left == nullptr) - { - result.push_back(node->data); - node = node->right; - } - else - { - Node* predecessor = node->left; - while (predecessor->right != nullptr && predecessor->right != node) - { - predecessor = predecessor->right; - } - if (predecessor->right == nullptr) - { - predecessor->right = node; - node = node->left; - } - else - { - predecessor->right = nullptr; - result.push_back(node->data); - node = node->right; - } - } - } - } - - void BinarySearchTree::MorrisPreorderTraversal(Node* node, vector& result) - { - while (node != nullptr) - { - if (node->left == nullptr) - { - result.push_back(node->data); - node = node->right; - } - else - { - Node* predecessor = node->left; - while (predecessor->right != nullptr && predecessor->right != node) - { - predecessor = predecessor->right; - } - if (predecessor->right == nullptr) - { - predecessor->right = node; - result.push_back(node->data); - node = node->left; - } - else - { - predecessor->right = nullptr; - node = node->right; - } - } - } - } - - void BinarySearchTree::MorrisPostorderTraversal(Node* node, vector& result) - { - while (node != nullptr) - { - if (node->right == nullptr) - { - result.push_back(node->data); - node = node->left; - } - else - { - Node* predecessor = node->right; - while (predecessor->left != nullptr && predecessor->left != node) - { - predecessor = predecessor->left; - } - if (predecessor->left == nullptr) - { - predecessor->left = node; - result.push_back(node->data); - node = node->right; - } - else - { - predecessor->left = nullptr; - node = node->left; - } - } - } - reverse(result.begin(), result.end()); - } - - void BinarySearchTree::InsertNode(int value) - { - Node* node = new Node(value, nullptr, nullptr, nullptr); - this->InsertBinarySearchTreeNode(node); - } - - void BinarySearchTree::DeleteNode(int value) - { - Node* node = this->FindBinarySearchTreeNode(value); - this->DeleteBinarySearchTreeNode(node); - } - - vector BinarySearchTree::GetRecursiveInorderTravesalResult() - { - vector result; - this->RecursiveInorderTraversal(this->_root, result); - return result; - } - - vector BinarySearchTree::GetRecursivePreorderTravesalResult() - { - vector result; - this->RecursivePreorderTraversal(this->_root, result); - return result; - } - - vector BinarySearchTree::GetRecursivePostorderTravesalResult() - { - vector result; - this->RecursivePostorderTraversal(this->_root, result); - return result; - } - - vector BinarySearchTree::GetMorrisInorderTraversalResult() - { - vector result; - this->MorrisInorderTraversal(this->_root, result); - return result; - } - - vector BinarySearchTree::GetMorrisPreorderTraversalResult() - { - vector result; - this->MorrisPreorderTraversal(this->_root, result); - return result; - } - - vector BinarySearchTree::GetMorrisPostorderTraversalResult() - { - vector result; - this->MorrisPostorderTraversal(this->_root, result); - return result; - } -} \ No newline at end of file diff --git a/src/0002_Tree/CMakeLists.txt b/src/0002_Tree/CMakeLists.txt deleted file mode 100644 index 5508146..0000000 --- a/src/0002_Tree/CMakeLists.txt +++ /dev/null @@ -1,11 +0,0 @@ -# Specify the source files -set(0002TREE_SOURCES - 0001_BinarySearchTree.cc -) - -# Create a library target -add_library(0002TREE ${0002TREE_SOURCES}) - -target_include_directories(0002TREE PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/headers -) \ No newline at end of file diff --git a/src/0002_tree/headers/0001_BinarySearchTree.h b/src/0002_tree/headers/0001_BinarySearchTree.h deleted file mode 100644 index 1e9bcc2..0000000 --- a/src/0002_tree/headers/0001_BinarySearchTree.h +++ /dev/null @@ -1,49 +0,0 @@ -#pragma once - -#include -#include -using namespace std; - -namespace BinarySearchTree -{ - class Node - { - public: - int data; - Node* parent; - Node* left; - Node* right; - - Node(int data, Node* parent, Node* left, Node* right); - }; - - class BinarySearchTree - { - private: - Node* _root; - void InsertBinarySearchTreeNode(Node* node); - Node* FindBinarySearchTreeNode(int value); - Node* FindBinarySearchTreeMinimumValueNode(Node* node); - Node* FindBinarySearchTreeMaximumValueNode(Node* node); - Node* FindSuccessorBinarySearchTreeNode(Node* node); - Node* FindPredecessorBinarySearchTreeNode(Node* node); - void TransplantBinarySearchTreeNode(Node* nodeU, Node* nodeV); - void DeleteBinarySearchTreeNode(Node* node); - void RecursiveInorderTraversal(Node* node, vector& result); - void RecursivePreorderTraversal(Node* node, vector& result); - void RecursivePostorderTraversal(Node* node, vector& result); - void MorrisInorderTraversal(Node* node, vector& result); - void MorrisPreorderTraversal(Node* node, vector& result); - void MorrisPostorderTraversal(Node* node, vector& result); - public: - BinarySearchTree(); - void InsertNode(int value); - void DeleteNode(int value); - vector GetRecursiveInorderTravesalResult(); - vector GetRecursivePreorderTravesalResult(); - vector GetRecursivePostorderTravesalResult(); - vector GetMorrisInorderTraversalResult(); - vector GetMorrisPreorderTraversalResult(); - vector GetMorrisPostorderTraversalResult(); - }; -} \ No newline at end of file diff --git a/src/0003_Graph/0001_BreadthFirstSearch.cc b/src/0003_Graph/0001_BreadthFirstSearch.cc deleted file mode 100644 index 9a8b1ac..0000000 --- a/src/0003_Graph/0001_BreadthFirstSearch.cc +++ /dev/null @@ -1,86 +0,0 @@ -#include "0001_BreadthFirstSearch.h" -#include -#include -#include -#include -#include -#include -using namespace std; - -namespace BreadthFirstSearch -{ - Node::Node(int value) - { - this->data = value; - this->distance = INT_MAX; - this->color = WHITE; - this->parent = nullptr; - } - - Node* Graph::MakeOrFindNode(int value) - { - Node* node = nullptr; - if (this->_nodeMap.find(value) == this->_nodeMap.end()) - { - node = new Node(value); - this->_nodeMap[value] = node; - } - else - { - node = this->_nodeMap[value]; - } - return node; - } - - void Graph::BreadthFirstSearch(Node* node) - { - node->color = WHITE; - node->distance = 0; - node->parent = nullptr; - - queue nodeQueue; - nodeQueue.push(node); - - while (nodeQueue.empty() != true) - { - Node* currentNode = nodeQueue.front(); - nodeQueue.pop(); - - for (auto& adjacentNode : this->_adjlist[currentNode]) - { - if (adjacentNode->color == WHITE) - { - adjacentNode->color = GRAY; - adjacentNode->parent = currentNode; - adjacentNode->distance = currentNode->distance + 1; - nodeQueue.push(adjacentNode); - } - } - currentNode->color = BLACK; - } - } - - void Graph::PushUndirectedEdge(int valueU, int valueV) - { - Node* nodeU = this->MakeOrFindNode(valueU); - Node* nodeV = this->MakeOrFindNode(valueV); - - this->_adjlist[nodeU].push_back(nodeV); - this->_adjlist[nodeV].push_back(nodeU); - } - - void Graph::BFS(int value) - { - this->BreadthFirstSearch(this->_nodeMap[value]); - } - - vector> Graph::ShowBFSResult() - { - vector> result; - for (auto& node : this->_nodeMap) - { - result.push_back(make_pair(node.first, node.second->distance)); - } - return result; - } -} \ No newline at end of file diff --git a/src/0003_Graph/0002_DepthFirstSearch.cc b/src/0003_Graph/0002_DepthFirstSearch.cc deleted file mode 100644 index 3cbc49a..0000000 --- a/src/0003_Graph/0002_DepthFirstSearch.cc +++ /dev/null @@ -1,80 +0,0 @@ -#include "0002_DepthFirstSearch.h" -#include -#include -#include -using namespace std; - -namespace DepthFirstSearch -{ - Node::Node(int value) - { - this->data = value; - this->discoveredTime = INT_MAX; - this->finishingTime = INT_MAX; - this->color = WHITE; - this->parent = nullptr; - } - - Node* Graph::MakeOrFindNode(int value) - { - Node* node = nullptr; - if (this->_nodeMap.find(value) == this->_nodeMap.end()) - { - node = new Node(value); - this->_nodeMap[value] = node; - } - else - { - node = this->_nodeMap[value]; - } - return node; - } - - void Graph::DepthFirstSearch(Node* nodeU) - { - this->_time++; - nodeU->discoveredTime = this->_time; - nodeU->color = GRAY; - for (auto nodeV : this->_adjlist[nodeU]) - { - if (nodeV->color == WHITE) - { - nodeV->parent = nodeU; - this->DepthFirstSearch(nodeV); - } - } - nodeU->color = BLACK; - this->_time++; - nodeU->finishingTime = this->_time; - } - - void Graph::PushDirectedEdge(int valueU, int valueV) - { - Node* nodeU = this->MakeOrFindNode(valueU); - Node* nodeV = this->MakeOrFindNode(valueV); - - this->_adjlist[nodeU].push_back(nodeV); - } - - void Graph::DFS() - { - this->_time = 0; - for (auto& iterator : this->_nodeMap) - { - if (iterator.second->color == WHITE) - { - this->DepthFirstSearch(iterator.second); - } - } - } - - vector>> Graph::ShowDFSResult() - { - vector>> result; - for (auto& node : this->_nodeMap) - { - result.push_back(make_pair(node.first, make_pair(node.second->discoveredTime, node.second->finishingTime))); - } - return result; - } -} \ No newline at end of file diff --git a/src/0003_Graph/0003_TopologicalSort.cc b/src/0003_Graph/0003_TopologicalSort.cc deleted file mode 100644 index 3d4d1cb..0000000 --- a/src/0003_Graph/0003_TopologicalSort.cc +++ /dev/null @@ -1,150 +0,0 @@ -#include "0003_TopologicalSort.h" -#include -#include -#include -#include -#include -using namespace std; - -namespace TopologicalSort -{ - Node::Node(int value) - { - this->data = value; - this->color = WHITE; - this->discoveryTime = INT_MAX; - this->finishingTime = INT_MAX; - this->inDegree = 0; - this->parent = nullptr; - } - - Node* Graph::MakeOrFindNode(int value) - { - Node* node = nullptr; - if (this->_nodeMap.find(value) == this->_nodeMap.end()) - { - node = new Node(value); - this->_nodeMap[value] = node; - } - else - { - node = this->_nodeMap[value]; - } - return node; - } - - void Graph::DepthFirstSearch(Node* nodeU) - { - this->_time++; - nodeU->discoveryTime = this->_time; - nodeU->color = GRAY; - for (auto& nodeV : this->_adjlist[nodeU]) - { - if (nodeV->color == WHITE) - { - nodeV->parent = nodeU; - this->DepthFirstSearch(nodeV); - } - else if (nodeV->color == GRAY) - { - this->_hasCycle = true; - return; - } - } - nodeU->color = BLACK; - this->_time++; - nodeU->finishingTime = this->_time; - this->_topologicalSortedNodeList.push_front(nodeU); - } - - void Graph::PushDirectedEdge(int valueU, int valueV) - { - Node* nodeU = this->MakeOrFindNode(valueU); - Node* nodeV = this->MakeOrFindNode(valueV); - - this->_adjlist[nodeU].push_back(nodeV); - nodeV->inDegree++; - } - - void Graph::PushSingleNode(int valueU) - { - this->MakeOrFindNode(valueU); - } - - void Graph::TopologicalSort() - { - this->_time = 0; - for (auto& iterator : this->_nodeMap) - { - if (iterator.second->color == WHITE) - { - this->DepthFirstSearch(iterator.second); - if (this->_hasCycle == true) - { - break; - } - } - } - } - - void Graph::KahnTopologicalSort() - { - // Step-1 Compute in-degree of each vertices - // This is already done while creating the graph - this->_time = 0; - queue nodeQueue; - - // Step-2 Enqueue vertices with in-degree 0 - for (auto& node : this->_nodeMap) - { - if (node.second->inDegree == 0) - { - this->_time++; - node.second->discoveryTime = this->_time; - nodeQueue.push(node.second); - } - } - - // Step-3 Process vertices in queue - while (!nodeQueue.empty()) - { - Node* node = nodeQueue.front(); - nodeQueue.pop(); - this->_time++; - node->finishingTime = this->_time; - this->_topologicalSortedNodeList.push_back(node); - - // Step-4 Process all the neighbours of current node based on in-degree - for (auto& neighbour : this->_adjlist[node]) - { - neighbour->inDegree--; - if (neighbour->inDegree == 0) - { - this->_time++; - neighbour->discoveryTime = this->_time; - nodeQueue.push(neighbour); - } - } - } - - // Step-5 Check if a cycle exists - if (this->_topologicalSortedNodeList.size() != this->_nodeMap.size()) - { - this->_hasCycle = true; - } - } - - vector>> Graph::ShowTopologicalSortResult() - { - if (this->_hasCycle == true) - { - return {}; - } - vector>> result; - for (auto& node : this->_topologicalSortedNodeList) - { - result.push_back(make_pair(node->data, make_pair(node->discoveryTime, node->finishingTime))); - } - return result; - } -} \ No newline at end of file diff --git a/src/0003_Graph/0004_StronglyConnectedComponents.cc b/src/0003_Graph/0004_StronglyConnectedComponents.cc deleted file mode 100644 index 7a99e34..0000000 --- a/src/0003_Graph/0004_StronglyConnectedComponents.cc +++ /dev/null @@ -1,121 +0,0 @@ -#include "0004_StronglyConnectedComponents.h" -#include -#include -#include -using namespace std; - -namespace StronglyConnectedComponents -{ - Node::Node(int value) - { - this->data = value; - this->discoveryTime = INT_MAX; - this->finishingTime = INT_MAX; - this->color = WHITE; - this->parent = nullptr; - } - - Node* Graph::MakeOrFindNode(int value) - { - Node* node = nullptr; - if (this->_nodeMap.find(value) == this->_nodeMap.end()) - { - node = new Node(value); - this->_nodeMap[value] = node; - } - else - { - node = this->_nodeMap[value]; - } - return node; - } - - void Graph::DepthFirstSearchOnGraphG(Node* nodeU) - { - this->_time++; - nodeU->discoveryTime = this->_time; - nodeU->color = GRAY; - for (auto nodeV : this->_adjlistG[nodeU]) - { - if (nodeV->color == WHITE) - { - nodeV->parent = nodeU; - this->DepthFirstSearchOnGraphG(nodeV); - } - } - nodeU->color = BLACK; - this->_time++; - nodeU->finishingTime = this->_time; - this->_nodesFinishingTimeOrder.push_front(nodeU); - } - - void Graph::DepthFirstSearchOnGraphT(Node* nodeU, vector& connectedComponents) - { - nodeU->color = GRAY; - connectedComponents.push_back(nodeU->data); - for (auto nodeV : this->_adjlistT[nodeU]) - { - if (nodeV->color == WHITE) - { - nodeV->parent = nodeU; - this->DepthFirstSearchOnGraphT(nodeV, connectedComponents); - } - } - nodeU->color = BLACK; - } - - void Graph::PushDirectedEdge(int valueU, int valueV) - { - Node* nodeU = this->MakeOrFindNode(valueU); - Node* nodeV = this->MakeOrFindNode(valueV); - - // Creating the actual graph. - this->_adjlistG[nodeU].push_back(nodeV); - - // Creating the transpose of the actual graph. - this->_adjlistT[nodeV].push_back(nodeU); - } - - void Graph::PushSingleNode(int valueU) - { - this->MakeOrFindNode(valueU); - } - - void Graph::DFSOnGraphG() - { - this->_time = 0; - for (auto& iterator : this->_nodeMap) - { - if (iterator.second->color == WHITE) - { - this->DepthFirstSearchOnGraphG(iterator.second); - } - } - } - - void Graph::DFSOnGraphT() - { - for (auto& iterator : this->_nodeMap) - { - iterator.second->color = WHITE; - iterator.second->parent = nullptr; - } - - for (auto& iterator : this->_nodesFinishingTimeOrder) - { - if (iterator->color == WHITE) - { - vector connectedComponents; - this->DepthFirstSearchOnGraphT(iterator, connectedComponents); - this->_allConnectedComponents.push_back(connectedComponents); - } - } - } - - vector> Graph::FindAllStronglyConnectedComponents() - { - this->DFSOnGraphG(); - this->DFSOnGraphT(); - return this->_allConnectedComponents; - } -} \ No newline at end of file diff --git a/src/0003_Graph/0005_HamiltonianPathAndCycle.cc b/src/0003_Graph/0005_HamiltonianPathAndCycle.cc deleted file mode 100644 index bfa99b5..0000000 --- a/src/0003_Graph/0005_HamiltonianPathAndCycle.cc +++ /dev/null @@ -1,114 +0,0 @@ -#include "0005_HamiltonianPathAndCycle.h" - -using namespace std; -namespace HamiltonianPathAndCycle -{ - Node::Node(int value) - { - this->data = value; - this->isVisited = false; - } - - // Graph Private Member Methods - Node* Graph::MakeOrFindNode(int value) - { - Node* node = nullptr; - if (this->_nodeMap.find(value) == this->_nodeMap.end()) - { - node = new Node(value); - this->_nodeMap[value] = node; - } - else - { - node = this->_nodeMap[value]; - } - return node; - } - - bool Graph::IsSafe(Node* nodeU, Node* nodeV) - { - if (this->_adjlist[nodeU].find(nodeV) == this->_adjlist[nodeU].end()) - { - return false; - } - if (nodeV->isVisited == true) - { - return false; - } - return true; - } - - bool Graph::HamiltonianCycleAndPathUtil(Node* nodeU) - { - if (this->_visitedNodeCount == this->_nodeMap.size()) - { - if (this->_adjlist[nodeU].find(this->_startingNode) != this->_adjlist[nodeU].end()) - { - this->_isHamiltonianCyclePresent = true; - this->_isHamiltonianPathPresent = true; - return true; - } - this->_isHamiltonianPathPresent = true; - return false; - } - for (auto& nodeV : this->_adjlist[nodeU]) - { - if (this->IsSafe(nodeU, nodeV)) - { - this->_hamiltonianPath.push_back(nodeV->data); - nodeV->isVisited = true; - this->_visitedNodeCount++; - if (this->HamiltonianCycleAndPathUtil(nodeV)) - { - return true; - } - this->_visitedNodeCount--; - nodeV->isVisited = false; - this->_hamiltonianPath.pop_back(); - } - } - return false; - } - - // Graph Public Member Methods - void Graph::PushUndirectedEdge(int valueU, int valueV) - { - Node* nodeU = this->MakeOrFindNode(valueU); - Node* nodeV = this->MakeOrFindNode(valueV); - - this->_adjlist[nodeU].insert(nodeV); - this->_adjlist[nodeV].insert(nodeU); - } - - void Graph::PushSingleNode(int valueU) - { - this->MakeOrFindNode(valueU); - } - - void Graph::FindHamiltonianCycleAndPath() - { - this->_isHamiltonianCyclePresent = false; - this->_isHamiltonianPathPresent = false; - this->_hamiltonianPath = {}; - this->_startingNode = this->_nodeMap[0]; - this->_hamiltonianPath.push_back(this->_startingNode->data); - this->_startingNode->isVisited = true; - this->_visitedNodeCount = 1; - this->HamiltonianCycleAndPathUtil(this->_startingNode); - } - - bool Graph::IsHamiltonianCyclePresent() - { - return this->_isHamiltonianCyclePresent; - } - - bool Graph::IsHamiltonianPathPresent() - { - return this->_isHamiltonianPathPresent; - } - - vector Graph::GetHamiltonianPath() - { - return this->_hamiltonianPath; - } -} \ No newline at end of file diff --git a/src/0003_Graph/0006_EulerianPathAndCircuit.cc b/src/0003_Graph/0006_EulerianPathAndCircuit.cc deleted file mode 100644 index ee132ca..0000000 --- a/src/0003_Graph/0006_EulerianPathAndCircuit.cc +++ /dev/null @@ -1,212 +0,0 @@ -#include "0006_EulerianPathAndCircuit.h" -#include -#include -using namespace std; - -namespace EulerianPathAndCircuit -{ - Node::Node(int value) - { - this->data = value; - this->degree = 0; - this->inDegree = 0; - this->outDegree = 0; - this->visited = false; - } - - // Graph Private Member Methods - Node* Graph::MakeOrFindNode(int value) - { - Node* node = nullptr; - if (this->_nodeMap.find(value) == this->_nodeMap.end()) - { - node = new Node(value); - this->_nodeMap[value] = node; - } - else - { - node = this->_nodeMap[value]; - } - return node; - } - - void Graph::DepthFirstSearch(Node* nodeU) - { - nodeU->visited = true; - for (auto& nodeV : this->_adjlist[nodeU]) - { - if (nodeV->visited == false) - { - this->DepthFirstSearch(nodeV); - } - } - } - - bool Graph::IsConnected() - { - // Step-1 : Make the visited property of all nodes as false. It is already done in constructor. - - // Step-2 : Find a node which do not have 0 degree. - Node* node = nullptr; - for (auto& iterator : this->_nodeMap) - { - if (iterator.second->degree != 0) - { - node = iterator.second; - break; - } - } - - // Step-3 : If node is null, it means G.E is null, so G is connected, else call DFS to traverse the graph G. - if (node == nullptr) - { - return true; - } - - this->DepthFirstSearch(node); - - // Step-4 : Checking if all the non-zero degree vertices have been visited or not. - for (auto& iterator : this->_nodeMap) - { - if (iterator.second->visited == false && iterator.second->degree != 0) - { - return false; - } - } - return true; - } - - void Graph::EulerianPathHierholzerAlgorithm(Node* startingNode) - { - stack currentPath; - currentPath.push(startingNode); - while (!currentPath.empty()) - { - Node* currentNode = currentPath.top(); - if (!this->_adjlist[currentNode].empty()) - { - Node* nextNode = this->_adjlist[currentNode].front(); - this->_adjlist[currentNode].pop_front(); - this->_adjlist[nextNode].remove(currentNode); - currentPath.push(nextNode); - } - else - { - currentPath.pop(); - this->_eulerianPath.push_back(currentNode->data); - } - } - } - - // Graph Public Member Methods - void Graph::PushUndirectedEdge(int valueU, int valueV) - { - Node* nodeU = this->MakeOrFindNode(valueU); - Node* nodeV = this->MakeOrFindNode(valueV); - - this->_adjlist[nodeU].push_back(nodeV); - nodeU->degree++; - this->_adjlist[nodeV].push_back(nodeU); - nodeV->degree++; - } - - void Graph::PushDirectedEdge(int valueU, int valueV) - { - Node* nodeU = this->MakeOrFindNode(valueU); - Node* nodeV = this->MakeOrFindNode(valueV); - - this->_adjlist[nodeU].push_back(nodeV); - nodeU->outDegree++; - nodeV->inDegree++; - } - - void Graph::PushSingleNode(int valueU) - { - this->MakeOrFindNode(valueU); - } - - void Graph::FindEulerianPathAndCircuit() - { - // If the graph is not connected then graph G is Not-Eulerian. - if (this->IsConnected() == false) - { - this->_isEulerianPathPresent = false; - this->_isEulerianCircuitPresent = false; - return; - } - - int oddDegreeVertexCount = 0; - for (auto& iterator : this->_nodeMap) - { - if (iterator.second->degree & 1) - { - oddDegreeVertexCount++; - } - } - - // Check-1 : When no vertex with odd degree is present, then graph G is Eulerian. - if (oddDegreeVertexCount == 0) - { - this->_isEulerianPathPresent = true; - this->_isEulerianCircuitPresent = true; - return; - } - - // Check-2 : When 2 vertices have odd degree, then graph G is Semi-Eulerian. - if (oddDegreeVertexCount == 2) - { - this->_isEulerianPathPresent = true; - this->_isEulerianCircuitPresent = false; - return; - } - - // Check-3 : When more than 2 vertices have odd degree, then graph G is Not Eulerian. - if (oddDegreeVertexCount > 2) - { - this->_isEulerianPathPresent = false; - this->_isEulerianCircuitPresent = false; - return; - } - } - - bool Graph::IsEulerianPathPresent() - { - return this->_isEulerianPathPresent; - } - - bool Graph::IsEulerianCircuitPresent() - { - return this->_isEulerianCircuitPresent; - } - - vector Graph::UndirectedGraphGetEulerianPath() - { - // Case-3 : When more than 2 vertices have odd degree, then the graph G is not Eulerian. - // No Eulerian Path is posible. - if (this->_isEulerianPathPresent == false) - { - return {}; - } - - // Now 2 cases remains. - // Case-2 : When 2 vertices have odd degree. Choose any one of them. - Node* node = nullptr; - for (auto& iterator : this->_nodeMap) - { - if (iterator.second->degree & 1) - { - node = iterator.second; - break; - } - } - - // Case-1 : When no vertex with odd degree is present. Choose any vertex as starting point. - if (node == nullptr) - { - node = this->_nodeMap[0]; - } - this->EulerianPathHierholzerAlgorithm(node); - reverse(this->_eulerianPath.begin(), this->_eulerianPath.end()); - return this->_eulerianPath; - } -} \ No newline at end of file diff --git a/src/0003_Graph/0007_MinimumSpanningTreeKruskalAlgorithm.cc b/src/0003_Graph/0007_MinimumSpanningTreeKruskalAlgorithm.cc deleted file mode 100644 index 20bea2b..0000000 --- a/src/0003_Graph/0007_MinimumSpanningTreeKruskalAlgorithm.cc +++ /dev/null @@ -1,108 +0,0 @@ -#include "0007_MinimumSpanningTreeKruskalAlgorithm.h" -#include -#include -using namespace std; - -namespace MinimumSpanningTreeKruskalAlgorithm -{ - Node::Node(int data) - { - this->data = data; - this->parent = nullptr; - this->rank = INT_MAX; - } - - Edge::Edge(Node* nodeU, Node* nodeV, int weight) - { - this->nodeU = nodeU; - this->nodeV = nodeV; - this->weight = weight; - } - - // Graph Private Member Methods - Node* Graph::MakeOrFindNode(int data) - { - Node* node = nullptr; - if (this->_nodeMap.find(data) == this->_nodeMap.end()) - { - node = new Node(data); - this->_nodeMap[data] = node; - } - else - { - node = this->_nodeMap[data]; - } - return node; - } - - void Graph::MakeSet(Node* node) - { - node->parent = node; - node->rank = 0; - } - - void Graph::Union(Node* nodeU, Node* nodeV) - { - this->Link(this->FindSet(nodeU), this->FindSet(nodeV)); - } - - void Graph::Link(Node* nodeU, Node* nodeV) - { - if (nodeV->rank > nodeU->rank) - { - nodeU->parent = nodeV; - } - else - { - nodeV->parent = nodeU; - if (nodeU->rank == nodeV->rank) - { - nodeU->rank += 1; - } - } - } - - Node* Graph::FindSet(Node* node) - { - if (node != node->parent) - { - node->parent = this->FindSet(node->parent); - } - return node->parent; - } - - // Graph Public Member Methods - void Graph::PushUndirectedEdge(int dataU, int dataV, int weight) - { - Node* nodeU = this->MakeOrFindNode(dataU); - Node* nodeV = this->MakeOrFindNode(dataV); - - this->_adjlist[nodeU].push_back(nodeV); - this->_adjlist[nodeV].push_back(nodeU); - this->_edgeList.push_back(new Edge(nodeU, nodeV, weight)); - } - - void Graph::FindMinimumSpanningTreeKruskalAlgorithm() - { - for (auto& iterator : this->_nodeMap) - { - this->MakeSet(iterator.second); - } - - sort(this->_edgeList.begin(), this->_edgeList.end(), [](Edge* edgeX, Edge* edgeY) { return edgeX->weight < edgeY->weight; }); - - for (auto& edge : this->_edgeList) - { - if (this->FindSet(edge->nodeU) != this->FindSet(edge->nodeV)) - { - this->Union(edge->nodeU, edge->nodeV); - this->_minimumSpanningTree.push_back({ {edge->nodeU->data, edge->nodeV->data}, edge->weight }); - } - } - } - - vector, int>> Graph::GetMinimumSpanningTree() - { - return this->_minimumSpanningTree; - } -} \ No newline at end of file diff --git a/src/0003_Graph/0008_MinimumSpanningTreePrimAlgorithm.cc b/src/0003_Graph/0008_MinimumSpanningTreePrimAlgorithm.cc deleted file mode 100644 index 1b36027..0000000 --- a/src/0003_Graph/0008_MinimumSpanningTreePrimAlgorithm.cc +++ /dev/null @@ -1,85 +0,0 @@ -#include "0008_MinimumSpanningTreePrimAlgorithm.h" -#include -using namespace std; - - -namespace MinimumSpanningTreePrimAlgorithm -{ - Node::Node(int data) - { - this->data = data; - this->parent = nullptr; - this->key = INT_MAX; - this->isInOperationalSet = false; - } - - // Graph Private Member Methods - Node* Graph::MakeOrFindNode(int data) - { - Node* node = nullptr; - if (this->_nodeMap.find(data) == this->_nodeMap.end()) - { - node = new Node(data); - this->_nodeMap[data] = node; - } - else - { - node = this->_nodeMap[data]; - } - return node; - } - - // Graph Public Member Methods - void Graph::PushUndirectedEdge(int dataU, int dataV, int weight) - { - Node* nodeU = this->MakeOrFindNode(dataU); - Node* nodeV = this->MakeOrFindNode(dataV); - - this->_adjlist[nodeU].push_back({nodeV, weight}); - this->_adjlist[nodeV].push_back({nodeU, weight}); - } - - void Graph::FindMinimumSpanningTreePrimAlgorithm() - { - Node* root = this->_nodeMap.begin()->second; - - root->key = 0; - for (auto& iterator : this->_nodeMap) - { - iterator.second->isInOperationalSet = true; - this->_operationalSet.insert(iterator.second); - } - - while (!this->_operationalSet.empty()) - { - Node* nodeU = *(this->_operationalSet.begin()); - this->_operationalSet.erase(nodeU); - nodeU->isInOperationalSet = false; - - for (auto& iterator : this->_adjlist[nodeU]) - { - Node* nodeV = iterator.first; - int weight = iterator.second; - - if (nodeV->isInOperationalSet && weight < nodeV->key) - { - this->_operationalSet.erase(nodeV); - nodeV->key = weight; - nodeV->parent = nodeU; - this->_operationalSet.insert(nodeV); - - } - } - - if (nodeU->parent != nullptr) - { - this->_minimumSpanningTree.push_back({ {nodeU->parent->data, nodeU->data}, nodeU->key }); - } - } - } - - vector, int>> Graph::GetMinimumSpanningTree() - { - return this->_minimumSpanningTree; - } -} \ No newline at end of file diff --git a/src/0003_Graph/0009_SingleSourceShortestPathBellmanFord.cc b/src/0003_Graph/0009_SingleSourceShortestPathBellmanFord.cc deleted file mode 100644 index b059b74..0000000 --- a/src/0003_Graph/0009_SingleSourceShortestPathBellmanFord.cc +++ /dev/null @@ -1,108 +0,0 @@ -#include "0009_SingleSourceShortestPathBellmanFord.h" -#include -#include -using namespace std; - -namespace SingleSourceShortestPathBellmanFord -{ - Node::Node(int data) - { - this->data = data; - this->distance = INT_MAX; - this->parent = nullptr; - } - - Edge::Edge(Node* nodeU, Node* nodeV, int weight) - { - this->nodeU = nodeU; - this->nodeV = nodeV; - this->weight = weight; - } - - // Graph Private Member Methods - Node* Graph::MakeOrFindNode(int data) - { - Node* node = nullptr; - if (this->_nodeMap.find(data) == this->_nodeMap.end()) - { - node = new Node(data); - this->_nodeMap[data] = node; - } - else - { - node = this->_nodeMap[data]; - } - return node; - } - - void Graph :: InitializeSingleSource(Node* sourceNode) - { - for (auto& iterator : this->_nodeMap) - { - iterator.second->distance = INT_MAX; - iterator.second->parent = nullptr; - } - sourceNode->distance = 0; - } - - void Graph::Relax(Edge* edge) - { - if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) - { - edge->nodeV->distance = edge->nodeU->distance + edge->weight; - edge->nodeV->parent = edge->nodeU; - } - } - - void Graph::GetShortestPath(Node* node, vector& path) - { - path.push_back(node->data); - if (node->parent != nullptr) - { - this->GetShortestPath(node->parent, path); - } - } - - // Graph Public Member Methods - void Graph::PushDirectedEdge(int dataU, int dataV, int weight) - { - Node* nodeU = this->MakeOrFindNode(dataU); - Node* nodeV = this->MakeOrFindNode(dataV); - - this->_adjlist[nodeU].push_back(nodeV); - this->_edgeList.push_back(new Edge(nodeU, nodeV, weight)); - } - - bool Graph::FindSingleSourceShortestPathBellmanFord(int data) - { - Node* source = this->_nodeMap[data]; - - this->InitializeSingleSource(source); - - for (int i = 0; i < this->_nodeMap.size() - 1; i++) - { - for (auto& edge : this->_edgeList) - { - this->Relax(edge); - } - } - - for (auto& edge : this->_edgeList) - { - if (edge->nodeV->distance > (edge->nodeU->distance + edge->weight)) - { - return false; - } - } - return true; - } - - vector Graph::GetShortestPathBellmanFord(int data) - { - vector path = {}; - Node* node = this->_nodeMap[data]; - this->GetShortestPath(node, path); - reverse(path.begin(), path.end()); - return path; - } -} \ No newline at end of file diff --git a/src/0003_Graph/0010_DirectedAcyclicGraphShortestPath.cc b/src/0003_Graph/0010_DirectedAcyclicGraphShortestPath.cc deleted file mode 100644 index 8f4cd81..0000000 --- a/src/0003_Graph/0010_DirectedAcyclicGraphShortestPath.cc +++ /dev/null @@ -1,124 +0,0 @@ -#include "0010_DirectedAcyclicGraphShortestPath.h" -#include -#include -using namespace std; - -namespace DirectedAcyclicGraphShortestPath -{ - Node::Node(int data) - { - this->data = data; - this->color = WHITE; - this->distance = INT_MAX; - this->parent = nullptr; - } - - Edge::Edge(Node* nodeU, Node* nodeV, int weight) - { - this->nodeU = nodeU; - this->nodeV = nodeV; - this->weight = weight; - } - - // Graph Private Member Methods - Node* Graph::MakeOrFindNode(int data) - { - Node* node = nullptr; - if (this->_nodeMap.find(data) == this->_nodeMap.end()) - { - node = new Node(data); - this->_nodeMap[data] = node; - } - else - { - node = this->_nodeMap[data]; - } - return node; - } - - void Graph::DepthFirstSearch(Node* nodeU) - { - nodeU->color = GRAY; - for (auto& nodeV : this->_adjlist[nodeU]) - { - if (nodeV->color == WHITE) - { - this->DepthFirstSearch(nodeV); - } - } - nodeU->color = BLACK; - this->_topologicalSortedNodeList.push_front(nodeU); - } - - void Graph::TopologicalSort() - { - for (auto& iterator : this->_nodeMap) - { - if (iterator.second->color == WHITE) - { - this->DepthFirstSearch(iterator.second); - } - } - } - - void Graph::InitializeSingleSource(Node* sourceNode) - { - for (auto& iterator : this->_nodeMap) - { - iterator.second->distance = INT_MAX; - iterator.second->parent = nullptr; - } - sourceNode->distance = 0; - } - - void Graph::Relax(Edge* edge) - { - if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) - { - edge->nodeV->distance = edge->nodeU->distance + edge->weight; - edge->nodeV->parent = edge->nodeU; - } - } - - void Graph::GetShortestPath(Node* node, vector& path) - { - path.push_back(node->data); - if (node->parent != nullptr) - { - this->GetShortestPath(node->parent, path); - } - } - - // Graph Public Member Methods - void Graph::PushDirectedEdge(int dataU, int dataV, int weight) - { - Node* nodeU = this->MakeOrFindNode(dataU); - Node* nodeV = this->MakeOrFindNode(dataV); - - this->_adjlist[nodeU].push_back(nodeV); - this->_edgeMap[nodeU].push_back(new Edge(nodeU, nodeV, weight)); - } - - void Graph::FindDAGShortestPath(int data) - { - this->TopologicalSort(); - Node* source = this->_nodeMap[data]; - this->InitializeSingleSource(source); - for (auto& node : this->_topologicalSortedNodeList) - { - for (auto& edge : this->_edgeMap[node]) - { - this->Relax(edge); - } - } - } - - vector Graph::GetDAGShortestPath(int data) - { - vector path = {}; - Node* node = this->_nodeMap[data]; - this->GetShortestPath(node, path); - reverse(path.begin(), path.end()); - return path; - } -} \ No newline at end of file diff --git a/src/0003_Graph/0011_SingleSourceShortestPathDijkstra.cc b/src/0003_Graph/0011_SingleSourceShortestPathDijkstra.cc deleted file mode 100644 index e796e37..0000000 --- a/src/0003_Graph/0011_SingleSourceShortestPathDijkstra.cc +++ /dev/null @@ -1,113 +0,0 @@ -#include "0011_SingleSourceShortestPathDijkstra.h" -#include -#include -using namespace std; - -namespace SingleSourceShortestPathDijkstra -{ - Node::Node(int data) - { - this->data = data; - this->distance = INT_MAX; - this->parent = nullptr; - } - - Edge::Edge(Node* nodeU, Node* nodeV, int weight) - { - this->nodeU = nodeU; - this->nodeV = nodeV; - this->weight = weight; - } - - // Graph Private Member Methods - Node* Graph::MakeOrFindNode(int data) - { - Node* node = nullptr; - if (this->_nodeMap.find(data) == this->_nodeMap.end()) - { - node = new Node(data); - this->_nodeMap[data] = node; - } - else - { - node = this->_nodeMap[data]; - } - return node; - } - - void Graph::InitializeSingleSource(Node* sourceNode) - { - for (auto& iterator : this->_nodeMap) - { - iterator.second->distance = INT_MAX; - iterator.second->parent = nullptr; - } - sourceNode->distance = 0; - } - - void Graph::Relax(Edge* edge) - { - if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) - { - this->_operationalSet.erase(edge->nodeV); - edge->nodeV->distance = edge->nodeU->distance + edge->weight; - edge->nodeV->parent = edge->nodeU; - this->_operationalSet.insert(edge->nodeV); - } - } - - void Graph::Dijkstra(Node* source) - { - this->InitializeSingleSource(source); - - for (auto& node : this->_nodeMap) - { - this->_operationalSet.insert(node.second); - } - - while (!this->_operationalSet.empty()) - { - Node* nodeU = *(this->_operationalSet.begin()); - this->_operationalSet.erase(nodeU); - - for (auto& edge : this->_edgeMap[nodeU]) - { - this->Relax(edge); - } - } - } - - void Graph::GetShortestPath(Node* node, vector& path) - { - path.push_back(node->data); - if (node->parent != nullptr) - { - this->GetShortestPath(node->parent, path); - } - } - - // Graph Public Member Methods - void Graph::PushDirectedEdge(int dataU, int dataV, int weight) - { - Node* nodeU = this->MakeOrFindNode(dataU); - Node* nodeV = this->MakeOrFindNode(dataV); - - this->_adjlist[nodeU].push_back(nodeV); - this->_edgeMap[nodeU].push_back(new Edge(nodeU, nodeV, weight)); - } - - void Graph::FindShortestPathDijkstra(int data) - { - Node* source = this->_nodeMap[data]; - this->Dijkstra(source); - } - - vector Graph::GetDijkstraShortestPath(int data) - { - vector path = {}; - Node* node = this->_nodeMap[data]; - this->GetShortestPath(node, path); - reverse(path.begin(), path.end()); - return path; - } -} \ No newline at end of file diff --git a/src/0003_Graph/0012_DifferenceConstraintsShortestPaths.cc b/src/0003_Graph/0012_DifferenceConstraintsShortestPaths.cc deleted file mode 100644 index 8764ba6..0000000 --- a/src/0003_Graph/0012_DifferenceConstraintsShortestPaths.cc +++ /dev/null @@ -1,133 +0,0 @@ -#include "0012_DifferenceConstraintsShortestPaths.h" -#include -using namespace std; - -namespace DifferenceConstraintsShortestPaths -{ - Node::Node(string data) - { - this->data = data; - this->distance = INT_MAX; - } - - Edge::Edge(Node* nodeU, Node* nodeV, int weight) - { - this->nodeU = nodeU; - this->nodeV = nodeV; - this->weight = weight; - } - - // Graph Private Member Methods - Node* Graph::MakeOrFindNode(string data) - { - Node* node = nullptr; - if (this->_nodeMap.find(data) == this->_nodeMap.end()) - { - node = new Node(data); - this->_nodeMap[data] = node; - } - else - { - node = this->_nodeMap[data]; - } - return node; - } - - void Graph::PushDirectedEdge(string dataU, string dataV, int weight) - { - Node* nodeU = this->MakeOrFindNode(dataU); - Node* nodeV = this->MakeOrFindNode(dataV); - - this->_adjlist[nodeU].push_back(nodeV); - this->_edgeList.push_back(new Edge(nodeU, nodeV, weight)); - } - - void Graph::InitializeSingleSource(Node* sourceNode) - { - for (auto& iterator : this->_nodeMap) - { - iterator.second->distance = INT_MAX; - } - sourceNode->distance = 0; - } - - void Graph::Relax(Edge* edge) - { - if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) - { - edge->nodeV->distance = edge->nodeU->distance + edge->weight; - } - } - - // Graph Public Member Methods - void Graph::PushAllDirectedEdges(vector> vectorA, vector vectorX, vector vectorB) - { - // Creating the Actual Graph - string valueU = ""; - string valueV = ""; - int weight = 0; - for (int i = 0; i < vectorA.size(); i++) - { - for (int j = 0; j < vectorX.size(); j++) - { - if (vectorA[i][j] == 1) - { - valueV= vectorX[j]; - } - if (vectorA[i][j] == -1) - { - valueU = vectorX[j]; - } - } - weight = vectorB[i]; - this->PushDirectedEdge(valueU, valueV, weight); - } - - // Creating all the edges from the additional vertex - valueU = ""; - valueV = ""; - weight = 0; - for (int i = 0; i < vectorX.size(); i++) - { - valueV = vectorX[i]; - this->PushDirectedEdge(valueU, valueV, weight); - } - } - - bool Graph::FindDifferenceConstraintsSolutionBellmanFord() - { - Node* source = this->_nodeMap[""]; - - this->InitializeSingleSource(source); - - for (int i = 0; i < this->_nodeMap.size(); i++) - { - for (auto& edge : this->_edgeList) - { - this->Relax(edge); - } - } - - for (auto& edge : this->_edgeList) - { - if (edge->nodeV->distance > (edge->nodeU->distance + edge->weight)) - { - return false; - } - } - return true; - } - - vector> Graph::GetDifferenceConstrtaintsSolution() - { - vector> result; - for (auto& node : this->_nodeMap) - { - if (node.second->data != "") - { - result.push_back({ node.second->data, node.second->distance }); - } - } - return result; - } -} \ No newline at end of file diff --git a/src/0003_Graph/0013_AllPairsShortestPathsFloydWarshall.cc b/src/0003_Graph/0013_AllPairsShortestPathsFloydWarshall.cc deleted file mode 100644 index ffd51d9..0000000 --- a/src/0003_Graph/0013_AllPairsShortestPathsFloydWarshall.cc +++ /dev/null @@ -1,104 +0,0 @@ -#include "0013_AllPairsShortestPathsFloydWarshall.h" -#include -using namespace std; - -namespace AllPairsShortestPathsFloydWarshall -{ - // Graph Private Member Methods - void Graph::InitializeDistanceAndPredecessors() - { - this->_shortestPathMatrixFloydWarshall = this->_adjMatrix; - - for (int i = 0; i < this->_noOfVertices; i++) - { - for (int j = 0; j < this->_noOfVertices; j++) - { - if ((i == j) || this->_adjMatrix[i][j] == INT_MAX) - { - this->_predecessorMatrix[i][j] = -1; - } - else - { - this->_predecessorMatrix[i][j] = i + 1; - } - } - } - } - - void Graph::GetShortestPath(int source, int destination, vector& path) - { - if (this->_predecessorMatrix[source - 1][destination - 1] != source) - { - int predecessor = this->_predecessorMatrix[source - 1][destination - 1]; - this->GetShortestPath(source, predecessor, path); - path.push_back(predecessor); - } - } - - // Graph Public Member Methods - void Graph::CreateGraph(int noOfVertices) - { - this->_noOfVertices = noOfVertices; - this->_adjMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, INT_MAX)); - this->_shortestPathMatrixFloydWarshall = vector>(this->_noOfVertices, vector(this->_noOfVertices, INT_MAX)); - this->_predecessorMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, INT_MAX)); - - for (int i = 0; i < this->_noOfVertices; i++) - { - for (int j = 0; j < this->_noOfVertices; j++) - { - if (i == j) - { - this->_adjMatrix[i][j] = 0; - } - } - } - } - - void Graph::PushDirectedEdge(int valueU, int valueV, int weight) - { - this->_adjMatrix[valueU - 1][valueV - 1] = weight; - } - - void Graph::FindAllPairsShortestPathsFloydWarshallSolution() - { - this->InitializeDistanceAndPredecessors(); - - for (int k = 0; k < this->_noOfVertices; k++) - { - for (int i = 0; i < this->_noOfVertices; i++) - { - for (int j = 0; j < this->_noOfVertices; j++) - { - if ((this->_shortestPathMatrixFloydWarshall[i][j] > (this->_shortestPathMatrixFloydWarshall[i][k] + this->_shortestPathMatrixFloydWarshall[k][j])) - && - (this->_shortestPathMatrixFloydWarshall[i][k] != INT_MAX && this->_shortestPathMatrixFloydWarshall[k][j] != INT_MAX)) - { - this->_shortestPathMatrixFloydWarshall[i][j] = this->_shortestPathMatrixFloydWarshall[i][k] + this->_shortestPathMatrixFloydWarshall[k][j]; - this->_predecessorMatrix[i][j] = this->_predecessorMatrix[k][j]; - } - } - } - } - } - - vector> Graph::GetFloydWarshallShortestPath() - { - vector> result; - for (int i = 0; i < this->_noOfVertices; i++) - { - for (int j = 0; j < this->_noOfVertices; j++) - { - if (i != j) - { - vector path = {}; - path.push_back(i + 1); - this->GetShortestPath(i + 1, j + 1, path); - path.push_back(j + 1); - result.push_back(path); - } - } - } - return result; - } -} \ No newline at end of file diff --git a/src/0003_Graph/0014_AllPairsShortestPathsJohnson.cc b/src/0003_Graph/0014_AllPairsShortestPathsJohnson.cc deleted file mode 100644 index e9f9ab2..0000000 --- a/src/0003_Graph/0014_AllPairsShortestPathsJohnson.cc +++ /dev/null @@ -1,217 +0,0 @@ -#include "0014_AllPairsShortestPathsJohnson.h" -#include -using namespace std; - -namespace AllPairsShortestPathsJohnson -{ - Node::Node(int data) - { - this->data = data; - this->distance = INT_MAX; - this->parent = nullptr; - this->potentialWeight = 0; - } - - Edge::Edge(Node* nodeU, Node* nodeV, int weight) - { - this->nodeU = nodeU; - this->nodeV = nodeV; - this->weight = weight; - } - - // Graph Private Member Methods - Node* Graph::MakeOrFindNode(int data) - { - Node* node = nullptr; - if (this->_nodeMap.find(data) == this->_nodeMap.end()) - { - node = new Node(data); - this->_nodeMap[data] = node; - } - else - { - node = this->_nodeMap[data]; - } - return node; - } - - void Graph::PushAugmentedDirectedEdges(Node* sourceNode, Node* nodeV, int weight) - { - this->_augmentedAdjlist[sourceNode].push_back(nodeV); - this->_augmentedEdgeList.push_back(new Edge(sourceNode, nodeV, weight)); - } - - void Graph::InitializeSingleSource(Node* sourceNode) - { - for (auto& iterator : this->_nodeMap) - { - iterator.second->distance = INT_MAX; - iterator.second->parent = nullptr; - } - sourceNode->distance = 0; - } - - void Graph::RelaxBellmanFord(Edge* edge) - { - if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) - { - edge->nodeV->distance = edge->nodeU->distance + edge->weight; - edge->nodeV->parent = edge->nodeU; - } - } - - bool Graph::BellmanFord(Node* source) - { - this->InitializeSingleSource(source); - - for (int i = 0; i < this->_nodeMap.size() - 1; i++) - { - for (auto& edge : this->_augmentedEdgeList) - { - this->RelaxBellmanFord(edge); - } - } - - for (auto& edge : this->_augmentedEdgeList) - { - if (edge->nodeV->distance > (edge->nodeU->distance + edge->weight)) - { - return false; - } - } - return true; - } - - void Graph::RelaxDijkstra(Edge* edge) - { - if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) - { - this->_operationalSet.erase(edge->nodeV); - edge->nodeV->distance = edge->nodeU->distance + edge->weight; - edge->nodeV->parent = edge->nodeU; - this->_operationalSet.insert(edge->nodeV); - } - } - - void Graph::Dijkstra(Node* source) - { - this->InitializeSingleSource(source); - - for (auto& node : this->_nodeMap) - { - this->_operationalSet.insert(node.second); - } - - while (!this->_operationalSet.empty()) - { - Node* nodeU = *(this->_operationalSet.begin()); - this->_operationalSet.erase(nodeU); - - for (auto& edge : this->_edgeMap[nodeU]) - { - this->RelaxDijkstra(edge); - } - } - } - - void Graph::GetShortestPath(int source, int destination, vector& path) - { - if (this->_predecessorMatrix[source - 1][destination - 1] != source) - { - int predecessor = this->_predecessorMatrix[source - 1][destination - 1]; - this->GetShortestPath(source, predecessor, path); - path.push_back(predecessor); - } - } - - // Graph Public Member Methods - void Graph::PushDirectedEdge(int dataU, int dataV, int weight) - { - Node* nodeU = this->MakeOrFindNode(dataU); - Node* nodeV = this->MakeOrFindNode(dataV); - - this->_adjlist[nodeU].push_back(nodeV); - Edge* edge = new Edge(nodeU, nodeV, weight); - this->_edgeMap[nodeU].push_back(edge); - this->_edgeList.push_back(edge); - } - - bool Graph::FindAllPairsShortestPathsJohnsonAlgorithm() - { - // Creating the graph G' - this->_augmentedAdjlist = this->_adjlist; - this->_augmentedEdgeList = this->_edgeList; - - // Source Node s - Node* source = new Node(0); - this->_nodeMap[0] = source; - - // Creating all the augmented edges in G'.E = G.E U {(s, v) : v in G.V - for (auto& node : this->_nodeMap) - { - if (node.second != source) - { - this->PushAugmentedDirectedEdges(source, node.second, 0); - } - } - - if (this->BellmanFord(source) == false) - { - return false; - } - else - { - this->_nodeMap.erase(0); - for (auto& node : this->_nodeMap) - { - node.second->potentialWeight = node.second->distance; - } - - for (auto& edge : this->_edgeList) - { - edge->weight = edge->weight + edge->nodeU->potentialWeight - edge->nodeV->potentialWeight; - } - - this->_noOfVertices = (int)this->_nodeMap.size(); - this->_shortestPathMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, -1)); - this->_predecessorMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, -1)); - for (auto& iteratorU : this->_nodeMap) - { - Node* nodeU = iteratorU.second; - this->Dijkstra(nodeU); - for (auto& iteratorV : this->_nodeMap) - { - Node* nodeV = iteratorV.second; - this->_shortestPathMatrix[nodeU->data - 1][nodeV->data - 1] = nodeV->distance + nodeV->potentialWeight - nodeU->potentialWeight; - this->_predecessorMatrix[nodeU->data - 1][nodeV->data - 1] = nodeV->parent != nullptr ? nodeV->parent->data : -1; - } - } - return true; - } - } - - vector> Graph::GetAllPairsShortestPathsDistanceMatrix() - { - return this->_shortestPathMatrix; - } - - vector> Graph::GetAllPairsShortestPathsPathMatrix() - { - vector> result; - for (int i = 0; i < this->_noOfVertices; i++) - { - for (int j = 0; j < this->_noOfVertices; j++) - { - if (i != j) - { - vector path = {}; - path.push_back(i + 1); - this->GetShortestPath(i + 1, j + 1, path); - path.push_back(j + 1); - result.push_back(path); - } - } - } - return result; - } -} \ No newline at end of file diff --git a/src/0003_Graph/0015_MaximumFlowFordFulkerson.cc b/src/0003_Graph/0015_MaximumFlowFordFulkerson.cc deleted file mode 100644 index dd8d48d..0000000 --- a/src/0003_Graph/0015_MaximumFlowFordFulkerson.cc +++ /dev/null @@ -1,139 +0,0 @@ -#include "0015_MaximumFlowFordFulkerson.h" -#include -using namespace std; - -namespace MaximumFlowFordFulkerson -{ - // Graph Private Member Methods - void Graph::ResolveAntiParallelEdges() - { - int countParallelEdges = 0; - for (int i = 0; i < this->_noOfVertices; i++) - { - for (int j = 0; j < this->_noOfVertices; j++) - { - if (this->_adjMatrix[i][j] > 0 && this->_adjMatrix[j][i] > 0) - { - countParallelEdges++; - } - } - } - - // As i->j and j->i both edges has been counted, actual count is count = count / 2 - countParallelEdges /= 2; - - this->_flagParallelEdges = countParallelEdges > 0; - - // If there are no anti-parallel edges, no need to modify the adjMatrix - if (!this->_flagParallelEdges) - { - return; - } - - int newNoOfVertices = this->_noOfVertices + countParallelEdges; - - // Modifying the adjMatrix - for (auto& edge : this->_adjMatrix) - { - edge.resize(newNoOfVertices, 0); - } - int k = this->_noOfVertices; - this->_visited.resize(newNoOfVertices, false); - this->_parent.resize(newNoOfVertices, -1); - this->_adjMatrix.resize(newNoOfVertices, vector(newNoOfVertices, 0)); - - // Removing the anti-parallel edges by adding new nodes - for (int i = 0; i < this->_noOfVertices; i++) - { - for (int j = 0; j < this->_noOfVertices; j++) - { - if (this->_adjMatrix[i][j] > 0 && this->_adjMatrix[j][i] > 0) - { - this->_adjMatrix[i][k] = this->_adjMatrix[i][j]; - this->_adjMatrix[k][j] = this->_adjMatrix[i][j]; - this->_adjMatrix[i][j] = 0; - k++; - } - } - } - - // Updating the total no of vertices after modifying the adjMatrix - this->_noOfVertices = newNoOfVertices; - } - - void Graph::DepthFirstSearchVisit(int nodeU) - { - this->_visited[nodeU] = true; - for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) - { - if (!this->_visited[nodeV] && this->_residualGraph[nodeU][nodeV] > 0) - { - this->_parent[nodeV] = nodeU; - this->DepthFirstSearchVisit(nodeV); - } - } - } - - bool Graph::DepthFirstSearch() - { - // Resetting the visited values - fill(this->_visited.begin(), this->_visited.end(), false); - - // Resetting the parent values - fill(this->_parent.begin(), this->_parent.end(), -1); - - // Starting the DepthFirstSearch from the source vertex - this->DepthFirstSearchVisit(this->_source); - - // Returning the visited value of the sink vertex, initially it was set to false - return this->_visited[this->_sink]; - } - - // Graph Public Member Methods - void Graph::CreateGraph(int noOfVertices) - { - this->_noOfVertices = noOfVertices; - this->_source = 0; - this->_sink = this->_noOfVertices - 1; - this->_maximumFlow = 0; - this->_flagParallelEdges = false; - this->_adjMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, 0)); - this->_parent = vector(this->_noOfVertices, -1); - this->_visited = vector(this->_noOfVertices, false); - } - - void Graph::PushDirectedEdge(int valueU, int valueV, int capacity) - { - this->_adjMatrix[valueU][valueV] = capacity; - } - - int Graph::FindMaximumFlowFordFulkerson() - { - // Resolving all the parallel edges if present - this->ResolveAntiParallelEdges(); - this->_residualGraph = this->_adjMatrix; - - // While there exists a path p from source to sink in the residual network G' - while (this->DepthFirstSearch()) - { - int augmentedPathFlow = INT_MAX; - - // Calculating c'(p) = min{ c'(u,v) : (u,v) is in p } - for (int nodeV = this->_sink; nodeV > this->_source; nodeV = this->_parent[nodeV]) - { - int nodeU = this->_parent[nodeV]; - augmentedPathFlow = min(augmentedPathFlow, this->_residualGraph[nodeU][nodeV]); - } - - for (int nodeV = this->_sink; nodeV > this->_source; nodeV = this->_parent[nodeV]) - { - int nodeU = this->_parent[nodeV]; - this->_residualGraph[nodeU][nodeV] -= augmentedPathFlow; - this->_residualGraph[nodeV][nodeU] += augmentedPathFlow; - } - this->_maximumFlow += augmentedPathFlow; - } - - return this->_maximumFlow; - } -} \ No newline at end of file diff --git a/src/0003_Graph/0016_MaximumFlowEdmondsKarp.cc b/src/0003_Graph/0016_MaximumFlowEdmondsKarp.cc deleted file mode 100644 index 627a2a6..0000000 --- a/src/0003_Graph/0016_MaximumFlowEdmondsKarp.cc +++ /dev/null @@ -1,144 +0,0 @@ -#include "0016_MaximumFlowEdmondsKarp.h" -#include -#include -using namespace std; - -namespace MaximumFlowEdmondsKarp -{ - // Graph Private Member Methods - void Graph::ResolveAntiParallelEdges() - { - int countParallelEdges = 0; - for (int i = 0; i < this->_noOfVertices; i++) - { - for (int j = 0; j < this->_noOfVertices; j++) - { - if (this->_adjMatrix[i][j] > 0 && this->_adjMatrix[j][i] > 0) - { - countParallelEdges++; - } - } - } - - // As i->j and j->i both edges has been counted, actual count is count = count / 2 - countParallelEdges /= 2; - - this->_flagParallelEdges = countParallelEdges > 0; - - // If there are no anti-parallel edges, no need to modify the adjMatrix - if (!this->_flagParallelEdges) - { - return; - } - - int newNoOfVertices = this->_noOfVertices + countParallelEdges; - - // Modifying the adjMatrix - for (auto& edge : this->_adjMatrix) - { - edge.resize(newNoOfVertices, 0); - } - int k = this->_noOfVertices; - this->_visited.resize(newNoOfVertices, false); - this->_parent.resize(newNoOfVertices, -1); - this->_adjMatrix.resize(newNoOfVertices, vector(newNoOfVertices, 0)); - - // Removing the anti-parallel edges by adding new nodes - for (int i = 0; i < this->_noOfVertices; i++) - { - for (int j = 0; j < this->_noOfVertices; j++) - { - if (this->_adjMatrix[i][j] > 0 && this->_adjMatrix[j][i] > 0) - { - this->_adjMatrix[i][k] = this->_adjMatrix[i][j]; - this->_adjMatrix[k][j] = this->_adjMatrix[i][j]; - this->_adjMatrix[i][j] = 0; - k++; - } - } - } - - // Updating the total no of vertices after modifying the adjMatrix - this->_noOfVertices = newNoOfVertices; - } - - bool Graph::BreadthFirstSearch() - { - // Resetting the visited values - fill(this->_visited.begin(), this->_visited.end(), false); - - // Resetting the parent values - fill(this->_parent.begin(), this->_parent.end(), -1); - - queue nodeQueue; - nodeQueue.push(this->_source); - this->_visited[this->_source] = true; - - while (!nodeQueue.empty()) - { - int nodeU = nodeQueue.front(); - nodeQueue.pop(); - - for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) - { - if (!this->_visited[nodeV] && this->_residualGraph[nodeU][nodeV] > 0) - { - this->_parent[nodeV] = nodeU; - this->_visited[nodeV] = true; - nodeQueue.push(nodeV); - } - } - } - - // Returning the visited value of the sink vertex, initially it was set to false - return this->_visited[this->_sink]; - } - - // Graph Public Member Methods - void Graph::CreateGraph(int noOfVertices) - { - this->_noOfVertices = noOfVertices; - this->_source = 0; - this->_sink = this->_noOfVertices - 1; - this->_maximumFlow = 0; - this->_flagParallelEdges = false; - this->_adjMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, 0)); - this->_parent = vector(this->_noOfVertices, -1); - this->_visited = vector(this->_noOfVertices, false); - } - - void Graph::PushDirectedEdge(int valueU, int valueV, int capacity) - { - this->_adjMatrix[valueU][valueV] = capacity; - } - - int Graph::FindMaximumFlowEdmondsKarp() - { - // Resolving all the parallel edges if present - this->ResolveAntiParallelEdges(); - this->_residualGraph = this->_adjMatrix; - - // While there exists a path p from source to sink in the residual network G' - while (this->BreadthFirstSearch()) - { - int augmentedPathFlow = INT_MAX; - - // Calculating c'(p) = min{ c'(u,v) : (u,v) is in p } - for (int nodeV = this->_sink; nodeV > this->_source; nodeV = this->_parent[nodeV]) - { - int nodeU = this->_parent[nodeV]; - augmentedPathFlow = min(augmentedPathFlow, this->_residualGraph[nodeU][nodeV]); - } - - for (int nodeV = this->_sink; nodeV > this->_source; nodeV = this->_parent[nodeV]) - { - int nodeU = this->_parent[nodeV]; - this->_residualGraph[nodeU][nodeV] -= augmentedPathFlow; - this->_residualGraph[nodeV][nodeU] += augmentedPathFlow; - } - this->_maximumFlow += augmentedPathFlow; - } - - return this->_maximumFlow; - } -} \ No newline at end of file diff --git a/src/0003_Graph/0017_MaximumBipartiteMatching.cc b/src/0003_Graph/0017_MaximumBipartiteMatching.cc deleted file mode 100644 index 7c55ce6..0000000 --- a/src/0003_Graph/0017_MaximumBipartiteMatching.cc +++ /dev/null @@ -1,263 +0,0 @@ -#include "0017_MaximumBipartiteMatching.h" -#include -#include -using namespace std; - -namespace MaximumBipartiteMatching -{ - // Graph Private Member Methods - void Graph::ResolveAntiParallelEdges() - { - int countParallelEdges = 0; - for (int i = 0; i < this->_noOfVertices; i++) - { - for (int j = 0; j < this->_noOfVertices; j++) - { - if (this->_adjMatrix[i][j] > 0 && this->_adjMatrix[j][i] > 0) - { - countParallelEdges++; - } - } - } - - // As i->j and j->i both edges has been counted, actual count is count = count / 2 - countParallelEdges /= 2; - - this->_flagParallelEdges = countParallelEdges > 0; - - // If there are no anti-parallel edges, no need to modify the adjMatrix - if (!this->_flagParallelEdges) - { - return; - } - - int newNoOfVertices = this->_noOfVertices + countParallelEdges; - - // Modifying the adjMatrix - for (auto& edge : this->_adjMatrix) - { - edge.resize(newNoOfVertices, 0); - } - int k = this->_noOfVertices; - this->_visited.resize(newNoOfVertices, false); - this->_parent.resize(newNoOfVertices, -1); - this->_adjMatrix.resize(newNoOfVertices, vector(newNoOfVertices, 0)); - - // Removing the anti-parallel edges by adding new nodes - for (int i = 0; i < this->_noOfVertices; i++) - { - for (int j = 0; j < this->_noOfVertices; j++) - { - if (this->_adjMatrix[i][j] > 0 && this->_adjMatrix[j][i] > 0) - { - this->_adjMatrix[i][k] = this->_adjMatrix[i][j]; - this->_adjMatrix[k][j] = this->_adjMatrix[i][j]; - this->_adjMatrix[i][j] = 0; - k++; - } - } - } - - // Updating the total no of vertices after modifying the adjMatrix - this->_noOfVertices = newNoOfVertices; - } - - // This method is used to color the vertices of the graph to determine if the given graph is bipartite or not - void Graph::ColorGraph() - { - // Color of all the vertices are initialised to WHITE - fill(this->_color.begin(), this->_color.end(), WHITE); - - // Queue to hold the vertices - queue nodeQueue; - - for (int node = 0; node < this->_noOfVertices; node++) - { - // Check if the node is already not colored - if (this->_color[node] == WHITE) - { - // The color of the node is set to RED - this->_color[node] = RED; - - // The node is inserted into the queue - nodeQueue.push(node); - - // Using BFS method to color all the vertices - while (!nodeQueue.empty()) - { - int nodeU = nodeQueue.front(); - nodeQueue.pop(); - - // Iterating over G.Adj[nodeU] - for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) - { - // As there are no self loops, continue - if (nodeU == nodeV) - { - continue; - } - // Check if there is an edge u --> v and nodeV is not colored yet - else if (this->_residualGraph[nodeU][nodeV] != 0 && this->_color[nodeV] == WHITE) - { - // Set the color of nodeV opposite of nodeU - this->_color[nodeV] = 1 - this->_color[nodeU]; - // Insert the nodeV into the queue - nodeQueue.push(nodeV); - } - // Check if there is an edge u --> v and nodeV is of same color as nodeU - else if (this->_residualGraph[nodeU][nodeV] != 0 && this->_color[nodeV] == this->_color[nodeU]) - { - // Set the _isBipartite flag to false and return - this->_isBipartite = false; - return; - } - } - } - } - } - - // If the above operation completes without returning yet that indicates the graph is bipartite - // Set the _isBipartite flag to true and return - this->_isBipartite = true; - return; - } - - // This method is used to create the additional edges - // from the source vertex to the RED colored vertices and - // from the BLUE colored vertices to the sink vertex - void Graph::AddAdditionalEdges() - { - // Resizing the residual graph to accomodate space for the new edges - for (auto& edge : this->_residualGraph) - { - edge.resize(this->_noOfVertices, 0); - } - - this->_parent.resize(this->_noOfVertices, -1); - this->_visited.resize(this->_noOfVertices, false); - this->_color.resize(this->_noOfVertices, WHITE); - this->_residualGraph.resize(this->_noOfVertices, vector(this->_noOfVertices, 0)); - - // Creating the additional edges - for (int node = 0; node < this->_source; node++) - { - // From source vertex --> RED colored vertices - if (this->_color[node] == RED) - { - this->_residualGraph[this->_source][node] = 1; - } - - // From BLUE colored vertices --> sink vertex - else if (this->_color[node] == BLUE) - { - this->_residualGraph[node][this->_sink] = 1; - } - } - } - - // Implementation of BreadthFirstSearch for EdmondsKarp algorithm to find the path from source to sink - bool Graph::BreadthFirstSearch() - { - // Resetting the visited values - fill(this->_visited.begin(), this->_visited.end(), false); - - // Resetting the parent values - fill(this->_parent.begin(), this->_parent.end(), -1); - - queue nodeQueue; - nodeQueue.push(this->_source); - this->_visited[this->_source] = true; - - while (!nodeQueue.empty()) - { - int nodeU = nodeQueue.front(); - nodeQueue.pop(); - - for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) - { - if (!this->_visited[nodeV] && this->_residualGraph[nodeU][nodeV] > 0) - { - this->_parent[nodeV] = nodeU; - this->_visited[nodeV] = true; - nodeQueue.push(nodeV); - } - } - } - - // Returning the visited value of the sink vertex, initially it was set to false - return this->_visited[this->_sink]; - } - - // Graph Public Member Methods - void Graph::CreateGraph(int noOfVertices) - { - this->_noOfVertices = noOfVertices; - this->_maximumFlow = 0; - this->_flagParallelEdges = false; - this->_adjMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, 0)); - this->_parent = vector(this->_noOfVertices, -1); - this->_visited = vector(this->_noOfVertices, false); - this->_color = vector(this->_noOfVertices, WHITE); - } - - void Graph::PushDirectedEdge(int valueU, int valueV) - { - this->_adjMatrix[valueU][valueV] = 1; - } - - int Graph::FindMaximumBipartiteMatching() - { - // Resolving all the parallel edges if present - this->ResolveAntiParallelEdges(); - this->_residualGraph = this->_adjMatrix; - - this->ColorGraph(); - - this->_source = this->_noOfVertices; - this->_noOfVertices++; - this->_sink = this->_noOfVertices; - this->_noOfVertices++; - - this->AddAdditionalEdges(); - - // While there exists a path p from source to sink in the residual network G' - while (this->BreadthFirstSearch()) - { - int augmentedPathFlow = 1; - - // No need to find the minimum amount of augmentedPathFlow as like standard EdmondsKarp algorithm - // as here capacity of each edges is 1 - for (int nodeV = this->_sink; nodeV != this->_source; nodeV = this->_parent[nodeV]) - { - int nodeU = this->_parent[nodeV]; - this->_residualGraph[nodeU][nodeV] -= augmentedPathFlow; - this->_residualGraph[nodeV][nodeU] += augmentedPathFlow; - } - this->_maximumFlow += augmentedPathFlow; - } - - return this->_maximumFlow; - } - - // This method is used for finding the matchings - vector> Graph::GetMatchings() - { - for (int nodeU = 0; nodeU < this->_adjMatrix.size(); nodeU++) - { - for (int nodeV = 0; nodeV < this->_adjMatrix.size(); nodeV++) - { - // Check if the nodeU and nodeV are not source or sink - // and there is a flow of 1 unit from nodeU --> nodeV - // which means nodeU --> nodeV is being used for the maximum flow (maximum matching) - if ((nodeU != this->_source || nodeU != this->_sink || nodeV != this->_source || nodeV != this->_sink) - && - (this->_adjMatrix[nodeU][nodeV] - this->_residualGraph[nodeU][nodeV]) == 1) - { - this->_matchings.push_back({ nodeU, nodeV }); - } - } - } - - return this->_matchings; - } -} \ No newline at end of file diff --git a/src/0003_Graph/0018_MaximumFlowGoldbergGenericPushRelabel.cc b/src/0003_Graph/0018_MaximumFlowGoldbergGenericPushRelabel.cc deleted file mode 100644 index 63c1475..0000000 --- a/src/0003_Graph/0018_MaximumFlowGoldbergGenericPushRelabel.cc +++ /dev/null @@ -1,172 +0,0 @@ -#include "0018_MaximumFlowGoldbergGenericPushRelabel.h" -#include -using namespace std; - -namespace MaximumFlowGoldbergGenericPushRelabel -{ - // Graph Private Member Methods - - // Initializes Pre-Flow in the given Flow Network - void Graph::InitializePreflow() - { - // The height of source is set to highest possible height value - this->_height[this->_source] = this->_noOfVertices; - - // Iterating over all the vertices - for (int i = 0; i < this->_noOfVertices; i++) - { - // For the all the edges (source, v) - if (this->_residualGraph[this->_source][i] > 0) - { - // v.excessFlow = capacity(source, v) - this->_excessFlow[i] = this->_residualGraph[this->_source][i]; - - // source.excessFlow = source.excessFlow - capacity(source, v) - this->_excessFlow[this->_source] = this->_excessFlow[this->_source] - this->_residualGraph[this->_source][i]; - - // Adjusting the flow and reverse flow along source->v and v->source respectively - this->_residualGraph[i][this->_source] = this->_residualGraph[this->_source][i]; - this->_residualGraph[this->_source][i] = 0; - } - } - } - - // Checks if there is any vertex which has excess flow - bool Graph::CheckOverFlow() - { - // Iterating over all of the vertices - for (int i = 0; i < this->_noOfVertices; i++) - { - // Checks if the current vertex is not any special vertex like source, sink - // and also if there is excess flow in the current vertex and it is already not present in the queue - if (i!=this->_source && i!=this->_sink && this->_excessFlow[i] > 0 && this->_visited[i] == false) - { - // Insert the current vertex into the queue - this->_nodeQueue.push(i); - - // Mark it as visited, so until it leaves the queue it is not inserted again even if all the excess flow is neutralized - this->_visited[i] = true; - } - } - - // Checks if there is no vertex having excess flow then returns false - if (this->_nodeQueue.empty()) - { - return false; - } - - return true; - } - - // Pushes the flow from nodeU to its neighbour vertices - bool Graph::Push(int nodeU) - { - int nodeV = -1; - int minimumFlow = INT_MAX; - - // Iterating over all the vertices - for (int i = 0; i < this->_noOfVertices; i++) - { - // For G'.Adj[nodeU] select the vertex if edge (nodeU, i) is non-saturated and height[nodeU] == height[i] + 1 - if (this->_residualGraph[nodeU][i] > 0 && this->_height[nodeU] == this->_height[i] + 1) - { - nodeV = i; - break; - } - } - - // Checks if any neighbour vertex found having non-saturated edge - if (nodeV != -1) - { - // Calculate the flow amount to be added along the edge and excess flow subtracted from nodeU - minimumFlow = min(this->_residualGraph[nodeU][nodeV], this->_excessFlow[nodeU]); - - // Adjust the flow and the reverse flow along (nodeU, nodeV) - this->_residualGraph[nodeU][nodeV] = this->_residualGraph[nodeU][nodeV] - minimumFlow; - this->_residualGraph[nodeV][nodeU] = this->_residualGraph[nodeV][nodeU] + minimumFlow; - - // Adjust the excess flows in nodeU and nodeV - this->_excessFlow[nodeU] = this->_excessFlow[nodeU] - minimumFlow; - this->_excessFlow[nodeV] = this->_excessFlow[nodeV] + minimumFlow; - - // Return that the Push operation is successful - return true; - } - - // Return that the Push operation is not successful - return false; - } - - // Relabels height of vertex nodeU when there are outgoing non-saturated edges available - void Graph::Relabel(int nodeU) - { - int minimumHeight = INT_MAX; - - // Iterating over all the vertices - for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) - { - // For G'.Adj[nodeU] select for which nodeV, height[nodeU] <= height[nodeV] - if (this->_residualGraph[nodeU][nodeV] > 0 && this->_height[nodeU] <= this->_height[nodeV]) - { - // Get the minimum height among all these G'.Adj[nodeU] - minimumHeight = min(minimumHeight, this->_height[nodeV]); - } - } - - // Set height[nodeU] - this->_height[nodeU] = minimumHeight + 1; - } - - - // Graph Public Member Methods - void Graph::CreateGraph(int noOfVertices) - { - this->_noOfVertices = noOfVertices; - this->_source = 0; - this->_sink = this->_noOfVertices - 1; - this->_maximumFlow = 0; - this->_adjMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, 0)); - this->_excessFlow = vector(this->_noOfVertices, 0); - this->_height = vector(this->_noOfVertices, 0); - this->_visited = vector(this->_noOfVertices, false); - } - - void Graph::PushDirectedEdge(int valueU, int valueV, int capacity) - { - this->_adjMatrix[valueU][valueV] = capacity; - } - - int Graph::FindMaximumFlowGoldbergGenericPushRelabel() - { - this->_residualGraph = this->_adjMatrix; - - // Initialize Pre-flow - this->InitializePreflow(); - - // Checks if there is some vertices which have excess flow - while (this->CheckOverFlow()) - { - // Get the vertex - int nodeU = this->_nodeQueue.front(); - - // Checks if the Push operation is successful - if (this->Push(nodeU)) - { - // Then remove the vertex from queue and set visited[nodeU] = true - // so that on next CheckOverFlow() method call this vertex can be discovered if it still has some excess flow - this->_nodeQueue.pop(); - this->_visited[nodeU] = false; - } - - // If the Push operation is not successful - else - { - // Then Relabel nodeU without removing it from the queue - this->Relabel(nodeU); - } - } - - // Return the excess flow in the sink vertex which is actually the maximum flow along the given flow network - return this->_excessFlow[this->_sink]; - } -} \ No newline at end of file diff --git a/src/0003_Graph/0019_MaximumFlowRelabelToFront.cc b/src/0003_Graph/0019_MaximumFlowRelabelToFront.cc deleted file mode 100644 index 034f5bf..0000000 --- a/src/0003_Graph/0019_MaximumFlowRelabelToFront.cc +++ /dev/null @@ -1,169 +0,0 @@ -#include "0019_MaximumFlowRelabelToFront.h" -#include -#include -using namespace std; - -namespace MaximumFlowRelabelToFront -{ - // Graph Private Member Methods - - // Initializes Pre-Flow in the given Flow Network - void Graph::InitializePreflow() - { - // The height of source is set to highest possible height value - this->_height[this->_source] = this->_noOfVertices; - - // Iterating over all the vertices - for (int i = 0; i < this->_noOfVertices; i++) - { - // For the all the edges (source, v) - if (this->_residualGraph[this->_source][i] > 0) - { - // v.excessFlow = capacity(source, v) - this->_excessFlow[i] = this->_residualGraph[this->_source][i]; - - // source.excessFlow = source.excessFlow - capacity(source, v) - this->_excessFlow[this->_source] = this->_excessFlow[this->_source] - this->_residualGraph[this->_source][i]; - - // Adjusting the flow and reverse flow along source->v and v->source respectively - this->_residualGraph[i][this->_source] = this->_residualGraph[this->_source][i]; - this->_residualGraph[this->_source][i] = 0; - } - } - } - - // Discharges the excess flow from nodeU - void Graph::Discharge(int nodeU) - { - // Check if excess flow of nodeU is > 0 - while (this->_excessFlow[nodeU] > 0) - { - // Falg to check if any amount of excess flow is pushed to any neighbour vertex - bool hasPushed = false; - - // Iterating over all of the vertices - for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) - { - // For G'.Adj[nodeU] check if edge (nodeU, nodeV) is admissible - if (this->_residualGraph[nodeU][nodeV] > 0 && this->_height[nodeU] == 1 + this->_height[nodeV]) - { - // Push excess flow along the admissible edge (nodeU, nodeV) - this->Push(nodeU, nodeV); - // Set the hasPushed flag to true - hasPushed = true; - // Check if there is no excess flow left in nodeU then no need to check any more admissible edge going from nodeU - if (this->_excessFlow[nodeU] == 0) - { - // Then break from iterating over G'.Adj[nodeU] - break; - } - } - } - - // Check if Push operation is not done yet - if (!hasPushed) - { - // Then it indicates that all the outgoing edges from nodeU are inadmissible - // so perform the Relabel operation on nodeU - this->Relabel(nodeU); - } - } - } - - // Pushes the flow from nodeU to its neighbour vertices - void Graph::Push(int nodeU, int nodeV) - { - // Calculate the flow amount to be added along the edge and excess flow subtracted from nodeU - int minimumFlow = min(this->_residualGraph[nodeU][nodeV], this->_excessFlow[nodeU]); - - // Adjust the flow and the reverse flow along (nodeU, nodeV) - this->_residualGraph[nodeU][nodeV] = this->_residualGraph[nodeU][nodeV] - minimumFlow; - this->_residualGraph[nodeV][nodeU] = this->_residualGraph[nodeV][nodeU] + minimumFlow; - - // Adjust the excess flows in nodeU and nodeV - this->_excessFlow[nodeU] = this->_excessFlow[nodeU] - minimumFlow; - this->_excessFlow[nodeV] = this->_excessFlow[nodeV] + minimumFlow; - } - - // Relabels height of vertex nodeU when there are outgoing non-saturated edges available - void Graph::Relabel(int nodeU) - { - int minimumHeight = INT_MAX; - - // Iterating over all the vertices - for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) - { - // For G'.Adj[nodeU] select for which nodeV, height[nodeU] <= height[nodeV] - if (this->_residualGraph[nodeU][nodeV] > 0 && this->_height[nodeU] <= this->_height[nodeV]) - { - // Get the minimum height among all these G'.Adj[nodeU] - minimumHeight = min(minimumHeight, this->_height[nodeV]); - } - } - - // Set height[nodeU] - this->_height[nodeU] = minimumHeight + 1; - } - - - // Graph Public Member Methods - void Graph::CreateGraph(int noOfVertices) - { - this->_noOfVertices = noOfVertices; - this->_source = 0; - this->_sink = this->_noOfVertices - 1; - this->_maximumFlow = 0; - this->_adjMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, 0)); - this->_excessFlow = vector(this->_noOfVertices, 0); - this->_height = vector(this->_noOfVertices, 0); - this->_visited = vector(this->_noOfVertices, false); - } - - void Graph::PushDirectedEdge(int valueU, int valueV, int capacity) - { - this->_adjMatrix[valueU][valueV] = capacity; - } - - int Graph::FindMaximumFlowRelabelToFront() - { - this->_residualGraph = this->_adjMatrix; - - // Initialize Pre-flow - this->InitializePreflow(); - - // Make the list L = G.V - {source, sink} - for (int i = 0; i < this->_noOfVertices; i++) - { - if (i != this->_source && i != this->_sink) - { - this->_nodeList.push_back(i); - } - } - - // Set current vertex = L.head - list::iterator nodeUiterator = this->_nodeList.begin(); - - // Iterate over all of the elements in the list L - while (nodeUiterator != this->_nodeList.end()) - { - // Get the height of current vertex - int oldHeight = this->_height[*nodeUiterator]; - - // Discharge the excess flow of current vertex - this->Discharge(*nodeUiterator); - - // Check if the height of current vertex increases which means the current vertex got relabeled - if (this->_height[*nodeUiterator] > oldHeight) - { - // Then move current vertex to the front of the list L - this->_nodeList.splice(this->_nodeList.begin(), this->_nodeList, nodeUiterator); - } - - // Go to the next vertex of current vertex in L - nodeUiterator++; - } - - // Return the excess flow in the sink vertex which is actually the maximum flow along the given flow network - return this->_excessFlow[this->_sink]; - } -} \ No newline at end of file diff --git a/src/0003_Graph/CMakeLists.txt b/src/0003_Graph/CMakeLists.txt deleted file mode 100644 index 02f8a77..0000000 --- a/src/0003_Graph/CMakeLists.txt +++ /dev/null @@ -1,30 +0,0 @@ -# Specify the source files -set(0003GRAPH_SOURCES - 0001_BreadthFirstSearch.cc - 0002_DepthFirstSearch.cc - 0003_TopologicalSort.cc - 0004_StronglyConnectedComponents.cc - 0005_HamiltonianPathAndCycle.cc - 0006_EulerianPathAndCircuit.cc - 0007_MinimumSpanningTreeKruskalAlgorithm.cc - 0008_MinimumSpanningTreePrimAlgorithm.cc - 0009_SingleSourceShortestPathBellmanFord.cc - 0010_DirectedAcyclicGraphShortestPath.cc - 0011_SingleSourceShortestPathDijkstra.cc - 0012_DifferenceConstraintsShortestPaths.cc - 0013_AllPairsShortestPathsFloydWarshall.cc - 0014_AllPairsShortestPathsJohnson.cc - 0015_MaximumFlowFordFulkerson.cc - 0016_MaximumFlowEdmondsKarp.cc - 0017_MaximumBipartiteMatching.cc - 0018_MaximumFlowGoldbergGenericPushRelabel.cc - 0019_MaximumFlowRelabelToFront.cc - -) - -# Create a library target -add_library(0003GRAPH ${0003GRAPH_SOURCES}) - -target_include_directories(0003GRAPH PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/headers -) \ No newline at end of file diff --git a/src/0003_graph/headers/0001_BreadthFirstSearch.h b/src/0003_graph/headers/0001_BreadthFirstSearch.h deleted file mode 100644 index ba7aec8..0000000 --- a/src/0003_graph/headers/0001_BreadthFirstSearch.h +++ /dev/null @@ -1,35 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -using namespace std; - -namespace BreadthFirstSearch -{ - enum color { WHITE, GRAY, BLACK }; - class Node - { - public: - int data; - int distance; - int color; - Node* parent; - Node(int value); - }; - - class Graph - { - private: - map> _adjlist; - map _nodeMap; - Node* MakeOrFindNode(int value); - void BreadthFirstSearch(Node* node); - public: - void PushUndirectedEdge(int valueU, int valueV); - void BFS(int value); - vector> ShowBFSResult(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0002_DepthFirstSearch.h b/src/0003_graph/headers/0002_DepthFirstSearch.h deleted file mode 100644 index e376295..0000000 --- a/src/0003_graph/headers/0002_DepthFirstSearch.h +++ /dev/null @@ -1,37 +0,0 @@ -#pragma once - -#include -#include -#include -#include -using namespace std; - -namespace DepthFirstSearch -{ - enum color { WHITE, GRAY, BLACK }; - - class Node - { - public: - int data; - int color; - int discoveredTime; - int finishingTime; - Node* parent; - Node(int value); - }; - - class Graph - { - private: - int _time; - map> _adjlist; - map _nodeMap; - Node* MakeOrFindNode(int value); - void DepthFirstSearch(Node* Node); - public: - void PushDirectedEdge(int valueU, int valueV); - void DFS(); - vector>> ShowDFSResult(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0003_TopologicalSort.h b/src/0003_graph/headers/0003_TopologicalSort.h deleted file mode 100644 index 441d7d1..0000000 --- a/src/0003_graph/headers/0003_TopologicalSort.h +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once - -#include -#include -#include -#include -using namespace std; - -namespace TopologicalSort -{ - enum color { WHITE, GRAY, BLACK }; - - class Node - { - public: - int data; - int color; - int discoveryTime; - int finishingTime; - int inDegree; - Node* parent; - Node(int value); - }; - - class Graph - { - private: - int _time; - bool _hasCycle; - map> _adjlist; - map _nodeMap; - list _topologicalSortedNodeList; - Node* MakeOrFindNode(int value); - void DepthFirstSearch(Node* DFSNode); - public: - void PushDirectedEdge(int valueU, int valueV); - void PushSingleNode(int valueU); - void TopologicalSort(); - void KahnTopologicalSort(); - vector>> ShowTopologicalSortResult(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0004_StronglyConnectedComponents.h b/src/0003_graph/headers/0004_StronglyConnectedComponents.h deleted file mode 100644 index 0e37f60..0000000 --- a/src/0003_graph/headers/0004_StronglyConnectedComponents.h +++ /dev/null @@ -1,43 +0,0 @@ -#pragma once - -#include -#include -#include -#include -using namespace std; - -namespace StronglyConnectedComponents -{ - enum color { WHITE, GRAY, BLACK }; - - class Node - { - public: - int data; - int color; - int discoveryTime; - int finishingTime; - Node* parent; - Node(int value); - }; - - class Graph - { - private: - int _time; - map> _adjlistG; - map> _adjlistT; - map _nodeMap; - list _nodesFinishingTimeOrder; - vector> _allConnectedComponents; - Node* MakeOrFindNode(int value); - void DepthFirstSearchOnGraphG(Node* DFSNode); - void DepthFirstSearchOnGraphT(Node* DFSNode, vector& connectedComponents); - public: - void PushDirectedEdge(int valueU, int valueV); - void PushSingleNode(int valueU); - void DFSOnGraphG(); - void DFSOnGraphT(); - vector> FindAllStronglyConnectedComponents(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0005_HamiltonianPathAndCycle.h b/src/0003_graph/headers/0005_HamiltonianPathAndCycle.h deleted file mode 100644 index 7ccca6a..0000000 --- a/src/0003_graph/headers/0005_HamiltonianPathAndCycle.h +++ /dev/null @@ -1,40 +0,0 @@ -#pragma once - -#include -#include -#include -using namespace std; - -namespace HamiltonianPathAndCycle -{ - class Node - { - public: - int data; - bool isVisited; - Node(int value); - }; - - class Graph - { - private: - bool _isHamiltonianCyclePresent; - bool _isHamiltonianPathPresent; - int _visitedNodeCount; - Node* _startingNode; - map> _adjlist; - map _nodeMap; - vector _hamiltonianPath; - Node* MakeOrFindNode(int value); - bool IsSafe(Node* nodeU, Node* nodeV); - bool HamiltonianCycleAndPathUtil(Node* node); - - public: - void PushUndirectedEdge(int valueU, int valueV); - void PushSingleNode(int valueU); - void FindHamiltonianCycleAndPath(); - bool IsHamiltonianCyclePresent(); - bool IsHamiltonianPathPresent(); - vector GetHamiltonianPath(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0006_EulerianPathAndCircuit.h b/src/0003_graph/headers/0006_EulerianPathAndCircuit.h deleted file mode 100644 index 92d0d34..0000000 --- a/src/0003_graph/headers/0006_EulerianPathAndCircuit.h +++ /dev/null @@ -1,43 +0,0 @@ -#pragma once - -#include -#include -#include -using namespace std; - -namespace EulerianPathAndCircuit -{ - class Node - { - public: - int data; - int degree; - int inDegree; - int outDegree; - bool visited; - Node(int value); - }; - - class Graph - { - private: - bool _isEulerianPathPresent; - bool _isEulerianCircuitPresent; - map> _adjlist; - map _nodeMap; - vector _eulerianPath; - Node* MakeOrFindNode(int value); - void DepthFirstSearch(Node* node); - bool IsConnected(); - void EulerianPathHierholzerAlgorithm(Node* startingNode); - - public: - void PushUndirectedEdge(int valueU, int valueV); - void PushDirectedEdge(int valueU, int valueV); - void PushSingleNode(int valueU); - void FindEulerianPathAndCircuit(); - bool IsEulerianPathPresent(); - bool IsEulerianCircuitPresent(); - vector UndirectedGraphGetEulerianPath(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0007_MinimumSpanningTreeKruskalAlgorithm.h b/src/0003_graph/headers/0007_MinimumSpanningTreeKruskalAlgorithm.h deleted file mode 100644 index 8ca704c..0000000 --- a/src/0003_graph/headers/0007_MinimumSpanningTreeKruskalAlgorithm.h +++ /dev/null @@ -1,46 +0,0 @@ -#pragma once - -#include -#include -#include -using namespace std; - -namespace MinimumSpanningTreeKruskalAlgorithm -{ - class Node - { - public: - int data; - Node* parent; - int rank; - Node(int data); - }; - - class Edge - { - public: - Node* nodeU; - Node* nodeV; - int weight; - Edge(Node* nodeU, Node* nodeV, int weight); - }; - - class Graph - { - private: - map> _adjlist; - map _nodeMap; - vector _edgeList; - vector, int>> _minimumSpanningTree; - Node* MakeOrFindNode(int data); - void MakeSet(Node* node); - void Union(Node* nodeU, Node* nodeV); - void Link(Node* nodeU, Node* nodeV); - Node* FindSet(Node* node); - - public: - void PushUndirectedEdge(int valueU, int valueV, int weight); - void FindMinimumSpanningTreeKruskalAlgorithm(); - vector, int>> GetMinimumSpanningTree(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0008_MinimumSpanningTreePrimAlgorithm.h b/src/0003_graph/headers/0008_MinimumSpanningTreePrimAlgorithm.h deleted file mode 100644 index ffe7c08..0000000 --- a/src/0003_graph/headers/0008_MinimumSpanningTreePrimAlgorithm.h +++ /dev/null @@ -1,42 +0,0 @@ -# pragma once - -#include -#include -#include -using namespace std; - -namespace MinimumSpanningTreePrimAlgorithm -{ - class Node - { - public: - int data; - Node* parent; - int key; - bool isInOperationalSet; - Node(int data); - }; - - class CompareNodeKey - { - public: - bool operator()(const Node* nodeU, const Node* nodeV) const - { - return nodeU->key < nodeV->key; - } - }; - - class Graph - { - private: - map>> _adjlist; - map _nodeMap; - vector, int>> _minimumSpanningTree; - multiset _operationalSet; - Node* MakeOrFindNode(int data); - public: - void PushUndirectedEdge(int valueU, int valueV, int weight); - void FindMinimumSpanningTreePrimAlgorithm(); - vector, int>> GetMinimumSpanningTree(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0009_SingleSourceShortestPathBellmanFord.h b/src/0003_graph/headers/0009_SingleSourceShortestPathBellmanFord.h deleted file mode 100644 index e51ca10..0000000 --- a/src/0003_graph/headers/0009_SingleSourceShortestPathBellmanFord.h +++ /dev/null @@ -1,44 +0,0 @@ -#pragma once - -#include -#include -using namespace std; - -namespace SingleSourceShortestPathBellmanFord -{ - class Node - { - public: - int data; - int distance; - Node* parent; - Node(int data); - }; - - class Edge - { - public: - Node* nodeU; - Node* nodeV; - int weight; - Edge(Node* nodeU, Node* nodeV, int weight); - }; - - class Graph - { - private: - map> _adjlist; - map _nodeMap; - vector _edgeList; - Node* MakeOrFindNode(int data); - void InitializeSingleSource(Node* sourceNode); - void Relax(Edge* edge); - void GetShortestPath(Node* node, vector& path); - - - public: - void PushDirectedEdge(int valueU, int valueV, int weight); - bool FindSingleSourceShortestPathBellmanFord(int data); - vector GetShortestPathBellmanFord(int data); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0010_DirectedAcyclicGraphShortestPath.h b/src/0003_graph/headers/0010_DirectedAcyclicGraphShortestPath.h deleted file mode 100644 index 8826ebc..0000000 --- a/src/0003_graph/headers/0010_DirectedAcyclicGraphShortestPath.h +++ /dev/null @@ -1,51 +0,0 @@ -#pragma once - -#include -#include -#include -using namespace std; - -namespace DirectedAcyclicGraphShortestPath -{ - enum color {WHITE, GRAY, BLACK}; - - class Node - { - public: - int data; - int color; - int distance; - Node* parent; - Node(int data); - }; - - class Edge - { - public: - Node* nodeU; - Node* nodeV; - int weight; - Edge(Node* nodeU, Node* nodeV, int weight); - }; - - class Graph - { - private: - map> _adjlist; - map _nodeMap; - map> _edgeMap; - list _topologicalSortedNodeList; - Node* MakeOrFindNode(int data); - void DepthFirstSearch(Node* node); - void TopologicalSort(); - void InitializeSingleSource(Node* sourceNode); - void Relax(Edge* edge); - void GetShortestPath(Node* node, vector& path); - - - public: - void PushDirectedEdge(int valueU, int valueV, int weight); - void FindDAGShortestPath(int data); - vector GetDAGShortestPath(int data); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0011_SingleSourceShortestPathDijkstra.h b/src/0003_graph/headers/0011_SingleSourceShortestPathDijkstra.h deleted file mode 100644 index 8911ac8..0000000 --- a/src/0003_graph/headers/0011_SingleSourceShortestPathDijkstra.h +++ /dev/null @@ -1,55 +0,0 @@ -#pragma once - -#include -#include -#include -using namespace std; - -namespace SingleSourceShortestPathDijkstra -{ - class Node - { - public: - int data; - int distance; - Node* parent; - Node(int data); - }; - - class Edge - { - public: - Node* nodeU; - Node* nodeV; - int weight; - Edge(Node* nodeU, Node* nodeV, int weight); - }; - - class CompareNodeDistance - { - public: - bool operator()(const Node* nodeU, const Node* nodeV) const - { - return nodeU->distance < nodeV->distance; - } - }; - - class Graph - { - private: - map> _adjlist; - map _nodeMap; - map> _edgeMap; - multiset _operationalSet; - Node* MakeOrFindNode(int data); - void InitializeSingleSource(Node* sourceNode); - void Relax(Edge* edge); - void Dijkstra(Node* source); - void GetShortestPath(Node* node, vector& path); - - public: - void PushDirectedEdge(int valueU, int valueV, int weight); - void FindShortestPathDijkstra(int data); - vector GetDijkstraShortestPath(int data); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0012_DifferenceConstraintsShortestPaths.h b/src/0003_graph/headers/0012_DifferenceConstraintsShortestPaths.h deleted file mode 100644 index 02d1426..0000000 --- a/src/0003_graph/headers/0012_DifferenceConstraintsShortestPaths.h +++ /dev/null @@ -1,43 +0,0 @@ -#pragma once - -#include -#include -#include -using namespace std; - -namespace DifferenceConstraintsShortestPaths -{ - class Node - { - public: - string data; - int distance; - Node(string data); - }; - - class Edge - { - public: - Node* nodeU; - Node* nodeV; - int weight; - Edge(Node* nodeU, Node* nodeV, int weight); - }; - - class Graph - { - private: - map> _adjlist; - map _nodeMap; - vector _edgeList; - Node* MakeOrFindNode(string data); - void PushDirectedEdge(string valueU, string valueV, int weight); - void InitializeSingleSource(Node* sourceNode); - void Relax(Edge* edge); - - public: - void PushAllDirectedEdges(vector> vectorA, vector vectorX, vector vectorB); - bool FindDifferenceConstraintsSolutionBellmanFord(); - vector> GetDifferenceConstrtaintsSolution(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0013_AllPairsShortestPathsFloydWarshall.h b/src/0003_graph/headers/0013_AllPairsShortestPathsFloydWarshall.h deleted file mode 100644 index 211e1b6..0000000 --- a/src/0003_graph/headers/0013_AllPairsShortestPathsFloydWarshall.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include -using namespace std; - -namespace AllPairsShortestPathsFloydWarshall -{ - class Graph - { - private: - int _noOfVertices; - vector> _adjMatrix; - vector> _shortestPathMatrixFloydWarshall; - vector> _predecessorMatrix; - void InitializeDistanceAndPredecessors(); - void GetShortestPath(int source, int destination, vector& path); - - public: - void CreateGraph(int noOfVertices); - void PushDirectedEdge(int valueU, int valueV, int weight); - void FindAllPairsShortestPathsFloydWarshallSolution(); - vector> GetFloydWarshallShortestPath(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0014_AllPairsShortestPathsJohnson.h b/src/0003_graph/headers/0014_AllPairsShortestPathsJohnson.h deleted file mode 100644 index 925e89e..0000000 --- a/src/0003_graph/headers/0014_AllPairsShortestPathsJohnson.h +++ /dev/null @@ -1,66 +0,0 @@ -#pragma once - -#include -#include -#include -using namespace std; - -namespace AllPairsShortestPathsJohnson -{ - class Node - { - public: - int data; - int distance; - Node* parent; - int potentialWeight; - Node(int data); - }; - - class Edge - { - public: - Node* nodeU; - Node* nodeV; - int weight; - Edge(Node* nodeU, Node* nodeV, int weight); - }; - - class CompareNodeDistance - { - public: - bool operator()(const Node* nodeU, const Node* nodeV) const - { - return nodeU->distance < nodeV->distance; - } - }; - - class Graph - { - private: - int _noOfVertices=0; - map> _adjlist; - map _nodeMap; - vector _edgeList; - map> _edgeMap; - map> _augmentedAdjlist; - vector _augmentedEdgeList; - multiset _operationalSet; - vector> _shortestPathMatrix; - vector> _predecessorMatrix; - Node* MakeOrFindNode(int data); - void PushAugmentedDirectedEdges(Node* sourceNode, Node* nodeV, int weight); - void InitializeSingleSource(Node* sourceNode); - void RelaxBellmanFord(Edge* edge); - bool BellmanFord(Node* source); - void RelaxDijkstra(Edge* edge); - void Dijkstra(Node* source); - void GetShortestPath(int source, int destination, vector& path); - - public: - void PushDirectedEdge(int dataU, int dataV, int weight); - bool FindAllPairsShortestPathsJohnsonAlgorithm(); - vector> GetAllPairsShortestPathsDistanceMatrix(); - vector> GetAllPairsShortestPathsPathMatrix(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0015_MaximumFlowFordFulkerson.h b/src/0003_graph/headers/0015_MaximumFlowFordFulkerson.h deleted file mode 100644 index 429b247..0000000 --- a/src/0003_graph/headers/0015_MaximumFlowFordFulkerson.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include -#include -using namespace std; - -namespace MaximumFlowFordFulkerson -{ - class Graph - { - private: - int _noOfVertices; - int _source; - int _sink; - int _maximumFlow; - bool _flagParallelEdges; - vector> _adjMatrix; - vector> _residualGraph; - vector _parent; - vector _visited; - void ResolveAntiParallelEdges(); - void DepthFirstSearchVisit(int nodeU); - bool DepthFirstSearch(); - public: - void CreateGraph(int noOfVertices); - void PushDirectedEdge(int valueU, int valueV, int capacity); - int FindMaximumFlowFordFulkerson(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0016_MaximumFlowEdmondsKarp.h b/src/0003_graph/headers/0016_MaximumFlowEdmondsKarp.h deleted file mode 100644 index 25c72f1..0000000 --- a/src/0003_graph/headers/0016_MaximumFlowEdmondsKarp.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once - -#include -#include -using namespace std; - -namespace MaximumFlowEdmondsKarp -{ - class Graph - { - private: - int _noOfVertices; - int _source; - int _sink; - int _maximumFlow; - bool _flagParallelEdges; - vector> _adjMatrix; - vector> _residualGraph; - vector _parent; - vector _visited; - void ResolveAntiParallelEdges(); - bool BreadthFirstSearch(); - public: - void CreateGraph(int noOfVertices); - void PushDirectedEdge(int valueU, int valueV, int capacity); - int FindMaximumFlowEdmondsKarp(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0017_MaximumBipartiteMatching.h b/src/0003_graph/headers/0017_MaximumBipartiteMatching.h deleted file mode 100644 index 741c3c0..0000000 --- a/src/0003_graph/headers/0017_MaximumBipartiteMatching.h +++ /dev/null @@ -1,41 +0,0 @@ -#pragma once - -#include -#include -using namespace std; - -namespace MaximumBipartiteMatching -{ - enum Color - { - WHITE = -1, - RED = 0, - BLUE = 1 - }; - - class Graph - { - private: - int _noOfVertices; - int _source; - int _sink; - int _maximumFlow; - bool _flagParallelEdges; - bool _isBipartite; - vector> _adjMatrix; - vector> _residualGraph; - vector _parent; - vector _visited; - vector _color; - vector> _matchings; - void ResolveAntiParallelEdges(); - void ColorGraph(); - void AddAdditionalEdges(); - bool BreadthFirstSearch(); - public: - void CreateGraph(int noOfVertices); - void PushDirectedEdge(int valueU, int valueV); - int FindMaximumBipartiteMatching(); - vector> GetMatchings(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0018_MaximumFlowGoldbergGenericPushRelabel.h b/src/0003_graph/headers/0018_MaximumFlowGoldbergGenericPushRelabel.h deleted file mode 100644 index fb13a01..0000000 --- a/src/0003_graph/headers/0018_MaximumFlowGoldbergGenericPushRelabel.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once - -#include -#include -using namespace std; - -namespace MaximumFlowGoldbergGenericPushRelabel -{ - class Graph - { - private: - int _noOfVertices; - int _source; - int _sink; - int _maximumFlow; - vector> _adjMatrix; - vector> _residualGraph; - vector _excessFlow; - vector _height; - vector _visited; - queue _nodeQueue; - void InitializePreflow(); - bool CheckOverFlow(); - bool Push(int nodeU); - void Relabel(int nodeU); - public: - void CreateGraph(int noOfVertices); - void PushDirectedEdge(int valueU, int valueV, int capacity); - int FindMaximumFlowGoldbergGenericPushRelabel(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0019_MaximumFlowRelabelToFront.h b/src/0003_graph/headers/0019_MaximumFlowRelabelToFront.h deleted file mode 100644 index aea70f6..0000000 --- a/src/0003_graph/headers/0019_MaximumFlowRelabelToFront.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once - -#include -#include -using namespace std; - -namespace MaximumFlowRelabelToFront -{ - class Graph - { - private: - int _noOfVertices; - int _source; - int _sink; - int _maximumFlow; - vector> _adjMatrix; - vector> _residualGraph; - vector _excessFlow; - vector _height; - vector _visited; - list _nodeList; - void InitializePreflow(); - void Discharge(int nodeU); - void Push(int nodeU, int nodeV); - void Relabel(int nodeU); - public: - void CreateGraph(int noOfVertices); - void PushDirectedEdge(int valueU, int valueV, int capacity); - int FindMaximumFlowRelabelToFront(); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0001_FibonacciNumber.cc b/src/0004_dynamic_programming/0001_FibonacciNumber.cc deleted file mode 100644 index 47073aa..0000000 --- a/src/0004_dynamic_programming/0001_FibonacciNumber.cc +++ /dev/null @@ -1,28 +0,0 @@ -#include "0001_FibonacciNumber.h" - -namespace FibonacciNumber -{ - int DynamicProgramming::RecursiveNthFibonacci(int n) - { - if (n <= 1) - { - return n; - } - - return this->RecursiveNthFibonacci(n - 1) + this->RecursiveNthFibonacci(n - 2); - } - - int DynamicProgramming::DpNthFibonacci(int n) - { - vector dp(n + 1, 0); - dp[0] = 0; - dp[1] = 1; - - for (int i = 2; i <= n; i++) - { - dp[i] = dp[i - 1] + dp[i - 2]; - } - - return dp[n]; - } -} diff --git a/src/0004_dynamic_programming/0002_TribonacciNumber.cc b/src/0004_dynamic_programming/0002_TribonacciNumber.cc deleted file mode 100644 index 84a4c59..0000000 --- a/src/0004_dynamic_programming/0002_TribonacciNumber.cc +++ /dev/null @@ -1,33 +0,0 @@ -#include "0002_TribonacciNumber.h" - -namespace TribonacciNumber -{ - int DynamicProgramming::RecursiveNthTribonacci(int n) - { - if (n == 0 || n == 1 || n == 2) - { - return 0; - } - - if (n == 3) - { - return 1; - } - - return this->RecursiveNthTribonacci(n - 1) + this->RecursiveNthTribonacci(n - 2) + this->RecursiveNthTribonacci(n - 3); - } - - int DynamicProgramming::DpNthTribonacci(int n) - { - vector dp(n, 0); - dp[0] = dp[1] = 0; - dp[2] = 1; - - for (int i = 3; i < n; i++) - { - dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]; - } - - return dp[n - 1]; - } -} diff --git a/src/0004_dynamic_programming/0003_ClimbingStairs.cc b/src/0004_dynamic_programming/0003_ClimbingStairs.cc deleted file mode 100644 index 6e365f8..0000000 --- a/src/0004_dynamic_programming/0003_ClimbingStairs.cc +++ /dev/null @@ -1,29 +0,0 @@ -#include "0003_ClimbingStairs.h" -using namespace std; - -namespace ClimbingStairs -{ - int DynamicProgramming::RecursiveCountWays(int n) - { - if (n == 0 || n == 1) - { - return 1; - } - - return this->RecursiveCountWays(n - 1) + this->RecursiveCountWays(n - 2); - } - - int DynamicProgramming::DpCountWays(int n) - { - vector dp(n + 1, 0); - dp[0] = 1; - dp[1] = 1; - - for (int i = 2; i <= n; i++) - { - dp[i] = dp[i - 1] + dp[i - 2]; - } - - return dp[n]; - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0004_MinimumCostClimbingStairs.cc b/src/0004_dynamic_programming/0004_MinimumCostClimbingStairs.cc deleted file mode 100644 index 661afc4..0000000 --- a/src/0004_dynamic_programming/0004_MinimumCostClimbingStairs.cc +++ /dev/null @@ -1,48 +0,0 @@ -#include "0004_MinimumCostClimbingStairs.h" -#include - -namespace MinimumCostClimbingStairs -{ - int DynamicProgramming::MinCostRecursive(size_t step, vector& cost) - { - if (step == 0 || step == 1) - { - return cost[step]; - } - - return cost[step] + min(this->MinCostRecursive(step - 1, cost), this->MinCostRecursive(step - 2, cost)); - } - - int DynamicProgramming::RecursiveMinimumCostClimbingStairs(vector& cost) - { - size_t totalSteps = cost.size(); - - if (totalSteps == 1) - { - return cost[0]; - } - - return min(this->MinCostRecursive(totalSteps - 1, cost), this->MinCostRecursive(totalSteps - 2, cost)); - } - - int DynamicProgramming::DpMinimumCostClimbingStairs(vector& cost) - { - size_t totalSteps = cost.size(); - vector dp(totalSteps, 0); - - if (totalSteps == 1) - { - return cost[0]; - } - - dp[0] = cost[0]; - dp[1] = cost[1]; - - for (size_t i = 2; i < totalSteps; i++) - { - dp[i] = cost[i] + min(dp[i - 1], dp[i - 2]); - } - - return min(dp[totalSteps - 1], dp[totalSteps - 2]); - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0005_HouseRobber1.cc b/src/0004_dynamic_programming/0005_HouseRobber1.cc deleted file mode 100644 index 2e3fb7f..0000000 --- a/src/0004_dynamic_programming/0005_HouseRobber1.cc +++ /dev/null @@ -1,44 +0,0 @@ -#include "0005_HouseRobber1.h" - -namespace HouseRobber1 -{ - int DynamicProgramming::MaxLootRecursive(size_t house, vector& houseValues) - { - if (house <= 0) - { - return 0; - } - - if (house == 1) - { - return houseValues[0]; - } - - int pickCurrentHouse = houseValues[house - 1] + this->MaxLootRecursive(house - 2, houseValues); - int dropCurrentHouse = this->MaxLootRecursive(house - 1, houseValues); - - return max(pickCurrentHouse, dropCurrentHouse); - } - - int DynamicProgramming::RecursiveMaximumLoot(vector& houseValues) - { - size_t totalNumberOfHouses = houseValues.size(); - return this->MaxLootRecursive(totalNumberOfHouses, houseValues); - } - - int DynamicProgramming::DpMaximumLoot(vector& houseValues) - { - size_t totalNumberOfHouses = houseValues.size(); - vector dp(totalNumberOfHouses + 1, 0); - - dp[0] = 0; - dp[1] = houseValues[0]; - - for (size_t i = 2; i <= totalNumberOfHouses; i++) - { - dp[i] = max(dp[i - 2] + houseValues[i - 1], dp[i - 1]); - } - - return dp[totalNumberOfHouses]; - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0006_HouseRobber2.cc b/src/0004_dynamic_programming/0006_HouseRobber2.cc deleted file mode 100644 index cbefdda..0000000 --- a/src/0004_dynamic_programming/0006_HouseRobber2.cc +++ /dev/null @@ -1,95 +0,0 @@ -#include "0006_HouseRobber2.h" - -namespace HouseRobber2 -{ - int DynamicProgramming::MaxLootRecursive(size_t house, vector& houseValues) - { - if (house <= 0) - { - return 0; - } - - if (house == 1) - { - return houseValues[0]; - } - - int pickCurrentHouse = houseValues[house - 1] + this->MaxLootRecursive(house - 2, houseValues); - int dropCurrentHouse = this->MaxLootRecursive(house - 1, houseValues); - - return max(pickCurrentHouse, dropCurrentHouse); - } - - int DynamicProgramming::MaxLootDp(size_t firstHouse, size_t lastHouse, vector& houseValues) - { - int totalNumberOfHouses = lastHouse - firstHouse + 1; - - if (totalNumberOfHouses == 0) - { - return 0; - } - - if (totalNumberOfHouses == 1) - { - return houseValues[firstHouse]; - } - - vector dp(totalNumberOfHouses, 0); - - dp[0] = houseValues[firstHouse]; - dp[1] = max(houseValues[firstHouse], houseValues[firstHouse + 1]); - - for (size_t i = 2; i < totalNumberOfHouses; i++) - { - dp[i] = max(houseValues[firstHouse + i] + dp[i - 2], dp[i - 1]); - } - - return dp[totalNumberOfHouses - 1]; - } - - int DynamicProgramming::RecursiveMaximumLoot(vector& houseValues) - { - if (houseValues.size() == 0) - { - return 0; - } - - if (houseValues.size() == 1) - { - return houseValues[0]; - } - - size_t totalNumberOfHouses = houseValues.size()-1; - - // Case 1: Exclude last house. - vector pickFirstHouse(houseValues.begin(), houseValues.end() - 1); - - // Case 2: Exlcude first house. - vector pickLastHouse(houseValues.begin() + 1, houseValues.end()); - - return max(this->MaxLootRecursive(totalNumberOfHouses, pickFirstHouse), this->MaxLootRecursive(totalNumberOfHouses, pickLastHouse)); - } - - int DynamicProgramming::DpMaximumLoot(vector& houseValues) - { - size_t totalNumberOfHouses = houseValues.size(); - - if (totalNumberOfHouses == 0) - { - return 0; - } - - if (totalNumberOfHouses == 1) - { - return houseValues[0]; - } - - // Case 1: Exclude last house. - int pickFirstHouse = this->MaxLootDp(0, totalNumberOfHouses - 2, houseValues); - - // Case 2: Exlcude first house. - int pickLastHouse = this->MaxLootDp(1, totalNumberOfHouses - 1, houseValues); - - return max(pickFirstHouse, pickLastHouse); - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0007_DecodeWays.cc b/src/0004_dynamic_programming/0007_DecodeWays.cc deleted file mode 100644 index bf93270..0000000 --- a/src/0004_dynamic_programming/0007_DecodeWays.cc +++ /dev/null @@ -1,61 +0,0 @@ -#include "0007_DecodeWays.h" - -namespace DecodeWays -{ - int DynamicProgramming::CountWaysRecursiveHelper(string& digits, size_t index) - { - size_t digitsLength = digits.size(); - - // Base case: If the end of the string is reached, return 1 as it signifies a valid decoding. - if (index >= digitsLength) - { - return 1; - } - - int ways = 0; - - // Single digit decoding: check if current digit is not '0'. - if (digits[index] != '0') - { - ways = this->CountWaysRecursiveHelper(digits, index + 1); - } - - // Two digit decoding: check if next two digits are valid. - if ((index + 1 < digitsLength) && ((digits[index] == '1' && digits[index + 1] <= '9') || (digits[index] == '2' && digits[index + 1] <= '6'))) - { - ways += this->CountWaysRecursiveHelper(digits, index + 2); - } - return ways; - } - - int DynamicProgramming::RecursiveCountWays(string digits) - { - return this->CountWaysRecursiveHelper(digits, 0); - } - - int DynamicProgramming::DpCountways(string digits) - { - size_t digitsLength = digits.size(); - - vector dp(digitsLength + 1, 0); - - dp[digitsLength] = 1; - - for (int index = digitsLength - 1; index >= 0; index--) - { - // Single digit decoding: check if current digit is not '0'. - if (digits[index] != '0') - { - dp[index] = dp[index + 1]; - } - - // Two digit decoding: check if next two digits are valid. - if ((index + 1 < digitsLength) && ((digits[index] == '1' && digits[index + 1] <= '9') || (digits[index] == '2' && digits[index + 1] <= '6'))) - { - dp[index] += dp[index + 2]; - } - } - - return dp[0]; - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0008_TilingProblem.cc b/src/0004_dynamic_programming/0008_TilingProblem.cc deleted file mode 100644 index d447c8d..0000000 --- a/src/0004_dynamic_programming/0008_TilingProblem.cc +++ /dev/null @@ -1,42 +0,0 @@ -#include "0008_TilingProblem.h" - -namespace TilingProblem -{ - int DynamicProgramming::NumberOfWaysRecursiveHelper(int n) - { - if (n < 0) - { - return 0; - } - - if (n == 0) - { - return 1; - } - - int result = 0; - result += this->NumberOfWaysRecursiveHelper(n - 1); - result += this->NumberOfWaysRecursiveHelper(n - 2); - - return result; - } - - int DynamicProgramming::RecursiveNumberOfWays(int n) - { - return this->NumberOfWaysRecursiveHelper(n); - } - - int DynamicProgramming::DpNumberOfWays(int n) - { - vector dp(n + 1, 0); - dp[0] = 1; - dp[1] = 1; - - for (int i = 2; i <= n; i++) - { - dp[i] = dp[i - 1] + dp[i - 2]; - } - - return dp[n]; - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0009_FriendsPairingProblem.cc b/src/0004_dynamic_programming/0009_FriendsPairingProblem.cc deleted file mode 100644 index fbea63f..0000000 --- a/src/0004_dynamic_programming/0009_FriendsPairingProblem.cc +++ /dev/null @@ -1,39 +0,0 @@ -#include "0009_FriendsPairingProblem.h" - -namespace FriendsPairingProblem -{ - // Dynamic Programming Private Member Methods. - int DynamicProgramming::CountFriendsPairingsRecursiveHelper(int n) - { - if (n <= 1) - { - return 1; - } - int result = 0; - result += this->CountFriendsPairingsRecursiveHelper(n - 1); - result += (n - 1) * this->CountFriendsPairingsRecursiveHelper(n - 2); - - return result; - } - - // Dynamic Programming Public Member Methods. - int DynamicProgramming::RecursiveCountFriendsPairings(int n) - { - return this->CountFriendsPairingsRecursiveHelper(n); - } - - int DynamicProgramming::DpCountFriendsPairings(int n) - { - vector dp(n + 1, 0); - dp[0] = 0; - dp[1] = 1; - dp[2] = 2; - - for (int i = 3; i <= n; i++) - { - dp[i] = dp[i - 1] + (i - 1) * dp[i - 2]; - } - - return dp[n]; - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0010_WaysToCoverDistance.cc b/src/0004_dynamic_programming/0010_WaysToCoverDistance.cc deleted file mode 100644 index b2f0bce..0000000 --- a/src/0004_dynamic_programming/0010_WaysToCoverDistance.cc +++ /dev/null @@ -1,52 +0,0 @@ -#include "0010_WaysToCoverDistance.h" - -namespace WaysToCoverDistance -{ - // Dynamic Programming Private Member Methods. - int DynamicProgramming::WaysToCoverDistanceRecursiveHelper(int dist) - { - if (dist < 0) - { - return 0; - } - - if (dist == 0) - { - return 1; - } - - int result = 0; - result += this->WaysToCoverDistanceRecursiveHelper(dist - 1); - result += this->WaysToCoverDistanceRecursiveHelper(dist - 2); - result += this->WaysToCoverDistanceRecursiveHelper(dist - 3); - - return result; - } - - // Dynamic Programming Public Member Methods. - int DynamicProgramming::RecursiveWaysToCoverDistance(int dist) - { - return this->WaysToCoverDistanceRecursiveHelper(dist); - } - - int DynamicProgramming::DpWaysToCoverDistance(int dist) - { - vector dp(dist + 1, 0); - dp[0] = 1; - if (dist >= 1) - { - dp[1] = 1; - } - if (dist >= 2) - { - dp[2] = 2; - } - - for(int i = 3; i <= dist; i++) - { - dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]; - } - - return dp[dist]; - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrder.cc b/src/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrder.cc deleted file mode 100644 index f4467e2..0000000 --- a/src/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrder.cc +++ /dev/null @@ -1,44 +0,0 @@ -#include "0011_CountWaysToReachNthStairIncludeOrder.h" - -namespace CountWaysToReachNthStairIncludeOrder -{ - // Dynamic Programming Private Member Methods. - int DynamicProgramming::RecursiveCountWaysToReachNthStairIncludeOrderHelper(int n) - { - if (n < 0) - { - return 0; - } - if (n == 0 || n == 1) - { - return 1; - } - - int result = 0; - result += this->RecursiveCountWaysToReachNthStairIncludeOrderHelper(n - 1); - result += this->RecursiveCountWaysToReachNthStairIncludeOrderHelper(n - 2); - - return result; - } - - // Dynamic Programming Public Member Methods. - int DynamicProgramming::RecursiveCountWaysToReachNthStairIncludeOrder(int n) - { - return this->RecursiveCountWaysToReachNthStairIncludeOrderHelper(n); - } - - int DynamicProgramming::DpCountWaysToReachNthStairIncludeOrder(int n) - { - vector dp(n + 1, 0); - dp[0] = 1; - if (n >= 1) - { - dp[1] = 1; - } - for(int i = 2; i <= n; i++) - { - dp[i] = dp[i - 1] + dp[i - 2]; - } - return dp[n]; - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrder.cc b/src/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrder.cc deleted file mode 100644 index 0e71a69..0000000 --- a/src/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrder.cc +++ /dev/null @@ -1,53 +0,0 @@ -#include "0012_CountWaysToReachNthStairExcludeOrder.h" - -namespace CountWaysToReachNthStairExcludeOrder -{ - // notes: - /* - To avoid counting ways which only differ in order, we can assume that a person initially takes only steps of size 1 followed by steps of size 2. - In other words, once a person takes a step of size 2, he will continue taking steps of size 2 till he reaches the nth stair. - A person can reach nth stair from either(n - 1)th stair or from(n - 2)th stair.So, there are two cases : - The person has reached nth step from(n - 1)th step, this means that the last step was of size 1 and all the previous steps should also be of size 1. So, there is only 1 way. - The person has reached nth step from(n - 2)th step, this means that the last step was of size 2 and the previous steps can either be of size 1 or size 2. - Therefore the Recurrence relation will be : - - nthStair(n) = 1 (last step was of size 1) + nthStair(n - 2) (last step was of size 2) - so f(n) = 1 + f(n - 2) - */ - - // Dynamic Programming Private Member Methods. - int DynamicProgramming::RecursiveCountWaysToReachNthStairExcludeOrderHelper(int n) - { - if (n < 0) - { - return 0; - } - if (n == 0) - { - return 1; - } - - return 1 + this->RecursiveCountWaysToReachNthStairExcludeOrderHelper(n - 2); - } - - // Dynamic Programming Public Member Methods. - int DynamicProgramming::RecursiveCountWaysToReachNthStairExcludeOrder(int n) - { - return this->RecursiveCountWaysToReachNthStairExcludeOrderHelper(n); - } - - int DynamicProgramming::DpCountWaysToReachNthStairExcludeOrder(int n) - { - vector dp(n + 1, 0); - dp[0] = 1; - if (n >= 1) - { - dp[1] = 1; - } - for (int i = 2; i <= n; i++) - { - dp[i] = 1 + dp[i - 2]; - } - return dp[n]; - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0013_KnapsackProblem.cc b/src/0004_dynamic_programming/0013_KnapsackProblem.cc deleted file mode 100644 index e9e5ba2..0000000 --- a/src/0004_dynamic_programming/0013_KnapsackProblem.cc +++ /dev/null @@ -1,78 +0,0 @@ -#include "0013_KnapsackProblem.h" - -namespace KnapsackProblem -{ - // Dynamic Programming Private Member Methods. - int DynamicProgramming::KnapsackRecursiveHelper(int capacity, vector& weight, vector& profit, int numberOfItems) - { - if (capacity <= 0 || numberOfItems == 0) - { - return 0; - } - - int pickCurrentItem = 0; - - // Pick the current item only if does not exceed the capacity. - if (weight[numberOfItems - 1] <= capacity) - { - pickCurrentItem = profit[numberOfItems - 1] + this->KnapsackRecursiveHelper(capacity - weight[numberOfItems - 1], weight, profit, numberOfItems - 1); - } - - int dropCurrentItem = this->KnapsackRecursiveHelper(capacity, weight, profit, numberOfItems - 1); - - return max(pickCurrentItem, dropCurrentItem); - } - - // Dynamic Programming Public Member Methods. - int DynamicProgramming::RecursiveKnapsack(int capacity, vector weight, vector profit) - { - size_t totalNumberOfItems = weight.size(); - return this->KnapsackRecursiveHelper(capacity, weight, profit, totalNumberOfItems); - } - - int DynamicProgramming::DpKnapsack(int capacity, vector weight, vector profit) - { - int numberOfItems = weight.size(); - vector> dp(numberOfItems + 1, vector(capacity + 1, 0)); - - for (int i = 0; i <= numberOfItems; i++) - { - for (int j = 0; j <= capacity; j++) - { - if (i == 0 || j == 0) - { - dp[i][j] = 0; - } - else - { - int pickCurrentItem = 0; - if (weight[i - 1] <= j) - { - pickCurrentItem = profit[i - 1] + dp[i - 1][j - weight[i - 1]]; - } - int dropCurrentItem = dp[i - 1][j]; - - dp[i][j] = max(pickCurrentItem, dropCurrentItem); - } - } - } - - return dp[numberOfItems][capacity]; - } - - int DynamicProgramming::DpKnapsackSpaceOptimized(int capacity, vector weight, vector profit) - { - int numberOfItems = weight.size(); - vector dp(capacity + 1, 0); - - for (int i = 1; i <= numberOfItems; i++) - { - for (int j = capacity; j >= weight[i - 1]; j--) - { - dp[j] = max(dp[j], profit[i - 1] + dp[j - weight[i - 1]]); - } - } - - return dp[capacity]; - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0014_SubsetSumProblem.cc b/src/0004_dynamic_programming/0014_SubsetSumProblem.cc deleted file mode 100644 index 7f558ba..0000000 --- a/src/0004_dynamic_programming/0014_SubsetSumProblem.cc +++ /dev/null @@ -1,71 +0,0 @@ -#include "0014_SubsetSumProblem.h" - -namespace SubsetSumProblem -{ - // Dynamic Programming Private Member Methods. - bool DynamicProgramming::SubsetSumRecursiveHelper(vector& nums, int sum, int numberOfElements) - { - // Base case. - // If the sum is 0, we found a subset with a given sum. - if (sum == 0) - { - return true; - } - - // Base case. - // If there are no elements left to process and the sum is not 0 yet, we did not find a subset with given sum, so return false. - if (numberOfElements == 0) - { - return false; - } - - // When the current element is greater than the sum, we skip it, as all elemeents are non-negative. - if (nums[numberOfElements - 1] > sum) - { - return this->SubsetSumRecursiveHelper(nums, sum, numberOfElements - 1); - } - - // When the current element is equal to or less than the sum, we have two choices. - // 1. Include the current element in the subset and the sum is reduced by the current element value and also the number of elements is reducded by 1. - // 2. Exclude the current element from the subset and the sum remains the same but the number of eleements is reduced by 1. - // If either of these two choices return true, we return true. - return this->SubsetSumRecursiveHelper(nums, sum - nums[numberOfElements - 1], numberOfElements - 1) || this->SubsetSumRecursiveHelper(nums, sum, numberOfElements - 1); - } - - // Dynamic Programming Public Member Methods. - bool DynamicProgramming::RecursiveSubsetSum(vector nums, int sum) - { - int numberOfElements = nums.size(); - return this->SubsetSumRecursiveHelper(nums, sum, numberOfElements); - } - - bool DynamicProgramming::DpIsSubsetSum(vector nums, int sum) - { - int numberOfElements = nums.size(); - vector> dp(numberOfElements + 1, vector(sum + 1, false)); - - // When the sum is 0, the result is true - for (int i = 0; i < numberOfElements; i++) - { - dp[i][0] = true; - } - - for (int i = 1; i < numberOfElements + 1; i++) - { - for (int j = 1; j < sum + 1; j++) - { - if (j < nums[i - 1]) - { - dp[i][j] = dp[i - 1][j]; - } - else - { - // include or exclude the current element - dp[i][j] = (dp[i-1][j-nums[i-1]] || dp[i-1][j]); - } - } - } - - return dp[numberOfElements][sum]; - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0015_CountSubsetsForSum.cc b/src/0004_dynamic_programming/0015_CountSubsetsForSum.cc deleted file mode 100644 index 64d75b6..0000000 --- a/src/0004_dynamic_programming/0015_CountSubsetsForSum.cc +++ /dev/null @@ -1,55 +0,0 @@ -#include "0015_CountSubsetsForSum.h" - -namespace CountSubsetsForSum -{ - // Dynamic Programming private member methods - int DynamicProgramming::RecursiveCountSubsetsHelper(vector& nums, int targetSum, int currentSum, int index) - { - int noOfElements = nums.size(); - if (index == noOfElements) - { - return (targetSum == currentSum); - } - - int exclude = this->RecursiveCountSubsetsHelper(nums, targetSum, currentSum, index + 1); - int include = 0; - - if ((nums[index] + currentSum) <= targetSum) - { - include = this->RecursiveCountSubsetsHelper(nums, targetSum, currentSum + nums[index], index + 1); - } - - return (exclude + include); - } - - // Dynamic Programming public member methods - int DynamicProgramming::RecursiveCountSubsets(vector nums, int sum) - { - return this->RecursiveCountSubsetsHelper(nums, sum, 0, 0); - } - - int DynamicProgramming::DpCountSubsets(vector nums, int sum) - { - int noOfElements = nums.size(); - vector> dp(noOfElements + 1, vector(sum + 1, 0)); - - dp[0][0] = 1; - - for (int i = 1; i <= noOfElements; i++) - { - for (int j = 0; j <= sum; j++) - { - // Considering excluding the current element - dp[i][j] = dp[i - 1][j]; - - // Case to include the current element - if (nums[i - 1] <= j) - { - dp[i][j] += dp[i - 1][j - nums[i - 1]]; - } - } - } - - return dp[noOfElements][sum]; - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0016_PartitionEqualSubsetSum.cc b/src/0004_dynamic_programming/0016_PartitionEqualSubsetSum.cc deleted file mode 100644 index 2db0dab..0000000 --- a/src/0004_dynamic_programming/0016_PartitionEqualSubsetSum.cc +++ /dev/null @@ -1,75 +0,0 @@ -#include "0016_PartitionEqualSubsetSum.h" - -namespace PartitionEqualSubsetSum -{ - bool DynamicProgramming::RecursivePartitionEqualSubsetsHelper(vector& nums, int targetSum, int numberOfElements) - { - if (targetSum == 0) - { - return true; - } - - if (numberOfElements == 0) - { - return false; - } - - if (nums[numberOfElements - 1] > targetSum) - { - return this->RecursivePartitionEqualSubsetsHelper(nums, targetSum, numberOfElements - 1); - } - - return (this->RecursivePartitionEqualSubsetsHelper(nums, targetSum - nums[numberOfElements - 1], numberOfElements - 1) || this->RecursivePartitionEqualSubsetsHelper(nums, targetSum, numberOfElements - 1)); - } - - bool DynamicProgramming::RecursivePartitionEqualSubsets(vector nums) - { - int targetSum = accumulate(nums.begin(), nums.end(), 0); - - // Check if targetSum is odd, then equal partition is not possible at all - if (targetSum % 2 != 0) - { - return false; - } - - int numberOfElements = nums.size(); - return this->RecursivePartitionEqualSubsetsHelper(nums, targetSum / 2, numberOfElements); - } - - bool DynamicProgramming::DpPartitionEqualSubsets(vector nums) - { - int targetSum = accumulate(nums.begin(), nums.end(), 0); - - // Check if targetSum is odd, then equal partition is not possible at all - if (targetSum % 2 != 0) - { - return false; - } - - int numberOfElements = nums.size(); - targetSum /= 2; - vector> dp(numberOfElements + 1, vector(targetSum + 1, false)); - - for (int i = 0; i <= numberOfElements; i++) - { - dp[i][0] = true; - } - - for (int i = 1; i <= numberOfElements; i++) - { - for (int j = 1; j <= targetSum; j++) - { - if (nums[i - 1] > j) - { - dp[i][j] = dp[i - 1][j]; - } - else - { - dp[i][j] = (dp[i-1][j-nums[i-1]] || dp[i-1][j]); - } - } - } - - return dp[numberOfElements][targetSum]; - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0017_TargetSum.cc b/src/0004_dynamic_programming/0017_TargetSum.cc deleted file mode 100644 index c92fe77..0000000 --- a/src/0004_dynamic_programming/0017_TargetSum.cc +++ /dev/null @@ -1,70 +0,0 @@ -#include "0017_TargetSum.h" - -namespace TargetSum -{ - int DynamicProgramming::RecursiveFindTotalWaysHelper(vector& nums, int currentSum, int targetSum, int index) - { - // Base case - if (currentSum == targetSum && index == nums.size()) - { - return 1; - } - - if (index >= nums.size()) - { - return 0; - } - - // Return total count of two possible ways while considering the current element - // 1. Add the current element to currentSum - // 2. Subtract the current element from currentSum - return ( - this->RecursiveFindTotalWaysHelper(nums, currentSum + nums[index], targetSum, index + 1) - + - this->RecursiveFindTotalWaysHelper(nums, currentSum - nums[index], targetSum, index + 1)); - } - - int DynamicProgramming::RecursiveFindTotalWays(vector nums, int target) - { - return this->RecursiveFindTotalWaysHelper(nums, 0, target, 0); - } - - int DynamicProgramming::DpFindTotalWays(vector nums, int target) - { - int totalSum = accumulate(nums.begin(), nums.end(), 0); - - if (abs(target) > totalSum) - { - return 0; - } - - int totalSumWithTarget = totalSum + target; - if (totalSumWithTarget % 2 != 0) - { - return 0; - } - - int targetSubsetSum = totalSumWithTarget / 2; - int noOfElements = nums.size(); - vector> dp(noOfElements + 1, vector(targetSubsetSum + 1, 0)); - - dp[0][0] = 1; - - for (int i = 1; i <= noOfElements; i++) - { - for (int j = 0; j <= targetSubsetSum; j++) - { - // Considering excluding the current element - dp[i][j] = dp[i - 1][j]; - - // Case to include the current element - if (nums[i - 1] <= j) - { - dp[i][j] += dp[i - 1][j - nums[i - 1]]; - } - } - } - - return dp[noOfElements][targetSubsetSum]; - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/CMakeLists.txt b/src/0004_dynamic_programming/CMakeLists.txt deleted file mode 100644 index b063b19..0000000 --- a/src/0004_dynamic_programming/CMakeLists.txt +++ /dev/null @@ -1,28 +0,0 @@ -# Specify the source files -set(0005DYNAMICPROGRAMMING_SOURCES - 0001_FibonacciNumber.cc - 0002_TribonacciNumber.cc - 0003_ClimbingStairs.cc - 0004_MinimumCostClimbingStairs.cc - 0005_HouseRobber1.cc - 0006_HouseRobber2.cc - 0007_DecodeWays.cc - 0008_TilingProblem.cc - 0009_FriendsPairingProblem.cc - 0010_WaysToCoverDistance.cc - 0011_CountWaysToReachNthStairIncludeOrder.cc - 0012_CountWaysToReachNthStairExcludeOrder.cc - 0013_KnapsackProblem.cc - 0014_SubsetSumProblem.cc - 0015_CountSubsetsForSum.cc - 0016_PartitionEqualSubsetSum.cc - 0017_TargetSum.cc - -) - -# Create a library target -add_library(0005DYNAMICPROGRAMMING ${0005DYNAMICPROGRAMMING_SOURCES}) - -target_include_directories(0005DYNAMICPROGRAMMING PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/headers -) \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0001_FibonacciNumber.h b/src/0004_dynamic_programming/headers/0001_FibonacciNumber.h deleted file mode 100644 index 204aeba..0000000 --- a/src/0004_dynamic_programming/headers/0001_FibonacciNumber.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once -#include -using namespace std; - -/* -Pattern 1 -Linear Recurrence - -Description -Print the n'th Fibonacci number. - -*/ - -namespace FibonacciNumber -{ - class DynamicProgramming - { - private: - public: - int RecursiveNthFibonacci(int n); - int DpNthFibonacci(int n); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0002_TribonacciNumber.h b/src/0004_dynamic_programming/headers/0002_TribonacciNumber.h deleted file mode 100644 index 31e805f..0000000 --- a/src/0004_dynamic_programming/headers/0002_TribonacciNumber.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once -#include -using namespace std; - -/* -Pattern 1 -Linear Recurrence - -Description -Print the n'th Tribonacci number. - -*/ - -namespace TribonacciNumber -{ - class DynamicProgramming - { - private: - public: - int RecursiveNthTribonacci(int n); - int DpNthTribonacci(int n); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0003_ClimbingStairs.h b/src/0004_dynamic_programming/headers/0003_ClimbingStairs.h deleted file mode 100644 index e32b71a..0000000 --- a/src/0004_dynamic_programming/headers/0003_ClimbingStairs.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once -#include -using namespace std; - -/* -Pattern 1 -Linear Recurrence - -Description -There are n stairs, and a person standing at the bottom wants to climb stairs to reach the top. -The person can climb either 1 stair or 2 stairs at a time, the task is to count the number of ways that a person can reach at the top. - -*/ - -namespace ClimbingStairs -{ - class DynamicProgramming - { - private: - public: - int RecursiveCountWays(int n); - int DpCountWays(int n); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0004_MinimumCostClimbingStairs.h b/src/0004_dynamic_programming/headers/0004_MinimumCostClimbingStairs.h deleted file mode 100644 index 9ef1ec8..0000000 --- a/src/0004_dynamic_programming/headers/0004_MinimumCostClimbingStairs.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once -#include -using namespace std; - -/* -Pattern 1 -Linear Recurrence - -Description -Given an array of integers cost[] of length n, where cost[i] is the cost of the ith step on a staircase. Once the cost is paid, we can either climb 1 or 2 steps. -We can either start from the step with index 0, or the step with index 1. The task is to find the minimum cost to reach the top. - -*/ - -namespace MinimumCostClimbingStairs -{ - class DynamicProgramming - { - private: - int MinCostRecursive(size_t step, vector& cost); - public: - int RecursiveMinimumCostClimbingStairs(vector& cost); - int DpMinimumCostClimbingStairs(vector& cost); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0005_HouseRobber1.h b/src/0004_dynamic_programming/headers/0005_HouseRobber1.h deleted file mode 100644 index 231fbba..0000000 --- a/src/0004_dynamic_programming/headers/0005_HouseRobber1.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once -#include -using namespace std; - -/* -Pattern 1 -Linear Recurrence - -Description -There are n houses built in a line, each of which contains some money in it. -A robber wants to steal money from these houses, but he can’t steal from two adjacent houses. The task is to find the maximum amount of money which can be stolen. - -*/ - -namespace HouseRobber1 -{ - class DynamicProgramming - { - private: - int MaxLootRecursive(size_t house, vector& houseValues); - public: - int RecursiveMaximumLoot(vector& houseValues); - int DpMaximumLoot(vector& houseValues); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0006_HouseRobber2.h b/src/0004_dynamic_programming/headers/0006_HouseRobber2.h deleted file mode 100644 index 74c3c93..0000000 --- a/src/0004_dynamic_programming/headers/0006_HouseRobber2.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once -#include -using namespace std; - -/* -Pattern 1 -Linear Recurrence - -Description -You are given an array arr[] which represents houses arranged in a circle, where each house has a certain value. A thief aims to maximize the total stolen value without robbing two adjacent houses. -Determine the maximum amount the thief can steal. - -Note: Since the houses are in a circle, the first and last houses are also considered adjacent. - -*/ - -namespace HouseRobber2 -{ - class DynamicProgramming - { - private: - int MaxLootRecursive(size_t house, vector& houseValues); - int MaxLootDp(size_t firstHouse, size_t lastHouse, vector& houseValues); - public: - int RecursiveMaximumLoot(vector& houseValues); - int DpMaximumLoot(vector& houseValues); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0007_DecodeWays.h b/src/0004_dynamic_programming/headers/0007_DecodeWays.h deleted file mode 100644 index fe2b6ce..0000000 --- a/src/0004_dynamic_programming/headers/0007_DecodeWays.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once - -#include -#include -using namespace std; - -/* -Pattern 1 -Linear Recurrence - -Description -Let 1 maps to 'A', 2 maps to 'B', ..., 26 to 'Z'.Given a digit sequence, count the number of possible decodings of the given digit sequence. - -Consider the input string "123".There are three valid ways to decode it : -"ABC" : The grouping is(1, 2, 3) -> 'A', 'B', 'C' -"AW" : The grouping is(1, 23) -> 'A', 'W' -"LC" : The grouping is(12, 3) -> 'L', 'C' -Note : Groupings that contain invalid codes(e.g., "0" by itself or numbers greater than "26") are not allowed. -For instance, the string "230" is invalid because "0" cannot stand alone, and "30" is greater than "26", so it cannot represent any letter.The task is to find the total number of valid ways to decode a given string. -*/ - -namespace DecodeWays -{ - class DynamicProgramming - { - private: - int CountWaysRecursiveHelper(string& digits, size_t index); - public: - int RecursiveCountWays(string digits); - int DpCountways(string digits); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0008_TilingProblem.h b/src/0004_dynamic_programming/headers/0008_TilingProblem.h deleted file mode 100644 index e9befb0..0000000 --- a/src/0004_dynamic_programming/headers/0008_TilingProblem.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -#include -using namespace std; - -/* -Pattern 1 -Linear Recurrence - -Description -Given a "2 x n" board and tiles of size "2 x 1", the task is to count the number of ways to tile the given board using the 2 x 1 tiles. -A tile can either be placed horizontally i.e., as a 1 x 2 tile or vertically i.e., as 2 x 1 tile. -*/ - -namespace TilingProblem -{ - class DynamicProgramming - { - private: - int NumberOfWaysRecursiveHelper(int n); - public: - int RecursiveNumberOfWays(int n); - int DpNumberOfWays(int n); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0009_FriendsPairingProblem.h b/src/0004_dynamic_programming/headers/0009_FriendsPairingProblem.h deleted file mode 100644 index 79cd9da..0000000 --- a/src/0004_dynamic_programming/headers/0009_FriendsPairingProblem.h +++ /dev/null @@ -1,46 +0,0 @@ -#pragma once - -#include -using namespace std; - -/* -Pattern 1 -Linear Recurrence - -Description -Given n friends, each one can remain single or can be paired up with some other friend. Each friend can be paired only once. Find out the total number of ways in which friends can remain single or can be paired up. - -Examples: - -Input : n = 3 -Output : 4 -Explanation: -{1}, {2}, {3} : all single -{1}, {2, 3} : 2 and 3 paired but 1 is single. -{1, 2}, {3} : 1 and 2 are paired but 3 is single. -{1, 3}, {2} : 1 and 3 are paired but 2 is single. -Note that {1, 2} and {2, 1} are considered same. - -Mathematical Explanation: -The problem is simplified version of how many ways we can divide n elements into multiple groups. -(here group size will be max of 2 elements). -In case of n = 3, we have only 2 ways to make a group: - 1) all elements are individual(1,1,1) - 2) a pair and individual (2,1) -In case of n = 4, we have 3 ways to form a group: - 1) all elements are individual (1,1,1,1) - 2) 2 individuals and one pair (2,1,1) - 3) 2 separate pairs (2,2) -*/ - -namespace FriendsPairingProblem -{ - class DynamicProgramming - { - private: - int CountFriendsPairingsRecursiveHelper(int n); - public: - int RecursiveCountFriendsPairings(int n); - int DpCountFriendsPairings(int n); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0010_WaysToCoverDistance.h b/src/0004_dynamic_programming/headers/0010_WaysToCoverDistance.h deleted file mode 100644 index 0268ff5..0000000 --- a/src/0004_dynamic_programming/headers/0010_WaysToCoverDistance.h +++ /dev/null @@ -1,47 +0,0 @@ -#pragma once - -#include -using namespace std; - -/* -Pattern 1 -Linear Recurrence - -Description -Given a distance 'dist', count total number of ways to cover the distance with 1, 2 and 3 steps. - -Examples: - -Input: n = 3 -Output: 4 -Explanation: Below are the four ways -=> 1 step + 1 step + 1 step -=> 1 step + 2 step -=> 2 step + 1 step -=> 3 step - - - -Input: n = 4 -Output: 7 -Explanation: Below are the four ways -=> 1 step + 1 step + 1 step + 1 step -=> 1 step + 2 step + 1 step -=> 2 step + 1 step + 1 step -=> 1 step + 1 step + 2 step -=> 2 step + 2 step -=> 3 step + 1 step -=> 1 step + 3 step -*/ - -namespace WaysToCoverDistance -{ - class DynamicProgramming - { - private: - int WaysToCoverDistanceRecursiveHelper(int dist); - public: - int RecursiveWaysToCoverDistance(int dist); - int DpWaysToCoverDistance(int dist); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0011_CountWaysToReachNthStairIncludeOrder.h b/src/0004_dynamic_programming/headers/0011_CountWaysToReachNthStairIncludeOrder.h deleted file mode 100644 index 6851031..0000000 --- a/src/0004_dynamic_programming/headers/0011_CountWaysToReachNthStairIncludeOrder.h +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once - -#include -using namespace std; - -/* -Pattern 1 -Linear Recurrence - -Description -There are n stairs, and a person standing at the bottom wants to climb stairs to reach the top. -The person can climb either 1 stair or 2 stairs at a time, the task is to count the number of ways that a person can reach at the top. - -Note: This problem is similar to Count ways to reach Nth stair (Order does not matter) with the only difference that in this problem, -we count all distinct ways where different orderings of the steps are considered unique. - -Examples: - -Input: n = 1 -Output: 1 -Explanation: There is only one way to climb 1 stair. - -Input: n = 2 -Output: 2 -Explanation: There are two ways to reach 2th stair: {1, 1} and {2}. - -Input: n = 4 -Output: 5 -Explanation: There are five ways to reach 4th stair: {1, 1, 1, 1}, {1, 1, 2}, {2, 1, 1}, {1, 2, 1} and {2, 2}. -*/ - -namespace CountWaysToReachNthStairIncludeOrder -{ - class DynamicProgramming - { - private: - int RecursiveCountWaysToReachNthStairIncludeOrderHelper(int n); - public: - int RecursiveCountWaysToReachNthStairIncludeOrder(int n); - int DpCountWaysToReachNthStairIncludeOrder(int n); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0012_CountWaysToReachNthStairExcludeOrder.h b/src/0004_dynamic_programming/headers/0012_CountWaysToReachNthStairExcludeOrder.h deleted file mode 100644 index 4d52930..0000000 --- a/src/0004_dynamic_programming/headers/0012_CountWaysToReachNthStairExcludeOrder.h +++ /dev/null @@ -1,44 +0,0 @@ -#pragma once - -#include -using namespace std; - -/* -Pattern 1 -Linear Recurrence - -Description -There are n stairs, and a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top (order does not matter). - -Note: The problem is similar to Climbing Stairs - Count ways to reach Nth stair with the only difference that in this problem, we don't have to count those ways which only differ in ordering of the steps. - -Examples: - -Input: n = 1 -Output: 1 -Explanation: There is only one way to climb 1 stair. - -Input: n = 2 -Output: 2 -Explanation: There are two ways to climb 2 stairs: {1, 1} and {2}. - -Input: n = 4 -Output: 3 -Explanation: Three ways to reach 4th stair: {1, 1, 1, 1}, {1, 1, 2} and {2, 2}. - -Input: n = 5 -Output: 3 -Explanation: Three ways to reach 5th stair: {1, 1, 1, 1, 1}, {1, 1, 1, 2} and {1, 2, 2}. -*/ - -namespace CountWaysToReachNthStairExcludeOrder -{ - class DynamicProgramming - { - private: - int RecursiveCountWaysToReachNthStairExcludeOrderHelper(int n); - public: - int RecursiveCountWaysToReachNthStairExcludeOrder(int n); - int DpCountWaysToReachNthStairExcludeOrder(int n); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0013_KnapsackProblem.h b/src/0004_dynamic_programming/headers/0013_KnapsackProblem.h deleted file mode 100644 index b7c90aa..0000000 --- a/src/0004_dynamic_programming/headers/0013_KnapsackProblem.h +++ /dev/null @@ -1,34 +0,0 @@ -#pragma once - -#include -using namespace std; - -/* -Pattern 2 -Subset / 0-1 Knapsack - -Description -Given n items where each item has some weight and profit associated with it and also given a bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items into the bag such that the sum of profits associated with them is the maximum possible. - -Note: The constraint here is we can either put an item completely into the bag or cannot put it at all [It is not possible to put a part of an item into the bag]. - -Input: W = 4, profit[] = [1, 2, 3], weight[] = [4, 5, 1] -Output: 3 -Explanation: There are two items which have weight less than or equal to 4. If we select the item with weight 4, the possible profit is 1. And if we select the item with weight 1, the possible profit is 3. So the maximum possible profit is 3. Note that we cannot put both the items with weight 4 and 1 together as the capacity of the bag is 4. - -Input: W = 3, profit[] = [1, 2, 3], weight[] = [4, 5, 6] -Output: 0 -*/ - -namespace KnapsackProblem -{ - class DynamicProgramming - { - private: - int KnapsackRecursiveHelper(int capacity, vector& weight, vector& profit, int numberOfItems); - public: - int RecursiveKnapsack(int capacity, vector weight, vector profit); - int DpKnapsack(int capacity, vector weight, vector profit); - int DpKnapsackSpaceOptimized(int capacity, vector weight, vector profit); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0014_SubsetSumProblem.h b/src/0004_dynamic_programming/headers/0014_SubsetSumProblem.h deleted file mode 100644 index 399d328..0000000 --- a/src/0004_dynamic_programming/headers/0014_SubsetSumProblem.h +++ /dev/null @@ -1,34 +0,0 @@ -#pragma once - -#include -using namespace std; - -/* -Pattern 2 -Subset / 0-1 Knapsack - -Description -Given an array arr[] of non-negative integers and a value sum, the task is to check if there is a subset of the given array whose sum is equal to the given sum. - -Examples: - -Input: arr[] = [3, 34, 4, 12, 5, 2], sum = 9 -Output: True -Explanation: There is a subset (4, 5) with sum 9. - -Input: arr[] = [3, 34, 4, 12, 5, 2], sum = 30 -Output: False -Explanation: There is no subset that add up to 30. -*/ - -namespace SubsetSumProblem -{ - class DynamicProgramming - { - private: - bool SubsetSumRecursiveHelper(vector& nums, int sum, int numberOfElements); - public: - bool RecursiveSubsetSum(vector nums, int sum); - bool DpIsSubsetSum(vector nums, int sum); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0015_CountSubsetsForSum.h b/src/0004_dynamic_programming/headers/0015_CountSubsetsForSum.h deleted file mode 100644 index 4f55bbf..0000000 --- a/src/0004_dynamic_programming/headers/0015_CountSubsetsForSum.h +++ /dev/null @@ -1,34 +0,0 @@ -#pragma once - -#include -using namespace std; - -/* -Pattern 2 -Subset / 0-1 Knapsack - -Description -Given an array arr[] of length n and an integer target, the task is to find the number of subsets with a sum equal to target. - -Examples: - -Input: arr[] = [1, 2, 3, 3], target = 6 -Output: 3 -Explanation: All the possible subsets are [1, 2, 3], [1, 2, 3] and [3, 3] - -Input: arr[] = [1, 1, 1, 1], target = 1 -Output: 4 -Explanation: All the possible subsets are [1], [1], [1] and [1] -*/ - -namespace CountSubsetsForSum -{ - class DynamicProgramming - { - private: - int RecursiveCountSubsetsHelper(vector& nums, int targetSum, int currentSum, int index); - public: - int RecursiveCountSubsets(vector nums, int sum); - int DpCountSubsets(vector nums, int sum); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0016_PartitionEqualSubsetSum.h b/src/0004_dynamic_programming/headers/0016_PartitionEqualSubsetSum.h deleted file mode 100644 index bf3c261..0000000 --- a/src/0004_dynamic_programming/headers/0016_PartitionEqualSubsetSum.h +++ /dev/null @@ -1,36 +0,0 @@ -#pragma once - -#include -#include -using namespace std; - -/* -Pattern 2 -Subset / 0-1 Knapsack - -Description -Given an array arr[], check if it can be partitioned into two parts such that the sum of elements in both parts is the same. -Note: Each element is present in either the first subset or the second subset, but not in both. - -Examples: - -Input: arr[] = [1, 5, 11, 5] -Output: true -Explanation: The array can be partitioned as [1, 5, 5] and [11] and the sum of both the subsets are equal. - -Input: arr[] = [1, 5, 3] -Output: false -Explanation: The array cannot be partitioned into equal sum sets. -*/ - -namespace PartitionEqualSubsetSum -{ - class DynamicProgramming - { - private: - bool RecursivePartitionEqualSubsetsHelper(vector& nums, int targetSum, int numberOfElements); - public: - bool RecursivePartitionEqualSubsets(vector nums); - bool DpPartitionEqualSubsets(vector nums); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0017_TargetSum.h b/src/0004_dynamic_programming/headers/0017_TargetSum.h deleted file mode 100644 index 1ee27ad..0000000 --- a/src/0004_dynamic_programming/headers/0017_TargetSum.h +++ /dev/null @@ -1,45 +0,0 @@ -#pragma once - -#include -#include -using namespace std; - -/* -Pattern 2 -Subset / 0-1 Knapsack - -Description -Given an array arr[] of length N and an integer target. -You want to build an expression out of arr[] by adding one of the symbols '+' and '-' before each integer in arr[] and then concatenate all the integers. -Return the number of different expressions that can be built, which evaluates to target. - -Example: - -Input : N = 5, arr[] = {1, 1, 1, 1, 1}, target = 3 -Output: 5 -Explanation: -There are 5 ways to assign symbols to -make the sum of array be target 3. - --1 + 1 + 1 + 1 + 1 = 3 -+1 - 1 + 1 + 1 + 1 = 3 -+1 + 1 - 1 + 1 + 1 = 3 -+1 + 1 + 1 - 1 + 1 = 3 -+1 + 1 + 1 + 1 - 1 = 3 - -Input: N = 1, arr[] = {1}, target = 1 -Output: 1 -*/ - -namespace TargetSum -{ - class DynamicProgramming - { - private: - int RecursiveFindTotalWaysHelper(vector& nums, int currentSum, int targetSum, int index); - int DpFindTotalWays(); - public: - int RecursiveFindTotalWays(vector nums, int target); - int DpFindTotalWays(vector nums, int target); - }; -} \ No newline at end of file diff --git a/src/0005_greedy_algorithms/CMakeLists.txt b/src/0005_greedy_algorithms/CMakeLists.txt deleted file mode 100644 index e69de29..0000000 diff --git a/src/0006_bitwise_algorithms/CMakeLists.txt b/src/0006_bitwise_algorithms/CMakeLists.txt deleted file mode 100644 index e69de29..0000000 diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt deleted file mode 100644 index 708289d..0000000 --- a/src/CMakeLists.txt +++ /dev/null @@ -1,6 +0,0 @@ -add_subdirectory(0001_basics) -add_subdirectory(0002_tree) -add_subdirectory(0003_graph) -add_subdirectory(0004_dynamic_programming) -add_subdirectory(0005_greedy_algorithms) -add_subdirectory(0006_bitwise_algorithms) \ No newline at end of file diff --git a/tests/0000_common_utilities/CMakeLists.txt b/tests/0000_common_utilities/CMakeLists.txt deleted file mode 100644 index e69de29..0000000 diff --git a/tests/0000_common_utilities/UnitTestHelper.h b/tests/0000_common_utilities/UnitTestHelper.h deleted file mode 100644 index ff676bd..0000000 --- a/tests/0000_common_utilities/UnitTestHelper.h +++ /dev/null @@ -1,183 +0,0 @@ -#pragma once - -#include -#include -#include -#include -using namespace std; - -class UnitTestHelper -{ -public: - template - string SerializeVectorToString(vector vector) - { - string result = ""; - for (auto& iterator : vector) - { - result += to_string(iterator) + " "; - } - result.pop_back(); - return result; - } - - template - string SerializeVectorToString(vector> vector) - { - string result = ""; - for (auto& iterator : vector) - { - result += to_string(iterator.first) + "(" + to_string(iterator.second) + ")" + " "; - } - - if (!result.empty()) - { - result.pop_back(); - } - return result; - } - - template - string SerializeVectorToString(vector>> vector) - { - string result = ""; - for (auto& iterator : vector) - { - result += to_string(iterator.first) + "(" + to_string(iterator.second.first) + "," + to_string(iterator.second.second) + ")" + " "; - } - - if (!result.empty()) - { - result.pop_back(); - } - return result; - } - - template - string SerializeVectorToString(vector> vector) - { - string result = ""; - for (auto& iterator : vector) - { - result += "["; - for (auto& it : iterator) - { - result += to_string(it) + " "; - } - if (!result.empty()) - { - result.pop_back(); - } - result += "]"; - } - return result; - } - - // This helper method is used to sort the vector of vectors of a particular typename. - // Each inner vector is sorted first. - // Then each of them are sorted by their first element, in increasing order. - template - vector> SortVectorOfVectors(vector> data) - { - // Step 1: Sorting each inner vectors. - for (auto& innerVector : data) - { - sort(innerVector.begin(), innerVector.end()); - } - - // Step 2: Sorting all the vectors by their first element, in increasing order. - sort(data.begin(), data.end(), [](const vector& a, const vector& b) - { - // Checking if both inner vectors are empty to prevent out-of-bounds access. - if (a.empty() && b.empty()) - return false; - - // Considering empty vector as less than non-empty vector. - if (a.empty()) - return true; - - // Considering non-empty vector as greater than empty vector. - if (b.empty()) - return false; - - // Comparing the first elements of each vector. - return (a[0] < b[0]); - }); - - return data; - } - - template - bool NormalizeCyclesAndCompare(vector data1, vector data2) - { - if (data1.size() != data2.size()) - { - return false; - } - - // Normalized rotation of cycle 1 - vector normalizedCycle1(data1); - auto minIterator1 = min_element(normalizedCycle1.begin(), normalizedCycle1.end()); - rotate(normalizedCycle1.begin(), minIterator1, normalizedCycle1.end()); - - // Normalized rotation of cycle 2 - vector normalizedCycle2(data2); - auto minIterator2 = min_element(normalizedCycle2.begin(), normalizedCycle2.end()); - rotate(normalizedCycle2.begin(), minIterator2, normalizedCycle2.end()); - - // Check clock wise - if (normalizedCycle1 == normalizedCycle2) - { - return true; - } - - // Check counter clock wise - reverse(normalizedCycle2.begin() + 1, normalizedCycle2.end()); - return (normalizedCycle1 == normalizedCycle2); - } - - template - vector, T>> SortVectorOfPair(vector, T>> data) - { - for (auto& iterator : data) - { - if (iterator.first.first > iterator.first.second) - { - swap(iterator.first.first, iterator.first.second); - } - } - - sort(data.begin(), data.end(), [](const pair, T>& pairA, const pair, T>& pairB) - { - if (pairA.second == pairB.second) - { - return pairA.first.first < pairB.first.first; - } - return pairA.second < pairB.second; - }); - return data; - } - - template - string SortVectorOfPairAndSerialize(vector> data) - { - // Sorting the vector in non-decreasing order on typename T1 - sort(data.begin(), data.end(), [](const pair& pair1, const pair& pair2) - { - return pair1.first < pair2.first; - }); - - // Serializing the vector to string - string result = ""; - for (auto& iterator : data) - { - result += iterator.first + "(" + to_string(iterator.second) + ")" + " "; - } - - if (!result.empty()) - { - result.pop_back(); - } - return result; - } -}; \ No newline at end of file diff --git a/tests/0001_Basics/CMakeLists.txt b/tests/0001_Basics/CMakeLists.txt deleted file mode 100644 index efa1008..0000000 --- a/tests/0001_Basics/CMakeLists.txt +++ /dev/null @@ -1,31 +0,0 @@ -cmake_policy(SET CMP0135 NEW) - -include(FetchContent) -FetchContent_Declare( - googletest - URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip -) -# For Windows: Prevent overriding the parent project's compiler/linker settings -set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) -FetchContent_MakeAvailable(googletest) - - -enable_testing() - -add_executable( - 0001BasicsTests - NodeTest.cc) - -target_link_libraries( - 0001BasicsTests - GTest::gtest_main - 0001BASICS -) - -# Add .clang-tidy configuration to this library. -if(CLANG_TIDY_EXE) - set_target_properties(0001BASICS PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") -endif() - -include(GoogleTest) -gtest_discover_tests(0001BasicsTests DISCOVERY_TIMEOUT 30) \ No newline at end of file diff --git a/tests/0001_Basics/NodeTest.cc b/tests/0001_Basics/NodeTest.cc deleted file mode 100644 index ca38297..0000000 --- a/tests/0001_Basics/NodeTest.cc +++ /dev/null @@ -1,12 +0,0 @@ -#include -#include "Node.h" - -// Demonstrate some basic assertions. -namespace NodeTesting -{ - TEST(TestingNodeValue, PositiveTestCase) - { - // Expect two strings not to be equal. - EXPECT_EQ(2 * 4, 8); - } -} \ No newline at end of file diff --git a/tests/0002_Tree/0001_BinarySearchTreeTest.cc b/tests/0002_Tree/0001_BinarySearchTreeTest.cc deleted file mode 100644 index d99a30e..0000000 --- a/tests/0002_Tree/0001_BinarySearchTreeTest.cc +++ /dev/null @@ -1,91 +0,0 @@ -#include -#include -#include "0001_BinarySearchTree.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace BinarySearchTree -{ - UnitTestHelper unitTestHelper; - - TEST(BSTInsertData, RecursiveInorderTest) - { - BinarySearchTree bst; - bst.InsertNode(50); - bst.InsertNode(30); - bst.InsertNode(60); - - - string actualResult = unitTestHelper.SerializeVectorToString(bst.GetRecursiveInorderTravesalResult()); - string expectedResult = "30 50 60"; - - EXPECT_EQ(actualResult, expectedResult); - } - - TEST(BSTInsertData, RecursivePreorderTest) - { - BinarySearchTree bst; - bst.InsertNode(50); - bst.InsertNode(30); - bst.InsertNode(60); - - string actualResult = unitTestHelper.SerializeVectorToString(bst.GetRecursivePreorderTravesalResult()); - string expectedResult = "50 30 60"; - - EXPECT_EQ(actualResult, expectedResult); - } - - TEST(BSTInsertData, RecursivePostorderTest) - { - BinarySearchTree bst; - bst.InsertNode(50); - bst.InsertNode(30); - bst.InsertNode(60); - - string actualResult = unitTestHelper.SerializeVectorToString(bst.GetRecursivePostorderTravesalResult()); - string expectedResult = "30 60 50"; - - EXPECT_EQ(actualResult, expectedResult); - } - - TEST(BSTInsertData, MorrisInorderTest) - { - BinarySearchTree bst; - bst.InsertNode(50); - bst.InsertNode(30); - bst.InsertNode(60); - - - string actualResult = unitTestHelper.SerializeVectorToString(bst.GetMorrisInorderTraversalResult()); - string expectedResult = "30 50 60"; - - EXPECT_EQ(actualResult, expectedResult); - } - - TEST(BSTInsertData, MorrisPreorderTest) - { - BinarySearchTree bst; - bst.InsertNode(50); - bst.InsertNode(30); - bst.InsertNode(60); - - - string actualResult = unitTestHelper.SerializeVectorToString(bst.GetMorrisPreorderTraversalResult()); - string expectedResult = "50 30 60"; - - EXPECT_EQ(actualResult, expectedResult); - } - - TEST(BSTInsertData, MorrisPostorderTest) - { - BinarySearchTree bst; - bst.InsertNode(50); - bst.InsertNode(30); - bst.InsertNode(60); - - - string actualResult = unitTestHelper.SerializeVectorToString(bst.GetMorrisPostorderTraversalResult()); - string expectedResult = "30 60 50"; - - EXPECT_EQ(actualResult, expectedResult); - } -} \ No newline at end of file diff --git a/tests/0002_Tree/CMakeLists.txt b/tests/0002_Tree/CMakeLists.txt deleted file mode 100644 index aef689e..0000000 --- a/tests/0002_Tree/CMakeLists.txt +++ /dev/null @@ -1,32 +0,0 @@ -cmake_policy(SET CMP0135 NEW) - -include(FetchContent) -FetchContent_Declare( - googletest - URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip -) - -# For Windows: Prevent overriding the parent project's compiler/linker settings -set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) -FetchContent_MakeAvailable(googletest) - -enable_testing() - -add_executable( - 0002TreeTests - 0001_BinarySearchTreeTest.cc -) - -target_link_libraries( - 0002TreeTests - GTest::gtest_main - 0002TREE -) - -# Add .clang-tidy configuration to this library. -if(CLANG_TIDY_EXE) - set_target_properties(0002TREE PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") -endif() - -include(GoogleTest) -gtest_discover_tests(0002TreeTests DISCOVERY_TIMEOUT 30) \ No newline at end of file diff --git a/tests/0003_Graph/0001_BreadthFirstSearchTest.cc b/tests/0003_Graph/0001_BreadthFirstSearchTest.cc deleted file mode 100644 index c0beb81..0000000 --- a/tests/0003_Graph/0001_BreadthFirstSearchTest.cc +++ /dev/null @@ -1,45 +0,0 @@ -#include -#include -#include "../../src/0003_graph/headers/0001_BreadthFirstSearch.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace BreadthFirstSearch -{ - UnitTestHelper unitTestHelper; - - - TEST(BFSTesting, ShowBFSResultTest01) - { - Graph graph; - - graph.PushUndirectedEdge(1, 2); - graph.PushUndirectedEdge(1, 3); - graph.PushUndirectedEdge(2, 4); - graph.PushUndirectedEdge(3, 5); - graph.PushUndirectedEdge(3, 6); - graph.PushUndirectedEdge(5, 6); - graph.PushUndirectedEdge(5, 7); - graph.PushUndirectedEdge(6, 7); - graph.PushUndirectedEdge(6, 8); - graph.PushUndirectedEdge(7, 8); - - graph.BFS(1); - - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowBFSResult()); - string expectedResult = "1(0) 2(1) 3(1) 4(2) 5(2) 6(2) 7(3) 8(3)"; - EXPECT_EQ(actualResult, expectedResult); - } - - TEST(BFSTesting, ShowBFSResultTest02) - { - Graph graph; - - graph.PushUndirectedEdge(1, 2); - - graph.BFS(1); - - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowBFSResult()); - string expectedResult = "1(0) 2(1)"; - EXPECT_EQ(actualResult, expectedResult); - } -} \ No newline at end of file diff --git a/tests/0003_Graph/0002_DepthFirstSearchTest.cc b/tests/0003_Graph/0002_DepthFirstSearchTest.cc deleted file mode 100644 index c96c55e..0000000 --- a/tests/0003_Graph/0002_DepthFirstSearchTest.cc +++ /dev/null @@ -1,177 +0,0 @@ -#include -#include "0002_DepthFirstSearch.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace DepthFirstSearch -{ - UnitTestHelper unitTestHelper; - - TEST(DFSTesting, ShowDFSResultTest01) - { - Graph graph; - - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(1, 4); - graph.PushDirectedEdge(2, 5); - graph.PushDirectedEdge(3, 5); - graph.PushDirectedEdge(3, 6); - graph.PushDirectedEdge(4, 2); - graph.PushDirectedEdge(5, 4); - graph.PushDirectedEdge(6, 6); - - graph.DFS(); - - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); - string expectedResult = "1(1,8) 2(2,7) 3(9,12) 4(4,5) 5(3,6) 6(10,11)"; - EXPECT_EQ(actualResult, expectedResult); - } - - - TEST(DFSTesting, ShowDFSResultTest_SingleVertex) - { - Graph graph; - - graph.PushDirectedEdge(1, 1); - - graph.DFS(); - - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); - string expectedResult = "1(1,2)"; - EXPECT_EQ(actualResult, expectedResult); - } - - TEST(DFSTesting, ShowDFSResultTest_DisconnectedGraph) - { - Graph graph; - - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(3, 4); - - graph.DFS(); - - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); - string expectedResult = "1(1,4) 2(2,3) 3(5,8) 4(6,7)"; - EXPECT_EQ(actualResult, expectedResult); - } - - TEST(DFSTesting, ShowDFSResultTest_CyclicGraph) - { - Graph graph; - - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(3, 1); - - graph.DFS(); - - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); - string expectedResult = "1(1,6) 2(2,5) 3(3,4)"; - EXPECT_EQ(actualResult, expectedResult); - } - - TEST(DFSTesting, ShowDFSResultTest_LargeGraph) - { - Graph graph; - - // Adding 15 nodes with several edges - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(1, 3); - graph.PushDirectedEdge(2, 4); - graph.PushDirectedEdge(4, 5); - graph.PushDirectedEdge(5, 6); - graph.PushDirectedEdge(6, 7); - graph.PushDirectedEdge(7, 8); - graph.PushDirectedEdge(8, 9); - graph.PushDirectedEdge(9, 10); - graph.PushDirectedEdge(10, 11); - graph.PushDirectedEdge(11, 12); - graph.PushDirectedEdge(12, 13); - graph.PushDirectedEdge(13, 14); - graph.PushDirectedEdge(14, 15); - graph.PushDirectedEdge(15, 16); - - graph.DFS(); - - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); - string expectedResult = "1(1,32) 2(2,29) 3(30,31) 4(3,28) 5(4,27) 6(5,26) 7(6,25) 8(7,24) 9(8,23) 10(9,22) 11(10,21) 12(11,20) 13(12,19) 14(13,18) 15(14,17) 16(15,16)"; - EXPECT_EQ(actualResult, expectedResult); - } - - TEST(DFSTesting, ShowDFSResultTest_NoEdges) - { - Graph graph; - - // Adding isolated nodes - graph.PushDirectedEdge(1, 1); - graph.PushDirectedEdge(2, 2); - graph.PushDirectedEdge(3, 3); - - graph.DFS(); - - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); - string expectedResult = "1(1,2) 2(3,4) 3(5,6)"; - EXPECT_EQ(actualResult, expectedResult); - } - - TEST(DFSTesting, ShowDFSResultTest_CyclicGraphWithBackEdges) - { - Graph graph; - - // Creating a cycle with back edges - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(3, 1); // Cycle back to 'a' - graph.PushDirectedEdge(2, 4); // Back edge - - graph.DFS(); - - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); - string expectedResult = "1(1,8) 2(2,7) 3(3,4) 4(5,6)"; - EXPECT_EQ(actualResult, expectedResult); - } - - TEST(DFSTesting, ShowDFSResultTest_DenseGraph) - { - Graph graph; - - // Complete graph of 4 nodes - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(1, 3); - graph.PushDirectedEdge(1, 4); - graph.PushDirectedEdge(2, 1); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(2, 4); - graph.PushDirectedEdge(3, 1); - graph.PushDirectedEdge(3, 2); - graph.PushDirectedEdge(3, 4); - graph.PushDirectedEdge(4, 1); - graph.PushDirectedEdge(4, 2); - graph.PushDirectedEdge(4, 3); - - graph.DFS(); - - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); - string expectedResult = "1(1,8) 2(2,7) 3(3,6) 4(4,5)"; - EXPECT_EQ(actualResult, expectedResult); - } - - TEST(DFSTesting, ShowDFSResultTest_SelfLoopsAndParallelEdges) - { - Graph graph; - - // Adding self-loops and parallel edges - graph.PushDirectedEdge(1, 1); - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(2, 2); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(2, 3); // Parallel edge - graph.PushDirectedEdge(3, 3); // Self-loop - - graph.DFS(); - - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); - string expectedResult = "1(1,6) 2(2,5) 3(3,4)"; - EXPECT_EQ(actualResult, expectedResult); - } - -} \ No newline at end of file diff --git a/tests/0003_Graph/0003_TopologicalSortTest.cc b/tests/0003_Graph/0003_TopologicalSortTest.cc deleted file mode 100644 index 6ad277e..0000000 --- a/tests/0003_Graph/0003_TopologicalSortTest.cc +++ /dev/null @@ -1,116 +0,0 @@ -#include -#include "0003_TopologicalSort.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace TopologicalSort -{ - UnitTestHelper unitTestHelper; - - TEST(TopoSortTesting, ShowTopoSortResult) - { - Graph graph; - - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(1, 4); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(4, 3); - graph.PushSingleNode(5); - graph.PushDirectedEdge(6, 7); - graph.PushDirectedEdge(6, 8); - graph.PushDirectedEdge(7, 4); - graph.PushDirectedEdge(7, 8); - graph.PushDirectedEdge(9, 8); - - graph.TopologicalSort(); - - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); - string expectedResult = "9(17,18) 6(11,16) 7(12,15) 8(13,14) 5(9,10) 1(1,8) 4(6,7) 2(2,5) 3(3,4)"; - - EXPECT_EQ(actualResult, expectedResult); - } - - // Test with a larger graph and multiple paths between nodes - TEST(TopoSortTesting, LargeGraphMultiplePaths) - { - Graph graph; - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(1, 3); - graph.PushDirectedEdge(2, 4); - graph.PushDirectedEdge(3, 4); - graph.PushDirectedEdge(4, 5); - graph.PushDirectedEdge(5, 6); - graph.PushDirectedEdge(6, 7); - - graph.TopologicalSort(); - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); - string expectedResult = "1(1,14) 3(12,13) 2(2,11) 4(3,10) 5(4,9) 6(5,8) 7(6,7)"; - - EXPECT_EQ(actualResult, expectedResult); - } - - // Test with a graph containing disconnected components - TEST(TopoSortTesting, DisconnectedGraph) - { - Graph graph; - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(3, 4); - graph.PushDirectedEdge(5, 6); - - graph.TopologicalSort(); - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); - string expectedResult = "5(9,12) 6(10,11) 3(5,8) 4(6,7) 1(1,4) 2(2,3)"; - - EXPECT_EQ(actualResult, expectedResult); - } - - // Test with a graph that has multiple nodes pointing to the same node - TEST(TopoSortTesting, MultipleIncomingEdges) - { - Graph graph; - graph.PushDirectedEdge(1, 3); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(3, 4); - - graph.TopologicalSort(); - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); - string expectedResult = "2(7,8) 1(1,6) 3(2,5) 4(3,4)"; - - EXPECT_EQ(actualResult, expectedResult); - } - - // Test for a single-node graph to check the base case - TEST(TopoSortTesting, SingleNodeGraph) - { - Graph graph; - graph.PushSingleNode(1); - - graph.TopologicalSort(); - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); - string expectedResult = "1(1,2)"; - - EXPECT_EQ(actualResult, expectedResult); - } - - TEST(TopoSortTesting, ShowTopoSortResultUsingKahnAlgorithm) - { - Graph graph; - - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(1, 4); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(4, 3); - graph.PushSingleNode(5); - graph.PushDirectedEdge(6, 7); - graph.PushDirectedEdge(6, 8); - graph.PushDirectedEdge(7, 4); - graph.PushDirectedEdge(7, 8); - graph.PushDirectedEdge(9, 8); - - graph.KahnTopologicalSort(); - - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); - string expectedResult = "1(1,5) 5(2,7) 6(3,8) 9(4,10) 2(6,11) 7(9,12) 4(13,15) 8(14,17) 3(16,18)"; - - EXPECT_EQ(actualResult, expectedResult); - } -} \ No newline at end of file diff --git a/tests/0003_Graph/0004_StronglyConnectedComponentsTest.cc b/tests/0003_Graph/0004_StronglyConnectedComponentsTest.cc deleted file mode 100644 index f8ede7f..0000000 --- a/tests/0003_Graph/0004_StronglyConnectedComponentsTest.cc +++ /dev/null @@ -1,102 +0,0 @@ -#include -#include "0004_StronglyConnectedComponents.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace StronglyConnectedComponents -{ - UnitTestHelper unitTestHelper; - - // Test case: Testing with a simple graph. - TEST(StronglyConnectedComponentsTesting, SimpleGraphTest) - { - Graph graph; - - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(1, 5); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(2, 4); - graph.PushDirectedEdge(3, 2); - graph.PushDirectedEdge(4, 4); - graph.PushDirectedEdge(5, 1); - graph.PushDirectedEdge(5, 4); - graph.PushDirectedEdge(6, 1); - graph.PushDirectedEdge(6, 3); - graph.PushDirectedEdge(6, 7); - graph.PushDirectedEdge(7, 3); - graph.PushDirectedEdge(7, 8); - graph.PushDirectedEdge(8, 6); - - auto actualResult = graph.FindAllStronglyConnectedComponents(); - vector> expectedResult = { {6, 8, 7},{1, 5},{2, 3},{4} }; - EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); - } - - // Test case: Single Node. - TEST(StronglyConnectedComponentsTesting, SingleNodeTest) - { - Graph graph; - graph.PushSingleNode(1); - - auto actualResult = graph.FindAllStronglyConnectedComponents(); - vector> expectedResult = { {1} }; - EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); - } - - // Test case: Disconnected Graph. - TEST(StronglyConnectedComponentsTesting, DisconnectedGraphTest) - { - Graph graph; - graph.PushSingleNode(1); - graph.PushSingleNode(2); - graph.PushSingleNode(3); - - auto actualResult = graph.FindAllStronglyConnectedComponents(); - vector> expectedResult = { {1},{3},{2} }; - EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); - } - - // Test case: Chain of Nodes. - TEST(StronglyConnectedComponentsTesting, ChainOfNodesTest) - { - Graph graph; - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(3, 4); - - auto actualResult = graph.FindAllStronglyConnectedComponents(); - vector> expectedResult = { {2},{1},{3},{4} }; - EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); - } - - // Test case: Bidirectional Edge. - TEST(StronglyConnectedComponentsTesting, BidirectionalEdgeTest) - { - Graph graph; - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(2, 1); - - auto actualResult = graph.FindAllStronglyConnectedComponents(); - vector> expectedResult = { {2, 1} }; - EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); - } - - // Test case: Complex Graph. - TEST(StronglyConnectedComponentsTesting, ComplexGraphTest) - { - Graph graph; - - // Graph structure with multiple SCCs and isolated nodes. - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(3, 1); // Cycle: 1 -> 2 -> 3 -> 1 - graph.PushDirectedEdge(4, 5); - graph.PushDirectedEdge(5, 6); - graph.PushDirectedEdge(6, 4); // Cycle: 4 -> 5 -> 6 -> 4 - graph.PushDirectedEdge(7, 8); // Single direction: 7 -> 8 - graph.PushSingleNode(9); // Isolated node. - - auto actualResult = graph.FindAllStronglyConnectedComponents(); - vector> expectedResult = { {4, 6, 5},{7}, { 2, 3, 1},{8}, {9} }; - EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); - } -} \ No newline at end of file diff --git a/tests/0003_Graph/0005_HamiltonianPathAndCycleTest.cc b/tests/0003_Graph/0005_HamiltonianPathAndCycleTest.cc deleted file mode 100644 index 33c351e..0000000 --- a/tests/0003_Graph/0005_HamiltonianPathAndCycleTest.cc +++ /dev/null @@ -1,33 +0,0 @@ -#include -#include "0005_HamiltonianPathAndCycle.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace HamiltonianPathAndCycle -{ - UnitTestHelper unitTestHelper; - - TEST(HamiltonianCycleAndPathTest, ShowResult) - { - Graph graph; - - graph.PushUndirectedEdge(0, 1); - graph.PushUndirectedEdge(0, 3); - graph.PushUndirectedEdge(1, 2); - graph.PushUndirectedEdge(1, 3); - graph.PushUndirectedEdge(1, 4); - graph.PushUndirectedEdge(2, 4); - graph.PushUndirectedEdge(3, 4); - - graph.FindHamiltonianCycleAndPath(); - - bool isHamiltonianCyclePresent = graph.IsHamiltonianCyclePresent(); - bool isHamiltonianPathPresent = graph.IsHamiltonianPathPresent(); - - vector hamiltonianPathActualResult = graph.GetHamiltonianPath(); - vector hamiltonianPathExpectedResult = { 4, 3, 0, 1, 2 }; - - ASSERT_TRUE(isHamiltonianCyclePresent); - ASSERT_TRUE(isHamiltonianPathPresent); - ASSERT_TRUE(unitTestHelper.NormalizeCyclesAndCompare(hamiltonianPathActualResult, hamiltonianPathExpectedResult)); - } -} \ No newline at end of file diff --git a/tests/0003_Graph/0006_EulerianPathAndCircuitTest.cc b/tests/0003_Graph/0006_EulerianPathAndCircuitTest.cc deleted file mode 100644 index a163a5c..0000000 --- a/tests/0003_Graph/0006_EulerianPathAndCircuitTest.cc +++ /dev/null @@ -1,32 +0,0 @@ -#include -#include "0006_EulerianPathAndCircuit.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace EulerianPathAndCircuit -{ - UnitTestHelper unitTestHelper; - - TEST(EulerianPathAndCycle, Test1) - { - Graph graph; - - graph.PushUndirectedEdge(1, 0); - graph.PushUndirectedEdge(0, 2); - graph.PushUndirectedEdge(2, 1); - graph.PushUndirectedEdge(0, 3); - graph.PushUndirectedEdge(3, 4); - graph.PushUndirectedEdge(4, 0); - - graph.FindEulerianPathAndCircuit(); - - bool isEulerianPathPresent = graph.IsEulerianPathPresent(); - bool isEulerianCircuitPresent = graph.IsEulerianCircuitPresent(); - - vector actualEulerianPath = graph.UndirectedGraphGetEulerianPath(); - vector expectedEulerianPath = { 0, 1, 2, 0, 3, 4, 0}; - - ASSERT_TRUE(isEulerianPathPresent); - ASSERT_TRUE(isEulerianCircuitPresent); - EXPECT_EQ(expectedEulerianPath, actualEulerianPath); - } -} \ No newline at end of file diff --git a/tests/0003_Graph/0007_MinimumSpanningTreeKruskalAlgorithmTest.cc b/tests/0003_Graph/0007_MinimumSpanningTreeKruskalAlgorithmTest.cc deleted file mode 100644 index 5736b79..0000000 --- a/tests/0003_Graph/0007_MinimumSpanningTreeKruskalAlgorithmTest.cc +++ /dev/null @@ -1,45 +0,0 @@ -#include -#include "0007_MinimumSpanningTreeKruskalAlgorithm.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace MinimumSpanningTreeKruskalAlgorithm -{ - UnitTestHelper unitTestHelper; - - TEST(MST, Kruskal) - { - Graph graph; - - graph.PushUndirectedEdge(1, 2, 4); - graph.PushUndirectedEdge(1, 8, 8); - graph.PushUndirectedEdge(2, 8, 11); - graph.PushUndirectedEdge(2, 3, 8); - graph.PushUndirectedEdge(3, 4, 7); - graph.PushUndirectedEdge(3, 9, 2); - graph.PushUndirectedEdge(3, 6, 4); - graph.PushUndirectedEdge(4, 5, 9); - graph.PushUndirectedEdge(4, 6, 14); - graph.PushUndirectedEdge(5, 6, 10); - graph.PushUndirectedEdge(6, 7, 2); - graph.PushUndirectedEdge(7, 8, 1); - graph.PushUndirectedEdge(7, 9, 6); - graph.PushUndirectedEdge(8, 9, 7); - - graph.FindMinimumSpanningTreeKruskalAlgorithm(); - - vector, int>> actualMST = graph.GetMinimumSpanningTree(); - vector, int>> expectedMST = - { - {{7, 8}, 1}, - {{3, 9}, 2}, - {{6, 7}, 2}, - {{2, 1}, 4}, - {{3, 6}, 4}, - {{3, 4}, 7}, - {{8, 1}, 8}, - {{4, 5}, 9} - }; - - ASSERT_EQ(unitTestHelper.SortVectorOfPair(actualMST), unitTestHelper.SortVectorOfPair(expectedMST)); - } -} \ No newline at end of file diff --git a/tests/0003_Graph/0008_MinimumSpanningTreePrimAlgorithmTest.cc b/tests/0003_Graph/0008_MinimumSpanningTreePrimAlgorithmTest.cc deleted file mode 100644 index 251c654..0000000 --- a/tests/0003_Graph/0008_MinimumSpanningTreePrimAlgorithmTest.cc +++ /dev/null @@ -1,45 +0,0 @@ -#include -#include "0008_MinimumSpanningTreePrimAlgorithm.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace MinimumSpanningTreePrimAlgorithm -{ - UnitTestHelper unitTestHelper; - - TEST(MST, Prim) - { - Graph graph; - - graph.PushUndirectedEdge(1, 2, 4); - graph.PushUndirectedEdge(1, 8, 8); - graph.PushUndirectedEdge(2, 8, 11); - graph.PushUndirectedEdge(2, 3, 8); - graph.PushUndirectedEdge(3, 4, 7); - graph.PushUndirectedEdge(3, 9, 2); - graph.PushUndirectedEdge(3, 6, 4); - graph.PushUndirectedEdge(4, 5, 9); - graph.PushUndirectedEdge(4, 6, 14); - graph.PushUndirectedEdge(5, 6, 10); - graph.PushUndirectedEdge(6, 7, 2); - graph.PushUndirectedEdge(7, 8, 1); - graph.PushUndirectedEdge(7, 9, 6); - graph.PushUndirectedEdge(8, 9, 7); - - graph.FindMinimumSpanningTreePrimAlgorithm(); - - vector, int>> actualMST = graph.GetMinimumSpanningTree(); - vector, int>> expectedMST = - { - {{7, 8}, 1}, - {{3, 9}, 2}, - {{6, 7}, 2}, - {{2, 1}, 4}, - {{3, 6}, 4}, - {{3, 4}, 7}, - {{8, 1}, 8}, - {{4, 5}, 9} - }; - - ASSERT_EQ(unitTestHelper.SortVectorOfPair(actualMST), unitTestHelper.SortVectorOfPair(expectedMST)); - } -} \ No newline at end of file diff --git a/tests/0003_Graph/0009_SingleSourceShortestPathBellmanFordTest.cc b/tests/0003_Graph/0009_SingleSourceShortestPathBellmanFordTest.cc deleted file mode 100644 index fc84901..0000000 --- a/tests/0003_Graph/0009_SingleSourceShortestPathBellmanFordTest.cc +++ /dev/null @@ -1,104 +0,0 @@ -#include -#include "0009_SingleSourceShortestPathBellmanFord.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace SingleSourceShortestPathBellmanFord -{ - UnitTestHelper unitTestHelper; - - // Test for Simple Graph - TEST(BellmanFordTest, SimpleTest) - { - Graph graph; - - graph.PushDirectedEdge(0, 1, 6); - graph.PushDirectedEdge(0, 3, 7); - graph.PushDirectedEdge(1, 2, 5); - graph.PushDirectedEdge(1, 3, 8); - graph.PushDirectedEdge(1, 4, -4); - graph.PushDirectedEdge(2, 1, -2); - graph.PushDirectedEdge(3, 2, -3); - graph.PushDirectedEdge(3, 4, 9); - graph.PushDirectedEdge(3, 4, 9); - graph.PushDirectedEdge(4, 2, 7); - graph.PushDirectedEdge(4, 0, 2); - - string expectedResult = "0 3 2 1 4"; - ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); - ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(4)), expectedResult); - } - - // Test for Single Node Graph - TEST(BellmanFordTest, SingleNodeTest) - { - Graph graph; - graph.PushDirectedEdge(0, 0, 0); // Self-loop - - string expectedResult = "0"; - ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); - ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(0)), expectedResult); - } - - // Test for Negative Weight Cycle - TEST(BellmanFordTest, NegativeWeightCycleTest) - { - Graph graph; - graph.PushDirectedEdge(0, 1, 1); - graph.PushDirectedEdge(1, 2, -1); - graph.PushDirectedEdge(2, 0, -1); // Negative weight cycle - - ASSERT_FALSE(graph.FindSingleSourceShortestPathBellmanFord(0)); - } - - // Test for Multiple Shortest Paths - TEST(BellmanFordTest, MultipleShortestPathsTest) - { - Graph graph; - graph.PushDirectedEdge(0, 1, 5); - graph.PushDirectedEdge(0, 2, 5); - graph.PushDirectedEdge(1, 3, 1); - graph.PushDirectedEdge(2, 3, 1); - - string expectedResult = "0 1 3"; - ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); - ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(3)), expectedResult); - } - - // Test for All Negative Weights - TEST(BellmanFordTest, AllNegativeWeightsTest) - { - Graph graph; - graph.PushDirectedEdge(0, 1, -5); - graph.PushDirectedEdge(1, 2, -3); - graph.PushDirectedEdge(2, 3, -2); - graph.PushDirectedEdge(3, 4, -1); - - string expectedResult = "0 1 2 3 4"; - ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); - ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(4)), expectedResult); - } - - // Test for Large Graph - TEST(BellmanFordTest, LargeGraphTest) - { - Graph graph; - for (int i = 0; i < 100; ++i) { - graph.PushDirectedEdge(i, i + 1, 1); - } - - string expectedResult = "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20"; - ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); - ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(20)), expectedResult); - } - - // Test for Self-Loop Edge - TEST(BellmanFordTest, SelfLoopTest) - { - Graph graph; - graph.PushDirectedEdge(0, 0, 10); // Self-loop with weight 10 - - string expectedResult = "0"; - ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); - ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(0)), expectedResult); - } -} diff --git a/tests/0003_Graph/0010_DirectedAcyclicGraphShortestPathTest.cc b/tests/0003_Graph/0010_DirectedAcyclicGraphShortestPathTest.cc deleted file mode 100644 index 50d7086..0000000 --- a/tests/0003_Graph/0010_DirectedAcyclicGraphShortestPathTest.cc +++ /dev/null @@ -1,29 +0,0 @@ -#include -#include "0010_DirectedAcyclicGraphShortestPath.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace DirectedAcyclicGraphShortestPath -{ - UnitTestHelper unitTestHelper; - - // Test for Simple Graph - TEST(DAGTest, SimpleGraph) - { - Graph graph; - - graph.PushDirectedEdge(0, 1, 5); - graph.PushDirectedEdge(0, 2, 3); - graph.PushDirectedEdge(1, 2, 2); - graph.PushDirectedEdge(1, 3, 6); - graph.PushDirectedEdge(2, 3, 7); - graph.PushDirectedEdge(2, 4, 4); - graph.PushDirectedEdge(2, 5, 2); - graph.PushDirectedEdge(3, 4, -1); - graph.PushDirectedEdge(3, 5, 1); - graph.PushDirectedEdge(4, 5, -2); - - graph.FindDAGShortestPath(1); - string expectedPath = "1 3 4 5"; - ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetDAGShortestPath(5)), expectedPath); - } -} \ No newline at end of file diff --git a/tests/0003_Graph/0011_SingleSourceShortestPathDijkstraTest.cc b/tests/0003_Graph/0011_SingleSourceShortestPathDijkstraTest.cc deleted file mode 100644 index 5460b1b..0000000 --- a/tests/0003_Graph/0011_SingleSourceShortestPathDijkstraTest.cc +++ /dev/null @@ -1,31 +0,0 @@ -#include -#include "0011_SingleSourceShortestPathDijkstra.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace SingleSourceShortestPathDijkstra -{ - UnitTestHelper unitTestHelper; - - // Test for Simple Graph - TEST(DijkstraTest, SimpleGraph) - { - Graph graph; - - graph.PushDirectedEdge(0, 1, 10); - graph.PushDirectedEdge(0, 3, 5); - graph.PushDirectedEdge(1, 2, 1); - graph.PushDirectedEdge(1, 3, 2); - graph.PushDirectedEdge(2, 4, 4); - graph.PushDirectedEdge(3, 1, 3); - graph.PushDirectedEdge(3, 2, 9); - graph.PushDirectedEdge(3, 4, 2); - graph.PushDirectedEdge(4, 2, 6); - graph.PushDirectedEdge(4, 0, 7); - - graph.FindShortestPathDijkstra(0); - - string expectedPath = "0 3 1 2"; - - ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetDijkstraShortestPath(2)), expectedPath); - } -} \ No newline at end of file diff --git a/tests/0003_Graph/0012_DifferenceConstraintsShortestPathsTest.cc b/tests/0003_Graph/0012_DifferenceConstraintsShortestPathsTest.cc deleted file mode 100644 index 152dd0d..0000000 --- a/tests/0003_Graph/0012_DifferenceConstraintsShortestPathsTest.cc +++ /dev/null @@ -1,40 +0,0 @@ -#include -#include "0012_DifferenceConstraintsShortestPaths.h" -#include"../0000_common_utilities/UnitTestHelper.h" -using namespace std; - -namespace DifferenceConstraintsShortestPaths -{ - UnitTestHelper unitTestHelper; - - TEST(DifferenceConstraints, SimpleGraph) - { - Graph graph; - - vector> vectorA = - { - {1, -1, 0, 0, 0}, - {1, 0, 0, 0, -1}, - {0, 1, 0, 0, -1}, - {-1, 0, 1, 0, 0}, - {-1, 0, 0, 1, 0}, - {0, 0, -1, 1, 0}, - {0, 0, -1, 0, 1}, - {0, 0, 0, -1, 1}, - }; - vector vectorX = { "v1", "v2", "v3", "v4", "v5" }; - vector vectorB = {0, -1, 1, 5, 4, -1, -3, -3}; - vector> expectedSolution = - { - {"v2", -3}, - {"v5", -4}, - {"v1", -5}, - {"v4", -1}, - {"v3", 0}, - }; - graph.PushAllDirectedEdges(vectorA, vectorX, vectorB); - - ASSERT_TRUE(graph.FindDifferenceConstraintsSolutionBellmanFord()); - ASSERT_EQ(unitTestHelper.SortVectorOfPairAndSerialize(graph.GetDifferenceConstrtaintsSolution()), unitTestHelper.SortVectorOfPairAndSerialize(expectedSolution)); - } -} \ No newline at end of file diff --git a/tests/0003_Graph/0013_AllPairsShortestPathsFloydWarshallTest.cc b/tests/0003_Graph/0013_AllPairsShortestPathsFloydWarshallTest.cc deleted file mode 100644 index 17a5045..0000000 --- a/tests/0003_Graph/0013_AllPairsShortestPathsFloydWarshallTest.cc +++ /dev/null @@ -1,36 +0,0 @@ -#include -#include "0013_AllPairsShortestPathsFloydWarshall.h" -#include "../0000_common_utilities/UnitTestHelper.h" -using namespace std; - -namespace AllPairsShortestPathsFloydWarshall -{ - UnitTestHelper unitTestHelper; - - TEST(FloydWarshall, SimpleGraph) - { - // Arrange - Graph graph; - int noOfVertices = 5; - string expectedResult = "[1 5 4 3 2][1 5 4 3][1 5 4][1 5][2 4 1][2 4 3][2 4][2 4 1 5][3 2 4 1][3 2][3 2 4][3 2 4 1 5][4 1][4 3 2][4 3][4 1 5][5 4 1][5 4 3 2][5 4 3][5 4]"; - - // Act - graph.CreateGraph(noOfVertices); - - graph.PushDirectedEdge(1, 2, 3); - graph.PushDirectedEdge(1, 3, 8); - graph.PushDirectedEdge(1, 5, -4); - graph.PushDirectedEdge(2, 4, 1); - graph.PushDirectedEdge(2, 5, 7); - graph.PushDirectedEdge(3, 2, 4); - graph.PushDirectedEdge(4, 3, -5); - graph.PushDirectedEdge(4, 1, 2); - graph.PushDirectedEdge(5, 4, 6); - - graph.FindAllPairsShortestPathsFloydWarshallSolution(); - string actualResult = unitTestHelper.SerializeVectorToString(graph.GetFloydWarshallShortestPath()); - - // Assert - ASSERT_EQ(actualResult, expectedResult); - } -} \ No newline at end of file diff --git a/tests/0003_Graph/0014_AllPairsShortestPathsJohnsonTest.cc b/tests/0003_Graph/0014_AllPairsShortestPathsJohnsonTest.cc deleted file mode 100644 index 66a63a1..0000000 --- a/tests/0003_Graph/0014_AllPairsShortestPathsJohnsonTest.cc +++ /dev/null @@ -1,44 +0,0 @@ -#include -#include "0014_AllPairsShortestPathsJohnson.h" -#include"../0000_common_utilities/UnitTestHelper.h" -using namespace std; - -namespace AllPairsShortestPathsJohnson -{ - UnitTestHelper unitTestHelper; - - TEST(JohnsonAlgorithm, SimpleGraph) - { - // Arrange - Graph graph; - vector> expectedDistanceMatrix = - { - {0, 1, -3, 2, -4}, - {3, 0, -4, 1, -1}, - {7, 4, 0, 5, 3}, - {2, -1, -5, 0, -2}, - {8, 5, 1, 6, 0}, - }; - string expectedPredecessorMatrixesult = "[1 5 4 3 2][1 5 4 3][1 5 4][1 5][2 4 1][2 4 3][2 4][2 4 1 5][3 2 4 1][3 2][3 2 4][3 2 4 1 5][4 1][4 3 2][4 3][4 1 5][5 4 1][5 4 3 2][5 4 3][5 4]"; - - // Act - graph.PushDirectedEdge(1, 2, 3); - graph.PushDirectedEdge(1, 3, 8); - graph.PushDirectedEdge(1, 5, -4); - graph.PushDirectedEdge(2, 4, 1); - graph.PushDirectedEdge(2, 5, 7); - graph.PushDirectedEdge(3, 2, 4); - graph.PushDirectedEdge(4, 3, -5); - graph.PushDirectedEdge(4, 1, 2); - graph.PushDirectedEdge(5, 4, 6); - - bool result = graph.FindAllPairsShortestPathsJohnsonAlgorithm(); - vector> actualDistanceMatrix = graph.GetAllPairsShortestPathsDistanceMatrix(); - string actualPredecessorMatrix = unitTestHelper.SerializeVectorToString(graph.GetAllPairsShortestPathsPathMatrix()); - - // Assert - ASSERT_TRUE(result); - ASSERT_EQ(expectedDistanceMatrix, actualDistanceMatrix); - ASSERT_EQ(expectedPredecessorMatrixesult, actualPredecessorMatrix); - } -} \ No newline at end of file diff --git a/tests/0003_Graph/0015_MaximumFlowFordFulkersonTest.cc b/tests/0003_Graph/0015_MaximumFlowFordFulkersonTest.cc deleted file mode 100644 index 117bfc2..0000000 --- a/tests/0003_Graph/0015_MaximumFlowFordFulkersonTest.cc +++ /dev/null @@ -1,64 +0,0 @@ -#include -#include "0015_MaximumFlowFordFulkerson.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace MaximumFlowFordFulkerson -{ - UnitTestHelper unitTestHelper; - - TEST(MaximumFlowFordFulkerson, GraphWithNoParallelEdges) - { - // Arrange - Graph graph; - int noOfVertices = 6; - int expectedMaximumFlow = 23; - - - // Act - graph.CreateGraph(noOfVertices); - - graph.PushDirectedEdge(0, 1, 16); - graph.PushDirectedEdge(0, 2, 13); - graph.PushDirectedEdge(1, 3, 12); - graph.PushDirectedEdge(2, 1, 4); - graph.PushDirectedEdge(2, 4, 14); - graph.PushDirectedEdge(3, 2, 9); - graph.PushDirectedEdge(3, 5, 20); - graph.PushDirectedEdge(4, 3, 7); - graph.PushDirectedEdge(4, 5, 4); - - int actualMaximumFlow = graph.FindMaximumFlowFordFulkerson(); - - // Assert - ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); - } - - TEST(MaximumFlowFordFulkerson, GraphWithParallelEdges) - { - // Arrange - Graph graph; - int noOfVertices = 6; - int expectedMaximumFlow = 24; - - - // Act - graph.CreateGraph(noOfVertices); - - graph.PushDirectedEdge(0, 1, 16); - graph.PushDirectedEdge(0, 2, 13); - graph.PushDirectedEdge(1, 3, 12); - graph.PushDirectedEdge(1, 2, 6); - graph.PushDirectedEdge(2, 1, 10); - graph.PushDirectedEdge(2, 4, 14); - graph.PushDirectedEdge(2, 3, 2); - graph.PushDirectedEdge(3, 2, 11); - graph.PushDirectedEdge(3, 5, 20); - graph.PushDirectedEdge(4, 3, 7); - graph.PushDirectedEdge(4, 5, 4); - - int actualMaximumFlow = graph.FindMaximumFlowFordFulkerson(); - - // Assert - ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); - } -} \ No newline at end of file diff --git a/tests/0003_Graph/0016_MaximumFlowEdmondsKarpTest.cc b/tests/0003_Graph/0016_MaximumFlowEdmondsKarpTest.cc deleted file mode 100644 index 5d3177a..0000000 --- a/tests/0003_Graph/0016_MaximumFlowEdmondsKarpTest.cc +++ /dev/null @@ -1,64 +0,0 @@ -#include -#include "0016_MaximumFlowEdmondsKarp.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace MaximumFlowEdmondsKarp -{ - UnitTestHelper unitTestHelper; - - TEST(MaximumFlowEdmondsKarp, GraphWithNoParallelEdges) - { - // Arrange - Graph graph; - int noOfVertices = 6; - int expectedMaximumFlow = 23; - - - // Act - graph.CreateGraph(noOfVertices); - - graph.PushDirectedEdge(0, 1, 16); - graph.PushDirectedEdge(0, 2, 13); - graph.PushDirectedEdge(1, 3, 12); - graph.PushDirectedEdge(2, 1, 4); - graph.PushDirectedEdge(2, 4, 14); - graph.PushDirectedEdge(3, 2, 9); - graph.PushDirectedEdge(3, 5, 20); - graph.PushDirectedEdge(4, 3, 7); - graph.PushDirectedEdge(4, 5, 4); - - int actualMaximumFlow = graph.FindMaximumFlowEdmondsKarp(); - - // Assert - ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); - } - - TEST(MaximumFlowEdmondsKarp, GraphWithParallelEdges) - { - // Arrange - Graph graph; - int noOfVertices = 6; - int expectedMaximumFlow = 24; - - - // Act - graph.CreateGraph(noOfVertices); - - graph.PushDirectedEdge(0, 1, 16); - graph.PushDirectedEdge(0, 2, 13); - graph.PushDirectedEdge(1, 3, 12); - graph.PushDirectedEdge(1, 2, 6); - graph.PushDirectedEdge(2, 1, 10); - graph.PushDirectedEdge(2, 4, 14); - graph.PushDirectedEdge(2, 3, 2); - graph.PushDirectedEdge(3, 2, 11); - graph.PushDirectedEdge(3, 5, 20); - graph.PushDirectedEdge(4, 3, 7); - graph.PushDirectedEdge(4, 5, 4); - - int actualMaximumFlow = graph.FindMaximumFlowEdmondsKarp(); - - // Assert - ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); - } -} \ No newline at end of file diff --git a/tests/0003_Graph/0017_MaximumBipartiteMatchingTest.cc b/tests/0003_Graph/0017_MaximumBipartiteMatchingTest.cc deleted file mode 100644 index d556e28..0000000 --- a/tests/0003_Graph/0017_MaximumBipartiteMatchingTest.cc +++ /dev/null @@ -1,35 +0,0 @@ -#include -#include "0017_MaximumBipartiteMatching.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace MaximumBipartiteMatching -{ - TEST(MaximumBipartiteMatching, SimpleGraph) - { - // Arrange - Graph graph; - UnitTestHelper unitTestHelper; - int noOfVertices = 9; - int expectedMaximumMatching = 3; - string expectedMatchings = "[0 1][2 6][3 5]"; - - // Act - graph.CreateGraph(noOfVertices); - - graph.PushDirectedEdge(0, 1); - graph.PushDirectedEdge(2, 1); - graph.PushDirectedEdge(2, 6); - graph.PushDirectedEdge(3, 5); - graph.PushDirectedEdge(3, 6); - graph.PushDirectedEdge(3, 7); - graph.PushDirectedEdge(4, 6); - graph.PushDirectedEdge(8, 6); - - int actualMaximumMatching = graph.FindMaximumBipartiteMatching(); - vector> actualMatchings = graph.GetMatchings(); - - // Assert - ASSERT_EQ(expectedMaximumMatching, actualMaximumMatching); - ASSERT_EQ(expectedMatchings, unitTestHelper.SerializeVectorToString(actualMatchings)); - } -} \ No newline at end of file diff --git a/tests/0003_Graph/0018_MaximumFlowGoldbergGenericPushRelabelTest.cc b/tests/0003_Graph/0018_MaximumFlowGoldbergGenericPushRelabelTest.cc deleted file mode 100644 index 283cab0..0000000 --- a/tests/0003_Graph/0018_MaximumFlowGoldbergGenericPushRelabelTest.cc +++ /dev/null @@ -1,35 +0,0 @@ -#include -#include "0018_MaximumFlowGoldbergGenericPushRelabel.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace MaximumFlowGoldbergGenericPushRelabel -{ - UnitTestHelper unitTestHelper; - - TEST(MaximumFlowGoldbergGenericPushRelabel, GraphWithNoParallelEdges) - { - // Arrange - Graph graph; - int noOfVertices = 6; - int expectedMaximumFlow = 23; - - - // Act - graph.CreateGraph(noOfVertices); - - graph.PushDirectedEdge(0, 1, 16); - graph.PushDirectedEdge(0, 2, 13); - graph.PushDirectedEdge(1, 3, 12); - graph.PushDirectedEdge(2, 1, 4); - graph.PushDirectedEdge(2, 4, 14); - graph.PushDirectedEdge(3, 2, 9); - graph.PushDirectedEdge(3, 5, 20); - graph.PushDirectedEdge(4, 3, 7); - graph.PushDirectedEdge(4, 5, 4); - - int actualMaximumFlow = graph.FindMaximumFlowGoldbergGenericPushRelabel(); - - // Assert - ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); - } -} \ No newline at end of file diff --git a/tests/0003_Graph/0019_MaximumFlowRelabelToFrontTest.cc b/tests/0003_Graph/0019_MaximumFlowRelabelToFrontTest.cc deleted file mode 100644 index a73b89d..0000000 --- a/tests/0003_Graph/0019_MaximumFlowRelabelToFrontTest.cc +++ /dev/null @@ -1,36 +0,0 @@ -#include -#include "0019_MaximumFlowRelabelToFront.h" -#include "../0000_common_utilities/UnitTestHelper.h" -using namespace std; - -namespace MaximumFlowRelabelToFront -{ - UnitTestHelper unitTestHelper; - - TEST(MaximumFlowRelabelToFront, SimpleGraph) - { - // Arrange - Graph graph; - int noOfVertices = 6; - int expectedMaximumFlow = 23; - - - // Act - graph.CreateGraph(noOfVertices); - - graph.PushDirectedEdge(0, 1, 16); - graph.PushDirectedEdge(0, 2, 13); - graph.PushDirectedEdge(1, 3, 12); - graph.PushDirectedEdge(2, 1, 4); - graph.PushDirectedEdge(2, 4, 14); - graph.PushDirectedEdge(3, 2, 9); - graph.PushDirectedEdge(3, 5, 20); - graph.PushDirectedEdge(4, 3, 7); - graph.PushDirectedEdge(4, 5, 4); - - int actualMaximumFlow = graph.FindMaximumFlowRelabelToFront(); - - // Assert - ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); - } -} \ No newline at end of file diff --git a/tests/0003_Graph/CMakeLists.txt b/tests/0003_Graph/CMakeLists.txt deleted file mode 100644 index 275d4a8..0000000 --- a/tests/0003_Graph/CMakeLists.txt +++ /dev/null @@ -1,50 +0,0 @@ -cmake_policy(SET CMP0135 NEW) - -include(FetchContent) -FetchContent_Declare( - googletest - URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip -) - -# For Windows: Prevent overriding the parent project's compiler/linker settings -set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) -FetchContent_MakeAvailable(googletest) - -enable_testing() - -add_executable( - 0003GraphTests - 0001_BreadthFirstSearchTest.cc - 0002_DepthFirstSearchTest.cc - 0003_TopologicalSortTest.cc - 0004_StronglyConnectedComponentsTest.cc - 0005_HamiltonianPathAndCycleTest.cc - 0006_EulerianPathAndCircuitTest.cc - 0007_MinimumSpanningTreeKruskalAlgorithmTest.cc - 0008_MinimumSpanningTreePrimAlgorithmTest.cc - 0009_SingleSourceShortestPathBellmanFordTest.cc - 0010_DirectedAcyclicGraphShortestPathTest.cc - 0011_SingleSourceShortestPathDijkstraTest.cc - 0012_DifferenceConstraintsShortestPathsTest.cc - 0013_AllPairsShortestPathsFloydWarshallTest.cc - 0014_AllPairsShortestPathsJohnsonTest.cc - 0015_MaximumFlowFordFulkersonTest.cc - 0016_MaximumFlowEdmondsKarpTest.cc - 0017_MaximumBipartiteMatchingTest.cc - 0018_MaximumFlowGoldbergGenericPushRelabelTest.cc - 0019_MaximumFlowRelabelToFrontTest.cc -) - -target_link_libraries( - 0003GraphTests - GTest::gtest_main - 0003GRAPH -) - -# Add .clang-tidy configuration to this library. -if(CLANG_TIDY_EXE) - set_target_properties(0003GRAPH PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") -endif() - -include(GoogleTest) -gtest_discover_tests(0003GraphTests DISCOVERY_TIMEOUT 30) \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0001_FibonacciNumberTest.cc b/tests/0004_dynamic_programming/0001_FibonacciNumberTest.cc deleted file mode 100644 index 1fdd9a4..0000000 --- a/tests/0004_dynamic_programming/0001_FibonacciNumberTest.cc +++ /dev/null @@ -1,34 +0,0 @@ -#include -#include "0001_FibonacciNumber.h" -using namespace std; - -namespace FibonacciNumber -{ - TEST(FibonacciNumber, RecursiveTest) - { - // Arrange - DynamicProgramming dp; - int n = 5; - int expectedFib = 5; - - // Act - int actualFib = dp.RecursiveNthFibonacci(n); - - // Assert - ASSERT_EQ(expectedFib, actualFib); - } - - TEST(FibonacciNumber, DpTest) - { - // Arrange - DynamicProgramming dp; - int n = 5; - int expectedFib = 5; - - // Act - int actualFib = dp.DpNthFibonacci(n); - - // Assert - ASSERT_EQ(expectedFib, actualFib); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0002_TribonacciNumberTest.cc b/tests/0004_dynamic_programming/0002_TribonacciNumberTest.cc deleted file mode 100644 index d25c394..0000000 --- a/tests/0004_dynamic_programming/0002_TribonacciNumberTest.cc +++ /dev/null @@ -1,34 +0,0 @@ -#include -#include "0002_TribonacciNumber.h" -using namespace std; - -namespace TribonacciNumber -{ - TEST(TribonacciNumber, RecursiveTest) - { - // Arrange - DynamicProgramming dp; - int n = 5; - int expectedFib = 2; - - // Act - int actualFib = dp.RecursiveNthTribonacci(n); - - // Assert - ASSERT_EQ(expectedFib, actualFib); - } - - TEST(TribonacciNumber, DpTest) - { - // Arrange - DynamicProgramming dp; - int n = 10; - int expectedFib = 44; - - // Act - int actualFib = dp.DpNthTribonacci(n); - - // Assert - ASSERT_EQ(expectedFib, actualFib); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0003_ClimbingStairsTest.cc b/tests/0004_dynamic_programming/0003_ClimbingStairsTest.cc deleted file mode 100644 index 0504cbc..0000000 --- a/tests/0004_dynamic_programming/0003_ClimbingStairsTest.cc +++ /dev/null @@ -1,33 +0,0 @@ -#include -#include "0003_ClimbingStairs.h" - -namespace ClimbingStairs -{ - TEST(ClimbingStairs, RecursiveTest) - { - // Arrange - DynamicProgramming dp; - int n = 4; - int expectedCount = 5; - - // Act - int actualCount = dp.RecursiveCountWays(n); - - // Assert - ASSERT_EQ(expectedCount, actualCount); - } - - TEST(ClimbingStairs, DpTest) - { - // Arrange - DynamicProgramming dp; - int n = 4; - int expectedCount = 5; - - // Act - int actualCount = dp.DpCountWays(n); - - // Assert - ASSERT_EQ(expectedCount, actualCount); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0004_MinimumCostClimbingStairsTest.cc b/tests/0004_dynamic_programming/0004_MinimumCostClimbingStairsTest.cc deleted file mode 100644 index b488105..0000000 --- a/tests/0004_dynamic_programming/0004_MinimumCostClimbingStairsTest.cc +++ /dev/null @@ -1,33 +0,0 @@ -#include -#include "0004_MinimumCostClimbingStairs.h" - -namespace MinimumCostClimbingStairs -{ - TEST(MinimumCostClimbingStairs, RecursionTest) - { - // Arrange - DynamicProgramming dp; - vector cost = { 16, 19, 10, 12, 18 }; - int expectedCost = 31; - - // Act - int actualCost = dp.RecursiveMinimumCostClimbingStairs(cost); - - // Assert - ASSERT_EQ(expectedCost, actualCost); - } - - TEST(MinimumCostClimbingStairs, DpTest) - { - // Arrange - DynamicProgramming dp; - vector cost = { 16, 19, 10, 12, 18 }; - int expectedCost = 31; - - // Act - int actualCost = dp.DpMinimumCostClimbingStairs(cost); - - // Assert - ASSERT_EQ(expectedCost, actualCost); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0005_HouseRobber1Test.cc b/tests/0004_dynamic_programming/0005_HouseRobber1Test.cc deleted file mode 100644 index d3f6312..0000000 --- a/tests/0004_dynamic_programming/0005_HouseRobber1Test.cc +++ /dev/null @@ -1,33 +0,0 @@ -#include -#include "0005_HouseRobber1.h" - -namespace HouseRobber1 -{ - TEST(HouseRobber1, RecursionTest) - { - // Arrange - DynamicProgramming dp; - vector houseValues = { 6, 7, 1, 3, 8, 2, 4 }; - int expectedMaximumLoot = 19; - - // Act - int actualMaximumLoot = dp.RecursiveMaximumLoot(houseValues); - - // Assert - ASSERT_EQ(expectedMaximumLoot, actualMaximumLoot); - } - - TEST(HouseRobber1, DpTest) - { - // Arrange - DynamicProgramming dp; - vector houseValues = { 6, 7, 1, 3, 8, 2, 4 }; - int expectedMaximumLoot = 19; - - // Act - int actualMaximumLoot = dp.DpMaximumLoot(houseValues); - - // Assert - ASSERT_EQ(expectedMaximumLoot, actualMaximumLoot); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0006_HouseRobber2Test.cc b/tests/0004_dynamic_programming/0006_HouseRobber2Test.cc deleted file mode 100644 index e37c346..0000000 --- a/tests/0004_dynamic_programming/0006_HouseRobber2Test.cc +++ /dev/null @@ -1,48 +0,0 @@ -#include -#include "0006_HouseRobber2.h" - -namespace HouseRobber2 -{ - TEST(HouseRobber2, RecursionTest01) - { - // Arrange - DynamicProgramming dp; - vector houseValues = { 2, 2, 3, 1, 2 }; - int expectedMaximumLoot = 5; - - // Act - int actualMaximumLoot = dp.RecursiveMaximumLoot(houseValues); - - // Assert - ASSERT_EQ(expectedMaximumLoot, actualMaximumLoot); - } - - TEST(HouseRobber2, DpTest01) - { - // Arrange - DynamicProgramming dp; - vector houseValues = { 2, 2, 3, 1, 2 }; - int expectedMaximumLoot = 5; - - // Act - int actualMaximumLoot = dp.DpMaximumLoot(houseValues); - - // Assert - ASSERT_EQ(expectedMaximumLoot, actualMaximumLoot); - } - - TEST(HouseRobber2, DpTest02) - { - // Arrange - DynamicProgramming dp; - vector houseValues = { 9, 1, 8, 2 }; - int expectedMaximumLoot = 17; - - // Act - int actualMaximumLoot = dp.DpMaximumLoot(houseValues); - - // Assert - ASSERT_EQ(expectedMaximumLoot, actualMaximumLoot); - } - -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0007_DecodeWaysTest.cc b/tests/0004_dynamic_programming/0007_DecodeWaysTest.cc deleted file mode 100644 index cf81a98..0000000 --- a/tests/0004_dynamic_programming/0007_DecodeWaysTest.cc +++ /dev/null @@ -1,47 +0,0 @@ -#include -#include "0007_DecodeWays.h" - -namespace DecodeWays -{ - TEST(DecodeWays, RecursionTest01) - { - // Arrange - DynamicProgramming dp; - string digits = "121"; - int expectedWaysCount = 3; - - // Act - int actualWaysCount = dp.RecursiveCountWays(digits); - - // Assert - ASSERT_EQ(expectedWaysCount, actualWaysCount); - } - - TEST(DecodeWays, DpTest01) - { - // Arrange - DynamicProgramming dp; - string digits = "121"; - int expectedWaysCount = 3; - - // Act - int actualWaysCount = dp.DpCountways(digits); - - // Assert - ASSERT_EQ(expectedWaysCount, actualWaysCount); - } - - TEST(DecodeWays, DpTestInvalidInput) - { - // Arrange - DynamicProgramming dp; - string digits = "230"; - int expectedWaysCount = 0; - - // Act - int actualWaysCount = dp.DpCountways(digits); - - // Assert - ASSERT_EQ(expectedWaysCount, actualWaysCount); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0008_TilingProblemTest.cc b/tests/0004_dynamic_programming/0008_TilingProblemTest.cc deleted file mode 100644 index bbcbb79..0000000 --- a/tests/0004_dynamic_programming/0008_TilingProblemTest.cc +++ /dev/null @@ -1,33 +0,0 @@ -#include -#include "0008_TilingProblem.h" - -namespace TilingProblem -{ - TEST(TilingProblem, RecursionTest01) - { - // Arrange - DynamicProgramming dp; - int nummberOfRows = 4; - int expectedNumberOfWays = 5; - - // Act - int actualNumberOfWays = dp.RecursiveNumberOfWays(nummberOfRows); - - // Assert - ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); - } - - TEST(TilingProblem, DpTest01) - { - // Arrange - DynamicProgramming dp; - int nummberOfRows = 4; - int expectedNumberOfWays = 5; - - // Act - int actualNumberOfWays = dp.DpNumberOfWays(nummberOfRows); - - // Assert - ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0009_FriendsPairingProblemTest.cc b/tests/0004_dynamic_programming/0009_FriendsPairingProblemTest.cc deleted file mode 100644 index 11376ac..0000000 --- a/tests/0004_dynamic_programming/0009_FriendsPairingProblemTest.cc +++ /dev/null @@ -1,91 +0,0 @@ -#include -#include "0009_FriendsPairingProblem.h" - -namespace FriendsPairingProblem -{ - TEST(FriendsPairingProblemDynamicProgrammingTest, RecursiveCountFriendsPairingsTest1) - { - // Arrange - DynamicProgramming dp; - int numberOfFriends = 3; - int expectedPairings = 4; - - // Act - int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); - - // Assert - ASSERT_EQ(expectedPairings, actualPairings); - EXPECT_EQ(dp.RecursiveCountFriendsPairings(4), 10); - EXPECT_EQ(dp.RecursiveCountFriendsPairings(5), 26); - } - - TEST(FriendsPairingProblemDynamicProgrammingTest, RecursiveCountFriendsPairingsTest2) - { - // Arrange - DynamicProgramming dp; - int numberOfFriends = 4; - int expectedPairings = 10; - - // Act - int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); - - // Assert - ASSERT_EQ(expectedPairings, actualPairings); - } - - TEST(FriendsPairingProblemDynamicProgrammingTest, RecursiveCountFriendsPairingsTest3) - { - // Arrange - DynamicProgramming dp; - int numberOfFriends = 5; - int expectedPairings = 26; - - // Act - int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); - - // Assert - ASSERT_EQ(expectedPairings, actualPairings); - } - - TEST(FriendsPairingProblemDynamicProgrammingTest, DpCountFriendsPairingsTest1) - { - // Arrange - DynamicProgramming dp; - int numberOfFriends = 3; - int expectedPairings = 4; - - // Act - int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); - - // Assert - ASSERT_EQ(expectedPairings, actualPairings); - } - - TEST(FriendsPairingProblemDynamicProgrammingTest, DpCountFriendsPairingsTest2) - { - // Arrange - DynamicProgramming dp; - int numberOfFriends = 4; - int expectedPairings = 10; - - // Act - int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); - - // Assert - ASSERT_EQ(expectedPairings, actualPairings); - } - - TEST(FriendsPairingProblemDynamicProgrammingTest, DpCountFriendsPairingsTest3) - { - // Arrange - DynamicProgramming dp; - int numberOfFriends = 5; - int expectedPairings = 26; - - // Act - int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); - - // Assert - ASSERT_EQ(expectedPairings, actualPairings); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0010_WaysToCoverDistanceTest.cc b/tests/0004_dynamic_programming/0010_WaysToCoverDistanceTest.cc deleted file mode 100644 index 7e7f0c9..0000000 --- a/tests/0004_dynamic_programming/0010_WaysToCoverDistanceTest.cc +++ /dev/null @@ -1,117 +0,0 @@ -#include -#include "0010_WaysToCoverDistance.h" - -namespace WaysToCoverDistance -{ - TEST(WaysToCoverDistanceTest, RecursiveWaysToCoverDistance1) - { - // Arrange - DynamicProgramming dp; - int distance = 3; - int expectedNumberOfWaysToCoverDistance = 4; - - // Act - int actualNumberOfWaysToCoverDistance = dp.RecursiveWaysToCoverDistance(distance); - - // Assert - ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); - } - - TEST(WaysToCoverDistanceTest, RecursiveWaysToCoverDistance2) - { - // Arrange - DynamicProgramming dp; - int distance = 4; - int expectedNumberOfWaysToCoverDistance = 7; - - // Act - int actualNumberOfWaysToCoverDistance = dp.RecursiveWaysToCoverDistance(distance); - - // Assert - ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); - } - - TEST(WaysToCoverDistanceTest, RecursiveWaysToCoverDistanc3) - { - // Arrange - DynamicProgramming dp; - int distance = 5; - int expectedNumberOfWaysToCoverDistance = 13; - - // Act - int actualNumberOfWaysToCoverDistance = dp.RecursiveWaysToCoverDistance(distance); - - // Assert - ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); - } - - TEST(WaysToCoverDistanceTest, RecursiveWaysToCoverDistanc4) - { - // Arrange - DynamicProgramming dp; - int distance = 6; - int expectedNumberOfWaysToCoverDistance = 24; - - // Act - int actualNumberOfWaysToCoverDistance = dp.RecursiveWaysToCoverDistance(distance); - - // Assert - ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); - } - - TEST(WaysToCoverDistanceTest, DpWaysToCoverDistance1) - { - // Arrange - DynamicProgramming dp; - int distance = 3; - int expectedNumberOfWaysToCoverDistance = 4; - - // Act - int actualNumberOfWaysToCoverDistance = dp.DpWaysToCoverDistance(distance); - - // Assert - ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); - } - - TEST(WaysToCoverDistanceTest, DpWaysToCoverDistance2) - { - // Arrange - DynamicProgramming dp; - int distance = 4; - int expectedNumberOfWaysToCoverDistance = 7; - - // Act - int actualNumberOfWaysToCoverDistance = dp.DpWaysToCoverDistance(distance); - - // Assert - ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); - } - - TEST(WaysToCoverDistanceTest, DpWaysToCoverDistance3) - { - // Arrange - DynamicProgramming dp; - int distance = 5; - int expectedNumberOfWaysToCoverDistance = 13; - - // Act - int actualNumberOfWaysToCoverDistance = dp.DpWaysToCoverDistance(distance); - - // Assert - ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); - } - - TEST(WaysToCoverDistanceTest, DpWaysToCoverDistance4) - { - // Arrange - DynamicProgramming dp; - int distance = 6; - int expectedNumberOfWaysToCoverDistance = 24; - - // Act - int actualNumberOfWaysToCoverDistance = dp.DpWaysToCoverDistance(distance); - - // Assert - ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrderTest.cc b/tests/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrderTest.cc deleted file mode 100644 index 8a9830c..0000000 --- a/tests/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrderTest.cc +++ /dev/null @@ -1,33 +0,0 @@ -#include -#include "0011_CountWaysToReachNthStairIncludeOrder.h" - -namespace CountWaysToReachNthStairIncludeOrder -{ - TEST(CountWaysToReachNthStairIncludeOrderTest, RecursiveCountWaysToReachNthStairIncludeOrder1) - { - // Arrange - DynamicProgramming dp; - int n = 4; - int expectedNumberOfWays = 5; - - // Act - int actualNumberOfWays = dp.RecursiveCountWaysToReachNthStairIncludeOrder(n); - - // Assert - ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); - } - - TEST(CountWaysToReachNthStairIncludeOrderTest, DpCountWaysToReachNthStairIncludeOrder1) - { - // Arrange - DynamicProgramming dp; - int n = 4; - int expectedNumberOfWays = 5; - - // Act - int actualNumberOfWays = dp.DpCountWaysToReachNthStairIncludeOrder(n); - - // Assert - ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrderTest.cc b/tests/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrderTest.cc deleted file mode 100644 index 2a67ce3..0000000 --- a/tests/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrderTest.cc +++ /dev/null @@ -1,33 +0,0 @@ -#include -#include "0012_CountWaysToReachNthStairExcludeOrder.h" - -namespace CountWaysToReachNthStairExcludeOrder -{ - TEST(CountWaysToReachNthStairExcludeOrderTest, RecursiveCountWaysToReachNthStairExcludeOrder1) - { - // Arrange - DynamicProgramming dp; - int n = 4; - int expectedNumberOfWays = 3; - - // Act - int actualNumberOfWays = dp.RecursiveCountWaysToReachNthStairExcludeOrder(n); - - // Assert - ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); - } - - TEST(CountWaysToReachNthStairExcludeOrderTest, DpCountWaysToReachNthStairExcludeOrder1) - { - // Arrange - DynamicProgramming dp; - int n = 4; - int expectedNumberOfWays = 3; - - // Act - int actualNumberOfWays = dp.DpCountWaysToReachNthStairExcludeOrder(n); - - // Assert - ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0013_KnapsackProblemTest.cc b/tests/0004_dynamic_programming/0013_KnapsackProblemTest.cc deleted file mode 100644 index 94d3e84..0000000 --- a/tests/0004_dynamic_programming/0013_KnapsackProblemTest.cc +++ /dev/null @@ -1,53 +0,0 @@ -#include -#include "0013_KnapsackProblem.h" - -namespace KnapsackProblem -{ - TEST(KnapsackProblemTest, RecursiveKnapsackProblemTest01) - { - // Arrange - DynamicProgramming dp; - int capacity = 4; - vector weight = { 4,5,1 }; - vector profit = { 1,2,3 }; - int expectedMaximumProfit = 3; - - // Act - int actualMaximumProfit = dp.RecursiveKnapsack(capacity, weight, profit); - - // Assert - ASSERT_EQ(expectedMaximumProfit, actualMaximumProfit); - } - - TEST(KnapsackProblemTest, DpKnapsackProblemTest01) - { - // Arrange - DynamicProgramming dp; - int capacity = 4; - vector weight = { 4,5,1 }; - vector profit = { 1,2,3 }; - int expectedMaximumProfit = 3; - - // Act - int actualMaximumProfit = dp.DpKnapsack(capacity, weight, profit); - - // Assert - ASSERT_EQ(expectedMaximumProfit, actualMaximumProfit); - } - - TEST(KnapsackProblemTest, DpKnapsackProblemTest02) - { - // Arrange - DynamicProgramming dp; - int capacity = 4; - vector weight = { 4,5,1 }; - vector profit = { 1,2,3 }; - int expectedMaximumProfit = 3; - - // Act - int actualMaximumProfit = dp.DpKnapsackSpaceOptimized(capacity, weight, profit); - - // Assert - ASSERT_EQ(expectedMaximumProfit, actualMaximumProfit); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0014_SubsetSumProblemTest.cc b/tests/0004_dynamic_programming/0014_SubsetSumProblemTest.cc deleted file mode 100644 index aeee852..0000000 --- a/tests/0004_dynamic_programming/0014_SubsetSumProblemTest.cc +++ /dev/null @@ -1,35 +0,0 @@ -#include -#include "0014_SubsetSumProblem.h" - -namespace SubsetSumProblem -{ - TEST(SubsetSumProblemTest, RecursiveSubsetSumTest) - { - // Arrange - DynamicProgramming dp; - vector nums = { 3, 34, 4, 12, 5, 2 }; - int sum = 9; - bool expectedResult = true; - - // Act - bool actualResult = dp.RecursiveSubsetSum(nums, sum); - - // Assert - ASSERT_EQ(expectedResult, actualResult); - } - - TEST(SubsetSumProblemTest, DpSubsetSumTest) - { - // Arrange - DynamicProgramming dp; - vector nums = { 3, 34, 4, 12, 5, 2 }; - int sum = 9; - bool expectedResult = true; - - // Act - bool actualResult = dp.DpIsSubsetSum(nums, sum); - - // Assert - ASSERT_EQ(expectedResult, actualResult); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0015_CountSubsetsForSumTest.cc b/tests/0004_dynamic_programming/0015_CountSubsetsForSumTest.cc deleted file mode 100644 index ba1fa7f..0000000 --- a/tests/0004_dynamic_programming/0015_CountSubsetsForSumTest.cc +++ /dev/null @@ -1,35 +0,0 @@ -#include -#include"0015_CountSubsetsForSum.h" - -namespace CountSubsetsForSum -{ - TEST(CountSubsetsForSum, RecursiveCountSubsetSum) - { - // Arrange - DynamicProgramming dp; - vector nums = { 1, 2, 3, 3 }; - int sum = 6; - int expectedCount = 3; - - // Act - int actualCount = dp.RecursiveCountSubsets(nums, sum); - - // Assert - ASSERT_EQ(expectedCount, actualCount); - } - - TEST(CountSubsetsForSum, DpCountSubsetSum) - { - // Arrange - DynamicProgramming dp; - vector nums = { 1, 2, 3, 3 }; - int sum = 6; - int expectedCount = 3; - - // Act - int actualCount = dp.DpCountSubsets(nums, sum); - - // Assert - ASSERT_EQ(expectedCount, actualCount); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0016_PartitionEqualSubsetSumTest.cc b/tests/0004_dynamic_programming/0016_PartitionEqualSubsetSumTest.cc deleted file mode 100644 index 2bfa292..0000000 --- a/tests/0004_dynamic_programming/0016_PartitionEqualSubsetSumTest.cc +++ /dev/null @@ -1,33 +0,0 @@ -#include -#include "0016_PartitionEqualSubsetSum.h" - -namespace PartitionEqualSubsetSum -{ - TEST(PartitionEqualSubsetSum, RecursivePartitionEqualSubsetSum) - { - // Arrange - DynamicProgramming dp; - vector nums = { 1, 5, 11, 5 }; - bool expectedResult = true; - - // Act - bool actualResult = dp.RecursivePartitionEqualSubsets(nums); - - // Assert - ASSERT_EQ(expectedResult, actualResult); - } - - TEST(PartitionEqualSubsetSum, DpPartitionEqualSubsetSum) - { - // Arrange - DynamicProgramming dp; - vector nums = { 1, 5, 11, 5 }; - bool expectedResult = true; - - // Act - bool actualResult = dp.DpPartitionEqualSubsets(nums); - - // Assert - ASSERT_EQ(expectedResult, actualResult); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0017_TargetSumTest.cc b/tests/0004_dynamic_programming/0017_TargetSumTest.cc deleted file mode 100644 index ab3fbf4..0000000 --- a/tests/0004_dynamic_programming/0017_TargetSumTest.cc +++ /dev/null @@ -1,50 +0,0 @@ -#include -#include "0017_TargetSum.h" - -namespace TargetSum -{ - TEST(TargetSum, RecursiveSolutionTest_ValidInput_ReturnsCorrectResult) - { - // Arrange - DynamicProgramming dp; - vector nums = { 1, 1, 1, 1, 1 }; - int target = 3; - int expectedResult = 5; - - // Act - int actualResult = dp.RecursiveFindTotalWays(nums, target); - - // Assert - ASSERT_EQ(expectedResult, actualResult); - } - - TEST(TargetSum, DpSolutionTest_ValidInput_ReturnsCorrectResult) - { - // Arrange - DynamicProgramming dp; - vector nums = { 1, 1, 1, 1, 1 }; - int target = 3; - int expectedResult = 5; - - // Act - int actualResult = dp.DpFindTotalWays(nums, target); - - // Assert - ASSERT_EQ(expectedResult, actualResult); - } - - TEST(TargetSum, DpSolutionTest_TargetGreaterThanTotalSum_ReturnsZero) - { - // Arrange - DynamicProgramming dp; - vector nums = { 1, 1, 1, 1, 1 }; - int target = -1000; - int expectedResult = 0; - - // Act - int actualResult = dp.DpFindTotalWays(nums, target); - - // Assert - ASSERT_EQ(expectedResult, actualResult); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/CMakeLists.txt b/tests/0004_dynamic_programming/CMakeLists.txt deleted file mode 100644 index 4ef67b0..0000000 --- a/tests/0004_dynamic_programming/CMakeLists.txt +++ /dev/null @@ -1,49 +0,0 @@ -cmake_policy(SET CMP0135 NEW) - -include(FetchContent) -FetchContent_Declare( - googletest - URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip -) - -# For Windows: Prevent overriding the parent project's compiler/linker settings -set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) -FetchContent_MakeAvailable(googletest) - -enable_testing() - -add_executable( - 0005DynamicProgrammingTests - 0001_FibonacciNumberTest.cc - 0002_TribonacciNumberTest.cc - 0003_ClimbingStairsTest.cc - 0004_MinimumCostClimbingStairsTest.cc - 0005_HouseRobber1Test.cc - 0006_HouseRobber2Test.cc - 0007_DecodeWaysTest.cc - 0008_TilingProblemTest.cc - 0009_FriendsPairingProblemTest.cc - 0010_WaysToCoverDistanceTest.cc - 0011_CountWaysToReachNthStairIncludeOrderTest.cc - 0012_CountWaysToReachNthStairExcludeOrderTest.cc - 0013_KnapsackProblemTest.cc - 0014_SubsetSumProblemTest.cc - 0015_CountSubsetsForSumTest.cc - 0016_PartitionEqualSubsetSumTest.cc - 0017_TargetSumTest.cc - -) - -target_link_libraries( - 0005DynamicProgrammingTests - GTest::gtest_main - 0005DYNAMICPROGRAMMING -) - -# Add .clang-tidy configuration to this library. -if(CLANG_TIDY_EXE) - set_target_properties(0005DYNAMICPROGRAMMING PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") -endif() - -include(GoogleTest) -gtest_discover_tests(0005DynamicProgrammingTests DISCOVERY_TIMEOUT 30) \ No newline at end of file diff --git a/tests/0005_greedy_algorithms/CMakeLists.txt b/tests/0005_greedy_algorithms/CMakeLists.txt deleted file mode 100644 index e69de29..0000000 diff --git a/tests/0006_bitwise_algorithms/CMakeLists.txt b/tests/0006_bitwise_algorithms/CMakeLists.txt deleted file mode 100644 index e69de29..0000000 diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt deleted file mode 100644 index 41d781c..0000000 --- a/tests/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -add_subdirectory(0000_common_utilities) -add_subdirectory(0001_basics) -add_subdirectory(0002_tree) -add_subdirectory(0003_graph) -add_subdirectory(0004_dynamic_programming) -add_subdirectory(0005_greedy_algorithms) -add_subdirectory(0006_bitwise_algorithms) \ No newline at end of file From be9aac446bf80a947e95e393c2a613816734d1d4 Mon Sep 17 00:00:00 2001 From: Debashis Nandi Date: Fri, 12 Jun 2026 01:51:45 +0530 Subject: [PATCH 03/13] feat: reinstated all files for setting correct folder structure --- .clang-tidy | 27 ++ .github/ISSUE_TEMPLATE/bug_report.md | 28 ++ .github/labeler.yaml | 51 +++ .github/pull_request_template.md | 28 ++ .github/release.yaml | 56 +++ .github/workflows/auto-labeler.yaml | 36 ++ .github/workflows/deploy.yaml | 160 ++++++++ .github/workflows/validate.yaml | 130 +++++++ .gitignore | 3 + CMakeLists.txt | 35 ++ CMakePresets.json | 61 +++ CODE_OF_CONDUCT.md | 127 +++++++ CONTRIBUTING.md | 1 + LICENSE | 21 ++ README.md | 21 ++ SECURITY.md | 1 + src/0001_basics/CMakeLists.txt | 11 + src/0001_basics/Node.cc | 6 + src/0001_basics/headers/Node.h | 8 + src/0002_tree/0001_BinarySearchTree.cc | 349 ++++++++++++++++++ src/0002_tree/CMakeLists.txt | 11 + src/0002_tree/headers/0001_BinarySearchTree.h | 49 +++ src/0003_graph/0001_BreadthFirstSearch.cc | 86 +++++ src/0003_graph/0002_DepthFirstSearch.cc | 80 ++++ src/0003_graph/0003_TopologicalSort.cc | 150 ++++++++ .../0004_StronglyConnectedComponents.cc | 121 ++++++ .../0005_HamiltonianPathAndCycle.cc | 114 ++++++ src/0003_graph/0006_EulerianPathAndCircuit.cc | 212 +++++++++++ ...007_MinimumSpanningTreeKruskalAlgorithm.cc | 108 ++++++ .../0008_MinimumSpanningTreePrimAlgorithm.cc | 85 +++++ ...009_SingleSourceShortestPathBellmanFord.cc | 108 ++++++ .../0010_DirectedAcyclicGraphShortestPath.cc | 124 +++++++ .../0011_SingleSourceShortestPathDijkstra.cc | 113 ++++++ ...0012_DifferenceConstraintsShortestPaths.cc | 133 +++++++ ...0013_AllPairsShortestPathsFloydWarshall.cc | 104 ++++++ .../0014_AllPairsShortestPathsJohnson.cc | 217 +++++++++++ .../0015_MaximumFlowFordFulkerson.cc | 139 +++++++ src/0003_graph/0016_MaximumFlowEdmondsKarp.cc | 144 ++++++++ .../0017_MaximumBipartiteMatching.cc | 263 +++++++++++++ ...8_MaximumFlowGoldbergGenericPushRelabel.cc | 172 +++++++++ .../0019_MaximumFlowRelabelToFront.cc | 169 +++++++++ src/0003_graph/CMakeLists.txt | 30 ++ .../headers/0001_BreadthFirstSearch.h | 35 ++ .../headers/0002_DepthFirstSearch.h | 37 ++ src/0003_graph/headers/0003_TopologicalSort.h | 42 +++ .../0004_StronglyConnectedComponents.h | 43 +++ .../headers/0005_HamiltonianPathAndCycle.h | 40 ++ .../headers/0006_EulerianPathAndCircuit.h | 43 +++ ...0007_MinimumSpanningTreeKruskalAlgorithm.h | 46 +++ .../0008_MinimumSpanningTreePrimAlgorithm.h | 42 +++ ...0009_SingleSourceShortestPathBellmanFord.h | 44 +++ .../0010_DirectedAcyclicGraphShortestPath.h | 51 +++ .../0011_SingleSourceShortestPathDijkstra.h | 55 +++ .../0012_DifferenceConstraintsShortestPaths.h | 43 +++ .../0013_AllPairsShortestPathsFloydWarshall.h | 24 ++ .../0014_AllPairsShortestPathsJohnson.h | 66 ++++ .../headers/0015_MaximumFlowFordFulkerson.h | 29 ++ .../headers/0016_MaximumFlowEdmondsKarp.h | 28 ++ .../headers/0017_MaximumBipartiteMatching.h | 41 ++ ...18_MaximumFlowGoldbergGenericPushRelabel.h | 31 ++ .../headers/0019_MaximumFlowRelabelToFront.h | 31 ++ .../0001_FibonacciNumber.cc | 28 ++ .../0002_TribonacciNumber.cc | 33 ++ .../0003_ClimbingStairs.cc | 29 ++ .../0004_MinimumCostClimbingStairs.cc | 48 +++ .../0005_HouseRobber1.cc | 44 +++ .../0006_HouseRobber2.cc | 95 +++++ .../0007_DecodeWays.cc | 61 +++ .../0008_TilingProblem.cc | 42 +++ .../0009_FriendsPairingProblem.cc | 39 ++ .../0010_WaysToCoverDistance.cc | 52 +++ ...11_CountWaysToReachNthStairIncludeOrder.cc | 44 +++ ...12_CountWaysToReachNthStairExcludeOrder.cc | 53 +++ .../0013_KnapsackProblem.cc | 78 ++++ .../0014_SubsetSumProblem.cc | 71 ++++ .../0015_CountSubsetsForSum.cc | 55 +++ .../0016_PartitionEqualSubsetSum.cc | 75 ++++ .../0017_TargetSum.cc | 70 ++++ src/0004_dynamic_programming/CMakeLists.txt | 28 ++ .../headers/0001_FibonacciNumber.h | 23 ++ .../headers/0002_TribonacciNumber.h | 23 ++ .../headers/0003_ClimbingStairs.h | 24 ++ .../headers/0004_MinimumCostClimbingStairs.h | 25 ++ .../headers/0005_HouseRobber1.h | 25 ++ .../headers/0006_HouseRobber2.h | 28 ++ .../headers/0007_DecodeWays.h | 32 ++ .../headers/0008_TilingProblem.h | 25 ++ .../headers/0009_FriendsPairingProblem.h | 46 +++ .../headers/0010_WaysToCoverDistance.h | 47 +++ ...011_CountWaysToReachNthStairIncludeOrder.h | 42 +++ ...012_CountWaysToReachNthStairExcludeOrder.h | 44 +++ .../headers/0013_KnapsackProblem.h | 34 ++ .../headers/0014_SubsetSumProblem.h | 34 ++ .../headers/0015_CountSubsetsForSum.h | 34 ++ .../headers/0016_PartitionEqualSubsetSum.h | 36 ++ .../headers/0017_TargetSum.h | 45 +++ src/0005_greedy_algorithms/CMakeLists.txt | 0 src/0006_bitwise_algorithms/CMakeLists.txt | 0 src/CMakeLists.txt | 6 + tests/0000_common_utilities/CMakeLists.txt | 0 tests/0000_common_utilities/UnitTestHelper.h | 183 +++++++++ tests/0001_basics/CMakeLists.txt | 31 ++ tests/0001_basics/NodeTest.cc | 12 + tests/0002_tree/0001_BinarySearchTreeTest.cc | 91 +++++ tests/0002_tree/CMakeLists.txt | 32 ++ .../0003_graph/0001_BreadthFirstSearchTest.cc | 45 +++ tests/0003_graph/0002_DepthFirstSearchTest.cc | 177 +++++++++ tests/0003_graph/0003_TopologicalSortTest.cc | 116 ++++++ .../0004_StronglyConnectedComponentsTest.cc | 102 +++++ .../0005_HamiltonianPathAndCycleTest.cc | 33 ++ .../0006_EulerianPathAndCircuitTest.cc | 32 ++ ...MinimumSpanningTreeKruskalAlgorithmTest.cc | 45 +++ ...08_MinimumSpanningTreePrimAlgorithmTest.cc | 45 +++ ...SingleSourceShortestPathBellmanFordTest.cc | 104 ++++++ ...10_DirectedAcyclicGraphShortestPathTest.cc | 29 ++ ...11_SingleSourceShortestPathDijkstraTest.cc | 31 ++ ..._DifferenceConstraintsShortestPathsTest.cc | 40 ++ ..._AllPairsShortestPathsFloydWarshallTest.cc | 36 ++ .../0014_AllPairsShortestPathsJohnsonTest.cc | 44 +++ .../0015_MaximumFlowFordFulkersonTest.cc | 64 ++++ .../0016_MaximumFlowEdmondsKarpTest.cc | 64 ++++ .../0017_MaximumBipartiteMatchingTest.cc | 35 ++ ...ximumFlowGoldbergGenericPushRelabelTest.cc | 35 ++ .../0019_MaximumFlowRelabelToFrontTest.cc | 36 ++ tests/0003_graph/CMakeLists.txt | 50 +++ .../0001_FibonacciNumberTest.cc | 34 ++ .../0002_TribonacciNumberTest.cc | 34 ++ .../0003_ClimbingStairsTest.cc | 33 ++ .../0004_MinimumCostClimbingStairsTest.cc | 33 ++ .../0005_HouseRobber1Test.cc | 33 ++ .../0006_HouseRobber2Test.cc | 48 +++ .../0007_DecodeWaysTest.cc | 47 +++ .../0008_TilingProblemTest.cc | 33 ++ .../0009_FriendsPairingProblemTest.cc | 91 +++++ .../0010_WaysToCoverDistanceTest.cc | 117 ++++++ ...ountWaysToReachNthStairIncludeOrderTest.cc | 33 ++ ...ountWaysToReachNthStairExcludeOrderTest.cc | 33 ++ .../0013_KnapsackProblemTest.cc | 53 +++ .../0014_SubsetSumProblemTest.cc | 35 ++ .../0015_CountSubsetsForSumTest.cc | 35 ++ .../0016_PartitionEqualSubsetSumTest.cc | 33 ++ .../0017_TargetSumTest.cc | 50 +++ tests/0004_dynamic_programming/CMakeLists.txt | 49 +++ tests/0005_greedy_algorithms/CMakeLists.txt | 0 tests/0006_bitwise_algorithms/CMakeLists.txt | 0 tests/CMakeLists.txt | 7 + 146 files changed, 8524 insertions(+) create mode 100644 .clang-tidy create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/labeler.yaml create mode 100644 .github/pull_request_template.md create mode 100644 .github/release.yaml create mode 100644 .github/workflows/auto-labeler.yaml create mode 100644 .github/workflows/deploy.yaml create mode 100644 .github/workflows/validate.yaml create mode 100644 .gitignore create mode 100644 CMakeLists.txt create mode 100644 CMakePresets.json create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 README.md create mode 100644 SECURITY.md create mode 100644 src/0001_basics/CMakeLists.txt create mode 100644 src/0001_basics/Node.cc create mode 100644 src/0001_basics/headers/Node.h create mode 100644 src/0002_tree/0001_BinarySearchTree.cc create mode 100644 src/0002_tree/CMakeLists.txt create mode 100644 src/0002_tree/headers/0001_BinarySearchTree.h create mode 100644 src/0003_graph/0001_BreadthFirstSearch.cc create mode 100644 src/0003_graph/0002_DepthFirstSearch.cc create mode 100644 src/0003_graph/0003_TopologicalSort.cc create mode 100644 src/0003_graph/0004_StronglyConnectedComponents.cc create mode 100644 src/0003_graph/0005_HamiltonianPathAndCycle.cc create mode 100644 src/0003_graph/0006_EulerianPathAndCircuit.cc create mode 100644 src/0003_graph/0007_MinimumSpanningTreeKruskalAlgorithm.cc create mode 100644 src/0003_graph/0008_MinimumSpanningTreePrimAlgorithm.cc create mode 100644 src/0003_graph/0009_SingleSourceShortestPathBellmanFord.cc create mode 100644 src/0003_graph/0010_DirectedAcyclicGraphShortestPath.cc create mode 100644 src/0003_graph/0011_SingleSourceShortestPathDijkstra.cc create mode 100644 src/0003_graph/0012_DifferenceConstraintsShortestPaths.cc create mode 100644 src/0003_graph/0013_AllPairsShortestPathsFloydWarshall.cc create mode 100644 src/0003_graph/0014_AllPairsShortestPathsJohnson.cc create mode 100644 src/0003_graph/0015_MaximumFlowFordFulkerson.cc create mode 100644 src/0003_graph/0016_MaximumFlowEdmondsKarp.cc create mode 100644 src/0003_graph/0017_MaximumBipartiteMatching.cc create mode 100644 src/0003_graph/0018_MaximumFlowGoldbergGenericPushRelabel.cc create mode 100644 src/0003_graph/0019_MaximumFlowRelabelToFront.cc create mode 100644 src/0003_graph/CMakeLists.txt create mode 100644 src/0003_graph/headers/0001_BreadthFirstSearch.h create mode 100644 src/0003_graph/headers/0002_DepthFirstSearch.h create mode 100644 src/0003_graph/headers/0003_TopologicalSort.h create mode 100644 src/0003_graph/headers/0004_StronglyConnectedComponents.h create mode 100644 src/0003_graph/headers/0005_HamiltonianPathAndCycle.h create mode 100644 src/0003_graph/headers/0006_EulerianPathAndCircuit.h create mode 100644 src/0003_graph/headers/0007_MinimumSpanningTreeKruskalAlgorithm.h create mode 100644 src/0003_graph/headers/0008_MinimumSpanningTreePrimAlgorithm.h create mode 100644 src/0003_graph/headers/0009_SingleSourceShortestPathBellmanFord.h create mode 100644 src/0003_graph/headers/0010_DirectedAcyclicGraphShortestPath.h create mode 100644 src/0003_graph/headers/0011_SingleSourceShortestPathDijkstra.h create mode 100644 src/0003_graph/headers/0012_DifferenceConstraintsShortestPaths.h create mode 100644 src/0003_graph/headers/0013_AllPairsShortestPathsFloydWarshall.h create mode 100644 src/0003_graph/headers/0014_AllPairsShortestPathsJohnson.h create mode 100644 src/0003_graph/headers/0015_MaximumFlowFordFulkerson.h create mode 100644 src/0003_graph/headers/0016_MaximumFlowEdmondsKarp.h create mode 100644 src/0003_graph/headers/0017_MaximumBipartiteMatching.h create mode 100644 src/0003_graph/headers/0018_MaximumFlowGoldbergGenericPushRelabel.h create mode 100644 src/0003_graph/headers/0019_MaximumFlowRelabelToFront.h create mode 100644 src/0004_dynamic_programming/0001_FibonacciNumber.cc create mode 100644 src/0004_dynamic_programming/0002_TribonacciNumber.cc create mode 100644 src/0004_dynamic_programming/0003_ClimbingStairs.cc create mode 100644 src/0004_dynamic_programming/0004_MinimumCostClimbingStairs.cc create mode 100644 src/0004_dynamic_programming/0005_HouseRobber1.cc create mode 100644 src/0004_dynamic_programming/0006_HouseRobber2.cc create mode 100644 src/0004_dynamic_programming/0007_DecodeWays.cc create mode 100644 src/0004_dynamic_programming/0008_TilingProblem.cc create mode 100644 src/0004_dynamic_programming/0009_FriendsPairingProblem.cc create mode 100644 src/0004_dynamic_programming/0010_WaysToCoverDistance.cc create mode 100644 src/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrder.cc create mode 100644 src/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrder.cc create mode 100644 src/0004_dynamic_programming/0013_KnapsackProblem.cc create mode 100644 src/0004_dynamic_programming/0014_SubsetSumProblem.cc create mode 100644 src/0004_dynamic_programming/0015_CountSubsetsForSum.cc create mode 100644 src/0004_dynamic_programming/0016_PartitionEqualSubsetSum.cc create mode 100644 src/0004_dynamic_programming/0017_TargetSum.cc create mode 100644 src/0004_dynamic_programming/CMakeLists.txt create mode 100644 src/0004_dynamic_programming/headers/0001_FibonacciNumber.h create mode 100644 src/0004_dynamic_programming/headers/0002_TribonacciNumber.h create mode 100644 src/0004_dynamic_programming/headers/0003_ClimbingStairs.h create mode 100644 src/0004_dynamic_programming/headers/0004_MinimumCostClimbingStairs.h create mode 100644 src/0004_dynamic_programming/headers/0005_HouseRobber1.h create mode 100644 src/0004_dynamic_programming/headers/0006_HouseRobber2.h create mode 100644 src/0004_dynamic_programming/headers/0007_DecodeWays.h create mode 100644 src/0004_dynamic_programming/headers/0008_TilingProblem.h create mode 100644 src/0004_dynamic_programming/headers/0009_FriendsPairingProblem.h create mode 100644 src/0004_dynamic_programming/headers/0010_WaysToCoverDistance.h create mode 100644 src/0004_dynamic_programming/headers/0011_CountWaysToReachNthStairIncludeOrder.h create mode 100644 src/0004_dynamic_programming/headers/0012_CountWaysToReachNthStairExcludeOrder.h create mode 100644 src/0004_dynamic_programming/headers/0013_KnapsackProblem.h create mode 100644 src/0004_dynamic_programming/headers/0014_SubsetSumProblem.h create mode 100644 src/0004_dynamic_programming/headers/0015_CountSubsetsForSum.h create mode 100644 src/0004_dynamic_programming/headers/0016_PartitionEqualSubsetSum.h create mode 100644 src/0004_dynamic_programming/headers/0017_TargetSum.h create mode 100644 src/0005_greedy_algorithms/CMakeLists.txt create mode 100644 src/0006_bitwise_algorithms/CMakeLists.txt create mode 100644 src/CMakeLists.txt create mode 100644 tests/0000_common_utilities/CMakeLists.txt create mode 100644 tests/0000_common_utilities/UnitTestHelper.h create mode 100644 tests/0001_basics/CMakeLists.txt create mode 100644 tests/0001_basics/NodeTest.cc create mode 100644 tests/0002_tree/0001_BinarySearchTreeTest.cc create mode 100644 tests/0002_tree/CMakeLists.txt create mode 100644 tests/0003_graph/0001_BreadthFirstSearchTest.cc create mode 100644 tests/0003_graph/0002_DepthFirstSearchTest.cc create mode 100644 tests/0003_graph/0003_TopologicalSortTest.cc create mode 100644 tests/0003_graph/0004_StronglyConnectedComponentsTest.cc create mode 100644 tests/0003_graph/0005_HamiltonianPathAndCycleTest.cc create mode 100644 tests/0003_graph/0006_EulerianPathAndCircuitTest.cc create mode 100644 tests/0003_graph/0007_MinimumSpanningTreeKruskalAlgorithmTest.cc create mode 100644 tests/0003_graph/0008_MinimumSpanningTreePrimAlgorithmTest.cc create mode 100644 tests/0003_graph/0009_SingleSourceShortestPathBellmanFordTest.cc create mode 100644 tests/0003_graph/0010_DirectedAcyclicGraphShortestPathTest.cc create mode 100644 tests/0003_graph/0011_SingleSourceShortestPathDijkstraTest.cc create mode 100644 tests/0003_graph/0012_DifferenceConstraintsShortestPathsTest.cc create mode 100644 tests/0003_graph/0013_AllPairsShortestPathsFloydWarshallTest.cc create mode 100644 tests/0003_graph/0014_AllPairsShortestPathsJohnsonTest.cc create mode 100644 tests/0003_graph/0015_MaximumFlowFordFulkersonTest.cc create mode 100644 tests/0003_graph/0016_MaximumFlowEdmondsKarpTest.cc create mode 100644 tests/0003_graph/0017_MaximumBipartiteMatchingTest.cc create mode 100644 tests/0003_graph/0018_MaximumFlowGoldbergGenericPushRelabelTest.cc create mode 100644 tests/0003_graph/0019_MaximumFlowRelabelToFrontTest.cc create mode 100644 tests/0003_graph/CMakeLists.txt create mode 100644 tests/0004_dynamic_programming/0001_FibonacciNumberTest.cc create mode 100644 tests/0004_dynamic_programming/0002_TribonacciNumberTest.cc create mode 100644 tests/0004_dynamic_programming/0003_ClimbingStairsTest.cc create mode 100644 tests/0004_dynamic_programming/0004_MinimumCostClimbingStairsTest.cc create mode 100644 tests/0004_dynamic_programming/0005_HouseRobber1Test.cc create mode 100644 tests/0004_dynamic_programming/0006_HouseRobber2Test.cc create mode 100644 tests/0004_dynamic_programming/0007_DecodeWaysTest.cc create mode 100644 tests/0004_dynamic_programming/0008_TilingProblemTest.cc create mode 100644 tests/0004_dynamic_programming/0009_FriendsPairingProblemTest.cc create mode 100644 tests/0004_dynamic_programming/0010_WaysToCoverDistanceTest.cc create mode 100644 tests/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrderTest.cc create mode 100644 tests/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrderTest.cc create mode 100644 tests/0004_dynamic_programming/0013_KnapsackProblemTest.cc create mode 100644 tests/0004_dynamic_programming/0014_SubsetSumProblemTest.cc create mode 100644 tests/0004_dynamic_programming/0015_CountSubsetsForSumTest.cc create mode 100644 tests/0004_dynamic_programming/0016_PartitionEqualSubsetSumTest.cc create mode 100644 tests/0004_dynamic_programming/0017_TargetSumTest.cc create mode 100644 tests/0004_dynamic_programming/CMakeLists.txt create mode 100644 tests/0005_greedy_algorithms/CMakeLists.txt create mode 100644 tests/0006_bitwise_algorithms/CMakeLists.txt create mode 100644 tests/CMakeLists.txt diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 0000000..b797f75 --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,27 @@ +Checks: > + readability-identifier-naming + +WarningsAsErrors: '*' + +HeaderFilterRegex: '(include/.*|source/.*)' + +CheckOptions: + # Private member variables + - key: readability-identifier-naming.PrivateMemberPrefix + value: _ + - key: readability-identifier-naming.PrivateMemberCase + value: camelBack + + # Member function (non-static, non-const, non-virtual) + - key: readability-identifier-naming.MethodCase + value: CamelCase + + # Class names + - key: readability-identifier-naming.ClassCase + value: CamelCase + + # Optional, but ensures errors are reported instead of silently skipped + - key: readability-identifier-naming.IgnoreFailures + value: false + - key: readability-identifier-naming.IgnoreFailedSplit + value: false \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..bfe83ee --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,28 @@ +## Bug Report + +### Describe the Bug +_A clear and concise description of what the bug is._ + +### Steps to Reproduce +_Steps to reproduce the behavior:_ +1. Go to `path/to/file.cpp` +2. Run the test case: `./test_case_name` +3. Observe the error + +### Expected Behavior +_A clear and concise description of what you expected to happen._ + +### Screenshots/Outputs +_If applicable, add screenshots or log output to help explain the issue._ + +### Environment (please complete the following information): +- **OS:** [e.g., Windows, macOS, Linux] +- **Compiler:** [e.g., GCC 11, Clang 14, MSVC] +- **CMake Version:** [if applicable] +- **Any other relevant setup details** + +### Possible Fix (Optional) +_If you have an idea of how to fix it, mention it here._ + +### Additional Context +_Add any other context about the problem here._ diff --git a/.github/labeler.yaml b/.github/labeler.yaml new file mode 100644 index 0000000..dae837a --- /dev/null +++ b/.github/labeler.yaml @@ -0,0 +1,51 @@ +# Data Structures and Algorithms: These labels group include, src, and tests by their specific topic +basics: + - changed-files: + - any-glob-to-any-file: 'include/0001_Basics/**' + - any-glob-to-any-file: 'src/0001_Basics/**' + - any-glob-to-any-file: 'tests/0001_Basics/**' +tree: + - changed-files: + - any-glob-to-any-file: 'include/0002_Tree/**' + - any-glob-to-any-file: 'src/0002_Tree/**' + - any-glob-to-any-file: 'tests/0002_Tree/**' +graph: + - changed-files: + - any-glob-to-any-file: 'include/0003_Graph/**' + - any-glob-to-any-file: 'src/0003_Graph/**' + - any-glob-to-any-file: 'tests/0003_Graph/**' +greedy-algorithms: + - changed-files: + - any-glob-to-any-file: 'include/0004_GreedyAlgorithms/**' + - any-glob-to-any-file: 'src/0004_GreedyAlgorithms/**' + - any-glob-to-any-file: 'tests/0004_GreedyAlgorithms/**' +dynamic-programming: + - changed-files: + - any-glob-to-any-file: 'include/0005_DynamicProgramming/**' + - any-glob-to-any-file: 'src/0005_DynamicProgramming/**' + - any-glob-to-any-file: 'tests/0005_DynamicProgramming/**' +bitwise-algorithms: + - changed-files: + - any-glob-to-any-file: 'include/0006_BitwiseAlgorithms/**' + - any-glob-to-any-file: 'src/0006_BitwiseAlgorithms/**' + - any-glob-to-any-file: 'tests/0006_BitwiseAlgorithms/**' + +# Build System: Only fires when every changed file is a CMakeLists.txt +build: + - changed-files: + - all-globs-to-all-files: '**/CMakeLists.txt' + +# Testing Utils: Catches the helper files in tests/0000_CommonUtilities +test-utils: + - changed-files: + - any-glob-to-any-file: 'tests/0000_CommonUtilities/**' + +# Tooling: Github workflows +workflows: + - changed-files: + - any-glob-to-any-file: '.github/**' + +# Documentation: Root level MD files +documentation: + - changed-files: + - any-glob-to-any-file: '*.md' \ No newline at end of file diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..b9581fa --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,28 @@ +### Pull Request Guidelines + +1. **feature → release:** Please provide a description of the solution or fix. The `auto-labeler` bot will automatically label this PR based on the files changed. +2. **release → main:** **Please select the version bump type**, release notes will be auto-generated from the merged feature PRs. + +### feature to release +*(Fill this out when merging a feature branch into a release branch)* + +**Description Category** +- [ ] Basics +- [ ] Tree +- [ ] Graph +- [ ] GreedyAlgorithms +- [ ] DynamicProgramming +- [ ] BitwiseAlgorithms + +**Notes** + + + + +### release to main +*(Fill this out ONLY when merging a release branch into main)* + +**Version Bump Type** +- [ ] Major +- [ ] Minor +- [ ] Patch \ No newline at end of file diff --git a/.github/release.yaml b/.github/release.yaml new file mode 100644 index 0000000..f4ee77d --- /dev/null +++ b/.github/release.yaml @@ -0,0 +1,56 @@ +template: | + ### datastructures-algorithms — release v$RESOLVED_VERSION + $CHANGES + + **Full Changelog:** https://github.com/$OWNER/$REPOSITORY/compare/$PREVIOUS_TAG...v$RESOLVED_VERSION + +change-template: '- $TITLE [#$NUMBER]' + +categories: + - title: 'Basics' + labels: + - 'basics' + + - title: 'Tree' + labels: + - 'tree' + + - title: 'Graph' + labels: + - 'graph' + + - title: 'Greedy Algorithms' + labels: + - 'greedy-algorithms' + + - title: 'Dynamic Programming' + labels: + - 'dynamic-programming' + + - title: 'Bitwise Algorithms' + labels: + - 'bitwise-algorithms' + + - title: 'Build System (CMake)' + labels: + - 'build' + + - title: 'Testing Utilities' + labels: + - 'test-utils' + + - title: 'Workflows Updated' + labels: + - 'workflows' + + - title: 'Documentation' + labels: + - 'documentation' + +exclude-labels: + - 'skip-changelog' + +# Convert "## Title" to "**Title**" +replacers: + - search: '/^## (.*)$/gm' + replace: '**$1**' \ No newline at end of file diff --git a/.github/workflows/auto-labeler.yaml b/.github/workflows/auto-labeler.yaml new file mode 100644 index 0000000..df13bc0 --- /dev/null +++ b/.github/workflows/auto-labeler.yaml @@ -0,0 +1,36 @@ +name: auto-labeler + +# Run this on every PR open or update +on: + pull_request: + types: [opened, synchronize, reopened] + +permissions: + contents: read + # Required to add labels + pull-requests: write + +jobs: + assign-labels: + runs-on: ubuntu-latest + steps: + - name: Checkout Repository + uses: actions/checkout@v4 + # 1. Standard File-based Labeler (Contest vs Problemset) + - name: Assign Labels Based on Changes + id: labeler + uses: actions/labeler@v5 + with: + # This tells it to look at your .github/labeler.yaml + configuration-path: .github/labeler.yaml + repo-token: "${{ secrets.GITHUB_TOKEN }}" + sync-labels: true + + # 2. NEW: Branch-based Labeler (Ignore Release Branches) + - name: Label Release PRs to Skip Changelog + # Only run if the source branch starts with 'release/' + if: startsWith(github.head_ref, 'release/') + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + gh pr edit ${{ github.event.pull_request.number }} --add-label "skip-changelog" \ No newline at end of file diff --git a/.github/workflows/deploy.yaml b/.github/workflows/deploy.yaml new file mode 100644 index 0000000..9f024d9 --- /dev/null +++ b/.github/workflows/deploy.yaml @@ -0,0 +1,160 @@ +name: deploy + +# Triggers only when a PR to 'main' is closed +on: + pull_request: + types: [closed] + branches: + - 'main' + +permissions: + contents: write # Required to push tags and create releases + pull-requests: read # Required to read PR body for checkboxes + +jobs: + # job 1: Deployment Validation + # Verifies the PR is merged, comes from a release/* branch, and has a bump type. + deployment-validation: + runs-on: ubuntu-latest + # Define outputs to pass to the next job + outputs: + bump_type: ${{ steps.get_bump_type.outputs.bump_type }} + + steps: + - name: Verify Merge and Branch Policy + run: | + IS_MERGED="${{ github.event.pull_request.merged }}" + HEAD_REF="${{ github.event.pull_request.head.ref }}" + + echo "PR Merged: $IS_MERGED" + echo "Source Branch: $HEAD_REF" + + # 1. Check if PR was actually merged (not just closed) + if [[ "$IS_MERGED" != "true" ]]; then + echo "::notice::PR was closed without merging. Skipping release." + exit 1 + fi + + # 2. Check if source branch starts with 'release/' + if [[ "$HEAD_REF" != release/* ]]; then + echo "::error::Invalid source branch. Releases must originate from 'release/*' branches." + exit 1 + fi + + echo "Branch policy checks passed." + + - name: Determine Version Bump Type + id: get_bump_type + env: + PR_BODY: ${{ github.event.pull_request.body }} + run: | + # Check checkboxes in PR Body: [x] Major, [x] Minor, etc. + if echo "$PR_BODY" | grep -q '\[x\] Major'; then + echo "bump_type=major" >> $GITHUB_OUTPUT + echo "Detected bump: MAJOR" + elif echo "$PR_BODY" | grep -q '\[x\] Minor'; then + echo "bump_type=minor" >> $GITHUB_OUTPUT + echo "Detected bump: MINOR" + elif echo "$PR_BODY" | grep -q '\[x\] Patch'; then + echo "bump_type=patch" >> $GITHUB_OUTPUT + echo "Detected bump: PATCH" + else + echo "::error::No version bump detected. Please check [x] Major, [x] Minor, or [x] Patch in the PR body." + exit 1 + fi + + # job 2: Create GitHub Tag and Release + create-github-tag-and-release: + needs: deployment-validation + runs-on: ubuntu-latest + env: + BUMP_TYPE: ${{ needs.deployment-validation.outputs.bump_type }} + + steps: + - name: Checkout main branch + uses: actions/checkout@v4 + with: + ref: 'main' + fetch-depth: 0 # Crucial for calculating history/tags + + - name: Configure Git + run: | + git config --global user.name "github-actions[bot]" + git config --global user.email "github-actions[bot]@users.noreply.github.com" + + # Step A: Find the existing tag + - name: Get Latest Tag + id: get_latest_tag + run: | + # 1. Fetch all tags + git fetch --tags + + # 2. Find latest tag (Sort by version number, take top) + LATEST_TAG=$(git tag --list 'v*.*.*' --sort=-v:refname | head -n 1) + + if [ -z "$LATEST_TAG" ]; then + echo "No previous tags found. Defaulting to v0.0.0" + LATEST_TAG="v0.0.0" + fi + + echo "Latest Tag: $LATEST_TAG" + + # Expose this variable to the next step + echo "latest_tag=$LATEST_TAG" >> $GITHUB_OUTPUT + + # Step B: Do the math + - name: Calculate New Tag + id: calc_new_tag + env: + # Pull the tag from the previous step + LATEST_TAG: ${{ steps.get_latest_tag.outputs.latest_tag }} + # Assuming BUMP_TYPE is set in the Job 'env' as per previous context + run: | + echo "Base Tag: $LATEST_TAG" + echo "Bump Type: $BUMP_TYPE" + + # 1. Parse Version + VERSION=${LATEST_TAG#v} # Remove 'v' + IFS='.' read -r -a parts <<< "$VERSION" + MAJOR=${parts[0]} + MINOR=${parts[1]} + PATCH=${parts[2]} + + # 2. Increment + case "$BUMP_TYPE" in + "major") MAJOR=$((MAJOR + 1)); MINOR=0; PATCH=0 ;; + "minor") MINOR=$((MINOR + 1)); PATCH=0 ;; + "patch") PATCH=$((PATCH + 1)) ;; + esac + + NEW_TAG="v${MAJOR}.${MINOR}.${PATCH}" + + echo "new_tag=$NEW_TAG" >> $GITHUB_OUTPUT + echo "New tag will be: $NEW_TAG" + + - name: Create and push new Git tag + run: | + NEW_TAG=${{ steps.calc_new_tag.outputs.new_tag }} + MERGE_COMMIT_SHA=${{ github.event.pull_request.merge_commit_sha }} + + echo "Tagging commit $MERGE_COMMIT_SHA as $NEW_TAG" + git tag $NEW_TAG $MERGE_COMMIT_SHA + git push origin $NEW_TAG + + # Step D: Generate Auto-Notes and Publish + - name: Create GitHub Release + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + uses: release-drafter/release-drafter@v6 + with: + # Uses your .github/release.yaml to categorize changes + config-name: release.yaml + + # We force it to use the tag you just calculated and pushed + tag: ${{ steps.calc_new_tag.outputs.new_tag }} + name: "${{ steps.calc_new_tag.outputs.new_tag }}" + version: ${{ steps.calc_new_tag.outputs.new_tag }} + + # This makes it a real release (not a draft) + publish: true + \ No newline at end of file diff --git a/.github/workflows/validate.yaml b/.github/workflows/validate.yaml new file mode 100644 index 0000000..47a55f5 --- /dev/null +++ b/.github/workflows/validate.yaml @@ -0,0 +1,130 @@ +name: validate + +on: + pull_request: + types: [opened, synchronize] + branches: + - 'release/*' + - 'main' + +jobs: + # job 1: Policy Check + validate-branch-policy: + runs-on: ubuntu-latest + steps: + - name: Verify Branch Strategy + run: | + HEAD="${{ github.head_ref }}" + BASE="${{ github.base_ref }}" + echo "Verifying path: $HEAD -> $BASE" + + if [[ "$HEAD" == feature/* && "$BASE" == release/* ]]; then + echo "Pull Request is allowed: $HEAD -> $BASE." + exit 0 + elif [[ "$HEAD" == release/* && "$BASE" == main ]]; then + echo "Pull Request is allowed: $HEAD -> $BASE." + exit 0 + else + echo "::error::Invalid Pull Request from '$HEAD' -> '$BASE'." + echo "Allowed: 'feature/*'->'release/*' OR 'release/*'->'main'." + exit 1 + fi + + # job 2: Static Analysis + lint-code: + needs: validate-branch-policy + runs-on: windows-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup MSVC + uses: ilammy/msvc-dev-cmd@v1 + with: + arch: x64 + + - name: Install dependencies + shell: pwsh + run: | + choco install cmake --no-progress -y + choco install ninja --no-progress -y + choco install llvm --no-progress -y + + - name: Configure CMake + shell: pwsh + run: cmake -S . -B build -G "Ninja" -DCMAKE_EXPORT_COMPILE_COMMANDS=ON + + - name: Run clang-tidy + shell: pwsh + run: | + clang-tidy --version + $files = Get-ChildItem -Recurse -Path src -Include *.cpp,*.cc,*.cxx -File + $failed = $false + # These source/.* files would be checked using .clang-tidy maintained at projectroot + foreach ($file in $files) { + Write-Host "Checking $($file.FullName)" + clang-tidy -p build "$($file.FullName)" --warnings-as-errors=* + if ($LASTEXITCODE -ne 0) { $failed = $true } + } + if ($failed) { Write-Error "Clang-tidy failed."; exit 1 } + + # job 3: Build Project + build-project: + needs: lint-code + runs-on: windows-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup MSVC + uses: ilammy/msvc-dev-cmd@v1 + with: + arch: x64 + + - name: Install dependencies + shell: pwsh + run: | + choco install cmake --no-progress -y + choco install ninja --no-progress -y + + - name: Configure CMake + shell: pwsh + run: cmake -S . -B build -G "Ninja" + + - name: Build + shell: pwsh + run: cmake --build build --config Release + + # Upload the build directory so the Test job can use it + - name: Upload Build Artifacts + uses: actions/upload-artifact@v4 + with: + name: build-artifacts + path: build/ + retention-days: 1 + + # job 4: Run all Tests + run-all-tests: + needs: build-project + runs-on: windows-latest + steps: + - name: Checkout code + # We need the source code because CTest might look for source files referenced in tests + uses: actions/checkout@v4 + + - name: Install dependencies + shell: pwsh + # We only need CMake (for ctest) here. Ninja/LLVM usually not needed unless tests invoke them. + run: choco install cmake --no-progress -y + + - name: Download Build Artifacts + uses: actions/download-artifact@v4 + with: + name: build-artifacts + path: build + + - name: Run tests + shell: pwsh + # -C Release is crucial if it's a multi-config generator, though Ninja is single-config. + # Good practice to keep it for consistency. + run: ctest --test-dir build --output-on-failure -C Release \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ccdf92f --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.vs/ +.vscode/ +artifact/ \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..d919238 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,35 @@ +cmake_minimum_required (VERSION 3.10) +project ("datastructures-algorithms") + +set(CMAKE_CXX_STANDARD 14) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) + + +# .clang-tidy setup +find_program(CLANG_TIDY_EXE NAMES "clang-tidy") +if(CLANG_TIDY_EXE) + message(STATUS "clang-tidy found: ${CLANG_TIDY_EXE}") + set(CLANG_TIDY_COMMAND + "${CLANG_TIDY_EXE}" + "--config-file=${CMAKE_SOURCE_DIR}/.clang-tidy" + "--extra-arg-before=-Wno-unknown-warning-option" + "--extra-arg-before=-Wno-c++98-compat-pedantic" + "--quiet" + ) +endif() + +add_subdirectory(src) + +cmake_policy(SET CMP0135 NEW) +include(FetchContent) +FetchContent_Declare( + googletest + URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip +) + +# For Windows: Prevent overriding the parent project's compiler/linker settings +set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) + +enable_testing() +add_subdirectory(tests) \ No newline at end of file diff --git a/CMakePresets.json b/CMakePresets.json new file mode 100644 index 0000000..71f41cb --- /dev/null +++ b/CMakePresets.json @@ -0,0 +1,61 @@ +{ + "version": 3, + "configurePresets": [ + { + "name": "windows-base", + "hidden": true, + "generator": "Ninja", + "binaryDir": "${sourceDir}/artifact/build/${presetName}", + "installDir": "${sourceDir}/artifact/install/${presetName}", + "cacheVariables": { + "CMAKE_C_COMPILER": "cl.exe", + "CMAKE_CXX_COMPILER": "cl.exe" + }, + "condition": { + "type": "equals", + "lhs": "${hostSystemName}", + "rhs": "Windows" + } + }, + { + "name": "x64-debug", + "displayName": "x64 Debug", + "inherits": "windows-base", + "architecture": { + "value": "x64", + "strategy": "external" + }, + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Debug" + } + }, + { + "name": "x64-release", + "displayName": "x64 Release", + "inherits": "x64-debug", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Release" + } + }, + { + "name": "x86-debug", + "displayName": "x86 Debug", + "inherits": "windows-base", + "architecture": { + "value": "x86", + "strategy": "external" + }, + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Debug" + } + }, + { + "name": "x86-release", + "displayName": "x86 Release", + "inherits": "x86-debug", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Release" + } + } + ] +} diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..3f705c7 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,127 @@ +## Contributor Covenant Code of Conduct + +### Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +### Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +### Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +### Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +### Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +### Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +#### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +#### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +#### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +#### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +### Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..68a2127 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1 @@ +## This project is for academic purpose, no contributions are expected right now. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..fd336ec --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Debashis Nandi + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..bd633b7 --- /dev/null +++ b/README.md @@ -0,0 +1,21 @@ +## Data Structures and Algorithms + +This repository contains a collection of **data structures and algorithms** implemented in **C++**. It is designed to provide efficient solutions to common algorithmic problems while adhering to clean coding practices and modular design. + +### Features + +- **Data Structures and Algorithms:** Implementations of data structures and algorithms based on the concepts from the book ***Introduction to Algorithms by Cormen, Leiserson, Rivest, and Stein (CLRS).*** +- **Modular Design:** Code is organized into manageable modules for better readability and reusability. +- **Testing:** + - Built with **CMake** as the build system for ease of compilation and dependency management. + - **Google Test** framework is integrated for comprehensive unit testing to ensure code correctness. + +### Folder Structure + +```plain text +datastructures-algorithms +├── include # Header Files +├── src # Implementation of the solutions +├── tests # Unit tests for implemented solutions +└── CMakeLists.txt # CMake configuration file +``` diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..206769a --- /dev/null +++ b/SECURITY.md @@ -0,0 +1 @@ +## Security Policy diff --git a/src/0001_basics/CMakeLists.txt b/src/0001_basics/CMakeLists.txt new file mode 100644 index 0000000..477c6cd --- /dev/null +++ b/src/0001_basics/CMakeLists.txt @@ -0,0 +1,11 @@ +# Specify the source files +set(0001BASICS_SOURCES + Node.cc +) + +# Create a library target +add_library(0001BASICS ${0001BASICS_SOURCES}) + +target_include_directories(0001BASICS PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}/headers +) \ No newline at end of file diff --git a/src/0001_basics/Node.cc b/src/0001_basics/Node.cc new file mode 100644 index 0000000..df1effa --- /dev/null +++ b/src/0001_basics/Node.cc @@ -0,0 +1,6 @@ +#include "Node.h" + +Node::Node() +{ + value = 8; +} \ No newline at end of file diff --git a/src/0001_basics/headers/Node.h b/src/0001_basics/headers/Node.h new file mode 100644 index 0000000..dcee809 --- /dev/null +++ b/src/0001_basics/headers/Node.h @@ -0,0 +1,8 @@ +#pragma once + +class Node +{ +public: + int value; + Node(); +}; \ No newline at end of file diff --git a/src/0002_tree/0001_BinarySearchTree.cc b/src/0002_tree/0001_BinarySearchTree.cc new file mode 100644 index 0000000..ba78751 --- /dev/null +++ b/src/0002_tree/0001_BinarySearchTree.cc @@ -0,0 +1,349 @@ +#include "0001_BinarySearchTree.h" +#include +#include +using namespace std; + +namespace BinarySearchTree +{ + Node::Node(int data, Node* parent, Node* left, Node* right) + { + this->data = data; + this->parent = parent; + this->left = left; + this->right = right; + } + + BinarySearchTree::BinarySearchTree() + { + this->_root = nullptr; + } + + + void BinarySearchTree::InsertBinarySearchTreeNode(Node* node) + { + Node* nodeY = nullptr; + Node* nodeX = this->_root; + while (nodeX != nullptr) + { + nodeY = nodeX; + if (node->data < nodeX->data) + { + nodeX = nodeX->left; + } + else + { + nodeX = nodeX->right; + } + } + node->parent = nodeY; + if (nodeY == nullptr) + { + this->_root = node; + } + else if (node->data < nodeY->data) + { + nodeY->left = node; + } + else + { + nodeY->right = node; + } + } + + Node* BinarySearchTree::FindBinarySearchTreeNode(int value) + { + Node* node = this->_root; + while (node != nullptr) + { + if (value < node->data) + { + node = node->left; + } + else if (value > node->data) + { + node = node->right; + } + else + { + break; + } + } + return node; + } + + Node* BinarySearchTree::FindBinarySearchTreeMinimumValueNode(Node* node) + { + while (node->left != nullptr) + { + node = node->left; + } + return node; + } + + Node* BinarySearchTree::FindBinarySearchTreeMaximumValueNode(Node* node) + { + while (node->right != nullptr) + { + node = node->right; + } + return node; + } + + Node* BinarySearchTree::FindSuccessorBinarySearchTreeNode(Node* node) + { + if (node->right != nullptr) + { + return this->FindBinarySearchTreeMinimumValueNode(node->right); + } + Node* nodeY = node->parent; + while (nodeY != nullptr && node == nodeY->right) + { + node = nodeY; + nodeY = nodeY->parent; + } + return nodeY; + } + + Node* BinarySearchTree::FindPredecessorBinarySearchTreeNode(Node* node) + { + if (node->left != nullptr) + { + return this->FindBinarySearchTreeMaximumValueNode(node->left); + } + Node* nodeY = node->parent; + while (nodeY != nullptr && node == nodeY->left) + { + node = nodeY; + nodeY = nodeY->parent; + } + return nodeY; + } + + void BinarySearchTree::TransplantBinarySearchTreeNode(Node* nodeU, Node* nodeV) + { + if (nodeU->parent == nullptr) + { + this->_root = nodeV; + } + else if (nodeU == nodeU->parent->left) + { + nodeU->parent->left = nodeV; + } + else + { + nodeU->parent->right = nodeV; + } + + if (nodeV != nullptr) + { + nodeV->parent = nodeU->parent; + } + } + + void BinarySearchTree::DeleteBinarySearchTreeNode(Node* node) + { + if (node->left == nullptr) + { + this->TransplantBinarySearchTreeNode(node, node->right); + } + else if (node->right == nullptr) + { + this->TransplantBinarySearchTreeNode(node, node->left); + } + else + { + Node* nodeY = this->FindBinarySearchTreeMinimumValueNode(node->right); + if (nodeY->parent != node) + { + this->TransplantBinarySearchTreeNode(nodeY, nodeY->right); + nodeY->right = node->right; + nodeY->right->parent = nodeY; + } + this->TransplantBinarySearchTreeNode(node, nodeY); + nodeY->left = node->left; + nodeY->left->parent = nodeY; + delete node; + } + } + + void BinarySearchTree::RecursiveInorderTraversal(Node* node, vector& result) + { + if (node == nullptr) + { + return; + } + this->RecursiveInorderTraversal(node->left, result); + result.push_back(node->data); + this->RecursiveInorderTraversal(node->right, result); + } + + void BinarySearchTree::RecursivePreorderTraversal(Node* node, vector& result) + { + if (node == nullptr) + { + return; + } + result.push_back(node->data); + this->RecursivePreorderTraversal(node->left, result); + this->RecursivePreorderTraversal(node->right, result); + } + + void BinarySearchTree::RecursivePostorderTraversal(Node* node, vector& result) + { + if (node == nullptr) + { + return; + } + this->RecursivePostorderTraversal(node->left, result); + this->RecursivePostorderTraversal(node->right, result); + result.push_back(node->data); + } + + void BinarySearchTree::MorrisInorderTraversal(Node* node, vector& result) + { + while (node != nullptr) + { + if (node->left == nullptr) + { + result.push_back(node->data); + node = node->right; + } + else + { + Node* predecessor = node->left; + while (predecessor->right != nullptr && predecessor->right != node) + { + predecessor = predecessor->right; + } + if (predecessor->right == nullptr) + { + predecessor->right = node; + node = node->left; + } + else + { + predecessor->right = nullptr; + result.push_back(node->data); + node = node->right; + } + } + } + } + + void BinarySearchTree::MorrisPreorderTraversal(Node* node, vector& result) + { + while (node != nullptr) + { + if (node->left == nullptr) + { + result.push_back(node->data); + node = node->right; + } + else + { + Node* predecessor = node->left; + while (predecessor->right != nullptr && predecessor->right != node) + { + predecessor = predecessor->right; + } + if (predecessor->right == nullptr) + { + predecessor->right = node; + result.push_back(node->data); + node = node->left; + } + else + { + predecessor->right = nullptr; + node = node->right; + } + } + } + } + + void BinarySearchTree::MorrisPostorderTraversal(Node* node, vector& result) + { + while (node != nullptr) + { + if (node->right == nullptr) + { + result.push_back(node->data); + node = node->left; + } + else + { + Node* predecessor = node->right; + while (predecessor->left != nullptr && predecessor->left != node) + { + predecessor = predecessor->left; + } + if (predecessor->left == nullptr) + { + predecessor->left = node; + result.push_back(node->data); + node = node->right; + } + else + { + predecessor->left = nullptr; + node = node->left; + } + } + } + reverse(result.begin(), result.end()); + } + + void BinarySearchTree::InsertNode(int value) + { + Node* node = new Node(value, nullptr, nullptr, nullptr); + this->InsertBinarySearchTreeNode(node); + } + + void BinarySearchTree::DeleteNode(int value) + { + Node* node = this->FindBinarySearchTreeNode(value); + this->DeleteBinarySearchTreeNode(node); + } + + vector BinarySearchTree::GetRecursiveInorderTravesalResult() + { + vector result; + this->RecursiveInorderTraversal(this->_root, result); + return result; + } + + vector BinarySearchTree::GetRecursivePreorderTravesalResult() + { + vector result; + this->RecursivePreorderTraversal(this->_root, result); + return result; + } + + vector BinarySearchTree::GetRecursivePostorderTravesalResult() + { + vector result; + this->RecursivePostorderTraversal(this->_root, result); + return result; + } + + vector BinarySearchTree::GetMorrisInorderTraversalResult() + { + vector result; + this->MorrisInorderTraversal(this->_root, result); + return result; + } + + vector BinarySearchTree::GetMorrisPreorderTraversalResult() + { + vector result; + this->MorrisPreorderTraversal(this->_root, result); + return result; + } + + vector BinarySearchTree::GetMorrisPostorderTraversalResult() + { + vector result; + this->MorrisPostorderTraversal(this->_root, result); + return result; + } +} \ No newline at end of file diff --git a/src/0002_tree/CMakeLists.txt b/src/0002_tree/CMakeLists.txt new file mode 100644 index 0000000..5508146 --- /dev/null +++ b/src/0002_tree/CMakeLists.txt @@ -0,0 +1,11 @@ +# Specify the source files +set(0002TREE_SOURCES + 0001_BinarySearchTree.cc +) + +# Create a library target +add_library(0002TREE ${0002TREE_SOURCES}) + +target_include_directories(0002TREE PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}/headers +) \ No newline at end of file diff --git a/src/0002_tree/headers/0001_BinarySearchTree.h b/src/0002_tree/headers/0001_BinarySearchTree.h new file mode 100644 index 0000000..1e9bcc2 --- /dev/null +++ b/src/0002_tree/headers/0001_BinarySearchTree.h @@ -0,0 +1,49 @@ +#pragma once + +#include +#include +using namespace std; + +namespace BinarySearchTree +{ + class Node + { + public: + int data; + Node* parent; + Node* left; + Node* right; + + Node(int data, Node* parent, Node* left, Node* right); + }; + + class BinarySearchTree + { + private: + Node* _root; + void InsertBinarySearchTreeNode(Node* node); + Node* FindBinarySearchTreeNode(int value); + Node* FindBinarySearchTreeMinimumValueNode(Node* node); + Node* FindBinarySearchTreeMaximumValueNode(Node* node); + Node* FindSuccessorBinarySearchTreeNode(Node* node); + Node* FindPredecessorBinarySearchTreeNode(Node* node); + void TransplantBinarySearchTreeNode(Node* nodeU, Node* nodeV); + void DeleteBinarySearchTreeNode(Node* node); + void RecursiveInorderTraversal(Node* node, vector& result); + void RecursivePreorderTraversal(Node* node, vector& result); + void RecursivePostorderTraversal(Node* node, vector& result); + void MorrisInorderTraversal(Node* node, vector& result); + void MorrisPreorderTraversal(Node* node, vector& result); + void MorrisPostorderTraversal(Node* node, vector& result); + public: + BinarySearchTree(); + void InsertNode(int value); + void DeleteNode(int value); + vector GetRecursiveInorderTravesalResult(); + vector GetRecursivePreorderTravesalResult(); + vector GetRecursivePostorderTravesalResult(); + vector GetMorrisInorderTraversalResult(); + vector GetMorrisPreorderTraversalResult(); + vector GetMorrisPostorderTraversalResult(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/0001_BreadthFirstSearch.cc b/src/0003_graph/0001_BreadthFirstSearch.cc new file mode 100644 index 0000000..9a8b1ac --- /dev/null +++ b/src/0003_graph/0001_BreadthFirstSearch.cc @@ -0,0 +1,86 @@ +#include "0001_BreadthFirstSearch.h" +#include +#include +#include +#include +#include +#include +using namespace std; + +namespace BreadthFirstSearch +{ + Node::Node(int value) + { + this->data = value; + this->distance = INT_MAX; + this->color = WHITE; + this->parent = nullptr; + } + + Node* Graph::MakeOrFindNode(int value) + { + Node* node = nullptr; + if (this->_nodeMap.find(value) == this->_nodeMap.end()) + { + node = new Node(value); + this->_nodeMap[value] = node; + } + else + { + node = this->_nodeMap[value]; + } + return node; + } + + void Graph::BreadthFirstSearch(Node* node) + { + node->color = WHITE; + node->distance = 0; + node->parent = nullptr; + + queue nodeQueue; + nodeQueue.push(node); + + while (nodeQueue.empty() != true) + { + Node* currentNode = nodeQueue.front(); + nodeQueue.pop(); + + for (auto& adjacentNode : this->_adjlist[currentNode]) + { + if (adjacentNode->color == WHITE) + { + adjacentNode->color = GRAY; + adjacentNode->parent = currentNode; + adjacentNode->distance = currentNode->distance + 1; + nodeQueue.push(adjacentNode); + } + } + currentNode->color = BLACK; + } + } + + void Graph::PushUndirectedEdge(int valueU, int valueV) + { + Node* nodeU = this->MakeOrFindNode(valueU); + Node* nodeV = this->MakeOrFindNode(valueV); + + this->_adjlist[nodeU].push_back(nodeV); + this->_adjlist[nodeV].push_back(nodeU); + } + + void Graph::BFS(int value) + { + this->BreadthFirstSearch(this->_nodeMap[value]); + } + + vector> Graph::ShowBFSResult() + { + vector> result; + for (auto& node : this->_nodeMap) + { + result.push_back(make_pair(node.first, node.second->distance)); + } + return result; + } +} \ No newline at end of file diff --git a/src/0003_graph/0002_DepthFirstSearch.cc b/src/0003_graph/0002_DepthFirstSearch.cc new file mode 100644 index 0000000..3cbc49a --- /dev/null +++ b/src/0003_graph/0002_DepthFirstSearch.cc @@ -0,0 +1,80 @@ +#include "0002_DepthFirstSearch.h" +#include +#include +#include +using namespace std; + +namespace DepthFirstSearch +{ + Node::Node(int value) + { + this->data = value; + this->discoveredTime = INT_MAX; + this->finishingTime = INT_MAX; + this->color = WHITE; + this->parent = nullptr; + } + + Node* Graph::MakeOrFindNode(int value) + { + Node* node = nullptr; + if (this->_nodeMap.find(value) == this->_nodeMap.end()) + { + node = new Node(value); + this->_nodeMap[value] = node; + } + else + { + node = this->_nodeMap[value]; + } + return node; + } + + void Graph::DepthFirstSearch(Node* nodeU) + { + this->_time++; + nodeU->discoveredTime = this->_time; + nodeU->color = GRAY; + for (auto nodeV : this->_adjlist[nodeU]) + { + if (nodeV->color == WHITE) + { + nodeV->parent = nodeU; + this->DepthFirstSearch(nodeV); + } + } + nodeU->color = BLACK; + this->_time++; + nodeU->finishingTime = this->_time; + } + + void Graph::PushDirectedEdge(int valueU, int valueV) + { + Node* nodeU = this->MakeOrFindNode(valueU); + Node* nodeV = this->MakeOrFindNode(valueV); + + this->_adjlist[nodeU].push_back(nodeV); + } + + void Graph::DFS() + { + this->_time = 0; + for (auto& iterator : this->_nodeMap) + { + if (iterator.second->color == WHITE) + { + this->DepthFirstSearch(iterator.second); + } + } + } + + vector>> Graph::ShowDFSResult() + { + vector>> result; + for (auto& node : this->_nodeMap) + { + result.push_back(make_pair(node.first, make_pair(node.second->discoveredTime, node.second->finishingTime))); + } + return result; + } +} \ No newline at end of file diff --git a/src/0003_graph/0003_TopologicalSort.cc b/src/0003_graph/0003_TopologicalSort.cc new file mode 100644 index 0000000..3d4d1cb --- /dev/null +++ b/src/0003_graph/0003_TopologicalSort.cc @@ -0,0 +1,150 @@ +#include "0003_TopologicalSort.h" +#include +#include +#include +#include +#include +using namespace std; + +namespace TopologicalSort +{ + Node::Node(int value) + { + this->data = value; + this->color = WHITE; + this->discoveryTime = INT_MAX; + this->finishingTime = INT_MAX; + this->inDegree = 0; + this->parent = nullptr; + } + + Node* Graph::MakeOrFindNode(int value) + { + Node* node = nullptr; + if (this->_nodeMap.find(value) == this->_nodeMap.end()) + { + node = new Node(value); + this->_nodeMap[value] = node; + } + else + { + node = this->_nodeMap[value]; + } + return node; + } + + void Graph::DepthFirstSearch(Node* nodeU) + { + this->_time++; + nodeU->discoveryTime = this->_time; + nodeU->color = GRAY; + for (auto& nodeV : this->_adjlist[nodeU]) + { + if (nodeV->color == WHITE) + { + nodeV->parent = nodeU; + this->DepthFirstSearch(nodeV); + } + else if (nodeV->color == GRAY) + { + this->_hasCycle = true; + return; + } + } + nodeU->color = BLACK; + this->_time++; + nodeU->finishingTime = this->_time; + this->_topologicalSortedNodeList.push_front(nodeU); + } + + void Graph::PushDirectedEdge(int valueU, int valueV) + { + Node* nodeU = this->MakeOrFindNode(valueU); + Node* nodeV = this->MakeOrFindNode(valueV); + + this->_adjlist[nodeU].push_back(nodeV); + nodeV->inDegree++; + } + + void Graph::PushSingleNode(int valueU) + { + this->MakeOrFindNode(valueU); + } + + void Graph::TopologicalSort() + { + this->_time = 0; + for (auto& iterator : this->_nodeMap) + { + if (iterator.second->color == WHITE) + { + this->DepthFirstSearch(iterator.second); + if (this->_hasCycle == true) + { + break; + } + } + } + } + + void Graph::KahnTopologicalSort() + { + // Step-1 Compute in-degree of each vertices + // This is already done while creating the graph + this->_time = 0; + queue nodeQueue; + + // Step-2 Enqueue vertices with in-degree 0 + for (auto& node : this->_nodeMap) + { + if (node.second->inDegree == 0) + { + this->_time++; + node.second->discoveryTime = this->_time; + nodeQueue.push(node.second); + } + } + + // Step-3 Process vertices in queue + while (!nodeQueue.empty()) + { + Node* node = nodeQueue.front(); + nodeQueue.pop(); + this->_time++; + node->finishingTime = this->_time; + this->_topologicalSortedNodeList.push_back(node); + + // Step-4 Process all the neighbours of current node based on in-degree + for (auto& neighbour : this->_adjlist[node]) + { + neighbour->inDegree--; + if (neighbour->inDegree == 0) + { + this->_time++; + neighbour->discoveryTime = this->_time; + nodeQueue.push(neighbour); + } + } + } + + // Step-5 Check if a cycle exists + if (this->_topologicalSortedNodeList.size() != this->_nodeMap.size()) + { + this->_hasCycle = true; + } + } + + vector>> Graph::ShowTopologicalSortResult() + { + if (this->_hasCycle == true) + { + return {}; + } + vector>> result; + for (auto& node : this->_topologicalSortedNodeList) + { + result.push_back(make_pair(node->data, make_pair(node->discoveryTime, node->finishingTime))); + } + return result; + } +} \ No newline at end of file diff --git a/src/0003_graph/0004_StronglyConnectedComponents.cc b/src/0003_graph/0004_StronglyConnectedComponents.cc new file mode 100644 index 0000000..7a99e34 --- /dev/null +++ b/src/0003_graph/0004_StronglyConnectedComponents.cc @@ -0,0 +1,121 @@ +#include "0004_StronglyConnectedComponents.h" +#include +#include +#include +using namespace std; + +namespace StronglyConnectedComponents +{ + Node::Node(int value) + { + this->data = value; + this->discoveryTime = INT_MAX; + this->finishingTime = INT_MAX; + this->color = WHITE; + this->parent = nullptr; + } + + Node* Graph::MakeOrFindNode(int value) + { + Node* node = nullptr; + if (this->_nodeMap.find(value) == this->_nodeMap.end()) + { + node = new Node(value); + this->_nodeMap[value] = node; + } + else + { + node = this->_nodeMap[value]; + } + return node; + } + + void Graph::DepthFirstSearchOnGraphG(Node* nodeU) + { + this->_time++; + nodeU->discoveryTime = this->_time; + nodeU->color = GRAY; + for (auto nodeV : this->_adjlistG[nodeU]) + { + if (nodeV->color == WHITE) + { + nodeV->parent = nodeU; + this->DepthFirstSearchOnGraphG(nodeV); + } + } + nodeU->color = BLACK; + this->_time++; + nodeU->finishingTime = this->_time; + this->_nodesFinishingTimeOrder.push_front(nodeU); + } + + void Graph::DepthFirstSearchOnGraphT(Node* nodeU, vector& connectedComponents) + { + nodeU->color = GRAY; + connectedComponents.push_back(nodeU->data); + for (auto nodeV : this->_adjlistT[nodeU]) + { + if (nodeV->color == WHITE) + { + nodeV->parent = nodeU; + this->DepthFirstSearchOnGraphT(nodeV, connectedComponents); + } + } + nodeU->color = BLACK; + } + + void Graph::PushDirectedEdge(int valueU, int valueV) + { + Node* nodeU = this->MakeOrFindNode(valueU); + Node* nodeV = this->MakeOrFindNode(valueV); + + // Creating the actual graph. + this->_adjlistG[nodeU].push_back(nodeV); + + // Creating the transpose of the actual graph. + this->_adjlistT[nodeV].push_back(nodeU); + } + + void Graph::PushSingleNode(int valueU) + { + this->MakeOrFindNode(valueU); + } + + void Graph::DFSOnGraphG() + { + this->_time = 0; + for (auto& iterator : this->_nodeMap) + { + if (iterator.second->color == WHITE) + { + this->DepthFirstSearchOnGraphG(iterator.second); + } + } + } + + void Graph::DFSOnGraphT() + { + for (auto& iterator : this->_nodeMap) + { + iterator.second->color = WHITE; + iterator.second->parent = nullptr; + } + + for (auto& iterator : this->_nodesFinishingTimeOrder) + { + if (iterator->color == WHITE) + { + vector connectedComponents; + this->DepthFirstSearchOnGraphT(iterator, connectedComponents); + this->_allConnectedComponents.push_back(connectedComponents); + } + } + } + + vector> Graph::FindAllStronglyConnectedComponents() + { + this->DFSOnGraphG(); + this->DFSOnGraphT(); + return this->_allConnectedComponents; + } +} \ No newline at end of file diff --git a/src/0003_graph/0005_HamiltonianPathAndCycle.cc b/src/0003_graph/0005_HamiltonianPathAndCycle.cc new file mode 100644 index 0000000..bfa99b5 --- /dev/null +++ b/src/0003_graph/0005_HamiltonianPathAndCycle.cc @@ -0,0 +1,114 @@ +#include "0005_HamiltonianPathAndCycle.h" + +using namespace std; +namespace HamiltonianPathAndCycle +{ + Node::Node(int value) + { + this->data = value; + this->isVisited = false; + } + + // Graph Private Member Methods + Node* Graph::MakeOrFindNode(int value) + { + Node* node = nullptr; + if (this->_nodeMap.find(value) == this->_nodeMap.end()) + { + node = new Node(value); + this->_nodeMap[value] = node; + } + else + { + node = this->_nodeMap[value]; + } + return node; + } + + bool Graph::IsSafe(Node* nodeU, Node* nodeV) + { + if (this->_adjlist[nodeU].find(nodeV) == this->_adjlist[nodeU].end()) + { + return false; + } + if (nodeV->isVisited == true) + { + return false; + } + return true; + } + + bool Graph::HamiltonianCycleAndPathUtil(Node* nodeU) + { + if (this->_visitedNodeCount == this->_nodeMap.size()) + { + if (this->_adjlist[nodeU].find(this->_startingNode) != this->_adjlist[nodeU].end()) + { + this->_isHamiltonianCyclePresent = true; + this->_isHamiltonianPathPresent = true; + return true; + } + this->_isHamiltonianPathPresent = true; + return false; + } + for (auto& nodeV : this->_adjlist[nodeU]) + { + if (this->IsSafe(nodeU, nodeV)) + { + this->_hamiltonianPath.push_back(nodeV->data); + nodeV->isVisited = true; + this->_visitedNodeCount++; + if (this->HamiltonianCycleAndPathUtil(nodeV)) + { + return true; + } + this->_visitedNodeCount--; + nodeV->isVisited = false; + this->_hamiltonianPath.pop_back(); + } + } + return false; + } + + // Graph Public Member Methods + void Graph::PushUndirectedEdge(int valueU, int valueV) + { + Node* nodeU = this->MakeOrFindNode(valueU); + Node* nodeV = this->MakeOrFindNode(valueV); + + this->_adjlist[nodeU].insert(nodeV); + this->_adjlist[nodeV].insert(nodeU); + } + + void Graph::PushSingleNode(int valueU) + { + this->MakeOrFindNode(valueU); + } + + void Graph::FindHamiltonianCycleAndPath() + { + this->_isHamiltonianCyclePresent = false; + this->_isHamiltonianPathPresent = false; + this->_hamiltonianPath = {}; + this->_startingNode = this->_nodeMap[0]; + this->_hamiltonianPath.push_back(this->_startingNode->data); + this->_startingNode->isVisited = true; + this->_visitedNodeCount = 1; + this->HamiltonianCycleAndPathUtil(this->_startingNode); + } + + bool Graph::IsHamiltonianCyclePresent() + { + return this->_isHamiltonianCyclePresent; + } + + bool Graph::IsHamiltonianPathPresent() + { + return this->_isHamiltonianPathPresent; + } + + vector Graph::GetHamiltonianPath() + { + return this->_hamiltonianPath; + } +} \ No newline at end of file diff --git a/src/0003_graph/0006_EulerianPathAndCircuit.cc b/src/0003_graph/0006_EulerianPathAndCircuit.cc new file mode 100644 index 0000000..ee132ca --- /dev/null +++ b/src/0003_graph/0006_EulerianPathAndCircuit.cc @@ -0,0 +1,212 @@ +#include "0006_EulerianPathAndCircuit.h" +#include +#include +using namespace std; + +namespace EulerianPathAndCircuit +{ + Node::Node(int value) + { + this->data = value; + this->degree = 0; + this->inDegree = 0; + this->outDegree = 0; + this->visited = false; + } + + // Graph Private Member Methods + Node* Graph::MakeOrFindNode(int value) + { + Node* node = nullptr; + if (this->_nodeMap.find(value) == this->_nodeMap.end()) + { + node = new Node(value); + this->_nodeMap[value] = node; + } + else + { + node = this->_nodeMap[value]; + } + return node; + } + + void Graph::DepthFirstSearch(Node* nodeU) + { + nodeU->visited = true; + for (auto& nodeV : this->_adjlist[nodeU]) + { + if (nodeV->visited == false) + { + this->DepthFirstSearch(nodeV); + } + } + } + + bool Graph::IsConnected() + { + // Step-1 : Make the visited property of all nodes as false. It is already done in constructor. + + // Step-2 : Find a node which do not have 0 degree. + Node* node = nullptr; + for (auto& iterator : this->_nodeMap) + { + if (iterator.second->degree != 0) + { + node = iterator.second; + break; + } + } + + // Step-3 : If node is null, it means G.E is null, so G is connected, else call DFS to traverse the graph G. + if (node == nullptr) + { + return true; + } + + this->DepthFirstSearch(node); + + // Step-4 : Checking if all the non-zero degree vertices have been visited or not. + for (auto& iterator : this->_nodeMap) + { + if (iterator.second->visited == false && iterator.second->degree != 0) + { + return false; + } + } + return true; + } + + void Graph::EulerianPathHierholzerAlgorithm(Node* startingNode) + { + stack currentPath; + currentPath.push(startingNode); + while (!currentPath.empty()) + { + Node* currentNode = currentPath.top(); + if (!this->_adjlist[currentNode].empty()) + { + Node* nextNode = this->_adjlist[currentNode].front(); + this->_adjlist[currentNode].pop_front(); + this->_adjlist[nextNode].remove(currentNode); + currentPath.push(nextNode); + } + else + { + currentPath.pop(); + this->_eulerianPath.push_back(currentNode->data); + } + } + } + + // Graph Public Member Methods + void Graph::PushUndirectedEdge(int valueU, int valueV) + { + Node* nodeU = this->MakeOrFindNode(valueU); + Node* nodeV = this->MakeOrFindNode(valueV); + + this->_adjlist[nodeU].push_back(nodeV); + nodeU->degree++; + this->_adjlist[nodeV].push_back(nodeU); + nodeV->degree++; + } + + void Graph::PushDirectedEdge(int valueU, int valueV) + { + Node* nodeU = this->MakeOrFindNode(valueU); + Node* nodeV = this->MakeOrFindNode(valueV); + + this->_adjlist[nodeU].push_back(nodeV); + nodeU->outDegree++; + nodeV->inDegree++; + } + + void Graph::PushSingleNode(int valueU) + { + this->MakeOrFindNode(valueU); + } + + void Graph::FindEulerianPathAndCircuit() + { + // If the graph is not connected then graph G is Not-Eulerian. + if (this->IsConnected() == false) + { + this->_isEulerianPathPresent = false; + this->_isEulerianCircuitPresent = false; + return; + } + + int oddDegreeVertexCount = 0; + for (auto& iterator : this->_nodeMap) + { + if (iterator.second->degree & 1) + { + oddDegreeVertexCount++; + } + } + + // Check-1 : When no vertex with odd degree is present, then graph G is Eulerian. + if (oddDegreeVertexCount == 0) + { + this->_isEulerianPathPresent = true; + this->_isEulerianCircuitPresent = true; + return; + } + + // Check-2 : When 2 vertices have odd degree, then graph G is Semi-Eulerian. + if (oddDegreeVertexCount == 2) + { + this->_isEulerianPathPresent = true; + this->_isEulerianCircuitPresent = false; + return; + } + + // Check-3 : When more than 2 vertices have odd degree, then graph G is Not Eulerian. + if (oddDegreeVertexCount > 2) + { + this->_isEulerianPathPresent = false; + this->_isEulerianCircuitPresent = false; + return; + } + } + + bool Graph::IsEulerianPathPresent() + { + return this->_isEulerianPathPresent; + } + + bool Graph::IsEulerianCircuitPresent() + { + return this->_isEulerianCircuitPresent; + } + + vector Graph::UndirectedGraphGetEulerianPath() + { + // Case-3 : When more than 2 vertices have odd degree, then the graph G is not Eulerian. + // No Eulerian Path is posible. + if (this->_isEulerianPathPresent == false) + { + return {}; + } + + // Now 2 cases remains. + // Case-2 : When 2 vertices have odd degree. Choose any one of them. + Node* node = nullptr; + for (auto& iterator : this->_nodeMap) + { + if (iterator.second->degree & 1) + { + node = iterator.second; + break; + } + } + + // Case-1 : When no vertex with odd degree is present. Choose any vertex as starting point. + if (node == nullptr) + { + node = this->_nodeMap[0]; + } + this->EulerianPathHierholzerAlgorithm(node); + reverse(this->_eulerianPath.begin(), this->_eulerianPath.end()); + return this->_eulerianPath; + } +} \ No newline at end of file diff --git a/src/0003_graph/0007_MinimumSpanningTreeKruskalAlgorithm.cc b/src/0003_graph/0007_MinimumSpanningTreeKruskalAlgorithm.cc new file mode 100644 index 0000000..20bea2b --- /dev/null +++ b/src/0003_graph/0007_MinimumSpanningTreeKruskalAlgorithm.cc @@ -0,0 +1,108 @@ +#include "0007_MinimumSpanningTreeKruskalAlgorithm.h" +#include +#include +using namespace std; + +namespace MinimumSpanningTreeKruskalAlgorithm +{ + Node::Node(int data) + { + this->data = data; + this->parent = nullptr; + this->rank = INT_MAX; + } + + Edge::Edge(Node* nodeU, Node* nodeV, int weight) + { + this->nodeU = nodeU; + this->nodeV = nodeV; + this->weight = weight; + } + + // Graph Private Member Methods + Node* Graph::MakeOrFindNode(int data) + { + Node* node = nullptr; + if (this->_nodeMap.find(data) == this->_nodeMap.end()) + { + node = new Node(data); + this->_nodeMap[data] = node; + } + else + { + node = this->_nodeMap[data]; + } + return node; + } + + void Graph::MakeSet(Node* node) + { + node->parent = node; + node->rank = 0; + } + + void Graph::Union(Node* nodeU, Node* nodeV) + { + this->Link(this->FindSet(nodeU), this->FindSet(nodeV)); + } + + void Graph::Link(Node* nodeU, Node* nodeV) + { + if (nodeV->rank > nodeU->rank) + { + nodeU->parent = nodeV; + } + else + { + nodeV->parent = nodeU; + if (nodeU->rank == nodeV->rank) + { + nodeU->rank += 1; + } + } + } + + Node* Graph::FindSet(Node* node) + { + if (node != node->parent) + { + node->parent = this->FindSet(node->parent); + } + return node->parent; + } + + // Graph Public Member Methods + void Graph::PushUndirectedEdge(int dataU, int dataV, int weight) + { + Node* nodeU = this->MakeOrFindNode(dataU); + Node* nodeV = this->MakeOrFindNode(dataV); + + this->_adjlist[nodeU].push_back(nodeV); + this->_adjlist[nodeV].push_back(nodeU); + this->_edgeList.push_back(new Edge(nodeU, nodeV, weight)); + } + + void Graph::FindMinimumSpanningTreeKruskalAlgorithm() + { + for (auto& iterator : this->_nodeMap) + { + this->MakeSet(iterator.second); + } + + sort(this->_edgeList.begin(), this->_edgeList.end(), [](Edge* edgeX, Edge* edgeY) { return edgeX->weight < edgeY->weight; }); + + for (auto& edge : this->_edgeList) + { + if (this->FindSet(edge->nodeU) != this->FindSet(edge->nodeV)) + { + this->Union(edge->nodeU, edge->nodeV); + this->_minimumSpanningTree.push_back({ {edge->nodeU->data, edge->nodeV->data}, edge->weight }); + } + } + } + + vector, int>> Graph::GetMinimumSpanningTree() + { + return this->_minimumSpanningTree; + } +} \ No newline at end of file diff --git a/src/0003_graph/0008_MinimumSpanningTreePrimAlgorithm.cc b/src/0003_graph/0008_MinimumSpanningTreePrimAlgorithm.cc new file mode 100644 index 0000000..1b36027 --- /dev/null +++ b/src/0003_graph/0008_MinimumSpanningTreePrimAlgorithm.cc @@ -0,0 +1,85 @@ +#include "0008_MinimumSpanningTreePrimAlgorithm.h" +#include +using namespace std; + + +namespace MinimumSpanningTreePrimAlgorithm +{ + Node::Node(int data) + { + this->data = data; + this->parent = nullptr; + this->key = INT_MAX; + this->isInOperationalSet = false; + } + + // Graph Private Member Methods + Node* Graph::MakeOrFindNode(int data) + { + Node* node = nullptr; + if (this->_nodeMap.find(data) == this->_nodeMap.end()) + { + node = new Node(data); + this->_nodeMap[data] = node; + } + else + { + node = this->_nodeMap[data]; + } + return node; + } + + // Graph Public Member Methods + void Graph::PushUndirectedEdge(int dataU, int dataV, int weight) + { + Node* nodeU = this->MakeOrFindNode(dataU); + Node* nodeV = this->MakeOrFindNode(dataV); + + this->_adjlist[nodeU].push_back({nodeV, weight}); + this->_adjlist[nodeV].push_back({nodeU, weight}); + } + + void Graph::FindMinimumSpanningTreePrimAlgorithm() + { + Node* root = this->_nodeMap.begin()->second; + + root->key = 0; + for (auto& iterator : this->_nodeMap) + { + iterator.second->isInOperationalSet = true; + this->_operationalSet.insert(iterator.second); + } + + while (!this->_operationalSet.empty()) + { + Node* nodeU = *(this->_operationalSet.begin()); + this->_operationalSet.erase(nodeU); + nodeU->isInOperationalSet = false; + + for (auto& iterator : this->_adjlist[nodeU]) + { + Node* nodeV = iterator.first; + int weight = iterator.second; + + if (nodeV->isInOperationalSet && weight < nodeV->key) + { + this->_operationalSet.erase(nodeV); + nodeV->key = weight; + nodeV->parent = nodeU; + this->_operationalSet.insert(nodeV); + + } + } + + if (nodeU->parent != nullptr) + { + this->_minimumSpanningTree.push_back({ {nodeU->parent->data, nodeU->data}, nodeU->key }); + } + } + } + + vector, int>> Graph::GetMinimumSpanningTree() + { + return this->_minimumSpanningTree; + } +} \ No newline at end of file diff --git a/src/0003_graph/0009_SingleSourceShortestPathBellmanFord.cc b/src/0003_graph/0009_SingleSourceShortestPathBellmanFord.cc new file mode 100644 index 0000000..b059b74 --- /dev/null +++ b/src/0003_graph/0009_SingleSourceShortestPathBellmanFord.cc @@ -0,0 +1,108 @@ +#include "0009_SingleSourceShortestPathBellmanFord.h" +#include +#include +using namespace std; + +namespace SingleSourceShortestPathBellmanFord +{ + Node::Node(int data) + { + this->data = data; + this->distance = INT_MAX; + this->parent = nullptr; + } + + Edge::Edge(Node* nodeU, Node* nodeV, int weight) + { + this->nodeU = nodeU; + this->nodeV = nodeV; + this->weight = weight; + } + + // Graph Private Member Methods + Node* Graph::MakeOrFindNode(int data) + { + Node* node = nullptr; + if (this->_nodeMap.find(data) == this->_nodeMap.end()) + { + node = new Node(data); + this->_nodeMap[data] = node; + } + else + { + node = this->_nodeMap[data]; + } + return node; + } + + void Graph :: InitializeSingleSource(Node* sourceNode) + { + for (auto& iterator : this->_nodeMap) + { + iterator.second->distance = INT_MAX; + iterator.second->parent = nullptr; + } + sourceNode->distance = 0; + } + + void Graph::Relax(Edge* edge) + { + if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) + { + edge->nodeV->distance = edge->nodeU->distance + edge->weight; + edge->nodeV->parent = edge->nodeU; + } + } + + void Graph::GetShortestPath(Node* node, vector& path) + { + path.push_back(node->data); + if (node->parent != nullptr) + { + this->GetShortestPath(node->parent, path); + } + } + + // Graph Public Member Methods + void Graph::PushDirectedEdge(int dataU, int dataV, int weight) + { + Node* nodeU = this->MakeOrFindNode(dataU); + Node* nodeV = this->MakeOrFindNode(dataV); + + this->_adjlist[nodeU].push_back(nodeV); + this->_edgeList.push_back(new Edge(nodeU, nodeV, weight)); + } + + bool Graph::FindSingleSourceShortestPathBellmanFord(int data) + { + Node* source = this->_nodeMap[data]; + + this->InitializeSingleSource(source); + + for (int i = 0; i < this->_nodeMap.size() - 1; i++) + { + for (auto& edge : this->_edgeList) + { + this->Relax(edge); + } + } + + for (auto& edge : this->_edgeList) + { + if (edge->nodeV->distance > (edge->nodeU->distance + edge->weight)) + { + return false; + } + } + return true; + } + + vector Graph::GetShortestPathBellmanFord(int data) + { + vector path = {}; + Node* node = this->_nodeMap[data]; + this->GetShortestPath(node, path); + reverse(path.begin(), path.end()); + return path; + } +} \ No newline at end of file diff --git a/src/0003_graph/0010_DirectedAcyclicGraphShortestPath.cc b/src/0003_graph/0010_DirectedAcyclicGraphShortestPath.cc new file mode 100644 index 0000000..8f4cd81 --- /dev/null +++ b/src/0003_graph/0010_DirectedAcyclicGraphShortestPath.cc @@ -0,0 +1,124 @@ +#include "0010_DirectedAcyclicGraphShortestPath.h" +#include +#include +using namespace std; + +namespace DirectedAcyclicGraphShortestPath +{ + Node::Node(int data) + { + this->data = data; + this->color = WHITE; + this->distance = INT_MAX; + this->parent = nullptr; + } + + Edge::Edge(Node* nodeU, Node* nodeV, int weight) + { + this->nodeU = nodeU; + this->nodeV = nodeV; + this->weight = weight; + } + + // Graph Private Member Methods + Node* Graph::MakeOrFindNode(int data) + { + Node* node = nullptr; + if (this->_nodeMap.find(data) == this->_nodeMap.end()) + { + node = new Node(data); + this->_nodeMap[data] = node; + } + else + { + node = this->_nodeMap[data]; + } + return node; + } + + void Graph::DepthFirstSearch(Node* nodeU) + { + nodeU->color = GRAY; + for (auto& nodeV : this->_adjlist[nodeU]) + { + if (nodeV->color == WHITE) + { + this->DepthFirstSearch(nodeV); + } + } + nodeU->color = BLACK; + this->_topologicalSortedNodeList.push_front(nodeU); + } + + void Graph::TopologicalSort() + { + for (auto& iterator : this->_nodeMap) + { + if (iterator.second->color == WHITE) + { + this->DepthFirstSearch(iterator.second); + } + } + } + + void Graph::InitializeSingleSource(Node* sourceNode) + { + for (auto& iterator : this->_nodeMap) + { + iterator.second->distance = INT_MAX; + iterator.second->parent = nullptr; + } + sourceNode->distance = 0; + } + + void Graph::Relax(Edge* edge) + { + if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) + { + edge->nodeV->distance = edge->nodeU->distance + edge->weight; + edge->nodeV->parent = edge->nodeU; + } + } + + void Graph::GetShortestPath(Node* node, vector& path) + { + path.push_back(node->data); + if (node->parent != nullptr) + { + this->GetShortestPath(node->parent, path); + } + } + + // Graph Public Member Methods + void Graph::PushDirectedEdge(int dataU, int dataV, int weight) + { + Node* nodeU = this->MakeOrFindNode(dataU); + Node* nodeV = this->MakeOrFindNode(dataV); + + this->_adjlist[nodeU].push_back(nodeV); + this->_edgeMap[nodeU].push_back(new Edge(nodeU, nodeV, weight)); + } + + void Graph::FindDAGShortestPath(int data) + { + this->TopologicalSort(); + Node* source = this->_nodeMap[data]; + this->InitializeSingleSource(source); + for (auto& node : this->_topologicalSortedNodeList) + { + for (auto& edge : this->_edgeMap[node]) + { + this->Relax(edge); + } + } + } + + vector Graph::GetDAGShortestPath(int data) + { + vector path = {}; + Node* node = this->_nodeMap[data]; + this->GetShortestPath(node, path); + reverse(path.begin(), path.end()); + return path; + } +} \ No newline at end of file diff --git a/src/0003_graph/0011_SingleSourceShortestPathDijkstra.cc b/src/0003_graph/0011_SingleSourceShortestPathDijkstra.cc new file mode 100644 index 0000000..e796e37 --- /dev/null +++ b/src/0003_graph/0011_SingleSourceShortestPathDijkstra.cc @@ -0,0 +1,113 @@ +#include "0011_SingleSourceShortestPathDijkstra.h" +#include +#include +using namespace std; + +namespace SingleSourceShortestPathDijkstra +{ + Node::Node(int data) + { + this->data = data; + this->distance = INT_MAX; + this->parent = nullptr; + } + + Edge::Edge(Node* nodeU, Node* nodeV, int weight) + { + this->nodeU = nodeU; + this->nodeV = nodeV; + this->weight = weight; + } + + // Graph Private Member Methods + Node* Graph::MakeOrFindNode(int data) + { + Node* node = nullptr; + if (this->_nodeMap.find(data) == this->_nodeMap.end()) + { + node = new Node(data); + this->_nodeMap[data] = node; + } + else + { + node = this->_nodeMap[data]; + } + return node; + } + + void Graph::InitializeSingleSource(Node* sourceNode) + { + for (auto& iterator : this->_nodeMap) + { + iterator.second->distance = INT_MAX; + iterator.second->parent = nullptr; + } + sourceNode->distance = 0; + } + + void Graph::Relax(Edge* edge) + { + if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) + { + this->_operationalSet.erase(edge->nodeV); + edge->nodeV->distance = edge->nodeU->distance + edge->weight; + edge->nodeV->parent = edge->nodeU; + this->_operationalSet.insert(edge->nodeV); + } + } + + void Graph::Dijkstra(Node* source) + { + this->InitializeSingleSource(source); + + for (auto& node : this->_nodeMap) + { + this->_operationalSet.insert(node.second); + } + + while (!this->_operationalSet.empty()) + { + Node* nodeU = *(this->_operationalSet.begin()); + this->_operationalSet.erase(nodeU); + + for (auto& edge : this->_edgeMap[nodeU]) + { + this->Relax(edge); + } + } + } + + void Graph::GetShortestPath(Node* node, vector& path) + { + path.push_back(node->data); + if (node->parent != nullptr) + { + this->GetShortestPath(node->parent, path); + } + } + + // Graph Public Member Methods + void Graph::PushDirectedEdge(int dataU, int dataV, int weight) + { + Node* nodeU = this->MakeOrFindNode(dataU); + Node* nodeV = this->MakeOrFindNode(dataV); + + this->_adjlist[nodeU].push_back(nodeV); + this->_edgeMap[nodeU].push_back(new Edge(nodeU, nodeV, weight)); + } + + void Graph::FindShortestPathDijkstra(int data) + { + Node* source = this->_nodeMap[data]; + this->Dijkstra(source); + } + + vector Graph::GetDijkstraShortestPath(int data) + { + vector path = {}; + Node* node = this->_nodeMap[data]; + this->GetShortestPath(node, path); + reverse(path.begin(), path.end()); + return path; + } +} \ No newline at end of file diff --git a/src/0003_graph/0012_DifferenceConstraintsShortestPaths.cc b/src/0003_graph/0012_DifferenceConstraintsShortestPaths.cc new file mode 100644 index 0000000..8764ba6 --- /dev/null +++ b/src/0003_graph/0012_DifferenceConstraintsShortestPaths.cc @@ -0,0 +1,133 @@ +#include "0012_DifferenceConstraintsShortestPaths.h" +#include +using namespace std; + +namespace DifferenceConstraintsShortestPaths +{ + Node::Node(string data) + { + this->data = data; + this->distance = INT_MAX; + } + + Edge::Edge(Node* nodeU, Node* nodeV, int weight) + { + this->nodeU = nodeU; + this->nodeV = nodeV; + this->weight = weight; + } + + // Graph Private Member Methods + Node* Graph::MakeOrFindNode(string data) + { + Node* node = nullptr; + if (this->_nodeMap.find(data) == this->_nodeMap.end()) + { + node = new Node(data); + this->_nodeMap[data] = node; + } + else + { + node = this->_nodeMap[data]; + } + return node; + } + + void Graph::PushDirectedEdge(string dataU, string dataV, int weight) + { + Node* nodeU = this->MakeOrFindNode(dataU); + Node* nodeV = this->MakeOrFindNode(dataV); + + this->_adjlist[nodeU].push_back(nodeV); + this->_edgeList.push_back(new Edge(nodeU, nodeV, weight)); + } + + void Graph::InitializeSingleSource(Node* sourceNode) + { + for (auto& iterator : this->_nodeMap) + { + iterator.second->distance = INT_MAX; + } + sourceNode->distance = 0; + } + + void Graph::Relax(Edge* edge) + { + if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) + { + edge->nodeV->distance = edge->nodeU->distance + edge->weight; + } + } + + // Graph Public Member Methods + void Graph::PushAllDirectedEdges(vector> vectorA, vector vectorX, vector vectorB) + { + // Creating the Actual Graph + string valueU = ""; + string valueV = ""; + int weight = 0; + for (int i = 0; i < vectorA.size(); i++) + { + for (int j = 0; j < vectorX.size(); j++) + { + if (vectorA[i][j] == 1) + { + valueV= vectorX[j]; + } + if (vectorA[i][j] == -1) + { + valueU = vectorX[j]; + } + } + weight = vectorB[i]; + this->PushDirectedEdge(valueU, valueV, weight); + } + + // Creating all the edges from the additional vertex + valueU = ""; + valueV = ""; + weight = 0; + for (int i = 0; i < vectorX.size(); i++) + { + valueV = vectorX[i]; + this->PushDirectedEdge(valueU, valueV, weight); + } + } + + bool Graph::FindDifferenceConstraintsSolutionBellmanFord() + { + Node* source = this->_nodeMap[""]; + + this->InitializeSingleSource(source); + + for (int i = 0; i < this->_nodeMap.size(); i++) + { + for (auto& edge : this->_edgeList) + { + this->Relax(edge); + } + } + + for (auto& edge : this->_edgeList) + { + if (edge->nodeV->distance > (edge->nodeU->distance + edge->weight)) + { + return false; + } + } + return true; + } + + vector> Graph::GetDifferenceConstrtaintsSolution() + { + vector> result; + for (auto& node : this->_nodeMap) + { + if (node.second->data != "") + { + result.push_back({ node.second->data, node.second->distance }); + } + } + return result; + } +} \ No newline at end of file diff --git a/src/0003_graph/0013_AllPairsShortestPathsFloydWarshall.cc b/src/0003_graph/0013_AllPairsShortestPathsFloydWarshall.cc new file mode 100644 index 0000000..ffd51d9 --- /dev/null +++ b/src/0003_graph/0013_AllPairsShortestPathsFloydWarshall.cc @@ -0,0 +1,104 @@ +#include "0013_AllPairsShortestPathsFloydWarshall.h" +#include +using namespace std; + +namespace AllPairsShortestPathsFloydWarshall +{ + // Graph Private Member Methods + void Graph::InitializeDistanceAndPredecessors() + { + this->_shortestPathMatrixFloydWarshall = this->_adjMatrix; + + for (int i = 0; i < this->_noOfVertices; i++) + { + for (int j = 0; j < this->_noOfVertices; j++) + { + if ((i == j) || this->_adjMatrix[i][j] == INT_MAX) + { + this->_predecessorMatrix[i][j] = -1; + } + else + { + this->_predecessorMatrix[i][j] = i + 1; + } + } + } + } + + void Graph::GetShortestPath(int source, int destination, vector& path) + { + if (this->_predecessorMatrix[source - 1][destination - 1] != source) + { + int predecessor = this->_predecessorMatrix[source - 1][destination - 1]; + this->GetShortestPath(source, predecessor, path); + path.push_back(predecessor); + } + } + + // Graph Public Member Methods + void Graph::CreateGraph(int noOfVertices) + { + this->_noOfVertices = noOfVertices; + this->_adjMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, INT_MAX)); + this->_shortestPathMatrixFloydWarshall = vector>(this->_noOfVertices, vector(this->_noOfVertices, INT_MAX)); + this->_predecessorMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, INT_MAX)); + + for (int i = 0; i < this->_noOfVertices; i++) + { + for (int j = 0; j < this->_noOfVertices; j++) + { + if (i == j) + { + this->_adjMatrix[i][j] = 0; + } + } + } + } + + void Graph::PushDirectedEdge(int valueU, int valueV, int weight) + { + this->_adjMatrix[valueU - 1][valueV - 1] = weight; + } + + void Graph::FindAllPairsShortestPathsFloydWarshallSolution() + { + this->InitializeDistanceAndPredecessors(); + + for (int k = 0; k < this->_noOfVertices; k++) + { + for (int i = 0; i < this->_noOfVertices; i++) + { + for (int j = 0; j < this->_noOfVertices; j++) + { + if ((this->_shortestPathMatrixFloydWarshall[i][j] > (this->_shortestPathMatrixFloydWarshall[i][k] + this->_shortestPathMatrixFloydWarshall[k][j])) + && + (this->_shortestPathMatrixFloydWarshall[i][k] != INT_MAX && this->_shortestPathMatrixFloydWarshall[k][j] != INT_MAX)) + { + this->_shortestPathMatrixFloydWarshall[i][j] = this->_shortestPathMatrixFloydWarshall[i][k] + this->_shortestPathMatrixFloydWarshall[k][j]; + this->_predecessorMatrix[i][j] = this->_predecessorMatrix[k][j]; + } + } + } + } + } + + vector> Graph::GetFloydWarshallShortestPath() + { + vector> result; + for (int i = 0; i < this->_noOfVertices; i++) + { + for (int j = 0; j < this->_noOfVertices; j++) + { + if (i != j) + { + vector path = {}; + path.push_back(i + 1); + this->GetShortestPath(i + 1, j + 1, path); + path.push_back(j + 1); + result.push_back(path); + } + } + } + return result; + } +} \ No newline at end of file diff --git a/src/0003_graph/0014_AllPairsShortestPathsJohnson.cc b/src/0003_graph/0014_AllPairsShortestPathsJohnson.cc new file mode 100644 index 0000000..e9f9ab2 --- /dev/null +++ b/src/0003_graph/0014_AllPairsShortestPathsJohnson.cc @@ -0,0 +1,217 @@ +#include "0014_AllPairsShortestPathsJohnson.h" +#include +using namespace std; + +namespace AllPairsShortestPathsJohnson +{ + Node::Node(int data) + { + this->data = data; + this->distance = INT_MAX; + this->parent = nullptr; + this->potentialWeight = 0; + } + + Edge::Edge(Node* nodeU, Node* nodeV, int weight) + { + this->nodeU = nodeU; + this->nodeV = nodeV; + this->weight = weight; + } + + // Graph Private Member Methods + Node* Graph::MakeOrFindNode(int data) + { + Node* node = nullptr; + if (this->_nodeMap.find(data) == this->_nodeMap.end()) + { + node = new Node(data); + this->_nodeMap[data] = node; + } + else + { + node = this->_nodeMap[data]; + } + return node; + } + + void Graph::PushAugmentedDirectedEdges(Node* sourceNode, Node* nodeV, int weight) + { + this->_augmentedAdjlist[sourceNode].push_back(nodeV); + this->_augmentedEdgeList.push_back(new Edge(sourceNode, nodeV, weight)); + } + + void Graph::InitializeSingleSource(Node* sourceNode) + { + for (auto& iterator : this->_nodeMap) + { + iterator.second->distance = INT_MAX; + iterator.second->parent = nullptr; + } + sourceNode->distance = 0; + } + + void Graph::RelaxBellmanFord(Edge* edge) + { + if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) + { + edge->nodeV->distance = edge->nodeU->distance + edge->weight; + edge->nodeV->parent = edge->nodeU; + } + } + + bool Graph::BellmanFord(Node* source) + { + this->InitializeSingleSource(source); + + for (int i = 0; i < this->_nodeMap.size() - 1; i++) + { + for (auto& edge : this->_augmentedEdgeList) + { + this->RelaxBellmanFord(edge); + } + } + + for (auto& edge : this->_augmentedEdgeList) + { + if (edge->nodeV->distance > (edge->nodeU->distance + edge->weight)) + { + return false; + } + } + return true; + } + + void Graph::RelaxDijkstra(Edge* edge) + { + if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) + { + this->_operationalSet.erase(edge->nodeV); + edge->nodeV->distance = edge->nodeU->distance + edge->weight; + edge->nodeV->parent = edge->nodeU; + this->_operationalSet.insert(edge->nodeV); + } + } + + void Graph::Dijkstra(Node* source) + { + this->InitializeSingleSource(source); + + for (auto& node : this->_nodeMap) + { + this->_operationalSet.insert(node.second); + } + + while (!this->_operationalSet.empty()) + { + Node* nodeU = *(this->_operationalSet.begin()); + this->_operationalSet.erase(nodeU); + + for (auto& edge : this->_edgeMap[nodeU]) + { + this->RelaxDijkstra(edge); + } + } + } + + void Graph::GetShortestPath(int source, int destination, vector& path) + { + if (this->_predecessorMatrix[source - 1][destination - 1] != source) + { + int predecessor = this->_predecessorMatrix[source - 1][destination - 1]; + this->GetShortestPath(source, predecessor, path); + path.push_back(predecessor); + } + } + + // Graph Public Member Methods + void Graph::PushDirectedEdge(int dataU, int dataV, int weight) + { + Node* nodeU = this->MakeOrFindNode(dataU); + Node* nodeV = this->MakeOrFindNode(dataV); + + this->_adjlist[nodeU].push_back(nodeV); + Edge* edge = new Edge(nodeU, nodeV, weight); + this->_edgeMap[nodeU].push_back(edge); + this->_edgeList.push_back(edge); + } + + bool Graph::FindAllPairsShortestPathsJohnsonAlgorithm() + { + // Creating the graph G' + this->_augmentedAdjlist = this->_adjlist; + this->_augmentedEdgeList = this->_edgeList; + + // Source Node s + Node* source = new Node(0); + this->_nodeMap[0] = source; + + // Creating all the augmented edges in G'.E = G.E U {(s, v) : v in G.V + for (auto& node : this->_nodeMap) + { + if (node.second != source) + { + this->PushAugmentedDirectedEdges(source, node.second, 0); + } + } + + if (this->BellmanFord(source) == false) + { + return false; + } + else + { + this->_nodeMap.erase(0); + for (auto& node : this->_nodeMap) + { + node.second->potentialWeight = node.second->distance; + } + + for (auto& edge : this->_edgeList) + { + edge->weight = edge->weight + edge->nodeU->potentialWeight - edge->nodeV->potentialWeight; + } + + this->_noOfVertices = (int)this->_nodeMap.size(); + this->_shortestPathMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, -1)); + this->_predecessorMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, -1)); + for (auto& iteratorU : this->_nodeMap) + { + Node* nodeU = iteratorU.second; + this->Dijkstra(nodeU); + for (auto& iteratorV : this->_nodeMap) + { + Node* nodeV = iteratorV.second; + this->_shortestPathMatrix[nodeU->data - 1][nodeV->data - 1] = nodeV->distance + nodeV->potentialWeight - nodeU->potentialWeight; + this->_predecessorMatrix[nodeU->data - 1][nodeV->data - 1] = nodeV->parent != nullptr ? nodeV->parent->data : -1; + } + } + return true; + } + } + + vector> Graph::GetAllPairsShortestPathsDistanceMatrix() + { + return this->_shortestPathMatrix; + } + + vector> Graph::GetAllPairsShortestPathsPathMatrix() + { + vector> result; + for (int i = 0; i < this->_noOfVertices; i++) + { + for (int j = 0; j < this->_noOfVertices; j++) + { + if (i != j) + { + vector path = {}; + path.push_back(i + 1); + this->GetShortestPath(i + 1, j + 1, path); + path.push_back(j + 1); + result.push_back(path); + } + } + } + return result; + } +} \ No newline at end of file diff --git a/src/0003_graph/0015_MaximumFlowFordFulkerson.cc b/src/0003_graph/0015_MaximumFlowFordFulkerson.cc new file mode 100644 index 0000000..dd8d48d --- /dev/null +++ b/src/0003_graph/0015_MaximumFlowFordFulkerson.cc @@ -0,0 +1,139 @@ +#include "0015_MaximumFlowFordFulkerson.h" +#include +using namespace std; + +namespace MaximumFlowFordFulkerson +{ + // Graph Private Member Methods + void Graph::ResolveAntiParallelEdges() + { + int countParallelEdges = 0; + for (int i = 0; i < this->_noOfVertices; i++) + { + for (int j = 0; j < this->_noOfVertices; j++) + { + if (this->_adjMatrix[i][j] > 0 && this->_adjMatrix[j][i] > 0) + { + countParallelEdges++; + } + } + } + + // As i->j and j->i both edges has been counted, actual count is count = count / 2 + countParallelEdges /= 2; + + this->_flagParallelEdges = countParallelEdges > 0; + + // If there are no anti-parallel edges, no need to modify the adjMatrix + if (!this->_flagParallelEdges) + { + return; + } + + int newNoOfVertices = this->_noOfVertices + countParallelEdges; + + // Modifying the adjMatrix + for (auto& edge : this->_adjMatrix) + { + edge.resize(newNoOfVertices, 0); + } + int k = this->_noOfVertices; + this->_visited.resize(newNoOfVertices, false); + this->_parent.resize(newNoOfVertices, -1); + this->_adjMatrix.resize(newNoOfVertices, vector(newNoOfVertices, 0)); + + // Removing the anti-parallel edges by adding new nodes + for (int i = 0; i < this->_noOfVertices; i++) + { + for (int j = 0; j < this->_noOfVertices; j++) + { + if (this->_adjMatrix[i][j] > 0 && this->_adjMatrix[j][i] > 0) + { + this->_adjMatrix[i][k] = this->_adjMatrix[i][j]; + this->_adjMatrix[k][j] = this->_adjMatrix[i][j]; + this->_adjMatrix[i][j] = 0; + k++; + } + } + } + + // Updating the total no of vertices after modifying the adjMatrix + this->_noOfVertices = newNoOfVertices; + } + + void Graph::DepthFirstSearchVisit(int nodeU) + { + this->_visited[nodeU] = true; + for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) + { + if (!this->_visited[nodeV] && this->_residualGraph[nodeU][nodeV] > 0) + { + this->_parent[nodeV] = nodeU; + this->DepthFirstSearchVisit(nodeV); + } + } + } + + bool Graph::DepthFirstSearch() + { + // Resetting the visited values + fill(this->_visited.begin(), this->_visited.end(), false); + + // Resetting the parent values + fill(this->_parent.begin(), this->_parent.end(), -1); + + // Starting the DepthFirstSearch from the source vertex + this->DepthFirstSearchVisit(this->_source); + + // Returning the visited value of the sink vertex, initially it was set to false + return this->_visited[this->_sink]; + } + + // Graph Public Member Methods + void Graph::CreateGraph(int noOfVertices) + { + this->_noOfVertices = noOfVertices; + this->_source = 0; + this->_sink = this->_noOfVertices - 1; + this->_maximumFlow = 0; + this->_flagParallelEdges = false; + this->_adjMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, 0)); + this->_parent = vector(this->_noOfVertices, -1); + this->_visited = vector(this->_noOfVertices, false); + } + + void Graph::PushDirectedEdge(int valueU, int valueV, int capacity) + { + this->_adjMatrix[valueU][valueV] = capacity; + } + + int Graph::FindMaximumFlowFordFulkerson() + { + // Resolving all the parallel edges if present + this->ResolveAntiParallelEdges(); + this->_residualGraph = this->_adjMatrix; + + // While there exists a path p from source to sink in the residual network G' + while (this->DepthFirstSearch()) + { + int augmentedPathFlow = INT_MAX; + + // Calculating c'(p) = min{ c'(u,v) : (u,v) is in p } + for (int nodeV = this->_sink; nodeV > this->_source; nodeV = this->_parent[nodeV]) + { + int nodeU = this->_parent[nodeV]; + augmentedPathFlow = min(augmentedPathFlow, this->_residualGraph[nodeU][nodeV]); + } + + for (int nodeV = this->_sink; nodeV > this->_source; nodeV = this->_parent[nodeV]) + { + int nodeU = this->_parent[nodeV]; + this->_residualGraph[nodeU][nodeV] -= augmentedPathFlow; + this->_residualGraph[nodeV][nodeU] += augmentedPathFlow; + } + this->_maximumFlow += augmentedPathFlow; + } + + return this->_maximumFlow; + } +} \ No newline at end of file diff --git a/src/0003_graph/0016_MaximumFlowEdmondsKarp.cc b/src/0003_graph/0016_MaximumFlowEdmondsKarp.cc new file mode 100644 index 0000000..627a2a6 --- /dev/null +++ b/src/0003_graph/0016_MaximumFlowEdmondsKarp.cc @@ -0,0 +1,144 @@ +#include "0016_MaximumFlowEdmondsKarp.h" +#include +#include +using namespace std; + +namespace MaximumFlowEdmondsKarp +{ + // Graph Private Member Methods + void Graph::ResolveAntiParallelEdges() + { + int countParallelEdges = 0; + for (int i = 0; i < this->_noOfVertices; i++) + { + for (int j = 0; j < this->_noOfVertices; j++) + { + if (this->_adjMatrix[i][j] > 0 && this->_adjMatrix[j][i] > 0) + { + countParallelEdges++; + } + } + } + + // As i->j and j->i both edges has been counted, actual count is count = count / 2 + countParallelEdges /= 2; + + this->_flagParallelEdges = countParallelEdges > 0; + + // If there are no anti-parallel edges, no need to modify the adjMatrix + if (!this->_flagParallelEdges) + { + return; + } + + int newNoOfVertices = this->_noOfVertices + countParallelEdges; + + // Modifying the adjMatrix + for (auto& edge : this->_adjMatrix) + { + edge.resize(newNoOfVertices, 0); + } + int k = this->_noOfVertices; + this->_visited.resize(newNoOfVertices, false); + this->_parent.resize(newNoOfVertices, -1); + this->_adjMatrix.resize(newNoOfVertices, vector(newNoOfVertices, 0)); + + // Removing the anti-parallel edges by adding new nodes + for (int i = 0; i < this->_noOfVertices; i++) + { + for (int j = 0; j < this->_noOfVertices; j++) + { + if (this->_adjMatrix[i][j] > 0 && this->_adjMatrix[j][i] > 0) + { + this->_adjMatrix[i][k] = this->_adjMatrix[i][j]; + this->_adjMatrix[k][j] = this->_adjMatrix[i][j]; + this->_adjMatrix[i][j] = 0; + k++; + } + } + } + + // Updating the total no of vertices after modifying the adjMatrix + this->_noOfVertices = newNoOfVertices; + } + + bool Graph::BreadthFirstSearch() + { + // Resetting the visited values + fill(this->_visited.begin(), this->_visited.end(), false); + + // Resetting the parent values + fill(this->_parent.begin(), this->_parent.end(), -1); + + queue nodeQueue; + nodeQueue.push(this->_source); + this->_visited[this->_source] = true; + + while (!nodeQueue.empty()) + { + int nodeU = nodeQueue.front(); + nodeQueue.pop(); + + for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) + { + if (!this->_visited[nodeV] && this->_residualGraph[nodeU][nodeV] > 0) + { + this->_parent[nodeV] = nodeU; + this->_visited[nodeV] = true; + nodeQueue.push(nodeV); + } + } + } + + // Returning the visited value of the sink vertex, initially it was set to false + return this->_visited[this->_sink]; + } + + // Graph Public Member Methods + void Graph::CreateGraph(int noOfVertices) + { + this->_noOfVertices = noOfVertices; + this->_source = 0; + this->_sink = this->_noOfVertices - 1; + this->_maximumFlow = 0; + this->_flagParallelEdges = false; + this->_adjMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, 0)); + this->_parent = vector(this->_noOfVertices, -1); + this->_visited = vector(this->_noOfVertices, false); + } + + void Graph::PushDirectedEdge(int valueU, int valueV, int capacity) + { + this->_adjMatrix[valueU][valueV] = capacity; + } + + int Graph::FindMaximumFlowEdmondsKarp() + { + // Resolving all the parallel edges if present + this->ResolveAntiParallelEdges(); + this->_residualGraph = this->_adjMatrix; + + // While there exists a path p from source to sink in the residual network G' + while (this->BreadthFirstSearch()) + { + int augmentedPathFlow = INT_MAX; + + // Calculating c'(p) = min{ c'(u,v) : (u,v) is in p } + for (int nodeV = this->_sink; nodeV > this->_source; nodeV = this->_parent[nodeV]) + { + int nodeU = this->_parent[nodeV]; + augmentedPathFlow = min(augmentedPathFlow, this->_residualGraph[nodeU][nodeV]); + } + + for (int nodeV = this->_sink; nodeV > this->_source; nodeV = this->_parent[nodeV]) + { + int nodeU = this->_parent[nodeV]; + this->_residualGraph[nodeU][nodeV] -= augmentedPathFlow; + this->_residualGraph[nodeV][nodeU] += augmentedPathFlow; + } + this->_maximumFlow += augmentedPathFlow; + } + + return this->_maximumFlow; + } +} \ No newline at end of file diff --git a/src/0003_graph/0017_MaximumBipartiteMatching.cc b/src/0003_graph/0017_MaximumBipartiteMatching.cc new file mode 100644 index 0000000..7c55ce6 --- /dev/null +++ b/src/0003_graph/0017_MaximumBipartiteMatching.cc @@ -0,0 +1,263 @@ +#include "0017_MaximumBipartiteMatching.h" +#include +#include +using namespace std; + +namespace MaximumBipartiteMatching +{ + // Graph Private Member Methods + void Graph::ResolveAntiParallelEdges() + { + int countParallelEdges = 0; + for (int i = 0; i < this->_noOfVertices; i++) + { + for (int j = 0; j < this->_noOfVertices; j++) + { + if (this->_adjMatrix[i][j] > 0 && this->_adjMatrix[j][i] > 0) + { + countParallelEdges++; + } + } + } + + // As i->j and j->i both edges has been counted, actual count is count = count / 2 + countParallelEdges /= 2; + + this->_flagParallelEdges = countParallelEdges > 0; + + // If there are no anti-parallel edges, no need to modify the adjMatrix + if (!this->_flagParallelEdges) + { + return; + } + + int newNoOfVertices = this->_noOfVertices + countParallelEdges; + + // Modifying the adjMatrix + for (auto& edge : this->_adjMatrix) + { + edge.resize(newNoOfVertices, 0); + } + int k = this->_noOfVertices; + this->_visited.resize(newNoOfVertices, false); + this->_parent.resize(newNoOfVertices, -1); + this->_adjMatrix.resize(newNoOfVertices, vector(newNoOfVertices, 0)); + + // Removing the anti-parallel edges by adding new nodes + for (int i = 0; i < this->_noOfVertices; i++) + { + for (int j = 0; j < this->_noOfVertices; j++) + { + if (this->_adjMatrix[i][j] > 0 && this->_adjMatrix[j][i] > 0) + { + this->_adjMatrix[i][k] = this->_adjMatrix[i][j]; + this->_adjMatrix[k][j] = this->_adjMatrix[i][j]; + this->_adjMatrix[i][j] = 0; + k++; + } + } + } + + // Updating the total no of vertices after modifying the adjMatrix + this->_noOfVertices = newNoOfVertices; + } + + // This method is used to color the vertices of the graph to determine if the given graph is bipartite or not + void Graph::ColorGraph() + { + // Color of all the vertices are initialised to WHITE + fill(this->_color.begin(), this->_color.end(), WHITE); + + // Queue to hold the vertices + queue nodeQueue; + + for (int node = 0; node < this->_noOfVertices; node++) + { + // Check if the node is already not colored + if (this->_color[node] == WHITE) + { + // The color of the node is set to RED + this->_color[node] = RED; + + // The node is inserted into the queue + nodeQueue.push(node); + + // Using BFS method to color all the vertices + while (!nodeQueue.empty()) + { + int nodeU = nodeQueue.front(); + nodeQueue.pop(); + + // Iterating over G.Adj[nodeU] + for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) + { + // As there are no self loops, continue + if (nodeU == nodeV) + { + continue; + } + // Check if there is an edge u --> v and nodeV is not colored yet + else if (this->_residualGraph[nodeU][nodeV] != 0 && this->_color[nodeV] == WHITE) + { + // Set the color of nodeV opposite of nodeU + this->_color[nodeV] = 1 - this->_color[nodeU]; + // Insert the nodeV into the queue + nodeQueue.push(nodeV); + } + // Check if there is an edge u --> v and nodeV is of same color as nodeU + else if (this->_residualGraph[nodeU][nodeV] != 0 && this->_color[nodeV] == this->_color[nodeU]) + { + // Set the _isBipartite flag to false and return + this->_isBipartite = false; + return; + } + } + } + } + } + + // If the above operation completes without returning yet that indicates the graph is bipartite + // Set the _isBipartite flag to true and return + this->_isBipartite = true; + return; + } + + // This method is used to create the additional edges + // from the source vertex to the RED colored vertices and + // from the BLUE colored vertices to the sink vertex + void Graph::AddAdditionalEdges() + { + // Resizing the residual graph to accomodate space for the new edges + for (auto& edge : this->_residualGraph) + { + edge.resize(this->_noOfVertices, 0); + } + + this->_parent.resize(this->_noOfVertices, -1); + this->_visited.resize(this->_noOfVertices, false); + this->_color.resize(this->_noOfVertices, WHITE); + this->_residualGraph.resize(this->_noOfVertices, vector(this->_noOfVertices, 0)); + + // Creating the additional edges + for (int node = 0; node < this->_source; node++) + { + // From source vertex --> RED colored vertices + if (this->_color[node] == RED) + { + this->_residualGraph[this->_source][node] = 1; + } + + // From BLUE colored vertices --> sink vertex + else if (this->_color[node] == BLUE) + { + this->_residualGraph[node][this->_sink] = 1; + } + } + } + + // Implementation of BreadthFirstSearch for EdmondsKarp algorithm to find the path from source to sink + bool Graph::BreadthFirstSearch() + { + // Resetting the visited values + fill(this->_visited.begin(), this->_visited.end(), false); + + // Resetting the parent values + fill(this->_parent.begin(), this->_parent.end(), -1); + + queue nodeQueue; + nodeQueue.push(this->_source); + this->_visited[this->_source] = true; + + while (!nodeQueue.empty()) + { + int nodeU = nodeQueue.front(); + nodeQueue.pop(); + + for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) + { + if (!this->_visited[nodeV] && this->_residualGraph[nodeU][nodeV] > 0) + { + this->_parent[nodeV] = nodeU; + this->_visited[nodeV] = true; + nodeQueue.push(nodeV); + } + } + } + + // Returning the visited value of the sink vertex, initially it was set to false + return this->_visited[this->_sink]; + } + + // Graph Public Member Methods + void Graph::CreateGraph(int noOfVertices) + { + this->_noOfVertices = noOfVertices; + this->_maximumFlow = 0; + this->_flagParallelEdges = false; + this->_adjMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, 0)); + this->_parent = vector(this->_noOfVertices, -1); + this->_visited = vector(this->_noOfVertices, false); + this->_color = vector(this->_noOfVertices, WHITE); + } + + void Graph::PushDirectedEdge(int valueU, int valueV) + { + this->_adjMatrix[valueU][valueV] = 1; + } + + int Graph::FindMaximumBipartiteMatching() + { + // Resolving all the parallel edges if present + this->ResolveAntiParallelEdges(); + this->_residualGraph = this->_adjMatrix; + + this->ColorGraph(); + + this->_source = this->_noOfVertices; + this->_noOfVertices++; + this->_sink = this->_noOfVertices; + this->_noOfVertices++; + + this->AddAdditionalEdges(); + + // While there exists a path p from source to sink in the residual network G' + while (this->BreadthFirstSearch()) + { + int augmentedPathFlow = 1; + + // No need to find the minimum amount of augmentedPathFlow as like standard EdmondsKarp algorithm + // as here capacity of each edges is 1 + for (int nodeV = this->_sink; nodeV != this->_source; nodeV = this->_parent[nodeV]) + { + int nodeU = this->_parent[nodeV]; + this->_residualGraph[nodeU][nodeV] -= augmentedPathFlow; + this->_residualGraph[nodeV][nodeU] += augmentedPathFlow; + } + this->_maximumFlow += augmentedPathFlow; + } + + return this->_maximumFlow; + } + + // This method is used for finding the matchings + vector> Graph::GetMatchings() + { + for (int nodeU = 0; nodeU < this->_adjMatrix.size(); nodeU++) + { + for (int nodeV = 0; nodeV < this->_adjMatrix.size(); nodeV++) + { + // Check if the nodeU and nodeV are not source or sink + // and there is a flow of 1 unit from nodeU --> nodeV + // which means nodeU --> nodeV is being used for the maximum flow (maximum matching) + if ((nodeU != this->_source || nodeU != this->_sink || nodeV != this->_source || nodeV != this->_sink) + && + (this->_adjMatrix[nodeU][nodeV] - this->_residualGraph[nodeU][nodeV]) == 1) + { + this->_matchings.push_back({ nodeU, nodeV }); + } + } + } + + return this->_matchings; + } +} \ No newline at end of file diff --git a/src/0003_graph/0018_MaximumFlowGoldbergGenericPushRelabel.cc b/src/0003_graph/0018_MaximumFlowGoldbergGenericPushRelabel.cc new file mode 100644 index 0000000..63c1475 --- /dev/null +++ b/src/0003_graph/0018_MaximumFlowGoldbergGenericPushRelabel.cc @@ -0,0 +1,172 @@ +#include "0018_MaximumFlowGoldbergGenericPushRelabel.h" +#include +using namespace std; + +namespace MaximumFlowGoldbergGenericPushRelabel +{ + // Graph Private Member Methods + + // Initializes Pre-Flow in the given Flow Network + void Graph::InitializePreflow() + { + // The height of source is set to highest possible height value + this->_height[this->_source] = this->_noOfVertices; + + // Iterating over all the vertices + for (int i = 0; i < this->_noOfVertices; i++) + { + // For the all the edges (source, v) + if (this->_residualGraph[this->_source][i] > 0) + { + // v.excessFlow = capacity(source, v) + this->_excessFlow[i] = this->_residualGraph[this->_source][i]; + + // source.excessFlow = source.excessFlow - capacity(source, v) + this->_excessFlow[this->_source] = this->_excessFlow[this->_source] - this->_residualGraph[this->_source][i]; + + // Adjusting the flow and reverse flow along source->v and v->source respectively + this->_residualGraph[i][this->_source] = this->_residualGraph[this->_source][i]; + this->_residualGraph[this->_source][i] = 0; + } + } + } + + // Checks if there is any vertex which has excess flow + bool Graph::CheckOverFlow() + { + // Iterating over all of the vertices + for (int i = 0; i < this->_noOfVertices; i++) + { + // Checks if the current vertex is not any special vertex like source, sink + // and also if there is excess flow in the current vertex and it is already not present in the queue + if (i!=this->_source && i!=this->_sink && this->_excessFlow[i] > 0 && this->_visited[i] == false) + { + // Insert the current vertex into the queue + this->_nodeQueue.push(i); + + // Mark it as visited, so until it leaves the queue it is not inserted again even if all the excess flow is neutralized + this->_visited[i] = true; + } + } + + // Checks if there is no vertex having excess flow then returns false + if (this->_nodeQueue.empty()) + { + return false; + } + + return true; + } + + // Pushes the flow from nodeU to its neighbour vertices + bool Graph::Push(int nodeU) + { + int nodeV = -1; + int minimumFlow = INT_MAX; + + // Iterating over all the vertices + for (int i = 0; i < this->_noOfVertices; i++) + { + // For G'.Adj[nodeU] select the vertex if edge (nodeU, i) is non-saturated and height[nodeU] == height[i] + 1 + if (this->_residualGraph[nodeU][i] > 0 && this->_height[nodeU] == this->_height[i] + 1) + { + nodeV = i; + break; + } + } + + // Checks if any neighbour vertex found having non-saturated edge + if (nodeV != -1) + { + // Calculate the flow amount to be added along the edge and excess flow subtracted from nodeU + minimumFlow = min(this->_residualGraph[nodeU][nodeV], this->_excessFlow[nodeU]); + + // Adjust the flow and the reverse flow along (nodeU, nodeV) + this->_residualGraph[nodeU][nodeV] = this->_residualGraph[nodeU][nodeV] - minimumFlow; + this->_residualGraph[nodeV][nodeU] = this->_residualGraph[nodeV][nodeU] + minimumFlow; + + // Adjust the excess flows in nodeU and nodeV + this->_excessFlow[nodeU] = this->_excessFlow[nodeU] - minimumFlow; + this->_excessFlow[nodeV] = this->_excessFlow[nodeV] + minimumFlow; + + // Return that the Push operation is successful + return true; + } + + // Return that the Push operation is not successful + return false; + } + + // Relabels height of vertex nodeU when there are outgoing non-saturated edges available + void Graph::Relabel(int nodeU) + { + int minimumHeight = INT_MAX; + + // Iterating over all the vertices + for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) + { + // For G'.Adj[nodeU] select for which nodeV, height[nodeU] <= height[nodeV] + if (this->_residualGraph[nodeU][nodeV] > 0 && this->_height[nodeU] <= this->_height[nodeV]) + { + // Get the minimum height among all these G'.Adj[nodeU] + minimumHeight = min(minimumHeight, this->_height[nodeV]); + } + } + + // Set height[nodeU] + this->_height[nodeU] = minimumHeight + 1; + } + + + // Graph Public Member Methods + void Graph::CreateGraph(int noOfVertices) + { + this->_noOfVertices = noOfVertices; + this->_source = 0; + this->_sink = this->_noOfVertices - 1; + this->_maximumFlow = 0; + this->_adjMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, 0)); + this->_excessFlow = vector(this->_noOfVertices, 0); + this->_height = vector(this->_noOfVertices, 0); + this->_visited = vector(this->_noOfVertices, false); + } + + void Graph::PushDirectedEdge(int valueU, int valueV, int capacity) + { + this->_adjMatrix[valueU][valueV] = capacity; + } + + int Graph::FindMaximumFlowGoldbergGenericPushRelabel() + { + this->_residualGraph = this->_adjMatrix; + + // Initialize Pre-flow + this->InitializePreflow(); + + // Checks if there is some vertices which have excess flow + while (this->CheckOverFlow()) + { + // Get the vertex + int nodeU = this->_nodeQueue.front(); + + // Checks if the Push operation is successful + if (this->Push(nodeU)) + { + // Then remove the vertex from queue and set visited[nodeU] = true + // so that on next CheckOverFlow() method call this vertex can be discovered if it still has some excess flow + this->_nodeQueue.pop(); + this->_visited[nodeU] = false; + } + + // If the Push operation is not successful + else + { + // Then Relabel nodeU without removing it from the queue + this->Relabel(nodeU); + } + } + + // Return the excess flow in the sink vertex which is actually the maximum flow along the given flow network + return this->_excessFlow[this->_sink]; + } +} \ No newline at end of file diff --git a/src/0003_graph/0019_MaximumFlowRelabelToFront.cc b/src/0003_graph/0019_MaximumFlowRelabelToFront.cc new file mode 100644 index 0000000..034f5bf --- /dev/null +++ b/src/0003_graph/0019_MaximumFlowRelabelToFront.cc @@ -0,0 +1,169 @@ +#include "0019_MaximumFlowRelabelToFront.h" +#include +#include +using namespace std; + +namespace MaximumFlowRelabelToFront +{ + // Graph Private Member Methods + + // Initializes Pre-Flow in the given Flow Network + void Graph::InitializePreflow() + { + // The height of source is set to highest possible height value + this->_height[this->_source] = this->_noOfVertices; + + // Iterating over all the vertices + for (int i = 0; i < this->_noOfVertices; i++) + { + // For the all the edges (source, v) + if (this->_residualGraph[this->_source][i] > 0) + { + // v.excessFlow = capacity(source, v) + this->_excessFlow[i] = this->_residualGraph[this->_source][i]; + + // source.excessFlow = source.excessFlow - capacity(source, v) + this->_excessFlow[this->_source] = this->_excessFlow[this->_source] - this->_residualGraph[this->_source][i]; + + // Adjusting the flow and reverse flow along source->v and v->source respectively + this->_residualGraph[i][this->_source] = this->_residualGraph[this->_source][i]; + this->_residualGraph[this->_source][i] = 0; + } + } + } + + // Discharges the excess flow from nodeU + void Graph::Discharge(int nodeU) + { + // Check if excess flow of nodeU is > 0 + while (this->_excessFlow[nodeU] > 0) + { + // Falg to check if any amount of excess flow is pushed to any neighbour vertex + bool hasPushed = false; + + // Iterating over all of the vertices + for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) + { + // For G'.Adj[nodeU] check if edge (nodeU, nodeV) is admissible + if (this->_residualGraph[nodeU][nodeV] > 0 && this->_height[nodeU] == 1 + this->_height[nodeV]) + { + // Push excess flow along the admissible edge (nodeU, nodeV) + this->Push(nodeU, nodeV); + // Set the hasPushed flag to true + hasPushed = true; + // Check if there is no excess flow left in nodeU then no need to check any more admissible edge going from nodeU + if (this->_excessFlow[nodeU] == 0) + { + // Then break from iterating over G'.Adj[nodeU] + break; + } + } + } + + // Check if Push operation is not done yet + if (!hasPushed) + { + // Then it indicates that all the outgoing edges from nodeU are inadmissible + // so perform the Relabel operation on nodeU + this->Relabel(nodeU); + } + } + } + + // Pushes the flow from nodeU to its neighbour vertices + void Graph::Push(int nodeU, int nodeV) + { + // Calculate the flow amount to be added along the edge and excess flow subtracted from nodeU + int minimumFlow = min(this->_residualGraph[nodeU][nodeV], this->_excessFlow[nodeU]); + + // Adjust the flow and the reverse flow along (nodeU, nodeV) + this->_residualGraph[nodeU][nodeV] = this->_residualGraph[nodeU][nodeV] - minimumFlow; + this->_residualGraph[nodeV][nodeU] = this->_residualGraph[nodeV][nodeU] + minimumFlow; + + // Adjust the excess flows in nodeU and nodeV + this->_excessFlow[nodeU] = this->_excessFlow[nodeU] - minimumFlow; + this->_excessFlow[nodeV] = this->_excessFlow[nodeV] + minimumFlow; + } + + // Relabels height of vertex nodeU when there are outgoing non-saturated edges available + void Graph::Relabel(int nodeU) + { + int minimumHeight = INT_MAX; + + // Iterating over all the vertices + for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) + { + // For G'.Adj[nodeU] select for which nodeV, height[nodeU] <= height[nodeV] + if (this->_residualGraph[nodeU][nodeV] > 0 && this->_height[nodeU] <= this->_height[nodeV]) + { + // Get the minimum height among all these G'.Adj[nodeU] + minimumHeight = min(minimumHeight, this->_height[nodeV]); + } + } + + // Set height[nodeU] + this->_height[nodeU] = minimumHeight + 1; + } + + + // Graph Public Member Methods + void Graph::CreateGraph(int noOfVertices) + { + this->_noOfVertices = noOfVertices; + this->_source = 0; + this->_sink = this->_noOfVertices - 1; + this->_maximumFlow = 0; + this->_adjMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, 0)); + this->_excessFlow = vector(this->_noOfVertices, 0); + this->_height = vector(this->_noOfVertices, 0); + this->_visited = vector(this->_noOfVertices, false); + } + + void Graph::PushDirectedEdge(int valueU, int valueV, int capacity) + { + this->_adjMatrix[valueU][valueV] = capacity; + } + + int Graph::FindMaximumFlowRelabelToFront() + { + this->_residualGraph = this->_adjMatrix; + + // Initialize Pre-flow + this->InitializePreflow(); + + // Make the list L = G.V - {source, sink} + for (int i = 0; i < this->_noOfVertices; i++) + { + if (i != this->_source && i != this->_sink) + { + this->_nodeList.push_back(i); + } + } + + // Set current vertex = L.head + list::iterator nodeUiterator = this->_nodeList.begin(); + + // Iterate over all of the elements in the list L + while (nodeUiterator != this->_nodeList.end()) + { + // Get the height of current vertex + int oldHeight = this->_height[*nodeUiterator]; + + // Discharge the excess flow of current vertex + this->Discharge(*nodeUiterator); + + // Check if the height of current vertex increases which means the current vertex got relabeled + if (this->_height[*nodeUiterator] > oldHeight) + { + // Then move current vertex to the front of the list L + this->_nodeList.splice(this->_nodeList.begin(), this->_nodeList, nodeUiterator); + } + + // Go to the next vertex of current vertex in L + nodeUiterator++; + } + + // Return the excess flow in the sink vertex which is actually the maximum flow along the given flow network + return this->_excessFlow[this->_sink]; + } +} \ No newline at end of file diff --git a/src/0003_graph/CMakeLists.txt b/src/0003_graph/CMakeLists.txt new file mode 100644 index 0000000..02f8a77 --- /dev/null +++ b/src/0003_graph/CMakeLists.txt @@ -0,0 +1,30 @@ +# Specify the source files +set(0003GRAPH_SOURCES + 0001_BreadthFirstSearch.cc + 0002_DepthFirstSearch.cc + 0003_TopologicalSort.cc + 0004_StronglyConnectedComponents.cc + 0005_HamiltonianPathAndCycle.cc + 0006_EulerianPathAndCircuit.cc + 0007_MinimumSpanningTreeKruskalAlgorithm.cc + 0008_MinimumSpanningTreePrimAlgorithm.cc + 0009_SingleSourceShortestPathBellmanFord.cc + 0010_DirectedAcyclicGraphShortestPath.cc + 0011_SingleSourceShortestPathDijkstra.cc + 0012_DifferenceConstraintsShortestPaths.cc + 0013_AllPairsShortestPathsFloydWarshall.cc + 0014_AllPairsShortestPathsJohnson.cc + 0015_MaximumFlowFordFulkerson.cc + 0016_MaximumFlowEdmondsKarp.cc + 0017_MaximumBipartiteMatching.cc + 0018_MaximumFlowGoldbergGenericPushRelabel.cc + 0019_MaximumFlowRelabelToFront.cc + +) + +# Create a library target +add_library(0003GRAPH ${0003GRAPH_SOURCES}) + +target_include_directories(0003GRAPH PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}/headers +) \ No newline at end of file diff --git a/src/0003_graph/headers/0001_BreadthFirstSearch.h b/src/0003_graph/headers/0001_BreadthFirstSearch.h new file mode 100644 index 0000000..ba7aec8 --- /dev/null +++ b/src/0003_graph/headers/0001_BreadthFirstSearch.h @@ -0,0 +1,35 @@ +#pragma once + +#include +#include +#include +#include +#include +using namespace std; + +namespace BreadthFirstSearch +{ + enum color { WHITE, GRAY, BLACK }; + class Node + { + public: + int data; + int distance; + int color; + Node* parent; + Node(int value); + }; + + class Graph + { + private: + map> _adjlist; + map _nodeMap; + Node* MakeOrFindNode(int value); + void BreadthFirstSearch(Node* node); + public: + void PushUndirectedEdge(int valueU, int valueV); + void BFS(int value); + vector> ShowBFSResult(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0002_DepthFirstSearch.h b/src/0003_graph/headers/0002_DepthFirstSearch.h new file mode 100644 index 0000000..e376295 --- /dev/null +++ b/src/0003_graph/headers/0002_DepthFirstSearch.h @@ -0,0 +1,37 @@ +#pragma once + +#include +#include +#include +#include +using namespace std; + +namespace DepthFirstSearch +{ + enum color { WHITE, GRAY, BLACK }; + + class Node + { + public: + int data; + int color; + int discoveredTime; + int finishingTime; + Node* parent; + Node(int value); + }; + + class Graph + { + private: + int _time; + map> _adjlist; + map _nodeMap; + Node* MakeOrFindNode(int value); + void DepthFirstSearch(Node* Node); + public: + void PushDirectedEdge(int valueU, int valueV); + void DFS(); + vector>> ShowDFSResult(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0003_TopologicalSort.h b/src/0003_graph/headers/0003_TopologicalSort.h new file mode 100644 index 0000000..441d7d1 --- /dev/null +++ b/src/0003_graph/headers/0003_TopologicalSort.h @@ -0,0 +1,42 @@ +#pragma once + +#include +#include +#include +#include +using namespace std; + +namespace TopologicalSort +{ + enum color { WHITE, GRAY, BLACK }; + + class Node + { + public: + int data; + int color; + int discoveryTime; + int finishingTime; + int inDegree; + Node* parent; + Node(int value); + }; + + class Graph + { + private: + int _time; + bool _hasCycle; + map> _adjlist; + map _nodeMap; + list _topologicalSortedNodeList; + Node* MakeOrFindNode(int value); + void DepthFirstSearch(Node* DFSNode); + public: + void PushDirectedEdge(int valueU, int valueV); + void PushSingleNode(int valueU); + void TopologicalSort(); + void KahnTopologicalSort(); + vector>> ShowTopologicalSortResult(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0004_StronglyConnectedComponents.h b/src/0003_graph/headers/0004_StronglyConnectedComponents.h new file mode 100644 index 0000000..0e37f60 --- /dev/null +++ b/src/0003_graph/headers/0004_StronglyConnectedComponents.h @@ -0,0 +1,43 @@ +#pragma once + +#include +#include +#include +#include +using namespace std; + +namespace StronglyConnectedComponents +{ + enum color { WHITE, GRAY, BLACK }; + + class Node + { + public: + int data; + int color; + int discoveryTime; + int finishingTime; + Node* parent; + Node(int value); + }; + + class Graph + { + private: + int _time; + map> _adjlistG; + map> _adjlistT; + map _nodeMap; + list _nodesFinishingTimeOrder; + vector> _allConnectedComponents; + Node* MakeOrFindNode(int value); + void DepthFirstSearchOnGraphG(Node* DFSNode); + void DepthFirstSearchOnGraphT(Node* DFSNode, vector& connectedComponents); + public: + void PushDirectedEdge(int valueU, int valueV); + void PushSingleNode(int valueU); + void DFSOnGraphG(); + void DFSOnGraphT(); + vector> FindAllStronglyConnectedComponents(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0005_HamiltonianPathAndCycle.h b/src/0003_graph/headers/0005_HamiltonianPathAndCycle.h new file mode 100644 index 0000000..7ccca6a --- /dev/null +++ b/src/0003_graph/headers/0005_HamiltonianPathAndCycle.h @@ -0,0 +1,40 @@ +#pragma once + +#include +#include +#include +using namespace std; + +namespace HamiltonianPathAndCycle +{ + class Node + { + public: + int data; + bool isVisited; + Node(int value); + }; + + class Graph + { + private: + bool _isHamiltonianCyclePresent; + bool _isHamiltonianPathPresent; + int _visitedNodeCount; + Node* _startingNode; + map> _adjlist; + map _nodeMap; + vector _hamiltonianPath; + Node* MakeOrFindNode(int value); + bool IsSafe(Node* nodeU, Node* nodeV); + bool HamiltonianCycleAndPathUtil(Node* node); + + public: + void PushUndirectedEdge(int valueU, int valueV); + void PushSingleNode(int valueU); + void FindHamiltonianCycleAndPath(); + bool IsHamiltonianCyclePresent(); + bool IsHamiltonianPathPresent(); + vector GetHamiltonianPath(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0006_EulerianPathAndCircuit.h b/src/0003_graph/headers/0006_EulerianPathAndCircuit.h new file mode 100644 index 0000000..92d0d34 --- /dev/null +++ b/src/0003_graph/headers/0006_EulerianPathAndCircuit.h @@ -0,0 +1,43 @@ +#pragma once + +#include +#include +#include +using namespace std; + +namespace EulerianPathAndCircuit +{ + class Node + { + public: + int data; + int degree; + int inDegree; + int outDegree; + bool visited; + Node(int value); + }; + + class Graph + { + private: + bool _isEulerianPathPresent; + bool _isEulerianCircuitPresent; + map> _adjlist; + map _nodeMap; + vector _eulerianPath; + Node* MakeOrFindNode(int value); + void DepthFirstSearch(Node* node); + bool IsConnected(); + void EulerianPathHierholzerAlgorithm(Node* startingNode); + + public: + void PushUndirectedEdge(int valueU, int valueV); + void PushDirectedEdge(int valueU, int valueV); + void PushSingleNode(int valueU); + void FindEulerianPathAndCircuit(); + bool IsEulerianPathPresent(); + bool IsEulerianCircuitPresent(); + vector UndirectedGraphGetEulerianPath(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0007_MinimumSpanningTreeKruskalAlgorithm.h b/src/0003_graph/headers/0007_MinimumSpanningTreeKruskalAlgorithm.h new file mode 100644 index 0000000..8ca704c --- /dev/null +++ b/src/0003_graph/headers/0007_MinimumSpanningTreeKruskalAlgorithm.h @@ -0,0 +1,46 @@ +#pragma once + +#include +#include +#include +using namespace std; + +namespace MinimumSpanningTreeKruskalAlgorithm +{ + class Node + { + public: + int data; + Node* parent; + int rank; + Node(int data); + }; + + class Edge + { + public: + Node* nodeU; + Node* nodeV; + int weight; + Edge(Node* nodeU, Node* nodeV, int weight); + }; + + class Graph + { + private: + map> _adjlist; + map _nodeMap; + vector _edgeList; + vector, int>> _minimumSpanningTree; + Node* MakeOrFindNode(int data); + void MakeSet(Node* node); + void Union(Node* nodeU, Node* nodeV); + void Link(Node* nodeU, Node* nodeV); + Node* FindSet(Node* node); + + public: + void PushUndirectedEdge(int valueU, int valueV, int weight); + void FindMinimumSpanningTreeKruskalAlgorithm(); + vector, int>> GetMinimumSpanningTree(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0008_MinimumSpanningTreePrimAlgorithm.h b/src/0003_graph/headers/0008_MinimumSpanningTreePrimAlgorithm.h new file mode 100644 index 0000000..ffe7c08 --- /dev/null +++ b/src/0003_graph/headers/0008_MinimumSpanningTreePrimAlgorithm.h @@ -0,0 +1,42 @@ +# pragma once + +#include +#include +#include +using namespace std; + +namespace MinimumSpanningTreePrimAlgorithm +{ + class Node + { + public: + int data; + Node* parent; + int key; + bool isInOperationalSet; + Node(int data); + }; + + class CompareNodeKey + { + public: + bool operator()(const Node* nodeU, const Node* nodeV) const + { + return nodeU->key < nodeV->key; + } + }; + + class Graph + { + private: + map>> _adjlist; + map _nodeMap; + vector, int>> _minimumSpanningTree; + multiset _operationalSet; + Node* MakeOrFindNode(int data); + public: + void PushUndirectedEdge(int valueU, int valueV, int weight); + void FindMinimumSpanningTreePrimAlgorithm(); + vector, int>> GetMinimumSpanningTree(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0009_SingleSourceShortestPathBellmanFord.h b/src/0003_graph/headers/0009_SingleSourceShortestPathBellmanFord.h new file mode 100644 index 0000000..e51ca10 --- /dev/null +++ b/src/0003_graph/headers/0009_SingleSourceShortestPathBellmanFord.h @@ -0,0 +1,44 @@ +#pragma once + +#include +#include +using namespace std; + +namespace SingleSourceShortestPathBellmanFord +{ + class Node + { + public: + int data; + int distance; + Node* parent; + Node(int data); + }; + + class Edge + { + public: + Node* nodeU; + Node* nodeV; + int weight; + Edge(Node* nodeU, Node* nodeV, int weight); + }; + + class Graph + { + private: + map> _adjlist; + map _nodeMap; + vector _edgeList; + Node* MakeOrFindNode(int data); + void InitializeSingleSource(Node* sourceNode); + void Relax(Edge* edge); + void GetShortestPath(Node* node, vector& path); + + + public: + void PushDirectedEdge(int valueU, int valueV, int weight); + bool FindSingleSourceShortestPathBellmanFord(int data); + vector GetShortestPathBellmanFord(int data); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0010_DirectedAcyclicGraphShortestPath.h b/src/0003_graph/headers/0010_DirectedAcyclicGraphShortestPath.h new file mode 100644 index 0000000..8826ebc --- /dev/null +++ b/src/0003_graph/headers/0010_DirectedAcyclicGraphShortestPath.h @@ -0,0 +1,51 @@ +#pragma once + +#include +#include +#include +using namespace std; + +namespace DirectedAcyclicGraphShortestPath +{ + enum color {WHITE, GRAY, BLACK}; + + class Node + { + public: + int data; + int color; + int distance; + Node* parent; + Node(int data); + }; + + class Edge + { + public: + Node* nodeU; + Node* nodeV; + int weight; + Edge(Node* nodeU, Node* nodeV, int weight); + }; + + class Graph + { + private: + map> _adjlist; + map _nodeMap; + map> _edgeMap; + list _topologicalSortedNodeList; + Node* MakeOrFindNode(int data); + void DepthFirstSearch(Node* node); + void TopologicalSort(); + void InitializeSingleSource(Node* sourceNode); + void Relax(Edge* edge); + void GetShortestPath(Node* node, vector& path); + + + public: + void PushDirectedEdge(int valueU, int valueV, int weight); + void FindDAGShortestPath(int data); + vector GetDAGShortestPath(int data); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0011_SingleSourceShortestPathDijkstra.h b/src/0003_graph/headers/0011_SingleSourceShortestPathDijkstra.h new file mode 100644 index 0000000..8911ac8 --- /dev/null +++ b/src/0003_graph/headers/0011_SingleSourceShortestPathDijkstra.h @@ -0,0 +1,55 @@ +#pragma once + +#include +#include +#include +using namespace std; + +namespace SingleSourceShortestPathDijkstra +{ + class Node + { + public: + int data; + int distance; + Node* parent; + Node(int data); + }; + + class Edge + { + public: + Node* nodeU; + Node* nodeV; + int weight; + Edge(Node* nodeU, Node* nodeV, int weight); + }; + + class CompareNodeDistance + { + public: + bool operator()(const Node* nodeU, const Node* nodeV) const + { + return nodeU->distance < nodeV->distance; + } + }; + + class Graph + { + private: + map> _adjlist; + map _nodeMap; + map> _edgeMap; + multiset _operationalSet; + Node* MakeOrFindNode(int data); + void InitializeSingleSource(Node* sourceNode); + void Relax(Edge* edge); + void Dijkstra(Node* source); + void GetShortestPath(Node* node, vector& path); + + public: + void PushDirectedEdge(int valueU, int valueV, int weight); + void FindShortestPathDijkstra(int data); + vector GetDijkstraShortestPath(int data); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0012_DifferenceConstraintsShortestPaths.h b/src/0003_graph/headers/0012_DifferenceConstraintsShortestPaths.h new file mode 100644 index 0000000..02d1426 --- /dev/null +++ b/src/0003_graph/headers/0012_DifferenceConstraintsShortestPaths.h @@ -0,0 +1,43 @@ +#pragma once + +#include +#include +#include +using namespace std; + +namespace DifferenceConstraintsShortestPaths +{ + class Node + { + public: + string data; + int distance; + Node(string data); + }; + + class Edge + { + public: + Node* nodeU; + Node* nodeV; + int weight; + Edge(Node* nodeU, Node* nodeV, int weight); + }; + + class Graph + { + private: + map> _adjlist; + map _nodeMap; + vector _edgeList; + Node* MakeOrFindNode(string data); + void PushDirectedEdge(string valueU, string valueV, int weight); + void InitializeSingleSource(Node* sourceNode); + void Relax(Edge* edge); + + public: + void PushAllDirectedEdges(vector> vectorA, vector vectorX, vector vectorB); + bool FindDifferenceConstraintsSolutionBellmanFord(); + vector> GetDifferenceConstrtaintsSolution(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0013_AllPairsShortestPathsFloydWarshall.h b/src/0003_graph/headers/0013_AllPairsShortestPathsFloydWarshall.h new file mode 100644 index 0000000..211e1b6 --- /dev/null +++ b/src/0003_graph/headers/0013_AllPairsShortestPathsFloydWarshall.h @@ -0,0 +1,24 @@ +#pragma once + +#include +using namespace std; + +namespace AllPairsShortestPathsFloydWarshall +{ + class Graph + { + private: + int _noOfVertices; + vector> _adjMatrix; + vector> _shortestPathMatrixFloydWarshall; + vector> _predecessorMatrix; + void InitializeDistanceAndPredecessors(); + void GetShortestPath(int source, int destination, vector& path); + + public: + void CreateGraph(int noOfVertices); + void PushDirectedEdge(int valueU, int valueV, int weight); + void FindAllPairsShortestPathsFloydWarshallSolution(); + vector> GetFloydWarshallShortestPath(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0014_AllPairsShortestPathsJohnson.h b/src/0003_graph/headers/0014_AllPairsShortestPathsJohnson.h new file mode 100644 index 0000000..925e89e --- /dev/null +++ b/src/0003_graph/headers/0014_AllPairsShortestPathsJohnson.h @@ -0,0 +1,66 @@ +#pragma once + +#include +#include +#include +using namespace std; + +namespace AllPairsShortestPathsJohnson +{ + class Node + { + public: + int data; + int distance; + Node* parent; + int potentialWeight; + Node(int data); + }; + + class Edge + { + public: + Node* nodeU; + Node* nodeV; + int weight; + Edge(Node* nodeU, Node* nodeV, int weight); + }; + + class CompareNodeDistance + { + public: + bool operator()(const Node* nodeU, const Node* nodeV) const + { + return nodeU->distance < nodeV->distance; + } + }; + + class Graph + { + private: + int _noOfVertices=0; + map> _adjlist; + map _nodeMap; + vector _edgeList; + map> _edgeMap; + map> _augmentedAdjlist; + vector _augmentedEdgeList; + multiset _operationalSet; + vector> _shortestPathMatrix; + vector> _predecessorMatrix; + Node* MakeOrFindNode(int data); + void PushAugmentedDirectedEdges(Node* sourceNode, Node* nodeV, int weight); + void InitializeSingleSource(Node* sourceNode); + void RelaxBellmanFord(Edge* edge); + bool BellmanFord(Node* source); + void RelaxDijkstra(Edge* edge); + void Dijkstra(Node* source); + void GetShortestPath(int source, int destination, vector& path); + + public: + void PushDirectedEdge(int dataU, int dataV, int weight); + bool FindAllPairsShortestPathsJohnsonAlgorithm(); + vector> GetAllPairsShortestPathsDistanceMatrix(); + vector> GetAllPairsShortestPathsPathMatrix(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0015_MaximumFlowFordFulkerson.h b/src/0003_graph/headers/0015_MaximumFlowFordFulkerson.h new file mode 100644 index 0000000..429b247 --- /dev/null +++ b/src/0003_graph/headers/0015_MaximumFlowFordFulkerson.h @@ -0,0 +1,29 @@ +#pragma once + +#include +#include +using namespace std; + +namespace MaximumFlowFordFulkerson +{ + class Graph + { + private: + int _noOfVertices; + int _source; + int _sink; + int _maximumFlow; + bool _flagParallelEdges; + vector> _adjMatrix; + vector> _residualGraph; + vector _parent; + vector _visited; + void ResolveAntiParallelEdges(); + void DepthFirstSearchVisit(int nodeU); + bool DepthFirstSearch(); + public: + void CreateGraph(int noOfVertices); + void PushDirectedEdge(int valueU, int valueV, int capacity); + int FindMaximumFlowFordFulkerson(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0016_MaximumFlowEdmondsKarp.h b/src/0003_graph/headers/0016_MaximumFlowEdmondsKarp.h new file mode 100644 index 0000000..25c72f1 --- /dev/null +++ b/src/0003_graph/headers/0016_MaximumFlowEdmondsKarp.h @@ -0,0 +1,28 @@ +#pragma once + +#include +#include +using namespace std; + +namespace MaximumFlowEdmondsKarp +{ + class Graph + { + private: + int _noOfVertices; + int _source; + int _sink; + int _maximumFlow; + bool _flagParallelEdges; + vector> _adjMatrix; + vector> _residualGraph; + vector _parent; + vector _visited; + void ResolveAntiParallelEdges(); + bool BreadthFirstSearch(); + public: + void CreateGraph(int noOfVertices); + void PushDirectedEdge(int valueU, int valueV, int capacity); + int FindMaximumFlowEdmondsKarp(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0017_MaximumBipartiteMatching.h b/src/0003_graph/headers/0017_MaximumBipartiteMatching.h new file mode 100644 index 0000000..741c3c0 --- /dev/null +++ b/src/0003_graph/headers/0017_MaximumBipartiteMatching.h @@ -0,0 +1,41 @@ +#pragma once + +#include +#include +using namespace std; + +namespace MaximumBipartiteMatching +{ + enum Color + { + WHITE = -1, + RED = 0, + BLUE = 1 + }; + + class Graph + { + private: + int _noOfVertices; + int _source; + int _sink; + int _maximumFlow; + bool _flagParallelEdges; + bool _isBipartite; + vector> _adjMatrix; + vector> _residualGraph; + vector _parent; + vector _visited; + vector _color; + vector> _matchings; + void ResolveAntiParallelEdges(); + void ColorGraph(); + void AddAdditionalEdges(); + bool BreadthFirstSearch(); + public: + void CreateGraph(int noOfVertices); + void PushDirectedEdge(int valueU, int valueV); + int FindMaximumBipartiteMatching(); + vector> GetMatchings(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0018_MaximumFlowGoldbergGenericPushRelabel.h b/src/0003_graph/headers/0018_MaximumFlowGoldbergGenericPushRelabel.h new file mode 100644 index 0000000..fb13a01 --- /dev/null +++ b/src/0003_graph/headers/0018_MaximumFlowGoldbergGenericPushRelabel.h @@ -0,0 +1,31 @@ +#pragma once + +#include +#include +using namespace std; + +namespace MaximumFlowGoldbergGenericPushRelabel +{ + class Graph + { + private: + int _noOfVertices; + int _source; + int _sink; + int _maximumFlow; + vector> _adjMatrix; + vector> _residualGraph; + vector _excessFlow; + vector _height; + vector _visited; + queue _nodeQueue; + void InitializePreflow(); + bool CheckOverFlow(); + bool Push(int nodeU); + void Relabel(int nodeU); + public: + void CreateGraph(int noOfVertices); + void PushDirectedEdge(int valueU, int valueV, int capacity); + int FindMaximumFlowGoldbergGenericPushRelabel(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0019_MaximumFlowRelabelToFront.h b/src/0003_graph/headers/0019_MaximumFlowRelabelToFront.h new file mode 100644 index 0000000..aea70f6 --- /dev/null +++ b/src/0003_graph/headers/0019_MaximumFlowRelabelToFront.h @@ -0,0 +1,31 @@ +#pragma once + +#include +#include +using namespace std; + +namespace MaximumFlowRelabelToFront +{ + class Graph + { + private: + int _noOfVertices; + int _source; + int _sink; + int _maximumFlow; + vector> _adjMatrix; + vector> _residualGraph; + vector _excessFlow; + vector _height; + vector _visited; + list _nodeList; + void InitializePreflow(); + void Discharge(int nodeU); + void Push(int nodeU, int nodeV); + void Relabel(int nodeU); + public: + void CreateGraph(int noOfVertices); + void PushDirectedEdge(int valueU, int valueV, int capacity); + int FindMaximumFlowRelabelToFront(); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0001_FibonacciNumber.cc b/src/0004_dynamic_programming/0001_FibonacciNumber.cc new file mode 100644 index 0000000..47073aa --- /dev/null +++ b/src/0004_dynamic_programming/0001_FibonacciNumber.cc @@ -0,0 +1,28 @@ +#include "0001_FibonacciNumber.h" + +namespace FibonacciNumber +{ + int DynamicProgramming::RecursiveNthFibonacci(int n) + { + if (n <= 1) + { + return n; + } + + return this->RecursiveNthFibonacci(n - 1) + this->RecursiveNthFibonacci(n - 2); + } + + int DynamicProgramming::DpNthFibonacci(int n) + { + vector dp(n + 1, 0); + dp[0] = 0; + dp[1] = 1; + + for (int i = 2; i <= n; i++) + { + dp[i] = dp[i - 1] + dp[i - 2]; + } + + return dp[n]; + } +} diff --git a/src/0004_dynamic_programming/0002_TribonacciNumber.cc b/src/0004_dynamic_programming/0002_TribonacciNumber.cc new file mode 100644 index 0000000..84a4c59 --- /dev/null +++ b/src/0004_dynamic_programming/0002_TribonacciNumber.cc @@ -0,0 +1,33 @@ +#include "0002_TribonacciNumber.h" + +namespace TribonacciNumber +{ + int DynamicProgramming::RecursiveNthTribonacci(int n) + { + if (n == 0 || n == 1 || n == 2) + { + return 0; + } + + if (n == 3) + { + return 1; + } + + return this->RecursiveNthTribonacci(n - 1) + this->RecursiveNthTribonacci(n - 2) + this->RecursiveNthTribonacci(n - 3); + } + + int DynamicProgramming::DpNthTribonacci(int n) + { + vector dp(n, 0); + dp[0] = dp[1] = 0; + dp[2] = 1; + + for (int i = 3; i < n; i++) + { + dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]; + } + + return dp[n - 1]; + } +} diff --git a/src/0004_dynamic_programming/0003_ClimbingStairs.cc b/src/0004_dynamic_programming/0003_ClimbingStairs.cc new file mode 100644 index 0000000..6e365f8 --- /dev/null +++ b/src/0004_dynamic_programming/0003_ClimbingStairs.cc @@ -0,0 +1,29 @@ +#include "0003_ClimbingStairs.h" +using namespace std; + +namespace ClimbingStairs +{ + int DynamicProgramming::RecursiveCountWays(int n) + { + if (n == 0 || n == 1) + { + return 1; + } + + return this->RecursiveCountWays(n - 1) + this->RecursiveCountWays(n - 2); + } + + int DynamicProgramming::DpCountWays(int n) + { + vector dp(n + 1, 0); + dp[0] = 1; + dp[1] = 1; + + for (int i = 2; i <= n; i++) + { + dp[i] = dp[i - 1] + dp[i - 2]; + } + + return dp[n]; + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0004_MinimumCostClimbingStairs.cc b/src/0004_dynamic_programming/0004_MinimumCostClimbingStairs.cc new file mode 100644 index 0000000..661afc4 --- /dev/null +++ b/src/0004_dynamic_programming/0004_MinimumCostClimbingStairs.cc @@ -0,0 +1,48 @@ +#include "0004_MinimumCostClimbingStairs.h" +#include + +namespace MinimumCostClimbingStairs +{ + int DynamicProgramming::MinCostRecursive(size_t step, vector& cost) + { + if (step == 0 || step == 1) + { + return cost[step]; + } + + return cost[step] + min(this->MinCostRecursive(step - 1, cost), this->MinCostRecursive(step - 2, cost)); + } + + int DynamicProgramming::RecursiveMinimumCostClimbingStairs(vector& cost) + { + size_t totalSteps = cost.size(); + + if (totalSteps == 1) + { + return cost[0]; + } + + return min(this->MinCostRecursive(totalSteps - 1, cost), this->MinCostRecursive(totalSteps - 2, cost)); + } + + int DynamicProgramming::DpMinimumCostClimbingStairs(vector& cost) + { + size_t totalSteps = cost.size(); + vector dp(totalSteps, 0); + + if (totalSteps == 1) + { + return cost[0]; + } + + dp[0] = cost[0]; + dp[1] = cost[1]; + + for (size_t i = 2; i < totalSteps; i++) + { + dp[i] = cost[i] + min(dp[i - 1], dp[i - 2]); + } + + return min(dp[totalSteps - 1], dp[totalSteps - 2]); + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0005_HouseRobber1.cc b/src/0004_dynamic_programming/0005_HouseRobber1.cc new file mode 100644 index 0000000..2e3fb7f --- /dev/null +++ b/src/0004_dynamic_programming/0005_HouseRobber1.cc @@ -0,0 +1,44 @@ +#include "0005_HouseRobber1.h" + +namespace HouseRobber1 +{ + int DynamicProgramming::MaxLootRecursive(size_t house, vector& houseValues) + { + if (house <= 0) + { + return 0; + } + + if (house == 1) + { + return houseValues[0]; + } + + int pickCurrentHouse = houseValues[house - 1] + this->MaxLootRecursive(house - 2, houseValues); + int dropCurrentHouse = this->MaxLootRecursive(house - 1, houseValues); + + return max(pickCurrentHouse, dropCurrentHouse); + } + + int DynamicProgramming::RecursiveMaximumLoot(vector& houseValues) + { + size_t totalNumberOfHouses = houseValues.size(); + return this->MaxLootRecursive(totalNumberOfHouses, houseValues); + } + + int DynamicProgramming::DpMaximumLoot(vector& houseValues) + { + size_t totalNumberOfHouses = houseValues.size(); + vector dp(totalNumberOfHouses + 1, 0); + + dp[0] = 0; + dp[1] = houseValues[0]; + + for (size_t i = 2; i <= totalNumberOfHouses; i++) + { + dp[i] = max(dp[i - 2] + houseValues[i - 1], dp[i - 1]); + } + + return dp[totalNumberOfHouses]; + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0006_HouseRobber2.cc b/src/0004_dynamic_programming/0006_HouseRobber2.cc new file mode 100644 index 0000000..cbefdda --- /dev/null +++ b/src/0004_dynamic_programming/0006_HouseRobber2.cc @@ -0,0 +1,95 @@ +#include "0006_HouseRobber2.h" + +namespace HouseRobber2 +{ + int DynamicProgramming::MaxLootRecursive(size_t house, vector& houseValues) + { + if (house <= 0) + { + return 0; + } + + if (house == 1) + { + return houseValues[0]; + } + + int pickCurrentHouse = houseValues[house - 1] + this->MaxLootRecursive(house - 2, houseValues); + int dropCurrentHouse = this->MaxLootRecursive(house - 1, houseValues); + + return max(pickCurrentHouse, dropCurrentHouse); + } + + int DynamicProgramming::MaxLootDp(size_t firstHouse, size_t lastHouse, vector& houseValues) + { + int totalNumberOfHouses = lastHouse - firstHouse + 1; + + if (totalNumberOfHouses == 0) + { + return 0; + } + + if (totalNumberOfHouses == 1) + { + return houseValues[firstHouse]; + } + + vector dp(totalNumberOfHouses, 0); + + dp[0] = houseValues[firstHouse]; + dp[1] = max(houseValues[firstHouse], houseValues[firstHouse + 1]); + + for (size_t i = 2; i < totalNumberOfHouses; i++) + { + dp[i] = max(houseValues[firstHouse + i] + dp[i - 2], dp[i - 1]); + } + + return dp[totalNumberOfHouses - 1]; + } + + int DynamicProgramming::RecursiveMaximumLoot(vector& houseValues) + { + if (houseValues.size() == 0) + { + return 0; + } + + if (houseValues.size() == 1) + { + return houseValues[0]; + } + + size_t totalNumberOfHouses = houseValues.size()-1; + + // Case 1: Exclude last house. + vector pickFirstHouse(houseValues.begin(), houseValues.end() - 1); + + // Case 2: Exlcude first house. + vector pickLastHouse(houseValues.begin() + 1, houseValues.end()); + + return max(this->MaxLootRecursive(totalNumberOfHouses, pickFirstHouse), this->MaxLootRecursive(totalNumberOfHouses, pickLastHouse)); + } + + int DynamicProgramming::DpMaximumLoot(vector& houseValues) + { + size_t totalNumberOfHouses = houseValues.size(); + + if (totalNumberOfHouses == 0) + { + return 0; + } + + if (totalNumberOfHouses == 1) + { + return houseValues[0]; + } + + // Case 1: Exclude last house. + int pickFirstHouse = this->MaxLootDp(0, totalNumberOfHouses - 2, houseValues); + + // Case 2: Exlcude first house. + int pickLastHouse = this->MaxLootDp(1, totalNumberOfHouses - 1, houseValues); + + return max(pickFirstHouse, pickLastHouse); + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0007_DecodeWays.cc b/src/0004_dynamic_programming/0007_DecodeWays.cc new file mode 100644 index 0000000..bf93270 --- /dev/null +++ b/src/0004_dynamic_programming/0007_DecodeWays.cc @@ -0,0 +1,61 @@ +#include "0007_DecodeWays.h" + +namespace DecodeWays +{ + int DynamicProgramming::CountWaysRecursiveHelper(string& digits, size_t index) + { + size_t digitsLength = digits.size(); + + // Base case: If the end of the string is reached, return 1 as it signifies a valid decoding. + if (index >= digitsLength) + { + return 1; + } + + int ways = 0; + + // Single digit decoding: check if current digit is not '0'. + if (digits[index] != '0') + { + ways = this->CountWaysRecursiveHelper(digits, index + 1); + } + + // Two digit decoding: check if next two digits are valid. + if ((index + 1 < digitsLength) && ((digits[index] == '1' && digits[index + 1] <= '9') || (digits[index] == '2' && digits[index + 1] <= '6'))) + { + ways += this->CountWaysRecursiveHelper(digits, index + 2); + } + return ways; + } + + int DynamicProgramming::RecursiveCountWays(string digits) + { + return this->CountWaysRecursiveHelper(digits, 0); + } + + int DynamicProgramming::DpCountways(string digits) + { + size_t digitsLength = digits.size(); + + vector dp(digitsLength + 1, 0); + + dp[digitsLength] = 1; + + for (int index = digitsLength - 1; index >= 0; index--) + { + // Single digit decoding: check if current digit is not '0'. + if (digits[index] != '0') + { + dp[index] = dp[index + 1]; + } + + // Two digit decoding: check if next two digits are valid. + if ((index + 1 < digitsLength) && ((digits[index] == '1' && digits[index + 1] <= '9') || (digits[index] == '2' && digits[index + 1] <= '6'))) + { + dp[index] += dp[index + 2]; + } + } + + return dp[0]; + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0008_TilingProblem.cc b/src/0004_dynamic_programming/0008_TilingProblem.cc new file mode 100644 index 0000000..d447c8d --- /dev/null +++ b/src/0004_dynamic_programming/0008_TilingProblem.cc @@ -0,0 +1,42 @@ +#include "0008_TilingProblem.h" + +namespace TilingProblem +{ + int DynamicProgramming::NumberOfWaysRecursiveHelper(int n) + { + if (n < 0) + { + return 0; + } + + if (n == 0) + { + return 1; + } + + int result = 0; + result += this->NumberOfWaysRecursiveHelper(n - 1); + result += this->NumberOfWaysRecursiveHelper(n - 2); + + return result; + } + + int DynamicProgramming::RecursiveNumberOfWays(int n) + { + return this->NumberOfWaysRecursiveHelper(n); + } + + int DynamicProgramming::DpNumberOfWays(int n) + { + vector dp(n + 1, 0); + dp[0] = 1; + dp[1] = 1; + + for (int i = 2; i <= n; i++) + { + dp[i] = dp[i - 1] + dp[i - 2]; + } + + return dp[n]; + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0009_FriendsPairingProblem.cc b/src/0004_dynamic_programming/0009_FriendsPairingProblem.cc new file mode 100644 index 0000000..fbea63f --- /dev/null +++ b/src/0004_dynamic_programming/0009_FriendsPairingProblem.cc @@ -0,0 +1,39 @@ +#include "0009_FriendsPairingProblem.h" + +namespace FriendsPairingProblem +{ + // Dynamic Programming Private Member Methods. + int DynamicProgramming::CountFriendsPairingsRecursiveHelper(int n) + { + if (n <= 1) + { + return 1; + } + int result = 0; + result += this->CountFriendsPairingsRecursiveHelper(n - 1); + result += (n - 1) * this->CountFriendsPairingsRecursiveHelper(n - 2); + + return result; + } + + // Dynamic Programming Public Member Methods. + int DynamicProgramming::RecursiveCountFriendsPairings(int n) + { + return this->CountFriendsPairingsRecursiveHelper(n); + } + + int DynamicProgramming::DpCountFriendsPairings(int n) + { + vector dp(n + 1, 0); + dp[0] = 0; + dp[1] = 1; + dp[2] = 2; + + for (int i = 3; i <= n; i++) + { + dp[i] = dp[i - 1] + (i - 1) * dp[i - 2]; + } + + return dp[n]; + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0010_WaysToCoverDistance.cc b/src/0004_dynamic_programming/0010_WaysToCoverDistance.cc new file mode 100644 index 0000000..b2f0bce --- /dev/null +++ b/src/0004_dynamic_programming/0010_WaysToCoverDistance.cc @@ -0,0 +1,52 @@ +#include "0010_WaysToCoverDistance.h" + +namespace WaysToCoverDistance +{ + // Dynamic Programming Private Member Methods. + int DynamicProgramming::WaysToCoverDistanceRecursiveHelper(int dist) + { + if (dist < 0) + { + return 0; + } + + if (dist == 0) + { + return 1; + } + + int result = 0; + result += this->WaysToCoverDistanceRecursiveHelper(dist - 1); + result += this->WaysToCoverDistanceRecursiveHelper(dist - 2); + result += this->WaysToCoverDistanceRecursiveHelper(dist - 3); + + return result; + } + + // Dynamic Programming Public Member Methods. + int DynamicProgramming::RecursiveWaysToCoverDistance(int dist) + { + return this->WaysToCoverDistanceRecursiveHelper(dist); + } + + int DynamicProgramming::DpWaysToCoverDistance(int dist) + { + vector dp(dist + 1, 0); + dp[0] = 1; + if (dist >= 1) + { + dp[1] = 1; + } + if (dist >= 2) + { + dp[2] = 2; + } + + for(int i = 3; i <= dist; i++) + { + dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]; + } + + return dp[dist]; + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrder.cc b/src/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrder.cc new file mode 100644 index 0000000..f4467e2 --- /dev/null +++ b/src/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrder.cc @@ -0,0 +1,44 @@ +#include "0011_CountWaysToReachNthStairIncludeOrder.h" + +namespace CountWaysToReachNthStairIncludeOrder +{ + // Dynamic Programming Private Member Methods. + int DynamicProgramming::RecursiveCountWaysToReachNthStairIncludeOrderHelper(int n) + { + if (n < 0) + { + return 0; + } + if (n == 0 || n == 1) + { + return 1; + } + + int result = 0; + result += this->RecursiveCountWaysToReachNthStairIncludeOrderHelper(n - 1); + result += this->RecursiveCountWaysToReachNthStairIncludeOrderHelper(n - 2); + + return result; + } + + // Dynamic Programming Public Member Methods. + int DynamicProgramming::RecursiveCountWaysToReachNthStairIncludeOrder(int n) + { + return this->RecursiveCountWaysToReachNthStairIncludeOrderHelper(n); + } + + int DynamicProgramming::DpCountWaysToReachNthStairIncludeOrder(int n) + { + vector dp(n + 1, 0); + dp[0] = 1; + if (n >= 1) + { + dp[1] = 1; + } + for(int i = 2; i <= n; i++) + { + dp[i] = dp[i - 1] + dp[i - 2]; + } + return dp[n]; + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrder.cc b/src/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrder.cc new file mode 100644 index 0000000..0e71a69 --- /dev/null +++ b/src/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrder.cc @@ -0,0 +1,53 @@ +#include "0012_CountWaysToReachNthStairExcludeOrder.h" + +namespace CountWaysToReachNthStairExcludeOrder +{ + // notes: + /* + To avoid counting ways which only differ in order, we can assume that a person initially takes only steps of size 1 followed by steps of size 2. + In other words, once a person takes a step of size 2, he will continue taking steps of size 2 till he reaches the nth stair. + A person can reach nth stair from either(n - 1)th stair or from(n - 2)th stair.So, there are two cases : + The person has reached nth step from(n - 1)th step, this means that the last step was of size 1 and all the previous steps should also be of size 1. So, there is only 1 way. + The person has reached nth step from(n - 2)th step, this means that the last step was of size 2 and the previous steps can either be of size 1 or size 2. + Therefore the Recurrence relation will be : + + nthStair(n) = 1 (last step was of size 1) + nthStair(n - 2) (last step was of size 2) + so f(n) = 1 + f(n - 2) + */ + + // Dynamic Programming Private Member Methods. + int DynamicProgramming::RecursiveCountWaysToReachNthStairExcludeOrderHelper(int n) + { + if (n < 0) + { + return 0; + } + if (n == 0) + { + return 1; + } + + return 1 + this->RecursiveCountWaysToReachNthStairExcludeOrderHelper(n - 2); + } + + // Dynamic Programming Public Member Methods. + int DynamicProgramming::RecursiveCountWaysToReachNthStairExcludeOrder(int n) + { + return this->RecursiveCountWaysToReachNthStairExcludeOrderHelper(n); + } + + int DynamicProgramming::DpCountWaysToReachNthStairExcludeOrder(int n) + { + vector dp(n + 1, 0); + dp[0] = 1; + if (n >= 1) + { + dp[1] = 1; + } + for (int i = 2; i <= n; i++) + { + dp[i] = 1 + dp[i - 2]; + } + return dp[n]; + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0013_KnapsackProblem.cc b/src/0004_dynamic_programming/0013_KnapsackProblem.cc new file mode 100644 index 0000000..e9e5ba2 --- /dev/null +++ b/src/0004_dynamic_programming/0013_KnapsackProblem.cc @@ -0,0 +1,78 @@ +#include "0013_KnapsackProblem.h" + +namespace KnapsackProblem +{ + // Dynamic Programming Private Member Methods. + int DynamicProgramming::KnapsackRecursiveHelper(int capacity, vector& weight, vector& profit, int numberOfItems) + { + if (capacity <= 0 || numberOfItems == 0) + { + return 0; + } + + int pickCurrentItem = 0; + + // Pick the current item only if does not exceed the capacity. + if (weight[numberOfItems - 1] <= capacity) + { + pickCurrentItem = profit[numberOfItems - 1] + this->KnapsackRecursiveHelper(capacity - weight[numberOfItems - 1], weight, profit, numberOfItems - 1); + } + + int dropCurrentItem = this->KnapsackRecursiveHelper(capacity, weight, profit, numberOfItems - 1); + + return max(pickCurrentItem, dropCurrentItem); + } + + // Dynamic Programming Public Member Methods. + int DynamicProgramming::RecursiveKnapsack(int capacity, vector weight, vector profit) + { + size_t totalNumberOfItems = weight.size(); + return this->KnapsackRecursiveHelper(capacity, weight, profit, totalNumberOfItems); + } + + int DynamicProgramming::DpKnapsack(int capacity, vector weight, vector profit) + { + int numberOfItems = weight.size(); + vector> dp(numberOfItems + 1, vector(capacity + 1, 0)); + + for (int i = 0; i <= numberOfItems; i++) + { + for (int j = 0; j <= capacity; j++) + { + if (i == 0 || j == 0) + { + dp[i][j] = 0; + } + else + { + int pickCurrentItem = 0; + if (weight[i - 1] <= j) + { + pickCurrentItem = profit[i - 1] + dp[i - 1][j - weight[i - 1]]; + } + int dropCurrentItem = dp[i - 1][j]; + + dp[i][j] = max(pickCurrentItem, dropCurrentItem); + } + } + } + + return dp[numberOfItems][capacity]; + } + + int DynamicProgramming::DpKnapsackSpaceOptimized(int capacity, vector weight, vector profit) + { + int numberOfItems = weight.size(); + vector dp(capacity + 1, 0); + + for (int i = 1; i <= numberOfItems; i++) + { + for (int j = capacity; j >= weight[i - 1]; j--) + { + dp[j] = max(dp[j], profit[i - 1] + dp[j - weight[i - 1]]); + } + } + + return dp[capacity]; + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0014_SubsetSumProblem.cc b/src/0004_dynamic_programming/0014_SubsetSumProblem.cc new file mode 100644 index 0000000..7f558ba --- /dev/null +++ b/src/0004_dynamic_programming/0014_SubsetSumProblem.cc @@ -0,0 +1,71 @@ +#include "0014_SubsetSumProblem.h" + +namespace SubsetSumProblem +{ + // Dynamic Programming Private Member Methods. + bool DynamicProgramming::SubsetSumRecursiveHelper(vector& nums, int sum, int numberOfElements) + { + // Base case. + // If the sum is 0, we found a subset with a given sum. + if (sum == 0) + { + return true; + } + + // Base case. + // If there are no elements left to process and the sum is not 0 yet, we did not find a subset with given sum, so return false. + if (numberOfElements == 0) + { + return false; + } + + // When the current element is greater than the sum, we skip it, as all elemeents are non-negative. + if (nums[numberOfElements - 1] > sum) + { + return this->SubsetSumRecursiveHelper(nums, sum, numberOfElements - 1); + } + + // When the current element is equal to or less than the sum, we have two choices. + // 1. Include the current element in the subset and the sum is reduced by the current element value and also the number of elements is reducded by 1. + // 2. Exclude the current element from the subset and the sum remains the same but the number of eleements is reduced by 1. + // If either of these two choices return true, we return true. + return this->SubsetSumRecursiveHelper(nums, sum - nums[numberOfElements - 1], numberOfElements - 1) || this->SubsetSumRecursiveHelper(nums, sum, numberOfElements - 1); + } + + // Dynamic Programming Public Member Methods. + bool DynamicProgramming::RecursiveSubsetSum(vector nums, int sum) + { + int numberOfElements = nums.size(); + return this->SubsetSumRecursiveHelper(nums, sum, numberOfElements); + } + + bool DynamicProgramming::DpIsSubsetSum(vector nums, int sum) + { + int numberOfElements = nums.size(); + vector> dp(numberOfElements + 1, vector(sum + 1, false)); + + // When the sum is 0, the result is true + for (int i = 0; i < numberOfElements; i++) + { + dp[i][0] = true; + } + + for (int i = 1; i < numberOfElements + 1; i++) + { + for (int j = 1; j < sum + 1; j++) + { + if (j < nums[i - 1]) + { + dp[i][j] = dp[i - 1][j]; + } + else + { + // include or exclude the current element + dp[i][j] = (dp[i-1][j-nums[i-1]] || dp[i-1][j]); + } + } + } + + return dp[numberOfElements][sum]; + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0015_CountSubsetsForSum.cc b/src/0004_dynamic_programming/0015_CountSubsetsForSum.cc new file mode 100644 index 0000000..64d75b6 --- /dev/null +++ b/src/0004_dynamic_programming/0015_CountSubsetsForSum.cc @@ -0,0 +1,55 @@ +#include "0015_CountSubsetsForSum.h" + +namespace CountSubsetsForSum +{ + // Dynamic Programming private member methods + int DynamicProgramming::RecursiveCountSubsetsHelper(vector& nums, int targetSum, int currentSum, int index) + { + int noOfElements = nums.size(); + if (index == noOfElements) + { + return (targetSum == currentSum); + } + + int exclude = this->RecursiveCountSubsetsHelper(nums, targetSum, currentSum, index + 1); + int include = 0; + + if ((nums[index] + currentSum) <= targetSum) + { + include = this->RecursiveCountSubsetsHelper(nums, targetSum, currentSum + nums[index], index + 1); + } + + return (exclude + include); + } + + // Dynamic Programming public member methods + int DynamicProgramming::RecursiveCountSubsets(vector nums, int sum) + { + return this->RecursiveCountSubsetsHelper(nums, sum, 0, 0); + } + + int DynamicProgramming::DpCountSubsets(vector nums, int sum) + { + int noOfElements = nums.size(); + vector> dp(noOfElements + 1, vector(sum + 1, 0)); + + dp[0][0] = 1; + + for (int i = 1; i <= noOfElements; i++) + { + for (int j = 0; j <= sum; j++) + { + // Considering excluding the current element + dp[i][j] = dp[i - 1][j]; + + // Case to include the current element + if (nums[i - 1] <= j) + { + dp[i][j] += dp[i - 1][j - nums[i - 1]]; + } + } + } + + return dp[noOfElements][sum]; + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0016_PartitionEqualSubsetSum.cc b/src/0004_dynamic_programming/0016_PartitionEqualSubsetSum.cc new file mode 100644 index 0000000..2db0dab --- /dev/null +++ b/src/0004_dynamic_programming/0016_PartitionEqualSubsetSum.cc @@ -0,0 +1,75 @@ +#include "0016_PartitionEqualSubsetSum.h" + +namespace PartitionEqualSubsetSum +{ + bool DynamicProgramming::RecursivePartitionEqualSubsetsHelper(vector& nums, int targetSum, int numberOfElements) + { + if (targetSum == 0) + { + return true; + } + + if (numberOfElements == 0) + { + return false; + } + + if (nums[numberOfElements - 1] > targetSum) + { + return this->RecursivePartitionEqualSubsetsHelper(nums, targetSum, numberOfElements - 1); + } + + return (this->RecursivePartitionEqualSubsetsHelper(nums, targetSum - nums[numberOfElements - 1], numberOfElements - 1) || this->RecursivePartitionEqualSubsetsHelper(nums, targetSum, numberOfElements - 1)); + } + + bool DynamicProgramming::RecursivePartitionEqualSubsets(vector nums) + { + int targetSum = accumulate(nums.begin(), nums.end(), 0); + + // Check if targetSum is odd, then equal partition is not possible at all + if (targetSum % 2 != 0) + { + return false; + } + + int numberOfElements = nums.size(); + return this->RecursivePartitionEqualSubsetsHelper(nums, targetSum / 2, numberOfElements); + } + + bool DynamicProgramming::DpPartitionEqualSubsets(vector nums) + { + int targetSum = accumulate(nums.begin(), nums.end(), 0); + + // Check if targetSum is odd, then equal partition is not possible at all + if (targetSum % 2 != 0) + { + return false; + } + + int numberOfElements = nums.size(); + targetSum /= 2; + vector> dp(numberOfElements + 1, vector(targetSum + 1, false)); + + for (int i = 0; i <= numberOfElements; i++) + { + dp[i][0] = true; + } + + for (int i = 1; i <= numberOfElements; i++) + { + for (int j = 1; j <= targetSum; j++) + { + if (nums[i - 1] > j) + { + dp[i][j] = dp[i - 1][j]; + } + else + { + dp[i][j] = (dp[i-1][j-nums[i-1]] || dp[i-1][j]); + } + } + } + + return dp[numberOfElements][targetSum]; + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0017_TargetSum.cc b/src/0004_dynamic_programming/0017_TargetSum.cc new file mode 100644 index 0000000..c92fe77 --- /dev/null +++ b/src/0004_dynamic_programming/0017_TargetSum.cc @@ -0,0 +1,70 @@ +#include "0017_TargetSum.h" + +namespace TargetSum +{ + int DynamicProgramming::RecursiveFindTotalWaysHelper(vector& nums, int currentSum, int targetSum, int index) + { + // Base case + if (currentSum == targetSum && index == nums.size()) + { + return 1; + } + + if (index >= nums.size()) + { + return 0; + } + + // Return total count of two possible ways while considering the current element + // 1. Add the current element to currentSum + // 2. Subtract the current element from currentSum + return ( + this->RecursiveFindTotalWaysHelper(nums, currentSum + nums[index], targetSum, index + 1) + + + this->RecursiveFindTotalWaysHelper(nums, currentSum - nums[index], targetSum, index + 1)); + } + + int DynamicProgramming::RecursiveFindTotalWays(vector nums, int target) + { + return this->RecursiveFindTotalWaysHelper(nums, 0, target, 0); + } + + int DynamicProgramming::DpFindTotalWays(vector nums, int target) + { + int totalSum = accumulate(nums.begin(), nums.end(), 0); + + if (abs(target) > totalSum) + { + return 0; + } + + int totalSumWithTarget = totalSum + target; + if (totalSumWithTarget % 2 != 0) + { + return 0; + } + + int targetSubsetSum = totalSumWithTarget / 2; + int noOfElements = nums.size(); + vector> dp(noOfElements + 1, vector(targetSubsetSum + 1, 0)); + + dp[0][0] = 1; + + for (int i = 1; i <= noOfElements; i++) + { + for (int j = 0; j <= targetSubsetSum; j++) + { + // Considering excluding the current element + dp[i][j] = dp[i - 1][j]; + + // Case to include the current element + if (nums[i - 1] <= j) + { + dp[i][j] += dp[i - 1][j - nums[i - 1]]; + } + } + } + + return dp[noOfElements][targetSubsetSum]; + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/CMakeLists.txt b/src/0004_dynamic_programming/CMakeLists.txt new file mode 100644 index 0000000..b063b19 --- /dev/null +++ b/src/0004_dynamic_programming/CMakeLists.txt @@ -0,0 +1,28 @@ +# Specify the source files +set(0005DYNAMICPROGRAMMING_SOURCES + 0001_FibonacciNumber.cc + 0002_TribonacciNumber.cc + 0003_ClimbingStairs.cc + 0004_MinimumCostClimbingStairs.cc + 0005_HouseRobber1.cc + 0006_HouseRobber2.cc + 0007_DecodeWays.cc + 0008_TilingProblem.cc + 0009_FriendsPairingProblem.cc + 0010_WaysToCoverDistance.cc + 0011_CountWaysToReachNthStairIncludeOrder.cc + 0012_CountWaysToReachNthStairExcludeOrder.cc + 0013_KnapsackProblem.cc + 0014_SubsetSumProblem.cc + 0015_CountSubsetsForSum.cc + 0016_PartitionEqualSubsetSum.cc + 0017_TargetSum.cc + +) + +# Create a library target +add_library(0005DYNAMICPROGRAMMING ${0005DYNAMICPROGRAMMING_SOURCES}) + +target_include_directories(0005DYNAMICPROGRAMMING PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}/headers +) \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0001_FibonacciNumber.h b/src/0004_dynamic_programming/headers/0001_FibonacciNumber.h new file mode 100644 index 0000000..204aeba --- /dev/null +++ b/src/0004_dynamic_programming/headers/0001_FibonacciNumber.h @@ -0,0 +1,23 @@ +#pragma once +#include +using namespace std; + +/* +Pattern 1 +Linear Recurrence + +Description +Print the n'th Fibonacci number. + +*/ + +namespace FibonacciNumber +{ + class DynamicProgramming + { + private: + public: + int RecursiveNthFibonacci(int n); + int DpNthFibonacci(int n); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0002_TribonacciNumber.h b/src/0004_dynamic_programming/headers/0002_TribonacciNumber.h new file mode 100644 index 0000000..31e805f --- /dev/null +++ b/src/0004_dynamic_programming/headers/0002_TribonacciNumber.h @@ -0,0 +1,23 @@ +#pragma once +#include +using namespace std; + +/* +Pattern 1 +Linear Recurrence + +Description +Print the n'th Tribonacci number. + +*/ + +namespace TribonacciNumber +{ + class DynamicProgramming + { + private: + public: + int RecursiveNthTribonacci(int n); + int DpNthTribonacci(int n); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0003_ClimbingStairs.h b/src/0004_dynamic_programming/headers/0003_ClimbingStairs.h new file mode 100644 index 0000000..e32b71a --- /dev/null +++ b/src/0004_dynamic_programming/headers/0003_ClimbingStairs.h @@ -0,0 +1,24 @@ +#pragma once +#include +using namespace std; + +/* +Pattern 1 +Linear Recurrence + +Description +There are n stairs, and a person standing at the bottom wants to climb stairs to reach the top. +The person can climb either 1 stair or 2 stairs at a time, the task is to count the number of ways that a person can reach at the top. + +*/ + +namespace ClimbingStairs +{ + class DynamicProgramming + { + private: + public: + int RecursiveCountWays(int n); + int DpCountWays(int n); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0004_MinimumCostClimbingStairs.h b/src/0004_dynamic_programming/headers/0004_MinimumCostClimbingStairs.h new file mode 100644 index 0000000..9ef1ec8 --- /dev/null +++ b/src/0004_dynamic_programming/headers/0004_MinimumCostClimbingStairs.h @@ -0,0 +1,25 @@ +#pragma once +#include +using namespace std; + +/* +Pattern 1 +Linear Recurrence + +Description +Given an array of integers cost[] of length n, where cost[i] is the cost of the ith step on a staircase. Once the cost is paid, we can either climb 1 or 2 steps. +We can either start from the step with index 0, or the step with index 1. The task is to find the minimum cost to reach the top. + +*/ + +namespace MinimumCostClimbingStairs +{ + class DynamicProgramming + { + private: + int MinCostRecursive(size_t step, vector& cost); + public: + int RecursiveMinimumCostClimbingStairs(vector& cost); + int DpMinimumCostClimbingStairs(vector& cost); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0005_HouseRobber1.h b/src/0004_dynamic_programming/headers/0005_HouseRobber1.h new file mode 100644 index 0000000..231fbba --- /dev/null +++ b/src/0004_dynamic_programming/headers/0005_HouseRobber1.h @@ -0,0 +1,25 @@ +#pragma once +#include +using namespace std; + +/* +Pattern 1 +Linear Recurrence + +Description +There are n houses built in a line, each of which contains some money in it. +A robber wants to steal money from these houses, but he can’t steal from two adjacent houses. The task is to find the maximum amount of money which can be stolen. + +*/ + +namespace HouseRobber1 +{ + class DynamicProgramming + { + private: + int MaxLootRecursive(size_t house, vector& houseValues); + public: + int RecursiveMaximumLoot(vector& houseValues); + int DpMaximumLoot(vector& houseValues); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0006_HouseRobber2.h b/src/0004_dynamic_programming/headers/0006_HouseRobber2.h new file mode 100644 index 0000000..74c3c93 --- /dev/null +++ b/src/0004_dynamic_programming/headers/0006_HouseRobber2.h @@ -0,0 +1,28 @@ +#pragma once +#include +using namespace std; + +/* +Pattern 1 +Linear Recurrence + +Description +You are given an array arr[] which represents houses arranged in a circle, where each house has a certain value. A thief aims to maximize the total stolen value without robbing two adjacent houses. +Determine the maximum amount the thief can steal. + +Note: Since the houses are in a circle, the first and last houses are also considered adjacent. + +*/ + +namespace HouseRobber2 +{ + class DynamicProgramming + { + private: + int MaxLootRecursive(size_t house, vector& houseValues); + int MaxLootDp(size_t firstHouse, size_t lastHouse, vector& houseValues); + public: + int RecursiveMaximumLoot(vector& houseValues); + int DpMaximumLoot(vector& houseValues); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0007_DecodeWays.h b/src/0004_dynamic_programming/headers/0007_DecodeWays.h new file mode 100644 index 0000000..fe2b6ce --- /dev/null +++ b/src/0004_dynamic_programming/headers/0007_DecodeWays.h @@ -0,0 +1,32 @@ +#pragma once + +#include +#include +using namespace std; + +/* +Pattern 1 +Linear Recurrence + +Description +Let 1 maps to 'A', 2 maps to 'B', ..., 26 to 'Z'.Given a digit sequence, count the number of possible decodings of the given digit sequence. + +Consider the input string "123".There are three valid ways to decode it : +"ABC" : The grouping is(1, 2, 3) -> 'A', 'B', 'C' +"AW" : The grouping is(1, 23) -> 'A', 'W' +"LC" : The grouping is(12, 3) -> 'L', 'C' +Note : Groupings that contain invalid codes(e.g., "0" by itself or numbers greater than "26") are not allowed. +For instance, the string "230" is invalid because "0" cannot stand alone, and "30" is greater than "26", so it cannot represent any letter.The task is to find the total number of valid ways to decode a given string. +*/ + +namespace DecodeWays +{ + class DynamicProgramming + { + private: + int CountWaysRecursiveHelper(string& digits, size_t index); + public: + int RecursiveCountWays(string digits); + int DpCountways(string digits); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0008_TilingProblem.h b/src/0004_dynamic_programming/headers/0008_TilingProblem.h new file mode 100644 index 0000000..e9befb0 --- /dev/null +++ b/src/0004_dynamic_programming/headers/0008_TilingProblem.h @@ -0,0 +1,25 @@ +#pragma once + +#include +using namespace std; + +/* +Pattern 1 +Linear Recurrence + +Description +Given a "2 x n" board and tiles of size "2 x 1", the task is to count the number of ways to tile the given board using the 2 x 1 tiles. +A tile can either be placed horizontally i.e., as a 1 x 2 tile or vertically i.e., as 2 x 1 tile. +*/ + +namespace TilingProblem +{ + class DynamicProgramming + { + private: + int NumberOfWaysRecursiveHelper(int n); + public: + int RecursiveNumberOfWays(int n); + int DpNumberOfWays(int n); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0009_FriendsPairingProblem.h b/src/0004_dynamic_programming/headers/0009_FriendsPairingProblem.h new file mode 100644 index 0000000..79cd9da --- /dev/null +++ b/src/0004_dynamic_programming/headers/0009_FriendsPairingProblem.h @@ -0,0 +1,46 @@ +#pragma once + +#include +using namespace std; + +/* +Pattern 1 +Linear Recurrence + +Description +Given n friends, each one can remain single or can be paired up with some other friend. Each friend can be paired only once. Find out the total number of ways in which friends can remain single or can be paired up. + +Examples: + +Input : n = 3 +Output : 4 +Explanation: +{1}, {2}, {3} : all single +{1}, {2, 3} : 2 and 3 paired but 1 is single. +{1, 2}, {3} : 1 and 2 are paired but 3 is single. +{1, 3}, {2} : 1 and 3 are paired but 2 is single. +Note that {1, 2} and {2, 1} are considered same. + +Mathematical Explanation: +The problem is simplified version of how many ways we can divide n elements into multiple groups. +(here group size will be max of 2 elements). +In case of n = 3, we have only 2 ways to make a group: + 1) all elements are individual(1,1,1) + 2) a pair and individual (2,1) +In case of n = 4, we have 3 ways to form a group: + 1) all elements are individual (1,1,1,1) + 2) 2 individuals and one pair (2,1,1) + 3) 2 separate pairs (2,2) +*/ + +namespace FriendsPairingProblem +{ + class DynamicProgramming + { + private: + int CountFriendsPairingsRecursiveHelper(int n); + public: + int RecursiveCountFriendsPairings(int n); + int DpCountFriendsPairings(int n); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0010_WaysToCoverDistance.h b/src/0004_dynamic_programming/headers/0010_WaysToCoverDistance.h new file mode 100644 index 0000000..0268ff5 --- /dev/null +++ b/src/0004_dynamic_programming/headers/0010_WaysToCoverDistance.h @@ -0,0 +1,47 @@ +#pragma once + +#include +using namespace std; + +/* +Pattern 1 +Linear Recurrence + +Description +Given a distance 'dist', count total number of ways to cover the distance with 1, 2 and 3 steps. + +Examples: + +Input: n = 3 +Output: 4 +Explanation: Below are the four ways +=> 1 step + 1 step + 1 step +=> 1 step + 2 step +=> 2 step + 1 step +=> 3 step + + + +Input: n = 4 +Output: 7 +Explanation: Below are the four ways +=> 1 step + 1 step + 1 step + 1 step +=> 1 step + 2 step + 1 step +=> 2 step + 1 step + 1 step +=> 1 step + 1 step + 2 step +=> 2 step + 2 step +=> 3 step + 1 step +=> 1 step + 3 step +*/ + +namespace WaysToCoverDistance +{ + class DynamicProgramming + { + private: + int WaysToCoverDistanceRecursiveHelper(int dist); + public: + int RecursiveWaysToCoverDistance(int dist); + int DpWaysToCoverDistance(int dist); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0011_CountWaysToReachNthStairIncludeOrder.h b/src/0004_dynamic_programming/headers/0011_CountWaysToReachNthStairIncludeOrder.h new file mode 100644 index 0000000..6851031 --- /dev/null +++ b/src/0004_dynamic_programming/headers/0011_CountWaysToReachNthStairIncludeOrder.h @@ -0,0 +1,42 @@ +#pragma once + +#include +using namespace std; + +/* +Pattern 1 +Linear Recurrence + +Description +There are n stairs, and a person standing at the bottom wants to climb stairs to reach the top. +The person can climb either 1 stair or 2 stairs at a time, the task is to count the number of ways that a person can reach at the top. + +Note: This problem is similar to Count ways to reach Nth stair (Order does not matter) with the only difference that in this problem, +we count all distinct ways where different orderings of the steps are considered unique. + +Examples: + +Input: n = 1 +Output: 1 +Explanation: There is only one way to climb 1 stair. + +Input: n = 2 +Output: 2 +Explanation: There are two ways to reach 2th stair: {1, 1} and {2}. + +Input: n = 4 +Output: 5 +Explanation: There are five ways to reach 4th stair: {1, 1, 1, 1}, {1, 1, 2}, {2, 1, 1}, {1, 2, 1} and {2, 2}. +*/ + +namespace CountWaysToReachNthStairIncludeOrder +{ + class DynamicProgramming + { + private: + int RecursiveCountWaysToReachNthStairIncludeOrderHelper(int n); + public: + int RecursiveCountWaysToReachNthStairIncludeOrder(int n); + int DpCountWaysToReachNthStairIncludeOrder(int n); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0012_CountWaysToReachNthStairExcludeOrder.h b/src/0004_dynamic_programming/headers/0012_CountWaysToReachNthStairExcludeOrder.h new file mode 100644 index 0000000..4d52930 --- /dev/null +++ b/src/0004_dynamic_programming/headers/0012_CountWaysToReachNthStairExcludeOrder.h @@ -0,0 +1,44 @@ +#pragma once + +#include +using namespace std; + +/* +Pattern 1 +Linear Recurrence + +Description +There are n stairs, and a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top (order does not matter). + +Note: The problem is similar to Climbing Stairs - Count ways to reach Nth stair with the only difference that in this problem, we don't have to count those ways which only differ in ordering of the steps. + +Examples: + +Input: n = 1 +Output: 1 +Explanation: There is only one way to climb 1 stair. + +Input: n = 2 +Output: 2 +Explanation: There are two ways to climb 2 stairs: {1, 1} and {2}. + +Input: n = 4 +Output: 3 +Explanation: Three ways to reach 4th stair: {1, 1, 1, 1}, {1, 1, 2} and {2, 2}. + +Input: n = 5 +Output: 3 +Explanation: Three ways to reach 5th stair: {1, 1, 1, 1, 1}, {1, 1, 1, 2} and {1, 2, 2}. +*/ + +namespace CountWaysToReachNthStairExcludeOrder +{ + class DynamicProgramming + { + private: + int RecursiveCountWaysToReachNthStairExcludeOrderHelper(int n); + public: + int RecursiveCountWaysToReachNthStairExcludeOrder(int n); + int DpCountWaysToReachNthStairExcludeOrder(int n); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0013_KnapsackProblem.h b/src/0004_dynamic_programming/headers/0013_KnapsackProblem.h new file mode 100644 index 0000000..b7c90aa --- /dev/null +++ b/src/0004_dynamic_programming/headers/0013_KnapsackProblem.h @@ -0,0 +1,34 @@ +#pragma once + +#include +using namespace std; + +/* +Pattern 2 +Subset / 0-1 Knapsack + +Description +Given n items where each item has some weight and profit associated with it and also given a bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items into the bag such that the sum of profits associated with them is the maximum possible. + +Note: The constraint here is we can either put an item completely into the bag or cannot put it at all [It is not possible to put a part of an item into the bag]. + +Input: W = 4, profit[] = [1, 2, 3], weight[] = [4, 5, 1] +Output: 3 +Explanation: There are two items which have weight less than or equal to 4. If we select the item with weight 4, the possible profit is 1. And if we select the item with weight 1, the possible profit is 3. So the maximum possible profit is 3. Note that we cannot put both the items with weight 4 and 1 together as the capacity of the bag is 4. + +Input: W = 3, profit[] = [1, 2, 3], weight[] = [4, 5, 6] +Output: 0 +*/ + +namespace KnapsackProblem +{ + class DynamicProgramming + { + private: + int KnapsackRecursiveHelper(int capacity, vector& weight, vector& profit, int numberOfItems); + public: + int RecursiveKnapsack(int capacity, vector weight, vector profit); + int DpKnapsack(int capacity, vector weight, vector profit); + int DpKnapsackSpaceOptimized(int capacity, vector weight, vector profit); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0014_SubsetSumProblem.h b/src/0004_dynamic_programming/headers/0014_SubsetSumProblem.h new file mode 100644 index 0000000..399d328 --- /dev/null +++ b/src/0004_dynamic_programming/headers/0014_SubsetSumProblem.h @@ -0,0 +1,34 @@ +#pragma once + +#include +using namespace std; + +/* +Pattern 2 +Subset / 0-1 Knapsack + +Description +Given an array arr[] of non-negative integers and a value sum, the task is to check if there is a subset of the given array whose sum is equal to the given sum. + +Examples: + +Input: arr[] = [3, 34, 4, 12, 5, 2], sum = 9 +Output: True +Explanation: There is a subset (4, 5) with sum 9. + +Input: arr[] = [3, 34, 4, 12, 5, 2], sum = 30 +Output: False +Explanation: There is no subset that add up to 30. +*/ + +namespace SubsetSumProblem +{ + class DynamicProgramming + { + private: + bool SubsetSumRecursiveHelper(vector& nums, int sum, int numberOfElements); + public: + bool RecursiveSubsetSum(vector nums, int sum); + bool DpIsSubsetSum(vector nums, int sum); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0015_CountSubsetsForSum.h b/src/0004_dynamic_programming/headers/0015_CountSubsetsForSum.h new file mode 100644 index 0000000..4f55bbf --- /dev/null +++ b/src/0004_dynamic_programming/headers/0015_CountSubsetsForSum.h @@ -0,0 +1,34 @@ +#pragma once + +#include +using namespace std; + +/* +Pattern 2 +Subset / 0-1 Knapsack + +Description +Given an array arr[] of length n and an integer target, the task is to find the number of subsets with a sum equal to target. + +Examples: + +Input: arr[] = [1, 2, 3, 3], target = 6 +Output: 3 +Explanation: All the possible subsets are [1, 2, 3], [1, 2, 3] and [3, 3] + +Input: arr[] = [1, 1, 1, 1], target = 1 +Output: 4 +Explanation: All the possible subsets are [1], [1], [1] and [1] +*/ + +namespace CountSubsetsForSum +{ + class DynamicProgramming + { + private: + int RecursiveCountSubsetsHelper(vector& nums, int targetSum, int currentSum, int index); + public: + int RecursiveCountSubsets(vector nums, int sum); + int DpCountSubsets(vector nums, int sum); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0016_PartitionEqualSubsetSum.h b/src/0004_dynamic_programming/headers/0016_PartitionEqualSubsetSum.h new file mode 100644 index 0000000..bf3c261 --- /dev/null +++ b/src/0004_dynamic_programming/headers/0016_PartitionEqualSubsetSum.h @@ -0,0 +1,36 @@ +#pragma once + +#include +#include +using namespace std; + +/* +Pattern 2 +Subset / 0-1 Knapsack + +Description +Given an array arr[], check if it can be partitioned into two parts such that the sum of elements in both parts is the same. +Note: Each element is present in either the first subset or the second subset, but not in both. + +Examples: + +Input: arr[] = [1, 5, 11, 5] +Output: true +Explanation: The array can be partitioned as [1, 5, 5] and [11] and the sum of both the subsets are equal. + +Input: arr[] = [1, 5, 3] +Output: false +Explanation: The array cannot be partitioned into equal sum sets. +*/ + +namespace PartitionEqualSubsetSum +{ + class DynamicProgramming + { + private: + bool RecursivePartitionEqualSubsetsHelper(vector& nums, int targetSum, int numberOfElements); + public: + bool RecursivePartitionEqualSubsets(vector nums); + bool DpPartitionEqualSubsets(vector nums); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0017_TargetSum.h b/src/0004_dynamic_programming/headers/0017_TargetSum.h new file mode 100644 index 0000000..1ee27ad --- /dev/null +++ b/src/0004_dynamic_programming/headers/0017_TargetSum.h @@ -0,0 +1,45 @@ +#pragma once + +#include +#include +using namespace std; + +/* +Pattern 2 +Subset / 0-1 Knapsack + +Description +Given an array arr[] of length N and an integer target. +You want to build an expression out of arr[] by adding one of the symbols '+' and '-' before each integer in arr[] and then concatenate all the integers. +Return the number of different expressions that can be built, which evaluates to target. + +Example: + +Input : N = 5, arr[] = {1, 1, 1, 1, 1}, target = 3 +Output: 5 +Explanation: +There are 5 ways to assign symbols to +make the sum of array be target 3. + +-1 + 1 + 1 + 1 + 1 = 3 ++1 - 1 + 1 + 1 + 1 = 3 ++1 + 1 - 1 + 1 + 1 = 3 ++1 + 1 + 1 - 1 + 1 = 3 ++1 + 1 + 1 + 1 - 1 = 3 + +Input: N = 1, arr[] = {1}, target = 1 +Output: 1 +*/ + +namespace TargetSum +{ + class DynamicProgramming + { + private: + int RecursiveFindTotalWaysHelper(vector& nums, int currentSum, int targetSum, int index); + int DpFindTotalWays(); + public: + int RecursiveFindTotalWays(vector nums, int target); + int DpFindTotalWays(vector nums, int target); + }; +} \ No newline at end of file diff --git a/src/0005_greedy_algorithms/CMakeLists.txt b/src/0005_greedy_algorithms/CMakeLists.txt new file mode 100644 index 0000000..e69de29 diff --git a/src/0006_bitwise_algorithms/CMakeLists.txt b/src/0006_bitwise_algorithms/CMakeLists.txt new file mode 100644 index 0000000..e69de29 diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt new file mode 100644 index 0000000..708289d --- /dev/null +++ b/src/CMakeLists.txt @@ -0,0 +1,6 @@ +add_subdirectory(0001_basics) +add_subdirectory(0002_tree) +add_subdirectory(0003_graph) +add_subdirectory(0004_dynamic_programming) +add_subdirectory(0005_greedy_algorithms) +add_subdirectory(0006_bitwise_algorithms) \ No newline at end of file diff --git a/tests/0000_common_utilities/CMakeLists.txt b/tests/0000_common_utilities/CMakeLists.txt new file mode 100644 index 0000000..e69de29 diff --git a/tests/0000_common_utilities/UnitTestHelper.h b/tests/0000_common_utilities/UnitTestHelper.h new file mode 100644 index 0000000..ff676bd --- /dev/null +++ b/tests/0000_common_utilities/UnitTestHelper.h @@ -0,0 +1,183 @@ +#pragma once + +#include +#include +#include +#include +using namespace std; + +class UnitTestHelper +{ +public: + template + string SerializeVectorToString(vector vector) + { + string result = ""; + for (auto& iterator : vector) + { + result += to_string(iterator) + " "; + } + result.pop_back(); + return result; + } + + template + string SerializeVectorToString(vector> vector) + { + string result = ""; + for (auto& iterator : vector) + { + result += to_string(iterator.first) + "(" + to_string(iterator.second) + ")" + " "; + } + + if (!result.empty()) + { + result.pop_back(); + } + return result; + } + + template + string SerializeVectorToString(vector>> vector) + { + string result = ""; + for (auto& iterator : vector) + { + result += to_string(iterator.first) + "(" + to_string(iterator.second.first) + "," + to_string(iterator.second.second) + ")" + " "; + } + + if (!result.empty()) + { + result.pop_back(); + } + return result; + } + + template + string SerializeVectorToString(vector> vector) + { + string result = ""; + for (auto& iterator : vector) + { + result += "["; + for (auto& it : iterator) + { + result += to_string(it) + " "; + } + if (!result.empty()) + { + result.pop_back(); + } + result += "]"; + } + return result; + } + + // This helper method is used to sort the vector of vectors of a particular typename. + // Each inner vector is sorted first. + // Then each of them are sorted by their first element, in increasing order. + template + vector> SortVectorOfVectors(vector> data) + { + // Step 1: Sorting each inner vectors. + for (auto& innerVector : data) + { + sort(innerVector.begin(), innerVector.end()); + } + + // Step 2: Sorting all the vectors by their first element, in increasing order. + sort(data.begin(), data.end(), [](const vector& a, const vector& b) + { + // Checking if both inner vectors are empty to prevent out-of-bounds access. + if (a.empty() && b.empty()) + return false; + + // Considering empty vector as less than non-empty vector. + if (a.empty()) + return true; + + // Considering non-empty vector as greater than empty vector. + if (b.empty()) + return false; + + // Comparing the first elements of each vector. + return (a[0] < b[0]); + }); + + return data; + } + + template + bool NormalizeCyclesAndCompare(vector data1, vector data2) + { + if (data1.size() != data2.size()) + { + return false; + } + + // Normalized rotation of cycle 1 + vector normalizedCycle1(data1); + auto minIterator1 = min_element(normalizedCycle1.begin(), normalizedCycle1.end()); + rotate(normalizedCycle1.begin(), minIterator1, normalizedCycle1.end()); + + // Normalized rotation of cycle 2 + vector normalizedCycle2(data2); + auto minIterator2 = min_element(normalizedCycle2.begin(), normalizedCycle2.end()); + rotate(normalizedCycle2.begin(), minIterator2, normalizedCycle2.end()); + + // Check clock wise + if (normalizedCycle1 == normalizedCycle2) + { + return true; + } + + // Check counter clock wise + reverse(normalizedCycle2.begin() + 1, normalizedCycle2.end()); + return (normalizedCycle1 == normalizedCycle2); + } + + template + vector, T>> SortVectorOfPair(vector, T>> data) + { + for (auto& iterator : data) + { + if (iterator.first.first > iterator.first.second) + { + swap(iterator.first.first, iterator.first.second); + } + } + + sort(data.begin(), data.end(), [](const pair, T>& pairA, const pair, T>& pairB) + { + if (pairA.second == pairB.second) + { + return pairA.first.first < pairB.first.first; + } + return pairA.second < pairB.second; + }); + return data; + } + + template + string SortVectorOfPairAndSerialize(vector> data) + { + // Sorting the vector in non-decreasing order on typename T1 + sort(data.begin(), data.end(), [](const pair& pair1, const pair& pair2) + { + return pair1.first < pair2.first; + }); + + // Serializing the vector to string + string result = ""; + for (auto& iterator : data) + { + result += iterator.first + "(" + to_string(iterator.second) + ")" + " "; + } + + if (!result.empty()) + { + result.pop_back(); + } + return result; + } +}; \ No newline at end of file diff --git a/tests/0001_basics/CMakeLists.txt b/tests/0001_basics/CMakeLists.txt new file mode 100644 index 0000000..efa1008 --- /dev/null +++ b/tests/0001_basics/CMakeLists.txt @@ -0,0 +1,31 @@ +cmake_policy(SET CMP0135 NEW) + +include(FetchContent) +FetchContent_Declare( + googletest + URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip +) +# For Windows: Prevent overriding the parent project's compiler/linker settings +set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) +FetchContent_MakeAvailable(googletest) + + +enable_testing() + +add_executable( + 0001BasicsTests + NodeTest.cc) + +target_link_libraries( + 0001BasicsTests + GTest::gtest_main + 0001BASICS +) + +# Add .clang-tidy configuration to this library. +if(CLANG_TIDY_EXE) + set_target_properties(0001BASICS PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") +endif() + +include(GoogleTest) +gtest_discover_tests(0001BasicsTests DISCOVERY_TIMEOUT 30) \ No newline at end of file diff --git a/tests/0001_basics/NodeTest.cc b/tests/0001_basics/NodeTest.cc new file mode 100644 index 0000000..ca38297 --- /dev/null +++ b/tests/0001_basics/NodeTest.cc @@ -0,0 +1,12 @@ +#include +#include "Node.h" + +// Demonstrate some basic assertions. +namespace NodeTesting +{ + TEST(TestingNodeValue, PositiveTestCase) + { + // Expect two strings not to be equal. + EXPECT_EQ(2 * 4, 8); + } +} \ No newline at end of file diff --git a/tests/0002_tree/0001_BinarySearchTreeTest.cc b/tests/0002_tree/0001_BinarySearchTreeTest.cc new file mode 100644 index 0000000..d99a30e --- /dev/null +++ b/tests/0002_tree/0001_BinarySearchTreeTest.cc @@ -0,0 +1,91 @@ +#include +#include +#include "0001_BinarySearchTree.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace BinarySearchTree +{ + UnitTestHelper unitTestHelper; + + TEST(BSTInsertData, RecursiveInorderTest) + { + BinarySearchTree bst; + bst.InsertNode(50); + bst.InsertNode(30); + bst.InsertNode(60); + + + string actualResult = unitTestHelper.SerializeVectorToString(bst.GetRecursiveInorderTravesalResult()); + string expectedResult = "30 50 60"; + + EXPECT_EQ(actualResult, expectedResult); + } + + TEST(BSTInsertData, RecursivePreorderTest) + { + BinarySearchTree bst; + bst.InsertNode(50); + bst.InsertNode(30); + bst.InsertNode(60); + + string actualResult = unitTestHelper.SerializeVectorToString(bst.GetRecursivePreorderTravesalResult()); + string expectedResult = "50 30 60"; + + EXPECT_EQ(actualResult, expectedResult); + } + + TEST(BSTInsertData, RecursivePostorderTest) + { + BinarySearchTree bst; + bst.InsertNode(50); + bst.InsertNode(30); + bst.InsertNode(60); + + string actualResult = unitTestHelper.SerializeVectorToString(bst.GetRecursivePostorderTravesalResult()); + string expectedResult = "30 60 50"; + + EXPECT_EQ(actualResult, expectedResult); + } + + TEST(BSTInsertData, MorrisInorderTest) + { + BinarySearchTree bst; + bst.InsertNode(50); + bst.InsertNode(30); + bst.InsertNode(60); + + + string actualResult = unitTestHelper.SerializeVectorToString(bst.GetMorrisInorderTraversalResult()); + string expectedResult = "30 50 60"; + + EXPECT_EQ(actualResult, expectedResult); + } + + TEST(BSTInsertData, MorrisPreorderTest) + { + BinarySearchTree bst; + bst.InsertNode(50); + bst.InsertNode(30); + bst.InsertNode(60); + + + string actualResult = unitTestHelper.SerializeVectorToString(bst.GetMorrisPreorderTraversalResult()); + string expectedResult = "50 30 60"; + + EXPECT_EQ(actualResult, expectedResult); + } + + TEST(BSTInsertData, MorrisPostorderTest) + { + BinarySearchTree bst; + bst.InsertNode(50); + bst.InsertNode(30); + bst.InsertNode(60); + + + string actualResult = unitTestHelper.SerializeVectorToString(bst.GetMorrisPostorderTraversalResult()); + string expectedResult = "30 60 50"; + + EXPECT_EQ(actualResult, expectedResult); + } +} \ No newline at end of file diff --git a/tests/0002_tree/CMakeLists.txt b/tests/0002_tree/CMakeLists.txt new file mode 100644 index 0000000..aef689e --- /dev/null +++ b/tests/0002_tree/CMakeLists.txt @@ -0,0 +1,32 @@ +cmake_policy(SET CMP0135 NEW) + +include(FetchContent) +FetchContent_Declare( + googletest + URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip +) + +# For Windows: Prevent overriding the parent project's compiler/linker settings +set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) +FetchContent_MakeAvailable(googletest) + +enable_testing() + +add_executable( + 0002TreeTests + 0001_BinarySearchTreeTest.cc +) + +target_link_libraries( + 0002TreeTests + GTest::gtest_main + 0002TREE +) + +# Add .clang-tidy configuration to this library. +if(CLANG_TIDY_EXE) + set_target_properties(0002TREE PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") +endif() + +include(GoogleTest) +gtest_discover_tests(0002TreeTests DISCOVERY_TIMEOUT 30) \ No newline at end of file diff --git a/tests/0003_graph/0001_BreadthFirstSearchTest.cc b/tests/0003_graph/0001_BreadthFirstSearchTest.cc new file mode 100644 index 0000000..c0beb81 --- /dev/null +++ b/tests/0003_graph/0001_BreadthFirstSearchTest.cc @@ -0,0 +1,45 @@ +#include +#include +#include "../../src/0003_graph/headers/0001_BreadthFirstSearch.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace BreadthFirstSearch +{ + UnitTestHelper unitTestHelper; + + + TEST(BFSTesting, ShowBFSResultTest01) + { + Graph graph; + + graph.PushUndirectedEdge(1, 2); + graph.PushUndirectedEdge(1, 3); + graph.PushUndirectedEdge(2, 4); + graph.PushUndirectedEdge(3, 5); + graph.PushUndirectedEdge(3, 6); + graph.PushUndirectedEdge(5, 6); + graph.PushUndirectedEdge(5, 7); + graph.PushUndirectedEdge(6, 7); + graph.PushUndirectedEdge(6, 8); + graph.PushUndirectedEdge(7, 8); + + graph.BFS(1); + + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowBFSResult()); + string expectedResult = "1(0) 2(1) 3(1) 4(2) 5(2) 6(2) 7(3) 8(3)"; + EXPECT_EQ(actualResult, expectedResult); + } + + TEST(BFSTesting, ShowBFSResultTest02) + { + Graph graph; + + graph.PushUndirectedEdge(1, 2); + + graph.BFS(1); + + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowBFSResult()); + string expectedResult = "1(0) 2(1)"; + EXPECT_EQ(actualResult, expectedResult); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0002_DepthFirstSearchTest.cc b/tests/0003_graph/0002_DepthFirstSearchTest.cc new file mode 100644 index 0000000..c96c55e --- /dev/null +++ b/tests/0003_graph/0002_DepthFirstSearchTest.cc @@ -0,0 +1,177 @@ +#include +#include "0002_DepthFirstSearch.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace DepthFirstSearch +{ + UnitTestHelper unitTestHelper; + + TEST(DFSTesting, ShowDFSResultTest01) + { + Graph graph; + + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(1, 4); + graph.PushDirectedEdge(2, 5); + graph.PushDirectedEdge(3, 5); + graph.PushDirectedEdge(3, 6); + graph.PushDirectedEdge(4, 2); + graph.PushDirectedEdge(5, 4); + graph.PushDirectedEdge(6, 6); + + graph.DFS(); + + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); + string expectedResult = "1(1,8) 2(2,7) 3(9,12) 4(4,5) 5(3,6) 6(10,11)"; + EXPECT_EQ(actualResult, expectedResult); + } + + + TEST(DFSTesting, ShowDFSResultTest_SingleVertex) + { + Graph graph; + + graph.PushDirectedEdge(1, 1); + + graph.DFS(); + + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); + string expectedResult = "1(1,2)"; + EXPECT_EQ(actualResult, expectedResult); + } + + TEST(DFSTesting, ShowDFSResultTest_DisconnectedGraph) + { + Graph graph; + + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(3, 4); + + graph.DFS(); + + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); + string expectedResult = "1(1,4) 2(2,3) 3(5,8) 4(6,7)"; + EXPECT_EQ(actualResult, expectedResult); + } + + TEST(DFSTesting, ShowDFSResultTest_CyclicGraph) + { + Graph graph; + + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(2, 3); + graph.PushDirectedEdge(3, 1); + + graph.DFS(); + + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); + string expectedResult = "1(1,6) 2(2,5) 3(3,4)"; + EXPECT_EQ(actualResult, expectedResult); + } + + TEST(DFSTesting, ShowDFSResultTest_LargeGraph) + { + Graph graph; + + // Adding 15 nodes with several edges + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(1, 3); + graph.PushDirectedEdge(2, 4); + graph.PushDirectedEdge(4, 5); + graph.PushDirectedEdge(5, 6); + graph.PushDirectedEdge(6, 7); + graph.PushDirectedEdge(7, 8); + graph.PushDirectedEdge(8, 9); + graph.PushDirectedEdge(9, 10); + graph.PushDirectedEdge(10, 11); + graph.PushDirectedEdge(11, 12); + graph.PushDirectedEdge(12, 13); + graph.PushDirectedEdge(13, 14); + graph.PushDirectedEdge(14, 15); + graph.PushDirectedEdge(15, 16); + + graph.DFS(); + + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); + string expectedResult = "1(1,32) 2(2,29) 3(30,31) 4(3,28) 5(4,27) 6(5,26) 7(6,25) 8(7,24) 9(8,23) 10(9,22) 11(10,21) 12(11,20) 13(12,19) 14(13,18) 15(14,17) 16(15,16)"; + EXPECT_EQ(actualResult, expectedResult); + } + + TEST(DFSTesting, ShowDFSResultTest_NoEdges) + { + Graph graph; + + // Adding isolated nodes + graph.PushDirectedEdge(1, 1); + graph.PushDirectedEdge(2, 2); + graph.PushDirectedEdge(3, 3); + + graph.DFS(); + + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); + string expectedResult = "1(1,2) 2(3,4) 3(5,6)"; + EXPECT_EQ(actualResult, expectedResult); + } + + TEST(DFSTesting, ShowDFSResultTest_CyclicGraphWithBackEdges) + { + Graph graph; + + // Creating a cycle with back edges + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(2, 3); + graph.PushDirectedEdge(3, 1); // Cycle back to 'a' + graph.PushDirectedEdge(2, 4); // Back edge + + graph.DFS(); + + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); + string expectedResult = "1(1,8) 2(2,7) 3(3,4) 4(5,6)"; + EXPECT_EQ(actualResult, expectedResult); + } + + TEST(DFSTesting, ShowDFSResultTest_DenseGraph) + { + Graph graph; + + // Complete graph of 4 nodes + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(1, 3); + graph.PushDirectedEdge(1, 4); + graph.PushDirectedEdge(2, 1); + graph.PushDirectedEdge(2, 3); + graph.PushDirectedEdge(2, 4); + graph.PushDirectedEdge(3, 1); + graph.PushDirectedEdge(3, 2); + graph.PushDirectedEdge(3, 4); + graph.PushDirectedEdge(4, 1); + graph.PushDirectedEdge(4, 2); + graph.PushDirectedEdge(4, 3); + + graph.DFS(); + + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); + string expectedResult = "1(1,8) 2(2,7) 3(3,6) 4(4,5)"; + EXPECT_EQ(actualResult, expectedResult); + } + + TEST(DFSTesting, ShowDFSResultTest_SelfLoopsAndParallelEdges) + { + Graph graph; + + // Adding self-loops and parallel edges + graph.PushDirectedEdge(1, 1); + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(2, 2); + graph.PushDirectedEdge(2, 3); + graph.PushDirectedEdge(2, 3); // Parallel edge + graph.PushDirectedEdge(3, 3); // Self-loop + + graph.DFS(); + + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); + string expectedResult = "1(1,6) 2(2,5) 3(3,4)"; + EXPECT_EQ(actualResult, expectedResult); + } + +} \ No newline at end of file diff --git a/tests/0003_graph/0003_TopologicalSortTest.cc b/tests/0003_graph/0003_TopologicalSortTest.cc new file mode 100644 index 0000000..6ad277e --- /dev/null +++ b/tests/0003_graph/0003_TopologicalSortTest.cc @@ -0,0 +1,116 @@ +#include +#include "0003_TopologicalSort.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace TopologicalSort +{ + UnitTestHelper unitTestHelper; + + TEST(TopoSortTesting, ShowTopoSortResult) + { + Graph graph; + + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(1, 4); + graph.PushDirectedEdge(2, 3); + graph.PushDirectedEdge(4, 3); + graph.PushSingleNode(5); + graph.PushDirectedEdge(6, 7); + graph.PushDirectedEdge(6, 8); + graph.PushDirectedEdge(7, 4); + graph.PushDirectedEdge(7, 8); + graph.PushDirectedEdge(9, 8); + + graph.TopologicalSort(); + + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); + string expectedResult = "9(17,18) 6(11,16) 7(12,15) 8(13,14) 5(9,10) 1(1,8) 4(6,7) 2(2,5) 3(3,4)"; + + EXPECT_EQ(actualResult, expectedResult); + } + + // Test with a larger graph and multiple paths between nodes + TEST(TopoSortTesting, LargeGraphMultiplePaths) + { + Graph graph; + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(1, 3); + graph.PushDirectedEdge(2, 4); + graph.PushDirectedEdge(3, 4); + graph.PushDirectedEdge(4, 5); + graph.PushDirectedEdge(5, 6); + graph.PushDirectedEdge(6, 7); + + graph.TopologicalSort(); + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); + string expectedResult = "1(1,14) 3(12,13) 2(2,11) 4(3,10) 5(4,9) 6(5,8) 7(6,7)"; + + EXPECT_EQ(actualResult, expectedResult); + } + + // Test with a graph containing disconnected components + TEST(TopoSortTesting, DisconnectedGraph) + { + Graph graph; + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(3, 4); + graph.PushDirectedEdge(5, 6); + + graph.TopologicalSort(); + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); + string expectedResult = "5(9,12) 6(10,11) 3(5,8) 4(6,7) 1(1,4) 2(2,3)"; + + EXPECT_EQ(actualResult, expectedResult); + } + + // Test with a graph that has multiple nodes pointing to the same node + TEST(TopoSortTesting, MultipleIncomingEdges) + { + Graph graph; + graph.PushDirectedEdge(1, 3); + graph.PushDirectedEdge(2, 3); + graph.PushDirectedEdge(3, 4); + + graph.TopologicalSort(); + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); + string expectedResult = "2(7,8) 1(1,6) 3(2,5) 4(3,4)"; + + EXPECT_EQ(actualResult, expectedResult); + } + + // Test for a single-node graph to check the base case + TEST(TopoSortTesting, SingleNodeGraph) + { + Graph graph; + graph.PushSingleNode(1); + + graph.TopologicalSort(); + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); + string expectedResult = "1(1,2)"; + + EXPECT_EQ(actualResult, expectedResult); + } + + TEST(TopoSortTesting, ShowTopoSortResultUsingKahnAlgorithm) + { + Graph graph; + + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(1, 4); + graph.PushDirectedEdge(2, 3); + graph.PushDirectedEdge(4, 3); + graph.PushSingleNode(5); + graph.PushDirectedEdge(6, 7); + graph.PushDirectedEdge(6, 8); + graph.PushDirectedEdge(7, 4); + graph.PushDirectedEdge(7, 8); + graph.PushDirectedEdge(9, 8); + + graph.KahnTopologicalSort(); + + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); + string expectedResult = "1(1,5) 5(2,7) 6(3,8) 9(4,10) 2(6,11) 7(9,12) 4(13,15) 8(14,17) 3(16,18)"; + + EXPECT_EQ(actualResult, expectedResult); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0004_StronglyConnectedComponentsTest.cc b/tests/0003_graph/0004_StronglyConnectedComponentsTest.cc new file mode 100644 index 0000000..f8ede7f --- /dev/null +++ b/tests/0003_graph/0004_StronglyConnectedComponentsTest.cc @@ -0,0 +1,102 @@ +#include +#include "0004_StronglyConnectedComponents.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace StronglyConnectedComponents +{ + UnitTestHelper unitTestHelper; + + // Test case: Testing with a simple graph. + TEST(StronglyConnectedComponentsTesting, SimpleGraphTest) + { + Graph graph; + + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(1, 5); + graph.PushDirectedEdge(2, 3); + graph.PushDirectedEdge(2, 4); + graph.PushDirectedEdge(3, 2); + graph.PushDirectedEdge(4, 4); + graph.PushDirectedEdge(5, 1); + graph.PushDirectedEdge(5, 4); + graph.PushDirectedEdge(6, 1); + graph.PushDirectedEdge(6, 3); + graph.PushDirectedEdge(6, 7); + graph.PushDirectedEdge(7, 3); + graph.PushDirectedEdge(7, 8); + graph.PushDirectedEdge(8, 6); + + auto actualResult = graph.FindAllStronglyConnectedComponents(); + vector> expectedResult = { {6, 8, 7},{1, 5},{2, 3},{4} }; + EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); + } + + // Test case: Single Node. + TEST(StronglyConnectedComponentsTesting, SingleNodeTest) + { + Graph graph; + graph.PushSingleNode(1); + + auto actualResult = graph.FindAllStronglyConnectedComponents(); + vector> expectedResult = { {1} }; + EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); + } + + // Test case: Disconnected Graph. + TEST(StronglyConnectedComponentsTesting, DisconnectedGraphTest) + { + Graph graph; + graph.PushSingleNode(1); + graph.PushSingleNode(2); + graph.PushSingleNode(3); + + auto actualResult = graph.FindAllStronglyConnectedComponents(); + vector> expectedResult = { {1},{3},{2} }; + EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); + } + + // Test case: Chain of Nodes. + TEST(StronglyConnectedComponentsTesting, ChainOfNodesTest) + { + Graph graph; + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(2, 3); + graph.PushDirectedEdge(3, 4); + + auto actualResult = graph.FindAllStronglyConnectedComponents(); + vector> expectedResult = { {2},{1},{3},{4} }; + EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); + } + + // Test case: Bidirectional Edge. + TEST(StronglyConnectedComponentsTesting, BidirectionalEdgeTest) + { + Graph graph; + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(2, 1); + + auto actualResult = graph.FindAllStronglyConnectedComponents(); + vector> expectedResult = { {2, 1} }; + EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); + } + + // Test case: Complex Graph. + TEST(StronglyConnectedComponentsTesting, ComplexGraphTest) + { + Graph graph; + + // Graph structure with multiple SCCs and isolated nodes. + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(2, 3); + graph.PushDirectedEdge(3, 1); // Cycle: 1 -> 2 -> 3 -> 1 + graph.PushDirectedEdge(4, 5); + graph.PushDirectedEdge(5, 6); + graph.PushDirectedEdge(6, 4); // Cycle: 4 -> 5 -> 6 -> 4 + graph.PushDirectedEdge(7, 8); // Single direction: 7 -> 8 + graph.PushSingleNode(9); // Isolated node. + + auto actualResult = graph.FindAllStronglyConnectedComponents(); + vector> expectedResult = { {4, 6, 5},{7}, { 2, 3, 1},{8}, {9} }; + EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0005_HamiltonianPathAndCycleTest.cc b/tests/0003_graph/0005_HamiltonianPathAndCycleTest.cc new file mode 100644 index 0000000..33c351e --- /dev/null +++ b/tests/0003_graph/0005_HamiltonianPathAndCycleTest.cc @@ -0,0 +1,33 @@ +#include +#include "0005_HamiltonianPathAndCycle.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace HamiltonianPathAndCycle +{ + UnitTestHelper unitTestHelper; + + TEST(HamiltonianCycleAndPathTest, ShowResult) + { + Graph graph; + + graph.PushUndirectedEdge(0, 1); + graph.PushUndirectedEdge(0, 3); + graph.PushUndirectedEdge(1, 2); + graph.PushUndirectedEdge(1, 3); + graph.PushUndirectedEdge(1, 4); + graph.PushUndirectedEdge(2, 4); + graph.PushUndirectedEdge(3, 4); + + graph.FindHamiltonianCycleAndPath(); + + bool isHamiltonianCyclePresent = graph.IsHamiltonianCyclePresent(); + bool isHamiltonianPathPresent = graph.IsHamiltonianPathPresent(); + + vector hamiltonianPathActualResult = graph.GetHamiltonianPath(); + vector hamiltonianPathExpectedResult = { 4, 3, 0, 1, 2 }; + + ASSERT_TRUE(isHamiltonianCyclePresent); + ASSERT_TRUE(isHamiltonianPathPresent); + ASSERT_TRUE(unitTestHelper.NormalizeCyclesAndCompare(hamiltonianPathActualResult, hamiltonianPathExpectedResult)); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0006_EulerianPathAndCircuitTest.cc b/tests/0003_graph/0006_EulerianPathAndCircuitTest.cc new file mode 100644 index 0000000..a163a5c --- /dev/null +++ b/tests/0003_graph/0006_EulerianPathAndCircuitTest.cc @@ -0,0 +1,32 @@ +#include +#include "0006_EulerianPathAndCircuit.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace EulerianPathAndCircuit +{ + UnitTestHelper unitTestHelper; + + TEST(EulerianPathAndCycle, Test1) + { + Graph graph; + + graph.PushUndirectedEdge(1, 0); + graph.PushUndirectedEdge(0, 2); + graph.PushUndirectedEdge(2, 1); + graph.PushUndirectedEdge(0, 3); + graph.PushUndirectedEdge(3, 4); + graph.PushUndirectedEdge(4, 0); + + graph.FindEulerianPathAndCircuit(); + + bool isEulerianPathPresent = graph.IsEulerianPathPresent(); + bool isEulerianCircuitPresent = graph.IsEulerianCircuitPresent(); + + vector actualEulerianPath = graph.UndirectedGraphGetEulerianPath(); + vector expectedEulerianPath = { 0, 1, 2, 0, 3, 4, 0}; + + ASSERT_TRUE(isEulerianPathPresent); + ASSERT_TRUE(isEulerianCircuitPresent); + EXPECT_EQ(expectedEulerianPath, actualEulerianPath); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0007_MinimumSpanningTreeKruskalAlgorithmTest.cc b/tests/0003_graph/0007_MinimumSpanningTreeKruskalAlgorithmTest.cc new file mode 100644 index 0000000..5736b79 --- /dev/null +++ b/tests/0003_graph/0007_MinimumSpanningTreeKruskalAlgorithmTest.cc @@ -0,0 +1,45 @@ +#include +#include "0007_MinimumSpanningTreeKruskalAlgorithm.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace MinimumSpanningTreeKruskalAlgorithm +{ + UnitTestHelper unitTestHelper; + + TEST(MST, Kruskal) + { + Graph graph; + + graph.PushUndirectedEdge(1, 2, 4); + graph.PushUndirectedEdge(1, 8, 8); + graph.PushUndirectedEdge(2, 8, 11); + graph.PushUndirectedEdge(2, 3, 8); + graph.PushUndirectedEdge(3, 4, 7); + graph.PushUndirectedEdge(3, 9, 2); + graph.PushUndirectedEdge(3, 6, 4); + graph.PushUndirectedEdge(4, 5, 9); + graph.PushUndirectedEdge(4, 6, 14); + graph.PushUndirectedEdge(5, 6, 10); + graph.PushUndirectedEdge(6, 7, 2); + graph.PushUndirectedEdge(7, 8, 1); + graph.PushUndirectedEdge(7, 9, 6); + graph.PushUndirectedEdge(8, 9, 7); + + graph.FindMinimumSpanningTreeKruskalAlgorithm(); + + vector, int>> actualMST = graph.GetMinimumSpanningTree(); + vector, int>> expectedMST = + { + {{7, 8}, 1}, + {{3, 9}, 2}, + {{6, 7}, 2}, + {{2, 1}, 4}, + {{3, 6}, 4}, + {{3, 4}, 7}, + {{8, 1}, 8}, + {{4, 5}, 9} + }; + + ASSERT_EQ(unitTestHelper.SortVectorOfPair(actualMST), unitTestHelper.SortVectorOfPair(expectedMST)); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0008_MinimumSpanningTreePrimAlgorithmTest.cc b/tests/0003_graph/0008_MinimumSpanningTreePrimAlgorithmTest.cc new file mode 100644 index 0000000..251c654 --- /dev/null +++ b/tests/0003_graph/0008_MinimumSpanningTreePrimAlgorithmTest.cc @@ -0,0 +1,45 @@ +#include +#include "0008_MinimumSpanningTreePrimAlgorithm.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace MinimumSpanningTreePrimAlgorithm +{ + UnitTestHelper unitTestHelper; + + TEST(MST, Prim) + { + Graph graph; + + graph.PushUndirectedEdge(1, 2, 4); + graph.PushUndirectedEdge(1, 8, 8); + graph.PushUndirectedEdge(2, 8, 11); + graph.PushUndirectedEdge(2, 3, 8); + graph.PushUndirectedEdge(3, 4, 7); + graph.PushUndirectedEdge(3, 9, 2); + graph.PushUndirectedEdge(3, 6, 4); + graph.PushUndirectedEdge(4, 5, 9); + graph.PushUndirectedEdge(4, 6, 14); + graph.PushUndirectedEdge(5, 6, 10); + graph.PushUndirectedEdge(6, 7, 2); + graph.PushUndirectedEdge(7, 8, 1); + graph.PushUndirectedEdge(7, 9, 6); + graph.PushUndirectedEdge(8, 9, 7); + + graph.FindMinimumSpanningTreePrimAlgorithm(); + + vector, int>> actualMST = graph.GetMinimumSpanningTree(); + vector, int>> expectedMST = + { + {{7, 8}, 1}, + {{3, 9}, 2}, + {{6, 7}, 2}, + {{2, 1}, 4}, + {{3, 6}, 4}, + {{3, 4}, 7}, + {{8, 1}, 8}, + {{4, 5}, 9} + }; + + ASSERT_EQ(unitTestHelper.SortVectorOfPair(actualMST), unitTestHelper.SortVectorOfPair(expectedMST)); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0009_SingleSourceShortestPathBellmanFordTest.cc b/tests/0003_graph/0009_SingleSourceShortestPathBellmanFordTest.cc new file mode 100644 index 0000000..fc84901 --- /dev/null +++ b/tests/0003_graph/0009_SingleSourceShortestPathBellmanFordTest.cc @@ -0,0 +1,104 @@ +#include +#include "0009_SingleSourceShortestPathBellmanFord.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace SingleSourceShortestPathBellmanFord +{ + UnitTestHelper unitTestHelper; + + // Test for Simple Graph + TEST(BellmanFordTest, SimpleTest) + { + Graph graph; + + graph.PushDirectedEdge(0, 1, 6); + graph.PushDirectedEdge(0, 3, 7); + graph.PushDirectedEdge(1, 2, 5); + graph.PushDirectedEdge(1, 3, 8); + graph.PushDirectedEdge(1, 4, -4); + graph.PushDirectedEdge(2, 1, -2); + graph.PushDirectedEdge(3, 2, -3); + graph.PushDirectedEdge(3, 4, 9); + graph.PushDirectedEdge(3, 4, 9); + graph.PushDirectedEdge(4, 2, 7); + graph.PushDirectedEdge(4, 0, 2); + + string expectedResult = "0 3 2 1 4"; + ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); + ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(4)), expectedResult); + } + + // Test for Single Node Graph + TEST(BellmanFordTest, SingleNodeTest) + { + Graph graph; + graph.PushDirectedEdge(0, 0, 0); // Self-loop + + string expectedResult = "0"; + ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); + ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(0)), expectedResult); + } + + // Test for Negative Weight Cycle + TEST(BellmanFordTest, NegativeWeightCycleTest) + { + Graph graph; + graph.PushDirectedEdge(0, 1, 1); + graph.PushDirectedEdge(1, 2, -1); + graph.PushDirectedEdge(2, 0, -1); // Negative weight cycle + + ASSERT_FALSE(graph.FindSingleSourceShortestPathBellmanFord(0)); + } + + // Test for Multiple Shortest Paths + TEST(BellmanFordTest, MultipleShortestPathsTest) + { + Graph graph; + graph.PushDirectedEdge(0, 1, 5); + graph.PushDirectedEdge(0, 2, 5); + graph.PushDirectedEdge(1, 3, 1); + graph.PushDirectedEdge(2, 3, 1); + + string expectedResult = "0 1 3"; + ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); + ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(3)), expectedResult); + } + + // Test for All Negative Weights + TEST(BellmanFordTest, AllNegativeWeightsTest) + { + Graph graph; + graph.PushDirectedEdge(0, 1, -5); + graph.PushDirectedEdge(1, 2, -3); + graph.PushDirectedEdge(2, 3, -2); + graph.PushDirectedEdge(3, 4, -1); + + string expectedResult = "0 1 2 3 4"; + ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); + ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(4)), expectedResult); + } + + // Test for Large Graph + TEST(BellmanFordTest, LargeGraphTest) + { + Graph graph; + for (int i = 0; i < 100; ++i) { + graph.PushDirectedEdge(i, i + 1, 1); + } + + string expectedResult = "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20"; + ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); + ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(20)), expectedResult); + } + + // Test for Self-Loop Edge + TEST(BellmanFordTest, SelfLoopTest) + { + Graph graph; + graph.PushDirectedEdge(0, 0, 10); // Self-loop with weight 10 + + string expectedResult = "0"; + ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); + ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(0)), expectedResult); + } +} diff --git a/tests/0003_graph/0010_DirectedAcyclicGraphShortestPathTest.cc b/tests/0003_graph/0010_DirectedAcyclicGraphShortestPathTest.cc new file mode 100644 index 0000000..50d7086 --- /dev/null +++ b/tests/0003_graph/0010_DirectedAcyclicGraphShortestPathTest.cc @@ -0,0 +1,29 @@ +#include +#include "0010_DirectedAcyclicGraphShortestPath.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace DirectedAcyclicGraphShortestPath +{ + UnitTestHelper unitTestHelper; + + // Test for Simple Graph + TEST(DAGTest, SimpleGraph) + { + Graph graph; + + graph.PushDirectedEdge(0, 1, 5); + graph.PushDirectedEdge(0, 2, 3); + graph.PushDirectedEdge(1, 2, 2); + graph.PushDirectedEdge(1, 3, 6); + graph.PushDirectedEdge(2, 3, 7); + graph.PushDirectedEdge(2, 4, 4); + graph.PushDirectedEdge(2, 5, 2); + graph.PushDirectedEdge(3, 4, -1); + graph.PushDirectedEdge(3, 5, 1); + graph.PushDirectedEdge(4, 5, -2); + + graph.FindDAGShortestPath(1); + string expectedPath = "1 3 4 5"; + ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetDAGShortestPath(5)), expectedPath); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0011_SingleSourceShortestPathDijkstraTest.cc b/tests/0003_graph/0011_SingleSourceShortestPathDijkstraTest.cc new file mode 100644 index 0000000..5460b1b --- /dev/null +++ b/tests/0003_graph/0011_SingleSourceShortestPathDijkstraTest.cc @@ -0,0 +1,31 @@ +#include +#include "0011_SingleSourceShortestPathDijkstra.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace SingleSourceShortestPathDijkstra +{ + UnitTestHelper unitTestHelper; + + // Test for Simple Graph + TEST(DijkstraTest, SimpleGraph) + { + Graph graph; + + graph.PushDirectedEdge(0, 1, 10); + graph.PushDirectedEdge(0, 3, 5); + graph.PushDirectedEdge(1, 2, 1); + graph.PushDirectedEdge(1, 3, 2); + graph.PushDirectedEdge(2, 4, 4); + graph.PushDirectedEdge(3, 1, 3); + graph.PushDirectedEdge(3, 2, 9); + graph.PushDirectedEdge(3, 4, 2); + graph.PushDirectedEdge(4, 2, 6); + graph.PushDirectedEdge(4, 0, 7); + + graph.FindShortestPathDijkstra(0); + + string expectedPath = "0 3 1 2"; + + ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetDijkstraShortestPath(2)), expectedPath); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0012_DifferenceConstraintsShortestPathsTest.cc b/tests/0003_graph/0012_DifferenceConstraintsShortestPathsTest.cc new file mode 100644 index 0000000..152dd0d --- /dev/null +++ b/tests/0003_graph/0012_DifferenceConstraintsShortestPathsTest.cc @@ -0,0 +1,40 @@ +#include +#include "0012_DifferenceConstraintsShortestPaths.h" +#include"../0000_common_utilities/UnitTestHelper.h" +using namespace std; + +namespace DifferenceConstraintsShortestPaths +{ + UnitTestHelper unitTestHelper; + + TEST(DifferenceConstraints, SimpleGraph) + { + Graph graph; + + vector> vectorA = + { + {1, -1, 0, 0, 0}, + {1, 0, 0, 0, -1}, + {0, 1, 0, 0, -1}, + {-1, 0, 1, 0, 0}, + {-1, 0, 0, 1, 0}, + {0, 0, -1, 1, 0}, + {0, 0, -1, 0, 1}, + {0, 0, 0, -1, 1}, + }; + vector vectorX = { "v1", "v2", "v3", "v4", "v5" }; + vector vectorB = {0, -1, 1, 5, 4, -1, -3, -3}; + vector> expectedSolution = + { + {"v2", -3}, + {"v5", -4}, + {"v1", -5}, + {"v4", -1}, + {"v3", 0}, + }; + graph.PushAllDirectedEdges(vectorA, vectorX, vectorB); + + ASSERT_TRUE(graph.FindDifferenceConstraintsSolutionBellmanFord()); + ASSERT_EQ(unitTestHelper.SortVectorOfPairAndSerialize(graph.GetDifferenceConstrtaintsSolution()), unitTestHelper.SortVectorOfPairAndSerialize(expectedSolution)); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0013_AllPairsShortestPathsFloydWarshallTest.cc b/tests/0003_graph/0013_AllPairsShortestPathsFloydWarshallTest.cc new file mode 100644 index 0000000..17a5045 --- /dev/null +++ b/tests/0003_graph/0013_AllPairsShortestPathsFloydWarshallTest.cc @@ -0,0 +1,36 @@ +#include +#include "0013_AllPairsShortestPathsFloydWarshall.h" +#include "../0000_common_utilities/UnitTestHelper.h" +using namespace std; + +namespace AllPairsShortestPathsFloydWarshall +{ + UnitTestHelper unitTestHelper; + + TEST(FloydWarshall, SimpleGraph) + { + // Arrange + Graph graph; + int noOfVertices = 5; + string expectedResult = "[1 5 4 3 2][1 5 4 3][1 5 4][1 5][2 4 1][2 4 3][2 4][2 4 1 5][3 2 4 1][3 2][3 2 4][3 2 4 1 5][4 1][4 3 2][4 3][4 1 5][5 4 1][5 4 3 2][5 4 3][5 4]"; + + // Act + graph.CreateGraph(noOfVertices); + + graph.PushDirectedEdge(1, 2, 3); + graph.PushDirectedEdge(1, 3, 8); + graph.PushDirectedEdge(1, 5, -4); + graph.PushDirectedEdge(2, 4, 1); + graph.PushDirectedEdge(2, 5, 7); + graph.PushDirectedEdge(3, 2, 4); + graph.PushDirectedEdge(4, 3, -5); + graph.PushDirectedEdge(4, 1, 2); + graph.PushDirectedEdge(5, 4, 6); + + graph.FindAllPairsShortestPathsFloydWarshallSolution(); + string actualResult = unitTestHelper.SerializeVectorToString(graph.GetFloydWarshallShortestPath()); + + // Assert + ASSERT_EQ(actualResult, expectedResult); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0014_AllPairsShortestPathsJohnsonTest.cc b/tests/0003_graph/0014_AllPairsShortestPathsJohnsonTest.cc new file mode 100644 index 0000000..66a63a1 --- /dev/null +++ b/tests/0003_graph/0014_AllPairsShortestPathsJohnsonTest.cc @@ -0,0 +1,44 @@ +#include +#include "0014_AllPairsShortestPathsJohnson.h" +#include"../0000_common_utilities/UnitTestHelper.h" +using namespace std; + +namespace AllPairsShortestPathsJohnson +{ + UnitTestHelper unitTestHelper; + + TEST(JohnsonAlgorithm, SimpleGraph) + { + // Arrange + Graph graph; + vector> expectedDistanceMatrix = + { + {0, 1, -3, 2, -4}, + {3, 0, -4, 1, -1}, + {7, 4, 0, 5, 3}, + {2, -1, -5, 0, -2}, + {8, 5, 1, 6, 0}, + }; + string expectedPredecessorMatrixesult = "[1 5 4 3 2][1 5 4 3][1 5 4][1 5][2 4 1][2 4 3][2 4][2 4 1 5][3 2 4 1][3 2][3 2 4][3 2 4 1 5][4 1][4 3 2][4 3][4 1 5][5 4 1][5 4 3 2][5 4 3][5 4]"; + + // Act + graph.PushDirectedEdge(1, 2, 3); + graph.PushDirectedEdge(1, 3, 8); + graph.PushDirectedEdge(1, 5, -4); + graph.PushDirectedEdge(2, 4, 1); + graph.PushDirectedEdge(2, 5, 7); + graph.PushDirectedEdge(3, 2, 4); + graph.PushDirectedEdge(4, 3, -5); + graph.PushDirectedEdge(4, 1, 2); + graph.PushDirectedEdge(5, 4, 6); + + bool result = graph.FindAllPairsShortestPathsJohnsonAlgorithm(); + vector> actualDistanceMatrix = graph.GetAllPairsShortestPathsDistanceMatrix(); + string actualPredecessorMatrix = unitTestHelper.SerializeVectorToString(graph.GetAllPairsShortestPathsPathMatrix()); + + // Assert + ASSERT_TRUE(result); + ASSERT_EQ(expectedDistanceMatrix, actualDistanceMatrix); + ASSERT_EQ(expectedPredecessorMatrixesult, actualPredecessorMatrix); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0015_MaximumFlowFordFulkersonTest.cc b/tests/0003_graph/0015_MaximumFlowFordFulkersonTest.cc new file mode 100644 index 0000000..117bfc2 --- /dev/null +++ b/tests/0003_graph/0015_MaximumFlowFordFulkersonTest.cc @@ -0,0 +1,64 @@ +#include +#include "0015_MaximumFlowFordFulkerson.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace MaximumFlowFordFulkerson +{ + UnitTestHelper unitTestHelper; + + TEST(MaximumFlowFordFulkerson, GraphWithNoParallelEdges) + { + // Arrange + Graph graph; + int noOfVertices = 6; + int expectedMaximumFlow = 23; + + + // Act + graph.CreateGraph(noOfVertices); + + graph.PushDirectedEdge(0, 1, 16); + graph.PushDirectedEdge(0, 2, 13); + graph.PushDirectedEdge(1, 3, 12); + graph.PushDirectedEdge(2, 1, 4); + graph.PushDirectedEdge(2, 4, 14); + graph.PushDirectedEdge(3, 2, 9); + graph.PushDirectedEdge(3, 5, 20); + graph.PushDirectedEdge(4, 3, 7); + graph.PushDirectedEdge(4, 5, 4); + + int actualMaximumFlow = graph.FindMaximumFlowFordFulkerson(); + + // Assert + ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); + } + + TEST(MaximumFlowFordFulkerson, GraphWithParallelEdges) + { + // Arrange + Graph graph; + int noOfVertices = 6; + int expectedMaximumFlow = 24; + + + // Act + graph.CreateGraph(noOfVertices); + + graph.PushDirectedEdge(0, 1, 16); + graph.PushDirectedEdge(0, 2, 13); + graph.PushDirectedEdge(1, 3, 12); + graph.PushDirectedEdge(1, 2, 6); + graph.PushDirectedEdge(2, 1, 10); + graph.PushDirectedEdge(2, 4, 14); + graph.PushDirectedEdge(2, 3, 2); + graph.PushDirectedEdge(3, 2, 11); + graph.PushDirectedEdge(3, 5, 20); + graph.PushDirectedEdge(4, 3, 7); + graph.PushDirectedEdge(4, 5, 4); + + int actualMaximumFlow = graph.FindMaximumFlowFordFulkerson(); + + // Assert + ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0016_MaximumFlowEdmondsKarpTest.cc b/tests/0003_graph/0016_MaximumFlowEdmondsKarpTest.cc new file mode 100644 index 0000000..5d3177a --- /dev/null +++ b/tests/0003_graph/0016_MaximumFlowEdmondsKarpTest.cc @@ -0,0 +1,64 @@ +#include +#include "0016_MaximumFlowEdmondsKarp.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace MaximumFlowEdmondsKarp +{ + UnitTestHelper unitTestHelper; + + TEST(MaximumFlowEdmondsKarp, GraphWithNoParallelEdges) + { + // Arrange + Graph graph; + int noOfVertices = 6; + int expectedMaximumFlow = 23; + + + // Act + graph.CreateGraph(noOfVertices); + + graph.PushDirectedEdge(0, 1, 16); + graph.PushDirectedEdge(0, 2, 13); + graph.PushDirectedEdge(1, 3, 12); + graph.PushDirectedEdge(2, 1, 4); + graph.PushDirectedEdge(2, 4, 14); + graph.PushDirectedEdge(3, 2, 9); + graph.PushDirectedEdge(3, 5, 20); + graph.PushDirectedEdge(4, 3, 7); + graph.PushDirectedEdge(4, 5, 4); + + int actualMaximumFlow = graph.FindMaximumFlowEdmondsKarp(); + + // Assert + ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); + } + + TEST(MaximumFlowEdmondsKarp, GraphWithParallelEdges) + { + // Arrange + Graph graph; + int noOfVertices = 6; + int expectedMaximumFlow = 24; + + + // Act + graph.CreateGraph(noOfVertices); + + graph.PushDirectedEdge(0, 1, 16); + graph.PushDirectedEdge(0, 2, 13); + graph.PushDirectedEdge(1, 3, 12); + graph.PushDirectedEdge(1, 2, 6); + graph.PushDirectedEdge(2, 1, 10); + graph.PushDirectedEdge(2, 4, 14); + graph.PushDirectedEdge(2, 3, 2); + graph.PushDirectedEdge(3, 2, 11); + graph.PushDirectedEdge(3, 5, 20); + graph.PushDirectedEdge(4, 3, 7); + graph.PushDirectedEdge(4, 5, 4); + + int actualMaximumFlow = graph.FindMaximumFlowEdmondsKarp(); + + // Assert + ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0017_MaximumBipartiteMatchingTest.cc b/tests/0003_graph/0017_MaximumBipartiteMatchingTest.cc new file mode 100644 index 0000000..d556e28 --- /dev/null +++ b/tests/0003_graph/0017_MaximumBipartiteMatchingTest.cc @@ -0,0 +1,35 @@ +#include +#include "0017_MaximumBipartiteMatching.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace MaximumBipartiteMatching +{ + TEST(MaximumBipartiteMatching, SimpleGraph) + { + // Arrange + Graph graph; + UnitTestHelper unitTestHelper; + int noOfVertices = 9; + int expectedMaximumMatching = 3; + string expectedMatchings = "[0 1][2 6][3 5]"; + + // Act + graph.CreateGraph(noOfVertices); + + graph.PushDirectedEdge(0, 1); + graph.PushDirectedEdge(2, 1); + graph.PushDirectedEdge(2, 6); + graph.PushDirectedEdge(3, 5); + graph.PushDirectedEdge(3, 6); + graph.PushDirectedEdge(3, 7); + graph.PushDirectedEdge(4, 6); + graph.PushDirectedEdge(8, 6); + + int actualMaximumMatching = graph.FindMaximumBipartiteMatching(); + vector> actualMatchings = graph.GetMatchings(); + + // Assert + ASSERT_EQ(expectedMaximumMatching, actualMaximumMatching); + ASSERT_EQ(expectedMatchings, unitTestHelper.SerializeVectorToString(actualMatchings)); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0018_MaximumFlowGoldbergGenericPushRelabelTest.cc b/tests/0003_graph/0018_MaximumFlowGoldbergGenericPushRelabelTest.cc new file mode 100644 index 0000000..283cab0 --- /dev/null +++ b/tests/0003_graph/0018_MaximumFlowGoldbergGenericPushRelabelTest.cc @@ -0,0 +1,35 @@ +#include +#include "0018_MaximumFlowGoldbergGenericPushRelabel.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace MaximumFlowGoldbergGenericPushRelabel +{ + UnitTestHelper unitTestHelper; + + TEST(MaximumFlowGoldbergGenericPushRelabel, GraphWithNoParallelEdges) + { + // Arrange + Graph graph; + int noOfVertices = 6; + int expectedMaximumFlow = 23; + + + // Act + graph.CreateGraph(noOfVertices); + + graph.PushDirectedEdge(0, 1, 16); + graph.PushDirectedEdge(0, 2, 13); + graph.PushDirectedEdge(1, 3, 12); + graph.PushDirectedEdge(2, 1, 4); + graph.PushDirectedEdge(2, 4, 14); + graph.PushDirectedEdge(3, 2, 9); + graph.PushDirectedEdge(3, 5, 20); + graph.PushDirectedEdge(4, 3, 7); + graph.PushDirectedEdge(4, 5, 4); + + int actualMaximumFlow = graph.FindMaximumFlowGoldbergGenericPushRelabel(); + + // Assert + ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0019_MaximumFlowRelabelToFrontTest.cc b/tests/0003_graph/0019_MaximumFlowRelabelToFrontTest.cc new file mode 100644 index 0000000..a73b89d --- /dev/null +++ b/tests/0003_graph/0019_MaximumFlowRelabelToFrontTest.cc @@ -0,0 +1,36 @@ +#include +#include "0019_MaximumFlowRelabelToFront.h" +#include "../0000_common_utilities/UnitTestHelper.h" +using namespace std; + +namespace MaximumFlowRelabelToFront +{ + UnitTestHelper unitTestHelper; + + TEST(MaximumFlowRelabelToFront, SimpleGraph) + { + // Arrange + Graph graph; + int noOfVertices = 6; + int expectedMaximumFlow = 23; + + + // Act + graph.CreateGraph(noOfVertices); + + graph.PushDirectedEdge(0, 1, 16); + graph.PushDirectedEdge(0, 2, 13); + graph.PushDirectedEdge(1, 3, 12); + graph.PushDirectedEdge(2, 1, 4); + graph.PushDirectedEdge(2, 4, 14); + graph.PushDirectedEdge(3, 2, 9); + graph.PushDirectedEdge(3, 5, 20); + graph.PushDirectedEdge(4, 3, 7); + graph.PushDirectedEdge(4, 5, 4); + + int actualMaximumFlow = graph.FindMaximumFlowRelabelToFront(); + + // Assert + ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); + } +} \ No newline at end of file diff --git a/tests/0003_graph/CMakeLists.txt b/tests/0003_graph/CMakeLists.txt new file mode 100644 index 0000000..275d4a8 --- /dev/null +++ b/tests/0003_graph/CMakeLists.txt @@ -0,0 +1,50 @@ +cmake_policy(SET CMP0135 NEW) + +include(FetchContent) +FetchContent_Declare( + googletest + URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip +) + +# For Windows: Prevent overriding the parent project's compiler/linker settings +set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) +FetchContent_MakeAvailable(googletest) + +enable_testing() + +add_executable( + 0003GraphTests + 0001_BreadthFirstSearchTest.cc + 0002_DepthFirstSearchTest.cc + 0003_TopologicalSortTest.cc + 0004_StronglyConnectedComponentsTest.cc + 0005_HamiltonianPathAndCycleTest.cc + 0006_EulerianPathAndCircuitTest.cc + 0007_MinimumSpanningTreeKruskalAlgorithmTest.cc + 0008_MinimumSpanningTreePrimAlgorithmTest.cc + 0009_SingleSourceShortestPathBellmanFordTest.cc + 0010_DirectedAcyclicGraphShortestPathTest.cc + 0011_SingleSourceShortestPathDijkstraTest.cc + 0012_DifferenceConstraintsShortestPathsTest.cc + 0013_AllPairsShortestPathsFloydWarshallTest.cc + 0014_AllPairsShortestPathsJohnsonTest.cc + 0015_MaximumFlowFordFulkersonTest.cc + 0016_MaximumFlowEdmondsKarpTest.cc + 0017_MaximumBipartiteMatchingTest.cc + 0018_MaximumFlowGoldbergGenericPushRelabelTest.cc + 0019_MaximumFlowRelabelToFrontTest.cc +) + +target_link_libraries( + 0003GraphTests + GTest::gtest_main + 0003GRAPH +) + +# Add .clang-tidy configuration to this library. +if(CLANG_TIDY_EXE) + set_target_properties(0003GRAPH PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") +endif() + +include(GoogleTest) +gtest_discover_tests(0003GraphTests DISCOVERY_TIMEOUT 30) \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0001_FibonacciNumberTest.cc b/tests/0004_dynamic_programming/0001_FibonacciNumberTest.cc new file mode 100644 index 0000000..1fdd9a4 --- /dev/null +++ b/tests/0004_dynamic_programming/0001_FibonacciNumberTest.cc @@ -0,0 +1,34 @@ +#include +#include "0001_FibonacciNumber.h" +using namespace std; + +namespace FibonacciNumber +{ + TEST(FibonacciNumber, RecursiveTest) + { + // Arrange + DynamicProgramming dp; + int n = 5; + int expectedFib = 5; + + // Act + int actualFib = dp.RecursiveNthFibonacci(n); + + // Assert + ASSERT_EQ(expectedFib, actualFib); + } + + TEST(FibonacciNumber, DpTest) + { + // Arrange + DynamicProgramming dp; + int n = 5; + int expectedFib = 5; + + // Act + int actualFib = dp.DpNthFibonacci(n); + + // Assert + ASSERT_EQ(expectedFib, actualFib); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0002_TribonacciNumberTest.cc b/tests/0004_dynamic_programming/0002_TribonacciNumberTest.cc new file mode 100644 index 0000000..d25c394 --- /dev/null +++ b/tests/0004_dynamic_programming/0002_TribonacciNumberTest.cc @@ -0,0 +1,34 @@ +#include +#include "0002_TribonacciNumber.h" +using namespace std; + +namespace TribonacciNumber +{ + TEST(TribonacciNumber, RecursiveTest) + { + // Arrange + DynamicProgramming dp; + int n = 5; + int expectedFib = 2; + + // Act + int actualFib = dp.RecursiveNthTribonacci(n); + + // Assert + ASSERT_EQ(expectedFib, actualFib); + } + + TEST(TribonacciNumber, DpTest) + { + // Arrange + DynamicProgramming dp; + int n = 10; + int expectedFib = 44; + + // Act + int actualFib = dp.DpNthTribonacci(n); + + // Assert + ASSERT_EQ(expectedFib, actualFib); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0003_ClimbingStairsTest.cc b/tests/0004_dynamic_programming/0003_ClimbingStairsTest.cc new file mode 100644 index 0000000..0504cbc --- /dev/null +++ b/tests/0004_dynamic_programming/0003_ClimbingStairsTest.cc @@ -0,0 +1,33 @@ +#include +#include "0003_ClimbingStairs.h" + +namespace ClimbingStairs +{ + TEST(ClimbingStairs, RecursiveTest) + { + // Arrange + DynamicProgramming dp; + int n = 4; + int expectedCount = 5; + + // Act + int actualCount = dp.RecursiveCountWays(n); + + // Assert + ASSERT_EQ(expectedCount, actualCount); + } + + TEST(ClimbingStairs, DpTest) + { + // Arrange + DynamicProgramming dp; + int n = 4; + int expectedCount = 5; + + // Act + int actualCount = dp.DpCountWays(n); + + // Assert + ASSERT_EQ(expectedCount, actualCount); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0004_MinimumCostClimbingStairsTest.cc b/tests/0004_dynamic_programming/0004_MinimumCostClimbingStairsTest.cc new file mode 100644 index 0000000..b488105 --- /dev/null +++ b/tests/0004_dynamic_programming/0004_MinimumCostClimbingStairsTest.cc @@ -0,0 +1,33 @@ +#include +#include "0004_MinimumCostClimbingStairs.h" + +namespace MinimumCostClimbingStairs +{ + TEST(MinimumCostClimbingStairs, RecursionTest) + { + // Arrange + DynamicProgramming dp; + vector cost = { 16, 19, 10, 12, 18 }; + int expectedCost = 31; + + // Act + int actualCost = dp.RecursiveMinimumCostClimbingStairs(cost); + + // Assert + ASSERT_EQ(expectedCost, actualCost); + } + + TEST(MinimumCostClimbingStairs, DpTest) + { + // Arrange + DynamicProgramming dp; + vector cost = { 16, 19, 10, 12, 18 }; + int expectedCost = 31; + + // Act + int actualCost = dp.DpMinimumCostClimbingStairs(cost); + + // Assert + ASSERT_EQ(expectedCost, actualCost); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0005_HouseRobber1Test.cc b/tests/0004_dynamic_programming/0005_HouseRobber1Test.cc new file mode 100644 index 0000000..d3f6312 --- /dev/null +++ b/tests/0004_dynamic_programming/0005_HouseRobber1Test.cc @@ -0,0 +1,33 @@ +#include +#include "0005_HouseRobber1.h" + +namespace HouseRobber1 +{ + TEST(HouseRobber1, RecursionTest) + { + // Arrange + DynamicProgramming dp; + vector houseValues = { 6, 7, 1, 3, 8, 2, 4 }; + int expectedMaximumLoot = 19; + + // Act + int actualMaximumLoot = dp.RecursiveMaximumLoot(houseValues); + + // Assert + ASSERT_EQ(expectedMaximumLoot, actualMaximumLoot); + } + + TEST(HouseRobber1, DpTest) + { + // Arrange + DynamicProgramming dp; + vector houseValues = { 6, 7, 1, 3, 8, 2, 4 }; + int expectedMaximumLoot = 19; + + // Act + int actualMaximumLoot = dp.DpMaximumLoot(houseValues); + + // Assert + ASSERT_EQ(expectedMaximumLoot, actualMaximumLoot); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0006_HouseRobber2Test.cc b/tests/0004_dynamic_programming/0006_HouseRobber2Test.cc new file mode 100644 index 0000000..e37c346 --- /dev/null +++ b/tests/0004_dynamic_programming/0006_HouseRobber2Test.cc @@ -0,0 +1,48 @@ +#include +#include "0006_HouseRobber2.h" + +namespace HouseRobber2 +{ + TEST(HouseRobber2, RecursionTest01) + { + // Arrange + DynamicProgramming dp; + vector houseValues = { 2, 2, 3, 1, 2 }; + int expectedMaximumLoot = 5; + + // Act + int actualMaximumLoot = dp.RecursiveMaximumLoot(houseValues); + + // Assert + ASSERT_EQ(expectedMaximumLoot, actualMaximumLoot); + } + + TEST(HouseRobber2, DpTest01) + { + // Arrange + DynamicProgramming dp; + vector houseValues = { 2, 2, 3, 1, 2 }; + int expectedMaximumLoot = 5; + + // Act + int actualMaximumLoot = dp.DpMaximumLoot(houseValues); + + // Assert + ASSERT_EQ(expectedMaximumLoot, actualMaximumLoot); + } + + TEST(HouseRobber2, DpTest02) + { + // Arrange + DynamicProgramming dp; + vector houseValues = { 9, 1, 8, 2 }; + int expectedMaximumLoot = 17; + + // Act + int actualMaximumLoot = dp.DpMaximumLoot(houseValues); + + // Assert + ASSERT_EQ(expectedMaximumLoot, actualMaximumLoot); + } + +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0007_DecodeWaysTest.cc b/tests/0004_dynamic_programming/0007_DecodeWaysTest.cc new file mode 100644 index 0000000..cf81a98 --- /dev/null +++ b/tests/0004_dynamic_programming/0007_DecodeWaysTest.cc @@ -0,0 +1,47 @@ +#include +#include "0007_DecodeWays.h" + +namespace DecodeWays +{ + TEST(DecodeWays, RecursionTest01) + { + // Arrange + DynamicProgramming dp; + string digits = "121"; + int expectedWaysCount = 3; + + // Act + int actualWaysCount = dp.RecursiveCountWays(digits); + + // Assert + ASSERT_EQ(expectedWaysCount, actualWaysCount); + } + + TEST(DecodeWays, DpTest01) + { + // Arrange + DynamicProgramming dp; + string digits = "121"; + int expectedWaysCount = 3; + + // Act + int actualWaysCount = dp.DpCountways(digits); + + // Assert + ASSERT_EQ(expectedWaysCount, actualWaysCount); + } + + TEST(DecodeWays, DpTestInvalidInput) + { + // Arrange + DynamicProgramming dp; + string digits = "230"; + int expectedWaysCount = 0; + + // Act + int actualWaysCount = dp.DpCountways(digits); + + // Assert + ASSERT_EQ(expectedWaysCount, actualWaysCount); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0008_TilingProblemTest.cc b/tests/0004_dynamic_programming/0008_TilingProblemTest.cc new file mode 100644 index 0000000..bbcbb79 --- /dev/null +++ b/tests/0004_dynamic_programming/0008_TilingProblemTest.cc @@ -0,0 +1,33 @@ +#include +#include "0008_TilingProblem.h" + +namespace TilingProblem +{ + TEST(TilingProblem, RecursionTest01) + { + // Arrange + DynamicProgramming dp; + int nummberOfRows = 4; + int expectedNumberOfWays = 5; + + // Act + int actualNumberOfWays = dp.RecursiveNumberOfWays(nummberOfRows); + + // Assert + ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); + } + + TEST(TilingProblem, DpTest01) + { + // Arrange + DynamicProgramming dp; + int nummberOfRows = 4; + int expectedNumberOfWays = 5; + + // Act + int actualNumberOfWays = dp.DpNumberOfWays(nummberOfRows); + + // Assert + ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0009_FriendsPairingProblemTest.cc b/tests/0004_dynamic_programming/0009_FriendsPairingProblemTest.cc new file mode 100644 index 0000000..11376ac --- /dev/null +++ b/tests/0004_dynamic_programming/0009_FriendsPairingProblemTest.cc @@ -0,0 +1,91 @@ +#include +#include "0009_FriendsPairingProblem.h" + +namespace FriendsPairingProblem +{ + TEST(FriendsPairingProblemDynamicProgrammingTest, RecursiveCountFriendsPairingsTest1) + { + // Arrange + DynamicProgramming dp; + int numberOfFriends = 3; + int expectedPairings = 4; + + // Act + int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); + + // Assert + ASSERT_EQ(expectedPairings, actualPairings); + EXPECT_EQ(dp.RecursiveCountFriendsPairings(4), 10); + EXPECT_EQ(dp.RecursiveCountFriendsPairings(5), 26); + } + + TEST(FriendsPairingProblemDynamicProgrammingTest, RecursiveCountFriendsPairingsTest2) + { + // Arrange + DynamicProgramming dp; + int numberOfFriends = 4; + int expectedPairings = 10; + + // Act + int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); + + // Assert + ASSERT_EQ(expectedPairings, actualPairings); + } + + TEST(FriendsPairingProblemDynamicProgrammingTest, RecursiveCountFriendsPairingsTest3) + { + // Arrange + DynamicProgramming dp; + int numberOfFriends = 5; + int expectedPairings = 26; + + // Act + int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); + + // Assert + ASSERT_EQ(expectedPairings, actualPairings); + } + + TEST(FriendsPairingProblemDynamicProgrammingTest, DpCountFriendsPairingsTest1) + { + // Arrange + DynamicProgramming dp; + int numberOfFriends = 3; + int expectedPairings = 4; + + // Act + int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); + + // Assert + ASSERT_EQ(expectedPairings, actualPairings); + } + + TEST(FriendsPairingProblemDynamicProgrammingTest, DpCountFriendsPairingsTest2) + { + // Arrange + DynamicProgramming dp; + int numberOfFriends = 4; + int expectedPairings = 10; + + // Act + int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); + + // Assert + ASSERT_EQ(expectedPairings, actualPairings); + } + + TEST(FriendsPairingProblemDynamicProgrammingTest, DpCountFriendsPairingsTest3) + { + // Arrange + DynamicProgramming dp; + int numberOfFriends = 5; + int expectedPairings = 26; + + // Act + int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); + + // Assert + ASSERT_EQ(expectedPairings, actualPairings); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0010_WaysToCoverDistanceTest.cc b/tests/0004_dynamic_programming/0010_WaysToCoverDistanceTest.cc new file mode 100644 index 0000000..7e7f0c9 --- /dev/null +++ b/tests/0004_dynamic_programming/0010_WaysToCoverDistanceTest.cc @@ -0,0 +1,117 @@ +#include +#include "0010_WaysToCoverDistance.h" + +namespace WaysToCoverDistance +{ + TEST(WaysToCoverDistanceTest, RecursiveWaysToCoverDistance1) + { + // Arrange + DynamicProgramming dp; + int distance = 3; + int expectedNumberOfWaysToCoverDistance = 4; + + // Act + int actualNumberOfWaysToCoverDistance = dp.RecursiveWaysToCoverDistance(distance); + + // Assert + ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); + } + + TEST(WaysToCoverDistanceTest, RecursiveWaysToCoverDistance2) + { + // Arrange + DynamicProgramming dp; + int distance = 4; + int expectedNumberOfWaysToCoverDistance = 7; + + // Act + int actualNumberOfWaysToCoverDistance = dp.RecursiveWaysToCoverDistance(distance); + + // Assert + ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); + } + + TEST(WaysToCoverDistanceTest, RecursiveWaysToCoverDistanc3) + { + // Arrange + DynamicProgramming dp; + int distance = 5; + int expectedNumberOfWaysToCoverDistance = 13; + + // Act + int actualNumberOfWaysToCoverDistance = dp.RecursiveWaysToCoverDistance(distance); + + // Assert + ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); + } + + TEST(WaysToCoverDistanceTest, RecursiveWaysToCoverDistanc4) + { + // Arrange + DynamicProgramming dp; + int distance = 6; + int expectedNumberOfWaysToCoverDistance = 24; + + // Act + int actualNumberOfWaysToCoverDistance = dp.RecursiveWaysToCoverDistance(distance); + + // Assert + ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); + } + + TEST(WaysToCoverDistanceTest, DpWaysToCoverDistance1) + { + // Arrange + DynamicProgramming dp; + int distance = 3; + int expectedNumberOfWaysToCoverDistance = 4; + + // Act + int actualNumberOfWaysToCoverDistance = dp.DpWaysToCoverDistance(distance); + + // Assert + ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); + } + + TEST(WaysToCoverDistanceTest, DpWaysToCoverDistance2) + { + // Arrange + DynamicProgramming dp; + int distance = 4; + int expectedNumberOfWaysToCoverDistance = 7; + + // Act + int actualNumberOfWaysToCoverDistance = dp.DpWaysToCoverDistance(distance); + + // Assert + ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); + } + + TEST(WaysToCoverDistanceTest, DpWaysToCoverDistance3) + { + // Arrange + DynamicProgramming dp; + int distance = 5; + int expectedNumberOfWaysToCoverDistance = 13; + + // Act + int actualNumberOfWaysToCoverDistance = dp.DpWaysToCoverDistance(distance); + + // Assert + ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); + } + + TEST(WaysToCoverDistanceTest, DpWaysToCoverDistance4) + { + // Arrange + DynamicProgramming dp; + int distance = 6; + int expectedNumberOfWaysToCoverDistance = 24; + + // Act + int actualNumberOfWaysToCoverDistance = dp.DpWaysToCoverDistance(distance); + + // Assert + ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrderTest.cc b/tests/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrderTest.cc new file mode 100644 index 0000000..8a9830c --- /dev/null +++ b/tests/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrderTest.cc @@ -0,0 +1,33 @@ +#include +#include "0011_CountWaysToReachNthStairIncludeOrder.h" + +namespace CountWaysToReachNthStairIncludeOrder +{ + TEST(CountWaysToReachNthStairIncludeOrderTest, RecursiveCountWaysToReachNthStairIncludeOrder1) + { + // Arrange + DynamicProgramming dp; + int n = 4; + int expectedNumberOfWays = 5; + + // Act + int actualNumberOfWays = dp.RecursiveCountWaysToReachNthStairIncludeOrder(n); + + // Assert + ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); + } + + TEST(CountWaysToReachNthStairIncludeOrderTest, DpCountWaysToReachNthStairIncludeOrder1) + { + // Arrange + DynamicProgramming dp; + int n = 4; + int expectedNumberOfWays = 5; + + // Act + int actualNumberOfWays = dp.DpCountWaysToReachNthStairIncludeOrder(n); + + // Assert + ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrderTest.cc b/tests/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrderTest.cc new file mode 100644 index 0000000..2a67ce3 --- /dev/null +++ b/tests/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrderTest.cc @@ -0,0 +1,33 @@ +#include +#include "0012_CountWaysToReachNthStairExcludeOrder.h" + +namespace CountWaysToReachNthStairExcludeOrder +{ + TEST(CountWaysToReachNthStairExcludeOrderTest, RecursiveCountWaysToReachNthStairExcludeOrder1) + { + // Arrange + DynamicProgramming dp; + int n = 4; + int expectedNumberOfWays = 3; + + // Act + int actualNumberOfWays = dp.RecursiveCountWaysToReachNthStairExcludeOrder(n); + + // Assert + ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); + } + + TEST(CountWaysToReachNthStairExcludeOrderTest, DpCountWaysToReachNthStairExcludeOrder1) + { + // Arrange + DynamicProgramming dp; + int n = 4; + int expectedNumberOfWays = 3; + + // Act + int actualNumberOfWays = dp.DpCountWaysToReachNthStairExcludeOrder(n); + + // Assert + ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0013_KnapsackProblemTest.cc b/tests/0004_dynamic_programming/0013_KnapsackProblemTest.cc new file mode 100644 index 0000000..94d3e84 --- /dev/null +++ b/tests/0004_dynamic_programming/0013_KnapsackProblemTest.cc @@ -0,0 +1,53 @@ +#include +#include "0013_KnapsackProblem.h" + +namespace KnapsackProblem +{ + TEST(KnapsackProblemTest, RecursiveKnapsackProblemTest01) + { + // Arrange + DynamicProgramming dp; + int capacity = 4; + vector weight = { 4,5,1 }; + vector profit = { 1,2,3 }; + int expectedMaximumProfit = 3; + + // Act + int actualMaximumProfit = dp.RecursiveKnapsack(capacity, weight, profit); + + // Assert + ASSERT_EQ(expectedMaximumProfit, actualMaximumProfit); + } + + TEST(KnapsackProblemTest, DpKnapsackProblemTest01) + { + // Arrange + DynamicProgramming dp; + int capacity = 4; + vector weight = { 4,5,1 }; + vector profit = { 1,2,3 }; + int expectedMaximumProfit = 3; + + // Act + int actualMaximumProfit = dp.DpKnapsack(capacity, weight, profit); + + // Assert + ASSERT_EQ(expectedMaximumProfit, actualMaximumProfit); + } + + TEST(KnapsackProblemTest, DpKnapsackProblemTest02) + { + // Arrange + DynamicProgramming dp; + int capacity = 4; + vector weight = { 4,5,1 }; + vector profit = { 1,2,3 }; + int expectedMaximumProfit = 3; + + // Act + int actualMaximumProfit = dp.DpKnapsackSpaceOptimized(capacity, weight, profit); + + // Assert + ASSERT_EQ(expectedMaximumProfit, actualMaximumProfit); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0014_SubsetSumProblemTest.cc b/tests/0004_dynamic_programming/0014_SubsetSumProblemTest.cc new file mode 100644 index 0000000..aeee852 --- /dev/null +++ b/tests/0004_dynamic_programming/0014_SubsetSumProblemTest.cc @@ -0,0 +1,35 @@ +#include +#include "0014_SubsetSumProblem.h" + +namespace SubsetSumProblem +{ + TEST(SubsetSumProblemTest, RecursiveSubsetSumTest) + { + // Arrange + DynamicProgramming dp; + vector nums = { 3, 34, 4, 12, 5, 2 }; + int sum = 9; + bool expectedResult = true; + + // Act + bool actualResult = dp.RecursiveSubsetSum(nums, sum); + + // Assert + ASSERT_EQ(expectedResult, actualResult); + } + + TEST(SubsetSumProblemTest, DpSubsetSumTest) + { + // Arrange + DynamicProgramming dp; + vector nums = { 3, 34, 4, 12, 5, 2 }; + int sum = 9; + bool expectedResult = true; + + // Act + bool actualResult = dp.DpIsSubsetSum(nums, sum); + + // Assert + ASSERT_EQ(expectedResult, actualResult); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0015_CountSubsetsForSumTest.cc b/tests/0004_dynamic_programming/0015_CountSubsetsForSumTest.cc new file mode 100644 index 0000000..ba1fa7f --- /dev/null +++ b/tests/0004_dynamic_programming/0015_CountSubsetsForSumTest.cc @@ -0,0 +1,35 @@ +#include +#include"0015_CountSubsetsForSum.h" + +namespace CountSubsetsForSum +{ + TEST(CountSubsetsForSum, RecursiveCountSubsetSum) + { + // Arrange + DynamicProgramming dp; + vector nums = { 1, 2, 3, 3 }; + int sum = 6; + int expectedCount = 3; + + // Act + int actualCount = dp.RecursiveCountSubsets(nums, sum); + + // Assert + ASSERT_EQ(expectedCount, actualCount); + } + + TEST(CountSubsetsForSum, DpCountSubsetSum) + { + // Arrange + DynamicProgramming dp; + vector nums = { 1, 2, 3, 3 }; + int sum = 6; + int expectedCount = 3; + + // Act + int actualCount = dp.DpCountSubsets(nums, sum); + + // Assert + ASSERT_EQ(expectedCount, actualCount); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0016_PartitionEqualSubsetSumTest.cc b/tests/0004_dynamic_programming/0016_PartitionEqualSubsetSumTest.cc new file mode 100644 index 0000000..2bfa292 --- /dev/null +++ b/tests/0004_dynamic_programming/0016_PartitionEqualSubsetSumTest.cc @@ -0,0 +1,33 @@ +#include +#include "0016_PartitionEqualSubsetSum.h" + +namespace PartitionEqualSubsetSum +{ + TEST(PartitionEqualSubsetSum, RecursivePartitionEqualSubsetSum) + { + // Arrange + DynamicProgramming dp; + vector nums = { 1, 5, 11, 5 }; + bool expectedResult = true; + + // Act + bool actualResult = dp.RecursivePartitionEqualSubsets(nums); + + // Assert + ASSERT_EQ(expectedResult, actualResult); + } + + TEST(PartitionEqualSubsetSum, DpPartitionEqualSubsetSum) + { + // Arrange + DynamicProgramming dp; + vector nums = { 1, 5, 11, 5 }; + bool expectedResult = true; + + // Act + bool actualResult = dp.DpPartitionEqualSubsets(nums); + + // Assert + ASSERT_EQ(expectedResult, actualResult); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0017_TargetSumTest.cc b/tests/0004_dynamic_programming/0017_TargetSumTest.cc new file mode 100644 index 0000000..ab3fbf4 --- /dev/null +++ b/tests/0004_dynamic_programming/0017_TargetSumTest.cc @@ -0,0 +1,50 @@ +#include +#include "0017_TargetSum.h" + +namespace TargetSum +{ + TEST(TargetSum, RecursiveSolutionTest_ValidInput_ReturnsCorrectResult) + { + // Arrange + DynamicProgramming dp; + vector nums = { 1, 1, 1, 1, 1 }; + int target = 3; + int expectedResult = 5; + + // Act + int actualResult = dp.RecursiveFindTotalWays(nums, target); + + // Assert + ASSERT_EQ(expectedResult, actualResult); + } + + TEST(TargetSum, DpSolutionTest_ValidInput_ReturnsCorrectResult) + { + // Arrange + DynamicProgramming dp; + vector nums = { 1, 1, 1, 1, 1 }; + int target = 3; + int expectedResult = 5; + + // Act + int actualResult = dp.DpFindTotalWays(nums, target); + + // Assert + ASSERT_EQ(expectedResult, actualResult); + } + + TEST(TargetSum, DpSolutionTest_TargetGreaterThanTotalSum_ReturnsZero) + { + // Arrange + DynamicProgramming dp; + vector nums = { 1, 1, 1, 1, 1 }; + int target = -1000; + int expectedResult = 0; + + // Act + int actualResult = dp.DpFindTotalWays(nums, target); + + // Assert + ASSERT_EQ(expectedResult, actualResult); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/CMakeLists.txt b/tests/0004_dynamic_programming/CMakeLists.txt new file mode 100644 index 0000000..4ef67b0 --- /dev/null +++ b/tests/0004_dynamic_programming/CMakeLists.txt @@ -0,0 +1,49 @@ +cmake_policy(SET CMP0135 NEW) + +include(FetchContent) +FetchContent_Declare( + googletest + URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip +) + +# For Windows: Prevent overriding the parent project's compiler/linker settings +set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) +FetchContent_MakeAvailable(googletest) + +enable_testing() + +add_executable( + 0005DynamicProgrammingTests + 0001_FibonacciNumberTest.cc + 0002_TribonacciNumberTest.cc + 0003_ClimbingStairsTest.cc + 0004_MinimumCostClimbingStairsTest.cc + 0005_HouseRobber1Test.cc + 0006_HouseRobber2Test.cc + 0007_DecodeWaysTest.cc + 0008_TilingProblemTest.cc + 0009_FriendsPairingProblemTest.cc + 0010_WaysToCoverDistanceTest.cc + 0011_CountWaysToReachNthStairIncludeOrderTest.cc + 0012_CountWaysToReachNthStairExcludeOrderTest.cc + 0013_KnapsackProblemTest.cc + 0014_SubsetSumProblemTest.cc + 0015_CountSubsetsForSumTest.cc + 0016_PartitionEqualSubsetSumTest.cc + 0017_TargetSumTest.cc + +) + +target_link_libraries( + 0005DynamicProgrammingTests + GTest::gtest_main + 0005DYNAMICPROGRAMMING +) + +# Add .clang-tidy configuration to this library. +if(CLANG_TIDY_EXE) + set_target_properties(0005DYNAMICPROGRAMMING PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") +endif() + +include(GoogleTest) +gtest_discover_tests(0005DynamicProgrammingTests DISCOVERY_TIMEOUT 30) \ No newline at end of file diff --git a/tests/0005_greedy_algorithms/CMakeLists.txt b/tests/0005_greedy_algorithms/CMakeLists.txt new file mode 100644 index 0000000..e69de29 diff --git a/tests/0006_bitwise_algorithms/CMakeLists.txt b/tests/0006_bitwise_algorithms/CMakeLists.txt new file mode 100644 index 0000000..e69de29 diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt new file mode 100644 index 0000000..41d781c --- /dev/null +++ b/tests/CMakeLists.txt @@ -0,0 +1,7 @@ +add_subdirectory(0000_common_utilities) +add_subdirectory(0001_basics) +add_subdirectory(0002_tree) +add_subdirectory(0003_graph) +add_subdirectory(0004_dynamic_programming) +add_subdirectory(0005_greedy_algorithms) +add_subdirectory(0006_bitwise_algorithms) \ No newline at end of file From 023f4b38ce56baa05a4c0788322313161f4f3d18 Mon Sep 17 00:00:00 2001 From: Debashis Nandi Date: Fri, 12 Jun 2026 04:01:02 +0530 Subject: [PATCH 04/13] feat: tree codes fixed to match style guide --- src/0002_tree/0001_BinarySearchTree.cc | 88 +++++++++---------- src/0002_tree/CMakeLists.txt | 4 +- src/0002_tree/headers/0001_BinarySearchTree.h | 44 +++++----- tests/0002_tree/0001_BinarySearchTreeTest.cc | 48 +++++----- tests/0002_tree/CMakeLists.txt | 10 +-- 5 files changed, 97 insertions(+), 97 deletions(-) diff --git a/src/0002_tree/0001_BinarySearchTree.cc b/src/0002_tree/0001_BinarySearchTree.cc index ba78751..0f0650e 100644 --- a/src/0002_tree/0001_BinarySearchTree.cc +++ b/src/0002_tree/0001_BinarySearchTree.cc @@ -19,7 +19,7 @@ namespace BinarySearchTree } - void BinarySearchTree::InsertBinarySearchTreeNode(Node* node) + void BinarySearchTree::_insertBSTreeNode(Node* node) { Node* nodeY = nullptr; Node* nodeX = this->_root; @@ -50,7 +50,7 @@ namespace BinarySearchTree } } - Node* BinarySearchTree::FindBinarySearchTreeNode(int value) + Node* BinarySearchTree::_findBSTreeNode(int value) { Node* node = this->_root; while (node != nullptr) @@ -71,7 +71,7 @@ namespace BinarySearchTree return node; } - Node* BinarySearchTree::FindBinarySearchTreeMinimumValueNode(Node* node) + Node* BinarySearchTree::_findBSTreeMinNode(Node* node) { while (node->left != nullptr) { @@ -80,7 +80,7 @@ namespace BinarySearchTree return node; } - Node* BinarySearchTree::FindBinarySearchTreeMaximumValueNode(Node* node) + Node* BinarySearchTree::_findBSTreeMaxNode(Node* node) { while (node->right != nullptr) { @@ -89,11 +89,11 @@ namespace BinarySearchTree return node; } - Node* BinarySearchTree::FindSuccessorBinarySearchTreeNode(Node* node) + Node* BinarySearchTree::_findSuccessor(Node* node) { if (node->right != nullptr) { - return this->FindBinarySearchTreeMinimumValueNode(node->right); + return this->_findBSTreeMinNode(node->right); } Node* nodeY = node->parent; while (nodeY != nullptr && node == nodeY->right) @@ -104,11 +104,11 @@ namespace BinarySearchTree return nodeY; } - Node* BinarySearchTree::FindPredecessorBinarySearchTreeNode(Node* node) + Node* BinarySearchTree::_findPredecessor(Node* node) { if (node->left != nullptr) { - return this->FindBinarySearchTreeMaximumValueNode(node->left); + return this->_findBSTreeMaxNode(node->left); } Node* nodeY = node->parent; while (nodeY != nullptr && node == nodeY->left) @@ -119,7 +119,7 @@ namespace BinarySearchTree return nodeY; } - void BinarySearchTree::TransplantBinarySearchTreeNode(Node* nodeU, Node* nodeV) + void BinarySearchTree::_transplant(Node* nodeU, Node* nodeV) { if (nodeU->parent == nullptr) { @@ -140,66 +140,66 @@ namespace BinarySearchTree } } - void BinarySearchTree::DeleteBinarySearchTreeNode(Node* node) + void BinarySearchTree::_deleteBSTreeNode(Node* node) { if (node->left == nullptr) { - this->TransplantBinarySearchTreeNode(node, node->right); + this->_transplant(node, node->right); } else if (node->right == nullptr) { - this->TransplantBinarySearchTreeNode(node, node->left); + this->_transplant(node, node->left); } else { - Node* nodeY = this->FindBinarySearchTreeMinimumValueNode(node->right); + Node* nodeY = this->_findBSTreeMinNode(node->right); if (nodeY->parent != node) { - this->TransplantBinarySearchTreeNode(nodeY, nodeY->right); + this->_transplant(nodeY, nodeY->right); nodeY->right = node->right; nodeY->right->parent = nodeY; } - this->TransplantBinarySearchTreeNode(node, nodeY); + this->_transplant(node, nodeY); nodeY->left = node->left; nodeY->left->parent = nodeY; delete node; } } - void BinarySearchTree::RecursiveInorderTraversal(Node* node, vector& result) + void BinarySearchTree::_recursiveInorder(Node* node, vector& result) { if (node == nullptr) { return; } - this->RecursiveInorderTraversal(node->left, result); + this->_recursiveInorder(node->left, result); result.push_back(node->data); - this->RecursiveInorderTraversal(node->right, result); + this->_recursiveInorder(node->right, result); } - void BinarySearchTree::RecursivePreorderTraversal(Node* node, vector& result) + void BinarySearchTree::_recursivePreorder(Node* node, vector& result) { if (node == nullptr) { return; } result.push_back(node->data); - this->RecursivePreorderTraversal(node->left, result); - this->RecursivePreorderTraversal(node->right, result); + this->_recursivePreorder(node->left, result); + this->_recursivePreorder(node->right, result); } - void BinarySearchTree::RecursivePostorderTraversal(Node* node, vector& result) + void BinarySearchTree::_recursivePostorder(Node* node, vector& result) { if (node == nullptr) { return; } - this->RecursivePostorderTraversal(node->left, result); - this->RecursivePostorderTraversal(node->right, result); + this->_recursivePostorder(node->left, result); + this->_recursivePostorder(node->right, result); result.push_back(node->data); } - void BinarySearchTree::MorrisInorderTraversal(Node* node, vector& result) + void BinarySearchTree::_morrisInorder(Node* node, vector& result) { while (node != nullptr) { @@ -230,7 +230,7 @@ namespace BinarySearchTree } } - void BinarySearchTree::MorrisPreorderTraversal(Node* node, vector& result) + void BinarySearchTree::_morrisPreorder(Node* node, vector& result) { while (node != nullptr) { @@ -261,7 +261,7 @@ namespace BinarySearchTree } } - void BinarySearchTree::MorrisPostorderTraversal(Node* node, vector& result) + void BinarySearchTree::_morrisPostorder(Node* node, vector& result) { while (node != nullptr) { @@ -293,57 +293,57 @@ namespace BinarySearchTree reverse(result.begin(), result.end()); } - void BinarySearchTree::InsertNode(int value) + void BinarySearchTree::insertNode(int value) { Node* node = new Node(value, nullptr, nullptr, nullptr); - this->InsertBinarySearchTreeNode(node); + this->_insertBSTreeNode(node); } - void BinarySearchTree::DeleteNode(int value) + void BinarySearchTree::deleteNode(int value) { - Node* node = this->FindBinarySearchTreeNode(value); - this->DeleteBinarySearchTreeNode(node); + Node* node = this->_findBSTreeNode(value); + this->_deleteBSTreeNode(node); } - vector BinarySearchTree::GetRecursiveInorderTravesalResult() + vector BinarySearchTree::recursiveInorderTraversal() { vector result; - this->RecursiveInorderTraversal(this->_root, result); + this->_recursiveInorder(this->_root, result); return result; } - vector BinarySearchTree::GetRecursivePreorderTravesalResult() + vector BinarySearchTree::recursivePreorderTravesal() { vector result; - this->RecursivePreorderTraversal(this->_root, result); + this->_recursivePreorder(this->_root, result); return result; } - vector BinarySearchTree::GetRecursivePostorderTravesalResult() + vector BinarySearchTree::recursivePostorderTravesal() { vector result; - this->RecursivePostorderTraversal(this->_root, result); + this->_recursivePostorder(this->_root, result); return result; } - vector BinarySearchTree::GetMorrisInorderTraversalResult() + vector BinarySearchTree::morrisInorderTraversal() { vector result; - this->MorrisInorderTraversal(this->_root, result); + this->_morrisInorder(this->_root, result); return result; } - vector BinarySearchTree::GetMorrisPreorderTraversalResult() + vector BinarySearchTree::morrisPreorderTraversal() { vector result; - this->MorrisPreorderTraversal(this->_root, result); + this->_morrisPreorder(this->_root, result); return result; } - vector BinarySearchTree::GetMorrisPostorderTraversalResult() + vector BinarySearchTree::morrisPostorderTraversal() { vector result; - this->MorrisPostorderTraversal(this->_root, result); + this->_morrisPostorder(this->_root, result); return result; } } \ No newline at end of file diff --git a/src/0002_tree/CMakeLists.txt b/src/0002_tree/CMakeLists.txt index 5508146..3ef4afa 100644 --- a/src/0002_tree/CMakeLists.txt +++ b/src/0002_tree/CMakeLists.txt @@ -4,8 +4,8 @@ set(0002TREE_SOURCES ) # Create a library target -add_library(0002TREE ${0002TREE_SOURCES}) +add_library(0002_Tree ${0002TREE_SOURCES}) -target_include_directories(0002TREE PUBLIC +target_include_directories(0002_Tree PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/headers ) \ No newline at end of file diff --git a/src/0002_tree/headers/0001_BinarySearchTree.h b/src/0002_tree/headers/0001_BinarySearchTree.h index 1e9bcc2..d422701 100644 --- a/src/0002_tree/headers/0001_BinarySearchTree.h +++ b/src/0002_tree/headers/0001_BinarySearchTree.h @@ -21,29 +21,29 @@ namespace BinarySearchTree { private: Node* _root; - void InsertBinarySearchTreeNode(Node* node); - Node* FindBinarySearchTreeNode(int value); - Node* FindBinarySearchTreeMinimumValueNode(Node* node); - Node* FindBinarySearchTreeMaximumValueNode(Node* node); - Node* FindSuccessorBinarySearchTreeNode(Node* node); - Node* FindPredecessorBinarySearchTreeNode(Node* node); - void TransplantBinarySearchTreeNode(Node* nodeU, Node* nodeV); - void DeleteBinarySearchTreeNode(Node* node); - void RecursiveInorderTraversal(Node* node, vector& result); - void RecursivePreorderTraversal(Node* node, vector& result); - void RecursivePostorderTraversal(Node* node, vector& result); - void MorrisInorderTraversal(Node* node, vector& result); - void MorrisPreorderTraversal(Node* node, vector& result); - void MorrisPostorderTraversal(Node* node, vector& result); + void _insertBSTreeNode(Node* node); + Node* _findBSTreeNode(int value); + Node* _findBSTreeMinNode(Node* node); + Node* _findBSTreeMaxNode(Node* node); + Node* _findSuccessor(Node* node); + Node* _findPredecessor(Node* node); + void _transplant(Node* nodeU, Node* nodeV); + void _deleteBSTreeNode(Node* node); + void _recursiveInorder(Node* node, vector& result); + void _recursivePreorder(Node* node, vector& result); + void _recursivePostorder(Node* node, vector& result); + void _morrisInorder(Node* node, vector& result); + void _morrisPreorder(Node* node, vector& result); + void _morrisPostorder(Node* node, vector& result); public: BinarySearchTree(); - void InsertNode(int value); - void DeleteNode(int value); - vector GetRecursiveInorderTravesalResult(); - vector GetRecursivePreorderTravesalResult(); - vector GetRecursivePostorderTravesalResult(); - vector GetMorrisInorderTraversalResult(); - vector GetMorrisPreorderTraversalResult(); - vector GetMorrisPostorderTraversalResult(); + void insertNode(int value); + void deleteNode(int value); + vector recursiveInorderTraversal(); + vector recursivePreorderTravesal(); + vector recursivePostorderTravesal(); + vector morrisInorderTraversal(); + vector morrisPreorderTraversal(); + vector morrisPostorderTraversal(); }; } \ No newline at end of file diff --git a/tests/0002_tree/0001_BinarySearchTreeTest.cc b/tests/0002_tree/0001_BinarySearchTreeTest.cc index d99a30e..0c8aab0 100644 --- a/tests/0002_tree/0001_BinarySearchTreeTest.cc +++ b/tests/0002_tree/0001_BinarySearchTreeTest.cc @@ -10,12 +10,12 @@ namespace BinarySearchTree TEST(BSTInsertData, RecursiveInorderTest) { BinarySearchTree bst; - bst.InsertNode(50); - bst.InsertNode(30); - bst.InsertNode(60); + bst.insertNode(50); + bst.insertNode(30); + bst.insertNode(60); - string actualResult = unitTestHelper.SerializeVectorToString(bst.GetRecursiveInorderTravesalResult()); + string actualResult = unitTestHelper.SerializeVectorToString(bst.recursiveInorderTraversal()); string expectedResult = "30 50 60"; EXPECT_EQ(actualResult, expectedResult); @@ -24,11 +24,11 @@ namespace BinarySearchTree TEST(BSTInsertData, RecursivePreorderTest) { BinarySearchTree bst; - bst.InsertNode(50); - bst.InsertNode(30); - bst.InsertNode(60); + bst.insertNode(50); + bst.insertNode(30); + bst.insertNode(60); - string actualResult = unitTestHelper.SerializeVectorToString(bst.GetRecursivePreorderTravesalResult()); + string actualResult = unitTestHelper.SerializeVectorToString(bst.recursivePreorderTravesal()); string expectedResult = "50 30 60"; EXPECT_EQ(actualResult, expectedResult); @@ -37,11 +37,11 @@ namespace BinarySearchTree TEST(BSTInsertData, RecursivePostorderTest) { BinarySearchTree bst; - bst.InsertNode(50); - bst.InsertNode(30); - bst.InsertNode(60); + bst.insertNode(50); + bst.insertNode(30); + bst.insertNode(60); - string actualResult = unitTestHelper.SerializeVectorToString(bst.GetRecursivePostorderTravesalResult()); + string actualResult = unitTestHelper.SerializeVectorToString(bst.recursivePostorderTravesal()); string expectedResult = "30 60 50"; EXPECT_EQ(actualResult, expectedResult); @@ -50,12 +50,12 @@ namespace BinarySearchTree TEST(BSTInsertData, MorrisInorderTest) { BinarySearchTree bst; - bst.InsertNode(50); - bst.InsertNode(30); - bst.InsertNode(60); + bst.insertNode(50); + bst.insertNode(30); + bst.insertNode(60); - string actualResult = unitTestHelper.SerializeVectorToString(bst.GetMorrisInorderTraversalResult()); + string actualResult = unitTestHelper.SerializeVectorToString(bst.morrisInorderTraversal()); string expectedResult = "30 50 60"; EXPECT_EQ(actualResult, expectedResult); @@ -64,12 +64,12 @@ namespace BinarySearchTree TEST(BSTInsertData, MorrisPreorderTest) { BinarySearchTree bst; - bst.InsertNode(50); - bst.InsertNode(30); - bst.InsertNode(60); + bst.insertNode(50); + bst.insertNode(30); + bst.insertNode(60); - string actualResult = unitTestHelper.SerializeVectorToString(bst.GetMorrisPreorderTraversalResult()); + string actualResult = unitTestHelper.SerializeVectorToString(bst.morrisPreorderTraversal()); string expectedResult = "50 30 60"; EXPECT_EQ(actualResult, expectedResult); @@ -78,12 +78,12 @@ namespace BinarySearchTree TEST(BSTInsertData, MorrisPostorderTest) { BinarySearchTree bst; - bst.InsertNode(50); - bst.InsertNode(30); - bst.InsertNode(60); + bst.insertNode(50); + bst.insertNode(30); + bst.insertNode(60); - string actualResult = unitTestHelper.SerializeVectorToString(bst.GetMorrisPostorderTraversalResult()); + string actualResult = unitTestHelper.SerializeVectorToString(bst.morrisPostorderTraversal()); string expectedResult = "30 60 50"; EXPECT_EQ(actualResult, expectedResult); diff --git a/tests/0002_tree/CMakeLists.txt b/tests/0002_tree/CMakeLists.txt index aef689e..a10743b 100644 --- a/tests/0002_tree/CMakeLists.txt +++ b/tests/0002_tree/CMakeLists.txt @@ -13,20 +13,20 @@ FetchContent_MakeAvailable(googletest) enable_testing() add_executable( - 0002TreeTests + 0002_TreeTests 0001_BinarySearchTreeTest.cc ) target_link_libraries( - 0002TreeTests + 0002_TreeTests GTest::gtest_main - 0002TREE + 0002_Tree ) # Add .clang-tidy configuration to this library. if(CLANG_TIDY_EXE) - set_target_properties(0002TREE PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") + set_target_properties(0002_Tree PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") endif() include(GoogleTest) -gtest_discover_tests(0002TreeTests DISCOVERY_TIMEOUT 30) \ No newline at end of file +gtest_discover_tests(0002_TreeTests DISCOVERY_TIMEOUT 30) \ No newline at end of file From 3facc55c0ab9be2ce18eba72b091c2776eb53711 Mon Sep 17 00:00:00 2001 From: Debashis Nandi Date: Sat, 13 Jun 2026 03:24:00 +0530 Subject: [PATCH 05/13] feat: removed all files to fix the file names --- .clang-tidy | 27 -- .github/ISSUE_TEMPLATE/bug_report.md | 28 -- .github/labeler.yaml | 51 --- .github/pull_request_template.md | 28 -- .github/release.yaml | 56 --- .github/workflows/auto-labeler.yaml | 36 -- .github/workflows/deploy.yaml | 160 -------- .github/workflows/validate.yaml | 130 ------- .gitignore | 3 - CMakeLists.txt | 35 -- CMakePresets.json | 61 --- CODE_OF_CONDUCT.md | 127 ------- CONTRIBUTING.md | 1 - LICENSE | 21 -- README.md | 21 -- SECURITY.md | 1 - src/0001_basics/CMakeLists.txt | 11 - src/0001_basics/Node.cc | 6 - src/0001_basics/headers/Node.h | 8 - src/0002_tree/0001_BinarySearchTree.cc | 349 ------------------ src/0002_tree/CMakeLists.txt | 11 - src/0002_tree/headers/0001_BinarySearchTree.h | 49 --- src/0003_graph/0001_BreadthFirstSearch.cc | 86 ----- src/0003_graph/0002_DepthFirstSearch.cc | 80 ---- src/0003_graph/0003_TopologicalSort.cc | 150 -------- .../0004_StronglyConnectedComponents.cc | 121 ------ .../0005_HamiltonianPathAndCycle.cc | 114 ------ src/0003_graph/0006_EulerianPathAndCircuit.cc | 212 ----------- ...007_MinimumSpanningTreeKruskalAlgorithm.cc | 108 ------ .../0008_MinimumSpanningTreePrimAlgorithm.cc | 85 ----- ...009_SingleSourceShortestPathBellmanFord.cc | 108 ------ .../0010_DirectedAcyclicGraphShortestPath.cc | 124 ------- .../0011_SingleSourceShortestPathDijkstra.cc | 113 ------ ...0012_DifferenceConstraintsShortestPaths.cc | 133 ------- ...0013_AllPairsShortestPathsFloydWarshall.cc | 104 ------ .../0014_AllPairsShortestPathsJohnson.cc | 217 ----------- .../0015_MaximumFlowFordFulkerson.cc | 139 ------- src/0003_graph/0016_MaximumFlowEdmondsKarp.cc | 144 -------- .../0017_MaximumBipartiteMatching.cc | 263 ------------- ...8_MaximumFlowGoldbergGenericPushRelabel.cc | 172 --------- .../0019_MaximumFlowRelabelToFront.cc | 169 --------- src/0003_graph/CMakeLists.txt | 30 -- .../headers/0001_BreadthFirstSearch.h | 35 -- .../headers/0002_DepthFirstSearch.h | 37 -- src/0003_graph/headers/0003_TopologicalSort.h | 42 --- .../0004_StronglyConnectedComponents.h | 43 --- .../headers/0005_HamiltonianPathAndCycle.h | 40 -- .../headers/0006_EulerianPathAndCircuit.h | 43 --- ...0007_MinimumSpanningTreeKruskalAlgorithm.h | 46 --- .../0008_MinimumSpanningTreePrimAlgorithm.h | 42 --- ...0009_SingleSourceShortestPathBellmanFord.h | 44 --- .../0010_DirectedAcyclicGraphShortestPath.h | 51 --- .../0011_SingleSourceShortestPathDijkstra.h | 55 --- .../0012_DifferenceConstraintsShortestPaths.h | 43 --- .../0013_AllPairsShortestPathsFloydWarshall.h | 24 -- .../0014_AllPairsShortestPathsJohnson.h | 66 ---- .../headers/0015_MaximumFlowFordFulkerson.h | 29 -- .../headers/0016_MaximumFlowEdmondsKarp.h | 28 -- .../headers/0017_MaximumBipartiteMatching.h | 41 -- ...18_MaximumFlowGoldbergGenericPushRelabel.h | 31 -- .../headers/0019_MaximumFlowRelabelToFront.h | 31 -- .../0001_FibonacciNumber.cc | 28 -- .../0002_TribonacciNumber.cc | 33 -- .../0003_ClimbingStairs.cc | 29 -- .../0004_MinimumCostClimbingStairs.cc | 48 --- .../0005_HouseRobber1.cc | 44 --- .../0006_HouseRobber2.cc | 95 ----- .../0007_DecodeWays.cc | 61 --- .../0008_TilingProblem.cc | 42 --- .../0009_FriendsPairingProblem.cc | 39 -- .../0010_WaysToCoverDistance.cc | 52 --- ...11_CountWaysToReachNthStairIncludeOrder.cc | 44 --- ...12_CountWaysToReachNthStairExcludeOrder.cc | 53 --- .../0013_KnapsackProblem.cc | 78 ---- .../0014_SubsetSumProblem.cc | 71 ---- .../0015_CountSubsetsForSum.cc | 55 --- .../0016_PartitionEqualSubsetSum.cc | 75 ---- .../0017_TargetSum.cc | 70 ---- src/0004_dynamic_programming/CMakeLists.txt | 28 -- .../headers/0001_FibonacciNumber.h | 23 -- .../headers/0002_TribonacciNumber.h | 23 -- .../headers/0003_ClimbingStairs.h | 24 -- .../headers/0004_MinimumCostClimbingStairs.h | 25 -- .../headers/0005_HouseRobber1.h | 25 -- .../headers/0006_HouseRobber2.h | 28 -- .../headers/0007_DecodeWays.h | 32 -- .../headers/0008_TilingProblem.h | 25 -- .../headers/0009_FriendsPairingProblem.h | 46 --- .../headers/0010_WaysToCoverDistance.h | 47 --- ...011_CountWaysToReachNthStairIncludeOrder.h | 42 --- ...012_CountWaysToReachNthStairExcludeOrder.h | 44 --- .../headers/0013_KnapsackProblem.h | 34 -- .../headers/0014_SubsetSumProblem.h | 34 -- .../headers/0015_CountSubsetsForSum.h | 34 -- .../headers/0016_PartitionEqualSubsetSum.h | 36 -- .../headers/0017_TargetSum.h | 45 --- src/0005_greedy_algorithms/CMakeLists.txt | 0 src/0006_bitwise_algorithms/CMakeLists.txt | 0 src/CMakeLists.txt | 6 - tests/0000_common_utilities/CMakeLists.txt | 0 tests/0000_common_utilities/UnitTestHelper.h | 183 --------- tests/0001_basics/CMakeLists.txt | 31 -- tests/0001_basics/NodeTest.cc | 12 - tests/0002_tree/0001_BinarySearchTreeTest.cc | 91 ----- tests/0002_tree/CMakeLists.txt | 32 -- .../0003_graph/0001_BreadthFirstSearchTest.cc | 45 --- tests/0003_graph/0002_DepthFirstSearchTest.cc | 177 --------- tests/0003_graph/0003_TopologicalSortTest.cc | 116 ------ .../0004_StronglyConnectedComponentsTest.cc | 102 ----- .../0005_HamiltonianPathAndCycleTest.cc | 33 -- .../0006_EulerianPathAndCircuitTest.cc | 32 -- ...MinimumSpanningTreeKruskalAlgorithmTest.cc | 45 --- ...08_MinimumSpanningTreePrimAlgorithmTest.cc | 45 --- ...SingleSourceShortestPathBellmanFordTest.cc | 104 ------ ...10_DirectedAcyclicGraphShortestPathTest.cc | 29 -- ...11_SingleSourceShortestPathDijkstraTest.cc | 31 -- ..._DifferenceConstraintsShortestPathsTest.cc | 40 -- ..._AllPairsShortestPathsFloydWarshallTest.cc | 36 -- .../0014_AllPairsShortestPathsJohnsonTest.cc | 44 --- .../0015_MaximumFlowFordFulkersonTest.cc | 64 ---- .../0016_MaximumFlowEdmondsKarpTest.cc | 64 ---- .../0017_MaximumBipartiteMatchingTest.cc | 35 -- ...ximumFlowGoldbergGenericPushRelabelTest.cc | 35 -- .../0019_MaximumFlowRelabelToFrontTest.cc | 36 -- tests/0003_graph/CMakeLists.txt | 50 --- .../0001_FibonacciNumberTest.cc | 34 -- .../0002_TribonacciNumberTest.cc | 34 -- .../0003_ClimbingStairsTest.cc | 33 -- .../0004_MinimumCostClimbingStairsTest.cc | 33 -- .../0005_HouseRobber1Test.cc | 33 -- .../0006_HouseRobber2Test.cc | 48 --- .../0007_DecodeWaysTest.cc | 47 --- .../0008_TilingProblemTest.cc | 33 -- .../0009_FriendsPairingProblemTest.cc | 91 ----- .../0010_WaysToCoverDistanceTest.cc | 117 ------ ...ountWaysToReachNthStairIncludeOrderTest.cc | 33 -- ...ountWaysToReachNthStairExcludeOrderTest.cc | 33 -- .../0013_KnapsackProblemTest.cc | 53 --- .../0014_SubsetSumProblemTest.cc | 35 -- .../0015_CountSubsetsForSumTest.cc | 35 -- .../0016_PartitionEqualSubsetSumTest.cc | 33 -- .../0017_TargetSumTest.cc | 50 --- tests/0004_dynamic_programming/CMakeLists.txt | 49 --- tests/0005_greedy_algorithms/CMakeLists.txt | 0 tests/0006_bitwise_algorithms/CMakeLists.txt | 0 tests/CMakeLists.txt | 7 - 146 files changed, 8524 deletions(-) delete mode 100644 .clang-tidy delete mode 100644 .github/ISSUE_TEMPLATE/bug_report.md delete mode 100644 .github/labeler.yaml delete mode 100644 .github/pull_request_template.md delete mode 100644 .github/release.yaml delete mode 100644 .github/workflows/auto-labeler.yaml delete mode 100644 .github/workflows/deploy.yaml delete mode 100644 .github/workflows/validate.yaml delete mode 100644 .gitignore delete mode 100644 CMakeLists.txt delete mode 100644 CMakePresets.json delete mode 100644 CODE_OF_CONDUCT.md delete mode 100644 CONTRIBUTING.md delete mode 100644 LICENSE delete mode 100644 README.md delete mode 100644 SECURITY.md delete mode 100644 src/0001_basics/CMakeLists.txt delete mode 100644 src/0001_basics/Node.cc delete mode 100644 src/0001_basics/headers/Node.h delete mode 100644 src/0002_tree/0001_BinarySearchTree.cc delete mode 100644 src/0002_tree/CMakeLists.txt delete mode 100644 src/0002_tree/headers/0001_BinarySearchTree.h delete mode 100644 src/0003_graph/0001_BreadthFirstSearch.cc delete mode 100644 src/0003_graph/0002_DepthFirstSearch.cc delete mode 100644 src/0003_graph/0003_TopologicalSort.cc delete mode 100644 src/0003_graph/0004_StronglyConnectedComponents.cc delete mode 100644 src/0003_graph/0005_HamiltonianPathAndCycle.cc delete mode 100644 src/0003_graph/0006_EulerianPathAndCircuit.cc delete mode 100644 src/0003_graph/0007_MinimumSpanningTreeKruskalAlgorithm.cc delete mode 100644 src/0003_graph/0008_MinimumSpanningTreePrimAlgorithm.cc delete mode 100644 src/0003_graph/0009_SingleSourceShortestPathBellmanFord.cc delete mode 100644 src/0003_graph/0010_DirectedAcyclicGraphShortestPath.cc delete mode 100644 src/0003_graph/0011_SingleSourceShortestPathDijkstra.cc delete mode 100644 src/0003_graph/0012_DifferenceConstraintsShortestPaths.cc delete mode 100644 src/0003_graph/0013_AllPairsShortestPathsFloydWarshall.cc delete mode 100644 src/0003_graph/0014_AllPairsShortestPathsJohnson.cc delete mode 100644 src/0003_graph/0015_MaximumFlowFordFulkerson.cc delete mode 100644 src/0003_graph/0016_MaximumFlowEdmondsKarp.cc delete mode 100644 src/0003_graph/0017_MaximumBipartiteMatching.cc delete mode 100644 src/0003_graph/0018_MaximumFlowGoldbergGenericPushRelabel.cc delete mode 100644 src/0003_graph/0019_MaximumFlowRelabelToFront.cc delete mode 100644 src/0003_graph/CMakeLists.txt delete mode 100644 src/0003_graph/headers/0001_BreadthFirstSearch.h delete mode 100644 src/0003_graph/headers/0002_DepthFirstSearch.h delete mode 100644 src/0003_graph/headers/0003_TopologicalSort.h delete mode 100644 src/0003_graph/headers/0004_StronglyConnectedComponents.h delete mode 100644 src/0003_graph/headers/0005_HamiltonianPathAndCycle.h delete mode 100644 src/0003_graph/headers/0006_EulerianPathAndCircuit.h delete mode 100644 src/0003_graph/headers/0007_MinimumSpanningTreeKruskalAlgorithm.h delete mode 100644 src/0003_graph/headers/0008_MinimumSpanningTreePrimAlgorithm.h delete mode 100644 src/0003_graph/headers/0009_SingleSourceShortestPathBellmanFord.h delete mode 100644 src/0003_graph/headers/0010_DirectedAcyclicGraphShortestPath.h delete mode 100644 src/0003_graph/headers/0011_SingleSourceShortestPathDijkstra.h delete mode 100644 src/0003_graph/headers/0012_DifferenceConstraintsShortestPaths.h delete mode 100644 src/0003_graph/headers/0013_AllPairsShortestPathsFloydWarshall.h delete mode 100644 src/0003_graph/headers/0014_AllPairsShortestPathsJohnson.h delete mode 100644 src/0003_graph/headers/0015_MaximumFlowFordFulkerson.h delete mode 100644 src/0003_graph/headers/0016_MaximumFlowEdmondsKarp.h delete mode 100644 src/0003_graph/headers/0017_MaximumBipartiteMatching.h delete mode 100644 src/0003_graph/headers/0018_MaximumFlowGoldbergGenericPushRelabel.h delete mode 100644 src/0003_graph/headers/0019_MaximumFlowRelabelToFront.h delete mode 100644 src/0004_dynamic_programming/0001_FibonacciNumber.cc delete mode 100644 src/0004_dynamic_programming/0002_TribonacciNumber.cc delete mode 100644 src/0004_dynamic_programming/0003_ClimbingStairs.cc delete mode 100644 src/0004_dynamic_programming/0004_MinimumCostClimbingStairs.cc delete mode 100644 src/0004_dynamic_programming/0005_HouseRobber1.cc delete mode 100644 src/0004_dynamic_programming/0006_HouseRobber2.cc delete mode 100644 src/0004_dynamic_programming/0007_DecodeWays.cc delete mode 100644 src/0004_dynamic_programming/0008_TilingProblem.cc delete mode 100644 src/0004_dynamic_programming/0009_FriendsPairingProblem.cc delete mode 100644 src/0004_dynamic_programming/0010_WaysToCoverDistance.cc delete mode 100644 src/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrder.cc delete mode 100644 src/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrder.cc delete mode 100644 src/0004_dynamic_programming/0013_KnapsackProblem.cc delete mode 100644 src/0004_dynamic_programming/0014_SubsetSumProblem.cc delete mode 100644 src/0004_dynamic_programming/0015_CountSubsetsForSum.cc delete mode 100644 src/0004_dynamic_programming/0016_PartitionEqualSubsetSum.cc delete mode 100644 src/0004_dynamic_programming/0017_TargetSum.cc delete mode 100644 src/0004_dynamic_programming/CMakeLists.txt delete mode 100644 src/0004_dynamic_programming/headers/0001_FibonacciNumber.h delete mode 100644 src/0004_dynamic_programming/headers/0002_TribonacciNumber.h delete mode 100644 src/0004_dynamic_programming/headers/0003_ClimbingStairs.h delete mode 100644 src/0004_dynamic_programming/headers/0004_MinimumCostClimbingStairs.h delete mode 100644 src/0004_dynamic_programming/headers/0005_HouseRobber1.h delete mode 100644 src/0004_dynamic_programming/headers/0006_HouseRobber2.h delete mode 100644 src/0004_dynamic_programming/headers/0007_DecodeWays.h delete mode 100644 src/0004_dynamic_programming/headers/0008_TilingProblem.h delete mode 100644 src/0004_dynamic_programming/headers/0009_FriendsPairingProblem.h delete mode 100644 src/0004_dynamic_programming/headers/0010_WaysToCoverDistance.h delete mode 100644 src/0004_dynamic_programming/headers/0011_CountWaysToReachNthStairIncludeOrder.h delete mode 100644 src/0004_dynamic_programming/headers/0012_CountWaysToReachNthStairExcludeOrder.h delete mode 100644 src/0004_dynamic_programming/headers/0013_KnapsackProblem.h delete mode 100644 src/0004_dynamic_programming/headers/0014_SubsetSumProblem.h delete mode 100644 src/0004_dynamic_programming/headers/0015_CountSubsetsForSum.h delete mode 100644 src/0004_dynamic_programming/headers/0016_PartitionEqualSubsetSum.h delete mode 100644 src/0004_dynamic_programming/headers/0017_TargetSum.h delete mode 100644 src/0005_greedy_algorithms/CMakeLists.txt delete mode 100644 src/0006_bitwise_algorithms/CMakeLists.txt delete mode 100644 src/CMakeLists.txt delete mode 100644 tests/0000_common_utilities/CMakeLists.txt delete mode 100644 tests/0000_common_utilities/UnitTestHelper.h delete mode 100644 tests/0001_basics/CMakeLists.txt delete mode 100644 tests/0001_basics/NodeTest.cc delete mode 100644 tests/0002_tree/0001_BinarySearchTreeTest.cc delete mode 100644 tests/0002_tree/CMakeLists.txt delete mode 100644 tests/0003_graph/0001_BreadthFirstSearchTest.cc delete mode 100644 tests/0003_graph/0002_DepthFirstSearchTest.cc delete mode 100644 tests/0003_graph/0003_TopologicalSortTest.cc delete mode 100644 tests/0003_graph/0004_StronglyConnectedComponentsTest.cc delete mode 100644 tests/0003_graph/0005_HamiltonianPathAndCycleTest.cc delete mode 100644 tests/0003_graph/0006_EulerianPathAndCircuitTest.cc delete mode 100644 tests/0003_graph/0007_MinimumSpanningTreeKruskalAlgorithmTest.cc delete mode 100644 tests/0003_graph/0008_MinimumSpanningTreePrimAlgorithmTest.cc delete mode 100644 tests/0003_graph/0009_SingleSourceShortestPathBellmanFordTest.cc delete mode 100644 tests/0003_graph/0010_DirectedAcyclicGraphShortestPathTest.cc delete mode 100644 tests/0003_graph/0011_SingleSourceShortestPathDijkstraTest.cc delete mode 100644 tests/0003_graph/0012_DifferenceConstraintsShortestPathsTest.cc delete mode 100644 tests/0003_graph/0013_AllPairsShortestPathsFloydWarshallTest.cc delete mode 100644 tests/0003_graph/0014_AllPairsShortestPathsJohnsonTest.cc delete mode 100644 tests/0003_graph/0015_MaximumFlowFordFulkersonTest.cc delete mode 100644 tests/0003_graph/0016_MaximumFlowEdmondsKarpTest.cc delete mode 100644 tests/0003_graph/0017_MaximumBipartiteMatchingTest.cc delete mode 100644 tests/0003_graph/0018_MaximumFlowGoldbergGenericPushRelabelTest.cc delete mode 100644 tests/0003_graph/0019_MaximumFlowRelabelToFrontTest.cc delete mode 100644 tests/0003_graph/CMakeLists.txt delete mode 100644 tests/0004_dynamic_programming/0001_FibonacciNumberTest.cc delete mode 100644 tests/0004_dynamic_programming/0002_TribonacciNumberTest.cc delete mode 100644 tests/0004_dynamic_programming/0003_ClimbingStairsTest.cc delete mode 100644 tests/0004_dynamic_programming/0004_MinimumCostClimbingStairsTest.cc delete mode 100644 tests/0004_dynamic_programming/0005_HouseRobber1Test.cc delete mode 100644 tests/0004_dynamic_programming/0006_HouseRobber2Test.cc delete mode 100644 tests/0004_dynamic_programming/0007_DecodeWaysTest.cc delete mode 100644 tests/0004_dynamic_programming/0008_TilingProblemTest.cc delete mode 100644 tests/0004_dynamic_programming/0009_FriendsPairingProblemTest.cc delete mode 100644 tests/0004_dynamic_programming/0010_WaysToCoverDistanceTest.cc delete mode 100644 tests/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrderTest.cc delete mode 100644 tests/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrderTest.cc delete mode 100644 tests/0004_dynamic_programming/0013_KnapsackProblemTest.cc delete mode 100644 tests/0004_dynamic_programming/0014_SubsetSumProblemTest.cc delete mode 100644 tests/0004_dynamic_programming/0015_CountSubsetsForSumTest.cc delete mode 100644 tests/0004_dynamic_programming/0016_PartitionEqualSubsetSumTest.cc delete mode 100644 tests/0004_dynamic_programming/0017_TargetSumTest.cc delete mode 100644 tests/0004_dynamic_programming/CMakeLists.txt delete mode 100644 tests/0005_greedy_algorithms/CMakeLists.txt delete mode 100644 tests/0006_bitwise_algorithms/CMakeLists.txt delete mode 100644 tests/CMakeLists.txt diff --git a/.clang-tidy b/.clang-tidy deleted file mode 100644 index b797f75..0000000 --- a/.clang-tidy +++ /dev/null @@ -1,27 +0,0 @@ -Checks: > - readability-identifier-naming - -WarningsAsErrors: '*' - -HeaderFilterRegex: '(include/.*|source/.*)' - -CheckOptions: - # Private member variables - - key: readability-identifier-naming.PrivateMemberPrefix - value: _ - - key: readability-identifier-naming.PrivateMemberCase - value: camelBack - - # Member function (non-static, non-const, non-virtual) - - key: readability-identifier-naming.MethodCase - value: CamelCase - - # Class names - - key: readability-identifier-naming.ClassCase - value: CamelCase - - # Optional, but ensures errors are reported instead of silently skipped - - key: readability-identifier-naming.IgnoreFailures - value: false - - key: readability-identifier-naming.IgnoreFailedSplit - value: false \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index bfe83ee..0000000 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,28 +0,0 @@ -## Bug Report - -### Describe the Bug -_A clear and concise description of what the bug is._ - -### Steps to Reproduce -_Steps to reproduce the behavior:_ -1. Go to `path/to/file.cpp` -2. Run the test case: `./test_case_name` -3. Observe the error - -### Expected Behavior -_A clear and concise description of what you expected to happen._ - -### Screenshots/Outputs -_If applicable, add screenshots or log output to help explain the issue._ - -### Environment (please complete the following information): -- **OS:** [e.g., Windows, macOS, Linux] -- **Compiler:** [e.g., GCC 11, Clang 14, MSVC] -- **CMake Version:** [if applicable] -- **Any other relevant setup details** - -### Possible Fix (Optional) -_If you have an idea of how to fix it, mention it here._ - -### Additional Context -_Add any other context about the problem here._ diff --git a/.github/labeler.yaml b/.github/labeler.yaml deleted file mode 100644 index dae837a..0000000 --- a/.github/labeler.yaml +++ /dev/null @@ -1,51 +0,0 @@ -# Data Structures and Algorithms: These labels group include, src, and tests by their specific topic -basics: - - changed-files: - - any-glob-to-any-file: 'include/0001_Basics/**' - - any-glob-to-any-file: 'src/0001_Basics/**' - - any-glob-to-any-file: 'tests/0001_Basics/**' -tree: - - changed-files: - - any-glob-to-any-file: 'include/0002_Tree/**' - - any-glob-to-any-file: 'src/0002_Tree/**' - - any-glob-to-any-file: 'tests/0002_Tree/**' -graph: - - changed-files: - - any-glob-to-any-file: 'include/0003_Graph/**' - - any-glob-to-any-file: 'src/0003_Graph/**' - - any-glob-to-any-file: 'tests/0003_Graph/**' -greedy-algorithms: - - changed-files: - - any-glob-to-any-file: 'include/0004_GreedyAlgorithms/**' - - any-glob-to-any-file: 'src/0004_GreedyAlgorithms/**' - - any-glob-to-any-file: 'tests/0004_GreedyAlgorithms/**' -dynamic-programming: - - changed-files: - - any-glob-to-any-file: 'include/0005_DynamicProgramming/**' - - any-glob-to-any-file: 'src/0005_DynamicProgramming/**' - - any-glob-to-any-file: 'tests/0005_DynamicProgramming/**' -bitwise-algorithms: - - changed-files: - - any-glob-to-any-file: 'include/0006_BitwiseAlgorithms/**' - - any-glob-to-any-file: 'src/0006_BitwiseAlgorithms/**' - - any-glob-to-any-file: 'tests/0006_BitwiseAlgorithms/**' - -# Build System: Only fires when every changed file is a CMakeLists.txt -build: - - changed-files: - - all-globs-to-all-files: '**/CMakeLists.txt' - -# Testing Utils: Catches the helper files in tests/0000_CommonUtilities -test-utils: - - changed-files: - - any-glob-to-any-file: 'tests/0000_CommonUtilities/**' - -# Tooling: Github workflows -workflows: - - changed-files: - - any-glob-to-any-file: '.github/**' - -# Documentation: Root level MD files -documentation: - - changed-files: - - any-glob-to-any-file: '*.md' \ No newline at end of file diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md deleted file mode 100644 index b9581fa..0000000 --- a/.github/pull_request_template.md +++ /dev/null @@ -1,28 +0,0 @@ -### Pull Request Guidelines - -1. **feature → release:** Please provide a description of the solution or fix. The `auto-labeler` bot will automatically label this PR based on the files changed. -2. **release → main:** **Please select the version bump type**, release notes will be auto-generated from the merged feature PRs. - -### feature to release -*(Fill this out when merging a feature branch into a release branch)* - -**Description Category** -- [ ] Basics -- [ ] Tree -- [ ] Graph -- [ ] GreedyAlgorithms -- [ ] DynamicProgramming -- [ ] BitwiseAlgorithms - -**Notes** - - - - -### release to main -*(Fill this out ONLY when merging a release branch into main)* - -**Version Bump Type** -- [ ] Major -- [ ] Minor -- [ ] Patch \ No newline at end of file diff --git a/.github/release.yaml b/.github/release.yaml deleted file mode 100644 index f4ee77d..0000000 --- a/.github/release.yaml +++ /dev/null @@ -1,56 +0,0 @@ -template: | - ### datastructures-algorithms — release v$RESOLVED_VERSION - $CHANGES - - **Full Changelog:** https://github.com/$OWNER/$REPOSITORY/compare/$PREVIOUS_TAG...v$RESOLVED_VERSION - -change-template: '- $TITLE [#$NUMBER]' - -categories: - - title: 'Basics' - labels: - - 'basics' - - - title: 'Tree' - labels: - - 'tree' - - - title: 'Graph' - labels: - - 'graph' - - - title: 'Greedy Algorithms' - labels: - - 'greedy-algorithms' - - - title: 'Dynamic Programming' - labels: - - 'dynamic-programming' - - - title: 'Bitwise Algorithms' - labels: - - 'bitwise-algorithms' - - - title: 'Build System (CMake)' - labels: - - 'build' - - - title: 'Testing Utilities' - labels: - - 'test-utils' - - - title: 'Workflows Updated' - labels: - - 'workflows' - - - title: 'Documentation' - labels: - - 'documentation' - -exclude-labels: - - 'skip-changelog' - -# Convert "## Title" to "**Title**" -replacers: - - search: '/^## (.*)$/gm' - replace: '**$1**' \ No newline at end of file diff --git a/.github/workflows/auto-labeler.yaml b/.github/workflows/auto-labeler.yaml deleted file mode 100644 index df13bc0..0000000 --- a/.github/workflows/auto-labeler.yaml +++ /dev/null @@ -1,36 +0,0 @@ -name: auto-labeler - -# Run this on every PR open or update -on: - pull_request: - types: [opened, synchronize, reopened] - -permissions: - contents: read - # Required to add labels - pull-requests: write - -jobs: - assign-labels: - runs-on: ubuntu-latest - steps: - - name: Checkout Repository - uses: actions/checkout@v4 - # 1. Standard File-based Labeler (Contest vs Problemset) - - name: Assign Labels Based on Changes - id: labeler - uses: actions/labeler@v5 - with: - # This tells it to look at your .github/labeler.yaml - configuration-path: .github/labeler.yaml - repo-token: "${{ secrets.GITHUB_TOKEN }}" - sync-labels: true - - # 2. NEW: Branch-based Labeler (Ignore Release Branches) - - name: Label Release PRs to Skip Changelog - # Only run if the source branch starts with 'release/' - if: startsWith(github.head_ref, 'release/') - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - gh pr edit ${{ github.event.pull_request.number }} --add-label "skip-changelog" \ No newline at end of file diff --git a/.github/workflows/deploy.yaml b/.github/workflows/deploy.yaml deleted file mode 100644 index 9f024d9..0000000 --- a/.github/workflows/deploy.yaml +++ /dev/null @@ -1,160 +0,0 @@ -name: deploy - -# Triggers only when a PR to 'main' is closed -on: - pull_request: - types: [closed] - branches: - - 'main' - -permissions: - contents: write # Required to push tags and create releases - pull-requests: read # Required to read PR body for checkboxes - -jobs: - # job 1: Deployment Validation - # Verifies the PR is merged, comes from a release/* branch, and has a bump type. - deployment-validation: - runs-on: ubuntu-latest - # Define outputs to pass to the next job - outputs: - bump_type: ${{ steps.get_bump_type.outputs.bump_type }} - - steps: - - name: Verify Merge and Branch Policy - run: | - IS_MERGED="${{ github.event.pull_request.merged }}" - HEAD_REF="${{ github.event.pull_request.head.ref }}" - - echo "PR Merged: $IS_MERGED" - echo "Source Branch: $HEAD_REF" - - # 1. Check if PR was actually merged (not just closed) - if [[ "$IS_MERGED" != "true" ]]; then - echo "::notice::PR was closed without merging. Skipping release." - exit 1 - fi - - # 2. Check if source branch starts with 'release/' - if [[ "$HEAD_REF" != release/* ]]; then - echo "::error::Invalid source branch. Releases must originate from 'release/*' branches." - exit 1 - fi - - echo "Branch policy checks passed." - - - name: Determine Version Bump Type - id: get_bump_type - env: - PR_BODY: ${{ github.event.pull_request.body }} - run: | - # Check checkboxes in PR Body: [x] Major, [x] Minor, etc. - if echo "$PR_BODY" | grep -q '\[x\] Major'; then - echo "bump_type=major" >> $GITHUB_OUTPUT - echo "Detected bump: MAJOR" - elif echo "$PR_BODY" | grep -q '\[x\] Minor'; then - echo "bump_type=minor" >> $GITHUB_OUTPUT - echo "Detected bump: MINOR" - elif echo "$PR_BODY" | grep -q '\[x\] Patch'; then - echo "bump_type=patch" >> $GITHUB_OUTPUT - echo "Detected bump: PATCH" - else - echo "::error::No version bump detected. Please check [x] Major, [x] Minor, or [x] Patch in the PR body." - exit 1 - fi - - # job 2: Create GitHub Tag and Release - create-github-tag-and-release: - needs: deployment-validation - runs-on: ubuntu-latest - env: - BUMP_TYPE: ${{ needs.deployment-validation.outputs.bump_type }} - - steps: - - name: Checkout main branch - uses: actions/checkout@v4 - with: - ref: 'main' - fetch-depth: 0 # Crucial for calculating history/tags - - - name: Configure Git - run: | - git config --global user.name "github-actions[bot]" - git config --global user.email "github-actions[bot]@users.noreply.github.com" - - # Step A: Find the existing tag - - name: Get Latest Tag - id: get_latest_tag - run: | - # 1. Fetch all tags - git fetch --tags - - # 2. Find latest tag (Sort by version number, take top) - LATEST_TAG=$(git tag --list 'v*.*.*' --sort=-v:refname | head -n 1) - - if [ -z "$LATEST_TAG" ]; then - echo "No previous tags found. Defaulting to v0.0.0" - LATEST_TAG="v0.0.0" - fi - - echo "Latest Tag: $LATEST_TAG" - - # Expose this variable to the next step - echo "latest_tag=$LATEST_TAG" >> $GITHUB_OUTPUT - - # Step B: Do the math - - name: Calculate New Tag - id: calc_new_tag - env: - # Pull the tag from the previous step - LATEST_TAG: ${{ steps.get_latest_tag.outputs.latest_tag }} - # Assuming BUMP_TYPE is set in the Job 'env' as per previous context - run: | - echo "Base Tag: $LATEST_TAG" - echo "Bump Type: $BUMP_TYPE" - - # 1. Parse Version - VERSION=${LATEST_TAG#v} # Remove 'v' - IFS='.' read -r -a parts <<< "$VERSION" - MAJOR=${parts[0]} - MINOR=${parts[1]} - PATCH=${parts[2]} - - # 2. Increment - case "$BUMP_TYPE" in - "major") MAJOR=$((MAJOR + 1)); MINOR=0; PATCH=0 ;; - "minor") MINOR=$((MINOR + 1)); PATCH=0 ;; - "patch") PATCH=$((PATCH + 1)) ;; - esac - - NEW_TAG="v${MAJOR}.${MINOR}.${PATCH}" - - echo "new_tag=$NEW_TAG" >> $GITHUB_OUTPUT - echo "New tag will be: $NEW_TAG" - - - name: Create and push new Git tag - run: | - NEW_TAG=${{ steps.calc_new_tag.outputs.new_tag }} - MERGE_COMMIT_SHA=${{ github.event.pull_request.merge_commit_sha }} - - echo "Tagging commit $MERGE_COMMIT_SHA as $NEW_TAG" - git tag $NEW_TAG $MERGE_COMMIT_SHA - git push origin $NEW_TAG - - # Step D: Generate Auto-Notes and Publish - - name: Create GitHub Release - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - uses: release-drafter/release-drafter@v6 - with: - # Uses your .github/release.yaml to categorize changes - config-name: release.yaml - - # We force it to use the tag you just calculated and pushed - tag: ${{ steps.calc_new_tag.outputs.new_tag }} - name: "${{ steps.calc_new_tag.outputs.new_tag }}" - version: ${{ steps.calc_new_tag.outputs.new_tag }} - - # This makes it a real release (not a draft) - publish: true - \ No newline at end of file diff --git a/.github/workflows/validate.yaml b/.github/workflows/validate.yaml deleted file mode 100644 index 47a55f5..0000000 --- a/.github/workflows/validate.yaml +++ /dev/null @@ -1,130 +0,0 @@ -name: validate - -on: - pull_request: - types: [opened, synchronize] - branches: - - 'release/*' - - 'main' - -jobs: - # job 1: Policy Check - validate-branch-policy: - runs-on: ubuntu-latest - steps: - - name: Verify Branch Strategy - run: | - HEAD="${{ github.head_ref }}" - BASE="${{ github.base_ref }}" - echo "Verifying path: $HEAD -> $BASE" - - if [[ "$HEAD" == feature/* && "$BASE" == release/* ]]; then - echo "Pull Request is allowed: $HEAD -> $BASE." - exit 0 - elif [[ "$HEAD" == release/* && "$BASE" == main ]]; then - echo "Pull Request is allowed: $HEAD -> $BASE." - exit 0 - else - echo "::error::Invalid Pull Request from '$HEAD' -> '$BASE'." - echo "Allowed: 'feature/*'->'release/*' OR 'release/*'->'main'." - exit 1 - fi - - # job 2: Static Analysis - lint-code: - needs: validate-branch-policy - runs-on: windows-latest - steps: - - name: Checkout code - uses: actions/checkout@v4 - - - name: Setup MSVC - uses: ilammy/msvc-dev-cmd@v1 - with: - arch: x64 - - - name: Install dependencies - shell: pwsh - run: | - choco install cmake --no-progress -y - choco install ninja --no-progress -y - choco install llvm --no-progress -y - - - name: Configure CMake - shell: pwsh - run: cmake -S . -B build -G "Ninja" -DCMAKE_EXPORT_COMPILE_COMMANDS=ON - - - name: Run clang-tidy - shell: pwsh - run: | - clang-tidy --version - $files = Get-ChildItem -Recurse -Path src -Include *.cpp,*.cc,*.cxx -File - $failed = $false - # These source/.* files would be checked using .clang-tidy maintained at projectroot - foreach ($file in $files) { - Write-Host "Checking $($file.FullName)" - clang-tidy -p build "$($file.FullName)" --warnings-as-errors=* - if ($LASTEXITCODE -ne 0) { $failed = $true } - } - if ($failed) { Write-Error "Clang-tidy failed."; exit 1 } - - # job 3: Build Project - build-project: - needs: lint-code - runs-on: windows-latest - steps: - - name: Checkout code - uses: actions/checkout@v4 - - - name: Setup MSVC - uses: ilammy/msvc-dev-cmd@v1 - with: - arch: x64 - - - name: Install dependencies - shell: pwsh - run: | - choco install cmake --no-progress -y - choco install ninja --no-progress -y - - - name: Configure CMake - shell: pwsh - run: cmake -S . -B build -G "Ninja" - - - name: Build - shell: pwsh - run: cmake --build build --config Release - - # Upload the build directory so the Test job can use it - - name: Upload Build Artifacts - uses: actions/upload-artifact@v4 - with: - name: build-artifacts - path: build/ - retention-days: 1 - - # job 4: Run all Tests - run-all-tests: - needs: build-project - runs-on: windows-latest - steps: - - name: Checkout code - # We need the source code because CTest might look for source files referenced in tests - uses: actions/checkout@v4 - - - name: Install dependencies - shell: pwsh - # We only need CMake (for ctest) here. Ninja/LLVM usually not needed unless tests invoke them. - run: choco install cmake --no-progress -y - - - name: Download Build Artifacts - uses: actions/download-artifact@v4 - with: - name: build-artifacts - path: build - - - name: Run tests - shell: pwsh - # -C Release is crucial if it's a multi-config generator, though Ninja is single-config. - # Good practice to keep it for consistency. - run: ctest --test-dir build --output-on-failure -C Release \ No newline at end of file diff --git a/.gitignore b/.gitignore deleted file mode 100644 index ccdf92f..0000000 --- a/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -.vs/ -.vscode/ -artifact/ \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt deleted file mode 100644 index d919238..0000000 --- a/CMakeLists.txt +++ /dev/null @@ -1,35 +0,0 @@ -cmake_minimum_required (VERSION 3.10) -project ("datastructures-algorithms") - -set(CMAKE_CXX_STANDARD 14) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_EXPORT_COMPILE_COMMANDS ON) - - -# .clang-tidy setup -find_program(CLANG_TIDY_EXE NAMES "clang-tidy") -if(CLANG_TIDY_EXE) - message(STATUS "clang-tidy found: ${CLANG_TIDY_EXE}") - set(CLANG_TIDY_COMMAND - "${CLANG_TIDY_EXE}" - "--config-file=${CMAKE_SOURCE_DIR}/.clang-tidy" - "--extra-arg-before=-Wno-unknown-warning-option" - "--extra-arg-before=-Wno-c++98-compat-pedantic" - "--quiet" - ) -endif() - -add_subdirectory(src) - -cmake_policy(SET CMP0135 NEW) -include(FetchContent) -FetchContent_Declare( - googletest - URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip -) - -# For Windows: Prevent overriding the parent project's compiler/linker settings -set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) - -enable_testing() -add_subdirectory(tests) \ No newline at end of file diff --git a/CMakePresets.json b/CMakePresets.json deleted file mode 100644 index 71f41cb..0000000 --- a/CMakePresets.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "version": 3, - "configurePresets": [ - { - "name": "windows-base", - "hidden": true, - "generator": "Ninja", - "binaryDir": "${sourceDir}/artifact/build/${presetName}", - "installDir": "${sourceDir}/artifact/install/${presetName}", - "cacheVariables": { - "CMAKE_C_COMPILER": "cl.exe", - "CMAKE_CXX_COMPILER": "cl.exe" - }, - "condition": { - "type": "equals", - "lhs": "${hostSystemName}", - "rhs": "Windows" - } - }, - { - "name": "x64-debug", - "displayName": "x64 Debug", - "inherits": "windows-base", - "architecture": { - "value": "x64", - "strategy": "external" - }, - "cacheVariables": { - "CMAKE_BUILD_TYPE": "Debug" - } - }, - { - "name": "x64-release", - "displayName": "x64 Release", - "inherits": "x64-debug", - "cacheVariables": { - "CMAKE_BUILD_TYPE": "Release" - } - }, - { - "name": "x86-debug", - "displayName": "x86 Debug", - "inherits": "windows-base", - "architecture": { - "value": "x86", - "strategy": "external" - }, - "cacheVariables": { - "CMAKE_BUILD_TYPE": "Debug" - } - }, - { - "name": "x86-release", - "displayName": "x86 Release", - "inherits": "x86-debug", - "cacheVariables": { - "CMAKE_BUILD_TYPE": "Release" - } - } - ] -} diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md deleted file mode 100644 index 3f705c7..0000000 --- a/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,127 +0,0 @@ -## Contributor Covenant Code of Conduct - -### Our Pledge - -We as members, contributors, and leaders pledge to make participation in our -community a harassment-free experience for everyone, regardless of age, body -size, visible or invisible disability, ethnicity, sex characteristics, gender -identity and expression, level of experience, education, socio-economic status, -nationality, personal appearance, race, religion, or sexual identity -and orientation. - -We pledge to act and interact in ways that contribute to an open, welcoming, -diverse, inclusive, and healthy community. - -### Our Standards - -Examples of behavior that contributes to a positive environment for our -community include: - -* Demonstrating empathy and kindness toward other people -* Being respectful of differing opinions, viewpoints, and experiences -* Giving and gracefully accepting constructive feedback -* Accepting responsibility and apologizing to those affected by our mistakes, - and learning from the experience -* Focusing on what is best not just for us as individuals, but for the - overall community - -Examples of unacceptable behavior include: - -* The use of sexualized language or imagery, and sexual attention or - advances of any kind -* Trolling, insulting or derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or email - address, without their explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -### Enforcement Responsibilities - -Community leaders are responsible for clarifying and enforcing our standards of -acceptable behavior and will take appropriate and fair corrective action in -response to any behavior that they deem inappropriate, threatening, offensive, -or harmful. - -Community leaders have the right and responsibility to remove, edit, or reject -comments, commits, code, wiki edits, issues, and other contributions that are -not aligned to this Code of Conduct, and will communicate reasons for moderation -decisions when appropriate. - -### Scope - -This Code of Conduct applies within all community spaces, and also applies when -an individual is officially representing the community in public spaces. -Examples of representing our community include using an official e-mail address, -posting via an official social media account, or acting as an appointed -representative at an online or offline event. - -### Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported to the community leaders responsible for enforcement at. -All complaints will be reviewed and investigated promptly and fairly. - -All community leaders are obligated to respect the privacy and security of the -reporter of any incident. - -### Enforcement Guidelines - -Community leaders will follow these Community Impact Guidelines in determining -the consequences for any action they deem in violation of this Code of Conduct: - -#### 1. Correction - -**Community Impact**: Use of inappropriate language or other behavior deemed -unprofessional or unwelcome in the community. - -**Consequence**: A private, written warning from community leaders, providing -clarity around the nature of the violation and an explanation of why the -behavior was inappropriate. A public apology may be requested. - -#### 2. Warning - -**Community Impact**: A violation through a single incident or series -of actions. - -**Consequence**: A warning with consequences for continued behavior. No -interaction with the people involved, including unsolicited interaction with -those enforcing the Code of Conduct, for a specified period of time. This -includes avoiding interactions in community spaces as well as external channels -like social media. Violating these terms may lead to a temporary or -permanent ban. - -#### 3. Temporary Ban - -**Community Impact**: A serious violation of community standards, including -sustained inappropriate behavior. - -**Consequence**: A temporary ban from any sort of interaction or public -communication with the community for a specified period of time. No public or -private interaction with the people involved, including unsolicited interaction -with those enforcing the Code of Conduct, is allowed during this period. -Violating these terms may lead to a permanent ban. - -#### 4. Permanent Ban - -**Community Impact**: Demonstrating a pattern of violation of community -standards, including sustained inappropriate behavior, harassment of an -individual, or aggression toward or disparagement of classes of individuals. - -**Consequence**: A permanent ban from any sort of public interaction within -the community. - -### Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], -version 2.0, available at -https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. - -Community Impact Guidelines were inspired by [Mozilla's code of conduct -enforcement ladder](https://github.com/mozilla/diversity). - -[homepage]: https://www.contributor-covenant.org - -For answers to common questions about this code of conduct, see the FAQ at -https://www.contributor-covenant.org/faq. Translations are available at -https://www.contributor-covenant.org/translations. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 68a2127..0000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1 +0,0 @@ -## This project is for academic purpose, no contributions are expected right now. diff --git a/LICENSE b/LICENSE deleted file mode 100644 index fd336ec..0000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2025 Debashis Nandi - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/README.md b/README.md deleted file mode 100644 index bd633b7..0000000 --- a/README.md +++ /dev/null @@ -1,21 +0,0 @@ -## Data Structures and Algorithms - -This repository contains a collection of **data structures and algorithms** implemented in **C++**. It is designed to provide efficient solutions to common algorithmic problems while adhering to clean coding practices and modular design. - -### Features - -- **Data Structures and Algorithms:** Implementations of data structures and algorithms based on the concepts from the book ***Introduction to Algorithms by Cormen, Leiserson, Rivest, and Stein (CLRS).*** -- **Modular Design:** Code is organized into manageable modules for better readability and reusability. -- **Testing:** - - Built with **CMake** as the build system for ease of compilation and dependency management. - - **Google Test** framework is integrated for comprehensive unit testing to ensure code correctness. - -### Folder Structure - -```plain text -datastructures-algorithms -├── include # Header Files -├── src # Implementation of the solutions -├── tests # Unit tests for implemented solutions -└── CMakeLists.txt # CMake configuration file -``` diff --git a/SECURITY.md b/SECURITY.md deleted file mode 100644 index 206769a..0000000 --- a/SECURITY.md +++ /dev/null @@ -1 +0,0 @@ -## Security Policy diff --git a/src/0001_basics/CMakeLists.txt b/src/0001_basics/CMakeLists.txt deleted file mode 100644 index 477c6cd..0000000 --- a/src/0001_basics/CMakeLists.txt +++ /dev/null @@ -1,11 +0,0 @@ -# Specify the source files -set(0001BASICS_SOURCES - Node.cc -) - -# Create a library target -add_library(0001BASICS ${0001BASICS_SOURCES}) - -target_include_directories(0001BASICS PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/headers -) \ No newline at end of file diff --git a/src/0001_basics/Node.cc b/src/0001_basics/Node.cc deleted file mode 100644 index df1effa..0000000 --- a/src/0001_basics/Node.cc +++ /dev/null @@ -1,6 +0,0 @@ -#include "Node.h" - -Node::Node() -{ - value = 8; -} \ No newline at end of file diff --git a/src/0001_basics/headers/Node.h b/src/0001_basics/headers/Node.h deleted file mode 100644 index dcee809..0000000 --- a/src/0001_basics/headers/Node.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -class Node -{ -public: - int value; - Node(); -}; \ No newline at end of file diff --git a/src/0002_tree/0001_BinarySearchTree.cc b/src/0002_tree/0001_BinarySearchTree.cc deleted file mode 100644 index 0f0650e..0000000 --- a/src/0002_tree/0001_BinarySearchTree.cc +++ /dev/null @@ -1,349 +0,0 @@ -#include "0001_BinarySearchTree.h" -#include -#include -using namespace std; - -namespace BinarySearchTree -{ - Node::Node(int data, Node* parent, Node* left, Node* right) - { - this->data = data; - this->parent = parent; - this->left = left; - this->right = right; - } - - BinarySearchTree::BinarySearchTree() - { - this->_root = nullptr; - } - - - void BinarySearchTree::_insertBSTreeNode(Node* node) - { - Node* nodeY = nullptr; - Node* nodeX = this->_root; - while (nodeX != nullptr) - { - nodeY = nodeX; - if (node->data < nodeX->data) - { - nodeX = nodeX->left; - } - else - { - nodeX = nodeX->right; - } - } - node->parent = nodeY; - if (nodeY == nullptr) - { - this->_root = node; - } - else if (node->data < nodeY->data) - { - nodeY->left = node; - } - else - { - nodeY->right = node; - } - } - - Node* BinarySearchTree::_findBSTreeNode(int value) - { - Node* node = this->_root; - while (node != nullptr) - { - if (value < node->data) - { - node = node->left; - } - else if (value > node->data) - { - node = node->right; - } - else - { - break; - } - } - return node; - } - - Node* BinarySearchTree::_findBSTreeMinNode(Node* node) - { - while (node->left != nullptr) - { - node = node->left; - } - return node; - } - - Node* BinarySearchTree::_findBSTreeMaxNode(Node* node) - { - while (node->right != nullptr) - { - node = node->right; - } - return node; - } - - Node* BinarySearchTree::_findSuccessor(Node* node) - { - if (node->right != nullptr) - { - return this->_findBSTreeMinNode(node->right); - } - Node* nodeY = node->parent; - while (nodeY != nullptr && node == nodeY->right) - { - node = nodeY; - nodeY = nodeY->parent; - } - return nodeY; - } - - Node* BinarySearchTree::_findPredecessor(Node* node) - { - if (node->left != nullptr) - { - return this->_findBSTreeMaxNode(node->left); - } - Node* nodeY = node->parent; - while (nodeY != nullptr && node == nodeY->left) - { - node = nodeY; - nodeY = nodeY->parent; - } - return nodeY; - } - - void BinarySearchTree::_transplant(Node* nodeU, Node* nodeV) - { - if (nodeU->parent == nullptr) - { - this->_root = nodeV; - } - else if (nodeU == nodeU->parent->left) - { - nodeU->parent->left = nodeV; - } - else - { - nodeU->parent->right = nodeV; - } - - if (nodeV != nullptr) - { - nodeV->parent = nodeU->parent; - } - } - - void BinarySearchTree::_deleteBSTreeNode(Node* node) - { - if (node->left == nullptr) - { - this->_transplant(node, node->right); - } - else if (node->right == nullptr) - { - this->_transplant(node, node->left); - } - else - { - Node* nodeY = this->_findBSTreeMinNode(node->right); - if (nodeY->parent != node) - { - this->_transplant(nodeY, nodeY->right); - nodeY->right = node->right; - nodeY->right->parent = nodeY; - } - this->_transplant(node, nodeY); - nodeY->left = node->left; - nodeY->left->parent = nodeY; - delete node; - } - } - - void BinarySearchTree::_recursiveInorder(Node* node, vector& result) - { - if (node == nullptr) - { - return; - } - this->_recursiveInorder(node->left, result); - result.push_back(node->data); - this->_recursiveInorder(node->right, result); - } - - void BinarySearchTree::_recursivePreorder(Node* node, vector& result) - { - if (node == nullptr) - { - return; - } - result.push_back(node->data); - this->_recursivePreorder(node->left, result); - this->_recursivePreorder(node->right, result); - } - - void BinarySearchTree::_recursivePostorder(Node* node, vector& result) - { - if (node == nullptr) - { - return; - } - this->_recursivePostorder(node->left, result); - this->_recursivePostorder(node->right, result); - result.push_back(node->data); - } - - void BinarySearchTree::_morrisInorder(Node* node, vector& result) - { - while (node != nullptr) - { - if (node->left == nullptr) - { - result.push_back(node->data); - node = node->right; - } - else - { - Node* predecessor = node->left; - while (predecessor->right != nullptr && predecessor->right != node) - { - predecessor = predecessor->right; - } - if (predecessor->right == nullptr) - { - predecessor->right = node; - node = node->left; - } - else - { - predecessor->right = nullptr; - result.push_back(node->data); - node = node->right; - } - } - } - } - - void BinarySearchTree::_morrisPreorder(Node* node, vector& result) - { - while (node != nullptr) - { - if (node->left == nullptr) - { - result.push_back(node->data); - node = node->right; - } - else - { - Node* predecessor = node->left; - while (predecessor->right != nullptr && predecessor->right != node) - { - predecessor = predecessor->right; - } - if (predecessor->right == nullptr) - { - predecessor->right = node; - result.push_back(node->data); - node = node->left; - } - else - { - predecessor->right = nullptr; - node = node->right; - } - } - } - } - - void BinarySearchTree::_morrisPostorder(Node* node, vector& result) - { - while (node != nullptr) - { - if (node->right == nullptr) - { - result.push_back(node->data); - node = node->left; - } - else - { - Node* predecessor = node->right; - while (predecessor->left != nullptr && predecessor->left != node) - { - predecessor = predecessor->left; - } - if (predecessor->left == nullptr) - { - predecessor->left = node; - result.push_back(node->data); - node = node->right; - } - else - { - predecessor->left = nullptr; - node = node->left; - } - } - } - reverse(result.begin(), result.end()); - } - - void BinarySearchTree::insertNode(int value) - { - Node* node = new Node(value, nullptr, nullptr, nullptr); - this->_insertBSTreeNode(node); - } - - void BinarySearchTree::deleteNode(int value) - { - Node* node = this->_findBSTreeNode(value); - this->_deleteBSTreeNode(node); - } - - vector BinarySearchTree::recursiveInorderTraversal() - { - vector result; - this->_recursiveInorder(this->_root, result); - return result; - } - - vector BinarySearchTree::recursivePreorderTravesal() - { - vector result; - this->_recursivePreorder(this->_root, result); - return result; - } - - vector BinarySearchTree::recursivePostorderTravesal() - { - vector result; - this->_recursivePostorder(this->_root, result); - return result; - } - - vector BinarySearchTree::morrisInorderTraversal() - { - vector result; - this->_morrisInorder(this->_root, result); - return result; - } - - vector BinarySearchTree::morrisPreorderTraversal() - { - vector result; - this->_morrisPreorder(this->_root, result); - return result; - } - - vector BinarySearchTree::morrisPostorderTraversal() - { - vector result; - this->_morrisPostorder(this->_root, result); - return result; - } -} \ No newline at end of file diff --git a/src/0002_tree/CMakeLists.txt b/src/0002_tree/CMakeLists.txt deleted file mode 100644 index 3ef4afa..0000000 --- a/src/0002_tree/CMakeLists.txt +++ /dev/null @@ -1,11 +0,0 @@ -# Specify the source files -set(0002TREE_SOURCES - 0001_BinarySearchTree.cc -) - -# Create a library target -add_library(0002_Tree ${0002TREE_SOURCES}) - -target_include_directories(0002_Tree PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/headers -) \ No newline at end of file diff --git a/src/0002_tree/headers/0001_BinarySearchTree.h b/src/0002_tree/headers/0001_BinarySearchTree.h deleted file mode 100644 index d422701..0000000 --- a/src/0002_tree/headers/0001_BinarySearchTree.h +++ /dev/null @@ -1,49 +0,0 @@ -#pragma once - -#include -#include -using namespace std; - -namespace BinarySearchTree -{ - class Node - { - public: - int data; - Node* parent; - Node* left; - Node* right; - - Node(int data, Node* parent, Node* left, Node* right); - }; - - class BinarySearchTree - { - private: - Node* _root; - void _insertBSTreeNode(Node* node); - Node* _findBSTreeNode(int value); - Node* _findBSTreeMinNode(Node* node); - Node* _findBSTreeMaxNode(Node* node); - Node* _findSuccessor(Node* node); - Node* _findPredecessor(Node* node); - void _transplant(Node* nodeU, Node* nodeV); - void _deleteBSTreeNode(Node* node); - void _recursiveInorder(Node* node, vector& result); - void _recursivePreorder(Node* node, vector& result); - void _recursivePostorder(Node* node, vector& result); - void _morrisInorder(Node* node, vector& result); - void _morrisPreorder(Node* node, vector& result); - void _morrisPostorder(Node* node, vector& result); - public: - BinarySearchTree(); - void insertNode(int value); - void deleteNode(int value); - vector recursiveInorderTraversal(); - vector recursivePreorderTravesal(); - vector recursivePostorderTravesal(); - vector morrisInorderTraversal(); - vector morrisPreorderTraversal(); - vector morrisPostorderTraversal(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/0001_BreadthFirstSearch.cc b/src/0003_graph/0001_BreadthFirstSearch.cc deleted file mode 100644 index 9a8b1ac..0000000 --- a/src/0003_graph/0001_BreadthFirstSearch.cc +++ /dev/null @@ -1,86 +0,0 @@ -#include "0001_BreadthFirstSearch.h" -#include -#include -#include -#include -#include -#include -using namespace std; - -namespace BreadthFirstSearch -{ - Node::Node(int value) - { - this->data = value; - this->distance = INT_MAX; - this->color = WHITE; - this->parent = nullptr; - } - - Node* Graph::MakeOrFindNode(int value) - { - Node* node = nullptr; - if (this->_nodeMap.find(value) == this->_nodeMap.end()) - { - node = new Node(value); - this->_nodeMap[value] = node; - } - else - { - node = this->_nodeMap[value]; - } - return node; - } - - void Graph::BreadthFirstSearch(Node* node) - { - node->color = WHITE; - node->distance = 0; - node->parent = nullptr; - - queue nodeQueue; - nodeQueue.push(node); - - while (nodeQueue.empty() != true) - { - Node* currentNode = nodeQueue.front(); - nodeQueue.pop(); - - for (auto& adjacentNode : this->_adjlist[currentNode]) - { - if (adjacentNode->color == WHITE) - { - adjacentNode->color = GRAY; - adjacentNode->parent = currentNode; - adjacentNode->distance = currentNode->distance + 1; - nodeQueue.push(adjacentNode); - } - } - currentNode->color = BLACK; - } - } - - void Graph::PushUndirectedEdge(int valueU, int valueV) - { - Node* nodeU = this->MakeOrFindNode(valueU); - Node* nodeV = this->MakeOrFindNode(valueV); - - this->_adjlist[nodeU].push_back(nodeV); - this->_adjlist[nodeV].push_back(nodeU); - } - - void Graph::BFS(int value) - { - this->BreadthFirstSearch(this->_nodeMap[value]); - } - - vector> Graph::ShowBFSResult() - { - vector> result; - for (auto& node : this->_nodeMap) - { - result.push_back(make_pair(node.first, node.second->distance)); - } - return result; - } -} \ No newline at end of file diff --git a/src/0003_graph/0002_DepthFirstSearch.cc b/src/0003_graph/0002_DepthFirstSearch.cc deleted file mode 100644 index 3cbc49a..0000000 --- a/src/0003_graph/0002_DepthFirstSearch.cc +++ /dev/null @@ -1,80 +0,0 @@ -#include "0002_DepthFirstSearch.h" -#include -#include -#include -using namespace std; - -namespace DepthFirstSearch -{ - Node::Node(int value) - { - this->data = value; - this->discoveredTime = INT_MAX; - this->finishingTime = INT_MAX; - this->color = WHITE; - this->parent = nullptr; - } - - Node* Graph::MakeOrFindNode(int value) - { - Node* node = nullptr; - if (this->_nodeMap.find(value) == this->_nodeMap.end()) - { - node = new Node(value); - this->_nodeMap[value] = node; - } - else - { - node = this->_nodeMap[value]; - } - return node; - } - - void Graph::DepthFirstSearch(Node* nodeU) - { - this->_time++; - nodeU->discoveredTime = this->_time; - nodeU->color = GRAY; - for (auto nodeV : this->_adjlist[nodeU]) - { - if (nodeV->color == WHITE) - { - nodeV->parent = nodeU; - this->DepthFirstSearch(nodeV); - } - } - nodeU->color = BLACK; - this->_time++; - nodeU->finishingTime = this->_time; - } - - void Graph::PushDirectedEdge(int valueU, int valueV) - { - Node* nodeU = this->MakeOrFindNode(valueU); - Node* nodeV = this->MakeOrFindNode(valueV); - - this->_adjlist[nodeU].push_back(nodeV); - } - - void Graph::DFS() - { - this->_time = 0; - for (auto& iterator : this->_nodeMap) - { - if (iterator.second->color == WHITE) - { - this->DepthFirstSearch(iterator.second); - } - } - } - - vector>> Graph::ShowDFSResult() - { - vector>> result; - for (auto& node : this->_nodeMap) - { - result.push_back(make_pair(node.first, make_pair(node.second->discoveredTime, node.second->finishingTime))); - } - return result; - } -} \ No newline at end of file diff --git a/src/0003_graph/0003_TopologicalSort.cc b/src/0003_graph/0003_TopologicalSort.cc deleted file mode 100644 index 3d4d1cb..0000000 --- a/src/0003_graph/0003_TopologicalSort.cc +++ /dev/null @@ -1,150 +0,0 @@ -#include "0003_TopologicalSort.h" -#include -#include -#include -#include -#include -using namespace std; - -namespace TopologicalSort -{ - Node::Node(int value) - { - this->data = value; - this->color = WHITE; - this->discoveryTime = INT_MAX; - this->finishingTime = INT_MAX; - this->inDegree = 0; - this->parent = nullptr; - } - - Node* Graph::MakeOrFindNode(int value) - { - Node* node = nullptr; - if (this->_nodeMap.find(value) == this->_nodeMap.end()) - { - node = new Node(value); - this->_nodeMap[value] = node; - } - else - { - node = this->_nodeMap[value]; - } - return node; - } - - void Graph::DepthFirstSearch(Node* nodeU) - { - this->_time++; - nodeU->discoveryTime = this->_time; - nodeU->color = GRAY; - for (auto& nodeV : this->_adjlist[nodeU]) - { - if (nodeV->color == WHITE) - { - nodeV->parent = nodeU; - this->DepthFirstSearch(nodeV); - } - else if (nodeV->color == GRAY) - { - this->_hasCycle = true; - return; - } - } - nodeU->color = BLACK; - this->_time++; - nodeU->finishingTime = this->_time; - this->_topologicalSortedNodeList.push_front(nodeU); - } - - void Graph::PushDirectedEdge(int valueU, int valueV) - { - Node* nodeU = this->MakeOrFindNode(valueU); - Node* nodeV = this->MakeOrFindNode(valueV); - - this->_adjlist[nodeU].push_back(nodeV); - nodeV->inDegree++; - } - - void Graph::PushSingleNode(int valueU) - { - this->MakeOrFindNode(valueU); - } - - void Graph::TopologicalSort() - { - this->_time = 0; - for (auto& iterator : this->_nodeMap) - { - if (iterator.second->color == WHITE) - { - this->DepthFirstSearch(iterator.second); - if (this->_hasCycle == true) - { - break; - } - } - } - } - - void Graph::KahnTopologicalSort() - { - // Step-1 Compute in-degree of each vertices - // This is already done while creating the graph - this->_time = 0; - queue nodeQueue; - - // Step-2 Enqueue vertices with in-degree 0 - for (auto& node : this->_nodeMap) - { - if (node.second->inDegree == 0) - { - this->_time++; - node.second->discoveryTime = this->_time; - nodeQueue.push(node.second); - } - } - - // Step-3 Process vertices in queue - while (!nodeQueue.empty()) - { - Node* node = nodeQueue.front(); - nodeQueue.pop(); - this->_time++; - node->finishingTime = this->_time; - this->_topologicalSortedNodeList.push_back(node); - - // Step-4 Process all the neighbours of current node based on in-degree - for (auto& neighbour : this->_adjlist[node]) - { - neighbour->inDegree--; - if (neighbour->inDegree == 0) - { - this->_time++; - neighbour->discoveryTime = this->_time; - nodeQueue.push(neighbour); - } - } - } - - // Step-5 Check if a cycle exists - if (this->_topologicalSortedNodeList.size() != this->_nodeMap.size()) - { - this->_hasCycle = true; - } - } - - vector>> Graph::ShowTopologicalSortResult() - { - if (this->_hasCycle == true) - { - return {}; - } - vector>> result; - for (auto& node : this->_topologicalSortedNodeList) - { - result.push_back(make_pair(node->data, make_pair(node->discoveryTime, node->finishingTime))); - } - return result; - } -} \ No newline at end of file diff --git a/src/0003_graph/0004_StronglyConnectedComponents.cc b/src/0003_graph/0004_StronglyConnectedComponents.cc deleted file mode 100644 index 7a99e34..0000000 --- a/src/0003_graph/0004_StronglyConnectedComponents.cc +++ /dev/null @@ -1,121 +0,0 @@ -#include "0004_StronglyConnectedComponents.h" -#include -#include -#include -using namespace std; - -namespace StronglyConnectedComponents -{ - Node::Node(int value) - { - this->data = value; - this->discoveryTime = INT_MAX; - this->finishingTime = INT_MAX; - this->color = WHITE; - this->parent = nullptr; - } - - Node* Graph::MakeOrFindNode(int value) - { - Node* node = nullptr; - if (this->_nodeMap.find(value) == this->_nodeMap.end()) - { - node = new Node(value); - this->_nodeMap[value] = node; - } - else - { - node = this->_nodeMap[value]; - } - return node; - } - - void Graph::DepthFirstSearchOnGraphG(Node* nodeU) - { - this->_time++; - nodeU->discoveryTime = this->_time; - nodeU->color = GRAY; - for (auto nodeV : this->_adjlistG[nodeU]) - { - if (nodeV->color == WHITE) - { - nodeV->parent = nodeU; - this->DepthFirstSearchOnGraphG(nodeV); - } - } - nodeU->color = BLACK; - this->_time++; - nodeU->finishingTime = this->_time; - this->_nodesFinishingTimeOrder.push_front(nodeU); - } - - void Graph::DepthFirstSearchOnGraphT(Node* nodeU, vector& connectedComponents) - { - nodeU->color = GRAY; - connectedComponents.push_back(nodeU->data); - for (auto nodeV : this->_adjlistT[nodeU]) - { - if (nodeV->color == WHITE) - { - nodeV->parent = nodeU; - this->DepthFirstSearchOnGraphT(nodeV, connectedComponents); - } - } - nodeU->color = BLACK; - } - - void Graph::PushDirectedEdge(int valueU, int valueV) - { - Node* nodeU = this->MakeOrFindNode(valueU); - Node* nodeV = this->MakeOrFindNode(valueV); - - // Creating the actual graph. - this->_adjlistG[nodeU].push_back(nodeV); - - // Creating the transpose of the actual graph. - this->_adjlistT[nodeV].push_back(nodeU); - } - - void Graph::PushSingleNode(int valueU) - { - this->MakeOrFindNode(valueU); - } - - void Graph::DFSOnGraphG() - { - this->_time = 0; - for (auto& iterator : this->_nodeMap) - { - if (iterator.second->color == WHITE) - { - this->DepthFirstSearchOnGraphG(iterator.second); - } - } - } - - void Graph::DFSOnGraphT() - { - for (auto& iterator : this->_nodeMap) - { - iterator.second->color = WHITE; - iterator.second->parent = nullptr; - } - - for (auto& iterator : this->_nodesFinishingTimeOrder) - { - if (iterator->color == WHITE) - { - vector connectedComponents; - this->DepthFirstSearchOnGraphT(iterator, connectedComponents); - this->_allConnectedComponents.push_back(connectedComponents); - } - } - } - - vector> Graph::FindAllStronglyConnectedComponents() - { - this->DFSOnGraphG(); - this->DFSOnGraphT(); - return this->_allConnectedComponents; - } -} \ No newline at end of file diff --git a/src/0003_graph/0005_HamiltonianPathAndCycle.cc b/src/0003_graph/0005_HamiltonianPathAndCycle.cc deleted file mode 100644 index bfa99b5..0000000 --- a/src/0003_graph/0005_HamiltonianPathAndCycle.cc +++ /dev/null @@ -1,114 +0,0 @@ -#include "0005_HamiltonianPathAndCycle.h" - -using namespace std; -namespace HamiltonianPathAndCycle -{ - Node::Node(int value) - { - this->data = value; - this->isVisited = false; - } - - // Graph Private Member Methods - Node* Graph::MakeOrFindNode(int value) - { - Node* node = nullptr; - if (this->_nodeMap.find(value) == this->_nodeMap.end()) - { - node = new Node(value); - this->_nodeMap[value] = node; - } - else - { - node = this->_nodeMap[value]; - } - return node; - } - - bool Graph::IsSafe(Node* nodeU, Node* nodeV) - { - if (this->_adjlist[nodeU].find(nodeV) == this->_adjlist[nodeU].end()) - { - return false; - } - if (nodeV->isVisited == true) - { - return false; - } - return true; - } - - bool Graph::HamiltonianCycleAndPathUtil(Node* nodeU) - { - if (this->_visitedNodeCount == this->_nodeMap.size()) - { - if (this->_adjlist[nodeU].find(this->_startingNode) != this->_adjlist[nodeU].end()) - { - this->_isHamiltonianCyclePresent = true; - this->_isHamiltonianPathPresent = true; - return true; - } - this->_isHamiltonianPathPresent = true; - return false; - } - for (auto& nodeV : this->_adjlist[nodeU]) - { - if (this->IsSafe(nodeU, nodeV)) - { - this->_hamiltonianPath.push_back(nodeV->data); - nodeV->isVisited = true; - this->_visitedNodeCount++; - if (this->HamiltonianCycleAndPathUtil(nodeV)) - { - return true; - } - this->_visitedNodeCount--; - nodeV->isVisited = false; - this->_hamiltonianPath.pop_back(); - } - } - return false; - } - - // Graph Public Member Methods - void Graph::PushUndirectedEdge(int valueU, int valueV) - { - Node* nodeU = this->MakeOrFindNode(valueU); - Node* nodeV = this->MakeOrFindNode(valueV); - - this->_adjlist[nodeU].insert(nodeV); - this->_adjlist[nodeV].insert(nodeU); - } - - void Graph::PushSingleNode(int valueU) - { - this->MakeOrFindNode(valueU); - } - - void Graph::FindHamiltonianCycleAndPath() - { - this->_isHamiltonianCyclePresent = false; - this->_isHamiltonianPathPresent = false; - this->_hamiltonianPath = {}; - this->_startingNode = this->_nodeMap[0]; - this->_hamiltonianPath.push_back(this->_startingNode->data); - this->_startingNode->isVisited = true; - this->_visitedNodeCount = 1; - this->HamiltonianCycleAndPathUtil(this->_startingNode); - } - - bool Graph::IsHamiltonianCyclePresent() - { - return this->_isHamiltonianCyclePresent; - } - - bool Graph::IsHamiltonianPathPresent() - { - return this->_isHamiltonianPathPresent; - } - - vector Graph::GetHamiltonianPath() - { - return this->_hamiltonianPath; - } -} \ No newline at end of file diff --git a/src/0003_graph/0006_EulerianPathAndCircuit.cc b/src/0003_graph/0006_EulerianPathAndCircuit.cc deleted file mode 100644 index ee132ca..0000000 --- a/src/0003_graph/0006_EulerianPathAndCircuit.cc +++ /dev/null @@ -1,212 +0,0 @@ -#include "0006_EulerianPathAndCircuit.h" -#include -#include -using namespace std; - -namespace EulerianPathAndCircuit -{ - Node::Node(int value) - { - this->data = value; - this->degree = 0; - this->inDegree = 0; - this->outDegree = 0; - this->visited = false; - } - - // Graph Private Member Methods - Node* Graph::MakeOrFindNode(int value) - { - Node* node = nullptr; - if (this->_nodeMap.find(value) == this->_nodeMap.end()) - { - node = new Node(value); - this->_nodeMap[value] = node; - } - else - { - node = this->_nodeMap[value]; - } - return node; - } - - void Graph::DepthFirstSearch(Node* nodeU) - { - nodeU->visited = true; - for (auto& nodeV : this->_adjlist[nodeU]) - { - if (nodeV->visited == false) - { - this->DepthFirstSearch(nodeV); - } - } - } - - bool Graph::IsConnected() - { - // Step-1 : Make the visited property of all nodes as false. It is already done in constructor. - - // Step-2 : Find a node which do not have 0 degree. - Node* node = nullptr; - for (auto& iterator : this->_nodeMap) - { - if (iterator.second->degree != 0) - { - node = iterator.second; - break; - } - } - - // Step-3 : If node is null, it means G.E is null, so G is connected, else call DFS to traverse the graph G. - if (node == nullptr) - { - return true; - } - - this->DepthFirstSearch(node); - - // Step-4 : Checking if all the non-zero degree vertices have been visited or not. - for (auto& iterator : this->_nodeMap) - { - if (iterator.second->visited == false && iterator.second->degree != 0) - { - return false; - } - } - return true; - } - - void Graph::EulerianPathHierholzerAlgorithm(Node* startingNode) - { - stack currentPath; - currentPath.push(startingNode); - while (!currentPath.empty()) - { - Node* currentNode = currentPath.top(); - if (!this->_adjlist[currentNode].empty()) - { - Node* nextNode = this->_adjlist[currentNode].front(); - this->_adjlist[currentNode].pop_front(); - this->_adjlist[nextNode].remove(currentNode); - currentPath.push(nextNode); - } - else - { - currentPath.pop(); - this->_eulerianPath.push_back(currentNode->data); - } - } - } - - // Graph Public Member Methods - void Graph::PushUndirectedEdge(int valueU, int valueV) - { - Node* nodeU = this->MakeOrFindNode(valueU); - Node* nodeV = this->MakeOrFindNode(valueV); - - this->_adjlist[nodeU].push_back(nodeV); - nodeU->degree++; - this->_adjlist[nodeV].push_back(nodeU); - nodeV->degree++; - } - - void Graph::PushDirectedEdge(int valueU, int valueV) - { - Node* nodeU = this->MakeOrFindNode(valueU); - Node* nodeV = this->MakeOrFindNode(valueV); - - this->_adjlist[nodeU].push_back(nodeV); - nodeU->outDegree++; - nodeV->inDegree++; - } - - void Graph::PushSingleNode(int valueU) - { - this->MakeOrFindNode(valueU); - } - - void Graph::FindEulerianPathAndCircuit() - { - // If the graph is not connected then graph G is Not-Eulerian. - if (this->IsConnected() == false) - { - this->_isEulerianPathPresent = false; - this->_isEulerianCircuitPresent = false; - return; - } - - int oddDegreeVertexCount = 0; - for (auto& iterator : this->_nodeMap) - { - if (iterator.second->degree & 1) - { - oddDegreeVertexCount++; - } - } - - // Check-1 : When no vertex with odd degree is present, then graph G is Eulerian. - if (oddDegreeVertexCount == 0) - { - this->_isEulerianPathPresent = true; - this->_isEulerianCircuitPresent = true; - return; - } - - // Check-2 : When 2 vertices have odd degree, then graph G is Semi-Eulerian. - if (oddDegreeVertexCount == 2) - { - this->_isEulerianPathPresent = true; - this->_isEulerianCircuitPresent = false; - return; - } - - // Check-3 : When more than 2 vertices have odd degree, then graph G is Not Eulerian. - if (oddDegreeVertexCount > 2) - { - this->_isEulerianPathPresent = false; - this->_isEulerianCircuitPresent = false; - return; - } - } - - bool Graph::IsEulerianPathPresent() - { - return this->_isEulerianPathPresent; - } - - bool Graph::IsEulerianCircuitPresent() - { - return this->_isEulerianCircuitPresent; - } - - vector Graph::UndirectedGraphGetEulerianPath() - { - // Case-3 : When more than 2 vertices have odd degree, then the graph G is not Eulerian. - // No Eulerian Path is posible. - if (this->_isEulerianPathPresent == false) - { - return {}; - } - - // Now 2 cases remains. - // Case-2 : When 2 vertices have odd degree. Choose any one of them. - Node* node = nullptr; - for (auto& iterator : this->_nodeMap) - { - if (iterator.second->degree & 1) - { - node = iterator.second; - break; - } - } - - // Case-1 : When no vertex with odd degree is present. Choose any vertex as starting point. - if (node == nullptr) - { - node = this->_nodeMap[0]; - } - this->EulerianPathHierholzerAlgorithm(node); - reverse(this->_eulerianPath.begin(), this->_eulerianPath.end()); - return this->_eulerianPath; - } -} \ No newline at end of file diff --git a/src/0003_graph/0007_MinimumSpanningTreeKruskalAlgorithm.cc b/src/0003_graph/0007_MinimumSpanningTreeKruskalAlgorithm.cc deleted file mode 100644 index 20bea2b..0000000 --- a/src/0003_graph/0007_MinimumSpanningTreeKruskalAlgorithm.cc +++ /dev/null @@ -1,108 +0,0 @@ -#include "0007_MinimumSpanningTreeKruskalAlgorithm.h" -#include -#include -using namespace std; - -namespace MinimumSpanningTreeKruskalAlgorithm -{ - Node::Node(int data) - { - this->data = data; - this->parent = nullptr; - this->rank = INT_MAX; - } - - Edge::Edge(Node* nodeU, Node* nodeV, int weight) - { - this->nodeU = nodeU; - this->nodeV = nodeV; - this->weight = weight; - } - - // Graph Private Member Methods - Node* Graph::MakeOrFindNode(int data) - { - Node* node = nullptr; - if (this->_nodeMap.find(data) == this->_nodeMap.end()) - { - node = new Node(data); - this->_nodeMap[data] = node; - } - else - { - node = this->_nodeMap[data]; - } - return node; - } - - void Graph::MakeSet(Node* node) - { - node->parent = node; - node->rank = 0; - } - - void Graph::Union(Node* nodeU, Node* nodeV) - { - this->Link(this->FindSet(nodeU), this->FindSet(nodeV)); - } - - void Graph::Link(Node* nodeU, Node* nodeV) - { - if (nodeV->rank > nodeU->rank) - { - nodeU->parent = nodeV; - } - else - { - nodeV->parent = nodeU; - if (nodeU->rank == nodeV->rank) - { - nodeU->rank += 1; - } - } - } - - Node* Graph::FindSet(Node* node) - { - if (node != node->parent) - { - node->parent = this->FindSet(node->parent); - } - return node->parent; - } - - // Graph Public Member Methods - void Graph::PushUndirectedEdge(int dataU, int dataV, int weight) - { - Node* nodeU = this->MakeOrFindNode(dataU); - Node* nodeV = this->MakeOrFindNode(dataV); - - this->_adjlist[nodeU].push_back(nodeV); - this->_adjlist[nodeV].push_back(nodeU); - this->_edgeList.push_back(new Edge(nodeU, nodeV, weight)); - } - - void Graph::FindMinimumSpanningTreeKruskalAlgorithm() - { - for (auto& iterator : this->_nodeMap) - { - this->MakeSet(iterator.second); - } - - sort(this->_edgeList.begin(), this->_edgeList.end(), [](Edge* edgeX, Edge* edgeY) { return edgeX->weight < edgeY->weight; }); - - for (auto& edge : this->_edgeList) - { - if (this->FindSet(edge->nodeU) != this->FindSet(edge->nodeV)) - { - this->Union(edge->nodeU, edge->nodeV); - this->_minimumSpanningTree.push_back({ {edge->nodeU->data, edge->nodeV->data}, edge->weight }); - } - } - } - - vector, int>> Graph::GetMinimumSpanningTree() - { - return this->_minimumSpanningTree; - } -} \ No newline at end of file diff --git a/src/0003_graph/0008_MinimumSpanningTreePrimAlgorithm.cc b/src/0003_graph/0008_MinimumSpanningTreePrimAlgorithm.cc deleted file mode 100644 index 1b36027..0000000 --- a/src/0003_graph/0008_MinimumSpanningTreePrimAlgorithm.cc +++ /dev/null @@ -1,85 +0,0 @@ -#include "0008_MinimumSpanningTreePrimAlgorithm.h" -#include -using namespace std; - - -namespace MinimumSpanningTreePrimAlgorithm -{ - Node::Node(int data) - { - this->data = data; - this->parent = nullptr; - this->key = INT_MAX; - this->isInOperationalSet = false; - } - - // Graph Private Member Methods - Node* Graph::MakeOrFindNode(int data) - { - Node* node = nullptr; - if (this->_nodeMap.find(data) == this->_nodeMap.end()) - { - node = new Node(data); - this->_nodeMap[data] = node; - } - else - { - node = this->_nodeMap[data]; - } - return node; - } - - // Graph Public Member Methods - void Graph::PushUndirectedEdge(int dataU, int dataV, int weight) - { - Node* nodeU = this->MakeOrFindNode(dataU); - Node* nodeV = this->MakeOrFindNode(dataV); - - this->_adjlist[nodeU].push_back({nodeV, weight}); - this->_adjlist[nodeV].push_back({nodeU, weight}); - } - - void Graph::FindMinimumSpanningTreePrimAlgorithm() - { - Node* root = this->_nodeMap.begin()->second; - - root->key = 0; - for (auto& iterator : this->_nodeMap) - { - iterator.second->isInOperationalSet = true; - this->_operationalSet.insert(iterator.second); - } - - while (!this->_operationalSet.empty()) - { - Node* nodeU = *(this->_operationalSet.begin()); - this->_operationalSet.erase(nodeU); - nodeU->isInOperationalSet = false; - - for (auto& iterator : this->_adjlist[nodeU]) - { - Node* nodeV = iterator.first; - int weight = iterator.second; - - if (nodeV->isInOperationalSet && weight < nodeV->key) - { - this->_operationalSet.erase(nodeV); - nodeV->key = weight; - nodeV->parent = nodeU; - this->_operationalSet.insert(nodeV); - - } - } - - if (nodeU->parent != nullptr) - { - this->_minimumSpanningTree.push_back({ {nodeU->parent->data, nodeU->data}, nodeU->key }); - } - } - } - - vector, int>> Graph::GetMinimumSpanningTree() - { - return this->_minimumSpanningTree; - } -} \ No newline at end of file diff --git a/src/0003_graph/0009_SingleSourceShortestPathBellmanFord.cc b/src/0003_graph/0009_SingleSourceShortestPathBellmanFord.cc deleted file mode 100644 index b059b74..0000000 --- a/src/0003_graph/0009_SingleSourceShortestPathBellmanFord.cc +++ /dev/null @@ -1,108 +0,0 @@ -#include "0009_SingleSourceShortestPathBellmanFord.h" -#include -#include -using namespace std; - -namespace SingleSourceShortestPathBellmanFord -{ - Node::Node(int data) - { - this->data = data; - this->distance = INT_MAX; - this->parent = nullptr; - } - - Edge::Edge(Node* nodeU, Node* nodeV, int weight) - { - this->nodeU = nodeU; - this->nodeV = nodeV; - this->weight = weight; - } - - // Graph Private Member Methods - Node* Graph::MakeOrFindNode(int data) - { - Node* node = nullptr; - if (this->_nodeMap.find(data) == this->_nodeMap.end()) - { - node = new Node(data); - this->_nodeMap[data] = node; - } - else - { - node = this->_nodeMap[data]; - } - return node; - } - - void Graph :: InitializeSingleSource(Node* sourceNode) - { - for (auto& iterator : this->_nodeMap) - { - iterator.second->distance = INT_MAX; - iterator.second->parent = nullptr; - } - sourceNode->distance = 0; - } - - void Graph::Relax(Edge* edge) - { - if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) - { - edge->nodeV->distance = edge->nodeU->distance + edge->weight; - edge->nodeV->parent = edge->nodeU; - } - } - - void Graph::GetShortestPath(Node* node, vector& path) - { - path.push_back(node->data); - if (node->parent != nullptr) - { - this->GetShortestPath(node->parent, path); - } - } - - // Graph Public Member Methods - void Graph::PushDirectedEdge(int dataU, int dataV, int weight) - { - Node* nodeU = this->MakeOrFindNode(dataU); - Node* nodeV = this->MakeOrFindNode(dataV); - - this->_adjlist[nodeU].push_back(nodeV); - this->_edgeList.push_back(new Edge(nodeU, nodeV, weight)); - } - - bool Graph::FindSingleSourceShortestPathBellmanFord(int data) - { - Node* source = this->_nodeMap[data]; - - this->InitializeSingleSource(source); - - for (int i = 0; i < this->_nodeMap.size() - 1; i++) - { - for (auto& edge : this->_edgeList) - { - this->Relax(edge); - } - } - - for (auto& edge : this->_edgeList) - { - if (edge->nodeV->distance > (edge->nodeU->distance + edge->weight)) - { - return false; - } - } - return true; - } - - vector Graph::GetShortestPathBellmanFord(int data) - { - vector path = {}; - Node* node = this->_nodeMap[data]; - this->GetShortestPath(node, path); - reverse(path.begin(), path.end()); - return path; - } -} \ No newline at end of file diff --git a/src/0003_graph/0010_DirectedAcyclicGraphShortestPath.cc b/src/0003_graph/0010_DirectedAcyclicGraphShortestPath.cc deleted file mode 100644 index 8f4cd81..0000000 --- a/src/0003_graph/0010_DirectedAcyclicGraphShortestPath.cc +++ /dev/null @@ -1,124 +0,0 @@ -#include "0010_DirectedAcyclicGraphShortestPath.h" -#include -#include -using namespace std; - -namespace DirectedAcyclicGraphShortestPath -{ - Node::Node(int data) - { - this->data = data; - this->color = WHITE; - this->distance = INT_MAX; - this->parent = nullptr; - } - - Edge::Edge(Node* nodeU, Node* nodeV, int weight) - { - this->nodeU = nodeU; - this->nodeV = nodeV; - this->weight = weight; - } - - // Graph Private Member Methods - Node* Graph::MakeOrFindNode(int data) - { - Node* node = nullptr; - if (this->_nodeMap.find(data) == this->_nodeMap.end()) - { - node = new Node(data); - this->_nodeMap[data] = node; - } - else - { - node = this->_nodeMap[data]; - } - return node; - } - - void Graph::DepthFirstSearch(Node* nodeU) - { - nodeU->color = GRAY; - for (auto& nodeV : this->_adjlist[nodeU]) - { - if (nodeV->color == WHITE) - { - this->DepthFirstSearch(nodeV); - } - } - nodeU->color = BLACK; - this->_topologicalSortedNodeList.push_front(nodeU); - } - - void Graph::TopologicalSort() - { - for (auto& iterator : this->_nodeMap) - { - if (iterator.second->color == WHITE) - { - this->DepthFirstSearch(iterator.second); - } - } - } - - void Graph::InitializeSingleSource(Node* sourceNode) - { - for (auto& iterator : this->_nodeMap) - { - iterator.second->distance = INT_MAX; - iterator.second->parent = nullptr; - } - sourceNode->distance = 0; - } - - void Graph::Relax(Edge* edge) - { - if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) - { - edge->nodeV->distance = edge->nodeU->distance + edge->weight; - edge->nodeV->parent = edge->nodeU; - } - } - - void Graph::GetShortestPath(Node* node, vector& path) - { - path.push_back(node->data); - if (node->parent != nullptr) - { - this->GetShortestPath(node->parent, path); - } - } - - // Graph Public Member Methods - void Graph::PushDirectedEdge(int dataU, int dataV, int weight) - { - Node* nodeU = this->MakeOrFindNode(dataU); - Node* nodeV = this->MakeOrFindNode(dataV); - - this->_adjlist[nodeU].push_back(nodeV); - this->_edgeMap[nodeU].push_back(new Edge(nodeU, nodeV, weight)); - } - - void Graph::FindDAGShortestPath(int data) - { - this->TopologicalSort(); - Node* source = this->_nodeMap[data]; - this->InitializeSingleSource(source); - for (auto& node : this->_topologicalSortedNodeList) - { - for (auto& edge : this->_edgeMap[node]) - { - this->Relax(edge); - } - } - } - - vector Graph::GetDAGShortestPath(int data) - { - vector path = {}; - Node* node = this->_nodeMap[data]; - this->GetShortestPath(node, path); - reverse(path.begin(), path.end()); - return path; - } -} \ No newline at end of file diff --git a/src/0003_graph/0011_SingleSourceShortestPathDijkstra.cc b/src/0003_graph/0011_SingleSourceShortestPathDijkstra.cc deleted file mode 100644 index e796e37..0000000 --- a/src/0003_graph/0011_SingleSourceShortestPathDijkstra.cc +++ /dev/null @@ -1,113 +0,0 @@ -#include "0011_SingleSourceShortestPathDijkstra.h" -#include -#include -using namespace std; - -namespace SingleSourceShortestPathDijkstra -{ - Node::Node(int data) - { - this->data = data; - this->distance = INT_MAX; - this->parent = nullptr; - } - - Edge::Edge(Node* nodeU, Node* nodeV, int weight) - { - this->nodeU = nodeU; - this->nodeV = nodeV; - this->weight = weight; - } - - // Graph Private Member Methods - Node* Graph::MakeOrFindNode(int data) - { - Node* node = nullptr; - if (this->_nodeMap.find(data) == this->_nodeMap.end()) - { - node = new Node(data); - this->_nodeMap[data] = node; - } - else - { - node = this->_nodeMap[data]; - } - return node; - } - - void Graph::InitializeSingleSource(Node* sourceNode) - { - for (auto& iterator : this->_nodeMap) - { - iterator.second->distance = INT_MAX; - iterator.second->parent = nullptr; - } - sourceNode->distance = 0; - } - - void Graph::Relax(Edge* edge) - { - if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) - { - this->_operationalSet.erase(edge->nodeV); - edge->nodeV->distance = edge->nodeU->distance + edge->weight; - edge->nodeV->parent = edge->nodeU; - this->_operationalSet.insert(edge->nodeV); - } - } - - void Graph::Dijkstra(Node* source) - { - this->InitializeSingleSource(source); - - for (auto& node : this->_nodeMap) - { - this->_operationalSet.insert(node.second); - } - - while (!this->_operationalSet.empty()) - { - Node* nodeU = *(this->_operationalSet.begin()); - this->_operationalSet.erase(nodeU); - - for (auto& edge : this->_edgeMap[nodeU]) - { - this->Relax(edge); - } - } - } - - void Graph::GetShortestPath(Node* node, vector& path) - { - path.push_back(node->data); - if (node->parent != nullptr) - { - this->GetShortestPath(node->parent, path); - } - } - - // Graph Public Member Methods - void Graph::PushDirectedEdge(int dataU, int dataV, int weight) - { - Node* nodeU = this->MakeOrFindNode(dataU); - Node* nodeV = this->MakeOrFindNode(dataV); - - this->_adjlist[nodeU].push_back(nodeV); - this->_edgeMap[nodeU].push_back(new Edge(nodeU, nodeV, weight)); - } - - void Graph::FindShortestPathDijkstra(int data) - { - Node* source = this->_nodeMap[data]; - this->Dijkstra(source); - } - - vector Graph::GetDijkstraShortestPath(int data) - { - vector path = {}; - Node* node = this->_nodeMap[data]; - this->GetShortestPath(node, path); - reverse(path.begin(), path.end()); - return path; - } -} \ No newline at end of file diff --git a/src/0003_graph/0012_DifferenceConstraintsShortestPaths.cc b/src/0003_graph/0012_DifferenceConstraintsShortestPaths.cc deleted file mode 100644 index 8764ba6..0000000 --- a/src/0003_graph/0012_DifferenceConstraintsShortestPaths.cc +++ /dev/null @@ -1,133 +0,0 @@ -#include "0012_DifferenceConstraintsShortestPaths.h" -#include -using namespace std; - -namespace DifferenceConstraintsShortestPaths -{ - Node::Node(string data) - { - this->data = data; - this->distance = INT_MAX; - } - - Edge::Edge(Node* nodeU, Node* nodeV, int weight) - { - this->nodeU = nodeU; - this->nodeV = nodeV; - this->weight = weight; - } - - // Graph Private Member Methods - Node* Graph::MakeOrFindNode(string data) - { - Node* node = nullptr; - if (this->_nodeMap.find(data) == this->_nodeMap.end()) - { - node = new Node(data); - this->_nodeMap[data] = node; - } - else - { - node = this->_nodeMap[data]; - } - return node; - } - - void Graph::PushDirectedEdge(string dataU, string dataV, int weight) - { - Node* nodeU = this->MakeOrFindNode(dataU); - Node* nodeV = this->MakeOrFindNode(dataV); - - this->_adjlist[nodeU].push_back(nodeV); - this->_edgeList.push_back(new Edge(nodeU, nodeV, weight)); - } - - void Graph::InitializeSingleSource(Node* sourceNode) - { - for (auto& iterator : this->_nodeMap) - { - iterator.second->distance = INT_MAX; - } - sourceNode->distance = 0; - } - - void Graph::Relax(Edge* edge) - { - if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) - { - edge->nodeV->distance = edge->nodeU->distance + edge->weight; - } - } - - // Graph Public Member Methods - void Graph::PushAllDirectedEdges(vector> vectorA, vector vectorX, vector vectorB) - { - // Creating the Actual Graph - string valueU = ""; - string valueV = ""; - int weight = 0; - for (int i = 0; i < vectorA.size(); i++) - { - for (int j = 0; j < vectorX.size(); j++) - { - if (vectorA[i][j] == 1) - { - valueV= vectorX[j]; - } - if (vectorA[i][j] == -1) - { - valueU = vectorX[j]; - } - } - weight = vectorB[i]; - this->PushDirectedEdge(valueU, valueV, weight); - } - - // Creating all the edges from the additional vertex - valueU = ""; - valueV = ""; - weight = 0; - for (int i = 0; i < vectorX.size(); i++) - { - valueV = vectorX[i]; - this->PushDirectedEdge(valueU, valueV, weight); - } - } - - bool Graph::FindDifferenceConstraintsSolutionBellmanFord() - { - Node* source = this->_nodeMap[""]; - - this->InitializeSingleSource(source); - - for (int i = 0; i < this->_nodeMap.size(); i++) - { - for (auto& edge : this->_edgeList) - { - this->Relax(edge); - } - } - - for (auto& edge : this->_edgeList) - { - if (edge->nodeV->distance > (edge->nodeU->distance + edge->weight)) - { - return false; - } - } - return true; - } - - vector> Graph::GetDifferenceConstrtaintsSolution() - { - vector> result; - for (auto& node : this->_nodeMap) - { - if (node.second->data != "") - { - result.push_back({ node.second->data, node.second->distance }); - } - } - return result; - } -} \ No newline at end of file diff --git a/src/0003_graph/0013_AllPairsShortestPathsFloydWarshall.cc b/src/0003_graph/0013_AllPairsShortestPathsFloydWarshall.cc deleted file mode 100644 index ffd51d9..0000000 --- a/src/0003_graph/0013_AllPairsShortestPathsFloydWarshall.cc +++ /dev/null @@ -1,104 +0,0 @@ -#include "0013_AllPairsShortestPathsFloydWarshall.h" -#include -using namespace std; - -namespace AllPairsShortestPathsFloydWarshall -{ - // Graph Private Member Methods - void Graph::InitializeDistanceAndPredecessors() - { - this->_shortestPathMatrixFloydWarshall = this->_adjMatrix; - - for (int i = 0; i < this->_noOfVertices; i++) - { - for (int j = 0; j < this->_noOfVertices; j++) - { - if ((i == j) || this->_adjMatrix[i][j] == INT_MAX) - { - this->_predecessorMatrix[i][j] = -1; - } - else - { - this->_predecessorMatrix[i][j] = i + 1; - } - } - } - } - - void Graph::GetShortestPath(int source, int destination, vector& path) - { - if (this->_predecessorMatrix[source - 1][destination - 1] != source) - { - int predecessor = this->_predecessorMatrix[source - 1][destination - 1]; - this->GetShortestPath(source, predecessor, path); - path.push_back(predecessor); - } - } - - // Graph Public Member Methods - void Graph::CreateGraph(int noOfVertices) - { - this->_noOfVertices = noOfVertices; - this->_adjMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, INT_MAX)); - this->_shortestPathMatrixFloydWarshall = vector>(this->_noOfVertices, vector(this->_noOfVertices, INT_MAX)); - this->_predecessorMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, INT_MAX)); - - for (int i = 0; i < this->_noOfVertices; i++) - { - for (int j = 0; j < this->_noOfVertices; j++) - { - if (i == j) - { - this->_adjMatrix[i][j] = 0; - } - } - } - } - - void Graph::PushDirectedEdge(int valueU, int valueV, int weight) - { - this->_adjMatrix[valueU - 1][valueV - 1] = weight; - } - - void Graph::FindAllPairsShortestPathsFloydWarshallSolution() - { - this->InitializeDistanceAndPredecessors(); - - for (int k = 0; k < this->_noOfVertices; k++) - { - for (int i = 0; i < this->_noOfVertices; i++) - { - for (int j = 0; j < this->_noOfVertices; j++) - { - if ((this->_shortestPathMatrixFloydWarshall[i][j] > (this->_shortestPathMatrixFloydWarshall[i][k] + this->_shortestPathMatrixFloydWarshall[k][j])) - && - (this->_shortestPathMatrixFloydWarshall[i][k] != INT_MAX && this->_shortestPathMatrixFloydWarshall[k][j] != INT_MAX)) - { - this->_shortestPathMatrixFloydWarshall[i][j] = this->_shortestPathMatrixFloydWarshall[i][k] + this->_shortestPathMatrixFloydWarshall[k][j]; - this->_predecessorMatrix[i][j] = this->_predecessorMatrix[k][j]; - } - } - } - } - } - - vector> Graph::GetFloydWarshallShortestPath() - { - vector> result; - for (int i = 0; i < this->_noOfVertices; i++) - { - for (int j = 0; j < this->_noOfVertices; j++) - { - if (i != j) - { - vector path = {}; - path.push_back(i + 1); - this->GetShortestPath(i + 1, j + 1, path); - path.push_back(j + 1); - result.push_back(path); - } - } - } - return result; - } -} \ No newline at end of file diff --git a/src/0003_graph/0014_AllPairsShortestPathsJohnson.cc b/src/0003_graph/0014_AllPairsShortestPathsJohnson.cc deleted file mode 100644 index e9f9ab2..0000000 --- a/src/0003_graph/0014_AllPairsShortestPathsJohnson.cc +++ /dev/null @@ -1,217 +0,0 @@ -#include "0014_AllPairsShortestPathsJohnson.h" -#include -using namespace std; - -namespace AllPairsShortestPathsJohnson -{ - Node::Node(int data) - { - this->data = data; - this->distance = INT_MAX; - this->parent = nullptr; - this->potentialWeight = 0; - } - - Edge::Edge(Node* nodeU, Node* nodeV, int weight) - { - this->nodeU = nodeU; - this->nodeV = nodeV; - this->weight = weight; - } - - // Graph Private Member Methods - Node* Graph::MakeOrFindNode(int data) - { - Node* node = nullptr; - if (this->_nodeMap.find(data) == this->_nodeMap.end()) - { - node = new Node(data); - this->_nodeMap[data] = node; - } - else - { - node = this->_nodeMap[data]; - } - return node; - } - - void Graph::PushAugmentedDirectedEdges(Node* sourceNode, Node* nodeV, int weight) - { - this->_augmentedAdjlist[sourceNode].push_back(nodeV); - this->_augmentedEdgeList.push_back(new Edge(sourceNode, nodeV, weight)); - } - - void Graph::InitializeSingleSource(Node* sourceNode) - { - for (auto& iterator : this->_nodeMap) - { - iterator.second->distance = INT_MAX; - iterator.second->parent = nullptr; - } - sourceNode->distance = 0; - } - - void Graph::RelaxBellmanFord(Edge* edge) - { - if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) - { - edge->nodeV->distance = edge->nodeU->distance + edge->weight; - edge->nodeV->parent = edge->nodeU; - } - } - - bool Graph::BellmanFord(Node* source) - { - this->InitializeSingleSource(source); - - for (int i = 0; i < this->_nodeMap.size() - 1; i++) - { - for (auto& edge : this->_augmentedEdgeList) - { - this->RelaxBellmanFord(edge); - } - } - - for (auto& edge : this->_augmentedEdgeList) - { - if (edge->nodeV->distance > (edge->nodeU->distance + edge->weight)) - { - return false; - } - } - return true; - } - - void Graph::RelaxDijkstra(Edge* edge) - { - if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) - { - this->_operationalSet.erase(edge->nodeV); - edge->nodeV->distance = edge->nodeU->distance + edge->weight; - edge->nodeV->parent = edge->nodeU; - this->_operationalSet.insert(edge->nodeV); - } - } - - void Graph::Dijkstra(Node* source) - { - this->InitializeSingleSource(source); - - for (auto& node : this->_nodeMap) - { - this->_operationalSet.insert(node.second); - } - - while (!this->_operationalSet.empty()) - { - Node* nodeU = *(this->_operationalSet.begin()); - this->_operationalSet.erase(nodeU); - - for (auto& edge : this->_edgeMap[nodeU]) - { - this->RelaxDijkstra(edge); - } - } - } - - void Graph::GetShortestPath(int source, int destination, vector& path) - { - if (this->_predecessorMatrix[source - 1][destination - 1] != source) - { - int predecessor = this->_predecessorMatrix[source - 1][destination - 1]; - this->GetShortestPath(source, predecessor, path); - path.push_back(predecessor); - } - } - - // Graph Public Member Methods - void Graph::PushDirectedEdge(int dataU, int dataV, int weight) - { - Node* nodeU = this->MakeOrFindNode(dataU); - Node* nodeV = this->MakeOrFindNode(dataV); - - this->_adjlist[nodeU].push_back(nodeV); - Edge* edge = new Edge(nodeU, nodeV, weight); - this->_edgeMap[nodeU].push_back(edge); - this->_edgeList.push_back(edge); - } - - bool Graph::FindAllPairsShortestPathsJohnsonAlgorithm() - { - // Creating the graph G' - this->_augmentedAdjlist = this->_adjlist; - this->_augmentedEdgeList = this->_edgeList; - - // Source Node s - Node* source = new Node(0); - this->_nodeMap[0] = source; - - // Creating all the augmented edges in G'.E = G.E U {(s, v) : v in G.V - for (auto& node : this->_nodeMap) - { - if (node.second != source) - { - this->PushAugmentedDirectedEdges(source, node.second, 0); - } - } - - if (this->BellmanFord(source) == false) - { - return false; - } - else - { - this->_nodeMap.erase(0); - for (auto& node : this->_nodeMap) - { - node.second->potentialWeight = node.second->distance; - } - - for (auto& edge : this->_edgeList) - { - edge->weight = edge->weight + edge->nodeU->potentialWeight - edge->nodeV->potentialWeight; - } - - this->_noOfVertices = (int)this->_nodeMap.size(); - this->_shortestPathMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, -1)); - this->_predecessorMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, -1)); - for (auto& iteratorU : this->_nodeMap) - { - Node* nodeU = iteratorU.second; - this->Dijkstra(nodeU); - for (auto& iteratorV : this->_nodeMap) - { - Node* nodeV = iteratorV.second; - this->_shortestPathMatrix[nodeU->data - 1][nodeV->data - 1] = nodeV->distance + nodeV->potentialWeight - nodeU->potentialWeight; - this->_predecessorMatrix[nodeU->data - 1][nodeV->data - 1] = nodeV->parent != nullptr ? nodeV->parent->data : -1; - } - } - return true; - } - } - - vector> Graph::GetAllPairsShortestPathsDistanceMatrix() - { - return this->_shortestPathMatrix; - } - - vector> Graph::GetAllPairsShortestPathsPathMatrix() - { - vector> result; - for (int i = 0; i < this->_noOfVertices; i++) - { - for (int j = 0; j < this->_noOfVertices; j++) - { - if (i != j) - { - vector path = {}; - path.push_back(i + 1); - this->GetShortestPath(i + 1, j + 1, path); - path.push_back(j + 1); - result.push_back(path); - } - } - } - return result; - } -} \ No newline at end of file diff --git a/src/0003_graph/0015_MaximumFlowFordFulkerson.cc b/src/0003_graph/0015_MaximumFlowFordFulkerson.cc deleted file mode 100644 index dd8d48d..0000000 --- a/src/0003_graph/0015_MaximumFlowFordFulkerson.cc +++ /dev/null @@ -1,139 +0,0 @@ -#include "0015_MaximumFlowFordFulkerson.h" -#include -using namespace std; - -namespace MaximumFlowFordFulkerson -{ - // Graph Private Member Methods - void Graph::ResolveAntiParallelEdges() - { - int countParallelEdges = 0; - for (int i = 0; i < this->_noOfVertices; i++) - { - for (int j = 0; j < this->_noOfVertices; j++) - { - if (this->_adjMatrix[i][j] > 0 && this->_adjMatrix[j][i] > 0) - { - countParallelEdges++; - } - } - } - - // As i->j and j->i both edges has been counted, actual count is count = count / 2 - countParallelEdges /= 2; - - this->_flagParallelEdges = countParallelEdges > 0; - - // If there are no anti-parallel edges, no need to modify the adjMatrix - if (!this->_flagParallelEdges) - { - return; - } - - int newNoOfVertices = this->_noOfVertices + countParallelEdges; - - // Modifying the adjMatrix - for (auto& edge : this->_adjMatrix) - { - edge.resize(newNoOfVertices, 0); - } - int k = this->_noOfVertices; - this->_visited.resize(newNoOfVertices, false); - this->_parent.resize(newNoOfVertices, -1); - this->_adjMatrix.resize(newNoOfVertices, vector(newNoOfVertices, 0)); - - // Removing the anti-parallel edges by adding new nodes - for (int i = 0; i < this->_noOfVertices; i++) - { - for (int j = 0; j < this->_noOfVertices; j++) - { - if (this->_adjMatrix[i][j] > 0 && this->_adjMatrix[j][i] > 0) - { - this->_adjMatrix[i][k] = this->_adjMatrix[i][j]; - this->_adjMatrix[k][j] = this->_adjMatrix[i][j]; - this->_adjMatrix[i][j] = 0; - k++; - } - } - } - - // Updating the total no of vertices after modifying the adjMatrix - this->_noOfVertices = newNoOfVertices; - } - - void Graph::DepthFirstSearchVisit(int nodeU) - { - this->_visited[nodeU] = true; - for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) - { - if (!this->_visited[nodeV] && this->_residualGraph[nodeU][nodeV] > 0) - { - this->_parent[nodeV] = nodeU; - this->DepthFirstSearchVisit(nodeV); - } - } - } - - bool Graph::DepthFirstSearch() - { - // Resetting the visited values - fill(this->_visited.begin(), this->_visited.end(), false); - - // Resetting the parent values - fill(this->_parent.begin(), this->_parent.end(), -1); - - // Starting the DepthFirstSearch from the source vertex - this->DepthFirstSearchVisit(this->_source); - - // Returning the visited value of the sink vertex, initially it was set to false - return this->_visited[this->_sink]; - } - - // Graph Public Member Methods - void Graph::CreateGraph(int noOfVertices) - { - this->_noOfVertices = noOfVertices; - this->_source = 0; - this->_sink = this->_noOfVertices - 1; - this->_maximumFlow = 0; - this->_flagParallelEdges = false; - this->_adjMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, 0)); - this->_parent = vector(this->_noOfVertices, -1); - this->_visited = vector(this->_noOfVertices, false); - } - - void Graph::PushDirectedEdge(int valueU, int valueV, int capacity) - { - this->_adjMatrix[valueU][valueV] = capacity; - } - - int Graph::FindMaximumFlowFordFulkerson() - { - // Resolving all the parallel edges if present - this->ResolveAntiParallelEdges(); - this->_residualGraph = this->_adjMatrix; - - // While there exists a path p from source to sink in the residual network G' - while (this->DepthFirstSearch()) - { - int augmentedPathFlow = INT_MAX; - - // Calculating c'(p) = min{ c'(u,v) : (u,v) is in p } - for (int nodeV = this->_sink; nodeV > this->_source; nodeV = this->_parent[nodeV]) - { - int nodeU = this->_parent[nodeV]; - augmentedPathFlow = min(augmentedPathFlow, this->_residualGraph[nodeU][nodeV]); - } - - for (int nodeV = this->_sink; nodeV > this->_source; nodeV = this->_parent[nodeV]) - { - int nodeU = this->_parent[nodeV]; - this->_residualGraph[nodeU][nodeV] -= augmentedPathFlow; - this->_residualGraph[nodeV][nodeU] += augmentedPathFlow; - } - this->_maximumFlow += augmentedPathFlow; - } - - return this->_maximumFlow; - } -} \ No newline at end of file diff --git a/src/0003_graph/0016_MaximumFlowEdmondsKarp.cc b/src/0003_graph/0016_MaximumFlowEdmondsKarp.cc deleted file mode 100644 index 627a2a6..0000000 --- a/src/0003_graph/0016_MaximumFlowEdmondsKarp.cc +++ /dev/null @@ -1,144 +0,0 @@ -#include "0016_MaximumFlowEdmondsKarp.h" -#include -#include -using namespace std; - -namespace MaximumFlowEdmondsKarp -{ - // Graph Private Member Methods - void Graph::ResolveAntiParallelEdges() - { - int countParallelEdges = 0; - for (int i = 0; i < this->_noOfVertices; i++) - { - for (int j = 0; j < this->_noOfVertices; j++) - { - if (this->_adjMatrix[i][j] > 0 && this->_adjMatrix[j][i] > 0) - { - countParallelEdges++; - } - } - } - - // As i->j and j->i both edges has been counted, actual count is count = count / 2 - countParallelEdges /= 2; - - this->_flagParallelEdges = countParallelEdges > 0; - - // If there are no anti-parallel edges, no need to modify the adjMatrix - if (!this->_flagParallelEdges) - { - return; - } - - int newNoOfVertices = this->_noOfVertices + countParallelEdges; - - // Modifying the adjMatrix - for (auto& edge : this->_adjMatrix) - { - edge.resize(newNoOfVertices, 0); - } - int k = this->_noOfVertices; - this->_visited.resize(newNoOfVertices, false); - this->_parent.resize(newNoOfVertices, -1); - this->_adjMatrix.resize(newNoOfVertices, vector(newNoOfVertices, 0)); - - // Removing the anti-parallel edges by adding new nodes - for (int i = 0; i < this->_noOfVertices; i++) - { - for (int j = 0; j < this->_noOfVertices; j++) - { - if (this->_adjMatrix[i][j] > 0 && this->_adjMatrix[j][i] > 0) - { - this->_adjMatrix[i][k] = this->_adjMatrix[i][j]; - this->_adjMatrix[k][j] = this->_adjMatrix[i][j]; - this->_adjMatrix[i][j] = 0; - k++; - } - } - } - - // Updating the total no of vertices after modifying the adjMatrix - this->_noOfVertices = newNoOfVertices; - } - - bool Graph::BreadthFirstSearch() - { - // Resetting the visited values - fill(this->_visited.begin(), this->_visited.end(), false); - - // Resetting the parent values - fill(this->_parent.begin(), this->_parent.end(), -1); - - queue nodeQueue; - nodeQueue.push(this->_source); - this->_visited[this->_source] = true; - - while (!nodeQueue.empty()) - { - int nodeU = nodeQueue.front(); - nodeQueue.pop(); - - for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) - { - if (!this->_visited[nodeV] && this->_residualGraph[nodeU][nodeV] > 0) - { - this->_parent[nodeV] = nodeU; - this->_visited[nodeV] = true; - nodeQueue.push(nodeV); - } - } - } - - // Returning the visited value of the sink vertex, initially it was set to false - return this->_visited[this->_sink]; - } - - // Graph Public Member Methods - void Graph::CreateGraph(int noOfVertices) - { - this->_noOfVertices = noOfVertices; - this->_source = 0; - this->_sink = this->_noOfVertices - 1; - this->_maximumFlow = 0; - this->_flagParallelEdges = false; - this->_adjMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, 0)); - this->_parent = vector(this->_noOfVertices, -1); - this->_visited = vector(this->_noOfVertices, false); - } - - void Graph::PushDirectedEdge(int valueU, int valueV, int capacity) - { - this->_adjMatrix[valueU][valueV] = capacity; - } - - int Graph::FindMaximumFlowEdmondsKarp() - { - // Resolving all the parallel edges if present - this->ResolveAntiParallelEdges(); - this->_residualGraph = this->_adjMatrix; - - // While there exists a path p from source to sink in the residual network G' - while (this->BreadthFirstSearch()) - { - int augmentedPathFlow = INT_MAX; - - // Calculating c'(p) = min{ c'(u,v) : (u,v) is in p } - for (int nodeV = this->_sink; nodeV > this->_source; nodeV = this->_parent[nodeV]) - { - int nodeU = this->_parent[nodeV]; - augmentedPathFlow = min(augmentedPathFlow, this->_residualGraph[nodeU][nodeV]); - } - - for (int nodeV = this->_sink; nodeV > this->_source; nodeV = this->_parent[nodeV]) - { - int nodeU = this->_parent[nodeV]; - this->_residualGraph[nodeU][nodeV] -= augmentedPathFlow; - this->_residualGraph[nodeV][nodeU] += augmentedPathFlow; - } - this->_maximumFlow += augmentedPathFlow; - } - - return this->_maximumFlow; - } -} \ No newline at end of file diff --git a/src/0003_graph/0017_MaximumBipartiteMatching.cc b/src/0003_graph/0017_MaximumBipartiteMatching.cc deleted file mode 100644 index 7c55ce6..0000000 --- a/src/0003_graph/0017_MaximumBipartiteMatching.cc +++ /dev/null @@ -1,263 +0,0 @@ -#include "0017_MaximumBipartiteMatching.h" -#include -#include -using namespace std; - -namespace MaximumBipartiteMatching -{ - // Graph Private Member Methods - void Graph::ResolveAntiParallelEdges() - { - int countParallelEdges = 0; - for (int i = 0; i < this->_noOfVertices; i++) - { - for (int j = 0; j < this->_noOfVertices; j++) - { - if (this->_adjMatrix[i][j] > 0 && this->_adjMatrix[j][i] > 0) - { - countParallelEdges++; - } - } - } - - // As i->j and j->i both edges has been counted, actual count is count = count / 2 - countParallelEdges /= 2; - - this->_flagParallelEdges = countParallelEdges > 0; - - // If there are no anti-parallel edges, no need to modify the adjMatrix - if (!this->_flagParallelEdges) - { - return; - } - - int newNoOfVertices = this->_noOfVertices + countParallelEdges; - - // Modifying the adjMatrix - for (auto& edge : this->_adjMatrix) - { - edge.resize(newNoOfVertices, 0); - } - int k = this->_noOfVertices; - this->_visited.resize(newNoOfVertices, false); - this->_parent.resize(newNoOfVertices, -1); - this->_adjMatrix.resize(newNoOfVertices, vector(newNoOfVertices, 0)); - - // Removing the anti-parallel edges by adding new nodes - for (int i = 0; i < this->_noOfVertices; i++) - { - for (int j = 0; j < this->_noOfVertices; j++) - { - if (this->_adjMatrix[i][j] > 0 && this->_adjMatrix[j][i] > 0) - { - this->_adjMatrix[i][k] = this->_adjMatrix[i][j]; - this->_adjMatrix[k][j] = this->_adjMatrix[i][j]; - this->_adjMatrix[i][j] = 0; - k++; - } - } - } - - // Updating the total no of vertices after modifying the adjMatrix - this->_noOfVertices = newNoOfVertices; - } - - // This method is used to color the vertices of the graph to determine if the given graph is bipartite or not - void Graph::ColorGraph() - { - // Color of all the vertices are initialised to WHITE - fill(this->_color.begin(), this->_color.end(), WHITE); - - // Queue to hold the vertices - queue nodeQueue; - - for (int node = 0; node < this->_noOfVertices; node++) - { - // Check if the node is already not colored - if (this->_color[node] == WHITE) - { - // The color of the node is set to RED - this->_color[node] = RED; - - // The node is inserted into the queue - nodeQueue.push(node); - - // Using BFS method to color all the vertices - while (!nodeQueue.empty()) - { - int nodeU = nodeQueue.front(); - nodeQueue.pop(); - - // Iterating over G.Adj[nodeU] - for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) - { - // As there are no self loops, continue - if (nodeU == nodeV) - { - continue; - } - // Check if there is an edge u --> v and nodeV is not colored yet - else if (this->_residualGraph[nodeU][nodeV] != 0 && this->_color[nodeV] == WHITE) - { - // Set the color of nodeV opposite of nodeU - this->_color[nodeV] = 1 - this->_color[nodeU]; - // Insert the nodeV into the queue - nodeQueue.push(nodeV); - } - // Check if there is an edge u --> v and nodeV is of same color as nodeU - else if (this->_residualGraph[nodeU][nodeV] != 0 && this->_color[nodeV] == this->_color[nodeU]) - { - // Set the _isBipartite flag to false and return - this->_isBipartite = false; - return; - } - } - } - } - } - - // If the above operation completes without returning yet that indicates the graph is bipartite - // Set the _isBipartite flag to true and return - this->_isBipartite = true; - return; - } - - // This method is used to create the additional edges - // from the source vertex to the RED colored vertices and - // from the BLUE colored vertices to the sink vertex - void Graph::AddAdditionalEdges() - { - // Resizing the residual graph to accomodate space for the new edges - for (auto& edge : this->_residualGraph) - { - edge.resize(this->_noOfVertices, 0); - } - - this->_parent.resize(this->_noOfVertices, -1); - this->_visited.resize(this->_noOfVertices, false); - this->_color.resize(this->_noOfVertices, WHITE); - this->_residualGraph.resize(this->_noOfVertices, vector(this->_noOfVertices, 0)); - - // Creating the additional edges - for (int node = 0; node < this->_source; node++) - { - // From source vertex --> RED colored vertices - if (this->_color[node] == RED) - { - this->_residualGraph[this->_source][node] = 1; - } - - // From BLUE colored vertices --> sink vertex - else if (this->_color[node] == BLUE) - { - this->_residualGraph[node][this->_sink] = 1; - } - } - } - - // Implementation of BreadthFirstSearch for EdmondsKarp algorithm to find the path from source to sink - bool Graph::BreadthFirstSearch() - { - // Resetting the visited values - fill(this->_visited.begin(), this->_visited.end(), false); - - // Resetting the parent values - fill(this->_parent.begin(), this->_parent.end(), -1); - - queue nodeQueue; - nodeQueue.push(this->_source); - this->_visited[this->_source] = true; - - while (!nodeQueue.empty()) - { - int nodeU = nodeQueue.front(); - nodeQueue.pop(); - - for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) - { - if (!this->_visited[nodeV] && this->_residualGraph[nodeU][nodeV] > 0) - { - this->_parent[nodeV] = nodeU; - this->_visited[nodeV] = true; - nodeQueue.push(nodeV); - } - } - } - - // Returning the visited value of the sink vertex, initially it was set to false - return this->_visited[this->_sink]; - } - - // Graph Public Member Methods - void Graph::CreateGraph(int noOfVertices) - { - this->_noOfVertices = noOfVertices; - this->_maximumFlow = 0; - this->_flagParallelEdges = false; - this->_adjMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, 0)); - this->_parent = vector(this->_noOfVertices, -1); - this->_visited = vector(this->_noOfVertices, false); - this->_color = vector(this->_noOfVertices, WHITE); - } - - void Graph::PushDirectedEdge(int valueU, int valueV) - { - this->_adjMatrix[valueU][valueV] = 1; - } - - int Graph::FindMaximumBipartiteMatching() - { - // Resolving all the parallel edges if present - this->ResolveAntiParallelEdges(); - this->_residualGraph = this->_adjMatrix; - - this->ColorGraph(); - - this->_source = this->_noOfVertices; - this->_noOfVertices++; - this->_sink = this->_noOfVertices; - this->_noOfVertices++; - - this->AddAdditionalEdges(); - - // While there exists a path p from source to sink in the residual network G' - while (this->BreadthFirstSearch()) - { - int augmentedPathFlow = 1; - - // No need to find the minimum amount of augmentedPathFlow as like standard EdmondsKarp algorithm - // as here capacity of each edges is 1 - for (int nodeV = this->_sink; nodeV != this->_source; nodeV = this->_parent[nodeV]) - { - int nodeU = this->_parent[nodeV]; - this->_residualGraph[nodeU][nodeV] -= augmentedPathFlow; - this->_residualGraph[nodeV][nodeU] += augmentedPathFlow; - } - this->_maximumFlow += augmentedPathFlow; - } - - return this->_maximumFlow; - } - - // This method is used for finding the matchings - vector> Graph::GetMatchings() - { - for (int nodeU = 0; nodeU < this->_adjMatrix.size(); nodeU++) - { - for (int nodeV = 0; nodeV < this->_adjMatrix.size(); nodeV++) - { - // Check if the nodeU and nodeV are not source or sink - // and there is a flow of 1 unit from nodeU --> nodeV - // which means nodeU --> nodeV is being used for the maximum flow (maximum matching) - if ((nodeU != this->_source || nodeU != this->_sink || nodeV != this->_source || nodeV != this->_sink) - && - (this->_adjMatrix[nodeU][nodeV] - this->_residualGraph[nodeU][nodeV]) == 1) - { - this->_matchings.push_back({ nodeU, nodeV }); - } - } - } - - return this->_matchings; - } -} \ No newline at end of file diff --git a/src/0003_graph/0018_MaximumFlowGoldbergGenericPushRelabel.cc b/src/0003_graph/0018_MaximumFlowGoldbergGenericPushRelabel.cc deleted file mode 100644 index 63c1475..0000000 --- a/src/0003_graph/0018_MaximumFlowGoldbergGenericPushRelabel.cc +++ /dev/null @@ -1,172 +0,0 @@ -#include "0018_MaximumFlowGoldbergGenericPushRelabel.h" -#include -using namespace std; - -namespace MaximumFlowGoldbergGenericPushRelabel -{ - // Graph Private Member Methods - - // Initializes Pre-Flow in the given Flow Network - void Graph::InitializePreflow() - { - // The height of source is set to highest possible height value - this->_height[this->_source] = this->_noOfVertices; - - // Iterating over all the vertices - for (int i = 0; i < this->_noOfVertices; i++) - { - // For the all the edges (source, v) - if (this->_residualGraph[this->_source][i] > 0) - { - // v.excessFlow = capacity(source, v) - this->_excessFlow[i] = this->_residualGraph[this->_source][i]; - - // source.excessFlow = source.excessFlow - capacity(source, v) - this->_excessFlow[this->_source] = this->_excessFlow[this->_source] - this->_residualGraph[this->_source][i]; - - // Adjusting the flow and reverse flow along source->v and v->source respectively - this->_residualGraph[i][this->_source] = this->_residualGraph[this->_source][i]; - this->_residualGraph[this->_source][i] = 0; - } - } - } - - // Checks if there is any vertex which has excess flow - bool Graph::CheckOverFlow() - { - // Iterating over all of the vertices - for (int i = 0; i < this->_noOfVertices; i++) - { - // Checks if the current vertex is not any special vertex like source, sink - // and also if there is excess flow in the current vertex and it is already not present in the queue - if (i!=this->_source && i!=this->_sink && this->_excessFlow[i] > 0 && this->_visited[i] == false) - { - // Insert the current vertex into the queue - this->_nodeQueue.push(i); - - // Mark it as visited, so until it leaves the queue it is not inserted again even if all the excess flow is neutralized - this->_visited[i] = true; - } - } - - // Checks if there is no vertex having excess flow then returns false - if (this->_nodeQueue.empty()) - { - return false; - } - - return true; - } - - // Pushes the flow from nodeU to its neighbour vertices - bool Graph::Push(int nodeU) - { - int nodeV = -1; - int minimumFlow = INT_MAX; - - // Iterating over all the vertices - for (int i = 0; i < this->_noOfVertices; i++) - { - // For G'.Adj[nodeU] select the vertex if edge (nodeU, i) is non-saturated and height[nodeU] == height[i] + 1 - if (this->_residualGraph[nodeU][i] > 0 && this->_height[nodeU] == this->_height[i] + 1) - { - nodeV = i; - break; - } - } - - // Checks if any neighbour vertex found having non-saturated edge - if (nodeV != -1) - { - // Calculate the flow amount to be added along the edge and excess flow subtracted from nodeU - minimumFlow = min(this->_residualGraph[nodeU][nodeV], this->_excessFlow[nodeU]); - - // Adjust the flow and the reverse flow along (nodeU, nodeV) - this->_residualGraph[nodeU][nodeV] = this->_residualGraph[nodeU][nodeV] - minimumFlow; - this->_residualGraph[nodeV][nodeU] = this->_residualGraph[nodeV][nodeU] + minimumFlow; - - // Adjust the excess flows in nodeU and nodeV - this->_excessFlow[nodeU] = this->_excessFlow[nodeU] - minimumFlow; - this->_excessFlow[nodeV] = this->_excessFlow[nodeV] + minimumFlow; - - // Return that the Push operation is successful - return true; - } - - // Return that the Push operation is not successful - return false; - } - - // Relabels height of vertex nodeU when there are outgoing non-saturated edges available - void Graph::Relabel(int nodeU) - { - int minimumHeight = INT_MAX; - - // Iterating over all the vertices - for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) - { - // For G'.Adj[nodeU] select for which nodeV, height[nodeU] <= height[nodeV] - if (this->_residualGraph[nodeU][nodeV] > 0 && this->_height[nodeU] <= this->_height[nodeV]) - { - // Get the minimum height among all these G'.Adj[nodeU] - minimumHeight = min(minimumHeight, this->_height[nodeV]); - } - } - - // Set height[nodeU] - this->_height[nodeU] = minimumHeight + 1; - } - - - // Graph Public Member Methods - void Graph::CreateGraph(int noOfVertices) - { - this->_noOfVertices = noOfVertices; - this->_source = 0; - this->_sink = this->_noOfVertices - 1; - this->_maximumFlow = 0; - this->_adjMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, 0)); - this->_excessFlow = vector(this->_noOfVertices, 0); - this->_height = vector(this->_noOfVertices, 0); - this->_visited = vector(this->_noOfVertices, false); - } - - void Graph::PushDirectedEdge(int valueU, int valueV, int capacity) - { - this->_adjMatrix[valueU][valueV] = capacity; - } - - int Graph::FindMaximumFlowGoldbergGenericPushRelabel() - { - this->_residualGraph = this->_adjMatrix; - - // Initialize Pre-flow - this->InitializePreflow(); - - // Checks if there is some vertices which have excess flow - while (this->CheckOverFlow()) - { - // Get the vertex - int nodeU = this->_nodeQueue.front(); - - // Checks if the Push operation is successful - if (this->Push(nodeU)) - { - // Then remove the vertex from queue and set visited[nodeU] = true - // so that on next CheckOverFlow() method call this vertex can be discovered if it still has some excess flow - this->_nodeQueue.pop(); - this->_visited[nodeU] = false; - } - - // If the Push operation is not successful - else - { - // Then Relabel nodeU without removing it from the queue - this->Relabel(nodeU); - } - } - - // Return the excess flow in the sink vertex which is actually the maximum flow along the given flow network - return this->_excessFlow[this->_sink]; - } -} \ No newline at end of file diff --git a/src/0003_graph/0019_MaximumFlowRelabelToFront.cc b/src/0003_graph/0019_MaximumFlowRelabelToFront.cc deleted file mode 100644 index 034f5bf..0000000 --- a/src/0003_graph/0019_MaximumFlowRelabelToFront.cc +++ /dev/null @@ -1,169 +0,0 @@ -#include "0019_MaximumFlowRelabelToFront.h" -#include -#include -using namespace std; - -namespace MaximumFlowRelabelToFront -{ - // Graph Private Member Methods - - // Initializes Pre-Flow in the given Flow Network - void Graph::InitializePreflow() - { - // The height of source is set to highest possible height value - this->_height[this->_source] = this->_noOfVertices; - - // Iterating over all the vertices - for (int i = 0; i < this->_noOfVertices; i++) - { - // For the all the edges (source, v) - if (this->_residualGraph[this->_source][i] > 0) - { - // v.excessFlow = capacity(source, v) - this->_excessFlow[i] = this->_residualGraph[this->_source][i]; - - // source.excessFlow = source.excessFlow - capacity(source, v) - this->_excessFlow[this->_source] = this->_excessFlow[this->_source] - this->_residualGraph[this->_source][i]; - - // Adjusting the flow and reverse flow along source->v and v->source respectively - this->_residualGraph[i][this->_source] = this->_residualGraph[this->_source][i]; - this->_residualGraph[this->_source][i] = 0; - } - } - } - - // Discharges the excess flow from nodeU - void Graph::Discharge(int nodeU) - { - // Check if excess flow of nodeU is > 0 - while (this->_excessFlow[nodeU] > 0) - { - // Falg to check if any amount of excess flow is pushed to any neighbour vertex - bool hasPushed = false; - - // Iterating over all of the vertices - for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) - { - // For G'.Adj[nodeU] check if edge (nodeU, nodeV) is admissible - if (this->_residualGraph[nodeU][nodeV] > 0 && this->_height[nodeU] == 1 + this->_height[nodeV]) - { - // Push excess flow along the admissible edge (nodeU, nodeV) - this->Push(nodeU, nodeV); - // Set the hasPushed flag to true - hasPushed = true; - // Check if there is no excess flow left in nodeU then no need to check any more admissible edge going from nodeU - if (this->_excessFlow[nodeU] == 0) - { - // Then break from iterating over G'.Adj[nodeU] - break; - } - } - } - - // Check if Push operation is not done yet - if (!hasPushed) - { - // Then it indicates that all the outgoing edges from nodeU are inadmissible - // so perform the Relabel operation on nodeU - this->Relabel(nodeU); - } - } - } - - // Pushes the flow from nodeU to its neighbour vertices - void Graph::Push(int nodeU, int nodeV) - { - // Calculate the flow amount to be added along the edge and excess flow subtracted from nodeU - int minimumFlow = min(this->_residualGraph[nodeU][nodeV], this->_excessFlow[nodeU]); - - // Adjust the flow and the reverse flow along (nodeU, nodeV) - this->_residualGraph[nodeU][nodeV] = this->_residualGraph[nodeU][nodeV] - minimumFlow; - this->_residualGraph[nodeV][nodeU] = this->_residualGraph[nodeV][nodeU] + minimumFlow; - - // Adjust the excess flows in nodeU and nodeV - this->_excessFlow[nodeU] = this->_excessFlow[nodeU] - minimumFlow; - this->_excessFlow[nodeV] = this->_excessFlow[nodeV] + minimumFlow; - } - - // Relabels height of vertex nodeU when there are outgoing non-saturated edges available - void Graph::Relabel(int nodeU) - { - int minimumHeight = INT_MAX; - - // Iterating over all the vertices - for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) - { - // For G'.Adj[nodeU] select for which nodeV, height[nodeU] <= height[nodeV] - if (this->_residualGraph[nodeU][nodeV] > 0 && this->_height[nodeU] <= this->_height[nodeV]) - { - // Get the minimum height among all these G'.Adj[nodeU] - minimumHeight = min(minimumHeight, this->_height[nodeV]); - } - } - - // Set height[nodeU] - this->_height[nodeU] = minimumHeight + 1; - } - - - // Graph Public Member Methods - void Graph::CreateGraph(int noOfVertices) - { - this->_noOfVertices = noOfVertices; - this->_source = 0; - this->_sink = this->_noOfVertices - 1; - this->_maximumFlow = 0; - this->_adjMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, 0)); - this->_excessFlow = vector(this->_noOfVertices, 0); - this->_height = vector(this->_noOfVertices, 0); - this->_visited = vector(this->_noOfVertices, false); - } - - void Graph::PushDirectedEdge(int valueU, int valueV, int capacity) - { - this->_adjMatrix[valueU][valueV] = capacity; - } - - int Graph::FindMaximumFlowRelabelToFront() - { - this->_residualGraph = this->_adjMatrix; - - // Initialize Pre-flow - this->InitializePreflow(); - - // Make the list L = G.V - {source, sink} - for (int i = 0; i < this->_noOfVertices; i++) - { - if (i != this->_source && i != this->_sink) - { - this->_nodeList.push_back(i); - } - } - - // Set current vertex = L.head - list::iterator nodeUiterator = this->_nodeList.begin(); - - // Iterate over all of the elements in the list L - while (nodeUiterator != this->_nodeList.end()) - { - // Get the height of current vertex - int oldHeight = this->_height[*nodeUiterator]; - - // Discharge the excess flow of current vertex - this->Discharge(*nodeUiterator); - - // Check if the height of current vertex increases which means the current vertex got relabeled - if (this->_height[*nodeUiterator] > oldHeight) - { - // Then move current vertex to the front of the list L - this->_nodeList.splice(this->_nodeList.begin(), this->_nodeList, nodeUiterator); - } - - // Go to the next vertex of current vertex in L - nodeUiterator++; - } - - // Return the excess flow in the sink vertex which is actually the maximum flow along the given flow network - return this->_excessFlow[this->_sink]; - } -} \ No newline at end of file diff --git a/src/0003_graph/CMakeLists.txt b/src/0003_graph/CMakeLists.txt deleted file mode 100644 index 02f8a77..0000000 --- a/src/0003_graph/CMakeLists.txt +++ /dev/null @@ -1,30 +0,0 @@ -# Specify the source files -set(0003GRAPH_SOURCES - 0001_BreadthFirstSearch.cc - 0002_DepthFirstSearch.cc - 0003_TopologicalSort.cc - 0004_StronglyConnectedComponents.cc - 0005_HamiltonianPathAndCycle.cc - 0006_EulerianPathAndCircuit.cc - 0007_MinimumSpanningTreeKruskalAlgorithm.cc - 0008_MinimumSpanningTreePrimAlgorithm.cc - 0009_SingleSourceShortestPathBellmanFord.cc - 0010_DirectedAcyclicGraphShortestPath.cc - 0011_SingleSourceShortestPathDijkstra.cc - 0012_DifferenceConstraintsShortestPaths.cc - 0013_AllPairsShortestPathsFloydWarshall.cc - 0014_AllPairsShortestPathsJohnson.cc - 0015_MaximumFlowFordFulkerson.cc - 0016_MaximumFlowEdmondsKarp.cc - 0017_MaximumBipartiteMatching.cc - 0018_MaximumFlowGoldbergGenericPushRelabel.cc - 0019_MaximumFlowRelabelToFront.cc - -) - -# Create a library target -add_library(0003GRAPH ${0003GRAPH_SOURCES}) - -target_include_directories(0003GRAPH PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/headers -) \ No newline at end of file diff --git a/src/0003_graph/headers/0001_BreadthFirstSearch.h b/src/0003_graph/headers/0001_BreadthFirstSearch.h deleted file mode 100644 index ba7aec8..0000000 --- a/src/0003_graph/headers/0001_BreadthFirstSearch.h +++ /dev/null @@ -1,35 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -using namespace std; - -namespace BreadthFirstSearch -{ - enum color { WHITE, GRAY, BLACK }; - class Node - { - public: - int data; - int distance; - int color; - Node* parent; - Node(int value); - }; - - class Graph - { - private: - map> _adjlist; - map _nodeMap; - Node* MakeOrFindNode(int value); - void BreadthFirstSearch(Node* node); - public: - void PushUndirectedEdge(int valueU, int valueV); - void BFS(int value); - vector> ShowBFSResult(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0002_DepthFirstSearch.h b/src/0003_graph/headers/0002_DepthFirstSearch.h deleted file mode 100644 index e376295..0000000 --- a/src/0003_graph/headers/0002_DepthFirstSearch.h +++ /dev/null @@ -1,37 +0,0 @@ -#pragma once - -#include -#include -#include -#include -using namespace std; - -namespace DepthFirstSearch -{ - enum color { WHITE, GRAY, BLACK }; - - class Node - { - public: - int data; - int color; - int discoveredTime; - int finishingTime; - Node* parent; - Node(int value); - }; - - class Graph - { - private: - int _time; - map> _adjlist; - map _nodeMap; - Node* MakeOrFindNode(int value); - void DepthFirstSearch(Node* Node); - public: - void PushDirectedEdge(int valueU, int valueV); - void DFS(); - vector>> ShowDFSResult(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0003_TopologicalSort.h b/src/0003_graph/headers/0003_TopologicalSort.h deleted file mode 100644 index 441d7d1..0000000 --- a/src/0003_graph/headers/0003_TopologicalSort.h +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once - -#include -#include -#include -#include -using namespace std; - -namespace TopologicalSort -{ - enum color { WHITE, GRAY, BLACK }; - - class Node - { - public: - int data; - int color; - int discoveryTime; - int finishingTime; - int inDegree; - Node* parent; - Node(int value); - }; - - class Graph - { - private: - int _time; - bool _hasCycle; - map> _adjlist; - map _nodeMap; - list _topologicalSortedNodeList; - Node* MakeOrFindNode(int value); - void DepthFirstSearch(Node* DFSNode); - public: - void PushDirectedEdge(int valueU, int valueV); - void PushSingleNode(int valueU); - void TopologicalSort(); - void KahnTopologicalSort(); - vector>> ShowTopologicalSortResult(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0004_StronglyConnectedComponents.h b/src/0003_graph/headers/0004_StronglyConnectedComponents.h deleted file mode 100644 index 0e37f60..0000000 --- a/src/0003_graph/headers/0004_StronglyConnectedComponents.h +++ /dev/null @@ -1,43 +0,0 @@ -#pragma once - -#include -#include -#include -#include -using namespace std; - -namespace StronglyConnectedComponents -{ - enum color { WHITE, GRAY, BLACK }; - - class Node - { - public: - int data; - int color; - int discoveryTime; - int finishingTime; - Node* parent; - Node(int value); - }; - - class Graph - { - private: - int _time; - map> _adjlistG; - map> _adjlistT; - map _nodeMap; - list _nodesFinishingTimeOrder; - vector> _allConnectedComponents; - Node* MakeOrFindNode(int value); - void DepthFirstSearchOnGraphG(Node* DFSNode); - void DepthFirstSearchOnGraphT(Node* DFSNode, vector& connectedComponents); - public: - void PushDirectedEdge(int valueU, int valueV); - void PushSingleNode(int valueU); - void DFSOnGraphG(); - void DFSOnGraphT(); - vector> FindAllStronglyConnectedComponents(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0005_HamiltonianPathAndCycle.h b/src/0003_graph/headers/0005_HamiltonianPathAndCycle.h deleted file mode 100644 index 7ccca6a..0000000 --- a/src/0003_graph/headers/0005_HamiltonianPathAndCycle.h +++ /dev/null @@ -1,40 +0,0 @@ -#pragma once - -#include -#include -#include -using namespace std; - -namespace HamiltonianPathAndCycle -{ - class Node - { - public: - int data; - bool isVisited; - Node(int value); - }; - - class Graph - { - private: - bool _isHamiltonianCyclePresent; - bool _isHamiltonianPathPresent; - int _visitedNodeCount; - Node* _startingNode; - map> _adjlist; - map _nodeMap; - vector _hamiltonianPath; - Node* MakeOrFindNode(int value); - bool IsSafe(Node* nodeU, Node* nodeV); - bool HamiltonianCycleAndPathUtil(Node* node); - - public: - void PushUndirectedEdge(int valueU, int valueV); - void PushSingleNode(int valueU); - void FindHamiltonianCycleAndPath(); - bool IsHamiltonianCyclePresent(); - bool IsHamiltonianPathPresent(); - vector GetHamiltonianPath(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0006_EulerianPathAndCircuit.h b/src/0003_graph/headers/0006_EulerianPathAndCircuit.h deleted file mode 100644 index 92d0d34..0000000 --- a/src/0003_graph/headers/0006_EulerianPathAndCircuit.h +++ /dev/null @@ -1,43 +0,0 @@ -#pragma once - -#include -#include -#include -using namespace std; - -namespace EulerianPathAndCircuit -{ - class Node - { - public: - int data; - int degree; - int inDegree; - int outDegree; - bool visited; - Node(int value); - }; - - class Graph - { - private: - bool _isEulerianPathPresent; - bool _isEulerianCircuitPresent; - map> _adjlist; - map _nodeMap; - vector _eulerianPath; - Node* MakeOrFindNode(int value); - void DepthFirstSearch(Node* node); - bool IsConnected(); - void EulerianPathHierholzerAlgorithm(Node* startingNode); - - public: - void PushUndirectedEdge(int valueU, int valueV); - void PushDirectedEdge(int valueU, int valueV); - void PushSingleNode(int valueU); - void FindEulerianPathAndCircuit(); - bool IsEulerianPathPresent(); - bool IsEulerianCircuitPresent(); - vector UndirectedGraphGetEulerianPath(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0007_MinimumSpanningTreeKruskalAlgorithm.h b/src/0003_graph/headers/0007_MinimumSpanningTreeKruskalAlgorithm.h deleted file mode 100644 index 8ca704c..0000000 --- a/src/0003_graph/headers/0007_MinimumSpanningTreeKruskalAlgorithm.h +++ /dev/null @@ -1,46 +0,0 @@ -#pragma once - -#include -#include -#include -using namespace std; - -namespace MinimumSpanningTreeKruskalAlgorithm -{ - class Node - { - public: - int data; - Node* parent; - int rank; - Node(int data); - }; - - class Edge - { - public: - Node* nodeU; - Node* nodeV; - int weight; - Edge(Node* nodeU, Node* nodeV, int weight); - }; - - class Graph - { - private: - map> _adjlist; - map _nodeMap; - vector _edgeList; - vector, int>> _minimumSpanningTree; - Node* MakeOrFindNode(int data); - void MakeSet(Node* node); - void Union(Node* nodeU, Node* nodeV); - void Link(Node* nodeU, Node* nodeV); - Node* FindSet(Node* node); - - public: - void PushUndirectedEdge(int valueU, int valueV, int weight); - void FindMinimumSpanningTreeKruskalAlgorithm(); - vector, int>> GetMinimumSpanningTree(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0008_MinimumSpanningTreePrimAlgorithm.h b/src/0003_graph/headers/0008_MinimumSpanningTreePrimAlgorithm.h deleted file mode 100644 index ffe7c08..0000000 --- a/src/0003_graph/headers/0008_MinimumSpanningTreePrimAlgorithm.h +++ /dev/null @@ -1,42 +0,0 @@ -# pragma once - -#include -#include -#include -using namespace std; - -namespace MinimumSpanningTreePrimAlgorithm -{ - class Node - { - public: - int data; - Node* parent; - int key; - bool isInOperationalSet; - Node(int data); - }; - - class CompareNodeKey - { - public: - bool operator()(const Node* nodeU, const Node* nodeV) const - { - return nodeU->key < nodeV->key; - } - }; - - class Graph - { - private: - map>> _adjlist; - map _nodeMap; - vector, int>> _minimumSpanningTree; - multiset _operationalSet; - Node* MakeOrFindNode(int data); - public: - void PushUndirectedEdge(int valueU, int valueV, int weight); - void FindMinimumSpanningTreePrimAlgorithm(); - vector, int>> GetMinimumSpanningTree(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0009_SingleSourceShortestPathBellmanFord.h b/src/0003_graph/headers/0009_SingleSourceShortestPathBellmanFord.h deleted file mode 100644 index e51ca10..0000000 --- a/src/0003_graph/headers/0009_SingleSourceShortestPathBellmanFord.h +++ /dev/null @@ -1,44 +0,0 @@ -#pragma once - -#include -#include -using namespace std; - -namespace SingleSourceShortestPathBellmanFord -{ - class Node - { - public: - int data; - int distance; - Node* parent; - Node(int data); - }; - - class Edge - { - public: - Node* nodeU; - Node* nodeV; - int weight; - Edge(Node* nodeU, Node* nodeV, int weight); - }; - - class Graph - { - private: - map> _adjlist; - map _nodeMap; - vector _edgeList; - Node* MakeOrFindNode(int data); - void InitializeSingleSource(Node* sourceNode); - void Relax(Edge* edge); - void GetShortestPath(Node* node, vector& path); - - - public: - void PushDirectedEdge(int valueU, int valueV, int weight); - bool FindSingleSourceShortestPathBellmanFord(int data); - vector GetShortestPathBellmanFord(int data); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0010_DirectedAcyclicGraphShortestPath.h b/src/0003_graph/headers/0010_DirectedAcyclicGraphShortestPath.h deleted file mode 100644 index 8826ebc..0000000 --- a/src/0003_graph/headers/0010_DirectedAcyclicGraphShortestPath.h +++ /dev/null @@ -1,51 +0,0 @@ -#pragma once - -#include -#include -#include -using namespace std; - -namespace DirectedAcyclicGraphShortestPath -{ - enum color {WHITE, GRAY, BLACK}; - - class Node - { - public: - int data; - int color; - int distance; - Node* parent; - Node(int data); - }; - - class Edge - { - public: - Node* nodeU; - Node* nodeV; - int weight; - Edge(Node* nodeU, Node* nodeV, int weight); - }; - - class Graph - { - private: - map> _adjlist; - map _nodeMap; - map> _edgeMap; - list _topologicalSortedNodeList; - Node* MakeOrFindNode(int data); - void DepthFirstSearch(Node* node); - void TopologicalSort(); - void InitializeSingleSource(Node* sourceNode); - void Relax(Edge* edge); - void GetShortestPath(Node* node, vector& path); - - - public: - void PushDirectedEdge(int valueU, int valueV, int weight); - void FindDAGShortestPath(int data); - vector GetDAGShortestPath(int data); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0011_SingleSourceShortestPathDijkstra.h b/src/0003_graph/headers/0011_SingleSourceShortestPathDijkstra.h deleted file mode 100644 index 8911ac8..0000000 --- a/src/0003_graph/headers/0011_SingleSourceShortestPathDijkstra.h +++ /dev/null @@ -1,55 +0,0 @@ -#pragma once - -#include -#include -#include -using namespace std; - -namespace SingleSourceShortestPathDijkstra -{ - class Node - { - public: - int data; - int distance; - Node* parent; - Node(int data); - }; - - class Edge - { - public: - Node* nodeU; - Node* nodeV; - int weight; - Edge(Node* nodeU, Node* nodeV, int weight); - }; - - class CompareNodeDistance - { - public: - bool operator()(const Node* nodeU, const Node* nodeV) const - { - return nodeU->distance < nodeV->distance; - } - }; - - class Graph - { - private: - map> _adjlist; - map _nodeMap; - map> _edgeMap; - multiset _operationalSet; - Node* MakeOrFindNode(int data); - void InitializeSingleSource(Node* sourceNode); - void Relax(Edge* edge); - void Dijkstra(Node* source); - void GetShortestPath(Node* node, vector& path); - - public: - void PushDirectedEdge(int valueU, int valueV, int weight); - void FindShortestPathDijkstra(int data); - vector GetDijkstraShortestPath(int data); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0012_DifferenceConstraintsShortestPaths.h b/src/0003_graph/headers/0012_DifferenceConstraintsShortestPaths.h deleted file mode 100644 index 02d1426..0000000 --- a/src/0003_graph/headers/0012_DifferenceConstraintsShortestPaths.h +++ /dev/null @@ -1,43 +0,0 @@ -#pragma once - -#include -#include -#include -using namespace std; - -namespace DifferenceConstraintsShortestPaths -{ - class Node - { - public: - string data; - int distance; - Node(string data); - }; - - class Edge - { - public: - Node* nodeU; - Node* nodeV; - int weight; - Edge(Node* nodeU, Node* nodeV, int weight); - }; - - class Graph - { - private: - map> _adjlist; - map _nodeMap; - vector _edgeList; - Node* MakeOrFindNode(string data); - void PushDirectedEdge(string valueU, string valueV, int weight); - void InitializeSingleSource(Node* sourceNode); - void Relax(Edge* edge); - - public: - void PushAllDirectedEdges(vector> vectorA, vector vectorX, vector vectorB); - bool FindDifferenceConstraintsSolutionBellmanFord(); - vector> GetDifferenceConstrtaintsSolution(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0013_AllPairsShortestPathsFloydWarshall.h b/src/0003_graph/headers/0013_AllPairsShortestPathsFloydWarshall.h deleted file mode 100644 index 211e1b6..0000000 --- a/src/0003_graph/headers/0013_AllPairsShortestPathsFloydWarshall.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include -using namespace std; - -namespace AllPairsShortestPathsFloydWarshall -{ - class Graph - { - private: - int _noOfVertices; - vector> _adjMatrix; - vector> _shortestPathMatrixFloydWarshall; - vector> _predecessorMatrix; - void InitializeDistanceAndPredecessors(); - void GetShortestPath(int source, int destination, vector& path); - - public: - void CreateGraph(int noOfVertices); - void PushDirectedEdge(int valueU, int valueV, int weight); - void FindAllPairsShortestPathsFloydWarshallSolution(); - vector> GetFloydWarshallShortestPath(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0014_AllPairsShortestPathsJohnson.h b/src/0003_graph/headers/0014_AllPairsShortestPathsJohnson.h deleted file mode 100644 index 925e89e..0000000 --- a/src/0003_graph/headers/0014_AllPairsShortestPathsJohnson.h +++ /dev/null @@ -1,66 +0,0 @@ -#pragma once - -#include -#include -#include -using namespace std; - -namespace AllPairsShortestPathsJohnson -{ - class Node - { - public: - int data; - int distance; - Node* parent; - int potentialWeight; - Node(int data); - }; - - class Edge - { - public: - Node* nodeU; - Node* nodeV; - int weight; - Edge(Node* nodeU, Node* nodeV, int weight); - }; - - class CompareNodeDistance - { - public: - bool operator()(const Node* nodeU, const Node* nodeV) const - { - return nodeU->distance < nodeV->distance; - } - }; - - class Graph - { - private: - int _noOfVertices=0; - map> _adjlist; - map _nodeMap; - vector _edgeList; - map> _edgeMap; - map> _augmentedAdjlist; - vector _augmentedEdgeList; - multiset _operationalSet; - vector> _shortestPathMatrix; - vector> _predecessorMatrix; - Node* MakeOrFindNode(int data); - void PushAugmentedDirectedEdges(Node* sourceNode, Node* nodeV, int weight); - void InitializeSingleSource(Node* sourceNode); - void RelaxBellmanFord(Edge* edge); - bool BellmanFord(Node* source); - void RelaxDijkstra(Edge* edge); - void Dijkstra(Node* source); - void GetShortestPath(int source, int destination, vector& path); - - public: - void PushDirectedEdge(int dataU, int dataV, int weight); - bool FindAllPairsShortestPathsJohnsonAlgorithm(); - vector> GetAllPairsShortestPathsDistanceMatrix(); - vector> GetAllPairsShortestPathsPathMatrix(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0015_MaximumFlowFordFulkerson.h b/src/0003_graph/headers/0015_MaximumFlowFordFulkerson.h deleted file mode 100644 index 429b247..0000000 --- a/src/0003_graph/headers/0015_MaximumFlowFordFulkerson.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include -#include -using namespace std; - -namespace MaximumFlowFordFulkerson -{ - class Graph - { - private: - int _noOfVertices; - int _source; - int _sink; - int _maximumFlow; - bool _flagParallelEdges; - vector> _adjMatrix; - vector> _residualGraph; - vector _parent; - vector _visited; - void ResolveAntiParallelEdges(); - void DepthFirstSearchVisit(int nodeU); - bool DepthFirstSearch(); - public: - void CreateGraph(int noOfVertices); - void PushDirectedEdge(int valueU, int valueV, int capacity); - int FindMaximumFlowFordFulkerson(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0016_MaximumFlowEdmondsKarp.h b/src/0003_graph/headers/0016_MaximumFlowEdmondsKarp.h deleted file mode 100644 index 25c72f1..0000000 --- a/src/0003_graph/headers/0016_MaximumFlowEdmondsKarp.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once - -#include -#include -using namespace std; - -namespace MaximumFlowEdmondsKarp -{ - class Graph - { - private: - int _noOfVertices; - int _source; - int _sink; - int _maximumFlow; - bool _flagParallelEdges; - vector> _adjMatrix; - vector> _residualGraph; - vector _parent; - vector _visited; - void ResolveAntiParallelEdges(); - bool BreadthFirstSearch(); - public: - void CreateGraph(int noOfVertices); - void PushDirectedEdge(int valueU, int valueV, int capacity); - int FindMaximumFlowEdmondsKarp(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0017_MaximumBipartiteMatching.h b/src/0003_graph/headers/0017_MaximumBipartiteMatching.h deleted file mode 100644 index 741c3c0..0000000 --- a/src/0003_graph/headers/0017_MaximumBipartiteMatching.h +++ /dev/null @@ -1,41 +0,0 @@ -#pragma once - -#include -#include -using namespace std; - -namespace MaximumBipartiteMatching -{ - enum Color - { - WHITE = -1, - RED = 0, - BLUE = 1 - }; - - class Graph - { - private: - int _noOfVertices; - int _source; - int _sink; - int _maximumFlow; - bool _flagParallelEdges; - bool _isBipartite; - vector> _adjMatrix; - vector> _residualGraph; - vector _parent; - vector _visited; - vector _color; - vector> _matchings; - void ResolveAntiParallelEdges(); - void ColorGraph(); - void AddAdditionalEdges(); - bool BreadthFirstSearch(); - public: - void CreateGraph(int noOfVertices); - void PushDirectedEdge(int valueU, int valueV); - int FindMaximumBipartiteMatching(); - vector> GetMatchings(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0018_MaximumFlowGoldbergGenericPushRelabel.h b/src/0003_graph/headers/0018_MaximumFlowGoldbergGenericPushRelabel.h deleted file mode 100644 index fb13a01..0000000 --- a/src/0003_graph/headers/0018_MaximumFlowGoldbergGenericPushRelabel.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once - -#include -#include -using namespace std; - -namespace MaximumFlowGoldbergGenericPushRelabel -{ - class Graph - { - private: - int _noOfVertices; - int _source; - int _sink; - int _maximumFlow; - vector> _adjMatrix; - vector> _residualGraph; - vector _excessFlow; - vector _height; - vector _visited; - queue _nodeQueue; - void InitializePreflow(); - bool CheckOverFlow(); - bool Push(int nodeU); - void Relabel(int nodeU); - public: - void CreateGraph(int noOfVertices); - void PushDirectedEdge(int valueU, int valueV, int capacity); - int FindMaximumFlowGoldbergGenericPushRelabel(); - }; -} \ No newline at end of file diff --git a/src/0003_graph/headers/0019_MaximumFlowRelabelToFront.h b/src/0003_graph/headers/0019_MaximumFlowRelabelToFront.h deleted file mode 100644 index aea70f6..0000000 --- a/src/0003_graph/headers/0019_MaximumFlowRelabelToFront.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once - -#include -#include -using namespace std; - -namespace MaximumFlowRelabelToFront -{ - class Graph - { - private: - int _noOfVertices; - int _source; - int _sink; - int _maximumFlow; - vector> _adjMatrix; - vector> _residualGraph; - vector _excessFlow; - vector _height; - vector _visited; - list _nodeList; - void InitializePreflow(); - void Discharge(int nodeU); - void Push(int nodeU, int nodeV); - void Relabel(int nodeU); - public: - void CreateGraph(int noOfVertices); - void PushDirectedEdge(int valueU, int valueV, int capacity); - int FindMaximumFlowRelabelToFront(); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0001_FibonacciNumber.cc b/src/0004_dynamic_programming/0001_FibonacciNumber.cc deleted file mode 100644 index 47073aa..0000000 --- a/src/0004_dynamic_programming/0001_FibonacciNumber.cc +++ /dev/null @@ -1,28 +0,0 @@ -#include "0001_FibonacciNumber.h" - -namespace FibonacciNumber -{ - int DynamicProgramming::RecursiveNthFibonacci(int n) - { - if (n <= 1) - { - return n; - } - - return this->RecursiveNthFibonacci(n - 1) + this->RecursiveNthFibonacci(n - 2); - } - - int DynamicProgramming::DpNthFibonacci(int n) - { - vector dp(n + 1, 0); - dp[0] = 0; - dp[1] = 1; - - for (int i = 2; i <= n; i++) - { - dp[i] = dp[i - 1] + dp[i - 2]; - } - - return dp[n]; - } -} diff --git a/src/0004_dynamic_programming/0002_TribonacciNumber.cc b/src/0004_dynamic_programming/0002_TribonacciNumber.cc deleted file mode 100644 index 84a4c59..0000000 --- a/src/0004_dynamic_programming/0002_TribonacciNumber.cc +++ /dev/null @@ -1,33 +0,0 @@ -#include "0002_TribonacciNumber.h" - -namespace TribonacciNumber -{ - int DynamicProgramming::RecursiveNthTribonacci(int n) - { - if (n == 0 || n == 1 || n == 2) - { - return 0; - } - - if (n == 3) - { - return 1; - } - - return this->RecursiveNthTribonacci(n - 1) + this->RecursiveNthTribonacci(n - 2) + this->RecursiveNthTribonacci(n - 3); - } - - int DynamicProgramming::DpNthTribonacci(int n) - { - vector dp(n, 0); - dp[0] = dp[1] = 0; - dp[2] = 1; - - for (int i = 3; i < n; i++) - { - dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]; - } - - return dp[n - 1]; - } -} diff --git a/src/0004_dynamic_programming/0003_ClimbingStairs.cc b/src/0004_dynamic_programming/0003_ClimbingStairs.cc deleted file mode 100644 index 6e365f8..0000000 --- a/src/0004_dynamic_programming/0003_ClimbingStairs.cc +++ /dev/null @@ -1,29 +0,0 @@ -#include "0003_ClimbingStairs.h" -using namespace std; - -namespace ClimbingStairs -{ - int DynamicProgramming::RecursiveCountWays(int n) - { - if (n == 0 || n == 1) - { - return 1; - } - - return this->RecursiveCountWays(n - 1) + this->RecursiveCountWays(n - 2); - } - - int DynamicProgramming::DpCountWays(int n) - { - vector dp(n + 1, 0); - dp[0] = 1; - dp[1] = 1; - - for (int i = 2; i <= n; i++) - { - dp[i] = dp[i - 1] + dp[i - 2]; - } - - return dp[n]; - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0004_MinimumCostClimbingStairs.cc b/src/0004_dynamic_programming/0004_MinimumCostClimbingStairs.cc deleted file mode 100644 index 661afc4..0000000 --- a/src/0004_dynamic_programming/0004_MinimumCostClimbingStairs.cc +++ /dev/null @@ -1,48 +0,0 @@ -#include "0004_MinimumCostClimbingStairs.h" -#include - -namespace MinimumCostClimbingStairs -{ - int DynamicProgramming::MinCostRecursive(size_t step, vector& cost) - { - if (step == 0 || step == 1) - { - return cost[step]; - } - - return cost[step] + min(this->MinCostRecursive(step - 1, cost), this->MinCostRecursive(step - 2, cost)); - } - - int DynamicProgramming::RecursiveMinimumCostClimbingStairs(vector& cost) - { - size_t totalSteps = cost.size(); - - if (totalSteps == 1) - { - return cost[0]; - } - - return min(this->MinCostRecursive(totalSteps - 1, cost), this->MinCostRecursive(totalSteps - 2, cost)); - } - - int DynamicProgramming::DpMinimumCostClimbingStairs(vector& cost) - { - size_t totalSteps = cost.size(); - vector dp(totalSteps, 0); - - if (totalSteps == 1) - { - return cost[0]; - } - - dp[0] = cost[0]; - dp[1] = cost[1]; - - for (size_t i = 2; i < totalSteps; i++) - { - dp[i] = cost[i] + min(dp[i - 1], dp[i - 2]); - } - - return min(dp[totalSteps - 1], dp[totalSteps - 2]); - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0005_HouseRobber1.cc b/src/0004_dynamic_programming/0005_HouseRobber1.cc deleted file mode 100644 index 2e3fb7f..0000000 --- a/src/0004_dynamic_programming/0005_HouseRobber1.cc +++ /dev/null @@ -1,44 +0,0 @@ -#include "0005_HouseRobber1.h" - -namespace HouseRobber1 -{ - int DynamicProgramming::MaxLootRecursive(size_t house, vector& houseValues) - { - if (house <= 0) - { - return 0; - } - - if (house == 1) - { - return houseValues[0]; - } - - int pickCurrentHouse = houseValues[house - 1] + this->MaxLootRecursive(house - 2, houseValues); - int dropCurrentHouse = this->MaxLootRecursive(house - 1, houseValues); - - return max(pickCurrentHouse, dropCurrentHouse); - } - - int DynamicProgramming::RecursiveMaximumLoot(vector& houseValues) - { - size_t totalNumberOfHouses = houseValues.size(); - return this->MaxLootRecursive(totalNumberOfHouses, houseValues); - } - - int DynamicProgramming::DpMaximumLoot(vector& houseValues) - { - size_t totalNumberOfHouses = houseValues.size(); - vector dp(totalNumberOfHouses + 1, 0); - - dp[0] = 0; - dp[1] = houseValues[0]; - - for (size_t i = 2; i <= totalNumberOfHouses; i++) - { - dp[i] = max(dp[i - 2] + houseValues[i - 1], dp[i - 1]); - } - - return dp[totalNumberOfHouses]; - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0006_HouseRobber2.cc b/src/0004_dynamic_programming/0006_HouseRobber2.cc deleted file mode 100644 index cbefdda..0000000 --- a/src/0004_dynamic_programming/0006_HouseRobber2.cc +++ /dev/null @@ -1,95 +0,0 @@ -#include "0006_HouseRobber2.h" - -namespace HouseRobber2 -{ - int DynamicProgramming::MaxLootRecursive(size_t house, vector& houseValues) - { - if (house <= 0) - { - return 0; - } - - if (house == 1) - { - return houseValues[0]; - } - - int pickCurrentHouse = houseValues[house - 1] + this->MaxLootRecursive(house - 2, houseValues); - int dropCurrentHouse = this->MaxLootRecursive(house - 1, houseValues); - - return max(pickCurrentHouse, dropCurrentHouse); - } - - int DynamicProgramming::MaxLootDp(size_t firstHouse, size_t lastHouse, vector& houseValues) - { - int totalNumberOfHouses = lastHouse - firstHouse + 1; - - if (totalNumberOfHouses == 0) - { - return 0; - } - - if (totalNumberOfHouses == 1) - { - return houseValues[firstHouse]; - } - - vector dp(totalNumberOfHouses, 0); - - dp[0] = houseValues[firstHouse]; - dp[1] = max(houseValues[firstHouse], houseValues[firstHouse + 1]); - - for (size_t i = 2; i < totalNumberOfHouses; i++) - { - dp[i] = max(houseValues[firstHouse + i] + dp[i - 2], dp[i - 1]); - } - - return dp[totalNumberOfHouses - 1]; - } - - int DynamicProgramming::RecursiveMaximumLoot(vector& houseValues) - { - if (houseValues.size() == 0) - { - return 0; - } - - if (houseValues.size() == 1) - { - return houseValues[0]; - } - - size_t totalNumberOfHouses = houseValues.size()-1; - - // Case 1: Exclude last house. - vector pickFirstHouse(houseValues.begin(), houseValues.end() - 1); - - // Case 2: Exlcude first house. - vector pickLastHouse(houseValues.begin() + 1, houseValues.end()); - - return max(this->MaxLootRecursive(totalNumberOfHouses, pickFirstHouse), this->MaxLootRecursive(totalNumberOfHouses, pickLastHouse)); - } - - int DynamicProgramming::DpMaximumLoot(vector& houseValues) - { - size_t totalNumberOfHouses = houseValues.size(); - - if (totalNumberOfHouses == 0) - { - return 0; - } - - if (totalNumberOfHouses == 1) - { - return houseValues[0]; - } - - // Case 1: Exclude last house. - int pickFirstHouse = this->MaxLootDp(0, totalNumberOfHouses - 2, houseValues); - - // Case 2: Exlcude first house. - int pickLastHouse = this->MaxLootDp(1, totalNumberOfHouses - 1, houseValues); - - return max(pickFirstHouse, pickLastHouse); - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0007_DecodeWays.cc b/src/0004_dynamic_programming/0007_DecodeWays.cc deleted file mode 100644 index bf93270..0000000 --- a/src/0004_dynamic_programming/0007_DecodeWays.cc +++ /dev/null @@ -1,61 +0,0 @@ -#include "0007_DecodeWays.h" - -namespace DecodeWays -{ - int DynamicProgramming::CountWaysRecursiveHelper(string& digits, size_t index) - { - size_t digitsLength = digits.size(); - - // Base case: If the end of the string is reached, return 1 as it signifies a valid decoding. - if (index >= digitsLength) - { - return 1; - } - - int ways = 0; - - // Single digit decoding: check if current digit is not '0'. - if (digits[index] != '0') - { - ways = this->CountWaysRecursiveHelper(digits, index + 1); - } - - // Two digit decoding: check if next two digits are valid. - if ((index + 1 < digitsLength) && ((digits[index] == '1' && digits[index + 1] <= '9') || (digits[index] == '2' && digits[index + 1] <= '6'))) - { - ways += this->CountWaysRecursiveHelper(digits, index + 2); - } - return ways; - } - - int DynamicProgramming::RecursiveCountWays(string digits) - { - return this->CountWaysRecursiveHelper(digits, 0); - } - - int DynamicProgramming::DpCountways(string digits) - { - size_t digitsLength = digits.size(); - - vector dp(digitsLength + 1, 0); - - dp[digitsLength] = 1; - - for (int index = digitsLength - 1; index >= 0; index--) - { - // Single digit decoding: check if current digit is not '0'. - if (digits[index] != '0') - { - dp[index] = dp[index + 1]; - } - - // Two digit decoding: check if next two digits are valid. - if ((index + 1 < digitsLength) && ((digits[index] == '1' && digits[index + 1] <= '9') || (digits[index] == '2' && digits[index + 1] <= '6'))) - { - dp[index] += dp[index + 2]; - } - } - - return dp[0]; - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0008_TilingProblem.cc b/src/0004_dynamic_programming/0008_TilingProblem.cc deleted file mode 100644 index d447c8d..0000000 --- a/src/0004_dynamic_programming/0008_TilingProblem.cc +++ /dev/null @@ -1,42 +0,0 @@ -#include "0008_TilingProblem.h" - -namespace TilingProblem -{ - int DynamicProgramming::NumberOfWaysRecursiveHelper(int n) - { - if (n < 0) - { - return 0; - } - - if (n == 0) - { - return 1; - } - - int result = 0; - result += this->NumberOfWaysRecursiveHelper(n - 1); - result += this->NumberOfWaysRecursiveHelper(n - 2); - - return result; - } - - int DynamicProgramming::RecursiveNumberOfWays(int n) - { - return this->NumberOfWaysRecursiveHelper(n); - } - - int DynamicProgramming::DpNumberOfWays(int n) - { - vector dp(n + 1, 0); - dp[0] = 1; - dp[1] = 1; - - for (int i = 2; i <= n; i++) - { - dp[i] = dp[i - 1] + dp[i - 2]; - } - - return dp[n]; - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0009_FriendsPairingProblem.cc b/src/0004_dynamic_programming/0009_FriendsPairingProblem.cc deleted file mode 100644 index fbea63f..0000000 --- a/src/0004_dynamic_programming/0009_FriendsPairingProblem.cc +++ /dev/null @@ -1,39 +0,0 @@ -#include "0009_FriendsPairingProblem.h" - -namespace FriendsPairingProblem -{ - // Dynamic Programming Private Member Methods. - int DynamicProgramming::CountFriendsPairingsRecursiveHelper(int n) - { - if (n <= 1) - { - return 1; - } - int result = 0; - result += this->CountFriendsPairingsRecursiveHelper(n - 1); - result += (n - 1) * this->CountFriendsPairingsRecursiveHelper(n - 2); - - return result; - } - - // Dynamic Programming Public Member Methods. - int DynamicProgramming::RecursiveCountFriendsPairings(int n) - { - return this->CountFriendsPairingsRecursiveHelper(n); - } - - int DynamicProgramming::DpCountFriendsPairings(int n) - { - vector dp(n + 1, 0); - dp[0] = 0; - dp[1] = 1; - dp[2] = 2; - - for (int i = 3; i <= n; i++) - { - dp[i] = dp[i - 1] + (i - 1) * dp[i - 2]; - } - - return dp[n]; - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0010_WaysToCoverDistance.cc b/src/0004_dynamic_programming/0010_WaysToCoverDistance.cc deleted file mode 100644 index b2f0bce..0000000 --- a/src/0004_dynamic_programming/0010_WaysToCoverDistance.cc +++ /dev/null @@ -1,52 +0,0 @@ -#include "0010_WaysToCoverDistance.h" - -namespace WaysToCoverDistance -{ - // Dynamic Programming Private Member Methods. - int DynamicProgramming::WaysToCoverDistanceRecursiveHelper(int dist) - { - if (dist < 0) - { - return 0; - } - - if (dist == 0) - { - return 1; - } - - int result = 0; - result += this->WaysToCoverDistanceRecursiveHelper(dist - 1); - result += this->WaysToCoverDistanceRecursiveHelper(dist - 2); - result += this->WaysToCoverDistanceRecursiveHelper(dist - 3); - - return result; - } - - // Dynamic Programming Public Member Methods. - int DynamicProgramming::RecursiveWaysToCoverDistance(int dist) - { - return this->WaysToCoverDistanceRecursiveHelper(dist); - } - - int DynamicProgramming::DpWaysToCoverDistance(int dist) - { - vector dp(dist + 1, 0); - dp[0] = 1; - if (dist >= 1) - { - dp[1] = 1; - } - if (dist >= 2) - { - dp[2] = 2; - } - - for(int i = 3; i <= dist; i++) - { - dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]; - } - - return dp[dist]; - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrder.cc b/src/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrder.cc deleted file mode 100644 index f4467e2..0000000 --- a/src/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrder.cc +++ /dev/null @@ -1,44 +0,0 @@ -#include "0011_CountWaysToReachNthStairIncludeOrder.h" - -namespace CountWaysToReachNthStairIncludeOrder -{ - // Dynamic Programming Private Member Methods. - int DynamicProgramming::RecursiveCountWaysToReachNthStairIncludeOrderHelper(int n) - { - if (n < 0) - { - return 0; - } - if (n == 0 || n == 1) - { - return 1; - } - - int result = 0; - result += this->RecursiveCountWaysToReachNthStairIncludeOrderHelper(n - 1); - result += this->RecursiveCountWaysToReachNthStairIncludeOrderHelper(n - 2); - - return result; - } - - // Dynamic Programming Public Member Methods. - int DynamicProgramming::RecursiveCountWaysToReachNthStairIncludeOrder(int n) - { - return this->RecursiveCountWaysToReachNthStairIncludeOrderHelper(n); - } - - int DynamicProgramming::DpCountWaysToReachNthStairIncludeOrder(int n) - { - vector dp(n + 1, 0); - dp[0] = 1; - if (n >= 1) - { - dp[1] = 1; - } - for(int i = 2; i <= n; i++) - { - dp[i] = dp[i - 1] + dp[i - 2]; - } - return dp[n]; - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrder.cc b/src/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrder.cc deleted file mode 100644 index 0e71a69..0000000 --- a/src/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrder.cc +++ /dev/null @@ -1,53 +0,0 @@ -#include "0012_CountWaysToReachNthStairExcludeOrder.h" - -namespace CountWaysToReachNthStairExcludeOrder -{ - // notes: - /* - To avoid counting ways which only differ in order, we can assume that a person initially takes only steps of size 1 followed by steps of size 2. - In other words, once a person takes a step of size 2, he will continue taking steps of size 2 till he reaches the nth stair. - A person can reach nth stair from either(n - 1)th stair or from(n - 2)th stair.So, there are two cases : - The person has reached nth step from(n - 1)th step, this means that the last step was of size 1 and all the previous steps should also be of size 1. So, there is only 1 way. - The person has reached nth step from(n - 2)th step, this means that the last step was of size 2 and the previous steps can either be of size 1 or size 2. - Therefore the Recurrence relation will be : - - nthStair(n) = 1 (last step was of size 1) + nthStair(n - 2) (last step was of size 2) - so f(n) = 1 + f(n - 2) - */ - - // Dynamic Programming Private Member Methods. - int DynamicProgramming::RecursiveCountWaysToReachNthStairExcludeOrderHelper(int n) - { - if (n < 0) - { - return 0; - } - if (n == 0) - { - return 1; - } - - return 1 + this->RecursiveCountWaysToReachNthStairExcludeOrderHelper(n - 2); - } - - // Dynamic Programming Public Member Methods. - int DynamicProgramming::RecursiveCountWaysToReachNthStairExcludeOrder(int n) - { - return this->RecursiveCountWaysToReachNthStairExcludeOrderHelper(n); - } - - int DynamicProgramming::DpCountWaysToReachNthStairExcludeOrder(int n) - { - vector dp(n + 1, 0); - dp[0] = 1; - if (n >= 1) - { - dp[1] = 1; - } - for (int i = 2; i <= n; i++) - { - dp[i] = 1 + dp[i - 2]; - } - return dp[n]; - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0013_KnapsackProblem.cc b/src/0004_dynamic_programming/0013_KnapsackProblem.cc deleted file mode 100644 index e9e5ba2..0000000 --- a/src/0004_dynamic_programming/0013_KnapsackProblem.cc +++ /dev/null @@ -1,78 +0,0 @@ -#include "0013_KnapsackProblem.h" - -namespace KnapsackProblem -{ - // Dynamic Programming Private Member Methods. - int DynamicProgramming::KnapsackRecursiveHelper(int capacity, vector& weight, vector& profit, int numberOfItems) - { - if (capacity <= 0 || numberOfItems == 0) - { - return 0; - } - - int pickCurrentItem = 0; - - // Pick the current item only if does not exceed the capacity. - if (weight[numberOfItems - 1] <= capacity) - { - pickCurrentItem = profit[numberOfItems - 1] + this->KnapsackRecursiveHelper(capacity - weight[numberOfItems - 1], weight, profit, numberOfItems - 1); - } - - int dropCurrentItem = this->KnapsackRecursiveHelper(capacity, weight, profit, numberOfItems - 1); - - return max(pickCurrentItem, dropCurrentItem); - } - - // Dynamic Programming Public Member Methods. - int DynamicProgramming::RecursiveKnapsack(int capacity, vector weight, vector profit) - { - size_t totalNumberOfItems = weight.size(); - return this->KnapsackRecursiveHelper(capacity, weight, profit, totalNumberOfItems); - } - - int DynamicProgramming::DpKnapsack(int capacity, vector weight, vector profit) - { - int numberOfItems = weight.size(); - vector> dp(numberOfItems + 1, vector(capacity + 1, 0)); - - for (int i = 0; i <= numberOfItems; i++) - { - for (int j = 0; j <= capacity; j++) - { - if (i == 0 || j == 0) - { - dp[i][j] = 0; - } - else - { - int pickCurrentItem = 0; - if (weight[i - 1] <= j) - { - pickCurrentItem = profit[i - 1] + dp[i - 1][j - weight[i - 1]]; - } - int dropCurrentItem = dp[i - 1][j]; - - dp[i][j] = max(pickCurrentItem, dropCurrentItem); - } - } - } - - return dp[numberOfItems][capacity]; - } - - int DynamicProgramming::DpKnapsackSpaceOptimized(int capacity, vector weight, vector profit) - { - int numberOfItems = weight.size(); - vector dp(capacity + 1, 0); - - for (int i = 1; i <= numberOfItems; i++) - { - for (int j = capacity; j >= weight[i - 1]; j--) - { - dp[j] = max(dp[j], profit[i - 1] + dp[j - weight[i - 1]]); - } - } - - return dp[capacity]; - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0014_SubsetSumProblem.cc b/src/0004_dynamic_programming/0014_SubsetSumProblem.cc deleted file mode 100644 index 7f558ba..0000000 --- a/src/0004_dynamic_programming/0014_SubsetSumProblem.cc +++ /dev/null @@ -1,71 +0,0 @@ -#include "0014_SubsetSumProblem.h" - -namespace SubsetSumProblem -{ - // Dynamic Programming Private Member Methods. - bool DynamicProgramming::SubsetSumRecursiveHelper(vector& nums, int sum, int numberOfElements) - { - // Base case. - // If the sum is 0, we found a subset with a given sum. - if (sum == 0) - { - return true; - } - - // Base case. - // If there are no elements left to process and the sum is not 0 yet, we did not find a subset with given sum, so return false. - if (numberOfElements == 0) - { - return false; - } - - // When the current element is greater than the sum, we skip it, as all elemeents are non-negative. - if (nums[numberOfElements - 1] > sum) - { - return this->SubsetSumRecursiveHelper(nums, sum, numberOfElements - 1); - } - - // When the current element is equal to or less than the sum, we have two choices. - // 1. Include the current element in the subset and the sum is reduced by the current element value and also the number of elements is reducded by 1. - // 2. Exclude the current element from the subset and the sum remains the same but the number of eleements is reduced by 1. - // If either of these two choices return true, we return true. - return this->SubsetSumRecursiveHelper(nums, sum - nums[numberOfElements - 1], numberOfElements - 1) || this->SubsetSumRecursiveHelper(nums, sum, numberOfElements - 1); - } - - // Dynamic Programming Public Member Methods. - bool DynamicProgramming::RecursiveSubsetSum(vector nums, int sum) - { - int numberOfElements = nums.size(); - return this->SubsetSumRecursiveHelper(nums, sum, numberOfElements); - } - - bool DynamicProgramming::DpIsSubsetSum(vector nums, int sum) - { - int numberOfElements = nums.size(); - vector> dp(numberOfElements + 1, vector(sum + 1, false)); - - // When the sum is 0, the result is true - for (int i = 0; i < numberOfElements; i++) - { - dp[i][0] = true; - } - - for (int i = 1; i < numberOfElements + 1; i++) - { - for (int j = 1; j < sum + 1; j++) - { - if (j < nums[i - 1]) - { - dp[i][j] = dp[i - 1][j]; - } - else - { - // include or exclude the current element - dp[i][j] = (dp[i-1][j-nums[i-1]] || dp[i-1][j]); - } - } - } - - return dp[numberOfElements][sum]; - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0015_CountSubsetsForSum.cc b/src/0004_dynamic_programming/0015_CountSubsetsForSum.cc deleted file mode 100644 index 64d75b6..0000000 --- a/src/0004_dynamic_programming/0015_CountSubsetsForSum.cc +++ /dev/null @@ -1,55 +0,0 @@ -#include "0015_CountSubsetsForSum.h" - -namespace CountSubsetsForSum -{ - // Dynamic Programming private member methods - int DynamicProgramming::RecursiveCountSubsetsHelper(vector& nums, int targetSum, int currentSum, int index) - { - int noOfElements = nums.size(); - if (index == noOfElements) - { - return (targetSum == currentSum); - } - - int exclude = this->RecursiveCountSubsetsHelper(nums, targetSum, currentSum, index + 1); - int include = 0; - - if ((nums[index] + currentSum) <= targetSum) - { - include = this->RecursiveCountSubsetsHelper(nums, targetSum, currentSum + nums[index], index + 1); - } - - return (exclude + include); - } - - // Dynamic Programming public member methods - int DynamicProgramming::RecursiveCountSubsets(vector nums, int sum) - { - return this->RecursiveCountSubsetsHelper(nums, sum, 0, 0); - } - - int DynamicProgramming::DpCountSubsets(vector nums, int sum) - { - int noOfElements = nums.size(); - vector> dp(noOfElements + 1, vector(sum + 1, 0)); - - dp[0][0] = 1; - - for (int i = 1; i <= noOfElements; i++) - { - for (int j = 0; j <= sum; j++) - { - // Considering excluding the current element - dp[i][j] = dp[i - 1][j]; - - // Case to include the current element - if (nums[i - 1] <= j) - { - dp[i][j] += dp[i - 1][j - nums[i - 1]]; - } - } - } - - return dp[noOfElements][sum]; - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0016_PartitionEqualSubsetSum.cc b/src/0004_dynamic_programming/0016_PartitionEqualSubsetSum.cc deleted file mode 100644 index 2db0dab..0000000 --- a/src/0004_dynamic_programming/0016_PartitionEqualSubsetSum.cc +++ /dev/null @@ -1,75 +0,0 @@ -#include "0016_PartitionEqualSubsetSum.h" - -namespace PartitionEqualSubsetSum -{ - bool DynamicProgramming::RecursivePartitionEqualSubsetsHelper(vector& nums, int targetSum, int numberOfElements) - { - if (targetSum == 0) - { - return true; - } - - if (numberOfElements == 0) - { - return false; - } - - if (nums[numberOfElements - 1] > targetSum) - { - return this->RecursivePartitionEqualSubsetsHelper(nums, targetSum, numberOfElements - 1); - } - - return (this->RecursivePartitionEqualSubsetsHelper(nums, targetSum - nums[numberOfElements - 1], numberOfElements - 1) || this->RecursivePartitionEqualSubsetsHelper(nums, targetSum, numberOfElements - 1)); - } - - bool DynamicProgramming::RecursivePartitionEqualSubsets(vector nums) - { - int targetSum = accumulate(nums.begin(), nums.end(), 0); - - // Check if targetSum is odd, then equal partition is not possible at all - if (targetSum % 2 != 0) - { - return false; - } - - int numberOfElements = nums.size(); - return this->RecursivePartitionEqualSubsetsHelper(nums, targetSum / 2, numberOfElements); - } - - bool DynamicProgramming::DpPartitionEqualSubsets(vector nums) - { - int targetSum = accumulate(nums.begin(), nums.end(), 0); - - // Check if targetSum is odd, then equal partition is not possible at all - if (targetSum % 2 != 0) - { - return false; - } - - int numberOfElements = nums.size(); - targetSum /= 2; - vector> dp(numberOfElements + 1, vector(targetSum + 1, false)); - - for (int i = 0; i <= numberOfElements; i++) - { - dp[i][0] = true; - } - - for (int i = 1; i <= numberOfElements; i++) - { - for (int j = 1; j <= targetSum; j++) - { - if (nums[i - 1] > j) - { - dp[i][j] = dp[i - 1][j]; - } - else - { - dp[i][j] = (dp[i-1][j-nums[i-1]] || dp[i-1][j]); - } - } - } - - return dp[numberOfElements][targetSum]; - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0017_TargetSum.cc b/src/0004_dynamic_programming/0017_TargetSum.cc deleted file mode 100644 index c92fe77..0000000 --- a/src/0004_dynamic_programming/0017_TargetSum.cc +++ /dev/null @@ -1,70 +0,0 @@ -#include "0017_TargetSum.h" - -namespace TargetSum -{ - int DynamicProgramming::RecursiveFindTotalWaysHelper(vector& nums, int currentSum, int targetSum, int index) - { - // Base case - if (currentSum == targetSum && index == nums.size()) - { - return 1; - } - - if (index >= nums.size()) - { - return 0; - } - - // Return total count of two possible ways while considering the current element - // 1. Add the current element to currentSum - // 2. Subtract the current element from currentSum - return ( - this->RecursiveFindTotalWaysHelper(nums, currentSum + nums[index], targetSum, index + 1) - + - this->RecursiveFindTotalWaysHelper(nums, currentSum - nums[index], targetSum, index + 1)); - } - - int DynamicProgramming::RecursiveFindTotalWays(vector nums, int target) - { - return this->RecursiveFindTotalWaysHelper(nums, 0, target, 0); - } - - int DynamicProgramming::DpFindTotalWays(vector nums, int target) - { - int totalSum = accumulate(nums.begin(), nums.end(), 0); - - if (abs(target) > totalSum) - { - return 0; - } - - int totalSumWithTarget = totalSum + target; - if (totalSumWithTarget % 2 != 0) - { - return 0; - } - - int targetSubsetSum = totalSumWithTarget / 2; - int noOfElements = nums.size(); - vector> dp(noOfElements + 1, vector(targetSubsetSum + 1, 0)); - - dp[0][0] = 1; - - for (int i = 1; i <= noOfElements; i++) - { - for (int j = 0; j <= targetSubsetSum; j++) - { - // Considering excluding the current element - dp[i][j] = dp[i - 1][j]; - - // Case to include the current element - if (nums[i - 1] <= j) - { - dp[i][j] += dp[i - 1][j - nums[i - 1]]; - } - } - } - - return dp[noOfElements][targetSubsetSum]; - } -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/CMakeLists.txt b/src/0004_dynamic_programming/CMakeLists.txt deleted file mode 100644 index b063b19..0000000 --- a/src/0004_dynamic_programming/CMakeLists.txt +++ /dev/null @@ -1,28 +0,0 @@ -# Specify the source files -set(0005DYNAMICPROGRAMMING_SOURCES - 0001_FibonacciNumber.cc - 0002_TribonacciNumber.cc - 0003_ClimbingStairs.cc - 0004_MinimumCostClimbingStairs.cc - 0005_HouseRobber1.cc - 0006_HouseRobber2.cc - 0007_DecodeWays.cc - 0008_TilingProblem.cc - 0009_FriendsPairingProblem.cc - 0010_WaysToCoverDistance.cc - 0011_CountWaysToReachNthStairIncludeOrder.cc - 0012_CountWaysToReachNthStairExcludeOrder.cc - 0013_KnapsackProblem.cc - 0014_SubsetSumProblem.cc - 0015_CountSubsetsForSum.cc - 0016_PartitionEqualSubsetSum.cc - 0017_TargetSum.cc - -) - -# Create a library target -add_library(0005DYNAMICPROGRAMMING ${0005DYNAMICPROGRAMMING_SOURCES}) - -target_include_directories(0005DYNAMICPROGRAMMING PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/headers -) \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0001_FibonacciNumber.h b/src/0004_dynamic_programming/headers/0001_FibonacciNumber.h deleted file mode 100644 index 204aeba..0000000 --- a/src/0004_dynamic_programming/headers/0001_FibonacciNumber.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once -#include -using namespace std; - -/* -Pattern 1 -Linear Recurrence - -Description -Print the n'th Fibonacci number. - -*/ - -namespace FibonacciNumber -{ - class DynamicProgramming - { - private: - public: - int RecursiveNthFibonacci(int n); - int DpNthFibonacci(int n); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0002_TribonacciNumber.h b/src/0004_dynamic_programming/headers/0002_TribonacciNumber.h deleted file mode 100644 index 31e805f..0000000 --- a/src/0004_dynamic_programming/headers/0002_TribonacciNumber.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once -#include -using namespace std; - -/* -Pattern 1 -Linear Recurrence - -Description -Print the n'th Tribonacci number. - -*/ - -namespace TribonacciNumber -{ - class DynamicProgramming - { - private: - public: - int RecursiveNthTribonacci(int n); - int DpNthTribonacci(int n); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0003_ClimbingStairs.h b/src/0004_dynamic_programming/headers/0003_ClimbingStairs.h deleted file mode 100644 index e32b71a..0000000 --- a/src/0004_dynamic_programming/headers/0003_ClimbingStairs.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once -#include -using namespace std; - -/* -Pattern 1 -Linear Recurrence - -Description -There are n stairs, and a person standing at the bottom wants to climb stairs to reach the top. -The person can climb either 1 stair or 2 stairs at a time, the task is to count the number of ways that a person can reach at the top. - -*/ - -namespace ClimbingStairs -{ - class DynamicProgramming - { - private: - public: - int RecursiveCountWays(int n); - int DpCountWays(int n); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0004_MinimumCostClimbingStairs.h b/src/0004_dynamic_programming/headers/0004_MinimumCostClimbingStairs.h deleted file mode 100644 index 9ef1ec8..0000000 --- a/src/0004_dynamic_programming/headers/0004_MinimumCostClimbingStairs.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once -#include -using namespace std; - -/* -Pattern 1 -Linear Recurrence - -Description -Given an array of integers cost[] of length n, where cost[i] is the cost of the ith step on a staircase. Once the cost is paid, we can either climb 1 or 2 steps. -We can either start from the step with index 0, or the step with index 1. The task is to find the minimum cost to reach the top. - -*/ - -namespace MinimumCostClimbingStairs -{ - class DynamicProgramming - { - private: - int MinCostRecursive(size_t step, vector& cost); - public: - int RecursiveMinimumCostClimbingStairs(vector& cost); - int DpMinimumCostClimbingStairs(vector& cost); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0005_HouseRobber1.h b/src/0004_dynamic_programming/headers/0005_HouseRobber1.h deleted file mode 100644 index 231fbba..0000000 --- a/src/0004_dynamic_programming/headers/0005_HouseRobber1.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once -#include -using namespace std; - -/* -Pattern 1 -Linear Recurrence - -Description -There are n houses built in a line, each of which contains some money in it. -A robber wants to steal money from these houses, but he can’t steal from two adjacent houses. The task is to find the maximum amount of money which can be stolen. - -*/ - -namespace HouseRobber1 -{ - class DynamicProgramming - { - private: - int MaxLootRecursive(size_t house, vector& houseValues); - public: - int RecursiveMaximumLoot(vector& houseValues); - int DpMaximumLoot(vector& houseValues); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0006_HouseRobber2.h b/src/0004_dynamic_programming/headers/0006_HouseRobber2.h deleted file mode 100644 index 74c3c93..0000000 --- a/src/0004_dynamic_programming/headers/0006_HouseRobber2.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once -#include -using namespace std; - -/* -Pattern 1 -Linear Recurrence - -Description -You are given an array arr[] which represents houses arranged in a circle, where each house has a certain value. A thief aims to maximize the total stolen value without robbing two adjacent houses. -Determine the maximum amount the thief can steal. - -Note: Since the houses are in a circle, the first and last houses are also considered adjacent. - -*/ - -namespace HouseRobber2 -{ - class DynamicProgramming - { - private: - int MaxLootRecursive(size_t house, vector& houseValues); - int MaxLootDp(size_t firstHouse, size_t lastHouse, vector& houseValues); - public: - int RecursiveMaximumLoot(vector& houseValues); - int DpMaximumLoot(vector& houseValues); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0007_DecodeWays.h b/src/0004_dynamic_programming/headers/0007_DecodeWays.h deleted file mode 100644 index fe2b6ce..0000000 --- a/src/0004_dynamic_programming/headers/0007_DecodeWays.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once - -#include -#include -using namespace std; - -/* -Pattern 1 -Linear Recurrence - -Description -Let 1 maps to 'A', 2 maps to 'B', ..., 26 to 'Z'.Given a digit sequence, count the number of possible decodings of the given digit sequence. - -Consider the input string "123".There are three valid ways to decode it : -"ABC" : The grouping is(1, 2, 3) -> 'A', 'B', 'C' -"AW" : The grouping is(1, 23) -> 'A', 'W' -"LC" : The grouping is(12, 3) -> 'L', 'C' -Note : Groupings that contain invalid codes(e.g., "0" by itself or numbers greater than "26") are not allowed. -For instance, the string "230" is invalid because "0" cannot stand alone, and "30" is greater than "26", so it cannot represent any letter.The task is to find the total number of valid ways to decode a given string. -*/ - -namespace DecodeWays -{ - class DynamicProgramming - { - private: - int CountWaysRecursiveHelper(string& digits, size_t index); - public: - int RecursiveCountWays(string digits); - int DpCountways(string digits); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0008_TilingProblem.h b/src/0004_dynamic_programming/headers/0008_TilingProblem.h deleted file mode 100644 index e9befb0..0000000 --- a/src/0004_dynamic_programming/headers/0008_TilingProblem.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -#include -using namespace std; - -/* -Pattern 1 -Linear Recurrence - -Description -Given a "2 x n" board and tiles of size "2 x 1", the task is to count the number of ways to tile the given board using the 2 x 1 tiles. -A tile can either be placed horizontally i.e., as a 1 x 2 tile or vertically i.e., as 2 x 1 tile. -*/ - -namespace TilingProblem -{ - class DynamicProgramming - { - private: - int NumberOfWaysRecursiveHelper(int n); - public: - int RecursiveNumberOfWays(int n); - int DpNumberOfWays(int n); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0009_FriendsPairingProblem.h b/src/0004_dynamic_programming/headers/0009_FriendsPairingProblem.h deleted file mode 100644 index 79cd9da..0000000 --- a/src/0004_dynamic_programming/headers/0009_FriendsPairingProblem.h +++ /dev/null @@ -1,46 +0,0 @@ -#pragma once - -#include -using namespace std; - -/* -Pattern 1 -Linear Recurrence - -Description -Given n friends, each one can remain single or can be paired up with some other friend. Each friend can be paired only once. Find out the total number of ways in which friends can remain single or can be paired up. - -Examples: - -Input : n = 3 -Output : 4 -Explanation: -{1}, {2}, {3} : all single -{1}, {2, 3} : 2 and 3 paired but 1 is single. -{1, 2}, {3} : 1 and 2 are paired but 3 is single. -{1, 3}, {2} : 1 and 3 are paired but 2 is single. -Note that {1, 2} and {2, 1} are considered same. - -Mathematical Explanation: -The problem is simplified version of how many ways we can divide n elements into multiple groups. -(here group size will be max of 2 elements). -In case of n = 3, we have only 2 ways to make a group: - 1) all elements are individual(1,1,1) - 2) a pair and individual (2,1) -In case of n = 4, we have 3 ways to form a group: - 1) all elements are individual (1,1,1,1) - 2) 2 individuals and one pair (2,1,1) - 3) 2 separate pairs (2,2) -*/ - -namespace FriendsPairingProblem -{ - class DynamicProgramming - { - private: - int CountFriendsPairingsRecursiveHelper(int n); - public: - int RecursiveCountFriendsPairings(int n); - int DpCountFriendsPairings(int n); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0010_WaysToCoverDistance.h b/src/0004_dynamic_programming/headers/0010_WaysToCoverDistance.h deleted file mode 100644 index 0268ff5..0000000 --- a/src/0004_dynamic_programming/headers/0010_WaysToCoverDistance.h +++ /dev/null @@ -1,47 +0,0 @@ -#pragma once - -#include -using namespace std; - -/* -Pattern 1 -Linear Recurrence - -Description -Given a distance 'dist', count total number of ways to cover the distance with 1, 2 and 3 steps. - -Examples: - -Input: n = 3 -Output: 4 -Explanation: Below are the four ways -=> 1 step + 1 step + 1 step -=> 1 step + 2 step -=> 2 step + 1 step -=> 3 step - - - -Input: n = 4 -Output: 7 -Explanation: Below are the four ways -=> 1 step + 1 step + 1 step + 1 step -=> 1 step + 2 step + 1 step -=> 2 step + 1 step + 1 step -=> 1 step + 1 step + 2 step -=> 2 step + 2 step -=> 3 step + 1 step -=> 1 step + 3 step -*/ - -namespace WaysToCoverDistance -{ - class DynamicProgramming - { - private: - int WaysToCoverDistanceRecursiveHelper(int dist); - public: - int RecursiveWaysToCoverDistance(int dist); - int DpWaysToCoverDistance(int dist); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0011_CountWaysToReachNthStairIncludeOrder.h b/src/0004_dynamic_programming/headers/0011_CountWaysToReachNthStairIncludeOrder.h deleted file mode 100644 index 6851031..0000000 --- a/src/0004_dynamic_programming/headers/0011_CountWaysToReachNthStairIncludeOrder.h +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once - -#include -using namespace std; - -/* -Pattern 1 -Linear Recurrence - -Description -There are n stairs, and a person standing at the bottom wants to climb stairs to reach the top. -The person can climb either 1 stair or 2 stairs at a time, the task is to count the number of ways that a person can reach at the top. - -Note: This problem is similar to Count ways to reach Nth stair (Order does not matter) with the only difference that in this problem, -we count all distinct ways where different orderings of the steps are considered unique. - -Examples: - -Input: n = 1 -Output: 1 -Explanation: There is only one way to climb 1 stair. - -Input: n = 2 -Output: 2 -Explanation: There are two ways to reach 2th stair: {1, 1} and {2}. - -Input: n = 4 -Output: 5 -Explanation: There are five ways to reach 4th stair: {1, 1, 1, 1}, {1, 1, 2}, {2, 1, 1}, {1, 2, 1} and {2, 2}. -*/ - -namespace CountWaysToReachNthStairIncludeOrder -{ - class DynamicProgramming - { - private: - int RecursiveCountWaysToReachNthStairIncludeOrderHelper(int n); - public: - int RecursiveCountWaysToReachNthStairIncludeOrder(int n); - int DpCountWaysToReachNthStairIncludeOrder(int n); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0012_CountWaysToReachNthStairExcludeOrder.h b/src/0004_dynamic_programming/headers/0012_CountWaysToReachNthStairExcludeOrder.h deleted file mode 100644 index 4d52930..0000000 --- a/src/0004_dynamic_programming/headers/0012_CountWaysToReachNthStairExcludeOrder.h +++ /dev/null @@ -1,44 +0,0 @@ -#pragma once - -#include -using namespace std; - -/* -Pattern 1 -Linear Recurrence - -Description -There are n stairs, and a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top (order does not matter). - -Note: The problem is similar to Climbing Stairs - Count ways to reach Nth stair with the only difference that in this problem, we don't have to count those ways which only differ in ordering of the steps. - -Examples: - -Input: n = 1 -Output: 1 -Explanation: There is only one way to climb 1 stair. - -Input: n = 2 -Output: 2 -Explanation: There are two ways to climb 2 stairs: {1, 1} and {2}. - -Input: n = 4 -Output: 3 -Explanation: Three ways to reach 4th stair: {1, 1, 1, 1}, {1, 1, 2} and {2, 2}. - -Input: n = 5 -Output: 3 -Explanation: Three ways to reach 5th stair: {1, 1, 1, 1, 1}, {1, 1, 1, 2} and {1, 2, 2}. -*/ - -namespace CountWaysToReachNthStairExcludeOrder -{ - class DynamicProgramming - { - private: - int RecursiveCountWaysToReachNthStairExcludeOrderHelper(int n); - public: - int RecursiveCountWaysToReachNthStairExcludeOrder(int n); - int DpCountWaysToReachNthStairExcludeOrder(int n); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0013_KnapsackProblem.h b/src/0004_dynamic_programming/headers/0013_KnapsackProblem.h deleted file mode 100644 index b7c90aa..0000000 --- a/src/0004_dynamic_programming/headers/0013_KnapsackProblem.h +++ /dev/null @@ -1,34 +0,0 @@ -#pragma once - -#include -using namespace std; - -/* -Pattern 2 -Subset / 0-1 Knapsack - -Description -Given n items where each item has some weight and profit associated with it and also given a bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items into the bag such that the sum of profits associated with them is the maximum possible. - -Note: The constraint here is we can either put an item completely into the bag or cannot put it at all [It is not possible to put a part of an item into the bag]. - -Input: W = 4, profit[] = [1, 2, 3], weight[] = [4, 5, 1] -Output: 3 -Explanation: There are two items which have weight less than or equal to 4. If we select the item with weight 4, the possible profit is 1. And if we select the item with weight 1, the possible profit is 3. So the maximum possible profit is 3. Note that we cannot put both the items with weight 4 and 1 together as the capacity of the bag is 4. - -Input: W = 3, profit[] = [1, 2, 3], weight[] = [4, 5, 6] -Output: 0 -*/ - -namespace KnapsackProblem -{ - class DynamicProgramming - { - private: - int KnapsackRecursiveHelper(int capacity, vector& weight, vector& profit, int numberOfItems); - public: - int RecursiveKnapsack(int capacity, vector weight, vector profit); - int DpKnapsack(int capacity, vector weight, vector profit); - int DpKnapsackSpaceOptimized(int capacity, vector weight, vector profit); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0014_SubsetSumProblem.h b/src/0004_dynamic_programming/headers/0014_SubsetSumProblem.h deleted file mode 100644 index 399d328..0000000 --- a/src/0004_dynamic_programming/headers/0014_SubsetSumProblem.h +++ /dev/null @@ -1,34 +0,0 @@ -#pragma once - -#include -using namespace std; - -/* -Pattern 2 -Subset / 0-1 Knapsack - -Description -Given an array arr[] of non-negative integers and a value sum, the task is to check if there is a subset of the given array whose sum is equal to the given sum. - -Examples: - -Input: arr[] = [3, 34, 4, 12, 5, 2], sum = 9 -Output: True -Explanation: There is a subset (4, 5) with sum 9. - -Input: arr[] = [3, 34, 4, 12, 5, 2], sum = 30 -Output: False -Explanation: There is no subset that add up to 30. -*/ - -namespace SubsetSumProblem -{ - class DynamicProgramming - { - private: - bool SubsetSumRecursiveHelper(vector& nums, int sum, int numberOfElements); - public: - bool RecursiveSubsetSum(vector nums, int sum); - bool DpIsSubsetSum(vector nums, int sum); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0015_CountSubsetsForSum.h b/src/0004_dynamic_programming/headers/0015_CountSubsetsForSum.h deleted file mode 100644 index 4f55bbf..0000000 --- a/src/0004_dynamic_programming/headers/0015_CountSubsetsForSum.h +++ /dev/null @@ -1,34 +0,0 @@ -#pragma once - -#include -using namespace std; - -/* -Pattern 2 -Subset / 0-1 Knapsack - -Description -Given an array arr[] of length n and an integer target, the task is to find the number of subsets with a sum equal to target. - -Examples: - -Input: arr[] = [1, 2, 3, 3], target = 6 -Output: 3 -Explanation: All the possible subsets are [1, 2, 3], [1, 2, 3] and [3, 3] - -Input: arr[] = [1, 1, 1, 1], target = 1 -Output: 4 -Explanation: All the possible subsets are [1], [1], [1] and [1] -*/ - -namespace CountSubsetsForSum -{ - class DynamicProgramming - { - private: - int RecursiveCountSubsetsHelper(vector& nums, int targetSum, int currentSum, int index); - public: - int RecursiveCountSubsets(vector nums, int sum); - int DpCountSubsets(vector nums, int sum); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0016_PartitionEqualSubsetSum.h b/src/0004_dynamic_programming/headers/0016_PartitionEqualSubsetSum.h deleted file mode 100644 index bf3c261..0000000 --- a/src/0004_dynamic_programming/headers/0016_PartitionEqualSubsetSum.h +++ /dev/null @@ -1,36 +0,0 @@ -#pragma once - -#include -#include -using namespace std; - -/* -Pattern 2 -Subset / 0-1 Knapsack - -Description -Given an array arr[], check if it can be partitioned into two parts such that the sum of elements in both parts is the same. -Note: Each element is present in either the first subset or the second subset, but not in both. - -Examples: - -Input: arr[] = [1, 5, 11, 5] -Output: true -Explanation: The array can be partitioned as [1, 5, 5] and [11] and the sum of both the subsets are equal. - -Input: arr[] = [1, 5, 3] -Output: false -Explanation: The array cannot be partitioned into equal sum sets. -*/ - -namespace PartitionEqualSubsetSum -{ - class DynamicProgramming - { - private: - bool RecursivePartitionEqualSubsetsHelper(vector& nums, int targetSum, int numberOfElements); - public: - bool RecursivePartitionEqualSubsets(vector nums); - bool DpPartitionEqualSubsets(vector nums); - }; -} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0017_TargetSum.h b/src/0004_dynamic_programming/headers/0017_TargetSum.h deleted file mode 100644 index 1ee27ad..0000000 --- a/src/0004_dynamic_programming/headers/0017_TargetSum.h +++ /dev/null @@ -1,45 +0,0 @@ -#pragma once - -#include -#include -using namespace std; - -/* -Pattern 2 -Subset / 0-1 Knapsack - -Description -Given an array arr[] of length N and an integer target. -You want to build an expression out of arr[] by adding one of the symbols '+' and '-' before each integer in arr[] and then concatenate all the integers. -Return the number of different expressions that can be built, which evaluates to target. - -Example: - -Input : N = 5, arr[] = {1, 1, 1, 1, 1}, target = 3 -Output: 5 -Explanation: -There are 5 ways to assign symbols to -make the sum of array be target 3. - --1 + 1 + 1 + 1 + 1 = 3 -+1 - 1 + 1 + 1 + 1 = 3 -+1 + 1 - 1 + 1 + 1 = 3 -+1 + 1 + 1 - 1 + 1 = 3 -+1 + 1 + 1 + 1 - 1 = 3 - -Input: N = 1, arr[] = {1}, target = 1 -Output: 1 -*/ - -namespace TargetSum -{ - class DynamicProgramming - { - private: - int RecursiveFindTotalWaysHelper(vector& nums, int currentSum, int targetSum, int index); - int DpFindTotalWays(); - public: - int RecursiveFindTotalWays(vector nums, int target); - int DpFindTotalWays(vector nums, int target); - }; -} \ No newline at end of file diff --git a/src/0005_greedy_algorithms/CMakeLists.txt b/src/0005_greedy_algorithms/CMakeLists.txt deleted file mode 100644 index e69de29..0000000 diff --git a/src/0006_bitwise_algorithms/CMakeLists.txt b/src/0006_bitwise_algorithms/CMakeLists.txt deleted file mode 100644 index e69de29..0000000 diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt deleted file mode 100644 index 708289d..0000000 --- a/src/CMakeLists.txt +++ /dev/null @@ -1,6 +0,0 @@ -add_subdirectory(0001_basics) -add_subdirectory(0002_tree) -add_subdirectory(0003_graph) -add_subdirectory(0004_dynamic_programming) -add_subdirectory(0005_greedy_algorithms) -add_subdirectory(0006_bitwise_algorithms) \ No newline at end of file diff --git a/tests/0000_common_utilities/CMakeLists.txt b/tests/0000_common_utilities/CMakeLists.txt deleted file mode 100644 index e69de29..0000000 diff --git a/tests/0000_common_utilities/UnitTestHelper.h b/tests/0000_common_utilities/UnitTestHelper.h deleted file mode 100644 index ff676bd..0000000 --- a/tests/0000_common_utilities/UnitTestHelper.h +++ /dev/null @@ -1,183 +0,0 @@ -#pragma once - -#include -#include -#include -#include -using namespace std; - -class UnitTestHelper -{ -public: - template - string SerializeVectorToString(vector vector) - { - string result = ""; - for (auto& iterator : vector) - { - result += to_string(iterator) + " "; - } - result.pop_back(); - return result; - } - - template - string SerializeVectorToString(vector> vector) - { - string result = ""; - for (auto& iterator : vector) - { - result += to_string(iterator.first) + "(" + to_string(iterator.second) + ")" + " "; - } - - if (!result.empty()) - { - result.pop_back(); - } - return result; - } - - template - string SerializeVectorToString(vector>> vector) - { - string result = ""; - for (auto& iterator : vector) - { - result += to_string(iterator.first) + "(" + to_string(iterator.second.first) + "," + to_string(iterator.second.second) + ")" + " "; - } - - if (!result.empty()) - { - result.pop_back(); - } - return result; - } - - template - string SerializeVectorToString(vector> vector) - { - string result = ""; - for (auto& iterator : vector) - { - result += "["; - for (auto& it : iterator) - { - result += to_string(it) + " "; - } - if (!result.empty()) - { - result.pop_back(); - } - result += "]"; - } - return result; - } - - // This helper method is used to sort the vector of vectors of a particular typename. - // Each inner vector is sorted first. - // Then each of them are sorted by their first element, in increasing order. - template - vector> SortVectorOfVectors(vector> data) - { - // Step 1: Sorting each inner vectors. - for (auto& innerVector : data) - { - sort(innerVector.begin(), innerVector.end()); - } - - // Step 2: Sorting all the vectors by their first element, in increasing order. - sort(data.begin(), data.end(), [](const vector& a, const vector& b) - { - // Checking if both inner vectors are empty to prevent out-of-bounds access. - if (a.empty() && b.empty()) - return false; - - // Considering empty vector as less than non-empty vector. - if (a.empty()) - return true; - - // Considering non-empty vector as greater than empty vector. - if (b.empty()) - return false; - - // Comparing the first elements of each vector. - return (a[0] < b[0]); - }); - - return data; - } - - template - bool NormalizeCyclesAndCompare(vector data1, vector data2) - { - if (data1.size() != data2.size()) - { - return false; - } - - // Normalized rotation of cycle 1 - vector normalizedCycle1(data1); - auto minIterator1 = min_element(normalizedCycle1.begin(), normalizedCycle1.end()); - rotate(normalizedCycle1.begin(), minIterator1, normalizedCycle1.end()); - - // Normalized rotation of cycle 2 - vector normalizedCycle2(data2); - auto minIterator2 = min_element(normalizedCycle2.begin(), normalizedCycle2.end()); - rotate(normalizedCycle2.begin(), minIterator2, normalizedCycle2.end()); - - // Check clock wise - if (normalizedCycle1 == normalizedCycle2) - { - return true; - } - - // Check counter clock wise - reverse(normalizedCycle2.begin() + 1, normalizedCycle2.end()); - return (normalizedCycle1 == normalizedCycle2); - } - - template - vector, T>> SortVectorOfPair(vector, T>> data) - { - for (auto& iterator : data) - { - if (iterator.first.first > iterator.first.second) - { - swap(iterator.first.first, iterator.first.second); - } - } - - sort(data.begin(), data.end(), [](const pair, T>& pairA, const pair, T>& pairB) - { - if (pairA.second == pairB.second) - { - return pairA.first.first < pairB.first.first; - } - return pairA.second < pairB.second; - }); - return data; - } - - template - string SortVectorOfPairAndSerialize(vector> data) - { - // Sorting the vector in non-decreasing order on typename T1 - sort(data.begin(), data.end(), [](const pair& pair1, const pair& pair2) - { - return pair1.first < pair2.first; - }); - - // Serializing the vector to string - string result = ""; - for (auto& iterator : data) - { - result += iterator.first + "(" + to_string(iterator.second) + ")" + " "; - } - - if (!result.empty()) - { - result.pop_back(); - } - return result; - } -}; \ No newline at end of file diff --git a/tests/0001_basics/CMakeLists.txt b/tests/0001_basics/CMakeLists.txt deleted file mode 100644 index efa1008..0000000 --- a/tests/0001_basics/CMakeLists.txt +++ /dev/null @@ -1,31 +0,0 @@ -cmake_policy(SET CMP0135 NEW) - -include(FetchContent) -FetchContent_Declare( - googletest - URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip -) -# For Windows: Prevent overriding the parent project's compiler/linker settings -set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) -FetchContent_MakeAvailable(googletest) - - -enable_testing() - -add_executable( - 0001BasicsTests - NodeTest.cc) - -target_link_libraries( - 0001BasicsTests - GTest::gtest_main - 0001BASICS -) - -# Add .clang-tidy configuration to this library. -if(CLANG_TIDY_EXE) - set_target_properties(0001BASICS PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") -endif() - -include(GoogleTest) -gtest_discover_tests(0001BasicsTests DISCOVERY_TIMEOUT 30) \ No newline at end of file diff --git a/tests/0001_basics/NodeTest.cc b/tests/0001_basics/NodeTest.cc deleted file mode 100644 index ca38297..0000000 --- a/tests/0001_basics/NodeTest.cc +++ /dev/null @@ -1,12 +0,0 @@ -#include -#include "Node.h" - -// Demonstrate some basic assertions. -namespace NodeTesting -{ - TEST(TestingNodeValue, PositiveTestCase) - { - // Expect two strings not to be equal. - EXPECT_EQ(2 * 4, 8); - } -} \ No newline at end of file diff --git a/tests/0002_tree/0001_BinarySearchTreeTest.cc b/tests/0002_tree/0001_BinarySearchTreeTest.cc deleted file mode 100644 index 0c8aab0..0000000 --- a/tests/0002_tree/0001_BinarySearchTreeTest.cc +++ /dev/null @@ -1,91 +0,0 @@ -#include -#include -#include "0001_BinarySearchTree.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace BinarySearchTree -{ - UnitTestHelper unitTestHelper; - - TEST(BSTInsertData, RecursiveInorderTest) - { - BinarySearchTree bst; - bst.insertNode(50); - bst.insertNode(30); - bst.insertNode(60); - - - string actualResult = unitTestHelper.SerializeVectorToString(bst.recursiveInorderTraversal()); - string expectedResult = "30 50 60"; - - EXPECT_EQ(actualResult, expectedResult); - } - - TEST(BSTInsertData, RecursivePreorderTest) - { - BinarySearchTree bst; - bst.insertNode(50); - bst.insertNode(30); - bst.insertNode(60); - - string actualResult = unitTestHelper.SerializeVectorToString(bst.recursivePreorderTravesal()); - string expectedResult = "50 30 60"; - - EXPECT_EQ(actualResult, expectedResult); - } - - TEST(BSTInsertData, RecursivePostorderTest) - { - BinarySearchTree bst; - bst.insertNode(50); - bst.insertNode(30); - bst.insertNode(60); - - string actualResult = unitTestHelper.SerializeVectorToString(bst.recursivePostorderTravesal()); - string expectedResult = "30 60 50"; - - EXPECT_EQ(actualResult, expectedResult); - } - - TEST(BSTInsertData, MorrisInorderTest) - { - BinarySearchTree bst; - bst.insertNode(50); - bst.insertNode(30); - bst.insertNode(60); - - - string actualResult = unitTestHelper.SerializeVectorToString(bst.morrisInorderTraversal()); - string expectedResult = "30 50 60"; - - EXPECT_EQ(actualResult, expectedResult); - } - - TEST(BSTInsertData, MorrisPreorderTest) - { - BinarySearchTree bst; - bst.insertNode(50); - bst.insertNode(30); - bst.insertNode(60); - - - string actualResult = unitTestHelper.SerializeVectorToString(bst.morrisPreorderTraversal()); - string expectedResult = "50 30 60"; - - EXPECT_EQ(actualResult, expectedResult); - } - - TEST(BSTInsertData, MorrisPostorderTest) - { - BinarySearchTree bst; - bst.insertNode(50); - bst.insertNode(30); - bst.insertNode(60); - - - string actualResult = unitTestHelper.SerializeVectorToString(bst.morrisPostorderTraversal()); - string expectedResult = "30 60 50"; - - EXPECT_EQ(actualResult, expectedResult); - } -} \ No newline at end of file diff --git a/tests/0002_tree/CMakeLists.txt b/tests/0002_tree/CMakeLists.txt deleted file mode 100644 index a10743b..0000000 --- a/tests/0002_tree/CMakeLists.txt +++ /dev/null @@ -1,32 +0,0 @@ -cmake_policy(SET CMP0135 NEW) - -include(FetchContent) -FetchContent_Declare( - googletest - URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip -) - -# For Windows: Prevent overriding the parent project's compiler/linker settings -set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) -FetchContent_MakeAvailable(googletest) - -enable_testing() - -add_executable( - 0002_TreeTests - 0001_BinarySearchTreeTest.cc -) - -target_link_libraries( - 0002_TreeTests - GTest::gtest_main - 0002_Tree -) - -# Add .clang-tidy configuration to this library. -if(CLANG_TIDY_EXE) - set_target_properties(0002_Tree PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") -endif() - -include(GoogleTest) -gtest_discover_tests(0002_TreeTests DISCOVERY_TIMEOUT 30) \ No newline at end of file diff --git a/tests/0003_graph/0001_BreadthFirstSearchTest.cc b/tests/0003_graph/0001_BreadthFirstSearchTest.cc deleted file mode 100644 index c0beb81..0000000 --- a/tests/0003_graph/0001_BreadthFirstSearchTest.cc +++ /dev/null @@ -1,45 +0,0 @@ -#include -#include -#include "../../src/0003_graph/headers/0001_BreadthFirstSearch.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace BreadthFirstSearch -{ - UnitTestHelper unitTestHelper; - - - TEST(BFSTesting, ShowBFSResultTest01) - { - Graph graph; - - graph.PushUndirectedEdge(1, 2); - graph.PushUndirectedEdge(1, 3); - graph.PushUndirectedEdge(2, 4); - graph.PushUndirectedEdge(3, 5); - graph.PushUndirectedEdge(3, 6); - graph.PushUndirectedEdge(5, 6); - graph.PushUndirectedEdge(5, 7); - graph.PushUndirectedEdge(6, 7); - graph.PushUndirectedEdge(6, 8); - graph.PushUndirectedEdge(7, 8); - - graph.BFS(1); - - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowBFSResult()); - string expectedResult = "1(0) 2(1) 3(1) 4(2) 5(2) 6(2) 7(3) 8(3)"; - EXPECT_EQ(actualResult, expectedResult); - } - - TEST(BFSTesting, ShowBFSResultTest02) - { - Graph graph; - - graph.PushUndirectedEdge(1, 2); - - graph.BFS(1); - - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowBFSResult()); - string expectedResult = "1(0) 2(1)"; - EXPECT_EQ(actualResult, expectedResult); - } -} \ No newline at end of file diff --git a/tests/0003_graph/0002_DepthFirstSearchTest.cc b/tests/0003_graph/0002_DepthFirstSearchTest.cc deleted file mode 100644 index c96c55e..0000000 --- a/tests/0003_graph/0002_DepthFirstSearchTest.cc +++ /dev/null @@ -1,177 +0,0 @@ -#include -#include "0002_DepthFirstSearch.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace DepthFirstSearch -{ - UnitTestHelper unitTestHelper; - - TEST(DFSTesting, ShowDFSResultTest01) - { - Graph graph; - - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(1, 4); - graph.PushDirectedEdge(2, 5); - graph.PushDirectedEdge(3, 5); - graph.PushDirectedEdge(3, 6); - graph.PushDirectedEdge(4, 2); - graph.PushDirectedEdge(5, 4); - graph.PushDirectedEdge(6, 6); - - graph.DFS(); - - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); - string expectedResult = "1(1,8) 2(2,7) 3(9,12) 4(4,5) 5(3,6) 6(10,11)"; - EXPECT_EQ(actualResult, expectedResult); - } - - - TEST(DFSTesting, ShowDFSResultTest_SingleVertex) - { - Graph graph; - - graph.PushDirectedEdge(1, 1); - - graph.DFS(); - - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); - string expectedResult = "1(1,2)"; - EXPECT_EQ(actualResult, expectedResult); - } - - TEST(DFSTesting, ShowDFSResultTest_DisconnectedGraph) - { - Graph graph; - - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(3, 4); - - graph.DFS(); - - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); - string expectedResult = "1(1,4) 2(2,3) 3(5,8) 4(6,7)"; - EXPECT_EQ(actualResult, expectedResult); - } - - TEST(DFSTesting, ShowDFSResultTest_CyclicGraph) - { - Graph graph; - - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(3, 1); - - graph.DFS(); - - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); - string expectedResult = "1(1,6) 2(2,5) 3(3,4)"; - EXPECT_EQ(actualResult, expectedResult); - } - - TEST(DFSTesting, ShowDFSResultTest_LargeGraph) - { - Graph graph; - - // Adding 15 nodes with several edges - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(1, 3); - graph.PushDirectedEdge(2, 4); - graph.PushDirectedEdge(4, 5); - graph.PushDirectedEdge(5, 6); - graph.PushDirectedEdge(6, 7); - graph.PushDirectedEdge(7, 8); - graph.PushDirectedEdge(8, 9); - graph.PushDirectedEdge(9, 10); - graph.PushDirectedEdge(10, 11); - graph.PushDirectedEdge(11, 12); - graph.PushDirectedEdge(12, 13); - graph.PushDirectedEdge(13, 14); - graph.PushDirectedEdge(14, 15); - graph.PushDirectedEdge(15, 16); - - graph.DFS(); - - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); - string expectedResult = "1(1,32) 2(2,29) 3(30,31) 4(3,28) 5(4,27) 6(5,26) 7(6,25) 8(7,24) 9(8,23) 10(9,22) 11(10,21) 12(11,20) 13(12,19) 14(13,18) 15(14,17) 16(15,16)"; - EXPECT_EQ(actualResult, expectedResult); - } - - TEST(DFSTesting, ShowDFSResultTest_NoEdges) - { - Graph graph; - - // Adding isolated nodes - graph.PushDirectedEdge(1, 1); - graph.PushDirectedEdge(2, 2); - graph.PushDirectedEdge(3, 3); - - graph.DFS(); - - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); - string expectedResult = "1(1,2) 2(3,4) 3(5,6)"; - EXPECT_EQ(actualResult, expectedResult); - } - - TEST(DFSTesting, ShowDFSResultTest_CyclicGraphWithBackEdges) - { - Graph graph; - - // Creating a cycle with back edges - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(3, 1); // Cycle back to 'a' - graph.PushDirectedEdge(2, 4); // Back edge - - graph.DFS(); - - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); - string expectedResult = "1(1,8) 2(2,7) 3(3,4) 4(5,6)"; - EXPECT_EQ(actualResult, expectedResult); - } - - TEST(DFSTesting, ShowDFSResultTest_DenseGraph) - { - Graph graph; - - // Complete graph of 4 nodes - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(1, 3); - graph.PushDirectedEdge(1, 4); - graph.PushDirectedEdge(2, 1); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(2, 4); - graph.PushDirectedEdge(3, 1); - graph.PushDirectedEdge(3, 2); - graph.PushDirectedEdge(3, 4); - graph.PushDirectedEdge(4, 1); - graph.PushDirectedEdge(4, 2); - graph.PushDirectedEdge(4, 3); - - graph.DFS(); - - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); - string expectedResult = "1(1,8) 2(2,7) 3(3,6) 4(4,5)"; - EXPECT_EQ(actualResult, expectedResult); - } - - TEST(DFSTesting, ShowDFSResultTest_SelfLoopsAndParallelEdges) - { - Graph graph; - - // Adding self-loops and parallel edges - graph.PushDirectedEdge(1, 1); - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(2, 2); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(2, 3); // Parallel edge - graph.PushDirectedEdge(3, 3); // Self-loop - - graph.DFS(); - - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); - string expectedResult = "1(1,6) 2(2,5) 3(3,4)"; - EXPECT_EQ(actualResult, expectedResult); - } - -} \ No newline at end of file diff --git a/tests/0003_graph/0003_TopologicalSortTest.cc b/tests/0003_graph/0003_TopologicalSortTest.cc deleted file mode 100644 index 6ad277e..0000000 --- a/tests/0003_graph/0003_TopologicalSortTest.cc +++ /dev/null @@ -1,116 +0,0 @@ -#include -#include "0003_TopologicalSort.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace TopologicalSort -{ - UnitTestHelper unitTestHelper; - - TEST(TopoSortTesting, ShowTopoSortResult) - { - Graph graph; - - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(1, 4); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(4, 3); - graph.PushSingleNode(5); - graph.PushDirectedEdge(6, 7); - graph.PushDirectedEdge(6, 8); - graph.PushDirectedEdge(7, 4); - graph.PushDirectedEdge(7, 8); - graph.PushDirectedEdge(9, 8); - - graph.TopologicalSort(); - - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); - string expectedResult = "9(17,18) 6(11,16) 7(12,15) 8(13,14) 5(9,10) 1(1,8) 4(6,7) 2(2,5) 3(3,4)"; - - EXPECT_EQ(actualResult, expectedResult); - } - - // Test with a larger graph and multiple paths between nodes - TEST(TopoSortTesting, LargeGraphMultiplePaths) - { - Graph graph; - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(1, 3); - graph.PushDirectedEdge(2, 4); - graph.PushDirectedEdge(3, 4); - graph.PushDirectedEdge(4, 5); - graph.PushDirectedEdge(5, 6); - graph.PushDirectedEdge(6, 7); - - graph.TopologicalSort(); - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); - string expectedResult = "1(1,14) 3(12,13) 2(2,11) 4(3,10) 5(4,9) 6(5,8) 7(6,7)"; - - EXPECT_EQ(actualResult, expectedResult); - } - - // Test with a graph containing disconnected components - TEST(TopoSortTesting, DisconnectedGraph) - { - Graph graph; - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(3, 4); - graph.PushDirectedEdge(5, 6); - - graph.TopologicalSort(); - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); - string expectedResult = "5(9,12) 6(10,11) 3(5,8) 4(6,7) 1(1,4) 2(2,3)"; - - EXPECT_EQ(actualResult, expectedResult); - } - - // Test with a graph that has multiple nodes pointing to the same node - TEST(TopoSortTesting, MultipleIncomingEdges) - { - Graph graph; - graph.PushDirectedEdge(1, 3); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(3, 4); - - graph.TopologicalSort(); - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); - string expectedResult = "2(7,8) 1(1,6) 3(2,5) 4(3,4)"; - - EXPECT_EQ(actualResult, expectedResult); - } - - // Test for a single-node graph to check the base case - TEST(TopoSortTesting, SingleNodeGraph) - { - Graph graph; - graph.PushSingleNode(1); - - graph.TopologicalSort(); - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); - string expectedResult = "1(1,2)"; - - EXPECT_EQ(actualResult, expectedResult); - } - - TEST(TopoSortTesting, ShowTopoSortResultUsingKahnAlgorithm) - { - Graph graph; - - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(1, 4); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(4, 3); - graph.PushSingleNode(5); - graph.PushDirectedEdge(6, 7); - graph.PushDirectedEdge(6, 8); - graph.PushDirectedEdge(7, 4); - graph.PushDirectedEdge(7, 8); - graph.PushDirectedEdge(9, 8); - - graph.KahnTopologicalSort(); - - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); - string expectedResult = "1(1,5) 5(2,7) 6(3,8) 9(4,10) 2(6,11) 7(9,12) 4(13,15) 8(14,17) 3(16,18)"; - - EXPECT_EQ(actualResult, expectedResult); - } -} \ No newline at end of file diff --git a/tests/0003_graph/0004_StronglyConnectedComponentsTest.cc b/tests/0003_graph/0004_StronglyConnectedComponentsTest.cc deleted file mode 100644 index f8ede7f..0000000 --- a/tests/0003_graph/0004_StronglyConnectedComponentsTest.cc +++ /dev/null @@ -1,102 +0,0 @@ -#include -#include "0004_StronglyConnectedComponents.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace StronglyConnectedComponents -{ - UnitTestHelper unitTestHelper; - - // Test case: Testing with a simple graph. - TEST(StronglyConnectedComponentsTesting, SimpleGraphTest) - { - Graph graph; - - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(1, 5); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(2, 4); - graph.PushDirectedEdge(3, 2); - graph.PushDirectedEdge(4, 4); - graph.PushDirectedEdge(5, 1); - graph.PushDirectedEdge(5, 4); - graph.PushDirectedEdge(6, 1); - graph.PushDirectedEdge(6, 3); - graph.PushDirectedEdge(6, 7); - graph.PushDirectedEdge(7, 3); - graph.PushDirectedEdge(7, 8); - graph.PushDirectedEdge(8, 6); - - auto actualResult = graph.FindAllStronglyConnectedComponents(); - vector> expectedResult = { {6, 8, 7},{1, 5},{2, 3},{4} }; - EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); - } - - // Test case: Single Node. - TEST(StronglyConnectedComponentsTesting, SingleNodeTest) - { - Graph graph; - graph.PushSingleNode(1); - - auto actualResult = graph.FindAllStronglyConnectedComponents(); - vector> expectedResult = { {1} }; - EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); - } - - // Test case: Disconnected Graph. - TEST(StronglyConnectedComponentsTesting, DisconnectedGraphTest) - { - Graph graph; - graph.PushSingleNode(1); - graph.PushSingleNode(2); - graph.PushSingleNode(3); - - auto actualResult = graph.FindAllStronglyConnectedComponents(); - vector> expectedResult = { {1},{3},{2} }; - EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); - } - - // Test case: Chain of Nodes. - TEST(StronglyConnectedComponentsTesting, ChainOfNodesTest) - { - Graph graph; - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(3, 4); - - auto actualResult = graph.FindAllStronglyConnectedComponents(); - vector> expectedResult = { {2},{1},{3},{4} }; - EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); - } - - // Test case: Bidirectional Edge. - TEST(StronglyConnectedComponentsTesting, BidirectionalEdgeTest) - { - Graph graph; - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(2, 1); - - auto actualResult = graph.FindAllStronglyConnectedComponents(); - vector> expectedResult = { {2, 1} }; - EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); - } - - // Test case: Complex Graph. - TEST(StronglyConnectedComponentsTesting, ComplexGraphTest) - { - Graph graph; - - // Graph structure with multiple SCCs and isolated nodes. - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(3, 1); // Cycle: 1 -> 2 -> 3 -> 1 - graph.PushDirectedEdge(4, 5); - graph.PushDirectedEdge(5, 6); - graph.PushDirectedEdge(6, 4); // Cycle: 4 -> 5 -> 6 -> 4 - graph.PushDirectedEdge(7, 8); // Single direction: 7 -> 8 - graph.PushSingleNode(9); // Isolated node. - - auto actualResult = graph.FindAllStronglyConnectedComponents(); - vector> expectedResult = { {4, 6, 5},{7}, { 2, 3, 1},{8}, {9} }; - EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); - } -} \ No newline at end of file diff --git a/tests/0003_graph/0005_HamiltonianPathAndCycleTest.cc b/tests/0003_graph/0005_HamiltonianPathAndCycleTest.cc deleted file mode 100644 index 33c351e..0000000 --- a/tests/0003_graph/0005_HamiltonianPathAndCycleTest.cc +++ /dev/null @@ -1,33 +0,0 @@ -#include -#include "0005_HamiltonianPathAndCycle.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace HamiltonianPathAndCycle -{ - UnitTestHelper unitTestHelper; - - TEST(HamiltonianCycleAndPathTest, ShowResult) - { - Graph graph; - - graph.PushUndirectedEdge(0, 1); - graph.PushUndirectedEdge(0, 3); - graph.PushUndirectedEdge(1, 2); - graph.PushUndirectedEdge(1, 3); - graph.PushUndirectedEdge(1, 4); - graph.PushUndirectedEdge(2, 4); - graph.PushUndirectedEdge(3, 4); - - graph.FindHamiltonianCycleAndPath(); - - bool isHamiltonianCyclePresent = graph.IsHamiltonianCyclePresent(); - bool isHamiltonianPathPresent = graph.IsHamiltonianPathPresent(); - - vector hamiltonianPathActualResult = graph.GetHamiltonianPath(); - vector hamiltonianPathExpectedResult = { 4, 3, 0, 1, 2 }; - - ASSERT_TRUE(isHamiltonianCyclePresent); - ASSERT_TRUE(isHamiltonianPathPresent); - ASSERT_TRUE(unitTestHelper.NormalizeCyclesAndCompare(hamiltonianPathActualResult, hamiltonianPathExpectedResult)); - } -} \ No newline at end of file diff --git a/tests/0003_graph/0006_EulerianPathAndCircuitTest.cc b/tests/0003_graph/0006_EulerianPathAndCircuitTest.cc deleted file mode 100644 index a163a5c..0000000 --- a/tests/0003_graph/0006_EulerianPathAndCircuitTest.cc +++ /dev/null @@ -1,32 +0,0 @@ -#include -#include "0006_EulerianPathAndCircuit.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace EulerianPathAndCircuit -{ - UnitTestHelper unitTestHelper; - - TEST(EulerianPathAndCycle, Test1) - { - Graph graph; - - graph.PushUndirectedEdge(1, 0); - graph.PushUndirectedEdge(0, 2); - graph.PushUndirectedEdge(2, 1); - graph.PushUndirectedEdge(0, 3); - graph.PushUndirectedEdge(3, 4); - graph.PushUndirectedEdge(4, 0); - - graph.FindEulerianPathAndCircuit(); - - bool isEulerianPathPresent = graph.IsEulerianPathPresent(); - bool isEulerianCircuitPresent = graph.IsEulerianCircuitPresent(); - - vector actualEulerianPath = graph.UndirectedGraphGetEulerianPath(); - vector expectedEulerianPath = { 0, 1, 2, 0, 3, 4, 0}; - - ASSERT_TRUE(isEulerianPathPresent); - ASSERT_TRUE(isEulerianCircuitPresent); - EXPECT_EQ(expectedEulerianPath, actualEulerianPath); - } -} \ No newline at end of file diff --git a/tests/0003_graph/0007_MinimumSpanningTreeKruskalAlgorithmTest.cc b/tests/0003_graph/0007_MinimumSpanningTreeKruskalAlgorithmTest.cc deleted file mode 100644 index 5736b79..0000000 --- a/tests/0003_graph/0007_MinimumSpanningTreeKruskalAlgorithmTest.cc +++ /dev/null @@ -1,45 +0,0 @@ -#include -#include "0007_MinimumSpanningTreeKruskalAlgorithm.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace MinimumSpanningTreeKruskalAlgorithm -{ - UnitTestHelper unitTestHelper; - - TEST(MST, Kruskal) - { - Graph graph; - - graph.PushUndirectedEdge(1, 2, 4); - graph.PushUndirectedEdge(1, 8, 8); - graph.PushUndirectedEdge(2, 8, 11); - graph.PushUndirectedEdge(2, 3, 8); - graph.PushUndirectedEdge(3, 4, 7); - graph.PushUndirectedEdge(3, 9, 2); - graph.PushUndirectedEdge(3, 6, 4); - graph.PushUndirectedEdge(4, 5, 9); - graph.PushUndirectedEdge(4, 6, 14); - graph.PushUndirectedEdge(5, 6, 10); - graph.PushUndirectedEdge(6, 7, 2); - graph.PushUndirectedEdge(7, 8, 1); - graph.PushUndirectedEdge(7, 9, 6); - graph.PushUndirectedEdge(8, 9, 7); - - graph.FindMinimumSpanningTreeKruskalAlgorithm(); - - vector, int>> actualMST = graph.GetMinimumSpanningTree(); - vector, int>> expectedMST = - { - {{7, 8}, 1}, - {{3, 9}, 2}, - {{6, 7}, 2}, - {{2, 1}, 4}, - {{3, 6}, 4}, - {{3, 4}, 7}, - {{8, 1}, 8}, - {{4, 5}, 9} - }; - - ASSERT_EQ(unitTestHelper.SortVectorOfPair(actualMST), unitTestHelper.SortVectorOfPair(expectedMST)); - } -} \ No newline at end of file diff --git a/tests/0003_graph/0008_MinimumSpanningTreePrimAlgorithmTest.cc b/tests/0003_graph/0008_MinimumSpanningTreePrimAlgorithmTest.cc deleted file mode 100644 index 251c654..0000000 --- a/tests/0003_graph/0008_MinimumSpanningTreePrimAlgorithmTest.cc +++ /dev/null @@ -1,45 +0,0 @@ -#include -#include "0008_MinimumSpanningTreePrimAlgorithm.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace MinimumSpanningTreePrimAlgorithm -{ - UnitTestHelper unitTestHelper; - - TEST(MST, Prim) - { - Graph graph; - - graph.PushUndirectedEdge(1, 2, 4); - graph.PushUndirectedEdge(1, 8, 8); - graph.PushUndirectedEdge(2, 8, 11); - graph.PushUndirectedEdge(2, 3, 8); - graph.PushUndirectedEdge(3, 4, 7); - graph.PushUndirectedEdge(3, 9, 2); - graph.PushUndirectedEdge(3, 6, 4); - graph.PushUndirectedEdge(4, 5, 9); - graph.PushUndirectedEdge(4, 6, 14); - graph.PushUndirectedEdge(5, 6, 10); - graph.PushUndirectedEdge(6, 7, 2); - graph.PushUndirectedEdge(7, 8, 1); - graph.PushUndirectedEdge(7, 9, 6); - graph.PushUndirectedEdge(8, 9, 7); - - graph.FindMinimumSpanningTreePrimAlgorithm(); - - vector, int>> actualMST = graph.GetMinimumSpanningTree(); - vector, int>> expectedMST = - { - {{7, 8}, 1}, - {{3, 9}, 2}, - {{6, 7}, 2}, - {{2, 1}, 4}, - {{3, 6}, 4}, - {{3, 4}, 7}, - {{8, 1}, 8}, - {{4, 5}, 9} - }; - - ASSERT_EQ(unitTestHelper.SortVectorOfPair(actualMST), unitTestHelper.SortVectorOfPair(expectedMST)); - } -} \ No newline at end of file diff --git a/tests/0003_graph/0009_SingleSourceShortestPathBellmanFordTest.cc b/tests/0003_graph/0009_SingleSourceShortestPathBellmanFordTest.cc deleted file mode 100644 index fc84901..0000000 --- a/tests/0003_graph/0009_SingleSourceShortestPathBellmanFordTest.cc +++ /dev/null @@ -1,104 +0,0 @@ -#include -#include "0009_SingleSourceShortestPathBellmanFord.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace SingleSourceShortestPathBellmanFord -{ - UnitTestHelper unitTestHelper; - - // Test for Simple Graph - TEST(BellmanFordTest, SimpleTest) - { - Graph graph; - - graph.PushDirectedEdge(0, 1, 6); - graph.PushDirectedEdge(0, 3, 7); - graph.PushDirectedEdge(1, 2, 5); - graph.PushDirectedEdge(1, 3, 8); - graph.PushDirectedEdge(1, 4, -4); - graph.PushDirectedEdge(2, 1, -2); - graph.PushDirectedEdge(3, 2, -3); - graph.PushDirectedEdge(3, 4, 9); - graph.PushDirectedEdge(3, 4, 9); - graph.PushDirectedEdge(4, 2, 7); - graph.PushDirectedEdge(4, 0, 2); - - string expectedResult = "0 3 2 1 4"; - ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); - ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(4)), expectedResult); - } - - // Test for Single Node Graph - TEST(BellmanFordTest, SingleNodeTest) - { - Graph graph; - graph.PushDirectedEdge(0, 0, 0); // Self-loop - - string expectedResult = "0"; - ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); - ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(0)), expectedResult); - } - - // Test for Negative Weight Cycle - TEST(BellmanFordTest, NegativeWeightCycleTest) - { - Graph graph; - graph.PushDirectedEdge(0, 1, 1); - graph.PushDirectedEdge(1, 2, -1); - graph.PushDirectedEdge(2, 0, -1); // Negative weight cycle - - ASSERT_FALSE(graph.FindSingleSourceShortestPathBellmanFord(0)); - } - - // Test for Multiple Shortest Paths - TEST(BellmanFordTest, MultipleShortestPathsTest) - { - Graph graph; - graph.PushDirectedEdge(0, 1, 5); - graph.PushDirectedEdge(0, 2, 5); - graph.PushDirectedEdge(1, 3, 1); - graph.PushDirectedEdge(2, 3, 1); - - string expectedResult = "0 1 3"; - ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); - ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(3)), expectedResult); - } - - // Test for All Negative Weights - TEST(BellmanFordTest, AllNegativeWeightsTest) - { - Graph graph; - graph.PushDirectedEdge(0, 1, -5); - graph.PushDirectedEdge(1, 2, -3); - graph.PushDirectedEdge(2, 3, -2); - graph.PushDirectedEdge(3, 4, -1); - - string expectedResult = "0 1 2 3 4"; - ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); - ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(4)), expectedResult); - } - - // Test for Large Graph - TEST(BellmanFordTest, LargeGraphTest) - { - Graph graph; - for (int i = 0; i < 100; ++i) { - graph.PushDirectedEdge(i, i + 1, 1); - } - - string expectedResult = "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20"; - ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); - ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(20)), expectedResult); - } - - // Test for Self-Loop Edge - TEST(BellmanFordTest, SelfLoopTest) - { - Graph graph; - graph.PushDirectedEdge(0, 0, 10); // Self-loop with weight 10 - - string expectedResult = "0"; - ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); - ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(0)), expectedResult); - } -} diff --git a/tests/0003_graph/0010_DirectedAcyclicGraphShortestPathTest.cc b/tests/0003_graph/0010_DirectedAcyclicGraphShortestPathTest.cc deleted file mode 100644 index 50d7086..0000000 --- a/tests/0003_graph/0010_DirectedAcyclicGraphShortestPathTest.cc +++ /dev/null @@ -1,29 +0,0 @@ -#include -#include "0010_DirectedAcyclicGraphShortestPath.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace DirectedAcyclicGraphShortestPath -{ - UnitTestHelper unitTestHelper; - - // Test for Simple Graph - TEST(DAGTest, SimpleGraph) - { - Graph graph; - - graph.PushDirectedEdge(0, 1, 5); - graph.PushDirectedEdge(0, 2, 3); - graph.PushDirectedEdge(1, 2, 2); - graph.PushDirectedEdge(1, 3, 6); - graph.PushDirectedEdge(2, 3, 7); - graph.PushDirectedEdge(2, 4, 4); - graph.PushDirectedEdge(2, 5, 2); - graph.PushDirectedEdge(3, 4, -1); - graph.PushDirectedEdge(3, 5, 1); - graph.PushDirectedEdge(4, 5, -2); - - graph.FindDAGShortestPath(1); - string expectedPath = "1 3 4 5"; - ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetDAGShortestPath(5)), expectedPath); - } -} \ No newline at end of file diff --git a/tests/0003_graph/0011_SingleSourceShortestPathDijkstraTest.cc b/tests/0003_graph/0011_SingleSourceShortestPathDijkstraTest.cc deleted file mode 100644 index 5460b1b..0000000 --- a/tests/0003_graph/0011_SingleSourceShortestPathDijkstraTest.cc +++ /dev/null @@ -1,31 +0,0 @@ -#include -#include "0011_SingleSourceShortestPathDijkstra.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace SingleSourceShortestPathDijkstra -{ - UnitTestHelper unitTestHelper; - - // Test for Simple Graph - TEST(DijkstraTest, SimpleGraph) - { - Graph graph; - - graph.PushDirectedEdge(0, 1, 10); - graph.PushDirectedEdge(0, 3, 5); - graph.PushDirectedEdge(1, 2, 1); - graph.PushDirectedEdge(1, 3, 2); - graph.PushDirectedEdge(2, 4, 4); - graph.PushDirectedEdge(3, 1, 3); - graph.PushDirectedEdge(3, 2, 9); - graph.PushDirectedEdge(3, 4, 2); - graph.PushDirectedEdge(4, 2, 6); - graph.PushDirectedEdge(4, 0, 7); - - graph.FindShortestPathDijkstra(0); - - string expectedPath = "0 3 1 2"; - - ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetDijkstraShortestPath(2)), expectedPath); - } -} \ No newline at end of file diff --git a/tests/0003_graph/0012_DifferenceConstraintsShortestPathsTest.cc b/tests/0003_graph/0012_DifferenceConstraintsShortestPathsTest.cc deleted file mode 100644 index 152dd0d..0000000 --- a/tests/0003_graph/0012_DifferenceConstraintsShortestPathsTest.cc +++ /dev/null @@ -1,40 +0,0 @@ -#include -#include "0012_DifferenceConstraintsShortestPaths.h" -#include"../0000_common_utilities/UnitTestHelper.h" -using namespace std; - -namespace DifferenceConstraintsShortestPaths -{ - UnitTestHelper unitTestHelper; - - TEST(DifferenceConstraints, SimpleGraph) - { - Graph graph; - - vector> vectorA = - { - {1, -1, 0, 0, 0}, - {1, 0, 0, 0, -1}, - {0, 1, 0, 0, -1}, - {-1, 0, 1, 0, 0}, - {-1, 0, 0, 1, 0}, - {0, 0, -1, 1, 0}, - {0, 0, -1, 0, 1}, - {0, 0, 0, -1, 1}, - }; - vector vectorX = { "v1", "v2", "v3", "v4", "v5" }; - vector vectorB = {0, -1, 1, 5, 4, -1, -3, -3}; - vector> expectedSolution = - { - {"v2", -3}, - {"v5", -4}, - {"v1", -5}, - {"v4", -1}, - {"v3", 0}, - }; - graph.PushAllDirectedEdges(vectorA, vectorX, vectorB); - - ASSERT_TRUE(graph.FindDifferenceConstraintsSolutionBellmanFord()); - ASSERT_EQ(unitTestHelper.SortVectorOfPairAndSerialize(graph.GetDifferenceConstrtaintsSolution()), unitTestHelper.SortVectorOfPairAndSerialize(expectedSolution)); - } -} \ No newline at end of file diff --git a/tests/0003_graph/0013_AllPairsShortestPathsFloydWarshallTest.cc b/tests/0003_graph/0013_AllPairsShortestPathsFloydWarshallTest.cc deleted file mode 100644 index 17a5045..0000000 --- a/tests/0003_graph/0013_AllPairsShortestPathsFloydWarshallTest.cc +++ /dev/null @@ -1,36 +0,0 @@ -#include -#include "0013_AllPairsShortestPathsFloydWarshall.h" -#include "../0000_common_utilities/UnitTestHelper.h" -using namespace std; - -namespace AllPairsShortestPathsFloydWarshall -{ - UnitTestHelper unitTestHelper; - - TEST(FloydWarshall, SimpleGraph) - { - // Arrange - Graph graph; - int noOfVertices = 5; - string expectedResult = "[1 5 4 3 2][1 5 4 3][1 5 4][1 5][2 4 1][2 4 3][2 4][2 4 1 5][3 2 4 1][3 2][3 2 4][3 2 4 1 5][4 1][4 3 2][4 3][4 1 5][5 4 1][5 4 3 2][5 4 3][5 4]"; - - // Act - graph.CreateGraph(noOfVertices); - - graph.PushDirectedEdge(1, 2, 3); - graph.PushDirectedEdge(1, 3, 8); - graph.PushDirectedEdge(1, 5, -4); - graph.PushDirectedEdge(2, 4, 1); - graph.PushDirectedEdge(2, 5, 7); - graph.PushDirectedEdge(3, 2, 4); - graph.PushDirectedEdge(4, 3, -5); - graph.PushDirectedEdge(4, 1, 2); - graph.PushDirectedEdge(5, 4, 6); - - graph.FindAllPairsShortestPathsFloydWarshallSolution(); - string actualResult = unitTestHelper.SerializeVectorToString(graph.GetFloydWarshallShortestPath()); - - // Assert - ASSERT_EQ(actualResult, expectedResult); - } -} \ No newline at end of file diff --git a/tests/0003_graph/0014_AllPairsShortestPathsJohnsonTest.cc b/tests/0003_graph/0014_AllPairsShortestPathsJohnsonTest.cc deleted file mode 100644 index 66a63a1..0000000 --- a/tests/0003_graph/0014_AllPairsShortestPathsJohnsonTest.cc +++ /dev/null @@ -1,44 +0,0 @@ -#include -#include "0014_AllPairsShortestPathsJohnson.h" -#include"../0000_common_utilities/UnitTestHelper.h" -using namespace std; - -namespace AllPairsShortestPathsJohnson -{ - UnitTestHelper unitTestHelper; - - TEST(JohnsonAlgorithm, SimpleGraph) - { - // Arrange - Graph graph; - vector> expectedDistanceMatrix = - { - {0, 1, -3, 2, -4}, - {3, 0, -4, 1, -1}, - {7, 4, 0, 5, 3}, - {2, -1, -5, 0, -2}, - {8, 5, 1, 6, 0}, - }; - string expectedPredecessorMatrixesult = "[1 5 4 3 2][1 5 4 3][1 5 4][1 5][2 4 1][2 4 3][2 4][2 4 1 5][3 2 4 1][3 2][3 2 4][3 2 4 1 5][4 1][4 3 2][4 3][4 1 5][5 4 1][5 4 3 2][5 4 3][5 4]"; - - // Act - graph.PushDirectedEdge(1, 2, 3); - graph.PushDirectedEdge(1, 3, 8); - graph.PushDirectedEdge(1, 5, -4); - graph.PushDirectedEdge(2, 4, 1); - graph.PushDirectedEdge(2, 5, 7); - graph.PushDirectedEdge(3, 2, 4); - graph.PushDirectedEdge(4, 3, -5); - graph.PushDirectedEdge(4, 1, 2); - graph.PushDirectedEdge(5, 4, 6); - - bool result = graph.FindAllPairsShortestPathsJohnsonAlgorithm(); - vector> actualDistanceMatrix = graph.GetAllPairsShortestPathsDistanceMatrix(); - string actualPredecessorMatrix = unitTestHelper.SerializeVectorToString(graph.GetAllPairsShortestPathsPathMatrix()); - - // Assert - ASSERT_TRUE(result); - ASSERT_EQ(expectedDistanceMatrix, actualDistanceMatrix); - ASSERT_EQ(expectedPredecessorMatrixesult, actualPredecessorMatrix); - } -} \ No newline at end of file diff --git a/tests/0003_graph/0015_MaximumFlowFordFulkersonTest.cc b/tests/0003_graph/0015_MaximumFlowFordFulkersonTest.cc deleted file mode 100644 index 117bfc2..0000000 --- a/tests/0003_graph/0015_MaximumFlowFordFulkersonTest.cc +++ /dev/null @@ -1,64 +0,0 @@ -#include -#include "0015_MaximumFlowFordFulkerson.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace MaximumFlowFordFulkerson -{ - UnitTestHelper unitTestHelper; - - TEST(MaximumFlowFordFulkerson, GraphWithNoParallelEdges) - { - // Arrange - Graph graph; - int noOfVertices = 6; - int expectedMaximumFlow = 23; - - - // Act - graph.CreateGraph(noOfVertices); - - graph.PushDirectedEdge(0, 1, 16); - graph.PushDirectedEdge(0, 2, 13); - graph.PushDirectedEdge(1, 3, 12); - graph.PushDirectedEdge(2, 1, 4); - graph.PushDirectedEdge(2, 4, 14); - graph.PushDirectedEdge(3, 2, 9); - graph.PushDirectedEdge(3, 5, 20); - graph.PushDirectedEdge(4, 3, 7); - graph.PushDirectedEdge(4, 5, 4); - - int actualMaximumFlow = graph.FindMaximumFlowFordFulkerson(); - - // Assert - ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); - } - - TEST(MaximumFlowFordFulkerson, GraphWithParallelEdges) - { - // Arrange - Graph graph; - int noOfVertices = 6; - int expectedMaximumFlow = 24; - - - // Act - graph.CreateGraph(noOfVertices); - - graph.PushDirectedEdge(0, 1, 16); - graph.PushDirectedEdge(0, 2, 13); - graph.PushDirectedEdge(1, 3, 12); - graph.PushDirectedEdge(1, 2, 6); - graph.PushDirectedEdge(2, 1, 10); - graph.PushDirectedEdge(2, 4, 14); - graph.PushDirectedEdge(2, 3, 2); - graph.PushDirectedEdge(3, 2, 11); - graph.PushDirectedEdge(3, 5, 20); - graph.PushDirectedEdge(4, 3, 7); - graph.PushDirectedEdge(4, 5, 4); - - int actualMaximumFlow = graph.FindMaximumFlowFordFulkerson(); - - // Assert - ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); - } -} \ No newline at end of file diff --git a/tests/0003_graph/0016_MaximumFlowEdmondsKarpTest.cc b/tests/0003_graph/0016_MaximumFlowEdmondsKarpTest.cc deleted file mode 100644 index 5d3177a..0000000 --- a/tests/0003_graph/0016_MaximumFlowEdmondsKarpTest.cc +++ /dev/null @@ -1,64 +0,0 @@ -#include -#include "0016_MaximumFlowEdmondsKarp.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace MaximumFlowEdmondsKarp -{ - UnitTestHelper unitTestHelper; - - TEST(MaximumFlowEdmondsKarp, GraphWithNoParallelEdges) - { - // Arrange - Graph graph; - int noOfVertices = 6; - int expectedMaximumFlow = 23; - - - // Act - graph.CreateGraph(noOfVertices); - - graph.PushDirectedEdge(0, 1, 16); - graph.PushDirectedEdge(0, 2, 13); - graph.PushDirectedEdge(1, 3, 12); - graph.PushDirectedEdge(2, 1, 4); - graph.PushDirectedEdge(2, 4, 14); - graph.PushDirectedEdge(3, 2, 9); - graph.PushDirectedEdge(3, 5, 20); - graph.PushDirectedEdge(4, 3, 7); - graph.PushDirectedEdge(4, 5, 4); - - int actualMaximumFlow = graph.FindMaximumFlowEdmondsKarp(); - - // Assert - ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); - } - - TEST(MaximumFlowEdmondsKarp, GraphWithParallelEdges) - { - // Arrange - Graph graph; - int noOfVertices = 6; - int expectedMaximumFlow = 24; - - - // Act - graph.CreateGraph(noOfVertices); - - graph.PushDirectedEdge(0, 1, 16); - graph.PushDirectedEdge(0, 2, 13); - graph.PushDirectedEdge(1, 3, 12); - graph.PushDirectedEdge(1, 2, 6); - graph.PushDirectedEdge(2, 1, 10); - graph.PushDirectedEdge(2, 4, 14); - graph.PushDirectedEdge(2, 3, 2); - graph.PushDirectedEdge(3, 2, 11); - graph.PushDirectedEdge(3, 5, 20); - graph.PushDirectedEdge(4, 3, 7); - graph.PushDirectedEdge(4, 5, 4); - - int actualMaximumFlow = graph.FindMaximumFlowEdmondsKarp(); - - // Assert - ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); - } -} \ No newline at end of file diff --git a/tests/0003_graph/0017_MaximumBipartiteMatchingTest.cc b/tests/0003_graph/0017_MaximumBipartiteMatchingTest.cc deleted file mode 100644 index d556e28..0000000 --- a/tests/0003_graph/0017_MaximumBipartiteMatchingTest.cc +++ /dev/null @@ -1,35 +0,0 @@ -#include -#include "0017_MaximumBipartiteMatching.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace MaximumBipartiteMatching -{ - TEST(MaximumBipartiteMatching, SimpleGraph) - { - // Arrange - Graph graph; - UnitTestHelper unitTestHelper; - int noOfVertices = 9; - int expectedMaximumMatching = 3; - string expectedMatchings = "[0 1][2 6][3 5]"; - - // Act - graph.CreateGraph(noOfVertices); - - graph.PushDirectedEdge(0, 1); - graph.PushDirectedEdge(2, 1); - graph.PushDirectedEdge(2, 6); - graph.PushDirectedEdge(3, 5); - graph.PushDirectedEdge(3, 6); - graph.PushDirectedEdge(3, 7); - graph.PushDirectedEdge(4, 6); - graph.PushDirectedEdge(8, 6); - - int actualMaximumMatching = graph.FindMaximumBipartiteMatching(); - vector> actualMatchings = graph.GetMatchings(); - - // Assert - ASSERT_EQ(expectedMaximumMatching, actualMaximumMatching); - ASSERT_EQ(expectedMatchings, unitTestHelper.SerializeVectorToString(actualMatchings)); - } -} \ No newline at end of file diff --git a/tests/0003_graph/0018_MaximumFlowGoldbergGenericPushRelabelTest.cc b/tests/0003_graph/0018_MaximumFlowGoldbergGenericPushRelabelTest.cc deleted file mode 100644 index 283cab0..0000000 --- a/tests/0003_graph/0018_MaximumFlowGoldbergGenericPushRelabelTest.cc +++ /dev/null @@ -1,35 +0,0 @@ -#include -#include "0018_MaximumFlowGoldbergGenericPushRelabel.h" -#include "../0000_common_utilities/UnitTestHelper.h" - -namespace MaximumFlowGoldbergGenericPushRelabel -{ - UnitTestHelper unitTestHelper; - - TEST(MaximumFlowGoldbergGenericPushRelabel, GraphWithNoParallelEdges) - { - // Arrange - Graph graph; - int noOfVertices = 6; - int expectedMaximumFlow = 23; - - - // Act - graph.CreateGraph(noOfVertices); - - graph.PushDirectedEdge(0, 1, 16); - graph.PushDirectedEdge(0, 2, 13); - graph.PushDirectedEdge(1, 3, 12); - graph.PushDirectedEdge(2, 1, 4); - graph.PushDirectedEdge(2, 4, 14); - graph.PushDirectedEdge(3, 2, 9); - graph.PushDirectedEdge(3, 5, 20); - graph.PushDirectedEdge(4, 3, 7); - graph.PushDirectedEdge(4, 5, 4); - - int actualMaximumFlow = graph.FindMaximumFlowGoldbergGenericPushRelabel(); - - // Assert - ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); - } -} \ No newline at end of file diff --git a/tests/0003_graph/0019_MaximumFlowRelabelToFrontTest.cc b/tests/0003_graph/0019_MaximumFlowRelabelToFrontTest.cc deleted file mode 100644 index a73b89d..0000000 --- a/tests/0003_graph/0019_MaximumFlowRelabelToFrontTest.cc +++ /dev/null @@ -1,36 +0,0 @@ -#include -#include "0019_MaximumFlowRelabelToFront.h" -#include "../0000_common_utilities/UnitTestHelper.h" -using namespace std; - -namespace MaximumFlowRelabelToFront -{ - UnitTestHelper unitTestHelper; - - TEST(MaximumFlowRelabelToFront, SimpleGraph) - { - // Arrange - Graph graph; - int noOfVertices = 6; - int expectedMaximumFlow = 23; - - - // Act - graph.CreateGraph(noOfVertices); - - graph.PushDirectedEdge(0, 1, 16); - graph.PushDirectedEdge(0, 2, 13); - graph.PushDirectedEdge(1, 3, 12); - graph.PushDirectedEdge(2, 1, 4); - graph.PushDirectedEdge(2, 4, 14); - graph.PushDirectedEdge(3, 2, 9); - graph.PushDirectedEdge(3, 5, 20); - graph.PushDirectedEdge(4, 3, 7); - graph.PushDirectedEdge(4, 5, 4); - - int actualMaximumFlow = graph.FindMaximumFlowRelabelToFront(); - - // Assert - ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); - } -} \ No newline at end of file diff --git a/tests/0003_graph/CMakeLists.txt b/tests/0003_graph/CMakeLists.txt deleted file mode 100644 index 275d4a8..0000000 --- a/tests/0003_graph/CMakeLists.txt +++ /dev/null @@ -1,50 +0,0 @@ -cmake_policy(SET CMP0135 NEW) - -include(FetchContent) -FetchContent_Declare( - googletest - URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip -) - -# For Windows: Prevent overriding the parent project's compiler/linker settings -set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) -FetchContent_MakeAvailable(googletest) - -enable_testing() - -add_executable( - 0003GraphTests - 0001_BreadthFirstSearchTest.cc - 0002_DepthFirstSearchTest.cc - 0003_TopologicalSortTest.cc - 0004_StronglyConnectedComponentsTest.cc - 0005_HamiltonianPathAndCycleTest.cc - 0006_EulerianPathAndCircuitTest.cc - 0007_MinimumSpanningTreeKruskalAlgorithmTest.cc - 0008_MinimumSpanningTreePrimAlgorithmTest.cc - 0009_SingleSourceShortestPathBellmanFordTest.cc - 0010_DirectedAcyclicGraphShortestPathTest.cc - 0011_SingleSourceShortestPathDijkstraTest.cc - 0012_DifferenceConstraintsShortestPathsTest.cc - 0013_AllPairsShortestPathsFloydWarshallTest.cc - 0014_AllPairsShortestPathsJohnsonTest.cc - 0015_MaximumFlowFordFulkersonTest.cc - 0016_MaximumFlowEdmondsKarpTest.cc - 0017_MaximumBipartiteMatchingTest.cc - 0018_MaximumFlowGoldbergGenericPushRelabelTest.cc - 0019_MaximumFlowRelabelToFrontTest.cc -) - -target_link_libraries( - 0003GraphTests - GTest::gtest_main - 0003GRAPH -) - -# Add .clang-tidy configuration to this library. -if(CLANG_TIDY_EXE) - set_target_properties(0003GRAPH PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") -endif() - -include(GoogleTest) -gtest_discover_tests(0003GraphTests DISCOVERY_TIMEOUT 30) \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0001_FibonacciNumberTest.cc b/tests/0004_dynamic_programming/0001_FibonacciNumberTest.cc deleted file mode 100644 index 1fdd9a4..0000000 --- a/tests/0004_dynamic_programming/0001_FibonacciNumberTest.cc +++ /dev/null @@ -1,34 +0,0 @@ -#include -#include "0001_FibonacciNumber.h" -using namespace std; - -namespace FibonacciNumber -{ - TEST(FibonacciNumber, RecursiveTest) - { - // Arrange - DynamicProgramming dp; - int n = 5; - int expectedFib = 5; - - // Act - int actualFib = dp.RecursiveNthFibonacci(n); - - // Assert - ASSERT_EQ(expectedFib, actualFib); - } - - TEST(FibonacciNumber, DpTest) - { - // Arrange - DynamicProgramming dp; - int n = 5; - int expectedFib = 5; - - // Act - int actualFib = dp.DpNthFibonacci(n); - - // Assert - ASSERT_EQ(expectedFib, actualFib); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0002_TribonacciNumberTest.cc b/tests/0004_dynamic_programming/0002_TribonacciNumberTest.cc deleted file mode 100644 index d25c394..0000000 --- a/tests/0004_dynamic_programming/0002_TribonacciNumberTest.cc +++ /dev/null @@ -1,34 +0,0 @@ -#include -#include "0002_TribonacciNumber.h" -using namespace std; - -namespace TribonacciNumber -{ - TEST(TribonacciNumber, RecursiveTest) - { - // Arrange - DynamicProgramming dp; - int n = 5; - int expectedFib = 2; - - // Act - int actualFib = dp.RecursiveNthTribonacci(n); - - // Assert - ASSERT_EQ(expectedFib, actualFib); - } - - TEST(TribonacciNumber, DpTest) - { - // Arrange - DynamicProgramming dp; - int n = 10; - int expectedFib = 44; - - // Act - int actualFib = dp.DpNthTribonacci(n); - - // Assert - ASSERT_EQ(expectedFib, actualFib); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0003_ClimbingStairsTest.cc b/tests/0004_dynamic_programming/0003_ClimbingStairsTest.cc deleted file mode 100644 index 0504cbc..0000000 --- a/tests/0004_dynamic_programming/0003_ClimbingStairsTest.cc +++ /dev/null @@ -1,33 +0,0 @@ -#include -#include "0003_ClimbingStairs.h" - -namespace ClimbingStairs -{ - TEST(ClimbingStairs, RecursiveTest) - { - // Arrange - DynamicProgramming dp; - int n = 4; - int expectedCount = 5; - - // Act - int actualCount = dp.RecursiveCountWays(n); - - // Assert - ASSERT_EQ(expectedCount, actualCount); - } - - TEST(ClimbingStairs, DpTest) - { - // Arrange - DynamicProgramming dp; - int n = 4; - int expectedCount = 5; - - // Act - int actualCount = dp.DpCountWays(n); - - // Assert - ASSERT_EQ(expectedCount, actualCount); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0004_MinimumCostClimbingStairsTest.cc b/tests/0004_dynamic_programming/0004_MinimumCostClimbingStairsTest.cc deleted file mode 100644 index b488105..0000000 --- a/tests/0004_dynamic_programming/0004_MinimumCostClimbingStairsTest.cc +++ /dev/null @@ -1,33 +0,0 @@ -#include -#include "0004_MinimumCostClimbingStairs.h" - -namespace MinimumCostClimbingStairs -{ - TEST(MinimumCostClimbingStairs, RecursionTest) - { - // Arrange - DynamicProgramming dp; - vector cost = { 16, 19, 10, 12, 18 }; - int expectedCost = 31; - - // Act - int actualCost = dp.RecursiveMinimumCostClimbingStairs(cost); - - // Assert - ASSERT_EQ(expectedCost, actualCost); - } - - TEST(MinimumCostClimbingStairs, DpTest) - { - // Arrange - DynamicProgramming dp; - vector cost = { 16, 19, 10, 12, 18 }; - int expectedCost = 31; - - // Act - int actualCost = dp.DpMinimumCostClimbingStairs(cost); - - // Assert - ASSERT_EQ(expectedCost, actualCost); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0005_HouseRobber1Test.cc b/tests/0004_dynamic_programming/0005_HouseRobber1Test.cc deleted file mode 100644 index d3f6312..0000000 --- a/tests/0004_dynamic_programming/0005_HouseRobber1Test.cc +++ /dev/null @@ -1,33 +0,0 @@ -#include -#include "0005_HouseRobber1.h" - -namespace HouseRobber1 -{ - TEST(HouseRobber1, RecursionTest) - { - // Arrange - DynamicProgramming dp; - vector houseValues = { 6, 7, 1, 3, 8, 2, 4 }; - int expectedMaximumLoot = 19; - - // Act - int actualMaximumLoot = dp.RecursiveMaximumLoot(houseValues); - - // Assert - ASSERT_EQ(expectedMaximumLoot, actualMaximumLoot); - } - - TEST(HouseRobber1, DpTest) - { - // Arrange - DynamicProgramming dp; - vector houseValues = { 6, 7, 1, 3, 8, 2, 4 }; - int expectedMaximumLoot = 19; - - // Act - int actualMaximumLoot = dp.DpMaximumLoot(houseValues); - - // Assert - ASSERT_EQ(expectedMaximumLoot, actualMaximumLoot); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0006_HouseRobber2Test.cc b/tests/0004_dynamic_programming/0006_HouseRobber2Test.cc deleted file mode 100644 index e37c346..0000000 --- a/tests/0004_dynamic_programming/0006_HouseRobber2Test.cc +++ /dev/null @@ -1,48 +0,0 @@ -#include -#include "0006_HouseRobber2.h" - -namespace HouseRobber2 -{ - TEST(HouseRobber2, RecursionTest01) - { - // Arrange - DynamicProgramming dp; - vector houseValues = { 2, 2, 3, 1, 2 }; - int expectedMaximumLoot = 5; - - // Act - int actualMaximumLoot = dp.RecursiveMaximumLoot(houseValues); - - // Assert - ASSERT_EQ(expectedMaximumLoot, actualMaximumLoot); - } - - TEST(HouseRobber2, DpTest01) - { - // Arrange - DynamicProgramming dp; - vector houseValues = { 2, 2, 3, 1, 2 }; - int expectedMaximumLoot = 5; - - // Act - int actualMaximumLoot = dp.DpMaximumLoot(houseValues); - - // Assert - ASSERT_EQ(expectedMaximumLoot, actualMaximumLoot); - } - - TEST(HouseRobber2, DpTest02) - { - // Arrange - DynamicProgramming dp; - vector houseValues = { 9, 1, 8, 2 }; - int expectedMaximumLoot = 17; - - // Act - int actualMaximumLoot = dp.DpMaximumLoot(houseValues); - - // Assert - ASSERT_EQ(expectedMaximumLoot, actualMaximumLoot); - } - -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0007_DecodeWaysTest.cc b/tests/0004_dynamic_programming/0007_DecodeWaysTest.cc deleted file mode 100644 index cf81a98..0000000 --- a/tests/0004_dynamic_programming/0007_DecodeWaysTest.cc +++ /dev/null @@ -1,47 +0,0 @@ -#include -#include "0007_DecodeWays.h" - -namespace DecodeWays -{ - TEST(DecodeWays, RecursionTest01) - { - // Arrange - DynamicProgramming dp; - string digits = "121"; - int expectedWaysCount = 3; - - // Act - int actualWaysCount = dp.RecursiveCountWays(digits); - - // Assert - ASSERT_EQ(expectedWaysCount, actualWaysCount); - } - - TEST(DecodeWays, DpTest01) - { - // Arrange - DynamicProgramming dp; - string digits = "121"; - int expectedWaysCount = 3; - - // Act - int actualWaysCount = dp.DpCountways(digits); - - // Assert - ASSERT_EQ(expectedWaysCount, actualWaysCount); - } - - TEST(DecodeWays, DpTestInvalidInput) - { - // Arrange - DynamicProgramming dp; - string digits = "230"; - int expectedWaysCount = 0; - - // Act - int actualWaysCount = dp.DpCountways(digits); - - // Assert - ASSERT_EQ(expectedWaysCount, actualWaysCount); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0008_TilingProblemTest.cc b/tests/0004_dynamic_programming/0008_TilingProblemTest.cc deleted file mode 100644 index bbcbb79..0000000 --- a/tests/0004_dynamic_programming/0008_TilingProblemTest.cc +++ /dev/null @@ -1,33 +0,0 @@ -#include -#include "0008_TilingProblem.h" - -namespace TilingProblem -{ - TEST(TilingProblem, RecursionTest01) - { - // Arrange - DynamicProgramming dp; - int nummberOfRows = 4; - int expectedNumberOfWays = 5; - - // Act - int actualNumberOfWays = dp.RecursiveNumberOfWays(nummberOfRows); - - // Assert - ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); - } - - TEST(TilingProblem, DpTest01) - { - // Arrange - DynamicProgramming dp; - int nummberOfRows = 4; - int expectedNumberOfWays = 5; - - // Act - int actualNumberOfWays = dp.DpNumberOfWays(nummberOfRows); - - // Assert - ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0009_FriendsPairingProblemTest.cc b/tests/0004_dynamic_programming/0009_FriendsPairingProblemTest.cc deleted file mode 100644 index 11376ac..0000000 --- a/tests/0004_dynamic_programming/0009_FriendsPairingProblemTest.cc +++ /dev/null @@ -1,91 +0,0 @@ -#include -#include "0009_FriendsPairingProblem.h" - -namespace FriendsPairingProblem -{ - TEST(FriendsPairingProblemDynamicProgrammingTest, RecursiveCountFriendsPairingsTest1) - { - // Arrange - DynamicProgramming dp; - int numberOfFriends = 3; - int expectedPairings = 4; - - // Act - int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); - - // Assert - ASSERT_EQ(expectedPairings, actualPairings); - EXPECT_EQ(dp.RecursiveCountFriendsPairings(4), 10); - EXPECT_EQ(dp.RecursiveCountFriendsPairings(5), 26); - } - - TEST(FriendsPairingProblemDynamicProgrammingTest, RecursiveCountFriendsPairingsTest2) - { - // Arrange - DynamicProgramming dp; - int numberOfFriends = 4; - int expectedPairings = 10; - - // Act - int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); - - // Assert - ASSERT_EQ(expectedPairings, actualPairings); - } - - TEST(FriendsPairingProblemDynamicProgrammingTest, RecursiveCountFriendsPairingsTest3) - { - // Arrange - DynamicProgramming dp; - int numberOfFriends = 5; - int expectedPairings = 26; - - // Act - int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); - - // Assert - ASSERT_EQ(expectedPairings, actualPairings); - } - - TEST(FriendsPairingProblemDynamicProgrammingTest, DpCountFriendsPairingsTest1) - { - // Arrange - DynamicProgramming dp; - int numberOfFriends = 3; - int expectedPairings = 4; - - // Act - int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); - - // Assert - ASSERT_EQ(expectedPairings, actualPairings); - } - - TEST(FriendsPairingProblemDynamicProgrammingTest, DpCountFriendsPairingsTest2) - { - // Arrange - DynamicProgramming dp; - int numberOfFriends = 4; - int expectedPairings = 10; - - // Act - int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); - - // Assert - ASSERT_EQ(expectedPairings, actualPairings); - } - - TEST(FriendsPairingProblemDynamicProgrammingTest, DpCountFriendsPairingsTest3) - { - // Arrange - DynamicProgramming dp; - int numberOfFriends = 5; - int expectedPairings = 26; - - // Act - int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); - - // Assert - ASSERT_EQ(expectedPairings, actualPairings); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0010_WaysToCoverDistanceTest.cc b/tests/0004_dynamic_programming/0010_WaysToCoverDistanceTest.cc deleted file mode 100644 index 7e7f0c9..0000000 --- a/tests/0004_dynamic_programming/0010_WaysToCoverDistanceTest.cc +++ /dev/null @@ -1,117 +0,0 @@ -#include -#include "0010_WaysToCoverDistance.h" - -namespace WaysToCoverDistance -{ - TEST(WaysToCoverDistanceTest, RecursiveWaysToCoverDistance1) - { - // Arrange - DynamicProgramming dp; - int distance = 3; - int expectedNumberOfWaysToCoverDistance = 4; - - // Act - int actualNumberOfWaysToCoverDistance = dp.RecursiveWaysToCoverDistance(distance); - - // Assert - ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); - } - - TEST(WaysToCoverDistanceTest, RecursiveWaysToCoverDistance2) - { - // Arrange - DynamicProgramming dp; - int distance = 4; - int expectedNumberOfWaysToCoverDistance = 7; - - // Act - int actualNumberOfWaysToCoverDistance = dp.RecursiveWaysToCoverDistance(distance); - - // Assert - ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); - } - - TEST(WaysToCoverDistanceTest, RecursiveWaysToCoverDistanc3) - { - // Arrange - DynamicProgramming dp; - int distance = 5; - int expectedNumberOfWaysToCoverDistance = 13; - - // Act - int actualNumberOfWaysToCoverDistance = dp.RecursiveWaysToCoverDistance(distance); - - // Assert - ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); - } - - TEST(WaysToCoverDistanceTest, RecursiveWaysToCoverDistanc4) - { - // Arrange - DynamicProgramming dp; - int distance = 6; - int expectedNumberOfWaysToCoverDistance = 24; - - // Act - int actualNumberOfWaysToCoverDistance = dp.RecursiveWaysToCoverDistance(distance); - - // Assert - ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); - } - - TEST(WaysToCoverDistanceTest, DpWaysToCoverDistance1) - { - // Arrange - DynamicProgramming dp; - int distance = 3; - int expectedNumberOfWaysToCoverDistance = 4; - - // Act - int actualNumberOfWaysToCoverDistance = dp.DpWaysToCoverDistance(distance); - - // Assert - ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); - } - - TEST(WaysToCoverDistanceTest, DpWaysToCoverDistance2) - { - // Arrange - DynamicProgramming dp; - int distance = 4; - int expectedNumberOfWaysToCoverDistance = 7; - - // Act - int actualNumberOfWaysToCoverDistance = dp.DpWaysToCoverDistance(distance); - - // Assert - ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); - } - - TEST(WaysToCoverDistanceTest, DpWaysToCoverDistance3) - { - // Arrange - DynamicProgramming dp; - int distance = 5; - int expectedNumberOfWaysToCoverDistance = 13; - - // Act - int actualNumberOfWaysToCoverDistance = dp.DpWaysToCoverDistance(distance); - - // Assert - ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); - } - - TEST(WaysToCoverDistanceTest, DpWaysToCoverDistance4) - { - // Arrange - DynamicProgramming dp; - int distance = 6; - int expectedNumberOfWaysToCoverDistance = 24; - - // Act - int actualNumberOfWaysToCoverDistance = dp.DpWaysToCoverDistance(distance); - - // Assert - ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrderTest.cc b/tests/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrderTest.cc deleted file mode 100644 index 8a9830c..0000000 --- a/tests/0004_dynamic_programming/0011_CountWaysToReachNthStairIncludeOrderTest.cc +++ /dev/null @@ -1,33 +0,0 @@ -#include -#include "0011_CountWaysToReachNthStairIncludeOrder.h" - -namespace CountWaysToReachNthStairIncludeOrder -{ - TEST(CountWaysToReachNthStairIncludeOrderTest, RecursiveCountWaysToReachNthStairIncludeOrder1) - { - // Arrange - DynamicProgramming dp; - int n = 4; - int expectedNumberOfWays = 5; - - // Act - int actualNumberOfWays = dp.RecursiveCountWaysToReachNthStairIncludeOrder(n); - - // Assert - ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); - } - - TEST(CountWaysToReachNthStairIncludeOrderTest, DpCountWaysToReachNthStairIncludeOrder1) - { - // Arrange - DynamicProgramming dp; - int n = 4; - int expectedNumberOfWays = 5; - - // Act - int actualNumberOfWays = dp.DpCountWaysToReachNthStairIncludeOrder(n); - - // Assert - ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrderTest.cc b/tests/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrderTest.cc deleted file mode 100644 index 2a67ce3..0000000 --- a/tests/0004_dynamic_programming/0012_CountWaysToReachNthStairExcludeOrderTest.cc +++ /dev/null @@ -1,33 +0,0 @@ -#include -#include "0012_CountWaysToReachNthStairExcludeOrder.h" - -namespace CountWaysToReachNthStairExcludeOrder -{ - TEST(CountWaysToReachNthStairExcludeOrderTest, RecursiveCountWaysToReachNthStairExcludeOrder1) - { - // Arrange - DynamicProgramming dp; - int n = 4; - int expectedNumberOfWays = 3; - - // Act - int actualNumberOfWays = dp.RecursiveCountWaysToReachNthStairExcludeOrder(n); - - // Assert - ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); - } - - TEST(CountWaysToReachNthStairExcludeOrderTest, DpCountWaysToReachNthStairExcludeOrder1) - { - // Arrange - DynamicProgramming dp; - int n = 4; - int expectedNumberOfWays = 3; - - // Act - int actualNumberOfWays = dp.DpCountWaysToReachNthStairExcludeOrder(n); - - // Assert - ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0013_KnapsackProblemTest.cc b/tests/0004_dynamic_programming/0013_KnapsackProblemTest.cc deleted file mode 100644 index 94d3e84..0000000 --- a/tests/0004_dynamic_programming/0013_KnapsackProblemTest.cc +++ /dev/null @@ -1,53 +0,0 @@ -#include -#include "0013_KnapsackProblem.h" - -namespace KnapsackProblem -{ - TEST(KnapsackProblemTest, RecursiveKnapsackProblemTest01) - { - // Arrange - DynamicProgramming dp; - int capacity = 4; - vector weight = { 4,5,1 }; - vector profit = { 1,2,3 }; - int expectedMaximumProfit = 3; - - // Act - int actualMaximumProfit = dp.RecursiveKnapsack(capacity, weight, profit); - - // Assert - ASSERT_EQ(expectedMaximumProfit, actualMaximumProfit); - } - - TEST(KnapsackProblemTest, DpKnapsackProblemTest01) - { - // Arrange - DynamicProgramming dp; - int capacity = 4; - vector weight = { 4,5,1 }; - vector profit = { 1,2,3 }; - int expectedMaximumProfit = 3; - - // Act - int actualMaximumProfit = dp.DpKnapsack(capacity, weight, profit); - - // Assert - ASSERT_EQ(expectedMaximumProfit, actualMaximumProfit); - } - - TEST(KnapsackProblemTest, DpKnapsackProblemTest02) - { - // Arrange - DynamicProgramming dp; - int capacity = 4; - vector weight = { 4,5,1 }; - vector profit = { 1,2,3 }; - int expectedMaximumProfit = 3; - - // Act - int actualMaximumProfit = dp.DpKnapsackSpaceOptimized(capacity, weight, profit); - - // Assert - ASSERT_EQ(expectedMaximumProfit, actualMaximumProfit); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0014_SubsetSumProblemTest.cc b/tests/0004_dynamic_programming/0014_SubsetSumProblemTest.cc deleted file mode 100644 index aeee852..0000000 --- a/tests/0004_dynamic_programming/0014_SubsetSumProblemTest.cc +++ /dev/null @@ -1,35 +0,0 @@ -#include -#include "0014_SubsetSumProblem.h" - -namespace SubsetSumProblem -{ - TEST(SubsetSumProblemTest, RecursiveSubsetSumTest) - { - // Arrange - DynamicProgramming dp; - vector nums = { 3, 34, 4, 12, 5, 2 }; - int sum = 9; - bool expectedResult = true; - - // Act - bool actualResult = dp.RecursiveSubsetSum(nums, sum); - - // Assert - ASSERT_EQ(expectedResult, actualResult); - } - - TEST(SubsetSumProblemTest, DpSubsetSumTest) - { - // Arrange - DynamicProgramming dp; - vector nums = { 3, 34, 4, 12, 5, 2 }; - int sum = 9; - bool expectedResult = true; - - // Act - bool actualResult = dp.DpIsSubsetSum(nums, sum); - - // Assert - ASSERT_EQ(expectedResult, actualResult); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0015_CountSubsetsForSumTest.cc b/tests/0004_dynamic_programming/0015_CountSubsetsForSumTest.cc deleted file mode 100644 index ba1fa7f..0000000 --- a/tests/0004_dynamic_programming/0015_CountSubsetsForSumTest.cc +++ /dev/null @@ -1,35 +0,0 @@ -#include -#include"0015_CountSubsetsForSum.h" - -namespace CountSubsetsForSum -{ - TEST(CountSubsetsForSum, RecursiveCountSubsetSum) - { - // Arrange - DynamicProgramming dp; - vector nums = { 1, 2, 3, 3 }; - int sum = 6; - int expectedCount = 3; - - // Act - int actualCount = dp.RecursiveCountSubsets(nums, sum); - - // Assert - ASSERT_EQ(expectedCount, actualCount); - } - - TEST(CountSubsetsForSum, DpCountSubsetSum) - { - // Arrange - DynamicProgramming dp; - vector nums = { 1, 2, 3, 3 }; - int sum = 6; - int expectedCount = 3; - - // Act - int actualCount = dp.DpCountSubsets(nums, sum); - - // Assert - ASSERT_EQ(expectedCount, actualCount); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0016_PartitionEqualSubsetSumTest.cc b/tests/0004_dynamic_programming/0016_PartitionEqualSubsetSumTest.cc deleted file mode 100644 index 2bfa292..0000000 --- a/tests/0004_dynamic_programming/0016_PartitionEqualSubsetSumTest.cc +++ /dev/null @@ -1,33 +0,0 @@ -#include -#include "0016_PartitionEqualSubsetSum.h" - -namespace PartitionEqualSubsetSum -{ - TEST(PartitionEqualSubsetSum, RecursivePartitionEqualSubsetSum) - { - // Arrange - DynamicProgramming dp; - vector nums = { 1, 5, 11, 5 }; - bool expectedResult = true; - - // Act - bool actualResult = dp.RecursivePartitionEqualSubsets(nums); - - // Assert - ASSERT_EQ(expectedResult, actualResult); - } - - TEST(PartitionEqualSubsetSum, DpPartitionEqualSubsetSum) - { - // Arrange - DynamicProgramming dp; - vector nums = { 1, 5, 11, 5 }; - bool expectedResult = true; - - // Act - bool actualResult = dp.DpPartitionEqualSubsets(nums); - - // Assert - ASSERT_EQ(expectedResult, actualResult); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0017_TargetSumTest.cc b/tests/0004_dynamic_programming/0017_TargetSumTest.cc deleted file mode 100644 index ab3fbf4..0000000 --- a/tests/0004_dynamic_programming/0017_TargetSumTest.cc +++ /dev/null @@ -1,50 +0,0 @@ -#include -#include "0017_TargetSum.h" - -namespace TargetSum -{ - TEST(TargetSum, RecursiveSolutionTest_ValidInput_ReturnsCorrectResult) - { - // Arrange - DynamicProgramming dp; - vector nums = { 1, 1, 1, 1, 1 }; - int target = 3; - int expectedResult = 5; - - // Act - int actualResult = dp.RecursiveFindTotalWays(nums, target); - - // Assert - ASSERT_EQ(expectedResult, actualResult); - } - - TEST(TargetSum, DpSolutionTest_ValidInput_ReturnsCorrectResult) - { - // Arrange - DynamicProgramming dp; - vector nums = { 1, 1, 1, 1, 1 }; - int target = 3; - int expectedResult = 5; - - // Act - int actualResult = dp.DpFindTotalWays(nums, target); - - // Assert - ASSERT_EQ(expectedResult, actualResult); - } - - TEST(TargetSum, DpSolutionTest_TargetGreaterThanTotalSum_ReturnsZero) - { - // Arrange - DynamicProgramming dp; - vector nums = { 1, 1, 1, 1, 1 }; - int target = -1000; - int expectedResult = 0; - - // Act - int actualResult = dp.DpFindTotalWays(nums, target); - - // Assert - ASSERT_EQ(expectedResult, actualResult); - } -} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/CMakeLists.txt b/tests/0004_dynamic_programming/CMakeLists.txt deleted file mode 100644 index 4ef67b0..0000000 --- a/tests/0004_dynamic_programming/CMakeLists.txt +++ /dev/null @@ -1,49 +0,0 @@ -cmake_policy(SET CMP0135 NEW) - -include(FetchContent) -FetchContent_Declare( - googletest - URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip -) - -# For Windows: Prevent overriding the parent project's compiler/linker settings -set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) -FetchContent_MakeAvailable(googletest) - -enable_testing() - -add_executable( - 0005DynamicProgrammingTests - 0001_FibonacciNumberTest.cc - 0002_TribonacciNumberTest.cc - 0003_ClimbingStairsTest.cc - 0004_MinimumCostClimbingStairsTest.cc - 0005_HouseRobber1Test.cc - 0006_HouseRobber2Test.cc - 0007_DecodeWaysTest.cc - 0008_TilingProblemTest.cc - 0009_FriendsPairingProblemTest.cc - 0010_WaysToCoverDistanceTest.cc - 0011_CountWaysToReachNthStairIncludeOrderTest.cc - 0012_CountWaysToReachNthStairExcludeOrderTest.cc - 0013_KnapsackProblemTest.cc - 0014_SubsetSumProblemTest.cc - 0015_CountSubsetsForSumTest.cc - 0016_PartitionEqualSubsetSumTest.cc - 0017_TargetSumTest.cc - -) - -target_link_libraries( - 0005DynamicProgrammingTests - GTest::gtest_main - 0005DYNAMICPROGRAMMING -) - -# Add .clang-tidy configuration to this library. -if(CLANG_TIDY_EXE) - set_target_properties(0005DYNAMICPROGRAMMING PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") -endif() - -include(GoogleTest) -gtest_discover_tests(0005DynamicProgrammingTests DISCOVERY_TIMEOUT 30) \ No newline at end of file diff --git a/tests/0005_greedy_algorithms/CMakeLists.txt b/tests/0005_greedy_algorithms/CMakeLists.txt deleted file mode 100644 index e69de29..0000000 diff --git a/tests/0006_bitwise_algorithms/CMakeLists.txt b/tests/0006_bitwise_algorithms/CMakeLists.txt deleted file mode 100644 index e69de29..0000000 diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt deleted file mode 100644 index 41d781c..0000000 --- a/tests/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -add_subdirectory(0000_common_utilities) -add_subdirectory(0001_basics) -add_subdirectory(0002_tree) -add_subdirectory(0003_graph) -add_subdirectory(0004_dynamic_programming) -add_subdirectory(0005_greedy_algorithms) -add_subdirectory(0006_bitwise_algorithms) \ No newline at end of file From de9d991d356c4fcef221243d36d820d382a68129 Mon Sep 17 00:00:00 2001 From: Debashis Nandi Date: Sat, 13 Jun 2026 03:25:01 +0530 Subject: [PATCH 06/13] feat: reinstated all files after renaming --- .clang-tidy | 27 ++ .github/ISSUE_TEMPLATE/bug_report.md | 28 ++ .github/labeler.yaml | 51 +++ .github/pull_request_template.md | 28 ++ .github/release.yaml | 56 +++ .github/workflows/auto-labeler.yaml | 36 ++ .github/workflows/deploy.yaml | 160 ++++++++ .github/workflows/validate.yaml | 130 +++++++ .gitignore | 3 + CMakeLists.txt | 35 ++ CMakePresets.json | 61 +++ CODE_OF_CONDUCT.md | 127 +++++++ CONTRIBUTING.md | 1 + LICENSE | 21 ++ README.md | 21 ++ SECURITY.md | 1 + src/0001_basics/CMakeLists.txt | 11 + src/0001_basics/headers/node.h | 8 + src/0001_basics/node.cc | 6 + src/0002_tree/0001_binary_search_tree.cc | 349 ++++++++++++++++++ src/0002_tree/CMakeLists.txt | 11 + .../headers/0001_binary_search_tree.h | 49 +++ src/0003_graph/0001_breadth_first_search.cc | 86 +++++ src/0003_graph/0002_depth_first_search.cc | 80 ++++ src/0003_graph/0003_topological_sort.cc | 150 ++++++++ .../0004_strongly_connected_components.cc | 121 ++++++ .../0005_hamiltonian_path_and_cycle.cc | 114 ++++++ .../0006_eulerian_path_and_circuit.cc | 212 +++++++++++ ...minimum_spanning_tree_kruskal_algorithm.cc | 108 ++++++ ...08_minimum_spanning_tree_prim_algorithm.cc | 85 +++++ ...ingle_source_shortest_path_bellman_ford.cc | 108 ++++++ ...10_directed_acyclic_graph_shortest_path.cc | 124 +++++++ ...11_single_source_shortest_path_dijkstra.cc | 113 ++++++ ...2_difference_constraints_shortest_paths.cc | 133 +++++++ ...all_pairs_shortest_paths_floyd_warshall.cc | 104 ++++++ .../0014_all_pairs_shortest_paths_johnson.cc | 217 +++++++++++ .../0015_maximum_flow_ford_fulkerson.cc | 139 +++++++ .../0016_maximum_flow_edmonds_karp.cc | 144 ++++++++ .../0017_maximum_bipartite_matching.cc | 263 +++++++++++++ ...imum_flow_goldberg_generic_push_relabel.cc | 172 +++++++++ .../0019_maximum_flow_relabel_to_front.cc | 169 +++++++++ src/0003_graph/CMakeLists.txt | 30 ++ .../headers/0001_breadth_first_search.h | 35 ++ .../headers/0002_depth_first_search.h | 37 ++ .../headers/0003_topological_sort.h | 42 +++ .../0004_strongly_connected_components.h | 43 +++ .../headers/0005_hamiltonian_path_and_cycle.h | 40 ++ .../headers/0006_eulerian_path_and_circuit.h | 43 +++ ..._minimum_spanning_tree_kruskal_algorithm.h | 46 +++ ...008_minimum_spanning_tree_prim_algorithm.h | 42 +++ ...single_source_shortest_path_bellman_ford.h | 44 +++ ...010_directed_acyclic_graph_shortest_path.h | 51 +++ ...011_single_source_shortest_path_dijkstra.h | 55 +++ ...12_difference_constraints_shortest_paths.h | 43 +++ ..._all_pairs_shortest_paths_floyd_warshall.h | 24 ++ .../0014_all_pairs_shortest_paths_johnson.h | 66 ++++ .../0015_maximum_flow_ford_fulkerson.h | 29 ++ .../headers/0016_maximum_flow_edmonds_karp.h | 28 ++ .../headers/0017_maximum_bipartite_matching.h | 41 ++ ...ximum_flow_goldberg_generic_push_relabel.h | 31 ++ .../0019_maximum_flow_relabel_to_front.h | 31 ++ .../0001_fibonacci_number.cc | 28 ++ .../0002_tribonacci_number.cc | 33 ++ .../0003_climbing_stairs.cc | 29 ++ .../0004_minimum_cost_climbing_stairs.cc | 48 +++ .../0005_house_robber1.cc | 44 +++ .../0006_house_robber2.cc | 95 +++++ .../0007_decode_ways.cc | 61 +++ .../0008_tiling_problem.cc | 42 +++ .../0009_friends_pairing_problem.cc | 39 ++ .../0010_ways_to_cover_distance.cc | 52 +++ ...t_ways_to_reach_nth_stair_include_order.cc | 44 +++ ...t_ways_to_reach_nth_stair_exclude_order.cc | 53 +++ .../0013_knapsack_problem.cc | 78 ++++ .../0014_subset_sum_problem.cc | 71 ++++ .../0015_count_subsets_for_sum.cc | 55 +++ .../0016_partition_equal_subset_sum.cc | 75 ++++ .../0017_target_sum.cc | 70 ++++ src/0004_dynamic_programming/CMakeLists.txt | 28 ++ .../headers/0001_fibonacci_number.h | 23 ++ .../headers/0002_tribonacci_number.h | 23 ++ .../headers/0003_climbing_stairs.h | 24 ++ .../0004_minimum_cost_climbing_stairs.h | 25 ++ .../headers/0005_house_robber1.h | 25 ++ .../headers/0006_house_robber2.h | 28 ++ .../headers/0007_decode_ways.h | 32 ++ .../headers/0008_tiling_problem.h | 25 ++ .../headers/0009_friends_pairing_problem.h | 46 +++ .../headers/0010_ways_to_cover_distance.h | 47 +++ ...nt_ways_to_reach_nth_stair_include_order.h | 42 +++ ...nt_ways_to_reach_nth_stair_exclude_order.h | 44 +++ .../headers/0013_knapsack_problem.h | 34 ++ .../headers/0014_subset_sum_problem.h | 34 ++ .../headers/0015_count_subsets_for_sum.h | 34 ++ .../headers/0016_partition_equal_subset_sum.h | 36 ++ .../headers/0017_target_sum.h | 45 +++ src/0005_greedy_algorithms/CMakeLists.txt | 0 src/0006_bitwise_algorithms/CMakeLists.txt | 0 src/CMakeLists.txt | 6 + tests/0000_common_utilities/CMakeLists.txt | 0 .../0000_common_utilities/unit_test_helper.h | 183 +++++++++ tests/0001_basics/CMakeLists.txt | 31 ++ tests/0001_basics/node_test.cc | 12 + .../0002_tree/0001_binary_search_tree_test.cc | 91 +++++ tests/0002_tree/CMakeLists.txt | 32 ++ .../0001_breadth_first_search_test.cc | 45 +++ .../0002_depth_first_search_test.cc | 177 +++++++++ .../0003_graph/0003_topological_sort_test.cc | 116 ++++++ ...0004_strongly_connected_components_test.cc | 102 +++++ .../0005_hamiltonian_path_and_cycle_test.cc | 33 ++ .../0006_eulerian_path_and_circuit_test.cc | 32 ++ ...um_spanning_tree_kruskal_algorithm_test.cc | 45 +++ ...nimum_spanning_tree_prim_algorithm_test.cc | 45 +++ ..._source_shortest_path_bellman_ford_test.cc | 104 ++++++ ...rected_acyclic_graph_shortest_path_test.cc | 29 ++ ...ngle_source_shortest_path_dijkstra_test.cc | 31 ++ ...ference_constraints_shortest_paths_test.cc | 40 ++ ...airs_shortest_paths_floyd_warshall_test.cc | 36 ++ ...4_all_pairs_shortest_paths_johnson_test.cc | 44 +++ .../0015_maximum_flow_ford_fulkerson_test.cc | 64 ++++ .../0016_maximum_flow_edmonds_karp_test.cc | 64 ++++ .../0017_maximum_bipartite_matching_test.cc | 35 ++ ...flow_goldberg_generic_push_relabel_test.cc | 35 ++ ...0019_maximum_flow_relabel_to_front_test.cc | 36 ++ tests/0003_graph/CMakeLists.txt | 50 +++ .../0001_fibonacci_number_test.cc | 34 ++ .../0002_tribonacci_number_test.cc | 34 ++ .../0003_climbing_stairs_test.cc | 33 ++ .../0004_minimum_cost_climbing_stairs_test.cc | 33 ++ .../0005_house_robber1_test.cc | 33 ++ .../0006_house_robber2_test.cc | 48 +++ .../0007_decode_ways_test.cc | 47 +++ .../0008_tiling_problem_test.cc | 33 ++ .../0009_friends_pairing_problem_test.cc | 91 +++++ .../0010_ways_to_cover_distance_test.cc | 117 ++++++ ...s_to_reach_nth_stair_include_order_test.cc | 33 ++ ...s_to_reach_nth_stair_exclude_order_test.cc | 33 ++ .../0013_knapsack_problem_test.cc | 53 +++ .../0014_subset_sum_problem_test.cc | 35 ++ .../0015_count_subsets_for_sum_test.cc | 35 ++ .../0016_partition_equal_subset_sum_test.cc | 33 ++ .../0017_target_sum_test.cc | 50 +++ tests/0004_dynamic_programming/CMakeLists.txt | 49 +++ tests/0005_greedy_algorithms/CMakeLists.txt | 0 tests/0006_bitwise_algorithms/CMakeLists.txt | 0 tests/CMakeLists.txt | 7 + 146 files changed, 8524 insertions(+) create mode 100644 .clang-tidy create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/labeler.yaml create mode 100644 .github/pull_request_template.md create mode 100644 .github/release.yaml create mode 100644 .github/workflows/auto-labeler.yaml create mode 100644 .github/workflows/deploy.yaml create mode 100644 .github/workflows/validate.yaml create mode 100644 .gitignore create mode 100644 CMakeLists.txt create mode 100644 CMakePresets.json create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 README.md create mode 100644 SECURITY.md create mode 100644 src/0001_basics/CMakeLists.txt create mode 100644 src/0001_basics/headers/node.h create mode 100644 src/0001_basics/node.cc create mode 100644 src/0002_tree/0001_binary_search_tree.cc create mode 100644 src/0002_tree/CMakeLists.txt create mode 100644 src/0002_tree/headers/0001_binary_search_tree.h create mode 100644 src/0003_graph/0001_breadth_first_search.cc create mode 100644 src/0003_graph/0002_depth_first_search.cc create mode 100644 src/0003_graph/0003_topological_sort.cc create mode 100644 src/0003_graph/0004_strongly_connected_components.cc create mode 100644 src/0003_graph/0005_hamiltonian_path_and_cycle.cc create mode 100644 src/0003_graph/0006_eulerian_path_and_circuit.cc create mode 100644 src/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm.cc create mode 100644 src/0003_graph/0008_minimum_spanning_tree_prim_algorithm.cc create mode 100644 src/0003_graph/0009_single_source_shortest_path_bellman_ford.cc create mode 100644 src/0003_graph/0010_directed_acyclic_graph_shortest_path.cc create mode 100644 src/0003_graph/0011_single_source_shortest_path_dijkstra.cc create mode 100644 src/0003_graph/0012_difference_constraints_shortest_paths.cc create mode 100644 src/0003_graph/0013_all_pairs_shortest_paths_floyd_warshall.cc create mode 100644 src/0003_graph/0014_all_pairs_shortest_paths_johnson.cc create mode 100644 src/0003_graph/0015_maximum_flow_ford_fulkerson.cc create mode 100644 src/0003_graph/0016_maximum_flow_edmonds_karp.cc create mode 100644 src/0003_graph/0017_maximum_bipartite_matching.cc create mode 100644 src/0003_graph/0018_maximum_flow_goldberg_generic_push_relabel.cc create mode 100644 src/0003_graph/0019_maximum_flow_relabel_to_front.cc create mode 100644 src/0003_graph/CMakeLists.txt create mode 100644 src/0003_graph/headers/0001_breadth_first_search.h create mode 100644 src/0003_graph/headers/0002_depth_first_search.h create mode 100644 src/0003_graph/headers/0003_topological_sort.h create mode 100644 src/0003_graph/headers/0004_strongly_connected_components.h create mode 100644 src/0003_graph/headers/0005_hamiltonian_path_and_cycle.h create mode 100644 src/0003_graph/headers/0006_eulerian_path_and_circuit.h create mode 100644 src/0003_graph/headers/0007_minimum_spanning_tree_kruskal_algorithm.h create mode 100644 src/0003_graph/headers/0008_minimum_spanning_tree_prim_algorithm.h create mode 100644 src/0003_graph/headers/0009_single_source_shortest_path_bellman_ford.h create mode 100644 src/0003_graph/headers/0010_directed_acyclic_graph_shortest_path.h create mode 100644 src/0003_graph/headers/0011_single_source_shortest_path_dijkstra.h create mode 100644 src/0003_graph/headers/0012_difference_constraints_shortest_paths.h create mode 100644 src/0003_graph/headers/0013_all_pairs_shortest_paths_floyd_warshall.h create mode 100644 src/0003_graph/headers/0014_all_pairs_shortest_paths_johnson.h create mode 100644 src/0003_graph/headers/0015_maximum_flow_ford_fulkerson.h create mode 100644 src/0003_graph/headers/0016_maximum_flow_edmonds_karp.h create mode 100644 src/0003_graph/headers/0017_maximum_bipartite_matching.h create mode 100644 src/0003_graph/headers/0018_maximum_flow_goldberg_generic_push_relabel.h create mode 100644 src/0003_graph/headers/0019_maximum_flow_relabel_to_front.h create mode 100644 src/0004_dynamic_programming/0001_fibonacci_number.cc create mode 100644 src/0004_dynamic_programming/0002_tribonacci_number.cc create mode 100644 src/0004_dynamic_programming/0003_climbing_stairs.cc create mode 100644 src/0004_dynamic_programming/0004_minimum_cost_climbing_stairs.cc create mode 100644 src/0004_dynamic_programming/0005_house_robber1.cc create mode 100644 src/0004_dynamic_programming/0006_house_robber2.cc create mode 100644 src/0004_dynamic_programming/0007_decode_ways.cc create mode 100644 src/0004_dynamic_programming/0008_tiling_problem.cc create mode 100644 src/0004_dynamic_programming/0009_friends_pairing_problem.cc create mode 100644 src/0004_dynamic_programming/0010_ways_to_cover_distance.cc create mode 100644 src/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order.cc create mode 100644 src/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order.cc create mode 100644 src/0004_dynamic_programming/0013_knapsack_problem.cc create mode 100644 src/0004_dynamic_programming/0014_subset_sum_problem.cc create mode 100644 src/0004_dynamic_programming/0015_count_subsets_for_sum.cc create mode 100644 src/0004_dynamic_programming/0016_partition_equal_subset_sum.cc create mode 100644 src/0004_dynamic_programming/0017_target_sum.cc create mode 100644 src/0004_dynamic_programming/CMakeLists.txt create mode 100644 src/0004_dynamic_programming/headers/0001_fibonacci_number.h create mode 100644 src/0004_dynamic_programming/headers/0002_tribonacci_number.h create mode 100644 src/0004_dynamic_programming/headers/0003_climbing_stairs.h create mode 100644 src/0004_dynamic_programming/headers/0004_minimum_cost_climbing_stairs.h create mode 100644 src/0004_dynamic_programming/headers/0005_house_robber1.h create mode 100644 src/0004_dynamic_programming/headers/0006_house_robber2.h create mode 100644 src/0004_dynamic_programming/headers/0007_decode_ways.h create mode 100644 src/0004_dynamic_programming/headers/0008_tiling_problem.h create mode 100644 src/0004_dynamic_programming/headers/0009_friends_pairing_problem.h create mode 100644 src/0004_dynamic_programming/headers/0010_ways_to_cover_distance.h create mode 100644 src/0004_dynamic_programming/headers/0011_count_ways_to_reach_nth_stair_include_order.h create mode 100644 src/0004_dynamic_programming/headers/0012_count_ways_to_reach_nth_stair_exclude_order.h create mode 100644 src/0004_dynamic_programming/headers/0013_knapsack_problem.h create mode 100644 src/0004_dynamic_programming/headers/0014_subset_sum_problem.h create mode 100644 src/0004_dynamic_programming/headers/0015_count_subsets_for_sum.h create mode 100644 src/0004_dynamic_programming/headers/0016_partition_equal_subset_sum.h create mode 100644 src/0004_dynamic_programming/headers/0017_target_sum.h create mode 100644 src/0005_greedy_algorithms/CMakeLists.txt create mode 100644 src/0006_bitwise_algorithms/CMakeLists.txt create mode 100644 src/CMakeLists.txt create mode 100644 tests/0000_common_utilities/CMakeLists.txt create mode 100644 tests/0000_common_utilities/unit_test_helper.h create mode 100644 tests/0001_basics/CMakeLists.txt create mode 100644 tests/0001_basics/node_test.cc create mode 100644 tests/0002_tree/0001_binary_search_tree_test.cc create mode 100644 tests/0002_tree/CMakeLists.txt create mode 100644 tests/0003_graph/0001_breadth_first_search_test.cc create mode 100644 tests/0003_graph/0002_depth_first_search_test.cc create mode 100644 tests/0003_graph/0003_topological_sort_test.cc create mode 100644 tests/0003_graph/0004_strongly_connected_components_test.cc create mode 100644 tests/0003_graph/0005_hamiltonian_path_and_cycle_test.cc create mode 100644 tests/0003_graph/0006_eulerian_path_and_circuit_test.cc create mode 100644 tests/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm_test.cc create mode 100644 tests/0003_graph/0008_minimum_spanning_tree_prim_algorithm_test.cc create mode 100644 tests/0003_graph/0009_single_source_shortest_path_bellman_ford_test.cc create mode 100644 tests/0003_graph/0010_directed_acyclic_graph_shortest_path_test.cc create mode 100644 tests/0003_graph/0011_single_source_shortest_path_dijkstra_test.cc create mode 100644 tests/0003_graph/0012_difference_constraints_shortest_paths_test.cc create mode 100644 tests/0003_graph/0013_all_pairs_shortest_paths_floyd_warshall_test.cc create mode 100644 tests/0003_graph/0014_all_pairs_shortest_paths_johnson_test.cc create mode 100644 tests/0003_graph/0015_maximum_flow_ford_fulkerson_test.cc create mode 100644 tests/0003_graph/0016_maximum_flow_edmonds_karp_test.cc create mode 100644 tests/0003_graph/0017_maximum_bipartite_matching_test.cc create mode 100644 tests/0003_graph/0018_maximum_flow_goldberg_generic_push_relabel_test.cc create mode 100644 tests/0003_graph/0019_maximum_flow_relabel_to_front_test.cc create mode 100644 tests/0003_graph/CMakeLists.txt create mode 100644 tests/0004_dynamic_programming/0001_fibonacci_number_test.cc create mode 100644 tests/0004_dynamic_programming/0002_tribonacci_number_test.cc create mode 100644 tests/0004_dynamic_programming/0003_climbing_stairs_test.cc create mode 100644 tests/0004_dynamic_programming/0004_minimum_cost_climbing_stairs_test.cc create mode 100644 tests/0004_dynamic_programming/0005_house_robber1_test.cc create mode 100644 tests/0004_dynamic_programming/0006_house_robber2_test.cc create mode 100644 tests/0004_dynamic_programming/0007_decode_ways_test.cc create mode 100644 tests/0004_dynamic_programming/0008_tiling_problem_test.cc create mode 100644 tests/0004_dynamic_programming/0009_friends_pairing_problem_test.cc create mode 100644 tests/0004_dynamic_programming/0010_ways_to_cover_distance_test.cc create mode 100644 tests/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order_test.cc create mode 100644 tests/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order_test.cc create mode 100644 tests/0004_dynamic_programming/0013_knapsack_problem_test.cc create mode 100644 tests/0004_dynamic_programming/0014_subset_sum_problem_test.cc create mode 100644 tests/0004_dynamic_programming/0015_count_subsets_for_sum_test.cc create mode 100644 tests/0004_dynamic_programming/0016_partition_equal_subset_sum_test.cc create mode 100644 tests/0004_dynamic_programming/0017_target_sum_test.cc create mode 100644 tests/0004_dynamic_programming/CMakeLists.txt create mode 100644 tests/0005_greedy_algorithms/CMakeLists.txt create mode 100644 tests/0006_bitwise_algorithms/CMakeLists.txt create mode 100644 tests/CMakeLists.txt diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 0000000..b797f75 --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,27 @@ +Checks: > + readability-identifier-naming + +WarningsAsErrors: '*' + +HeaderFilterRegex: '(include/.*|source/.*)' + +CheckOptions: + # Private member variables + - key: readability-identifier-naming.PrivateMemberPrefix + value: _ + - key: readability-identifier-naming.PrivateMemberCase + value: camelBack + + # Member function (non-static, non-const, non-virtual) + - key: readability-identifier-naming.MethodCase + value: CamelCase + + # Class names + - key: readability-identifier-naming.ClassCase + value: CamelCase + + # Optional, but ensures errors are reported instead of silently skipped + - key: readability-identifier-naming.IgnoreFailures + value: false + - key: readability-identifier-naming.IgnoreFailedSplit + value: false \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..bfe83ee --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,28 @@ +## Bug Report + +### Describe the Bug +_A clear and concise description of what the bug is._ + +### Steps to Reproduce +_Steps to reproduce the behavior:_ +1. Go to `path/to/file.cpp` +2. Run the test case: `./test_case_name` +3. Observe the error + +### Expected Behavior +_A clear and concise description of what you expected to happen._ + +### Screenshots/Outputs +_If applicable, add screenshots or log output to help explain the issue._ + +### Environment (please complete the following information): +- **OS:** [e.g., Windows, macOS, Linux] +- **Compiler:** [e.g., GCC 11, Clang 14, MSVC] +- **CMake Version:** [if applicable] +- **Any other relevant setup details** + +### Possible Fix (Optional) +_If you have an idea of how to fix it, mention it here._ + +### Additional Context +_Add any other context about the problem here._ diff --git a/.github/labeler.yaml b/.github/labeler.yaml new file mode 100644 index 0000000..dae837a --- /dev/null +++ b/.github/labeler.yaml @@ -0,0 +1,51 @@ +# Data Structures and Algorithms: These labels group include, src, and tests by their specific topic +basics: + - changed-files: + - any-glob-to-any-file: 'include/0001_Basics/**' + - any-glob-to-any-file: 'src/0001_Basics/**' + - any-glob-to-any-file: 'tests/0001_Basics/**' +tree: + - changed-files: + - any-glob-to-any-file: 'include/0002_Tree/**' + - any-glob-to-any-file: 'src/0002_Tree/**' + - any-glob-to-any-file: 'tests/0002_Tree/**' +graph: + - changed-files: + - any-glob-to-any-file: 'include/0003_Graph/**' + - any-glob-to-any-file: 'src/0003_Graph/**' + - any-glob-to-any-file: 'tests/0003_Graph/**' +greedy-algorithms: + - changed-files: + - any-glob-to-any-file: 'include/0004_GreedyAlgorithms/**' + - any-glob-to-any-file: 'src/0004_GreedyAlgorithms/**' + - any-glob-to-any-file: 'tests/0004_GreedyAlgorithms/**' +dynamic-programming: + - changed-files: + - any-glob-to-any-file: 'include/0005_DynamicProgramming/**' + - any-glob-to-any-file: 'src/0005_DynamicProgramming/**' + - any-glob-to-any-file: 'tests/0005_DynamicProgramming/**' +bitwise-algorithms: + - changed-files: + - any-glob-to-any-file: 'include/0006_BitwiseAlgorithms/**' + - any-glob-to-any-file: 'src/0006_BitwiseAlgorithms/**' + - any-glob-to-any-file: 'tests/0006_BitwiseAlgorithms/**' + +# Build System: Only fires when every changed file is a CMakeLists.txt +build: + - changed-files: + - all-globs-to-all-files: '**/CMakeLists.txt' + +# Testing Utils: Catches the helper files in tests/0000_CommonUtilities +test-utils: + - changed-files: + - any-glob-to-any-file: 'tests/0000_CommonUtilities/**' + +# Tooling: Github workflows +workflows: + - changed-files: + - any-glob-to-any-file: '.github/**' + +# Documentation: Root level MD files +documentation: + - changed-files: + - any-glob-to-any-file: '*.md' \ No newline at end of file diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..b9581fa --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,28 @@ +### Pull Request Guidelines + +1. **feature → release:** Please provide a description of the solution or fix. The `auto-labeler` bot will automatically label this PR based on the files changed. +2. **release → main:** **Please select the version bump type**, release notes will be auto-generated from the merged feature PRs. + +### feature to release +*(Fill this out when merging a feature branch into a release branch)* + +**Description Category** +- [ ] Basics +- [ ] Tree +- [ ] Graph +- [ ] GreedyAlgorithms +- [ ] DynamicProgramming +- [ ] BitwiseAlgorithms + +**Notes** + + + + +### release to main +*(Fill this out ONLY when merging a release branch into main)* + +**Version Bump Type** +- [ ] Major +- [ ] Minor +- [ ] Patch \ No newline at end of file diff --git a/.github/release.yaml b/.github/release.yaml new file mode 100644 index 0000000..f4ee77d --- /dev/null +++ b/.github/release.yaml @@ -0,0 +1,56 @@ +template: | + ### datastructures-algorithms — release v$RESOLVED_VERSION + $CHANGES + + **Full Changelog:** https://github.com/$OWNER/$REPOSITORY/compare/$PREVIOUS_TAG...v$RESOLVED_VERSION + +change-template: '- $TITLE [#$NUMBER]' + +categories: + - title: 'Basics' + labels: + - 'basics' + + - title: 'Tree' + labels: + - 'tree' + + - title: 'Graph' + labels: + - 'graph' + + - title: 'Greedy Algorithms' + labels: + - 'greedy-algorithms' + + - title: 'Dynamic Programming' + labels: + - 'dynamic-programming' + + - title: 'Bitwise Algorithms' + labels: + - 'bitwise-algorithms' + + - title: 'Build System (CMake)' + labels: + - 'build' + + - title: 'Testing Utilities' + labels: + - 'test-utils' + + - title: 'Workflows Updated' + labels: + - 'workflows' + + - title: 'Documentation' + labels: + - 'documentation' + +exclude-labels: + - 'skip-changelog' + +# Convert "## Title" to "**Title**" +replacers: + - search: '/^## (.*)$/gm' + replace: '**$1**' \ No newline at end of file diff --git a/.github/workflows/auto-labeler.yaml b/.github/workflows/auto-labeler.yaml new file mode 100644 index 0000000..df13bc0 --- /dev/null +++ b/.github/workflows/auto-labeler.yaml @@ -0,0 +1,36 @@ +name: auto-labeler + +# Run this on every PR open or update +on: + pull_request: + types: [opened, synchronize, reopened] + +permissions: + contents: read + # Required to add labels + pull-requests: write + +jobs: + assign-labels: + runs-on: ubuntu-latest + steps: + - name: Checkout Repository + uses: actions/checkout@v4 + # 1. Standard File-based Labeler (Contest vs Problemset) + - name: Assign Labels Based on Changes + id: labeler + uses: actions/labeler@v5 + with: + # This tells it to look at your .github/labeler.yaml + configuration-path: .github/labeler.yaml + repo-token: "${{ secrets.GITHUB_TOKEN }}" + sync-labels: true + + # 2. NEW: Branch-based Labeler (Ignore Release Branches) + - name: Label Release PRs to Skip Changelog + # Only run if the source branch starts with 'release/' + if: startsWith(github.head_ref, 'release/') + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + gh pr edit ${{ github.event.pull_request.number }} --add-label "skip-changelog" \ No newline at end of file diff --git a/.github/workflows/deploy.yaml b/.github/workflows/deploy.yaml new file mode 100644 index 0000000..9f024d9 --- /dev/null +++ b/.github/workflows/deploy.yaml @@ -0,0 +1,160 @@ +name: deploy + +# Triggers only when a PR to 'main' is closed +on: + pull_request: + types: [closed] + branches: + - 'main' + +permissions: + contents: write # Required to push tags and create releases + pull-requests: read # Required to read PR body for checkboxes + +jobs: + # job 1: Deployment Validation + # Verifies the PR is merged, comes from a release/* branch, and has a bump type. + deployment-validation: + runs-on: ubuntu-latest + # Define outputs to pass to the next job + outputs: + bump_type: ${{ steps.get_bump_type.outputs.bump_type }} + + steps: + - name: Verify Merge and Branch Policy + run: | + IS_MERGED="${{ github.event.pull_request.merged }}" + HEAD_REF="${{ github.event.pull_request.head.ref }}" + + echo "PR Merged: $IS_MERGED" + echo "Source Branch: $HEAD_REF" + + # 1. Check if PR was actually merged (not just closed) + if [[ "$IS_MERGED" != "true" ]]; then + echo "::notice::PR was closed without merging. Skipping release." + exit 1 + fi + + # 2. Check if source branch starts with 'release/' + if [[ "$HEAD_REF" != release/* ]]; then + echo "::error::Invalid source branch. Releases must originate from 'release/*' branches." + exit 1 + fi + + echo "Branch policy checks passed." + + - name: Determine Version Bump Type + id: get_bump_type + env: + PR_BODY: ${{ github.event.pull_request.body }} + run: | + # Check checkboxes in PR Body: [x] Major, [x] Minor, etc. + if echo "$PR_BODY" | grep -q '\[x\] Major'; then + echo "bump_type=major" >> $GITHUB_OUTPUT + echo "Detected bump: MAJOR" + elif echo "$PR_BODY" | grep -q '\[x\] Minor'; then + echo "bump_type=minor" >> $GITHUB_OUTPUT + echo "Detected bump: MINOR" + elif echo "$PR_BODY" | grep -q '\[x\] Patch'; then + echo "bump_type=patch" >> $GITHUB_OUTPUT + echo "Detected bump: PATCH" + else + echo "::error::No version bump detected. Please check [x] Major, [x] Minor, or [x] Patch in the PR body." + exit 1 + fi + + # job 2: Create GitHub Tag and Release + create-github-tag-and-release: + needs: deployment-validation + runs-on: ubuntu-latest + env: + BUMP_TYPE: ${{ needs.deployment-validation.outputs.bump_type }} + + steps: + - name: Checkout main branch + uses: actions/checkout@v4 + with: + ref: 'main' + fetch-depth: 0 # Crucial for calculating history/tags + + - name: Configure Git + run: | + git config --global user.name "github-actions[bot]" + git config --global user.email "github-actions[bot]@users.noreply.github.com" + + # Step A: Find the existing tag + - name: Get Latest Tag + id: get_latest_tag + run: | + # 1. Fetch all tags + git fetch --tags + + # 2. Find latest tag (Sort by version number, take top) + LATEST_TAG=$(git tag --list 'v*.*.*' --sort=-v:refname | head -n 1) + + if [ -z "$LATEST_TAG" ]; then + echo "No previous tags found. Defaulting to v0.0.0" + LATEST_TAG="v0.0.0" + fi + + echo "Latest Tag: $LATEST_TAG" + + # Expose this variable to the next step + echo "latest_tag=$LATEST_TAG" >> $GITHUB_OUTPUT + + # Step B: Do the math + - name: Calculate New Tag + id: calc_new_tag + env: + # Pull the tag from the previous step + LATEST_TAG: ${{ steps.get_latest_tag.outputs.latest_tag }} + # Assuming BUMP_TYPE is set in the Job 'env' as per previous context + run: | + echo "Base Tag: $LATEST_TAG" + echo "Bump Type: $BUMP_TYPE" + + # 1. Parse Version + VERSION=${LATEST_TAG#v} # Remove 'v' + IFS='.' read -r -a parts <<< "$VERSION" + MAJOR=${parts[0]} + MINOR=${parts[1]} + PATCH=${parts[2]} + + # 2. Increment + case "$BUMP_TYPE" in + "major") MAJOR=$((MAJOR + 1)); MINOR=0; PATCH=0 ;; + "minor") MINOR=$((MINOR + 1)); PATCH=0 ;; + "patch") PATCH=$((PATCH + 1)) ;; + esac + + NEW_TAG="v${MAJOR}.${MINOR}.${PATCH}" + + echo "new_tag=$NEW_TAG" >> $GITHUB_OUTPUT + echo "New tag will be: $NEW_TAG" + + - name: Create and push new Git tag + run: | + NEW_TAG=${{ steps.calc_new_tag.outputs.new_tag }} + MERGE_COMMIT_SHA=${{ github.event.pull_request.merge_commit_sha }} + + echo "Tagging commit $MERGE_COMMIT_SHA as $NEW_TAG" + git tag $NEW_TAG $MERGE_COMMIT_SHA + git push origin $NEW_TAG + + # Step D: Generate Auto-Notes and Publish + - name: Create GitHub Release + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + uses: release-drafter/release-drafter@v6 + with: + # Uses your .github/release.yaml to categorize changes + config-name: release.yaml + + # We force it to use the tag you just calculated and pushed + tag: ${{ steps.calc_new_tag.outputs.new_tag }} + name: "${{ steps.calc_new_tag.outputs.new_tag }}" + version: ${{ steps.calc_new_tag.outputs.new_tag }} + + # This makes it a real release (not a draft) + publish: true + \ No newline at end of file diff --git a/.github/workflows/validate.yaml b/.github/workflows/validate.yaml new file mode 100644 index 0000000..47a55f5 --- /dev/null +++ b/.github/workflows/validate.yaml @@ -0,0 +1,130 @@ +name: validate + +on: + pull_request: + types: [opened, synchronize] + branches: + - 'release/*' + - 'main' + +jobs: + # job 1: Policy Check + validate-branch-policy: + runs-on: ubuntu-latest + steps: + - name: Verify Branch Strategy + run: | + HEAD="${{ github.head_ref }}" + BASE="${{ github.base_ref }}" + echo "Verifying path: $HEAD -> $BASE" + + if [[ "$HEAD" == feature/* && "$BASE" == release/* ]]; then + echo "Pull Request is allowed: $HEAD -> $BASE." + exit 0 + elif [[ "$HEAD" == release/* && "$BASE" == main ]]; then + echo "Pull Request is allowed: $HEAD -> $BASE." + exit 0 + else + echo "::error::Invalid Pull Request from '$HEAD' -> '$BASE'." + echo "Allowed: 'feature/*'->'release/*' OR 'release/*'->'main'." + exit 1 + fi + + # job 2: Static Analysis + lint-code: + needs: validate-branch-policy + runs-on: windows-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup MSVC + uses: ilammy/msvc-dev-cmd@v1 + with: + arch: x64 + + - name: Install dependencies + shell: pwsh + run: | + choco install cmake --no-progress -y + choco install ninja --no-progress -y + choco install llvm --no-progress -y + + - name: Configure CMake + shell: pwsh + run: cmake -S . -B build -G "Ninja" -DCMAKE_EXPORT_COMPILE_COMMANDS=ON + + - name: Run clang-tidy + shell: pwsh + run: | + clang-tidy --version + $files = Get-ChildItem -Recurse -Path src -Include *.cpp,*.cc,*.cxx -File + $failed = $false + # These source/.* files would be checked using .clang-tidy maintained at projectroot + foreach ($file in $files) { + Write-Host "Checking $($file.FullName)" + clang-tidy -p build "$($file.FullName)" --warnings-as-errors=* + if ($LASTEXITCODE -ne 0) { $failed = $true } + } + if ($failed) { Write-Error "Clang-tidy failed."; exit 1 } + + # job 3: Build Project + build-project: + needs: lint-code + runs-on: windows-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup MSVC + uses: ilammy/msvc-dev-cmd@v1 + with: + arch: x64 + + - name: Install dependencies + shell: pwsh + run: | + choco install cmake --no-progress -y + choco install ninja --no-progress -y + + - name: Configure CMake + shell: pwsh + run: cmake -S . -B build -G "Ninja" + + - name: Build + shell: pwsh + run: cmake --build build --config Release + + # Upload the build directory so the Test job can use it + - name: Upload Build Artifacts + uses: actions/upload-artifact@v4 + with: + name: build-artifacts + path: build/ + retention-days: 1 + + # job 4: Run all Tests + run-all-tests: + needs: build-project + runs-on: windows-latest + steps: + - name: Checkout code + # We need the source code because CTest might look for source files referenced in tests + uses: actions/checkout@v4 + + - name: Install dependencies + shell: pwsh + # We only need CMake (for ctest) here. Ninja/LLVM usually not needed unless tests invoke them. + run: choco install cmake --no-progress -y + + - name: Download Build Artifacts + uses: actions/download-artifact@v4 + with: + name: build-artifacts + path: build + + - name: Run tests + shell: pwsh + # -C Release is crucial if it's a multi-config generator, though Ninja is single-config. + # Good practice to keep it for consistency. + run: ctest --test-dir build --output-on-failure -C Release \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ccdf92f --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.vs/ +.vscode/ +artifact/ \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..d919238 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,35 @@ +cmake_minimum_required (VERSION 3.10) +project ("datastructures-algorithms") + +set(CMAKE_CXX_STANDARD 14) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) + + +# .clang-tidy setup +find_program(CLANG_TIDY_EXE NAMES "clang-tidy") +if(CLANG_TIDY_EXE) + message(STATUS "clang-tidy found: ${CLANG_TIDY_EXE}") + set(CLANG_TIDY_COMMAND + "${CLANG_TIDY_EXE}" + "--config-file=${CMAKE_SOURCE_DIR}/.clang-tidy" + "--extra-arg-before=-Wno-unknown-warning-option" + "--extra-arg-before=-Wno-c++98-compat-pedantic" + "--quiet" + ) +endif() + +add_subdirectory(src) + +cmake_policy(SET CMP0135 NEW) +include(FetchContent) +FetchContent_Declare( + googletest + URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip +) + +# For Windows: Prevent overriding the parent project's compiler/linker settings +set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) + +enable_testing() +add_subdirectory(tests) \ No newline at end of file diff --git a/CMakePresets.json b/CMakePresets.json new file mode 100644 index 0000000..71f41cb --- /dev/null +++ b/CMakePresets.json @@ -0,0 +1,61 @@ +{ + "version": 3, + "configurePresets": [ + { + "name": "windows-base", + "hidden": true, + "generator": "Ninja", + "binaryDir": "${sourceDir}/artifact/build/${presetName}", + "installDir": "${sourceDir}/artifact/install/${presetName}", + "cacheVariables": { + "CMAKE_C_COMPILER": "cl.exe", + "CMAKE_CXX_COMPILER": "cl.exe" + }, + "condition": { + "type": "equals", + "lhs": "${hostSystemName}", + "rhs": "Windows" + } + }, + { + "name": "x64-debug", + "displayName": "x64 Debug", + "inherits": "windows-base", + "architecture": { + "value": "x64", + "strategy": "external" + }, + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Debug" + } + }, + { + "name": "x64-release", + "displayName": "x64 Release", + "inherits": "x64-debug", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Release" + } + }, + { + "name": "x86-debug", + "displayName": "x86 Debug", + "inherits": "windows-base", + "architecture": { + "value": "x86", + "strategy": "external" + }, + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Debug" + } + }, + { + "name": "x86-release", + "displayName": "x86 Release", + "inherits": "x86-debug", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Release" + } + } + ] +} diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..3f705c7 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,127 @@ +## Contributor Covenant Code of Conduct + +### Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +### Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +### Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +### Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +### Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +### Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +#### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +#### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +#### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +#### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +### Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..68a2127 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1 @@ +## This project is for academic purpose, no contributions are expected right now. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..fd336ec --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Debashis Nandi + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..bd633b7 --- /dev/null +++ b/README.md @@ -0,0 +1,21 @@ +## Data Structures and Algorithms + +This repository contains a collection of **data structures and algorithms** implemented in **C++**. It is designed to provide efficient solutions to common algorithmic problems while adhering to clean coding practices and modular design. + +### Features + +- **Data Structures and Algorithms:** Implementations of data structures and algorithms based on the concepts from the book ***Introduction to Algorithms by Cormen, Leiserson, Rivest, and Stein (CLRS).*** +- **Modular Design:** Code is organized into manageable modules for better readability and reusability. +- **Testing:** + - Built with **CMake** as the build system for ease of compilation and dependency management. + - **Google Test** framework is integrated for comprehensive unit testing to ensure code correctness. + +### Folder Structure + +```plain text +datastructures-algorithms +├── include # Header Files +├── src # Implementation of the solutions +├── tests # Unit tests for implemented solutions +└── CMakeLists.txt # CMake configuration file +``` diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..206769a --- /dev/null +++ b/SECURITY.md @@ -0,0 +1 @@ +## Security Policy diff --git a/src/0001_basics/CMakeLists.txt b/src/0001_basics/CMakeLists.txt new file mode 100644 index 0000000..477c6cd --- /dev/null +++ b/src/0001_basics/CMakeLists.txt @@ -0,0 +1,11 @@ +# Specify the source files +set(0001BASICS_SOURCES + Node.cc +) + +# Create a library target +add_library(0001BASICS ${0001BASICS_SOURCES}) + +target_include_directories(0001BASICS PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}/headers +) \ No newline at end of file diff --git a/src/0001_basics/headers/node.h b/src/0001_basics/headers/node.h new file mode 100644 index 0000000..dcee809 --- /dev/null +++ b/src/0001_basics/headers/node.h @@ -0,0 +1,8 @@ +#pragma once + +class Node +{ +public: + int value; + Node(); +}; \ No newline at end of file diff --git a/src/0001_basics/node.cc b/src/0001_basics/node.cc new file mode 100644 index 0000000..df1effa --- /dev/null +++ b/src/0001_basics/node.cc @@ -0,0 +1,6 @@ +#include "Node.h" + +Node::Node() +{ + value = 8; +} \ No newline at end of file diff --git a/src/0002_tree/0001_binary_search_tree.cc b/src/0002_tree/0001_binary_search_tree.cc new file mode 100644 index 0000000..0f0650e --- /dev/null +++ b/src/0002_tree/0001_binary_search_tree.cc @@ -0,0 +1,349 @@ +#include "0001_BinarySearchTree.h" +#include +#include +using namespace std; + +namespace BinarySearchTree +{ + Node::Node(int data, Node* parent, Node* left, Node* right) + { + this->data = data; + this->parent = parent; + this->left = left; + this->right = right; + } + + BinarySearchTree::BinarySearchTree() + { + this->_root = nullptr; + } + + + void BinarySearchTree::_insertBSTreeNode(Node* node) + { + Node* nodeY = nullptr; + Node* nodeX = this->_root; + while (nodeX != nullptr) + { + nodeY = nodeX; + if (node->data < nodeX->data) + { + nodeX = nodeX->left; + } + else + { + nodeX = nodeX->right; + } + } + node->parent = nodeY; + if (nodeY == nullptr) + { + this->_root = node; + } + else if (node->data < nodeY->data) + { + nodeY->left = node; + } + else + { + nodeY->right = node; + } + } + + Node* BinarySearchTree::_findBSTreeNode(int value) + { + Node* node = this->_root; + while (node != nullptr) + { + if (value < node->data) + { + node = node->left; + } + else if (value > node->data) + { + node = node->right; + } + else + { + break; + } + } + return node; + } + + Node* BinarySearchTree::_findBSTreeMinNode(Node* node) + { + while (node->left != nullptr) + { + node = node->left; + } + return node; + } + + Node* BinarySearchTree::_findBSTreeMaxNode(Node* node) + { + while (node->right != nullptr) + { + node = node->right; + } + return node; + } + + Node* BinarySearchTree::_findSuccessor(Node* node) + { + if (node->right != nullptr) + { + return this->_findBSTreeMinNode(node->right); + } + Node* nodeY = node->parent; + while (nodeY != nullptr && node == nodeY->right) + { + node = nodeY; + nodeY = nodeY->parent; + } + return nodeY; + } + + Node* BinarySearchTree::_findPredecessor(Node* node) + { + if (node->left != nullptr) + { + return this->_findBSTreeMaxNode(node->left); + } + Node* nodeY = node->parent; + while (nodeY != nullptr && node == nodeY->left) + { + node = nodeY; + nodeY = nodeY->parent; + } + return nodeY; + } + + void BinarySearchTree::_transplant(Node* nodeU, Node* nodeV) + { + if (nodeU->parent == nullptr) + { + this->_root = nodeV; + } + else if (nodeU == nodeU->parent->left) + { + nodeU->parent->left = nodeV; + } + else + { + nodeU->parent->right = nodeV; + } + + if (nodeV != nullptr) + { + nodeV->parent = nodeU->parent; + } + } + + void BinarySearchTree::_deleteBSTreeNode(Node* node) + { + if (node->left == nullptr) + { + this->_transplant(node, node->right); + } + else if (node->right == nullptr) + { + this->_transplant(node, node->left); + } + else + { + Node* nodeY = this->_findBSTreeMinNode(node->right); + if (nodeY->parent != node) + { + this->_transplant(nodeY, nodeY->right); + nodeY->right = node->right; + nodeY->right->parent = nodeY; + } + this->_transplant(node, nodeY); + nodeY->left = node->left; + nodeY->left->parent = nodeY; + delete node; + } + } + + void BinarySearchTree::_recursiveInorder(Node* node, vector& result) + { + if (node == nullptr) + { + return; + } + this->_recursiveInorder(node->left, result); + result.push_back(node->data); + this->_recursiveInorder(node->right, result); + } + + void BinarySearchTree::_recursivePreorder(Node* node, vector& result) + { + if (node == nullptr) + { + return; + } + result.push_back(node->data); + this->_recursivePreorder(node->left, result); + this->_recursivePreorder(node->right, result); + } + + void BinarySearchTree::_recursivePostorder(Node* node, vector& result) + { + if (node == nullptr) + { + return; + } + this->_recursivePostorder(node->left, result); + this->_recursivePostorder(node->right, result); + result.push_back(node->data); + } + + void BinarySearchTree::_morrisInorder(Node* node, vector& result) + { + while (node != nullptr) + { + if (node->left == nullptr) + { + result.push_back(node->data); + node = node->right; + } + else + { + Node* predecessor = node->left; + while (predecessor->right != nullptr && predecessor->right != node) + { + predecessor = predecessor->right; + } + if (predecessor->right == nullptr) + { + predecessor->right = node; + node = node->left; + } + else + { + predecessor->right = nullptr; + result.push_back(node->data); + node = node->right; + } + } + } + } + + void BinarySearchTree::_morrisPreorder(Node* node, vector& result) + { + while (node != nullptr) + { + if (node->left == nullptr) + { + result.push_back(node->data); + node = node->right; + } + else + { + Node* predecessor = node->left; + while (predecessor->right != nullptr && predecessor->right != node) + { + predecessor = predecessor->right; + } + if (predecessor->right == nullptr) + { + predecessor->right = node; + result.push_back(node->data); + node = node->left; + } + else + { + predecessor->right = nullptr; + node = node->right; + } + } + } + } + + void BinarySearchTree::_morrisPostorder(Node* node, vector& result) + { + while (node != nullptr) + { + if (node->right == nullptr) + { + result.push_back(node->data); + node = node->left; + } + else + { + Node* predecessor = node->right; + while (predecessor->left != nullptr && predecessor->left != node) + { + predecessor = predecessor->left; + } + if (predecessor->left == nullptr) + { + predecessor->left = node; + result.push_back(node->data); + node = node->right; + } + else + { + predecessor->left = nullptr; + node = node->left; + } + } + } + reverse(result.begin(), result.end()); + } + + void BinarySearchTree::insertNode(int value) + { + Node* node = new Node(value, nullptr, nullptr, nullptr); + this->_insertBSTreeNode(node); + } + + void BinarySearchTree::deleteNode(int value) + { + Node* node = this->_findBSTreeNode(value); + this->_deleteBSTreeNode(node); + } + + vector BinarySearchTree::recursiveInorderTraversal() + { + vector result; + this->_recursiveInorder(this->_root, result); + return result; + } + + vector BinarySearchTree::recursivePreorderTravesal() + { + vector result; + this->_recursivePreorder(this->_root, result); + return result; + } + + vector BinarySearchTree::recursivePostorderTravesal() + { + vector result; + this->_recursivePostorder(this->_root, result); + return result; + } + + vector BinarySearchTree::morrisInorderTraversal() + { + vector result; + this->_morrisInorder(this->_root, result); + return result; + } + + vector BinarySearchTree::morrisPreorderTraversal() + { + vector result; + this->_morrisPreorder(this->_root, result); + return result; + } + + vector BinarySearchTree::morrisPostorderTraversal() + { + vector result; + this->_morrisPostorder(this->_root, result); + return result; + } +} \ No newline at end of file diff --git a/src/0002_tree/CMakeLists.txt b/src/0002_tree/CMakeLists.txt new file mode 100644 index 0000000..3ef4afa --- /dev/null +++ b/src/0002_tree/CMakeLists.txt @@ -0,0 +1,11 @@ +# Specify the source files +set(0002TREE_SOURCES + 0001_BinarySearchTree.cc +) + +# Create a library target +add_library(0002_Tree ${0002TREE_SOURCES}) + +target_include_directories(0002_Tree PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}/headers +) \ No newline at end of file diff --git a/src/0002_tree/headers/0001_binary_search_tree.h b/src/0002_tree/headers/0001_binary_search_tree.h new file mode 100644 index 0000000..d422701 --- /dev/null +++ b/src/0002_tree/headers/0001_binary_search_tree.h @@ -0,0 +1,49 @@ +#pragma once + +#include +#include +using namespace std; + +namespace BinarySearchTree +{ + class Node + { + public: + int data; + Node* parent; + Node* left; + Node* right; + + Node(int data, Node* parent, Node* left, Node* right); + }; + + class BinarySearchTree + { + private: + Node* _root; + void _insertBSTreeNode(Node* node); + Node* _findBSTreeNode(int value); + Node* _findBSTreeMinNode(Node* node); + Node* _findBSTreeMaxNode(Node* node); + Node* _findSuccessor(Node* node); + Node* _findPredecessor(Node* node); + void _transplant(Node* nodeU, Node* nodeV); + void _deleteBSTreeNode(Node* node); + void _recursiveInorder(Node* node, vector& result); + void _recursivePreorder(Node* node, vector& result); + void _recursivePostorder(Node* node, vector& result); + void _morrisInorder(Node* node, vector& result); + void _morrisPreorder(Node* node, vector& result); + void _morrisPostorder(Node* node, vector& result); + public: + BinarySearchTree(); + void insertNode(int value); + void deleteNode(int value); + vector recursiveInorderTraversal(); + vector recursivePreorderTravesal(); + vector recursivePostorderTravesal(); + vector morrisInorderTraversal(); + vector morrisPreorderTraversal(); + vector morrisPostorderTraversal(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/0001_breadth_first_search.cc b/src/0003_graph/0001_breadth_first_search.cc new file mode 100644 index 0000000..9a8b1ac --- /dev/null +++ b/src/0003_graph/0001_breadth_first_search.cc @@ -0,0 +1,86 @@ +#include "0001_BreadthFirstSearch.h" +#include +#include +#include +#include +#include +#include +using namespace std; + +namespace BreadthFirstSearch +{ + Node::Node(int value) + { + this->data = value; + this->distance = INT_MAX; + this->color = WHITE; + this->parent = nullptr; + } + + Node* Graph::MakeOrFindNode(int value) + { + Node* node = nullptr; + if (this->_nodeMap.find(value) == this->_nodeMap.end()) + { + node = new Node(value); + this->_nodeMap[value] = node; + } + else + { + node = this->_nodeMap[value]; + } + return node; + } + + void Graph::BreadthFirstSearch(Node* node) + { + node->color = WHITE; + node->distance = 0; + node->parent = nullptr; + + queue nodeQueue; + nodeQueue.push(node); + + while (nodeQueue.empty() != true) + { + Node* currentNode = nodeQueue.front(); + nodeQueue.pop(); + + for (auto& adjacentNode : this->_adjlist[currentNode]) + { + if (adjacentNode->color == WHITE) + { + adjacentNode->color = GRAY; + adjacentNode->parent = currentNode; + adjacentNode->distance = currentNode->distance + 1; + nodeQueue.push(adjacentNode); + } + } + currentNode->color = BLACK; + } + } + + void Graph::PushUndirectedEdge(int valueU, int valueV) + { + Node* nodeU = this->MakeOrFindNode(valueU); + Node* nodeV = this->MakeOrFindNode(valueV); + + this->_adjlist[nodeU].push_back(nodeV); + this->_adjlist[nodeV].push_back(nodeU); + } + + void Graph::BFS(int value) + { + this->BreadthFirstSearch(this->_nodeMap[value]); + } + + vector> Graph::ShowBFSResult() + { + vector> result; + for (auto& node : this->_nodeMap) + { + result.push_back(make_pair(node.first, node.second->distance)); + } + return result; + } +} \ No newline at end of file diff --git a/src/0003_graph/0002_depth_first_search.cc b/src/0003_graph/0002_depth_first_search.cc new file mode 100644 index 0000000..3cbc49a --- /dev/null +++ b/src/0003_graph/0002_depth_first_search.cc @@ -0,0 +1,80 @@ +#include "0002_DepthFirstSearch.h" +#include +#include +#include +using namespace std; + +namespace DepthFirstSearch +{ + Node::Node(int value) + { + this->data = value; + this->discoveredTime = INT_MAX; + this->finishingTime = INT_MAX; + this->color = WHITE; + this->parent = nullptr; + } + + Node* Graph::MakeOrFindNode(int value) + { + Node* node = nullptr; + if (this->_nodeMap.find(value) == this->_nodeMap.end()) + { + node = new Node(value); + this->_nodeMap[value] = node; + } + else + { + node = this->_nodeMap[value]; + } + return node; + } + + void Graph::DepthFirstSearch(Node* nodeU) + { + this->_time++; + nodeU->discoveredTime = this->_time; + nodeU->color = GRAY; + for (auto nodeV : this->_adjlist[nodeU]) + { + if (nodeV->color == WHITE) + { + nodeV->parent = nodeU; + this->DepthFirstSearch(nodeV); + } + } + nodeU->color = BLACK; + this->_time++; + nodeU->finishingTime = this->_time; + } + + void Graph::PushDirectedEdge(int valueU, int valueV) + { + Node* nodeU = this->MakeOrFindNode(valueU); + Node* nodeV = this->MakeOrFindNode(valueV); + + this->_adjlist[nodeU].push_back(nodeV); + } + + void Graph::DFS() + { + this->_time = 0; + for (auto& iterator : this->_nodeMap) + { + if (iterator.second->color == WHITE) + { + this->DepthFirstSearch(iterator.second); + } + } + } + + vector>> Graph::ShowDFSResult() + { + vector>> result; + for (auto& node : this->_nodeMap) + { + result.push_back(make_pair(node.first, make_pair(node.second->discoveredTime, node.second->finishingTime))); + } + return result; + } +} \ No newline at end of file diff --git a/src/0003_graph/0003_topological_sort.cc b/src/0003_graph/0003_topological_sort.cc new file mode 100644 index 0000000..3d4d1cb --- /dev/null +++ b/src/0003_graph/0003_topological_sort.cc @@ -0,0 +1,150 @@ +#include "0003_TopologicalSort.h" +#include +#include +#include +#include +#include +using namespace std; + +namespace TopologicalSort +{ + Node::Node(int value) + { + this->data = value; + this->color = WHITE; + this->discoveryTime = INT_MAX; + this->finishingTime = INT_MAX; + this->inDegree = 0; + this->parent = nullptr; + } + + Node* Graph::MakeOrFindNode(int value) + { + Node* node = nullptr; + if (this->_nodeMap.find(value) == this->_nodeMap.end()) + { + node = new Node(value); + this->_nodeMap[value] = node; + } + else + { + node = this->_nodeMap[value]; + } + return node; + } + + void Graph::DepthFirstSearch(Node* nodeU) + { + this->_time++; + nodeU->discoveryTime = this->_time; + nodeU->color = GRAY; + for (auto& nodeV : this->_adjlist[nodeU]) + { + if (nodeV->color == WHITE) + { + nodeV->parent = nodeU; + this->DepthFirstSearch(nodeV); + } + else if (nodeV->color == GRAY) + { + this->_hasCycle = true; + return; + } + } + nodeU->color = BLACK; + this->_time++; + nodeU->finishingTime = this->_time; + this->_topologicalSortedNodeList.push_front(nodeU); + } + + void Graph::PushDirectedEdge(int valueU, int valueV) + { + Node* nodeU = this->MakeOrFindNode(valueU); + Node* nodeV = this->MakeOrFindNode(valueV); + + this->_adjlist[nodeU].push_back(nodeV); + nodeV->inDegree++; + } + + void Graph::PushSingleNode(int valueU) + { + this->MakeOrFindNode(valueU); + } + + void Graph::TopologicalSort() + { + this->_time = 0; + for (auto& iterator : this->_nodeMap) + { + if (iterator.second->color == WHITE) + { + this->DepthFirstSearch(iterator.second); + if (this->_hasCycle == true) + { + break; + } + } + } + } + + void Graph::KahnTopologicalSort() + { + // Step-1 Compute in-degree of each vertices + // This is already done while creating the graph + this->_time = 0; + queue nodeQueue; + + // Step-2 Enqueue vertices with in-degree 0 + for (auto& node : this->_nodeMap) + { + if (node.second->inDegree == 0) + { + this->_time++; + node.second->discoveryTime = this->_time; + nodeQueue.push(node.second); + } + } + + // Step-3 Process vertices in queue + while (!nodeQueue.empty()) + { + Node* node = nodeQueue.front(); + nodeQueue.pop(); + this->_time++; + node->finishingTime = this->_time; + this->_topologicalSortedNodeList.push_back(node); + + // Step-4 Process all the neighbours of current node based on in-degree + for (auto& neighbour : this->_adjlist[node]) + { + neighbour->inDegree--; + if (neighbour->inDegree == 0) + { + this->_time++; + neighbour->discoveryTime = this->_time; + nodeQueue.push(neighbour); + } + } + } + + // Step-5 Check if a cycle exists + if (this->_topologicalSortedNodeList.size() != this->_nodeMap.size()) + { + this->_hasCycle = true; + } + } + + vector>> Graph::ShowTopologicalSortResult() + { + if (this->_hasCycle == true) + { + return {}; + } + vector>> result; + for (auto& node : this->_topologicalSortedNodeList) + { + result.push_back(make_pair(node->data, make_pair(node->discoveryTime, node->finishingTime))); + } + return result; + } +} \ No newline at end of file diff --git a/src/0003_graph/0004_strongly_connected_components.cc b/src/0003_graph/0004_strongly_connected_components.cc new file mode 100644 index 0000000..7a99e34 --- /dev/null +++ b/src/0003_graph/0004_strongly_connected_components.cc @@ -0,0 +1,121 @@ +#include "0004_StronglyConnectedComponents.h" +#include +#include +#include +using namespace std; + +namespace StronglyConnectedComponents +{ + Node::Node(int value) + { + this->data = value; + this->discoveryTime = INT_MAX; + this->finishingTime = INT_MAX; + this->color = WHITE; + this->parent = nullptr; + } + + Node* Graph::MakeOrFindNode(int value) + { + Node* node = nullptr; + if (this->_nodeMap.find(value) == this->_nodeMap.end()) + { + node = new Node(value); + this->_nodeMap[value] = node; + } + else + { + node = this->_nodeMap[value]; + } + return node; + } + + void Graph::DepthFirstSearchOnGraphG(Node* nodeU) + { + this->_time++; + nodeU->discoveryTime = this->_time; + nodeU->color = GRAY; + for (auto nodeV : this->_adjlistG[nodeU]) + { + if (nodeV->color == WHITE) + { + nodeV->parent = nodeU; + this->DepthFirstSearchOnGraphG(nodeV); + } + } + nodeU->color = BLACK; + this->_time++; + nodeU->finishingTime = this->_time; + this->_nodesFinishingTimeOrder.push_front(nodeU); + } + + void Graph::DepthFirstSearchOnGraphT(Node* nodeU, vector& connectedComponents) + { + nodeU->color = GRAY; + connectedComponents.push_back(nodeU->data); + for (auto nodeV : this->_adjlistT[nodeU]) + { + if (nodeV->color == WHITE) + { + nodeV->parent = nodeU; + this->DepthFirstSearchOnGraphT(nodeV, connectedComponents); + } + } + nodeU->color = BLACK; + } + + void Graph::PushDirectedEdge(int valueU, int valueV) + { + Node* nodeU = this->MakeOrFindNode(valueU); + Node* nodeV = this->MakeOrFindNode(valueV); + + // Creating the actual graph. + this->_adjlistG[nodeU].push_back(nodeV); + + // Creating the transpose of the actual graph. + this->_adjlistT[nodeV].push_back(nodeU); + } + + void Graph::PushSingleNode(int valueU) + { + this->MakeOrFindNode(valueU); + } + + void Graph::DFSOnGraphG() + { + this->_time = 0; + for (auto& iterator : this->_nodeMap) + { + if (iterator.second->color == WHITE) + { + this->DepthFirstSearchOnGraphG(iterator.second); + } + } + } + + void Graph::DFSOnGraphT() + { + for (auto& iterator : this->_nodeMap) + { + iterator.second->color = WHITE; + iterator.second->parent = nullptr; + } + + for (auto& iterator : this->_nodesFinishingTimeOrder) + { + if (iterator->color == WHITE) + { + vector connectedComponents; + this->DepthFirstSearchOnGraphT(iterator, connectedComponents); + this->_allConnectedComponents.push_back(connectedComponents); + } + } + } + + vector> Graph::FindAllStronglyConnectedComponents() + { + this->DFSOnGraphG(); + this->DFSOnGraphT(); + return this->_allConnectedComponents; + } +} \ No newline at end of file diff --git a/src/0003_graph/0005_hamiltonian_path_and_cycle.cc b/src/0003_graph/0005_hamiltonian_path_and_cycle.cc new file mode 100644 index 0000000..bfa99b5 --- /dev/null +++ b/src/0003_graph/0005_hamiltonian_path_and_cycle.cc @@ -0,0 +1,114 @@ +#include "0005_HamiltonianPathAndCycle.h" + +using namespace std; +namespace HamiltonianPathAndCycle +{ + Node::Node(int value) + { + this->data = value; + this->isVisited = false; + } + + // Graph Private Member Methods + Node* Graph::MakeOrFindNode(int value) + { + Node* node = nullptr; + if (this->_nodeMap.find(value) == this->_nodeMap.end()) + { + node = new Node(value); + this->_nodeMap[value] = node; + } + else + { + node = this->_nodeMap[value]; + } + return node; + } + + bool Graph::IsSafe(Node* nodeU, Node* nodeV) + { + if (this->_adjlist[nodeU].find(nodeV) == this->_adjlist[nodeU].end()) + { + return false; + } + if (nodeV->isVisited == true) + { + return false; + } + return true; + } + + bool Graph::HamiltonianCycleAndPathUtil(Node* nodeU) + { + if (this->_visitedNodeCount == this->_nodeMap.size()) + { + if (this->_adjlist[nodeU].find(this->_startingNode) != this->_adjlist[nodeU].end()) + { + this->_isHamiltonianCyclePresent = true; + this->_isHamiltonianPathPresent = true; + return true; + } + this->_isHamiltonianPathPresent = true; + return false; + } + for (auto& nodeV : this->_adjlist[nodeU]) + { + if (this->IsSafe(nodeU, nodeV)) + { + this->_hamiltonianPath.push_back(nodeV->data); + nodeV->isVisited = true; + this->_visitedNodeCount++; + if (this->HamiltonianCycleAndPathUtil(nodeV)) + { + return true; + } + this->_visitedNodeCount--; + nodeV->isVisited = false; + this->_hamiltonianPath.pop_back(); + } + } + return false; + } + + // Graph Public Member Methods + void Graph::PushUndirectedEdge(int valueU, int valueV) + { + Node* nodeU = this->MakeOrFindNode(valueU); + Node* nodeV = this->MakeOrFindNode(valueV); + + this->_adjlist[nodeU].insert(nodeV); + this->_adjlist[nodeV].insert(nodeU); + } + + void Graph::PushSingleNode(int valueU) + { + this->MakeOrFindNode(valueU); + } + + void Graph::FindHamiltonianCycleAndPath() + { + this->_isHamiltonianCyclePresent = false; + this->_isHamiltonianPathPresent = false; + this->_hamiltonianPath = {}; + this->_startingNode = this->_nodeMap[0]; + this->_hamiltonianPath.push_back(this->_startingNode->data); + this->_startingNode->isVisited = true; + this->_visitedNodeCount = 1; + this->HamiltonianCycleAndPathUtil(this->_startingNode); + } + + bool Graph::IsHamiltonianCyclePresent() + { + return this->_isHamiltonianCyclePresent; + } + + bool Graph::IsHamiltonianPathPresent() + { + return this->_isHamiltonianPathPresent; + } + + vector Graph::GetHamiltonianPath() + { + return this->_hamiltonianPath; + } +} \ No newline at end of file diff --git a/src/0003_graph/0006_eulerian_path_and_circuit.cc b/src/0003_graph/0006_eulerian_path_and_circuit.cc new file mode 100644 index 0000000..ee132ca --- /dev/null +++ b/src/0003_graph/0006_eulerian_path_and_circuit.cc @@ -0,0 +1,212 @@ +#include "0006_EulerianPathAndCircuit.h" +#include +#include +using namespace std; + +namespace EulerianPathAndCircuit +{ + Node::Node(int value) + { + this->data = value; + this->degree = 0; + this->inDegree = 0; + this->outDegree = 0; + this->visited = false; + } + + // Graph Private Member Methods + Node* Graph::MakeOrFindNode(int value) + { + Node* node = nullptr; + if (this->_nodeMap.find(value) == this->_nodeMap.end()) + { + node = new Node(value); + this->_nodeMap[value] = node; + } + else + { + node = this->_nodeMap[value]; + } + return node; + } + + void Graph::DepthFirstSearch(Node* nodeU) + { + nodeU->visited = true; + for (auto& nodeV : this->_adjlist[nodeU]) + { + if (nodeV->visited == false) + { + this->DepthFirstSearch(nodeV); + } + } + } + + bool Graph::IsConnected() + { + // Step-1 : Make the visited property of all nodes as false. It is already done in constructor. + + // Step-2 : Find a node which do not have 0 degree. + Node* node = nullptr; + for (auto& iterator : this->_nodeMap) + { + if (iterator.second->degree != 0) + { + node = iterator.second; + break; + } + } + + // Step-3 : If node is null, it means G.E is null, so G is connected, else call DFS to traverse the graph G. + if (node == nullptr) + { + return true; + } + + this->DepthFirstSearch(node); + + // Step-4 : Checking if all the non-zero degree vertices have been visited or not. + for (auto& iterator : this->_nodeMap) + { + if (iterator.second->visited == false && iterator.second->degree != 0) + { + return false; + } + } + return true; + } + + void Graph::EulerianPathHierholzerAlgorithm(Node* startingNode) + { + stack currentPath; + currentPath.push(startingNode); + while (!currentPath.empty()) + { + Node* currentNode = currentPath.top(); + if (!this->_adjlist[currentNode].empty()) + { + Node* nextNode = this->_adjlist[currentNode].front(); + this->_adjlist[currentNode].pop_front(); + this->_adjlist[nextNode].remove(currentNode); + currentPath.push(nextNode); + } + else + { + currentPath.pop(); + this->_eulerianPath.push_back(currentNode->data); + } + } + } + + // Graph Public Member Methods + void Graph::PushUndirectedEdge(int valueU, int valueV) + { + Node* nodeU = this->MakeOrFindNode(valueU); + Node* nodeV = this->MakeOrFindNode(valueV); + + this->_adjlist[nodeU].push_back(nodeV); + nodeU->degree++; + this->_adjlist[nodeV].push_back(nodeU); + nodeV->degree++; + } + + void Graph::PushDirectedEdge(int valueU, int valueV) + { + Node* nodeU = this->MakeOrFindNode(valueU); + Node* nodeV = this->MakeOrFindNode(valueV); + + this->_adjlist[nodeU].push_back(nodeV); + nodeU->outDegree++; + nodeV->inDegree++; + } + + void Graph::PushSingleNode(int valueU) + { + this->MakeOrFindNode(valueU); + } + + void Graph::FindEulerianPathAndCircuit() + { + // If the graph is not connected then graph G is Not-Eulerian. + if (this->IsConnected() == false) + { + this->_isEulerianPathPresent = false; + this->_isEulerianCircuitPresent = false; + return; + } + + int oddDegreeVertexCount = 0; + for (auto& iterator : this->_nodeMap) + { + if (iterator.second->degree & 1) + { + oddDegreeVertexCount++; + } + } + + // Check-1 : When no vertex with odd degree is present, then graph G is Eulerian. + if (oddDegreeVertexCount == 0) + { + this->_isEulerianPathPresent = true; + this->_isEulerianCircuitPresent = true; + return; + } + + // Check-2 : When 2 vertices have odd degree, then graph G is Semi-Eulerian. + if (oddDegreeVertexCount == 2) + { + this->_isEulerianPathPresent = true; + this->_isEulerianCircuitPresent = false; + return; + } + + // Check-3 : When more than 2 vertices have odd degree, then graph G is Not Eulerian. + if (oddDegreeVertexCount > 2) + { + this->_isEulerianPathPresent = false; + this->_isEulerianCircuitPresent = false; + return; + } + } + + bool Graph::IsEulerianPathPresent() + { + return this->_isEulerianPathPresent; + } + + bool Graph::IsEulerianCircuitPresent() + { + return this->_isEulerianCircuitPresent; + } + + vector Graph::UndirectedGraphGetEulerianPath() + { + // Case-3 : When more than 2 vertices have odd degree, then the graph G is not Eulerian. + // No Eulerian Path is posible. + if (this->_isEulerianPathPresent == false) + { + return {}; + } + + // Now 2 cases remains. + // Case-2 : When 2 vertices have odd degree. Choose any one of them. + Node* node = nullptr; + for (auto& iterator : this->_nodeMap) + { + if (iterator.second->degree & 1) + { + node = iterator.second; + break; + } + } + + // Case-1 : When no vertex with odd degree is present. Choose any vertex as starting point. + if (node == nullptr) + { + node = this->_nodeMap[0]; + } + this->EulerianPathHierholzerAlgorithm(node); + reverse(this->_eulerianPath.begin(), this->_eulerianPath.end()); + return this->_eulerianPath; + } +} \ No newline at end of file diff --git a/src/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm.cc b/src/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm.cc new file mode 100644 index 0000000..20bea2b --- /dev/null +++ b/src/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm.cc @@ -0,0 +1,108 @@ +#include "0007_MinimumSpanningTreeKruskalAlgorithm.h" +#include +#include +using namespace std; + +namespace MinimumSpanningTreeKruskalAlgorithm +{ + Node::Node(int data) + { + this->data = data; + this->parent = nullptr; + this->rank = INT_MAX; + } + + Edge::Edge(Node* nodeU, Node* nodeV, int weight) + { + this->nodeU = nodeU; + this->nodeV = nodeV; + this->weight = weight; + } + + // Graph Private Member Methods + Node* Graph::MakeOrFindNode(int data) + { + Node* node = nullptr; + if (this->_nodeMap.find(data) == this->_nodeMap.end()) + { + node = new Node(data); + this->_nodeMap[data] = node; + } + else + { + node = this->_nodeMap[data]; + } + return node; + } + + void Graph::MakeSet(Node* node) + { + node->parent = node; + node->rank = 0; + } + + void Graph::Union(Node* nodeU, Node* nodeV) + { + this->Link(this->FindSet(nodeU), this->FindSet(nodeV)); + } + + void Graph::Link(Node* nodeU, Node* nodeV) + { + if (nodeV->rank > nodeU->rank) + { + nodeU->parent = nodeV; + } + else + { + nodeV->parent = nodeU; + if (nodeU->rank == nodeV->rank) + { + nodeU->rank += 1; + } + } + } + + Node* Graph::FindSet(Node* node) + { + if (node != node->parent) + { + node->parent = this->FindSet(node->parent); + } + return node->parent; + } + + // Graph Public Member Methods + void Graph::PushUndirectedEdge(int dataU, int dataV, int weight) + { + Node* nodeU = this->MakeOrFindNode(dataU); + Node* nodeV = this->MakeOrFindNode(dataV); + + this->_adjlist[nodeU].push_back(nodeV); + this->_adjlist[nodeV].push_back(nodeU); + this->_edgeList.push_back(new Edge(nodeU, nodeV, weight)); + } + + void Graph::FindMinimumSpanningTreeKruskalAlgorithm() + { + for (auto& iterator : this->_nodeMap) + { + this->MakeSet(iterator.second); + } + + sort(this->_edgeList.begin(), this->_edgeList.end(), [](Edge* edgeX, Edge* edgeY) { return edgeX->weight < edgeY->weight; }); + + for (auto& edge : this->_edgeList) + { + if (this->FindSet(edge->nodeU) != this->FindSet(edge->nodeV)) + { + this->Union(edge->nodeU, edge->nodeV); + this->_minimumSpanningTree.push_back({ {edge->nodeU->data, edge->nodeV->data}, edge->weight }); + } + } + } + + vector, int>> Graph::GetMinimumSpanningTree() + { + return this->_minimumSpanningTree; + } +} \ No newline at end of file diff --git a/src/0003_graph/0008_minimum_spanning_tree_prim_algorithm.cc b/src/0003_graph/0008_minimum_spanning_tree_prim_algorithm.cc new file mode 100644 index 0000000..1b36027 --- /dev/null +++ b/src/0003_graph/0008_minimum_spanning_tree_prim_algorithm.cc @@ -0,0 +1,85 @@ +#include "0008_MinimumSpanningTreePrimAlgorithm.h" +#include +using namespace std; + + +namespace MinimumSpanningTreePrimAlgorithm +{ + Node::Node(int data) + { + this->data = data; + this->parent = nullptr; + this->key = INT_MAX; + this->isInOperationalSet = false; + } + + // Graph Private Member Methods + Node* Graph::MakeOrFindNode(int data) + { + Node* node = nullptr; + if (this->_nodeMap.find(data) == this->_nodeMap.end()) + { + node = new Node(data); + this->_nodeMap[data] = node; + } + else + { + node = this->_nodeMap[data]; + } + return node; + } + + // Graph Public Member Methods + void Graph::PushUndirectedEdge(int dataU, int dataV, int weight) + { + Node* nodeU = this->MakeOrFindNode(dataU); + Node* nodeV = this->MakeOrFindNode(dataV); + + this->_adjlist[nodeU].push_back({nodeV, weight}); + this->_adjlist[nodeV].push_back({nodeU, weight}); + } + + void Graph::FindMinimumSpanningTreePrimAlgorithm() + { + Node* root = this->_nodeMap.begin()->second; + + root->key = 0; + for (auto& iterator : this->_nodeMap) + { + iterator.second->isInOperationalSet = true; + this->_operationalSet.insert(iterator.second); + } + + while (!this->_operationalSet.empty()) + { + Node* nodeU = *(this->_operationalSet.begin()); + this->_operationalSet.erase(nodeU); + nodeU->isInOperationalSet = false; + + for (auto& iterator : this->_adjlist[nodeU]) + { + Node* nodeV = iterator.first; + int weight = iterator.second; + + if (nodeV->isInOperationalSet && weight < nodeV->key) + { + this->_operationalSet.erase(nodeV); + nodeV->key = weight; + nodeV->parent = nodeU; + this->_operationalSet.insert(nodeV); + + } + } + + if (nodeU->parent != nullptr) + { + this->_minimumSpanningTree.push_back({ {nodeU->parent->data, nodeU->data}, nodeU->key }); + } + } + } + + vector, int>> Graph::GetMinimumSpanningTree() + { + return this->_minimumSpanningTree; + } +} \ No newline at end of file diff --git a/src/0003_graph/0009_single_source_shortest_path_bellman_ford.cc b/src/0003_graph/0009_single_source_shortest_path_bellman_ford.cc new file mode 100644 index 0000000..b059b74 --- /dev/null +++ b/src/0003_graph/0009_single_source_shortest_path_bellman_ford.cc @@ -0,0 +1,108 @@ +#include "0009_SingleSourceShortestPathBellmanFord.h" +#include +#include +using namespace std; + +namespace SingleSourceShortestPathBellmanFord +{ + Node::Node(int data) + { + this->data = data; + this->distance = INT_MAX; + this->parent = nullptr; + } + + Edge::Edge(Node* nodeU, Node* nodeV, int weight) + { + this->nodeU = nodeU; + this->nodeV = nodeV; + this->weight = weight; + } + + // Graph Private Member Methods + Node* Graph::MakeOrFindNode(int data) + { + Node* node = nullptr; + if (this->_nodeMap.find(data) == this->_nodeMap.end()) + { + node = new Node(data); + this->_nodeMap[data] = node; + } + else + { + node = this->_nodeMap[data]; + } + return node; + } + + void Graph :: InitializeSingleSource(Node* sourceNode) + { + for (auto& iterator : this->_nodeMap) + { + iterator.second->distance = INT_MAX; + iterator.second->parent = nullptr; + } + sourceNode->distance = 0; + } + + void Graph::Relax(Edge* edge) + { + if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) + { + edge->nodeV->distance = edge->nodeU->distance + edge->weight; + edge->nodeV->parent = edge->nodeU; + } + } + + void Graph::GetShortestPath(Node* node, vector& path) + { + path.push_back(node->data); + if (node->parent != nullptr) + { + this->GetShortestPath(node->parent, path); + } + } + + // Graph Public Member Methods + void Graph::PushDirectedEdge(int dataU, int dataV, int weight) + { + Node* nodeU = this->MakeOrFindNode(dataU); + Node* nodeV = this->MakeOrFindNode(dataV); + + this->_adjlist[nodeU].push_back(nodeV); + this->_edgeList.push_back(new Edge(nodeU, nodeV, weight)); + } + + bool Graph::FindSingleSourceShortestPathBellmanFord(int data) + { + Node* source = this->_nodeMap[data]; + + this->InitializeSingleSource(source); + + for (int i = 0; i < this->_nodeMap.size() - 1; i++) + { + for (auto& edge : this->_edgeList) + { + this->Relax(edge); + } + } + + for (auto& edge : this->_edgeList) + { + if (edge->nodeV->distance > (edge->nodeU->distance + edge->weight)) + { + return false; + } + } + return true; + } + + vector Graph::GetShortestPathBellmanFord(int data) + { + vector path = {}; + Node* node = this->_nodeMap[data]; + this->GetShortestPath(node, path); + reverse(path.begin(), path.end()); + return path; + } +} \ No newline at end of file diff --git a/src/0003_graph/0010_directed_acyclic_graph_shortest_path.cc b/src/0003_graph/0010_directed_acyclic_graph_shortest_path.cc new file mode 100644 index 0000000..8f4cd81 --- /dev/null +++ b/src/0003_graph/0010_directed_acyclic_graph_shortest_path.cc @@ -0,0 +1,124 @@ +#include "0010_DirectedAcyclicGraphShortestPath.h" +#include +#include +using namespace std; + +namespace DirectedAcyclicGraphShortestPath +{ + Node::Node(int data) + { + this->data = data; + this->color = WHITE; + this->distance = INT_MAX; + this->parent = nullptr; + } + + Edge::Edge(Node* nodeU, Node* nodeV, int weight) + { + this->nodeU = nodeU; + this->nodeV = nodeV; + this->weight = weight; + } + + // Graph Private Member Methods + Node* Graph::MakeOrFindNode(int data) + { + Node* node = nullptr; + if (this->_nodeMap.find(data) == this->_nodeMap.end()) + { + node = new Node(data); + this->_nodeMap[data] = node; + } + else + { + node = this->_nodeMap[data]; + } + return node; + } + + void Graph::DepthFirstSearch(Node* nodeU) + { + nodeU->color = GRAY; + for (auto& nodeV : this->_adjlist[nodeU]) + { + if (nodeV->color == WHITE) + { + this->DepthFirstSearch(nodeV); + } + } + nodeU->color = BLACK; + this->_topologicalSortedNodeList.push_front(nodeU); + } + + void Graph::TopologicalSort() + { + for (auto& iterator : this->_nodeMap) + { + if (iterator.second->color == WHITE) + { + this->DepthFirstSearch(iterator.second); + } + } + } + + void Graph::InitializeSingleSource(Node* sourceNode) + { + for (auto& iterator : this->_nodeMap) + { + iterator.second->distance = INT_MAX; + iterator.second->parent = nullptr; + } + sourceNode->distance = 0; + } + + void Graph::Relax(Edge* edge) + { + if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) + { + edge->nodeV->distance = edge->nodeU->distance + edge->weight; + edge->nodeV->parent = edge->nodeU; + } + } + + void Graph::GetShortestPath(Node* node, vector& path) + { + path.push_back(node->data); + if (node->parent != nullptr) + { + this->GetShortestPath(node->parent, path); + } + } + + // Graph Public Member Methods + void Graph::PushDirectedEdge(int dataU, int dataV, int weight) + { + Node* nodeU = this->MakeOrFindNode(dataU); + Node* nodeV = this->MakeOrFindNode(dataV); + + this->_adjlist[nodeU].push_back(nodeV); + this->_edgeMap[nodeU].push_back(new Edge(nodeU, nodeV, weight)); + } + + void Graph::FindDAGShortestPath(int data) + { + this->TopologicalSort(); + Node* source = this->_nodeMap[data]; + this->InitializeSingleSource(source); + for (auto& node : this->_topologicalSortedNodeList) + { + for (auto& edge : this->_edgeMap[node]) + { + this->Relax(edge); + } + } + } + + vector Graph::GetDAGShortestPath(int data) + { + vector path = {}; + Node* node = this->_nodeMap[data]; + this->GetShortestPath(node, path); + reverse(path.begin(), path.end()); + return path; + } +} \ No newline at end of file diff --git a/src/0003_graph/0011_single_source_shortest_path_dijkstra.cc b/src/0003_graph/0011_single_source_shortest_path_dijkstra.cc new file mode 100644 index 0000000..e796e37 --- /dev/null +++ b/src/0003_graph/0011_single_source_shortest_path_dijkstra.cc @@ -0,0 +1,113 @@ +#include "0011_SingleSourceShortestPathDijkstra.h" +#include +#include +using namespace std; + +namespace SingleSourceShortestPathDijkstra +{ + Node::Node(int data) + { + this->data = data; + this->distance = INT_MAX; + this->parent = nullptr; + } + + Edge::Edge(Node* nodeU, Node* nodeV, int weight) + { + this->nodeU = nodeU; + this->nodeV = nodeV; + this->weight = weight; + } + + // Graph Private Member Methods + Node* Graph::MakeOrFindNode(int data) + { + Node* node = nullptr; + if (this->_nodeMap.find(data) == this->_nodeMap.end()) + { + node = new Node(data); + this->_nodeMap[data] = node; + } + else + { + node = this->_nodeMap[data]; + } + return node; + } + + void Graph::InitializeSingleSource(Node* sourceNode) + { + for (auto& iterator : this->_nodeMap) + { + iterator.second->distance = INT_MAX; + iterator.second->parent = nullptr; + } + sourceNode->distance = 0; + } + + void Graph::Relax(Edge* edge) + { + if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) + { + this->_operationalSet.erase(edge->nodeV); + edge->nodeV->distance = edge->nodeU->distance + edge->weight; + edge->nodeV->parent = edge->nodeU; + this->_operationalSet.insert(edge->nodeV); + } + } + + void Graph::Dijkstra(Node* source) + { + this->InitializeSingleSource(source); + + for (auto& node : this->_nodeMap) + { + this->_operationalSet.insert(node.second); + } + + while (!this->_operationalSet.empty()) + { + Node* nodeU = *(this->_operationalSet.begin()); + this->_operationalSet.erase(nodeU); + + for (auto& edge : this->_edgeMap[nodeU]) + { + this->Relax(edge); + } + } + } + + void Graph::GetShortestPath(Node* node, vector& path) + { + path.push_back(node->data); + if (node->parent != nullptr) + { + this->GetShortestPath(node->parent, path); + } + } + + // Graph Public Member Methods + void Graph::PushDirectedEdge(int dataU, int dataV, int weight) + { + Node* nodeU = this->MakeOrFindNode(dataU); + Node* nodeV = this->MakeOrFindNode(dataV); + + this->_adjlist[nodeU].push_back(nodeV); + this->_edgeMap[nodeU].push_back(new Edge(nodeU, nodeV, weight)); + } + + void Graph::FindShortestPathDijkstra(int data) + { + Node* source = this->_nodeMap[data]; + this->Dijkstra(source); + } + + vector Graph::GetDijkstraShortestPath(int data) + { + vector path = {}; + Node* node = this->_nodeMap[data]; + this->GetShortestPath(node, path); + reverse(path.begin(), path.end()); + return path; + } +} \ No newline at end of file diff --git a/src/0003_graph/0012_difference_constraints_shortest_paths.cc b/src/0003_graph/0012_difference_constraints_shortest_paths.cc new file mode 100644 index 0000000..8764ba6 --- /dev/null +++ b/src/0003_graph/0012_difference_constraints_shortest_paths.cc @@ -0,0 +1,133 @@ +#include "0012_DifferenceConstraintsShortestPaths.h" +#include +using namespace std; + +namespace DifferenceConstraintsShortestPaths +{ + Node::Node(string data) + { + this->data = data; + this->distance = INT_MAX; + } + + Edge::Edge(Node* nodeU, Node* nodeV, int weight) + { + this->nodeU = nodeU; + this->nodeV = nodeV; + this->weight = weight; + } + + // Graph Private Member Methods + Node* Graph::MakeOrFindNode(string data) + { + Node* node = nullptr; + if (this->_nodeMap.find(data) == this->_nodeMap.end()) + { + node = new Node(data); + this->_nodeMap[data] = node; + } + else + { + node = this->_nodeMap[data]; + } + return node; + } + + void Graph::PushDirectedEdge(string dataU, string dataV, int weight) + { + Node* nodeU = this->MakeOrFindNode(dataU); + Node* nodeV = this->MakeOrFindNode(dataV); + + this->_adjlist[nodeU].push_back(nodeV); + this->_edgeList.push_back(new Edge(nodeU, nodeV, weight)); + } + + void Graph::InitializeSingleSource(Node* sourceNode) + { + for (auto& iterator : this->_nodeMap) + { + iterator.second->distance = INT_MAX; + } + sourceNode->distance = 0; + } + + void Graph::Relax(Edge* edge) + { + if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) + { + edge->nodeV->distance = edge->nodeU->distance + edge->weight; + } + } + + // Graph Public Member Methods + void Graph::PushAllDirectedEdges(vector> vectorA, vector vectorX, vector vectorB) + { + // Creating the Actual Graph + string valueU = ""; + string valueV = ""; + int weight = 0; + for (int i = 0; i < vectorA.size(); i++) + { + for (int j = 0; j < vectorX.size(); j++) + { + if (vectorA[i][j] == 1) + { + valueV= vectorX[j]; + } + if (vectorA[i][j] == -1) + { + valueU = vectorX[j]; + } + } + weight = vectorB[i]; + this->PushDirectedEdge(valueU, valueV, weight); + } + + // Creating all the edges from the additional vertex + valueU = ""; + valueV = ""; + weight = 0; + for (int i = 0; i < vectorX.size(); i++) + { + valueV = vectorX[i]; + this->PushDirectedEdge(valueU, valueV, weight); + } + } + + bool Graph::FindDifferenceConstraintsSolutionBellmanFord() + { + Node* source = this->_nodeMap[""]; + + this->InitializeSingleSource(source); + + for (int i = 0; i < this->_nodeMap.size(); i++) + { + for (auto& edge : this->_edgeList) + { + this->Relax(edge); + } + } + + for (auto& edge : this->_edgeList) + { + if (edge->nodeV->distance > (edge->nodeU->distance + edge->weight)) + { + return false; + } + } + return true; + } + + vector> Graph::GetDifferenceConstrtaintsSolution() + { + vector> result; + for (auto& node : this->_nodeMap) + { + if (node.second->data != "") + { + result.push_back({ node.second->data, node.second->distance }); + } + } + return result; + } +} \ No newline at end of file diff --git a/src/0003_graph/0013_all_pairs_shortest_paths_floyd_warshall.cc b/src/0003_graph/0013_all_pairs_shortest_paths_floyd_warshall.cc new file mode 100644 index 0000000..ffd51d9 --- /dev/null +++ b/src/0003_graph/0013_all_pairs_shortest_paths_floyd_warshall.cc @@ -0,0 +1,104 @@ +#include "0013_AllPairsShortestPathsFloydWarshall.h" +#include +using namespace std; + +namespace AllPairsShortestPathsFloydWarshall +{ + // Graph Private Member Methods + void Graph::InitializeDistanceAndPredecessors() + { + this->_shortestPathMatrixFloydWarshall = this->_adjMatrix; + + for (int i = 0; i < this->_noOfVertices; i++) + { + for (int j = 0; j < this->_noOfVertices; j++) + { + if ((i == j) || this->_adjMatrix[i][j] == INT_MAX) + { + this->_predecessorMatrix[i][j] = -1; + } + else + { + this->_predecessorMatrix[i][j] = i + 1; + } + } + } + } + + void Graph::GetShortestPath(int source, int destination, vector& path) + { + if (this->_predecessorMatrix[source - 1][destination - 1] != source) + { + int predecessor = this->_predecessorMatrix[source - 1][destination - 1]; + this->GetShortestPath(source, predecessor, path); + path.push_back(predecessor); + } + } + + // Graph Public Member Methods + void Graph::CreateGraph(int noOfVertices) + { + this->_noOfVertices = noOfVertices; + this->_adjMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, INT_MAX)); + this->_shortestPathMatrixFloydWarshall = vector>(this->_noOfVertices, vector(this->_noOfVertices, INT_MAX)); + this->_predecessorMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, INT_MAX)); + + for (int i = 0; i < this->_noOfVertices; i++) + { + for (int j = 0; j < this->_noOfVertices; j++) + { + if (i == j) + { + this->_adjMatrix[i][j] = 0; + } + } + } + } + + void Graph::PushDirectedEdge(int valueU, int valueV, int weight) + { + this->_adjMatrix[valueU - 1][valueV - 1] = weight; + } + + void Graph::FindAllPairsShortestPathsFloydWarshallSolution() + { + this->InitializeDistanceAndPredecessors(); + + for (int k = 0; k < this->_noOfVertices; k++) + { + for (int i = 0; i < this->_noOfVertices; i++) + { + for (int j = 0; j < this->_noOfVertices; j++) + { + if ((this->_shortestPathMatrixFloydWarshall[i][j] > (this->_shortestPathMatrixFloydWarshall[i][k] + this->_shortestPathMatrixFloydWarshall[k][j])) + && + (this->_shortestPathMatrixFloydWarshall[i][k] != INT_MAX && this->_shortestPathMatrixFloydWarshall[k][j] != INT_MAX)) + { + this->_shortestPathMatrixFloydWarshall[i][j] = this->_shortestPathMatrixFloydWarshall[i][k] + this->_shortestPathMatrixFloydWarshall[k][j]; + this->_predecessorMatrix[i][j] = this->_predecessorMatrix[k][j]; + } + } + } + } + } + + vector> Graph::GetFloydWarshallShortestPath() + { + vector> result; + for (int i = 0; i < this->_noOfVertices; i++) + { + for (int j = 0; j < this->_noOfVertices; j++) + { + if (i != j) + { + vector path = {}; + path.push_back(i + 1); + this->GetShortestPath(i + 1, j + 1, path); + path.push_back(j + 1); + result.push_back(path); + } + } + } + return result; + } +} \ No newline at end of file diff --git a/src/0003_graph/0014_all_pairs_shortest_paths_johnson.cc b/src/0003_graph/0014_all_pairs_shortest_paths_johnson.cc new file mode 100644 index 0000000..e9f9ab2 --- /dev/null +++ b/src/0003_graph/0014_all_pairs_shortest_paths_johnson.cc @@ -0,0 +1,217 @@ +#include "0014_AllPairsShortestPathsJohnson.h" +#include +using namespace std; + +namespace AllPairsShortestPathsJohnson +{ + Node::Node(int data) + { + this->data = data; + this->distance = INT_MAX; + this->parent = nullptr; + this->potentialWeight = 0; + } + + Edge::Edge(Node* nodeU, Node* nodeV, int weight) + { + this->nodeU = nodeU; + this->nodeV = nodeV; + this->weight = weight; + } + + // Graph Private Member Methods + Node* Graph::MakeOrFindNode(int data) + { + Node* node = nullptr; + if (this->_nodeMap.find(data) == this->_nodeMap.end()) + { + node = new Node(data); + this->_nodeMap[data] = node; + } + else + { + node = this->_nodeMap[data]; + } + return node; + } + + void Graph::PushAugmentedDirectedEdges(Node* sourceNode, Node* nodeV, int weight) + { + this->_augmentedAdjlist[sourceNode].push_back(nodeV); + this->_augmentedEdgeList.push_back(new Edge(sourceNode, nodeV, weight)); + } + + void Graph::InitializeSingleSource(Node* sourceNode) + { + for (auto& iterator : this->_nodeMap) + { + iterator.second->distance = INT_MAX; + iterator.second->parent = nullptr; + } + sourceNode->distance = 0; + } + + void Graph::RelaxBellmanFord(Edge* edge) + { + if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) + { + edge->nodeV->distance = edge->nodeU->distance + edge->weight; + edge->nodeV->parent = edge->nodeU; + } + } + + bool Graph::BellmanFord(Node* source) + { + this->InitializeSingleSource(source); + + for (int i = 0; i < this->_nodeMap.size() - 1; i++) + { + for (auto& edge : this->_augmentedEdgeList) + { + this->RelaxBellmanFord(edge); + } + } + + for (auto& edge : this->_augmentedEdgeList) + { + if (edge->nodeV->distance > (edge->nodeU->distance + edge->weight)) + { + return false; + } + } + return true; + } + + void Graph::RelaxDijkstra(Edge* edge) + { + if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) + { + this->_operationalSet.erase(edge->nodeV); + edge->nodeV->distance = edge->nodeU->distance + edge->weight; + edge->nodeV->parent = edge->nodeU; + this->_operationalSet.insert(edge->nodeV); + } + } + + void Graph::Dijkstra(Node* source) + { + this->InitializeSingleSource(source); + + for (auto& node : this->_nodeMap) + { + this->_operationalSet.insert(node.second); + } + + while (!this->_operationalSet.empty()) + { + Node* nodeU = *(this->_operationalSet.begin()); + this->_operationalSet.erase(nodeU); + + for (auto& edge : this->_edgeMap[nodeU]) + { + this->RelaxDijkstra(edge); + } + } + } + + void Graph::GetShortestPath(int source, int destination, vector& path) + { + if (this->_predecessorMatrix[source - 1][destination - 1] != source) + { + int predecessor = this->_predecessorMatrix[source - 1][destination - 1]; + this->GetShortestPath(source, predecessor, path); + path.push_back(predecessor); + } + } + + // Graph Public Member Methods + void Graph::PushDirectedEdge(int dataU, int dataV, int weight) + { + Node* nodeU = this->MakeOrFindNode(dataU); + Node* nodeV = this->MakeOrFindNode(dataV); + + this->_adjlist[nodeU].push_back(nodeV); + Edge* edge = new Edge(nodeU, nodeV, weight); + this->_edgeMap[nodeU].push_back(edge); + this->_edgeList.push_back(edge); + } + + bool Graph::FindAllPairsShortestPathsJohnsonAlgorithm() + { + // Creating the graph G' + this->_augmentedAdjlist = this->_adjlist; + this->_augmentedEdgeList = this->_edgeList; + + // Source Node s + Node* source = new Node(0); + this->_nodeMap[0] = source; + + // Creating all the augmented edges in G'.E = G.E U {(s, v) : v in G.V + for (auto& node : this->_nodeMap) + { + if (node.second != source) + { + this->PushAugmentedDirectedEdges(source, node.second, 0); + } + } + + if (this->BellmanFord(source) == false) + { + return false; + } + else + { + this->_nodeMap.erase(0); + for (auto& node : this->_nodeMap) + { + node.second->potentialWeight = node.second->distance; + } + + for (auto& edge : this->_edgeList) + { + edge->weight = edge->weight + edge->nodeU->potentialWeight - edge->nodeV->potentialWeight; + } + + this->_noOfVertices = (int)this->_nodeMap.size(); + this->_shortestPathMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, -1)); + this->_predecessorMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, -1)); + for (auto& iteratorU : this->_nodeMap) + { + Node* nodeU = iteratorU.second; + this->Dijkstra(nodeU); + for (auto& iteratorV : this->_nodeMap) + { + Node* nodeV = iteratorV.second; + this->_shortestPathMatrix[nodeU->data - 1][nodeV->data - 1] = nodeV->distance + nodeV->potentialWeight - nodeU->potentialWeight; + this->_predecessorMatrix[nodeU->data - 1][nodeV->data - 1] = nodeV->parent != nullptr ? nodeV->parent->data : -1; + } + } + return true; + } + } + + vector> Graph::GetAllPairsShortestPathsDistanceMatrix() + { + return this->_shortestPathMatrix; + } + + vector> Graph::GetAllPairsShortestPathsPathMatrix() + { + vector> result; + for (int i = 0; i < this->_noOfVertices; i++) + { + for (int j = 0; j < this->_noOfVertices; j++) + { + if (i != j) + { + vector path = {}; + path.push_back(i + 1); + this->GetShortestPath(i + 1, j + 1, path); + path.push_back(j + 1); + result.push_back(path); + } + } + } + return result; + } +} \ No newline at end of file diff --git a/src/0003_graph/0015_maximum_flow_ford_fulkerson.cc b/src/0003_graph/0015_maximum_flow_ford_fulkerson.cc new file mode 100644 index 0000000..dd8d48d --- /dev/null +++ b/src/0003_graph/0015_maximum_flow_ford_fulkerson.cc @@ -0,0 +1,139 @@ +#include "0015_MaximumFlowFordFulkerson.h" +#include +using namespace std; + +namespace MaximumFlowFordFulkerson +{ + // Graph Private Member Methods + void Graph::ResolveAntiParallelEdges() + { + int countParallelEdges = 0; + for (int i = 0; i < this->_noOfVertices; i++) + { + for (int j = 0; j < this->_noOfVertices; j++) + { + if (this->_adjMatrix[i][j] > 0 && this->_adjMatrix[j][i] > 0) + { + countParallelEdges++; + } + } + } + + // As i->j and j->i both edges has been counted, actual count is count = count / 2 + countParallelEdges /= 2; + + this->_flagParallelEdges = countParallelEdges > 0; + + // If there are no anti-parallel edges, no need to modify the adjMatrix + if (!this->_flagParallelEdges) + { + return; + } + + int newNoOfVertices = this->_noOfVertices + countParallelEdges; + + // Modifying the adjMatrix + for (auto& edge : this->_adjMatrix) + { + edge.resize(newNoOfVertices, 0); + } + int k = this->_noOfVertices; + this->_visited.resize(newNoOfVertices, false); + this->_parent.resize(newNoOfVertices, -1); + this->_adjMatrix.resize(newNoOfVertices, vector(newNoOfVertices, 0)); + + // Removing the anti-parallel edges by adding new nodes + for (int i = 0; i < this->_noOfVertices; i++) + { + for (int j = 0; j < this->_noOfVertices; j++) + { + if (this->_adjMatrix[i][j] > 0 && this->_adjMatrix[j][i] > 0) + { + this->_adjMatrix[i][k] = this->_adjMatrix[i][j]; + this->_adjMatrix[k][j] = this->_adjMatrix[i][j]; + this->_adjMatrix[i][j] = 0; + k++; + } + } + } + + // Updating the total no of vertices after modifying the adjMatrix + this->_noOfVertices = newNoOfVertices; + } + + void Graph::DepthFirstSearchVisit(int nodeU) + { + this->_visited[nodeU] = true; + for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) + { + if (!this->_visited[nodeV] && this->_residualGraph[nodeU][nodeV] > 0) + { + this->_parent[nodeV] = nodeU; + this->DepthFirstSearchVisit(nodeV); + } + } + } + + bool Graph::DepthFirstSearch() + { + // Resetting the visited values + fill(this->_visited.begin(), this->_visited.end(), false); + + // Resetting the parent values + fill(this->_parent.begin(), this->_parent.end(), -1); + + // Starting the DepthFirstSearch from the source vertex + this->DepthFirstSearchVisit(this->_source); + + // Returning the visited value of the sink vertex, initially it was set to false + return this->_visited[this->_sink]; + } + + // Graph Public Member Methods + void Graph::CreateGraph(int noOfVertices) + { + this->_noOfVertices = noOfVertices; + this->_source = 0; + this->_sink = this->_noOfVertices - 1; + this->_maximumFlow = 0; + this->_flagParallelEdges = false; + this->_adjMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, 0)); + this->_parent = vector(this->_noOfVertices, -1); + this->_visited = vector(this->_noOfVertices, false); + } + + void Graph::PushDirectedEdge(int valueU, int valueV, int capacity) + { + this->_adjMatrix[valueU][valueV] = capacity; + } + + int Graph::FindMaximumFlowFordFulkerson() + { + // Resolving all the parallel edges if present + this->ResolveAntiParallelEdges(); + this->_residualGraph = this->_adjMatrix; + + // While there exists a path p from source to sink in the residual network G' + while (this->DepthFirstSearch()) + { + int augmentedPathFlow = INT_MAX; + + // Calculating c'(p) = min{ c'(u,v) : (u,v) is in p } + for (int nodeV = this->_sink; nodeV > this->_source; nodeV = this->_parent[nodeV]) + { + int nodeU = this->_parent[nodeV]; + augmentedPathFlow = min(augmentedPathFlow, this->_residualGraph[nodeU][nodeV]); + } + + for (int nodeV = this->_sink; nodeV > this->_source; nodeV = this->_parent[nodeV]) + { + int nodeU = this->_parent[nodeV]; + this->_residualGraph[nodeU][nodeV] -= augmentedPathFlow; + this->_residualGraph[nodeV][nodeU] += augmentedPathFlow; + } + this->_maximumFlow += augmentedPathFlow; + } + + return this->_maximumFlow; + } +} \ No newline at end of file diff --git a/src/0003_graph/0016_maximum_flow_edmonds_karp.cc b/src/0003_graph/0016_maximum_flow_edmonds_karp.cc new file mode 100644 index 0000000..627a2a6 --- /dev/null +++ b/src/0003_graph/0016_maximum_flow_edmonds_karp.cc @@ -0,0 +1,144 @@ +#include "0016_MaximumFlowEdmondsKarp.h" +#include +#include +using namespace std; + +namespace MaximumFlowEdmondsKarp +{ + // Graph Private Member Methods + void Graph::ResolveAntiParallelEdges() + { + int countParallelEdges = 0; + for (int i = 0; i < this->_noOfVertices; i++) + { + for (int j = 0; j < this->_noOfVertices; j++) + { + if (this->_adjMatrix[i][j] > 0 && this->_adjMatrix[j][i] > 0) + { + countParallelEdges++; + } + } + } + + // As i->j and j->i both edges has been counted, actual count is count = count / 2 + countParallelEdges /= 2; + + this->_flagParallelEdges = countParallelEdges > 0; + + // If there are no anti-parallel edges, no need to modify the adjMatrix + if (!this->_flagParallelEdges) + { + return; + } + + int newNoOfVertices = this->_noOfVertices + countParallelEdges; + + // Modifying the adjMatrix + for (auto& edge : this->_adjMatrix) + { + edge.resize(newNoOfVertices, 0); + } + int k = this->_noOfVertices; + this->_visited.resize(newNoOfVertices, false); + this->_parent.resize(newNoOfVertices, -1); + this->_adjMatrix.resize(newNoOfVertices, vector(newNoOfVertices, 0)); + + // Removing the anti-parallel edges by adding new nodes + for (int i = 0; i < this->_noOfVertices; i++) + { + for (int j = 0; j < this->_noOfVertices; j++) + { + if (this->_adjMatrix[i][j] > 0 && this->_adjMatrix[j][i] > 0) + { + this->_adjMatrix[i][k] = this->_adjMatrix[i][j]; + this->_adjMatrix[k][j] = this->_adjMatrix[i][j]; + this->_adjMatrix[i][j] = 0; + k++; + } + } + } + + // Updating the total no of vertices after modifying the adjMatrix + this->_noOfVertices = newNoOfVertices; + } + + bool Graph::BreadthFirstSearch() + { + // Resetting the visited values + fill(this->_visited.begin(), this->_visited.end(), false); + + // Resetting the parent values + fill(this->_parent.begin(), this->_parent.end(), -1); + + queue nodeQueue; + nodeQueue.push(this->_source); + this->_visited[this->_source] = true; + + while (!nodeQueue.empty()) + { + int nodeU = nodeQueue.front(); + nodeQueue.pop(); + + for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) + { + if (!this->_visited[nodeV] && this->_residualGraph[nodeU][nodeV] > 0) + { + this->_parent[nodeV] = nodeU; + this->_visited[nodeV] = true; + nodeQueue.push(nodeV); + } + } + } + + // Returning the visited value of the sink vertex, initially it was set to false + return this->_visited[this->_sink]; + } + + // Graph Public Member Methods + void Graph::CreateGraph(int noOfVertices) + { + this->_noOfVertices = noOfVertices; + this->_source = 0; + this->_sink = this->_noOfVertices - 1; + this->_maximumFlow = 0; + this->_flagParallelEdges = false; + this->_adjMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, 0)); + this->_parent = vector(this->_noOfVertices, -1); + this->_visited = vector(this->_noOfVertices, false); + } + + void Graph::PushDirectedEdge(int valueU, int valueV, int capacity) + { + this->_adjMatrix[valueU][valueV] = capacity; + } + + int Graph::FindMaximumFlowEdmondsKarp() + { + // Resolving all the parallel edges if present + this->ResolveAntiParallelEdges(); + this->_residualGraph = this->_adjMatrix; + + // While there exists a path p from source to sink in the residual network G' + while (this->BreadthFirstSearch()) + { + int augmentedPathFlow = INT_MAX; + + // Calculating c'(p) = min{ c'(u,v) : (u,v) is in p } + for (int nodeV = this->_sink; nodeV > this->_source; nodeV = this->_parent[nodeV]) + { + int nodeU = this->_parent[nodeV]; + augmentedPathFlow = min(augmentedPathFlow, this->_residualGraph[nodeU][nodeV]); + } + + for (int nodeV = this->_sink; nodeV > this->_source; nodeV = this->_parent[nodeV]) + { + int nodeU = this->_parent[nodeV]; + this->_residualGraph[nodeU][nodeV] -= augmentedPathFlow; + this->_residualGraph[nodeV][nodeU] += augmentedPathFlow; + } + this->_maximumFlow += augmentedPathFlow; + } + + return this->_maximumFlow; + } +} \ No newline at end of file diff --git a/src/0003_graph/0017_maximum_bipartite_matching.cc b/src/0003_graph/0017_maximum_bipartite_matching.cc new file mode 100644 index 0000000..7c55ce6 --- /dev/null +++ b/src/0003_graph/0017_maximum_bipartite_matching.cc @@ -0,0 +1,263 @@ +#include "0017_MaximumBipartiteMatching.h" +#include +#include +using namespace std; + +namespace MaximumBipartiteMatching +{ + // Graph Private Member Methods + void Graph::ResolveAntiParallelEdges() + { + int countParallelEdges = 0; + for (int i = 0; i < this->_noOfVertices; i++) + { + for (int j = 0; j < this->_noOfVertices; j++) + { + if (this->_adjMatrix[i][j] > 0 && this->_adjMatrix[j][i] > 0) + { + countParallelEdges++; + } + } + } + + // As i->j and j->i both edges has been counted, actual count is count = count / 2 + countParallelEdges /= 2; + + this->_flagParallelEdges = countParallelEdges > 0; + + // If there are no anti-parallel edges, no need to modify the adjMatrix + if (!this->_flagParallelEdges) + { + return; + } + + int newNoOfVertices = this->_noOfVertices + countParallelEdges; + + // Modifying the adjMatrix + for (auto& edge : this->_adjMatrix) + { + edge.resize(newNoOfVertices, 0); + } + int k = this->_noOfVertices; + this->_visited.resize(newNoOfVertices, false); + this->_parent.resize(newNoOfVertices, -1); + this->_adjMatrix.resize(newNoOfVertices, vector(newNoOfVertices, 0)); + + // Removing the anti-parallel edges by adding new nodes + for (int i = 0; i < this->_noOfVertices; i++) + { + for (int j = 0; j < this->_noOfVertices; j++) + { + if (this->_adjMatrix[i][j] > 0 && this->_adjMatrix[j][i] > 0) + { + this->_adjMatrix[i][k] = this->_adjMatrix[i][j]; + this->_adjMatrix[k][j] = this->_adjMatrix[i][j]; + this->_adjMatrix[i][j] = 0; + k++; + } + } + } + + // Updating the total no of vertices after modifying the adjMatrix + this->_noOfVertices = newNoOfVertices; + } + + // This method is used to color the vertices of the graph to determine if the given graph is bipartite or not + void Graph::ColorGraph() + { + // Color of all the vertices are initialised to WHITE + fill(this->_color.begin(), this->_color.end(), WHITE); + + // Queue to hold the vertices + queue nodeQueue; + + for (int node = 0; node < this->_noOfVertices; node++) + { + // Check if the node is already not colored + if (this->_color[node] == WHITE) + { + // The color of the node is set to RED + this->_color[node] = RED; + + // The node is inserted into the queue + nodeQueue.push(node); + + // Using BFS method to color all the vertices + while (!nodeQueue.empty()) + { + int nodeU = nodeQueue.front(); + nodeQueue.pop(); + + // Iterating over G.Adj[nodeU] + for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) + { + // As there are no self loops, continue + if (nodeU == nodeV) + { + continue; + } + // Check if there is an edge u --> v and nodeV is not colored yet + else if (this->_residualGraph[nodeU][nodeV] != 0 && this->_color[nodeV] == WHITE) + { + // Set the color of nodeV opposite of nodeU + this->_color[nodeV] = 1 - this->_color[nodeU]; + // Insert the nodeV into the queue + nodeQueue.push(nodeV); + } + // Check if there is an edge u --> v and nodeV is of same color as nodeU + else if (this->_residualGraph[nodeU][nodeV] != 0 && this->_color[nodeV] == this->_color[nodeU]) + { + // Set the _isBipartite flag to false and return + this->_isBipartite = false; + return; + } + } + } + } + } + + // If the above operation completes without returning yet that indicates the graph is bipartite + // Set the _isBipartite flag to true and return + this->_isBipartite = true; + return; + } + + // This method is used to create the additional edges + // from the source vertex to the RED colored vertices and + // from the BLUE colored vertices to the sink vertex + void Graph::AddAdditionalEdges() + { + // Resizing the residual graph to accomodate space for the new edges + for (auto& edge : this->_residualGraph) + { + edge.resize(this->_noOfVertices, 0); + } + + this->_parent.resize(this->_noOfVertices, -1); + this->_visited.resize(this->_noOfVertices, false); + this->_color.resize(this->_noOfVertices, WHITE); + this->_residualGraph.resize(this->_noOfVertices, vector(this->_noOfVertices, 0)); + + // Creating the additional edges + for (int node = 0; node < this->_source; node++) + { + // From source vertex --> RED colored vertices + if (this->_color[node] == RED) + { + this->_residualGraph[this->_source][node] = 1; + } + + // From BLUE colored vertices --> sink vertex + else if (this->_color[node] == BLUE) + { + this->_residualGraph[node][this->_sink] = 1; + } + } + } + + // Implementation of BreadthFirstSearch for EdmondsKarp algorithm to find the path from source to sink + bool Graph::BreadthFirstSearch() + { + // Resetting the visited values + fill(this->_visited.begin(), this->_visited.end(), false); + + // Resetting the parent values + fill(this->_parent.begin(), this->_parent.end(), -1); + + queue nodeQueue; + nodeQueue.push(this->_source); + this->_visited[this->_source] = true; + + while (!nodeQueue.empty()) + { + int nodeU = nodeQueue.front(); + nodeQueue.pop(); + + for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) + { + if (!this->_visited[nodeV] && this->_residualGraph[nodeU][nodeV] > 0) + { + this->_parent[nodeV] = nodeU; + this->_visited[nodeV] = true; + nodeQueue.push(nodeV); + } + } + } + + // Returning the visited value of the sink vertex, initially it was set to false + return this->_visited[this->_sink]; + } + + // Graph Public Member Methods + void Graph::CreateGraph(int noOfVertices) + { + this->_noOfVertices = noOfVertices; + this->_maximumFlow = 0; + this->_flagParallelEdges = false; + this->_adjMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, 0)); + this->_parent = vector(this->_noOfVertices, -1); + this->_visited = vector(this->_noOfVertices, false); + this->_color = vector(this->_noOfVertices, WHITE); + } + + void Graph::PushDirectedEdge(int valueU, int valueV) + { + this->_adjMatrix[valueU][valueV] = 1; + } + + int Graph::FindMaximumBipartiteMatching() + { + // Resolving all the parallel edges if present + this->ResolveAntiParallelEdges(); + this->_residualGraph = this->_adjMatrix; + + this->ColorGraph(); + + this->_source = this->_noOfVertices; + this->_noOfVertices++; + this->_sink = this->_noOfVertices; + this->_noOfVertices++; + + this->AddAdditionalEdges(); + + // While there exists a path p from source to sink in the residual network G' + while (this->BreadthFirstSearch()) + { + int augmentedPathFlow = 1; + + // No need to find the minimum amount of augmentedPathFlow as like standard EdmondsKarp algorithm + // as here capacity of each edges is 1 + for (int nodeV = this->_sink; nodeV != this->_source; nodeV = this->_parent[nodeV]) + { + int nodeU = this->_parent[nodeV]; + this->_residualGraph[nodeU][nodeV] -= augmentedPathFlow; + this->_residualGraph[nodeV][nodeU] += augmentedPathFlow; + } + this->_maximumFlow += augmentedPathFlow; + } + + return this->_maximumFlow; + } + + // This method is used for finding the matchings + vector> Graph::GetMatchings() + { + for (int nodeU = 0; nodeU < this->_adjMatrix.size(); nodeU++) + { + for (int nodeV = 0; nodeV < this->_adjMatrix.size(); nodeV++) + { + // Check if the nodeU and nodeV are not source or sink + // and there is a flow of 1 unit from nodeU --> nodeV + // which means nodeU --> nodeV is being used for the maximum flow (maximum matching) + if ((nodeU != this->_source || nodeU != this->_sink || nodeV != this->_source || nodeV != this->_sink) + && + (this->_adjMatrix[nodeU][nodeV] - this->_residualGraph[nodeU][nodeV]) == 1) + { + this->_matchings.push_back({ nodeU, nodeV }); + } + } + } + + return this->_matchings; + } +} \ No newline at end of file diff --git a/src/0003_graph/0018_maximum_flow_goldberg_generic_push_relabel.cc b/src/0003_graph/0018_maximum_flow_goldberg_generic_push_relabel.cc new file mode 100644 index 0000000..63c1475 --- /dev/null +++ b/src/0003_graph/0018_maximum_flow_goldberg_generic_push_relabel.cc @@ -0,0 +1,172 @@ +#include "0018_MaximumFlowGoldbergGenericPushRelabel.h" +#include +using namespace std; + +namespace MaximumFlowGoldbergGenericPushRelabel +{ + // Graph Private Member Methods + + // Initializes Pre-Flow in the given Flow Network + void Graph::InitializePreflow() + { + // The height of source is set to highest possible height value + this->_height[this->_source] = this->_noOfVertices; + + // Iterating over all the vertices + for (int i = 0; i < this->_noOfVertices; i++) + { + // For the all the edges (source, v) + if (this->_residualGraph[this->_source][i] > 0) + { + // v.excessFlow = capacity(source, v) + this->_excessFlow[i] = this->_residualGraph[this->_source][i]; + + // source.excessFlow = source.excessFlow - capacity(source, v) + this->_excessFlow[this->_source] = this->_excessFlow[this->_source] - this->_residualGraph[this->_source][i]; + + // Adjusting the flow and reverse flow along source->v and v->source respectively + this->_residualGraph[i][this->_source] = this->_residualGraph[this->_source][i]; + this->_residualGraph[this->_source][i] = 0; + } + } + } + + // Checks if there is any vertex which has excess flow + bool Graph::CheckOverFlow() + { + // Iterating over all of the vertices + for (int i = 0; i < this->_noOfVertices; i++) + { + // Checks if the current vertex is not any special vertex like source, sink + // and also if there is excess flow in the current vertex and it is already not present in the queue + if (i!=this->_source && i!=this->_sink && this->_excessFlow[i] > 0 && this->_visited[i] == false) + { + // Insert the current vertex into the queue + this->_nodeQueue.push(i); + + // Mark it as visited, so until it leaves the queue it is not inserted again even if all the excess flow is neutralized + this->_visited[i] = true; + } + } + + // Checks if there is no vertex having excess flow then returns false + if (this->_nodeQueue.empty()) + { + return false; + } + + return true; + } + + // Pushes the flow from nodeU to its neighbour vertices + bool Graph::Push(int nodeU) + { + int nodeV = -1; + int minimumFlow = INT_MAX; + + // Iterating over all the vertices + for (int i = 0; i < this->_noOfVertices; i++) + { + // For G'.Adj[nodeU] select the vertex if edge (nodeU, i) is non-saturated and height[nodeU] == height[i] + 1 + if (this->_residualGraph[nodeU][i] > 0 && this->_height[nodeU] == this->_height[i] + 1) + { + nodeV = i; + break; + } + } + + // Checks if any neighbour vertex found having non-saturated edge + if (nodeV != -1) + { + // Calculate the flow amount to be added along the edge and excess flow subtracted from nodeU + minimumFlow = min(this->_residualGraph[nodeU][nodeV], this->_excessFlow[nodeU]); + + // Adjust the flow and the reverse flow along (nodeU, nodeV) + this->_residualGraph[nodeU][nodeV] = this->_residualGraph[nodeU][nodeV] - minimumFlow; + this->_residualGraph[nodeV][nodeU] = this->_residualGraph[nodeV][nodeU] + minimumFlow; + + // Adjust the excess flows in nodeU and nodeV + this->_excessFlow[nodeU] = this->_excessFlow[nodeU] - minimumFlow; + this->_excessFlow[nodeV] = this->_excessFlow[nodeV] + minimumFlow; + + // Return that the Push operation is successful + return true; + } + + // Return that the Push operation is not successful + return false; + } + + // Relabels height of vertex nodeU when there are outgoing non-saturated edges available + void Graph::Relabel(int nodeU) + { + int minimumHeight = INT_MAX; + + // Iterating over all the vertices + for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) + { + // For G'.Adj[nodeU] select for which nodeV, height[nodeU] <= height[nodeV] + if (this->_residualGraph[nodeU][nodeV] > 0 && this->_height[nodeU] <= this->_height[nodeV]) + { + // Get the minimum height among all these G'.Adj[nodeU] + minimumHeight = min(minimumHeight, this->_height[nodeV]); + } + } + + // Set height[nodeU] + this->_height[nodeU] = minimumHeight + 1; + } + + + // Graph Public Member Methods + void Graph::CreateGraph(int noOfVertices) + { + this->_noOfVertices = noOfVertices; + this->_source = 0; + this->_sink = this->_noOfVertices - 1; + this->_maximumFlow = 0; + this->_adjMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, 0)); + this->_excessFlow = vector(this->_noOfVertices, 0); + this->_height = vector(this->_noOfVertices, 0); + this->_visited = vector(this->_noOfVertices, false); + } + + void Graph::PushDirectedEdge(int valueU, int valueV, int capacity) + { + this->_adjMatrix[valueU][valueV] = capacity; + } + + int Graph::FindMaximumFlowGoldbergGenericPushRelabel() + { + this->_residualGraph = this->_adjMatrix; + + // Initialize Pre-flow + this->InitializePreflow(); + + // Checks if there is some vertices which have excess flow + while (this->CheckOverFlow()) + { + // Get the vertex + int nodeU = this->_nodeQueue.front(); + + // Checks if the Push operation is successful + if (this->Push(nodeU)) + { + // Then remove the vertex from queue and set visited[nodeU] = true + // so that on next CheckOverFlow() method call this vertex can be discovered if it still has some excess flow + this->_nodeQueue.pop(); + this->_visited[nodeU] = false; + } + + // If the Push operation is not successful + else + { + // Then Relabel nodeU without removing it from the queue + this->Relabel(nodeU); + } + } + + // Return the excess flow in the sink vertex which is actually the maximum flow along the given flow network + return this->_excessFlow[this->_sink]; + } +} \ No newline at end of file diff --git a/src/0003_graph/0019_maximum_flow_relabel_to_front.cc b/src/0003_graph/0019_maximum_flow_relabel_to_front.cc new file mode 100644 index 0000000..034f5bf --- /dev/null +++ b/src/0003_graph/0019_maximum_flow_relabel_to_front.cc @@ -0,0 +1,169 @@ +#include "0019_MaximumFlowRelabelToFront.h" +#include +#include +using namespace std; + +namespace MaximumFlowRelabelToFront +{ + // Graph Private Member Methods + + // Initializes Pre-Flow in the given Flow Network + void Graph::InitializePreflow() + { + // The height of source is set to highest possible height value + this->_height[this->_source] = this->_noOfVertices; + + // Iterating over all the vertices + for (int i = 0; i < this->_noOfVertices; i++) + { + // For the all the edges (source, v) + if (this->_residualGraph[this->_source][i] > 0) + { + // v.excessFlow = capacity(source, v) + this->_excessFlow[i] = this->_residualGraph[this->_source][i]; + + // source.excessFlow = source.excessFlow - capacity(source, v) + this->_excessFlow[this->_source] = this->_excessFlow[this->_source] - this->_residualGraph[this->_source][i]; + + // Adjusting the flow and reverse flow along source->v and v->source respectively + this->_residualGraph[i][this->_source] = this->_residualGraph[this->_source][i]; + this->_residualGraph[this->_source][i] = 0; + } + } + } + + // Discharges the excess flow from nodeU + void Graph::Discharge(int nodeU) + { + // Check if excess flow of nodeU is > 0 + while (this->_excessFlow[nodeU] > 0) + { + // Falg to check if any amount of excess flow is pushed to any neighbour vertex + bool hasPushed = false; + + // Iterating over all of the vertices + for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) + { + // For G'.Adj[nodeU] check if edge (nodeU, nodeV) is admissible + if (this->_residualGraph[nodeU][nodeV] > 0 && this->_height[nodeU] == 1 + this->_height[nodeV]) + { + // Push excess flow along the admissible edge (nodeU, nodeV) + this->Push(nodeU, nodeV); + // Set the hasPushed flag to true + hasPushed = true; + // Check if there is no excess flow left in nodeU then no need to check any more admissible edge going from nodeU + if (this->_excessFlow[nodeU] == 0) + { + // Then break from iterating over G'.Adj[nodeU] + break; + } + } + } + + // Check if Push operation is not done yet + if (!hasPushed) + { + // Then it indicates that all the outgoing edges from nodeU are inadmissible + // so perform the Relabel operation on nodeU + this->Relabel(nodeU); + } + } + } + + // Pushes the flow from nodeU to its neighbour vertices + void Graph::Push(int nodeU, int nodeV) + { + // Calculate the flow amount to be added along the edge and excess flow subtracted from nodeU + int minimumFlow = min(this->_residualGraph[nodeU][nodeV], this->_excessFlow[nodeU]); + + // Adjust the flow and the reverse flow along (nodeU, nodeV) + this->_residualGraph[nodeU][nodeV] = this->_residualGraph[nodeU][nodeV] - minimumFlow; + this->_residualGraph[nodeV][nodeU] = this->_residualGraph[nodeV][nodeU] + minimumFlow; + + // Adjust the excess flows in nodeU and nodeV + this->_excessFlow[nodeU] = this->_excessFlow[nodeU] - minimumFlow; + this->_excessFlow[nodeV] = this->_excessFlow[nodeV] + minimumFlow; + } + + // Relabels height of vertex nodeU when there are outgoing non-saturated edges available + void Graph::Relabel(int nodeU) + { + int minimumHeight = INT_MAX; + + // Iterating over all the vertices + for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) + { + // For G'.Adj[nodeU] select for which nodeV, height[nodeU] <= height[nodeV] + if (this->_residualGraph[nodeU][nodeV] > 0 && this->_height[nodeU] <= this->_height[nodeV]) + { + // Get the minimum height among all these G'.Adj[nodeU] + minimumHeight = min(minimumHeight, this->_height[nodeV]); + } + } + + // Set height[nodeU] + this->_height[nodeU] = minimumHeight + 1; + } + + + // Graph Public Member Methods + void Graph::CreateGraph(int noOfVertices) + { + this->_noOfVertices = noOfVertices; + this->_source = 0; + this->_sink = this->_noOfVertices - 1; + this->_maximumFlow = 0; + this->_adjMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, 0)); + this->_excessFlow = vector(this->_noOfVertices, 0); + this->_height = vector(this->_noOfVertices, 0); + this->_visited = vector(this->_noOfVertices, false); + } + + void Graph::PushDirectedEdge(int valueU, int valueV, int capacity) + { + this->_adjMatrix[valueU][valueV] = capacity; + } + + int Graph::FindMaximumFlowRelabelToFront() + { + this->_residualGraph = this->_adjMatrix; + + // Initialize Pre-flow + this->InitializePreflow(); + + // Make the list L = G.V - {source, sink} + for (int i = 0; i < this->_noOfVertices; i++) + { + if (i != this->_source && i != this->_sink) + { + this->_nodeList.push_back(i); + } + } + + // Set current vertex = L.head + list::iterator nodeUiterator = this->_nodeList.begin(); + + // Iterate over all of the elements in the list L + while (nodeUiterator != this->_nodeList.end()) + { + // Get the height of current vertex + int oldHeight = this->_height[*nodeUiterator]; + + // Discharge the excess flow of current vertex + this->Discharge(*nodeUiterator); + + // Check if the height of current vertex increases which means the current vertex got relabeled + if (this->_height[*nodeUiterator] > oldHeight) + { + // Then move current vertex to the front of the list L + this->_nodeList.splice(this->_nodeList.begin(), this->_nodeList, nodeUiterator); + } + + // Go to the next vertex of current vertex in L + nodeUiterator++; + } + + // Return the excess flow in the sink vertex which is actually the maximum flow along the given flow network + return this->_excessFlow[this->_sink]; + } +} \ No newline at end of file diff --git a/src/0003_graph/CMakeLists.txt b/src/0003_graph/CMakeLists.txt new file mode 100644 index 0000000..02f8a77 --- /dev/null +++ b/src/0003_graph/CMakeLists.txt @@ -0,0 +1,30 @@ +# Specify the source files +set(0003GRAPH_SOURCES + 0001_BreadthFirstSearch.cc + 0002_DepthFirstSearch.cc + 0003_TopologicalSort.cc + 0004_StronglyConnectedComponents.cc + 0005_HamiltonianPathAndCycle.cc + 0006_EulerianPathAndCircuit.cc + 0007_MinimumSpanningTreeKruskalAlgorithm.cc + 0008_MinimumSpanningTreePrimAlgorithm.cc + 0009_SingleSourceShortestPathBellmanFord.cc + 0010_DirectedAcyclicGraphShortestPath.cc + 0011_SingleSourceShortestPathDijkstra.cc + 0012_DifferenceConstraintsShortestPaths.cc + 0013_AllPairsShortestPathsFloydWarshall.cc + 0014_AllPairsShortestPathsJohnson.cc + 0015_MaximumFlowFordFulkerson.cc + 0016_MaximumFlowEdmondsKarp.cc + 0017_MaximumBipartiteMatching.cc + 0018_MaximumFlowGoldbergGenericPushRelabel.cc + 0019_MaximumFlowRelabelToFront.cc + +) + +# Create a library target +add_library(0003GRAPH ${0003GRAPH_SOURCES}) + +target_include_directories(0003GRAPH PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}/headers +) \ No newline at end of file diff --git a/src/0003_graph/headers/0001_breadth_first_search.h b/src/0003_graph/headers/0001_breadth_first_search.h new file mode 100644 index 0000000..ba7aec8 --- /dev/null +++ b/src/0003_graph/headers/0001_breadth_first_search.h @@ -0,0 +1,35 @@ +#pragma once + +#include +#include +#include +#include +#include +using namespace std; + +namespace BreadthFirstSearch +{ + enum color { WHITE, GRAY, BLACK }; + class Node + { + public: + int data; + int distance; + int color; + Node* parent; + Node(int value); + }; + + class Graph + { + private: + map> _adjlist; + map _nodeMap; + Node* MakeOrFindNode(int value); + void BreadthFirstSearch(Node* node); + public: + void PushUndirectedEdge(int valueU, int valueV); + void BFS(int value); + vector> ShowBFSResult(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0002_depth_first_search.h b/src/0003_graph/headers/0002_depth_first_search.h new file mode 100644 index 0000000..e376295 --- /dev/null +++ b/src/0003_graph/headers/0002_depth_first_search.h @@ -0,0 +1,37 @@ +#pragma once + +#include +#include +#include +#include +using namespace std; + +namespace DepthFirstSearch +{ + enum color { WHITE, GRAY, BLACK }; + + class Node + { + public: + int data; + int color; + int discoveredTime; + int finishingTime; + Node* parent; + Node(int value); + }; + + class Graph + { + private: + int _time; + map> _adjlist; + map _nodeMap; + Node* MakeOrFindNode(int value); + void DepthFirstSearch(Node* Node); + public: + void PushDirectedEdge(int valueU, int valueV); + void DFS(); + vector>> ShowDFSResult(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0003_topological_sort.h b/src/0003_graph/headers/0003_topological_sort.h new file mode 100644 index 0000000..441d7d1 --- /dev/null +++ b/src/0003_graph/headers/0003_topological_sort.h @@ -0,0 +1,42 @@ +#pragma once + +#include +#include +#include +#include +using namespace std; + +namespace TopologicalSort +{ + enum color { WHITE, GRAY, BLACK }; + + class Node + { + public: + int data; + int color; + int discoveryTime; + int finishingTime; + int inDegree; + Node* parent; + Node(int value); + }; + + class Graph + { + private: + int _time; + bool _hasCycle; + map> _adjlist; + map _nodeMap; + list _topologicalSortedNodeList; + Node* MakeOrFindNode(int value); + void DepthFirstSearch(Node* DFSNode); + public: + void PushDirectedEdge(int valueU, int valueV); + void PushSingleNode(int valueU); + void TopologicalSort(); + void KahnTopologicalSort(); + vector>> ShowTopologicalSortResult(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0004_strongly_connected_components.h b/src/0003_graph/headers/0004_strongly_connected_components.h new file mode 100644 index 0000000..0e37f60 --- /dev/null +++ b/src/0003_graph/headers/0004_strongly_connected_components.h @@ -0,0 +1,43 @@ +#pragma once + +#include +#include +#include +#include +using namespace std; + +namespace StronglyConnectedComponents +{ + enum color { WHITE, GRAY, BLACK }; + + class Node + { + public: + int data; + int color; + int discoveryTime; + int finishingTime; + Node* parent; + Node(int value); + }; + + class Graph + { + private: + int _time; + map> _adjlistG; + map> _adjlistT; + map _nodeMap; + list _nodesFinishingTimeOrder; + vector> _allConnectedComponents; + Node* MakeOrFindNode(int value); + void DepthFirstSearchOnGraphG(Node* DFSNode); + void DepthFirstSearchOnGraphT(Node* DFSNode, vector& connectedComponents); + public: + void PushDirectedEdge(int valueU, int valueV); + void PushSingleNode(int valueU); + void DFSOnGraphG(); + void DFSOnGraphT(); + vector> FindAllStronglyConnectedComponents(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0005_hamiltonian_path_and_cycle.h b/src/0003_graph/headers/0005_hamiltonian_path_and_cycle.h new file mode 100644 index 0000000..7ccca6a --- /dev/null +++ b/src/0003_graph/headers/0005_hamiltonian_path_and_cycle.h @@ -0,0 +1,40 @@ +#pragma once + +#include +#include +#include +using namespace std; + +namespace HamiltonianPathAndCycle +{ + class Node + { + public: + int data; + bool isVisited; + Node(int value); + }; + + class Graph + { + private: + bool _isHamiltonianCyclePresent; + bool _isHamiltonianPathPresent; + int _visitedNodeCount; + Node* _startingNode; + map> _adjlist; + map _nodeMap; + vector _hamiltonianPath; + Node* MakeOrFindNode(int value); + bool IsSafe(Node* nodeU, Node* nodeV); + bool HamiltonianCycleAndPathUtil(Node* node); + + public: + void PushUndirectedEdge(int valueU, int valueV); + void PushSingleNode(int valueU); + void FindHamiltonianCycleAndPath(); + bool IsHamiltonianCyclePresent(); + bool IsHamiltonianPathPresent(); + vector GetHamiltonianPath(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0006_eulerian_path_and_circuit.h b/src/0003_graph/headers/0006_eulerian_path_and_circuit.h new file mode 100644 index 0000000..92d0d34 --- /dev/null +++ b/src/0003_graph/headers/0006_eulerian_path_and_circuit.h @@ -0,0 +1,43 @@ +#pragma once + +#include +#include +#include +using namespace std; + +namespace EulerianPathAndCircuit +{ + class Node + { + public: + int data; + int degree; + int inDegree; + int outDegree; + bool visited; + Node(int value); + }; + + class Graph + { + private: + bool _isEulerianPathPresent; + bool _isEulerianCircuitPresent; + map> _adjlist; + map _nodeMap; + vector _eulerianPath; + Node* MakeOrFindNode(int value); + void DepthFirstSearch(Node* node); + bool IsConnected(); + void EulerianPathHierholzerAlgorithm(Node* startingNode); + + public: + void PushUndirectedEdge(int valueU, int valueV); + void PushDirectedEdge(int valueU, int valueV); + void PushSingleNode(int valueU); + void FindEulerianPathAndCircuit(); + bool IsEulerianPathPresent(); + bool IsEulerianCircuitPresent(); + vector UndirectedGraphGetEulerianPath(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0007_minimum_spanning_tree_kruskal_algorithm.h b/src/0003_graph/headers/0007_minimum_spanning_tree_kruskal_algorithm.h new file mode 100644 index 0000000..8ca704c --- /dev/null +++ b/src/0003_graph/headers/0007_minimum_spanning_tree_kruskal_algorithm.h @@ -0,0 +1,46 @@ +#pragma once + +#include +#include +#include +using namespace std; + +namespace MinimumSpanningTreeKruskalAlgorithm +{ + class Node + { + public: + int data; + Node* parent; + int rank; + Node(int data); + }; + + class Edge + { + public: + Node* nodeU; + Node* nodeV; + int weight; + Edge(Node* nodeU, Node* nodeV, int weight); + }; + + class Graph + { + private: + map> _adjlist; + map _nodeMap; + vector _edgeList; + vector, int>> _minimumSpanningTree; + Node* MakeOrFindNode(int data); + void MakeSet(Node* node); + void Union(Node* nodeU, Node* nodeV); + void Link(Node* nodeU, Node* nodeV); + Node* FindSet(Node* node); + + public: + void PushUndirectedEdge(int valueU, int valueV, int weight); + void FindMinimumSpanningTreeKruskalAlgorithm(); + vector, int>> GetMinimumSpanningTree(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0008_minimum_spanning_tree_prim_algorithm.h b/src/0003_graph/headers/0008_minimum_spanning_tree_prim_algorithm.h new file mode 100644 index 0000000..ffe7c08 --- /dev/null +++ b/src/0003_graph/headers/0008_minimum_spanning_tree_prim_algorithm.h @@ -0,0 +1,42 @@ +# pragma once + +#include +#include +#include +using namespace std; + +namespace MinimumSpanningTreePrimAlgorithm +{ + class Node + { + public: + int data; + Node* parent; + int key; + bool isInOperationalSet; + Node(int data); + }; + + class CompareNodeKey + { + public: + bool operator()(const Node* nodeU, const Node* nodeV) const + { + return nodeU->key < nodeV->key; + } + }; + + class Graph + { + private: + map>> _adjlist; + map _nodeMap; + vector, int>> _minimumSpanningTree; + multiset _operationalSet; + Node* MakeOrFindNode(int data); + public: + void PushUndirectedEdge(int valueU, int valueV, int weight); + void FindMinimumSpanningTreePrimAlgorithm(); + vector, int>> GetMinimumSpanningTree(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0009_single_source_shortest_path_bellman_ford.h b/src/0003_graph/headers/0009_single_source_shortest_path_bellman_ford.h new file mode 100644 index 0000000..e51ca10 --- /dev/null +++ b/src/0003_graph/headers/0009_single_source_shortest_path_bellman_ford.h @@ -0,0 +1,44 @@ +#pragma once + +#include +#include +using namespace std; + +namespace SingleSourceShortestPathBellmanFord +{ + class Node + { + public: + int data; + int distance; + Node* parent; + Node(int data); + }; + + class Edge + { + public: + Node* nodeU; + Node* nodeV; + int weight; + Edge(Node* nodeU, Node* nodeV, int weight); + }; + + class Graph + { + private: + map> _adjlist; + map _nodeMap; + vector _edgeList; + Node* MakeOrFindNode(int data); + void InitializeSingleSource(Node* sourceNode); + void Relax(Edge* edge); + void GetShortestPath(Node* node, vector& path); + + + public: + void PushDirectedEdge(int valueU, int valueV, int weight); + bool FindSingleSourceShortestPathBellmanFord(int data); + vector GetShortestPathBellmanFord(int data); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0010_directed_acyclic_graph_shortest_path.h b/src/0003_graph/headers/0010_directed_acyclic_graph_shortest_path.h new file mode 100644 index 0000000..8826ebc --- /dev/null +++ b/src/0003_graph/headers/0010_directed_acyclic_graph_shortest_path.h @@ -0,0 +1,51 @@ +#pragma once + +#include +#include +#include +using namespace std; + +namespace DirectedAcyclicGraphShortestPath +{ + enum color {WHITE, GRAY, BLACK}; + + class Node + { + public: + int data; + int color; + int distance; + Node* parent; + Node(int data); + }; + + class Edge + { + public: + Node* nodeU; + Node* nodeV; + int weight; + Edge(Node* nodeU, Node* nodeV, int weight); + }; + + class Graph + { + private: + map> _adjlist; + map _nodeMap; + map> _edgeMap; + list _topologicalSortedNodeList; + Node* MakeOrFindNode(int data); + void DepthFirstSearch(Node* node); + void TopologicalSort(); + void InitializeSingleSource(Node* sourceNode); + void Relax(Edge* edge); + void GetShortestPath(Node* node, vector& path); + + + public: + void PushDirectedEdge(int valueU, int valueV, int weight); + void FindDAGShortestPath(int data); + vector GetDAGShortestPath(int data); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0011_single_source_shortest_path_dijkstra.h b/src/0003_graph/headers/0011_single_source_shortest_path_dijkstra.h new file mode 100644 index 0000000..8911ac8 --- /dev/null +++ b/src/0003_graph/headers/0011_single_source_shortest_path_dijkstra.h @@ -0,0 +1,55 @@ +#pragma once + +#include +#include +#include +using namespace std; + +namespace SingleSourceShortestPathDijkstra +{ + class Node + { + public: + int data; + int distance; + Node* parent; + Node(int data); + }; + + class Edge + { + public: + Node* nodeU; + Node* nodeV; + int weight; + Edge(Node* nodeU, Node* nodeV, int weight); + }; + + class CompareNodeDistance + { + public: + bool operator()(const Node* nodeU, const Node* nodeV) const + { + return nodeU->distance < nodeV->distance; + } + }; + + class Graph + { + private: + map> _adjlist; + map _nodeMap; + map> _edgeMap; + multiset _operationalSet; + Node* MakeOrFindNode(int data); + void InitializeSingleSource(Node* sourceNode); + void Relax(Edge* edge); + void Dijkstra(Node* source); + void GetShortestPath(Node* node, vector& path); + + public: + void PushDirectedEdge(int valueU, int valueV, int weight); + void FindShortestPathDijkstra(int data); + vector GetDijkstraShortestPath(int data); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0012_difference_constraints_shortest_paths.h b/src/0003_graph/headers/0012_difference_constraints_shortest_paths.h new file mode 100644 index 0000000..02d1426 --- /dev/null +++ b/src/0003_graph/headers/0012_difference_constraints_shortest_paths.h @@ -0,0 +1,43 @@ +#pragma once + +#include +#include +#include +using namespace std; + +namespace DifferenceConstraintsShortestPaths +{ + class Node + { + public: + string data; + int distance; + Node(string data); + }; + + class Edge + { + public: + Node* nodeU; + Node* nodeV; + int weight; + Edge(Node* nodeU, Node* nodeV, int weight); + }; + + class Graph + { + private: + map> _adjlist; + map _nodeMap; + vector _edgeList; + Node* MakeOrFindNode(string data); + void PushDirectedEdge(string valueU, string valueV, int weight); + void InitializeSingleSource(Node* sourceNode); + void Relax(Edge* edge); + + public: + void PushAllDirectedEdges(vector> vectorA, vector vectorX, vector vectorB); + bool FindDifferenceConstraintsSolutionBellmanFord(); + vector> GetDifferenceConstrtaintsSolution(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0013_all_pairs_shortest_paths_floyd_warshall.h b/src/0003_graph/headers/0013_all_pairs_shortest_paths_floyd_warshall.h new file mode 100644 index 0000000..211e1b6 --- /dev/null +++ b/src/0003_graph/headers/0013_all_pairs_shortest_paths_floyd_warshall.h @@ -0,0 +1,24 @@ +#pragma once + +#include +using namespace std; + +namespace AllPairsShortestPathsFloydWarshall +{ + class Graph + { + private: + int _noOfVertices; + vector> _adjMatrix; + vector> _shortestPathMatrixFloydWarshall; + vector> _predecessorMatrix; + void InitializeDistanceAndPredecessors(); + void GetShortestPath(int source, int destination, vector& path); + + public: + void CreateGraph(int noOfVertices); + void PushDirectedEdge(int valueU, int valueV, int weight); + void FindAllPairsShortestPathsFloydWarshallSolution(); + vector> GetFloydWarshallShortestPath(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0014_all_pairs_shortest_paths_johnson.h b/src/0003_graph/headers/0014_all_pairs_shortest_paths_johnson.h new file mode 100644 index 0000000..925e89e --- /dev/null +++ b/src/0003_graph/headers/0014_all_pairs_shortest_paths_johnson.h @@ -0,0 +1,66 @@ +#pragma once + +#include +#include +#include +using namespace std; + +namespace AllPairsShortestPathsJohnson +{ + class Node + { + public: + int data; + int distance; + Node* parent; + int potentialWeight; + Node(int data); + }; + + class Edge + { + public: + Node* nodeU; + Node* nodeV; + int weight; + Edge(Node* nodeU, Node* nodeV, int weight); + }; + + class CompareNodeDistance + { + public: + bool operator()(const Node* nodeU, const Node* nodeV) const + { + return nodeU->distance < nodeV->distance; + } + }; + + class Graph + { + private: + int _noOfVertices=0; + map> _adjlist; + map _nodeMap; + vector _edgeList; + map> _edgeMap; + map> _augmentedAdjlist; + vector _augmentedEdgeList; + multiset _operationalSet; + vector> _shortestPathMatrix; + vector> _predecessorMatrix; + Node* MakeOrFindNode(int data); + void PushAugmentedDirectedEdges(Node* sourceNode, Node* nodeV, int weight); + void InitializeSingleSource(Node* sourceNode); + void RelaxBellmanFord(Edge* edge); + bool BellmanFord(Node* source); + void RelaxDijkstra(Edge* edge); + void Dijkstra(Node* source); + void GetShortestPath(int source, int destination, vector& path); + + public: + void PushDirectedEdge(int dataU, int dataV, int weight); + bool FindAllPairsShortestPathsJohnsonAlgorithm(); + vector> GetAllPairsShortestPathsDistanceMatrix(); + vector> GetAllPairsShortestPathsPathMatrix(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0015_maximum_flow_ford_fulkerson.h b/src/0003_graph/headers/0015_maximum_flow_ford_fulkerson.h new file mode 100644 index 0000000..429b247 --- /dev/null +++ b/src/0003_graph/headers/0015_maximum_flow_ford_fulkerson.h @@ -0,0 +1,29 @@ +#pragma once + +#include +#include +using namespace std; + +namespace MaximumFlowFordFulkerson +{ + class Graph + { + private: + int _noOfVertices; + int _source; + int _sink; + int _maximumFlow; + bool _flagParallelEdges; + vector> _adjMatrix; + vector> _residualGraph; + vector _parent; + vector _visited; + void ResolveAntiParallelEdges(); + void DepthFirstSearchVisit(int nodeU); + bool DepthFirstSearch(); + public: + void CreateGraph(int noOfVertices); + void PushDirectedEdge(int valueU, int valueV, int capacity); + int FindMaximumFlowFordFulkerson(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0016_maximum_flow_edmonds_karp.h b/src/0003_graph/headers/0016_maximum_flow_edmonds_karp.h new file mode 100644 index 0000000..25c72f1 --- /dev/null +++ b/src/0003_graph/headers/0016_maximum_flow_edmonds_karp.h @@ -0,0 +1,28 @@ +#pragma once + +#include +#include +using namespace std; + +namespace MaximumFlowEdmondsKarp +{ + class Graph + { + private: + int _noOfVertices; + int _source; + int _sink; + int _maximumFlow; + bool _flagParallelEdges; + vector> _adjMatrix; + vector> _residualGraph; + vector _parent; + vector _visited; + void ResolveAntiParallelEdges(); + bool BreadthFirstSearch(); + public: + void CreateGraph(int noOfVertices); + void PushDirectedEdge(int valueU, int valueV, int capacity); + int FindMaximumFlowEdmondsKarp(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0017_maximum_bipartite_matching.h b/src/0003_graph/headers/0017_maximum_bipartite_matching.h new file mode 100644 index 0000000..741c3c0 --- /dev/null +++ b/src/0003_graph/headers/0017_maximum_bipartite_matching.h @@ -0,0 +1,41 @@ +#pragma once + +#include +#include +using namespace std; + +namespace MaximumBipartiteMatching +{ + enum Color + { + WHITE = -1, + RED = 0, + BLUE = 1 + }; + + class Graph + { + private: + int _noOfVertices; + int _source; + int _sink; + int _maximumFlow; + bool _flagParallelEdges; + bool _isBipartite; + vector> _adjMatrix; + vector> _residualGraph; + vector _parent; + vector _visited; + vector _color; + vector> _matchings; + void ResolveAntiParallelEdges(); + void ColorGraph(); + void AddAdditionalEdges(); + bool BreadthFirstSearch(); + public: + void CreateGraph(int noOfVertices); + void PushDirectedEdge(int valueU, int valueV); + int FindMaximumBipartiteMatching(); + vector> GetMatchings(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0018_maximum_flow_goldberg_generic_push_relabel.h b/src/0003_graph/headers/0018_maximum_flow_goldberg_generic_push_relabel.h new file mode 100644 index 0000000..fb13a01 --- /dev/null +++ b/src/0003_graph/headers/0018_maximum_flow_goldberg_generic_push_relabel.h @@ -0,0 +1,31 @@ +#pragma once + +#include +#include +using namespace std; + +namespace MaximumFlowGoldbergGenericPushRelabel +{ + class Graph + { + private: + int _noOfVertices; + int _source; + int _sink; + int _maximumFlow; + vector> _adjMatrix; + vector> _residualGraph; + vector _excessFlow; + vector _height; + vector _visited; + queue _nodeQueue; + void InitializePreflow(); + bool CheckOverFlow(); + bool Push(int nodeU); + void Relabel(int nodeU); + public: + void CreateGraph(int noOfVertices); + void PushDirectedEdge(int valueU, int valueV, int capacity); + int FindMaximumFlowGoldbergGenericPushRelabel(); + }; +} \ No newline at end of file diff --git a/src/0003_graph/headers/0019_maximum_flow_relabel_to_front.h b/src/0003_graph/headers/0019_maximum_flow_relabel_to_front.h new file mode 100644 index 0000000..aea70f6 --- /dev/null +++ b/src/0003_graph/headers/0019_maximum_flow_relabel_to_front.h @@ -0,0 +1,31 @@ +#pragma once + +#include +#include +using namespace std; + +namespace MaximumFlowRelabelToFront +{ + class Graph + { + private: + int _noOfVertices; + int _source; + int _sink; + int _maximumFlow; + vector> _adjMatrix; + vector> _residualGraph; + vector _excessFlow; + vector _height; + vector _visited; + list _nodeList; + void InitializePreflow(); + void Discharge(int nodeU); + void Push(int nodeU, int nodeV); + void Relabel(int nodeU); + public: + void CreateGraph(int noOfVertices); + void PushDirectedEdge(int valueU, int valueV, int capacity); + int FindMaximumFlowRelabelToFront(); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0001_fibonacci_number.cc b/src/0004_dynamic_programming/0001_fibonacci_number.cc new file mode 100644 index 0000000..47073aa --- /dev/null +++ b/src/0004_dynamic_programming/0001_fibonacci_number.cc @@ -0,0 +1,28 @@ +#include "0001_FibonacciNumber.h" + +namespace FibonacciNumber +{ + int DynamicProgramming::RecursiveNthFibonacci(int n) + { + if (n <= 1) + { + return n; + } + + return this->RecursiveNthFibonacci(n - 1) + this->RecursiveNthFibonacci(n - 2); + } + + int DynamicProgramming::DpNthFibonacci(int n) + { + vector dp(n + 1, 0); + dp[0] = 0; + dp[1] = 1; + + for (int i = 2; i <= n; i++) + { + dp[i] = dp[i - 1] + dp[i - 2]; + } + + return dp[n]; + } +} diff --git a/src/0004_dynamic_programming/0002_tribonacci_number.cc b/src/0004_dynamic_programming/0002_tribonacci_number.cc new file mode 100644 index 0000000..84a4c59 --- /dev/null +++ b/src/0004_dynamic_programming/0002_tribonacci_number.cc @@ -0,0 +1,33 @@ +#include "0002_TribonacciNumber.h" + +namespace TribonacciNumber +{ + int DynamicProgramming::RecursiveNthTribonacci(int n) + { + if (n == 0 || n == 1 || n == 2) + { + return 0; + } + + if (n == 3) + { + return 1; + } + + return this->RecursiveNthTribonacci(n - 1) + this->RecursiveNthTribonacci(n - 2) + this->RecursiveNthTribonacci(n - 3); + } + + int DynamicProgramming::DpNthTribonacci(int n) + { + vector dp(n, 0); + dp[0] = dp[1] = 0; + dp[2] = 1; + + for (int i = 3; i < n; i++) + { + dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]; + } + + return dp[n - 1]; + } +} diff --git a/src/0004_dynamic_programming/0003_climbing_stairs.cc b/src/0004_dynamic_programming/0003_climbing_stairs.cc new file mode 100644 index 0000000..6e365f8 --- /dev/null +++ b/src/0004_dynamic_programming/0003_climbing_stairs.cc @@ -0,0 +1,29 @@ +#include "0003_ClimbingStairs.h" +using namespace std; + +namespace ClimbingStairs +{ + int DynamicProgramming::RecursiveCountWays(int n) + { + if (n == 0 || n == 1) + { + return 1; + } + + return this->RecursiveCountWays(n - 1) + this->RecursiveCountWays(n - 2); + } + + int DynamicProgramming::DpCountWays(int n) + { + vector dp(n + 1, 0); + dp[0] = 1; + dp[1] = 1; + + for (int i = 2; i <= n; i++) + { + dp[i] = dp[i - 1] + dp[i - 2]; + } + + return dp[n]; + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0004_minimum_cost_climbing_stairs.cc b/src/0004_dynamic_programming/0004_minimum_cost_climbing_stairs.cc new file mode 100644 index 0000000..661afc4 --- /dev/null +++ b/src/0004_dynamic_programming/0004_minimum_cost_climbing_stairs.cc @@ -0,0 +1,48 @@ +#include "0004_MinimumCostClimbingStairs.h" +#include + +namespace MinimumCostClimbingStairs +{ + int DynamicProgramming::MinCostRecursive(size_t step, vector& cost) + { + if (step == 0 || step == 1) + { + return cost[step]; + } + + return cost[step] + min(this->MinCostRecursive(step - 1, cost), this->MinCostRecursive(step - 2, cost)); + } + + int DynamicProgramming::RecursiveMinimumCostClimbingStairs(vector& cost) + { + size_t totalSteps = cost.size(); + + if (totalSteps == 1) + { + return cost[0]; + } + + return min(this->MinCostRecursive(totalSteps - 1, cost), this->MinCostRecursive(totalSteps - 2, cost)); + } + + int DynamicProgramming::DpMinimumCostClimbingStairs(vector& cost) + { + size_t totalSteps = cost.size(); + vector dp(totalSteps, 0); + + if (totalSteps == 1) + { + return cost[0]; + } + + dp[0] = cost[0]; + dp[1] = cost[1]; + + for (size_t i = 2; i < totalSteps; i++) + { + dp[i] = cost[i] + min(dp[i - 1], dp[i - 2]); + } + + return min(dp[totalSteps - 1], dp[totalSteps - 2]); + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0005_house_robber1.cc b/src/0004_dynamic_programming/0005_house_robber1.cc new file mode 100644 index 0000000..2e3fb7f --- /dev/null +++ b/src/0004_dynamic_programming/0005_house_robber1.cc @@ -0,0 +1,44 @@ +#include "0005_HouseRobber1.h" + +namespace HouseRobber1 +{ + int DynamicProgramming::MaxLootRecursive(size_t house, vector& houseValues) + { + if (house <= 0) + { + return 0; + } + + if (house == 1) + { + return houseValues[0]; + } + + int pickCurrentHouse = houseValues[house - 1] + this->MaxLootRecursive(house - 2, houseValues); + int dropCurrentHouse = this->MaxLootRecursive(house - 1, houseValues); + + return max(pickCurrentHouse, dropCurrentHouse); + } + + int DynamicProgramming::RecursiveMaximumLoot(vector& houseValues) + { + size_t totalNumberOfHouses = houseValues.size(); + return this->MaxLootRecursive(totalNumberOfHouses, houseValues); + } + + int DynamicProgramming::DpMaximumLoot(vector& houseValues) + { + size_t totalNumberOfHouses = houseValues.size(); + vector dp(totalNumberOfHouses + 1, 0); + + dp[0] = 0; + dp[1] = houseValues[0]; + + for (size_t i = 2; i <= totalNumberOfHouses; i++) + { + dp[i] = max(dp[i - 2] + houseValues[i - 1], dp[i - 1]); + } + + return dp[totalNumberOfHouses]; + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0006_house_robber2.cc b/src/0004_dynamic_programming/0006_house_robber2.cc new file mode 100644 index 0000000..cbefdda --- /dev/null +++ b/src/0004_dynamic_programming/0006_house_robber2.cc @@ -0,0 +1,95 @@ +#include "0006_HouseRobber2.h" + +namespace HouseRobber2 +{ + int DynamicProgramming::MaxLootRecursive(size_t house, vector& houseValues) + { + if (house <= 0) + { + return 0; + } + + if (house == 1) + { + return houseValues[0]; + } + + int pickCurrentHouse = houseValues[house - 1] + this->MaxLootRecursive(house - 2, houseValues); + int dropCurrentHouse = this->MaxLootRecursive(house - 1, houseValues); + + return max(pickCurrentHouse, dropCurrentHouse); + } + + int DynamicProgramming::MaxLootDp(size_t firstHouse, size_t lastHouse, vector& houseValues) + { + int totalNumberOfHouses = lastHouse - firstHouse + 1; + + if (totalNumberOfHouses == 0) + { + return 0; + } + + if (totalNumberOfHouses == 1) + { + return houseValues[firstHouse]; + } + + vector dp(totalNumberOfHouses, 0); + + dp[0] = houseValues[firstHouse]; + dp[1] = max(houseValues[firstHouse], houseValues[firstHouse + 1]); + + for (size_t i = 2; i < totalNumberOfHouses; i++) + { + dp[i] = max(houseValues[firstHouse + i] + dp[i - 2], dp[i - 1]); + } + + return dp[totalNumberOfHouses - 1]; + } + + int DynamicProgramming::RecursiveMaximumLoot(vector& houseValues) + { + if (houseValues.size() == 0) + { + return 0; + } + + if (houseValues.size() == 1) + { + return houseValues[0]; + } + + size_t totalNumberOfHouses = houseValues.size()-1; + + // Case 1: Exclude last house. + vector pickFirstHouse(houseValues.begin(), houseValues.end() - 1); + + // Case 2: Exlcude first house. + vector pickLastHouse(houseValues.begin() + 1, houseValues.end()); + + return max(this->MaxLootRecursive(totalNumberOfHouses, pickFirstHouse), this->MaxLootRecursive(totalNumberOfHouses, pickLastHouse)); + } + + int DynamicProgramming::DpMaximumLoot(vector& houseValues) + { + size_t totalNumberOfHouses = houseValues.size(); + + if (totalNumberOfHouses == 0) + { + return 0; + } + + if (totalNumberOfHouses == 1) + { + return houseValues[0]; + } + + // Case 1: Exclude last house. + int pickFirstHouse = this->MaxLootDp(0, totalNumberOfHouses - 2, houseValues); + + // Case 2: Exlcude first house. + int pickLastHouse = this->MaxLootDp(1, totalNumberOfHouses - 1, houseValues); + + return max(pickFirstHouse, pickLastHouse); + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0007_decode_ways.cc b/src/0004_dynamic_programming/0007_decode_ways.cc new file mode 100644 index 0000000..bf93270 --- /dev/null +++ b/src/0004_dynamic_programming/0007_decode_ways.cc @@ -0,0 +1,61 @@ +#include "0007_DecodeWays.h" + +namespace DecodeWays +{ + int DynamicProgramming::CountWaysRecursiveHelper(string& digits, size_t index) + { + size_t digitsLength = digits.size(); + + // Base case: If the end of the string is reached, return 1 as it signifies a valid decoding. + if (index >= digitsLength) + { + return 1; + } + + int ways = 0; + + // Single digit decoding: check if current digit is not '0'. + if (digits[index] != '0') + { + ways = this->CountWaysRecursiveHelper(digits, index + 1); + } + + // Two digit decoding: check if next two digits are valid. + if ((index + 1 < digitsLength) && ((digits[index] == '1' && digits[index + 1] <= '9') || (digits[index] == '2' && digits[index + 1] <= '6'))) + { + ways += this->CountWaysRecursiveHelper(digits, index + 2); + } + return ways; + } + + int DynamicProgramming::RecursiveCountWays(string digits) + { + return this->CountWaysRecursiveHelper(digits, 0); + } + + int DynamicProgramming::DpCountways(string digits) + { + size_t digitsLength = digits.size(); + + vector dp(digitsLength + 1, 0); + + dp[digitsLength] = 1; + + for (int index = digitsLength - 1; index >= 0; index--) + { + // Single digit decoding: check if current digit is not '0'. + if (digits[index] != '0') + { + dp[index] = dp[index + 1]; + } + + // Two digit decoding: check if next two digits are valid. + if ((index + 1 < digitsLength) && ((digits[index] == '1' && digits[index + 1] <= '9') || (digits[index] == '2' && digits[index + 1] <= '6'))) + { + dp[index] += dp[index + 2]; + } + } + + return dp[0]; + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0008_tiling_problem.cc b/src/0004_dynamic_programming/0008_tiling_problem.cc new file mode 100644 index 0000000..d447c8d --- /dev/null +++ b/src/0004_dynamic_programming/0008_tiling_problem.cc @@ -0,0 +1,42 @@ +#include "0008_TilingProblem.h" + +namespace TilingProblem +{ + int DynamicProgramming::NumberOfWaysRecursiveHelper(int n) + { + if (n < 0) + { + return 0; + } + + if (n == 0) + { + return 1; + } + + int result = 0; + result += this->NumberOfWaysRecursiveHelper(n - 1); + result += this->NumberOfWaysRecursiveHelper(n - 2); + + return result; + } + + int DynamicProgramming::RecursiveNumberOfWays(int n) + { + return this->NumberOfWaysRecursiveHelper(n); + } + + int DynamicProgramming::DpNumberOfWays(int n) + { + vector dp(n + 1, 0); + dp[0] = 1; + dp[1] = 1; + + for (int i = 2; i <= n; i++) + { + dp[i] = dp[i - 1] + dp[i - 2]; + } + + return dp[n]; + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0009_friends_pairing_problem.cc b/src/0004_dynamic_programming/0009_friends_pairing_problem.cc new file mode 100644 index 0000000..fbea63f --- /dev/null +++ b/src/0004_dynamic_programming/0009_friends_pairing_problem.cc @@ -0,0 +1,39 @@ +#include "0009_FriendsPairingProblem.h" + +namespace FriendsPairingProblem +{ + // Dynamic Programming Private Member Methods. + int DynamicProgramming::CountFriendsPairingsRecursiveHelper(int n) + { + if (n <= 1) + { + return 1; + } + int result = 0; + result += this->CountFriendsPairingsRecursiveHelper(n - 1); + result += (n - 1) * this->CountFriendsPairingsRecursiveHelper(n - 2); + + return result; + } + + // Dynamic Programming Public Member Methods. + int DynamicProgramming::RecursiveCountFriendsPairings(int n) + { + return this->CountFriendsPairingsRecursiveHelper(n); + } + + int DynamicProgramming::DpCountFriendsPairings(int n) + { + vector dp(n + 1, 0); + dp[0] = 0; + dp[1] = 1; + dp[2] = 2; + + for (int i = 3; i <= n; i++) + { + dp[i] = dp[i - 1] + (i - 1) * dp[i - 2]; + } + + return dp[n]; + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0010_ways_to_cover_distance.cc b/src/0004_dynamic_programming/0010_ways_to_cover_distance.cc new file mode 100644 index 0000000..b2f0bce --- /dev/null +++ b/src/0004_dynamic_programming/0010_ways_to_cover_distance.cc @@ -0,0 +1,52 @@ +#include "0010_WaysToCoverDistance.h" + +namespace WaysToCoverDistance +{ + // Dynamic Programming Private Member Methods. + int DynamicProgramming::WaysToCoverDistanceRecursiveHelper(int dist) + { + if (dist < 0) + { + return 0; + } + + if (dist == 0) + { + return 1; + } + + int result = 0; + result += this->WaysToCoverDistanceRecursiveHelper(dist - 1); + result += this->WaysToCoverDistanceRecursiveHelper(dist - 2); + result += this->WaysToCoverDistanceRecursiveHelper(dist - 3); + + return result; + } + + // Dynamic Programming Public Member Methods. + int DynamicProgramming::RecursiveWaysToCoverDistance(int dist) + { + return this->WaysToCoverDistanceRecursiveHelper(dist); + } + + int DynamicProgramming::DpWaysToCoverDistance(int dist) + { + vector dp(dist + 1, 0); + dp[0] = 1; + if (dist >= 1) + { + dp[1] = 1; + } + if (dist >= 2) + { + dp[2] = 2; + } + + for(int i = 3; i <= dist; i++) + { + dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]; + } + + return dp[dist]; + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order.cc b/src/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order.cc new file mode 100644 index 0000000..f4467e2 --- /dev/null +++ b/src/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order.cc @@ -0,0 +1,44 @@ +#include "0011_CountWaysToReachNthStairIncludeOrder.h" + +namespace CountWaysToReachNthStairIncludeOrder +{ + // Dynamic Programming Private Member Methods. + int DynamicProgramming::RecursiveCountWaysToReachNthStairIncludeOrderHelper(int n) + { + if (n < 0) + { + return 0; + } + if (n == 0 || n == 1) + { + return 1; + } + + int result = 0; + result += this->RecursiveCountWaysToReachNthStairIncludeOrderHelper(n - 1); + result += this->RecursiveCountWaysToReachNthStairIncludeOrderHelper(n - 2); + + return result; + } + + // Dynamic Programming Public Member Methods. + int DynamicProgramming::RecursiveCountWaysToReachNthStairIncludeOrder(int n) + { + return this->RecursiveCountWaysToReachNthStairIncludeOrderHelper(n); + } + + int DynamicProgramming::DpCountWaysToReachNthStairIncludeOrder(int n) + { + vector dp(n + 1, 0); + dp[0] = 1; + if (n >= 1) + { + dp[1] = 1; + } + for(int i = 2; i <= n; i++) + { + dp[i] = dp[i - 1] + dp[i - 2]; + } + return dp[n]; + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order.cc b/src/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order.cc new file mode 100644 index 0000000..0e71a69 --- /dev/null +++ b/src/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order.cc @@ -0,0 +1,53 @@ +#include "0012_CountWaysToReachNthStairExcludeOrder.h" + +namespace CountWaysToReachNthStairExcludeOrder +{ + // notes: + /* + To avoid counting ways which only differ in order, we can assume that a person initially takes only steps of size 1 followed by steps of size 2. + In other words, once a person takes a step of size 2, he will continue taking steps of size 2 till he reaches the nth stair. + A person can reach nth stair from either(n - 1)th stair or from(n - 2)th stair.So, there are two cases : + The person has reached nth step from(n - 1)th step, this means that the last step was of size 1 and all the previous steps should also be of size 1. So, there is only 1 way. + The person has reached nth step from(n - 2)th step, this means that the last step was of size 2 and the previous steps can either be of size 1 or size 2. + Therefore the Recurrence relation will be : + + nthStair(n) = 1 (last step was of size 1) + nthStair(n - 2) (last step was of size 2) + so f(n) = 1 + f(n - 2) + */ + + // Dynamic Programming Private Member Methods. + int DynamicProgramming::RecursiveCountWaysToReachNthStairExcludeOrderHelper(int n) + { + if (n < 0) + { + return 0; + } + if (n == 0) + { + return 1; + } + + return 1 + this->RecursiveCountWaysToReachNthStairExcludeOrderHelper(n - 2); + } + + // Dynamic Programming Public Member Methods. + int DynamicProgramming::RecursiveCountWaysToReachNthStairExcludeOrder(int n) + { + return this->RecursiveCountWaysToReachNthStairExcludeOrderHelper(n); + } + + int DynamicProgramming::DpCountWaysToReachNthStairExcludeOrder(int n) + { + vector dp(n + 1, 0); + dp[0] = 1; + if (n >= 1) + { + dp[1] = 1; + } + for (int i = 2; i <= n; i++) + { + dp[i] = 1 + dp[i - 2]; + } + return dp[n]; + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0013_knapsack_problem.cc b/src/0004_dynamic_programming/0013_knapsack_problem.cc new file mode 100644 index 0000000..e9e5ba2 --- /dev/null +++ b/src/0004_dynamic_programming/0013_knapsack_problem.cc @@ -0,0 +1,78 @@ +#include "0013_KnapsackProblem.h" + +namespace KnapsackProblem +{ + // Dynamic Programming Private Member Methods. + int DynamicProgramming::KnapsackRecursiveHelper(int capacity, vector& weight, vector& profit, int numberOfItems) + { + if (capacity <= 0 || numberOfItems == 0) + { + return 0; + } + + int pickCurrentItem = 0; + + // Pick the current item only if does not exceed the capacity. + if (weight[numberOfItems - 1] <= capacity) + { + pickCurrentItem = profit[numberOfItems - 1] + this->KnapsackRecursiveHelper(capacity - weight[numberOfItems - 1], weight, profit, numberOfItems - 1); + } + + int dropCurrentItem = this->KnapsackRecursiveHelper(capacity, weight, profit, numberOfItems - 1); + + return max(pickCurrentItem, dropCurrentItem); + } + + // Dynamic Programming Public Member Methods. + int DynamicProgramming::RecursiveKnapsack(int capacity, vector weight, vector profit) + { + size_t totalNumberOfItems = weight.size(); + return this->KnapsackRecursiveHelper(capacity, weight, profit, totalNumberOfItems); + } + + int DynamicProgramming::DpKnapsack(int capacity, vector weight, vector profit) + { + int numberOfItems = weight.size(); + vector> dp(numberOfItems + 1, vector(capacity + 1, 0)); + + for (int i = 0; i <= numberOfItems; i++) + { + for (int j = 0; j <= capacity; j++) + { + if (i == 0 || j == 0) + { + dp[i][j] = 0; + } + else + { + int pickCurrentItem = 0; + if (weight[i - 1] <= j) + { + pickCurrentItem = profit[i - 1] + dp[i - 1][j - weight[i - 1]]; + } + int dropCurrentItem = dp[i - 1][j]; + + dp[i][j] = max(pickCurrentItem, dropCurrentItem); + } + } + } + + return dp[numberOfItems][capacity]; + } + + int DynamicProgramming::DpKnapsackSpaceOptimized(int capacity, vector weight, vector profit) + { + int numberOfItems = weight.size(); + vector dp(capacity + 1, 0); + + for (int i = 1; i <= numberOfItems; i++) + { + for (int j = capacity; j >= weight[i - 1]; j--) + { + dp[j] = max(dp[j], profit[i - 1] + dp[j - weight[i - 1]]); + } + } + + return dp[capacity]; + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0014_subset_sum_problem.cc b/src/0004_dynamic_programming/0014_subset_sum_problem.cc new file mode 100644 index 0000000..7f558ba --- /dev/null +++ b/src/0004_dynamic_programming/0014_subset_sum_problem.cc @@ -0,0 +1,71 @@ +#include "0014_SubsetSumProblem.h" + +namespace SubsetSumProblem +{ + // Dynamic Programming Private Member Methods. + bool DynamicProgramming::SubsetSumRecursiveHelper(vector& nums, int sum, int numberOfElements) + { + // Base case. + // If the sum is 0, we found a subset with a given sum. + if (sum == 0) + { + return true; + } + + // Base case. + // If there are no elements left to process and the sum is not 0 yet, we did not find a subset with given sum, so return false. + if (numberOfElements == 0) + { + return false; + } + + // When the current element is greater than the sum, we skip it, as all elemeents are non-negative. + if (nums[numberOfElements - 1] > sum) + { + return this->SubsetSumRecursiveHelper(nums, sum, numberOfElements - 1); + } + + // When the current element is equal to or less than the sum, we have two choices. + // 1. Include the current element in the subset and the sum is reduced by the current element value and also the number of elements is reducded by 1. + // 2. Exclude the current element from the subset and the sum remains the same but the number of eleements is reduced by 1. + // If either of these two choices return true, we return true. + return this->SubsetSumRecursiveHelper(nums, sum - nums[numberOfElements - 1], numberOfElements - 1) || this->SubsetSumRecursiveHelper(nums, sum, numberOfElements - 1); + } + + // Dynamic Programming Public Member Methods. + bool DynamicProgramming::RecursiveSubsetSum(vector nums, int sum) + { + int numberOfElements = nums.size(); + return this->SubsetSumRecursiveHelper(nums, sum, numberOfElements); + } + + bool DynamicProgramming::DpIsSubsetSum(vector nums, int sum) + { + int numberOfElements = nums.size(); + vector> dp(numberOfElements + 1, vector(sum + 1, false)); + + // When the sum is 0, the result is true + for (int i = 0; i < numberOfElements; i++) + { + dp[i][0] = true; + } + + for (int i = 1; i < numberOfElements + 1; i++) + { + for (int j = 1; j < sum + 1; j++) + { + if (j < nums[i - 1]) + { + dp[i][j] = dp[i - 1][j]; + } + else + { + // include or exclude the current element + dp[i][j] = (dp[i-1][j-nums[i-1]] || dp[i-1][j]); + } + } + } + + return dp[numberOfElements][sum]; + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0015_count_subsets_for_sum.cc b/src/0004_dynamic_programming/0015_count_subsets_for_sum.cc new file mode 100644 index 0000000..64d75b6 --- /dev/null +++ b/src/0004_dynamic_programming/0015_count_subsets_for_sum.cc @@ -0,0 +1,55 @@ +#include "0015_CountSubsetsForSum.h" + +namespace CountSubsetsForSum +{ + // Dynamic Programming private member methods + int DynamicProgramming::RecursiveCountSubsetsHelper(vector& nums, int targetSum, int currentSum, int index) + { + int noOfElements = nums.size(); + if (index == noOfElements) + { + return (targetSum == currentSum); + } + + int exclude = this->RecursiveCountSubsetsHelper(nums, targetSum, currentSum, index + 1); + int include = 0; + + if ((nums[index] + currentSum) <= targetSum) + { + include = this->RecursiveCountSubsetsHelper(nums, targetSum, currentSum + nums[index], index + 1); + } + + return (exclude + include); + } + + // Dynamic Programming public member methods + int DynamicProgramming::RecursiveCountSubsets(vector nums, int sum) + { + return this->RecursiveCountSubsetsHelper(nums, sum, 0, 0); + } + + int DynamicProgramming::DpCountSubsets(vector nums, int sum) + { + int noOfElements = nums.size(); + vector> dp(noOfElements + 1, vector(sum + 1, 0)); + + dp[0][0] = 1; + + for (int i = 1; i <= noOfElements; i++) + { + for (int j = 0; j <= sum; j++) + { + // Considering excluding the current element + dp[i][j] = dp[i - 1][j]; + + // Case to include the current element + if (nums[i - 1] <= j) + { + dp[i][j] += dp[i - 1][j - nums[i - 1]]; + } + } + } + + return dp[noOfElements][sum]; + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0016_partition_equal_subset_sum.cc b/src/0004_dynamic_programming/0016_partition_equal_subset_sum.cc new file mode 100644 index 0000000..2db0dab --- /dev/null +++ b/src/0004_dynamic_programming/0016_partition_equal_subset_sum.cc @@ -0,0 +1,75 @@ +#include "0016_PartitionEqualSubsetSum.h" + +namespace PartitionEqualSubsetSum +{ + bool DynamicProgramming::RecursivePartitionEqualSubsetsHelper(vector& nums, int targetSum, int numberOfElements) + { + if (targetSum == 0) + { + return true; + } + + if (numberOfElements == 0) + { + return false; + } + + if (nums[numberOfElements - 1] > targetSum) + { + return this->RecursivePartitionEqualSubsetsHelper(nums, targetSum, numberOfElements - 1); + } + + return (this->RecursivePartitionEqualSubsetsHelper(nums, targetSum - nums[numberOfElements - 1], numberOfElements - 1) || this->RecursivePartitionEqualSubsetsHelper(nums, targetSum, numberOfElements - 1)); + } + + bool DynamicProgramming::RecursivePartitionEqualSubsets(vector nums) + { + int targetSum = accumulate(nums.begin(), nums.end(), 0); + + // Check if targetSum is odd, then equal partition is not possible at all + if (targetSum % 2 != 0) + { + return false; + } + + int numberOfElements = nums.size(); + return this->RecursivePartitionEqualSubsetsHelper(nums, targetSum / 2, numberOfElements); + } + + bool DynamicProgramming::DpPartitionEqualSubsets(vector nums) + { + int targetSum = accumulate(nums.begin(), nums.end(), 0); + + // Check if targetSum is odd, then equal partition is not possible at all + if (targetSum % 2 != 0) + { + return false; + } + + int numberOfElements = nums.size(); + targetSum /= 2; + vector> dp(numberOfElements + 1, vector(targetSum + 1, false)); + + for (int i = 0; i <= numberOfElements; i++) + { + dp[i][0] = true; + } + + for (int i = 1; i <= numberOfElements; i++) + { + for (int j = 1; j <= targetSum; j++) + { + if (nums[i - 1] > j) + { + dp[i][j] = dp[i - 1][j]; + } + else + { + dp[i][j] = (dp[i-1][j-nums[i-1]] || dp[i-1][j]); + } + } + } + + return dp[numberOfElements][targetSum]; + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/0017_target_sum.cc b/src/0004_dynamic_programming/0017_target_sum.cc new file mode 100644 index 0000000..c92fe77 --- /dev/null +++ b/src/0004_dynamic_programming/0017_target_sum.cc @@ -0,0 +1,70 @@ +#include "0017_TargetSum.h" + +namespace TargetSum +{ + int DynamicProgramming::RecursiveFindTotalWaysHelper(vector& nums, int currentSum, int targetSum, int index) + { + // Base case + if (currentSum == targetSum && index == nums.size()) + { + return 1; + } + + if (index >= nums.size()) + { + return 0; + } + + // Return total count of two possible ways while considering the current element + // 1. Add the current element to currentSum + // 2. Subtract the current element from currentSum + return ( + this->RecursiveFindTotalWaysHelper(nums, currentSum + nums[index], targetSum, index + 1) + + + this->RecursiveFindTotalWaysHelper(nums, currentSum - nums[index], targetSum, index + 1)); + } + + int DynamicProgramming::RecursiveFindTotalWays(vector nums, int target) + { + return this->RecursiveFindTotalWaysHelper(nums, 0, target, 0); + } + + int DynamicProgramming::DpFindTotalWays(vector nums, int target) + { + int totalSum = accumulate(nums.begin(), nums.end(), 0); + + if (abs(target) > totalSum) + { + return 0; + } + + int totalSumWithTarget = totalSum + target; + if (totalSumWithTarget % 2 != 0) + { + return 0; + } + + int targetSubsetSum = totalSumWithTarget / 2; + int noOfElements = nums.size(); + vector> dp(noOfElements + 1, vector(targetSubsetSum + 1, 0)); + + dp[0][0] = 1; + + for (int i = 1; i <= noOfElements; i++) + { + for (int j = 0; j <= targetSubsetSum; j++) + { + // Considering excluding the current element + dp[i][j] = dp[i - 1][j]; + + // Case to include the current element + if (nums[i - 1] <= j) + { + dp[i][j] += dp[i - 1][j - nums[i - 1]]; + } + } + } + + return dp[noOfElements][targetSubsetSum]; + } +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/CMakeLists.txt b/src/0004_dynamic_programming/CMakeLists.txt new file mode 100644 index 0000000..b063b19 --- /dev/null +++ b/src/0004_dynamic_programming/CMakeLists.txt @@ -0,0 +1,28 @@ +# Specify the source files +set(0005DYNAMICPROGRAMMING_SOURCES + 0001_FibonacciNumber.cc + 0002_TribonacciNumber.cc + 0003_ClimbingStairs.cc + 0004_MinimumCostClimbingStairs.cc + 0005_HouseRobber1.cc + 0006_HouseRobber2.cc + 0007_DecodeWays.cc + 0008_TilingProblem.cc + 0009_FriendsPairingProblem.cc + 0010_WaysToCoverDistance.cc + 0011_CountWaysToReachNthStairIncludeOrder.cc + 0012_CountWaysToReachNthStairExcludeOrder.cc + 0013_KnapsackProblem.cc + 0014_SubsetSumProblem.cc + 0015_CountSubsetsForSum.cc + 0016_PartitionEqualSubsetSum.cc + 0017_TargetSum.cc + +) + +# Create a library target +add_library(0005DYNAMICPROGRAMMING ${0005DYNAMICPROGRAMMING_SOURCES}) + +target_include_directories(0005DYNAMICPROGRAMMING PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}/headers +) \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0001_fibonacci_number.h b/src/0004_dynamic_programming/headers/0001_fibonacci_number.h new file mode 100644 index 0000000..204aeba --- /dev/null +++ b/src/0004_dynamic_programming/headers/0001_fibonacci_number.h @@ -0,0 +1,23 @@ +#pragma once +#include +using namespace std; + +/* +Pattern 1 +Linear Recurrence + +Description +Print the n'th Fibonacci number. + +*/ + +namespace FibonacciNumber +{ + class DynamicProgramming + { + private: + public: + int RecursiveNthFibonacci(int n); + int DpNthFibonacci(int n); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0002_tribonacci_number.h b/src/0004_dynamic_programming/headers/0002_tribonacci_number.h new file mode 100644 index 0000000..31e805f --- /dev/null +++ b/src/0004_dynamic_programming/headers/0002_tribonacci_number.h @@ -0,0 +1,23 @@ +#pragma once +#include +using namespace std; + +/* +Pattern 1 +Linear Recurrence + +Description +Print the n'th Tribonacci number. + +*/ + +namespace TribonacciNumber +{ + class DynamicProgramming + { + private: + public: + int RecursiveNthTribonacci(int n); + int DpNthTribonacci(int n); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0003_climbing_stairs.h b/src/0004_dynamic_programming/headers/0003_climbing_stairs.h new file mode 100644 index 0000000..e32b71a --- /dev/null +++ b/src/0004_dynamic_programming/headers/0003_climbing_stairs.h @@ -0,0 +1,24 @@ +#pragma once +#include +using namespace std; + +/* +Pattern 1 +Linear Recurrence + +Description +There are n stairs, and a person standing at the bottom wants to climb stairs to reach the top. +The person can climb either 1 stair or 2 stairs at a time, the task is to count the number of ways that a person can reach at the top. + +*/ + +namespace ClimbingStairs +{ + class DynamicProgramming + { + private: + public: + int RecursiveCountWays(int n); + int DpCountWays(int n); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0004_minimum_cost_climbing_stairs.h b/src/0004_dynamic_programming/headers/0004_minimum_cost_climbing_stairs.h new file mode 100644 index 0000000..9ef1ec8 --- /dev/null +++ b/src/0004_dynamic_programming/headers/0004_minimum_cost_climbing_stairs.h @@ -0,0 +1,25 @@ +#pragma once +#include +using namespace std; + +/* +Pattern 1 +Linear Recurrence + +Description +Given an array of integers cost[] of length n, where cost[i] is the cost of the ith step on a staircase. Once the cost is paid, we can either climb 1 or 2 steps. +We can either start from the step with index 0, or the step with index 1. The task is to find the minimum cost to reach the top. + +*/ + +namespace MinimumCostClimbingStairs +{ + class DynamicProgramming + { + private: + int MinCostRecursive(size_t step, vector& cost); + public: + int RecursiveMinimumCostClimbingStairs(vector& cost); + int DpMinimumCostClimbingStairs(vector& cost); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0005_house_robber1.h b/src/0004_dynamic_programming/headers/0005_house_robber1.h new file mode 100644 index 0000000..231fbba --- /dev/null +++ b/src/0004_dynamic_programming/headers/0005_house_robber1.h @@ -0,0 +1,25 @@ +#pragma once +#include +using namespace std; + +/* +Pattern 1 +Linear Recurrence + +Description +There are n houses built in a line, each of which contains some money in it. +A robber wants to steal money from these houses, but he can’t steal from two adjacent houses. The task is to find the maximum amount of money which can be stolen. + +*/ + +namespace HouseRobber1 +{ + class DynamicProgramming + { + private: + int MaxLootRecursive(size_t house, vector& houseValues); + public: + int RecursiveMaximumLoot(vector& houseValues); + int DpMaximumLoot(vector& houseValues); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0006_house_robber2.h b/src/0004_dynamic_programming/headers/0006_house_robber2.h new file mode 100644 index 0000000..74c3c93 --- /dev/null +++ b/src/0004_dynamic_programming/headers/0006_house_robber2.h @@ -0,0 +1,28 @@ +#pragma once +#include +using namespace std; + +/* +Pattern 1 +Linear Recurrence + +Description +You are given an array arr[] which represents houses arranged in a circle, where each house has a certain value. A thief aims to maximize the total stolen value without robbing two adjacent houses. +Determine the maximum amount the thief can steal. + +Note: Since the houses are in a circle, the first and last houses are also considered adjacent. + +*/ + +namespace HouseRobber2 +{ + class DynamicProgramming + { + private: + int MaxLootRecursive(size_t house, vector& houseValues); + int MaxLootDp(size_t firstHouse, size_t lastHouse, vector& houseValues); + public: + int RecursiveMaximumLoot(vector& houseValues); + int DpMaximumLoot(vector& houseValues); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0007_decode_ways.h b/src/0004_dynamic_programming/headers/0007_decode_ways.h new file mode 100644 index 0000000..fe2b6ce --- /dev/null +++ b/src/0004_dynamic_programming/headers/0007_decode_ways.h @@ -0,0 +1,32 @@ +#pragma once + +#include +#include +using namespace std; + +/* +Pattern 1 +Linear Recurrence + +Description +Let 1 maps to 'A', 2 maps to 'B', ..., 26 to 'Z'.Given a digit sequence, count the number of possible decodings of the given digit sequence. + +Consider the input string "123".There are three valid ways to decode it : +"ABC" : The grouping is(1, 2, 3) -> 'A', 'B', 'C' +"AW" : The grouping is(1, 23) -> 'A', 'W' +"LC" : The grouping is(12, 3) -> 'L', 'C' +Note : Groupings that contain invalid codes(e.g., "0" by itself or numbers greater than "26") are not allowed. +For instance, the string "230" is invalid because "0" cannot stand alone, and "30" is greater than "26", so it cannot represent any letter.The task is to find the total number of valid ways to decode a given string. +*/ + +namespace DecodeWays +{ + class DynamicProgramming + { + private: + int CountWaysRecursiveHelper(string& digits, size_t index); + public: + int RecursiveCountWays(string digits); + int DpCountways(string digits); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0008_tiling_problem.h b/src/0004_dynamic_programming/headers/0008_tiling_problem.h new file mode 100644 index 0000000..e9befb0 --- /dev/null +++ b/src/0004_dynamic_programming/headers/0008_tiling_problem.h @@ -0,0 +1,25 @@ +#pragma once + +#include +using namespace std; + +/* +Pattern 1 +Linear Recurrence + +Description +Given a "2 x n" board and tiles of size "2 x 1", the task is to count the number of ways to tile the given board using the 2 x 1 tiles. +A tile can either be placed horizontally i.e., as a 1 x 2 tile or vertically i.e., as 2 x 1 tile. +*/ + +namespace TilingProblem +{ + class DynamicProgramming + { + private: + int NumberOfWaysRecursiveHelper(int n); + public: + int RecursiveNumberOfWays(int n); + int DpNumberOfWays(int n); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0009_friends_pairing_problem.h b/src/0004_dynamic_programming/headers/0009_friends_pairing_problem.h new file mode 100644 index 0000000..79cd9da --- /dev/null +++ b/src/0004_dynamic_programming/headers/0009_friends_pairing_problem.h @@ -0,0 +1,46 @@ +#pragma once + +#include +using namespace std; + +/* +Pattern 1 +Linear Recurrence + +Description +Given n friends, each one can remain single or can be paired up with some other friend. Each friend can be paired only once. Find out the total number of ways in which friends can remain single or can be paired up. + +Examples: + +Input : n = 3 +Output : 4 +Explanation: +{1}, {2}, {3} : all single +{1}, {2, 3} : 2 and 3 paired but 1 is single. +{1, 2}, {3} : 1 and 2 are paired but 3 is single. +{1, 3}, {2} : 1 and 3 are paired but 2 is single. +Note that {1, 2} and {2, 1} are considered same. + +Mathematical Explanation: +The problem is simplified version of how many ways we can divide n elements into multiple groups. +(here group size will be max of 2 elements). +In case of n = 3, we have only 2 ways to make a group: + 1) all elements are individual(1,1,1) + 2) a pair and individual (2,1) +In case of n = 4, we have 3 ways to form a group: + 1) all elements are individual (1,1,1,1) + 2) 2 individuals and one pair (2,1,1) + 3) 2 separate pairs (2,2) +*/ + +namespace FriendsPairingProblem +{ + class DynamicProgramming + { + private: + int CountFriendsPairingsRecursiveHelper(int n); + public: + int RecursiveCountFriendsPairings(int n); + int DpCountFriendsPairings(int n); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0010_ways_to_cover_distance.h b/src/0004_dynamic_programming/headers/0010_ways_to_cover_distance.h new file mode 100644 index 0000000..0268ff5 --- /dev/null +++ b/src/0004_dynamic_programming/headers/0010_ways_to_cover_distance.h @@ -0,0 +1,47 @@ +#pragma once + +#include +using namespace std; + +/* +Pattern 1 +Linear Recurrence + +Description +Given a distance 'dist', count total number of ways to cover the distance with 1, 2 and 3 steps. + +Examples: + +Input: n = 3 +Output: 4 +Explanation: Below are the four ways +=> 1 step + 1 step + 1 step +=> 1 step + 2 step +=> 2 step + 1 step +=> 3 step + + + +Input: n = 4 +Output: 7 +Explanation: Below are the four ways +=> 1 step + 1 step + 1 step + 1 step +=> 1 step + 2 step + 1 step +=> 2 step + 1 step + 1 step +=> 1 step + 1 step + 2 step +=> 2 step + 2 step +=> 3 step + 1 step +=> 1 step + 3 step +*/ + +namespace WaysToCoverDistance +{ + class DynamicProgramming + { + private: + int WaysToCoverDistanceRecursiveHelper(int dist); + public: + int RecursiveWaysToCoverDistance(int dist); + int DpWaysToCoverDistance(int dist); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0011_count_ways_to_reach_nth_stair_include_order.h b/src/0004_dynamic_programming/headers/0011_count_ways_to_reach_nth_stair_include_order.h new file mode 100644 index 0000000..6851031 --- /dev/null +++ b/src/0004_dynamic_programming/headers/0011_count_ways_to_reach_nth_stair_include_order.h @@ -0,0 +1,42 @@ +#pragma once + +#include +using namespace std; + +/* +Pattern 1 +Linear Recurrence + +Description +There are n stairs, and a person standing at the bottom wants to climb stairs to reach the top. +The person can climb either 1 stair or 2 stairs at a time, the task is to count the number of ways that a person can reach at the top. + +Note: This problem is similar to Count ways to reach Nth stair (Order does not matter) with the only difference that in this problem, +we count all distinct ways where different orderings of the steps are considered unique. + +Examples: + +Input: n = 1 +Output: 1 +Explanation: There is only one way to climb 1 stair. + +Input: n = 2 +Output: 2 +Explanation: There are two ways to reach 2th stair: {1, 1} and {2}. + +Input: n = 4 +Output: 5 +Explanation: There are five ways to reach 4th stair: {1, 1, 1, 1}, {1, 1, 2}, {2, 1, 1}, {1, 2, 1} and {2, 2}. +*/ + +namespace CountWaysToReachNthStairIncludeOrder +{ + class DynamicProgramming + { + private: + int RecursiveCountWaysToReachNthStairIncludeOrderHelper(int n); + public: + int RecursiveCountWaysToReachNthStairIncludeOrder(int n); + int DpCountWaysToReachNthStairIncludeOrder(int n); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0012_count_ways_to_reach_nth_stair_exclude_order.h b/src/0004_dynamic_programming/headers/0012_count_ways_to_reach_nth_stair_exclude_order.h new file mode 100644 index 0000000..4d52930 --- /dev/null +++ b/src/0004_dynamic_programming/headers/0012_count_ways_to_reach_nth_stair_exclude_order.h @@ -0,0 +1,44 @@ +#pragma once + +#include +using namespace std; + +/* +Pattern 1 +Linear Recurrence + +Description +There are n stairs, and a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top (order does not matter). + +Note: The problem is similar to Climbing Stairs - Count ways to reach Nth stair with the only difference that in this problem, we don't have to count those ways which only differ in ordering of the steps. + +Examples: + +Input: n = 1 +Output: 1 +Explanation: There is only one way to climb 1 stair. + +Input: n = 2 +Output: 2 +Explanation: There are two ways to climb 2 stairs: {1, 1} and {2}. + +Input: n = 4 +Output: 3 +Explanation: Three ways to reach 4th stair: {1, 1, 1, 1}, {1, 1, 2} and {2, 2}. + +Input: n = 5 +Output: 3 +Explanation: Three ways to reach 5th stair: {1, 1, 1, 1, 1}, {1, 1, 1, 2} and {1, 2, 2}. +*/ + +namespace CountWaysToReachNthStairExcludeOrder +{ + class DynamicProgramming + { + private: + int RecursiveCountWaysToReachNthStairExcludeOrderHelper(int n); + public: + int RecursiveCountWaysToReachNthStairExcludeOrder(int n); + int DpCountWaysToReachNthStairExcludeOrder(int n); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0013_knapsack_problem.h b/src/0004_dynamic_programming/headers/0013_knapsack_problem.h new file mode 100644 index 0000000..b7c90aa --- /dev/null +++ b/src/0004_dynamic_programming/headers/0013_knapsack_problem.h @@ -0,0 +1,34 @@ +#pragma once + +#include +using namespace std; + +/* +Pattern 2 +Subset / 0-1 Knapsack + +Description +Given n items where each item has some weight and profit associated with it and also given a bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items into the bag such that the sum of profits associated with them is the maximum possible. + +Note: The constraint here is we can either put an item completely into the bag or cannot put it at all [It is not possible to put a part of an item into the bag]. + +Input: W = 4, profit[] = [1, 2, 3], weight[] = [4, 5, 1] +Output: 3 +Explanation: There are two items which have weight less than or equal to 4. If we select the item with weight 4, the possible profit is 1. And if we select the item with weight 1, the possible profit is 3. So the maximum possible profit is 3. Note that we cannot put both the items with weight 4 and 1 together as the capacity of the bag is 4. + +Input: W = 3, profit[] = [1, 2, 3], weight[] = [4, 5, 6] +Output: 0 +*/ + +namespace KnapsackProblem +{ + class DynamicProgramming + { + private: + int KnapsackRecursiveHelper(int capacity, vector& weight, vector& profit, int numberOfItems); + public: + int RecursiveKnapsack(int capacity, vector weight, vector profit); + int DpKnapsack(int capacity, vector weight, vector profit); + int DpKnapsackSpaceOptimized(int capacity, vector weight, vector profit); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0014_subset_sum_problem.h b/src/0004_dynamic_programming/headers/0014_subset_sum_problem.h new file mode 100644 index 0000000..399d328 --- /dev/null +++ b/src/0004_dynamic_programming/headers/0014_subset_sum_problem.h @@ -0,0 +1,34 @@ +#pragma once + +#include +using namespace std; + +/* +Pattern 2 +Subset / 0-1 Knapsack + +Description +Given an array arr[] of non-negative integers and a value sum, the task is to check if there is a subset of the given array whose sum is equal to the given sum. + +Examples: + +Input: arr[] = [3, 34, 4, 12, 5, 2], sum = 9 +Output: True +Explanation: There is a subset (4, 5) with sum 9. + +Input: arr[] = [3, 34, 4, 12, 5, 2], sum = 30 +Output: False +Explanation: There is no subset that add up to 30. +*/ + +namespace SubsetSumProblem +{ + class DynamicProgramming + { + private: + bool SubsetSumRecursiveHelper(vector& nums, int sum, int numberOfElements); + public: + bool RecursiveSubsetSum(vector nums, int sum); + bool DpIsSubsetSum(vector nums, int sum); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0015_count_subsets_for_sum.h b/src/0004_dynamic_programming/headers/0015_count_subsets_for_sum.h new file mode 100644 index 0000000..4f55bbf --- /dev/null +++ b/src/0004_dynamic_programming/headers/0015_count_subsets_for_sum.h @@ -0,0 +1,34 @@ +#pragma once + +#include +using namespace std; + +/* +Pattern 2 +Subset / 0-1 Knapsack + +Description +Given an array arr[] of length n and an integer target, the task is to find the number of subsets with a sum equal to target. + +Examples: + +Input: arr[] = [1, 2, 3, 3], target = 6 +Output: 3 +Explanation: All the possible subsets are [1, 2, 3], [1, 2, 3] and [3, 3] + +Input: arr[] = [1, 1, 1, 1], target = 1 +Output: 4 +Explanation: All the possible subsets are [1], [1], [1] and [1] +*/ + +namespace CountSubsetsForSum +{ + class DynamicProgramming + { + private: + int RecursiveCountSubsetsHelper(vector& nums, int targetSum, int currentSum, int index); + public: + int RecursiveCountSubsets(vector nums, int sum); + int DpCountSubsets(vector nums, int sum); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0016_partition_equal_subset_sum.h b/src/0004_dynamic_programming/headers/0016_partition_equal_subset_sum.h new file mode 100644 index 0000000..bf3c261 --- /dev/null +++ b/src/0004_dynamic_programming/headers/0016_partition_equal_subset_sum.h @@ -0,0 +1,36 @@ +#pragma once + +#include +#include +using namespace std; + +/* +Pattern 2 +Subset / 0-1 Knapsack + +Description +Given an array arr[], check if it can be partitioned into two parts such that the sum of elements in both parts is the same. +Note: Each element is present in either the first subset or the second subset, but not in both. + +Examples: + +Input: arr[] = [1, 5, 11, 5] +Output: true +Explanation: The array can be partitioned as [1, 5, 5] and [11] and the sum of both the subsets are equal. + +Input: arr[] = [1, 5, 3] +Output: false +Explanation: The array cannot be partitioned into equal sum sets. +*/ + +namespace PartitionEqualSubsetSum +{ + class DynamicProgramming + { + private: + bool RecursivePartitionEqualSubsetsHelper(vector& nums, int targetSum, int numberOfElements); + public: + bool RecursivePartitionEqualSubsets(vector nums); + bool DpPartitionEqualSubsets(vector nums); + }; +} \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0017_target_sum.h b/src/0004_dynamic_programming/headers/0017_target_sum.h new file mode 100644 index 0000000..1ee27ad --- /dev/null +++ b/src/0004_dynamic_programming/headers/0017_target_sum.h @@ -0,0 +1,45 @@ +#pragma once + +#include +#include +using namespace std; + +/* +Pattern 2 +Subset / 0-1 Knapsack + +Description +Given an array arr[] of length N and an integer target. +You want to build an expression out of arr[] by adding one of the symbols '+' and '-' before each integer in arr[] and then concatenate all the integers. +Return the number of different expressions that can be built, which evaluates to target. + +Example: + +Input : N = 5, arr[] = {1, 1, 1, 1, 1}, target = 3 +Output: 5 +Explanation: +There are 5 ways to assign symbols to +make the sum of array be target 3. + +-1 + 1 + 1 + 1 + 1 = 3 ++1 - 1 + 1 + 1 + 1 = 3 ++1 + 1 - 1 + 1 + 1 = 3 ++1 + 1 + 1 - 1 + 1 = 3 ++1 + 1 + 1 + 1 - 1 = 3 + +Input: N = 1, arr[] = {1}, target = 1 +Output: 1 +*/ + +namespace TargetSum +{ + class DynamicProgramming + { + private: + int RecursiveFindTotalWaysHelper(vector& nums, int currentSum, int targetSum, int index); + int DpFindTotalWays(); + public: + int RecursiveFindTotalWays(vector nums, int target); + int DpFindTotalWays(vector nums, int target); + }; +} \ No newline at end of file diff --git a/src/0005_greedy_algorithms/CMakeLists.txt b/src/0005_greedy_algorithms/CMakeLists.txt new file mode 100644 index 0000000..e69de29 diff --git a/src/0006_bitwise_algorithms/CMakeLists.txt b/src/0006_bitwise_algorithms/CMakeLists.txt new file mode 100644 index 0000000..e69de29 diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt new file mode 100644 index 0000000..708289d --- /dev/null +++ b/src/CMakeLists.txt @@ -0,0 +1,6 @@ +add_subdirectory(0001_basics) +add_subdirectory(0002_tree) +add_subdirectory(0003_graph) +add_subdirectory(0004_dynamic_programming) +add_subdirectory(0005_greedy_algorithms) +add_subdirectory(0006_bitwise_algorithms) \ No newline at end of file diff --git a/tests/0000_common_utilities/CMakeLists.txt b/tests/0000_common_utilities/CMakeLists.txt new file mode 100644 index 0000000..e69de29 diff --git a/tests/0000_common_utilities/unit_test_helper.h b/tests/0000_common_utilities/unit_test_helper.h new file mode 100644 index 0000000..ff676bd --- /dev/null +++ b/tests/0000_common_utilities/unit_test_helper.h @@ -0,0 +1,183 @@ +#pragma once + +#include +#include +#include +#include +using namespace std; + +class UnitTestHelper +{ +public: + template + string SerializeVectorToString(vector vector) + { + string result = ""; + for (auto& iterator : vector) + { + result += to_string(iterator) + " "; + } + result.pop_back(); + return result; + } + + template + string SerializeVectorToString(vector> vector) + { + string result = ""; + for (auto& iterator : vector) + { + result += to_string(iterator.first) + "(" + to_string(iterator.second) + ")" + " "; + } + + if (!result.empty()) + { + result.pop_back(); + } + return result; + } + + template + string SerializeVectorToString(vector>> vector) + { + string result = ""; + for (auto& iterator : vector) + { + result += to_string(iterator.first) + "(" + to_string(iterator.second.first) + "," + to_string(iterator.second.second) + ")" + " "; + } + + if (!result.empty()) + { + result.pop_back(); + } + return result; + } + + template + string SerializeVectorToString(vector> vector) + { + string result = ""; + for (auto& iterator : vector) + { + result += "["; + for (auto& it : iterator) + { + result += to_string(it) + " "; + } + if (!result.empty()) + { + result.pop_back(); + } + result += "]"; + } + return result; + } + + // This helper method is used to sort the vector of vectors of a particular typename. + // Each inner vector is sorted first. + // Then each of them are sorted by their first element, in increasing order. + template + vector> SortVectorOfVectors(vector> data) + { + // Step 1: Sorting each inner vectors. + for (auto& innerVector : data) + { + sort(innerVector.begin(), innerVector.end()); + } + + // Step 2: Sorting all the vectors by their first element, in increasing order. + sort(data.begin(), data.end(), [](const vector& a, const vector& b) + { + // Checking if both inner vectors are empty to prevent out-of-bounds access. + if (a.empty() && b.empty()) + return false; + + // Considering empty vector as less than non-empty vector. + if (a.empty()) + return true; + + // Considering non-empty vector as greater than empty vector. + if (b.empty()) + return false; + + // Comparing the first elements of each vector. + return (a[0] < b[0]); + }); + + return data; + } + + template + bool NormalizeCyclesAndCompare(vector data1, vector data2) + { + if (data1.size() != data2.size()) + { + return false; + } + + // Normalized rotation of cycle 1 + vector normalizedCycle1(data1); + auto minIterator1 = min_element(normalizedCycle1.begin(), normalizedCycle1.end()); + rotate(normalizedCycle1.begin(), minIterator1, normalizedCycle1.end()); + + // Normalized rotation of cycle 2 + vector normalizedCycle2(data2); + auto minIterator2 = min_element(normalizedCycle2.begin(), normalizedCycle2.end()); + rotate(normalizedCycle2.begin(), minIterator2, normalizedCycle2.end()); + + // Check clock wise + if (normalizedCycle1 == normalizedCycle2) + { + return true; + } + + // Check counter clock wise + reverse(normalizedCycle2.begin() + 1, normalizedCycle2.end()); + return (normalizedCycle1 == normalizedCycle2); + } + + template + vector, T>> SortVectorOfPair(vector, T>> data) + { + for (auto& iterator : data) + { + if (iterator.first.first > iterator.first.second) + { + swap(iterator.first.first, iterator.first.second); + } + } + + sort(data.begin(), data.end(), [](const pair, T>& pairA, const pair, T>& pairB) + { + if (pairA.second == pairB.second) + { + return pairA.first.first < pairB.first.first; + } + return pairA.second < pairB.second; + }); + return data; + } + + template + string SortVectorOfPairAndSerialize(vector> data) + { + // Sorting the vector in non-decreasing order on typename T1 + sort(data.begin(), data.end(), [](const pair& pair1, const pair& pair2) + { + return pair1.first < pair2.first; + }); + + // Serializing the vector to string + string result = ""; + for (auto& iterator : data) + { + result += iterator.first + "(" + to_string(iterator.second) + ")" + " "; + } + + if (!result.empty()) + { + result.pop_back(); + } + return result; + } +}; \ No newline at end of file diff --git a/tests/0001_basics/CMakeLists.txt b/tests/0001_basics/CMakeLists.txt new file mode 100644 index 0000000..efa1008 --- /dev/null +++ b/tests/0001_basics/CMakeLists.txt @@ -0,0 +1,31 @@ +cmake_policy(SET CMP0135 NEW) + +include(FetchContent) +FetchContent_Declare( + googletest + URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip +) +# For Windows: Prevent overriding the parent project's compiler/linker settings +set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) +FetchContent_MakeAvailable(googletest) + + +enable_testing() + +add_executable( + 0001BasicsTests + NodeTest.cc) + +target_link_libraries( + 0001BasicsTests + GTest::gtest_main + 0001BASICS +) + +# Add .clang-tidy configuration to this library. +if(CLANG_TIDY_EXE) + set_target_properties(0001BASICS PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") +endif() + +include(GoogleTest) +gtest_discover_tests(0001BasicsTests DISCOVERY_TIMEOUT 30) \ No newline at end of file diff --git a/tests/0001_basics/node_test.cc b/tests/0001_basics/node_test.cc new file mode 100644 index 0000000..ca38297 --- /dev/null +++ b/tests/0001_basics/node_test.cc @@ -0,0 +1,12 @@ +#include +#include "Node.h" + +// Demonstrate some basic assertions. +namespace NodeTesting +{ + TEST(TestingNodeValue, PositiveTestCase) + { + // Expect two strings not to be equal. + EXPECT_EQ(2 * 4, 8); + } +} \ No newline at end of file diff --git a/tests/0002_tree/0001_binary_search_tree_test.cc b/tests/0002_tree/0001_binary_search_tree_test.cc new file mode 100644 index 0000000..0c8aab0 --- /dev/null +++ b/tests/0002_tree/0001_binary_search_tree_test.cc @@ -0,0 +1,91 @@ +#include +#include +#include "0001_BinarySearchTree.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace BinarySearchTree +{ + UnitTestHelper unitTestHelper; + + TEST(BSTInsertData, RecursiveInorderTest) + { + BinarySearchTree bst; + bst.insertNode(50); + bst.insertNode(30); + bst.insertNode(60); + + + string actualResult = unitTestHelper.SerializeVectorToString(bst.recursiveInorderTraversal()); + string expectedResult = "30 50 60"; + + EXPECT_EQ(actualResult, expectedResult); + } + + TEST(BSTInsertData, RecursivePreorderTest) + { + BinarySearchTree bst; + bst.insertNode(50); + bst.insertNode(30); + bst.insertNode(60); + + string actualResult = unitTestHelper.SerializeVectorToString(bst.recursivePreorderTravesal()); + string expectedResult = "50 30 60"; + + EXPECT_EQ(actualResult, expectedResult); + } + + TEST(BSTInsertData, RecursivePostorderTest) + { + BinarySearchTree bst; + bst.insertNode(50); + bst.insertNode(30); + bst.insertNode(60); + + string actualResult = unitTestHelper.SerializeVectorToString(bst.recursivePostorderTravesal()); + string expectedResult = "30 60 50"; + + EXPECT_EQ(actualResult, expectedResult); + } + + TEST(BSTInsertData, MorrisInorderTest) + { + BinarySearchTree bst; + bst.insertNode(50); + bst.insertNode(30); + bst.insertNode(60); + + + string actualResult = unitTestHelper.SerializeVectorToString(bst.morrisInorderTraversal()); + string expectedResult = "30 50 60"; + + EXPECT_EQ(actualResult, expectedResult); + } + + TEST(BSTInsertData, MorrisPreorderTest) + { + BinarySearchTree bst; + bst.insertNode(50); + bst.insertNode(30); + bst.insertNode(60); + + + string actualResult = unitTestHelper.SerializeVectorToString(bst.morrisPreorderTraversal()); + string expectedResult = "50 30 60"; + + EXPECT_EQ(actualResult, expectedResult); + } + + TEST(BSTInsertData, MorrisPostorderTest) + { + BinarySearchTree bst; + bst.insertNode(50); + bst.insertNode(30); + bst.insertNode(60); + + + string actualResult = unitTestHelper.SerializeVectorToString(bst.morrisPostorderTraversal()); + string expectedResult = "30 60 50"; + + EXPECT_EQ(actualResult, expectedResult); + } +} \ No newline at end of file diff --git a/tests/0002_tree/CMakeLists.txt b/tests/0002_tree/CMakeLists.txt new file mode 100644 index 0000000..a10743b --- /dev/null +++ b/tests/0002_tree/CMakeLists.txt @@ -0,0 +1,32 @@ +cmake_policy(SET CMP0135 NEW) + +include(FetchContent) +FetchContent_Declare( + googletest + URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip +) + +# For Windows: Prevent overriding the parent project's compiler/linker settings +set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) +FetchContent_MakeAvailable(googletest) + +enable_testing() + +add_executable( + 0002_TreeTests + 0001_BinarySearchTreeTest.cc +) + +target_link_libraries( + 0002_TreeTests + GTest::gtest_main + 0002_Tree +) + +# Add .clang-tidy configuration to this library. +if(CLANG_TIDY_EXE) + set_target_properties(0002_Tree PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") +endif() + +include(GoogleTest) +gtest_discover_tests(0002_TreeTests DISCOVERY_TIMEOUT 30) \ No newline at end of file diff --git a/tests/0003_graph/0001_breadth_first_search_test.cc b/tests/0003_graph/0001_breadth_first_search_test.cc new file mode 100644 index 0000000..c0beb81 --- /dev/null +++ b/tests/0003_graph/0001_breadth_first_search_test.cc @@ -0,0 +1,45 @@ +#include +#include +#include "../../src/0003_graph/headers/0001_BreadthFirstSearch.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace BreadthFirstSearch +{ + UnitTestHelper unitTestHelper; + + + TEST(BFSTesting, ShowBFSResultTest01) + { + Graph graph; + + graph.PushUndirectedEdge(1, 2); + graph.PushUndirectedEdge(1, 3); + graph.PushUndirectedEdge(2, 4); + graph.PushUndirectedEdge(3, 5); + graph.PushUndirectedEdge(3, 6); + graph.PushUndirectedEdge(5, 6); + graph.PushUndirectedEdge(5, 7); + graph.PushUndirectedEdge(6, 7); + graph.PushUndirectedEdge(6, 8); + graph.PushUndirectedEdge(7, 8); + + graph.BFS(1); + + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowBFSResult()); + string expectedResult = "1(0) 2(1) 3(1) 4(2) 5(2) 6(2) 7(3) 8(3)"; + EXPECT_EQ(actualResult, expectedResult); + } + + TEST(BFSTesting, ShowBFSResultTest02) + { + Graph graph; + + graph.PushUndirectedEdge(1, 2); + + graph.BFS(1); + + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowBFSResult()); + string expectedResult = "1(0) 2(1)"; + EXPECT_EQ(actualResult, expectedResult); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0002_depth_first_search_test.cc b/tests/0003_graph/0002_depth_first_search_test.cc new file mode 100644 index 0000000..c96c55e --- /dev/null +++ b/tests/0003_graph/0002_depth_first_search_test.cc @@ -0,0 +1,177 @@ +#include +#include "0002_DepthFirstSearch.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace DepthFirstSearch +{ + UnitTestHelper unitTestHelper; + + TEST(DFSTesting, ShowDFSResultTest01) + { + Graph graph; + + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(1, 4); + graph.PushDirectedEdge(2, 5); + graph.PushDirectedEdge(3, 5); + graph.PushDirectedEdge(3, 6); + graph.PushDirectedEdge(4, 2); + graph.PushDirectedEdge(5, 4); + graph.PushDirectedEdge(6, 6); + + graph.DFS(); + + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); + string expectedResult = "1(1,8) 2(2,7) 3(9,12) 4(4,5) 5(3,6) 6(10,11)"; + EXPECT_EQ(actualResult, expectedResult); + } + + + TEST(DFSTesting, ShowDFSResultTest_SingleVertex) + { + Graph graph; + + graph.PushDirectedEdge(1, 1); + + graph.DFS(); + + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); + string expectedResult = "1(1,2)"; + EXPECT_EQ(actualResult, expectedResult); + } + + TEST(DFSTesting, ShowDFSResultTest_DisconnectedGraph) + { + Graph graph; + + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(3, 4); + + graph.DFS(); + + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); + string expectedResult = "1(1,4) 2(2,3) 3(5,8) 4(6,7)"; + EXPECT_EQ(actualResult, expectedResult); + } + + TEST(DFSTesting, ShowDFSResultTest_CyclicGraph) + { + Graph graph; + + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(2, 3); + graph.PushDirectedEdge(3, 1); + + graph.DFS(); + + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); + string expectedResult = "1(1,6) 2(2,5) 3(3,4)"; + EXPECT_EQ(actualResult, expectedResult); + } + + TEST(DFSTesting, ShowDFSResultTest_LargeGraph) + { + Graph graph; + + // Adding 15 nodes with several edges + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(1, 3); + graph.PushDirectedEdge(2, 4); + graph.PushDirectedEdge(4, 5); + graph.PushDirectedEdge(5, 6); + graph.PushDirectedEdge(6, 7); + graph.PushDirectedEdge(7, 8); + graph.PushDirectedEdge(8, 9); + graph.PushDirectedEdge(9, 10); + graph.PushDirectedEdge(10, 11); + graph.PushDirectedEdge(11, 12); + graph.PushDirectedEdge(12, 13); + graph.PushDirectedEdge(13, 14); + graph.PushDirectedEdge(14, 15); + graph.PushDirectedEdge(15, 16); + + graph.DFS(); + + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); + string expectedResult = "1(1,32) 2(2,29) 3(30,31) 4(3,28) 5(4,27) 6(5,26) 7(6,25) 8(7,24) 9(8,23) 10(9,22) 11(10,21) 12(11,20) 13(12,19) 14(13,18) 15(14,17) 16(15,16)"; + EXPECT_EQ(actualResult, expectedResult); + } + + TEST(DFSTesting, ShowDFSResultTest_NoEdges) + { + Graph graph; + + // Adding isolated nodes + graph.PushDirectedEdge(1, 1); + graph.PushDirectedEdge(2, 2); + graph.PushDirectedEdge(3, 3); + + graph.DFS(); + + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); + string expectedResult = "1(1,2) 2(3,4) 3(5,6)"; + EXPECT_EQ(actualResult, expectedResult); + } + + TEST(DFSTesting, ShowDFSResultTest_CyclicGraphWithBackEdges) + { + Graph graph; + + // Creating a cycle with back edges + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(2, 3); + graph.PushDirectedEdge(3, 1); // Cycle back to 'a' + graph.PushDirectedEdge(2, 4); // Back edge + + graph.DFS(); + + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); + string expectedResult = "1(1,8) 2(2,7) 3(3,4) 4(5,6)"; + EXPECT_EQ(actualResult, expectedResult); + } + + TEST(DFSTesting, ShowDFSResultTest_DenseGraph) + { + Graph graph; + + // Complete graph of 4 nodes + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(1, 3); + graph.PushDirectedEdge(1, 4); + graph.PushDirectedEdge(2, 1); + graph.PushDirectedEdge(2, 3); + graph.PushDirectedEdge(2, 4); + graph.PushDirectedEdge(3, 1); + graph.PushDirectedEdge(3, 2); + graph.PushDirectedEdge(3, 4); + graph.PushDirectedEdge(4, 1); + graph.PushDirectedEdge(4, 2); + graph.PushDirectedEdge(4, 3); + + graph.DFS(); + + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); + string expectedResult = "1(1,8) 2(2,7) 3(3,6) 4(4,5)"; + EXPECT_EQ(actualResult, expectedResult); + } + + TEST(DFSTesting, ShowDFSResultTest_SelfLoopsAndParallelEdges) + { + Graph graph; + + // Adding self-loops and parallel edges + graph.PushDirectedEdge(1, 1); + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(2, 2); + graph.PushDirectedEdge(2, 3); + graph.PushDirectedEdge(2, 3); // Parallel edge + graph.PushDirectedEdge(3, 3); // Self-loop + + graph.DFS(); + + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); + string expectedResult = "1(1,6) 2(2,5) 3(3,4)"; + EXPECT_EQ(actualResult, expectedResult); + } + +} \ No newline at end of file diff --git a/tests/0003_graph/0003_topological_sort_test.cc b/tests/0003_graph/0003_topological_sort_test.cc new file mode 100644 index 0000000..6ad277e --- /dev/null +++ b/tests/0003_graph/0003_topological_sort_test.cc @@ -0,0 +1,116 @@ +#include +#include "0003_TopologicalSort.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace TopologicalSort +{ + UnitTestHelper unitTestHelper; + + TEST(TopoSortTesting, ShowTopoSortResult) + { + Graph graph; + + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(1, 4); + graph.PushDirectedEdge(2, 3); + graph.PushDirectedEdge(4, 3); + graph.PushSingleNode(5); + graph.PushDirectedEdge(6, 7); + graph.PushDirectedEdge(6, 8); + graph.PushDirectedEdge(7, 4); + graph.PushDirectedEdge(7, 8); + graph.PushDirectedEdge(9, 8); + + graph.TopologicalSort(); + + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); + string expectedResult = "9(17,18) 6(11,16) 7(12,15) 8(13,14) 5(9,10) 1(1,8) 4(6,7) 2(2,5) 3(3,4)"; + + EXPECT_EQ(actualResult, expectedResult); + } + + // Test with a larger graph and multiple paths between nodes + TEST(TopoSortTesting, LargeGraphMultiplePaths) + { + Graph graph; + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(1, 3); + graph.PushDirectedEdge(2, 4); + graph.PushDirectedEdge(3, 4); + graph.PushDirectedEdge(4, 5); + graph.PushDirectedEdge(5, 6); + graph.PushDirectedEdge(6, 7); + + graph.TopologicalSort(); + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); + string expectedResult = "1(1,14) 3(12,13) 2(2,11) 4(3,10) 5(4,9) 6(5,8) 7(6,7)"; + + EXPECT_EQ(actualResult, expectedResult); + } + + // Test with a graph containing disconnected components + TEST(TopoSortTesting, DisconnectedGraph) + { + Graph graph; + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(3, 4); + graph.PushDirectedEdge(5, 6); + + graph.TopologicalSort(); + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); + string expectedResult = "5(9,12) 6(10,11) 3(5,8) 4(6,7) 1(1,4) 2(2,3)"; + + EXPECT_EQ(actualResult, expectedResult); + } + + // Test with a graph that has multiple nodes pointing to the same node + TEST(TopoSortTesting, MultipleIncomingEdges) + { + Graph graph; + graph.PushDirectedEdge(1, 3); + graph.PushDirectedEdge(2, 3); + graph.PushDirectedEdge(3, 4); + + graph.TopologicalSort(); + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); + string expectedResult = "2(7,8) 1(1,6) 3(2,5) 4(3,4)"; + + EXPECT_EQ(actualResult, expectedResult); + } + + // Test for a single-node graph to check the base case + TEST(TopoSortTesting, SingleNodeGraph) + { + Graph graph; + graph.PushSingleNode(1); + + graph.TopologicalSort(); + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); + string expectedResult = "1(1,2)"; + + EXPECT_EQ(actualResult, expectedResult); + } + + TEST(TopoSortTesting, ShowTopoSortResultUsingKahnAlgorithm) + { + Graph graph; + + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(1, 4); + graph.PushDirectedEdge(2, 3); + graph.PushDirectedEdge(4, 3); + graph.PushSingleNode(5); + graph.PushDirectedEdge(6, 7); + graph.PushDirectedEdge(6, 8); + graph.PushDirectedEdge(7, 4); + graph.PushDirectedEdge(7, 8); + graph.PushDirectedEdge(9, 8); + + graph.KahnTopologicalSort(); + + string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); + string expectedResult = "1(1,5) 5(2,7) 6(3,8) 9(4,10) 2(6,11) 7(9,12) 4(13,15) 8(14,17) 3(16,18)"; + + EXPECT_EQ(actualResult, expectedResult); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0004_strongly_connected_components_test.cc b/tests/0003_graph/0004_strongly_connected_components_test.cc new file mode 100644 index 0000000..f8ede7f --- /dev/null +++ b/tests/0003_graph/0004_strongly_connected_components_test.cc @@ -0,0 +1,102 @@ +#include +#include "0004_StronglyConnectedComponents.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace StronglyConnectedComponents +{ + UnitTestHelper unitTestHelper; + + // Test case: Testing with a simple graph. + TEST(StronglyConnectedComponentsTesting, SimpleGraphTest) + { + Graph graph; + + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(1, 5); + graph.PushDirectedEdge(2, 3); + graph.PushDirectedEdge(2, 4); + graph.PushDirectedEdge(3, 2); + graph.PushDirectedEdge(4, 4); + graph.PushDirectedEdge(5, 1); + graph.PushDirectedEdge(5, 4); + graph.PushDirectedEdge(6, 1); + graph.PushDirectedEdge(6, 3); + graph.PushDirectedEdge(6, 7); + graph.PushDirectedEdge(7, 3); + graph.PushDirectedEdge(7, 8); + graph.PushDirectedEdge(8, 6); + + auto actualResult = graph.FindAllStronglyConnectedComponents(); + vector> expectedResult = { {6, 8, 7},{1, 5},{2, 3},{4} }; + EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); + } + + // Test case: Single Node. + TEST(StronglyConnectedComponentsTesting, SingleNodeTest) + { + Graph graph; + graph.PushSingleNode(1); + + auto actualResult = graph.FindAllStronglyConnectedComponents(); + vector> expectedResult = { {1} }; + EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); + } + + // Test case: Disconnected Graph. + TEST(StronglyConnectedComponentsTesting, DisconnectedGraphTest) + { + Graph graph; + graph.PushSingleNode(1); + graph.PushSingleNode(2); + graph.PushSingleNode(3); + + auto actualResult = graph.FindAllStronglyConnectedComponents(); + vector> expectedResult = { {1},{3},{2} }; + EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); + } + + // Test case: Chain of Nodes. + TEST(StronglyConnectedComponentsTesting, ChainOfNodesTest) + { + Graph graph; + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(2, 3); + graph.PushDirectedEdge(3, 4); + + auto actualResult = graph.FindAllStronglyConnectedComponents(); + vector> expectedResult = { {2},{1},{3},{4} }; + EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); + } + + // Test case: Bidirectional Edge. + TEST(StronglyConnectedComponentsTesting, BidirectionalEdgeTest) + { + Graph graph; + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(2, 1); + + auto actualResult = graph.FindAllStronglyConnectedComponents(); + vector> expectedResult = { {2, 1} }; + EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); + } + + // Test case: Complex Graph. + TEST(StronglyConnectedComponentsTesting, ComplexGraphTest) + { + Graph graph; + + // Graph structure with multiple SCCs and isolated nodes. + graph.PushDirectedEdge(1, 2); + graph.PushDirectedEdge(2, 3); + graph.PushDirectedEdge(3, 1); // Cycle: 1 -> 2 -> 3 -> 1 + graph.PushDirectedEdge(4, 5); + graph.PushDirectedEdge(5, 6); + graph.PushDirectedEdge(6, 4); // Cycle: 4 -> 5 -> 6 -> 4 + graph.PushDirectedEdge(7, 8); // Single direction: 7 -> 8 + graph.PushSingleNode(9); // Isolated node. + + auto actualResult = graph.FindAllStronglyConnectedComponents(); + vector> expectedResult = { {4, 6, 5},{7}, { 2, 3, 1},{8}, {9} }; + EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0005_hamiltonian_path_and_cycle_test.cc b/tests/0003_graph/0005_hamiltonian_path_and_cycle_test.cc new file mode 100644 index 0000000..33c351e --- /dev/null +++ b/tests/0003_graph/0005_hamiltonian_path_and_cycle_test.cc @@ -0,0 +1,33 @@ +#include +#include "0005_HamiltonianPathAndCycle.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace HamiltonianPathAndCycle +{ + UnitTestHelper unitTestHelper; + + TEST(HamiltonianCycleAndPathTest, ShowResult) + { + Graph graph; + + graph.PushUndirectedEdge(0, 1); + graph.PushUndirectedEdge(0, 3); + graph.PushUndirectedEdge(1, 2); + graph.PushUndirectedEdge(1, 3); + graph.PushUndirectedEdge(1, 4); + graph.PushUndirectedEdge(2, 4); + graph.PushUndirectedEdge(3, 4); + + graph.FindHamiltonianCycleAndPath(); + + bool isHamiltonianCyclePresent = graph.IsHamiltonianCyclePresent(); + bool isHamiltonianPathPresent = graph.IsHamiltonianPathPresent(); + + vector hamiltonianPathActualResult = graph.GetHamiltonianPath(); + vector hamiltonianPathExpectedResult = { 4, 3, 0, 1, 2 }; + + ASSERT_TRUE(isHamiltonianCyclePresent); + ASSERT_TRUE(isHamiltonianPathPresent); + ASSERT_TRUE(unitTestHelper.NormalizeCyclesAndCompare(hamiltonianPathActualResult, hamiltonianPathExpectedResult)); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0006_eulerian_path_and_circuit_test.cc b/tests/0003_graph/0006_eulerian_path_and_circuit_test.cc new file mode 100644 index 0000000..a163a5c --- /dev/null +++ b/tests/0003_graph/0006_eulerian_path_and_circuit_test.cc @@ -0,0 +1,32 @@ +#include +#include "0006_EulerianPathAndCircuit.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace EulerianPathAndCircuit +{ + UnitTestHelper unitTestHelper; + + TEST(EulerianPathAndCycle, Test1) + { + Graph graph; + + graph.PushUndirectedEdge(1, 0); + graph.PushUndirectedEdge(0, 2); + graph.PushUndirectedEdge(2, 1); + graph.PushUndirectedEdge(0, 3); + graph.PushUndirectedEdge(3, 4); + graph.PushUndirectedEdge(4, 0); + + graph.FindEulerianPathAndCircuit(); + + bool isEulerianPathPresent = graph.IsEulerianPathPresent(); + bool isEulerianCircuitPresent = graph.IsEulerianCircuitPresent(); + + vector actualEulerianPath = graph.UndirectedGraphGetEulerianPath(); + vector expectedEulerianPath = { 0, 1, 2, 0, 3, 4, 0}; + + ASSERT_TRUE(isEulerianPathPresent); + ASSERT_TRUE(isEulerianCircuitPresent); + EXPECT_EQ(expectedEulerianPath, actualEulerianPath); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm_test.cc b/tests/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm_test.cc new file mode 100644 index 0000000..5736b79 --- /dev/null +++ b/tests/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm_test.cc @@ -0,0 +1,45 @@ +#include +#include "0007_MinimumSpanningTreeKruskalAlgorithm.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace MinimumSpanningTreeKruskalAlgorithm +{ + UnitTestHelper unitTestHelper; + + TEST(MST, Kruskal) + { + Graph graph; + + graph.PushUndirectedEdge(1, 2, 4); + graph.PushUndirectedEdge(1, 8, 8); + graph.PushUndirectedEdge(2, 8, 11); + graph.PushUndirectedEdge(2, 3, 8); + graph.PushUndirectedEdge(3, 4, 7); + graph.PushUndirectedEdge(3, 9, 2); + graph.PushUndirectedEdge(3, 6, 4); + graph.PushUndirectedEdge(4, 5, 9); + graph.PushUndirectedEdge(4, 6, 14); + graph.PushUndirectedEdge(5, 6, 10); + graph.PushUndirectedEdge(6, 7, 2); + graph.PushUndirectedEdge(7, 8, 1); + graph.PushUndirectedEdge(7, 9, 6); + graph.PushUndirectedEdge(8, 9, 7); + + graph.FindMinimumSpanningTreeKruskalAlgorithm(); + + vector, int>> actualMST = graph.GetMinimumSpanningTree(); + vector, int>> expectedMST = + { + {{7, 8}, 1}, + {{3, 9}, 2}, + {{6, 7}, 2}, + {{2, 1}, 4}, + {{3, 6}, 4}, + {{3, 4}, 7}, + {{8, 1}, 8}, + {{4, 5}, 9} + }; + + ASSERT_EQ(unitTestHelper.SortVectorOfPair(actualMST), unitTestHelper.SortVectorOfPair(expectedMST)); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0008_minimum_spanning_tree_prim_algorithm_test.cc b/tests/0003_graph/0008_minimum_spanning_tree_prim_algorithm_test.cc new file mode 100644 index 0000000..251c654 --- /dev/null +++ b/tests/0003_graph/0008_minimum_spanning_tree_prim_algorithm_test.cc @@ -0,0 +1,45 @@ +#include +#include "0008_MinimumSpanningTreePrimAlgorithm.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace MinimumSpanningTreePrimAlgorithm +{ + UnitTestHelper unitTestHelper; + + TEST(MST, Prim) + { + Graph graph; + + graph.PushUndirectedEdge(1, 2, 4); + graph.PushUndirectedEdge(1, 8, 8); + graph.PushUndirectedEdge(2, 8, 11); + graph.PushUndirectedEdge(2, 3, 8); + graph.PushUndirectedEdge(3, 4, 7); + graph.PushUndirectedEdge(3, 9, 2); + graph.PushUndirectedEdge(3, 6, 4); + graph.PushUndirectedEdge(4, 5, 9); + graph.PushUndirectedEdge(4, 6, 14); + graph.PushUndirectedEdge(5, 6, 10); + graph.PushUndirectedEdge(6, 7, 2); + graph.PushUndirectedEdge(7, 8, 1); + graph.PushUndirectedEdge(7, 9, 6); + graph.PushUndirectedEdge(8, 9, 7); + + graph.FindMinimumSpanningTreePrimAlgorithm(); + + vector, int>> actualMST = graph.GetMinimumSpanningTree(); + vector, int>> expectedMST = + { + {{7, 8}, 1}, + {{3, 9}, 2}, + {{6, 7}, 2}, + {{2, 1}, 4}, + {{3, 6}, 4}, + {{3, 4}, 7}, + {{8, 1}, 8}, + {{4, 5}, 9} + }; + + ASSERT_EQ(unitTestHelper.SortVectorOfPair(actualMST), unitTestHelper.SortVectorOfPair(expectedMST)); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0009_single_source_shortest_path_bellman_ford_test.cc b/tests/0003_graph/0009_single_source_shortest_path_bellman_ford_test.cc new file mode 100644 index 0000000..fc84901 --- /dev/null +++ b/tests/0003_graph/0009_single_source_shortest_path_bellman_ford_test.cc @@ -0,0 +1,104 @@ +#include +#include "0009_SingleSourceShortestPathBellmanFord.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace SingleSourceShortestPathBellmanFord +{ + UnitTestHelper unitTestHelper; + + // Test for Simple Graph + TEST(BellmanFordTest, SimpleTest) + { + Graph graph; + + graph.PushDirectedEdge(0, 1, 6); + graph.PushDirectedEdge(0, 3, 7); + graph.PushDirectedEdge(1, 2, 5); + graph.PushDirectedEdge(1, 3, 8); + graph.PushDirectedEdge(1, 4, -4); + graph.PushDirectedEdge(2, 1, -2); + graph.PushDirectedEdge(3, 2, -3); + graph.PushDirectedEdge(3, 4, 9); + graph.PushDirectedEdge(3, 4, 9); + graph.PushDirectedEdge(4, 2, 7); + graph.PushDirectedEdge(4, 0, 2); + + string expectedResult = "0 3 2 1 4"; + ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); + ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(4)), expectedResult); + } + + // Test for Single Node Graph + TEST(BellmanFordTest, SingleNodeTest) + { + Graph graph; + graph.PushDirectedEdge(0, 0, 0); // Self-loop + + string expectedResult = "0"; + ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); + ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(0)), expectedResult); + } + + // Test for Negative Weight Cycle + TEST(BellmanFordTest, NegativeWeightCycleTest) + { + Graph graph; + graph.PushDirectedEdge(0, 1, 1); + graph.PushDirectedEdge(1, 2, -1); + graph.PushDirectedEdge(2, 0, -1); // Negative weight cycle + + ASSERT_FALSE(graph.FindSingleSourceShortestPathBellmanFord(0)); + } + + // Test for Multiple Shortest Paths + TEST(BellmanFordTest, MultipleShortestPathsTest) + { + Graph graph; + graph.PushDirectedEdge(0, 1, 5); + graph.PushDirectedEdge(0, 2, 5); + graph.PushDirectedEdge(1, 3, 1); + graph.PushDirectedEdge(2, 3, 1); + + string expectedResult = "0 1 3"; + ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); + ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(3)), expectedResult); + } + + // Test for All Negative Weights + TEST(BellmanFordTest, AllNegativeWeightsTest) + { + Graph graph; + graph.PushDirectedEdge(0, 1, -5); + graph.PushDirectedEdge(1, 2, -3); + graph.PushDirectedEdge(2, 3, -2); + graph.PushDirectedEdge(3, 4, -1); + + string expectedResult = "0 1 2 3 4"; + ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); + ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(4)), expectedResult); + } + + // Test for Large Graph + TEST(BellmanFordTest, LargeGraphTest) + { + Graph graph; + for (int i = 0; i < 100; ++i) { + graph.PushDirectedEdge(i, i + 1, 1); + } + + string expectedResult = "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20"; + ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); + ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(20)), expectedResult); + } + + // Test for Self-Loop Edge + TEST(BellmanFordTest, SelfLoopTest) + { + Graph graph; + graph.PushDirectedEdge(0, 0, 10); // Self-loop with weight 10 + + string expectedResult = "0"; + ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); + ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(0)), expectedResult); + } +} diff --git a/tests/0003_graph/0010_directed_acyclic_graph_shortest_path_test.cc b/tests/0003_graph/0010_directed_acyclic_graph_shortest_path_test.cc new file mode 100644 index 0000000..50d7086 --- /dev/null +++ b/tests/0003_graph/0010_directed_acyclic_graph_shortest_path_test.cc @@ -0,0 +1,29 @@ +#include +#include "0010_DirectedAcyclicGraphShortestPath.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace DirectedAcyclicGraphShortestPath +{ + UnitTestHelper unitTestHelper; + + // Test for Simple Graph + TEST(DAGTest, SimpleGraph) + { + Graph graph; + + graph.PushDirectedEdge(0, 1, 5); + graph.PushDirectedEdge(0, 2, 3); + graph.PushDirectedEdge(1, 2, 2); + graph.PushDirectedEdge(1, 3, 6); + graph.PushDirectedEdge(2, 3, 7); + graph.PushDirectedEdge(2, 4, 4); + graph.PushDirectedEdge(2, 5, 2); + graph.PushDirectedEdge(3, 4, -1); + graph.PushDirectedEdge(3, 5, 1); + graph.PushDirectedEdge(4, 5, -2); + + graph.FindDAGShortestPath(1); + string expectedPath = "1 3 4 5"; + ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetDAGShortestPath(5)), expectedPath); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0011_single_source_shortest_path_dijkstra_test.cc b/tests/0003_graph/0011_single_source_shortest_path_dijkstra_test.cc new file mode 100644 index 0000000..5460b1b --- /dev/null +++ b/tests/0003_graph/0011_single_source_shortest_path_dijkstra_test.cc @@ -0,0 +1,31 @@ +#include +#include "0011_SingleSourceShortestPathDijkstra.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace SingleSourceShortestPathDijkstra +{ + UnitTestHelper unitTestHelper; + + // Test for Simple Graph + TEST(DijkstraTest, SimpleGraph) + { + Graph graph; + + graph.PushDirectedEdge(0, 1, 10); + graph.PushDirectedEdge(0, 3, 5); + graph.PushDirectedEdge(1, 2, 1); + graph.PushDirectedEdge(1, 3, 2); + graph.PushDirectedEdge(2, 4, 4); + graph.PushDirectedEdge(3, 1, 3); + graph.PushDirectedEdge(3, 2, 9); + graph.PushDirectedEdge(3, 4, 2); + graph.PushDirectedEdge(4, 2, 6); + graph.PushDirectedEdge(4, 0, 7); + + graph.FindShortestPathDijkstra(0); + + string expectedPath = "0 3 1 2"; + + ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetDijkstraShortestPath(2)), expectedPath); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0012_difference_constraints_shortest_paths_test.cc b/tests/0003_graph/0012_difference_constraints_shortest_paths_test.cc new file mode 100644 index 0000000..152dd0d --- /dev/null +++ b/tests/0003_graph/0012_difference_constraints_shortest_paths_test.cc @@ -0,0 +1,40 @@ +#include +#include "0012_DifferenceConstraintsShortestPaths.h" +#include"../0000_common_utilities/UnitTestHelper.h" +using namespace std; + +namespace DifferenceConstraintsShortestPaths +{ + UnitTestHelper unitTestHelper; + + TEST(DifferenceConstraints, SimpleGraph) + { + Graph graph; + + vector> vectorA = + { + {1, -1, 0, 0, 0}, + {1, 0, 0, 0, -1}, + {0, 1, 0, 0, -1}, + {-1, 0, 1, 0, 0}, + {-1, 0, 0, 1, 0}, + {0, 0, -1, 1, 0}, + {0, 0, -1, 0, 1}, + {0, 0, 0, -1, 1}, + }; + vector vectorX = { "v1", "v2", "v3", "v4", "v5" }; + vector vectorB = {0, -1, 1, 5, 4, -1, -3, -3}; + vector> expectedSolution = + { + {"v2", -3}, + {"v5", -4}, + {"v1", -5}, + {"v4", -1}, + {"v3", 0}, + }; + graph.PushAllDirectedEdges(vectorA, vectorX, vectorB); + + ASSERT_TRUE(graph.FindDifferenceConstraintsSolutionBellmanFord()); + ASSERT_EQ(unitTestHelper.SortVectorOfPairAndSerialize(graph.GetDifferenceConstrtaintsSolution()), unitTestHelper.SortVectorOfPairAndSerialize(expectedSolution)); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0013_all_pairs_shortest_paths_floyd_warshall_test.cc b/tests/0003_graph/0013_all_pairs_shortest_paths_floyd_warshall_test.cc new file mode 100644 index 0000000..17a5045 --- /dev/null +++ b/tests/0003_graph/0013_all_pairs_shortest_paths_floyd_warshall_test.cc @@ -0,0 +1,36 @@ +#include +#include "0013_AllPairsShortestPathsFloydWarshall.h" +#include "../0000_common_utilities/UnitTestHelper.h" +using namespace std; + +namespace AllPairsShortestPathsFloydWarshall +{ + UnitTestHelper unitTestHelper; + + TEST(FloydWarshall, SimpleGraph) + { + // Arrange + Graph graph; + int noOfVertices = 5; + string expectedResult = "[1 5 4 3 2][1 5 4 3][1 5 4][1 5][2 4 1][2 4 3][2 4][2 4 1 5][3 2 4 1][3 2][3 2 4][3 2 4 1 5][4 1][4 3 2][4 3][4 1 5][5 4 1][5 4 3 2][5 4 3][5 4]"; + + // Act + graph.CreateGraph(noOfVertices); + + graph.PushDirectedEdge(1, 2, 3); + graph.PushDirectedEdge(1, 3, 8); + graph.PushDirectedEdge(1, 5, -4); + graph.PushDirectedEdge(2, 4, 1); + graph.PushDirectedEdge(2, 5, 7); + graph.PushDirectedEdge(3, 2, 4); + graph.PushDirectedEdge(4, 3, -5); + graph.PushDirectedEdge(4, 1, 2); + graph.PushDirectedEdge(5, 4, 6); + + graph.FindAllPairsShortestPathsFloydWarshallSolution(); + string actualResult = unitTestHelper.SerializeVectorToString(graph.GetFloydWarshallShortestPath()); + + // Assert + ASSERT_EQ(actualResult, expectedResult); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0014_all_pairs_shortest_paths_johnson_test.cc b/tests/0003_graph/0014_all_pairs_shortest_paths_johnson_test.cc new file mode 100644 index 0000000..66a63a1 --- /dev/null +++ b/tests/0003_graph/0014_all_pairs_shortest_paths_johnson_test.cc @@ -0,0 +1,44 @@ +#include +#include "0014_AllPairsShortestPathsJohnson.h" +#include"../0000_common_utilities/UnitTestHelper.h" +using namespace std; + +namespace AllPairsShortestPathsJohnson +{ + UnitTestHelper unitTestHelper; + + TEST(JohnsonAlgorithm, SimpleGraph) + { + // Arrange + Graph graph; + vector> expectedDistanceMatrix = + { + {0, 1, -3, 2, -4}, + {3, 0, -4, 1, -1}, + {7, 4, 0, 5, 3}, + {2, -1, -5, 0, -2}, + {8, 5, 1, 6, 0}, + }; + string expectedPredecessorMatrixesult = "[1 5 4 3 2][1 5 4 3][1 5 4][1 5][2 4 1][2 4 3][2 4][2 4 1 5][3 2 4 1][3 2][3 2 4][3 2 4 1 5][4 1][4 3 2][4 3][4 1 5][5 4 1][5 4 3 2][5 4 3][5 4]"; + + // Act + graph.PushDirectedEdge(1, 2, 3); + graph.PushDirectedEdge(1, 3, 8); + graph.PushDirectedEdge(1, 5, -4); + graph.PushDirectedEdge(2, 4, 1); + graph.PushDirectedEdge(2, 5, 7); + graph.PushDirectedEdge(3, 2, 4); + graph.PushDirectedEdge(4, 3, -5); + graph.PushDirectedEdge(4, 1, 2); + graph.PushDirectedEdge(5, 4, 6); + + bool result = graph.FindAllPairsShortestPathsJohnsonAlgorithm(); + vector> actualDistanceMatrix = graph.GetAllPairsShortestPathsDistanceMatrix(); + string actualPredecessorMatrix = unitTestHelper.SerializeVectorToString(graph.GetAllPairsShortestPathsPathMatrix()); + + // Assert + ASSERT_TRUE(result); + ASSERT_EQ(expectedDistanceMatrix, actualDistanceMatrix); + ASSERT_EQ(expectedPredecessorMatrixesult, actualPredecessorMatrix); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0015_maximum_flow_ford_fulkerson_test.cc b/tests/0003_graph/0015_maximum_flow_ford_fulkerson_test.cc new file mode 100644 index 0000000..117bfc2 --- /dev/null +++ b/tests/0003_graph/0015_maximum_flow_ford_fulkerson_test.cc @@ -0,0 +1,64 @@ +#include +#include "0015_MaximumFlowFordFulkerson.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace MaximumFlowFordFulkerson +{ + UnitTestHelper unitTestHelper; + + TEST(MaximumFlowFordFulkerson, GraphWithNoParallelEdges) + { + // Arrange + Graph graph; + int noOfVertices = 6; + int expectedMaximumFlow = 23; + + + // Act + graph.CreateGraph(noOfVertices); + + graph.PushDirectedEdge(0, 1, 16); + graph.PushDirectedEdge(0, 2, 13); + graph.PushDirectedEdge(1, 3, 12); + graph.PushDirectedEdge(2, 1, 4); + graph.PushDirectedEdge(2, 4, 14); + graph.PushDirectedEdge(3, 2, 9); + graph.PushDirectedEdge(3, 5, 20); + graph.PushDirectedEdge(4, 3, 7); + graph.PushDirectedEdge(4, 5, 4); + + int actualMaximumFlow = graph.FindMaximumFlowFordFulkerson(); + + // Assert + ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); + } + + TEST(MaximumFlowFordFulkerson, GraphWithParallelEdges) + { + // Arrange + Graph graph; + int noOfVertices = 6; + int expectedMaximumFlow = 24; + + + // Act + graph.CreateGraph(noOfVertices); + + graph.PushDirectedEdge(0, 1, 16); + graph.PushDirectedEdge(0, 2, 13); + graph.PushDirectedEdge(1, 3, 12); + graph.PushDirectedEdge(1, 2, 6); + graph.PushDirectedEdge(2, 1, 10); + graph.PushDirectedEdge(2, 4, 14); + graph.PushDirectedEdge(2, 3, 2); + graph.PushDirectedEdge(3, 2, 11); + graph.PushDirectedEdge(3, 5, 20); + graph.PushDirectedEdge(4, 3, 7); + graph.PushDirectedEdge(4, 5, 4); + + int actualMaximumFlow = graph.FindMaximumFlowFordFulkerson(); + + // Assert + ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0016_maximum_flow_edmonds_karp_test.cc b/tests/0003_graph/0016_maximum_flow_edmonds_karp_test.cc new file mode 100644 index 0000000..5d3177a --- /dev/null +++ b/tests/0003_graph/0016_maximum_flow_edmonds_karp_test.cc @@ -0,0 +1,64 @@ +#include +#include "0016_MaximumFlowEdmondsKarp.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace MaximumFlowEdmondsKarp +{ + UnitTestHelper unitTestHelper; + + TEST(MaximumFlowEdmondsKarp, GraphWithNoParallelEdges) + { + // Arrange + Graph graph; + int noOfVertices = 6; + int expectedMaximumFlow = 23; + + + // Act + graph.CreateGraph(noOfVertices); + + graph.PushDirectedEdge(0, 1, 16); + graph.PushDirectedEdge(0, 2, 13); + graph.PushDirectedEdge(1, 3, 12); + graph.PushDirectedEdge(2, 1, 4); + graph.PushDirectedEdge(2, 4, 14); + graph.PushDirectedEdge(3, 2, 9); + graph.PushDirectedEdge(3, 5, 20); + graph.PushDirectedEdge(4, 3, 7); + graph.PushDirectedEdge(4, 5, 4); + + int actualMaximumFlow = graph.FindMaximumFlowEdmondsKarp(); + + // Assert + ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); + } + + TEST(MaximumFlowEdmondsKarp, GraphWithParallelEdges) + { + // Arrange + Graph graph; + int noOfVertices = 6; + int expectedMaximumFlow = 24; + + + // Act + graph.CreateGraph(noOfVertices); + + graph.PushDirectedEdge(0, 1, 16); + graph.PushDirectedEdge(0, 2, 13); + graph.PushDirectedEdge(1, 3, 12); + graph.PushDirectedEdge(1, 2, 6); + graph.PushDirectedEdge(2, 1, 10); + graph.PushDirectedEdge(2, 4, 14); + graph.PushDirectedEdge(2, 3, 2); + graph.PushDirectedEdge(3, 2, 11); + graph.PushDirectedEdge(3, 5, 20); + graph.PushDirectedEdge(4, 3, 7); + graph.PushDirectedEdge(4, 5, 4); + + int actualMaximumFlow = graph.FindMaximumFlowEdmondsKarp(); + + // Assert + ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0017_maximum_bipartite_matching_test.cc b/tests/0003_graph/0017_maximum_bipartite_matching_test.cc new file mode 100644 index 0000000..d556e28 --- /dev/null +++ b/tests/0003_graph/0017_maximum_bipartite_matching_test.cc @@ -0,0 +1,35 @@ +#include +#include "0017_MaximumBipartiteMatching.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace MaximumBipartiteMatching +{ + TEST(MaximumBipartiteMatching, SimpleGraph) + { + // Arrange + Graph graph; + UnitTestHelper unitTestHelper; + int noOfVertices = 9; + int expectedMaximumMatching = 3; + string expectedMatchings = "[0 1][2 6][3 5]"; + + // Act + graph.CreateGraph(noOfVertices); + + graph.PushDirectedEdge(0, 1); + graph.PushDirectedEdge(2, 1); + graph.PushDirectedEdge(2, 6); + graph.PushDirectedEdge(3, 5); + graph.PushDirectedEdge(3, 6); + graph.PushDirectedEdge(3, 7); + graph.PushDirectedEdge(4, 6); + graph.PushDirectedEdge(8, 6); + + int actualMaximumMatching = graph.FindMaximumBipartiteMatching(); + vector> actualMatchings = graph.GetMatchings(); + + // Assert + ASSERT_EQ(expectedMaximumMatching, actualMaximumMatching); + ASSERT_EQ(expectedMatchings, unitTestHelper.SerializeVectorToString(actualMatchings)); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0018_maximum_flow_goldberg_generic_push_relabel_test.cc b/tests/0003_graph/0018_maximum_flow_goldberg_generic_push_relabel_test.cc new file mode 100644 index 0000000..283cab0 --- /dev/null +++ b/tests/0003_graph/0018_maximum_flow_goldberg_generic_push_relabel_test.cc @@ -0,0 +1,35 @@ +#include +#include "0018_MaximumFlowGoldbergGenericPushRelabel.h" +#include "../0000_common_utilities/UnitTestHelper.h" + +namespace MaximumFlowGoldbergGenericPushRelabel +{ + UnitTestHelper unitTestHelper; + + TEST(MaximumFlowGoldbergGenericPushRelabel, GraphWithNoParallelEdges) + { + // Arrange + Graph graph; + int noOfVertices = 6; + int expectedMaximumFlow = 23; + + + // Act + graph.CreateGraph(noOfVertices); + + graph.PushDirectedEdge(0, 1, 16); + graph.PushDirectedEdge(0, 2, 13); + graph.PushDirectedEdge(1, 3, 12); + graph.PushDirectedEdge(2, 1, 4); + graph.PushDirectedEdge(2, 4, 14); + graph.PushDirectedEdge(3, 2, 9); + graph.PushDirectedEdge(3, 5, 20); + graph.PushDirectedEdge(4, 3, 7); + graph.PushDirectedEdge(4, 5, 4); + + int actualMaximumFlow = graph.FindMaximumFlowGoldbergGenericPushRelabel(); + + // Assert + ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); + } +} \ No newline at end of file diff --git a/tests/0003_graph/0019_maximum_flow_relabel_to_front_test.cc b/tests/0003_graph/0019_maximum_flow_relabel_to_front_test.cc new file mode 100644 index 0000000..a73b89d --- /dev/null +++ b/tests/0003_graph/0019_maximum_flow_relabel_to_front_test.cc @@ -0,0 +1,36 @@ +#include +#include "0019_MaximumFlowRelabelToFront.h" +#include "../0000_common_utilities/UnitTestHelper.h" +using namespace std; + +namespace MaximumFlowRelabelToFront +{ + UnitTestHelper unitTestHelper; + + TEST(MaximumFlowRelabelToFront, SimpleGraph) + { + // Arrange + Graph graph; + int noOfVertices = 6; + int expectedMaximumFlow = 23; + + + // Act + graph.CreateGraph(noOfVertices); + + graph.PushDirectedEdge(0, 1, 16); + graph.PushDirectedEdge(0, 2, 13); + graph.PushDirectedEdge(1, 3, 12); + graph.PushDirectedEdge(2, 1, 4); + graph.PushDirectedEdge(2, 4, 14); + graph.PushDirectedEdge(3, 2, 9); + graph.PushDirectedEdge(3, 5, 20); + graph.PushDirectedEdge(4, 3, 7); + graph.PushDirectedEdge(4, 5, 4); + + int actualMaximumFlow = graph.FindMaximumFlowRelabelToFront(); + + // Assert + ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); + } +} \ No newline at end of file diff --git a/tests/0003_graph/CMakeLists.txt b/tests/0003_graph/CMakeLists.txt new file mode 100644 index 0000000..275d4a8 --- /dev/null +++ b/tests/0003_graph/CMakeLists.txt @@ -0,0 +1,50 @@ +cmake_policy(SET CMP0135 NEW) + +include(FetchContent) +FetchContent_Declare( + googletest + URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip +) + +# For Windows: Prevent overriding the parent project's compiler/linker settings +set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) +FetchContent_MakeAvailable(googletest) + +enable_testing() + +add_executable( + 0003GraphTests + 0001_BreadthFirstSearchTest.cc + 0002_DepthFirstSearchTest.cc + 0003_TopologicalSortTest.cc + 0004_StronglyConnectedComponentsTest.cc + 0005_HamiltonianPathAndCycleTest.cc + 0006_EulerianPathAndCircuitTest.cc + 0007_MinimumSpanningTreeKruskalAlgorithmTest.cc + 0008_MinimumSpanningTreePrimAlgorithmTest.cc + 0009_SingleSourceShortestPathBellmanFordTest.cc + 0010_DirectedAcyclicGraphShortestPathTest.cc + 0011_SingleSourceShortestPathDijkstraTest.cc + 0012_DifferenceConstraintsShortestPathsTest.cc + 0013_AllPairsShortestPathsFloydWarshallTest.cc + 0014_AllPairsShortestPathsJohnsonTest.cc + 0015_MaximumFlowFordFulkersonTest.cc + 0016_MaximumFlowEdmondsKarpTest.cc + 0017_MaximumBipartiteMatchingTest.cc + 0018_MaximumFlowGoldbergGenericPushRelabelTest.cc + 0019_MaximumFlowRelabelToFrontTest.cc +) + +target_link_libraries( + 0003GraphTests + GTest::gtest_main + 0003GRAPH +) + +# Add .clang-tidy configuration to this library. +if(CLANG_TIDY_EXE) + set_target_properties(0003GRAPH PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") +endif() + +include(GoogleTest) +gtest_discover_tests(0003GraphTests DISCOVERY_TIMEOUT 30) \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0001_fibonacci_number_test.cc b/tests/0004_dynamic_programming/0001_fibonacci_number_test.cc new file mode 100644 index 0000000..1fdd9a4 --- /dev/null +++ b/tests/0004_dynamic_programming/0001_fibonacci_number_test.cc @@ -0,0 +1,34 @@ +#include +#include "0001_FibonacciNumber.h" +using namespace std; + +namespace FibonacciNumber +{ + TEST(FibonacciNumber, RecursiveTest) + { + // Arrange + DynamicProgramming dp; + int n = 5; + int expectedFib = 5; + + // Act + int actualFib = dp.RecursiveNthFibonacci(n); + + // Assert + ASSERT_EQ(expectedFib, actualFib); + } + + TEST(FibonacciNumber, DpTest) + { + // Arrange + DynamicProgramming dp; + int n = 5; + int expectedFib = 5; + + // Act + int actualFib = dp.DpNthFibonacci(n); + + // Assert + ASSERT_EQ(expectedFib, actualFib); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0002_tribonacci_number_test.cc b/tests/0004_dynamic_programming/0002_tribonacci_number_test.cc new file mode 100644 index 0000000..d25c394 --- /dev/null +++ b/tests/0004_dynamic_programming/0002_tribonacci_number_test.cc @@ -0,0 +1,34 @@ +#include +#include "0002_TribonacciNumber.h" +using namespace std; + +namespace TribonacciNumber +{ + TEST(TribonacciNumber, RecursiveTest) + { + // Arrange + DynamicProgramming dp; + int n = 5; + int expectedFib = 2; + + // Act + int actualFib = dp.RecursiveNthTribonacci(n); + + // Assert + ASSERT_EQ(expectedFib, actualFib); + } + + TEST(TribonacciNumber, DpTest) + { + // Arrange + DynamicProgramming dp; + int n = 10; + int expectedFib = 44; + + // Act + int actualFib = dp.DpNthTribonacci(n); + + // Assert + ASSERT_EQ(expectedFib, actualFib); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0003_climbing_stairs_test.cc b/tests/0004_dynamic_programming/0003_climbing_stairs_test.cc new file mode 100644 index 0000000..0504cbc --- /dev/null +++ b/tests/0004_dynamic_programming/0003_climbing_stairs_test.cc @@ -0,0 +1,33 @@ +#include +#include "0003_ClimbingStairs.h" + +namespace ClimbingStairs +{ + TEST(ClimbingStairs, RecursiveTest) + { + // Arrange + DynamicProgramming dp; + int n = 4; + int expectedCount = 5; + + // Act + int actualCount = dp.RecursiveCountWays(n); + + // Assert + ASSERT_EQ(expectedCount, actualCount); + } + + TEST(ClimbingStairs, DpTest) + { + // Arrange + DynamicProgramming dp; + int n = 4; + int expectedCount = 5; + + // Act + int actualCount = dp.DpCountWays(n); + + // Assert + ASSERT_EQ(expectedCount, actualCount); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0004_minimum_cost_climbing_stairs_test.cc b/tests/0004_dynamic_programming/0004_minimum_cost_climbing_stairs_test.cc new file mode 100644 index 0000000..b488105 --- /dev/null +++ b/tests/0004_dynamic_programming/0004_minimum_cost_climbing_stairs_test.cc @@ -0,0 +1,33 @@ +#include +#include "0004_MinimumCostClimbingStairs.h" + +namespace MinimumCostClimbingStairs +{ + TEST(MinimumCostClimbingStairs, RecursionTest) + { + // Arrange + DynamicProgramming dp; + vector cost = { 16, 19, 10, 12, 18 }; + int expectedCost = 31; + + // Act + int actualCost = dp.RecursiveMinimumCostClimbingStairs(cost); + + // Assert + ASSERT_EQ(expectedCost, actualCost); + } + + TEST(MinimumCostClimbingStairs, DpTest) + { + // Arrange + DynamicProgramming dp; + vector cost = { 16, 19, 10, 12, 18 }; + int expectedCost = 31; + + // Act + int actualCost = dp.DpMinimumCostClimbingStairs(cost); + + // Assert + ASSERT_EQ(expectedCost, actualCost); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0005_house_robber1_test.cc b/tests/0004_dynamic_programming/0005_house_robber1_test.cc new file mode 100644 index 0000000..d3f6312 --- /dev/null +++ b/tests/0004_dynamic_programming/0005_house_robber1_test.cc @@ -0,0 +1,33 @@ +#include +#include "0005_HouseRobber1.h" + +namespace HouseRobber1 +{ + TEST(HouseRobber1, RecursionTest) + { + // Arrange + DynamicProgramming dp; + vector houseValues = { 6, 7, 1, 3, 8, 2, 4 }; + int expectedMaximumLoot = 19; + + // Act + int actualMaximumLoot = dp.RecursiveMaximumLoot(houseValues); + + // Assert + ASSERT_EQ(expectedMaximumLoot, actualMaximumLoot); + } + + TEST(HouseRobber1, DpTest) + { + // Arrange + DynamicProgramming dp; + vector houseValues = { 6, 7, 1, 3, 8, 2, 4 }; + int expectedMaximumLoot = 19; + + // Act + int actualMaximumLoot = dp.DpMaximumLoot(houseValues); + + // Assert + ASSERT_EQ(expectedMaximumLoot, actualMaximumLoot); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0006_house_robber2_test.cc b/tests/0004_dynamic_programming/0006_house_robber2_test.cc new file mode 100644 index 0000000..e37c346 --- /dev/null +++ b/tests/0004_dynamic_programming/0006_house_robber2_test.cc @@ -0,0 +1,48 @@ +#include +#include "0006_HouseRobber2.h" + +namespace HouseRobber2 +{ + TEST(HouseRobber2, RecursionTest01) + { + // Arrange + DynamicProgramming dp; + vector houseValues = { 2, 2, 3, 1, 2 }; + int expectedMaximumLoot = 5; + + // Act + int actualMaximumLoot = dp.RecursiveMaximumLoot(houseValues); + + // Assert + ASSERT_EQ(expectedMaximumLoot, actualMaximumLoot); + } + + TEST(HouseRobber2, DpTest01) + { + // Arrange + DynamicProgramming dp; + vector houseValues = { 2, 2, 3, 1, 2 }; + int expectedMaximumLoot = 5; + + // Act + int actualMaximumLoot = dp.DpMaximumLoot(houseValues); + + // Assert + ASSERT_EQ(expectedMaximumLoot, actualMaximumLoot); + } + + TEST(HouseRobber2, DpTest02) + { + // Arrange + DynamicProgramming dp; + vector houseValues = { 9, 1, 8, 2 }; + int expectedMaximumLoot = 17; + + // Act + int actualMaximumLoot = dp.DpMaximumLoot(houseValues); + + // Assert + ASSERT_EQ(expectedMaximumLoot, actualMaximumLoot); + } + +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0007_decode_ways_test.cc b/tests/0004_dynamic_programming/0007_decode_ways_test.cc new file mode 100644 index 0000000..cf81a98 --- /dev/null +++ b/tests/0004_dynamic_programming/0007_decode_ways_test.cc @@ -0,0 +1,47 @@ +#include +#include "0007_DecodeWays.h" + +namespace DecodeWays +{ + TEST(DecodeWays, RecursionTest01) + { + // Arrange + DynamicProgramming dp; + string digits = "121"; + int expectedWaysCount = 3; + + // Act + int actualWaysCount = dp.RecursiveCountWays(digits); + + // Assert + ASSERT_EQ(expectedWaysCount, actualWaysCount); + } + + TEST(DecodeWays, DpTest01) + { + // Arrange + DynamicProgramming dp; + string digits = "121"; + int expectedWaysCount = 3; + + // Act + int actualWaysCount = dp.DpCountways(digits); + + // Assert + ASSERT_EQ(expectedWaysCount, actualWaysCount); + } + + TEST(DecodeWays, DpTestInvalidInput) + { + // Arrange + DynamicProgramming dp; + string digits = "230"; + int expectedWaysCount = 0; + + // Act + int actualWaysCount = dp.DpCountways(digits); + + // Assert + ASSERT_EQ(expectedWaysCount, actualWaysCount); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0008_tiling_problem_test.cc b/tests/0004_dynamic_programming/0008_tiling_problem_test.cc new file mode 100644 index 0000000..bbcbb79 --- /dev/null +++ b/tests/0004_dynamic_programming/0008_tiling_problem_test.cc @@ -0,0 +1,33 @@ +#include +#include "0008_TilingProblem.h" + +namespace TilingProblem +{ + TEST(TilingProblem, RecursionTest01) + { + // Arrange + DynamicProgramming dp; + int nummberOfRows = 4; + int expectedNumberOfWays = 5; + + // Act + int actualNumberOfWays = dp.RecursiveNumberOfWays(nummberOfRows); + + // Assert + ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); + } + + TEST(TilingProblem, DpTest01) + { + // Arrange + DynamicProgramming dp; + int nummberOfRows = 4; + int expectedNumberOfWays = 5; + + // Act + int actualNumberOfWays = dp.DpNumberOfWays(nummberOfRows); + + // Assert + ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0009_friends_pairing_problem_test.cc b/tests/0004_dynamic_programming/0009_friends_pairing_problem_test.cc new file mode 100644 index 0000000..11376ac --- /dev/null +++ b/tests/0004_dynamic_programming/0009_friends_pairing_problem_test.cc @@ -0,0 +1,91 @@ +#include +#include "0009_FriendsPairingProblem.h" + +namespace FriendsPairingProblem +{ + TEST(FriendsPairingProblemDynamicProgrammingTest, RecursiveCountFriendsPairingsTest1) + { + // Arrange + DynamicProgramming dp; + int numberOfFriends = 3; + int expectedPairings = 4; + + // Act + int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); + + // Assert + ASSERT_EQ(expectedPairings, actualPairings); + EXPECT_EQ(dp.RecursiveCountFriendsPairings(4), 10); + EXPECT_EQ(dp.RecursiveCountFriendsPairings(5), 26); + } + + TEST(FriendsPairingProblemDynamicProgrammingTest, RecursiveCountFriendsPairingsTest2) + { + // Arrange + DynamicProgramming dp; + int numberOfFriends = 4; + int expectedPairings = 10; + + // Act + int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); + + // Assert + ASSERT_EQ(expectedPairings, actualPairings); + } + + TEST(FriendsPairingProblemDynamicProgrammingTest, RecursiveCountFriendsPairingsTest3) + { + // Arrange + DynamicProgramming dp; + int numberOfFriends = 5; + int expectedPairings = 26; + + // Act + int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); + + // Assert + ASSERT_EQ(expectedPairings, actualPairings); + } + + TEST(FriendsPairingProblemDynamicProgrammingTest, DpCountFriendsPairingsTest1) + { + // Arrange + DynamicProgramming dp; + int numberOfFriends = 3; + int expectedPairings = 4; + + // Act + int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); + + // Assert + ASSERT_EQ(expectedPairings, actualPairings); + } + + TEST(FriendsPairingProblemDynamicProgrammingTest, DpCountFriendsPairingsTest2) + { + // Arrange + DynamicProgramming dp; + int numberOfFriends = 4; + int expectedPairings = 10; + + // Act + int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); + + // Assert + ASSERT_EQ(expectedPairings, actualPairings); + } + + TEST(FriendsPairingProblemDynamicProgrammingTest, DpCountFriendsPairingsTest3) + { + // Arrange + DynamicProgramming dp; + int numberOfFriends = 5; + int expectedPairings = 26; + + // Act + int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); + + // Assert + ASSERT_EQ(expectedPairings, actualPairings); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0010_ways_to_cover_distance_test.cc b/tests/0004_dynamic_programming/0010_ways_to_cover_distance_test.cc new file mode 100644 index 0000000..7e7f0c9 --- /dev/null +++ b/tests/0004_dynamic_programming/0010_ways_to_cover_distance_test.cc @@ -0,0 +1,117 @@ +#include +#include "0010_WaysToCoverDistance.h" + +namespace WaysToCoverDistance +{ + TEST(WaysToCoverDistanceTest, RecursiveWaysToCoverDistance1) + { + // Arrange + DynamicProgramming dp; + int distance = 3; + int expectedNumberOfWaysToCoverDistance = 4; + + // Act + int actualNumberOfWaysToCoverDistance = dp.RecursiveWaysToCoverDistance(distance); + + // Assert + ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); + } + + TEST(WaysToCoverDistanceTest, RecursiveWaysToCoverDistance2) + { + // Arrange + DynamicProgramming dp; + int distance = 4; + int expectedNumberOfWaysToCoverDistance = 7; + + // Act + int actualNumberOfWaysToCoverDistance = dp.RecursiveWaysToCoverDistance(distance); + + // Assert + ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); + } + + TEST(WaysToCoverDistanceTest, RecursiveWaysToCoverDistanc3) + { + // Arrange + DynamicProgramming dp; + int distance = 5; + int expectedNumberOfWaysToCoverDistance = 13; + + // Act + int actualNumberOfWaysToCoverDistance = dp.RecursiveWaysToCoverDistance(distance); + + // Assert + ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); + } + + TEST(WaysToCoverDistanceTest, RecursiveWaysToCoverDistanc4) + { + // Arrange + DynamicProgramming dp; + int distance = 6; + int expectedNumberOfWaysToCoverDistance = 24; + + // Act + int actualNumberOfWaysToCoverDistance = dp.RecursiveWaysToCoverDistance(distance); + + // Assert + ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); + } + + TEST(WaysToCoverDistanceTest, DpWaysToCoverDistance1) + { + // Arrange + DynamicProgramming dp; + int distance = 3; + int expectedNumberOfWaysToCoverDistance = 4; + + // Act + int actualNumberOfWaysToCoverDistance = dp.DpWaysToCoverDistance(distance); + + // Assert + ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); + } + + TEST(WaysToCoverDistanceTest, DpWaysToCoverDistance2) + { + // Arrange + DynamicProgramming dp; + int distance = 4; + int expectedNumberOfWaysToCoverDistance = 7; + + // Act + int actualNumberOfWaysToCoverDistance = dp.DpWaysToCoverDistance(distance); + + // Assert + ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); + } + + TEST(WaysToCoverDistanceTest, DpWaysToCoverDistance3) + { + // Arrange + DynamicProgramming dp; + int distance = 5; + int expectedNumberOfWaysToCoverDistance = 13; + + // Act + int actualNumberOfWaysToCoverDistance = dp.DpWaysToCoverDistance(distance); + + // Assert + ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); + } + + TEST(WaysToCoverDistanceTest, DpWaysToCoverDistance4) + { + // Arrange + DynamicProgramming dp; + int distance = 6; + int expectedNumberOfWaysToCoverDistance = 24; + + // Act + int actualNumberOfWaysToCoverDistance = dp.DpWaysToCoverDistance(distance); + + // Assert + ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order_test.cc b/tests/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order_test.cc new file mode 100644 index 0000000..8a9830c --- /dev/null +++ b/tests/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order_test.cc @@ -0,0 +1,33 @@ +#include +#include "0011_CountWaysToReachNthStairIncludeOrder.h" + +namespace CountWaysToReachNthStairIncludeOrder +{ + TEST(CountWaysToReachNthStairIncludeOrderTest, RecursiveCountWaysToReachNthStairIncludeOrder1) + { + // Arrange + DynamicProgramming dp; + int n = 4; + int expectedNumberOfWays = 5; + + // Act + int actualNumberOfWays = dp.RecursiveCountWaysToReachNthStairIncludeOrder(n); + + // Assert + ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); + } + + TEST(CountWaysToReachNthStairIncludeOrderTest, DpCountWaysToReachNthStairIncludeOrder1) + { + // Arrange + DynamicProgramming dp; + int n = 4; + int expectedNumberOfWays = 5; + + // Act + int actualNumberOfWays = dp.DpCountWaysToReachNthStairIncludeOrder(n); + + // Assert + ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order_test.cc b/tests/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order_test.cc new file mode 100644 index 0000000..2a67ce3 --- /dev/null +++ b/tests/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order_test.cc @@ -0,0 +1,33 @@ +#include +#include "0012_CountWaysToReachNthStairExcludeOrder.h" + +namespace CountWaysToReachNthStairExcludeOrder +{ + TEST(CountWaysToReachNthStairExcludeOrderTest, RecursiveCountWaysToReachNthStairExcludeOrder1) + { + // Arrange + DynamicProgramming dp; + int n = 4; + int expectedNumberOfWays = 3; + + // Act + int actualNumberOfWays = dp.RecursiveCountWaysToReachNthStairExcludeOrder(n); + + // Assert + ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); + } + + TEST(CountWaysToReachNthStairExcludeOrderTest, DpCountWaysToReachNthStairExcludeOrder1) + { + // Arrange + DynamicProgramming dp; + int n = 4; + int expectedNumberOfWays = 3; + + // Act + int actualNumberOfWays = dp.DpCountWaysToReachNthStairExcludeOrder(n); + + // Assert + ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0013_knapsack_problem_test.cc b/tests/0004_dynamic_programming/0013_knapsack_problem_test.cc new file mode 100644 index 0000000..94d3e84 --- /dev/null +++ b/tests/0004_dynamic_programming/0013_knapsack_problem_test.cc @@ -0,0 +1,53 @@ +#include +#include "0013_KnapsackProblem.h" + +namespace KnapsackProblem +{ + TEST(KnapsackProblemTest, RecursiveKnapsackProblemTest01) + { + // Arrange + DynamicProgramming dp; + int capacity = 4; + vector weight = { 4,5,1 }; + vector profit = { 1,2,3 }; + int expectedMaximumProfit = 3; + + // Act + int actualMaximumProfit = dp.RecursiveKnapsack(capacity, weight, profit); + + // Assert + ASSERT_EQ(expectedMaximumProfit, actualMaximumProfit); + } + + TEST(KnapsackProblemTest, DpKnapsackProblemTest01) + { + // Arrange + DynamicProgramming dp; + int capacity = 4; + vector weight = { 4,5,1 }; + vector profit = { 1,2,3 }; + int expectedMaximumProfit = 3; + + // Act + int actualMaximumProfit = dp.DpKnapsack(capacity, weight, profit); + + // Assert + ASSERT_EQ(expectedMaximumProfit, actualMaximumProfit); + } + + TEST(KnapsackProblemTest, DpKnapsackProblemTest02) + { + // Arrange + DynamicProgramming dp; + int capacity = 4; + vector weight = { 4,5,1 }; + vector profit = { 1,2,3 }; + int expectedMaximumProfit = 3; + + // Act + int actualMaximumProfit = dp.DpKnapsackSpaceOptimized(capacity, weight, profit); + + // Assert + ASSERT_EQ(expectedMaximumProfit, actualMaximumProfit); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0014_subset_sum_problem_test.cc b/tests/0004_dynamic_programming/0014_subset_sum_problem_test.cc new file mode 100644 index 0000000..aeee852 --- /dev/null +++ b/tests/0004_dynamic_programming/0014_subset_sum_problem_test.cc @@ -0,0 +1,35 @@ +#include +#include "0014_SubsetSumProblem.h" + +namespace SubsetSumProblem +{ + TEST(SubsetSumProblemTest, RecursiveSubsetSumTest) + { + // Arrange + DynamicProgramming dp; + vector nums = { 3, 34, 4, 12, 5, 2 }; + int sum = 9; + bool expectedResult = true; + + // Act + bool actualResult = dp.RecursiveSubsetSum(nums, sum); + + // Assert + ASSERT_EQ(expectedResult, actualResult); + } + + TEST(SubsetSumProblemTest, DpSubsetSumTest) + { + // Arrange + DynamicProgramming dp; + vector nums = { 3, 34, 4, 12, 5, 2 }; + int sum = 9; + bool expectedResult = true; + + // Act + bool actualResult = dp.DpIsSubsetSum(nums, sum); + + // Assert + ASSERT_EQ(expectedResult, actualResult); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0015_count_subsets_for_sum_test.cc b/tests/0004_dynamic_programming/0015_count_subsets_for_sum_test.cc new file mode 100644 index 0000000..ba1fa7f --- /dev/null +++ b/tests/0004_dynamic_programming/0015_count_subsets_for_sum_test.cc @@ -0,0 +1,35 @@ +#include +#include"0015_CountSubsetsForSum.h" + +namespace CountSubsetsForSum +{ + TEST(CountSubsetsForSum, RecursiveCountSubsetSum) + { + // Arrange + DynamicProgramming dp; + vector nums = { 1, 2, 3, 3 }; + int sum = 6; + int expectedCount = 3; + + // Act + int actualCount = dp.RecursiveCountSubsets(nums, sum); + + // Assert + ASSERT_EQ(expectedCount, actualCount); + } + + TEST(CountSubsetsForSum, DpCountSubsetSum) + { + // Arrange + DynamicProgramming dp; + vector nums = { 1, 2, 3, 3 }; + int sum = 6; + int expectedCount = 3; + + // Act + int actualCount = dp.DpCountSubsets(nums, sum); + + // Assert + ASSERT_EQ(expectedCount, actualCount); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0016_partition_equal_subset_sum_test.cc b/tests/0004_dynamic_programming/0016_partition_equal_subset_sum_test.cc new file mode 100644 index 0000000..2bfa292 --- /dev/null +++ b/tests/0004_dynamic_programming/0016_partition_equal_subset_sum_test.cc @@ -0,0 +1,33 @@ +#include +#include "0016_PartitionEqualSubsetSum.h" + +namespace PartitionEqualSubsetSum +{ + TEST(PartitionEqualSubsetSum, RecursivePartitionEqualSubsetSum) + { + // Arrange + DynamicProgramming dp; + vector nums = { 1, 5, 11, 5 }; + bool expectedResult = true; + + // Act + bool actualResult = dp.RecursivePartitionEqualSubsets(nums); + + // Assert + ASSERT_EQ(expectedResult, actualResult); + } + + TEST(PartitionEqualSubsetSum, DpPartitionEqualSubsetSum) + { + // Arrange + DynamicProgramming dp; + vector nums = { 1, 5, 11, 5 }; + bool expectedResult = true; + + // Act + bool actualResult = dp.DpPartitionEqualSubsets(nums); + + // Assert + ASSERT_EQ(expectedResult, actualResult); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0017_target_sum_test.cc b/tests/0004_dynamic_programming/0017_target_sum_test.cc new file mode 100644 index 0000000..ab3fbf4 --- /dev/null +++ b/tests/0004_dynamic_programming/0017_target_sum_test.cc @@ -0,0 +1,50 @@ +#include +#include "0017_TargetSum.h" + +namespace TargetSum +{ + TEST(TargetSum, RecursiveSolutionTest_ValidInput_ReturnsCorrectResult) + { + // Arrange + DynamicProgramming dp; + vector nums = { 1, 1, 1, 1, 1 }; + int target = 3; + int expectedResult = 5; + + // Act + int actualResult = dp.RecursiveFindTotalWays(nums, target); + + // Assert + ASSERT_EQ(expectedResult, actualResult); + } + + TEST(TargetSum, DpSolutionTest_ValidInput_ReturnsCorrectResult) + { + // Arrange + DynamicProgramming dp; + vector nums = { 1, 1, 1, 1, 1 }; + int target = 3; + int expectedResult = 5; + + // Act + int actualResult = dp.DpFindTotalWays(nums, target); + + // Assert + ASSERT_EQ(expectedResult, actualResult); + } + + TEST(TargetSum, DpSolutionTest_TargetGreaterThanTotalSum_ReturnsZero) + { + // Arrange + DynamicProgramming dp; + vector nums = { 1, 1, 1, 1, 1 }; + int target = -1000; + int expectedResult = 0; + + // Act + int actualResult = dp.DpFindTotalWays(nums, target); + + // Assert + ASSERT_EQ(expectedResult, actualResult); + } +} \ No newline at end of file diff --git a/tests/0004_dynamic_programming/CMakeLists.txt b/tests/0004_dynamic_programming/CMakeLists.txt new file mode 100644 index 0000000..4ef67b0 --- /dev/null +++ b/tests/0004_dynamic_programming/CMakeLists.txt @@ -0,0 +1,49 @@ +cmake_policy(SET CMP0135 NEW) + +include(FetchContent) +FetchContent_Declare( + googletest + URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip +) + +# For Windows: Prevent overriding the parent project's compiler/linker settings +set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) +FetchContent_MakeAvailable(googletest) + +enable_testing() + +add_executable( + 0005DynamicProgrammingTests + 0001_FibonacciNumberTest.cc + 0002_TribonacciNumberTest.cc + 0003_ClimbingStairsTest.cc + 0004_MinimumCostClimbingStairsTest.cc + 0005_HouseRobber1Test.cc + 0006_HouseRobber2Test.cc + 0007_DecodeWaysTest.cc + 0008_TilingProblemTest.cc + 0009_FriendsPairingProblemTest.cc + 0010_WaysToCoverDistanceTest.cc + 0011_CountWaysToReachNthStairIncludeOrderTest.cc + 0012_CountWaysToReachNthStairExcludeOrderTest.cc + 0013_KnapsackProblemTest.cc + 0014_SubsetSumProblemTest.cc + 0015_CountSubsetsForSumTest.cc + 0016_PartitionEqualSubsetSumTest.cc + 0017_TargetSumTest.cc + +) + +target_link_libraries( + 0005DynamicProgrammingTests + GTest::gtest_main + 0005DYNAMICPROGRAMMING +) + +# Add .clang-tidy configuration to this library. +if(CLANG_TIDY_EXE) + set_target_properties(0005DYNAMICPROGRAMMING PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") +endif() + +include(GoogleTest) +gtest_discover_tests(0005DynamicProgrammingTests DISCOVERY_TIMEOUT 30) \ No newline at end of file diff --git a/tests/0005_greedy_algorithms/CMakeLists.txt b/tests/0005_greedy_algorithms/CMakeLists.txt new file mode 100644 index 0000000..e69de29 diff --git a/tests/0006_bitwise_algorithms/CMakeLists.txt b/tests/0006_bitwise_algorithms/CMakeLists.txt new file mode 100644 index 0000000..e69de29 diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt new file mode 100644 index 0000000..41d781c --- /dev/null +++ b/tests/CMakeLists.txt @@ -0,0 +1,7 @@ +add_subdirectory(0000_common_utilities) +add_subdirectory(0001_basics) +add_subdirectory(0002_tree) +add_subdirectory(0003_graph) +add_subdirectory(0004_dynamic_programming) +add_subdirectory(0005_greedy_algorithms) +add_subdirectory(0006_bitwise_algorithms) \ No newline at end of file From e2ac601df81f84821c5c94938c9ee4fa0608919c Mon Sep 17 00:00:00 2001 From: Debashis Nandi Date: Sun, 14 Jun 2026 03:17:08 +0530 Subject: [PATCH 07/13] fix: method names fixed --- src/0001_basics/node.cc | 2 +- src/0002_tree/0001_binary_search_tree.cc | 4 +- src/0002_tree/CMakeLists.txt | 2 +- .../headers/0001_binary_search_tree.h | 2 +- src/0003_graph/0001_breadth_first_search.cc | 18 +- src/0003_graph/0002_depth_first_search.cc | 20 +-- src/0003_graph/0003_topological_sort.cc | 40 ++--- .../0004_strongly_connected_components.cc | 42 ++--- .../0005_hamiltonian_path_and_cycle.cc | 38 ++--- .../0006_eulerian_path_and_circuit.cc | 74 ++++---- ...minimum_spanning_tree_kruskal_algorithm.cc | 38 ++--- ...08_minimum_spanning_tree_prim_algorithm.cc | 20 +-- ...ingle_source_shortest_path_bellman_ford.cc | 34 ++-- ...10_directed_acyclic_graph_shortest_path.cc | 44 ++--- ...11_single_source_shortest_path_dijkstra.cc | 38 ++--- ...2_difference_constraints_shortest_paths.cc | 38 ++--- ...all_pairs_shortest_paths_floyd_warshall.cc | 26 +-- .../0014_all_pairs_shortest_paths_johnson.cc | 60 +++---- .../0015_maximum_flow_ford_fulkerson.cc | 52 +++--- .../0016_maximum_flow_edmonds_karp.cc | 44 ++--- .../0017_maximum_bipartite_matching.cc | 100 +++++------ ...imum_flow_goldberg_generic_push_relabel.cc | 98 +++++------ .../0019_maximum_flow_relabel_to_front.cc | 102 +++++------ src/0003_graph/CMakeLists.txt | 38 ++--- .../headers/0001_breadth_first_search.h | 10 +- .../headers/0002_depth_first_search.h | 10 +- .../headers/0003_topological_sort.h | 16 +- .../0004_strongly_connected_components.h | 18 +- .../headers/0005_hamiltonian_path_and_cycle.h | 20 +-- .../headers/0006_eulerian_path_and_circuit.h | 24 +-- ..._minimum_spanning_tree_kruskal_algorithm.h | 18 +- ...008_minimum_spanning_tree_prim_algorithm.h | 10 +- ...single_source_shortest_path_bellman_ford.h | 16 +- ...010_directed_acyclic_graph_shortest_path.h | 20 +-- ...011_single_source_shortest_path_dijkstra.h | 18 +- ...12_difference_constraints_shortest_paths.h | 16 +- ..._all_pairs_shortest_paths_floyd_warshall.h | 14 +- .../0014_all_pairs_shortest_paths_johnson.h | 26 +-- .../0015_maximum_flow_ford_fulkerson.h | 14 +- .../headers/0016_maximum_flow_edmonds_karp.h | 12 +- .../headers/0017_maximum_bipartite_matching.h | 20 +-- ...ximum_flow_goldberg_generic_push_relabel.h | 16 +- .../0019_maximum_flow_relabel_to_front.h | 16 +- .../0001_fibonacci_number.cc | 10 +- .../0002_tribonacci_number.cc | 10 +- .../0003_climbing_stairs.cc | 10 +- .../0004_minimum_cost_climbing_stairs.cc | 14 +- .../0005_house_robber1.cc | 16 +- .../0006_house_robber2.cc | 30 ++-- .../0007_decode_ways.cc | 26 +-- .../0008_tiling_problem.cc | 16 +- .../0009_friends_pairing_problem.cc | 20 +-- .../0010_ways_to_cover_distance.cc | 22 +-- ...t_ways_to_reach_nth_stair_include_order.cc | 20 +-- ...t_ways_to_reach_nth_stair_exclude_order.cc | 26 +-- .../0013_knapsack_problem.cc | 24 +-- .../0014_subset_sum_problem.cc | 36 ++-- .../0015_count_subsets_for_sum.cc | 22 +-- .../0016_partition_equal_subset_sum.cc | 20 +-- .../0017_target_sum.cc | 24 +-- src/0004_dynamic_programming/CMakeLists.txt | 34 ++-- .../headers/0001_fibonacci_number.h | 14 +- .../headers/0002_tribonacci_number.h | 14 +- .../headers/0003_climbing_stairs.h | 16 +- .../0004_minimum_cost_climbing_stairs.h | 18 +- .../headers/0005_house_robber1.h | 18 +- .../headers/0006_house_robber2.h | 22 +-- .../headers/0007_decode_ways.h | 28 +-- .../headers/0008_tiling_problem.h | 16 +- .../headers/0009_friends_pairing_problem.h | 30 ++-- .../headers/0010_ways_to_cover_distance.h | 30 ++-- ...nt_ways_to_reach_nth_stair_include_order.h | 40 ++--- ...nt_ways_to_reach_nth_stair_exclude_order.h | 44 ++--- .../headers/0013_knapsack_problem.h | 30 ++-- .../headers/0014_subset_sum_problem.h | 30 ++-- .../headers/0015_count_subsets_for_sum.h | 30 ++-- .../headers/0016_partition_equal_subset_sum.h | 32 ++-- .../headers/0017_target_sum.h | 36 ++-- .../0000_common_utilities/unit_test_helper.h | 46 ++--- tests/0001_basics/CMakeLists.txt | 3 +- tests/0001_basics/node_test.cc | 10 +- .../0002_tree/0001_binary_search_tree_test.cc | 30 ++-- tests/0002_tree/CMakeLists.txt | 2 +- .../0001_breadth_first_search_test.cc | 36 ++-- .../0002_depth_first_search_test.cc | 160 +++++++++--------- .../0003_graph/0003_topological_sort_test.cc | 112 ++++++------ ...0004_strongly_connected_components_test.cc | 118 ++++++------- .../0005_hamiltonian_path_and_cycle_test.cc | 32 ++-- .../0006_eulerian_path_and_circuit_test.cc | 28 +-- ...um_spanning_tree_kruskal_algorithm_test.cc | 42 ++--- ...nimum_spanning_tree_prim_algorithm_test.cc | 42 ++--- ..._source_shortest_path_bellman_ford_test.cc | 110 ++++++------ ...rected_acyclic_graph_shortest_path_test.cc | 34 ++-- ...ngle_source_shortest_path_dijkstra_test.cc | 34 ++-- ...ference_constraints_shortest_paths_test.cc | 14 +- ...airs_shortest_paths_floyd_warshall_test.cc | 38 ++--- ...4_all_pairs_shortest_paths_johnson_test.cc | 38 ++--- .../0015_maximum_flow_ford_fulkerson_test.cc | 70 ++++---- .../0016_maximum_flow_edmonds_karp_test.cc | 70 ++++---- .../0017_maximum_bipartite_matching_test.cc | 38 ++--- ...flow_goldberg_generic_push_relabel_test.cc | 36 ++-- ...0019_maximum_flow_relabel_to_front_test.cc | 36 ++-- tests/0003_graph/CMakeLists.txt | 39 ++--- .../0001_fibonacci_number_test.cc | 24 +-- .../0002_tribonacci_number_test.cc | 24 +-- .../0003_climbing_stairs_test.cc | 24 +-- .../0004_minimum_cost_climbing_stairs_test.cc | 24 +-- .../0005_house_robber1_test.cc | 24 +-- .../0006_house_robber2_test.cc | 34 ++-- .../0007_decode_ways_test.cc | 34 ++-- .../0008_tiling_problem_test.cc | 24 +-- .../0009_friends_pairing_problem_test.cc | 68 ++++---- .../0010_ways_to_cover_distance_test.cc | 84 ++++----- ...s_to_reach_nth_stair_include_order_test.cc | 24 +-- ...s_to_reach_nth_stair_exclude_order_test.cc | 24 +-- .../0013_knapsack_problem_test.cc | 34 ++-- .../0014_subset_sum_problem_test.cc | 24 +-- .../0015_count_subsets_for_sum_test.cc | 26 +-- .../0016_partition_equal_subset_sum_test.cc | 24 +-- .../0017_target_sum_test.cc | 34 ++-- tests/0004_dynamic_programming/CMakeLists.txt | 35 ++-- 121 files changed, 1963 insertions(+), 1960 deletions(-) diff --git a/src/0001_basics/node.cc b/src/0001_basics/node.cc index df1effa..47482bc 100644 --- a/src/0001_basics/node.cc +++ b/src/0001_basics/node.cc @@ -1,4 +1,4 @@ -#include "Node.h" +#include "node.h" Node::Node() { diff --git a/src/0002_tree/0001_binary_search_tree.cc b/src/0002_tree/0001_binary_search_tree.cc index 0f0650e..ca077d9 100644 --- a/src/0002_tree/0001_binary_search_tree.cc +++ b/src/0002_tree/0001_binary_search_tree.cc @@ -1,9 +1,9 @@ -#include "0001_BinarySearchTree.h" +#include "0001_binary_search_tree.h" #include #include using namespace std; -namespace BinarySearchTree +namespace binary_search_tree { Node::Node(int data, Node* parent, Node* left, Node* right) { diff --git a/src/0002_tree/CMakeLists.txt b/src/0002_tree/CMakeLists.txt index 3ef4afa..4db770b 100644 --- a/src/0002_tree/CMakeLists.txt +++ b/src/0002_tree/CMakeLists.txt @@ -1,6 +1,6 @@ # Specify the source files set(0002TREE_SOURCES - 0001_BinarySearchTree.cc + 0001_binary_search_tree.cc ) # Create a library target diff --git a/src/0002_tree/headers/0001_binary_search_tree.h b/src/0002_tree/headers/0001_binary_search_tree.h index d422701..571481b 100644 --- a/src/0002_tree/headers/0001_binary_search_tree.h +++ b/src/0002_tree/headers/0001_binary_search_tree.h @@ -4,7 +4,7 @@ #include using namespace std; -namespace BinarySearchTree +namespace binary_search_tree { class Node { diff --git a/src/0003_graph/0001_breadth_first_search.cc b/src/0003_graph/0001_breadth_first_search.cc index 9a8b1ac..fc06255 100644 --- a/src/0003_graph/0001_breadth_first_search.cc +++ b/src/0003_graph/0001_breadth_first_search.cc @@ -1,4 +1,4 @@ -#include "0001_BreadthFirstSearch.h" +#include "0001_breadth_first_search.h" #include #include #include @@ -7,7 +7,7 @@ #include using namespace std; -namespace BreadthFirstSearch +namespace breadth_first_search { Node::Node(int value) { @@ -17,7 +17,7 @@ namespace BreadthFirstSearch this->parent = nullptr; } - Node* Graph::MakeOrFindNode(int value) + Node* Graph::makeOrFindNode(int value) { Node* node = nullptr; if (this->_nodeMap.find(value) == this->_nodeMap.end()) @@ -32,7 +32,7 @@ namespace BreadthFirstSearch return node; } - void Graph::BreadthFirstSearch(Node* node) + void Graph::breadthFirstSearch(Node* node) { node->color = WHITE; node->distance = 0; @@ -60,10 +60,10 @@ namespace BreadthFirstSearch } } - void Graph::PushUndirectedEdge(int valueU, int valueV) + void Graph::pushUndirectedEdge(int valueU, int valueV) { - Node* nodeU = this->MakeOrFindNode(valueU); - Node* nodeV = this->MakeOrFindNode(valueV); + Node* nodeU = this->makeOrFindNode(valueU); + Node* nodeV = this->makeOrFindNode(valueV); this->_adjlist[nodeU].push_back(nodeV); this->_adjlist[nodeV].push_back(nodeU); @@ -71,10 +71,10 @@ namespace BreadthFirstSearch void Graph::BFS(int value) { - this->BreadthFirstSearch(this->_nodeMap[value]); + this->breadthFirstSearch(this->_nodeMap[value]); } - vector> Graph::ShowBFSResult() + vector> Graph::showBFSResult() { vector> result; for (auto& node : this->_nodeMap) diff --git a/src/0003_graph/0002_depth_first_search.cc b/src/0003_graph/0002_depth_first_search.cc index 3cbc49a..0a4f378 100644 --- a/src/0003_graph/0002_depth_first_search.cc +++ b/src/0003_graph/0002_depth_first_search.cc @@ -1,10 +1,10 @@ -#include "0002_DepthFirstSearch.h" +#include "0002_depth_first_search.h" #include #include #include using namespace std; -namespace DepthFirstSearch +namespace depth_first_search { Node::Node(int value) { @@ -15,7 +15,7 @@ namespace DepthFirstSearch this->parent = nullptr; } - Node* Graph::MakeOrFindNode(int value) + Node* Graph::makeOrFindNode(int value) { Node* node = nullptr; if (this->_nodeMap.find(value) == this->_nodeMap.end()) @@ -30,7 +30,7 @@ namespace DepthFirstSearch return node; } - void Graph::DepthFirstSearch(Node* nodeU) + void Graph::depthFirstSearch(Node* nodeU) { this->_time++; nodeU->discoveredTime = this->_time; @@ -40,7 +40,7 @@ namespace DepthFirstSearch if (nodeV->color == WHITE) { nodeV->parent = nodeU; - this->DepthFirstSearch(nodeV); + this->depthFirstSearch(nodeV); } } nodeU->color = BLACK; @@ -48,10 +48,10 @@ namespace DepthFirstSearch nodeU->finishingTime = this->_time; } - void Graph::PushDirectedEdge(int valueU, int valueV) + void Graph::pushDirectedEdge(int valueU, int valueV) { - Node* nodeU = this->MakeOrFindNode(valueU); - Node* nodeV = this->MakeOrFindNode(valueV); + Node* nodeU = this->makeOrFindNode(valueU); + Node* nodeV = this->makeOrFindNode(valueV); this->_adjlist[nodeU].push_back(nodeV); } @@ -63,12 +63,12 @@ namespace DepthFirstSearch { if (iterator.second->color == WHITE) { - this->DepthFirstSearch(iterator.second); + this->depthFirstSearch(iterator.second); } } } - vector>> Graph::ShowDFSResult() + vector>> Graph::showDFSResult() { vector>> result; for (auto& node : this->_nodeMap) diff --git a/src/0003_graph/0003_topological_sort.cc b/src/0003_graph/0003_topological_sort.cc index 3d4d1cb..b76662c 100644 --- a/src/0003_graph/0003_topological_sort.cc +++ b/src/0003_graph/0003_topological_sort.cc @@ -1,4 +1,4 @@ -#include "0003_TopologicalSort.h" +#include "0003_topological_sort.h" #include #include #include @@ -6,7 +6,7 @@ #include using namespace std; -namespace TopologicalSort +namespace topological_sort { Node::Node(int value) { @@ -18,7 +18,7 @@ namespace TopologicalSort this->parent = nullptr; } - Node* Graph::MakeOrFindNode(int value) + Node* Graph::makeOrFindNode(int value) { Node* node = nullptr; if (this->_nodeMap.find(value) == this->_nodeMap.end()) @@ -33,7 +33,7 @@ namespace TopologicalSort return node; } - void Graph::DepthFirstSearch(Node* nodeU) + void Graph::depthFirstSearch(Node* nodeU) { this->_time++; nodeU->discoveryTime = this->_time; @@ -43,7 +43,7 @@ namespace TopologicalSort if (nodeV->color == WHITE) { nodeV->parent = nodeU; - this->DepthFirstSearch(nodeV); + this->depthFirstSearch(nodeV); } else if (nodeV->color == GRAY) { @@ -57,28 +57,28 @@ namespace TopologicalSort this->_topologicalSortedNodeList.push_front(nodeU); } - void Graph::PushDirectedEdge(int valueU, int valueV) + void Graph::pushDirectedEdge(int valueU, int valueV) { - Node* nodeU = this->MakeOrFindNode(valueU); - Node* nodeV = this->MakeOrFindNode(valueV); + Node* nodeU = this->makeOrFindNode(valueU); + Node* nodeV = this->makeOrFindNode(valueV); this->_adjlist[nodeU].push_back(nodeV); nodeV->inDegree++; } - void Graph::PushSingleNode(int valueU) + void Graph::pushSingleNode(int valueU) { - this->MakeOrFindNode(valueU); + this->makeOrFindNode(valueU); } - void Graph::TopologicalSort() + void Graph::topologicalSort() { this->_time = 0; for (auto& iterator : this->_nodeMap) { if (iterator.second->color == WHITE) { - this->DepthFirstSearch(iterator.second); + this->depthFirstSearch(iterator.second); if (this->_hasCycle == true) { break; @@ -87,14 +87,14 @@ namespace TopologicalSort } } - void Graph::KahnTopologicalSort() + void Graph::kahnTopologicalSort() { - // Step-1 Compute in-degree of each vertices - // This is already done while creating the graph + // step-1 compute in-degree of each vertices + // this is already done while creating the graph this->_time = 0; queue nodeQueue; - // Step-2 Enqueue vertices with in-degree 0 + // step-2 enqueue vertices with in-degree 0 for (auto& node : this->_nodeMap) { if (node.second->inDegree == 0) @@ -105,7 +105,7 @@ namespace TopologicalSort } } - // Step-3 Process vertices in queue + // step-3 process vertices in queue while (!nodeQueue.empty()) { Node* node = nodeQueue.front(); @@ -114,7 +114,7 @@ namespace TopologicalSort node->finishingTime = this->_time; this->_topologicalSortedNodeList.push_back(node); - // Step-4 Process all the neighbours of current node based on in-degree + // step-4 process all the neighbours of current node based on in-degree for (auto& neighbour : this->_adjlist[node]) { neighbour->inDegree--; @@ -127,14 +127,14 @@ namespace TopologicalSort } } - // Step-5 Check if a cycle exists + // step-5 check if a cycle exists if (this->_topologicalSortedNodeList.size() != this->_nodeMap.size()) { this->_hasCycle = true; } } - vector>> Graph::ShowTopologicalSortResult() + vector>> Graph::showTopologicalSortResult() { if (this->_hasCycle == true) { diff --git a/src/0003_graph/0004_strongly_connected_components.cc b/src/0003_graph/0004_strongly_connected_components.cc index 7a99e34..a12adc5 100644 --- a/src/0003_graph/0004_strongly_connected_components.cc +++ b/src/0003_graph/0004_strongly_connected_components.cc @@ -1,10 +1,10 @@ -#include "0004_StronglyConnectedComponents.h" +#include "0004_strongly_connected_components.h" #include #include #include using namespace std; -namespace StronglyConnectedComponents +namespace strongly_connected_components { Node::Node(int value) { @@ -15,7 +15,7 @@ namespace StronglyConnectedComponents this->parent = nullptr; } - Node* Graph::MakeOrFindNode(int value) + Node* Graph::makeOrFindNode(int value) { Node* node = nullptr; if (this->_nodeMap.find(value) == this->_nodeMap.end()) @@ -30,7 +30,7 @@ namespace StronglyConnectedComponents return node; } - void Graph::DepthFirstSearchOnGraphG(Node* nodeU) + void Graph::depthFirstSearchOnGraphG(Node* nodeU) { this->_time++; nodeU->discoveryTime = this->_time; @@ -40,7 +40,7 @@ namespace StronglyConnectedComponents if (nodeV->color == WHITE) { nodeV->parent = nodeU; - this->DepthFirstSearchOnGraphG(nodeV); + this->depthFirstSearchOnGraphG(nodeV); } } nodeU->color = BLACK; @@ -49,7 +49,7 @@ namespace StronglyConnectedComponents this->_nodesFinishingTimeOrder.push_front(nodeU); } - void Graph::DepthFirstSearchOnGraphT(Node* nodeU, vector& connectedComponents) + void Graph::depthFirstSearchOnGraphT(Node* nodeU, vector& connectedComponents) { nodeU->color = GRAY; connectedComponents.push_back(nodeU->data); @@ -58,42 +58,42 @@ namespace StronglyConnectedComponents if (nodeV->color == WHITE) { nodeV->parent = nodeU; - this->DepthFirstSearchOnGraphT(nodeV, connectedComponents); + this->depthFirstSearchOnGraphT(nodeV, connectedComponents); } } nodeU->color = BLACK; } - void Graph::PushDirectedEdge(int valueU, int valueV) + void Graph::pushDirectedEdge(int valueU, int valueV) { - Node* nodeU = this->MakeOrFindNode(valueU); - Node* nodeV = this->MakeOrFindNode(valueV); + Node* nodeU = this->makeOrFindNode(valueU); + Node* nodeV = this->makeOrFindNode(valueV); - // Creating the actual graph. + // creating the actual graph. this->_adjlistG[nodeU].push_back(nodeV); - // Creating the transpose of the actual graph. + // creating the transpose of the actual graph. this->_adjlistT[nodeV].push_back(nodeU); } - void Graph::PushSingleNode(int valueU) + void Graph::pushSingleNode(int valueU) { - this->MakeOrFindNode(valueU); + this->makeOrFindNode(valueU); } - void Graph::DFSOnGraphG() + void Graph::dFSOnGraphG() { this->_time = 0; for (auto& iterator : this->_nodeMap) { if (iterator.second->color == WHITE) { - this->DepthFirstSearchOnGraphG(iterator.second); + this->depthFirstSearchOnGraphG(iterator.second); } } } - void Graph::DFSOnGraphT() + void Graph::dFSOnGraphT() { for (auto& iterator : this->_nodeMap) { @@ -106,16 +106,16 @@ namespace StronglyConnectedComponents if (iterator->color == WHITE) { vector connectedComponents; - this->DepthFirstSearchOnGraphT(iterator, connectedComponents); + this->depthFirstSearchOnGraphT(iterator, connectedComponents); this->_allConnectedComponents.push_back(connectedComponents); } } } - vector> Graph::FindAllStronglyConnectedComponents() + vector> Graph::findAllStronglyConnectedComponents() { - this->DFSOnGraphG(); - this->DFSOnGraphT(); + this->dFSOnGraphG(); + this->dFSOnGraphT(); return this->_allConnectedComponents; } } \ No newline at end of file diff --git a/src/0003_graph/0005_hamiltonian_path_and_cycle.cc b/src/0003_graph/0005_hamiltonian_path_and_cycle.cc index bfa99b5..5c8d5e4 100644 --- a/src/0003_graph/0005_hamiltonian_path_and_cycle.cc +++ b/src/0003_graph/0005_hamiltonian_path_and_cycle.cc @@ -1,7 +1,7 @@ -#include "0005_HamiltonianPathAndCycle.h" +#include "0005_hamiltonian_path_and_cycle.h" using namespace std; -namespace HamiltonianPathAndCycle +namespace hamiltonian_path_and_cycle { Node::Node(int value) { @@ -9,8 +9,8 @@ namespace HamiltonianPathAndCycle this->isVisited = false; } - // Graph Private Member Methods - Node* Graph::MakeOrFindNode(int value) + // Graph private member methods + Node* Graph::makeOrFindNode(int value) { Node* node = nullptr; if (this->_nodeMap.find(value) == this->_nodeMap.end()) @@ -25,7 +25,7 @@ namespace HamiltonianPathAndCycle return node; } - bool Graph::IsSafe(Node* nodeU, Node* nodeV) + bool Graph::isSafe(Node* nodeU, Node* nodeV) { if (this->_adjlist[nodeU].find(nodeV) == this->_adjlist[nodeU].end()) { @@ -38,7 +38,7 @@ namespace HamiltonianPathAndCycle return true; } - bool Graph::HamiltonianCycleAndPathUtil(Node* nodeU) + bool Graph::hamiltonianCycleAndPathUtil(Node* nodeU) { if (this->_visitedNodeCount == this->_nodeMap.size()) { @@ -53,12 +53,12 @@ namespace HamiltonianPathAndCycle } for (auto& nodeV : this->_adjlist[nodeU]) { - if (this->IsSafe(nodeU, nodeV)) + if (this->isSafe(nodeU, nodeV)) { this->_hamiltonianPath.push_back(nodeV->data); nodeV->isVisited = true; this->_visitedNodeCount++; - if (this->HamiltonianCycleAndPathUtil(nodeV)) + if (this->hamiltonianCycleAndPathUtil(nodeV)) { return true; } @@ -70,22 +70,22 @@ namespace HamiltonianPathAndCycle return false; } - // Graph Public Member Methods - void Graph::PushUndirectedEdge(int valueU, int valueV) + // Graph public member methods + void Graph::pushUndirectedEdge(int valueU, int valueV) { - Node* nodeU = this->MakeOrFindNode(valueU); - Node* nodeV = this->MakeOrFindNode(valueV); + Node* nodeU = this->makeOrFindNode(valueU); + Node* nodeV = this->makeOrFindNode(valueV); this->_adjlist[nodeU].insert(nodeV); this->_adjlist[nodeV].insert(nodeU); } - void Graph::PushSingleNode(int valueU) + void Graph::pushSingleNode(int valueU) { - this->MakeOrFindNode(valueU); + this->makeOrFindNode(valueU); } - void Graph::FindHamiltonianCycleAndPath() + void Graph::findHamiltonianCycleAndPath() { this->_isHamiltonianCyclePresent = false; this->_isHamiltonianPathPresent = false; @@ -94,20 +94,20 @@ namespace HamiltonianPathAndCycle this->_hamiltonianPath.push_back(this->_startingNode->data); this->_startingNode->isVisited = true; this->_visitedNodeCount = 1; - this->HamiltonianCycleAndPathUtil(this->_startingNode); + this->hamiltonianCycleAndPathUtil(this->_startingNode); } - bool Graph::IsHamiltonianCyclePresent() + bool Graph::isHamiltonianCyclePresent() { return this->_isHamiltonianCyclePresent; } - bool Graph::IsHamiltonianPathPresent() + bool Graph::isHamiltonianPathPresent() { return this->_isHamiltonianPathPresent; } - vector Graph::GetHamiltonianPath() + vector Graph::getHamiltonianPath() { return this->_hamiltonianPath; } diff --git a/src/0003_graph/0006_eulerian_path_and_circuit.cc b/src/0003_graph/0006_eulerian_path_and_circuit.cc index ee132ca..a69bb01 100644 --- a/src/0003_graph/0006_eulerian_path_and_circuit.cc +++ b/src/0003_graph/0006_eulerian_path_and_circuit.cc @@ -1,9 +1,9 @@ -#include "0006_EulerianPathAndCircuit.h" +#include "0006_eulerian_path_and_circuit.h" #include #include using namespace std; -namespace EulerianPathAndCircuit +namespace eulerian_path_and_circuit { Node::Node(int value) { @@ -14,8 +14,8 @@ namespace EulerianPathAndCircuit this->visited = false; } - // Graph Private Member Methods - Node* Graph::MakeOrFindNode(int value) + // Graph private member methods + Node* Graph::makeOrFindNode(int value) { Node* node = nullptr; if (this->_nodeMap.find(value) == this->_nodeMap.end()) @@ -30,23 +30,23 @@ namespace EulerianPathAndCircuit return node; } - void Graph::DepthFirstSearch(Node* nodeU) + void Graph::depthFirstSearch(Node* nodeU) { nodeU->visited = true; for (auto& nodeV : this->_adjlist[nodeU]) { if (nodeV->visited == false) { - this->DepthFirstSearch(nodeV); + this->depthFirstSearch(nodeV); } } } - bool Graph::IsConnected() + bool Graph::isConnected() { - // Step-1 : Make the visited property of all nodes as false. It is already done in constructor. + // step-1 : make the visited property of all nodes as false. it is already done in constructor. - // Step-2 : Find a node which do not have 0 degree. + // step-2 : find a node which do not have 0 degree. Node* node = nullptr; for (auto& iterator : this->_nodeMap) { @@ -57,15 +57,15 @@ namespace EulerianPathAndCircuit } } - // Step-3 : If node is null, it means G.E is null, so G is connected, else call DFS to traverse the graph G. + // step-3 : if node is null, it means G.E is null, so G is connected, else call DFS to traverse the graph G. if (node == nullptr) { return true; } - this->DepthFirstSearch(node); + this->depthFirstSearch(node); - // Step-4 : Checking if all the non-zero degree vertices have been visited or not. + // step-4 : checking if all the non-zero degree vertices have been visited or not. for (auto& iterator : this->_nodeMap) { if (iterator.second->visited == false && iterator.second->degree != 0) @@ -76,7 +76,7 @@ namespace EulerianPathAndCircuit return true; } - void Graph::EulerianPathHierholzerAlgorithm(Node* startingNode) + void Graph::eulerianPathHierholzerAlgorithm(Node* startingNode) { stack currentPath; currentPath.push(startingNode); @@ -98,11 +98,11 @@ namespace EulerianPathAndCircuit } } - // Graph Public Member Methods - void Graph::PushUndirectedEdge(int valueU, int valueV) + // Graph public member methods + void Graph::pushUndirectedEdge(int valueU, int valueV) { - Node* nodeU = this->MakeOrFindNode(valueU); - Node* nodeV = this->MakeOrFindNode(valueV); + Node* nodeU = this->makeOrFindNode(valueU); + Node* nodeV = this->makeOrFindNode(valueV); this->_adjlist[nodeU].push_back(nodeV); nodeU->degree++; @@ -110,25 +110,25 @@ namespace EulerianPathAndCircuit nodeV->degree++; } - void Graph::PushDirectedEdge(int valueU, int valueV) + void Graph::pushDirectedEdge(int valueU, int valueV) { - Node* nodeU = this->MakeOrFindNode(valueU); - Node* nodeV = this->MakeOrFindNode(valueV); + Node* nodeU = this->makeOrFindNode(valueU); + Node* nodeV = this->makeOrFindNode(valueV); this->_adjlist[nodeU].push_back(nodeV); nodeU->outDegree++; nodeV->inDegree++; } - void Graph::PushSingleNode(int valueU) + void Graph::pushSingleNode(int valueU) { - this->MakeOrFindNode(valueU); + this->makeOrFindNode(valueU); } - void Graph::FindEulerianPathAndCircuit() + void Graph::findEulerianPathAndCircuit() { - // If the graph is not connected then graph G is Not-Eulerian. - if (this->IsConnected() == false) + // if the graph is not connected then graph G is not-eulerian. + if (this->isConnected() == false) { this->_isEulerianPathPresent = false; this->_isEulerianCircuitPresent = false; @@ -144,7 +144,7 @@ namespace EulerianPathAndCircuit } } - // Check-1 : When no vertex with odd degree is present, then graph G is Eulerian. + // check-1 : when no vertex with odd degree is present, then graph G is eulerian. if (oddDegreeVertexCount == 0) { this->_isEulerianPathPresent = true; @@ -152,7 +152,7 @@ namespace EulerianPathAndCircuit return; } - // Check-2 : When 2 vertices have odd degree, then graph G is Semi-Eulerian. + // check-2 : when 2 vertices have odd degree, then graph G is semi-eulerian. if (oddDegreeVertexCount == 2) { this->_isEulerianPathPresent = true; @@ -160,7 +160,7 @@ namespace EulerianPathAndCircuit return; } - // Check-3 : When more than 2 vertices have odd degree, then graph G is Not Eulerian. + // check-3 : when more than 2 vertices have odd degree, then graph G is not eulerian. if (oddDegreeVertexCount > 2) { this->_isEulerianPathPresent = false; @@ -169,27 +169,27 @@ namespace EulerianPathAndCircuit } } - bool Graph::IsEulerianPathPresent() + bool Graph::isEulerianPathPresent() { return this->_isEulerianPathPresent; } - bool Graph::IsEulerianCircuitPresent() + bool Graph::isEulerianCircuitPresent() { return this->_isEulerianCircuitPresent; } - vector Graph::UndirectedGraphGetEulerianPath() + vector Graph::undirectedGraphGetEulerianPath() { - // Case-3 : When more than 2 vertices have odd degree, then the graph G is not Eulerian. - // No Eulerian Path is posible. + // Case-3 : when more than 2 vertices have odd degree, then the graph G is not eulerian. + // no eulerian path is posible. if (this->_isEulerianPathPresent == false) { return {}; } - // Now 2 cases remains. - // Case-2 : When 2 vertices have odd degree. Choose any one of them. + // now 2 cases remains. + // Case-2 : when 2 vertices have odd degree. choose any one of them. Node* node = nullptr; for (auto& iterator : this->_nodeMap) { @@ -200,12 +200,12 @@ namespace EulerianPathAndCircuit } } - // Case-1 : When no vertex with odd degree is present. Choose any vertex as starting point. + // Case-1 : when no vertex with odd degree is present. choose any vertex as starting point. if (node == nullptr) { node = this->_nodeMap[0]; } - this->EulerianPathHierholzerAlgorithm(node); + this->eulerianPathHierholzerAlgorithm(node); reverse(this->_eulerianPath.begin(), this->_eulerianPath.end()); return this->_eulerianPath; } diff --git a/src/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm.cc b/src/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm.cc index 20bea2b..ca17a63 100644 --- a/src/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm.cc +++ b/src/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm.cc @@ -1,9 +1,9 @@ -#include "0007_MinimumSpanningTreeKruskalAlgorithm.h" +#include "0007_minimum_spanning_tree_kruskal_algorithm.h" #include #include using namespace std; -namespace MinimumSpanningTreeKruskalAlgorithm +namespace minimum_spanning_tree_kruskal_algorithm { Node::Node(int data) { @@ -19,8 +19,8 @@ namespace MinimumSpanningTreeKruskalAlgorithm this->weight = weight; } - // Graph Private Member Methods - Node* Graph::MakeOrFindNode(int data) + // Graph private member methods + Node* Graph::makeOrFindNode(int data) { Node* node = nullptr; if (this->_nodeMap.find(data) == this->_nodeMap.end()) @@ -35,18 +35,18 @@ namespace MinimumSpanningTreeKruskalAlgorithm return node; } - void Graph::MakeSet(Node* node) + void Graph::makeSet(Node* node) { node->parent = node; node->rank = 0; } - void Graph::Union(Node* nodeU, Node* nodeV) + void Graph::unionSet(Node* nodeU, Node* nodeV) { - this->Link(this->FindSet(nodeU), this->FindSet(nodeV)); + this->link(this->findSet(nodeU), this->findSet(nodeV)); } - void Graph::Link(Node* nodeU, Node* nodeV) + void Graph::link(Node* nodeU, Node* nodeV) { if (nodeV->rank > nodeU->rank) { @@ -62,46 +62,46 @@ namespace MinimumSpanningTreeKruskalAlgorithm } } - Node* Graph::FindSet(Node* node) + Node* Graph::findSet(Node* node) { if (node != node->parent) { - node->parent = this->FindSet(node->parent); + node->parent = this->findSet(node->parent); } return node->parent; } - // Graph Public Member Methods - void Graph::PushUndirectedEdge(int dataU, int dataV, int weight) + // Graph public member methods + void Graph::pushUndirectedEdge(int dataU, int dataV, int weight) { - Node* nodeU = this->MakeOrFindNode(dataU); - Node* nodeV = this->MakeOrFindNode(dataV); + Node* nodeU = this->makeOrFindNode(dataU); + Node* nodeV = this->makeOrFindNode(dataV); this->_adjlist[nodeU].push_back(nodeV); this->_adjlist[nodeV].push_back(nodeU); this->_edgeList.push_back(new Edge(nodeU, nodeV, weight)); } - void Graph::FindMinimumSpanningTreeKruskalAlgorithm() + void Graph::findMinimumSpanningTreeKruskalAlgorithm() { for (auto& iterator : this->_nodeMap) { - this->MakeSet(iterator.second); + this->makeSet(iterator.second); } sort(this->_edgeList.begin(), this->_edgeList.end(), [](Edge* edgeX, Edge* edgeY) { return edgeX->weight < edgeY->weight; }); for (auto& edge : this->_edgeList) { - if (this->FindSet(edge->nodeU) != this->FindSet(edge->nodeV)) + if (this->findSet(edge->nodeU) != this->findSet(edge->nodeV)) { - this->Union(edge->nodeU, edge->nodeV); + this->unionSet(edge->nodeU, edge->nodeV); this->_minimumSpanningTree.push_back({ {edge->nodeU->data, edge->nodeV->data}, edge->weight }); } } } - vector, int>> Graph::GetMinimumSpanningTree() + vector, int>> Graph::getMinimumSpanningTree() { return this->_minimumSpanningTree; } diff --git a/src/0003_graph/0008_minimum_spanning_tree_prim_algorithm.cc b/src/0003_graph/0008_minimum_spanning_tree_prim_algorithm.cc index 1b36027..8ac0237 100644 --- a/src/0003_graph/0008_minimum_spanning_tree_prim_algorithm.cc +++ b/src/0003_graph/0008_minimum_spanning_tree_prim_algorithm.cc @@ -1,9 +1,9 @@ -#include "0008_MinimumSpanningTreePrimAlgorithm.h" +#include "0008_minimum_spanning_tree_prim_algorithm.h" #include using namespace std; -namespace MinimumSpanningTreePrimAlgorithm +namespace minimum_spanning_tree_prim_algorithm { Node::Node(int data) { @@ -13,8 +13,8 @@ namespace MinimumSpanningTreePrimAlgorithm this->isInOperationalSet = false; } - // Graph Private Member Methods - Node* Graph::MakeOrFindNode(int data) + // Graph private member methods + Node* Graph::makeOrFindNode(int data) { Node* node = nullptr; if (this->_nodeMap.find(data) == this->_nodeMap.end()) @@ -29,17 +29,17 @@ namespace MinimumSpanningTreePrimAlgorithm return node; } - // Graph Public Member Methods - void Graph::PushUndirectedEdge(int dataU, int dataV, int weight) + // Graph public member methods + void Graph::pushUndirectedEdge(int dataU, int dataV, int weight) { - Node* nodeU = this->MakeOrFindNode(dataU); - Node* nodeV = this->MakeOrFindNode(dataV); + Node* nodeU = this->makeOrFindNode(dataU); + Node* nodeV = this->makeOrFindNode(dataV); this->_adjlist[nodeU].push_back({nodeV, weight}); this->_adjlist[nodeV].push_back({nodeU, weight}); } - void Graph::FindMinimumSpanningTreePrimAlgorithm() + void Graph::findMinimumSpanningTreePrimAlgorithm() { Node* root = this->_nodeMap.begin()->second; @@ -78,7 +78,7 @@ namespace MinimumSpanningTreePrimAlgorithm } } - vector, int>> Graph::GetMinimumSpanningTree() + vector, int>> Graph::getMinimumSpanningTree() { return this->_minimumSpanningTree; } diff --git a/src/0003_graph/0009_single_source_shortest_path_bellman_ford.cc b/src/0003_graph/0009_single_source_shortest_path_bellman_ford.cc index b059b74..becfa00 100644 --- a/src/0003_graph/0009_single_source_shortest_path_bellman_ford.cc +++ b/src/0003_graph/0009_single_source_shortest_path_bellman_ford.cc @@ -1,9 +1,9 @@ -#include "0009_SingleSourceShortestPathBellmanFord.h" +#include "0009_single_source_shortest_path_bellman_ford.h" #include #include using namespace std; -namespace SingleSourceShortestPathBellmanFord +namespace single_source_shortest_path_bellman_ford { Node::Node(int data) { @@ -19,8 +19,8 @@ namespace SingleSourceShortestPathBellmanFord this->weight = weight; } - // Graph Private Member Methods - Node* Graph::MakeOrFindNode(int data) + // Graph private member methods + Node* Graph::makeOrFindNode(int data) { Node* node = nullptr; if (this->_nodeMap.find(data) == this->_nodeMap.end()) @@ -35,7 +35,7 @@ namespace SingleSourceShortestPathBellmanFord return node; } - void Graph :: InitializeSingleSource(Node* sourceNode) + void Graph :: initializeSingleSource(Node* sourceNode) { for (auto& iterator : this->_nodeMap) { @@ -45,7 +45,7 @@ namespace SingleSourceShortestPathBellmanFord sourceNode->distance = 0; } - void Graph::Relax(Edge* edge) + void Graph::relax(Edge* edge) { if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) { @@ -54,36 +54,36 @@ namespace SingleSourceShortestPathBellmanFord } } - void Graph::GetShortestPath(Node* node, vector& path) + void Graph::getShortestPath(Node* node, vector& path) { path.push_back(node->data); if (node->parent != nullptr) { - this->GetShortestPath(node->parent, path); + this->getShortestPath(node->parent, path); } } - // Graph Public Member Methods - void Graph::PushDirectedEdge(int dataU, int dataV, int weight) + // Graph public member methods + void Graph::pushDirectedEdge(int dataU, int dataV, int weight) { - Node* nodeU = this->MakeOrFindNode(dataU); - Node* nodeV = this->MakeOrFindNode(dataV); + Node* nodeU = this->makeOrFindNode(dataU); + Node* nodeV = this->makeOrFindNode(dataV); this->_adjlist[nodeU].push_back(nodeV); this->_edgeList.push_back(new Edge(nodeU, nodeV, weight)); } - bool Graph::FindSingleSourceShortestPathBellmanFord(int data) + bool Graph::findSingleSourceShortestPathBellmanFord(int data) { Node* source = this->_nodeMap[data]; - this->InitializeSingleSource(source); + this->initializeSingleSource(source); for (int i = 0; i < this->_nodeMap.size() - 1; i++) { for (auto& edge : this->_edgeList) { - this->Relax(edge); + this->relax(edge); } } @@ -97,11 +97,11 @@ namespace SingleSourceShortestPathBellmanFord return true; } - vector Graph::GetShortestPathBellmanFord(int data) + vector Graph::getShortestPathBellmanFord(int data) { vector path = {}; Node* node = this->_nodeMap[data]; - this->GetShortestPath(node, path); + this->getShortestPath(node, path); reverse(path.begin(), path.end()); return path; } diff --git a/src/0003_graph/0010_directed_acyclic_graph_shortest_path.cc b/src/0003_graph/0010_directed_acyclic_graph_shortest_path.cc index 8f4cd81..6634790 100644 --- a/src/0003_graph/0010_directed_acyclic_graph_shortest_path.cc +++ b/src/0003_graph/0010_directed_acyclic_graph_shortest_path.cc @@ -1,9 +1,9 @@ -#include "0010_DirectedAcyclicGraphShortestPath.h" +#include "0010_directed_acyclic_graph_shortest_path.h" #include #include using namespace std; -namespace DirectedAcyclicGraphShortestPath +namespace directed_acyclic_graph_shortest_path { Node::Node(int data) { @@ -20,8 +20,8 @@ namespace DirectedAcyclicGraphShortestPath this->weight = weight; } - // Graph Private Member Methods - Node* Graph::MakeOrFindNode(int data) + // Graph private member methods + Node* Graph::makeOrFindNode(int data) { Node* node = nullptr; if (this->_nodeMap.find(data) == this->_nodeMap.end()) @@ -36,32 +36,32 @@ namespace DirectedAcyclicGraphShortestPath return node; } - void Graph::DepthFirstSearch(Node* nodeU) + void Graph::depthFirstSearch(Node* nodeU) { nodeU->color = GRAY; for (auto& nodeV : this->_adjlist[nodeU]) { if (nodeV->color == WHITE) { - this->DepthFirstSearch(nodeV); + this->depthFirstSearch(nodeV); } } nodeU->color = BLACK; this->_topologicalSortedNodeList.push_front(nodeU); } - void Graph::TopologicalSort() + void Graph::topologicalSort() { for (auto& iterator : this->_nodeMap) { if (iterator.second->color == WHITE) { - this->DepthFirstSearch(iterator.second); + this->depthFirstSearch(iterator.second); } } } - void Graph::InitializeSingleSource(Node* sourceNode) + void Graph::initializeSingleSource(Node* sourceNode) { for (auto& iterator : this->_nodeMap) { @@ -71,7 +71,7 @@ namespace DirectedAcyclicGraphShortestPath sourceNode->distance = 0; } - void Graph::Relax(Edge* edge) + void Graph::relax(Edge* edge) { if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) { @@ -80,44 +80,44 @@ namespace DirectedAcyclicGraphShortestPath } } - void Graph::GetShortestPath(Node* node, vector& path) + void Graph::getShortestPath(Node* node, vector& path) { path.push_back(node->data); if (node->parent != nullptr) { - this->GetShortestPath(node->parent, path); + this->getShortestPath(node->parent, path); } } - // Graph Public Member Methods - void Graph::PushDirectedEdge(int dataU, int dataV, int weight) + // Graph public member methods + void Graph::pushDirectedEdge(int dataU, int dataV, int weight) { - Node* nodeU = this->MakeOrFindNode(dataU); - Node* nodeV = this->MakeOrFindNode(dataV); + Node* nodeU = this->makeOrFindNode(dataU); + Node* nodeV = this->makeOrFindNode(dataV); this->_adjlist[nodeU].push_back(nodeV); this->_edgeMap[nodeU].push_back(new Edge(nodeU, nodeV, weight)); } - void Graph::FindDAGShortestPath(int data) + void Graph::findDAGShortestPath(int data) { - this->TopologicalSort(); + this->topologicalSort(); Node* source = this->_nodeMap[data]; - this->InitializeSingleSource(source); + this->initializeSingleSource(source); for (auto& node : this->_topologicalSortedNodeList) { for (auto& edge : this->_edgeMap[node]) { - this->Relax(edge); + this->relax(edge); } } } - vector Graph::GetDAGShortestPath(int data) + vector Graph::getDAGShortestPath(int data) { vector path = {}; Node* node = this->_nodeMap[data]; - this->GetShortestPath(node, path); + this->getShortestPath(node, path); reverse(path.begin(), path.end()); return path; } diff --git a/src/0003_graph/0011_single_source_shortest_path_dijkstra.cc b/src/0003_graph/0011_single_source_shortest_path_dijkstra.cc index e796e37..7904dbb 100644 --- a/src/0003_graph/0011_single_source_shortest_path_dijkstra.cc +++ b/src/0003_graph/0011_single_source_shortest_path_dijkstra.cc @@ -1,9 +1,9 @@ -#include "0011_SingleSourceShortestPathDijkstra.h" +#include "0011_single_source_shortest_path_dijkstra.h" #include #include using namespace std; -namespace SingleSourceShortestPathDijkstra +namespace single_source_shortest_path_dijkstra { Node::Node(int data) { @@ -19,8 +19,8 @@ namespace SingleSourceShortestPathDijkstra this->weight = weight; } - // Graph Private Member Methods - Node* Graph::MakeOrFindNode(int data) + // Graph private member methods + Node* Graph::makeOrFindNode(int data) { Node* node = nullptr; if (this->_nodeMap.find(data) == this->_nodeMap.end()) @@ -35,7 +35,7 @@ namespace SingleSourceShortestPathDijkstra return node; } - void Graph::InitializeSingleSource(Node* sourceNode) + void Graph::initializeSingleSource(Node* sourceNode) { for (auto& iterator : this->_nodeMap) { @@ -45,7 +45,7 @@ namespace SingleSourceShortestPathDijkstra sourceNode->distance = 0; } - void Graph::Relax(Edge* edge) + void Graph::relax(Edge* edge) { if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) { @@ -56,9 +56,9 @@ namespace SingleSourceShortestPathDijkstra } } - void Graph::Dijkstra(Node* source) + void Graph::dijkstra(Node* source) { - this->InitializeSingleSource(source); + this->initializeSingleSource(source); for (auto& node : this->_nodeMap) { @@ -72,41 +72,41 @@ namespace SingleSourceShortestPathDijkstra for (auto& edge : this->_edgeMap[nodeU]) { - this->Relax(edge); + this->relax(edge); } } } - void Graph::GetShortestPath(Node* node, vector& path) + void Graph::getShortestPath(Node* node, vector& path) { path.push_back(node->data); if (node->parent != nullptr) { - this->GetShortestPath(node->parent, path); + this->getShortestPath(node->parent, path); } } - // Graph Public Member Methods - void Graph::PushDirectedEdge(int dataU, int dataV, int weight) + // Graph public member methods + void Graph::pushDirectedEdge(int dataU, int dataV, int weight) { - Node* nodeU = this->MakeOrFindNode(dataU); - Node* nodeV = this->MakeOrFindNode(dataV); + Node* nodeU = this->makeOrFindNode(dataU); + Node* nodeV = this->makeOrFindNode(dataV); this->_adjlist[nodeU].push_back(nodeV); this->_edgeMap[nodeU].push_back(new Edge(nodeU, nodeV, weight)); } - void Graph::FindShortestPathDijkstra(int data) + void Graph::findShortestPathDijkstra(int data) { Node* source = this->_nodeMap[data]; - this->Dijkstra(source); + this->dijkstra(source); } - vector Graph::GetDijkstraShortestPath(int data) + vector Graph::getDijkstraShortestPath(int data) { vector path = {}; Node* node = this->_nodeMap[data]; - this->GetShortestPath(node, path); + this->getShortestPath(node, path); reverse(path.begin(), path.end()); return path; } diff --git a/src/0003_graph/0012_difference_constraints_shortest_paths.cc b/src/0003_graph/0012_difference_constraints_shortest_paths.cc index 8764ba6..767d259 100644 --- a/src/0003_graph/0012_difference_constraints_shortest_paths.cc +++ b/src/0003_graph/0012_difference_constraints_shortest_paths.cc @@ -1,8 +1,8 @@ -#include "0012_DifferenceConstraintsShortestPaths.h" +#include "0012_difference_constraints_shortest_paths.h" #include using namespace std; -namespace DifferenceConstraintsShortestPaths +namespace difference_constraints_shortest_paths { Node::Node(string data) { @@ -17,8 +17,8 @@ namespace DifferenceConstraintsShortestPaths this->weight = weight; } - // Graph Private Member Methods - Node* Graph::MakeOrFindNode(string data) + // Graph private member methods + Node* Graph::makeOrFindNode(string data) { Node* node = nullptr; if (this->_nodeMap.find(data) == this->_nodeMap.end()) @@ -33,16 +33,16 @@ namespace DifferenceConstraintsShortestPaths return node; } - void Graph::PushDirectedEdge(string dataU, string dataV, int weight) + void Graph::pushDirectedEdge(string dataU, string dataV, int weight) { - Node* nodeU = this->MakeOrFindNode(dataU); - Node* nodeV = this->MakeOrFindNode(dataV); + Node* nodeU = this->makeOrFindNode(dataU); + Node* nodeV = this->makeOrFindNode(dataV); this->_adjlist[nodeU].push_back(nodeV); this->_edgeList.push_back(new Edge(nodeU, nodeV, weight)); } - void Graph::InitializeSingleSource(Node* sourceNode) + void Graph::initializeSingleSource(Node* sourceNode) { for (auto& iterator : this->_nodeMap) { @@ -51,7 +51,7 @@ namespace DifferenceConstraintsShortestPaths sourceNode->distance = 0; } - void Graph::Relax(Edge* edge) + void Graph::relax(Edge* edge) { if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) { @@ -59,10 +59,10 @@ namespace DifferenceConstraintsShortestPaths } } - // Graph Public Member Methods - void Graph::PushAllDirectedEdges(vector> vectorA, vector vectorX, vector vectorB) + // Graph public member methods + void Graph::pushAllDirectedEdges(vector> vectorA, vector vectorX, vector vectorB) { - // Creating the Actual Graph + // creating the actual Graph string valueU = ""; string valueV = ""; int weight = 0; @@ -80,31 +80,31 @@ namespace DifferenceConstraintsShortestPaths } } weight = vectorB[i]; - this->PushDirectedEdge(valueU, valueV, weight); + this->pushDirectedEdge(valueU, valueV, weight); } - // Creating all the edges from the additional vertex + // creating all the edges from the additional vertex valueU = ""; valueV = ""; weight = 0; for (int i = 0; i < vectorX.size(); i++) { valueV = vectorX[i]; - this->PushDirectedEdge(valueU, valueV, weight); + this->pushDirectedEdge(valueU, valueV, weight); } } - bool Graph::FindDifferenceConstraintsSolutionBellmanFord() + bool Graph::findDifferenceConstraintsSolutionBellmanFord() { Node* source = this->_nodeMap[""]; - this->InitializeSingleSource(source); + this->initializeSingleSource(source); for (int i = 0; i < this->_nodeMap.size(); i++) { for (auto& edge : this->_edgeList) { - this->Relax(edge); + this->relax(edge); } } @@ -118,7 +118,7 @@ namespace DifferenceConstraintsShortestPaths return true; } - vector> Graph::GetDifferenceConstrtaintsSolution() + vector> Graph::getDifferenceConstrtaintsSolution() { vector> result; for (auto& node : this->_nodeMap) diff --git a/src/0003_graph/0013_all_pairs_shortest_paths_floyd_warshall.cc b/src/0003_graph/0013_all_pairs_shortest_paths_floyd_warshall.cc index ffd51d9..db2c7f3 100644 --- a/src/0003_graph/0013_all_pairs_shortest_paths_floyd_warshall.cc +++ b/src/0003_graph/0013_all_pairs_shortest_paths_floyd_warshall.cc @@ -1,11 +1,11 @@ -#include "0013_AllPairsShortestPathsFloydWarshall.h" +#include "0013_all_pairs_shortest_paths_floyd_warshall.h" #include using namespace std; -namespace AllPairsShortestPathsFloydWarshall +namespace all_pairs_shortest_paths_floyd_warshall { - // Graph Private Member Methods - void Graph::InitializeDistanceAndPredecessors() + // Graph private member methods + void Graph::initializeDistanceAndPredecessors() { this->_shortestPathMatrixFloydWarshall = this->_adjMatrix; @@ -25,18 +25,18 @@ namespace AllPairsShortestPathsFloydWarshall } } - void Graph::GetShortestPath(int source, int destination, vector& path) + void Graph::getShortestPath(int source, int destination, vector& path) { if (this->_predecessorMatrix[source - 1][destination - 1] != source) { int predecessor = this->_predecessorMatrix[source - 1][destination - 1]; - this->GetShortestPath(source, predecessor, path); + this->getShortestPath(source, predecessor, path); path.push_back(predecessor); } } - // Graph Public Member Methods - void Graph::CreateGraph(int noOfVertices) + // Graph public member methods + void Graph::createGraph(int noOfVertices) { this->_noOfVertices = noOfVertices; this->_adjMatrix = vector>(this->_noOfVertices, vector(this->_noOfVertices, INT_MAX)); @@ -55,14 +55,14 @@ namespace AllPairsShortestPathsFloydWarshall } } - void Graph::PushDirectedEdge(int valueU, int valueV, int weight) + void Graph::pushDirectedEdge(int valueU, int valueV, int weight) { this->_adjMatrix[valueU - 1][valueV - 1] = weight; } - void Graph::FindAllPairsShortestPathsFloydWarshallSolution() + void Graph::findAllPairsShortestPathsFloydWarshallSolution() { - this->InitializeDistanceAndPredecessors(); + this->initializeDistanceAndPredecessors(); for (int k = 0; k < this->_noOfVertices; k++) { @@ -82,7 +82,7 @@ namespace AllPairsShortestPathsFloydWarshall } } - vector> Graph::GetFloydWarshallShortestPath() + vector> Graph::getFloydWarshallShortestPath() { vector> result; for (int i = 0; i < this->_noOfVertices; i++) @@ -93,7 +93,7 @@ namespace AllPairsShortestPathsFloydWarshall { vector path = {}; path.push_back(i + 1); - this->GetShortestPath(i + 1, j + 1, path); + this->getShortestPath(i + 1, j + 1, path); path.push_back(j + 1); result.push_back(path); } diff --git a/src/0003_graph/0014_all_pairs_shortest_paths_johnson.cc b/src/0003_graph/0014_all_pairs_shortest_paths_johnson.cc index e9f9ab2..d068e68 100644 --- a/src/0003_graph/0014_all_pairs_shortest_paths_johnson.cc +++ b/src/0003_graph/0014_all_pairs_shortest_paths_johnson.cc @@ -1,8 +1,8 @@ -#include "0014_AllPairsShortestPathsJohnson.h" +#include "0014_all_pairs_shortest_paths_johnson.h" #include using namespace std; -namespace AllPairsShortestPathsJohnson +namespace all_pairs_shortest_paths_johnson { Node::Node(int data) { @@ -19,8 +19,8 @@ namespace AllPairsShortestPathsJohnson this->weight = weight; } - // Graph Private Member Methods - Node* Graph::MakeOrFindNode(int data) + // Graph private member methods + Node* Graph::makeOrFindNode(int data) { Node* node = nullptr; if (this->_nodeMap.find(data) == this->_nodeMap.end()) @@ -35,13 +35,13 @@ namespace AllPairsShortestPathsJohnson return node; } - void Graph::PushAugmentedDirectedEdges(Node* sourceNode, Node* nodeV, int weight) + void Graph::pushAugmentedDirectedEdges(Node* sourceNode, Node* nodeV, int weight) { this->_augmentedAdjlist[sourceNode].push_back(nodeV); this->_augmentedEdgeList.push_back(new Edge(sourceNode, nodeV, weight)); } - void Graph::InitializeSingleSource(Node* sourceNode) + void Graph::initializeSingleSource(Node* sourceNode) { for (auto& iterator : this->_nodeMap) { @@ -51,7 +51,7 @@ namespace AllPairsShortestPathsJohnson sourceNode->distance = 0; } - void Graph::RelaxBellmanFord(Edge* edge) + void Graph::relaxBellmanFord(Edge* edge) { if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) { @@ -60,15 +60,15 @@ namespace AllPairsShortestPathsJohnson } } - bool Graph::BellmanFord(Node* source) + bool Graph::bellmanFord(Node* source) { - this->InitializeSingleSource(source); + this->initializeSingleSource(source); for (int i = 0; i < this->_nodeMap.size() - 1; i++) { for (auto& edge : this->_augmentedEdgeList) { - this->RelaxBellmanFord(edge); + this->relaxBellmanFord(edge); } } @@ -82,7 +82,7 @@ namespace AllPairsShortestPathsJohnson return true; } - void Graph::RelaxDijkstra(Edge* edge) + void Graph::relaxDijkstra(Edge* edge) { if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) { @@ -93,9 +93,9 @@ namespace AllPairsShortestPathsJohnson } } - void Graph::Dijkstra(Node* source) + void Graph::dijkstra(Node* source) { - this->InitializeSingleSource(source); + this->initializeSingleSource(source); for (auto& node : this->_nodeMap) { @@ -109,26 +109,26 @@ namespace AllPairsShortestPathsJohnson for (auto& edge : this->_edgeMap[nodeU]) { - this->RelaxDijkstra(edge); + this->relaxDijkstra(edge); } } } - void Graph::GetShortestPath(int source, int destination, vector& path) + void Graph::getShortestPath(int source, int destination, vector& path) { if (this->_predecessorMatrix[source - 1][destination - 1] != source) { int predecessor = this->_predecessorMatrix[source - 1][destination - 1]; - this->GetShortestPath(source, predecessor, path); + this->getShortestPath(source, predecessor, path); path.push_back(predecessor); } } - // Graph Public Member Methods - void Graph::PushDirectedEdge(int dataU, int dataV, int weight) + // Graph public member methods + void Graph::pushDirectedEdge(int dataU, int dataV, int weight) { - Node* nodeU = this->MakeOrFindNode(dataU); - Node* nodeV = this->MakeOrFindNode(dataV); + Node* nodeU = this->makeOrFindNode(dataU); + Node* nodeV = this->makeOrFindNode(dataV); this->_adjlist[nodeU].push_back(nodeV); Edge* edge = new Edge(nodeU, nodeV, weight); @@ -136,26 +136,26 @@ namespace AllPairsShortestPathsJohnson this->_edgeList.push_back(edge); } - bool Graph::FindAllPairsShortestPathsJohnsonAlgorithm() + bool Graph::findAllPairsShortestPathsJohnsonAlgorithm() { - // Creating the graph G' + // creating the graph G' this->_augmentedAdjlist = this->_adjlist; this->_augmentedEdgeList = this->_edgeList; - // Source Node s + // source Node s Node* source = new Node(0); this->_nodeMap[0] = source; - // Creating all the augmented edges in G'.E = G.E U {(s, v) : v in G.V + // creating all the augmented edges in G'.E = G.E U {(s, v) : v in G.V for (auto& node : this->_nodeMap) { if (node.second != source) { - this->PushAugmentedDirectedEdges(source, node.second, 0); + this->pushAugmentedDirectedEdges(source, node.second, 0); } } - if (this->BellmanFord(source) == false) + if (this->bellmanFord(source) == false) { return false; } @@ -178,7 +178,7 @@ namespace AllPairsShortestPathsJohnson for (auto& iteratorU : this->_nodeMap) { Node* nodeU = iteratorU.second; - this->Dijkstra(nodeU); + this->dijkstra(nodeU); for (auto& iteratorV : this->_nodeMap) { Node* nodeV = iteratorV.second; @@ -190,12 +190,12 @@ namespace AllPairsShortestPathsJohnson } } - vector> Graph::GetAllPairsShortestPathsDistanceMatrix() + vector> Graph::getAllPairsShortestPathsDistanceMatrix() { return this->_shortestPathMatrix; } - vector> Graph::GetAllPairsShortestPathsPathMatrix() + vector> Graph::getAllPairsShortestPathsPathMatrix() { vector> result; for (int i = 0; i < this->_noOfVertices; i++) @@ -206,7 +206,7 @@ namespace AllPairsShortestPathsJohnson { vector path = {}; path.push_back(i + 1); - this->GetShortestPath(i + 1, j + 1, path); + this->getShortestPath(i + 1, j + 1, path); path.push_back(j + 1); result.push_back(path); } diff --git a/src/0003_graph/0015_maximum_flow_ford_fulkerson.cc b/src/0003_graph/0015_maximum_flow_ford_fulkerson.cc index dd8d48d..c975746 100644 --- a/src/0003_graph/0015_maximum_flow_ford_fulkerson.cc +++ b/src/0003_graph/0015_maximum_flow_ford_fulkerson.cc @@ -1,11 +1,11 @@ -#include "0015_MaximumFlowFordFulkerson.h" +#include "0015_maximum_flow_ford_fulkerson.h" #include using namespace std; -namespace MaximumFlowFordFulkerson +namespace maximum_flow_ford_fulkerson { - // Graph Private Member Methods - void Graph::ResolveAntiParallelEdges() + // Graph private member methods + void Graph::resolveAntiParallelEdges() { int countParallelEdges = 0; for (int i = 0; i < this->_noOfVertices; i++) @@ -19,12 +19,12 @@ namespace MaximumFlowFordFulkerson } } - // As i->j and j->i both edges has been counted, actual count is count = count / 2 + // as i->j and j->i both edges has been counted, actual count is count = count / 2 countParallelEdges /= 2; this->_flagParallelEdges = countParallelEdges > 0; - // If there are no anti-parallel edges, no need to modify the adjMatrix + // if there are no anti-parallel edges, no need to modify the adjMatrix if (!this->_flagParallelEdges) { return; @@ -32,7 +32,7 @@ namespace MaximumFlowFordFulkerson int newNoOfVertices = this->_noOfVertices + countParallelEdges; - // Modifying the adjMatrix + // modifying the adjMatrix for (auto& edge : this->_adjMatrix) { edge.resize(newNoOfVertices, 0); @@ -42,7 +42,7 @@ namespace MaximumFlowFordFulkerson this->_parent.resize(newNoOfVertices, -1); this->_adjMatrix.resize(newNoOfVertices, vector(newNoOfVertices, 0)); - // Removing the anti-parallel edges by adding new nodes + // removing the anti-parallel edges by adding new nodes for (int i = 0; i < this->_noOfVertices; i++) { for (int j = 0; j < this->_noOfVertices; j++) @@ -57,11 +57,11 @@ namespace MaximumFlowFordFulkerson } } - // Updating the total no of vertices after modifying the adjMatrix + // updating the total no of vertices after modifying the adjMatrix this->_noOfVertices = newNoOfVertices; } - void Graph::DepthFirstSearchVisit(int nodeU) + void Graph::depthFirstSearchVisit(int nodeU) { this->_visited[nodeU] = true; for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) @@ -69,28 +69,28 @@ namespace MaximumFlowFordFulkerson if (!this->_visited[nodeV] && this->_residualGraph[nodeU][nodeV] > 0) { this->_parent[nodeV] = nodeU; - this->DepthFirstSearchVisit(nodeV); + this->depthFirstSearchVisit(nodeV); } } } - bool Graph::DepthFirstSearch() + bool Graph::depthFirstSearch() { - // Resetting the visited values + // resetting the visited values fill(this->_visited.begin(), this->_visited.end(), false); - // Resetting the parent values + // resetting the parent values fill(this->_parent.begin(), this->_parent.end(), -1); - // Starting the DepthFirstSearch from the source vertex - this->DepthFirstSearchVisit(this->_source); + // starting the depthFirstSearch from the source vertex + this->depthFirstSearchVisit(this->_source); - // Returning the visited value of the sink vertex, initially it was set to false + // returning the visited value of the sink vertex, initially it was set to false return this->_visited[this->_sink]; } - // Graph Public Member Methods - void Graph::CreateGraph(int noOfVertices) + // Graph public member methods + void Graph::createGraph(int noOfVertices) { this->_noOfVertices = noOfVertices; this->_source = 0; @@ -102,23 +102,23 @@ namespace MaximumFlowFordFulkerson this->_visited = vector(this->_noOfVertices, false); } - void Graph::PushDirectedEdge(int valueU, int valueV, int capacity) + void Graph::pushDirectedEdge(int valueU, int valueV, int capacity) { this->_adjMatrix[valueU][valueV] = capacity; } - int Graph::FindMaximumFlowFordFulkerson() + int Graph::findMaximumFlowFordFulkerson() { - // Resolving all the parallel edges if present - this->ResolveAntiParallelEdges(); + // resolving all the parallel edges if present + this->resolveAntiParallelEdges(); this->_residualGraph = this->_adjMatrix; - // While there exists a path p from source to sink in the residual network G' - while (this->DepthFirstSearch()) + // while there exists a path p from source to sink in the residual network G' + while (this->depthFirstSearch()) { int augmentedPathFlow = INT_MAX; - // Calculating c'(p) = min{ c'(u,v) : (u,v) is in p } + // calculating c'(p) = min{ c'(u,v) : (u,v) is in p } for (int nodeV = this->_sink; nodeV > this->_source; nodeV = this->_parent[nodeV]) { int nodeU = this->_parent[nodeV]; diff --git a/src/0003_graph/0016_maximum_flow_edmonds_karp.cc b/src/0003_graph/0016_maximum_flow_edmonds_karp.cc index 627a2a6..baeb840 100644 --- a/src/0003_graph/0016_maximum_flow_edmonds_karp.cc +++ b/src/0003_graph/0016_maximum_flow_edmonds_karp.cc @@ -1,12 +1,12 @@ -#include "0016_MaximumFlowEdmondsKarp.h" +#include "0016_maximum_flow_edmonds_karp.h" #include #include using namespace std; -namespace MaximumFlowEdmondsKarp +namespace maximum_flow_edmonds_karp { - // Graph Private Member Methods - void Graph::ResolveAntiParallelEdges() + // Graph private member methods + void Graph::resolveAntiParallelEdges() { int countParallelEdges = 0; for (int i = 0; i < this->_noOfVertices; i++) @@ -20,12 +20,12 @@ namespace MaximumFlowEdmondsKarp } } - // As i->j and j->i both edges has been counted, actual count is count = count / 2 + // as i->j and j->i both edges has been counted, actual count is count = count / 2 countParallelEdges /= 2; this->_flagParallelEdges = countParallelEdges > 0; - // If there are no anti-parallel edges, no need to modify the adjMatrix + // if there are no anti-parallel edges, no need to modify the adjMatrix if (!this->_flagParallelEdges) { return; @@ -33,7 +33,7 @@ namespace MaximumFlowEdmondsKarp int newNoOfVertices = this->_noOfVertices + countParallelEdges; - // Modifying the adjMatrix + // modifying the adjMatrix for (auto& edge : this->_adjMatrix) { edge.resize(newNoOfVertices, 0); @@ -43,7 +43,7 @@ namespace MaximumFlowEdmondsKarp this->_parent.resize(newNoOfVertices, -1); this->_adjMatrix.resize(newNoOfVertices, vector(newNoOfVertices, 0)); - // Removing the anti-parallel edges by adding new nodes + // removing the anti-parallel edges by adding new nodes for (int i = 0; i < this->_noOfVertices; i++) { for (int j = 0; j < this->_noOfVertices; j++) @@ -58,16 +58,16 @@ namespace MaximumFlowEdmondsKarp } } - // Updating the total no of vertices after modifying the adjMatrix + // updating the total no of vertices after modifying the adjMatrix this->_noOfVertices = newNoOfVertices; } - bool Graph::BreadthFirstSearch() + bool Graph::breadthFirstSearch() { - // Resetting the visited values + // resetting the visited values fill(this->_visited.begin(), this->_visited.end(), false); - // Resetting the parent values + // resetting the parent values fill(this->_parent.begin(), this->_parent.end(), -1); queue nodeQueue; @@ -90,12 +90,12 @@ namespace MaximumFlowEdmondsKarp } } - // Returning the visited value of the sink vertex, initially it was set to false + // returning the visited value of the sink vertex, initially it was set to false return this->_visited[this->_sink]; } - // Graph Public Member Methods - void Graph::CreateGraph(int noOfVertices) + // Graph public member methods + void Graph::createGraph(int noOfVertices) { this->_noOfVertices = noOfVertices; this->_source = 0; @@ -107,23 +107,23 @@ namespace MaximumFlowEdmondsKarp this->_visited = vector(this->_noOfVertices, false); } - void Graph::PushDirectedEdge(int valueU, int valueV, int capacity) + void Graph::pushDirectedEdge(int valueU, int valueV, int capacity) { this->_adjMatrix[valueU][valueV] = capacity; } - int Graph::FindMaximumFlowEdmondsKarp() + int Graph::findMaximumFlowEdmondsKarp() { - // Resolving all the parallel edges if present - this->ResolveAntiParallelEdges(); + // resolving all the parallel edges if present + this->resolveAntiParallelEdges(); this->_residualGraph = this->_adjMatrix; - // While there exists a path p from source to sink in the residual network G' - while (this->BreadthFirstSearch()) + // while there exists a path p from source to sink in the residual network G' + while (this->breadthFirstSearch()) { int augmentedPathFlow = INT_MAX; - // Calculating c'(p) = min{ c'(u,v) : (u,v) is in p } + // calculating c'(p) = min{ c'(u,v) : (u,v) is in p } for (int nodeV = this->_sink; nodeV > this->_source; nodeV = this->_parent[nodeV]) { int nodeU = this->_parent[nodeV]; diff --git a/src/0003_graph/0017_maximum_bipartite_matching.cc b/src/0003_graph/0017_maximum_bipartite_matching.cc index 7c55ce6..30374cd 100644 --- a/src/0003_graph/0017_maximum_bipartite_matching.cc +++ b/src/0003_graph/0017_maximum_bipartite_matching.cc @@ -1,12 +1,12 @@ -#include "0017_MaximumBipartiteMatching.h" +#include "0017_maximum_bipartite_matching.h" #include #include using namespace std; -namespace MaximumBipartiteMatching +namespace maximum_bipartite_matching { - // Graph Private Member Methods - void Graph::ResolveAntiParallelEdges() + // Graph private member methods + void Graph::resolveAntiParallelEdges() { int countParallelEdges = 0; for (int i = 0; i < this->_noOfVertices; i++) @@ -20,12 +20,12 @@ namespace MaximumBipartiteMatching } } - // As i->j and j->i both edges has been counted, actual count is count = count / 2 + // as i->j and j->i both edges has been counted, actual count is count = count / 2 countParallelEdges /= 2; this->_flagParallelEdges = countParallelEdges > 0; - // If there are no anti-parallel edges, no need to modify the adjMatrix + // if there are no anti-parallel edges, no need to modify the adjMatrix if (!this->_flagParallelEdges) { return; @@ -33,7 +33,7 @@ namespace MaximumBipartiteMatching int newNoOfVertices = this->_noOfVertices + countParallelEdges; - // Modifying the adjMatrix + // modifying the adjMatrix for (auto& edge : this->_adjMatrix) { edge.resize(newNoOfVertices, 0); @@ -43,7 +43,7 @@ namespace MaximumBipartiteMatching this->_parent.resize(newNoOfVertices, -1); this->_adjMatrix.resize(newNoOfVertices, vector(newNoOfVertices, 0)); - // Removing the anti-parallel edges by adding new nodes + // removing the anti-parallel edges by adding new nodes for (int i = 0; i < this->_noOfVertices; i++) { for (int j = 0; j < this->_noOfVertices; j++) @@ -58,14 +58,14 @@ namespace MaximumBipartiteMatching } } - // Updating the total no of vertices after modifying the adjMatrix + // updating the total no of vertices after modifying the adjMatrix this->_noOfVertices = newNoOfVertices; } - // This method is used to color the vertices of the graph to determine if the given graph is bipartite or not - void Graph::ColorGraph() + // this method is used to color the vertices of the graph to determine if the given graph is bipartite or not + void Graph::colorGraph() { - // Color of all the vertices are initialised to WHITE + // color of all the vertices are initialised to WHITE fill(this->_color.begin(), this->_color.end(), WHITE); // Queue to hold the vertices @@ -73,41 +73,41 @@ namespace MaximumBipartiteMatching for (int node = 0; node < this->_noOfVertices; node++) { - // Check if the node is already not colored + // check if the node is already not colored if (this->_color[node] == WHITE) { - // The color of the node is set to RED + // the color of the node is set to RED this->_color[node] = RED; - // The node is inserted into the queue + // the node is inserted into the queue nodeQueue.push(node); - // Using BFS method to color all the vertices + // using BFS method to color all the vertices while (!nodeQueue.empty()) { int nodeU = nodeQueue.front(); nodeQueue.pop(); - // Iterating over G.Adj[nodeU] + // iterating over G.adj[nodeU] for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) { - // As there are no self loops, continue + // as there are no self loops, continue if (nodeU == nodeV) { continue; } - // Check if there is an edge u --> v and nodeV is not colored yet + // check if there is an edge u --> v and nodeV is not colored yet else if (this->_residualGraph[nodeU][nodeV] != 0 && this->_color[nodeV] == WHITE) { - // Set the color of nodeV opposite of nodeU + // set the color of nodeV opposite of nodeU this->_color[nodeV] = 1 - this->_color[nodeU]; - // Insert the nodeV into the queue + // insert the nodeV into the queue nodeQueue.push(nodeV); } - // Check if there is an edge u --> v and nodeV is of same color as nodeU + // check if there is an edge u --> v and nodeV is of same color as nodeU else if (this->_residualGraph[nodeU][nodeV] != 0 && this->_color[nodeV] == this->_color[nodeU]) { - // Set the _isBipartite flag to false and return + // set the _isBipartite flag to false and return this->_isBipartite = false; return; } @@ -116,18 +116,18 @@ namespace MaximumBipartiteMatching } } - // If the above operation completes without returning yet that indicates the graph is bipartite - // Set the _isBipartite flag to true and return + // if the above operation completes without returning yet that indicates the graph is bipartite + // set the _isBipartite flag to true and return this->_isBipartite = true; return; } - // This method is used to create the additional edges + // this method is used to create the additional edges // from the source vertex to the RED colored vertices and // from the BLUE colored vertices to the sink vertex - void Graph::AddAdditionalEdges() + void Graph::addAdditionalEdges() { - // Resizing the residual graph to accomodate space for the new edges + // resizing the residual graph to accomodate space for the new edges for (auto& edge : this->_residualGraph) { edge.resize(this->_noOfVertices, 0); @@ -138,16 +138,16 @@ namespace MaximumBipartiteMatching this->_color.resize(this->_noOfVertices, WHITE); this->_residualGraph.resize(this->_noOfVertices, vector(this->_noOfVertices, 0)); - // Creating the additional edges + // creating the additional edges for (int node = 0; node < this->_source; node++) { - // From source vertex --> RED colored vertices + // from source vertex --> RED colored vertices if (this->_color[node] == RED) { this->_residualGraph[this->_source][node] = 1; } - // From BLUE colored vertices --> sink vertex + // from BLUE colored vertices --> sink vertex else if (this->_color[node] == BLUE) { this->_residualGraph[node][this->_sink] = 1; @@ -155,13 +155,13 @@ namespace MaximumBipartiteMatching } } - // Implementation of BreadthFirstSearch for EdmondsKarp algorithm to find the path from source to sink - bool Graph::BreadthFirstSearch() + // implementation of breadthFirstSearch for edmondsKarp algorithm to find the path from source to sink + bool Graph::breadthFirstSearch() { - // Resetting the visited values + // resetting the visited values fill(this->_visited.begin(), this->_visited.end(), false); - // Resetting the parent values + // resetting the parent values fill(this->_parent.begin(), this->_parent.end(), -1); queue nodeQueue; @@ -184,12 +184,12 @@ namespace MaximumBipartiteMatching } } - // Returning the visited value of the sink vertex, initially it was set to false + // returning the visited value of the sink vertex, initially it was set to false return this->_visited[this->_sink]; } - // Graph Public Member Methods - void Graph::CreateGraph(int noOfVertices) + // Graph public member methods + void Graph::createGraph(int noOfVertices) { this->_noOfVertices = noOfVertices; this->_maximumFlow = 0; @@ -200,32 +200,32 @@ namespace MaximumBipartiteMatching this->_color = vector(this->_noOfVertices, WHITE); } - void Graph::PushDirectedEdge(int valueU, int valueV) + void Graph::pushDirectedEdge(int valueU, int valueV) { this->_adjMatrix[valueU][valueV] = 1; } - int Graph::FindMaximumBipartiteMatching() + int Graph::findMaximumBipartiteMatching() { - // Resolving all the parallel edges if present - this->ResolveAntiParallelEdges(); + // resolving all the parallel edges if present + this->resolveAntiParallelEdges(); this->_residualGraph = this->_adjMatrix; - this->ColorGraph(); + this->colorGraph(); this->_source = this->_noOfVertices; this->_noOfVertices++; this->_sink = this->_noOfVertices; this->_noOfVertices++; - this->AddAdditionalEdges(); + this->addAdditionalEdges(); - // While there exists a path p from source to sink in the residual network G' - while (this->BreadthFirstSearch()) + // while there exists a path p from source to sink in the residual network G' + while (this->breadthFirstSearch()) { int augmentedPathFlow = 1; - // No need to find the minimum amount of augmentedPathFlow as like standard EdmondsKarp algorithm + // no need to find the minimum amount of augmentedPathFlow as like standard edmondsKarp algorithm // as here capacity of each edges is 1 for (int nodeV = this->_sink; nodeV != this->_source; nodeV = this->_parent[nodeV]) { @@ -239,14 +239,14 @@ namespace MaximumBipartiteMatching return this->_maximumFlow; } - // This method is used for finding the matchings - vector> Graph::GetMatchings() + // this method is used for finding the matchings + vector> Graph::getMatchings() { for (int nodeU = 0; nodeU < this->_adjMatrix.size(); nodeU++) { for (int nodeV = 0; nodeV < this->_adjMatrix.size(); nodeV++) { - // Check if the nodeU and nodeV are not source or sink + // check if the nodeU and nodeV are not source or sink // and there is a flow of 1 unit from nodeU --> nodeV // which means nodeU --> nodeV is being used for the maximum flow (maximum matching) if ((nodeU != this->_source || nodeU != this->_sink || nodeV != this->_source || nodeV != this->_sink) diff --git a/src/0003_graph/0018_maximum_flow_goldberg_generic_push_relabel.cc b/src/0003_graph/0018_maximum_flow_goldberg_generic_push_relabel.cc index 63c1475..7127abc 100644 --- a/src/0003_graph/0018_maximum_flow_goldberg_generic_push_relabel.cc +++ b/src/0003_graph/0018_maximum_flow_goldberg_generic_push_relabel.cc @@ -1,21 +1,21 @@ -#include "0018_MaximumFlowGoldbergGenericPushRelabel.h" +#include "0018_maximum_flow_goldberg_generic_push_relabel.h" #include using namespace std; -namespace MaximumFlowGoldbergGenericPushRelabel +namespace maximum_flow_goldberg_generic_push_relabel { - // Graph Private Member Methods + // Graph private member methods - // Initializes Pre-Flow in the given Flow Network - void Graph::InitializePreflow() + // initializes pre-flow in the given flow network + void Graph::initializePreflow() { - // The height of source is set to highest possible height value + // the height of source is set to highest possible height value this->_height[this->_source] = this->_noOfVertices; - // Iterating over all the vertices + // iterating over all the vertices for (int i = 0; i < this->_noOfVertices; i++) { - // For the all the edges (source, v) + // for the all the edges (source, v) if (this->_residualGraph[this->_source][i] > 0) { // v.excessFlow = capacity(source, v) @@ -24,32 +24,32 @@ namespace MaximumFlowGoldbergGenericPushRelabel // source.excessFlow = source.excessFlow - capacity(source, v) this->_excessFlow[this->_source] = this->_excessFlow[this->_source] - this->_residualGraph[this->_source][i]; - // Adjusting the flow and reverse flow along source->v and v->source respectively + // adjusting the flow and reverse flow along source->v and v->source respectively this->_residualGraph[i][this->_source] = this->_residualGraph[this->_source][i]; this->_residualGraph[this->_source][i] = 0; } } } - // Checks if there is any vertex which has excess flow - bool Graph::CheckOverFlow() + // checks if there is any vertex which has excess flow + bool Graph::checkOverFlow() { - // Iterating over all of the vertices + // iterating over all of the vertices for (int i = 0; i < this->_noOfVertices; i++) { - // Checks if the current vertex is not any special vertex like source, sink + // checks if the current vertex is not any special vertex like source, sink // and also if there is excess flow in the current vertex and it is already not present in the queue if (i!=this->_source && i!=this->_sink && this->_excessFlow[i] > 0 && this->_visited[i] == false) { - // Insert the current vertex into the queue + // insert the current vertex into the queue this->_nodeQueue.push(i); - // Mark it as visited, so until it leaves the queue it is not inserted again even if all the excess flow is neutralized + // mark it as visited, so until it leaves the queue it is not inserted again even if all the excess flow is neutralized this->_visited[i] = true; } } - // Checks if there is no vertex having excess flow then returns false + // checks if there is no vertex having excess flow then returns false if (this->_nodeQueue.empty()) { return false; @@ -58,16 +58,16 @@ namespace MaximumFlowGoldbergGenericPushRelabel return true; } - // Pushes the flow from nodeU to its neighbour vertices - bool Graph::Push(int nodeU) + // pushes the flow from nodeU to its neighbour vertices + bool Graph::push(int nodeU) { int nodeV = -1; int minimumFlow = INT_MAX; - // Iterating over all the vertices + // iterating over all the vertices for (int i = 0; i < this->_noOfVertices; i++) { - // For G'.Adj[nodeU] select the vertex if edge (nodeU, i) is non-saturated and height[nodeU] == height[i] + 1 + // for G'.adj[nodeU] select the vertex if edge (nodeU, i) is non-saturated and height[nodeU] == height[i] + 1 if (this->_residualGraph[nodeU][i] > 0 && this->_height[nodeU] == this->_height[i] + 1) { nodeV = i; @@ -75,51 +75,51 @@ namespace MaximumFlowGoldbergGenericPushRelabel } } - // Checks if any neighbour vertex found having non-saturated edge + // checks if any neighbour vertex found having non-saturated edge if (nodeV != -1) { - // Calculate the flow amount to be added along the edge and excess flow subtracted from nodeU + // calculate the flow amount to be added along the edge and excess flow subtracted from nodeU minimumFlow = min(this->_residualGraph[nodeU][nodeV], this->_excessFlow[nodeU]); - // Adjust the flow and the reverse flow along (nodeU, nodeV) + // adjust the flow and the reverse flow along (nodeU, nodeV) this->_residualGraph[nodeU][nodeV] = this->_residualGraph[nodeU][nodeV] - minimumFlow; this->_residualGraph[nodeV][nodeU] = this->_residualGraph[nodeV][nodeU] + minimumFlow; - // Adjust the excess flows in nodeU and nodeV + // adjust the excess flows in nodeU and nodeV this->_excessFlow[nodeU] = this->_excessFlow[nodeU] - minimumFlow; this->_excessFlow[nodeV] = this->_excessFlow[nodeV] + minimumFlow; - // Return that the Push operation is successful + // return that the push operation is successful return true; } - // Return that the Push operation is not successful + // return that the push operation is not successful return false; } - // Relabels height of vertex nodeU when there are outgoing non-saturated edges available - void Graph::Relabel(int nodeU) + // relabels height of vertex nodeU when there are outgoing non-saturated edges available + void Graph::relabel(int nodeU) { int minimumHeight = INT_MAX; - // Iterating over all the vertices + // iterating over all the vertices for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) { - // For G'.Adj[nodeU] select for which nodeV, height[nodeU] <= height[nodeV] + // for G'.adj[nodeU] select for which nodeV, height[nodeU] <= height[nodeV] if (this->_residualGraph[nodeU][nodeV] > 0 && this->_height[nodeU] <= this->_height[nodeV]) { - // Get the minimum height among all these G'.Adj[nodeU] + // get the minimum height among all these G'.adj[nodeU] minimumHeight = min(minimumHeight, this->_height[nodeV]); } } - // Set height[nodeU] + // set height[nodeU] this->_height[nodeU] = minimumHeight + 1; } - // Graph Public Member Methods - void Graph::CreateGraph(int noOfVertices) + // Graph public member methods + void Graph::createGraph(int noOfVertices) { this->_noOfVertices = noOfVertices; this->_source = 0; @@ -131,42 +131,42 @@ namespace MaximumFlowGoldbergGenericPushRelabel this->_visited = vector(this->_noOfVertices, false); } - void Graph::PushDirectedEdge(int valueU, int valueV, int capacity) + void Graph::pushDirectedEdge(int valueU, int valueV, int capacity) { this->_adjMatrix[valueU][valueV] = capacity; } - int Graph::FindMaximumFlowGoldbergGenericPushRelabel() + int Graph::findMaximumFlowGoldbergGenericPushRelabel() { this->_residualGraph = this->_adjMatrix; - // Initialize Pre-flow - this->InitializePreflow(); + // initialize pre-flow + this->initializePreflow(); - // Checks if there is some vertices which have excess flow - while (this->CheckOverFlow()) + // checks if there is some vertices which have excess flow + while (this->checkOverFlow()) { - // Get the vertex + // get the vertex int nodeU = this->_nodeQueue.front(); - // Checks if the Push operation is successful - if (this->Push(nodeU)) + // checks if the push operation is successful + if (this->push(nodeU)) { - // Then remove the vertex from queue and set visited[nodeU] = true - // so that on next CheckOverFlow() method call this vertex can be discovered if it still has some excess flow + // then remove the vertex from queue and set visited[nodeU] = true + // so that on next checkOverFlow() method call this vertex can be discovered if it still has some excess flow this->_nodeQueue.pop(); this->_visited[nodeU] = false; } - // If the Push operation is not successful + // if the push operation is not successful else { - // Then Relabel nodeU without removing it from the queue - this->Relabel(nodeU); + // then relabel nodeU without removing it from the queue + this->relabel(nodeU); } } - // Return the excess flow in the sink vertex which is actually the maximum flow along the given flow network + // return the excess flow in the sink vertex which is actually the maximum flow along the given flow network return this->_excessFlow[this->_sink]; } } \ No newline at end of file diff --git a/src/0003_graph/0019_maximum_flow_relabel_to_front.cc b/src/0003_graph/0019_maximum_flow_relabel_to_front.cc index 034f5bf..a9b72eb 100644 --- a/src/0003_graph/0019_maximum_flow_relabel_to_front.cc +++ b/src/0003_graph/0019_maximum_flow_relabel_to_front.cc @@ -1,22 +1,22 @@ -#include "0019_MaximumFlowRelabelToFront.h" +#include "0019_maximum_flow_relabel_to_front.h" #include #include using namespace std; -namespace MaximumFlowRelabelToFront +namespace maximum_flow_relabel_to_front { - // Graph Private Member Methods + // Graph private member methods - // Initializes Pre-Flow in the given Flow Network - void Graph::InitializePreflow() + // initializes pre-flow in the given flow network + void Graph::initializePreflow() { - // The height of source is set to highest possible height value + // the height of source is set to highest possible height value this->_height[this->_source] = this->_noOfVertices; - // Iterating over all the vertices + // iterating over all the vertices for (int i = 0; i < this->_noOfVertices; i++) { - // For the all the edges (source, v) + // for the all the edges (source, v) if (this->_residualGraph[this->_source][i] > 0) { // v.excessFlow = capacity(source, v) @@ -25,89 +25,89 @@ namespace MaximumFlowRelabelToFront // source.excessFlow = source.excessFlow - capacity(source, v) this->_excessFlow[this->_source] = this->_excessFlow[this->_source] - this->_residualGraph[this->_source][i]; - // Adjusting the flow and reverse flow along source->v and v->source respectively + // adjusting the flow and reverse flow along source->v and v->source respectively this->_residualGraph[i][this->_source] = this->_residualGraph[this->_source][i]; this->_residualGraph[this->_source][i] = 0; } } } - // Discharges the excess flow from nodeU - void Graph::Discharge(int nodeU) + // discharges the excess flow from nodeU + void Graph::discharge(int nodeU) { - // Check if excess flow of nodeU is > 0 + // check if excess flow of nodeU is > 0 while (this->_excessFlow[nodeU] > 0) { - // Falg to check if any amount of excess flow is pushed to any neighbour vertex + // falg to check if any amount of excess flow is pushed to any neighbour vertex bool hasPushed = false; - // Iterating over all of the vertices + // iterating over all of the vertices for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) { - // For G'.Adj[nodeU] check if edge (nodeU, nodeV) is admissible + // for G'.adj[nodeU] check if edge (nodeU, nodeV) is admissible if (this->_residualGraph[nodeU][nodeV] > 0 && this->_height[nodeU] == 1 + this->_height[nodeV]) { - // Push excess flow along the admissible edge (nodeU, nodeV) - this->Push(nodeU, nodeV); - // Set the hasPushed flag to true + // push excess flow along the admissible edge (nodeU, nodeV) + this->push(nodeU, nodeV); + // set the hasPushed flag to true hasPushed = true; - // Check if there is no excess flow left in nodeU then no need to check any more admissible edge going from nodeU + // check if there is no excess flow left in nodeU then no need to check any more admissible edge going from nodeU if (this->_excessFlow[nodeU] == 0) { - // Then break from iterating over G'.Adj[nodeU] + // then break from iterating over G'.adj[nodeU] break; } } } - // Check if Push operation is not done yet + // check if push operation is not done yet if (!hasPushed) { - // Then it indicates that all the outgoing edges from nodeU are inadmissible - // so perform the Relabel operation on nodeU - this->Relabel(nodeU); + // then it indicates that all the outgoing edges from nodeU are inadmissible + // so perform the relabel operation on nodeU + this->relabel(nodeU); } } } - // Pushes the flow from nodeU to its neighbour vertices - void Graph::Push(int nodeU, int nodeV) + // pushes the flow from nodeU to its neighbour vertices + void Graph::push(int nodeU, int nodeV) { - // Calculate the flow amount to be added along the edge and excess flow subtracted from nodeU + // calculate the flow amount to be added along the edge and excess flow subtracted from nodeU int minimumFlow = min(this->_residualGraph[nodeU][nodeV], this->_excessFlow[nodeU]); - // Adjust the flow and the reverse flow along (nodeU, nodeV) + // adjust the flow and the reverse flow along (nodeU, nodeV) this->_residualGraph[nodeU][nodeV] = this->_residualGraph[nodeU][nodeV] - minimumFlow; this->_residualGraph[nodeV][nodeU] = this->_residualGraph[nodeV][nodeU] + minimumFlow; - // Adjust the excess flows in nodeU and nodeV + // adjust the excess flows in nodeU and nodeV this->_excessFlow[nodeU] = this->_excessFlow[nodeU] - minimumFlow; this->_excessFlow[nodeV] = this->_excessFlow[nodeV] + minimumFlow; } - // Relabels height of vertex nodeU when there are outgoing non-saturated edges available - void Graph::Relabel(int nodeU) + // relabels height of vertex nodeU when there are outgoing non-saturated edges available + void Graph::relabel(int nodeU) { int minimumHeight = INT_MAX; - // Iterating over all the vertices + // iterating over all the vertices for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) { - // For G'.Adj[nodeU] select for which nodeV, height[nodeU] <= height[nodeV] + // for G'.adj[nodeU] select for which nodeV, height[nodeU] <= height[nodeV] if (this->_residualGraph[nodeU][nodeV] > 0 && this->_height[nodeU] <= this->_height[nodeV]) { - // Get the minimum height among all these G'.Adj[nodeU] + // get the minimum height among all these G'.adj[nodeU] minimumHeight = min(minimumHeight, this->_height[nodeV]); } } - // Set height[nodeU] + // set height[nodeU] this->_height[nodeU] = minimumHeight + 1; } - // Graph Public Member Methods - void Graph::CreateGraph(int noOfVertices) + // Graph public member methods + void Graph::createGraph(int noOfVertices) { this->_noOfVertices = noOfVertices; this->_source = 0; @@ -119,19 +119,19 @@ namespace MaximumFlowRelabelToFront this->_visited = vector(this->_noOfVertices, false); } - void Graph::PushDirectedEdge(int valueU, int valueV, int capacity) + void Graph::pushDirectedEdge(int valueU, int valueV, int capacity) { this->_adjMatrix[valueU][valueV] = capacity; } - int Graph::FindMaximumFlowRelabelToFront() + int Graph::findMaximumFlowRelabelToFront() { this->_residualGraph = this->_adjMatrix; - // Initialize Pre-flow - this->InitializePreflow(); + // initialize pre-flow + this->initializePreflow(); - // Make the list L = G.V - {source, sink} + // make the list L = G.V - {source, sink} for (int i = 0; i < this->_noOfVertices; i++) { if (i != this->_source && i != this->_sink) @@ -140,30 +140,30 @@ namespace MaximumFlowRelabelToFront } } - // Set current vertex = L.head + // set current vertex = L.head list::iterator nodeUiterator = this->_nodeList.begin(); - // Iterate over all of the elements in the list L + // iterate over all of the elements in the list L while (nodeUiterator != this->_nodeList.end()) { - // Get the height of current vertex + // get the height of current vertex int oldHeight = this->_height[*nodeUiterator]; - // Discharge the excess flow of current vertex - this->Discharge(*nodeUiterator); + // discharge the excess flow of current vertex + this->discharge(*nodeUiterator); - // Check if the height of current vertex increases which means the current vertex got relabeled + // check if the height of current vertex increases which means the current vertex got relabeled if (this->_height[*nodeUiterator] > oldHeight) { - // Then move current vertex to the front of the list L + // then move current vertex to the front of the list L this->_nodeList.splice(this->_nodeList.begin(), this->_nodeList, nodeUiterator); } - // Go to the next vertex of current vertex in L + // go to the next vertex of current vertex in L nodeUiterator++; } - // Return the excess flow in the sink vertex which is actually the maximum flow along the given flow network + // return the excess flow in the sink vertex which is actually the maximum flow along the given flow network return this->_excessFlow[this->_sink]; } } \ No newline at end of file diff --git a/src/0003_graph/CMakeLists.txt b/src/0003_graph/CMakeLists.txt index 02f8a77..9daf4b5 100644 --- a/src/0003_graph/CMakeLists.txt +++ b/src/0003_graph/CMakeLists.txt @@ -1,24 +1,24 @@ # Specify the source files set(0003GRAPH_SOURCES - 0001_BreadthFirstSearch.cc - 0002_DepthFirstSearch.cc - 0003_TopologicalSort.cc - 0004_StronglyConnectedComponents.cc - 0005_HamiltonianPathAndCycle.cc - 0006_EulerianPathAndCircuit.cc - 0007_MinimumSpanningTreeKruskalAlgorithm.cc - 0008_MinimumSpanningTreePrimAlgorithm.cc - 0009_SingleSourceShortestPathBellmanFord.cc - 0010_DirectedAcyclicGraphShortestPath.cc - 0011_SingleSourceShortestPathDijkstra.cc - 0012_DifferenceConstraintsShortestPaths.cc - 0013_AllPairsShortestPathsFloydWarshall.cc - 0014_AllPairsShortestPathsJohnson.cc - 0015_MaximumFlowFordFulkerson.cc - 0016_MaximumFlowEdmondsKarp.cc - 0017_MaximumBipartiteMatching.cc - 0018_MaximumFlowGoldbergGenericPushRelabel.cc - 0019_MaximumFlowRelabelToFront.cc + 0001_breadth_first_search.cc + 0002_depth_first_search.cc + 0003_topological_sort.cc + 0004_strongly_connected_components.cc + 0005_hamiltonian_path_and_cycle.cc + 0006_eulerian_path_and_circuit.cc + 0007_minimum_spanning_tree_kruskal_algorithm.cc + 0008_minimum_spanning_tree_prim_algorithm.cc + 0009_single_source_shortest_path_bellman_ford.cc + 0010_directed_acyclic_graph_shortest_path.cc + 0011_single_source_shortest_path_dijkstra.cc + 0012_difference_constraints_shortest_paths.cc + 0013_all_pairs_shortest_paths_floyd_warshall.cc + 0014_all_pairs_shortest_paths_johnson.cc + 0015_maximum_flow_ford_fulkerson.cc + 0016_maximum_flow_edmonds_karp.cc + 0017_maximum_bipartite_matching.cc + 0018_maximum_flow_goldberg_generic_push_relabel.cc + 0019_maximum_flow_relabel_to_front.cc ) diff --git a/src/0003_graph/headers/0001_breadth_first_search.h b/src/0003_graph/headers/0001_breadth_first_search.h index ba7aec8..73a0f21 100644 --- a/src/0003_graph/headers/0001_breadth_first_search.h +++ b/src/0003_graph/headers/0001_breadth_first_search.h @@ -7,7 +7,7 @@ #include using namespace std; -namespace BreadthFirstSearch +namespace breadth_first_search { enum color { WHITE, GRAY, BLACK }; class Node @@ -25,11 +25,11 @@ namespace BreadthFirstSearch private: map> _adjlist; map _nodeMap; - Node* MakeOrFindNode(int value); - void BreadthFirstSearch(Node* node); + Node* makeOrFindNode(int value); + void breadthFirstSearch(Node* node); public: - void PushUndirectedEdge(int valueU, int valueV); + void pushUndirectedEdge(int valueU, int valueV); void BFS(int value); - vector> ShowBFSResult(); + vector> showBFSResult(); }; } \ No newline at end of file diff --git a/src/0003_graph/headers/0002_depth_first_search.h b/src/0003_graph/headers/0002_depth_first_search.h index e376295..1137c0c 100644 --- a/src/0003_graph/headers/0002_depth_first_search.h +++ b/src/0003_graph/headers/0002_depth_first_search.h @@ -6,7 +6,7 @@ #include using namespace std; -namespace DepthFirstSearch +namespace depth_first_search { enum color { WHITE, GRAY, BLACK }; @@ -27,11 +27,11 @@ namespace DepthFirstSearch int _time; map> _adjlist; map _nodeMap; - Node* MakeOrFindNode(int value); - void DepthFirstSearch(Node* Node); + Node* makeOrFindNode(int value); + void depthFirstSearch(Node* Node); public: - void PushDirectedEdge(int valueU, int valueV); + void pushDirectedEdge(int valueU, int valueV); void DFS(); - vector>> ShowDFSResult(); + vector>> showDFSResult(); }; } \ No newline at end of file diff --git a/src/0003_graph/headers/0003_topological_sort.h b/src/0003_graph/headers/0003_topological_sort.h index 441d7d1..5373d41 100644 --- a/src/0003_graph/headers/0003_topological_sort.h +++ b/src/0003_graph/headers/0003_topological_sort.h @@ -6,7 +6,7 @@ #include using namespace std; -namespace TopologicalSort +namespace topological_sort { enum color { WHITE, GRAY, BLACK }; @@ -30,13 +30,13 @@ namespace TopologicalSort map> _adjlist; map _nodeMap; list _topologicalSortedNodeList; - Node* MakeOrFindNode(int value); - void DepthFirstSearch(Node* DFSNode); + Node* makeOrFindNode(int value); + void depthFirstSearch(Node* dFSNode); public: - void PushDirectedEdge(int valueU, int valueV); - void PushSingleNode(int valueU); - void TopologicalSort(); - void KahnTopologicalSort(); - vector>> ShowTopologicalSortResult(); + void pushDirectedEdge(int valueU, int valueV); + void pushSingleNode(int valueU); + void topologicalSort(); + void kahnTopologicalSort(); + vector>> showTopologicalSortResult(); }; } \ No newline at end of file diff --git a/src/0003_graph/headers/0004_strongly_connected_components.h b/src/0003_graph/headers/0004_strongly_connected_components.h index 0e37f60..3fbd84c 100644 --- a/src/0003_graph/headers/0004_strongly_connected_components.h +++ b/src/0003_graph/headers/0004_strongly_connected_components.h @@ -6,7 +6,7 @@ #include using namespace std; -namespace StronglyConnectedComponents +namespace strongly_connected_components { enum color { WHITE, GRAY, BLACK }; @@ -30,14 +30,14 @@ namespace StronglyConnectedComponents map _nodeMap; list _nodesFinishingTimeOrder; vector> _allConnectedComponents; - Node* MakeOrFindNode(int value); - void DepthFirstSearchOnGraphG(Node* DFSNode); - void DepthFirstSearchOnGraphT(Node* DFSNode, vector& connectedComponents); + Node* makeOrFindNode(int value); + void depthFirstSearchOnGraphG(Node* dFSNode); + void depthFirstSearchOnGraphT(Node* dFSNode, vector& connectedComponents); public: - void PushDirectedEdge(int valueU, int valueV); - void PushSingleNode(int valueU); - void DFSOnGraphG(); - void DFSOnGraphT(); - vector> FindAllStronglyConnectedComponents(); + void pushDirectedEdge(int valueU, int valueV); + void pushSingleNode(int valueU); + void dFSOnGraphG(); + void dFSOnGraphT(); + vector> findAllStronglyConnectedComponents(); }; } \ No newline at end of file diff --git a/src/0003_graph/headers/0005_hamiltonian_path_and_cycle.h b/src/0003_graph/headers/0005_hamiltonian_path_and_cycle.h index 7ccca6a..8e52744 100644 --- a/src/0003_graph/headers/0005_hamiltonian_path_and_cycle.h +++ b/src/0003_graph/headers/0005_hamiltonian_path_and_cycle.h @@ -5,7 +5,7 @@ #include using namespace std; -namespace HamiltonianPathAndCycle +namespace hamiltonian_path_and_cycle { class Node { @@ -25,16 +25,16 @@ namespace HamiltonianPathAndCycle map> _adjlist; map _nodeMap; vector _hamiltonianPath; - Node* MakeOrFindNode(int value); - bool IsSafe(Node* nodeU, Node* nodeV); - bool HamiltonianCycleAndPathUtil(Node* node); + Node* makeOrFindNode(int value); + bool isSafe(Node* nodeU, Node* nodeV); + bool hamiltonianCycleAndPathUtil(Node* node); public: - void PushUndirectedEdge(int valueU, int valueV); - void PushSingleNode(int valueU); - void FindHamiltonianCycleAndPath(); - bool IsHamiltonianCyclePresent(); - bool IsHamiltonianPathPresent(); - vector GetHamiltonianPath(); + void pushUndirectedEdge(int valueU, int valueV); + void pushSingleNode(int valueU); + void findHamiltonianCycleAndPath(); + bool isHamiltonianCyclePresent(); + bool isHamiltonianPathPresent(); + vector getHamiltonianPath(); }; } \ No newline at end of file diff --git a/src/0003_graph/headers/0006_eulerian_path_and_circuit.h b/src/0003_graph/headers/0006_eulerian_path_and_circuit.h index 92d0d34..27b8cb5 100644 --- a/src/0003_graph/headers/0006_eulerian_path_and_circuit.h +++ b/src/0003_graph/headers/0006_eulerian_path_and_circuit.h @@ -5,7 +5,7 @@ #include using namespace std; -namespace EulerianPathAndCircuit +namespace eulerian_path_and_circuit { class Node { @@ -26,18 +26,18 @@ namespace EulerianPathAndCircuit map> _adjlist; map _nodeMap; vector _eulerianPath; - Node* MakeOrFindNode(int value); - void DepthFirstSearch(Node* node); - bool IsConnected(); - void EulerianPathHierholzerAlgorithm(Node* startingNode); + Node* makeOrFindNode(int value); + void depthFirstSearch(Node* node); + bool isConnected(); + void eulerianPathHierholzerAlgorithm(Node* startingNode); public: - void PushUndirectedEdge(int valueU, int valueV); - void PushDirectedEdge(int valueU, int valueV); - void PushSingleNode(int valueU); - void FindEulerianPathAndCircuit(); - bool IsEulerianPathPresent(); - bool IsEulerianCircuitPresent(); - vector UndirectedGraphGetEulerianPath(); + void pushUndirectedEdge(int valueU, int valueV); + void pushDirectedEdge(int valueU, int valueV); + void pushSingleNode(int valueU); + void findEulerianPathAndCircuit(); + bool isEulerianPathPresent(); + bool isEulerianCircuitPresent(); + vector undirectedGraphGetEulerianPath(); }; } \ No newline at end of file diff --git a/src/0003_graph/headers/0007_minimum_spanning_tree_kruskal_algorithm.h b/src/0003_graph/headers/0007_minimum_spanning_tree_kruskal_algorithm.h index 8ca704c..fcf4a52 100644 --- a/src/0003_graph/headers/0007_minimum_spanning_tree_kruskal_algorithm.h +++ b/src/0003_graph/headers/0007_minimum_spanning_tree_kruskal_algorithm.h @@ -5,7 +5,7 @@ #include using namespace std; -namespace MinimumSpanningTreeKruskalAlgorithm +namespace minimum_spanning_tree_kruskal_algorithm { class Node { @@ -32,15 +32,15 @@ namespace MinimumSpanningTreeKruskalAlgorithm map _nodeMap; vector _edgeList; vector, int>> _minimumSpanningTree; - Node* MakeOrFindNode(int data); - void MakeSet(Node* node); - void Union(Node* nodeU, Node* nodeV); - void Link(Node* nodeU, Node* nodeV); - Node* FindSet(Node* node); + Node* makeOrFindNode(int data); + void makeSet(Node* node); + void unionSet(Node* nodeU, Node* nodeV); + void link(Node* nodeU, Node* nodeV); + Node* findSet(Node* node); public: - void PushUndirectedEdge(int valueU, int valueV, int weight); - void FindMinimumSpanningTreeKruskalAlgorithm(); - vector, int>> GetMinimumSpanningTree(); + void pushUndirectedEdge(int valueU, int valueV, int weight); + void findMinimumSpanningTreeKruskalAlgorithm(); + vector, int>> getMinimumSpanningTree(); }; } \ No newline at end of file diff --git a/src/0003_graph/headers/0008_minimum_spanning_tree_prim_algorithm.h b/src/0003_graph/headers/0008_minimum_spanning_tree_prim_algorithm.h index ffe7c08..15ae01f 100644 --- a/src/0003_graph/headers/0008_minimum_spanning_tree_prim_algorithm.h +++ b/src/0003_graph/headers/0008_minimum_spanning_tree_prim_algorithm.h @@ -5,7 +5,7 @@ #include using namespace std; -namespace MinimumSpanningTreePrimAlgorithm +namespace minimum_spanning_tree_prim_algorithm { class Node { @@ -33,10 +33,10 @@ namespace MinimumSpanningTreePrimAlgorithm map _nodeMap; vector, int>> _minimumSpanningTree; multiset _operationalSet; - Node* MakeOrFindNode(int data); + Node* makeOrFindNode(int data); public: - void PushUndirectedEdge(int valueU, int valueV, int weight); - void FindMinimumSpanningTreePrimAlgorithm(); - vector, int>> GetMinimumSpanningTree(); + void pushUndirectedEdge(int valueU, int valueV, int weight); + void findMinimumSpanningTreePrimAlgorithm(); + vector, int>> getMinimumSpanningTree(); }; } \ No newline at end of file diff --git a/src/0003_graph/headers/0009_single_source_shortest_path_bellman_ford.h b/src/0003_graph/headers/0009_single_source_shortest_path_bellman_ford.h index e51ca10..c5cb712 100644 --- a/src/0003_graph/headers/0009_single_source_shortest_path_bellman_ford.h +++ b/src/0003_graph/headers/0009_single_source_shortest_path_bellman_ford.h @@ -4,7 +4,7 @@ #include using namespace std; -namespace SingleSourceShortestPathBellmanFord +namespace single_source_shortest_path_bellman_ford { class Node { @@ -30,15 +30,15 @@ namespace SingleSourceShortestPathBellmanFord map> _adjlist; map _nodeMap; vector _edgeList; - Node* MakeOrFindNode(int data); - void InitializeSingleSource(Node* sourceNode); - void Relax(Edge* edge); - void GetShortestPath(Node* node, vector& path); + Node* makeOrFindNode(int data); + void initializeSingleSource(Node* sourceNode); + void relax(Edge* edge); + void getShortestPath(Node* node, vector& path); public: - void PushDirectedEdge(int valueU, int valueV, int weight); - bool FindSingleSourceShortestPathBellmanFord(int data); - vector GetShortestPathBellmanFord(int data); + void pushDirectedEdge(int valueU, int valueV, int weight); + bool findSingleSourceShortestPathBellmanFord(int data); + vector getShortestPathBellmanFord(int data); }; } \ No newline at end of file diff --git a/src/0003_graph/headers/0010_directed_acyclic_graph_shortest_path.h b/src/0003_graph/headers/0010_directed_acyclic_graph_shortest_path.h index 8826ebc..2ee5ca6 100644 --- a/src/0003_graph/headers/0010_directed_acyclic_graph_shortest_path.h +++ b/src/0003_graph/headers/0010_directed_acyclic_graph_shortest_path.h @@ -5,7 +5,7 @@ #include using namespace std; -namespace DirectedAcyclicGraphShortestPath +namespace directed_acyclic_graph_shortest_path { enum color {WHITE, GRAY, BLACK}; @@ -35,17 +35,17 @@ namespace DirectedAcyclicGraphShortestPath map _nodeMap; map> _edgeMap; list _topologicalSortedNodeList; - Node* MakeOrFindNode(int data); - void DepthFirstSearch(Node* node); - void TopologicalSort(); - void InitializeSingleSource(Node* sourceNode); - void Relax(Edge* edge); - void GetShortestPath(Node* node, vector& path); + Node* makeOrFindNode(int data); + void depthFirstSearch(Node* node); + void topologicalSort(); + void initializeSingleSource(Node* sourceNode); + void relax(Edge* edge); + void getShortestPath(Node* node, vector& path); public: - void PushDirectedEdge(int valueU, int valueV, int weight); - void FindDAGShortestPath(int data); - vector GetDAGShortestPath(int data); + void pushDirectedEdge(int valueU, int valueV, int weight); + void findDAGShortestPath(int data); + vector getDAGShortestPath(int data); }; } \ No newline at end of file diff --git a/src/0003_graph/headers/0011_single_source_shortest_path_dijkstra.h b/src/0003_graph/headers/0011_single_source_shortest_path_dijkstra.h index 8911ac8..28c90b9 100644 --- a/src/0003_graph/headers/0011_single_source_shortest_path_dijkstra.h +++ b/src/0003_graph/headers/0011_single_source_shortest_path_dijkstra.h @@ -5,7 +5,7 @@ #include using namespace std; -namespace SingleSourceShortestPathDijkstra +namespace single_source_shortest_path_dijkstra { class Node { @@ -41,15 +41,15 @@ namespace SingleSourceShortestPathDijkstra map _nodeMap; map> _edgeMap; multiset _operationalSet; - Node* MakeOrFindNode(int data); - void InitializeSingleSource(Node* sourceNode); - void Relax(Edge* edge); - void Dijkstra(Node* source); - void GetShortestPath(Node* node, vector& path); + Node* makeOrFindNode(int data); + void initializeSingleSource(Node* sourceNode); + void relax(Edge* edge); + void dijkstra(Node* source); + void getShortestPath(Node* node, vector& path); public: - void PushDirectedEdge(int valueU, int valueV, int weight); - void FindShortestPathDijkstra(int data); - vector GetDijkstraShortestPath(int data); + void pushDirectedEdge(int valueU, int valueV, int weight); + void findShortestPathDijkstra(int data); + vector getDijkstraShortestPath(int data); }; } \ No newline at end of file diff --git a/src/0003_graph/headers/0012_difference_constraints_shortest_paths.h b/src/0003_graph/headers/0012_difference_constraints_shortest_paths.h index 02d1426..bda0d4a 100644 --- a/src/0003_graph/headers/0012_difference_constraints_shortest_paths.h +++ b/src/0003_graph/headers/0012_difference_constraints_shortest_paths.h @@ -5,7 +5,7 @@ #include using namespace std; -namespace DifferenceConstraintsShortestPaths +namespace difference_constraints_shortest_paths { class Node { @@ -30,14 +30,14 @@ namespace DifferenceConstraintsShortestPaths map> _adjlist; map _nodeMap; vector _edgeList; - Node* MakeOrFindNode(string data); - void PushDirectedEdge(string valueU, string valueV, int weight); - void InitializeSingleSource(Node* sourceNode); - void Relax(Edge* edge); + Node* makeOrFindNode(string data); + void pushDirectedEdge(string valueU, string valueV, int weight); + void initializeSingleSource(Node* sourceNode); + void relax(Edge* edge); public: - void PushAllDirectedEdges(vector> vectorA, vector vectorX, vector vectorB); - bool FindDifferenceConstraintsSolutionBellmanFord(); - vector> GetDifferenceConstrtaintsSolution(); + void pushAllDirectedEdges(vector> vectorA, vector vectorX, vector vectorB); + bool findDifferenceConstraintsSolutionBellmanFord(); + vector> getDifferenceConstrtaintsSolution(); }; } \ No newline at end of file diff --git a/src/0003_graph/headers/0013_all_pairs_shortest_paths_floyd_warshall.h b/src/0003_graph/headers/0013_all_pairs_shortest_paths_floyd_warshall.h index 211e1b6..cc6ce1b 100644 --- a/src/0003_graph/headers/0013_all_pairs_shortest_paths_floyd_warshall.h +++ b/src/0003_graph/headers/0013_all_pairs_shortest_paths_floyd_warshall.h @@ -3,7 +3,7 @@ #include using namespace std; -namespace AllPairsShortestPathsFloydWarshall +namespace all_pairs_shortest_paths_floyd_warshall { class Graph { @@ -12,13 +12,13 @@ namespace AllPairsShortestPathsFloydWarshall vector> _adjMatrix; vector> _shortestPathMatrixFloydWarshall; vector> _predecessorMatrix; - void InitializeDistanceAndPredecessors(); - void GetShortestPath(int source, int destination, vector& path); + void initializeDistanceAndPredecessors(); + void getShortestPath(int source, int destination, vector& path); public: - void CreateGraph(int noOfVertices); - void PushDirectedEdge(int valueU, int valueV, int weight); - void FindAllPairsShortestPathsFloydWarshallSolution(); - vector> GetFloydWarshallShortestPath(); + void createGraph(int noOfVertices); + void pushDirectedEdge(int valueU, int valueV, int weight); + void findAllPairsShortestPathsFloydWarshallSolution(); + vector> getFloydWarshallShortestPath(); }; } \ No newline at end of file diff --git a/src/0003_graph/headers/0014_all_pairs_shortest_paths_johnson.h b/src/0003_graph/headers/0014_all_pairs_shortest_paths_johnson.h index 925e89e..1f091dc 100644 --- a/src/0003_graph/headers/0014_all_pairs_shortest_paths_johnson.h +++ b/src/0003_graph/headers/0014_all_pairs_shortest_paths_johnson.h @@ -5,7 +5,7 @@ #include using namespace std; -namespace AllPairsShortestPathsJohnson +namespace all_pairs_shortest_paths_johnson { class Node { @@ -48,19 +48,19 @@ namespace AllPairsShortestPathsJohnson multiset _operationalSet; vector> _shortestPathMatrix; vector> _predecessorMatrix; - Node* MakeOrFindNode(int data); - void PushAugmentedDirectedEdges(Node* sourceNode, Node* nodeV, int weight); - void InitializeSingleSource(Node* sourceNode); - void RelaxBellmanFord(Edge* edge); - bool BellmanFord(Node* source); - void RelaxDijkstra(Edge* edge); - void Dijkstra(Node* source); - void GetShortestPath(int source, int destination, vector& path); + Node* makeOrFindNode(int data); + void pushAugmentedDirectedEdges(Node* sourceNode, Node* nodeV, int weight); + void initializeSingleSource(Node* sourceNode); + void relaxBellmanFord(Edge* edge); + bool bellmanFord(Node* source); + void relaxDijkstra(Edge* edge); + void dijkstra(Node* source); + void getShortestPath(int source, int destination, vector& path); public: - void PushDirectedEdge(int dataU, int dataV, int weight); - bool FindAllPairsShortestPathsJohnsonAlgorithm(); - vector> GetAllPairsShortestPathsDistanceMatrix(); - vector> GetAllPairsShortestPathsPathMatrix(); + void pushDirectedEdge(int dataU, int dataV, int weight); + bool findAllPairsShortestPathsJohnsonAlgorithm(); + vector> getAllPairsShortestPathsDistanceMatrix(); + vector> getAllPairsShortestPathsPathMatrix(); }; } \ No newline at end of file diff --git a/src/0003_graph/headers/0015_maximum_flow_ford_fulkerson.h b/src/0003_graph/headers/0015_maximum_flow_ford_fulkerson.h index 429b247..1815566 100644 --- a/src/0003_graph/headers/0015_maximum_flow_ford_fulkerson.h +++ b/src/0003_graph/headers/0015_maximum_flow_ford_fulkerson.h @@ -4,7 +4,7 @@ #include using namespace std; -namespace MaximumFlowFordFulkerson +namespace maximum_flow_ford_fulkerson { class Graph { @@ -18,12 +18,12 @@ namespace MaximumFlowFordFulkerson vector> _residualGraph; vector _parent; vector _visited; - void ResolveAntiParallelEdges(); - void DepthFirstSearchVisit(int nodeU); - bool DepthFirstSearch(); + void resolveAntiParallelEdges(); + void depthFirstSearchVisit(int nodeU); + bool depthFirstSearch(); public: - void CreateGraph(int noOfVertices); - void PushDirectedEdge(int valueU, int valueV, int capacity); - int FindMaximumFlowFordFulkerson(); + void createGraph(int noOfVertices); + void pushDirectedEdge(int valueU, int valueV, int capacity); + int findMaximumFlowFordFulkerson(); }; } \ No newline at end of file diff --git a/src/0003_graph/headers/0016_maximum_flow_edmonds_karp.h b/src/0003_graph/headers/0016_maximum_flow_edmonds_karp.h index 25c72f1..2b5904d 100644 --- a/src/0003_graph/headers/0016_maximum_flow_edmonds_karp.h +++ b/src/0003_graph/headers/0016_maximum_flow_edmonds_karp.h @@ -4,7 +4,7 @@ #include using namespace std; -namespace MaximumFlowEdmondsKarp +namespace maximum_flow_edmonds_karp { class Graph { @@ -18,11 +18,11 @@ namespace MaximumFlowEdmondsKarp vector> _residualGraph; vector _parent; vector _visited; - void ResolveAntiParallelEdges(); - bool BreadthFirstSearch(); + void resolveAntiParallelEdges(); + bool breadthFirstSearch(); public: - void CreateGraph(int noOfVertices); - void PushDirectedEdge(int valueU, int valueV, int capacity); - int FindMaximumFlowEdmondsKarp(); + void createGraph(int noOfVertices); + void pushDirectedEdge(int valueU, int valueV, int capacity); + int findMaximumFlowEdmondsKarp(); }; } \ No newline at end of file diff --git a/src/0003_graph/headers/0017_maximum_bipartite_matching.h b/src/0003_graph/headers/0017_maximum_bipartite_matching.h index 741c3c0..88e0bc2 100644 --- a/src/0003_graph/headers/0017_maximum_bipartite_matching.h +++ b/src/0003_graph/headers/0017_maximum_bipartite_matching.h @@ -4,9 +4,9 @@ #include using namespace std; -namespace MaximumBipartiteMatching +namespace maximum_bipartite_matching { - enum Color + enum color { WHITE = -1, RED = 0, @@ -28,14 +28,14 @@ namespace MaximumBipartiteMatching vector _visited; vector _color; vector> _matchings; - void ResolveAntiParallelEdges(); - void ColorGraph(); - void AddAdditionalEdges(); - bool BreadthFirstSearch(); + void resolveAntiParallelEdges(); + void colorGraph(); + void addAdditionalEdges(); + bool breadthFirstSearch(); public: - void CreateGraph(int noOfVertices); - void PushDirectedEdge(int valueU, int valueV); - int FindMaximumBipartiteMatching(); - vector> GetMatchings(); + void createGraph(int noOfVertices); + void pushDirectedEdge(int valueU, int valueV); + int findMaximumBipartiteMatching(); + vector> getMatchings(); }; } \ No newline at end of file diff --git a/src/0003_graph/headers/0018_maximum_flow_goldberg_generic_push_relabel.h b/src/0003_graph/headers/0018_maximum_flow_goldberg_generic_push_relabel.h index fb13a01..af138a3 100644 --- a/src/0003_graph/headers/0018_maximum_flow_goldberg_generic_push_relabel.h +++ b/src/0003_graph/headers/0018_maximum_flow_goldberg_generic_push_relabel.h @@ -4,7 +4,7 @@ #include using namespace std; -namespace MaximumFlowGoldbergGenericPushRelabel +namespace maximum_flow_goldberg_generic_push_relabel { class Graph { @@ -19,13 +19,13 @@ namespace MaximumFlowGoldbergGenericPushRelabel vector _height; vector _visited; queue _nodeQueue; - void InitializePreflow(); - bool CheckOverFlow(); - bool Push(int nodeU); - void Relabel(int nodeU); + void initializePreflow(); + bool checkOverFlow(); + bool push(int nodeU); + void relabel(int nodeU); public: - void CreateGraph(int noOfVertices); - void PushDirectedEdge(int valueU, int valueV, int capacity); - int FindMaximumFlowGoldbergGenericPushRelabel(); + void createGraph(int noOfVertices); + void pushDirectedEdge(int valueU, int valueV, int capacity); + int findMaximumFlowGoldbergGenericPushRelabel(); }; } \ No newline at end of file diff --git a/src/0003_graph/headers/0019_maximum_flow_relabel_to_front.h b/src/0003_graph/headers/0019_maximum_flow_relabel_to_front.h index aea70f6..785c427 100644 --- a/src/0003_graph/headers/0019_maximum_flow_relabel_to_front.h +++ b/src/0003_graph/headers/0019_maximum_flow_relabel_to_front.h @@ -4,7 +4,7 @@ #include using namespace std; -namespace MaximumFlowRelabelToFront +namespace maximum_flow_relabel_to_front { class Graph { @@ -19,13 +19,13 @@ namespace MaximumFlowRelabelToFront vector _height; vector _visited; list _nodeList; - void InitializePreflow(); - void Discharge(int nodeU); - void Push(int nodeU, int nodeV); - void Relabel(int nodeU); + void initializePreflow(); + void discharge(int nodeU); + void push(int nodeU, int nodeV); + void relabel(int nodeU); public: - void CreateGraph(int noOfVertices); - void PushDirectedEdge(int valueU, int valueV, int capacity); - int FindMaximumFlowRelabelToFront(); + void createGraph(int noOfVertices); + void pushDirectedEdge(int valueU, int valueV, int capacity); + int findMaximumFlowRelabelToFront(); }; } \ No newline at end of file diff --git a/src/0004_dynamic_programming/0001_fibonacci_number.cc b/src/0004_dynamic_programming/0001_fibonacci_number.cc index 47073aa..9b96a0a 100644 --- a/src/0004_dynamic_programming/0001_fibonacci_number.cc +++ b/src/0004_dynamic_programming/0001_fibonacci_number.cc @@ -1,18 +1,18 @@ -#include "0001_FibonacciNumber.h" +#include "0001_fibonacci_number.h" -namespace FibonacciNumber +namespace fibonacci_number { - int DynamicProgramming::RecursiveNthFibonacci(int n) + int DynamicProgramming::recursiveNthFibonacci(int n) { if (n <= 1) { return n; } - return this->RecursiveNthFibonacci(n - 1) + this->RecursiveNthFibonacci(n - 2); + return this->recursiveNthFibonacci(n - 1) + this->recursiveNthFibonacci(n - 2); } - int DynamicProgramming::DpNthFibonacci(int n) + int DynamicProgramming::dpNthFibonacci(int n) { vector dp(n + 1, 0); dp[0] = 0; diff --git a/src/0004_dynamic_programming/0002_tribonacci_number.cc b/src/0004_dynamic_programming/0002_tribonacci_number.cc index 84a4c59..2d22eef 100644 --- a/src/0004_dynamic_programming/0002_tribonacci_number.cc +++ b/src/0004_dynamic_programming/0002_tribonacci_number.cc @@ -1,8 +1,8 @@ -#include "0002_TribonacciNumber.h" +#include "0002_tribonacci_number.h" -namespace TribonacciNumber +namespace tribonacci_number { - int DynamicProgramming::RecursiveNthTribonacci(int n) + int DynamicProgramming::recursiveNthTribonacci(int n) { if (n == 0 || n == 1 || n == 2) { @@ -14,10 +14,10 @@ namespace TribonacciNumber return 1; } - return this->RecursiveNthTribonacci(n - 1) + this->RecursiveNthTribonacci(n - 2) + this->RecursiveNthTribonacci(n - 3); + return this->recursiveNthTribonacci(n - 1) + this->recursiveNthTribonacci(n - 2) + this->recursiveNthTribonacci(n - 3); } - int DynamicProgramming::DpNthTribonacci(int n) + int DynamicProgramming::dpNthTribonacci(int n) { vector dp(n, 0); dp[0] = dp[1] = 0; diff --git a/src/0004_dynamic_programming/0003_climbing_stairs.cc b/src/0004_dynamic_programming/0003_climbing_stairs.cc index 6e365f8..cdf2832 100644 --- a/src/0004_dynamic_programming/0003_climbing_stairs.cc +++ b/src/0004_dynamic_programming/0003_climbing_stairs.cc @@ -1,19 +1,19 @@ -#include "0003_ClimbingStairs.h" +#include "0003_climbing_stairs.h" using namespace std; -namespace ClimbingStairs +namespace climbing_stairs { - int DynamicProgramming::RecursiveCountWays(int n) + int DynamicProgramming::recursiveCountWays(int n) { if (n == 0 || n == 1) { return 1; } - return this->RecursiveCountWays(n - 1) + this->RecursiveCountWays(n - 2); + return this->recursiveCountWays(n - 1) + this->recursiveCountWays(n - 2); } - int DynamicProgramming::DpCountWays(int n) + int DynamicProgramming::dpCountWays(int n) { vector dp(n + 1, 0); dp[0] = 1; diff --git a/src/0004_dynamic_programming/0004_minimum_cost_climbing_stairs.cc b/src/0004_dynamic_programming/0004_minimum_cost_climbing_stairs.cc index 661afc4..92e87d9 100644 --- a/src/0004_dynamic_programming/0004_minimum_cost_climbing_stairs.cc +++ b/src/0004_dynamic_programming/0004_minimum_cost_climbing_stairs.cc @@ -1,19 +1,19 @@ -#include "0004_MinimumCostClimbingStairs.h" +#include "0004_minimum_cost_climbing_stairs.h" #include -namespace MinimumCostClimbingStairs +namespace minimum_cost_climbing_stairs { - int DynamicProgramming::MinCostRecursive(size_t step, vector& cost) + int DynamicProgramming::minCostRecursive(size_t step, vector& cost) { if (step == 0 || step == 1) { return cost[step]; } - return cost[step] + min(this->MinCostRecursive(step - 1, cost), this->MinCostRecursive(step - 2, cost)); + return cost[step] + min(this->minCostRecursive(step - 1, cost), this->minCostRecursive(step - 2, cost)); } - int DynamicProgramming::RecursiveMinimumCostClimbingStairs(vector& cost) + int DynamicProgramming::recursiveMinimumCostClimbingStairs(vector& cost) { size_t totalSteps = cost.size(); @@ -22,10 +22,10 @@ namespace MinimumCostClimbingStairs return cost[0]; } - return min(this->MinCostRecursive(totalSteps - 1, cost), this->MinCostRecursive(totalSteps - 2, cost)); + return min(this->minCostRecursive(totalSteps - 1, cost), this->minCostRecursive(totalSteps - 2, cost)); } - int DynamicProgramming::DpMinimumCostClimbingStairs(vector& cost) + int DynamicProgramming::dpMinimumCostClimbingStairs(vector& cost) { size_t totalSteps = cost.size(); vector dp(totalSteps, 0); diff --git a/src/0004_dynamic_programming/0005_house_robber1.cc b/src/0004_dynamic_programming/0005_house_robber1.cc index 2e3fb7f..9e2be4b 100644 --- a/src/0004_dynamic_programming/0005_house_robber1.cc +++ b/src/0004_dynamic_programming/0005_house_robber1.cc @@ -1,8 +1,8 @@ -#include "0005_HouseRobber1.h" +#include "0005_house_robber1.h" -namespace HouseRobber1 +namespace house_robber1 { - int DynamicProgramming::MaxLootRecursive(size_t house, vector& houseValues) + int DynamicProgramming::maxLootRecursive(size_t house, vector& houseValues) { if (house <= 0) { @@ -14,19 +14,19 @@ namespace HouseRobber1 return houseValues[0]; } - int pickCurrentHouse = houseValues[house - 1] + this->MaxLootRecursive(house - 2, houseValues); - int dropCurrentHouse = this->MaxLootRecursive(house - 1, houseValues); + int pickCurrentHouse = houseValues[house - 1] + this->maxLootRecursive(house - 2, houseValues); + int dropCurrentHouse = this->maxLootRecursive(house - 1, houseValues); return max(pickCurrentHouse, dropCurrentHouse); } - int DynamicProgramming::RecursiveMaximumLoot(vector& houseValues) + int DynamicProgramming::recursiveMaximumLoot(vector& houseValues) { size_t totalNumberOfHouses = houseValues.size(); - return this->MaxLootRecursive(totalNumberOfHouses, houseValues); + return this->maxLootRecursive(totalNumberOfHouses, houseValues); } - int DynamicProgramming::DpMaximumLoot(vector& houseValues) + int DynamicProgramming::dpMaximumLoot(vector& houseValues) { size_t totalNumberOfHouses = houseValues.size(); vector dp(totalNumberOfHouses + 1, 0); diff --git a/src/0004_dynamic_programming/0006_house_robber2.cc b/src/0004_dynamic_programming/0006_house_robber2.cc index cbefdda..bf87a96 100644 --- a/src/0004_dynamic_programming/0006_house_robber2.cc +++ b/src/0004_dynamic_programming/0006_house_robber2.cc @@ -1,8 +1,8 @@ -#include "0006_HouseRobber2.h" +#include "0006_house_robber2.h" -namespace HouseRobber2 +namespace house_robber2 { - int DynamicProgramming::MaxLootRecursive(size_t house, vector& houseValues) + int DynamicProgramming::maxLootRecursive(size_t house, vector& houseValues) { if (house <= 0) { @@ -14,13 +14,13 @@ namespace HouseRobber2 return houseValues[0]; } - int pickCurrentHouse = houseValues[house - 1] + this->MaxLootRecursive(house - 2, houseValues); - int dropCurrentHouse = this->MaxLootRecursive(house - 1, houseValues); + int pickCurrentHouse = houseValues[house - 1] + this->maxLootRecursive(house - 2, houseValues); + int dropCurrentHouse = this->maxLootRecursive(house - 1, houseValues); return max(pickCurrentHouse, dropCurrentHouse); } - int DynamicProgramming::MaxLootDp(size_t firstHouse, size_t lastHouse, vector& houseValues) + int DynamicProgramming::maxLootDp(size_t firstHouse, size_t lastHouse, vector& houseValues) { int totalNumberOfHouses = lastHouse - firstHouse + 1; @@ -47,7 +47,7 @@ namespace HouseRobber2 return dp[totalNumberOfHouses - 1]; } - int DynamicProgramming::RecursiveMaximumLoot(vector& houseValues) + int DynamicProgramming::recursiveMaximumLoot(vector& houseValues) { if (houseValues.size() == 0) { @@ -61,16 +61,16 @@ namespace HouseRobber2 size_t totalNumberOfHouses = houseValues.size()-1; - // Case 1: Exclude last house. + // Case 1: exclude last house. vector pickFirstHouse(houseValues.begin(), houseValues.end() - 1); - // Case 2: Exlcude first house. + // Case 2: exlcude first house. vector pickLastHouse(houseValues.begin() + 1, houseValues.end()); - return max(this->MaxLootRecursive(totalNumberOfHouses, pickFirstHouse), this->MaxLootRecursive(totalNumberOfHouses, pickLastHouse)); + return max(this->maxLootRecursive(totalNumberOfHouses, pickFirstHouse), this->maxLootRecursive(totalNumberOfHouses, pickLastHouse)); } - int DynamicProgramming::DpMaximumLoot(vector& houseValues) + int DynamicProgramming::dpMaximumLoot(vector& houseValues) { size_t totalNumberOfHouses = houseValues.size(); @@ -84,11 +84,11 @@ namespace HouseRobber2 return houseValues[0]; } - // Case 1: Exclude last house. - int pickFirstHouse = this->MaxLootDp(0, totalNumberOfHouses - 2, houseValues); + // Case 1: exclude last house. + int pickFirstHouse = this->maxLootDp(0, totalNumberOfHouses - 2, houseValues); - // Case 2: Exlcude first house. - int pickLastHouse = this->MaxLootDp(1, totalNumberOfHouses - 1, houseValues); + // Case 2: exlcude first house. + int pickLastHouse = this->maxLootDp(1, totalNumberOfHouses - 1, houseValues); return max(pickFirstHouse, pickLastHouse); } diff --git a/src/0004_dynamic_programming/0007_decode_ways.cc b/src/0004_dynamic_programming/0007_decode_ways.cc index bf93270..ee4f14e 100644 --- a/src/0004_dynamic_programming/0007_decode_ways.cc +++ b/src/0004_dynamic_programming/0007_decode_ways.cc @@ -1,12 +1,12 @@ -#include "0007_DecodeWays.h" +#include "0007_decode_ways.h" -namespace DecodeWays +namespace decode_ways { - int DynamicProgramming::CountWaysRecursiveHelper(string& digits, size_t index) + int DynamicProgramming::countWaysRecursiveHelper(string& digits, size_t index) { size_t digitsLength = digits.size(); - // Base case: If the end of the string is reached, return 1 as it signifies a valid decoding. + // Base case: if the end of the string is reached, return 1 as it signifies a valid decoding. if (index >= digitsLength) { return 1; @@ -14,26 +14,26 @@ namespace DecodeWays int ways = 0; - // Single digit decoding: check if current digit is not '0'. + // single digit decoding: check if current digit is not '0'. if (digits[index] != '0') { - ways = this->CountWaysRecursiveHelper(digits, index + 1); + ways = this->countWaysRecursiveHelper(digits, index + 1); } - // Two digit decoding: check if next two digits are valid. + // two digit decoding: check if next two digits are valid. if ((index + 1 < digitsLength) && ((digits[index] == '1' && digits[index + 1] <= '9') || (digits[index] == '2' && digits[index + 1] <= '6'))) { - ways += this->CountWaysRecursiveHelper(digits, index + 2); + ways += this->countWaysRecursiveHelper(digits, index + 2); } return ways; } - int DynamicProgramming::RecursiveCountWays(string digits) + int DynamicProgramming::recursiveCountWays(string digits) { - return this->CountWaysRecursiveHelper(digits, 0); + return this->countWaysRecursiveHelper(digits, 0); } - int DynamicProgramming::DpCountways(string digits) + int DynamicProgramming::dpCountways(string digits) { size_t digitsLength = digits.size(); @@ -43,13 +43,13 @@ namespace DecodeWays for (int index = digitsLength - 1; index >= 0; index--) { - // Single digit decoding: check if current digit is not '0'. + // single digit decoding: check if current digit is not '0'. if (digits[index] != '0') { dp[index] = dp[index + 1]; } - // Two digit decoding: check if next two digits are valid. + // two digit decoding: check if next two digits are valid. if ((index + 1 < digitsLength) && ((digits[index] == '1' && digits[index + 1] <= '9') || (digits[index] == '2' && digits[index + 1] <= '6'))) { dp[index] += dp[index + 2]; diff --git a/src/0004_dynamic_programming/0008_tiling_problem.cc b/src/0004_dynamic_programming/0008_tiling_problem.cc index d447c8d..070e80b 100644 --- a/src/0004_dynamic_programming/0008_tiling_problem.cc +++ b/src/0004_dynamic_programming/0008_tiling_problem.cc @@ -1,8 +1,8 @@ -#include "0008_TilingProblem.h" +#include "0008_tiling_problem.h" -namespace TilingProblem +namespace tiling_problem { - int DynamicProgramming::NumberOfWaysRecursiveHelper(int n) + int DynamicProgramming::numberOfWaysRecursiveHelper(int n) { if (n < 0) { @@ -15,18 +15,18 @@ namespace TilingProblem } int result = 0; - result += this->NumberOfWaysRecursiveHelper(n - 1); - result += this->NumberOfWaysRecursiveHelper(n - 2); + result += this->numberOfWaysRecursiveHelper(n - 1); + result += this->numberOfWaysRecursiveHelper(n - 2); return result; } - int DynamicProgramming::RecursiveNumberOfWays(int n) + int DynamicProgramming::recursiveNumberOfWays(int n) { - return this->NumberOfWaysRecursiveHelper(n); + return this->numberOfWaysRecursiveHelper(n); } - int DynamicProgramming::DpNumberOfWays(int n) + int DynamicProgramming::dpNumberOfWays(int n) { vector dp(n + 1, 0); dp[0] = 1; diff --git a/src/0004_dynamic_programming/0009_friends_pairing_problem.cc b/src/0004_dynamic_programming/0009_friends_pairing_problem.cc index fbea63f..d80c892 100644 --- a/src/0004_dynamic_programming/0009_friends_pairing_problem.cc +++ b/src/0004_dynamic_programming/0009_friends_pairing_problem.cc @@ -1,28 +1,28 @@ -#include "0009_FriendsPairingProblem.h" +#include "0009_friends_pairing_problem.h" -namespace FriendsPairingProblem +namespace friends_pairing_problem { - // Dynamic Programming Private Member Methods. - int DynamicProgramming::CountFriendsPairingsRecursiveHelper(int n) + // dynamic programming private member methods. + int DynamicProgramming::countFriendsPairingsRecursiveHelper(int n) { if (n <= 1) { return 1; } int result = 0; - result += this->CountFriendsPairingsRecursiveHelper(n - 1); - result += (n - 1) * this->CountFriendsPairingsRecursiveHelper(n - 2); + result += this->countFriendsPairingsRecursiveHelper(n - 1); + result += (n - 1) * this->countFriendsPairingsRecursiveHelper(n - 2); return result; } - // Dynamic Programming Public Member Methods. - int DynamicProgramming::RecursiveCountFriendsPairings(int n) + // dynamic programming public member methods. + int DynamicProgramming::recursiveCountFriendsPairings(int n) { - return this->CountFriendsPairingsRecursiveHelper(n); + return this->countFriendsPairingsRecursiveHelper(n); } - int DynamicProgramming::DpCountFriendsPairings(int n) + int DynamicProgramming::dpCountFriendsPairings(int n) { vector dp(n + 1, 0); dp[0] = 0; diff --git a/src/0004_dynamic_programming/0010_ways_to_cover_distance.cc b/src/0004_dynamic_programming/0010_ways_to_cover_distance.cc index b2f0bce..e9301ca 100644 --- a/src/0004_dynamic_programming/0010_ways_to_cover_distance.cc +++ b/src/0004_dynamic_programming/0010_ways_to_cover_distance.cc @@ -1,9 +1,9 @@ -#include "0010_WaysToCoverDistance.h" +#include "0010_ways_to_cover_distance.h" -namespace WaysToCoverDistance +namespace ways_to_cover_distance { - // Dynamic Programming Private Member Methods. - int DynamicProgramming::WaysToCoverDistanceRecursiveHelper(int dist) + // dynamic programming private member methods. + int DynamicProgramming::waysToCoverDistanceRecursiveHelper(int dist) { if (dist < 0) { @@ -16,20 +16,20 @@ namespace WaysToCoverDistance } int result = 0; - result += this->WaysToCoverDistanceRecursiveHelper(dist - 1); - result += this->WaysToCoverDistanceRecursiveHelper(dist - 2); - result += this->WaysToCoverDistanceRecursiveHelper(dist - 3); + result += this->waysToCoverDistanceRecursiveHelper(dist - 1); + result += this->waysToCoverDistanceRecursiveHelper(dist - 2); + result += this->waysToCoverDistanceRecursiveHelper(dist - 3); return result; } - // Dynamic Programming Public Member Methods. - int DynamicProgramming::RecursiveWaysToCoverDistance(int dist) + // dynamic programming public member methods. + int DynamicProgramming::recursiveWaysToCoverDistance(int dist) { - return this->WaysToCoverDistanceRecursiveHelper(dist); + return this->waysToCoverDistanceRecursiveHelper(dist); } - int DynamicProgramming::DpWaysToCoverDistance(int dist) + int DynamicProgramming::dpWaysToCoverDistance(int dist) { vector dp(dist + 1, 0); dp[0] = 1; diff --git a/src/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order.cc b/src/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order.cc index f4467e2..624eba9 100644 --- a/src/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order.cc +++ b/src/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order.cc @@ -1,9 +1,9 @@ -#include "0011_CountWaysToReachNthStairIncludeOrder.h" +#include "0011_count_ways_to_reach_nth_stair_include_order.h" -namespace CountWaysToReachNthStairIncludeOrder +namespace count_ways_to_reach_nth_stair_include_order { - // Dynamic Programming Private Member Methods. - int DynamicProgramming::RecursiveCountWaysToReachNthStairIncludeOrderHelper(int n) + // dynamic programming private member methods. + int DynamicProgramming::recursiveCountWaysToReachNthStairIncludeOrderHelper(int n) { if (n < 0) { @@ -15,19 +15,19 @@ namespace CountWaysToReachNthStairIncludeOrder } int result = 0; - result += this->RecursiveCountWaysToReachNthStairIncludeOrderHelper(n - 1); - result += this->RecursiveCountWaysToReachNthStairIncludeOrderHelper(n - 2); + result += this->recursiveCountWaysToReachNthStairIncludeOrderHelper(n - 1); + result += this->recursiveCountWaysToReachNthStairIncludeOrderHelper(n - 2); return result; } - // Dynamic Programming Public Member Methods. - int DynamicProgramming::RecursiveCountWaysToReachNthStairIncludeOrder(int n) + // dynamic programming public member methods. + int DynamicProgramming::recursiveCountWaysToReachNthStairIncludeOrder(int n) { - return this->RecursiveCountWaysToReachNthStairIncludeOrderHelper(n); + return this->recursiveCountWaysToReachNthStairIncludeOrderHelper(n); } - int DynamicProgramming::DpCountWaysToReachNthStairIncludeOrder(int n) + int DynamicProgramming::dpCountWaysToReachNthStairIncludeOrder(int n) { vector dp(n + 1, 0); dp[0] = 1; diff --git a/src/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order.cc b/src/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order.cc index 0e71a69..1fbbb41 100644 --- a/src/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order.cc +++ b/src/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order.cc @@ -1,22 +1,22 @@ -#include "0012_CountWaysToReachNthStairExcludeOrder.h" +#include "0012_count_ways_to_reach_nth_stair_exclude_order.h" -namespace CountWaysToReachNthStairExcludeOrder +namespace count_ways_to_reach_nth_stair_exclude_order { // notes: /* To avoid counting ways which only differ in order, we can assume that a person initially takes only steps of size 1 followed by steps of size 2. In other words, once a person takes a step of size 2, he will continue taking steps of size 2 till he reaches the nth stair. - A person can reach nth stair from either(n - 1)th stair or from(n - 2)th stair.So, there are two cases : - The person has reached nth step from(n - 1)th step, this means that the last step was of size 1 and all the previous steps should also be of size 1. So, there is only 1 way. - The person has reached nth step from(n - 2)th step, this means that the last step was of size 2 and the previous steps can either be of size 1 or size 2. - Therefore the Recurrence relation will be : + A person can reach nth stair from either(n - 1)th stair or from(n - 2)th stair.so, there are two cases : + the person has reached nth step from(n - 1)th step, this means that the last step was of size 1 and all the previous steps should also be of size 1. so, there is only 1 way. + the person has reached nth step from(n - 2)th step, this means that the last step was of size 2 and the previous steps can either be of size 1 or size 2. + therefore the recurrence relation will be : nthStair(n) = 1 (last step was of size 1) + nthStair(n - 2) (last step was of size 2) so f(n) = 1 + f(n - 2) */ - // Dynamic Programming Private Member Methods. - int DynamicProgramming::RecursiveCountWaysToReachNthStairExcludeOrderHelper(int n) + // dynamic programming private member methods. + int DynamicProgramming::recursiveCountWaysToReachNthStairExcludeOrderHelper(int n) { if (n < 0) { @@ -27,16 +27,16 @@ namespace CountWaysToReachNthStairExcludeOrder return 1; } - return 1 + this->RecursiveCountWaysToReachNthStairExcludeOrderHelper(n - 2); + return 1 + this->recursiveCountWaysToReachNthStairExcludeOrderHelper(n - 2); } - // Dynamic Programming Public Member Methods. - int DynamicProgramming::RecursiveCountWaysToReachNthStairExcludeOrder(int n) + // dynamic programming public member methods. + int DynamicProgramming::recursiveCountWaysToReachNthStairExcludeOrder(int n) { - return this->RecursiveCountWaysToReachNthStairExcludeOrderHelper(n); + return this->recursiveCountWaysToReachNthStairExcludeOrderHelper(n); } - int DynamicProgramming::DpCountWaysToReachNthStairExcludeOrder(int n) + int DynamicProgramming::dpCountWaysToReachNthStairExcludeOrder(int n) { vector dp(n + 1, 0); dp[0] = 1; diff --git a/src/0004_dynamic_programming/0013_knapsack_problem.cc b/src/0004_dynamic_programming/0013_knapsack_problem.cc index e9e5ba2..5d06ec9 100644 --- a/src/0004_dynamic_programming/0013_knapsack_problem.cc +++ b/src/0004_dynamic_programming/0013_knapsack_problem.cc @@ -1,9 +1,9 @@ -#include "0013_KnapsackProblem.h" +#include "0013_knapsack_problem.h" -namespace KnapsackProblem +namespace knapsack_problem { - // Dynamic Programming Private Member Methods. - int DynamicProgramming::KnapsackRecursiveHelper(int capacity, vector& weight, vector& profit, int numberOfItems) + // dynamic programming private member methods. + int DynamicProgramming::knapsackRecursiveHelper(int capacity, vector& weight, vector& profit, int numberOfItems) { if (capacity <= 0 || numberOfItems == 0) { @@ -12,25 +12,25 @@ namespace KnapsackProblem int pickCurrentItem = 0; - // Pick the current item only if does not exceed the capacity. + // pick the current item only if does not exceed the capacity. if (weight[numberOfItems - 1] <= capacity) { - pickCurrentItem = profit[numberOfItems - 1] + this->KnapsackRecursiveHelper(capacity - weight[numberOfItems - 1], weight, profit, numberOfItems - 1); + pickCurrentItem = profit[numberOfItems - 1] + this->knapsackRecursiveHelper(capacity - weight[numberOfItems - 1], weight, profit, numberOfItems - 1); } - int dropCurrentItem = this->KnapsackRecursiveHelper(capacity, weight, profit, numberOfItems - 1); + int dropCurrentItem = this->knapsackRecursiveHelper(capacity, weight, profit, numberOfItems - 1); return max(pickCurrentItem, dropCurrentItem); } - // Dynamic Programming Public Member Methods. - int DynamicProgramming::RecursiveKnapsack(int capacity, vector weight, vector profit) + // dynamic programming public member methods. + int DynamicProgramming::recursiveKnapsack(int capacity, vector weight, vector profit) { size_t totalNumberOfItems = weight.size(); - return this->KnapsackRecursiveHelper(capacity, weight, profit, totalNumberOfItems); + return this->knapsackRecursiveHelper(capacity, weight, profit, totalNumberOfItems); } - int DynamicProgramming::DpKnapsack(int capacity, vector weight, vector profit) + int DynamicProgramming::dpKnapsack(int capacity, vector weight, vector profit) { int numberOfItems = weight.size(); vector> dp(numberOfItems + 1, vector(capacity + 1, 0)); @@ -60,7 +60,7 @@ namespace KnapsackProblem return dp[numberOfItems][capacity]; } - int DynamicProgramming::DpKnapsackSpaceOptimized(int capacity, vector weight, vector profit) + int DynamicProgramming::dpKnapsackSpaceOptimized(int capacity, vector weight, vector profit) { int numberOfItems = weight.size(); vector dp(capacity + 1, 0); diff --git a/src/0004_dynamic_programming/0014_subset_sum_problem.cc b/src/0004_dynamic_programming/0014_subset_sum_problem.cc index 7f558ba..f5694ec 100644 --- a/src/0004_dynamic_programming/0014_subset_sum_problem.cc +++ b/src/0004_dynamic_programming/0014_subset_sum_problem.cc @@ -1,50 +1,50 @@ -#include "0014_SubsetSumProblem.h" +#include "0014_subset_sum_problem.h" -namespace SubsetSumProblem +namespace subset_sum_problem { - // Dynamic Programming Private Member Methods. - bool DynamicProgramming::SubsetSumRecursiveHelper(vector& nums, int sum, int numberOfElements) + // dynamic programming private member methods. + bool DynamicProgramming::subsetSumRecursiveHelper(vector& nums, int sum, int numberOfElements) { // Base case. - // If the sum is 0, we found a subset with a given sum. + // if the sum is 0, we found a subset with a given sum. if (sum == 0) { return true; } // Base case. - // If there are no elements left to process and the sum is not 0 yet, we did not find a subset with given sum, so return false. + // if there are no elements left to process and the sum is not 0 yet, we did not find a subset with given sum, so return false. if (numberOfElements == 0) { return false; } - // When the current element is greater than the sum, we skip it, as all elemeents are non-negative. + // when the current element is greater than the sum, we skip it, as all elemeents are non-negative. if (nums[numberOfElements - 1] > sum) { - return this->SubsetSumRecursiveHelper(nums, sum, numberOfElements - 1); + return this->subsetSumRecursiveHelper(nums, sum, numberOfElements - 1); } - // When the current element is equal to or less than the sum, we have two choices. - // 1. Include the current element in the subset and the sum is reduced by the current element value and also the number of elements is reducded by 1. - // 2. Exclude the current element from the subset and the sum remains the same but the number of eleements is reduced by 1. - // If either of these two choices return true, we return true. - return this->SubsetSumRecursiveHelper(nums, sum - nums[numberOfElements - 1], numberOfElements - 1) || this->SubsetSumRecursiveHelper(nums, sum, numberOfElements - 1); + // when the current element is equal to or less than the sum, we have two choices. + // 1. include the current element in the subset and the sum is reduced by the current element value and also the number of elements is reducded by 1. + // 2. exclude the current element from the subset and the sum remains the same but the number of eleements is reduced by 1. + // if either of these two choices return true, we return true. + return this->subsetSumRecursiveHelper(nums, sum - nums[numberOfElements - 1], numberOfElements - 1) || this->subsetSumRecursiveHelper(nums, sum, numberOfElements - 1); } - // Dynamic Programming Public Member Methods. - bool DynamicProgramming::RecursiveSubsetSum(vector nums, int sum) + // dynamic programming public member methods. + bool DynamicProgramming::recursiveSubsetSum(vector nums, int sum) { int numberOfElements = nums.size(); - return this->SubsetSumRecursiveHelper(nums, sum, numberOfElements); + return this->subsetSumRecursiveHelper(nums, sum, numberOfElements); } - bool DynamicProgramming::DpIsSubsetSum(vector nums, int sum) + bool DynamicProgramming::dpIsSubsetSum(vector nums, int sum) { int numberOfElements = nums.size(); vector> dp(numberOfElements + 1, vector(sum + 1, false)); - // When the sum is 0, the result is true + // when the sum is 0, the result is true for (int i = 0; i < numberOfElements; i++) { dp[i][0] = true; diff --git a/src/0004_dynamic_programming/0015_count_subsets_for_sum.cc b/src/0004_dynamic_programming/0015_count_subsets_for_sum.cc index 64d75b6..6ec8743 100644 --- a/src/0004_dynamic_programming/0015_count_subsets_for_sum.cc +++ b/src/0004_dynamic_programming/0015_count_subsets_for_sum.cc @@ -1,9 +1,9 @@ -#include "0015_CountSubsetsForSum.h" +#include "0015_count_subsets_for_sum.h" -namespace CountSubsetsForSum +namespace count_subsets_for_sum { - // Dynamic Programming private member methods - int DynamicProgramming::RecursiveCountSubsetsHelper(vector& nums, int targetSum, int currentSum, int index) + // dynamic programming private member methods + int DynamicProgramming::recursiveCountSubsetsHelper(vector& nums, int targetSum, int currentSum, int index) { int noOfElements = nums.size(); if (index == noOfElements) @@ -11,24 +11,24 @@ namespace CountSubsetsForSum return (targetSum == currentSum); } - int exclude = this->RecursiveCountSubsetsHelper(nums, targetSum, currentSum, index + 1); + int exclude = this->recursiveCountSubsetsHelper(nums, targetSum, currentSum, index + 1); int include = 0; if ((nums[index] + currentSum) <= targetSum) { - include = this->RecursiveCountSubsetsHelper(nums, targetSum, currentSum + nums[index], index + 1); + include = this->recursiveCountSubsetsHelper(nums, targetSum, currentSum + nums[index], index + 1); } return (exclude + include); } - // Dynamic Programming public member methods - int DynamicProgramming::RecursiveCountSubsets(vector nums, int sum) + // dynamic programming public member methods + int DynamicProgramming::recursiveCountSubsets(vector nums, int sum) { - return this->RecursiveCountSubsetsHelper(nums, sum, 0, 0); + return this->recursiveCountSubsetsHelper(nums, sum, 0, 0); } - int DynamicProgramming::DpCountSubsets(vector nums, int sum) + int DynamicProgramming::dpCountSubsets(vector nums, int sum) { int noOfElements = nums.size(); vector> dp(noOfElements + 1, vector(sum + 1, 0)); @@ -39,7 +39,7 @@ namespace CountSubsetsForSum { for (int j = 0; j <= sum; j++) { - // Considering excluding the current element + // considering excluding the current element dp[i][j] = dp[i - 1][j]; // Case to include the current element diff --git a/src/0004_dynamic_programming/0016_partition_equal_subset_sum.cc b/src/0004_dynamic_programming/0016_partition_equal_subset_sum.cc index 2db0dab..8ad0f8c 100644 --- a/src/0004_dynamic_programming/0016_partition_equal_subset_sum.cc +++ b/src/0004_dynamic_programming/0016_partition_equal_subset_sum.cc @@ -1,8 +1,8 @@ -#include "0016_PartitionEqualSubsetSum.h" +#include "0016_partition_equal_subset_sum.h" -namespace PartitionEqualSubsetSum +namespace partition_equal_subset_sum { - bool DynamicProgramming::RecursivePartitionEqualSubsetsHelper(vector& nums, int targetSum, int numberOfElements) + bool DynamicProgramming::recursivePartitionEqualSubsetsHelper(vector& nums, int targetSum, int numberOfElements) { if (targetSum == 0) { @@ -16,31 +16,31 @@ namespace PartitionEqualSubsetSum if (nums[numberOfElements - 1] > targetSum) { - return this->RecursivePartitionEqualSubsetsHelper(nums, targetSum, numberOfElements - 1); + return this->recursivePartitionEqualSubsetsHelper(nums, targetSum, numberOfElements - 1); } - return (this->RecursivePartitionEqualSubsetsHelper(nums, targetSum - nums[numberOfElements - 1], numberOfElements - 1) || this->RecursivePartitionEqualSubsetsHelper(nums, targetSum, numberOfElements - 1)); + return (this->recursivePartitionEqualSubsetsHelper(nums, targetSum - nums[numberOfElements - 1], numberOfElements - 1) || this->recursivePartitionEqualSubsetsHelper(nums, targetSum, numberOfElements - 1)); } - bool DynamicProgramming::RecursivePartitionEqualSubsets(vector nums) + bool DynamicProgramming::recursivePartitionEqualSubsets(vector nums) { int targetSum = accumulate(nums.begin(), nums.end(), 0); - // Check if targetSum is odd, then equal partition is not possible at all + // check if targetSum is odd, then equal partition is not possible at all if (targetSum % 2 != 0) { return false; } int numberOfElements = nums.size(); - return this->RecursivePartitionEqualSubsetsHelper(nums, targetSum / 2, numberOfElements); + return this->recursivePartitionEqualSubsetsHelper(nums, targetSum / 2, numberOfElements); } - bool DynamicProgramming::DpPartitionEqualSubsets(vector nums) + bool DynamicProgramming::dpPartitionEqualSubsets(vector nums) { int targetSum = accumulate(nums.begin(), nums.end(), 0); - // Check if targetSum is odd, then equal partition is not possible at all + // check if targetSum is odd, then equal partition is not possible at all if (targetSum % 2 != 0) { return false; diff --git a/src/0004_dynamic_programming/0017_target_sum.cc b/src/0004_dynamic_programming/0017_target_sum.cc index c92fe77..d92c8a6 100644 --- a/src/0004_dynamic_programming/0017_target_sum.cc +++ b/src/0004_dynamic_programming/0017_target_sum.cc @@ -1,8 +1,8 @@ -#include "0017_TargetSum.h" +#include "0017_target_sum.h" -namespace TargetSum +namespace target_sum { - int DynamicProgramming::RecursiveFindTotalWaysHelper(vector& nums, int currentSum, int targetSum, int index) + int DynamicProgramming::recursiveFindTotalWaysHelper(vector& nums, int currentSum, int targetSum, int index) { // Base case if (currentSum == targetSum && index == nums.size()) @@ -15,21 +15,21 @@ namespace TargetSum return 0; } - // Return total count of two possible ways while considering the current element - // 1. Add the current element to currentSum - // 2. Subtract the current element from currentSum + // return total count of two possible ways while considering the current element + // 1. add the current element to currentSum + // 2. subtract the current element from currentSum return ( - this->RecursiveFindTotalWaysHelper(nums, currentSum + nums[index], targetSum, index + 1) + this->recursiveFindTotalWaysHelper(nums, currentSum + nums[index], targetSum, index + 1) + - this->RecursiveFindTotalWaysHelper(nums, currentSum - nums[index], targetSum, index + 1)); + this->recursiveFindTotalWaysHelper(nums, currentSum - nums[index], targetSum, index + 1)); } - int DynamicProgramming::RecursiveFindTotalWays(vector nums, int target) + int DynamicProgramming::recursiveFindTotalWays(vector nums, int target) { - return this->RecursiveFindTotalWaysHelper(nums, 0, target, 0); + return this->recursiveFindTotalWaysHelper(nums, 0, target, 0); } - int DynamicProgramming::DpFindTotalWays(vector nums, int target) + int DynamicProgramming::dpFindTotalWays(vector nums, int target) { int totalSum = accumulate(nums.begin(), nums.end(), 0); @@ -54,7 +54,7 @@ namespace TargetSum { for (int j = 0; j <= targetSubsetSum; j++) { - // Considering excluding the current element + // considering excluding the current element dp[i][j] = dp[i - 1][j]; // Case to include the current element diff --git a/src/0004_dynamic_programming/CMakeLists.txt b/src/0004_dynamic_programming/CMakeLists.txt index b063b19..50fd0de 100644 --- a/src/0004_dynamic_programming/CMakeLists.txt +++ b/src/0004_dynamic_programming/CMakeLists.txt @@ -1,22 +1,22 @@ # Specify the source files set(0005DYNAMICPROGRAMMING_SOURCES - 0001_FibonacciNumber.cc - 0002_TribonacciNumber.cc - 0003_ClimbingStairs.cc - 0004_MinimumCostClimbingStairs.cc - 0005_HouseRobber1.cc - 0006_HouseRobber2.cc - 0007_DecodeWays.cc - 0008_TilingProblem.cc - 0009_FriendsPairingProblem.cc - 0010_WaysToCoverDistance.cc - 0011_CountWaysToReachNthStairIncludeOrder.cc - 0012_CountWaysToReachNthStairExcludeOrder.cc - 0013_KnapsackProblem.cc - 0014_SubsetSumProblem.cc - 0015_CountSubsetsForSum.cc - 0016_PartitionEqualSubsetSum.cc - 0017_TargetSum.cc + 0001_fibonacci_number.cc + 0002_tribonacci_number.cc + 0003_climbing_stairs.cc + 0004_minimum_cost_climbing_stairs.cc + 0005_house_robber1.cc + 0006_house_robber2.cc + 0007_decode_ways.cc + 0008_tiling_problem.cc + 0009_friends_pairing_problem.cc + 0010_ways_to_cover_distance.cc + 0011_count_ways_to_reach_nth_stair_include_order.cc + 0012_count_ways_to_reach_nth_stair_exclude_order.cc + 0013_knapsack_problem.cc + 0014_subset_sum_problem.cc + 0015_count_subsets_for_sum.cc + 0016_partition_equal_subset_sum.cc + 0017_target_sum.cc ) diff --git a/src/0004_dynamic_programming/headers/0001_fibonacci_number.h b/src/0004_dynamic_programming/headers/0001_fibonacci_number.h index 204aeba..3ae14cd 100644 --- a/src/0004_dynamic_programming/headers/0001_fibonacci_number.h +++ b/src/0004_dynamic_programming/headers/0001_fibonacci_number.h @@ -3,21 +3,21 @@ using namespace std; /* -Pattern 1 -Linear Recurrence +pattern 1 +linear recurrence -Description -Print the n'th Fibonacci number. +description +print the n'th fibonacci number. */ -namespace FibonacciNumber +namespace fibonacci_number { class DynamicProgramming { private: public: - int RecursiveNthFibonacci(int n); - int DpNthFibonacci(int n); + int recursiveNthFibonacci(int n); + int dpNthFibonacci(int n); }; } \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0002_tribonacci_number.h b/src/0004_dynamic_programming/headers/0002_tribonacci_number.h index 31e805f..b394f0b 100644 --- a/src/0004_dynamic_programming/headers/0002_tribonacci_number.h +++ b/src/0004_dynamic_programming/headers/0002_tribonacci_number.h @@ -3,21 +3,21 @@ using namespace std; /* -Pattern 1 -Linear Recurrence +pattern 1 +linear recurrence -Description -Print the n'th Tribonacci number. +description +print the n'th tribonacci number. */ -namespace TribonacciNumber +namespace tribonacci_number { class DynamicProgramming { private: public: - int RecursiveNthTribonacci(int n); - int DpNthTribonacci(int n); + int recursiveNthTribonacci(int n); + int dpNthTribonacci(int n); }; } \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0003_climbing_stairs.h b/src/0004_dynamic_programming/headers/0003_climbing_stairs.h index e32b71a..8ce6a3d 100644 --- a/src/0004_dynamic_programming/headers/0003_climbing_stairs.h +++ b/src/0004_dynamic_programming/headers/0003_climbing_stairs.h @@ -3,22 +3,22 @@ using namespace std; /* -Pattern 1 -Linear Recurrence +pattern 1 +linear recurrence -Description -There are n stairs, and a person standing at the bottom wants to climb stairs to reach the top. -The person can climb either 1 stair or 2 stairs at a time, the task is to count the number of ways that a person can reach at the top. +description +there are n stairs, and a person standing at the bottom wants to climb stairs to reach the top. +the person can climb either 1 stair or 2 stairs at a time, the task is to count the number of ways that a person can reach at the top. */ -namespace ClimbingStairs +namespace climbing_stairs { class DynamicProgramming { private: public: - int RecursiveCountWays(int n); - int DpCountWays(int n); + int recursiveCountWays(int n); + int dpCountWays(int n); }; } \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0004_minimum_cost_climbing_stairs.h b/src/0004_dynamic_programming/headers/0004_minimum_cost_climbing_stairs.h index 9ef1ec8..bc01c46 100644 --- a/src/0004_dynamic_programming/headers/0004_minimum_cost_climbing_stairs.h +++ b/src/0004_dynamic_programming/headers/0004_minimum_cost_climbing_stairs.h @@ -3,23 +3,23 @@ using namespace std; /* -Pattern 1 -Linear Recurrence +pattern 1 +linear recurrence -Description -Given an array of integers cost[] of length n, where cost[i] is the cost of the ith step on a staircase. Once the cost is paid, we can either climb 1 or 2 steps. -We can either start from the step with index 0, or the step with index 1. The task is to find the minimum cost to reach the top. +description +given an array of integers cost[] of length n, where cost[i] is the cost of the ith step on a staircase. once the cost is paid, we can either climb 1 or 2 steps. +we can either start from the step with index 0, or the step with index 1. the task is to find the minimum cost to reach the top. */ -namespace MinimumCostClimbingStairs +namespace minimum_cost_climbing_stairs { class DynamicProgramming { private: - int MinCostRecursive(size_t step, vector& cost); + int minCostRecursive(size_t step, vector& cost); public: - int RecursiveMinimumCostClimbingStairs(vector& cost); - int DpMinimumCostClimbingStairs(vector& cost); + int recursiveMinimumCostClimbingStairs(vector& cost); + int dpMinimumCostClimbingStairs(vector& cost); }; } \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0005_house_robber1.h b/src/0004_dynamic_programming/headers/0005_house_robber1.h index 231fbba..f4e5e91 100644 --- a/src/0004_dynamic_programming/headers/0005_house_robber1.h +++ b/src/0004_dynamic_programming/headers/0005_house_robber1.h @@ -3,23 +3,23 @@ using namespace std; /* -Pattern 1 -Linear Recurrence +pattern 1 +linear recurrence -Description -There are n houses built in a line, each of which contains some money in it. -A robber wants to steal money from these houses, but he can’t steal from two adjacent houses. The task is to find the maximum amount of money which can be stolen. +description +there are n houses built in a line, each of which contains some money in it. +A robber wants to steal money from these houses, but he can’t steal from two adjacent houses. the task is to find the maximum amount of money which can be stolen. */ -namespace HouseRobber1 +namespace house_robber1 { class DynamicProgramming { private: - int MaxLootRecursive(size_t house, vector& houseValues); + int maxLootRecursive(size_t house, vector& houseValues); public: - int RecursiveMaximumLoot(vector& houseValues); - int DpMaximumLoot(vector& houseValues); + int recursiveMaximumLoot(vector& houseValues); + int dpMaximumLoot(vector& houseValues); }; } \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0006_house_robber2.h b/src/0004_dynamic_programming/headers/0006_house_robber2.h index 74c3c93..646146e 100644 --- a/src/0004_dynamic_programming/headers/0006_house_robber2.h +++ b/src/0004_dynamic_programming/headers/0006_house_robber2.h @@ -3,26 +3,26 @@ using namespace std; /* -Pattern 1 -Linear Recurrence +pattern 1 +linear recurrence -Description -You are given an array arr[] which represents houses arranged in a circle, where each house has a certain value. A thief aims to maximize the total stolen value without robbing two adjacent houses. -Determine the maximum amount the thief can steal. +description +you are given an array arr[] which represents houses arranged in a circle, where each house has a certain value. A thief aims to maximize the total stolen value without robbing two adjacent houses. +determine the maximum amount the thief can steal. -Note: Since the houses are in a circle, the first and last houses are also considered adjacent. +note: since the houses are in a circle, the first and last houses are also considered adjacent. */ -namespace HouseRobber2 +namespace house_robber2 { class DynamicProgramming { private: - int MaxLootRecursive(size_t house, vector& houseValues); - int MaxLootDp(size_t firstHouse, size_t lastHouse, vector& houseValues); + int maxLootRecursive(size_t house, vector& houseValues); + int maxLootDp(size_t firstHouse, size_t lastHouse, vector& houseValues); public: - int RecursiveMaximumLoot(vector& houseValues); - int DpMaximumLoot(vector& houseValues); + int recursiveMaximumLoot(vector& houseValues); + int dpMaximumLoot(vector& houseValues); }; } \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0007_decode_ways.h b/src/0004_dynamic_programming/headers/0007_decode_ways.h index fe2b6ce..6b6549d 100644 --- a/src/0004_dynamic_programming/headers/0007_decode_ways.h +++ b/src/0004_dynamic_programming/headers/0007_decode_ways.h @@ -5,28 +5,28 @@ using namespace std; /* -Pattern 1 -Linear Recurrence +pattern 1 +linear recurrence -Description -Let 1 maps to 'A', 2 maps to 'B', ..., 26 to 'Z'.Given a digit sequence, count the number of possible decodings of the given digit sequence. +description +let 1 maps to 'A', 2 maps to 'B', ..., 26 to 'Z'.given a digit sequence, count the number of possible decodings of the given digit sequence. -Consider the input string "123".There are three valid ways to decode it : -"ABC" : The grouping is(1, 2, 3) -> 'A', 'B', 'C' -"AW" : The grouping is(1, 23) -> 'A', 'W' -"LC" : The grouping is(12, 3) -> 'L', 'C' -Note : Groupings that contain invalid codes(e.g., "0" by itself or numbers greater than "26") are not allowed. -For instance, the string "230" is invalid because "0" cannot stand alone, and "30" is greater than "26", so it cannot represent any letter.The task is to find the total number of valid ways to decode a given string. +consider the input string "123".there are three valid ways to decode it : +"ABC" : the grouping is(1, 2, 3) -> 'A', 'B', 'C' +"AW" : the grouping is(1, 23) -> 'A', 'W' +"LC" : the grouping is(12, 3) -> 'L', 'C' +note : groupings that contain invalid codes(e.g., "0" by itself or numbers greater than "26") are not allowed. +for instance, the string "230" is invalid because "0" cannot stand alone, and "30" is greater than "26", so it cannot represent any letter.the task is to find the total number of valid ways to decode a given string. */ -namespace DecodeWays +namespace decode_ways { class DynamicProgramming { private: - int CountWaysRecursiveHelper(string& digits, size_t index); + int countWaysRecursiveHelper(string& digits, size_t index); public: - int RecursiveCountWays(string digits); - int DpCountways(string digits); + int recursiveCountWays(string digits); + int dpCountways(string digits); }; } \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0008_tiling_problem.h b/src/0004_dynamic_programming/headers/0008_tiling_problem.h index e9befb0..ab541b1 100644 --- a/src/0004_dynamic_programming/headers/0008_tiling_problem.h +++ b/src/0004_dynamic_programming/headers/0008_tiling_problem.h @@ -4,22 +4,22 @@ using namespace std; /* -Pattern 1 -Linear Recurrence +pattern 1 +linear recurrence -Description -Given a "2 x n" board and tiles of size "2 x 1", the task is to count the number of ways to tile the given board using the 2 x 1 tiles. +description +given a "2 x n" board and tiles of size "2 x 1", the task is to count the number of ways to tile the given board using the 2 x 1 tiles. A tile can either be placed horizontally i.e., as a 1 x 2 tile or vertically i.e., as 2 x 1 tile. */ -namespace TilingProblem +namespace tiling_problem { class DynamicProgramming { private: - int NumberOfWaysRecursiveHelper(int n); + int numberOfWaysRecursiveHelper(int n); public: - int RecursiveNumberOfWays(int n); - int DpNumberOfWays(int n); + int recursiveNumberOfWays(int n); + int dpNumberOfWays(int n); }; } \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0009_friends_pairing_problem.h b/src/0004_dynamic_programming/headers/0009_friends_pairing_problem.h index 79cd9da..4d9949e 100644 --- a/src/0004_dynamic_programming/headers/0009_friends_pairing_problem.h +++ b/src/0004_dynamic_programming/headers/0009_friends_pairing_problem.h @@ -4,25 +4,25 @@ using namespace std; /* -Pattern 1 -Linear Recurrence +pattern 1 +linear recurrence -Description -Given n friends, each one can remain single or can be paired up with some other friend. Each friend can be paired only once. Find out the total number of ways in which friends can remain single or can be paired up. +description +given n friends, each one can remain single or can be paired up with some other friend. each friend can be paired only once. find out the total number of ways in which friends can remain single or can be paired up. -Examples: +examples: -Input : n = 3 -Output : 4 -Explanation: +input : n = 3 +output : 4 +explanation: {1}, {2}, {3} : all single {1}, {2, 3} : 2 and 3 paired but 1 is single. {1, 2}, {3} : 1 and 2 are paired but 3 is single. {1, 3}, {2} : 1 and 3 are paired but 2 is single. -Note that {1, 2} and {2, 1} are considered same. +note that {1, 2} and {2, 1} are considered same. -Mathematical Explanation: -The problem is simplified version of how many ways we can divide n elements into multiple groups. +mathematical explanation: +the problem is simplified version of how many ways we can divide n elements into multiple groups. (here group size will be max of 2 elements). In case of n = 3, we have only 2 ways to make a group: 1) all elements are individual(1,1,1) @@ -33,14 +33,14 @@ In case of n = 4, we have 3 ways to form a group: 3) 2 separate pairs (2,2) */ -namespace FriendsPairingProblem +namespace friends_pairing_problem { class DynamicProgramming { private: - int CountFriendsPairingsRecursiveHelper(int n); + int countFriendsPairingsRecursiveHelper(int n); public: - int RecursiveCountFriendsPairings(int n); - int DpCountFriendsPairings(int n); + int recursiveCountFriendsPairings(int n); + int dpCountFriendsPairings(int n); }; } \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0010_ways_to_cover_distance.h b/src/0004_dynamic_programming/headers/0010_ways_to_cover_distance.h index 0268ff5..4d68621 100644 --- a/src/0004_dynamic_programming/headers/0010_ways_to_cover_distance.h +++ b/src/0004_dynamic_programming/headers/0010_ways_to_cover_distance.h @@ -4,17 +4,17 @@ using namespace std; /* -Pattern 1 -Linear Recurrence +pattern 1 +linear recurrence -Description -Given a distance 'dist', count total number of ways to cover the distance with 1, 2 and 3 steps. +description +given a distance 'dist', count total number of ways to cover the distance with 1, 2 and 3 steps. -Examples: +examples: -Input: n = 3 -Output: 4 -Explanation: Below are the four ways +input: n = 3 +output: 4 +explanation: below are the four ways => 1 step + 1 step + 1 step => 1 step + 2 step => 2 step + 1 step @@ -22,9 +22,9 @@ Explanation: Below are the four ways -Input: n = 4 -Output: 7 -Explanation: Below are the four ways +input: n = 4 +output: 7 +explanation: below are the four ways => 1 step + 1 step + 1 step + 1 step => 1 step + 2 step + 1 step => 2 step + 1 step + 1 step @@ -34,14 +34,14 @@ Explanation: Below are the four ways => 1 step + 3 step */ -namespace WaysToCoverDistance +namespace ways_to_cover_distance { class DynamicProgramming { private: - int WaysToCoverDistanceRecursiveHelper(int dist); + int waysToCoverDistanceRecursiveHelper(int dist); public: - int RecursiveWaysToCoverDistance(int dist); - int DpWaysToCoverDistance(int dist); + int recursiveWaysToCoverDistance(int dist); + int dpWaysToCoverDistance(int dist); }; } \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0011_count_ways_to_reach_nth_stair_include_order.h b/src/0004_dynamic_programming/headers/0011_count_ways_to_reach_nth_stair_include_order.h index 6851031..2101931 100644 --- a/src/0004_dynamic_programming/headers/0011_count_ways_to_reach_nth_stair_include_order.h +++ b/src/0004_dynamic_programming/headers/0011_count_ways_to_reach_nth_stair_include_order.h @@ -4,39 +4,39 @@ using namespace std; /* -Pattern 1 -Linear Recurrence +pattern 1 +linear recurrence -Description -There are n stairs, and a person standing at the bottom wants to climb stairs to reach the top. -The person can climb either 1 stair or 2 stairs at a time, the task is to count the number of ways that a person can reach at the top. +description +there are n stairs, and a person standing at the bottom wants to climb stairs to reach the top. +the person can climb either 1 stair or 2 stairs at a time, the task is to count the number of ways that a person can reach at the top. -Note: This problem is similar to Count ways to reach Nth stair (Order does not matter) with the only difference that in this problem, +note: this problem is similar to count ways to reach nth stair (order does not matter) with the only difference that in this problem, we count all distinct ways where different orderings of the steps are considered unique. -Examples: +examples: -Input: n = 1 -Output: 1 -Explanation: There is only one way to climb 1 stair. +input: n = 1 +output: 1 +explanation: there is only one way to climb 1 stair. -Input: n = 2 -Output: 2 -Explanation: There are two ways to reach 2th stair: {1, 1} and {2}. +input: n = 2 +output: 2 +explanation: there are two ways to reach 2th stair: {1, 1} and {2}. -Input: n = 4 -Output: 5 -Explanation: There are five ways to reach 4th stair: {1, 1, 1, 1}, {1, 1, 2}, {2, 1, 1}, {1, 2, 1} and {2, 2}. +input: n = 4 +output: 5 +explanation: there are five ways to reach 4th stair: {1, 1, 1, 1}, {1, 1, 2}, {2, 1, 1}, {1, 2, 1} and {2, 2}. */ -namespace CountWaysToReachNthStairIncludeOrder +namespace count_ways_to_reach_nth_stair_include_order { class DynamicProgramming { private: - int RecursiveCountWaysToReachNthStairIncludeOrderHelper(int n); + int recursiveCountWaysToReachNthStairIncludeOrderHelper(int n); public: - int RecursiveCountWaysToReachNthStairIncludeOrder(int n); - int DpCountWaysToReachNthStairIncludeOrder(int n); + int recursiveCountWaysToReachNthStairIncludeOrder(int n); + int dpCountWaysToReachNthStairIncludeOrder(int n); }; } \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0012_count_ways_to_reach_nth_stair_exclude_order.h b/src/0004_dynamic_programming/headers/0012_count_ways_to_reach_nth_stair_exclude_order.h index 4d52930..c2f0a2a 100644 --- a/src/0004_dynamic_programming/headers/0012_count_ways_to_reach_nth_stair_exclude_order.h +++ b/src/0004_dynamic_programming/headers/0012_count_ways_to_reach_nth_stair_exclude_order.h @@ -4,41 +4,41 @@ using namespace std; /* -Pattern 1 -Linear Recurrence +pattern 1 +linear recurrence -Description -There are n stairs, and a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top (order does not matter). +description +there are n stairs, and a person standing at the bottom wants to reach the top. the person can climb either 1 stair or 2 stairs at a time. count the number of ways, the person can reach the top (order does not matter). -Note: The problem is similar to Climbing Stairs - Count ways to reach Nth stair with the only difference that in this problem, we don't have to count those ways which only differ in ordering of the steps. +note: the problem is similar to climbing stairs - count ways to reach nth stair with the only difference that in this problem, we don't have to count those ways which only differ in ordering of the steps. -Examples: +examples: -Input: n = 1 -Output: 1 -Explanation: There is only one way to climb 1 stair. +input: n = 1 +output: 1 +explanation: there is only one way to climb 1 stair. -Input: n = 2 -Output: 2 -Explanation: There are two ways to climb 2 stairs: {1, 1} and {2}. +input: n = 2 +output: 2 +explanation: there are two ways to climb 2 stairs: {1, 1} and {2}. -Input: n = 4 -Output: 3 -Explanation: Three ways to reach 4th stair: {1, 1, 1, 1}, {1, 1, 2} and {2, 2}. +input: n = 4 +output: 3 +explanation: three ways to reach 4th stair: {1, 1, 1, 1}, {1, 1, 2} and {2, 2}. -Input: n = 5 -Output: 3 -Explanation: Three ways to reach 5th stair: {1, 1, 1, 1, 1}, {1, 1, 1, 2} and {1, 2, 2}. +input: n = 5 +output: 3 +explanation: three ways to reach 5th stair: {1, 1, 1, 1, 1}, {1, 1, 1, 2} and {1, 2, 2}. */ -namespace CountWaysToReachNthStairExcludeOrder +namespace count_ways_to_reach_nth_stair_exclude_order { class DynamicProgramming { private: - int RecursiveCountWaysToReachNthStairExcludeOrderHelper(int n); + int recursiveCountWaysToReachNthStairExcludeOrderHelper(int n); public: - int RecursiveCountWaysToReachNthStairExcludeOrder(int n); - int DpCountWaysToReachNthStairExcludeOrder(int n); + int recursiveCountWaysToReachNthStairExcludeOrder(int n); + int dpCountWaysToReachNthStairExcludeOrder(int n); }; } \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0013_knapsack_problem.h b/src/0004_dynamic_programming/headers/0013_knapsack_problem.h index b7c90aa..d882423 100644 --- a/src/0004_dynamic_programming/headers/0013_knapsack_problem.h +++ b/src/0004_dynamic_programming/headers/0013_knapsack_problem.h @@ -4,31 +4,31 @@ using namespace std; /* -Pattern 2 -Subset / 0-1 Knapsack +pattern 2 +subset / 0-1 knapsack -Description -Given n items where each item has some weight and profit associated with it and also given a bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items into the bag such that the sum of profits associated with them is the maximum possible. +description +given n items where each item has some weight and profit associated with it and also given a bag with capacity W, [i.e., the bag can hold at most W weight in it]. the task is to put the items into the bag such that the sum of profits associated with them is the maximum possible. -Note: The constraint here is we can either put an item completely into the bag or cannot put it at all [It is not possible to put a part of an item into the bag]. +note: the constraint here is we can either put an item completely into the bag or cannot put it at all [it is not possible to put a part of an item into the bag]. -Input: W = 4, profit[] = [1, 2, 3], weight[] = [4, 5, 1] -Output: 3 -Explanation: There are two items which have weight less than or equal to 4. If we select the item with weight 4, the possible profit is 1. And if we select the item with weight 1, the possible profit is 3. So the maximum possible profit is 3. Note that we cannot put both the items with weight 4 and 1 together as the capacity of the bag is 4. +input: W = 4, profit[] = [1, 2, 3], weight[] = [4, 5, 1] +output: 3 +explanation: there are two items which have weight less than or equal to 4. if we select the item with weight 4, the possible profit is 1. and if we select the item with weight 1, the possible profit is 3. so the maximum possible profit is 3. note that we cannot put both the items with weight 4 and 1 together as the capacity of the bag is 4. -Input: W = 3, profit[] = [1, 2, 3], weight[] = [4, 5, 6] -Output: 0 +input: W = 3, profit[] = [1, 2, 3], weight[] = [4, 5, 6] +output: 0 */ -namespace KnapsackProblem +namespace knapsack_problem { class DynamicProgramming { private: - int KnapsackRecursiveHelper(int capacity, vector& weight, vector& profit, int numberOfItems); + int knapsackRecursiveHelper(int capacity, vector& weight, vector& profit, int numberOfItems); public: - int RecursiveKnapsack(int capacity, vector weight, vector profit); - int DpKnapsack(int capacity, vector weight, vector profit); - int DpKnapsackSpaceOptimized(int capacity, vector weight, vector profit); + int recursiveKnapsack(int capacity, vector weight, vector profit); + int dpKnapsack(int capacity, vector weight, vector profit); + int dpKnapsackSpaceOptimized(int capacity, vector weight, vector profit); }; } \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0014_subset_sum_problem.h b/src/0004_dynamic_programming/headers/0014_subset_sum_problem.h index 399d328..37b1784 100644 --- a/src/0004_dynamic_programming/headers/0014_subset_sum_problem.h +++ b/src/0004_dynamic_programming/headers/0014_subset_sum_problem.h @@ -4,31 +4,31 @@ using namespace std; /* -Pattern 2 -Subset / 0-1 Knapsack +pattern 2 +subset / 0-1 knapsack -Description -Given an array arr[] of non-negative integers and a value sum, the task is to check if there is a subset of the given array whose sum is equal to the given sum. +description +given an array arr[] of non-negative integers and a value sum, the task is to check if there is a subset of the given array whose sum is equal to the given sum. -Examples: +examples: -Input: arr[] = [3, 34, 4, 12, 5, 2], sum = 9 -Output: True -Explanation: There is a subset (4, 5) with sum 9. +input: arr[] = [3, 34, 4, 12, 5, 2], sum = 9 +output: true +explanation: there is a subset (4, 5) with sum 9. -Input: arr[] = [3, 34, 4, 12, 5, 2], sum = 30 -Output: False -Explanation: There is no subset that add up to 30. +input: arr[] = [3, 34, 4, 12, 5, 2], sum = 30 +output: false +explanation: there is no subset that add up to 30. */ -namespace SubsetSumProblem +namespace subset_sum_problem { class DynamicProgramming { private: - bool SubsetSumRecursiveHelper(vector& nums, int sum, int numberOfElements); + bool subsetSumRecursiveHelper(vector& nums, int sum, int numberOfElements); public: - bool RecursiveSubsetSum(vector nums, int sum); - bool DpIsSubsetSum(vector nums, int sum); + bool recursiveSubsetSum(vector nums, int sum); + bool dpIsSubsetSum(vector nums, int sum); }; } \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0015_count_subsets_for_sum.h b/src/0004_dynamic_programming/headers/0015_count_subsets_for_sum.h index 4f55bbf..b3e42cd 100644 --- a/src/0004_dynamic_programming/headers/0015_count_subsets_for_sum.h +++ b/src/0004_dynamic_programming/headers/0015_count_subsets_for_sum.h @@ -4,31 +4,31 @@ using namespace std; /* -Pattern 2 -Subset / 0-1 Knapsack +pattern 2 +subset / 0-1 knapsack -Description -Given an array arr[] of length n and an integer target, the task is to find the number of subsets with a sum equal to target. +description +given an array arr[] of length n and an integer target, the task is to find the number of subsets with a sum equal to target. -Examples: +examples: -Input: arr[] = [1, 2, 3, 3], target = 6 -Output: 3 -Explanation: All the possible subsets are [1, 2, 3], [1, 2, 3] and [3, 3] +input: arr[] = [1, 2, 3, 3], target = 6 +output: 3 +explanation: all the possible subsets are [1, 2, 3], [1, 2, 3] and [3, 3] -Input: arr[] = [1, 1, 1, 1], target = 1 -Output: 4 -Explanation: All the possible subsets are [1], [1], [1] and [1] +input: arr[] = [1, 1, 1, 1], target = 1 +output: 4 +explanation: all the possible subsets are [1], [1], [1] and [1] */ -namespace CountSubsetsForSum +namespace count_subsets_for_sum { class DynamicProgramming { private: - int RecursiveCountSubsetsHelper(vector& nums, int targetSum, int currentSum, int index); + int recursiveCountSubsetsHelper(vector& nums, int targetSum, int currentSum, int index); public: - int RecursiveCountSubsets(vector nums, int sum); - int DpCountSubsets(vector nums, int sum); + int recursiveCountSubsets(vector nums, int sum); + int dpCountSubsets(vector nums, int sum); }; } \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0016_partition_equal_subset_sum.h b/src/0004_dynamic_programming/headers/0016_partition_equal_subset_sum.h index bf3c261..6fb9635 100644 --- a/src/0004_dynamic_programming/headers/0016_partition_equal_subset_sum.h +++ b/src/0004_dynamic_programming/headers/0016_partition_equal_subset_sum.h @@ -5,32 +5,32 @@ using namespace std; /* -Pattern 2 -Subset / 0-1 Knapsack +pattern 2 +subset / 0-1 knapsack -Description -Given an array arr[], check if it can be partitioned into two parts such that the sum of elements in both parts is the same. -Note: Each element is present in either the first subset or the second subset, but not in both. +description +given an array arr[], check if it can be partitioned into two parts such that the sum of elements in both parts is the same. +note: each element is present in either the first subset or the second subset, but not in both. -Examples: +examples: -Input: arr[] = [1, 5, 11, 5] -Output: true -Explanation: The array can be partitioned as [1, 5, 5] and [11] and the sum of both the subsets are equal. +input: arr[] = [1, 5, 11, 5] +output: true +explanation: the array can be partitioned as [1, 5, 5] and [11] and the sum of both the subsets are equal. -Input: arr[] = [1, 5, 3] -Output: false -Explanation: The array cannot be partitioned into equal sum sets. +input: arr[] = [1, 5, 3] +output: false +explanation: the array cannot be partitioned into equal sum sets. */ -namespace PartitionEqualSubsetSum +namespace partition_equal_subset_sum { class DynamicProgramming { private: - bool RecursivePartitionEqualSubsetsHelper(vector& nums, int targetSum, int numberOfElements); + bool recursivePartitionEqualSubsetsHelper(vector& nums, int targetSum, int numberOfElements); public: - bool RecursivePartitionEqualSubsets(vector nums); - bool DpPartitionEqualSubsets(vector nums); + bool recursivePartitionEqualSubsets(vector nums); + bool dpPartitionEqualSubsets(vector nums); }; } \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0017_target_sum.h b/src/0004_dynamic_programming/headers/0017_target_sum.h index 1ee27ad..89e1853 100644 --- a/src/0004_dynamic_programming/headers/0017_target_sum.h +++ b/src/0004_dynamic_programming/headers/0017_target_sum.h @@ -5,20 +5,20 @@ using namespace std; /* -Pattern 2 -Subset / 0-1 Knapsack +pattern 2 +subset / 0-1 knapsack -Description -Given an array arr[] of length N and an integer target. -You want to build an expression out of arr[] by adding one of the symbols '+' and '-' before each integer in arr[] and then concatenate all the integers. -Return the number of different expressions that can be built, which evaluates to target. +description +given an array arr[] of length N and an integer target. +you want to build an expression out of arr[] by adding one of the symbols '+' and '-' before each integer in arr[] and then concatenate all the integers. +return the number of different expressions that can be built, which evaluates to target. -Example: +example: -Input : N = 5, arr[] = {1, 1, 1, 1, 1}, target = 3 -Output: 5 -Explanation: -There are 5 ways to assign symbols to +input : N = 5, arr[] = {1, 1, 1, 1, 1}, target = 3 +output: 5 +explanation: +there are 5 ways to assign symbols to make the sum of array be target 3. -1 + 1 + 1 + 1 + 1 = 3 @@ -27,19 +27,19 @@ make the sum of array be target 3. +1 + 1 + 1 - 1 + 1 = 3 +1 + 1 + 1 + 1 - 1 = 3 -Input: N = 1, arr[] = {1}, target = 1 -Output: 1 +input: N = 1, arr[] = {1}, target = 1 +output: 1 */ -namespace TargetSum +namespace target_sum { class DynamicProgramming { private: - int RecursiveFindTotalWaysHelper(vector& nums, int currentSum, int targetSum, int index); - int DpFindTotalWays(); + int recursiveFindTotalWaysHelper(vector& nums, int currentSum, int targetSum, int index); + int dpFindTotalWays(); public: - int RecursiveFindTotalWays(vector nums, int target); - int DpFindTotalWays(vector nums, int target); + int recursiveFindTotalWays(vector nums, int target); + int dpFindTotalWays(vector nums, int target); }; } \ No newline at end of file diff --git a/tests/0000_common_utilities/unit_test_helper.h b/tests/0000_common_utilities/unit_test_helper.h index ff676bd..956cb1b 100644 --- a/tests/0000_common_utilities/unit_test_helper.h +++ b/tests/0000_common_utilities/unit_test_helper.h @@ -10,7 +10,7 @@ class UnitTestHelper { public: template - string SerializeVectorToString(vector vector) + string serializeVectorToString(vector vector) { string result = ""; for (auto& iterator : vector) @@ -22,7 +22,7 @@ class UnitTestHelper } template - string SerializeVectorToString(vector> vector) + string serializeVectorToString(vector> vector) { string result = ""; for (auto& iterator : vector) @@ -38,7 +38,7 @@ class UnitTestHelper } template - string SerializeVectorToString(vector>> vector) + string serializeVectorToString(vector>> vector) { string result = ""; for (auto& iterator : vector) @@ -54,7 +54,7 @@ class UnitTestHelper } template - string SerializeVectorToString(vector> vector) + string serializeVectorToString(vector> vector) { string result = ""; for (auto& iterator : vector) @@ -73,34 +73,34 @@ class UnitTestHelper return result; } - // This helper method is used to sort the vector of vectors of a particular typename. - // Each inner vector is sorted first. - // Then each of them are sorted by their first element, in increasing order. + // this helper method is used to sort the vector of vectors of a particular typename. + // each inner vector is sorted first. + // then each of them are sorted by their first element, in increasing order. template - vector> SortVectorOfVectors(vector> data) + vector> sortVectorOfVectors(vector> data) { - // Step 1: Sorting each inner vectors. + // step 1: sorting each inner vectors. for (auto& innerVector : data) { sort(innerVector.begin(), innerVector.end()); } - // Step 2: Sorting all the vectors by their first element, in increasing order. + // step 2: sorting all the vectors by their first element, in increasing order. sort(data.begin(), data.end(), [](const vector& a, const vector& b) { - // Checking if both inner vectors are empty to prevent out-of-bounds access. + // checking if both inner vectors are empty to prevent out-of-bounds access. if (a.empty() && b.empty()) return false; - // Considering empty vector as less than non-empty vector. + // considering empty vector as less than non-empty vector. if (a.empty()) return true; - // Considering non-empty vector as greater than empty vector. + // considering non-empty vector as greater than empty vector. if (b.empty()) return false; - // Comparing the first elements of each vector. + // comparing the first elements of each vector. return (a[0] < b[0]); }); @@ -108,36 +108,36 @@ class UnitTestHelper } template - bool NormalizeCyclesAndCompare(vector data1, vector data2) + bool normalizeCyclesAndCompare(vector data1, vector data2) { if (data1.size() != data2.size()) { return false; } - // Normalized rotation of cycle 1 + // normalized rotation of cycle 1 vector normalizedCycle1(data1); auto minIterator1 = min_element(normalizedCycle1.begin(), normalizedCycle1.end()); rotate(normalizedCycle1.begin(), minIterator1, normalizedCycle1.end()); - // Normalized rotation of cycle 2 + // normalized rotation of cycle 2 vector normalizedCycle2(data2); auto minIterator2 = min_element(normalizedCycle2.begin(), normalizedCycle2.end()); rotate(normalizedCycle2.begin(), minIterator2, normalizedCycle2.end()); - // Check clock wise + // check clock wise if (normalizedCycle1 == normalizedCycle2) { return true; } - // Check counter clock wise + // check counter clock wise reverse(normalizedCycle2.begin() + 1, normalizedCycle2.end()); return (normalizedCycle1 == normalizedCycle2); } template - vector, T>> SortVectorOfPair(vector, T>> data) + vector, T>> sortVectorOfPair(vector, T>> data) { for (auto& iterator : data) { @@ -159,15 +159,15 @@ class UnitTestHelper } template - string SortVectorOfPairAndSerialize(vector> data) + string sortVectorOfPairAndSerialize(vector> data) { - // Sorting the vector in non-decreasing order on typename T1 + // sorting the vector in non-decreasing order on typename T1 sort(data.begin(), data.end(), [](const pair& pair1, const pair& pair2) { return pair1.first < pair2.first; }); - // Serializing the vector to string + // serializing the vector to string string result = ""; for (auto& iterator : data) { diff --git a/tests/0001_basics/CMakeLists.txt b/tests/0001_basics/CMakeLists.txt index efa1008..71a64c0 100644 --- a/tests/0001_basics/CMakeLists.txt +++ b/tests/0001_basics/CMakeLists.txt @@ -14,7 +14,8 @@ enable_testing() add_executable( 0001BasicsTests - NodeTest.cc) + node_test.cc +) target_link_libraries( 0001BasicsTests diff --git a/tests/0001_basics/node_test.cc b/tests/0001_basics/node_test.cc index ca38297..3da9a0c 100644 --- a/tests/0001_basics/node_test.cc +++ b/tests/0001_basics/node_test.cc @@ -1,12 +1,12 @@ #include -#include "Node.h" +#include "node.h" -// Demonstrate some basic assertions. -namespace NodeTesting +// demonstrate some basic assertions. +namespace node_testing { - TEST(TestingNodeValue, PositiveTestCase) + TEST(testingNodeValue, positiveTestCase) { - // Expect two strings not to be equal. + // expect two strings not to be equal. EXPECT_EQ(2 * 4, 8); } } \ No newline at end of file diff --git a/tests/0002_tree/0001_binary_search_tree_test.cc b/tests/0002_tree/0001_binary_search_tree_test.cc index 0c8aab0..4e08fa9 100644 --- a/tests/0002_tree/0001_binary_search_tree_test.cc +++ b/tests/0002_tree/0001_binary_search_tree_test.cc @@ -1,13 +1,13 @@ #include #include -#include "0001_BinarySearchTree.h" -#include "../0000_common_utilities/UnitTestHelper.h" +#include "0001_binary_search_tree.h" +#include "../0000_common_utilities/unit_test_helper.h" -namespace BinarySearchTree +namespace binary_search_tree { UnitTestHelper unitTestHelper; - TEST(BSTInsertData, RecursiveInorderTest) + TEST(bSTInsertData, recursiveInorderTest) { BinarySearchTree bst; bst.insertNode(50); @@ -15,39 +15,39 @@ namespace BinarySearchTree bst.insertNode(60); - string actualResult = unitTestHelper.SerializeVectorToString(bst.recursiveInorderTraversal()); + string actualResult = unitTestHelper.serializeVectorToString(bst.recursiveInorderTraversal()); string expectedResult = "30 50 60"; EXPECT_EQ(actualResult, expectedResult); } - TEST(BSTInsertData, RecursivePreorderTest) + TEST(bSTInsertData, recursivePreorderTest) { BinarySearchTree bst; bst.insertNode(50); bst.insertNode(30); bst.insertNode(60); - string actualResult = unitTestHelper.SerializeVectorToString(bst.recursivePreorderTravesal()); + string actualResult = unitTestHelper.serializeVectorToString(bst.recursivePreorderTravesal()); string expectedResult = "50 30 60"; EXPECT_EQ(actualResult, expectedResult); } - TEST(BSTInsertData, RecursivePostorderTest) + TEST(bSTInsertData, recursivePostorderTest) { BinarySearchTree bst; bst.insertNode(50); bst.insertNode(30); bst.insertNode(60); - string actualResult = unitTestHelper.SerializeVectorToString(bst.recursivePostorderTravesal()); + string actualResult = unitTestHelper.serializeVectorToString(bst.recursivePostorderTravesal()); string expectedResult = "30 60 50"; EXPECT_EQ(actualResult, expectedResult); } - TEST(BSTInsertData, MorrisInorderTest) + TEST(bSTInsertData, morrisInorderTest) { BinarySearchTree bst; bst.insertNode(50); @@ -55,13 +55,13 @@ namespace BinarySearchTree bst.insertNode(60); - string actualResult = unitTestHelper.SerializeVectorToString(bst.morrisInorderTraversal()); + string actualResult = unitTestHelper.serializeVectorToString(bst.morrisInorderTraversal()); string expectedResult = "30 50 60"; EXPECT_EQ(actualResult, expectedResult); } - TEST(BSTInsertData, MorrisPreorderTest) + TEST(bSTInsertData, morrisPreorderTest) { BinarySearchTree bst; bst.insertNode(50); @@ -69,13 +69,13 @@ namespace BinarySearchTree bst.insertNode(60); - string actualResult = unitTestHelper.SerializeVectorToString(bst.morrisPreorderTraversal()); + string actualResult = unitTestHelper.serializeVectorToString(bst.morrisPreorderTraversal()); string expectedResult = "50 30 60"; EXPECT_EQ(actualResult, expectedResult); } - TEST(BSTInsertData, MorrisPostorderTest) + TEST(bSTInsertData, morrisPostorderTest) { BinarySearchTree bst; bst.insertNode(50); @@ -83,7 +83,7 @@ namespace BinarySearchTree bst.insertNode(60); - string actualResult = unitTestHelper.SerializeVectorToString(bst.morrisPostorderTraversal()); + string actualResult = unitTestHelper.serializeVectorToString(bst.morrisPostorderTraversal()); string expectedResult = "30 60 50"; EXPECT_EQ(actualResult, expectedResult); diff --git a/tests/0002_tree/CMakeLists.txt b/tests/0002_tree/CMakeLists.txt index a10743b..b289d25 100644 --- a/tests/0002_tree/CMakeLists.txt +++ b/tests/0002_tree/CMakeLists.txt @@ -14,7 +14,7 @@ enable_testing() add_executable( 0002_TreeTests - 0001_BinarySearchTreeTest.cc + 0001_binary_search_tree_test.cc ) target_link_libraries( diff --git a/tests/0003_graph/0001_breadth_first_search_test.cc b/tests/0003_graph/0001_breadth_first_search_test.cc index c0beb81..4fa89aa 100644 --- a/tests/0003_graph/0001_breadth_first_search_test.cc +++ b/tests/0003_graph/0001_breadth_first_search_test.cc @@ -1,44 +1,44 @@ #include #include -#include "../../src/0003_graph/headers/0001_BreadthFirstSearch.h" -#include "../0000_common_utilities/UnitTestHelper.h" +#include "../../src/0003_graph/headers/0001_breadth_first_search.h" +#include "../0000_common_utilities/unit_test_helper.h" -namespace BreadthFirstSearch +namespace breadth_first_search { UnitTestHelper unitTestHelper; - TEST(BFSTesting, ShowBFSResultTest01) + TEST(bFSTesting, showBFSResultTest01) { Graph graph; - graph.PushUndirectedEdge(1, 2); - graph.PushUndirectedEdge(1, 3); - graph.PushUndirectedEdge(2, 4); - graph.PushUndirectedEdge(3, 5); - graph.PushUndirectedEdge(3, 6); - graph.PushUndirectedEdge(5, 6); - graph.PushUndirectedEdge(5, 7); - graph.PushUndirectedEdge(6, 7); - graph.PushUndirectedEdge(6, 8); - graph.PushUndirectedEdge(7, 8); + graph.pushUndirectedEdge(1, 2); + graph.pushUndirectedEdge(1, 3); + graph.pushUndirectedEdge(2, 4); + graph.pushUndirectedEdge(3, 5); + graph.pushUndirectedEdge(3, 6); + graph.pushUndirectedEdge(5, 6); + graph.pushUndirectedEdge(5, 7); + graph.pushUndirectedEdge(6, 7); + graph.pushUndirectedEdge(6, 8); + graph.pushUndirectedEdge(7, 8); graph.BFS(1); - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowBFSResult()); + string actualResult = unitTestHelper.serializeVectorToString(graph.showBFSResult()); string expectedResult = "1(0) 2(1) 3(1) 4(2) 5(2) 6(2) 7(3) 8(3)"; EXPECT_EQ(actualResult, expectedResult); } - TEST(BFSTesting, ShowBFSResultTest02) + TEST(bFSTesting, showBFSResultTest02) { Graph graph; - graph.PushUndirectedEdge(1, 2); + graph.pushUndirectedEdge(1, 2); graph.BFS(1); - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowBFSResult()); + string actualResult = unitTestHelper.serializeVectorToString(graph.showBFSResult()); string expectedResult = "1(0) 2(1)"; EXPECT_EQ(actualResult, expectedResult); } diff --git a/tests/0003_graph/0002_depth_first_search_test.cc b/tests/0003_graph/0002_depth_first_search_test.cc index c96c55e..6ac5b67 100644 --- a/tests/0003_graph/0002_depth_first_search_test.cc +++ b/tests/0003_graph/0002_depth_first_search_test.cc @@ -1,175 +1,175 @@ #include -#include "0002_DepthFirstSearch.h" -#include "../0000_common_utilities/UnitTestHelper.h" +#include "0002_depth_first_search.h" +#include "../0000_common_utilities/unit_test_helper.h" -namespace DepthFirstSearch +namespace depth_first_search { UnitTestHelper unitTestHelper; - TEST(DFSTesting, ShowDFSResultTest01) + TEST(dFSTesting, showDFSResultTest01) { Graph graph; - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(1, 4); - graph.PushDirectedEdge(2, 5); - graph.PushDirectedEdge(3, 5); - graph.PushDirectedEdge(3, 6); - graph.PushDirectedEdge(4, 2); - graph.PushDirectedEdge(5, 4); - graph.PushDirectedEdge(6, 6); + graph.pushDirectedEdge(1, 2); + graph.pushDirectedEdge(1, 4); + graph.pushDirectedEdge(2, 5); + graph.pushDirectedEdge(3, 5); + graph.pushDirectedEdge(3, 6); + graph.pushDirectedEdge(4, 2); + graph.pushDirectedEdge(5, 4); + graph.pushDirectedEdge(6, 6); graph.DFS(); - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); + string actualResult = unitTestHelper.serializeVectorToString(graph.showDFSResult()); string expectedResult = "1(1,8) 2(2,7) 3(9,12) 4(4,5) 5(3,6) 6(10,11)"; EXPECT_EQ(actualResult, expectedResult); } - TEST(DFSTesting, ShowDFSResultTest_SingleVertex) + TEST(dFSTesting, showDFSResultTest_SingleVertex) { Graph graph; - graph.PushDirectedEdge(1, 1); + graph.pushDirectedEdge(1, 1); graph.DFS(); - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); + string actualResult = unitTestHelper.serializeVectorToString(graph.showDFSResult()); string expectedResult = "1(1,2)"; EXPECT_EQ(actualResult, expectedResult); } - TEST(DFSTesting, ShowDFSResultTest_DisconnectedGraph) + TEST(dFSTesting, showDFSResultTest_DisconnectedGraph) { Graph graph; - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(3, 4); + graph.pushDirectedEdge(1, 2); + graph.pushDirectedEdge(3, 4); graph.DFS(); - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); + string actualResult = unitTestHelper.serializeVectorToString(graph.showDFSResult()); string expectedResult = "1(1,4) 2(2,3) 3(5,8) 4(6,7)"; EXPECT_EQ(actualResult, expectedResult); } - TEST(DFSTesting, ShowDFSResultTest_CyclicGraph) + TEST(dFSTesting, showDFSResultTest_CyclicGraph) { Graph graph; - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(3, 1); + graph.pushDirectedEdge(1, 2); + graph.pushDirectedEdge(2, 3); + graph.pushDirectedEdge(3, 1); graph.DFS(); - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); + string actualResult = unitTestHelper.serializeVectorToString(graph.showDFSResult()); string expectedResult = "1(1,6) 2(2,5) 3(3,4)"; EXPECT_EQ(actualResult, expectedResult); } - TEST(DFSTesting, ShowDFSResultTest_LargeGraph) + TEST(dFSTesting, showDFSResultTest_LargeGraph) { Graph graph; - // Adding 15 nodes with several edges - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(1, 3); - graph.PushDirectedEdge(2, 4); - graph.PushDirectedEdge(4, 5); - graph.PushDirectedEdge(5, 6); - graph.PushDirectedEdge(6, 7); - graph.PushDirectedEdge(7, 8); - graph.PushDirectedEdge(8, 9); - graph.PushDirectedEdge(9, 10); - graph.PushDirectedEdge(10, 11); - graph.PushDirectedEdge(11, 12); - graph.PushDirectedEdge(12, 13); - graph.PushDirectedEdge(13, 14); - graph.PushDirectedEdge(14, 15); - graph.PushDirectedEdge(15, 16); + // adding 15 nodes with several edges + graph.pushDirectedEdge(1, 2); + graph.pushDirectedEdge(1, 3); + graph.pushDirectedEdge(2, 4); + graph.pushDirectedEdge(4, 5); + graph.pushDirectedEdge(5, 6); + graph.pushDirectedEdge(6, 7); + graph.pushDirectedEdge(7, 8); + graph.pushDirectedEdge(8, 9); + graph.pushDirectedEdge(9, 10); + graph.pushDirectedEdge(10, 11); + graph.pushDirectedEdge(11, 12); + graph.pushDirectedEdge(12, 13); + graph.pushDirectedEdge(13, 14); + graph.pushDirectedEdge(14, 15); + graph.pushDirectedEdge(15, 16); graph.DFS(); - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); + string actualResult = unitTestHelper.serializeVectorToString(graph.showDFSResult()); string expectedResult = "1(1,32) 2(2,29) 3(30,31) 4(3,28) 5(4,27) 6(5,26) 7(6,25) 8(7,24) 9(8,23) 10(9,22) 11(10,21) 12(11,20) 13(12,19) 14(13,18) 15(14,17) 16(15,16)"; EXPECT_EQ(actualResult, expectedResult); } - TEST(DFSTesting, ShowDFSResultTest_NoEdges) + TEST(dFSTesting, showDFSResultTest_NoEdges) { Graph graph; - // Adding isolated nodes - graph.PushDirectedEdge(1, 1); - graph.PushDirectedEdge(2, 2); - graph.PushDirectedEdge(3, 3); + // adding isolated nodes + graph.pushDirectedEdge(1, 1); + graph.pushDirectedEdge(2, 2); + graph.pushDirectedEdge(3, 3); graph.DFS(); - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); + string actualResult = unitTestHelper.serializeVectorToString(graph.showDFSResult()); string expectedResult = "1(1,2) 2(3,4) 3(5,6)"; EXPECT_EQ(actualResult, expectedResult); } - TEST(DFSTesting, ShowDFSResultTest_CyclicGraphWithBackEdges) + TEST(dFSTesting, showDFSResultTest_CyclicGraphWithBackEdges) { Graph graph; - // Creating a cycle with back edges - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(3, 1); // Cycle back to 'a' - graph.PushDirectedEdge(2, 4); // Back edge + // creating a cycle with back edges + graph.pushDirectedEdge(1, 2); + graph.pushDirectedEdge(2, 3); + graph.pushDirectedEdge(3, 1); // cycle back to 'a' + graph.pushDirectedEdge(2, 4); // back edge graph.DFS(); - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); + string actualResult = unitTestHelper.serializeVectorToString(graph.showDFSResult()); string expectedResult = "1(1,8) 2(2,7) 3(3,4) 4(5,6)"; EXPECT_EQ(actualResult, expectedResult); } - TEST(DFSTesting, ShowDFSResultTest_DenseGraph) + TEST(dFSTesting, showDFSResultTest_DenseGraph) { Graph graph; - // Complete graph of 4 nodes - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(1, 3); - graph.PushDirectedEdge(1, 4); - graph.PushDirectedEdge(2, 1); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(2, 4); - graph.PushDirectedEdge(3, 1); - graph.PushDirectedEdge(3, 2); - graph.PushDirectedEdge(3, 4); - graph.PushDirectedEdge(4, 1); - graph.PushDirectedEdge(4, 2); - graph.PushDirectedEdge(4, 3); + // complete graph of 4 nodes + graph.pushDirectedEdge(1, 2); + graph.pushDirectedEdge(1, 3); + graph.pushDirectedEdge(1, 4); + graph.pushDirectedEdge(2, 1); + graph.pushDirectedEdge(2, 3); + graph.pushDirectedEdge(2, 4); + graph.pushDirectedEdge(3, 1); + graph.pushDirectedEdge(3, 2); + graph.pushDirectedEdge(3, 4); + graph.pushDirectedEdge(4, 1); + graph.pushDirectedEdge(4, 2); + graph.pushDirectedEdge(4, 3); graph.DFS(); - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); + string actualResult = unitTestHelper.serializeVectorToString(graph.showDFSResult()); string expectedResult = "1(1,8) 2(2,7) 3(3,6) 4(4,5)"; EXPECT_EQ(actualResult, expectedResult); } - TEST(DFSTesting, ShowDFSResultTest_SelfLoopsAndParallelEdges) + TEST(dFSTesting, showDFSResultTest_SelfLoopsAndParallelEdges) { Graph graph; - // Adding self-loops and parallel edges - graph.PushDirectedEdge(1, 1); - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(2, 2); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(2, 3); // Parallel edge - graph.PushDirectedEdge(3, 3); // Self-loop + // adding self-loops and parallel edges + graph.pushDirectedEdge(1, 1); + graph.pushDirectedEdge(1, 2); + graph.pushDirectedEdge(2, 2); + graph.pushDirectedEdge(2, 3); + graph.pushDirectedEdge(2, 3); // parallel edge + graph.pushDirectedEdge(3, 3); // self-loop graph.DFS(); - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowDFSResult()); + string actualResult = unitTestHelper.serializeVectorToString(graph.showDFSResult()); string expectedResult = "1(1,6) 2(2,5) 3(3,4)"; EXPECT_EQ(actualResult, expectedResult); } diff --git a/tests/0003_graph/0003_topological_sort_test.cc b/tests/0003_graph/0003_topological_sort_test.cc index 6ad277e..72fd320 100644 --- a/tests/0003_graph/0003_topological_sort_test.cc +++ b/tests/0003_graph/0003_topological_sort_test.cc @@ -1,114 +1,114 @@ #include -#include "0003_TopologicalSort.h" -#include "../0000_common_utilities/UnitTestHelper.h" +#include "0003_topological_sort.h" +#include "../0000_common_utilities/unit_test_helper.h" -namespace TopologicalSort +namespace topological_sort { UnitTestHelper unitTestHelper; - TEST(TopoSortTesting, ShowTopoSortResult) + TEST(topoSortTesting, showTopoSortResult) { Graph graph; - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(1, 4); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(4, 3); - graph.PushSingleNode(5); - graph.PushDirectedEdge(6, 7); - graph.PushDirectedEdge(6, 8); - graph.PushDirectedEdge(7, 4); - graph.PushDirectedEdge(7, 8); - graph.PushDirectedEdge(9, 8); + graph.pushDirectedEdge(1, 2); + graph.pushDirectedEdge(1, 4); + graph.pushDirectedEdge(2, 3); + graph.pushDirectedEdge(4, 3); + graph.pushSingleNode(5); + graph.pushDirectedEdge(6, 7); + graph.pushDirectedEdge(6, 8); + graph.pushDirectedEdge(7, 4); + graph.pushDirectedEdge(7, 8); + graph.pushDirectedEdge(9, 8); - graph.TopologicalSort(); + graph.topologicalSort(); - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); + string actualResult = unitTestHelper.serializeVectorToString(graph.showTopologicalSortResult()); string expectedResult = "9(17,18) 6(11,16) 7(12,15) 8(13,14) 5(9,10) 1(1,8) 4(6,7) 2(2,5) 3(3,4)"; EXPECT_EQ(actualResult, expectedResult); } // Test with a larger graph and multiple paths between nodes - TEST(TopoSortTesting, LargeGraphMultiplePaths) + TEST(topoSortTesting, largeGraphMultiplePaths) { Graph graph; - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(1, 3); - graph.PushDirectedEdge(2, 4); - graph.PushDirectedEdge(3, 4); - graph.PushDirectedEdge(4, 5); - graph.PushDirectedEdge(5, 6); - graph.PushDirectedEdge(6, 7); - - graph.TopologicalSort(); - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); + graph.pushDirectedEdge(1, 2); + graph.pushDirectedEdge(1, 3); + graph.pushDirectedEdge(2, 4); + graph.pushDirectedEdge(3, 4); + graph.pushDirectedEdge(4, 5); + graph.pushDirectedEdge(5, 6); + graph.pushDirectedEdge(6, 7); + + graph.topologicalSort(); + string actualResult = unitTestHelper.serializeVectorToString(graph.showTopologicalSortResult()); string expectedResult = "1(1,14) 3(12,13) 2(2,11) 4(3,10) 5(4,9) 6(5,8) 7(6,7)"; EXPECT_EQ(actualResult, expectedResult); } // Test with a graph containing disconnected components - TEST(TopoSortTesting, DisconnectedGraph) + TEST(topoSortTesting, disconnectedGraph) { Graph graph; - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(3, 4); - graph.PushDirectedEdge(5, 6); + graph.pushDirectedEdge(1, 2); + graph.pushDirectedEdge(3, 4); + graph.pushDirectedEdge(5, 6); - graph.TopologicalSort(); - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); + graph.topologicalSort(); + string actualResult = unitTestHelper.serializeVectorToString(graph.showTopologicalSortResult()); string expectedResult = "5(9,12) 6(10,11) 3(5,8) 4(6,7) 1(1,4) 2(2,3)"; EXPECT_EQ(actualResult, expectedResult); } // Test with a graph that has multiple nodes pointing to the same node - TEST(TopoSortTesting, MultipleIncomingEdges) + TEST(topoSortTesting, multipleIncomingEdges) { Graph graph; - graph.PushDirectedEdge(1, 3); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(3, 4); + graph.pushDirectedEdge(1, 3); + graph.pushDirectedEdge(2, 3); + graph.pushDirectedEdge(3, 4); - graph.TopologicalSort(); - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); + graph.topologicalSort(); + string actualResult = unitTestHelper.serializeVectorToString(graph.showTopologicalSortResult()); string expectedResult = "2(7,8) 1(1,6) 3(2,5) 4(3,4)"; EXPECT_EQ(actualResult, expectedResult); } // Test for a single-node graph to check the base case - TEST(TopoSortTesting, SingleNodeGraph) + TEST(topoSortTesting, singleNodeGraph) { Graph graph; - graph.PushSingleNode(1); + graph.pushSingleNode(1); - graph.TopologicalSort(); - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); + graph.topologicalSort(); + string actualResult = unitTestHelper.serializeVectorToString(graph.showTopologicalSortResult()); string expectedResult = "1(1,2)"; EXPECT_EQ(actualResult, expectedResult); } - TEST(TopoSortTesting, ShowTopoSortResultUsingKahnAlgorithm) + TEST(topoSortTesting, showTopoSortResultUsingKahnAlgorithm) { Graph graph; - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(1, 4); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(4, 3); - graph.PushSingleNode(5); - graph.PushDirectedEdge(6, 7); - graph.PushDirectedEdge(6, 8); - graph.PushDirectedEdge(7, 4); - graph.PushDirectedEdge(7, 8); - graph.PushDirectedEdge(9, 8); + graph.pushDirectedEdge(1, 2); + graph.pushDirectedEdge(1, 4); + graph.pushDirectedEdge(2, 3); + graph.pushDirectedEdge(4, 3); + graph.pushSingleNode(5); + graph.pushDirectedEdge(6, 7); + graph.pushDirectedEdge(6, 8); + graph.pushDirectedEdge(7, 4); + graph.pushDirectedEdge(7, 8); + graph.pushDirectedEdge(9, 8); - graph.KahnTopologicalSort(); + graph.kahnTopologicalSort(); - string actualResult = unitTestHelper.SerializeVectorToString(graph.ShowTopologicalSortResult()); + string actualResult = unitTestHelper.serializeVectorToString(graph.showTopologicalSortResult()); string expectedResult = "1(1,5) 5(2,7) 6(3,8) 9(4,10) 2(6,11) 7(9,12) 4(13,15) 8(14,17) 3(16,18)"; EXPECT_EQ(actualResult, expectedResult); diff --git a/tests/0003_graph/0004_strongly_connected_components_test.cc b/tests/0003_graph/0004_strongly_connected_components_test.cc index f8ede7f..8b8c84d 100644 --- a/tests/0003_graph/0004_strongly_connected_components_test.cc +++ b/tests/0003_graph/0004_strongly_connected_components_test.cc @@ -1,102 +1,102 @@ #include -#include "0004_StronglyConnectedComponents.h" -#include "../0000_common_utilities/UnitTestHelper.h" +#include "0004_strongly_connected_components.h" +#include "../0000_common_utilities/unit_test_helper.h" -namespace StronglyConnectedComponents +namespace strongly_connected_components { UnitTestHelper unitTestHelper; - // Test case: Testing with a simple graph. - TEST(StronglyConnectedComponentsTesting, SimpleGraphTest) + // Test case: testing with a simple graph. + TEST(stronglyConnectedComponentsTesting, simpleGraphTest) { Graph graph; - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(1, 5); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(2, 4); - graph.PushDirectedEdge(3, 2); - graph.PushDirectedEdge(4, 4); - graph.PushDirectedEdge(5, 1); - graph.PushDirectedEdge(5, 4); - graph.PushDirectedEdge(6, 1); - graph.PushDirectedEdge(6, 3); - graph.PushDirectedEdge(6, 7); - graph.PushDirectedEdge(7, 3); - graph.PushDirectedEdge(7, 8); - graph.PushDirectedEdge(8, 6); + graph.pushDirectedEdge(1, 2); + graph.pushDirectedEdge(1, 5); + graph.pushDirectedEdge(2, 3); + graph.pushDirectedEdge(2, 4); + graph.pushDirectedEdge(3, 2); + graph.pushDirectedEdge(4, 4); + graph.pushDirectedEdge(5, 1); + graph.pushDirectedEdge(5, 4); + graph.pushDirectedEdge(6, 1); + graph.pushDirectedEdge(6, 3); + graph.pushDirectedEdge(6, 7); + graph.pushDirectedEdge(7, 3); + graph.pushDirectedEdge(7, 8); + graph.pushDirectedEdge(8, 6); - auto actualResult = graph.FindAllStronglyConnectedComponents(); + auto actualResult = graph.findAllStronglyConnectedComponents(); vector> expectedResult = { {6, 8, 7},{1, 5},{2, 3},{4} }; - EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); + EXPECT_EQ(unitTestHelper.sortVectorOfVectors(actualResult), unitTestHelper.sortVectorOfVectors(expectedResult)); } - // Test case: Single Node. - TEST(StronglyConnectedComponentsTesting, SingleNodeTest) + // Test case: single Node. + TEST(stronglyConnectedComponentsTesting, singleNodeTest) { Graph graph; - graph.PushSingleNode(1); + graph.pushSingleNode(1); - auto actualResult = graph.FindAllStronglyConnectedComponents(); + auto actualResult = graph.findAllStronglyConnectedComponents(); vector> expectedResult = { {1} }; - EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); + EXPECT_EQ(unitTestHelper.sortVectorOfVectors(actualResult), unitTestHelper.sortVectorOfVectors(expectedResult)); } - // Test case: Disconnected Graph. - TEST(StronglyConnectedComponentsTesting, DisconnectedGraphTest) + // Test case: disconnected Graph. + TEST(stronglyConnectedComponentsTesting, disconnectedGraphTest) { Graph graph; - graph.PushSingleNode(1); - graph.PushSingleNode(2); - graph.PushSingleNode(3); + graph.pushSingleNode(1); + graph.pushSingleNode(2); + graph.pushSingleNode(3); - auto actualResult = graph.FindAllStronglyConnectedComponents(); + auto actualResult = graph.findAllStronglyConnectedComponents(); vector> expectedResult = { {1},{3},{2} }; - EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); + EXPECT_EQ(unitTestHelper.sortVectorOfVectors(actualResult), unitTestHelper.sortVectorOfVectors(expectedResult)); } - // Test case: Chain of Nodes. - TEST(StronglyConnectedComponentsTesting, ChainOfNodesTest) + // Test case: chain of nodes. + TEST(stronglyConnectedComponentsTesting, chainOfNodesTest) { Graph graph; - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(3, 4); + graph.pushDirectedEdge(1, 2); + graph.pushDirectedEdge(2, 3); + graph.pushDirectedEdge(3, 4); - auto actualResult = graph.FindAllStronglyConnectedComponents(); + auto actualResult = graph.findAllStronglyConnectedComponents(); vector> expectedResult = { {2},{1},{3},{4} }; - EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); + EXPECT_EQ(unitTestHelper.sortVectorOfVectors(actualResult), unitTestHelper.sortVectorOfVectors(expectedResult)); } - // Test case: Bidirectional Edge. - TEST(StronglyConnectedComponentsTesting, BidirectionalEdgeTest) + // Test case: bidirectional Edge. + TEST(stronglyConnectedComponentsTesting, bidirectionalEdgeTest) { Graph graph; - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(2, 1); + graph.pushDirectedEdge(1, 2); + graph.pushDirectedEdge(2, 1); - auto actualResult = graph.FindAllStronglyConnectedComponents(); + auto actualResult = graph.findAllStronglyConnectedComponents(); vector> expectedResult = { {2, 1} }; - EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); + EXPECT_EQ(unitTestHelper.sortVectorOfVectors(actualResult), unitTestHelper.sortVectorOfVectors(expectedResult)); } - // Test case: Complex Graph. - TEST(StronglyConnectedComponentsTesting, ComplexGraphTest) + // Test case: complex Graph. + TEST(stronglyConnectedComponentsTesting, complexGraphTest) { Graph graph; - // Graph structure with multiple SCCs and isolated nodes. - graph.PushDirectedEdge(1, 2); - graph.PushDirectedEdge(2, 3); - graph.PushDirectedEdge(3, 1); // Cycle: 1 -> 2 -> 3 -> 1 - graph.PushDirectedEdge(4, 5); - graph.PushDirectedEdge(5, 6); - graph.PushDirectedEdge(6, 4); // Cycle: 4 -> 5 -> 6 -> 4 - graph.PushDirectedEdge(7, 8); // Single direction: 7 -> 8 - graph.PushSingleNode(9); // Isolated node. + // Graph structure with multiple sCCs and isolated nodes. + graph.pushDirectedEdge(1, 2); + graph.pushDirectedEdge(2, 3); + graph.pushDirectedEdge(3, 1); // cycle: 1 -> 2 -> 3 -> 1 + graph.pushDirectedEdge(4, 5); + graph.pushDirectedEdge(5, 6); + graph.pushDirectedEdge(6, 4); // cycle: 4 -> 5 -> 6 -> 4 + graph.pushDirectedEdge(7, 8); // single direction: 7 -> 8 + graph.pushSingleNode(9); // isolated node. - auto actualResult = graph.FindAllStronglyConnectedComponents(); + auto actualResult = graph.findAllStronglyConnectedComponents(); vector> expectedResult = { {4, 6, 5},{7}, { 2, 3, 1},{8}, {9} }; - EXPECT_EQ(unitTestHelper.SortVectorOfVectors(actualResult), unitTestHelper.SortVectorOfVectors(expectedResult)); + EXPECT_EQ(unitTestHelper.sortVectorOfVectors(actualResult), unitTestHelper.sortVectorOfVectors(expectedResult)); } } \ No newline at end of file diff --git a/tests/0003_graph/0005_hamiltonian_path_and_cycle_test.cc b/tests/0003_graph/0005_hamiltonian_path_and_cycle_test.cc index 33c351e..2a1aae2 100644 --- a/tests/0003_graph/0005_hamiltonian_path_and_cycle_test.cc +++ b/tests/0003_graph/0005_hamiltonian_path_and_cycle_test.cc @@ -1,33 +1,33 @@ #include -#include "0005_HamiltonianPathAndCycle.h" -#include "../0000_common_utilities/UnitTestHelper.h" +#include "0005_hamiltonian_path_and_cycle.h" +#include "../0000_common_utilities/unit_test_helper.h" -namespace HamiltonianPathAndCycle +namespace hamiltonian_path_and_cycle { UnitTestHelper unitTestHelper; - TEST(HamiltonianCycleAndPathTest, ShowResult) + TEST(hamiltonianCycleAndPathTest, showResult) { Graph graph; - graph.PushUndirectedEdge(0, 1); - graph.PushUndirectedEdge(0, 3); - graph.PushUndirectedEdge(1, 2); - graph.PushUndirectedEdge(1, 3); - graph.PushUndirectedEdge(1, 4); - graph.PushUndirectedEdge(2, 4); - graph.PushUndirectedEdge(3, 4); + graph.pushUndirectedEdge(0, 1); + graph.pushUndirectedEdge(0, 3); + graph.pushUndirectedEdge(1, 2); + graph.pushUndirectedEdge(1, 3); + graph.pushUndirectedEdge(1, 4); + graph.pushUndirectedEdge(2, 4); + graph.pushUndirectedEdge(3, 4); - graph.FindHamiltonianCycleAndPath(); + graph.findHamiltonianCycleAndPath(); - bool isHamiltonianCyclePresent = graph.IsHamiltonianCyclePresent(); - bool isHamiltonianPathPresent = graph.IsHamiltonianPathPresent(); + bool isHamiltonianCyclePresent = graph.isHamiltonianCyclePresent(); + bool isHamiltonianPathPresent = graph.isHamiltonianPathPresent(); - vector hamiltonianPathActualResult = graph.GetHamiltonianPath(); + vector hamiltonianPathActualResult = graph.getHamiltonianPath(); vector hamiltonianPathExpectedResult = { 4, 3, 0, 1, 2 }; ASSERT_TRUE(isHamiltonianCyclePresent); ASSERT_TRUE(isHamiltonianPathPresent); - ASSERT_TRUE(unitTestHelper.NormalizeCyclesAndCompare(hamiltonianPathActualResult, hamiltonianPathExpectedResult)); + ASSERT_TRUE(unitTestHelper.normalizeCyclesAndCompare(hamiltonianPathActualResult, hamiltonianPathExpectedResult)); } } \ No newline at end of file diff --git a/tests/0003_graph/0006_eulerian_path_and_circuit_test.cc b/tests/0003_graph/0006_eulerian_path_and_circuit_test.cc index a163a5c..246f0c3 100644 --- a/tests/0003_graph/0006_eulerian_path_and_circuit_test.cc +++ b/tests/0003_graph/0006_eulerian_path_and_circuit_test.cc @@ -1,28 +1,28 @@ #include -#include "0006_EulerianPathAndCircuit.h" -#include "../0000_common_utilities/UnitTestHelper.h" +#include "0006_eulerian_path_and_circuit.h" +#include "../0000_common_utilities/unit_test_helper.h" -namespace EulerianPathAndCircuit +namespace eulerian_path_and_circuit { UnitTestHelper unitTestHelper; - TEST(EulerianPathAndCycle, Test1) + TEST(eulerianPathAndCycle, test1) { Graph graph; - graph.PushUndirectedEdge(1, 0); - graph.PushUndirectedEdge(0, 2); - graph.PushUndirectedEdge(2, 1); - graph.PushUndirectedEdge(0, 3); - graph.PushUndirectedEdge(3, 4); - graph.PushUndirectedEdge(4, 0); + graph.pushUndirectedEdge(1, 0); + graph.pushUndirectedEdge(0, 2); + graph.pushUndirectedEdge(2, 1); + graph.pushUndirectedEdge(0, 3); + graph.pushUndirectedEdge(3, 4); + graph.pushUndirectedEdge(4, 0); - graph.FindEulerianPathAndCircuit(); + graph.findEulerianPathAndCircuit(); - bool isEulerianPathPresent = graph.IsEulerianPathPresent(); - bool isEulerianCircuitPresent = graph.IsEulerianCircuitPresent(); + bool isEulerianPathPresent = graph.isEulerianPathPresent(); + bool isEulerianCircuitPresent = graph.isEulerianCircuitPresent(); - vector actualEulerianPath = graph.UndirectedGraphGetEulerianPath(); + vector actualEulerianPath = graph.undirectedGraphGetEulerianPath(); vector expectedEulerianPath = { 0, 1, 2, 0, 3, 4, 0}; ASSERT_TRUE(isEulerianPathPresent); diff --git a/tests/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm_test.cc b/tests/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm_test.cc index 5736b79..4672fc0 100644 --- a/tests/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm_test.cc +++ b/tests/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm_test.cc @@ -1,33 +1,33 @@ #include -#include "0007_MinimumSpanningTreeKruskalAlgorithm.h" -#include "../0000_common_utilities/UnitTestHelper.h" +#include "0007_minimum_spanning_tree_kruskal_algorithm.h" +#include "../0000_common_utilities/unit_test_helper.h" -namespace MinimumSpanningTreeKruskalAlgorithm +namespace minimum_spanning_tree_kruskal_algorithm { UnitTestHelper unitTestHelper; - TEST(MST, Kruskal) + TEST(MST, kruskal) { Graph graph; - graph.PushUndirectedEdge(1, 2, 4); - graph.PushUndirectedEdge(1, 8, 8); - graph.PushUndirectedEdge(2, 8, 11); - graph.PushUndirectedEdge(2, 3, 8); - graph.PushUndirectedEdge(3, 4, 7); - graph.PushUndirectedEdge(3, 9, 2); - graph.PushUndirectedEdge(3, 6, 4); - graph.PushUndirectedEdge(4, 5, 9); - graph.PushUndirectedEdge(4, 6, 14); - graph.PushUndirectedEdge(5, 6, 10); - graph.PushUndirectedEdge(6, 7, 2); - graph.PushUndirectedEdge(7, 8, 1); - graph.PushUndirectedEdge(7, 9, 6); - graph.PushUndirectedEdge(8, 9, 7); + graph.pushUndirectedEdge(1, 2, 4); + graph.pushUndirectedEdge(1, 8, 8); + graph.pushUndirectedEdge(2, 8, 11); + graph.pushUndirectedEdge(2, 3, 8); + graph.pushUndirectedEdge(3, 4, 7); + graph.pushUndirectedEdge(3, 9, 2); + graph.pushUndirectedEdge(3, 6, 4); + graph.pushUndirectedEdge(4, 5, 9); + graph.pushUndirectedEdge(4, 6, 14); + graph.pushUndirectedEdge(5, 6, 10); + graph.pushUndirectedEdge(6, 7, 2); + graph.pushUndirectedEdge(7, 8, 1); + graph.pushUndirectedEdge(7, 9, 6); + graph.pushUndirectedEdge(8, 9, 7); - graph.FindMinimumSpanningTreeKruskalAlgorithm(); + graph.findMinimumSpanningTreeKruskalAlgorithm(); - vector, int>> actualMST = graph.GetMinimumSpanningTree(); + vector, int>> actualMST = graph.getMinimumSpanningTree(); vector, int>> expectedMST = { {{7, 8}, 1}, @@ -40,6 +40,6 @@ namespace MinimumSpanningTreeKruskalAlgorithm {{4, 5}, 9} }; - ASSERT_EQ(unitTestHelper.SortVectorOfPair(actualMST), unitTestHelper.SortVectorOfPair(expectedMST)); + ASSERT_EQ(unitTestHelper.sortVectorOfPair(actualMST), unitTestHelper.sortVectorOfPair(expectedMST)); } } \ No newline at end of file diff --git a/tests/0003_graph/0008_minimum_spanning_tree_prim_algorithm_test.cc b/tests/0003_graph/0008_minimum_spanning_tree_prim_algorithm_test.cc index 251c654..145b07d 100644 --- a/tests/0003_graph/0008_minimum_spanning_tree_prim_algorithm_test.cc +++ b/tests/0003_graph/0008_minimum_spanning_tree_prim_algorithm_test.cc @@ -1,33 +1,33 @@ #include -#include "0008_MinimumSpanningTreePrimAlgorithm.h" -#include "../0000_common_utilities/UnitTestHelper.h" +#include "0008_minimum_spanning_tree_prim_algorithm.h" +#include "../0000_common_utilities/unit_test_helper.h" -namespace MinimumSpanningTreePrimAlgorithm +namespace minimum_spanning_tree_prim_algorithm { UnitTestHelper unitTestHelper; - TEST(MST, Prim) + TEST(MST, prim) { Graph graph; - graph.PushUndirectedEdge(1, 2, 4); - graph.PushUndirectedEdge(1, 8, 8); - graph.PushUndirectedEdge(2, 8, 11); - graph.PushUndirectedEdge(2, 3, 8); - graph.PushUndirectedEdge(3, 4, 7); - graph.PushUndirectedEdge(3, 9, 2); - graph.PushUndirectedEdge(3, 6, 4); - graph.PushUndirectedEdge(4, 5, 9); - graph.PushUndirectedEdge(4, 6, 14); - graph.PushUndirectedEdge(5, 6, 10); - graph.PushUndirectedEdge(6, 7, 2); - graph.PushUndirectedEdge(7, 8, 1); - graph.PushUndirectedEdge(7, 9, 6); - graph.PushUndirectedEdge(8, 9, 7); + graph.pushUndirectedEdge(1, 2, 4); + graph.pushUndirectedEdge(1, 8, 8); + graph.pushUndirectedEdge(2, 8, 11); + graph.pushUndirectedEdge(2, 3, 8); + graph.pushUndirectedEdge(3, 4, 7); + graph.pushUndirectedEdge(3, 9, 2); + graph.pushUndirectedEdge(3, 6, 4); + graph.pushUndirectedEdge(4, 5, 9); + graph.pushUndirectedEdge(4, 6, 14); + graph.pushUndirectedEdge(5, 6, 10); + graph.pushUndirectedEdge(6, 7, 2); + graph.pushUndirectedEdge(7, 8, 1); + graph.pushUndirectedEdge(7, 9, 6); + graph.pushUndirectedEdge(8, 9, 7); - graph.FindMinimumSpanningTreePrimAlgorithm(); + graph.findMinimumSpanningTreePrimAlgorithm(); - vector, int>> actualMST = graph.GetMinimumSpanningTree(); + vector, int>> actualMST = graph.getMinimumSpanningTree(); vector, int>> expectedMST = { {{7, 8}, 1}, @@ -40,6 +40,6 @@ namespace MinimumSpanningTreePrimAlgorithm {{4, 5}, 9} }; - ASSERT_EQ(unitTestHelper.SortVectorOfPair(actualMST), unitTestHelper.SortVectorOfPair(expectedMST)); + ASSERT_EQ(unitTestHelper.sortVectorOfPair(actualMST), unitTestHelper.sortVectorOfPair(expectedMST)); } } \ No newline at end of file diff --git a/tests/0003_graph/0009_single_source_shortest_path_bellman_ford_test.cc b/tests/0003_graph/0009_single_source_shortest_path_bellman_ford_test.cc index fc84901..26b55ac 100644 --- a/tests/0003_graph/0009_single_source_shortest_path_bellman_ford_test.cc +++ b/tests/0003_graph/0009_single_source_shortest_path_bellman_ford_test.cc @@ -1,104 +1,104 @@ #include -#include "0009_SingleSourceShortestPathBellmanFord.h" -#include "../0000_common_utilities/UnitTestHelper.h" +#include "0009_single_source_shortest_path_bellman_ford.h" +#include "../0000_common_utilities/unit_test_helper.h" -namespace SingleSourceShortestPathBellmanFord +namespace single_source_shortest_path_bellman_ford { UnitTestHelper unitTestHelper; - // Test for Simple Graph - TEST(BellmanFordTest, SimpleTest) + // Test for simple Graph + TEST(bellmanFordTest, simpleTest) { Graph graph; - graph.PushDirectedEdge(0, 1, 6); - graph.PushDirectedEdge(0, 3, 7); - graph.PushDirectedEdge(1, 2, 5); - graph.PushDirectedEdge(1, 3, 8); - graph.PushDirectedEdge(1, 4, -4); - graph.PushDirectedEdge(2, 1, -2); - graph.PushDirectedEdge(3, 2, -3); - graph.PushDirectedEdge(3, 4, 9); - graph.PushDirectedEdge(3, 4, 9); - graph.PushDirectedEdge(4, 2, 7); - graph.PushDirectedEdge(4, 0, 2); + graph.pushDirectedEdge(0, 1, 6); + graph.pushDirectedEdge(0, 3, 7); + graph.pushDirectedEdge(1, 2, 5); + graph.pushDirectedEdge(1, 3, 8); + graph.pushDirectedEdge(1, 4, -4); + graph.pushDirectedEdge(2, 1, -2); + graph.pushDirectedEdge(3, 2, -3); + graph.pushDirectedEdge(3, 4, 9); + graph.pushDirectedEdge(3, 4, 9); + graph.pushDirectedEdge(4, 2, 7); + graph.pushDirectedEdge(4, 0, 2); string expectedResult = "0 3 2 1 4"; - ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); - ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(4)), expectedResult); + ASSERT_TRUE(graph.findSingleSourceShortestPathBellmanFord(0)); + ASSERT_EQ(unitTestHelper.serializeVectorToString(graph.getShortestPathBellmanFord(4)), expectedResult); } - // Test for Single Node Graph - TEST(BellmanFordTest, SingleNodeTest) + // Test for single Node Graph + TEST(bellmanFordTest, singleNodeTest) { Graph graph; - graph.PushDirectedEdge(0, 0, 0); // Self-loop + graph.pushDirectedEdge(0, 0, 0); // self-loop string expectedResult = "0"; - ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); - ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(0)), expectedResult); + ASSERT_TRUE(graph.findSingleSourceShortestPathBellmanFord(0)); + ASSERT_EQ(unitTestHelper.serializeVectorToString(graph.getShortestPathBellmanFord(0)), expectedResult); } - // Test for Negative Weight Cycle - TEST(BellmanFordTest, NegativeWeightCycleTest) + // Test for negative weight cycle + TEST(bellmanFordTest, negativeWeightCycleTest) { Graph graph; - graph.PushDirectedEdge(0, 1, 1); - graph.PushDirectedEdge(1, 2, -1); - graph.PushDirectedEdge(2, 0, -1); // Negative weight cycle + graph.pushDirectedEdge(0, 1, 1); + graph.pushDirectedEdge(1, 2, -1); + graph.pushDirectedEdge(2, 0, -1); // negative weight cycle - ASSERT_FALSE(graph.FindSingleSourceShortestPathBellmanFord(0)); + ASSERT_FALSE(graph.findSingleSourceShortestPathBellmanFord(0)); } - // Test for Multiple Shortest Paths - TEST(BellmanFordTest, MultipleShortestPathsTest) + // Test for multiple shortest paths + TEST(bellmanFordTest, multipleShortestPathsTest) { Graph graph; - graph.PushDirectedEdge(0, 1, 5); - graph.PushDirectedEdge(0, 2, 5); - graph.PushDirectedEdge(1, 3, 1); - graph.PushDirectedEdge(2, 3, 1); + graph.pushDirectedEdge(0, 1, 5); + graph.pushDirectedEdge(0, 2, 5); + graph.pushDirectedEdge(1, 3, 1); + graph.pushDirectedEdge(2, 3, 1); string expectedResult = "0 1 3"; - ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); - ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(3)), expectedResult); + ASSERT_TRUE(graph.findSingleSourceShortestPathBellmanFord(0)); + ASSERT_EQ(unitTestHelper.serializeVectorToString(graph.getShortestPathBellmanFord(3)), expectedResult); } - // Test for All Negative Weights - TEST(BellmanFordTest, AllNegativeWeightsTest) + // Test for all negative weights + TEST(bellmanFordTest, allNegativeWeightsTest) { Graph graph; - graph.PushDirectedEdge(0, 1, -5); - graph.PushDirectedEdge(1, 2, -3); - graph.PushDirectedEdge(2, 3, -2); - graph.PushDirectedEdge(3, 4, -1); + graph.pushDirectedEdge(0, 1, -5); + graph.pushDirectedEdge(1, 2, -3); + graph.pushDirectedEdge(2, 3, -2); + graph.pushDirectedEdge(3, 4, -1); string expectedResult = "0 1 2 3 4"; - ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); - ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(4)), expectedResult); + ASSERT_TRUE(graph.findSingleSourceShortestPathBellmanFord(0)); + ASSERT_EQ(unitTestHelper.serializeVectorToString(graph.getShortestPathBellmanFord(4)), expectedResult); } - // Test for Large Graph - TEST(BellmanFordTest, LargeGraphTest) + // Test for large Graph + TEST(bellmanFordTest, largeGraphTest) { Graph graph; for (int i = 0; i < 100; ++i) { - graph.PushDirectedEdge(i, i + 1, 1); + graph.pushDirectedEdge(i, i + 1, 1); } string expectedResult = "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20"; - ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); - ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(20)), expectedResult); + ASSERT_TRUE(graph.findSingleSourceShortestPathBellmanFord(0)); + ASSERT_EQ(unitTestHelper.serializeVectorToString(graph.getShortestPathBellmanFord(20)), expectedResult); } - // Test for Self-Loop Edge - TEST(BellmanFordTest, SelfLoopTest) + // Test for self-loop Edge + TEST(bellmanFordTest, selfLoopTest) { Graph graph; - graph.PushDirectedEdge(0, 0, 10); // Self-loop with weight 10 + graph.pushDirectedEdge(0, 0, 10); // self-loop with weight 10 string expectedResult = "0"; - ASSERT_TRUE(graph.FindSingleSourceShortestPathBellmanFord(0)); - ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetShortestPathBellmanFord(0)), expectedResult); + ASSERT_TRUE(graph.findSingleSourceShortestPathBellmanFord(0)); + ASSERT_EQ(unitTestHelper.serializeVectorToString(graph.getShortestPathBellmanFord(0)), expectedResult); } } diff --git a/tests/0003_graph/0010_directed_acyclic_graph_shortest_path_test.cc b/tests/0003_graph/0010_directed_acyclic_graph_shortest_path_test.cc index 50d7086..7e5cf1e 100644 --- a/tests/0003_graph/0010_directed_acyclic_graph_shortest_path_test.cc +++ b/tests/0003_graph/0010_directed_acyclic_graph_shortest_path_test.cc @@ -1,29 +1,29 @@ #include -#include "0010_DirectedAcyclicGraphShortestPath.h" -#include "../0000_common_utilities/UnitTestHelper.h" +#include "0010_directed_acyclic_graph_shortest_path.h" +#include "../0000_common_utilities/unit_test_helper.h" -namespace DirectedAcyclicGraphShortestPath +namespace directed_acyclic_graph_shortest_path { UnitTestHelper unitTestHelper; - // Test for Simple Graph - TEST(DAGTest, SimpleGraph) + // Test for simple Graph + TEST(dAGTest, simpleGraph) { Graph graph; - graph.PushDirectedEdge(0, 1, 5); - graph.PushDirectedEdge(0, 2, 3); - graph.PushDirectedEdge(1, 2, 2); - graph.PushDirectedEdge(1, 3, 6); - graph.PushDirectedEdge(2, 3, 7); - graph.PushDirectedEdge(2, 4, 4); - graph.PushDirectedEdge(2, 5, 2); - graph.PushDirectedEdge(3, 4, -1); - graph.PushDirectedEdge(3, 5, 1); - graph.PushDirectedEdge(4, 5, -2); + graph.pushDirectedEdge(0, 1, 5); + graph.pushDirectedEdge(0, 2, 3); + graph.pushDirectedEdge(1, 2, 2); + graph.pushDirectedEdge(1, 3, 6); + graph.pushDirectedEdge(2, 3, 7); + graph.pushDirectedEdge(2, 4, 4); + graph.pushDirectedEdge(2, 5, 2); + graph.pushDirectedEdge(3, 4, -1); + graph.pushDirectedEdge(3, 5, 1); + graph.pushDirectedEdge(4, 5, -2); - graph.FindDAGShortestPath(1); + graph.findDAGShortestPath(1); string expectedPath = "1 3 4 5"; - ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetDAGShortestPath(5)), expectedPath); + ASSERT_EQ(unitTestHelper.serializeVectorToString(graph.getDAGShortestPath(5)), expectedPath); } } \ No newline at end of file diff --git a/tests/0003_graph/0011_single_source_shortest_path_dijkstra_test.cc b/tests/0003_graph/0011_single_source_shortest_path_dijkstra_test.cc index 5460b1b..8835eb9 100644 --- a/tests/0003_graph/0011_single_source_shortest_path_dijkstra_test.cc +++ b/tests/0003_graph/0011_single_source_shortest_path_dijkstra_test.cc @@ -1,31 +1,31 @@ #include -#include "0011_SingleSourceShortestPathDijkstra.h" -#include "../0000_common_utilities/UnitTestHelper.h" +#include "0011_single_source_shortest_path_dijkstra.h" +#include "../0000_common_utilities/unit_test_helper.h" -namespace SingleSourceShortestPathDijkstra +namespace single_source_shortest_path_dijkstra { UnitTestHelper unitTestHelper; - // Test for Simple Graph - TEST(DijkstraTest, SimpleGraph) + // Test for simple Graph + TEST(dijkstraTest, simpleGraph) { Graph graph; - graph.PushDirectedEdge(0, 1, 10); - graph.PushDirectedEdge(0, 3, 5); - graph.PushDirectedEdge(1, 2, 1); - graph.PushDirectedEdge(1, 3, 2); - graph.PushDirectedEdge(2, 4, 4); - graph.PushDirectedEdge(3, 1, 3); - graph.PushDirectedEdge(3, 2, 9); - graph.PushDirectedEdge(3, 4, 2); - graph.PushDirectedEdge(4, 2, 6); - graph.PushDirectedEdge(4, 0, 7); + graph.pushDirectedEdge(0, 1, 10); + graph.pushDirectedEdge(0, 3, 5); + graph.pushDirectedEdge(1, 2, 1); + graph.pushDirectedEdge(1, 3, 2); + graph.pushDirectedEdge(2, 4, 4); + graph.pushDirectedEdge(3, 1, 3); + graph.pushDirectedEdge(3, 2, 9); + graph.pushDirectedEdge(3, 4, 2); + graph.pushDirectedEdge(4, 2, 6); + graph.pushDirectedEdge(4, 0, 7); - graph.FindShortestPathDijkstra(0); + graph.findShortestPathDijkstra(0); string expectedPath = "0 3 1 2"; - ASSERT_EQ(unitTestHelper.SerializeVectorToString(graph.GetDijkstraShortestPath(2)), expectedPath); + ASSERT_EQ(unitTestHelper.serializeVectorToString(graph.getDijkstraShortestPath(2)), expectedPath); } } \ No newline at end of file diff --git a/tests/0003_graph/0012_difference_constraints_shortest_paths_test.cc b/tests/0003_graph/0012_difference_constraints_shortest_paths_test.cc index 152dd0d..e2ef7c7 100644 --- a/tests/0003_graph/0012_difference_constraints_shortest_paths_test.cc +++ b/tests/0003_graph/0012_difference_constraints_shortest_paths_test.cc @@ -1,13 +1,13 @@ #include -#include "0012_DifferenceConstraintsShortestPaths.h" -#include"../0000_common_utilities/UnitTestHelper.h" +#include "0012_difference_constraints_shortest_paths.h" +#include"../0000_common_utilities/unit_test_helper.h" using namespace std; -namespace DifferenceConstraintsShortestPaths +namespace difference_constraints_shortest_paths { UnitTestHelper unitTestHelper; - TEST(DifferenceConstraints, SimpleGraph) + TEST(differenceConstraints, simpleGraph) { Graph graph; @@ -32,9 +32,9 @@ namespace DifferenceConstraintsShortestPaths {"v4", -1}, {"v3", 0}, }; - graph.PushAllDirectedEdges(vectorA, vectorX, vectorB); + graph.pushAllDirectedEdges(vectorA, vectorX, vectorB); - ASSERT_TRUE(graph.FindDifferenceConstraintsSolutionBellmanFord()); - ASSERT_EQ(unitTestHelper.SortVectorOfPairAndSerialize(graph.GetDifferenceConstrtaintsSolution()), unitTestHelper.SortVectorOfPairAndSerialize(expectedSolution)); + ASSERT_TRUE(graph.findDifferenceConstraintsSolutionBellmanFord()); + ASSERT_EQ(unitTestHelper.sortVectorOfPairAndSerialize(graph.getDifferenceConstrtaintsSolution()), unitTestHelper.sortVectorOfPairAndSerialize(expectedSolution)); } } \ No newline at end of file diff --git a/tests/0003_graph/0013_all_pairs_shortest_paths_floyd_warshall_test.cc b/tests/0003_graph/0013_all_pairs_shortest_paths_floyd_warshall_test.cc index 17a5045..7194c3f 100644 --- a/tests/0003_graph/0013_all_pairs_shortest_paths_floyd_warshall_test.cc +++ b/tests/0003_graph/0013_all_pairs_shortest_paths_floyd_warshall_test.cc @@ -1,36 +1,36 @@ #include -#include "0013_AllPairsShortestPathsFloydWarshall.h" -#include "../0000_common_utilities/UnitTestHelper.h" +#include "0013_all_pairs_shortest_paths_floyd_warshall.h" +#include "../0000_common_utilities/unit_test_helper.h" using namespace std; -namespace AllPairsShortestPathsFloydWarshall +namespace all_pairs_shortest_paths_floyd_warshall { UnitTestHelper unitTestHelper; - TEST(FloydWarshall, SimpleGraph) + TEST(floydWarshall, simpleGraph) { - // Arrange + // arrange Graph graph; int noOfVertices = 5; string expectedResult = "[1 5 4 3 2][1 5 4 3][1 5 4][1 5][2 4 1][2 4 3][2 4][2 4 1 5][3 2 4 1][3 2][3 2 4][3 2 4 1 5][4 1][4 3 2][4 3][4 1 5][5 4 1][5 4 3 2][5 4 3][5 4]"; - // Act - graph.CreateGraph(noOfVertices); + // act + graph.createGraph(noOfVertices); - graph.PushDirectedEdge(1, 2, 3); - graph.PushDirectedEdge(1, 3, 8); - graph.PushDirectedEdge(1, 5, -4); - graph.PushDirectedEdge(2, 4, 1); - graph.PushDirectedEdge(2, 5, 7); - graph.PushDirectedEdge(3, 2, 4); - graph.PushDirectedEdge(4, 3, -5); - graph.PushDirectedEdge(4, 1, 2); - graph.PushDirectedEdge(5, 4, 6); + graph.pushDirectedEdge(1, 2, 3); + graph.pushDirectedEdge(1, 3, 8); + graph.pushDirectedEdge(1, 5, -4); + graph.pushDirectedEdge(2, 4, 1); + graph.pushDirectedEdge(2, 5, 7); + graph.pushDirectedEdge(3, 2, 4); + graph.pushDirectedEdge(4, 3, -5); + graph.pushDirectedEdge(4, 1, 2); + graph.pushDirectedEdge(5, 4, 6); - graph.FindAllPairsShortestPathsFloydWarshallSolution(); - string actualResult = unitTestHelper.SerializeVectorToString(graph.GetFloydWarshallShortestPath()); + graph.findAllPairsShortestPathsFloydWarshallSolution(); + string actualResult = unitTestHelper.serializeVectorToString(graph.getFloydWarshallShortestPath()); - // Assert + // assert ASSERT_EQ(actualResult, expectedResult); } } \ No newline at end of file diff --git a/tests/0003_graph/0014_all_pairs_shortest_paths_johnson_test.cc b/tests/0003_graph/0014_all_pairs_shortest_paths_johnson_test.cc index 66a63a1..f7bdea9 100644 --- a/tests/0003_graph/0014_all_pairs_shortest_paths_johnson_test.cc +++ b/tests/0003_graph/0014_all_pairs_shortest_paths_johnson_test.cc @@ -1,15 +1,15 @@ #include -#include "0014_AllPairsShortestPathsJohnson.h" -#include"../0000_common_utilities/UnitTestHelper.h" +#include "0014_all_pairs_shortest_paths_johnson.h" +#include"../0000_common_utilities/unit_test_helper.h" using namespace std; -namespace AllPairsShortestPathsJohnson +namespace all_pairs_shortest_paths_johnson { UnitTestHelper unitTestHelper; - TEST(JohnsonAlgorithm, SimpleGraph) + TEST(johnsonAlgorithm, simpleGraph) { - // Arrange + // arrange Graph graph; vector> expectedDistanceMatrix = { @@ -21,22 +21,22 @@ namespace AllPairsShortestPathsJohnson }; string expectedPredecessorMatrixesult = "[1 5 4 3 2][1 5 4 3][1 5 4][1 5][2 4 1][2 4 3][2 4][2 4 1 5][3 2 4 1][3 2][3 2 4][3 2 4 1 5][4 1][4 3 2][4 3][4 1 5][5 4 1][5 4 3 2][5 4 3][5 4]"; - // Act - graph.PushDirectedEdge(1, 2, 3); - graph.PushDirectedEdge(1, 3, 8); - graph.PushDirectedEdge(1, 5, -4); - graph.PushDirectedEdge(2, 4, 1); - graph.PushDirectedEdge(2, 5, 7); - graph.PushDirectedEdge(3, 2, 4); - graph.PushDirectedEdge(4, 3, -5); - graph.PushDirectedEdge(4, 1, 2); - graph.PushDirectedEdge(5, 4, 6); + // act + graph.pushDirectedEdge(1, 2, 3); + graph.pushDirectedEdge(1, 3, 8); + graph.pushDirectedEdge(1, 5, -4); + graph.pushDirectedEdge(2, 4, 1); + graph.pushDirectedEdge(2, 5, 7); + graph.pushDirectedEdge(3, 2, 4); + graph.pushDirectedEdge(4, 3, -5); + graph.pushDirectedEdge(4, 1, 2); + graph.pushDirectedEdge(5, 4, 6); - bool result = graph.FindAllPairsShortestPathsJohnsonAlgorithm(); - vector> actualDistanceMatrix = graph.GetAllPairsShortestPathsDistanceMatrix(); - string actualPredecessorMatrix = unitTestHelper.SerializeVectorToString(graph.GetAllPairsShortestPathsPathMatrix()); + bool result = graph.findAllPairsShortestPathsJohnsonAlgorithm(); + vector> actualDistanceMatrix = graph.getAllPairsShortestPathsDistanceMatrix(); + string actualPredecessorMatrix = unitTestHelper.serializeVectorToString(graph.getAllPairsShortestPathsPathMatrix()); - // Assert + // assert ASSERT_TRUE(result); ASSERT_EQ(expectedDistanceMatrix, actualDistanceMatrix); ASSERT_EQ(expectedPredecessorMatrixesult, actualPredecessorMatrix); diff --git a/tests/0003_graph/0015_maximum_flow_ford_fulkerson_test.cc b/tests/0003_graph/0015_maximum_flow_ford_fulkerson_test.cc index 117bfc2..f6b2a77 100644 --- a/tests/0003_graph/0015_maximum_flow_ford_fulkerson_test.cc +++ b/tests/0003_graph/0015_maximum_flow_ford_fulkerson_test.cc @@ -1,64 +1,64 @@ #include -#include "0015_MaximumFlowFordFulkerson.h" -#include "../0000_common_utilities/UnitTestHelper.h" +#include "0015_maximum_flow_ford_fulkerson.h" +#include "../0000_common_utilities/unit_test_helper.h" -namespace MaximumFlowFordFulkerson +namespace maximum_flow_ford_fulkerson { UnitTestHelper unitTestHelper; - TEST(MaximumFlowFordFulkerson, GraphWithNoParallelEdges) + TEST(maximumFlowFordFulkerson, graphWithNoParallelEdges) { - // Arrange + // arrange Graph graph; int noOfVertices = 6; int expectedMaximumFlow = 23; - // Act - graph.CreateGraph(noOfVertices); + // act + graph.createGraph(noOfVertices); - graph.PushDirectedEdge(0, 1, 16); - graph.PushDirectedEdge(0, 2, 13); - graph.PushDirectedEdge(1, 3, 12); - graph.PushDirectedEdge(2, 1, 4); - graph.PushDirectedEdge(2, 4, 14); - graph.PushDirectedEdge(3, 2, 9); - graph.PushDirectedEdge(3, 5, 20); - graph.PushDirectedEdge(4, 3, 7); - graph.PushDirectedEdge(4, 5, 4); + graph.pushDirectedEdge(0, 1, 16); + graph.pushDirectedEdge(0, 2, 13); + graph.pushDirectedEdge(1, 3, 12); + graph.pushDirectedEdge(2, 1, 4); + graph.pushDirectedEdge(2, 4, 14); + graph.pushDirectedEdge(3, 2, 9); + graph.pushDirectedEdge(3, 5, 20); + graph.pushDirectedEdge(4, 3, 7); + graph.pushDirectedEdge(4, 5, 4); - int actualMaximumFlow = graph.FindMaximumFlowFordFulkerson(); + int actualMaximumFlow = graph.findMaximumFlowFordFulkerson(); - // Assert + // assert ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); } - TEST(MaximumFlowFordFulkerson, GraphWithParallelEdges) + TEST(maximumFlowFordFulkerson, graphWithParallelEdges) { - // Arrange + // arrange Graph graph; int noOfVertices = 6; int expectedMaximumFlow = 24; - // Act - graph.CreateGraph(noOfVertices); + // act + graph.createGraph(noOfVertices); - graph.PushDirectedEdge(0, 1, 16); - graph.PushDirectedEdge(0, 2, 13); - graph.PushDirectedEdge(1, 3, 12); - graph.PushDirectedEdge(1, 2, 6); - graph.PushDirectedEdge(2, 1, 10); - graph.PushDirectedEdge(2, 4, 14); - graph.PushDirectedEdge(2, 3, 2); - graph.PushDirectedEdge(3, 2, 11); - graph.PushDirectedEdge(3, 5, 20); - graph.PushDirectedEdge(4, 3, 7); - graph.PushDirectedEdge(4, 5, 4); + graph.pushDirectedEdge(0, 1, 16); + graph.pushDirectedEdge(0, 2, 13); + graph.pushDirectedEdge(1, 3, 12); + graph.pushDirectedEdge(1, 2, 6); + graph.pushDirectedEdge(2, 1, 10); + graph.pushDirectedEdge(2, 4, 14); + graph.pushDirectedEdge(2, 3, 2); + graph.pushDirectedEdge(3, 2, 11); + graph.pushDirectedEdge(3, 5, 20); + graph.pushDirectedEdge(4, 3, 7); + graph.pushDirectedEdge(4, 5, 4); - int actualMaximumFlow = graph.FindMaximumFlowFordFulkerson(); + int actualMaximumFlow = graph.findMaximumFlowFordFulkerson(); - // Assert + // assert ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); } } \ No newline at end of file diff --git a/tests/0003_graph/0016_maximum_flow_edmonds_karp_test.cc b/tests/0003_graph/0016_maximum_flow_edmonds_karp_test.cc index 5d3177a..9205f34 100644 --- a/tests/0003_graph/0016_maximum_flow_edmonds_karp_test.cc +++ b/tests/0003_graph/0016_maximum_flow_edmonds_karp_test.cc @@ -1,64 +1,64 @@ #include -#include "0016_MaximumFlowEdmondsKarp.h" -#include "../0000_common_utilities/UnitTestHelper.h" +#include "0016_maximum_flow_edmonds_karp.h" +#include "../0000_common_utilities/unit_test_helper.h" -namespace MaximumFlowEdmondsKarp +namespace maximum_flow_edmonds_karp { UnitTestHelper unitTestHelper; - TEST(MaximumFlowEdmondsKarp, GraphWithNoParallelEdges) + TEST(maximumFlowEdmondsKarp, graphWithNoParallelEdges) { - // Arrange + // arrange Graph graph; int noOfVertices = 6; int expectedMaximumFlow = 23; - // Act - graph.CreateGraph(noOfVertices); + // act + graph.createGraph(noOfVertices); - graph.PushDirectedEdge(0, 1, 16); - graph.PushDirectedEdge(0, 2, 13); - graph.PushDirectedEdge(1, 3, 12); - graph.PushDirectedEdge(2, 1, 4); - graph.PushDirectedEdge(2, 4, 14); - graph.PushDirectedEdge(3, 2, 9); - graph.PushDirectedEdge(3, 5, 20); - graph.PushDirectedEdge(4, 3, 7); - graph.PushDirectedEdge(4, 5, 4); + graph.pushDirectedEdge(0, 1, 16); + graph.pushDirectedEdge(0, 2, 13); + graph.pushDirectedEdge(1, 3, 12); + graph.pushDirectedEdge(2, 1, 4); + graph.pushDirectedEdge(2, 4, 14); + graph.pushDirectedEdge(3, 2, 9); + graph.pushDirectedEdge(3, 5, 20); + graph.pushDirectedEdge(4, 3, 7); + graph.pushDirectedEdge(4, 5, 4); - int actualMaximumFlow = graph.FindMaximumFlowEdmondsKarp(); + int actualMaximumFlow = graph.findMaximumFlowEdmondsKarp(); - // Assert + // assert ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); } - TEST(MaximumFlowEdmondsKarp, GraphWithParallelEdges) + TEST(maximumFlowEdmondsKarp, graphWithParallelEdges) { - // Arrange + // arrange Graph graph; int noOfVertices = 6; int expectedMaximumFlow = 24; - // Act - graph.CreateGraph(noOfVertices); + // act + graph.createGraph(noOfVertices); - graph.PushDirectedEdge(0, 1, 16); - graph.PushDirectedEdge(0, 2, 13); - graph.PushDirectedEdge(1, 3, 12); - graph.PushDirectedEdge(1, 2, 6); - graph.PushDirectedEdge(2, 1, 10); - graph.PushDirectedEdge(2, 4, 14); - graph.PushDirectedEdge(2, 3, 2); - graph.PushDirectedEdge(3, 2, 11); - graph.PushDirectedEdge(3, 5, 20); - graph.PushDirectedEdge(4, 3, 7); - graph.PushDirectedEdge(4, 5, 4); + graph.pushDirectedEdge(0, 1, 16); + graph.pushDirectedEdge(0, 2, 13); + graph.pushDirectedEdge(1, 3, 12); + graph.pushDirectedEdge(1, 2, 6); + graph.pushDirectedEdge(2, 1, 10); + graph.pushDirectedEdge(2, 4, 14); + graph.pushDirectedEdge(2, 3, 2); + graph.pushDirectedEdge(3, 2, 11); + graph.pushDirectedEdge(3, 5, 20); + graph.pushDirectedEdge(4, 3, 7); + graph.pushDirectedEdge(4, 5, 4); - int actualMaximumFlow = graph.FindMaximumFlowEdmondsKarp(); + int actualMaximumFlow = graph.findMaximumFlowEdmondsKarp(); - // Assert + // assert ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); } } \ No newline at end of file diff --git a/tests/0003_graph/0017_maximum_bipartite_matching_test.cc b/tests/0003_graph/0017_maximum_bipartite_matching_test.cc index d556e28..c5e7347 100644 --- a/tests/0003_graph/0017_maximum_bipartite_matching_test.cc +++ b/tests/0003_graph/0017_maximum_bipartite_matching_test.cc @@ -1,35 +1,35 @@ #include -#include "0017_MaximumBipartiteMatching.h" -#include "../0000_common_utilities/UnitTestHelper.h" +#include "0017_maximum_bipartite_matching.h" +#include "../0000_common_utilities/unit_test_helper.h" -namespace MaximumBipartiteMatching +namespace maximum_bipartite_matching { - TEST(MaximumBipartiteMatching, SimpleGraph) + TEST(maximumBipartiteMatching, simpleGraph) { - // Arrange + // arrange Graph graph; UnitTestHelper unitTestHelper; int noOfVertices = 9; int expectedMaximumMatching = 3; string expectedMatchings = "[0 1][2 6][3 5]"; - // Act - graph.CreateGraph(noOfVertices); + // act + graph.createGraph(noOfVertices); - graph.PushDirectedEdge(0, 1); - graph.PushDirectedEdge(2, 1); - graph.PushDirectedEdge(2, 6); - graph.PushDirectedEdge(3, 5); - graph.PushDirectedEdge(3, 6); - graph.PushDirectedEdge(3, 7); - graph.PushDirectedEdge(4, 6); - graph.PushDirectedEdge(8, 6); + graph.pushDirectedEdge(0, 1); + graph.pushDirectedEdge(2, 1); + graph.pushDirectedEdge(2, 6); + graph.pushDirectedEdge(3, 5); + graph.pushDirectedEdge(3, 6); + graph.pushDirectedEdge(3, 7); + graph.pushDirectedEdge(4, 6); + graph.pushDirectedEdge(8, 6); - int actualMaximumMatching = graph.FindMaximumBipartiteMatching(); - vector> actualMatchings = graph.GetMatchings(); + int actualMaximumMatching = graph.findMaximumBipartiteMatching(); + vector> actualMatchings = graph.getMatchings(); - // Assert + // assert ASSERT_EQ(expectedMaximumMatching, actualMaximumMatching); - ASSERT_EQ(expectedMatchings, unitTestHelper.SerializeVectorToString(actualMatchings)); + ASSERT_EQ(expectedMatchings, unitTestHelper.serializeVectorToString(actualMatchings)); } } \ No newline at end of file diff --git a/tests/0003_graph/0018_maximum_flow_goldberg_generic_push_relabel_test.cc b/tests/0003_graph/0018_maximum_flow_goldberg_generic_push_relabel_test.cc index 283cab0..878fc79 100644 --- a/tests/0003_graph/0018_maximum_flow_goldberg_generic_push_relabel_test.cc +++ b/tests/0003_graph/0018_maximum_flow_goldberg_generic_push_relabel_test.cc @@ -1,35 +1,35 @@ #include -#include "0018_MaximumFlowGoldbergGenericPushRelabel.h" -#include "../0000_common_utilities/UnitTestHelper.h" +#include "0018_maximum_flow_goldberg_generic_push_relabel.h" +#include "../0000_common_utilities/unit_test_helper.h" -namespace MaximumFlowGoldbergGenericPushRelabel +namespace maximum_flow_goldberg_generic_push_relabel { UnitTestHelper unitTestHelper; - TEST(MaximumFlowGoldbergGenericPushRelabel, GraphWithNoParallelEdges) + TEST(maximumFlowGoldbergGenericPushRelabel, graphWithNoParallelEdges) { - // Arrange + // arrange Graph graph; int noOfVertices = 6; int expectedMaximumFlow = 23; - // Act - graph.CreateGraph(noOfVertices); + // act + graph.createGraph(noOfVertices); - graph.PushDirectedEdge(0, 1, 16); - graph.PushDirectedEdge(0, 2, 13); - graph.PushDirectedEdge(1, 3, 12); - graph.PushDirectedEdge(2, 1, 4); - graph.PushDirectedEdge(2, 4, 14); - graph.PushDirectedEdge(3, 2, 9); - graph.PushDirectedEdge(3, 5, 20); - graph.PushDirectedEdge(4, 3, 7); - graph.PushDirectedEdge(4, 5, 4); + graph.pushDirectedEdge(0, 1, 16); + graph.pushDirectedEdge(0, 2, 13); + graph.pushDirectedEdge(1, 3, 12); + graph.pushDirectedEdge(2, 1, 4); + graph.pushDirectedEdge(2, 4, 14); + graph.pushDirectedEdge(3, 2, 9); + graph.pushDirectedEdge(3, 5, 20); + graph.pushDirectedEdge(4, 3, 7); + graph.pushDirectedEdge(4, 5, 4); - int actualMaximumFlow = graph.FindMaximumFlowGoldbergGenericPushRelabel(); + int actualMaximumFlow = graph.findMaximumFlowGoldbergGenericPushRelabel(); - // Assert + // assert ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); } } \ No newline at end of file diff --git a/tests/0003_graph/0019_maximum_flow_relabel_to_front_test.cc b/tests/0003_graph/0019_maximum_flow_relabel_to_front_test.cc index a73b89d..2130547 100644 --- a/tests/0003_graph/0019_maximum_flow_relabel_to_front_test.cc +++ b/tests/0003_graph/0019_maximum_flow_relabel_to_front_test.cc @@ -1,36 +1,36 @@ #include -#include "0019_MaximumFlowRelabelToFront.h" -#include "../0000_common_utilities/UnitTestHelper.h" +#include "0019_maximum_flow_relabel_to_front.h" +#include "../0000_common_utilities/unit_test_helper.h" using namespace std; -namespace MaximumFlowRelabelToFront +namespace maximum_flow_relabel_to_front { UnitTestHelper unitTestHelper; - TEST(MaximumFlowRelabelToFront, SimpleGraph) + TEST(maximumFlowRelabelToFront, simpleGraph) { - // Arrange + // arrange Graph graph; int noOfVertices = 6; int expectedMaximumFlow = 23; - // Act - graph.CreateGraph(noOfVertices); + // act + graph.createGraph(noOfVertices); - graph.PushDirectedEdge(0, 1, 16); - graph.PushDirectedEdge(0, 2, 13); - graph.PushDirectedEdge(1, 3, 12); - graph.PushDirectedEdge(2, 1, 4); - graph.PushDirectedEdge(2, 4, 14); - graph.PushDirectedEdge(3, 2, 9); - graph.PushDirectedEdge(3, 5, 20); - graph.PushDirectedEdge(4, 3, 7); - graph.PushDirectedEdge(4, 5, 4); + graph.pushDirectedEdge(0, 1, 16); + graph.pushDirectedEdge(0, 2, 13); + graph.pushDirectedEdge(1, 3, 12); + graph.pushDirectedEdge(2, 1, 4); + graph.pushDirectedEdge(2, 4, 14); + graph.pushDirectedEdge(3, 2, 9); + graph.pushDirectedEdge(3, 5, 20); + graph.pushDirectedEdge(4, 3, 7); + graph.pushDirectedEdge(4, 5, 4); - int actualMaximumFlow = graph.FindMaximumFlowRelabelToFront(); + int actualMaximumFlow = graph.findMaximumFlowRelabelToFront(); - // Assert + // assert ASSERT_EQ(expectedMaximumFlow, actualMaximumFlow); } } \ No newline at end of file diff --git a/tests/0003_graph/CMakeLists.txt b/tests/0003_graph/CMakeLists.txt index 275d4a8..a40f049 100644 --- a/tests/0003_graph/CMakeLists.txt +++ b/tests/0003_graph/CMakeLists.txt @@ -14,25 +14,26 @@ enable_testing() add_executable( 0003GraphTests - 0001_BreadthFirstSearchTest.cc - 0002_DepthFirstSearchTest.cc - 0003_TopologicalSortTest.cc - 0004_StronglyConnectedComponentsTest.cc - 0005_HamiltonianPathAndCycleTest.cc - 0006_EulerianPathAndCircuitTest.cc - 0007_MinimumSpanningTreeKruskalAlgorithmTest.cc - 0008_MinimumSpanningTreePrimAlgorithmTest.cc - 0009_SingleSourceShortestPathBellmanFordTest.cc - 0010_DirectedAcyclicGraphShortestPathTest.cc - 0011_SingleSourceShortestPathDijkstraTest.cc - 0012_DifferenceConstraintsShortestPathsTest.cc - 0013_AllPairsShortestPathsFloydWarshallTest.cc - 0014_AllPairsShortestPathsJohnsonTest.cc - 0015_MaximumFlowFordFulkersonTest.cc - 0016_MaximumFlowEdmondsKarpTest.cc - 0017_MaximumBipartiteMatchingTest.cc - 0018_MaximumFlowGoldbergGenericPushRelabelTest.cc - 0019_MaximumFlowRelabelToFrontTest.cc + + 0001_breadth_first_search_test.cc + 0002_depth_first_search_test.cc + 0003_topological_sort_test.cc + 0004_strongly_connected_components_test.cc + 0005_hamiltonian_path_and_cycle_test.cc + 0006_eulerian_path_and_circuit_test.cc + 0007_minimum_spanning_tree_kruskal_algorithm_test.cc + 0008_minimum_spanning_tree_prim_algorithm_test.cc + 0009_single_source_shortest_path_bellman_ford_test.cc + 0010_directed_acyclic_graph_shortest_path_test.cc + 0011_single_source_shortest_path_dijkstra_test.cc + 0012_difference_constraints_shortest_paths_test.cc + 0013_all_pairs_shortest_paths_floyd_warshall_test.cc + 0014_all_pairs_shortest_paths_johnson_test.cc + 0015_maximum_flow_ford_fulkerson_test.cc + 0016_maximum_flow_edmonds_karp_test.cc + 0017_maximum_bipartite_matching_test.cc + 0018_maximum_flow_goldberg_generic_push_relabel_test.cc + 0019_maximum_flow_relabel_to_front_test.cc ) target_link_libraries( diff --git a/tests/0004_dynamic_programming/0001_fibonacci_number_test.cc b/tests/0004_dynamic_programming/0001_fibonacci_number_test.cc index 1fdd9a4..9947442 100644 --- a/tests/0004_dynamic_programming/0001_fibonacci_number_test.cc +++ b/tests/0004_dynamic_programming/0001_fibonacci_number_test.cc @@ -1,34 +1,34 @@ #include -#include "0001_FibonacciNumber.h" +#include "0001_fibonacci_number.h" using namespace std; -namespace FibonacciNumber +namespace fibonacci_number { - TEST(FibonacciNumber, RecursiveTest) + TEST(fibonacciNumber, recursiveTest) { - // Arrange + // arrange DynamicProgramming dp; int n = 5; int expectedFib = 5; - // Act - int actualFib = dp.RecursiveNthFibonacci(n); + // act + int actualFib = dp.recursiveNthFibonacci(n); - // Assert + // assert ASSERT_EQ(expectedFib, actualFib); } - TEST(FibonacciNumber, DpTest) + TEST(fibonacciNumber, dpTest) { - // Arrange + // arrange DynamicProgramming dp; int n = 5; int expectedFib = 5; - // Act - int actualFib = dp.DpNthFibonacci(n); + // act + int actualFib = dp.dpNthFibonacci(n); - // Assert + // assert ASSERT_EQ(expectedFib, actualFib); } } \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0002_tribonacci_number_test.cc b/tests/0004_dynamic_programming/0002_tribonacci_number_test.cc index d25c394..886cf82 100644 --- a/tests/0004_dynamic_programming/0002_tribonacci_number_test.cc +++ b/tests/0004_dynamic_programming/0002_tribonacci_number_test.cc @@ -1,34 +1,34 @@ #include -#include "0002_TribonacciNumber.h" +#include "0002_tribonacci_number.h" using namespace std; -namespace TribonacciNumber +namespace tribonacci_number { - TEST(TribonacciNumber, RecursiveTest) + TEST(tribonacciNumber, recursiveTest) { - // Arrange + // arrange DynamicProgramming dp; int n = 5; int expectedFib = 2; - // Act - int actualFib = dp.RecursiveNthTribonacci(n); + // act + int actualFib = dp.recursiveNthTribonacci(n); - // Assert + // assert ASSERT_EQ(expectedFib, actualFib); } - TEST(TribonacciNumber, DpTest) + TEST(tribonacciNumber, dpTest) { - // Arrange + // arrange DynamicProgramming dp; int n = 10; int expectedFib = 44; - // Act - int actualFib = dp.DpNthTribonacci(n); + // act + int actualFib = dp.dpNthTribonacci(n); - // Assert + // assert ASSERT_EQ(expectedFib, actualFib); } } \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0003_climbing_stairs_test.cc b/tests/0004_dynamic_programming/0003_climbing_stairs_test.cc index 0504cbc..0824572 100644 --- a/tests/0004_dynamic_programming/0003_climbing_stairs_test.cc +++ b/tests/0004_dynamic_programming/0003_climbing_stairs_test.cc @@ -1,33 +1,33 @@ #include -#include "0003_ClimbingStairs.h" +#include "0003_climbing_stairs.h" -namespace ClimbingStairs +namespace climbing_stairs { - TEST(ClimbingStairs, RecursiveTest) + TEST(climbingStairs, recursiveTest) { - // Arrange + // arrange DynamicProgramming dp; int n = 4; int expectedCount = 5; - // Act - int actualCount = dp.RecursiveCountWays(n); + // act + int actualCount = dp.recursiveCountWays(n); - // Assert + // assert ASSERT_EQ(expectedCount, actualCount); } - TEST(ClimbingStairs, DpTest) + TEST(climbingStairs, dpTest) { - // Arrange + // arrange DynamicProgramming dp; int n = 4; int expectedCount = 5; - // Act - int actualCount = dp.DpCountWays(n); + // act + int actualCount = dp.dpCountWays(n); - // Assert + // assert ASSERT_EQ(expectedCount, actualCount); } } \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0004_minimum_cost_climbing_stairs_test.cc b/tests/0004_dynamic_programming/0004_minimum_cost_climbing_stairs_test.cc index b488105..383614b 100644 --- a/tests/0004_dynamic_programming/0004_minimum_cost_climbing_stairs_test.cc +++ b/tests/0004_dynamic_programming/0004_minimum_cost_climbing_stairs_test.cc @@ -1,33 +1,33 @@ #include -#include "0004_MinimumCostClimbingStairs.h" +#include "0004_minimum_cost_climbing_stairs.h" -namespace MinimumCostClimbingStairs +namespace minimum_cost_climbing_stairs { - TEST(MinimumCostClimbingStairs, RecursionTest) + TEST(minimumCostClimbingStairs, recursionTest) { - // Arrange + // arrange DynamicProgramming dp; vector cost = { 16, 19, 10, 12, 18 }; int expectedCost = 31; - // Act - int actualCost = dp.RecursiveMinimumCostClimbingStairs(cost); + // act + int actualCost = dp.recursiveMinimumCostClimbingStairs(cost); - // Assert + // assert ASSERT_EQ(expectedCost, actualCost); } - TEST(MinimumCostClimbingStairs, DpTest) + TEST(minimumCostClimbingStairs, dpTest) { - // Arrange + // arrange DynamicProgramming dp; vector cost = { 16, 19, 10, 12, 18 }; int expectedCost = 31; - // Act - int actualCost = dp.DpMinimumCostClimbingStairs(cost); + // act + int actualCost = dp.dpMinimumCostClimbingStairs(cost); - // Assert + // assert ASSERT_EQ(expectedCost, actualCost); } } \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0005_house_robber1_test.cc b/tests/0004_dynamic_programming/0005_house_robber1_test.cc index d3f6312..9c2c45e 100644 --- a/tests/0004_dynamic_programming/0005_house_robber1_test.cc +++ b/tests/0004_dynamic_programming/0005_house_robber1_test.cc @@ -1,33 +1,33 @@ #include -#include "0005_HouseRobber1.h" +#include "0005_house_robber1.h" -namespace HouseRobber1 +namespace house_robber1 { - TEST(HouseRobber1, RecursionTest) + TEST(houseRobber1, recursionTest) { - // Arrange + // arrange DynamicProgramming dp; vector houseValues = { 6, 7, 1, 3, 8, 2, 4 }; int expectedMaximumLoot = 19; - // Act - int actualMaximumLoot = dp.RecursiveMaximumLoot(houseValues); + // act + int actualMaximumLoot = dp.recursiveMaximumLoot(houseValues); - // Assert + // assert ASSERT_EQ(expectedMaximumLoot, actualMaximumLoot); } - TEST(HouseRobber1, DpTest) + TEST(houseRobber1, dpTest) { - // Arrange + // arrange DynamicProgramming dp; vector houseValues = { 6, 7, 1, 3, 8, 2, 4 }; int expectedMaximumLoot = 19; - // Act - int actualMaximumLoot = dp.DpMaximumLoot(houseValues); + // act + int actualMaximumLoot = dp.dpMaximumLoot(houseValues); - // Assert + // assert ASSERT_EQ(expectedMaximumLoot, actualMaximumLoot); } } \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0006_house_robber2_test.cc b/tests/0004_dynamic_programming/0006_house_robber2_test.cc index e37c346..0a74cd7 100644 --- a/tests/0004_dynamic_programming/0006_house_robber2_test.cc +++ b/tests/0004_dynamic_programming/0006_house_robber2_test.cc @@ -1,47 +1,47 @@ #include -#include "0006_HouseRobber2.h" +#include "0006_house_robber2.h" -namespace HouseRobber2 +namespace house_robber2 { - TEST(HouseRobber2, RecursionTest01) + TEST(houseRobber2, recursionTest01) { - // Arrange + // arrange DynamicProgramming dp; vector houseValues = { 2, 2, 3, 1, 2 }; int expectedMaximumLoot = 5; - // Act - int actualMaximumLoot = dp.RecursiveMaximumLoot(houseValues); + // act + int actualMaximumLoot = dp.recursiveMaximumLoot(houseValues); - // Assert + // assert ASSERT_EQ(expectedMaximumLoot, actualMaximumLoot); } - TEST(HouseRobber2, DpTest01) + TEST(houseRobber2, dpTest01) { - // Arrange + // arrange DynamicProgramming dp; vector houseValues = { 2, 2, 3, 1, 2 }; int expectedMaximumLoot = 5; - // Act - int actualMaximumLoot = dp.DpMaximumLoot(houseValues); + // act + int actualMaximumLoot = dp.dpMaximumLoot(houseValues); - // Assert + // assert ASSERT_EQ(expectedMaximumLoot, actualMaximumLoot); } - TEST(HouseRobber2, DpTest02) + TEST(houseRobber2, dpTest02) { - // Arrange + // arrange DynamicProgramming dp; vector houseValues = { 9, 1, 8, 2 }; int expectedMaximumLoot = 17; - // Act - int actualMaximumLoot = dp.DpMaximumLoot(houseValues); + // act + int actualMaximumLoot = dp.dpMaximumLoot(houseValues); - // Assert + // assert ASSERT_EQ(expectedMaximumLoot, actualMaximumLoot); } diff --git a/tests/0004_dynamic_programming/0007_decode_ways_test.cc b/tests/0004_dynamic_programming/0007_decode_ways_test.cc index cf81a98..fa6e767 100644 --- a/tests/0004_dynamic_programming/0007_decode_ways_test.cc +++ b/tests/0004_dynamic_programming/0007_decode_ways_test.cc @@ -1,47 +1,47 @@ #include -#include "0007_DecodeWays.h" +#include "0007_decode_ways.h" -namespace DecodeWays +namespace decode_ways { - TEST(DecodeWays, RecursionTest01) + TEST(decodeWays, recursionTest01) { - // Arrange + // arrange DynamicProgramming dp; string digits = "121"; int expectedWaysCount = 3; - // Act - int actualWaysCount = dp.RecursiveCountWays(digits); + // act + int actualWaysCount = dp.recursiveCountWays(digits); - // Assert + // assert ASSERT_EQ(expectedWaysCount, actualWaysCount); } - TEST(DecodeWays, DpTest01) + TEST(decodeWays, dpTest01) { - // Arrange + // arrange DynamicProgramming dp; string digits = "121"; int expectedWaysCount = 3; - // Act - int actualWaysCount = dp.DpCountways(digits); + // act + int actualWaysCount = dp.dpCountways(digits); - // Assert + // assert ASSERT_EQ(expectedWaysCount, actualWaysCount); } - TEST(DecodeWays, DpTestInvalidInput) + TEST(decodeWays, dpTestInvalidInput) { - // Arrange + // arrange DynamicProgramming dp; string digits = "230"; int expectedWaysCount = 0; - // Act - int actualWaysCount = dp.DpCountways(digits); + // act + int actualWaysCount = dp.dpCountways(digits); - // Assert + // assert ASSERT_EQ(expectedWaysCount, actualWaysCount); } } \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0008_tiling_problem_test.cc b/tests/0004_dynamic_programming/0008_tiling_problem_test.cc index bbcbb79..1f2ccf6 100644 --- a/tests/0004_dynamic_programming/0008_tiling_problem_test.cc +++ b/tests/0004_dynamic_programming/0008_tiling_problem_test.cc @@ -1,33 +1,33 @@ #include -#include "0008_TilingProblem.h" +#include "0008_tiling_problem.h" -namespace TilingProblem +namespace tiling_problem { - TEST(TilingProblem, RecursionTest01) + TEST(tilingProblem, recursionTest01) { - // Arrange + // arrange DynamicProgramming dp; int nummberOfRows = 4; int expectedNumberOfWays = 5; - // Act - int actualNumberOfWays = dp.RecursiveNumberOfWays(nummberOfRows); + // act + int actualNumberOfWays = dp.recursiveNumberOfWays(nummberOfRows); - // Assert + // assert ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); } - TEST(TilingProblem, DpTest01) + TEST(tilingProblem, dpTest01) { - // Arrange + // arrange DynamicProgramming dp; int nummberOfRows = 4; int expectedNumberOfWays = 5; - // Act - int actualNumberOfWays = dp.DpNumberOfWays(nummberOfRows); + // act + int actualNumberOfWays = dp.dpNumberOfWays(nummberOfRows); - // Assert + // assert ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); } } \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0009_friends_pairing_problem_test.cc b/tests/0004_dynamic_programming/0009_friends_pairing_problem_test.cc index 11376ac..bcda5b2 100644 --- a/tests/0004_dynamic_programming/0009_friends_pairing_problem_test.cc +++ b/tests/0004_dynamic_programming/0009_friends_pairing_problem_test.cc @@ -1,91 +1,91 @@ #include -#include "0009_FriendsPairingProblem.h" +#include "0009_friends_pairing_problem.h" -namespace FriendsPairingProblem +namespace friends_pairing_problem { - TEST(FriendsPairingProblemDynamicProgrammingTest, RecursiveCountFriendsPairingsTest1) + TEST(friendsPairingProblemDynamicProgrammingTest, recursiveCountFriendsPairingsTest1) { - // Arrange + // arrange DynamicProgramming dp; int numberOfFriends = 3; int expectedPairings = 4; - // Act - int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); + // act + int actualPairings = dp.recursiveCountFriendsPairings(numberOfFriends); - // Assert + // assert ASSERT_EQ(expectedPairings, actualPairings); - EXPECT_EQ(dp.RecursiveCountFriendsPairings(4), 10); - EXPECT_EQ(dp.RecursiveCountFriendsPairings(5), 26); + EXPECT_EQ(dp.recursiveCountFriendsPairings(4), 10); + EXPECT_EQ(dp.recursiveCountFriendsPairings(5), 26); } - TEST(FriendsPairingProblemDynamicProgrammingTest, RecursiveCountFriendsPairingsTest2) + TEST(friendsPairingProblemDynamicProgrammingTest, recursiveCountFriendsPairingsTest2) { - // Arrange + // arrange DynamicProgramming dp; int numberOfFriends = 4; int expectedPairings = 10; - // Act - int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); + // act + int actualPairings = dp.recursiveCountFriendsPairings(numberOfFriends); - // Assert + // assert ASSERT_EQ(expectedPairings, actualPairings); } - TEST(FriendsPairingProblemDynamicProgrammingTest, RecursiveCountFriendsPairingsTest3) + TEST(friendsPairingProblemDynamicProgrammingTest, recursiveCountFriendsPairingsTest3) { - // Arrange + // arrange DynamicProgramming dp; int numberOfFriends = 5; int expectedPairings = 26; - // Act - int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); + // act + int actualPairings = dp.recursiveCountFriendsPairings(numberOfFriends); - // Assert + // assert ASSERT_EQ(expectedPairings, actualPairings); } - TEST(FriendsPairingProblemDynamicProgrammingTest, DpCountFriendsPairingsTest1) + TEST(friendsPairingProblemDynamicProgrammingTest, dpCountFriendsPairingsTest1) { - // Arrange + // arrange DynamicProgramming dp; int numberOfFriends = 3; int expectedPairings = 4; - // Act - int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); + // act + int actualPairings = dp.recursiveCountFriendsPairings(numberOfFriends); - // Assert + // assert ASSERT_EQ(expectedPairings, actualPairings); } - TEST(FriendsPairingProblemDynamicProgrammingTest, DpCountFriendsPairingsTest2) + TEST(friendsPairingProblemDynamicProgrammingTest, dpCountFriendsPairingsTest2) { - // Arrange + // arrange DynamicProgramming dp; int numberOfFriends = 4; int expectedPairings = 10; - // Act - int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); + // act + int actualPairings = dp.recursiveCountFriendsPairings(numberOfFriends); - // Assert + // assert ASSERT_EQ(expectedPairings, actualPairings); } - TEST(FriendsPairingProblemDynamicProgrammingTest, DpCountFriendsPairingsTest3) + TEST(friendsPairingProblemDynamicProgrammingTest, dpCountFriendsPairingsTest3) { - // Arrange + // arrange DynamicProgramming dp; int numberOfFriends = 5; int expectedPairings = 26; - // Act - int actualPairings = dp.RecursiveCountFriendsPairings(numberOfFriends); + // act + int actualPairings = dp.recursiveCountFriendsPairings(numberOfFriends); - // Assert + // assert ASSERT_EQ(expectedPairings, actualPairings); } } \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0010_ways_to_cover_distance_test.cc b/tests/0004_dynamic_programming/0010_ways_to_cover_distance_test.cc index 7e7f0c9..0895315 100644 --- a/tests/0004_dynamic_programming/0010_ways_to_cover_distance_test.cc +++ b/tests/0004_dynamic_programming/0010_ways_to_cover_distance_test.cc @@ -1,117 +1,117 @@ #include -#include "0010_WaysToCoverDistance.h" +#include "0010_ways_to_cover_distance.h" -namespace WaysToCoverDistance +namespace ways_to_cover_distance { - TEST(WaysToCoverDistanceTest, RecursiveWaysToCoverDistance1) + TEST(waysToCoverDistanceTest, recursiveWaysToCoverDistance1) { - // Arrange + // arrange DynamicProgramming dp; int distance = 3; int expectedNumberOfWaysToCoverDistance = 4; - // Act - int actualNumberOfWaysToCoverDistance = dp.RecursiveWaysToCoverDistance(distance); + // act + int actualNumberOfWaysToCoverDistance = dp.recursiveWaysToCoverDistance(distance); - // Assert + // assert ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); } - TEST(WaysToCoverDistanceTest, RecursiveWaysToCoverDistance2) + TEST(waysToCoverDistanceTest, recursiveWaysToCoverDistance2) { - // Arrange + // arrange DynamicProgramming dp; int distance = 4; int expectedNumberOfWaysToCoverDistance = 7; - // Act - int actualNumberOfWaysToCoverDistance = dp.RecursiveWaysToCoverDistance(distance); + // act + int actualNumberOfWaysToCoverDistance = dp.recursiveWaysToCoverDistance(distance); - // Assert + // assert ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); } - TEST(WaysToCoverDistanceTest, RecursiveWaysToCoverDistanc3) + TEST(waysToCoverDistanceTest, recursiveWaysToCoverDistanc3) { - // Arrange + // arrange DynamicProgramming dp; int distance = 5; int expectedNumberOfWaysToCoverDistance = 13; - // Act - int actualNumberOfWaysToCoverDistance = dp.RecursiveWaysToCoverDistance(distance); + // act + int actualNumberOfWaysToCoverDistance = dp.recursiveWaysToCoverDistance(distance); - // Assert + // assert ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); } - TEST(WaysToCoverDistanceTest, RecursiveWaysToCoverDistanc4) + TEST(waysToCoverDistanceTest, recursiveWaysToCoverDistanc4) { - // Arrange + // arrange DynamicProgramming dp; int distance = 6; int expectedNumberOfWaysToCoverDistance = 24; - // Act - int actualNumberOfWaysToCoverDistance = dp.RecursiveWaysToCoverDistance(distance); + // act + int actualNumberOfWaysToCoverDistance = dp.recursiveWaysToCoverDistance(distance); - // Assert + // assert ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); } - TEST(WaysToCoverDistanceTest, DpWaysToCoverDistance1) + TEST(waysToCoverDistanceTest, dpWaysToCoverDistance1) { - // Arrange + // arrange DynamicProgramming dp; int distance = 3; int expectedNumberOfWaysToCoverDistance = 4; - // Act - int actualNumberOfWaysToCoverDistance = dp.DpWaysToCoverDistance(distance); + // act + int actualNumberOfWaysToCoverDistance = dp.dpWaysToCoverDistance(distance); - // Assert + // assert ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); } - TEST(WaysToCoverDistanceTest, DpWaysToCoverDistance2) + TEST(waysToCoverDistanceTest, dpWaysToCoverDistance2) { - // Arrange + // arrange DynamicProgramming dp; int distance = 4; int expectedNumberOfWaysToCoverDistance = 7; - // Act - int actualNumberOfWaysToCoverDistance = dp.DpWaysToCoverDistance(distance); + // act + int actualNumberOfWaysToCoverDistance = dp.dpWaysToCoverDistance(distance); - // Assert + // assert ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); } - TEST(WaysToCoverDistanceTest, DpWaysToCoverDistance3) + TEST(waysToCoverDistanceTest, dpWaysToCoverDistance3) { - // Arrange + // arrange DynamicProgramming dp; int distance = 5; int expectedNumberOfWaysToCoverDistance = 13; - // Act - int actualNumberOfWaysToCoverDistance = dp.DpWaysToCoverDistance(distance); + // act + int actualNumberOfWaysToCoverDistance = dp.dpWaysToCoverDistance(distance); - // Assert + // assert ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); } - TEST(WaysToCoverDistanceTest, DpWaysToCoverDistance4) + TEST(waysToCoverDistanceTest, dpWaysToCoverDistance4) { - // Arrange + // arrange DynamicProgramming dp; int distance = 6; int expectedNumberOfWaysToCoverDistance = 24; - // Act - int actualNumberOfWaysToCoverDistance = dp.DpWaysToCoverDistance(distance); + // act + int actualNumberOfWaysToCoverDistance = dp.dpWaysToCoverDistance(distance); - // Assert + // assert ASSERT_EQ(expectedNumberOfWaysToCoverDistance, actualNumberOfWaysToCoverDistance); } } \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order_test.cc b/tests/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order_test.cc index 8a9830c..239c05c 100644 --- a/tests/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order_test.cc +++ b/tests/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order_test.cc @@ -1,33 +1,33 @@ #include -#include "0011_CountWaysToReachNthStairIncludeOrder.h" +#include "0011_count_ways_to_reach_nth_stair_include_order.h" -namespace CountWaysToReachNthStairIncludeOrder +namespace count_ways_to_reach_nth_stair_include_order { - TEST(CountWaysToReachNthStairIncludeOrderTest, RecursiveCountWaysToReachNthStairIncludeOrder1) + TEST(countWaysToReachNthStairIncludeOrderTest, recursiveCountWaysToReachNthStairIncludeOrder1) { - // Arrange + // arrange DynamicProgramming dp; int n = 4; int expectedNumberOfWays = 5; - // Act - int actualNumberOfWays = dp.RecursiveCountWaysToReachNthStairIncludeOrder(n); + // act + int actualNumberOfWays = dp.recursiveCountWaysToReachNthStairIncludeOrder(n); - // Assert + // assert ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); } - TEST(CountWaysToReachNthStairIncludeOrderTest, DpCountWaysToReachNthStairIncludeOrder1) + TEST(countWaysToReachNthStairIncludeOrderTest, dpCountWaysToReachNthStairIncludeOrder1) { - // Arrange + // arrange DynamicProgramming dp; int n = 4; int expectedNumberOfWays = 5; - // Act - int actualNumberOfWays = dp.DpCountWaysToReachNthStairIncludeOrder(n); + // act + int actualNumberOfWays = dp.dpCountWaysToReachNthStairIncludeOrder(n); - // Assert + // assert ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); } } \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order_test.cc b/tests/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order_test.cc index 2a67ce3..df1f344 100644 --- a/tests/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order_test.cc +++ b/tests/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order_test.cc @@ -1,33 +1,33 @@ #include -#include "0012_CountWaysToReachNthStairExcludeOrder.h" +#include "0012_count_ways_to_reach_nth_stair_exclude_order.h" -namespace CountWaysToReachNthStairExcludeOrder +namespace count_ways_to_reach_nth_stair_exclude_order { - TEST(CountWaysToReachNthStairExcludeOrderTest, RecursiveCountWaysToReachNthStairExcludeOrder1) + TEST(countWaysToReachNthStairExcludeOrderTest, recursiveCountWaysToReachNthStairExcludeOrder1) { - // Arrange + // arrange DynamicProgramming dp; int n = 4; int expectedNumberOfWays = 3; - // Act - int actualNumberOfWays = dp.RecursiveCountWaysToReachNthStairExcludeOrder(n); + // act + int actualNumberOfWays = dp.recursiveCountWaysToReachNthStairExcludeOrder(n); - // Assert + // assert ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); } - TEST(CountWaysToReachNthStairExcludeOrderTest, DpCountWaysToReachNthStairExcludeOrder1) + TEST(countWaysToReachNthStairExcludeOrderTest, dpCountWaysToReachNthStairExcludeOrder1) { - // Arrange + // arrange DynamicProgramming dp; int n = 4; int expectedNumberOfWays = 3; - // Act - int actualNumberOfWays = dp.DpCountWaysToReachNthStairExcludeOrder(n); + // act + int actualNumberOfWays = dp.dpCountWaysToReachNthStairExcludeOrder(n); - // Assert + // assert ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); } } \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0013_knapsack_problem_test.cc b/tests/0004_dynamic_programming/0013_knapsack_problem_test.cc index 94d3e84..bc2a7bc 100644 --- a/tests/0004_dynamic_programming/0013_knapsack_problem_test.cc +++ b/tests/0004_dynamic_programming/0013_knapsack_problem_test.cc @@ -1,53 +1,53 @@ #include -#include "0013_KnapsackProblem.h" +#include "0013_knapsack_problem.h" -namespace KnapsackProblem +namespace knapsack_problem { - TEST(KnapsackProblemTest, RecursiveKnapsackProblemTest01) + TEST(knapsackProblemTest, recursiveKnapsackProblemTest01) { - // Arrange + // arrange DynamicProgramming dp; int capacity = 4; vector weight = { 4,5,1 }; vector profit = { 1,2,3 }; int expectedMaximumProfit = 3; - // Act - int actualMaximumProfit = dp.RecursiveKnapsack(capacity, weight, profit); + // act + int actualMaximumProfit = dp.recursiveKnapsack(capacity, weight, profit); - // Assert + // assert ASSERT_EQ(expectedMaximumProfit, actualMaximumProfit); } - TEST(KnapsackProblemTest, DpKnapsackProblemTest01) + TEST(knapsackProblemTest, dpKnapsackProblemTest01) { - // Arrange + // arrange DynamicProgramming dp; int capacity = 4; vector weight = { 4,5,1 }; vector profit = { 1,2,3 }; int expectedMaximumProfit = 3; - // Act - int actualMaximumProfit = dp.DpKnapsack(capacity, weight, profit); + // act + int actualMaximumProfit = dp.dpKnapsack(capacity, weight, profit); - // Assert + // assert ASSERT_EQ(expectedMaximumProfit, actualMaximumProfit); } - TEST(KnapsackProblemTest, DpKnapsackProblemTest02) + TEST(knapsackProblemTest, dpKnapsackProblemTest02) { - // Arrange + // arrange DynamicProgramming dp; int capacity = 4; vector weight = { 4,5,1 }; vector profit = { 1,2,3 }; int expectedMaximumProfit = 3; - // Act - int actualMaximumProfit = dp.DpKnapsackSpaceOptimized(capacity, weight, profit); + // act + int actualMaximumProfit = dp.dpKnapsackSpaceOptimized(capacity, weight, profit); - // Assert + // assert ASSERT_EQ(expectedMaximumProfit, actualMaximumProfit); } } \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0014_subset_sum_problem_test.cc b/tests/0004_dynamic_programming/0014_subset_sum_problem_test.cc index aeee852..2206f21 100644 --- a/tests/0004_dynamic_programming/0014_subset_sum_problem_test.cc +++ b/tests/0004_dynamic_programming/0014_subset_sum_problem_test.cc @@ -1,35 +1,35 @@ #include -#include "0014_SubsetSumProblem.h" +#include "0014_subset_sum_problem.h" -namespace SubsetSumProblem +namespace subset_sum_problem { - TEST(SubsetSumProblemTest, RecursiveSubsetSumTest) + TEST(subsetSumProblemTest, recursiveSubsetSumTest) { - // Arrange + // arrange DynamicProgramming dp; vector nums = { 3, 34, 4, 12, 5, 2 }; int sum = 9; bool expectedResult = true; - // Act - bool actualResult = dp.RecursiveSubsetSum(nums, sum); + // act + bool actualResult = dp.recursiveSubsetSum(nums, sum); - // Assert + // assert ASSERT_EQ(expectedResult, actualResult); } - TEST(SubsetSumProblemTest, DpSubsetSumTest) + TEST(subsetSumProblemTest, dpSubsetSumTest) { - // Arrange + // arrange DynamicProgramming dp; vector nums = { 3, 34, 4, 12, 5, 2 }; int sum = 9; bool expectedResult = true; - // Act - bool actualResult = dp.DpIsSubsetSum(nums, sum); + // act + bool actualResult = dp.dpIsSubsetSum(nums, sum); - // Assert + // assert ASSERT_EQ(expectedResult, actualResult); } } \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0015_count_subsets_for_sum_test.cc b/tests/0004_dynamic_programming/0015_count_subsets_for_sum_test.cc index ba1fa7f..c0afa36 100644 --- a/tests/0004_dynamic_programming/0015_count_subsets_for_sum_test.cc +++ b/tests/0004_dynamic_programming/0015_count_subsets_for_sum_test.cc @@ -1,35 +1,35 @@ -#include -#include"0015_CountSubsetsForSum.h" +#include +#include "0015_count_subsets_for_sum.h" -namespace CountSubsetsForSum +namespace count_subsets_for_sum { - TEST(CountSubsetsForSum, RecursiveCountSubsetSum) + TEST(countSubsetsForSum, recursiveCountSubsetSum) { - // Arrange + // arrange DynamicProgramming dp; vector nums = { 1, 2, 3, 3 }; int sum = 6; int expectedCount = 3; - // Act - int actualCount = dp.RecursiveCountSubsets(nums, sum); + // act + int actualCount = dp.recursiveCountSubsets(nums, sum); - // Assert + // assert ASSERT_EQ(expectedCount, actualCount); } - TEST(CountSubsetsForSum, DpCountSubsetSum) + TEST(countSubsetsForSum, dpCountSubsetSum) { - // Arrange + // arrange DynamicProgramming dp; vector nums = { 1, 2, 3, 3 }; int sum = 6; int expectedCount = 3; - // Act - int actualCount = dp.DpCountSubsets(nums, sum); + // act + int actualCount = dp.dpCountSubsets(nums, sum); - // Assert + // assert ASSERT_EQ(expectedCount, actualCount); } } \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0016_partition_equal_subset_sum_test.cc b/tests/0004_dynamic_programming/0016_partition_equal_subset_sum_test.cc index 2bfa292..7d69351 100644 --- a/tests/0004_dynamic_programming/0016_partition_equal_subset_sum_test.cc +++ b/tests/0004_dynamic_programming/0016_partition_equal_subset_sum_test.cc @@ -1,33 +1,33 @@ #include -#include "0016_PartitionEqualSubsetSum.h" +#include "0016_partition_equal_subset_sum.h" -namespace PartitionEqualSubsetSum +namespace partition_equal_subset_sum { - TEST(PartitionEqualSubsetSum, RecursivePartitionEqualSubsetSum) + TEST(partitionEqualSubsetSum, recursivePartitionEqualSubsetSum) { - // Arrange + // arrange DynamicProgramming dp; vector nums = { 1, 5, 11, 5 }; bool expectedResult = true; - // Act - bool actualResult = dp.RecursivePartitionEqualSubsets(nums); + // act + bool actualResult = dp.recursivePartitionEqualSubsets(nums); - // Assert + // assert ASSERT_EQ(expectedResult, actualResult); } - TEST(PartitionEqualSubsetSum, DpPartitionEqualSubsetSum) + TEST(partitionEqualSubsetSum, dpPartitionEqualSubsetSum) { - // Arrange + // arrange DynamicProgramming dp; vector nums = { 1, 5, 11, 5 }; bool expectedResult = true; - // Act - bool actualResult = dp.DpPartitionEqualSubsets(nums); + // act + bool actualResult = dp.dpPartitionEqualSubsets(nums); - // Assert + // assert ASSERT_EQ(expectedResult, actualResult); } } \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0017_target_sum_test.cc b/tests/0004_dynamic_programming/0017_target_sum_test.cc index ab3fbf4..1d4b393 100644 --- a/tests/0004_dynamic_programming/0017_target_sum_test.cc +++ b/tests/0004_dynamic_programming/0017_target_sum_test.cc @@ -1,50 +1,50 @@ #include -#include "0017_TargetSum.h" +#include "0017_target_sum.h" -namespace TargetSum +namespace target_sum { - TEST(TargetSum, RecursiveSolutionTest_ValidInput_ReturnsCorrectResult) + TEST(targetSum, recursiveSolutionTest_ValidInput_ReturnsCorrectResult) { - // Arrange + // arrange DynamicProgramming dp; vector nums = { 1, 1, 1, 1, 1 }; int target = 3; int expectedResult = 5; - // Act - int actualResult = dp.RecursiveFindTotalWays(nums, target); + // act + int actualResult = dp.recursiveFindTotalWays(nums, target); - // Assert + // assert ASSERT_EQ(expectedResult, actualResult); } - TEST(TargetSum, DpSolutionTest_ValidInput_ReturnsCorrectResult) + TEST(targetSum, dpSolutionTest_ValidInput_ReturnsCorrectResult) { - // Arrange + // arrange DynamicProgramming dp; vector nums = { 1, 1, 1, 1, 1 }; int target = 3; int expectedResult = 5; - // Act - int actualResult = dp.DpFindTotalWays(nums, target); + // act + int actualResult = dp.dpFindTotalWays(nums, target); - // Assert + // assert ASSERT_EQ(expectedResult, actualResult); } - TEST(TargetSum, DpSolutionTest_TargetGreaterThanTotalSum_ReturnsZero) + TEST(targetSum, dpSolutionTest_TargetGreaterThanTotalSum_ReturnsZero) { - // Arrange + // arrange DynamicProgramming dp; vector nums = { 1, 1, 1, 1, 1 }; int target = -1000; int expectedResult = 0; - // Act - int actualResult = dp.DpFindTotalWays(nums, target); + // act + int actualResult = dp.dpFindTotalWays(nums, target); - // Assert + // assert ASSERT_EQ(expectedResult, actualResult); } } \ No newline at end of file diff --git a/tests/0004_dynamic_programming/CMakeLists.txt b/tests/0004_dynamic_programming/CMakeLists.txt index 4ef67b0..51714d5 100644 --- a/tests/0004_dynamic_programming/CMakeLists.txt +++ b/tests/0004_dynamic_programming/CMakeLists.txt @@ -14,23 +14,24 @@ enable_testing() add_executable( 0005DynamicProgrammingTests - 0001_FibonacciNumberTest.cc - 0002_TribonacciNumberTest.cc - 0003_ClimbingStairsTest.cc - 0004_MinimumCostClimbingStairsTest.cc - 0005_HouseRobber1Test.cc - 0006_HouseRobber2Test.cc - 0007_DecodeWaysTest.cc - 0008_TilingProblemTest.cc - 0009_FriendsPairingProblemTest.cc - 0010_WaysToCoverDistanceTest.cc - 0011_CountWaysToReachNthStairIncludeOrderTest.cc - 0012_CountWaysToReachNthStairExcludeOrderTest.cc - 0013_KnapsackProblemTest.cc - 0014_SubsetSumProblemTest.cc - 0015_CountSubsetsForSumTest.cc - 0016_PartitionEqualSubsetSumTest.cc - 0017_TargetSumTest.cc + + 0001_fibonacci_number_test.cc + 0002_tribonacci_number_test.cc + 0003_climbing_stairs_test.cc + 0004_minimum_cost_climbing_stairs_test.cc + 0005_house_robber1_test.cc + 0006_house_robber2_test.cc + 0007_decode_ways_test.cc + 0008_tiling_problem_test.cc + 0009_friends_pairing_problem_test.cc + 0010_ways_to_cover_distance_test.cc + 0011_count_ways_to_reach_nth_stair_include_order_test.cc + 0012_count_ways_to_reach_nth_stair_exclude_order_test.cc + 0013_knapsack_problem_test.cc + 0014_subset_sum_problem_test.cc + 0015_count_subsets_for_sum_test.cc + 0016_partition_equal_subset_sum_test.cc + 0017_target_sum_test.cc ) From 590b51c40cff3d1fd660a2f1ba4cf42384c9cefa Mon Sep 17 00:00:00 2001 From: Debashis Nandi Date: Sun, 14 Jun 2026 03:23:44 +0530 Subject: [PATCH 08/13] fix: .clang-tidy and validate yaml updated --- .clang-tidy | 4 ++-- .github/workflows/validate.yaml | 3 +-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index b797f75..8aee568 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -3,7 +3,7 @@ Checks: > WarningsAsErrors: '*' -HeaderFilterRegex: '(include/.*|source/.*)' +HeaderFilterRegex: '(include/.*|src/.*)' CheckOptions: # Private member variables @@ -14,7 +14,7 @@ CheckOptions: # Member function (non-static, non-const, non-virtual) - key: readability-identifier-naming.MethodCase - value: CamelCase + value: camelBack # Class names - key: readability-identifier-naming.ClassCase diff --git a/.github/workflows/validate.yaml b/.github/workflows/validate.yaml index 47a55f5..bda1e63 100644 --- a/.github/workflows/validate.yaml +++ b/.github/workflows/validate.yaml @@ -60,10 +60,9 @@ jobs: clang-tidy --version $files = Get-ChildItem -Recurse -Path src -Include *.cpp,*.cc,*.cxx -File $failed = $false - # These source/.* files would be checked using .clang-tidy maintained at projectroot foreach ($file in $files) { Write-Host "Checking $($file.FullName)" - clang-tidy -p build "$($file.FullName)" --warnings-as-errors=* + clang-tidy -p build --header-filter=".*" "$($file.FullName)" --warnings-as-errors=* if ($LASTEXITCODE -ne 0) { $failed = $true } } if ($failed) { Write-Error "Clang-tidy failed."; exit 1 } From a78fcbe2c23812c94708cf7e7011902b8c7f1840 Mon Sep 17 00:00:00 2001 From: Debashis Nandi Date: Sun, 14 Jun 2026 03:32:18 +0530 Subject: [PATCH 09/13] fix: .clang-tidy updated --- .clang-tidy | 8 +++++++- src/0003_graph/0001_breadth_first_search.cc | 2 +- src/0003_graph/0002_depth_first_search.cc | 2 +- .../headers/0001_breadth_first_search.h | 2 +- .../headers/0002_depth_first_search.h | 2 +- .../0001_breadth_first_search_test.cc | 4 ++-- .../0003_graph/0002_depth_first_search_test.cc | 18 +++++++++--------- 7 files changed, 22 insertions(+), 16 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index 8aee568..40279ab 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -12,7 +12,13 @@ CheckOptions: - key: readability-identifier-naming.PrivateMemberCase value: camelBack - # Member function (non-static, non-const, non-virtual) + # Private member methods + - key: readability-identifier-naming.PrivateMethodPrefix + value: _ + - key: readability-identifier-naming.PrivateMethodCase + value: camelBack + + # Public/Protected member methods - key: readability-identifier-naming.MethodCase value: camelBack diff --git a/src/0003_graph/0001_breadth_first_search.cc b/src/0003_graph/0001_breadth_first_search.cc index fc06255..edba700 100644 --- a/src/0003_graph/0001_breadth_first_search.cc +++ b/src/0003_graph/0001_breadth_first_search.cc @@ -69,7 +69,7 @@ namespace breadth_first_search this->_adjlist[nodeV].push_back(nodeU); } - void Graph::BFS(int value) + void Graph::bfs(int value) { this->breadthFirstSearch(this->_nodeMap[value]); } diff --git a/src/0003_graph/0002_depth_first_search.cc b/src/0003_graph/0002_depth_first_search.cc index 0a4f378..dd44ee9 100644 --- a/src/0003_graph/0002_depth_first_search.cc +++ b/src/0003_graph/0002_depth_first_search.cc @@ -56,7 +56,7 @@ namespace depth_first_search this->_adjlist[nodeU].push_back(nodeV); } - void Graph::DFS() + void Graph::dfs() { this->_time = 0; for (auto& iterator : this->_nodeMap) diff --git a/src/0003_graph/headers/0001_breadth_first_search.h b/src/0003_graph/headers/0001_breadth_first_search.h index 73a0f21..64893cf 100644 --- a/src/0003_graph/headers/0001_breadth_first_search.h +++ b/src/0003_graph/headers/0001_breadth_first_search.h @@ -29,7 +29,7 @@ namespace breadth_first_search void breadthFirstSearch(Node* node); public: void pushUndirectedEdge(int valueU, int valueV); - void BFS(int value); + void bfs(int value); vector> showBFSResult(); }; } \ No newline at end of file diff --git a/src/0003_graph/headers/0002_depth_first_search.h b/src/0003_graph/headers/0002_depth_first_search.h index 1137c0c..c128dea 100644 --- a/src/0003_graph/headers/0002_depth_first_search.h +++ b/src/0003_graph/headers/0002_depth_first_search.h @@ -31,7 +31,7 @@ namespace depth_first_search void depthFirstSearch(Node* Node); public: void pushDirectedEdge(int valueU, int valueV); - void DFS(); + void dfs(); vector>> showDFSResult(); }; } \ No newline at end of file diff --git a/tests/0003_graph/0001_breadth_first_search_test.cc b/tests/0003_graph/0001_breadth_first_search_test.cc index 4fa89aa..b6fd573 100644 --- a/tests/0003_graph/0001_breadth_first_search_test.cc +++ b/tests/0003_graph/0001_breadth_first_search_test.cc @@ -23,7 +23,7 @@ namespace breadth_first_search graph.pushUndirectedEdge(6, 8); graph.pushUndirectedEdge(7, 8); - graph.BFS(1); + graph.bfs(1); string actualResult = unitTestHelper.serializeVectorToString(graph.showBFSResult()); string expectedResult = "1(0) 2(1) 3(1) 4(2) 5(2) 6(2) 7(3) 8(3)"; @@ -36,7 +36,7 @@ namespace breadth_first_search graph.pushUndirectedEdge(1, 2); - graph.BFS(1); + graph.bfs(1); string actualResult = unitTestHelper.serializeVectorToString(graph.showBFSResult()); string expectedResult = "1(0) 2(1)"; diff --git a/tests/0003_graph/0002_depth_first_search_test.cc b/tests/0003_graph/0002_depth_first_search_test.cc index 6ac5b67..11b5c62 100644 --- a/tests/0003_graph/0002_depth_first_search_test.cc +++ b/tests/0003_graph/0002_depth_first_search_test.cc @@ -19,7 +19,7 @@ namespace depth_first_search graph.pushDirectedEdge(5, 4); graph.pushDirectedEdge(6, 6); - graph.DFS(); + graph.dfs(); string actualResult = unitTestHelper.serializeVectorToString(graph.showDFSResult()); string expectedResult = "1(1,8) 2(2,7) 3(9,12) 4(4,5) 5(3,6) 6(10,11)"; @@ -33,7 +33,7 @@ namespace depth_first_search graph.pushDirectedEdge(1, 1); - graph.DFS(); + graph.dfs(); string actualResult = unitTestHelper.serializeVectorToString(graph.showDFSResult()); string expectedResult = "1(1,2)"; @@ -47,7 +47,7 @@ namespace depth_first_search graph.pushDirectedEdge(1, 2); graph.pushDirectedEdge(3, 4); - graph.DFS(); + graph.dfs(); string actualResult = unitTestHelper.serializeVectorToString(graph.showDFSResult()); string expectedResult = "1(1,4) 2(2,3) 3(5,8) 4(6,7)"; @@ -62,7 +62,7 @@ namespace depth_first_search graph.pushDirectedEdge(2, 3); graph.pushDirectedEdge(3, 1); - graph.DFS(); + graph.dfs(); string actualResult = unitTestHelper.serializeVectorToString(graph.showDFSResult()); string expectedResult = "1(1,6) 2(2,5) 3(3,4)"; @@ -90,7 +90,7 @@ namespace depth_first_search graph.pushDirectedEdge(14, 15); graph.pushDirectedEdge(15, 16); - graph.DFS(); + graph.dfs(); string actualResult = unitTestHelper.serializeVectorToString(graph.showDFSResult()); string expectedResult = "1(1,32) 2(2,29) 3(30,31) 4(3,28) 5(4,27) 6(5,26) 7(6,25) 8(7,24) 9(8,23) 10(9,22) 11(10,21) 12(11,20) 13(12,19) 14(13,18) 15(14,17) 16(15,16)"; @@ -106,7 +106,7 @@ namespace depth_first_search graph.pushDirectedEdge(2, 2); graph.pushDirectedEdge(3, 3); - graph.DFS(); + graph.dfs(); string actualResult = unitTestHelper.serializeVectorToString(graph.showDFSResult()); string expectedResult = "1(1,2) 2(3,4) 3(5,6)"; @@ -123,7 +123,7 @@ namespace depth_first_search graph.pushDirectedEdge(3, 1); // cycle back to 'a' graph.pushDirectedEdge(2, 4); // back edge - graph.DFS(); + graph.dfs(); string actualResult = unitTestHelper.serializeVectorToString(graph.showDFSResult()); string expectedResult = "1(1,8) 2(2,7) 3(3,4) 4(5,6)"; @@ -148,7 +148,7 @@ namespace depth_first_search graph.pushDirectedEdge(4, 2); graph.pushDirectedEdge(4, 3); - graph.DFS(); + graph.dfs(); string actualResult = unitTestHelper.serializeVectorToString(graph.showDFSResult()); string expectedResult = "1(1,8) 2(2,7) 3(3,6) 4(4,5)"; @@ -167,7 +167,7 @@ namespace depth_first_search graph.pushDirectedEdge(2, 3); // parallel edge graph.pushDirectedEdge(3, 3); // self-loop - graph.DFS(); + graph.dfs(); string actualResult = unitTestHelper.serializeVectorToString(graph.showDFSResult()); string expectedResult = "1(1,6) 2(2,5) 3(3,4)"; From 75ab5c4ff93e8ae79d61a8154b79fd9ceb9b8743 Mon Sep 17 00:00:00 2001 From: Debashis Nandi Date: Mon, 15 Jun 2026 01:52:38 +0530 Subject: [PATCH 10/13] fix: private methods names fixed --- src/0001_basics/CMakeLists.txt | 4 +- src/0002_tree/0001_binary_search_tree.cc | 22 +++++------ .../headers/0001_binary_search_tree.h | 10 ++--- src/0003_graph/0001_breadth_first_search.cc | 10 ++--- src/0003_graph/0002_depth_first_search.cc | 12 +++--- src/0003_graph/0003_topological_sort.cc | 14 +++---- .../0004_strongly_connected_components.cc | 20 +++++----- .../0005_hamiltonian_path_and_cycle.cc | 18 ++++----- .../0006_eulerian_path_and_circuit.cc | 26 ++++++------- ...minimum_spanning_tree_kruskal_algorithm.cc | 24 ++++++------ ...08_minimum_spanning_tree_prim_algorithm.cc | 6 +-- ...ingle_source_shortest_path_bellman_ford.cc | 20 +++++----- ...10_directed_acyclic_graph_shortest_path.cc | 30 +++++++-------- ...11_single_source_shortest_path_dijkstra.cc | 24 ++++++------ ...2_difference_constraints_shortest_paths.cc | 20 +++++----- ...all_pairs_shortest_paths_floyd_warshall.cc | 10 ++--- .../0014_all_pairs_shortest_paths_johnson.cc | 38 +++++++++---------- .../0015_maximum_flow_ford_fulkerson.cc | 14 +++---- .../0016_maximum_flow_edmonds_karp.cc | 8 ++-- .../0017_maximum_bipartite_matching.cc | 16 ++++---- ...imum_flow_goldberg_generic_push_relabel.cc | 16 ++++---- .../0019_maximum_flow_relabel_to_front.cc | 16 ++++---- src/0003_graph/CMakeLists.txt | 4 +- .../headers/0001_breadth_first_search.h | 4 +- .../headers/0002_depth_first_search.h | 4 +- .../headers/0003_topological_sort.h | 4 +- .../0004_strongly_connected_components.h | 6 +-- .../headers/0005_hamiltonian_path_and_cycle.h | 6 +-- .../headers/0006_eulerian_path_and_circuit.h | 8 ++-- ..._minimum_spanning_tree_kruskal_algorithm.h | 10 ++--- ...008_minimum_spanning_tree_prim_algorithm.h | 2 +- ...single_source_shortest_path_bellman_ford.h | 8 ++-- ...010_directed_acyclic_graph_shortest_path.h | 12 +++--- ...011_single_source_shortest_path_dijkstra.h | 10 ++--- ...12_difference_constraints_shortest_paths.h | 8 ++-- ..._all_pairs_shortest_paths_floyd_warshall.h | 4 +- .../0014_all_pairs_shortest_paths_johnson.h | 16 ++++---- .../0015_maximum_flow_ford_fulkerson.h | 6 +-- .../headers/0016_maximum_flow_edmonds_karp.h | 4 +- .../headers/0017_maximum_bipartite_matching.h | 8 ++-- ...ximum_flow_goldberg_generic_push_relabel.h | 8 ++-- .../0019_maximum_flow_relabel_to_front.h | 8 ++-- .../0004_minimum_cost_climbing_stairs.cc | 6 +-- .../0005_house_robber1.cc | 8 ++-- .../0006_house_robber2.cc | 14 +++---- .../0007_decode_ways.cc | 8 ++-- .../0008_tiling_problem.cc | 8 ++-- .../0009_friends_pairing_problem.cc | 8 ++-- .../0010_ways_to_cover_distance.cc | 10 ++--- ...t_ways_to_reach_nth_stair_include_order.cc | 12 +++--- ...t_ways_to_reach_nth_stair_exclude_order.cc | 10 ++--- .../0013_knapsack_problem.cc | 8 ++-- .../0014_subset_sum_problem.cc | 8 ++-- .../0015_count_subsets_for_sum.cc | 8 ++-- .../0016_partition_equal_subset_sum.cc | 8 ++-- .../0017_target_sum.cc | 8 ++-- src/0004_dynamic_programming/CMakeLists.txt | 4 +- .../0004_minimum_cost_climbing_stairs.h | 2 +- .../headers/0005_house_robber1.h | 2 +- .../headers/0006_house_robber2.h | 4 +- .../headers/0007_decode_ways.h | 2 +- .../headers/0008_tiling_problem.h | 2 +- .../headers/0009_friends_pairing_problem.h | 2 +- .../headers/0010_ways_to_cover_distance.h | 2 +- ...nt_ways_to_reach_nth_stair_include_order.h | 6 +-- ...nt_ways_to_reach_nth_stair_exclude_order.h | 6 +-- .../headers/0013_knapsack_problem.h | 2 +- .../headers/0014_subset_sum_problem.h | 2 +- .../headers/0015_count_subsets_for_sum.h | 2 +- .../headers/0016_partition_equal_subset_sum.h | 2 +- .../headers/0017_target_sum.h | 3 +- tests/0001_basics/CMakeLists.txt | 10 ++--- tests/0003_graph/CMakeLists.txt | 10 ++--- ...s_to_reach_nth_stair_include_order_test.cc | 4 +- ...s_to_reach_nth_stair_exclude_order_test.cc | 4 +- tests/0004_dynamic_programming/CMakeLists.txt | 10 ++--- 76 files changed, 361 insertions(+), 362 deletions(-) diff --git a/src/0001_basics/CMakeLists.txt b/src/0001_basics/CMakeLists.txt index 477c6cd..b7ca5b3 100644 --- a/src/0001_basics/CMakeLists.txt +++ b/src/0001_basics/CMakeLists.txt @@ -4,8 +4,8 @@ set(0001BASICS_SOURCES ) # Create a library target -add_library(0001BASICS ${0001BASICS_SOURCES}) +add_library(0001_Basics ${0001BASICS_SOURCES}) -target_include_directories(0001BASICS PUBLIC +target_include_directories(0001_Basics PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/headers ) \ No newline at end of file diff --git a/src/0002_tree/0001_binary_search_tree.cc b/src/0002_tree/0001_binary_search_tree.cc index ca077d9..acd293e 100644 --- a/src/0002_tree/0001_binary_search_tree.cc +++ b/src/0002_tree/0001_binary_search_tree.cc @@ -19,7 +19,7 @@ namespace binary_search_tree } - void BinarySearchTree::_insertBSTreeNode(Node* node) + void BinarySearchTree::_insert(Node* node) { Node* nodeY = nullptr; Node* nodeX = this->_root; @@ -50,7 +50,7 @@ namespace binary_search_tree } } - Node* BinarySearchTree::_findBSTreeNode(int value) + Node* BinarySearchTree::_findNodeByValue(int value) { Node* node = this->_root; while (node != nullptr) @@ -71,7 +71,7 @@ namespace binary_search_tree return node; } - Node* BinarySearchTree::_findBSTreeMinNode(Node* node) + Node* BinarySearchTree::_findMinimumValueNode(Node* node) { while (node->left != nullptr) { @@ -80,7 +80,7 @@ namespace binary_search_tree return node; } - Node* BinarySearchTree::_findBSTreeMaxNode(Node* node) + Node* BinarySearchTree::_findMaximumValueNode(Node* node) { while (node->right != nullptr) { @@ -93,7 +93,7 @@ namespace binary_search_tree { if (node->right != nullptr) { - return this->_findBSTreeMinNode(node->right); + return this->_findMinimumValueNode(node->right); } Node* nodeY = node->parent; while (nodeY != nullptr && node == nodeY->right) @@ -108,7 +108,7 @@ namespace binary_search_tree { if (node->left != nullptr) { - return this->_findBSTreeMaxNode(node->left); + return this->_findMaximumValueNode(node->left); } Node* nodeY = node->parent; while (nodeY != nullptr && node == nodeY->left) @@ -140,7 +140,7 @@ namespace binary_search_tree } } - void BinarySearchTree::_deleteBSTreeNode(Node* node) + void BinarySearchTree::_delete(Node* node) { if (node->left == nullptr) { @@ -152,7 +152,7 @@ namespace binary_search_tree } else { - Node* nodeY = this->_findBSTreeMinNode(node->right); + Node* nodeY = this->_findMinimumValueNode(node->right); if (nodeY->parent != node) { this->_transplant(nodeY, nodeY->right); @@ -296,13 +296,13 @@ namespace binary_search_tree void BinarySearchTree::insertNode(int value) { Node* node = new Node(value, nullptr, nullptr, nullptr); - this->_insertBSTreeNode(node); + this->_insert(node); } void BinarySearchTree::deleteNode(int value) { - Node* node = this->_findBSTreeNode(value); - this->_deleteBSTreeNode(node); + Node* node = this->_findNodeByValue(value); + this->_delete(node); } vector BinarySearchTree::recursiveInorderTraversal() diff --git a/src/0002_tree/headers/0001_binary_search_tree.h b/src/0002_tree/headers/0001_binary_search_tree.h index 571481b..4572b20 100644 --- a/src/0002_tree/headers/0001_binary_search_tree.h +++ b/src/0002_tree/headers/0001_binary_search_tree.h @@ -21,14 +21,14 @@ namespace binary_search_tree { private: Node* _root; - void _insertBSTreeNode(Node* node); - Node* _findBSTreeNode(int value); - Node* _findBSTreeMinNode(Node* node); - Node* _findBSTreeMaxNode(Node* node); + void _insert(Node* node); + Node* _findNodeByValue(int value); + Node* _findMinimumValueNode(Node* node); + Node* _findMaximumValueNode(Node* node); Node* _findSuccessor(Node* node); Node* _findPredecessor(Node* node); void _transplant(Node* nodeU, Node* nodeV); - void _deleteBSTreeNode(Node* node); + void _delete(Node* node); void _recursiveInorder(Node* node, vector& result); void _recursivePreorder(Node* node, vector& result); void _recursivePostorder(Node* node, vector& result); diff --git a/src/0003_graph/0001_breadth_first_search.cc b/src/0003_graph/0001_breadth_first_search.cc index edba700..14c8b21 100644 --- a/src/0003_graph/0001_breadth_first_search.cc +++ b/src/0003_graph/0001_breadth_first_search.cc @@ -17,7 +17,7 @@ namespace breadth_first_search this->parent = nullptr; } - Node* Graph::makeOrFindNode(int value) + Node* Graph::_makeOrFindNode(int value) { Node* node = nullptr; if (this->_nodeMap.find(value) == this->_nodeMap.end()) @@ -32,7 +32,7 @@ namespace breadth_first_search return node; } - void Graph::breadthFirstSearch(Node* node) + void Graph::_breadthFirstSearch(Node* node) { node->color = WHITE; node->distance = 0; @@ -62,8 +62,8 @@ namespace breadth_first_search void Graph::pushUndirectedEdge(int valueU, int valueV) { - Node* nodeU = this->makeOrFindNode(valueU); - Node* nodeV = this->makeOrFindNode(valueV); + Node* nodeU = this->_makeOrFindNode(valueU); + Node* nodeV = this->_makeOrFindNode(valueV); this->_adjlist[nodeU].push_back(nodeV); this->_adjlist[nodeV].push_back(nodeU); @@ -71,7 +71,7 @@ namespace breadth_first_search void Graph::bfs(int value) { - this->breadthFirstSearch(this->_nodeMap[value]); + this->_breadthFirstSearch(this->_nodeMap[value]); } vector> Graph::showBFSResult() diff --git a/src/0003_graph/0002_depth_first_search.cc b/src/0003_graph/0002_depth_first_search.cc index dd44ee9..ce05132 100644 --- a/src/0003_graph/0002_depth_first_search.cc +++ b/src/0003_graph/0002_depth_first_search.cc @@ -15,7 +15,7 @@ namespace depth_first_search this->parent = nullptr; } - Node* Graph::makeOrFindNode(int value) + Node* Graph::_makeOrFindNode(int value) { Node* node = nullptr; if (this->_nodeMap.find(value) == this->_nodeMap.end()) @@ -30,7 +30,7 @@ namespace depth_first_search return node; } - void Graph::depthFirstSearch(Node* nodeU) + void Graph::_depthFirstSearch(Node* nodeU) { this->_time++; nodeU->discoveredTime = this->_time; @@ -40,7 +40,7 @@ namespace depth_first_search if (nodeV->color == WHITE) { nodeV->parent = nodeU; - this->depthFirstSearch(nodeV); + this->_depthFirstSearch(nodeV); } } nodeU->color = BLACK; @@ -50,8 +50,8 @@ namespace depth_first_search void Graph::pushDirectedEdge(int valueU, int valueV) { - Node* nodeU = this->makeOrFindNode(valueU); - Node* nodeV = this->makeOrFindNode(valueV); + Node* nodeU = this->_makeOrFindNode(valueU); + Node* nodeV = this->_makeOrFindNode(valueV); this->_adjlist[nodeU].push_back(nodeV); } @@ -63,7 +63,7 @@ namespace depth_first_search { if (iterator.second->color == WHITE) { - this->depthFirstSearch(iterator.second); + this->_depthFirstSearch(iterator.second); } } } diff --git a/src/0003_graph/0003_topological_sort.cc b/src/0003_graph/0003_topological_sort.cc index b76662c..e7f21be 100644 --- a/src/0003_graph/0003_topological_sort.cc +++ b/src/0003_graph/0003_topological_sort.cc @@ -18,7 +18,7 @@ namespace topological_sort this->parent = nullptr; } - Node* Graph::makeOrFindNode(int value) + Node* Graph::_makeOrFindNode(int value) { Node* node = nullptr; if (this->_nodeMap.find(value) == this->_nodeMap.end()) @@ -33,7 +33,7 @@ namespace topological_sort return node; } - void Graph::depthFirstSearch(Node* nodeU) + void Graph::_depthFirstSearch(Node* nodeU) { this->_time++; nodeU->discoveryTime = this->_time; @@ -43,7 +43,7 @@ namespace topological_sort if (nodeV->color == WHITE) { nodeV->parent = nodeU; - this->depthFirstSearch(nodeV); + this->_depthFirstSearch(nodeV); } else if (nodeV->color == GRAY) { @@ -59,8 +59,8 @@ namespace topological_sort void Graph::pushDirectedEdge(int valueU, int valueV) { - Node* nodeU = this->makeOrFindNode(valueU); - Node* nodeV = this->makeOrFindNode(valueV); + Node* nodeU = this->_makeOrFindNode(valueU); + Node* nodeV = this->_makeOrFindNode(valueV); this->_adjlist[nodeU].push_back(nodeV); nodeV->inDegree++; @@ -68,7 +68,7 @@ namespace topological_sort void Graph::pushSingleNode(int valueU) { - this->makeOrFindNode(valueU); + this->_makeOrFindNode(valueU); } void Graph::topologicalSort() @@ -78,7 +78,7 @@ namespace topological_sort { if (iterator.second->color == WHITE) { - this->depthFirstSearch(iterator.second); + this->_depthFirstSearch(iterator.second); if (this->_hasCycle == true) { break; diff --git a/src/0003_graph/0004_strongly_connected_components.cc b/src/0003_graph/0004_strongly_connected_components.cc index a12adc5..0576800 100644 --- a/src/0003_graph/0004_strongly_connected_components.cc +++ b/src/0003_graph/0004_strongly_connected_components.cc @@ -15,7 +15,7 @@ namespace strongly_connected_components this->parent = nullptr; } - Node* Graph::makeOrFindNode(int value) + Node* Graph::_makeOrFindNode(int value) { Node* node = nullptr; if (this->_nodeMap.find(value) == this->_nodeMap.end()) @@ -30,7 +30,7 @@ namespace strongly_connected_components return node; } - void Graph::depthFirstSearchOnGraphG(Node* nodeU) + void Graph::_depthFirstSearchOnGraphG(Node* nodeU) { this->_time++; nodeU->discoveryTime = this->_time; @@ -40,7 +40,7 @@ namespace strongly_connected_components if (nodeV->color == WHITE) { nodeV->parent = nodeU; - this->depthFirstSearchOnGraphG(nodeV); + this->_depthFirstSearchOnGraphG(nodeV); } } nodeU->color = BLACK; @@ -49,7 +49,7 @@ namespace strongly_connected_components this->_nodesFinishingTimeOrder.push_front(nodeU); } - void Graph::depthFirstSearchOnGraphT(Node* nodeU, vector& connectedComponents) + void Graph::_depthFirstSearchOnGraphT(Node* nodeU, vector& connectedComponents) { nodeU->color = GRAY; connectedComponents.push_back(nodeU->data); @@ -58,7 +58,7 @@ namespace strongly_connected_components if (nodeV->color == WHITE) { nodeV->parent = nodeU; - this->depthFirstSearchOnGraphT(nodeV, connectedComponents); + this->_depthFirstSearchOnGraphT(nodeV, connectedComponents); } } nodeU->color = BLACK; @@ -66,8 +66,8 @@ namespace strongly_connected_components void Graph::pushDirectedEdge(int valueU, int valueV) { - Node* nodeU = this->makeOrFindNode(valueU); - Node* nodeV = this->makeOrFindNode(valueV); + Node* nodeU = this->_makeOrFindNode(valueU); + Node* nodeV = this->_makeOrFindNode(valueV); // creating the actual graph. this->_adjlistG[nodeU].push_back(nodeV); @@ -78,7 +78,7 @@ namespace strongly_connected_components void Graph::pushSingleNode(int valueU) { - this->makeOrFindNode(valueU); + this->_makeOrFindNode(valueU); } void Graph::dFSOnGraphG() @@ -88,7 +88,7 @@ namespace strongly_connected_components { if (iterator.second->color == WHITE) { - this->depthFirstSearchOnGraphG(iterator.second); + this->_depthFirstSearchOnGraphG(iterator.second); } } } @@ -106,7 +106,7 @@ namespace strongly_connected_components if (iterator->color == WHITE) { vector connectedComponents; - this->depthFirstSearchOnGraphT(iterator, connectedComponents); + this->_depthFirstSearchOnGraphT(iterator, connectedComponents); this->_allConnectedComponents.push_back(connectedComponents); } } diff --git a/src/0003_graph/0005_hamiltonian_path_and_cycle.cc b/src/0003_graph/0005_hamiltonian_path_and_cycle.cc index 5c8d5e4..424c5c0 100644 --- a/src/0003_graph/0005_hamiltonian_path_and_cycle.cc +++ b/src/0003_graph/0005_hamiltonian_path_and_cycle.cc @@ -10,7 +10,7 @@ namespace hamiltonian_path_and_cycle } // Graph private member methods - Node* Graph::makeOrFindNode(int value) + Node* Graph::_makeOrFindNode(int value) { Node* node = nullptr; if (this->_nodeMap.find(value) == this->_nodeMap.end()) @@ -25,7 +25,7 @@ namespace hamiltonian_path_and_cycle return node; } - bool Graph::isSafe(Node* nodeU, Node* nodeV) + bool Graph::_isSafe(Node* nodeU, Node* nodeV) { if (this->_adjlist[nodeU].find(nodeV) == this->_adjlist[nodeU].end()) { @@ -38,7 +38,7 @@ namespace hamiltonian_path_and_cycle return true; } - bool Graph::hamiltonianCycleAndPathUtil(Node* nodeU) + bool Graph::_hamiltonianCycleAndPathUtil(Node* nodeU) { if (this->_visitedNodeCount == this->_nodeMap.size()) { @@ -53,12 +53,12 @@ namespace hamiltonian_path_and_cycle } for (auto& nodeV : this->_adjlist[nodeU]) { - if (this->isSafe(nodeU, nodeV)) + if (this->_isSafe(nodeU, nodeV)) { this->_hamiltonianPath.push_back(nodeV->data); nodeV->isVisited = true; this->_visitedNodeCount++; - if (this->hamiltonianCycleAndPathUtil(nodeV)) + if (this->_hamiltonianCycleAndPathUtil(nodeV)) { return true; } @@ -73,8 +73,8 @@ namespace hamiltonian_path_and_cycle // Graph public member methods void Graph::pushUndirectedEdge(int valueU, int valueV) { - Node* nodeU = this->makeOrFindNode(valueU); - Node* nodeV = this->makeOrFindNode(valueV); + Node* nodeU = this->_makeOrFindNode(valueU); + Node* nodeV = this->_makeOrFindNode(valueV); this->_adjlist[nodeU].insert(nodeV); this->_adjlist[nodeV].insert(nodeU); @@ -82,7 +82,7 @@ namespace hamiltonian_path_and_cycle void Graph::pushSingleNode(int valueU) { - this->makeOrFindNode(valueU); + this->_makeOrFindNode(valueU); } void Graph::findHamiltonianCycleAndPath() @@ -94,7 +94,7 @@ namespace hamiltonian_path_and_cycle this->_hamiltonianPath.push_back(this->_startingNode->data); this->_startingNode->isVisited = true; this->_visitedNodeCount = 1; - this->hamiltonianCycleAndPathUtil(this->_startingNode); + this->_hamiltonianCycleAndPathUtil(this->_startingNode); } bool Graph::isHamiltonianCyclePresent() diff --git a/src/0003_graph/0006_eulerian_path_and_circuit.cc b/src/0003_graph/0006_eulerian_path_and_circuit.cc index a69bb01..e4a874f 100644 --- a/src/0003_graph/0006_eulerian_path_and_circuit.cc +++ b/src/0003_graph/0006_eulerian_path_and_circuit.cc @@ -15,7 +15,7 @@ namespace eulerian_path_and_circuit } // Graph private member methods - Node* Graph::makeOrFindNode(int value) + Node* Graph::_makeOrFindNode(int value) { Node* node = nullptr; if (this->_nodeMap.find(value) == this->_nodeMap.end()) @@ -30,19 +30,19 @@ namespace eulerian_path_and_circuit return node; } - void Graph::depthFirstSearch(Node* nodeU) + void Graph::_depthFirstSearch(Node* nodeU) { nodeU->visited = true; for (auto& nodeV : this->_adjlist[nodeU]) { if (nodeV->visited == false) { - this->depthFirstSearch(nodeV); + this->_depthFirstSearch(nodeV); } } } - bool Graph::isConnected() + bool Graph::_isConnected() { // step-1 : make the visited property of all nodes as false. it is already done in constructor. @@ -63,7 +63,7 @@ namespace eulerian_path_and_circuit return true; } - this->depthFirstSearch(node); + this->_depthFirstSearch(node); // step-4 : checking if all the non-zero degree vertices have been visited or not. for (auto& iterator : this->_nodeMap) @@ -76,7 +76,7 @@ namespace eulerian_path_and_circuit return true; } - void Graph::eulerianPathHierholzerAlgorithm(Node* startingNode) + void Graph::_eulerianPathHierholzerAlgorithm(Node* startingNode) { stack currentPath; currentPath.push(startingNode); @@ -101,8 +101,8 @@ namespace eulerian_path_and_circuit // Graph public member methods void Graph::pushUndirectedEdge(int valueU, int valueV) { - Node* nodeU = this->makeOrFindNode(valueU); - Node* nodeV = this->makeOrFindNode(valueV); + Node* nodeU = this->_makeOrFindNode(valueU); + Node* nodeV = this->_makeOrFindNode(valueV); this->_adjlist[nodeU].push_back(nodeV); nodeU->degree++; @@ -112,8 +112,8 @@ namespace eulerian_path_and_circuit void Graph::pushDirectedEdge(int valueU, int valueV) { - Node* nodeU = this->makeOrFindNode(valueU); - Node* nodeV = this->makeOrFindNode(valueV); + Node* nodeU = this->_makeOrFindNode(valueU); + Node* nodeV = this->_makeOrFindNode(valueV); this->_adjlist[nodeU].push_back(nodeV); nodeU->outDegree++; @@ -122,13 +122,13 @@ namespace eulerian_path_and_circuit void Graph::pushSingleNode(int valueU) { - this->makeOrFindNode(valueU); + this->_makeOrFindNode(valueU); } void Graph::findEulerianPathAndCircuit() { // if the graph is not connected then graph G is not-eulerian. - if (this->isConnected() == false) + if (this->_isConnected() == false) { this->_isEulerianPathPresent = false; this->_isEulerianCircuitPresent = false; @@ -205,7 +205,7 @@ namespace eulerian_path_and_circuit { node = this->_nodeMap[0]; } - this->eulerianPathHierholzerAlgorithm(node); + this->_eulerianPathHierholzerAlgorithm(node); reverse(this->_eulerianPath.begin(), this->_eulerianPath.end()); return this->_eulerianPath; } diff --git a/src/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm.cc b/src/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm.cc index ca17a63..dd5a50e 100644 --- a/src/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm.cc +++ b/src/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm.cc @@ -20,7 +20,7 @@ namespace minimum_spanning_tree_kruskal_algorithm } // Graph private member methods - Node* Graph::makeOrFindNode(int data) + Node* Graph::_makeOrFindNode(int data) { Node* node = nullptr; if (this->_nodeMap.find(data) == this->_nodeMap.end()) @@ -35,18 +35,18 @@ namespace minimum_spanning_tree_kruskal_algorithm return node; } - void Graph::makeSet(Node* node) + void Graph::_makeSet(Node* node) { node->parent = node; node->rank = 0; } - void Graph::unionSet(Node* nodeU, Node* nodeV) + void Graph::_unionSet(Node* nodeU, Node* nodeV) { - this->link(this->findSet(nodeU), this->findSet(nodeV)); + this->_linkSet(this->_findSet(nodeU), this->_findSet(nodeV)); } - void Graph::link(Node* nodeU, Node* nodeV) + void Graph::_linkSet(Node* nodeU, Node* nodeV) { if (nodeV->rank > nodeU->rank) { @@ -62,11 +62,11 @@ namespace minimum_spanning_tree_kruskal_algorithm } } - Node* Graph::findSet(Node* node) + Node* Graph::_findSet(Node* node) { if (node != node->parent) { - node->parent = this->findSet(node->parent); + node->parent = this->_findSet(node->parent); } return node->parent; } @@ -74,8 +74,8 @@ namespace minimum_spanning_tree_kruskal_algorithm // Graph public member methods void Graph::pushUndirectedEdge(int dataU, int dataV, int weight) { - Node* nodeU = this->makeOrFindNode(dataU); - Node* nodeV = this->makeOrFindNode(dataV); + Node* nodeU = this->_makeOrFindNode(dataU); + Node* nodeV = this->_makeOrFindNode(dataV); this->_adjlist[nodeU].push_back(nodeV); this->_adjlist[nodeV].push_back(nodeU); @@ -86,16 +86,16 @@ namespace minimum_spanning_tree_kruskal_algorithm { for (auto& iterator : this->_nodeMap) { - this->makeSet(iterator.second); + this->_makeSet(iterator.second); } sort(this->_edgeList.begin(), this->_edgeList.end(), [](Edge* edgeX, Edge* edgeY) { return edgeX->weight < edgeY->weight; }); for (auto& edge : this->_edgeList) { - if (this->findSet(edge->nodeU) != this->findSet(edge->nodeV)) + if (this->_findSet(edge->nodeU) != this->_findSet(edge->nodeV)) { - this->unionSet(edge->nodeU, edge->nodeV); + this->_unionSet(edge->nodeU, edge->nodeV); this->_minimumSpanningTree.push_back({ {edge->nodeU->data, edge->nodeV->data}, edge->weight }); } } diff --git a/src/0003_graph/0008_minimum_spanning_tree_prim_algorithm.cc b/src/0003_graph/0008_minimum_spanning_tree_prim_algorithm.cc index 8ac0237..6267d1c 100644 --- a/src/0003_graph/0008_minimum_spanning_tree_prim_algorithm.cc +++ b/src/0003_graph/0008_minimum_spanning_tree_prim_algorithm.cc @@ -14,7 +14,7 @@ namespace minimum_spanning_tree_prim_algorithm } // Graph private member methods - Node* Graph::makeOrFindNode(int data) + Node* Graph::_makeOrFindNode(int data) { Node* node = nullptr; if (this->_nodeMap.find(data) == this->_nodeMap.end()) @@ -32,8 +32,8 @@ namespace minimum_spanning_tree_prim_algorithm // Graph public member methods void Graph::pushUndirectedEdge(int dataU, int dataV, int weight) { - Node* nodeU = this->makeOrFindNode(dataU); - Node* nodeV = this->makeOrFindNode(dataV); + Node* nodeU = this->_makeOrFindNode(dataU); + Node* nodeV = this->_makeOrFindNode(dataV); this->_adjlist[nodeU].push_back({nodeV, weight}); this->_adjlist[nodeV].push_back({nodeU, weight}); diff --git a/src/0003_graph/0009_single_source_shortest_path_bellman_ford.cc b/src/0003_graph/0009_single_source_shortest_path_bellman_ford.cc index becfa00..250d06e 100644 --- a/src/0003_graph/0009_single_source_shortest_path_bellman_ford.cc +++ b/src/0003_graph/0009_single_source_shortest_path_bellman_ford.cc @@ -20,7 +20,7 @@ namespace single_source_shortest_path_bellman_ford } // Graph private member methods - Node* Graph::makeOrFindNode(int data) + Node* Graph::_makeOrFindNode(int data) { Node* node = nullptr; if (this->_nodeMap.find(data) == this->_nodeMap.end()) @@ -35,7 +35,7 @@ namespace single_source_shortest_path_bellman_ford return node; } - void Graph :: initializeSingleSource(Node* sourceNode) + void Graph :: _initializeSingleSource(Node* sourceNode) { for (auto& iterator : this->_nodeMap) { @@ -45,7 +45,7 @@ namespace single_source_shortest_path_bellman_ford sourceNode->distance = 0; } - void Graph::relax(Edge* edge) + void Graph::_relax(Edge* edge) { if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) { @@ -54,20 +54,20 @@ namespace single_source_shortest_path_bellman_ford } } - void Graph::getShortestPath(Node* node, vector& path) + void Graph::_getShortestPath(Node* node, vector& path) { path.push_back(node->data); if (node->parent != nullptr) { - this->getShortestPath(node->parent, path); + this->_getShortestPath(node->parent, path); } } // Graph public member methods void Graph::pushDirectedEdge(int dataU, int dataV, int weight) { - Node* nodeU = this->makeOrFindNode(dataU); - Node* nodeV = this->makeOrFindNode(dataV); + Node* nodeU = this->_makeOrFindNode(dataU); + Node* nodeV = this->_makeOrFindNode(dataV); this->_adjlist[nodeU].push_back(nodeV); this->_edgeList.push_back(new Edge(nodeU, nodeV, weight)); @@ -77,13 +77,13 @@ namespace single_source_shortest_path_bellman_ford { Node* source = this->_nodeMap[data]; - this->initializeSingleSource(source); + this->_initializeSingleSource(source); for (int i = 0; i < this->_nodeMap.size() - 1; i++) { for (auto& edge : this->_edgeList) { - this->relax(edge); + this->_relax(edge); } } @@ -101,7 +101,7 @@ namespace single_source_shortest_path_bellman_ford { vector path = {}; Node* node = this->_nodeMap[data]; - this->getShortestPath(node, path); + this->_getShortestPath(node, path); reverse(path.begin(), path.end()); return path; } diff --git a/src/0003_graph/0010_directed_acyclic_graph_shortest_path.cc b/src/0003_graph/0010_directed_acyclic_graph_shortest_path.cc index 6634790..ee6c49b 100644 --- a/src/0003_graph/0010_directed_acyclic_graph_shortest_path.cc +++ b/src/0003_graph/0010_directed_acyclic_graph_shortest_path.cc @@ -21,7 +21,7 @@ namespace directed_acyclic_graph_shortest_path } // Graph private member methods - Node* Graph::makeOrFindNode(int data) + Node* Graph::_makeOrFindNode(int data) { Node* node = nullptr; if (this->_nodeMap.find(data) == this->_nodeMap.end()) @@ -36,32 +36,32 @@ namespace directed_acyclic_graph_shortest_path return node; } - void Graph::depthFirstSearch(Node* nodeU) + void Graph::_depthFirstSearch(Node* nodeU) { nodeU->color = GRAY; for (auto& nodeV : this->_adjlist[nodeU]) { if (nodeV->color == WHITE) { - this->depthFirstSearch(nodeV); + this->_depthFirstSearch(nodeV); } } nodeU->color = BLACK; this->_topologicalSortedNodeList.push_front(nodeU); } - void Graph::topologicalSort() + void Graph::_topologicalSort() { for (auto& iterator : this->_nodeMap) { if (iterator.second->color == WHITE) { - this->depthFirstSearch(iterator.second); + this->_depthFirstSearch(iterator.second); } } } - void Graph::initializeSingleSource(Node* sourceNode) + void Graph::_initializeSingleSource(Node* sourceNode) { for (auto& iterator : this->_nodeMap) { @@ -71,7 +71,7 @@ namespace directed_acyclic_graph_shortest_path sourceNode->distance = 0; } - void Graph::relax(Edge* edge) + void Graph::_relax(Edge* edge) { if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) { @@ -80,20 +80,20 @@ namespace directed_acyclic_graph_shortest_path } } - void Graph::getShortestPath(Node* node, vector& path) + void Graph::_getShortestPath(Node* node, vector& path) { path.push_back(node->data); if (node->parent != nullptr) { - this->getShortestPath(node->parent, path); + this->_getShortestPath(node->parent, path); } } // Graph public member methods void Graph::pushDirectedEdge(int dataU, int dataV, int weight) { - Node* nodeU = this->makeOrFindNode(dataU); - Node* nodeV = this->makeOrFindNode(dataV); + Node* nodeU = this->_makeOrFindNode(dataU); + Node* nodeV = this->_makeOrFindNode(dataV); this->_adjlist[nodeU].push_back(nodeV); this->_edgeMap[nodeU].push_back(new Edge(nodeU, nodeV, weight)); @@ -101,14 +101,14 @@ namespace directed_acyclic_graph_shortest_path void Graph::findDAGShortestPath(int data) { - this->topologicalSort(); + this->_topologicalSort(); Node* source = this->_nodeMap[data]; - this->initializeSingleSource(source); + this->_initializeSingleSource(source); for (auto& node : this->_topologicalSortedNodeList) { for (auto& edge : this->_edgeMap[node]) { - this->relax(edge); + this->_relax(edge); } } } @@ -117,7 +117,7 @@ namespace directed_acyclic_graph_shortest_path { vector path = {}; Node* node = this->_nodeMap[data]; - this->getShortestPath(node, path); + this->_getShortestPath(node, path); reverse(path.begin(), path.end()); return path; } diff --git a/src/0003_graph/0011_single_source_shortest_path_dijkstra.cc b/src/0003_graph/0011_single_source_shortest_path_dijkstra.cc index 7904dbb..f582213 100644 --- a/src/0003_graph/0011_single_source_shortest_path_dijkstra.cc +++ b/src/0003_graph/0011_single_source_shortest_path_dijkstra.cc @@ -20,7 +20,7 @@ namespace single_source_shortest_path_dijkstra } // Graph private member methods - Node* Graph::makeOrFindNode(int data) + Node* Graph::_makeOrFindNode(int data) { Node* node = nullptr; if (this->_nodeMap.find(data) == this->_nodeMap.end()) @@ -35,7 +35,7 @@ namespace single_source_shortest_path_dijkstra return node; } - void Graph::initializeSingleSource(Node* sourceNode) + void Graph::_initializeSingleSource(Node* sourceNode) { for (auto& iterator : this->_nodeMap) { @@ -45,7 +45,7 @@ namespace single_source_shortest_path_dijkstra sourceNode->distance = 0; } - void Graph::relax(Edge* edge) + void Graph::_relax(Edge* edge) { if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) { @@ -56,9 +56,9 @@ namespace single_source_shortest_path_dijkstra } } - void Graph::dijkstra(Node* source) + void Graph::_dijkstra(Node* source) { - this->initializeSingleSource(source); + this->_initializeSingleSource(source); for (auto& node : this->_nodeMap) { @@ -72,25 +72,25 @@ namespace single_source_shortest_path_dijkstra for (auto& edge : this->_edgeMap[nodeU]) { - this->relax(edge); + this->_relax(edge); } } } - void Graph::getShortestPath(Node* node, vector& path) + void Graph::_getShortestPath(Node* node, vector& path) { path.push_back(node->data); if (node->parent != nullptr) { - this->getShortestPath(node->parent, path); + this->_getShortestPath(node->parent, path); } } // Graph public member methods void Graph::pushDirectedEdge(int dataU, int dataV, int weight) { - Node* nodeU = this->makeOrFindNode(dataU); - Node* nodeV = this->makeOrFindNode(dataV); + Node* nodeU = this->_makeOrFindNode(dataU); + Node* nodeV = this->_makeOrFindNode(dataV); this->_adjlist[nodeU].push_back(nodeV); this->_edgeMap[nodeU].push_back(new Edge(nodeU, nodeV, weight)); @@ -99,14 +99,14 @@ namespace single_source_shortest_path_dijkstra void Graph::findShortestPathDijkstra(int data) { Node* source = this->_nodeMap[data]; - this->dijkstra(source); + this->_dijkstra(source); } vector Graph::getDijkstraShortestPath(int data) { vector path = {}; Node* node = this->_nodeMap[data]; - this->getShortestPath(node, path); + this->_getShortestPath(node, path); reverse(path.begin(), path.end()); return path; } diff --git a/src/0003_graph/0012_difference_constraints_shortest_paths.cc b/src/0003_graph/0012_difference_constraints_shortest_paths.cc index 767d259..4c08f2d 100644 --- a/src/0003_graph/0012_difference_constraints_shortest_paths.cc +++ b/src/0003_graph/0012_difference_constraints_shortest_paths.cc @@ -18,7 +18,7 @@ namespace difference_constraints_shortest_paths } // Graph private member methods - Node* Graph::makeOrFindNode(string data) + Node* Graph::_makeOrFindNode(string data) { Node* node = nullptr; if (this->_nodeMap.find(data) == this->_nodeMap.end()) @@ -33,16 +33,16 @@ namespace difference_constraints_shortest_paths return node; } - void Graph::pushDirectedEdge(string dataU, string dataV, int weight) + void Graph::_pushDirectedEdge(string dataU, string dataV, int weight) { - Node* nodeU = this->makeOrFindNode(dataU); - Node* nodeV = this->makeOrFindNode(dataV); + Node* nodeU = this->_makeOrFindNode(dataU); + Node* nodeV = this->_makeOrFindNode(dataV); this->_adjlist[nodeU].push_back(nodeV); this->_edgeList.push_back(new Edge(nodeU, nodeV, weight)); } - void Graph::initializeSingleSource(Node* sourceNode) + void Graph::_initializeSingleSource(Node* sourceNode) { for (auto& iterator : this->_nodeMap) { @@ -51,7 +51,7 @@ namespace difference_constraints_shortest_paths sourceNode->distance = 0; } - void Graph::relax(Edge* edge) + void Graph::_relax(Edge* edge) { if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) { @@ -80,7 +80,7 @@ namespace difference_constraints_shortest_paths } } weight = vectorB[i]; - this->pushDirectedEdge(valueU, valueV, weight); + this->_pushDirectedEdge(valueU, valueV, weight); } // creating all the edges from the additional vertex @@ -90,7 +90,7 @@ namespace difference_constraints_shortest_paths for (int i = 0; i < vectorX.size(); i++) { valueV = vectorX[i]; - this->pushDirectedEdge(valueU, valueV, weight); + this->_pushDirectedEdge(valueU, valueV, weight); } } @@ -98,13 +98,13 @@ namespace difference_constraints_shortest_paths { Node* source = this->_nodeMap[""]; - this->initializeSingleSource(source); + this->_initializeSingleSource(source); for (int i = 0; i < this->_nodeMap.size(); i++) { for (auto& edge : this->_edgeList) { - this->relax(edge); + this->_relax(edge); } } diff --git a/src/0003_graph/0013_all_pairs_shortest_paths_floyd_warshall.cc b/src/0003_graph/0013_all_pairs_shortest_paths_floyd_warshall.cc index db2c7f3..91618a8 100644 --- a/src/0003_graph/0013_all_pairs_shortest_paths_floyd_warshall.cc +++ b/src/0003_graph/0013_all_pairs_shortest_paths_floyd_warshall.cc @@ -5,7 +5,7 @@ using namespace std; namespace all_pairs_shortest_paths_floyd_warshall { // Graph private member methods - void Graph::initializeDistanceAndPredecessors() + void Graph::_initializeDistanceAndPredecessors() { this->_shortestPathMatrixFloydWarshall = this->_adjMatrix; @@ -25,12 +25,12 @@ namespace all_pairs_shortest_paths_floyd_warshall } } - void Graph::getShortestPath(int source, int destination, vector& path) + void Graph::_getShortestPath(int source, int destination, vector& path) { if (this->_predecessorMatrix[source - 1][destination - 1] != source) { int predecessor = this->_predecessorMatrix[source - 1][destination - 1]; - this->getShortestPath(source, predecessor, path); + this->_getShortestPath(source, predecessor, path); path.push_back(predecessor); } } @@ -62,7 +62,7 @@ namespace all_pairs_shortest_paths_floyd_warshall void Graph::findAllPairsShortestPathsFloydWarshallSolution() { - this->initializeDistanceAndPredecessors(); + this->_initializeDistanceAndPredecessors(); for (int k = 0; k < this->_noOfVertices; k++) { @@ -93,7 +93,7 @@ namespace all_pairs_shortest_paths_floyd_warshall { vector path = {}; path.push_back(i + 1); - this->getShortestPath(i + 1, j + 1, path); + this->_getShortestPath(i + 1, j + 1, path); path.push_back(j + 1); result.push_back(path); } diff --git a/src/0003_graph/0014_all_pairs_shortest_paths_johnson.cc b/src/0003_graph/0014_all_pairs_shortest_paths_johnson.cc index d068e68..4028970 100644 --- a/src/0003_graph/0014_all_pairs_shortest_paths_johnson.cc +++ b/src/0003_graph/0014_all_pairs_shortest_paths_johnson.cc @@ -20,7 +20,7 @@ namespace all_pairs_shortest_paths_johnson } // Graph private member methods - Node* Graph::makeOrFindNode(int data) + Node* Graph::_makeOrFindNode(int data) { Node* node = nullptr; if (this->_nodeMap.find(data) == this->_nodeMap.end()) @@ -35,13 +35,13 @@ namespace all_pairs_shortest_paths_johnson return node; } - void Graph::pushAugmentedDirectedEdges(Node* sourceNode, Node* nodeV, int weight) + void Graph::_pushAugmentedDirectedEdges(Node* sourceNode, Node* nodeV, int weight) { this->_augmentedAdjlist[sourceNode].push_back(nodeV); this->_augmentedEdgeList.push_back(new Edge(sourceNode, nodeV, weight)); } - void Graph::initializeSingleSource(Node* sourceNode) + void Graph::_initializeSingleSource(Node* sourceNode) { for (auto& iterator : this->_nodeMap) { @@ -51,7 +51,7 @@ namespace all_pairs_shortest_paths_johnson sourceNode->distance = 0; } - void Graph::relaxBellmanFord(Edge* edge) + void Graph::_relaxBellmanFord(Edge* edge) { if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) { @@ -60,15 +60,15 @@ namespace all_pairs_shortest_paths_johnson } } - bool Graph::bellmanFord(Node* source) + bool Graph::_bellmanFord(Node* source) { - this->initializeSingleSource(source); + this->_initializeSingleSource(source); for (int i = 0; i < this->_nodeMap.size() - 1; i++) { for (auto& edge : this->_augmentedEdgeList) { - this->relaxBellmanFord(edge); + this->_relaxBellmanFord(edge); } } @@ -82,7 +82,7 @@ namespace all_pairs_shortest_paths_johnson return true; } - void Graph::relaxDijkstra(Edge* edge) + void Graph::_relaxDijkstra(Edge* edge) { if (edge->nodeU->distance != INT_MAX && (edge->nodeV->distance > (edge->nodeU->distance + edge->weight))) { @@ -93,9 +93,9 @@ namespace all_pairs_shortest_paths_johnson } } - void Graph::dijkstra(Node* source) + void Graph::_dijkstra(Node* source) { - this->initializeSingleSource(source); + this->_initializeSingleSource(source); for (auto& node : this->_nodeMap) { @@ -109,17 +109,17 @@ namespace all_pairs_shortest_paths_johnson for (auto& edge : this->_edgeMap[nodeU]) { - this->relaxDijkstra(edge); + this->_relaxDijkstra(edge); } } } - void Graph::getShortestPath(int source, int destination, vector& path) + void Graph::_getShortestPath(int source, int destination, vector& path) { if (this->_predecessorMatrix[source - 1][destination - 1] != source) { int predecessor = this->_predecessorMatrix[source - 1][destination - 1]; - this->getShortestPath(source, predecessor, path); + this->_getShortestPath(source, predecessor, path); path.push_back(predecessor); } } @@ -127,8 +127,8 @@ namespace all_pairs_shortest_paths_johnson // Graph public member methods void Graph::pushDirectedEdge(int dataU, int dataV, int weight) { - Node* nodeU = this->makeOrFindNode(dataU); - Node* nodeV = this->makeOrFindNode(dataV); + Node* nodeU = this->_makeOrFindNode(dataU); + Node* nodeV = this->_makeOrFindNode(dataV); this->_adjlist[nodeU].push_back(nodeV); Edge* edge = new Edge(nodeU, nodeV, weight); @@ -151,11 +151,11 @@ namespace all_pairs_shortest_paths_johnson { if (node.second != source) { - this->pushAugmentedDirectedEdges(source, node.second, 0); + this->_pushAugmentedDirectedEdges(source, node.second, 0); } } - if (this->bellmanFord(source) == false) + if (this->_bellmanFord(source) == false) { return false; } @@ -178,7 +178,7 @@ namespace all_pairs_shortest_paths_johnson for (auto& iteratorU : this->_nodeMap) { Node* nodeU = iteratorU.second; - this->dijkstra(nodeU); + this->_dijkstra(nodeU); for (auto& iteratorV : this->_nodeMap) { Node* nodeV = iteratorV.second; @@ -206,7 +206,7 @@ namespace all_pairs_shortest_paths_johnson { vector path = {}; path.push_back(i + 1); - this->getShortestPath(i + 1, j + 1, path); + this->_getShortestPath(i + 1, j + 1, path); path.push_back(j + 1); result.push_back(path); } diff --git a/src/0003_graph/0015_maximum_flow_ford_fulkerson.cc b/src/0003_graph/0015_maximum_flow_ford_fulkerson.cc index c975746..41c0124 100644 --- a/src/0003_graph/0015_maximum_flow_ford_fulkerson.cc +++ b/src/0003_graph/0015_maximum_flow_ford_fulkerson.cc @@ -5,7 +5,7 @@ using namespace std; namespace maximum_flow_ford_fulkerson { // Graph private member methods - void Graph::resolveAntiParallelEdges() + void Graph::_resolveAntiParallelEdges() { int countParallelEdges = 0; for (int i = 0; i < this->_noOfVertices; i++) @@ -61,7 +61,7 @@ namespace maximum_flow_ford_fulkerson this->_noOfVertices = newNoOfVertices; } - void Graph::depthFirstSearchVisit(int nodeU) + void Graph::_depthFirstSearchVisit(int nodeU) { this->_visited[nodeU] = true; for (int nodeV = 0; nodeV < this->_noOfVertices; nodeV++) @@ -69,12 +69,12 @@ namespace maximum_flow_ford_fulkerson if (!this->_visited[nodeV] && this->_residualGraph[nodeU][nodeV] > 0) { this->_parent[nodeV] = nodeU; - this->depthFirstSearchVisit(nodeV); + this->_depthFirstSearchVisit(nodeV); } } } - bool Graph::depthFirstSearch() + bool Graph::_depthFirstSearch() { // resetting the visited values fill(this->_visited.begin(), this->_visited.end(), false); @@ -83,7 +83,7 @@ namespace maximum_flow_ford_fulkerson fill(this->_parent.begin(), this->_parent.end(), -1); // starting the depthFirstSearch from the source vertex - this->depthFirstSearchVisit(this->_source); + this->_depthFirstSearchVisit(this->_source); // returning the visited value of the sink vertex, initially it was set to false return this->_visited[this->_sink]; @@ -110,11 +110,11 @@ namespace maximum_flow_ford_fulkerson int Graph::findMaximumFlowFordFulkerson() { // resolving all the parallel edges if present - this->resolveAntiParallelEdges(); + this->_resolveAntiParallelEdges(); this->_residualGraph = this->_adjMatrix; // while there exists a path p from source to sink in the residual network G' - while (this->depthFirstSearch()) + while (this->_depthFirstSearch()) { int augmentedPathFlow = INT_MAX; diff --git a/src/0003_graph/0016_maximum_flow_edmonds_karp.cc b/src/0003_graph/0016_maximum_flow_edmonds_karp.cc index baeb840..0dfc02b 100644 --- a/src/0003_graph/0016_maximum_flow_edmonds_karp.cc +++ b/src/0003_graph/0016_maximum_flow_edmonds_karp.cc @@ -6,7 +6,7 @@ using namespace std; namespace maximum_flow_edmonds_karp { // Graph private member methods - void Graph::resolveAntiParallelEdges() + void Graph::_resolveAntiParallelEdges() { int countParallelEdges = 0; for (int i = 0; i < this->_noOfVertices; i++) @@ -62,7 +62,7 @@ namespace maximum_flow_edmonds_karp this->_noOfVertices = newNoOfVertices; } - bool Graph::breadthFirstSearch() + bool Graph::_breadthFirstSearch() { // resetting the visited values fill(this->_visited.begin(), this->_visited.end(), false); @@ -115,11 +115,11 @@ namespace maximum_flow_edmonds_karp int Graph::findMaximumFlowEdmondsKarp() { // resolving all the parallel edges if present - this->resolveAntiParallelEdges(); + this->_resolveAntiParallelEdges(); this->_residualGraph = this->_adjMatrix; // while there exists a path p from source to sink in the residual network G' - while (this->breadthFirstSearch()) + while (this->_breadthFirstSearch()) { int augmentedPathFlow = INT_MAX; diff --git a/src/0003_graph/0017_maximum_bipartite_matching.cc b/src/0003_graph/0017_maximum_bipartite_matching.cc index 30374cd..e5e505d 100644 --- a/src/0003_graph/0017_maximum_bipartite_matching.cc +++ b/src/0003_graph/0017_maximum_bipartite_matching.cc @@ -6,7 +6,7 @@ using namespace std; namespace maximum_bipartite_matching { // Graph private member methods - void Graph::resolveAntiParallelEdges() + void Graph::_resolveAntiParallelEdges() { int countParallelEdges = 0; for (int i = 0; i < this->_noOfVertices; i++) @@ -63,7 +63,7 @@ namespace maximum_bipartite_matching } // this method is used to color the vertices of the graph to determine if the given graph is bipartite or not - void Graph::colorGraph() + void Graph::_colorGraph() { // color of all the vertices are initialised to WHITE fill(this->_color.begin(), this->_color.end(), WHITE); @@ -125,7 +125,7 @@ namespace maximum_bipartite_matching // this method is used to create the additional edges // from the source vertex to the RED colored vertices and // from the BLUE colored vertices to the sink vertex - void Graph::addAdditionalEdges() + void Graph::_addAdditionalEdges() { // resizing the residual graph to accomodate space for the new edges for (auto& edge : this->_residualGraph) @@ -156,7 +156,7 @@ namespace maximum_bipartite_matching } // implementation of breadthFirstSearch for edmondsKarp algorithm to find the path from source to sink - bool Graph::breadthFirstSearch() + bool Graph::_breadthFirstSearch() { // resetting the visited values fill(this->_visited.begin(), this->_visited.end(), false); @@ -208,20 +208,20 @@ namespace maximum_bipartite_matching int Graph::findMaximumBipartiteMatching() { // resolving all the parallel edges if present - this->resolveAntiParallelEdges(); + this->_resolveAntiParallelEdges(); this->_residualGraph = this->_adjMatrix; - this->colorGraph(); + this->_colorGraph(); this->_source = this->_noOfVertices; this->_noOfVertices++; this->_sink = this->_noOfVertices; this->_noOfVertices++; - this->addAdditionalEdges(); + this->_addAdditionalEdges(); // while there exists a path p from source to sink in the residual network G' - while (this->breadthFirstSearch()) + while (this->_breadthFirstSearch()) { int augmentedPathFlow = 1; diff --git a/src/0003_graph/0018_maximum_flow_goldberg_generic_push_relabel.cc b/src/0003_graph/0018_maximum_flow_goldberg_generic_push_relabel.cc index 7127abc..be68e7e 100644 --- a/src/0003_graph/0018_maximum_flow_goldberg_generic_push_relabel.cc +++ b/src/0003_graph/0018_maximum_flow_goldberg_generic_push_relabel.cc @@ -7,7 +7,7 @@ namespace maximum_flow_goldberg_generic_push_relabel // Graph private member methods // initializes pre-flow in the given flow network - void Graph::initializePreflow() + void Graph::_initializePreflow() { // the height of source is set to highest possible height value this->_height[this->_source] = this->_noOfVertices; @@ -32,7 +32,7 @@ namespace maximum_flow_goldberg_generic_push_relabel } // checks if there is any vertex which has excess flow - bool Graph::checkOverFlow() + bool Graph::_checkOverFlow() { // iterating over all of the vertices for (int i = 0; i < this->_noOfVertices; i++) @@ -59,7 +59,7 @@ namespace maximum_flow_goldberg_generic_push_relabel } // pushes the flow from nodeU to its neighbour vertices - bool Graph::push(int nodeU) + bool Graph::_push(int nodeU) { int nodeV = -1; int minimumFlow = INT_MAX; @@ -98,7 +98,7 @@ namespace maximum_flow_goldberg_generic_push_relabel } // relabels height of vertex nodeU when there are outgoing non-saturated edges available - void Graph::relabel(int nodeU) + void Graph::_relabel(int nodeU) { int minimumHeight = INT_MAX; @@ -141,16 +141,16 @@ namespace maximum_flow_goldberg_generic_push_relabel this->_residualGraph = this->_adjMatrix; // initialize pre-flow - this->initializePreflow(); + this->_initializePreflow(); // checks if there is some vertices which have excess flow - while (this->checkOverFlow()) + while (this->_checkOverFlow()) { // get the vertex int nodeU = this->_nodeQueue.front(); // checks if the push operation is successful - if (this->push(nodeU)) + if (this->_push(nodeU)) { // then remove the vertex from queue and set visited[nodeU] = true // so that on next checkOverFlow() method call this vertex can be discovered if it still has some excess flow @@ -162,7 +162,7 @@ namespace maximum_flow_goldberg_generic_push_relabel else { // then relabel nodeU without removing it from the queue - this->relabel(nodeU); + this->_relabel(nodeU); } } diff --git a/src/0003_graph/0019_maximum_flow_relabel_to_front.cc b/src/0003_graph/0019_maximum_flow_relabel_to_front.cc index a9b72eb..c0f3a90 100644 --- a/src/0003_graph/0019_maximum_flow_relabel_to_front.cc +++ b/src/0003_graph/0019_maximum_flow_relabel_to_front.cc @@ -8,7 +8,7 @@ namespace maximum_flow_relabel_to_front // Graph private member methods // initializes pre-flow in the given flow network - void Graph::initializePreflow() + void Graph::_initializePreflow() { // the height of source is set to highest possible height value this->_height[this->_source] = this->_noOfVertices; @@ -33,7 +33,7 @@ namespace maximum_flow_relabel_to_front } // discharges the excess flow from nodeU - void Graph::discharge(int nodeU) + void Graph::_discharge(int nodeU) { // check if excess flow of nodeU is > 0 while (this->_excessFlow[nodeU] > 0) @@ -48,7 +48,7 @@ namespace maximum_flow_relabel_to_front if (this->_residualGraph[nodeU][nodeV] > 0 && this->_height[nodeU] == 1 + this->_height[nodeV]) { // push excess flow along the admissible edge (nodeU, nodeV) - this->push(nodeU, nodeV); + this->_push(nodeU, nodeV); // set the hasPushed flag to true hasPushed = true; // check if there is no excess flow left in nodeU then no need to check any more admissible edge going from nodeU @@ -65,13 +65,13 @@ namespace maximum_flow_relabel_to_front { // then it indicates that all the outgoing edges from nodeU are inadmissible // so perform the relabel operation on nodeU - this->relabel(nodeU); + this->_relabel(nodeU); } } } // pushes the flow from nodeU to its neighbour vertices - void Graph::push(int nodeU, int nodeV) + void Graph::_push(int nodeU, int nodeV) { // calculate the flow amount to be added along the edge and excess flow subtracted from nodeU int minimumFlow = min(this->_residualGraph[nodeU][nodeV], this->_excessFlow[nodeU]); @@ -86,7 +86,7 @@ namespace maximum_flow_relabel_to_front } // relabels height of vertex nodeU when there are outgoing non-saturated edges available - void Graph::relabel(int nodeU) + void Graph::_relabel(int nodeU) { int minimumHeight = INT_MAX; @@ -129,7 +129,7 @@ namespace maximum_flow_relabel_to_front this->_residualGraph = this->_adjMatrix; // initialize pre-flow - this->initializePreflow(); + this->_initializePreflow(); // make the list L = G.V - {source, sink} for (int i = 0; i < this->_noOfVertices; i++) @@ -150,7 +150,7 @@ namespace maximum_flow_relabel_to_front int oldHeight = this->_height[*nodeUiterator]; // discharge the excess flow of current vertex - this->discharge(*nodeUiterator); + this->_discharge(*nodeUiterator); // check if the height of current vertex increases which means the current vertex got relabeled if (this->_height[*nodeUiterator] > oldHeight) diff --git a/src/0003_graph/CMakeLists.txt b/src/0003_graph/CMakeLists.txt index 9daf4b5..3e98596 100644 --- a/src/0003_graph/CMakeLists.txt +++ b/src/0003_graph/CMakeLists.txt @@ -23,8 +23,8 @@ set(0003GRAPH_SOURCES ) # Create a library target -add_library(0003GRAPH ${0003GRAPH_SOURCES}) +add_library(0003_Graph ${0003GRAPH_SOURCES}) -target_include_directories(0003GRAPH PUBLIC +target_include_directories(0003_Graph PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/headers ) \ No newline at end of file diff --git a/src/0003_graph/headers/0001_breadth_first_search.h b/src/0003_graph/headers/0001_breadth_first_search.h index 64893cf..7a2a36c 100644 --- a/src/0003_graph/headers/0001_breadth_first_search.h +++ b/src/0003_graph/headers/0001_breadth_first_search.h @@ -25,8 +25,8 @@ namespace breadth_first_search private: map> _adjlist; map _nodeMap; - Node* makeOrFindNode(int value); - void breadthFirstSearch(Node* node); + Node* _makeOrFindNode(int value); + void _breadthFirstSearch(Node* node); public: void pushUndirectedEdge(int valueU, int valueV); void bfs(int value); diff --git a/src/0003_graph/headers/0002_depth_first_search.h b/src/0003_graph/headers/0002_depth_first_search.h index c128dea..64ab19e 100644 --- a/src/0003_graph/headers/0002_depth_first_search.h +++ b/src/0003_graph/headers/0002_depth_first_search.h @@ -27,8 +27,8 @@ namespace depth_first_search int _time; map> _adjlist; map _nodeMap; - Node* makeOrFindNode(int value); - void depthFirstSearch(Node* Node); + Node* _makeOrFindNode(int value); + void _depthFirstSearch(Node* Node); public: void pushDirectedEdge(int valueU, int valueV); void dfs(); diff --git a/src/0003_graph/headers/0003_topological_sort.h b/src/0003_graph/headers/0003_topological_sort.h index 5373d41..553e3ca 100644 --- a/src/0003_graph/headers/0003_topological_sort.h +++ b/src/0003_graph/headers/0003_topological_sort.h @@ -30,8 +30,8 @@ namespace topological_sort map> _adjlist; map _nodeMap; list _topologicalSortedNodeList; - Node* makeOrFindNode(int value); - void depthFirstSearch(Node* dFSNode); + Node* _makeOrFindNode(int value); + void _depthFirstSearch(Node* dFSNode); public: void pushDirectedEdge(int valueU, int valueV); void pushSingleNode(int valueU); diff --git a/src/0003_graph/headers/0004_strongly_connected_components.h b/src/0003_graph/headers/0004_strongly_connected_components.h index 3fbd84c..4b0e9e6 100644 --- a/src/0003_graph/headers/0004_strongly_connected_components.h +++ b/src/0003_graph/headers/0004_strongly_connected_components.h @@ -30,9 +30,9 @@ namespace strongly_connected_components map _nodeMap; list _nodesFinishingTimeOrder; vector> _allConnectedComponents; - Node* makeOrFindNode(int value); - void depthFirstSearchOnGraphG(Node* dFSNode); - void depthFirstSearchOnGraphT(Node* dFSNode, vector& connectedComponents); + Node* _makeOrFindNode(int value); + void _depthFirstSearchOnGraphG(Node* dFSNode); + void _depthFirstSearchOnGraphT(Node* dFSNode, vector& connectedComponents); public: void pushDirectedEdge(int valueU, int valueV); void pushSingleNode(int valueU); diff --git a/src/0003_graph/headers/0005_hamiltonian_path_and_cycle.h b/src/0003_graph/headers/0005_hamiltonian_path_and_cycle.h index 8e52744..37e64fa 100644 --- a/src/0003_graph/headers/0005_hamiltonian_path_and_cycle.h +++ b/src/0003_graph/headers/0005_hamiltonian_path_and_cycle.h @@ -25,9 +25,9 @@ namespace hamiltonian_path_and_cycle map> _adjlist; map _nodeMap; vector _hamiltonianPath; - Node* makeOrFindNode(int value); - bool isSafe(Node* nodeU, Node* nodeV); - bool hamiltonianCycleAndPathUtil(Node* node); + Node* _makeOrFindNode(int value); + bool _isSafe(Node* nodeU, Node* nodeV); + bool _hamiltonianCycleAndPathUtil(Node* node); public: void pushUndirectedEdge(int valueU, int valueV); diff --git a/src/0003_graph/headers/0006_eulerian_path_and_circuit.h b/src/0003_graph/headers/0006_eulerian_path_and_circuit.h index 27b8cb5..42dd7e0 100644 --- a/src/0003_graph/headers/0006_eulerian_path_and_circuit.h +++ b/src/0003_graph/headers/0006_eulerian_path_and_circuit.h @@ -26,10 +26,10 @@ namespace eulerian_path_and_circuit map> _adjlist; map _nodeMap; vector _eulerianPath; - Node* makeOrFindNode(int value); - void depthFirstSearch(Node* node); - bool isConnected(); - void eulerianPathHierholzerAlgorithm(Node* startingNode); + Node* _makeOrFindNode(int value); + void _depthFirstSearch(Node* node); + bool _isConnected(); + void _eulerianPathHierholzerAlgorithm(Node* startingNode); public: void pushUndirectedEdge(int valueU, int valueV); diff --git a/src/0003_graph/headers/0007_minimum_spanning_tree_kruskal_algorithm.h b/src/0003_graph/headers/0007_minimum_spanning_tree_kruskal_algorithm.h index fcf4a52..95db855 100644 --- a/src/0003_graph/headers/0007_minimum_spanning_tree_kruskal_algorithm.h +++ b/src/0003_graph/headers/0007_minimum_spanning_tree_kruskal_algorithm.h @@ -32,11 +32,11 @@ namespace minimum_spanning_tree_kruskal_algorithm map _nodeMap; vector _edgeList; vector, int>> _minimumSpanningTree; - Node* makeOrFindNode(int data); - void makeSet(Node* node); - void unionSet(Node* nodeU, Node* nodeV); - void link(Node* nodeU, Node* nodeV); - Node* findSet(Node* node); + Node* _makeOrFindNode(int data); + void _makeSet(Node* node); + void _unionSet(Node* nodeU, Node* nodeV); + void _linkSet(Node* nodeU, Node* nodeV); + Node* _findSet(Node* node); public: void pushUndirectedEdge(int valueU, int valueV, int weight); diff --git a/src/0003_graph/headers/0008_minimum_spanning_tree_prim_algorithm.h b/src/0003_graph/headers/0008_minimum_spanning_tree_prim_algorithm.h index 15ae01f..adfca0b 100644 --- a/src/0003_graph/headers/0008_minimum_spanning_tree_prim_algorithm.h +++ b/src/0003_graph/headers/0008_minimum_spanning_tree_prim_algorithm.h @@ -33,7 +33,7 @@ namespace minimum_spanning_tree_prim_algorithm map _nodeMap; vector, int>> _minimumSpanningTree; multiset _operationalSet; - Node* makeOrFindNode(int data); + Node* _makeOrFindNode(int data); public: void pushUndirectedEdge(int valueU, int valueV, int weight); void findMinimumSpanningTreePrimAlgorithm(); diff --git a/src/0003_graph/headers/0009_single_source_shortest_path_bellman_ford.h b/src/0003_graph/headers/0009_single_source_shortest_path_bellman_ford.h index c5cb712..bfcd3c1 100644 --- a/src/0003_graph/headers/0009_single_source_shortest_path_bellman_ford.h +++ b/src/0003_graph/headers/0009_single_source_shortest_path_bellman_ford.h @@ -30,10 +30,10 @@ namespace single_source_shortest_path_bellman_ford map> _adjlist; map _nodeMap; vector _edgeList; - Node* makeOrFindNode(int data); - void initializeSingleSource(Node* sourceNode); - void relax(Edge* edge); - void getShortestPath(Node* node, vector& path); + Node* _makeOrFindNode(int data); + void _initializeSingleSource(Node* sourceNode); + void _relax(Edge* edge); + void _getShortestPath(Node* node, vector& path); public: diff --git a/src/0003_graph/headers/0010_directed_acyclic_graph_shortest_path.h b/src/0003_graph/headers/0010_directed_acyclic_graph_shortest_path.h index 2ee5ca6..cf5f93c 100644 --- a/src/0003_graph/headers/0010_directed_acyclic_graph_shortest_path.h +++ b/src/0003_graph/headers/0010_directed_acyclic_graph_shortest_path.h @@ -35,12 +35,12 @@ namespace directed_acyclic_graph_shortest_path map _nodeMap; map> _edgeMap; list _topologicalSortedNodeList; - Node* makeOrFindNode(int data); - void depthFirstSearch(Node* node); - void topologicalSort(); - void initializeSingleSource(Node* sourceNode); - void relax(Edge* edge); - void getShortestPath(Node* node, vector& path); + Node* _makeOrFindNode(int data); + void _depthFirstSearch(Node* node); + void _topologicalSort(); + void _initializeSingleSource(Node* sourceNode); + void _relax(Edge* edge); + void _getShortestPath(Node* node, vector& path); public: diff --git a/src/0003_graph/headers/0011_single_source_shortest_path_dijkstra.h b/src/0003_graph/headers/0011_single_source_shortest_path_dijkstra.h index 28c90b9..0d5ae13 100644 --- a/src/0003_graph/headers/0011_single_source_shortest_path_dijkstra.h +++ b/src/0003_graph/headers/0011_single_source_shortest_path_dijkstra.h @@ -41,11 +41,11 @@ namespace single_source_shortest_path_dijkstra map _nodeMap; map> _edgeMap; multiset _operationalSet; - Node* makeOrFindNode(int data); - void initializeSingleSource(Node* sourceNode); - void relax(Edge* edge); - void dijkstra(Node* source); - void getShortestPath(Node* node, vector& path); + Node* _makeOrFindNode(int data); + void _initializeSingleSource(Node* sourceNode); + void _relax(Edge* edge); + void _dijkstra(Node* source); + void _getShortestPath(Node* node, vector& path); public: void pushDirectedEdge(int valueU, int valueV, int weight); diff --git a/src/0003_graph/headers/0012_difference_constraints_shortest_paths.h b/src/0003_graph/headers/0012_difference_constraints_shortest_paths.h index bda0d4a..5237b70 100644 --- a/src/0003_graph/headers/0012_difference_constraints_shortest_paths.h +++ b/src/0003_graph/headers/0012_difference_constraints_shortest_paths.h @@ -30,10 +30,10 @@ namespace difference_constraints_shortest_paths map> _adjlist; map _nodeMap; vector _edgeList; - Node* makeOrFindNode(string data); - void pushDirectedEdge(string valueU, string valueV, int weight); - void initializeSingleSource(Node* sourceNode); - void relax(Edge* edge); + Node* _makeOrFindNode(string data); + void _pushDirectedEdge(string valueU, string valueV, int weight); + void _initializeSingleSource(Node* sourceNode); + void _relax(Edge* edge); public: void pushAllDirectedEdges(vector> vectorA, vector vectorX, vector vectorB); diff --git a/src/0003_graph/headers/0013_all_pairs_shortest_paths_floyd_warshall.h b/src/0003_graph/headers/0013_all_pairs_shortest_paths_floyd_warshall.h index cc6ce1b..9226e7a 100644 --- a/src/0003_graph/headers/0013_all_pairs_shortest_paths_floyd_warshall.h +++ b/src/0003_graph/headers/0013_all_pairs_shortest_paths_floyd_warshall.h @@ -12,8 +12,8 @@ namespace all_pairs_shortest_paths_floyd_warshall vector> _adjMatrix; vector> _shortestPathMatrixFloydWarshall; vector> _predecessorMatrix; - void initializeDistanceAndPredecessors(); - void getShortestPath(int source, int destination, vector& path); + void _initializeDistanceAndPredecessors(); + void _getShortestPath(int source, int destination, vector& path); public: void createGraph(int noOfVertices); diff --git a/src/0003_graph/headers/0014_all_pairs_shortest_paths_johnson.h b/src/0003_graph/headers/0014_all_pairs_shortest_paths_johnson.h index 1f091dc..56b4948 100644 --- a/src/0003_graph/headers/0014_all_pairs_shortest_paths_johnson.h +++ b/src/0003_graph/headers/0014_all_pairs_shortest_paths_johnson.h @@ -48,14 +48,14 @@ namespace all_pairs_shortest_paths_johnson multiset _operationalSet; vector> _shortestPathMatrix; vector> _predecessorMatrix; - Node* makeOrFindNode(int data); - void pushAugmentedDirectedEdges(Node* sourceNode, Node* nodeV, int weight); - void initializeSingleSource(Node* sourceNode); - void relaxBellmanFord(Edge* edge); - bool bellmanFord(Node* source); - void relaxDijkstra(Edge* edge); - void dijkstra(Node* source); - void getShortestPath(int source, int destination, vector& path); + Node* _makeOrFindNode(int data); + void _pushAugmentedDirectedEdges(Node* sourceNode, Node* nodeV, int weight); + void _initializeSingleSource(Node* sourceNode); + void _relaxBellmanFord(Edge* edge); + bool _bellmanFord(Node* source); + void _relaxDijkstra(Edge* edge); + void _dijkstra(Node* source); + void _getShortestPath(int source, int destination, vector& path); public: void pushDirectedEdge(int dataU, int dataV, int weight); diff --git a/src/0003_graph/headers/0015_maximum_flow_ford_fulkerson.h b/src/0003_graph/headers/0015_maximum_flow_ford_fulkerson.h index 1815566..f685e33 100644 --- a/src/0003_graph/headers/0015_maximum_flow_ford_fulkerson.h +++ b/src/0003_graph/headers/0015_maximum_flow_ford_fulkerson.h @@ -18,9 +18,9 @@ namespace maximum_flow_ford_fulkerson vector> _residualGraph; vector _parent; vector _visited; - void resolveAntiParallelEdges(); - void depthFirstSearchVisit(int nodeU); - bool depthFirstSearch(); + void _resolveAntiParallelEdges(); + void _depthFirstSearchVisit(int nodeU); + bool _depthFirstSearch(); public: void createGraph(int noOfVertices); void pushDirectedEdge(int valueU, int valueV, int capacity); diff --git a/src/0003_graph/headers/0016_maximum_flow_edmonds_karp.h b/src/0003_graph/headers/0016_maximum_flow_edmonds_karp.h index 2b5904d..c0036ca 100644 --- a/src/0003_graph/headers/0016_maximum_flow_edmonds_karp.h +++ b/src/0003_graph/headers/0016_maximum_flow_edmonds_karp.h @@ -18,8 +18,8 @@ namespace maximum_flow_edmonds_karp vector> _residualGraph; vector _parent; vector _visited; - void resolveAntiParallelEdges(); - bool breadthFirstSearch(); + void _resolveAntiParallelEdges(); + bool _breadthFirstSearch(); public: void createGraph(int noOfVertices); void pushDirectedEdge(int valueU, int valueV, int capacity); diff --git a/src/0003_graph/headers/0017_maximum_bipartite_matching.h b/src/0003_graph/headers/0017_maximum_bipartite_matching.h index 88e0bc2..994f6ea 100644 --- a/src/0003_graph/headers/0017_maximum_bipartite_matching.h +++ b/src/0003_graph/headers/0017_maximum_bipartite_matching.h @@ -28,10 +28,10 @@ namespace maximum_bipartite_matching vector _visited; vector _color; vector> _matchings; - void resolveAntiParallelEdges(); - void colorGraph(); - void addAdditionalEdges(); - bool breadthFirstSearch(); + void _resolveAntiParallelEdges(); + void _colorGraph(); + void _addAdditionalEdges(); + bool _breadthFirstSearch(); public: void createGraph(int noOfVertices); void pushDirectedEdge(int valueU, int valueV); diff --git a/src/0003_graph/headers/0018_maximum_flow_goldberg_generic_push_relabel.h b/src/0003_graph/headers/0018_maximum_flow_goldberg_generic_push_relabel.h index af138a3..7f42725 100644 --- a/src/0003_graph/headers/0018_maximum_flow_goldberg_generic_push_relabel.h +++ b/src/0003_graph/headers/0018_maximum_flow_goldberg_generic_push_relabel.h @@ -19,10 +19,10 @@ namespace maximum_flow_goldberg_generic_push_relabel vector _height; vector _visited; queue _nodeQueue; - void initializePreflow(); - bool checkOverFlow(); - bool push(int nodeU); - void relabel(int nodeU); + void _initializePreflow(); + bool _checkOverFlow(); + bool _push(int nodeU); + void _relabel(int nodeU); public: void createGraph(int noOfVertices); void pushDirectedEdge(int valueU, int valueV, int capacity); diff --git a/src/0003_graph/headers/0019_maximum_flow_relabel_to_front.h b/src/0003_graph/headers/0019_maximum_flow_relabel_to_front.h index 785c427..839cd26 100644 --- a/src/0003_graph/headers/0019_maximum_flow_relabel_to_front.h +++ b/src/0003_graph/headers/0019_maximum_flow_relabel_to_front.h @@ -19,10 +19,10 @@ namespace maximum_flow_relabel_to_front vector _height; vector _visited; list _nodeList; - void initializePreflow(); - void discharge(int nodeU); - void push(int nodeU, int nodeV); - void relabel(int nodeU); + void _initializePreflow(); + void _discharge(int nodeU); + void _push(int nodeU, int nodeV); + void _relabel(int nodeU); public: void createGraph(int noOfVertices); void pushDirectedEdge(int valueU, int valueV, int capacity); diff --git a/src/0004_dynamic_programming/0004_minimum_cost_climbing_stairs.cc b/src/0004_dynamic_programming/0004_minimum_cost_climbing_stairs.cc index 92e87d9..4fc8ce0 100644 --- a/src/0004_dynamic_programming/0004_minimum_cost_climbing_stairs.cc +++ b/src/0004_dynamic_programming/0004_minimum_cost_climbing_stairs.cc @@ -3,14 +3,14 @@ namespace minimum_cost_climbing_stairs { - int DynamicProgramming::minCostRecursive(size_t step, vector& cost) + int DynamicProgramming::_minCostRecursive(size_t step, vector& cost) { if (step == 0 || step == 1) { return cost[step]; } - return cost[step] + min(this->minCostRecursive(step - 1, cost), this->minCostRecursive(step - 2, cost)); + return cost[step] + min(this->_minCostRecursive(step - 1, cost), this->_minCostRecursive(step - 2, cost)); } int DynamicProgramming::recursiveMinimumCostClimbingStairs(vector& cost) @@ -22,7 +22,7 @@ namespace minimum_cost_climbing_stairs return cost[0]; } - return min(this->minCostRecursive(totalSteps - 1, cost), this->minCostRecursive(totalSteps - 2, cost)); + return min(this->_minCostRecursive(totalSteps - 1, cost), this->_minCostRecursive(totalSteps - 2, cost)); } int DynamicProgramming::dpMinimumCostClimbingStairs(vector& cost) diff --git a/src/0004_dynamic_programming/0005_house_robber1.cc b/src/0004_dynamic_programming/0005_house_robber1.cc index 9e2be4b..d250fc5 100644 --- a/src/0004_dynamic_programming/0005_house_robber1.cc +++ b/src/0004_dynamic_programming/0005_house_robber1.cc @@ -2,7 +2,7 @@ namespace house_robber1 { - int DynamicProgramming::maxLootRecursive(size_t house, vector& houseValues) + int DynamicProgramming::_maxLootRecursive(size_t house, vector& houseValues) { if (house <= 0) { @@ -14,8 +14,8 @@ namespace house_robber1 return houseValues[0]; } - int pickCurrentHouse = houseValues[house - 1] + this->maxLootRecursive(house - 2, houseValues); - int dropCurrentHouse = this->maxLootRecursive(house - 1, houseValues); + int pickCurrentHouse = houseValues[house - 1] + this->_maxLootRecursive(house - 2, houseValues); + int dropCurrentHouse = this->_maxLootRecursive(house - 1, houseValues); return max(pickCurrentHouse, dropCurrentHouse); } @@ -23,7 +23,7 @@ namespace house_robber1 int DynamicProgramming::recursiveMaximumLoot(vector& houseValues) { size_t totalNumberOfHouses = houseValues.size(); - return this->maxLootRecursive(totalNumberOfHouses, houseValues); + return this->_maxLootRecursive(totalNumberOfHouses, houseValues); } int DynamicProgramming::dpMaximumLoot(vector& houseValues) diff --git a/src/0004_dynamic_programming/0006_house_robber2.cc b/src/0004_dynamic_programming/0006_house_robber2.cc index bf87a96..421c141 100644 --- a/src/0004_dynamic_programming/0006_house_robber2.cc +++ b/src/0004_dynamic_programming/0006_house_robber2.cc @@ -2,7 +2,7 @@ namespace house_robber2 { - int DynamicProgramming::maxLootRecursive(size_t house, vector& houseValues) + int DynamicProgramming::_maxLootRecursive(size_t house, vector& houseValues) { if (house <= 0) { @@ -14,13 +14,13 @@ namespace house_robber2 return houseValues[0]; } - int pickCurrentHouse = houseValues[house - 1] + this->maxLootRecursive(house - 2, houseValues); - int dropCurrentHouse = this->maxLootRecursive(house - 1, houseValues); + int pickCurrentHouse = houseValues[house - 1] + this->_maxLootRecursive(house - 2, houseValues); + int dropCurrentHouse = this->_maxLootRecursive(house - 1, houseValues); return max(pickCurrentHouse, dropCurrentHouse); } - int DynamicProgramming::maxLootDp(size_t firstHouse, size_t lastHouse, vector& houseValues) + int DynamicProgramming::_maxLootDp(size_t firstHouse, size_t lastHouse, vector& houseValues) { int totalNumberOfHouses = lastHouse - firstHouse + 1; @@ -67,7 +67,7 @@ namespace house_robber2 // Case 2: exlcude first house. vector pickLastHouse(houseValues.begin() + 1, houseValues.end()); - return max(this->maxLootRecursive(totalNumberOfHouses, pickFirstHouse), this->maxLootRecursive(totalNumberOfHouses, pickLastHouse)); + return max(this->_maxLootRecursive(totalNumberOfHouses, pickFirstHouse), this->_maxLootRecursive(totalNumberOfHouses, pickLastHouse)); } int DynamicProgramming::dpMaximumLoot(vector& houseValues) @@ -85,10 +85,10 @@ namespace house_robber2 } // Case 1: exclude last house. - int pickFirstHouse = this->maxLootDp(0, totalNumberOfHouses - 2, houseValues); + int pickFirstHouse = this->_maxLootDp(0, totalNumberOfHouses - 2, houseValues); // Case 2: exlcude first house. - int pickLastHouse = this->maxLootDp(1, totalNumberOfHouses - 1, houseValues); + int pickLastHouse = this->_maxLootDp(1, totalNumberOfHouses - 1, houseValues); return max(pickFirstHouse, pickLastHouse); } diff --git a/src/0004_dynamic_programming/0007_decode_ways.cc b/src/0004_dynamic_programming/0007_decode_ways.cc index ee4f14e..0265074 100644 --- a/src/0004_dynamic_programming/0007_decode_ways.cc +++ b/src/0004_dynamic_programming/0007_decode_ways.cc @@ -2,7 +2,7 @@ namespace decode_ways { - int DynamicProgramming::countWaysRecursiveHelper(string& digits, size_t index) + int DynamicProgramming::_countWaysRecursiveHelper(string& digits, size_t index) { size_t digitsLength = digits.size(); @@ -17,20 +17,20 @@ namespace decode_ways // single digit decoding: check if current digit is not '0'. if (digits[index] != '0') { - ways = this->countWaysRecursiveHelper(digits, index + 1); + ways = this->_countWaysRecursiveHelper(digits, index + 1); } // two digit decoding: check if next two digits are valid. if ((index + 1 < digitsLength) && ((digits[index] == '1' && digits[index + 1] <= '9') || (digits[index] == '2' && digits[index + 1] <= '6'))) { - ways += this->countWaysRecursiveHelper(digits, index + 2); + ways += this->_countWaysRecursiveHelper(digits, index + 2); } return ways; } int DynamicProgramming::recursiveCountWays(string digits) { - return this->countWaysRecursiveHelper(digits, 0); + return this->_countWaysRecursiveHelper(digits, 0); } int DynamicProgramming::dpCountways(string digits) diff --git a/src/0004_dynamic_programming/0008_tiling_problem.cc b/src/0004_dynamic_programming/0008_tiling_problem.cc index 070e80b..e1e0043 100644 --- a/src/0004_dynamic_programming/0008_tiling_problem.cc +++ b/src/0004_dynamic_programming/0008_tiling_problem.cc @@ -2,7 +2,7 @@ namespace tiling_problem { - int DynamicProgramming::numberOfWaysRecursiveHelper(int n) + int DynamicProgramming::_numberOfWaysRecursiveHelper(int n) { if (n < 0) { @@ -15,15 +15,15 @@ namespace tiling_problem } int result = 0; - result += this->numberOfWaysRecursiveHelper(n - 1); - result += this->numberOfWaysRecursiveHelper(n - 2); + result += this->_numberOfWaysRecursiveHelper(n - 1); + result += this->_numberOfWaysRecursiveHelper(n - 2); return result; } int DynamicProgramming::recursiveNumberOfWays(int n) { - return this->numberOfWaysRecursiveHelper(n); + return this->_numberOfWaysRecursiveHelper(n); } int DynamicProgramming::dpNumberOfWays(int n) diff --git a/src/0004_dynamic_programming/0009_friends_pairing_problem.cc b/src/0004_dynamic_programming/0009_friends_pairing_problem.cc index d80c892..80ab43e 100644 --- a/src/0004_dynamic_programming/0009_friends_pairing_problem.cc +++ b/src/0004_dynamic_programming/0009_friends_pairing_problem.cc @@ -3,15 +3,15 @@ namespace friends_pairing_problem { // dynamic programming private member methods. - int DynamicProgramming::countFriendsPairingsRecursiveHelper(int n) + int DynamicProgramming::_countFriendsPairingsRecursiveHelper(int n) { if (n <= 1) { return 1; } int result = 0; - result += this->countFriendsPairingsRecursiveHelper(n - 1); - result += (n - 1) * this->countFriendsPairingsRecursiveHelper(n - 2); + result += this->_countFriendsPairingsRecursiveHelper(n - 1); + result += (n - 1) * this->_countFriendsPairingsRecursiveHelper(n - 2); return result; } @@ -19,7 +19,7 @@ namespace friends_pairing_problem // dynamic programming public member methods. int DynamicProgramming::recursiveCountFriendsPairings(int n) { - return this->countFriendsPairingsRecursiveHelper(n); + return this->_countFriendsPairingsRecursiveHelper(n); } int DynamicProgramming::dpCountFriendsPairings(int n) diff --git a/src/0004_dynamic_programming/0010_ways_to_cover_distance.cc b/src/0004_dynamic_programming/0010_ways_to_cover_distance.cc index e9301ca..6e539c7 100644 --- a/src/0004_dynamic_programming/0010_ways_to_cover_distance.cc +++ b/src/0004_dynamic_programming/0010_ways_to_cover_distance.cc @@ -3,7 +3,7 @@ namespace ways_to_cover_distance { // dynamic programming private member methods. - int DynamicProgramming::waysToCoverDistanceRecursiveHelper(int dist) + int DynamicProgramming::_waysToCoverDistanceRecursiveHelper(int dist) { if (dist < 0) { @@ -16,9 +16,9 @@ namespace ways_to_cover_distance } int result = 0; - result += this->waysToCoverDistanceRecursiveHelper(dist - 1); - result += this->waysToCoverDistanceRecursiveHelper(dist - 2); - result += this->waysToCoverDistanceRecursiveHelper(dist - 3); + result += this->_waysToCoverDistanceRecursiveHelper(dist - 1); + result += this->_waysToCoverDistanceRecursiveHelper(dist - 2); + result += this->_waysToCoverDistanceRecursiveHelper(dist - 3); return result; } @@ -26,7 +26,7 @@ namespace ways_to_cover_distance // dynamic programming public member methods. int DynamicProgramming::recursiveWaysToCoverDistance(int dist) { - return this->waysToCoverDistanceRecursiveHelper(dist); + return this->_waysToCoverDistanceRecursiveHelper(dist); } int DynamicProgramming::dpWaysToCoverDistance(int dist) diff --git a/src/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order.cc b/src/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order.cc index 624eba9..f03c200 100644 --- a/src/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order.cc +++ b/src/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order.cc @@ -3,7 +3,7 @@ namespace count_ways_to_reach_nth_stair_include_order { // dynamic programming private member methods. - int DynamicProgramming::recursiveCountWaysToReachNthStairIncludeOrderHelper(int n) + int DynamicProgramming::_recursiveCountWaysHelper(int n) { if (n < 0) { @@ -15,19 +15,19 @@ namespace count_ways_to_reach_nth_stair_include_order } int result = 0; - result += this->recursiveCountWaysToReachNthStairIncludeOrderHelper(n - 1); - result += this->recursiveCountWaysToReachNthStairIncludeOrderHelper(n - 2); + result += this->_recursiveCountWaysHelper(n - 1); + result += this->_recursiveCountWaysHelper(n - 2); return result; } // dynamic programming public member methods. - int DynamicProgramming::recursiveCountWaysToReachNthStairIncludeOrder(int n) + int DynamicProgramming::recursiveCountWays(int n) { - return this->recursiveCountWaysToReachNthStairIncludeOrderHelper(n); + return this->_recursiveCountWaysHelper(n); } - int DynamicProgramming::dpCountWaysToReachNthStairIncludeOrder(int n) + int DynamicProgramming::dpCountWays(int n) { vector dp(n + 1, 0); dp[0] = 1; diff --git a/src/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order.cc b/src/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order.cc index 1fbbb41..b9a56a8 100644 --- a/src/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order.cc +++ b/src/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order.cc @@ -16,7 +16,7 @@ namespace count_ways_to_reach_nth_stair_exclude_order */ // dynamic programming private member methods. - int DynamicProgramming::recursiveCountWaysToReachNthStairExcludeOrderHelper(int n) + int DynamicProgramming::_recursiveCountWaysHelper(int n) { if (n < 0) { @@ -27,16 +27,16 @@ namespace count_ways_to_reach_nth_stair_exclude_order return 1; } - return 1 + this->recursiveCountWaysToReachNthStairExcludeOrderHelper(n - 2); + return 1 + this->_recursiveCountWaysHelper(n - 2); } // dynamic programming public member methods. - int DynamicProgramming::recursiveCountWaysToReachNthStairExcludeOrder(int n) + int DynamicProgramming::recursiveCountWays(int n) { - return this->recursiveCountWaysToReachNthStairExcludeOrderHelper(n); + return this->_recursiveCountWaysHelper(n); } - int DynamicProgramming::dpCountWaysToReachNthStairExcludeOrder(int n) + int DynamicProgramming::dpCountWays(int n) { vector dp(n + 1, 0); dp[0] = 1; diff --git a/src/0004_dynamic_programming/0013_knapsack_problem.cc b/src/0004_dynamic_programming/0013_knapsack_problem.cc index 5d06ec9..bddd50a 100644 --- a/src/0004_dynamic_programming/0013_knapsack_problem.cc +++ b/src/0004_dynamic_programming/0013_knapsack_problem.cc @@ -3,7 +3,7 @@ namespace knapsack_problem { // dynamic programming private member methods. - int DynamicProgramming::knapsackRecursiveHelper(int capacity, vector& weight, vector& profit, int numberOfItems) + int DynamicProgramming::_recursiveKnapsackHelper(int capacity, vector& weight, vector& profit, int numberOfItems) { if (capacity <= 0 || numberOfItems == 0) { @@ -15,10 +15,10 @@ namespace knapsack_problem // pick the current item only if does not exceed the capacity. if (weight[numberOfItems - 1] <= capacity) { - pickCurrentItem = profit[numberOfItems - 1] + this->knapsackRecursiveHelper(capacity - weight[numberOfItems - 1], weight, profit, numberOfItems - 1); + pickCurrentItem = profit[numberOfItems - 1] + this->_recursiveKnapsackHelper(capacity - weight[numberOfItems - 1], weight, profit, numberOfItems - 1); } - int dropCurrentItem = this->knapsackRecursiveHelper(capacity, weight, profit, numberOfItems - 1); + int dropCurrentItem = this->_recursiveKnapsackHelper(capacity, weight, profit, numberOfItems - 1); return max(pickCurrentItem, dropCurrentItem); } @@ -27,7 +27,7 @@ namespace knapsack_problem int DynamicProgramming::recursiveKnapsack(int capacity, vector weight, vector profit) { size_t totalNumberOfItems = weight.size(); - return this->knapsackRecursiveHelper(capacity, weight, profit, totalNumberOfItems); + return this->_recursiveKnapsackHelper(capacity, weight, profit, totalNumberOfItems); } int DynamicProgramming::dpKnapsack(int capacity, vector weight, vector profit) diff --git a/src/0004_dynamic_programming/0014_subset_sum_problem.cc b/src/0004_dynamic_programming/0014_subset_sum_problem.cc index f5694ec..f1571f7 100644 --- a/src/0004_dynamic_programming/0014_subset_sum_problem.cc +++ b/src/0004_dynamic_programming/0014_subset_sum_problem.cc @@ -3,7 +3,7 @@ namespace subset_sum_problem { // dynamic programming private member methods. - bool DynamicProgramming::subsetSumRecursiveHelper(vector& nums, int sum, int numberOfElements) + bool DynamicProgramming::_recursiveSubsetSumHelper(vector& nums, int sum, int numberOfElements) { // Base case. // if the sum is 0, we found a subset with a given sum. @@ -22,21 +22,21 @@ namespace subset_sum_problem // when the current element is greater than the sum, we skip it, as all elemeents are non-negative. if (nums[numberOfElements - 1] > sum) { - return this->subsetSumRecursiveHelper(nums, sum, numberOfElements - 1); + return this->_recursiveSubsetSumHelper(nums, sum, numberOfElements - 1); } // when the current element is equal to or less than the sum, we have two choices. // 1. include the current element in the subset and the sum is reduced by the current element value and also the number of elements is reducded by 1. // 2. exclude the current element from the subset and the sum remains the same but the number of eleements is reduced by 1. // if either of these two choices return true, we return true. - return this->subsetSumRecursiveHelper(nums, sum - nums[numberOfElements - 1], numberOfElements - 1) || this->subsetSumRecursiveHelper(nums, sum, numberOfElements - 1); + return this->_recursiveSubsetSumHelper(nums, sum - nums[numberOfElements - 1], numberOfElements - 1) || this->_recursiveSubsetSumHelper(nums, sum, numberOfElements - 1); } // dynamic programming public member methods. bool DynamicProgramming::recursiveSubsetSum(vector nums, int sum) { int numberOfElements = nums.size(); - return this->subsetSumRecursiveHelper(nums, sum, numberOfElements); + return this->_recursiveSubsetSumHelper(nums, sum, numberOfElements); } bool DynamicProgramming::dpIsSubsetSum(vector nums, int sum) diff --git a/src/0004_dynamic_programming/0015_count_subsets_for_sum.cc b/src/0004_dynamic_programming/0015_count_subsets_for_sum.cc index 6ec8743..8d122e5 100644 --- a/src/0004_dynamic_programming/0015_count_subsets_for_sum.cc +++ b/src/0004_dynamic_programming/0015_count_subsets_for_sum.cc @@ -3,7 +3,7 @@ namespace count_subsets_for_sum { // dynamic programming private member methods - int DynamicProgramming::recursiveCountSubsetsHelper(vector& nums, int targetSum, int currentSum, int index) + int DynamicProgramming::_recursiveCountSubsetsHelper(vector& nums, int targetSum, int currentSum, int index) { int noOfElements = nums.size(); if (index == noOfElements) @@ -11,12 +11,12 @@ namespace count_subsets_for_sum return (targetSum == currentSum); } - int exclude = this->recursiveCountSubsetsHelper(nums, targetSum, currentSum, index + 1); + int exclude = this->_recursiveCountSubsetsHelper(nums, targetSum, currentSum, index + 1); int include = 0; if ((nums[index] + currentSum) <= targetSum) { - include = this->recursiveCountSubsetsHelper(nums, targetSum, currentSum + nums[index], index + 1); + include = this->_recursiveCountSubsetsHelper(nums, targetSum, currentSum + nums[index], index + 1); } return (exclude + include); @@ -25,7 +25,7 @@ namespace count_subsets_for_sum // dynamic programming public member methods int DynamicProgramming::recursiveCountSubsets(vector nums, int sum) { - return this->recursiveCountSubsetsHelper(nums, sum, 0, 0); + return this->_recursiveCountSubsetsHelper(nums, sum, 0, 0); } int DynamicProgramming::dpCountSubsets(vector nums, int sum) diff --git a/src/0004_dynamic_programming/0016_partition_equal_subset_sum.cc b/src/0004_dynamic_programming/0016_partition_equal_subset_sum.cc index 8ad0f8c..8b41f82 100644 --- a/src/0004_dynamic_programming/0016_partition_equal_subset_sum.cc +++ b/src/0004_dynamic_programming/0016_partition_equal_subset_sum.cc @@ -2,7 +2,7 @@ namespace partition_equal_subset_sum { - bool DynamicProgramming::recursivePartitionEqualSubsetsHelper(vector& nums, int targetSum, int numberOfElements) + bool DynamicProgramming::_recursivePartitionEqualSubsetsHelper(vector& nums, int targetSum, int numberOfElements) { if (targetSum == 0) { @@ -16,10 +16,10 @@ namespace partition_equal_subset_sum if (nums[numberOfElements - 1] > targetSum) { - return this->recursivePartitionEqualSubsetsHelper(nums, targetSum, numberOfElements - 1); + return this->_recursivePartitionEqualSubsetsHelper(nums, targetSum, numberOfElements - 1); } - return (this->recursivePartitionEqualSubsetsHelper(nums, targetSum - nums[numberOfElements - 1], numberOfElements - 1) || this->recursivePartitionEqualSubsetsHelper(nums, targetSum, numberOfElements - 1)); + return (this->_recursivePartitionEqualSubsetsHelper(nums, targetSum - nums[numberOfElements - 1], numberOfElements - 1) || this->_recursivePartitionEqualSubsetsHelper(nums, targetSum, numberOfElements - 1)); } bool DynamicProgramming::recursivePartitionEqualSubsets(vector nums) @@ -33,7 +33,7 @@ namespace partition_equal_subset_sum } int numberOfElements = nums.size(); - return this->recursivePartitionEqualSubsetsHelper(nums, targetSum / 2, numberOfElements); + return this->_recursivePartitionEqualSubsetsHelper(nums, targetSum / 2, numberOfElements); } bool DynamicProgramming::dpPartitionEqualSubsets(vector nums) diff --git a/src/0004_dynamic_programming/0017_target_sum.cc b/src/0004_dynamic_programming/0017_target_sum.cc index d92c8a6..121c153 100644 --- a/src/0004_dynamic_programming/0017_target_sum.cc +++ b/src/0004_dynamic_programming/0017_target_sum.cc @@ -2,7 +2,7 @@ namespace target_sum { - int DynamicProgramming::recursiveFindTotalWaysHelper(vector& nums, int currentSum, int targetSum, int index) + int DynamicProgramming::_recursiveFindTotalWaysHelper(vector& nums, int currentSum, int targetSum, int index) { // Base case if (currentSum == targetSum && index == nums.size()) @@ -19,14 +19,14 @@ namespace target_sum // 1. add the current element to currentSum // 2. subtract the current element from currentSum return ( - this->recursiveFindTotalWaysHelper(nums, currentSum + nums[index], targetSum, index + 1) + this->_recursiveFindTotalWaysHelper(nums, currentSum + nums[index], targetSum, index + 1) + - this->recursiveFindTotalWaysHelper(nums, currentSum - nums[index], targetSum, index + 1)); + this->_recursiveFindTotalWaysHelper(nums, currentSum - nums[index], targetSum, index + 1)); } int DynamicProgramming::recursiveFindTotalWays(vector nums, int target) { - return this->recursiveFindTotalWaysHelper(nums, 0, target, 0); + return this->_recursiveFindTotalWaysHelper(nums, 0, target, 0); } int DynamicProgramming::dpFindTotalWays(vector nums, int target) diff --git a/src/0004_dynamic_programming/CMakeLists.txt b/src/0004_dynamic_programming/CMakeLists.txt index 50fd0de..fa18701 100644 --- a/src/0004_dynamic_programming/CMakeLists.txt +++ b/src/0004_dynamic_programming/CMakeLists.txt @@ -21,8 +21,8 @@ set(0005DYNAMICPROGRAMMING_SOURCES ) # Create a library target -add_library(0005DYNAMICPROGRAMMING ${0005DYNAMICPROGRAMMING_SOURCES}) +add_library(0005_DynamicProgramming ${0005DYNAMICPROGRAMMING_SOURCES}) -target_include_directories(0005DYNAMICPROGRAMMING PUBLIC +target_include_directories(0005_DynamicProgramming PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/headers ) \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0004_minimum_cost_climbing_stairs.h b/src/0004_dynamic_programming/headers/0004_minimum_cost_climbing_stairs.h index bc01c46..7ed9816 100644 --- a/src/0004_dynamic_programming/headers/0004_minimum_cost_climbing_stairs.h +++ b/src/0004_dynamic_programming/headers/0004_minimum_cost_climbing_stairs.h @@ -17,7 +17,7 @@ namespace minimum_cost_climbing_stairs class DynamicProgramming { private: - int minCostRecursive(size_t step, vector& cost); + int _minCostRecursive(size_t step, vector& cost); public: int recursiveMinimumCostClimbingStairs(vector& cost); int dpMinimumCostClimbingStairs(vector& cost); diff --git a/src/0004_dynamic_programming/headers/0005_house_robber1.h b/src/0004_dynamic_programming/headers/0005_house_robber1.h index f4e5e91..1dddd2e 100644 --- a/src/0004_dynamic_programming/headers/0005_house_robber1.h +++ b/src/0004_dynamic_programming/headers/0005_house_robber1.h @@ -17,7 +17,7 @@ namespace house_robber1 class DynamicProgramming { private: - int maxLootRecursive(size_t house, vector& houseValues); + int _maxLootRecursive(size_t house, vector& houseValues); public: int recursiveMaximumLoot(vector& houseValues); int dpMaximumLoot(vector& houseValues); diff --git a/src/0004_dynamic_programming/headers/0006_house_robber2.h b/src/0004_dynamic_programming/headers/0006_house_robber2.h index 646146e..3f7afb1 100644 --- a/src/0004_dynamic_programming/headers/0006_house_robber2.h +++ b/src/0004_dynamic_programming/headers/0006_house_robber2.h @@ -19,8 +19,8 @@ namespace house_robber2 class DynamicProgramming { private: - int maxLootRecursive(size_t house, vector& houseValues); - int maxLootDp(size_t firstHouse, size_t lastHouse, vector& houseValues); + int _maxLootRecursive(size_t house, vector& houseValues); + int _maxLootDp(size_t firstHouse, size_t lastHouse, vector& houseValues); public: int recursiveMaximumLoot(vector& houseValues); int dpMaximumLoot(vector& houseValues); diff --git a/src/0004_dynamic_programming/headers/0007_decode_ways.h b/src/0004_dynamic_programming/headers/0007_decode_ways.h index 6b6549d..654fe94 100644 --- a/src/0004_dynamic_programming/headers/0007_decode_ways.h +++ b/src/0004_dynamic_programming/headers/0007_decode_ways.h @@ -24,7 +24,7 @@ namespace decode_ways class DynamicProgramming { private: - int countWaysRecursiveHelper(string& digits, size_t index); + int _countWaysRecursiveHelper(string& digits, size_t index); public: int recursiveCountWays(string digits); int dpCountways(string digits); diff --git a/src/0004_dynamic_programming/headers/0008_tiling_problem.h b/src/0004_dynamic_programming/headers/0008_tiling_problem.h index ab541b1..95be45b 100644 --- a/src/0004_dynamic_programming/headers/0008_tiling_problem.h +++ b/src/0004_dynamic_programming/headers/0008_tiling_problem.h @@ -17,7 +17,7 @@ namespace tiling_problem class DynamicProgramming { private: - int numberOfWaysRecursiveHelper(int n); + int _numberOfWaysRecursiveHelper(int n); public: int recursiveNumberOfWays(int n); int dpNumberOfWays(int n); diff --git a/src/0004_dynamic_programming/headers/0009_friends_pairing_problem.h b/src/0004_dynamic_programming/headers/0009_friends_pairing_problem.h index 4d9949e..375c908 100644 --- a/src/0004_dynamic_programming/headers/0009_friends_pairing_problem.h +++ b/src/0004_dynamic_programming/headers/0009_friends_pairing_problem.h @@ -38,7 +38,7 @@ namespace friends_pairing_problem class DynamicProgramming { private: - int countFriendsPairingsRecursiveHelper(int n); + int _countFriendsPairingsRecursiveHelper(int n); public: int recursiveCountFriendsPairings(int n); int dpCountFriendsPairings(int n); diff --git a/src/0004_dynamic_programming/headers/0010_ways_to_cover_distance.h b/src/0004_dynamic_programming/headers/0010_ways_to_cover_distance.h index 4d68621..ab0f714 100644 --- a/src/0004_dynamic_programming/headers/0010_ways_to_cover_distance.h +++ b/src/0004_dynamic_programming/headers/0010_ways_to_cover_distance.h @@ -39,7 +39,7 @@ namespace ways_to_cover_distance class DynamicProgramming { private: - int waysToCoverDistanceRecursiveHelper(int dist); + int _waysToCoverDistanceRecursiveHelper(int dist); public: int recursiveWaysToCoverDistance(int dist); int dpWaysToCoverDistance(int dist); diff --git a/src/0004_dynamic_programming/headers/0011_count_ways_to_reach_nth_stair_include_order.h b/src/0004_dynamic_programming/headers/0011_count_ways_to_reach_nth_stair_include_order.h index 2101931..e43c415 100644 --- a/src/0004_dynamic_programming/headers/0011_count_ways_to_reach_nth_stair_include_order.h +++ b/src/0004_dynamic_programming/headers/0011_count_ways_to_reach_nth_stair_include_order.h @@ -34,9 +34,9 @@ namespace count_ways_to_reach_nth_stair_include_order class DynamicProgramming { private: - int recursiveCountWaysToReachNthStairIncludeOrderHelper(int n); + int _recursiveCountWaysHelper(int n); public: - int recursiveCountWaysToReachNthStairIncludeOrder(int n); - int dpCountWaysToReachNthStairIncludeOrder(int n); + int recursiveCountWays(int n); + int dpCountWays(int n); }; } \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0012_count_ways_to_reach_nth_stair_exclude_order.h b/src/0004_dynamic_programming/headers/0012_count_ways_to_reach_nth_stair_exclude_order.h index c2f0a2a..80e7acc 100644 --- a/src/0004_dynamic_programming/headers/0012_count_ways_to_reach_nth_stair_exclude_order.h +++ b/src/0004_dynamic_programming/headers/0012_count_ways_to_reach_nth_stair_exclude_order.h @@ -36,9 +36,9 @@ namespace count_ways_to_reach_nth_stair_exclude_order class DynamicProgramming { private: - int recursiveCountWaysToReachNthStairExcludeOrderHelper(int n); + int _recursiveCountWaysHelper(int n); public: - int recursiveCountWaysToReachNthStairExcludeOrder(int n); - int dpCountWaysToReachNthStairExcludeOrder(int n); + int recursiveCountWays(int n); + int dpCountWays(int n); }; } \ No newline at end of file diff --git a/src/0004_dynamic_programming/headers/0013_knapsack_problem.h b/src/0004_dynamic_programming/headers/0013_knapsack_problem.h index d882423..129af61 100644 --- a/src/0004_dynamic_programming/headers/0013_knapsack_problem.h +++ b/src/0004_dynamic_programming/headers/0013_knapsack_problem.h @@ -25,7 +25,7 @@ namespace knapsack_problem class DynamicProgramming { private: - int knapsackRecursiveHelper(int capacity, vector& weight, vector& profit, int numberOfItems); + int _recursiveKnapsackHelper(int capacity, vector& weight, vector& profit, int numberOfItems); public: int recursiveKnapsack(int capacity, vector weight, vector profit); int dpKnapsack(int capacity, vector weight, vector profit); diff --git a/src/0004_dynamic_programming/headers/0014_subset_sum_problem.h b/src/0004_dynamic_programming/headers/0014_subset_sum_problem.h index 37b1784..2dcbcf9 100644 --- a/src/0004_dynamic_programming/headers/0014_subset_sum_problem.h +++ b/src/0004_dynamic_programming/headers/0014_subset_sum_problem.h @@ -26,7 +26,7 @@ namespace subset_sum_problem class DynamicProgramming { private: - bool subsetSumRecursiveHelper(vector& nums, int sum, int numberOfElements); + bool _recursiveSubsetSumHelper(vector& nums, int sum, int numberOfElements); public: bool recursiveSubsetSum(vector nums, int sum); bool dpIsSubsetSum(vector nums, int sum); diff --git a/src/0004_dynamic_programming/headers/0015_count_subsets_for_sum.h b/src/0004_dynamic_programming/headers/0015_count_subsets_for_sum.h index b3e42cd..c092d2c 100644 --- a/src/0004_dynamic_programming/headers/0015_count_subsets_for_sum.h +++ b/src/0004_dynamic_programming/headers/0015_count_subsets_for_sum.h @@ -26,7 +26,7 @@ namespace count_subsets_for_sum class DynamicProgramming { private: - int recursiveCountSubsetsHelper(vector& nums, int targetSum, int currentSum, int index); + int _recursiveCountSubsetsHelper(vector& nums, int targetSum, int currentSum, int index); public: int recursiveCountSubsets(vector nums, int sum); int dpCountSubsets(vector nums, int sum); diff --git a/src/0004_dynamic_programming/headers/0016_partition_equal_subset_sum.h b/src/0004_dynamic_programming/headers/0016_partition_equal_subset_sum.h index 6fb9635..f55fec2 100644 --- a/src/0004_dynamic_programming/headers/0016_partition_equal_subset_sum.h +++ b/src/0004_dynamic_programming/headers/0016_partition_equal_subset_sum.h @@ -28,7 +28,7 @@ namespace partition_equal_subset_sum class DynamicProgramming { private: - bool recursivePartitionEqualSubsetsHelper(vector& nums, int targetSum, int numberOfElements); + bool _recursivePartitionEqualSubsetsHelper(vector& nums, int targetSum, int numberOfElements); public: bool recursivePartitionEqualSubsets(vector nums); bool dpPartitionEqualSubsets(vector nums); diff --git a/src/0004_dynamic_programming/headers/0017_target_sum.h b/src/0004_dynamic_programming/headers/0017_target_sum.h index 89e1853..6830243 100644 --- a/src/0004_dynamic_programming/headers/0017_target_sum.h +++ b/src/0004_dynamic_programming/headers/0017_target_sum.h @@ -36,8 +36,7 @@ namespace target_sum class DynamicProgramming { private: - int recursiveFindTotalWaysHelper(vector& nums, int currentSum, int targetSum, int index); - int dpFindTotalWays(); + int _recursiveFindTotalWaysHelper(vector& nums, int currentSum, int targetSum, int index); public: int recursiveFindTotalWays(vector nums, int target); int dpFindTotalWays(vector nums, int target); diff --git a/tests/0001_basics/CMakeLists.txt b/tests/0001_basics/CMakeLists.txt index 71a64c0..320fb67 100644 --- a/tests/0001_basics/CMakeLists.txt +++ b/tests/0001_basics/CMakeLists.txt @@ -13,20 +13,20 @@ FetchContent_MakeAvailable(googletest) enable_testing() add_executable( - 0001BasicsTests + 0001_BasicsTests node_test.cc ) target_link_libraries( - 0001BasicsTests + 0001_BasicsTests GTest::gtest_main - 0001BASICS + 0001_Basics ) # Add .clang-tidy configuration to this library. if(CLANG_TIDY_EXE) - set_target_properties(0001BASICS PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") + set_target_properties(0001_Basics PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") endif() include(GoogleTest) -gtest_discover_tests(0001BasicsTests DISCOVERY_TIMEOUT 30) \ No newline at end of file +gtest_discover_tests(0001_BasicsTests DISCOVERY_TIMEOUT 30) \ No newline at end of file diff --git a/tests/0003_graph/CMakeLists.txt b/tests/0003_graph/CMakeLists.txt index a40f049..da86fde 100644 --- a/tests/0003_graph/CMakeLists.txt +++ b/tests/0003_graph/CMakeLists.txt @@ -13,7 +13,7 @@ FetchContent_MakeAvailable(googletest) enable_testing() add_executable( - 0003GraphTests + 0003_GraphTests 0001_breadth_first_search_test.cc 0002_depth_first_search_test.cc @@ -37,15 +37,15 @@ add_executable( ) target_link_libraries( - 0003GraphTests + 0003_GraphTests GTest::gtest_main - 0003GRAPH + 0003_Graph ) # Add .clang-tidy configuration to this library. if(CLANG_TIDY_EXE) - set_target_properties(0003GRAPH PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") + set_target_properties(0003_Graph PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") endif() include(GoogleTest) -gtest_discover_tests(0003GraphTests DISCOVERY_TIMEOUT 30) \ No newline at end of file +gtest_discover_tests(0003_GraphTests DISCOVERY_TIMEOUT 30) \ No newline at end of file diff --git a/tests/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order_test.cc b/tests/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order_test.cc index 239c05c..0ad3a15 100644 --- a/tests/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order_test.cc +++ b/tests/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order_test.cc @@ -11,7 +11,7 @@ namespace count_ways_to_reach_nth_stair_include_order int expectedNumberOfWays = 5; // act - int actualNumberOfWays = dp.recursiveCountWaysToReachNthStairIncludeOrder(n); + int actualNumberOfWays = dp.recursiveCountWays(n); // assert ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); @@ -25,7 +25,7 @@ namespace count_ways_to_reach_nth_stair_include_order int expectedNumberOfWays = 5; // act - int actualNumberOfWays = dp.dpCountWaysToReachNthStairIncludeOrder(n); + int actualNumberOfWays = dp.dpCountWays(n); // assert ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); diff --git a/tests/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order_test.cc b/tests/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order_test.cc index df1f344..d14f280 100644 --- a/tests/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order_test.cc +++ b/tests/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order_test.cc @@ -11,7 +11,7 @@ namespace count_ways_to_reach_nth_stair_exclude_order int expectedNumberOfWays = 3; // act - int actualNumberOfWays = dp.recursiveCountWaysToReachNthStairExcludeOrder(n); + int actualNumberOfWays = dp.recursiveCountWays(n); // assert ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); @@ -25,7 +25,7 @@ namespace count_ways_to_reach_nth_stair_exclude_order int expectedNumberOfWays = 3; // act - int actualNumberOfWays = dp.dpCountWaysToReachNthStairExcludeOrder(n); + int actualNumberOfWays = dp.dpCountWays(n); // assert ASSERT_EQ(expectedNumberOfWays, actualNumberOfWays); diff --git a/tests/0004_dynamic_programming/CMakeLists.txt b/tests/0004_dynamic_programming/CMakeLists.txt index 51714d5..a655df7 100644 --- a/tests/0004_dynamic_programming/CMakeLists.txt +++ b/tests/0004_dynamic_programming/CMakeLists.txt @@ -13,7 +13,7 @@ FetchContent_MakeAvailable(googletest) enable_testing() add_executable( - 0005DynamicProgrammingTests + 0005_DynamicProgrammingTests 0001_fibonacci_number_test.cc 0002_tribonacci_number_test.cc @@ -36,15 +36,15 @@ add_executable( ) target_link_libraries( - 0005DynamicProgrammingTests + 0005_DynamicProgrammingTests GTest::gtest_main - 0005DYNAMICPROGRAMMING + 0005_DynamicProgramming ) # Add .clang-tidy configuration to this library. if(CLANG_TIDY_EXE) - set_target_properties(0005DYNAMICPROGRAMMING PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") + set_target_properties(0005_DynamicProgramming PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}") endif() include(GoogleTest) -gtest_discover_tests(0005DynamicProgrammingTests DISCOVERY_TIMEOUT 30) \ No newline at end of file +gtest_discover_tests(0005_DynamicProgrammingTests DISCOVERY_TIMEOUT 30) \ No newline at end of file From ebb1f81bedf19e244730fa5fa598214c0b9d4fb0 Mon Sep 17 00:00:00 2001 From: Debashis Nandi Date: Mon, 15 Jun 2026 02:09:27 +0530 Subject: [PATCH 11/13] fix: test suite names updated --- .../0002_tree/0001_binary_search_tree_test.cc | 12 ++++++------ .../0001_breadth_first_search_test.cc | 4 ++-- .../0003_graph/0002_depth_first_search_test.cc | 18 +++++++++--------- ...mum_spanning_tree_kruskal_algorithm_test.cc | 2 +- ...inimum_spanning_tree_prim_algorithm_test.cc | 2 +- 5 files changed, 19 insertions(+), 19 deletions(-) diff --git a/tests/0002_tree/0001_binary_search_tree_test.cc b/tests/0002_tree/0001_binary_search_tree_test.cc index 4e08fa9..a4c32ff 100644 --- a/tests/0002_tree/0001_binary_search_tree_test.cc +++ b/tests/0002_tree/0001_binary_search_tree_test.cc @@ -7,7 +7,7 @@ namespace binary_search_tree { UnitTestHelper unitTestHelper; - TEST(bSTInsertData, recursiveInorderTest) + TEST(binarySearchTree, recursiveInorderTest) { BinarySearchTree bst; bst.insertNode(50); @@ -21,7 +21,7 @@ namespace binary_search_tree EXPECT_EQ(actualResult, expectedResult); } - TEST(bSTInsertData, recursivePreorderTest) + TEST(binarySearchTree, recursivePreorderTest) { BinarySearchTree bst; bst.insertNode(50); @@ -34,7 +34,7 @@ namespace binary_search_tree EXPECT_EQ(actualResult, expectedResult); } - TEST(bSTInsertData, recursivePostorderTest) + TEST(binarySearchTree, recursivePostorderTest) { BinarySearchTree bst; bst.insertNode(50); @@ -47,7 +47,7 @@ namespace binary_search_tree EXPECT_EQ(actualResult, expectedResult); } - TEST(bSTInsertData, morrisInorderTest) + TEST(binarySearchTree, morrisInorderTest) { BinarySearchTree bst; bst.insertNode(50); @@ -61,7 +61,7 @@ namespace binary_search_tree EXPECT_EQ(actualResult, expectedResult); } - TEST(bSTInsertData, morrisPreorderTest) + TEST(binarySearchTree, morrisPreorderTest) { BinarySearchTree bst; bst.insertNode(50); @@ -75,7 +75,7 @@ namespace binary_search_tree EXPECT_EQ(actualResult, expectedResult); } - TEST(bSTInsertData, morrisPostorderTest) + TEST(binarySearchTree, morrisPostorderTest) { BinarySearchTree bst; bst.insertNode(50); diff --git a/tests/0003_graph/0001_breadth_first_search_test.cc b/tests/0003_graph/0001_breadth_first_search_test.cc index b6fd573..b46ffc4 100644 --- a/tests/0003_graph/0001_breadth_first_search_test.cc +++ b/tests/0003_graph/0001_breadth_first_search_test.cc @@ -8,7 +8,7 @@ namespace breadth_first_search UnitTestHelper unitTestHelper; - TEST(bFSTesting, showBFSResultTest01) + TEST(breadthFirstSearch, showBFSResultTest01) { Graph graph; @@ -30,7 +30,7 @@ namespace breadth_first_search EXPECT_EQ(actualResult, expectedResult); } - TEST(bFSTesting, showBFSResultTest02) + TEST(breadthFirstSearch, showBFSResultTest02) { Graph graph; diff --git a/tests/0003_graph/0002_depth_first_search_test.cc b/tests/0003_graph/0002_depth_first_search_test.cc index 11b5c62..f950f0b 100644 --- a/tests/0003_graph/0002_depth_first_search_test.cc +++ b/tests/0003_graph/0002_depth_first_search_test.cc @@ -6,7 +6,7 @@ namespace depth_first_search { UnitTestHelper unitTestHelper; - TEST(dFSTesting, showDFSResultTest01) + TEST(depthFirstSearch, showDFSResultTest01) { Graph graph; @@ -27,7 +27,7 @@ namespace depth_first_search } - TEST(dFSTesting, showDFSResultTest_SingleVertex) + TEST(depthFirstSearch, showDFSResultTestSingleVertex) { Graph graph; @@ -40,7 +40,7 @@ namespace depth_first_search EXPECT_EQ(actualResult, expectedResult); } - TEST(dFSTesting, showDFSResultTest_DisconnectedGraph) + TEST(depthFirstSearch, showDFSResultTestDisconnectedGraph) { Graph graph; @@ -54,7 +54,7 @@ namespace depth_first_search EXPECT_EQ(actualResult, expectedResult); } - TEST(dFSTesting, showDFSResultTest_CyclicGraph) + TEST(depthFirstSearch, showDFSResultTestCyclicGraph) { Graph graph; @@ -69,7 +69,7 @@ namespace depth_first_search EXPECT_EQ(actualResult, expectedResult); } - TEST(dFSTesting, showDFSResultTest_LargeGraph) + TEST(depthFirstSearch, showDFSResultTestLargeGraph) { Graph graph; @@ -97,7 +97,7 @@ namespace depth_first_search EXPECT_EQ(actualResult, expectedResult); } - TEST(dFSTesting, showDFSResultTest_NoEdges) + TEST(depthFirstSearch, showDFSResultTestNoEdges) { Graph graph; @@ -113,7 +113,7 @@ namespace depth_first_search EXPECT_EQ(actualResult, expectedResult); } - TEST(dFSTesting, showDFSResultTest_CyclicGraphWithBackEdges) + TEST(depthFirstSearch, showDFSResultTest_CyclicGraphWithBackEdges) { Graph graph; @@ -130,7 +130,7 @@ namespace depth_first_search EXPECT_EQ(actualResult, expectedResult); } - TEST(dFSTesting, showDFSResultTest_DenseGraph) + TEST(depthFirstSearch, showDFSResultTestDenseGraph) { Graph graph; @@ -155,7 +155,7 @@ namespace depth_first_search EXPECT_EQ(actualResult, expectedResult); } - TEST(dFSTesting, showDFSResultTest_SelfLoopsAndParallelEdges) + TEST(depthFirstSearch, showDFSResultTestSelfLoopsAndParallelEdges) { Graph graph; diff --git a/tests/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm_test.cc b/tests/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm_test.cc index 4672fc0..ff8fec3 100644 --- a/tests/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm_test.cc +++ b/tests/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm_test.cc @@ -6,7 +6,7 @@ namespace minimum_spanning_tree_kruskal_algorithm { UnitTestHelper unitTestHelper; - TEST(MST, kruskal) + TEST(minimumSpanningTreeKruskal, getMinimumSpanningTreeKruskal) { Graph graph; diff --git a/tests/0003_graph/0008_minimum_spanning_tree_prim_algorithm_test.cc b/tests/0003_graph/0008_minimum_spanning_tree_prim_algorithm_test.cc index 145b07d..d479f81 100644 --- a/tests/0003_graph/0008_minimum_spanning_tree_prim_algorithm_test.cc +++ b/tests/0003_graph/0008_minimum_spanning_tree_prim_algorithm_test.cc @@ -6,7 +6,7 @@ namespace minimum_spanning_tree_prim_algorithm { UnitTestHelper unitTestHelper; - TEST(MST, prim) + TEST(minimumSpanningTreePrim, getMinimumSpanningTreePrim) { Graph graph; From a4c2336d718e5c825ccb3e8461ebe7faa10cef8f Mon Sep 17 00:00:00 2001 From: Debashis Nandi Date: Mon, 15 Jun 2026 02:18:05 +0530 Subject: [PATCH 12/13] feat: namespaces updated to fully qualified namespaces --- CMakeLists.txt | 2 +- src/0002_tree/0001_binary_search_tree.cc | 2 +- src/0002_tree/headers/0001_binary_search_tree.h | 2 +- src/0003_graph/0001_breadth_first_search.cc | 2 +- src/0003_graph/0002_depth_first_search.cc | 2 +- src/0003_graph/0003_topological_sort.cc | 2 +- src/0003_graph/0004_strongly_connected_components.cc | 2 +- src/0003_graph/0005_hamiltonian_path_and_cycle.cc | 2 +- src/0003_graph/0006_eulerian_path_and_circuit.cc | 2 +- .../0007_minimum_spanning_tree_kruskal_algorithm.cc | 2 +- src/0003_graph/0008_minimum_spanning_tree_prim_algorithm.cc | 2 +- .../0009_single_source_shortest_path_bellman_ford.cc | 2 +- src/0003_graph/0010_directed_acyclic_graph_shortest_path.cc | 2 +- src/0003_graph/0011_single_source_shortest_path_dijkstra.cc | 2 +- src/0003_graph/0012_difference_constraints_shortest_paths.cc | 2 +- .../0013_all_pairs_shortest_paths_floyd_warshall.cc | 2 +- src/0003_graph/0014_all_pairs_shortest_paths_johnson.cc | 2 +- src/0003_graph/0015_maximum_flow_ford_fulkerson.cc | 2 +- src/0003_graph/0016_maximum_flow_edmonds_karp.cc | 2 +- src/0003_graph/0017_maximum_bipartite_matching.cc | 2 +- .../0018_maximum_flow_goldberg_generic_push_relabel.cc | 2 +- src/0003_graph/0019_maximum_flow_relabel_to_front.cc | 2 +- src/0003_graph/headers/0001_breadth_first_search.h | 2 +- src/0003_graph/headers/0002_depth_first_search.h | 2 +- src/0003_graph/headers/0003_topological_sort.h | 2 +- src/0003_graph/headers/0004_strongly_connected_components.h | 2 +- src/0003_graph/headers/0005_hamiltonian_path_and_cycle.h | 2 +- src/0003_graph/headers/0006_eulerian_path_and_circuit.h | 2 +- .../headers/0007_minimum_spanning_tree_kruskal_algorithm.h | 2 +- .../headers/0008_minimum_spanning_tree_prim_algorithm.h | 2 +- .../headers/0009_single_source_shortest_path_bellman_ford.h | 2 +- .../headers/0010_directed_acyclic_graph_shortest_path.h | 2 +- .../headers/0011_single_source_shortest_path_dijkstra.h | 2 +- .../headers/0012_difference_constraints_shortest_paths.h | 2 +- .../headers/0013_all_pairs_shortest_paths_floyd_warshall.h | 2 +- .../headers/0014_all_pairs_shortest_paths_johnson.h | 2 +- src/0003_graph/headers/0015_maximum_flow_ford_fulkerson.h | 2 +- src/0003_graph/headers/0016_maximum_flow_edmonds_karp.h | 2 +- src/0003_graph/headers/0017_maximum_bipartite_matching.h | 2 +- .../headers/0018_maximum_flow_goldberg_generic_push_relabel.h | 2 +- src/0003_graph/headers/0019_maximum_flow_relabel_to_front.h | 2 +- src/0004_dynamic_programming/0001_fibonacci_number.cc | 2 +- src/0004_dynamic_programming/0002_tribonacci_number.cc | 2 +- src/0004_dynamic_programming/0003_climbing_stairs.cc | 2 +- .../0004_minimum_cost_climbing_stairs.cc | 2 +- src/0004_dynamic_programming/0005_house_robber1.cc | 2 +- src/0004_dynamic_programming/0006_house_robber2.cc | 2 +- src/0004_dynamic_programming/0007_decode_ways.cc | 2 +- src/0004_dynamic_programming/0008_tiling_problem.cc | 2 +- src/0004_dynamic_programming/0009_friends_pairing_problem.cc | 2 +- src/0004_dynamic_programming/0010_ways_to_cover_distance.cc | 2 +- .../0011_count_ways_to_reach_nth_stair_include_order.cc | 2 +- .../0012_count_ways_to_reach_nth_stair_exclude_order.cc | 2 +- src/0004_dynamic_programming/0013_knapsack_problem.cc | 2 +- src/0004_dynamic_programming/0014_subset_sum_problem.cc | 2 +- src/0004_dynamic_programming/0015_count_subsets_for_sum.cc | 2 +- .../0016_partition_equal_subset_sum.cc | 2 +- src/0004_dynamic_programming/0017_target_sum.cc | 2 +- src/0004_dynamic_programming/headers/0001_fibonacci_number.h | 2 +- src/0004_dynamic_programming/headers/0002_tribonacci_number.h | 2 +- src/0004_dynamic_programming/headers/0003_climbing_stairs.h | 2 +- .../headers/0004_minimum_cost_climbing_stairs.h | 2 +- src/0004_dynamic_programming/headers/0005_house_robber1.h | 4 ++-- src/0004_dynamic_programming/headers/0006_house_robber2.h | 2 +- src/0004_dynamic_programming/headers/0007_decode_ways.h | 2 +- src/0004_dynamic_programming/headers/0008_tiling_problem.h | 2 +- .../headers/0009_friends_pairing_problem.h | 2 +- .../headers/0010_ways_to_cover_distance.h | 2 +- .../0011_count_ways_to_reach_nth_stair_include_order.h | 2 +- .../0012_count_ways_to_reach_nth_stair_exclude_order.h | 2 +- src/0004_dynamic_programming/headers/0013_knapsack_problem.h | 2 +- .../headers/0014_subset_sum_problem.h | 2 +- .../headers/0015_count_subsets_for_sum.h | 2 +- .../headers/0016_partition_equal_subset_sum.h | 2 +- src/0004_dynamic_programming/headers/0017_target_sum.h | 2 +- tests/0001_basics/node_test.cc | 2 +- tests/0002_tree/0001_binary_search_tree_test.cc | 2 +- tests/0003_graph/0001_breadth_first_search_test.cc | 2 +- tests/0003_graph/0002_depth_first_search_test.cc | 2 +- tests/0003_graph/0003_topological_sort_test.cc | 2 +- tests/0003_graph/0004_strongly_connected_components_test.cc | 2 +- tests/0003_graph/0005_hamiltonian_path_and_cycle_test.cc | 2 +- tests/0003_graph/0006_eulerian_path_and_circuit_test.cc | 2 +- .../0007_minimum_spanning_tree_kruskal_algorithm_test.cc | 2 +- .../0008_minimum_spanning_tree_prim_algorithm_test.cc | 2 +- .../0009_single_source_shortest_path_bellman_ford_test.cc | 2 +- .../0010_directed_acyclic_graph_shortest_path_test.cc | 2 +- .../0011_single_source_shortest_path_dijkstra_test.cc | 2 +- .../0012_difference_constraints_shortest_paths_test.cc | 2 +- .../0013_all_pairs_shortest_paths_floyd_warshall_test.cc | 2 +- .../0003_graph/0014_all_pairs_shortest_paths_johnson_test.cc | 2 +- tests/0003_graph/0015_maximum_flow_ford_fulkerson_test.cc | 2 +- tests/0003_graph/0016_maximum_flow_edmonds_karp_test.cc | 2 +- tests/0003_graph/0017_maximum_bipartite_matching_test.cc | 2 +- .../0018_maximum_flow_goldberg_generic_push_relabel_test.cc | 2 +- tests/0003_graph/0019_maximum_flow_relabel_to_front_test.cc | 2 +- tests/0004_dynamic_programming/0001_fibonacci_number_test.cc | 2 +- tests/0004_dynamic_programming/0002_tribonacci_number_test.cc | 2 +- tests/0004_dynamic_programming/0003_climbing_stairs_test.cc | 2 +- .../0004_minimum_cost_climbing_stairs_test.cc | 2 +- tests/0004_dynamic_programming/0005_house_robber1_test.cc | 2 +- tests/0004_dynamic_programming/0006_house_robber2_test.cc | 2 +- tests/0004_dynamic_programming/0007_decode_ways_test.cc | 2 +- tests/0004_dynamic_programming/0008_tiling_problem_test.cc | 2 +- .../0009_friends_pairing_problem_test.cc | 2 +- .../0010_ways_to_cover_distance_test.cc | 2 +- .../0011_count_ways_to_reach_nth_stair_include_order_test.cc | 2 +- .../0012_count_ways_to_reach_nth_stair_exclude_order_test.cc | 2 +- tests/0004_dynamic_programming/0013_knapsack_problem_test.cc | 2 +- .../0004_dynamic_programming/0014_subset_sum_problem_test.cc | 2 +- .../0015_count_subsets_for_sum_test.cc | 2 +- .../0016_partition_equal_subset_sum_test.cc | 2 +- tests/0004_dynamic_programming/0017_target_sum_test.cc | 2 +- 113 files changed, 114 insertions(+), 114 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index d919238..bae14b4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,7 +1,7 @@ cmake_minimum_required (VERSION 3.10) project ("datastructures-algorithms") -set(CMAKE_CXX_STANDARD 14) +set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) diff --git a/src/0002_tree/0001_binary_search_tree.cc b/src/0002_tree/0001_binary_search_tree.cc index acd293e..3a9e2fc 100644 --- a/src/0002_tree/0001_binary_search_tree.cc +++ b/src/0002_tree/0001_binary_search_tree.cc @@ -3,7 +3,7 @@ #include using namespace std; -namespace binary_search_tree +namespace dsa::binary_search_tree { Node::Node(int data, Node* parent, Node* left, Node* right) { diff --git a/src/0002_tree/headers/0001_binary_search_tree.h b/src/0002_tree/headers/0001_binary_search_tree.h index 4572b20..abdd87b 100644 --- a/src/0002_tree/headers/0001_binary_search_tree.h +++ b/src/0002_tree/headers/0001_binary_search_tree.h @@ -4,7 +4,7 @@ #include using namespace std; -namespace binary_search_tree +namespace dsa::binary_search_tree { class Node { diff --git a/src/0003_graph/0001_breadth_first_search.cc b/src/0003_graph/0001_breadth_first_search.cc index 14c8b21..20b47ee 100644 --- a/src/0003_graph/0001_breadth_first_search.cc +++ b/src/0003_graph/0001_breadth_first_search.cc @@ -7,7 +7,7 @@ #include using namespace std; -namespace breadth_first_search +namespace dsa::breadth_first_search { Node::Node(int value) { diff --git a/src/0003_graph/0002_depth_first_search.cc b/src/0003_graph/0002_depth_first_search.cc index ce05132..b3f510d 100644 --- a/src/0003_graph/0002_depth_first_search.cc +++ b/src/0003_graph/0002_depth_first_search.cc @@ -4,7 +4,7 @@ #include using namespace std; -namespace depth_first_search +namespace dsa::depth_first_search { Node::Node(int value) { diff --git a/src/0003_graph/0003_topological_sort.cc b/src/0003_graph/0003_topological_sort.cc index e7f21be..bade828 100644 --- a/src/0003_graph/0003_topological_sort.cc +++ b/src/0003_graph/0003_topological_sort.cc @@ -6,7 +6,7 @@ #include using namespace std; -namespace topological_sort +namespace dsa::topological_sort { Node::Node(int value) { diff --git a/src/0003_graph/0004_strongly_connected_components.cc b/src/0003_graph/0004_strongly_connected_components.cc index 0576800..bc45596 100644 --- a/src/0003_graph/0004_strongly_connected_components.cc +++ b/src/0003_graph/0004_strongly_connected_components.cc @@ -4,7 +4,7 @@ #include using namespace std; -namespace strongly_connected_components +namespace dsa::strongly_connected_components { Node::Node(int value) { diff --git a/src/0003_graph/0005_hamiltonian_path_and_cycle.cc b/src/0003_graph/0005_hamiltonian_path_and_cycle.cc index 424c5c0..11eae5d 100644 --- a/src/0003_graph/0005_hamiltonian_path_and_cycle.cc +++ b/src/0003_graph/0005_hamiltonian_path_and_cycle.cc @@ -1,7 +1,7 @@ #include "0005_hamiltonian_path_and_cycle.h" using namespace std; -namespace hamiltonian_path_and_cycle +namespace dsa::hamiltonian_path_and_cycle { Node::Node(int value) { diff --git a/src/0003_graph/0006_eulerian_path_and_circuit.cc b/src/0003_graph/0006_eulerian_path_and_circuit.cc index e4a874f..a08279a 100644 --- a/src/0003_graph/0006_eulerian_path_and_circuit.cc +++ b/src/0003_graph/0006_eulerian_path_and_circuit.cc @@ -3,7 +3,7 @@ #include using namespace std; -namespace eulerian_path_and_circuit +namespace dsa::eulerian_path_and_circuit { Node::Node(int value) { diff --git a/src/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm.cc b/src/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm.cc index dd5a50e..9989a3f 100644 --- a/src/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm.cc +++ b/src/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm.cc @@ -3,7 +3,7 @@ #include using namespace std; -namespace minimum_spanning_tree_kruskal_algorithm +namespace dsa::minimum_spanning_tree_kruskal_algorithm { Node::Node(int data) { diff --git a/src/0003_graph/0008_minimum_spanning_tree_prim_algorithm.cc b/src/0003_graph/0008_minimum_spanning_tree_prim_algorithm.cc index 6267d1c..fbdb94a 100644 --- a/src/0003_graph/0008_minimum_spanning_tree_prim_algorithm.cc +++ b/src/0003_graph/0008_minimum_spanning_tree_prim_algorithm.cc @@ -3,7 +3,7 @@ using namespace std; -namespace minimum_spanning_tree_prim_algorithm +namespace dsa::minimum_spanning_tree_prim_algorithm { Node::Node(int data) { diff --git a/src/0003_graph/0009_single_source_shortest_path_bellman_ford.cc b/src/0003_graph/0009_single_source_shortest_path_bellman_ford.cc index 250d06e..fa2109b 100644 --- a/src/0003_graph/0009_single_source_shortest_path_bellman_ford.cc +++ b/src/0003_graph/0009_single_source_shortest_path_bellman_ford.cc @@ -3,7 +3,7 @@ #include using namespace std; -namespace single_source_shortest_path_bellman_ford +namespace dsa::single_source_shortest_path_bellman_ford { Node::Node(int data) { diff --git a/src/0003_graph/0010_directed_acyclic_graph_shortest_path.cc b/src/0003_graph/0010_directed_acyclic_graph_shortest_path.cc index ee6c49b..e5733fe 100644 --- a/src/0003_graph/0010_directed_acyclic_graph_shortest_path.cc +++ b/src/0003_graph/0010_directed_acyclic_graph_shortest_path.cc @@ -3,7 +3,7 @@ #include using namespace std; -namespace directed_acyclic_graph_shortest_path +namespace dsa::directed_acyclic_graph_shortest_path { Node::Node(int data) { diff --git a/src/0003_graph/0011_single_source_shortest_path_dijkstra.cc b/src/0003_graph/0011_single_source_shortest_path_dijkstra.cc index f582213..ab2c3c9 100644 --- a/src/0003_graph/0011_single_source_shortest_path_dijkstra.cc +++ b/src/0003_graph/0011_single_source_shortest_path_dijkstra.cc @@ -3,7 +3,7 @@ #include using namespace std; -namespace single_source_shortest_path_dijkstra +namespace dsa::single_source_shortest_path_dijkstra { Node::Node(int data) { diff --git a/src/0003_graph/0012_difference_constraints_shortest_paths.cc b/src/0003_graph/0012_difference_constraints_shortest_paths.cc index 4c08f2d..bab6d5f 100644 --- a/src/0003_graph/0012_difference_constraints_shortest_paths.cc +++ b/src/0003_graph/0012_difference_constraints_shortest_paths.cc @@ -2,7 +2,7 @@ #include using namespace std; -namespace difference_constraints_shortest_paths +namespace dsa::difference_constraints_shortest_paths { Node::Node(string data) { diff --git a/src/0003_graph/0013_all_pairs_shortest_paths_floyd_warshall.cc b/src/0003_graph/0013_all_pairs_shortest_paths_floyd_warshall.cc index 91618a8..71e26e9 100644 --- a/src/0003_graph/0013_all_pairs_shortest_paths_floyd_warshall.cc +++ b/src/0003_graph/0013_all_pairs_shortest_paths_floyd_warshall.cc @@ -2,7 +2,7 @@ #include using namespace std; -namespace all_pairs_shortest_paths_floyd_warshall +namespace dsa::all_pairs_shortest_paths_floyd_warshall { // Graph private member methods void Graph::_initializeDistanceAndPredecessors() diff --git a/src/0003_graph/0014_all_pairs_shortest_paths_johnson.cc b/src/0003_graph/0014_all_pairs_shortest_paths_johnson.cc index 4028970..25a92ff 100644 --- a/src/0003_graph/0014_all_pairs_shortest_paths_johnson.cc +++ b/src/0003_graph/0014_all_pairs_shortest_paths_johnson.cc @@ -2,7 +2,7 @@ #include using namespace std; -namespace all_pairs_shortest_paths_johnson +namespace dsa::all_pairs_shortest_paths_johnson { Node::Node(int data) { diff --git a/src/0003_graph/0015_maximum_flow_ford_fulkerson.cc b/src/0003_graph/0015_maximum_flow_ford_fulkerson.cc index 41c0124..90dde88 100644 --- a/src/0003_graph/0015_maximum_flow_ford_fulkerson.cc +++ b/src/0003_graph/0015_maximum_flow_ford_fulkerson.cc @@ -2,7 +2,7 @@ #include using namespace std; -namespace maximum_flow_ford_fulkerson +namespace dsa::maximum_flow_ford_fulkerson { // Graph private member methods void Graph::_resolveAntiParallelEdges() diff --git a/src/0003_graph/0016_maximum_flow_edmonds_karp.cc b/src/0003_graph/0016_maximum_flow_edmonds_karp.cc index 0dfc02b..4cb9a6f 100644 --- a/src/0003_graph/0016_maximum_flow_edmonds_karp.cc +++ b/src/0003_graph/0016_maximum_flow_edmonds_karp.cc @@ -3,7 +3,7 @@ #include using namespace std; -namespace maximum_flow_edmonds_karp +namespace dsa::maximum_flow_edmonds_karp { // Graph private member methods void Graph::_resolveAntiParallelEdges() diff --git a/src/0003_graph/0017_maximum_bipartite_matching.cc b/src/0003_graph/0017_maximum_bipartite_matching.cc index e5e505d..c309ef8 100644 --- a/src/0003_graph/0017_maximum_bipartite_matching.cc +++ b/src/0003_graph/0017_maximum_bipartite_matching.cc @@ -3,7 +3,7 @@ #include using namespace std; -namespace maximum_bipartite_matching +namespace dsa::maximum_bipartite_matching { // Graph private member methods void Graph::_resolveAntiParallelEdges() diff --git a/src/0003_graph/0018_maximum_flow_goldberg_generic_push_relabel.cc b/src/0003_graph/0018_maximum_flow_goldberg_generic_push_relabel.cc index be68e7e..69e61ce 100644 --- a/src/0003_graph/0018_maximum_flow_goldberg_generic_push_relabel.cc +++ b/src/0003_graph/0018_maximum_flow_goldberg_generic_push_relabel.cc @@ -2,7 +2,7 @@ #include using namespace std; -namespace maximum_flow_goldberg_generic_push_relabel +namespace dsa::maximum_flow_goldberg_generic_push_relabel { // Graph private member methods diff --git a/src/0003_graph/0019_maximum_flow_relabel_to_front.cc b/src/0003_graph/0019_maximum_flow_relabel_to_front.cc index c0f3a90..034e6ca 100644 --- a/src/0003_graph/0019_maximum_flow_relabel_to_front.cc +++ b/src/0003_graph/0019_maximum_flow_relabel_to_front.cc @@ -3,7 +3,7 @@ #include using namespace std; -namespace maximum_flow_relabel_to_front +namespace dsa::maximum_flow_relabel_to_front { // Graph private member methods diff --git a/src/0003_graph/headers/0001_breadth_first_search.h b/src/0003_graph/headers/0001_breadth_first_search.h index 7a2a36c..1388ed6 100644 --- a/src/0003_graph/headers/0001_breadth_first_search.h +++ b/src/0003_graph/headers/0001_breadth_first_search.h @@ -7,7 +7,7 @@ #include using namespace std; -namespace breadth_first_search +namespace dsa::breadth_first_search { enum color { WHITE, GRAY, BLACK }; class Node diff --git a/src/0003_graph/headers/0002_depth_first_search.h b/src/0003_graph/headers/0002_depth_first_search.h index 64ab19e..79612f2 100644 --- a/src/0003_graph/headers/0002_depth_first_search.h +++ b/src/0003_graph/headers/0002_depth_first_search.h @@ -6,7 +6,7 @@ #include using namespace std; -namespace depth_first_search +namespace dsa::depth_first_search { enum color { WHITE, GRAY, BLACK }; diff --git a/src/0003_graph/headers/0003_topological_sort.h b/src/0003_graph/headers/0003_topological_sort.h index 553e3ca..7b34cd8 100644 --- a/src/0003_graph/headers/0003_topological_sort.h +++ b/src/0003_graph/headers/0003_topological_sort.h @@ -6,7 +6,7 @@ #include using namespace std; -namespace topological_sort +namespace dsa::topological_sort { enum color { WHITE, GRAY, BLACK }; diff --git a/src/0003_graph/headers/0004_strongly_connected_components.h b/src/0003_graph/headers/0004_strongly_connected_components.h index 4b0e9e6..266fce5 100644 --- a/src/0003_graph/headers/0004_strongly_connected_components.h +++ b/src/0003_graph/headers/0004_strongly_connected_components.h @@ -6,7 +6,7 @@ #include using namespace std; -namespace strongly_connected_components +namespace dsa::strongly_connected_components { enum color { WHITE, GRAY, BLACK }; diff --git a/src/0003_graph/headers/0005_hamiltonian_path_and_cycle.h b/src/0003_graph/headers/0005_hamiltonian_path_and_cycle.h index 37e64fa..d29af50 100644 --- a/src/0003_graph/headers/0005_hamiltonian_path_and_cycle.h +++ b/src/0003_graph/headers/0005_hamiltonian_path_and_cycle.h @@ -5,7 +5,7 @@ #include using namespace std; -namespace hamiltonian_path_and_cycle +namespace dsa::hamiltonian_path_and_cycle { class Node { diff --git a/src/0003_graph/headers/0006_eulerian_path_and_circuit.h b/src/0003_graph/headers/0006_eulerian_path_and_circuit.h index 42dd7e0..09fd175 100644 --- a/src/0003_graph/headers/0006_eulerian_path_and_circuit.h +++ b/src/0003_graph/headers/0006_eulerian_path_and_circuit.h @@ -5,7 +5,7 @@ #include using namespace std; -namespace eulerian_path_and_circuit +namespace dsa::eulerian_path_and_circuit { class Node { diff --git a/src/0003_graph/headers/0007_minimum_spanning_tree_kruskal_algorithm.h b/src/0003_graph/headers/0007_minimum_spanning_tree_kruskal_algorithm.h index 95db855..52ec487 100644 --- a/src/0003_graph/headers/0007_minimum_spanning_tree_kruskal_algorithm.h +++ b/src/0003_graph/headers/0007_minimum_spanning_tree_kruskal_algorithm.h @@ -5,7 +5,7 @@ #include using namespace std; -namespace minimum_spanning_tree_kruskal_algorithm +namespace dsa::minimum_spanning_tree_kruskal_algorithm { class Node { diff --git a/src/0003_graph/headers/0008_minimum_spanning_tree_prim_algorithm.h b/src/0003_graph/headers/0008_minimum_spanning_tree_prim_algorithm.h index adfca0b..79a193f 100644 --- a/src/0003_graph/headers/0008_minimum_spanning_tree_prim_algorithm.h +++ b/src/0003_graph/headers/0008_minimum_spanning_tree_prim_algorithm.h @@ -5,7 +5,7 @@ #include using namespace std; -namespace minimum_spanning_tree_prim_algorithm +namespace dsa::minimum_spanning_tree_prim_algorithm { class Node { diff --git a/src/0003_graph/headers/0009_single_source_shortest_path_bellman_ford.h b/src/0003_graph/headers/0009_single_source_shortest_path_bellman_ford.h index bfcd3c1..618f3da 100644 --- a/src/0003_graph/headers/0009_single_source_shortest_path_bellman_ford.h +++ b/src/0003_graph/headers/0009_single_source_shortest_path_bellman_ford.h @@ -4,7 +4,7 @@ #include using namespace std; -namespace single_source_shortest_path_bellman_ford +namespace dsa::single_source_shortest_path_bellman_ford { class Node { diff --git a/src/0003_graph/headers/0010_directed_acyclic_graph_shortest_path.h b/src/0003_graph/headers/0010_directed_acyclic_graph_shortest_path.h index cf5f93c..e641b55 100644 --- a/src/0003_graph/headers/0010_directed_acyclic_graph_shortest_path.h +++ b/src/0003_graph/headers/0010_directed_acyclic_graph_shortest_path.h @@ -5,7 +5,7 @@ #include using namespace std; -namespace directed_acyclic_graph_shortest_path +namespace dsa::directed_acyclic_graph_shortest_path { enum color {WHITE, GRAY, BLACK}; diff --git a/src/0003_graph/headers/0011_single_source_shortest_path_dijkstra.h b/src/0003_graph/headers/0011_single_source_shortest_path_dijkstra.h index 0d5ae13..7bb439a 100644 --- a/src/0003_graph/headers/0011_single_source_shortest_path_dijkstra.h +++ b/src/0003_graph/headers/0011_single_source_shortest_path_dijkstra.h @@ -5,7 +5,7 @@ #include using namespace std; -namespace single_source_shortest_path_dijkstra +namespace dsa::single_source_shortest_path_dijkstra { class Node { diff --git a/src/0003_graph/headers/0012_difference_constraints_shortest_paths.h b/src/0003_graph/headers/0012_difference_constraints_shortest_paths.h index 5237b70..265b9f4 100644 --- a/src/0003_graph/headers/0012_difference_constraints_shortest_paths.h +++ b/src/0003_graph/headers/0012_difference_constraints_shortest_paths.h @@ -5,7 +5,7 @@ #include using namespace std; -namespace difference_constraints_shortest_paths +namespace dsa::difference_constraints_shortest_paths { class Node { diff --git a/src/0003_graph/headers/0013_all_pairs_shortest_paths_floyd_warshall.h b/src/0003_graph/headers/0013_all_pairs_shortest_paths_floyd_warshall.h index 9226e7a..2185604 100644 --- a/src/0003_graph/headers/0013_all_pairs_shortest_paths_floyd_warshall.h +++ b/src/0003_graph/headers/0013_all_pairs_shortest_paths_floyd_warshall.h @@ -3,7 +3,7 @@ #include using namespace std; -namespace all_pairs_shortest_paths_floyd_warshall +namespace dsa::all_pairs_shortest_paths_floyd_warshall { class Graph { diff --git a/src/0003_graph/headers/0014_all_pairs_shortest_paths_johnson.h b/src/0003_graph/headers/0014_all_pairs_shortest_paths_johnson.h index 56b4948..22e48c4 100644 --- a/src/0003_graph/headers/0014_all_pairs_shortest_paths_johnson.h +++ b/src/0003_graph/headers/0014_all_pairs_shortest_paths_johnson.h @@ -5,7 +5,7 @@ #include using namespace std; -namespace all_pairs_shortest_paths_johnson +namespace dsa::all_pairs_shortest_paths_johnson { class Node { diff --git a/src/0003_graph/headers/0015_maximum_flow_ford_fulkerson.h b/src/0003_graph/headers/0015_maximum_flow_ford_fulkerson.h index f685e33..a3ff467 100644 --- a/src/0003_graph/headers/0015_maximum_flow_ford_fulkerson.h +++ b/src/0003_graph/headers/0015_maximum_flow_ford_fulkerson.h @@ -4,7 +4,7 @@ #include using namespace std; -namespace maximum_flow_ford_fulkerson +namespace dsa::maximum_flow_ford_fulkerson { class Graph { diff --git a/src/0003_graph/headers/0016_maximum_flow_edmonds_karp.h b/src/0003_graph/headers/0016_maximum_flow_edmonds_karp.h index c0036ca..799bc15 100644 --- a/src/0003_graph/headers/0016_maximum_flow_edmonds_karp.h +++ b/src/0003_graph/headers/0016_maximum_flow_edmonds_karp.h @@ -4,7 +4,7 @@ #include using namespace std; -namespace maximum_flow_edmonds_karp +namespace dsa::maximum_flow_edmonds_karp { class Graph { diff --git a/src/0003_graph/headers/0017_maximum_bipartite_matching.h b/src/0003_graph/headers/0017_maximum_bipartite_matching.h index 994f6ea..12d9a6a 100644 --- a/src/0003_graph/headers/0017_maximum_bipartite_matching.h +++ b/src/0003_graph/headers/0017_maximum_bipartite_matching.h @@ -4,7 +4,7 @@ #include using namespace std; -namespace maximum_bipartite_matching +namespace dsa::maximum_bipartite_matching { enum color { diff --git a/src/0003_graph/headers/0018_maximum_flow_goldberg_generic_push_relabel.h b/src/0003_graph/headers/0018_maximum_flow_goldberg_generic_push_relabel.h index 7f42725..34b7dae 100644 --- a/src/0003_graph/headers/0018_maximum_flow_goldberg_generic_push_relabel.h +++ b/src/0003_graph/headers/0018_maximum_flow_goldberg_generic_push_relabel.h @@ -4,7 +4,7 @@ #include using namespace std; -namespace maximum_flow_goldberg_generic_push_relabel +namespace dsa::maximum_flow_goldberg_generic_push_relabel { class Graph { diff --git a/src/0003_graph/headers/0019_maximum_flow_relabel_to_front.h b/src/0003_graph/headers/0019_maximum_flow_relabel_to_front.h index 839cd26..4f57573 100644 --- a/src/0003_graph/headers/0019_maximum_flow_relabel_to_front.h +++ b/src/0003_graph/headers/0019_maximum_flow_relabel_to_front.h @@ -4,7 +4,7 @@ #include using namespace std; -namespace maximum_flow_relabel_to_front +namespace dsa::maximum_flow_relabel_to_front { class Graph { diff --git a/src/0004_dynamic_programming/0001_fibonacci_number.cc b/src/0004_dynamic_programming/0001_fibonacci_number.cc index 9b96a0a..837f8d2 100644 --- a/src/0004_dynamic_programming/0001_fibonacci_number.cc +++ b/src/0004_dynamic_programming/0001_fibonacci_number.cc @@ -1,6 +1,6 @@ #include "0001_fibonacci_number.h" -namespace fibonacci_number +namespace dsa::fibonacci_number { int DynamicProgramming::recursiveNthFibonacci(int n) { diff --git a/src/0004_dynamic_programming/0002_tribonacci_number.cc b/src/0004_dynamic_programming/0002_tribonacci_number.cc index 2d22eef..f9a7f31 100644 --- a/src/0004_dynamic_programming/0002_tribonacci_number.cc +++ b/src/0004_dynamic_programming/0002_tribonacci_number.cc @@ -1,6 +1,6 @@ #include "0002_tribonacci_number.h" -namespace tribonacci_number +namespace dsa::tribonacci_number { int DynamicProgramming::recursiveNthTribonacci(int n) { diff --git a/src/0004_dynamic_programming/0003_climbing_stairs.cc b/src/0004_dynamic_programming/0003_climbing_stairs.cc index cdf2832..0d7e0bf 100644 --- a/src/0004_dynamic_programming/0003_climbing_stairs.cc +++ b/src/0004_dynamic_programming/0003_climbing_stairs.cc @@ -1,7 +1,7 @@ #include "0003_climbing_stairs.h" using namespace std; -namespace climbing_stairs +namespace dsa::climbing_stairs { int DynamicProgramming::recursiveCountWays(int n) { diff --git a/src/0004_dynamic_programming/0004_minimum_cost_climbing_stairs.cc b/src/0004_dynamic_programming/0004_minimum_cost_climbing_stairs.cc index 4fc8ce0..9b2e136 100644 --- a/src/0004_dynamic_programming/0004_minimum_cost_climbing_stairs.cc +++ b/src/0004_dynamic_programming/0004_minimum_cost_climbing_stairs.cc @@ -1,7 +1,7 @@ #include "0004_minimum_cost_climbing_stairs.h" #include -namespace minimum_cost_climbing_stairs +namespace dsa::minimum_cost_climbing_stairs { int DynamicProgramming::_minCostRecursive(size_t step, vector& cost) { diff --git a/src/0004_dynamic_programming/0005_house_robber1.cc b/src/0004_dynamic_programming/0005_house_robber1.cc index d250fc5..5427acf 100644 --- a/src/0004_dynamic_programming/0005_house_robber1.cc +++ b/src/0004_dynamic_programming/0005_house_robber1.cc @@ -1,6 +1,6 @@ #include "0005_house_robber1.h" -namespace house_robber1 +namespace dsa::house_robber1 { int DynamicProgramming::_maxLootRecursive(size_t house, vector& houseValues) { diff --git a/src/0004_dynamic_programming/0006_house_robber2.cc b/src/0004_dynamic_programming/0006_house_robber2.cc index 421c141..daeddc8 100644 --- a/src/0004_dynamic_programming/0006_house_robber2.cc +++ b/src/0004_dynamic_programming/0006_house_robber2.cc @@ -1,6 +1,6 @@ #include "0006_house_robber2.h" -namespace house_robber2 +namespace dsa::house_robber2 { int DynamicProgramming::_maxLootRecursive(size_t house, vector& houseValues) { diff --git a/src/0004_dynamic_programming/0007_decode_ways.cc b/src/0004_dynamic_programming/0007_decode_ways.cc index 0265074..5b8e009 100644 --- a/src/0004_dynamic_programming/0007_decode_ways.cc +++ b/src/0004_dynamic_programming/0007_decode_ways.cc @@ -1,6 +1,6 @@ #include "0007_decode_ways.h" -namespace decode_ways +namespace dsa::decode_ways { int DynamicProgramming::_countWaysRecursiveHelper(string& digits, size_t index) { diff --git a/src/0004_dynamic_programming/0008_tiling_problem.cc b/src/0004_dynamic_programming/0008_tiling_problem.cc index e1e0043..5fa6cf8 100644 --- a/src/0004_dynamic_programming/0008_tiling_problem.cc +++ b/src/0004_dynamic_programming/0008_tiling_problem.cc @@ -1,6 +1,6 @@ #include "0008_tiling_problem.h" -namespace tiling_problem +namespace dsa::tiling_problem { int DynamicProgramming::_numberOfWaysRecursiveHelper(int n) { diff --git a/src/0004_dynamic_programming/0009_friends_pairing_problem.cc b/src/0004_dynamic_programming/0009_friends_pairing_problem.cc index 80ab43e..ca37ca6 100644 --- a/src/0004_dynamic_programming/0009_friends_pairing_problem.cc +++ b/src/0004_dynamic_programming/0009_friends_pairing_problem.cc @@ -1,6 +1,6 @@ #include "0009_friends_pairing_problem.h" -namespace friends_pairing_problem +namespace dsa::friends_pairing_problem { // dynamic programming private member methods. int DynamicProgramming::_countFriendsPairingsRecursiveHelper(int n) diff --git a/src/0004_dynamic_programming/0010_ways_to_cover_distance.cc b/src/0004_dynamic_programming/0010_ways_to_cover_distance.cc index 6e539c7..c26c4c6 100644 --- a/src/0004_dynamic_programming/0010_ways_to_cover_distance.cc +++ b/src/0004_dynamic_programming/0010_ways_to_cover_distance.cc @@ -1,6 +1,6 @@ #include "0010_ways_to_cover_distance.h" -namespace ways_to_cover_distance +namespace dsa::ways_to_cover_distance { // dynamic programming private member methods. int DynamicProgramming::_waysToCoverDistanceRecursiveHelper(int dist) diff --git a/src/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order.cc b/src/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order.cc index f03c200..3609d80 100644 --- a/src/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order.cc +++ b/src/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order.cc @@ -1,6 +1,6 @@ #include "0011_count_ways_to_reach_nth_stair_include_order.h" -namespace count_ways_to_reach_nth_stair_include_order +namespace dsa::count_ways_to_reach_nth_stair_include_order { // dynamic programming private member methods. int DynamicProgramming::_recursiveCountWaysHelper(int n) diff --git a/src/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order.cc b/src/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order.cc index b9a56a8..8c2f165 100644 --- a/src/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order.cc +++ b/src/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order.cc @@ -1,6 +1,6 @@ #include "0012_count_ways_to_reach_nth_stair_exclude_order.h" -namespace count_ways_to_reach_nth_stair_exclude_order +namespace dsa::count_ways_to_reach_nth_stair_exclude_order { // notes: /* diff --git a/src/0004_dynamic_programming/0013_knapsack_problem.cc b/src/0004_dynamic_programming/0013_knapsack_problem.cc index bddd50a..5952344 100644 --- a/src/0004_dynamic_programming/0013_knapsack_problem.cc +++ b/src/0004_dynamic_programming/0013_knapsack_problem.cc @@ -1,6 +1,6 @@ #include "0013_knapsack_problem.h" -namespace knapsack_problem +namespace dsa::knapsack_problem { // dynamic programming private member methods. int DynamicProgramming::_recursiveKnapsackHelper(int capacity, vector& weight, vector& profit, int numberOfItems) diff --git a/src/0004_dynamic_programming/0014_subset_sum_problem.cc b/src/0004_dynamic_programming/0014_subset_sum_problem.cc index f1571f7..4712c61 100644 --- a/src/0004_dynamic_programming/0014_subset_sum_problem.cc +++ b/src/0004_dynamic_programming/0014_subset_sum_problem.cc @@ -1,6 +1,6 @@ #include "0014_subset_sum_problem.h" -namespace subset_sum_problem +namespace dsa::subset_sum_problem { // dynamic programming private member methods. bool DynamicProgramming::_recursiveSubsetSumHelper(vector& nums, int sum, int numberOfElements) diff --git a/src/0004_dynamic_programming/0015_count_subsets_for_sum.cc b/src/0004_dynamic_programming/0015_count_subsets_for_sum.cc index 8d122e5..394bac2 100644 --- a/src/0004_dynamic_programming/0015_count_subsets_for_sum.cc +++ b/src/0004_dynamic_programming/0015_count_subsets_for_sum.cc @@ -1,6 +1,6 @@ #include "0015_count_subsets_for_sum.h" -namespace count_subsets_for_sum +namespace dsa::count_subsets_for_sum { // dynamic programming private member methods int DynamicProgramming::_recursiveCountSubsetsHelper(vector& nums, int targetSum, int currentSum, int index) diff --git a/src/0004_dynamic_programming/0016_partition_equal_subset_sum.cc b/src/0004_dynamic_programming/0016_partition_equal_subset_sum.cc index 8b41f82..54f0456 100644 --- a/src/0004_dynamic_programming/0016_partition_equal_subset_sum.cc +++ b/src/0004_dynamic_programming/0016_partition_equal_subset_sum.cc @@ -1,6 +1,6 @@ #include "0016_partition_equal_subset_sum.h" -namespace partition_equal_subset_sum +namespace dsa::partition_equal_subset_sum { bool DynamicProgramming::_recursivePartitionEqualSubsetsHelper(vector& nums, int targetSum, int numberOfElements) { diff --git a/src/0004_dynamic_programming/0017_target_sum.cc b/src/0004_dynamic_programming/0017_target_sum.cc index 121c153..c610813 100644 --- a/src/0004_dynamic_programming/0017_target_sum.cc +++ b/src/0004_dynamic_programming/0017_target_sum.cc @@ -1,6 +1,6 @@ #include "0017_target_sum.h" -namespace target_sum +namespace dsa::target_sum { int DynamicProgramming::_recursiveFindTotalWaysHelper(vector& nums, int currentSum, int targetSum, int index) { diff --git a/src/0004_dynamic_programming/headers/0001_fibonacci_number.h b/src/0004_dynamic_programming/headers/0001_fibonacci_number.h index 3ae14cd..fa8fabb 100644 --- a/src/0004_dynamic_programming/headers/0001_fibonacci_number.h +++ b/src/0004_dynamic_programming/headers/0001_fibonacci_number.h @@ -11,7 +11,7 @@ print the n'th fibonacci number. */ -namespace fibonacci_number +namespace dsa::fibonacci_number { class DynamicProgramming { diff --git a/src/0004_dynamic_programming/headers/0002_tribonacci_number.h b/src/0004_dynamic_programming/headers/0002_tribonacci_number.h index b394f0b..9f2ab4c 100644 --- a/src/0004_dynamic_programming/headers/0002_tribonacci_number.h +++ b/src/0004_dynamic_programming/headers/0002_tribonacci_number.h @@ -11,7 +11,7 @@ print the n'th tribonacci number. */ -namespace tribonacci_number +namespace dsa::tribonacci_number { class DynamicProgramming { diff --git a/src/0004_dynamic_programming/headers/0003_climbing_stairs.h b/src/0004_dynamic_programming/headers/0003_climbing_stairs.h index 8ce6a3d..ba3f089 100644 --- a/src/0004_dynamic_programming/headers/0003_climbing_stairs.h +++ b/src/0004_dynamic_programming/headers/0003_climbing_stairs.h @@ -12,7 +12,7 @@ the person can climb either 1 stair or 2 stairs at a time, the task is to count */ -namespace climbing_stairs +namespace dsa::climbing_stairs { class DynamicProgramming { diff --git a/src/0004_dynamic_programming/headers/0004_minimum_cost_climbing_stairs.h b/src/0004_dynamic_programming/headers/0004_minimum_cost_climbing_stairs.h index 7ed9816..c38a1c8 100644 --- a/src/0004_dynamic_programming/headers/0004_minimum_cost_climbing_stairs.h +++ b/src/0004_dynamic_programming/headers/0004_minimum_cost_climbing_stairs.h @@ -12,7 +12,7 @@ we can either start from the step with index 0, or the step with index 1. the ta */ -namespace minimum_cost_climbing_stairs +namespace dsa::minimum_cost_climbing_stairs { class DynamicProgramming { diff --git a/src/0004_dynamic_programming/headers/0005_house_robber1.h b/src/0004_dynamic_programming/headers/0005_house_robber1.h index 1dddd2e..ea990d2 100644 --- a/src/0004_dynamic_programming/headers/0005_house_robber1.h +++ b/src/0004_dynamic_programming/headers/0005_house_robber1.h @@ -8,11 +8,11 @@ linear recurrence description there are n houses built in a line, each of which contains some money in it. -A robber wants to steal money from these houses, but he can’t steal from two adjacent houses. the task is to find the maximum amount of money which can be stolen. +A robber wants to steal money from these houses, but he can�t steal from two adjacent houses. the task is to find the maximum amount of money which can be stolen. */ -namespace house_robber1 +namespace dsa::house_robber1 { class DynamicProgramming { diff --git a/src/0004_dynamic_programming/headers/0006_house_robber2.h b/src/0004_dynamic_programming/headers/0006_house_robber2.h index 3f7afb1..34648a2 100644 --- a/src/0004_dynamic_programming/headers/0006_house_robber2.h +++ b/src/0004_dynamic_programming/headers/0006_house_robber2.h @@ -14,7 +14,7 @@ note: since the houses are in a circle, the first and last houses are also consi */ -namespace house_robber2 +namespace dsa::house_robber2 { class DynamicProgramming { diff --git a/src/0004_dynamic_programming/headers/0007_decode_ways.h b/src/0004_dynamic_programming/headers/0007_decode_ways.h index 654fe94..f2525ec 100644 --- a/src/0004_dynamic_programming/headers/0007_decode_ways.h +++ b/src/0004_dynamic_programming/headers/0007_decode_ways.h @@ -19,7 +19,7 @@ note : groupings that contain invalid codes(e.g., "0" by itself or numbers great for instance, the string "230" is invalid because "0" cannot stand alone, and "30" is greater than "26", so it cannot represent any letter.the task is to find the total number of valid ways to decode a given string. */ -namespace decode_ways +namespace dsa::decode_ways { class DynamicProgramming { diff --git a/src/0004_dynamic_programming/headers/0008_tiling_problem.h b/src/0004_dynamic_programming/headers/0008_tiling_problem.h index 95be45b..ef0c97f 100644 --- a/src/0004_dynamic_programming/headers/0008_tiling_problem.h +++ b/src/0004_dynamic_programming/headers/0008_tiling_problem.h @@ -12,7 +12,7 @@ given a "2 x n" board and tiles of size "2 x 1", the task is to count the number A tile can either be placed horizontally i.e., as a 1 x 2 tile or vertically i.e., as 2 x 1 tile. */ -namespace tiling_problem +namespace dsa::tiling_problem { class DynamicProgramming { diff --git a/src/0004_dynamic_programming/headers/0009_friends_pairing_problem.h b/src/0004_dynamic_programming/headers/0009_friends_pairing_problem.h index 375c908..6433a8d 100644 --- a/src/0004_dynamic_programming/headers/0009_friends_pairing_problem.h +++ b/src/0004_dynamic_programming/headers/0009_friends_pairing_problem.h @@ -33,7 +33,7 @@ In case of n = 4, we have 3 ways to form a group: 3) 2 separate pairs (2,2) */ -namespace friends_pairing_problem +namespace dsa::friends_pairing_problem { class DynamicProgramming { diff --git a/src/0004_dynamic_programming/headers/0010_ways_to_cover_distance.h b/src/0004_dynamic_programming/headers/0010_ways_to_cover_distance.h index ab0f714..eb264b2 100644 --- a/src/0004_dynamic_programming/headers/0010_ways_to_cover_distance.h +++ b/src/0004_dynamic_programming/headers/0010_ways_to_cover_distance.h @@ -34,7 +34,7 @@ explanation: below are the four ways => 1 step + 3 step */ -namespace ways_to_cover_distance +namespace dsa::ways_to_cover_distance { class DynamicProgramming { diff --git a/src/0004_dynamic_programming/headers/0011_count_ways_to_reach_nth_stair_include_order.h b/src/0004_dynamic_programming/headers/0011_count_ways_to_reach_nth_stair_include_order.h index e43c415..b9b8fcc 100644 --- a/src/0004_dynamic_programming/headers/0011_count_ways_to_reach_nth_stair_include_order.h +++ b/src/0004_dynamic_programming/headers/0011_count_ways_to_reach_nth_stair_include_order.h @@ -29,7 +29,7 @@ output: 5 explanation: there are five ways to reach 4th stair: {1, 1, 1, 1}, {1, 1, 2}, {2, 1, 1}, {1, 2, 1} and {2, 2}. */ -namespace count_ways_to_reach_nth_stair_include_order +namespace dsa::count_ways_to_reach_nth_stair_include_order { class DynamicProgramming { diff --git a/src/0004_dynamic_programming/headers/0012_count_ways_to_reach_nth_stair_exclude_order.h b/src/0004_dynamic_programming/headers/0012_count_ways_to_reach_nth_stair_exclude_order.h index 80e7acc..0cca6d3 100644 --- a/src/0004_dynamic_programming/headers/0012_count_ways_to_reach_nth_stair_exclude_order.h +++ b/src/0004_dynamic_programming/headers/0012_count_ways_to_reach_nth_stair_exclude_order.h @@ -31,7 +31,7 @@ output: 3 explanation: three ways to reach 5th stair: {1, 1, 1, 1, 1}, {1, 1, 1, 2} and {1, 2, 2}. */ -namespace count_ways_to_reach_nth_stair_exclude_order +namespace dsa::count_ways_to_reach_nth_stair_exclude_order { class DynamicProgramming { diff --git a/src/0004_dynamic_programming/headers/0013_knapsack_problem.h b/src/0004_dynamic_programming/headers/0013_knapsack_problem.h index 129af61..51f8287 100644 --- a/src/0004_dynamic_programming/headers/0013_knapsack_problem.h +++ b/src/0004_dynamic_programming/headers/0013_knapsack_problem.h @@ -20,7 +20,7 @@ input: W = 3, profit[] = [1, 2, 3], weight[] = [4, 5, 6] output: 0 */ -namespace knapsack_problem +namespace dsa::knapsack_problem { class DynamicProgramming { diff --git a/src/0004_dynamic_programming/headers/0014_subset_sum_problem.h b/src/0004_dynamic_programming/headers/0014_subset_sum_problem.h index 2dcbcf9..0ecb546 100644 --- a/src/0004_dynamic_programming/headers/0014_subset_sum_problem.h +++ b/src/0004_dynamic_programming/headers/0014_subset_sum_problem.h @@ -21,7 +21,7 @@ output: false explanation: there is no subset that add up to 30. */ -namespace subset_sum_problem +namespace dsa::subset_sum_problem { class DynamicProgramming { diff --git a/src/0004_dynamic_programming/headers/0015_count_subsets_for_sum.h b/src/0004_dynamic_programming/headers/0015_count_subsets_for_sum.h index c092d2c..db5e7da 100644 --- a/src/0004_dynamic_programming/headers/0015_count_subsets_for_sum.h +++ b/src/0004_dynamic_programming/headers/0015_count_subsets_for_sum.h @@ -21,7 +21,7 @@ output: 4 explanation: all the possible subsets are [1], [1], [1] and [1] */ -namespace count_subsets_for_sum +namespace dsa::count_subsets_for_sum { class DynamicProgramming { diff --git a/src/0004_dynamic_programming/headers/0016_partition_equal_subset_sum.h b/src/0004_dynamic_programming/headers/0016_partition_equal_subset_sum.h index f55fec2..9aa6a04 100644 --- a/src/0004_dynamic_programming/headers/0016_partition_equal_subset_sum.h +++ b/src/0004_dynamic_programming/headers/0016_partition_equal_subset_sum.h @@ -23,7 +23,7 @@ output: false explanation: the array cannot be partitioned into equal sum sets. */ -namespace partition_equal_subset_sum +namespace dsa::partition_equal_subset_sum { class DynamicProgramming { diff --git a/src/0004_dynamic_programming/headers/0017_target_sum.h b/src/0004_dynamic_programming/headers/0017_target_sum.h index 6830243..20b2a05 100644 --- a/src/0004_dynamic_programming/headers/0017_target_sum.h +++ b/src/0004_dynamic_programming/headers/0017_target_sum.h @@ -31,7 +31,7 @@ input: N = 1, arr[] = {1}, target = 1 output: 1 */ -namespace target_sum +namespace dsa::target_sum { class DynamicProgramming { diff --git a/tests/0001_basics/node_test.cc b/tests/0001_basics/node_test.cc index 3da9a0c..f537ce2 100644 --- a/tests/0001_basics/node_test.cc +++ b/tests/0001_basics/node_test.cc @@ -2,7 +2,7 @@ #include "node.h" // demonstrate some basic assertions. -namespace node_testing +namespace dsa::node_testing { TEST(testingNodeValue, positiveTestCase) { diff --git a/tests/0002_tree/0001_binary_search_tree_test.cc b/tests/0002_tree/0001_binary_search_tree_test.cc index a4c32ff..2906786 100644 --- a/tests/0002_tree/0001_binary_search_tree_test.cc +++ b/tests/0002_tree/0001_binary_search_tree_test.cc @@ -3,7 +3,7 @@ #include "0001_binary_search_tree.h" #include "../0000_common_utilities/unit_test_helper.h" -namespace binary_search_tree +namespace dsa::binary_search_tree { UnitTestHelper unitTestHelper; diff --git a/tests/0003_graph/0001_breadth_first_search_test.cc b/tests/0003_graph/0001_breadth_first_search_test.cc index b46ffc4..9c095da 100644 --- a/tests/0003_graph/0001_breadth_first_search_test.cc +++ b/tests/0003_graph/0001_breadth_first_search_test.cc @@ -3,7 +3,7 @@ #include "../../src/0003_graph/headers/0001_breadth_first_search.h" #include "../0000_common_utilities/unit_test_helper.h" -namespace breadth_first_search +namespace dsa::breadth_first_search { UnitTestHelper unitTestHelper; diff --git a/tests/0003_graph/0002_depth_first_search_test.cc b/tests/0003_graph/0002_depth_first_search_test.cc index f950f0b..4678867 100644 --- a/tests/0003_graph/0002_depth_first_search_test.cc +++ b/tests/0003_graph/0002_depth_first_search_test.cc @@ -2,7 +2,7 @@ #include "0002_depth_first_search.h" #include "../0000_common_utilities/unit_test_helper.h" -namespace depth_first_search +namespace dsa::depth_first_search { UnitTestHelper unitTestHelper; diff --git a/tests/0003_graph/0003_topological_sort_test.cc b/tests/0003_graph/0003_topological_sort_test.cc index 72fd320..911e3c9 100644 --- a/tests/0003_graph/0003_topological_sort_test.cc +++ b/tests/0003_graph/0003_topological_sort_test.cc @@ -2,7 +2,7 @@ #include "0003_topological_sort.h" #include "../0000_common_utilities/unit_test_helper.h" -namespace topological_sort +namespace dsa::topological_sort { UnitTestHelper unitTestHelper; diff --git a/tests/0003_graph/0004_strongly_connected_components_test.cc b/tests/0003_graph/0004_strongly_connected_components_test.cc index 8b8c84d..00e0ee5 100644 --- a/tests/0003_graph/0004_strongly_connected_components_test.cc +++ b/tests/0003_graph/0004_strongly_connected_components_test.cc @@ -2,7 +2,7 @@ #include "0004_strongly_connected_components.h" #include "../0000_common_utilities/unit_test_helper.h" -namespace strongly_connected_components +namespace dsa::strongly_connected_components { UnitTestHelper unitTestHelper; diff --git a/tests/0003_graph/0005_hamiltonian_path_and_cycle_test.cc b/tests/0003_graph/0005_hamiltonian_path_and_cycle_test.cc index 2a1aae2..3ce1b50 100644 --- a/tests/0003_graph/0005_hamiltonian_path_and_cycle_test.cc +++ b/tests/0003_graph/0005_hamiltonian_path_and_cycle_test.cc @@ -2,7 +2,7 @@ #include "0005_hamiltonian_path_and_cycle.h" #include "../0000_common_utilities/unit_test_helper.h" -namespace hamiltonian_path_and_cycle +namespace dsa::hamiltonian_path_and_cycle { UnitTestHelper unitTestHelper; diff --git a/tests/0003_graph/0006_eulerian_path_and_circuit_test.cc b/tests/0003_graph/0006_eulerian_path_and_circuit_test.cc index 246f0c3..351df33 100644 --- a/tests/0003_graph/0006_eulerian_path_and_circuit_test.cc +++ b/tests/0003_graph/0006_eulerian_path_and_circuit_test.cc @@ -2,7 +2,7 @@ #include "0006_eulerian_path_and_circuit.h" #include "../0000_common_utilities/unit_test_helper.h" -namespace eulerian_path_and_circuit +namespace dsa::eulerian_path_and_circuit { UnitTestHelper unitTestHelper; diff --git a/tests/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm_test.cc b/tests/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm_test.cc index ff8fec3..2b71270 100644 --- a/tests/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm_test.cc +++ b/tests/0003_graph/0007_minimum_spanning_tree_kruskal_algorithm_test.cc @@ -2,7 +2,7 @@ #include "0007_minimum_spanning_tree_kruskal_algorithm.h" #include "../0000_common_utilities/unit_test_helper.h" -namespace minimum_spanning_tree_kruskal_algorithm +namespace dsa::minimum_spanning_tree_kruskal_algorithm { UnitTestHelper unitTestHelper; diff --git a/tests/0003_graph/0008_minimum_spanning_tree_prim_algorithm_test.cc b/tests/0003_graph/0008_minimum_spanning_tree_prim_algorithm_test.cc index d479f81..6adb394 100644 --- a/tests/0003_graph/0008_minimum_spanning_tree_prim_algorithm_test.cc +++ b/tests/0003_graph/0008_minimum_spanning_tree_prim_algorithm_test.cc @@ -2,7 +2,7 @@ #include "0008_minimum_spanning_tree_prim_algorithm.h" #include "../0000_common_utilities/unit_test_helper.h" -namespace minimum_spanning_tree_prim_algorithm +namespace dsa::minimum_spanning_tree_prim_algorithm { UnitTestHelper unitTestHelper; diff --git a/tests/0003_graph/0009_single_source_shortest_path_bellman_ford_test.cc b/tests/0003_graph/0009_single_source_shortest_path_bellman_ford_test.cc index 26b55ac..cefa263 100644 --- a/tests/0003_graph/0009_single_source_shortest_path_bellman_ford_test.cc +++ b/tests/0003_graph/0009_single_source_shortest_path_bellman_ford_test.cc @@ -2,7 +2,7 @@ #include "0009_single_source_shortest_path_bellman_ford.h" #include "../0000_common_utilities/unit_test_helper.h" -namespace single_source_shortest_path_bellman_ford +namespace dsa::single_source_shortest_path_bellman_ford { UnitTestHelper unitTestHelper; diff --git a/tests/0003_graph/0010_directed_acyclic_graph_shortest_path_test.cc b/tests/0003_graph/0010_directed_acyclic_graph_shortest_path_test.cc index 7e5cf1e..ec57e54 100644 --- a/tests/0003_graph/0010_directed_acyclic_graph_shortest_path_test.cc +++ b/tests/0003_graph/0010_directed_acyclic_graph_shortest_path_test.cc @@ -2,7 +2,7 @@ #include "0010_directed_acyclic_graph_shortest_path.h" #include "../0000_common_utilities/unit_test_helper.h" -namespace directed_acyclic_graph_shortest_path +namespace dsa::directed_acyclic_graph_shortest_path { UnitTestHelper unitTestHelper; diff --git a/tests/0003_graph/0011_single_source_shortest_path_dijkstra_test.cc b/tests/0003_graph/0011_single_source_shortest_path_dijkstra_test.cc index 8835eb9..a634ef7 100644 --- a/tests/0003_graph/0011_single_source_shortest_path_dijkstra_test.cc +++ b/tests/0003_graph/0011_single_source_shortest_path_dijkstra_test.cc @@ -2,7 +2,7 @@ #include "0011_single_source_shortest_path_dijkstra.h" #include "../0000_common_utilities/unit_test_helper.h" -namespace single_source_shortest_path_dijkstra +namespace dsa::single_source_shortest_path_dijkstra { UnitTestHelper unitTestHelper; diff --git a/tests/0003_graph/0012_difference_constraints_shortest_paths_test.cc b/tests/0003_graph/0012_difference_constraints_shortest_paths_test.cc index e2ef7c7..7b45734 100644 --- a/tests/0003_graph/0012_difference_constraints_shortest_paths_test.cc +++ b/tests/0003_graph/0012_difference_constraints_shortest_paths_test.cc @@ -3,7 +3,7 @@ #include"../0000_common_utilities/unit_test_helper.h" using namespace std; -namespace difference_constraints_shortest_paths +namespace dsa::difference_constraints_shortest_paths { UnitTestHelper unitTestHelper; diff --git a/tests/0003_graph/0013_all_pairs_shortest_paths_floyd_warshall_test.cc b/tests/0003_graph/0013_all_pairs_shortest_paths_floyd_warshall_test.cc index 7194c3f..06bae14 100644 --- a/tests/0003_graph/0013_all_pairs_shortest_paths_floyd_warshall_test.cc +++ b/tests/0003_graph/0013_all_pairs_shortest_paths_floyd_warshall_test.cc @@ -3,7 +3,7 @@ #include "../0000_common_utilities/unit_test_helper.h" using namespace std; -namespace all_pairs_shortest_paths_floyd_warshall +namespace dsa::all_pairs_shortest_paths_floyd_warshall { UnitTestHelper unitTestHelper; diff --git a/tests/0003_graph/0014_all_pairs_shortest_paths_johnson_test.cc b/tests/0003_graph/0014_all_pairs_shortest_paths_johnson_test.cc index f7bdea9..574a5d3 100644 --- a/tests/0003_graph/0014_all_pairs_shortest_paths_johnson_test.cc +++ b/tests/0003_graph/0014_all_pairs_shortest_paths_johnson_test.cc @@ -3,7 +3,7 @@ #include"../0000_common_utilities/unit_test_helper.h" using namespace std; -namespace all_pairs_shortest_paths_johnson +namespace dsa::all_pairs_shortest_paths_johnson { UnitTestHelper unitTestHelper; diff --git a/tests/0003_graph/0015_maximum_flow_ford_fulkerson_test.cc b/tests/0003_graph/0015_maximum_flow_ford_fulkerson_test.cc index f6b2a77..5efa4cb 100644 --- a/tests/0003_graph/0015_maximum_flow_ford_fulkerson_test.cc +++ b/tests/0003_graph/0015_maximum_flow_ford_fulkerson_test.cc @@ -2,7 +2,7 @@ #include "0015_maximum_flow_ford_fulkerson.h" #include "../0000_common_utilities/unit_test_helper.h" -namespace maximum_flow_ford_fulkerson +namespace dsa::maximum_flow_ford_fulkerson { UnitTestHelper unitTestHelper; diff --git a/tests/0003_graph/0016_maximum_flow_edmonds_karp_test.cc b/tests/0003_graph/0016_maximum_flow_edmonds_karp_test.cc index 9205f34..28605db 100644 --- a/tests/0003_graph/0016_maximum_flow_edmonds_karp_test.cc +++ b/tests/0003_graph/0016_maximum_flow_edmonds_karp_test.cc @@ -2,7 +2,7 @@ #include "0016_maximum_flow_edmonds_karp.h" #include "../0000_common_utilities/unit_test_helper.h" -namespace maximum_flow_edmonds_karp +namespace dsa::maximum_flow_edmonds_karp { UnitTestHelper unitTestHelper; diff --git a/tests/0003_graph/0017_maximum_bipartite_matching_test.cc b/tests/0003_graph/0017_maximum_bipartite_matching_test.cc index c5e7347..1c303af 100644 --- a/tests/0003_graph/0017_maximum_bipartite_matching_test.cc +++ b/tests/0003_graph/0017_maximum_bipartite_matching_test.cc @@ -2,7 +2,7 @@ #include "0017_maximum_bipartite_matching.h" #include "../0000_common_utilities/unit_test_helper.h" -namespace maximum_bipartite_matching +namespace dsa::maximum_bipartite_matching { TEST(maximumBipartiteMatching, simpleGraph) { diff --git a/tests/0003_graph/0018_maximum_flow_goldberg_generic_push_relabel_test.cc b/tests/0003_graph/0018_maximum_flow_goldberg_generic_push_relabel_test.cc index 878fc79..71e9acb 100644 --- a/tests/0003_graph/0018_maximum_flow_goldberg_generic_push_relabel_test.cc +++ b/tests/0003_graph/0018_maximum_flow_goldberg_generic_push_relabel_test.cc @@ -2,7 +2,7 @@ #include "0018_maximum_flow_goldberg_generic_push_relabel.h" #include "../0000_common_utilities/unit_test_helper.h" -namespace maximum_flow_goldberg_generic_push_relabel +namespace dsa::maximum_flow_goldberg_generic_push_relabel { UnitTestHelper unitTestHelper; diff --git a/tests/0003_graph/0019_maximum_flow_relabel_to_front_test.cc b/tests/0003_graph/0019_maximum_flow_relabel_to_front_test.cc index 2130547..a2780b8 100644 --- a/tests/0003_graph/0019_maximum_flow_relabel_to_front_test.cc +++ b/tests/0003_graph/0019_maximum_flow_relabel_to_front_test.cc @@ -3,7 +3,7 @@ #include "../0000_common_utilities/unit_test_helper.h" using namespace std; -namespace maximum_flow_relabel_to_front +namespace dsa::maximum_flow_relabel_to_front { UnitTestHelper unitTestHelper; diff --git a/tests/0004_dynamic_programming/0001_fibonacci_number_test.cc b/tests/0004_dynamic_programming/0001_fibonacci_number_test.cc index 9947442..15ed85b 100644 --- a/tests/0004_dynamic_programming/0001_fibonacci_number_test.cc +++ b/tests/0004_dynamic_programming/0001_fibonacci_number_test.cc @@ -2,7 +2,7 @@ #include "0001_fibonacci_number.h" using namespace std; -namespace fibonacci_number +namespace dsa::fibonacci_number { TEST(fibonacciNumber, recursiveTest) { diff --git a/tests/0004_dynamic_programming/0002_tribonacci_number_test.cc b/tests/0004_dynamic_programming/0002_tribonacci_number_test.cc index 886cf82..af11642 100644 --- a/tests/0004_dynamic_programming/0002_tribonacci_number_test.cc +++ b/tests/0004_dynamic_programming/0002_tribonacci_number_test.cc @@ -2,7 +2,7 @@ #include "0002_tribonacci_number.h" using namespace std; -namespace tribonacci_number +namespace dsa::tribonacci_number { TEST(tribonacciNumber, recursiveTest) { diff --git a/tests/0004_dynamic_programming/0003_climbing_stairs_test.cc b/tests/0004_dynamic_programming/0003_climbing_stairs_test.cc index 0824572..33e5930 100644 --- a/tests/0004_dynamic_programming/0003_climbing_stairs_test.cc +++ b/tests/0004_dynamic_programming/0003_climbing_stairs_test.cc @@ -1,7 +1,7 @@ #include #include "0003_climbing_stairs.h" -namespace climbing_stairs +namespace dsa::climbing_stairs { TEST(climbingStairs, recursiveTest) { diff --git a/tests/0004_dynamic_programming/0004_minimum_cost_climbing_stairs_test.cc b/tests/0004_dynamic_programming/0004_minimum_cost_climbing_stairs_test.cc index 383614b..ce36d4c 100644 --- a/tests/0004_dynamic_programming/0004_minimum_cost_climbing_stairs_test.cc +++ b/tests/0004_dynamic_programming/0004_minimum_cost_climbing_stairs_test.cc @@ -1,7 +1,7 @@ #include #include "0004_minimum_cost_climbing_stairs.h" -namespace minimum_cost_climbing_stairs +namespace dsa::minimum_cost_climbing_stairs { TEST(minimumCostClimbingStairs, recursionTest) { diff --git a/tests/0004_dynamic_programming/0005_house_robber1_test.cc b/tests/0004_dynamic_programming/0005_house_robber1_test.cc index 9c2c45e..da817dd 100644 --- a/tests/0004_dynamic_programming/0005_house_robber1_test.cc +++ b/tests/0004_dynamic_programming/0005_house_robber1_test.cc @@ -1,7 +1,7 @@ #include #include "0005_house_robber1.h" -namespace house_robber1 +namespace dsa::house_robber1 { TEST(houseRobber1, recursionTest) { diff --git a/tests/0004_dynamic_programming/0006_house_robber2_test.cc b/tests/0004_dynamic_programming/0006_house_robber2_test.cc index 0a74cd7..22fea25 100644 --- a/tests/0004_dynamic_programming/0006_house_robber2_test.cc +++ b/tests/0004_dynamic_programming/0006_house_robber2_test.cc @@ -1,7 +1,7 @@ #include #include "0006_house_robber2.h" -namespace house_robber2 +namespace dsa::house_robber2 { TEST(houseRobber2, recursionTest01) { diff --git a/tests/0004_dynamic_programming/0007_decode_ways_test.cc b/tests/0004_dynamic_programming/0007_decode_ways_test.cc index fa6e767..2cedff2 100644 --- a/tests/0004_dynamic_programming/0007_decode_ways_test.cc +++ b/tests/0004_dynamic_programming/0007_decode_ways_test.cc @@ -1,7 +1,7 @@ #include #include "0007_decode_ways.h" -namespace decode_ways +namespace dsa::decode_ways { TEST(decodeWays, recursionTest01) { diff --git a/tests/0004_dynamic_programming/0008_tiling_problem_test.cc b/tests/0004_dynamic_programming/0008_tiling_problem_test.cc index 1f2ccf6..2ec9d03 100644 --- a/tests/0004_dynamic_programming/0008_tiling_problem_test.cc +++ b/tests/0004_dynamic_programming/0008_tiling_problem_test.cc @@ -1,7 +1,7 @@ #include #include "0008_tiling_problem.h" -namespace tiling_problem +namespace dsa::tiling_problem { TEST(tilingProblem, recursionTest01) { diff --git a/tests/0004_dynamic_programming/0009_friends_pairing_problem_test.cc b/tests/0004_dynamic_programming/0009_friends_pairing_problem_test.cc index bcda5b2..5d47716 100644 --- a/tests/0004_dynamic_programming/0009_friends_pairing_problem_test.cc +++ b/tests/0004_dynamic_programming/0009_friends_pairing_problem_test.cc @@ -1,7 +1,7 @@ #include #include "0009_friends_pairing_problem.h" -namespace friends_pairing_problem +namespace dsa::friends_pairing_problem { TEST(friendsPairingProblemDynamicProgrammingTest, recursiveCountFriendsPairingsTest1) { diff --git a/tests/0004_dynamic_programming/0010_ways_to_cover_distance_test.cc b/tests/0004_dynamic_programming/0010_ways_to_cover_distance_test.cc index 0895315..e54bfcf 100644 --- a/tests/0004_dynamic_programming/0010_ways_to_cover_distance_test.cc +++ b/tests/0004_dynamic_programming/0010_ways_to_cover_distance_test.cc @@ -1,7 +1,7 @@ #include #include "0010_ways_to_cover_distance.h" -namespace ways_to_cover_distance +namespace dsa::ways_to_cover_distance { TEST(waysToCoverDistanceTest, recursiveWaysToCoverDistance1) { diff --git a/tests/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order_test.cc b/tests/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order_test.cc index 0ad3a15..2e5b8c8 100644 --- a/tests/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order_test.cc +++ b/tests/0004_dynamic_programming/0011_count_ways_to_reach_nth_stair_include_order_test.cc @@ -1,7 +1,7 @@ #include #include "0011_count_ways_to_reach_nth_stair_include_order.h" -namespace count_ways_to_reach_nth_stair_include_order +namespace dsa::count_ways_to_reach_nth_stair_include_order { TEST(countWaysToReachNthStairIncludeOrderTest, recursiveCountWaysToReachNthStairIncludeOrder1) { diff --git a/tests/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order_test.cc b/tests/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order_test.cc index d14f280..301f771 100644 --- a/tests/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order_test.cc +++ b/tests/0004_dynamic_programming/0012_count_ways_to_reach_nth_stair_exclude_order_test.cc @@ -1,7 +1,7 @@ #include #include "0012_count_ways_to_reach_nth_stair_exclude_order.h" -namespace count_ways_to_reach_nth_stair_exclude_order +namespace dsa::count_ways_to_reach_nth_stair_exclude_order { TEST(countWaysToReachNthStairExcludeOrderTest, recursiveCountWaysToReachNthStairExcludeOrder1) { diff --git a/tests/0004_dynamic_programming/0013_knapsack_problem_test.cc b/tests/0004_dynamic_programming/0013_knapsack_problem_test.cc index bc2a7bc..f114a8a 100644 --- a/tests/0004_dynamic_programming/0013_knapsack_problem_test.cc +++ b/tests/0004_dynamic_programming/0013_knapsack_problem_test.cc @@ -1,7 +1,7 @@ #include #include "0013_knapsack_problem.h" -namespace knapsack_problem +namespace dsa::knapsack_problem { TEST(knapsackProblemTest, recursiveKnapsackProblemTest01) { diff --git a/tests/0004_dynamic_programming/0014_subset_sum_problem_test.cc b/tests/0004_dynamic_programming/0014_subset_sum_problem_test.cc index 2206f21..d1e8c0c 100644 --- a/tests/0004_dynamic_programming/0014_subset_sum_problem_test.cc +++ b/tests/0004_dynamic_programming/0014_subset_sum_problem_test.cc @@ -1,7 +1,7 @@ #include #include "0014_subset_sum_problem.h" -namespace subset_sum_problem +namespace dsa::subset_sum_problem { TEST(subsetSumProblemTest, recursiveSubsetSumTest) { diff --git a/tests/0004_dynamic_programming/0015_count_subsets_for_sum_test.cc b/tests/0004_dynamic_programming/0015_count_subsets_for_sum_test.cc index c0afa36..26450ef 100644 --- a/tests/0004_dynamic_programming/0015_count_subsets_for_sum_test.cc +++ b/tests/0004_dynamic_programming/0015_count_subsets_for_sum_test.cc @@ -1,7 +1,7 @@ #include #include "0015_count_subsets_for_sum.h" -namespace count_subsets_for_sum +namespace dsa::count_subsets_for_sum { TEST(countSubsetsForSum, recursiveCountSubsetSum) { diff --git a/tests/0004_dynamic_programming/0016_partition_equal_subset_sum_test.cc b/tests/0004_dynamic_programming/0016_partition_equal_subset_sum_test.cc index 7d69351..cf7092b 100644 --- a/tests/0004_dynamic_programming/0016_partition_equal_subset_sum_test.cc +++ b/tests/0004_dynamic_programming/0016_partition_equal_subset_sum_test.cc @@ -1,7 +1,7 @@ #include #include "0016_partition_equal_subset_sum.h" -namespace partition_equal_subset_sum +namespace dsa::partition_equal_subset_sum { TEST(partitionEqualSubsetSum, recursivePartitionEqualSubsetSum) { diff --git a/tests/0004_dynamic_programming/0017_target_sum_test.cc b/tests/0004_dynamic_programming/0017_target_sum_test.cc index 1d4b393..32cd6b3 100644 --- a/tests/0004_dynamic_programming/0017_target_sum_test.cc +++ b/tests/0004_dynamic_programming/0017_target_sum_test.cc @@ -1,7 +1,7 @@ #include #include "0017_target_sum.h" -namespace target_sum +namespace dsa::target_sum { TEST(targetSum, recursiveSolutionTest_ValidInput_ReturnsCorrectResult) { From 91d68fddc667b8b5b31ba58385d26cb57dd4460f Mon Sep 17 00:00:00 2001 From: Debashis Nandi Date: Mon, 15 Jun 2026 02:21:07 +0530 Subject: [PATCH 13/13] fix: dag test suite name updated --- .../0010_directed_acyclic_graph_shortest_path_test.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/0003_graph/0010_directed_acyclic_graph_shortest_path_test.cc b/tests/0003_graph/0010_directed_acyclic_graph_shortest_path_test.cc index ec57e54..9e1b3a1 100644 --- a/tests/0003_graph/0010_directed_acyclic_graph_shortest_path_test.cc +++ b/tests/0003_graph/0010_directed_acyclic_graph_shortest_path_test.cc @@ -7,7 +7,7 @@ namespace dsa::directed_acyclic_graph_shortest_path UnitTestHelper unitTestHelper; // Test for simple Graph - TEST(dAGTest, simpleGraph) + TEST(directedAcyclicGraphShortestPath, shortestPath) { Graph graph;