Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: update to CXX standard 17 and add CMakeLists file to directories without them #2746

Merged
merged 50 commits into from
Nov 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
50 commits
Select commit Hold shift + click to select a range
ed217d7
chore: add cache and build comment to git ignore
realstealthninja Oct 1, 2024
79dd912
fix: add cmakelists to dynamic programming
realstealthninja Oct 1, 2024
b6ac253
fix: add cmakelists to greedy_algorithms
realstealthninja Oct 1, 2024
3a442a0
fix: add cmakelists to operations_on_datastructures
realstealthninja Oct 1, 2024
c98fe80
fix: add cmakelists to range_queries
realstealthninja Oct 1, 2024
2b40841
fix: add `dynamic_programmin`, `greedy_algorithms`, `range_queries` a…
realstealthninja Oct 1, 2024
939ca4a
fix: init of transform_reduce in dynamic_programming
realstealthninja Oct 1, 2024
8ed74c6
fix: add an include for functional in catalan_numbers
realstealthninja Oct 1, 2024
e3ae1d1
chore: bump CXX standard to 20
realstealthninja Oct 1, 2024
4e524df
revert: bump CXX standard to 20
realstealthninja Oct 1, 2024
382e9b2
chore: bump c++ version to 17 and add justification
realstealthninja Oct 1, 2024
a71fa6d
fix: compilation error in catalan numbers
realstealthninja Oct 1, 2024
8d260bf
fix: add <set> header to longest increasing subsequence nlogn
realstealthninja Oct 1, 2024
01cb061
fix: add cmath & algorithm header to mo.cpp
realstealthninja Oct 1, 2024
cf96959
fix: remove register key word from fast integer
realstealthninja Oct 1, 2024
7ca7b58
fix: replace using namespace std with std::cin and std::cout
realstealthninja Oct 1, 2024
bddae75
docs: typo in c++17
realstealthninja Oct 1, 2024
48f03b2
fix: memory leak in bellman_ford
realstealthninja Oct 1, 2024
7da9561
fix: typo in bellman_ford
realstealthninja Oct 1, 2024
c7064a6
fix: typo in word_break
realstealthninja Oct 1, 2024
7984cd4
fix: dynamic array in coin_change
realstealthninja Oct 1, 2024
efea5c6
fix dynamic array in egg_dropping puzzle
realstealthninja Oct 1, 2024
747657d
Merge branch 'master' into cmake
realstealthninja Oct 4, 2024
153a0dc
chore: remove unnecessary comment
realstealthninja Oct 4, 2024
973eb90
fix: add vla to be an error
realstealthninja Oct 4, 2024
3bed814
chore: add extra warnings
realstealthninja Oct 4, 2024
49e9269
fix: use add_compile options instead of set()
realstealthninja Oct 4, 2024
46f423c
fix: compile options are not strings
realstealthninja Oct 4, 2024
b796161
fix: vla in floyd_warshall
realstealthninja Oct 4, 2024
3091f15
fix: vla in egg_dropping_puzzel
realstealthninja Oct 4, 2024
94ca2df
fix: vla in coin_change
realstealthninja Oct 4, 2024
f7154b7
fix: vla in edit_distance
realstealthninja Oct 4, 2024
4db1f40
fix: vla in floyd_warshall
realstealthninja Oct 4, 2024
2b278e9
feat: remove kadane and replace it with kadane2
realstealthninja Oct 4, 2024
a0abcbe
fix: vla in longest_common_subsequence
realstealthninja Oct 4, 2024
77e7eba
fix: int overflow in floyd_warshall
realstealthninja Oct 4, 2024
1c2e186
fix: vla in lisnlogn
realstealthninja Oct 4, 2024
a16a4bc
fix: use const vector& instead of array
realstealthninja Oct 4, 2024
6a55384
fix: use dynamic array instead of vla in knapsack
realstealthninja Oct 4, 2024
1ed8329
fix: use of and in msvc is unsupported by default adding permissive f…
realstealthninja Oct 4, 2024
7a16c31
test: make executables the tests themselves
realstealthninja Oct 4, 2024
40be378
Revert "test: make executables the tests themselves"
realstealthninja Oct 4, 2024
334fb7d
Merge branch 'master' into cmake
realstealthninja Oct 5, 2024
79d40fb
fix: make dist constant in print
realstealthninja Oct 5, 2024
62faa00
Merge branch 'master' into cmake
realstealthninja Oct 5, 2024
b4adae8
Merge branch 'master' into cmake
realstealthninja Oct 6, 2024
c4fa878
Merge branch 'master' into cmake
realstealthninja Nov 4, 2024
e004861
Merge branch 'master' into cmake
realstealthninja Nov 4, 2024
902e297
fix: namespace issue in unbounded_0_1
realstealthninja Nov 4, 2024
8e329d3
fix: include cstdint to fix compilation
realstealthninja Nov 4, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,9 @@ a.out
*.out
*.app

