Skip to content

Commit 0d766b0

Browse files
feat: update to CXX standard 17 and add CMakeLists file to directories without them (#2746)
* chore: add cache and build comment to git ignore * fix: add cmakelists to dynamic programming * fix: add cmakelists to greedy_algorithms * fix: add cmakelists to operations_on_datastructures * fix: add cmakelists to range_queries * fix: add `dynamic_programmin`, `greedy_algorithms`, `range_queries` and `operations_on_datastructures` subdirectories to cmakelists.txt * fix: init of transform_reduce in dynamic_programming * fix: add an include for functional in catalan_numbers * chore: bump CXX standard to 20 * revert: bump CXX standard to 20 * chore: bump c++ version to 17 and add justification Arm supports c++ 17 Esp32 supports c++ 23 decision was made to be 17 because it seemed to offer the best combatability * fix: compilation error in catalan numbers * fix: add <set> header to longest increasing subsequence nlogn * fix: add cmath & algorithm header to mo.cpp * fix: remove register key word from fast integer * fix: replace using namespace std with std::cin and std::cout * docs: typo in c++17 * fix: memory leak in bellman_ford * fix: typo in bellman_ford * fix: typo in word_break * fix: dynamic array in coin_change * fix dynamic array in egg_dropping puzzle * chore: remove unnecessary comment * fix: add vla to be an error * chore: add extra warnings * fix: use add_compile options instead of set() * fix: compile options are not strings * fix: vla in floyd_warshall * fix: vla in egg_dropping_puzzel * fix: vla in coin_change * fix: vla in edit_distance * fix: vla in floyd_warshall * feat: remove kadane and replace it with kadane2 * fix: vla in longest_common_subsequence * fix: int overflow in floyd_warshall * fix: vla in lisnlogn * fix: use const vector& instead of array * fix: use dynamic array instead of vla in knapsack * fix: use of and in msvc is unsupported by default adding permissive flag fixes it * test: make executables the tests themselves * Revert "test: make executables the tests themselves" This reverts commit 7a16c31. * fix: make dist constant in print * fix: namespace issue in unbounded_0_1 * fix: include cstdint to fix compilation
1 parent c6af943 commit 0d766b0

35 files changed

+377
-268
lines changed

.gitignore

+4
Original file line numberDiff line numberDiff line change
@@ -34,5 +34,9 @@ a.out
3434
*.out
3535
*.app
3636

37+
# Cache
38+
.cache/
39+
40+
# Build
3741
build/
3842
git_diff.txt

CMakeLists.txt

+11-6
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,17 @@ project(Algorithms_in_C++
55
DESCRIPTION "Set of algorithms implemented in C++."
66
)
77

8-
# set(CMAKE_CXX_CPPLINT "~/anaconda3/bin/cpplint --filter=-legal/copyright --std=c++11")
9-
# find_program(CLANG_FORMAT "clang-format")
10-
11-
set(CMAKE_CXX_STANDARD 11)
8+
# C++ standard
9+
set(CMAKE_CXX_STANDARD 17)
1210
set(CMAKE_CXX_STANDARD_REQUIRED ON)
1311

12+
# Additional warnings and errors
1413
if(MSVC)
15-
# set(CMAKE_CXX_STANDARD 14)
1614
add_compile_definitions(_CRT_SECURE_NO_WARNINGS)
17-
endif(MSVC)
15+
add_compile_options(/W4 /permissive-)
16+
else()
17+
add_compile_options(-Wall -Wextra -Wno-register -Werror=vla)
18+
endif()
1819

1920
option(USE_OPENMP "flag to use OpenMP for multithreading" ON)
2021
if(USE_OPENMP)
@@ -38,6 +39,10 @@ add_subdirectory(graphics)
3839
add_subdirectory(probability)
3940
add_subdirectory(backtracking)
4041
add_subdirectory(bit_manipulation)
42+
add_subdirectory(dynamic_programming)
43+
add_subdirectory(greedy_algorithms)
44+
add_subdirectory(range_queries)
45+
add_subdirectory(operations_on_datastructures)
4146
add_subdirectory(data_structures)
4247
add_subdirectory(machine_learning)
4348
add_subdirectory(numerical_methods)

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ This repository is a collection of open-source implementation of a variety of al
2222
* Well documented source code with detailed explanations provide a valuable resource for educators and students alike.
2323
* 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.
2424
* 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.
25-
* 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.
25+
* 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.
2626
* Self-checks within programs ensure correct implementations with confidence.
2727
* Modular implementations and OpenSource licensing enable the functions to be utilized conveniently in other applications.
2828

dynamic_programming/CMakeLists.txt

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# If necessary, use the RELATIVE flag, otherwise each source file may be listed
2+
# with full pathname. RELATIVE may makes it easier to extract an executable name
3+
# automatically.
4+
file( GLOB APP_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp )
5+
# file( GLOB APP_SOURCES ${CMAKE_SOURCE_DIR}/*.c )
6+
# AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR} APP_SOURCES)
7+
foreach( testsourcefile ${APP_SOURCES} )
8+
# I used a simple string replace, to cut off .cpp.
9+
string( REPLACE ".cpp" "" testname ${testsourcefile} )
10+
add_executable( ${testname} ${testsourcefile} )
11+
12+
set_target_properties(${testname} PROPERTIES LINKER_LANGUAGE CXX)
13+
if(OpenMP_CXX_FOUND)
14+
target_link_libraries(${testname} OpenMP::OpenMP_CXX)
15+
endif()
16+
install(TARGETS ${testname} DESTINATION "bin/dynamic_programming")
17+
18+
endforeach( testsourcefile ${APP_SOURCES} )

dynamic_programming/abbreviation.cpp

+1
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
*/
2525

2626
#include <cassert> /// for `assert`
27+
#include <cstdint> /// for `std::uint32_t`
2728
#include <iostream> /// for IO operations
2829
#include <string> /// for `std::string` library
2930
#include <vector> /// for `std::vector` STL library

dynamic_programming/bellman_ford.cpp

+7-5
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
#include <limits.h>
1+
#include <climits>
22
#include <iostream>
3+
#include <vector>
34

45
using namespace std;
56

@@ -13,13 +14,13 @@ class Edge {
1314
class Graph {
1415
public:
1516
int vertexNum, edgeNum;
16-
Edge *edges;
17+
std::vector<Edge> edges;
1718

1819
// Constructs a graph with V vertices and E edges
1920
Graph(int V, int E) {
2021
this->vertexNum = V;
2122
this->edgeNum = E;
22-
this->edges = (Edge *)malloc(E * sizeof(Edge));
23+
this->edges.reserve(E);
2324
}
2425

2526
// Adds the given edge to the graph
@@ -36,7 +37,7 @@ class Graph {
3637
};
3738

3839
// Utility function to print distances
39-
void print(int dist[], int V) {
40+
void print(const std::vector<int>& dist, int V) {
4041
cout << "\nVertex Distance" << endl;
4142
for (int i = 0; i < V; i++) {
4243
if (dist[i] != INT_MAX)
@@ -52,7 +53,8 @@ void print(int dist[], int V) {
5253
void BellmanFord(Graph graph, int src) {
5354
int V = graph.vertexNum;
5455
int E = graph.edgeNum;
55-
int dist[V];
56+
std::vector<int> dist;
57+
dist.reserve(E);
5658

5759
// Initialize distances array as INF for all except source
5860
// Intialize source as zero

dynamic_programming/catalan_numbers.cpp

+7-6
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,12 @@
99
https://oeis.org/A000108/
1010
*/
1111

12-
#include <cassert> /// for assert
13-
#include <cstdint> /// for std::uint64_t
14-
#include <cstdlib> /// for std::size_t
15-
#include <numeric> /// for std::transform_reduce
16-
#include <vector> /// for std::vector
12+
#include <cassert> /// for assert
13+
#include <cstdint> /// for std::uint64_t
14+
#include <cstdlib> /// for std::size_t
15+
#include <functional> /// for std::plus & std::multiplies
16+
#include <numeric> /// for std::transform_reduce
17+
#include <vector> /// for std::vector
1718

1819
/**
1920
* @brief computes and caches Catalan numbers
@@ -24,7 +25,7 @@ class catalan_numbers {
2425

2526
value_type compute_next() {
2627
return std::transform_reduce(known.begin(), known.end(), known.rbegin(),
27-
static_cast<value_type>(), std::plus<>(),
28+
static_cast<value_type>(0), std::plus<>(),
2829
std::multiplies<>());
2930
}
3031

dynamic_programming/coin_change.cpp

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
#include <climits>
22
#include <iostream>
3+
#include <vector>
34
using namespace std;
45

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

1011
// 0 coins are needed for 0 sum
1112

dynamic_programming/cut_rod.cpp

+7-6
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
#include <array>
2222
#include <cassert>
2323
#include <climits>
24+
#include <cstdint>
2425
#include <iostream>
2526
/**
2627
* @namespace dynamic_programming
@@ -70,8 +71,8 @@ int maxProfitByCuttingRod(const std::array<int, T> &price, const uint64_t &n) {
7071
*/
7172
static void test() {
7273
// Test 1
73-
const int16_t n1 = 8; // size of rod
74-
std::array<int32_t, n1> price1 = {1,2,4,6,8,45,21,9}; // price array
74+
const int16_t n1 = 8; // size of rod
75+
std::array<int32_t, n1> price1 = {1, 2, 4, 6, 8, 45, 21, 9}; // price array
7576
const int64_t max_profit1 =
7677
dynamic_programming::cut_rod::maxProfitByCuttingRod(price1, n1);
7778
const int64_t expected_max_profit1 = 47;
@@ -86,15 +87,15 @@ static void test() {
8687
31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
8788
41, 42, 43, 44, 45, 46, 47, 48, 49, 50};
8889

89-
const int64_t max_profit2=
90+
const int64_t max_profit2 =
9091
dynamic_programming::cut_rod::maxProfitByCuttingRod(price2, n2);
9192
const int32_t expected_max_profit2 = 90;
9293
assert(max_profit2 == expected_max_profit2);
9394
std::cout << "Maximum profit with " << n2 << " inch road is " << max_profit2
9495
<< std::endl;
95-
// Test 3
96-
const int16_t n3 = 5; // size of rod
97-
std::array<int32_t, n3> price3 = {2,9,17,23,45}; // price array
96+
// Test 3
97+
const int16_t n3 = 5; // size of rod
98+
std::array<int32_t, n3> price3 = {2, 9, 17, 23, 45}; // price array
9899
const int64_t max_profit3 =
99100
dynamic_programming::cut_rod::maxProfitByCuttingRod(price3, n3);
100101
const int64_t expected_max_profit3 = 45;

dynamic_programming/edit_distance.cpp

+2-1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
#include <iostream>
1515
#include <string>
16+
#include <vector>
1617
using namespace std;
1718

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

5152
// Fill d[][] in bottom up manner
5253
for (int i = 0; i <= m; i++) {

dynamic_programming/egg_dropping_puzzle.cpp

+4-1
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,13 @@
44

55
#include <climits>
66
#include <iostream>
7+
#include <vector>
8+
79
using namespace std;
810

911
int eggDrop(int n, int k) {
10-
int eggFloor[n + 1][k + 1];
12+
std::vector<std::vector<int> > eggFloor(n + 1, std::vector<int>(k + 1));
13+
1114
int result;
1215

1316
for (int i = 1; i <= n; i++) {

dynamic_programming/floyd_warshall.cpp

+9-6
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#include <climits>
2+
#include <cstddef>
23
#include <iostream>
3-
#include <string>
4+
#include <vector>
45

56
using std::cin;
67
using std::cout;
@@ -24,7 +25,9 @@ class Graph {
2425
}
2526

2627
~Graph() {
27-
for (int i = 0; i < vertexNum; i++) delete[] edges[i];
28+
for (int i = 0; i < vertexNum; i++) {
29+
delete[] edges[i];
30+
}
2831
delete[] edges;
2932
}
3033

@@ -35,7 +38,7 @@ class Graph {
3538
};
3639

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

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

7881
// Convert 2d array to 1d array for print
79-
int dist1d[V * V];
82+
std::vector<int> dist1d(V * V);
8083
for (int i = 0; i < V; i++)
8184
for (int j = 0; j < V; j++) dist1d[i * V + j] = dist[i][j];
8285

dynamic_programming/house_robber.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@
1111

1212
#include <cassert> /// for assert
1313
#include <climits> /// for std::max
14+
#include <cstdint> /// for std::uint32_t
1415
#include <iostream> /// for io operations
1516
#include <vector> /// for std::vector
16-
1717
/**
1818
* @namespace dynamic_programming
1919
* @brief Dynamic Programming algorithms

dynamic_programming/kadane.cpp

+65-20
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,74 @@
1+
/**
2+
* @file
3+
* @brief Implementation of [Kadane
4+
* Algorithm](https://en.wikipedia.org/wiki/Kadane%27s_algorithm)
5+
*
6+
* @details
7+
* Kadane algorithm is used to find the maximum sum subarray in an array and
8+
* maximum sum subarray problem is the task of finding a contiguous subarray
9+
* with the largest sum
10+
*
11+
* ### Algorithm
12+
* The simple idea of the algorithm is to search for all positive
13+
* contiguous segments of the array and keep track of maximum sum contiguous
14+
* segment among all positive segments(curr_sum is used for this)
15+
* Each time we get a positive sum we compare it with max_sum and update max_sum
16+
* if it is greater than curr_sum
17+
*
18+
* @author [Ayush Singh](https://github.com/ayush523)
19+
*/
20+
#include <array>
121
#include <climits>
222
#include <iostream>
3-
4-
int maxSubArraySum(int a[], int size) {
5-
int max_so_far = INT_MIN, max_ending_here = 0;
6-
7-
for (int i = 0; i < size; i++) {
8-
max_ending_here = max_ending_here + a[i];
9-
if (max_so_far < max_ending_here)
10-
max_so_far = max_ending_here;
11-
12-
if (max_ending_here < 0)
13-
max_ending_here = 0;
23+
/**
24+
* @namespace dynamic_programming
25+
* @brief Dynamic Programming algorithms
26+
*/
27+
namespace dynamic_programming {
28+
/**
29+
* @namespace kadane
30+
* @brief Functions for
31+
* [Kadane](https://en.wikipedia.org/wiki/Kadane%27s_algorithm) algorithm.
32+
*/
33+
namespace kadane {
34+
/**
35+
* @brief maxSubArray function is used to calculate the maximum sum subarray
36+
* and returns the value of maximum sum which is stored in the variable max_sum
37+
* @tparam N number of array size
38+
* @param n array where numbers are saved
39+
* @returns the value of maximum subarray sum
40+
*/
41+
template <size_t N>
42+
int maxSubArray(const std::array<int, N> &n) {
43+
int curr_sum =
44+
0; // declaring a variable named as curr_sum and initialized it to 0
45+
int max_sum = INT_MIN; // Initialized max_sum to INT_MIN
46+
for (int i : n) { // for loop to iterate over the elements of the array
47+
curr_sum += n[i];
48+
max_sum = std::max(max_sum, curr_sum); // getting the maximum value
49+
curr_sum = std::max(curr_sum, 0); // updating the value of curr_sum
1450
}
15-
return max_so_far;
51+
return max_sum; // returning the value of max_sum
1652
}
53+
} // namespace kadane
54+
} // namespace dynamic_programming
1755

56+
/**
57+
* @brief Main function
58+
* @returns 0 on exit
59+
*/
1860
int main() {
19-
int n, i;
20-
std::cout << "Enter the number of elements \n";
21-
std::cin >> n;
22-
int a[n]; // NOLINT
23-
for (i = 0; i < n; i++) {
24-
std::cin >> a[i];
61+
const int N = 5;
62+
std::array<int, N> n{}; // declaring array
63+
// taking values of elements from user
64+
for (int i = 0; i < n.size(); i++) {
65+
std::cout << "Enter value of n[" << i << "]"
66+
<< "\n";
67+
std::cin >> n[i];
2568
}
26-
int max_sum = maxSubArraySum(a, n);
27-
std::cout << "Maximum contiguous sum is " << max_sum;
69+
int max_sum = dynamic_programming::kadane::maxSubArray<N>(
70+
n); // calling maxSubArray function
71+
std::cout << "Maximum subarray sum is " << max_sum; // Printing the answer
72+
2873
return 0;
2974
}

0 commit comments

Comments
 (0)