# Cache
.cache/

# Build
build/
git_diff.txt
17 changes: 11 additions & 6 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,17 @@ project(Algorithms_in_C++
DESCRIPTION "Set of algorithms implemented in C++."
)

# set(CMAKE_CXX_CPPLINT "~/anaconda3/bin/cpplint --filter=-legal/copyright --std=c++11")
# find_program(CLANG_FORMAT "clang-format")

set(CMAKE_CXX_STANDARD 11)
# C++ standard
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# Additional warnings and errors
if(MSVC)
# set(CMAKE_CXX_STANDARD 14)
add_compile_definitions(_CRT_SECURE_NO_WARNINGS)
endif(MSVC)
add_compile_options(/W4 /permissive-)
else()
add_compile_options(-Wall -Wextra -Wno-register -Werror=vla)
endif()

option(USE_OPENMP "flag to use OpenMP for multithreading" ON)
if(USE_OPENMP)
Expand All @@ -38,6 +39,10 @@ add_subdirectory(graphics)
add_subdirectory(probability)
add_subdirectory(backtracking)
add_subdirectory(bit_manipulation)
add_subdirectory(dynamic_programming)
add_subdirectory(greedy_algorithms)
add_subdirectory(range_queries)
add_subdirectory(operations_on_datastructures)
add_subdirectory(data_structures)
add_subdirectory(machine_learning)
add_subdirectory(numerical_methods)
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ This repository is a collection of open-source implementation of a variety of al
* Well documented source code with detailed explanations provide a valuable resource for educators and students alike.
* Each source code is atomic using [STL classes](https://en.wikipedia.org/wiki/Standard_Template_Library) and _no external libraries_ are required for their compilation and execution. Thus, the fundamentals of the algorithms can be studied in much depth.
* Source codes are [compiled and tested](https://github.com/TheAlgorithms/C-Plus-Plus/actions?query=workflow%3A%22Awesome+CI+Workflow%22) for every commit on the latest versions of three major operating systems viz., Windows, MacOS, and Ubuntu (Linux) using MSVC 19 2022, AppleClang 14.0.0, and GNU 11.3.0 respectively.
* Strict adherence to [C++11](https://en.wikipedia.org/wiki/C%2B%2B11) standard ensures portability of code to embedded systems as well like ESP32, ARM Cortex, etc. with little to no changes.
* Strict adherence to [C++17](https://en.wikipedia.org/wiki/C%2B%2B17) standard ensures portability of code to embedded systems as well like [ESP32](https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-guides/cplusplus.html#c-language-standard), [ARM Cortex](https://developer.arm.com/documentation/101458/2404/Standards-support/Supported-C-C---standards-in-Arm-C-C---Compiler), etc. with little to no changes.
* Self-checks within programs ensure correct implementations with confidence.
* Modular implementations and OpenSource licensing enable the functions to be utilized conveniently in other applications.

Expand Down
18 changes: 18 additions & 0 deletions dynamic_programming/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# If necessary, use the RELATIVE flag, otherwise each source file may be listed
# with full pathname. RELATIVE may makes it easier to extract an executable name
# automatically.
file( GLOB APP_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp )
# file( GLOB APP_SOURCES ${CMAKE_SOURCE_DIR}/*.c )
# AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR} APP_SOURCES)
foreach( testsourcefile ${APP_SOURCES} )
# I used a simple string replace, to cut off .cpp.
string( REPLACE ".cpp" "" testname ${testsourcefile} )
add_executable( ${testname} ${testsourcefile} )

set_target_properties(${testname} PROPERTIES LINKER_LANGUAGE CXX)
if(OpenMP_CXX_FOUND)
target_link_libraries(${testname} OpenMP::OpenMP_CXX)
endif()
install(TARGETS ${testname} DESTINATION "bin/dynamic_programming")

endforeach( testsourcefile ${APP_SOURCES} )
1 change: 1 addition & 0 deletions dynamic_programming/abbreviation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
*/

#include <cassert> /// for `assert`
#include <cstdint> /// for `std::uint32_t`
#include <iostream> /// for IO operations
#include <string> /// for `std::string` library
#include <vector> /// for `std::vector` STL library
Expand Down
12 changes: 7 additions & 5 deletions dynamic_programming/bellman_ford.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#include <limits.h>
#include <climits>
#include <iostream>
#include <vector>

using namespace std;

Expand All @@ -13,13 +14,13 @@ class Edge {
class Graph {
public:
int vertexNum, edgeNum;
Edge *edges;
std::vector<Edge> edges;

// Constructs a graph with V vertices and E edges
Graph(int V, int E) {
this->vertexNum = V;
this->edgeNum = E;
this->edges = (Edge *)malloc(E * sizeof(Edge));
this->edges.reserve(E);
}

// Adds the given edge to the graph
Expand All @@ -36,7 +37,7 @@ class Graph {
};

// Utility function to print distances
void print(int dist[], int V) {
void print(const std::vector<int>& dist, int V) {
cout << "\nVertex Distance" << endl;
for (int i = 0; i < V; i++) {
if (dist[i] != INT_MAX)
Expand All @@ -52,7 +53,8 @@ void print(int dist[], int V) {
void BellmanFord(Graph graph, int src) {
int V = graph.vertexNum;
int E = graph.edgeNum;
int dist[V];
std::vector<int> dist;
dist.reserve(E);

// Initialize distances array as INF for all except source
// Intialize source as zero
Expand Down
13 changes: 7 additions & 6 deletions dynamic_programming/catalan_numbers.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@
https://oeis.org/A000108/
*/

#include <cassert> /// for assert
#include <cstdint> /// for std::uint64_t
#include <cstdlib> /// for std::size_t
#include <numeric> /// for std::transform_reduce
#include <vector> /// for std::vector
#include <cassert> /// for assert
#include <cstdint> /// for std::uint64_t
#include <cstdlib> /// for std::size_t
#include <functional> /// for std::plus & std::multiplies
#include <numeric> /// for std::transform_reduce
#include <vector> /// for std::vector

/**
* @brief computes and caches Catalan numbers
Expand All @@ -24,7 +25,7 @@ class catalan_numbers {

value_type compute_next() {
return std::transform_reduce(known.begin(), known.end(), known.rbegin(),
static_cast<value_type>(), std::plus<>(),
static_cast<value_type>(0), std::plus<>(),
std::multiplies<>());
}

Expand Down
3 changes: 2 additions & 1 deletion dynamic_programming/coin_change.cpp
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
#include <climits>
#include <iostream>
#include <vector>
using namespace std;

// Function to find the Minimum number of coins required to get Sum S
int findMinCoins(int arr[], int n, int N) {
// dp[i] = no of coins required to get a total of i
int dp[N + 1];
std::vector<int> dp(N + 1);

// 0 coins are needed for 0 sum

Expand Down
13 changes: 7 additions & 6 deletions dynamic_programming/cut_rod.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
#include <array>
#include <cassert>
#include <climits>
#include <cstdint>
#include <iostream>
/**
* @namespace dynamic_programming
Expand Down Expand Up @@ -70,8 +71,8 @@ int maxProfitByCuttingRod(const std::array<int, T> &price, const uint64_t &n) {
*/
static void test() {
// Test 1
const int16_t n1 = 8; // size of rod
std::array<int32_t, n1> price1 = {1,2,4,6,8,45,21,9}; // price array
const int16_t n1 = 8; // size of rod
std::array<int32_t, n1> price1 = {1, 2, 4, 6, 8, 45, 21, 9}; // price array
const int64_t max_profit1 =
dynamic_programming::cut_rod::maxProfitByCuttingRod(price1, n1);
const int64_t expected_max_profit1 = 47;
Expand All @@ -86,15 +87,15 @@ static void test() {
31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50};

const int64_t max_profit2=
const int64_t max_profit2 =
dynamic_programming::cut_rod::maxProfitByCuttingRod(price2, n2);
const int32_t expected_max_profit2 = 90;
assert(max_profit2 == expected_max_profit2);
std::cout << "Maximum profit with " << n2 << " inch road is " << max_profit2
<< std::endl;
// Test 3
const int16_t n3 = 5; // size of rod
std::array<int32_t, n3> price3 = {2,9,17,23,45}; // price array
// Test 3
const int16_t n3 = 5; // size of rod
std::array<int32_t, n3> price3 = {2, 9, 17, 23, 45}; // price array
const int64_t max_profit3 =
dynamic_programming::cut_rod::maxProfitByCuttingRod(price3, n3);
const int64_t expected_max_profit3 = 45;
Expand Down
3 changes: 2 additions & 1 deletion dynamic_programming/edit_distance.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int min(int x, int y, int z) { return min(min(x, y), z); }
Expand Down Expand Up @@ -46,7 +47,7 @@ int editDist(string str1, string str2, int m, int n) {
*/
int editDistDP(string str1, string str2, int m, int n) {
// Create Table for SubProblems
int dp[m + 1][n + 1];
std::vector<std::vector<int> > dp(m + 1, std::vector<int>(n + 1));

// Fill d[][] in bottom up manner
for (int i = 0; i <= m; i++) {
Expand Down
5 changes: 4 additions & 1 deletion dynamic_programming/egg_dropping_puzzle.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@

#include <climits>
#include <iostream>
#include <vector>

using namespace std;

int eggDrop(int n, int k) {
int eggFloor[n + 1][k + 1];
std::vector<std::vector<int> > eggFloor(n + 1, std::vector<int>(k + 1));

int result;

for (int i = 1; i <= n; i++) {
Expand Down
15 changes: 9 additions & 6 deletions dynamic_programming/floyd_warshall.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#include <climits>
#include <cstddef>
#include <iostream>
#include <string>
#include <vector>

using std::cin;
using std::cout;
Expand All @@ -24,7 +25,9 @@ class Graph {
}

~Graph() {
for (int i = 0; i < vertexNum; i++) delete[] edges[i];
for (int i = 0; i < vertexNum; i++) {
delete[] edges[i];
}
delete[] edges;
}

Expand All @@ -35,7 +38,7 @@ class Graph {
};

// Utility function to print distances
void print(int dist[], int V) {
void print(const std::vector<int>& dist, int V) {
cout << "\nThe Distance matrix for Floyd - Warshall" << endl;
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
Expand All @@ -52,8 +55,8 @@ void print(int dist[], int V) {
// The main function that finds the shortest path from a vertex
// to all other vertices using Floyd-Warshall Algorithm.
void FloydWarshall(Graph graph) {
int V = graph.vertexNum;
int dist[V][V];
std::size_t V = graph.vertexNum;
std::vector<std::vector<int> > dist(V, std::vector<int>(V));

// Initialise distance array
for (int i = 0; i < V; i++)
Expand All @@ -76,7 +79,7 @@ void FloydWarshall(Graph graph) {
dist[i][j] = dist[i][k] + dist[k][j];

// Convert 2d array to 1d array for print
int dist1d[V * V];
std::vector<int> dist1d(V * V);
Fixed Show fixed Hide fixed
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++) dist1d[i * V + j] = dist[i][j];

Expand Down
2 changes: 1 addition & 1 deletion dynamic_programming/house_robber.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@

#include <cassert> /// for assert
#include <climits> /// for std::max
#include <cstdint> /// for std::uint32_t
#include <iostream> /// for io operations
#include <vector> /// for std::vector

/**
* @namespace dynamic_programming
* @brief Dynamic Programming algorithms
Expand Down
85 changes: 65 additions & 20 deletions dynamic_programming/kadane.cpp
Original file line number Diff line number Diff line change
@@ -1,29 +1,74 @@
/**
* @file
* @brief Implementation of [Kadane
* Algorithm](https://en.wikipedia.org/wiki/Kadane%27s_algorithm)
*
* @details
* Kadane algorithm is used to find the maximum sum subarray in an array and
* maximum sum subarray problem is the task of finding a contiguous subarray
* with the largest sum
*
* ### Algorithm
* The simple idea of the algorithm is to search for all positive
* contiguous segments of the array and keep track of maximum sum contiguous
* segment among all positive segments(curr_sum is used for this)
* Each time we get a positive sum we compare it with max_sum and update max_sum
* if it is greater than curr_sum
*
* @author [Ayush Singh](https://github.com/ayush523)
*/
#include <array>
#include <climits>
#include <iostream>

int maxSubArraySum(int a[], int size) {
int max_so_far = INT_MIN, max_ending_here = 0;

for (int i = 0; i < size; i++) {
max_ending_here = max_ending_here + a[i];
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;

if (max_ending_here < 0)
max_ending_here = 0;
/**
* @namespace dynamic_programming
* @brief Dynamic Programming algorithms
*/
namespace dynamic_programming {
/**
* @namespace kadane
* @brief Functions for
* [Kadane](https://en.wikipedia.org/wiki/Kadane%27s_algorithm) algorithm.
*/
namespace kadane {
/**
* @brief maxSubArray function is used to calculate the maximum sum subarray
* and returns the value of maximum sum which is stored in the variable max_sum
* @tparam N number of array size
* @param n array where numbers are saved
* @returns the value of maximum subarray sum
*/
template <size_t N>
int maxSubArray(const std::array<int, N> &n) {
int curr_sum =
0; // declaring a variable named as curr_sum and initialized it to 0
int max_sum = INT_MIN; // Initialized max_sum to INT_MIN
for (int i : n) { // for loop to iterate over the elements of the array
curr_sum += n[i];
max_sum = std::max(max_sum, curr_sum); // getting the maximum value
curr_sum = std::max(curr_sum, 0); // updating the value of curr_sum
}
return max_so_far;
return max_sum; // returning the value of max_sum
}
} // namespace kadane
} // namespace dynamic_programming

/**
* @brief Main function
* @returns 0 on exit
*/
int main() {
int n, i;
std::cout << "Enter the number of elements \n";
std::cin >> n;
int a[n]; // NOLINT
for (i = 0; i < n; i++) {
std::cin >> a[i];
const int N = 5;
std::array<int, N> n{}; // declaring array
// taking values of elements from user
for (int i = 0; i < n.size(); i++) {
std::cout << "Enter value of n[" << i << "]"
<< "\n";
std::cin >> n[i];
}
int max_sum = maxSubArraySum(a, n);
std::cout << "Maximum contiguous sum is " << max_sum;
int max_sum = dynamic_programming::kadane::maxSubArray<N>(
n); // calling maxSubArray function
std::cout << "Maximum subarray sum is " << max_sum; // Printing the answer

return 0;
}
Loading
Loading