From e8a0bf2c2ce4ebb155efbc3f792eaeb6ce05bbde Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 23 May 2020 19:26:11 -0400 Subject: [PATCH 001/433] compute stats of data in realtime (unknown length of data) - mean, variance and standard deviation --- math/realtime_stats.cpp | 106 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 math/realtime_stats.cpp diff --git a/math/realtime_stats.cpp b/math/realtime_stats.cpp new file mode 100644 index 00000000000..af0c54ca9e5 --- /dev/null +++ b/math/realtime_stats.cpp @@ -0,0 +1,106 @@ +#include +#include + +/** + * continuous mean and variance computance using + * first value as an approximation for the mean + **/ +template class stats_computer1 +{ +public: + void new_val(T x) + { + if (n == 0) + K = x; + n++; + T tmp = x - K; + Ex += tmp; + Ex2 += tmp * tmp; + } + + double mean() const { return K + Ex / n; } + + double variance() const { return (Ex2 - (Ex * Ex) / n) / (n - 1); } + + double std() const { return std::sqrt(this->variance()); } + + friend std::istream &operator>>(std::istream &input, stats_computer1 &stat) + { + T val; + input >> val; + stat.new_val(val); + return input; + } + +private: + unsigned int n = 0; + double Ex, Ex2; + T K; +}; + +/** + * continuous mean and variance computance using + * Welford's algorithm + **/ +template class stats_computer2 +{ +public: + void new_val(T x) + { + n++; + double delta = x - mu; + mu += delta / n; + double delta2 = x - mu; + M += delta * delta2; + } + + double mean() const { return mu; } + + double variance() const { return M / n; } + + double std() const { return std::sqrt(this->variance()); } + + friend std::istream &operator>>(std::istream &input, stats_computer2 &stat) + { + T val; + input >> val; + stat.new_val(val); + return input; + } + +private: + unsigned int n = 0; + double mu = 0, var = 0, M = 0; +}; + +int main(int argc, char **argv) +{ + std::cout + << "Enter data. Any non-numeric data will terminate the data input." + << std::endl; + + stats_computer1 stats1; + stats_computer2 stats2; + + while (1) + { + double val; + std::cout << "Enter number: "; + std::cin >> val; + if (std::cin.fail()) // check for failure to read input. Happens for + // non-numeric data + break; + stats1.new_val(val); + stats2.new_val(val); + std::cout << "\tMethod 1:" + << "\tMean: " << stats1.mean() + << "\t Variance: " << stats1.variance() + << "\t Std: " << stats1.std() << std::endl; + std::cout << "\tMethod 2:" + << "\tMean: " << stats2.mean() + << "\t Variance: " << stats2.variance() + << "\t Std: " << stats2.std() << std::endl; + } + + return 0; +} \ No newline at end of file From e5d3316ef2e3572efcd7d72a8a2af0fd5ac661c3 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 23 May 2020 19:51:18 -0400 Subject: [PATCH 002/433] fixed formatting --- math/realtime_stats.cpp | 174 +++++++++++++++++++--------------------- 1 file changed, 83 insertions(+), 91 deletions(-) diff --git a/math/realtime_stats.cpp b/math/realtime_stats.cpp index af0c54ca9e5..e1b8cfaa1cb 100644 --- a/math/realtime_stats.cpp +++ b/math/realtime_stats.cpp @@ -5,102 +5,94 @@ * continuous mean and variance computance using * first value as an approximation for the mean **/ -template class stats_computer1 -{ -public: - void new_val(T x) - { - if (n == 0) - K = x; - n++; - T tmp = x - K; - Ex += tmp; - Ex2 += tmp * tmp; - } - - double mean() const { return K + Ex / n; } - - double variance() const { return (Ex2 - (Ex * Ex) / n) / (n - 1); } - - double std() const { return std::sqrt(this->variance()); } - - friend std::istream &operator>>(std::istream &input, stats_computer1 &stat) - { - T val; - input >> val; - stat.new_val(val); - return input; - } - -private: - unsigned int n = 0; - double Ex, Ex2; - T K; +template +class stats_computer1 { + public: + void new_val(T x) { + if (n == 0) K = x; + n++; + T tmp = x - K; + Ex += tmp; + Ex2 += tmp * tmp; + } + + double mean() const { return K + Ex / n; } + + double variance() const { return (Ex2 - (Ex * Ex) / n) / (n - 1); } + + double std() const { return std::sqrt(this->variance()); } + + friend std::istream &operator>>(std::istream &input, stats_computer1 &stat) { + T val; + input >> val; + stat.new_val(val); + return input; + } + + private: + unsigned int n = 0; + double Ex, Ex2; + T K; }; /** * continuous mean and variance computance using * Welford's algorithm **/ -template class stats_computer2 -{ -public: - void new_val(T x) - { - n++; - double delta = x - mu; - mu += delta / n; - double delta2 = x - mu; - M += delta * delta2; - } - - double mean() const { return mu; } - - double variance() const { return M / n; } - - double std() const { return std::sqrt(this->variance()); } - - friend std::istream &operator>>(std::istream &input, stats_computer2 &stat) - { - T val; - input >> val; - stat.new_val(val); - return input; - } - -private: - unsigned int n = 0; - double mu = 0, var = 0, M = 0; +template +class stats_computer2 { + public: + void new_val(T x) { + n++; + double delta = x - mu; + mu += delta / n; + double delta2 = x - mu; + M += delta * delta2; + } + + double mean() const { return mu; } + + double variance() const { return M / n; } + + double std() const { return std::sqrt(this->variance()); } + + friend std::istream &operator>>(std::istream &input, stats_computer2 &stat) { + T val; + input >> val; + stat.new_val(val); + return input; + } + + private: + unsigned int n = 0; + double mu = 0, var = 0, M = 0; }; -int main(int argc, char **argv) -{ - std::cout - << "Enter data. Any non-numeric data will terminate the data input." - << std::endl; - - stats_computer1 stats1; - stats_computer2 stats2; - - while (1) - { - double val; - std::cout << "Enter number: "; - std::cin >> val; - if (std::cin.fail()) // check for failure to read input. Happens for - // non-numeric data - break; - stats1.new_val(val); - stats2.new_val(val); - std::cout << "\tMethod 1:" - << "\tMean: " << stats1.mean() - << "\t Variance: " << stats1.variance() - << "\t Std: " << stats1.std() << std::endl; - std::cout << "\tMethod 2:" - << "\tMean: " << stats2.mean() - << "\t Variance: " << stats2.variance() - << "\t Std: " << stats2.std() << std::endl; - } - - return 0; -} \ No newline at end of file +int main(int argc, char **argv) { + std::cout << "Enter data. Any non-numeric data will terminate the data input." + << std::endl; + + stats_computer1 stats1; + stats_computer2 stats2; + + while (1) { + double val; + std::cout << "Enter number: "; + std::cin >> val; + if (std::cin.fail()) // check for failure to read input. Happens for + // non-numeric data + break; + stats1.new_val(val); + stats2.new_val(val); + std::cout << "\tMethod 1:" + << "\tMean: " << stats1.mean() + << "\t Variance: " << stats1.variance() + << "\t Std: " << stats1.std() << std::endl; + std::cout << "\tMethod 2:" + << "\tMean: " << stats2.mean() + << "\t Variance: " << stats2.variance() + << "\t Std: " << stats2.std() << std::endl; + } + + return 0; +} From 9b61d570f139a93d4090aefbb60851180ea2b7a7 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 24 May 2020 13:22:55 -0400 Subject: [PATCH 003/433] rebase conflict resolved --- .vscode/settings.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 0ab2708d0fd..e2efa1634ae 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -68,4 +68,4 @@ "editor.formatOnSave": true, "editor.formatOnType": true, "editor.formatOnPaste": true -} +} \ No newline at end of file From 6156f95571809dff9fd22ff70107a9457193ffd1 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 24 May 2020 17:23:51 +0000 Subject: [PATCH 004/433] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index ddbfd06d8f5..780eea03e21 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -116,6 +116,7 @@ * [Prime Factorization](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/prime_factorization.cpp) * [Prime Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/prime_numbers.cpp) * [Primes Up To 10^8](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/primes_up_to_10^8.cpp) + * [Realtime Stats](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/realtime_stats.cpp) * [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/sieve_of_eratosthenes.cpp) * [Sqrt Double](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/sqrt_double.cpp) From 6da2b9645a935542a971ba7a499ae0144347d92d Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 24 May 2020 13:56:34 -0400 Subject: [PATCH 005/433] added missing newline character --- .vscode/settings.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index e2efa1634ae..0ab2708d0fd 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -68,4 +68,4 @@ "editor.formatOnSave": true, "editor.formatOnType": true, "editor.formatOnPaste": true -} \ No newline at end of file +} From fe0c2b8517e17b30f10c24793112ac6817bca214 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Fri, 1 May 2020 23:12:38 -0400 Subject: [PATCH 006/433] compute factorial of arbitrarily any number --- others/large_factorial.cpp | 128 +++++++++++++++++++++++++++++++++++++ 1 file changed, 128 insertions(+) create mode 100644 others/large_factorial.cpp diff --git a/others/large_factorial.cpp b/others/large_factorial.cpp new file mode 100644 index 00000000000..ef9b68feba8 --- /dev/null +++ b/others/large_factorial.cpp @@ -0,0 +1,128 @@ +#include +#include +#include + +using namespace std; + +/** + * Store large unsigned numbers as a C++ vector + * The class provides convenience functions to add a + * digit to the number, perform multiplication of + * large number with long unsigned integers. + **/ +class large_number +{ +public: + large_number() /**< initializer */ + { + _digits.push_back(1); + } + + /** + * add a digit to the large number + **/ + void add_digit(unsigned int value) + { + if (value > 9) + { + fprintf(stderr, "digit > 9!!\n"); + exit(EXIT_FAILURE); + } + + _digits.push_back(value); + } + + /** + * Get number of digits in the number + **/ + const size_t num_digits() const + { + return _digits.size(); + } + + /** + * operator over load to access the + * i^th digit conveniently and also + * assign value to it + **/ + unsigned char &operator[](size_t n) + { + return this->_digits[n]; + } + + /** + * multiply large number with another integer and + * store the result in the same large number + **/ + void multiply(const unsigned long n) + { + size_t i; + unsigned long long carry = 0, temp; + for (i = 0; i < this->num_digits(); i++) + { + temp = (*this)[i] * n; + temp += carry; + if (temp < 10) + carry = 0; + else + { + carry = temp / 10; + temp = temp % 10; + } + (*this)[i] = temp; + } + + while (carry != 0) + { + this->add_digit(carry % 10); + carry /= 10; + } + }; + + /** + * print the large number + **/ + void print() + { + for (size_t i = num_digits(); i > 0; i--) + putchar(_digits[i - 1] + '0'); + }; + +private: + vector _digits; /**< where individual digits are stored */ +}; + +/** + * Main program + **/ +int main(int argc, char *argv[]) +{ + int number, i; + + //Asks for the number/position of term in Fibonnacci sequence + if (argc == 2) + number = atoi(argv[1]); + else + { + printf("Enter the value of n(n starts from 0 ): "); + scanf("%d", &number); + } + + large_number result; + + auto start_time = chrono::high_resolution_clock::now(); + for (i = 2; i <= number; i++) + /* Multiply every number from 2 thru N */ + result.multiply(i); + auto end_time = chrono::high_resolution_clock::now(); + chrono::duration time_taken = end_time - start_time; + + cout << number << "! = "; + result.print(); + cout << endl + << "Number of digits: " << result.num_digits() << endl + << "Time taken: " << time_taken.count() << " s" + << endl; + + return 0; +} From 70cd195f307c3e68e0779a9a0b95fd950f800489 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Fri, 1 May 2020 23:31:39 -0400 Subject: [PATCH 007/433] large_factorial.cpp: added tests --- others/large_factorial.cpp | 67 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/others/large_factorial.cpp b/others/large_factorial.cpp index ef9b68feba8..2e7d8bb6679 100644 --- a/others/large_factorial.cpp +++ b/others/large_factorial.cpp @@ -92,6 +92,70 @@ class large_number vector _digits; /**< where individual digits are stored */ }; +bool test1() +{ + cout << "---- Check 1\t"; + unsigned int i, number = 10; + large_number result; + for (i = 2; i <= number; i++) + /* Multiply every number from 2 thru N */ + result.multiply(i); + + const char *known_reslt = "3628800"; + + /* check 1 */ + if (strlen(known_reslt) != result.num_digits()) + { + cerr << "Result lengths dont match! " << strlen(known_reslt) << " != " << result.num_digits() << endl; + return false; + } + + size_t N = result.num_digits(); + for (i = 0; i < N; i++) + { + if (known_reslt[i] != (result[N - i - 1] + '0')) + { + cerr << i << "^th digit mismatch! " << known_reslt[i] << " != " << result[N - i - 1] << endl; + return false; + } + } + + cout << "Passed!" << endl; + return true; +} + +bool test2() +{ + cout << "---- Check 2\t"; + unsigned int i, number = 100; + large_number result; + for (i = 2; i <= number; i++) + /* Multiply every number from 2 thru N */ + result.multiply(i); + + const char *known_reslt = "93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000"; + + /* check 1 */ + if (strlen(known_reslt) != result.num_digits()) + { + cerr << "Result lengths dont match! " << strlen(known_reslt) << " != " << result.num_digits() << endl; + return false; + } + + size_t N = result.num_digits(); + for (i = 0; i < N; i++) + { + if (known_reslt[i] != (result[N - i - 1] + '0')) + { + cerr << i << "^th digit mismatch! " << known_reslt[i] << " != " << result[N - i - 1] << endl; + return false; + } + } + + cout << "Passed!" << endl; + return true; +} + /** * Main program **/ @@ -124,5 +188,8 @@ int main(int argc, char *argv[]) << "Time taken: " << time_taken.count() << " s" << endl; + test1(); + test2(); + return 0; } From a1997776c93904f0f4d66c1a802cd1429975bcf2 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Sat, 2 May 2020 15:57:12 -0400 Subject: [PATCH 008/433] split large_number class to a separate header file --- others/large_factorial.cpp | 114 ++----------- others/large_number.h | 323 +++++++++++++++++++++++++++++++++++++ 2 files changed, 336 insertions(+), 101 deletions(-) create mode 100644 others/large_number.h diff --git a/others/large_factorial.cpp b/others/large_factorial.cpp index 2e7d8bb6679..dccdcaeab8c 100644 --- a/others/large_factorial.cpp +++ b/others/large_factorial.cpp @@ -1,97 +1,10 @@ #include +#include #include -#include +#include "large_number.h" using namespace std; -/** - * Store large unsigned numbers as a C++ vector - * The class provides convenience functions to add a - * digit to the number, perform multiplication of - * large number with long unsigned integers. - **/ -class large_number -{ -public: - large_number() /**< initializer */ - { - _digits.push_back(1); - } - - /** - * add a digit to the large number - **/ - void add_digit(unsigned int value) - { - if (value > 9) - { - fprintf(stderr, "digit > 9!!\n"); - exit(EXIT_FAILURE); - } - - _digits.push_back(value); - } - - /** - * Get number of digits in the number - **/ - const size_t num_digits() const - { - return _digits.size(); - } - - /** - * operator over load to access the - * i^th digit conveniently and also - * assign value to it - **/ - unsigned char &operator[](size_t n) - { - return this->_digits[n]; - } - - /** - * multiply large number with another integer and - * store the result in the same large number - **/ - void multiply(const unsigned long n) - { - size_t i; - unsigned long long carry = 0, temp; - for (i = 0; i < this->num_digits(); i++) - { - temp = (*this)[i] * n; - temp += carry; - if (temp < 10) - carry = 0; - else - { - carry = temp / 10; - temp = temp % 10; - } - (*this)[i] = temp; - } - - while (carry != 0) - { - this->add_digit(carry % 10); - carry /= 10; - } - }; - - /** - * print the large number - **/ - void print() - { - for (size_t i = num_digits(); i > 0; i--) - putchar(_digits[i - 1] + '0'); - }; - -private: - vector _digits; /**< where individual digits are stored */ -}; - bool test1() { cout << "---- Check 1\t"; @@ -99,7 +12,7 @@ bool test1() large_number result; for (i = 2; i <= number; i++) /* Multiply every number from 2 thru N */ - result.multiply(i); + result *= i; const char *known_reslt = "3628800"; @@ -110,12 +23,12 @@ bool test1() return false; } - size_t N = result.num_digits(); + const size_t N = result.num_digits(); for (i = 0; i < N; i++) { - if (known_reslt[i] != (result[N - i - 1] + '0')) + if (known_reslt[i] != result.digit_char(i)) { - cerr << i << "^th digit mismatch! " << known_reslt[i] << " != " << result[N - i - 1] << endl; + cerr << i << "^th digit mismatch! " << known_reslt[i] << " != " << result.digit_char(i) << endl; return false; } } @@ -131,7 +44,7 @@ bool test2() large_number result; for (i = 2; i <= number; i++) /* Multiply every number from 2 thru N */ - result.multiply(i); + result *= i; const char *known_reslt = "93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000"; @@ -142,12 +55,12 @@ bool test2() return false; } - size_t N = result.num_digits(); + const size_t N = result.num_digits(); for (i = 0; i < N; i++) { - if (known_reslt[i] != (result[N - i - 1] + '0')) + if (known_reslt[i] != result.digit_char(i)) { - cerr << i << "^th digit mismatch! " << known_reslt[i] << " != " << result[N - i - 1] << endl; + cerr << i << "^th digit mismatch! " << known_reslt[i] << " != " << result.digit_char(i) << endl; return false; } } @@ -177,19 +90,18 @@ int main(int argc, char *argv[]) auto start_time = chrono::high_resolution_clock::now(); for (i = 2; i <= number; i++) /* Multiply every number from 2 thru N */ - result.multiply(i); + result *= i; auto end_time = chrono::high_resolution_clock::now(); chrono::duration time_taken = end_time - start_time; - cout << number << "! = "; - result.print(); - cout << endl + cout << number << "! = " << result << endl << "Number of digits: " << result.num_digits() << endl << "Time taken: " << time_taken.count() << " s" << endl; test1(); test2(); + result.test(); return 0; } diff --git a/others/large_number.h b/others/large_number.h new file mode 100644 index 00000000000..0494a540b3b --- /dev/null +++ b/others/large_number.h @@ -0,0 +1,323 @@ +/** + * @author Krishna Vedala + * @email krishna (dot) vedala (at) ieee (dot) org + **/ + +#ifndef __LARGE_NUMBER__ +#define __LARGE_NUMBER__ +#include +#include +#include +#include + +/** + * Store large unsigned numbers as a C++ vector + * The class provides convenience functions to add a + * digit to the number, perform multiplication of + * large number with long unsigned integers. + **/ +class large_number +{ +public: + large_number() /**< initializer */ + { + _digits.push_back(1); + } + + large_number(unsigned long n) /**< initializer */ + { + unsigned long carry = n; + do + { + add_digit(carry % 10); + carry /= 10; + } while (carry != 0); + } + + large_number(const large_number &a) /**< initializer */ + { + _digits = a._digits; + } + + large_number(const std::vector &vec) /**< initializer */ + { + _digits = vec; + } + + /** + * Function to check implementation + **/ + static bool test() + { + std::cout << "------ Checking `large_number` class implementations\t" << std::endl; + large_number a(40); + a *= 10; + if (a != large_number(400)) + { + std::cerr << "\tFailed 1/5 (" << a << "!=400)" << std::endl; + return false; + } + std::cout << "\tPassed 1/5..."; + a += 120; + if (a != large_number(520)) + { + std::cerr << "\tFailed 2/5 (" << a << "!=520)" << std::endl; + return false; + } + std::cout << "\tPassed 2/5..."; + a *= 10; + if (a != large_number(5200)) + { + std::cerr << "\tFailed 3/5 (" << a << "!=5200)" << std::endl; + return false; + } + std::cout << "\tPassed 3/5..."; + ++a; + if (a != large_number(5201)) + { + std::cerr << "\tFailed 4/5 (" << a << "!=5201)" << std::endl; + return false; + } + std::cout << "\tPassed 4/5..."; + a++; + if (a != large_number(5202)) + { + std::cerr << "\tFailed 5/5 (" << a << "!=5202)" << std::endl; + return false; + } + std::cout << "\tPassed 5/5..." << std::endl; + return true; + } + + /** + * add a digit at MSB to the large number + **/ + void add_digit(unsigned int value) + { + if (value > 9) + { + std::cerr << "digit > 9!!\n"; + exit(EXIT_FAILURE); + } + + _digits.push_back(value); + } + + /** + * Get number of digits in the number + **/ + const size_t num_digits() const + { + return _digits.size(); + } + + /** + * operator over load to access the + * i^th digit conveniently and also + * assign value to it + **/ + inline unsigned char &operator[](size_t n) + { + return this->_digits[n]; + } + + inline const unsigned char &operator[](size_t n) const + { + return this->_digits[n]; + } + + /** + * operator overload to compare two numbers + **/ + friend std::ostream &operator<<(std::ostream &out, const large_number &a) + { + for (size_t i = a.num_digits(); i > 0; i--) + out << a[i - 1] + '0'; + return out; + } + + /** + * operator overload to compare two numbers + **/ + friend bool operator==(const large_number &a, const large_number b) + { + size_t N = a.num_digits(); + if (N != b.num_digits()) + return false; + for (size_t i = 0; i < N; i++) + if (a[i] != b[i]) + return false; + return true; + } + + /** + * operator overload to compare two numbers + **/ + friend bool operator!=(const large_number &a, const large_number b) + { + return !(a == b); + } + + /** + * operator overload to increment (prefix) + **/ + large_number &operator++() + { + this->add((unsigned int)1); + return *this; + } + + /** + * operator overload to increment (postfix) + **/ + large_number &operator++(int) + { + large_number tmp(_digits); + ++(*this); + return tmp; + } + + /** + * operator overload to add + **/ + template + large_number &operator+=(T &n) + { + if (std::is_same::value) // if adding with another large_number + { + large_number *b = &n; + const size_t max_L = std::max(this->num_digits(), b->num_digits()); + unsigned int carry = 0, temp; + for (size_t i = 0; i < max_L; i++) + { + temp += carry; + if (i < b->num_digits()) + temp += (*b)[i]; + if (i < this->num_digits()) + temp += (*this)[i]; + if (temp < 10) + carry = 0; + else + { + carry = temp / 10; + temp = temp % 10; + } + if (i < this->num_digits()) + (*this)[i] = temp; + else + this->add_digit(temp); + } + while (carry != 0) + { + if (i < this->num_digits()) + (*this)[i] = carry % 10; + else + this->add_digit(carry % 10); + carry /= 10; + } + + return *this; + } + + static_assert(std::is_integral::value, "Must be integer addition unsigned integer types."); + // typedef typename std::make_unsigned::type T2; + this->add(b); + return *this; + } + + // /** + // * operator overload to increment + // **/ + // friend large_number &operator+(large_number a, const large_number b) + // { + // const size_t max_L = std::max(a.num_digits(), b.num_digits()); + + // return a; + // } + + /** + * operator overload to increment + **/ + template + large_number &operator*=(const T n) + { + static_assert(std::is_integral::value, "Must be integer addition unsigned integer types."); + this->multiply(n); + return *this; + } + + /** + * returns i^th digit as an ASCII character + **/ + const char digit_char(size_t i) const + { + return _digits[num_digits() - i - 1] + '0'; + } + +private: + /** + * multiply large number with another integer and + * store the result in the same large number + **/ + template + void multiply(const T n) + { + static_assert(std::is_integral::value, "Can only have integer types."); + // assert(!(std::is_signed::value)); //, "Implemented only for unsigned integer types."); + + size_t i; + unsigned long long carry = 0, temp; + for (i = 0; i < this->num_digits(); i++) + { + temp = (*this)[i] * n; + temp += carry; + if (temp < 10) + carry = 0; + else + { + carry = temp / 10; + temp = temp % 10; + } + (*this)[i] = temp; + } + + while (carry != 0) + { + this->add_digit(carry % 10); + carry /= 10; + } + }; + + /** + * add large number with another integer and + * store the result in the same large number + **/ + template + void add(const T n) + { + static_assert(std::is_integral::value, "Can only have integer types."); + // static_assert(!(std::is_signed::value), "Implemented only for unsigned integer types."); + + size_t i = 0; + long long carry = n; + + while (carry != 0) + { + if (i < this->num_digits()) + { + carry += (*this)[i]; + (*this)[i] = carry % 10; + i++; + } + else + this->add_digit(carry % 10); + carry /= 10; + if (carry == 0) + return; + } + }; + + std::vector _digits; /**< where individual digits are stored */ +}; + +#endif From 72ac15ed01dfd3064616a87053adfe7b2073f18e Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Sat, 2 May 2020 17:19:43 -0400 Subject: [PATCH 009/433] resolved compiler warnings --- others/large_number.h | 145 +++++++++++++++++------------------------- 1 file changed, 60 insertions(+), 85 deletions(-) diff --git a/others/large_number.h b/others/large_number.h index 0494a540b3b..6d117d9dd44 100644 --- a/others/large_number.h +++ b/others/large_number.h @@ -8,6 +8,7 @@ #include #include #include +#include #include /** @@ -19,12 +20,12 @@ class large_number { public: - large_number() /**< initializer */ + large_number() /**< initializer with value = 1 */ { _digits.push_back(1); } - large_number(unsigned long n) /**< initializer */ + large_number(unsigned long n) /**< initializer from an integer */ { unsigned long carry = n; do @@ -34,16 +35,22 @@ class large_number } while (carry != 0); } - large_number(const large_number &a) /**< initializer */ + large_number(const large_number &a) /**< initializer from another large_number */ { _digits = a._digits; } - large_number(const std::vector &vec) /**< initializer */ + large_number(const std::vector &vec) /**< initializer from a vector */ { _digits = vec; } + large_number(const char *number_str) /**< initializer from a string */ + { + for (size_t i = strlen(number_str); i > 0; i--) + _digits.push_back(number_str[i - 1] - '0'); + } + /** * Function to check implementation **/ @@ -51,41 +58,54 @@ class large_number { std::cout << "------ Checking `large_number` class implementations\t" << std::endl; large_number a(40); + // 1. test multiplication a *= 10; if (a != large_number(400)) { - std::cerr << "\tFailed 1/5 (" << a << "!=400)" << std::endl; + std::cerr << "\tFailed 1/6 (" << a << "!=400)" << std::endl; return false; } - std::cout << "\tPassed 1/5..."; + std::cout << "\tPassed 1/6..."; + // 2. test compound addition with integer a += 120; if (a != large_number(520)) { - std::cerr << "\tFailed 2/5 (" << a << "!=520)" << std::endl; + std::cerr << "\tFailed 2/6 (" << a << "!=520)" << std::endl; return false; } - std::cout << "\tPassed 2/5..."; + std::cout << "\tPassed 2/6..."; + // 3. test compound multiplication again a *= 10; if (a != large_number(5200)) { - std::cerr << "\tFailed 3/5 (" << a << "!=5200)" << std::endl; + std::cerr << "\tFailed 3/6 (" << a << "!=5200)" << std::endl; return false; } - std::cout << "\tPassed 3/5..."; + std::cout << "\tPassed 3/6..."; + // 4. test increment (prefix) ++a; if (a != large_number(5201)) { - std::cerr << "\tFailed 4/5 (" << a << "!=5201)" << std::endl; + std::cerr << "\tFailed 4/6 (" << a << "!=5201)" << std::endl; return false; } - std::cout << "\tPassed 4/5..."; + std::cout << "\tPassed 4/6..."; + // 5. test increment (postfix) a++; if (a != large_number(5202)) { - std::cerr << "\tFailed 5/5 (" << a << "!=5202)" << std::endl; + std::cerr << "\tFailed 5/6 (" << a << "!=5202)" << std::endl; + return false; + } + std::cout << "\tPassed 5/6..."; + // 6. test addition with another large number + a = a + large_number("7000000000000000000000000000000"); + if (a != large_number("7000000000000000000000000005202")) + { + std::cerr << "\tFailed 6/6 (" << a << "!=7000000000000000000000000005202)" << std::endl; return false; } - std::cout << "\tPassed 5/5..." << std::endl; + std::cout << "\tPassed 6/6..." << std::endl; return true; } @@ -132,14 +152,14 @@ class large_number friend std::ostream &operator<<(std::ostream &out, const large_number &a) { for (size_t i = a.num_digits(); i > 0; i--) - out << a[i - 1] + '0'; + out << static_cast(a[i - 1]); return out; } /** * operator overload to compare two numbers **/ - friend bool operator==(const large_number &a, const large_number b) + friend bool operator==(const large_number &a, const large_number &b) { size_t N = a.num_digits(); if (N != b.num_digits()) @@ -153,7 +173,7 @@ class large_number /** * operator overload to compare two numbers **/ - friend bool operator!=(const large_number &a, const large_number b) + friend bool operator!=(const large_number &a, const large_number &b) { return !(a == b); } @@ -163,14 +183,14 @@ class large_number **/ large_number &operator++() { - this->add((unsigned int)1); + (*this) += 1; return *this; } /** * operator overload to increment (postfix) **/ - large_number &operator++(int) + large_number operator++(int) { large_number tmp(_digits); ++(*this); @@ -181,59 +201,43 @@ class large_number * operator overload to add **/ template - large_number &operator+=(T &n) + large_number &operator+=(T n) { - if (std::is_same::value) // if adding with another large_number + if (typeid(T) == typeid(large_number)) // if adding with another large_number { - large_number *b = &n; + large_number *b = (large_number *)&n; const size_t max_L = std::max(this->num_digits(), b->num_digits()); - unsigned int carry = 0, temp; - for (size_t i = 0; i < max_L; i++) + unsigned int carry = 0; + size_t i; + for (i = 0; i < max_L || carry != 0; i++) { - temp += carry; if (i < b->num_digits()) - temp += (*b)[i]; + carry += (*b)[i]; if (i < this->num_digits()) - temp += (*this)[i]; - if (temp < 10) - carry = 0; - else - { - carry = temp / 10; - temp = temp % 10; - } - if (i < this->num_digits()) - (*this)[i] = temp; - else - this->add_digit(temp); - } - while (carry != 0) - { + carry += (*this)[i]; if (i < this->num_digits()) (*this)[i] = carry % 10; else this->add_digit(carry % 10); carry /= 10; } - - return *this; } - - static_assert(std::is_integral::value, "Must be integer addition unsigned integer types."); - // typedef typename std::make_unsigned::type T2; - this->add(b); + else if (std::is_integral::value) + return (*this) += large_number(n); + else + std::cerr << "Must be integer addition unsigned integer types." << std::endl; return *this; } - // /** - // * operator overload to increment - // **/ - // friend large_number &operator+(large_number a, const large_number b) - // { - // const size_t max_L = std::max(a.num_digits(), b.num_digits()); - - // return a; - // } + /** + * operator overload to perform addition + **/ + template + friend large_number &operator+(large_number &a, const T &b) + { + a += b; + return a; + } /** * operator overload to increment @@ -288,35 +292,6 @@ class large_number } }; - /** - * add large number with another integer and - * store the result in the same large number - **/ - template - void add(const T n) - { - static_assert(std::is_integral::value, "Can only have integer types."); - // static_assert(!(std::is_signed::value), "Implemented only for unsigned integer types."); - - size_t i = 0; - long long carry = n; - - while (carry != 0) - { - if (i < this->num_digits()) - { - carry += (*this)[i]; - (*this)[i] = carry % 10; - i++; - } - else - this->add_digit(carry % 10); - carry /= 10; - if (carry == 0) - return; - } - }; - std::vector _digits; /**< where individual digits are stored */ }; From 1cb1641abc35fed7143c6d4ec7af8739bc056810 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Sat, 2 May 2020 17:56:19 -0400 Subject: [PATCH 010/433] compute arbitrarily large fibonacci number --- others/fibonacci_large.cpp | 51 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 others/fibonacci_large.cpp diff --git a/others/fibonacci_large.cpp b/others/fibonacci_large.cpp new file mode 100644 index 00000000000..709268b667c --- /dev/null +++ b/others/fibonacci_large.cpp @@ -0,0 +1,51 @@ +/** + * Computes N^th Fibonacci number given as + * input argument. Uses custom build arbitrary integers library + * to perform additions and other operations. + * + * Took 0.608246 seconds to compute 50,000^th Fibonacci + * number that contains 10450 digits! + **/ + +#include "large_number.h" +#include +#include + +large_number fib(unsigned long long n) +{ + large_number f0(1); + large_number f1(1); + + do + { + large_number f2 = f0 + f1; + f0 = f1; + f1 = f2; + n--; + } while (n > 2); // since we start from 2 + return f1; +} + +int main(int argc, char *argv[]) +{ + unsigned long long N; + if (argc == 2) + N = strtoull(argv[1], NULL, 10); + else + { + std::cout << "Enter N: "; + std::cin >> N; + } + + auto start_time = std::chrono::high_resolution_clock::now(); + large_number result = fib(N); + auto end_time = std::chrono::high_resolution_clock::now(); + std::chrono::duration time_taken = end_time - start_time; + + std::cout + << std::endl + << N << "^th Fibonacci number: " << result << std::endl + << "Number of digits: " << result.num_digits() << std::endl + << "Time taken: " << time_taken.count() << " s" << std::endl; + return 0; +} \ No newline at end of file From f4778612e071ee5c1502ab736ed822b8b81b2678 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Sat, 2 May 2020 17:56:42 -0400 Subject: [PATCH 011/433] large_number: created assignment operator --- others/large_number.h | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/others/large_number.h b/others/large_number.h index 6d117d9dd44..8a6afcaa4f2 100644 --- a/others/large_number.h +++ b/others/large_number.h @@ -239,6 +239,14 @@ class large_number return a; } + /** + * assignment operator + **/ + void operator=(const large_number &b) + { + _digits = b._digits; + } + /** * operator overload to increment **/ From 9b538f3783415e7172a5372800ea965dc911b7ba Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Sat, 2 May 2020 18:04:58 -0400 Subject: [PATCH 012/433] ignore non numeric characters when creating large_number from a string --- others/large_number.h | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/others/large_number.h b/others/large_number.h index 8a6afcaa4f2..8c7f688d0b4 100644 --- a/others/large_number.h +++ b/others/large_number.h @@ -48,7 +48,11 @@ class large_number large_number(const char *number_str) /**< initializer from a string */ { for (size_t i = strlen(number_str); i > 0; i--) - _digits.push_back(number_str[i - 1] - '0'); + { + unsigned char a = number_str[i - 1] - '0'; + if (a >= 0 && a <= 9) + _digits.push_back(a); + } } /** From 9c633857bd396bbf490ad8e736832f31ca4caced Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Sat, 2 May 2020 18:05:11 -0400 Subject: [PATCH 013/433] added test case --- others/fibonacci_large.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/others/fibonacci_large.cpp b/others/fibonacci_large.cpp index 709268b667c..a47e967d3e2 100644 --- a/others/fibonacci_large.cpp +++ b/others/fibonacci_large.cpp @@ -47,5 +47,11 @@ int main(int argc, char *argv[]) << N << "^th Fibonacci number: " << result << std::endl << "Number of digits: " << result.num_digits() << std::endl << "Time taken: " << time_taken.count() << " s" << std::endl; + + if (fib(5000) == large_number("3878968454388325633701916308325905312082127714646245106160597214895550139044037097010822916462210669479293452858882973813483102008954982940361430156911478938364216563944106910214505634133706558656238254656700712525929903854933813928836378347518908762970712033337052923107693008518093849801803847813996748881765554653788291644268912980384613778969021502293082475666346224923071883324803280375039130352903304505842701147635242270210934637699104006714174883298422891491273104054328753298044273676822977244987749874555691907703880637046832794811358973739993110106219308149018570815397854379195305617510761053075688783766033667355445258844886241619210553457493675897849027988234351023599844663934853256411952221859563060475364645470760330902420806382584929156452876291575759142343809142302917491088984155209854432486594079793571316841692868039545309545388698114665082066862897420639323438488465240988742395873801976993820317174208932265468879364002630797780058759129671389634214252579116872755600360311370547754724604639987588046985178408674382863125")) + std::cout << "Test for 5000^th Fibonacci number passed!" << std::endl; + else + std::cerr << "Test for 5000^th Fibonacci number failed!" << std::endl; + return 0; } \ No newline at end of file From 90840a1e3747ce65fb4c557ce6f13ee51f30d416 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Sat, 2 May 2020 18:06:41 -0400 Subject: [PATCH 014/433] user editable test "N" --- others/fibonacci_large.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/others/fibonacci_large.cpp b/others/fibonacci_large.cpp index a47e967d3e2..12b926759f5 100644 --- a/others/fibonacci_large.cpp +++ b/others/fibonacci_large.cpp @@ -48,10 +48,11 @@ int main(int argc, char *argv[]) << "Number of digits: " << result.num_digits() << std::endl << "Time taken: " << time_taken.count() << " s" << std::endl; - if (fib(5000) == large_number("3878968454388325633701916308325905312082127714646245106160597214895550139044037097010822916462210669479293452858882973813483102008954982940361430156911478938364216563944106910214505634133706558656238254656700712525929903854933813928836378347518908762970712033337052923107693008518093849801803847813996748881765554653788291644268912980384613778969021502293082475666346224923071883324803280375039130352903304505842701147635242270210934637699104006714174883298422891491273104054328753298044273676822977244987749874555691907703880637046832794811358973739993110106219308149018570815397854379195305617510761053075688783766033667355445258844886241619210553457493675897849027988234351023599844663934853256411952221859563060475364645470760330902420806382584929156452876291575759142343809142302917491088984155209854432486594079793571316841692868039545309545388698114665082066862897420639323438488465240988742395873801976993820317174208932265468879364002630797780058759129671389634214252579116872755600360311370547754724604639987588046985178408674382863125")) - std::cout << "Test for 5000^th Fibonacci number passed!" << std::endl; + N = 5000; + if (fib(N) == large_number("3878968454388325633701916308325905312082127714646245106160597214895550139044037097010822916462210669479293452858882973813483102008954982940361430156911478938364216563944106910214505634133706558656238254656700712525929903854933813928836378347518908762970712033337052923107693008518093849801803847813996748881765554653788291644268912980384613778969021502293082475666346224923071883324803280375039130352903304505842701147635242270210934637699104006714174883298422891491273104054328753298044273676822977244987749874555691907703880637046832794811358973739993110106219308149018570815397854379195305617510761053075688783766033667355445258844886241619210553457493675897849027988234351023599844663934853256411952221859563060475364645470760330902420806382584929156452876291575759142343809142302917491088984155209854432486594079793571316841692868039545309545388698114665082066862897420639323438488465240988742395873801976993820317174208932265468879364002630797780058759129671389634214252579116872755600360311370547754724604639987588046985178408674382863125")) + std::cout << "Test for " << N << "^th Fibonacci number passed!" << std::endl; else - std::cerr << "Test for 5000^th Fibonacci number failed!" << std::endl; + std::cerr << "Test for " << N << "^th Fibonacci number failed!" << std::endl; return 0; } \ No newline at end of file From f1b07d33a7e47921862b9702a35f6d2d1007c099 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Sat, 2 May 2020 18:10:15 -0400 Subject: [PATCH 015/433] remove incorrect comment --- others/large_factorial.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/others/large_factorial.cpp b/others/large_factorial.cpp index dccdcaeab8c..5ee116b4cb6 100644 --- a/others/large_factorial.cpp +++ b/others/large_factorial.cpp @@ -76,7 +76,6 @@ int main(int argc, char *argv[]) { int number, i; - //Asks for the number/position of term in Fibonnacci sequence if (argc == 2) number = atoi(argv[1]); else From a77151c254d6c820b4af9984814b8cb6d77b1df1 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 24 May 2020 18:38:16 +0000 Subject: [PATCH 016/433] updating DIRECTORY.md --- DIRECTORY.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index ddbfd06d8f5..d7c1386210f 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -137,8 +137,11 @@ * [Decimal To Roman Numeral](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Decimal%20to%20Roman%20Numeral.cpp) * [Fast Interger Input](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/fast_interger_input.cpp) * [Fibonacci](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/fibonacci.cpp) + * [Fibonacci Large](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/fibonacci_large.cpp) * [Gcd Of N Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/GCD_of_n_numbers.cpp) * [Happy Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/happy_number.cpp) + * [Large Factorial](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/large_factorial.cpp) + * [Large Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/large_number.h) * [Matrix Exponentiation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/matrix_exponentiation.cpp) * [Measure Time Elapsed](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/measure_time_elapsed.cpp) * [Palindromeofnumber](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Palindromeofnumber.cpp) From 236b6581302989cc5770233ec0ed6c58db621642 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 24 May 2020 15:56:45 -0400 Subject: [PATCH 017/433] replace `std::chronos` with `ctime` - cpplint does not allow c++-11 --- others/fibonacci_large.cpp | 61 +++++++++------ others/large_factorial.cpp | 93 +++++++++++------------ others/large_number.h | 152 +++++++++++++++---------------------- 3 files changed, 143 insertions(+), 163 deletions(-) diff --git a/others/fibonacci_large.cpp b/others/fibonacci_large.cpp index 12b926759f5..bdfb201a5c4 100644 --- a/others/fibonacci_large.cpp +++ b/others/fibonacci_large.cpp @@ -7,52 +7,69 @@ * number that contains 10450 digits! **/ -#include "large_number.h" +#include #include -#include -large_number fib(unsigned long long n) -{ +#include "large_number.h" + +large_number fib(unsigned long long n) { large_number f0(1); large_number f1(1); - do - { + do { large_number f2 = f0 + f1; f0 = f1; f1 = f2; n--; - } while (n > 2); // since we start from 2 + } while (n > 2); // since we start from 2 return f1; } -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { unsigned long long N; if (argc == 2) N = strtoull(argv[1], NULL, 10); - else - { + else { std::cout << "Enter N: "; std::cin >> N; } - auto start_time = std::chrono::high_resolution_clock::now(); + clock_t start_time = std::clock(); large_number result = fib(N); - auto end_time = std::chrono::high_resolution_clock::now(); - std::chrono::duration time_taken = end_time - start_time; + clock_t end_time = std::clock(); + double time_taken = static_cast(end_time - start_time) / + static_cast(CLOCKS_PER_SEC); - std::cout - << std::endl - << N << "^th Fibonacci number: " << result << std::endl - << "Number of digits: " << result.num_digits() << std::endl - << "Time taken: " << time_taken.count() << " s" << std::endl; + std::cout << std::endl + << N << "^th Fibonacci number: " << result << std::endl + << "Number of digits: " << result.num_digits() << std::endl + << "Time taken: " << std::scientific << time_taken << " s" + << std::endl; N = 5000; - if (fib(N) == large_number("3878968454388325633701916308325905312082127714646245106160597214895550139044037097010822916462210669479293452858882973813483102008954982940361430156911478938364216563944106910214505634133706558656238254656700712525929903854933813928836378347518908762970712033337052923107693008518093849801803847813996748881765554653788291644268912980384613778969021502293082475666346224923071883324803280375039130352903304505842701147635242270210934637699104006714174883298422891491273104054328753298044273676822977244987749874555691907703880637046832794811358973739993110106219308149018570815397854379195305617510761053075688783766033667355445258844886241619210553457493675897849027988234351023599844663934853256411952221859563060475364645470760330902420806382584929156452876291575759142343809142302917491088984155209854432486594079793571316841692868039545309545388698114665082066862897420639323438488465240988742395873801976993820317174208932265468879364002630797780058759129671389634214252579116872755600360311370547754724604639987588046985178408674382863125")) - std::cout << "Test for " << N << "^th Fibonacci number passed!" << std::endl; + if (fib(N) == + large_number( + "387896845438832563370191630832590531208212771464624510616059721489" + "555013904403709701082291646221066947929345285888297381348310200895" + "498294036143015691147893836421656394410691021450563413370655865623" + "825465670071252592990385493381392883637834751890876297071203333705" + "292310769300851809384980180384781399674888176555465378829164426891" + "298038461377896902150229308247566634622492307188332480328037503913" + "035290330450584270114763524227021093463769910400671417488329842289" + "149127310405432875329804427367682297724498774987455569190770388063" + "704683279481135897373999311010621930814901857081539785437919530561" + "751076105307568878376603366735544525884488624161921055345749367589" + "784902798823435102359984466393485325641195222185956306047536464547" + "076033090242080638258492915645287629157575914234380914230291749108" + "898415520985443248659407979357131684169286803954530954538869811466" + "508206686289742063932343848846524098874239587380197699382031717420" + "893226546887936400263079778005875912967138963421425257911687275560" + "0360311370547754724604639987588046985178408674382863125")) + std::cout << "Test for " << N << "^th Fibonacci number passed!" + << std::endl; else - std::cerr << "Test for " << N << "^th Fibonacci number failed!" << std::endl; + std::cerr << "Test for " << N << "^th Fibonacci number failed!" + << std::endl; return 0; } \ No newline at end of file diff --git a/others/large_factorial.cpp b/others/large_factorial.cpp index 5ee116b4cb6..f06f4e7af3c 100644 --- a/others/large_factorial.cpp +++ b/others/large_factorial.cpp @@ -1,102 +1,97 @@ -#include #include -#include -#include "large_number.h" -using namespace std; +#include +#include + +#include "large_number.h" -bool test1() -{ - cout << "---- Check 1\t"; +bool test1() { + std::cout << "---- Check 1\t"; unsigned int i, number = 10; large_number result; - for (i = 2; i <= number; i++) - /* Multiply every number from 2 thru N */ + for (i = 2; i <= number; i++) /* Multiply every number from 2 thru N */ result *= i; const char *known_reslt = "3628800"; /* check 1 */ - if (strlen(known_reslt) != result.num_digits()) - { - cerr << "Result lengths dont match! " << strlen(known_reslt) << " != " << result.num_digits() << endl; + if (strlen(known_reslt) != result.num_digits()) { + std::cerr << "Result lengths dont match! " << strlen(known_reslt) + << " != " << result.num_digits() << std::endl; return false; } const size_t N = result.num_digits(); - for (i = 0; i < N; i++) - { - if (known_reslt[i] != result.digit_char(i)) - { - cerr << i << "^th digit mismatch! " << known_reslt[i] << " != " << result.digit_char(i) << endl; + for (i = 0; i < N; i++) { + if (known_reslt[i] != result.digit_char(i)) { + std::cerr << i << "^th digit mismatch! " << known_reslt[i] + << " != " << result.digit_char(i) << std::endl; return false; } } - cout << "Passed!" << endl; + std::cout << "Passed!" << std::endl; return true; } -bool test2() -{ - cout << "---- Check 2\t"; +bool test2() { + std::cout << "---- Check 2\t"; unsigned int i, number = 100; large_number result; - for (i = 2; i <= number; i++) - /* Multiply every number from 2 thru N */ + for (i = 2; i <= number; i++) /* Multiply every number from 2 thru N */ result *= i; - const char *known_reslt = "93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000"; + const char *known_reslt = + "9332621544394415268169923885626670049071596826438162146859296389521759" + "9993229915608941463976156518286253697920827223758251185210916864000000" + "000000000000000000"; /* check 1 */ - if (strlen(known_reslt) != result.num_digits()) - { - cerr << "Result lengths dont match! " << strlen(known_reslt) << " != " << result.num_digits() << endl; + if (strlen(known_reslt) != result.num_digits()) { + std::cerr << "Result lengths dont match! " << strlen(known_reslt) + << " != " << result.num_digits() << std::endl; return false; } const size_t N = result.num_digits(); - for (i = 0; i < N; i++) - { - if (known_reslt[i] != result.digit_char(i)) - { - cerr << i << "^th digit mismatch! " << known_reslt[i] << " != " << result.digit_char(i) << endl; + for (i = 0; i < N; i++) { + if (known_reslt[i] != result.digit_char(i)) { + std::cerr << i << "^th digit mismatch! " << known_reslt[i] + << " != " << result.digit_char(i) << std::endl; return false; } } - cout << "Passed!" << endl; + std::cout << "Passed!" << std::endl; return true; } /** * Main program **/ -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { int number, i; if (argc == 2) number = atoi(argv[1]); - else - { - printf("Enter the value of n(n starts from 0 ): "); - scanf("%d", &number); + else { + std::cout << "Enter the value of n(n starts from 0 ): "; + std::cin >> number; } large_number result; - auto start_time = chrono::high_resolution_clock::now(); - for (i = 2; i <= number; i++) - /* Multiply every number from 2 thru N */ + std::clock_t start_time = std::clock(); + for (i = 2; i <= number; i++) /* Multiply every number from 2 thru N */ result *= i; - auto end_time = chrono::high_resolution_clock::now(); - chrono::duration time_taken = end_time - start_time; - - cout << number << "! = " << result << endl - << "Number of digits: " << result.num_digits() << endl - << "Time taken: " << time_taken.count() << " s" - << endl; + std::clock_t end_time = std::clock(); + double time_taken = + static_cast(end_time - start_time) / CLOCKS_PER_SEC; + + std::cout << number << "! = " << result << std::endl + << "Number of digits: " << result.num_digits() << std::endl + << "Time taken: " << std::scientific << time_taken << " s" + << std::endl; test1(); test2(); diff --git a/others/large_number.h b/others/large_number.h index 8c7f688d0b4..4657e87afe8 100644 --- a/others/large_number.h +++ b/others/large_number.h @@ -5,10 +5,10 @@ #ifndef __LARGE_NUMBER__ #define __LARGE_NUMBER__ -#include -#include #include #include +#include +#include #include /** @@ -17,9 +17,8 @@ * digit to the number, perform multiplication of * large number with long unsigned integers. **/ -class large_number -{ -public: +class large_number { + public: large_number() /**< initializer with value = 1 */ { _digits.push_back(1); @@ -28,85 +27,79 @@ class large_number large_number(unsigned long n) /**< initializer from an integer */ { unsigned long carry = n; - do - { + do { add_digit(carry % 10); carry /= 10; } while (carry != 0); } - large_number(const large_number &a) /**< initializer from another large_number */ + large_number( + const large_number &a) /**< initializer from another large_number */ { _digits = a._digits; } - large_number(const std::vector &vec) /**< initializer from a vector */ + large_number( + const std::vector &vec) /**< initializer from a vector */ { _digits = vec; } large_number(const char *number_str) /**< initializer from a string */ { - for (size_t i = strlen(number_str); i > 0; i--) - { + for (size_t i = strlen(number_str); i > 0; i--) { unsigned char a = number_str[i - 1] - '0'; - if (a >= 0 && a <= 9) - _digits.push_back(a); + if (a >= 0 && a <= 9) _digits.push_back(a); } } /** * Function to check implementation **/ - static bool test() - { - std::cout << "------ Checking `large_number` class implementations\t" << std::endl; + static bool test() { + std::cout << "------ Checking `large_number` class implementations\t" + << std::endl; large_number a(40); // 1. test multiplication a *= 10; - if (a != large_number(400)) - { + if (a != large_number(400)) { std::cerr << "\tFailed 1/6 (" << a << "!=400)" << std::endl; return false; } std::cout << "\tPassed 1/6..."; // 2. test compound addition with integer a += 120; - if (a != large_number(520)) - { + if (a != large_number(520)) { std::cerr << "\tFailed 2/6 (" << a << "!=520)" << std::endl; return false; } std::cout << "\tPassed 2/6..."; // 3. test compound multiplication again a *= 10; - if (a != large_number(5200)) - { + if (a != large_number(5200)) { std::cerr << "\tFailed 3/6 (" << a << "!=5200)" << std::endl; return false; } std::cout << "\tPassed 3/6..."; // 4. test increment (prefix) ++a; - if (a != large_number(5201)) - { + if (a != large_number(5201)) { std::cerr << "\tFailed 4/6 (" << a << "!=5201)" << std::endl; return false; } std::cout << "\tPassed 4/6..."; // 5. test increment (postfix) a++; - if (a != large_number(5202)) - { + if (a != large_number(5202)) { std::cerr << "\tFailed 5/6 (" << a << "!=5202)" << std::endl; return false; } std::cout << "\tPassed 5/6..."; // 6. test addition with another large number a = a + large_number("7000000000000000000000000000000"); - if (a != large_number("7000000000000000000000000005202")) - { - std::cerr << "\tFailed 6/6 (" << a << "!=7000000000000000000000000005202)" << std::endl; + if (a != large_number("7000000000000000000000000005202")) { + std::cerr << "\tFailed 6/6 (" << a + << "!=7000000000000000000000000005202)" << std::endl; return false; } std::cout << "\tPassed 6/6..." << std::endl; @@ -116,10 +109,8 @@ class large_number /** * add a digit at MSB to the large number **/ - void add_digit(unsigned int value) - { - if (value > 9) - { + void add_digit(unsigned int value) { + if (value > 9) { std::cerr << "digit > 9!!\n"; exit(EXIT_FAILURE); } @@ -130,31 +121,23 @@ class large_number /** * Get number of digits in the number **/ - const size_t num_digits() const - { - return _digits.size(); - } + const size_t num_digits() const { return _digits.size(); } /** * operator over load to access the * i^th digit conveniently and also * assign value to it **/ - inline unsigned char &operator[](size_t n) - { - return this->_digits[n]; - } + inline unsigned char &operator[](size_t n) { return this->_digits[n]; } - inline const unsigned char &operator[](size_t n) const - { + inline const unsigned char &operator[](size_t n) const { return this->_digits[n]; } /** * operator overload to compare two numbers **/ - friend std::ostream &operator<<(std::ostream &out, const large_number &a) - { + friend std::ostream &operator<<(std::ostream &out, const large_number &a) { for (size_t i = a.num_digits(); i > 0; i--) out << static_cast(a[i - 1]); return out; @@ -163,30 +146,25 @@ class large_number /** * operator overload to compare two numbers **/ - friend bool operator==(const large_number &a, const large_number &b) - { + friend bool operator==(large_number const &a, large_number const &b) { size_t N = a.num_digits(); - if (N != b.num_digits()) - return false; + if (N != b.num_digits()) return false; for (size_t i = 0; i < N; i++) - if (a[i] != b[i]) - return false; + if (a[i] != b[i]) return false; return true; } /** * operator overload to compare two numbers **/ - friend bool operator!=(const large_number &a, const large_number &b) - { + friend bool operator!=(large_number const &a, large_number const &b) { return !(a == b); } /** * operator overload to increment (prefix) **/ - large_number &operator++() - { + large_number &operator++() { (*this) += 1; return *this; } @@ -194,8 +172,7 @@ class large_number /** * operator overload to increment (postfix) **/ - large_number operator++(int) - { + large_number operator++(int) { large_number tmp(_digits); ++(*this); return tmp; @@ -205,31 +182,28 @@ class large_number * operator overload to add **/ template - large_number &operator+=(T n) - { - if (typeid(T) == typeid(large_number)) // if adding with another large_number + large_number &operator+=(T n) { + if (typeid(T) == + typeid(large_number)) // if adding with another large_number { large_number *b = (large_number *)&n; const size_t max_L = std::max(this->num_digits(), b->num_digits()); unsigned int carry = 0; size_t i; - for (i = 0; i < max_L || carry != 0; i++) - { - if (i < b->num_digits()) - carry += (*b)[i]; - if (i < this->num_digits()) - carry += (*this)[i]; + for (i = 0; i < max_L || carry != 0; i++) { + if (i < b->num_digits()) carry += (*b)[i]; + if (i < this->num_digits()) carry += (*this)[i]; if (i < this->num_digits()) (*this)[i] = carry % 10; else this->add_digit(carry % 10); carry /= 10; } - } - else if (std::is_integral::value) + } else if (std::is_integral::value) return (*this) += large_number(n); else - std::cerr << "Must be integer addition unsigned integer types." << std::endl; + std::cerr << "Must be integer addition unsigned integer types." + << std::endl; return *this; } @@ -237,8 +211,7 @@ class large_number * operator overload to perform addition **/ template - friend large_number &operator+(large_number &a, const T &b) - { + friend large_number &operator+(large_number &a, const T &b) { a += b; return a; } @@ -246,18 +219,15 @@ class large_number /** * assignment operator **/ - void operator=(const large_number &b) - { - _digits = b._digits; - } + void operator=(const large_number &b) { _digits = b._digits; } /** * operator overload to increment **/ template - large_number &operator*=(const T n) - { - static_assert(std::is_integral::value, "Must be integer addition unsigned integer types."); + large_number &operator*=(const T n) { + static_assert(std::is_integral::value, + "Must be integer addition unsigned integer types."); this->multiply(n); return *this; } @@ -265,46 +235,44 @@ class large_number /** * returns i^th digit as an ASCII character **/ - const char digit_char(size_t i) const - { + const char digit_char(size_t i) const { return _digits[num_digits() - i - 1] + '0'; } -private: + private: /** * multiply large number with another integer and * store the result in the same large number **/ template - void multiply(const T n) - { - static_assert(std::is_integral::value, "Can only have integer types."); - // assert(!(std::is_signed::value)); //, "Implemented only for unsigned integer types."); + void multiply(const T n) { + static_assert(std::is_integral::value, + "Can only have integer types."); + // assert(!(std::is_signed::value)); //, "Implemented only for + // unsigned integer types."); size_t i; unsigned long long carry = 0, temp; - for (i = 0; i < this->num_digits(); i++) - { + for (i = 0; i < this->num_digits(); i++) { temp = (*this)[i] * n; temp += carry; if (temp < 10) carry = 0; - else - { + else { carry = temp / 10; temp = temp % 10; } (*this)[i] = temp; } - while (carry != 0) - { + while (carry != 0) { this->add_digit(carry % 10); carry /= 10; } }; - std::vector _digits; /**< where individual digits are stored */ + std::vector + _digits; /**< where individual digits are stored */ }; #endif From e989ad0fe5bf7b59dadbb11bbc44aba7e6654756 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 24 May 2020 16:02:00 -0400 Subject: [PATCH 018/433] cpp lint fixes --- others/fibonacci_large.cpp | 13 +++++++------ others/large_factorial.cpp | 6 +++--- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/others/fibonacci_large.cpp b/others/fibonacci_large.cpp index bdfb201a5c4..0333feb81b2 100644 --- a/others/fibonacci_large.cpp +++ b/others/fibonacci_large.cpp @@ -7,12 +7,13 @@ * number that contains 10450 digits! **/ +#include #include #include -#include "large_number.h" +#include "./large_number.h" -large_number fib(unsigned long long n) { +large_number fib(uint64_t n) { large_number f0(1); large_number f1(1); @@ -26,10 +27,10 @@ large_number fib(unsigned long long n) { } int main(int argc, char *argv[]) { - unsigned long long N; - if (argc == 2) + uint64_t N; + if (argc == 2) { N = strtoull(argv[1], NULL, 10); - else { + } else { std::cout << "Enter N: "; std::cin >> N; } @@ -72,4 +73,4 @@ int main(int argc, char *argv[]) { << std::endl; return 0; -} \ No newline at end of file +} diff --git a/others/large_factorial.cpp b/others/large_factorial.cpp index f06f4e7af3c..6d538558943 100644 --- a/others/large_factorial.cpp +++ b/others/large_factorial.cpp @@ -3,7 +3,7 @@ #include #include -#include "large_number.h" +#include "./large_number.h" bool test1() { std::cout << "---- Check 1\t"; @@ -72,9 +72,9 @@ bool test2() { int main(int argc, char *argv[]) { int number, i; - if (argc == 2) + if (argc == 2) { number = atoi(argv[1]); - else { + } else { std::cout << "Enter the value of n(n starts from 0 ): "; std::cin >> number; } From 045a1dc977f309a52d121b1efe66fb6a25e3fb29 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 24 May 2020 16:08:00 -0400 Subject: [PATCH 019/433] more cpp lint fixes --- others/large_number.h | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/others/large_number.h b/others/large_number.h index 4657e87afe8..abc63b765cf 100644 --- a/others/large_number.h +++ b/others/large_number.h @@ -3,8 +3,8 @@ * @email krishna (dot) vedala (at) ieee (dot) org **/ -#ifndef __LARGE_NUMBER__ -#define __LARGE_NUMBER__ +#ifndef OTHERS_LARGE_NUMBER_H_ +#define OTHERS_LARGE_NUMBER_H_ #include #include #include @@ -18,11 +18,8 @@ * large number with long unsigned integers. **/ class large_number { - public: - large_number() /**< initializer with value = 1 */ - { - _digits.push_back(1); - } +public: + large_number() /**< initializer with value = 1 */ { _digits.push_back(1); } large_number(unsigned long n) /**< initializer from an integer */ { @@ -49,7 +46,8 @@ class large_number { { for (size_t i = strlen(number_str); i > 0; i--) { unsigned char a = number_str[i - 1] - '0'; - if (a >= 0 && a <= 9) _digits.push_back(a); + if (a >= 0 && a <= 9) + _digits.push_back(a); } } @@ -148,9 +146,11 @@ class large_number { **/ friend bool operator==(large_number const &a, large_number const &b) { size_t N = a.num_digits(); - if (N != b.num_digits()) return false; + if (N != b.num_digits()) + return false; for (size_t i = 0; i < N; i++) - if (a[i] != b[i]) return false; + if (a[i] != b[i]) + return false; return true; } @@ -191,8 +191,10 @@ class large_number { unsigned int carry = 0; size_t i; for (i = 0; i < max_L || carry != 0; i++) { - if (i < b->num_digits()) carry += (*b)[i]; - if (i < this->num_digits()) carry += (*this)[i]; + if (i < b->num_digits()) + carry += (*b)[i]; + if (i < this->num_digits()) + carry += (*this)[i]; if (i < this->num_digits()) (*this)[i] = carry % 10; else @@ -239,7 +241,7 @@ class large_number { return _digits[num_digits() - i - 1] + '0'; } - private: +private: /** * multiply large number with another integer and * store the result in the same large number @@ -275,4 +277,4 @@ class large_number { _digits; /**< where individual digits are stored */ }; -#endif +#endif // OTHERS_LARGE_NUMBER_H_ From ca08e3e9a21a16ad08d97f3ceb06d4a511bc1c39 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 24 May 2020 16:08:12 -0400 Subject: [PATCH 020/433] updated vscode settings --- .vscode/settings.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 0ab2708d0fd..5815b26668b 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -64,7 +64,7 @@ "valarray": "cpp", "algorithm": "cpp" }, - "C_Cpp.clang_format_style": "{BasedOnStyle: Google, IndentWidth: 4, ColumnLimit: 80, UseTab: Never}", + "C_Cpp.clang_format_style": "{ BasedOnStyle: Google, UseTab: Never, IndentWidth: 4, TabWidth: 4,, AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: true, ColumnLimit: 80, AccessModifierOffset: -4, NamespaceIndentation: All }", "editor.formatOnSave": true, "editor.formatOnType": true, "editor.formatOnPaste": true From 6276e4ec06b1d698cc3e0ca5e5d9dd9b57097b32 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 24 May 2020 16:11:08 -0400 Subject: [PATCH 021/433] use cinttypes for size specific int type --- others/large_number.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/others/large_number.h b/others/large_number.h index abc63b765cf..84d885f67b5 100644 --- a/others/large_number.h +++ b/others/large_number.h @@ -6,6 +6,7 @@ #ifndef OTHERS_LARGE_NUMBER_H_ #define OTHERS_LARGE_NUMBER_H_ #include +#include #include #include #include @@ -21,9 +22,9 @@ class large_number { public: large_number() /**< initializer with value = 1 */ { _digits.push_back(1); } - large_number(unsigned long n) /**< initializer from an integer */ + large_number(uint64_t n) /**< initializer from an integer */ { - unsigned long carry = n; + uint64_t carry = n; do { add_digit(carry % 10); carry /= 10; From b802dbe077faf117cce2203d1a5c33064a12c9e5 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 24 May 2020 16:24:41 -0400 Subject: [PATCH 022/433] code cleanup --- others/large_number.h | 449 +++++++++++++++++++++--------------------- 1 file changed, 220 insertions(+), 229 deletions(-) diff --git a/others/large_number.h b/others/large_number.h index 84d885f67b5..4f3851053f9 100644 --- a/others/large_number.h +++ b/others/large_number.h @@ -5,6 +5,7 @@ #ifndef OTHERS_LARGE_NUMBER_H_ #define OTHERS_LARGE_NUMBER_H_ +#include #include #include #include @@ -19,263 +20,253 @@ * large number with long unsigned integers. **/ class large_number { -public: - large_number() /**< initializer with value = 1 */ { _digits.push_back(1); } + public: + /**< initializer with value = 1 */ + large_number() { _digits.push_back(1); } - large_number(uint64_t n) /**< initializer from an integer */ - { - uint64_t carry = n; - do { - add_digit(carry % 10); - carry /= 10; - } while (carry != 0); - } + /**< initializer from an integer */ + explicit large_number(uint64_t n) { + uint64_t carry = n; + do { + add_digit(carry % 10); + carry /= 10; + } while (carry != 0); + } - large_number( - const large_number &a) /**< initializer from another large_number */ - { - _digits = a._digits; - } + /**< initializer from another large_number */ + explicit large_number(const large_number &a) { _digits = a._digits; } - large_number( - const std::vector &vec) /**< initializer from a vector */ - { - _digits = vec; - } + /**< initializer from a vector */ + explicit large_number(const std::vector &vec) { + _digits = vec; + } - large_number(const char *number_str) /**< initializer from a string */ - { - for (size_t i = strlen(number_str); i > 0; i--) { - unsigned char a = number_str[i - 1] - '0'; - if (a >= 0 && a <= 9) - _digits.push_back(a); - } + /**< initializer from a string */ + explicit large_number(const char *number_str) { + for (size_t i = strlen(number_str); i > 0; i--) { + unsigned char a = number_str[i - 1] - '0'; + if (a >= 0 && a <= 9) _digits.push_back(a); } + } - /** - * Function to check implementation - **/ - static bool test() { - std::cout << "------ Checking `large_number` class implementations\t" - << std::endl; - large_number a(40); - // 1. test multiplication - a *= 10; - if (a != large_number(400)) { - std::cerr << "\tFailed 1/6 (" << a << "!=400)" << std::endl; - return false; - } - std::cout << "\tPassed 1/6..."; - // 2. test compound addition with integer - a += 120; - if (a != large_number(520)) { - std::cerr << "\tFailed 2/6 (" << a << "!=520)" << std::endl; - return false; - } - std::cout << "\tPassed 2/6..."; - // 3. test compound multiplication again - a *= 10; - if (a != large_number(5200)) { - std::cerr << "\tFailed 3/6 (" << a << "!=5200)" << std::endl; - return false; - } - std::cout << "\tPassed 3/6..."; - // 4. test increment (prefix) - ++a; - if (a != large_number(5201)) { - std::cerr << "\tFailed 4/6 (" << a << "!=5201)" << std::endl; - return false; - } - std::cout << "\tPassed 4/6..."; - // 5. test increment (postfix) - a++; - if (a != large_number(5202)) { - std::cerr << "\tFailed 5/6 (" << a << "!=5202)" << std::endl; - return false; - } - std::cout << "\tPassed 5/6..."; - // 6. test addition with another large number - a = a + large_number("7000000000000000000000000000000"); - if (a != large_number("7000000000000000000000000005202")) { - std::cerr << "\tFailed 6/6 (" << a - << "!=7000000000000000000000000005202)" << std::endl; - return false; - } - std::cout << "\tPassed 6/6..." << std::endl; - return true; + /** + * Function to check implementation + **/ + static bool test() { + std::cout << "------ Checking `large_number` class implementations\t" + << std::endl; + large_number a(40); + // 1. test multiplication + a *= 10; + if (a != large_number(400)) { + std::cerr << "\tFailed 1/6 (" << a << "!=400)" << std::endl; + return false; } + std::cout << "\tPassed 1/6..."; + // 2. test compound addition with integer + a += 120; + if (a != large_number(520)) { + std::cerr << "\tFailed 2/6 (" << a << "!=520)" << std::endl; + return false; + } + std::cout << "\tPassed 2/6..."; + // 3. test compound multiplication again + a *= 10; + if (a != large_number(5200)) { + std::cerr << "\tFailed 3/6 (" << a << "!=5200)" << std::endl; + return false; + } + std::cout << "\tPassed 3/6..."; + // 4. test increment (prefix) + ++a; + if (a != large_number(5201)) { + std::cerr << "\tFailed 4/6 (" << a << "!=5201)" << std::endl; + return false; + } + std::cout << "\tPassed 4/6..."; + // 5. test increment (postfix) + a++; + if (a != large_number(5202)) { + std::cerr << "\tFailed 5/6 (" << a << "!=5202)" << std::endl; + return false; + } + std::cout << "\tPassed 5/6..."; + // 6. test addition with another large number + a = a + large_number("7000000000000000000000000000000"); + if (a != large_number("7000000000000000000000000005202")) { + std::cerr << "\tFailed 6/6 (" << a << "!=7000000000000000000000000005202)" + << std::endl; + return false; + } + std::cout << "\tPassed 6/6..." << std::endl; + return true; + } - /** - * add a digit at MSB to the large number - **/ - void add_digit(unsigned int value) { - if (value > 9) { - std::cerr << "digit > 9!!\n"; - exit(EXIT_FAILURE); - } - - _digits.push_back(value); + /** + * add a digit at MSB to the large number + **/ + void add_digit(unsigned int value) { + if (value > 9) { + std::cerr << "digit > 9!!\n"; + exit(EXIT_FAILURE); } - /** - * Get number of digits in the number - **/ - const size_t num_digits() const { return _digits.size(); } + _digits.push_back(value); + } - /** - * operator over load to access the - * i^th digit conveniently and also - * assign value to it - **/ - inline unsigned char &operator[](size_t n) { return this->_digits[n]; } + /** + * Get number of digits in the number + **/ + const size_t num_digits() const { return _digits.size(); } - inline const unsigned char &operator[](size_t n) const { - return this->_digits[n]; - } + /** + * operator over load to access the + * i^th digit conveniently and also + * assign value to it + **/ + inline unsigned char &operator[](size_t n) { return this->_digits[n]; } - /** - * operator overload to compare two numbers - **/ - friend std::ostream &operator<<(std::ostream &out, const large_number &a) { - for (size_t i = a.num_digits(); i > 0; i--) - out << static_cast(a[i - 1]); - return out; - } + inline const unsigned char &operator[](size_t n) const { + return this->_digits[n]; + } - /** - * operator overload to compare two numbers - **/ - friend bool operator==(large_number const &a, large_number const &b) { - size_t N = a.num_digits(); - if (N != b.num_digits()) - return false; - for (size_t i = 0; i < N; i++) - if (a[i] != b[i]) - return false; - return true; - } + /** + * operator overload to compare two numbers + **/ + friend std::ostream &operator<<(std::ostream &out, const large_number &a) { + for (size_t i = a.num_digits(); i > 0; i--) + out << static_cast(a[i - 1]); + return out; + } - /** - * operator overload to compare two numbers - **/ - friend bool operator!=(large_number const &a, large_number const &b) { - return !(a == b); - } + /** + * operator overload to compare two numbers + **/ + friend bool operator==(large_number const &a, large_number const &b) { + size_t N = a.num_digits(); + if (N != b.num_digits()) return false; + for (size_t i = 0; i < N; i++) + if (a[i] != b[i]) return false; + return true; + } - /** - * operator overload to increment (prefix) - **/ - large_number &operator++() { - (*this) += 1; - return *this; - } + /** + * operator overload to compare two numbers + **/ + friend bool operator!=(large_number const &a, large_number const &b) { + return !(a == b); + } - /** - * operator overload to increment (postfix) - **/ - large_number operator++(int) { - large_number tmp(_digits); - ++(*this); - return tmp; - } + /** + * operator overload to increment (prefix) + **/ + large_number &operator++() { + (*this) += 1; + return *this; + } + + /** + * operator overload to increment (postfix) + **/ + large_number operator++(int) { + large_number tmp(_digits); + ++(*this); + return tmp; + } - /** - * operator overload to add - **/ - template - large_number &operator+=(T n) { - if (typeid(T) == - typeid(large_number)) // if adding with another large_number - { - large_number *b = (large_number *)&n; - const size_t max_L = std::max(this->num_digits(), b->num_digits()); - unsigned int carry = 0; - size_t i; - for (i = 0; i < max_L || carry != 0; i++) { - if (i < b->num_digits()) - carry += (*b)[i]; - if (i < this->num_digits()) - carry += (*this)[i]; - if (i < this->num_digits()) - (*this)[i] = carry % 10; - else - this->add_digit(carry % 10); - carry /= 10; - } - } else if (std::is_integral::value) - return (*this) += large_number(n); + /** + * operator overload to add + **/ + template + large_number &operator+=(T n) { + // if adding with another large_number + if (typeid(T) == typeid(large_number)) { + large_number *b = static_cast(&n); + const size_t max_L = std::max(this->num_digits(), b->num_digits()); + unsigned int carry = 0; + size_t i; + for (i = 0; i < max_L || carry != 0; i++) { + if (i < b->num_digits()) carry += (*b)[i]; + if (i < this->num_digits()) carry += (*this)[i]; + if (i < this->num_digits()) + (*this)[i] = carry % 10; else - std::cerr << "Must be integer addition unsigned integer types." - << std::endl; - return *this; + this->add_digit(carry % 10); + carry /= 10; + } + } else if (std::is_integral::value) { + return (*this) += large_number(n); + } else { + std::cerr << "Must be integer addition unsigned integer types." + << std::endl; } + return *this; + } - /** - * operator overload to perform addition - **/ - template - friend large_number &operator+(large_number &a, const T &b) { - a += b; - return a; - } + /** + * operator overload to perform addition + **/ + template + friend large_number &operator+(const large_number &a, const T &b) { + a += b; + return a; + } - /** - * assignment operator - **/ - void operator=(const large_number &b) { _digits = b._digits; } + /** + * assignment operator + **/ + void operator=(const large_number &b) { _digits = b._digits; } - /** - * operator overload to increment - **/ - template - large_number &operator*=(const T n) { - static_assert(std::is_integral::value, - "Must be integer addition unsigned integer types."); - this->multiply(n); - return *this; - } + /** + * operator overload to increment + **/ + template + large_number &operator*=(const T n) { + static_assert(std::is_integral::value, + "Must be integer addition unsigned integer types."); + this->multiply(n); + return *this; + } - /** - * returns i^th digit as an ASCII character - **/ - const char digit_char(size_t i) const { - return _digits[num_digits() - i - 1] + '0'; - } + /** + * returns i^th digit as an ASCII character + **/ + const char digit_char(size_t i) const { + return _digits[num_digits() - i - 1] + '0'; + } -private: - /** - * multiply large number with another integer and - * store the result in the same large number - **/ - template - void multiply(const T n) { - static_assert(std::is_integral::value, - "Can only have integer types."); - // assert(!(std::is_signed::value)); //, "Implemented only for - // unsigned integer types."); + private: + /** + * multiply large number with another integer and + * store the result in the same large number + **/ + template + void multiply(const T n) { + static_assert(std::is_integral::value, "Can only have integer types."); + // assert(!(std::is_signed::value)); //, "Implemented only for + // unsigned integer types."); - size_t i; - unsigned long long carry = 0, temp; - for (i = 0; i < this->num_digits(); i++) { - temp = (*this)[i] * n; - temp += carry; - if (temp < 10) - carry = 0; - else { - carry = temp / 10; - temp = temp % 10; - } - (*this)[i] = temp; - } + size_t i; + uint64_t carry = 0, temp; + for (i = 0; i < this->num_digits(); i++) { + temp = (*this)[i] * n; + temp += carry; + if (temp < 10) { + carry = 0; + } else { + carry = temp / 10; + temp = temp % 10; + } + (*this)[i] = temp; + } - while (carry != 0) { - this->add_digit(carry % 10); - carry /= 10; - } - }; + while (carry != 0) { + this->add_digit(carry % 10); + carry /= 10; + } + } - std::vector - _digits; /**< where individual digits are stored */ + std::vector _digits; /**< where individual digits are stored */ }; #endif // OTHERS_LARGE_NUMBER_H_ From 58f77c404696402bc5b45174ad1f02baaedfda4b Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 24 May 2020 16:27:18 -0400 Subject: [PATCH 023/433] remove erroneous const from `+` operator --- others/large_number.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/others/large_number.h b/others/large_number.h index 4f3851053f9..38d9125dee2 100644 --- a/others/large_number.h +++ b/others/large_number.h @@ -207,7 +207,7 @@ class large_number { * operator overload to perform addition **/ template - friend large_number &operator+(const large_number &a, const T &b) { + friend large_number &operator+(large_number &a, const T &b) { a += b; return a; } From 251c32d8b334779c0ac891422a2722d3ba4660fa Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Mon, 25 May 2020 11:03:30 -0400 Subject: [PATCH 024/433] Update .vscode/settings.json removed additional comma in the JSON Co-authored-by: Christian Clauss --- .vscode/settings.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 5815b26668b..4d291141b4d 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -64,7 +64,7 @@ "valarray": "cpp", "algorithm": "cpp" }, - "C_Cpp.clang_format_style": "{ BasedOnStyle: Google, UseTab: Never, IndentWidth: 4, TabWidth: 4,, AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: true, ColumnLimit: 80, AccessModifierOffset: -4, NamespaceIndentation: All }", + "C_Cpp.clang_format_style": "{ BasedOnStyle: Google, UseTab: Never, IndentWidth: 4, TabWidth: 4, AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: true, ColumnLimit: 80, AccessModifierOffset: -4, NamespaceIndentation: All }", "editor.formatOnSave": true, "editor.formatOnType": true, "editor.formatOnPaste": true From 64f07fc21a985c403b5295f5bef0ae5401c9efbd Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Mon, 25 May 2020 21:43:52 -0400 Subject: [PATCH 025/433] initial cmake --- CMakeLists.txt | 75 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 00000000000..f98109382ba --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,75 @@ +cmake_minimum_required(VERSION 3.3) +project(Algorithms_in_C + LANGUAGES C CXX + VERSION 1.0.0 + DESCRIPTION "Set of algorithms implemented in C." +) + +option(USE_OPENMP "flag to use OpenMP for multithreading" ON) + +cmake_policy(SET CMP0054 NEW) +cmake_policy(SET CMP0057 NEW) +find_package(Doxygen OPTIONAL_COMPONENTS dot dia) +if(DOXYGEN_FOUND) + set(DOXYGEN_GENERATE_MAN NO) + set(DOXYGEN_USE_MATHJAX YES) + set(DOXYGEN_GENERATE_HTML YES) + set(DOXYGEN_INLINE_SOURCES YES) + set(DOXYGEN_CREATE_SUBDIRS YES) + set(DOCYGEN_GENERATE_TREEVIEW YES) + set(DOXYGEN_STRIP_CODE_COMMENTS NO) + set(DOXYGEN_OPTIMIZE_OUTPUT_FOR_C YES) + set(DOXYGEN_MATHJAX_RELPATH "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/MathJax.js?config=TeX-MML-AM_CHTML") + if(Doxygen_dot_FOUND) + set(DOXYGEN_HAVE_DOT YES) + set(DOXYGEN_CALL_GRAPH YES) + set(DOXYGEN_INTERACTIVE_SVG YES) + set(DOXYGEN_DOT_IMAGE_FORMAT "svg") + endif() + + doxygen_add_docs( + doc + ${PROJECT_SOURCE_DIR} + COMMENT "Generate documentation" + ) +endif() + +function(function_timer) + set(CMAKE_BUILD_TYPE "Release") # This is local to function + add_subdirectory(function_timer EXCLUDE_FROM_ALL) +endfunction() + +function_timer() + +include_directories(function_timer/include) +# link_libraries(function_timer) +# include_directories(${CMAKE_BINARY_DIR}/include) +# link_directories(${CMAKE_BINARY_DIR}/lib/${CMAKE_BUILD_TYPE}) + +set(CMAKE_C_STANDARD 11) +set(CMAKE_C_STANDARD_REQUIRED ON) + +if(MSVC) + add_compile_definitions(_CRT_SECURE_NO_WARNINGS) + add_compile_options(/Za) +endif(MSVC) + +add_subdirectory(conversions) +add_subdirectory(misc) +add_subdirectory(project_euler) +add_subdirectory(sorting) +add_subdirectory(searching) +add_subdirectory(numerical_methods) + +if(USE_OPENMP) + find_package(OpenMP) + if (OpenMP_C_FOUND) + message(STATUS "Building with OpenMP Multithreading.") + else() + message(STATUS "No OpenMP found, no multithreading.") + endif() +endif() + +set(CPACK_PROJECT_NAME ${PROJECT_NAME}) +set(CPACK_PROJECT_VERSION ${PROJECT_VERSION}) +include(CPack) From 0e3a57ab3fdf9bf11a4dd9c3b575656ba50decc3 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Mon, 25 May 2020 22:13:08 -0400 Subject: [PATCH 026/433] ignore build directory --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index ed3934e45be..12318c6cd0f 100644 --- a/.gitignore +++ b/.gitignore @@ -33,3 +33,5 @@ a.out *.out *.app + +build/ \ No newline at end of file From 412d3ff1a2fc491e4c8e0b05db814c186bdf7dc4 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Mon, 25 May 2020 22:13:39 -0400 Subject: [PATCH 027/433] file rename to standards --- math/{primes_up_to_10^8.cpp => primes_up_to_billion.cpp} | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) rename math/{primes_up_to_10^8.cpp => primes_up_to_billion.cpp} (79%) diff --git a/math/primes_up_to_10^8.cpp b/math/primes_up_to_billion.cpp similarity index 79% rename from math/primes_up_to_10^8.cpp rename to math/primes_up_to_billion.cpp index db9b56cab32..d8f5a9f9d3e 100644 --- a/math/primes_up_to_10^8.cpp +++ b/math/primes_up_to_billion.cpp @@ -1,12 +1,12 @@ -#include #include +#include char prime[100000000]; void Sieve(int64_t n) { memset(prime, '1', sizeof(prime)); // intitize '1' to every index - prime[0] = '0'; // 0 is not prime - prime[1] = '0'; // 1 is not prime + prime[0] = '0'; // 0 is not prime + prime[1] = '0'; // 1 is not prime for (int p = 2; p * p <= n; p++) { if (prime[p] == '1') { for (int i = p * p; i <= n; i += p) @@ -15,7 +15,6 @@ void Sieve(int64_t n) { } } - int main() { Sieve(100000000); int64_t n; From 260ba8d3a46e76b8d319c96b23983c9c2d93d046 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Mon, 25 May 2020 22:13:52 -0400 Subject: [PATCH 028/433] syntax correction --- math/fibonacci.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/math/fibonacci.cpp b/math/fibonacci.cpp index 1c07cd93fff..e82875da3c5 100644 --- a/math/fibonacci.cpp +++ b/math/fibonacci.cpp @@ -1,5 +1,5 @@ -#include #include +#include /* Calculate the the value on Fibonacci's sequence given an integer as input @@ -7,14 +7,13 @@ Fibonacci = 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ... */ -int fibonacci(uint n) { +int fibonacci(unsigned int n) { /* If the input is 0 or 1 just return the same This will set the first 2 values of the sequence */ - if (n <= 1) - return n; + if (n <= 1) return n; /* Add the last 2 values of the sequence to get next */ - return fibonacci(n-1) + fibonacci(n-2); + return fibonacci(n - 1) + fibonacci(n - 2); } int main() { From a1663277c76e8d814a745a596f864c2e1fdd9080 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Mon, 25 May 2020 22:51:18 -0400 Subject: [PATCH 029/433] cherry pick changes from "cmake branch" From 8207c776ebdbd3a77018651223e37780a151cc2a Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Mon, 25 May 2020 22:13:52 -0400 Subject: [PATCH 030/433] syntax correction (cherry picked from commit 260ba8d3a46e76b8d319c96b23983c9c2d93d046) --- math/fibonacci.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/math/fibonacci.cpp b/math/fibonacci.cpp index 1c07cd93fff..e82875da3c5 100644 --- a/math/fibonacci.cpp +++ b/math/fibonacci.cpp @@ -1,5 +1,5 @@ -#include #include +#include /* Calculate the the value on Fibonacci's sequence given an integer as input @@ -7,14 +7,13 @@ Fibonacci = 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ... */ -int fibonacci(uint n) { +int fibonacci(unsigned int n) { /* If the input is 0 or 1 just return the same This will set the first 2 values of the sequence */ - if (n <= 1) - return n; + if (n <= 1) return n; /* Add the last 2 values of the sequence to get next */ - return fibonacci(n-1) + fibonacci(n-2); + return fibonacci(n - 1) + fibonacci(n - 2); } int main() { From b36322c629809375de3abc30d48479efa4acddbf Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Mon, 25 May 2020 22:13:39 -0400 Subject: [PATCH 031/433] file rename to standards (cherry picked from commit 412d3ff1a2fc491e4c8e0b05db814c186bdf7dc4) --- math/{primes_up_to_10^8.cpp => primes_up_to_billion.cpp} | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) rename math/{primes_up_to_10^8.cpp => primes_up_to_billion.cpp} (79%) diff --git a/math/primes_up_to_10^8.cpp b/math/primes_up_to_billion.cpp similarity index 79% rename from math/primes_up_to_10^8.cpp rename to math/primes_up_to_billion.cpp index db9b56cab32..d8f5a9f9d3e 100644 --- a/math/primes_up_to_10^8.cpp +++ b/math/primes_up_to_billion.cpp @@ -1,12 +1,12 @@ -#include #include +#include char prime[100000000]; void Sieve(int64_t n) { memset(prime, '1', sizeof(prime)); // intitize '1' to every index - prime[0] = '0'; // 0 is not prime - prime[1] = '0'; // 1 is not prime + prime[0] = '0'; // 0 is not prime + prime[1] = '0'; // 1 is not prime for (int p = 2; p * p <= n; p++) { if (prime[p] == '1') { for (int i = p * p; i <= n; i += p) @@ -15,7 +15,6 @@ void Sieve(int64_t n) { } } - int main() { Sieve(100000000); int64_t n; From 1e5b9f842da6d3d25ef608f5fbdaf54f38631db8 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Mon, 25 May 2020 22:13:08 -0400 Subject: [PATCH 032/433] ignore build directory (cherry picked from commit 0e3a57ab3fdf9bf11a4dd9c3b575656ba50decc3) --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index ed3934e45be..12318c6cd0f 100644 --- a/.gitignore +++ b/.gitignore @@ -33,3 +33,5 @@ a.out *.out *.app + +build/ \ No newline at end of file From baea3b07c1588361ed1a514d39a2979c56ff4a6a Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Mon, 25 May 2020 22:56:38 -0400 Subject: [PATCH 033/433] major corrections in the files - bad CPPLINT and non-compilable codes --- .../Bisection_method.CPP | 75 ++++++++----------- .../Newton_Raphson.CPP | 53 ------------- .../Secant_method.CPP | 70 +++++++---------- .../newton_raphson_method.cpp | 41 ++++++++++ .../successive_approximation.CPP | 59 +++++++-------- math/prime_factorization.cpp | 46 +++++------- 6 files changed, 143 insertions(+), 201 deletions(-) delete mode 100644 computer_oriented_statistical_methods/Newton_Raphson.CPP create mode 100644 computer_oriented_statistical_methods/newton_raphson_method.cpp diff --git a/computer_oriented_statistical_methods/Bisection_method.CPP b/computer_oriented_statistical_methods/Bisection_method.CPP index 717987321cd..266083de1c1 100644 --- a/computer_oriented_statistical_methods/Bisection_method.CPP +++ b/computer_oriented_statistical_methods/Bisection_method.CPP @@ -1,53 +1,40 @@ -#include -#include -#include +#include +#include -float eq(float i) -{ - return (pow(i, 3) - (4 * i) - 9); // original equation +float eq(float i) { + return (std::pow(i, 3) - (4 * i) - 9); // original equation } -void main() -{ - float a, b, x, z; - clrscr(); - for (int i = 0; i < 100; i++) - { - z = eq(i); - if (z >= 0) - { - b = i; - a = --i; - goto START; - } - } +int main() { + float a, b, x, z; -START: + for (int i = 0; i < 100; i++) { + z = eq(i); + if (z >= 0) { + b = i; + a = --i; + break; + } + } - cout << "\nFirst initial: " << a; - cout << "\nSecond initial: " << b; - for (i = 0; i < 100; i++) - { - x = (a + b) / 2; - z = eq(x); - cout << "\n\nz: " << z << "\t[" << a << " , " << b << " | Bisect: " << x << "]"; + std::cout << "\nFirst initial: " << a; + std::cout << "\nSecond initial: " << b; + for (int i = 0; i < 100; i++) { + x = (a + b) / 2; + z = eq(x); + std::cout << "\n\nz: " << z << "\t[" << a << " , " << b + << " | Bisect: " << x << "]"; - if (z < 0) - { - a = x; - } - else - { - b = x; - } + if (z < 0) { + a = x; + } else { + b = x; + } - if (z > 0 && z < 0.0009) // stoping criteria - { - goto END; - } - } + if (z > 0 && z < 0.0009) // stoping criteria + break; + } -END: - cout << "\n\nRoot: " << x; - getch(); + std::cout << "\n\nRoot: " << x; + return 0; } diff --git a/computer_oriented_statistical_methods/Newton_Raphson.CPP b/computer_oriented_statistical_methods/Newton_Raphson.CPP deleted file mode 100644 index 183a78daf8a..00000000000 --- a/computer_oriented_statistical_methods/Newton_Raphson.CPP +++ /dev/null @@ -1,53 +0,0 @@ -#include -#include -#include - -float eq(float i) -{ - return (pow(i, 3) - (4 * i) - 9); // original equation -} -float eq_der(float i) -{ - return ((3 * pow(i, 2)) - 4); // derivative of equation -} - -void main() -{ - float a, b, z, c, m, n; - clrscr(); - for (int i = 0; i < 100; i++) - { - z = eq(i); - if (z >= 0) - { - b = i; - a = --i; - goto START; - } - } - -START: - - cout << "\nFirst initial: " << a; - cout << "\nSecond initial: " << b; - c = (a + b) / 2; - - for (i = 0; i < 100; i++) - { - float h; - m = eq(c); - n = eq_der(c); - - z = c - (m / n); - c = z; - - if (m > 0 && m < 0.009) // stoping criteria - { - goto END; - } - } - -END: - cout << "\n\nRoot: " << z; - getch(); -} diff --git a/computer_oriented_statistical_methods/Secant_method.CPP b/computer_oriented_statistical_methods/Secant_method.CPP index b897e9184f4..bd805ed3682 100644 --- a/computer_oriented_statistical_methods/Secant_method.CPP +++ b/computer_oriented_statistical_methods/Secant_method.CPP @@ -1,49 +1,37 @@ -#include -#include -#include +#include +#include -float eq(float i) -{ - return (pow(i, 3) - (4 * i) - 9); // original equation +float eq(float i) { + return (pow(i, 3) - (4 * i) - 9); // original equation } -void main() -{ - float a, b, z, c, m, n; - clrscr(); - for (int i = 0; i < 100; i++) - { - z = eq(i); - if (z >= 0) - { - b = i; - a = --i; - goto START; - } - } +int main() { + float a, b, z, c, m, n; + for (int i = 0; i < 100; i++) { + z = eq(i); + if (z >= 0) { + b = i; + a = --i; + break; + } + } -START: + std::cout << "\nFirst initial: " << a; + std::cout << "\nSecond initial: " << b; + for (int i = 0; i < 100; i++) { + float h, d; + m = eq(a); + n = eq(b); - cout << "\nFirst initial: " << a; - cout << "\nSecond initial: " << b; - for (i = 0; i < 100; i++) - { - float h, d; - m = eq(a); - n = eq(b); + c = ((a * n) - (b * m)) / (n - m); + a = b; + b = c; - c = ((a * n) - (b * m)) / (n - m); - a = b; - b = c; + z = eq(c); + if (z > 0 && z < 0.09) // stoping criteria + break; + } - z = eq(c); - if (z > 0 && z < 0.09) // stoping criteria - { - goto END; - } - } - -END: - cout << "\n\nRoot: " << c; - getch(); + std::cout << "\n\nRoot: " << c; + return 0; } diff --git a/computer_oriented_statistical_methods/newton_raphson_method.cpp b/computer_oriented_statistical_methods/newton_raphson_method.cpp new file mode 100644 index 00000000000..a2a57768ede --- /dev/null +++ b/computer_oriented_statistical_methods/newton_raphson_method.cpp @@ -0,0 +1,41 @@ +#include +#include + +float eq(float i) { + return (std::pow(i, 3) - (4 * i) - 9); // original equation +} +float eq_der(float i) { + return ((3 * std::pow(i, 2)) - 4); // derivative of equation +} + +int main() { + float a, b, z, c, m, n; + + for (int i = 0; i < 100; i++) { + z = eq(i); + if (z >= 0) { + b = i; + a = --i; + break; + } + } + + std::cout << "\nFirst initial: " << a; + std::cout << "\nSecond initial: " << b; + c = (a + b) / 2; + + for (int i = 0; i < 100; i++) { + float h; + m = eq(c); + n = eq_der(c); + + z = c - (m / n); + c = z; + + if (m > 0 && m < 0.009) // stoping criteria + break; + } + + std::cout << "\n\nRoot: " << z << std::endl; + return 0; +} diff --git a/computer_oriented_statistical_methods/successive_approximation.CPP b/computer_oriented_statistical_methods/successive_approximation.CPP index b42ab8f8c11..85c42c9fb98 100644 --- a/computer_oriented_statistical_methods/successive_approximation.CPP +++ b/computer_oriented_statistical_methods/successive_approximation.CPP @@ -1,37 +1,28 @@ -#include -#include -#include -float eq(float y) -{ - return ((3 * y) - (cos(y)) - 2); -} -float eqd(float y) -{ - return ((0.5) * ((cos(y)) + 2)); -} -void main() -{ - float y, x1, x2, x3, sum, s, a, f1, f2, gd; - int i, n; +#include +#include + +float eq(float y) { return ((3 * y) - (cos(y)) - 2); } +float eqd(float y) { return ((0.5) * ((cos(y)) + 2)); } - clrscr(); - for (i = 0; i < 10; i++) - { - sum = eq(y); - cout << "value of equation at " << i << " " << sum << "\n"; - y++; - } - cout << "enter the x1->"; - cin >> x1; - cout << "enter the no iteration to perform->\n"; - cin >> n; +int main() { + float y, x1, x2, x3, sum, s, a, f1, f2, gd; + int i, n; - for (i = 0; i <= n; i++) - { - x2 = eqd(x1); - cout << "\nenter the x2->" << x2; - x1 = x2; - } - getch(); -} \ No newline at end of file + for (i = 0; i < 10; i++) { + sum = eq(y); + std::cout << "value of equation at " << i << " " << sum << "\n"; + y++; + } + std::cout << "enter the x1->"; + std::cin >> x1; + std::cout << "enter the no iteration to perform->\n"; + std::cin >> n; + + for (i = 0; i <= n; i++) { + x2 = eqd(x1); + std::cout << "\nenter the x2->" << x2; + x1 = x2; + } + return 0; +} diff --git a/math/prime_factorization.cpp b/math/prime_factorization.cpp index 822cad332c6..bd1b99d9793 100644 --- a/math/prime_factorization.cpp +++ b/math/prime_factorization.cpp @@ -1,67 +1,56 @@ +#include +#include #include #include -#include using namespace std; -// Declaring variables for maintaing prime numbers and to check whether a number is prime or not +// Declaring variables for maintaing prime numbers and to check whether a number +// is prime or not bool isprime[1000006]; vector prime_numbers; vector> factors; // Calculating prime number upto a given range -void SieveOfEratosthenes(int N) -{ +void SieveOfEratosthenes(int N) { // initializes the array isprime memset(isprime, true, sizeof isprime); - for (int i = 2; i <= N; i++) - { - if (isprime[i]) - { - for (int j = 2 * i; j <= N; j += i) - isprime[j] = false; + for (int i = 2; i <= N; i++) { + if (isprime[i]) { + for (int j = 2 * i; j <= N; j += i) isprime[j] = false; } } - for (int i = 2; i <= N; i++) - { - if (isprime[i]) - prime_numbers.push_back(i); + for (int i = 2; i <= N; i++) { + if (isprime[i]) prime_numbers.push_back(i); } } // Prime factorization of a number -void prime_factorization(int num) -{ - +void prime_factorization(int num) { int number = num; - for (int i = 0; prime_numbers[i] <= num; i++) - { + for (int i = 0; prime_numbers[i] <= num; i++) { int count = 0; // termination condition - if (number == 1) - { + if (number == 1) { break; } - while (number % prime_numbers[i] == 0) - { + while (number % prime_numbers[i] == 0) { count++; number = number / prime_numbers[i]; } - if (count) - factors.push_back(make_pair(prime_numbers[i], count)); + if (count) factors.push_back(make_pair(prime_numbers[i], count)); } } /* I added a simple UI. */ -int main() -{ +int main() { int num; cout << "\t\tComputes the prime factorization\n\n"; cout << "Type in a number: "; @@ -72,8 +61,7 @@ int main() prime_factorization(num); // Prime factors with their powers in the given number in new line - for (auto it : factors) - { + for (auto it : factors) { cout << it.first << " " << it.second << endl; } From ef24ae3a09a0db7a8988ddf9fcaff985e2d7d43f Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 26 May 2020 02:57:04 +0000 Subject: [PATCH 034/433] updating DIRECTORY.md --- DIRECTORY.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index 9e36309dc6a..17cd5f5c69e 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -13,7 +13,7 @@ * [Bisection Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/Bisection_method.CPP) * [False-Position](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/false-position.cpp) * [Gaussian Elimination](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/Gaussian_elimination.cpp) - * [Newton Raphson](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/Newton_Raphson.CPP) + * [Newton Raphson Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/newton_raphson_method.cpp) * [Ordinary Least Squares Regressor](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp) * [Secant Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/Secant_method.CPP) * [Successive Approximation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/successive_approximation.CPP) @@ -116,7 +116,7 @@ * [Power For Huge Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/power_for_huge_numbers.cpp) * [Prime Factorization](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/prime_factorization.cpp) * [Prime Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/prime_numbers.cpp) - * [Primes Up To 10^8](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/primes_up_to_10^8.cpp) + * [Primes Up To Billion](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/primes_up_to_billion.cpp) * [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/sieve_of_eratosthenes.cpp) * [Sqrt Double](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/sqrt_double.cpp) From 4e8a2f715197b92879cf599d9073578b940ab9af Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Mon, 25 May 2020 23:12:12 -0400 Subject: [PATCH 035/433] non compiling and illegible code removed --- others/Strassen Matrix Multiplication.cpp | 56 ----------------------- 1 file changed, 56 deletions(-) delete mode 100644 others/Strassen Matrix Multiplication.cpp diff --git a/others/Strassen Matrix Multiplication.cpp b/others/Strassen Matrix Multiplication.cpp deleted file mode 100644 index 85b62776385..00000000000 --- a/others/Strassen Matrix Multiplication.cpp +++ /dev/null @@ -1,56 +0,0 @@ -#include -using namespace std; - -Multiply(int A[][], int B[][], int n) -{ - if (n == 2) - { - int p1 = (a[0][0] + a[1][1]) * (b[0][0] + b[1][1]); - int p2 = (a[1][0] + a[1][1]) * b[0][0]; - int p3 = a[0][0] * (b[0][1] - b[1][1]); - int p4 = a[1][1] * (b[1][0] - b[0][0]); - int p5 = (a[0][0] + a[0][1]) * b[1][1]; - int p6 = (a[1][0] - a[0][0]) * (b[0][0] + b[0][1]); - int p7 = (a[0][1] - a[1][1]) * (b[1][0] + b[1][1]); - - int c[n][n]; - c[0][0] = p1 + p4 - p5 + p7; - c[0][1] = p3 + p5; - c[1][0] = p2 + p4; - c[1][1] = p1 - p2 + p3 + p6; - - return c[][]; - } - else - { - } -} - -int main() -{ - int p, q, r, s; - cout << "Enter the dimensions of Matrices"; - cin >> n; - int A[n][n], ; - int B[n][n], ; - cout << "Enter the elements of Matrix A"; - for (int i = 0; i < n; i++) - { - for (int j = 0; j < n; j++) - { - cin >> A[i][j]; - } - } - - cout << "Enter the elements of Matrix B"; - for (int i = 0; i < n; i++) - { - for (int j = 0; j < n; j++) - { - cin >> B[i][j]; - } - } - - Multiply(A, B, n); - return 0; -} \ No newline at end of file From 120fe06fcb0d75c944c9453d703a20ce91e46e80 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Mon, 25 May 2020 23:13:26 -0400 Subject: [PATCH 036/433] files renamed to standard - without spaces and made CPPLINT compatible --- others/GCD_of_n_numbers.cpp | 41 ++++--- ...al To Binary.cpp => decimal_to_binary.cpp} | 0 ...ecimal .cpp => decimal_to_hexadecimal.cpp} | 0 ...meral.cpp => decimal_to_roman_numeral.cpp} | 0 others/fibonacci.cpp | 42 ------- others/fibonacci_fast.cpp | 37 ++++++ others/matrix_exponentiation.cpp | 14 +-- ... Matching.cpp => paranthesis_matching.cpp} | 0 others/pascal_triangle.cpp | 106 ++++++++---------- ...{Primality Test.cpp => primality_test.cpp} | 0 .../{Sparse matrix.cpp => sparse_matrix.cpp} | 0 ...ing Fibonacci.cpp => string_fibonacci.cpp} | 0 ...{Tower of Hanoi.cpp => tower_of_hanoi.cpp} | 0 sorting/shell_sort2.cpp | 105 +++++++++++++++++ 14 files changed, 216 insertions(+), 129 deletions(-) rename others/{Decimal To Binary.cpp => decimal_to_binary.cpp} (100%) rename others/{Decimal To Hexadecimal .cpp => decimal_to_hexadecimal.cpp} (100%) rename others/{Decimal to Roman Numeral.cpp => decimal_to_roman_numeral.cpp} (100%) delete mode 100644 others/fibonacci.cpp create mode 100644 others/fibonacci_fast.cpp rename others/{Paranthesis Matching.cpp => paranthesis_matching.cpp} (100%) rename others/{Primality Test.cpp => primality_test.cpp} (100%) rename others/{Sparse matrix.cpp => sparse_matrix.cpp} (100%) rename others/{String Fibonacci.cpp => string_fibonacci.cpp} (100%) rename others/{Tower of Hanoi.cpp => tower_of_hanoi.cpp} (100%) create mode 100644 sorting/shell_sort2.cpp diff --git a/others/GCD_of_n_numbers.cpp b/others/GCD_of_n_numbers.cpp index 8158052f8fd..b592e59316a 100644 --- a/others/GCD_of_n_numbers.cpp +++ b/others/GCD_of_n_numbers.cpp @@ -1,23 +1,22 @@ -//This program aims at calculating the GCD of n numbers by division method +// This program aims at calculating the GCD of n numbers by division method #include -using namepsace std; -int main() -{ - cout << "Enter value of n:" << endl; - cin >> n; - int a[n]; - int i, j, gcd; - cout << "Enter the n numbers:" << endl; - for (i = 0; i < n; i++) - cin >> a[i]; - j = 1; //to access all elements of the array starting from 1 - gcd = a[0]; - while (j < n) - { - if (a[j] % gcd == 0) //value of gcd is as needed so far - j++; //so we check for next element - else - gcd = a[j] % gcd; //calculating GCD by division method - } - cout << "GCD of entered n numbers:" << gcd; + +int main() { + int n; + std::cout << "Enter value of n:" << std::endl; + std::cin >> n; + int a[n]; + int i, j, gcd; + std::cout << "Enter the n numbers:" << std::endl; + for (i = 0; i < n; i++) std::cin >> a[i]; + j = 1; // to access all elements of the array starting from 1 + gcd = a[0]; + while (j < n) { + if (a[j] % gcd == 0) // value of gcd is as needed so far + j++; // so we check for next element + else + gcd = a[j] % gcd; // calculating GCD by division method + } + std::cout << "GCD of entered n numbers:" << gcd; + return 0; } diff --git a/others/Decimal To Binary.cpp b/others/decimal_to_binary.cpp similarity index 100% rename from others/Decimal To Binary.cpp rename to others/decimal_to_binary.cpp diff --git a/others/Decimal To Hexadecimal .cpp b/others/decimal_to_hexadecimal.cpp similarity index 100% rename from others/Decimal To Hexadecimal .cpp rename to others/decimal_to_hexadecimal.cpp diff --git a/others/Decimal to Roman Numeral.cpp b/others/decimal_to_roman_numeral.cpp similarity index 100% rename from others/Decimal to Roman Numeral.cpp rename to others/decimal_to_roman_numeral.cpp diff --git a/others/fibonacci.cpp b/others/fibonacci.cpp deleted file mode 100644 index 87ccda6d3dd..00000000000 --- a/others/fibonacci.cpp +++ /dev/null @@ -1,42 +0,0 @@ -//An efficient way to calculate nth fibonacci number faster and simpler than O(nlogn) method of matrix exponentiation -//This works by using both recursion and dynamic programming. -//as 93rd fibonacci exceeds 19 digits, which cannot be stored in a single long long variable, we can only use it till 92nd fibonacci -//we can use it for 10000th fibonacci etc, if we implement bigintegers. -//This algorithm works with the fact that nth fibonacci can easily found if we have already found n/2th or (n+1)/2th fibonacci -//It is a property of fibonacci similar to matrix exponentiation. - -#include -#include -using namespace std; - -const long long MAX = 93; - -long long f[MAX] = {0}; - -long long fib(long long n) -{ - - if (n == 0) - return 0; - if (n == 1 || n == 2) - return (f[n] = 1); - - if (f[n]) - return f[n]; - - long long k = (n % 2 != 0) ? (n + 1) / 2 : n / 2; - - f[n] = (n % 2 != 0) ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) - : (2 * fib(k - 1) + fib(k)) * fib(k); - return f[n]; -} - -int main() -{ - //Main Function - for (long long i = 1; i < 93; i++) - { - cout << i << " th fibonacci number is " << fib(i) << "\n"; - } - return 0; -} diff --git a/others/fibonacci_fast.cpp b/others/fibonacci_fast.cpp new file mode 100644 index 00000000000..dd348142256 --- /dev/null +++ b/others/fibonacci_fast.cpp @@ -0,0 +1,37 @@ +// An efficient way to calculate nth fibonacci number faster and simpler than +// O(nlogn) method of matrix exponentiation This works by using both recursion +// and dynamic programming. as 93rd fibonacci exceeds 19 digits, which cannot be +// stored in a single long long variable, we can only use it till 92nd fibonacci +// we can use it for 10000th fibonacci etc, if we implement bigintegers. +// This algorithm works with the fact that nth fibonacci can easily found if we +// have already found n/2th or (n+1)/2th fibonacci It is a property of fibonacci +// similar to matrix exponentiation. + +#include +#include +using namespace std; + +const long long MAX = 93; + +long long f[MAX] = {0}; + +long long fib(long long n) { + if (n == 0) return 0; + if (n == 1 || n == 2) return (f[n] = 1); + + if (f[n]) return f[n]; + + long long k = (n % 2 != 0) ? (n + 1) / 2 : n / 2; + + f[n] = (n % 2 != 0) ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) + : (2 * fib(k - 1) + fib(k)) * fib(k); + return f[n]; +} + +int main() { + // Main Function + for (long long i = 1; i < 93; i++) { + cout << i << " th fibonacci number is " << fib(i) << "\n"; + } + return 0; +} diff --git a/others/matrix_exponentiation.cpp b/others/matrix_exponentiation.cpp index 25c411ddacb..f9b4997e970 100644 --- a/others/matrix_exponentiation.cpp +++ b/others/matrix_exponentiation.cpp @@ -19,6 +19,8 @@ The first element of this matrix is the required result. */ #include +#include + using std::cin; using std::cout; using std::vector; @@ -46,8 +48,7 @@ vector> multiply(vector> A, vector> B) { // computing power of a matrix vector> power(vector> A, ll p) { - if (p == 1) - return A; + if (p == 1) return A; if (p % 2 == 1) { return multiply(A, power(A, p - 1)); } else { @@ -58,14 +59,11 @@ vector> power(vector> A, ll p) { // main function ll ans(ll n) { - if (n == 0) - return 0; - if (n <= k) - return b[n - 1]; + if (n == 0) return 0; + if (n <= k) return b[n - 1]; // F1 vector F1(k + 1); - for (ll i = 1; i <= k; i++) - F1[i] = b[i - 1]; + for (ll i = 1; i <= k; i++) F1[i] = b[i - 1]; // Transpose matrix vector> T(k + 1, vector(k + 1)); diff --git a/others/Paranthesis Matching.cpp b/others/paranthesis_matching.cpp similarity index 100% rename from others/Paranthesis Matching.cpp rename to others/paranthesis_matching.cpp diff --git a/others/pascal_triangle.cpp b/others/pascal_triangle.cpp index 101100018fa..063a6666a3a 100644 --- a/others/pascal_triangle.cpp +++ b/others/pascal_triangle.cpp @@ -1,63 +1,53 @@ -#include - -using namespace std; - -void show_pascal(int **arr, int n) -{ - //pint Pascal's Triangle - for (int i = 0; i < n; ++i) - { - for (int j = 0; j < n + i; ++j) - { - if (arr[i][j] == 0) - cout << " "; - else - cout << arr[i][j]; - } - cout << endl; - } +#include +#include + +void show_pascal(int **arr, int n) { + // pint Pascal's Triangle + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n + i; ++j) { + if (arr[i][j] == 0) + std::cout << " "; + else + std::cout << arr[i][j]; + } + std::cout << std::endl; + } } -int **pascal_triangle(int **arr, int n) -{ - for (int i = 0; i < n; ++i) - { - for (int j = n - i - 1; j < n + i; ++j) - { - if (j == n - i - 1 || j == n + i - 1) - arr[i][j] = 1; //The edge of the Pascal triangle goes in 1 - else - arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j + 1]; - } - } - - return arr; +int **pascal_triangle(int **arr, int n) { + for (int i = 0; i < n; ++i) { + for (int j = n - i - 1; j < n + i; ++j) { + if (j == n - i - 1 || j == n + i - 1) + arr[i][j] = 1; // The edge of the Pascal triangle goes in 1 + else + arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j + 1]; + } + } + + return arr; } -int main() -{ - int n = 0; - - cout << "Set Pascal's Triangle Height" << endl; - cin >> n; - - //memory allocation (Assign two-dimensional array to store Pascal triangle) - int **arr = new int*[n]; - for (int i = 0; i < n; ++i) - { - arr[i] = new int[2 * n - 1]; - memset(arr[i], 0, sizeof(int)*(2 * n - 1)); - } - - pascal_triangle(arr, n); - show_pascal(arr, n); - - //deallocation - for (int i = 0; i < n; ++i) - { - delete[] arr[i]; - } - delete[] arr; - - return 0; +int main() { + int n = 0; + + std::cout << "Set Pascal's Triangle Height" << std::endl; + std::cin >> n; + + // memory allocation (Assign two-dimensional array to store Pascal triangle) + int **arr = new int *[n]; + for (int i = 0; i < n; ++i) { + arr[i] = new int[2 * n - 1]; + memset(arr[i], 0, sizeof(int) * (2 * n - 1)); + } + + pascal_triangle(arr, n); + show_pascal(arr, n); + + // deallocation + for (int i = 0; i < n; ++i) { + delete[] arr[i]; + } + delete[] arr; + + return 0; } diff --git a/others/Primality Test.cpp b/others/primality_test.cpp similarity index 100% rename from others/Primality Test.cpp rename to others/primality_test.cpp diff --git a/others/Sparse matrix.cpp b/others/sparse_matrix.cpp similarity index 100% rename from others/Sparse matrix.cpp rename to others/sparse_matrix.cpp diff --git a/others/String Fibonacci.cpp b/others/string_fibonacci.cpp similarity index 100% rename from others/String Fibonacci.cpp rename to others/string_fibonacci.cpp diff --git a/others/Tower of Hanoi.cpp b/others/tower_of_hanoi.cpp similarity index 100% rename from others/Tower of Hanoi.cpp rename to others/tower_of_hanoi.cpp diff --git a/sorting/shell_sort2.cpp b/sorting/shell_sort2.cpp new file mode 100644 index 00000000000..1268c7a50e7 --- /dev/null +++ b/sorting/shell_sort2.cpp @@ -0,0 +1,105 @@ +#include +#include +#include +#include + +// for std::swap +#include + +template void show_data(T *arr, size_t LEN) { + size_t i; + + for (i = 0; i < LEN; i++) + std::cout << arr[i] << ", "; + std::cout << std::endl; +} + +template void show_data(T (&arr)[N]) { show_data(arr, N); } + +/** + * Optimized algorithm - takes half the time by utilizing + * Mar + **/ +template void shell_sort(T *arr, size_t LEN) { + const unsigned int gaps[] = {701, 301, 132, 57, 23, 10, 4, 1}; + const unsigned int gap_len = 8; + size_t i, j, g; + + for (g = 0; g < gap_len; g++) { + unsigned int gap = gaps[g]; + for (i = gap; i < LEN; i++) { + T tmp = arr[i]; + + for (j = i; j >= gap && (arr[j - gap] - tmp) > 0; j -= gap) + arr[j] = arr[j - gap]; + + arr[j] = tmp; + } + } +} + +template void shell_sort(T (&arr)[N]) { + shell_sort(arr, N); +} + +/** + * function to compare sorting using cstdlib's qsort + **/ +int compare(const void *a, const void *b) { + int arg1 = *static_cast(a); + int arg2 = *static_cast(b); + + if (arg1 < arg2) + return -1; + if (arg1 > arg2) + return 1; + return 0; + + // return (arg1 > arg2) - (arg1 < arg2); // possible shortcut + // return arg1 - arg2; // erroneous shortcut (fails if INT_MIN is present) +} + +int main(int argc, char *argv[]) { + int i, NUM_DATA; + + if (argc == 2) + NUM_DATA = atoi(argv[1]); + else + NUM_DATA = 200; + + // int array = new int[NUM_DATA]; + int *data = new int[NUM_DATA]; + int *data2 = new int[NUM_DATA]; + // int array2 = new int[NUM_DATA]; + int range = 1800; + + std::srand(time(NULL)); + for (i = 0; i < NUM_DATA; i++) + data[i] = data2[i] = (std::rand() % range) - (range >> 1); + + std::cout << "Unsorted original data: " << std::endl; + show_data(data, NUM_DATA); + std::clock_t start = std::clock(); + shell_sort(data, NUM_DATA); + std::clock_t end = std::clock(); + + std::cout << std::endl + << "Data Sorted using custom implementation: " << std::endl; + show_data(data, NUM_DATA); + + double elapsed_time = (end - start) * 1.f / CLOCKS_PER_SEC; + std::cout << "Time spent sorting: " << elapsed_time << "s\n" << std::endl; + + start = std::clock(); + qsort(data2, NUM_DATA, sizeof(data2[0]), compare); + end = std::clock(); + std::cout << "Data Sorted using cstdlib qsort: " << std::endl; + show_data(data2, NUM_DATA); + + elapsed_time = (end - start) * 1.f / CLOCKS_PER_SEC; + std::cout << "Time spent sorting: " << elapsed_time << "s\n" << std::endl; + + free(data); + free(data2); + return 0; +} From 15d481f8ca7e7a33b2d567108ea58252ec2318fe Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 26 May 2020 03:13:48 +0000 Subject: [PATCH 037/433] updating DIRECTORY.md --- DIRECTORY.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index 17cd5f5c69e..644c57056c8 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -133,27 +133,26 @@ ## Others * [Buzz Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Buzz_number.cpp) - * [Decimal To Binary](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Decimal%20To%20Binary.cpp) - * [Decimal To Hexadecimal ](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Decimal%20To%20Hexadecimal%20.cpp) - * [Decimal To Roman Numeral](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Decimal%20to%20Roman%20Numeral.cpp) + * [Decimal To Binary](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/decimal_to_binary.cpp) + * [Decimal To Hexadecimal](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/decimal_to_hexadecimal.cpp) + * [Decimal To Roman Numeral](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/decimal_to_roman_numeral.cpp) * [Fast Interger Input](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/fast_interger_input.cpp) - * [Fibonacci](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/fibonacci.cpp) + * [Fibonacci Fast](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/fibonacci_fast.cpp) * [Gcd Of N Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/GCD_of_n_numbers.cpp) * [Happy Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/happy_number.cpp) * [Matrix Exponentiation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/matrix_exponentiation.cpp) * [Measure Time Elapsed](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/measure_time_elapsed.cpp) * [Palindromeofnumber](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Palindromeofnumber.cpp) - * [Paranthesis Matching](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Paranthesis%20Matching.cpp) + * [Paranthesis Matching](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/paranthesis_matching.cpp) * [Pascal Triangle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/pascal_triangle.cpp) - * [Primality Test](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Primality%20Test.cpp) + * [Primality Test](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/primality_test.cpp) * [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/sieve_of_Eratosthenes.cpp) * [Smallest-Circle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/smallest-circle.cpp) - * [Sparse Matrix](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Sparse%20matrix.cpp) + * [Sparse Matrix](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/sparse_matrix.cpp) * [Spiral Print](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/spiral_print.cpp) * [Stairs Pattern](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/stairs_pattern.cpp) - * [Strassen Matrix Multiplication](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Strassen%20Matrix%20Multiplication.cpp) - * [String Fibonacci](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/String%20Fibonacci.cpp) - * [Tower Of Hanoi](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Tower%20of%20Hanoi.cpp) + * [String Fibonacci](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/string_fibonacci.cpp) + * [Tower Of Hanoi](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/tower_of_hanoi.cpp) * [Vector Important Functions](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/vector_important_functions.cpp) ## Probability @@ -200,6 +199,7 @@ * [Radix Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Radix%20Sort.cpp) * [Selection Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Selection%20Sort.cpp) * [Shell Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Shell%20Sort.cpp) + * [Shell Sort2](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/shell_sort2.cpp) * [Slow Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Slow%20Sort.cpp) * [Swap Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/swap_sort.cpp) * [Tim Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Tim%20Sort.cpp) From 82dab7515cfc8a0ce11843ecb5bebcec64788c7c Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Mon, 25 May 2020 23:22:26 -0400 Subject: [PATCH 038/433] filenames and namespace fixes --- .../{Secant_method.CPP => secant_method.cpp} | 0 ...oximation.CPP => successive_approximation.cpp} | 0 math/prime_factorization.cpp | 15 +++++++-------- others/GCD_of_n_numbers.cpp | 3 ++- others/fibonacci_fast.cpp | 3 +-- 5 files changed, 10 insertions(+), 11 deletions(-) rename computer_oriented_statistical_methods/{Secant_method.CPP => secant_method.cpp} (100%) rename computer_oriented_statistical_methods/{successive_approximation.CPP => successive_approximation.cpp} (100%) diff --git a/computer_oriented_statistical_methods/Secant_method.CPP b/computer_oriented_statistical_methods/secant_method.cpp similarity index 100% rename from computer_oriented_statistical_methods/Secant_method.CPP rename to computer_oriented_statistical_methods/secant_method.cpp diff --git a/computer_oriented_statistical_methods/successive_approximation.CPP b/computer_oriented_statistical_methods/successive_approximation.cpp similarity index 100% rename from computer_oriented_statistical_methods/successive_approximation.CPP rename to computer_oriented_statistical_methods/successive_approximation.cpp diff --git a/math/prime_factorization.cpp b/math/prime_factorization.cpp index bd1b99d9793..c018de6662a 100644 --- a/math/prime_factorization.cpp +++ b/math/prime_factorization.cpp @@ -2,13 +2,12 @@ #include #include #include -using namespace std; // Declaring variables for maintaing prime numbers and to check whether a number // is prime or not bool isprime[1000006]; -vector prime_numbers; -vector> factors; +std::vector prime_numbers; +std::vector> factors; // Calculating prime number upto a given range void SieveOfEratosthenes(int N) { @@ -43,7 +42,7 @@ void prime_factorization(int num) { number = number / prime_numbers[i]; } - if (count) factors.push_back(make_pair(prime_numbers[i], count)); + if (count) factors.push_back(std::make_pair(prime_numbers[i], count)); } } @@ -52,9 +51,9 @@ void prime_factorization(int num) { */ int main() { int num; - cout << "\t\tComputes the prime factorization\n\n"; - cout << "Type in a number: "; - cin >> num; + std::cout << "\t\tComputes the prime factorization\n\n"; + std::cout << "Type in a number: "; + std::cin >> num; SieveOfEratosthenes(num); @@ -62,7 +61,7 @@ int main() { // Prime factors with their powers in the given number in new line for (auto it : factors) { - cout << it.first << " " << it.second << endl; + std::cout << it.first << " " << it.second << std::endl; } return 0; diff --git a/others/GCD_of_n_numbers.cpp b/others/GCD_of_n_numbers.cpp index b592e59316a..37e82173a94 100644 --- a/others/GCD_of_n_numbers.cpp +++ b/others/GCD_of_n_numbers.cpp @@ -5,7 +5,7 @@ int main() { int n; std::cout << "Enter value of n:" << std::endl; std::cin >> n; - int a[n]; + int *a = new int[n]; int i, j, gcd; std::cout << "Enter the n numbers:" << std::endl; for (i = 0; i < n; i++) std::cin >> a[i]; @@ -18,5 +18,6 @@ int main() { gcd = a[j] % gcd; // calculating GCD by division method } std::cout << "GCD of entered n numbers:" << gcd; + delete[] a; return 0; } diff --git a/others/fibonacci_fast.cpp b/others/fibonacci_fast.cpp index dd348142256..381a82d7c94 100644 --- a/others/fibonacci_fast.cpp +++ b/others/fibonacci_fast.cpp @@ -9,7 +9,6 @@ #include #include -using namespace std; const long long MAX = 93; @@ -31,7 +30,7 @@ long long fib(long long n) { int main() { // Main Function for (long long i = 1; i < 93; i++) { - cout << i << " th fibonacci number is " << fib(i) << "\n"; + std::cout << i << " th fibonacci number is " << fib(i) << "\n"; } return 0; } From 4c7685fdf6f14a6ae9924757f5f9bf05281812d8 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 26 May 2020 03:22:58 +0000 Subject: [PATCH 039/433] updating DIRECTORY.md --- DIRECTORY.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index 644c57056c8..f215744548d 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -15,8 +15,8 @@ * [Gaussian Elimination](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/Gaussian_elimination.cpp) * [Newton Raphson Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/newton_raphson_method.cpp) * [Ordinary Least Squares Regressor](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp) - * [Secant Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/Secant_method.CPP) - * [Successive Approximation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/successive_approximation.CPP) + * [Secant Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/secant_method.cpp) + * [Successive Approximation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/successive_approximation.cpp) ## Data Structure * [Avltree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/AVLtree.cpp) From c93f3ef35eb05cef312be1cab83bafda83f6011b Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Mon, 25 May 2020 23:25:44 -0400 Subject: [PATCH 040/433] fix inttypes --- others/fibonacci_fast.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/others/fibonacci_fast.cpp b/others/fibonacci_fast.cpp index 381a82d7c94..a0b83b640b2 100644 --- a/others/fibonacci_fast.cpp +++ b/others/fibonacci_fast.cpp @@ -7,20 +7,21 @@ // have already found n/2th or (n+1)/2th fibonacci It is a property of fibonacci // similar to matrix exponentiation. +#include #include #include -const long long MAX = 93; +const uint64_t MAX = 93; -long long f[MAX] = {0}; +uint64_t f[MAX] = {0}; -long long fib(long long n) { +uint64_t fib(uint64_t n) { if (n == 0) return 0; if (n == 1 || n == 2) return (f[n] = 1); if (f[n]) return f[n]; - long long k = (n % 2 != 0) ? (n + 1) / 2 : n / 2; + uint64_t k = (n % 2 != 0) ? (n + 1) / 2 : n / 2; f[n] = (n % 2 != 0) ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) : (2 * fib(k - 1) + fib(k)) * fib(k); @@ -29,7 +30,7 @@ long long fib(long long n) { int main() { // Main Function - for (long long i = 1; i < 93; i++) { + for (uint64_t i = 1; i < 93; i++) { std::cout << i << " th fibonacci number is " << fib(i) << "\n"; } return 0; From b9bb6caa73083da8fc0d74d366dd9262da081c3d Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Mon, 25 May 2020 23:32:31 -0400 Subject: [PATCH 041/433] made functions static to files *BUG* in CPP lint github action --- .../Gaussian_elimination.cpp | 52 ++++++++----------- ...ection_method.CPP => bisection_method.cpp} | 2 +- .../false-position.cpp | 21 ++++---- .../newton_raphson_method.cpp | 5 +- .../secant_method.cpp | 2 +- .../successive_approximation.cpp | 5 +- 6 files changed, 40 insertions(+), 47 deletions(-) rename computer_oriented_statistical_methods/{Bisection_method.CPP => bisection_method.cpp} (96%) diff --git a/computer_oriented_statistical_methods/Gaussian_elimination.cpp b/computer_oriented_statistical_methods/Gaussian_elimination.cpp index 58e634505af..ecfbfacc9d0 100644 --- a/computer_oriented_statistical_methods/Gaussian_elimination.cpp +++ b/computer_oriented_statistical_methods/Gaussian_elimination.cpp @@ -1,29 +1,23 @@ #include -using namespace std; -int main() -{ +int main() { int mat_size, i, j, step; - cout << "Matrix size: "; - cin >> mat_size; + std::cout << "Matrix size: "; + std::cin >> mat_size; double mat[mat_size + 1][mat_size + 1], x[mat_size][mat_size + 1]; - cout << endl - << "Enter value of the matrix: " << endl; - for (i = 0; i < mat_size; i++) - { - for (j = 0; j <= mat_size; j++) - { - cin >> mat[i][j]; //Enter (mat_size*mat_size) value of the matrix. + std::cout << std::endl << "Enter value of the matrix: " << std::endl; + for (i = 0; i < mat_size; i++) { + for (j = 0; j <= mat_size; j++) { + std::cin >> + mat[i][j]; // Enter (mat_size*mat_size) value of the matrix. } } - for (step = 0; step < mat_size - 1; step++) - { - for (i = step; i < mat_size - 1; i++) - { + for (step = 0; step < mat_size - 1; step++) { + for (i = step; i < mat_size - 1; i++) { double a = (mat[i + 1][step] / mat[step][step]); for (j = step; j <= mat_size; j++) @@ -31,24 +25,20 @@ int main() } } - cout << endl - << "Matrix using Gaussian Elimination method: " << endl; - for (i = 0; i < mat_size; i++) - { - for (j = 0; j <= mat_size; j++) - { + std::cout << std::endl + << "Matrix using Gaussian Elimination method: " << std::endl; + for (i = 0; i < mat_size; i++) { + for (j = 0; j <= mat_size; j++) { x[i][j] = mat[i][j]; - cout << mat[i][j] << " "; + std::cout << mat[i][j] << " "; } - cout << endl; + std::cout << std::endl; } - cout << endl - << "Value of the Gaussian Elimination method: " << endl; - for (i = mat_size - 1; i >= 0; i--) - { + std::cout << std::endl + << "Value of the Gaussian Elimination method: " << std::endl; + for (i = mat_size - 1; i >= 0; i--) { double sum = 0; - for (j = mat_size - 1; j > i; j--) - { + for (j = mat_size - 1; j > i; j--) { x[i][j] = x[j][j] * x[i][j]; sum = x[i][j] + sum; } @@ -57,7 +47,7 @@ int main() else x[i][i] = (x[i][mat_size] - sum) / (x[i][i]); - cout << "x" << i << "= " << x[i][i] << endl; + std::cout << "x" << i << "= " << x[i][i] << std::endl; } return 0; } diff --git a/computer_oriented_statistical_methods/Bisection_method.CPP b/computer_oriented_statistical_methods/bisection_method.cpp similarity index 96% rename from computer_oriented_statistical_methods/Bisection_method.CPP rename to computer_oriented_statistical_methods/bisection_method.cpp index 266083de1c1..089828c9a3f 100644 --- a/computer_oriented_statistical_methods/Bisection_method.CPP +++ b/computer_oriented_statistical_methods/bisection_method.cpp @@ -1,7 +1,7 @@ #include #include -float eq(float i) { +static float eq(float i) { return (std::pow(i, 3) - (4 * i) - 9); // original equation } diff --git a/computer_oriented_statistical_methods/false-position.cpp b/computer_oriented_statistical_methods/false-position.cpp index 5e15e92cc4c..c5a31450868 100644 --- a/computer_oriented_statistical_methods/false-position.cpp +++ b/computer_oriented_statistical_methods/false-position.cpp @@ -1,9 +1,11 @@ -#include -#include +#include +#include #include -float eq(float i) { + +static float eq(float i) { return (pow(i, 3) - (4 * i) - 9); // origial equation } + int main() { float a, b, z, c, m, n; system("clear"); @@ -12,12 +14,13 @@ int main() { if (z >= 0) { b = i; a = --i; - goto START; - } + break; } - START: + } + std::cout << "\nFirst initial: " << a; std::cout << "\nSecond initial: " << b; + for (int i = 0; i < 100; i++) { float h, d; m = eq(a); @@ -26,10 +29,10 @@ int main() { a = c; z = eq(c); if (z > 0 && z < 0.09) { // stoping criteria - goto END; + break; } } - END: + std::cout << "\n\nRoot: " << c; - system("pause"); + return 0; } diff --git a/computer_oriented_statistical_methods/newton_raphson_method.cpp b/computer_oriented_statistical_methods/newton_raphson_method.cpp index a2a57768ede..47d2764908b 100644 --- a/computer_oriented_statistical_methods/newton_raphson_method.cpp +++ b/computer_oriented_statistical_methods/newton_raphson_method.cpp @@ -1,10 +1,11 @@ #include #include -float eq(float i) { +static float eq(float i) { return (std::pow(i, 3) - (4 * i) - 9); // original equation } -float eq_der(float i) { + +static float eq_der(float i) { return ((3 * std::pow(i, 2)) - 4); // derivative of equation } diff --git a/computer_oriented_statistical_methods/secant_method.cpp b/computer_oriented_statistical_methods/secant_method.cpp index bd805ed3682..c353ef850f4 100644 --- a/computer_oriented_statistical_methods/secant_method.cpp +++ b/computer_oriented_statistical_methods/secant_method.cpp @@ -1,7 +1,7 @@ #include #include -float eq(float i) { +static float eq(float i) { return (pow(i, 3) - (4 * i) - 9); // original equation } diff --git a/computer_oriented_statistical_methods/successive_approximation.cpp b/computer_oriented_statistical_methods/successive_approximation.cpp index 85c42c9fb98..efbcc3bbff3 100644 --- a/computer_oriented_statistical_methods/successive_approximation.cpp +++ b/computer_oriented_statistical_methods/successive_approximation.cpp @@ -1,9 +1,8 @@ - #include #include -float eq(float y) { return ((3 * y) - (cos(y)) - 2); } -float eqd(float y) { return ((0.5) * ((cos(y)) + 2)); } +static float eq(float y) { return ((3 * y) - (cos(y)) - 2); } +static float eqd(float y) { return ((0.5) * ((cos(y)) + 2)); } int main() { float y, x1, x2, x3, sum, s, a, f1, f2, gd; From 2e2f9c209ca0ea04e59117859f2f0f08f638fbf4 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 26 May 2020 03:32:54 +0000 Subject: [PATCH 042/433] updating DIRECTORY.md --- DIRECTORY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index f215744548d..26210d6d405 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -10,7 +10,7 @@ * [Sudoku Solve](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/sudoku_solve.cpp) ## Computer Oriented Statistical Methods - * [Bisection Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/Bisection_method.CPP) + * [Bisection Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/bisection_method.cpp) * [False-Position](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/false-position.cpp) * [Gaussian Elimination](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/Gaussian_elimination.cpp) * [Newton Raphson Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/newton_raphson_method.cpp) From 9c0025aa3d1c1a01ef78b0ceeab775a796d66abd Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Mon, 25 May 2020 23:42:37 -0400 Subject: [PATCH 043/433] added cmake to math, others and compu_stats --- CMakeLists.txt | 32 ++++++------------- .../CMakeLists.txt | 18 +++++++++++ math/CMakeLists.txt | 18 +++++++++++ others/CMakeLists.txt | 18 +++++++++++ 4 files changed, 64 insertions(+), 22 deletions(-) create mode 100644 computer_oriented_statistical_methods/CMakeLists.txt create mode 100644 math/CMakeLists.txt create mode 100644 others/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index f98109382ba..b9c7831c898 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,10 +1,13 @@ cmake_minimum_required(VERSION 3.3) -project(Algorithms_in_C - LANGUAGES C CXX +project(Algorithms_in_C++ + LANGUAGES CXX VERSION 1.0.0 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") + option(USE_OPENMP "flag to use OpenMP for multithreading" ON) cmake_policy(SET CMP0054 NEW) @@ -34,32 +37,17 @@ if(DOXYGEN_FOUND) ) endif() -function(function_timer) - set(CMAKE_BUILD_TYPE "Release") # This is local to function - add_subdirectory(function_timer EXCLUDE_FROM_ALL) -endfunction() - -function_timer() - -include_directories(function_timer/include) -# link_libraries(function_timer) -# include_directories(${CMAKE_BINARY_DIR}/include) -# link_directories(${CMAKE_BINARY_DIR}/lib/${CMAKE_BUILD_TYPE}) - -set(CMAKE_C_STANDARD 11) -set(CMAKE_C_STANDARD_REQUIRED ON) +set(CMAKE_CXX_STANDARD 11) +set(CMAKE_CXX_STANDARD_REQUIRED ON) if(MSVC) add_compile_definitions(_CRT_SECURE_NO_WARNINGS) add_compile_options(/Za) endif(MSVC) -add_subdirectory(conversions) -add_subdirectory(misc) -add_subdirectory(project_euler) -add_subdirectory(sorting) -add_subdirectory(searching) -add_subdirectory(numerical_methods) +add_subdirectory(math) +add_subdirectory(others) +add_subdirectory(computer_oriented_statistical_methods) if(USE_OPENMP) find_package(OpenMP) diff --git a/computer_oriented_statistical_methods/CMakeLists.txt b/computer_oriented_statistical_methods/CMakeLists.txt new file mode 100644 index 00000000000..acff1ed1c5c --- /dev/null +++ b/computer_oriented_statistical_methods/CMakeLists.txt @@ -0,0 +1,18 @@ +# If necessary, use the RELATIVE flag, otherwise each source file may be listed +# with full pathname. RELATIVE may makes it easier to extract an executable name +# automatically. +file( GLOB APP_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp ) +# file( GLOB APP_SOURCES ${CMAKE_SOURCE_DIR}/*.c ) +# AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR} APP_SOURCES) +foreach( testsourcefile ${APP_SOURCES} ) + # I used a simple string replace, to cut off .cpp. + string( REPLACE ".cpp" "" testname ${testsourcefile} ) + add_executable( ${testname} ${testsourcefile} ) + + set_target_properties(${testname} PROPERTIES LINKER_LANGUAGE CXX) + if(OpenMP_CXX_FOUND) + target_link_libraries(${testname} OpenMP::OpenMP_CXX) + endif() + install(TARGETS ${testname} DESTINATION "bin/stats") + +endforeach( testsourcefile ${APP_SOURCES} ) diff --git a/math/CMakeLists.txt b/math/CMakeLists.txt new file mode 100644 index 00000000000..2b70b2d3101 --- /dev/null +++ b/math/CMakeLists.txt @@ -0,0 +1,18 @@ +# If necessary, use the RELATIVE flag, otherwise each source file may be listed +# with full pathname. RELATIVE may makes it easier to extract an executable name +# automatically. +file( GLOB APP_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp ) +# file( GLOB APP_SOURCES ${CMAKE_SOURCE_DIR}/*.c ) +# AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR} APP_SOURCES) +foreach( testsourcefile ${APP_SOURCES} ) + # I used a simple string replace, to cut off .cpp. + string( REPLACE ".cpp" "" testname ${testsourcefile} ) + add_executable( ${testname} ${testsourcefile} ) + + set_target_properties(${testname} PROPERTIES LINKER_LANGUAGE CXX) + if(OpenMP_CXX_FOUND) + target_link_libraries(${testname} OpenMP::OpenMP_CXX) + endif() + install(TARGETS ${testname} DESTINATION "bin/math") + +endforeach( testsourcefile ${APP_SOURCES} ) diff --git a/others/CMakeLists.txt b/others/CMakeLists.txt new file mode 100644 index 00000000000..f049b5f2d31 --- /dev/null +++ b/others/CMakeLists.txt @@ -0,0 +1,18 @@ +# If necessary, use the RELATIVE flag, otherwise each source file may be listed +# with full pathname. RELATIVE may makes it easier to extract an executable name +# automatically. +file( GLOB APP_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp ) +# file( GLOB APP_SOURCES ${CMAKE_SOURCE_DIR}/*.c ) +# AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR} APP_SOURCES) +foreach( testsourcefile ${APP_SOURCES} ) + # I used a simple string replace, to cut off .cpp. + string( REPLACE ".cpp" "" testname ${testsourcefile} ) + add_executable( ${testname} ${testsourcefile} ) + + set_target_properties(${testname} PROPERTIES LINKER_LANGUAGE CXX) + if(OpenMP_CXX_FOUND) + target_link_libraries(${testname} OpenMP::OpenMP_CXX) + endif() + install(TARGETS ${testname} DESTINATION "bin/others") + +endforeach( testsourcefile ${APP_SOURCES} ) From 565031ba73b6668a244ccdba78f56e197ae5eada Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 00:09:07 -0400 Subject: [PATCH 044/433] added documentation --- .../ordinary_least_squares_regressor.cpp | 525 ++++++++++-------- 1 file changed, 287 insertions(+), 238 deletions(-) diff --git a/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp b/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp index f50ccf1b1d7..41acfa10a9c 100644 --- a/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp +++ b/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp @@ -1,349 +1,398 @@ /** + * @file + * * Program that gets the number of data samples and number of features per * sample along with output per sample. It applies OLS regression to compute * the regression output for additional test data samples. - **/ + */ #include #include #include +/** + * operator to print a matrix + */ template std::ostream &operator<<(std::ostream &out, std::vector> const &v) { - const int width = 10; - const char separator = ' '; - - for (size_t row = 0; row < v.size(); row++) { - for (size_t col = 0; col < v[row].size(); col++) - out << std::left << std::setw(width) << std::setfill(separator) - << v[row][col]; - out << std::endl; - } + const int width = 10; + const char separator = ' '; + + for (size_t row = 0; row < v.size(); row++) { + for (size_t col = 0; col < v[row].size(); col++) + out << std::left << std::setw(width) << std::setfill(separator) + << v[row][col]; + out << std::endl; + } - return out; + return out; } +/** + * operator to print a vector + */ template std::ostream &operator<<(std::ostream &out, std::vector const &v) { - const int width = 15; - const char separator = ' '; + const int width = 15; + const char separator = ' '; - for (size_t row = 0; row < v.size(); row++) - out << std::left << std::setw(width) << std::setfill(separator) << v[row]; + for (size_t row = 0; row < v.size(); row++) + out << std::left << std::setw(width) << std::setfill(separator) + << v[row]; - return out; + return out; } +/** + * function to check if given matrix is a square matrix + * \returns 1 if true, 0 if false + */ template inline bool is_square(std::vector> const &A) { - // Assuming A is square matrix - size_t N = A.size(); - for (size_t i = 0; i < N; i++) - if (A[i].size() != N) - return false; - return true; + // Assuming A is square matrix + size_t N = A.size(); + for (size_t i = 0; i < N; i++) + if (A[i].size() != N) return false; + return true; } /** - * matrix multiplication + * Matrix multiplication such that if A is size (mxn) and + * B is of size (pxq) then the multiplication is defined + * only when n = p and the resultant matrix is of size (mxq) + * + * \returns resultant matrix **/ template std::vector> operator*(std::vector> const &A, std::vector> const &B) { - // Number of rows in A - size_t N_A = A.size(); - // Number of columns in B - size_t N_B = B[0].size(); + // Number of rows in A + size_t N_A = A.size(); + // Number of columns in B + size_t N_B = B[0].size(); - std::vector> result(N_A); + std::vector> result(N_A); - if (A[0].size() != B.size()) { - std::cerr << "Number of columns in A != Number of rows in B (" - << A[0].size() << ", " << B.size() << ")" << std::endl; - return result; - } - - for (size_t row = 0; row < N_A; row++) { - std::vector v(N_B); - for (size_t col = 0; col < N_B; col++) { - v[col] = static_cast(0); - for (size_t j = 0; j < B.size(); j++) - v[col] += A[row][j] * B[j][col]; + if (A[0].size() != B.size()) { + std::cerr << "Number of columns in A != Number of rows in B (" + << A[0].size() << ", " << B.size() << ")" << std::endl; + return result; + } + + for (size_t row = 0; row < N_A; row++) { + std::vector v(N_B); + for (size_t col = 0; col < N_B; col++) { + v[col] = static_cast(0); + for (size_t j = 0; j < B.size(); j++) + v[col] += A[row][j] * B[j][col]; + } + result[row] = v; } - result[row] = v; - } - return result; + return result; } +/** + * multiplication of a matrix with a column vector + * \returns resultant vector + */ template std::vector operator*(std::vector> const &A, std::vector const &B) { - // Number of rows in A - size_t N_A = A.size(); + // Number of rows in A + size_t N_A = A.size(); - std::vector result(N_A); + std::vector result(N_A); - if (A[0].size() != B.size()) { - std::cerr << "Number of columns in A != Number of rows in B (" - << A[0].size() << ", " << B.size() << ")" << std::endl; - return result; - } + if (A[0].size() != B.size()) { + std::cerr << "Number of columns in A != Number of rows in B (" + << A[0].size() << ", " << B.size() << ")" << std::endl; + return result; + } - for (size_t row = 0; row < N_A; row++) { - result[row] = static_cast(0); - for (size_t j = 0; j < B.size(); j++) - result[row] += A[row][j] * B[j]; - } + for (size_t row = 0; row < N_A; row++) { + result[row] = static_cast(0); + for (size_t j = 0; j < B.size(); j++) result[row] += A[row][j] * B[j]; + } - return result; + return result; } +/** + * pre-multiplication of a vector by a scalar + * \returns resultant vector + */ template std::vector operator*(float const scalar, std::vector const &A) { - // Number of rows in A - size_t N_A = A.size(); + // Number of rows in A + size_t N_A = A.size(); - std::vector result(N_A); + std::vector result(N_A); - for (size_t row = 0; row < N_A; row++) { - result[row] += A[row] * static_cast(scalar); - } + for (size_t row = 0; row < N_A; row++) { + result[row] += A[row] * static_cast(scalar); + } - return result; + return result; } +/** + * post-multiplication of a vector by a scalar + * \returns resultant vector + */ template std::vector operator*(std::vector const &A, float const scalar) { - // Number of rows in A - size_t N_A = A.size(); + // Number of rows in A + size_t N_A = A.size(); - std::vector result(N_A); + std::vector result(N_A); - for (size_t row = 0; row < N_A; row++) - result[row] = A[row] * static_cast(scalar); + for (size_t row = 0; row < N_A; row++) + result[row] = A[row] * static_cast(scalar); - return result; + return result; } +/** + * division of a vector by a scalar + * \returns resultant vector + */ template std::vector operator/(std::vector const &A, float const scalar) { - return (1.f / scalar) * A; + return (1.f / scalar) * A; } +/** + * subtraction of two vectors of identical lengths + * \returns resultant vector + */ template std::vector operator-(std::vector const &A, std::vector const &B) { - // Number of rows in A - size_t N = A.size(); + // Number of rows in A + size_t N = A.size(); - std::vector result(N); + std::vector result(N); - if (B.size() != N) { - std::cerr << "Vector dimensions shouldbe identical!" << std::endl; - return A; - } + if (B.size() != N) { + std::cerr << "Vector dimensions shouldbe identical!" << std::endl; + return A; + } - for (size_t row = 0; row < N; row++) - result[row] = A[row] - B[row]; + for (size_t row = 0; row < N; row++) result[row] = A[row] - B[row]; - return result; + return result; } +/** + * addition of two vectors of identical lengths + * \returns resultant vector + */ template std::vector operator+(std::vector const &A, std::vector const &B) { - // Number of rows in A - size_t N = A.size(); + // Number of rows in A + size_t N = A.size(); - std::vector result(N); + std::vector result(N); - if (B.size() != N) { - std::cerr << "Vector dimensions shouldbe identical!" << std::endl; - return A; - } + if (B.size() != N) { + std::cerr << "Vector dimensions shouldbe identical!" << std::endl; + return A; + } - for (size_t row = 0; row < N; row++) - result[row] = A[row] + B[row]; + for (size_t row = 0; row < N; row++) result[row] = A[row] + B[row]; - return result; + return result; } /** - * Get matrix inverse using Row-trasnformations + * Get matrix inverse using Row-trasnformations. Given matrix must + * be a square and non-singular. + * \returns inverse matrix **/ template -std::vector> -get_inverse(std::vector> const &A) { - // Assuming A is square matrix - size_t N = A.size(); - - std::vector> inverse(N); - for (size_t row = 0; row < N; row++) { - // preallocatae a resultant identity matrix - inverse[row] = std::vector(N); - for (size_t col = 0; col < N; col++) - inverse[row][col] = (row == col) ? 1.f : 0.f; - } - - if (!is_square(A)) { - std::cerr << "A must be a square matrix!" << std::endl; - return inverse; - } - - // preallocatae a temporary matrix identical to A - std::vector> temp(N); - for (size_t row = 0; row < N; row++) { - std::vector v(N); - for (size_t col = 0; col < N; col++) - v[col] = static_cast(A[row][col]); - temp[row] = v; - } - - // start transformations - for (size_t row = 0; row < N; row++) { - for (size_t row2 = row; row2 < N && temp[row][row] == 0; row2++) { - // this to ensure diagonal elements are not 0 - temp[row] = temp[row] + temp[row2]; - inverse[row] = inverse[row] + inverse[row2]; +std::vector> get_inverse( + std::vector> const &A) { + // Assuming A is square matrix + size_t N = A.size(); + + std::vector> inverse(N); + for (size_t row = 0; row < N; row++) { + // preallocatae a resultant identity matrix + inverse[row] = std::vector(N); + for (size_t col = 0; col < N; col++) + inverse[row][col] = (row == col) ? 1.f : 0.f; } - for (size_t col2 = row; col2 < N && temp[row][row] == 0; col2++) { - // this to further ensure diagonal elements are not 0 - for (size_t row2 = 0; row2 < N; row2++) { - temp[row2][row] = temp[row2][row] + temp[row2][col2]; - inverse[row2][row] = inverse[row2][row] + inverse[row2][col2]; - } + if (!is_square(A)) { + std::cerr << "A must be a square matrix!" << std::endl; + return inverse; } - if (temp[row][row] == 0) { - // Probably a low-rank matrix and hence singular - std::cerr << "Low-rank matrix, no inverse!" << std::endl; - return inverse; + // preallocatae a temporary matrix identical to A + std::vector> temp(N); + for (size_t row = 0; row < N; row++) { + std::vector v(N); + for (size_t col = 0; col < N; col++) + v[col] = static_cast(A[row][col]); + temp[row] = v; } - // set diagonal to 1 - float divisor = static_cast(temp[row][row]); - temp[row] = temp[row] / divisor; - inverse[row] = inverse[row] / divisor; - // Row transformations - for (size_t row2 = 0; row2 < N; row2++) { - if (row2 == row) - continue; - float factor = temp[row2][row]; - temp[row2] = temp[row2] - factor * temp[row]; - inverse[row2] = inverse[row2] - factor * inverse[row]; + // start transformations + for (size_t row = 0; row < N; row++) { + for (size_t row2 = row; row2 < N && temp[row][row] == 0; row2++) { + // this to ensure diagonal elements are not 0 + temp[row] = temp[row] + temp[row2]; + inverse[row] = inverse[row] + inverse[row2]; + } + + for (size_t col2 = row; col2 < N && temp[row][row] == 0; col2++) { + // this to further ensure diagonal elements are not 0 + for (size_t row2 = 0; row2 < N; row2++) { + temp[row2][row] = temp[row2][row] + temp[row2][col2]; + inverse[row2][row] = inverse[row2][row] + inverse[row2][col2]; + } + } + + if (temp[row][row] == 0) { + // Probably a low-rank matrix and hence singular + std::cerr << "Low-rank matrix, no inverse!" << std::endl; + return inverse; + } + + // set diagonal to 1 + float divisor = static_cast(temp[row][row]); + temp[row] = temp[row] / divisor; + inverse[row] = inverse[row] / divisor; + // Row transformations + for (size_t row2 = 0; row2 < N; row2++) { + if (row2 == row) continue; + float factor = temp[row2][row]; + temp[row2] = temp[row2] - factor * temp[row]; + inverse[row2] = inverse[row2] - factor * inverse[row]; + } } - } - return inverse; + return inverse; } /** * matrix transpose + * \returns resultant matrix **/ template -std::vector> -get_transpose(std::vector> const &A) { - std::vector> result(A[0].size()); - - for (size_t row = 0; row < A[0].size(); row++) { - std::vector v(A.size()); - for (size_t col = 0; col < A.size(); col++) - v[col] = A[col][row]; - - result[row] = v; - } - return result; +std::vector> get_transpose( + std::vector> const &A) { + std::vector> result(A[0].size()); + + for (size_t row = 0; row < A[0].size(); row++) { + std::vector v(A.size()); + for (size_t col = 0; col < A.size(); col++) v[col] = A[col][row]; + + result[row] = v; + } + return result; } +/** + * Perform Ordinary Least Squares curve fit. + * \param X feature matrix with rows representing sample vector of features + * \param Y known regression value for each sample + * \returns fitted regression model polynomial coefficients + */ template std::vector fit_OLS_regressor(std::vector> const &X, std::vector const &Y) { - // NxF - std::vector> X2 = X; - for (size_t i = 0; i < X2.size(); i++) - // add Y-intercept -> Nx(F+1) - X2[i].push_back(1); - // (F+1)xN - std::vector> Xt = get_transpose(X2); - // (F+1)x(F+1) - std::vector> tmp = get_inverse(Xt * X2); - // (F+1)xN - std::vector> out = tmp * Xt; - // cout << endl - // << "Projection matrix: " << X2 * out << endl; - - // Fx1,1 -> (F+1)^th element is the independent constant - return out * Y; + // NxF + std::vector> X2 = X; + for (size_t i = 0; i < X2.size(); i++) + // add Y-intercept -> Nx(F+1) + X2[i].push_back(1); + // (F+1)xN + std::vector> Xt = get_transpose(X2); + // (F+1)x(F+1) + std::vector> tmp = get_inverse(Xt * X2); + // (F+1)xN + std::vector> out = tmp * Xt; + // cout << endl + // << "Projection matrix: " << X2 * out << endl; + + // Fx1,1 -> (F+1)^th element is the independent constant + return out * Y; } /** * Given data and OLS model coeffficients, predict - * regression estimates + * regression estimates. + * \param X feature matrix with rows representing sample vector of features + * \param \f$\beta\f$ fitted regression model + * \return vector with regression values for each sample **/ template std::vector predict_OLS_regressor(std::vector> const &X, - std::vector const &beta) { - std::vector result(X.size()); - - for (size_t rows = 0; rows < X.size(); rows++) { - // -> start with constant term - result[rows] = beta[X[0].size()]; - for (size_t cols = 0; cols < X[0].size(); cols++) - result[rows] += beta[cols] * X[rows][cols]; - } - // Nx1 - return result; + std::vector const &beta /**< */ +) { + std::vector result(X.size()); + + for (size_t rows = 0; rows < X.size(); rows++) { + // -> start with constant term + result[rows] = beta[X[0].size()]; + for (size_t cols = 0; cols < X[0].size(); cols++) + result[rows] += beta[cols] * X[rows][cols]; + } + // Nx1 + return result; } +/** + * main function + */ int main() { - size_t N, F; - - std::cout << "Enter number of features: "; - // number of features = columns - std::cin >> F; - std::cout << "Enter number of samples: "; - // number of samples = rows - std::cin >> N; - - std::vector> data(N); - std::vector Y(N); - - std::cout - << "Enter training data. Per sample, provide features ad one output." - << std::endl; - - for (size_t rows = 0; rows < N; rows++) { - std::vector v(F); - std::cout << "Sample# " << rows + 1 << ": "; - for (size_t cols = 0; cols < F; cols++) - // get the F features - std::cin >> v[cols]; - data[rows] = v; - // get the corresponding output - std::cin >> Y[rows]; - } - - std::vector beta = fit_OLS_regressor(data, Y); - std::cout << std::endl << std::endl << "beta:" << beta << std::endl; - - size_t T; - std::cout << "Enter number of test samples: "; - // number of test sample inputs - std::cin >> T; - std::vector> data2(T); - // vector Y2(T); - - for (size_t rows = 0; rows < T; rows++) { - std::cout << "Sample# " << rows + 1 << ": "; - std::vector v(F); - for (size_t cols = 0; cols < F; cols++) - std::cin >> v[cols]; - data2[rows] = v; - } - - std::vector out = predict_OLS_regressor(data2, beta); - for (size_t rows = 0; rows < T; rows++) - std::cout << out[rows] << std::endl; - - return 0; + size_t N, F; + + std::cout << "Enter number of features: "; + // number of features = columns + std::cin >> F; + std::cout << "Enter number of samples: "; + // number of samples = rows + std::cin >> N; + + std::vector> data(N); + std::vector Y(N); + + std::cout + << "Enter training data. Per sample, provide features ad one output." + << std::endl; + + for (size_t rows = 0; rows < N; rows++) { + std::vector v(F); + std::cout << "Sample# " << rows + 1 << ": "; + for (size_t cols = 0; cols < F; cols++) + // get the F features + std::cin >> v[cols]; + data[rows] = v; + // get the corresponding output + std::cin >> Y[rows]; + } + + std::vector beta = fit_OLS_regressor(data, Y); + std::cout << std::endl << std::endl << "beta:" << beta << std::endl; + + size_t T; + std::cout << "Enter number of test samples: "; + // number of test sample inputs + std::cin >> T; + std::vector> data2(T); + // vector Y2(T); + + for (size_t rows = 0; rows < T; rows++) { + std::cout << "Sample# " << rows + 1 << ": "; + std::vector v(F); + for (size_t cols = 0; cols < F; cols++) std::cin >> v[cols]; + data2[rows] = v; + } + + std::vector out = predict_OLS_regressor(data2, beta); + for (size_t rows = 0; rows < T; rows++) std::cout << out[rows] << std::endl; + + return 0; } From 880fc707fc29169c445e27ff5c66a6fcba71f428 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 00:09:17 -0400 Subject: [PATCH 045/433] cpp code docs optimize --- CMakeLists.txt | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index b9c7831c898..bf1f1d3c729 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -21,7 +21,10 @@ if(DOXYGEN_FOUND) set(DOXYGEN_CREATE_SUBDIRS YES) set(DOCYGEN_GENERATE_TREEVIEW YES) set(DOXYGEN_STRIP_CODE_COMMENTS NO) - set(DOXYGEN_OPTIMIZE_OUTPUT_FOR_C YES) + set(DOXYGEN_BUILTIN_STL_SUPPORT YES) + if(MSVC) + set(DOXYGEN_CPP_CLI_SUPPORT YES) + endif() set(DOXYGEN_MATHJAX_RELPATH "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/MathJax.js?config=TeX-MML-AM_CHTML") if(Doxygen_dot_FOUND) set(DOXYGEN_HAVE_DOT YES) From 79f53543b90449baa0bd5788a828e593a9caea02 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 00:21:06 -0400 Subject: [PATCH 046/433] added doxygen CI github action --- .github/workflows/gh-pages.yml | 35 ++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 .github/workflows/gh-pages.yml diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml new file mode 100644 index 00000000000..aff5dcdcefe --- /dev/null +++ b/.github/workflows/gh-pages.yml @@ -0,0 +1,35 @@ +name: Doxygen CI + +on: + push: + branches: [master] + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@master + with: + submodules: true + - name: Install requirements + run: | + sudo apt -qq -y update + sudo apt -qq install doxygen graphviz ninja-build + - name: configure + run: cmake -G Ninja -B ./build -S . + - name: build + run: cmake --build build -t doc + - name: gh-pages + uses: actions/checkout@master + with: + ref: "gh-pages" + clean: false + - name: Move & Commit files + run: | + cp -rp ./build/html/* . && rm -rf ./build && ls -lah + git config --global user.name github-actions + git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' + git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY + git add * + git commit -m "Documentation for $GITHUB_SHA" || true + git push --force || true From 59a6db23cd530ab6ca04baf850febf2091390764 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 00:41:57 -0400 Subject: [PATCH 047/433] added CPP compile action --- .github/workflows/ccpp.yml | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 .github/workflows/ccpp.yml diff --git a/.github/workflows/ccpp.yml b/.github/workflows/ccpp.yml new file mode 100644 index 00000000000..7eff580532c --- /dev/null +++ b/.github/workflows/ccpp.yml @@ -0,0 +1,27 @@ +name: C/C++ CI + +on: [push] +# push: +# branches: [ master ] +# pull_request: +# branches: [ master ] + +jobs: + build: + + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest, windows-latest, macOS-latest] + + steps: + - uses: actions/checkout@master + with: + submodules: true + - name: Install requirements + run: sudo apt -qq install ninja-buil + - name: configure + run: cmake -G Ninja -B ./build -S . + - name: build + run: cmake --build build + From 22b375c058cf2eec6c47990ae1b46e08d6cdd3ee Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 00:49:27 -0400 Subject: [PATCH 048/433] fix cpp_lint bug --- .github/workflows/cpplint_modified_files.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/cpplint_modified_files.yml b/.github/workflows/cpplint_modified_files.yml index 07a32ece97d..8de6a5e4115 100644 --- a/.github/workflows/cpplint_modified_files.yml +++ b/.github/workflows/cpplint_modified_files.yml @@ -11,7 +11,7 @@ jobs: cpplint_modified_files: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v1 # v2 is broken for git diff + - uses: actions/checkout@v1 # v2 is broken for git diff - uses: actions/setup-python@v1 - run: python -m pip install cpplint - run: git remote -v @@ -42,7 +42,8 @@ jobs: print("g++:") # compile_exts = tuple(".c .c++ .cc .cpp .cu .cxx".split()) # compile_files = [file for file in cpp_files if file.lower().endswith(compile_exts)] - subprocess.run(["g++"] + cpp_files, check=True, text=True) + for cpp_file in cpp_files: + subprocess.run(["g++", cpp_file], check=True, text=True) upper_files = [file for file in cpp_files if file != file.lower()] if upper_files: From dddcbee9ce2432b90f28ebf50aebe9500dcd854e Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 00:52:38 -0400 Subject: [PATCH 049/433] fixed more filenames --- .../{Gaussian_elimination.cpp => gaussian_elimination.cpp} | 0 others/{Buzz_number.cpp => buzz_number.cpp} | 0 others/{GCD_of_n_numbers.cpp => gcd_of_n_numbers.cpp} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename computer_oriented_statistical_methods/{Gaussian_elimination.cpp => gaussian_elimination.cpp} (100%) rename others/{Buzz_number.cpp => buzz_number.cpp} (100%) rename others/{GCD_of_n_numbers.cpp => gcd_of_n_numbers.cpp} (100%) diff --git a/computer_oriented_statistical_methods/Gaussian_elimination.cpp b/computer_oriented_statistical_methods/gaussian_elimination.cpp similarity index 100% rename from computer_oriented_statistical_methods/Gaussian_elimination.cpp rename to computer_oriented_statistical_methods/gaussian_elimination.cpp diff --git a/others/Buzz_number.cpp b/others/buzz_number.cpp similarity index 100% rename from others/Buzz_number.cpp rename to others/buzz_number.cpp diff --git a/others/GCD_of_n_numbers.cpp b/others/gcd_of_n_numbers.cpp similarity index 100% rename from others/GCD_of_n_numbers.cpp rename to others/gcd_of_n_numbers.cpp From 9d64ff014e817d0f7f6442ab0b226b3c8f6464a8 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 26 May 2020 04:52:59 +0000 Subject: [PATCH 050/433] updating DIRECTORY.md --- DIRECTORY.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index 26210d6d405..b7f6ebdd557 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -12,7 +12,7 @@ ## Computer Oriented Statistical Methods * [Bisection Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/bisection_method.cpp) * [False-Position](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/false-position.cpp) - * [Gaussian Elimination](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/Gaussian_elimination.cpp) + * [Gaussian Elimination](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/gaussian_elimination.cpp) * [Newton Raphson Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/newton_raphson_method.cpp) * [Ordinary Least Squares Regressor](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp) * [Secant Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/secant_method.cpp) @@ -132,13 +132,13 @@ * [Union Of 2 Arrays](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Union_of_2_arrays.cpp) ## Others - * [Buzz Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Buzz_number.cpp) + * [Buzz Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/buzz_number.cpp) * [Decimal To Binary](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/decimal_to_binary.cpp) * [Decimal To Hexadecimal](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/decimal_to_hexadecimal.cpp) * [Decimal To Roman Numeral](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/decimal_to_roman_numeral.cpp) * [Fast Interger Input](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/fast_interger_input.cpp) * [Fibonacci Fast](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/fibonacci_fast.cpp) - * [Gcd Of N Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/GCD_of_n_numbers.cpp) + * [Gcd Of N Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/gcd_of_n_numbers.cpp) * [Happy Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/happy_number.cpp) * [Matrix Exponentiation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/matrix_exponentiation.cpp) * [Measure Time Elapsed](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/measure_time_elapsed.cpp) From ecffb77f86164cc0ec4d2614df7239abd65f21e9 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 00:54:03 -0400 Subject: [PATCH 051/433] remove dash from filename --- .../{false-position.cpp => false_position.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename computer_oriented_statistical_methods/{false-position.cpp => false_position.cpp} (100%) diff --git a/computer_oriented_statistical_methods/false-position.cpp b/computer_oriented_statistical_methods/false_position.cpp similarity index 100% rename from computer_oriented_statistical_methods/false-position.cpp rename to computer_oriented_statistical_methods/false_position.cpp From f28099d3f86dd18fc1f9e02aa13b837a9dab13a7 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 26 May 2020 04:54:27 +0000 Subject: [PATCH 052/433] updating DIRECTORY.md --- DIRECTORY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index b7f6ebdd557..9e163d41435 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -11,7 +11,7 @@ ## Computer Oriented Statistical Methods * [Bisection Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/bisection_method.cpp) - * [False-Position](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/false-position.cpp) + * [False Position](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/false_position.cpp) * [Gaussian Elimination](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/gaussian_elimination.cpp) * [Newton Raphson Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/newton_raphson_method.cpp) * [Ordinary Least Squares Regressor](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp) From 7bb69e4183dda6dff56719b0f63c168670d5cbd0 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 01:17:12 -0400 Subject: [PATCH 053/433] added documentation equations --- .../ordinary_least_squares_regressor.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp b/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp index 41acfa10a9c..06bd4ea5291 100644 --- a/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp +++ b/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp @@ -294,7 +294,8 @@ std::vector> get_transpose( } /** - * Perform Ordinary Least Squares curve fit. + * Perform Ordinary Least Squares curve fit. This operation is defined as + * \f[\beta = \left(X^TXX^T\right)Y\f] * \param X feature matrix with rows representing sample vector of features * \param Y known regression value for each sample * \returns fitted regression model polynomial coefficients @@ -322,9 +323,11 @@ std::vector fit_OLS_regressor(std::vector> const &X, /** * Given data and OLS model coeffficients, predict - * regression estimates. + * regression estimates. This operation is defined as + * \f[y_{\text{row}=i} = \sum_{j=\text{columns}}\beta_j\cdot X_{i,j}\f] + * * \param X feature matrix with rows representing sample vector of features - * \param \f$\beta\f$ fitted regression model + * \param beta fitted regression model * \return vector with regression values for each sample **/ template From c4e49b95578d632f2a9524ae36ef2518f92ca0d1 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 01:17:30 -0400 Subject: [PATCH 054/433] project description correction --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index bf1f1d3c729..ff568fc9dfe 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.3) project(Algorithms_in_C++ LANGUAGES CXX VERSION 1.0.0 - DESCRIPTION "Set of algorithms implemented in C." + DESCRIPTION "Set of algorithms implemented in C++." ) # set(CMAKE_CXX_CPPLINT "~/anaconda3/bin/cpplint --filter=-legal/copyright --std=c++11") From 06fe0efc9429ab72787faa5d6317aff9593b414b Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 01:18:59 -0400 Subject: [PATCH 055/433] yml file indentation correction --- .github/workflows/ccpp.yml | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/.github/workflows/ccpp.yml b/.github/workflows/ccpp.yml index 7eff580532c..392c8bd8f5a 100644 --- a/.github/workflows/ccpp.yml +++ b/.github/workflows/ccpp.yml @@ -8,20 +8,18 @@ on: [push] jobs: build: - runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-latest, windows-latest, macOS-latest] steps: - - uses: actions/checkout@master - with: - submodules: true - - name: Install requirements - run: sudo apt -qq install ninja-buil - - name: configure - run: cmake -G Ninja -B ./build -S . - - name: build - run: cmake --build build - + - uses: actions/checkout@master + with: + submodules: true + - name: Install requirements + run: sudo apt -qq install ninja-build + - name: configure + run: cmake -G Ninja -B ./build -S . + - name: build + run: cmake --build build From 249b91d5ff4af928711f7d9b411f4e3e2fd961d9 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 01:21:32 -0400 Subject: [PATCH 056/433] remove install ninja --- .github/workflows/ccpp.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/ccpp.yml b/.github/workflows/ccpp.yml index 392c8bd8f5a..30b8edf19a5 100644 --- a/.github/workflows/ccpp.yml +++ b/.github/workflows/ccpp.yml @@ -17,8 +17,6 @@ jobs: - uses: actions/checkout@master with: submodules: true - - name: Install requirements - run: sudo apt -qq install ninja-build - name: configure run: cmake -G Ninja -B ./build -S . - name: build From 65d4fe035a2c101b6471e3cf8f6080cca243ed41 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 01:22:46 -0400 Subject: [PATCH 057/433] remove ninja as cmake generator --- .github/workflows/ccpp.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ccpp.yml b/.github/workflows/ccpp.yml index 30b8edf19a5..34085cdecb0 100644 --- a/.github/workflows/ccpp.yml +++ b/.github/workflows/ccpp.yml @@ -18,6 +18,6 @@ jobs: with: submodules: true - name: configure - run: cmake -G Ninja -B ./build -S . + run: cmake -B ./build -S . - name: build run: cmake --build build From 0163e6a34d898c7a8be1791b53252b5c3d1d3dee Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Tue, 26 May 2020 01:29:51 -0400 Subject: [PATCH 058/433] added CI badges --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index a3077cdc5b8..04feb9c5209 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,9 @@ [![contributions welcome](https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square)](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTION.md)  ![GitHub repo size](https://img.shields.io/github/repo-size/TheAlgorithms/C-Plus-Plus?color=red&style=flat-square) ![GitHub closed pull requests](https://img.shields.io/github/issues-pr-closed/TheAlgorithms/C-Plus-Plus?color=green&style=flat-square) +![Doxygen CI](https://github.com/kvedala/C-Plus-Plus/workflows/Doxygen%20CI/badge.svg) +![cpplint](https://github.com/kvedala/C-Plus-Plus/workflows/cpplint_modified_files/badge.svg) +![C/C++ CI](https://github.com/kvedala/C-Plus-Plus/workflows/C/C++%20CI/badge.svg) ### All algorithms implemented in C++ (for education) The implementations are for learning purpose. They may be less efficient than the implementation in the standard library. From 10da051ba6673e09af3328bbee96e7f1d202f540 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Tue, 26 May 2020 01:31:58 -0400 Subject: [PATCH 059/433] added documentation URL --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 04feb9c5209..e8034d7c4d9 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,8 @@ ![cpplint](https://github.com/kvedala/C-Plus-Plus/workflows/cpplint_modified_files/badge.svg) ![C/C++ CI](https://github.com/kvedala/C-Plus-Plus/workflows/C/C++%20CI/badge.svg) +[Documentation](https://kvedala.github.io/C-Plus-Plus) + ### All algorithms implemented in C++ (for education) The implementations are for learning purpose. They may be less efficient than the implementation in the standard library. From 614ea8eb5841199d86c40414935e68e10bc3b918 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 08:48:09 -0400 Subject: [PATCH 060/433] newline character at EOF of gitignore --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 12318c6cd0f..5275088d0f4 100644 --- a/.gitignore +++ b/.gitignore @@ -34,4 +34,4 @@ a.out *.out *.app -build/ \ No newline at end of file +build/ From 0ad756f8609efdb5fd3d27508fa692c738fc1fc7 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 09:05:29 -0400 Subject: [PATCH 061/433] `rand_r` is non-portable and obsolete --- math/fast_power.cpp | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/math/fast_power.cpp b/math/fast_power.cpp index 4f6e0208197..5dd724085c5 100644 --- a/math/fast_power.cpp +++ b/math/fast_power.cpp @@ -50,30 +50,28 @@ double fast_power_linear(int64_t a, int64_t b) { } int main() { - std::srand(time(NULL)); + std::srand(std::time(nullptr)); std::ios_base::sync_with_stdio(false); std::cout << "Testing..." << std::endl; for (int i = 0; i < 20; i++) { - unsigned int *rand1, *rand2; - int a = rand_r(rand1) % 20 - 10; - int b = rand_r(rand2) % 20 - 10; + int a = std::rand() % 20 - 10; + int b = std::rand() % 20 - 10; std::cout << std::endl << "Calculating " << a << "^" << b << std::endl; assert(fast_power_recursive(a, b) == std::pow(a, b)); assert(fast_power_linear(a, b) == std::pow(a, b)); - std::cout << "------ " << a << "^" << b << " = "<< - fast_power_recursive(a, b) << std::endl; + std::cout << "------ " << a << "^" << b << " = " + << fast_power_recursive(a, b) << std::endl; } int64_t a, b; std::cin >> a >> b; - std::cout << a << "^" << b << " = "<< - fast_power_recursive(a, b) << std::endl; + std::cout << a << "^" << b << " = " << fast_power_recursive(a, b) + << std::endl; - std::cout << a << "^" << b << " = "<< - fast_power_linear(a, b) << std::endl; + std::cout << a << "^" << b << " = " << fast_power_linear(a, b) << std::endl; return 0; } From 139964d32563b3c92e0651bf46350e107391c5a5 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 09:05:44 -0400 Subject: [PATCH 062/433] improved documentation --- math/fast_power.cpp | 40 +++++++++++++++++++++++----------------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/math/fast_power.cpp b/math/fast_power.cpp index 5dd724085c5..0ffbcd40d78 100644 --- a/math/fast_power.cpp +++ b/math/fast_power.cpp @@ -1,22 +1,29 @@ -#include -#include -#include -#include -#include -#include - -/* - Program that computes a^b in O(logN) time. +/** + * @file + Program that computes \f$a^b\f$ in \f$O(logN)\f$ time. It is based on formula that: - case1) if b is even: a^b = a^(b/2) * a^(b/2) = (a^(b/2))ˆ2 - case2) if b is odd: a^b = a^((b-1)/2) * a^((b-1)/2) * a = (a^((b-1)/2))^2 * a - We can compute a^b recursively using above algorithm. + 1. if \f$b\f$ is even: \f$a^b = a^\frac{b}{2} \cdot a^\frac{b}{2} = + {a^\frac{b}{2}}^2\f$ + 2. if \f$b\f$ is odd: \f$a^b = a^\frac{b-1}{2} \cdot + a^\frac{b-1}{2} \cdot a = {a^\frac{b-1}{2}}^2 \cdot a\f$ + + We can compute \f$a^b\f$ + recursively using above algorithm. */ +#include +#include +#include +#include +#include +#include + +/** + * algorithm implementation for \f$a^b\f$ + */ double fast_power_recursive(int64_t a, int64_t b) { // negative power. a^b = 1 / (a^-b) - if (b < 0) - return 1.0 / fast_power_recursive(a, -b); + if (b < 0) return 1.0 / fast_power_recursive(a, -b); if (b == 0) return 1; int64_t bottom = fast_power_recursive(a, b >> 1); @@ -31,14 +38,13 @@ double fast_power_recursive(int64_t a, int64_t b) { return result; } -/* +/** Same algorithm with little different formula. It still calculates in O(logN) */ double fast_power_linear(int64_t a, int64_t b) { // negative power. a^b = 1 / (a^-b) - if (b < 0) - return 1.0 / fast_power_linear(a, -b); + if (b < 0) return 1.0 / fast_power_linear(a, -b); double result = 1; while (b) { From 2def9abcc2306ab569687f85f1802c4e5493d244 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 09:10:28 -0400 Subject: [PATCH 063/433] cin accepts only one variable at a time & fixed cpplint --- others/sparse_matrix.cpp | 65 ++++++++++++++++++++-------------------- 1 file changed, 32 insertions(+), 33 deletions(-) diff --git a/others/sparse_matrix.cpp b/others/sparse_matrix.cpp index 1861163f15f..de4759a3e14 100644 --- a/others/sparse_matrix.cpp +++ b/others/sparse_matrix.cpp @@ -1,41 +1,40 @@ -/*A sparse matrix is a matrix which has number of zeroes greater than (m*n)/2, -where m and n are the dimensions of the matrix.*/ +/** @file + * A sparse matrix is a matrix which has number of zeroes greater than + * \f$\frac{m*n}{2}\f$, where m and n are the dimensions of the matrix. + */ + #include -using namespace std; -int main() -{ - int m, n; - int counterZeros = 0; - cout << "Enter dimensions of matrix (seperated with space): "; - cin >> m >> n; - int a[m][n]; - cout << "Enter matrix elements:"; - cout << "\n"; +int main() { + int m, n; + int counterZeros = 0; + + std::cout << "Enter dimensions of matrix (seperated with space): "; + std::cin >> m; + std::cin >> n; + + int a[m][n]; + std::cout << "Enter matrix elements:"; + std::cout << "\n"; - // reads the matrix from stdin - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { - cout << "element? "; - cin >> a[i][j]; + // reads the matrix from stdin + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + std::cout << "element? "; + std::cin >> a[i][j]; + } } - } - // counts the zero's - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { - if (a[i][j] == 0) - counterZeros++; //Counting number of zeroes + // counts the zero's + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (a[i][j] == 0) counterZeros++; // Counting number of zeroes + } } - } - // makes sure the matrix is a sparse matrix - if (counterZeros > ((m * n) / 2)) //Checking for sparse matrix - cout << "Sparse matrix"; - else - cout << "Not a sparse matrix"; + // makes sure the matrix is a sparse matrix + if (counterZeros > ((m * n) / 2)) // Checking for sparse matrix + std::cout << "Sparse matrix"; + else + std::cout << "Not a sparse matrix"; } From d6d328c8c9a760b86e61b6e3e491a6a4416926db Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 09:25:42 -0400 Subject: [PATCH 064/433] file rename --- others/{Palindromeofnumber.cpp => palindrome_of_number.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename others/{Palindromeofnumber.cpp => palindrome_of_number.cpp} (100%) diff --git a/others/Palindromeofnumber.cpp b/others/palindrome_of_number.cpp similarity index 100% rename from others/Palindromeofnumber.cpp rename to others/palindrome_of_number.cpp From fb3a8091f9492ccac9b66572612e39e394eed4ad Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 09:26:40 -0400 Subject: [PATCH 065/433] fixed lint --- others/palindrome_of_number.cpp | 29 +++++++++++++---------------- 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/others/palindrome_of_number.cpp b/others/palindrome_of_number.cpp index 64780399703..dda8728826c 100644 --- a/others/palindrome_of_number.cpp +++ b/others/palindrome_of_number.cpp @@ -1,23 +1,20 @@ -#include #include +#include -using namespace std; - -int main() -{ - int num; - cout << "Enter number = "; - cin >> num; +int main() { + int num; + std::cout << "Enter number = "; + std::cin >> num; - string s1 = to_string(num); - string s2 = s1; + std::string s1 = std::to_string(num); + std::string s2 = s1; - reverse(s1.begin(), s1.end()); + reverse(s1.begin(), s1.end()); - if (s1 == s2) - cout << "true"; - else - cout << "false"; + if (s1 == s2) + std::cout << "true"; + else + std::cout << "false"; - return 0; + return 0; } From 4b25222d430a3be8b2072cd671df7513412c8a5c Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 09:32:37 -0400 Subject: [PATCH 066/433] fixed windows build error --- .../gaussian_elimination.cpp | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/computer_oriented_statistical_methods/gaussian_elimination.cpp b/computer_oriented_statistical_methods/gaussian_elimination.cpp index ecfbfacc9d0..0b8bb693de6 100644 --- a/computer_oriented_statistical_methods/gaussian_elimination.cpp +++ b/computer_oriented_statistical_methods/gaussian_elimination.cpp @@ -6,7 +6,11 @@ int main() { std::cout << "Matrix size: "; std::cin >> mat_size; - double mat[mat_size + 1][mat_size + 1], x[mat_size][mat_size + 1]; + double **mat = new double *[mat_size + 1], **x = new double *[mat_size]; + for (i = 0; i <= mat_size; i++) { + mat[i] = new double[mat_size + 1]; + if (i < mat_size) x[i] = new double[mat_size + 1]; + } std::cout << std::endl << "Enter value of the matrix: " << std::endl; for (i = 0; i < mat_size; i++) { @@ -49,5 +53,13 @@ int main() { std::cout << "x" << i << "= " << x[i][i] << std::endl; } + + for (i = 0; i <= mat_size; i++) { + delete[] mat[i]; + if (i < mat_size) delete[] x[i]; + } + delete[] mat; + delete[] x; + return 0; } From a3a57aea2d1aee64f7e9ce5e0b7f3eac686642ce Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 26 May 2020 13:33:02 +0000 Subject: [PATCH 067/433] updating DIRECTORY.md --- DIRECTORY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index 9e163d41435..7b0fb2b6b29 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -142,7 +142,7 @@ * [Happy Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/happy_number.cpp) * [Matrix Exponentiation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/matrix_exponentiation.cpp) * [Measure Time Elapsed](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/measure_time_elapsed.cpp) - * [Palindromeofnumber](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Palindromeofnumber.cpp) + * [Palindrome Of Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/palindrome_of_number.cpp) * [Paranthesis Matching](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/paranthesis_matching.cpp) * [Pascal Triangle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/pascal_triangle.cpp) * [Primality Test](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/primality_test.cpp) From 899be6a1f17e4f1bd1e7fee6375432767757cc0b Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 09:35:25 -0400 Subject: [PATCH 068/433] removed in-favor of chronos library of c++11 --- others/measure_time_elapsed.cpp | 19 ------------------- 1 file changed, 19 deletions(-) delete mode 100644 others/measure_time_elapsed.cpp diff --git a/others/measure_time_elapsed.cpp b/others/measure_time_elapsed.cpp deleted file mode 100644 index d0830ab79fe..00000000000 --- a/others/measure_time_elapsed.cpp +++ /dev/null @@ -1,19 +0,0 @@ -// To calculate the time taken by a code to execute -#include -#include - -__int64_t getTimeInMicroseconds() { - struct timeval start; - gettimeofday(&start, NULL); - return start.tv_sec * 1000000 + start.tv_usec; -} - -// write function sample(args) - -int main() { - // write code - __int64_t starttime = getTimeInMicroseconds(); - // sample(args) function run - // Any other functions (if present) run - std::cout << getTimeInMicroseconds() - starttime; -} From dd20bf94427392ea0baa428ecf2587d6a8a7a131 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 09:37:36 -0400 Subject: [PATCH 069/433] fixed dynamic array --- others/sparse_matrix.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/others/sparse_matrix.cpp b/others/sparse_matrix.cpp index de4759a3e14..d9878fda425 100644 --- a/others/sparse_matrix.cpp +++ b/others/sparse_matrix.cpp @@ -13,7 +13,9 @@ int main() { std::cin >> m; std::cin >> n; - int a[m][n]; + int **a = new int *[m]; + for (int i = 0; i < m; i++) a[i] = new int[n]; + std::cout << "Enter matrix elements:"; std::cout << "\n"; @@ -37,4 +39,8 @@ int main() { std::cout << "Sparse matrix"; else std::cout << "Not a sparse matrix"; + + for (int i = 0; i < m; i++) delete[] a[i]; + delete[] a; + return 0; } From 3d5a6fbce3f7ad219c2946e6faeb03335e66367d Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 26 May 2020 13:40:20 +0000 Subject: [PATCH 070/433] updating DIRECTORY.md --- DIRECTORY.md | 1 - 1 file changed, 1 deletion(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index 7b0fb2b6b29..47842b9cad8 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -141,7 +141,6 @@ * [Gcd Of N Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/gcd_of_n_numbers.cpp) * [Happy Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/happy_number.cpp) * [Matrix Exponentiation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/matrix_exponentiation.cpp) - * [Measure Time Elapsed](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/measure_time_elapsed.cpp) * [Palindrome Of Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/palindrome_of_number.cpp) * [Paranthesis Matching](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/paranthesis_matching.cpp) * [Pascal Triangle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/pascal_triangle.cpp) From 2217049119a2ecfcd7f2aad8feae03594be0787c Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 09:40:57 -0400 Subject: [PATCH 071/433] add cstring for std::to_string() --- others/palindrome_of_number.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/others/palindrome_of_number.cpp b/others/palindrome_of_number.cpp index dda8728826c..93c54a96515 100644 --- a/others/palindrome_of_number.cpp +++ b/others/palindrome_of_number.cpp @@ -1,4 +1,5 @@ #include +#include #include int main() { From fdee12d82af42f86a3df5964a6be4182084bbe26 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 09:50:41 -0400 Subject: [PATCH 072/433] remove redundant /Za for VC --- CMakeLists.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index ff568fc9dfe..14079562a10 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -45,7 +45,6 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON) if(MSVC) add_compile_definitions(_CRT_SECURE_NO_WARNINGS) - add_compile_options(/Za) endif(MSVC) add_subdirectory(math) From 8bc1559b082454a397cd6f8f0104a7cc0c0b7737 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 10:00:09 -0400 Subject: [PATCH 073/433] for windows build, MSVC knows C++-14 and not 11 --- CMakeLists.txt | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 14079562a10..4394f84e143 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,6 +8,14 @@ project(Algorithms_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) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +if(MSVC) + set(CMAKE_CXX_STANDARD 14) + add_compile_definitions(_CRT_SECURE_NO_WARNINGS) +endif(MSVC) + option(USE_OPENMP "flag to use OpenMP for multithreading" ON) cmake_policy(SET CMP0054 NEW) @@ -40,20 +48,13 @@ if(DOXYGEN_FOUND) ) endif() -set(CMAKE_CXX_STANDARD 11) -set(CMAKE_CXX_STANDARD_REQUIRED ON) - -if(MSVC) - add_compile_definitions(_CRT_SECURE_NO_WARNINGS) -endif(MSVC) - add_subdirectory(math) add_subdirectory(others) add_subdirectory(computer_oriented_statistical_methods) if(USE_OPENMP) find_package(OpenMP) - if (OpenMP_C_FOUND) + if (OpenMP_CXX_FOUND) message(STATUS "Building with OpenMP Multithreading.") else() message(STATUS "No OpenMP found, no multithreading.") From fe9d2b9bc66ee9f2e5112ced6b6d5aab7d5e5f05 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 10:06:01 -0400 Subject: [PATCH 074/433] MSVC does not know cstring-use string-for toString --- others/palindrome_of_number.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/others/palindrome_of_number.cpp b/others/palindrome_of_number.cpp index 93c54a96515..621b09ab6ba 100644 --- a/others/palindrome_of_number.cpp +++ b/others/palindrome_of_number.cpp @@ -1,7 +1,13 @@ #include -#include #include +#ifdef _MSC_VER +// Required to compile std::toString function using MSVC +#include +#else +#include +#endif + int main() { int num; std::cout << "Enter number = "; From a6319c5f43d019a23a8eb3ffa48f6b8a30ff85a4 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 08:48:09 -0400 Subject: [PATCH 075/433] newline character at EOF of gitignore (cherry picked from commit 614ea8eb5841199d86c40414935e68e10bc3b918) --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 12318c6cd0f..5275088d0f4 100644 --- a/.gitignore +++ b/.gitignore @@ -34,4 +34,4 @@ a.out *.out *.app -build/ \ No newline at end of file +build/ From 36b4d59d5914f1c35f09f82cab65514a48166fa7 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 09:05:29 -0400 Subject: [PATCH 076/433] `rand_r` is non-portable and obsolete (cherry picked from commit 0ad756f8609efdb5fd3d27508fa692c738fc1fc7) --- math/fast_power.cpp | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/math/fast_power.cpp b/math/fast_power.cpp index 4f6e0208197..5dd724085c5 100644 --- a/math/fast_power.cpp +++ b/math/fast_power.cpp @@ -50,30 +50,28 @@ double fast_power_linear(int64_t a, int64_t b) { } int main() { - std::srand(time(NULL)); + std::srand(std::time(nullptr)); std::ios_base::sync_with_stdio(false); std::cout << "Testing..." << std::endl; for (int i = 0; i < 20; i++) { - unsigned int *rand1, *rand2; - int a = rand_r(rand1) % 20 - 10; - int b = rand_r(rand2) % 20 - 10; + int a = std::rand() % 20 - 10; + int b = std::rand() % 20 - 10; std::cout << std::endl << "Calculating " << a << "^" << b << std::endl; assert(fast_power_recursive(a, b) == std::pow(a, b)); assert(fast_power_linear(a, b) == std::pow(a, b)); - std::cout << "------ " << a << "^" << b << " = "<< - fast_power_recursive(a, b) << std::endl; + std::cout << "------ " << a << "^" << b << " = " + << fast_power_recursive(a, b) << std::endl; } int64_t a, b; std::cin >> a >> b; - std::cout << a << "^" << b << " = "<< - fast_power_recursive(a, b) << std::endl; + std::cout << a << "^" << b << " = " << fast_power_recursive(a, b) + << std::endl; - std::cout << a << "^" << b << " = "<< - fast_power_linear(a, b) << std::endl; + std::cout << a << "^" << b << " = " << fast_power_linear(a, b) << std::endl; return 0; } From 05ec7bed7282997e36dec1f7dd5273e85e46834c Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 09:05:44 -0400 Subject: [PATCH 077/433] improved documentation (cherry picked from commit 139964d32563b3c92e0651bf46350e107391c5a5) --- math/fast_power.cpp | 40 +++++++++++++++++++++++----------------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/math/fast_power.cpp b/math/fast_power.cpp index 5dd724085c5..0ffbcd40d78 100644 --- a/math/fast_power.cpp +++ b/math/fast_power.cpp @@ -1,22 +1,29 @@ -#include -#include -#include -#include -#include -#include - -/* - Program that computes a^b in O(logN) time. +/** + * @file + Program that computes \f$a^b\f$ in \f$O(logN)\f$ time. It is based on formula that: - case1) if b is even: a^b = a^(b/2) * a^(b/2) = (a^(b/2))ˆ2 - case2) if b is odd: a^b = a^((b-1)/2) * a^((b-1)/2) * a = (a^((b-1)/2))^2 * a - We can compute a^b recursively using above algorithm. + 1. if \f$b\f$ is even: \f$a^b = a^\frac{b}{2} \cdot a^\frac{b}{2} = + {a^\frac{b}{2}}^2\f$ + 2. if \f$b\f$ is odd: \f$a^b = a^\frac{b-1}{2} \cdot + a^\frac{b-1}{2} \cdot a = {a^\frac{b-1}{2}}^2 \cdot a\f$ + + We can compute \f$a^b\f$ + recursively using above algorithm. */ +#include +#include +#include +#include +#include +#include + +/** + * algorithm implementation for \f$a^b\f$ + */ double fast_power_recursive(int64_t a, int64_t b) { // negative power. a^b = 1 / (a^-b) - if (b < 0) - return 1.0 / fast_power_recursive(a, -b); + if (b < 0) return 1.0 / fast_power_recursive(a, -b); if (b == 0) return 1; int64_t bottom = fast_power_recursive(a, b >> 1); @@ -31,14 +38,13 @@ double fast_power_recursive(int64_t a, int64_t b) { return result; } -/* +/** Same algorithm with little different formula. It still calculates in O(logN) */ double fast_power_linear(int64_t a, int64_t b) { // negative power. a^b = 1 / (a^-b) - if (b < 0) - return 1.0 / fast_power_linear(a, -b); + if (b < 0) return 1.0 / fast_power_linear(a, -b); double result = 1; while (b) { From 5fddd6c7cd3d8deb2d8e135c3fe3d11586244957 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 09:10:28 -0400 Subject: [PATCH 078/433] cin accepts only one variable at a time & fixed cpplint (cherry picked from commit 2def9abcc2306ab569687f85f1802c4e5493d244) --- others/sparse_matrix.cpp | 65 ++++++++++++++++++++-------------------- 1 file changed, 32 insertions(+), 33 deletions(-) diff --git a/others/sparse_matrix.cpp b/others/sparse_matrix.cpp index 1861163f15f..de4759a3e14 100644 --- a/others/sparse_matrix.cpp +++ b/others/sparse_matrix.cpp @@ -1,41 +1,40 @@ -/*A sparse matrix is a matrix which has number of zeroes greater than (m*n)/2, -where m and n are the dimensions of the matrix.*/ +/** @file + * A sparse matrix is a matrix which has number of zeroes greater than + * \f$\frac{m*n}{2}\f$, where m and n are the dimensions of the matrix. + */ + #include -using namespace std; -int main() -{ - int m, n; - int counterZeros = 0; - cout << "Enter dimensions of matrix (seperated with space): "; - cin >> m >> n; - int a[m][n]; - cout << "Enter matrix elements:"; - cout << "\n"; +int main() { + int m, n; + int counterZeros = 0; + + std::cout << "Enter dimensions of matrix (seperated with space): "; + std::cin >> m; + std::cin >> n; + + int a[m][n]; + std::cout << "Enter matrix elements:"; + std::cout << "\n"; - // reads the matrix from stdin - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { - cout << "element? "; - cin >> a[i][j]; + // reads the matrix from stdin + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + std::cout << "element? "; + std::cin >> a[i][j]; + } } - } - // counts the zero's - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { - if (a[i][j] == 0) - counterZeros++; //Counting number of zeroes + // counts the zero's + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (a[i][j] == 0) counterZeros++; // Counting number of zeroes + } } - } - // makes sure the matrix is a sparse matrix - if (counterZeros > ((m * n) / 2)) //Checking for sparse matrix - cout << "Sparse matrix"; - else - cout << "Not a sparse matrix"; + // makes sure the matrix is a sparse matrix + if (counterZeros > ((m * n) / 2)) // Checking for sparse matrix + std::cout << "Sparse matrix"; + else + std::cout << "Not a sparse matrix"; } From 5f8b270992e4b6f344aa50b78a92236c8e48a48b Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 09:25:42 -0400 Subject: [PATCH 079/433] file rename (cherry picked from commit d6d328c8c9a760b86e61b6e3e491a6a4416926db) --- others/{Palindromeofnumber.cpp => palindrome_of_number.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename others/{Palindromeofnumber.cpp => palindrome_of_number.cpp} (100%) diff --git a/others/Palindromeofnumber.cpp b/others/palindrome_of_number.cpp similarity index 100% rename from others/Palindromeofnumber.cpp rename to others/palindrome_of_number.cpp From 59be834836c839db7fba0ab852193252e6fa3eeb Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 09:26:40 -0400 Subject: [PATCH 080/433] fixed lint (cherry picked from commit fb3a8091f9492ccac9b66572612e39e394eed4ad) --- others/palindrome_of_number.cpp | 29 +++++++++++++---------------- 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/others/palindrome_of_number.cpp b/others/palindrome_of_number.cpp index 64780399703..dda8728826c 100644 --- a/others/palindrome_of_number.cpp +++ b/others/palindrome_of_number.cpp @@ -1,23 +1,20 @@ -#include #include +#include -using namespace std; - -int main() -{ - int num; - cout << "Enter number = "; - cin >> num; +int main() { + int num; + std::cout << "Enter number = "; + std::cin >> num; - string s1 = to_string(num); - string s2 = s1; + std::string s1 = std::to_string(num); + std::string s2 = s1; - reverse(s1.begin(), s1.end()); + reverse(s1.begin(), s1.end()); - if (s1 == s2) - cout << "true"; - else - cout << "false"; + if (s1 == s2) + std::cout << "true"; + else + std::cout << "false"; - return 0; + return 0; } From 48473295275ad3b1911365f0216249d44e3afe8b Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 09:32:37 -0400 Subject: [PATCH 081/433] fixed windows build error (cherry picked from commit 4b25222d430a3be8b2072cd671df7513412c8a5c) --- .../gaussian_elimination.cpp | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/computer_oriented_statistical_methods/gaussian_elimination.cpp b/computer_oriented_statistical_methods/gaussian_elimination.cpp index ecfbfacc9d0..0b8bb693de6 100644 --- a/computer_oriented_statistical_methods/gaussian_elimination.cpp +++ b/computer_oriented_statistical_methods/gaussian_elimination.cpp @@ -6,7 +6,11 @@ int main() { std::cout << "Matrix size: "; std::cin >> mat_size; - double mat[mat_size + 1][mat_size + 1], x[mat_size][mat_size + 1]; + double **mat = new double *[mat_size + 1], **x = new double *[mat_size]; + for (i = 0; i <= mat_size; i++) { + mat[i] = new double[mat_size + 1]; + if (i < mat_size) x[i] = new double[mat_size + 1]; + } std::cout << std::endl << "Enter value of the matrix: " << std::endl; for (i = 0; i < mat_size; i++) { @@ -49,5 +53,13 @@ int main() { std::cout << "x" << i << "= " << x[i][i] << std::endl; } + + for (i = 0; i <= mat_size; i++) { + delete[] mat[i]; + if (i < mat_size) delete[] x[i]; + } + delete[] mat; + delete[] x; + return 0; } From 8cb310a9fce0c50101487c4f559a6db3d79290c0 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 09:35:25 -0400 Subject: [PATCH 082/433] removed in-favor of chronos library of c++11 (cherry picked from commit 899be6a1f17e4f1bd1e7fee6375432767757cc0b) --- others/measure_time_elapsed.cpp | 19 ------------------- 1 file changed, 19 deletions(-) delete mode 100644 others/measure_time_elapsed.cpp diff --git a/others/measure_time_elapsed.cpp b/others/measure_time_elapsed.cpp deleted file mode 100644 index d0830ab79fe..00000000000 --- a/others/measure_time_elapsed.cpp +++ /dev/null @@ -1,19 +0,0 @@ -// To calculate the time taken by a code to execute -#include -#include - -__int64_t getTimeInMicroseconds() { - struct timeval start; - gettimeofday(&start, NULL); - return start.tv_sec * 1000000 + start.tv_usec; -} - -// write function sample(args) - -int main() { - // write code - __int64_t starttime = getTimeInMicroseconds(); - // sample(args) function run - // Any other functions (if present) run - std::cout << getTimeInMicroseconds() - starttime; -} From 64c8bf38bdb214c9a0eb1e3c6c2f0245e9dcad78 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 09:37:36 -0400 Subject: [PATCH 083/433] fixed dynamic array (cherry picked from commit dd20bf94427392ea0baa428ecf2587d6a8a7a131) --- others/sparse_matrix.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/others/sparse_matrix.cpp b/others/sparse_matrix.cpp index de4759a3e14..d9878fda425 100644 --- a/others/sparse_matrix.cpp +++ b/others/sparse_matrix.cpp @@ -13,7 +13,9 @@ int main() { std::cin >> m; std::cin >> n; - int a[m][n]; + int **a = new int *[m]; + for (int i = 0; i < m; i++) a[i] = new int[n]; + std::cout << "Enter matrix elements:"; std::cout << "\n"; @@ -37,4 +39,8 @@ int main() { std::cout << "Sparse matrix"; else std::cout << "Not a sparse matrix"; + + for (int i = 0; i < m; i++) delete[] a[i]; + delete[] a; + return 0; } From a15b5c5a9ba954c112e8e599e7885d9afb297ac0 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 10:06:01 -0400 Subject: [PATCH 084/433] MSVC does not know cstring-use string-for toString (cherry picked from commit fe9d2b9bc66ee9f2e5112ced6b6d5aab7d5e5f05) --- others/palindrome_of_number.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/others/palindrome_of_number.cpp b/others/palindrome_of_number.cpp index dda8728826c..621b09ab6ba 100644 --- a/others/palindrome_of_number.cpp +++ b/others/palindrome_of_number.cpp @@ -1,6 +1,13 @@ #include #include +#ifdef _MSC_VER +// Required to compile std::toString function using MSVC +#include +#else +#include +#endif + int main() { int num; std::cout << "Enter number = "; From cfe9142c92e7cabc763b0c931f6bec5548c46c0a Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 26 May 2020 14:18:48 +0000 Subject: [PATCH 085/433] updating DIRECTORY.md --- DIRECTORY.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index 9e163d41435..47842b9cad8 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -141,8 +141,7 @@ * [Gcd Of N Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/gcd_of_n_numbers.cpp) * [Happy Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/happy_number.cpp) * [Matrix Exponentiation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/matrix_exponentiation.cpp) - * [Measure Time Elapsed](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/measure_time_elapsed.cpp) - * [Palindromeofnumber](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Palindromeofnumber.cpp) + * [Palindrome Of Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/palindrome_of_number.cpp) * [Paranthesis Matching](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/paranthesis_matching.cpp) * [Pascal Triangle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/pascal_triangle.cpp) * [Primality Test](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/primality_test.cpp) From 62ff9fb19b97c34fdaf5fc4e06c32886542696a8 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 10:57:46 -0400 Subject: [PATCH 086/433] add cmake to strings folder remove CXX-14 standard for MSVC --- CMakeLists.txt | 3 ++- strings/CMakeLists.txt | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 strings/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index 4394f84e143..ab633b82742 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -12,7 +12,7 @@ set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED ON) if(MSVC) - set(CMAKE_CXX_STANDARD 14) + # set(CMAKE_CXX_STANDARD 14) add_compile_definitions(_CRT_SECURE_NO_WARNINGS) endif(MSVC) @@ -50,6 +50,7 @@ endif() add_subdirectory(math) add_subdirectory(others) +add_subdirectory(strings) add_subdirectory(computer_oriented_statistical_methods) if(USE_OPENMP) diff --git a/strings/CMakeLists.txt b/strings/CMakeLists.txt new file mode 100644 index 00000000000..3c15695cc6f --- /dev/null +++ b/strings/CMakeLists.txt @@ -0,0 +1,18 @@ +# If necessary, use the RELATIVE flag, otherwise each source file may be listed +# with full pathname. RELATIVE may makes it easier to extract an executable name +# automatically. +file( GLOB APP_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp ) +# file( GLOB APP_SOURCES ${CMAKE_SOURCE_DIR}/*.c ) +# AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR} APP_SOURCES) +foreach( testsourcefile ${APP_SOURCES} ) + # I used a simple string replace, to cut off .cpp. + string( REPLACE ".cpp" "" testname ${testsourcefile} ) + add_executable( ${testname} ${testsourcefile} ) + + set_target_properties(${testname} PROPERTIES LINKER_LANGUAGE CXX) + if(OpenMP_CXX_FOUND) + target_link_libraries(${testname} OpenMP::OpenMP_CXX) + endif() + install(TARGETS ${testname} DESTINATION "bin/strings") + +endforeach( testsourcefile ${APP_SOURCES} ) From 3f5c524722ce29723c17513d4507004a7b7bfe41 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 10:57:46 -0400 Subject: [PATCH 087/433] add cmake to strings folder remove CXX-14 standard for MSVC --- CMakeLists.txt | 3 ++- strings/CMakeLists.txt | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 strings/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index 4394f84e143..ab633b82742 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -12,7 +12,7 @@ set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED ON) if(MSVC) - set(CMAKE_CXX_STANDARD 14) + # set(CMAKE_CXX_STANDARD 14) add_compile_definitions(_CRT_SECURE_NO_WARNINGS) endif(MSVC) @@ -50,6 +50,7 @@ endif() add_subdirectory(math) add_subdirectory(others) +add_subdirectory(strings) add_subdirectory(computer_oriented_statistical_methods) if(USE_OPENMP) diff --git a/strings/CMakeLists.txt b/strings/CMakeLists.txt new file mode 100644 index 00000000000..3c15695cc6f --- /dev/null +++ b/strings/CMakeLists.txt @@ -0,0 +1,18 @@ +# If necessary, use the RELATIVE flag, otherwise each source file may be listed +# with full pathname. RELATIVE may makes it easier to extract an executable name +# automatically. +file( GLOB APP_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp ) +# file( GLOB APP_SOURCES ${CMAKE_SOURCE_DIR}/*.c ) +# AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR} APP_SOURCES) +foreach( testsourcefile ${APP_SOURCES} ) + # I used a simple string replace, to cut off .cpp. + string( REPLACE ".cpp" "" testname ${testsourcefile} ) + add_executable( ${testname} ${testsourcefile} ) + + set_target_properties(${testname} PROPERTIES LINKER_LANGUAGE CXX) + if(OpenMP_CXX_FOUND) + target_link_libraries(${testname} OpenMP::OpenMP_CXX) + endif() + install(TARGETS ${testname} DESTINATION "bin/strings") + +endforeach( testsourcefile ${APP_SOURCES} ) From 7efa52e0672749b9915d8af03545f66fd6d5848e Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 11:33:57 -0400 Subject: [PATCH 088/433] fix CPPLINT in sorting folder --- sorting/BeadSort.cpp | 63 --- sorting/BitonicSort.cpp | 76 ---- sorting/Bubble Sort.cpp | 83 ---- sorting/CocktailSelectionSort.cpp | 109 ----- sorting/NumericStringSort.cpp | 62 --- sorting/bead_sort.cpp | 54 +++ sorting/bitonic_sort.cpp | 63 +++ sorting/bubble_sort.cpp | 83 ++++ sorting/{bucketSort.cpp => bucket_sort.cpp} | 0 sorting/cocktail_selection_sort.cpp | 101 +++++ sorting/{combsort.cpp => comb_sort.cpp} | 0 ...ortString.cpp => counting_sort_string.cpp} | 0 sorting/doxy.txt | 374 ------------------ ...{Insertion Sort.cpp => insertion_sort.cpp} | 0 sorting/makefile | 11 - sorting/{Merge Sort.cpp => merge_sort.cpp} | 0 sorting/non_recursive_merge_sort.cpp | 38 +- sorting/numeric_string_sort.cpp | 54 +++ .../{OddEven Sort.cpp => odd_even_sort.cpp} | 0 sorting/{Quick Sort.cpp => quick_sort.cpp} | 0 sorting/{Radix Sort.cpp => radix_sort.cpp} | 0 ...{Selection Sort.cpp => selection_sort.cpp} | 0 sorting/{Shell Sort.cpp => shell_sort.cpp} | 0 sorting/{Slow Sort.cpp => slow_sort.cpp} | 0 sorting/{Tim Sort.cpp => tim_sort.cpp} | 0 25 files changed, 372 insertions(+), 799 deletions(-) delete mode 100644 sorting/BeadSort.cpp delete mode 100644 sorting/BitonicSort.cpp delete mode 100644 sorting/Bubble Sort.cpp delete mode 100644 sorting/CocktailSelectionSort.cpp delete mode 100644 sorting/NumericStringSort.cpp create mode 100644 sorting/bead_sort.cpp create mode 100644 sorting/bitonic_sort.cpp create mode 100644 sorting/bubble_sort.cpp rename sorting/{bucketSort.cpp => bucket_sort.cpp} (100%) create mode 100644 sorting/cocktail_selection_sort.cpp rename sorting/{combsort.cpp => comb_sort.cpp} (100%) rename sorting/{CountingSortString.cpp => counting_sort_string.cpp} (100%) delete mode 100644 sorting/doxy.txt rename sorting/{Insertion Sort.cpp => insertion_sort.cpp} (100%) delete mode 100644 sorting/makefile rename sorting/{Merge Sort.cpp => merge_sort.cpp} (100%) create mode 100644 sorting/numeric_string_sort.cpp rename sorting/{OddEven Sort.cpp => odd_even_sort.cpp} (100%) rename sorting/{Quick Sort.cpp => quick_sort.cpp} (100%) rename sorting/{Radix Sort.cpp => radix_sort.cpp} (100%) rename sorting/{Selection Sort.cpp => selection_sort.cpp} (100%) rename sorting/{Shell Sort.cpp => shell_sort.cpp} (100%) rename sorting/{Slow Sort.cpp => slow_sort.cpp} (100%) rename sorting/{Tim Sort.cpp => tim_sort.cpp} (100%) diff --git a/sorting/BeadSort.cpp b/sorting/BeadSort.cpp deleted file mode 100644 index c8e27b2507e..00000000000 --- a/sorting/BeadSort.cpp +++ /dev/null @@ -1,63 +0,0 @@ -// C++ program to implement gravity/bead sort -#include -#include -using namespace std; - -#define BEAD(i, j) beads[i * max + j] - -// function to perform the above algorithm -void beadSort(int *a, int len) -{ - // Find the maximum element - int max = a[0]; - for (int i = 1; i < len; i++) - if (a[i] > max) - max = a[i]; - - // allocating memory - unsigned char beads[max*len]; - memset(beads, 0, sizeof(beads)); - - // mark the beads - for (int i = 0; i < len; i++) - for (int j = 0; j < a[i]; j++) - BEAD(i, j) = 1; - - for (int j = 0; j < max; j++) - { - // count how many beads are on each post - int sum = 0; - for (int i=0; i < len; i++) - { - sum += BEAD(i, j); - BEAD(i, j) = 0; - } - - // Move beads down - for (int i = len - sum; i < len; i++) - BEAD(i, j) = 1; - } - - // Put sorted values in array using beads - for (int i = 0; i < len; i++) - { - int j; - for (j = 0; j < max && BEAD(i, j); j++); - - a[i] = j; - } -} - -// driver function to test the algorithm -int main() -{ - int a[] = {5, 3, 1, 7, 4, 1, 1, 20}; - int len = sizeof(a)/sizeof(a[0]); - - beadSort(a, len); - - for (int i = 0; i < len; i++) - printf("%d ", a[i]); - - return 0; -} diff --git a/sorting/BitonicSort.cpp b/sorting/BitonicSort.cpp deleted file mode 100644 index 6ad2489d229..00000000000 --- a/sorting/BitonicSort.cpp +++ /dev/null @@ -1,76 +0,0 @@ -// Source : https://www.geeksforgeeks.org/bitonic-sort/ - -/* C++ Program for Bitonic Sort. Note that this program - works only when size of input is a power of 2. */ - -#include -#include -using namespace std; - -/*The parameter dir indicates the sorting direction, ASCENDING - or DESCENDING; if (a[i] > a[j]) agrees with the direction, - then a[i] and a[j] are interchanged.*/ -void compAndSwap(int a[], int i, int j, int dir) -{ - if (dir == (a[i] > a[j])) - swap(a[i], a[j]); -} - -/*It recursively sorts a bitonic sequence in ascending order, - if dir = 1, and in descending order otherwise (means dir=0). - The sequence to be sorted starts at index position low, - the parameter cnt is the number of elements to be sorted.*/ -void bitonicMerge(int a[], int low, int cnt, int dir) -{ - if (cnt > 1) - { - int k = cnt / 2; - for (int i = low; i < low + k; i++) - compAndSwap(a, i, i + k, dir); - bitonicMerge(a, low, k, dir); - bitonicMerge(a, low + k, k, dir); - } -} - -/* This function first produces a bitonic sequence by recursively - sorting its two halves in opposite sorting orders, and then - calls bitonicMerge to make them in the same order */ -void bitonicSort(int a[], int low, int cnt, int dir) -{ - if (cnt > 1) - { - int k = cnt / 2; - - // sort in ascending order since dir here is 1 - bitonicSort(a, low, k, 1); - - // sort in descending order since dir here is 0 - bitonicSort(a, low + k, k, 0); - - // Will merge wole sequence in ascending order - // since dir=1. - bitonicMerge(a, low, cnt, dir); - } -} - -/* Caller of bitonicSort for sorting the entire array of - length N in ASCENDING order */ -void sort(int a[], int N, int up) -{ - bitonicSort(a, 0, N, up); -} - -// Driver code -int main() -{ - int a[] = {3, 7, 4, 8, 6, 2, 1, 5}; - int N = sizeof(a) / sizeof(a[0]); - - int up = 1; // means sort in ascending order - sort(a, N, up); - - printf("Sorted array: \n"); - for (int i = 0; i < N; i++) - printf("%d ", a[i]); - return 0; -} diff --git a/sorting/Bubble Sort.cpp b/sorting/Bubble Sort.cpp deleted file mode 100644 index b160ac4790a..00000000000 --- a/sorting/Bubble Sort.cpp +++ /dev/null @@ -1,83 +0,0 @@ -//Bubble Sort - -#include -#include -using namespace std; - -int main() -{ - int n; - short swap_check = 1; - cout << "Enter the amount of numbers to sort: "; - cin >> n; - vector numbers; - cout << "Enter " << n << " numbers: "; - int num; - - //Input - for (int i = 0; i < n; i++) - { - cin >> num; - numbers.push_back(num); - } - - //Bubble Sorting - for (int i = 0; (i < n) && (swap_check == 1); i++) - { - swap_check = 0; - for (int j = 0; j < n - 1 - i; j++) - { - if (numbers[j] > numbers[j + 1]) - { - swap_check = 1; - swap(numbers[j], numbers[j + 1]);// by changing swap location. I mean, j. If the number is greater than j + 1, then it means the location. - } - } - } - - //Output - cout << "\nSorted Array : "; - for (int i = 0; i < numbers.size(); i++) - { - if (i != numbers.size() - 1) - { - cout << numbers[i] << ", "; - } - else - { - cout << numbers[i] << endl; - } - } - return 0; -} - -/*The working principle of the Bubble sort algorithm: - -Bubble sort algorithm is the bubble sorting algorithm. The most important reason for calling the bubble is that the largest number is thrown at the end of this algorithm. -This is all about the logic. -In each iteration, the largest number is expired and when iterations are completed, the sorting takes place. - -What is Swap? - -Swap in the software means that two variables are displaced. -An additional variable is required for this operation. x = 5, y = 10. -We want x = 10, y = 5. Here we create the most variable to do it. - -int z; -z = x; -x = y; -y = z; - -The above process is a typical displacement process. -When x assigns the value to x, the old value of x is lost. -That's why we created a variable z to create the first value of the value of x, and finally, we have assigned to y. - -Bubble Sort Algorithm Analysis (Best Case - Worst Case - Average Case) - -Bubble Sort Worst Case Performance is O (n²). Why is that? Because if you remember Big O Notation, we were calculating the complexity of the algorithms in the nested loops. -The n * (n - 1) product gives us O (n²) performance. In the worst case all the steps of the cycle will occur. -Bubble Sort (Avarage Case) Performance. Bubble Sort is not an optimal algorithm. -in average, O (n²) performance is taken. -Bubble Sort Best Case Performance. O (n). -However, you can't get the best status in the code we shared above. This happens on the optimized bubble sort algorithm. It's right down there. -* / diff --git a/sorting/CocktailSelectionSort.cpp b/sorting/CocktailSelectionSort.cpp deleted file mode 100644 index cac6a361871..00000000000 --- a/sorting/CocktailSelectionSort.cpp +++ /dev/null @@ -1,109 +0,0 @@ -//Returns Sorted elements after performing Cocktail Selection Sort -//It is a Sorting algorithm which chooses the minimum and maximum element in an array simultaneously, -//and swaps it with the lowest and highest available position iteratively or recursively - -#include -using namespace std; - -//Iterative Version - -void CocktailSelectionSort(vector &vec, int low, int high) -{ - while (low <= high) - { - int minimum = vec[low]; - int minimumindex = low; - int maximum = vec[high]; - int maximumindex = high; - - for (int i = low; i <= high; i++) - { - if (vec[i] >= maximum) - { - maximum = vec[i]; - maximumindex = i; - } - if (vec[i] <= minimum) - { - minimum = vec[i]; - minimumindex = i; - } - } - if (low != maximumindex || high != minimumindex) - { - swap(vec[low], vec[minimumindex]); - swap(vec[high], vec[maximumindex]); - } - else - { - swap(vec[low], vec[high]); - } - - low++; - high--; - } -} - -//Recursive Version - -void CocktailSelectionSort(vector &vec, int low, int high) -{ - - if (low >= high) - return; - - int minimum = vec[low]; - int minimumindex = low; - int maximum = vec[high]; - int maximumindex = high; - - for (int i = low; i <= high; i++) - { - if (vec[i] >= maximum) - { - maximum = vec[i]; - maximumindex = i; - } - if (vec[i] <= minimum) - { - minimum = vec[i]; - minimumindex = i; - } - } - if (low != maximumindex || high != minimumindex) - { - swap(vec[low], vec[minimumindex]); - swap(vec[high], vec[maximumindex]); - } - else - { - swap(vec[low], vec[high]); - } - - CocktailSelectionSort(vec, low + 1, high - 1); -} - -//main function, select any one of iterative or recursive version - -int main() -{ - - int n; - cout << "Enter number of elements\n"; - cin >> n; - std::vector v(n); - cout << "Enter all the elements\n"; - for (int i = 0; i < n; ++i) - { - cin >> v[i]; - } - - CocktailSelectionSort(v, 0, n - 1); - cout << "Sorted elements are\n"; - for (int i = 0; i < n; ++i) - { - cout << v[i] << " "; - } - - return 0; -} diff --git a/sorting/NumericStringSort.cpp b/sorting/NumericStringSort.cpp deleted file mode 100644 index 02f6964ba14..00000000000 --- a/sorting/NumericStringSort.cpp +++ /dev/null @@ -1,62 +0,0 @@ -//Using general algorithms to sort a collection of strings results in alphanumeric sort. -//If it is a numeric string, it leads to unnatural sorting - -//eg, an array of strings 1,10,100,2,20,200,3,30,300 -//would be sorted in that same order by using conventional sorting, -//even though we know the correct sorting order is 1,2,3,10,20,30,100,200,300 - -//This Programme uses a comparator to sort the array in Numerical order instead of Alphanumeric order - -#include -#include -#include -using namespace std; - -bool NumericSort(string a, string b) -{ - while (a[0] == '0') - { - a.erase(a.begin()); - } - while (b[0] == '0') - { - b.erase(b.begin()); - } - int n = a.length(); - int m = b.length(); - if (n == m) - return a < b; - return n < m; -} - -int main() -{ - - int n; - cout << "Enter number of elements to be sorted Numerically\n"; - cin >> n; - - vector v(n); - cout << "Enter the string of Numbers\n"; - for (int i = 0; i < n; i++) - { - cin >> v[i]; - } - - sort(v.begin(), v.end()); - cout << "Elements sorted normally \n"; - for (int i = 0; i < n; i++) - { - cout << v[i] << " "; - } - cout << "\n"; - - sort(v.begin(), v.end(), NumericSort); - cout << "Elements sorted Numerically \n"; - for (int i = 0; i < n; i++) - { - cout << v[i] << " "; - } - - return 0; -} diff --git a/sorting/bead_sort.cpp b/sorting/bead_sort.cpp new file mode 100644 index 00000000000..12b7d4d3205 --- /dev/null +++ b/sorting/bead_sort.cpp @@ -0,0 +1,54 @@ +// C++ program to implement gravity/bead sort +#include +#include + +#define BEAD(i, j) beads[i * max + j] + +// function to perform the above algorithm +void beadSort(int *a, int len) { + // Find the maximum element + int max = a[0]; + for (int i = 1; i < len; i++) + if (a[i] > max) max = a[i]; + + // allocating memory + unsigned char beads[max * len]; + memset(beads, 0, sizeof(beads)); + + // mark the beads + for (int i = 0; i < len; i++) + for (int j = 0; j < a[i]; j++) BEAD(i, j) = 1; + + for (int j = 0; j < max; j++) { + // count how many beads are on each post + int sum = 0; + for (int i = 0; i < len; i++) { + sum += BEAD(i, j); + BEAD(i, j) = 0; + } + + // Move beads down + for (int i = len - sum; i < len; i++) BEAD(i, j) = 1; + } + + // Put sorted values in array using beads + for (int i = 0; i < len; i++) { + int j; + for (j = 0; j < max && BEAD(i, j); j++) + ; + + a[i] = j; + } +} + +// driver function to test the algorithm +int main() { + int a[] = {5, 3, 1, 7, 4, 1, 1, 20}; + int len = sizeof(a) / sizeof(a[0]); + + beadSort(a, len); + + for (int i = 0; i < len; i++) printf("%d ", a[i]); + + return 0; +} diff --git a/sorting/bitonic_sort.cpp b/sorting/bitonic_sort.cpp new file mode 100644 index 00000000000..4d098105649 --- /dev/null +++ b/sorting/bitonic_sort.cpp @@ -0,0 +1,63 @@ +// Source : https://www.geeksforgeeks.org/bitonic-sort/ + +/* C++ Program for Bitonic Sort. Note that this program + works only when size of input is a power of 2. */ + +#include +#include + +/*The parameter dir indicates the sorting direction, ASCENDING + or DESCENDING; if (a[i] > a[j]) agrees with the direction, + then a[i] and a[j] are interchanged.*/ +void compAndSwap(int a[], int i, int j, int dir) { + if (dir == (a[i] > a[j])) std::swap(a[i], a[j]); +} + +/*It recursively sorts a bitonic sequence in ascending order, + if dir = 1, and in descending order otherwise (means dir=0). + The sequence to be sorted starts at index position low, + the parameter cnt is the number of elements to be sorted.*/ +void bitonicMerge(int a[], int low, int cnt, int dir) { + if (cnt > 1) { + int k = cnt / 2; + for (int i = low; i < low + k; i++) compAndSwap(a, i, i + k, dir); + bitonicMerge(a, low, k, dir); + bitonicMerge(a, low + k, k, dir); + } +} + +/* This function first produces a bitonic sequence by recursively + sorting its two halves in opposite sorting orders, and then + calls bitonicMerge to make them in the same order */ +void bitonicSort(int a[], int low, int cnt, int dir) { + if (cnt > 1) { + int k = cnt / 2; + + // sort in ascending order since dir here is 1 + bitonicSort(a, low, k, 1); + + // sort in descending order since dir here is 0 + bitonicSort(a, low + k, k, 0); + + // Will merge wole sequence in ascending order + // since dir=1. + bitonicMerge(a, low, cnt, dir); + } +} + +/* Caller of bitonicSort for sorting the entire array of + length N in ASCENDING order */ +void sort(int a[], int N, int up) { bitonicSort(a, 0, N, up); } + +// Driver code +int main() { + int a[] = {3, 7, 4, 8, 6, 2, 1, 5}; + int N = sizeof(a) / sizeof(a[0]); + + int up = 1; // means sort in ascending order + sort(a, N, up); + + std::cout << "Sorted array: \n"; + for (int i = 0; i < N; i++) std::cout << a[i] << " "; + return 0; +} diff --git a/sorting/bubble_sort.cpp b/sorting/bubble_sort.cpp new file mode 100644 index 00000000000..794f651983d --- /dev/null +++ b/sorting/bubble_sort.cpp @@ -0,0 +1,83 @@ +/** + * @file + * @brief Bubble sort algorithm + * + * The working principle of the Bubble sort algorithm: + +Bubble sort algorithm is the bubble sorting algorithm. The most important reason +for calling the bubble is that the largest number is thrown at the end of this +algorithm. This is all about the logic. In each iteration, the largest number is +expired and when iterations are completed, the sorting takes place. + +What is Swap? + +Swap in the software means that two variables are displaced. +An additional variable is required for this operation. x = 5, y = 10. +We want x = 10, y = 5. Here we create the most variable to do it. + +int z; +z = x; +x = y; +y = z; + +The above process is a typical displacement process. +When x assigns the value to x, the old value of x is lost. +That's why we created a variable z to create the first value of the value of x, +and finally, we have assigned to y. + +Bubble Sort Algorithm Analysis (Best Case - Worst Case - Average Case) + +Bubble Sort Worst Case Performance is O (n²). Why is that? Because if you +remember Big O Notation, we were calculating the complexity of the algorithms in +the nested loops. The n * (n - 1) product gives us O (n²) performance. In the +worst case all the steps of the cycle will occur. Bubble Sort (Avarage Case) +Performance. Bubble Sort is not an optimal algorithm. in average, O (n²) +performance is taken. Bubble Sort Best Case Performance. O (n). However, you +can't get the best status in the code we shared above. This happens on the +optimized bubble sort algorithm. It's right down there. +*/ + +#include +#include + +int main() { + int n; + short swap_check = 1; + std::cout << "Enter the amount of numbers to sort: "; + std::cin >> n; + std::vector numbers; + std::cout << "Enter " << n << " numbers: "; + int num; + + // Input + for (int i = 0; i < n; i++) { + std::cin >> num; + numbers.push_back(num); + } + + // Bubble Sorting + for (int i = 0; (i < n) && (swap_check == 1); i++) { + swap_check = 0; + for (int j = 0; j < n - 1 - i; j++) { + if (numbers[j] > numbers[j + 1]) { + swap_check = 1; + std::swap(numbers[j], + numbers[j + 1]); // by changing swap location. + // I mean, j. If the number is + // greater than j + 1, then it + // means the location. + } + } + } + + // Output + std::cout << "\nSorted Array : "; + for (int i = 0; i < numbers.size(); i++) { + if (i != numbers.size() - 1) { + std::cout << numbers[i] << ", "; + } else { + std::cout << numbers[i] << std::endl; + } + } + return 0; +} diff --git a/sorting/bucketSort.cpp b/sorting/bucket_sort.cpp similarity index 100% rename from sorting/bucketSort.cpp rename to sorting/bucket_sort.cpp diff --git a/sorting/cocktail_selection_sort.cpp b/sorting/cocktail_selection_sort.cpp new file mode 100644 index 00000000000..a9abd86d535 --- /dev/null +++ b/sorting/cocktail_selection_sort.cpp @@ -0,0 +1,101 @@ +// Returns Sorted elements after performing Cocktail Selection Sort +// It is a Sorting algorithm which chooses the minimum and maximum element in an +// array simultaneously, and swaps it with the lowest and highest available +// position iteratively or recursively + +#include +#include +#include + +// Iterative Version + +void CocktailSelectionSort(std::vector &vec, int low, int high) { + while (low <= high) { + int minimum = vec[low]; + int minimumindex = low; + int maximum = vec[high]; + int maximumindex = high; + + for (int i = low; i <= high; i++) { + if (vec[i] >= maximum) { + maximum = vec[i]; + maximumindex = i; + } + if (vec[i] <= minimum) { + minimum = vec[i]; + minimumindex = i; + } + } + if (low != maximumindex || high != minimumindex) { + std::swap(vec[low], vec[minimumindex]); + std::swap(vec[high], vec[maximumindex]); + } else { + std::swap(vec[low], vec[high]); + } + + low++; + high--; + } +} + +// Recursive Version + +void CocktailSelectionSort_v2(std::vector &vec, int low, int high) { + if (low >= high) return; + + int minimum = vec[low]; + int minimumindex = low; + int maximum = vec[high]; + int maximumindex = high; + + for (int i = low; i <= high; i++) { + if (vec[i] >= maximum) { + maximum = vec[i]; + maximumindex = i; + } + if (vec[i] <= minimum) { + minimum = vec[i]; + minimumindex = i; + } + } + if (low != maximumindex || high != minimumindex) { + std::swap(vec[low], vec[minimumindex]); + std::swap(vec[high], vec[maximumindex]); + } else { + std::swap(vec[low], vec[high]); + } + + CocktailSelectionSort(vec, low + 1, high - 1); +} + +// main function, select any one of iterative or recursive version + +int main() { + int n; + std::cout << "Enter number of elements\n"; + std::cin >> n; + std::vector v(n); + std::cout << "Enter all the elements\n"; + for (int i = 0; i < n; ++i) { + std::cin >> v[i]; + } + + int method; + std::cout << "Enter method: \n\t0: iterative\n\t1: recursive:\t"; + std::cin >> method; + + if (method == 0) { + CocktailSelectionSort(v, 0, n - 1); + } else if (method == 1) { + CocktailSelectionSort_v2(v, 0, n - 1); + } else { + std::cerr << "Unknown method" << std::endl; + return -1; + } + std::cout << "Sorted elements are\n"; + for (int i = 0; i < n; ++i) { + std::cout << v[i] << " "; + } + + return 0; +} diff --git a/sorting/combsort.cpp b/sorting/comb_sort.cpp similarity index 100% rename from sorting/combsort.cpp rename to sorting/comb_sort.cpp diff --git a/sorting/CountingSortString.cpp b/sorting/counting_sort_string.cpp similarity index 100% rename from sorting/CountingSortString.cpp rename to sorting/counting_sort_string.cpp diff --git a/sorting/doxy.txt b/sorting/doxy.txt deleted file mode 100644 index 68079276e7b..00000000000 --- a/sorting/doxy.txt +++ /dev/null @@ -1,374 +0,0 @@ -# Doxyfile 1.8.13 -#This configuration file has been generated from Doxygen template. -#--------------------------------------------------------------------------- -# Project related configuration options -#--------------------------------------------------------------------------- -DOXYFILE_ENCODING = UTF-8 -PROJECT_NAME = "My Project" -PROJECT_NUMBER = -PROJECT_BRIEF = -PROJECT_LOGO = -OUTPUT_DIRECTORY = -CREATE_SUBDIRS = NO -ALLOW_UNICODE_NAMES = NO -OUTPUT_LANGUAGE = English -BRIEF_MEMBER_DESC = YES -REPEAT_BRIEF = YES -ABBREVIATE_BRIEF = "The $name class" \ - "The $name widget" \ - "The $name file" \ - is \ - provides \ - specifies \ - contains \ - represents \ - a \ - an \ - the -ALWAYS_DETAILED_SEC = NO -INLINE_INHERITED_MEMB = NO -FULL_PATH_NAMES = YES -STRIP_FROM_PATH = -STRIP_FROM_INC_PATH = -SHORT_NAMES = NO -JAVADOC_AUTOBRIEF = NO -QT_AUTOBRIEF = NO -MULTILINE_CPP_IS_BRIEF = NO -INHERIT_DOCS = YES -SEPARATE_MEMBER_PAGES = NO -TAB_SIZE = 4 -ALIASES = -TCL_SUBST = -OPTIMIZE_OUTPUT_FOR_C = NO -OPTIMIZE_OUTPUT_JAVA = NO -OPTIMIZE_FOR_FORTRAN = NO -OPTIMIZE_OUTPUT_VHDL = NO -EXTENSION_MAPPING = -MARKDOWN_SUPPORT = YES -TOC_INCLUDE_HEADINGS = 0 -AUTOLINK_SUPPORT = YES -BUILTIN_STL_SUPPORT = NO -CPP_CLI_SUPPORT = NO -SIP_SUPPORT = NO -IDL_PROPERTY_SUPPORT = YES -DISTRIBUTE_GROUP_DOC = NO -GROUP_NESTED_COMPOUNDS = NO -SUBGROUPING = YES -INLINE_GROUPED_CLASSES = NO -INLINE_SIMPLE_STRUCTS = NO -TYPEDEF_HIDES_STRUCT = NO -LOOKUP_CACHE_SIZE = 0 -#--------------------------------------------------------------------------- -# Build related configuration options -#--------------------------------------------------------------------------- -EXTRACT_ALL = NO -EXTRACT_PRIVATE = NO -EXTRACT_PACKAGE = NO -EXTRACT_STATIC = NO -EXTRACT_LOCAL_CLASSES = YES -EXTRACT_LOCAL_METHODS = NO -EXTRACT_ANON_NSPACES = NO -HIDE_UNDOC_MEMBERS = NO -HIDE_UNDOC_CLASSES = NO -HIDE_FRIEND_COMPOUNDS = NO -HIDE_IN_BODY_DOCS = NO -INTERNAL_DOCS = NO -CASE_SENSE_NAMES = YES -HIDE_SCOPE_NAMES = NO -HIDE_COMPOUND_REFERENCE= NO -SHOW_INCLUDE_FILES = YES -SHOW_GROUPED_MEMB_INC = NO -FORCE_LOCAL_INCLUDES = NO -INLINE_INFO = YES -SORT_MEMBER_DOCS = YES -SORT_BRIEF_DOCS = NO -SORT_MEMBERS_CTORS_1ST = NO -SORT_GROUP_NAMES = NO -SORT_BY_SCOPE_NAME = NO -STRICT_PROTO_MATCHING = NO -GENERATE_TODOLIST = YES -GENERATE_TESTLIST = YES -GENERATE_BUGLIST = YES -GENERATE_DEPRECATEDLIST= YES -ENABLED_SECTIONS = -MAX_INITIALIZER_LINES = 30 -SHOW_USED_FILES = YES -SHOW_FILES = YES -SHOW_NAMESPACES = YES -FILE_VERSION_FILTER = -LAYOUT_FILE = -CITE_BIB_FILES = -#--------------------------------------------------------------------------- -# Configuration options related to warning and progress messages -#--------------------------------------------------------------------------- -QUIET = NO -WARNINGS = YES -WARN_IF_UNDOCUMENTED = YES -WARN_IF_DOC_ERROR = YES -WARN_NO_PARAMDOC = NO -WARN_AS_ERROR = NO -WARN_FORMAT = "$file:$line: $text" -WARN_LOGFILE = -#--------------------------------------------------------------------------- -# Configuration options related to the input files -#--------------------------------------------------------------------------- -INPUT = -INPUT_ENCODING = UTF-8 -FILE_PATTERNS = *.c \ - *.cc \ - *.cxx \ - *.cpp \ - *.c++ \ - *.java \ - *.ii \ - *.ixx \ - *.ipp \ - *.i++ \ - *.inl \ - *.idl \ - *.ddl \ - *.odl \ - *.h \ - *.hh \ - *.hxx \ - *.hpp \ - *.h++ \ - *.cs \ - *.d \ - *.php \ - *.php4 \ - *.php5 \ - *.phtml \ - *.inc \ - *.m \ - *.markdown \ - *.md \ - *.mm \ - *.dox \ - *.py \ - *.pyw \ - *.f90 \ - *.f95 \ - *.f03 \ - *.f08 \ - *.f \ - *.for \ - *.tcl \ - *.vhd \ - *.vhdl \ - *.ucf \ - *.qsf -RECURSIVE = NO -EXCLUDE = -EXCLUDE_SYMLINKS = NO -EXCLUDE_PATTERNS = -EXCLUDE_SYMBOLS = -EXAMPLE_PATH = -EXAMPLE_PATTERNS = * -EXAMPLE_RECURSIVE = NO -IMAGE_PATH = -INPUT_FILTER = -FILTER_PATTERNS = -FILTER_SOURCE_FILES = NO -FILTER_SOURCE_PATTERNS = -USE_MDFILE_AS_MAINPAGE = -#--------------------------------------------------------------------------- -# Configuration options related to source browsing -#--------------------------------------------------------------------------- -SOURCE_BROWSER = NO -INLINE_SOURCES = NO -STRIP_CODE_COMMENTS = YES -REFERENCED_BY_RELATION = NO -REFERENCES_RELATION = NO -REFERENCES_LINK_SOURCE = YES -SOURCE_TOOLTIPS = YES -USE_HTAGS = NO -VERBATIM_HEADERS = YES -CLANG_ASSISTED_PARSING = NO -CLANG_OPTIONS = -#--------------------------------------------------------------------------- -# Configuration options related to the alphabetical class index -#--------------------------------------------------------------------------- -ALPHABETICAL_INDEX = YES -COLS_IN_ALPHA_INDEX = 5 -IGNORE_PREFIX = -#--------------------------------------------------------------------------- -# Configuration options related to the HTML output -#--------------------------------------------------------------------------- -GENERATE_HTML = YES -HTML_OUTPUT = html -HTML_FILE_EXTENSION = .html -HTML_HEADER = -HTML_FOOTER = -HTML_STYLESHEET = -HTML_EXTRA_STYLESHEET = -HTML_EXTRA_FILES = -HTML_COLORSTYLE_HUE = 220 -HTML_COLORSTYLE_SAT = 100 -HTML_COLORSTYLE_GAMMA = 80 -HTML_TIMESTAMP = NO -HTML_DYNAMIC_SECTIONS = NO -HTML_INDEX_NUM_ENTRIES = 100 -GENERATE_DOCSET = NO -DOCSET_FEEDNAME = "Doxygen generated docs" -DOCSET_BUNDLE_ID = org.doxygen.Project -DOCSET_PUBLISHER_ID = org.doxygen.Publisher -DOCSET_PUBLISHER_NAME = Publisher -GENERATE_HTMLHELP = NO -CHM_FILE = -HHC_LOCATION = -GENERATE_CHI = NO -CHM_INDEX_ENCODING = -BINARY_TOC = NO -TOC_EXPAND = NO -GENERATE_QHP = NO -QCH_FILE = -QHP_NAMESPACE = org.doxygen.Project -QHP_VIRTUAL_FOLDER = doc -QHP_CUST_FILTER_NAME = -QHP_CUST_FILTER_ATTRS = -QHP_SECT_FILTER_ATTRS = -QHG_LOCATION = -GENERATE_ECLIPSEHELP = NO -ECLIPSE_DOC_ID = org.doxygen.Project -DISABLE_INDEX = NO -GENERATE_TREEVIEW = NO -ENUM_VALUES_PER_LINE = 4 -TREEVIEW_WIDTH = 250 -EXT_LINKS_IN_WINDOW = NO -FORMULA_FONTSIZE = 10 -FORMULA_TRANSPARENT = YES -USE_MATHJAX = NO -MATHJAX_FORMAT = HTML-CSS -MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest -MATHJAX_EXTENSIONS = -MATHJAX_CODEFILE = -SEARCHENGINE = YES -SERVER_BASED_SEARCH = NO -EXTERNAL_SEARCH = NO -SEARCHENGINE_URL = -SEARCHDATA_FILE = searchdata.xml -EXTERNAL_SEARCH_ID = -EXTRA_SEARCH_MAPPINGS = -#--------------------------------------------------------------------------- -# Configuration options related to the LaTeX output -#--------------------------------------------------------------------------- -GENERATE_LATEX = NO -LATEX_OUTPUT = latex -LATEX_CMD_NAME = latex -MAKEINDEX_CMD_NAME = makeindex -COMPACT_LATEX = NO -PAPER_TYPE = a4 -EXTRA_PACKAGES = -LATEX_HEADER = -LATEX_FOOTER = -LATEX_EXTRA_STYLESHEET = -LATEX_EXTRA_FILES = -PDF_HYPERLINKS = YES -USE_PDFLATEX = YES -LATEX_BATCHMODE = NO -LATEX_HIDE_INDICES = NO -LATEX_SOURCE_CODE = NO -LATEX_BIB_STYLE = plain -LATEX_TIMESTAMP = NO -#--------------------------------------------------------------------------- -# Configuration options related to the RTF output -#--------------------------------------------------------------------------- -GENERATE_RTF = NO -RTF_OUTPUT = rtf -COMPACT_RTF = NO -RTF_HYPERLINKS = NO -RTF_STYLESHEET_FILE = -RTF_EXTENSIONS_FILE = -RTF_SOURCE_CODE = NO -#--------------------------------------------------------------------------- -# Configuration options related to the man page output -#--------------------------------------------------------------------------- -GENERATE_MAN = NO -MAN_OUTPUT = man -MAN_EXTENSION = .3 -MAN_SUBDIR = -MAN_LINKS = NO -#--------------------------------------------------------------------------- -# Configuration options related to the XML output -#--------------------------------------------------------------------------- -GENERATE_XML = NO -XML_OUTPUT = xml -XML_PROGRAMLISTING = YES -#--------------------------------------------------------------------------- -# Configuration options related to the DOCBOOK output -#--------------------------------------------------------------------------- -GENERATE_DOCBOOK = NO -DOCBOOK_OUTPUT = docbook -DOCBOOK_PROGRAMLISTING = NO -#--------------------------------------------------------------------------- -# Configuration options for the AutoGen Definitions output -#--------------------------------------------------------------------------- -GENERATE_AUTOGEN_DEF = NO -#--------------------------------------------------------------------------- -# Configuration options related to the Perl module output -#--------------------------------------------------------------------------- -GENERATE_PERLMOD = NO -PERLMOD_LATEX = NO -PERLMOD_PRETTY = YES -PERLMOD_MAKEVAR_PREFIX = -#--------------------------------------------------------------------------- -# Configuration options related to the preprocessor -#--------------------------------------------------------------------------- -ENABLE_PREPROCESSING = YES -MACRO_EXPANSION = NO -EXPAND_ONLY_PREDEF = NO -SEARCH_INCLUDES = YES -INCLUDE_PATH = -INCLUDE_FILE_PATTERNS = -PREDEFINED = -EXPAND_AS_DEFINED = -SKIP_FUNCTION_MACROS = YES -#--------------------------------------------------------------------------- -# Configuration options related to external references -#--------------------------------------------------------------------------- -TAGFILES = -GENERATE_TAGFILE = -ALLEXTERNALS = NO -EXTERNAL_GROUPS = YES -EXTERNAL_PAGES = YES -PERL_PATH = /usr/bin/perl -#--------------------------------------------------------------------------- -# Configuration options related to the dot tool -#--------------------------------------------------------------------------- -CLASS_DIAGRAMS = YES -MSCGEN_PATH = -DIA_PATH = -HIDE_UNDOC_RELATIONS = YES -HAVE_DOT = YES -DOT_NUM_THREADS = 0 -DOT_FONTNAME = Helvetica -DOT_FONTSIZE = 10 -DOT_FONTPATH = -CLASS_GRAPH = YES -COLLABORATION_GRAPH = YES -GROUP_GRAPHS = YES -UML_LOOK = NO -UML_LIMIT_NUM_FIELDS = 10 -TEMPLATE_RELATIONS = NO -INCLUDE_GRAPH = YES -INCLUDED_BY_GRAPH = YES -CALL_GRAPH = NO -CALLER_GRAPH = NO -GRAPHICAL_HIERARCHY = YES -DIRECTORY_GRAPH = YES -DOT_IMAGE_FORMAT = png -INTERACTIVE_SVG = NO -DOT_PATH = -DOTFILE_DIRS = -MSCFILE_DIRS = -DIAFILE_DIRS = -PLANTUML_JAR_PATH = -PLANTUML_CFG_FILE = -PLANTUML_INCLUDE_PATH = -DOT_GRAPH_MAX_NODES = 50 -MAX_DOT_GRAPH_DEPTH = 0 -DOT_TRANSPARENT = NO -DOT_MULTI_TARGETS = NO -GENERATE_LEGEND = YES -DOT_CLEANUP = YES diff --git a/sorting/Insertion Sort.cpp b/sorting/insertion_sort.cpp similarity index 100% rename from sorting/Insertion Sort.cpp rename to sorting/insertion_sort.cpp diff --git a/sorting/makefile b/sorting/makefile deleted file mode 100644 index 21d3186c698..00000000000 --- a/sorting/makefile +++ /dev/null @@ -1,11 +0,0 @@ -non_recursive_merge_sort: non_recursive_merge_sort.cpp - g++ -std=c++17 -o non_recursive_merge_sort non_recursive_merge_sort.cpp -.PHONY: test -.PHONY: doc -.PHONY: clean -test: non_recursive_merge_sort - ./non_recursive_merge_sort -doc: doxy.txt - doxygen doxy.txt -clean: - rm -fr non_recursive_merge_sort html diff --git a/sorting/Merge Sort.cpp b/sorting/merge_sort.cpp similarity index 100% rename from sorting/Merge Sort.cpp rename to sorting/merge_sort.cpp diff --git a/sorting/non_recursive_merge_sort.cpp b/sorting/non_recursive_merge_sort.cpp index c6ca56376df..ebfef1dcc50 100644 --- a/sorting/non_recursive_merge_sort.cpp +++ b/sorting/non_recursive_merge_sort.cpp @@ -6,7 +6,7 @@ */ #include // for size_t #include // for std::move & std::remove_reference_t -template +template void merge(Iterator, Iterator, const Iterator, char[]); /// bottom-up merge sort which sorts elements in a non-decreasing order /** @@ -17,13 +17,13 @@ void merge(Iterator, Iterator, const Iterator, char[]); * @param first points to the first element * @param last points to 1-step past the last element * @param n the number of elements -*/ -template + */ +template void non_recursive_merge_sort(const Iterator first, const Iterator last, const size_t n) { // create a buffer large enough to store all elements // dynamically allocated to comply with cpplint - char * buffer = new char[n * sizeof(*first)]; + char* buffer = new char[n * sizeof(*first)]; // buffer size can be optimized to largest power of 2 less than n elements // divide the container into equally-sized segments whose length start at 1 // and keeps increasing by factors of 2 @@ -49,32 +49,28 @@ void non_recursive_merge_sort(const Iterator first, const Iterator last, * @param r points to the right part, end of left part * @param e points to end of right part * @param b points at the buffer -*/ -template + */ +template void merge(Iterator l, Iterator r, const Iterator e, char b[]) { // create 2 pointers to point at the buffer auto p(reinterpret_cast*>(b)), c(p); // move the left part of the segment - for (Iterator t(l); r != t; ++t) - *p++ = std::move(*t); + for (Iterator t(l); r != t; ++t) *p++ = std::move(*t); // while neither the buffer nor the right part has been exhausted // move the smallest element of the two back to the container - while (e != r && c != p) - *l++ = std::move(*r < *c ? *r++ : *c++); + while (e != r && c != p) *l++ = std::move(*r < *c ? *r++ : *c++); // notice only one of the two following loops will be executed // while the right part hasn't bee exhausted, move it back - while (e != r) - *l++ = std::move(*r++); + while (e != r) *l++ = std::move(*r++); // while the buffer hasn't bee exhausted, move it back - while (c != p) - *l++ = std::move(*c++); + while (c != p) *l++ = std::move(*c++); } /// bottom-up merge sort which sorts elements in a non-decreasing order /** * @param first points to the first element * @param n the number of elements -*/ -template + */ +template void non_recursive_merge_sort(const Iterator first, const size_t n) { non_recursive_merge_sort(first, first + n, n); } @@ -82,8 +78,8 @@ void non_recursive_merge_sort(const Iterator first, const size_t n) { /** * @param first points to the first element * @param last points to 1-step past the last element -*/ -template + */ +template void non_recursive_merge_sort(const Iterator first, const Iterator last) { non_recursive_merge_sort(first, last, last - first); } @@ -92,15 +88,15 @@ void non_recursive_merge_sort(const Iterator first, const Iterator last) { * Currently, it only creates output for non_recursive_merge_sort.cpp, but if * it has proven its efficacy it can be expanded to other files. * The configuration file is named doxy.txt and has been auto-generated too. -*/ + */ // the remaining of this file is only for testing. It can erased to to convert // it into a header file for later re-use. #include -int main(int argc, char ** argv) { +int main(int argc, char** argv) { int size; std::cout << "Enter the number of elements : "; std::cin >> size; - int * arr = new int[size]; + int* arr = new int[size]; for (int i = 0; i < size; ++i) { std::cout << "arr[" << i << "] = "; std::cin >> arr[i]; diff --git a/sorting/numeric_string_sort.cpp b/sorting/numeric_string_sort.cpp new file mode 100644 index 00000000000..8b86bb29d51 --- /dev/null +++ b/sorting/numeric_string_sort.cpp @@ -0,0 +1,54 @@ +// Using general algorithms to sort a collection of strings results in +// alphanumeric sort. If it is a numeric string, it leads to unnatural sorting + +// eg, an array of strings 1,10,100,2,20,200,3,30,300 +// would be sorted in that same order by using conventional sorting, +// even though we know the correct sorting order is 1,2,3,10,20,30,100,200,300 + +// This Programme uses a comparator to sort the array in Numerical order instead +// of Alphanumeric order + +#include +#include +#include +#include + +bool NumericSort(std::string a, std::string b) { + while (a[0] == '0') { + a.erase(a.begin()); + } + while (b[0] == '0') { + b.erase(b.begin()); + } + int n = a.length(); + int m = b.length(); + if (n == m) return a < b; + return n < m; +} + +int main() { + int n; + std::cout << "Enter number of elements to be sorted Numerically\n"; + std::cin >> n; + + std::vector v(n); + std::cout << "Enter the string of Numbers\n"; + for (int i = 0; i < n; i++) { + std::cin >> v[i]; + } + + sort(v.begin(), v.end()); + std::cout << "Elements sorted normally \n"; + for (int i = 0; i < n; i++) { + std::cout << v[i] << " "; + } + std::cout << "\n"; + + std::sort(v.begin(), v.end(), NumericSort); + std::cout << "Elements sorted Numerically \n"; + for (int i = 0; i < n; i++) { + std::cout << v[i] << " "; + } + + return 0; +} diff --git a/sorting/OddEven Sort.cpp b/sorting/odd_even_sort.cpp similarity index 100% rename from sorting/OddEven Sort.cpp rename to sorting/odd_even_sort.cpp diff --git a/sorting/Quick Sort.cpp b/sorting/quick_sort.cpp similarity index 100% rename from sorting/Quick Sort.cpp rename to sorting/quick_sort.cpp diff --git a/sorting/Radix Sort.cpp b/sorting/radix_sort.cpp similarity index 100% rename from sorting/Radix Sort.cpp rename to sorting/radix_sort.cpp diff --git a/sorting/Selection Sort.cpp b/sorting/selection_sort.cpp similarity index 100% rename from sorting/Selection Sort.cpp rename to sorting/selection_sort.cpp diff --git a/sorting/Shell Sort.cpp b/sorting/shell_sort.cpp similarity index 100% rename from sorting/Shell Sort.cpp rename to sorting/shell_sort.cpp diff --git a/sorting/Slow Sort.cpp b/sorting/slow_sort.cpp similarity index 100% rename from sorting/Slow Sort.cpp rename to sorting/slow_sort.cpp diff --git a/sorting/Tim Sort.cpp b/sorting/tim_sort.cpp similarity index 100% rename from sorting/Tim Sort.cpp rename to sorting/tim_sort.cpp From b35a7875dacda7643df506968349f8841328551e Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 11:34:07 -0400 Subject: [PATCH 089/433] add CMAKE to sorting folder --- CMakeLists.txt | 1 + sorting/CMakeLists.txt | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+) create mode 100644 sorting/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index ab633b82742..f2940c9623d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -51,6 +51,7 @@ endif() add_subdirectory(math) add_subdirectory(others) add_subdirectory(strings) +add_subdirectory(sorting) add_subdirectory(computer_oriented_statistical_methods) if(USE_OPENMP) diff --git a/sorting/CMakeLists.txt b/sorting/CMakeLists.txt new file mode 100644 index 00000000000..9e76c8dec15 --- /dev/null +++ b/sorting/CMakeLists.txt @@ -0,0 +1,20 @@ +# 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 + CXX_STANDARD 14) + if(OpenMP_CXX_FOUND) + target_link_libraries(${testname} OpenMP::OpenMP_CXX) + endif() + install(TARGETS ${testname} DESTINATION "bin/strings") + +endforeach( testsourcefile ${APP_SOURCES} ) From 0941caf209b9b6ddbf8f1278bd809f02d4801905 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 26 May 2020 15:34:31 +0000 Subject: [PATCH 090/433] updating DIRECTORY.md --- DIRECTORY.md | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index 47842b9cad8..9a336c1a5b1 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -179,29 +179,29 @@ * [Ternary Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/ternary_search.cpp) ## Sorting - * [Beadsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/BeadSort.cpp) - * [Bitonicsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/BitonicSort.cpp) - * [Bubble Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Bubble%20Sort.cpp) - * [Bucketsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/bucketSort.cpp) - * [Cocktailselectionsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/CocktailSelectionSort.cpp) - * [Combsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/combsort.cpp) + * [Bead Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/bead_sort.cpp) + * [Bitonic Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/bitonic_sort.cpp) + * [Bubble Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/bubble_sort.cpp) + * [Bucket Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/bucket_sort.cpp) + * [Cocktail Selection Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/cocktail_selection_sort.cpp) + * [Comb Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/comb_sort.cpp) * [Counting Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Counting_Sort.cpp) - * [Countingsortstring](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/CountingSortString.cpp) + * [Counting Sort String](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/counting_sort_string.cpp) * [Heap Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/heap_sort.cpp) - * [Insertion Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Insertion%20Sort.cpp) + * [Insertion Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/insertion_sort.cpp) * [Library Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/library_sort.cpp) - * [Merge Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Merge%20Sort.cpp) + * [Merge Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/merge_sort.cpp) * [Non Recursive Merge Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/non_recursive_merge_sort.cpp) - * [Numericstringsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/NumericStringSort.cpp) - * [Oddeven Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/OddEven%20Sort.cpp) - * [Quick Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Quick%20Sort.cpp) - * [Radix Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Radix%20Sort.cpp) - * [Selection Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Selection%20Sort.cpp) - * [Shell Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Shell%20Sort.cpp) + * [Numeric String Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/numeric_string_sort.cpp) + * [Odd Even Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/odd_even_sort.cpp) + * [Quick Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/quick_sort.cpp) + * [Radix Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/radix_sort.cpp) + * [Selection Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/selection_sort.cpp) + * [Shell Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/shell_sort.cpp) * [Shell Sort2](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/shell_sort2.cpp) - * [Slow Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Slow%20Sort.cpp) + * [Slow Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/slow_sort.cpp) * [Swap Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/swap_sort.cpp) - * [Tim Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Tim%20Sort.cpp) + * [Tim Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/tim_sort.cpp) ## Strings * [Brute Force String Searching](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/strings/brute_force_string_searching.cpp) From 47cc3f6825733ae974044684e21f686bff74291c Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 11:37:04 -0400 Subject: [PATCH 091/433] fix sorting bin output foldername --- sorting/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sorting/CMakeLists.txt b/sorting/CMakeLists.txt index 9e76c8dec15..00877bb613a 100644 --- a/sorting/CMakeLists.txt +++ b/sorting/CMakeLists.txt @@ -15,6 +15,6 @@ foreach( testsourcefile ${APP_SOURCES} ) if(OpenMP_CXX_FOUND) target_link_libraries(${testname} OpenMP::OpenMP_CXX) endif() - install(TARGETS ${testname} DESTINATION "bin/strings") + install(TARGETS ${testname} DESTINATION "bin/sorting") endforeach( testsourcefile ${APP_SOURCES} ) From 76a5f572d5d9834585201836183027e3575b1e55 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 11:46:24 -0400 Subject: [PATCH 092/433] sorting fixes for MSVC and CPPLINT --- sorting/bead_sort.cpp | 5 ++-- sorting/bucket_sort.cpp | 51 ++++++++++++++++++----------------------- sorting/comb_sort.cpp | 47 +++++++++++++++---------------------- 3 files changed, 43 insertions(+), 60 deletions(-) diff --git a/sorting/bead_sort.cpp b/sorting/bead_sort.cpp index 12b7d4d3205..d3470607383 100644 --- a/sorting/bead_sort.cpp +++ b/sorting/bead_sort.cpp @@ -12,8 +12,8 @@ void beadSort(int *a, int len) { if (a[i] > max) max = a[i]; // allocating memory - unsigned char beads[max * len]; - memset(beads, 0, sizeof(beads)); + unsigned char *beads = new unsigned char[max * len]; + memset(beads, 0, max * len); // mark the beads for (int i = 0; i < len; i++) @@ -39,6 +39,7 @@ void beadSort(int *a, int len) { a[i] = j; } + delete[] beads; } // driver function to test the algorithm diff --git a/sorting/bucket_sort.cpp b/sorting/bucket_sort.cpp index 0ffbf8e4cb7..f120f04fc9c 100644 --- a/sorting/bucket_sort.cpp +++ b/sorting/bucket_sort.cpp @@ -1,42 +1,35 @@ // C++ program to sort an array using bucket sort -#include #include +#include #include -using namespace std; // Function to sort arr[] of size n using bucket sort -void bucketSort(float arr[], int n) -{ - // 1) Create n empty buckets - vector b[n]; +void bucketSort(float arr[], int n) { + // 1) Create n empty buckets + std::vector b[n]; - // 2) Put array elements in different buckets - for (int i = 0; i < n; i++) - { - int bi = n * arr[i]; // Index in bucket - b[bi].push_back(arr[i]); - } + // 2) Put array elements in different buckets + for (int i = 0; i < n; i++) { + int bi = n * arr[i]; // Index in bucket + b[bi].push_back(arr[i]); + } - // 3) Sort individual buckets - for (int i = 0; i < n; i++) - sort(b[i].begin(), b[i].end()); + // 3) Sort individual buckets + for (int i = 0; i < n; i++) std::sort(b[i].begin(), b[i].end()); - // 4) Concatenate all buckets into arr[] - int index = 0; - for (int i = 0; i < n; i++) - for (int j = 0; j < b[i].size(); j++) - arr[index++] = b[i][j]; + // 4) Concatenate all buckets into arr[] + int index = 0; + for (int i = 0; i < n; i++) + for (int j = 0; j < b[i].size(); j++) arr[index++] = b[i][j]; } /* Driver program to test above funtion */ -int main() -{ - float arr[] = {0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434}; - int n = sizeof(arr) / sizeof(arr[0]); - bucketSort(arr, n); +int main() { + float arr[] = {0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434}; + int n = sizeof(arr) / sizeof(arr[0]); + bucketSort(arr, n); - cout << "Sorted array is \n"; - for (int i = 0; i < n; i++) - cout << arr[i] << " "; - return 0; + std::cout << "Sorted array is \n"; + for (int i = 0; i < n; i++) std::cout << arr[i] << " "; + return 0; } diff --git a/sorting/comb_sort.cpp b/sorting/comb_sort.cpp index 2209c96fc55..feed4ba448b 100644 --- a/sorting/comb_sort.cpp +++ b/sorting/comb_sort.cpp @@ -1,59 +1,48 @@ -//Kind of better version of Bubble sort. -//While Bubble sort is comparering adjacent value, Combsort is using gap larger than 1 -//Best case: O(n) -//Worst case: O(n ^ 2) +// Kind of better version of Bubble sort. +// While Bubble sort is comparering adjacent value, Combsort is using gap larger +// than 1 Best case: O(n) Worst case: O(n ^ 2) #include -using namespace std; - int a[100005]; int n; -int FindNextGap(int x) -{ +int FindNextGap(int x) { x = (x * 10) / 13; - return max(1, x); + return std::max(1, x); } -void CombSort(int a[], int l, int r) -{ - //Init gap +void CombSort(int a[], int l, int r) { + // Init gap int gap = n; - //Initialize swapped as true to make sure that loop runs + // Initialize swapped as true to make sure that loop runs bool swapped = true; - //Keep running until gap = 1 or none elements were swapped - while (gap != 1 || swapped) - { - //Find next gap + // Keep running until gap = 1 or none elements were swapped + while (gap != 1 || swapped) { + // Find next gap gap = FindNextGap(gap); swapped = false; // Compare all elements with current gap - for (int i = l; i <= r - gap; ++i) - { - if (a[i] > a[i + gap]) - { - swap(a[i], a[i + gap]); + for (int i = l; i <= r - gap; ++i) { + if (a[i] > a[i + gap]) { + std::swap(a[i], a[i + gap]); swapped = true; } } } } -int main() -{ - cin >> n; - for (int i = 1; i <= n; ++i) - cin >> a[i]; +int main() { + std::cin >> n; + for (int i = 1; i <= n; ++i) std::cin >> a[i]; CombSort(a, 1, n); - for (int i = 1; i <= n; ++i) - cout << a[i] << ' '; + for (int i = 1; i <= n; ++i) std::cout << a[i] << ' '; return 0; } From 0d8e015d15b87ea188b75f1f70b7be614cdf86cd Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 12:15:12 -0400 Subject: [PATCH 093/433] cpplint and msvc fixes for - sorting --- sorting/bead_sort.cpp | 4 +-- sorting/bubble_sort.cpp | 8 +++--- sorting/cocktail_selection_sort.cpp | 44 ++++++++++++++--------------- 3 files changed, 28 insertions(+), 28 deletions(-) diff --git a/sorting/bead_sort.cpp b/sorting/bead_sort.cpp index d3470607383..a1a54c1e04a 100644 --- a/sorting/bead_sort.cpp +++ b/sorting/bead_sort.cpp @@ -34,8 +34,8 @@ void beadSort(int *a, int len) { // Put sorted values in array using beads for (int i = 0; i < len; i++) { int j; - for (j = 0; j < max && BEAD(i, j); j++) - ; + for (j = 0; j < max && BEAD(i, j); j++) { + } a[i] = j; } diff --git a/sorting/bubble_sort.cpp b/sorting/bubble_sort.cpp index 794f651983d..c43e425fcd9 100644 --- a/sorting/bubble_sort.cpp +++ b/sorting/bubble_sort.cpp @@ -42,7 +42,7 @@ optimized bubble sort algorithm. It's right down there. int main() { int n; - short swap_check = 1; + bool swap_check = true; std::cout << "Enter the amount of numbers to sort: "; std::cin >> n; std::vector numbers; @@ -56,11 +56,11 @@ int main() { } // Bubble Sorting - for (int i = 0; (i < n) && (swap_check == 1); i++) { - swap_check = 0; + for (int i = 0; (i < n) && (swap_check); i++) { + swap_check = false; for (int j = 0; j < n - 1 - i; j++) { if (numbers[j] > numbers[j + 1]) { - swap_check = 1; + swap_check = true; std::swap(numbers[j], numbers[j + 1]); // by changing swap location. // I mean, j. If the number is diff --git a/sorting/cocktail_selection_sort.cpp b/sorting/cocktail_selection_sort.cpp index a9abd86d535..ab622999687 100644 --- a/sorting/cocktail_selection_sort.cpp +++ b/sorting/cocktail_selection_sort.cpp @@ -9,28 +9,28 @@ // Iterative Version -void CocktailSelectionSort(std::vector &vec, int low, int high) { +void CocktailSelectionSort(std::vector *vec, int low, int high) { while (low <= high) { - int minimum = vec[low]; + int minimum = (*vec)[low]; int minimumindex = low; - int maximum = vec[high]; + int maximum = (*vec)[high]; int maximumindex = high; for (int i = low; i <= high; i++) { - if (vec[i] >= maximum) { - maximum = vec[i]; + if ((*vec)[i] >= maximum) { + maximum = (*vec)[i]; maximumindex = i; } - if (vec[i] <= minimum) { - minimum = vec[i]; + if ((*vec)[i] <= minimum) { + minimum = (*vec)[i]; minimumindex = i; } } if (low != maximumindex || high != minimumindex) { - std::swap(vec[low], vec[minimumindex]); - std::swap(vec[high], vec[maximumindex]); + std::swap((*vec)[low], (*vec)[minimumindex]); + std::swap((*vec)[high], (*vec)[maximumindex]); } else { - std::swap(vec[low], vec[high]); + std::swap((*vec)[low], (*vec)[high]); } low++; @@ -40,29 +40,29 @@ void CocktailSelectionSort(std::vector &vec, int low, int high) { // Recursive Version -void CocktailSelectionSort_v2(std::vector &vec, int low, int high) { +void CocktailSelectionSort_v2(std::vector *vec, int low, int high) { if (low >= high) return; - int minimum = vec[low]; + int minimum = (*vec)[low]; int minimumindex = low; - int maximum = vec[high]; + int maximum = (*vec)[high]; int maximumindex = high; for (int i = low; i <= high; i++) { - if (vec[i] >= maximum) { - maximum = vec[i]; + if ((*vec)[i] >= maximum) { + maximum = (*vec)[i]; maximumindex = i; } - if (vec[i] <= minimum) { - minimum = vec[i]; + if ((*vec)[i] <= minimum) { + minimum = (*vec)[i]; minimumindex = i; } } if (low != maximumindex || high != minimumindex) { - std::swap(vec[low], vec[minimumindex]); - std::swap(vec[high], vec[maximumindex]); + std::swap((*vec)[low], (*vec)[minimumindex]); + std::swap((*vec)[high], (*vec)[maximumindex]); } else { - std::swap(vec[low], vec[high]); + std::swap((*vec)[low], (*vec)[high]); } CocktailSelectionSort(vec, low + 1, high - 1); @@ -85,9 +85,9 @@ int main() { std::cin >> method; if (method == 0) { - CocktailSelectionSort(v, 0, n - 1); + CocktailSelectionSort(&v, 0, n - 1); } else if (method == 1) { - CocktailSelectionSort_v2(v, 0, n - 1); + CocktailSelectionSort_v2(&v, 0, n - 1); } else { std::cerr << "Unknown method" << std::endl; return -1; From 717f5c8f01c1d5559320e118ccc8eabdf602e8ff Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 12:31:49 -0400 Subject: [PATCH 094/433] fix dynamic array --- sorting/bucket_sort.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sorting/bucket_sort.cpp b/sorting/bucket_sort.cpp index f120f04fc9c..c43865281bc 100644 --- a/sorting/bucket_sort.cpp +++ b/sorting/bucket_sort.cpp @@ -6,7 +6,7 @@ // Function to sort arr[] of size n using bucket sort void bucketSort(float arr[], int n) { // 1) Create n empty buckets - std::vector b[n]; + std::vector *b = new std::vector[n]; // 2) Put array elements in different buckets for (int i = 0; i < n; i++) { @@ -21,6 +21,7 @@ void bucketSort(float arr[], int n) { int index = 0; for (int i = 0; i < n; i++) for (int j = 0; j < b[i].size(); j++) arr[index++] = b[i][j]; + delete[] b; } /* Driver program to test above funtion */ From 01b69fcb249c30d4f1795766bf4cc617d8200ab3 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 13:02:10 -0400 Subject: [PATCH 095/433] fix dynamic array issues in sorting folder --- sorting/comb_sort.cpp | 1 + sorting/insertion_sort.cpp | 62 ++++++++++---------- sorting/merge_sort.cpp | 66 +++++++++------------ sorting/quick_sort.cpp | 51 +++++++--------- sorting/radix_sort.cpp | 116 +++++++++++++++++-------------------- sorting/shell_sort.cpp | 72 ++++++++++------------- sorting/slow_sort.cpp | 82 +++++++++++++------------- sorting/swap_sort.cpp | 7 ++- sorting/tim_sort.cpp | 110 ++++++++++++++++------------------- 9 files changed, 256 insertions(+), 311 deletions(-) diff --git a/sorting/comb_sort.cpp b/sorting/comb_sort.cpp index feed4ba448b..1b0a4d70633 100644 --- a/sorting/comb_sort.cpp +++ b/sorting/comb_sort.cpp @@ -2,6 +2,7 @@ // While Bubble sort is comparering adjacent value, Combsort is using gap larger // than 1 Best case: O(n) Worst case: O(n ^ 2) +#include #include int a[100005]; diff --git a/sorting/insertion_sort.cpp b/sorting/insertion_sort.cpp index 2563acaf8f2..fe920ca5913 100644 --- a/sorting/insertion_sort.cpp +++ b/sorting/insertion_sort.cpp @@ -1,40 +1,36 @@ -//Insertion Sort +// Insertion Sort #include -using namespace std; -int main() -{ - int n; - cout << "\nEnter the length of your array : "; - cin >> n; - int Array[n]; - cout << "\nEnter any " << n << " Numbers for Unsorted Array : "; +int main() { + int n; + std::cout << "\nEnter the length of your array : "; + std::cin >> n; + int *Array = new int[n]; + std::cout << "\nEnter any " << n << " Numbers for Unsorted Array : "; - //Input - for (int i = 0; i < n; i++) - { - cin >> Array[i]; - } + // Input + for (int i = 0; i < n; i++) { + std::cin >> Array[i]; + } - //Sorting - for (int i = 1; i < n; i++) - { - int temp = Array[i]; - int j = i - 1; - while (j >= 0 && temp < Array[j]) - { - Array[j + 1] = Array[j]; - j--; - } - Array[j + 1] = temp; - } + // Sorting + for (int i = 1; i < n; i++) { + int temp = Array[i]; + int j = i - 1; + while (j >= 0 && temp < Array[j]) { + Array[j + 1] = Array[j]; + j--; + } + Array[j + 1] = temp; + } - //Output - cout << "\nSorted Array : "; - for (int i = 0; i < n; i++) - { - cout << Array[i] << "\t"; - } - return 0; + // Output + std::cout << "\nSorted Array : "; + for (int i = 0; i < n; i++) { + std::cout << Array[i] << "\t"; + } + + delete[] Array; + return 0; } diff --git a/sorting/merge_sort.cpp b/sorting/merge_sort.cpp index b8edc8851f4..82ab869cd2c 100644 --- a/sorting/merge_sort.cpp +++ b/sorting/merge_sort.cpp @@ -1,57 +1,47 @@ #include -using namespace std; -void merge(int arr[], int l, int m, int r) -{ +void merge(int arr[], int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; - int L[n1], R[n2]; + int *L = new int[n1], *R = new int[n2]; - for (i = 0; i < n1; i++) - L[i] = arr[l + i]; - for (j = 0; j < n2; j++) - R[j] = arr[m + 1 + j]; + for (i = 0; i < n1; i++) L[i] = arr[l + i]; + for (j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; i = 0; j = 0; k = l; - while (i < n1 && j < n2) - { - if (L[i] <= R[j]) - { + while (i < n1 && j < n2) { + if (L[i] <= R[j]) { arr[k] = L[i]; i++; - } - else - { + } else { arr[k] = R[j]; j++; } k++; } - while (i < n1) - { + while (i < n1) { arr[k] = L[i]; i++; k++; } - while (j < n2) - { + while (j < n2) { arr[k] = R[j]; j++; k++; } -} -void mergeSort(int arr[], int l, int r) -{ - if (l < r) - { + delete[] L; + delete[] R; +} +void mergeSort(int arr[], int l, int r) { + if (l < r) { int m = l + (r - l) / 2; mergeSort(arr, l, m); @@ -61,33 +51,31 @@ void mergeSort(int arr[], int l, int r) } } -void show(int A[], int size) -{ +void show(int A[], int size) { int i; - for (i = 0; i < size; i++) - cout << A[i] << "\n"; + for (i = 0; i < size; i++) std::cout << A[i] << "\n"; } -int main() -{ +int main() { int size; - cout << "\nEnter the number of elements : "; + std::cout << "\nEnter the number of elements : "; - cin >> size; + std::cin >> size; - int arr[size]; + int *arr = new int[size]; - cout << "\nEnter the unsorted elements : "; + std::cout << "\nEnter the unsorted elements : "; - for (int i = 0; i < size; ++i) - { - cout << "\n"; - cin >> arr[i]; + for (int i = 0; i < size; ++i) { + std::cout << "\n"; + std::cin >> arr[i]; } mergeSort(arr, 0, size); - cout << "Sorted array\n"; + std::cout << "Sorted array\n"; show(arr, size); + + delete[] arr; return 0; } diff --git a/sorting/quick_sort.cpp b/sorting/quick_sort.cpp index 0b807898fb3..489e1096549 100644 --- a/sorting/quick_sort.cpp +++ b/sorting/quick_sort.cpp @@ -1,19 +1,15 @@ /* C implementation QuickSort */ #include -using namespace std; -int partition(int arr[], int low, int high) -{ - int pivot = arr[high]; // pivot - int i = (low - 1); // Index of smaller element +int partition(int arr[], int low, int high) { + int pivot = arr[high]; // pivot + int i = (low - 1); // Index of smaller element - for (int j = low; j < high; j++) - { + for (int j = low; j < high; j++) { // If current element is smaller than or // equal to pivot - if (arr[j] <= pivot) - { - i++; // increment index of smaller element + if (arr[j] <= pivot) { + i++; // increment index of smaller element int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; @@ -25,11 +21,8 @@ int partition(int arr[], int low, int high) return (i + 1); } -void quickSort(int arr[], int low, int high) -{ - if (low < high) - { - +void quickSort(int arr[], int low, int high) { + if (low < high) { int p = partition(arr, low, high); quickSort(arr, low, p - 1); @@ -37,31 +30,29 @@ void quickSort(int arr[], int low, int high) } } -void show(int arr[], int size) -{ - for (int i = 0; i < size; i++) - cout << arr[i] << "\n"; +void show(int arr[], int size) { + for (int i = 0; i < size; i++) std::cout << arr[i] << "\n"; } // Driver program to test above functions -int main() -{ +int main() { int size; - cout << "\nEnter the number of elements : "; + std::cout << "\nEnter the number of elements : "; - cin >> size; + std::cin >> size; - int arr[size]; + int *arr = new int[size]; - cout << "\nEnter the unsorted elements : "; + std::cout << "\nEnter the unsorted elements : "; - for (int i = 0; i < size; ++i) - { - cout << "\n"; - cin >> arr[i]; + for (int i = 0; i < size; ++i) { + std::cout << "\n"; + std::cin >> arr[i]; } quickSort(arr, 0, size); - cout << "Sorted array\n"; + std::cout << "Sorted array\n"; show(arr, size); + + delete[] arr; return 0; } diff --git a/sorting/radix_sort.cpp b/sorting/radix_sort.cpp index 09c91bb2248..e5bc3db8427 100644 --- a/sorting/radix_sort.cpp +++ b/sorting/radix_sort.cpp @@ -1,68 +1,58 @@ -#include -#include #include +#include #include -using namespace std; -void radixsort(int a[], int n) -{ - int count[10]; - int output[n]; - memset(output, 0, sizeof(output)); - memset(count, 0, sizeof(count)); - int max = 0; - for (int i = 0; i < n; ++i) - { - if (a[i] > max) - { - max = a[i]; - } - } - int maxdigits = 0; - while (max) - { - maxdigits++; - max /= 10; - } - for (int j = 0; j < maxdigits; j++) - { - for (int i = 0; i < n; i++) - { - int t = pow(10, j); - count[(a[i] % (10 * t)) / t]++; - } - int k = 0; - for (int p = 0; p < 10; p++) - { - for (int i = 0; i < n; i++) - { - int t = pow(10, j); - if ((a[i] % (10 * t)) / t == p) - { - output[k] = a[i]; - k++; - } - } - } - memset(count, 0, sizeof(count)); - for (int i = 0; i < n; ++i) - { - a[i] = output[i]; - } - } +#include + +void radixsort(int a[], int n) { + int count[10]; + int* output = new int[n]; + memset(output, 0, n * sizeof(*output)); + memset(count, 0, sizeof(count)); + int max = 0; + for (int i = 0; i < n; ++i) { + if (a[i] > max) { + max = a[i]; + } + } + int maxdigits = 0; + while (max) { + maxdigits++; + max /= 10; + } + for (int j = 0; j < maxdigits; j++) { + for (int i = 0; i < n; i++) { + int t = std::pow(10, j); + count[(a[i] % (10 * t)) / t]++; + } + int k = 0; + for (int p = 0; p < 10; p++) { + for (int i = 0; i < n; i++) { + int t = std::pow(10, j); + if ((a[i] % (10 * t)) / t == p) { + output[k] = a[i]; + k++; + } + } + } + memset(count, 0, sizeof(count)); + for (int i = 0; i < n; ++i) { + a[i] = output[i]; + } + } + delete[] output; } -void print(int a[], int n) -{ - for (int i = 0; i < n; ++i) - { - cout << a[i] << " "; - } - cout << endl; + +void print(int a[], int n) { + for (int i = 0; i < n; ++i) { + std::cout << a[i] << " "; + } + std::cout << std::endl; } -int main(int argc, char const *argv[]) -{ - int a[] = {170, 45, 75, 90, 802, 24, 2, 66}; - int n = sizeof(a) / sizeof(a[0]); - radixsort(a, n); - print(a, n); - return 0; + +int main(int argc, char const* argv[]) { + int a[] = {170, 45, 75, 90, 802, 24, 2, 66}; + int n = sizeof(a) / sizeof(a[0]); + radixsort(a, n); + print(a, n); + return 0; } \ No newline at end of file diff --git a/sorting/shell_sort.cpp b/sorting/shell_sort.cpp index b08c7ffd826..eb701478d4e 100644 --- a/sorting/shell_sort.cpp +++ b/sorting/shell_sort.cpp @@ -1,45 +1,37 @@ #include -using namespace std; -int main() -{ - int size = 10; - int array[size]; - // Input - cout << "\nHow many numbers do want to enter in unsorted array : "; - cin >> size; - cout << "\nEnter the numbers for unsorted array : "; - for (int i = 0; i < size; i++) - { - cin >> array[i]; - } +int main() { + int size = 10; + int* array = new int[size]; + // Input + std::cout << "\nHow many numbers do want to enter in unsorted array : "; + std::cin >> size; + std::cout << "\nEnter the numbers for unsorted array : "; + for (int i = 0; i < size; i++) { + std::cin >> array[i]; + } - // Sorting - for (int i = size / 2; i > 0; i = i / 2) - { - for (int j = i; j < size; j++) - { - for (int k = j - i; k >= 0; k = k - i) - { - if (array[k] < array[k + i]) - { - break; - } - else - { - int temp = array[k + i]; - array[k + i] = array[k]; - array[k] = temp; - } - } - } - } + // Sorting + for (int i = size / 2; i > 0; i = i / 2) { + for (int j = i; j < size; j++) { + for (int k = j - i; k >= 0; k = k - i) { + if (array[k] < array[k + i]) { + break; + } else { + int temp = array[k + i]; + array[k + i] = array[k]; + array[k] = temp; + } + } + } + } - // Output - cout << "\nSorted array : "; - for (int i = 0; i < size; ++i) - { - cout << array[i] << "\t"; - } - return 0; + // Output + std::cout << "\nSorted array : "; + for (int i = 0; i < size; ++i) { + std::cout << array[i] << "\t"; + } + + delete[] array; + return 0; } diff --git a/sorting/slow_sort.cpp b/sorting/slow_sort.cpp index f8f7e74b804..2872b37d88c 100644 --- a/sorting/slow_sort.cpp +++ b/sorting/slow_sort.cpp @@ -1,57 +1,55 @@ -//Returns the sorted vector after performing SlowSort -//It is a sorting algorithm that is of humorous nature and not useful. -//It's based on the principle of multiply and surrender, a tongue-in-cheek joke of divide and conquer. -//It was published in 1986 by Andrei Broder and Jorge Stolfi in their paper Pessimal Algorithms and Simplexity Analysis. -//This algorithm multiplies a single problem into multiple subproblems -//It is interesting because it is provably the least efficient sorting algorithm that can be built asymptotically, -//and with the restriction that such an algorithm, while being slow, must still all the time be working towards a result. +// Returns the sorted vector after performing SlowSort +// It is a sorting algorithm that is of humorous nature and not useful. +// It's based on the principle of multiply and surrender, a tongue-in-cheek joke +// of divide and conquer. It was published in 1986 by Andrei Broder and Jorge +// Stolfi in their paper Pessimal Algorithms and Simplexity Analysis. This +// algorithm multiplies a single problem into multiple subproblems It is +// interesting because it is provably the least efficient sorting algorithm that +// can be built asymptotically, and with the restriction that such an algorithm, +// while being slow, must still all the time be working towards a result. #include using namespace std; -void SlowSort(int a[], int i, int j) -{ - if (i >= j) - return; - int m = i + (j - i) / 2; //midpoint, implemented this way to avoid overflow - int temp; - SlowSort(a, i, m); - SlowSort(a, m + 1, j); - if (a[j] < a[m]) - { - temp = a[j]; //swapping a[j] & a[m] - a[j] = a[m]; - a[m] = temp; - } - SlowSort(a, i, j - 1); +void SlowSort(int a[], int i, int j) { + if (i >= j) return; + int m = i + (j - i) / 2; // midpoint, implemented this way to avoid + // overflow + int temp; + SlowSort(a, i, m); + SlowSort(a, m + 1, j); + if (a[j] < a[m]) { + temp = a[j]; // swapping a[j] & a[m] + a[j] = a[m]; + a[m] = temp; + } + SlowSort(a, i, j - 1); } -//Sample Main function +// Sample Main function -int main() -{ - int size; - cout << "\nEnter the number of elements : "; +int main() { + int size; + cout << "\nEnter the number of elements : "; - cin >> size; + cin >> size; - int arr[size]; + int *arr = new int[size]; - cout << "\nEnter the unsorted elements : "; + cout << "\nEnter the unsorted elements : "; - for (int i = 0; i < size; ++i) - { - cout << "\n"; - cin >> arr[i]; - } + for (int i = 0; i < size; ++i) { + cout << "\n"; + cin >> arr[i]; + } - SlowSort(arr, 0, size); + SlowSort(arr, 0, size); - cout << "Sorted array\n"; + cout << "Sorted array\n"; - for (int i = 0; i < size; ++i) - { - cout << arr[i] << " "; - } - return 0; + for (int i = 0; i < size; ++i) { + cout << arr[i] << " "; + } + delete[] arr; + return 0; } diff --git a/sorting/swap_sort.cpp b/sorting/swap_sort.cpp index a4ab1e57b66..2e59e2fb3bf 100644 --- a/sorting/swap_sort.cpp +++ b/sorting/swap_sort.cpp @@ -10,7 +10,7 @@ int minSwaps(int arr[], int n) { // Create an array of pairs where first // element is array element and second element // is position of first element - std::pair arrPos[n]; + std::pair *arrPos = new std::pair[n]; for (int i = 0; i < n; i++) { arrPos[i].first = arr[i]; arrPos[i].second = i; @@ -32,8 +32,7 @@ int minSwaps(int arr[], int n) { for (int i = 0; i < n; i++) { // already swapped and corrected or // already present at correct pos - if (vis[i] || arrPos[i].second == i) - continue; + if (vis[i] || arrPos[i].second == i) continue; // find out the number of node in // this cycle and add in ans @@ -53,6 +52,8 @@ int minSwaps(int arr[], int n) { } } + delete[] arrPos; + // Return result return ans; } diff --git a/sorting/tim_sort.cpp b/sorting/tim_sort.cpp index 14d3a04d049..94f5aa230b3 100644 --- a/sorting/tim_sort.cpp +++ b/sorting/tim_sort.cpp @@ -1,115 +1,103 @@ // C++ program to perform TimSort. +#include #include -using namespace std; + const int RUN = 32; - -// this function sorts array from left index to to right index which is of size atmost RUN -void insertionSort(int arr[], int left, int right) -{ - for (int i = left + 1; i <= right; i++) - { + +// this function sorts array from left index to to right index which is of size +// atmost RUN +void insertionSort(int arr[], int left, int right) { + for (int i = left + 1; i <= right; i++) { int temp = arr[i]; int j = i - 1; - while (arr[j] > temp && j >= left) - { - arr[j+1] = arr[j]; + while (arr[j] > temp && j >= left) { + arr[j + 1] = arr[j]; j--; } - arr[j+1] = temp; + arr[j + 1] = temp; } } - + // merge function merges the sorted runs -void merge(int arr[], int l, int m, int r) -{ +void merge(int arr[], int l, int m, int r) { // original array is broken in two parts, left and right array int len1 = m - l + 1, len2 = r - m; - int left[len1], right[len2]; - for (int i = 0; i < len1; i++) - left[i] = arr[l + i]; - for (int i = 0; i < len2; i++) - right[i] = arr[m + 1 + i]; - + int *left = new int[len1], *right = new int[len2]; + for (int i = 0; i < len1; i++) left[i] = arr[l + i]; + for (int i = 0; i < len2; i++) right[i] = arr[m + 1 + i]; + int i = 0; int j = 0; int k = l; - + // after comparing, we merge those two array in larger sub array - while (i < len1 && j < len2) - { - if (left[i] <= right[j]) - { + while (i < len1 && j < len2) { + if (left[i] <= right[j]) { arr[k] = left[i]; i++; - } - else - { + } else { arr[k] = right[j]; j++; } k++; } - + // copy remaining elements of left, if any - while (i < len1) - { + while (i < len1) { arr[k] = left[i]; k++; i++; } - + // copy remaining element of right, if any - while (j < len2) - { + while (j < len2) { arr[k] = right[j]; k++; j++; } + delete[] left; + delete[] right; } - + // iterative Timsort function to sort the array[0...n-1] (similar to merge sort) -void timSort(int arr[], int n) -{ +void timSort(int arr[], int n) { // Sort individual subarrays of size RUN - for (int i = 0; i < n; i+=RUN) - insertionSort(arr, i, min((i+31), (n-1))); - - // start merging from size RUN (or 32). It will merge to form size 64, then 128, 256 and so on .... - for (int size = RUN; size < n; size = 2*size) - { - // pick starting point of left sub array. We are going to merge arr[left..left+size-1] and arr[left+size, left+2*size-1] - // After every merge, we increase left by 2*size - for (int left = 0; left < n; left += 2*size) - { + for (int i = 0; i < n; i += RUN) + insertionSort(arr, i, std::min((i + 31), (n - 1))); + + // start merging from size RUN (or 32). It will merge to form size 64, then + // 128, 256 and so on .... + for (int size = RUN; size < n; size = 2 * size) { + // pick starting point of left sub array. We are going to merge + // arr[left..left+size-1] and arr[left+size, left+2*size-1] After every + // merge, we increase left by 2*size + for (int left = 0; left < n; left += 2 * size) { // find ending point of left sub array // mid+1 is starting point of right sub array int mid = left + size - 1; - int right = min((left + 2*size - 1), (n-1)); - + int right = std::min((left + 2 * size - 1), (n - 1)); + // merge sub array arr[left.....mid] & arr[mid+1....right] merge(arr, left, mid, right); } } } - + // utility function to print the Array -void printArray(int arr[], int n) -{ - for (int i = 0; i < n; i++) - printf("%d ", arr[i]); - printf("\n"); +void printArray(int arr[], int n) { + for (int i = 0; i < n; i++) printf("%d ", arr[i]); + std::cout << std::endl; } - + // Driver program to test above function -int main() -{ +int main() { int arr[] = {5, 21, 7, 23, 19}; - int n = sizeof(arr)/sizeof(arr[0]); + int n = sizeof(arr) / sizeof(arr[0]); printf("Given Array is\n"); printArray(arr, n); - + timSort(arr, n); - + printf("After Sorting Array is\n"); printArray(arr, n); return 0; From 35c53760d34bc483ba737706937985346bf39fd8 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 13:07:14 -0400 Subject: [PATCH 096/433] cpplint issues fixed in sorting folder --- sorting/radix_sort.cpp | 2 +- sorting/slow_sort.cpp | 16 ++++++++-------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/sorting/radix_sort.cpp b/sorting/radix_sort.cpp index e5bc3db8427..a0fbfe99ee5 100644 --- a/sorting/radix_sort.cpp +++ b/sorting/radix_sort.cpp @@ -55,4 +55,4 @@ int main(int argc, char const* argv[]) { radixsort(a, n); print(a, n); return 0; -} \ No newline at end of file +} diff --git a/sorting/slow_sort.cpp b/sorting/slow_sort.cpp index 2872b37d88c..b2627d12f3a 100644 --- a/sorting/slow_sort.cpp +++ b/sorting/slow_sort.cpp @@ -9,7 +9,6 @@ // while being slow, must still all the time be working towards a result. #include -using namespace std; void SlowSort(int a[], int i, int j) { if (i >= j) return; @@ -30,26 +29,27 @@ void SlowSort(int a[], int i, int j) { int main() { int size; - cout << "\nEnter the number of elements : "; + std::cout << "\nEnter the number of elements : "; - cin >> size; + std::cin >> size; int *arr = new int[size]; - cout << "\nEnter the unsorted elements : "; + std::cout << "\nEnter the unsorted elements : "; for (int i = 0; i < size; ++i) { - cout << "\n"; - cin >> arr[i]; + std::cout << "\n"; + std::cin >> arr[i]; } SlowSort(arr, 0, size); - cout << "Sorted array\n"; + std::cout << "Sorted array\n"; for (int i = 0; i < size; ++i) { - cout << arr[i] << " "; + std::cout << arr[i] << " "; } + delete[] arr; return 0; } From 7e3d87695f7341ab60059ce8988310fa06249b06 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 13:07:30 -0400 Subject: [PATCH 097/433] remove redundant github action --- .../sorting_non_recursive_merge_sort.yml | 24 ------------------- 1 file changed, 24 deletions(-) delete mode 100644 .github/workflows/sorting_non_recursive_merge_sort.yml diff --git a/.github/workflows/sorting_non_recursive_merge_sort.yml b/.github/workflows/sorting_non_recursive_merge_sort.yml deleted file mode 100644 index add9efd5d67..00000000000 --- a/.github/workflows/sorting_non_recursive_merge_sort.yml +++ /dev/null @@ -1,24 +0,0 @@ -name: sorting_non_recursive_merge_sort -on: - pull_request: - push: - # branches: [master] -jobs: - sorting_non_recursive_merge_sort: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@master - - uses: mattnotmitt/doxygen-action@master - with: - working-directory: 'sorting/' - doxyfile-path: 'doxy.txt' - #- uses: peaceiris/actions-gh-pages@v3 - # with: - # github_token: ${{ secrets.GITHUB_TOKEN }} - # publish_dir: ./sorting - # external_repository: TheAlgorithms/C-Plus-Plus - # publish_branch: master - # enable_jekyll: true - - run: | - cd sorting - make test From 966aa2d333123fa124f52d02fc2f3d37261fe923 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 13:28:12 -0400 Subject: [PATCH 098/433] remove mainpage doxygen tag --- sorting/non_recursive_merge_sort.cpp | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/sorting/non_recursive_merge_sort.cpp b/sorting/non_recursive_merge_sort.cpp index ebfef1dcc50..9d4e95f2fdd 100644 --- a/sorting/non_recursive_merge_sort.cpp +++ b/sorting/non_recursive_merge_sort.cpp @@ -5,7 +5,9 @@ * A generic implementation of non-recursive merge sort. */ #include // for size_t +#include #include // for std::move & std::remove_reference_t + template void merge(Iterator, Iterator, const Iterator, char[]); /// bottom-up merge sort which sorts elements in a non-decreasing order @@ -83,15 +85,7 @@ template void non_recursive_merge_sort(const Iterator first, const Iterator last) { non_recursive_merge_sort(first, last, last - first); } -/** - * @mainpage A demonstration of auto-generated documentation using Doxygen. - * Currently, it only creates output for non_recursive_merge_sort.cpp, but if - * it has proven its efficacy it can be expanded to other files. - * The configuration file is named doxy.txt and has been auto-generated too. - */ -// the remaining of this file is only for testing. It can erased to to convert -// it into a header file for later re-use. -#include + int main(int argc, char** argv) { int size; std::cout << "Enter the number of elements : "; From a2e7d9099944588e3e0ab5ce04ec40ac13991982 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 13:28:33 -0400 Subject: [PATCH 099/433] add mainpage tag to README in the root folder --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e8034d7c4d9..4befc6afa7f 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# The Algorithms - C++ +# The Algorithms - C++ # {#mainpage} [![contributions welcome](https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square)](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTION.md)  ![GitHub repo size](https://img.shields.io/github/repo-size/TheAlgorithms/C-Plus-Plus?color=red&style=flat-square) ![GitHub closed pull requests](https://img.shields.io/github/issues-pr-closed/TheAlgorithms/C-Plus-Plus?color=green&style=flat-square) From e4084e77a81a4124ad58b294cc2618cb917ec59e Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 11:33:57 -0400 Subject: [PATCH 100/433] fix CPPLINT in sorting folder (cherry picked from commit 7efa52e0672749b9915d8af03545f66fd6d5848e) --- sorting/BeadSort.cpp | 63 --- sorting/BitonicSort.cpp | 76 ---- sorting/Bubble Sort.cpp | 83 ---- sorting/CocktailSelectionSort.cpp | 109 ----- sorting/NumericStringSort.cpp | 62 --- sorting/bead_sort.cpp | 54 +++ sorting/bitonic_sort.cpp | 63 +++ sorting/bubble_sort.cpp | 83 ++++ sorting/{bucketSort.cpp => bucket_sort.cpp} | 0 sorting/cocktail_selection_sort.cpp | 101 +++++ sorting/{combsort.cpp => comb_sort.cpp} | 0 ...ortString.cpp => counting_sort_string.cpp} | 0 sorting/doxy.txt | 374 ------------------ ...{Insertion Sort.cpp => insertion_sort.cpp} | 0 sorting/makefile | 11 - sorting/{Merge Sort.cpp => merge_sort.cpp} | 0 sorting/non_recursive_merge_sort.cpp | 38 +- sorting/numeric_string_sort.cpp | 54 +++ .../{OddEven Sort.cpp => odd_even_sort.cpp} | 0 sorting/{Quick Sort.cpp => quick_sort.cpp} | 0 sorting/{Radix Sort.cpp => radix_sort.cpp} | 0 ...{Selection Sort.cpp => selection_sort.cpp} | 0 sorting/{Shell Sort.cpp => shell_sort.cpp} | 0 sorting/{Slow Sort.cpp => slow_sort.cpp} | 0 sorting/{Tim Sort.cpp => tim_sort.cpp} | 0 25 files changed, 372 insertions(+), 799 deletions(-) delete mode 100644 sorting/BeadSort.cpp delete mode 100644 sorting/BitonicSort.cpp delete mode 100644 sorting/Bubble Sort.cpp delete mode 100644 sorting/CocktailSelectionSort.cpp delete mode 100644 sorting/NumericStringSort.cpp create mode 100644 sorting/bead_sort.cpp create mode 100644 sorting/bitonic_sort.cpp create mode 100644 sorting/bubble_sort.cpp rename sorting/{bucketSort.cpp => bucket_sort.cpp} (100%) create mode 100644 sorting/cocktail_selection_sort.cpp rename sorting/{combsort.cpp => comb_sort.cpp} (100%) rename sorting/{CountingSortString.cpp => counting_sort_string.cpp} (100%) delete mode 100644 sorting/doxy.txt rename sorting/{Insertion Sort.cpp => insertion_sort.cpp} (100%) delete mode 100644 sorting/makefile rename sorting/{Merge Sort.cpp => merge_sort.cpp} (100%) create mode 100644 sorting/numeric_string_sort.cpp rename sorting/{OddEven Sort.cpp => odd_even_sort.cpp} (100%) rename sorting/{Quick Sort.cpp => quick_sort.cpp} (100%) rename sorting/{Radix Sort.cpp => radix_sort.cpp} (100%) rename sorting/{Selection Sort.cpp => selection_sort.cpp} (100%) rename sorting/{Shell Sort.cpp => shell_sort.cpp} (100%) rename sorting/{Slow Sort.cpp => slow_sort.cpp} (100%) rename sorting/{Tim Sort.cpp => tim_sort.cpp} (100%) diff --git a/sorting/BeadSort.cpp b/sorting/BeadSort.cpp deleted file mode 100644 index c8e27b2507e..00000000000 --- a/sorting/BeadSort.cpp +++ /dev/null @@ -1,63 +0,0 @@ -// C++ program to implement gravity/bead sort -#include -#include -using namespace std; - -#define BEAD(i, j) beads[i * max + j] - -// function to perform the above algorithm -void beadSort(int *a, int len) -{ - // Find the maximum element - int max = a[0]; - for (int i = 1; i < len; i++) - if (a[i] > max) - max = a[i]; - - // allocating memory - unsigned char beads[max*len]; - memset(beads, 0, sizeof(beads)); - - // mark the beads - for (int i = 0; i < len; i++) - for (int j = 0; j < a[i]; j++) - BEAD(i, j) = 1; - - for (int j = 0; j < max; j++) - { - // count how many beads are on each post - int sum = 0; - for (int i=0; i < len; i++) - { - sum += BEAD(i, j); - BEAD(i, j) = 0; - } - - // Move beads down - for (int i = len - sum; i < len; i++) - BEAD(i, j) = 1; - } - - // Put sorted values in array using beads - for (int i = 0; i < len; i++) - { - int j; - for (j = 0; j < max && BEAD(i, j); j++); - - a[i] = j; - } -} - -// driver function to test the algorithm -int main() -{ - int a[] = {5, 3, 1, 7, 4, 1, 1, 20}; - int len = sizeof(a)/sizeof(a[0]); - - beadSort(a, len); - - for (int i = 0; i < len; i++) - printf("%d ", a[i]); - - return 0; -} diff --git a/sorting/BitonicSort.cpp b/sorting/BitonicSort.cpp deleted file mode 100644 index 6ad2489d229..00000000000 --- a/sorting/BitonicSort.cpp +++ /dev/null @@ -1,76 +0,0 @@ -// Source : https://www.geeksforgeeks.org/bitonic-sort/ - -/* C++ Program for Bitonic Sort. Note that this program - works only when size of input is a power of 2. */ - -#include -#include -using namespace std; - -/*The parameter dir indicates the sorting direction, ASCENDING - or DESCENDING; if (a[i] > a[j]) agrees with the direction, - then a[i] and a[j] are interchanged.*/ -void compAndSwap(int a[], int i, int j, int dir) -{ - if (dir == (a[i] > a[j])) - swap(a[i], a[j]); -} - -/*It recursively sorts a bitonic sequence in ascending order, - if dir = 1, and in descending order otherwise (means dir=0). - The sequence to be sorted starts at index position low, - the parameter cnt is the number of elements to be sorted.*/ -void bitonicMerge(int a[], int low, int cnt, int dir) -{ - if (cnt > 1) - { - int k = cnt / 2; - for (int i = low; i < low + k; i++) - compAndSwap(a, i, i + k, dir); - bitonicMerge(a, low, k, dir); - bitonicMerge(a, low + k, k, dir); - } -} - -/* This function first produces a bitonic sequence by recursively - sorting its two halves in opposite sorting orders, and then - calls bitonicMerge to make them in the same order */ -void bitonicSort(int a[], int low, int cnt, int dir) -{ - if (cnt > 1) - { - int k = cnt / 2; - - // sort in ascending order since dir here is 1 - bitonicSort(a, low, k, 1); - - // sort in descending order since dir here is 0 - bitonicSort(a, low + k, k, 0); - - // Will merge wole sequence in ascending order - // since dir=1. - bitonicMerge(a, low, cnt, dir); - } -} - -/* Caller of bitonicSort for sorting the entire array of - length N in ASCENDING order */ -void sort(int a[], int N, int up) -{ - bitonicSort(a, 0, N, up); -} - -// Driver code -int main() -{ - int a[] = {3, 7, 4, 8, 6, 2, 1, 5}; - int N = sizeof(a) / sizeof(a[0]); - - int up = 1; // means sort in ascending order - sort(a, N, up); - - printf("Sorted array: \n"); - for (int i = 0; i < N; i++) - printf("%d ", a[i]); - return 0; -} diff --git a/sorting/Bubble Sort.cpp b/sorting/Bubble Sort.cpp deleted file mode 100644 index b160ac4790a..00000000000 --- a/sorting/Bubble Sort.cpp +++ /dev/null @@ -1,83 +0,0 @@ -//Bubble Sort - -#include -#include -using namespace std; - -int main() -{ - int n; - short swap_check = 1; - cout << "Enter the amount of numbers to sort: "; - cin >> n; - vector numbers; - cout << "Enter " << n << " numbers: "; - int num; - - //Input - for (int i = 0; i < n; i++) - { - cin >> num; - numbers.push_back(num); - } - - //Bubble Sorting - for (int i = 0; (i < n) && (swap_check == 1); i++) - { - swap_check = 0; - for (int j = 0; j < n - 1 - i; j++) - { - if (numbers[j] > numbers[j + 1]) - { - swap_check = 1; - swap(numbers[j], numbers[j + 1]);// by changing swap location. I mean, j. If the number is greater than j + 1, then it means the location. - } - } - } - - //Output - cout << "\nSorted Array : "; - for (int i = 0; i < numbers.size(); i++) - { - if (i != numbers.size() - 1) - { - cout << numbers[i] << ", "; - } - else - { - cout << numbers[i] << endl; - } - } - return 0; -} - -/*The working principle of the Bubble sort algorithm: - -Bubble sort algorithm is the bubble sorting algorithm. The most important reason for calling the bubble is that the largest number is thrown at the end of this algorithm. -This is all about the logic. -In each iteration, the largest number is expired and when iterations are completed, the sorting takes place. - -What is Swap? - -Swap in the software means that two variables are displaced. -An additional variable is required for this operation. x = 5, y = 10. -We want x = 10, y = 5. Here we create the most variable to do it. - -int z; -z = x; -x = y; -y = z; - -The above process is a typical displacement process. -When x assigns the value to x, the old value of x is lost. -That's why we created a variable z to create the first value of the value of x, and finally, we have assigned to y. - -Bubble Sort Algorithm Analysis (Best Case - Worst Case - Average Case) - -Bubble Sort Worst Case Performance is O (n²). Why is that? Because if you remember Big O Notation, we were calculating the complexity of the algorithms in the nested loops. -The n * (n - 1) product gives us O (n²) performance. In the worst case all the steps of the cycle will occur. -Bubble Sort (Avarage Case) Performance. Bubble Sort is not an optimal algorithm. -in average, O (n²) performance is taken. -Bubble Sort Best Case Performance. O (n). -However, you can't get the best status in the code we shared above. This happens on the optimized bubble sort algorithm. It's right down there. -* / diff --git a/sorting/CocktailSelectionSort.cpp b/sorting/CocktailSelectionSort.cpp deleted file mode 100644 index cac6a361871..00000000000 --- a/sorting/CocktailSelectionSort.cpp +++ /dev/null @@ -1,109 +0,0 @@ -//Returns Sorted elements after performing Cocktail Selection Sort -//It is a Sorting algorithm which chooses the minimum and maximum element in an array simultaneously, -//and swaps it with the lowest and highest available position iteratively or recursively - -#include -using namespace std; - -//Iterative Version - -void CocktailSelectionSort(vector &vec, int low, int high) -{ - while (low <= high) - { - int minimum = vec[low]; - int minimumindex = low; - int maximum = vec[high]; - int maximumindex = high; - - for (int i = low; i <= high; i++) - { - if (vec[i] >= maximum) - { - maximum = vec[i]; - maximumindex = i; - } - if (vec[i] <= minimum) - { - minimum = vec[i]; - minimumindex = i; - } - } - if (low != maximumindex || high != minimumindex) - { - swap(vec[low], vec[minimumindex]); - swap(vec[high], vec[maximumindex]); - } - else - { - swap(vec[low], vec[high]); - } - - low++; - high--; - } -} - -//Recursive Version - -void CocktailSelectionSort(vector &vec, int low, int high) -{ - - if (low >= high) - return; - - int minimum = vec[low]; - int minimumindex = low; - int maximum = vec[high]; - int maximumindex = high; - - for (int i = low; i <= high; i++) - { - if (vec[i] >= maximum) - { - maximum = vec[i]; - maximumindex = i; - } - if (vec[i] <= minimum) - { - minimum = vec[i]; - minimumindex = i; - } - } - if (low != maximumindex || high != minimumindex) - { - swap(vec[low], vec[minimumindex]); - swap(vec[high], vec[maximumindex]); - } - else - { - swap(vec[low], vec[high]); - } - - CocktailSelectionSort(vec, low + 1, high - 1); -} - -//main function, select any one of iterative or recursive version - -int main() -{ - - int n; - cout << "Enter number of elements\n"; - cin >> n; - std::vector v(n); - cout << "Enter all the elements\n"; - for (int i = 0; i < n; ++i) - { - cin >> v[i]; - } - - CocktailSelectionSort(v, 0, n - 1); - cout << "Sorted elements are\n"; - for (int i = 0; i < n; ++i) - { - cout << v[i] << " "; - } - - return 0; -} diff --git a/sorting/NumericStringSort.cpp b/sorting/NumericStringSort.cpp deleted file mode 100644 index 02f6964ba14..00000000000 --- a/sorting/NumericStringSort.cpp +++ /dev/null @@ -1,62 +0,0 @@ -//Using general algorithms to sort a collection of strings results in alphanumeric sort. -//If it is a numeric string, it leads to unnatural sorting - -//eg, an array of strings 1,10,100,2,20,200,3,30,300 -//would be sorted in that same order by using conventional sorting, -//even though we know the correct sorting order is 1,2,3,10,20,30,100,200,300 - -//This Programme uses a comparator to sort the array in Numerical order instead of Alphanumeric order - -#include -#include -#include -using namespace std; - -bool NumericSort(string a, string b) -{ - while (a[0] == '0') - { - a.erase(a.begin()); - } - while (b[0] == '0') - { - b.erase(b.begin()); - } - int n = a.length(); - int m = b.length(); - if (n == m) - return a < b; - return n < m; -} - -int main() -{ - - int n; - cout << "Enter number of elements to be sorted Numerically\n"; - cin >> n; - - vector v(n); - cout << "Enter the string of Numbers\n"; - for (int i = 0; i < n; i++) - { - cin >> v[i]; - } - - sort(v.begin(), v.end()); - cout << "Elements sorted normally \n"; - for (int i = 0; i < n; i++) - { - cout << v[i] << " "; - } - cout << "\n"; - - sort(v.begin(), v.end(), NumericSort); - cout << "Elements sorted Numerically \n"; - for (int i = 0; i < n; i++) - { - cout << v[i] << " "; - } - - return 0; -} diff --git a/sorting/bead_sort.cpp b/sorting/bead_sort.cpp new file mode 100644 index 00000000000..12b7d4d3205 --- /dev/null +++ b/sorting/bead_sort.cpp @@ -0,0 +1,54 @@ +// C++ program to implement gravity/bead sort +#include +#include + +#define BEAD(i, j) beads[i * max + j] + +// function to perform the above algorithm +void beadSort(int *a, int len) { + // Find the maximum element + int max = a[0]; + for (int i = 1; i < len; i++) + if (a[i] > max) max = a[i]; + + // allocating memory + unsigned char beads[max * len]; + memset(beads, 0, sizeof(beads)); + + // mark the beads + for (int i = 0; i < len; i++) + for (int j = 0; j < a[i]; j++) BEAD(i, j) = 1; + + for (int j = 0; j < max; j++) { + // count how many beads are on each post + int sum = 0; + for (int i = 0; i < len; i++) { + sum += BEAD(i, j); + BEAD(i, j) = 0; + } + + // Move beads down + for (int i = len - sum; i < len; i++) BEAD(i, j) = 1; + } + + // Put sorted values in array using beads + for (int i = 0; i < len; i++) { + int j; + for (j = 0; j < max && BEAD(i, j); j++) + ; + + a[i] = j; + } +} + +// driver function to test the algorithm +int main() { + int a[] = {5, 3, 1, 7, 4, 1, 1, 20}; + int len = sizeof(a) / sizeof(a[0]); + + beadSort(a, len); + + for (int i = 0; i < len; i++) printf("%d ", a[i]); + + return 0; +} diff --git a/sorting/bitonic_sort.cpp b/sorting/bitonic_sort.cpp new file mode 100644 index 00000000000..4d098105649 --- /dev/null +++ b/sorting/bitonic_sort.cpp @@ -0,0 +1,63 @@ +// Source : https://www.geeksforgeeks.org/bitonic-sort/ + +/* C++ Program for Bitonic Sort. Note that this program + works only when size of input is a power of 2. */ + +#include +#include + +/*The parameter dir indicates the sorting direction, ASCENDING + or DESCENDING; if (a[i] > a[j]) agrees with the direction, + then a[i] and a[j] are interchanged.*/ +void compAndSwap(int a[], int i, int j, int dir) { + if (dir == (a[i] > a[j])) std::swap(a[i], a[j]); +} + +/*It recursively sorts a bitonic sequence in ascending order, + if dir = 1, and in descending order otherwise (means dir=0). + The sequence to be sorted starts at index position low, + the parameter cnt is the number of elements to be sorted.*/ +void bitonicMerge(int a[], int low, int cnt, int dir) { + if (cnt > 1) { + int k = cnt / 2; + for (int i = low; i < low + k; i++) compAndSwap(a, i, i + k, dir); + bitonicMerge(a, low, k, dir); + bitonicMerge(a, low + k, k, dir); + } +} + +/* This function first produces a bitonic sequence by recursively + sorting its two halves in opposite sorting orders, and then + calls bitonicMerge to make them in the same order */ +void bitonicSort(int a[], int low, int cnt, int dir) { + if (cnt > 1) { + int k = cnt / 2; + + // sort in ascending order since dir here is 1 + bitonicSort(a, low, k, 1); + + // sort in descending order since dir here is 0 + bitonicSort(a, low + k, k, 0); + + // Will merge wole sequence in ascending order + // since dir=1. + bitonicMerge(a, low, cnt, dir); + } +} + +/* Caller of bitonicSort for sorting the entire array of + length N in ASCENDING order */ +void sort(int a[], int N, int up) { bitonicSort(a, 0, N, up); } + +// Driver code +int main() { + int a[] = {3, 7, 4, 8, 6, 2, 1, 5}; + int N = sizeof(a) / sizeof(a[0]); + + int up = 1; // means sort in ascending order + sort(a, N, up); + + std::cout << "Sorted array: \n"; + for (int i = 0; i < N; i++) std::cout << a[i] << " "; + return 0; +} diff --git a/sorting/bubble_sort.cpp b/sorting/bubble_sort.cpp new file mode 100644 index 00000000000..794f651983d --- /dev/null +++ b/sorting/bubble_sort.cpp @@ -0,0 +1,83 @@ +/** + * @file + * @brief Bubble sort algorithm + * + * The working principle of the Bubble sort algorithm: + +Bubble sort algorithm is the bubble sorting algorithm. The most important reason +for calling the bubble is that the largest number is thrown at the end of this +algorithm. This is all about the logic. In each iteration, the largest number is +expired and when iterations are completed, the sorting takes place. + +What is Swap? + +Swap in the software means that two variables are displaced. +An additional variable is required for this operation. x = 5, y = 10. +We want x = 10, y = 5. Here we create the most variable to do it. + +int z; +z = x; +x = y; +y = z; + +The above process is a typical displacement process. +When x assigns the value to x, the old value of x is lost. +That's why we created a variable z to create the first value of the value of x, +and finally, we have assigned to y. + +Bubble Sort Algorithm Analysis (Best Case - Worst Case - Average Case) + +Bubble Sort Worst Case Performance is O (n²). Why is that? Because if you +remember Big O Notation, we were calculating the complexity of the algorithms in +the nested loops. The n * (n - 1) product gives us O (n²) performance. In the +worst case all the steps of the cycle will occur. Bubble Sort (Avarage Case) +Performance. Bubble Sort is not an optimal algorithm. in average, O (n²) +performance is taken. Bubble Sort Best Case Performance. O (n). However, you +can't get the best status in the code we shared above. This happens on the +optimized bubble sort algorithm. It's right down there. +*/ + +#include +#include + +int main() { + int n; + short swap_check = 1; + std::cout << "Enter the amount of numbers to sort: "; + std::cin >> n; + std::vector numbers; + std::cout << "Enter " << n << " numbers: "; + int num; + + // Input + for (int i = 0; i < n; i++) { + std::cin >> num; + numbers.push_back(num); + } + + // Bubble Sorting + for (int i = 0; (i < n) && (swap_check == 1); i++) { + swap_check = 0; + for (int j = 0; j < n - 1 - i; j++) { + if (numbers[j] > numbers[j + 1]) { + swap_check = 1; + std::swap(numbers[j], + numbers[j + 1]); // by changing swap location. + // I mean, j. If the number is + // greater than j + 1, then it + // means the location. + } + } + } + + // Output + std::cout << "\nSorted Array : "; + for (int i = 0; i < numbers.size(); i++) { + if (i != numbers.size() - 1) { + std::cout << numbers[i] << ", "; + } else { + std::cout << numbers[i] << std::endl; + } + } + return 0; +} diff --git a/sorting/bucketSort.cpp b/sorting/bucket_sort.cpp similarity index 100% rename from sorting/bucketSort.cpp rename to sorting/bucket_sort.cpp diff --git a/sorting/cocktail_selection_sort.cpp b/sorting/cocktail_selection_sort.cpp new file mode 100644 index 00000000000..a9abd86d535 --- /dev/null +++ b/sorting/cocktail_selection_sort.cpp @@ -0,0 +1,101 @@ +// Returns Sorted elements after performing Cocktail Selection Sort +// It is a Sorting algorithm which chooses the minimum and maximum element in an +// array simultaneously, and swaps it with the lowest and highest available +// position iteratively or recursively + +#include +#include +#include + +// Iterative Version + +void CocktailSelectionSort(std::vector &vec, int low, int high) { + while (low <= high) { + int minimum = vec[low]; + int minimumindex = low; + int maximum = vec[high]; + int maximumindex = high; + + for (int i = low; i <= high; i++) { + if (vec[i] >= maximum) { + maximum = vec[i]; + maximumindex = i; + } + if (vec[i] <= minimum) { + minimum = vec[i]; + minimumindex = i; + } + } + if (low != maximumindex || high != minimumindex) { + std::swap(vec[low], vec[minimumindex]); + std::swap(vec[high], vec[maximumindex]); + } else { + std::swap(vec[low], vec[high]); + } + + low++; + high--; + } +} + +// Recursive Version + +void CocktailSelectionSort_v2(std::vector &vec, int low, int high) { + if (low >= high) return; + + int minimum = vec[low]; + int minimumindex = low; + int maximum = vec[high]; + int maximumindex = high; + + for (int i = low; i <= high; i++) { + if (vec[i] >= maximum) { + maximum = vec[i]; + maximumindex = i; + } + if (vec[i] <= minimum) { + minimum = vec[i]; + minimumindex = i; + } + } + if (low != maximumindex || high != minimumindex) { + std::swap(vec[low], vec[minimumindex]); + std::swap(vec[high], vec[maximumindex]); + } else { + std::swap(vec[low], vec[high]); + } + + CocktailSelectionSort(vec, low + 1, high - 1); +} + +// main function, select any one of iterative or recursive version + +int main() { + int n; + std::cout << "Enter number of elements\n"; + std::cin >> n; + std::vector v(n); + std::cout << "Enter all the elements\n"; + for (int i = 0; i < n; ++i) { + std::cin >> v[i]; + } + + int method; + std::cout << "Enter method: \n\t0: iterative\n\t1: recursive:\t"; + std::cin >> method; + + if (method == 0) { + CocktailSelectionSort(v, 0, n - 1); + } else if (method == 1) { + CocktailSelectionSort_v2(v, 0, n - 1); + } else { + std::cerr << "Unknown method" << std::endl; + return -1; + } + std::cout << "Sorted elements are\n"; + for (int i = 0; i < n; ++i) { + std::cout << v[i] << " "; + } + + return 0; +} diff --git a/sorting/combsort.cpp b/sorting/comb_sort.cpp similarity index 100% rename from sorting/combsort.cpp rename to sorting/comb_sort.cpp diff --git a/sorting/CountingSortString.cpp b/sorting/counting_sort_string.cpp similarity index 100% rename from sorting/CountingSortString.cpp rename to sorting/counting_sort_string.cpp diff --git a/sorting/doxy.txt b/sorting/doxy.txt deleted file mode 100644 index 68079276e7b..00000000000 --- a/sorting/doxy.txt +++ /dev/null @@ -1,374 +0,0 @@ -# Doxyfile 1.8.13 -#This configuration file has been generated from Doxygen template. -#--------------------------------------------------------------------------- -# Project related configuration options -#--------------------------------------------------------------------------- -DOXYFILE_ENCODING = UTF-8 -PROJECT_NAME = "My Project" -PROJECT_NUMBER = -PROJECT_BRIEF = -PROJECT_LOGO = -OUTPUT_DIRECTORY = -CREATE_SUBDIRS = NO -ALLOW_UNICODE_NAMES = NO -OUTPUT_LANGUAGE = English -BRIEF_MEMBER_DESC = YES -REPEAT_BRIEF = YES -ABBREVIATE_BRIEF = "The $name class" \ - "The $name widget" \ - "The $name file" \ - is \ - provides \ - specifies \ - contains \ - represents \ - a \ - an \ - the -ALWAYS_DETAILED_SEC = NO -INLINE_INHERITED_MEMB = NO -FULL_PATH_NAMES = YES -STRIP_FROM_PATH = -STRIP_FROM_INC_PATH = -SHORT_NAMES = NO -JAVADOC_AUTOBRIEF = NO -QT_AUTOBRIEF = NO -MULTILINE_CPP_IS_BRIEF = NO -INHERIT_DOCS = YES -SEPARATE_MEMBER_PAGES = NO -TAB_SIZE = 4 -ALIASES = -TCL_SUBST = -OPTIMIZE_OUTPUT_FOR_C = NO -OPTIMIZE_OUTPUT_JAVA = NO -OPTIMIZE_FOR_FORTRAN = NO -OPTIMIZE_OUTPUT_VHDL = NO -EXTENSION_MAPPING = -MARKDOWN_SUPPORT = YES -TOC_INCLUDE_HEADINGS = 0 -AUTOLINK_SUPPORT = YES -BUILTIN_STL_SUPPORT = NO -CPP_CLI_SUPPORT = NO -SIP_SUPPORT = NO -IDL_PROPERTY_SUPPORT = YES -DISTRIBUTE_GROUP_DOC = NO -GROUP_NESTED_COMPOUNDS = NO -SUBGROUPING = YES -INLINE_GROUPED_CLASSES = NO -INLINE_SIMPLE_STRUCTS = NO -TYPEDEF_HIDES_STRUCT = NO -LOOKUP_CACHE_SIZE = 0 -#--------------------------------------------------------------------------- -# Build related configuration options -#--------------------------------------------------------------------------- -EXTRACT_ALL = NO -EXTRACT_PRIVATE = NO -EXTRACT_PACKAGE = NO -EXTRACT_STATIC = NO -EXTRACT_LOCAL_CLASSES = YES -EXTRACT_LOCAL_METHODS = NO -EXTRACT_ANON_NSPACES = NO -HIDE_UNDOC_MEMBERS = NO -HIDE_UNDOC_CLASSES = NO -HIDE_FRIEND_COMPOUNDS = NO -HIDE_IN_BODY_DOCS = NO -INTERNAL_DOCS = NO -CASE_SENSE_NAMES = YES -HIDE_SCOPE_NAMES = NO -HIDE_COMPOUND_REFERENCE= NO -SHOW_INCLUDE_FILES = YES -SHOW_GROUPED_MEMB_INC = NO -FORCE_LOCAL_INCLUDES = NO -INLINE_INFO = YES -SORT_MEMBER_DOCS = YES -SORT_BRIEF_DOCS = NO -SORT_MEMBERS_CTORS_1ST = NO -SORT_GROUP_NAMES = NO -SORT_BY_SCOPE_NAME = NO -STRICT_PROTO_MATCHING = NO -GENERATE_TODOLIST = YES -GENERATE_TESTLIST = YES -GENERATE_BUGLIST = YES -GENERATE_DEPRECATEDLIST= YES -ENABLED_SECTIONS = -MAX_INITIALIZER_LINES = 30 -SHOW_USED_FILES = YES -SHOW_FILES = YES -SHOW_NAMESPACES = YES -FILE_VERSION_FILTER = -LAYOUT_FILE = -CITE_BIB_FILES = -#--------------------------------------------------------------------------- -# Configuration options related to warning and progress messages -#--------------------------------------------------------------------------- -QUIET = NO -WARNINGS = YES -WARN_IF_UNDOCUMENTED = YES -WARN_IF_DOC_ERROR = YES -WARN_NO_PARAMDOC = NO -WARN_AS_ERROR = NO -WARN_FORMAT = "$file:$line: $text" -WARN_LOGFILE = -#--------------------------------------------------------------------------- -# Configuration options related to the input files -#--------------------------------------------------------------------------- -INPUT = -INPUT_ENCODING = UTF-8 -FILE_PATTERNS = *.c \ - *.cc \ - *.cxx \ - *.cpp \ - *.c++ \ - *.java \ - *.ii \ - *.ixx \ - *.ipp \ - *.i++ \ - *.inl \ - *.idl \ - *.ddl \ - *.odl \ - *.h \ - *.hh \ - *.hxx \ - *.hpp \ - *.h++ \ - *.cs \ - *.d \ - *.php \ - *.php4 \ - *.php5 \ - *.phtml \ - *.inc \ - *.m \ - *.markdown \ - *.md \ - *.mm \ - *.dox \ - *.py \ - *.pyw \ - *.f90 \ - *.f95 \ - *.f03 \ - *.f08 \ - *.f \ - *.for \ - *.tcl \ - *.vhd \ - *.vhdl \ - *.ucf \ - *.qsf -RECURSIVE = NO -EXCLUDE = -EXCLUDE_SYMLINKS = NO -EXCLUDE_PATTERNS = -EXCLUDE_SYMBOLS = -EXAMPLE_PATH = -EXAMPLE_PATTERNS = * -EXAMPLE_RECURSIVE = NO -IMAGE_PATH = -INPUT_FILTER = -FILTER_PATTERNS = -FILTER_SOURCE_FILES = NO -FILTER_SOURCE_PATTERNS = -USE_MDFILE_AS_MAINPAGE = -#--------------------------------------------------------------------------- -# Configuration options related to source browsing -#--------------------------------------------------------------------------- -SOURCE_BROWSER = NO -INLINE_SOURCES = NO -STRIP_CODE_COMMENTS = YES -REFERENCED_BY_RELATION = NO -REFERENCES_RELATION = NO -REFERENCES_LINK_SOURCE = YES -SOURCE_TOOLTIPS = YES -USE_HTAGS = NO -VERBATIM_HEADERS = YES -CLANG_ASSISTED_PARSING = NO -CLANG_OPTIONS = -#--------------------------------------------------------------------------- -# Configuration options related to the alphabetical class index -#--------------------------------------------------------------------------- -ALPHABETICAL_INDEX = YES -COLS_IN_ALPHA_INDEX = 5 -IGNORE_PREFIX = -#--------------------------------------------------------------------------- -# Configuration options related to the HTML output -#--------------------------------------------------------------------------- -GENERATE_HTML = YES -HTML_OUTPUT = html -HTML_FILE_EXTENSION = .html -HTML_HEADER = -HTML_FOOTER = -HTML_STYLESHEET = -HTML_EXTRA_STYLESHEET = -HTML_EXTRA_FILES = -HTML_COLORSTYLE_HUE = 220 -HTML_COLORSTYLE_SAT = 100 -HTML_COLORSTYLE_GAMMA = 80 -HTML_TIMESTAMP = NO -HTML_DYNAMIC_SECTIONS = NO -HTML_INDEX_NUM_ENTRIES = 100 -GENERATE_DOCSET = NO -DOCSET_FEEDNAME = "Doxygen generated docs" -DOCSET_BUNDLE_ID = org.doxygen.Project -DOCSET_PUBLISHER_ID = org.doxygen.Publisher -DOCSET_PUBLISHER_NAME = Publisher -GENERATE_HTMLHELP = NO -CHM_FILE = -HHC_LOCATION = -GENERATE_CHI = NO -CHM_INDEX_ENCODING = -BINARY_TOC = NO -TOC_EXPAND = NO -GENERATE_QHP = NO -QCH_FILE = -QHP_NAMESPACE = org.doxygen.Project -QHP_VIRTUAL_FOLDER = doc -QHP_CUST_FILTER_NAME = -QHP_CUST_FILTER_ATTRS = -QHP_SECT_FILTER_ATTRS = -QHG_LOCATION = -GENERATE_ECLIPSEHELP = NO -ECLIPSE_DOC_ID = org.doxygen.Project -DISABLE_INDEX = NO -GENERATE_TREEVIEW = NO -ENUM_VALUES_PER_LINE = 4 -TREEVIEW_WIDTH = 250 -EXT_LINKS_IN_WINDOW = NO -FORMULA_FONTSIZE = 10 -FORMULA_TRANSPARENT = YES -USE_MATHJAX = NO -MATHJAX_FORMAT = HTML-CSS -MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest -MATHJAX_EXTENSIONS = -MATHJAX_CODEFILE = -SEARCHENGINE = YES -SERVER_BASED_SEARCH = NO -EXTERNAL_SEARCH = NO -SEARCHENGINE_URL = -SEARCHDATA_FILE = searchdata.xml -EXTERNAL_SEARCH_ID = -EXTRA_SEARCH_MAPPINGS = -#--------------------------------------------------------------------------- -# Configuration options related to the LaTeX output -#--------------------------------------------------------------------------- -GENERATE_LATEX = NO -LATEX_OUTPUT = latex -LATEX_CMD_NAME = latex -MAKEINDEX_CMD_NAME = makeindex -COMPACT_LATEX = NO -PAPER_TYPE = a4 -EXTRA_PACKAGES = -LATEX_HEADER = -LATEX_FOOTER = -LATEX_EXTRA_STYLESHEET = -LATEX_EXTRA_FILES = -PDF_HYPERLINKS = YES -USE_PDFLATEX = YES -LATEX_BATCHMODE = NO -LATEX_HIDE_INDICES = NO -LATEX_SOURCE_CODE = NO -LATEX_BIB_STYLE = plain -LATEX_TIMESTAMP = NO -#--------------------------------------------------------------------------- -# Configuration options related to the RTF output -#--------------------------------------------------------------------------- -GENERATE_RTF = NO -RTF_OUTPUT = rtf -COMPACT_RTF = NO -RTF_HYPERLINKS = NO -RTF_STYLESHEET_FILE = -RTF_EXTENSIONS_FILE = -RTF_SOURCE_CODE = NO -#--------------------------------------------------------------------------- -# Configuration options related to the man page output -#--------------------------------------------------------------------------- -GENERATE_MAN = NO -MAN_OUTPUT = man -MAN_EXTENSION = .3 -MAN_SUBDIR = -MAN_LINKS = NO -#--------------------------------------------------------------------------- -# Configuration options related to the XML output -#--------------------------------------------------------------------------- -GENERATE_XML = NO -XML_OUTPUT = xml -XML_PROGRAMLISTING = YES -#--------------------------------------------------------------------------- -# Configuration options related to the DOCBOOK output -#--------------------------------------------------------------------------- -GENERATE_DOCBOOK = NO -DOCBOOK_OUTPUT = docbook -DOCBOOK_PROGRAMLISTING = NO -#--------------------------------------------------------------------------- -# Configuration options for the AutoGen Definitions output -#--------------------------------------------------------------------------- -GENERATE_AUTOGEN_DEF = NO -#--------------------------------------------------------------------------- -# Configuration options related to the Perl module output -#--------------------------------------------------------------------------- -GENERATE_PERLMOD = NO -PERLMOD_LATEX = NO -PERLMOD_PRETTY = YES -PERLMOD_MAKEVAR_PREFIX = -#--------------------------------------------------------------------------- -# Configuration options related to the preprocessor -#--------------------------------------------------------------------------- -ENABLE_PREPROCESSING = YES -MACRO_EXPANSION = NO -EXPAND_ONLY_PREDEF = NO -SEARCH_INCLUDES = YES -INCLUDE_PATH = -INCLUDE_FILE_PATTERNS = -PREDEFINED = -EXPAND_AS_DEFINED = -SKIP_FUNCTION_MACROS = YES -#--------------------------------------------------------------------------- -# Configuration options related to external references -#--------------------------------------------------------------------------- -TAGFILES = -GENERATE_TAGFILE = -ALLEXTERNALS = NO -EXTERNAL_GROUPS = YES -EXTERNAL_PAGES = YES -PERL_PATH = /usr/bin/perl -#--------------------------------------------------------------------------- -# Configuration options related to the dot tool -#--------------------------------------------------------------------------- -CLASS_DIAGRAMS = YES -MSCGEN_PATH = -DIA_PATH = -HIDE_UNDOC_RELATIONS = YES -HAVE_DOT = YES -DOT_NUM_THREADS = 0 -DOT_FONTNAME = Helvetica -DOT_FONTSIZE = 10 -DOT_FONTPATH = -CLASS_GRAPH = YES -COLLABORATION_GRAPH = YES -GROUP_GRAPHS = YES -UML_LOOK = NO -UML_LIMIT_NUM_FIELDS = 10 -TEMPLATE_RELATIONS = NO -INCLUDE_GRAPH = YES -INCLUDED_BY_GRAPH = YES -CALL_GRAPH = NO -CALLER_GRAPH = NO -GRAPHICAL_HIERARCHY = YES -DIRECTORY_GRAPH = YES -DOT_IMAGE_FORMAT = png -INTERACTIVE_SVG = NO -DOT_PATH = -DOTFILE_DIRS = -MSCFILE_DIRS = -DIAFILE_DIRS = -PLANTUML_JAR_PATH = -PLANTUML_CFG_FILE = -PLANTUML_INCLUDE_PATH = -DOT_GRAPH_MAX_NODES = 50 -MAX_DOT_GRAPH_DEPTH = 0 -DOT_TRANSPARENT = NO -DOT_MULTI_TARGETS = NO -GENERATE_LEGEND = YES -DOT_CLEANUP = YES diff --git a/sorting/Insertion Sort.cpp b/sorting/insertion_sort.cpp similarity index 100% rename from sorting/Insertion Sort.cpp rename to sorting/insertion_sort.cpp diff --git a/sorting/makefile b/sorting/makefile deleted file mode 100644 index 21d3186c698..00000000000 --- a/sorting/makefile +++ /dev/null @@ -1,11 +0,0 @@ -non_recursive_merge_sort: non_recursive_merge_sort.cpp - g++ -std=c++17 -o non_recursive_merge_sort non_recursive_merge_sort.cpp -.PHONY: test -.PHONY: doc -.PHONY: clean -test: non_recursive_merge_sort - ./non_recursive_merge_sort -doc: doxy.txt - doxygen doxy.txt -clean: - rm -fr non_recursive_merge_sort html diff --git a/sorting/Merge Sort.cpp b/sorting/merge_sort.cpp similarity index 100% rename from sorting/Merge Sort.cpp rename to sorting/merge_sort.cpp diff --git a/sorting/non_recursive_merge_sort.cpp b/sorting/non_recursive_merge_sort.cpp index c6ca56376df..ebfef1dcc50 100644 --- a/sorting/non_recursive_merge_sort.cpp +++ b/sorting/non_recursive_merge_sort.cpp @@ -6,7 +6,7 @@ */ #include // for size_t #include // for std::move & std::remove_reference_t -template +template void merge(Iterator, Iterator, const Iterator, char[]); /// bottom-up merge sort which sorts elements in a non-decreasing order /** @@ -17,13 +17,13 @@ void merge(Iterator, Iterator, const Iterator, char[]); * @param first points to the first element * @param last points to 1-step past the last element * @param n the number of elements -*/ -template + */ +template void non_recursive_merge_sort(const Iterator first, const Iterator last, const size_t n) { // create a buffer large enough to store all elements // dynamically allocated to comply with cpplint - char * buffer = new char[n * sizeof(*first)]; + char* buffer = new char[n * sizeof(*first)]; // buffer size can be optimized to largest power of 2 less than n elements // divide the container into equally-sized segments whose length start at 1 // and keeps increasing by factors of 2 @@ -49,32 +49,28 @@ void non_recursive_merge_sort(const Iterator first, const Iterator last, * @param r points to the right part, end of left part * @param e points to end of right part * @param b points at the buffer -*/ -template + */ +template void merge(Iterator l, Iterator r, const Iterator e, char b[]) { // create 2 pointers to point at the buffer auto p(reinterpret_cast*>(b)), c(p); // move the left part of the segment - for (Iterator t(l); r != t; ++t) - *p++ = std::move(*t); + for (Iterator t(l); r != t; ++t) *p++ = std::move(*t); // while neither the buffer nor the right part has been exhausted // move the smallest element of the two back to the container - while (e != r && c != p) - *l++ = std::move(*r < *c ? *r++ : *c++); + while (e != r && c != p) *l++ = std::move(*r < *c ? *r++ : *c++); // notice only one of the two following loops will be executed // while the right part hasn't bee exhausted, move it back - while (e != r) - *l++ = std::move(*r++); + while (e != r) *l++ = std::move(*r++); // while the buffer hasn't bee exhausted, move it back - while (c != p) - *l++ = std::move(*c++); + while (c != p) *l++ = std::move(*c++); } /// bottom-up merge sort which sorts elements in a non-decreasing order /** * @param first points to the first element * @param n the number of elements -*/ -template + */ +template void non_recursive_merge_sort(const Iterator first, const size_t n) { non_recursive_merge_sort(first, first + n, n); } @@ -82,8 +78,8 @@ void non_recursive_merge_sort(const Iterator first, const size_t n) { /** * @param first points to the first element * @param last points to 1-step past the last element -*/ -template + */ +template void non_recursive_merge_sort(const Iterator first, const Iterator last) { non_recursive_merge_sort(first, last, last - first); } @@ -92,15 +88,15 @@ void non_recursive_merge_sort(const Iterator first, const Iterator last) { * Currently, it only creates output for non_recursive_merge_sort.cpp, but if * it has proven its efficacy it can be expanded to other files. * The configuration file is named doxy.txt and has been auto-generated too. -*/ + */ // the remaining of this file is only for testing. It can erased to to convert // it into a header file for later re-use. #include -int main(int argc, char ** argv) { +int main(int argc, char** argv) { int size; std::cout << "Enter the number of elements : "; std::cin >> size; - int * arr = new int[size]; + int* arr = new int[size]; for (int i = 0; i < size; ++i) { std::cout << "arr[" << i << "] = "; std::cin >> arr[i]; diff --git a/sorting/numeric_string_sort.cpp b/sorting/numeric_string_sort.cpp new file mode 100644 index 00000000000..8b86bb29d51 --- /dev/null +++ b/sorting/numeric_string_sort.cpp @@ -0,0 +1,54 @@ +// Using general algorithms to sort a collection of strings results in +// alphanumeric sort. If it is a numeric string, it leads to unnatural sorting + +// eg, an array of strings 1,10,100,2,20,200,3,30,300 +// would be sorted in that same order by using conventional sorting, +// even though we know the correct sorting order is 1,2,3,10,20,30,100,200,300 + +// This Programme uses a comparator to sort the array in Numerical order instead +// of Alphanumeric order + +#include +#include +#include +#include + +bool NumericSort(std::string a, std::string b) { + while (a[0] == '0') { + a.erase(a.begin()); + } + while (b[0] == '0') { + b.erase(b.begin()); + } + int n = a.length(); + int m = b.length(); + if (n == m) return a < b; + return n < m; +} + +int main() { + int n; + std::cout << "Enter number of elements to be sorted Numerically\n"; + std::cin >> n; + + std::vector v(n); + std::cout << "Enter the string of Numbers\n"; + for (int i = 0; i < n; i++) { + std::cin >> v[i]; + } + + sort(v.begin(), v.end()); + std::cout << "Elements sorted normally \n"; + for (int i = 0; i < n; i++) { + std::cout << v[i] << " "; + } + std::cout << "\n"; + + std::sort(v.begin(), v.end(), NumericSort); + std::cout << "Elements sorted Numerically \n"; + for (int i = 0; i < n; i++) { + std::cout << v[i] << " "; + } + + return 0; +} diff --git a/sorting/OddEven Sort.cpp b/sorting/odd_even_sort.cpp similarity index 100% rename from sorting/OddEven Sort.cpp rename to sorting/odd_even_sort.cpp diff --git a/sorting/Quick Sort.cpp b/sorting/quick_sort.cpp similarity index 100% rename from sorting/Quick Sort.cpp rename to sorting/quick_sort.cpp diff --git a/sorting/Radix Sort.cpp b/sorting/radix_sort.cpp similarity index 100% rename from sorting/Radix Sort.cpp rename to sorting/radix_sort.cpp diff --git a/sorting/Selection Sort.cpp b/sorting/selection_sort.cpp similarity index 100% rename from sorting/Selection Sort.cpp rename to sorting/selection_sort.cpp diff --git a/sorting/Shell Sort.cpp b/sorting/shell_sort.cpp similarity index 100% rename from sorting/Shell Sort.cpp rename to sorting/shell_sort.cpp diff --git a/sorting/Slow Sort.cpp b/sorting/slow_sort.cpp similarity index 100% rename from sorting/Slow Sort.cpp rename to sorting/slow_sort.cpp diff --git a/sorting/Tim Sort.cpp b/sorting/tim_sort.cpp similarity index 100% rename from sorting/Tim Sort.cpp rename to sorting/tim_sort.cpp From 887bff8a9ead3c19b03b73f91384e92de98d05cf Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 11:46:24 -0400 Subject: [PATCH 101/433] sorting fixes for MSVC and CPPLINT (cherry picked from commit 76a5f572d5d9834585201836183027e3575b1e55) --- sorting/bead_sort.cpp | 5 ++-- sorting/bucket_sort.cpp | 51 ++++++++++++++++++----------------------- sorting/comb_sort.cpp | 47 +++++++++++++++---------------------- 3 files changed, 43 insertions(+), 60 deletions(-) diff --git a/sorting/bead_sort.cpp b/sorting/bead_sort.cpp index 12b7d4d3205..d3470607383 100644 --- a/sorting/bead_sort.cpp +++ b/sorting/bead_sort.cpp @@ -12,8 +12,8 @@ void beadSort(int *a, int len) { if (a[i] > max) max = a[i]; // allocating memory - unsigned char beads[max * len]; - memset(beads, 0, sizeof(beads)); + unsigned char *beads = new unsigned char[max * len]; + memset(beads, 0, max * len); // mark the beads for (int i = 0; i < len; i++) @@ -39,6 +39,7 @@ void beadSort(int *a, int len) { a[i] = j; } + delete[] beads; } // driver function to test the algorithm diff --git a/sorting/bucket_sort.cpp b/sorting/bucket_sort.cpp index 0ffbf8e4cb7..f120f04fc9c 100644 --- a/sorting/bucket_sort.cpp +++ b/sorting/bucket_sort.cpp @@ -1,42 +1,35 @@ // C++ program to sort an array using bucket sort -#include #include +#include #include -using namespace std; // Function to sort arr[] of size n using bucket sort -void bucketSort(float arr[], int n) -{ - // 1) Create n empty buckets - vector b[n]; +void bucketSort(float arr[], int n) { + // 1) Create n empty buckets + std::vector b[n]; - // 2) Put array elements in different buckets - for (int i = 0; i < n; i++) - { - int bi = n * arr[i]; // Index in bucket - b[bi].push_back(arr[i]); - } + // 2) Put array elements in different buckets + for (int i = 0; i < n; i++) { + int bi = n * arr[i]; // Index in bucket + b[bi].push_back(arr[i]); + } - // 3) Sort individual buckets - for (int i = 0; i < n; i++) - sort(b[i].begin(), b[i].end()); + // 3) Sort individual buckets + for (int i = 0; i < n; i++) std::sort(b[i].begin(), b[i].end()); - // 4) Concatenate all buckets into arr[] - int index = 0; - for (int i = 0; i < n; i++) - for (int j = 0; j < b[i].size(); j++) - arr[index++] = b[i][j]; + // 4) Concatenate all buckets into arr[] + int index = 0; + for (int i = 0; i < n; i++) + for (int j = 0; j < b[i].size(); j++) arr[index++] = b[i][j]; } /* Driver program to test above funtion */ -int main() -{ - float arr[] = {0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434}; - int n = sizeof(arr) / sizeof(arr[0]); - bucketSort(arr, n); +int main() { + float arr[] = {0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434}; + int n = sizeof(arr) / sizeof(arr[0]); + bucketSort(arr, n); - cout << "Sorted array is \n"; - for (int i = 0; i < n; i++) - cout << arr[i] << " "; - return 0; + std::cout << "Sorted array is \n"; + for (int i = 0; i < n; i++) std::cout << arr[i] << " "; + return 0; } diff --git a/sorting/comb_sort.cpp b/sorting/comb_sort.cpp index 2209c96fc55..feed4ba448b 100644 --- a/sorting/comb_sort.cpp +++ b/sorting/comb_sort.cpp @@ -1,59 +1,48 @@ -//Kind of better version of Bubble sort. -//While Bubble sort is comparering adjacent value, Combsort is using gap larger than 1 -//Best case: O(n) -//Worst case: O(n ^ 2) +// Kind of better version of Bubble sort. +// While Bubble sort is comparering adjacent value, Combsort is using gap larger +// than 1 Best case: O(n) Worst case: O(n ^ 2) #include -using namespace std; - int a[100005]; int n; -int FindNextGap(int x) -{ +int FindNextGap(int x) { x = (x * 10) / 13; - return max(1, x); + return std::max(1, x); } -void CombSort(int a[], int l, int r) -{ - //Init gap +void CombSort(int a[], int l, int r) { + // Init gap int gap = n; - //Initialize swapped as true to make sure that loop runs + // Initialize swapped as true to make sure that loop runs bool swapped = true; - //Keep running until gap = 1 or none elements were swapped - while (gap != 1 || swapped) - { - //Find next gap + // Keep running until gap = 1 or none elements were swapped + while (gap != 1 || swapped) { + // Find next gap gap = FindNextGap(gap); swapped = false; // Compare all elements with current gap - for (int i = l; i <= r - gap; ++i) - { - if (a[i] > a[i + gap]) - { - swap(a[i], a[i + gap]); + for (int i = l; i <= r - gap; ++i) { + if (a[i] > a[i + gap]) { + std::swap(a[i], a[i + gap]); swapped = true; } } } } -int main() -{ - cin >> n; - for (int i = 1; i <= n; ++i) - cin >> a[i]; +int main() { + std::cin >> n; + for (int i = 1; i <= n; ++i) std::cin >> a[i]; CombSort(a, 1, n); - for (int i = 1; i <= n; ++i) - cout << a[i] << ' '; + for (int i = 1; i <= n; ++i) std::cout << a[i] << ' '; return 0; } From 77e781f709308a393b8e0ab11ac2f6b5dec15a68 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 12:15:12 -0400 Subject: [PATCH 102/433] cpplint and msvc fixes for - sorting (cherry picked from commit 0d8e015d15b87ea188b75f1f70b7be614cdf86cd) --- sorting/bead_sort.cpp | 4 +-- sorting/bubble_sort.cpp | 8 +++--- sorting/cocktail_selection_sort.cpp | 44 ++++++++++++++--------------- 3 files changed, 28 insertions(+), 28 deletions(-) diff --git a/sorting/bead_sort.cpp b/sorting/bead_sort.cpp index d3470607383..a1a54c1e04a 100644 --- a/sorting/bead_sort.cpp +++ b/sorting/bead_sort.cpp @@ -34,8 +34,8 @@ void beadSort(int *a, int len) { // Put sorted values in array using beads for (int i = 0; i < len; i++) { int j; - for (j = 0; j < max && BEAD(i, j); j++) - ; + for (j = 0; j < max && BEAD(i, j); j++) { + } a[i] = j; } diff --git a/sorting/bubble_sort.cpp b/sorting/bubble_sort.cpp index 794f651983d..c43e425fcd9 100644 --- a/sorting/bubble_sort.cpp +++ b/sorting/bubble_sort.cpp @@ -42,7 +42,7 @@ optimized bubble sort algorithm. It's right down there. int main() { int n; - short swap_check = 1; + bool swap_check = true; std::cout << "Enter the amount of numbers to sort: "; std::cin >> n; std::vector numbers; @@ -56,11 +56,11 @@ int main() { } // Bubble Sorting - for (int i = 0; (i < n) && (swap_check == 1); i++) { - swap_check = 0; + for (int i = 0; (i < n) && (swap_check); i++) { + swap_check = false; for (int j = 0; j < n - 1 - i; j++) { if (numbers[j] > numbers[j + 1]) { - swap_check = 1; + swap_check = true; std::swap(numbers[j], numbers[j + 1]); // by changing swap location. // I mean, j. If the number is diff --git a/sorting/cocktail_selection_sort.cpp b/sorting/cocktail_selection_sort.cpp index a9abd86d535..ab622999687 100644 --- a/sorting/cocktail_selection_sort.cpp +++ b/sorting/cocktail_selection_sort.cpp @@ -9,28 +9,28 @@ // Iterative Version -void CocktailSelectionSort(std::vector &vec, int low, int high) { +void CocktailSelectionSort(std::vector *vec, int low, int high) { while (low <= high) { - int minimum = vec[low]; + int minimum = (*vec)[low]; int minimumindex = low; - int maximum = vec[high]; + int maximum = (*vec)[high]; int maximumindex = high; for (int i = low; i <= high; i++) { - if (vec[i] >= maximum) { - maximum = vec[i]; + if ((*vec)[i] >= maximum) { + maximum = (*vec)[i]; maximumindex = i; } - if (vec[i] <= minimum) { - minimum = vec[i]; + if ((*vec)[i] <= minimum) { + minimum = (*vec)[i]; minimumindex = i; } } if (low != maximumindex || high != minimumindex) { - std::swap(vec[low], vec[minimumindex]); - std::swap(vec[high], vec[maximumindex]); + std::swap((*vec)[low], (*vec)[minimumindex]); + std::swap((*vec)[high], (*vec)[maximumindex]); } else { - std::swap(vec[low], vec[high]); + std::swap((*vec)[low], (*vec)[high]); } low++; @@ -40,29 +40,29 @@ void CocktailSelectionSort(std::vector &vec, int low, int high) { // Recursive Version -void CocktailSelectionSort_v2(std::vector &vec, int low, int high) { +void CocktailSelectionSort_v2(std::vector *vec, int low, int high) { if (low >= high) return; - int minimum = vec[low]; + int minimum = (*vec)[low]; int minimumindex = low; - int maximum = vec[high]; + int maximum = (*vec)[high]; int maximumindex = high; for (int i = low; i <= high; i++) { - if (vec[i] >= maximum) { - maximum = vec[i]; + if ((*vec)[i] >= maximum) { + maximum = (*vec)[i]; maximumindex = i; } - if (vec[i] <= minimum) { - minimum = vec[i]; + if ((*vec)[i] <= minimum) { + minimum = (*vec)[i]; minimumindex = i; } } if (low != maximumindex || high != minimumindex) { - std::swap(vec[low], vec[minimumindex]); - std::swap(vec[high], vec[maximumindex]); + std::swap((*vec)[low], (*vec)[minimumindex]); + std::swap((*vec)[high], (*vec)[maximumindex]); } else { - std::swap(vec[low], vec[high]); + std::swap((*vec)[low], (*vec)[high]); } CocktailSelectionSort(vec, low + 1, high - 1); @@ -85,9 +85,9 @@ int main() { std::cin >> method; if (method == 0) { - CocktailSelectionSort(v, 0, n - 1); + CocktailSelectionSort(&v, 0, n - 1); } else if (method == 1) { - CocktailSelectionSort_v2(v, 0, n - 1); + CocktailSelectionSort_v2(&v, 0, n - 1); } else { std::cerr << "Unknown method" << std::endl; return -1; From 09f073306527f5f5d47f1f0c046d526902f080d0 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 12:31:49 -0400 Subject: [PATCH 103/433] fix dynamic array (cherry picked from commit 717f5c8f01c1d5559320e118ccc8eabdf602e8ff) --- sorting/bucket_sort.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sorting/bucket_sort.cpp b/sorting/bucket_sort.cpp index f120f04fc9c..c43865281bc 100644 --- a/sorting/bucket_sort.cpp +++ b/sorting/bucket_sort.cpp @@ -6,7 +6,7 @@ // Function to sort arr[] of size n using bucket sort void bucketSort(float arr[], int n) { // 1) Create n empty buckets - std::vector b[n]; + std::vector *b = new std::vector[n]; // 2) Put array elements in different buckets for (int i = 0; i < n; i++) { @@ -21,6 +21,7 @@ void bucketSort(float arr[], int n) { int index = 0; for (int i = 0; i < n; i++) for (int j = 0; j < b[i].size(); j++) arr[index++] = b[i][j]; + delete[] b; } /* Driver program to test above funtion */ From 231c99f8802346b84962bb087f37ed34d1a0d3fc Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 13:02:10 -0400 Subject: [PATCH 104/433] fix dynamic array issues in sorting folder (cherry picked from commit 01b69fcb249c30d4f1795766bf4cc617d8200ab3) --- sorting/comb_sort.cpp | 1 + sorting/insertion_sort.cpp | 62 ++++++++++---------- sorting/merge_sort.cpp | 66 +++++++++------------ sorting/quick_sort.cpp | 51 +++++++--------- sorting/radix_sort.cpp | 116 +++++++++++++++++-------------------- sorting/shell_sort.cpp | 72 ++++++++++------------- sorting/slow_sort.cpp | 82 +++++++++++++------------- sorting/swap_sort.cpp | 7 ++- sorting/tim_sort.cpp | 110 ++++++++++++++++------------------- 9 files changed, 256 insertions(+), 311 deletions(-) diff --git a/sorting/comb_sort.cpp b/sorting/comb_sort.cpp index feed4ba448b..1b0a4d70633 100644 --- a/sorting/comb_sort.cpp +++ b/sorting/comb_sort.cpp @@ -2,6 +2,7 @@ // While Bubble sort is comparering adjacent value, Combsort is using gap larger // than 1 Best case: O(n) Worst case: O(n ^ 2) +#include #include int a[100005]; diff --git a/sorting/insertion_sort.cpp b/sorting/insertion_sort.cpp index 2563acaf8f2..fe920ca5913 100644 --- a/sorting/insertion_sort.cpp +++ b/sorting/insertion_sort.cpp @@ -1,40 +1,36 @@ -//Insertion Sort +// Insertion Sort #include -using namespace std; -int main() -{ - int n; - cout << "\nEnter the length of your array : "; - cin >> n; - int Array[n]; - cout << "\nEnter any " << n << " Numbers for Unsorted Array : "; +int main() { + int n; + std::cout << "\nEnter the length of your array : "; + std::cin >> n; + int *Array = new int[n]; + std::cout << "\nEnter any " << n << " Numbers for Unsorted Array : "; - //Input - for (int i = 0; i < n; i++) - { - cin >> Array[i]; - } + // Input + for (int i = 0; i < n; i++) { + std::cin >> Array[i]; + } - //Sorting - for (int i = 1; i < n; i++) - { - int temp = Array[i]; - int j = i - 1; - while (j >= 0 && temp < Array[j]) - { - Array[j + 1] = Array[j]; - j--; - } - Array[j + 1] = temp; - } + // Sorting + for (int i = 1; i < n; i++) { + int temp = Array[i]; + int j = i - 1; + while (j >= 0 && temp < Array[j]) { + Array[j + 1] = Array[j]; + j--; + } + Array[j + 1] = temp; + } - //Output - cout << "\nSorted Array : "; - for (int i = 0; i < n; i++) - { - cout << Array[i] << "\t"; - } - return 0; + // Output + std::cout << "\nSorted Array : "; + for (int i = 0; i < n; i++) { + std::cout << Array[i] << "\t"; + } + + delete[] Array; + return 0; } diff --git a/sorting/merge_sort.cpp b/sorting/merge_sort.cpp index b8edc8851f4..82ab869cd2c 100644 --- a/sorting/merge_sort.cpp +++ b/sorting/merge_sort.cpp @@ -1,57 +1,47 @@ #include -using namespace std; -void merge(int arr[], int l, int m, int r) -{ +void merge(int arr[], int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; - int L[n1], R[n2]; + int *L = new int[n1], *R = new int[n2]; - for (i = 0; i < n1; i++) - L[i] = arr[l + i]; - for (j = 0; j < n2; j++) - R[j] = arr[m + 1 + j]; + for (i = 0; i < n1; i++) L[i] = arr[l + i]; + for (j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; i = 0; j = 0; k = l; - while (i < n1 && j < n2) - { - if (L[i] <= R[j]) - { + while (i < n1 && j < n2) { + if (L[i] <= R[j]) { arr[k] = L[i]; i++; - } - else - { + } else { arr[k] = R[j]; j++; } k++; } - while (i < n1) - { + while (i < n1) { arr[k] = L[i]; i++; k++; } - while (j < n2) - { + while (j < n2) { arr[k] = R[j]; j++; k++; } -} -void mergeSort(int arr[], int l, int r) -{ - if (l < r) - { + delete[] L; + delete[] R; +} +void mergeSort(int arr[], int l, int r) { + if (l < r) { int m = l + (r - l) / 2; mergeSort(arr, l, m); @@ -61,33 +51,31 @@ void mergeSort(int arr[], int l, int r) } } -void show(int A[], int size) -{ +void show(int A[], int size) { int i; - for (i = 0; i < size; i++) - cout << A[i] << "\n"; + for (i = 0; i < size; i++) std::cout << A[i] << "\n"; } -int main() -{ +int main() { int size; - cout << "\nEnter the number of elements : "; + std::cout << "\nEnter the number of elements : "; - cin >> size; + std::cin >> size; - int arr[size]; + int *arr = new int[size]; - cout << "\nEnter the unsorted elements : "; + std::cout << "\nEnter the unsorted elements : "; - for (int i = 0; i < size; ++i) - { - cout << "\n"; - cin >> arr[i]; + for (int i = 0; i < size; ++i) { + std::cout << "\n"; + std::cin >> arr[i]; } mergeSort(arr, 0, size); - cout << "Sorted array\n"; + std::cout << "Sorted array\n"; show(arr, size); + + delete[] arr; return 0; } diff --git a/sorting/quick_sort.cpp b/sorting/quick_sort.cpp index 0b807898fb3..489e1096549 100644 --- a/sorting/quick_sort.cpp +++ b/sorting/quick_sort.cpp @@ -1,19 +1,15 @@ /* C implementation QuickSort */ #include -using namespace std; -int partition(int arr[], int low, int high) -{ - int pivot = arr[high]; // pivot - int i = (low - 1); // Index of smaller element +int partition(int arr[], int low, int high) { + int pivot = arr[high]; // pivot + int i = (low - 1); // Index of smaller element - for (int j = low; j < high; j++) - { + for (int j = low; j < high; j++) { // If current element is smaller than or // equal to pivot - if (arr[j] <= pivot) - { - i++; // increment index of smaller element + if (arr[j] <= pivot) { + i++; // increment index of smaller element int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; @@ -25,11 +21,8 @@ int partition(int arr[], int low, int high) return (i + 1); } -void quickSort(int arr[], int low, int high) -{ - if (low < high) - { - +void quickSort(int arr[], int low, int high) { + if (low < high) { int p = partition(arr, low, high); quickSort(arr, low, p - 1); @@ -37,31 +30,29 @@ void quickSort(int arr[], int low, int high) } } -void show(int arr[], int size) -{ - for (int i = 0; i < size; i++) - cout << arr[i] << "\n"; +void show(int arr[], int size) { + for (int i = 0; i < size; i++) std::cout << arr[i] << "\n"; } // Driver program to test above functions -int main() -{ +int main() { int size; - cout << "\nEnter the number of elements : "; + std::cout << "\nEnter the number of elements : "; - cin >> size; + std::cin >> size; - int arr[size]; + int *arr = new int[size]; - cout << "\nEnter the unsorted elements : "; + std::cout << "\nEnter the unsorted elements : "; - for (int i = 0; i < size; ++i) - { - cout << "\n"; - cin >> arr[i]; + for (int i = 0; i < size; ++i) { + std::cout << "\n"; + std::cin >> arr[i]; } quickSort(arr, 0, size); - cout << "Sorted array\n"; + std::cout << "Sorted array\n"; show(arr, size); + + delete[] arr; return 0; } diff --git a/sorting/radix_sort.cpp b/sorting/radix_sort.cpp index 09c91bb2248..e5bc3db8427 100644 --- a/sorting/radix_sort.cpp +++ b/sorting/radix_sort.cpp @@ -1,68 +1,58 @@ -#include -#include #include +#include #include -using namespace std; -void radixsort(int a[], int n) -{ - int count[10]; - int output[n]; - memset(output, 0, sizeof(output)); - memset(count, 0, sizeof(count)); - int max = 0; - for (int i = 0; i < n; ++i) - { - if (a[i] > max) - { - max = a[i]; - } - } - int maxdigits = 0; - while (max) - { - maxdigits++; - max /= 10; - } - for (int j = 0; j < maxdigits; j++) - { - for (int i = 0; i < n; i++) - { - int t = pow(10, j); - count[(a[i] % (10 * t)) / t]++; - } - int k = 0; - for (int p = 0; p < 10; p++) - { - for (int i = 0; i < n; i++) - { - int t = pow(10, j); - if ((a[i] % (10 * t)) / t == p) - { - output[k] = a[i]; - k++; - } - } - } - memset(count, 0, sizeof(count)); - for (int i = 0; i < n; ++i) - { - a[i] = output[i]; - } - } +#include + +void radixsort(int a[], int n) { + int count[10]; + int* output = new int[n]; + memset(output, 0, n * sizeof(*output)); + memset(count, 0, sizeof(count)); + int max = 0; + for (int i = 0; i < n; ++i) { + if (a[i] > max) { + max = a[i]; + } + } + int maxdigits = 0; + while (max) { + maxdigits++; + max /= 10; + } + for (int j = 0; j < maxdigits; j++) { + for (int i = 0; i < n; i++) { + int t = std::pow(10, j); + count[(a[i] % (10 * t)) / t]++; + } + int k = 0; + for (int p = 0; p < 10; p++) { + for (int i = 0; i < n; i++) { + int t = std::pow(10, j); + if ((a[i] % (10 * t)) / t == p) { + output[k] = a[i]; + k++; + } + } + } + memset(count, 0, sizeof(count)); + for (int i = 0; i < n; ++i) { + a[i] = output[i]; + } + } + delete[] output; } -void print(int a[], int n) -{ - for (int i = 0; i < n; ++i) - { - cout << a[i] << " "; - } - cout << endl; + +void print(int a[], int n) { + for (int i = 0; i < n; ++i) { + std::cout << a[i] << " "; + } + std::cout << std::endl; } -int main(int argc, char const *argv[]) -{ - int a[] = {170, 45, 75, 90, 802, 24, 2, 66}; - int n = sizeof(a) / sizeof(a[0]); - radixsort(a, n); - print(a, n); - return 0; + +int main(int argc, char const* argv[]) { + int a[] = {170, 45, 75, 90, 802, 24, 2, 66}; + int n = sizeof(a) / sizeof(a[0]); + radixsort(a, n); + print(a, n); + return 0; } \ No newline at end of file diff --git a/sorting/shell_sort.cpp b/sorting/shell_sort.cpp index b08c7ffd826..eb701478d4e 100644 --- a/sorting/shell_sort.cpp +++ b/sorting/shell_sort.cpp @@ -1,45 +1,37 @@ #include -using namespace std; -int main() -{ - int size = 10; - int array[size]; - // Input - cout << "\nHow many numbers do want to enter in unsorted array : "; - cin >> size; - cout << "\nEnter the numbers for unsorted array : "; - for (int i = 0; i < size; i++) - { - cin >> array[i]; - } +int main() { + int size = 10; + int* array = new int[size]; + // Input + std::cout << "\nHow many numbers do want to enter in unsorted array : "; + std::cin >> size; + std::cout << "\nEnter the numbers for unsorted array : "; + for (int i = 0; i < size; i++) { + std::cin >> array[i]; + } - // Sorting - for (int i = size / 2; i > 0; i = i / 2) - { - for (int j = i; j < size; j++) - { - for (int k = j - i; k >= 0; k = k - i) - { - if (array[k] < array[k + i]) - { - break; - } - else - { - int temp = array[k + i]; - array[k + i] = array[k]; - array[k] = temp; - } - } - } - } + // Sorting + for (int i = size / 2; i > 0; i = i / 2) { + for (int j = i; j < size; j++) { + for (int k = j - i; k >= 0; k = k - i) { + if (array[k] < array[k + i]) { + break; + } else { + int temp = array[k + i]; + array[k + i] = array[k]; + array[k] = temp; + } + } + } + } - // Output - cout << "\nSorted array : "; - for (int i = 0; i < size; ++i) - { - cout << array[i] << "\t"; - } - return 0; + // Output + std::cout << "\nSorted array : "; + for (int i = 0; i < size; ++i) { + std::cout << array[i] << "\t"; + } + + delete[] array; + return 0; } diff --git a/sorting/slow_sort.cpp b/sorting/slow_sort.cpp index f8f7e74b804..2872b37d88c 100644 --- a/sorting/slow_sort.cpp +++ b/sorting/slow_sort.cpp @@ -1,57 +1,55 @@ -//Returns the sorted vector after performing SlowSort -//It is a sorting algorithm that is of humorous nature and not useful. -//It's based on the principle of multiply and surrender, a tongue-in-cheek joke of divide and conquer. -//It was published in 1986 by Andrei Broder and Jorge Stolfi in their paper Pessimal Algorithms and Simplexity Analysis. -//This algorithm multiplies a single problem into multiple subproblems -//It is interesting because it is provably the least efficient sorting algorithm that can be built asymptotically, -//and with the restriction that such an algorithm, while being slow, must still all the time be working towards a result. +// Returns the sorted vector after performing SlowSort +// It is a sorting algorithm that is of humorous nature and not useful. +// It's based on the principle of multiply and surrender, a tongue-in-cheek joke +// of divide and conquer. It was published in 1986 by Andrei Broder and Jorge +// Stolfi in their paper Pessimal Algorithms and Simplexity Analysis. This +// algorithm multiplies a single problem into multiple subproblems It is +// interesting because it is provably the least efficient sorting algorithm that +// can be built asymptotically, and with the restriction that such an algorithm, +// while being slow, must still all the time be working towards a result. #include using namespace std; -void SlowSort(int a[], int i, int j) -{ - if (i >= j) - return; - int m = i + (j - i) / 2; //midpoint, implemented this way to avoid overflow - int temp; - SlowSort(a, i, m); - SlowSort(a, m + 1, j); - if (a[j] < a[m]) - { - temp = a[j]; //swapping a[j] & a[m] - a[j] = a[m]; - a[m] = temp; - } - SlowSort(a, i, j - 1); +void SlowSort(int a[], int i, int j) { + if (i >= j) return; + int m = i + (j - i) / 2; // midpoint, implemented this way to avoid + // overflow + int temp; + SlowSort(a, i, m); + SlowSort(a, m + 1, j); + if (a[j] < a[m]) { + temp = a[j]; // swapping a[j] & a[m] + a[j] = a[m]; + a[m] = temp; + } + SlowSort(a, i, j - 1); } -//Sample Main function +// Sample Main function -int main() -{ - int size; - cout << "\nEnter the number of elements : "; +int main() { + int size; + cout << "\nEnter the number of elements : "; - cin >> size; + cin >> size; - int arr[size]; + int *arr = new int[size]; - cout << "\nEnter the unsorted elements : "; + cout << "\nEnter the unsorted elements : "; - for (int i = 0; i < size; ++i) - { - cout << "\n"; - cin >> arr[i]; - } + for (int i = 0; i < size; ++i) { + cout << "\n"; + cin >> arr[i]; + } - SlowSort(arr, 0, size); + SlowSort(arr, 0, size); - cout << "Sorted array\n"; + cout << "Sorted array\n"; - for (int i = 0; i < size; ++i) - { - cout << arr[i] << " "; - } - return 0; + for (int i = 0; i < size; ++i) { + cout << arr[i] << " "; + } + delete[] arr; + return 0; } diff --git a/sorting/swap_sort.cpp b/sorting/swap_sort.cpp index a4ab1e57b66..2e59e2fb3bf 100644 --- a/sorting/swap_sort.cpp +++ b/sorting/swap_sort.cpp @@ -10,7 +10,7 @@ int minSwaps(int arr[], int n) { // Create an array of pairs where first // element is array element and second element // is position of first element - std::pair arrPos[n]; + std::pair *arrPos = new std::pair[n]; for (int i = 0; i < n; i++) { arrPos[i].first = arr[i]; arrPos[i].second = i; @@ -32,8 +32,7 @@ int minSwaps(int arr[], int n) { for (int i = 0; i < n; i++) { // already swapped and corrected or // already present at correct pos - if (vis[i] || arrPos[i].second == i) - continue; + if (vis[i] || arrPos[i].second == i) continue; // find out the number of node in // this cycle and add in ans @@ -53,6 +52,8 @@ int minSwaps(int arr[], int n) { } } + delete[] arrPos; + // Return result return ans; } diff --git a/sorting/tim_sort.cpp b/sorting/tim_sort.cpp index 14d3a04d049..94f5aa230b3 100644 --- a/sorting/tim_sort.cpp +++ b/sorting/tim_sort.cpp @@ -1,115 +1,103 @@ // C++ program to perform TimSort. +#include #include -using namespace std; + const int RUN = 32; - -// this function sorts array from left index to to right index which is of size atmost RUN -void insertionSort(int arr[], int left, int right) -{ - for (int i = left + 1; i <= right; i++) - { + +// this function sorts array from left index to to right index which is of size +// atmost RUN +void insertionSort(int arr[], int left, int right) { + for (int i = left + 1; i <= right; i++) { int temp = arr[i]; int j = i - 1; - while (arr[j] > temp && j >= left) - { - arr[j+1] = arr[j]; + while (arr[j] > temp && j >= left) { + arr[j + 1] = arr[j]; j--; } - arr[j+1] = temp; + arr[j + 1] = temp; } } - + // merge function merges the sorted runs -void merge(int arr[], int l, int m, int r) -{ +void merge(int arr[], int l, int m, int r) { // original array is broken in two parts, left and right array int len1 = m - l + 1, len2 = r - m; - int left[len1], right[len2]; - for (int i = 0; i < len1; i++) - left[i] = arr[l + i]; - for (int i = 0; i < len2; i++) - right[i] = arr[m + 1 + i]; - + int *left = new int[len1], *right = new int[len2]; + for (int i = 0; i < len1; i++) left[i] = arr[l + i]; + for (int i = 0; i < len2; i++) right[i] = arr[m + 1 + i]; + int i = 0; int j = 0; int k = l; - + // after comparing, we merge those two array in larger sub array - while (i < len1 && j < len2) - { - if (left[i] <= right[j]) - { + while (i < len1 && j < len2) { + if (left[i] <= right[j]) { arr[k] = left[i]; i++; - } - else - { + } else { arr[k] = right[j]; j++; } k++; } - + // copy remaining elements of left, if any - while (i < len1) - { + while (i < len1) { arr[k] = left[i]; k++; i++; } - + // copy remaining element of right, if any - while (j < len2) - { + while (j < len2) { arr[k] = right[j]; k++; j++; } + delete[] left; + delete[] right; } - + // iterative Timsort function to sort the array[0...n-1] (similar to merge sort) -void timSort(int arr[], int n) -{ +void timSort(int arr[], int n) { // Sort individual subarrays of size RUN - for (int i = 0; i < n; i+=RUN) - insertionSort(arr, i, min((i+31), (n-1))); - - // start merging from size RUN (or 32). It will merge to form size 64, then 128, 256 and so on .... - for (int size = RUN; size < n; size = 2*size) - { - // pick starting point of left sub array. We are going to merge arr[left..left+size-1] and arr[left+size, left+2*size-1] - // After every merge, we increase left by 2*size - for (int left = 0; left < n; left += 2*size) - { + for (int i = 0; i < n; i += RUN) + insertionSort(arr, i, std::min((i + 31), (n - 1))); + + // start merging from size RUN (or 32). It will merge to form size 64, then + // 128, 256 and so on .... + for (int size = RUN; size < n; size = 2 * size) { + // pick starting point of left sub array. We are going to merge + // arr[left..left+size-1] and arr[left+size, left+2*size-1] After every + // merge, we increase left by 2*size + for (int left = 0; left < n; left += 2 * size) { // find ending point of left sub array // mid+1 is starting point of right sub array int mid = left + size - 1; - int right = min((left + 2*size - 1), (n-1)); - + int right = std::min((left + 2 * size - 1), (n - 1)); + // merge sub array arr[left.....mid] & arr[mid+1....right] merge(arr, left, mid, right); } } } - + // utility function to print the Array -void printArray(int arr[], int n) -{ - for (int i = 0; i < n; i++) - printf("%d ", arr[i]); - printf("\n"); +void printArray(int arr[], int n) { + for (int i = 0; i < n; i++) printf("%d ", arr[i]); + std::cout << std::endl; } - + // Driver program to test above function -int main() -{ +int main() { int arr[] = {5, 21, 7, 23, 19}; - int n = sizeof(arr)/sizeof(arr[0]); + int n = sizeof(arr) / sizeof(arr[0]); printf("Given Array is\n"); printArray(arr, n); - + timSort(arr, n); - + printf("After Sorting Array is\n"); printArray(arr, n); return 0; From d3acc554c6b5f7ffa1a12ffb49d0323d852a3c20 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 13:07:14 -0400 Subject: [PATCH 105/433] cpplint issues fixed in sorting folder (cherry picked from commit 35c53760d34bc483ba737706937985346bf39fd8) --- sorting/radix_sort.cpp | 2 +- sorting/slow_sort.cpp | 16 ++++++++-------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/sorting/radix_sort.cpp b/sorting/radix_sort.cpp index e5bc3db8427..a0fbfe99ee5 100644 --- a/sorting/radix_sort.cpp +++ b/sorting/radix_sort.cpp @@ -55,4 +55,4 @@ int main(int argc, char const* argv[]) { radixsort(a, n); print(a, n); return 0; -} \ No newline at end of file +} diff --git a/sorting/slow_sort.cpp b/sorting/slow_sort.cpp index 2872b37d88c..b2627d12f3a 100644 --- a/sorting/slow_sort.cpp +++ b/sorting/slow_sort.cpp @@ -9,7 +9,6 @@ // while being slow, must still all the time be working towards a result. #include -using namespace std; void SlowSort(int a[], int i, int j) { if (i >= j) return; @@ -30,26 +29,27 @@ void SlowSort(int a[], int i, int j) { int main() { int size; - cout << "\nEnter the number of elements : "; + std::cout << "\nEnter the number of elements : "; - cin >> size; + std::cin >> size; int *arr = new int[size]; - cout << "\nEnter the unsorted elements : "; + std::cout << "\nEnter the unsorted elements : "; for (int i = 0; i < size; ++i) { - cout << "\n"; - cin >> arr[i]; + std::cout << "\n"; + std::cin >> arr[i]; } SlowSort(arr, 0, size); - cout << "Sorted array\n"; + std::cout << "Sorted array\n"; for (int i = 0; i < size; ++i) { - cout << arr[i] << " "; + std::cout << arr[i] << " "; } + delete[] arr; return 0; } From 6e6f92e7739526bda9772c0edcc433b01062fac3 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 26 May 2020 17:33:50 +0000 Subject: [PATCH 106/433] updating DIRECTORY.md --- DIRECTORY.md | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index 47842b9cad8..9a336c1a5b1 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -179,29 +179,29 @@ * [Ternary Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/ternary_search.cpp) ## Sorting - * [Beadsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/BeadSort.cpp) - * [Bitonicsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/BitonicSort.cpp) - * [Bubble Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Bubble%20Sort.cpp) - * [Bucketsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/bucketSort.cpp) - * [Cocktailselectionsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/CocktailSelectionSort.cpp) - * [Combsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/combsort.cpp) + * [Bead Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/bead_sort.cpp) + * [Bitonic Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/bitonic_sort.cpp) + * [Bubble Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/bubble_sort.cpp) + * [Bucket Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/bucket_sort.cpp) + * [Cocktail Selection Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/cocktail_selection_sort.cpp) + * [Comb Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/comb_sort.cpp) * [Counting Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Counting_Sort.cpp) - * [Countingsortstring](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/CountingSortString.cpp) + * [Counting Sort String](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/counting_sort_string.cpp) * [Heap Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/heap_sort.cpp) - * [Insertion Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Insertion%20Sort.cpp) + * [Insertion Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/insertion_sort.cpp) * [Library Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/library_sort.cpp) - * [Merge Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Merge%20Sort.cpp) + * [Merge Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/merge_sort.cpp) * [Non Recursive Merge Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/non_recursive_merge_sort.cpp) - * [Numericstringsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/NumericStringSort.cpp) - * [Oddeven Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/OddEven%20Sort.cpp) - * [Quick Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Quick%20Sort.cpp) - * [Radix Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Radix%20Sort.cpp) - * [Selection Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Selection%20Sort.cpp) - * [Shell Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Shell%20Sort.cpp) + * [Numeric String Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/numeric_string_sort.cpp) + * [Odd Even Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/odd_even_sort.cpp) + * [Quick Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/quick_sort.cpp) + * [Radix Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/radix_sort.cpp) + * [Selection Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/selection_sort.cpp) + * [Shell Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/shell_sort.cpp) * [Shell Sort2](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/shell_sort2.cpp) - * [Slow Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Slow%20Sort.cpp) + * [Slow Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/slow_sort.cpp) * [Swap Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/swap_sort.cpp) - * [Tim Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Tim%20Sort.cpp) + * [Tim Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/tim_sort.cpp) ## Strings * [Brute Force String Searching](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/strings/brute_force_string_searching.cpp) From 07ebe713b01d26bd32b0dc1c8965459e7837f390 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 13:41:11 -0400 Subject: [PATCH 107/433] added deleted files back - not really needed but there is a redundant github action that required it --- sorting/doxy.txt | 374 +++++++++++++++++++++++++++++++++++++++++++++++ sorting/makefile | 11 ++ 2 files changed, 385 insertions(+) create mode 100644 sorting/doxy.txt create mode 100644 sorting/makefile diff --git a/sorting/doxy.txt b/sorting/doxy.txt new file mode 100644 index 00000000000..68079276e7b --- /dev/null +++ b/sorting/doxy.txt @@ -0,0 +1,374 @@ +# Doxyfile 1.8.13 +#This configuration file has been generated from Doxygen template. +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- +DOXYFILE_ENCODING = UTF-8 +PROJECT_NAME = "My Project" +PROJECT_NUMBER = +PROJECT_BRIEF = +PROJECT_LOGO = +OUTPUT_DIRECTORY = +CREATE_SUBDIRS = NO +ALLOW_UNICODE_NAMES = NO +OUTPUT_LANGUAGE = English +BRIEF_MEMBER_DESC = YES +REPEAT_BRIEF = YES +ABBREVIATE_BRIEF = "The $name class" \ + "The $name widget" \ + "The $name file" \ + is \ + provides \ + specifies \ + contains \ + represents \ + a \ + an \ + the +ALWAYS_DETAILED_SEC = NO +INLINE_INHERITED_MEMB = NO +FULL_PATH_NAMES = YES +STRIP_FROM_PATH = +STRIP_FROM_INC_PATH = +SHORT_NAMES = NO +JAVADOC_AUTOBRIEF = NO +QT_AUTOBRIEF = NO +MULTILINE_CPP_IS_BRIEF = NO +INHERIT_DOCS = YES +SEPARATE_MEMBER_PAGES = NO +TAB_SIZE = 4 +ALIASES = +TCL_SUBST = +OPTIMIZE_OUTPUT_FOR_C = NO +OPTIMIZE_OUTPUT_JAVA = NO +OPTIMIZE_FOR_FORTRAN = NO +OPTIMIZE_OUTPUT_VHDL = NO +EXTENSION_MAPPING = +MARKDOWN_SUPPORT = YES +TOC_INCLUDE_HEADINGS = 0 +AUTOLINK_SUPPORT = YES +BUILTIN_STL_SUPPORT = NO +CPP_CLI_SUPPORT = NO +SIP_SUPPORT = NO +IDL_PROPERTY_SUPPORT = YES +DISTRIBUTE_GROUP_DOC = NO +GROUP_NESTED_COMPOUNDS = NO +SUBGROUPING = YES +INLINE_GROUPED_CLASSES = NO +INLINE_SIMPLE_STRUCTS = NO +TYPEDEF_HIDES_STRUCT = NO +LOOKUP_CACHE_SIZE = 0 +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- +EXTRACT_ALL = NO +EXTRACT_PRIVATE = NO +EXTRACT_PACKAGE = NO +EXTRACT_STATIC = NO +EXTRACT_LOCAL_CLASSES = YES +EXTRACT_LOCAL_METHODS = NO +EXTRACT_ANON_NSPACES = NO +HIDE_UNDOC_MEMBERS = NO +HIDE_UNDOC_CLASSES = NO +HIDE_FRIEND_COMPOUNDS = NO +HIDE_IN_BODY_DOCS = NO +INTERNAL_DOCS = NO +CASE_SENSE_NAMES = YES +HIDE_SCOPE_NAMES = NO +HIDE_COMPOUND_REFERENCE= NO +SHOW_INCLUDE_FILES = YES +SHOW_GROUPED_MEMB_INC = NO +FORCE_LOCAL_INCLUDES = NO +INLINE_INFO = YES +SORT_MEMBER_DOCS = YES +SORT_BRIEF_DOCS = NO +SORT_MEMBERS_CTORS_1ST = NO +SORT_GROUP_NAMES = NO +SORT_BY_SCOPE_NAME = NO +STRICT_PROTO_MATCHING = NO +GENERATE_TODOLIST = YES +GENERATE_TESTLIST = YES +GENERATE_BUGLIST = YES +GENERATE_DEPRECATEDLIST= YES +ENABLED_SECTIONS = +MAX_INITIALIZER_LINES = 30 +SHOW_USED_FILES = YES +SHOW_FILES = YES +SHOW_NAMESPACES = YES +FILE_VERSION_FILTER = +LAYOUT_FILE = +CITE_BIB_FILES = +#--------------------------------------------------------------------------- +# Configuration options related to warning and progress messages +#--------------------------------------------------------------------------- +QUIET = NO +WARNINGS = YES +WARN_IF_UNDOCUMENTED = YES +WARN_IF_DOC_ERROR = YES +WARN_NO_PARAMDOC = NO +WARN_AS_ERROR = NO +WARN_FORMAT = "$file:$line: $text" +WARN_LOGFILE = +#--------------------------------------------------------------------------- +# Configuration options related to the input files +#--------------------------------------------------------------------------- +INPUT = +INPUT_ENCODING = UTF-8 +FILE_PATTERNS = *.c \ + *.cc \ + *.cxx \ + *.cpp \ + *.c++ \ + *.java \ + *.ii \ + *.ixx \ + *.ipp \ + *.i++ \ + *.inl \ + *.idl \ + *.ddl \ + *.odl \ + *.h \ + *.hh \ + *.hxx \ + *.hpp \ + *.h++ \ + *.cs \ + *.d \ + *.php \ + *.php4 \ + *.php5 \ + *.phtml \ + *.inc \ + *.m \ + *.markdown \ + *.md \ + *.mm \ + *.dox \ + *.py \ + *.pyw \ + *.f90 \ + *.f95 \ + *.f03 \ + *.f08 \ + *.f \ + *.for \ + *.tcl \ + *.vhd \ + *.vhdl \ + *.ucf \ + *.qsf +RECURSIVE = NO +EXCLUDE = +EXCLUDE_SYMLINKS = NO +EXCLUDE_PATTERNS = +EXCLUDE_SYMBOLS = +EXAMPLE_PATH = +EXAMPLE_PATTERNS = * +EXAMPLE_RECURSIVE = NO +IMAGE_PATH = +INPUT_FILTER = +FILTER_PATTERNS = +FILTER_SOURCE_FILES = NO +FILTER_SOURCE_PATTERNS = +USE_MDFILE_AS_MAINPAGE = +#--------------------------------------------------------------------------- +# Configuration options related to source browsing +#--------------------------------------------------------------------------- +SOURCE_BROWSER = NO +INLINE_SOURCES = NO +STRIP_CODE_COMMENTS = YES +REFERENCED_BY_RELATION = NO +REFERENCES_RELATION = NO +REFERENCES_LINK_SOURCE = YES +SOURCE_TOOLTIPS = YES +USE_HTAGS = NO +VERBATIM_HEADERS = YES +CLANG_ASSISTED_PARSING = NO +CLANG_OPTIONS = +#--------------------------------------------------------------------------- +# Configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- +ALPHABETICAL_INDEX = YES +COLS_IN_ALPHA_INDEX = 5 +IGNORE_PREFIX = +#--------------------------------------------------------------------------- +# Configuration options related to the HTML output +#--------------------------------------------------------------------------- +GENERATE_HTML = YES +HTML_OUTPUT = html +HTML_FILE_EXTENSION = .html +HTML_HEADER = +HTML_FOOTER = +HTML_STYLESHEET = +HTML_EXTRA_STYLESHEET = +HTML_EXTRA_FILES = +HTML_COLORSTYLE_HUE = 220 +HTML_COLORSTYLE_SAT = 100 +HTML_COLORSTYLE_GAMMA = 80 +HTML_TIMESTAMP = NO +HTML_DYNAMIC_SECTIONS = NO +HTML_INDEX_NUM_ENTRIES = 100 +GENERATE_DOCSET = NO +DOCSET_FEEDNAME = "Doxygen generated docs" +DOCSET_BUNDLE_ID = org.doxygen.Project +DOCSET_PUBLISHER_ID = org.doxygen.Publisher +DOCSET_PUBLISHER_NAME = Publisher +GENERATE_HTMLHELP = NO +CHM_FILE = +HHC_LOCATION = +GENERATE_CHI = NO +CHM_INDEX_ENCODING = +BINARY_TOC = NO +TOC_EXPAND = NO +GENERATE_QHP = NO +QCH_FILE = +QHP_NAMESPACE = org.doxygen.Project +QHP_VIRTUAL_FOLDER = doc +QHP_CUST_FILTER_NAME = +QHP_CUST_FILTER_ATTRS = +QHP_SECT_FILTER_ATTRS = +QHG_LOCATION = +GENERATE_ECLIPSEHELP = NO +ECLIPSE_DOC_ID = org.doxygen.Project +DISABLE_INDEX = NO +GENERATE_TREEVIEW = NO +ENUM_VALUES_PER_LINE = 4 +TREEVIEW_WIDTH = 250 +EXT_LINKS_IN_WINDOW = NO +FORMULA_FONTSIZE = 10 +FORMULA_TRANSPARENT = YES +USE_MATHJAX = NO +MATHJAX_FORMAT = HTML-CSS +MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest +MATHJAX_EXTENSIONS = +MATHJAX_CODEFILE = +SEARCHENGINE = YES +SERVER_BASED_SEARCH = NO +EXTERNAL_SEARCH = NO +SEARCHENGINE_URL = +SEARCHDATA_FILE = searchdata.xml +EXTERNAL_SEARCH_ID = +EXTRA_SEARCH_MAPPINGS = +#--------------------------------------------------------------------------- +# Configuration options related to the LaTeX output +#--------------------------------------------------------------------------- +GENERATE_LATEX = NO +LATEX_OUTPUT = latex +LATEX_CMD_NAME = latex +MAKEINDEX_CMD_NAME = makeindex +COMPACT_LATEX = NO +PAPER_TYPE = a4 +EXTRA_PACKAGES = +LATEX_HEADER = +LATEX_FOOTER = +LATEX_EXTRA_STYLESHEET = +LATEX_EXTRA_FILES = +PDF_HYPERLINKS = YES +USE_PDFLATEX = YES +LATEX_BATCHMODE = NO +LATEX_HIDE_INDICES = NO +LATEX_SOURCE_CODE = NO +LATEX_BIB_STYLE = plain +LATEX_TIMESTAMP = NO +#--------------------------------------------------------------------------- +# Configuration options related to the RTF output +#--------------------------------------------------------------------------- +GENERATE_RTF = NO +RTF_OUTPUT = rtf +COMPACT_RTF = NO +RTF_HYPERLINKS = NO +RTF_STYLESHEET_FILE = +RTF_EXTENSIONS_FILE = +RTF_SOURCE_CODE = NO +#--------------------------------------------------------------------------- +# Configuration options related to the man page output +#--------------------------------------------------------------------------- +GENERATE_MAN = NO +MAN_OUTPUT = man +MAN_EXTENSION = .3 +MAN_SUBDIR = +MAN_LINKS = NO +#--------------------------------------------------------------------------- +# Configuration options related to the XML output +#--------------------------------------------------------------------------- +GENERATE_XML = NO +XML_OUTPUT = xml +XML_PROGRAMLISTING = YES +#--------------------------------------------------------------------------- +# Configuration options related to the DOCBOOK output +#--------------------------------------------------------------------------- +GENERATE_DOCBOOK = NO +DOCBOOK_OUTPUT = docbook +DOCBOOK_PROGRAMLISTING = NO +#--------------------------------------------------------------------------- +# Configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- +GENERATE_AUTOGEN_DEF = NO +#--------------------------------------------------------------------------- +# Configuration options related to the Perl module output +#--------------------------------------------------------------------------- +GENERATE_PERLMOD = NO +PERLMOD_LATEX = NO +PERLMOD_PRETTY = YES +PERLMOD_MAKEVAR_PREFIX = +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- +ENABLE_PREPROCESSING = YES +MACRO_EXPANSION = NO +EXPAND_ONLY_PREDEF = NO +SEARCH_INCLUDES = YES +INCLUDE_PATH = +INCLUDE_FILE_PATTERNS = +PREDEFINED = +EXPAND_AS_DEFINED = +SKIP_FUNCTION_MACROS = YES +#--------------------------------------------------------------------------- +# Configuration options related to external references +#--------------------------------------------------------------------------- +TAGFILES = +GENERATE_TAGFILE = +ALLEXTERNALS = NO +EXTERNAL_GROUPS = YES +EXTERNAL_PAGES = YES +PERL_PATH = /usr/bin/perl +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- +CLASS_DIAGRAMS = YES +MSCGEN_PATH = +DIA_PATH = +HIDE_UNDOC_RELATIONS = YES +HAVE_DOT = YES +DOT_NUM_THREADS = 0 +DOT_FONTNAME = Helvetica +DOT_FONTSIZE = 10 +DOT_FONTPATH = +CLASS_GRAPH = YES +COLLABORATION_GRAPH = YES +GROUP_GRAPHS = YES +UML_LOOK = NO +UML_LIMIT_NUM_FIELDS = 10 +TEMPLATE_RELATIONS = NO +INCLUDE_GRAPH = YES +INCLUDED_BY_GRAPH = YES +CALL_GRAPH = NO +CALLER_GRAPH = NO +GRAPHICAL_HIERARCHY = YES +DIRECTORY_GRAPH = YES +DOT_IMAGE_FORMAT = png +INTERACTIVE_SVG = NO +DOT_PATH = +DOTFILE_DIRS = +MSCFILE_DIRS = +DIAFILE_DIRS = +PLANTUML_JAR_PATH = +PLANTUML_CFG_FILE = +PLANTUML_INCLUDE_PATH = +DOT_GRAPH_MAX_NODES = 50 +MAX_DOT_GRAPH_DEPTH = 0 +DOT_TRANSPARENT = NO +DOT_MULTI_TARGETS = NO +GENERATE_LEGEND = YES +DOT_CLEANUP = YES diff --git a/sorting/makefile b/sorting/makefile new file mode 100644 index 00000000000..21d3186c698 --- /dev/null +++ b/sorting/makefile @@ -0,0 +1,11 @@ +non_recursive_merge_sort: non_recursive_merge_sort.cpp + g++ -std=c++17 -o non_recursive_merge_sort non_recursive_merge_sort.cpp +.PHONY: test +.PHONY: doc +.PHONY: clean +test: non_recursive_merge_sort + ./non_recursive_merge_sort +doc: doxy.txt + doxygen doxy.txt +clean: + rm -fr non_recursive_merge_sort html From 286ca5c5106cc8b7620a3da6f73c006363caf626 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Tue, 26 May 2020 16:40:09 -0400 Subject: [PATCH 108/433] include search folder in cmake --- CMakeLists.txt | 2 + search/CMakeLists.txt | 18 +++ search/Linear Search.cpp | 47 ------ search/exponential_search.cpp | 63 ++++---- ...n Search.cpp => interpolation_search2.cpp} | 23 ++- search/jump_search.cpp | 35 ++--- search/linear_search.cpp | 39 +++++ search/median_search.cpp | 101 +++++------- search/searching.cpp | 52 +++---- search/ternary_search.cpp | 147 ++++++++---------- 10 files changed, 253 insertions(+), 274 deletions(-) create mode 100644 search/CMakeLists.txt delete mode 100644 search/Linear Search.cpp rename search/{Interpolation Search.cpp => interpolation_search2.cpp} (50%) create mode 100644 search/linear_search.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index f2940c9623d..aafeb69d3c4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -24,6 +24,7 @@ find_package(Doxygen OPTIONAL_COMPONENTS dot dia) if(DOXYGEN_FOUND) set(DOXYGEN_GENERATE_MAN NO) set(DOXYGEN_USE_MATHJAX YES) + set(DOXYGEN_FILE_PATTERNS *.cpp *.h *.hpp *.md) set(DOXYGEN_GENERATE_HTML YES) set(DOXYGEN_INLINE_SOURCES YES) set(DOXYGEN_CREATE_SUBDIRS YES) @@ -50,6 +51,7 @@ endif() add_subdirectory(math) add_subdirectory(others) +add_subdirectory(search) add_subdirectory(strings) add_subdirectory(sorting) add_subdirectory(computer_oriented_statistical_methods) diff --git a/search/CMakeLists.txt b/search/CMakeLists.txt new file mode 100644 index 00000000000..5fd1ae59113 --- /dev/null +++ b/search/CMakeLists.txt @@ -0,0 +1,18 @@ +# If necessary, use the RELATIVE flag, otherwise each source file may be listed +# with full pathname. RELATIVE may makes it easier to extract an executable name +# automatically. +file( GLOB APP_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp ) +# file( GLOB APP_SOURCES ${CMAKE_SOURCE_DIR}/*.c ) +# AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR} APP_SOURCES) +foreach( testsourcefile ${APP_SOURCES} ) + # I used a simple string replace, to cut off .cpp. + string( REPLACE ".cpp" "" testname ${testsourcefile} ) + add_executable( ${testname} ${testsourcefile} ) + + set_target_properties(${testname} PROPERTIES LINKER_LANGUAGE CXX) + if(OpenMP_CXX_FOUND) + target_link_libraries(${testname} OpenMP::OpenMP_CXX) + endif() + install(TARGETS ${testname} DESTINATION "bin/search") + +endforeach( testsourcefile ${APP_SOURCES} ) diff --git a/search/Linear Search.cpp b/search/Linear Search.cpp deleted file mode 100644 index 97e82043712..00000000000 --- a/search/Linear Search.cpp +++ /dev/null @@ -1,47 +0,0 @@ -#include -using namespace std; - -int LinearSearch(int *array, int size, int key) -{ - for (int i = 0; i < size; ++i) - { - if (array[i] == key) - { - return i; - } - } - - return -1; -} - -int main() -{ - int size; - cout << "\nEnter the size of the Array : "; - cin >> size; - - int array[size]; - int key; - - //Input array - cout << "\nEnter the Array of " << size << " numbers : "; - for (int i = 0; i < size; i++) - { - cin >> array[i]; - } - - cout << "\nEnter the number to be searched : "; - cin >> key; - - int index = LinearSearch(array, size, key); - if (index != -1) - { - cout << "\nNumber found at index : " << index; - } - else - { - cout << "\nNot found"; - } - - return 0; -} diff --git a/search/exponential_search.cpp b/search/exponential_search.cpp index b8343fa0214..5f9e6421766 100644 --- a/search/exponential_search.cpp +++ b/search/exponential_search.cpp @@ -1,23 +1,28 @@ // Copyright 2020 Divide-et-impera-11 -#include +#include +#include #include #include -using namespaces std; + // Binary Search Algorithm(use by struzik algorithm) // Time Complexity O(log n) where 'n' is the number of elements // Worst Time Complexity O(log n) // Best Time Complexity Ω(1) // Space Complexity O(1) // Auxiliary Space Complexity O(1) -template inline Type* binary_s(Type *array, size_t size, Type key) { -int32_t lower_index(0), upper_index(size - 1), middle_index; -while (lower_index <= upper_index) { - middle_index = floor((lower_index + upper_index) / 2); - if (*(array + middle_index) < key) lower_index = (middle_index + 1); - else if (*(array + middle_index) > key)upper_index = (middle_index - 1); - else return (array + middle_index); - } -return nullptr; +template +inline Type* binary_s(Type* array, size_t size, Type key) { + int32_t lower_index(0), upper_index(size - 1), middle_index; + while (lower_index <= upper_index) { + middle_index = std::floor((lower_index + upper_index) / 2); + if (*(array + middle_index) < key) + lower_index = (middle_index + 1); + else if (*(array + middle_index) > key) + upper_index = (middle_index - 1); + else + return (array + middle_index); + } + return nullptr; } // Struzik Search Algorithm(Exponential) // Time Complexity O(log i)where i is the position of search key in the list @@ -32,25 +37,27 @@ If the key is larger than the last element of array, the start of block(block_front) will be equal to the end of block(block_size) and the algorithm return null ponter, every other cases the algoritm return fom the loop. */ -template Type* struzik_search(Type* array, size_t size, Type key) { - uint32_t block_front(0), block_size = size == 0 ? 0 : 1; - while (block_front != block_size) { +template +Type* struzik_search(Type* array, size_t size, Type key) { + uint32_t block_front(0), block_size = size == 0 ? 0 : 1; + while (block_front != block_size) { if (*(array + block_size - 1) < key) { - block_front = block_size; - (block_size * 2 - 1 < size) ? (block_size *= 2) : block_size = size; - continue; + block_front = block_size; + (block_size * 2 - 1 < size) ? (block_size *= 2) : block_size = size; + continue; } - return binary_s(array + block_front, (block_size - block_front), key); - } -return nullptr; + return binary_s(array + block_front, (block_size - block_front), + key); + } + return nullptr; } int main() { -// TEST CASES -int *sorted_array = new int[7]{7, 10, 15, 23, 70, 105, 203}; -assert(struzik_search(sorted_array, 7, 0) == nullptr); -assert(struzik_search(sorted_array, 7, 1000) == nullptr); -assert(struzik_search(sorted_array, 7, 50) == nullptr); -assert(struzik_search(sorted_array, 7, 7) == sorted_array); -// TEST CASES -return 0; + // TEST CASES + int* sorted_array = new int[7]{7, 10, 15, 23, 70, 105, 203}; + assert(struzik_search(sorted_array, 7, 0) == nullptr); + assert(struzik_search(sorted_array, 7, 1000) == nullptr); + assert(struzik_search(sorted_array, 7, 50) == nullptr); + assert(struzik_search(sorted_array, 7, 7) == sorted_array); + // TEST CASES + return 0; } diff --git a/search/Interpolation Search.cpp b/search/interpolation_search2.cpp similarity index 50% rename from search/Interpolation Search.cpp rename to search/interpolation_search2.cpp index f52ce4f4fb1..0e6d3b79d36 100644 --- a/search/Interpolation Search.cpp +++ b/search/interpolation_search2.cpp @@ -1,31 +1,30 @@ #include -int InterpolationSearch(int A[], int n, int x) -{ +int InterpolationSearch(int A[], int n, int x) { int low = 0; int high = n - 1; - while (low <= high) - { + while (low <= high) { int mid = low + (((high - 1) * (x - A[low])) / (A[high] - A[low])); if (x == A[mid]) - return mid; // Found x, return (exit) + return mid; // Found x, return (exit) else if (x < A[mid]) - high = mid - 1; // X lies before mid + high = mid - 1; // X lies before mid else - low = mid + 1; // x lies after mid + low = mid + 1; // x lies after mid } return -1; } -int main() -{ +int main() { int A[] = {2, 4, 5, 7, 13, 14, 15, 23}; int x = 17; - int index = InterpolationSearch(A, 8, x); // passed array A inside the InterpolationSearch function + int index = InterpolationSearch( + A, 8, x); // passed array A inside the InterpolationSearch function if (index != -1) std::cout << "Number " << x << " is at " << index; else std::cout << "Number " << x << " not found"; } -// randomly set x bcoz array was defined by us , therefore not reasonable for asking input. -// We could have asked for input if array elements were inputed by the user. +// randomly set x bcoz array was defined by us , therefore not reasonable for +// asking input. We could have asked for input if array elements were inputed by +// the user. diff --git a/search/jump_search.cpp b/search/jump_search.cpp index 0ee7e4e001d..aa2ee0bdb3e 100644 --- a/search/jump_search.cpp +++ b/search/jump_search.cpp @@ -1,47 +1,40 @@ // C++ program to implement Jump Search -#include -using namespace std; +#include +#include +#include -int jumpSearch(int arr[], int x, int n) -{ +int jumpSearch(int arr[], int x, int n) { // Finding block size to be jumped - int step = sqrt(n); + int step = std::sqrt(n); // Finding the block where element is // present (if it is present) int prev = 0; - while (arr[min(step, n)-1] < x) - { + while (arr[std::min(step, n) - 1] < x) { prev = step; - step += sqrt(n); - if (prev >= n) - return -1; + step += std::sqrt(n); + if (prev >= n) return -1; } // Doing a linear search for x in block // beginning with prev. - while (arr[prev] < x) - { + while (arr[prev] < x) { prev++; // If we reached next block or end of // array, element is not present. - if (prev == min(step, n)) - return -1; + if (prev == std::min(step, n)) return -1; } // If element is found - if (arr[prev] == x) - return prev; + if (arr[prev] == x) return prev; return -1; } // Driver program to test function -int main() -{ - int arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, - 34, 55, 89, 144, 233, 377, 610 }; +int main() { + int arr[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610}; int x = 55; int n = sizeof(arr) / sizeof(arr[0]); @@ -49,6 +42,6 @@ int main() int index = jumpSearch(arr, x, n); // Print the index where 'x' is located - cout << "\nNumber " << x << " is at index " << index; + std::cout << "\nNumber " << x << " is at index " << index; return 0; } diff --git a/search/linear_search.cpp b/search/linear_search.cpp new file mode 100644 index 00000000000..8849549e54d --- /dev/null +++ b/search/linear_search.cpp @@ -0,0 +1,39 @@ +#include + +int LinearSearch(int *array, int size, int key) { + for (int i = 0; i < size; ++i) { + if (array[i] == key) { + return i; + } + } + + return -1; +} + +int main() { + int size; + std::cout << "\nEnter the size of the Array : "; + std::cin >> size; + + int *array = new int[size]; + int key; + + // Input array + std::cout << "\nEnter the Array of " << size << " numbers : "; + for (int i = 0; i < size; i++) { + std::cin >> array[i]; + } + + std::cout << "\nEnter the number to be searched : "; + std::cin >> key; + + int index = LinearSearch(array, size, key); + if (index != -1) { + std::cout << "\nNumber found at index : " << index; + } else { + std::cout << "\nNot found"; + } + + delete[] array; + return 0; +} diff --git a/search/median_search.cpp b/search/median_search.cpp index be95b599f94..fa8ef38268b 100644 --- a/search/median_search.cpp +++ b/search/median_search.cpp @@ -1,72 +1,57 @@ -#include -#include -#include -#include -#include -#include -#include -using namespace std; -vectorv; -vectors1; -vectors2; -vectors3; +#include +#include +#include +#include +#include +#include +#include + +std::vector v; +std::vector s1; +std::vector s2; +std::vector s3; + template -void comp(X x) -{ - if(s1.size()>=x && s1.size()+s2.size()x) - { - sort(s1.begin(),s1.end()); - cout<x) - { - sort(s3.begin(),s3.end()); - cout<= x && s1.size() + s2.size() < x) { + std::cout << s2[0] << " is the " << x + 1 << "th element from front"; + } else if (s1.size() > x) { + std::sort(s1.begin(), s1.end()); + std::cout << s1[x] << " is the " << x + 1 << "th element from front"; + } else if (s1.size() + s2.size() <= x && s3.size() > x) { + std::sort(s3.begin(), s3.end()); + std::cout << s3[x - s1.size() - s2.size()] << " is the " << x + 1 + << "th element from front"; + } else { + std::cout << x + 1 << " is invalid location"; } } -int main() -{ - for(int i=0;i<1000;i++) - { - v.push_back(rand()%1000); +int main() { + for (int i = 0; i < 1000; i++) { + v.push_back(std::rand() % 1000); } - for(int r:v) - { - cout<>x; - comp(x-1); + std::cout << "enter the no. to be searched form begining:- "; + std::cin >> x; + comp(x - 1); return 0; } diff --git a/search/searching.cpp b/search/searching.cpp index 6a9dcac7dd9..d0161973811 100644 --- a/search/searching.cpp +++ b/search/searching.cpp @@ -1,38 +1,32 @@ +#include #include #include -#include -using namespace std; char paragraph; -int main() -{ - string paragraph; - cout << "Please enter your paragraph: \n"; - getline(cin, paragraph); - cout << "\nHello, your paragraph is:\n " << paragraph << "!\n"; - cout << "\nThe size of your paragraph = " << paragraph.size() << " characters. \n\n"; +int main() { + std::string paragraph; + std::cout << "Please enter your paragraph: \n"; + std::getline(std::cin, paragraph); + std::cout << "\nHello, your paragraph is:\n " << paragraph << "!\n"; + std::cout << "\nThe size of your paragraph = " << paragraph.size() + << " characters. \n\n"; - if (paragraph.empty()) - { - cout << "\nThe paragraph is empty" << endl; - } - else - { - while (true) - { - string word; - cout << "Please enter the word you are searching for: "; - getline(cin, word); - cout << "Hello, your word is " << word << "!\n"; - if (paragraph.find(word) == string::npos) - { - cout << word << " does not exist in the sentence" << endl; - } - else - { - cout << "The word " << word << " is now found at location " << paragraph.find(word) << endl - << endl; + if (paragraph.empty()) { + std::cout << "\nThe paragraph is empty" << std::endl; + } else { + while (true) { + std::string word; + std::cout << "Please enter the word you are searching for: "; + std::getline(std::cin, word); + std::cout << "Hello, your word is " << word << "!\n"; + if (paragraph.find(word) == std::string::npos) { + std::cout << word << " does not exist in the sentence" + << std::endl; + } else { + std::cout << "The word " << word << " is now found at location " + << paragraph.find(word) << std::endl + << std::endl; } system("pause"); } diff --git a/search/ternary_search.cpp b/search/ternary_search.cpp index 4cb8d19d996..4d1918d482d 100644 --- a/search/ternary_search.cpp +++ b/search/ternary_search.cpp @@ -3,16 +3,15 @@ * It does this by dividing the search space by 3 parts and * using its property (usually monotonic property) to find * the desired index. - * + * * Time Complexity : O(log3 n) * Space Complexity : O(1) (without the array) */ #include -using namespace std; /* - * The absolutePrecision can be modified to fit preference but + * The absolutePrecision can be modified to fit preference but * it is recommended to not go lower than 10 due to errors that * may occur. * @@ -30,99 +29,89 @@ int A[MAX] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 10}; /* * get_input function is to receive input from standard IO */ -void get_input() -{ - // TODO: Get input from STDIO or write input to memory as done above. +void get_input() { + // TODO(christianbender): Get input from STDIO or write input to memory as + // done above. } /* - * This is the iterative method of the ternary search which returns the index of the element. + * This is the iterative method of the ternary search which returns the index of + * the element. */ -int it_ternary_search(int left, int right, int A[], int target) -{ - while (1) - { - if (left < right) - { - if (right - left < absolutePrecision) - { - for (int i = left; i <= right; i++) - if (A[i] == target) - return i; - - return -1; - } - - int oneThird = (left + right) / 3 + 1; - int twoThird = (left + right) * 2 / 3 + 1; - - if (A[oneThird] == target) - return oneThird; - else if (A[twoThird] == target) - return twoThird; - - else if (target > A[twoThird]) - left = twoThird + 1; - else if (target < A[oneThird]) - right = oneThird - 1; - - else - left = oneThird + 1, right = twoThird - 1; +int it_ternary_search(int left, int right, int A[], int target) { + while (1) { + if (left < right) { + if (right - left < absolutePrecision) { + for (int i = left; i <= right; i++) + if (A[i] == target) return i; + + return -1; + } + + int oneThird = (left + right) / 3 + 1; + int twoThird = (left + right) * 2 / 3 + 1; + + if (A[oneThird] == target) + return oneThird; + else if (A[twoThird] == target) + return twoThird; + + else if (target > A[twoThird]) + left = twoThird + 1; + else if (target < A[oneThird]) + right = oneThird - 1; + + else + left = oneThird + 1, right = twoThird - 1; + } else { + return -1; + } } - else - return -1; - } } -/* - * This is the recursive method of the ternary search which returns the index of the element. +/* + * This is the recursive method of the ternary search which returns the index of + * the element. */ -int rec_ternary_search(int left, int right, int A[], int target) -{ - if (left < right) - { - if (right - left < absolutePrecision) - { - for (int i = left; i <= right; i++) - if (A[i] == target) - return i; - - return -1; - } +int rec_ternary_search(int left, int right, int A[], int target) { + if (left < right) { + if (right - left < absolutePrecision) { + for (int i = left; i <= right; i++) + if (A[i] == target) return i; - int oneThird = (left + right) / 3 + 1; - int twoThird = (left + right) * 2 / 3 + 1; + return -1; + } - if (A[oneThird] == target) - return oneThird; - if (A[twoThird] == target) - return twoThird; + int oneThird = (left + right) / 3 + 1; + int twoThird = (left + right) * 2 / 3 + 1; - if (target < A[oneThird]) - return rec_ternary_search(left, oneThird - 1, A, target); - if (target > A[twoThird]) - return rec_ternary_search(twoThird + 1, right, A, target); + if (A[oneThird] == target) return oneThird; + if (A[twoThird] == target) return twoThird; - return rec_ternary_search(oneThird + 1, twoThird - 1, A, target); - } - else - return -1; + if (target < A[oneThird]) + return rec_ternary_search(left, oneThird - 1, A, target); + if (target > A[twoThird]) + return rec_ternary_search(twoThird + 1, right, A, target); + + return rec_ternary_search(oneThird + 1, twoThird - 1, A, target); + } else { + return -1; + } } /* * ternary_search is a template function - * You could either use it_ternary_search or rec_ternary_search according to preference. + * You could either use it_ternary_search or rec_ternary_search according to + * preference. */ -void ternary_search(int N, int A[], int target) -{ - cout << it_ternary_search(0, N - 1, A, target) << '\t'; - cout << rec_ternary_search(0, N - 1, A, target) << '\t'; - cout << '\n'; +void ternary_search(int N, int A[], int target) { + std::cout << it_ternary_search(0, N - 1, A, target) << '\t'; + std::cout << rec_ternary_search(0, N - 1, A, target) << '\t'; + std::cout << std::endl; } -int main() -{ - get_input(); - ternary_search(N, A, _target); - return 0; +int main() { + get_input(); + ternary_search(N, A, _target); + return 0; } From 0aa566757ebdbd2e72af57a2fbfe51769bc2d6a6 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 26 May 2020 20:40:33 +0000 Subject: [PATCH 109/433] updating DIRECTORY.md --- DIRECTORY.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index 9a336c1a5b1..ba455f2c118 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -170,10 +170,10 @@ * [Binary Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/binary_search.cpp) * [Exponential Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/exponential_search.cpp) * [Hash Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/hash_search.cpp) - * [Interpolation Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/Interpolation%20Search.cpp) * [Interpolation Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/interpolation_search.cpp) + * [Interpolation Search2](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/interpolation_search2.cpp) * [Jump Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/jump_search.cpp) - * [Linear Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/Linear%20Search.cpp) + * [Linear Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/linear_search.cpp) * [Median Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/median_search.cpp) * [Searching](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/searching.cpp) * [Ternary Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/ternary_search.cpp) From c892cbadc630bac45ea9ffbb2bada8a427187bba Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Tue, 26 May 2020 18:07:41 -0400 Subject: [PATCH 110/433] fixed code for lint and copy constructor --- others/fibonacci_large.cpp | 7 +- others/large_number.h | 444 +++++++++++++++++++------------------ 2 files changed, 231 insertions(+), 220 deletions(-) diff --git a/others/fibonacci_large.cpp b/others/fibonacci_large.cpp index 0333feb81b2..6f36702a28c 100644 --- a/others/fibonacci_large.cpp +++ b/others/fibonacci_large.cpp @@ -18,11 +18,12 @@ large_number fib(uint64_t n) { large_number f1(1); do { - large_number f2 = f0 + f1; - f0 = f1; - f1 = f2; + large_number f2 = f1; + f1 += f0; + f0 = f2; n--; } while (n > 2); // since we start from 2 + return f1; } diff --git a/others/large_number.h b/others/large_number.h index 38d9125dee2..8ea8190b663 100644 --- a/others/large_number.h +++ b/others/large_number.h @@ -1,4 +1,5 @@ /** + * @file * @author Krishna Vedala * @email krishna (dot) vedala (at) ieee (dot) org **/ @@ -21,252 +22,261 @@ **/ class large_number { public: - /**< initializer with value = 1 */ - large_number() { _digits.push_back(1); } + /**< initializer with value = 1 */ + large_number() { _digits.push_back(1); } - /**< initializer from an integer */ - explicit large_number(uint64_t n) { - uint64_t carry = n; - do { - add_digit(carry % 10); - carry /= 10; - } while (carry != 0); - } + // /**< initializer from an integer */ + // explicit large_number(uint64_t n) { + // uint64_t carry = n; + // do { + // add_digit(carry % 10); + // carry /= 10; + // } while (carry != 0); + // } - /**< initializer from another large_number */ - explicit large_number(const large_number &a) { _digits = a._digits; } + /**< initializer from an integer */ + explicit large_number(int n) { + int carry = n; + do { + add_digit(carry % 10); + carry /= 10; + } while (carry != 0); + } - /**< initializer from a vector */ - explicit large_number(const std::vector &vec) { - _digits = vec; - } + /**< initializer from another large_number */ + large_number(const large_number &a) : _digits(a._digits) {} - /**< initializer from a string */ - explicit large_number(const char *number_str) { - for (size_t i = strlen(number_str); i > 0; i--) { - unsigned char a = number_str[i - 1] - '0'; - if (a >= 0 && a <= 9) _digits.push_back(a); - } - } + /**< initializer from a vector */ + explicit large_number(std::vector &vec) : _digits(vec) {} - /** - * Function to check implementation - **/ - static bool test() { - std::cout << "------ Checking `large_number` class implementations\t" - << std::endl; - large_number a(40); - // 1. test multiplication - a *= 10; - if (a != large_number(400)) { - std::cerr << "\tFailed 1/6 (" << a << "!=400)" << std::endl; - return false; - } - std::cout << "\tPassed 1/6..."; - // 2. test compound addition with integer - a += 120; - if (a != large_number(520)) { - std::cerr << "\tFailed 2/6 (" << a << "!=520)" << std::endl; - return false; - } - std::cout << "\tPassed 2/6..."; - // 3. test compound multiplication again - a *= 10; - if (a != large_number(5200)) { - std::cerr << "\tFailed 3/6 (" << a << "!=5200)" << std::endl; - return false; - } - std::cout << "\tPassed 3/6..."; - // 4. test increment (prefix) - ++a; - if (a != large_number(5201)) { - std::cerr << "\tFailed 4/6 (" << a << "!=5201)" << std::endl; - return false; - } - std::cout << "\tPassed 4/6..."; - // 5. test increment (postfix) - a++; - if (a != large_number(5202)) { - std::cerr << "\tFailed 5/6 (" << a << "!=5202)" << std::endl; - return false; + /**< initializer from a string */ + explicit large_number(char const *number_str) { + for (size_t i = strlen(number_str); i > 0; i--) { + unsigned char a = number_str[i - 1] - '0'; + if (a >= 0 && a <= 9) _digits.push_back(a); + } } - std::cout << "\tPassed 5/6..."; - // 6. test addition with another large number - a = a + large_number("7000000000000000000000000000000"); - if (a != large_number("7000000000000000000000000005202")) { - std::cerr << "\tFailed 6/6 (" << a << "!=7000000000000000000000000005202)" - << std::endl; - return false; - } - std::cout << "\tPassed 6/6..." << std::endl; - return true; - } - /** - * add a digit at MSB to the large number - **/ - void add_digit(unsigned int value) { - if (value > 9) { - std::cerr << "digit > 9!!\n"; - exit(EXIT_FAILURE); + /** + * Function to check implementation + **/ + static bool test() { + std::cout << "------ Checking `large_number` class implementations\t" + << std::endl; + large_number a(40); + // 1. test multiplication + a *= 10; + if (a != large_number(400)) { + std::cerr << "\tFailed 1/6 (" << a << "!=400)" << std::endl; + return false; + } + std::cout << "\tPassed 1/6..."; + // 2. test compound addition with integer + a += 120; + if (a != large_number(520)) { + std::cerr << "\tFailed 2/6 (" << a << "!=520)" << std::endl; + return false; + } + std::cout << "\tPassed 2/6..."; + // 3. test compound multiplication again + a *= 10; + if (a != large_number(5200)) { + std::cerr << "\tFailed 3/6 (" << a << "!=5200)" << std::endl; + return false; + } + std::cout << "\tPassed 3/6..."; + // 4. test increment (prefix) + ++a; + if (a != large_number(5201)) { + std::cerr << "\tFailed 4/6 (" << a << "!=5201)" << std::endl; + return false; + } + std::cout << "\tPassed 4/6..."; + // 5. test increment (postfix) + a++; + if (a != large_number(5202)) { + std::cerr << "\tFailed 5/6 (" << a << "!=5202)" << std::endl; + return false; + } + std::cout << "\tPassed 5/6..."; + // 6. test addition with another large number + a = a + large_number("7000000000000000000000000000000"); + if (a != large_number("7000000000000000000000000005202")) { + std::cerr << "\tFailed 6/6 (" << a + << "!=7000000000000000000000000005202)" << std::endl; + return false; + } + std::cout << "\tPassed 6/6..." << std::endl; + return true; } - _digits.push_back(value); - } + /** + * add a digit at MSB to the large number + **/ + void add_digit(unsigned int value) { + if (value > 9) { + std::cerr << "digit > 9!!\n"; + exit(EXIT_FAILURE); + } - /** - * Get number of digits in the number - **/ - const size_t num_digits() const { return _digits.size(); } + _digits.push_back(value); + } - /** - * operator over load to access the - * i^th digit conveniently and also - * assign value to it - **/ - inline unsigned char &operator[](size_t n) { return this->_digits[n]; } + /** + * Get number of digits in the number + **/ + const size_t num_digits() const { return _digits.size(); } - inline const unsigned char &operator[](size_t n) const { - return this->_digits[n]; - } + /** + * operator over load to access the + * i^th digit conveniently and also + * assign value to it + **/ + inline unsigned char &operator[](size_t n) { return this->_digits[n]; } - /** - * operator overload to compare two numbers - **/ - friend std::ostream &operator<<(std::ostream &out, const large_number &a) { - for (size_t i = a.num_digits(); i > 0; i--) - out << static_cast(a[i - 1]); - return out; - } + inline const unsigned char &operator[](size_t n) const { + return this->_digits[n]; + } - /** - * operator overload to compare two numbers - **/ - friend bool operator==(large_number const &a, large_number const &b) { - size_t N = a.num_digits(); - if (N != b.num_digits()) return false; - for (size_t i = 0; i < N; i++) - if (a[i] != b[i]) return false; - return true; - } + /** + * operator overload to compare two numbers + **/ + friend std::ostream &operator<<(std::ostream &out, const large_number &a) { + for (size_t i = a.num_digits(); i > 0; i--) + out << static_cast(a[i - 1]); + return out; + } - /** - * operator overload to compare two numbers - **/ - friend bool operator!=(large_number const &a, large_number const &b) { - return !(a == b); - } + /** + * operator overload to compare two numbers + **/ + friend bool operator==(large_number const &a, large_number const &b) { + size_t N = a.num_digits(); + if (N != b.num_digits()) return false; + for (size_t i = 0; i < N; i++) + if (a[i] != b[i]) return false; + return true; + } - /** - * operator overload to increment (prefix) - **/ - large_number &operator++() { - (*this) += 1; - return *this; - } + /** + * operator overload to compare two numbers + **/ + friend bool operator!=(large_number const &a, large_number const &b) { + return !(a == b); + } - /** - * operator overload to increment (postfix) - **/ - large_number operator++(int) { - large_number tmp(_digits); - ++(*this); - return tmp; - } + /** + * operator overload to increment (prefix) + **/ + large_number &operator++() { + (*this) += 1; + return *this; + } - /** - * operator overload to add - **/ - template - large_number &operator+=(T n) { - // if adding with another large_number - if (typeid(T) == typeid(large_number)) { - large_number *b = static_cast(&n); - const size_t max_L = std::max(this->num_digits(), b->num_digits()); - unsigned int carry = 0; - size_t i; - for (i = 0; i < max_L || carry != 0; i++) { - if (i < b->num_digits()) carry += (*b)[i]; - if (i < this->num_digits()) carry += (*this)[i]; - if (i < this->num_digits()) - (*this)[i] = carry % 10; - else - this->add_digit(carry % 10); - carry /= 10; - } - } else if (std::is_integral::value) { - return (*this) += large_number(n); - } else { - std::cerr << "Must be integer addition unsigned integer types." - << std::endl; + /** + * operator overload to increment (postfix) + **/ + large_number &operator++(int) { + large_number tmp(_digits); + ++(*this); + return tmp; } - return *this; - } - /** - * operator overload to perform addition - **/ - template - friend large_number &operator+(large_number &a, const T &b) { - a += b; - return a; - } + /** + * operator overload to add + **/ + large_number &operator+=(large_number n) { + // if adding with another large_number + large_number *b = reinterpret_cast(&n); + const size_t max_L = std::max(this->num_digits(), b->num_digits()); + unsigned int carry = 0; + size_t i; + for (i = 0; i < max_L || carry != 0; i++) { + if (i < b->num_digits()) carry += (*b)[i]; + if (i < this->num_digits()) carry += (*this)[i]; + if (i < this->num_digits()) + (*this)[i] = carry % 10; + else + this->add_digit(carry % 10); + carry /= 10; + } + return *this; + } + + large_number &operator+=(int n) { return (*this) += large_number(n); } + // large_number &operator+=(uint64_t n) { return (*this) += large_number(n); + // } + + /** + * operator overload to perform addition + **/ + template + friend large_number &operator+(const large_number &a, const T &b) { + large_number c = a; + c += b; + return c; + } - /** - * assignment operator - **/ - void operator=(const large_number &b) { _digits = b._digits; } + /** + * assignment operator + **/ + large_number &operator=(const large_number &b) { + this->_digits = b._digits; + return *this; + } - /** - * operator overload to increment - **/ - template - large_number &operator*=(const T n) { - static_assert(std::is_integral::value, - "Must be integer addition unsigned integer types."); - this->multiply(n); - return *this; - } + /** + * operator overload to increment + **/ + template + large_number &operator*=(const T n) { + static_assert(std::is_integral::value, + "Must be integer addition unsigned integer types."); + this->multiply(n); + return *this; + } - /** - * returns i^th digit as an ASCII character - **/ - const char digit_char(size_t i) const { - return _digits[num_digits() - i - 1] + '0'; - } + /** + * returns i^th digit as an ASCII character + **/ + const char digit_char(size_t i) const { + return _digits[num_digits() - i - 1] + '0'; + } private: - /** - * multiply large number with another integer and - * store the result in the same large number - **/ - template - void multiply(const T n) { - static_assert(std::is_integral::value, "Can only have integer types."); - // assert(!(std::is_signed::value)); //, "Implemented only for - // unsigned integer types."); + /** + * multiply large number with another integer and + * store the result in the same large number + **/ + template + void multiply(const T n) { + static_assert(std::is_integral::value, + "Can only have integer types."); + // assert(!(std::is_signed::value)); //, "Implemented only for + // unsigned integer types."); - size_t i; - uint64_t carry = 0, temp; - for (i = 0; i < this->num_digits(); i++) { - temp = (*this)[i] * n; - temp += carry; - if (temp < 10) { - carry = 0; - } else { - carry = temp / 10; - temp = temp % 10; - } - (*this)[i] = temp; - } + size_t i; + uint64_t carry = 0, temp; + for (i = 0; i < this->num_digits(); i++) { + temp = (*this)[i] * n; + temp += carry; + if (temp < 10) { + carry = 0; + } else { + carry = temp / 10; + temp = temp % 10; + } + (*this)[i] = temp; + } - while (carry != 0) { - this->add_digit(carry % 10); - carry /= 10; + while (carry != 0) { + this->add_digit(carry % 10); + carry /= 10; + } } - } - std::vector _digits; /**< where individual digits are stored */ + std::vector + _digits; /**< where individual digits are stored */ }; #endif // OTHERS_LARGE_NUMBER_H_ From 77641f9b69b1f0e4b8e9988561ced94e5c343718 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Tue, 26 May 2020 18:15:00 -0400 Subject: [PATCH 111/433] use static variable to return reference for --- others/large_number.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/others/large_number.h b/others/large_number.h index 8ea8190b663..54468298734 100644 --- a/others/large_number.h +++ b/others/large_number.h @@ -177,7 +177,7 @@ class large_number { * operator overload to increment (postfix) **/ large_number &operator++(int) { - large_number tmp(_digits); + static large_number tmp(_digits); ++(*this); return tmp; } @@ -212,7 +212,7 @@ class large_number { **/ template friend large_number &operator+(const large_number &a, const T &b) { - large_number c = a; + static large_number c = a; c += b; return c; } From 1a37992c1e7e538c7ffbe02c8448ef1abbdc1ab4 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 08:08:31 -0400 Subject: [PATCH 112/433] set 1 space for `private` and `public` keywords in cpp-classes --- .vscode/settings.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 4d291141b4d..0a257500b52 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -64,7 +64,7 @@ "valarray": "cpp", "algorithm": "cpp" }, - "C_Cpp.clang_format_style": "{ BasedOnStyle: Google, UseTab: Never, IndentWidth: 4, TabWidth: 4, AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: true, ColumnLimit: 80, AccessModifierOffset: -4, NamespaceIndentation: All }", + "C_Cpp.clang_format_style": "{ BasedOnStyle: Google, UseTab: Never, IndentWidth: 4, TabWidth: 4, AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: true, ColumnLimit: 80, AccessModifierOffset: -3, NamespaceIndentation: All }", "editor.formatOnSave": true, "editor.formatOnType": true, "editor.formatOnPaste": true From 334eb3df591cabf3d860bd0467b7bdd70ce157f9 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 09:13:21 -0400 Subject: [PATCH 113/433] documetnation for binary_exponent.cpp --- math/binary_exponent.cpp | 59 ++++++++++++++++++++++++---------------- 1 file changed, 35 insertions(+), 24 deletions(-) diff --git a/math/binary_exponent.cpp b/math/binary_exponent.cpp index b4551da25f6..05e6f33f7ae 100644 --- a/math/binary_exponent.cpp +++ b/math/binary_exponent.cpp @@ -1,46 +1,57 @@ -/// C++ Program to find Binary Exponent Iteratively and Recursively. - -#include -/* - * Calculate a^b in O(log(b)) by converting b to a binary number. - * Binary exponentiation is also known as exponentiation by squaring. - * NOTE : This is a far better approach compared to naive method which provide O(b) operations. +/** + * @file + * @brief C++ Program to find Binary Exponent Iteratively and Recursively. + * + * Calculate \f$a^b\f$ in \f$O(\log(b))\f$ by converting \f$b\f$ to a + * binary number. Binary exponentiation is also known as exponentiation by + * squaring. + * @note This is a far better approach compared to naive method which + * provide \f$O(b)\f$ operations. + * * Example: - * 10 in base 2 is 1010. - * 2^10 = 2^(1010) = 2^8 * 2^2 - * 2^1 = 2 - * 2^2 = (2^1)^2 = 2^2 = 4 - * 2^4 = (2^2)^2 = 4^2 = 16 - * 2^8 = (2^4)^2 = 16^2 = 256 - * Hence to calculate 2^10 we only need to multiply 2^8 and 2^2 skipping 2^1 and 2^4. -*/ + *
10 in base 2 is 1010. + * \f{eqnarray*}{ + * 2^{10_d} &=& 2^{1010_b} = 2^8 * 2^2\\ + * 2^1 &=& 2\\ + * 2^2 &=& (2^1)^2 = 2^2 = 4\\ + * 2^4 &=& (2^2)^2 = 4^2 = 16\\ + * 2^8 &=& (2^4)^2 = 16^2 = 256\\ + * \f} + * Hence to calculate 2^10 we only need to multiply \f$2^8\f$ and \f$2^2\f$ + * skipping \f$2^1\f$ and \f$2^4\f$. + */ + +#include -/// Recursive function to calculate exponent in O(log(n)) using binary exponent. +/// Recursive function to calculate exponent in \f$O(\log(n))\f$ using binary +/// exponent. int binExpo(int a, int b) { if (b == 0) { return 1; } - int res = binExpo(a, b/2); - if (b%2) { - return res*res*a; + int res = binExpo(a, b / 2); + if (b % 2) { + return res * res * a; } else { - return res*res; + return res * res; } } -/// Iterative function to calculate exponent in O(log(n)) using binary exponent. +/// Iterative function to calculate exponent in \f$O(\log(n))\f$ using binary +/// exponent. int binExpo_alt(int a, int b) { int res = 1; while (b > 0) { - if (b%2) { - res = res*a; + if (b % 2) { + res = res * a; } - a = a*a; + a = a * a; b /= 2; } return res; } +/// Main function int main() { int a, b; /// Give two numbers a, b From 4134c16f429be72eece8b1d176ed0790738d31b1 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 09:21:54 -0400 Subject: [PATCH 114/433] documentation for double_factorial --- math/double_factorial.cpp | 41 ++++++++++++++++++++++----------------- 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/math/double_factorial.cpp b/math/double_factorial.cpp index 7b0d1d9709f..2b28a5d5a79 100644 --- a/math/double_factorial.cpp +++ b/math/double_factorial.cpp @@ -1,28 +1,33 @@ -#include -#include +/** + * @file + * Double factorial of a non-negative integer n, is defined as the product of + * all the integers from 1 to n that have the same parity (odd or even) as n. + *
It is also called as semifactorial of a number and is denoted by `!!` + */ -/* Double factorial of a non-negative integer n, is defined as the product of -all the integers from 1 to n that have the same parity (odd or even) as n. -It is also called as semifactorial of a number and is denoted by !! */ +#include +#include +/// Compute double factorial using iterative method uint64_t double_factorial_iterative(uint64_t n) { - uint64_t res = 1; - for ( uint64_t i = n; i >= 0; i -= 2 ) { - if (i == 0 || i == 1) return res; - res *= i; - } + uint64_t res = 1; + for (uint64_t i = n; i >= 0; i -= 2) { + if (i == 0 || i == 1) return res; + res *= i; + } } -/* Recursion can be costly for large numbers */ - +/// Compute double factorial using resursive method. +//
Recursion can be costly for large numbers. uint64_t double_factorial_recursive(uint64_t n) { - if (n <= 1) return 1; - return n * double_factorial_recursive(n - 2); + if (n <= 1) return 1; + return n * double_factorial_recursive(n - 2); } +/// main function int main() { - uint64_t n{}; - std::cin >> n; - assert(n >= 0); - std::cout << double_factorial_iterative(n); + uint64_t n{}; + std::cin >> n; + assert(n >= 0); + std::cout << double_factorial_iterative(n); } From 44f68e9a2e50275fce0d6a3e23ed5f15585c1ff5 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 12:54:42 -0400 Subject: [PATCH 115/433] bug fix - no function return and invalid for loop termination check --- math/double_factorial.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/math/double_factorial.cpp b/math/double_factorial.cpp index 2b28a5d5a79..73a3d344a69 100644 --- a/math/double_factorial.cpp +++ b/math/double_factorial.cpp @@ -11,10 +11,11 @@ /// Compute double factorial using iterative method uint64_t double_factorial_iterative(uint64_t n) { uint64_t res = 1; - for (uint64_t i = n; i >= 0; i -= 2) { + for (uint64_t i = n;; i -= 2) { if (i == 0 || i == 1) return res; res *= i; } + return res; } /// Compute double factorial using resursive method. From 50070774dd7cbf80e76bbf32f5f45c2cb3d8f24b Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 12:55:03 -0400 Subject: [PATCH 116/433] fix documentation for double_factorial --- math/double_factorial.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/math/double_factorial.cpp b/math/double_factorial.cpp index 73a3d344a69..26b90f356aa 100644 --- a/math/double_factorial.cpp +++ b/math/double_factorial.cpp @@ -2,7 +2,8 @@ * @file * Double factorial of a non-negative integer n, is defined as the product of * all the integers from 1 to n that have the same parity (odd or even) as n. - *
It is also called as semifactorial of a number and is denoted by `!!` + *
It is also called as semifactorial of a number and is denoted by + * \f$n!!\f$ */ #include @@ -27,7 +28,7 @@ uint64_t double_factorial_recursive(uint64_t n) { /// main function int main() { - uint64_t n{}; + uint64_t n; std::cin >> n; assert(n >= 0); std::cout << double_factorial_iterative(n); From d723604e0162c5f828d9f3137f1ff9c7f26e97ed Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 14:07:05 -0400 Subject: [PATCH 117/433] documentation update for double_factorial --- math/double_factorial.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/math/double_factorial.cpp b/math/double_factorial.cpp index 26b90f356aa..37bd2052ac3 100644 --- a/math/double_factorial.cpp +++ b/math/double_factorial.cpp @@ -1,5 +1,7 @@ /** * @file + * @brief Compute double factorial: \f$n!!\f$ + * * Double factorial of a non-negative integer n, is defined as the product of * all the integers from 1 to n that have the same parity (odd or even) as n. *
It is also called as semifactorial of a number and is denoted by @@ -9,7 +11,8 @@ #include #include -/// Compute double factorial using iterative method +/** Compute double factorial using iterative method + */ uint64_t double_factorial_iterative(uint64_t n) { uint64_t res = 1; for (uint64_t i = n;; i -= 2) { @@ -19,8 +22,9 @@ uint64_t double_factorial_iterative(uint64_t n) { return res; } -/// Compute double factorial using resursive method. -//
Recursion can be costly for large numbers. +/** Compute double factorial using resursive method. + *
Recursion can be costly for large numbers. + */ uint64_t double_factorial_recursive(uint64_t n) { if (n <= 1) return 1; return n * double_factorial_recursive(n - 2); From 4944d4c8b1dc00231209d24f26374dfc96d2c429 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 14:07:18 -0400 Subject: [PATCH 118/433] documentation for eulers_totient_function.cpp --- math/eulers_totient_function.cpp | 62 ++++++++++++++++++++------------ 1 file changed, 39 insertions(+), 23 deletions(-) diff --git a/math/eulers_totient_function.cpp b/math/eulers_totient_function.cpp index 31ced5a5181..e7f6fbf7f5b 100644 --- a/math/eulers_totient_function.cpp +++ b/math/eulers_totient_function.cpp @@ -1,28 +1,37 @@ -/// C++ Program to find Euler Totient Function -#include - -/* +/** + * @file + * @brief C++ Program to find + * [Euler's Totient](https://en.wikipedia.org/wiki/Euler%27s_totient_function) + * function + * * Euler Totient Function is also known as phi function. - * phi(n) = phi(p1^a1).phi(p2^a2)... - * where p1, p2,... are prime factors of n. - * 3 Euler's properties: - * 1. phi(prime_no) = prime_no-1 - * 2. phi(prime_no^k) = (prime_no^k - prime_no^(k-1)) - * 3. phi(a,b) = phi(a). phi(b) where a and b are relative primes. + * \f[\phi(n) = + * \phi\left({p_1}^{a_1}\right)\cdot\phi\left({p_2}^{a_2}\right)\ldots\f] where + * \f$p_1\f$, \f$p_2\f$, \f$\ldots\f$ are prime factors of n. + *
3 Euler's properties: + * 1. \f$\phi(n) = n-1\f$ + * 2. \f$\phi(n^k) = n^k - n^{k-1}\f$ + * 3. \f$\phi(a,b) = \phi(a)\cdot\phi(b)\f$ where a and b are relative primes. + * * Applying this 3 properties on the first equation. - * phi(n) = n. (1-1/p1). (1-1/p2). ... - * where p1,p2... are prime factors. - * Hence Implementation in O(sqrt(n)). - * phi(100) = 40 - * phi(1) = 1 - * phi(17501) = 15120 - * phi(1420) = 560 + * \f[\phi(n) = + * n\cdot\left(1-\frac{1}{p_1}\right)\cdot\left(1-\frac{1}{p_2}\right)\cdots\f] + * where \f$p_1\f$,\f$p_2\f$... are prime factors. + * Hence Implementation in \f$O\left(\sqrt{n}\right)\f$. + *
Some known values are: + * * \f$\phi(100) = 40\f$ + * * \f$\phi(1) = 1\f$ + * * \f$\phi(17501) = 15120\f$ + * * \f$\phi(1420) = 560\f$ */ +#include +#include -// Function to caculate Euler's totient phi -int phiFunction(int n) { - int result = n; - for (int i = 2; i * i <= n; i++) { +/** Function to caculate Euler's totient phi + */ +uint64_t phiFunction(uint64_t n) { + uint64_t result = n; + for (uint64_t i = 2; i * i <= n; i++) { if (n % i == 0) { while (n % i == 0) { n /= i; @@ -34,8 +43,15 @@ int phiFunction(int n) { return result; } -int main() { - int n; +/// Main function +int main(int argc, char *argv[]) { + uint64_t n; + if (argc < 2) { + std::cout << "Enter the number: "; + } else { + n = strtoull(argv[1], nullptr, 10); + } std::cin >> n; std::cout << phiFunction(n); + return 0; } From 691cbdb1f514f5bbd295b97c5d8123f63a9e62fe Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 15:06:36 -0400 Subject: [PATCH 119/433] fix code for generic types --- math/extended_euclid_algorithm.cpp | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/math/extended_euclid_algorithm.cpp b/math/extended_euclid_algorithm.cpp index 3db14802f0d..829db4336d2 100644 --- a/math/extended_euclid_algorithm.cpp +++ b/math/extended_euclid_algorithm.cpp @@ -4,25 +4,27 @@ // This is also used in finding Modular multiplicative inverse of a number. // (A * B)%M == 1 Here B is the MMI of A for given M, // so extendedEuclid (A, M) gives B. +template +void extendedEuclid(T A, T B, T *GCD, T2 *x, T2 *y) { + if (B > A) std::swap(A, B); // Ensure that A >= B -int d, x, y; -void extendedEuclid(int A, int B) { if (B == 0) { - d = A; - x = 1; - y = 0; + *GCD = A; + *x = 1; + *y = 0; } else { - extendedEuclid(B, A%B); - int temp = x; - x = y; - y = temp - (A/B)*y; + extendedEuclid(B, A % B, GCD, x, y); + T2 temp = *x; + *x = *y; + *y = temp - (A / B) * (*y); } } int main() { - int a, b; + uint32_t a, b, gcd; + int32_t x, y; std::cin >> a >> b; - extendedEuclid(a, b); - std::cout << x << " " << y << std::endl; + extendedEuclid(a, b, &gcd, &x, &y); + std::cout << gcd << " " << x << " " << y << std::endl; return 0; } From 757970dbaec023fd9cdcbab40fb64f66cae21bb5 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 15:06:46 -0400 Subject: [PATCH 120/433] documentation for extended euclid --- math/extended_euclid_algorithm.cpp | 74 ++++++++++++++++++++++++++++-- 1 file changed, 69 insertions(+), 5 deletions(-) diff --git a/math/extended_euclid_algorithm.cpp b/math/extended_euclid_algorithm.cpp index 829db4336d2..84dec55c53e 100644 --- a/math/extended_euclid_algorithm.cpp +++ b/math/extended_euclid_algorithm.cpp @@ -1,9 +1,70 @@ +/** + * @file + * @brief GCD using [extended Euclid's algorithm] + * (https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm) + * + * Finding coefficients of a and b ie x and y in Bézout's identity + * \f[\text{gcd}(a, b) = a \times x + b \times y \f] + * This is also used in finding Modular + * multiplicative inverse of a number. (A * B)%M == 1 Here B is the MMI of A for + * given M, so extendedEuclid (A, M) gives B. + */ +#include // for swap function #include -// Finding coefficients of a and b ie x and y in gcd(a, b) = a * x + b * y -// d is gcd(a, b) -// This is also used in finding Modular multiplicative inverse of a number. -// (A * B)%M == 1 Here B is the MMI of A for given M, -// so extendedEuclid (A, M) gives B. + +/** + * function to update the coefficients per iteration + * \f[r_0,\,r = r,\, r_0 - \text{quotient}\times r\f] + * + * @param[in,out] r signed + * @param[in,out] r0 signed + * @param[in] quotient unsigned input + */ +template +inline void update_step(T &r, T &r0, const T2 quotient) { + T temp = r; + r = r0 - (quotient * temp); + r0 = temp; +} + +/** + * Implementation using iterative algorithm from + * [Wikipedia](https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Pseudocode) + * + * @param[in] A unsigned + * @param[in] B unsigned + * @param[out] GCD unsigned + * @param[out] x signed + * @param[out] y signed + */ +template +void extendedEuclid_1(T1 A, T1 B, T1 *GCD, T2 *x, T2 *y) { + if (B > A) std::swap(A, B); // Ensure that A >= B + + T2 s = 0, s0 = 1; + T2 t = 1, t0 = 0; + T1 r = B, r0 = A; + + while (r != 0) { + T1 quotient = r0 / r; + update_step(r, r0, quotient); + update_step(s, s0, quotient); + update_step(t, t0, quotient); + } + *GCD = r0; + *x = s0; + *y = t0; +} + +/** + * Implementation using recursive algorithm + * + * @param[in] A unsigned + * @param[in] B unsigned + * @param[out] GCD unsigned + * @param[in,out] x signed + * @param[in,out] y signed + */ template void extendedEuclid(T A, T B, T *GCD, T2 *x, T2 *y) { if (B > A) std::swap(A, B); // Ensure that A >= B @@ -20,11 +81,14 @@ void extendedEuclid(T A, T B, T *GCD, T2 *x, T2 *y) { } } +/// Main function int main() { uint32_t a, b, gcd; int32_t x, y; std::cin >> a >> b; extendedEuclid(a, b, &gcd, &x, &y); std::cout << gcd << " " << x << " " << y << std::endl; + extendedEuclid_1(a, b, &gcd, &x, &y); + std::cout << gcd << " " << x << " " << y << std::endl; return 0; } From d26206549248998e1dc1de57a271d3c931c44019 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 15:14:30 -0400 Subject: [PATCH 121/433] use template based functions --- math/fast_power.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/math/fast_power.cpp b/math/fast_power.cpp index 0ffbcd40d78..f69a90e4c1f 100644 --- a/math/fast_power.cpp +++ b/math/fast_power.cpp @@ -21,16 +21,17 @@ /** * algorithm implementation for \f$a^b\f$ */ -double fast_power_recursive(int64_t a, int64_t b) { +template +double fast_power_recursive(T a, T b) { // negative power. a^b = 1 / (a^-b) if (b < 0) return 1.0 / fast_power_recursive(a, -b); if (b == 0) return 1; - int64_t bottom = fast_power_recursive(a, b >> 1); + T bottom = fast_power_recursive(a, b >> 1); // Since it is integer division b/2 = (b-1)/2 where b is odd. // Therefore, case2 is easily solved by integer division. - int64_t result; + double result; if ((b & 1) == 0) // case1 result = bottom * bottom; else // case2 @@ -42,7 +43,8 @@ double fast_power_recursive(int64_t a, int64_t b) { Same algorithm with little different formula. It still calculates in O(logN) */ -double fast_power_linear(int64_t a, int64_t b) { +template +double fast_power_linear(T a, T b) { // negative power. a^b = 1 / (a^-b) if (b < 0) return 1.0 / fast_power_linear(a, -b); From a436cd7a1b3050af91f8aa4fdb6e5ec24b1d181d Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 15:14:39 -0400 Subject: [PATCH 122/433] improve documentation for fast_power --- math/fast_power.cpp | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/math/fast_power.cpp b/math/fast_power.cpp index f69a90e4c1f..d4de074603c 100644 --- a/math/fast_power.cpp +++ b/math/fast_power.cpp @@ -1,15 +1,16 @@ /** * @file - Program that computes \f$a^b\f$ in \f$O(logN)\f$ time. - It is based on formula that: - 1. if \f$b\f$ is even: \f$a^b = a^\frac{b}{2} \cdot a^\frac{b}{2} = - {a^\frac{b}{2}}^2\f$ - 2. if \f$b\f$ is odd: \f$a^b = a^\frac{b-1}{2} \cdot - a^\frac{b-1}{2} \cdot a = {a^\frac{b-1}{2}}^2 \cdot a\f$ - - We can compute \f$a^b\f$ - recursively using above algorithm. -*/ + * @brief Faster computation for \f$a^b\f$ + * + * Program that computes \f$a^b\f$ in \f$O(logN)\f$ time. + * It is based on formula that: + * 1. if \f$b\f$ is even: + * \f$a^b = a^\frac{b}{2} \cdot a^\frac{b}{2} = {a^\frac{b}{2}}^2\f$ + * 2. if \f$b\f$ is odd: \f$a^b = a^\frac{b-1}{2} + * \cdot a^\frac{b-1}{2} \cdot a = {a^\frac{b-1}{2}}^2 \cdot a\f$ + * + * We can compute \f$a^b\f$ recursively using above algorithm. + */ #include #include @@ -41,7 +42,7 @@ double fast_power_recursive(T a, T b) { /** Same algorithm with little different formula. - It still calculates in O(logN) + It still calculates in \f$O(\log N)\f$ */ template double fast_power_linear(T a, T b) { @@ -57,6 +58,9 @@ double fast_power_linear(T a, T b) { return result; } +/** + * Main function + */ int main() { std::srand(std::time(nullptr)); std::ios_base::sync_with_stdio(false); From e31ee6e83332e9c6e508e8bd88f216ce6042d40f Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 15:42:12 -0400 Subject: [PATCH 123/433] better document GCD programs --- ...lidean.cpp => gcd_iterative_euclidean.cpp} | 18 +++++-- math/gcd_recursive_euclidean.cpp | 48 +++++++++++++++++++ math/greatest_common_divisor.cpp | 27 ----------- 3 files changed, 62 insertions(+), 31 deletions(-) rename math/{greatest_common_divisor_euclidean.cpp => gcd_iterative_euclidean.cpp} (80%) create mode 100644 math/gcd_recursive_euclidean.cpp delete mode 100644 math/greatest_common_divisor.cpp diff --git a/math/greatest_common_divisor_euclidean.cpp b/math/gcd_iterative_euclidean.cpp similarity index 80% rename from math/greatest_common_divisor_euclidean.cpp rename to math/gcd_iterative_euclidean.cpp index c4812e45b4c..61fb640a388 100644 --- a/math/greatest_common_divisor_euclidean.cpp +++ b/math/gcd_iterative_euclidean.cpp @@ -1,10 +1,17 @@ -#include +/** + * @file + * @brief Compute the greatest common denominator of two integers using + * *iterative form* of + * [Euclidean algorithm](https://en.wikipedia.org/wiki/Euclidean_algorithm) + * + * @see gcd_recursive_euclidean.cpp + */ #include #include -// will find the greatest common denominator of two ints integers -// Euclidean algorithm can be found here -// https://en.wikipedia.org/wiki/Euclidean_algorithm +/** + * algorithm + */ int gcd(int num1, int num2) { if (num1 <= 0 | num2 <= 0) { throw std::domain_error("Euclidean algorithm domain is for ints > 0"); @@ -34,6 +41,9 @@ int gcd(int num1, int num2) { return previous_remainder; } +/** + * Main function + */ int main() { std::cout << "gcd of 120,7 is " << (gcd(120, 7)) << std::endl; try { diff --git a/math/gcd_recursive_euclidean.cpp b/math/gcd_recursive_euclidean.cpp new file mode 100644 index 00000000000..3a1ca6e6613 --- /dev/null +++ b/math/gcd_recursive_euclidean.cpp @@ -0,0 +1,48 @@ +/** + * @file + * @brief Compute the greatest common denominator of two integers using + * *recursive form* of + * [Euclidean algorithm](https://en.wikipedia.org/wiki/Euclidean_algorithm) + * + * @see gcd_iterative_euclidean.cpp + */ +#include + +/** + * algorithm + */ +int gcd(int num1, int num2) { + if (num1 <= 0 | num2 <= 0) { + throw std::domain_error("Euclidean algorithm domain is for ints > 0"); + } + + if (num1 == num2) { + return num1; + } + + // Everything divides 0 + if (num1 == 0) return num2; + if (num2 == 0) return num1; + + // base case + if (num1 == num2) return num1; + + // a is greater + if (num1 > num2) return gcd(num1 - num2, num2); + return gcd(num1, num2 - num1); +} + +/** + * Main function + */ +int main() { + std::cout << "gcd of 120,7 is " << (gcd(120, 7)) << std::endl; + try { + std::cout << "gcd of -120,10 is " << gcd(-120, 10) << std::endl; + } catch (const std::domain_error &e) { + std::cout << "Error handling was successful" << std::endl; + } + std::cout << "gcd of 312,221 is " << (gcd(312, 221)) << std::endl; + std::cout << "gcd of 289,204 is " << (gcd(289, 204)) << std::endl; + return 0; +} diff --git a/math/greatest_common_divisor.cpp b/math/greatest_common_divisor.cpp deleted file mode 100644 index 5601c4be91c..00000000000 --- a/math/greatest_common_divisor.cpp +++ /dev/null @@ -1,27 +0,0 @@ -// C++ program to find GCD of two numbers -#include - -// Recursive function to return gcd of a and b -int gcd(int a, int b) { - // Everything divides 0 - if (a == 0) - return b; - if (b == 0) - return a; - - // base case - if (a == b) - return a; - - // a is greater - if (a > b) - return gcd(a-b, b); - return gcd(a, b-a); -} - -// Driver program to test above function -int main() { - int a = 98, b = 56; - std::cout << "GCD of " << a << " and " << b << " is " << gcd(a, b); - return 0; -} From 49fe1b11ef124c240b5552b57d1b2ddbefcea5a5 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 15:42:23 -0400 Subject: [PATCH 124/433] document fibonacci program --- math/fibonacci.cpp | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/math/fibonacci.cpp b/math/fibonacci.cpp index e82875da3c5..1a5f4afb40f 100644 --- a/math/fibonacci.cpp +++ b/math/fibonacci.cpp @@ -1,12 +1,17 @@ +/** + * @file + * @brief Generate fibonacci sequence + * + * Calculate the the value on Fibonacci's sequence given an + * integer as input. + * \f[\text{fib}(n) = \text{fib}(n-1) + \text{fib}(n-2)\f] + */ #include #include -/* Calculate the the value on Fibonacci's sequence given an -integer as input -Fibonacci = 0, 1, 1, 2, 3, 5, - 8, 13, 21, 34, 55, - 89, 144, ... */ - +/** + * Recursively compute sequences + */ int fibonacci(unsigned int n) { /* If the input is 0 or 1 just return the same This will set the first 2 values of the sequence */ @@ -16,6 +21,7 @@ int fibonacci(unsigned int n) { return fibonacci(n - 1) + fibonacci(n - 2); } +/// Main function int main() { int n; std::cin >> n; From 4d272210fc8bd9c26f68abb4124edd5c3d509419 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Wed, 27 May 2020 19:42:57 +0000 Subject: [PATCH 125/433] updating DIRECTORY.md --- DIRECTORY.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index ba455f2c118..2b73144b807 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -109,8 +109,8 @@ * [Factorial](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/factorial.cpp) * [Fast Power](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/fast_power.cpp) * [Fibonacci](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/fibonacci.cpp) - * [Greatest Common Divisor](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/greatest_common_divisor.cpp) - * [Greatest Common Divisor Euclidean](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/greatest_common_divisor_euclidean.cpp) + * [Gcd Iterative Euclidean](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/gcd_iterative_euclidean.cpp) + * [Gcd Recursive Euclidean](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/gcd_recursive_euclidean.cpp) * [Modular Inverse Fermat Little Theorem](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/modular_inverse_fermat_little_theorem.cpp) * [Number Of Positive Divisors](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/number_of_positive_divisors.cpp) * [Power For Huge Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/power_for_huge_numbers.cpp) From 6173a6a7017553805c7e3cb05af42cae6147af58 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 16:09:50 -0400 Subject: [PATCH 126/433] documentation for Little Fermat's Thm --- .../modular_inverse_fermat_little_theorem.cpp | 81 ++++++++++++------- 1 file changed, 50 insertions(+), 31 deletions(-) diff --git a/math/modular_inverse_fermat_little_theorem.cpp b/math/modular_inverse_fermat_little_theorem.cpp index 965c21298ae..7550e14bf23 100644 --- a/math/modular_inverse_fermat_little_theorem.cpp +++ b/math/modular_inverse_fermat_little_theorem.cpp @@ -1,44 +1,59 @@ -/* - * C++ Program to find the modular inverse using Fermat's Little Theorem. - * Fermat's Little Theorem state that => ϕ(m) = m-1, where m is a prime number. - * - * (a * x) ≡ 1 mod m. - * x ≡ (a^(-1)) mod m. +/** + * @file + * @brief C++ Program to find the modular inverse using [Fermat's Little + * Theorem](https://en.wikipedia.org/wiki/Fermat%27s_little_theorem) * + * Fermat's Little Theorem state that \f[ϕ(m) = m-1\f] + * where \f$m\f$ is a prime number. + * \f{eqnarray*}{ + * a \cdot x &≡& 1 \;\text{mod}\; m\\ + * x &≡& a^{-1} \;\text{mod}\; m + * \f} * Using Euler's theorem we can modify the equation. + *\f[ + * a^{ϕ(m)} ≡ 1 \;\text{mod}\; m + * \f] + * (Where '^' denotes the exponent operator) * - * (a^ϕ(m)) ≡ 1 mod m (Where '^' denotes the exponent operator) - * Here 'ϕ' is Euler's Totient Function. For modular inverse existence 'a' and 'm' must be relatively primes numbers. - * To apply Fermat's Little Theorem is necessary that 'm' must be a prime number. - * Generally in many competitive programming competitions 'm' is either 1000000007 (1e9+7) or 998244353. + * Here 'ϕ' is Euler's Totient Function. For modular inverse existence 'a' and + * 'm' must be relatively primes numbers. To apply Fermat's Little Theorem is + * necessary that 'm' must be a prime number. Generally in many competitive + * programming competitions 'm' is either 1000000007 (1e9+7) or 998244353. * * We considered m as large prime (1e9+7). - * (a^ϕ(m)) ≡ 1 mod m (Using Euler's Theorem) - * ϕ(m) = m-1 using Fermat's Little Theorem. - * (a^(m-1)) ≡ 1 mod m - * Now multiplying both side by (a^(-1)). - * (a^(m-1)) * (a^(-1)) ≡ (a^(-1)) mod m - * (a^(m-2)) ≡ (a^(-1)) mod m + * \f$a^{ϕ(m)} ≡ 1 \;\text{mod}\; m\f$ (Using Euler's Theorem) + * \f$ϕ(m) = m-1\f$ using Fermat's Little Theorem. + * \f$a^{m-1} ≡ 1 \;\text{mod}\; m\f$ + * Now multiplying both side by \f$a^{-1}\f$. + * \f{eqnarray*}{ + * a^{m-1} \cdot a^{-1} &≡& a^{-1} \;\text{mod}\; m\\ + * a^{m-2} &≡& a^{-1} \;\text{mod}\; m + * \f} * - * We will find the exponent using binary exponentiation. Such that the algorithm works in O(log(m)) time. + * We will find the exponent using binary exponentiation. Such that the + * algorithm works in \f$O(\log m)\f$ time. * - * Example: - - * a = 3 and m = 7 - * (a^(-1) mod m) is equivalent to (a^(m-2) mod m) - * (3^(5) mod 7) = (243 mod 7) = 5 - * Hence, ( 3^(-1) mod 7 ) = 5 - * or ( 3 * 5 ) mod 7 = 1 mod 7 (as a*(a^(-1)) = 1) + * Examples: - + * * a = 3 and m = 7 + * * \f$a^{-1} \;\text{mod}\; m\f$ is equivalent to + * \f$a^{m-2} \;\text{mod}\; m\f$ + * * \f$3^5 \;\text{mod}\; 7 = 243 \;\text{mod}\; 7 = 5\f$ + *
Hence, \f$3^{-1} \;\text{mod}\; 7 = 5\f$ + * or \f$3 \times 5 \;\text{mod}\; 7 = 1 \;\text{mod}\; 7\f$ + * (as \f$a\times a^{-1} = 1\f$) */ -#include -#include +#include +#include -// Recursive function to calculate exponent in O(log(n)) using binary exponent. +/** Recursive function to calculate exponent in \f$O(\log n)\f$ using binary + * exponent. + */ int64_t binExpo(int64_t a, int64_t b, int64_t m) { a %= m; int64_t res = 1; while (b > 0) { - if (b%2) { + if (b % 2) { res = res * a % m; } a = a * a % m; @@ -48,13 +63,14 @@ int64_t binExpo(int64_t a, int64_t b, int64_t m) { return res; } -// Prime check in O(sqrt(m)) time. +/** Prime check in \f$O(\sqrt{m})\f$ time. + */ bool isPrime(int64_t m) { if (m <= 1) { return false; } else { - for (int i=2; i*i <= m; i++) { - if (m%i == 0) { + for (int64_t i = 2; i * i <= m; i++) { + if (m % i == 0) { return false; } } @@ -62,6 +78,9 @@ bool isPrime(int64_t m) { return true; } +/** + * Main function + */ int main() { int64_t a, m; // Take input of a and m. @@ -71,7 +90,7 @@ int main() { std::cin >> a >> m; if (isPrime(m)) { std::cout << "The modular inverse of a with mod m is (a^(m-2)) : "; - std::cout << binExpo(a, m-2, m) << std::endl; + std::cout << binExpo(a, m - 2, m) << std::endl; } else { std::cout << "m must be a prime number."; std::cout << std::endl; From f432c0f5840d1151e4b4491abc55303e8dc8d4d9 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 16:22:10 -0400 Subject: [PATCH 127/433] documetnation for positive divisors --- math/number_of_positive_divisors.cpp | 46 ++++++++++++++++------------ 1 file changed, 27 insertions(+), 19 deletions(-) diff --git a/math/number_of_positive_divisors.cpp b/math/number_of_positive_divisors.cpp index 48ab63c3642..f157f7b4161 100644 --- a/math/number_of_positive_divisors.cpp +++ b/math/number_of_positive_divisors.cpp @@ -1,34 +1,39 @@ -/// C++ Program to calculate number of divisors. - -#include -#include - /** + * @file + * @brief C++ Program to calculate number of divisors + * * This algorithm use the prime factorization approach. * Any number can be written in multiplication of its prime factors. - * Let N = P1^E1 * P2^E2 ... Pk^Ek - * Therefore. number-of-divisors(N) = (E1+1) * (E2+1) ... (Ek+1). - * Where P1, P2 ... Pk are prime factors and E1, E2 ... Ek are exponents respectively. + *
Let N = P1^E1 * P2^E2 ... Pk^Ek + *
Therefore. number-of-divisors(N) = (E1+1) * (E2+1) ... (Ek+1). + *
Where P1, P2 ... Pk are prime factors and E1, E2 ... Ek are exponents +respectively. * * Example:- - * N = 36 - * 36 = (3^2 * 2^2) - * number_of_positive_divisors(36) = (2+1) * (2+1) = 9. - * list of positive divisors of 36 = 1, 2, 3, 4, 6, 9, 12, 18, 36. + *
N = 36 + *
36 = (3^2 * 2^2) + *
number_of_positive_divisors(36) = (2+1) * (2+1) = 9. + *
list of positive divisors of 36 = 1, 2, 3, 4, 6, 9, 12, 18, 36. * * Similarly if N is -36 at that time number of positive divisors remain same. * * Example:- - * N = -36 - * -36 = -1 * (3^2 * 2^2) - * number_of_positive_divisors(-36) = (2+1) * (2+1) = 9. - * list of positive divisors of -36 = 1, 2, 3, 4, 6, 9, 12, 18, 36. + *
N = -36 + *
-36 = -1 * (3^2 * 2^2) + *
number_of_positive_divisors(-36) = (2+1) * (2+1) = 9. + *
list of positive divisors of -36 = 1, 2, 3, 4, 6, 9, 12, 18, 36. * **/ +#include +#include + +/** + * Algorithm + */ int number_of_positive_divisors(int n) { std::vector prime_exponent_count; - for (int i=2; i*i <= n; i++) { + for (int i = 2; i * i <= n; i++) { int prime_count = 0; while (n % i == 0) { prime_count += 1; @@ -44,13 +49,16 @@ int number_of_positive_divisors(int n) { int divisors_count = 1; - for (int i=0; i < prime_exponent_count.size(); i++) { - divisors_count = divisors_count * (prime_exponent_count[i]+1); + for (int i = 0; i < prime_exponent_count.size(); i++) { + divisors_count = divisors_count * (prime_exponent_count[i] + 1); } return divisors_count; } +/** + * Main function + */ int main() { int n; std::cin >> n; From 9154d5a25dde12744898c5d5cd19ab9c1b3f0268 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 16:22:22 -0400 Subject: [PATCH 128/433] docs for large number power --- math/power_for_huge_numbers.cpp | 147 ++++++++++++++++---------------- 1 file changed, 73 insertions(+), 74 deletions(-) diff --git a/math/power_for_huge_numbers.cpp b/math/power_for_huge_numbers.cpp index bf93742289d..5cb1ae514d6 100644 --- a/math/power_for_huge_numbers.cpp +++ b/math/power_for_huge_numbers.cpp @@ -1,91 +1,90 @@ +/** + * @file + * @brief Compute powers of large numbers + */ #include -using namespace std; -// Maximum number of digits in output -// x^n where 1 <= x, n <= 10000 and overflow may happen +/** Maximum number of digits in output + * \f$x^n\f$ where \f$1 <= x,\; n <= 10000\f$ and overflow may happen + */ #define MAX 100000 -// This function multiplies x -// with the number represented by res[]. -// res_size is size of res[] or -// number of digits in the number -// represented by res[]. This function -// uses simple school mathematics -// for multiplication. -// This function may value of res_size -// and returns the new value of res_size -int multiply(int x, int res[], int res_size) -{ +/** This function multiplies x + * with the number represented by res[]. + * res_size is size of res[] or + * number of digits in the number + * represented by res[]. This function + * uses simple school mathematics + * for multiplication. + * This function may value of res_size + * and returns the new value of res_size + * @param x multiplicand + * @param res large number representation using array + * @param res_size number of digits in `res` + */ +int multiply(int x, int res[], int res_size) { + // Initialize carry + int carry = 0; - // Initialize carry - int carry = 0; + // One by one multiply n with + // individual digits of res[] + for (int i = 0; i < res_size; i++) { + int prod = res[i] * x + carry; - // One by one multiply n with - // individual digits of res[] - for (int i = 0; i < res_size; i++) - { - int prod = res[i] * x + carry; + // Store last digit of + // 'prod' in res[] + res[i] = prod % 10; - // Store last digit of - // 'prod' in res[] - res[i] = prod % 10; + // Put rest in carry + carry = prod / 10; + } - // Put rest in carry - carry = prod / 10; - } - - // Put carry in res and - // increase result size - while (carry) - { - res[res_size] = carry % 10; - carry = carry / 10; - res_size++; - } - return res_size; + // Put carry in res and + // increase result size + while (carry) { + res[res_size] = carry % 10; + carry = carry / 10; + res_size++; + } + return res_size; } -// This function finds -// power of a number x -void power(int x, int n) -{ - - //printing value "1" for power = 0 - if (n == 0) - { - cout << "1"; - return; - } +/** This function finds power of a number x and print \f$x^n\f$ + * @param x base + * @param n exponent + */ +void power(int x, int n) { + // printing value "1" for power = 0 + if (n == 0) { + std::cout << "1"; + return; + } - int res[MAX]; - int res_size = 0; - int temp = x; + int res[MAX]; + int res_size = 0; + int temp = x; - // Initialize result - while (temp != 0) - { - res[res_size++] = temp % 10; - temp = temp / 10; - } + // Initialize result + while (temp != 0) { + res[res_size++] = temp % 10; + temp = temp / 10; + } - // Multiply x n times - // (x^n = x*x*x....n times) - for (int i = 2; i <= n; i++) - res_size = multiply(x, res, res_size); + // Multiply x n times + // (x^n = x*x*x....n times) + for (int i = 2; i <= n; i++) res_size = multiply(x, res, res_size); - cout << x << "^" << n << " = "; - for (int i = res_size - 1; i >= 0; i--) - cout << res[i]; + std::cout << x << "^" << n << " = "; + for (int i = res_size - 1; i >= 0; i--) std::cout << res[i]; } -// Driver program -int main() -{ - int exponent, base; - printf("Enter base "); - scanf("%id \n", &base); - printf("Enter exponent "); - scanf("%id", &exponent); - power(base, exponent); - return 0; +/** Main function */ +int main() { + int exponent, base; + printf("Enter base "); + scanf("%id \n", &base); + printf("Enter exponent "); + scanf("%id", &exponent); + power(base, exponent); + return 0; } From 093b993cc717aabdabc3886dca65bc7ba8b47348 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 16:44:58 -0400 Subject: [PATCH 129/433] fix cpplint --- math/extended_euclid_algorithm.cpp | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/math/extended_euclid_algorithm.cpp b/math/extended_euclid_algorithm.cpp index 84dec55c53e..3fdae25b56a 100644 --- a/math/extended_euclid_algorithm.cpp +++ b/math/extended_euclid_algorithm.cpp @@ -16,15 +16,15 @@ * function to update the coefficients per iteration * \f[r_0,\,r = r,\, r_0 - \text{quotient}\times r\f] * - * @param[in,out] r signed - * @param[in,out] r0 signed - * @param[in] quotient unsigned input + * @param[in,out] r signed or unsigned + * @param[in,out] r0 signed or unsigned + * @param[in] quotient unsigned */ template -inline void update_step(T &r, T &r0, const T2 quotient) { - T temp = r; - r = r0 - (quotient * temp); - r0 = temp; +inline void update_step(T *r, T *r0, const T2 quotient) { + T temp = *r; + *r = *r0 - (quotient * temp); + *r0 = temp; } /** @@ -47,9 +47,9 @@ void extendedEuclid_1(T1 A, T1 B, T1 *GCD, T2 *x, T2 *y) { while (r != 0) { T1 quotient = r0 / r; - update_step(r, r0, quotient); - update_step(s, s0, quotient); - update_step(t, t0, quotient); + update_step(&r, &r0, quotient); + update_step(&s, &s0, quotient); + update_step(&t, &t0, quotient); } *GCD = r0; *x = s0; From ea3f8bbf29381b0a999891d6590c934cd2cdbacc Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 16:45:33 -0400 Subject: [PATCH 130/433] documentation and bug fixes --- math/prime_factorization.cpp | 22 ++++++---- math/prime_numbers.cpp | 15 +++++-- math/primes_up_to_billion.cpp | 10 +++++ math/sieve_of_eratosthenes.cpp | 74 ++++++++++++++++------------------ 4 files changed, 71 insertions(+), 50 deletions(-) diff --git a/math/prime_factorization.cpp b/math/prime_factorization.cpp index c018de6662a..d0e05cb4ca7 100644 --- a/math/prime_factorization.cpp +++ b/math/prime_factorization.cpp @@ -1,15 +1,25 @@ +/** + * @file + * @brief Prime factorization of positive integers + */ #include #include #include #include -// Declaring variables for maintaing prime numbers and to check whether a number -// is prime or not +/** Declaring variables for maintaing prime numbers and to check whether a + * number is prime or not + */ bool isprime[1000006]; + +/** list of prime numbers */ std::vector prime_numbers; + +/** list of prime factor-pairs */ std::vector> factors; -// Calculating prime number upto a given range +/** Calculating prime number upto a given range + */ void SieveOfEratosthenes(int N) { // initializes the array isprime memset(isprime, true, sizeof isprime); @@ -25,7 +35,7 @@ void SieveOfEratosthenes(int N) { } } -// Prime factorization of a number +/** Prime factorization of a number */ void prime_factorization(int num) { int number = num; @@ -46,9 +56,7 @@ void prime_factorization(int num) { } } -/* - I added a simple UI. -*/ +/** Main program */ int main() { int num; std::cout << "\t\tComputes the prime factorization\n\n"; diff --git a/math/prime_numbers.cpp b/math/prime_numbers.cpp index 7264ff5287c..4dd54f13657 100644 --- a/math/prime_numbers.cpp +++ b/math/prime_numbers.cpp @@ -1,26 +1,33 @@ +/** + * @file + * @brief Get list of prime numbers + * @see primes_up_to_billion.cpp sieve_of_eratosthenes.cpp + */ #include #include +/** Generate an increasingly large number of primes + * and store in a list + */ std::vector primes(int max) { max++; std::vector res; std::vector numbers(max, false); for (int i = 2; i < max; i++) { if (!numbers[i]) { - for (int j = i; j < max; j += i) - numbers[j] = true; + for (int j = i; j < max; j += i) numbers[j] = true; res.push_back(i); } } return res; } +/** main function */ int main() { std::cout << "Calculate primes up to:\n>> "; int n; std::cin >> n; std::vector ans = primes(n); - for (int i = 0; i < ans.size(); i++) - std::cout << ans[i] << ' '; + for (int i = 0; i < ans.size(); i++) std::cout << ans[i] << ' '; std::cout << std::endl; } diff --git a/math/primes_up_to_billion.cpp b/math/primes_up_to_billion.cpp index d8f5a9f9d3e..4fb79a15e7c 100644 --- a/math/primes_up_to_billion.cpp +++ b/math/primes_up_to_billion.cpp @@ -1,8 +1,15 @@ +/** + * @file + * @brief Compute prime numbers upto 1 billion + * @see prime_numbers.cpp sieve_of_eratosthenes.cpp + */ #include #include +/** array to store the primes */ char prime[100000000]; +/** Perform Sieve algorithm */ void Sieve(int64_t n) { memset(prime, '1', sizeof(prime)); // intitize '1' to every index prime[0] = '0'; // 0 is not prime @@ -15,6 +22,7 @@ void Sieve(int64_t n) { } } +/** Main function */ int main() { Sieve(100000000); int64_t n; @@ -23,4 +31,6 @@ int main() { std::cout << "YES\n"; else std::cout << "NO\n"; + + return 0; } diff --git a/math/sieve_of_eratosthenes.cpp b/math/sieve_of_eratosthenes.cpp index e600e480d7b..d8fa705313e 100644 --- a/math/sieve_of_eratosthenes.cpp +++ b/math/sieve_of_eratosthenes.cpp @@ -1,69 +1,65 @@ -/* - * Sieve of Eratosthenes is an algorithm to find the primes +/** + * @file + * @brief Get list of prime numbers using Sieve of Eratosthenes + * Sieve of Eratosthenes is an algorithm to find the primes * that is between 2 to N (as defined in main). * - * Time Complexity : O(N * log N) - * Space Complexity : O(N) + * Time Complexity : \f$O(N \cdot\log N)\f$ + *
Space Complexity : \f$O(N)\f$ + * + * @see primes_up_to_billion.cpp prime_numbers.cpp */ #include -using namespace std; +/** Maximum number of primes */ #define MAX 10000000 -int isprime[MAX]; +/** array to store the primes */ +bool isprime[MAX]; -/* - * This is the function that finds the primes and eliminates +/** + * This is the function that finds the primes and eliminates * the multiples. */ -void sieve(int N) -{ - isprime[0] = 0; - isprime[1] = 0; - for (int i = 2; i <= N; i++) - { - if (isprime[i]) - { - for (int j = i * 2; j <= N; j += i) - { - isprime[j] = 0; +void sieve(uint32_t N) { + isprime[0] = false; + isprime[1] = false; + for (uint32_t i = 2; i <= N; i++) { + if (isprime[i]) { + for (uint32_t j = (i << 1); j <= N; j += i) { + isprime[j] = false; } } } } -/* +/** * This function prints out the primes to STDOUT */ -void print(int N) -{ - for (int i = 1; i <= N; i++) - { - if (isprime[i] == 1) - { - cout << i << ' '; +void print(uint32_t N) { + for (uint32_t i = 1; i <= N; i++) { + if (isprime[i]) { + std::cout << i << ' '; } } - cout << '\n'; + std::cout << std::endl; } -/* - * NOTE: This function is important for the - * initialization of the array. +/** + * Initialize the array */ -void init() -{ - for (int i = 1; i < MAX; i++) - { - isprime[i] = 1; +void init() { + for (uint32_t i = 1; i < MAX; i++) { + isprime[i] = true; } } -int main() -{ - int N = 100; +/** main function */ +int main() { + uint32_t N = 100; init(); sieve(N); print(N); + return 0; } From 6cd589a75287298317b04ed2e221bd63f0a7c593 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 16:47:32 -0400 Subject: [PATCH 131/433] math readme title --- math/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/math/README.md b/math/README.md index 4ac39c87877..d7b862f9f77 100644 --- a/math/README.md +++ b/math/README.md @@ -1,3 +1,4 @@ +# Prime factorization # {#section} Prime Factorization is a very important and useful technique to factorize any number into its prime factors. It has various applications in the field of number theory. The method of prime factorization involves two function calls. From 27cea79fa3538ab18c36d3aa64c28624041b1357 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 16:58:30 -0400 Subject: [PATCH 132/433] document square-root that uses bisection method --- math/sqrt_double.cpp | 50 ++++++++++++++++++++++++++------------------ 1 file changed, 30 insertions(+), 20 deletions(-) diff --git a/math/sqrt_double.cpp b/math/sqrt_double.cpp index 5a0fd1c88a5..1521b500a19 100644 --- a/math/sqrt_double.cpp +++ b/math/sqrt_double.cpp @@ -1,27 +1,35 @@ -#include +/** + * @file + * @brief Calculate the square root of any positive number in \f$O(\log N)\f$ + * time, with precision fixed using [bisection + * method](https://en.wikipedia.org/wiki/Bisection_method) of root-finding. + * + * @see Can be implemented using faster and better algorithms like + * newton_raphson_method.cpp and false_position.cpp + */ #include +#include -/* Calculate the square root of any -number in O(logn) time, -with precision fixed */ - -double Sqrt(double x) { - if ( x > 0 && x < 1 ) { - return 1/Sqrt(1/x); +/** Bisection method implemented for the function \f$x^2-a=0\f$ + * whose roots are \f$\pm\sqrt{a}\f$ and only the positive root is returned. + */ +double Sqrt(double a) { + if (a > 0 && a < 1) { + return 1 / Sqrt(1 / a); } - double l = 0, r = x; - /* Epsilon is the precision. - A great precision is + double l = 0, r = a; + /* Epsilon is the precision. + A great precision is between 1e-7 and 1e-12. double epsilon = 1e-12; */ double epsilon = 1e-12; - while ( l <= r ) { + while (l <= r) { double mid = (l + r) / 2; - if ( mid * mid > x ) { + if (mid * mid > a) { r = mid; } else { - if ( x - mid * mid < epsilon ) { + if (a - mid * mid < epsilon) { return mid; } l = mid; @@ -29,11 +37,13 @@ double Sqrt(double x) { } return -1; } + +/** main function */ int main() { - double n{}; - std::cin >> n; - assert(n >= 0); - // Change this line for a better precision - std::cout.precision(12); - std::cout << std::fixed << Sqrt(n); + double n{}; + std::cin >> n; + assert(n >= 0); + // Change this line for a better precision + std::cout.precision(12); + std::cout << std::fixed << Sqrt(n); } From 9965614174f64085422d1a82fa6a67273cc730fb Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 17:32:10 -0400 Subject: [PATCH 133/433] added documetnation to large_factorial.cpp --- others/large_factorial.cpp | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/others/large_factorial.cpp b/others/large_factorial.cpp index 6d538558943..1027f41abf8 100644 --- a/others/large_factorial.cpp +++ b/others/large_factorial.cpp @@ -1,10 +1,18 @@ -#include - +/** + * @file + * @brief Compute factorial of any arbitratily large number/ + * + * @see factorial.cpp + */ +#include #include #include #include "./large_number.h" +/** Test implementation for 10! Result must be 3628800. + * @returns True if test pass else False + */ bool test1() { std::cout << "---- Check 1\t"; unsigned int i, number = 10; @@ -34,6 +42,14 @@ bool test1() { return true; } +/** Test implementation for 100! The result is the 156 digit number: + * ``` + * 9332621544394415268169923885626670049071596826438162146859296389521759 + * 9993229915608941463976156518286253697920827223758251185210916864000000 + * 000000000000000000 + * ``` + * @returns True if test pass else False + */ bool test2() { std::cout << "---- Check 2\t"; unsigned int i, number = 100; From 772e7fb789be4a7db263bb2f1cabc0fc829f6042 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 17:32:46 -0400 Subject: [PATCH 134/433] removed author details from comments for header file --- others/large_number.h | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/others/large_number.h b/others/large_number.h index 54468298734..9596221878e 100644 --- a/others/large_number.h +++ b/others/large_number.h @@ -1,8 +1,8 @@ /** * @file - * @author Krishna Vedala - * @email krishna (dot) vedala (at) ieee (dot) org - **/ + * @brief Library to perform arithmatic operations on arbitrarily large + * numbers. + */ #ifndef OTHERS_LARGE_NUMBER_H_ #define OTHERS_LARGE_NUMBER_H_ @@ -53,7 +53,8 @@ class large_number { explicit large_number(char const *number_str) { for (size_t i = strlen(number_str); i > 0; i--) { unsigned char a = number_str[i - 1] - '0'; - if (a >= 0 && a <= 9) _digits.push_back(a); + if (a >= 0 && a <= 9) + _digits.push_back(a); } } @@ -152,9 +153,11 @@ class large_number { **/ friend bool operator==(large_number const &a, large_number const &b) { size_t N = a.num_digits(); - if (N != b.num_digits()) return false; + if (N != b.num_digits()) + return false; for (size_t i = 0; i < N; i++) - if (a[i] != b[i]) return false; + if (a[i] != b[i]) + return false; return true; } @@ -192,8 +195,10 @@ class large_number { unsigned int carry = 0; size_t i; for (i = 0; i < max_L || carry != 0; i++) { - if (i < b->num_digits()) carry += (*b)[i]; - if (i < this->num_digits()) carry += (*this)[i]; + if (i < b->num_digits()) + carry += (*b)[i]; + if (i < this->num_digits()) + carry += (*this)[i]; if (i < this->num_digits()) (*this)[i] = carry % 10; else From 962e27a2bef143b13266ba18142a220f6b59eac3 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Wed, 27 May 2020 21:38:10 +0000 Subject: [PATCH 135/433] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 37132246bd0..d627af28c5f 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -138,6 +138,7 @@ * [Decimal To Roman Numeral](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/decimal_to_roman_numeral.cpp) * [Fast Interger Input](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/fast_interger_input.cpp) * [Fibonacci Fast](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/fibonacci_fast.cpp) + * [Fibonacci Large](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/fibonacci_large.cpp) * [Gcd Of N Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/gcd_of_n_numbers.cpp) * [Happy Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/happy_number.cpp) * [Large Factorial](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/large_factorial.cpp) From 0228c388e4b8f6c8081c71d0c35e4b160d89f4e5 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Wed, 27 May 2020 17:43:02 -0400 Subject: [PATCH 136/433] use the correct repo for badges --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4befc6afa7f..9f16cb6b2fb 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # The Algorithms - C++ # {#mainpage} -[![contributions welcome](https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square)](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTION.md)  -![GitHub repo size](https://img.shields.io/github/repo-size/TheAlgorithms/C-Plus-Plus?color=red&style=flat-square) +[![contributions welcome](https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square)](https://github.com/kvedala/C-Plus-Plus/blob/master/CONTRIBUTION.md)  +![GitHub repo size](https://img.shields.io/github/repo-size/kvedala/C-Plus-Plus?color=red&style=flat-square) ![GitHub closed pull requests](https://img.shields.io/github/issues-pr-closed/TheAlgorithms/C-Plus-Plus?color=green&style=flat-square) ![Doxygen CI](https://github.com/kvedala/C-Plus-Plus/workflows/Doxygen%20CI/badge.svg) ![cpplint](https://github.com/kvedala/C-Plus-Plus/workflows/cpplint_modified_files/badge.svg) From 08470a9e2226bd4d5861e2bb5b3e4517cb0098bc Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Wed, 27 May 2020 17:43:37 -0400 Subject: [PATCH 137/433] fixed another repo badge link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9f16cb6b2fb..b56c4f5f40e 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # The Algorithms - C++ # {#mainpage} [![contributions welcome](https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square)](https://github.com/kvedala/C-Plus-Plus/blob/master/CONTRIBUTION.md)  ![GitHub repo size](https://img.shields.io/github/repo-size/kvedala/C-Plus-Plus?color=red&style=flat-square) -![GitHub closed pull requests](https://img.shields.io/github/issues-pr-closed/TheAlgorithms/C-Plus-Plus?color=green&style=flat-square) +![GitHub closed pull requests](https://img.shields.io/github/issues-pr-closed/kvedala/C-Plus-Plus?color=green&style=flat-square) ![Doxygen CI](https://github.com/kvedala/C-Plus-Plus/workflows/Doxygen%20CI/badge.svg) ![cpplint](https://github.com/kvedala/C-Plus-Plus/workflows/cpplint_modified_files/badge.svg) ![C/C++ CI](https://github.com/kvedala/C-Plus-Plus/workflows/C/C++%20CI/badge.svg) From c27fa436b894a2cf9dfcd45e9df6c1eac156ff34 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 17:57:38 -0400 Subject: [PATCH 138/433] remove redundant file --- others/sieve_of_Eratosthenes.cpp | 60 -------------------------------- 1 file changed, 60 deletions(-) delete mode 100644 others/sieve_of_Eratosthenes.cpp diff --git a/others/sieve_of_Eratosthenes.cpp b/others/sieve_of_Eratosthenes.cpp deleted file mode 100644 index e87ad498367..00000000000 --- a/others/sieve_of_Eratosthenes.cpp +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Sieve of Eratosthenes is an algorithm to find the primes - * that is between 2 to N (as defined in main). - * - * Time Complexity : O(N) - * Space Complexity : O(N) - */ - -#include -using namespace std; - -#define MAX 10000000 - -int primes[MAX]; - -/* - * This is the function that finds the primes and eliminates - * the multiples. - */ -void sieve(int N) -{ - primes[0] = 1; - primes[1] = 1; - for (int i = 2; i <= N; i++) - { - if (primes[i] == 1) - continue; - for (int j = i + i; j <= N; j += i) - primes[j] = 1; - } -} - -/* - * This function prints out the primes to STDOUT - */ -void print(int N) -{ - for (int i = 0; i <= N; i++) - if (primes[i] == 0) - cout << i << ' '; - cout << '\n'; -} - -/* - * NOTE: This function is important for the - * initialization of the array. - */ -void init() -{ - for (int i = 0; i < MAX; i++) - primes[i] = 0; -} - -int main() -{ - int N = 100; - init(); - sieve(N); - print(N); -} From 6dfdfa6662938fe0d932fd7d81b9ca9d1ef4032c Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 17:58:17 -0400 Subject: [PATCH 139/433] fibonacci documentation --- math/fibonacci.cpp | 5 ++++- others/fibonacci_large.cpp | 11 +++++++++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/math/fibonacci.cpp b/math/fibonacci.cpp index 1a5f4afb40f..034b919702d 100644 --- a/math/fibonacci.cpp +++ b/math/fibonacci.cpp @@ -5,6 +5,8 @@ * Calculate the the value on Fibonacci's sequence given an * integer as input. * \f[\text{fib}(n) = \text{fib}(n-1) + \text{fib}(n-2)\f] + * + * @see fibonacci_large.cpp */ #include #include @@ -15,7 +17,8 @@ int fibonacci(unsigned int n) { /* If the input is 0 or 1 just return the same This will set the first 2 values of the sequence */ - if (n <= 1) return n; + if (n <= 1) + return n; /* Add the last 2 values of the sequence to get next */ return fibonacci(n - 1) + fibonacci(n - 2); diff --git a/others/fibonacci_large.cpp b/others/fibonacci_large.cpp index 6f36702a28c..6b556066a4b 100644 --- a/others/fibonacci_large.cpp +++ b/others/fibonacci_large.cpp @@ -1,11 +1,14 @@ /** - * Computes N^th Fibonacci number given as + * @file + * @brief Computes N^th Fibonacci number given as * input argument. Uses custom build arbitrary integers library * to perform additions and other operations. * * Took 0.608246 seconds to compute 50,000^th Fibonacci * number that contains 10450 digits! - **/ + * + * @see fibonacci.cpp + */ #include #include @@ -13,6 +16,10 @@ #include "./large_number.h" +/** Compute fibonacci numbers using the relation + * \f[f(n)=f(n-1)+f(n-2)\f] + * and returns the result as a large_number type. + */ large_number fib(uint64_t n) { large_number f0(1); large_number f1(1); From e963ba4c5b22f0e0984c60d474d329e88e761f93 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 18:00:02 -0400 Subject: [PATCH 140/433] fix buzz number --- others/buzz_number.cpp | 33 ++++++++++++++++++--------------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/others/buzz_number.cpp b/others/buzz_number.cpp index f31038aad61..ed9fc5f2888 100644 --- a/others/buzz_number.cpp +++ b/others/buzz_number.cpp @@ -1,17 +1,20 @@ -//A buzz number is a number that is either divisble by 7 or has last digit as 7. +/** + * @file + * @brief A buzz number is a number that is either divisible by 7 or has last + * digit as 7. + */ #include -using namespace std; -int main() -{ - int n, t; - cin >> t; - while (t--) - { - cin >> n; - if ((n % 7 == 0) || (n % 10 == 7)) - cout << n << " is a buzz number" << endl; - else - cout << n << " is not a buzz number" << endl; - } - return 0; + +/** main function */ +int main() { + int n, t; + std::cin >> t; + while (t--) { + std::cin >> n; + if ((n % 7 == 0) || (n % 10 == 7)) + std::cout << n << " is a buzz number" << std::endl; + else + std::cout << n << " is not a buzz number" << std::endl; + } + return 0; } From e7632d107caddbf7928f872f509678e678a5262c Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 18:16:32 -0400 Subject: [PATCH 141/433] fixed CPPLINT + added method 2 --- others/decimal_to_binary.cpp | 76 +++++++++++++++++++++++++----------- 1 file changed, 53 insertions(+), 23 deletions(-) diff --git a/others/decimal_to_binary.cpp b/others/decimal_to_binary.cpp index 4e2119ebce8..11ce064a538 100644 --- a/others/decimal_to_binary.cpp +++ b/others/decimal_to_binary.cpp @@ -1,25 +1,55 @@ -// This function convert decimal to binary number -// +/** + * @file + * @brief Function to convert decimal number to binary representation + */ #include -using namespace std; - -int main() -{ - int number; - cout << "Enter a number:"; - cin >> number; - int remainder, binary = 0, var = 1; - - do - { - remainder = number % 2; - number = number / 2; - binary = binary + (remainder * var); - var = var * 10; - - } while (number > 0); - cout << "the binary is :"; - cout << binary; - cout << endl; - return 0; + +/** + * This method converts the bit representation and stores it as a decimal + * number. + */ +void method1(int number) { + int remainder, binary = 0, var = 1; + + do { + remainder = number % 2; + number = number / 2; + binary = binary + (remainder * var); + var = var * 10; + } while (number > 0); + std::cout << "Method 1 : " << binary << std::endl; +} + +/** + * This method stores each bit value from LSB to MSB and then prints them back + * from MSB to LSB + */ +void method2(int number) { + int num_bits = 0; + char bit_string[50]; + + do { + bool bit = number & 0x01; // get last bit + if (bit) + bit_string[num_bits++] = '1'; + else + bit_string[num_bits++] = '0'; + number >>= 1; // right shift bit 1 bit + } while (number > 0); + + std::cout << "Method 2 : "; + while (num_bits >= 0) + std::cout << bit_string[num_bits--]; // print from MSB to LSB + std::cout << std::endl; +} + +int main() { + int number; + std::cout << "Enter a number:"; + std::cin >> number; + + method1(number); + method2(number); + + return 0; } From 7e875baab71de9b02537e7d9a1075ec9bdc4ccc3 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 18:22:49 -0400 Subject: [PATCH 142/433] fixed decimal to hex --- others/decimal_to_hexadecimal.cpp | 48 +++++++++++++++++-------------- 1 file changed, 27 insertions(+), 21 deletions(-) diff --git a/others/decimal_to_hexadecimal.cpp b/others/decimal_to_hexadecimal.cpp index 705f21ba49f..a3e544f49f8 100644 --- a/others/decimal_to_hexadecimal.cpp +++ b/others/decimal_to_hexadecimal.cpp @@ -1,28 +1,34 @@ -#include +/** + * @file + * @brief Convert decimal number to hexadecimal representation + */ -using namespace std; +#include -int main(void) -{ - int valueToConvert = 0; //Holds user input - int hexArray[8]; //Contains hex values backwards - int i = 0; //counter - char HexValues[] = "0123456789ABCDEF"; +/** + * Main program + */ +int main(void) { + int valueToConvert = 0; // Holds user input + int hexArray[8]; // Contains hex values backwards + int i = 0; // counter + char HexValues[] = "0123456789ABCDEF"; - cout << "Enter a Decimal Value" << endl; //Displays request to stdout - cin >> valueToConvert; //Stores value into valueToConvert via user input + std::cout << "Enter a Decimal Value" + << std::endl; // Displays request to stdout + std::cin >> + valueToConvert; // Stores value into valueToConvert via user input - while (valueToConvert > 15) - { //Dec to Hex Algorithm - hexArray[i++] = valueToConvert % 16; //Gets remainder - valueToConvert /= 16; - } - hexArray[i] = valueToConvert; //Gets last value + while (valueToConvert > 15) { // Dec to Hex Algorithm + hexArray[i++] = valueToConvert % 16; // Gets remainder + valueToConvert /= 16; + // valueToConvert >>= 4; // This will divide by 2^4=16 and is faster + } + hexArray[i] = valueToConvert; // Gets last value - cout << "Hex Value: "; - while (i >= 0) - cout << HexValues[hexArray[i--]]; + std::cout << "Hex Value: "; + while (i >= 0) std::cout << HexValues[hexArray[i--]]; - cout << endl; - return 0; + std::cout << std::endl; + return 0; } From a8bdbbda355be055f5d99fa7e3dfcd71ea9a0ba9 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 18:22:57 -0400 Subject: [PATCH 143/433] fixed decimal to roman --- others/decimal_to_roman_numeral.cpp | 131 ++++++++++++---------------- 1 file changed, 55 insertions(+), 76 deletions(-) diff --git a/others/decimal_to_roman_numeral.cpp b/others/decimal_to_roman_numeral.cpp index 0372e800342..6bd1be39511 100644 --- a/others/decimal_to_roman_numeral.cpp +++ b/others/decimal_to_roman_numeral.cpp @@ -1,97 +1,76 @@ -//This Programme Converts a given decimal number in the range [0,4000) -//to both Lower case and Upper case Roman Numeral +/** + * @file + * @brief This Programme Converts a given decimal number in the range [0,4000) + * to both Lower case and Upper case Roman Numeral + */ #include #include -#include +#include #include -using namespace std; -//This functions fills a string with character c, n times and returns it -string fill(char c, int n) -{ - string s = ""; - while (n--) - s += c; +/** This functions fills a string with character c, n times and returns it + * @note This can probably be replace by `memcpy` function. + */ +std::string fill(char c, int n) { + std::string s = ""; + while (n--) s += c; return s; } -//to convert to lowercase Roman Numeral -// the function works recursively -string tolowerRoman(int n) -{ - if (n < 4) - return fill('i', n); - if (n < 6) - return fill('i', 5 - n) + "v"; - if (n < 9) - return string("v") + fill('i', n - 5); - if (n < 11) - return fill('i', 10 - n) + "x"; - if (n < 40) - return fill('x', n / 10) + tolowerRoman(n % 10); - if (n < 60) - return fill('x', 5 - n / 10) + 'l' + tolowerRoman(n % 10); +/** to convert to lowercase Roman Numeral + * the function works recursively + */ +std::string tolowerRoman(int n) { + if (n < 4) return fill('i', n); + if (n < 6) return fill('i', 5 - n) + "v"; + if (n < 9) return std::string("v") + fill('i', n - 5); + if (n < 11) return fill('i', 10 - n) + "x"; + if (n < 40) return fill('x', n / 10) + tolowerRoman(n % 10); + if (n < 60) return fill('x', 5 - n / 10) + 'l' + tolowerRoman(n % 10); if (n < 90) - return string("l") + fill('x', n / 10 - 5) + tolowerRoman(n % 10); - if (n < 110) - return fill('x', 10 - n / 10) + "c" + tolowerRoman(n % 10); - if (n < 400) - return fill('c', n / 100) + tolowerRoman(n % 100); - if (n < 600) - return fill('c', 5 - n / 100) + 'd' + tolowerRoman(n % 100); + return std::string("l") + fill('x', n / 10 - 5) + tolowerRoman(n % 10); + if (n < 110) return fill('x', 10 - n / 10) + "c" + tolowerRoman(n % 10); + if (n < 400) return fill('c', n / 100) + tolowerRoman(n % 100); + if (n < 600) return fill('c', 5 - n / 100) + 'd' + tolowerRoman(n % 100); if (n < 900) - return string("d") + fill('c', n / 100 - 5) + tolowerRoman(n % 100); - if (n < 1100) - return fill('c', 10 - n / 100) + "m" + tolowerRoman(n % 100); - if (n < 4000) - return fill('m', n / 1000) + tolowerRoman(n % 1000); + return std::string("d") + fill('c', n / 100 - 5) + + tolowerRoman(n % 100); + if (n < 1100) return fill('c', 10 - n / 100) + "m" + tolowerRoman(n % 100); + if (n < 4000) return fill('m', n / 1000) + tolowerRoman(n % 1000); return "?"; } -//to convert to uppercase Roman Numeral -// the function works recursively -string toupperRoman(int n) -{ - if (n < 4) - return fill('I', n); - if (n < 6) - return fill('I', 5 - n) + "V"; - if (n < 9) - return string("V") + fill('I', n - 5); - if (n < 11) - return fill('I', 10 - n) + "X"; - if (n < 40) - return fill('X', n / 10) + toupperRoman(n % 10); - if (n < 60) - return fill('X', 5 - n / 10) + 'L' + toupperRoman(n % 10); +/** to convert to uppercase Roman Numeral + * the function works recursively + */ +std::string toupperRoman(int n) { + if (n < 4) return fill('I', n); + if (n < 6) return fill('I', 5 - n) + "V"; + if (n < 9) return std::string("V") + fill('I', n - 5); + if (n < 11) return fill('I', 10 - n) + "X"; + if (n < 40) return fill('X', n / 10) + toupperRoman(n % 10); + if (n < 60) return fill('X', 5 - n / 10) + 'L' + toupperRoman(n % 10); if (n < 90) - return string("L") + fill('X', n / 10 - 5) + toupperRoman(n % 10); - if (n < 110) - return fill('X', 10 - n / 10) + "C" + toupperRoman(n % 10); - if (n < 400) - return fill('C', n / 100) + toupperRoman(n % 100); - if (n < 600) - return fill('C', 5 - n / 100) + 'D' + toupperRoman(n % 100); + return std::string("L") + fill('X', n / 10 - 5) + toupperRoman(n % 10); + if (n < 110) return fill('X', 10 - n / 10) + "C" + toupperRoman(n % 10); + if (n < 400) return fill('C', n / 100) + toupperRoman(n % 100); + if (n < 600) return fill('C', 5 - n / 100) + 'D' + toupperRoman(n % 100); if (n < 900) - return string("D") + fill('C', n / 100 - 5) + toupperRoman(n % 100); - if (n < 1100) - return fill('C', 10 - n / 100) + "M" + toupperRoman(n % 100); - if (n < 4000) - return fill('M', n / 1000) + toupperRoman(n % 1000); + return std::string("D") + fill('C', n / 100 - 5) + + toupperRoman(n % 100); + if (n < 1100) return fill('C', 10 - n / 100) + "M" + toupperRoman(n % 100); + if (n < 4000) return fill('M', n / 1000) + toupperRoman(n % 1000); return "?"; } -//main function - -int main() -{ - +/** main function */ +int main() { int n; - cout << "\t\tRoman numbers converter\n\n"; - cout << "Type in decimal number between 0 up to 4000 (exclusive): "; - cin >> n; - cout << n << " in Upper Roman Numerals is " << toupperRoman(n) << "\n"; - cout << n << " in Lower Roman Numerals is " << tolowerRoman(n) << "\n"; + std::cout << "\t\tRoman numbers converter\n\n"; + std::cout << "Type in decimal number between 0 up to 4000 (exclusive): "; + std::cin >> n; + std::cout << n << " in Upper Roman Numerals is " << toupperRoman(n) << "\n"; + std::cout << n << " in Lower Roman Numerals is " << tolowerRoman(n) << "\n"; return 0; } From 9249fa274323bf44c7c83bc152efc37f3268fc83 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Wed, 27 May 2020 22:41:28 +0000 Subject: [PATCH 144/433] updating DIRECTORY.md --- DIRECTORY.md | 1 - 1 file changed, 1 deletion(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index d627af28c5f..e99f32611bc 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -148,7 +148,6 @@ * [Paranthesis Matching](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/paranthesis_matching.cpp) * [Pascal Triangle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/pascal_triangle.cpp) * [Primality Test](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/primality_test.cpp) - * [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/sieve_of_Eratosthenes.cpp) * [Smallest-Circle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/smallest-circle.cpp) * [Sparse Matrix](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/sparse_matrix.cpp) * [Spiral Print](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/spiral_print.cpp) From 7238aa78697f217dd06e5d88a020fcd5a9630b0f Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 18:45:52 -0400 Subject: [PATCH 145/433] fix merge conflicts --- sorting/quick_sort.cpp | 63 ++++++++++++------------------------------ 1 file changed, 17 insertions(+), 46 deletions(-) diff --git a/sorting/quick_sort.cpp b/sorting/quick_sort.cpp index eaa5981f3e7..1db6b014e07 100644 --- a/sorting/quick_sort.cpp +++ b/sorting/quick_sort.cpp @@ -1,16 +1,6 @@ -<<<<<<< HEAD -/* C implementation QuickSort */ -#include - -int partition(int arr[], int low, int high) { - int pivot = arr[high]; // pivot - int i = (low - 1); // Index of smaller element -======= /** - * - * copyright The Algorithms - * Author - - * Correction - ayaankhan98 + * @file + * @brief Quick sort algorithm * * Implementation Details - * Quick Sort is a divide and conquer algorithm. It picks and element as @@ -35,28 +25,23 @@ int partition(int arr[], int low, int high) { #include /** - * This function takes last element as pivot, places - * the pivot element at its correct position in sorted - * array, and places all smaller (smaller than pivot) - * to left of pivot and all greater elements to right - * of pivot + * This function takes last element as pivot, places + * the pivot element at its correct position in sorted + * array, and places all smaller (smaller than pivot) + * to left of pivot and all greater elements to right + * of pivot * */ int partition(int arr[], int low, int high) { - int pivot = arr[high]; // taking the last element as pivot - int i = (low - 1); // Index of smaller element ->>>>>>> major-corrections-to-files + int pivot = arr[high]; // taking the last element as pivot + int i = (low - 1); // Index of smaller element for (int j = low; j < high; j++) { // If current element is smaller than or // equal to pivot if (arr[j] <= pivot) { -<<<<<<< HEAD i++; // increment index of smaller element -======= - i++; // increment index of smaller element ->>>>>>> major-corrections-to-files int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; @@ -68,41 +53,27 @@ int partition(int arr[], int low, int high) { return (i + 1); } -<<<<<<< HEAD -void quickSort(int arr[], int low, int high) { - if (low < high) { - int p = partition(arr, low, high); - -======= - -/** - * The main function that implements QuickSort - * arr[] --> Array to be sorted, - * low --> Starting index, - * high --> Ending index -*/ +/** + * The main function that implements QuickSort + * arr[] --> Array to be sorted, + * low --> Starting index, + * high --> Ending index + */ void quickSort(int arr[], int low, int high) { if (low < high) { int p = partition(arr, low, high); ->>>>>>> major-corrections-to-files quickSort(arr, low, p - 1); quickSort(arr, p + 1, high); } } -<<<<<<< HEAD -void show(int arr[], int size) { - for (int i = 0; i < size; i++) std::cout << arr[i] << "\n"; -======= // prints the array after sorting void show(int arr[], int size) { - for (int i = 0; i < size; i++) - std::cout << arr[i] << " "; + for (int i = 0; i < size; i++) std::cout << arr[i] << " "; std::cout << "\n"; ->>>>>>> major-corrections-to-files } -// Driver program to test above functions +/** Driver program to test above functions */ int main() { int size; std::cout << "\nEnter the number of elements : "; From 894cd9a71db8f67b5f279ad02df873191eb49e66 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 18:46:22 -0400 Subject: [PATCH 146/433] document fast_integer --- others/fast_interger_input.cpp | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/others/fast_interger_input.cpp b/others/fast_interger_input.cpp index 3358fc8bbe6..5e7bcb99d28 100644 --- a/others/fast_interger_input.cpp +++ b/others/fast_interger_input.cpp @@ -1,7 +1,15 @@ -// Read integers in the fastest way in c plus plus -#include +/** + * @file + * @brief Read integers from stdin continuously as they are entered without + * waiting for the `\n` character + */ +#include + +/** Function to read the number from stdin. The function reads input until a non + * numeric character is entered. + */ void fastinput(int *number) { -// variable to indicate sign of input integer + // variable to indicate sign of input integer bool negative = false; register int c; *number = 0; @@ -19,18 +27,17 @@ void fastinput(int *number) { // Keep on extracting characters if they are integers // i.e ASCII Value lies from '0'(48) to '9' (57) for (; (c > 47 && c < 58); c = std::getchar()) - *number = *number *10 + c - 48; + *number = *number * 10 + c - 48; // if scanned input has a negative sign, negate the // value of the input number - if (negative) - *(number) *= -1; + if (negative) *(number) *= -1; } -// Function Call +/** Main function */ int main() { int number; fastinput(&number); - std::cout << number << "\n"; + std::cout << number << std::endl; return 0; } From 28ffd29d4c5b5ccbfb19def617da359d551397e7 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 18:51:39 -0400 Subject: [PATCH 147/433] update documentation for gcd_of_n_numbers --- others/gcd_of_n_numbers.cpp | 41 +++++++++++++++++++++++++++---------- 1 file changed, 30 insertions(+), 11 deletions(-) diff --git a/others/gcd_of_n_numbers.cpp b/others/gcd_of_n_numbers.cpp index 37e82173a94..0a187f6d0c6 100644 --- a/others/gcd_of_n_numbers.cpp +++ b/others/gcd_of_n_numbers.cpp @@ -1,23 +1,42 @@ -// This program aims at calculating the GCD of n numbers by division method +/** + * @file + * @brief This program aims at calculating the GCD of n numbers by division + * method + * + * @see ../math/greatest_common_divisor.cpp + * greatest_common_divisor_euclidean.cpp + */ #include +/** Compute GCD using division algorithm + * + * @param[in] a array of integers to compute GCD for + * @param[in] n number of integers in array `a` + */ +int gcd(int *a, int n) { + int j = 1; // to access all elements of the array starting from 1 + int gcd = a[0]; + while (j < n) { + if (a[j] % gcd == 0) // value of gcd is as needed so far + j++; // so we check for next element + else + gcd = a[j] % gcd; // calculating GCD by division method + } + return gcd; +} + +/** Main function */ int main() { int n; std::cout << "Enter value of n:" << std::endl; std::cin >> n; int *a = new int[n]; - int i, j, gcd; + int i; std::cout << "Enter the n numbers:" << std::endl; for (i = 0; i < n; i++) std::cin >> a[i]; - j = 1; // to access all elements of the array starting from 1 - gcd = a[0]; - while (j < n) { - if (a[j] % gcd == 0) // value of gcd is as needed so far - j++; // so we check for next element - else - gcd = a[j] % gcd; // calculating GCD by division method - } - std::cout << "GCD of entered n numbers:" << gcd; + + std::cout << "GCD of entered n numbers:" << gcd(a, n) << std::endl; + delete[] a; return 0; } From 21c963c2f505e843f69be8799424c7744604c0c2 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 18:52:07 -0400 Subject: [PATCH 148/433] move the gcd_of_n_numbers to math folder along with all other GCD algorithms --- {others => math}/gcd_of_n_numbers.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {others => math}/gcd_of_n_numbers.cpp (100%) diff --git a/others/gcd_of_n_numbers.cpp b/math/gcd_of_n_numbers.cpp similarity index 100% rename from others/gcd_of_n_numbers.cpp rename to math/gcd_of_n_numbers.cpp From 0a58f8f08fd3eb4cfbcd079ab80a7a64b137b91a Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 18:55:09 -0400 Subject: [PATCH 149/433] include see-also for all gcd algos --- math/gcd_iterative_euclidean.cpp | 2 +- math/gcd_of_n_numbers.cpp | 3 +-- math/gcd_recursive_euclidean.cpp | 14 +++++++++----- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/math/gcd_iterative_euclidean.cpp b/math/gcd_iterative_euclidean.cpp index 61fb640a388..2c0651ad7ca 100644 --- a/math/gcd_iterative_euclidean.cpp +++ b/math/gcd_iterative_euclidean.cpp @@ -4,7 +4,7 @@ * *iterative form* of * [Euclidean algorithm](https://en.wikipedia.org/wiki/Euclidean_algorithm) * - * @see gcd_recursive_euclidean.cpp + * @see gcd_recursive_euclidean.cpp, gcd_of_n_numbers.cpp */ #include #include diff --git a/math/gcd_of_n_numbers.cpp b/math/gcd_of_n_numbers.cpp index 0a187f6d0c6..92968ff1265 100644 --- a/math/gcd_of_n_numbers.cpp +++ b/math/gcd_of_n_numbers.cpp @@ -3,8 +3,7 @@ * @brief This program aims at calculating the GCD of n numbers by division * method * - * @see ../math/greatest_common_divisor.cpp - * greatest_common_divisor_euclidean.cpp + * @see gcd_iterative_euclidean.cpp, gcd_recursive_euclidean.cpp */ #include diff --git a/math/gcd_recursive_euclidean.cpp b/math/gcd_recursive_euclidean.cpp index 3a1ca6e6613..2a3d2183c4e 100644 --- a/math/gcd_recursive_euclidean.cpp +++ b/math/gcd_recursive_euclidean.cpp @@ -4,7 +4,7 @@ * *recursive form* of * [Euclidean algorithm](https://en.wikipedia.org/wiki/Euclidean_algorithm) * - * @see gcd_iterative_euclidean.cpp + * @see gcd_iterative_euclidean.cpp, gcd_of_n_numbers.cpp */ #include @@ -21,14 +21,18 @@ int gcd(int num1, int num2) { } // Everything divides 0 - if (num1 == 0) return num2; - if (num2 == 0) return num1; + if (num1 == 0) + return num2; + if (num2 == 0) + return num1; // base case - if (num1 == num2) return num1; + if (num1 == num2) + return num1; // a is greater - if (num1 > num2) return gcd(num1 - num2, num2); + if (num1 > num2) + return gcd(num1 - num2, num2); return gcd(num1, num2 - num1); } From a53ba4b8569e8cbeb9b8f5522b2a32bdac9d12dc Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 18:58:21 -0400 Subject: [PATCH 150/433] document fibonacci fast & link to fibonacci numbers --- math/fibonacci.cpp | 2 +- others/fibonacci_fast.cpp | 39 ++++++++++++++++++++++++++------------ others/fibonacci_large.cpp | 2 +- 3 files changed, 29 insertions(+), 14 deletions(-) diff --git a/math/fibonacci.cpp b/math/fibonacci.cpp index 034b919702d..da7736564b3 100644 --- a/math/fibonacci.cpp +++ b/math/fibonacci.cpp @@ -6,7 +6,7 @@ * integer as input. * \f[\text{fib}(n) = \text{fib}(n-1) + \text{fib}(n-2)\f] * - * @see fibonacci_large.cpp + * @see fibonacci_large.cpp, fibonacci_fast.cpp */ #include #include diff --git a/others/fibonacci_fast.cpp b/others/fibonacci_fast.cpp index a0b83b640b2..dc59742b87c 100644 --- a/others/fibonacci_fast.cpp +++ b/others/fibonacci_fast.cpp @@ -1,25 +1,39 @@ -// An efficient way to calculate nth fibonacci number faster and simpler than -// O(nlogn) method of matrix exponentiation This works by using both recursion -// and dynamic programming. as 93rd fibonacci exceeds 19 digits, which cannot be -// stored in a single long long variable, we can only use it till 92nd fibonacci -// we can use it for 10000th fibonacci etc, if we implement bigintegers. -// This algorithm works with the fact that nth fibonacci can easily found if we -// have already found n/2th or (n+1)/2th fibonacci It is a property of fibonacci -// similar to matrix exponentiation. +/** + * @file + * @brief Faster computation of Fibonacci series + * + * An efficient way to calculate nth fibonacci number faster and simpler than + * \f$O(n\log n)\f$ method of matrix exponentiation This works by using both + * recursion and dynamic programming. as 93rd fibonacci exceeds 19 digits, which + * cannot be stored in a single long long variable, we can only use it till 92nd + * fibonacci we can use it for 10000th fibonacci etc, if we implement + * bigintegers. This algorithm works with the fact that nth fibonacci can easily + * found if we have already found n/2th or (n+1)/2th fibonacci It is a property + * of fibonacci similar to matrix exponentiation. + * + * @see fibonacci_large.cpp, fibonacci.cpp + */ #include #include #include +/** maximum number that can be computed - The result after 93 cannot be stored + * in a `uint64_t` data type. */ const uint64_t MAX = 93; +/** Array of computed fibonacci numbers */ uint64_t f[MAX] = {0}; +/** Algorithm */ uint64_t fib(uint64_t n) { - if (n == 0) return 0; - if (n == 1 || n == 2) return (f[n] = 1); + if (n == 0) + return 0; + if (n == 1 || n == 2) + return (f[n] = 1); - if (f[n]) return f[n]; + if (f[n]) + return f[n]; uint64_t k = (n % 2 != 0) ? (n + 1) / 2 : n / 2; @@ -28,10 +42,11 @@ uint64_t fib(uint64_t n) { return f[n]; } +/** Main function */ int main() { // Main Function for (uint64_t i = 1; i < 93; i++) { - std::cout << i << " th fibonacci number is " << fib(i) << "\n"; + std::cout << i << " th fibonacci number is " << fib(i) << std::endl; } return 0; } diff --git a/others/fibonacci_large.cpp b/others/fibonacci_large.cpp index 6b556066a4b..4545fdc9f9d 100644 --- a/others/fibonacci_large.cpp +++ b/others/fibonacci_large.cpp @@ -7,7 +7,7 @@ * Took 0.608246 seconds to compute 50,000^th Fibonacci * number that contains 10450 digits! * - * @see fibonacci.cpp + * @see fibonacci.cpp, fibonacci_fast.cpp */ #include From e480c049be85f5250e6bdcf89e7d2fea26c3156d Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 19:00:20 -0400 Subject: [PATCH 151/433] mode math algorithms to math folder --- {others => math}/fibonacci_fast.cpp | 0 {others => math}/fibonacci_large.cpp | 0 {others => math}/large_factorial.cpp | 0 {others => math}/large_number.h | 0 4 files changed, 0 insertions(+), 0 deletions(-) rename {others => math}/fibonacci_fast.cpp (100%) rename {others => math}/fibonacci_large.cpp (100%) rename {others => math}/large_factorial.cpp (100%) rename {others => math}/large_number.h (100%) diff --git a/others/fibonacci_fast.cpp b/math/fibonacci_fast.cpp similarity index 100% rename from others/fibonacci_fast.cpp rename to math/fibonacci_fast.cpp diff --git a/others/fibonacci_large.cpp b/math/fibonacci_large.cpp similarity index 100% rename from others/fibonacci_large.cpp rename to math/fibonacci_large.cpp diff --git a/others/large_factorial.cpp b/math/large_factorial.cpp similarity index 100% rename from others/large_factorial.cpp rename to math/large_factorial.cpp diff --git a/others/large_number.h b/math/large_number.h similarity index 100% rename from others/large_number.h rename to math/large_number.h From cd43716d892ba33bc92f058b256c6465f1552e10 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Wed, 27 May 2020 20:21:09 -0400 Subject: [PATCH 152/433] doxygen TAGFILE to provide more torough documentation for the STL classes from https://cppreference.com Based out of SO: https://stackoverflow.com/questions/43099899/can-i-make-doxygen-resolve-refs-to-c-standard-library-functions --- CMakeLists.txt | 5 +- doc/cppreference-doxygen-web.tag.xml | 35489 +++++++++++++++++++++++++ 2 files changed, 35493 insertions(+), 1 deletion(-) create mode 100644 doc/cppreference-doxygen-web.tag.xml diff --git a/CMakeLists.txt b/CMakeLists.txt index aafeb69d3c4..c072de6e0cf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -24,13 +24,16 @@ find_package(Doxygen OPTIONAL_COMPONENTS dot dia) if(DOXYGEN_FOUND) set(DOXYGEN_GENERATE_MAN NO) set(DOXYGEN_USE_MATHJAX YES) - set(DOXYGEN_FILE_PATTERNS *.cpp *.h *.hpp *.md) set(DOXYGEN_GENERATE_HTML YES) + set(DOXYGEN_EXTRACT_STATIC YES) set(DOXYGEN_INLINE_SOURCES YES) set(DOXYGEN_CREATE_SUBDIRS YES) + set(DOXYGEN_EXTRACT_PRIVATE YES) set(DOCYGEN_GENERATE_TREEVIEW YES) set(DOXYGEN_STRIP_CODE_COMMENTS NO) set(DOXYGEN_BUILTIN_STL_SUPPORT YES) + set(DOXYGEN_FILE_PATTERNS *.cpp *.h *.hpp *.md) + set(DOXYGEN_TAGFILES "doc/cppreference-doxygen-web.tag.xml=http://en.cppreference.com/w/") if(MSVC) set(DOXYGEN_CPP_CLI_SUPPORT YES) endif() diff --git a/doc/cppreference-doxygen-web.tag.xml b/doc/cppreference-doxygen-web.tag.xml new file mode 100644 index 00000000000..ea8388b8b8e --- /dev/null +++ b/doc/cppreference-doxygen-web.tag.xml @@ -0,0 +1,35489 @@ + + + + std + + std::is_function + + T + atomic_fetch_and_explicit + cpp/atomic/atomic_fetch_sub + + (T... args) + + + T + atomic_fetch_xor_explicit + cpp/atomic/atomic_fetch_xor + + (T... args) + + + T + set_unexpected + cpp/error/set_unexpected + + (T... args) + + std::input_iterator_tag + std::logical_and + std::is_integral + std::money_get + + T + fputs + cpp/io/c/fputs + + (T... args) + + std::basic_ofstream + std::ratio_subtract + + T + modf + cpp/numeric/math/modf + + (T... args) + + std::size_t + + T + not2 + cpp/utility/functional/not2 + + (T... args) + + + T + strlen + cpp/string/byte/strlen + + (T... args) + + + T + exp2 + cpp/numeric/math/exp2 + + (T... args) + + std::ctype_byname + std::wcout + + T + setiosflags + cpp/io/manip/setiosflags + + (T... args) + + + T + adjacent_difference + cpp/algorithm/adjacent_difference + + (T... args) + + + T + cos + cpp/numeric/math/cos + + (T... args) + + + T + fwscanf + cpp/io/c/fwscanf + + (T... args) + + + T + atomic_init + cpp/atomic/atomic_init + + (T... args) + + std::fstream + std::valarray + std::ratio_greater_equal + + T + forward_as_tuple + cpp/utility/tuple/forward_as_tuple + + (T... args) + + std::remove_extent + std::ratio_greater + + T + abort + cpp/utility/program/abort + + (T... args) + + + T + wcsncmp + cpp/string/wide/wcsncmp + + (T... args) + + std::intptr_t + std::regex_iterator + + T + set_intersection + cpp/algorithm/set_intersection + + (T... args) + + std::lock_guard + std::wbuffer_convert + std::modulus + std::ratio_divide + + T + atomic_signal_fence + cpp/atomic/atomic_signal_fence + + (T... args) + + + T + llabs + cpp/numeric/math/abs + + (T... args) + + + T + make_move_iterator + cpp/iterator/make_move_iterator + + (T... args) + + std::ostreambuf_iterator + std::dynarray + std::is_nothrow_move_constructible + std::vector + + T + scanf + cpp/io/c/fscanf + + (T... args) + + std::match_results + std::back_insert_iterator + + T + nextafter + cpp/numeric/math/nextafter + + (T... args) + + std::iterator + std::int8_t + + T + stol + cpp/string/basic_string/stol + + (T... args) + + + T + strcspn + cpp/string/byte/strcspn + + (T... args) + + + T + ungetwc + cpp/io/c/ungetwc + + (T... args) + + + T + transform + cpp/algorithm/transform + + (T... args) + + std::student_t_distribution + std::mt19937_64 + std::runtime_error + + T + putc + cpp/io/c/fputc + + (T... args) + + + T + iswdigit + cpp/string/wide/iswdigit + + (T... args) + + std::ranlux24_base + + T + rint + cpp/numeric/math/rint + + (T... args) + + std::allocator_traits + + T + memset + cpp/string/byte/memset + + (T... args) + + + T + isgraph + cpp/string/byte/isgraph + + (T... args) + + std::codecvt + std::ratio_less_equal + + T + replace_copy_if + cpp/algorithm/replace_copy + + (T... args) + + + T + scalbn + cpp/numeric/math/scalbn + + (T... args) + + std::condition_variable_any + + T + partial_sort_copy + cpp/algorithm/partial_sort_copy + + (T... args) + + std::deca + std::extreme_value_distribution + std::cout + std::decay + std::is_trivially_move_assignable + std::adopt_lock_t + + T + make_exception_ptr + cpp/error/make_exception_ptr + + (T... args) + + std::wcerr + + T + frexp + cpp/numeric/math/frexp + + (T... args) + + std::lognormal_distribution + + T + isxdigit + cpp/string/byte/isxdigit + + (T... args) + + std::wclog + + T + atomic_exchange_explicit + cpp/atomic/atomic_exchange + + (T... args) + + + T + wprintf + cpp/io/c/fwprintf + + (T... args) + + std::char_traits + std::remove_reference + + T + fdim + cpp/numeric/math/fdim + + (T... args) + + std::num_get + + T + wctype + cpp/string/wide/wctype + + (T... args) + + std::is_pointer + + T + mbrtoc32 + cpp/string/multibyte/mbrtoc32 + + (T... args) + + + T + setw + cpp/io/manip/setw + + (T... args) + + + T + get_temporary_buffer + cpp/memory/get_temporary_buffer + + (T... args) + + + T + fmax + cpp/numeric/math/fmax + + (T... args) + + std::multiset + + T + atomic_thread_fence + cpp/atomic/atomic_thread_fence + + (T... args) + + + T + atomic_exchange + cpp/atomic/atomic_exchange + + (T... args) + + std::weak_ptr + std::bidirectional_iterator_tag + std::wstring_convert + + T + fgetwc + cpp/io/c/fgetwc + + (T... args) + + + T + swprintf + cpp/io/c/fwprintf + + (T... args) + + + T + prev_permutation + cpp/algorithm/prev_permutation + + (T... args) + + std::greater_equal + std::is_trivially_constructible + + T + max_element + cpp/algorithm/max_element + + (T... args) + + std::string + std::discrete_distribution + std::wostream + std::is_polymorphic + + T + set_symmetric_difference + cpp/algorithm/set_symmetric_difference + + (T... args) + + + T + wcscpy + cpp/string/wide/wcscpy + + (T... args) + + + T + const_pointer_cast + cpp/memory/shared_ptr/pointer_cast + + (T... args) + + + T + minmax_element + cpp/algorithm/minmax_element + + (T... args) + + + T + wcstok + cpp/string/wide/wcstok + + (T... args) + + + T + ref + cpp/utility/functional/ref + + (T... args) + + std::reverse_iterator + + T + feupdateenv + cpp/numeric/fenv/feupdateenv + + (T... args) + + std::bad_array_new_length + + T + endl + cpp/io/manip/endl + + (T... args) + + + T + end + cpp/iterator/end + + (T... args) + + std::condition_variable + + T + wmemmove + cpp/string/wide/wmemmove + + (T... args) + + + T + fmin + cpp/numeric/math/fmin + + (T... args) + + + T + uninitialized_fill_n + cpp/memory/uninitialized_fill_n + + (T... args) + + std::ranlux48 + + T + nouppercase + cpp/io/manip/uppercase + + (T... args) + + + T + noshowpos + cpp/io/manip/showpos + + (T... args) + + + T + ctime + cpp/chrono/c/ctime + + (T... args) + + + T + wmemset + cpp/string/wide/wmemset + + (T... args) + + std::unexpected_handler + + T + iswpunct + cpp/string/wide/iswpunct + + (T... args) + + std::piecewise_constant_distribution + std::codecvt_base + std::set + + T + pop_heap + cpp/algorithm/pop_heap + + (T... args) + + + T + sprintf + cpp/io/c/fprintf + + (T... args) + + + T + fixed + cpp/io/manip/fixed + + (T... args) + + + T + make_shared + cpp/memory/shared_ptr/make_shared + + (T... args) + + std::forward_iterator_tag + std::codecvt_byname + std::pointer_safety + std::uint_least64_t + std::placeholders + std::nothrow_t + std::is_nothrow_copy_assignable + std::is_same + + T + make_heap + cpp/algorithm/make_heap + + (T... args) + + + T + fmod + cpp/numeric/math/fmod + + (T... args) + + std::unique_lock + std::basic_ostringstream + + T + atol + cpp/string/byte/atoi + + (T... args) + + std::is_error_code_enum + std::time_put_byname + + T + uninitialized_copy + cpp/memory/uninitialized_copy + + (T... args) + + std::time_get + + T + dynamic_pointer_cast + cpp/memory/shared_ptr/pointer_cast + + (T... args) + + + T + set_union + cpp/algorithm/set_union + + (T... args) + + std::regex + std::cin + + T + hexfloat + cpp/io/manip/fixed + + (T... args) + + + T + vswprintf + cpp/io/c/vfwprintf + + (T... args) + + + T + asctime + cpp/chrono/c/asctime + + (T... args) + + std::unordered_map + + T + iswspace + cpp/string/wide/iswspace + + (T... args) + + std::initializer_list + + T + nan + cpp/numeric/math/nan + + (T... args) + + + T + sort + cpp/algorithm/sort + + (T... args) + + + T + quick_exit + cpp/utility/program/quick_exit + + (T... args) + + std::is_const + + T + log10 + cpp/numeric/math/log10 + + (T... args) + + std::basic_regex + + T + mbstowcs + cpp/string/multibyte/mbstowcs + + (T... args) + + + T + isspace + cpp/string/byte/isspace + + (T... args) + + std::poisson_distribution + std::bad_typeid + + T + strncat + cpp/string/byte/strncat + + (T... args) + + std::less_equal + + T + isinf + cpp/numeric/math/isinf + + (T... args) + + + T + atof + cpp/string/byte/atof + + (T... args) + + std::sig_atomic_t + + T + erf + cpp/numeric/math/erf + + (T... args) + + + T + is_sorted_until + cpp/algorithm/is_sorted_until + + (T... args) + + + T + cbrt + cpp/numeric/math/cbrt + + (T... args) + + + T + log1p + cpp/numeric/math/log1p + + (T... args) + + + T + return_temporary_buffer + cpp/memory/return_temporary_buffer + + (T... args) + + + T + mbsrtowcs + cpp/string/multibyte/mbsrtowcs + + (T... args) + + + T + feraiseexcept + cpp/numeric/fenv/feraiseexcept + + (T... args) + + + T + fseek + cpp/io/c/fseek + + (T... args) + + std::make_unsigned + std::basic_filebuf + + T + atomic_fetch_or_explicit + cpp/atomic/atomic_fetch_or + + (T... args) + + std::logical_or + + T + log + cpp/numeric/math/log + + (T... args) + + + T + putchar + cpp/io/c/putchar + + (T... args) + + + T + make_tuple + cpp/utility/tuple/make_tuple + + (T... args) + + + T + expm1 + cpp/numeric/math/expm1 + + (T... args) + + std::wstringbuf + + T + fma + cpp/numeric/math/fma + + (T... args) + + std::kilo + std::bernoulli_distribution + + T + remove_copy_if + cpp/algorithm/remove_copy + + (T... args) + + + T + showpoint + cpp/io/manip/showpoint + + (T... args) + + std::int16_t + + T + fscanf + cpp/io/c/fscanf + + (T... args) + + + T + stable_partition + cpp/algorithm/stable_partition + + (T... args) + + std::basic_ios + std::int32_t + + T + fill_n + cpp/algorithm/fill_n + + (T... args) + + std::is_rvalue_reference + + T + remove_copy + cpp/algorithm/remove_copy + + (T... args) + + + T + atomic_compare_exchange_strong_explicit + cpp/atomic/atomic_compare_exchange + + (T... args) + + std::integral_constant + std::wsmatch + + T + wctomb + cpp/string/multibyte/wctomb + + (T... args) + + + T + fgets + cpp/io/c/fgets + + (T... args) + + + T + remainder + cpp/numeric/math/remainder + + (T... args) + + std::cerr + std::codecvt_utf8 + + T + allocate_shared + cpp/memory/shared_ptr/allocate_shared + + (T... args) + + std::ratio_add + + T + unique + cpp/algorithm/unique + + (T... args) + + std::is_trivially_move_constructible + + T + includes + cpp/algorithm/includes + + (T... args) + + + T + iswalnum + cpp/string/wide/iswalnum + + (T... args) + + std::wcsub_match + + T + exit + cpp/utility/program/exit + + (T... args) + + + T + put_time + cpp/io/manip/put_time + + (T... args) + + + T + to_string + cpp/string/basic_string/to_string + + (T... args) + + + T + is_heap_until + cpp/algorithm/is_heap_until + + (T... args) + + std::is_member_pointer + + T + wcstold + cpp/string/wide/wcstof + + (T... args) + + std::wstreampos + std::uint_least16_t + + T + stold + cpp/string/basic_string/stof + + (T... args) + + + T + ftell + cpp/io/c/ftell + + (T... args) + + std::tuple + + T + copy_backward + cpp/algorithm/copy_backward + + (T... args) + + + T + wcstoll + cpp/string/wide/wcstol + + (T... args) + + + T + perror + cpp/io/c/perror + + (T... args) + + + T + vwscanf + cpp/io/c/vfwscanf + + (T... args) + + + T + stable_sort + cpp/algorithm/stable_sort + + (T... args) + + std::make_signed + + T + generic_category + cpp/error/generic_category + + (T... args) + + + T + abs(int) + cpp/numeric/math/abs + + (T... args) + + + T + fgetws + cpp/io/c/fgetws + + (T... args) + + std::logic_error + std::sregex_iterator + + T + showpos + cpp/io/manip/showpos + + (T... args) + + std::int_least64_t + + T + exp + cpp/numeric/math/exp + + (T... args) + + std::binary_negate + + T + fill + cpp/algorithm/fill + + (T... args) + + + T + isalpha + cpp/string/byte/isalpha + + (T... args) + + std::discard_block_engine + std::is_trivially_assignable + std::add_cv + + T + lgamma + cpp/numeric/math/lgamma + + (T... args) + + std::pico + std::iterator_traits + std::is_trivially_default_constructible + + T + feclearexcept + cpp/numeric/fenv/feclearexcept + + (T... args) + + + T + wcsncpy + cpp/string/wide/wcsncpy + + (T... args) + + + T + undeclare_reachable + cpp/memory/gc/undeclare_reachable + + (T... args) + + std::shared_ptr + + T + oct + cpp/io/manip/hex + + (T... args) + + std::bad_alloc + std::ostringstream + std::basic_fstream + std::stringbuf + std::exponential_distribution + std::uint32_t + + T + strspn + cpp/string/byte/strspn + + (T... args) + + std::wcregex_iterator + std::bad_function_call + + T + realloc + cpp/memory/c/realloc + + (T... args) + + + T + copy + cpp/algorithm/copy + + (T... args) + + + T + binary_search + cpp/algorithm/binary_search + + (T... args) + + + T + system_category + cpp/error/system_category + + (T... args) + + + T + mbrtowc + cpp/string/multibyte/mbrtowc + + (T... args) + + std::false_type + + T + strtof + cpp/string/byte/strtof + + (T... args) + + + T + mem_fn + cpp/utility/functional/mem_fn + + (T... args) + + std::wregex + + T + distance + cpp/iterator/distance + + (T... args) + + + T + lock + cpp/thread/lock + + (T... args) + + + T + strcmp + cpp/string/byte/strcmp + + (T... args) + + + T + tmpfile + cpp/io/c/tmpfile + + (T... args) + + + T + hypot + cpp/numeric/math/hypot + + (T... args) + + + T + getenv + cpp/utility/program/getenv + + (T... args) + + + T + strrchr + cpp/string/byte/strrchr + + (T... args) + + + T + count + cpp/algorithm/count + + (T... args) + + std::uint_least8_t + + T + tan + cpp/numeric/math/tan + + (T... args) + + + T + strftime + cpp/chrono/c/strftime + + (T... args) + + std::uniform_real_distribution + + T + stod + cpp/string/basic_string/stof + + (T... args) + + + T + towupper + cpp/string/wide/towupper + + (T... args) + + std::smatch + std::cregex_token_iterator + std::range_error + std::is_assignable + + T + atoll + cpp/string/byte/atoi + + (T... args) + + std::is_copy_assignable + std::invalid_argument + + T + atomic_store + cpp/atomic/atomic_store + + (T... args) + + std::is_unsigned + std::jmp_buf + std::is_class + std::geometric_distribution + + T + stoi + cpp/string/basic_string/stol + + (T... args) + + + T + rethrow_exception + cpp/error/rethrow_exception + + (T... args) + + std::uint_fast8_t + + T + sin + cpp/numeric/math/sin + + (T... args) + + + T + atomic_fetch_sub_explicit + cpp/atomic/atomic_fetch_sub + + (T... args) + + + T + unexpected + cpp/error/unexpected + + (T... args) + + + T + mbtowc + cpp/string/multibyte/mbtowc + + (T... args) + + std::mersenne_twister_engine + + T + get_time + cpp/io/manip/get_time + + (T... args) + + + T + partition + cpp/algorithm/partition + + (T... args) + + + T + next + cpp/iterator/next + + (T... args) + + std::is_arithmetic + std::negate + std::try_to_lock_t + std::wfilebuf + std::is_compound + std::iostream + std::is_object + + T + isfinite + cpp/numeric/math/isfinite + + (T... args) + + + T + boolalpha + cpp/io/manip/boolalpha + + (T... args) + + + T + fetestexcept + cpp/numeric/fenv/fetestexcept + + (T... args) + + + T + mbrlen + cpp/string/multibyte/mbrlen + + (T... args) + + std::recursive_mutex + std::is_copy_constructible + + T + iswgraph + cpp/string/wide/iswgraph + + (T... args) + + std::codecvt_utf8_utf16 + std::not_equal_to + std::is_destructible + std::int_fast32_t + + T + time + cpp/chrono/c/time + + (T... args) + + + T + atomic_compare_exchange_strong + cpp/atomic/atomic_compare_exchange + + (T... args) + + std::rank + + T + wcschr + cpp/string/wide/wcschr + + (T... args) + + + T + uppercase + cpp/io/manip/uppercase + + (T... args) + + std::milli + std::deci + + T + lower_bound + cpp/algorithm/lower_bound + + (T... args) + + std::add_lvalue_reference + std::is_bind_expression + std::ios_base + + T + copy_if + cpp/algorithm/copy + + (T... args) + + std::ratio_less + std::int64_t + std::nullptr_t + + T + isnan + cpp/numeric/math/isnan + + (T... args) + + + T + has_facet + cpp/locale/has_facet + + (T... args) + + + T + kill_dependency + cpp/atomic/kill_dependency + + (T... args) + + + T + uninitialized_copy_n + cpp/memory/uninitialized_copy_n + + (T... args) + + std::stack + + T + feholdexcept + cpp/numeric/fenv/feholdexcept + + (T... args) + + + T + div + cpp/numeric/math/div + + (T... args) + + + T + at_quick_exit + cpp/utility/program/at_quick_exit + + (T... args) + + std::uint_fast64_t + std::is_reference + std::ratio + std::shared_future + std::u16streampos + + T + wcspbrk + cpp/string/wide/wcspbrk + + (T... args) + + + T + search + cpp/algorithm/search + + (T... args) + + std::wistream + std::aligned_storage + + T + find_first_of + cpp/algorithm/find_first_of + + (T... args) + + + T + iota + cpp/algorithm/iota + + (T... args) + + std::wstreambuf + + T + declare_reachable + cpp/memory/gc/declare_reachable + + (T... args) + + + T + atomic_compare_exchange_weak + cpp/atomic/atomic_compare_exchange + + (T... args) + + std::binary_function + + T + strtod + cpp/string/byte/strtof + + (T... args) + + + T + accumulate + cpp/algorithm/accumulate + + (T... args) + + + T + wcsrchr + cpp/string/wide/wcsrchr + + (T... args) + + std::out_of_range + + T + min_element + cpp/algorithm/min_element + + (T... args) + + std::independent_bits_engine + + T + clearerr + cpp/io/c/clearerr + + (T... args) + + + T + random_shuffle + cpp/algorithm/random_shuffle + + (T... args) + + std::stringstream + std::tera + + T + iswalpha + cpp/string/wide/iswalpha + + (T... args) + + std::recursive_timed_mutex + std::nano + + T + atomic_fetch_and + cpp/atomic/atomic_fetch_sub + + (T... args) + + + T + wmemchr + cpp/string/wide/wmemchr + + (T... args) + + std::unordered_multimap + std::normal_distribution + + T + bsearch + cpp/algorithm/bsearch + + (T... args) + + + T + ilogb + cpp/numeric/math/ilogb + + (T... args) + + std::minstd_rand + std::is_signed + + T + unique_copy + cpp/algorithm/unique_copy + + (T... args) + + + T + _Exit + cpp/utility/program/_Exit + + (T... args) + + + T + move + cpp/utility/move + + (T... args) + + + T + find_end + cpp/algorithm/find_end + + (T... args) + + std::is_move_constructible + std::unique_ptr + + T + fesetexceptflag + cpp/numeric/fenv/feexceptflag + + (T... args) + + std::is_nothrow_copy_constructible + std::forward_list + std::errc + std::lconv + + T + nth_element + cpp/algorithm/nth_element + + (T... args) + + + T + gets + cpp/io/c/gets + + (T... args) + + + T + lexicographical_compare + cpp/algorithm/lexicographical_compare + + (T... args) + + + T + nearbyint + cpp/numeric/math/nearbyint + + (T... args) + + std::strstreambuf + std::locale + std::equal_to + + T + memcpy + cpp/string/byte/memcpy + + (T... args) + + + T + fwrite + cpp/io/c/fwrite + + (T... args) + + std::divides + std::collate_byname + + T + unitbuf + cpp/io/manip/unitbuf + + (T... args) + + + T + iswlower + cpp/string/wide/iswlower + + (T... args) + + + T + mblen + cpp/string/multibyte/mblen + + (T... args) + + + T + swscanf + cpp/io/c/fwscanf + + (T... args) + + + T + wcstoimax + cpp/string/wide/wcstoimax + + (T... args) + + std::domain_error + + T + fprintf + cpp/io/c/fprintf + + (T... args) + + + T + find_if + cpp/algorithm/find + + (T... args) + + std::is_empty + + T + strtoimax + cpp/string/byte/strtoimax + + (T... args) + + + T + isalnum + cpp/string/byte/isalnum + + (T... args) + + + T + atomic_fetch_add_explicit + cpp/atomic/atomic_fetch_add + + (T... args) + + std::is_nothrow_default_constructible + std::ratio_equal + + T + push_heap + cpp/algorithm/push_heap + + (T... args) + + + T + min + cpp/algorithm/min + + (T... args) + + + T + fwprintf + cpp/io/c/fwprintf + + (T... args) + + std::ostream + std::streamsize + + T + uncaught_exception + cpp/error/uncaught_exception + + (T... args) + + std::shared_lock + + T + strtoll + cpp/string/byte/strtol + + (T... args) + + std::uint8_t + + T + throw_with_nested + cpp/error/throw_with_nested + + (T... args) + + + T + shuffle + cpp/algorithm/random_shuffle + + (T... args) + + + T + isprint + cpp/string/byte/isprint + + (T... args) + + + T + get_new_handler + cpp/memory/new/get_new_handler + + (T... args) + + + T + call_once + cpp/thread/call_once + + (T... args) + + + T + trunc + cpp/numeric/math/trunc + + (T... args) + + + T + wcscspn + cpp/string/wide/wcscspn + + (T... args) + + std::enable_shared_from_this + std::ptrdiff_t + + T + mbrtoc16 + cpp/string/multibyte/mbrtoc16 + + (T... args) + + std::int_fast8_t + std::aligned_union + + T + lround + cpp/numeric/math/round + + (T... args) + + std::future + std::wcmatch + std::overflow_error + std::centi + + T + pow + cpp/numeric/math/pow + + (T... args) + + std::wssub_match + std::is_nothrow_move_assignable + std::pair + + T + tgamma + cpp/numeric/math/tgamma + + (T... args) + + + T + erfc + cpp/numeric/math/erfc + + (T... args) + + + T + llround + cpp/numeric/math/round + + (T... args) + + + T + abs(float) + cpp/numeric/math/fabs + + (T... args) + + + T + asinh + cpp/numeric/math/asinh + + (T... args) + + + T + feof + cpp/io/c/feof + + (T... args) + + std::wsregex_token_iterator + std::weibull_distribution + + T + noskipws + cpp/io/manip/skipws + + (T... args) + + std::less + std::multiplies + + T + find + cpp/algorithm/find + + (T... args) + + + T + atoi + cpp/string/byte/atoi + + (T... args) + + std::is_enum + + T + not1 + cpp/utility/functional/not1 + + (T... args) + + + T + vfscanf + cpp/io/c/vfscanf + + (T... args) + + std::unary_function + + T + stof + cpp/string/basic_string/stof + + (T... args) + + + T + regex_search + cpp/regex/regex_search + + (T... args) + + std::error_code + std::yocto + std::streampos + std::istream_iterator + + T + rotate_copy + cpp/algorithm/rotate_copy + + (T... args) + + + T + set_new_handler + cpp/memory/new/set_new_handler + + (T... args) + + + T + undeclare_no_pointers + cpp/memory/gc/undeclare_no_pointers + + (T... args) + + std::wifstream + + T + async + cpp/thread/async + + (T... args) + + + T + partition_point + cpp/algorithm/partition_point + + (T... args) + + std::moneypunct_byname + + T + vsscanf + cpp/io/c/vfscanf + + (T... args) + + std::terminate_handler + std::ctype_base + std::reference_wrapper + + T + fesetround + cpp/numeric/fenv/feround + + (T... args) + + + T + atomic_is_lock_free + cpp/atomic/atomic_is_lock_free + + (T... args) + + std::ranlux48_base + + T + tanh + cpp/numeric/math/tanh + + (T... args) + + std::bit_not + std::int_fast16_t + + T + ldiv + cpp/numeric/math/div + + (T... args) + + + T + setbase + cpp/io/manip/setbase + + (T... args) + + + T + remove + cpp/algorithm/remove + + (T... args) + + + T + strtol + cpp/string/byte/strtol + + (T... args) + + + T + strpbrk + cpp/string/byte/strpbrk + + (T... args) + + std::error_category + std::regex_traits + + T + signbit + cpp/numeric/math/signbit + + (T... args) + + + T + wcsncat + cpp/string/wide/wcsncat + + (T... args) + + + T + get_money + cpp/io/manip/get_money + + (T... args) + + std::regex_constants + + T + set_difference + cpp/algorithm/set_difference + + (T... args) + + std::negative_binomial_distribution + + T + cref + cpp/utility/functional/ref + + (T... args) + + std::is_union + + T + getline + cpp/string/basic_string/getline + + (T... args) + + std::mt19937 + std::enable_if + + T + to_wstring + cpp/string/basic_string/to_wstring + + (T... args) + + std::chi_squared_distribution + std::add_rvalue_reference + + T + system + cpp/utility/program/system + + (T... args) + + + T + static_pointer_cast + cpp/memory/shared_ptr/pointer_cast + + (T... args) + + std::basic_istream + std::ostream_iterator + + T + wcstoumax + cpp/string/wide/wcstoimax + + (T... args) + + + T + memmove + cpp/string/byte/memmove + + (T... args) + + + T + getwchar + cpp/io/c/getwchar + + (T... args) + + + T + scientific + cpp/io/manip/fixed + + (T... args) + + + T + wcsftime + cpp/chrono/c/wcsftime + + (T... args) + + + T + begin + cpp/iterator/begin + + (T... args) + + + T + ceil + cpp/numeric/math/ceil + + (T... args) + + + T + sinh + cpp/numeric/math/sinh + + (T... args) + + + T + is_permutation + cpp/algorithm/is_permutation + + (T... args) + + std::is_trivially_copy_assignable + + T + generate_n + cpp/algorithm/generate_n + + (T... args) + + + T + acosh + cpp/numeric/math/acosh + + (T... args) + + std::clog + std::is_scalar + + T + advance + cpp/iterator/advance + + (T... args) + + std::uses_allocator + std::piecewise_linear_distribution + std::hash + + T + flush + cpp/io/manip/flush + + (T... args) + + std::shuffle_order_engine + std::chrono + std::greater + std::csub_match + std::uintmax_t + + T + atomic_fetch_xor + cpp/atomic/atomic_fetch_xor + + (T... args) + + std::remove_pointer + std::numeric_limits + + T + ws + cpp/io/manip/ws + + (T... args) + + std::add_volatile + std::once_flag + std::is_literal_type + std::money_base + + T + signal + cpp/utility/program/signal + + (T... args) + + + T + noshowbase + cpp/io/manip/showbase + + (T... args) + + std::peta + std::is_placeholder + + T + generate + cpp/algorithm/generate + + (T... args) + + + T + ldexp + cpp/numeric/math/ldexp + + (T... args) + + std::add_const + std::basic_stringbuf + std::tm + std::is_abstract + std::deque + + T + vsnprintf + cpp/io/c/vfprintf + + (T... args) + + std::allocator + + T + remove_if + cpp/algorithm/remove + + (T... args) + + std::scoped_allocator_adaptor + std::ssub_match + + T + stoull + cpp/string/basic_string/stoul + + (T... args) + + std::messages_byname + + T + fegetexceptflag + cpp/numeric/fenv/feexceptflag + + (T... args) + + + T + find_if_not + cpp/algorithm/find + + (T... args) + + std::promise + + T + merge + cpp/algorithm/merge + + (T... args) + + + T + free + cpp/memory/c/free + + (T... args) + + + T + count_if + cpp/algorithm/count + + (T... args) + + + T + clock + cpp/chrono/c/clock + + (T... args) + + + T + mktime + cpp/chrono/c/mktime + + (T... args) + + std::add_pointer + std::uintptr_t + + T + inserter + cpp/iterator/inserter + + (T... args) + + + T + puts + cpp/io/c/puts + + (T... args) + + std::bit_and + + T + asin + cpp/numeric/math/asin + + (T... args) + + std::uniform_int_distribution + std::type_info + + T + iscntrl + cpp/string/byte/iscntrl + + (T... args) + + + T + difftime + cpp/chrono/c/difftime + + (T... args) + + + T + terminate + cpp/error/terminate + + (T... args) + + + T + memcmp + cpp/string/byte/memcmp + + (T... args) + + std::fisher_f_distribution + + T + uninitialized_fill + cpp/memory/uninitialized_fill + + (T... args) + + std::strstream + + T + hex + cpp/io/manip/hex + + (T... args) + + + T + tie + cpp/utility/tuple/tie + + (T... args) + + + T + back_inserter + cpp/iterator/back_inserter + + (T... args) + + + T + upper_bound + cpp/algorithm/upper_bound + + (T... args) + + std::time_get_byname + std::basic_streambuf + + T + adjacent_find + cpp/algorithm/adjacent_find + + (T... args) + + std::is_nothrow_constructible + + T + use_facet + cpp/locale/use_facet + + (T... args) + + std::queue + std::is_base_of + std::intmax_t + std::ranlux24 + + T + vfwprintf + cpp/io/c/vfwprintf + + (T... args) + + + T + atomic_fetch_add + cpp/atomic/atomic_fetch_add + + (T... args) + + std::remove_cv + + T + fsetpos + cpp/io/c/fsetpos + + (T... args) + + + T + malloc + cpp/memory/c/malloc + + (T... args) + + + T + localtime + cpp/chrono/c/localtime + + (T... args) + + std::is_trivially_destructible + std::wcin + + T + wcscmp + cpp/string/wide/wcscmp + + (T... args) + + + T + c32rtomb + cpp/string/multibyte/c32rtomb + + (T... args) + + + T + isupper + cpp/string/byte/isupper + + (T... args) + + std::atomic + std::basic_stringstream + + T + wcstod + cpp/string/wide/wcstof + + (T... args) + + + T + tolower + cpp/string/byte/tolower + + (T... args) + + std::is_void + + T + sort_heap + cpp/algorithm/sort_heap + + (T... args) + + std::plus + + T + isdigit + cpp/string/byte/isdigit + + (T... args) + + std::bitset + + T + wcslen + cpp/string/wide/wcslen + + (T... args) + + + T + wmemcmp + cpp/string/wide/wmemcmp + + (T... args) + + std::FILE + + T + move_if_noexcept + cpp/utility/move_if_noexcept + + (T... args) + + + T + declval + cpp/utility/declval + + (T... args) + + + T + fpclassify + cpp/numeric/math/fpclassify + + (T... args) + + + T + iswupper + cpp/string/wide/iswupper + + (T... args) + + std::thread + std::future_error + std::time_base + std::alignment_of + std::time_put + std::bit_or + + T + rand + cpp/numeric/random/rand + + (T... args) + + + T + atomic_compare_exchange_weak_explicit + cpp/atomic/atomic_compare_exchange + + (T... args) + + std::pointer_traits + + T + partial_sort + cpp/algorithm/partial_sort + + (T... args) + + std::basic_string + + T + llrint + cpp/numeric/math/rint + + (T... args) + + std::priority_queue + + T + fclose + cpp/io/c/fclose + + (T... args) + + + T + reverse + cpp/algorithm/reverse + + (T... args) + + std::exa + + T + partial_sum + cpp/algorithm/partial_sum + + (T... args) + + std::wostringstream + + T + showbase + cpp/io/manip/showbase + + (T... args) + + std::is_default_constructible + std::cregex_iterator + + T + vswscanf + cpp/io/c/vfwscanf + + (T... args) + + std::wstring + + T + atan + cpp/numeric/math/atan + + (T... args) + + + T + atanh + cpp/numeric/math/atanh + + (T... args) + + std::remove_all_extents + + T + iter_swap + cpp/algorithm/iter_swap + + (T... args) + + + T + scalbln + cpp/numeric/math/scalbn + + (T... args) + + std::istrstream + + T + reverse_copy + cpp/algorithm/reverse_copy + + (T... args) + + std::unary_negate + std::unordered_multiset + std::basic_ostream + std::wsregex_iterator + std::uint_fast16_t + std::is_nothrow_assignable + + T + forward + cpp/utility/forward + + (T... args) + + std::moneypunct + + T + getc + cpp/io/c/fgetc + + (T... args) + + std::type_index + + T + equal_range + cpp/algorithm/equal_range + + (T... args) + + + T + atomic_fetch_sub + cpp/atomic/atomic_fetch_sub + + (T... args) + + + T + is_partitioned + cpp/algorithm/is_partitioned + + (T... args) + + + T + next_permutation + cpp/algorithm/next_permutation + + (T... args) + + + T + isblank + cpp/string/byte/isblank + + (T... args) + + + T + noshowpoint + cpp/io/manip/showpoint + + (T... args) + + + T + atan2 + cpp/numeric/math/atan2 + + (T... args) + + + T + nanf + cpp/numeric/math/nan + + (T... args) + + + T + towctrans + cpp/string/wide/towctrans + + (T... args) + + std::is_standard_layout + std::timed_mutex + + T + right + cpp/io/manip/left + + (T... args) + + + T + fputwc + cpp/io/c/fputwc + + (T... args) + + + T + strtoul + cpp/string/byte/strtoul + + (T... args) + + + T + is_heap + cpp/algorithm/is_heap + + (T... args) + + std::bad_exception + + T + fflush + cpp/io/c/fflush + + (T... args) + + + T + strtoumax + cpp/string/byte/strtoimax + + (T... args) + + + T + nexttoward + cpp/numeric/math/nextafter + + (T... args) + + std::int_fast64_t + std::function + + T + nounitbuf + cpp/io/manip/unitbuf + + (T... args) + + std::bad_cast + std::error_condition + std::filebuf + std::int_least16_t + + T + ispunct + cpp/string/byte/ispunct + + (T... args) + + std::istreambuf_iterator + std::u16string + + T + noboolalpha + cpp/io/manip/boolalpha + + (T... args) + + + T + make_pair + cpp/utility/pair/make_pair + + (T... args) + + std::is_error_condition_enum + std::is_nothrow_destructible + std::wiostream + + T + iswctype + cpp/string/wide/iswctype + + (T... args) + + std::allocator_arg_t + + T + srand + cpp/numeric/random/srand + + (T... args) + + std::rel_ops + std::uint_least32_t + std::collate + + T + replace_copy + cpp/algorithm/replace_copy + + (T... args) + + + T + future_category + cpp/thread/future/future_category + + (T... args) + + std::remove_const + + T + resetiosflags + cpp/io/manip/resetiosflags + + (T... args) + + + T + vprintf + cpp/io/c/vfprintf + + (T... args) + + std::u32string + std::uint_fast32_t + + T + gmtime + cpp/chrono/c/gmtime + + (T... args) + + std::is_lvalue_reference + + T + align + cpp/memory/align + + (T... args) + + + T + tuple_cat + cpp/utility/tuple/tuple_cat + + (T... args) + + + T + ends + cpp/io/manip/ends + + (T... args) + + + T + set_terminate + cpp/error/set_terminate + + (T... args) + + + T + lrint + cpp/numeric/math/rint + + (T... args) + + std::complex + std::ofstream + std::insert_iterator + std::bad_array_length + + T + none_of + cpp/algorithm/all_any_none_of + + (T... args) + + std::this_thread + + T + wscanf + cpp/io/c/fwscanf + + (T... args) + + + T + fputc + cpp/io/c/fputc + + (T... args) + + + T + dec + cpp/io/manip/hex + + (T... args) + + + T + strcat + cpp/string/byte/strcat + + (T... args) + + std::is_trivially_copyable + std::basic_istringstream + std::basic_ifstream + std::list + + T + raise + cpp/utility/program/raise + + (T... args) + + std::minus + + T + wcsspn + cpp/string/wide/wcsspn + + (T... args) + + + T + fabs + cpp/numeric/math/fabs + + (T... args) + + + T + wmemcpy + cpp/string/wide/wmemcpy + + (T... args) + + + T + copy_n + cpp/algorithm/copy_n + + (T... args) + + std::map + std::linear_congruential_engine + + T + rethrow_if_nested + cpp/error/rethrow_if_nested + + (T... args) + + + T + setlocale + cpp/locale/setlocale + + (T... args) + + std::codecvt_utf16 + + T + addressof + cpp/memory/addressof + + (T... args) + + + T + calloc + cpp/memory/c/calloc + + (T... args) + + std::cmatch + + T + strerror + cpp/string/byte/strerror + + (T... args) + + std::defer_lock_t + + T + strcpy + cpp/string/byte/strcpy + + (T... args) + + std::exception + + T + wcstoull + cpp/string/wide/wcstoul + + (T... args) + + + T + c16rtomb + cpp/string/multibyte/c16rtomb + + (T... args) + + std::front_insert_iterator + + T + generate_canonical + cpp/numeric/random/generate_canonical + + (T... args) + + + T + vfprintf + cpp/io/c/vfprintf + + (T... args) + + + T + notify_all_at_thread_exit + cpp/thread/notify_all_at_thread_exit + + (T... args) + + + T + rotate + cpp/algorithm/rotate + + (T... args) + + + T + current_exception + cpp/error/current_exception + + (T... args) + + + T + strtok + cpp/string/byte/strtok + + (T... args) + + + T + wcscat + cpp/string/wide/wcscat + + (T... args) + + + T + strncpy + cpp/string/byte/strncpy + + (T... args) + + + T + towlower + cpp/string/wide/towlower + + (T... args) + + + T + floor + cpp/numeric/math/floor + + (T... args) + + std::zetta + + T + left + cpp/io/manip/left + + (T... args) + + + T + ferror + cpp/io/c/ferror + + (T... args) + + std::streambuf + + T + atomic_load_explicit + cpp/atomic/atomic_load + + (T... args) + + std::experimental + std::num_put + + T + swap + cpp/algorithm/swap + + (T... args) + + + T + acos + cpp/numeric/math/acos + + (T... args) + + std::owner_less + + T + wcscoll + cpp/string/wide/wcscoll + + (T... args) + + + T + sqrt + cpp/numeric/math/sqrt + + (T... args) + + std::extent + + T + mbsinit + cpp/string/multibyte/mbsinit + + (T... args) + + std::bad_optional_access + + T + qsort + cpp/algorithm/qsort + + (T... args) + + + T + stoll + cpp/string/basic_string/stol + + (T... args) + + + T + put_money + cpp/io/manip/put_money + + (T... args) + + + T + wcstoul + cpp/string/wide/wcstoul + + (T... args) + + + T + wcstol + cpp/string/wide/wcstol + + (T... args) + + + T + atexit + cpp/utility/program/atexit + + (T... args) + + + T + atomic_fetch_or + cpp/atomic/atomic_fetch_or + + (T... args) + + + T + rewind + cpp/io/c/rewind + + (T... args) + + + T + wcsxfrm + cpp/string/wide/wcsxfrm + + (T... args) + + std::yotta + std::wcregex_token_iterator + + T + round + cpp/numeric/math/round + + (T... args) + + std::uint64_t + std::messages + + T + vwprintf + cpp/io/c/vfwprintf + + (T... args) + + + T + all_of + cpp/algorithm/all_any_none_of + + (T... args) + + std::regex_token_iterator + + T + replace + cpp/algorithm/replace + + (T... args) + + std::move_iterator + + T + remquo + cpp/numeric/math/remquo + + (T... args) + + + T + setbuf + cpp/io/c/setbuf + + (T... args) + + std::messages_base + + T + strncmp + cpp/string/byte/strncmp + + (T... args) + + + T + localeconv + cpp/locale/localeconv + + (T... args) + + + T + wctrans + cpp/string/wide/wctrans + + (T... args) + + std::istringstream + std::giga + + T + any_of + cpp/algorithm/all_any_none_of + + (T... args) + + std::integer_sequence + + T + equal + cpp/algorithm/equal + + (T... args) + + + T + max + cpp/algorithm/max + + (T... args) + + + T + strxfrm + cpp/string/byte/strxfrm + + (T... args) + + std::has_virtual_destructor + std::max_align_t + std::remove_volatile + std::underlying_type + + T + iswxdigit + cpp/string/wide/iswxdigit + + (T... args) + + + T + labs + cpp/numeric/math/abs + + (T... args) + + std::hecto + + T + regex_match + cpp/regex/regex_match + + (T... args) + + std::is_member_object_pointer + std::exception_ptr + + T + fputws + cpp/io/c/fputws + + (T... args) + + + T + wcrtomb + cpp/string/multibyte/wcrtomb + + (T... args) + + + T + setprecision + cpp/io/manip/setprecision + + (T... args) + + + T + setvbuf + cpp/io/c/setvbuf + + (T... args) + + std::nested_exception + std::random_access_iterator_tag + + T + regex_replace + cpp/regex/regex_replace + + (T... args) + + std::ctype + + T + freopen + cpp/io/c/freopen + + (T... args) + + + T + logb + cpp/numeric/math/logb + + (T... args) + + std::time_t + + T + wctob + cpp/string/multibyte/wctob + + (T... args) + + std::knuth_b + + T + atomic_load + cpp/atomic/atomic_load + + (T... args) + + + T + search_n + cpp/algorithm/search_n + + (T... args) + + + T + toupper + cpp/string/byte/toupper + + (T... args) + + std::auto_ptr + + T + move_backward + cpp/algorithm/move_backward + + (T... args) + + + T + is_sorted + cpp/algorithm/is_sorted + + (T... args) + + std::minstd_rand0 + + T + strtoull + cpp/string/byte/strtoul + + (T... args) + + std::sregex_token_iterator + std::logical_not + std::fpos_t + + T + iswblank + cpp/string/wide/iswblank + + (T... args) + + std::istream + std::seed_seq + std::default_delete + std::femto + std::clock_t + std::true_type + + T + get_pointer_safety + cpp/memory/gc/get_pointer_safety + + (T... args) + + std::mbstate_t + + T + get_unexpected + cpp/error/get_unexpected + + (T... args) + + + T + sscanf + cpp/io/c/fscanf + + (T... args) + + std::ostrstream + std::gamma_distribution + std::bad_weak_ptr + std::output_iterator_tag + std::micro + std::is_trivial + + T + fesetenv + cpp/numeric/fenv/feenv + + (T... args) + + + T + atomic_store_explicit + cpp/atomic/atomic_store + + (T... args) + + + T + strtold + cpp/string/byte/strtof + + (T... args) + + + T + fread + cpp/io/c/fread + + (T... args) + + std::packaged_task + std::unordered_set + std::is_volatile + + T + memchr + cpp/string/byte/memchr + + (T... args) + + + T + btowc + cpp/string/multibyte/btowc + + (T... args) + + std::wfstream + + T + replace_if + cpp/algorithm/replace + + (T... args) + + std::multimap + + T + strcoll + cpp/string/byte/strcoll + + (T... args) + + + T + vsprintf + cpp/io/c/vfprintf + + (T... args) + + + T + mismatch + cpp/algorithm/mismatch + + (T... args) + + + T + getchar + cpp/io/c/getchar + + (T... args) + + std::atomic_flag + + T + islower + cpp/string/byte/islower + + (T... args) + + + T + tmpnam + cpp/io/c/tmpnam + + (T... args) + + std::numpunct_byname + + T + nanl + cpp/numeric/math/nan + + (T... args) + + std::binomial_distribution + + T + fopen + cpp/io/c/fopen + + (T... args) + + std::basic_iostream + std::wofstream + std::fpos + std::underflow_error + + T + for_each + cpp/algorithm/for_each + + (T... args) + + + T + fegetround + cpp/numeric/fenv/feround + + (T... args) + + + T + ungetc + cpp/io/c/ungetc + + (T... args) + + std::cauchy_distribution + std::is_trivially_copy_constructible + std::conditional + std::is_pod + + T + internal + cpp/io/manip/left + + (T... args) + + + T + vfwscanf + cpp/io/c/vfwscanf + + (T... args) + + std::int_least8_t + + T + fgetc + cpp/io/c/fgetc + + (T... args) + + std::streamoff + std::is_move_assignable + std::int_least32_t + + T + wcstof + cpp/string/wide/wcstof + + (T... args) + + std::wstringstream + std::subtract_with_carry_engine + std::regex_error + + T + bind + cpp/utility/functional/bind + + (T... args) + + + T + skipws + cpp/io/manip/skipws + + (T... args) + + std::is_constructible + std::piecewise_construct_t + + T + iswprint + cpp/string/wide/iswprint + + (T... args) + + + T + wcstombs + cpp/string/multibyte/wcstombs + + (T... args) + + + T + inplace_merge + cpp/algorithm/inplace_merge + + (T... args) + + + T + copysign + cpp/numeric/math/copysign + + (T... args) + + + T + putwchar + cpp/io/c/putwchar + + (T... args) + + std::mutex + + T + wcsstr + cpp/string/wide/wcsstr + + (T... args) + + + T + fegetenv + cpp/numeric/fenv/feenv + + (T... args) + + + T + longjmp + cpp/utility/program/longjmp + + (T... args) + + + T + iswcntrl + cpp/string/wide/iswcntrl + + (T... args) + + std::system_error + + T + declare_no_pointers + cpp/memory/gc/declare_no_pointers + + (T... args) + + + T + isnormal + cpp/numeric/math/isnormal + + (T... args) + + + T + swap_ranges + cpp/algorithm/swap_ranges + + (T... args) + + std::wistringstream + std::is_floating_point + + T + minmax + cpp/algorithm/minmax + + (T... args) + + + T + defaultfloat + cpp/io/manip/fixed + + (T... args) + + + T + rename + cpp/io/c/rename + + (T... args) + + + T + snprintf + cpp/io/c/fprintf + + (T... args) + + + T + try_lock + cpp/thread/try_lock + + (T... args) + + std::ratio_not_equal + std::ratio_multiply + std::result_of + std::is_fundamental + + T + stoul + cpp/string/basic_string/stoul + + (T... args) + + std::ifstream + std::u32streampos + + T + fgetpos + cpp/io/c/fgetpos + + (T... args) + + std::length_error + + T + partition_copy + cpp/algorithm/partition_copy + + (T... args) + + + T + vscanf + cpp/io/c/vfscanf + + (T... args) + + + T + front_inserter + cpp/iterator/front_inserter + + (T... args) + + std::sub_match + std::common_type + + T + get_terminate + cpp/error/get_terminate + + (T... args) + + + T + cosh + cpp/numeric/math/cosh + + (T... args) + + std::shared_timed_mutex + std::array + std::random_device + std::default_random_engine + std::raw_storage_iterator + std::is_convertible + + T + prev + cpp/iterator/prev + + (T... args) + + std::uint16_t + + T + strchr + cpp/string/byte/strchr + + (T... args) + + std::is_array + + T + strstr + cpp/string/byte/strstr + + (T... args) + + std::mega + + T + printf + cpp/io/c/fprintf + + (T... args) + + std::numpunct + std::money_put + std::new_handler + std::is_member_function_pointer + + T + setfill + cpp/io/manip/setfill + + (T... args) + + + T + inner_product + cpp/algorithm/inner_product + + (T... args) + + + + std::is_function + cpp/types/is_function + + + std::input_iterator_tag + cpp/iterator/iterator_tags + + + std::logical_and + cpp/utility/functional/logical_and + + T + operator() + cpp/utility/functional/logical_and + + (T... args) + + + + std::is_integral + cpp/types/is_integral + + + std::money_get + cpp/locale/money_get + + T + do_get + cpp/locale/money_get/get + + (T... args) + + std::money_get::char_type + std::money_get::pattern + + T + get + cpp/locale/money_get/get + + (T... args) + + + T + ~money_get + cpp/locale/money_get/~money_get + + (T... args) + + std::money_get::string_type + std::money_get::iter_type + + T + money_get + cpp/locale/money_get/money_get + + (T... args) + + + + std::money_get::char_type + cpp/locale/money_get + + + std::money_get::pattern + cpp/locale/money_base + + + std::money_get::string_type + cpp/locale/money_get + + + std::money_get::iter_type + cpp/locale/money_get + + + std::basic_ofstream + cpp/io/basic_ofstream + + T + seekp + cpp/io/basic_ostream/seekp + + (T... args) + + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + basic_ofstream + cpp/io/basic_ofstream/basic_ofstream + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + std::basic_ofstream::event_callback + + T + open + cpp/io/basic_ofstream/open + + (T... args) + + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + tellp + cpp/io/basic_ostream/tellp + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + operator<< + cpp/io/basic_ostream/operator_ltlt + + (T... args) + + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + close + cpp/io/basic_ofstream/close + + (T... args) + + + T + write + cpp/io/basic_ostream/write + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + std::basic_ofstream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + flush + cpp/io/basic_ostream/flush + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + is_open + cpp/io/basic_ofstream/is_open + + (T... args) + + + T + operator= + cpp/io/basic_ofstream/operator= + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + std::basic_ofstream::sentry + + T + put + cpp/io/basic_ostream/put + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::basic_ofstream::event_callback + cpp/io/ios_base/event_callback + + + std::basic_ofstream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::basic_ofstream::sentry + cpp/io/basic_ostream/sentry + + T + ~sentry + cpp/io/basic_ostream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_ostream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_ostream/sentry + + (T... args) + + + + std::ratio_subtract + cpp/numeric/ratio/ratio_subtract + + + std::size_t + cpp/types/size_t + + + std::ctype_byname + cpp/locale/ctype_byname + + T + ~ctype_byname + cpp/locale/ctype_byname + + (T... args) + + + T + ctype_byname + cpp/locale/ctype_byname + + (T... args) + + + T + do_toupper + cpp/locale/ctype/toupper + + (T... args) + + + T + toupper + cpp/locale/ctype/toupper + + (T... args) + + + T + do_scan_is + cpp/locale/ctype/scan_is + + (T... args) + + + T + do_tolower + cpp/locale/ctype/tolower + + (T... args) + + + T + do_narrow + cpp/locale/ctype/narrow + + (T... args) + + + T + widen + cpp/locale/ctype/widen + + (T... args) + + + T + is + cpp/locale/ctype/is + + (T... args) + + + T + scan_is + cpp/locale/ctype/scan_is + + (T... args) + + + T + tolower + cpp/locale/ctype/tolower + + (T... args) + + + T + do_is + cpp/locale/ctype/is + + (T... args) + + + T + narrow + cpp/locale/ctype/narrow + + (T... args) + + std::ctype_byname::mask + + T + do_widen + cpp/locale/ctype/widen + + (T... args) + + + + std::ctype_byname::mask + cpp/locale/ctype_base + + + std::wcout + cpp/io/basic_ostream + + + std::fstream + cpp/io/basic_fstream + + T + seekp + cpp/io/basic_ostream/seekp + + (T... args) + + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + operator>> + cpp/io/basic_istream/operator_gtgt + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + + T + seekg + cpp/io/basic_istream/seekg + + (T... args) + + + T + open + cpp/io/basic_fstream/open + + (T... args) + + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + tellp + cpp/io/basic_ostream/tellp + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + gcount + cpp/io/basic_istream/gcount + + (T... args) + + + T + fstream + cpp/io/basic_fstream/basic_fstream + + (T... args) + + + T + unget + cpp/io/basic_istream/unget + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + read + cpp/io/basic_istream/read + + (T... args) + + + T + getline + cpp/io/basic_istream/getline + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + std::fstream::sentry + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + operator<< + cpp/io/basic_ostream/operator_ltlt + + (T... args) + + std::fstream::event_callback + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + write + cpp/io/basic_ostream/write + + (T... args) + + + T + close + cpp/io/basic_fstream/close + + (T... args) + + + T + sync + cpp/io/basic_istream/sync + + (T... args) + + + T + putback + cpp/io/basic_istream/putback + + (T... args) + + + T + ignore + cpp/io/basic_istream/ignore + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + readsome + cpp/io/basic_istream/readsome + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + std::fstream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + get + cpp/io/basic_istream/get + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + flush + cpp/io/basic_ostream/flush + + (T... args) + + + T + tellg + cpp/io/basic_istream/tellg + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + is_open + cpp/io/basic_fstream/is_open + + (T... args) + + + T + peek + cpp/io/basic_istream/peek + + (T... args) + + + T + operator= + cpp/io/basic_fstream/operator= + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + + T + put + cpp/io/basic_ostream/put + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::fstream::sentry + cpp/io/basic_ostream/sentry + + T + ~sentry + cpp/io/basic_istream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_istream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_istream/sentry + + (T... args) + + + + std::fstream::event_callback + cpp/io/ios_base/event_callback + + + std::fstream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::valarray + cpp/numeric/valarray + + + std::ratio_greater_equal + cpp/numeric/ratio/ratio_greater_equal + + + std::remove_extent + cpp/types/remove_extent + + + std::ratio_greater + cpp/numeric/ratio/ratio_greater + + + std::intptr_t + cpp/types/integer + + + std::regex_iterator + cpp/regex/regex_iterator + + T + operator!= + cpp/regex/regex_iterator/operator_cmp + + (T... args) + + + T + operator= + cpp/regex/regex_iterator/operator= + + (T... args) + + + T + operator== + cpp/regex/regex_iterator/operator_cmp + + (T... args) + + + T + operator-> + cpp/regex/regex_iterator/operator* + + (T... args) + + + T + regex_iterator + cpp/regex/regex_iterator/regex_iterator + + (T... args) + + + T + operator++ + cpp/regex/regex_iterator/operator_arith + + (T... args) + + + T + operator* + cpp/regex/regex_iterator/operator* + + (T... args) + + + T + operator++(int) + cpp/regex/regex_iterator/operator_arith + + (T... args) + + + + std::lock_guard + cpp/thread/lock_guard + + T + ~lock_guard + cpp/thread/lock_guard/~lock_guard + + (T... args) + + + T + lock_guard + cpp/thread/lock_guard/lock_guard + + (T... args) + + + + std::wbuffer_convert + cpp/locale/wbuffer_convert + + T + state + cpp/locale/wbuffer_convert/state + + (T... args) + + + T + wbuffer_convert + cpp/locale/wbuffer_convert/wbuffer_convert + + (T... args) + + + T + rdbuf + cpp/locale/wbuffer_convert/rdbuf + + (T... args) + + + T + ~wbuffer_convert + cpp/locale/wbuffer_convert/~wbuffer_convert + + (T... args) + + + + std::modulus + cpp/utility/functional/modulus + + T + operator() + cpp/utility/functional/modulus + + (T... args) + + + + std::ratio_divide + cpp/numeric/ratio/ratio_divide + + + std::ostreambuf_iterator + cpp/iterator/ostreambuf_iterator + + + std::dynarray + cpp/container/dynarray + + T + rbegin + cpp/container/dynarray/rbegin + + (T... args) + + + T + crend + cpp/container/dynarray/rend + + (T... args) + + + T + begin + cpp/container/dynarray/begin + + (T... args) + + + T + data + cpp/container/dynarray/data + + (T... args) + + + T + at + cpp/container/dynarray/at + + (T... args) + + + T + back + cpp/container/dynarray/back + + (T... args) + + + T + end + cpp/container/dynarray/end + + (T... args) + + + T + fill + cpp/container/dynarray/fill + + (T... args) + + + T + empty + cpp/container/dynarray/empty + + (T... args) + + + T + size + cpp/container/dynarray/size + + (T... args) + + + T + cend + cpp/container/dynarray/end + + (T... args) + + + T + ~dynarray + cpp/container/dynarray/~dynarray + + (T... args) + + + T + max_size + cpp/container/dynarray/max_size + + (T... args) + + + T + rend + cpp/container/dynarray/rend + + (T... args) + + + T + front + cpp/container/dynarray/front + + (T... args) + + + T + dynarray + cpp/container/dynarray/dynarray + + (T... args) + + + T + operator[] + cpp/container/dynarray/operator_at + + (T... args) + + + T + crbegin + cpp/container/dynarray/rbegin + + (T... args) + + + T + cbegin + cpp/container/dynarray/begin + + (T... args) + + + + std::is_nothrow_move_constructible + cpp/types/is_move_constructible + + + std::vector + cpp/container/vector + + T + push_back + cpp/container/vector/push_back + + (T... args) + + + T + crbegin + cpp/container/vector/rbegin + + (T... args) + + + T + erase + cpp/container/vector/erase + + (T... args) + + + T + data + cpp/container/vector/data + + (T... args) + + + T + insert + cpp/container/vector/insert + + (T... args) + + + T + pop_back + cpp/container/vector/pop_back + + (T... args) + + + T + shrink_to_fit + cpp/container/vector/shrink_to_fit + + (T... args) + + + T + back + cpp/container/vector/back + + (T... args) + + + T + end + cpp/container/vector/end + + (T... args) + + + T + resize + cpp/container/vector/resize + + (T... args) + + + T + emplace_back + cpp/container/vector/emplace_back + + (T... args) + + + T + size + cpp/container/vector/size + + (T... args) + + + T + cbegin + cpp/container/vector/begin + + (T... args) + + + T + front + cpp/container/vector/front + + (T... args) + + + T + ~vector + cpp/container/vector/~vector + + (T... args) + + + T + rbegin + cpp/container/vector/rbegin + + (T... args) + + + T + crend + cpp/container/vector/rend + + (T... args) + + + T + assign + cpp/container/vector/assign + + (T... args) + + + T + operator= + cpp/container/vector/operator= + + (T... args) + + + T + vector + cpp/container/vector/vector + + (T... args) + + + T + reserve + cpp/container/vector/reserve + + (T... args) + + + T + capacity + cpp/container/vector/capacity + + (T... args) + + + T + empty + cpp/container/vector/empty + + (T... args) + + + T + cend + cpp/container/vector/end + + (T... args) + + + T + swap + cpp/container/vector/swap + + (T... args) + + + T + max_size + cpp/container/vector/max_size + + (T... args) + + + T + rend + cpp/container/vector/rend + + (T... args) + + + T + get_allocator + cpp/container/vector/get_allocator + + (T... args) + + + T + clear + cpp/container/vector/clear + + (T... args) + + + T + at + cpp/container/vector/at + + (T... args) + + + T + emplace + cpp/container/vector/emplace + + (T... args) + + + T + operator[] + cpp/container/vector/operator_at + + (T... args) + + + T + begin + cpp/container/vector/begin + + (T... args) + + + + std::match_results + cpp/regex/match_results + + T + cbegin + cpp/regex/match_results/begin + + (T... args) + + + T + format + cpp/regex/match_results/format + + (T... args) + + + T + ~match_results + cpp/regex/match_results/~match_results + + (T... args) + + + T + size + cpp/regex/match_results/size + + (T... args) + + + T + swap + cpp/regex/match_results/swap + + (T... args) + + + T + position + cpp/regex/match_results/position + + (T... args) + + + T + prefix + cpp/regex/match_results/prefix + + (T... args) + + + T + str + cpp/regex/match_results/str + + (T... args) + + + T + begin + cpp/regex/match_results/begin + + (T... args) + + + T + empty + cpp/regex/match_results/empty + + (T... args) + + + T + suffix + cpp/regex/match_results/suffix + + (T... args) + + + T + get_allocator + cpp/regex/match_results/get_allocator + + (T... args) + + + T + end + cpp/regex/match_results/end + + (T... args) + + + T + match_results + cpp/regex/match_results/match_results + + (T... args) + + + T + ready + cpp/regex/match_results/ready + + (T... args) + + + T + cend + cpp/regex/match_results/end + + (T... args) + + + T + operator[] + cpp/regex/match_results/operator_at + + (T... args) + + + T + length + cpp/regex/match_results/length + + (T... args) + + + T + max_size + cpp/regex/match_results/max_size + + (T... args) + + + + std::back_insert_iterator + cpp/iterator/back_insert_iterator + + + std::iterator + cpp/iterator/iterator + + + std::int8_t + cpp/types/integer + + + std::student_t_distribution + cpp/numeric/random/student_t_distribution + + T + n + cpp/numeric/random/student_t_distribution/n + + (T... args) + + + T + reset + cpp/numeric/random/student_t_distribution/reset + + (T... args) + + + T + max + cpp/numeric/random/student_t_distribution/max + + (T... args) + + + T + operator() + cpp/numeric/random/student_t_distribution/operator() + + (T... args) + + + T + student_t_distribution + cpp/numeric/random/student_t_distribution/student_t_distribution + + (T... args) + + + T + param + cpp/numeric/random/student_t_distribution/param + + (T... args) + + + T + min + cpp/numeric/random/student_t_distribution/min + + (T... args) + + + + std::mt19937_64 + cpp/numeric/random/mersenne_twister_engine + + T + discard + cpp/numeric/random/mersenne_twister_engine/discard + + (T... args) + + + T + mt19937_64 + cpp/numeric/random/mersenne_twister_engine/mersenne_twister_engine + + (T... args) + + + T + max + cpp/numeric/random/mersenne_twister_engine/max + + (T... args) + + + T + operator() + cpp/numeric/random/mersenne_twister_engine/operator() + + (T... args) + + + T + seed + cpp/numeric/random/mersenne_twister_engine/seed + + (T... args) + + + T + min + cpp/numeric/random/mersenne_twister_engine/min + + (T... args) + + + + std::runtime_error + cpp/error/runtime_error + + T + runtime_error + cpp/error/runtime_error + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::ranlux24_base + cpp/numeric/random/subtract_with_carry_engine + + T + discard + cpp/numeric/random/subtract_with_carry_engine/discard + + (T... args) + + + T + ranlux24_base + cpp/numeric/random/subtract_with_carry_engine/subtract_with_carry_engine + + (T... args) + + + T + max + cpp/numeric/random/subtract_with_carry_engine/max + + (T... args) + + + T + operator() + cpp/numeric/random/subtract_with_carry_engine/operator() + + (T... args) + + + T + seed + cpp/numeric/random/subtract_with_carry_engine/seed + + (T... args) + + + T + min + cpp/numeric/random/subtract_with_carry_engine/min + + (T... args) + + + + std::allocator_traits + cpp/memory/allocator_traits + + T + destroy + cpp/memory/allocator_traits/destroy + + (T... args) + + + T + select_on_container_copy_construction + cpp/memory/allocator_traits/select_on_container_copy_construction + + (T... args) + + + T + max_size + cpp/memory/allocator_traits/max_size + + (T... args) + + + T + allocate + cpp/memory/allocator_traits/allocate + + (T... args) + + + T + deallocate + cpp/memory/allocator_traits/deallocate + + (T... args) + + + T + construct + cpp/memory/allocator_traits/construct + + (T... args) + + + + std::codecvt + cpp/locale/codecvt + std::codecvt::extern_type + + T + out + cpp/locale/codecvt/out + + (T... args) + + + T + do_length + cpp/locale/codecvt/length + + (T... args) + + + T + always_noconv + cpp/locale/codecvt/always_noconv + + (T... args) + + + T + do_encoding + cpp/locale/codecvt/encoding + + (T... args) + + + T + do_in + cpp/locale/codecvt/in + + (T... args) + + + T + unshift + cpp/locale/codecvt/unshift + + (T... args) + + std::codecvt::state_type + + T + max_length + cpp/locale/codecvt/max_length + + (T... args) + + + T + encoding + cpp/locale/codecvt/encoding + + (T... args) + + + T + codecvt + cpp/locale/codecvt/codecvt + + (T... args) + + + T + do_unshift + cpp/locale/codecvt/unshift + + (T... args) + + + T + do_out + cpp/locale/codecvt/out + + (T... args) + + + T + do_max_length + cpp/locale/codecvt/max_length + + (T... args) + + + T + do_always_noconv + cpp/locale/codecvt/always_noconv + + (T... args) + + + T + in + cpp/locale/codecvt/in + + (T... args) + + std::codecvt::intern_type + + T + length + cpp/locale/codecvt/length + + (T... args) + + + T + ~codecvt + cpp/locale/codecvt/~codecvt + + (T... args) + + + + std::codecvt::extern_type + cpp/locale/codecvt + + + std::codecvt::state_type + cpp/locale/codecvt + + + std::codecvt::intern_type + cpp/locale/codecvt + + + std::ratio_less_equal + cpp/numeric/ratio/ratio_less_equal + + + std::condition_variable_any + cpp/thread/condition_variable_any + + T + condition_variable_any + cpp/thread/condition_variable_any/condition_variable_any + + (T... args) + + + T + notify_one + cpp/thread/condition_variable_any/notify_one + + (T... args) + + + T + wait_for + cpp/thread/condition_variable_any/wait_for + + (T... args) + + + T + native_handle + cpp/thread/condition_variable_any/native_handle + + (T... args) + + + T + notify_all + cpp/thread/condition_variable_any/notify_all + + (T... args) + + + T + ~condition_variable_any + cpp/thread/condition_variable_any/~condition_variable_any + + (T... args) + + + T + wait_until + cpp/thread/condition_variable_any/wait_until + + (T... args) + + + T + wait + cpp/thread/condition_variable_any/wait + + (T... args) + + + + std::deca + cpp/numeric/ratio/ratio + + + std::extreme_value_distribution + cpp/numeric/random/extreme_value_distribution + + T + max + cpp/numeric/random/extreme_value_distribution/max + + (T... args) + + + T + b + cpp/numeric/random/extreme_value_distribution/params + + (T... args) + + + T + a + cpp/numeric/random/extreme_value_distribution/params + + (T... args) + + + T + operator() + cpp/numeric/random/extreme_value_distribution/operator() + + (T... args) + + + T + extreme_value_distribution + cpp/numeric/random/extreme_value_distribution/extreme_value_distribution + + (T... args) + + + T + param + cpp/numeric/random/extreme_value_distribution/param + + (T... args) + + + T + min + cpp/numeric/random/extreme_value_distribution/min + + (T... args) + + + T + reset + cpp/numeric/random/extreme_value_distribution/reset + + (T... args) + + + + std::cout + cpp/io/basic_ostream + + + std::decay + cpp/types/decay + + + std::is_trivially_move_assignable + cpp/types/is_move_assignable + + + std::adopt_lock_t + cpp/thread/lock_tag_t + + + std::wcerr + cpp/io/basic_ostream + + + std::lognormal_distribution + cpp/numeric/random/lognormal_distribution + + T + max + cpp/numeric/random/lognormal_distribution/max + + (T... args) + + + T + reset + cpp/numeric/random/lognormal_distribution/reset + + (T... args) + + + T + lognormal_distribution + cpp/numeric/random/lognormal_distribution/lognormal_distribution + + (T... args) + + + T + m + cpp/numeric/random/lognormal_distribution/params + + (T... args) + + + T + operator() + cpp/numeric/random/lognormal_distribution/operator() + + (T... args) + + + T + s + cpp/numeric/random/lognormal_distribution/params + + (T... args) + + + T + param + cpp/numeric/random/lognormal_distribution/param + + (T... args) + + + T + min + cpp/numeric/random/lognormal_distribution/min + + (T... args) + + + + std::wclog + cpp/io/basic_ostream + + + std::char_traits + cpp/string/char_traits + + T + assign + cpp/string/char_traits/assign + + (T... args) + + + T + not_eof + cpp/string/char_traits/not_eof + + (T... args) + + + T + to_int_type + cpp/string/char_traits/to_int_type + + (T... args) + + + T + to_char_type + cpp/string/char_traits/to_char_type + + (T... args) + + + T + eq + cpp/string/char_traits/cmp + + (T... args) + + + T + copy + cpp/string/char_traits/copy + + (T... args) + + + T + length + cpp/string/char_traits/length + + (T... args) + + + T + lt + cpp/string/char_traits/cmp + + (T... args) + + + T + eof + cpp/string/char_traits/eof + + (T... args) + + + T + find + cpp/string/char_traits/find + + (T... args) + + + T + move + cpp/string/char_traits/move + + (T... args) + + + T + compare + cpp/string/char_traits/compare + + (T... args) + + + T + eq_int_type + cpp/string/char_traits/eq_int_type + + (T... args) + + + + std::remove_reference + cpp/types/remove_reference + + + std::num_get + cpp/locale/num_get + + T + do_get + cpp/locale/num_get/get + + (T... args) + + std::num_get::char_type + std::num_get::iter_type + + T + num_get + cpp/locale/num_get/num_get + + (T... args) + + + T + ~num_get + cpp/locale/num_get/~num_get + + (T... args) + + + T + get + cpp/locale/num_get/get + + (T... args) + + + + std::num_get::char_type + cpp/locale/num_get + + + std::num_get::iter_type + cpp/locale/num_get + + + std::is_pointer + cpp/types/is_pointer + + + std::multiset + cpp/container/multiset + + T + begin + cpp/container/multiset/begin + + (T... args) + + + T + erase + cpp/container/multiset/erase + + (T... args) + + + T + insert + cpp/container/multiset/insert + + (T... args) + + + T + swap + cpp/container/multiset/swap + + (T... args) + + + T + end + cpp/container/multiset/end + + (T... args) + + + T + emplace_hint + cpp/container/multiset/emplace_hint + + (T... args) + + + T + key_comp + cpp/container/multiset/key_comp + + (T... args) + + + T + cbegin + cpp/container/multiset/begin + + (T... args) + + + T + count + cpp/container/multiset/count + + (T... args) + + + T + find + cpp/container/multiset/find + + (T... args) + + + T + crbegin + cpp/container/multiset/rbegin + + (T... args) + + + T + multiset + cpp/container/multiset/multiset + + (T... args) + + + T + upper_bound + cpp/container/multiset/upper_bound + + (T... args) + + + T + rbegin + cpp/container/multiset/rbegin + + (T... args) + + + T + crend + cpp/container/multiset/rend + + (T... args) + + + T + size + cpp/container/multiset/size + + (T... args) + + + T + operator= + cpp/container/multiset/operator= + + (T... args) + + + T + ~multiset + cpp/container/multiset/~multiset + + (T... args) + + + T + value_comp + cpp/container/multiset/value_comp + + (T... args) + + + T + empty + cpp/container/multiset/empty + + (T... args) + + + T + lower_bound + cpp/container/multiset/lower_bound + + (T... args) + + + T + get_allocator + cpp/container/multiset/get_allocator + + (T... args) + + + T + max_size + cpp/container/multiset/max_size + + (T... args) + + + T + rend + cpp/container/multiset/rend + + (T... args) + + + T + cend + cpp/container/multiset/end + + (T... args) + + + T + clear + cpp/container/multiset/clear + + (T... args) + + + T + equal_range + cpp/container/multiset/equal_range + + (T... args) + + + T + emplace + cpp/container/multiset/emplace + + (T... args) + + + + std::weak_ptr + cpp/memory/weak_ptr + + T + operator= + cpp/memory/weak_ptr/operator= + + (T... args) + + + T + swap + cpp/memory/weak_ptr/swap + + (T... args) + + + T + weak_ptr + cpp/memory/weak_ptr/weak_ptr + + (T... args) + + + T + owner_before + cpp/memory/weak_ptr/owner_before + + (T... args) + + + T + ~weak_ptr + cpp/memory/weak_ptr/~weak_ptr + + (T... args) + + + T + use_count + cpp/memory/weak_ptr/use_count + + (T... args) + + + T + expired + cpp/memory/weak_ptr/expired + + (T... args) + + + T + lock + cpp/memory/weak_ptr/lock + + (T... args) + + + T + reset + cpp/memory/weak_ptr/reset + + (T... args) + + + + std::bidirectional_iterator_tag + cpp/iterator/iterator_tags + + + std::wstring_convert + cpp/locale/wstring_convert + + T + converted + cpp/locale/wstring_convert/converted + + (T... args) + + + T + to_bytes + cpp/locale/wstring_convert/to_bytes + + (T... args) + + + T + ~wstring_convert + cpp/locale/wstring_convert/~wstring_convert + + (T... args) + + + T + state + cpp/locale/wstring_convert/state + + (T... args) + + + T + wstring_convert + cpp/locale/wstring_convert/wstring_convert + + (T... args) + + + T + from_bytes + cpp/locale/wstring_convert/from_bytes + + (T... args) + + + + std::greater_equal + cpp/utility/functional/greater_equal + + T + operator() + cpp/utility/functional/greater_equal + + (T... args) + + + + std::is_trivially_constructible + cpp/types/is_constructible + + + std::string + cpp/string/basic_string + + T + push_back + cpp/string/basic_string/push_back + + (T... args) + + + T + shrink_to_fit + cpp/string/basic_string/shrink_to_fit + + (T... args) + + + T + rfind + cpp/string/basic_string/rfind + + (T... args) + + + T + begin + cpp/string/basic_string/begin + + (T... args) + + + T + erase + cpp/string/basic_string/erase + + (T... args) + + + T + append + cpp/string/basic_string/append + + (T... args) + + + T + data + cpp/string/basic_string/data + + (T... args) + + + T + insert + cpp/string/basic_string/insert + + (T... args) + + + T + assign + cpp/string/basic_string/assign + + (T... args) + + + T + find_first_not_of + cpp/string/basic_string/find_first_not_of + + (T... args) + + + T + back + cpp/string/basic_string/back + + (T... args) + + + T + end + cpp/string/basic_string/end + + (T... args) + + + T + resize + cpp/string/basic_string/resize + + (T... args) + + + T + copy + cpp/string/basic_string/copy + + (T... args) + + + T + find_last_of + cpp/string/basic_string/find_last_of + + (T... args) + + + T + pop_back + cpp/string/basic_string/pop_back + + (T... args) + + + T + replace + cpp/string/basic_string/replace + + (T... args) + + + T + front + cpp/string/basic_string/front + + (T... args) + + + T + substr + cpp/string/basic_string/substr + + (T... args) + + + T + find + cpp/string/basic_string/find + + (T... args) + + + T + compare + cpp/string/basic_string/compare + + (T... args) + + + T + crbegin + cpp/string/basic_string/rbegin + + (T... args) + + + T + cbegin + cpp/string/basic_string/begin + + (T... args) + + + T + find_first_of + cpp/string/basic_string/find_first_of + + (T... args) + + + T + rbegin + cpp/string/basic_string/rbegin + + (T... args) + + + T + crend + cpp/string/basic_string/rend + + (T... args) + + + T + size + cpp/string/basic_string/size + + (T... args) + + + T + operator= + cpp/string/basic_string/operator= + + (T... args) + + + T + find_last_not_of + cpp/string/basic_string/find_last_not_of + + (T... args) + + + T + reserve + cpp/string/basic_string/reserve + + (T... args) + + + T + capacity + cpp/string/basic_string/capacity + + (T... args) + + + T + c_str + cpp/string/basic_string/c_str + + (T... args) + + + T + empty + cpp/string/basic_string/empty + + (T... args) + + + T + cend + cpp/string/basic_string/end + + (T... args) + + + T + string + cpp/string/basic_string/basic_string + + (T... args) + + + T + max_size + cpp/string/basic_string/max_size + + (T... args) + + + T + rend + cpp/string/basic_string/rend + + (T... args) + + + T + get_allocator + cpp/string/basic_string/get_allocator + + (T... args) + + + T + clear + cpp/string/basic_string/clear + + (T... args) + + + T + at + cpp/string/basic_string/at + + (T... args) + + + T + swap + cpp/string/basic_string/swap + + (T... args) + + + T + operator[] + cpp/string/basic_string/operator_at + + (T... args) + + + T + length + cpp/string/basic_string/size + + (T... args) + + + + std::discrete_distribution + cpp/numeric/random/discrete_distribution + + T + probabilities + cpp/numeric/random/discrete_distribution/probabilities + + (T... args) + + + T + reset + cpp/numeric/random/discrete_distribution/reset + + (T... args) + + + T + operator() + cpp/numeric/random/discrete_distribution/operator() + + (T... args) + + + T + discrete_distribution + cpp/numeric/random/discrete_distribution/discrete_distribution + + (T... args) + + + T + max + cpp/numeric/random/discrete_distribution/max + + (T... args) + + + T + param + cpp/numeric/random/discrete_distribution/param + + (T... args) + + + T + min + cpp/numeric/random/discrete_distribution/min + + (T... args) + + + + std::wostream + cpp/io/basic_ostream + + T + seekp + cpp/io/basic_ostream/seekp + + (T... args) + + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + + T + tellp + cpp/io/basic_ostream/tellp + + (T... args) + + std::wostream::event_callback + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + ~wostream + cpp/io/basic_ostream/~basic_ostream + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + wostream + cpp/io/basic_ostream/basic_ostream + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + operator<< + cpp/io/basic_ostream/operator_ltlt + + (T... args) + + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + write + cpp/io/basic_ostream/write + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + std::wostream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + flush + cpp/io/basic_ostream/flush + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + std::wostream::sentry + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + + T + put + cpp/io/basic_ostream/put + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::wostream::event_callback + cpp/io/ios_base/event_callback + + + std::wostream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::wostream::sentry + cpp/io/basic_ostream/sentry + + T + ~sentry + cpp/io/basic_ostream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_ostream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_ostream/sentry + + (T... args) + + + + std::is_polymorphic + cpp/types/is_polymorphic + + + std::reverse_iterator + cpp/iterator/reverse_iterator + + + std::bad_array_new_length + cpp/memory/new/bad_array_new_length + + T + bad_array_new_length + cpp/memory/new/bad_array_new_length/bad_array_new_length + + (T... args) + + + T + what + cpp/memory/new/bad_alloc + + (T... args) + + + + std::condition_variable + cpp/thread/condition_variable + + T + wait + cpp/thread/condition_variable/wait + + (T... args) + + + T + notify_one + cpp/thread/condition_variable/notify_one + + (T... args) + + + T + wait_for + cpp/thread/condition_variable/wait_for + + (T... args) + + + T + notify_all + cpp/thread/condition_variable/notify_all + + (T... args) + + + T + native_handle + cpp/thread/condition_variable/native_handle + + (T... args) + + + T + wait_until + cpp/thread/condition_variable/wait_until + + (T... args) + + + T + condition_variable + cpp/thread/condition_variable/condition_variable + + (T... args) + + + T + ~condition_variable + cpp/thread/condition_variable/~condition_variable + + (T... args) + + + + std::ranlux48 + cpp/numeric/random/discard_block_engine + + T + discard + cpp/numeric/random/discard_block_engine/discard + + (T... args) + + + T + operator() + cpp/numeric/random/discard_block_engine/operator() + + (T... args) + + + T + ranlux48 + cpp/numeric/random/discard_block_engine/discard_block_engine + + (T... args) + + + T + base + cpp/numeric/random/discard_block_engine/base + + (T... args) + + + T + seed + cpp/numeric/random/discard_block_engine/seed + + (T... args) + + + T + max + cpp/numeric/random/discard_block_engine/max + + (T... args) + + + T + min + cpp/numeric/random/discard_block_engine/min + + (T... args) + + + + std::unexpected_handler + cpp/error/unexpected_handler + + + std::piecewise_constant_distribution + cpp/numeric/random/piecewise_constant_distribution + + T + densities + cpp/numeric/random/piecewise_constant_distribution/params + + (T... args) + + + T + max + cpp/numeric/random/piecewise_constant_distribution/max + + (T... args) + + + T + intervals + cpp/numeric/random/piecewise_constant_distribution/params + + (T... args) + + + T + reset + cpp/numeric/random/piecewise_constant_distribution/reset + + (T... args) + + + T + piecewise_constant_distribution + cpp/numeric/random/piecewise_constant_distribution/piecewise_constant_distribution + + (T... args) + + + T + operator() + cpp/numeric/random/piecewise_constant_distribution/operator() + + (T... args) + + + T + param + cpp/numeric/random/piecewise_constant_distribution/param + + (T... args) + + + T + min + cpp/numeric/random/piecewise_constant_distribution/min + + (T... args) + + + + std::codecvt_base + cpp/locale/codecvt_base + + + std::set + cpp/container/set + + T + begin + cpp/container/set/begin + + (T... args) + + + T + erase + cpp/container/set/erase + + (T... args) + + + T + insert + cpp/container/set/insert + + (T... args) + + + T + ~set + cpp/container/set/~set + + (T... args) + + + T + rbegin + cpp/container/set/rbegin + + (T... args) + + + T + end + cpp/container/set/end + + (T... args) + + + T + emplace_hint + cpp/container/set/emplace_hint + + (T... args) + + + T + key_comp + cpp/container/set/key_comp + + (T... args) + + + T + count + cpp/container/set/count + + (T... args) + + + T + find + cpp/container/set/find + + (T... args) + + + T + crbegin + cpp/container/set/rbegin + + (T... args) + + + T + cbegin + cpp/container/set/begin + + (T... args) + + + T + upper_bound + cpp/container/set/upper_bound + + (T... args) + + + T + swap + cpp/container/set/swap + + (T... args) + + + T + crend + cpp/container/set/rend + + (T... args) + + + T + size + cpp/container/set/size + + (T... args) + + + T + set + cpp/container/set/set + + (T... args) + + + T + operator= + cpp/container/set/operator= + + (T... args) + + + T + value_comp + cpp/container/set/value_comp + + (T... args) + + + T + empty + cpp/container/set/empty + + (T... args) + + + T + lower_bound + cpp/container/set/lower_bound + + (T... args) + + + T + get_allocator + cpp/container/set/get_allocator + + (T... args) + + + T + max_size + cpp/container/set/max_size + + (T... args) + + + T + rend + cpp/container/set/rend + + (T... args) + + + T + cend + cpp/container/set/end + + (T... args) + + + T + clear + cpp/container/set/clear + + (T... args) + + + T + equal_range + cpp/container/set/equal_range + + (T... args) + + + T + emplace + cpp/container/set/emplace + + (T... args) + + + + std::forward_iterator_tag + cpp/iterator/iterator_tags + + + std::codecvt_byname + cpp/locale/codecvt_byname + std::codecvt_byname::extern_type + + T + out + cpp/locale/codecvt/out + + (T... args) + + + T + do_length + cpp/locale/codecvt/length + + (T... args) + + + T + do_unshift + cpp/locale/codecvt/unshift + + (T... args) + + + T + do_encoding + cpp/locale/codecvt/encoding + + (T... args) + + + T + do_in + cpp/locale/codecvt/in + + (T... args) + + + T + unshift + cpp/locale/codecvt/unshift + + (T... args) + + + T + max_length + cpp/locale/codecvt/max_length + + (T... args) + + std::codecvt_byname::state_type + + T + encoding + cpp/locale/codecvt/encoding + + (T... args) + + + T + always_noconv + cpp/locale/codecvt/always_noconv + + (T... args) + + + T + do_out + cpp/locale/codecvt/out + + (T... args) + + + T + codecvt_byname + cpp/locale/codecvt_byname + + (T... args) + + + T + do_max_length + cpp/locale/codecvt/max_length + + (T... args) + + + T + do_always_noconv + cpp/locale/codecvt/always_noconv + + (T... args) + + + T + in + cpp/locale/codecvt/in + + (T... args) + + std::codecvt_byname::intern_type + + T + length + cpp/locale/codecvt/length + + (T... args) + + + T + ~codecvt_byname + cpp/locale/codecvt_byname + + (T... args) + + + + std::codecvt_byname::extern_type + cpp/locale/codecvt + + + std::codecvt_byname::state_type + cpp/locale/codecvt + + + std::codecvt_byname::intern_type + cpp/locale/codecvt + + + std::pointer_safety + cpp/memory/gc/pointer_safety + + + std::uint_least64_t + cpp/types/integer + + + std::placeholders + cpp/utility/functional/placeholders + + + std::nothrow_t + cpp/memory/new/nothrow_t + + + std::is_nothrow_copy_assignable + cpp/types/is_copy_assignable + + + std::is_same + cpp/types/is_same + + + std::unique_lock + cpp/thread/unique_lock + + T + mutex + cpp/thread/unique_lock/mutex + + (T... args) + + + T + swap + cpp/thread/unique_lock/swap + + (T... args) + + + T + owns_lock + cpp/thread/unique_lock/owns_lock + + (T... args) + + + T + try_lock_for + cpp/thread/unique_lock/try_lock_for + + (T... args) + + + T + release + cpp/thread/unique_lock/release + + (T... args) + + + T + lock + cpp/thread/unique_lock/lock + + (T... args) + + + T + operator bool + cpp/thread/unique_lock/operator_bool + + (T... args) + + + T + ~unique_lock + cpp/thread/unique_lock/~unique_lock + + (T... args) + + + T + unlock + cpp/thread/unique_lock/unlock + + (T... args) + + + T + operator= + cpp/thread/unique_lock/operator= + + (T... args) + + + T + try_lock_until + cpp/thread/unique_lock/try_lock_until + + (T... args) + + + T + try_lock + cpp/thread/unique_lock/try_lock + + (T... args) + + + T + unique_lock + cpp/thread/unique_lock/unique_lock + + (T... args) + + + + std::basic_ostringstream + cpp/io/basic_ostringstream + + T + seekp + cpp/io/basic_ostream/seekp + + (T... args) + + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + str + cpp/io/basic_ostringstream/str + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + std::basic_ostringstream::event_callback + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + tellp + cpp/io/basic_ostream/tellp + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + operator<< + cpp/io/basic_ostream/operator_ltlt + + (T... args) + + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + write + cpp/io/basic_ostream/write + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + std::basic_ostringstream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + flush + cpp/io/basic_ostream/flush + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + operator= + cpp/io/basic_ostringstream/operator= + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + basic_ostringstream + cpp/io/basic_ostringstream/basic_ostringstream + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + std::basic_ostringstream::sentry + + T + put + cpp/io/basic_ostream/put + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::basic_ostringstream::event_callback + cpp/io/ios_base/event_callback + + + std::basic_ostringstream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::basic_ostringstream::sentry + cpp/io/basic_ostream/sentry + + T + ~sentry + cpp/io/basic_ostream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_ostream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_ostream/sentry + + (T... args) + + + + std::is_error_code_enum + cpp/error/error_code/is_error_code_enum + + + std::time_put_byname + cpp/locale/time_put_byname + + T + time_put_byname + cpp/locale/time_put_byname + + (T... args) + + std::time_put_byname::char_type + + T + do_put + cpp/locale/time_put/put + + (T... args) + + + T + put + cpp/locale/time_put/put + + (T... args) + + + T + ~time_put_byname + cpp/locale/time_put_byname + + (T... args) + + std::time_put_byname::iter_type + + + std::time_put_byname::char_type + cpp/locale/time_put + + + std::time_put_byname::iter_type + cpp/locale/time_put + + + std::time_get + cpp/locale/time_get + + T + do_date_order + cpp/locale/time_get/date_order + + (T... args) + + + T + do_get + cpp/locale/time_get/get + + (T... args) + + + T + do_get_monthname + cpp/locale/time_get/get_monthname + + (T... args) + + + T + get_weekday + cpp/locale/time_get/get_weekday + + (T... args) + + + T + do_get_time + cpp/locale/time_get/get_time + + (T... args) + + + T + ~time_get + cpp/locale/time_get/~time_get + + (T... args) + + + T + do_get_year + cpp/locale/time_get/get_year + + (T... args) + + std::time_get::iter_type + + T + get_monthname + cpp/locale/time_get/get_monthname + + (T... args) + + + T + get_time + cpp/locale/time_get/get_time + + (T... args) + + + T + time_get + cpp/locale/time_get/time_get + + (T... args) + + + T + do_get_date + cpp/locale/time_get/get_date + + (T... args) + + + T + get_date + cpp/locale/time_get/get_date + + (T... args) + + std::time_get::char_type + + T + date_order + cpp/locale/time_get/date_order + + (T... args) + + + T + get_year + cpp/locale/time_get/get_year + + (T... args) + + + T + get + cpp/locale/time_get/get + + (T... args) + + + T + do_get_weekday + cpp/locale/time_get/get_weekday + + (T... args) + + + + std::time_get::iter_type + cpp/locale/time_get + + + std::time_get::char_type + cpp/locale/time_get + + + std::regex + cpp/regex/basic_regex + + T + operator= + cpp/regex/basic_regex/operator= + + (T... args) + + + T + swap + cpp/regex/basic_regex/swap + + (T... args) + + + T + imbue + cpp/regex/basic_regex/imbue + + (T... args) + + + T + assign + cpp/regex/basic_regex/assign + + (T... args) + + + T + regex + cpp/regex/basic_regex/basic_regex + + (T... args) + + + T + mark_count + cpp/regex/basic_regex/mark_count + + (T... args) + + + T + getloc + cpp/regex/basic_regex/getloc + + (T... args) + + + T + flags + cpp/regex/basic_regex/flags + + (T... args) + + + T + ~regex + cpp/regex/basic_regex/~basic_regex + + (T... args) + + + + std::cin + cpp/io/basic_istream + + + std::unordered_map + cpp/container/unordered_map + + T + max_bucket_count + cpp/container/unordered_map/max_bucket_count + + (T... args) + + + T + cbegin + cpp/container/unordered_map/begin + + (T... args) + + + T + erase + cpp/container/unordered_map/erase + + (T... args) + + + T + insert + cpp/container/unordered_map/insert + + (T... args) + + + T + bucket_count + cpp/container/unordered_map/bucket_count + + (T... args) + + + T + max_load_factor + cpp/container/unordered_map/max_load_factor + + (T... args) + + + T + end + cpp/container/unordered_map/end + + (T... args) + + + T + emplace_hint + cpp/container/unordered_map/emplace_hint + + (T... args) + + + T + end(int) + cpp/container/unordered_map/end2 + + (T... args) + + + T + load_factor + cpp/container/unordered_map/load_factor + + (T... args) + + + T + get_allocator + cpp/container/unordered_map/get_allocator + + (T... args) + + + T + key_eq + cpp/container/unordered_map/key_eq + + (T... args) + + + T + ~unordered_map + cpp/container/unordered_map/~unordered_map + + (T... args) + + + T + hash_function + cpp/container/unordered_map/hash_function + + (T... args) + + + T + find + cpp/container/unordered_map/find + + (T... args) + + + T + at + cpp/container/unordered_map/at + + (T... args) + + + T + cbegin(int) + cpp/container/unordered_map/begin2 + + (T... args) + + + T + swap + cpp/container/unordered_map/swap + + (T... args) + + + T + begin(int) + cpp/container/unordered_map/begin2 + + (T... args) + + + T + unordered_map + cpp/container/unordered_map/unordered_map + + (T... args) + + + T + size + cpp/container/unordered_map/size + + (T... args) + + + T + operator= + cpp/container/unordered_map/operator= + + (T... args) + + + T + cend(int) + cpp/container/unordered_map/end2 + + (T... args) + + + T + reserve + cpp/container/unordered_map/reserve + + (T... args) + + + T + rehash + cpp/container/unordered_map/rehash + + (T... args) + + + T + bucket + cpp/container/unordered_map/bucket + + (T... args) + + + T + empty + cpp/container/unordered_map/empty + + (T... args) + + + T + cend + cpp/container/unordered_map/end + + (T... args) + + + T + max_size + cpp/container/unordered_map/max_size + + (T... args) + + + T + count + cpp/container/unordered_map/count + + (T... args) + + + T + clear + cpp/container/unordered_map/clear + + (T... args) + + + T + equal_range + cpp/container/unordered_map/equal_range + + (T... args) + + + T + emplace + cpp/container/unordered_map/emplace + + (T... args) + + + T + operator[] + cpp/container/unordered_map/operator_at + + (T... args) + + + T + begin + cpp/container/unordered_map/begin + + (T... args) + + + T + bucket_size + cpp/container/unordered_map/bucket_size + + (T... args) + + + + std::initializer_list + cpp/utility/initializer_list + + T + end + cpp/utility/initializer_list/end + + (T... args) + + + T + size + cpp/utility/initializer_list/size + + (T... args) + + + T + initializer_list + cpp/utility/initializer_list/initializer_list + + (T... args) + + + T + begin + cpp/utility/initializer_list/begin + + (T... args) + + + + std::is_const + cpp/types/is_const + + + std::basic_regex + cpp/regex/basic_regex + + T + basic_regex + cpp/regex/basic_regex/basic_regex + + (T... args) + + + T + operator= + cpp/regex/basic_regex/operator= + + (T... args) + + + T + swap + cpp/regex/basic_regex/swap + + (T... args) + + + T + assign + cpp/regex/basic_regex/assign + + (T... args) + + + T + ~basic_regex + cpp/regex/basic_regex/~basic_regex + + (T... args) + + + T + getloc + cpp/regex/basic_regex/getloc + + (T... args) + + + T + mark_count + cpp/regex/basic_regex/mark_count + + (T... args) + + + T + imbue + cpp/regex/basic_regex/imbue + + (T... args) + + + T + flags + cpp/regex/basic_regex/flags + + (T... args) + + + + std::poisson_distribution + cpp/numeric/random/poisson_distribution + + T + poisson_distribution + cpp/numeric/random/poisson_distribution/poisson_distribution + + (T... args) + + + T + mean + cpp/numeric/random/poisson_distribution/mean + + (T... args) + + + T + max + cpp/numeric/random/poisson_distribution/max + + (T... args) + + + T + param + cpp/numeric/random/poisson_distribution/param + + (T... args) + + + T + min + cpp/numeric/random/poisson_distribution/min + + (T... args) + + + T + reset + cpp/numeric/random/poisson_distribution/reset + + (T... args) + + + + std::bad_typeid + cpp/types/bad_typeid + + T + bad_typeid + cpp/types/bad_typeid/bad_typeid + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::less_equal + cpp/utility/functional/less_equal + + T + operator() + cpp/utility/functional/less_equal + + (T... args) + + + + std::sig_atomic_t + cpp/utility/program/sig_atomic_t + + + std::make_unsigned + cpp/types/make_unsigned + + + std::basic_filebuf + cpp/io/basic_filebuf + + T + eback + cpp/io/basic_streambuf/gptr + + (T... args) + + + T + setp + cpp/io/basic_streambuf/setp + + (T... args) + + + T + pbackfail + cpp/io/basic_streambuf/pbackfail + + (T... args) + + + T + seekoff + cpp/io/basic_streambuf/pubseekoff + + (T... args) + + + T + pbase + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + egptr + cpp/io/basic_streambuf/gptr + + (T... args) + + + T + basic_filebuf + cpp/io/basic_filebuf/basic_filebuf + + (T... args) + + + T + underflow + cpp/io/basic_streambuf/underflow + + (T... args) + + + T + setbuf + cpp/io/basic_streambuf/pubsetbuf + + (T... args) + + + T + gbump + cpp/io/basic_streambuf/gbump + + (T... args) + + + T + xsgetn + cpp/io/basic_streambuf/sgetn + + (T... args) + + + T + is_open + cpp/io/basic_filebuf/is_open + + (T... args) + + + T + sputn + cpp/io/basic_streambuf/sputn + + (T... args) + + + T + pptr + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + seekpos + cpp/io/basic_streambuf/pubseekpos + + (T... args) + + + T + pubsync + cpp/io/basic_streambuf/pubsync + + (T... args) + + + T + pubseekoff + cpp/io/basic_streambuf/pubseekoff + + (T... args) + + + T + setg + cpp/io/basic_streambuf/setg + + (T... args) + + + T + pbump + cpp/io/basic_streambuf/pbump + + (T... args) + + + T + pubseekpos + cpp/io/basic_streambuf/pubseekpos + + (T... args) + + + T + ~basic_filebuf + cpp/io/basic_filebuf/~basic_filebuf + + (T... args) + + + T + sputbackc + cpp/io/basic_streambuf/sputbackc + + (T... args) + + + T + in_avail + cpp/io/basic_streambuf/in_avail + + (T... args) + + + T + getloc + cpp/io/basic_streambuf/getloc + + (T... args) + + + T + sungetc + cpp/io/basic_streambuf/sungetc + + (T... args) + + + T + epptr + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + close + cpp/io/basic_filebuf/close + + (T... args) + + + T + sync + cpp/io/basic_streambuf/pubsync + + (T... args) + + + T + xsputn + cpp/io/basic_streambuf/sputn + + (T... args) + + + T + pubimbue + cpp/io/basic_streambuf/pubimbue + + (T... args) + + + T + showmanyc + cpp/io/basic_streambuf/showmanyc + + (T... args) + + + T + open + cpp/io/basic_filebuf/open + + (T... args) + + + T + sgetc + cpp/io/basic_streambuf/sgetc + + (T... args) + + + T + swap + cpp/io/basic_streambuf/swap + + (T... args) + + + T + sputc + cpp/io/basic_streambuf/sputc + + (T... args) + + + T + overflow + cpp/io/basic_streambuf/overflow + + (T... args) + + + T + uflow + cpp/io/basic_streambuf/uflow + + (T... args) + + + T + sgetn + cpp/io/basic_streambuf/sgetn + + (T... args) + + + T + sbumpc + cpp/io/basic_streambuf/sbumpc + + (T... args) + + + T + operator= + cpp/io/basic_filebuf/operator= + + (T... args) + + + T + pubsetbuf + cpp/io/basic_streambuf/pubsetbuf + + (T... args) + + + T + imbue + cpp/io/basic_streambuf/pubimbue + + (T... args) + + + T + snextc + cpp/io/basic_streambuf/snextc + + (T... args) + + + T + gptr + cpp/io/basic_streambuf/gptr + + (T... args) + + + + std::logical_or + cpp/utility/functional/logical_or + + T + operator() + cpp/utility/functional/logical_or + + (T... args) + + + + std::wstringbuf + cpp/io/basic_stringbuf + + T + pptr + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + epptr + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + eback + cpp/io/basic_streambuf/gptr + + (T... args) + + + T + setp + cpp/io/basic_streambuf/setp + + (T... args) + + + T + sputbackc + cpp/io/basic_streambuf/sputbackc + + (T... args) + + + T + sgetc + cpp/io/basic_streambuf/sgetc + + (T... args) + + + T + sungetc + cpp/io/basic_streambuf/sungetc + + (T... args) + + + T + pubseekoff + cpp/io/basic_streambuf/pubseekoff + + (T... args) + + + T + seekoff + cpp/io/basic_streambuf/pubseekoff + + (T... args) + + + T + str + cpp/io/basic_stringbuf/str + + (T... args) + + + T + sync + cpp/io/basic_streambuf/pubsync + + (T... args) + + + T + xsputn + cpp/io/basic_streambuf/sputn + + (T... args) + + + T + pbase + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + pubimbue + cpp/io/basic_streambuf/pubimbue + + (T... args) + + + T + showmanyc + cpp/io/basic_streambuf/showmanyc + + (T... args) + + + T + egptr + cpp/io/basic_streambuf/gptr + + (T... args) + + + T + seekpos + cpp/io/basic_streambuf/pubseekpos + + (T... args) + + + T + underflow + cpp/io/basic_streambuf/underflow + + (T... args) + + + T + setbuf + cpp/io/basic_streambuf/pubsetbuf + + (T... args) + + + T + gbump + cpp/io/basic_streambuf/gbump + + (T... args) + + + T + in_avail + cpp/io/basic_streambuf/in_avail + + (T... args) + + + T + swap + cpp/io/basic_streambuf/swap + + (T... args) + + + T + pbackfail + cpp/io/basic_streambuf/pbackfail + + (T... args) + + + T + sputc + cpp/io/basic_streambuf/sputc + + (T... args) + + + T + xsgetn + cpp/io/basic_streambuf/sgetn + + (T... args) + + + T + uflow + cpp/io/basic_streambuf/uflow + + (T... args) + + + T + gptr + cpp/io/basic_streambuf/gptr + + (T... args) + + + T + sputn + cpp/io/basic_streambuf/sputn + + (T... args) + + + T + sgetn + cpp/io/basic_streambuf/sgetn + + (T... args) + + + T + sbumpc + cpp/io/basic_streambuf/sbumpc + + (T... args) + + + T + overflow + cpp/io/basic_streambuf/overflow + + (T... args) + + + T + operator= + cpp/io/basic_stringbuf/operator= + + (T... args) + + + T + pbump + cpp/io/basic_streambuf/pbump + + (T... args) + + + T + pubsetbuf + cpp/io/basic_streambuf/pubsetbuf + + (T... args) + + + T + pubsync + cpp/io/basic_streambuf/pubsync + + (T... args) + + + T + imbue + cpp/io/basic_streambuf/pubimbue + + (T... args) + + + T + setg + cpp/io/basic_streambuf/setg + + (T... args) + + + T + snextc + cpp/io/basic_streambuf/snextc + + (T... args) + + + T + getloc + cpp/io/basic_streambuf/getloc + + (T... args) + + + T + pubseekpos + cpp/io/basic_streambuf/pubseekpos + + (T... args) + + + T + wstringbuf + cpp/io/basic_stringbuf/basic_stringbuf + + (T... args) + + + + std::kilo + cpp/numeric/ratio/ratio + + + std::bernoulli_distribution + cpp/numeric/random/bernoulli_distribution + + T + bernoulli_distribution + cpp/numeric/random/bernoulli_distribution/bernoulli_distribution + + (T... args) + + + T + p + cpp/numeric/random/bernoulli_distribution/p + + (T... args) + + + T + reset + cpp/numeric/random/bernoulli_distribution/reset + + (T... args) + + + T + max + cpp/numeric/random/bernoulli_distribution/max + + (T... args) + + + T + param + cpp/numeric/random/bernoulli_distribution/param + + (T... args) + + + T + min + cpp/numeric/random/bernoulli_distribution/min + + (T... args) + + + + std::int16_t + cpp/types/integer + + + std::basic_ios + cpp/io/basic_ios + + T + setf + cpp/io/ios_base/setf + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + imbue + cpp/io/ios_base/imbue + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + std::basic_ios::failure + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + basic_ios + cpp/io/basic_ios/basic_ios + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + ~basic_ios + cpp/io/basic_ios/~basic_ios + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + std::basic_ios::event_callback + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::basic_ios::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::basic_ios::event_callback + cpp/io/ios_base/event_callback + + + std::int32_t + cpp/types/integer + + + std::is_rvalue_reference + cpp/types/is_rvalue_reference + + + std::integral_constant + cpp/types/integral_constant + + + std::wsmatch + cpp/regex/match_results + + T + cbegin + cpp/regex/match_results/begin + + (T... args) + + + T + format + cpp/regex/match_results/format + + (T... args) + + + T + wsmatch + cpp/regex/match_results/match_results + + (T... args) + + + T + size + cpp/regex/match_results/size + + (T... args) + + + T + swap + cpp/regex/match_results/swap + + (T... args) + + + T + position + cpp/regex/match_results/position + + (T... args) + + + T + prefix + cpp/regex/match_results/prefix + + (T... args) + + + T + str + cpp/regex/match_results/str + + (T... args) + + + T + ~wsmatch + cpp/regex/match_results/~match_results + + (T... args) + + + T + empty + cpp/regex/match_results/empty + + (T... args) + + + T + suffix + cpp/regex/match_results/suffix + + (T... args) + + + T + get_allocator + cpp/regex/match_results/get_allocator + + (T... args) + + + T + end + cpp/regex/match_results/end + + (T... args) + + + T + max_size + cpp/regex/match_results/max_size + + (T... args) + + + T + ready + cpp/regex/match_results/ready + + (T... args) + + + T + cend + cpp/regex/match_results/end + + (T... args) + + + T + operator[] + cpp/regex/match_results/operator_at + + (T... args) + + + T + length + cpp/regex/match_results/length + + (T... args) + + + T + begin + cpp/regex/match_results/begin + + (T... args) + + + + std::cerr + cpp/io/basic_ostream + + + std::codecvt_utf8 + cpp/locale/codecvt_utf8 + std::codecvt_utf8::extern_type + + T + out + cpp/locale/codecvt/out + + (T... args) + + + T + do_length + cpp/locale/codecvt/length + + (T... args) + + + T + do_unshift + cpp/locale/codecvt/unshift + + (T... args) + + + T + do_encoding + cpp/locale/codecvt/encoding + + (T... args) + + + T + do_in + cpp/locale/codecvt/in + + (T... args) + + + T + unshift + cpp/locale/codecvt/unshift + + (T... args) + + + T + max_length + cpp/locale/codecvt/max_length + + (T... args) + + std::codecvt_utf8::state_type + + T + encoding + cpp/locale/codecvt/encoding + + (T... args) + + + T + always_noconv + cpp/locale/codecvt/always_noconv + + (T... args) + + + T + do_out + cpp/locale/codecvt/out + + (T... args) + + + T + do_max_length + cpp/locale/codecvt/max_length + + (T... args) + + + T + do_always_noconv + cpp/locale/codecvt/always_noconv + + (T... args) + + + T + in + cpp/locale/codecvt/in + + (T... args) + + std::codecvt_utf8::intern_type + + T + length + cpp/locale/codecvt/length + + (T... args) + + + + std::codecvt_utf8::extern_type + cpp/locale/codecvt + + + std::codecvt_utf8::state_type + cpp/locale/codecvt + + + std::codecvt_utf8::intern_type + cpp/locale/codecvt + + + std::ratio_add + cpp/numeric/ratio/ratio_add + + + std::is_trivially_move_constructible + cpp/types/is_move_constructible + + + std::wcsub_match + cpp/regex/sub_match + + T + operator string_type + cpp/regex/sub_match/str + + (T... args) + + + T + wcsub_match + cpp/regex/sub_match/sub_match + + (T... args) + + + T + str + cpp/regex/sub_match/str + + (T... args) + + + T + length + cpp/regex/sub_match/length + + (T... args) + + + T + compare + cpp/regex/sub_match/compare + + (T... args) + + + + std::is_member_pointer + cpp/types/is_member_pointer + + + std::wstreampos + cpp/io/fpos + + T + state + cpp/io/fpos/state + + (T... args) + + + + std::uint_least16_t + cpp/types/integer + + + std::tuple + cpp/utility/tuple + + T + operator= + cpp/utility/tuple/operator= + + (T... args) + + + T + swap + cpp/utility/tuple/swap + + (T... args) + + + T + tuple + cpp/utility/tuple/tuple + + (T... args) + + + + std::make_signed + cpp/types/make_signed + + + std::logic_error + cpp/error/logic_error + + T + logic_error + cpp/error/logic_error + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::sregex_iterator + cpp/regex/regex_iterator + + T + operator!= + cpp/regex/regex_iterator/operator_cmp + + (T... args) + + + T + operator= + cpp/regex/regex_iterator/operator= + + (T... args) + + + T + operator== + cpp/regex/regex_iterator/operator_cmp + + (T... args) + + + T + operator-> + cpp/regex/regex_iterator/operator* + + (T... args) + + + T + operator++ + cpp/regex/regex_iterator/operator_arith + + (T... args) + + + T + sregex_iterator + cpp/regex/regex_iterator/regex_iterator + + (T... args) + + + T + operator* + cpp/regex/regex_iterator/operator* + + (T... args) + + + T + operator++(int) + cpp/regex/regex_iterator/operator_arith + + (T... args) + + + + std::int_least64_t + cpp/types/integer + + + std::binary_negate + cpp/utility/functional/binary_negate + + T + operator() + cpp/utility/functional/binary_negate + + (T... args) + + + T + binary_negate + cpp/utility/functional/binary_negate + + (T... args) + + + + std::discard_block_engine + cpp/numeric/random/discard_block_engine + + T + discard + cpp/numeric/random/discard_block_engine/discard + + (T... args) + + + T + max + cpp/numeric/random/discard_block_engine/max + + (T... args) + + + T + operator() + cpp/numeric/random/discard_block_engine/operator() + + (T... args) + + + T + base + cpp/numeric/random/discard_block_engine/base + + (T... args) + + + T + seed + cpp/numeric/random/discard_block_engine/seed + + (T... args) + + + T + discard_block_engine + cpp/numeric/random/discard_block_engine/discard_block_engine + + (T... args) + + + T + min + cpp/numeric/random/discard_block_engine/min + + (T... args) + + + + std::is_trivially_assignable + cpp/types/is_assignable + + + std::add_cv + cpp/types/add_cv + + + std::pico + cpp/numeric/ratio/ratio + + + std::iterator_traits + cpp/iterator/iterator_traits + + + std::is_trivially_default_constructible + cpp/types/is_default_constructible + + + std::shared_ptr + cpp/memory/shared_ptr + + T + shared_ptr + cpp/memory/shared_ptr/shared_ptr + + (T... args) + + + T + ~shared_ptr + cpp/memory/shared_ptr/~shared_ptr + + (T... args) + + + T + swap + cpp/memory/shared_ptr/swap + + (T... args) + + + T + owner_before + cpp/memory/shared_ptr/owner_before + + (T... args) + + + T + reset + cpp/memory/shared_ptr/reset + + (T... args) + + + T + operator-> + cpp/memory/shared_ptr/operator* + + (T... args) + + + T + operator= + cpp/memory/shared_ptr/operator= + + (T... args) + + + T + unique + cpp/memory/shared_ptr/unique + + (T... args) + + + T + operator* + cpp/memory/shared_ptr/operator* + + (T... args) + + + T + operator bool + cpp/memory/shared_ptr/operator_bool + + (T... args) + + + T + get + cpp/memory/shared_ptr/get + + (T... args) + + + + std::bad_alloc + cpp/memory/new/bad_alloc + + T + operator= + cpp/memory/new/bad_alloc + + (T... args) + + + T + bad_alloc + cpp/memory/new/bad_alloc + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::ostringstream + cpp/io/basic_ostringstream + + T + seekp + cpp/io/basic_ostream/seekp + + (T... args) + + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + str + cpp/io/basic_ostringstream/str + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + std::ostringstream::event_callback + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + tellp + cpp/io/basic_ostream/tellp + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + ostringstream + cpp/io/basic_ostringstream/basic_ostringstream + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + operator<< + cpp/io/basic_ostream/operator_ltlt + + (T... args) + + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + write + cpp/io/basic_ostream/write + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + std::ostringstream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + flush + cpp/io/basic_ostream/flush + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + operator= + cpp/io/basic_ostringstream/operator= + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + std::ostringstream::sentry + + T + put + cpp/io/basic_ostream/put + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::ostringstream::event_callback + cpp/io/ios_base/event_callback + + + std::ostringstream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::ostringstream::sentry + cpp/io/basic_ostream/sentry + + T + ~sentry + cpp/io/basic_ostream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_ostream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_ostream/sentry + + (T... args) + + + + std::basic_fstream + cpp/io/basic_fstream + + T + seekp + cpp/io/basic_ostream/seekp + + (T... args) + + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + basic_fstream + cpp/io/basic_fstream/basic_fstream + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + operator>> + cpp/io/basic_istream/operator_gtgt + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + + T + seekg + cpp/io/basic_istream/seekg + + (T... args) + + + T + open + cpp/io/basic_fstream/open + + (T... args) + + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + tellp + cpp/io/basic_ostream/tellp + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + gcount + cpp/io/basic_istream/gcount + + (T... args) + + + T + unget + cpp/io/basic_istream/unget + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + read + cpp/io/basic_istream/read + + (T... args) + + + T + getline + cpp/io/basic_istream/getline + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + std::basic_fstream::sentry + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + operator<< + cpp/io/basic_ostream/operator_ltlt + + (T... args) + + std::basic_fstream::event_callback + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + write + cpp/io/basic_ostream/write + + (T... args) + + + T + close + cpp/io/basic_fstream/close + + (T... args) + + + T + sync + cpp/io/basic_istream/sync + + (T... args) + + + T + putback + cpp/io/basic_istream/putback + + (T... args) + + + T + ignore + cpp/io/basic_istream/ignore + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + readsome + cpp/io/basic_istream/readsome + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + std::basic_fstream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + get + cpp/io/basic_istream/get + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + flush + cpp/io/basic_ostream/flush + + (T... args) + + + T + tellg + cpp/io/basic_istream/tellg + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + is_open + cpp/io/basic_fstream/is_open + + (T... args) + + + T + peek + cpp/io/basic_istream/peek + + (T... args) + + + T + operator= + cpp/io/basic_fstream/operator= + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + + T + put + cpp/io/basic_ostream/put + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::basic_fstream::sentry + cpp/io/basic_ostream/sentry + + T + ~sentry + cpp/io/basic_istream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_istream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_istream/sentry + + (T... args) + + + + std::basic_fstream::event_callback + cpp/io/ios_base/event_callback + + + std::basic_fstream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::stringbuf + cpp/io/basic_stringbuf + + T + pptr + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + epptr + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + eback + cpp/io/basic_streambuf/gptr + + (T... args) + + + T + setp + cpp/io/basic_streambuf/setp + + (T... args) + + + T + sputbackc + cpp/io/basic_streambuf/sputbackc + + (T... args) + + + T + sgetc + cpp/io/basic_streambuf/sgetc + + (T... args) + + + T + stringbuf + cpp/io/basic_stringbuf/basic_stringbuf + + (T... args) + + + T + sungetc + cpp/io/basic_streambuf/sungetc + + (T... args) + + + T + pubseekoff + cpp/io/basic_streambuf/pubseekoff + + (T... args) + + + T + seekoff + cpp/io/basic_streambuf/pubseekoff + + (T... args) + + + T + str + cpp/io/basic_stringbuf/str + + (T... args) + + + T + sync + cpp/io/basic_streambuf/pubsync + + (T... args) + + + T + xsputn + cpp/io/basic_streambuf/sputn + + (T... args) + + + T + pbase + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + pubimbue + cpp/io/basic_streambuf/pubimbue + + (T... args) + + + T + showmanyc + cpp/io/basic_streambuf/showmanyc + + (T... args) + + + T + egptr + cpp/io/basic_streambuf/gptr + + (T... args) + + + T + seekpos + cpp/io/basic_streambuf/pubseekpos + + (T... args) + + + T + underflow + cpp/io/basic_streambuf/underflow + + (T... args) + + + T + setbuf + cpp/io/basic_streambuf/pubsetbuf + + (T... args) + + + T + gbump + cpp/io/basic_streambuf/gbump + + (T... args) + + + T + in_avail + cpp/io/basic_streambuf/in_avail + + (T... args) + + + T + swap + cpp/io/basic_streambuf/swap + + (T... args) + + + T + pbackfail + cpp/io/basic_streambuf/pbackfail + + (T... args) + + + T + sputc + cpp/io/basic_streambuf/sputc + + (T... args) + + + T + xsgetn + cpp/io/basic_streambuf/sgetn + + (T... args) + + + T + uflow + cpp/io/basic_streambuf/uflow + + (T... args) + + + T + gptr + cpp/io/basic_streambuf/gptr + + (T... args) + + + T + sputn + cpp/io/basic_streambuf/sputn + + (T... args) + + + T + sgetn + cpp/io/basic_streambuf/sgetn + + (T... args) + + + T + sbumpc + cpp/io/basic_streambuf/sbumpc + + (T... args) + + + T + overflow + cpp/io/basic_streambuf/overflow + + (T... args) + + + T + operator= + cpp/io/basic_stringbuf/operator= + + (T... args) + + + T + pbump + cpp/io/basic_streambuf/pbump + + (T... args) + + + T + pubsetbuf + cpp/io/basic_streambuf/pubsetbuf + + (T... args) + + + T + pubsync + cpp/io/basic_streambuf/pubsync + + (T... args) + + + T + imbue + cpp/io/basic_streambuf/pubimbue + + (T... args) + + + T + setg + cpp/io/basic_streambuf/setg + + (T... args) + + + T + snextc + cpp/io/basic_streambuf/snextc + + (T... args) + + + T + getloc + cpp/io/basic_streambuf/getloc + + (T... args) + + + T + pubseekpos + cpp/io/basic_streambuf/pubseekpos + + (T... args) + + + + std::exponential_distribution + cpp/numeric/random/exponential_distribution + + T + exponential_distribution + cpp/numeric/random/exponential_distribution/exponential_distribution + + (T... args) + + + T + min + cpp/numeric/random/exponential_distribution/min + + (T... args) + + + T + max + cpp/numeric/random/exponential_distribution/max + + (T... args) + + + T + operator() + cpp/numeric/random/exponential_distribution/operator() + + (T... args) + + + T + param + cpp/numeric/random/exponential_distribution/param + + (T... args) + + + T + reset + cpp/numeric/random/exponential_distribution/reset + + (T... args) + + + T + lambda + cpp/numeric/random/exponential_distribution/lambda + + (T... args) + + + + std::uint32_t + cpp/types/integer + + + std::wcregex_iterator + cpp/regex/regex_iterator + + T + operator!= + cpp/regex/regex_iterator/operator_cmp + + (T... args) + + + T + operator= + cpp/regex/regex_iterator/operator= + + (T... args) + + + T + operator== + cpp/regex/regex_iterator/operator_cmp + + (T... args) + + + T + operator-> + cpp/regex/regex_iterator/operator* + + (T... args) + + + T + operator++ + cpp/regex/regex_iterator/operator_arith + + (T... args) + + + T + operator* + cpp/regex/regex_iterator/operator* + + (T... args) + + + T + wcregex_iterator + cpp/regex/regex_iterator/regex_iterator + + (T... args) + + + T + operator++(int) + cpp/regex/regex_iterator/operator_arith + + (T... args) + + + + std::bad_function_call + cpp/utility/functional/bad_function_call + + T + bad_function_call + cpp/utility/functional/bad_function_call + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::false_type + cpp/types/integral_constant + + + std::wregex + cpp/regex/basic_regex + + T + wregex + cpp/regex/basic_regex/basic_regex + + (T... args) + + + T + swap + cpp/regex/basic_regex/swap + + (T... args) + + + T + imbue + cpp/regex/basic_regex/imbue + + (T... args) + + + T + assign + cpp/regex/basic_regex/assign + + (T... args) + + + T + ~wregex + cpp/regex/basic_regex/~basic_regex + + (T... args) + + + T + operator= + cpp/regex/basic_regex/operator= + + (T... args) + + + T + mark_count + cpp/regex/basic_regex/mark_count + + (T... args) + + + T + getloc + cpp/regex/basic_regex/getloc + + (T... args) + + + T + flags + cpp/regex/basic_regex/flags + + (T... args) + + + + std::uint_least8_t + cpp/types/integer + + + std::uniform_real_distribution + cpp/numeric/random/uniform_real_distribution + + T + uniform_real_distribution + cpp/numeric/random/uniform_real_distribution/uniform_real_distribution + + (T... args) + + + T + reset + cpp/numeric/random/uniform_real_distribution/reset + + (T... args) + + + T + a + cpp/numeric/random/uniform_real_distribution/params + + (T... args) + + + T + max + cpp/numeric/random/uniform_real_distribution/max + + (T... args) + + + T + param + cpp/numeric/random/uniform_real_distribution/param + + (T... args) + + + T + min + cpp/numeric/random/uniform_real_distribution/min + + (T... args) + + + T + b + cpp/numeric/random/uniform_real_distribution/params + + (T... args) + + + + std::smatch + cpp/regex/match_results + + T + smatch + cpp/regex/match_results/match_results + + (T... args) + + + T + cbegin + cpp/regex/match_results/begin + + (T... args) + + + T + format + cpp/regex/match_results/format + + (T... args) + + + T + size + cpp/regex/match_results/size + + (T... args) + + + T + swap + cpp/regex/match_results/swap + + (T... args) + + + T + position + cpp/regex/match_results/position + + (T... args) + + + T + ~smatch + cpp/regex/match_results/~match_results + + (T... args) + + + T + prefix + cpp/regex/match_results/prefix + + (T... args) + + + T + str + cpp/regex/match_results/str + + (T... args) + + + T + empty + cpp/regex/match_results/empty + + (T... args) + + + T + suffix + cpp/regex/match_results/suffix + + (T... args) + + + T + get_allocator + cpp/regex/match_results/get_allocator + + (T... args) + + + T + end + cpp/regex/match_results/end + + (T... args) + + + T + max_size + cpp/regex/match_results/max_size + + (T... args) + + + T + ready + cpp/regex/match_results/ready + + (T... args) + + + T + cend + cpp/regex/match_results/end + + (T... args) + + + T + operator[] + cpp/regex/match_results/operator_at + + (T... args) + + + T + length + cpp/regex/match_results/length + + (T... args) + + + T + begin + cpp/regex/match_results/begin + + (T... args) + + + + std::cregex_token_iterator + cpp/regex/regex_token_iterator + + T + operator!= + cpp/regex/regex_token_iterator/operator_cmp + + (T... args) + + + T + operator= + cpp/regex/regex_token_iterator/operator= + + (T... args) + + + T + operator== + cpp/regex/regex_token_iterator/operator_cmp + + (T... args) + + + T + operator-> + cpp/regex/regex_token_iterator/operator* + + (T... args) + + + T + cregex_token_iterator + cpp/regex/regex_token_iterator/regex_token_iterator + + (T... args) + + + T + operator++ + cpp/regex/regex_token_iterator/operator_arith + + (T... args) + + + T + operator* + cpp/regex/regex_token_iterator/operator* + + (T... args) + + + T + operator++(int) + cpp/regex/regex_token_iterator/operator_arith + + (T... args) + + + + std::range_error + cpp/error/range_error + + T + range_error + cpp/error/range_error + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::is_assignable + cpp/types/is_assignable + + + std::is_copy_assignable + cpp/types/is_copy_assignable + + + std::invalid_argument + cpp/error/invalid_argument + + T + invalid_argument + cpp/error/invalid_argument + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::is_unsigned + cpp/types/is_unsigned + + + std::jmp_buf + cpp/utility/program/jmp_buf + + + std::is_class + cpp/types/is_class + + + std::geometric_distribution + cpp/numeric/random/geometric_distribution + + T + p + cpp/numeric/random/geometric_distribution/p + + (T... args) + + + T + reset + cpp/numeric/random/geometric_distribution/reset + + (T... args) + + + T + max + cpp/numeric/random/geometric_distribution/max + + (T... args) + + + T + geometric_distribution + cpp/numeric/random/geometric_distribution/geometric_distribution + + (T... args) + + + T + param + cpp/numeric/random/geometric_distribution/param + + (T... args) + + + T + min + cpp/numeric/random/geometric_distribution/min + + (T... args) + + + + std::uint_fast8_t + cpp/types/integer + + + std::mersenne_twister_engine + cpp/numeric/random/mersenne_twister_engine + + T + discard + cpp/numeric/random/mersenne_twister_engine/discard + + (T... args) + + + T + max + cpp/numeric/random/mersenne_twister_engine/max + + (T... args) + + + T + operator() + cpp/numeric/random/mersenne_twister_engine/operator() + + (T... args) + + + T + mersenne_twister_engine + cpp/numeric/random/mersenne_twister_engine/mersenne_twister_engine + + (T... args) + + + T + seed + cpp/numeric/random/mersenne_twister_engine/seed + + (T... args) + + + T + min + cpp/numeric/random/mersenne_twister_engine/min + + (T... args) + + + + std::is_arithmetic + cpp/types/is_arithmetic + + + std::negate + cpp/utility/functional/negate + + T + operator() + cpp/utility/functional/negate + + (T... args) + + + + std::try_to_lock_t + cpp/thread/lock_tag_t + + + std::wfilebuf + cpp/io/basic_filebuf + + T + eback + cpp/io/basic_streambuf/gptr + + (T... args) + + + T + setp + cpp/io/basic_streambuf/setp + + (T... args) + + + T + pbackfail + cpp/io/basic_streambuf/pbackfail + + (T... args) + + + T + seekoff + cpp/io/basic_streambuf/pubseekoff + + (T... args) + + + T + pbase + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + egptr + cpp/io/basic_streambuf/gptr + + (T... args) + + + T + underflow + cpp/io/basic_streambuf/underflow + + (T... args) + + + T + setbuf + cpp/io/basic_streambuf/pubsetbuf + + (T... args) + + + T + gbump + cpp/io/basic_streambuf/gbump + + (T... args) + + + T + xsgetn + cpp/io/basic_streambuf/sgetn + + (T... args) + + + T + is_open + cpp/io/basic_filebuf/is_open + + (T... args) + + + T + sputn + cpp/io/basic_streambuf/sputn + + (T... args) + + + T + pptr + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + seekpos + cpp/io/basic_streambuf/pubseekpos + + (T... args) + + + T + pubsync + cpp/io/basic_streambuf/pubsync + + (T... args) + + + T + pubseekoff + cpp/io/basic_streambuf/pubseekoff + + (T... args) + + + T + setg + cpp/io/basic_streambuf/setg + + (T... args) + + + T + pbump + cpp/io/basic_streambuf/pbump + + (T... args) + + + T + pubseekpos + cpp/io/basic_streambuf/pubseekpos + + (T... args) + + + T + ~wfilebuf + cpp/io/basic_filebuf/~basic_filebuf + + (T... args) + + + T + sputbackc + cpp/io/basic_streambuf/sputbackc + + (T... args) + + + T + in_avail + cpp/io/basic_streambuf/in_avail + + (T... args) + + + T + getloc + cpp/io/basic_streambuf/getloc + + (T... args) + + + T + sungetc + cpp/io/basic_streambuf/sungetc + + (T... args) + + + T + wfilebuf + cpp/io/basic_filebuf/basic_filebuf + + (T... args) + + + T + epptr + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + close + cpp/io/basic_filebuf/close + + (T... args) + + + T + sync + cpp/io/basic_streambuf/pubsync + + (T... args) + + + T + xsputn + cpp/io/basic_streambuf/sputn + + (T... args) + + + T + pubimbue + cpp/io/basic_streambuf/pubimbue + + (T... args) + + + T + showmanyc + cpp/io/basic_streambuf/showmanyc + + (T... args) + + + T + open + cpp/io/basic_filebuf/open + + (T... args) + + + T + sgetc + cpp/io/basic_streambuf/sgetc + + (T... args) + + + T + swap + cpp/io/basic_streambuf/swap + + (T... args) + + + T + sputc + cpp/io/basic_streambuf/sputc + + (T... args) + + + T + overflow + cpp/io/basic_streambuf/overflow + + (T... args) + + + T + uflow + cpp/io/basic_streambuf/uflow + + (T... args) + + + T + sgetn + cpp/io/basic_streambuf/sgetn + + (T... args) + + + T + sbumpc + cpp/io/basic_streambuf/sbumpc + + (T... args) + + + T + operator= + cpp/io/basic_filebuf/operator= + + (T... args) + + + T + pubsetbuf + cpp/io/basic_streambuf/pubsetbuf + + (T... args) + + + T + imbue + cpp/io/basic_streambuf/pubimbue + + (T... args) + + + T + snextc + cpp/io/basic_streambuf/snextc + + (T... args) + + + T + gptr + cpp/io/basic_streambuf/gptr + + (T... args) + + + + std::is_compound + cpp/types/is_compound + + + std::iostream + cpp/io/basic_iostream + + T + seekp + cpp/io/basic_ostream/seekp + + (T... args) + + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + operator>> + cpp/io/basic_istream/operator_gtgt + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + + T + seekg + cpp/io/basic_istream/seekg + + (T... args) + + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + tellp + cpp/io/basic_ostream/tellp + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + gcount + cpp/io/basic_istream/gcount + + (T... args) + + + T + unget + cpp/io/basic_istream/unget + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + read + cpp/io/basic_istream/read + + (T... args) + + + T + getline + cpp/io/basic_istream/getline + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + ~iostream + cpp/io/basic_iostream/~basic_iostream + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + std::iostream::sentry + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + operator<< + cpp/io/basic_ostream/operator_ltlt + + (T... args) + + std::iostream::event_callback + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + write + cpp/io/basic_ostream/write + + (T... args) + + + T + sync + cpp/io/basic_istream/sync + + (T... args) + + + T + putback + cpp/io/basic_istream/putback + + (T... args) + + + T + ignore + cpp/io/basic_istream/ignore + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + readsome + cpp/io/basic_istream/readsome + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + std::iostream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + get + cpp/io/basic_istream/get + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + flush + cpp/io/basic_ostream/flush + + (T... args) + + + T + tellg + cpp/io/basic_istream/tellg + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + iostream + cpp/io/basic_iostream/basic_iostream + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + peek + cpp/io/basic_istream/peek + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + + T + put + cpp/io/basic_ostream/put + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::iostream::sentry + cpp/io/basic_ostream/sentry + + T + ~sentry + cpp/io/basic_istream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_istream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_istream/sentry + + (T... args) + + + + std::iostream::event_callback + cpp/io/ios_base/event_callback + + + std::iostream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::is_object + cpp/types/is_object + + + std::recursive_mutex + cpp/thread/recursive_mutex + + T + unlock + cpp/thread/recursive_mutex/unlock + + (T... args) + + + T + native_handle + cpp/thread/recursive_mutex/native_handle + + (T... args) + + + T + recursive_mutex + cpp/thread/recursive_mutex/recursive_mutex + + (T... args) + + + T + lock + cpp/thread/recursive_mutex/lock + + (T... args) + + + T + try_lock + cpp/thread/recursive_mutex/try_lock + + (T... args) + + + + std::is_copy_constructible + cpp/types/is_copy_constructible + + + std::codecvt_utf8_utf16 + cpp/locale/codecvt_utf8_utf16 + std::codecvt_utf8_utf16::extern_type + + T + out + cpp/locale/codecvt/out + + (T... args) + + + T + do_length + cpp/locale/codecvt/length + + (T... args) + + + T + do_unshift + cpp/locale/codecvt/unshift + + (T... args) + + + T + do_encoding + cpp/locale/codecvt/encoding + + (T... args) + + + T + do_in + cpp/locale/codecvt/in + + (T... args) + + + T + unshift + cpp/locale/codecvt/unshift + + (T... args) + + + T + max_length + cpp/locale/codecvt/max_length + + (T... args) + + std::codecvt_utf8_utf16::state_type + + T + encoding + cpp/locale/codecvt/encoding + + (T... args) + + + T + always_noconv + cpp/locale/codecvt/always_noconv + + (T... args) + + + T + do_out + cpp/locale/codecvt/out + + (T... args) + + + T + do_max_length + cpp/locale/codecvt/max_length + + (T... args) + + + T + do_always_noconv + cpp/locale/codecvt/always_noconv + + (T... args) + + + T + in + cpp/locale/codecvt/in + + (T... args) + + std::codecvt_utf8_utf16::intern_type + + T + length + cpp/locale/codecvt/length + + (T... args) + + + + std::codecvt_utf8_utf16::extern_type + cpp/locale/codecvt + + + std::codecvt_utf8_utf16::state_type + cpp/locale/codecvt + + + std::codecvt_utf8_utf16::intern_type + cpp/locale/codecvt + + + std::not_equal_to + cpp/utility/functional/not_equal_to + + T + operator() + cpp/utility/functional/not_equal_to + + (T... args) + + + + std::is_destructible + cpp/types/is_destructible + + + std::int_fast32_t + cpp/types/integer + + + std::rank + cpp/types/rank + + + std::milli + cpp/numeric/ratio/ratio + + + std::deci + cpp/numeric/ratio/ratio + + + std::add_lvalue_reference + cpp/types/add_reference + + + std::is_bind_expression + cpp/utility/functional/is_bind_expression + + + std::ios_base + cpp/io/ios_base + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + std::ios_base::event_callback + std::ios_base::failure + + T + setf + cpp/io/ios_base/setf + + (T... args) + + + T + imbue + cpp/io/ios_base/imbue + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + ios_base + cpp/io/ios_base/ios_base + + (T... args) + + + T + ~ios_base + cpp/io/ios_base/~ios_base + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + + std::ios_base::event_callback + cpp/io/ios_base/event_callback + + + std::ios_base::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::ratio_less + cpp/numeric/ratio/ratio_less + + + std::int64_t + cpp/types/integer + + + std::nullptr_t + cpp/types/nullptr_t + + + std::stack + cpp/container/stack + + T + operator= + cpp/container/stack/operator= + + (T... args) + + + T + swap + cpp/container/stack/swap + + (T... args) + + + T + size + cpp/container/stack/size + + (T... args) + + + T + empty + cpp/container/stack/empty + + (T... args) + + + T + pop + cpp/container/stack/pop + + (T... args) + + + T + emplace + cpp/container/stack/emplace + + (T... args) + + + T + ~stack + cpp/container/stack/~stack + + (T... args) + + + T + top + cpp/container/stack/top + + (T... args) + + + T + stack + cpp/container/stack/stack + + (T... args) + + + T + push + cpp/container/stack/push + + (T... args) + + + + std::uint_fast64_t + cpp/types/integer + + + std::is_reference + cpp/types/is_reference + + + std::ratio + cpp/numeric/ratio/ratio + + + std::shared_future + cpp/thread/shared_future + + T + ~shared_future + cpp/thread/shared_future/~shared_future + + (T... args) + + + T + operator= + cpp/thread/shared_future/operator= + + (T... args) + + + T + wait + cpp/thread/shared_future/wait + + (T... args) + + + T + wait_until + cpp/thread/shared_future/wait_until + + (T... args) + + + T + wait_for + cpp/thread/shared_future/wait_for + + (T... args) + + + T + shared_future + cpp/thread/shared_future/shared_future + + (T... args) + + + T + valid + cpp/thread/shared_future/valid + + (T... args) + + + T + get + cpp/thread/shared_future/get + + (T... args) + + + + std::u16streampos + cpp/io/fpos + + T + state + cpp/io/fpos/state + + (T... args) + + + + std::wistream + cpp/io/basic_istream + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + seekg + cpp/io/basic_istream/seekg + + (T... args) + + + T + operator>> + cpp/io/basic_istream/operator_gtgt + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + std::wistream::event_callback + + T + wistream + cpp/io/basic_istream/basic_istream + + (T... args) + + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + getline + cpp/io/basic_istream/getline + + (T... args) + + + T + gcount + cpp/io/basic_istream/gcount + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + read + cpp/io/basic_istream/read + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + unget + cpp/io/basic_istream/unget + + (T... args) + + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + sync + cpp/io/basic_istream/sync + + (T... args) + + + T + putback + cpp/io/basic_istream/putback + + (T... args) + + + T + ~wistream + cpp/io/basic_istream/~basic_istream + + (T... args) + + + T + ignore + cpp/io/basic_istream/ignore + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + std::wistream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + get + cpp/io/basic_istream/get + + (T... args) + + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + readsome + cpp/io/basic_istream/readsome + + (T... args) + + + T + tellg + cpp/io/basic_istream/tellg + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + peek + cpp/io/basic_istream/peek + + (T... args) + + std::wistream::sentry + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::wistream::event_callback + cpp/io/ios_base/event_callback + + + std::wistream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::wistream::sentry + cpp/io/basic_istream/sentry + + T + ~sentry + cpp/io/basic_istream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_istream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_istream/sentry + + (T... args) + + + + std::aligned_storage + cpp/types/aligned_storage + + + std::wstreambuf + cpp/io/basic_streambuf + + T + pptr + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + epptr + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + eback + cpp/io/basic_streambuf/gptr + + (T... args) + + + T + setp + cpp/io/basic_streambuf/setp + + (T... args) + + + T + sputbackc + cpp/io/basic_streambuf/sputbackc + + (T... args) + + + T + getloc + cpp/io/basic_streambuf/getloc + + (T... args) + + + T + seekoff + cpp/io/basic_streambuf/pubseekoff + + (T... args) + + + T + pubseekoff + cpp/io/basic_streambuf/pubseekoff + + (T... args) + + + T + sungetc + cpp/io/basic_streambuf/sungetc + + (T... args) + + + T + sync + cpp/io/basic_streambuf/pubsync + + (T... args) + + + T + xsputn + cpp/io/basic_streambuf/sputn + + (T... args) + + + T + pbase + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + sgetc + cpp/io/basic_streambuf/sgetc + + (T... args) + + + T + pubimbue + cpp/io/basic_streambuf/pubimbue + + (T... args) + + + T + showmanyc + cpp/io/basic_streambuf/showmanyc + + (T... args) + + + T + egptr + cpp/io/basic_streambuf/gptr + + (T... args) + + + T + seekpos + cpp/io/basic_streambuf/pubseekpos + + (T... args) + + + T + underflow + cpp/io/basic_streambuf/underflow + + (T... args) + + + T + setbuf + cpp/io/basic_streambuf/pubsetbuf + + (T... args) + + + T + gbump + cpp/io/basic_streambuf/gbump + + (T... args) + + + T + in_avail + cpp/io/basic_streambuf/in_avail + + (T... args) + + + T + swap + cpp/io/basic_streambuf/swap + + (T... args) + + + T + pbackfail + cpp/io/basic_streambuf/pbackfail + + (T... args) + + + T + wstreambuf + cpp/io/basic_streambuf/basic_streambuf + + (T... args) + + + T + sputc + cpp/io/basic_streambuf/sputc + + (T... args) + + + T + xsgetn + cpp/io/basic_streambuf/sgetn + + (T... args) + + + T + uflow + cpp/io/basic_streambuf/uflow + + (T... args) + + + T + overflow + cpp/io/basic_streambuf/overflow + + (T... args) + + + T + sputn + cpp/io/basic_streambuf/sputn + + (T... args) + + + T + sgetn + cpp/io/basic_streambuf/sgetn + + (T... args) + + + T + sbumpc + cpp/io/basic_streambuf/sbumpc + + (T... args) + + + T + ~wstreambuf + cpp/io/basic_streambuf/~basic_streambuf + + (T... args) + + + T + operator= + cpp/io/basic_streambuf/operator= + + (T... args) + + + T + pbump + cpp/io/basic_streambuf/pbump + + (T... args) + + + T + pubsetbuf + cpp/io/basic_streambuf/pubsetbuf + + (T... args) + + + T + pubsync + cpp/io/basic_streambuf/pubsync + + (T... args) + + + T + imbue + cpp/io/basic_streambuf/pubimbue + + (T... args) + + + T + setg + cpp/io/basic_streambuf/setg + + (T... args) + + + T + snextc + cpp/io/basic_streambuf/snextc + + (T... args) + + + T + gptr + cpp/io/basic_streambuf/gptr + + (T... args) + + + T + pubseekpos + cpp/io/basic_streambuf/pubseekpos + + (T... args) + + + + std::binary_function + cpp/utility/functional/binary_function + + + std::out_of_range + cpp/error/out_of_range + + T + out_of_range + cpp/error/out_of_range + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::independent_bits_engine + cpp/numeric/random/independent_bits_engine + + T + discard + cpp/numeric/random/independent_bits_engine/discard + + (T... args) + + + T + max + cpp/numeric/random/independent_bits_engine/max + + (T... args) + + + T + independent_bits_engine + cpp/numeric/random/independent_bits_engine/independent_bits_engine + + (T... args) + + + T + operator() + cpp/numeric/random/independent_bits_engine/operator() + + (T... args) + + + T + base + cpp/numeric/random/independent_bits_engine/base + + (T... args) + + + T + seed + cpp/numeric/random/independent_bits_engine/seed + + (T... args) + + + T + min + cpp/numeric/random/independent_bits_engine/min + + (T... args) + + + + std::stringstream + cpp/io/basic_stringstream + + T + seekp + cpp/io/basic_ostream/seekp + + (T... args) + + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + str + cpp/io/basic_stringstream/str + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + operator>> + cpp/io/basic_istream/operator_gtgt + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + + T + seekg + cpp/io/basic_istream/seekg + + (T... args) + + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + stringstream + cpp/io/basic_stringstream/basic_stringstream + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + tellp + cpp/io/basic_ostream/tellp + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + gcount + cpp/io/basic_istream/gcount + + (T... args) + + + T + unget + cpp/io/basic_istream/unget + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + read + cpp/io/basic_istream/read + + (T... args) + + + T + getline + cpp/io/basic_istream/getline + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + std::stringstream::sentry + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + operator<< + cpp/io/basic_ostream/operator_ltlt + + (T... args) + + std::stringstream::event_callback + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + write + cpp/io/basic_ostream/write + + (T... args) + + + T + sync + cpp/io/basic_istream/sync + + (T... args) + + + T + putback + cpp/io/basic_istream/putback + + (T... args) + + + T + ignore + cpp/io/basic_istream/ignore + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + readsome + cpp/io/basic_istream/readsome + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + std::stringstream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + get + cpp/io/basic_istream/get + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + flush + cpp/io/basic_ostream/flush + + (T... args) + + + T + tellg + cpp/io/basic_istream/tellg + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + peek + cpp/io/basic_istream/peek + + (T... args) + + + T + operator= + cpp/io/basic_stringstream/operator= + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + + T + put + cpp/io/basic_ostream/put + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::stringstream::sentry + cpp/io/basic_ostream/sentry + + T + ~sentry + cpp/io/basic_istream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_istream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_istream/sentry + + (T... args) + + + + std::stringstream::event_callback + cpp/io/ios_base/event_callback + + + std::stringstream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::tera + cpp/numeric/ratio/ratio + + + std::recursive_timed_mutex + cpp/thread/recursive_timed_mutex + + T + unlock + cpp/thread/recursive_timed_mutex/unlock + + (T... args) + + + T + native_handle + cpp/thread/recursive_timed_mutex/native_handle + + (T... args) + + + T + try_lock_until + cpp/thread/recursive_timed_mutex/try_lock_until + + (T... args) + + + T + try_lock_for + cpp/thread/recursive_timed_mutex/try_lock_for + + (T... args) + + + T + recursive_timed_mutex + cpp/thread/recursive_timed_mutex/recursive_timed_mutex + + (T... args) + + + T + lock + cpp/thread/recursive_timed_mutex/lock + + (T... args) + + + T + try_lock + cpp/thread/recursive_timed_mutex/try_lock + + (T... args) + + + + std::nano + cpp/numeric/ratio/ratio + + + std::unordered_multimap + cpp/container/unordered_multimap + + T + ~unordered_multimap + cpp/container/unordered_multimap/~unordered_multimap + + (T... args) + + + T + max_bucket_count + cpp/container/unordered_multimap/max_bucket_count + + (T... args) + + + T + bucket_count + cpp/container/unordered_multimap/bucket_count + + (T... args) + + + T + cbegin + cpp/container/unordered_multimap/begin + + (T... args) + + + T + erase + cpp/container/unordered_multimap/erase + + (T... args) + + + T + insert + cpp/container/unordered_multimap/insert + + (T... args) + + + T + unordered_multimap + cpp/container/unordered_multimap/unordered_multimap + + (T... args) + + + T + max_load_factor + cpp/container/unordered_multimap/max_load_factor + + (T... args) + + + T + end + cpp/container/unordered_multimap/end + + (T... args) + + + T + emplace_hint + cpp/container/unordered_multimap/emplace_hint + + (T... args) + + + T + end(int) + cpp/container/unordered_multimap/end2 + + (T... args) + + + T + key_eq + cpp/container/unordered_multimap/key_eq + + (T... args) + + + T + hash_function + cpp/container/unordered_multimap/hash_function + + (T... args) + + + T + find + cpp/container/unordered_multimap/find + + (T... args) + + + T + begin + cpp/container/unordered_multimap/begin + + (T... args) + + + T + cbegin(int) + cpp/container/unordered_multimap/begin2 + + (T... args) + + + T + swap + cpp/container/unordered_multimap/swap + + (T... args) + + + T + begin(int) + cpp/container/unordered_multimap/begin2 + + (T... args) + + + T + load_factor + cpp/container/unordered_multimap/load_factor + + (T... args) + + + T + size + cpp/container/unordered_multimap/size + + (T... args) + + + T + operator= + cpp/container/unordered_multimap/operator= + + (T... args) + + + T + cend + cpp/container/unordered_multimap/end + + (T... args) + + + T + reserve + cpp/container/unordered_multimap/reserve + + (T... args) + + + T + rehash + cpp/container/unordered_multimap/rehash + + (T... args) + + + T + bucket + cpp/container/unordered_multimap/bucket + + (T... args) + + + T + empty + cpp/container/unordered_multimap/empty + + (T... args) + + + T + get_allocator + cpp/container/unordered_multimap/get_allocator + + (T... args) + + + T + max_size + cpp/container/unordered_multimap/max_size + + (T... args) + + + T + cend(int) + cpp/container/unordered_multimap/end2 + + (T... args) + + + T + count + cpp/container/unordered_multimap/count + + (T... args) + + + T + clear + cpp/container/unordered_multimap/clear + + (T... args) + + + T + equal_range + cpp/container/unordered_multimap/equal_range + + (T... args) + + + T + emplace + cpp/container/unordered_multimap/emplace + + (T... args) + + + T + bucket_size + cpp/container/unordered_multimap/bucket_size + + (T... args) + + + + std::normal_distribution + cpp/numeric/random/normal_distribution + + T + min + cpp/numeric/random/normal_distribution/min + + (T... args) + + + T + stddev + cpp/numeric/random/normal_distribution/params + + (T... args) + + + T + reset + cpp/numeric/random/normal_distribution/reset + + (T... args) + + + T + mean + cpp/numeric/random/normal_distribution/params + + (T... args) + + + T + max + cpp/numeric/random/normal_distribution/max + + (T... args) + + + T + operator() + cpp/numeric/random/normal_distribution/operator() + + (T... args) + + + T + param + cpp/numeric/random/normal_distribution/param + + (T... args) + + + T + normal_distribution + cpp/numeric/random/normal_distribution/normal_distribution + + (T... args) + + + + std::minstd_rand + cpp/numeric/random/linear_congruential_engine + + T + discard + cpp/numeric/random/linear_congruential_engine/discard + + (T... args) + + + T + minstd_rand + cpp/numeric/random/linear_congruential_engine/linear_congruential_engine + + (T... args) + + + T + max + cpp/numeric/random/linear_congruential_engine/max + + (T... args) + + + T + operator() + cpp/numeric/random/linear_congruential_engine/operator() + + (T... args) + + + T + seed + cpp/numeric/random/linear_congruential_engine/seed + + (T... args) + + + T + min + cpp/numeric/random/linear_congruential_engine/min + + (T... args) + + + + std::is_signed + cpp/types/is_signed + + + std::is_move_constructible + cpp/types/is_move_constructible + + + std::unique_ptr + cpp/memory/unique_ptr + + T + unique_ptr + cpp/memory/unique_ptr/unique_ptr + + (T... args) + + + T + operator= + cpp/memory/unique_ptr/operator= + + (T... args) + + + T + swap + cpp/memory/unique_ptr/swap + + (T... args) + + + T + operator* + cpp/memory/unique_ptr/operator* + + (T... args) + + + T + ~unique_ptr + cpp/memory/unique_ptr/~unique_ptr + + (T... args) + + + T + operator-> + cpp/memory/unique_ptr/operator* + + (T... args) + + + T + release + cpp/memory/unique_ptr/release + + (T... args) + + + T + get_deleter + cpp/memory/unique_ptr/get_deleter + + (T... args) + + + T + operator bool + cpp/memory/unique_ptr/operator_bool + + (T... args) + + + T + get + cpp/memory/unique_ptr/get + + (T... args) + + + T + reset + cpp/memory/unique_ptr/reset + + (T... args) + + + + std::is_nothrow_copy_constructible + cpp/types/is_copy_constructible + + + std::forward_list + cpp/container/forward_list + + T + pop_front + cpp/container/forward_list/pop_front + + (T... args) + + + T + unique + cpp/container/forward_list/unique + + (T... args) + + + T + sort + cpp/container/forward_list/sort + + (T... args) + + + T + cbegin + cpp/container/forward_list/begin + + (T... args) + + + T + splice_after + cpp/container/forward_list/splice_after + + (T... args) + + + T + reverse + cpp/container/forward_list/reverse + + (T... args) + + + T + remove_if + cpp/container/forward_list/remove + + (T... args) + + + T + end + cpp/container/forward_list/end + + (T... args) + + + T + remove + cpp/container/forward_list/remove + + (T... args) + + + T + push_front + cpp/container/forward_list/push_front + + (T... args) + + + T + emplace_after + cpp/container/forward_list/emplace_after + + (T... args) + + + T + get_allocator + cpp/container/forward_list/get_allocator + + (T... args) + + + T + front + cpp/container/forward_list/front + + (T... args) + + + T + begin + cpp/container/forward_list/begin + + (T... args) + + + T + resize + cpp/container/forward_list/resize + + (T... args) + + + T + emplace_front + cpp/container/forward_list/emplace_front + + (T... args) + + + T + swap + cpp/container/forward_list/swap + + (T... args) + + + T + erase_after + cpp/container/forward_list/erase_after + + (T... args) + + + T + assign + cpp/container/forward_list/assign + + (T... args) + + + T + forward_list + cpp/container/forward_list/forward_list + + (T... args) + + + T + ~forward_list + cpp/container/forward_list/~forward_list + + (T... args) + + + T + before_begin + cpp/container/forward_list/before_begin + + (T... args) + + + T + cbefore_begin + cpp/container/forward_list/before_begin + + (T... args) + + + T + merge + cpp/container/forward_list/merge + + (T... args) + + + T + operator= + cpp/container/forward_list/operator= + + (T... args) + + + T + insert_after + cpp/container/forward_list/insert_after + + (T... args) + + + T + empty + cpp/container/forward_list/empty + + (T... args) + + + T + max_size + cpp/container/forward_list/max_size + + (T... args) + + + T + cend + cpp/container/forward_list/end + + (T... args) + + + T + clear + cpp/container/forward_list/clear + + (T... args) + + + + std::errc + cpp/error/errc + + + std::lconv + cpp/locale/lconv + + + std::strstreambuf + cpp/io/strstreambuf + + T + pptr + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + epptr + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + eback + cpp/io/basic_streambuf/gptr + + (T... args) + + + T + setp + cpp/io/basic_streambuf/setp + + (T... args) + + + T + sputbackc + cpp/io/basic_streambuf/sputbackc + + (T... args) + + + T + sgetc + cpp/io/basic_streambuf/sgetc + + (T... args) + + + T + sungetc + cpp/io/basic_streambuf/sungetc + + (T... args) + + + T + pubseekoff + cpp/io/basic_streambuf/pubseekoff + + (T... args) + + + T + seekoff + cpp/io/basic_streambuf/pubseekoff + + (T... args) + + + T + str + cpp/io/strstreambuf/str + + (T... args) + + + T + sync + cpp/io/basic_streambuf/pubsync + + (T... args) + + + T + xsputn + cpp/io/basic_streambuf/sputn + + (T... args) + + + T + pbase + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + pubimbue + cpp/io/basic_streambuf/pubimbue + + (T... args) + + + T + showmanyc + cpp/io/basic_streambuf/showmanyc + + (T... args) + + + T + egptr + cpp/io/basic_streambuf/gptr + + (T... args) + + + T + seekpos + cpp/io/basic_streambuf/pubseekpos + + (T... args) + + + T + underflow + cpp/io/basic_streambuf/underflow + + (T... args) + + + T + setbuf + cpp/io/basic_streambuf/pubsetbuf + + (T... args) + + + T + pcount + cpp/io/strstreambuf/pcount + + (T... args) + + + T + gbump + cpp/io/basic_streambuf/gbump + + (T... args) + + + T + in_avail + cpp/io/basic_streambuf/in_avail + + (T... args) + + + T + swap + cpp/io/basic_streambuf/swap + + (T... args) + + + T + pbackfail + cpp/io/basic_streambuf/pbackfail + + (T... args) + + + T + sputc + cpp/io/basic_streambuf/sputc + + (T... args) + + + T + xsgetn + cpp/io/basic_streambuf/sgetn + + (T... args) + + + T + uflow + cpp/io/basic_streambuf/uflow + + (T... args) + + + T + ~strstreambuf + cpp/io/strstreambuf/~strstreambuf + + (T... args) + + + T + gptr + cpp/io/basic_streambuf/gptr + + (T... args) + + + T + sputn + cpp/io/basic_streambuf/sputn + + (T... args) + + + T + sgetn + cpp/io/basic_streambuf/sgetn + + (T... args) + + + T + sbumpc + cpp/io/basic_streambuf/sbumpc + + (T... args) + + + T + overflow + cpp/io/basic_streambuf/overflow + + (T... args) + + + T + freeze + cpp/io/strstreambuf/freeze + + (T... args) + + + T + pbump + cpp/io/basic_streambuf/pbump + + (T... args) + + + T + pubsetbuf + cpp/io/basic_streambuf/pubsetbuf + + (T... args) + + + T + pubsync + cpp/io/basic_streambuf/pubsync + + (T... args) + + + T + strstreambuf + cpp/io/strstreambuf/strstreambuf + + (T... args) + + + T + imbue + cpp/io/basic_streambuf/pubimbue + + (T... args) + + + T + setg + cpp/io/basic_streambuf/setg + + (T... args) + + + T + snextc + cpp/io/basic_streambuf/snextc + + (T... args) + + + T + getloc + cpp/io/basic_streambuf/getloc + + (T... args) + + + T + pubseekpos + cpp/io/basic_streambuf/pubseekpos + + (T... args) + + + + std::locale + cpp/locale/locale + + T + name + cpp/locale/locale/name + + (T... args) + + + T + combine + cpp/locale/locale/combine + + (T... args) + + + T + operator() + cpp/locale/locale/operator() + + (T... args) + + + T + classic + cpp/locale/locale/classic + + (T... args) + + + T + global + cpp/locale/locale/global + + (T... args) + + + T + operator!= + cpp/locale/locale/operator_cmp + + (T... args) + + + T + operator= + cpp/locale/locale/operator= + + (T... args) + + std::locale::facet + + T + operator== + cpp/locale/locale/operator_cmp + + (T... args) + + + T + locale + cpp/locale/locale/locale + + (T... args) + + std::locale::id + + T + ~locale + cpp/locale/locale/~locale + + (T... args) + + + + std::locale::facet + cpp/locale/locale/facet + + T + facet + cpp/locale/locale/facet/facet + + (T... args) + + + + std::locale::id + cpp/locale/locale/id + + T + id + cpp/locale/locale/id/id + + (T... args) + + + + std::equal_to + cpp/utility/functional/equal_to + + T + operator() + cpp/utility/functional/equal_to + + (T... args) + + + + std::divides + cpp/utility/functional/divides + + T + operator() + cpp/utility/functional/divides + + (T... args) + + + + std::collate_byname + cpp/locale/collate_byname + + T + hash + cpp/locale/collate/hash + + (T... args) + + + T + do_hash + cpp/locale/collate/hash + + (T... args) + + std::collate_byname::char_type + + T + do_transform + cpp/locale/collate/transform + + (T... args) + + + T + transform + cpp/locale/collate/transform + + (T... args) + + + T + do_compare + cpp/locale/collate/compare + + (T... args) + + + T + ~collate_byname + cpp/locale/collate_byname + + (T... args) + + std::collate_byname::string_type + + T + collate_byname + cpp/locale/collate_byname + + (T... args) + + + T + compare + cpp/locale/collate/compare + + (T... args) + + + + std::collate_byname::char_type + cpp/locale/collate + + + std::collate_byname::string_type + cpp/locale/collate + + + std::domain_error + cpp/error/domain_error + + T + domain_error + cpp/error/domain_error + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::is_empty + cpp/types/is_empty + + + std::is_nothrow_default_constructible + cpp/types/is_default_constructible + + + std::ratio_equal + cpp/numeric/ratio/ratio_equal + + + std::ostream + cpp/io/basic_ostream + + T + seekp + cpp/io/basic_ostream/seekp + + (T... args) + + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + std::ostream::event_callback + + T + ostream + cpp/io/basic_ostream/basic_ostream + + (T... args) + + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + tellp + cpp/io/basic_ostream/tellp + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + ~ostream + cpp/io/basic_ostream/~basic_ostream + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + operator<< + cpp/io/basic_ostream/operator_ltlt + + (T... args) + + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + write + cpp/io/basic_ostream/write + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + std::ostream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + flush + cpp/io/basic_ostream/flush + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + std::ostream::sentry + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + + T + put + cpp/io/basic_ostream/put + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::ostream::event_callback + cpp/io/ios_base/event_callback + + + std::ostream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::ostream::sentry + cpp/io/basic_ostream/sentry + + T + ~sentry + cpp/io/basic_ostream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_ostream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_ostream/sentry + + (T... args) + + + + std::streamsize + cpp/io/streamsize + + + std::shared_lock + cpp/thread/shared_lock + + T + mutex + cpp/thread/shared_lock/mutex + + (T... args) + + + T + swap + cpp/thread/shared_lock/swap + + (T... args) + + + T + shared_lock + cpp/thread/shared_lock/shared_lock + + (T... args) + + + T + try_lock_for + cpp/thread/shared_lock/try_lock_for + + (T... args) + + + T + release + cpp/thread/shared_lock/release + + (T... args) + + + T + lock + cpp/thread/shared_lock/lock + + (T... args) + + + T + operator bool + cpp/thread/shared_lock/operator_bool + + (T... args) + + + T + unlock + cpp/thread/shared_lock/unlock + + (T... args) + + + T + operator= + cpp/thread/shared_lock/operator= + + (T... args) + + + T + ~shared_lock + cpp/thread/shared_lock/~shared_lock + + (T... args) + + + T + try_lock_until + cpp/thread/shared_lock/try_lock_until + + (T... args) + + + T + try_lock + cpp/thread/shared_lock/try_lock + + (T... args) + + + T + owns_lock + cpp/thread/shared_lock/owns_lock + + (T... args) + + + + std::uint8_t + cpp/types/integer + + + std::enable_shared_from_this + cpp/memory/enable_shared_from_this + + T + enable_shared_from_this + cpp/memory/enable_shared_from_this/enable_shared_from_this + + (T... args) + + + T + operator= + cpp/memory/enable_shared_from_this/operator= + + (T... args) + + + T + shared_from_this + cpp/memory/enable_shared_from_this/shared_from_this + + (T... args) + + + T + ~enable_shared_from_this + cpp/memory/enable_shared_from_this/~enable_shared_from_this + + (T... args) + + + + std::ptrdiff_t + cpp/types/ptrdiff_t + + + std::int_fast8_t + cpp/types/integer + + + std::aligned_union + cpp/types/aligned_union + + + std::future + cpp/thread/future + + T + operator= + cpp/thread/future/operator= + + (T... args) + + + T + wait + cpp/thread/future/wait + + (T... args) + + + T + wait_until + cpp/thread/future/wait_until + + (T... args) + + + T + wait_for + cpp/thread/future/wait_for + + (T... args) + + + T + ~future + cpp/thread/future/~future + + (T... args) + + + T + share + cpp/thread/future/share + + (T... args) + + + T + future + cpp/thread/future/future + + (T... args) + + + T + valid + cpp/thread/future/valid + + (T... args) + + + T + get + cpp/thread/future/get + + (T... args) + + + + std::wcmatch + cpp/regex/match_results + + T + wcmatch + cpp/regex/match_results/match_results + + (T... args) + + + T + cbegin + cpp/regex/match_results/begin + + (T... args) + + + T + format + cpp/regex/match_results/format + + (T... args) + + + T + size + cpp/regex/match_results/size + + (T... args) + + + T + swap + cpp/regex/match_results/swap + + (T... args) + + + T + position + cpp/regex/match_results/position + + (T... args) + + + T + prefix + cpp/regex/match_results/prefix + + (T... args) + + + T + str + cpp/regex/match_results/str + + (T... args) + + + T + empty + cpp/regex/match_results/empty + + (T... args) + + + T + suffix + cpp/regex/match_results/suffix + + (T... args) + + + T + get_allocator + cpp/regex/match_results/get_allocator + + (T... args) + + + T + end + cpp/regex/match_results/end + + (T... args) + + + T + max_size + cpp/regex/match_results/max_size + + (T... args) + + + T + ~wcmatch + cpp/regex/match_results/~match_results + + (T... args) + + + T + ready + cpp/regex/match_results/ready + + (T... args) + + + T + cend + cpp/regex/match_results/end + + (T... args) + + + T + operator[] + cpp/regex/match_results/operator_at + + (T... args) + + + T + length + cpp/regex/match_results/length + + (T... args) + + + T + begin + cpp/regex/match_results/begin + + (T... args) + + + + std::overflow_error + cpp/error/overflow_error + + T + overflow_error + cpp/error/overflow_error + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::centi + cpp/numeric/ratio/ratio + + + std::wssub_match + cpp/regex/sub_match + + T + operator string_type + cpp/regex/sub_match/str + + (T... args) + + + T + str + cpp/regex/sub_match/str + + (T... args) + + + T + wssub_match + cpp/regex/sub_match/sub_match + + (T... args) + + + T + length + cpp/regex/sub_match/length + + (T... args) + + + T + compare + cpp/regex/sub_match/compare + + (T... args) + + + + std::is_nothrow_move_assignable + cpp/types/is_move_assignable + + + std::pair + cpp/utility/pair + + T + pair + cpp/utility/pair/pair + + (T... args) + + + T + swap + cpp/utility/pair/swap + + (T... args) + + + T + operator= + cpp/utility/pair/operator= + + (T... args) + + + + std::wsregex_token_iterator + cpp/regex/regex_token_iterator + + T + operator!= + cpp/regex/regex_token_iterator/operator_cmp + + (T... args) + + + T + operator= + cpp/regex/regex_token_iterator/operator= + + (T... args) + + + T + wsregex_token_iterator + cpp/regex/regex_token_iterator/regex_token_iterator + + (T... args) + + + T + operator-> + cpp/regex/regex_token_iterator/operator* + + (T... args) + + + T + operator++ + cpp/regex/regex_token_iterator/operator_arith + + (T... args) + + + T + operator== + cpp/regex/regex_token_iterator/operator_cmp + + (T... args) + + + T + operator* + cpp/regex/regex_token_iterator/operator* + + (T... args) + + + T + operator++(int) + cpp/regex/regex_token_iterator/operator_arith + + (T... args) + + + + std::weibull_distribution + cpp/numeric/random/weibull_distribution + + T + reset + cpp/numeric/random/weibull_distribution/reset + + (T... args) + + + T + a + cpp/numeric/random/weibull_distribution/params + + (T... args) + + + T + max + cpp/numeric/random/weibull_distribution/max + + (T... args) + + + T + weibull_distribution + cpp/numeric/random/weibull_distribution/weibull_distribution + + (T... args) + + + T + operator() + cpp/numeric/random/weibull_distribution/operator() + + (T... args) + + + T + param + cpp/numeric/random/weibull_distribution/param + + (T... args) + + + T + min + cpp/numeric/random/weibull_distribution/min + + (T... args) + + + T + b + cpp/numeric/random/weibull_distribution/params + + (T... args) + + + + std::less + cpp/utility/functional/less + + T + operator() + cpp/utility/functional/less + + (T... args) + + + + std::multiplies + cpp/utility/functional/multiplies + + T + operator() + cpp/utility/functional/multiplies + + (T... args) + + + + std::is_enum + cpp/types/is_enum + + + std::unary_function + cpp/utility/functional/unary_function + + + std::error_code + cpp/error/error_code + + T + value + cpp/error/error_code/value + + (T... args) + + + T + operator bool + cpp/error/error_code/operator_bool + + (T... args) + + + T + assign + cpp/error/error_code/assign + + (T... args) + + + T + operator= + cpp/error/error_code/operator= + + (T... args) + + + T + error_code + cpp/error/error_code/error_code + + (T... args) + + + T + clear + cpp/error/error_code/clear + + (T... args) + + + T + default_error_condition + cpp/error/error_code/default_error_condition + + (T... args) + + + T + message + cpp/error/error_code/message + + (T... args) + + + T + category + cpp/error/error_code/category + + (T... args) + + + + std::yocto + cpp/numeric/ratio/ratio + + + std::streampos + cpp/io/fpos + + T + state + cpp/io/fpos/state + + (T... args) + + + + std::istream_iterator + cpp/iterator/istream_iterator + + + std::wifstream + cpp/io/basic_ifstream + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + readsome + cpp/io/basic_istream/readsome + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + + T + open + cpp/io/basic_ifstream/open + + (T... args) + + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + operator= + cpp/io/basic_ifstream/operator= + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + gcount + cpp/io/basic_istream/gcount + + (T... args) + + + T + get + cpp/io/basic_istream/get + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + read + cpp/io/basic_istream/read + + (T... args) + + + T + getline + cpp/io/basic_istream/getline + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + unget + cpp/io/basic_istream/unget + + (T... args) + + std::wifstream::event_callback + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + close + cpp/io/basic_ifstream/close + + (T... args) + + + T + sync + cpp/io/basic_istream/sync + + (T... args) + + + T + putback + cpp/io/basic_istream/putback + + (T... args) + + + T + ignore + cpp/io/basic_istream/ignore + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + seekg + cpp/io/basic_istream/seekg + + (T... args) + + std::wifstream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + tellg + cpp/io/basic_istream/tellg + + (T... args) + + + T + operator>> + cpp/io/basic_istream/operator_gtgt + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + is_open + cpp/io/basic_ifstream/is_open + + (T... args) + + + T + peek + cpp/io/basic_istream/peek + + (T... args) + + + T + wifstream + cpp/io/basic_ifstream/basic_ifstream + + (T... args) + + std::wifstream::sentry + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::wifstream::event_callback + cpp/io/ios_base/event_callback + + + std::wifstream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::wifstream::sentry + cpp/io/basic_istream/sentry + + T + ~sentry + cpp/io/basic_istream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_istream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_istream/sentry + + (T... args) + + + + std::moneypunct_byname + cpp/locale/moneypunct_byname + + T + do_curr_symbol + cpp/locale/moneypunct/curr_symbol + + (T... args) + + + T + do_decimal_point + cpp/locale/moneypunct/decimal_point + + (T... args) + + + T + thousands_sep + cpp/locale/moneypunct/thousands_sep + + (T... args) + + + T + moneypunct_byname + cpp/locale/moneypunct_byname + + (T... args) + + + T + curr_symbol + cpp/locale/moneypunct/curr_symbol + + (T... args) + + + T + do_thousands_sep + cpp/locale/moneypunct/thousands_sep + + (T... args) + + + T + positive_sign + cpp/locale/moneypunct/positive_sign + + (T... args) + + + T + frac_digits + cpp/locale/moneypunct/frac_digits + + (T... args) + + + T + do_negative_sign + cpp/locale/moneypunct/positive_sign + + (T... args) + + + T + pos_format + cpp/locale/moneypunct/pos_format + + (T... args) + + + T + do_pos_format + cpp/locale/moneypunct/pos_format + + (T... args) + + + T + neg_format + cpp/locale/moneypunct/pos_format + + (T... args) + + + T + negative_sign + cpp/locale/moneypunct/positive_sign + + (T... args) + + + T + grouping + cpp/locale/moneypunct/grouping + + (T... args) + + + T + do_frac_digits + cpp/locale/moneypunct/frac_digits + + (T... args) + + + T + decimal_point + cpp/locale/moneypunct/decimal_point + + (T... args) + + + T + do_neg_format + cpp/locale/moneypunct/pos_format + + (T... args) + + std::moneypunct_byname::string_type + std::moneypunct_byname::pattern + + T + do_positive_sign + cpp/locale/moneypunct/positive_sign + + (T... args) + + std::moneypunct_byname::char_type + + T + ~moneypunct_byname + cpp/locale/moneypunct_byname + + (T... args) + + + T + do_grouping + cpp/locale/moneypunct/grouping + + (T... args) + + + + std::moneypunct_byname::string_type + cpp/locale/moneypunct + + + std::moneypunct_byname::pattern + cpp/locale/money_base + + + std::moneypunct_byname::char_type + cpp/locale/moneypunct + + + std::terminate_handler + cpp/error/terminate_handler + + + std::ctype_base + cpp/locale/ctype_base + std::ctype_base::mask + + + std::ctype_base::mask + cpp/locale/ctype_base + + + std::reference_wrapper + cpp/utility/functional/reference_wrapper + + T + operator= + cpp/utility/functional/reference_wrapper/operator= + + (T... args) + + + T + operator() + cpp/utility/functional/reference_wrapper/operator() + + (T... args) + + + T + get + cpp/utility/functional/reference_wrapper/get + + (T... args) + + + T + reference_wrapper + cpp/utility/functional/reference_wrapper/reference_wrapper + + (T... args) + + + T + operator T& + cpp/utility/functional/reference_wrapper/get + + (T... args) + + + + std::ranlux48_base + cpp/numeric/random/subtract_with_carry_engine + + T + discard + cpp/numeric/random/subtract_with_carry_engine/discard + + (T... args) + + + T + ranlux48_base + cpp/numeric/random/subtract_with_carry_engine/subtract_with_carry_engine + + (T... args) + + + T + max + cpp/numeric/random/subtract_with_carry_engine/max + + (T... args) + + + T + operator() + cpp/numeric/random/subtract_with_carry_engine/operator() + + (T... args) + + + T + seed + cpp/numeric/random/subtract_with_carry_engine/seed + + (T... args) + + + T + min + cpp/numeric/random/subtract_with_carry_engine/min + + (T... args) + + + + std::bit_not + cpp/utility/functional/bit_not + + T + operator() + cpp/utility/functional/bit_not + + (T... args) + + + + std::int_fast16_t + cpp/types/integer + + + std::error_category + cpp/error/error_category + + T + name + cpp/error/error_category/name + + (T... args) + + + T + operator!= + cpp/error/error_category/operator_cmp + + (T... args) + + + T + operator< + cpp/error/error_category/operator_cmp + + (T... args) + + + T + error_category + cpp/error/error_category/error_category + + (T... args) + + + T + equivalent + cpp/error/error_category/equivalent + + (T... args) + + + T + operator== + cpp/error/error_category/operator_cmp + + (T... args) + + + T + ~error_category + cpp/error/error_category/~error_category + + (T... args) + + + T + default_error_condition + cpp/error/error_category/default_error_condition + + (T... args) + + + T + message + cpp/error/error_category/message + + (T... args) + + + + std::regex_traits + cpp/regex/regex_traits + + T + value + cpp/regex/regex_traits/value + + (T... args) + + + T + lookup_collatename + cpp/regex/regex_traits/lookup_collatename + + (T... args) + + + T + isctype + cpp/regex/regex_traits/isctype + + (T... args) + + + T + getloc + cpp/regex/regex_traits/getloc + + (T... args) + + + T + regex_traits + cpp/regex/regex_traits/regex_traits + + (T... args) + + + T + transform_primary + cpp/regex/regex_traits/transform_primary + + (T... args) + + + T + translate + cpp/regex/regex_traits/translate + + (T... args) + + + T + imbue + cpp/regex/regex_traits/imbue + + (T... args) + + + T + lookup_classname + cpp/regex/regex_traits/lookup_classname + + (T... args) + + + T + transform + cpp/regex/regex_traits/transform + + (T... args) + + + T + length + cpp/regex/regex_traits/length + + (T... args) + + + T + translate_nocase + cpp/regex/regex_traits/translate_nocase + + (T... args) + + + + std::regex_constants + + + + std::negative_binomial_distribution + cpp/numeric/random/negative_binomial_distribution + + T + p + cpp/numeric/random/negative_binomial_distribution/params + + (T... args) + + + T + negative_binomial_distribution + cpp/numeric/random/negative_binomial_distribution/negative_binomial_distribution + + (T... args) + + + T + min + cpp/numeric/random/negative_binomial_distribution/min + + (T... args) + + + T + max + cpp/numeric/random/negative_binomial_distribution/max + + (T... args) + + + T + param + cpp/numeric/random/negative_binomial_distribution/param + + (T... args) + + + T + reset + cpp/numeric/random/negative_binomial_distribution/reset + + (T... args) + + + T + k + cpp/numeric/random/negative_binomial_distribution/params + + (T... args) + + + + std::is_union + cpp/types/is_union + + + std::mt19937 + cpp/numeric/random/mersenne_twister_engine + + T + seed + cpp/numeric/random/mersenne_twister_engine/seed + + (T... args) + + + T + discard + cpp/numeric/random/mersenne_twister_engine/discard + + (T... args) + + + T + operator() + cpp/numeric/random/mersenne_twister_engine/operator() + + (T... args) + + + T + mt19937 + cpp/numeric/random/mersenne_twister_engine/mersenne_twister_engine + + (T... args) + + + T + max + cpp/numeric/random/mersenne_twister_engine/max + + (T... args) + + + T + min + cpp/numeric/random/mersenne_twister_engine/min + + (T... args) + + + + std::enable_if + cpp/types/enable_if + + + std::chi_squared_distribution + cpp/numeric/random/chi_squared_distribution + + T + n + cpp/numeric/random/chi_squared_distribution/n + + (T... args) + + + T + reset + cpp/numeric/random/chi_squared_distribution/reset + + (T... args) + + + T + max + cpp/numeric/random/chi_squared_distribution/max + + (T... args) + + + T + operator() + cpp/numeric/random/chi_squared_distribution/operator() + + (T... args) + + + T + param + cpp/numeric/random/chi_squared_distribution/param + + (T... args) + + + T + min + cpp/numeric/random/chi_squared_distribution/min + + (T... args) + + + T + chi_squared_distribution + cpp/numeric/random/chi_squared_distribution/chi_squared_distribution + + (T... args) + + + + std::add_rvalue_reference + cpp/types/add_reference + + + std::basic_istream + cpp/io/basic_istream + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + seekg + cpp/io/basic_istream/seekg + + (T... args) + + + T + operator>> + cpp/io/basic_istream/operator_gtgt + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + std::basic_istream::event_callback + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + getline + cpp/io/basic_istream/getline + + (T... args) + + + T + putback + cpp/io/basic_istream/putback + + (T... args) + + + T + gcount + cpp/io/basic_istream/gcount + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + read + cpp/io/basic_istream/read + + (T... args) + + + T + basic_istream + cpp/io/basic_istream/basic_istream + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + unget + cpp/io/basic_istream/unget + + (T... args) + + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + sync + cpp/io/basic_istream/sync + + (T... args) + + + T + ~basic_istream + cpp/io/basic_istream/~basic_istream + + (T... args) + + + T + ignore + cpp/io/basic_istream/ignore + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + std::basic_istream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + get + cpp/io/basic_istream/get + + (T... args) + + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + readsome + cpp/io/basic_istream/readsome + + (T... args) + + + T + tellg + cpp/io/basic_istream/tellg + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + peek + cpp/io/basic_istream/peek + + (T... args) + + std::basic_istream::sentry + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::basic_istream::event_callback + cpp/io/ios_base/event_callback + + + std::basic_istream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::basic_istream::sentry + cpp/io/basic_istream/sentry + + T + ~sentry + cpp/io/basic_istream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_istream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_istream/sentry + + (T... args) + + + + std::ostream_iterator + cpp/iterator/ostream_iterator + + + std::is_trivially_copy_assignable + cpp/types/is_copy_assignable + + + std::clog + cpp/io/basic_ostream + + + std::is_scalar + cpp/types/is_scalar + + + std::uses_allocator + cpp/memory/uses_allocator + + + std::piecewise_linear_distribution + cpp/numeric/random/piecewise_linear_distribution + + T + piecewise_linear_distribution + cpp/numeric/random/piecewise_linear_distribution/piecewise_linear_distribution + + (T... args) + + + T + densities + cpp/numeric/random/piecewise_linear_distribution/params + + (T... args) + + + T + intervals + cpp/numeric/random/piecewise_linear_distribution/params + + (T... args) + + + T + reset + cpp/numeric/random/piecewise_linear_distribution/reset + + (T... args) + + + T + max + cpp/numeric/random/piecewise_linear_distribution/max + + (T... args) + + + T + operator() + cpp/numeric/random/piecewise_linear_distribution/operator() + + (T... args) + + + T + param + cpp/numeric/random/piecewise_linear_distribution/param + + (T... args) + + + T + min + cpp/numeric/random/piecewise_linear_distribution/min + + (T... args) + + + + std::hash + cpp/utility/hash + + T + hash + cpp/utility/hash/hash + + (T... args) + + + T + operator() + cpp/utility/hash/operator() + + (T... args) + + + + std::shuffle_order_engine + cpp/numeric/random/shuffle_order_engine + + T + discard + cpp/numeric/random/shuffle_order_engine/discard + + (T... args) + + + T + shuffle_order_engine + cpp/numeric/random/shuffle_order_engine/shuffle_order_engine + + (T... args) + + + T + max + cpp/numeric/random/shuffle_order_engine/max + + (T... args) + + + T + operator() + cpp/numeric/random/shuffle_order_engine/operator() + + (T... args) + + + T + base + cpp/numeric/random/shuffle_order_engine/base + + (T... args) + + + T + seed + cpp/numeric/random/shuffle_order_engine/seed + + (T... args) + + + T + min + cpp/numeric/random/shuffle_order_engine/min + + (T... args) + + + + std::chrono + + std::chrono::minutes + + T + time_point_cast + cpp/chrono/time_point/time_point_cast + + (T... args) + + std::chrono::seconds + std::chrono::treat_as_floating_point + std::chrono::duration + std::chrono::milliseconds + std::chrono::steady_clock + std::chrono::system_clock + std::chrono::hours + std::chrono::time_point + std::chrono::high_resolution_clock + std::chrono::duration_values + std::chrono::microseconds + std::chrono::nanoseconds + + T + duration_cast + cpp/chrono/duration/duration_cast + + (T... args) + + + + std::chrono::minutes + cpp/chrono/duration + + T + operator--(int) + cpp/chrono/duration/operator_arith2 + + (T... args) + + + T + minutes + cpp/chrono/duration/duration + + (T... args) + + + T + zero + cpp/chrono/duration/zero + + (T... args) + + + T + operator-- + cpp/chrono/duration/operator_arith2 + + (T... args) + + + T + operator+= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + T + operator- + cpp/chrono/duration/operator_arith + + (T... args) + + + T + operator/= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + T + operator++ + cpp/chrono/duration/operator_arith2 + + (T... args) + + + T + operator++(int) + cpp/chrono/duration/operator_arith2 + + (T... args) + + + T + operator= + cpp/chrono/duration/operator= + + (T... args) + + + T + operator*= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + T + min + cpp/chrono/duration/min + + (T... args) + + + T + count + cpp/chrono/duration/count + + (T... args) + + + T + operator%= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + T + max + cpp/chrono/duration/max + + (T... args) + + + T + operator+ + cpp/chrono/duration/operator_arith + + (T... args) + + + T + operator-= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + + std::chrono::seconds + cpp/chrono/duration + + T + operator--(int) + cpp/chrono/duration/operator_arith2 + + (T... args) + + + T + zero + cpp/chrono/duration/zero + + (T... args) + + + T + operator-- + cpp/chrono/duration/operator_arith2 + + (T... args) + + + T + count + cpp/chrono/duration/count + + (T... args) + + + T + operator+= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + T + operator- + cpp/chrono/duration/operator_arith + + (T... args) + + + T + operator/= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + T + operator++ + cpp/chrono/duration/operator_arith2 + + (T... args) + + + T + operator++(int) + cpp/chrono/duration/operator_arith2 + + (T... args) + + + T + operator= + cpp/chrono/duration/operator= + + (T... args) + + + T + operator*= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + T + min + cpp/chrono/duration/min + + (T... args) + + + T + max + cpp/chrono/duration/max + + (T... args) + + + T + operator%= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + T + seconds + cpp/chrono/duration/duration + + (T... args) + + + T + operator+ + cpp/chrono/duration/operator_arith + + (T... args) + + + T + operator-= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + + std::chrono::treat_as_floating_point + cpp/chrono/treat_as_floating_point + + + std::chrono::duration + cpp/chrono/duration + + T + operator--(int) + cpp/chrono/duration/operator_arith2 + + (T... args) + + + T + zero + cpp/chrono/duration/zero + + (T... args) + + + T + operator-- + cpp/chrono/duration/operator_arith2 + + (T... args) + + + T + count + cpp/chrono/duration/count + + (T... args) + + + T + operator+= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + T + duration + cpp/chrono/duration/duration + + (T... args) + + + T + operator/= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + T + operator++ + cpp/chrono/duration/operator_arith2 + + (T... args) + + + T + operator++(int) + cpp/chrono/duration/operator_arith2 + + (T... args) + + + T + operator= + cpp/chrono/duration/operator= + + (T... args) + + + T + operator*= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + T + min + cpp/chrono/duration/min + + (T... args) + + + T + operator- + cpp/chrono/duration/operator_arith + + (T... args) + + + T + operator%= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + T + max + cpp/chrono/duration/max + + (T... args) + + + T + operator+ + cpp/chrono/duration/operator_arith + + (T... args) + + + T + operator-= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + + std::chrono::milliseconds + cpp/chrono/duration + + T + operator--(int) + cpp/chrono/duration/operator_arith2 + + (T... args) + + + T + zero + cpp/chrono/duration/zero + + (T... args) + + + T + operator-- + cpp/chrono/duration/operator_arith2 + + (T... args) + + + T + operator+= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + T + operator- + cpp/chrono/duration/operator_arith + + (T... args) + + + T + operator/= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + T + operator++ + cpp/chrono/duration/operator_arith2 + + (T... args) + + + T + milliseconds + cpp/chrono/duration/duration + + (T... args) + + + T + operator++(int) + cpp/chrono/duration/operator_arith2 + + (T... args) + + + T + operator= + cpp/chrono/duration/operator= + + (T... args) + + + T + operator*= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + T + min + cpp/chrono/duration/min + + (T... args) + + + T + count + cpp/chrono/duration/count + + (T... args) + + + T + operator%= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + T + max + cpp/chrono/duration/max + + (T... args) + + + T + operator+ + cpp/chrono/duration/operator_arith + + (T... args) + + + T + operator-= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + + std::chrono::steady_clock + cpp/chrono/steady_clock + + T + now + cpp/chrono/steady_clock/now + + (T... args) + + + + std::chrono::system_clock + cpp/chrono/system_clock + + T + now + cpp/chrono/system_clock/now + + (T... args) + + + T + to_time_t + cpp/chrono/system_clock/to_time_t + + (T... args) + + + T + from_time_t + cpp/chrono/system_clock/from_time_t + + (T... args) + + + + std::chrono::hours + cpp/chrono/duration + + T + operator--(int) + cpp/chrono/duration/operator_arith2 + + (T... args) + + + T + zero + cpp/chrono/duration/zero + + (T... args) + + + T + operator-- + cpp/chrono/duration/operator_arith2 + + (T... args) + + + T + operator+= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + T + operator- + cpp/chrono/duration/operator_arith + + (T... args) + + + T + operator/= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + T + operator++ + cpp/chrono/duration/operator_arith2 + + (T... args) + + + T + operator++(int) + cpp/chrono/duration/operator_arith2 + + (T... args) + + + T + operator= + cpp/chrono/duration/operator= + + (T... args) + + + T + operator*= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + T + hours + cpp/chrono/duration/duration + + (T... args) + + + T + min + cpp/chrono/duration/min + + (T... args) + + + T + count + cpp/chrono/duration/count + + (T... args) + + + T + operator%= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + T + max + cpp/chrono/duration/max + + (T... args) + + + T + operator+ + cpp/chrono/duration/operator_arith + + (T... args) + + + T + operator-= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + + std::chrono::time_point + cpp/chrono/time_point + + T + time_since_epoch + cpp/chrono/time_point/time_since_epoch + + (T... args) + + + T + min + cpp/chrono/time_point/min + + (T... args) + + + T + operator- + cpp/chrono/time_point/operator_arith + + (T... args) + + + T + max + cpp/chrono/time_point/max + + (T... args) + + + T + operator+ + cpp/chrono/time_point/operator_arith + + (T... args) + + + T + time_point + cpp/chrono/time_point/time_point + + (T... args) + + + + std::chrono::high_resolution_clock + cpp/chrono/high_resolution_clock + + T + now + cpp/chrono/high_resolution_clock/now + + (T... args) + + + + std::chrono::duration_values + cpp/chrono/duration_values + + T + max + cpp/chrono/duration_values/max + + (T... args) + + + T + zero + cpp/chrono/duration_values/zero + + (T... args) + + + T + min + cpp/chrono/duration_values/min + + (T... args) + + + + std::chrono::microseconds + cpp/chrono/duration + + T + operator--(int) + cpp/chrono/duration/operator_arith2 + + (T... args) + + + T + zero + cpp/chrono/duration/zero + + (T... args) + + + T + operator-- + cpp/chrono/duration/operator_arith2 + + (T... args) + + + T + count + cpp/chrono/duration/count + + (T... args) + + + T + operator+= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + T + operator/= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + T + operator++ + cpp/chrono/duration/operator_arith2 + + (T... args) + + + T + operator++(int) + cpp/chrono/duration/operator_arith2 + + (T... args) + + + T + operator= + cpp/chrono/duration/operator= + + (T... args) + + + T + operator*= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + T + min + cpp/chrono/duration/min + + (T... args) + + + T + operator- + cpp/chrono/duration/operator_arith + + (T... args) + + + T + operator%= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + T + max + cpp/chrono/duration/max + + (T... args) + + + T + microseconds + cpp/chrono/duration/duration + + (T... args) + + + T + operator+ + cpp/chrono/duration/operator_arith + + (T... args) + + + T + operator-= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + + std::chrono::nanoseconds + cpp/chrono/duration + + T + operator--(int) + cpp/chrono/duration/operator_arith2 + + (T... args) + + + T + min + cpp/chrono/duration/min + + (T... args) + + + T + zero + cpp/chrono/duration/zero + + (T... args) + + + T + operator-- + cpp/chrono/duration/operator_arith2 + + (T... args) + + + T + operator+= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + T + operator- + cpp/chrono/duration/operator_arith + + (T... args) + + + T + operator/= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + T + operator++ + cpp/chrono/duration/operator_arith2 + + (T... args) + + + T + operator++(int) + cpp/chrono/duration/operator_arith2 + + (T... args) + + + T + operator= + cpp/chrono/duration/operator= + + (T... args) + + + T + operator*= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + T + operator+ + cpp/chrono/duration/operator_arith + + (T... args) + + + T + count + cpp/chrono/duration/count + + (T... args) + + + T + operator%= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + T + max + cpp/chrono/duration/max + + (T... args) + + + T + nanoseconds + cpp/chrono/duration/duration + + (T... args) + + + T + operator-= + cpp/chrono/duration/operator_arith3 + + (T... args) + + + + std::greater + cpp/utility/functional/greater + + T + operator() + cpp/utility/functional/greater + + (T... args) + + + + std::csub_match + cpp/regex/sub_match + + T + csub_match + cpp/regex/sub_match/sub_match + + (T... args) + + + T + operator string_type + cpp/regex/sub_match/str + + (T... args) + + + T + str + cpp/regex/sub_match/str + + (T... args) + + + T + length + cpp/regex/sub_match/length + + (T... args) + + + T + compare + cpp/regex/sub_match/compare + + (T... args) + + + + std::uintmax_t + cpp/types/integer + + + std::remove_pointer + cpp/types/remove_pointer + + + std::numeric_limits + cpp/types/numeric_limits + + T + lowest + cpp/types/numeric_limits/lowest + + (T... args) + + + T + infinity + cpp/types/numeric_limits/infinity + + (T... args) + + + T + signaling_NaN + cpp/types/numeric_limits/signaling_NaN + + (T... args) + + + T + quiet_NaN + cpp/types/numeric_limits/quiet_NaN + + (T... args) + + + T + denorm_min + cpp/types/numeric_limits/denorm_min + + (T... args) + + + T + max + cpp/types/numeric_limits/max + + (T... args) + + + T + round_error + cpp/types/numeric_limits/round_error + + (T... args) + + + T + min + cpp/types/numeric_limits/min + + (T... args) + + + T + epsilon + cpp/types/numeric_limits/epsilon + + (T... args) + + + + std::add_volatile + cpp/types/add_cv + + + std::once_flag + cpp/thread/once_flag + + T + once_flag + cpp/thread/once_flag + + (T... args) + + + + std::is_literal_type + cpp/types/is_literal_type + + + std::money_base + cpp/locale/money_base + std::money_base::pattern + + + std::money_base::pattern + cpp/locale/money_base + + + std::peta + cpp/numeric/ratio/ratio + + + std::is_placeholder + cpp/utility/functional/is_placeholder + + + std::add_const + cpp/types/add_cv + + + std::basic_stringbuf + cpp/io/basic_stringbuf + + T + pptr + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + epptr + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + eback + cpp/io/basic_streambuf/gptr + + (T... args) + + + T + setp + cpp/io/basic_streambuf/setp + + (T... args) + + + T + sputbackc + cpp/io/basic_streambuf/sputbackc + + (T... args) + + + T + sgetc + cpp/io/basic_streambuf/sgetc + + (T... args) + + + T + sungetc + cpp/io/basic_streambuf/sungetc + + (T... args) + + + T + pubseekoff + cpp/io/basic_streambuf/pubseekoff + + (T... args) + + + T + seekoff + cpp/io/basic_streambuf/pubseekoff + + (T... args) + + + T + str + cpp/io/basic_stringbuf/str + + (T... args) + + + T + sync + cpp/io/basic_streambuf/pubsync + + (T... args) + + + T + xsputn + cpp/io/basic_streambuf/sputn + + (T... args) + + + T + pbase + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + pubimbue + cpp/io/basic_streambuf/pubimbue + + (T... args) + + + T + showmanyc + cpp/io/basic_streambuf/showmanyc + + (T... args) + + + T + basic_stringbuf + cpp/io/basic_stringbuf/basic_stringbuf + + (T... args) + + + T + egptr + cpp/io/basic_streambuf/gptr + + (T... args) + + + T + seekpos + cpp/io/basic_streambuf/pubseekpos + + (T... args) + + + T + underflow + cpp/io/basic_streambuf/underflow + + (T... args) + + + T + setbuf + cpp/io/basic_streambuf/pubsetbuf + + (T... args) + + + T + gbump + cpp/io/basic_streambuf/gbump + + (T... args) + + + T + in_avail + cpp/io/basic_streambuf/in_avail + + (T... args) + + + T + swap + cpp/io/basic_streambuf/swap + + (T... args) + + + T + pbackfail + cpp/io/basic_streambuf/pbackfail + + (T... args) + + + T + sputc + cpp/io/basic_streambuf/sputc + + (T... args) + + + T + xsgetn + cpp/io/basic_streambuf/sgetn + + (T... args) + + + T + uflow + cpp/io/basic_streambuf/uflow + + (T... args) + + + T + gptr + cpp/io/basic_streambuf/gptr + + (T... args) + + + T + sputn + cpp/io/basic_streambuf/sputn + + (T... args) + + + T + sgetn + cpp/io/basic_streambuf/sgetn + + (T... args) + + + T + sbumpc + cpp/io/basic_streambuf/sbumpc + + (T... args) + + + T + overflow + cpp/io/basic_streambuf/overflow + + (T... args) + + + T + operator= + cpp/io/basic_stringbuf/operator= + + (T... args) + + + T + pbump + cpp/io/basic_streambuf/pbump + + (T... args) + + + T + pubsetbuf + cpp/io/basic_streambuf/pubsetbuf + + (T... args) + + + T + pubsync + cpp/io/basic_streambuf/pubsync + + (T... args) + + + T + imbue + cpp/io/basic_streambuf/pubimbue + + (T... args) + + + T + setg + cpp/io/basic_streambuf/setg + + (T... args) + + + T + snextc + cpp/io/basic_streambuf/snextc + + (T... args) + + + T + getloc + cpp/io/basic_streambuf/getloc + + (T... args) + + + T + pubseekpos + cpp/io/basic_streambuf/pubseekpos + + (T... args) + + + + std::tm + cpp/chrono/c/tm + + + std::is_abstract + cpp/types/is_abstract + + + std::deque + cpp/container/deque + + T + pop_front + cpp/container/deque/pop_front + + (T... args) + + + T + push_back + cpp/container/deque/push_back + + (T... args) + + + T + shrink_to_fit + cpp/container/deque/shrink_to_fit + + (T... args) + + + T + crbegin + cpp/container/deque/rbegin + + (T... args) + + + T + erase + cpp/container/deque/erase + + (T... args) + + + T + insert + cpp/container/deque/insert + + (T... args) + + + T + ~deque + cpp/container/deque/~deque + + (T... args) + + + T + back + cpp/container/deque/back + + (T... args) + + + T + end + cpp/container/deque/end + + (T... args) + + + T + push_front + cpp/container/deque/push_front + + (T... args) + + + T + emplace_back + cpp/container/deque/emplace_back + + (T... args) + + + T + pop_back + cpp/container/deque/pop_back + + (T... args) + + + T + cbegin + cpp/container/deque/begin + + (T... args) + + + T + front + cpp/container/deque/front + + (T... args) + + + T + deque + cpp/container/deque/deque + + (T... args) + + + T + size + cpp/container/deque/size + + (T... args) + + + T + resize + cpp/container/deque/resize + + (T... args) + + + T + emplace_front + cpp/container/deque/emplace_front + + (T... args) + + + T + rbegin + cpp/container/deque/rbegin + + (T... args) + + + T + crend + cpp/container/deque/rend + + (T... args) + + + T + assign + cpp/container/deque/assign + + (T... args) + + + T + operator= + cpp/container/deque/operator= + + (T... args) + + + T + empty + cpp/container/deque/empty + + (T... args) + + + T + cend + cpp/container/deque/end + + (T... args) + + + T + swap + cpp/container/deque/swap + + (T... args) + + + T + max_size + cpp/container/deque/max_size + + (T... args) + + + T + rend + cpp/container/deque/rend + + (T... args) + + + T + get_allocator + cpp/container/deque/get_allocator + + (T... args) + + + T + clear + cpp/container/deque/clear + + (T... args) + + + T + at + cpp/container/deque/at + + (T... args) + + + T + emplace + cpp/container/deque/emplace + + (T... args) + + + T + operator[] + cpp/container/deque/operator_at + + (T... args) + + + T + begin + cpp/container/deque/begin + + (T... args) + + + + std::allocator + cpp/memory/allocator + + T + allocator + cpp/memory/allocator/allocator + + (T... args) + + + T + allocate + cpp/memory/allocator/allocate + + (T... args) + + + T + destroy + cpp/memory/allocator/destroy + + (T... args) + + + T + ~allocator + cpp/memory/allocator/~allocator + + (T... args) + + + T + max_size + cpp/memory/allocator/max_size + + (T... args) + + + T + address + cpp/memory/allocator/address + + (T... args) + + + T + deallocate + cpp/memory/allocator/deallocate + + (T... args) + + + T + construct + cpp/memory/allocator/construct + + (T... args) + + + + std::scoped_allocator_adaptor + cpp/memory/scoped_allocator_adaptor + + T + deallocate + cpp/memory/scoped_allocator_adaptor/deallocate + + (T... args) + + + T + scoped_allocator_adaptor + cpp/memory/scoped_allocator_adaptor/scoped_allocator_adaptor + + (T... args) + + + T + destroy + cpp/memory/scoped_allocator_adaptor/destroy + + (T... args) + + + T + construct + cpp/memory/scoped_allocator_adaptor/construct + + (T... args) + + + T + max_size + cpp/memory/scoped_allocator_adaptor/max_size + + (T... args) + + + T + inner_allocator + cpp/memory/scoped_allocator_adaptor/inner_allocator + + (T... args) + + + T + select_on_container_copy_construction + cpp/memory/scoped_allocator_adaptor/select_on_container_copy_construction + + (T... args) + + + T + allocate + cpp/memory/scoped_allocator_adaptor/allocate + + (T... args) + + + T + outer_allocator + cpp/memory/scoped_allocator_adaptor/outer_allocator + + (T... args) + + + T + ~scoped_allocator_adaptor + cpp/memory/scoped_allocator_adaptor/~scoped_allocator_adaptor + + (T... args) + + + + std::ssub_match + cpp/regex/sub_match + + T + operator string_type + cpp/regex/sub_match/str + + (T... args) + + + T + ssub_match + cpp/regex/sub_match/sub_match + + (T... args) + + + T + str + cpp/regex/sub_match/str + + (T... args) + + + T + length + cpp/regex/sub_match/length + + (T... args) + + + T + compare + cpp/regex/sub_match/compare + + (T... args) + + + + std::messages_byname + cpp/locale/messages_byname + + T + do_get + cpp/locale/messages/get + + (T... args) + + std::messages_byname::char_type + std::messages_byname::catalog + + T + ~messages_byname + cpp/locale/messages_byname + + (T... args) + + + T + messages_byname + cpp/locale/messages_byname + + (T... args) + + + T + do_open + cpp/locale/messages/open + + (T... args) + + + T + do_close + cpp/locale/messages/close + + (T... args) + + + T + open + cpp/locale/messages/open + + (T... args) + + std::messages_byname::string_type + + T + get + cpp/locale/messages/get + + (T... args) + + + T + close + cpp/locale/messages/close + + (T... args) + + + + std::messages_byname::char_type + cpp/locale/messages + + + std::messages_byname::catalog + cpp/locale/messages_base + + + std::messages_byname::string_type + cpp/locale/messages + + + std::promise + cpp/thread/promise + + T + set_exception + cpp/thread/promise/set_exception + + (T... args) + + + T + operator= + cpp/thread/promise/operator= + + (T... args) + + + T + swap + cpp/thread/promise/swap + + (T... args) + + + T + set_exception_at_thread_exit + cpp/thread/promise/set_exception_at_thread_exit + + (T... args) + + + T + set_value + cpp/thread/promise/set_value + + (T... args) + + + T + get_future + cpp/thread/promise/get_future + + (T... args) + + + T + promise + cpp/thread/promise/promise + + (T... args) + + + T + ~promise + cpp/thread/promise/~promise + + (T... args) + + + T + set_value_at_thread_exit + cpp/thread/promise/set_value_at_thread_exit + + (T... args) + + + + std::add_pointer + cpp/types/add_pointer + + + std::uintptr_t + cpp/types/integer + + + std::bit_and + cpp/utility/functional/bit_and + + T + operator() + cpp/utility/functional/bit_and + + (T... args) + + + + std::uniform_int_distribution + cpp/numeric/random/uniform_int_distribution + + T + min + cpp/numeric/random/uniform_int_distribution/min + + (T... args) + + + T + b + cpp/numeric/random/uniform_int_distribution/params + + (T... args) + + + T + a + cpp/numeric/random/uniform_int_distribution/params + + (T... args) + + + T + max + cpp/numeric/random/uniform_int_distribution/max + + (T... args) + + + T + operator() + cpp/numeric/random/uniform_int_distribution/operator() + + (T... args) + + + T + param + cpp/numeric/random/uniform_int_distribution/param + + (T... args) + + + T + reset + cpp/numeric/random/uniform_int_distribution/reset + + (T... args) + + + T + uniform_int_distribution + cpp/numeric/random/uniform_int_distribution/uniform_int_distribution + + (T... args) + + + + std::type_info + cpp/types/type_info + + T + operator!= + cpp/types/type_info/operator_cmp + + (T... args) + + + T + before + cpp/types/type_info/before + + (T... args) + + + T + name + cpp/types/type_info/name + + (T... args) + + + T + operator== + cpp/types/type_info/operator_cmp + + (T... args) + + + T + hash_code + cpp/types/type_info/hash_code + + (T... args) + + + + std::fisher_f_distribution + cpp/numeric/random/fisher_f_distribution + + T + fisher_f_distribution + cpp/numeric/random/fisher_f_distribution/fisher_f_distribution + + (T... args) + + + T + n + cpp/numeric/random/fisher_f_distribution/params + + (T... args) + + + T + reset + cpp/numeric/random/fisher_f_distribution/reset + + (T... args) + + + T + m + cpp/numeric/random/fisher_f_distribution/params + + (T... args) + + + T + operator() + cpp/numeric/random/fisher_f_distribution/operator() + + (T... args) + + + T + max + cpp/numeric/random/fisher_f_distribution/max + + (T... args) + + + T + param + cpp/numeric/random/fisher_f_distribution/param + + (T... args) + + + T + min + cpp/numeric/random/fisher_f_distribution/min + + (T... args) + + + + std::strstream + cpp/io/strstream + + T + seekp + cpp/io/basic_ostream/seekp + + (T... args) + + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + str + cpp/io/strstream/str + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + operator>> + cpp/io/basic_istream/operator_gtgt + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + + T + seekg + cpp/io/basic_istream/seekg + + (T... args) + + + T + pcount + cpp/io/strstream/pcount + + (T... args) + + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + tellp + cpp/io/basic_ostream/tellp + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + gcount + cpp/io/basic_istream/gcount + + (T... args) + + + T + unget + cpp/io/basic_istream/unget + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + read + cpp/io/basic_istream/read + + (T... args) + + + T + getline + cpp/io/basic_istream/getline + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + std::strstream::sentry + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + operator<< + cpp/io/basic_ostream/operator_ltlt + + (T... args) + + std::strstream::event_callback + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + write + cpp/io/basic_ostream/write + + (T... args) + + + T + sync + cpp/io/basic_istream/sync + + (T... args) + + + T + putback + cpp/io/basic_istream/putback + + (T... args) + + + T + ignore + cpp/io/basic_istream/ignore + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + readsome + cpp/io/basic_istream/readsome + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + std::strstream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + get + cpp/io/basic_istream/get + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + strstream + cpp/io/strstream/strstream + + (T... args) + + + T + flush + cpp/io/basic_ostream/flush + + (T... args) + + + T + tellg + cpp/io/basic_istream/tellg + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + freeze + cpp/io/strstream/freeze + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + peek + cpp/io/basic_istream/peek + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + + T + ~strstream + cpp/io/strstream/~strstream + + (T... args) + + + T + put + cpp/io/basic_ostream/put + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::strstream::sentry + cpp/io/basic_ostream/sentry + + T + ~sentry + cpp/io/basic_istream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_istream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_istream/sentry + + (T... args) + + + + std::strstream::event_callback + cpp/io/ios_base/event_callback + + + std::strstream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::time_get_byname + cpp/locale/time_get_byname + + T + do_get + cpp/locale/time_get/get + + (T... args) + + + T + do_get_monthname + cpp/locale/time_get/get_monthname + + (T... args) + + + T + get_weekday + cpp/locale/time_get/get_weekday + + (T... args) + + + T + do_get_time + cpp/locale/time_get/get_time + + (T... args) + + + T + time_get_byname + cpp/locale/time_get_byname + + (T... args) + + + T + do_get_year + cpp/locale/time_get/get_year + + (T... args) + + std::time_get_byname::iter_type + + T + get_monthname + cpp/locale/time_get/get_monthname + + (T... args) + + + T + ~time_get_byname + cpp/locale/time_get_byname + + (T... args) + + + T + get_time + cpp/locale/time_get/get_time + + (T... args) + + std::time_get_byname::char_type + + T + do_get_date + cpp/locale/time_get/get_date + + (T... args) + + + T + get_date + cpp/locale/time_get/get_date + + (T... args) + + + T + do_date_order + cpp/locale/time_get/date_order + + (T... args) + + + T + get_year + cpp/locale/time_get/get_year + + (T... args) + + + T + date_order + cpp/locale/time_get/date_order + + (T... args) + + + T + get + cpp/locale/time_get/get + + (T... args) + + + T + do_get_weekday + cpp/locale/time_get/get_weekday + + (T... args) + + + + std::time_get_byname::iter_type + cpp/locale/time_get + + + std::time_get_byname::char_type + cpp/locale/time_get + + + std::basic_streambuf + cpp/io/basic_streambuf + + T + pptr + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + epptr + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + eback + cpp/io/basic_streambuf/gptr + + (T... args) + + + T + setp + cpp/io/basic_streambuf/setp + + (T... args) + + + T + sputbackc + cpp/io/basic_streambuf/sputbackc + + (T... args) + + + T + getloc + cpp/io/basic_streambuf/getloc + + (T... args) + + + T + seekoff + cpp/io/basic_streambuf/pubseekoff + + (T... args) + + + T + pubseekoff + cpp/io/basic_streambuf/pubseekoff + + (T... args) + + + T + sungetc + cpp/io/basic_streambuf/sungetc + + (T... args) + + + T + sync + cpp/io/basic_streambuf/pubsync + + (T... args) + + + T + xsputn + cpp/io/basic_streambuf/sputn + + (T... args) + + + T + pbase + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + sgetc + cpp/io/basic_streambuf/sgetc + + (T... args) + + + T + pubimbue + cpp/io/basic_streambuf/pubimbue + + (T... args) + + + T + showmanyc + cpp/io/basic_streambuf/showmanyc + + (T... args) + + + T + egptr + cpp/io/basic_streambuf/gptr + + (T... args) + + + T + seekpos + cpp/io/basic_streambuf/pubseekpos + + (T... args) + + + T + underflow + cpp/io/basic_streambuf/underflow + + (T... args) + + + T + setbuf + cpp/io/basic_streambuf/pubsetbuf + + (T... args) + + + T + gbump + cpp/io/basic_streambuf/gbump + + (T... args) + + + T + in_avail + cpp/io/basic_streambuf/in_avail + + (T... args) + + + T + swap + cpp/io/basic_streambuf/swap + + (T... args) + + + T + basic_streambuf + cpp/io/basic_streambuf/basic_streambuf + + (T... args) + + + T + pbackfail + cpp/io/basic_streambuf/pbackfail + + (T... args) + + + T + sputc + cpp/io/basic_streambuf/sputc + + (T... args) + + + T + xsgetn + cpp/io/basic_streambuf/sgetn + + (T... args) + + + T + uflow + cpp/io/basic_streambuf/uflow + + (T... args) + + + T + overflow + cpp/io/basic_streambuf/overflow + + (T... args) + + + T + sputn + cpp/io/basic_streambuf/sputn + + (T... args) + + + T + sgetn + cpp/io/basic_streambuf/sgetn + + (T... args) + + + T + sbumpc + cpp/io/basic_streambuf/sbumpc + + (T... args) + + + T + operator= + cpp/io/basic_streambuf/operator= + + (T... args) + + + T + pbump + cpp/io/basic_streambuf/pbump + + (T... args) + + + T + pubsetbuf + cpp/io/basic_streambuf/pubsetbuf + + (T... args) + + + T + pubsync + cpp/io/basic_streambuf/pubsync + + (T... args) + + + T + imbue + cpp/io/basic_streambuf/pubimbue + + (T... args) + + + T + setg + cpp/io/basic_streambuf/setg + + (T... args) + + + T + snextc + cpp/io/basic_streambuf/snextc + + (T... args) + + + T + gptr + cpp/io/basic_streambuf/gptr + + (T... args) + + + T + pubseekpos + cpp/io/basic_streambuf/pubseekpos + + (T... args) + + + T + ~basic_streambuf + cpp/io/basic_streambuf/~basic_streambuf + + (T... args) + + + + std::is_nothrow_constructible + cpp/types/is_constructible + + + std::queue + cpp/container/queue + + T + operator= + cpp/container/queue/operator= + + (T... args) + + + T + swap + cpp/container/queue/swap + + (T... args) + + + T + emplace + cpp/container/queue/emplace + + (T... args) + + + T + empty + cpp/container/queue/empty + + (T... args) + + + T + ~queue + cpp/container/queue/~queue + + (T... args) + + + T + pop + cpp/container/queue/pop + + (T... args) + + + T + front + cpp/container/queue/front + + (T... args) + + + T + push + cpp/container/queue/push + + (T... args) + + + T + queue + cpp/container/queue/queue + + (T... args) + + + T + back + cpp/container/queue/back + + (T... args) + + + T + size + cpp/container/queue/size + + (T... args) + + + + std::is_base_of + cpp/types/is_base_of + + + std::intmax_t + cpp/types/integer + + + std::ranlux24 + cpp/numeric/random/discard_block_engine + + T + discard + cpp/numeric/random/discard_block_engine/discard + + (T... args) + + + T + ranlux24 + cpp/numeric/random/discard_block_engine/discard_block_engine + + (T... args) + + + T + max + cpp/numeric/random/discard_block_engine/max + + (T... args) + + + T + operator() + cpp/numeric/random/discard_block_engine/operator() + + (T... args) + + + T + base + cpp/numeric/random/discard_block_engine/base + + (T... args) + + + T + seed + cpp/numeric/random/discard_block_engine/seed + + (T... args) + + + T + min + cpp/numeric/random/discard_block_engine/min + + (T... args) + + + + std::remove_cv + cpp/types/remove_cv + + + std::is_trivially_destructible + cpp/types/is_destructible + + + std::wcin + cpp/io/basic_istream + + + std::atomic + cpp/atomic/atomic + + T + store + cpp/atomic/atomic/store + + (T... args) + + + T + compare_exchange_strong + cpp/atomic/atomic/compare_exchange + + (T... args) + + + T + load + cpp/atomic/atomic/load + + (T... args) + + + T + operator--(int) + cpp/atomic/atomic/operator_arith + + (T... args) + + + T + operator+= + cpp/atomic/atomic/operator_arith2 + + (T... args) + + + T + fetch_or + cpp/atomic/atomic/fetch_or + + (T... args) + + + T + fetch_xor + cpp/atomic/atomic/fetch_xor + + (T... args) + + + T + operator^= + cpp/atomic/atomic/operator_arith2 + + (T... args) + + + T + operator|= + cpp/atomic/atomic/operator_arith2 + + (T... args) + + + T + compare_exchange_weak + cpp/atomic/atomic/compare_exchange + + (T... args) + + + T + operator-= + cpp/atomic/atomic/operator_arith2 + + (T... args) + + + T + fetch_add + cpp/atomic/atomic/fetch_add + + (T... args) + + + T + operator&= + cpp/atomic/atomic/operator_arith2 + + (T... args) + + + T + operator-- + cpp/atomic/atomic/operator_arith + + (T... args) + + + T + atomic + cpp/atomic/atomic/atomic + + (T... args) + + + T + fetch_and + cpp/atomic/atomic/fetch_and + + (T... args) + + + T + exchange + cpp/atomic/atomic/exchange + + (T... args) + + + T + operator T + cpp/atomic/atomic/operator_T + + (T... args) + + + T + operator++(int) + cpp/atomic/atomic/operator_arith + + (T... args) + + + T + operator= + cpp/atomic/atomic/operator= + + (T... args) + + + T + operator++ + cpp/atomic/atomic/operator_arith + + (T... args) + + + T + fetch_sub + cpp/atomic/atomic/fetch_sub + + (T... args) + + + T + is_lock_free + cpp/atomic/atomic/is_lock_free + + (T... args) + + + + std::basic_stringstream + cpp/io/basic_stringstream + + T + seekp + cpp/io/basic_ostream/seekp + + (T... args) + + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + str + cpp/io/basic_stringstream/str + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + operator>> + cpp/io/basic_istream/operator_gtgt + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + + T + seekg + cpp/io/basic_istream/seekg + + (T... args) + + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + tellp + cpp/io/basic_ostream/tellp + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + gcount + cpp/io/basic_istream/gcount + + (T... args) + + + T + unget + cpp/io/basic_istream/unget + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + read + cpp/io/basic_istream/read + + (T... args) + + + T + getline + cpp/io/basic_istream/getline + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + basic_stringstream + cpp/io/basic_stringstream/basic_stringstream + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + std::basic_stringstream::sentry + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + operator<< + cpp/io/basic_ostream/operator_ltlt + + (T... args) + + std::basic_stringstream::event_callback + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + write + cpp/io/basic_ostream/write + + (T... args) + + + T + sync + cpp/io/basic_istream/sync + + (T... args) + + + T + putback + cpp/io/basic_istream/putback + + (T... args) + + + T + ignore + cpp/io/basic_istream/ignore + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + readsome + cpp/io/basic_istream/readsome + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + std::basic_stringstream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + get + cpp/io/basic_istream/get + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + flush + cpp/io/basic_ostream/flush + + (T... args) + + + T + tellg + cpp/io/basic_istream/tellg + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + peek + cpp/io/basic_istream/peek + + (T... args) + + + T + operator= + cpp/io/basic_stringstream/operator= + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + + T + put + cpp/io/basic_ostream/put + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::basic_stringstream::sentry + cpp/io/basic_ostream/sentry + + T + ~sentry + cpp/io/basic_istream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_istream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_istream/sentry + + (T... args) + + + + std::basic_stringstream::event_callback + cpp/io/ios_base/event_callback + + + std::basic_stringstream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::is_void + cpp/types/is_void + + + std::plus + cpp/utility/functional/plus + + T + operator() + cpp/utility/functional/plus + + (T... args) + + + + std::bitset + cpp/utility/bitset + + T + none + cpp/utility/bitset/all_any_none + + (T... args) + + + T + operator<< + cpp/utility/bitset/operator_ltltgtgt + + (T... args) + + + T + operator>> + cpp/utility/bitset/operator_ltltgtgt + + (T... args) + + std::bitset::reference + + T + reset + cpp/utility/bitset/reset + + (T... args) + + + T + count + cpp/utility/bitset/count + + (T... args) + + + T + operator<<= + cpp/utility/bitset/operator_ltltgtgt + + (T... args) + + + T + operator|= + cpp/utility/bitset/operator_logic + + (T... args) + + + T + operator&= + cpp/utility/bitset/operator_logic + + (T... args) + + + T + bitset + cpp/utility/bitset/bitset + + (T... args) + + + T + size + cpp/utility/bitset/size + + (T... args) + + + T + set + cpp/utility/bitset/set + + (T... args) + + + T + all + cpp/utility/bitset/all_any_none + + (T... args) + + + T + to_string + cpp/utility/bitset/to_string + + (T... args) + + + T + operator!= + cpp/utility/bitset/operator_cmp + + (T... args) + + + T + any + cpp/utility/bitset/all_any_none + + (T... args) + + + T + test + cpp/utility/bitset/test + + (T... args) + + + T + operator== + cpp/utility/bitset/operator_cmp + + (T... args) + + + T + operator>>= + cpp/utility/bitset/operator_ltltgtgt + + (T... args) + + + T + to_ulong + cpp/utility/bitset/to_ulong + + (T... args) + + + T + operator^= + cpp/utility/bitset/operator_logic + + (T... args) + + + T + operator~ + cpp/utility/bitset/operator_logic + + (T... args) + + + T + to_ullong + cpp/utility/bitset/to_ullong + + (T... args) + + + T + operator[] + cpp/utility/bitset/operator_at + + (T... args) + + + T + flip + cpp/utility/bitset/flip + + (T... args) + + + + std::bitset::reference + cpp/utility/bitset/reference + + + std::FILE + cpp/io/c + + + std::thread + cpp/thread/thread + + T + joinable + cpp/thread/thread/joinable + + (T... args) + + + T + operator= + cpp/thread/thread/operator= + + (T... args) + + + T + native_handle + cpp/thread/thread/native_handle + + (T... args) + + + T + ~thread + cpp/thread/thread/~thread + + (T... args) + + + T + swap + cpp/thread/thread/swap + + (T... args) + + + T + hardware_concurrency + cpp/thread/thread/hardware_concurrency + + (T... args) + + std::thread::id + + T + thread + cpp/thread/thread/thread + + (T... args) + + + T + join + cpp/thread/thread/join + + (T... args) + + + T + detach + cpp/thread/thread/detach + + (T... args) + + + T + get_id + cpp/thread/thread/get_id + + (T... args) + + + + std::thread::id + cpp/thread/thread/id + + T + operator!= + cpp/thread/thread/id/operator_cmp + + (T... args) + + + T + operator>= + cpp/thread/thread/id/operator_cmp + + (T... args) + + + T + operator<= + cpp/thread/thread/id/operator_cmp + + (T... args) + + + T + operator< + cpp/thread/thread/id/operator_cmp + + (T... args) + + + T + operator== + cpp/thread/thread/id/operator_cmp + + (T... args) + + + T + operator<< + cpp/thread/thread/id/operator_ltlt + + (T... args) + + + T + id + cpp/thread/thread/id/id + + (T... args) + + + T + operator> + cpp/thread/thread/id/operator_cmp + + (T... args) + + + + std::future_error + cpp/thread/future_error + + T + code + cpp/thread/future_error/code + + (T... args) + + + T + future_error + cpp/thread/future_error/future_error + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::time_base + cpp/locale/time_base + + + std::alignment_of + cpp/types/alignment_of + + + std::time_put + cpp/locale/time_put + std::time_put::char_type + std::time_put::iter_type + + T + do_put + cpp/locale/time_put/put + + (T... args) + + + T + ~time_put + cpp/locale/time_put/~time_put + + (T... args) + + + T + put + cpp/locale/time_put/put + + (T... args) + + + T + time_put + cpp/locale/time_put/time_put + + (T... args) + + + + std::time_put::char_type + cpp/locale/time_put + + + std::time_put::iter_type + cpp/locale/time_put + + + std::bit_or + cpp/utility/functional/bit_or + + T + operator() + cpp/utility/functional/bit_or + + (T... args) + + + + std::pointer_traits + cpp/memory/pointer_traits + + T + pointer_to + cpp/memory/pointer_traits/pointer_to + + (T... args) + + + + std::basic_string + cpp/string/basic_string + + T + push_back + cpp/string/basic_string/push_back + + (T... args) + + + T + shrink_to_fit + cpp/string/basic_string/shrink_to_fit + + (T... args) + + + T + rfind + cpp/string/basic_string/rfind + + (T... args) + + + T + begin + cpp/string/basic_string/begin + + (T... args) + + + T + erase + cpp/string/basic_string/erase + + (T... args) + + + T + append + cpp/string/basic_string/append + + (T... args) + + + T + data + cpp/string/basic_string/data + + (T... args) + + + T + insert + cpp/string/basic_string/insert + + (T... args) + + + T + assign + cpp/string/basic_string/assign + + (T... args) + + + T + find_first_not_of + cpp/string/basic_string/find_first_not_of + + (T... args) + + + T + back + cpp/string/basic_string/back + + (T... args) + + + T + end + cpp/string/basic_string/end + + (T... args) + + + T + resize + cpp/string/basic_string/resize + + (T... args) + + + T + copy + cpp/string/basic_string/copy + + (T... args) + + + T + find_last_of + cpp/string/basic_string/find_last_of + + (T... args) + + + T + pop_back + cpp/string/basic_string/pop_back + + (T... args) + + + T + cbegin + cpp/string/basic_string/begin + + (T... args) + + + T + replace + cpp/string/basic_string/replace + + (T... args) + + + T + front + cpp/string/basic_string/front + + (T... args) + + + T + find + cpp/string/basic_string/find + + (T... args) + + + T + compare + cpp/string/basic_string/compare + + (T... args) + + + T + crbegin + cpp/string/basic_string/rbegin + + (T... args) + + + T + at + cpp/string/basic_string/at + + (T... args) + + + T + find_first_of + cpp/string/basic_string/find_first_of + + (T... args) + + + T + rbegin + cpp/string/basic_string/rbegin + + (T... args) + + + T + crend + cpp/string/basic_string/rend + + (T... args) + + + T + size + cpp/string/basic_string/size + + (T... args) + + + T + operator= + cpp/string/basic_string/operator= + + (T... args) + + + T + find_last_not_of + cpp/string/basic_string/find_last_not_of + + (T... args) + + + T + reserve + cpp/string/basic_string/reserve + + (T... args) + + + T + capacity + cpp/string/basic_string/capacity + + (T... args) + + + T + c_str + cpp/string/basic_string/c_str + + (T... args) + + + T + empty + cpp/string/basic_string/empty + + (T... args) + + + T + cend + cpp/string/basic_string/end + + (T... args) + + + T + substr + cpp/string/basic_string/substr + + (T... args) + + + T + max_size + cpp/string/basic_string/max_size + + (T... args) + + + T + rend + cpp/string/basic_string/rend + + (T... args) + + + T + get_allocator + cpp/string/basic_string/get_allocator + + (T... args) + + + T + clear + cpp/string/basic_string/clear + + (T... args) + + + T + swap + cpp/string/basic_string/swap + + (T... args) + + + T + operator[] + cpp/string/basic_string/operator_at + + (T... args) + + + T + length + cpp/string/basic_string/size + + (T... args) + + + T + basic_string + cpp/string/basic_string/basic_string + + (T... args) + + + + std::priority_queue + cpp/container/priority_queue + + T + empty + cpp/container/priority_queue/empty + + (T... args) + + + T + swap + cpp/container/priority_queue/swap + + (T... args) + + + T + priority_queue + cpp/container/priority_queue/priority_queue + + (T... args) + + + T + size + cpp/container/priority_queue/size + + (T... args) + + + T + operator= + cpp/container/priority_queue/operator= + + (T... args) + + + T + pop + cpp/container/priority_queue/pop + + (T... args) + + + T + emplace + cpp/container/priority_queue/emplace + + (T... args) + + + T + push + cpp/container/priority_queue/push + + (T... args) + + + T + top + cpp/container/priority_queue/top + + (T... args) + + + T + ~priority_queue + cpp/container/priority_queue/~priority_queue + + (T... args) + + + + std::exa + cpp/numeric/ratio/ratio + + + std::wostringstream + cpp/io/basic_ostringstream + + T + seekp + cpp/io/basic_ostream/seekp + + (T... args) + + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + str + cpp/io/basic_ostringstream/str + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + std::wostringstream::event_callback + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + tellp + cpp/io/basic_ostream/tellp + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + operator<< + cpp/io/basic_ostream/operator_ltlt + + (T... args) + + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + wostringstream + cpp/io/basic_ostringstream/basic_ostringstream + + (T... args) + + + T + write + cpp/io/basic_ostream/write + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + std::wostringstream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + flush + cpp/io/basic_ostream/flush + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + operator= + cpp/io/basic_ostringstream/operator= + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + std::wostringstream::sentry + + T + put + cpp/io/basic_ostream/put + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::wostringstream::event_callback + cpp/io/ios_base/event_callback + + + std::wostringstream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::wostringstream::sentry + cpp/io/basic_ostream/sentry + + T + ~sentry + cpp/io/basic_ostream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_ostream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_ostream/sentry + + (T... args) + + + + std::is_default_constructible + cpp/types/is_default_constructible + + + std::cregex_iterator + cpp/regex/regex_iterator + + T + operator!= + cpp/regex/regex_iterator/operator_cmp + + (T... args) + + + T + operator= + cpp/regex/regex_iterator/operator= + + (T... args) + + + T + cregex_iterator + cpp/regex/regex_iterator/regex_iterator + + (T... args) + + + T + operator-> + cpp/regex/regex_iterator/operator* + + (T... args) + + + T + operator++ + cpp/regex/regex_iterator/operator_arith + + (T... args) + + + T + operator== + cpp/regex/regex_iterator/operator_cmp + + (T... args) + + + T + operator* + cpp/regex/regex_iterator/operator* + + (T... args) + + + T + operator++(int) + cpp/regex/regex_iterator/operator_arith + + (T... args) + + + + std::wstring + cpp/string/basic_string + + T + push_back + cpp/string/basic_string/push_back + + (T... args) + + + T + shrink_to_fit + cpp/string/basic_string/shrink_to_fit + + (T... args) + + + T + rfind + cpp/string/basic_string/rfind + + (T... args) + + + T + begin + cpp/string/basic_string/begin + + (T... args) + + + T + erase + cpp/string/basic_string/erase + + (T... args) + + + T + append + cpp/string/basic_string/append + + (T... args) + + + T + data + cpp/string/basic_string/data + + (T... args) + + + T + insert + cpp/string/basic_string/insert + + (T... args) + + + T + assign + cpp/string/basic_string/assign + + (T... args) + + + T + find_first_not_of + cpp/string/basic_string/find_first_not_of + + (T... args) + + + T + back + cpp/string/basic_string/back + + (T... args) + + + T + end + cpp/string/basic_string/end + + (T... args) + + + T + resize + cpp/string/basic_string/resize + + (T... args) + + + T + copy + cpp/string/basic_string/copy + + (T... args) + + + T + find_last_of + cpp/string/basic_string/find_last_of + + (T... args) + + + T + pop_back + cpp/string/basic_string/pop_back + + (T... args) + + + T + replace + cpp/string/basic_string/replace + + (T... args) + + + T + wstring + cpp/string/basic_string/basic_string + + (T... args) + + + T + front + cpp/string/basic_string/front + + (T... args) + + + T + find + cpp/string/basic_string/find + + (T... args) + + + T + compare + cpp/string/basic_string/compare + + (T... args) + + + T + crbegin + cpp/string/basic_string/rbegin + + (T... args) + + + T + cbegin + cpp/string/basic_string/begin + + (T... args) + + + T + find_first_of + cpp/string/basic_string/find_first_of + + (T... args) + + + T + rbegin + cpp/string/basic_string/rbegin + + (T... args) + + + T + crend + cpp/string/basic_string/rend + + (T... args) + + + T + size + cpp/string/basic_string/size + + (T... args) + + + T + operator= + cpp/string/basic_string/operator= + + (T... args) + + + T + find_last_not_of + cpp/string/basic_string/find_last_not_of + + (T... args) + + + T + reserve + cpp/string/basic_string/reserve + + (T... args) + + + T + capacity + cpp/string/basic_string/capacity + + (T... args) + + + T + c_str + cpp/string/basic_string/c_str + + (T... args) + + + T + empty + cpp/string/basic_string/empty + + (T... args) + + + T + cend + cpp/string/basic_string/end + + (T... args) + + + T + substr + cpp/string/basic_string/substr + + (T... args) + + + T + max_size + cpp/string/basic_string/max_size + + (T... args) + + + T + rend + cpp/string/basic_string/rend + + (T... args) + + + T + get_allocator + cpp/string/basic_string/get_allocator + + (T... args) + + + T + clear + cpp/string/basic_string/clear + + (T... args) + + + T + at + cpp/string/basic_string/at + + (T... args) + + + T + swap + cpp/string/basic_string/swap + + (T... args) + + + T + operator[] + cpp/string/basic_string/operator_at + + (T... args) + + + T + length + cpp/string/basic_string/size + + (T... args) + + + + std::remove_all_extents + cpp/types/remove_all_extents + + + std::istrstream + cpp/io/istrstream + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + ~istrstream + cpp/io/istrstream/~istrstream + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + str + cpp/io/istrstream/str + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + readsome + cpp/io/basic_istream/readsome + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + gcount + cpp/io/basic_istream/gcount + + (T... args) + + + T + get + cpp/io/basic_istream/get + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + read + cpp/io/basic_istream/read + + (T... args) + + + T + getline + cpp/io/basic_istream/getline + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + unget + cpp/io/basic_istream/unget + + (T... args) + + std::istrstream::event_callback + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + sync + cpp/io/basic_istream/sync + + (T... args) + + + T + putback + cpp/io/basic_istream/putback + + (T... args) + + + T + ignore + cpp/io/basic_istream/ignore + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + seekg + cpp/io/basic_istream/seekg + + (T... args) + + std::istrstream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + istrstream + cpp/io/istrstream/istrstream + + (T... args) + + + T + tellg + cpp/io/basic_istream/tellg + + (T... args) + + + T + operator>> + cpp/io/basic_istream/operator_gtgt + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + peek + cpp/io/basic_istream/peek + + (T... args) + + std::istrstream::sentry + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::istrstream::event_callback + cpp/io/ios_base/event_callback + + + std::istrstream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::istrstream::sentry + cpp/io/basic_istream/sentry + + T + ~sentry + cpp/io/basic_istream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_istream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_istream/sentry + + (T... args) + + + + std::unary_negate + cpp/utility/functional/unary_negate + + T + operator() + cpp/utility/functional/unary_negate + + (T... args) + + + T + unary_negate + cpp/utility/functional/unary_negate + + (T... args) + + + + std::unordered_multiset + cpp/container/unordered_multiset + + T + max_bucket_count + cpp/container/unordered_multiset/max_bucket_count + + (T... args) + + + T + cbegin + cpp/container/unordered_multiset/begin + + (T... args) + + + T + erase + cpp/container/unordered_multiset/erase + + (T... args) + + + T + insert + cpp/container/unordered_multiset/insert + + (T... args) + + + T + bucket_count + cpp/container/unordered_multiset/bucket_count + + (T... args) + + + T + max_load_factor + cpp/container/unordered_multiset/max_load_factor + + (T... args) + + + T + end + cpp/container/unordered_multiset/end + + (T... args) + + + T + emplace_hint + cpp/container/unordered_multiset/emplace_hint + + (T... args) + + + T + unordered_multiset + cpp/container/unordered_multiset/unordered_multiset + + (T... args) + + + T + end(int) + cpp/container/unordered_multiset/end2 + + (T... args) + + + T + key_eq + cpp/container/unordered_multiset/key_eq + + (T... args) + + + T + hash_function + cpp/container/unordered_multiset/hash_function + + (T... args) + + + T + equal_range + cpp/container/unordered_multiset/equal_range + + (T... args) + + + T + begin + cpp/container/unordered_multiset/begin + + (T... args) + + + T + cbegin(int) + cpp/container/unordered_multiset/begin2 + + (T... args) + + + T + swap + cpp/container/unordered_multiset/swap + + (T... args) + + + T + ~unordered_multiset + cpp/container/unordered_multiset/~unordered_multiset + + (T... args) + + + T + load_factor + cpp/container/unordered_multiset/load_factor + + (T... args) + + + T + size + cpp/container/unordered_multiset/size + + (T... args) + + + T + operator= + cpp/container/unordered_multiset/operator= + + (T... args) + + + T + cend + cpp/container/unordered_multiset/end + + (T... args) + + + T + reserve + cpp/container/unordered_multiset/reserve + + (T... args) + + + T + rehash + cpp/container/unordered_multiset/rehash + + (T... args) + + + T + bucket + cpp/container/unordered_multiset/bucket + + (T... args) + + + T + find + cpp/container/unordered_multiset/find + + (T... args) + + + T + empty + cpp/container/unordered_multiset/empty + + (T... args) + + + T + get_allocator + cpp/container/unordered_multiset/get_allocator + + (T... args) + + + T + max_size + cpp/container/unordered_multiset/max_size + + (T... args) + + + T + cend(int) + cpp/container/unordered_multiset/end2 + + (T... args) + + + T + count + cpp/container/unordered_multiset/count + + (T... args) + + + T + clear + cpp/container/unordered_multiset/clear + + (T... args) + + + T + begin(int) + cpp/container/unordered_multiset/begin2 + + (T... args) + + + T + emplace + cpp/container/unordered_multiset/emplace + + (T... args) + + + T + bucket_size + cpp/container/unordered_multiset/bucket_size + + (T... args) + + + + std::basic_ostream + cpp/io/basic_ostream + + T + seekp + cpp/io/basic_ostream/seekp + + (T... args) + + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + std::basic_ostream::event_callback + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + tellp + cpp/io/basic_ostream/tellp + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + operator<< + cpp/io/basic_ostream/operator_ltlt + + (T... args) + + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + write + cpp/io/basic_ostream/write + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + std::basic_ostream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + flush + cpp/io/basic_ostream/flush + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + basic_ostream + cpp/io/basic_ostream/basic_ostream + + (T... args) + + + T + ~basic_ostream + cpp/io/basic_ostream/~basic_ostream + + (T... args) + + std::basic_ostream::sentry + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + + T + put + cpp/io/basic_ostream/put + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::basic_ostream::event_callback + cpp/io/ios_base/event_callback + + + std::basic_ostream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::basic_ostream::sentry + cpp/io/basic_ostream/sentry + + T + ~sentry + cpp/io/basic_ostream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_ostream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_ostream/sentry + + (T... args) + + + + std::wsregex_iterator + cpp/regex/regex_iterator + + T + wsregex_iterator + cpp/regex/regex_iterator/regex_iterator + + (T... args) + + + T + operator= + cpp/regex/regex_iterator/operator= + + (T... args) + + + T + operator== + cpp/regex/regex_iterator/operator_cmp + + (T... args) + + + T + operator-> + cpp/regex/regex_iterator/operator* + + (T... args) + + + T + operator++ + cpp/regex/regex_iterator/operator_arith + + (T... args) + + + T + operator* + cpp/regex/regex_iterator/operator* + + (T... args) + + + T + operator!= + cpp/regex/regex_iterator/operator_cmp + + (T... args) + + + T + operator++(int) + cpp/regex/regex_iterator/operator_arith + + (T... args) + + + + std::uint_fast16_t + cpp/types/integer + + + std::is_nothrow_assignable + cpp/types/is_assignable + + + std::moneypunct + cpp/locale/moneypunct + + T + do_curr_symbol + cpp/locale/moneypunct/curr_symbol + + (T... args) + + + T + do_decimal_point + cpp/locale/moneypunct/decimal_point + + (T... args) + + + T + thousands_sep + cpp/locale/moneypunct/thousands_sep + + (T... args) + + + T + do_pos_format + cpp/locale/moneypunct/pos_format + + (T... args) + + + T + curr_symbol + cpp/locale/moneypunct/curr_symbol + + (T... args) + + + T + positive_sign + cpp/locale/moneypunct/positive_sign + + (T... args) + + + T + frac_digits + cpp/locale/moneypunct/frac_digits + + (T... args) + + + T + do_negative_sign + cpp/locale/moneypunct/positive_sign + + (T... args) + + + T + ~moneypunct + cpp/locale/moneypunct/~moneypunct + + (T... args) + + + T + pos_format + cpp/locale/moneypunct/pos_format + + (T... args) + + + T + do_thousands_sep + cpp/locale/moneypunct/thousands_sep + + (T... args) + + + T + neg_format + cpp/locale/moneypunct/pos_format + + (T... args) + + + T + negative_sign + cpp/locale/moneypunct/positive_sign + + (T... args) + + + T + grouping + cpp/locale/moneypunct/grouping + + (T... args) + + + T + do_frac_digits + cpp/locale/moneypunct/frac_digits + + (T... args) + + + T + decimal_point + cpp/locale/moneypunct/decimal_point + + (T... args) + + + T + do_neg_format + cpp/locale/moneypunct/pos_format + + (T... args) + + std::moneypunct::string_type + std::moneypunct::pattern + + T + do_positive_sign + cpp/locale/moneypunct/positive_sign + + (T... args) + + std::moneypunct::char_type + + T + moneypunct + cpp/locale/moneypunct/moneypunct + + (T... args) + + + T + do_grouping + cpp/locale/moneypunct/grouping + + (T... args) + + + + std::moneypunct::string_type + cpp/locale/moneypunct + + + std::moneypunct::pattern + cpp/locale/money_base + + + std::moneypunct::char_type + cpp/locale/moneypunct + + + std::type_index + cpp/types/type_index + + T + operator!= + cpp/types/type_index/operator_cmp + + (T... args) + + + T + hash_code + cpp/types/type_index/hash_code + + (T... args) + + + T + operator<= + cpp/types/type_index/operator_cmp + + (T... args) + + + T + operator< + cpp/types/type_index/operator_cmp + + (T... args) + + + T + operator== + cpp/types/type_index/operator_cmp + + (T... args) + + + T + operator>= + cpp/types/type_index/operator_cmp + + (T... args) + + + T + type_index + cpp/types/type_index/type_index + + (T... args) + + + T + name + cpp/types/type_index/name + + (T... args) + + + T + operator> + cpp/types/type_index/operator_cmp + + (T... args) + + + + std::is_standard_layout + cpp/types/is_standard_layout + + + std::timed_mutex + cpp/thread/timed_mutex + + T + unlock + cpp/thread/timed_mutex/unlock + + (T... args) + + + T + native_handle + cpp/thread/timed_mutex/native_handle + + (T... args) + + + T + try_lock_until + cpp/thread/timed_mutex/try_lock_until + + (T... args) + + + T + try_lock_for + cpp/thread/timed_mutex/try_lock_for + + (T... args) + + + T + lock + cpp/thread/timed_mutex/lock + + (T... args) + + + T + try_lock + cpp/thread/timed_mutex/try_lock + + (T... args) + + + T + timed_mutex + cpp/thread/timed_mutex/timed_mutex + + (T... args) + + + + std::bad_exception + cpp/error/bad_exception + + + std::int_fast64_t + cpp/types/integer + + + std::function + cpp/utility/functional/function + + T + operator= + cpp/utility/functional/function/operator= + + (T... args) + + + T + swap + cpp/utility/functional/function/swap + + (T... args) + + + T + assign + cpp/utility/functional/function/assign + + (T... args) + + + T + target + cpp/utility/functional/function/target + + (T... args) + + + T + operator() + cpp/utility/functional/function/operator() + + (T... args) + + + T + target_type + cpp/utility/functional/function/target_type + + (T... args) + + + T + function + cpp/utility/functional/function/function + + (T... args) + + + T + operator bool + cpp/utility/functional/function/operator_bool + + (T... args) + + + T + ~function + cpp/utility/functional/function/~function + + (T... args) + + + + std::bad_cast + cpp/types/bad_cast + + T + bad_cast + cpp/types/bad_cast/bad_cast + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::error_condition + cpp/error/error_condition + + T + error_condition + cpp/error/error_condition/error_condition + + (T... args) + + + T + operator= + cpp/error/error_condition/operator= + + (T... args) + + + T + operator bool + cpp/error/error_condition/operator_bool + + (T... args) + + + T + assign + cpp/error/error_condition/assign + + (T... args) + + + T + value + cpp/error/error_condition/value + + (T... args) + + + T + clear + cpp/error/error_condition/clear + + (T... args) + + + T + message + cpp/error/error_condition/message + + (T... args) + + + T + category + cpp/error/error_condition/category + + (T... args) + + + + std::filebuf + cpp/io/basic_filebuf + + T + eback + cpp/io/basic_streambuf/gptr + + (T... args) + + + T + setp + cpp/io/basic_streambuf/setp + + (T... args) + + + T + pbackfail + cpp/io/basic_streambuf/pbackfail + + (T... args) + + + T + seekoff + cpp/io/basic_streambuf/pubseekoff + + (T... args) + + + T + pbase + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + egptr + cpp/io/basic_streambuf/gptr + + (T... args) + + + T + underflow + cpp/io/basic_streambuf/underflow + + (T... args) + + + T + setbuf + cpp/io/basic_streambuf/pubsetbuf + + (T... args) + + + T + gbump + cpp/io/basic_streambuf/gbump + + (T... args) + + + T + xsgetn + cpp/io/basic_streambuf/sgetn + + (T... args) + + + T + is_open + cpp/io/basic_filebuf/is_open + + (T... args) + + + T + sputn + cpp/io/basic_streambuf/sputn + + (T... args) + + + T + pptr + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + seekpos + cpp/io/basic_streambuf/pubseekpos + + (T... args) + + + T + pubsync + cpp/io/basic_streambuf/pubsync + + (T... args) + + + T + pubseekoff + cpp/io/basic_streambuf/pubseekoff + + (T... args) + + + T + filebuf + cpp/io/basic_filebuf/basic_filebuf + + (T... args) + + + T + pbump + cpp/io/basic_streambuf/pbump + + (T... args) + + + T + pubseekpos + cpp/io/basic_streambuf/pubseekpos + + (T... args) + + + T + sputbackc + cpp/io/basic_streambuf/sputbackc + + (T... args) + + + T + in_avail + cpp/io/basic_streambuf/in_avail + + (T... args) + + + T + getloc + cpp/io/basic_streambuf/getloc + + (T... args) + + + T + sungetc + cpp/io/basic_streambuf/sungetc + + (T... args) + + + T + epptr + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + close + cpp/io/basic_filebuf/close + + (T... args) + + + T + sync + cpp/io/basic_streambuf/pubsync + + (T... args) + + + T + xsputn + cpp/io/basic_streambuf/sputn + + (T... args) + + + T + setg + cpp/io/basic_streambuf/setg + + (T... args) + + + T + pubimbue + cpp/io/basic_streambuf/pubimbue + + (T... args) + + + T + showmanyc + cpp/io/basic_streambuf/showmanyc + + (T... args) + + + T + open + cpp/io/basic_filebuf/open + + (T... args) + + + T + sgetc + cpp/io/basic_streambuf/sgetc + + (T... args) + + + T + swap + cpp/io/basic_streambuf/swap + + (T... args) + + + T + sputc + cpp/io/basic_streambuf/sputc + + (T... args) + + + T + overflow + cpp/io/basic_streambuf/overflow + + (T... args) + + + T + uflow + cpp/io/basic_streambuf/uflow + + (T... args) + + + T + sgetn + cpp/io/basic_streambuf/sgetn + + (T... args) + + + T + sbumpc + cpp/io/basic_streambuf/sbumpc + + (T... args) + + + T + ~filebuf + cpp/io/basic_filebuf/~basic_filebuf + + (T... args) + + + T + operator= + cpp/io/basic_filebuf/operator= + + (T... args) + + + T + pubsetbuf + cpp/io/basic_streambuf/pubsetbuf + + (T... args) + + + T + imbue + cpp/io/basic_streambuf/pubimbue + + (T... args) + + + T + snextc + cpp/io/basic_streambuf/snextc + + (T... args) + + + T + gptr + cpp/io/basic_streambuf/gptr + + (T... args) + + + + std::int_least16_t + cpp/types/integer + + + std::istreambuf_iterator + cpp/iterator/istreambuf_iterator + + + std::u16string + cpp/string/basic_string + + T + push_back + cpp/string/basic_string/push_back + + (T... args) + + + T + shrink_to_fit + cpp/string/basic_string/shrink_to_fit + + (T... args) + + + T + rfind + cpp/string/basic_string/rfind + + (T... args) + + + T + begin + cpp/string/basic_string/begin + + (T... args) + + + T + erase + cpp/string/basic_string/erase + + (T... args) + + + T + append + cpp/string/basic_string/append + + (T... args) + + + T + data + cpp/string/basic_string/data + + (T... args) + + + T + insert + cpp/string/basic_string/insert + + (T... args) + + + T + assign + cpp/string/basic_string/assign + + (T... args) + + + T + find_first_not_of + cpp/string/basic_string/find_first_not_of + + (T... args) + + + T + back + cpp/string/basic_string/back + + (T... args) + + + T + end + cpp/string/basic_string/end + + (T... args) + + + T + resize + cpp/string/basic_string/resize + + (T... args) + + + T + copy + cpp/string/basic_string/copy + + (T... args) + + + T + find_last_of + cpp/string/basic_string/find_last_of + + (T... args) + + + T + pop_back + cpp/string/basic_string/pop_back + + (T... args) + + + T + replace + cpp/string/basic_string/replace + + (T... args) + + + T + front + cpp/string/basic_string/front + + (T... args) + + + T + substr + cpp/string/basic_string/substr + + (T... args) + + + T + find + cpp/string/basic_string/find + + (T... args) + + + T + compare + cpp/string/basic_string/compare + + (T... args) + + + T + crbegin + cpp/string/basic_string/rbegin + + (T... args) + + + T + cbegin + cpp/string/basic_string/begin + + (T... args) + + + T + find_first_of + cpp/string/basic_string/find_first_of + + (T... args) + + + T + rbegin + cpp/string/basic_string/rbegin + + (T... args) + + + T + crend + cpp/string/basic_string/rend + + (T... args) + + + T + size + cpp/string/basic_string/size + + (T... args) + + + T + operator= + cpp/string/basic_string/operator= + + (T... args) + + + T + find_last_not_of + cpp/string/basic_string/find_last_not_of + + (T... args) + + + T + reserve + cpp/string/basic_string/reserve + + (T... args) + + + T + capacity + cpp/string/basic_string/capacity + + (T... args) + + + T + c_str + cpp/string/basic_string/c_str + + (T... args) + + + T + empty + cpp/string/basic_string/empty + + (T... args) + + + T + cend + cpp/string/basic_string/end + + (T... args) + + + T + u16string + cpp/string/basic_string/basic_string + + (T... args) + + + T + max_size + cpp/string/basic_string/max_size + + (T... args) + + + T + rend + cpp/string/basic_string/rend + + (T... args) + + + T + get_allocator + cpp/string/basic_string/get_allocator + + (T... args) + + + T + clear + cpp/string/basic_string/clear + + (T... args) + + + T + at + cpp/string/basic_string/at + + (T... args) + + + T + swap + cpp/string/basic_string/swap + + (T... args) + + + T + operator[] + cpp/string/basic_string/operator_at + + (T... args) + + + T + length + cpp/string/basic_string/size + + (T... args) + + + + std::is_error_condition_enum + cpp/error/error_condition/is_error_condition_enum + + + std::is_nothrow_destructible + cpp/types/is_destructible + + + std::wiostream + cpp/io/basic_iostream + + T + seekp + cpp/io/basic_ostream/seekp + + (T... args) + + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + operator>> + cpp/io/basic_istream/operator_gtgt + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + + T + seekg + cpp/io/basic_istream/seekg + + (T... args) + + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + tellp + cpp/io/basic_ostream/tellp + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + gcount + cpp/io/basic_istream/gcount + + (T... args) + + + T + unget + cpp/io/basic_istream/unget + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + read + cpp/io/basic_istream/read + + (T... args) + + + T + getline + cpp/io/basic_istream/getline + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + std::wiostream::sentry + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + operator<< + cpp/io/basic_ostream/operator_ltlt + + (T... args) + + std::wiostream::event_callback + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + wiostream + cpp/io/basic_iostream/basic_iostream + + (T... args) + + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + write + cpp/io/basic_ostream/write + + (T... args) + + + T + sync + cpp/io/basic_istream/sync + + (T... args) + + + T + putback + cpp/io/basic_istream/putback + + (T... args) + + + T + ignore + cpp/io/basic_istream/ignore + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + readsome + cpp/io/basic_istream/readsome + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + std::wiostream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + get + cpp/io/basic_istream/get + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + ~wiostream + cpp/io/basic_iostream/~basic_iostream + + (T... args) + + + T + flush + cpp/io/basic_ostream/flush + + (T... args) + + + T + tellg + cpp/io/basic_istream/tellg + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + peek + cpp/io/basic_istream/peek + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + + T + put + cpp/io/basic_ostream/put + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::wiostream::sentry + cpp/io/basic_ostream/sentry + + T + ~sentry + cpp/io/basic_istream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_istream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_istream/sentry + + (T... args) + + + + std::wiostream::event_callback + cpp/io/ios_base/event_callback + + + std::wiostream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::allocator_arg_t + cpp/memory/allocator_arg_t + + + std::rel_ops + + + T + operator!= + cpp/utility/rel_ops/operator_cmp + + (T... args) + + + T + operator>= + cpp/utility/rel_ops/operator_cmp + + (T... args) + + + T + operator<= + cpp/utility/rel_ops/operator_cmp + + (T... args) + + + T + operator> + cpp/utility/rel_ops/operator_cmp + + (T... args) + + + + std::uint_least32_t + cpp/types/integer + + + std::collate + cpp/locale/collate + + T + hash + cpp/locale/collate/hash + + (T... args) + + + T + do_hash + cpp/locale/collate/hash + + (T... args) + + + T + collate + cpp/locale/collate/collate + + (T... args) + + std::collate::char_type + + T + ~collate + cpp/locale/collate/~collate + + (T... args) + + + T + do_transform + cpp/locale/collate/transform + + (T... args) + + + T + transform + cpp/locale/collate/transform + + (T... args) + + + T + do_compare + cpp/locale/collate/compare + + (T... args) + + std::collate::string_type + + T + compare + cpp/locale/collate/compare + + (T... args) + + + + std::collate::char_type + cpp/locale/collate + + + std::collate::string_type + cpp/locale/collate + + + std::remove_const + cpp/types/remove_cv + + + std::u32string + cpp/string/basic_string + + T + push_back + cpp/string/basic_string/push_back + + (T... args) + + + T + shrink_to_fit + cpp/string/basic_string/shrink_to_fit + + (T... args) + + + T + rfind + cpp/string/basic_string/rfind + + (T... args) + + + T + begin + cpp/string/basic_string/begin + + (T... args) + + + T + erase + cpp/string/basic_string/erase + + (T... args) + + + T + append + cpp/string/basic_string/append + + (T... args) + + + T + data + cpp/string/basic_string/data + + (T... args) + + + T + insert + cpp/string/basic_string/insert + + (T... args) + + + T + u32string + cpp/string/basic_string/basic_string + + (T... args) + + + T + find_first_not_of + cpp/string/basic_string/find_first_not_of + + (T... args) + + + T + back + cpp/string/basic_string/back + + (T... args) + + + T + end + cpp/string/basic_string/end + + (T... args) + + + T + resize + cpp/string/basic_string/resize + + (T... args) + + + T + copy + cpp/string/basic_string/copy + + (T... args) + + + T + find_last_of + cpp/string/basic_string/find_last_of + + (T... args) + + + T + pop_back + cpp/string/basic_string/pop_back + + (T... args) + + + T + cbegin + cpp/string/basic_string/begin + + (T... args) + + + T + replace + cpp/string/basic_string/replace + + (T... args) + + + T + front + cpp/string/basic_string/front + + (T... args) + + + T + find + cpp/string/basic_string/find + + (T... args) + + + T + compare + cpp/string/basic_string/compare + + (T... args) + + + T + crbegin + cpp/string/basic_string/rbegin + + (T... args) + + + T + size + cpp/string/basic_string/size + + (T... args) + + + T + find_first_of + cpp/string/basic_string/find_first_of + + (T... args) + + + T + rbegin + cpp/string/basic_string/rbegin + + (T... args) + + + T + crend + cpp/string/basic_string/rend + + (T... args) + + + T + assign + cpp/string/basic_string/assign + + (T... args) + + + T + operator= + cpp/string/basic_string/operator= + + (T... args) + + + T + find_last_not_of + cpp/string/basic_string/find_last_not_of + + (T... args) + + + T + reserve + cpp/string/basic_string/reserve + + (T... args) + + + T + capacity + cpp/string/basic_string/capacity + + (T... args) + + + T + c_str + cpp/string/basic_string/c_str + + (T... args) + + + T + empty + cpp/string/basic_string/empty + + (T... args) + + + T + cend + cpp/string/basic_string/end + + (T... args) + + + T + substr + cpp/string/basic_string/substr + + (T... args) + + + T + max_size + cpp/string/basic_string/max_size + + (T... args) + + + T + rend + cpp/string/basic_string/rend + + (T... args) + + + T + get_allocator + cpp/string/basic_string/get_allocator + + (T... args) + + + T + clear + cpp/string/basic_string/clear + + (T... args) + + + T + at + cpp/string/basic_string/at + + (T... args) + + + T + swap + cpp/string/basic_string/swap + + (T... args) + + + T + operator[] + cpp/string/basic_string/operator_at + + (T... args) + + + T + length + cpp/string/basic_string/size + + (T... args) + + + + std::uint_fast32_t + cpp/types/integer + + + std::is_lvalue_reference + cpp/types/is_lvalue_reference + + + std::complex + cpp/numeric/complex + + T + operator= + cpp/numeric/complex/operator= + + (T... args) + + + T + complex + cpp/numeric/complex/complex + + (T... args) + + + T + operator-= + cpp/numeric/complex/operator_arith + + (T... args) + + + T + imag + cpp/numeric/complex/imag + + (T... args) + + + T + operator+= + cpp/numeric/complex/operator_arith + + (T... args) + + + T + operator/= + cpp/numeric/complex/operator_arith + + (T... args) + + + T + operator*= + cpp/numeric/complex/operator_arith + + (T... args) + + + T + real + cpp/numeric/complex/real + + (T... args) + + + + std::ofstream + cpp/io/basic_ofstream + + T + seekp + cpp/io/basic_ostream/seekp + + (T... args) + + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + std::ofstream::event_callback + + T + open + cpp/io/basic_ofstream/open + + (T... args) + + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + tellp + cpp/io/basic_ostream/tellp + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + operator<< + cpp/io/basic_ostream/operator_ltlt + + (T... args) + + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + close + cpp/io/basic_ofstream/close + + (T... args) + + + T + write + cpp/io/basic_ostream/write + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + std::ofstream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + flush + cpp/io/basic_ostream/flush + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + is_open + cpp/io/basic_ofstream/is_open + + (T... args) + + + T + operator= + cpp/io/basic_ofstream/operator= + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + std::ofstream::sentry + + T + put + cpp/io/basic_ostream/put + + (T... args) + + + T + ofstream + cpp/io/basic_ofstream/basic_ofstream + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::ofstream::event_callback + cpp/io/ios_base/event_callback + + + std::ofstream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::ofstream::sentry + cpp/io/basic_ostream/sentry + + T + ~sentry + cpp/io/basic_ostream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_ostream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_ostream/sentry + + (T... args) + + + + std::insert_iterator + cpp/iterator/insert_iterator + + + std::bad_array_length + cpp/memory/new/bad_array_length + + T + bad_array_length + cpp/memory/new/bad_array_length + + (T... args) + + + T + what + cpp/memory/new/bad_alloc + + (T... args) + + + + std::this_thread + + + T + yield + cpp/thread/yield + + (T... args) + + + T + sleep_for + cpp/thread/sleep_for + + (T... args) + + + T + sleep_until + cpp/thread/sleep_until + + (T... args) + + + T + get_id + cpp/thread/get_id + + (T... args) + + + + std::is_trivially_copyable + cpp/types/is_trivially_copyable + + + std::basic_istringstream + cpp/io/basic_istringstream + + T + basic_istringstream + cpp/io/basic_istringstream/basic_istringstream + + (T... args) + + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + str + cpp/io/basic_istringstream/str + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + readsome + cpp/io/basic_istream/readsome + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + gcount + cpp/io/basic_istream/gcount + + (T... args) + + + T + get + cpp/io/basic_istream/get + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + read + cpp/io/basic_istream/read + + (T... args) + + + T + getline + cpp/io/basic_istream/getline + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + unget + cpp/io/basic_istream/unget + + (T... args) + + std::basic_istringstream::event_callback + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + sync + cpp/io/basic_istream/sync + + (T... args) + + + T + putback + cpp/io/basic_istream/putback + + (T... args) + + + T + ignore + cpp/io/basic_istream/ignore + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + seekg + cpp/io/basic_istream/seekg + + (T... args) + + std::basic_istringstream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + tellg + cpp/io/basic_istream/tellg + + (T... args) + + + T + operator>> + cpp/io/basic_istream/operator_gtgt + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + peek + cpp/io/basic_istream/peek + + (T... args) + + + T + operator= + cpp/io/basic_istringstream/operator= + + (T... args) + + std::basic_istringstream::sentry + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::basic_istringstream::event_callback + cpp/io/ios_base/event_callback + + + std::basic_istringstream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::basic_istringstream::sentry + cpp/io/basic_istream/sentry + + T + ~sentry + cpp/io/basic_istream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_istream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_istream/sentry + + (T... args) + + + + std::basic_ifstream + cpp/io/basic_ifstream + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + basic_ifstream + cpp/io/basic_ifstream/basic_ifstream + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + readsome + cpp/io/basic_istream/readsome + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + + T + open + cpp/io/basic_ifstream/open + + (T... args) + + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + gcount + cpp/io/basic_istream/gcount + + (T... args) + + + T + get + cpp/io/basic_istream/get + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + read + cpp/io/basic_istream/read + + (T... args) + + + T + getline + cpp/io/basic_istream/getline + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + unget + cpp/io/basic_istream/unget + + (T... args) + + std::basic_ifstream::event_callback + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + close + cpp/io/basic_ifstream/close + + (T... args) + + + T + sync + cpp/io/basic_istream/sync + + (T... args) + + + T + putback + cpp/io/basic_istream/putback + + (T... args) + + + T + ignore + cpp/io/basic_istream/ignore + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + seekg + cpp/io/basic_istream/seekg + + (T... args) + + std::basic_ifstream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + tellg + cpp/io/basic_istream/tellg + + (T... args) + + + T + operator>> + cpp/io/basic_istream/operator_gtgt + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + is_open + cpp/io/basic_ifstream/is_open + + (T... args) + + + T + peek + cpp/io/basic_istream/peek + + (T... args) + + + T + operator= + cpp/io/basic_ifstream/operator= + + (T... args) + + std::basic_ifstream::sentry + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::basic_ifstream::event_callback + cpp/io/ios_base/event_callback + + + std::basic_ifstream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::basic_ifstream::sentry + cpp/io/basic_istream/sentry + + T + ~sentry + cpp/io/basic_istream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_istream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_istream/sentry + + (T... args) + + + + std::list + cpp/container/list + + T + pop_front + cpp/container/list/pop_front + + (T... args) + + + T + push_back + cpp/container/list/push_back + + (T... args) + + + T + splice + cpp/container/list/splice + + (T... args) + + + T + crbegin + cpp/container/list/rbegin + + (T... args) + + + T + erase + cpp/container/list/erase + + (T... args) + + + T + emplace_front + cpp/container/list/emplace_front + + (T... args) + + + T + insert + cpp/container/list/insert + + (T... args) + + + T + reverse + cpp/container/list/reverse + + (T... args) + + + T + back + cpp/container/list/back + + (T... args) + + + T + end + cpp/container/list/end + + (T... args) + + + T + remove + cpp/container/list/remove + + (T... args) + + + T + list + cpp/container/list/list + + (T... args) + + + T + emplace_back + cpp/container/list/emplace_back + + (T... args) + + + T + pop_back + cpp/container/list/pop_back + + (T... args) + + + T + cbegin + cpp/container/list/begin + + (T... args) + + + T + front + cpp/container/list/front + + (T... args) + + + T + unique + cpp/container/list/unique + + (T... args) + + + T + size + cpp/container/list/size + + (T... args) + + + T + resize + cpp/container/list/resize + + (T... args) + + + T + push_front + cpp/container/list/push_front + + (T... args) + + + T + rbegin + cpp/container/list/rbegin + + (T... args) + + + T + crend + cpp/container/list/rend + + (T... args) + + + T + assign + cpp/container/list/assign + + (T... args) + + + T + operator= + cpp/container/list/operator= + + (T... args) + + + T + sort + cpp/container/list/sort + + (T... args) + + + T + ~list + cpp/container/list/~list + + (T... args) + + + T + merge + cpp/container/list/merge + + (T... args) + + + T + empty + cpp/container/list/empty + + (T... args) + + + T + remove_if + cpp/container/list/remove + + (T... args) + + + T + cend + cpp/container/list/end + + (T... args) + + + T + swap + cpp/container/list/swap + + (T... args) + + + T + max_size + cpp/container/list/max_size + + (T... args) + + + T + rend + cpp/container/list/rend + + (T... args) + + + T + get_allocator + cpp/container/list/get_allocator + + (T... args) + + + T + clear + cpp/container/list/clear + + (T... args) + + + T + emplace + cpp/container/list/emplace + + (T... args) + + + T + begin + cpp/container/list/begin + + (T... args) + + + + std::minus + cpp/utility/functional/minus + + T + operator() + cpp/utility/functional/minus + + (T... args) + + + + std::map + cpp/container/map + + T + begin + cpp/container/map/begin + + (T... args) + + + T + erase + cpp/container/map/erase + + (T... args) + + + T + insert + cpp/container/map/insert + + (T... args) + + + T + swap + cpp/container/map/swap + + (T... args) + + + T + end + cpp/container/map/end + + (T... args) + + + T + emplace_hint + cpp/container/map/emplace_hint + + (T... args) + + + T + key_comp + cpp/container/map/key_comp + + (T... args) + + std::map::value_compare + + T + cbegin + cpp/container/map/begin + + (T... args) + + + T + count + cpp/container/map/count + + (T... args) + + + T + find + cpp/container/map/find + + (T... args) + + + T + map + cpp/container/map/map + + (T... args) + + + T + crbegin + cpp/container/map/rbegin + + (T... args) + + + T + at + cpp/container/map/at + + (T... args) + + + T + upper_bound + cpp/container/map/upper_bound + + (T... args) + + + T + rbegin + cpp/container/map/rbegin + + (T... args) + + + T + crend + cpp/container/map/rend + + (T... args) + + + T + size + cpp/container/map/size + + (T... args) + + + T + operator= + cpp/container/map/operator= + + (T... args) + + + T + ~map + cpp/container/map/~map + + (T... args) + + + T + value_comp + cpp/container/map/value_comp + + (T... args) + + + T + empty + cpp/container/map/empty + + (T... args) + + + T + lower_bound + cpp/container/map/lower_bound + + (T... args) + + + T + cend + cpp/container/map/end + + (T... args) + + + T + max_size + cpp/container/map/max_size + + (T... args) + + + T + rend + cpp/container/map/rend + + (T... args) + + + T + get_allocator + cpp/container/map/get_allocator + + (T... args) + + + T + clear + cpp/container/map/clear + + (T... args) + + + T + equal_range + cpp/container/map/equal_range + + (T... args) + + + T + emplace + cpp/container/map/emplace + + (T... args) + + + T + operator[] + cpp/container/map/operator_at + + (T... args) + + + + std::map::value_compare + cpp/container/map/value_compare + + + std::linear_congruential_engine + cpp/numeric/random/linear_congruential_engine + + T + discard + cpp/numeric/random/linear_congruential_engine/discard + + (T... args) + + + T + linear_congruential_engine + cpp/numeric/random/linear_congruential_engine/linear_congruential_engine + + (T... args) + + + T + max + cpp/numeric/random/linear_congruential_engine/max + + (T... args) + + + T + operator() + cpp/numeric/random/linear_congruential_engine/operator() + + (T... args) + + + T + seed + cpp/numeric/random/linear_congruential_engine/seed + + (T... args) + + + T + min + cpp/numeric/random/linear_congruential_engine/min + + (T... args) + + + + std::codecvt_utf16 + cpp/locale/codecvt_utf16 + std::codecvt_utf16::extern_type + + T + out + cpp/locale/codecvt/out + + (T... args) + + + T + do_length + cpp/locale/codecvt/length + + (T... args) + + + T + do_unshift + cpp/locale/codecvt/unshift + + (T... args) + + + T + do_encoding + cpp/locale/codecvt/encoding + + (T... args) + + + T + do_in + cpp/locale/codecvt/in + + (T... args) + + + T + unshift + cpp/locale/codecvt/unshift + + (T... args) + + + T + max_length + cpp/locale/codecvt/max_length + + (T... args) + + std::codecvt_utf16::state_type + + T + encoding + cpp/locale/codecvt/encoding + + (T... args) + + + T + always_noconv + cpp/locale/codecvt/always_noconv + + (T... args) + + + T + do_out + cpp/locale/codecvt/out + + (T... args) + + + T + do_max_length + cpp/locale/codecvt/max_length + + (T... args) + + + T + do_always_noconv + cpp/locale/codecvt/always_noconv + + (T... args) + + + T + in + cpp/locale/codecvt/in + + (T... args) + + std::codecvt_utf16::intern_type + + T + length + cpp/locale/codecvt/length + + (T... args) + + + + std::codecvt_utf16::extern_type + cpp/locale/codecvt + + + std::codecvt_utf16::state_type + cpp/locale/codecvt + + + std::codecvt_utf16::intern_type + cpp/locale/codecvt + + + std::cmatch + cpp/regex/match_results + + T + cbegin + cpp/regex/match_results/begin + + (T... args) + + + T + format + cpp/regex/match_results/format + + (T... args) + + + T + size + cpp/regex/match_results/size + + (T... args) + + + T + swap + cpp/regex/match_results/swap + + (T... args) + + + T + position + cpp/regex/match_results/position + + (T... args) + + + T + ~cmatch + cpp/regex/match_results/~match_results + + (T... args) + + + T + prefix + cpp/regex/match_results/prefix + + (T... args) + + + T + str + cpp/regex/match_results/str + + (T... args) + + + T + empty + cpp/regex/match_results/empty + + (T... args) + + + T + suffix + cpp/regex/match_results/suffix + + (T... args) + + + T + get_allocator + cpp/regex/match_results/get_allocator + + (T... args) + + + T + end + cpp/regex/match_results/end + + (T... args) + + + T + max_size + cpp/regex/match_results/max_size + + (T... args) + + + T + cmatch + cpp/regex/match_results/match_results + + (T... args) + + + T + ready + cpp/regex/match_results/ready + + (T... args) + + + T + cend + cpp/regex/match_results/end + + (T... args) + + + T + operator[] + cpp/regex/match_results/operator_at + + (T... args) + + + T + length + cpp/regex/match_results/length + + (T... args) + + + T + begin + cpp/regex/match_results/begin + + (T... args) + + + + std::defer_lock_t + cpp/thread/lock_tag_t + + + std::exception + cpp/error/exception + + T + what + cpp/error/exception/what + + (T... args) + + + T + ~exception + cpp/error/exception/~exception + + (T... args) + + + T + operator= + cpp/error/exception/operator= + + (T... args) + + + T + exception + cpp/error/exception/exception + + (T... args) + + + + std::front_insert_iterator + cpp/iterator/front_insert_iterator + + + std::zetta + cpp/numeric/ratio/ratio + + + std::streambuf + cpp/io/basic_streambuf + + T + pptr + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + epptr + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + eback + cpp/io/basic_streambuf/gptr + + (T... args) + + + T + setp + cpp/io/basic_streambuf/setp + + (T... args) + + + T + sputbackc + cpp/io/basic_streambuf/sputbackc + + (T... args) + + + T + getloc + cpp/io/basic_streambuf/getloc + + (T... args) + + + T + seekoff + cpp/io/basic_streambuf/pubseekoff + + (T... args) + + + T + imbue + cpp/io/basic_streambuf/pubimbue + + (T... args) + + + T + sungetc + cpp/io/basic_streambuf/sungetc + + (T... args) + + + T + sync + cpp/io/basic_streambuf/pubsync + + (T... args) + + + T + xsputn + cpp/io/basic_streambuf/sputn + + (T... args) + + + T + pbase + cpp/io/basic_streambuf/pptr + + (T... args) + + + T + sgetc + cpp/io/basic_streambuf/sgetc + + (T... args) + + + T + pubimbue + cpp/io/basic_streambuf/pubimbue + + (T... args) + + + T + showmanyc + cpp/io/basic_streambuf/showmanyc + + (T... args) + + + T + snextc + cpp/io/basic_streambuf/snextc + + (T... args) + + + T + egptr + cpp/io/basic_streambuf/gptr + + (T... args) + + + T + seekpos + cpp/io/basic_streambuf/pubseekpos + + (T... args) + + + T + underflow + cpp/io/basic_streambuf/underflow + + (T... args) + + + T + setbuf + cpp/io/basic_streambuf/pubsetbuf + + (T... args) + + + T + gbump + cpp/io/basic_streambuf/gbump + + (T... args) + + + T + in_avail + cpp/io/basic_streambuf/in_avail + + (T... args) + + + T + swap + cpp/io/basic_streambuf/swap + + (T... args) + + + T + pbackfail + cpp/io/basic_streambuf/pbackfail + + (T... args) + + + T + sputc + cpp/io/basic_streambuf/sputc + + (T... args) + + + T + xsgetn + cpp/io/basic_streambuf/sgetn + + (T... args) + + + T + uflow + cpp/io/basic_streambuf/uflow + + (T... args) + + + T + overflow + cpp/io/basic_streambuf/overflow + + (T... args) + + + T + sputn + cpp/io/basic_streambuf/sputn + + (T... args) + + + T + sgetn + cpp/io/basic_streambuf/sgetn + + (T... args) + + + T + sbumpc + cpp/io/basic_streambuf/sbumpc + + (T... args) + + + T + ~streambuf + cpp/io/basic_streambuf/~basic_streambuf + + (T... args) + + + T + operator= + cpp/io/basic_streambuf/operator= + + (T... args) + + + T + pbump + cpp/io/basic_streambuf/pbump + + (T... args) + + + T + pubsetbuf + cpp/io/basic_streambuf/pubsetbuf + + (T... args) + + + T + pubsync + cpp/io/basic_streambuf/pubsync + + (T... args) + + + T + pubseekoff + cpp/io/basic_streambuf/pubseekoff + + (T... args) + + + T + setg + cpp/io/basic_streambuf/setg + + (T... args) + + + T + streambuf + cpp/io/basic_streambuf/basic_streambuf + + (T... args) + + + T + gptr + cpp/io/basic_streambuf/gptr + + (T... args) + + + T + pubseekpos + cpp/io/basic_streambuf/pubseekpos + + (T... args) + + + + std::experimental + + + T + make_optional + cpp/experimental/optional/make_optional + + (T... args) + + std::experimental::optional + + + std::experimental::optional + cpp/experimental/optional + + T + operator= + cpp/experimental/optional/operator= + + (T... args) + + + T + operator bool + cpp/experimental/optional/operator_bool + + (T... args) + + + T + optional + cpp/experimental/optional/optional + + (T... args) + + + T + ~optional + cpp/experimental/optional/~optional + + (T... args) + + + T + operator-> + cpp/experimental/optional/operator* + + (T... args) + + + T + value + cpp/experimental/optional/value + + (T... args) + + + T + value_or + cpp/experimental/optional/value_or + + (T... args) + + + T + operator* + cpp/experimental/optional/operator* + + (T... args) + + + T + emplace + cpp/experimental/optional/emplace + + (T... args) + + + T + swap + cpp/experimental/optional/swap + + (T... args) + + + + std::num_put + cpp/locale/num_put + + T + num_put + cpp/locale/num_put/num_put + + (T... args) + + std::num_put::char_type + + T + ~num_put + cpp/locale/num_put/~num_put + + (T... args) + + + T + do_put + cpp/locale/num_put/put + + (T... args) + + + T + put + cpp/locale/num_put/put + + (T... args) + + std::num_put::iter_type + + + std::num_put::char_type + cpp/locale/num_put + + + std::num_put::iter_type + cpp/locale/num_put + + + std::owner_less + cpp/memory/owner_less + + T + operator() + cpp/memory/owner_less + + (T... args) + + + + std::extent + cpp/types/extent + + + std::bad_optional_access + cpp/utility/bad_optional_access + + T + bad_optional_access + cpp/utility/bad_optional_access + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::yotta + cpp/numeric/ratio/ratio + + + std::wcregex_token_iterator + cpp/regex/regex_token_iterator + + T + operator!= + cpp/regex/regex_token_iterator/operator_cmp + + (T... args) + + + T + operator= + cpp/regex/regex_token_iterator/operator= + + (T... args) + + + T + operator== + cpp/regex/regex_token_iterator/operator_cmp + + (T... args) + + + T + operator-> + cpp/regex/regex_token_iterator/operator* + + (T... args) + + + T + operator++ + cpp/regex/regex_token_iterator/operator_arith + + (T... args) + + + T + operator* + cpp/regex/regex_token_iterator/operator* + + (T... args) + + + T + operator++(int) + cpp/regex/regex_token_iterator/operator_arith + + (T... args) + + + T + wcregex_token_iterator + cpp/regex/regex_token_iterator/regex_token_iterator + + (T... args) + + + + std::uint64_t + cpp/types/integer + + + std::messages + cpp/locale/messages + + T + do_get + cpp/locale/messages/get + + (T... args) + + + T + do_close + cpp/locale/messages/close + + (T... args) + + std::messages::char_type + + T + get + cpp/locale/messages/get + + (T... args) + + + T + ~messages + cpp/locale/messages/~messages + + (T... args) + + + T + do_open + cpp/locale/messages/open + + (T... args) + + + T + messages + cpp/locale/messages/messages + + (T... args) + + + T + open + cpp/locale/messages/open + + (T... args) + + std::messages::string_type + std::messages::catalog + + T + close + cpp/locale/messages/close + + (T... args) + + + + std::messages::char_type + cpp/locale/messages + + + std::messages::string_type + cpp/locale/messages + + + std::messages::catalog + cpp/locale/messages_base + + + std::regex_token_iterator + cpp/regex/regex_token_iterator + + T + regex_token_iterator + cpp/regex/regex_token_iterator/regex_token_iterator + + (T... args) + + + T + operator= + cpp/regex/regex_token_iterator/operator= + + (T... args) + + + T + operator== + cpp/regex/regex_token_iterator/operator_cmp + + (T... args) + + + T + operator-> + cpp/regex/regex_token_iterator/operator* + + (T... args) + + + T + operator++ + cpp/regex/regex_token_iterator/operator_arith + + (T... args) + + + T + operator* + cpp/regex/regex_token_iterator/operator* + + (T... args) + + + T + operator!= + cpp/regex/regex_token_iterator/operator_cmp + + (T... args) + + + T + operator++(int) + cpp/regex/regex_token_iterator/operator_arith + + (T... args) + + + + std::move_iterator + cpp/iterator/move_iterator + + + std::messages_base + cpp/locale/messages_base + std::messages_base::catalog + + + std::messages_base::catalog + cpp/locale/messages_base + + + std::istringstream + cpp/io/basic_istringstream + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + str + cpp/io/basic_istringstream/str + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + readsome + cpp/io/basic_istream/readsome + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + gcount + cpp/io/basic_istream/gcount + + (T... args) + + + T + istringstream + cpp/io/basic_istringstream/basic_istringstream + + (T... args) + + + T + get + cpp/io/basic_istream/get + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + read + cpp/io/basic_istream/read + + (T... args) + + + T + getline + cpp/io/basic_istream/getline + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + unget + cpp/io/basic_istream/unget + + (T... args) + + std::istringstream::event_callback + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + sync + cpp/io/basic_istream/sync + + (T... args) + + + T + putback + cpp/io/basic_istream/putback + + (T... args) + + + T + ignore + cpp/io/basic_istream/ignore + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + seekg + cpp/io/basic_istream/seekg + + (T... args) + + std::istringstream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + tellg + cpp/io/basic_istream/tellg + + (T... args) + + + T + operator>> + cpp/io/basic_istream/operator_gtgt + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + peek + cpp/io/basic_istream/peek + + (T... args) + + + T + operator= + cpp/io/basic_istringstream/operator= + + (T... args) + + std::istringstream::sentry + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::istringstream::event_callback + cpp/io/ios_base/event_callback + + + std::istringstream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::istringstream::sentry + cpp/io/basic_istream/sentry + + T + ~sentry + cpp/io/basic_istream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_istream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_istream/sentry + + (T... args) + + + + std::giga + cpp/numeric/ratio/ratio + + + std::integer_sequence + cpp/utility/integer_sequence + + + std::has_virtual_destructor + cpp/types/has_virtual_destructor + + + std::max_align_t + cpp/types/max_align_t + + + std::remove_volatile + cpp/types/remove_cv + + + std::underlying_type + cpp/types/underlying_type + + + std::hecto + cpp/numeric/ratio/ratio + + + std::is_member_object_pointer + cpp/types/is_member_object_pointer + + + std::exception_ptr + cpp/error/exception_ptr + + + std::nested_exception + cpp/error/nested_exception + + T + operator= + cpp/error/nested_exception/operator= + + (T... args) + + + T + ~nested_exception + cpp/error/nested_exception/~nested_exception + + (T... args) + + + T + rethrow_nested + cpp/error/nested_exception/rethrow_nested + + (T... args) + + + T + nested_exception + cpp/error/nested_exception/nested_exception + + (T... args) + + + T + nested_ptr + cpp/error/nested_exception/nested_ptr + + (T... args) + + + + std::random_access_iterator_tag + cpp/iterator/iterator_tags + + + std::ctype + cpp/locale/ctype + + T + do_toupper + cpp/locale/ctype/toupper + + (T... args) + + + T + toupper + cpp/locale/ctype/toupper + + (T... args) + + + T + scan_is + cpp/locale/ctype/scan_is + + (T... args) + + + T + narrow + cpp/locale/ctype/narrow + + (T... args) + + + T + ~ctype + cpp/locale/ctype/~ctype + + (T... args) + + + T + do_narrow + cpp/locale/ctype/narrow + + (T... args) + + + T + widen + cpp/locale/ctype/widen + + (T... args) + + + T + is + cpp/locale/ctype/is + + (T... args) + + + T + do_scan_is + cpp/locale/ctype/scan_is + + (T... args) + + + T + tolower + cpp/locale/ctype/tolower + + (T... args) + + + T + do_is + cpp/locale/ctype/is + + (T... args) + + + T + do_tolower + cpp/locale/ctype/tolower + + (T... args) + + std::ctype::mask + + T + do_widen + cpp/locale/ctype/widen + + (T... args) + + + T + ctype + cpp/locale/ctype/ctype + + (T... args) + + + + std::ctype::mask + cpp/locale/ctype_base + + + std::time_t + cpp/chrono/c/time_t + + + std::knuth_b + cpp/numeric/random/shuffle_order_engine + + T + discard + cpp/numeric/random/shuffle_order_engine/discard + + (T... args) + + + T + max + cpp/numeric/random/shuffle_order_engine/max + + (T... args) + + + T + knuth_b + cpp/numeric/random/shuffle_order_engine/shuffle_order_engine + + (T... args) + + + T + operator() + cpp/numeric/random/shuffle_order_engine/operator() + + (T... args) + + + T + base + cpp/numeric/random/shuffle_order_engine/base + + (T... args) + + + T + seed + cpp/numeric/random/shuffle_order_engine/seed + + (T... args) + + + T + min + cpp/numeric/random/shuffle_order_engine/min + + (T... args) + + + + std::auto_ptr + cpp/memory/auto_ptr + + T + release + cpp/memory/auto_ptr/release + + (T... args) + + + T + operator* + cpp/memory/auto_ptr/operator* + + (T... args) + + + T + operator auto_ptr<Y> + cpp/memory/auto_ptr/operator_auto_ptr + + (T... args) + + + T + reset + cpp/memory/auto_ptr/reset + + (T... args) + + + T + operator-> + cpp/memory/auto_ptr/operator* + + (T... args) + + + T + operator= + cpp/memory/auto_ptr/operator= + + (T... args) + + + T + auto_ptr + cpp/memory/auto_ptr/auto_ptr + + (T... args) + + + T + ~auto_ptr + cpp/memory/auto_ptr/~auto_ptr + + (T... args) + + + T + get + cpp/memory/auto_ptr/get + + (T... args) + + + + std::minstd_rand0 + cpp/numeric/random/linear_congruential_engine + + T + discard + cpp/numeric/random/linear_congruential_engine/discard + + (T... args) + + + T + max + cpp/numeric/random/linear_congruential_engine/max + + (T... args) + + + T + operator() + cpp/numeric/random/linear_congruential_engine/operator() + + (T... args) + + + T + seed + cpp/numeric/random/linear_congruential_engine/seed + + (T... args) + + + T + min + cpp/numeric/random/linear_congruential_engine/min + + (T... args) + + + T + minstd_rand0 + cpp/numeric/random/linear_congruential_engine/linear_congruential_engine + + (T... args) + + + + std::sregex_token_iterator + cpp/regex/regex_token_iterator + + T + operator!= + cpp/regex/regex_token_iterator/operator_cmp + + (T... args) + + + T + operator= + cpp/regex/regex_token_iterator/operator= + + (T... args) + + + T + sregex_token_iterator + cpp/regex/regex_token_iterator/regex_token_iterator + + (T... args) + + + T + operator== + cpp/regex/regex_token_iterator/operator_cmp + + (T... args) + + + T + operator-> + cpp/regex/regex_token_iterator/operator* + + (T... args) + + + T + operator++ + cpp/regex/regex_token_iterator/operator_arith + + (T... args) + + + T + operator* + cpp/regex/regex_token_iterator/operator* + + (T... args) + + + T + operator++(int) + cpp/regex/regex_token_iterator/operator_arith + + (T... args) + + + + std::logical_not + cpp/utility/functional/logical_not + + T + operator() + cpp/utility/functional/logical_not + + (T... args) + + + + std::fpos_t + cpp/io/c + + + std::istream + cpp/io/basic_istream + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + ~istream + cpp/io/basic_istream/~basic_istream + + (T... args) + + + T + istream + cpp/io/basic_istream/basic_istream + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + seekg + cpp/io/basic_istream/seekg + + (T... args) + + + T + operator>> + cpp/io/basic_istream/operator_gtgt + + (T... args) + + + T + read + cpp/io/basic_istream/read + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + std::istream::event_callback + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + getline + cpp/io/basic_istream/getline + + (T... args) + + + T + gcount + cpp/io/basic_istream/gcount + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + unget + cpp/io/basic_istream/unget + + (T... args) + + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + sync + cpp/io/basic_istream/sync + + (T... args) + + + T + putback + cpp/io/basic_istream/putback + + (T... args) + + + T + ignore + cpp/io/basic_istream/ignore + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + std::istream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + get + cpp/io/basic_istream/get + + (T... args) + + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + readsome + cpp/io/basic_istream/readsome + + (T... args) + + + T + tellg + cpp/io/basic_istream/tellg + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + peek + cpp/io/basic_istream/peek + + (T... args) + + std::istream::sentry + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::istream::event_callback + cpp/io/ios_base/event_callback + + + std::istream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::istream::sentry + cpp/io/basic_istream/sentry + + T + ~sentry + cpp/io/basic_istream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_istream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_istream/sentry + + (T... args) + + + + std::seed_seq + cpp/numeric/random/seed_seq + + T + generate + cpp/numeric/random/seed_seq/generate + + (T... args) + + + T + param + cpp/numeric/random/seed_seq/param + + (T... args) + + + T + size + cpp/numeric/random/seed_seq/size + + (T... args) + + + T + seed_seq + cpp/numeric/random/seed_seq/seed_seq + + (T... args) + + + + std::default_delete + cpp/memory/default_delete + + T + default_delete + cpp/memory/default_delete + + (T... args) + + + T + operator() + cpp/memory/default_delete + + (T... args) + + + + std::femto + cpp/numeric/ratio/ratio + + + std::clock_t + cpp/chrono/c/clock_t + + + std::true_type + cpp/types/integral_constant + + + std::mbstate_t + cpp/string/multibyte/mbstate_t + + + std::ostrstream + cpp/io/ostrstream + + T + seekp + cpp/io/basic_ostream/seekp + + (T... args) + + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + str + cpp/io/ostrstream/str + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + std::ostrstream::event_callback + + T + pcount + cpp/io/ostrstream/pcount + + (T... args) + + + T + ostrstream + cpp/io/ostrstream/ostrstream + + (T... args) + + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + tellp + cpp/io/basic_ostream/tellp + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + operator<< + cpp/io/basic_ostream/operator_ltlt + + (T... args) + + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + write + cpp/io/basic_ostream/write + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + std::ostrstream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + flush + cpp/io/basic_ostream/flush + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + freeze + cpp/io/ostrstream/freeze + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + ~ostrstream + cpp/io/ostrstream/~ostrstream + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + std::ostrstream::sentry + + T + put + cpp/io/basic_ostream/put + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::ostrstream::event_callback + cpp/io/ios_base/event_callback + + + std::ostrstream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::ostrstream::sentry + cpp/io/basic_ostream/sentry + + T + ~sentry + cpp/io/basic_ostream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_ostream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_ostream/sentry + + (T... args) + + + + std::gamma_distribution + cpp/numeric/random/gamma_distribution + + T + gamma_distribution + cpp/numeric/random/gamma_distribution/gamma_distribution + + (T... args) + + + T + max + cpp/numeric/random/gamma_distribution/max + + (T... args) + + + T + operator() + cpp/numeric/random/gamma_distribution/operator() + + (T... args) + + + T + reset + cpp/numeric/random/gamma_distribution/reset + + (T... args) + + + T + alpha + cpp/numeric/random/gamma_distribution/params + + (T... args) + + + T + beta + cpp/numeric/random/gamma_distribution/params + + (T... args) + + + T + param + cpp/numeric/random/gamma_distribution/param + + (T... args) + + + T + min + cpp/numeric/random/gamma_distribution/min + + (T... args) + + + + std::bad_weak_ptr + cpp/memory/bad_weak_ptr + + T + bad_weak_ptr + cpp/memory/bad_weak_ptr/bad_weak_ptr + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::output_iterator_tag + cpp/iterator/iterator_tags + + + std::micro + cpp/numeric/ratio/ratio + + + std::is_trivial + cpp/types/is_trivial + + + std::packaged_task + cpp/thread/packaged_task + + T + operator= + cpp/thread/packaged_task/operator= + + (T... args) + + + T + swap + cpp/thread/packaged_task/swap + + (T... args) + + + T + reset + cpp/thread/packaged_task/reset + + (T... args) + + + T + packaged_task + cpp/thread/packaged_task/packaged_task + + (T... args) + + + T + make_ready_at_thread_exit + cpp/thread/packaged_task/make_ready_at_thread_exit + + (T... args) + + + T + operator() + cpp/thread/packaged_task/operator() + + (T... args) + + + T + get_future + cpp/thread/packaged_task/get_future + + (T... args) + + + T + valid + cpp/thread/packaged_task/valid + + (T... args) + + + T + ~packaged_task + cpp/thread/packaged_task/~packaged_task + + (T... args) + + + + std::unordered_set + cpp/container/unordered_set + + T + max_bucket_count + cpp/container/unordered_set/max_bucket_count + + (T... args) + + + T + cbegin + cpp/container/unordered_set/begin + + (T... args) + + + T + erase + cpp/container/unordered_set/erase + + (T... args) + + + T + insert + cpp/container/unordered_set/insert + + (T... args) + + + T + bucket_count + cpp/container/unordered_set/bucket_count + + (T... args) + + + T + max_load_factor + cpp/container/unordered_set/max_load_factor + + (T... args) + + + T + end + cpp/container/unordered_set/end + + (T... args) + + + T + emplace_hint + cpp/container/unordered_set/emplace_hint + + (T... args) + + + T + end(int) + cpp/container/unordered_set/end2 + + (T... args) + + + T + ~unordered_set + cpp/container/unordered_set/~unordered_set + + (T... args) + + + T + key_eq + cpp/container/unordered_set/key_eq + + (T... args) + + + T + hash_function + cpp/container/unordered_set/hash_function + + (T... args) + + + T + find + cpp/container/unordered_set/find + + (T... args) + + + T + clear + cpp/container/unordered_set/clear + + (T... args) + + + T + begin + cpp/container/unordered_set/begin + + (T... args) + + + T + cbegin(int) + cpp/container/unordered_set/begin2 + + (T... args) + + + T + swap + cpp/container/unordered_set/swap + + (T... args) + + + T + begin(int) + cpp/container/unordered_set/begin2 + + (T... args) + + + T + load_factor + cpp/container/unordered_set/load_factor + + (T... args) + + + T + size + cpp/container/unordered_set/size + + (T... args) + + + T + operator= + cpp/container/unordered_set/operator= + + (T... args) + + + T + cend + cpp/container/unordered_set/end + + (T... args) + + + T + reserve + cpp/container/unordered_set/reserve + + (T... args) + + + T + rehash + cpp/container/unordered_set/rehash + + (T... args) + + + T + bucket + cpp/container/unordered_set/bucket + + (T... args) + + + T + empty + cpp/container/unordered_set/empty + + (T... args) + + + T + get_allocator + cpp/container/unordered_set/get_allocator + + (T... args) + + + T + max_size + cpp/container/unordered_set/max_size + + (T... args) + + + T + cend(int) + cpp/container/unordered_set/end2 + + (T... args) + + + T + count + cpp/container/unordered_set/count + + (T... args) + + + T + unordered_set + cpp/container/unordered_set/unordered_set + + (T... args) + + + T + equal_range + cpp/container/unordered_set/equal_range + + (T... args) + + + T + emplace + cpp/container/unordered_set/emplace + + (T... args) + + + T + bucket_size + cpp/container/unordered_set/bucket_size + + (T... args) + + + + std::is_volatile + cpp/types/is_volatile + + + std::wfstream + cpp/io/basic_fstream + + T + seekp + cpp/io/basic_ostream/seekp + + (T... args) + + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + operator>> + cpp/io/basic_istream/operator_gtgt + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + + T + seekg + cpp/io/basic_istream/seekg + + (T... args) + + + T + open + cpp/io/basic_fstream/open + + (T... args) + + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + tellp + cpp/io/basic_ostream/tellp + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + gcount + cpp/io/basic_istream/gcount + + (T... args) + + + T + unget + cpp/io/basic_istream/unget + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + read + cpp/io/basic_istream/read + + (T... args) + + + T + getline + cpp/io/basic_istream/getline + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + std::wfstream::sentry + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + wfstream + cpp/io/basic_fstream/basic_fstream + + (T... args) + + + T + operator<< + cpp/io/basic_ostream/operator_ltlt + + (T... args) + + std::wfstream::event_callback + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + write + cpp/io/basic_ostream/write + + (T... args) + + + T + close + cpp/io/basic_fstream/close + + (T... args) + + + T + sync + cpp/io/basic_istream/sync + + (T... args) + + + T + putback + cpp/io/basic_istream/putback + + (T... args) + + + T + ignore + cpp/io/basic_istream/ignore + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + readsome + cpp/io/basic_istream/readsome + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + std::wfstream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + get + cpp/io/basic_istream/get + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + flush + cpp/io/basic_ostream/flush + + (T... args) + + + T + tellg + cpp/io/basic_istream/tellg + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + is_open + cpp/io/basic_fstream/is_open + + (T... args) + + + T + peek + cpp/io/basic_istream/peek + + (T... args) + + + T + operator= + cpp/io/basic_fstream/operator= + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + + T + put + cpp/io/basic_ostream/put + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::wfstream::sentry + cpp/io/basic_ostream/sentry + + T + ~sentry + cpp/io/basic_istream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_istream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_istream/sentry + + (T... args) + + + + std::wfstream::event_callback + cpp/io/ios_base/event_callback + + + std::wfstream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::multimap + cpp/container/multimap + + T + multimap + cpp/container/multimap/multimap + + (T... args) + + + T + begin + cpp/container/multimap/begin + + (T... args) + + + T + erase + cpp/container/multimap/erase + + (T... args) + + + T + insert + cpp/container/multimap/insert + + (T... args) + + + T + swap + cpp/container/multimap/swap + + (T... args) + + + T + end + cpp/container/multimap/end + + (T... args) + + + T + ~multimap + cpp/container/multimap/~multimap + + (T... args) + + + T + emplace_hint + cpp/container/multimap/emplace_hint + + (T... args) + + + T + key_comp + cpp/container/multimap/key_comp + + (T... args) + + std::multimap::value_compare + + T + cbegin + cpp/container/multimap/begin + + (T... args) + + + T + count + cpp/container/multimap/count + + (T... args) + + + T + find + cpp/container/multimap/find + + (T... args) + + + T + crbegin + cpp/container/multimap/rbegin + + (T... args) + + + T + upper_bound + cpp/container/multimap/upper_bound + + (T... args) + + + T + rbegin + cpp/container/multimap/rbegin + + (T... args) + + + T + crend + cpp/container/multimap/rend + + (T... args) + + + T + size + cpp/container/multimap/size + + (T... args) + + + T + operator= + cpp/container/multimap/operator= + + (T... args) + + + T + value_comp + cpp/container/multimap/value_comp + + (T... args) + + + T + empty + cpp/container/multimap/empty + + (T... args) + + + T + lower_bound + cpp/container/multimap/lower_bound + + (T... args) + + + T + cend + cpp/container/multimap/end + + (T... args) + + + T + max_size + cpp/container/multimap/max_size + + (T... args) + + + T + rend + cpp/container/multimap/rend + + (T... args) + + + T + get_allocator + cpp/container/multimap/get_allocator + + (T... args) + + + T + clear + cpp/container/multimap/clear + + (T... args) + + + T + equal_range + cpp/container/multimap/equal_range + + (T... args) + + + T + emplace + cpp/container/multimap/emplace + + (T... args) + + + + std::multimap::value_compare + cpp/container/multimap/value_compare + + + std::atomic_flag + cpp/atomic/atomic_flag + + T + operator= + cpp/atomic/atomic_flag/operator= + + (T... args) + + + T + clear + cpp/atomic/atomic_flag/clear + + (T... args) + + + T + atomic_flag + cpp/atomic/atomic_flag/atomic_flag + + (T... args) + + + T + test_and_set + cpp/atomic/atomic_flag/test_and_set + + (T... args) + + + + std::numpunct_byname + cpp/locale/numpunct_byname + + T + grouping + cpp/locale/numpunct/grouping + + (T... args) + + + T + do_decimal_point + cpp/locale/numpunct/decimal_point + + (T... args) + + + T + thousands_sep + cpp/locale/numpunct/thousands_sep + + (T... args) + + + T + falsename + cpp/locale/numpunct/truefalsename + + (T... args) + + + T + do_falsename + cpp/locale/numpunct/truefalsename + + (T... args) + + std::numpunct_byname::string_type + + T + numpunct_byname + cpp/locale/numpunct_byname + + (T... args) + + + T + truename + cpp/locale/numpunct/truefalsename + + (T... args) + + std::numpunct_byname::char_type + + T + do_truename + cpp/locale/numpunct/truefalsename + + (T... args) + + + T + do_grouping + cpp/locale/numpunct/grouping + + (T... args) + + + T + decimal_point + cpp/locale/numpunct/decimal_point + + (T... args) + + + T + do_thousands_sep + cpp/locale/numpunct/thousands_sep + + (T... args) + + + T + ~numpunct_byname + cpp/locale/numpunct_byname + + (T... args) + + + + std::numpunct_byname::string_type + cpp/locale/numpunct + + + std::numpunct_byname::char_type + cpp/locale/numpunct + + + std::binomial_distribution + cpp/numeric/random/binomial_distribution + + T + t + cpp/numeric/random/binomial_distribution/params + + (T... args) + + + T + binomial_distribution + cpp/numeric/random/binomial_distribution/binomial_distribution + + (T... args) + + + T + reset + cpp/numeric/random/binomial_distribution/reset + + (T... args) + + + T + max + cpp/numeric/random/binomial_distribution/max + + (T... args) + + + T + p + cpp/numeric/random/binomial_distribution/params + + (T... args) + + + T + min + cpp/numeric/random/binomial_distribution/min + + (T... args) + + + T + param + cpp/numeric/random/binomial_distribution/param + + (T... args) + + + + std::basic_iostream + cpp/io/basic_iostream + + T + seekp + cpp/io/basic_ostream/seekp + + (T... args) + + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + operator>> + cpp/io/basic_istream/operator_gtgt + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + + T + seekg + cpp/io/basic_istream/seekg + + (T... args) + + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + tellp + cpp/io/basic_ostream/tellp + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + gcount + cpp/io/basic_istream/gcount + + (T... args) + + + T + ~basic_iostream + cpp/io/basic_iostream/~basic_iostream + + (T... args) + + + T + unget + cpp/io/basic_istream/unget + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + read + cpp/io/basic_istream/read + + (T... args) + + + T + getline + cpp/io/basic_istream/getline + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + std::basic_iostream::sentry + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + operator<< + cpp/io/basic_ostream/operator_ltlt + + (T... args) + + std::basic_iostream::event_callback + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + write + cpp/io/basic_ostream/write + + (T... args) + + + T + sync + cpp/io/basic_istream/sync + + (T... args) + + + T + putback + cpp/io/basic_istream/putback + + (T... args) + + + T + basic_iostream + cpp/io/basic_iostream/basic_iostream + + (T... args) + + + T + ignore + cpp/io/basic_istream/ignore + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + readsome + cpp/io/basic_istream/readsome + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + std::basic_iostream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + get + cpp/io/basic_istream/get + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + flush + cpp/io/basic_ostream/flush + + (T... args) + + + T + tellg + cpp/io/basic_istream/tellg + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + peek + cpp/io/basic_istream/peek + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + + T + put + cpp/io/basic_ostream/put + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::basic_iostream::sentry + cpp/io/basic_ostream/sentry + + T + ~sentry + cpp/io/basic_istream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_istream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_istream/sentry + + (T... args) + + + + std::basic_iostream::event_callback + cpp/io/ios_base/event_callback + + + std::basic_iostream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::wofstream + cpp/io/basic_ofstream + + T + seekp + cpp/io/basic_ostream/seekp + + (T... args) + + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + std::wofstream::event_callback + + T + open + cpp/io/basic_ofstream/open + + (T... args) + + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + tellp + cpp/io/basic_ostream/tellp + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + wofstream + cpp/io/basic_ofstream/basic_ofstream + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + operator<< + cpp/io/basic_ostream/operator_ltlt + + (T... args) + + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + close + cpp/io/basic_ofstream/close + + (T... args) + + + T + write + cpp/io/basic_ostream/write + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + std::wofstream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + flush + cpp/io/basic_ostream/flush + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + is_open + cpp/io/basic_ofstream/is_open + + (T... args) + + + T + operator= + cpp/io/basic_ofstream/operator= + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + std::wofstream::sentry + + T + put + cpp/io/basic_ostream/put + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::wofstream::event_callback + cpp/io/ios_base/event_callback + + + std::wofstream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::wofstream::sentry + cpp/io/basic_ostream/sentry + + T + ~sentry + cpp/io/basic_ostream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_ostream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_ostream/sentry + + (T... args) + + + + std::fpos + cpp/io/fpos + + T + state + cpp/io/fpos/state + + (T... args) + + + + std::underflow_error + cpp/error/underflow_error + + T + underflow_error + cpp/error/underflow_error + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::cauchy_distribution + cpp/numeric/random/cauchy_distribution + + T + min + cpp/numeric/random/cauchy_distribution/min + + (T... args) + + + T + reset + cpp/numeric/random/cauchy_distribution/reset + + (T... args) + + + T + a + cpp/numeric/random/cauchy_distribution/params + + (T... args) + + + T + max + cpp/numeric/random/cauchy_distribution/max + + (T... args) + + + T + operator() + cpp/numeric/random/cauchy_distribution/operator() + + (T... args) + + + T + param + cpp/numeric/random/cauchy_distribution/param + + (T... args) + + + T + cauchy_distribution + cpp/numeric/random/cauchy_distribution/cauchy_distribution + + (T... args) + + + T + b + cpp/numeric/random/cauchy_distribution/params + + (T... args) + + + + std::is_trivially_copy_constructible + cpp/types/is_copy_constructible + + + std::conditional + cpp/types/conditional + + + std::is_pod + cpp/types/is_pod + + + std::int_least8_t + cpp/types/integer + + + std::streamoff + cpp/io/streamoff + + + std::is_move_assignable + cpp/types/is_move_assignable + + + std::int_least32_t + cpp/types/integer + + + std::wstringstream + cpp/io/basic_stringstream + + T + seekp + cpp/io/basic_ostream/seekp + + (T... args) + + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + str + cpp/io/basic_stringstream/str + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + operator>> + cpp/io/basic_istream/operator_gtgt + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + + T + seekg + cpp/io/basic_istream/seekg + + (T... args) + + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + tellp + cpp/io/basic_ostream/tellp + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + gcount + cpp/io/basic_istream/gcount + + (T... args) + + + T + unget + cpp/io/basic_istream/unget + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + read + cpp/io/basic_istream/read + + (T... args) + + + T + getline + cpp/io/basic_istream/getline + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + std::wstringstream::sentry + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + operator<< + cpp/io/basic_ostream/operator_ltlt + + (T... args) + + std::wstringstream::event_callback + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + write + cpp/io/basic_ostream/write + + (T... args) + + + T + sync + cpp/io/basic_istream/sync + + (T... args) + + + T + putback + cpp/io/basic_istream/putback + + (T... args) + + + T + ignore + cpp/io/basic_istream/ignore + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + readsome + cpp/io/basic_istream/readsome + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + std::wstringstream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + get + cpp/io/basic_istream/get + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + flush + cpp/io/basic_ostream/flush + + (T... args) + + + T + tellg + cpp/io/basic_istream/tellg + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + peek + cpp/io/basic_istream/peek + + (T... args) + + + T + operator= + cpp/io/basic_stringstream/operator= + + (T... args) + + + T + wstringstream + cpp/io/basic_stringstream/basic_stringstream + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + + T + put + cpp/io/basic_ostream/put + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::wstringstream::sentry + cpp/io/basic_ostream/sentry + + T + ~sentry + cpp/io/basic_istream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_istream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_istream/sentry + + (T... args) + + + + std::wstringstream::event_callback + cpp/io/ios_base/event_callback + + + std::wstringstream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::subtract_with_carry_engine + cpp/numeric/random/subtract_with_carry_engine + + T + discard + cpp/numeric/random/subtract_with_carry_engine/discard + + (T... args) + + + T + subtract_with_carry_engine + cpp/numeric/random/subtract_with_carry_engine/subtract_with_carry_engine + + (T... args) + + + T + max + cpp/numeric/random/subtract_with_carry_engine/max + + (T... args) + + + T + operator() + cpp/numeric/random/subtract_with_carry_engine/operator() + + (T... args) + + + T + seed + cpp/numeric/random/subtract_with_carry_engine/seed + + (T... args) + + + T + min + cpp/numeric/random/subtract_with_carry_engine/min + + (T... args) + + + + std::regex_error + cpp/regex/regex_error + + T + code + cpp/regex/regex_error/code + + (T... args) + + + T + regex_error + cpp/regex/regex_error/regex_error + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::is_constructible + cpp/types/is_constructible + + + std::piecewise_construct_t + cpp/utility/piecewise_construct_t + + + std::mutex + cpp/thread/mutex + + T + mutex + cpp/thread/mutex/mutex + + (T... args) + + + T + unlock + cpp/thread/mutex/unlock + + (T... args) + + + T + lock + cpp/thread/mutex/lock + + (T... args) + + + T + try_lock + cpp/thread/mutex/try_lock + + (T... args) + + + T + native_handle + cpp/thread/mutex/native_handle + + (T... args) + + + + std::system_error + cpp/error/system_error + + T + code + cpp/error/system_error/code + + (T... args) + + + T + system_error + cpp/error/system_error/system_error + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::wistringstream + cpp/io/basic_istringstream + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + str + cpp/io/basic_istringstream/str + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + readsome + cpp/io/basic_istream/readsome + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + wistringstream + cpp/io/basic_istringstream/basic_istringstream + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + gcount + cpp/io/basic_istream/gcount + + (T... args) + + + T + get + cpp/io/basic_istream/get + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + read + cpp/io/basic_istream/read + + (T... args) + + + T + getline + cpp/io/basic_istream/getline + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + unget + cpp/io/basic_istream/unget + + (T... args) + + std::wistringstream::event_callback + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + sync + cpp/io/basic_istream/sync + + (T... args) + + + T + putback + cpp/io/basic_istream/putback + + (T... args) + + + T + ignore + cpp/io/basic_istream/ignore + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + seekg + cpp/io/basic_istream/seekg + + (T... args) + + std::wistringstream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + tellg + cpp/io/basic_istream/tellg + + (T... args) + + + T + operator>> + cpp/io/basic_istream/operator_gtgt + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + peek + cpp/io/basic_istream/peek + + (T... args) + + + T + operator= + cpp/io/basic_istringstream/operator= + + (T... args) + + std::wistringstream::sentry + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::wistringstream::event_callback + cpp/io/ios_base/event_callback + + + std::wistringstream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::wistringstream::sentry + cpp/io/basic_istream/sentry + + T + ~sentry + cpp/io/basic_istream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_istream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_istream/sentry + + (T... args) + + + + std::is_floating_point + cpp/types/is_floating_point + + + std::ratio_not_equal + cpp/numeric/ratio/ratio_not_equal + + + std::ratio_multiply + cpp/numeric/ratio/ratio_multiply + + + std::result_of + cpp/types/result_of + + + std::is_fundamental + cpp/types/is_fundamental + + + std::ifstream + cpp/io/basic_ifstream + + T + setstate + cpp/io/basic_ios/setstate + + (T... args) + + + T + getloc + cpp/io/ios_base/getloc + + (T... args) + + + T + precision + cpp/io/ios_base/precision + + (T... args) + + + T + flags + cpp/io/ios_base/flags + + (T... args) + + + T + widen + cpp/io/basic_ios/widen + + (T... args) + + + T + readsome + cpp/io/basic_istream/readsome + + (T... args) + + + T + fill + cpp/io/basic_ios/fill + + (T... args) + + + T + setf + cpp/io/ios_base/setf + + (T... args) + + + T + tie + cpp/io/basic_ios/tie + + (T... args) + + + T + open + cpp/io/basic_ifstream/open + + (T... args) + + + T + operator bool + cpp/io/basic_ios/operator_bool + + (T... args) + + + T + copyfmt + cpp/io/basic_ios/copyfmt + + (T... args) + + + T + sync_with_stdio + cpp/io/ios_base/sync_with_stdio + + (T... args) + + + T + gcount + cpp/io/basic_istream/gcount + + (T... args) + + + T + get + cpp/io/basic_istream/get + + (T... args) + + + T + xalloc + cpp/io/ios_base/xalloc + + (T... args) + + + T + read + cpp/io/basic_istream/read + + (T... args) + + + T + getline + cpp/io/basic_istream/getline + + (T... args) + + + T + exceptions + cpp/io/basic_ios/exceptions + + (T... args) + + + T + iword + cpp/io/ios_base/iword + + (T... args) + + + T + unget + cpp/io/basic_istream/unget + + (T... args) + + std::ifstream::event_callback + + T + narrow + cpp/io/basic_ios/narrow + + (T... args) + + + T + ifstream + cpp/io/basic_ifstream/basic_ifstream + + (T... args) + + + T + good + cpp/io/basic_ios/good + + (T... args) + + + T + operator! + cpp/io/basic_ios/operator! + + (T... args) + + + T + close + cpp/io/basic_ifstream/close + + (T... args) + + + T + sync + cpp/io/basic_istream/sync + + (T... args) + + + T + putback + cpp/io/basic_istream/putback + + (T... args) + + + T + ignore + cpp/io/basic_istream/ignore + + (T... args) + + + T + unsetf + cpp/io/ios_base/unsetf + + (T... args) + + + T + width + cpp/io/ios_base/width + + (T... args) + + + T + rdstate + cpp/io/basic_ios/rdstate + + (T... args) + + + T + seekg + cpp/io/basic_istream/seekg + + (T... args) + + std::ifstream::failure + + T + move + cpp/io/basic_ios/move + + (T... args) + + + T + eof + cpp/io/basic_ios/eof + + (T... args) + + + T + register_callback + cpp/io/ios_base/register_callback + + (T... args) + + + T + pword + cpp/io/ios_base/pword + + (T... args) + + + T + swap + cpp/io/basic_ios/swap + + (T... args) + + + T + tellg + cpp/io/basic_istream/tellg + + (T... args) + + + T + operator>> + cpp/io/basic_istream/operator_gtgt + + (T... args) + + + T + set_rdbuf + cpp/io/basic_ios/set_rdbuf + + (T... args) + + + T + fail + cpp/io/basic_ios/fail + + (T... args) + + + T + is_open + cpp/io/basic_ifstream/is_open + + (T... args) + + + T + peek + cpp/io/basic_istream/peek + + (T... args) + + + T + operator= + cpp/io/basic_ifstream/operator= + + (T... args) + + std::ifstream::sentry + + T + rdbuf + cpp/io/basic_ios/rdbuf + + (T... args) + + + T + imbue + cpp/io/basic_ios/imbue + + (T... args) + + + T + bad + cpp/io/basic_ios/bad + + (T... args) + + + T + clear + cpp/io/basic_ios/clear + + (T... args) + + + T + init + cpp/io/basic_ios/init + + (T... args) + + + + std::ifstream::event_callback + cpp/io/ios_base/event_callback + + + std::ifstream::failure + cpp/io/ios_base/failure + + T + failure + cpp/io/ios_base/failure + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::ifstream::sentry + cpp/io/basic_istream/sentry + + T + ~sentry + cpp/io/basic_istream/sentry + + (T... args) + + + T + operator bool + cpp/io/basic_istream/sentry + + (T... args) + + + T + sentry + cpp/io/basic_istream/sentry + + (T... args) + + + + std::u32streampos + cpp/io/fpos + + T + state + cpp/io/fpos/state + + (T... args) + + + + std::length_error + cpp/error/length_error + + T + length_error + cpp/error/length_error + + (T... args) + + + T + what + cpp/error/exception/what + + (T... args) + + + + std::sub_match + cpp/regex/sub_match + + T + operator string_type + cpp/regex/sub_match/str + + (T... args) + + + T + sub_match + cpp/regex/sub_match/sub_match + + (T... args) + + + T + str + cpp/regex/sub_match/str + + (T... args) + + + T + length + cpp/regex/sub_match/length + + (T... args) + + + T + compare + cpp/regex/sub_match/compare + + (T... args) + + + + std::common_type + cpp/types/common_type + + + std::shared_timed_mutex + cpp/thread/shared_timed_mutex + + T + unlock + cpp/thread/shared_timed_mutex/unlock + + (T... args) + + + T + unlock_shared + cpp/thread/shared_timed_mutex/unlock_shared + + (T... args) + + + T + try_lock_until + cpp/thread/shared_timed_mutex/try_lock_until + + (T... args) + + + T + try_lock_for + cpp/thread/shared_timed_mutex/try_lock_for + + (T... args) + + + T + try_lock_shared_until + cpp/thread/shared_timed_mutex/try_lock_shared_until + + (T... args) + + + T + shared_timed_mutex + cpp/thread/shared_timed_mutex/shared_timed_mutex + + (T... args) + + + T + lock_shared + cpp/thread/shared_timed_mutex/lock_shared + + (T... args) + + + T + lock + cpp/thread/shared_timed_mutex/lock + + (T... args) + + + T + try_lock + cpp/thread/shared_timed_mutex/try_lock + + (T... args) + + + T + try_lock_shared + cpp/thread/shared_timed_mutex/try_lock_shared + + (T... args) + + + T + try_lock_shared_for + cpp/thread/shared_timed_mutex/try_lock_shared_for + + (T... args) + + + + std::array + cpp/container/array + + T + max_size + cpp/container/array/max_size + + (T... args) + + + T + rbegin + cpp/container/array/rbegin + + (T... args) + + + T + crend + cpp/container/array/rend + + (T... args) + + + T + crbegin + cpp/container/array/rbegin + + (T... args) + + + T + swap + cpp/container/array/swap + + (T... args) + + + T + data + cpp/container/array/data + + (T... args) + + + T + back + cpp/container/array/back + + (T... args) + + + T + end + cpp/container/array/end + + (T... args) + + + T + fill + cpp/container/array/fill + + (T... args) + + + T + empty + cpp/container/array/empty + + (T... args) + + + T + cend + cpp/container/array/end + + (T... args) + + + T + size + cpp/container/array/size + + (T... args) + + + T + cbegin + cpp/container/array/begin + + (T... args) + + + T + rend + cpp/container/array/rend + + (T... args) + + + T + front + cpp/container/array/front + + (T... args) + + + T + at + cpp/container/array/at + + (T... args) + + + T + operator[] + cpp/container/array/operator_at + + (T... args) + + + T + begin + cpp/container/array/begin + + (T... args) + + + + std::random_device + cpp/numeric/random/random_device + + T + operator() + cpp/numeric/random/random_device/operator() + + (T... args) + + + T + random_device + cpp/numeric/random/random_device/random_device + + (T... args) + + + T + entropy + cpp/numeric/random/random_device/entropy + + (T... args) + + + T + min + cpp/numeric/random/random_device/min + + (T... args) + + + T + max + cpp/numeric/random/random_device/max + + (T... args) + + + + std::default_random_engine + cpp/numeric/random + + + std::raw_storage_iterator + cpp/memory/raw_storage_iterator + + T + operator= + cpp/memory/raw_storage_iterator/operator= + + (T... args) + + + T + raw_storage_iterator + cpp/memory/raw_storage_iterator/raw_storage_iterator + + (T... args) + + + T + operator* + cpp/memory/raw_storage_iterator/operator* + + (T... args) + + + T + operator++ + cpp/memory/raw_storage_iterator/operator_arith + + (T... args) + + + + std::is_convertible + cpp/types/is_convertible + + + std::uint16_t + cpp/types/integer + + + std::is_array + cpp/types/is_array + + + std::mega + cpp/numeric/ratio/ratio + + + std::numpunct + cpp/locale/numpunct + + T + grouping + cpp/locale/numpunct/grouping + + (T... args) + + + T + do_decimal_point + cpp/locale/numpunct/decimal_point + + (T... args) + + + T + thousands_sep + cpp/locale/numpunct/thousands_sep + + (T... args) + + + T + numpunct + cpp/locale/numpunct/numpunct + + (T... args) + + + T + do_falsename + cpp/locale/numpunct/truefalsename + + (T... args) + + std::numpunct::string_type + + T + do_grouping + cpp/locale/numpunct/grouping + + (T... args) + + + T + truename + cpp/locale/numpunct/truefalsename + + (T... args) + + std::numpunct::char_type + + T + falsename + cpp/locale/numpunct/truefalsename + + (T... args) + + + T + do_truename + cpp/locale/numpunct/truefalsename + + (T... args) + + + T + ~numpunct + cpp/locale/numpunct/~numpunct + + (T... args) + + + T + decimal_point + cpp/locale/numpunct/decimal_point + + (T... args) + + + T + do_thousands_sep + cpp/locale/numpunct/thousands_sep + + (T... args) + + + + std::numpunct::string_type + cpp/locale/numpunct + + + std::numpunct::char_type + cpp/locale/numpunct + + + std::money_put + cpp/locale/money_put + std::money_put::char_type + std::money_put::pattern + + T + do_put + cpp/locale/money_put/put + + (T... args) + + + T + money_put + cpp/locale/money_put/money_put + + (T... args) + + + T + ~money_put + cpp/locale/money_put/~money_put + + (T... args) + + + T + put + cpp/locale/money_put/put + + (T... args) + + std::money_put::string_type + std::money_put::iter_type + + + std::money_put::char_type + cpp/locale/money_put + + + std::money_put::pattern + cpp/locale/money_base + + + std::money_put::string_type + cpp/locale/money_put + + + std::money_put::iter_type + cpp/locale/money_put + + + std::new_handler + cpp/memory/new/new_handler + + + std::is_member_function_pointer + cpp/types/is_member_function_pointer + + + va_list + cpp/utility/variadic/va_list + + From 5bbeec3ace4fb3fcf9d3b5aefc579dd896185edf Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 28 May 2020 00:22:16 +0000 Subject: [PATCH 153/433] updating DIRECTORY.md --- DIRECTORY.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index e99f32611bc..bbf405b7f9d 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -109,8 +109,13 @@ * [Factorial](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/factorial.cpp) * [Fast Power](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/fast_power.cpp) * [Fibonacci](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/fibonacci.cpp) + * [Fibonacci Fast](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/fibonacci_fast.cpp) + * [Fibonacci Large](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/fibonacci_large.cpp) * [Gcd Iterative Euclidean](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/gcd_iterative_euclidean.cpp) + * [Gcd Of N Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/gcd_of_n_numbers.cpp) * [Gcd Recursive Euclidean](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/gcd_recursive_euclidean.cpp) + * [Large Factorial](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/large_factorial.cpp) + * [Large Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/large_number.h) * [Modular Inverse Fermat Little Theorem](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/modular_inverse_fermat_little_theorem.cpp) * [Number Of Positive Divisors](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/number_of_positive_divisors.cpp) * [Power For Huge Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/power_for_huge_numbers.cpp) @@ -137,12 +142,7 @@ * [Decimal To Hexadecimal](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/decimal_to_hexadecimal.cpp) * [Decimal To Roman Numeral](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/decimal_to_roman_numeral.cpp) * [Fast Interger Input](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/fast_interger_input.cpp) - * [Fibonacci Fast](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/fibonacci_fast.cpp) - * [Fibonacci Large](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/fibonacci_large.cpp) - * [Gcd Of N Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/gcd_of_n_numbers.cpp) * [Happy Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/happy_number.cpp) - * [Large Factorial](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/large_factorial.cpp) - * [Large Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/large_number.h) * [Matrix Exponentiation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/matrix_exponentiation.cpp) * [Palindrome Of Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/palindrome_of_number.cpp) * [Paranthesis Matching](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/paranthesis_matching.cpp) From cc5ce16b5874ec33c3b3fb5fc48188d91bf4987c Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 11:24:14 -0400 Subject: [PATCH 154/433] document happy numbers --- others/happy_number.cpp | 57 ++++++++++++++++++++++++----------------- 1 file changed, 34 insertions(+), 23 deletions(-) diff --git a/others/happy_number.cpp b/others/happy_number.cpp index 7d25a1bbd83..dacb2b8c4d5 100644 --- a/others/happy_number.cpp +++ b/others/happy_number.cpp @@ -1,28 +1,39 @@ -/* A happy number is a number whose sum of digits is calculated until the sum is a single digit, - and this sum turns out to be 1 */ - -// Copyright 2019 TheAlgorithms contributors +/** + * A [happy number](https://en.wikipedia.org/wiki/Happy_number) is a decimal + * number whose sum of digits is calculated until the sum is a single digit, and + * this sum turns out to be 1. + */ #include -int main() { - int n, k, s = 0, d; - std::cout << "Enter a number:"; - std::cin >> n; - s = 0; - k = n; - while (k > 9) { - while (k != 0) { - d = k % 10; - s += d; - k /= 10; +/** + * Checks if a decimal number is a happy number + * \returns true if happy else false + */ +template +bool is_happy(T n) { + T s = 0; // stores sum of digits + while (n > 9) { // while number is > 9, there are more than 1 digit + while (n != 0) { // get digit + T d = n % 10; + s += d; + n /= 10; + } + n = s; + s = 0; } - k = s; - s = 0; - } - if (k == 1) - std::cout << n << " is a happy number" << std::endl; - else - std::cout << n << " is not a happy number" << std::endl; - return 0; + return (n == 1) ? true : false; // true if k == 1 +} + +/** Main function */ +int main() { + int n; + std::cout << "Enter a number:"; + std::cin >> n; + + if (is_happy(n)) + std::cout << n << " is a happy number" << std::endl; + else + std::cout << n << " is not a happy number" << std::endl; + return 0; } From 84d33ba5d9dddb630b372bccf83eb0804e5513a0 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 11:24:22 -0400 Subject: [PATCH 155/433] document matrix exponentiation --- others/matrix_exponentiation.cpp | 80 +++++++++++++++++++++++--------- 1 file changed, 57 insertions(+), 23 deletions(-) diff --git a/others/matrix_exponentiation.cpp b/others/matrix_exponentiation.cpp index f9b4997e970..d44d225937c 100644 --- a/others/matrix_exponentiation.cpp +++ b/others/matrix_exponentiation.cpp @@ -1,20 +1,24 @@ -/* -Matrix Exponentiation. +/** +@file +@brief Matrix Exponentiation. + The problem can be solved with DP but constraints are high. -ai = bi (for i <= k) -ai = c1*ai-1 + c2*ai-2 + ... + ck*ai-k (for i > k) -Taking the example of Fibonacci series, K=2 -b1 = 1, b2=1 -c1 = 1, c2=1 -a = 0 1 1 2 .... -This way you can find the 10^18 fibonacci number%MOD. +
\f$a_i = b_i\f$ (for \f$i <= k\f$) +
\f$a_i = c_1 a_{i-1} + c_2 a_{i-2} + ... + c_k a_{i-k}\f$ (for \f$i > k\f$) +
Taking the example of Fibonacci series, \f$k=2\f$ +
\f$b_1 = 1,\; b_2=1\f$ +
\f$c_1 = 1,\; c_2=1\f$ +
\f$a = \begin{bmatrix}0& 1& 1& 2& \ldots\end{bmatrix}\f$ +
This way you can find the \f$10^{18}\f$ fibonacci number%MOD. I have given a general way to use it. The program takes the input of B and C matrix. + Steps for Matrix Expo 1. Create vector F1 : which is the copy of B. 2. Create transpose matrix (Learn more about it on the internet) -3. Perform T^(n-1) [transpose matrix to the power n-1] -4. Multiply with F to get the last matrix of size (1xk). +3. Perform \f$T^{n-1}\f$ [transpose matrix to the power n-1] +4. Multiply with F to get the last matrix of size (1\f$\times\f$k). + The first element of this matrix is the required result. */ @@ -25,16 +29,36 @@ using std::cin; using std::cout; using std::vector; +/*! shorthand definition for `int64_t` */ #define ll int64_t -#define endl '\n' + +/*! shorthand definition for `std::endl` */ +#define endl std::endl + +/*! shorthand definition for `int64_t` */ #define pb push_back #define MOD 1000000007 -ll ab(ll x) { return x > 0LL ? x : -x; } + +/** returns absolute value */ +inline ll ab(ll x) { return x > 0LL ? x : -x; } + +/** global variable k + * @todo @stepfencurryxiao add documetnation + */ ll k; + +/** global vector variables + * @todo @stepfencurryxiao add documetnation + */ vector a, b, c; -// To multiply 2 matrix -vector> multiply(vector> A, vector> B) { +/** To multiply 2 matrices + * \param [in] A matrix 1 of size (m\f$\times\f$n) + * \param [in] B \p matrix 2 of size (p\f$\times\f$q)\n\note \f$p=n\f$ + * \result matrix of dimension (m\f$\times\f$q) + */ +vector> multiply(const vector> &A, + const vector> &B) { vector> C(k + 1, vector(k + 1)); for (ll i = 1; i <= k; i++) { for (ll j = 1; j <= k; j++) { @@ -46,9 +70,15 @@ vector> multiply(vector> A, vector> B) { return C; } -// computing power of a matrix -vector> power(vector> A, ll p) { - if (p == 1) return A; +/** computing integer power of a matrix using recursive multiplication. + * @note A must be a square matrix for this algorithm. + * \param [in] A base matrix + * \param [in] p exponent + * \return matrix of same dimension as A + */ +vector> power(const vector> &A, ll p) { + if (p == 1) + return A; if (p % 2 == 1) { return multiply(A, power(A, p - 1)); } else { @@ -57,10 +87,15 @@ vector> power(vector> A, ll p) { } } -// main function +/*! Wrapper for Fibonacci + * \param[in] n \f$n^\text{th}\f$ Fibonacci number + * \return \f$n^\text{th}\f$ Fibonacci number + */ ll ans(ll n) { - if (n == 0) return 0; - if (n <= k) return b[n - 1]; + if (n == 0) + return 0; + if (n <= k) + return b[n - 1]; // F1 vector F1(k + 1); for (ll i = 1; i <= k; i++) F1[i] = b[i - 1]; @@ -90,8 +125,7 @@ ll ans(ll n) { return res; } -// 1 1 2 3 5 - +/** Main function */ int main() { cin.tie(0); cout.tie(0); From 0c8515657303d2cdafc33dafed35dd0cda9f9d7d Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 11:24:36 -0400 Subject: [PATCH 156/433] document number palindrome --- others/palindrome_of_number.cpp | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/others/palindrome_of_number.cpp b/others/palindrome_of_number.cpp index 621b09ab6ba..66401ff966a 100644 --- a/others/palindrome_of_number.cpp +++ b/others/palindrome_of_number.cpp @@ -1,3 +1,10 @@ +/** + * @file + * @brief Check if a number is + * [palindrome](https://en.wikipedia.org/wiki/Palindrome) or not. + * + * This program cheats by using the STL library's std::reverse function. + */ #include #include @@ -8,17 +15,18 @@ #include #endif +/** Main function */ int main() { int num; std::cout << "Enter number = "; std::cin >> num; - std::string s1 = std::to_string(num); + std::string s1 = std::to_string(num); // convert number to string std::string s2 = s1; - reverse(s1.begin(), s1.end()); + std::reverse(s1.begin(), s1.end()); // reverse the string - if (s1 == s2) + if (s1 == s2) // check if reverse and original string are identical std::cout << "true"; else std::cout << "false"; From 4206ac2a291cc96a4627c4fe8e61636de81eb8e2 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 11:24:46 -0400 Subject: [PATCH 157/433] document paranthesis matching --- others/paranthesis_matching.cpp | 119 ++++++++++++++++---------------- 1 file changed, 59 insertions(+), 60 deletions(-) diff --git a/others/paranthesis_matching.cpp b/others/paranthesis_matching.cpp index d2bb4d39c3d..ef5da6e47cc 100644 --- a/others/paranthesis_matching.cpp +++ b/others/paranthesis_matching.cpp @@ -1,76 +1,75 @@ +/** + * @file + * @brief Perform paranthesis matching. \note Do not know the application of + * this, however. + * @note Implementation is C-type and does not utilize the C++ constructs + * @todo implement as a C++ class + */ #include -#include - -using namespace std; +#ifdef _MSC_VER +#include // Visual Studio C requires this include +#else +#include +#endif +/** check number */ #define MAX 100 -// -------------- stack -------------- - +//! @{-------------- stack -------------- +//! global stack char stack[MAX]; + +//! pointer to track stack index int top = -1; -void push(char ch) -{ - stack[++top] = ch; -} +//! push byte to stack variable +void push(char ch) { stack[++top] = ch; } -char pop() -{ - return stack[top--]; -} +//! pop a byte out of stack variable +char pop() { return stack[top--]; } -// -------------- end stack ----------- +//! @}-------------- end stack ----------- -char opening(char ch) -{ - switch (ch) - { - case '}': - return '{'; - case ']': - return '['; - case ')': - return '('; - case '>': - return '<'; - } +/** return opening paranthesis corresponding to the close paranthesis + * @param[in] ch closed paranthesis character + */ +char opening(char ch) { + switch (ch) { + case '}': + return '{'; + case ']': + return '['; + case ')': + return '('; + case '>': + return '<'; + } + return '\0'; } -int main() -{ - - string exp; - int valid = 1, i = 0; - cout << "Enter The Expression : "; - cin >> exp; +int main() { + std::string exp; + int valid = 1, i = 0; + std::cout << "Enter The Expression : "; + std::cin >> exp; - while (valid == 1 && i < exp.length()) - { - if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[' || exp[i] == '<') - { - push(exp[i]); - } - else if (top >= 0 && stack[top] == opening(exp[i])) - { - pop(); - } - else - { - valid = 0; - } - i++; - } + while (valid == 1 && i < exp.length()) { + if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[' || exp[i] == '<') { + push(exp[i]); + } else if (top >= 0 && stack[top] == opening(exp[i])) { + pop(); + } else { + valid = 0; + } + i++; + } - // makes sure the stack is empty after processsing (above) - if (valid == 1 && top == -1) - { - cout << "\nCorrect Expression"; - } - else - { - cout << "\nWrong Expression"; - } + // makes sure the stack is empty after processsing (above) + if (valid == 1 && top == -1) { + std::cout << "\nCorrect Expression"; + } else { + std::cout << "\nWrong Expression"; + } - return 0; + return 0; } From 34c3ce9c5e6d6bd3cf5e4058f13d5d93be736216 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 11:24:55 -0400 Subject: [PATCH 158/433] document pascals triangle --- others/pascal_triangle.cpp | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/others/pascal_triangle.cpp b/others/pascal_triangle.cpp index 063a6666a3a..4ea58f3f1e4 100644 --- a/others/pascal_triangle.cpp +++ b/others/pascal_triangle.cpp @@ -1,19 +1,38 @@ +/** + * @file + * @brief Pascal's triangle implementation + */ +#ifdef _MSC_VER +#include // required for Visual C +#else #include +#endif +#include #include +/** + * Print the triangle + * \param [in] arr 2D-array containing Pascal numbers + * \param [in] n depth of Pascal triangle to print + */ void show_pascal(int **arr, int n) { - // pint Pascal's Triangle for (int i = 0; i < n; ++i) { for (int j = 0; j < n + i; ++j) { if (arr[i][j] == 0) - std::cout << " "; + std::cout << std::setw(4) << " "; else - std::cout << arr[i][j]; + std::cout << std::setw(4) << arr[i][j]; } std::cout << std::endl; } } +/** + * Print the triangle + * \param [in,out] arr array containing Pascal numbers + * \param [in] n depth of Pascal triangle to print + * \result arr pointer returned + */ int **pascal_triangle(int **arr, int n) { for (int i = 0; i < n; ++i) { for (int j = n - i - 1; j < n + i; ++j) { @@ -27,6 +46,9 @@ int **pascal_triangle(int **arr, int n) { return arr; } +/** + * main function + */ int main() { int n = 0; From 00c8c0bfdbc4b1c7b7beed29c281c45e66861731 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 12:55:06 -0400 Subject: [PATCH 159/433] document primality test --- others/primality_test.cpp | 60 +++++++++++++++++++++++---------------- 1 file changed, 35 insertions(+), 25 deletions(-) diff --git a/others/primality_test.cpp b/others/primality_test.cpp index ce8fc1706a0..faec6589cff 100644 --- a/others/primality_test.cpp +++ b/others/primality_test.cpp @@ -1,32 +1,42 @@ +/** + * @file + * @brief [Primality test](https://en.wikipedia.org/wiki/Primality_test) + * implementation. + * + * A simple and efficient implementation of a function to test if a number is + * prime, based on the fact that + * > Every Prime number, except 2 and 3, are of the form \f$6k\pm1\f$ for + * > integer values of k. + * This gives a 3x speed improvement. + */ #include -using namespace std; -//A simple and efficient implementation of a function to test if a number is prime, based on the fact that -//Every Prime number, except 2 and 3 are of the form 6*k+1 or 6*k-1 for integer values of k. +/** Check if a number is prime + * \param[in] number number to check + * \returns true if prime else false + */ +bool IsPrime(int number) { + if (((!(number & 1)) && number != 2) || (number < 2) || + (number % 3 == 0 && number != 3)) + return false; -bool IsPrime(int number) -{ - if (((!(number & 1)) && number != 2) || (number < 2) || (number % 3 == 0 && number != 3)) - return false; - - for (int k = 1; 36 * k * k - 12 * k < number; ++k) - { - if ((number % (6 * k + 1) == 0) || (number % (6 * k - 1) == 0)) - return false; - } - return true; + for (int k = 1; 36 * k * k - 12 * k < number; ++k) { + if ((number % (6 * k + 1) == 0) || (number % (6 * k - 1) == 0)) + return false; + } + return true; } -int main() -{ - //Main Function - cout << "Enter the value of n to check if Prime\n"; - int n; - cin >> n; - if (IsPrime(n)) - cout << n << " is Prime" << endl; - else - cout << n << " is not Prime" << endl; +/** main function */ +int main() { + // Main Function + std::cout << "Enter the value of n to check if Prime\n"; + int n; + std::cin >> n; + if (IsPrime(n)) + std::cout << n << " is Prime" << std::endl; + else + std::cout << n << " is not Prime" << std::endl; - return 0; + return 0; } From be997d3da34367a6bc5f52fe719f6b72dd8a6cd4 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 13:39:58 -0400 Subject: [PATCH 160/433] updated documentation - NOTE TESTS FAIL @yanglbme this algorithm does not give right answers --- others/smallest-circle.cpp | 190 ++++++++++++++++++++++++++----------- 1 file changed, 132 insertions(+), 58 deletions(-) diff --git a/others/smallest-circle.cpp b/others/smallest-circle.cpp index 48437cd8681..7eb913cd1e9 100644 --- a/others/smallest-circle.cpp +++ b/others/smallest-circle.cpp @@ -1,121 +1,195 @@ +/** + * @file + * @brief Get centre and radius of the + * [smallest circle](https://en.wikipedia.org/wiki/Smallest-circle_problem) + * that circumscribes given set of points. + * + * @see [other + * implementation](https://www.nayuki.io/page/smallest-enclosing-circle) + */ +#include #include #include -#include -using namespace std; +/** Define a point */ +struct Point { + double x, /**< abscissa */ + y; /**< ordinate */ -struct Point -{ - double x, y; - Point(double a = 0.0, double b = 0.0) - { + /** construct a point + * \param [in] a absicca (default = 0.0) + * \param [in] b ordinate (default = 0.0) + */ + Point(double a = 0.0, double b = 0.0) { x = a; y = b; } }; -double LenghtLine(Point A, Point B) -{ - return sqrt(abs((B.x - A.x) * (B.x - A.x)) + abs((B.y - A.y) * (B.y - A.y))); +/** Compute the Euclidian distance between two points \f$A\equiv(x_1,y_1)\f$ and + * \f$B\equiv(x_2,y_2)\f$ using the formula: + * \f[d=\sqrt{\left(x_1-x_2\right)^2+\left(y_1-y_2\right)^2}\f] + * + * \param [in] A point A + * \param [in] B point B + * \return ditance + */ +double LenghtLine(const Point &A, const Point &B) { + double dx = B.x - A.x; + double dy = B.y - A.y; + return std::sqrt((dx * dx) + (dy * dy)); } -double TriangleArea(Point A, Point B, Point C) -{ +/** + * Compute the area of triangle formed by three points using [Heron's + * formula](https://en.wikipedia.org/wiki/Heron%27s_formula). + * If the lengths of the sides of the triangle are \f$a,\,b,\,c\f$ and + * \f$s=\displaystyle\frac{a+b+c}{2}\f$ is the semi-perimeter then the area is + * given by \f[A=\sqrt{s(s-a)(s-b)(s-c)}\f] + * \param [in] A vertex A + * \param [in] B vertex B + * \param [in] C vertex C + * \returns area of triangle + */ +double TriangleArea(const Point &A, const Point &B, const Point &C) { double a = LenghtLine(A, B); double b = LenghtLine(B, C); double c = LenghtLine(C, A); double p = (a + b + c) / 2; - return sqrt(p * (p - a) * (p - b) * (p - c)); + return std::sqrt(p * (p - a) * (p - b) * (p - c)); } -bool PointInCircle(vector &P, Point Center, double R) -{ - for (size_t i = 0; i < P.size(); i++) - { +/** + * Check if a set of points lie within given circle. This is true if the + * distance of all the points from the centre of the circle is less than the + * radius of the circle + * \param [in] P set of points to check + * \param [in] Center coordinates to centre of the circle + * \param [in] R radius of the circle + * \returns True if P lies on or within the circle + * \returns False if P lies outside the circle + */ +bool PointInCircle(const std::vector &P, const Point &Center, double R) { + for (size_t i = 0; i < P.size(); i++) { if (LenghtLine(P[i], Center) > R) return false; } return true; } -double circle(vector P) -{ +/** + * Find the centre and radius of a circle enclosing a set of points.\n + * The function returns the radius of the circle and prints the coordinated of + * the centre of the circle. + * \param [in] P vector of points + * \returns radius of the circle + */ +double circle(const std::vector &P) { double minR = INT8_MAX; double R; Point C; Point minC; - for (size_t i = 0; i < P.size() - 2; i++) - for (size_t j = i + 1; j < P.size(); j++) - for (size_t k = j + 1; k < P.size(); k++) - { - C.x = -0.5 * ((P[i].y * (P[j].x * P[j].x + P[j].y * P[j].y - P[k].x * P[k].x - P[k].y * P[k].y) + P[j].y * (P[k].x * P[k].x + P[k].y * P[k].y - P[i].x * P[i].x - P[i].y * P[i].y) + P[k].y * (P[i].x * P[i].x + P[i].y * P[i].y - P[j].x * P[j].x - P[j].y * P[j].y)) / (P[i].x * (P[j].y - P[k].y) + P[j].x * (P[k].y - P[i].y) + P[k].x * (P[i].y - P[j].y))); - C.y = 0.5 * ((P[i].x * (P[j].x * P[j].x + P[j].y * P[j].y - P[k].x * P[k].x - P[k].y * P[k].y) + P[j].x * (P[k].x * P[k].x + P[k].y * P[k].y - P[i].x * P[i].x - P[i].y * P[i].y) + P[k].x * (P[i].x * P[i].x + P[i].y * P[i].y - P[j].x * P[j].x - P[j].y * P[j].y)) / (P[i].x * (P[j].y - P[k].y) + P[j].x * (P[k].y - P[i].y) + P[k].x * (P[i].y - P[j].y))); - R = (LenghtLine(P[i], P[j]) * LenghtLine(P[j], P[k]) * LenghtLine(P[k], P[i])) / (4 * TriangleArea(P[i], P[j], P[k])); - if (!PointInCircle(P, C, R)) - { - continue; - } - if (R <= minR) - { - minR = R; - minC = C; + + /* This code is invalid and does not give correct result for TEST 3 + // for each point in the list + for (size_t i = 0; i < P.size() - 2; i++) + // for every subsequent point in the list + for (size_t j = i + 1; j < P.size(); j++) + // for every subsequent point in the list + for (size_t k = j + 1; k < P.size(); k++) { + // here, we now have picked three points from the given set + of + // points that we can use + // viz., P[i], P[j] and P[k] + C.x = -0.5 * ((P[i].y * (P[j].x * P[j].x + P[j].y * P[j].y - + P[k].x * P[k].x - P[k].y * P[k].y) + + P[j].y * (P[k].x * P[k].x + P[k].y * P[k].y - P[i].x * P[i].x - P[i].y + * P[i].y) + P[k].y * (P[i].x * P[i].x + P[i].y * P[i].y - P[j].x * P[j].x + - P[j].y * P[j].y)) / (P[i].x * (P[j].y - P[k].y) + P[j].x * (P[k].y - + P[i].y) + P[k].x * (P[i].y - P[j].y))); C.y = 0.5 * ((P[i].x * (P[j].x * + P[j].x + P[j].y * P[j].y - P[k].x * P[k].x - P[k].y * P[k].y) + P[j].x * + (P[k].x * P[k].x + P[k].y * P[k].y - P[i].x * P[i].x - P[i].y * P[i].y) + + P[k].x * (P[i].x * P[i].x + P[i].y * P[i].y - + P[j].x * P[j].x - P[j].y * P[j].y)) + / (P[i].x * (P[j].y - P[k].y) + P[j].x * (P[k].y - P[i].y) + P[k].x * + (P[i].y - P[j].y))); R = (LenghtLine(P[i], P[j]) * LenghtLine(P[j], P[k]) + * LenghtLine(P[k], P[i])) / (4 * TriangleArea(P[i], P[j], P[k])); if + (!PointInCircle(P, C, R)) { continue; + } + if (R <= minR) { + minR = R; + minC = C; + } } - } + */ + + // for each point in the list for (size_t i = 0; i < P.size() - 1; i++) - for (size_t j = i + 1; j < P.size(); j++) - { + // for every subsequent point in the list + for (size_t j = i + 1; j < P.size(); j++) { C.x = (P[i].x + P[j].x) / 2; C.y = (P[i].y + P[j].y) / 2; R = LenghtLine(C, P[i]); - if (!PointInCircle(P, C, R)) - { + if (!PointInCircle(P, C, R)) { continue; } - if (R <= minR) - { + if (R <= minR) { minR = R; minC = C; } } - cout << minC.x << " " << minC.y << endl; + std::cout << minC.x << " " << minC.y << std::endl; return minR; } -void test() -{ - vector Pv(5); +/** Test case: result should be: + * \n Circle with + * \n radius 3.318493136080724 + * \n centre at (3.0454545454545454 1.3181818181818181) + */ +void test() { + std::vector Pv(5); Pv.push_back(Point(0, 0)); Pv.push_back(Point(1, 3)); Pv.push_back(Point(4, 1)); Pv.push_back(Point(5, 4)); Pv.push_back(Point(3, -2)); - cout << circle(Pv) << endl; + std::cout << circle(Pv) << std::endl; } -void test2() -{ - vector Pv(4); +/** Test case: result should be: + * \n Circle with + * \n radius 1.4142135623730951 + * \n centre at (1.0 1.0) + */ +void test2() { + std::vector Pv(4); Pv.push_back(Point(0, 0)); Pv.push_back(Point(0, 2)); Pv.push_back(Point(2, 2)); Pv.push_back(Point(2, 0)); - cout << circle(Pv) << endl; + std::cout << circle(Pv) << std::endl; } -void test3() -{ - vector Pv(3); +/** Test case: result should be: + * \n Circle with + * \n radius 1.821078397711709 + * \n centre at (2.142857142857143 1.7857142857142856) + */ +void test3() { + std::vector Pv(3); Pv.push_back(Point(0.5, 1)); Pv.push_back(Point(3.5, 3)); Pv.push_back(Point(2.5, 0)); - cout << circle(Pv) << endl; + std::cout << circle(Pv) << std::endl; } -int main() -{ + +/** Main program */ +int main() { test(); - cout << endl; + std::cout << std::endl; test2(); - cout << endl; + std::cout << std::endl; test3(); return 0; } From 9da5e0cecf583d35be1eae46638374bc4f12f9f9 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 14:07:27 -0400 Subject: [PATCH 161/433] re-enable the commented algorithm --- others/smallest-circle.cpp | 81 +++++++++++++++++++++----------------- 1 file changed, 44 insertions(+), 37 deletions(-) diff --git a/others/smallest-circle.cpp b/others/smallest-circle.cpp index 7eb913cd1e9..8f023185314 100644 --- a/others/smallest-circle.cpp +++ b/others/smallest-circle.cpp @@ -20,7 +20,7 @@ struct Point { * \param [in] a absicca (default = 0.0) * \param [in] b ordinate (default = 0.0) */ - Point(double a = 0.0, double b = 0.0) { + Point(double a = 0.f, double b = 0.f) { x = a; y = b; } @@ -90,38 +90,45 @@ double circle(const std::vector &P) { Point C; Point minC; - /* This code is invalid and does not give correct result for TEST 3 - // for each point in the list - for (size_t i = 0; i < P.size() - 2; i++) + /* This code is invalid and does not give correct result for TEST 3 */ + // for each point in the list + for (size_t i = 0; i < P.size() - 2; i++) + // for every subsequent point in the list + for (size_t j = i + 1; j < P.size(); j++) // for every subsequent point in the list - for (size_t j = i + 1; j < P.size(); j++) - // for every subsequent point in the list - for (size_t k = j + 1; k < P.size(); k++) { - // here, we now have picked three points from the given set - of - // points that we can use - // viz., P[i], P[j] and P[k] - C.x = -0.5 * ((P[i].y * (P[j].x * P[j].x + P[j].y * P[j].y - - P[k].x * P[k].x - P[k].y * P[k].y) - + P[j].y * (P[k].x * P[k].x + P[k].y * P[k].y - P[i].x * P[i].x - P[i].y - * P[i].y) + P[k].y * (P[i].x * P[i].x + P[i].y * P[i].y - P[j].x * P[j].x - - P[j].y * P[j].y)) / (P[i].x * (P[j].y - P[k].y) + P[j].x * (P[k].y - - P[i].y) + P[k].x * (P[i].y - P[j].y))); C.y = 0.5 * ((P[i].x * (P[j].x * - P[j].x + P[j].y * P[j].y - P[k].x * P[k].x - P[k].y * P[k].y) + P[j].x * - (P[k].x * P[k].x + P[k].y * P[k].y - P[i].x * P[i].x - P[i].y * P[i].y) + - P[k].x * (P[i].x * P[i].x + P[i].y * P[i].y - - P[j].x * P[j].x - P[j].y * P[j].y)) - / (P[i].x * (P[j].y - P[k].y) + P[j].x * (P[k].y - P[i].y) + P[k].x * - (P[i].y - P[j].y))); R = (LenghtLine(P[i], P[j]) * LenghtLine(P[j], P[k]) - * LenghtLine(P[k], P[i])) / (4 * TriangleArea(P[i], P[j], P[k])); if - (!PointInCircle(P, C, R)) { continue; - } - if (R <= minR) { - minR = R; - minC = C; - } + for (size_t k = j + 1; k < P.size(); k++) { + // here, we now have picked three points from the given set of + // points that we can use + // viz., P[i], P[j] and P[k] + C.x = -0.5 * ((P[i].y * (P[j].x * P[j].x + P[j].y * P[j].y - + P[k].x * P[k].x - P[k].y * P[k].y) + + P[j].y * (P[k].x * P[k].x + P[k].y * P[k].y - + P[i].x * P[i].x - P[i].y * P[i].y) + + P[k].y * (P[i].x * P[i].x + P[i].y * P[i].y - + P[j].x * P[j].x - P[j].y * P[j].y)) / + (P[i].x * (P[j].y - P[k].y) + + P[j].x * (P[k].y - P[i].y) + + P[k].x * (P[i].y - P[j].y))); + C.y = 0.5 * ((P[i].x * (P[j].x * P[j].x + P[j].y * P[j].y - + P[k].x * P[k].x - P[k].y * P[k].y) + + P[j].x * (P[k].x * P[k].x + P[k].y * P[k].y - + P[i].x * P[i].x - P[i].y * P[i].y) + + P[k].x * (P[i].x * P[i].x + P[i].y * P[i].y - + P[j].x * P[j].x - P[j].y * P[j].y)) / + (P[i].x * (P[j].y - P[k].y) + + P[j].x * (P[k].y - P[i].y) + + P[k].x * (P[i].y - P[j].y))); + R = (LenghtLine(P[i], P[j]) * LenghtLine(P[j], P[k]) * + LenghtLine(P[k], P[i])) / + (4 * TriangleArea(P[i], P[j], P[k])); + if (!PointInCircle(P, C, R)) { + continue; } - */ + if (R <= minR) { + minR = R; + minC = C; + } + } // for each point in the list for (size_t i = 0; i < P.size() - 1; i++) @@ -145,42 +152,42 @@ double circle(const std::vector &P) { /** Test case: result should be: * \n Circle with * \n radius 3.318493136080724 - * \n centre at (3.0454545454545454 1.3181818181818181) + * \n centre at (3.0454545454545454, 1.3181818181818181) */ void test() { - std::vector Pv(5); Pv.push_back(Point(0, 0)); Pv.push_back(Point(1, 3)); Pv.push_back(Point(4, 1)); Pv.push_back(Point(5, 4)); Pv.push_back(Point(3, -2)); + std::vector Pv; std::cout << circle(Pv) << std::endl; } /** Test case: result should be: * \n Circle with * \n radius 1.4142135623730951 - * \n centre at (1.0 1.0) + * \n centre at (1.0, 1.0) */ void test2() { - std::vector Pv(4); Pv.push_back(Point(0, 0)); Pv.push_back(Point(0, 2)); Pv.push_back(Point(2, 2)); Pv.push_back(Point(2, 0)); + std::vector Pv; std::cout << circle(Pv) << std::endl; } /** Test case: result should be: * \n Circle with * \n radius 1.821078397711709 - * \n centre at (2.142857142857143 1.7857142857142856) + * \n centre at (2.142857142857143, 1.7857142857142856) */ void test3() { - std::vector Pv(3); Pv.push_back(Point(0.5, 1)); Pv.push_back(Point(3.5, 3)); Pv.push_back(Point(2.5, 0)); + std::vector Pv; std::cout << circle(Pv) << std::endl; } From 5c7db7aba3e3da22ff9f877ef3d74a326eb48158 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 14:09:24 -0400 Subject: [PATCH 162/433] fixed syntax --- others/smallest-circle.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/others/smallest-circle.cpp b/others/smallest-circle.cpp index 8f023185314..a0a2302faa2 100644 --- a/others/smallest-circle.cpp +++ b/others/smallest-circle.cpp @@ -155,12 +155,12 @@ double circle(const std::vector &P) { * \n centre at (3.0454545454545454, 1.3181818181818181) */ void test() { + std::vector Pv; Pv.push_back(Point(0, 0)); + Pv.push_back(Point(5, 4)); Pv.push_back(Point(1, 3)); Pv.push_back(Point(4, 1)); - Pv.push_back(Point(5, 4)); Pv.push_back(Point(3, -2)); - std::vector Pv; std::cout << circle(Pv) << std::endl; } @@ -170,11 +170,11 @@ void test() { * \n centre at (1.0, 1.0) */ void test2() { + std::vector Pv; Pv.push_back(Point(0, 0)); Pv.push_back(Point(0, 2)); Pv.push_back(Point(2, 2)); Pv.push_back(Point(2, 0)); - std::vector Pv; std::cout << circle(Pv) << std::endl; } @@ -184,10 +184,10 @@ void test2() { * \n centre at (2.142857142857143, 1.7857142857142856) */ void test3() { + std::vector Pv; Pv.push_back(Point(0.5, 1)); Pv.push_back(Point(3.5, 3)); Pv.push_back(Point(2.5, 0)); - std::vector Pv; std::cout << circle(Pv) << std::endl; } From c43e76286d123721c829f9b9cdeda6d9705d70ee Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 14:10:24 -0400 Subject: [PATCH 163/433] mark constructor function call as explicit --- others/smallest-circle.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/others/smallest-circle.cpp b/others/smallest-circle.cpp index a0a2302faa2..c1bd74de042 100644 --- a/others/smallest-circle.cpp +++ b/others/smallest-circle.cpp @@ -20,7 +20,7 @@ struct Point { * \param [in] a absicca (default = 0.0) * \param [in] b ordinate (default = 0.0) */ - Point(double a = 0.f, double b = 0.f) { + explicit Point(double a = 0.f, double b = 0.f) { x = a; y = b; } From 0994e6e028dc56965e98f8943680e40820926b1f Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 14:23:52 -0400 Subject: [PATCH 164/433] minor documetnation --- others/smallest-circle.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/others/smallest-circle.cpp b/others/smallest-circle.cpp index c1bd74de042..9ee4353eb4e 100644 --- a/others/smallest-circle.cpp +++ b/others/smallest-circle.cpp @@ -85,7 +85,7 @@ bool PointInCircle(const std::vector &P, const Point &Center, double R) { * \returns radius of the circle */ double circle(const std::vector &P) { - double minR = INT8_MAX; + double minR = INFINITY; double R; Point C; Point minC; @@ -134,6 +134,7 @@ double circle(const std::vector &P) { for (size_t i = 0; i < P.size() - 1; i++) // for every subsequent point in the list for (size_t j = i + 1; j < P.size(); j++) { + // check for diameterically opposite points C.x = (P[i].x + P[j].x) / 2; C.y = (P[i].y + P[j].y) / 2; R = LenghtLine(C, P[i]); @@ -182,12 +183,14 @@ void test2() { * \n Circle with * \n radius 1.821078397711709 * \n centre at (2.142857142857143, 1.7857142857142856) + * @todo This test fails */ void test3() { std::vector Pv; Pv.push_back(Point(0.5, 1)); Pv.push_back(Point(3.5, 3)); Pv.push_back(Point(2.5, 0)); + Pv.push_back(Point(2, 1.5)); std::cout << circle(Pv) << std::endl; } From bc8fda9056f0fd52d42bd17bf58ce8309a6f3b0e Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 14:25:00 -0400 Subject: [PATCH 165/433] sparse matrix docs --- others/sparse_matrix.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/others/sparse_matrix.cpp b/others/sparse_matrix.cpp index d9878fda425..a358f0da472 100644 --- a/others/sparse_matrix.cpp +++ b/others/sparse_matrix.cpp @@ -1,10 +1,11 @@ /** @file * A sparse matrix is a matrix which has number of zeroes greater than - * \f$\frac{m*n}{2}\f$, where m and n are the dimensions of the matrix. + * \f$\frac{m\times n}{2}\f$, where m and n are the dimensions of the matrix. */ #include +/** main function */ int main() { int m, n; int counterZeros = 0; @@ -30,7 +31,8 @@ int main() { // counts the zero's for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { - if (a[i][j] == 0) counterZeros++; // Counting number of zeroes + if (a[i][j] == 0) + counterZeros++; // Counting number of zeroes } } From 10bfe1399592c924f5756b0d1b0b8f0e78ceef9f Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 14:29:44 -0400 Subject: [PATCH 166/433] addendum cpplint bugfix 22b375c058cf2eec6c47990ae1b46e08d6cdd3ee --- .github/workflows/cpplint_modified_files.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/cpplint_modified_files.yml b/.github/workflows/cpplint_modified_files.yml index 8de6a5e4115..e21a5114e5d 100644 --- a/.github/workflows/cpplint_modified_files.yml +++ b/.github/workflows/cpplint_modified_files.yml @@ -37,7 +37,8 @@ jobs: sys.exit(0) print("cpplint:") - subprocess.run(["cpplint", "--filter=-legal/copyright"] + cpp_files, check=True, text=True) + for cpp_file in cpp_files: + subprocess.run(["cpplint", "--filter=-legal/copyright"] + cpp_file, check=True, text=True) print("g++:") # compile_exts = tuple(".c .c++ .cc .cpp .cu .cxx".split()) From 05beeb5104f596523ec96e13c8c52b2e79dbae22 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 14:31:20 -0400 Subject: [PATCH 167/433] instead of concatenate, pass filename as argument --- .github/workflows/cpplint_modified_files.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/cpplint_modified_files.yml b/.github/workflows/cpplint_modified_files.yml index e21a5114e5d..a5aa6a65263 100644 --- a/.github/workflows/cpplint_modified_files.yml +++ b/.github/workflows/cpplint_modified_files.yml @@ -38,7 +38,7 @@ jobs: print("cpplint:") for cpp_file in cpp_files: - subprocess.run(["cpplint", "--filter=-legal/copyright"] + cpp_file, check=True, text=True) + subprocess.run(["cpplint", "--filter=-legal/copyright", cpp_file], check=True, text=True) print("g++:") # compile_exts = tuple(".c .c++ .cc .cpp .cu .cxx".split()) From e7c6217097df8331a90233fede6b88467eb7a9a0 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 14:33:48 -0400 Subject: [PATCH 168/433] filename must not contain spaces or dashes --- others/{smallest-circle.cpp => smallest_circle.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename others/{smallest-circle.cpp => smallest_circle.cpp} (100%) diff --git a/others/smallest-circle.cpp b/others/smallest_circle.cpp similarity index 100% rename from others/smallest-circle.cpp rename to others/smallest_circle.cpp From ec8f4105582abb0e4e3d803b48b504dd73f8f199 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 28 May 2020 18:34:08 +0000 Subject: [PATCH 169/433] updating DIRECTORY.md --- DIRECTORY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index bbf405b7f9d..bd84673f04b 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -148,7 +148,7 @@ * [Paranthesis Matching](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/paranthesis_matching.cpp) * [Pascal Triangle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/pascal_triangle.cpp) * [Primality Test](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/primality_test.cpp) - * [Smallest-Circle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/smallest-circle.cpp) + * [Smallest Circle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/smallest_circle.cpp) * [Sparse Matrix](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/sparse_matrix.cpp) * [Spiral Print](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/spiral_print.cpp) * [Stairs Pattern](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/stairs_pattern.cpp) From 4e12f5361f1ba6bdca8e7f3cb703ac04e514cb24 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 15:17:53 -0400 Subject: [PATCH 170/433] document string_fibonacci --- others/string_fibonacci.cpp | 80 ++++++++++++++++++++----------------- 1 file changed, 43 insertions(+), 37 deletions(-) diff --git a/others/string_fibonacci.cpp b/others/string_fibonacci.cpp index e5475eec9aa..2617fc18fa2 100644 --- a/others/string_fibonacci.cpp +++ b/others/string_fibonacci.cpp @@ -1,82 +1,88 @@ -//This Programme returns the Nth fibonacci as a string. -//The method used is manual addition with carry and placing it in a string which is called string addition -//This makes it have no bounds or limits +/** + * @file + * @brief This Programme returns the Nth fibonacci as a string. + * + * The method used is manual addition with carry and placing it in a string + * which is called string addition This makes it have no bounds or limits + * + * @see fibonacci_large.cpp, fibonacci_fast.cpp, fibonacci.cpp + */ #include -#include +#ifdef _MSC_VER +#include // use this for MS Visual C +#else +#include // otherwise +#endif -using namespace std; - -string add(string a, string b) -{ - string temp = ""; +/** + * function to add two string numbers + * \param [in] a first number in string to add + * \param [in] b second number in string to add + * \returns sum as a std::string + */ +std::string add(std::string a, std::string b) { + std::string temp = ""; // carry flag int carry = 0; // fills up with zeros - while ((int)a.length() < (int)b.length()) - { + while ((int)a.length() < (int)b.length()) { a = "0" + a; } // fills up with zeros - while ((int)b.length() < (int)a.length()) - { + while ((int)b.length() < (int)a.length()) { b = "0" + b; } // adds the numbers a and b - for (int i = a.length() - 1; i >= 0; i--) - { + for (int i = a.length() - 1; i >= 0; i--) { char val = (char)(((a[i] - 48) + (b[i] - 48)) + 48 + carry); - if (val > 57) - { + if (val > 57) { carry = 1; val -= 10; - } - else - { + } else { carry = 0; } temp = val + temp; } // processes the carry flag - if (carry == 1) - { + if (carry == 1) { temp = "1" + temp; } // removes leading zeros. - while (temp[0] == '0' && temp.length() > 1) - { + while (temp[0] == '0' && temp.length() > 1) { temp = temp.substr(1); } return temp; } -void fib_Accurate(long long n) -{ - string tmp = ""; - string fibMinus1 = "1"; - string fibMinus2 = "0"; - for (long long i = 0; i < n; i++) - { +/** Fibonacci iterator + * \param [in] n n^th Fibonacci number + */ +void fib_Accurate(long long n) { + std::string tmp = ""; + std::string fibMinus1 = "1"; + std::string fibMinus2 = "0"; + for (long long i = 0; i < n; i++) { tmp = add(fibMinus1, fibMinus2); fibMinus2 = fibMinus1; fibMinus1 = tmp; } - cout << fibMinus2; + std::cout << fibMinus2; } -int main() -{ +/** main function */ +int main() { int n; - cout << "Enter whatever number N you want to find the fibonacci of\n"; - cin >> n; - cout << n << " th Fibonacci is \n"; + std::cout << "Enter whatever number N you want to find the fibonacci of\n"; + std::cin >> n; + std::cout << n << " th Fibonacci is \n"; fib_Accurate(n); return 0; From ea8aaf963d739cae311f338bafc746f2fea37ee5 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 15:18:48 -0400 Subject: [PATCH 171/433] move string fibonacci to math folder --- {others => math}/string_fibonacci.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {others => math}/string_fibonacci.cpp (100%) diff --git a/others/string_fibonacci.cpp b/math/string_fibonacci.cpp similarity index 100% rename from others/string_fibonacci.cpp rename to math/string_fibonacci.cpp From 71bcc27e11e49901b695d1da9cf7f3bc3adaa9f6 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 28 May 2020 19:19:13 +0000 Subject: [PATCH 172/433] updating DIRECTORY.md --- DIRECTORY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index bd84673f04b..51e840ef41c 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -124,6 +124,7 @@ * [Primes Up To Billion](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/primes_up_to_billion.cpp) * [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/sieve_of_eratosthenes.cpp) * [Sqrt Double](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/sqrt_double.cpp) + * [String Fibonacci](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/string_fibonacci.cpp) ## Operations On Datastructures * [Array Left Rotation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Array%20Left%20Rotation.cpp) @@ -152,7 +153,6 @@ * [Sparse Matrix](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/sparse_matrix.cpp) * [Spiral Print](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/spiral_print.cpp) * [Stairs Pattern](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/stairs_pattern.cpp) - * [String Fibonacci](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/string_fibonacci.cpp) * [Tower Of Hanoi](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/tower_of_hanoi.cpp) * [Vector Important Functions](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/vector_important_functions.cpp) From 2216628678419a3b751162cbabf916caf8fd7543 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 15:19:27 -0400 Subject: [PATCH 173/433] update math fibonacci see-also links --- math/fibonacci.cpp | 2 +- math/fibonacci_large.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/math/fibonacci.cpp b/math/fibonacci.cpp index da7736564b3..e15cfc0ccff 100644 --- a/math/fibonacci.cpp +++ b/math/fibonacci.cpp @@ -6,7 +6,7 @@ * integer as input. * \f[\text{fib}(n) = \text{fib}(n-1) + \text{fib}(n-2)\f] * - * @see fibonacci_large.cpp, fibonacci_fast.cpp + * @see fibonacci_large.cpp, fibonacci_fast.cpp, string_fibonacci.cpp */ #include #include diff --git a/math/fibonacci_large.cpp b/math/fibonacci_large.cpp index 4545fdc9f9d..d9dbff79968 100644 --- a/math/fibonacci_large.cpp +++ b/math/fibonacci_large.cpp @@ -7,7 +7,7 @@ * Took 0.608246 seconds to compute 50,000^th Fibonacci * number that contains 10450 digits! * - * @see fibonacci.cpp, fibonacci_fast.cpp + * @see fibonacci.cpp, fibonacci_fast.cpp, string_fibonacci.cpp */ #include From 51affd4aa4f135b3c04b354660ebb84bf5862cf2 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 15:27:49 -0400 Subject: [PATCH 174/433] document spiral print --- others/spiral_print.cpp | 83 +++++++++++++++++++++-------------------- 1 file changed, 43 insertions(+), 40 deletions(-) diff --git a/others/spiral_print.cpp b/others/spiral_print.cpp index e6e6899ef6d..02dc3183aee 100644 --- a/others/spiral_print.cpp +++ b/others/spiral_print.cpp @@ -1,78 +1,81 @@ +/** + * @file + * @brief Print the elements of a matrix traversing it spirally + */ #include -using namespace std; - -void genArray(int a[][10], int r, int c) -{ +/** Arrange sequence of numbers from '1' in a matrix form + * \param [out] a matrix to fill + * \param [in] r number of rows + * \param [in] c number of columns + */ +void genArray(int **a, int r, int c) { int value = 1; - for (int i = 0; i < r; i++) - { - for (int j = 0; j < c; j++) - { + for (int i = 0; i < r; i++) { + for (int j = 0; j < c; j++) { a[i][j] = value; - cout << a[i][j] << " "; + std::cout << a[i][j] << " "; value++; } - cout << endl; + std::cout << std::endl; } } -void spiralPrint(int a[][10], int r, int c) -{ +/** Traverse the matrix spirally and print the sequence of elements + * \param [in] a matrix to read from + * \param [in] r number of rows + * \param [in] c number of columns + */ +void spiralPrint(int **a, int r, int c) { int startRow = 0, endRow = r - 1; int startCol = 0, endCol = c - 1; int cnt = 0; - while (startRow <= endRow && startCol <= endCol) - { - - ///Print start row - for (int i = startCol; i <= endCol; i++, cnt++) - { - cout << a[startRow][i] << " "; + while (startRow <= endRow && startCol <= endCol) { + /// Print start row + for (int i = startCol; i <= endCol; i++, cnt++) { + std::cout << a[startRow][i] << " "; } startRow++; - ///Print the end col - for (int i = startRow; i <= endRow; i++, cnt++) - { - cout << a[i][endCol] << " "; + /// Print the end col + for (int i = startRow; i <= endRow; i++, cnt++) { + std::cout << a[i][endCol] << " "; } endCol--; - ///Print the end row - if (cnt == r * c) - { + /// Print the end row + if (cnt == r * c) { break; } - for (int i = endCol; i >= startCol; i--, cnt++) - { - cout << a[endRow][i] << " "; + for (int i = endCol; i >= startCol; i--, cnt++) { + std::cout << a[endRow][i] << " "; } endRow--; - ///Print the start Col - if (cnt == r * c) - { + /// Print the start Col + if (cnt == r * c) { break; } - for (int i = endRow; i >= startRow; i--, cnt++) - { - cout << a[i][startCol] << " "; + for (int i = endRow; i >= startRow; i--, cnt++) { + std::cout << a[i][startCol] << " "; } startCol++; } } -int main() -{ - int a[10][10]; - +/** main function */ +int main() { int r, c; - cin >> r >> c; + std::cin >> r >> c; + int **a = new int *[r]; + for (int i = 0; i < r; i++) a[i] = new int[c]; + genArray(a, r, c); spiralPrint(a, r, c); + for (int i = 0; i < r; i++) delete[] a[i]; + delete[] a; return 0; } From 1e3247895045243e4e45f2ae6b60f6fb771805ce Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 15:27:58 -0400 Subject: [PATCH 175/433] document stairs print --- others/stairs_pattern.cpp | 60 +++++++++++++++++++++------------------ 1 file changed, 32 insertions(+), 28 deletions(-) diff --git a/others/stairs_pattern.cpp b/others/stairs_pattern.cpp index 281446a2fbf..a3b8b0a44d6 100644 --- a/others/stairs_pattern.cpp +++ b/others/stairs_pattern.cpp @@ -1,31 +1,35 @@ -/* -This program is use to print the following pattern - ** - ** - **** - **** - ****** - ****** -******** -******** -where number of pairs line is given by user +/** + * @file +@brief This program is use to print the following pattern
+   \*\*
+   \*\*
+  \*\*\*\*
+  \*\*\*\*
+ \*\*\*\*\*\*
+ \*\*\*\*\*\*
+\*\*\*\*\*\*\*\*
+********
+where number of pairs line is given by user */ -#include +#include + +/** main function */ int main() { -int l, st = 2, x, r, z, n, sp; -std::cout << "enter Index "; -std::cin >> x; -z = x; -for (r = 1; r <= x; r++) { -z = z - 1; -for (n = 1; n <= 2; n++) { -for (sp = 1; sp <= z; sp++) { -std::cout << " "; + int l, st = 2, x, r, z, n, sp; + std::cout << "enter Index "; + std::cin >> x; + z = x; + for (r = 1; r <= x; r++) { + z = z - 1; + for (n = 1; n <= 2; n++) { + for (sp = 1; sp <= z; sp++) { + std::cout << " "; + } + for (l = 1; l <= st; l++) { + std::cout << "*"; + } + std::cout << std::endl; + } + st = st + 2; + } } -for (l = 1; l <= st; l++) { -std::cout << "*"; -} -std::cout <<"\n"; -} -st = st + 2; -}} From 1e5f97c042564ffccf9226228b186752c82db084 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 15:50:35 -0400 Subject: [PATCH 176/433] document towers of hanoi --- others/tower_of_hanoi.cpp | 123 ++++++++++++++++++++------------------ 1 file changed, 66 insertions(+), 57 deletions(-) diff --git a/others/tower_of_hanoi.cpp b/others/tower_of_hanoi.cpp index 5783d6a9882..d6c22961707 100644 --- a/others/tower_of_hanoi.cpp +++ b/others/tower_of_hanoi.cpp @@ -1,73 +1,82 @@ +/** + * @file + * @brief Solve the [Tower of + * Hanoi](https://en.wikipedia.org/wiki/Tower_of_Hanoi) problem. + */ #include -using namespace std; -struct tower -{ - int values[10]; - int top; +/** + * Define the state of tower + */ +struct tower { + //! Values in the tower + int values[10]; + //! top tower ID + int top; } F, U, T; -void show() -{ - cout << "\n\n\tF : "; - for (int i = 0; i < F.top; i++) - { - cout << F.values[i] << "\t"; - } - cout << "\n\tU : "; - for (int i = 0; i < U.top; i++) - { - cout << U.values[i] << "\t"; - } - cout << "\n\tT : "; - for (int i = 0; i < T.top; i++) - { - cout << T.values[i] << "\t"; - } +/** Display the towers */ +void show() { + std::cout << "\n\n\tF : "; + for (int i = 0; i < F.top; i++) { + std::cout << F.values[i] << "\t"; + } + std::cout << "\n\tU : "; + for (int i = 0; i < U.top; i++) { + std::cout << U.values[i] << "\t"; + } + std::cout << "\n\tT : "; + for (int i = 0; i < T.top; i++) { + std::cout << T.values[i] << "\t"; + } } -void mov(tower &From, tower &To) -{ - --From.top; - To.values[To.top] = From.values[From.top]; - ++To.top; +/** Move one disc from one tower to another + * \param [in,out] From tower to move disk *from* + * \param [in,out] To tower to move disk *to* + */ +void mov(tower &From, tower &To) { + --From.top; + To.values[To.top] = From.values[From.top]; + ++To.top; } -void TH(int n, tower &From, tower &Using, tower &To) -{ - - if (n == 1) - { - mov(From, To); - show(); - } - else - { - TH(n - 1, From, To, Using); - mov(From, To); - show(); - TH(n - 1, Using, From, To); - } +/** + * Recursive algorithm to solve the puzzle + * \param [in] n starting number of disks + * \param [in,out] From tower to move disks from + * \param [in,out] Using temporary tower for the puzzle + * \param [in,out] To tower to move disk to + */ +void TH(int n, tower &From, tower &Using, tower &To) { + if (n == 1) { + mov(From, To); + show(); + } else { + TH(n - 1, From, To, Using); + mov(From, To); + show(); + TH(n - 1, Using, From, To); + } } -int main() -{ - F.top = 0; - U.top = 0; - T.top = 0; +/** Main function */ +int main() { + F.top = 0; + U.top = 0; + T.top = 0; - int no; + int no; - cout << "\nEnter number of discs : "; - cin >> no; + std::cout << "\nEnter number of discs : "; + std::cin >> no; - for (int i = no; i > 0; i--) - { - F.values[F.top++] = i; - }; + for (int i = no; i > 0; i--) { + F.values[F.top++] = i; + } - show(); - TH(no, F, U, T); + show(); + TH(no, F, U, T); - return 0; + return 0; } From 2412f95964221bf7707ad435b91ba5179e8e47a0 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 15:55:46 -0400 Subject: [PATCH 177/433] document vector sort, reverse example --- others/vector_important_functions.cpp | 60 +++++++++++++-------------- 1 file changed, 29 insertions(+), 31 deletions(-) diff --git a/others/vector_important_functions.cpp b/others/vector_important_functions.cpp index e0a70eedacd..d23ff9c978d 100644 --- a/others/vector_important_functions.cpp +++ b/others/vector_important_functions.cpp @@ -1,45 +1,43 @@ -// A C++ program to demonstrate working of sort(), -// reverse() +/** + * @file + * @brief A C++ program to demonstrate working of std::sort(), std::reverse() + */ #include #include +#include // For accumulate operation #include -#include //For accumulate operation -using namespace std; -int main() -{ - // Initializing vector with array values - int arr[] = {10, 20, 5, 23 ,42 , 15}; - int n = sizeof(arr)/sizeof(arr[0]); - vector vect(arr, arr+n); +/** Main function */ +int main() { + // Initializing vector with array values + int arr[] = {10, 20, 5, 23, 42, 15}; + int n = sizeof(arr) / sizeof(arr[0]); + std::vector vect(arr, arr + n); - cout << "Vector is: "; - for (int i=0; i Date: Thu, 28 May 2020 15:59:28 -0400 Subject: [PATCH 178/433] remove un-necessary typecast & use uint64_t --- math/string_fibonacci.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/math/string_fibonacci.cpp b/math/string_fibonacci.cpp index 2617fc18fa2..eb9b6d7e1a7 100644 --- a/math/string_fibonacci.cpp +++ b/math/string_fibonacci.cpp @@ -28,18 +28,18 @@ std::string add(std::string a, std::string b) { int carry = 0; // fills up with zeros - while ((int)a.length() < (int)b.length()) { + while (a.length() < b.length()) { a = "0" + a; } // fills up with zeros - while ((int)b.length() < (int)a.length()) { + while (b.length() < a.length()) { b = "0" + b; } // adds the numbers a and b for (int i = a.length() - 1; i >= 0; i--) { - char val = (char)(((a[i] - 48) + (b[i] - 48)) + 48 + carry); + char val = static_cast(((a[i] - 48) + (b[i] - 48)) + 48 + carry); if (val > 57) { carry = 1; val -= 10; @@ -65,11 +65,11 @@ std::string add(std::string a, std::string b) { /** Fibonacci iterator * \param [in] n n^th Fibonacci number */ -void fib_Accurate(long long n) { +void fib_Accurate(uint64_t n) { std::string tmp = ""; std::string fibMinus1 = "1"; std::string fibMinus2 = "0"; - for (long long i = 0; i < n; i++) { + for (uint64_t i = 0; i < n; i++) { tmp = add(fibMinus1, fibMinus2); fibMinus2 = fibMinus1; fibMinus1 = tmp; From b9b930213fc2a2e7c86b335cc70099c45a6c24ea Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 16:05:43 -0400 Subject: [PATCH 179/433] use pointers instead of non-const references and globals --- others/tower_of_hanoi.cpp | 37 ++++++++++++++++++++----------------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/others/tower_of_hanoi.cpp b/others/tower_of_hanoi.cpp index d6c22961707..323b2e424a5 100644 --- a/others/tower_of_hanoi.cpp +++ b/others/tower_of_hanoi.cpp @@ -13,21 +13,22 @@ struct tower { int values[10]; //! top tower ID int top; -} F, U, T; +}; /** Display the towers */ -void show() { +void show(const struct tower *const F, const struct tower *const T, + const struct tower *const U) { std::cout << "\n\n\tF : "; - for (int i = 0; i < F.top; i++) { - std::cout << F.values[i] << "\t"; + for (int i = 0; i < F->top; i++) { + std::cout << F->values[i] << "\t"; } std::cout << "\n\tU : "; - for (int i = 0; i < U.top; i++) { - std::cout << U.values[i] << "\t"; + for (int i = 0; i < U->top; i++) { + std::cout << U->values[i] << "\t"; } std::cout << "\n\tT : "; - for (int i = 0; i < T.top; i++) { - std::cout << T.values[i] << "\t"; + for (int i = 0; i < T->top; i++) { + std::cout << T->values[i] << "\t"; } } @@ -35,10 +36,10 @@ void show() { * \param [in,out] From tower to move disk *from* * \param [in,out] To tower to move disk *to* */ -void mov(tower &From, tower &To) { - --From.top; - To.values[To.top] = From.values[From.top]; - ++To.top; +void mov(tower *From, tower *To) { + --From->top; + To->values[To->top] = From->values[From->top]; + ++To->top; } /** @@ -48,20 +49,22 @@ void mov(tower &From, tower &To) { * \param [in,out] Using temporary tower for the puzzle * \param [in,out] To tower to move disk to */ -void TH(int n, tower &From, tower &Using, tower &To) { +void TH(int n, tower *From, tower *Using, tower *To) { if (n == 1) { mov(From, To); - show(); + show(From, To, Using); } else { TH(n - 1, From, To, Using); mov(From, To); - show(); + show(From, To, Using); TH(n - 1, Using, From, To); } } /** Main function */ int main() { + struct tower F, U, T; + F.top = 0; U.top = 0; T.top = 0; @@ -75,8 +78,8 @@ int main() { F.values[F.top++] = i; } - show(); - TH(no, F, U, T); + show(&F, &T, &U); + TH(no, &F, &U, &T); return 0; } From 9ef8100a52db10d0581ea816c98de27e27fbf1eb Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 16:37:03 -0400 Subject: [PATCH 180/433] added see also reference to fibonacci --- math/fibonacci_fast.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/math/fibonacci_fast.cpp b/math/fibonacci_fast.cpp index dc59742b87c..08cced35105 100644 --- a/math/fibonacci_fast.cpp +++ b/math/fibonacci_fast.cpp @@ -11,7 +11,7 @@ * found if we have already found n/2th or (n+1)/2th fibonacci It is a property * of fibonacci similar to matrix exponentiation. * - * @see fibonacci_large.cpp, fibonacci.cpp + * @see fibonacci_large.cpp, fibonacci.cpp, string_fibonacci.cpp */ #include From e52da1db6ea46fac9f68ae8b492fbbb6a87b5190 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 16:40:08 -0400 Subject: [PATCH 181/433] documented factorial --- math/factorial.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/math/factorial.cpp b/math/factorial.cpp index 8b13eb52de4..353f0b16bc7 100644 --- a/math/factorial.cpp +++ b/math/factorial.cpp @@ -1,14 +1,17 @@ -// C++ program to find factorial of given number -#include +/** + * @file + * @brief C++ program to find factorial of given number + */ +#include -// function to find factorial of given number +/** function to find factorial of given number */ unsigned int factorial(unsigned int n) { if (n == 0) return 1; return n * factorial(n - 1); } -// Driver code +/** Main function */ int main() { int num = 5; std::cout << "Factorial of " << num << " is " << factorial(num) From c559ebcedbf811333009a9cc27cc782c75f4a338 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 16:41:07 -0400 Subject: [PATCH 182/433] replace printf & scanf with std::cout and std::cin --- math/power_for_huge_numbers.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/math/power_for_huge_numbers.cpp b/math/power_for_huge_numbers.cpp index 5cb1ae514d6..301767d666e 100644 --- a/math/power_for_huge_numbers.cpp +++ b/math/power_for_huge_numbers.cpp @@ -81,10 +81,10 @@ void power(int x, int n) { /** Main function */ int main() { int exponent, base; - printf("Enter base "); - scanf("%id \n", &base); - printf("Enter exponent "); - scanf("%id", &exponent); + std::cout << "Enter base "; + std::cin >> base; + std::cout << "Enter exponent "; + std::cin >> exponent; power(base, exponent); return 0; } From 2683b9d6ede5176b01f22bfe483be6579d6c7533 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 16:43:03 -0400 Subject: [PATCH 183/433] fix happy number code and documetnation --- others/happy_number.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/others/happy_number.cpp b/others/happy_number.cpp index dacb2b8c4d5..b1debaa54db 100644 --- a/others/happy_number.cpp +++ b/others/happy_number.cpp @@ -1,7 +1,7 @@ /** - * A [happy number](https://en.wikipedia.org/wiki/Happy_number) is a decimal - * number whose sum of digits is calculated until the sum is a single digit, and - * this sum turns out to be 1. + * @file + * @brief A happy number is a number whose sum of digits is calculated until the + * sum is a single digit, and this sum turns out to be 1 */ #include From 2f3cb1adaa9a88d679736d49a5a6d35d03f7057b Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 16:34:29 -0400 Subject: [PATCH 184/433] document probability addition rule --- probability/addition_rule.cpp | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/probability/addition_rule.cpp b/probability/addition_rule.cpp index f19955071f6..7809514899c 100644 --- a/probability/addition_rule.cpp +++ b/probability/addition_rule.cpp @@ -1,28 +1,42 @@ +/** + * @file + * @brief Addition rule of probabilities + */ #include -// calculates the probability of the events A or B for independent events - +/** + * calculates the probability of the independent events A or B for independent + * events + * \parama [in] A probability of event A + * \parama [in] B probability of event B + * \returns probability of A and B + */ double addition_rule_independent(double A, double B) { return (A + B) - (A * B); } -// calculates the probability of the events A or B for dependent events -// note that if value of B_given_A is unknown, use chainrule to find it - +/** Calculates the probability of the events A or B for dependent events + * note that if value of B_given_A is unknown, use chainrule to find it + * \parama [in] A probability of event A + * \parama [in] B probability of event B + * \parama [in] B_given_A probability of event B condition A + * \returns probability of A and B + */ double addition_rule_dependent(double A, double B, double B_given_A) { return (A + B) - (A * B_given_A); } +/** Main function */ int main() { double A = 0.5; double B = 0.25; double B_given_A = 0.05; - std::cout << "independent P(A or B) = " - << addition_rule_independent(A, B) << std::endl; + std::cout << "independent P(A or B) = " << addition_rule_independent(A, B) + << std::endl; std::cout << "dependent P(A or B) = " - << addition_rule_dependent(A, B, B_given_A) << std::endl; + << addition_rule_dependent(A, B, B_given_A) << std::endl; return 0; } From 589dceb5b38b409dce072a87112327db23a73f34 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 16:34:37 -0400 Subject: [PATCH 185/433] document bayes theorem --- probability/bayes_theorem.cpp | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/probability/bayes_theorem.cpp b/probability/bayes_theorem.cpp index d30be6c9ab1..aaa557a9456 100644 --- a/probability/bayes_theorem.cpp +++ b/probability/bayes_theorem.cpp @@ -1,24 +1,28 @@ +/** + * @file + * @brief [Bayes' theorem](https://en.wikipedia.org/wiki/Bayes%27_theorem) + * + * Bayes' theorem allows one to find \f$P(A|B)\f$ given \f$P(B|A)\f$ or + * \f$P(B|A)\f$ given \f$P(A|B)\f$ and \f$P(A)\f$ and \f$P(B)\f$.\n + * Note that \f$P(A|B)\f$ is read 'The probability of A given that the event B + * has occured'. + */ #include -// bayes' theorem > https://en.wikipedia.org/wiki/Bayes%27_theorem - -// bayes' theorem allows one to find P(A|B) given P(B|A) -// or P(B|A) given P(A|B) and P(A) and P(B) - -// note P(A|B) is read 'The probability of A given that the event B has occured' - -// returns P(A|B) - +/** returns P(A|B) + */ double bayes_AgivenB(double BgivenA, double A, double B) { return (BgivenA * A) / B; } -// returns P(B|A) - +/** returns P(B|A) + */ double bayes_BgivenA(double AgivenB, double A, double B) { return (AgivenB * B) / A; } +/** Main function + */ int main() { double A = 0.01; double B = 0.1; From 70473004643aebc9232d2f57bd95764b99dd9d0c Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 17:00:39 -0400 Subject: [PATCH 186/433] add probability folder to cmake --- CMakeLists.txt | 1 + probability/CMakeLists.txt | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) create mode 100644 probability/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index c072de6e0cf..70c5b9b2c16 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -57,6 +57,7 @@ add_subdirectory(others) add_subdirectory(search) add_subdirectory(strings) add_subdirectory(sorting) +add_subdirectory(probability) add_subdirectory(computer_oriented_statistical_methods) if(USE_OPENMP) diff --git a/probability/CMakeLists.txt b/probability/CMakeLists.txt new file mode 100644 index 00000000000..0e0b7b7f04f --- /dev/null +++ b/probability/CMakeLists.txt @@ -0,0 +1,18 @@ +# If necessary, use the RELATIVE flag, otherwise each source file may be listed +# with full pathname. RELATIVE may makes it easier to extract an executable name +# automatically. +file( GLOB APP_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp ) +# file( GLOB APP_SOURCES ${CMAKE_SOURCE_DIR}/*.c ) +# AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR} APP_SOURCES) +foreach( testsourcefile ${APP_SOURCES} ) + # I used a simple string replace, to cut off .cpp. + string( REPLACE ".cpp" "" testname ${testsourcefile} ) + add_executable( ${testname} ${testsourcefile} ) + + set_target_properties(${testname} PROPERTIES LINKER_LANGUAGE CXX) + if(OpenMP_CXX_FOUND) + target_link_libraries(${testname} OpenMP::OpenMP_CXX) + endif() + install(TARGETS ${testname} DESTINATION "bin/probability") + +endforeach( testsourcefile ${APP_SOURCES} ) From 9a7018c5c89af5ef5f782c4a0b54ed2d933ccbf4 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 17:14:39 -0400 Subject: [PATCH 187/433] document poisson distribution --- probability/poisson_dist.cpp | 61 ++++++++++++++++++++++-------------- 1 file changed, 37 insertions(+), 24 deletions(-) diff --git a/probability/poisson_dist.cpp b/probability/poisson_dist.cpp index 34536336801..6a2a377c3f0 100644 --- a/probability/poisson_dist.cpp +++ b/probability/poisson_dist.cpp @@ -1,26 +1,32 @@ -#include +/** + * @file + * @brief [Poisson + * statistics](https://en.wikipedia.org/wiki/Poisson_distribution) + * + * The Poisson distribution counts how many + * events occur over a set time interval. + */ #include +#include -// The Poisson distribution counts how many -// events occur over a set time interval -// https://en.wikipedia.org/wiki/Poisson_distribution - -// calculate the events per unit time -// e.g 5 dollars every 2 mins = 5 / 2 = 2.5 - +/** + * poisson rate:\n + * calculate the events per unit time\n + * e.g 5 dollars every 2 mins = 5 / 2 = 2.5 + */ double poisson_rate(double events, double timeframe) { return events / timeframe; } -// calculate the expected value over a time -// e.g rate of 2.5 over 10 mins = 2.5 x 10 = 25 - -double poisson_expected(double rate, double time) { - return rate * time; -} - -// find the factorial of a given number +/** + * calculate the expected value over a time + * e.g rate of 2.5 over 10 mins = 2.5 x 10 = 25 + */ +double poisson_expected(double rate, double time) { return rate * time; } +/** + * Compute factorial of a given number + */ double fact(double x) { double x_fact = x; for (int i = x - 1; i > 0; i--) { @@ -33,14 +39,18 @@ double fact(double x) { return x_fact; } -// find the probability of x successes in a Poisson dist - +/** + * Find the probability of x successes in a Poisson dist. + * \f[p(\mu,x) = \frac{\mu^x e^{-\mu}}{x!}\f] + */ double poisson_x_successes(double expected, double x) { - return (pow(expected, x) * exp(-expected)) / fact(x); + return (std::pow(expected, x) * std::exp(-expected)) / fact(x); } -// probability of a success in range for Poisson dist (inclusive, inclusive) - +/** + * probability of a success in range for Poisson dist (inclusive, inclusive) + * \f[P = \sum_i p(\mu,i)\f] + */ double poisson_range_successes(double expected, double lower, double upper) { double probability = 0; for (int i = lower; i <= upper; i++) { @@ -49,6 +59,9 @@ double poisson_range_successes(double expected, double lower, double upper) { return probability; } +/** + * main function + */ int main() { double rate, expected; rate = poisson_rate(3, 1); @@ -57,10 +70,10 @@ int main() { expected = poisson_expected(rate, 2); std::cout << "Poisson expected : " << expected << std::endl; - std::cout << "Poisson 0 successes : " - < Date: Thu, 28 May 2020 17:38:50 -0400 Subject: [PATCH 188/433] documented binomial distribution --- probability/binomial_dist.cpp | 107 ++++++++++++++++++++-------------- 1 file changed, 63 insertions(+), 44 deletions(-) diff --git a/probability/binomial_dist.cpp b/probability/binomial_dist.cpp index b21a3e0fcef..1f30c504800 100644 --- a/probability/binomial_dist.cpp +++ b/probability/binomial_dist.cpp @@ -1,81 +1,100 @@ -#include +/** + * @file + * @brief [Binomial + * distribution](https://en.wikipedia.org/wiki/Binomial_distribution) example + * + * The binomial distribution models the number of + * successes in a sequence of n independent events + * + * Summary of variables used: + * * n : number of trials + * * p : probability of success + * * x : desired successes + */ #include +#include -// the binomial distribution models the number of -// successes in a sequence of n independent events - -// n : number of trials -// p : probability of success -// x : desired successes - -// finds the expected value of a binomial distribution - -double binomial_expected(double n, double p) { - return n * p; -} - -// finds the variance of the binomial distribution - -double binomial_variance(double n, double p) { - return n * p * (1 - p); -} - -// finds the standard deviation of the binomial distribution - +/** finds the expected value of a binomial distribution + * \param [in] n + * \param [in] p + * \returns \f$\mu=np\f$ + */ +double binomial_expected(double n, double p) { return n * p; } + +/** finds the variance of the binomial distribution + * \param [in] n + * \param [in] p + * \returns \f$\sigma^2 = n\cdot p\cdot (1-p)\f$ + */ +double binomial_variance(double n, double p) { return n * p * (1 - p); } + +/** finds the standard deviation of the binomial distribution + * \param [in] n + * \param [in] p + * \returns \f$\sigma = \sqrt{\sigma^2} = \sqrt{n\cdot p\cdot (1-p)}\f$ + */ double binomial_standard_deviation(double n, double p) { - return sqrt(binomial_variance(n, p)); + return std::sqrt(binomial_variance(n, p)); } -// Computes n choose r -// n being the trials and r being the desired successes - +/** Computes n choose r + * \param [in] n + * \param [in] r + * \returns \f$\displaystyle {n\choose r} = + * \frac{n!}{r!(n-r)!} = \frac{n\times(n-1)\times(n-2)\times\cdots(n-r)}{r!} + * \f$ + */ double nCr(double n, double r) { double numerator = n; double denominator = r; - for (int i = n - 1 ; i >= ((n - r) + 1); i--) { + for (int i = n - 1; i >= ((n - r) + 1); i--) { numerator *= i; } - for (int i = 1; i < r ; i++) { + for (int i = 1; i < r; i++) { denominator *= i; } return numerator / denominator; } -// calculates the probability of exactly x successes - +/** calculates the probability of exactly x successes + * \returns \f$\displaystyle P(n,p,x) = {n\choose x} p^x (1-p)^{n-x}\f$ + */ double binomial_x_successes(double n, double p, double x) { - return nCr(n, x) * pow(p, x) * pow(1-p, n-x); + return nCr(n, x) * std::pow(p, x) * std::pow(1 - p, n - x); } -// calculates the probability of a result within a range (inclusive, inclusive) - -double binomial_range_successes( - double n, double p, double lower_bound, double upper_bound) { +/** calculates the probability of a result within a range (inclusive, inclusive) + * \returns \f$\displaystyle \left.P(n,p)\right|_{x_0}^{x_1} = + * \sum_{i=x_0}^{x_1} P(i) + * =\sum_{i=x_0}^{x_1} {n\choose i} p^i (1-p)^{n-i}\f$ + */ +double binomial_range_successes(double n, double p, double lower_bound, + double upper_bound) { double probability = 0; for (int i = lower_bound; i <= upper_bound; i++) { - probability += nCr(n, i) * pow(p, i) * pow(1 - p, n - i); + probability += nCr(n, i) * std::pow(p, i) * std::pow(1 - p, n - i); } return probability; } +/** main function */ int main() { - std::cout << "expected value : " - < Date: Thu, 28 May 2020 17:39:08 -0400 Subject: [PATCH 189/433] added AMS extenstions to MATHJAX in doxygen --- CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 70c5b9b2c16..95c09d8e2e8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -33,6 +33,7 @@ if(DOXYGEN_FOUND) set(DOXYGEN_STRIP_CODE_COMMENTS NO) set(DOXYGEN_BUILTIN_STL_SUPPORT YES) set(DOXYGEN_FILE_PATTERNS *.cpp *.h *.hpp *.md) + set(DOXYGEN_MATHJAX_EXTENSIONS TeX/AMSmath TeX/AMSsymbols) set(DOXYGEN_TAGFILES "doc/cppreference-doxygen-web.tag.xml=http://en.cppreference.com/w/") if(MSVC) set(DOXYGEN_CPP_CLI_SUPPORT YES) From 90180bfe2e9bd4799bec6a79bfca243012f68100 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 17:56:46 -0400 Subject: [PATCH 190/433] temporarily enable DOXYGEN CI to test README.md fixes --- .github/workflows/gh-pages.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml index aff5dcdcefe..f3aec275c67 100644 --- a/.github/workflows/gh-pages.yml +++ b/.github/workflows/gh-pages.yml @@ -1,8 +1,9 @@ name: Doxygen CI on: - push: - branches: [master] + [push] + # push: + # branches: [master] jobs: build: From 1ef2e381fcb10e96417f0e07d181f880e5505205 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 17:58:09 -0400 Subject: [PATCH 191/433] replace SVG images in markdown with HTML img tags --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index b56c4f5f40e..f166aaf0fa7 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ # The Algorithms - C++ # {#mainpage} -[![contributions welcome](https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square)](https://github.com/kvedala/C-Plus-Plus/blob/master/CONTRIBUTION.md)  +[contributions welcome](https://github.com/kvedala/C-Plus-Plus/blob/master/CONTRIBUTION.md) ![GitHub repo size](https://img.shields.io/github/repo-size/kvedala/C-Plus-Plus?color=red&style=flat-square) ![GitHub closed pull requests](https://img.shields.io/github/issues-pr-closed/kvedala/C-Plus-Plus?color=green&style=flat-square) -![Doxygen CI](https://github.com/kvedala/C-Plus-Plus/workflows/Doxygen%20CI/badge.svg) -![cpplint](https://github.com/kvedala/C-Plus-Plus/workflows/cpplint_modified_files/badge.svg) -![C/C++ CI](https://github.com/kvedala/C-Plus-Plus/workflows/C/C++%20CI/badge.svg) +Doxygen CI +cpplint status +C/C++ CI [Documentation](https://kvedala.github.io/C-Plus-Plus) From 9f9325e5f3192e423fc99c0805dde5b0b7a87698 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 18:18:19 -0400 Subject: [PATCH 192/433] install doxygen via brew --- .github/workflows/gh-pages.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml index f3aec275c67..b24c36f3e22 100644 --- a/.github/workflows/gh-pages.yml +++ b/.github/workflows/gh-pages.yml @@ -15,7 +15,8 @@ jobs: - name: Install requirements run: | sudo apt -qq -y update - sudo apt -qq install doxygen graphviz ninja-build + sudo apt -qq install graphviz ninja-build + sudo brew install doxygen - name: configure run: cmake -G Ninja -B ./build -S . - name: build From 4c3823ada32c54afdd0ad4ab48b141a71be82b0f Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 18:25:06 -0400 Subject: [PATCH 193/433] switch doxygen build to macos --- .github/workflows/gh-pages.yml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml index b24c36f3e22..c548dd05ba6 100644 --- a/.github/workflows/gh-pages.yml +++ b/.github/workflows/gh-pages.yml @@ -7,15 +7,14 @@ on: jobs: build: - runs-on: ubuntu-latest + runs-on: macos-latest steps: - uses: actions/checkout@master with: submodules: true - name: Install requirements run: | - sudo apt -qq -y update - sudo apt -qq install graphviz ninja-build + sudo brew install graphviz ninja-build sudo brew install doxygen - name: configure run: cmake -G Ninja -B ./build -S . From f2a6b63c53a62ae8d60d38ed93ab954894e97929 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 18:26:29 -0400 Subject: [PATCH 194/433] brew install without sudo --- .github/workflows/gh-pages.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml index c548dd05ba6..9749b9b8d7d 100644 --- a/.github/workflows/gh-pages.yml +++ b/.github/workflows/gh-pages.yml @@ -14,8 +14,8 @@ jobs: submodules: true - name: Install requirements run: | - sudo brew install graphviz ninja-build - sudo brew install doxygen + brew install graphviz ninja-build + brew install doxygen - name: configure run: cmake -G Ninja -B ./build -S . - name: build From 5b58d7092c2bab4f8db614d81234f9e70dda7589 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 18:29:48 -0400 Subject: [PATCH 195/433] brew uses "ninja" and not "ninja-build" --- .github/workflows/gh-pages.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml index 9749b9b8d7d..ed43f44eabc 100644 --- a/.github/workflows/gh-pages.yml +++ b/.github/workflows/gh-pages.yml @@ -14,7 +14,7 @@ jobs: submodules: true - name: Install requirements run: | - brew install graphviz ninja-build + brew install graphviz ninja brew install doxygen - name: configure run: cmake -G Ninja -B ./build -S . From e3fbc6bc2c29296a30bffb8896c7fa2c2b7fcff2 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 18:34:45 -0400 Subject: [PATCH 196/433] reset README.md file to using non-HTML tags --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index f166aaf0fa7..b56c4f5f40e 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ # The Algorithms - C++ # {#mainpage} -[contributions welcome](https://github.com/kvedala/C-Plus-Plus/blob/master/CONTRIBUTION.md) +[![contributions welcome](https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square)](https://github.com/kvedala/C-Plus-Plus/blob/master/CONTRIBUTION.md)  ![GitHub repo size](https://img.shields.io/github/repo-size/kvedala/C-Plus-Plus?color=red&style=flat-square) ![GitHub closed pull requests](https://img.shields.io/github/issues-pr-closed/kvedala/C-Plus-Plus?color=green&style=flat-square) -Doxygen CI -cpplint status -C/C++ CI +![Doxygen CI](https://github.com/kvedala/C-Plus-Plus/workflows/Doxygen%20CI/badge.svg) +![cpplint](https://github.com/kvedala/C-Plus-Plus/workflows/cpplint_modified_files/badge.svg) +![C/C++ CI](https://github.com/kvedala/C-Plus-Plus/workflows/C/C++%20CI/badge.svg) [Documentation](https://kvedala.github.io/C-Plus-Plus) From 11bb03f25579c223f848f02a876169c958739bfb Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 18:39:15 -0400 Subject: [PATCH 197/433] reset Doxygen CI to only execute on master branch --- .github/workflows/gh-pages.yml | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml index ed43f44eabc..700d1a3f7a8 100644 --- a/.github/workflows/gh-pages.yml +++ b/.github/workflows/gh-pages.yml @@ -1,9 +1,8 @@ name: Doxygen CI on: - [push] - # push: - # branches: [master] + push: + branches: [master] jobs: build: @@ -14,8 +13,7 @@ jobs: submodules: true - name: Install requirements run: | - brew install graphviz ninja - brew install doxygen + brew install graphviz ninja doxygen - name: configure run: cmake -G Ninja -B ./build -S . - name: build From 186c7a2de85adc61cd7d2ae6b83d51ee21616fd1 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 19:37:21 -0400 Subject: [PATCH 198/433] add missing free for dynamic memory allocated --- search/binary_search.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/search/binary_search.cpp b/search/binary_search.cpp index 9933c98166e..d8a3a663126 100644 --- a/search/binary_search.cpp +++ b/search/binary_search.cpp @@ -30,5 +30,7 @@ int main(int argc, char const* argv[]) { std::cout << key << " found at index " << res << std::endl; else std::cout << key << " not found" << std::endl; + + delete[] a; return 0; } From 94f3ffe146f7f2daa4a8c4e8498d587e6ee27876 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 19:37:33 -0400 Subject: [PATCH 199/433] document binary search --- search/binary_search.cpp | 56 +++++++++++++++++++++++++++------------- 1 file changed, 38 insertions(+), 18 deletions(-) diff --git a/search/binary_search.cpp b/search/binary_search.cpp index d8a3a663126..66da31d7fca 100644 --- a/search/binary_search.cpp +++ b/search/binary_search.cpp @@ -1,35 +1,55 @@ +/** + * @file + * @brief [Binary search + * algorithm](https://en.wikipedia.org/wiki/Binary_search_algorithm) + */ #include -// binary_search function -int binary_search(int a[], int l, int r, int key) { + +/** binary_search function + * \param [in] a array to sort + * \param [in] r right hand limit = \f$n-1\f$ + * \param [in] key value to find + * \returns index if T is found + * \return -1 if T is not found + */ +int binary_search(int a[], int r, int key) { + int l = 0; + while (l <= r) { - int m = l + (r - l) / 2; - if (key == a[m]) - return m; - else if (key < a[m]) - r = m - 1; - else - l = m + 1; - } - return -1; - } + int m = l + (r - l) / 2; + if (key == a[m]) + return m; + else if (key < a[m]) + r = m - 1; + else + l = m + 1; + } + return -1; +} + +/** main function */ int main(int argc, char const* argv[]) { int n, key; std::cout << "Enter size of array: "; std::cin >> n; std::cout << "Enter array elements: "; + int* a = new int[n]; -// this loop use for store value in Array + + // this loop use for store value in Array for (int i = 0; i < n; i++) { std::cin >> a[i]; - } + } + std::cout << "Enter search key: "; std::cin >> key; -// this is use for find value in given array - int res = binary_search(a, 0, n - 1, key); + + // this is use for find value in given array + int res = binary_search(a, n - 1, key); if (res != -1) - std::cout << key << " found at index " << res << std::endl; + std::cout << key << " found at index " << res << std::endl; else - std::cout << key << " not found" << std::endl; + std::cout << key << " not found" << std::endl; delete[] a; return 0; From 605fa140cc34caa6cc1a9c00c6b40b9a89fc2929 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 19:54:24 -0400 Subject: [PATCH 200/433] free dynamically allocated memory --- search/exponential_search.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/search/exponential_search.cpp b/search/exponential_search.cpp index 5f9e6421766..79f09e38b9a 100644 --- a/search/exponential_search.cpp +++ b/search/exponential_search.cpp @@ -59,5 +59,6 @@ int main() { assert(struzik_search(sorted_array, 7, 50) == nullptr); assert(struzik_search(sorted_array, 7, 7) == sorted_array); // TEST CASES + delete[] sorted_array; return 0; } From 969e916871f3e168506c8968008fded8122e7a74 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 19:54:37 -0400 Subject: [PATCH 201/433] document exponential search --- search/exponential_search.cpp | 62 +++++++++++++++++++++++------------ 1 file changed, 41 insertions(+), 21 deletions(-) diff --git a/search/exponential_search.cpp b/search/exponential_search.cpp index 79f09e38b9a..f57cbf96b51 100644 --- a/search/exponential_search.cpp +++ b/search/exponential_search.cpp @@ -1,20 +1,42 @@ -// Copyright 2020 Divide-et-impera-11 +/** + * \file + * \brief [Exponential search + * algorithm](https://en.wikipedia.org/wiki/Exponential_search) + * \copyright 2020 Divide-et-impera-11 + * + * The algorithm try to search the range where the key should be. + * If it has been found we do a binary search there. + * The range of the search grows by exponential every time. + * If the key is larger than the last element of array, the start of + * block(block_front) will be equal to the end of block(block_size) and the + * algorithm return null ponter, every other cases the algoritm return fom the + * loop. + */ #include #include #include -#include +#ifdef _MSC_VER +#include // use for MS Visual C++ +#else +#include // for all other compilers +#endif -// Binary Search Algorithm(use by struzik algorithm) -// Time Complexity O(log n) where 'n' is the number of elements -// Worst Time Complexity O(log n) -// Best Time Complexity Ω(1) -// Space Complexity O(1) -// Auxiliary Space Complexity O(1) +/** Binary Search Algorithm (used by ::struzik_search)\n + * * Time Complexity O(log n) where 'n' is the number of elements + * * Worst Time Complexity O(log n) + * * Best Time Complexity Ω(1) + * * Space Complexity O(1) + * * Auxiliary Space Complexity O(1) + * \returns pointer to value in the array + * \returns `nullptr` if value not found + */ template inline Type* binary_s(Type* array, size_t size, Type key) { int32_t lower_index(0), upper_index(size - 1), middle_index; + while (lower_index <= upper_index) { middle_index = std::floor((lower_index + upper_index) / 2); + if (*(array + middle_index) < key) lower_index = (middle_index + 1); else if (*(array + middle_index) > key) @@ -22,21 +44,17 @@ inline Type* binary_s(Type* array, size_t size, Type key) { else return (array + middle_index); } + return nullptr; } -// Struzik Search Algorithm(Exponential) -// Time Complexity O(log i)where i is the position of search key in the list -// Worst Time Complexity O(log i) -// Best Time Complexity Ω(1) -// Space Complexity O(1) -// Auxiliary Space Complexity O(1) -/* Tha algorithm try to search the range where the key should be. -If it has been found we do a binary search there. -The range of the search grows by exponential every time. -If the key is larger than the last element of array, -the start of block(block_front) will be equal to the end of block(block_size) -and the algorithm return null ponter, -every other cases the algoritm return fom the loop. */ + +/** Struzik Search Algorithm(Exponential) + * * Time Complexity O(log i) where i is the position of search key in the list + * * Worst Time Complexity O(log i) + * * Best Time Complexity Ω(1) + * * Space Complexity O(1) + * * Auxiliary Space Complexity O(1) + */ template Type* struzik_search(Type* array, size_t size, Type key) { uint32_t block_front(0), block_size = size == 0 ? 0 : 1; @@ -51,6 +69,8 @@ Type* struzik_search(Type* array, size_t size, Type key) { } return nullptr; } + +/** Main function */ int main() { // TEST CASES int* sorted_array = new int[7]{7, 10, 15, 23, 70, 105, 203}; From d9ffc8aca168cade7093d13501c09b8d616a2df3 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 20:24:44 -0400 Subject: [PATCH 202/433] document hash search --- search/hash_search.cpp | 147 ++++++++++++++++++++++++++--------------- 1 file changed, 93 insertions(+), 54 deletions(-) diff --git a/search/hash_search.cpp b/search/hash_search.cpp index 94d87b58aaa..6e4caffc30e 100644 --- a/search/hash_search.cpp +++ b/search/hash_search.cpp @@ -1,100 +1,139 @@ -// Copyright 2020 Arctic2333 -#include -#include -#define MAX 6 // Determines how much data -# define HASHMAX 5 // Determines the length of the hash table /** - * Hash Search Algorithm - * Best Time Complexity Ω(1) - * In this algorithm, we use the method of division and reservation remainder to construct the hash function, - * and use the method of chain address to solve the conflict, that is, we link a chain list after the data, - * and store all the records whose keywords are synonyms in the same linear chain list. */ -int data[MAX] = { 1, 10, 15, 5, 8, 7}; // test data + * \file + * \brief Hash Search Algorithm - Best Time Complexity Ω(1) + * + * \copyright 2020 Arctic2333 + * + * In this algorithm, we use the method of division and reservation remainder to + * construct the hash function, and use the method of chain address to solve the + * conflict, that is, we link a chain list after the data, and store all the + * records whose keywords are synonyms in the same linear chain list. + * + * @warning This program is only for educational purposes. It has serious flaws + * in implementation with regards to memory management resulting in large + * amounts of memory leaks. + * @todo fix the program for memory leaks and better structure in C++ and not C + * fashion + */ +#include +#include + +#define MAX 6 ///< Determines how much data +#define HASHMAX 5 ///< Determines the length of the hash table + +int data[MAX] = {1, 10, 15, 5, 8, 7}; //!< test data + +/** + * a one-way linked list + */ typedef struct list { - int key; - struct list * next; -} -node, * link; -node hashtab[HASHMAX]; -int counter = 1; -/* int h(int key) + int key; //!< key value for node + struct list* next; //!< pointer to next link in the chain +} node, /**< define node as one item list */ + *link; ///< pointer to nodes + +node hashtab[HASHMAX]; ///< array of nodes + +// int counter = 1; + +/** * Mode of hash detection : - * Division method */ -int h(int key) { - return key % HASHMAX; -} -/* void create_list(int key) + * Division method + * \param [in] key to hash + * \returns hash value for `key` + */ +int h(int key) { return key % HASHMAX; } + +/** * The same after the remainder will be added after the same hash header * To avoid conflict, zipper method is used - * Insert elements into the linked list in the header */ + * Insert elements into the linked list in the header + * \param [in] key key to add to list + * \warning dynamic memory allocated to `n` never gets freed. + * \todo fix memory leak + */ void create_list(int key) { // Construct hash table link p, n; int index; - n = (link) malloc(sizeof(node)); - n -> key = key; - n -> next = NULL; + n = (link)malloc(sizeof(node)); + n->key = key; + n->next = NULL; index = h(key); p = hashtab[index].next; if (p != NULL) { - n -> next = p; + n->next = p; hashtab[index].next = n; } else { - hashtab[index].next = n; } + hashtab[index].next = n; + } } -/* int hash_search(int key) - * Input the key to be searched, and get the hash header position through the H (int key) function, - * then one-dimensional linear search. - * If found @return element depth and number of searches - * If not found @return -1 */ -int hash_search(int key) { // Hash lookup function + +/** + * Input the key to be searched, and get the hash header position through the H + * (int key) function, then one-dimensional linear search. If found @return + * element depth and number of searches If not found @return -1 + */ +int hash_search(int key, int* counter) { // Hash lookup function link pointer; int index; - counter = 0; + + *counter = 0; index = h(key); pointer = hashtab[index].next; - printf("data[%d]:", index); + + std::cout << "data[" << index << "]:"; + while (pointer != NULL) { - counter++; - printf("data[%d]:", pointer -> key); - if (pointer -> key == key) + counter[0]++; + std::cout << "data[" << pointer->key << "]:"; + if (pointer->key == key) return 1; else - pointer = pointer -> next; + pointer = pointer->next; } + return 0; } + +/** main function */ int main() { link p; - int key, index, i; // Key is the value to be found + int key, index, i, counter; // Key is the value to be found index = 0; + // You can write the input mode here while (index < MAX) { // Construct hash table create_list(data[index]); index++; } + for (i = 0; i < HASHMAX; i++) { // Output hash table - printf("hashtab [%d]", i); - printf("\n"); + std::cout << "hashtab [" << i << "]\n"; + p = hashtab[i].next; + while (p != NULL) { - printf("please int key:"); - if (p -> key > 0) - printf("[%d]", p -> key); - p = p -> next; + std::cout << "please int key:"; + if (p->key > 0) + std::cout << "[" << p->key << "]"; + p = p->next; } - printf("\n"); + std::cout << std::endl; } + while (key != -1) { // You can write the input mode here // test key = 10 key = 10; - if (hash_search(key)) - printf("search time = %d\n", counter); + if (hash_search(key, &counter)) + std::cout << "search time = " << counter << std::endl; else - printf("no found!\n"); + std::cout << "no found!\n"; key = -1; // Exit test - /* The test sample is returned as: data[0]:data[5]:data[15]:data[10]:search time = 3 - * The search is successful. There are 10 in this set of data */ + /* The test sample is returned as: + * data[0]:data[5]:data[15]:data[10]:search time = 3 The search is + * successful. There are 10 in this set of data */ } + return 0; } From 7fd12991f74280018724920d73761ef6328b51b8 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 20:31:41 -0400 Subject: [PATCH 203/433] document interpolation search --- search/interpolation_search.cpp | 91 +++++++++++++++++++++------------ 1 file changed, 58 insertions(+), 33 deletions(-) diff --git a/search/interpolation_search.cpp b/search/interpolation_search.cpp index afa9e7c5091..e12dbd157a0 100644 --- a/search/interpolation_search.cpp +++ b/search/interpolation_search.cpp @@ -1,36 +1,61 @@ -#include - -// function to search the value in an array using interpolation search -int search(int arr[], int value, int len) { - int low = 0, high, mid; - high = len-1; - while (arr[low] <= value && arr[high] >= value) { - mid = (low + ((value-arr[low])*(high-low)) / (arr[high]-arr[low])); - if (arr[mid] > value) - high = mid-1; - else if (arr[mid] < value) - low = mid+1; - else - return mid; - } - if (arr[low] == value) - return low; - return 0; +/** + * \file + * \brief [Interpolation + * search](https://en.wikipedia.org/wiki/Interpolation_search) algorithm + */ +#include + +/** function to search the value in an array using interpolation search + * \param [in] arr array to search in + * \param [in] value value to search for + * \param [in] len length of array + * \returns index where the value is found + * \returns 0 if not found + */ +int interpolation_search(int arr[], int value, int len) { + int low = 0, high, mid; + high = len - 1; + + while (arr[low] <= value && arr[high] >= value) { + mid = (low + + ((value - arr[low]) * (high - low)) / (arr[high] - arr[low])); + if (arr[mid] > value) + high = mid - 1; + else if (arr[mid] < value) + low = mid + 1; + else + return mid; + } + + if (arr[low] == value) + return low; + + return 0; } +/** main function */ int main() { - int n, value, array[100], re; - std::cout << "Enter the size of array(less than 100) : "; - std::cin >> n; - std::cout << "array in ascending (increasing) order : " << std::endl; - for (int i=0; i < n; i++) - std::cin >> array[i]; - std::cout << "Enter the value you want to search : "; - std::cin >> value; - re = search(array, value, n); - if (re == 0) - std::cout << "Entered value is not in the array" << std::endl; - else - std::cout << "The value is at the position " << re << std::endl; - return 0; - } + int n, value, re; + + std::cout << "Enter the size of array(less than 100) : "; + std::cin >> n; + + int *array = new int[n]; + + std::cout << "array in ascending (increasing) order : " << std::endl; + + for (int i = 0; i < n; i++) std::cin >> array[i]; + + std::cout << "Enter the value you want to search : "; + std::cin >> value; + + re = interpolation_search(array, value, n); + + if (re == 0) + std::cout << "Entered value is not in the array" << std::endl; + else + std::cout << "The value is at the position " << re << std::endl; + + delete[] array; + return 0; +} From 85020eea5faf69972a8e685b7b4be80abec052c7 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 20:33:25 -0400 Subject: [PATCH 204/433] change error return value for function --- search/interpolation_search.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/search/interpolation_search.cpp b/search/interpolation_search.cpp index e12dbd157a0..4339dc3661e 100644 --- a/search/interpolation_search.cpp +++ b/search/interpolation_search.cpp @@ -30,7 +30,7 @@ int interpolation_search(int arr[], int value, int len) { if (arr[low] == value) return low; - return 0; + return -1; } /** main function */ @@ -51,7 +51,7 @@ int main() { re = interpolation_search(array, value, n); - if (re == 0) + if (re == -1) std::cout << "Entered value is not in the array" << std::endl; else std::cout << "The value is at the position " << re << std::endl; From 4bc199ff1d9eda8faeb298c88c7c9dfeeb22f9b9 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 20:35:12 -0400 Subject: [PATCH 205/433] document interpolation search 2 --- search/interpolation_search2.cpp | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/search/interpolation_search2.cpp b/search/interpolation_search2.cpp index 0e6d3b79d36..93fa6cd836e 100644 --- a/search/interpolation_search2.cpp +++ b/search/interpolation_search2.cpp @@ -1,4 +1,17 @@ +/** + * \file + * \brief [Interpolation + * search](https://en.wikipedia.org/wiki/Interpolation_search) algorithm + */ #include + +/** function to search the value in an array using interpolation search + * \param [in] arr array to search in + * \param [in] value value to search for + * \param [in] len length of array + * \returns index where the value is found + * \returns -1 if not found + */ int InterpolationSearch(int A[], int n, int x) { int low = 0; int high = n - 1; @@ -11,18 +24,21 @@ int InterpolationSearch(int A[], int n, int x) { else low = mid + 1; // x lies after mid } + return -1; } +/** main function */ int main() { int A[] = {2, 4, 5, 7, 13, 14, 15, 23}; int x = 17; - int index = InterpolationSearch( - A, 8, x); // passed array A inside the InterpolationSearch function - if (index != -1) - std::cout << "Number " << x << " is at " << index; + + ///< passed array A inside the InterpolationSearch function + int index = InterpolationSearch(A, 8, x); + if (index < 0) + std::cout << "Number " << x << " not found" << std::endl; else - std::cout << "Number " << x << " not found"; + std::cout << "Number " << x << " is at " << index << std::endl; } // randomly set x bcoz array was defined by us , therefore not reasonable for From 2b57d1ff881b77636b88987978ae38d62741192f Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 20:36:44 -0400 Subject: [PATCH 206/433] document jump search --- search/jump_search.cpp | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/search/jump_search.cpp b/search/jump_search.cpp index aa2ee0bdb3e..f7b100a4e03 100644 --- a/search/jump_search.cpp +++ b/search/jump_search.cpp @@ -1,9 +1,14 @@ -// C++ program to implement Jump Search - +/** + * \file + * \brief C++ program to implement [Jump + * Search](https://en.wikipedia.org/wiki/Jump_search) + */ #include #include #include +/** jump search implementation + */ int jumpSearch(int arr[], int x, int n) { // Finding block size to be jumped int step = std::sqrt(n); @@ -14,7 +19,8 @@ int jumpSearch(int arr[], int x, int n) { while (arr[std::min(step, n) - 1] < x) { prev = step; step += std::sqrt(n); - if (prev >= n) return -1; + if (prev >= n) + return -1; } // Doing a linear search for x in block @@ -24,10 +30,12 @@ int jumpSearch(int arr[], int x, int n) { // If we reached next block or end of // array, element is not present. - if (prev == std::min(step, n)) return -1; + if (prev == std::min(step, n)) + return -1; } // If element is found - if (arr[prev] == x) return prev; + if (arr[prev] == x) + return prev; return -1; } From 5ab43ad039f9aa943e596f6e47d26a36a1fb42a0 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 20:41:31 -0400 Subject: [PATCH 207/433] document linear search --- search/linear_search.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/search/linear_search.cpp b/search/linear_search.cpp index 8849549e54d..14250695112 100644 --- a/search/linear_search.cpp +++ b/search/linear_search.cpp @@ -1,5 +1,18 @@ +/** + * \file + * \brief [Linear search + * algorithm](https://en.wikipedia.org/wiki/Linear_search) + */ #include +/** + * Algorithm implementation + * \param [in] array array to search in + * \param [in] size length of array + * \param [in] key key value to search for + * \returns index where the key-value occurs in the array + * \returns -1 if key-value not found + */ int LinearSearch(int *array, int size, int key) { for (int i = 0; i < size; ++i) { if (array[i] == key) { @@ -10,6 +23,7 @@ int LinearSearch(int *array, int size, int key) { return -1; } +/** main function */ int main() { int size; std::cout << "\nEnter the size of the Array : "; From 8291db4f9fb6cf119f75248c795cf56540cee3e2 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 21:06:53 -0400 Subject: [PATCH 208/433] attempted to document median search --- search/median_search.cpp | 59 +++++++++++++++++++++++++++------------- 1 file changed, 40 insertions(+), 19 deletions(-) diff --git a/search/median_search.cpp b/search/median_search.cpp index fa8ef38268b..2134a0dbe42 100644 --- a/search/median_search.cpp +++ b/search/median_search.cpp @@ -1,18 +1,21 @@ +/** + * \file + * \brief [Median search](https://en.wikipedia.org/wiki/Median_search) algorithm + * \warning This core is erroneous and gives invorrect answers. Tested using + * cases from [here](https://brilliant.org/wiki/median-finding-algorithm/) + * \ingroup median search + * \{ + */ #include -#include -#include #include -#include -#include #include -std::vector v; -std::vector s1; -std::vector s2; -std::vector s3; - +/** + * @todo add documentation + */ template -void comp(X x) { +void comp(X x, std::vector &s1, std::vector &s2, + std::vector &s3) { if (s1.size() >= x && s1.size() + s2.size() < x) { std::cout << s2[0] << " is the " << x + 1 << "th element from front"; } else if (s1.size() > x) { @@ -26,17 +29,32 @@ void comp(X x) { std::cout << x + 1 << " is invalid location"; } } + +#define MAX_NUM 20 ///< maximum number of values to sort from + +/** + * Main function + */ int main() { - for (int i = 0; i < 1000; i++) { - v.push_back(std::rand() % 1000); - } - for (int r : v) { - std::cout << r << " "; - } - int median = std::rand() % 1000; + std::vector v{25, 21, 98, 100, 76, 22, 43, 60, 89, 87}; + std::vector s1; + std::vector s2; + std::vector s3; + + // creates an array of random numbers + // for (int i = 0; i < MAX_NUM; i++) { + // int r = std::rand() % 1000; + // v.push_back(r); + // std::cout << r << " "; + // } + for (int r : v) std::cout << r << " "; + + int median = std::rand() % 1000; // initialize to a random numnber + std::cout << "\nmedian=" << median << std::endl; int avg1, avg2, avg3, sum1 = 0, sum2 = 0, sum3 = 0; - for (int i = 0; i < 1000; i++) { + + for (int i = 0; i < v.size(); i++) { // iterate through all numbers if (v.back() == v[median]) { avg1 = sum1 + v.back(); s2.push_back(v.back()); @@ -49,9 +67,12 @@ int main() { } v.pop_back(); } + int x; std::cout << "enter the no. to be searched form begining:- "; std::cin >> x; - comp(x - 1); + comp(x - 1, s1, s2, s3); + return 0; } +/// } From ecddfd2704b156886e159bd92c619eb53a0f130b Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 21:30:42 -0400 Subject: [PATCH 209/433] use pointers instead --- search/median_search.cpp | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/search/median_search.cpp b/search/median_search.cpp index 2134a0dbe42..7379cad26e9 100644 --- a/search/median_search.cpp +++ b/search/median_search.cpp @@ -14,16 +14,16 @@ * @todo add documentation */ template -void comp(X x, std::vector &s1, std::vector &s2, - std::vector &s3) { - if (s1.size() >= x && s1.size() + s2.size() < x) { - std::cout << s2[0] << " is the " << x + 1 << "th element from front"; - } else if (s1.size() > x) { - std::sort(s1.begin(), s1.end()); - std::cout << s1[x] << " is the " << x + 1 << "th element from front"; - } else if (s1.size() + s2.size() <= x && s3.size() > x) { - std::sort(s3.begin(), s3.end()); - std::cout << s3[x - s1.size() - s2.size()] << " is the " << x + 1 +void comp(X x, std::vector *s1, std::vector *s2, + std::vector *s3) { + if (s1->size() >= x && s1->size() + s2->size() < x) { + std::cout << (*s2)[0] << " is the " << x + 1 << "th element from front"; + } else if (s1->size() > x) { + std::sort(s1->begin(), s1->end()); + std::cout << (*s1)[x] << " is the " << x + 1 << "th element from front"; + } else if (s1->size() + s2->size() <= x && s3->size() > x) { + std::sort(s3->begin(), s3->end()); + std::cout << (*s3)[x - s1->size() - s2->size()] << " is the " << x + 1 << "th element from front"; } else { std::cout << x + 1 << " is invalid location"; @@ -71,7 +71,7 @@ int main() { int x; std::cout << "enter the no. to be searched form begining:- "; std::cin >> x; - comp(x - 1, s1, s2, s3); + comp(x - 1, &s1, &s2, &s3); return 0; } From 9dc580c045de9da759698d519ab86aba4b81e05b Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 21:35:28 -0400 Subject: [PATCH 210/433] rename to more meaningful text_search --- search/{searching.cpp => text_search.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename search/{searching.cpp => text_search.cpp} (100%) diff --git a/search/searching.cpp b/search/text_search.cpp similarity index 100% rename from search/searching.cpp rename to search/text_search.cpp From a3c1f04b31ce57d89cf02ebfe743fc37ed01078f Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 21:36:01 -0400 Subject: [PATCH 211/433] replace platform specific system("pause") --- search/text_search.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/search/text_search.cpp b/search/text_search.cpp index d0161973811..903442fc4a3 100644 --- a/search/text_search.cpp +++ b/search/text_search.cpp @@ -28,7 +28,7 @@ int main() { << paragraph.find(word) << std::endl << std::endl; } - system("pause"); + std::cin.get(); } } } From b122d659c326a58ff9c305e544181855e7f47fad Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 21:36:11 -0400 Subject: [PATCH 212/433] document text_search --- search/text_search.cpp | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/search/text_search.cpp b/search/text_search.cpp index 903442fc4a3..ee66a506a8a 100644 --- a/search/text_search.cpp +++ b/search/text_search.cpp @@ -1,9 +1,17 @@ +/** + * \file + * \brief Search for words in a long textual paragraph. + */ #include #include -#include - -char paragraph; +#ifdef _MSC_VER +#include // required for MS Visual C++ +#else +#include +#endif +/** Main function + */ int main() { std::string paragraph; std::cout << "Please enter your paragraph: \n"; From 5698363bd7814048975ebeb7543535e184bb5043 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 21:46:18 -0400 Subject: [PATCH 213/433] reformat documentation --- search/ternary_search.cpp | 67 ++++++++++++++++++++++++++------------- 1 file changed, 45 insertions(+), 22 deletions(-) diff --git a/search/ternary_search.cpp b/search/ternary_search.cpp index 4d1918d482d..73b89da7a2a 100644 --- a/search/ternary_search.cpp +++ b/search/ternary_search.cpp @@ -1,49 +1,57 @@ -/* +/** + * \file + * \brief [Ternary search](https://en.wikipedia.org/wiki/Ternary_search) + * algorithm + * * This is a divide and conquer algorithm. * It does this by dividing the search space by 3 parts and * using its property (usually monotonic property) to find * the desired index. * - * Time Complexity : O(log3 n) - * Space Complexity : O(1) (without the array) + * * Time Complexity : O(log3 n) + * * Space Complexity : O(1) (without the array) */ #include -/* +/** * The absolutePrecision can be modified to fit preference but * it is recommended to not go lower than 10 due to errors that * may occur. - * + */ +#define absolutePrecision 10 +/** * The value of _target should be decided or can be decided later * by using the variable of the function. */ - #define _target 10 -#define absolutePrecision 10 -#define MAX 10000000 -int N = 21; -int A[MAX] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 10}; +#define MAX 10000000 ///< Maximum length of array -/* +/** * get_input function is to receive input from standard IO + * @todo @christianbender Get input from STDIO or write input to memory as done + * above. */ -void get_input() { - // TODO(christianbender): Get input from STDIO or write input to memory as - // done above. -} +void get_input() {} -/* +/** * This is the iterative method of the ternary search which returns the index of * the element. + * \param[in] left lower interval limit + * \param[in] right upper interval limit + * \param[in] A array to search in + * \param[in] target value to search for + * \returns index where the target value was found + * \returns -1 if target value not found */ int it_ternary_search(int left, int right, int A[], int target) { while (1) { if (left < right) { if (right - left < absolutePrecision) { for (int i = left; i <= right; i++) - if (A[i] == target) return i; + if (A[i] == target) + return i; return -1; } @@ -69,15 +77,22 @@ int it_ternary_search(int left, int right, int A[], int target) { } } -/* +/** * This is the recursive method of the ternary search which returns the index of * the element. + * \param[in] left lower interval limit + * \param[in] right upper interval limit + * \param[in] A array to search in + * \param[in] target value to search for + * \returns index where the target value was found + * \returns -1 if target value not found */ int rec_ternary_search(int left, int right, int A[], int target) { if (left < right) { if (right - left < absolutePrecision) { for (int i = left; i <= right; i++) - if (A[i] == target) return i; + if (A[i] == target) + return i; return -1; } @@ -85,8 +100,10 @@ int rec_ternary_search(int left, int right, int A[], int target) { int oneThird = (left + right) / 3 + 1; int twoThird = (left + right) * 2 / 3 + 1; - if (A[oneThird] == target) return oneThird; - if (A[twoThird] == target) return twoThird; + if (A[oneThird] == target) + return oneThird; + if (A[twoThird] == target) + return twoThird; if (target < A[oneThird]) return rec_ternary_search(left, oneThird - 1, A, target); @@ -99,10 +116,13 @@ int rec_ternary_search(int left, int right, int A[], int target) { } } -/* +/** * ternary_search is a template function * You could either use it_ternary_search or rec_ternary_search according to * preference. + * \param [in] N length of array + * \param[in] A array to search in + * \param[in] target value to search for */ void ternary_search(int N, int A[], int target) { std::cout << it_ternary_search(0, N - 1, A, target) << '\t'; @@ -110,7 +130,10 @@ void ternary_search(int N, int A[], int target) { std::cout << std::endl; } +/** Main function */ int main() { + int N = 21; + int A[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 10}; get_input(); ternary_search(N, A, _target); return 0; From a9e160fe26972dd2ed17d8784359d6cf825e670e Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 29 May 2020 01:46:43 +0000 Subject: [PATCH 214/433] updating DIRECTORY.md --- DIRECTORY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index 51e840ef41c..740a6164753 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -177,8 +177,8 @@ * [Jump Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/jump_search.cpp) * [Linear Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/linear_search.cpp) * [Median Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/median_search.cpp) - * [Searching](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/searching.cpp) * [Ternary Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/ternary_search.cpp) + * [Text Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/text_search.cpp) ## Sorting * [Bead Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/bead_sort.cpp) From 68cf8540a1e6c9df1a4e4cb3a4ae29752c2e675e Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 22:48:52 -0400 Subject: [PATCH 215/433] delete secant method - it is identical to regula falsi --- .../secant_method.cpp | 37 ------------------- 1 file changed, 37 deletions(-) delete mode 100644 computer_oriented_statistical_methods/secant_method.cpp diff --git a/computer_oriented_statistical_methods/secant_method.cpp b/computer_oriented_statistical_methods/secant_method.cpp deleted file mode 100644 index c353ef850f4..00000000000 --- a/computer_oriented_statistical_methods/secant_method.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include -#include - -static float eq(float i) { - return (pow(i, 3) - (4 * i) - 9); // original equation -} - -int main() { - float a, b, z, c, m, n; - for (int i = 0; i < 100; i++) { - z = eq(i); - if (z >= 0) { - b = i; - a = --i; - break; - } - } - - std::cout << "\nFirst initial: " << a; - std::cout << "\nSecond initial: " << b; - for (int i = 0; i < 100; i++) { - float h, d; - m = eq(a); - n = eq(b); - - c = ((a * n) - (b * m)) / (n - m); - a = b; - b = c; - - z = eq(c); - if (z > 0 && z < 0.09) // stoping criteria - break; - } - - std::cout << "\n\nRoot: " << c; - return 0; -} From 7af2ad1eaaaaecd5a47aaf823c3049bfc8bf1bc9 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 23:04:35 -0400 Subject: [PATCH 216/433] document + improvize root finding algorithms --- .../bisection_method.cpp | 55 +++++++++++++--- .../false_position.cpp | 62 +++++++++++++++---- .../newton_raphson_method.cpp | 51 +++++++++------ 3 files changed, 127 insertions(+), 41 deletions(-) diff --git a/computer_oriented_statistical_methods/bisection_method.cpp b/computer_oriented_statistical_methods/bisection_method.cpp index 089828c9a3f..c93c529d248 100644 --- a/computer_oriented_statistical_methods/bisection_method.cpp +++ b/computer_oriented_statistical_methods/bisection_method.cpp @@ -1,25 +1,60 @@ +/** + * \file + * \brief Solve the equation \f$f(x)=0\f$ using [bisection + * method](https://en.wikipedia.org/wiki/Bisection_method) + * + * Given two points \f$a\f$ and \f$b\f$ such that \f$f(a)<0\f$ and + * \f$f(b)>0\f$, then the \f$(i+1)^\text{th}\f$ approximation is given by: \f[ + * x_{i+1} = \frac{a_i+b_i}{2} + * \f] + * For the next iteration, the interval is selected + * as: \f$[a,x]\f$ if \f$x>0\f$ or \f$[x,b]\f$ if \f$x<0\f$. The Process is + * continued till a close enough approximation is achieved. + * + * \see newton_raphson_method.cpp, false_position.cpp, secant_method.cpp + */ #include #include +#include -static float eq(float i) { +#define EPSILON \ + 1e-6 // std::numeric_limits::epsilon() ///< system accuracy limit +#define MAX_ITERATIONS 50000 ///< Maximum number of iterations to check + +/** define \f$f(x)\f$ to find root for + */ +static double eq(double i) { return (std::pow(i, 3) - (4 * i) - 9); // original equation } +/** get the sign of any given number */ +template +int sgn(T val) { + return (T(0) < val) - (val < T(0)); +} + +/** main function */ int main() { - float a, b, x, z; + double a = -1, b = 1, x, z; + int i; - for (int i = 0; i < 100; i++) { - z = eq(i); - if (z >= 0) { - b = i; - a = --i; + // loop to find initial intervals a, b + for (int i = 0; i < MAX_ITERATIONS; i++) { + z = eq(a); + x = eq(b); + if (sgn(z) == sgn(x)) { // same signs, increase interval + b++; + a--; + } else { // if opposite signs, we got our interval break; } } std::cout << "\nFirst initial: " << a; std::cout << "\nSecond initial: " << b; - for (int i = 0; i < 100; i++) { + + // start iterations + for (i = 0; i < MAX_ITERATIONS; i++) { x = (a + b) / 2; z = eq(x); std::cout << "\n\nz: " << z << "\t[" << a << " , " << b @@ -31,10 +66,10 @@ int main() { b = x; } - if (z > 0 && z < 0.0009) // stoping criteria + if (std::abs(z) < EPSILON) // stoping criteria break; } - std::cout << "\n\nRoot: " << x; + std::cout << "\n\nRoot: " << x << "\t\tSteps: " << i << std::endl; return 0; } diff --git a/computer_oriented_statistical_methods/false_position.cpp b/computer_oriented_statistical_methods/false_position.cpp index c5a31450868..aebd154bb07 100644 --- a/computer_oriented_statistical_methods/false_position.cpp +++ b/computer_oriented_statistical_methods/false_position.cpp @@ -1,19 +1,53 @@ +/** + * \file + * \brief Solve the equation \f$f(x)=0\f$ using [false position + * method](https://en.wikipedia.org/wiki/Regula_falsi), also known as the Secant + * method + * + * Given two points \f$a\f$ and \f$b\f$ such that \f$f(a)<0\f$ and + * \f$f(b)>0\f$, then the \f$(i+1)^\text{th}\f$ approximation is given by: \f[ + * x_{i+1} = \frac{a_i\cdot f(b_i) - b_i\cdot f(a_i)}{f(b_i) - f(a_i)} + * \f] + * For the next iteration, the interval is selected + * as: \f$[a,x]\f$ if \f$x>0\f$ or \f$[x,b]\f$ if \f$x<0\f$. The Process is + * continued till a close enough approximation is achieved. + * + * \see newton_raphson_method.cpp, bisection_method.cpp + */ #include #include #include +#include -static float eq(float i) { - return (pow(i, 3) - (4 * i) - 9); // origial equation +#define EPSILON \ + 1e-6 // std::numeric_limits::epsilon() ///< system accuracy limit +#define MAX_ITERATIONS 50000 ///< Maximum number of iterations to check + +/** define \f$f(x)\f$ to find root for + */ +static double eq(double i) { + return (std::pow(i, 3) - (4 * i) - 9); // origial equation +} + +/** get the sign of any given number */ +template +int sgn(T val) { + return (T(0) < val) - (val < T(0)); } +/** main function */ int main() { - float a, b, z, c, m, n; - system("clear"); - for (int i = 0; i < 100; i++) { - z = eq(i); - if (z >= 0) { - b = i; - a = --i; + double a = -1, b = 1, x, z, m, n, c; + int i; + + // loop to find initial intervals a, b + for (int i = 0; i < MAX_ITERATIONS; i++) { + z = eq(a); + x = eq(b); + if (sgn(z) == sgn(x)) { // same signs, increase interval + b++; + a--; + } else { // if opposite signs, we got our interval break; } } @@ -21,18 +55,20 @@ int main() { std::cout << "\nFirst initial: " << a; std::cout << "\nSecond initial: " << b; - for (int i = 0; i < 100; i++) { - float h, d; + for (i = 0; i < MAX_ITERATIONS; i++) { m = eq(a); n = eq(b); + c = ((a * n) - (b * m)) / (n - m); + a = c; z = eq(c); - if (z > 0 && z < 0.09) { // stoping criteria + + if (std::abs(z) < EPSILON) { // stoping criteria break; } } - std::cout << "\n\nRoot: " << c; + std::cout << "\n\nRoot: " << c << "\t\tSteps: " << i << std::endl; return 0; } diff --git a/computer_oriented_statistical_methods/newton_raphson_method.cpp b/computer_oriented_statistical_methods/newton_raphson_method.cpp index 47d2764908b..318363a3922 100644 --- a/computer_oriented_statistical_methods/newton_raphson_method.cpp +++ b/computer_oriented_statistical_methods/newton_raphson_method.cpp @@ -1,42 +1,57 @@ +/** + * \file + * \brief Solve the equation \f$f(x)=0\f$ using [Newton-Raphson + * method](https://en.wikipedia.org/wiki/Newton%27s_method) + * + * The \f$(i+1)^\text{th}\f$ approximation is given by: + * \f[ + * x_{i+1} = x_i - \frac{f(x_i)}{f'(x_i)} + * \f] + * + * \see bisection_method.cpp, false_position.cpp + */ #include +#include #include +#include -static float eq(float i) { +#define EPSILON \ + 1e-6 // std::numeric_limits::epsilon() ///< system accuracy limit +#define MAX_ITERATIONS 50000 ///< Maximum number of iterations to check + +/** define \f$f(x)\f$ to find root for + */ +static double eq(double i) { return (std::pow(i, 3) - (4 * i) - 9); // original equation } -static float eq_der(float i) { +/** define the derivative function \f$f'(x)\f$ + */ +static double eq_der(double i) { return ((3 * std::pow(i, 2)) - 4); // derivative of equation } +/** Main function */ int main() { - float a, b, z, c, m, n; + std::srand(std::time(nullptr)); // initialize randomizer - for (int i = 0; i < 100; i++) { - z = eq(i); - if (z >= 0) { - b = i; - a = --i; - break; - } - } + double z, c = std::rand() % 100, m, n; + int i; - std::cout << "\nFirst initial: " << a; - std::cout << "\nSecond initial: " << b; - c = (a + b) / 2; + std::cout << "\nInitial approximation: " << c; - for (int i = 0; i < 100; i++) { - float h; + // start iterations + for (i = 0; i < MAX_ITERATIONS; i++) { m = eq(c); n = eq_der(c); z = c - (m / n); c = z; - if (m > 0 && m < 0.009) // stoping criteria + if (std::abs(m) < EPSILON) // stoping criteria break; } - std::cout << "\n\nRoot: " << z << std::endl; + std::cout << "\n\nRoot: " << z << "\t\tSteps: " << i << std::endl; return 0; } From bf3ec59ec8e9a8ad3535446118508ab7ee3b6701 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 23:08:24 -0400 Subject: [PATCH 217/433] attempt to document gaussian elimination --- .../gaussian_elimination.cpp | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/computer_oriented_statistical_methods/gaussian_elimination.cpp b/computer_oriented_statistical_methods/gaussian_elimination.cpp index 0b8bb693de6..60b5648ec84 100644 --- a/computer_oriented_statistical_methods/gaussian_elimination.cpp +++ b/computer_oriented_statistical_methods/gaussian_elimination.cpp @@ -1,17 +1,26 @@ +/** + * \file + * \brief [Gaussian elimination + * method](https://en.wikipedia.org/wiki/Gaussian_elimination) + */ #include +/** Main function */ int main() { int mat_size, i, j, step; std::cout << "Matrix size: "; std::cin >> mat_size; + // create a 2D matrix by dynamic memory allocation double **mat = new double *[mat_size + 1], **x = new double *[mat_size]; for (i = 0; i <= mat_size; i++) { mat[i] = new double[mat_size + 1]; - if (i < mat_size) x[i] = new double[mat_size + 1]; + if (i < mat_size) + x[i] = new double[mat_size + 1]; } + // get the matrix elements from user std::cout << std::endl << "Enter value of the matrix: " << std::endl; for (i = 0; i < mat_size; i++) { for (j = 0; j <= mat_size; j++) { @@ -20,6 +29,7 @@ int main() { } } + // perform Gaussian elimination for (step = 0; step < mat_size - 1; step++) { for (i = step; i < mat_size - 1; i++) { double a = (mat[i + 1][step] / mat[step][step]); @@ -56,7 +66,8 @@ int main() { for (i = 0; i <= mat_size; i++) { delete[] mat[i]; - if (i < mat_size) delete[] x[i]; + if (i < mat_size) + delete[] x[i]; } delete[] mat; delete[] x; From 2e0a50b6f52cd158bc9b51d5e5e1336905d8dc25 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 23:11:39 -0400 Subject: [PATCH 218/433] added file brief --- .../ordinary_least_squares_regressor.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp b/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp index 06bd4ea5291..de02b27bba7 100644 --- a/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp +++ b/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp @@ -1,11 +1,13 @@ /** * @file + * \brief Linear regression example using [Ordinary least + * squares](https://en.wikipedia.org/wiki/Ordinary_least_squares) * * Program that gets the number of data samples and number of features per * sample along with output per sample. It applies OLS regression to compute * the regression output for additional test data samples. */ -#include +#include // for print formatting #include #include @@ -52,7 +54,8 @@ inline bool is_square(std::vector> const &A) { // Assuming A is square matrix size_t N = A.size(); for (size_t i = 0; i < N; i++) - if (A[i].size() != N) return false; + if (A[i].size() != N) + return false; return true; } @@ -265,7 +268,8 @@ std::vector> get_inverse( inverse[row] = inverse[row] / divisor; // Row transformations for (size_t row2 = 0; row2 < N; row2++) { - if (row2 == row) continue; + if (row2 == row) + continue; float factor = temp[row2][row]; temp[row2] = temp[row2] - factor * temp[row]; inverse[row2] = inverse[row2] - factor * inverse[row]; From 68392e2aa866f6bb0ac5d1b84f4e37ca3beaaed2 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 28 May 2020 23:22:24 -0400 Subject: [PATCH 219/433] commented doxygen-mainpage, added files-list link --- README.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b56c4f5f40e..9fb649a0e5e 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,7 @@ -# The Algorithms - C++ # {#mainpage} + +# The Algorithms - C++ [![contributions welcome](https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square)](https://github.com/kvedala/C-Plus-Plus/blob/master/CONTRIBUTION.md)  ![GitHub repo size](https://img.shields.io/github/repo-size/kvedala/C-Plus-Plus?color=red&style=flat-square) ![GitHub closed pull requests](https://img.shields.io/github/issues-pr-closed/kvedala/C-Plus-Plus?color=green&style=flat-square) @@ -6,9 +9,11 @@ ![cpplint](https://github.com/kvedala/C-Plus-Plus/workflows/cpplint_modified_files/badge.svg) ![C/C++ CI](https://github.com/kvedala/C-Plus-Plus/workflows/C/C++%20CI/badge.svg) -[Documentation](https://kvedala.github.io/C-Plus-Plus) +[Online Documentation](https://kvedala.github.io/C-Plus-Plus). -### All algorithms implemented in C++ (for education) +Click on [Files menu](https://kvedala.github.io/C-Plus-Plus/build/html/files.html) to see the list of all the files documented with the code. + +### Algorithms implemented in C++ (for education) The implementations are for learning purpose. They may be less efficient than the implementation in the standard library. ### Contribute Guidelines From 05e544bdce355e62e636c041f6cf028cb4e2d5d7 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 28 May 2020 23:23:23 -0400 Subject: [PATCH 220/433] corrected files list link path --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9fb649a0e5e..df1f13b248a 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ This is for Doxygen to recognize as the index file for the complete documentatio [Online Documentation](https://kvedala.github.io/C-Plus-Plus). -Click on [Files menu](https://kvedala.github.io/C-Plus-Plus/build/html/files.html) to see the list of all the files documented with the code. +Click on [Files menu](https://kvedala.github.io/C-Plus-Plus/html/files.html) to see the list of all the files documented with the code. ### Algorithms implemented in C++ (for education) The implementations are for learning purpose. They may be less efficient than the implementation in the standard library. From 1ec59ba1dd818627647954e86babcf7fe4b99793 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 28 May 2020 23:24:53 -0400 Subject: [PATCH 221/433] files-list link correction - this time works :) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index df1f13b248a..2cad007c323 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ This is for Doxygen to recognize as the index file for the complete documentatio [Online Documentation](https://kvedala.github.io/C-Plus-Plus). -Click on [Files menu](https://kvedala.github.io/C-Plus-Plus/html/files.html) to see the list of all the files documented with the code. +Click on [Files menu](https://kvedala.github.io/C-Plus-Plus/files.html) to see the list of all the files documented with the code. ### Algorithms implemented in C++ (for education) The implementations are for learning purpose. They may be less efficient than the implementation in the standard library. From 7dfde74ece640aeb21f75ec2e28c7133614a8581 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 23:28:03 -0400 Subject: [PATCH 222/433] document successive approximations --- .../successive_approximation.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/computer_oriented_statistical_methods/successive_approximation.cpp b/computer_oriented_statistical_methods/successive_approximation.cpp index efbcc3bbff3..338831464e5 100644 --- a/computer_oriented_statistical_methods/successive_approximation.cpp +++ b/computer_oriented_statistical_methods/successive_approximation.cpp @@ -1,9 +1,22 @@ +/** + * \file + * \brief Method of successive approximations using [fixed-point + * iteration](https://en.wikipedia.org/wiki/Fixed-point_iteration) method + */ #include #include +/** equation 1 + * \f[f(y) = 3y - \cos y -2\f] + */ static float eq(float y) { return ((3 * y) - (cos(y)) - 2); } + +/** equation 2 + * \f[f(y) = \frac{\cos y}{2} +2\f] + */ static float eqd(float y) { return ((0.5) * ((cos(y)) + 2)); } +/** Main function */ int main() { float y, x1, x2, x3, sum, s, a, f1, f2, gd; int i, n; From 413198bc36c9b758dd43dc6699e52ffeae94c441 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 23:30:10 -0400 Subject: [PATCH 223/433] cleaner equation --- .../successive_approximation.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/computer_oriented_statistical_methods/successive_approximation.cpp b/computer_oriented_statistical_methods/successive_approximation.cpp index 338831464e5..351382f2418 100644 --- a/computer_oriented_statistical_methods/successive_approximation.cpp +++ b/computer_oriented_statistical_methods/successive_approximation.cpp @@ -9,12 +9,12 @@ /** equation 1 * \f[f(y) = 3y - \cos y -2\f] */ -static float eq(float y) { return ((3 * y) - (cos(y)) - 2); } +static float eq(float y) { return (3 * y) - cos(y) - 2; } /** equation 2 - * \f[f(y) = \frac{\cos y}{2} +2\f] + * \f[f(y) = \frac{\cos y+2}{2}\f] */ -static float eqd(float y) { return ((0.5) * ((cos(y)) + 2)); } +static float eqd(float y) { return 0.5 * (cos(y) + 2); } /** Main function */ int main() { From 1afdaa24b6f739bba79004d1226391ccc937cd74 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 29 May 2020 03:36:31 +0000 Subject: [PATCH 224/433] updating DIRECTORY.md --- DIRECTORY.md | 1 - 1 file changed, 1 deletion(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index 740a6164753..189d6041b88 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -15,7 +15,6 @@ * [Gaussian Elimination](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/gaussian_elimination.cpp) * [Newton Raphson Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/newton_raphson_method.cpp) * [Ordinary Least Squares Regressor](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp) - * [Secant Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/secant_method.cpp) * [Successive Approximation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/successive_approximation.cpp) ## Data Structure From 8621a1db73398891c502f96ad0a3ac2dbcf0b5c5 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Fri, 29 May 2020 07:53:46 -0400 Subject: [PATCH 225/433] documented kmp string search --- strings/knuth_morris_pratt.cpp | 120 ++++++++++++++++++++------------- 1 file changed, 72 insertions(+), 48 deletions(-) diff --git a/strings/knuth_morris_pratt.cpp b/strings/knuth_morris_pratt.cpp index f6f1169d30b..b83cab96632 100644 --- a/strings/knuth_morris_pratt.cpp +++ b/strings/knuth_morris_pratt.cpp @@ -1,64 +1,88 @@ -/* - The Knuth-Morris-Pratt Algorithm for finding a pattern within a piece of text - with complexity O(n + m) - 1) Preprocess pattern to identify any suffixes that are identical to prefixes - This tells us where to continue from if we get a mismatch between a character in our pattern - and the text. - 2) Step through the text one character at a time and compare it to a character in the pattern - updating our location within the pattern if necessary -*/ +/** + * \file + * \brief The [Knuth-Morris-Pratt + * Algorithm](https://en.wikipedia.org/wiki/Knuth–Morris–Pratt_algorithm) for + * finding a pattern within a piece of text with complexity O(n + m) + * + * 1. Preprocess pattern to identify any suffixes that are identical to + * prefixes. This tells us where to continue from if we get a mismatch between a + * character in our pattern and the text. + * 2. Step through the text one character at a time and compare it to a + * character in the pattern updating our location within the pattern if + * necessary + */ -#include -#include -#include -using namespace std; -vector getFailureArray(string pattern){ - int pattern_length=pattern.size(); - vectorfailure(pattern_length+1); - failure[0]=-1; - int j=-1; - for(int i=0; i +#ifdef _MSC_VER +#include // use this for MS Visucal C++ +#else +#include +#endif +#include + +/** + * Generate the partial match table aka failure function for a pattern to + * search. + * \param[in] pattern text for which to create the partial match table + * \returns the partial match table as a vector array + */ +std::vector getFailureArray(const std::string &pattern) { + int pattern_length = pattern.size(); + std::vector failure(pattern_length + 1); + failure[0] = -1; + int j = -1; + + for (int i = 0; i < pattern_length; i++) { + while (j != -1 && pattern[j] != pattern[i]) { + j = failure[j]; } j++; - failure[i+1]=j; + failure[i + 1] = j; } return failure; } -bool kmp(string pattern,string text){ - int text_length=text.size(),pattern_length=pattern.size(); - vectorfailure=getFailureArray(pattern); - int k=0; - for(int j=0; j failure = getFailureArray(pattern); + + int k = 0; + for (int j = 0; j < text_length; j++) { + while (k != -1 && pattern[k] != text[j]) { + k = failure[k]; } k++; - if(k==pattern_length)return true; + if (k == pattern_length) + return true; } return false; } -int main() -{ - - string text="alskfjaldsabc1abc1abc12k23adsfabcabc"; - string pattern="abc1abc12l"; - if(kmp(pattern,text)==true){ - cout<<"Found"< Date: Fri, 29 May 2020 08:00:58 -0400 Subject: [PATCH 226/433] document brute force string search --- strings/brute_force_string_searching.cpp | 87 ++++++++++++------------ 1 file changed, 44 insertions(+), 43 deletions(-) diff --git a/strings/brute_force_string_searching.cpp b/strings/brute_force_string_searching.cpp index 3288b36b0a9..9a2b5327a35 100644 --- a/strings/brute_force_string_searching.cpp +++ b/strings/brute_force_string_searching.cpp @@ -1,52 +1,53 @@ -#include -#include -#include +/** + * @file + * @brief String pattern search - brute force + */ +#include +#ifdef _MSC_VER +#include // use this for MS Visucal C++ +#else +#include +#endif +#include -using std::string; +/** + * Find a pattern in a string by comparing the pattern to every substring. + * @param text Any string that might contain the pattern. + * @param pattern String that we are searching for. + * @return Index where the pattern starts in the text + * @return -1 if the pattern was not found. + */ +int brute_force(const std::string &text, const std::string &pattern) { + size_t pat_l = pattern.length(); + size_t txt_l = text.length(); + int index = -1; + if (pat_l <= txt_l) { + for (size_t i = 0; i < txt_l - pat_l + 1; i++) { + std::string s = text.substr(i, pat_l); + if (s == pattern) { + index = i; + break; + } + } + } + return index; +} -int brute_force(string text, string pattern); -std::vector> test_set = { +/** set of test cases */ +const std::vector> test_set = { // {text, pattern, expected output} - {"a", "aa", "-1"}, - {"a", "a", "0"}, - {"ba", "b", "0"}, - {"bba", "bb", "0"}, - {"bbca", "c", "2"}, - {"ab", "b", "1"} -}; + {"a", "aa", "-1"}, {"a", "a", "0"}, {"ba", "b", "0"}, + {"bba", "bb", "0"}, {"bbca", "c", "2"}, {"ab", "b", "1"}}; +/** Main function */ int main() { - for (size_t i = 0 ; i < test_set.size(); i++) { - int output = brute_force(test_set[i][0], test_set[i][1]); - if (std::to_string(output) == test_set[i][2]) - std::cout << "success\n"; + for (size_t i = 0; i < test_set.size(); i++) { + int output = brute_force(test_set[i][0], test_set[i][1]); + + if (std::to_string(output) == test_set[i][2]) + std::cout << "success\n"; else - std::cout << "failure\n"; + std::cout << "failure\n"; } return 0; } - -/* - *@description Find a pattern in a string by comparing the pattern - * to every substring. - *@param text Any string that might contain the pattern. - *@param pattern String that we are searching for. - *@return Index where the pattern starts in the text or - * -1 if the pattern was not found. - */ - -int brute_force(string text, string pattern) { - size_t pat_l = pattern.length(); - size_t txt_l = text.length(); - int index = -1; - if (pat_l <= txt_l) { - for (size_t i = 0; i < txt_l-pat_l+1; i++) { - string s = text.substr(i, pat_l); - if (s == pattern) { - index = i; - break; - } - } - } - return index; -} From 26701b38befee0151c124e4e0ae3702e88ed149a Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Fri, 29 May 2020 08:27:33 -0400 Subject: [PATCH 227/433] document rabin-karp string search --- strings/rabin_karp.cpp | 108 ++++++++++++++++++++++++++--------------- 1 file changed, 68 insertions(+), 40 deletions(-) diff --git a/strings/rabin_karp.cpp b/strings/rabin_karp.cpp index 62e3691c133..018ff56324f 100644 --- a/strings/rabin_karp.cpp +++ b/strings/rabin_karp.cpp @@ -1,39 +1,64 @@ -/* - * file name : rabin_karp.cpp - * author : Amit Kumar - * Copyright : 2020 , Amit Kumar - * version : 1.0 +/** + * \file + * \brief The [Rabin-Karp + * Algorithm](https://en.wikipedia.org/wiki/Rabin–Karp_algorithm) for finding a + * pattern within a piece of text with complexity O(n + m) */ -#include -#include -#include -#include +#include +#include +#include +#ifdef _MSC_VER +#include // use this for MS Visucal C++ +#else +#include +#endif -using std::string; -using std::pow; +#define PRIME 5 ///< Prime modulus for hash functions -#define PRIME 5 - -int64_t create_hash(string s , int n) { +/** + * convert a string to an intger - called as hashing function + * \param[in] s source of string to hash + * \param[in] n length of substring to hash + * \returns hash integer + */ +int64_t create_hash(const std::string& s, int n) { int64_t result = 0; - for ( int i = 0; i < n; ++i ) { - result += (int64_t)(s[i] * (int64_t)pow(PRIME , i)); + for (int i = 0; i < n; ++i) { + result += (int64_t)(s[i] * (int64_t)pow(PRIME, i)); } return result; } -int64_t recalculate_hash(string s , int old_index , - int new_index , int64_t old_hash , int patLength) { +/** + * re-hash a string using known existing hash + * \param[in] s source of string to hash + * \param[in] old_index previous index of string + * \param[in] new_index new index of string + * \param[in] old_hash previous hash of substring + * \param[in] patLength length of substring to hash + * \returns new hash integer + */ +int64_t recalculate_hash(const std::string& s, int old_index, int new_index, + int64_t old_hash, int patLength) { int64_t new_hash = old_hash - s[old_index]; new_hash /= PRIME; - new_hash += (int64_t)(s[new_index]*(int64_t)pow(PRIME, patLength-1)); + new_hash += (int64_t)(s[new_index] * (int64_t)pow(PRIME, patLength - 1)); return new_hash; } -bool check_if_equal(string str1 , string str2 , - int start1 , int end1 , - int start2 , int end2) { - if (end1-start1 != end2-start2) { +/** + * compare if two sub-strings are equal + * \param[in] str1 string pattern to search + * \param[in] str2 text in which to search + * \param[in] start1,end1 start and end indices for substring in str1 + * \param[in] start2,end2 start and end indices for substring in str2 + * \returns `true` if pattern was found + * \returns `false` if pattern was not found + * @note can this be replaced by std::string::compare? + */ +bool check_if_equal(const std::string& str1, const std::string& str2, + int start1, int end1, int start2, int end2) { + if (end1 - start1 != end2 - start2) { return false; } while (start1 <= end1 && start2 <= end2) { @@ -46,33 +71,36 @@ bool check_if_equal(string str1 , string str2 , return true; } -/* - * @description : search pattern in the given text - * @param : string str - * @param : string pat - * @return index of first occurrence of pattern or -1 if pattern not found +/** + * Perform string pattern search using Rabin-Karp algorithm + * @param[in] str string to search in + * @param[in] pat pattern to search for + * @return index of first occurrence of pattern + * @return -1 if pattern not found */ -int rabin_karp(const string &str , const string& pat) { - int64_t pat_hash = create_hash(pat , pat.size()); - int64_t str_hash = create_hash(str , pat.size()); - for (int i=0; i <= str.size()-pat.size(); ++i) { +int rabin_karp(const std::string& str, const std::string& pat) { + int64_t pat_hash = create_hash(pat, pat.size()); + int64_t str_hash = create_hash(str, pat.size()); + for (int i = 0; i <= str.size() - pat.size(); ++i) { if (pat_hash == str_hash && - check_if_equal(str , pat , i , i+pat.size()-1 , 0 , pat.size()-1)) { - return i; + check_if_equal(str, pat, i, i + pat.size() - 1, 0, + pat.size() - 1)) { + return i; } - if (i < str.size()-pat.size()) { + if (i < str.size() - pat.size()) { str_hash = - recalculate_hash(str, i, i+pat.size(), str_hash, pat.size()); + recalculate_hash(str, i, i + pat.size(), str_hash, pat.size()); } } return -1; // return -1 if given pattern not found } +/** Main function */ int main(void) { - assert(rabin_karp("helloWorld", "world") == -1); - assert(rabin_karp("helloWorld", "World") == 5); - assert(rabin_karp("this_is_c++" , "c++") == 8); - assert(rabin_karp("happy_coding", "happy") == 0); + assert(rabin_karp("helloWorld", "world") == -1); + assert(rabin_karp("helloWorld", "World") == 5); + assert(rabin_karp("this_is_c++", "c++") == 8); + assert(rabin_karp("happy_coding", "happy") == 0); return 0; } From 82362529dfb4d9f1d8e14be74388ef6e1f4eee55 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Fri, 29 May 2020 08:32:44 -0400 Subject: [PATCH 228/433] fixed mainpage readme --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 2cad007c323..85ddf1bb9c2 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ - +{#mainpage} +--> # The Algorithms - C++ [![contributions welcome](https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square)](https://github.com/kvedala/C-Plus-Plus/blob/master/CONTRIBUTION.md)  ![GitHub repo size](https://img.shields.io/github/repo-size/kvedala/C-Plus-Plus?color=red&style=flat-square) From a79ce9d2b610ffea591c10a90e6550950cffe7bf Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Fri, 29 May 2020 08:42:21 -0400 Subject: [PATCH 229/433] doxygen v1.8.18 will suppress out the #minipage in the markdown --- README.md | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 85ddf1bb9c2..df39ee55415 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,5 @@ - -# The Algorithms - C++ +# The Algorithms - C++ # {#mainpage} + [![contributions welcome](https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square)](https://github.com/kvedala/C-Plus-Plus/blob/master/CONTRIBUTION.md)  ![GitHub repo size](https://img.shields.io/github/repo-size/kvedala/C-Plus-Plus?color=red&style=flat-square) ![GitHub closed pull requests](https://img.shields.io/github/issues-pr-closed/kvedala/C-Plus-Plus?color=green&style=flat-square) From 8036cf033f9606596edfd0da2c58006d789abce0 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Fri, 29 May 2020 09:44:08 -0400 Subject: [PATCH 230/433] cpplint correction for header guard style --- math/large_number.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/math/large_number.h b/math/large_number.h index 9596221878e..c1a3665e4d1 100644 --- a/math/large_number.h +++ b/math/large_number.h @@ -4,8 +4,8 @@ * numbers. */ -#ifndef OTHERS_LARGE_NUMBER_H_ -#define OTHERS_LARGE_NUMBER_H_ +#ifndef MATH_LARGE_NUMBER_H_ +#define MATH_LARGE_NUMBER_H_ #include #include #include @@ -284,4 +284,4 @@ class large_number { _digits; /**< where individual digits are stored */ }; -#endif // OTHERS_LARGE_NUMBER_H_ +#endif // MATH_LARGE_NUMBER_H_ From 29705aca4bb81ee6ce2dd2abe0953203cb2b0cef Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:06:37 -0400 Subject: [PATCH 231/433] github action to auto format source code per cpplint standard --- .github/workflows/clang-format.yml | 39 ++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 .github/workflows/clang-format.yml diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml new file mode 100644 index 00000000000..6a95452e84f --- /dev/null +++ b/.github/workflows/clang-format.yml @@ -0,0 +1,39 @@ +name: Code Formatting + +on: [push] +# push: +# branches: [ master ] +# pull_request: +# branches: [ master ] + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: requirements + run: | + sudo apt -qq -y update + sudo apt -qq install clang-format + - uses: actions/checkout@master + with: + submodules: true + - name: Formatter + run: | + for fname in $(find . -name '*.cpp' -o -name '*.h') + do + clang-format --verbose -i --style="$line1 $line2 $line3 $line4" "$fname" + done + env: + line1: "{ BasedOnStyle: Google, UseTab: Never," + line2: "IndentWidth: 4, TabWidth: 4, BreakBeforeBraces: Allman," + line3: "AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: false," + line4: "ColumnLimit: 80, AccessModifierOffset: -4 }" + - name: Commit files + run: | + cp -rp ./build/html/* . && rm -rf ./build && ls -lah + git config --global user.name github-actions + git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' + git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY + git commit -am "formatting source-code for $GITHUB_SHA" || true + git push + From e459ea26d347140851b2accd8b1fe0d66ac629de Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:07:47 -0400 Subject: [PATCH 232/433] updated setting to add 1 space before `private` and `public` keywords --- .github/workflows/clang-format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 6a95452e84f..4acf665366b 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -27,7 +27,7 @@ jobs: line1: "{ BasedOnStyle: Google, UseTab: Never," line2: "IndentWidth: 4, TabWidth: 4, BreakBeforeBraces: Allman," line3: "AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: false," - line4: "ColumnLimit: 80, AccessModifierOffset: -4 }" + line4: "ColumnLimit: 80, AccessModifierOffset: -3 }" - name: Commit files run: | cp -rp ./build/html/* . && rm -rf ./build && ls -lah From adae176d2a235defd055200bc6d327949ba48c46 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:22:51 -0400 Subject: [PATCH 233/433] auto rename files and auto format code --- .github/workflows/clang-format.yml | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 4acf665366b..e44869528a8 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -17,23 +17,30 @@ jobs: - uses: actions/checkout@master with: submodules: true - - name: Formatter + - name: Setup Git Specs + run: | + git config --global user.name github-actions + git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' + git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY + - name: Filename Formatter + for fname in $(find . -name '*.cpp' -o -name '*.h') + do + new_fname = tr ' ' '_' $fname + new_fname = tr 'A-Z' 'a-z' $fname + echo $new_fname + done + git commit -am "formatting filenames $GITHUB_SHA" || true + - name: Clang Formatter run: | for fname in $(find . -name '*.cpp' -o -name '*.h') do clang-format --verbose -i --style="$line1 $line2 $line3 $line4" "$fname" done + git commit -am "formatting source-code for $GITHUB_SHA" || true env: line1: "{ BasedOnStyle: Google, UseTab: Never," line2: "IndentWidth: 4, TabWidth: 4, BreakBeforeBraces: Allman," line3: "AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: false," line4: "ColumnLimit: 80, AccessModifierOffset: -3 }" - - name: Commit files - run: | - cp -rp ./build/html/* . && rm -rf ./build && ls -lah - git config --global user.name github-actions - git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' - git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - git commit -am "formatting source-code for $GITHUB_SHA" || true - git push - + # -name: Git Push + # run: git push From 4c282aed0f30a4b2af10bab3f95471cb1f44412a Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:24:14 -0400 Subject: [PATCH 234/433] added missing "run" for step --- .github/workflows/clang-format.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index e44869528a8..b4a46ed0450 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -23,6 +23,7 @@ jobs: git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - name: Filename Formatter + run: | for fname in $(find . -name '*.cpp' -o -name '*.h') do new_fname = tr ' ' '_' $fname From 8edc022423ad5c45154ff2b835b5bb33f25cd26a Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:26:17 -0400 Subject: [PATCH 235/433] corrected asignmemt operation --- .github/workflows/clang-format.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index b4a46ed0450..cea2616223f 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -26,8 +26,8 @@ jobs: run: | for fname in $(find . -name '*.cpp' -o -name '*.h') do - new_fname = tr ' ' '_' $fname - new_fname = tr 'A-Z' 'a-z' $fname + $new_fname = tr ' ' '_' $fname + $new_fname = tr 'A-Z' 'a-z' $new_fname echo $new_fname done git commit -am "formatting filenames $GITHUB_SHA" || true From 0ea90eb3bd10aae256b01abd431e2b82f963abe6 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:30:55 -0400 Subject: [PATCH 236/433] fixed trim and assign syntax --- .github/workflows/clang-format.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index cea2616223f..6071aef07b9 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -26,8 +26,8 @@ jobs: run: | for fname in $(find . -name '*.cpp' -o -name '*.h') do - $new_fname = tr ' ' '_' $fname - $new_fname = tr 'A-Z' 'a-z' $new_fname + new_fname="$(echo -e "${fname}" | tr ' ' '_')" + new_fname="$(echo -e "${new_fname}"tr'A-Z' 'a-z')" echo $new_fname done git commit -am "formatting filenames $GITHUB_SHA" || true From 1a8cc7ecec9c0ac381685af8d31f2d254b7fd593 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:33:10 -0400 Subject: [PATCH 237/433] added git move for renaming bad filenames --- .github/workflows/clang-format.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 6071aef07b9..0acad3a2d04 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -29,6 +29,7 @@ jobs: new_fname="$(echo -e "${fname}" | tr ' ' '_')" new_fname="$(echo -e "${new_fname}"tr'A-Z' 'a-z')" echo $new_fname + git mv $fname $new_fname done git commit -am "formatting filenames $GITHUB_SHA" || true - name: Clang Formatter From a045cf894f745200accaa8f047a2c560c987c0a4 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:34:20 -0400 Subject: [PATCH 238/433] added missing pipe for trim --- .github/workflows/clang-format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 0acad3a2d04..1b35cd16b41 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -27,7 +27,7 @@ jobs: for fname in $(find . -name '*.cpp' -o -name '*.h') do new_fname="$(echo -e "${fname}" | tr ' ' '_')" - new_fname="$(echo -e "${new_fname}"tr'A-Z' 'a-z')" + new_fname="$(echo -e "${new_fname}" | tr'A-Z' 'a-z')" echo $new_fname git mv $fname $new_fname done From cbcebf30ecb8244129e90b08c6b9e5c2cad7873c Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:35:14 -0400 Subject: [PATCH 239/433] added missing space --- .github/workflows/clang-format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 1b35cd16b41..bec69d4815a 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -27,7 +27,7 @@ jobs: for fname in $(find . -name '*.cpp' -o -name '*.h') do new_fname="$(echo -e "${fname}" | tr ' ' '_')" - new_fname="$(echo -e "${new_fname}" | tr'A-Z' 'a-z')" + new_fname="$(echo -e "${new_fname}" | tr 'A-Z' 'a-z')" echo $new_fname git mv $fname $new_fname done From 48bf52907fdc0c15af4fc92e8a61d6e46f804732 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:37:36 -0400 Subject: [PATCH 240/433] use old and new fnames --- .github/workflows/clang-format.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index bec69d4815a..f3940c5b6e7 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -26,10 +26,11 @@ jobs: run: | for fname in $(find . -name '*.cpp' -o -name '*.h') do + old_fname="${fname}" new_fname="$(echo -e "${fname}" | tr ' ' '_')" new_fname="$(echo -e "${new_fname}" | tr 'A-Z' 'a-z')" echo $new_fname - git mv $fname $new_fname + git mv $old_fname $new_fname done git commit -am "formatting filenames $GITHUB_SHA" || true - name: Clang Formatter From 1d11ab428426480f5cf2c775e7dfe9fd35c1ecd4 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:40:45 -0400 Subject: [PATCH 241/433] store old fname using echo --- .github/workflows/clang-format.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index f3940c5b6e7..33eed8c2876 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -26,11 +26,11 @@ jobs: run: | for fname in $(find . -name '*.cpp' -o -name '*.h') do - old_fname="${fname}" + old_fname="$(echo -e ${fname})" new_fname="$(echo -e "${fname}" | tr ' ' '_')" new_fname="$(echo -e "${new_fname}" | tr 'A-Z' 'a-z')" - echo $new_fname - git mv $old_fname $new_fname + echo "${old_fname} --> ${new_fname}" + git mv ${old_fname} ${new_fname} done git commit -am "formatting filenames $GITHUB_SHA" || true - name: Clang Formatter From 93b9bc11473de0706eb450f35c60bca03c10febe Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:43:28 -0400 Subject: [PATCH 242/433] move files only if there is a change in filename --- .github/workflows/clang-format.yml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 33eed8c2876..db96de16ae0 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -29,8 +29,11 @@ jobs: old_fname="$(echo -e ${fname})" new_fname="$(echo -e "${fname}" | tr ' ' '_')" new_fname="$(echo -e "${new_fname}" | tr 'A-Z' 'a-z')" - echo "${old_fname} --> ${new_fname}" - git mv ${old_fname} ${new_fname} + if [$old_fname != $new_fname] + then + echo "${old_fname} --> ${new_fname}" + git mv ${old_fname} ${new_fname} + fi done git commit -am "formatting filenames $GITHUB_SHA" || true - name: Clang Formatter From 493c52f19ad05f491068db3dfd52cd6d876a4a15 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:45:54 -0400 Subject: [PATCH 243/433] put old filenames in quotes --- .github/workflows/clang-format.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index db96de16ae0..5fe5e589d8b 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -29,10 +29,10 @@ jobs: old_fname="$(echo -e ${fname})" new_fname="$(echo -e "${fname}" | tr ' ' '_')" new_fname="$(echo -e "${new_fname}" | tr 'A-Z' 'a-z')" - if [$old_fname != $new_fname] + if [ '$old_fname' != '$new_fname' ] then - echo "${old_fname} --> ${new_fname}" - git mv ${old_fname} ${new_fname} + echo "'${old_fname}' --> ${new_fname}" + git mv '${old_fname}' ${new_fname} fi done git commit -am "formatting filenames $GITHUB_SHA" || true From 45f5bb65d0a78026a7ad7375afdf35293b41e001 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:47:40 -0400 Subject: [PATCH 244/433] use double quote for old filename --- .github/workflows/clang-format.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 5fe5e589d8b..a8ba8a273b2 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -29,10 +29,10 @@ jobs: old_fname="$(echo -e ${fname})" new_fname="$(echo -e "${fname}" | tr ' ' '_')" new_fname="$(echo -e "${new_fname}" | tr 'A-Z' 'a-z')" - if [ '$old_fname' != '$new_fname' ] + if [ $old_fname != $new_fname ] then echo "'${old_fname}' --> ${new_fname}" - git mv '${old_fname}' ${new_fname} + git mv "${old_fname}" ${new_fname} fi done git commit -am "formatting filenames $GITHUB_SHA" || true From 29c066de048ccbf9f11955be02b8e1ed81c19013 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:50:17 -0400 Subject: [PATCH 245/433] escape double quotes --- .github/workflows/clang-format.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index a8ba8a273b2..1a9d5ccfcb4 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -31,8 +31,8 @@ jobs: new_fname="$(echo -e "${new_fname}" | tr 'A-Z' 'a-z')" if [ $old_fname != $new_fname ] then - echo "'${old_fname}' --> ${new_fname}" - git mv "${old_fname}" ${new_fname} + echo '"${old_fname}" --> ${new_fname}' + git mv \"${old_fname}\" ${new_fname} fi done git commit -am "formatting filenames $GITHUB_SHA" || true From c0dcc91276e17be5dc55bc1397bafbdae6bce604 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:52:50 -0400 Subject: [PATCH 246/433] remove old_fname --- .github/workflows/clang-format.yml | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 1a9d5ccfcb4..50f2169dacd 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -26,13 +26,12 @@ jobs: run: | for fname in $(find . -name '*.cpp' -o -name '*.h') do - old_fname="$(echo -e ${fname})" new_fname="$(echo -e "${fname}" | tr ' ' '_')" new_fname="$(echo -e "${new_fname}" | tr 'A-Z' 'a-z')" - if [ $old_fname != $new_fname ] + if [ $fname != $new_fname ] then - echo '"${old_fname}" --> ${new_fname}' - git mv \"${old_fname}\" ${new_fname} + echo '"${fname}" --> ${new_fname}' + git mv "${fname}" ${new_fname} fi done git commit -am "formatting filenames $GITHUB_SHA" || true From 63f13ea50bb03f59ae0057b3fcc0f1342426baa1 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:00:34 -0400 Subject: [PATCH 247/433] try escape characters and echo" --- .github/workflows/clang-format.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 50f2169dacd..fac11f90854 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -30,8 +30,8 @@ jobs: new_fname="$(echo -e "${new_fname}" | tr 'A-Z' 'a-z')" if [ $fname != $new_fname ] then - echo '"${fname}" --> ${new_fname}' - git mv "${fname}" ${new_fname} + echo -e "'"$fname"' --> '"$new_fname"'" + git mv "$(echo -e "$fname")" $new_fname fi done git commit -am "formatting filenames $GITHUB_SHA" || true From 18a74bb9a082147720bb30ef3ceb0a23a9ac6dcf Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:06:55 -0400 Subject: [PATCH 248/433] add file-type to find --- .github/workflows/clang-format.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index fac11f90854..aaea3325fee 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -24,14 +24,14 @@ jobs: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - name: Filename Formatter run: | - for fname in $(find . -name '*.cpp' -o -name '*.h') + for fname in $(find . -type f -name '*.cpp' -o -name '*.h') do new_fname="$(echo -e "${fname}" | tr ' ' '_')" new_fname="$(echo -e "${new_fname}" | tr 'A-Z' 'a-z')" if [ $fname != $new_fname ] then - echo -e "'"$fname"' --> '"$new_fname"'" - git mv "$(echo -e "$fname")" $new_fname + echo -e "$(echo -e "$fname")" --> '"$new_fname"'" + git mv "$fname" $new_fname fi done git commit -am "formatting filenames $GITHUB_SHA" || true From 24f65d859954410e749d4b27a57be776a53d8adb Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:08:48 -0400 Subject: [PATCH 249/433] cleanup echo --- .github/workflows/clang-format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index aaea3325fee..5ee612c9929 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -30,7 +30,7 @@ jobs: new_fname="$(echo -e "${new_fname}" | tr 'A-Z' 'a-z')" if [ $fname != $new_fname ] then - echo -e "$(echo -e "$fname")" --> '"$new_fname"'" + echo -e $fname" --> "$new_fname git mv "$fname" $new_fname fi done From bb973aa17d201af39b8e04e9c1911c1e8b393b3a Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:11:49 -0400 Subject: [PATCH 250/433] ensure all trim variables are also in quotes --- .github/workflows/clang-format.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 5ee612c9929..1f9dcb98b91 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -26,8 +26,8 @@ jobs: run: | for fname in $(find . -type f -name '*.cpp' -o -name '*.h') do - new_fname="$(echo -e "${fname}" | tr ' ' '_')" - new_fname="$(echo -e "${new_fname}" | tr 'A-Z' 'a-z')" + new_fname="$(echo -e ${fname} | tr ' ' '_')" + new_fname="$(echo -e ${new_fname} | tr 'A-Z' 'a-z')" if [ $fname != $new_fname ] then echo -e $fname" --> "$new_fname From b5f4637cc7d5419104155576c077438a18ad11b3 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:14:56 -0400 Subject: [PATCH 251/433] try escape -quote again --- .github/workflows/clang-format.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 1f9dcb98b91..8c56fbed666 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -26,11 +26,11 @@ jobs: run: | for fname in $(find . -type f -name '*.cpp' -o -name '*.h') do - new_fname="$(echo -e ${fname} | tr ' ' '_')" - new_fname="$(echo -e ${new_fname} | tr 'A-Z' 'a-z')" + new_fname="$(echo -e \"${fname}\" | tr ' ' '_')" + new_fname="$(echo -e \"${new_fname}\" | tr 'A-Z' 'a-z')" if [ $fname != $new_fname ] then - echo -e $fname" --> "$new_fname + echo -e "\"$fname\" --> $new_fname" git mv "$fname" $new_fname fi done From 4011a18ff90ea87bd4a988f168bc6614527bd153 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:17:46 -0400 Subject: [PATCH 252/433] remove second escpe quote --- .github/workflows/clang-format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 8c56fbed666..600968b3d0d 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -27,7 +27,7 @@ jobs: for fname in $(find . -type f -name '*.cpp' -o -name '*.h') do new_fname="$(echo -e \"${fname}\" | tr ' ' '_')" - new_fname="$(echo -e \"${new_fname}\" | tr 'A-Z' 'a-z')" + new_fname="$(echo -e ${new_fname} | tr 'A-Z' 'a-z')" if [ $fname != $new_fname ] then echo -e "\"$fname\" --> $new_fname" From b3242230e86118e4670db2b742c5d0ec699fbfc6 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:20:21 -0400 Subject: [PATCH 253/433] use single quote for first check --- .github/workflows/clang-format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 600968b3d0d..4984aa7cfb1 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -26,7 +26,7 @@ jobs: run: | for fname in $(find . -type f -name '*.cpp' -o -name '*.h') do - new_fname="$(echo -e \"${fname}\" | tr ' ' '_')" + new_fname="$(echo -e '${fname}' | tr ' ' '_')" new_fname="$(echo -e ${new_fname} | tr 'A-Z' 'a-z')" if [ $fname != $new_fname ] then From 097f0d23eb7ccb94ed8f0b83103a28b2f5e78d2b Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:24:00 -0400 Subject: [PATCH 254/433] use carets instead of quotes --- .github/workflows/clang-format.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 4984aa7cfb1..64e2c387265 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -26,11 +26,11 @@ jobs: run: | for fname in $(find . -type f -name '*.cpp' -o -name '*.h') do - new_fname="$(echo -e '${fname}' | tr ' ' '_')" - new_fname="$(echo -e ${new_fname} | tr 'A-Z' 'a-z')" + new_fname=`echo -e ${fname} | tr ' ' '_'` + new_fname=`echo -e ${new_fname} | tr 'A-Z' 'a-z'` if [ $fname != $new_fname ] then - echo -e "\"$fname\" --> $new_fname" + echo -e "$fname --> $new_fname" git mv "$fname" $new_fname fi done From 43b28808923a36b984347c1457208d4237d2dfae Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:25:38 -0400 Subject: [PATCH 255/433] put variables in brackets --- .github/workflows/clang-format.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 64e2c387265..0c5e1d82f01 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -28,10 +28,10 @@ jobs: do new_fname=`echo -e ${fname} | tr ' ' '_'` new_fname=`echo -e ${new_fname} | tr 'A-Z' 'a-z'` - if [ $fname != $new_fname ] + if [ ${fname} != ${new_fname} ] then - echo -e "$fname --> $new_fname" - git mv "$fname" $new_fname + echo -e "${fname} --> ${new_fname}" + git mv "${fname}" ${new_fname} fi done git commit -am "formatting filenames $GITHUB_SHA" || true From b9ed82475e80e528809ea85ffec3925865792876 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:29:50 -0400 Subject: [PATCH 256/433] remove -e from echo --- .github/workflows/clang-format.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 0c5e1d82f01..2e1bc9fe029 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -26,11 +26,11 @@ jobs: run: | for fname in $(find . -type f -name '*.cpp' -o -name '*.h') do - new_fname=`echo -e ${fname} | tr ' ' '_'` - new_fname=`echo -e ${new_fname} | tr 'A-Z' 'a-z'` + new_fname=`echo ${fname} | tr ' ' '_'` + new_fname=`echo ${new_fname} | tr 'A-Z' 'a-z'` if [ ${fname} != ${new_fname} ] then - echo -e "${fname} --> ${new_fname}" + echo "${fname} --> ${new_fname}" git mv "${fname}" ${new_fname} fi done From 2a674c3d9e136b6aea9b1aa305d4fde4543d563a Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:32:03 -0400 Subject: [PATCH 257/433] add debug echos --- .github/workflows/clang-format.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 2e1bc9fe029..8f7f4a7b2bf 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -26,11 +26,14 @@ jobs: run: | for fname in $(find . -type f -name '*.cpp' -o -name '*.h') do + echo "${fname}" new_fname=`echo ${fname} | tr ' ' '_'` + echo " ${new_fname}" new_fname=`echo ${new_fname} | tr 'A-Z' 'a-z'` + echo " ${new_fname}" if [ ${fname} != ${new_fname} ] then - echo "${fname} --> ${new_fname}" + echo " ${fname} --> ${new_fname}" git mv "${fname}" ${new_fname} fi done From 9844d887b0a7f6aba1736d30bb2aa8149cb178e2 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:37:32 -0400 Subject: [PATCH 258/433] try print0 flag --- .github/workflows/clang-format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 8f7f4a7b2bf..90c7ffc8237 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -24,7 +24,7 @@ jobs: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - name: Filename Formatter run: | - for fname in $(find . -type f -name '*.cpp' -o -name '*.h') + for fname in `find . -type f -name '*.cpp' -o -name '*.h' -print0` do echo "${fname}" new_fname=`echo ${fname} | tr ' ' '_'` From 1d24b96ad6debfb3db755dfa74903b4fa7f7761e Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:47:20 -0400 Subject: [PATCH 259/433] find command with while instead of for-loop --- .github/workflows/clang-format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 90c7ffc8237..b50b8717ea1 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -24,7 +24,7 @@ jobs: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - name: Filename Formatter run: | - for fname in `find . -type f -name '*.cpp' -o -name '*.h' -print0` + find . -type f -name '*.cpp' -o -name '*.h' -print0 | while read -d $'\0' fname do echo "${fname}" new_fname=`echo ${fname} | tr ' ' '_'` From 0e130658b570f9e5d09df2c8da8520b0c70128e0 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:52:01 -0400 Subject: [PATCH 260/433] find command using IFS instead --- .github/workflows/clang-format.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index b50b8717ea1..44260450aef 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -24,7 +24,8 @@ jobs: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - name: Filename Formatter run: | - find . -type f -name '*.cpp' -o -name '*.h' -print0 | while read -d $'\0' fname + IFS=$'\n' + for fname in `find . -type f -name '*.cpp' -o -name '*.h'` do echo "${fname}" new_fname=`echo ${fname} | tr ' ' '_'` From 65dbaf7c693988d9e1ce7821cc3d93363af8a353 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:55:36 -0400 Subject: [PATCH 261/433] :tada: IFS fix worked - escaped quotes for git mv --- .github/workflows/clang-format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 44260450aef..d2702bf3a7f 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -35,7 +35,7 @@ jobs: if [ ${fname} != ${new_fname} ] then echo " ${fname} --> ${new_fname}" - git mv "${fname}" ${new_fname} + git mv \"${fname}\" ${new_fname} fi done git commit -am "formatting filenames $GITHUB_SHA" || true From 9643f75e0f7968f1eec91f9a4d865b6c8dbd7371 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 19:04:14 -0400 Subject: [PATCH 262/433] protetc each word in git mv .. --- .github/workflows/clang-format.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index d2702bf3a7f..e6d8dee9ab7 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -32,10 +32,12 @@ jobs: echo " ${new_fname}" new_fname=`echo ${new_fname} | tr 'A-Z' 'a-z'` echo " ${new_fname}" + new_fname=`echo ${new_fname} | tr '-' '_'` + echo " ${new_fname}" if [ ${fname} != ${new_fname} ] then echo " ${fname} --> ${new_fname}" - git mv \"${fname}\" ${new_fname} + git "mv" "${fname}" ${new_fname} fi done git commit -am "formatting filenames $GITHUB_SHA" || true From 7b6932cd6ed490299b3b0a16d1d153e86c10e58f Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 19:08:43 -0400 Subject: [PATCH 263/433] filename exists in lower cases - renamed --- data_structure/{Queue Using Array.cpp => Queue Using Array2.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename data_structure/{Queue Using Array.cpp => Queue Using Array2.cpp} (100%) diff --git a/data_structure/Queue Using Array.cpp b/data_structure/Queue Using Array2.cpp similarity index 100% rename from data_structure/Queue Using Array.cpp rename to data_structure/Queue Using Array2.cpp From e7bc4e26192fbd948bb73e810f2ab7edc63c53c3 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 19:23:01 -0400 Subject: [PATCH 264/433] :tada: git push enabled --- .github/workflows/clang-format.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index e6d8dee9ab7..3fb7374e69f 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -53,5 +53,5 @@ jobs: line2: "IndentWidth: 4, TabWidth: 4, BreakBeforeBraces: Allman," line3: "AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: false," line4: "ColumnLimit: 80, AccessModifierOffset: -3 }" - # -name: Git Push - # run: git push + - name: Git Push + run: git push From fd394fd113463f0733aa6bfc7cab0b88dcb8b318 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 29 May 2020 23:23:29 +0000 Subject: [PATCH 265/433] updating DIRECTORY.md --- DIRECTORY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index 189d6041b88..d90326050d7 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -32,7 +32,7 @@ * [Linkedlist Implentation Usingarray](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/linkedList_implentation_usingArray.cpp) * [List Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/List%20Array.cpp) * [Morrisinorder](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/MorrisInorder.cpp) - * [Queue Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Queue%20Using%20Array.cpp) + * [Queue Using Array2](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Queue%20Using%20Array2.cpp) * [Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Queue%20Using%20Linked%20List.cpp) * Queue * [Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue/queue.cpp) From fed47f610ce64ecb4fa78219abd2262f47ec0484 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 19:24:24 -0400 Subject: [PATCH 266/433] git pull & then push --- .github/workflows/clang-format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 3fb7374e69f..a8d61e423f1 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -54,4 +54,4 @@ jobs: line3: "AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: false," line4: "ColumnLimit: 80, AccessModifierOffset: -3 }" - name: Git Push - run: git push + run: git pull && git push From edb3d51ec259e80e4da596a4aaae27505def43bc Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 29 May 2020 23:26:28 +0000 Subject: [PATCH 267/433] formatting filenames d7af6fdc8cb08578de6980d412e6e1caca1a1bcf --- data_structure/{AVLtree.cpp => avltree.cpp} | 0 data_structure/{Binary Search Tree.cpp => binary_search_tree.cpp} | 0 data_structure/{Binaryheap.cpp => binaryheap.cpp} | 0 ...using_Linked_List.cpp => circular_queue_using_linked_list.cpp} | 0 ...tion_usingArray.cpp => linkedlist_implentation_usingarray.cpp} | 0 data_structure/{List Array.cpp => list_array.cpp} | 0 data_structure/{MorrisInorder.cpp => morrisinorder.cpp} | 0 data_structure/{Queue Using Array2.cpp => queue_using_array2.cpp} | 0 .../{Queue Using Linked List.cpp => queue_using_linked_list.cpp} | 0 data_structure/{Stack Using Array.cpp => stack_using_array.cpp} | 0 .../{Stack Using Linked List.cpp => stack_using_linked_list.cpp} | 0 data_structure/{Tree.cpp => tree.cpp} | 0 dynamic_programming/{0-1 Knapsack.cpp => 0_1_knapsack.cpp} | 0 dynamic_programming/{Bellman-Ford.cpp => bellman_ford.cpp} | 0 dynamic_programming/{Catalan-Numbers.cpp => catalan_numbers.cpp} | 0 dynamic_programming/{Coin-Change.cpp => coin_change.cpp} | 0 dynamic_programming/{Cut Rod.cpp => cut_rod.cpp} | 0 dynamic_programming/{Edit Distance.cpp => edit_distance.cpp} | 0 .../{Egg-Dropping-Puzzle.cpp => egg_dropping_puzzle.cpp} | 0 .../{Fibonacci_Bottom_Up.cpp => fibonacci_bottom_up.cpp} | 0 .../{Fibonacci_Top_Down.cpp => fibonacci_top_down.cpp} | 0 dynamic_programming/{Floyd-Warshall.cpp => floyd_warshall.cpp} | 0 ...gest Common Subsequence.cpp => longest_common_subsequence.cpp} | 0 ...reasing Subsequence.cpp => longest_increasing_subsequence.cpp} | 0 ...nce (nlogn).cpp => longest_increasing_subsequence_(nlogn).cpp} | 0 ...x-Chain-Multiplication.cpp => matrix_chain_multiplication.cpp} | 0 graph/{BFS.cpp => bfs.cpp} | 0 graph/{DFS.cpp => dfs.cpp} | 0 graph/{Dijkstra.cpp => dijkstra.cpp} | 0 graph/{Kruskal.cpp => kruskal.cpp} | 0 graph/{Topological-Sort.cpp => topological_sort.cpp} | 0 greedy_algorithms/{Dijkstra.cpp => dijkstra.cpp} | 0 greedy_algorithms/{Knapsack.cpp => knapsack.cpp} | 0 ...nimum Spanning Tree.cpp => kruskals_minimum_spanning_tree.cpp} | 0 ... Minimum Spanning Tree.cpp => prims_minimum_spanning_tree.cpp} | 0 hashing/{Chaining.cpp => chaining.cpp} | 0 .../{Array Left Rotation.cpp => array_left_rotation.cpp} | 0 .../{Array Right Rotation.cpp => array_right_rotation.cpp} | 0 .../{Circular Linked List.cpp => circular_linked_list.cpp} | 0 ...cular Queue Using Array.cpp => circular_queue_using_array.cpp} | 0 ...{Intersection_of_2_arrays.cpp => intersection_of_2_arrays.cpp} | 0 ...sing Recusion.cpp => reverse_a_linked_list_using_recusion.cpp} | 0 .../{selectionSortLinkedList.cpp => selectionsortlinkedlist.cpp} | 0 .../{Union_of_2_arrays.cpp => union_of_2_arrays.cpp} | 0 range_queries/{FenwickTree.cpp => fenwicktree.cpp} | 0 range_queries/{MO.cpp => mo.cpp} | 0 range_queries/{segTree.cpp => segtree.cpp} | 0 sorting/{Counting_Sort.cpp => counting_sort.cpp} | 0 48 files changed, 0 insertions(+), 0 deletions(-) rename data_structure/{AVLtree.cpp => avltree.cpp} (100%) rename data_structure/{Binary Search Tree.cpp => binary_search_tree.cpp} (100%) rename data_structure/{Binaryheap.cpp => binaryheap.cpp} (100%) rename data_structure/{circular_Queue_using_Linked_List.cpp => circular_queue_using_linked_list.cpp} (100%) rename data_structure/{linkedList_implentation_usingArray.cpp => linkedlist_implentation_usingarray.cpp} (100%) rename data_structure/{List Array.cpp => list_array.cpp} (100%) rename data_structure/{MorrisInorder.cpp => morrisinorder.cpp} (100%) rename data_structure/{Queue Using Array2.cpp => queue_using_array2.cpp} (100%) rename data_structure/{Queue Using Linked List.cpp => queue_using_linked_list.cpp} (100%) rename data_structure/{Stack Using Array.cpp => stack_using_array.cpp} (100%) rename data_structure/{Stack Using Linked List.cpp => stack_using_linked_list.cpp} (100%) rename data_structure/{Tree.cpp => tree.cpp} (100%) rename dynamic_programming/{0-1 Knapsack.cpp => 0_1_knapsack.cpp} (100%) rename dynamic_programming/{Bellman-Ford.cpp => bellman_ford.cpp} (100%) rename dynamic_programming/{Catalan-Numbers.cpp => catalan_numbers.cpp} (100%) rename dynamic_programming/{Coin-Change.cpp => coin_change.cpp} (100%) rename dynamic_programming/{Cut Rod.cpp => cut_rod.cpp} (100%) rename dynamic_programming/{Edit Distance.cpp => edit_distance.cpp} (100%) rename dynamic_programming/{Egg-Dropping-Puzzle.cpp => egg_dropping_puzzle.cpp} (100%) rename dynamic_programming/{Fibonacci_Bottom_Up.cpp => fibonacci_bottom_up.cpp} (100%) rename dynamic_programming/{Fibonacci_Top_Down.cpp => fibonacci_top_down.cpp} (100%) rename dynamic_programming/{Floyd-Warshall.cpp => floyd_warshall.cpp} (100%) rename dynamic_programming/{Longest Common Subsequence.cpp => longest_common_subsequence.cpp} (100%) rename dynamic_programming/{Longest Increasing Subsequence.cpp => longest_increasing_subsequence.cpp} (100%) rename dynamic_programming/{Longest Increasing Subsequence (nlogn).cpp => longest_increasing_subsequence_(nlogn).cpp} (100%) rename dynamic_programming/{Matrix-Chain-Multiplication.cpp => matrix_chain_multiplication.cpp} (100%) rename graph/{BFS.cpp => bfs.cpp} (100%) rename graph/{DFS.cpp => dfs.cpp} (100%) rename graph/{Dijkstra.cpp => dijkstra.cpp} (100%) rename graph/{Kruskal.cpp => kruskal.cpp} (100%) rename graph/{Topological-Sort.cpp => topological_sort.cpp} (100%) rename greedy_algorithms/{Dijkstra.cpp => dijkstra.cpp} (100%) rename greedy_algorithms/{Knapsack.cpp => knapsack.cpp} (100%) rename greedy_algorithms/{Kruskals Minimum Spanning Tree.cpp => kruskals_minimum_spanning_tree.cpp} (100%) rename greedy_algorithms/{Prims Minimum Spanning Tree.cpp => prims_minimum_spanning_tree.cpp} (100%) rename hashing/{Chaining.cpp => chaining.cpp} (100%) rename operations_on_datastructures/{Array Left Rotation.cpp => array_left_rotation.cpp} (100%) rename operations_on_datastructures/{Array Right Rotation.cpp => array_right_rotation.cpp} (100%) rename operations_on_datastructures/{Circular Linked List.cpp => circular_linked_list.cpp} (100%) rename operations_on_datastructures/{Circular Queue Using Array.cpp => circular_queue_using_array.cpp} (100%) rename operations_on_datastructures/{Intersection_of_2_arrays.cpp => intersection_of_2_arrays.cpp} (100%) rename operations_on_datastructures/{Reverse a Linked List using Recusion.cpp => reverse_a_linked_list_using_recusion.cpp} (100%) rename operations_on_datastructures/{selectionSortLinkedList.cpp => selectionsortlinkedlist.cpp} (100%) rename operations_on_datastructures/{Union_of_2_arrays.cpp => union_of_2_arrays.cpp} (100%) rename range_queries/{FenwickTree.cpp => fenwicktree.cpp} (100%) rename range_queries/{MO.cpp => mo.cpp} (100%) rename range_queries/{segTree.cpp => segtree.cpp} (100%) rename sorting/{Counting_Sort.cpp => counting_sort.cpp} (100%) diff --git a/data_structure/AVLtree.cpp b/data_structure/avltree.cpp similarity index 100% rename from data_structure/AVLtree.cpp rename to data_structure/avltree.cpp diff --git a/data_structure/Binary Search Tree.cpp b/data_structure/binary_search_tree.cpp similarity index 100% rename from data_structure/Binary Search Tree.cpp rename to data_structure/binary_search_tree.cpp diff --git a/data_structure/Binaryheap.cpp b/data_structure/binaryheap.cpp similarity index 100% rename from data_structure/Binaryheap.cpp rename to data_structure/binaryheap.cpp diff --git a/data_structure/circular_Queue_using_Linked_List.cpp b/data_structure/circular_queue_using_linked_list.cpp similarity index 100% rename from data_structure/circular_Queue_using_Linked_List.cpp rename to data_structure/circular_queue_using_linked_list.cpp diff --git a/data_structure/linkedList_implentation_usingArray.cpp b/data_structure/linkedlist_implentation_usingarray.cpp similarity index 100% rename from data_structure/linkedList_implentation_usingArray.cpp rename to data_structure/linkedlist_implentation_usingarray.cpp diff --git a/data_structure/List Array.cpp b/data_structure/list_array.cpp similarity index 100% rename from data_structure/List Array.cpp rename to data_structure/list_array.cpp diff --git a/data_structure/MorrisInorder.cpp b/data_structure/morrisinorder.cpp similarity index 100% rename from data_structure/MorrisInorder.cpp rename to data_structure/morrisinorder.cpp diff --git a/data_structure/Queue Using Array2.cpp b/data_structure/queue_using_array2.cpp similarity index 100% rename from data_structure/Queue Using Array2.cpp rename to data_structure/queue_using_array2.cpp diff --git a/data_structure/Queue Using Linked List.cpp b/data_structure/queue_using_linked_list.cpp similarity index 100% rename from data_structure/Queue Using Linked List.cpp rename to data_structure/queue_using_linked_list.cpp diff --git a/data_structure/Stack Using Array.cpp b/data_structure/stack_using_array.cpp similarity index 100% rename from data_structure/Stack Using Array.cpp rename to data_structure/stack_using_array.cpp diff --git a/data_structure/Stack Using Linked List.cpp b/data_structure/stack_using_linked_list.cpp similarity index 100% rename from data_structure/Stack Using Linked List.cpp rename to data_structure/stack_using_linked_list.cpp diff --git a/data_structure/Tree.cpp b/data_structure/tree.cpp similarity index 100% rename from data_structure/Tree.cpp rename to data_structure/tree.cpp diff --git a/dynamic_programming/0-1 Knapsack.cpp b/dynamic_programming/0_1_knapsack.cpp similarity index 100% rename from dynamic_programming/0-1 Knapsack.cpp rename to dynamic_programming/0_1_knapsack.cpp diff --git a/dynamic_programming/Bellman-Ford.cpp b/dynamic_programming/bellman_ford.cpp similarity index 100% rename from dynamic_programming/Bellman-Ford.cpp rename to dynamic_programming/bellman_ford.cpp diff --git a/dynamic_programming/Catalan-Numbers.cpp b/dynamic_programming/catalan_numbers.cpp similarity index 100% rename from dynamic_programming/Catalan-Numbers.cpp rename to dynamic_programming/catalan_numbers.cpp diff --git a/dynamic_programming/Coin-Change.cpp b/dynamic_programming/coin_change.cpp similarity index 100% rename from dynamic_programming/Coin-Change.cpp rename to dynamic_programming/coin_change.cpp diff --git a/dynamic_programming/Cut Rod.cpp b/dynamic_programming/cut_rod.cpp similarity index 100% rename from dynamic_programming/Cut Rod.cpp rename to dynamic_programming/cut_rod.cpp diff --git a/dynamic_programming/Edit Distance.cpp b/dynamic_programming/edit_distance.cpp similarity index 100% rename from dynamic_programming/Edit Distance.cpp rename to dynamic_programming/edit_distance.cpp diff --git a/dynamic_programming/Egg-Dropping-Puzzle.cpp b/dynamic_programming/egg_dropping_puzzle.cpp similarity index 100% rename from dynamic_programming/Egg-Dropping-Puzzle.cpp rename to dynamic_programming/egg_dropping_puzzle.cpp diff --git a/dynamic_programming/Fibonacci_Bottom_Up.cpp b/dynamic_programming/fibonacci_bottom_up.cpp similarity index 100% rename from dynamic_programming/Fibonacci_Bottom_Up.cpp rename to dynamic_programming/fibonacci_bottom_up.cpp diff --git a/dynamic_programming/Fibonacci_Top_Down.cpp b/dynamic_programming/fibonacci_top_down.cpp similarity index 100% rename from dynamic_programming/Fibonacci_Top_Down.cpp rename to dynamic_programming/fibonacci_top_down.cpp diff --git a/dynamic_programming/Floyd-Warshall.cpp b/dynamic_programming/floyd_warshall.cpp similarity index 100% rename from dynamic_programming/Floyd-Warshall.cpp rename to dynamic_programming/floyd_warshall.cpp diff --git a/dynamic_programming/Longest Common Subsequence.cpp b/dynamic_programming/longest_common_subsequence.cpp similarity index 100% rename from dynamic_programming/Longest Common Subsequence.cpp rename to dynamic_programming/longest_common_subsequence.cpp diff --git a/dynamic_programming/Longest Increasing Subsequence.cpp b/dynamic_programming/longest_increasing_subsequence.cpp similarity index 100% rename from dynamic_programming/Longest Increasing Subsequence.cpp rename to dynamic_programming/longest_increasing_subsequence.cpp diff --git a/dynamic_programming/Longest Increasing Subsequence (nlogn).cpp b/dynamic_programming/longest_increasing_subsequence_(nlogn).cpp similarity index 100% rename from dynamic_programming/Longest Increasing Subsequence (nlogn).cpp rename to dynamic_programming/longest_increasing_subsequence_(nlogn).cpp diff --git a/dynamic_programming/Matrix-Chain-Multiplication.cpp b/dynamic_programming/matrix_chain_multiplication.cpp similarity index 100% rename from dynamic_programming/Matrix-Chain-Multiplication.cpp rename to dynamic_programming/matrix_chain_multiplication.cpp diff --git a/graph/BFS.cpp b/graph/bfs.cpp similarity index 100% rename from graph/BFS.cpp rename to graph/bfs.cpp diff --git a/graph/DFS.cpp b/graph/dfs.cpp similarity index 100% rename from graph/DFS.cpp rename to graph/dfs.cpp diff --git a/graph/Dijkstra.cpp b/graph/dijkstra.cpp similarity index 100% rename from graph/Dijkstra.cpp rename to graph/dijkstra.cpp diff --git a/graph/Kruskal.cpp b/graph/kruskal.cpp similarity index 100% rename from graph/Kruskal.cpp rename to graph/kruskal.cpp diff --git a/graph/Topological-Sort.cpp b/graph/topological_sort.cpp similarity index 100% rename from graph/Topological-Sort.cpp rename to graph/topological_sort.cpp diff --git a/greedy_algorithms/Dijkstra.cpp b/greedy_algorithms/dijkstra.cpp similarity index 100% rename from greedy_algorithms/Dijkstra.cpp rename to greedy_algorithms/dijkstra.cpp diff --git a/greedy_algorithms/Knapsack.cpp b/greedy_algorithms/knapsack.cpp similarity index 100% rename from greedy_algorithms/Knapsack.cpp rename to greedy_algorithms/knapsack.cpp diff --git a/greedy_algorithms/Kruskals Minimum Spanning Tree.cpp b/greedy_algorithms/kruskals_minimum_spanning_tree.cpp similarity index 100% rename from greedy_algorithms/Kruskals Minimum Spanning Tree.cpp rename to greedy_algorithms/kruskals_minimum_spanning_tree.cpp diff --git a/greedy_algorithms/Prims Minimum Spanning Tree.cpp b/greedy_algorithms/prims_minimum_spanning_tree.cpp similarity index 100% rename from greedy_algorithms/Prims Minimum Spanning Tree.cpp rename to greedy_algorithms/prims_minimum_spanning_tree.cpp diff --git a/hashing/Chaining.cpp b/hashing/chaining.cpp similarity index 100% rename from hashing/Chaining.cpp rename to hashing/chaining.cpp diff --git a/operations_on_datastructures/Array Left Rotation.cpp b/operations_on_datastructures/array_left_rotation.cpp similarity index 100% rename from operations_on_datastructures/Array Left Rotation.cpp rename to operations_on_datastructures/array_left_rotation.cpp diff --git a/operations_on_datastructures/Array Right Rotation.cpp b/operations_on_datastructures/array_right_rotation.cpp similarity index 100% rename from operations_on_datastructures/Array Right Rotation.cpp rename to operations_on_datastructures/array_right_rotation.cpp diff --git a/operations_on_datastructures/Circular Linked List.cpp b/operations_on_datastructures/circular_linked_list.cpp similarity index 100% rename from operations_on_datastructures/Circular Linked List.cpp rename to operations_on_datastructures/circular_linked_list.cpp diff --git a/operations_on_datastructures/Circular Queue Using Array.cpp b/operations_on_datastructures/circular_queue_using_array.cpp similarity index 100% rename from operations_on_datastructures/Circular Queue Using Array.cpp rename to operations_on_datastructures/circular_queue_using_array.cpp diff --git a/operations_on_datastructures/Intersection_of_2_arrays.cpp b/operations_on_datastructures/intersection_of_2_arrays.cpp similarity index 100% rename from operations_on_datastructures/Intersection_of_2_arrays.cpp rename to operations_on_datastructures/intersection_of_2_arrays.cpp diff --git a/operations_on_datastructures/Reverse a Linked List using Recusion.cpp b/operations_on_datastructures/reverse_a_linked_list_using_recusion.cpp similarity index 100% rename from operations_on_datastructures/Reverse a Linked List using Recusion.cpp rename to operations_on_datastructures/reverse_a_linked_list_using_recusion.cpp diff --git a/operations_on_datastructures/selectionSortLinkedList.cpp b/operations_on_datastructures/selectionsortlinkedlist.cpp similarity index 100% rename from operations_on_datastructures/selectionSortLinkedList.cpp rename to operations_on_datastructures/selectionsortlinkedlist.cpp diff --git a/operations_on_datastructures/Union_of_2_arrays.cpp b/operations_on_datastructures/union_of_2_arrays.cpp similarity index 100% rename from operations_on_datastructures/Union_of_2_arrays.cpp rename to operations_on_datastructures/union_of_2_arrays.cpp diff --git a/range_queries/FenwickTree.cpp b/range_queries/fenwicktree.cpp similarity index 100% rename from range_queries/FenwickTree.cpp rename to range_queries/fenwicktree.cpp diff --git a/range_queries/MO.cpp b/range_queries/mo.cpp similarity index 100% rename from range_queries/MO.cpp rename to range_queries/mo.cpp diff --git a/range_queries/segTree.cpp b/range_queries/segtree.cpp similarity index 100% rename from range_queries/segTree.cpp rename to range_queries/segtree.cpp diff --git a/sorting/Counting_Sort.cpp b/sorting/counting_sort.cpp similarity index 100% rename from sorting/Counting_Sort.cpp rename to sorting/counting_sort.cpp From 7ad1f171c139e206761c17d50dd7093a6875ee5a Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 29 May 2020 23:26:30 +0000 Subject: [PATCH 268/433] formatting source-code for d7af6fdc8cb08578de6980d412e6e1caca1a1bcf --- backtracking/graph_coloring.cpp | 8 +- backtracking/knight_tour.cpp | 69 ++-- backtracking/minimax.cpp | 8 +- backtracking/n_queens.cpp | 12 +- .../n_queens_all_solution_optimised.cpp | 68 ++-- backtracking/nqueen_print_all_solutions.cpp | 36 +- backtracking/rat_maze.cpp | 108 +++--- backtracking/sudoku_solve.cpp | 41 +- .../bisection_method.cpp | 29 +- .../false_position.cpp | 25 +- .../gaussian_elimination.cpp | 33 +- .../newton_raphson_method.cpp | 12 +- .../ordinary_least_squares_regressor.cpp | 112 ++++-- .../successive_approximation.cpp | 9 +- data_structure/avltree.cpp | 217 ++++++----- data_structure/binary_search_tree.cpp | 336 ++++++++--------- data_structure/binaryheap.cpp | 10 +- .../circular_queue_using_linked_list.cpp | 2 +- data_structure/cll/cll.cpp | 70 ++-- data_structure/cll/cll.h | 50 +-- data_structure/cll/main_cll.cpp | 72 ++-- data_structure/disjoint_set.cpp | 104 ++--- data_structure/doubly_linked_list.cpp | 264 +++++++------ data_structure/linked_list.cpp | 245 ++++++------ .../linkedlist_implentation_usingarray.cpp | 26 +- data_structure/list_array.cpp | 354 +++++++++--------- data_structure/morrisinorder.cpp | 170 ++++----- data_structure/queue/queue.cpp | 28 +- data_structure/queue/queue.h | 27 +- data_structure/queue/test_queue.cpp | 28 +- data_structure/queue_using_array.cpp | 72 ++-- data_structure/queue_using_array2.cpp | 101 +++-- data_structure/queue_using_linked_list.cpp | 4 +- data_structure/queue_using_linkedlist.cpp | 129 +++---- data_structure/stack_using_array.cpp | 110 +++--- data_structure/stack_using_linked_list.cpp | 95 +++-- data_structure/stk/main.cpp | 26 +- data_structure/stk/stack.cpp | 27 +- data_structure/stk/stack.h | 29 +- data_structure/stk/test_stack.cpp | 34 +- data_structure/tree.cpp | 20 +- data_structure/trie_tree.cpp | 91 +++-- dynamic_programming/0_1_knapsack.cpp | 75 ++-- dynamic_programming/armstrong_number.cpp | 32 +- dynamic_programming/bellman_ford.cpp | 211 +++++------ dynamic_programming/catalan_numbers.cpp | 4 +- dynamic_programming/coin_change.cpp | 74 ++-- dynamic_programming/cut_rod.cpp | 9 +- dynamic_programming/edit_distance.cpp | 34 +- dynamic_programming/egg_dropping_puzzle.cpp | 10 +- dynamic_programming/fibonacci_bottom_up.cpp | 32 +- dynamic_programming/fibonacci_top_down.cpp | 34 +- dynamic_programming/floyd_warshall.cpp | 168 ++++----- dynamic_programming/kadane.cpp | 17 +- dynamic_programming/longest_common_string.cpp | 74 ++-- .../longest_common_subsequence.cpp | 11 +- .../longest_increasing_subsequence.cpp | 62 +-- ...longest_increasing_subsequence_(nlogn).cpp | 22 +- .../matrix_chain_multiplication.cpp | 73 ++-- .../searching_of_element_in_dynamic_array.cpp | 80 ++-- dynamic_programming/tree_height.cpp | 41 +- graph/bfs.cpp | 104 ++--- .../bridge_finding_with_tarjan_algorithm.cpp | 54 +-- graph/connected_components.cpp | 71 ++-- graph/connected_components_with_dsu.cpp | 29 +- graph/dfs.cpp | 34 +- graph/dijkstra.cpp | 17 +- graph/kosaraju.cpp | 147 ++++---- graph/kruskal.cpp | 178 +++++---- graph/lca.cpp | 44 +-- ...th_ford_fulkerson_and_edmond_karp_algo.cpp | 94 +++-- graph/prim.cpp | 33 +- graph/topological_sort.cpp | 71 ++-- graph/topological_sort_by_kahns_algo.cpp | 50 ++- greedy_algorithms/dijkstra.cpp | 34 +- greedy_algorithms/huffman.cpp | 213 ++++++----- greedy_algorithms/knapsack.cpp | 130 ++++--- .../kruskals_minimum_spanning_tree.cpp | 45 ++- .../prims_minimum_spanning_tree.cpp | 94 +++-- hashing/chaining.cpp | 220 ++++++----- hashing/double_hash_hash_table.cpp | 144 ++++--- hashing/linear_probing_hash_table.cpp | 130 ++++--- hashing/quadratic_probing_hash_table.cpp | 150 +++++--- math/binary_exponent.cpp | 36 +- math/double_factorial.cpp | 18 +- math/eulers_totient_function.cpp | 25 +- math/extended_euclid_algorithm.cpp | 28 +- math/factorial.cpp | 6 +- math/fast_power.cpp | 27 +- math/fibonacci.cpp | 6 +- math/fibonacci_fast.cpp | 9 +- math/fibonacci_large.cpp | 16 +- math/gcd_iterative_euclidean.cpp | 29 +- math/gcd_of_n_numbers.cpp | 9 +- math/gcd_recursive_euclidean.cpp | 19 +- math/large_factorial.cpp | 34 +- math/large_number.h | 94 +++-- .../modular_inverse_fermat_little_theorem.cpp | 35 +- math/number_of_positive_divisors.cpp | 31 +- math/power_for_huge_numbers.cpp | 21 +- math/prime_factorization.cpp | 36 +- math/prime_numbers.cpp | 12 +- math/primes_up_to_billion.cpp | 12 +- math/sieve_of_eratosthenes.cpp | 30 +- math/sqrt_double.cpp | 22 +- math/string_fibonacci.cpp | 34 +- .../array_left_rotation.cpp | 68 ++-- .../array_right_rotation.cpp | 3 +- .../circular_linked_list.cpp | 168 ++++----- .../circular_queue_using_array.cpp | 97 +++-- .../get_size_of_linked_list.cpp | 15 +- .../intersection_of_2_arrays.cpp | 48 ++- .../reverse_a_linked_list_using_recusion.cpp | 98 ++--- .../selectionsortlinkedlist.cpp | 95 +++-- .../union_of_2_arrays.cpp | 52 ++- others/buzz_number.cpp | 6 +- others/decimal_to_binary.cpp | 15 +- others/decimal_to_hexadecimal.cpp | 6 +- others/decimal_to_roman_numeral.cpp | 78 ++-- others/fast_interger_input.cpp | 12 +- others/happy_number.cpp | 14 +- others/matrix_exponentiation.cpp | 49 ++- others/palindrome_of_number.cpp | 3 +- others/paranthesis_matching.cpp | 46 ++- others/pascal_triangle.cpp | 27 +- others/primality_test.cpp | 9 +- others/smallest_circle.cpp | 51 ++- others/sparse_matrix.cpp | 15 +- others/spiral_print.cpp | 36 +- others/stairs_pattern.cpp | 15 +- others/tower_of_hanoi.cpp | 34 +- others/vector_important_functions.cpp | 3 +- probability/addition_rule.cpp | 9 +- probability/bayes_theorem.cpp | 9 +- probability/binomial_dist.cpp | 24 +- probability/poisson_dist.cpp | 24 +- range_queries/bit.cpp | 37 +- range_queries/fenwicktree.cpp | 38 +- range_queries/mo.cpp | 104 +++-- range_queries/segtree.cpp | 156 ++++---- search/binary_search.cpp | 12 +- search/exponential_search.cpp | 18 +- search/hash_search.cpp | 34 +- search/interpolation_search.cpp | 9 +- search/interpolation_search2.cpp | 9 +- search/jump_search.cpp | 12 +- search/linear_search.cpp | 22 +- search/median_search.cpp | 36 +- search/ternary_search.cpp | 35 +- search/text_search.cpp | 20 +- sorting/bead_sort.cpp | 21 +- sorting/bitonic_sort.cpp | 21 +- sorting/bubble_sort.cpp | 25 +- sorting/bucket_sort.cpp | 9 +- sorting/cocktail_selection_sort.cpp | 64 +++- sorting/comb_sort.cpp | 18 +- sorting/counting_sort.cpp | 75 ++-- sorting/counting_sort_string.cpp | 13 +- sorting/heap_sort.cpp | 27 +- sorting/insertion_sort.cpp | 15 +- sorting/library_sort.cpp | 40 +- sorting/merge_sort.cpp | 34 +- sorting/non_recursive_merge_sort.cpp | 24 +- sorting/numeric_string_sort.cpp | 24 +- sorting/odd_even_sort.cpp | 77 ++-- sorting/quick_sort.cpp | 24 +- sorting/radix_sort.cpp | 39 +- sorting/selection_sort.cpp | 58 +-- sorting/shell_sort.cpp | 25 +- sorting/shell_sort2.cpp | 169 +++++---- sorting/slow_sort.cpp | 18 +- sorting/swap_sort.cpp | 21 +- sorting/tim_sort.cpp | 43 ++- strings/brute_force_string_searching.cpp | 18 +- strings/knuth_morris_pratt.cpp | 35 +- strings/rabin_karp.cpp | 37 +- 176 files changed, 5374 insertions(+), 4320 deletions(-) diff --git a/backtracking/graph_coloring.cpp b/backtracking/graph_coloring.cpp index cadc6d5ec3d..5d0049902ca 100644 --- a/backtracking/graph_coloring.cpp +++ b/backtracking/graph_coloring.cpp @@ -48,8 +48,7 @@ void graphColoring(bool graph[V][V], int m, int color[], int v) void printSolution(int color[]) { printf(" Following are the assigned colors \n"); - for (int i = 0; i < V; i++) - printf(" %d ", color[i]); + for (int i = 0; i < V; i++) printf(" %d ", color[i]); printf("\n"); } @@ -69,12 +68,11 @@ int main() {1, 1, 0, 1}, {1, 0, 1, 0}, }; - int m = 3; // Number of colors + int m = 3; // Number of colors int color[V]; - for (int i = 0; i < V; i++) - color[i] = 0; + for (int i = 0; i < V; i++) color[i] = 0; graphColoring(graph, m, color, 0); return 0; diff --git a/backtracking/knight_tour.cpp b/backtracking/knight_tour.cpp index fbb8a6f963b..72b900376e0 100644 --- a/backtracking/knight_tour.cpp +++ b/backtracking/knight_tour.cpp @@ -1,68 +1,65 @@ #include -# define n 8 +#define n 8 /** A knight's tour is a sequence of moves of a knight on a chessboard -such that the knight visits every square only once. If the knight -ends on a square that is one knight's move from the beginning -square (so that it could tour the board again immediately, following +such that the knight visits every square only once. If the knight +ends on a square that is one knight's move from the beginning +square (so that it could tour the board again immediately, following the same path), the tour is closed; otherwise, it is open. **/ using namespace std; -bool issafe(int x,int y,int sol[n][n]) +bool issafe(int x, int y, int sol[n][n]) { - return (x=0 && y=0 && sol[x][y]==-1); - + return (x < n && x >= 0 && y < n && y >= 0 && sol[x][y] == -1); } -bool solve(int x,int y, int mov, int sol[n][n], int xmov[n], int ymov[n]) +bool solve(int x, int y, int mov, int sol[n][n], int xmov[n], int ymov[n]) { - int k,xnext,ynext; + int k, xnext, ynext; - if(mov == n*n) + if (mov == n * n) return true; - for(k=0;k<8;k++) + for (k = 0; k < 8; k++) { - xnext=x+xmov[k]; - ynext=y+ymov[k]; + xnext = x + xmov[k]; + ynext = y + ymov[k]; - if(issafe(xnext,ynext,sol)) - { - sol[xnext][ynext]=mov; + if (issafe(xnext, ynext, sol)) + { + sol[xnext][ynext] = mov; - if(solve(xnext,ynext,mov+1,sol,xmov,ymov)==true) - return true; - else - sol[xnext][ynext]=-1; - } + if (solve(xnext, ynext, mov + 1, sol, xmov, ymov) == true) + return true; + else + sol[xnext][ynext] = -1; + } } return false; } int main() { - //initialize(); + // initialize(); int sol[n][n]; - int i,j; - for(i=0;i scores, - int height) { + int height) +{ if (depth == height) return scores[node_index]; @@ -19,8 +20,9 @@ int minimax(int depth, int node_index, bool is_max, vector scores, return is_max ? max(v1, v2) : min(v1, v2); } -int main() { - vector scores = { 90, 23, 6, 33, 21, 65, 123, 34423 }; +int main() +{ + vector scores = {90, 23, 6, 33, 21, 65, 123, 34423}; int height = log2(scores.size()); cout << "Optimal value: " << minimax(0, 0, true, scores, height) << endl; diff --git a/backtracking/n_queens.cpp b/backtracking/n_queens.cpp index 472aaa2fe1c..45d6f436cb5 100644 --- a/backtracking/n_queens.cpp +++ b/backtracking/n_queens.cpp @@ -7,8 +7,7 @@ void printSolution(int board[N][N]) cout << "\n"; for (int i = 0; i < N; i++) { - for (int j = 0; j < N; j++) - cout << "" << board[i][j]; + for (int j = 0; j < N; j++) cout << "" << board[i][j]; cout << "\n"; } } @@ -37,7 +36,6 @@ bool isSafe(int board[N][N], int row, int col) void solveNQ(int board[N][N], int col) { - if (col >= N) { printSolution(board); @@ -59,18 +57,14 @@ void solveNQ(int board[N][N], int col) /* recur to place rest of the queens */ solveNQ(board, col + 1); - board[i][col] = 0; // BACKTRACK + board[i][col] = 0; // BACKTRACK } } } int main() { - - int board[N][N] = {{0, 0, 0, 0}, - {0, 0, 0, 0}, - {0, 0, 0, 0}, - {0, 0, 0, 0}}; + int board[N][N] = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}; solveNQ(board, 0); return 0; diff --git a/backtracking/n_queens_all_solution_optimised.cpp b/backtracking/n_queens_all_solution_optimised.cpp index 1db730f636b..f27b3468bcb 100644 --- a/backtracking/n_queens_all_solution_optimised.cpp +++ b/backtracking/n_queens_all_solution_optimised.cpp @@ -1,50 +1,60 @@ #include #define n 4 -#define inc_loop(var, start, stop) for (int var=start; var <= stop; var++) -#define dec_loop(var, start, stop) for (int var=start; var >= stop; var--) -void PrintSol(int Board[n][n]) { - inc_loop(i, 0, n-1) { - inc_loop(j, 0, n-1) - std::cout << Board[i][j] << " "; +#define inc_loop(var, start, stop) for (int var = start; var <= stop; var++) +#define dec_loop(var, start, stop) for (int var = start; var >= stop; var--) +void PrintSol(int Board[n][n]) +{ + inc_loop(i, 0, n - 1) + { + inc_loop(j, 0, n - 1) std::cout << Board[i][j] << " "; std::cout << std::endl; } std::cout << std::endl; - if (n%2 == 0 || (n%2 == 1 && Board[n/2+1][0] != 1)) { - inc_loop(i, 0, n-1) { - dec_loop(j, n-1, 0) - std::cout << Board[i][j] << " "; + if (n % 2 == 0 || (n % 2 == 1 && Board[n / 2 + 1][0] != 1)) + { + inc_loop(i, 0, n - 1) + { + dec_loop(j, n - 1, 0) std::cout << Board[i][j] << " "; std::cout << std::endl; } std::cout << std::endl; } } -bool CanIMove(int Board[n][n], int row, int col) { +bool CanIMove(int Board[n][n], int row, int col) +{ /// check in the row - inc_loop(i, 0, col-1) { + inc_loop(i, 0, col - 1) + { if (Board[row][i] == 1) return false; } /// check the first diagonal - for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) { + for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) + { if (Board[i][j] == 1) return false; } /// check the second diagonal - for (int i = row, j = col; i <= n - 1 && j >= 0; i++, j--) { + for (int i = row, j = col; i <= n - 1 && j >= 0; i++, j--) + { if (Board[i][j] == 1) return false; } return true; } -void NQueenSol(int Board[n][n], int col) { - if (col >= n) { +void NQueenSol(int Board[n][n], int col) +{ + if (col >= n) + { PrintSol(Board); return; } - inc_loop(i, 0, n-1) { - if (CanIMove(Board, i, col)) { + inc_loop(i, 0, n - 1) + { + if (CanIMove(Board, i, col)) + { Board[i][col] = 1; NQueenSol(Board, col + 1); Board[i][col] = 0; @@ -52,19 +62,27 @@ void NQueenSol(int Board[n][n], int col) { } } -int main() { +int main() +{ int Board[n][n] = {0}; - if (n%2 == 0) { - inc_loop(i, 0, n/2-1) { - if (CanIMove(Board, i, 0)) { + if (n % 2 == 0) + { + inc_loop(i, 0, n / 2 - 1) + { + if (CanIMove(Board, i, 0)) + { Board[i][0] = 1; NQueenSol(Board, 1); Board[i][0] = 0; } } - } else { - inc_loop(i, 0, n/2) { - if (CanIMove(Board, i, 0)) { + } + else + { + inc_loop(i, 0, n / 2) + { + if (CanIMove(Board, i, 0)) + { Board[i][0] = 1; NQueenSol(Board, 1); Board[i][0] = 0; diff --git a/backtracking/nqueen_print_all_solutions.cpp b/backtracking/nqueen_print_all_solutions.cpp index e6736da1e74..d3d50998dfe 100644 --- a/backtracking/nqueen_print_all_solutions.cpp +++ b/backtracking/nqueen_print_all_solutions.cpp @@ -1,9 +1,12 @@ #include #define n 4 -void PrintSol(int Board[n][n]) { - for (int i = 0; i < n; i++) { - for (int j = 0; j < n; j++) { +void PrintSol(int Board[n][n]) +{ + for (int i = 0; i < n; i++) + { + for (int j = 0; j < n; j++) + { std::cout << Board[i][j] << " "; } std::cout << std::endl; @@ -11,32 +14,40 @@ void PrintSol(int Board[n][n]) { std::cout << std::endl; } -bool CanIMove(int Board[n][n], int row, int col) { +bool CanIMove(int Board[n][n], int row, int col) +{ /// check in the row - for (int i = 0; i < col; i++) { + for (int i = 0; i < col; i++) + { if (Board[row][i] == 1) return false; } /// check the first diagonal - for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) { + for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) + { if (Board[i][j] == 1) return false; } /// check the second diagonal - for (int i = row, j = col; i <= n - 1 && j >= 0; i++, j--) { + for (int i = row, j = col; i <= n - 1 && j >= 0; i++, j--) + { if (Board[i][j] == 1) return false; } return true; } -void NQueenSol(int Board[n][n], int col) { - if (col >= n) { +void NQueenSol(int Board[n][n], int col) +{ + if (col >= n) + { PrintSol(Board); return; } - for (int i = 0; i < n; i++) { - if (CanIMove(Board, i, col)) { + for (int i = 0; i < n; i++) + { + if (CanIMove(Board, i, col)) + { Board[i][col] = 1; NQueenSol(Board, col + 1); Board[i][col] = 0; @@ -44,7 +55,8 @@ void NQueenSol(int Board[n][n], int col) { } } -int main() { +int main() +{ int Board[n][n] = {0}; NQueenSol(Board, 0); } diff --git a/backtracking/rat_maze.cpp b/backtracking/rat_maze.cpp index 307b5c7b0c9..5454a6c82d3 100644 --- a/backtracking/rat_maze.cpp +++ b/backtracking/rat_maze.cpp @@ -1,73 +1,73 @@ /* - A Maze is given as N*N binary matrix of blocks where source block is the upper - left most block i.e., maze[0][0] and destination block is lower rightmost - block i.e., maze[N-1][N-1]. A rat starts from source and has to reach destination. - The rat can move only in two directions: forward and down. In the maze matrix, - 0 means the block is dead end and 1 means the block can be used in the path - from source to destination. + A Maze is given as N*N binary matrix of blocks where source block is the + upper left most block i.e., maze[0][0] and destination block is lower + rightmost block i.e., maze[N-1][N-1]. A rat starts from source and has to + reach destination. The rat can move only in two directions: forward and down. + In the maze matrix, 0 means the block is dead end and 1 means the block can + be used in the path from source to destination. */ #include #define size 4 using namespace std; -int solveMaze(int currposrow, int currposcol, int maze[size][size], int soln[size][size]) +int solveMaze(int currposrow, int currposcol, int maze[size][size], + int soln[size][size]) { - if ((currposrow == size - 1) && (currposcol == size - 1)) - { - soln[currposrow][currposcol] = 1; - for (int i = 0; i < size; ++i) - { - for (int j = 0; j < size; ++j) - { - cout << soln[i][j]; - } - cout << endl; - } - return 1; - } - else - { - soln[currposrow][currposcol] = 1; + if ((currposrow == size - 1) && (currposcol == size - 1)) + { + soln[currposrow][currposcol] = 1; + for (int i = 0; i < size; ++i) + { + for (int j = 0; j < size; ++j) + { + cout << soln[i][j]; + } + cout << endl; + } + return 1; + } + else + { + soln[currposrow][currposcol] = 1; - // if there exist a solution by moving one step ahead in a collumn - if ((currposcol < size - 1) && maze[currposrow][currposcol + 1] == 1 && solveMaze(currposrow, currposcol + 1, maze, soln)) - { - return 1; - } + // if there exist a solution by moving one step ahead in a collumn + if ((currposcol < size - 1) && maze[currposrow][currposcol + 1] == 1 && + solveMaze(currposrow, currposcol + 1, maze, soln)) + { + return 1; + } - // if there exists a solution by moving one step ahead in a row - if ((currposrow < size - 1) && maze[currposrow + 1][currposcol] == 1 && solveMaze(currposrow + 1, currposcol, maze, soln)) - { - return 1; - } + // if there exists a solution by moving one step ahead in a row + if ((currposrow < size - 1) && maze[currposrow + 1][currposcol] == 1 && + solveMaze(currposrow + 1, currposcol, maze, soln)) + { + return 1; + } - // the backtracking part - soln[currposrow][currposcol] = 0; - return 0; - } + // the backtracking part + soln[currposrow][currposcol] = 0; + return 0; + } } int main(int argc, char const *argv[]) { - int maze[size][size] = { - {1, 0, 1, 0}, - {1, 0, 1, 1}, - {1, 0, 0, 1}, - {1, 1, 1, 1}}; + int maze[size][size] = { + {1, 0, 1, 0}, {1, 0, 1, 1}, {1, 0, 0, 1}, {1, 1, 1, 1}}; - int soln[size][size]; + int soln[size][size]; - for (int i = 0; i < size; ++i) - { - for (int j = 0; j < size; ++j) - { - soln[i][j] = 0; - } - } + for (int i = 0; i < size; ++i) + { + for (int j = 0; j < size; ++j) + { + soln[i][j] = 0; + } + } - int currposrow = 0; - int currposcol = 0; - solveMaze(currposrow, currposcol, maze, soln); - return 0; + int currposrow = 0; + int currposcol = 0; + solveMaze(currposrow, currposcol, maze, soln); + return 0; } diff --git a/backtracking/sudoku_solve.cpp b/backtracking/sudoku_solve.cpp index 6a01fd395ea..c980408411e 100644 --- a/backtracking/sudoku_solve.cpp +++ b/backtracking/sudoku_solve.cpp @@ -1,11 +1,11 @@ #include using namespace std; -///N=9; +/// N=9; int n = 9; bool isPossible(int mat[][9], int i, int j, int no) { - ///Row or col nahin hona chahiye + /// Row or col nahin hona chahiye for (int x = 0; x < n; x++) { if (mat[x][j] == no || mat[i][x] == no) @@ -33,7 +33,6 @@ bool isPossible(int mat[][9], int i, int j, int no) } void printMat(int mat[][9]) { - for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) @@ -54,60 +53,54 @@ void printMat(int mat[][9]) bool solveSudoku(int mat[][9], int i, int j) { - ///Base Case + /// Base Case if (i == 9) { - ///Solve kr chuke hain for 9 rows already + /// Solve kr chuke hain for 9 rows already printMat(mat); return true; } - ///Crossed the last Cell in the row + /// Crossed the last Cell in the row if (j == 9) { return solveSudoku(mat, i + 1, 0); } - ///Blue Cell - Skip + /// Blue Cell - Skip if (mat[i][j] != 0) { return solveSudoku(mat, i, j + 1); } - ///White Cell - ///Try to place every possible no + /// White Cell + /// Try to place every possible no for (int no = 1; no <= 9; no++) { if (isPossible(mat, i, j, no)) { - ///Place the no - assuming solution aa jayega + /// Place the no - assuming solution aa jayega mat[i][j] = no; bool aageKiSolveHui = solveSudoku(mat, i, j + 1); if (aageKiSolveHui) { return true; } - ///Nahin solve hui - ///loop will place the next no. + /// Nahin solve hui + /// loop will place the next no. } } - ///Sare no try kr liey, kisi se bhi solve nahi hui + /// Sare no try kr liey, kisi se bhi solve nahi hui mat[i][j] = 0; return false; } int main() { - - int mat[9][9] = - {{5, 3, 0, 0, 7, 0, 0, 0, 0}, - {6, 0, 0, 1, 9, 5, 0, 0, 0}, - {0, 9, 8, 0, 0, 0, 0, 6, 0}, - {8, 0, 0, 0, 6, 0, 0, 0, 3}, - {4, 0, 0, 8, 0, 3, 0, 0, 1}, - {7, 0, 0, 0, 2, 0, 0, 0, 6}, - {0, 6, 0, 0, 0, 0, 2, 8, 0}, - {0, 0, 0, 4, 1, 9, 0, 0, 5}, - {0, 0, 0, 0, 8, 0, 0, 7, 9}}; + int mat[9][9] = {{5, 3, 0, 0, 7, 0, 0, 0, 0}, {6, 0, 0, 1, 9, 5, 0, 0, 0}, + {0, 9, 8, 0, 0, 0, 0, 6, 0}, {8, 0, 0, 0, 6, 0, 0, 0, 3}, + {4, 0, 0, 8, 0, 3, 0, 0, 1}, {7, 0, 0, 0, 2, 0, 0, 0, 6}, + {0, 6, 0, 0, 0, 0, 2, 8, 0}, {0, 0, 0, 4, 1, 9, 0, 0, 5}, + {0, 0, 0, 0, 8, 0, 0, 7, 9}}; printMat(mat); cout << "Solution " << endl; diff --git a/computer_oriented_statistical_methods/bisection_method.cpp b/computer_oriented_statistical_methods/bisection_method.cpp index c93c529d248..ea0a5e931c5 100644 --- a/computer_oriented_statistical_methods/bisection_method.cpp +++ b/computer_oriented_statistical_methods/bisection_method.cpp @@ -23,29 +23,36 @@ /** define \f$f(x)\f$ to find root for */ -static double eq(double i) { +static double eq(double i) +{ return (std::pow(i, 3) - (4 * i) - 9); // original equation } /** get the sign of any given number */ template -int sgn(T val) { +int sgn(T val) +{ return (T(0) < val) - (val < T(0)); } /** main function */ -int main() { +int main() +{ double a = -1, b = 1, x, z; int i; // loop to find initial intervals a, b - for (int i = 0; i < MAX_ITERATIONS; i++) { + for (int i = 0; i < MAX_ITERATIONS; i++) + { z = eq(a); x = eq(b); - if (sgn(z) == sgn(x)) { // same signs, increase interval + if (sgn(z) == sgn(x)) + { // same signs, increase interval b++; a--; - } else { // if opposite signs, we got our interval + } + else + { // if opposite signs, we got our interval break; } } @@ -54,15 +61,19 @@ int main() { std::cout << "\nSecond initial: " << b; // start iterations - for (i = 0; i < MAX_ITERATIONS; i++) { + for (i = 0; i < MAX_ITERATIONS; i++) + { x = (a + b) / 2; z = eq(x); std::cout << "\n\nz: " << z << "\t[" << a << " , " << b << " | Bisect: " << x << "]"; - if (z < 0) { + if (z < 0) + { a = x; - } else { + } + else + { b = x; } diff --git a/computer_oriented_statistical_methods/false_position.cpp b/computer_oriented_statistical_methods/false_position.cpp index aebd154bb07..6bdc0cf6798 100644 --- a/computer_oriented_statistical_methods/false_position.cpp +++ b/computer_oriented_statistical_methods/false_position.cpp @@ -25,29 +25,36 @@ /** define \f$f(x)\f$ to find root for */ -static double eq(double i) { +static double eq(double i) +{ return (std::pow(i, 3) - (4 * i) - 9); // origial equation } /** get the sign of any given number */ template -int sgn(T val) { +int sgn(T val) +{ return (T(0) < val) - (val < T(0)); } /** main function */ -int main() { +int main() +{ double a = -1, b = 1, x, z, m, n, c; int i; // loop to find initial intervals a, b - for (int i = 0; i < MAX_ITERATIONS; i++) { + for (int i = 0; i < MAX_ITERATIONS; i++) + { z = eq(a); x = eq(b); - if (sgn(z) == sgn(x)) { // same signs, increase interval + if (sgn(z) == sgn(x)) + { // same signs, increase interval b++; a--; - } else { // if opposite signs, we got our interval + } + else + { // if opposite signs, we got our interval break; } } @@ -55,7 +62,8 @@ int main() { std::cout << "\nFirst initial: " << a; std::cout << "\nSecond initial: " << b; - for (i = 0; i < MAX_ITERATIONS; i++) { + for (i = 0; i < MAX_ITERATIONS; i++) + { m = eq(a); n = eq(b); @@ -64,7 +72,8 @@ int main() { a = c; z = eq(c); - if (std::abs(z) < EPSILON) { // stoping criteria + if (std::abs(z) < EPSILON) + { // stoping criteria break; } } diff --git a/computer_oriented_statistical_methods/gaussian_elimination.cpp b/computer_oriented_statistical_methods/gaussian_elimination.cpp index 60b5648ec84..01cb578b2ca 100644 --- a/computer_oriented_statistical_methods/gaussian_elimination.cpp +++ b/computer_oriented_statistical_methods/gaussian_elimination.cpp @@ -6,7 +6,8 @@ #include /** Main function */ -int main() { +int main() +{ int mat_size, i, j, step; std::cout << "Matrix size: "; @@ -14,7 +15,8 @@ int main() { // create a 2D matrix by dynamic memory allocation double **mat = new double *[mat_size + 1], **x = new double *[mat_size]; - for (i = 0; i <= mat_size; i++) { + for (i = 0; i <= mat_size; i++) + { mat[i] = new double[mat_size + 1]; if (i < mat_size) x[i] = new double[mat_size + 1]; @@ -22,16 +24,20 @@ int main() { // get the matrix elements from user std::cout << std::endl << "Enter value of the matrix: " << std::endl; - for (i = 0; i < mat_size; i++) { - for (j = 0; j <= mat_size; j++) { + for (i = 0; i < mat_size; i++) + { + for (j = 0; j <= mat_size; j++) + { std::cin >> mat[i][j]; // Enter (mat_size*mat_size) value of the matrix. } } // perform Gaussian elimination - for (step = 0; step < mat_size - 1; step++) { - for (i = step; i < mat_size - 1; i++) { + for (step = 0; step < mat_size - 1; step++) + { + for (i = step; i < mat_size - 1; i++) + { double a = (mat[i + 1][step] / mat[step][step]); for (j = step; j <= mat_size; j++) @@ -41,8 +47,10 @@ int main() { std::cout << std::endl << "Matrix using Gaussian Elimination method: " << std::endl; - for (i = 0; i < mat_size; i++) { - for (j = 0; j <= mat_size; j++) { + for (i = 0; i < mat_size; i++) + { + for (j = 0; j <= mat_size; j++) + { x[i][j] = mat[i][j]; std::cout << mat[i][j] << " "; } @@ -50,9 +58,11 @@ int main() { } std::cout << std::endl << "Value of the Gaussian Elimination method: " << std::endl; - for (i = mat_size - 1; i >= 0; i--) { + for (i = mat_size - 1; i >= 0; i--) + { double sum = 0; - for (j = mat_size - 1; j > i; j--) { + for (j = mat_size - 1; j > i; j--) + { x[i][j] = x[j][j] * x[i][j]; sum = x[i][j] + sum; } @@ -64,7 +74,8 @@ int main() { std::cout << "x" << i << "= " << x[i][i] << std::endl; } - for (i = 0; i <= mat_size; i++) { + for (i = 0; i <= mat_size; i++) + { delete[] mat[i]; if (i < mat_size) delete[] x[i]; diff --git a/computer_oriented_statistical_methods/newton_raphson_method.cpp b/computer_oriented_statistical_methods/newton_raphson_method.cpp index 318363a3922..a93774b9167 100644 --- a/computer_oriented_statistical_methods/newton_raphson_method.cpp +++ b/computer_oriented_statistical_methods/newton_raphson_method.cpp @@ -21,18 +21,21 @@ /** define \f$f(x)\f$ to find root for */ -static double eq(double i) { +static double eq(double i) +{ return (std::pow(i, 3) - (4 * i) - 9); // original equation } /** define the derivative function \f$f'(x)\f$ */ -static double eq_der(double i) { +static double eq_der(double i) +{ return ((3 * std::pow(i, 2)) - 4); // derivative of equation } /** Main function */ -int main() { +int main() +{ std::srand(std::time(nullptr)); // initialize randomizer double z, c = std::rand() % 100, m, n; @@ -41,7 +44,8 @@ int main() { std::cout << "\nInitial approximation: " << c; // start iterations - for (i = 0; i < MAX_ITERATIONS; i++) { + for (i = 0; i < MAX_ITERATIONS; i++) + { m = eq(c); n = eq_der(c); diff --git a/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp b/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp index de02b27bba7..c3fe8be0399 100644 --- a/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp +++ b/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp @@ -16,11 +16,13 @@ */ template std::ostream &operator<<(std::ostream &out, - std::vector> const &v) { + std::vector> const &v) +{ const int width = 10; const char separator = ' '; - for (size_t row = 0; row < v.size(); row++) { + for (size_t row = 0; row < v.size(); row++) + { for (size_t col = 0; col < v[row].size(); col++) out << std::left << std::setw(width) << std::setfill(separator) << v[row][col]; @@ -34,7 +36,8 @@ std::ostream &operator<<(std::ostream &out, * operator to print a vector */ template -std::ostream &operator<<(std::ostream &out, std::vector const &v) { +std::ostream &operator<<(std::ostream &out, std::vector const &v) +{ const int width = 15; const char separator = ' '; @@ -50,7 +53,8 @@ std::ostream &operator<<(std::ostream &out, std::vector const &v) { * \returns 1 if true, 0 if false */ template -inline bool is_square(std::vector> const &A) { +inline bool is_square(std::vector> const &A) +{ // Assuming A is square matrix size_t N = A.size(); for (size_t i = 0; i < N; i++) @@ -68,7 +72,8 @@ inline bool is_square(std::vector> const &A) { **/ template std::vector> operator*(std::vector> const &A, - std::vector> const &B) { + std::vector> const &B) +{ // Number of rows in A size_t N_A = A.size(); // Number of columns in B @@ -76,15 +81,18 @@ std::vector> operator*(std::vector> const &A, std::vector> result(N_A); - if (A[0].size() != B.size()) { + if (A[0].size() != B.size()) + { std::cerr << "Number of columns in A != Number of rows in B (" << A[0].size() << ", " << B.size() << ")" << std::endl; return result; } - for (size_t row = 0; row < N_A; row++) { + for (size_t row = 0; row < N_A; row++) + { std::vector v(N_B); - for (size_t col = 0; col < N_B; col++) { + for (size_t col = 0; col < N_B; col++) + { v[col] = static_cast(0); for (size_t j = 0; j < B.size(); j++) v[col] += A[row][j] * B[j][col]; @@ -101,19 +109,22 @@ std::vector> operator*(std::vector> const &A, */ template std::vector operator*(std::vector> const &A, - std::vector const &B) { + std::vector const &B) +{ // Number of rows in A size_t N_A = A.size(); std::vector result(N_A); - if (A[0].size() != B.size()) { + if (A[0].size() != B.size()) + { std::cerr << "Number of columns in A != Number of rows in B (" << A[0].size() << ", " << B.size() << ")" << std::endl; return result; } - for (size_t row = 0; row < N_A; row++) { + for (size_t row = 0; row < N_A; row++) + { result[row] = static_cast(0); for (size_t j = 0; j < B.size(); j++) result[row] += A[row][j] * B[j]; } @@ -126,13 +137,15 @@ std::vector operator*(std::vector> const &A, * \returns resultant vector */ template -std::vector operator*(float const scalar, std::vector const &A) { +std::vector operator*(float const scalar, std::vector const &A) +{ // Number of rows in A size_t N_A = A.size(); std::vector result(N_A); - for (size_t row = 0; row < N_A; row++) { + for (size_t row = 0; row < N_A; row++) + { result[row] += A[row] * static_cast(scalar); } @@ -144,7 +157,8 @@ std::vector operator*(float const scalar, std::vector const &A) { * \returns resultant vector */ template -std::vector operator*(std::vector const &A, float const scalar) { +std::vector operator*(std::vector const &A, float const scalar) +{ // Number of rows in A size_t N_A = A.size(); @@ -161,7 +175,8 @@ std::vector operator*(std::vector const &A, float const scalar) { * \returns resultant vector */ template -std::vector operator/(std::vector const &A, float const scalar) { +std::vector operator/(std::vector const &A, float const scalar) +{ return (1.f / scalar) * A; } @@ -170,13 +185,15 @@ std::vector operator/(std::vector const &A, float const scalar) { * \returns resultant vector */ template -std::vector operator-(std::vector const &A, std::vector const &B) { +std::vector operator-(std::vector const &A, std::vector const &B) +{ // Number of rows in A size_t N = A.size(); std::vector result(N); - if (B.size() != N) { + if (B.size() != N) + { std::cerr << "Vector dimensions shouldbe identical!" << std::endl; return A; } @@ -191,13 +208,15 @@ std::vector operator-(std::vector const &A, std::vector const &B) { * \returns resultant vector */ template -std::vector operator+(std::vector const &A, std::vector const &B) { +std::vector operator+(std::vector const &A, std::vector const &B) +{ // Number of rows in A size_t N = A.size(); std::vector result(N); - if (B.size() != N) { + if (B.size() != N) + { std::cerr << "Vector dimensions shouldbe identical!" << std::endl; return A; } @@ -214,26 +233,30 @@ std::vector operator+(std::vector const &A, std::vector const &B) { **/ template std::vector> get_inverse( - std::vector> const &A) { + std::vector> const &A) +{ // Assuming A is square matrix size_t N = A.size(); std::vector> inverse(N); - for (size_t row = 0; row < N; row++) { + for (size_t row = 0; row < N; row++) + { // preallocatae a resultant identity matrix inverse[row] = std::vector(N); for (size_t col = 0; col < N; col++) inverse[row][col] = (row == col) ? 1.f : 0.f; } - if (!is_square(A)) { + if (!is_square(A)) + { std::cerr << "A must be a square matrix!" << std::endl; return inverse; } // preallocatae a temporary matrix identical to A std::vector> temp(N); - for (size_t row = 0; row < N; row++) { + for (size_t row = 0; row < N; row++) + { std::vector v(N); for (size_t col = 0; col < N; col++) v[col] = static_cast(A[row][col]); @@ -241,22 +264,27 @@ std::vector> get_inverse( } // start transformations - for (size_t row = 0; row < N; row++) { - for (size_t row2 = row; row2 < N && temp[row][row] == 0; row2++) { + for (size_t row = 0; row < N; row++) + { + for (size_t row2 = row; row2 < N && temp[row][row] == 0; row2++) + { // this to ensure diagonal elements are not 0 temp[row] = temp[row] + temp[row2]; inverse[row] = inverse[row] + inverse[row2]; } - for (size_t col2 = row; col2 < N && temp[row][row] == 0; col2++) { + for (size_t col2 = row; col2 < N && temp[row][row] == 0; col2++) + { // this to further ensure diagonal elements are not 0 - for (size_t row2 = 0; row2 < N; row2++) { + for (size_t row2 = 0; row2 < N; row2++) + { temp[row2][row] = temp[row2][row] + temp[row2][col2]; inverse[row2][row] = inverse[row2][row] + inverse[row2][col2]; } } - if (temp[row][row] == 0) { + if (temp[row][row] == 0) + { // Probably a low-rank matrix and hence singular std::cerr << "Low-rank matrix, no inverse!" << std::endl; return inverse; @@ -267,7 +295,8 @@ std::vector> get_inverse( temp[row] = temp[row] / divisor; inverse[row] = inverse[row] / divisor; // Row transformations - for (size_t row2 = 0; row2 < N; row2++) { + for (size_t row2 = 0; row2 < N; row2++) + { if (row2 == row) continue; float factor = temp[row2][row]; @@ -284,11 +313,12 @@ std::vector> get_inverse( * \returns resultant matrix **/ template -std::vector> get_transpose( - std::vector> const &A) { +std::vector> get_transpose(std::vector> const &A) +{ std::vector> result(A[0].size()); - for (size_t row = 0; row < A[0].size(); row++) { + for (size_t row = 0; row < A[0].size(); row++) + { std::vector v(A.size()); for (size_t col = 0; col < A.size(); col++) v[col] = A[col][row]; @@ -306,7 +336,8 @@ std::vector> get_transpose( */ template std::vector fit_OLS_regressor(std::vector> const &X, - std::vector const &Y) { + std::vector const &Y) +{ // NxF std::vector> X2 = X; for (size_t i = 0; i < X2.size(); i++) @@ -337,10 +368,12 @@ std::vector fit_OLS_regressor(std::vector> const &X, template std::vector predict_OLS_regressor(std::vector> const &X, std::vector const &beta /**< */ -) { +) +{ std::vector result(X.size()); - for (size_t rows = 0; rows < X.size(); rows++) { + for (size_t rows = 0; rows < X.size(); rows++) + { // -> start with constant term result[rows] = beta[X[0].size()]; for (size_t cols = 0; cols < X[0].size(); cols++) @@ -353,7 +386,8 @@ std::vector predict_OLS_regressor(std::vector> const &X, /** * main function */ -int main() { +int main() +{ size_t N, F; std::cout << "Enter number of features: "; @@ -370,7 +404,8 @@ int main() { << "Enter training data. Per sample, provide features ad one output." << std::endl; - for (size_t rows = 0; rows < N; rows++) { + for (size_t rows = 0; rows < N; rows++) + { std::vector v(F); std::cout << "Sample# " << rows + 1 << ": "; for (size_t cols = 0; cols < F; cols++) @@ -391,7 +426,8 @@ int main() { std::vector> data2(T); // vector Y2(T); - for (size_t rows = 0; rows < T; rows++) { + for (size_t rows = 0; rows < T; rows++) + { std::cout << "Sample# " << rows + 1 << ": "; std::vector v(F); for (size_t cols = 0; cols < F; cols++) std::cin >> v[cols]; diff --git a/computer_oriented_statistical_methods/successive_approximation.cpp b/computer_oriented_statistical_methods/successive_approximation.cpp index 351382f2418..137933591f9 100644 --- a/computer_oriented_statistical_methods/successive_approximation.cpp +++ b/computer_oriented_statistical_methods/successive_approximation.cpp @@ -17,11 +17,13 @@ static float eq(float y) { return (3 * y) - cos(y) - 2; } static float eqd(float y) { return 0.5 * (cos(y) + 2); } /** Main function */ -int main() { +int main() +{ float y, x1, x2, x3, sum, s, a, f1, f2, gd; int i, n; - for (i = 0; i < 10; i++) { + for (i = 0; i < 10; i++) + { sum = eq(y); std::cout << "value of equation at " << i << " " << sum << "\n"; y++; @@ -31,7 +33,8 @@ int main() { std::cout << "enter the no iteration to perform->\n"; std::cin >> n; - for (i = 0; i <= n; i++) { + for (i = 0; i <= n; i++) + { x2 = eqd(x1); std::cout << "\nenter the x2->" << x2; x1 = x2; diff --git a/data_structure/avltree.cpp b/data_structure/avltree.cpp index db6b9e0d449..dc96ad97760 100644 --- a/data_structure/avltree.cpp +++ b/data_structure/avltree.cpp @@ -5,172 +5,165 @@ using namespace std; typedef struct node { - int data; - int height; - struct node *left; - struct node *right; + int data; + int height; + struct node *left; + struct node *right; } node; -int max(int a, int b) -{ - return a > b ? a : b; -} +int max(int a, int b) { return a > b ? a : b; } // Returns a new Node node *createNode(int data) { - node *nn = new node(); - nn->data = data; - nn->height = 0; - nn->left = NULL; - nn->right = NULL; - return nn; + node *nn = new node(); + nn->data = data; + nn->height = 0; + nn->left = NULL; + nn->right = NULL; + return nn; } // Returns height of tree int height(node *root) { - if (root == NULL) - return 0; - return 1 + max(height(root->left), height(root->right)); + if (root == NULL) + return 0; + return 1 + max(height(root->left), height(root->right)); } // Returns difference between height of left and right subtree -int getBalance(node *root) -{ - return height(root->left) - height(root->right); -} +int getBalance(node *root) { return height(root->left) - height(root->right); } // Returns Node after Right Rotation node *rightRotate(node *root) { - node *t = root->left; - node *u = t->right; - t->right = root; - root->left = u; - return t; + node *t = root->left; + node *u = t->right; + t->right = root; + root->left = u; + return t; } // Returns Node after Left Rotation node *leftRotate(node *root) { - node *t = root->right; - node *u = t->left; - t->left = root; - root->right = u; - return t; + node *t = root->right; + node *u = t->left; + t->left = root; + root->right = u; + return t; } // Returns node with minimum value in the tree node *minValue(node *root) { - if (root->left == NULL) - return root; - return minValue(root->left); + if (root->left == NULL) + return root; + return minValue(root->left); } // Balanced Insertion node *insert(node *root, int item) { - node *nn = createNode(item); - if (root == NULL) - return nn; - if (item < root->data) - root->left = insert(root->left, item); - else - root->right = insert(root->right, item); - int b = getBalance(root); - if (b > 1) - { - if (getBalance(root->left) < 0) - root->left = leftRotate(root->left); // Left-Right Case - return rightRotate(root); // Left-Left Case - } - else if (b < -1) - { - if (getBalance(root->right) > 0) - root->right = rightRotate(root->right); // Right-Left Case - return leftRotate(root); // Right-Right Case - } - return root; + node *nn = createNode(item); + if (root == NULL) + return nn; + if (item < root->data) + root->left = insert(root->left, item); + else + root->right = insert(root->right, item); + int b = getBalance(root); + if (b > 1) + { + if (getBalance(root->left) < 0) + root->left = leftRotate(root->left); // Left-Right Case + return rightRotate(root); // Left-Left Case + } + else if (b < -1) + { + if (getBalance(root->right) > 0) + root->right = rightRotate(root->right); // Right-Left Case + return leftRotate(root); // Right-Right Case + } + return root; } // Balanced Deletion node *deleteNode(node *root, int key) { - if (root == NULL) - return root; - if (key < root->data) - root->left = deleteNode(root->left, key); - else if (key > root->data) - root->right = deleteNode(root->right, key); - - else - { - // Node to be deleted is leaf node or have only one Child - if (!root->right) - { - node *temp = root->left; - delete (root); - root = NULL; - return temp; - } - else if (!root->left) - { - node *temp = root->right; - delete (root); - root = NULL; - return temp; - } - // Node to be deleted have both left and right subtrees - node *temp = minValue(root->right); - root->data = temp->data; - root->right = deleteNode(root->right, temp->data); - } - // Balancing Tree after deletion - return root; + if (root == NULL) + return root; + if (key < root->data) + root->left = deleteNode(root->left, key); + else if (key > root->data) + root->right = deleteNode(root->right, key); + + else + { + // Node to be deleted is leaf node or have only one Child + if (!root->right) + { + node *temp = root->left; + delete (root); + root = NULL; + return temp; + } + else if (!root->left) + { + node *temp = root->right; + delete (root); + root = NULL; + return temp; + } + // Node to be deleted have both left and right subtrees + node *temp = minValue(root->right); + root->data = temp->data; + root->right = deleteNode(root->right, temp->data); + } + // Balancing Tree after deletion + return root; } // LevelOrder (Breadth First Search) void levelOrder(node *root) { - queue q; - q.push(root); - while (!q.empty()) - { - root = q.front(); - cout << root->data << " "; - q.pop(); - if (root->left) - q.push(root->left); - if (root->right) - q.push(root->right); - } + queue q; + q.push(root); + while (!q.empty()) + { + root = q.front(); + cout << root->data << " "; + q.pop(); + if (root->left) + q.push(root->left); + if (root->right) + q.push(root->right); + } } int main() { - // Testing AVL Tree - node *root = NULL; - int i; - for (i = 1; i <= 7; i++) - root = insert(root, i); - cout << "LevelOrder: "; - levelOrder(root); - root = deleteNode(root, 1); // Deleting key with value 1 - cout << "\nLevelOrder: "; - levelOrder(root); - root = deleteNode(root, 4); // Deletin key with value 4 - cout << "\nLevelOrder: "; - levelOrder(root); - return 0; + // Testing AVL Tree + node *root = NULL; + int i; + for (i = 1; i <= 7; i++) root = insert(root, i); + cout << "LevelOrder: "; + levelOrder(root); + root = deleteNode(root, 1); // Deleting key with value 1 + cout << "\nLevelOrder: "; + levelOrder(root); + root = deleteNode(root, 4); // Deletin key with value 4 + cout << "\nLevelOrder: "; + levelOrder(root); + return 0; } diff --git a/data_structure/binary_search_tree.cpp b/data_structure/binary_search_tree.cpp index 32a65517cdd..ea9df12d377 100644 --- a/data_structure/binary_search_tree.cpp +++ b/data_structure/binary_search_tree.cpp @@ -3,216 +3,210 @@ using namespace std; struct node { - int val; - node *left; - node *right; + int val; + node *left; + node *right; }; struct queue { - node *t[100]; - int front; - int rear; + node *t[100]; + int front; + int rear; }; queue q; -void enqueue(node *n) -{ - q.t[q.rear++] = n; -} +void enqueue(node *n) { q.t[q.rear++] = n; } -node *dequeue() -{ - return (q.t[q.front++]); -} +node *dequeue() { return (q.t[q.front++]); } void Insert(node *n, int x) { - if (x < n->val) - { - if (n->left == NULL) - { - node *temp = new node; - temp->val = x; - temp->left = NULL; - temp->right = NULL; - n->left = temp; - } - else - { - Insert(n->left, x); - } - } - else - { - if (n->right == NULL) - { - node *temp = new node; - temp->val = x; - temp->left = NULL; - temp->right = NULL; - n->left = temp; - } - else - { - Insert(n->right, x); - } - } + if (x < n->val) + { + if (n->left == NULL) + { + node *temp = new node; + temp->val = x; + temp->left = NULL; + temp->right = NULL; + n->left = temp; + } + else + { + Insert(n->left, x); + } + } + else + { + if (n->right == NULL) + { + node *temp = new node; + temp->val = x; + temp->left = NULL; + temp->right = NULL; + n->left = temp; + } + else + { + Insert(n->right, x); + } + } } int findMaxInLeftST(node *n) { - while (n->right != NULL) - { - n = n->right; - } - return n->val; + while (n->right != NULL) + { + n = n->right; + } + return n->val; } void Remove(node *p, node *n, int x) { - if (n->val == x) - { - if (n->right == NULL && n->left == NULL) - { - if (x < p->val) - { - p->right = NULL; - } - else - { - p->left = NULL; - } - } - else if (n->right == NULL) - { - if (x < p->val) - { - p->right = n->left; - } - else - { - p->left = n->left; - } - } - else if (n->left == NULL) - { - if (x < p->val) - { - p->right = n->right; - } - else - { - p->left = n->right; - } - } - else - { - int y = findMaxInLeftST(n->left); - n->val = y; - Remove(n, n->right, y); - } - } - else if (x < n->val) - { - Remove(n, n->left, x); - } - else - { - Remove(n, n->right, x); - } + if (n->val == x) + { + if (n->right == NULL && n->left == NULL) + { + if (x < p->val) + { + p->right = NULL; + } + else + { + p->left = NULL; + } + } + else if (n->right == NULL) + { + if (x < p->val) + { + p->right = n->left; + } + else + { + p->left = n->left; + } + } + else if (n->left == NULL) + { + if (x < p->val) + { + p->right = n->right; + } + else + { + p->left = n->right; + } + } + else + { + int y = findMaxInLeftST(n->left); + n->val = y; + Remove(n, n->right, y); + } + } + else if (x < n->val) + { + Remove(n, n->left, x); + } + else + { + Remove(n, n->right, x); + } } void BFT(node *n) { - if (n != NULL) - { - cout << n->val << " "; - enqueue(n->left); - enqueue(n->right); - BFT(dequeue()); - } + if (n != NULL) + { + cout << n->val << " "; + enqueue(n->left); + enqueue(n->right); + BFT(dequeue()); + } } void Pre(node *n) { - if (n != NULL) - { - cout << n->val << " "; - Pre(n->left); - Pre(n->right); - } + if (n != NULL) + { + cout << n->val << " "; + Pre(n->left); + Pre(n->right); + } } void In(node *n) { - if (n != NULL) - { - In(n->left); - cout << n->val << " "; - In(n->right); - } + if (n != NULL) + { + In(n->left); + cout << n->val << " "; + In(n->right); + } } void Post(node *n) { - if (n != NULL) - { - Post(n->left); - Post(n->right); - cout << n->val << " "; - } + if (n != NULL) + { + Post(n->left); + Post(n->right); + cout << n->val << " "; + } } int main() { - q.front = 0; - q.rear = 0; - int value; - int ch; - node *root = new node; - cout << "\nEnter the value of root node :"; - cin >> value; - root->val = value; - root->left = NULL; - root->right = NULL; - do - { - cout << "\n1. Insert"; - cout << "\n2. Delete"; - cout << "\n3. Breadth First"; - cout << "\n4. Preorder Depth First"; - cout << "\n5. Inorder Depth First"; - cout << "\n6. Postorder Depth First"; + q.front = 0; + q.rear = 0; + int value; + int ch; + node *root = new node; + cout << "\nEnter the value of root node :"; + cin >> value; + root->val = value; + root->left = NULL; + root->right = NULL; + do + { + cout << "\n1. Insert"; + cout << "\n2. Delete"; + cout << "\n3. Breadth First"; + cout << "\n4. Preorder Depth First"; + cout << "\n5. Inorder Depth First"; + cout << "\n6. Postorder Depth First"; - cout << "\nEnter Your Choice : "; - cin >> ch; - int x; - switch (ch) - { - case 1: - cout << "\nEnter the value to be Inserted : "; - cin >> x; - Insert(root, x); - break; - case 2: - cout << "\nEnter the value to be Deleted : "; - cin >> x; - Remove(root, root, x); - break; - case 3: - BFT(root); - break; - case 4: - Pre(root); - break; - case 5: - In(root); - break; - case 6: - Post(root); - break; - } - } while (ch != 0); + cout << "\nEnter Your Choice : "; + cin >> ch; + int x; + switch (ch) + { + case 1: + cout << "\nEnter the value to be Inserted : "; + cin >> x; + Insert(root, x); + break; + case 2: + cout << "\nEnter the value to be Deleted : "; + cin >> x; + Remove(root, root, x); + break; + case 3: + BFT(root); + break; + case 4: + Pre(root); + break; + case 5: + In(root); + break; + case 6: + Post(root); + break; + } + } while (ch != 0); } diff --git a/data_structure/binaryheap.cpp b/data_structure/binaryheap.cpp index 31129a82375..b2fc7d99cb4 100644 --- a/data_structure/binaryheap.cpp +++ b/data_structure/binaryheap.cpp @@ -1,6 +1,6 @@ // A C++ program to demonstrate common Binary Heap Operations -#include #include +#include using namespace std; // Prototype of a utility function to swap two integers @@ -9,10 +9,10 @@ void swap(int *x, int *y); // A class for Min Heap class MinHeap { - int *harr; // pointer to array of elements in heap - int capacity; // maximum possible size of min heap - int heap_size; // Current number of elements in min heap -public: + int *harr; // pointer to array of elements in heap + int capacity; // maximum possible size of min heap + int heap_size; // Current number of elements in min heap + public: // Constructor MinHeap(int capacity); diff --git a/data_structure/circular_queue_using_linked_list.cpp b/data_structure/circular_queue_using_linked_list.cpp index 4b1ec476c3d..d871244483b 100644 --- a/data_structure/circular_queue_using_linked_list.cpp +++ b/data_structure/circular_queue_using_linked_list.cpp @@ -11,7 +11,7 @@ class Queue node *front; node *rear; -public: + public: Queue() { front = NULL; diff --git a/data_structure/cll/cll.cpp b/data_structure/cll/cll.cpp index efc068f3c6a..e9fcfc40b3e 100644 --- a/data_structure/cll/cll.cpp +++ b/data_structure/cll/cll.cpp @@ -11,10 +11,7 @@ cll::cll() total = 0; } -cll::~cll() -{ - /* Desstructure, no need to fill */ -} +cll::~cll() { /* Desstructure, no need to fill */ } /* Display a list. and total element */ void cll::display() @@ -28,10 +25,10 @@ void cll::display() for (int i = 0; i < total; i++) { cout << current->data << " -> "; - current = current ->next; + current = current->next; } cout << head->data << endl; - cout << "Total element: "<< total <data = new_data; newNode->next = NULL; - if(head==NULL) { + if (head == NULL) + { head = newNode; - head -> next = head; - } else { + head->next = head; + } + else + { node *current = head; - while (current -> next != head) { + while (current->next != head) + { current = current->next; } newNode->next = head; @@ -64,12 +65,16 @@ void cll::insert_tail(int new_data) newNode = new node; newNode->data = new_data; newNode->next = NULL; - if(head==NULL) { + if (head == NULL) + { head = newNode; - head -> next = head; - } else { + head->next = head; + } + else + { node *current = head; - while (current -> next != head) { + while (current->next != head) + { current = current->next; } current->next = newNode; @@ -79,22 +84,22 @@ void cll::insert_tail(int new_data) } /* Get total element in list */ -int cll::get_size() -{ - return total; -} - +int cll::get_size() { return total; } /* Return true if the requested item (sent in as an argument) is in the list, otherwise return false */ bool cll::find_item(int item_to_find) { - if (head == NULL) { + if (head == NULL) + { cout << "List is empty !" << endl; return false; - } else { + } + else + { node *current = head; - while (current -> next != head) { + while (current->next != head) + { if (current->data == item_to_find) return true; current = current->next; @@ -104,24 +109,25 @@ bool cll::find_item(int item_to_find) } /* Overloading method*/ -int cll::operator*() -{ - return head->data; -} +int cll::operator*() { return head->data; } /* Overload the pre-increment operator. The iterator is advanced to the next node. */ void cll::operator++() { - if (head == NULL) { + if (head == NULL) + { cout << "List is empty !" << endl; - } else { + } + else + { node *current = head; - while (current -> next != head) { - current = current -> next; + while (current->next != head) + { + current = current->next; } - current->next = head -> next; - head = head -> next; + current->next = head->next; + head = head->next; } total--; } diff --git a/data_structure/cll/cll.h b/data_structure/cll/cll.h index ae71dcd01d2..89a9fe1991e 100644 --- a/data_structure/cll/cll.h +++ b/data_structure/cll/cll.h @@ -1,45 +1,45 @@ /* * Simple data structure CLL (Cicular Linear Linked List) * */ -#include #include -#include #include +#include +#include #ifndef CLL_H #define CLL_H /*The data structure is a linear linked list of integers */ struct node { - int data; - node * next; + int data; + node* next; }; class cll { - public: - cll(); /* Construct without parameter */ - ~cll(); - void display(); /* Show the list */ + public: + cll(); /* Construct without parameter */ + ~cll(); + void display(); /* Show the list */ - /****************************************************** - * Useful method for list - *******************************************************/ - void insert_front(int new_data); /* Insert a new value at head */ - void insert_tail(int new_data); /* Insert a new value at tail */ - int get_size(); /* Get total element in list */ - bool find_item(int item_to_find); /* Find an item in list */ + /****************************************************** + * Useful method for list + *******************************************************/ + void insert_front(int new_data); /* Insert a new value at head */ + void insert_tail(int new_data); /* Insert a new value at tail */ + int get_size(); /* Get total element in list */ + bool find_item(int item_to_find); /* Find an item in list */ - /****************************************************** - * Overloading method for list - *******************************************************/ - int operator*(); /* Returns the info contained in head */ - /* Overload the pre-increment operator. - The iterator is advanced to the next node. */ - void operator++(); + /****************************************************** + * Overloading method for list + *******************************************************/ + int operator*(); /* Returns the info contained in head */ + /* Overload the pre-increment operator. + The iterator is advanced to the next node. */ + void operator++(); - protected: - node * head; - int total; /* Total element in a list */ + protected: + node* head; + int total; /* Total element in a list */ }; #endif diff --git a/data_structure/cll/main_cll.cpp b/data_structure/cll/main_cll.cpp index 15388b8224d..3876f0393e9 100644 --- a/data_structure/cll/main_cll.cpp +++ b/data_structure/cll/main_cll.cpp @@ -3,42 +3,42 @@ using namespace std; int main() { - /* Test CLL */ - cout << "----------- Test construct -----------" << endl; - cll list1; - list1.display(); - cout << "----------- Test insert front -----------" << endl; - list1.insert_front(5); - cout << "After insert 5 at front: "< root, rnk; -void CreateSet(int n) { - root = vector (n+1); - rnk = vector (n+1, 1); - for (int i = 1; i <= n; ++i) { - root[i] = i; - } +void CreateSet(int n) +{ + root = vector(n + 1); + rnk = vector(n + 1, 1); + for (int i = 1; i <= n; ++i) + { + root[i] = i; + } } -int Find(int x) { - if (root[x] == x) { - return x; - } - return root[x] = Find(root[x]); +int Find(int x) +{ + if (root[x] == x) + { + return x; + } + return root[x] = Find(root[x]); } -bool InSameUnion(int x, int y) { - return Find(x) == Find(y); -} +bool InSameUnion(int x, int y) { return Find(x) == Find(y); } -void Union(int x, int y) { - int a = Find(x), b = Find(y); - if (a != b) { - if (rnk[a] < rnk[b]) { - root[a] = b; - } else if (rnk[a] > rnk[b]) { - root[b] = a; - } else { - root[a] = b; - ++rnk[b]; +void Union(int x, int y) +{ + int a = Find(x), b = Find(y); + if (a != b) + { + if (rnk[a] < rnk[b]) + { + root[a] = b; + } + else if (rnk[a] > rnk[b]) + { + root[b] = a; + } + else + { + root[a] = b; + ++rnk[b]; + } } - } } -int main() { - // tests CreateSet & Find - int n = 100; - CreateSet(n); - for (int i = 1; i <= 100; ++i) { - if (root[i] != i) { - cout << "Fail" << endl; - break; +int main() +{ + // tests CreateSet & Find + int n = 100; + CreateSet(n); + for (int i = 1; i <= 100; ++i) + { + if (root[i] != i) + { + cout << "Fail" << endl; + break; + } + } + // tests InSameUnion & Union + cout << "1 and 2 are initially not in the same subset" << endl; + if (InSameUnion(1, 2)) + { + cout << "Fail" << endl; + } + Union(1, 2); + cout << "1 and 2 are now in the same subset" << endl; + if (!InSameUnion(1, 2)) + { + cout << "Fail" << endl; } - } - // tests InSameUnion & Union - cout << "1 and 2 are initially not in the same subset" << endl; - if (InSameUnion(1, 2)) { - cout << "Fail" << endl; - } - Union(1, 2); - cout << "1 and 2 are now in the same subset" << endl; - if (!InSameUnion(1, 2)) { - cout << "Fail" << endl; - } - return 0; + return 0; } diff --git a/data_structure/doubly_linked_list.cpp b/data_structure/doubly_linked_list.cpp index 4fc38abfc28..4907c125d74 100644 --- a/data_structure/doubly_linked_list.cpp +++ b/data_structure/doubly_linked_list.cpp @@ -1,138 +1,166 @@ +#include +#include #include -#include -#include -struct node { - int val; - node *prev; - node *next; -}*start; +struct node +{ + int val; + node *prev; + node *next; +} * start; -class double_linked_list { +class double_linked_list +{ public: - double_linked_list() { - start = NULL; - } - void insert(int x); - void remove(int x); - void search(int x); - void show(); - void reverseShow(); + double_linked_list() { start = NULL; } + void insert(int x); + void remove(int x); + void search(int x); + void show(); + void reverseShow(); }; -void double_linked_list::insert(int x) { - node *t = start; - if (start != NULL) { - while (t->next != NULL) { - t = t->next; +void double_linked_list::insert(int x) +{ + node *t = start; + if (start != NULL) + { + while (t->next != NULL) + { + t = t->next; + } + node *n = new node; + t->next = n; + n->prev = t; + n->val = x; + n->next = NULL; + } + else + { + node *n = new node; + n->val = x; + n->prev = NULL; + n->next = NULL; + start = n; } - node *n = new node; - t->next = n; - n->prev = t; - n->val = x; - n->next = NULL; - } else { - node *n = new node; - n->val = x; - n->prev = NULL; - n->next = NULL; - start = n; - } } -void double_linked_list::remove(int x) { - node *t = start; - while (t != NULL && t->val != x) { - t = t-> next; - } - if (t == NULL) { - return; - } - if (t->prev == NULL) { - if (t->next == NULL) { - start = NULL; - } else { - start = t->next; - start->prev = NULL; +void double_linked_list::remove(int x) +{ + node *t = start; + while (t != NULL && t->val != x) + { + t = t->next; + } + if (t == NULL) + { + return; + } + if (t->prev == NULL) + { + if (t->next == NULL) + { + start = NULL; + } + else + { + start = t->next; + start->prev = NULL; + } + } + else if (t->next == NULL) + { + t->prev->next = NULL; + } + else + { + t->prev->next = t->next; + t->next->prev = t->prev; } - } else if (t->next == NULL) { - t->prev->next = NULL; - } else { - t->prev->next = t->next; - t->next->prev = t->prev; - } - delete t; + delete t; } -void double_linked_list::search(int x) { - node *t = start; - int found = 0; - while (t != NULL) { - if (t->val == x) { - std::cout << "\nFound"; - found = 1; - break; +void double_linked_list::search(int x) +{ + node *t = start; + int found = 0; + while (t != NULL) + { + if (t->val == x) + { + std::cout << "\nFound"; + found = 1; + break; + } + t = t->next; + } + if (found == 0) + { + std::cout << "\nNot Found"; } - t = t->next; - } - if (found == 0) { - std::cout << "\nNot Found"; - } } -void double_linked_list::show() { - node *t = start; - while (t != NULL) { - std::cout << t->val << "\t"; - t = t->next; - } +void double_linked_list::show() +{ + node *t = start; + while (t != NULL) + { + std::cout << t->val << "\t"; + t = t->next; + } } -void double_linked_list::reverseShow() { - node *t = start; - while (t != NULL && t->next != NULL) { - t = t->next; - } - while (t != NULL) { - std::cout << t->val << "\t"; - t = t->prev; - } +void double_linked_list::reverseShow() +{ + node *t = start; + while (t != NULL && t->next != NULL) + { + t = t->next; + } + while (t != NULL) + { + std::cout << t->val << "\t"; + t = t->prev; + } } -int main() { - int choice, x; - double_linked_list ob; - do { - std::cout << "\n1. Insert"; - std::cout << "\n2. Delete"; - std::cout << "\n3. Search"; - std::cout << "\n4. Forward print"; - std::cout << "\n5. Reverse print"; - std::cout << "\n\nEnter you choice : "; - std::cin >> choice; - switch (choice) { - case 1: - std::cout << "\nEnter the element to be inserted : "; - std::cin >> x; - ob.insert(x); - break; - case 2: - std::cout << "\nEnter the element to be removed : "; - std::cin >> x; - ob.remove(x); - break; - case 3: - std::cout << "\nEnter the element to be searched : "; - std::cin >> x; - ob.search(x); - break; - case 4: - ob.show(); - break; - case 5: - ob.reverseShow(); - break; - } - } while (choice != 0); - return 0; +int main() +{ + int choice, x; + double_linked_list ob; + do + { + std::cout << "\n1. Insert"; + std::cout << "\n2. Delete"; + std::cout << "\n3. Search"; + std::cout << "\n4. Forward print"; + std::cout << "\n5. Reverse print"; + std::cout << "\n\nEnter you choice : "; + std::cin >> choice; + switch (choice) + { + case 1: + std::cout << "\nEnter the element to be inserted : "; + std::cin >> x; + ob.insert(x); + break; + case 2: + std::cout << "\nEnter the element to be removed : "; + std::cin >> x; + ob.remove(x); + break; + case 3: + std::cout << "\nEnter the element to be searched : "; + std::cin >> x; + ob.search(x); + break; + case 4: + ob.show(); + break; + case 5: + ob.reverseShow(); + break; + } + } while (choice != 0); + return 0; } diff --git a/data_structure/linked_list.cpp b/data_structure/linked_list.cpp index 64cad14f9ea..f639bb16ce7 100644 --- a/data_structure/linked_list.cpp +++ b/data_structure/linked_list.cpp @@ -1,135 +1,160 @@ #include -struct node { - int val; - node *next; +struct node +{ + int val; + node *next; }; node *start; -void insert(int x) { - node *t = start; - node *n = new node; - n->val = x; - n->next = NULL; - if (start != NULL) { - while (t->next != NULL) { - t = t->next; - } - t->next = n; - } else { - start = n; +void insert(int x) +{ + node *t = start; + node *n = new node; + n->val = x; + n->next = NULL; + if (start != NULL) + { + while (t->next != NULL) + { + t = t->next; } - + t->next = n; + } + else + { + start = n; + } } -void remove(int x) { - if (start == NULL) { - std::cout << "\nLinked List is empty\n"; - return; - } else if (start->val == x) { - node *temp = start; - start = start->next; - delete temp; - return; - } +void remove(int x) +{ + if (start == NULL) + { + std::cout << "\nLinked List is empty\n"; + return; + } + else if (start->val == x) + { + node *temp = start; + start = start->next; + delete temp; + return; + } - node *temp = start, *parent = start; + node *temp = start, *parent = start; - while (temp != NULL && temp->val != x) { - parent = temp; - temp = temp->next; - } + while (temp != NULL && temp->val != x) + { + parent = temp; + temp = temp->next; + } - if (temp == NULL) { - std::cout << std::endl << x << " not found in list\n"; - return; - } + if (temp == NULL) + { + std::cout << std::endl << x << " not found in list\n"; + return; + } - parent->next = temp->next; - delete temp; + parent->next = temp->next; + delete temp; } -void search(int x) { - node *t = start; - int found = 0; - while (t != NULL) { - if (t->val == x) { - std::cout << "\nFound"; - found = 1; - break; - } - t = t->next; - } - if (found == 0) { - std::cout << "\nNot Found"; +void search(int x) +{ + node *t = start; + int found = 0; + while (t != NULL) + { + if (t->val == x) + { + std::cout << "\nFound"; + found = 1; + break; } + t = t->next; + } + if (found == 0) + { + std::cout << "\nNot Found"; + } } -void show() { - node *t = start; - while (t != NULL) { - std::cout << t->val << "\t"; - t = t->next; - } +void show() +{ + node *t = start; + while (t != NULL) + { + std::cout << t->val << "\t"; + t = t->next; + } } -void reverse() { - node *first = start; - if (first != NULL) { - node *second = first->next; - while (second != NULL) { - node *tem = second->next; - second->next = first; - first = second; - second = tem; - } - start->next = NULL; - start = first; - } else { - std::cout << "\nEmpty list"; +void reverse() +{ + node *first = start; + if (first != NULL) + { + node *second = first->next; + while (second != NULL) + { + node *tem = second->next; + second->next = first; + first = second; + second = tem; } + start->next = NULL; + start = first; + } + else + { + std::cout << "\nEmpty list"; + } } -int main() { - int choice, x; - do { - std::cout << "\n1. Insert"; - std::cout << "\n2. Delete"; - std::cout << "\n3. Search"; - std::cout << "\n4. Print"; - std::cout << "\n5. Reverse"; - std::cout << "\n0. Exit"; - std::cout << "\n\nEnter you choice : "; - std::cin >> choice; - switch (choice) { - case 1: - std::cout << "\nEnter the element to be inserted : "; - std::cin >> x; - insert(x); - break; - case 2: - std::cout << "\nEnter the element to be removed : "; - std::cin >> x; - remove(x); - break; - case 3: - std::cout << "\nEnter the element to be searched : "; - std::cin >> x; - search(x); - break; - case 4: - show(); - std::cout << "\n"; - break; - case 5: - std::cout << "The reversed list: \n"; - reverse(); - show(); - std::cout << "\n"; - break; - } - } while (choice != 0); +int main() +{ + int choice, x; + do + { + std::cout << "\n1. Insert"; + std::cout << "\n2. Delete"; + std::cout << "\n3. Search"; + std::cout << "\n4. Print"; + std::cout << "\n5. Reverse"; + std::cout << "\n0. Exit"; + std::cout << "\n\nEnter you choice : "; + std::cin >> choice; + switch (choice) + { + case 1: + std::cout << "\nEnter the element to be inserted : "; + std::cin >> x; + insert(x); + break; + case 2: + std::cout << "\nEnter the element to be removed : "; + std::cin >> x; + remove(x); + break; + case 3: + std::cout << "\nEnter the element to be searched : "; + std::cin >> x; + search(x); + break; + case 4: + show(); + std::cout << "\n"; + break; + case 5: + std::cout << "The reversed list: \n"; + reverse(); + show(); + std::cout << "\n"; + break; + } + } while (choice != 0); - return 0; + return 0; } diff --git a/data_structure/linkedlist_implentation_usingarray.cpp b/data_structure/linkedlist_implentation_usingarray.cpp index 6f8205f27e2..168124f003b 100644 --- a/data_structure/linkedlist_implentation_usingarray.cpp +++ b/data_structure/linkedlist_implentation_usingarray.cpp @@ -1,6 +1,8 @@ -/* The difference between the pointer implementation of linked list and array implementation of linked list: +/* The difference between the pointer implementation of linked list and array + implementation of linked list: 1. The NULL is represented by -1; - 2. Limited size. (in the following case it is 100 nodes at max). But we can reuse the nodes that are to be deleted by again linking it bacj to the list. + 2. Limited size. (in the following case it is 100 nodes at max). But we can + reuse the nodes that are to be deleted by again linking it bacj to the list. */ #include @@ -10,7 +12,7 @@ struct Node int data; int next; }; -Node AvailArray[100]; //array that will act as nodes of a linked list. +Node AvailArray[100]; // array that will act as nodes of a linked list. int head = -1; int avail = 0; void initialise_list() @@ -19,23 +21,28 @@ void initialise_list() { AvailArray[i].next = i + 1; } - AvailArray[99].next = -1; //indicating the end of the linked list. + AvailArray[99].next = -1; // indicating the end of the linked list. } -int getnode() //This will return the index of the first free node present in the avail list +int getnode() // This will return the index of the first free node present in + // the avail list { int NodeIndexToBeReturned = avail; avail = AvailArray[avail].next; return NodeIndexToBeReturned; } -void freeNode(int nodeToBeDeleted) //This function when called will delete the node with the index presented as an argument, and will put back that node into the array. +void freeNode( + int nodeToBeDeleted) // This function when called will delete the node with + // the index presented as an argument, and will put + // back that node into the array. { AvailArray[nodeToBeDeleted].next = avail; avail = nodeToBeDeleted; } -void insertAtTheBeginning(int data) //The function will insert the given data into the front of the linked list. +void insertAtTheBeginning(int data) // The function will insert the given data + // into the front of the linked list. { int newNode = getnode(); AvailArray[newNode].data = data; @@ -51,7 +58,7 @@ void insertAtTheEnd(int data) { temp = AvailArray[temp].next; } - //temp is now pointing to the end node. + // temp is now pointing to the end node. AvailArray[newNode].data = data; AvailArray[newNode].next = -1; AvailArray[temp].next = newNode; @@ -94,7 +101,8 @@ int main() insertAtTheEnd(y); break; case 3: - cout << "The linked list contains the following element in order" << endl; + cout << "The linked list contains the following element in order" + << endl; display(); break; case 4: diff --git a/data_structure/list_array.cpp b/data_structure/list_array.cpp index de984876b09..f572b77b461 100644 --- a/data_structure/list_array.cpp +++ b/data_structure/list_array.cpp @@ -3,186 +3,184 @@ using namespace std; struct list { - int data[50]; - int top = 0; - bool isSorted = false; - - int BinarySearch(int *array, int first, int last, int x) - { - if (last < first) - { - return -1; - } - int mid = (first + last) / 2; - if (array[mid] == x) - return mid; - else if (x < array[mid]) - return (BinarySearch(array, first, mid - 1, x)); - else if (x > array[mid]) - return (BinarySearch(array, mid + 1, last, x)); - } - - int LinarSearch(int *array, int x) - { - for (int i = 0; i < top; i++) - { - if (array[i] == x) - { - return i; - } - } - - return -1; - } - - int Search(int x) - { - int pos = -1; - - if (isSorted) - { - pos = BinarySearch(data, 0, top - 1, x); - } - - else - { - pos = LinarSearch(data, x); - } - - if (pos != -1) - { - cout << "\nElement found at position : " << pos; - } - else - { - cout << "\nElement not found"; - } - return pos; - } - - void Sort() - { - int i, j, pos; - for (i = 0; i < top; i++) - { - int min = data[i]; - for (j = i + 1; j < top; j++) - { - if (data[j] < min) - { - pos = j; - min = data[pos]; - } - } - - int temp = data[i]; - data[i] = data[pos]; - data[pos] = temp; - } - isSorted = true; - } - - void insert(int x) - { - if (!isSorted) - { - - if (top == 49) - { - cout << "\nOverflow"; - } - else - { - data[top] = x; - top++; - } - } - - else - { - int pos = 0; - - for (int i = 0; i < top - 1; i++) - { - if (data[i] <= x && x <= data[i + 1]) - { - pos = i + 1; - break; - } - } - if (pos == 0) - { - pos = top - 1; - } - - for (int i = top; i > pos; i--) - { - data[i] = data[i - 1]; - } - top++; - data[pos] = x; - } - } - - void Remove(int x) - { - int pos = Search(x); - cout << "\n" - << data[pos] << " deleted"; - for (int i = pos; i < top; i++) - { - data[i] = data[i + 1]; - } - top--; - } - - void Show() - { - for (int i = 0; i < top; i++) - { - cout << data[i] << "\t"; - } - } + int data[50]; + int top = 0; + bool isSorted = false; + + int BinarySearch(int *array, int first, int last, int x) + { + if (last < first) + { + return -1; + } + int mid = (first + last) / 2; + if (array[mid] == x) + return mid; + else if (x < array[mid]) + return (BinarySearch(array, first, mid - 1, x)); + else if (x > array[mid]) + return (BinarySearch(array, mid + 1, last, x)); + } + + int LinarSearch(int *array, int x) + { + for (int i = 0; i < top; i++) + { + if (array[i] == x) + { + return i; + } + } + + return -1; + } + + int Search(int x) + { + int pos = -1; + + if (isSorted) + { + pos = BinarySearch(data, 0, top - 1, x); + } + + else + { + pos = LinarSearch(data, x); + } + + if (pos != -1) + { + cout << "\nElement found at position : " << pos; + } + else + { + cout << "\nElement not found"; + } + return pos; + } + + void Sort() + { + int i, j, pos; + for (i = 0; i < top; i++) + { + int min = data[i]; + for (j = i + 1; j < top; j++) + { + if (data[j] < min) + { + pos = j; + min = data[pos]; + } + } + + int temp = data[i]; + data[i] = data[pos]; + data[pos] = temp; + } + isSorted = true; + } + + void insert(int x) + { + if (!isSorted) + { + if (top == 49) + { + cout << "\nOverflow"; + } + else + { + data[top] = x; + top++; + } + } + + else + { + int pos = 0; + + for (int i = 0; i < top - 1; i++) + { + if (data[i] <= x && x <= data[i + 1]) + { + pos = i + 1; + break; + } + } + if (pos == 0) + { + pos = top - 1; + } + + for (int i = top; i > pos; i--) + { + data[i] = data[i - 1]; + } + top++; + data[pos] = x; + } + } + + void Remove(int x) + { + int pos = Search(x); + cout << "\n" << data[pos] << " deleted"; + for (int i = pos; i < top; i++) + { + data[i] = data[i + 1]; + } + top--; + } + + void Show() + { + for (int i = 0; i < top; i++) + { + cout << data[i] << "\t"; + } + } }; int main() { - list L; - int choice; - int x; - do - { - cout << "\n1.Insert"; - cout << "\n2.Delete"; - cout << "\n3.Search"; - cout << "\n4.Sort"; - cout << "\n5.Print"; - cout << "\n\nEnter Your Choice : "; - cin >> choice; - switch (choice) - { - case 1: - cout << "\nEnter the element to be inserted : "; - cin >> x; - L.insert(x); - break; - case 2: - cout << "\nEnter the element to be removed : "; - cin >> x; - L.Remove(x); - break; - case 3: - cout << "\nEnter the element to be searched : "; - cin >> x; - L.Search(x); - break; - case 4: - L.Sort(); - break; - case 5: - L.Show(); - break; - } - } while (choice != 0); - return 0; + list L; + int choice; + int x; + do + { + cout << "\n1.Insert"; + cout << "\n2.Delete"; + cout << "\n3.Search"; + cout << "\n4.Sort"; + cout << "\n5.Print"; + cout << "\n\nEnter Your Choice : "; + cin >> choice; + switch (choice) + { + case 1: + cout << "\nEnter the element to be inserted : "; + cin >> x; + L.insert(x); + break; + case 2: + cout << "\nEnter the element to be removed : "; + cin >> x; + L.Remove(x); + break; + case 3: + cout << "\nEnter the element to be searched : "; + cin >> x; + L.Search(x); + break; + case 4: + L.Sort(); + break; + case 5: + L.Show(); + break; + } + } while (choice != 0); + return 0; } diff --git a/data_structure/morrisinorder.cpp b/data_structure/morrisinorder.cpp index d3a2e9fd724..58f267907f2 100644 --- a/data_structure/morrisinorder.cpp +++ b/data_structure/morrisinorder.cpp @@ -2,107 +2,107 @@ #include /************************** - @author shrutisheoran + @author shrutisheoran **************************/ using namespace std; struct Btree { - int data; - struct Btree *left; //Pointer to left subtree - struct Btree *right; //Pointer to right subtree + int data; + struct Btree *left; // Pointer to left subtree + struct Btree *right; // Pointer to right subtree }; void insert(Btree **root, int d) { - Btree *nn = new Btree(); //Creating new node - nn->data = d; - nn->left = NULL; - nn->right = NULL; - if (*root == NULL) - { - *root = nn; - return; - } - else - { - queue q; - // Adding root node to queue - q.push(*root); - while (!q.empty()) - { - Btree *node = q.front(); - // Removing parent node from queue - q.pop(); - if (node->left) - // Adding left child of removed node to queue - q.push(node->left); - else - { - // Adding new node if no left child is present - node->left = nn; - return; - } - if (node->right) - // Adding right child of removed node to queue - q.push(node->right); - else - { - // Adding new node if no right child is present - node->right = nn; - return; - } - } - } + Btree *nn = new Btree(); // Creating new node + nn->data = d; + nn->left = NULL; + nn->right = NULL; + if (*root == NULL) + { + *root = nn; + return; + } + else + { + queue q; + // Adding root node to queue + q.push(*root); + while (!q.empty()) + { + Btree *node = q.front(); + // Removing parent node from queue + q.pop(); + if (node->left) + // Adding left child of removed node to queue + q.push(node->left); + else + { + // Adding new node if no left child is present + node->left = nn; + return; + } + if (node->right) + // Adding right child of removed node to queue + q.push(node->right); + else + { + // Adding new node if no right child is present + node->right = nn; + return; + } + } + } } void morrisInorder(Btree *root) { - Btree *curr = root; - Btree *temp; - while (curr) - { - if (curr->left == NULL) - { - cout << curr->data << " "; - // If left of current node is NULL then curr is shifted to right - curr = curr->right; - } - else - { - // Left of current node is stored in temp - temp = curr->left; - // Moving to extreme right of temp - while (temp->right && temp->right != curr) - temp = temp->right; - // If extreme right is null it is made to point to currrent node (will be used for backtracking) - if (temp->right == NULL) - { - temp->right = curr; - // current node is made to point its left subtree - curr = curr->left; - } - // If extreme right already points to currrent node it it set to null - else if (temp->right == curr) - { - cout << curr->data << " "; - temp->right = NULL; - // current node is made to point its right subtree - curr = curr->right; - } - } - } + Btree *curr = root; + Btree *temp; + while (curr) + { + if (curr->left == NULL) + { + cout << curr->data << " "; + // If left of current node is NULL then curr is shifted to right + curr = curr->right; + } + else + { + // Left of current node is stored in temp + temp = curr->left; + // Moving to extreme right of temp + while (temp->right && temp->right != curr) temp = temp->right; + // If extreme right is null it is made to point to currrent node + // (will be used for backtracking) + if (temp->right == NULL) + { + temp->right = curr; + // current node is made to point its left subtree + curr = curr->left; + } + // If extreme right already points to currrent node it it set to + // null + else if (temp->right == curr) + { + cout << curr->data << " "; + temp->right = NULL; + // current node is made to point its right subtree + curr = curr->right; + } + } + } } int main() { - // Testing morrisInorder funtion - Btree *root = NULL; - int i; - for (i = 1; i <= 7; i++) - insert(&root, i); - cout << "Morris Inorder: "; - morrisInorder(root); - return 0; + // Testing morrisInorder funtion + Btree *root = NULL; + int i; + for (i = 1; i <= 7; i++) insert(&root, i); + cout << "Morris Inorder: "; + morrisInorder(root); + return 0; } diff --git a/data_structure/queue/queue.cpp b/data_structure/queue/queue.cpp index 728adfc1837..e8ff8966c3e 100644 --- a/data_structure/queue/queue.cpp +++ b/data_structure/queue/queue.cpp @@ -1,6 +1,6 @@ -#include -#include #include "queue.h" +#include +#include using namespace std; @@ -25,11 +25,12 @@ void queue::display() { node *current = queueFront; cout << "Front --> "; - while(current != NULL) { - cout<data<< " "; - current = current -> next; + while (current != NULL) + { + cout << current->data << " "; + current = current->next; } - cout <::enQueue(Kind item) newNode = new node; newNode->data = item; newNode->next = NULL; - if (queueFront == NULL) { + if (queueFront == NULL) + { queueFront = newNode; queueRear = newNode; - } else { + } + else + { queueRear->next = newNode; queueRear = queueRear->next; } @@ -78,13 +82,15 @@ template void queue::deQueue() { node *temp; - if(!isEmptyQueue()) { + if (!isEmptyQueue()) + { temp = queueFront; queueFront = queueFront->next; delete temp; size--; - } else { + } + else + { cout << "Queue is empty !" << endl; } } - diff --git a/data_structure/queue/queue.h b/data_structure/queue/queue.h index 715def1efa1..7e9c44559ca 100644 --- a/data_structure/queue/queue.h +++ b/data_structure/queue/queue.h @@ -14,21 +14,20 @@ struct node template class queue { - public: - void display(); /* Show queue */ - queue(); /* Default constructor*/ - ~queue(); /* Destructor */ - bool isEmptyQueue(); /* Determine whether the queue is empty */ - void enQueue (Kind item); /* Add new item to the queue */ - Kind front(); /* Return the first element of the queue */ - void deQueue(); /* Remove the top element of the queue */ - void clear(); + public: + void display(); /* Show queue */ + queue(); /* Default constructor*/ + ~queue(); /* Destructor */ + bool isEmptyQueue(); /* Determine whether the queue is empty */ + void enQueue(Kind item); /* Add new item to the queue */ + Kind front(); /* Return the first element of the queue */ + void deQueue(); /* Remove the top element of the queue */ + void clear(); - private: - node *queueFront; /* Pointer to the front of the queue */ - node *queueRear; /* Pointer to the rear of the queue */ - int size; + private: + node *queueFront; /* Pointer to the front of the queue */ + node *queueRear; /* Pointer to the rear of the queue */ + int size; }; #endif - diff --git a/data_structure/queue/test_queue.cpp b/data_structure/queue/test_queue.cpp index caf80318cb1..d9308adcb3f 100644 --- a/data_structure/queue/test_queue.cpp +++ b/data_structure/queue/test_queue.cpp @@ -1,22 +1,25 @@ #include #include -#include "queue.h" #include "queue.cpp" +#include "queue.h" using namespace std; int main() { queue q; - cout << "---------------------- Test construct ----------------------" << endl; + cout << "---------------------- Test construct ----------------------" + << endl; q.display(); - cout << "---------------------- Test isEmptyQueue ----------------------" << endl; - if(q.isEmptyQueue()) - cout << "PASS" <> op; - if (op == 1) { + if (op == 1) + { std::cout << "Enter data "; std::cin >> data; ob.enqueue(data); - } else if (op == 2) { + } + else if (op == 2) + { data = ob.dequeue(); std::cout << "\ndequeue element is:\t" << data; - } else if (op == 3) { + } + else if (op == 3) + { ob.display(); - } else if (op == 4) { + } + else if (op == 4) + { exit(0); - } else { + } + else + { std::cout << "\nWrong choice "; } } diff --git a/data_structure/queue_using_array2.cpp b/data_structure/queue_using_array2.cpp index 3b79d06fc05..7e1ada725a4 100644 --- a/data_structure/queue_using_array2.cpp +++ b/data_structure/queue_using_array2.cpp @@ -7,69 +7,68 @@ int rear = 0; void Enque(int x) { - if (rear == 10) - { - cout << "\nOverflow"; - } - else - { - queue[rear++] = x; - } + if (rear == 10) + { + cout << "\nOverflow"; + } + else + { + queue[rear++] = x; + } } void Deque() { - if (front == rear) - { - cout << "\nUnderflow"; - } + if (front == rear) + { + cout << "\nUnderflow"; + } - else - { - cout << "\n" - << queue[front++] << " deleted"; - for (int i = front; i < rear; i++) - { - queue[i - front] = queue[i]; - } - rear = rear - front; - front = 0; - } + else + { + cout << "\n" << queue[front++] << " deleted"; + for (int i = front; i < rear; i++) + { + queue[i - front] = queue[i]; + } + rear = rear - front; + front = 0; + } } void show() { - for (int i = front; i < rear; i++) - { - cout << queue[i] << "\t"; - } + for (int i = front; i < rear; i++) + { + cout << queue[i] << "\t"; + } } int main() { - int ch, x; - do - { - cout << "\n1. Enque"; - cout << "\n2. Deque"; - cout << "\n3. Print"; - cout << "\nEnter Your Choice : "; - cin >> ch; - if (ch == 1) - { - cout << "\nInsert : "; - cin >> x; - Enque(x); - } - else if (ch == 2) - { - Deque(); - } - else if (ch == 3) - { - show(); - } - } while (ch != 0); + int ch, x; + do + { + cout << "\n1. Enque"; + cout << "\n2. Deque"; + cout << "\n3. Print"; + cout << "\nEnter Your Choice : "; + cin >> ch; + if (ch == 1) + { + cout << "\nInsert : "; + cin >> x; + Enque(x); + } + else if (ch == 2) + { + Deque(); + } + else if (ch == 3) + { + show(); + } + } while (ch != 0); - return 0; + return 0; } diff --git a/data_structure/queue_using_linked_list.cpp b/data_structure/queue_using_linked_list.cpp index 39d7a9ae376..9ddbdaa423e 100644 --- a/data_structure/queue_using_linked_list.cpp +++ b/data_structure/queue_using_linked_list.cpp @@ -22,7 +22,6 @@ void Enque(int x) else { - node *n = new node; n->val = x; n->next = NULL; @@ -40,8 +39,7 @@ void Deque() else { node *t = front; - cout << "\n" - << t->val << " deleted"; + cout << "\n" << t->val << " deleted"; front = front->next; delete t; if (front == NULL) diff --git a/data_structure/queue_using_linkedlist.cpp b/data_structure/queue_using_linkedlist.cpp index 8bc130c27c8..21ff0cfcfd0 100644 --- a/data_structure/queue_using_linkedlist.cpp +++ b/data_structure/queue_using_linkedlist.cpp @@ -1,98 +1,99 @@ /* Write a program to implement Queue using linkedlist. */ -#include - - -struct linkedlist{ - int data; - linkedlist *next; +#include +struct linkedlist +{ + int data; + linkedlist *next; }; -class stack_linkedList{ - public: +class stack_linkedList +{ + public: linkedlist *front; linkedlist *rear; - - stack_linkedList(){ - front=rear=NULL; - } + + stack_linkedList() { front = rear = NULL; } void enqueue(int); int dequeue(); void display(); - }; -void stack_linkedList::enqueue(int ele){ - - linkedlist *temp=new linkedlist(); - temp->data=ele; - temp->next=NULL; +void stack_linkedList::enqueue(int ele) +{ + linkedlist *temp = new linkedlist(); + temp->data = ele; + temp->next = NULL; - if(front==NULL) - front=rear=temp; - else{ - rear->next=temp; - rear=temp; + if (front == NULL) + front = rear = temp; + else + { + rear->next = temp; + rear = temp; } } -int stack_linkedList::dequeue(){ +int stack_linkedList::dequeue() +{ linkedlist *temp; int ele; - if(front==NULL) - std::cout<<"\nStack is empty"; - else{ - temp=front; - ele=temp->data; - if(front==rear) //if length of queue is 1; - rear=rear->next; - front=front->next; - delete(temp); + if (front == NULL) + std::cout << "\nStack is empty"; + else + { + temp = front; + ele = temp->data; + if (front == rear) // if length of queue is 1; + rear = rear->next; + front = front->next; + delete (temp); } return ele; } -void stack_linkedList::display(){ - - if(front==NULL) - std::cout<<"\nStack is empty"; - - else { - +void stack_linkedList::display() +{ + if (front == NULL) + std::cout << "\nStack is empty"; + + else + { linkedlist *temp; - temp=front; - while(temp!=NULL){ - std::cout<data<<" "; - temp=temp->next; + temp = front; + while (temp != NULL) + { + std::cout << temp->data << " "; + temp = temp->next; } } } -int main(){ - - int op,data; +int main() +{ + int op, data; stack_linkedList ob; - std::cout<<"\n1. enqueue(Insertion) "; - std::cout<<"\n2. dequeue(Deletion)"; - std::cout<<"\n3. Display"; - std::cout<<"\n4. Exit"; - - while(1){ - std::cout<<"\nEnter your choice "; - std::cin>>op; - if(op==1) + std::cout << "\n1. enqueue(Insertion) "; + std::cout << "\n2. dequeue(Deletion)"; + std::cout << "\n3. Display"; + std::cout << "\n4. Exit"; + + while (1) + { + std::cout << "\nEnter your choice "; + std::cin >> op; + if (op == 1) { - std::cout<<"Enter data "; - std::cin>>data; + std::cout << "Enter data "; + std::cin >> data; ob.enqueue(data); } - else if(op==2) - data=ob.dequeue(); - else if(op==3) + else if (op == 2) + data = ob.dequeue(); + else if (op == 3) ob.display(); - else if(op==4) + else if (op == 4) exit(0); else - std::cout<<"\nWrong choice "; - + std::cout << "\nWrong choice "; } return 0; } diff --git a/data_structure/stack_using_array.cpp b/data_structure/stack_using_array.cpp index af1d57c464f..dd0709ff27a 100644 --- a/data_structure/stack_using_array.cpp +++ b/data_structure/stack_using_array.cpp @@ -6,74 +6,70 @@ int top = 0, size; void push(int x) { - if (top == size) - { - cout << "\nOverflow"; - } - else - { - stack[top++] = x; - } + if (top == size) + { + cout << "\nOverflow"; + } + else + { + stack[top++] = x; + } } void pop() { - if (top == 0) - { - cout << "\nUnderflow"; - } - else - { - cout << "\n" - << stack[--top] << " deleted"; - } + if (top == 0) + { + cout << "\nUnderflow"; + } + else + { + cout << "\n" << stack[--top] << " deleted"; + } } void show() { - for (int i = 0; i < top; i++) - { - cout << stack[i] << "\n"; - } + for (int i = 0; i < top; i++) + { + cout << stack[i] << "\n"; + } } -void topmost() -{ - cout << "\nTopmost element: " << stack[top - 1]; -} +void topmost() { cout << "\nTopmost element: " << stack[top - 1]; } int main() { - cout << "\nEnter Size of stack : "; - cin >> size; - stack = new int[size]; - int ch, x; - do - { - cout << "\n1. Push"; - cout << "\n2. Pop"; - cout << "\n3. Print"; - cout << "\n4. Print topmost element:"; - cout << "\nEnter Your Choice : "; - cin >> ch; - if (ch == 1) - { - cout << "\nInsert : "; - cin >> x; - push(x); - } - else if (ch == 2) - { - pop(); - } - else if (ch == 3) - { - show(); - } - else if (ch == 4) - { - topmost(); - } - } while (ch != 0); + cout << "\nEnter Size of stack : "; + cin >> size; + stack = new int[size]; + int ch, x; + do + { + cout << "\n1. Push"; + cout << "\n2. Pop"; + cout << "\n3. Print"; + cout << "\n4. Print topmost element:"; + cout << "\nEnter Your Choice : "; + cin >> ch; + if (ch == 1) + { + cout << "\nInsert : "; + cin >> x; + push(x); + } + else if (ch == 2) + { + pop(); + } + else if (ch == 3) + { + show(); + } + else if (ch == 4) + { + topmost(); + } + } while (ch != 0); - return 0; + return 0; } diff --git a/data_structure/stack_using_linked_list.cpp b/data_structure/stack_using_linked_list.cpp index 6925cf10cf4..89a15fe39c9 100644 --- a/data_structure/stack_using_linked_list.cpp +++ b/data_structure/stack_using_linked_list.cpp @@ -3,71 +3,70 @@ using namespace std; struct node { - int val; - node *next; + int val; + node *next; }; node *top; void push(int x) { - node *n = new node; - n->val = x; - n->next = top; - top = n; + node *n = new node; + n->val = x; + n->next = top; + top = n; } void pop() { - if (top == NULL) - { - cout << "\nUnderflow"; - } - else - { - node *t = top; - cout << "\n" - << t->val << " deleted"; - top = top->next; - delete t; - } + if (top == NULL) + { + cout << "\nUnderflow"; + } + else + { + node *t = top; + cout << "\n" << t->val << " deleted"; + top = top->next; + delete t; + } } void show() { - node *t = top; - while (t != NULL) - { - cout << t->val << "\n"; - t = t->next; - } + node *t = top; + while (t != NULL) + { + cout << t->val << "\n"; + t = t->next; + } } int main() { - int ch, x; - do - { - cout << "\n1. Push"; - cout << "\n2. Pop"; - cout << "\n3. Print"; - cout << "\nEnter Your Choice : "; - cin >> ch; - if (ch == 1) - { - cout << "\nInsert : "; - cin >> x; - push(x); - } - else if (ch == 2) - { - pop(); - } - else if (ch == 3) - { - show(); - } - } while (ch != 0); + int ch, x; + do + { + cout << "\n1. Push"; + cout << "\n2. Pop"; + cout << "\n3. Print"; + cout << "\nEnter Your Choice : "; + cin >> ch; + if (ch == 1) + { + cout << "\nInsert : "; + cin >> x; + push(x); + } + else if (ch == 2) + { + pop(); + } + else if (ch == 3) + { + show(); + } + } while (ch != 0); - return 0; + return 0; } diff --git a/data_structure/stk/main.cpp b/data_structure/stk/main.cpp index 2d6bbec5617..ceac2ac8a4a 100644 --- a/data_structure/stk/main.cpp +++ b/data_structure/stk/main.cpp @@ -8,18 +8,19 @@ * ./main student.txt ************************************************************ * */ -#include -#include +#include #include +#include +#include #include -#include -#include "stack.h" #include "stack.cpp" +#include "stack.h" using namespace std; -int main(int argc, char * argv[]) { +int main(int argc, char* argv[]) +{ double GPA; double highestGPA; string name; @@ -34,19 +35,24 @@ int main(int argc, char * argv[]) { infile >> GPA >> name; highestGPA = GPA; - while (infile) { - if (GPA > highestGPA) { + while (infile) + { + if (GPA > highestGPA) + { stk.clear(); stk.push(name); highestGPA = GPA; - } else if (GPA == highestGPA) { + } + else if (GPA == highestGPA) + { stk.push(name); } infile >> GPA >> name; } - cout << "Highest GPA: " << highestGPA < -#include #include "stack.h" +#include +#include using namespace std; @@ -24,11 +24,12 @@ void stack::display() { node *current = stackTop; cout << "Top --> "; - while(current != NULL) { - cout<data<< " "; - current = current -> next; + while (current != NULL) + { + cout << current->data << " "; + current = current->next; } - cout < void stack::pop() { node *temp; - if(!isEmptyStack()) { + if (!isEmptyStack()) + { temp = stackTop; stackTop = stackTop->next; delete temp; size--; - } else { + } + else + { cout << "Stack is empty !" << endl; } } /* Operator "=" */ template -stack stack::operator=(stack & otherStack) +stack stack::operator=(stack &otherStack) { node *newNode, *current, *last; @@ -91,13 +95,14 @@ stack stack::operator=(stack & otherStack) stackTop = NULL; if (otherStack.stackTop == NULL) stackTop = NULL; - else { + else + { current = otherStack.stackTop; stackTop = new node; stackTop->data = current->data; stackTop->next = NULL; last = stackTop; - current = current ->next; + current = current->next; /* Copy the remaining stack */ while (current != NULL) { diff --git a/data_structure/stk/stack.h b/data_structure/stk/stack.h index a9366948216..39b455ac0f4 100644 --- a/data_structure/stk/stack.h +++ b/data_structure/stk/stack.h @@ -14,22 +14,21 @@ struct node template class stack { - public: - void display(); /* Show stack */ - stack(); /* Default constructor*/ - ~stack(); /* Destructor */ - bool isEmptyStack(); /* Determine whether the stack is empty */ - void push (Type item); /* Add new item to the stack */ - Type top(); /* Return the top element of the stack */ - void pop(); /* Remove the top element of the stack */ - void clear(); + public: + void display(); /* Show stack */ + stack(); /* Default constructor*/ + ~stack(); /* Destructor */ + bool isEmptyStack(); /* Determine whether the stack is empty */ + void push(Type item); /* Add new item to the stack */ + Type top(); /* Return the top element of the stack */ + void pop(); /* Remove the top element of the stack */ + void clear(); - stack operator=(stack & otherStack); - // Overload "=" the assignment operator. - private: - node *stackTop; /* Pointer to the stack */ - int size; + stack operator=(stack &otherStack); + // Overload "=" the assignment operator. + private: + node *stackTop; /* Pointer to the stack */ + int size; }; #endif - diff --git a/data_structure/stk/test_stack.cpp b/data_structure/stk/test_stack.cpp index 4703fc906ae..8839fdfa350 100644 --- a/data_structure/stk/test_stack.cpp +++ b/data_structure/stk/test_stack.cpp @@ -1,21 +1,23 @@ #include -#include "stack.h" #include "stack.cpp" +#include "stack.h" using namespace std; int main() { stack stk; - cout << "---------------------- Test construct ----------------------" << endl; + cout << "---------------------- Test construct ----------------------" + << endl; stk.display(); - cout << "---------------------- Test isEmptyStack ----------------------" << endl; - if(stk.isEmptyStack()) - cout << "PASS" < stk1; - cout << "stk current: "<< endl; + cout << "stk current: " << endl; stk.display(); - cout << endl << "Assign stk1 = stk "<< endl; + cout << endl << "Assign stk1 = stk " << endl; stk1 = stk; stk1.display(); - cout << endl<< "After pushing 8 9 10 into stk1:" <val << " : "; - cin >> ch; - if (ch == 'l') - CreateTree(n, n->left, x, ch); - else if (ch == 'r') - CreateTree(n, n->right, x, ch); + cout << "\nLeft or Right of " << n->val << " : "; + cin >> ch; + if (ch == 'l') + CreateTree(n, n->left, x, ch); + else if (ch == 'r') + CreateTree(n, n->right, x, ch); } else { @@ -40,19 +40,19 @@ void CreateTree(node *curr, node *n, int x, char pos) void BFT(node *n) { - list queue; + list queue; queue.push_back(n); - while(!queue.empty()) + while (!queue.empty()) { n = queue.front(); cout << n->val << " "; queue.pop_front(); - if(n->left != NULL) + if (n->left != NULL) queue.push_back(n->left); - if(n->right != NULL) + if (n->right != NULL) queue.push_back(n->right); } } diff --git a/data_structure/trie_tree.cpp b/data_structure/trie_tree.cpp index 2b84099e89b..d34dd2dbc29 100644 --- a/data_structure/trie_tree.cpp +++ b/data_structure/trie_tree.cpp @@ -1,86 +1,99 @@ -#include #include +#include #include #include // structure definition -typedef struct trie { - struct trie * arr[26]; +typedef struct trie +{ + struct trie* arr[26]; bool isEndofWord; } trie; // create a new node for trie -trie * createNode() { - trie * nn = new trie(); - for (int i = 0; i < 26; i++) - nn -> arr[i] = NULL; - nn -> isEndofWord = false; +trie* createNode() +{ + trie* nn = new trie(); + for (int i = 0; i < 26; i++) nn->arr[i] = NULL; + nn->isEndofWord = false; return nn; } // insert string into the trie -void insert(trie * root, std::string str) { - for (int i = 0; i < str.length(); i++) { +void insert(trie* root, std::string str) +{ + for (int i = 0; i < str.length(); i++) + { int j = str[i] - 'a'; - if (root -> arr[j]) { - root = root -> arr[j]; - } else { - root -> arr[j] = createNode(); - root = root -> arr[j]; + if (root->arr[j]) + { + root = root->arr[j]; + } + else + { + root->arr[j] = createNode(); + root = root->arr[j]; } } - root -> isEndofWord = true; + root->isEndofWord = true; } // search a string exists inside the trie -bool search(trie * root, std::string str, int index) { - if (index == str.length()) { - if (!root -> isEndofWord) +bool search(trie* root, std::string str, int index) +{ + if (index == str.length()) + { + if (!root->isEndofWord) return false; return true; } int j = str[index] - 'a'; - if (!root -> arr[j]) + if (!root->arr[j]) return false; - return search(root -> arr[j], str, index + 1); + return search(root->arr[j], str, index + 1); } /* -removes the string if it is not a prefix of any other -string, if it is then just sets the endofword to false, else +removes the string if it is not a prefix of any other +string, if it is then just sets the endofword to false, else removes the given string */ -bool deleteString(trie * root, std::string str, int index) { - if (index == str.length()) { - if (!root -> isEndofWord) - return false; - root -> isEndofWord = false; - for (int i = 0; i < 26; i++) +bool deleteString(trie* root, std::string str, int index) +{ + if (index == str.length()) + { + if (!root->isEndofWord) return false; + root->isEndofWord = false; + for (int i = 0; i < 26; i++) return false; return true; } int j = str[index] - 'a'; - if (!root -> arr[j]) + if (!root->arr[j]) return false; - bool - var = deleteString(root, str, index + 1); - if (var) { - root -> arr[j] = NULL; - if (root -> isEndofWord) { + bool var = deleteString(root, str, index + 1); + if (var) + { + root->arr[j] = NULL; + if (root->isEndofWord) + { return false; - } else { + } + else + { int i; for (i = 0; i < 26; i++) - if (root -> arr[i]) + if (root->arr[i]) return false; return true; } } } -int main() { - trie * root = createNode(); +int main() +{ + trie* root = createNode(); insert(root, "hello"); insert(root, "world"); int a = search(root, "hello", 0); diff --git a/dynamic_programming/0_1_knapsack.cpp b/dynamic_programming/0_1_knapsack.cpp index 9348372b210..0ce40ca0a99 100644 --- a/dynamic_programming/0_1_knapsack.cpp +++ b/dynamic_programming/0_1_knapsack.cpp @@ -1,9 +1,9 @@ -//0-1 Knapsack problem - Dynamic programming +// 0-1 Knapsack problem - Dynamic programming //#include #include using namespace std; -//void Print(int res[20][20], int i, int j, int capacity) +// void Print(int res[20][20], int i, int j, int capacity) //{ // if(i==0 || j==0) // { @@ -30,42 +30,43 @@ using namespace std; int Knapsack(int capacity, int n, int weight[], int value[]) { - int res[20][20]; - for (int i = 0; i < n + 1; ++i) - { - for (int j = 0; j < capacity + 1; ++j) - { - if (i == 0 || j == 0) - res[i][j] = 0; - else if (weight[i - 1] <= j) - res[i][j] = max(value[i - 1] + res[i - 1][j - weight[i - 1]], res[i - 1][j]); - else - res[i][j] = res[i - 1][j]; - } - } - // Print(res, n, capacity, capacity); - // cout<<"\n"; - return res[n][capacity]; + int res[20][20]; + for (int i = 0; i < n + 1; ++i) + { + for (int j = 0; j < capacity + 1; ++j) + { + if (i == 0 || j == 0) + res[i][j] = 0; + else if (weight[i - 1] <= j) + res[i][j] = max(value[i - 1] + res[i - 1][j - weight[i - 1]], + res[i - 1][j]); + else + res[i][j] = res[i - 1][j]; + } + } + // Print(res, n, capacity, capacity); + // cout<<"\n"; + return res[n][capacity]; } int main() { - int n; - cout << "Enter number of items: "; - cin >> n; - int weight[n], value[n]; - cout << "Enter weights: "; - for (int i = 0; i < n; ++i) - { - cin >> weight[i]; - } - cout << "Enter values: "; - for (int i = 0; i < n; ++i) - { - cin >> value[i]; - } - int capacity; - cout << "Enter capacity: "; - cin >> capacity; - cout << Knapsack(capacity, n, weight, value); - return 0; + int n; + cout << "Enter number of items: "; + cin >> n; + int weight[n], value[n]; + cout << "Enter weights: "; + for (int i = 0; i < n; ++i) + { + cin >> weight[i]; + } + cout << "Enter values: "; + for (int i = 0; i < n; ++i) + { + cin >> value[i]; + } + int capacity; + cout << "Enter capacity: "; + cin >> capacity; + cout << Knapsack(capacity, n, weight, value); + return 0; } diff --git a/dynamic_programming/armstrong_number.cpp b/dynamic_programming/armstrong_number.cpp index 4dba89a27f8..218d6365d1a 100644 --- a/dynamic_programming/armstrong_number.cpp +++ b/dynamic_programming/armstrong_number.cpp @@ -1,21 +1,23 @@ // Program to check whether a number is an armstrong number or not #include -using std::cout; using std::cin; +using std::cout; -int main() { - int n, k, d, s = 0; - cout << "Enter a number:"; - cin >> n; - k = n; - while (k != 0) { - d = k % 10; - s += d * d * d; - k /= 10; - } - if (s == n) - cout << n << "is an armstrong number"; - else - cout << n << "is not an armstrong number"; +int main() +{ + int n, k, d, s = 0; + cout << "Enter a number:"; + cin >> n; + k = n; + while (k != 0) + { + d = k % 10; + s += d * d * d; + k /= 10; + } + if (s == n) + cout << n << "is an armstrong number"; + else + cout << n << "is not an armstrong number"; } diff --git a/dynamic_programming/bellman_ford.cpp b/dynamic_programming/bellman_ford.cpp index 7c36d96df4a..85d3bff0619 100644 --- a/dynamic_programming/bellman_ford.cpp +++ b/dynamic_programming/bellman_ford.cpp @@ -1,128 +1,129 @@ -#include #include +#include using namespace std; -//Wrapper class for storing an edge +// Wrapper class for storing an edge class Edge { -public: - int src, dst, weight; + public: + int src, dst, weight; }; -//Wrapper class for storing a graph +// Wrapper class for storing a graph class Graph { -public: - int vertexNum, edgeNum; - 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)); - } - - //Adds the given edge to the graph - void addEdge(int src, int dst, int weight) - { - static int edgeInd = 0; - if (edgeInd < this->edgeNum) - { - Edge newEdge; - newEdge.src = src; - newEdge.dst = dst; - newEdge.weight = weight; - this->edges[edgeInd++] = newEdge; - } - } + public: + int vertexNum, edgeNum; + 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)); + } + + // Adds the given edge to the graph + void addEdge(int src, int dst, int weight) + { + static int edgeInd = 0; + if (edgeInd < this->edgeNum) + { + Edge newEdge; + newEdge.src = src; + newEdge.dst = dst; + newEdge.weight = weight; + this->edges[edgeInd++] = newEdge; + } + } }; -//Utility function to print distances +// Utility function to print distances void print(int dist[], int V) { - cout << "\nVertex Distance" << endl; - for (int i = 0; i < V; i++) - { - if (dist[i] != INT_MAX) - cout << i << "\t" << dist[i] << endl; - else - cout << i << "\tINF" << endl; - } + cout << "\nVertex Distance" << endl; + for (int i = 0; i < V; i++) + { + if (dist[i] != INT_MAX) + cout << i << "\t" << dist[i] << endl; + else + cout << i << "\tINF" << endl; + } } -//The main function that finds the shortest path from given source -//to all other vertices using Bellman-Ford.It also detects negative -//weight cycle +// The main function that finds the shortest path from given source +// to all other vertices using Bellman-Ford.It also detects negative +// weight cycle void BellmanFord(Graph graph, int src) { - int V = graph.vertexNum; - int E = graph.edgeNum; - int dist[V]; - - //Initialize distances array as INF for all except source - //Intialize source as zero - for (int i = 0; i < V; i++) - dist[i] = INT_MAX; - dist[src] = 0; - - //Calculate shortest path distance from source to all edges - //A path can contain maximum (|V|-1) edges - for (int i = 0; i <= V - 1; i++) - for (int j = 0; j < E; j++) - { - int u = graph.edges[j].src; - int v = graph.edges[j].dst; - int w = graph.edges[j].weight; - - if (dist[u] != INT_MAX && dist[u] + w < dist[v]) - dist[v] = dist[u] + w; - } - - //Iterate inner loop once more to check for negative cycle - for (int j = 0; j < E; j++) - { - int u = graph.edges[j].src; - int v = graph.edges[j].dst; - int w = graph.edges[j].weight; - - if (dist[u] != INT_MAX && dist[u] + w < dist[v]) - { - cout << "Graph contains negative weight cycle. Hence, shortest distance not guaranteed." << endl; - return; - } - } - - print(dist, V); - - return; + int V = graph.vertexNum; + int E = graph.edgeNum; + int dist[V]; + + // Initialize distances array as INF for all except source + // Intialize source as zero + for (int i = 0; i < V; i++) dist[i] = INT_MAX; + dist[src] = 0; + + // Calculate shortest path distance from source to all edges + // A path can contain maximum (|V|-1) edges + for (int i = 0; i <= V - 1; i++) + for (int j = 0; j < E; j++) + { + int u = graph.edges[j].src; + int v = graph.edges[j].dst; + int w = graph.edges[j].weight; + + if (dist[u] != INT_MAX && dist[u] + w < dist[v]) + dist[v] = dist[u] + w; + } + + // Iterate inner loop once more to check for negative cycle + for (int j = 0; j < E; j++) + { + int u = graph.edges[j].src; + int v = graph.edges[j].dst; + int w = graph.edges[j].weight; + + if (dist[u] != INT_MAX && dist[u] + w < dist[v]) + { + cout << "Graph contains negative weight cycle. Hence, shortest " + "distance not guaranteed." + << endl; + return; + } + } + + print(dist, V); + + return; } -//Driver Function +// Driver Function int main() { - int V, E, gsrc; - int src, dst, weight; - cout << "Enter number of vertices: "; - cin >> V; - cout << "Enter number of edges: "; - cin >> E; - Graph G(V, E); - for (int i = 0; i < E; i++) - { - cout << "\nEdge " << i + 1 << "\nEnter source: "; - cin >> src; - cout << "Enter destination: "; - cin >> dst; - cout << "Enter weight: "; - cin >> weight; - G.addEdge(src, dst, weight); - } - cout << "\nEnter source: "; - cin >> gsrc; - BellmanFord(G, gsrc); - - return 0; + int V, E, gsrc; + int src, dst, weight; + cout << "Enter number of vertices: "; + cin >> V; + cout << "Enter number of edges: "; + cin >> E; + Graph G(V, E); + for (int i = 0; i < E; i++) + { + cout << "\nEdge " << i + 1 << "\nEnter source: "; + cin >> src; + cout << "Enter destination: "; + cin >> dst; + cout << "Enter weight: "; + cin >> weight; + G.addEdge(src, dst, weight); + } + cout << "\nEnter source: "; + cin >> gsrc; + BellmanFord(G, gsrc); + + return 0; } diff --git a/dynamic_programming/catalan_numbers.cpp b/dynamic_programming/catalan_numbers.cpp index 4d73cd51a2e..0107b9f20f8 100644 --- a/dynamic_programming/catalan_numbers.cpp +++ b/dynamic_programming/catalan_numbers.cpp @@ -9,7 +9,7 @@ #include using namespace std; -int *cat; // global array to hold catalan numbers +int *cat; // global array to hold catalan numbers unsigned long int catalan_dp(int n) { @@ -33,7 +33,7 @@ unsigned long int catalan_dp(int n) { cat[i] = 0; for (int j = 0; j < i; j++) - cat[i] += cat[j] * cat[i - j - 1]; // applying the definition here + cat[i] += cat[j] * cat[i - j - 1]; // applying the definition here } // Return the result diff --git a/dynamic_programming/coin_change.cpp b/dynamic_programming/coin_change.cpp index c8acad48e4f..f43d4fa18d0 100644 --- a/dynamic_programming/coin_change.cpp +++ b/dynamic_programming/coin_change.cpp @@ -1,50 +1,52 @@ -#include #include +#include 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]; - - // 0 coins are needed for 0 sum - - dp[0] = 0; - - for (int i = 1; i <= N; i++) - { - // initialize minimum number of coins needed to infinity - dp[i] = INT_MAX; - int res = INT_MAX; - - // do for each coin - for (int c = 0; c < n; c++) - { - if (i - arr[c] >= 0) // check if coins doesn't become negative by including it - res = dp[i - arr[c]]; - - // if total can be reached by including current coin c, - // update minimum number of coins needed dp[i] - if (res != INT_MAX) - dp[i] = min(dp[i], res + 1); - } - } - - // The Minimum No of Coins Required for N = dp[N] - return dp[N]; + // dp[i] = no of coins required to get a total of i + int dp[N + 1]; + + // 0 coins are needed for 0 sum + + dp[0] = 0; + + for (int i = 1; i <= N; i++) + { + // initialize minimum number of coins needed to infinity + dp[i] = INT_MAX; + int res = INT_MAX; + + // do for each coin + for (int c = 0; c < n; c++) + { + if (i - arr[c] >= + 0) // check if coins doesn't become negative by including it + res = dp[i - arr[c]]; + + // if total can be reached by including current coin c, + // update minimum number of coins needed dp[i] + if (res != INT_MAX) + dp[i] = min(dp[i], res + 1); + } + } + + // The Minimum No of Coins Required for N = dp[N] + return dp[N]; } int main() { - // No of Coins We Have - int arr[] = {1, 2, 3, 4}; - int n = sizeof(arr) / sizeof(arr[0]); + // No of Coins We Have + int arr[] = {1, 2, 3, 4}; + int n = sizeof(arr) / sizeof(arr[0]); - // Total Change Required - int N = 15; + // Total Change Required + int N = 15; - cout << "Minimum Number of Coins Required " << findMinCoins(arr, n, N) << "\n"; + cout << "Minimum Number of Coins Required " << findMinCoins(arr, n, N) + << "\n"; - return 0; + return 0; } \ No newline at end of file diff --git a/dynamic_programming/cut_rod.cpp b/dynamic_programming/cut_rod.cpp index afca3dced8b..3df0a9fbe6d 100644 --- a/dynamic_programming/cut_rod.cpp +++ b/dynamic_programming/cut_rod.cpp @@ -1,6 +1,6 @@ -/*Given a rod of length n inches and an array of prices that -contains prices of all pieces of size smaller than n. Determine -the maximum value obtainable by cutting up the rod and selling +/*Given a rod of length n inches and an array of prices that +contains prices of all pieces of size smaller than n. Determine +the maximum value obtainable by cutting up the rod and selling the pieces.*/ #include @@ -22,7 +22,8 @@ int cutrod(int p[], int n) } int main() { - int price[] = {1, 5, 8, 9, 10, 17, 17, 20, 24, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50}; + int price[] = {1, 5, 8, 9, 10, 17, 17, 20, 24, 30, 31, 32, 33, 34, 35, + 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50}; cout << cutrod(price, 30); return 0; } diff --git a/dynamic_programming/edit_distance.cpp b/dynamic_programming/edit_distance.cpp index 996d3272c7e..da613b23832 100644 --- a/dynamic_programming/edit_distance.cpp +++ b/dynamic_programming/edit_distance.cpp @@ -7,7 +7,7 @@ * a. Insert * b. Remove * c. Replace - * All of the above operations are + * All of the above operations are * of equal cost */ @@ -15,10 +15,7 @@ #include using namespace std; -int min(int x, int y, int z) -{ - return min(min(x, y), z); -} +int min(int x, int y, int z) { return min(min(x, y), z); } /* A Naive recursive C++ program to find * minimum number of operations to convert @@ -32,14 +29,14 @@ int editDist(string str1, string str2, int m, int n) if (n == 0) return m; - //If last characters are same then continue - //for the rest of them. + // If last characters are same then continue + // for the rest of them. if (str1[m - 1] == str2[n - 1]) return editDist(str1, str2, m - 1, n - 1); - //If last not same, then 3 possibilities - //a.Insert b.Remove c. Replace - //Get min of three and continue for rest. + // If last not same, then 3 possibilities + // a.Insert b.Remove c. Replace + // Get min of three and continue for rest. return 1 + min(editDist(str1, str2, m, n - 1), editDist(str1, str2, m - 1, n), editDist(str1, str2, m - 1, n - 1)); @@ -50,31 +47,30 @@ int editDist(string str1, string str2, int m, int n) */ int editDistDP(string str1, string str2, int m, int n) { - - //Create Table for SubProblems + // Create Table for SubProblems int dp[m + 1][n + 1]; - //Fill d[][] in bottom up manner + // Fill d[][] in bottom up manner for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { - //If str1 empty. Then add all of str2 + // If str1 empty. Then add all of str2 if (i == 0) dp[i][j] = j; - //If str2 empty. Then add all of str1 + // If str2 empty. Then add all of str1 else if (j == 0) dp[i][j] = i; - //If character same. Recur for remaining + // If character same. Recur for remaining else if (str1[i - 1] == str2[j - 1]) dp[i][j] = dp[i - 1][j - 1]; else - dp[i][j] = 1 + min(dp[i][j - 1], //Insert - dp[i - 1][j], //Remove - dp[i - 1][j - 1] //Replace + dp[i][j] = 1 + min(dp[i][j - 1], // Insert + dp[i - 1][j], // Remove + dp[i - 1][j - 1] // Replace ); } } diff --git a/dynamic_programming/egg_dropping_puzzle.cpp b/dynamic_programming/egg_dropping_puzzle.cpp index a441f29cbdf..79de4cc22fd 100644 --- a/dynamic_programming/egg_dropping_puzzle.cpp +++ b/dynamic_programming/egg_dropping_puzzle.cpp @@ -1,9 +1,9 @@ -/* Function to get minimun number of trials needed - * in worst case with n eggs and k floors +/* Function to get minimun number of trials needed + * in worst case with n eggs and k floors */ -#include #include +#include using namespace std; int eggDrop(int n, int k) @@ -13,8 +13,8 @@ int eggDrop(int n, int k) for (int i = 1; i <= n; i++) { - eggFloor[i][1] = 1; //n eggs..1 Floor - eggFloor[i][0] = 0; //n eggs..0 Floor + eggFloor[i][1] = 1; // n eggs..1 Floor + eggFloor[i][0] = 0; // n eggs..0 Floor } // Only one egg available diff --git a/dynamic_programming/fibonacci_bottom_up.cpp b/dynamic_programming/fibonacci_bottom_up.cpp index ab5b5b41f2a..3a9669fa9c1 100644 --- a/dynamic_programming/fibonacci_bottom_up.cpp +++ b/dynamic_programming/fibonacci_bottom_up.cpp @@ -2,23 +2,23 @@ using namespace std; int fib(int n) { - int res[3]; - res[0] = 0; - res[1] = 1; - for (int i = 2; i <= n; i++) - { - res[2] = res[1] + res[0]; - res[0] = res[1]; - res[1] = res[2]; - } - return res[1]; + int res[3]; + res[0] = 0; + res[1] = 1; + for (int i = 2; i <= n; i++) + { + res[2] = res[1] + res[0]; + res[0] = res[1]; + res[1] = res[2]; + } + return res[1]; } int main(int argc, char const *argv[]) { - int n; - cout << "Enter n: "; - cin >> n; - cout << "Fibonacci number is "; - cout << fib(n) << endl; - return 0; + int n; + cout << "Enter n: "; + cin >> n; + cout << "Fibonacci number is "; + cout << fib(n) << endl; + return 0; } diff --git a/dynamic_programming/fibonacci_top_down.cpp b/dynamic_programming/fibonacci_top_down.cpp index 9d76366f783..3ac3fdb40a0 100644 --- a/dynamic_programming/fibonacci_top_down.cpp +++ b/dynamic_programming/fibonacci_top_down.cpp @@ -3,24 +3,24 @@ using namespace std; int arr[1000000]; int fib(int n) { - if (arr[n] == -1) - { - if (n <= 1) - arr[n] = n; - else - arr[n] = fib(n - 1) + fib(n - 2); - } - return arr[n]; + if (arr[n] == -1) + { + if (n <= 1) + arr[n] = n; + else + arr[n] = fib(n - 1) + fib(n - 2); + } + return arr[n]; } int main(int argc, char const *argv[]) { - int n; - cout << "Enter n: "; - cin >> n; - for (int i = 0; i < n + 1; ++i) - { - arr[i] = -1; - } - cout << "Fibonacci number is " << fib(n) << endl; - return 0; + int n; + cout << "Enter n: "; + cin >> n; + for (int i = 0; i < n + 1; ++i) + { + arr[i] = -1; + } + cout << "Fibonacci number is " << fib(n) << endl; + return 0; } \ No newline at end of file diff --git a/dynamic_programming/floyd_warshall.cpp b/dynamic_programming/floyd_warshall.cpp index 93ccff62f38..e3b0c66d3b6 100644 --- a/dynamic_programming/floyd_warshall.cpp +++ b/dynamic_programming/floyd_warshall.cpp @@ -1,112 +1,110 @@ -#include #include #include +#include using namespace std; -//Wrapper class for storing a graph +// Wrapper class for storing a graph class Graph { -public: - int vertexNum; - int **edges; - - //Constructs a graph with V vertices and E edges - Graph(int V) - { - this->vertexNum = V; - this->edges = (int **)malloc(V * sizeof(int *)); - for (int i = 0; i < V; i++) - { - this->edges[i] = (int *)malloc(V * sizeof(int)); - for (int j = 0; j < V; j++) - this->edges[i][j] = INT_MAX; - this->edges[i][i] = 0; - } - } - - //Adds the given edge to the graph - void addEdge(int src, int dst, int weight) - { - this->edges[src][dst] = weight; - } + public: + int vertexNum; + int **edges; + + // Constructs a graph with V vertices and E edges + Graph(int V) + { + this->vertexNum = V; + this->edges = (int **)malloc(V * sizeof(int *)); + for (int i = 0; i < V; i++) + { + this->edges[i] = (int *)malloc(V * sizeof(int)); + for (int j = 0; j < V; j++) this->edges[i][j] = INT_MAX; + this->edges[i][i] = 0; + } + } + + // Adds the given edge to the graph + void addEdge(int src, int dst, int weight) + { + this->edges[src][dst] = weight; + } }; -//Utility function to print distances +// Utility function to print distances void print(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++) - { - - if (dist[i * V + j] != INT_MAX) - cout << dist[i * V + j] << "\t"; - else - cout << "INF" - << "\t"; - } - cout << endl; - } + cout << "\nThe Distance matrix for Floyd - Warshall" << endl; + for (int i = 0; i < V; i++) + { + for (int j = 0; j < V; j++) + { + if (dist[i * V + j] != INT_MAX) + cout << dist[i * V + j] << "\t"; + else + cout << "INF" + << "\t"; + } + cout << endl; + } } -//The main function that finds the shortest path from a vertex -//to all other vertices using Floyd-Warshall Algorithm. +// 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]; + int V = graph.vertexNum; + int dist[V][V]; - //Initialise distance array - for (int i = 0; i < V; i++) - for (int j = 0; j < V; j++) - dist[i][j] = graph.edges[i][j]; + // Initialise distance array + for (int i = 0; i < V; i++) + for (int j = 0; j < V; j++) dist[i][j] = graph.edges[i][j]; - //Calculate distances - for (int k = 0; k < V; k++) - //Choose an intermediate vertex + // Calculate distances + for (int k = 0; k < V; k++) + // Choose an intermediate vertex - for (int i = 0; i < V; i++) - //Choose a source vertex for given intermediate + for (int i = 0; i < V; i++) + // Choose a source vertex for given intermediate - for (int j = 0; j < V; j++) - //Choose a destination vertex for above source vertex + for (int j = 0; j < V; j++) + // Choose a destination vertex for above source vertex - if (dist[i][k] != INT_MAX && dist[k][j] != INT_MAX && dist[i][k] + dist[k][j] < dist[i][j]) - //If the distance through intermediate vertex is less than direct edge then update value in distance array - dist[i][j] = dist[i][k] + dist[k][j]; + if (dist[i][k] != INT_MAX && dist[k][j] != INT_MAX && + dist[i][k] + dist[k][j] < dist[i][j]) + // If the distance through intermediate vertex is less than + // direct edge then update value in distance array + dist[i][j] = dist[i][k] + dist[k][j]; - //Convert 2d array to 1d array for print - int dist1d[V * V]; - for (int i = 0; i < V; i++) - for (int j = 0; j < V; j++) - dist1d[i * V + j] = dist[i][j]; + // Convert 2d array to 1d array for print + int dist1d[V * V]; + for (int i = 0; i < V; i++) + for (int j = 0; j < V; j++) dist1d[i * V + j] = dist[i][j]; - print(dist1d, V); + print(dist1d, V); } -//Driver Function +// Driver Function int main() { - int V, E; - int src, dst, weight; - cout << "Enter number of vertices: "; - cin >> V; - cout << "Enter number of edges: "; - cin >> E; - Graph G(V); - for (int i = 0; i < E; i++) - { - cout << "\nEdge " << i + 1 << "\nEnter source: "; - cin >> src; - cout << "Enter destination: "; - cin >> dst; - cout << "Enter weight: "; - cin >> weight; - G.addEdge(src, dst, weight); - } - FloydWarshall(G); - - return 0; + int V, E; + int src, dst, weight; + cout << "Enter number of vertices: "; + cin >> V; + cout << "Enter number of edges: "; + cin >> E; + Graph G(V); + for (int i = 0; i < E; i++) + { + cout << "\nEdge " << i + 1 << "\nEnter source: "; + cin >> src; + cout << "Enter destination: "; + cin >> dst; + cout << "Enter weight: "; + cin >> weight; + G.addEdge(src, dst, weight); + } + FloydWarshall(G); + + return 0; } diff --git a/dynamic_programming/kadane.cpp b/dynamic_programming/kadane.cpp index bf2aa76ac9b..31d17ae9e92 100644 --- a/dynamic_programming/kadane.cpp +++ b/dynamic_programming/kadane.cpp @@ -1,10 +1,12 @@ -#include -#include +#include +#include -int maxSubArraySum(int a[], int size) { +int maxSubArraySum(int a[], int size) +{ int max_so_far = INT_MIN, max_ending_here = 0; - for (int i = 0; i < size; i++) { + 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; @@ -15,13 +17,14 @@ int maxSubArraySum(int a[], int size) { return max_so_far; } - -int main() { +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++) { + for (i = 0; i < n; i++) + { std::cin >> a[i]; } int max_sum = maxSubArraySum(a, n); diff --git a/dynamic_programming/longest_common_string.cpp b/dynamic_programming/longest_common_string.cpp index c1e89d6dbf2..e33489cb1da 100644 --- a/dynamic_programming/longest_common_string.cpp +++ b/dynamic_programming/longest_common_string.cpp @@ -1,65 +1,59 @@ #include using namespace std; -int max(int a,int b) -{ - return (a > b) ? a : b; -} +int max(int a, int b) { return (a > b) ? a : b; } int main() { - char str1[]="DEFBCD"; - char str2[]="ABDEFJ"; - int i,j,k; - int n=strlen(str1)+1; - int m=strlen(str2)+1; - //cout<ma) + if (a[i][j] > ma) { - ma=a[i][j]; - indi=i; - indj=j; + ma = a[i][j]; + indi = i; + indj = j; } } } - cout< using namespace std; @@ -52,19 +52,22 @@ int lcs(string a, string b) else if (a[i - 1] == b[j - 1]) { res[i][j] = 1 + res[i - 1][j - 1]; - trace[i][j] = 1; // 1 means trace the matrix in upper left diagonal direction. + trace[i][j] = 1; // 1 means trace the matrix in upper left + // diagonal direction. } else { if (res[i - 1][j] > res[i][j - 1]) { res[i][j] = res[i - 1][j]; - trace[i][j] = 2; // 2 means trace the matrix in upwards direction. + trace[i][j] = + 2; // 2 means trace the matrix in upwards direction. } else { res[i][j] = res[i][j - 1]; - trace[i][j] = 3; // means trace the matrix in left direction. + trace[i][j] = + 3; // means trace the matrix in left direction. } } } diff --git a/dynamic_programming/longest_increasing_subsequence.cpp b/dynamic_programming/longest_increasing_subsequence.cpp index 49c54a941af..573db34a58f 100644 --- a/dynamic_programming/longest_increasing_subsequence.cpp +++ b/dynamic_programming/longest_increasing_subsequence.cpp @@ -1,39 +1,39 @@ -//Program to calculate length of longest increasing subsequence in an array +// Program to calculate length of longest increasing subsequence in an array #include using namespace std; int LIS(int a[], int n) { - int lis[n]; - for (int i = 0; i < n; ++i) - { - lis[i] = 1; - } - for (int i = 0; i < n; ++i) - { - for (int j = 0; j < i; ++j) - { - if (a[i] > a[j] && lis[i] < lis[j] + 1) - lis[i] = lis[j] + 1; - } - } - int res = 0; - for (int i = 0; i < n; ++i) - { - res = max(res, lis[i]); - } - return res; + int lis[n]; + for (int i = 0; i < n; ++i) + { + lis[i] = 1; + } + for (int i = 0; i < n; ++i) + { + for (int j = 0; j < i; ++j) + { + if (a[i] > a[j] && lis[i] < lis[j] + 1) + lis[i] = lis[j] + 1; + } + } + int res = 0; + for (int i = 0; i < n; ++i) + { + res = max(res, lis[i]); + } + return res; } int main(int argc, char const *argv[]) { - int n; - cout << "Enter size of array: "; - cin >> n; - int a[n]; - cout << "Enter array elements: "; - for (int i = 0; i < n; ++i) - { - cin >> a[i]; - } - cout << LIS(a, n) << endl; - return 0; + int n; + cout << "Enter size of array: "; + cin >> n; + int a[n]; + cout << "Enter array elements: "; + for (int i = 0; i < n; ++i) + { + cin >> a[i]; + } + cout << LIS(a, n) << endl; + return 0; } \ No newline at end of file diff --git a/dynamic_programming/longest_increasing_subsequence_(nlogn).cpp b/dynamic_programming/longest_increasing_subsequence_(nlogn).cpp index 5ee24e6a78b..2471b701f38 100644 --- a/dynamic_programming/longest_increasing_subsequence_(nlogn).cpp +++ b/dynamic_programming/longest_increasing_subsequence_(nlogn).cpp @@ -1,4 +1,4 @@ -//Program to calculate length of longest increasing subsequence in an array +// Program to calculate length of longest increasing subsequence in an array // in O(n log n) // tested on : https://cses.fi/problemset/task/1145/ @@ -7,30 +7,32 @@ using namespace std; int LIS(int arr[], int n) { - set < int > active; // The current built LIS. + set active; // The current built LIS. active.insert(arr[0]); // Loop through every element. for (int i = 1; i < n; ++i) { auto get = active.lower_bound(arr[i]); if (get == active.end()) - { + { active.insert(arr[i]); - } // current element is the greatest so LIS increases by 1. + } // current element is the greatest so LIS increases by 1. else - { - int val = * get; // we find the position where arr[i] will be in the LIS. If it is in the LIS already we do nothing + { + int val = *get; // we find the position where arr[i] will be in the + // LIS. If it is in the LIS already we do nothing if (val > arr[i]) - { - // else we remove the bigger element and add a smaller element (which is arr[i]) and continue; + { + // else we remove the bigger element and add a smaller element + // (which is arr[i]) and continue; active.erase(get); active.insert(arr[i]); } } } - return active.size(); // size of the LIS. + return active.size(); // size of the LIS. } -int main(int argc, char const * argv[]) +int main(int argc, char const* argv[]) { int n; cout << "Enter size of array: "; diff --git a/dynamic_programming/matrix_chain_multiplication.cpp b/dynamic_programming/matrix_chain_multiplication.cpp index 1e885bd7e4c..378edcc7f2d 100644 --- a/dynamic_programming/matrix_chain_multiplication.cpp +++ b/dynamic_programming/matrix_chain_multiplication.cpp @@ -1,5 +1,5 @@ -#include #include +#include using namespace std; #define MAX 10 @@ -7,56 +7,59 @@ using namespace std; // dp table to store the solution for already computed sub problems int dp[MAX][MAX]; -// Function to find the most efficient way to multiply the given sequence of matrices +// Function to find the most efficient way to multiply the given sequence of +// matrices int MatrixChainMultiplication(int dim[], int i, int j) { - // base case: one matrix - if (j <= i + 1) - return 0; + // base case: one matrix + if (j <= i + 1) + return 0; - // stores minimum number of scalar multiplications (i.e., cost) - // needed to compute the matrix M[i+1]...M[j] = M[i..j] - int min = INT_MAX; + // stores minimum number of scalar multiplications (i.e., cost) + // needed to compute the matrix M[i+1]...M[j] = M[i..j] + int min = INT_MAX; - // if dp[i][j] is not calculated (calculate it!!) + // if dp[i][j] is not calculated (calculate it!!) - if (dp[i][j] == 0) - { - // take the minimum over each possible position at which the - // sequence of matrices can be split + if (dp[i][j] == 0) + { + // take the minimum over each possible position at which the + // sequence of matrices can be split - for (int k = i + 1; k <= j - 1; k++) - { - // recur for M[i+1]..M[k] to get a i x k matrix - int cost = MatrixChainMultiplication(dim, i, k); + for (int k = i + 1; k <= j - 1; k++) + { + // recur for M[i+1]..M[k] to get a i x k matrix + int cost = MatrixChainMultiplication(dim, i, k); - // recur for M[k+1]..M[j] to get a k x j matrix - cost += MatrixChainMultiplication(dim, k, j); + // recur for M[k+1]..M[j] to get a k x j matrix + cost += MatrixChainMultiplication(dim, k, j); - // cost to multiply two (i x k) and (k x j) matrix - cost += dim[i] * dim[k] * dim[j]; + // cost to multiply two (i x k) and (k x j) matrix + cost += dim[i] * dim[k] * dim[j]; - if (cost < min) - min = cost; // store the minimum cost - } - dp[i][j] = min; - } + if (cost < min) + min = cost; // store the minimum cost + } + dp[i][j] = min; + } - // return min cost to multiply M[j+1]..M[j] - return dp[i][j]; + // return min cost to multiply M[j+1]..M[j] + return dp[i][j]; } // main function int main() { - // Matrix i has Dimensions dim[i-1] & dim[i] for i=1..n - // input is 10 x 30 matrix, 30 x 5 matrix, 5 x 60 matrix - int dim[] = {10, 30, 5, 60}; - int n = sizeof(dim) / sizeof(dim[0]); + // Matrix i has Dimensions dim[i-1] & dim[i] for i=1..n + // input is 10 x 30 matrix, 30 x 5 matrix, 5 x 60 matrix + int dim[] = {10, 30, 5, 60}; + int n = sizeof(dim) / sizeof(dim[0]); - // Function Calling: MatrixChainMultiplications(dimensions_array, starting, ending); + // Function Calling: MatrixChainMultiplications(dimensions_array, starting, + // ending); - cout << "Minimum cost is " << MatrixChainMultiplication(dim, 0, n - 1) << "\n"; + cout << "Minimum cost is " << MatrixChainMultiplication(dim, 0, n - 1) + << "\n"; - return 0; + return 0; } \ No newline at end of file diff --git a/dynamic_programming/searching_of_element_in_dynamic_array.cpp b/dynamic_programming/searching_of_element_in_dynamic_array.cpp index 9ee48ddedf7..3dea46bf4b6 100644 --- a/dynamic_programming/searching_of_element_in_dynamic_array.cpp +++ b/dynamic_programming/searching_of_element_in_dynamic_array.cpp @@ -1,41 +1,42 @@ /* -*this program is use to find any elemet in any row with variable array size -*aplication of pointer is use in it -*important point start from here to: -*the index value of array can be go to 1 to 100000 -*check till array[1000] -*end here -*how to work example: -**Question: -***number of array 2 -***quarry 3 -***array 1 is {1 2 3 4 5} -***array 2 is {6 7} -****i) what is 2nd element in 1st array -****ii) what is 1st element in 2nd array -****iii) what is 5th element in 1st array -*****output: -*****Enter Number of array you want to Store : 2 -*****Enter Number of Question or Quary you want to do Related to Array : 3 -*****Enter number of element in 1 rows : 5 -*****Enter the element of Array 1 2 3 4 5 -*****Enter number of element in 2 rows : 2 -*****Enter the element of Array 6 7 -*****enter the number of row which element You want to find : 1 -*****enter the position of element which You want to find : 2 -*****The element is 2 -*****enter the number of row which element You want to find : 2 -*****enter the position of element which You want to find : 1 -*****The element is 6 -*****enter the number of row which element You want to find : 1 -*****enter the position of element which You want to find : 5 -*****The element is 5 -*/ + *this program is use to find any elemet in any row with variable array size + *aplication of pointer is use in it + *important point start from here to: + *the index value of array can be go to 1 to 100000 + *check till array[1000] + *end here + *how to work example: + **Question: + ***number of array 2 + ***quarry 3 + ***array 1 is {1 2 3 4 5} + ***array 2 is {6 7} + ****i) what is 2nd element in 1st array + ****ii) what is 1st element in 2nd array + ****iii) what is 5th element in 1st array + *****output: + *****Enter Number of array you want to Store : 2 + *****Enter Number of Question or Quary you want to do Related to Array : 3 + *****Enter number of element in 1 rows : 5 + *****Enter the element of Array 1 2 3 4 5 + *****Enter number of element in 2 rows : 2 + *****Enter the element of Array 6 7 + *****enter the number of row which element You want to find : 1 + *****enter the position of element which You want to find : 2 + *****The element is 2 + *****enter the number of row which element You want to find : 2 + *****enter the position of element which You want to find : 1 + *****The element is 6 + *****enter the number of row which element You want to find : 1 + *****enter the position of element which You want to find : 5 + *****The element is 5 + */ #include // this is main fuction // *** -int main() { +int main() +{ int64_t r, mr = 0, x, q, i, z; std::cout << "Enter Number of array you want to Store :"; std::cin >> x; @@ -46,10 +47,11 @@ int main() { // create a Array in run time because use can // change the size of each array which he/she is going to store // create a 2D array - int** ar = new int* [x](); + int** ar = new int*[x](); // this for loop is use for entering different variable size array // *** - for (r = 0; r < x; r++) { + for (r = 0; r < x; r++) + { std::cout << "Enter number of element in " << r + 1 << " rows :"; std::cin >> mr; // creating a 1D array @@ -57,7 +59,8 @@ int main() { std::cout << "Enter the element of Array "; // this for loop is use for storing values in array // *** - for (i = 0; i < mr; i++) { + for (i = 0; i < mr; i++) + { // entering the value of rows in array in Horizontal std::cin >> ac[i]; } @@ -66,7 +69,8 @@ int main() { } // this for loop is use for display result of querry // *** - for (z = 0; z < q; z++) { + for (z = 0; z < q; z++) + { int64_t r1 = 0, q1 = 0; std::cout << "enter the number of row which element you want to find :"; std::cin >> r1; @@ -75,6 +79,6 @@ int main() { std::cin >> q1; q1 = q1 - 1; // use this to find desire position of element in desire array - std::cout <<"The element is "<< ar[r1][q1] < -#include +#include +#include // global declarations // no of nodes max limit. @@ -29,22 +29,26 @@ std::vector adj[MAX]; std::vector visited; std::vector dp; -void depth_first_search(int u) { +void depth_first_search(int u) +{ visited[u] = true; int child_height = 1; - for (int v : adj[u]) { - if (!visited[v]) { + for (int v : adj[u]) + { + if (!visited[v]) + { depth_first_search(v); // select maximum sub-tree height from all children. - child_height = std::max(child_height, dp[v]+1); + child_height = std::max(child_height, dp[v] + 1); } } // assigned the max child height to current visited node. dp[u] = child_height; } -int main() { +int main() +{ // number of nodes int number_of_nodes; std::cout << "Enter number of nodes of the tree : " << std::endl; @@ -54,16 +58,17 @@ int main() { int u, v; // Tree contains exactly n-1 edges where n denotes the number of nodes. std::cout << "Enter edges of the tree : " << std::endl; - for (int i = 0; i < number_of_nodes - 1; i++) { + for (int i = 0; i < number_of_nodes - 1; i++) + { std::cin >> u >> v; // undirected tree u -> v and v -> u. adj[u].push_back(v); adj[v].push_back(u); } // initialize all nodes as unvisited. - visited.assign(number_of_nodes+1, false); + visited.assign(number_of_nodes + 1, false); // initialize depth of all nodes to 0. - dp.assign(number_of_nodes+1, 0); + dp.assign(number_of_nodes + 1, 0); // function call which will initialize the height of all nodes. depth_first_search(1); std::cout << "Height of the Tree : " << dp[1] << std::endl; diff --git a/graph/bfs.cpp b/graph/bfs.cpp index e4e12886b73..f5d372134cd 100644 --- a/graph/bfs.cpp +++ b/graph/bfs.cpp @@ -2,72 +2,72 @@ using namespace std; class graph { - int v; - list *adj; + int v; + list *adj; -public: - graph(int v); - void addedge(int src, int dest); - void printgraph(); - void bfs(int s); + public: + graph(int v); + void addedge(int src, int dest); + void printgraph(); + void bfs(int s); }; graph::graph(int v) { - this->v = v; - this->adj = new list[v]; + this->v = v; + this->adj = new list[v]; } void graph::addedge(int src, int dest) { - src--; - dest--; - adj[src].push_back(dest); - //adj[dest].push_back(src); + src--; + dest--; + adj[src].push_back(dest); + // adj[dest].push_back(src); } void graph::printgraph() { - for (int i = 0; i < this->v; i++) - { - cout << "Adjacency list of vertex " << i + 1 << " is \n"; - list::iterator it; - for (it = adj[i].begin(); it != adj[i].end(); ++it) - { - cout << *it + 1 << " "; - } - cout << endl; - } + for (int i = 0; i < this->v; i++) + { + cout << "Adjacency list of vertex " << i + 1 << " is \n"; + list::iterator it; + for (it = adj[i].begin(); it != adj[i].end(); ++it) + { + cout << *it + 1 << " "; + } + cout << endl; + } } void graph::bfs(int s) { - bool *visited = new bool[this->v + 1]; - memset(visited, false, sizeof(bool) * (this->v + 1)); - visited[s] = true; - list q; - q.push_back(s); - list::iterator it; - while (!q.empty()) - { - int u = q.front(); - cout << u << " "; - q.pop_front(); - for (it = adj[u].begin(); it != adj[u].end(); ++it) - { - if (visited[*it] == false) - { - visited[*it] = true; - q.push_back(*it); - } - } - } + bool *visited = new bool[this->v + 1]; + memset(visited, false, sizeof(bool) * (this->v + 1)); + visited[s] = true; + list q; + q.push_back(s); + list::iterator it; + while (!q.empty()) + { + int u = q.front(); + cout << u << " "; + q.pop_front(); + for (it = adj[u].begin(); it != adj[u].end(); ++it) + { + if (visited[*it] == false) + { + visited[*it] = true; + q.push_back(*it); + } + } + } } int main() { - graph g(4); - g.addedge(1, 2); - g.addedge(2, 3); - g.addedge(3, 4); - g.addedge(1, 4); - g.addedge(1, 3); - //g.printgraph(); - g.bfs(2); - return 0; + graph g(4); + g.addedge(1, 2); + g.addedge(2, 3); + g.addedge(3, 4); + g.addedge(1, 4); + g.addedge(1, 3); + // g.printgraph(); + g.bfs(2); + return 0; } diff --git a/graph/bridge_finding_with_tarjan_algorithm.cpp b/graph/bridge_finding_with_tarjan_algorithm.cpp index ca124f512f0..a283a7c916e 100644 --- a/graph/bridge_finding_with_tarjan_algorithm.cpp +++ b/graph/bridge_finding_with_tarjan_algorithm.cpp @@ -4,28 +4,34 @@ * Last Modified Date: May 24, 2020 * */ -#include // for std::vector #include // for min & max -#include // for cout -using std::vector; +#include // for cout +#include // for std::vector using std::cout; using std::min; -class Solution { - vector < vector < int > > graph; - vectorin_time , out_time; +using std::vector; +class Solution +{ + vector> graph; + vector in_time, out_time; int timer; - vector < vector < int > > bridge; - vectorvisited; - void dfs(int current_node , int parent) { + vector> bridge; + vector visited; + void dfs(int current_node, int parent) + { visited.at(current_node) = true; in_time[current_node] = out_time[current_node] = timer++; - for ( auto&itr : graph[current_node] ) { - if (itr == parent) { + for (auto& itr : graph[current_node]) + { + if (itr == parent) + { continue; } - if (!visited[itr]) { - dfs(itr , current_node); - if (out_time[itr] > in_time[current_node]) { + if (!visited[itr]) + { + dfs(itr, current_node); + if (out_time[itr] > in_time[current_node]) + { bridge.push_back({itr, current_node}); } } @@ -34,14 +40,16 @@ class Solution { } public: - vector > search_bridges(int n, - const vector>& connections) { + vector> search_bridges(int n, + const vector>& connections) + { timer = 0; graph.resize(n); in_time.assign(n, 0); visited.assign(n, false); out_time.assign(n, 0); - for (auto&itr : connections) { + for (auto& itr : connections) + { graph.at(itr[0]).push_back(itr[1]); graph.at(itr[1]).push_back(itr[0]); } @@ -49,10 +57,11 @@ class Solution { return bridge; } }; -int main(void) { +int main(void) +{ Solution s1; int number_of_node = 5; - vector< vector >node; + vector> node; node.push_back({0, 1}); node.push_back({1, 3}); node.push_back({1, 2}); @@ -66,13 +75,14 @@ int main(void) { * 3 4 * * In this graph there are 4 bridges [0,2] , [2,4] , [3,5] , [1,2] - * + * * I assumed that the graph is bi-directional and connected. * */ - vector< vector > bridges = s1.search_bridges(number_of_node , node); + vector> bridges = s1.search_bridges(number_of_node, node); cout << bridges.size() << " bridges found!\n"; - for (auto&itr : bridges) { + for (auto& itr : bridges) + { cout << itr[0] << " --> " << itr[1] << '\n'; } return 0; diff --git a/graph/connected_components.cpp b/graph/connected_components.cpp index 9c22cc35e48..f78ef011e90 100644 --- a/graph/connected_components.cpp +++ b/graph/connected_components.cpp @@ -3,53 +3,62 @@ using std::vector; -class graph { +class graph +{ private: vector> adj; int connected_components; void depth_first_search(); - void explore(int, vector&); + void explore(int, vector &); + public: - explicit graph(int n): adj(n, vector()) { - connected_components = 0; - } + explicit graph(int n) : adj(n, vector()) { connected_components = 0; } void addEdge(int, int); - int getConnectedComponents() { - depth_first_search(); - return connected_components; + int getConnectedComponents() + { + depth_first_search(); + return connected_components; } }; -void graph::addEdge(int u, int v) { - adj[u-1].push_back(v-1); - adj[v-1].push_back(u-1); +void graph::addEdge(int u, int v) +{ + adj[u - 1].push_back(v - 1); + adj[v - 1].push_back(u - 1); } -void graph::depth_first_search() { - int n = adj.size(); - vector visited(n, false); +void graph::depth_first_search() +{ + int n = adj.size(); + vector visited(n, false); - for (int i = 0 ; i < n ; i++) { - if (!visited[i]) { - explore(i, visited); - connected_components++; + for (int i = 0; i < n; i++) + { + if (!visited[i]) + { + explore(i, visited); + connected_components++; + } } - } } -void graph::explore(int u, vector &visited) { - visited[u] = true; - for (auto v : adj[u]) { - if (!visited[v]) { - explore(v, visited); +void graph::explore(int u, vector &visited) +{ + visited[u] = true; + for (auto v : adj[u]) + { + if (!visited[v]) + { + explore(v, visited); + } } - } } -int main() { - graph g(4); - g.addEdge(1, 2); - g.addEdge(3, 2); - std::cout << g.getConnectedComponents(); - return 0; +int main() +{ + graph g(4); + g.addEdge(1, 2); + g.addEdge(3, 2); + std::cout << g.getConnectedComponents(); + return 0; } diff --git a/graph/connected_components_with_dsu.cpp b/graph/connected_components_with_dsu.cpp index 2c5c6dab55b..07fda5d2740 100644 --- a/graph/connected_components_with_dsu.cpp +++ b/graph/connected_components_with_dsu.cpp @@ -1,27 +1,32 @@ #include -#include #include +#include int N; // denotes number of nodes; std::vector parent; std::vector siz; -void make_set() { // function the initialize every node as it's own parent - for (int i = 1; i <= N; i++) { +void make_set() +{ // function the initialize every node as it's own parent + for (int i = 1; i <= N; i++) + { parent[i] = i; siz[i] = 1; } } // To find the component where following node belongs to -int find_set(int v) { +int find_set(int v) +{ if (v == parent[v]) return v; return parent[v] = find_set(parent[v]); } -void union_sets(int a, int b) { // To join 2 components to belong to one +void union_sets(int a, int b) +{ // To join 2 components to belong to one a = find_set(a); b = find_set(b); - if (a != b) { + if (a != b) + { if (siz[a] < siz[b]) std::swap(a, b); parent[b] = a; @@ -29,23 +34,25 @@ void union_sets(int a, int b) { // To join 2 components to belong to one } } -int no_of_connected_components() { // To find total no of connected components +int no_of_connected_components() +{ // To find total no of connected components std::set temp; // temp set to count number of connected components - for (int i = 1; i <= N; i++) - temp.insert(find_set(i)); + for (int i = 1; i <= N; i++) temp.insert(find_set(i)); return temp.size(); } // All critical/corner cases have been taken care of. // Input your required values: (not hardcoded) -int main() { +int main() +{ std::cin >> N; parent.resize(N + 1); siz.resize(N + 1); make_set(); int edges; std::cin >> edges; // no of edges in the graph - while (edges--) { + while (edges--) + { int node_a, node_b; std::cin >> node_a >> node_b; union_sets(node_a, node_b); diff --git a/graph/dfs.cpp b/graph/dfs.cpp index 656711ac822..7c7ec776135 100644 --- a/graph/dfs.cpp +++ b/graph/dfs.cpp @@ -3,29 +3,29 @@ using namespace std; int v = 4; void DFSUtil_(int graph[4][4], bool visited[], int s) { - visited[s] = true; - cout << s << " "; - for (int i = 0; i < v; i++) - { - if (graph[s][i] == 1 && visited[i] == false) - { - DFSUtil_(graph, visited, i); - } - } + visited[s] = true; + cout << s << " "; + for (int i = 0; i < v; i++) + { + if (graph[s][i] == 1 && visited[i] == false) + { + DFSUtil_(graph, visited, i); + } + } } void DFS_(int graph[4][4], int s) { - bool visited[v]; - memset(visited, 0, sizeof(visited)); - DFSUtil_(graph, visited, s); + bool visited[v]; + memset(visited, 0, sizeof(visited)); + DFSUtil_(graph, visited, s); } int main() { - int graph[4][4] = {{0, 1, 1, 0}, {0, 0, 1, 0}, {1, 0, 0, 1}, {0, 0, 0, 1}}; - cout << "DFS: "; - DFS_(graph, 2); - cout << endl; - return 0; + int graph[4][4] = {{0, 1, 1, 0}, {0, 0, 1, 0}, {1, 0, 0, 1}, {0, 0, 0, 1}}; + cout << "DFS: "; + DFS_(graph, 2); + cout << endl; + return 0; } \ No newline at end of file diff --git a/graph/dijkstra.cpp b/graph/dijkstra.cpp index b3ee44c416c..f2551093516 100644 --- a/graph/dijkstra.cpp +++ b/graph/dijkstra.cpp @@ -1,14 +1,16 @@ -#include -#include #include #include +#include +#include using namespace std; #define INF 10000010 vector> graph[5 * 100001]; int dis[5 * 100001]; int dij(vector> *v, int s, int *dis) { - priority_queue, vector>, greater>> pq; + priority_queue, vector>, + greater>> + pq; // source distance to zero. pq.push(make_pair(0, s)); dis[s] = 0; @@ -17,7 +19,8 @@ int dij(vector> *v, int s, int *dis) { u = (pq.top()).second; pq.pop(); - for (vector>::iterator it = v[u].begin(); it != v[u].end(); it++) + for (vector>::iterator it = v[u].begin(); + it != v[u].end(); it++) { if (dis[u] + it->first < dis[it->second]) { @@ -37,13 +40,13 @@ int main() // input edges. scanf("%d%d%d", &x, &y, &l); graph[x].push_back(make_pair(l, y)); - graph[y].push_back(make_pair(l, x)); // comment this line for directed graph + graph[y].push_back( + make_pair(l, x)); // comment this line for directed graph } // start node. scanf("%d", &s); // intialise all distances to infinity. - for (int i = 1; i <= n; i++) - dis[i] = INF; + for (int i = 1; i <= n; i++) dis[i] = INF; dij(graph, s, dis); for (int i = 1; i <= n; i++) diff --git a/graph/kosaraju.cpp b/graph/kosaraju.cpp index 2e66f131fe5..0efa291bc67 100644 --- a/graph/kosaraju.cpp +++ b/graph/kosaraju.cpp @@ -1,134 +1,135 @@ -/* Implementation of Kosaraju's Algorithm to find out the strongly connected components (SCCs) in a graph. - Author:Anirban166 -*/ +/* Implementation of Kosaraju's Algorithm to find out the strongly connected + components (SCCs) in a graph. Author:Anirban166 +*/ -#include -#include +#include +#include using namespace std; /** -* Iterative function/method to print graph: -* @param a[] : array of vectors (2D) -* @param V : vertices -* @return void -**/ -void print(vector a[],int V) + * Iterative function/method to print graph: + * @param a[] : array of vectors (2D) + * @param V : vertices + * @return void + **/ +void print(vector a[], int V) { - for(int i=0;i"; - for(int j=0;j"; + for (int j = 0; j < a[i].size(); j++) cout << a[i][j] << " "; + if (!a[i].empty()) + cout << endl; } } /** -* //Recursive function/method to push vertices into stack passed as parameter: -* @param v : vertices -* @param &st : stack passed by reference -* @param vis[] : array to keep track of visited nodes (boolean type) -* @param adj[] : array of vectors to represent graph -* @return void -**/ -void push_vertex(int v,stack &st,bool vis[],vector adj[]) + * //Recursive function/method to push vertices into stack passed as parameter: + * @param v : vertices + * @param &st : stack passed by reference + * @param vis[] : array to keep track of visited nodes (boolean type) + * @param adj[] : array of vectors to represent graph + * @return void + **/ +void push_vertex(int v, stack &st, bool vis[], vector adj[]) { - vis[v]=true; - for(auto i=adj[v].begin();i!=adj[v].end();i++) + vis[v] = true; + for (auto i = adj[v].begin(); i != adj[v].end(); i++) { - if(vis[*i]==false) - push_vertex(*i,st,vis,adj); + if (vis[*i] == false) + push_vertex(*i, st, vis, adj); } st.push(v); } - /** -* //Recursive function/method to implement depth first traversal(dfs): -* @param v : vertices -* @param vis[] : array to keep track of visited nodes (boolean type) -* @param grev[] : graph with reversed edges -* @return void -**/ -void dfs(int v,bool vis[],vector grev[]) + * //Recursive function/method to implement depth first traversal(dfs): + * @param v : vertices + * @param vis[] : array to keep track of visited nodes (boolean type) + * @param grev[] : graph with reversed edges + * @return void + **/ +void dfs(int v, bool vis[], vector grev[]) { - vis[v]=true; + vis[v] = true; // cout<0)) - i.e. it returns the count of (number of) strongly connected components (SCCs) in the graph. (variable 'count_scc' within function) +* @return int ( 0, 1, 2..and so on, only unsigned values as either there can be +no SCCs i.e. none(0) or there will be x no. of SCCs (x>0)) i.e. it returns the +count of (number of) strongly connected components (SCCs) in the graph. +(variable 'count_scc' within function) **/ int kosaraju(int V, vector adj[]) { - bool vis[V]={}; + bool vis[V] = {}; stack st; - for(int v=0;v grev[V]; - for(int i=0;i 57) && c != '-'); c = gc()) - ; - if (c == '-') - { - neg = 1; - c = gc(); - } - for (; c > 47 && c < 58; c = gc()) - { - x = (x << 1) + (x << 3) + c - 48; - } - if (neg) - x = -x; + register int c = gc(); + x = 0; + int neg = 0; + for (; ((c < 48 || c > 57) && c != '-'); c = gc()) + ; + if (c == '-') + { + neg = 1; + c = gc(); + } + for (; c > 47 && c < 58; c = gc()) + { + x = (x << 1) + (x << 3) + c - 48; + } + if (neg) + x = -x; } void out(int n) { - int N = n, rev, count = 0; - rev = N; - if (N == 0) - { - pc('0'); - return; - } - while ((rev % 10) == 0) - { - count++; - rev /= 10; - } - rev = 0; - while (N != 0) - { - rev = (rev << 3) + (rev << 1) + N % 10; - N /= 10; - } - while (rev != 0) - { - pc(rev % 10 + '0'); - rev /= 10; - } - while (count--) - pc('0'); + int N = n, rev, count = 0; + rev = N; + if (N == 0) + { + pc('0'); + return; + } + while ((rev % 10) == 0) + { + count++; + rev /= 10; + } + rev = 0; + while (N != 0) + { + rev = (rev << 3) + (rev << 1) + N % 10; + N /= 10; + } + while (rev != 0) + { + pc(rev % 10 + '0'); + rev /= 10; + } + while (count--) pc('0'); } ll parent[mx], arr[mx], node, edge; vector>> v; void initial() { - int i; - rep(i, node + edge) - parent[i] = i; + int i; + rep(i, node + edge) parent[i] = i; } int root(int i) { - while (parent[i] != i) - { - parent[i] = parent[parent[i]]; - i = parent[i]; - } - return i; + while (parent[i] != i) + { + parent[i] = parent[parent[i]]; + i = parent[i]; + } + return i; } void join(int x, int y) { - int root_x = root(x); //Disjoint set union by rank - int root_y = root(y); - parent[root_x] = root_y; + int root_x = root(x); // Disjoint set union by rank + int root_y = root(y); + parent[root_x] = root_y; } ll kruskal() { - ll mincost = 0, i, x, y; - rep(i, edge) - { - x = v[i].second.first; - y = v[i].second.second; - if (root(x) != root(y)) - { - mincost += v[i].first; - join(x, y); - } - } - return mincost; + ll mincost = 0, i, x, y; + rep(i, edge) + { + x = v[i].second.first; + y = v[i].second.second; + if (root(x) != root(y)) + { + mincost += v[i].first; + join(x, y); + } + } + return mincost; } int main() { - fast; - while (1) - { - int i, j, from, to, cost, totalcost = 0; - cin >> node >> edge; //Enter the nodes and edges - if (node == 0 && edge == 0) - break; //Enter 0 0 to break out - initial(); //Initialise the parent array - rep(i, edge) - { - cin >> from >> to >> cost; - v.pb(mp(cost, mp(from, to))); - totalcost += cost; - } - sort(v.begin(), v.end()); - // rep(i,v.size()) - // cout<> node >> edge; // Enter the nodes and edges + if (node == 0 && edge == 0) + break; // Enter 0 0 to break out + initial(); // Initialise the parent array + rep(i, edge) + { + cin >> from >> to >> cost; + v.pb(mp(cost, mp(from, to))); + totalcost += cost; + } + sort(v.begin(), v.end()); + // rep(i,v.size()) + // cout< adj[N]; // Graph - int up[LG][N]; // build this table - int level[N]; // get the levels of all of them + vector adj[N]; // Graph + int up[LG][N]; // build this table + int level[N]; // get the levels of all of them - lca(int n_): n(n_) + lca(int n_) : n(n_) { memset(up, -1, sizeof(up)); memset(level, 0, sizeof(level)); for (int i = 0; i < n - 1; ++i) - { + { int a, b; cin >> a >> b; a--; @@ -34,15 +34,15 @@ struct lca void verify() { for (int i = 0; i < n; ++i) - { + { cout << i << " : level: " << level[i] << endl; } cout << endl; for (int i = 0; i < LG; ++i) - { + { cout << "Power:" << i << ": "; for (int j = 0; j < n; ++j) - { + { cout << up[i][j] << " "; } cout << endl; @@ -52,11 +52,11 @@ struct lca void build() { for (int i = 1; i < LG; ++i) - { + { for (int j = 0; j < n; ++j) - { + { if (up[i - 1][j] != -1) - { + { up[i][j] = up[i - 1][up[i - 1][j]]; } } @@ -66,10 +66,10 @@ struct lca void dfs(int node, int par) { up[0][node] = par; - for (auto i: adj[node]) - { + for (auto i : adj[node]) + { if (i != par) - { + { level[i] = level[node] + 1; dfs(i, node); } @@ -80,28 +80,28 @@ struct lca u--; v--; if (level[v] > level[u]) - { + { swap(u, v); } // u is at the bottom. int dist = level[u] - level[v]; // Go up this much distance for (int i = LG - 1; i >= 0; --i) - { + { if (dist & (1 << i)) - { + { u = up[i][u]; } } if (u == v) - { + { return u; } assert(level[u] == level[v]); for (int i = LG - 1; i >= 0; --i) - { + { if (up[i][u] != up[i][v]) - { + { u = up[i][u]; v = up[i][v]; } @@ -113,8 +113,8 @@ struct lca int main() { - int n; // number of nodes in the tree. - lca l(n); // will take the input in the format given + int n; // number of nodes in the tree. + lca l(n); // will take the input in the format given // n-1 edges of the form // a b // Use verify function to see. diff --git a/graph/max_flow_with_ford_fulkerson_and_edmond_karp_algo.cpp b/graph/max_flow_with_ford_fulkerson_and_edmond_karp_algo.cpp index ee394d9f09a..f02a48e01b1 100644 --- a/graph/max_flow_with_ford_fulkerson_and_edmond_karp_algo.cpp +++ b/graph/max_flow_with_ford_fulkerson_and_edmond_karp_algo.cpp @@ -4,41 +4,47 @@ * Copyright: 2020, Open-Source * Last Modified: May 25, 2020 */ -#include -#include -#include #include #include -#include #include -#include +#include +#include +#include +#include #include +#include // std::max capacity of node in graph const int MAXN = 505; -class Graph { +class Graph +{ int residual_capacity[MAXN][MAXN]; int capacity[MAXN][MAXN]; // used while checking the flow of edge int total_nodes; int total_edges, source, sink; int parent[MAXN]; - std::vector >edge_participated; - std::bitset visited; + std::vector > edge_participated; + std::bitset visited; int max_flow = 0; - bool bfs(int source, int sink) { // to find the augmented - path + bool bfs(int source, int sink) + { // to find the augmented - path memset(parent, -1, sizeof(parent)); visited.reset(); - std::queueq; + std::queue q; q.push(source); bool is_path_found = false; - while (q.empty() == false && is_path_found == false) { + while (q.empty() == false && is_path_found == false) + { int current_node = q.front(); visited.set(current_node); q.pop(); - for (int i = 0; i < total_nodes; ++i) { - if (residual_capacity[current_node][i] > 0 && !visited[i]) { + for (int i = 0; i < total_nodes; ++i) + { + if (residual_capacity[current_node][i] > 0 && !visited[i]) + { visited.set(i); parent[i] = current_node; - if (i == sink) { + if (i == sink) + { return true; } q.push(i); @@ -49,29 +55,33 @@ class Graph { } public: - Graph() { - memset(residual_capacity, 0, sizeof(residual_capacity)); - } - void set_graph(void) { + Graph() { memset(residual_capacity, 0, sizeof(residual_capacity)); } + void set_graph(void) + { std::cin >> total_nodes >> total_edges >> source >> sink; - for (int start, destination, capacity_, i = 0; i < total_edges; ++i) { + for (int start, destination, capacity_, i = 0; i < total_edges; ++i) + { std::cin >> start >> destination >> capacity_; residual_capacity[start][destination] = capacity_; capacity[start][destination] = capacity_; } } - void ford_fulkerson(void) { - while (bfs(source, sink)) { + void ford_fulkerson(void) + { + while (bfs(source, sink)) + { int current_node = sink; int flow = std::numeric_limits::max(); - while (current_node != source) { + while (current_node != source) + { int parent_ = parent[current_node]; flow = std::min(flow, residual_capacity[parent_][current_node]); current_node = parent_; } current_node = sink; max_flow += flow; - while ( current_node != source ) { + while (current_node != source) + { int parent_ = parent[current_node]; residual_capacity[parent_][current_node] -= flow; residual_capacity[current_node][parent_] += flow; @@ -79,31 +89,34 @@ class Graph { } } } - void print_flow_info(void) { - for (int i = 0; i < total_nodes; ++i) { - for (int j = 0; j < total_nodes; ++j) { - if (capacity[i][j] && - residual_capacity[i][j] < capacity[i][j]) { - edge_participated.push_back( - std::make_tuple(i, j, - capacity[i][j]-residual_capacity[i][j])); + void print_flow_info(void) + { + for (int i = 0; i < total_nodes; ++i) + { + for (int j = 0; j < total_nodes; ++j) + { + if (capacity[i][j] && residual_capacity[i][j] < capacity[i][j]) + { + edge_participated.push_back(std::make_tuple( + i, j, capacity[i][j] - residual_capacity[i][j])); } } } - std::cout << "\nNodes : " << total_nodes - << "\nMax flow: " << max_flow - << "\nEdge present in flow: " << edge_participated.size() - << '\n'; - std::cout<< "\nSource\tDestination\tCapacity\total_nodes"; - for (auto&edge_data : edge_participated) { + std::cout << "\nNodes : " << total_nodes << "\nMax flow: " << max_flow + << "\nEdge present in flow: " << edge_participated.size() + << '\n'; + std::cout << "\nSource\tDestination\tCapacity\total_nodes"; + for (auto& edge_data : edge_participated) + { int source, destination, capacity_; std::tie(source, destination, capacity_) = edge_data; - std::cout << source << "\t" << destination << "\t\t" - << capacity_ <<'\t'; + std::cout << source << "\t" << destination << "\t\t" << capacity_ + << '\t'; } } }; -int main(void) { +int main(void) +{ /* Input Graph: (for testing ) 4 5 0 3 @@ -119,4 +132,3 @@ int main(void) { graph.print_flow_info(); return 0; } - diff --git a/graph/prim.cpp b/graph/prim.cpp index 2923b5b25fe..8332bdb367d 100644 --- a/graph/prim.cpp +++ b/graph/prim.cpp @@ -1,23 +1,25 @@ // C++ program to implement Prim's Algorithm #include -#include #include +#include const int MAX = 1e4 + 5; -typedef std:: pair PII; +typedef std::pair PII; bool marked[MAX]; -std:: vector adj[MAX]; +std::vector adj[MAX]; -int prim(int x) { +int prim(int x) +{ // priority queue to maintain edges with respect to weights - std:: priority_queue, std:: greater > Q; + std::priority_queue, std::greater > Q; int y; int minimumCost = 0; PII p; - Q.push(std:: make_pair(0, x)); - while (!Q.empty()) { + Q.push(std::make_pair(0, x)); + while (!Q.empty()) + { // Select the edge with minimum weight p = Q.top(); Q.pop(); @@ -27,7 +29,8 @@ int prim(int x) { continue; minimumCost += p.first; marked[x] = true; - for (int i = 0; i < adj[x].size(); ++i) { + for (int i = 0; i < adj[x].size(); ++i) + { y = adj[x][i].second; if (marked[y] == false) Q.push(adj[x][i]); @@ -36,23 +39,25 @@ int prim(int x) { return minimumCost; } -int main() { +int main() +{ int nodes, edges, x, y; int weight, minimumCost; - std:: cin >> nodes >> edges; // number of nodes & edges in graph + std::cin >> nodes >> edges; // number of nodes & edges in graph if (nodes == 0 || edges == 0) return 0; // Edges with their nodes & weight - for (int i = 0; i < edges; ++i) { + for (int i = 0; i < edges; ++i) + { std::cin >> x >> y >> weight; - adj[x].push_back(std:: make_pair(weight, y)); - adj[y].push_back(std:: make_pair(weight, x)); + adj[x].push_back(std::make_pair(weight, y)); + adj[y].push_back(std::make_pair(weight, x)); } // Selecting 1 as the starting node minimumCost = prim(1); - std:: cout << minimumCost << std:: endl; + std::cout << minimumCost << std::endl; return 0; } diff --git a/graph/topological_sort.cpp b/graph/topological_sort.cpp index 2203231ae4e..d863c69933f 100644 --- a/graph/topological_sort.cpp +++ b/graph/topological_sort.cpp @@ -1,53 +1,54 @@ +#include #include #include -#include using namespace std; -int n, m; // For number of Vertices (V) and number of edges (E) +int n, m; // For number of Vertices (V) and number of edges (E) vector> G; vector visited; vector ans; void dfs(int v) { - visited[v] = true; - for (int u : G[v]) - { - if (!visited[u]) - dfs(u); - } - ans.push_back(v); + visited[v] = true; + for (int u : G[v]) + { + if (!visited[u]) + dfs(u); + } + ans.push_back(v); } void topological_sort() { - visited.assign(n, false); - ans.clear(); - for (int i = 0; i < n; ++i) - { - if (!visited[i]) - dfs(i); - } - reverse(ans.begin(), ans.end()); + visited.assign(n, false); + ans.clear(); + for (int i = 0; i < n; ++i) + { + if (!visited[i]) + dfs(i); + } + reverse(ans.begin(), ans.end()); } int main() { - cout << "Enter the number of vertices and the number of directed edges\n"; - cin >> n >> m; - int x, y; - G.resize(n, vector()); - for (int i = 0; i < n; ++i) - { - cin >> x >> y; - x--, y--; // to convert 1-indexed to 0-indexed - G[x].push_back(y); - } - topological_sort(); - cout << "Topological Order : \n"; - for (int v : ans) - { - cout << v + 1 << ' '; // converting zero based indexing back to one based. - } - cout << '\n'; - return 0; + cout << "Enter the number of vertices and the number of directed edges\n"; + cin >> n >> m; + int x, y; + G.resize(n, vector()); + for (int i = 0; i < n; ++i) + { + cin >> x >> y; + x--, y--; // to convert 1-indexed to 0-indexed + G[x].push_back(y); + } + topological_sort(); + cout << "Topological Order : \n"; + for (int v : ans) + { + cout << v + 1 + << ' '; // converting zero based indexing back to one based. + } + cout << '\n'; + return 0; } diff --git a/graph/topological_sort_by_kahns_algo.cpp b/graph/topological_sort_by_kahns_algo.cpp index eda2a74bc5a..b56ae565140 100644 --- a/graph/topological_sort_by_kahns_algo.cpp +++ b/graph/topological_sort_by_kahns_algo.cpp @@ -1,63 +1,75 @@ #include #include #include -#include #include +#include int *topoSortKahn(int N, std::vector adj[]); -int main() { +int main() +{ int nodes, edges; std::cin >> edges >> nodes; if (edges == 0 || nodes == 0) return 0; int u, v; - std::vectorgraph[nodes]; + std::vector graph[nodes]; // create graph // example // 6 6 // 5 0 5 2 2 3 4 0 4 1 1 3 - for (int i = 0; i < edges; i++) { + for (int i = 0; i < edges; i++) + { std::cin >> u >> v; graph[u].push_back(v); } int *topo = topoSortKahn(nodes, graph); // topologically sorted nodes - for (int i = 0; i < nodes; i++) { + for (int i = 0; i < nodes; i++) + { std::cout << topo[i] << " "; } } -int* topoSortKahn(int V, std::vector adj[]) { - std::vectorvis(V+1, false); - std::vectordeg(V+1, 0); - for (int i = 0; i < V; i++) { - for (int j = 0; j < adj[i].size(); j++) { +int *topoSortKahn(int V, std::vector adj[]) +{ + std::vector vis(V + 1, false); + std::vector deg(V + 1, 0); + for (int i = 0; i < V; i++) + { + for (int j = 0; j < adj[i].size(); j++) + { deg[adj[i][j]]++; } } - std::queueq; - for (int i = 0; i < V; i++) { - if (deg[i] == 0) { + std::queue q; + for (int i = 0; i < V; i++) + { + if (deg[i] == 0) + { q.push(i); vis[i] = true; } } - int *arr = new int[V+1]; - memset(arr, 0, V+1); + int *arr = new int[V + 1]; + memset(arr, 0, V + 1); int count = 0; - while (!q.empty()) { + while (!q.empty()) + { int cur = q.front(); q.pop(); arr[count] = cur; count++; - for (int i = 0; i < adj[cur].size(); i++) { - if (!vis[adj[cur][i]]) { + for (int i = 0; i < adj[cur].size(); i++) + { + if (!vis[adj[cur][i]]) + { deg[adj[cur][i]]--; - if (deg[adj[cur][i]] == 0) { + if (deg[adj[cur][i]] == 0) + { q.push(adj[cur][i]); vis[adj[cur][i]] = true; } diff --git a/greedy_algorithms/dijkstra.cpp b/greedy_algorithms/dijkstra.cpp index 0c7fffc8cbf..b87b4ab109c 100644 --- a/greedy_algorithms/dijkstra.cpp +++ b/greedy_algorithms/dijkstra.cpp @@ -1,19 +1,18 @@ -#include #include +#include using namespace std; -//Wrapper class for storing a graph +// Wrapper class for storing a graph class Graph { -public: + public: int vertexNum; int **edges; - //Constructs a graph with V vertices and E edges + // Constructs a graph with V vertices and E edges Graph(const int V) { - // initializes the array edges. this->edges = new int *[V]; for (int i = 0; i < V; i++) @@ -33,13 +32,13 @@ class Graph this->vertexNum = V; } - //Adds the given edge to the graph + // Adds the given edge to the graph void addEdge(int src, int dst, int weight) { this->edges[src][dst] = weight; } }; -//Utility function to find minimum distance vertex in mdist +// Utility function to find minimum distance vertex in mdist int minDistance(int mdist[], bool vset[], int V) { int minVal = INT_MAX, minInd = 0; @@ -55,7 +54,7 @@ int minDistance(int mdist[], bool vset[], int V) return minInd; } -//Utility function to print distances +// Utility function to print distances void print(int dist[], int V) { cout << "\nVertex Distance" << endl; @@ -68,17 +67,17 @@ void print(int dist[], int V) } } -//The main function that finds the shortest path from given source -//to all other vertices using Dijkstra's Algorithm.It doesn't work on negative -//weights +// The main function that finds the shortest path from given source +// to all other vertices using Dijkstra's Algorithm.It doesn't work on negative +// weights void Dijkstra(Graph graph, int src) { int V = graph.vertexNum; - int mdist[V]; //Stores updated distances to vertex - bool vset[V]; // vset[i] is true if the vertex i included + int mdist[V]; // Stores updated distances to vertex + bool vset[V]; // vset[i] is true if the vertex i included // in the shortest path tree - //Initialise mdist and vset. Set distance of source as zero + // Initialise mdist and vset. Set distance of source as zero for (int i = 0; i < V; i++) { mdist[i] = INT_MAX; @@ -87,7 +86,7 @@ void Dijkstra(Graph graph, int src) mdist[src] = 0; - //iterate to find shortest path + // iterate to find shortest path for (int count = 0; count < V - 1; count++) { int u = minDistance(mdist, vset, V); @@ -96,7 +95,8 @@ void Dijkstra(Graph graph, int src) for (int v = 0; v < V; v++) { - if (!vset[v] && graph.edges[u][v] && mdist[u] + graph.edges[u][v] < mdist[v]) + if (!vset[v] && graph.edges[u][v] && + mdist[u] + graph.edges[u][v] < mdist[v]) { mdist[v] = mdist[u] + graph.edges[u][v]; } @@ -106,7 +106,7 @@ void Dijkstra(Graph graph, int src) print(mdist, V); } -//Driver Function +// Driver Function int main() { int V, E, gsrc; diff --git a/greedy_algorithms/huffman.cpp b/greedy_algorithms/huffman.cpp index 253d8d0b520..bf3d9ff9a69 100644 --- a/greedy_algorithms/huffman.cpp +++ b/greedy_algorithms/huffman.cpp @@ -1,109 +1,106 @@ -// C++ program for Huffman Coding +// C++ program for Huffman Coding #include -#include -using namespace std; - -// A Huffman tree node -struct MinHeapNode { - - // One of the input characters - char data; - - // Frequency of the character - unsigned freq; - - // Left and right child - MinHeapNode *left, *right; - - MinHeapNode(char data, unsigned freq) - - { - - left = right = NULL; - this->data = data; - this->freq = freq; - } -}; - -// For comparison of -// two heap nodes (needed in min heap) -struct compare { - - bool operator()(MinHeapNode* l, MinHeapNode* r) - - { - return (l->freq > r->freq); - } -}; - -// Prints huffman codes from -// the root of Huffman Tree. -void printCodes(struct MinHeapNode* root, string str) -{ - - if (!root) - return; - - if (root->data != '$') - cout << root->data << ": " << str << "\n"; - - printCodes(root->left, str + "0"); - printCodes(root->right, str + "1"); -} - -// The main function that builds a Huffman Tree and -// print codes by traversing the built Huffman Tree -void HuffmanCodes(char data[], int freq[], int size) -{ - struct MinHeapNode *left, *right, *top; - - // Create a min heap & inserts all characters of data[] - priority_queue, compare> minHeap; - - for (int i = 0; i < size; ++i) - minHeap.push(new MinHeapNode(data[i], freq[i])); - - // Iterate while size of heap doesn't become 1 - while (minHeap.size() != 1) { - - // Extract the two minimum - // freq items from min heap - left = minHeap.top(); - minHeap.pop(); - - right = minHeap.top(); - minHeap.pop(); - - // Create a new internal node with - // frequency equal to the sum of the - // two nodes frequencies. Make the - // two extracted node as left and right children - // of this new node. Add this node - // to the min heap '$' is a special value - // for internal nodes, not used - top = new MinHeapNode('$', left->freq + right->freq); - - top->left = left; - top->right = right; - - minHeap.push(top); - } - - // Print Huffman codes using - // the Huffman tree built above - printCodes(minHeap.top(), ""); -} - -// Driver program to test above functions -int main() -{ - - char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; - int freq[] = { 5, 9, 12, 13, 16, 45 }; - - int size = sizeof(arr) / sizeof(arr[0]); - - HuffmanCodes(arr, freq, size); - - return 0; -} +#include +using namespace std; + +// A Huffman tree node +struct MinHeapNode +{ + // One of the input characters + char data; + + // Frequency of the character + unsigned freq; + + // Left and right child + MinHeapNode *left, *right; + + MinHeapNode(char data, unsigned freq) + + { + left = right = NULL; + this->data = data; + this->freq = freq; + } +}; + +// For comparison of +// two heap nodes (needed in min heap) +struct compare +{ + bool operator()(MinHeapNode* l, MinHeapNode* r) + + { + return (l->freq > r->freq); + } +}; + +// Prints huffman codes from +// the root of Huffman Tree. +void printCodes(struct MinHeapNode* root, string str) +{ + if (!root) + return; + + if (root->data != '$') + cout << root->data << ": " << str << "\n"; + + printCodes(root->left, str + "0"); + printCodes(root->right, str + "1"); +} + +// The main function that builds a Huffman Tree and +// print codes by traversing the built Huffman Tree +void HuffmanCodes(char data[], int freq[], int size) +{ + struct MinHeapNode *left, *right, *top; + + // Create a min heap & inserts all characters of data[] + priority_queue, compare> minHeap; + + for (int i = 0; i < size; ++i) + minHeap.push(new MinHeapNode(data[i], freq[i])); + + // Iterate while size of heap doesn't become 1 + while (minHeap.size() != 1) + { + // Extract the two minimum + // freq items from min heap + left = minHeap.top(); + minHeap.pop(); + + right = minHeap.top(); + minHeap.pop(); + + // Create a new internal node with + // frequency equal to the sum of the + // two nodes frequencies. Make the + // two extracted node as left and right children + // of this new node. Add this node + // to the min heap '$' is a special value + // for internal nodes, not used + top = new MinHeapNode('$', left->freq + right->freq); + + top->left = left; + top->right = right; + + minHeap.push(top); + } + + // Print Huffman codes using + // the Huffman tree built above + printCodes(minHeap.top(), ""); +} + +// Driver program to test above functions +int main() +{ + char arr[] = {'a', 'b', 'c', 'd', 'e', 'f'}; + int freq[] = {5, 9, 12, 13, 16, 45}; + + int size = sizeof(arr) / sizeof(arr[0]); + + HuffmanCodes(arr, freq, size); + + return 0; +} diff --git a/greedy_algorithms/knapsack.cpp b/greedy_algorithms/knapsack.cpp index 2135bd1ebe9..81fd879de02 100644 --- a/greedy_algorithms/knapsack.cpp +++ b/greedy_algorithms/knapsack.cpp @@ -3,90 +3,88 @@ using namespace std; struct Item { - int weight; - int profit; + int weight; + int profit; }; -float profitPerUnit(Item x) -{ - return (float)x.profit / (float)x.weight; -} +float profitPerUnit(Item x) { return (float)x.profit / (float)x.weight; } int partition(Item arr[], int low, int high) { - Item pivot = arr[high]; // pivot - int i = (low - 1); // Index of smaller element + Item pivot = arr[high]; // pivot + int i = (low - 1); // Index of smaller element - for (int j = low; j < high; j++) - { - // If current element is smaller than or - // equal to pivot - if (profitPerUnit(arr[j]) <= profitPerUnit(pivot)) - { - i++; // increment index of smaller element - Item temp = arr[i]; - arr[i] = arr[j]; - arr[j] = temp; - } - } - Item temp = arr[i + 1]; - arr[i + 1] = arr[high]; - arr[high] = temp; - return (i + 1); + for (int j = low; j < high; j++) + { + // If current element is smaller than or + // equal to pivot + if (profitPerUnit(arr[j]) <= profitPerUnit(pivot)) + { + i++; // increment index of smaller element + Item temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + } + Item temp = arr[i + 1]; + arr[i + 1] = arr[high]; + arr[high] = temp; + return (i + 1); } void quickSort(Item arr[], int low, int high) { - if (low < high) - { - - int p = partition(arr, low, high); + if (low < high) + { + int p = partition(arr, low, high); - quickSort(arr, low, p - 1); - quickSort(arr, p + 1, high); - } + quickSort(arr, low, p - 1); + quickSort(arr, p + 1, high); + } } int main() { - cout << "\nEnter the capacity of the knapsack : "; - float capacity; - cin >> capacity; - cout << "\n Enter the number of Items : "; - int n; - cin >> n; - Item itemArray[n]; - for (int i = 0; i < n; i++) - { - cout << "\nEnter the weight and profit of item " << i + 1 << " : "; - cin >> itemArray[i].weight; - cin >> itemArray[i].profit; - } + cout << "\nEnter the capacity of the knapsack : "; + float capacity; + cin >> capacity; + cout << "\n Enter the number of Items : "; + int n; + cin >> n; + Item itemArray[n]; + for (int i = 0; i < n; i++) + { + cout << "\nEnter the weight and profit of item " << i + 1 << " : "; + cin >> itemArray[i].weight; + cin >> itemArray[i].profit; + } - quickSort(itemArray, 0, n - 1); + quickSort(itemArray, 0, n - 1); - // show(itemArray, n); + // show(itemArray, n); - float maxProfit = 0; - int i = n; - while (capacity > 0 && --i >= 0) - { - if (capacity >= itemArray[i].weight) - { - maxProfit += itemArray[i].profit; - capacity -= itemArray[i].weight; - cout << "\n\t" << itemArray[i].weight << "\t" << itemArray[i].profit; - } - else - { - maxProfit += profitPerUnit(itemArray[i]) * capacity; - cout << "\n\t" << capacity << "\t" << profitPerUnit(itemArray[i]) * capacity; - capacity = 0; - break; - } - } + float maxProfit = 0; + int i = n; + while (capacity > 0 && --i >= 0) + { + if (capacity >= itemArray[i].weight) + { + maxProfit += itemArray[i].profit; + capacity -= itemArray[i].weight; + cout << "\n\t" << itemArray[i].weight << "\t" + << itemArray[i].profit; + } + else + { + maxProfit += profitPerUnit(itemArray[i]) * capacity; + cout << "\n\t" << capacity << "\t" + << profitPerUnit(itemArray[i]) * capacity; + capacity = 0; + break; + } + } - cout << "\nMax Profit : " << maxProfit; + cout << "\nMax Profit : " << maxProfit; - return 0; + return 0; } diff --git a/greedy_algorithms/kruskals_minimum_spanning_tree.cpp b/greedy_algorithms/kruskals_minimum_spanning_tree.cpp index 951d4a88ac6..feeaf0102d1 100644 --- a/greedy_algorithms/kruskals_minimum_spanning_tree.cpp +++ b/greedy_algorithms/kruskals_minimum_spanning_tree.cpp @@ -4,34 +4,33 @@ using namespace std; #define V 6 #define INFINITY 99999 -int graph[V][V] = { - {0, 4, 1, 4, INFINITY, INFINITY}, - {4, 0, 3, 8, 3, INFINITY}, - {1, 3, 0, INFINITY, 1, INFINITY}, - {4, 8, INFINITY, 0, 5, 7}, - {INFINITY, 3, 1, 5, 0, INFINITY}, - {INFINITY, INFINITY, INFINITY, 7, INFINITY, 0}}; +int graph[V][V] = {{0, 4, 1, 4, INFINITY, INFINITY}, + {4, 0, 3, 8, 3, INFINITY}, + {1, 3, 0, INFINITY, 1, INFINITY}, + {4, 8, INFINITY, 0, 5, 7}, + {INFINITY, 3, 1, 5, 0, INFINITY}, + {INFINITY, INFINITY, INFINITY, 7, INFINITY, 0}}; void findMinimumEdge() { - for (int i = 0; i < V; i++) - { - int min = INFINITY; - int minIndex = 0; - for (int j = 0; j < V; j++) - { - if (graph[i][j] != 0 && graph[i][j] < min) - { - min = graph[i][j]; - minIndex = j; - } - } - cout << i << " - " << minIndex << "\t" << graph[i][minIndex] << "\n"; - } + for (int i = 0; i < V; i++) + { + int min = INFINITY; + int minIndex = 0; + for (int j = 0; j < V; j++) + { + if (graph[i][j] != 0 && graph[i][j] < min) + { + min = graph[i][j]; + minIndex = j; + } + } + cout << i << " - " << minIndex << "\t" << graph[i][minIndex] << "\n"; + } } int main() { - findMinimumEdge(); - return 0; + findMinimumEdge(); + return 0; } diff --git a/greedy_algorithms/prims_minimum_spanning_tree.cpp b/greedy_algorithms/prims_minimum_spanning_tree.cpp index 769ca64e4de..c1d3df66947 100644 --- a/greedy_algorithms/prims_minimum_spanning_tree.cpp +++ b/greedy_algorithms/prims_minimum_spanning_tree.cpp @@ -4,76 +4,74 @@ using namespace std; #define V 4 #define INFINITY 99999 -int graph[V][V] = { - {0, 5, 1, 2}, - {5, 0, 3, 3}, - {1, 3, 0, 4}, - {2, 3, 4, 0}}; +int graph[V][V] = {{0, 5, 1, 2}, {5, 0, 3, 3}, {1, 3, 0, 4}, {2, 3, 4, 0}}; struct mst { - bool visited; - int key; - int near; + bool visited; + int key; + int near; }; mst MST_Array[V]; void initilize() { - for (int i = 0; i < V; i++) - { - MST_Array[i].visited = false; - MST_Array[i].key = INFINITY; // considering INFINITY as inifinity - MST_Array[i].near = i; - } + for (int i = 0; i < V; i++) + { + MST_Array[i].visited = false; + MST_Array[i].key = INFINITY; // considering INFINITY as inifinity + MST_Array[i].near = i; + } - MST_Array[0].key = 0; + MST_Array[0].key = 0; } void updateNear() { - for (int v = 0; v < V; v++) - { - int min = INFINITY; - int minIndex = 0; - for (int i = 0; i < V; i++) - { - if (MST_Array[i].key < min && MST_Array[i].visited == false && MST_Array[i].key != INFINITY) - { - min = MST_Array[i].key; - minIndex = i; - } - } + for (int v = 0; v < V; v++) + { + int min = INFINITY; + int minIndex = 0; + for (int i = 0; i < V; i++) + { + if (MST_Array[i].key < min && MST_Array[i].visited == false && + MST_Array[i].key != INFINITY) + { + min = MST_Array[i].key; + minIndex = i; + } + } - MST_Array[minIndex].visited = true; + MST_Array[minIndex].visited = true; - for (int i = 0; i < V; i++) - { - if (graph[minIndex][i] != 0 && graph[minIndex][i] < INFINITY) - { - if (graph[minIndex][i] < MST_Array[i].key) - { - MST_Array[i].key = graph[minIndex][i]; - MST_Array[i].near = minIndex; - } - } - } - } + for (int i = 0; i < V; i++) + { + if (graph[minIndex][i] != 0 && graph[minIndex][i] < INFINITY) + { + if (graph[minIndex][i] < MST_Array[i].key) + { + MST_Array[i].key = graph[minIndex][i]; + MST_Array[i].near = minIndex; + } + } + } + } } void show() { - for (int i = 0; i < V; i++) - { - cout << i << " - " << MST_Array[i].near << "\t" << graph[i][MST_Array[i].near] << "\n"; - } + for (int i = 0; i < V; i++) + { + cout << i << " - " << MST_Array[i].near << "\t" + << graph[i][MST_Array[i].near] << "\n"; + } } int main() { - initilize(); - updateNear(); - show(); - return 0; + initilize(); + updateNear(); + show(); + return 0; } diff --git a/hashing/chaining.cpp b/hashing/chaining.cpp index 55aa8961c79..ae46aea59dc 100644 --- a/hashing/chaining.cpp +++ b/hashing/chaining.cpp @@ -1,140 +1,134 @@ -#include #include +#include using namespace std; struct Node { - int data; - struct Node *next; + int data; + struct Node *next; } * head[100], *curr; void init() { - for (int i = 0; i < 100; i++) - head[i] = NULL; + for (int i = 0; i < 100; i++) head[i] = NULL; } void add(int x, int h) { - struct Node *temp = new Node; - temp->data = x; - temp->next = NULL; - if (!head[h]) - { - head[h] = temp; - curr = head[h]; - } - else - { - curr = head[h]; - while (curr->next) - curr = curr->next; - curr->next = temp; - } + struct Node *temp = new Node; + temp->data = x; + temp->next = NULL; + if (!head[h]) + { + head[h] = temp; + curr = head[h]; + } + else + { + curr = head[h]; + while (curr->next) curr = curr->next; + curr->next = temp; + } } void display(int mod) { - struct Node *temp; - int i; - for (i = 0; i < mod; i++) - { - if (!head[i]) - { - cout << "Key " << i << " is empty" << endl; - } - else - { - cout << "Key " << i << " has values = "; - temp = head[i]; - while (temp->next) - { - cout << temp->data << " "; - temp = temp->next; - } - cout << temp->data; - cout << endl; - } - } + struct Node *temp; + int i; + for (i = 0; i < mod; i++) + { + if (!head[i]) + { + cout << "Key " << i << " is empty" << endl; + } + else + { + cout << "Key " << i << " has values = "; + temp = head[i]; + while (temp->next) + { + cout << temp->data << " "; + temp = temp->next; + } + cout << temp->data; + cout << endl; + } + } } -int hash(int x, int mod) -{ - return x % mod; -} +int hash(int x, int mod) { return x % mod; } void find(int x, int h) { - struct Node *temp = head[h]; - if (!head[h]) - { - cout << "Element not found"; - return; - } - while (temp->data != x && temp->next) - temp = temp->next; - if (temp->next) - cout << "Element found"; - else - { - if (temp->data == x) - cout << "Element found"; - else - cout << "Element not found"; - } + struct Node *temp = head[h]; + if (!head[h]) + { + cout << "Element not found"; + return; + } + while (temp->data != x && temp->next) temp = temp->next; + if (temp->next) + cout << "Element found"; + else + { + if (temp->data == x) + cout << "Element found"; + else + cout << "Element not found"; + } } int main(void) { - init(); - int c, x, mod, h; - cout << "Enter the size of Hash Table. = "; - cin >> mod; - bool loop = true; - while (loop) - { - cout << endl; - cout << "PLEASE CHOOSE -" << endl; - cout << "1. Add element." << endl; - cout << "2. Find element." << endl; - cout << "3. Generate Hash." << endl; - cout << "4. Display Hash table." << endl; - cout << "5. Exit." << endl; - cin >> c; - switch (c) - { - case 1: - cout << "Enter element to add = "; - cin >> x; - h = hash(x, mod); - h = fabs(h); - add(x, h); - break; - case 2: - cout << "Enter element to search = "; - cin >> x; - h = hash(x, mod); - find(x, h); - break; - case 3: - cout << "Enter element to generate hash = "; - cin >> x; - cout << "Hash of " << x << " is = " << hash(x, mod); - break; - case 4: - display(mod); - break; - default: - loop = false; - break; - } - cout << endl; - } - /*add(1,&head1); - add(2,&head1); - add(3,&head2); - add(5,&head1); - display(&head1); - display(&head2);*/ - return 0; + init(); + int c, x, mod, h; + cout << "Enter the size of Hash Table. = "; + cin >> mod; + bool loop = true; + while (loop) + { + cout << endl; + cout << "PLEASE CHOOSE -" << endl; + cout << "1. Add element." << endl; + cout << "2. Find element." << endl; + cout << "3. Generate Hash." << endl; + cout << "4. Display Hash table." << endl; + cout << "5. Exit." << endl; + cin >> c; + switch (c) + { + case 1: + cout << "Enter element to add = "; + cin >> x; + h = hash(x, mod); + h = fabs(h); + add(x, h); + break; + case 2: + cout << "Enter element to search = "; + cin >> x; + h = hash(x, mod); + find(x, h); + break; + case 3: + cout << "Enter element to generate hash = "; + cin >> x; + cout << "Hash of " << x << " is = " << hash(x, mod); + break; + case 4: + display(mod); + break; + default: + loop = false; + break; + } + cout << endl; + } + /*add(1,&head1); + add(2,&head1); + add(3,&head2); + add(5,&head1); + display(&head1); + display(&head2);*/ + return 0; } \ No newline at end of file diff --git a/hashing/double_hash_hash_table.cpp b/hashing/double_hash_hash_table.cpp index 6030b7ff361..842f383c5a1 100644 --- a/hashing/double_hash_hash_table.cpp +++ b/hashing/double_hash_hash_table.cpp @@ -1,13 +1,13 @@ // Copyright 2019 -#include -#include -#include -#include +#include +#include +#include +#include -using std::endl; -using std::cout; using std::cin; +using std::cout; +using std::endl; using std::string; // fwd declarations @@ -25,53 +25,70 @@ int size; bool rehashing; // Node that holds key -struct Entry { +struct Entry +{ explicit Entry(int key = notPresent) : key(key) {} int key; }; // Hash a key -int hashFxn(int key) { +int hashFxn(int key) +{ std::hash hash; return hash(key); } // Used for second hash function -int otherHashFxn(int key) { +int otherHashFxn(int key) +{ std::hash hash; return 1 + (7 - (hash(key) % 7)); } // Performs double hashing to resolve collisions -int doubleHash(int key, bool searching) { +int doubleHash(int key, bool searching) +{ int hash = static_cast(fabs(hashFxn(key))); int i = 0; Entry entry; - do { - int index = static_cast(fabs((hash + - (i * otherHashFxn(key))))) % totalSize; + do + { + int index = static_cast(fabs((hash + (i * otherHashFxn(key))))) % + totalSize; entry = table[index]; - if (searching) { - if (entry.key == notPresent) { + if (searching) + { + if (entry.key == notPresent) + { return notPresent; } - if (searchingProber(entry, key)) { + if (searchingProber(entry, key)) + { cout << "Found key!" << endl; return index; } cout << "Found tombstone or equal hash, checking next" << endl; i++; - } else { - if (putProber(entry, key)) { - if (!rehashing) cout << "Spot found!" << endl; + } + else + { + if (putProber(entry, key)) + { + if (!rehashing) + cout << "Spot found!" << endl; return index; } - if (!rehashing) cout << "Spot taken, looking at next (next index:" - << " " << static_cast(fabs((hash + - (i * otherHashFxn(key))))) % totalSize << ")" << endl; + if (!rehashing) + cout << "Spot taken, looking at next (next index:" + << " " + << static_cast( + fabs((hash + (i * otherHashFxn(key))))) % + totalSize + << ")" << endl; i++; } - if (i == totalSize * 100) { + if (i == totalSize * 100) + { cout << "DoubleHash probe failed" << endl; return notPresent; } @@ -80,27 +97,38 @@ int doubleHash(int key, bool searching) { } // Finds empty spot -bool putProber(Entry entry, int key) { - if (entry.key == notPresent || entry.key == tomb) { +bool putProber(Entry entry, int key) +{ + if (entry.key == notPresent || entry.key == tomb) + { return true; } return false; } // Looks for a matching key -bool searchingProber(Entry entry, int key) { - if (entry.key == key) return true; +bool searchingProber(Entry entry, int key) +{ + if (entry.key == key) + return true; return false; } // Displays the table -void display() { - for (int i = 0; i < totalSize; i++) { - if (table[i].key == notPresent) { +void display() +{ + for (int i = 0; i < totalSize; i++) + { + if (table[i].key == notPresent) + { cout << " Empty "; - } else if (table[i].key == tomb) { + } + else if (table[i].key == tomb) + { cout << " Tomb "; - } else { + } + else + { cout << " "; cout << table[i].key; cout << " "; @@ -110,7 +138,8 @@ void display() { } // Rehashes the table into a bigger table -void rehash() { +void rehash() +{ // Necessary so wall of add info isn't printed all at once rehashing = true; int oldSize = totalSize; @@ -118,8 +147,10 @@ void rehash() { // Really this should use the next prime number greater than totalSize * 2 table = new Entry[totalSize * 2]; totalSize *= 2; - for (int i = 0; i < oldSize; i++) { - if (oldTable[i].key != -1 && oldTable[i].key != notPresent) { + for (int i = 0; i < oldSize; i++) + { + if (oldTable[i].key != -1 && oldTable[i].key != notPresent) + { size--; // Size stays the same (add increments size) add(oldTable[i].key); } @@ -130,21 +161,25 @@ void rehash() { } // Checks for load factor here -void add(int key) { - Entry * entry = new Entry(); +void add(int key) +{ + Entry* entry = new Entry(); entry->key = key; int index = doubleHash(key, false); table[index] = *entry; // Load factor greater than 0.5 causes resizing - if (++size/ static_cast(totalSize) >= 0.5) { + if (++size / static_cast(totalSize) >= 0.5) + { rehash(); } } // Removes key. Leaves tombstone upon removal. -void remove(int key) { +void remove(int key) +{ int index = doubleHash(key, true); - if (index == notPresent) { + if (index == notPresent) + { cout << "key not found" << endl; } table[index].key = tomb; @@ -153,12 +188,13 @@ void remove(int key) { } // Information about the adding process -void addInfo(int key) { +void addInfo(int key) +{ cout << "Initial table: "; display(); cout << endl; - cout << "hash of " << key << " is " << hashFxn(key) - << " % " << totalSize << " == " << fabs(hashFxn(key) % totalSize); + cout << "hash of " << key << " is " << hashFxn(key) << " % " << totalSize + << " == " << fabs(hashFxn(key) % totalSize); cout << endl; add(key); cout << "New table: "; @@ -166,12 +202,13 @@ void addInfo(int key) { } // Information about removal process -void removalInfo(int key) { +void removalInfo(int key) +{ cout << "Initial table: "; display(); cout << endl; - cout << "hash of " << key << " is " << hashFxn(key) - << " % " << totalSize << " == " << hashFxn(key) % totalSize; + cout << "hash of " << key << " is " << hashFxn(key) << " % " << totalSize + << " == " << hashFxn(key) % totalSize; cout << endl; remove(key); cout << "New table: "; @@ -179,13 +216,15 @@ void removalInfo(int key) { } // I/O -int main(void) { +int main(void) +{ int cmd, hash, key; cout << "Enter the initial size of Hash Table. = "; cin >> totalSize; table = new Entry[totalSize]; bool loop = true; - while (loop) { + while (loop) + { system("pause"); cout << endl; cout << "PLEASE CHOOSE -" << endl; @@ -196,7 +235,8 @@ int main(void) { cout << "5. Display Hash table." << endl; cout << "6. Exit." << endl; cin >> cmd; - switch (cmd) { + switch (cmd) + { case 1: cout << "Enter key to add = "; cin >> key; @@ -207,11 +247,13 @@ int main(void) { cin >> key; removalInfo(key); break; - case 3: { + case 3: + { cout << "Enter key to search = "; cin >> key; Entry entry = table[doubleHash(key, true)]; - if (entry.key == notPresent) { + if (entry.key == notPresent) + { cout << "Key not present"; } break; diff --git a/hashing/linear_probing_hash_table.cpp b/hashing/linear_probing_hash_table.cpp index b00eb864109..0d4b5b0e1f3 100644 --- a/hashing/linear_probing_hash_table.cpp +++ b/hashing/linear_probing_hash_table.cpp @@ -1,13 +1,13 @@ // Copyright 2019 -#include -#include -#include -#include +#include +#include +#include +#include -using std::endl; -using std::cout; using std::cin; +using std::cout; +using std::endl; using std::string; // fwd declarations @@ -25,44 +25,57 @@ int size; bool rehashing; // Node that holds key -struct Entry { +struct Entry +{ explicit Entry(int key = notPresent) : key(key) {} int key; }; // Hash a key -int hashFxn(int key) { +int hashFxn(int key) +{ std::hash hash; return hash(key); } // Performs linear probing to resolve collisions -int linearProbe(int key, bool searching) { +int linearProbe(int key, bool searching) +{ int hash = static_cast(fabs(hashFxn(key))); int i = 0; Entry entry; - do { + do + { int index = static_cast(fabs((hash + i) % totalSize)); entry = table[index]; - if (searching) { - if (entry.key == notPresent) { + if (searching) + { + if (entry.key == notPresent) + { return notPresent; } - if (searchingProber(entry, key)) { + if (searchingProber(entry, key)) + { cout << "Found key!" << endl; return index; } cout << "Found tombstone or equal hash, checking next" << endl; i++; - } else { - if (putProber(entry, key)) { - if (!rehashing) cout << "Spot found!" << endl; + } + else + { + if (putProber(entry, key)) + { + if (!rehashing) + cout << "Spot found!" << endl; return index; } - if (!rehashing) cout << "Spot taken, looking at next" << endl; + if (!rehashing) + cout << "Spot taken, looking at next" << endl; i++; } - if (i == totalSize) { + if (i == totalSize) + { cout << "Linear probe failed" << endl; return notPresent; } @@ -71,27 +84,38 @@ int linearProbe(int key, bool searching) { } // Finds empty spot -bool putProber(Entry entry, int key) { - if (entry.key == notPresent || entry.key == tomb) { +bool putProber(Entry entry, int key) +{ + if (entry.key == notPresent || entry.key == tomb) + { return true; } return false; } // Looks for a matching key -bool searchingProber(Entry entry, int key) { - if (entry.key == key) return true; +bool searchingProber(Entry entry, int key) +{ + if (entry.key == key) + return true; return false; } // Displays the table -void display() { - for (int i = 0; i < totalSize; i++) { - if (table[i].key == notPresent) { +void display() +{ + for (int i = 0; i < totalSize; i++) + { + if (table[i].key == notPresent) + { cout << " Empty "; - } else if (table[i].key == tomb) { + } + else if (table[i].key == tomb) + { cout << " Tomb "; - } else { + } + else + { cout << " "; cout << table[i].key; cout << " "; @@ -101,7 +125,8 @@ void display() { } // Rehashes the table into a bigger table -void rehash() { +void rehash() +{ // Necessary so wall of add info isn't printed all at once rehashing = true; int oldSize = totalSize; @@ -109,8 +134,10 @@ void rehash() { // Really this should use the next prime number greater than totalSize * 2 table = new Entry[totalSize * 2]; totalSize *= 2; - for (int i = 0; i < oldSize; i++) { - if (oldTable[i].key != -1 && oldTable[i].key != notPresent) { + for (int i = 0; i < oldSize; i++) + { + if (oldTable[i].key != -1 && oldTable[i].key != notPresent) + { size--; // Size stays the same (add increments size) add(oldTable[i].key); } @@ -121,21 +148,25 @@ void rehash() { } // Adds entry using linear probing. Checks for load factor here -void add(int key) { - Entry * entry = new Entry(); +void add(int key) +{ + Entry* entry = new Entry(); entry->key = key; int index = linearProbe(key, false); table[index] = *entry; // Load factor greater than 0.5 causes resizing - if (++size/ static_cast(totalSize) >= 0.5) { + if (++size / static_cast(totalSize) >= 0.5) + { rehash(); } } // Removes key. Leaves tombstone upon removal. -void remove(int key) { +void remove(int key) +{ int index = linearProbe(key, true); - if (index == notPresent) { + if (index == notPresent) + { cout << "key not found" << endl; } cout << "Removal Successful, leaving tomb" << endl; @@ -144,12 +175,13 @@ void remove(int key) { } // Information about the adding process -void addInfo(int key) { +void addInfo(int key) +{ cout << "Initial table: "; display(); cout << endl; - cout << "hash of " << key << " is " << hashFxn(key) << " % " - << totalSize << " == " << fabs(hashFxn(key) % totalSize); + cout << "hash of " << key << " is " << hashFxn(key) << " % " << totalSize + << " == " << fabs(hashFxn(key) % totalSize); cout << endl; add(key); cout << "New table: "; @@ -157,12 +189,13 @@ void addInfo(int key) { } // Information about removal process -void removalInfo(int key) { +void removalInfo(int key) +{ cout << "Initial table: "; display(); cout << endl; - cout << "hash of " << key << " is " << hashFxn(key) - << " % " << totalSize << " == " << hashFxn(key) % totalSize; + cout << "hash of " << key << " is " << hashFxn(key) << " % " << totalSize + << " == " << hashFxn(key) % totalSize; cout << endl; remove(key); cout << "New table: "; @@ -170,13 +203,15 @@ void removalInfo(int key) { } // I/O -int main(void) { +int main(void) +{ int cmd, hash, key; cout << "Enter the initial size of Hash Table. = "; cin >> totalSize; table = new Entry[totalSize]; bool loop = true; - while (loop) { + while (loop) + { system("pause"); cout << endl; cout << "PLEASE CHOOSE -" << endl; @@ -187,7 +222,8 @@ int main(void) { cout << "5. Display Hash table." << endl; cout << "6. Exit." << endl; cin >> cmd; - switch (cmd) { + switch (cmd) + { case 1: cout << "Enter key to add = "; cin >> key; @@ -198,11 +234,13 @@ int main(void) { cin >> key; removalInfo(key); break; - case 3: { + case 3: + { cout << "Enter key to search = "; cin >> key; Entry entry = table[linearProbe(key, true)]; - if (entry.key == notPresent) { + if (entry.key == notPresent) + { cout << "Key not present"; } break; diff --git a/hashing/quadratic_probing_hash_table.cpp b/hashing/quadratic_probing_hash_table.cpp index 44e2e3b9f1b..b549d057d80 100644 --- a/hashing/quadratic_probing_hash_table.cpp +++ b/hashing/quadratic_probing_hash_table.cpp @@ -1,14 +1,14 @@ // Copyright 2019 -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include -using std::endl; -using std::cout; using std::cin; +using std::cout; +using std::endl; using std::string; // fwd declarations @@ -26,49 +26,64 @@ int size; bool rehashing; // Node that holds key -struct Entry { +struct Entry +{ explicit Entry(int key = notPresent) : key(key) {} int key; }; // Hash a key -int hashFxn(int key) { +int hashFxn(int key) +{ std::hash hash; return hash(key); } // Performs quadratic probing to resolve collisions -int quadraticProbe(int key, bool searching) { +int quadraticProbe(int key, bool searching) +{ int hash = static_cast(fabs(hashFxn(key))); int i = 0; Entry entry; - do { - int index = std::round(fabs((hash + - static_cast(std::round(std::pow(i, 2)))) % totalSize)); + do + { + int index = std::round(fabs( + (hash + static_cast(std::round(std::pow(i, 2)))) % totalSize)); entry = table[index]; - if (searching) { - if (entry.key == notPresent) { + if (searching) + { + if (entry.key == notPresent) + { return notPresent; } - if (searchingProber(entry, key)) { + if (searchingProber(entry, key)) + { cout << "Found key!" << endl; return index; } cout << "Found tombstone or equal hash, checking next" << endl; i++; - } else { - if (putProber(entry, key)) { - if (!rehashing) cout << "Spot found!" << endl; + } + else + { + if (putProber(entry, key)) + { + if (!rehashing) + cout << "Spot found!" << endl; return index; } - if (!rehashing) { - cout << "Spot taken, looking at next (next index = " << - std::round(fabs((hash + static_cast(std::round( - std::pow(i + 1, 2)))) % totalSize)) << endl; + if (!rehashing) + { + cout << "Spot taken, looking at next (next index = " + << std::round(fabs((hash + static_cast(std::round( + std::pow(i + 1, 2)))) % + totalSize)) + << endl; } i++; } - if (i == totalSize * 100) { + if (i == totalSize * 100) + { cout << "Quadratic probe failed (infinite loop)" << endl; return notPresent; } @@ -77,34 +92,47 @@ int quadraticProbe(int key, bool searching) { } // Finds empty spot -bool putProber(Entry entry, int key) { - if (entry.key == notPresent || entry.key == tomb) { +bool putProber(Entry entry, int key) +{ + if (entry.key == notPresent || entry.key == tomb) + { return true; } return false; } // Looks for a matching key -bool searchingProber(Entry entry, int key) { - if (entry.key == key) return true; +bool searchingProber(Entry entry, int key) +{ + if (entry.key == key) + return true; return false; } // Helper -Entry find(int key) { +Entry find(int key) +{ int index = quadraticProbe(key, true); - if (index == notPresent) return Entry(); + if (index == notPresent) + return Entry(); return table[index]; } // Displays the table -void display() { - for (int i = 0; i < totalSize; i++) { - if (table[i].key == notPresent) { +void display() +{ + for (int i = 0; i < totalSize; i++) + { + if (table[i].key == notPresent) + { cout << " Empty "; - } else if (table[i].key == tomb) { + } + else if (table[i].key == tomb) + { cout << " Tomb "; - } else { + } + else + { cout << " "; cout << table[i].key; cout << " "; @@ -114,7 +142,8 @@ void display() { } // Rehashes the table into a bigger table -void rehash() { +void rehash() +{ // Necessary so wall of add info isn't printed all at once rehashing = true; int oldSize = totalSize; @@ -122,8 +151,10 @@ void rehash() { // Really this should use the next prime number greater than totalSize * 2 table = new Entry[totalSize * 2]; totalSize *= 2; - for (int i = 0; i < oldSize; i++) { - if (oldTable[i].key != -1 && oldTable[i].key != notPresent) { + for (int i = 0; i < oldSize; i++) + { + if (oldTable[i].key != -1 && oldTable[i].key != notPresent) + { size--; // Size stays the same (add increments size) add(oldTable[i].key); } @@ -134,21 +165,25 @@ void rehash() { } // Checks for load factor here -void add(int key) { - Entry * entry = new Entry(); +void add(int key) +{ + Entry* entry = new Entry(); entry->key = key; int index = quadraticProbe(key, false); table[index] = *entry; // Load factor greater than 0.5 causes resizing - if (++size/ static_cast(totalSize) >= 0.5) { + if (++size / static_cast(totalSize) >= 0.5) + { rehash(); } } // Removes key. Leaves tombstone upon removal. -void remove(int key) { +void remove(int key) +{ int index = quadraticProbe(key, true); - if (index == notPresent) { + if (index == notPresent) + { cout << "key not found" << endl; } table[index].key = tomb; @@ -157,12 +192,13 @@ void remove(int key) { } // Information about the adding process -void addInfo(int key) { +void addInfo(int key) +{ cout << "Initial table: "; display(); cout << endl; - cout << "hash of " << key << " is " << hashFxn(key) << " % " - << totalSize << " == " << fabs(hashFxn(key) % totalSize); + cout << "hash of " << key << " is " << hashFxn(key) << " % " << totalSize + << " == " << fabs(hashFxn(key) % totalSize); cout << endl; add(key); cout << "New table: "; @@ -170,12 +206,13 @@ void addInfo(int key) { } // Information about removal process -void removalInfo(int key) { +void removalInfo(int key) +{ cout << "Initial table: "; display(); cout << endl; - cout << "hash of " << key << " is " << hashFxn(key) - << " % " << totalSize << " == " << hashFxn(key) % totalSize; + cout << "hash of " << key << " is " << hashFxn(key) << " % " << totalSize + << " == " << hashFxn(key) % totalSize; cout << endl; remove(key); cout << "New table: "; @@ -183,13 +220,15 @@ void removalInfo(int key) { } // I/O -int main(void) { +int main(void) +{ int cmd, hash, key; cout << "Enter the initial size of Hash Table. = "; cin >> totalSize; table = new Entry[totalSize]; bool loop = true; - while (loop) { + while (loop) + { system("pause"); cout << endl; cout << "PLEASE CHOOSE -" << endl; @@ -200,7 +239,8 @@ int main(void) { cout << "5. Display Hash table." << endl; cout << "6. Exit." << endl; cin >> cmd; - switch (cmd) { + switch (cmd) + { case 1: cout << "Enter key to add = "; cin >> key; @@ -211,11 +251,13 @@ int main(void) { cin >> key; removalInfo(key); break; - case 3: { + case 3: + { cout << "Enter key to search = "; cin >> key; Entry entry = table[quadraticProbe(key, true)]; - if (entry.key == notPresent) { + if (entry.key == notPresent) + { cout << "Key not present"; } break; diff --git a/math/binary_exponent.cpp b/math/binary_exponent.cpp index 05e6f33f7ae..7bf3a34a1f4 100644 --- a/math/binary_exponent.cpp +++ b/math/binary_exponent.cpp @@ -25,24 +25,32 @@ /// Recursive function to calculate exponent in \f$O(\log(n))\f$ using binary /// exponent. -int binExpo(int a, int b) { - if (b == 0) { +int binExpo(int a, int b) +{ + if (b == 0) + { return 1; } int res = binExpo(a, b / 2); - if (b % 2) { + if (b % 2) + { return res * res * a; - } else { + } + else + { return res * res; } } /// Iterative function to calculate exponent in \f$O(\log(n))\f$ using binary /// exponent. -int binExpo_alt(int a, int b) { +int binExpo_alt(int a, int b) +{ int res = 1; - while (b > 0) { - if (b % 2) { + while (b > 0) + { + if (b % 2) + { res = res * a; } a = a * a; @@ -52,15 +60,21 @@ int binExpo_alt(int a, int b) { } /// Main function -int main() { +int main() +{ int a, b; /// Give two numbers a, b std::cin >> a >> b; - if (a == 0 && b == 0) { + if (a == 0 && b == 0) + { std::cout << "Math error" << std::endl; - } else if (b < 0) { + } + else if (b < 0) + { std::cout << "Exponent must be positive !!" << std::endl; - } else { + } + else + { int resRecurse = binExpo(a, b); /// int resIterate = binExpo_alt(a, b); diff --git a/math/double_factorial.cpp b/math/double_factorial.cpp index 37bd2052ac3..4909ad48967 100644 --- a/math/double_factorial.cpp +++ b/math/double_factorial.cpp @@ -13,10 +13,13 @@ /** Compute double factorial using iterative method */ -uint64_t double_factorial_iterative(uint64_t n) { +uint64_t double_factorial_iterative(uint64_t n) +{ uint64_t res = 1; - for (uint64_t i = n;; i -= 2) { - if (i == 0 || i == 1) return res; + for (uint64_t i = n;; i -= 2) + { + if (i == 0 || i == 1) + return res; res *= i; } return res; @@ -25,13 +28,16 @@ uint64_t double_factorial_iterative(uint64_t n) { /** Compute double factorial using resursive method. *
Recursion can be costly for large numbers. */ -uint64_t double_factorial_recursive(uint64_t n) { - if (n <= 1) return 1; +uint64_t double_factorial_recursive(uint64_t n) +{ + if (n <= 1) + return 1; return n * double_factorial_recursive(n - 2); } /// main function -int main() { +int main() +{ uint64_t n; std::cin >> n; assert(n >= 0); diff --git a/math/eulers_totient_function.cpp b/math/eulers_totient_function.cpp index e7f6fbf7f5b..283516b4230 100644 --- a/math/eulers_totient_function.cpp +++ b/math/eulers_totient_function.cpp @@ -29,26 +29,35 @@ /** Function to caculate Euler's totient phi */ -uint64_t phiFunction(uint64_t n) { +uint64_t phiFunction(uint64_t n) +{ uint64_t result = n; - for (uint64_t i = 2; i * i <= n; i++) { - if (n % i == 0) { - while (n % i == 0) { + for (uint64_t i = 2; i * i <= n; i++) + { + if (n % i == 0) + { + while (n % i == 0) + { n /= i; } result -= result / i; } } - if (n > 1) result -= result / n; + if (n > 1) + result -= result / n; return result; } /// Main function -int main(int argc, char *argv[]) { +int main(int argc, char *argv[]) +{ uint64_t n; - if (argc < 2) { + if (argc < 2) + { std::cout << "Enter the number: "; - } else { + } + else + { n = strtoull(argv[1], nullptr, 10); } std::cin >> n; diff --git a/math/extended_euclid_algorithm.cpp b/math/extended_euclid_algorithm.cpp index 3fdae25b56a..8a79e0c7803 100644 --- a/math/extended_euclid_algorithm.cpp +++ b/math/extended_euclid_algorithm.cpp @@ -21,7 +21,8 @@ * @param[in] quotient unsigned */ template -inline void update_step(T *r, T *r0, const T2 quotient) { +inline void update_step(T *r, T *r0, const T2 quotient) +{ T temp = *r; *r = *r0 - (quotient * temp); *r0 = temp; @@ -38,14 +39,17 @@ inline void update_step(T *r, T *r0, const T2 quotient) { * @param[out] y signed */ template -void extendedEuclid_1(T1 A, T1 B, T1 *GCD, T2 *x, T2 *y) { - if (B > A) std::swap(A, B); // Ensure that A >= B +void extendedEuclid_1(T1 A, T1 B, T1 *GCD, T2 *x, T2 *y) +{ + if (B > A) + std::swap(A, B); // Ensure that A >= B T2 s = 0, s0 = 1; T2 t = 1, t0 = 0; T1 r = B, r0 = A; - while (r != 0) { + while (r != 0) + { T1 quotient = r0 / r; update_step(&r, &r0, quotient); update_step(&s, &s0, quotient); @@ -66,14 +70,19 @@ void extendedEuclid_1(T1 A, T1 B, T1 *GCD, T2 *x, T2 *y) { * @param[in,out] y signed */ template -void extendedEuclid(T A, T B, T *GCD, T2 *x, T2 *y) { - if (B > A) std::swap(A, B); // Ensure that A >= B +void extendedEuclid(T A, T B, T *GCD, T2 *x, T2 *y) +{ + if (B > A) + std::swap(A, B); // Ensure that A >= B - if (B == 0) { + if (B == 0) + { *GCD = A; *x = 1; *y = 0; - } else { + } + else + { extendedEuclid(B, A % B, GCD, x, y); T2 temp = *x; *x = *y; @@ -82,7 +91,8 @@ void extendedEuclid(T A, T B, T *GCD, T2 *x, T2 *y) { } /// Main function -int main() { +int main() +{ uint32_t a, b, gcd; int32_t x, y; std::cin >> a >> b; diff --git a/math/factorial.cpp b/math/factorial.cpp index 353f0b16bc7..7f50544e257 100644 --- a/math/factorial.cpp +++ b/math/factorial.cpp @@ -5,14 +5,16 @@ #include /** function to find factorial of given number */ -unsigned int factorial(unsigned int n) { +unsigned int factorial(unsigned int n) +{ if (n == 0) return 1; return n * factorial(n - 1); } /** Main function */ -int main() { +int main() +{ int num = 5; std::cout << "Factorial of " << num << " is " << factorial(num) << std::endl; diff --git a/math/fast_power.cpp b/math/fast_power.cpp index d4de074603c..8a0525ac17b 100644 --- a/math/fast_power.cpp +++ b/math/fast_power.cpp @@ -23,11 +23,14 @@ * algorithm implementation for \f$a^b\f$ */ template -double fast_power_recursive(T a, T b) { +double fast_power_recursive(T a, T b) +{ // negative power. a^b = 1 / (a^-b) - if (b < 0) return 1.0 / fast_power_recursive(a, -b); + if (b < 0) + return 1.0 / fast_power_recursive(a, -b); - if (b == 0) return 1; + if (b == 0) + return 1; T bottom = fast_power_recursive(a, b >> 1); // Since it is integer division b/2 = (b-1)/2 where b is odd. // Therefore, case2 is easily solved by integer division. @@ -45,13 +48,17 @@ double fast_power_recursive(T a, T b) { It still calculates in \f$O(\log N)\f$ */ template -double fast_power_linear(T a, T b) { +double fast_power_linear(T a, T b) +{ // negative power. a^b = 1 / (a^-b) - if (b < 0) return 1.0 / fast_power_linear(a, -b); + if (b < 0) + return 1.0 / fast_power_linear(a, -b); double result = 1; - while (b) { - if (b & 1) result = result * a; + while (b) + { + if (b & 1) + result = result * a; a = a * a; b = b >> 1; } @@ -61,12 +68,14 @@ double fast_power_linear(T a, T b) { /** * Main function */ -int main() { +int main() +{ std::srand(std::time(nullptr)); std::ios_base::sync_with_stdio(false); std::cout << "Testing..." << std::endl; - for (int i = 0; i < 20; i++) { + for (int i = 0; i < 20; i++) + { int a = std::rand() % 20 - 10; int b = std::rand() % 20 - 10; std::cout << std::endl << "Calculating " << a << "^" << b << std::endl; diff --git a/math/fibonacci.cpp b/math/fibonacci.cpp index e15cfc0ccff..5a219bbf9fc 100644 --- a/math/fibonacci.cpp +++ b/math/fibonacci.cpp @@ -14,7 +14,8 @@ /** * Recursively compute sequences */ -int fibonacci(unsigned int n) { +int fibonacci(unsigned int n) +{ /* If the input is 0 or 1 just return the same This will set the first 2 values of the sequence */ if (n <= 1) @@ -25,7 +26,8 @@ int fibonacci(unsigned int n) { } /// Main function -int main() { +int main() +{ int n; std::cin >> n; assert(n >= 0); diff --git a/math/fibonacci_fast.cpp b/math/fibonacci_fast.cpp index 08cced35105..3b3a3ca3840 100644 --- a/math/fibonacci_fast.cpp +++ b/math/fibonacci_fast.cpp @@ -26,7 +26,8 @@ const uint64_t MAX = 93; uint64_t f[MAX] = {0}; /** Algorithm */ -uint64_t fib(uint64_t n) { +uint64_t fib(uint64_t n) +{ if (n == 0) return 0; if (n == 1 || n == 2) @@ -43,9 +44,11 @@ uint64_t fib(uint64_t n) { } /** Main function */ -int main() { +int main() +{ // Main Function - for (uint64_t i = 1; i < 93; i++) { + for (uint64_t i = 1; i < 93; i++) + { std::cout << i << " th fibonacci number is " << fib(i) << std::endl; } return 0; diff --git a/math/fibonacci_large.cpp b/math/fibonacci_large.cpp index d9dbff79968..edc513750fc 100644 --- a/math/fibonacci_large.cpp +++ b/math/fibonacci_large.cpp @@ -20,11 +20,13 @@ * \f[f(n)=f(n-1)+f(n-2)\f] * and returns the result as a large_number type. */ -large_number fib(uint64_t n) { +large_number fib(uint64_t n) +{ large_number f0(1); large_number f1(1); - do { + do + { large_number f2 = f1; f1 += f0; f0 = f2; @@ -34,11 +36,15 @@ large_number fib(uint64_t n) { return f1; } -int main(int argc, char *argv[]) { +int main(int argc, char *argv[]) +{ uint64_t N; - if (argc == 2) { + if (argc == 2) + { N = strtoull(argv[1], NULL, 10); - } else { + } + else + { std::cout << "Enter N: "; std::cin >> N; } diff --git a/math/gcd_iterative_euclidean.cpp b/math/gcd_iterative_euclidean.cpp index 2c0651ad7ca..e832605d7d0 100644 --- a/math/gcd_iterative_euclidean.cpp +++ b/math/gcd_iterative_euclidean.cpp @@ -12,27 +12,34 @@ /** * algorithm */ -int gcd(int num1, int num2) { - if (num1 <= 0 | num2 <= 0) { +int gcd(int num1, int num2) +{ + if (num1 <= 0 | num2 <= 0) + { throw std::domain_error("Euclidean algorithm domain is for ints > 0"); } - if (num1 == num2) { + if (num1 == num2) + { return num1; } int base_num = 0; int previous_remainder = 1; - if (num1 > num2) { + if (num1 > num2) + { base_num = num1; previous_remainder = num2; - } else { + } + else + { base_num = num2; previous_remainder = num1; } - while ((base_num % previous_remainder) != 0) { + while ((base_num % previous_remainder) != 0) + { int old_base = base_num; base_num = previous_remainder; previous_remainder = old_base % previous_remainder; @@ -44,11 +51,15 @@ int gcd(int num1, int num2) { /** * Main function */ -int main() { +int main() +{ std::cout << "gcd of 120,7 is " << (gcd(120, 7)) << std::endl; - try { + try + { std::cout << "gcd of -120,10 is " << gcd(-120, 10) << std::endl; - } catch (const std::domain_error &e) { + } + catch (const std::domain_error &e) + { std::cout << "Error handling was successful" << std::endl; } std::cout << "gcd of 312,221 is " << (gcd(312, 221)) << std::endl; diff --git a/math/gcd_of_n_numbers.cpp b/math/gcd_of_n_numbers.cpp index 92968ff1265..cd81e602531 100644 --- a/math/gcd_of_n_numbers.cpp +++ b/math/gcd_of_n_numbers.cpp @@ -12,10 +12,12 @@ * @param[in] a array of integers to compute GCD for * @param[in] n number of integers in array `a` */ -int gcd(int *a, int n) { +int gcd(int *a, int n) +{ int j = 1; // to access all elements of the array starting from 1 int gcd = a[0]; - while (j < n) { + while (j < n) + { if (a[j] % gcd == 0) // value of gcd is as needed so far j++; // so we check for next element else @@ -25,7 +27,8 @@ int gcd(int *a, int n) { } /** Main function */ -int main() { +int main() +{ int n; std::cout << "Enter value of n:" << std::endl; std::cin >> n; diff --git a/math/gcd_recursive_euclidean.cpp b/math/gcd_recursive_euclidean.cpp index 2a3d2183c4e..d16fb11908b 100644 --- a/math/gcd_recursive_euclidean.cpp +++ b/math/gcd_recursive_euclidean.cpp @@ -11,12 +11,15 @@ /** * algorithm */ -int gcd(int num1, int num2) { - if (num1 <= 0 | num2 <= 0) { +int gcd(int num1, int num2) +{ + if (num1 <= 0 | num2 <= 0) + { throw std::domain_error("Euclidean algorithm domain is for ints > 0"); } - if (num1 == num2) { + if (num1 == num2) + { return num1; } @@ -39,11 +42,15 @@ int gcd(int num1, int num2) { /** * Main function */ -int main() { +int main() +{ std::cout << "gcd of 120,7 is " << (gcd(120, 7)) << std::endl; - try { + try + { std::cout << "gcd of -120,10 is " << gcd(-120, 10) << std::endl; - } catch (const std::domain_error &e) { + } + catch (const std::domain_error &e) + { std::cout << "Error handling was successful" << std::endl; } std::cout << "gcd of 312,221 is " << (gcd(312, 221)) << std::endl; diff --git a/math/large_factorial.cpp b/math/large_factorial.cpp index 1027f41abf8..0a54f620bb6 100644 --- a/math/large_factorial.cpp +++ b/math/large_factorial.cpp @@ -13,7 +13,8 @@ /** Test implementation for 10! Result must be 3628800. * @returns True if test pass else False */ -bool test1() { +bool test1() +{ std::cout << "---- Check 1\t"; unsigned int i, number = 10; large_number result; @@ -23,15 +24,18 @@ bool test1() { const char *known_reslt = "3628800"; /* check 1 */ - if (strlen(known_reslt) != result.num_digits()) { + if (strlen(known_reslt) != result.num_digits()) + { std::cerr << "Result lengths dont match! " << strlen(known_reslt) << " != " << result.num_digits() << std::endl; return false; } const size_t N = result.num_digits(); - for (i = 0; i < N; i++) { - if (known_reslt[i] != result.digit_char(i)) { + for (i = 0; i < N; i++) + { + if (known_reslt[i] != result.digit_char(i)) + { std::cerr << i << "^th digit mismatch! " << known_reslt[i] << " != " << result.digit_char(i) << std::endl; return false; @@ -50,7 +54,8 @@ bool test1() { * ``` * @returns True if test pass else False */ -bool test2() { +bool test2() +{ std::cout << "---- Check 2\t"; unsigned int i, number = 100; large_number result; @@ -63,15 +68,18 @@ bool test2() { "000000000000000000"; /* check 1 */ - if (strlen(known_reslt) != result.num_digits()) { + if (strlen(known_reslt) != result.num_digits()) + { std::cerr << "Result lengths dont match! " << strlen(known_reslt) << " != " << result.num_digits() << std::endl; return false; } const size_t N = result.num_digits(); - for (i = 0; i < N; i++) { - if (known_reslt[i] != result.digit_char(i)) { + for (i = 0; i < N; i++) + { + if (known_reslt[i] != result.digit_char(i)) + { std::cerr << i << "^th digit mismatch! " << known_reslt[i] << " != " << result.digit_char(i) << std::endl; return false; @@ -85,12 +93,16 @@ bool test2() { /** * Main program **/ -int main(int argc, char *argv[]) { +int main(int argc, char *argv[]) +{ int number, i; - if (argc == 2) { + if (argc == 2) + { number = atoi(argv[1]); - } else { + } + else + { std::cout << "Enter the value of n(n starts from 0 ): "; std::cin >> number; } diff --git a/math/large_number.h b/math/large_number.h index c1a3665e4d1..88e3ba8020d 100644 --- a/math/large_number.h +++ b/math/large_number.h @@ -20,7 +20,8 @@ * digit to the number, perform multiplication of * large number with long unsigned integers. **/ -class large_number { +class large_number +{ public: /**< initializer with value = 1 */ large_number() { _digits.push_back(1); } @@ -35,9 +36,11 @@ class large_number { // } /**< initializer from an integer */ - explicit large_number(int n) { + explicit large_number(int n) + { int carry = n; - do { + do + { add_digit(carry % 10); carry /= 10; } while (carry != 0); @@ -50,8 +53,10 @@ class large_number { explicit large_number(std::vector &vec) : _digits(vec) {} /**< initializer from a string */ - explicit large_number(char const *number_str) { - for (size_t i = strlen(number_str); i > 0; i--) { + explicit large_number(char const *number_str) + { + for (size_t i = strlen(number_str); i > 0; i--) + { unsigned char a = number_str[i - 1] - '0'; if (a >= 0 && a <= 9) _digits.push_back(a); @@ -61,48 +66,55 @@ class large_number { /** * Function to check implementation **/ - static bool test() { + static bool test() + { std::cout << "------ Checking `large_number` class implementations\t" << std::endl; large_number a(40); // 1. test multiplication a *= 10; - if (a != large_number(400)) { + if (a != large_number(400)) + { std::cerr << "\tFailed 1/6 (" << a << "!=400)" << std::endl; return false; } std::cout << "\tPassed 1/6..."; // 2. test compound addition with integer a += 120; - if (a != large_number(520)) { + if (a != large_number(520)) + { std::cerr << "\tFailed 2/6 (" << a << "!=520)" << std::endl; return false; } std::cout << "\tPassed 2/6..."; // 3. test compound multiplication again a *= 10; - if (a != large_number(5200)) { + if (a != large_number(5200)) + { std::cerr << "\tFailed 3/6 (" << a << "!=5200)" << std::endl; return false; } std::cout << "\tPassed 3/6..."; // 4. test increment (prefix) ++a; - if (a != large_number(5201)) { + if (a != large_number(5201)) + { std::cerr << "\tFailed 4/6 (" << a << "!=5201)" << std::endl; return false; } std::cout << "\tPassed 4/6..."; // 5. test increment (postfix) a++; - if (a != large_number(5202)) { + if (a != large_number(5202)) + { std::cerr << "\tFailed 5/6 (" << a << "!=5202)" << std::endl; return false; } std::cout << "\tPassed 5/6..."; // 6. test addition with another large number a = a + large_number("7000000000000000000000000000000"); - if (a != large_number("7000000000000000000000000005202")) { + if (a != large_number("7000000000000000000000000005202")) + { std::cerr << "\tFailed 6/6 (" << a << "!=7000000000000000000000000005202)" << std::endl; return false; @@ -114,8 +126,10 @@ class large_number { /** * add a digit at MSB to the large number **/ - void add_digit(unsigned int value) { - if (value > 9) { + void add_digit(unsigned int value) + { + if (value > 9) + { std::cerr << "digit > 9!!\n"; exit(EXIT_FAILURE); } @@ -135,14 +149,16 @@ class large_number { **/ inline unsigned char &operator[](size_t n) { return this->_digits[n]; } - inline const unsigned char &operator[](size_t n) const { + inline const unsigned char &operator[](size_t n) const + { return this->_digits[n]; } /** * operator overload to compare two numbers **/ - friend std::ostream &operator<<(std::ostream &out, const large_number &a) { + friend std::ostream &operator<<(std::ostream &out, const large_number &a) + { for (size_t i = a.num_digits(); i > 0; i--) out << static_cast(a[i - 1]); return out; @@ -151,7 +167,8 @@ class large_number { /** * operator overload to compare two numbers **/ - friend bool operator==(large_number const &a, large_number const &b) { + friend bool operator==(large_number const &a, large_number const &b) + { size_t N = a.num_digits(); if (N != b.num_digits()) return false; @@ -164,14 +181,16 @@ class large_number { /** * operator overload to compare two numbers **/ - friend bool operator!=(large_number const &a, large_number const &b) { + friend bool operator!=(large_number const &a, large_number const &b) + { return !(a == b); } /** * operator overload to increment (prefix) **/ - large_number &operator++() { + large_number &operator++() + { (*this) += 1; return *this; } @@ -179,7 +198,8 @@ class large_number { /** * operator overload to increment (postfix) **/ - large_number &operator++(int) { + large_number &operator++(int) + { static large_number tmp(_digits); ++(*this); return tmp; @@ -188,13 +208,15 @@ class large_number { /** * operator overload to add **/ - large_number &operator+=(large_number n) { + large_number &operator+=(large_number n) + { // if adding with another large_number large_number *b = reinterpret_cast(&n); const size_t max_L = std::max(this->num_digits(), b->num_digits()); unsigned int carry = 0; size_t i; - for (i = 0; i < max_L || carry != 0; i++) { + for (i = 0; i < max_L || carry != 0; i++) + { if (i < b->num_digits()) carry += (*b)[i]; if (i < this->num_digits()) @@ -216,7 +238,8 @@ class large_number { * operator overload to perform addition **/ template - friend large_number &operator+(const large_number &a, const T &b) { + friend large_number &operator+(const large_number &a, const T &b) + { static large_number c = a; c += b; return c; @@ -225,7 +248,8 @@ class large_number { /** * assignment operator **/ - large_number &operator=(const large_number &b) { + large_number &operator=(const large_number &b) + { this->_digits = b._digits; return *this; } @@ -234,7 +258,8 @@ class large_number { * operator overload to increment **/ template - large_number &operator*=(const T n) { + large_number &operator*=(const T n) + { static_assert(std::is_integral::value, "Must be integer addition unsigned integer types."); this->multiply(n); @@ -244,7 +269,8 @@ class large_number { /** * returns i^th digit as an ASCII character **/ - const char digit_char(size_t i) const { + const char digit_char(size_t i) const + { return _digits[num_digits() - i - 1] + '0'; } @@ -254,7 +280,8 @@ class large_number { * store the result in the same large number **/ template - void multiply(const T n) { + void multiply(const T n) + { static_assert(std::is_integral::value, "Can only have integer types."); // assert(!(std::is_signed::value)); //, "Implemented only for @@ -262,19 +289,24 @@ class large_number { size_t i; uint64_t carry = 0, temp; - for (i = 0; i < this->num_digits(); i++) { + for (i = 0; i < this->num_digits(); i++) + { temp = (*this)[i] * n; temp += carry; - if (temp < 10) { + if (temp < 10) + { carry = 0; - } else { + } + else + { carry = temp / 10; temp = temp % 10; } (*this)[i] = temp; } - while (carry != 0) { + while (carry != 0) + { this->add_digit(carry % 10); carry /= 10; } diff --git a/math/modular_inverse_fermat_little_theorem.cpp b/math/modular_inverse_fermat_little_theorem.cpp index 7550e14bf23..6895cafbbf9 100644 --- a/math/modular_inverse_fermat_little_theorem.cpp +++ b/math/modular_inverse_fermat_little_theorem.cpp @@ -49,11 +49,14 @@ /** Recursive function to calculate exponent in \f$O(\log n)\f$ using binary * exponent. */ -int64_t binExpo(int64_t a, int64_t b, int64_t m) { +int64_t binExpo(int64_t a, int64_t b, int64_t m) +{ a %= m; int64_t res = 1; - while (b > 0) { - if (b % 2) { + while (b > 0) + { + if (b % 2) + { res = res * a % m; } a = a * a % m; @@ -65,12 +68,18 @@ int64_t binExpo(int64_t a, int64_t b, int64_t m) { /** Prime check in \f$O(\sqrt{m})\f$ time. */ -bool isPrime(int64_t m) { - if (m <= 1) { +bool isPrime(int64_t m) +{ + if (m <= 1) + { return false; - } else { - for (int64_t i = 2; i * i <= m; i++) { - if (m % i == 0) { + } + else + { + for (int64_t i = 2; i * i <= m; i++) + { + if (m % i == 0) + { return false; } } @@ -81,17 +90,21 @@ bool isPrime(int64_t m) { /** * Main function */ -int main() { +int main() +{ int64_t a, m; // Take input of a and m. std::cout << "Computing ((a^(-1))%(m)) using Fermat's Little Theorem"; std::cout << std::endl << std::endl; std::cout << "Give input 'a' and 'm' space separated : "; std::cin >> a >> m; - if (isPrime(m)) { + if (isPrime(m)) + { std::cout << "The modular inverse of a with mod m is (a^(m-2)) : "; std::cout << binExpo(a, m - 2, m) << std::endl; - } else { + } + else + { std::cout << "m must be a prime number."; std::cout << std::endl; } diff --git a/math/number_of_positive_divisors.cpp b/math/number_of_positive_divisors.cpp index f157f7b4161..beb4599439e 100644 --- a/math/number_of_positive_divisors.cpp +++ b/math/number_of_positive_divisors.cpp @@ -31,25 +31,31 @@ respectively. /** * Algorithm */ -int number_of_positive_divisors(int n) { +int number_of_positive_divisors(int n) +{ std::vector prime_exponent_count; - for (int i = 2; i * i <= n; i++) { + for (int i = 2; i * i <= n; i++) + { int prime_count = 0; - while (n % i == 0) { + while (n % i == 0) + { prime_count += 1; n /= i; } - if (prime_count != 0) { + if (prime_count != 0) + { prime_exponent_count.push_back(prime_count); } } - if (n > 1) { + if (n > 1) + { prime_exponent_count.push_back(1); } int divisors_count = 1; - for (int i = 0; i < prime_exponent_count.size(); i++) { + for (int i = 0; i < prime_exponent_count.size(); i++) + { divisors_count = divisors_count * (prime_exponent_count[i] + 1); } @@ -59,15 +65,20 @@ int number_of_positive_divisors(int n) { /** * Main function */ -int main() { +int main() +{ int n; std::cin >> n; - if (n < 0) { + if (n < 0) + { n = -n; } - if (n == 0) { + if (n == 0) + { std::cout << "All non-zero numbers are divisors of 0 !" << std::endl; - } else { + } + else + { std::cout << "Number of positive divisors is : "; std::cout << number_of_positive_divisors(n) << std::endl; } diff --git a/math/power_for_huge_numbers.cpp b/math/power_for_huge_numbers.cpp index 301767d666e..1f969f89d10 100644 --- a/math/power_for_huge_numbers.cpp +++ b/math/power_for_huge_numbers.cpp @@ -22,13 +22,15 @@ * @param res large number representation using array * @param res_size number of digits in `res` */ -int multiply(int x, int res[], int res_size) { +int multiply(int x, int res[], int res_size) +{ // Initialize carry int carry = 0; // One by one multiply n with // individual digits of res[] - for (int i = 0; i < res_size; i++) { + for (int i = 0; i < res_size; i++) + { int prod = res[i] * x + carry; // Store last digit of @@ -41,7 +43,8 @@ int multiply(int x, int res[], int res_size) { // Put carry in res and // increase result size - while (carry) { + while (carry) + { res[res_size] = carry % 10; carry = carry / 10; res_size++; @@ -53,9 +56,11 @@ int multiply(int x, int res[], int res_size) { * @param x base * @param n exponent */ -void power(int x, int n) { +void power(int x, int n) +{ // printing value "1" for power = 0 - if (n == 0) { + if (n == 0) + { std::cout << "1"; return; } @@ -65,7 +70,8 @@ void power(int x, int n) { int temp = x; // Initialize result - while (temp != 0) { + while (temp != 0) + { res[res_size++] = temp % 10; temp = temp / 10; } @@ -79,7 +85,8 @@ void power(int x, int n) { } /** Main function */ -int main() { +int main() +{ int exponent, base; std::cout << "Enter base "; std::cin >> base; diff --git a/math/prime_factorization.cpp b/math/prime_factorization.cpp index d0e05cb4ca7..c650497e2d1 100644 --- a/math/prime_factorization.cpp +++ b/math/prime_factorization.cpp @@ -20,44 +20,55 @@ std::vector> factors; /** Calculating prime number upto a given range */ -void SieveOfEratosthenes(int N) { +void SieveOfEratosthenes(int N) +{ // initializes the array isprime memset(isprime, true, sizeof isprime); - for (int i = 2; i <= N; i++) { - if (isprime[i]) { + for (int i = 2; i <= N; i++) + { + if (isprime[i]) + { for (int j = 2 * i; j <= N; j += i) isprime[j] = false; } } - for (int i = 2; i <= N; i++) { - if (isprime[i]) prime_numbers.push_back(i); + for (int i = 2; i <= N; i++) + { + if (isprime[i]) + prime_numbers.push_back(i); } } /** Prime factorization of a number */ -void prime_factorization(int num) { +void prime_factorization(int num) +{ int number = num; - for (int i = 0; prime_numbers[i] <= num; i++) { + for (int i = 0; prime_numbers[i] <= num; i++) + { int count = 0; // termination condition - if (number == 1) { + if (number == 1) + { break; } - while (number % prime_numbers[i] == 0) { + while (number % prime_numbers[i] == 0) + { count++; number = number / prime_numbers[i]; } - if (count) factors.push_back(std::make_pair(prime_numbers[i], count)); + if (count) + factors.push_back(std::make_pair(prime_numbers[i], count)); } } /** Main program */ -int main() { +int main() +{ int num; std::cout << "\t\tComputes the prime factorization\n\n"; std::cout << "Type in a number: "; @@ -68,7 +79,8 @@ int main() { prime_factorization(num); // Prime factors with their powers in the given number in new line - for (auto it : factors) { + for (auto it : factors) + { std::cout << it.first << " " << it.second << std::endl; } diff --git a/math/prime_numbers.cpp b/math/prime_numbers.cpp index 4dd54f13657..b3a52a1042d 100644 --- a/math/prime_numbers.cpp +++ b/math/prime_numbers.cpp @@ -9,12 +9,15 @@ /** Generate an increasingly large number of primes * and store in a list */ -std::vector primes(int max) { +std::vector primes(int max) +{ max++; std::vector res; std::vector numbers(max, false); - for (int i = 2; i < max; i++) { - if (!numbers[i]) { + for (int i = 2; i < max; i++) + { + if (!numbers[i]) + { for (int j = i; j < max; j += i) numbers[j] = true; res.push_back(i); } @@ -23,7 +26,8 @@ std::vector primes(int max) { } /** main function */ -int main() { +int main() +{ std::cout << "Calculate primes up to:\n>> "; int n; std::cin >> n; diff --git a/math/primes_up_to_billion.cpp b/math/primes_up_to_billion.cpp index 4fb79a15e7c..6c02b9089f0 100644 --- a/math/primes_up_to_billion.cpp +++ b/math/primes_up_to_billion.cpp @@ -10,12 +10,15 @@ char prime[100000000]; /** Perform Sieve algorithm */ -void Sieve(int64_t n) { +void Sieve(int64_t n) +{ memset(prime, '1', sizeof(prime)); // intitize '1' to every index prime[0] = '0'; // 0 is not prime prime[1] = '0'; // 1 is not prime - for (int p = 2; p * p <= n; p++) { - if (prime[p] == '1') { + for (int p = 2; p * p <= n; p++) + { + if (prime[p] == '1') + { for (int i = p * p; i <= n; i += p) prime[i] = '0'; // set all multiples of p to false } @@ -23,7 +26,8 @@ void Sieve(int64_t n) { } /** Main function */ -int main() { +int main() +{ Sieve(100000000); int64_t n; std::cin >> n; // 10006187 diff --git a/math/sieve_of_eratosthenes.cpp b/math/sieve_of_eratosthenes.cpp index d8fa705313e..90ad8bc40b2 100644 --- a/math/sieve_of_eratosthenes.cpp +++ b/math/sieve_of_eratosthenes.cpp @@ -22,12 +22,16 @@ bool isprime[MAX]; * This is the function that finds the primes and eliminates * the multiples. */ -void sieve(uint32_t N) { +void sieve(uint32_t N) +{ isprime[0] = false; isprime[1] = false; - for (uint32_t i = 2; i <= N; i++) { - if (isprime[i]) { - for (uint32_t j = (i << 1); j <= N; j += i) { + for (uint32_t i = 2; i <= N; i++) + { + if (isprime[i]) + { + for (uint32_t j = (i << 1); j <= N; j += i) + { isprime[j] = false; } } @@ -37,9 +41,12 @@ void sieve(uint32_t N) { /** * This function prints out the primes to STDOUT */ -void print(uint32_t N) { - for (uint32_t i = 1; i <= N; i++) { - if (isprime[i]) { +void print(uint32_t N) +{ + for (uint32_t i = 1; i <= N; i++) + { + if (isprime[i]) + { std::cout << i << ' '; } } @@ -49,14 +56,17 @@ void print(uint32_t N) { /** * Initialize the array */ -void init() { - for (uint32_t i = 1; i < MAX; i++) { +void init() +{ + for (uint32_t i = 1; i < MAX; i++) + { isprime[i] = true; } } /** main function */ -int main() { +int main() +{ uint32_t N = 100; init(); sieve(N); diff --git a/math/sqrt_double.cpp b/math/sqrt_double.cpp index 1521b500a19..ffc83998ab5 100644 --- a/math/sqrt_double.cpp +++ b/math/sqrt_double.cpp @@ -13,8 +13,10 @@ /** Bisection method implemented for the function \f$x^2-a=0\f$ * whose roots are \f$\pm\sqrt{a}\f$ and only the positive root is returned. */ -double Sqrt(double a) { - if (a > 0 && a < 1) { +double Sqrt(double a) +{ + if (a > 0 && a < 1) + { return 1 / Sqrt(1 / a); } double l = 0, r = a; @@ -24,12 +26,17 @@ double Sqrt(double a) { double epsilon = 1e-12; */ double epsilon = 1e-12; - while (l <= r) { + while (l <= r) + { double mid = (l + r) / 2; - if (mid * mid > a) { + if (mid * mid > a) + { r = mid; - } else { - if (a - mid * mid < epsilon) { + } + else + { + if (a - mid * mid < epsilon) + { return mid; } l = mid; @@ -39,7 +46,8 @@ double Sqrt(double a) { } /** main function */ -int main() { +int main() +{ double n{}; std::cin >> n; assert(n >= 0); diff --git a/math/string_fibonacci.cpp b/math/string_fibonacci.cpp index eb9b6d7e1a7..401b04d2da8 100644 --- a/math/string_fibonacci.cpp +++ b/math/string_fibonacci.cpp @@ -21,41 +21,50 @@ * \param [in] b second number in string to add * \returns sum as a std::string */ -std::string add(std::string a, std::string b) { +std::string add(std::string a, std::string b) +{ std::string temp = ""; // carry flag int carry = 0; // fills up with zeros - while (a.length() < b.length()) { + while (a.length() < b.length()) + { a = "0" + a; } // fills up with zeros - while (b.length() < a.length()) { + while (b.length() < a.length()) + { b = "0" + b; } // adds the numbers a and b - for (int i = a.length() - 1; i >= 0; i--) { + for (int i = a.length() - 1; i >= 0; i--) + { char val = static_cast(((a[i] - 48) + (b[i] - 48)) + 48 + carry); - if (val > 57) { + if (val > 57) + { carry = 1; val -= 10; - } else { + } + else + { carry = 0; } temp = val + temp; } // processes the carry flag - if (carry == 1) { + if (carry == 1) + { temp = "1" + temp; } // removes leading zeros. - while (temp[0] == '0' && temp.length() > 1) { + while (temp[0] == '0' && temp.length() > 1) + { temp = temp.substr(1); } @@ -65,11 +74,13 @@ std::string add(std::string a, std::string b) { /** Fibonacci iterator * \param [in] n n^th Fibonacci number */ -void fib_Accurate(uint64_t n) { +void fib_Accurate(uint64_t n) +{ std::string tmp = ""; std::string fibMinus1 = "1"; std::string fibMinus2 = "0"; - for (uint64_t i = 0; i < n; i++) { + for (uint64_t i = 0; i < n; i++) + { tmp = add(fibMinus1, fibMinus2); fibMinus2 = fibMinus1; fibMinus1 = tmp; @@ -78,7 +89,8 @@ void fib_Accurate(uint64_t n) { } /** main function */ -int main() { +int main() +{ int n; std::cout << "Enter whatever number N you want to find the fibonacci of\n"; std::cin >> n; diff --git a/operations_on_datastructures/array_left_rotation.cpp b/operations_on_datastructures/array_left_rotation.cpp index 9eb5d4e5002..444738360a5 100644 --- a/operations_on_datastructures/array_left_rotation.cpp +++ b/operations_on_datastructures/array_left_rotation.cpp @@ -2,38 +2,38 @@ using namespace std; int main() { - int n, k; - cout << "Enter size of array=\t"; - cin >> n; - cout << "Enter Number of indeces u want to rotate the array to left=\t"; - cin >> k; - int a[n]; - cout << "Enter elements of array=\t"; - for (int i = 0; i < n; i++) - { - cin >> a[i]; - } - int temp = 0; - for (int i = 0; i < k; i++) - { - temp = a[0]; - for (int j = 0; j < n; j++) - { - if (j == n - 1) - { - a[n - 1] = temp; - } - else - { - a[j] = a[j + 1]; - } - } - } - cout << "Your rotated array is=\t"; - for (int j = 0; j < n; j++) - { - cout << a[j] << " "; - } - getchar(); - return 0; + int n, k; + cout << "Enter size of array=\t"; + cin >> n; + cout << "Enter Number of indeces u want to rotate the array to left=\t"; + cin >> k; + int a[n]; + cout << "Enter elements of array=\t"; + for (int i = 0; i < n; i++) + { + cin >> a[i]; + } + int temp = 0; + for (int i = 0; i < k; i++) + { + temp = a[0]; + for (int j = 0; j < n; j++) + { + if (j == n - 1) + { + a[n - 1] = temp; + } + else + { + a[j] = a[j + 1]; + } + } + } + cout << "Your rotated array is=\t"; + for (int j = 0; j < n; j++) + { + cout << a[j] << " "; + } + getchar(); + return 0; } diff --git a/operations_on_datastructures/array_right_rotation.cpp b/operations_on_datastructures/array_right_rotation.cpp index 81875766c14..5077d2d74cb 100644 --- a/operations_on_datastructures/array_right_rotation.cpp +++ b/operations_on_datastructures/array_right_rotation.cpp @@ -9,8 +9,7 @@ int main() cin >> k; int a[n]; cout << "Enter elements of array=\t"; - for (int i = 0; i < n; i++) - cin >> a[i]; + for (int i = 0; i < n; i++) cin >> a[i]; int temp = 0; for (int i = 0; i < k; i++) { diff --git a/operations_on_datastructures/circular_linked_list.cpp b/operations_on_datastructures/circular_linked_list.cpp index d360f6cd7f3..2fddd3b7b6d 100644 --- a/operations_on_datastructures/circular_linked_list.cpp +++ b/operations_on_datastructures/circular_linked_list.cpp @@ -3,112 +3,112 @@ using namespace std; struct node { - int val; - node *next; + int val; + node *next; }; node *start; void insert(int x) { - node *t = start; + node *t = start; - if (start != NULL) - { - while (t->next != start) - { - t = t->next; - } - node *n = new node; - t->next = n; - n->val = x; - n->next = start; - } - else - { - node *n = new node; - n->val = x; - start = n; - n->next = start; - } + if (start != NULL) + { + while (t->next != start) + { + t = t->next; + } + node *n = new node; + t->next = n; + n->val = x; + n->next = start; + } + else + { + node *n = new node; + n->val = x; + start = n; + n->next = start; + } } void remove(int x) { - node *t = start; - node *p; - while (t->val != x) - { - p = t; - t = t->next; - } - p->next = t->next; - delete t; + node *t = start; + node *p; + while (t->val != x) + { + p = t; + t = t->next; + } + p->next = t->next; + delete t; } void search(int x) { - node *t = start; - int found = 0; - while (t->next != start) - { - if (t->val == x) - { - cout << "\nFound"; - found = 1; - break; - } - t = t->next; - } - if (found == 0) - { - cout << "\nNot Found"; - } + node *t = start; + int found = 0; + while (t->next != start) + { + if (t->val == x) + { + cout << "\nFound"; + found = 1; + break; + } + t = t->next; + } + if (found == 0) + { + cout << "\nNot Found"; + } } void show() { - node *t = start; - do - { - cout << t->val << "\t"; - t = t->next; - } while (t != start); + node *t = start; + do + { + cout << t->val << "\t"; + t = t->next; + } while (t != start); } int main() { - int choice, x; - do - { - cout << "\n1. Insert"; - cout << "\n2. Delete"; - cout << "\n3. Search"; - cout << "\n4. Print"; - cout << "\n\nEnter you choice : "; - cin >> choice; - switch (choice) - { - case 1: - cout << "\nEnter the element to be inserted : "; - cin >> x; - insert(x); - break; - case 2: - cout << "\nEnter the element to be removed : "; - cin >> x; - remove(x); - break; - case 3: - cout << "\nEnter the element to be searched : "; - cin >> x; - search(x); - break; - case 4: - show(); - break; - } - } while (choice != 0); + int choice, x; + do + { + cout << "\n1. Insert"; + cout << "\n2. Delete"; + cout << "\n3. Search"; + cout << "\n4. Print"; + cout << "\n\nEnter you choice : "; + cin >> choice; + switch (choice) + { + case 1: + cout << "\nEnter the element to be inserted : "; + cin >> x; + insert(x); + break; + case 2: + cout << "\nEnter the element to be removed : "; + cin >> x; + remove(x); + break; + case 3: + cout << "\nEnter the element to be searched : "; + cin >> x; + search(x); + break; + case 4: + show(); + break; + } + } while (choice != 0); - return 0; + return 0; } diff --git a/operations_on_datastructures/circular_queue_using_array.cpp b/operations_on_datastructures/circular_queue_using_array.cpp index 36d7e22c33d..cf6e39dd597 100644 --- a/operations_on_datastructures/circular_queue_using_array.cpp +++ b/operations_on_datastructures/circular_queue_using_array.cpp @@ -8,67 +8,66 @@ int count = 0; void Enque(int x) { - if (count == 10) - { - cout << "\nOverflow"; - } - else - { - queue[rear] = x; - rear = (rear + 1) % 10; - count++; - } + if (count == 10) + { + cout << "\nOverflow"; + } + else + { + queue[rear] = x; + rear = (rear + 1) % 10; + count++; + } } void Deque() { - if (front == rear) - { - cout << "\nUnderflow"; - } + if (front == rear) + { + cout << "\nUnderflow"; + } - else - { - cout << "\n" - << queue[front] << " deleted"; - front = (front + 1) % 10; - count--; - } + else + { + cout << "\n" << queue[front] << " deleted"; + front = (front + 1) % 10; + count--; + } } void show() { - for (int i = 0; i < count; i++) - { - cout << queue[(i + front) % 10] << "\t"; - } + for (int i = 0; i < count; i++) + { + cout << queue[(i + front) % 10] << "\t"; + } } int main() { - int ch, x; - do - { - cout << "\n1. Enque"; - cout << "\n2. Deque"; - cout << "\n3. Print"; - cout << "\nEnter Your Choice : "; - cin >> ch; - if (ch == 1) - { - cout << "\nInsert : "; - cin >> x; - Enque(x); - } - else if (ch == 2) - { - Deque(); - } - else if (ch == 3) - { - show(); - } - } while (ch != 0); + int ch, x; + do + { + cout << "\n1. Enque"; + cout << "\n2. Deque"; + cout << "\n3. Print"; + cout << "\nEnter Your Choice : "; + cin >> ch; + if (ch == 1) + { + cout << "\nInsert : "; + cin >> x; + Enque(x); + } + else if (ch == 2) + { + Deque(); + } + else if (ch == 3) + { + show(); + } + } while (ch != 0); - return 0; + return 0; } diff --git a/operations_on_datastructures/get_size_of_linked_list.cpp b/operations_on_datastructures/get_size_of_linked_list.cpp index 84f8db07fb8..0f22967c293 100644 --- a/operations_on_datastructures/get_size_of_linked_list.cpp +++ b/operations_on_datastructures/get_size_of_linked_list.cpp @@ -1,6 +1,7 @@ #include -class Node { +class Node +{ public: int val; Node *next; @@ -8,19 +9,23 @@ class Node { Node(int v, Node *n) : val(v), next(n) {} // Default constructor for Node }; -int getSize(Node *root) { - if (root == NULL) { +int getSize(Node *root) +{ + if (root == NULL) + { return 0; } // Each node will return 1 so the total adds up to be the size return 1 + getSize(root->next); } -int main() { +int main() +{ Node *myList = new Node(0, NULL); // Initializes the LinkedList Node *temp = myList; // Creates a linked lists of total size 10, numbered 1 - 10 - for (int i = 1; i < 10; i++) { + for (int i = 1; i < 10; i++) + { temp->next = new Node(i, NULL); temp = temp->next; } diff --git a/operations_on_datastructures/intersection_of_2_arrays.cpp b/operations_on_datastructures/intersection_of_2_arrays.cpp index 05652811f43..df83c9f2139 100644 --- a/operations_on_datastructures/intersection_of_2_arrays.cpp +++ b/operations_on_datastructures/intersection_of_2_arrays.cpp @@ -1,31 +1,29 @@ #include int main() { - int i, j, m, n; - cout << "Enter size of array 1:"; - cin >> m; - cout << "Enter size of array 2:"; - cin >> n; - int a[m]; - int b[n]; - cout << "Enter elements of array 1:"; - for (i = 0; i < m; i++) - cin >> a[i]; - for (i = 0; i < n; i++) - cin >> b[i]; - i = 0; - j = 0; - while ((i < m) && (j < n)) - { - if (a[i] < b[j]) - i++; - else if (a[i] > b[j]) - j++; - else + int i, j, m, n; + cout << "Enter size of array 1:"; + cin >> m; + cout << "Enter size of array 2:"; + cin >> n; + int a[m]; + int b[n]; + cout << "Enter elements of array 1:"; + for (i = 0; i < m; i++) cin >> a[i]; + for (i = 0; i < n; i++) cin >> b[i]; + i = 0; + j = 0; + while ((i < m) && (j < n)) { - cout << a[i++] << " "; - j++; + if (a[i] < b[j]) + i++; + else if (a[i] > b[j]) + j++; + else + { + cout << a[i++] << " "; + j++; + } } - } - return 0; + return 0; } diff --git a/operations_on_datastructures/reverse_a_linked_list_using_recusion.cpp b/operations_on_datastructures/reverse_a_linked_list_using_recusion.cpp index 0908080cc81..4fe6d291523 100644 --- a/operations_on_datastructures/reverse_a_linked_list_using_recusion.cpp +++ b/operations_on_datastructures/reverse_a_linked_list_using_recusion.cpp @@ -3,74 +3,74 @@ using namespace std; struct node { - int val; - node *next; + int val; + node *next; }; node *start; void insert(int x) { - node *t = start; - if (start != NULL) - { - while (t->next != NULL) - { - t = t->next; - } - node *n = new node; - t->next = n; - n->val = x; - n->next = NULL; - } - else - { - node *n = new node; - n->val = x; - n->next = NULL; - start = n; - } + node *t = start; + if (start != NULL) + { + while (t->next != NULL) + { + t = t->next; + } + node *n = new node; + t->next = n; + n->val = x; + n->next = NULL; + } + else + { + node *n = new node; + n->val = x; + n->next = NULL; + start = n; + } } void reverse(node *p, node *q) { - if (q->next == NULL) - { - q->next = p; - p->next = NULL; - start = q; - return; - } - else - { - reverse(q, q->next); - q->next = p; - p->next = NULL; - } + if (q->next == NULL) + { + q->next = p; + p->next = NULL; + start = q; + return; + } + else + { + reverse(q, q->next); + q->next = p; + p->next = NULL; + } } void show() { - node *t = start; - while (t != NULL) - { - cout << t->val << "\t"; - t = t->next; - } + node *t = start; + while (t != NULL) + { + cout << t->val << "\t"; + t = t->next; + } } int main() { - insert(1); - insert(2); - insert(3); - insert(4); - insert(5); - insert(6); + insert(1); + insert(2); + insert(3); + insert(4); + insert(5); + insert(6); - reverse(start, start->next); + reverse(start, start->next); - show(); + show(); - return 0; + return 0; } diff --git a/operations_on_datastructures/selectionsortlinkedlist.cpp b/operations_on_datastructures/selectionsortlinkedlist.cpp index 52363ceffe7..550928d01d6 100644 --- a/operations_on_datastructures/selectionsortlinkedlist.cpp +++ b/operations_on_datastructures/selectionsortlinkedlist.cpp @@ -1,10 +1,10 @@ #include using namespace std; -//node defined +// node defined class node { -public: + public: int data; node *link; node(int d) @@ -14,7 +14,7 @@ class node } }; -//printing the linked list +// printing the linked list void print(node *head) { node *current = head; @@ -26,7 +26,7 @@ void print(node *head) cout << endl; } -//creating the linked list with 'n' nodes +// creating the linked list with 'n' nodes node *createlist(int n) { node *head = NULL; @@ -50,51 +50,71 @@ node *createlist(int n) return head; } -//performing selection sort on the linked list in an iterative manner +// performing selection sort on the linked list in an iterative manner void my_selection_sort_linked_list(node *&head) { - node *min = head; //throughout the algorithm 'min' is used to denote the node with min value out of all the nodes left for scanning - //while scanning if we find a node 'X' with value lesser than min, - //then we update the pointers in such a way that 'X' becomes the predecessor of 'min' - node *current = min->link; // 'current' refers to the current node we are scanning - node *previous = min; //'previous' refers to the node that is previous to the current node - node *temp = NULL; // 'temp' in this algo is used to point to the last node of the sorted part of the linked list. - //eg. If at any time instance the state of the linked list is suppose 1->2->5->3->8->NULL - //then, we see that "1->2" is the sorted part of the LL, and therefore temp will be pointing to the last node of the sorted part,i.e,'2' - //We keep on arranging the Linked list in such a way that after each iteration the node with 'min' value is placed at its correct position. - //Eg. Let suppose initially we have 5->4->1->3->2->NULL - //After 1st iteration : 1->4->5->3->2->NULL and so on + node *min = head; // throughout the algorithm 'min' is used to denote the + // node with min value out of all the nodes left for + // scanning while scanning if we find a node 'X' with + // value lesser than min, then we update the pointers in + // such a way that 'X' becomes the predecessor of 'min' + node *current = + min->link; // 'current' refers to the current node we are scanning + node *previous = min; //'previous' refers to the node that is previous to + //the current node + node *temp = + NULL; // 'temp' in this algo is used to point to the last node of the + // sorted part of the linked list. + // eg. If at any time instance the state of the linked list is + // suppose 1->2->5->3->8->NULL then, we see that "1->2" is the + // sorted part of the LL, and therefore temp will be pointing to + // the last node of the sorted part,i.e,'2' We keep on arranging + // the Linked list in such a way that after each iteration the + // node with 'min' value is placed at its correct position. Eg. + // Let suppose initially we have 5->4->1->3->2->NULL After 1st + // iteration : 1->4->5->3->2->NULL and so on - while (min->link != NULL) //so that all the nodes are scanned or until there exists a node + while ( + min->link != + NULL) // so that all the nodes are scanned or until there exists a node { - //pick the first node from the unsorted part and assume that it is the minimum and then start scanning from the next node + // pick the first node from the unsorted part and assume that it is the + // minimum and then start scanning from the next node - while (current != NULL) //suppose you choose the min node to be X, then scan starts from the (X+1)th node until its NULL. current = (X+1)th node and min = X + while (current != NULL) // suppose you choose the min node to be X, + // then scan starts from the (X+1)th node until + // its NULL. current = (X+1)th node and min = X { - if (current->data < min->data) //if the current node is smaller than the presumed node 'min' + if (current->data < min->data) // if the current node is smaller + // than the presumed node 'min' { - if (temp == NULL) //temp stays null for the first iteration, therefore it symbolizes that we are scanning for the first time + if (temp == NULL) // temp stays null for the first iteration, + // therefore it symbolizes that we are + // scanning for the first time { - if (previous == min) //if the 'previous' is pointing to the 'min' node + if (previous == + min) // if the 'previous' is pointing to the 'min' node { - //Update the pointers - head = current; //update the head pointer with the current node + // Update the pointers + head = current; // update the head pointer with the + // current node min->link = current->link; current->link = previous; min = current; current = previous->link; } - else //if the 'previous' is not pointing to the 'min' node + else // if the 'previous' is not pointing to the 'min' node { - //Update the pointers - head = current; //update the head pointer with the current node + // Update the pointers + head = current; // update the head pointer with the + // current node previous->link = current->link; current->link = min; min = current; current = previous->link; } } - else //if 'temp' is not NULL, i.e., its not the 1st iteration + else // if 'temp' is not NULL, i.e., its not the 1st iteration { temp->link = current; previous->link = current->link; @@ -103,15 +123,17 @@ void my_selection_sort_linked_list(node *&head) current = previous->link; } } - else //if the current node is greater than min, just move the previous and the current pointer a step further + else // if the current node is greater than min, just move the + // previous and the current pointer a step further { previous = previous->link; current = current->link; } } - //update the pointers. Set 'temp' to the last node in the sorted part. Make 'min' move a step further so that 'min' points to the 1st node of the unsorted part - //start the iteration again + // update the pointers. Set 'temp' to the last node in the sorted part. + // Make 'min' move a step further so that 'min' points to the 1st node of + // the unsorted part start the iteration again temp = min; min = min->link; previous = min; @@ -145,15 +167,16 @@ int main() { node *head = NULL; int n; - cout << "enter the no. of nodes : "; //taking input from user about the number of nodes in linked list + cout << "enter the no. of nodes : "; // taking input from user about the + // number of nodes in linked list cin >> n; if (n == 0) return 0; - head = createlist(n); //creating the list + head = createlist(n); // creating the list cout << "original list is : "; - print(head); //printing the original linked list - my_selection_sort_linked_list(head); //applying selection sort + print(head); // printing the original linked list + my_selection_sort_linked_list(head); // applying selection sort cout << "sorted list is : "; - print(head); //printing the sorted linked list + print(head); // printing the sorted linked list return 0; } \ No newline at end of file diff --git a/operations_on_datastructures/union_of_2_arrays.cpp b/operations_on_datastructures/union_of_2_arrays.cpp index aaaeb83781b..45845f341e8 100644 --- a/operations_on_datastructures/union_of_2_arrays.cpp +++ b/operations_on_datastructures/union_of_2_arrays.cpp @@ -1,34 +1,30 @@ #include int main() { - int m, n, i = 0, j = 0; - cout << "Enter size of both arrays:"; - cin >> m >> n; - int a[m]; - int b[n]; - cout << "Enter elements of array 1:"; - for (i = 0; i < m; i++) - cin >> a[i]; - cout << "Enter elements of array 2:"; - for (i = 0; i < n; i++) - cin >> b[i]; - i = 0; - j = 0; - while ((i < m) && (j < n)) - { - if (a[i] < b[j]) - cout << a[i++] << " "; - else if (a[i] > b[j]) - cout << b[j++] << " "; - else + int m, n, i = 0, j = 0; + cout << "Enter size of both arrays:"; + cin >> m >> n; + int a[m]; + int b[n]; + cout << "Enter elements of array 1:"; + for (i = 0; i < m; i++) cin >> a[i]; + cout << "Enter elements of array 2:"; + for (i = 0; i < n; i++) cin >> b[i]; + i = 0; + j = 0; + while ((i < m) && (j < n)) { - cout << a[i++]; - j++; + if (a[i] < b[j]) + cout << a[i++] << " "; + else if (a[i] > b[j]) + cout << b[j++] << " "; + else + { + cout << a[i++]; + j++; + } } - } - while (i < m) - cout << a[i++] << " "; - while (j < n) - cout << b[j++] << " "; - return 0; + while (i < m) cout << a[i++] << " "; + while (j < n) cout << b[j++] << " "; + return 0; } diff --git a/others/buzz_number.cpp b/others/buzz_number.cpp index ed9fc5f2888..712b79401c5 100644 --- a/others/buzz_number.cpp +++ b/others/buzz_number.cpp @@ -6,10 +6,12 @@ #include /** main function */ -int main() { +int main() +{ int n, t; std::cin >> t; - while (t--) { + while (t--) + { std::cin >> n; if ((n % 7 == 0) || (n % 10 == 7)) std::cout << n << " is a buzz number" << std::endl; diff --git a/others/decimal_to_binary.cpp b/others/decimal_to_binary.cpp index 11ce064a538..32616944f2d 100644 --- a/others/decimal_to_binary.cpp +++ b/others/decimal_to_binary.cpp @@ -8,10 +8,12 @@ * This method converts the bit representation and stores it as a decimal * number. */ -void method1(int number) { +void method1(int number) +{ int remainder, binary = 0, var = 1; - do { + do + { remainder = number % 2; number = number / 2; binary = binary + (remainder * var); @@ -24,11 +26,13 @@ void method1(int number) { * This method stores each bit value from LSB to MSB and then prints them back * from MSB to LSB */ -void method2(int number) { +void method2(int number) +{ int num_bits = 0; char bit_string[50]; - do { + do + { bool bit = number & 0x01; // get last bit if (bit) bit_string[num_bits++] = '1'; @@ -43,7 +47,8 @@ void method2(int number) { std::cout << std::endl; } -int main() { +int main() +{ int number; std::cout << "Enter a number:"; std::cin >> number; diff --git a/others/decimal_to_hexadecimal.cpp b/others/decimal_to_hexadecimal.cpp index a3e544f49f8..f0a521db6f7 100644 --- a/others/decimal_to_hexadecimal.cpp +++ b/others/decimal_to_hexadecimal.cpp @@ -8,7 +8,8 @@ /** * Main program */ -int main(void) { +int main(void) +{ int valueToConvert = 0; // Holds user input int hexArray[8]; // Contains hex values backwards int i = 0; // counter @@ -19,7 +20,8 @@ int main(void) { std::cin >> valueToConvert; // Stores value into valueToConvert via user input - while (valueToConvert > 15) { // Dec to Hex Algorithm + while (valueToConvert > 15) + { // Dec to Hex Algorithm hexArray[i++] = valueToConvert % 16; // Gets remainder valueToConvert /= 16; // valueToConvert >>= 4; // This will divide by 2^4=16 and is faster diff --git a/others/decimal_to_roman_numeral.cpp b/others/decimal_to_roman_numeral.cpp index 6bd1be39511..fbcbaa2322b 100644 --- a/others/decimal_to_roman_numeral.cpp +++ b/others/decimal_to_roman_numeral.cpp @@ -12,7 +12,8 @@ /** This functions fills a string with character c, n times and returns it * @note This can probably be replace by `memcpy` function. */ -std::string fill(char c, int n) { +std::string fill(char c, int n) +{ std::string s = ""; while (n--) s += c; return s; @@ -21,51 +22,76 @@ std::string fill(char c, int n) { /** to convert to lowercase Roman Numeral * the function works recursively */ -std::string tolowerRoman(int n) { - if (n < 4) return fill('i', n); - if (n < 6) return fill('i', 5 - n) + "v"; - if (n < 9) return std::string("v") + fill('i', n - 5); - if (n < 11) return fill('i', 10 - n) + "x"; - if (n < 40) return fill('x', n / 10) + tolowerRoman(n % 10); - if (n < 60) return fill('x', 5 - n / 10) + 'l' + tolowerRoman(n % 10); +std::string tolowerRoman(int n) +{ + if (n < 4) + return fill('i', n); + if (n < 6) + return fill('i', 5 - n) + "v"; + if (n < 9) + return std::string("v") + fill('i', n - 5); + if (n < 11) + return fill('i', 10 - n) + "x"; + if (n < 40) + return fill('x', n / 10) + tolowerRoman(n % 10); + if (n < 60) + return fill('x', 5 - n / 10) + 'l' + tolowerRoman(n % 10); if (n < 90) return std::string("l") + fill('x', n / 10 - 5) + tolowerRoman(n % 10); - if (n < 110) return fill('x', 10 - n / 10) + "c" + tolowerRoman(n % 10); - if (n < 400) return fill('c', n / 100) + tolowerRoman(n % 100); - if (n < 600) return fill('c', 5 - n / 100) + 'd' + tolowerRoman(n % 100); + if (n < 110) + return fill('x', 10 - n / 10) + "c" + tolowerRoman(n % 10); + if (n < 400) + return fill('c', n / 100) + tolowerRoman(n % 100); + if (n < 600) + return fill('c', 5 - n / 100) + 'd' + tolowerRoman(n % 100); if (n < 900) return std::string("d") + fill('c', n / 100 - 5) + tolowerRoman(n % 100); - if (n < 1100) return fill('c', 10 - n / 100) + "m" + tolowerRoman(n % 100); - if (n < 4000) return fill('m', n / 1000) + tolowerRoman(n % 1000); + if (n < 1100) + return fill('c', 10 - n / 100) + "m" + tolowerRoman(n % 100); + if (n < 4000) + return fill('m', n / 1000) + tolowerRoman(n % 1000); return "?"; } /** to convert to uppercase Roman Numeral * the function works recursively */ -std::string toupperRoman(int n) { - if (n < 4) return fill('I', n); - if (n < 6) return fill('I', 5 - n) + "V"; - if (n < 9) return std::string("V") + fill('I', n - 5); - if (n < 11) return fill('I', 10 - n) + "X"; - if (n < 40) return fill('X', n / 10) + toupperRoman(n % 10); - if (n < 60) return fill('X', 5 - n / 10) + 'L' + toupperRoman(n % 10); +std::string toupperRoman(int n) +{ + if (n < 4) + return fill('I', n); + if (n < 6) + return fill('I', 5 - n) + "V"; + if (n < 9) + return std::string("V") + fill('I', n - 5); + if (n < 11) + return fill('I', 10 - n) + "X"; + if (n < 40) + return fill('X', n / 10) + toupperRoman(n % 10); + if (n < 60) + return fill('X', 5 - n / 10) + 'L' + toupperRoman(n % 10); if (n < 90) return std::string("L") + fill('X', n / 10 - 5) + toupperRoman(n % 10); - if (n < 110) return fill('X', 10 - n / 10) + "C" + toupperRoman(n % 10); - if (n < 400) return fill('C', n / 100) + toupperRoman(n % 100); - if (n < 600) return fill('C', 5 - n / 100) + 'D' + toupperRoman(n % 100); + if (n < 110) + return fill('X', 10 - n / 10) + "C" + toupperRoman(n % 10); + if (n < 400) + return fill('C', n / 100) + toupperRoman(n % 100); + if (n < 600) + return fill('C', 5 - n / 100) + 'D' + toupperRoman(n % 100); if (n < 900) return std::string("D") + fill('C', n / 100 - 5) + toupperRoman(n % 100); - if (n < 1100) return fill('C', 10 - n / 100) + "M" + toupperRoman(n % 100); - if (n < 4000) return fill('M', n / 1000) + toupperRoman(n % 1000); + if (n < 1100) + return fill('C', 10 - n / 100) + "M" + toupperRoman(n % 100); + if (n < 4000) + return fill('M', n / 1000) + toupperRoman(n % 1000); return "?"; } /** main function */ -int main() { +int main() +{ int n; std::cout << "\t\tRoman numbers converter\n\n"; std::cout << "Type in decimal number between 0 up to 4000 (exclusive): "; diff --git a/others/fast_interger_input.cpp b/others/fast_interger_input.cpp index 5e7bcb99d28..a71e807dd89 100644 --- a/others/fast_interger_input.cpp +++ b/others/fast_interger_input.cpp @@ -8,7 +8,8 @@ /** Function to read the number from stdin. The function reads input until a non * numeric character is entered. */ -void fastinput(int *number) { +void fastinput(int *number) +{ // variable to indicate sign of input integer bool negative = false; register int c; @@ -16,7 +17,8 @@ void fastinput(int *number) { // extract current character from buffer c = std::getchar(); - if (c == '-') { + if (c == '-') + { // number is negative negative = true; @@ -31,11 +33,13 @@ void fastinput(int *number) { // if scanned input has a negative sign, negate the // value of the input number - if (negative) *(number) *= -1; + if (negative) + *(number) *= -1; } /** Main function */ -int main() { +int main() +{ int number; fastinput(&number); std::cout << number << std::endl; diff --git a/others/happy_number.cpp b/others/happy_number.cpp index b1debaa54db..494891e3b4e 100644 --- a/others/happy_number.cpp +++ b/others/happy_number.cpp @@ -11,10 +11,13 @@ * \returns true if happy else false */ template -bool is_happy(T n) { - T s = 0; // stores sum of digits - while (n > 9) { // while number is > 9, there are more than 1 digit - while (n != 0) { // get digit +bool is_happy(T n) +{ + T s = 0; // stores sum of digits + while (n > 9) + { // while number is > 9, there are more than 1 digit + while (n != 0) + { // get digit T d = n % 10; s += d; n /= 10; @@ -26,7 +29,8 @@ bool is_happy(T n) { } /** Main function */ -int main() { +int main() +{ int n; std::cout << "Enter a number:"; std::cin >> n; diff --git a/others/matrix_exponentiation.cpp b/others/matrix_exponentiation.cpp index d44d225937c..78daca8ec74 100644 --- a/others/matrix_exponentiation.cpp +++ b/others/matrix_exponentiation.cpp @@ -58,11 +58,15 @@ vector a, b, c; * \result matrix of dimension (m\f$\times\f$q) */ vector> multiply(const vector> &A, - const vector> &B) { + const vector> &B) +{ vector> C(k + 1, vector(k + 1)); - for (ll i = 1; i <= k; i++) { - for (ll j = 1; j <= k; j++) { - for (ll z = 1; z <= k; z++) { + for (ll i = 1; i <= k; i++) + { + for (ll j = 1; j <= k; j++) + { + for (ll z = 1; z <= k; z++) + { C[i][j] = (C[i][j] + (A[i][z] * B[z][j]) % MOD) % MOD; } } @@ -76,12 +80,16 @@ vector> multiply(const vector> &A, * \param [in] p exponent * \return matrix of same dimension as A */ -vector> power(const vector> &A, ll p) { +vector> power(const vector> &A, ll p) +{ if (p == 1) return A; - if (p % 2 == 1) { + if (p % 2 == 1) + { return multiply(A, power(A, p - 1)); - } else { + } + else + { vector> X = power(A, p / 2); return multiply(X, X); } @@ -91,7 +99,8 @@ vector> power(const vector> &A, ll p) { * \param[in] n \f$n^\text{th}\f$ Fibonacci number * \return \f$n^\text{th}\f$ Fibonacci number */ -ll ans(ll n) { +ll ans(ll n) +{ if (n == 0) return 0; if (n <= k) @@ -102,9 +111,12 @@ ll ans(ll n) { // Transpose matrix vector> T(k + 1, vector(k + 1)); - for (ll i = 1; i <= k; i++) { - for (ll j = 1; j <= k; j++) { - if (i < k) { + for (ll i = 1; i <= k; i++) + { + for (ll j = 1; j <= k; j++) + { + if (i < k) + { if (j == i + 1) T[i][j] = 1; else @@ -119,26 +131,31 @@ ll ans(ll n) { // T*F1 ll res = 0; - for (ll i = 1; i <= k; i++) { + for (ll i = 1; i <= k; i++) + { res = (res + (T[1][i] * F1[i]) % MOD) % MOD; } return res; } /** Main function */ -int main() { +int main() +{ cin.tie(0); cout.tie(0); ll t; cin >> t; ll i, j, x; - while (t--) { + while (t--) + { cin >> k; - for (i = 0; i < k; i++) { + for (i = 0; i < k; i++) + { cin >> x; b.pb(x); } - for (i = 0; i < k; i++) { + for (i = 0; i < k; i++) + { cin >> x; c.pb(x); } diff --git a/others/palindrome_of_number.cpp b/others/palindrome_of_number.cpp index 66401ff966a..d6ed3fc7080 100644 --- a/others/palindrome_of_number.cpp +++ b/others/palindrome_of_number.cpp @@ -16,7 +16,8 @@ #endif /** Main function */ -int main() { +int main() +{ int num; std::cout << "Enter number = "; std::cin >> num; diff --git a/others/paranthesis_matching.cpp b/others/paranthesis_matching.cpp index ef5da6e47cc..95a9e11003d 100644 --- a/others/paranthesis_matching.cpp +++ b/others/paranthesis_matching.cpp @@ -33,41 +33,53 @@ char pop() { return stack[top--]; } /** return opening paranthesis corresponding to the close paranthesis * @param[in] ch closed paranthesis character */ -char opening(char ch) { - switch (ch) { - case '}': - return '{'; - case ']': - return '['; - case ')': - return '('; - case '>': - return '<'; +char opening(char ch) +{ + switch (ch) + { + case '}': + return '{'; + case ']': + return '['; + case ')': + return '('; + case '>': + return '<'; } return '\0'; } -int main() { +int main() +{ std::string exp; int valid = 1, i = 0; std::cout << "Enter The Expression : "; std::cin >> exp; - while (valid == 1 && i < exp.length()) { - if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[' || exp[i] == '<') { + while (valid == 1 && i < exp.length()) + { + if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[' || exp[i] == '<') + { push(exp[i]); - } else if (top >= 0 && stack[top] == opening(exp[i])) { + } + else if (top >= 0 && stack[top] == opening(exp[i])) + { pop(); - } else { + } + else + { valid = 0; } i++; } // makes sure the stack is empty after processsing (above) - if (valid == 1 && top == -1) { + if (valid == 1 && top == -1) + { std::cout << "\nCorrect Expression"; - } else { + } + else + { std::cout << "\nWrong Expression"; } diff --git a/others/pascal_triangle.cpp b/others/pascal_triangle.cpp index 4ea58f3f1e4..814b9a14244 100644 --- a/others/pascal_triangle.cpp +++ b/others/pascal_triangle.cpp @@ -15,9 +15,12 @@ * \param [in] arr 2D-array containing Pascal numbers * \param [in] n depth of Pascal triangle to print */ -void show_pascal(int **arr, int n) { - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n + i; ++j) { +void show_pascal(int **arr, int n) +{ + for (int i = 0; i < n; ++i) + { + for (int j = 0; j < n + i; ++j) + { if (arr[i][j] == 0) std::cout << std::setw(4) << " "; else @@ -33,9 +36,12 @@ void show_pascal(int **arr, int n) { * \param [in] n depth of Pascal triangle to print * \result arr pointer returned */ -int **pascal_triangle(int **arr, int n) { - for (int i = 0; i < n; ++i) { - for (int j = n - i - 1; j < n + i; ++j) { +int **pascal_triangle(int **arr, int n) +{ + for (int i = 0; i < n; ++i) + { + for (int j = n - i - 1; j < n + i; ++j) + { if (j == n - i - 1 || j == n + i - 1) arr[i][j] = 1; // The edge of the Pascal triangle goes in 1 else @@ -49,7 +55,8 @@ int **pascal_triangle(int **arr, int n) { /** * main function */ -int main() { +int main() +{ int n = 0; std::cout << "Set Pascal's Triangle Height" << std::endl; @@ -57,7 +64,8 @@ int main() { // memory allocation (Assign two-dimensional array to store Pascal triangle) int **arr = new int *[n]; - for (int i = 0; i < n; ++i) { + for (int i = 0; i < n; ++i) + { arr[i] = new int[2 * n - 1]; memset(arr[i], 0, sizeof(int) * (2 * n - 1)); } @@ -66,7 +74,8 @@ int main() { show_pascal(arr, n); // deallocation - for (int i = 0; i < n; ++i) { + for (int i = 0; i < n; ++i) + { delete[] arr[i]; } delete[] arr; diff --git a/others/primality_test.cpp b/others/primality_test.cpp index faec6589cff..16700ec4a80 100644 --- a/others/primality_test.cpp +++ b/others/primality_test.cpp @@ -15,12 +15,14 @@ * \param[in] number number to check * \returns true if prime else false */ -bool IsPrime(int number) { +bool IsPrime(int number) +{ if (((!(number & 1)) && number != 2) || (number < 2) || (number % 3 == 0 && number != 3)) return false; - for (int k = 1; 36 * k * k - 12 * k < number; ++k) { + for (int k = 1; 36 * k * k - 12 * k < number; ++k) + { if ((number % (6 * k + 1) == 0) || (number % (6 * k - 1) == 0)) return false; } @@ -28,7 +30,8 @@ bool IsPrime(int number) { } /** main function */ -int main() { +int main() +{ // Main Function std::cout << "Enter the value of n to check if Prime\n"; int n; diff --git a/others/smallest_circle.cpp b/others/smallest_circle.cpp index 9ee4353eb4e..5842a33c8ae 100644 --- a/others/smallest_circle.cpp +++ b/others/smallest_circle.cpp @@ -12,7 +12,8 @@ #include /** Define a point */ -struct Point { +struct Point +{ double x, /**< abscissa */ y; /**< ordinate */ @@ -20,7 +21,8 @@ struct Point { * \param [in] a absicca (default = 0.0) * \param [in] b ordinate (default = 0.0) */ - explicit Point(double a = 0.f, double b = 0.f) { + explicit Point(double a = 0.f, double b = 0.f) + { x = a; y = b; } @@ -34,7 +36,8 @@ struct Point { * \param [in] B point B * \return ditance */ -double LenghtLine(const Point &A, const Point &B) { +double LenghtLine(const Point &A, const Point &B) +{ double dx = B.x - A.x; double dy = B.y - A.y; return std::sqrt((dx * dx) + (dy * dy)); @@ -51,7 +54,8 @@ double LenghtLine(const Point &A, const Point &B) { * \param [in] C vertex C * \returns area of triangle */ -double TriangleArea(const Point &A, const Point &B, const Point &C) { +double TriangleArea(const Point &A, const Point &B, const Point &C) +{ double a = LenghtLine(A, B); double b = LenghtLine(B, C); double c = LenghtLine(C, A); @@ -69,8 +73,10 @@ double TriangleArea(const Point &A, const Point &B, const Point &C) { * \returns True if P lies on or within the circle * \returns False if P lies outside the circle */ -bool PointInCircle(const std::vector &P, const Point &Center, double R) { - for (size_t i = 0; i < P.size(); i++) { +bool PointInCircle(const std::vector &P, const Point &Center, double R) +{ + for (size_t i = 0; i < P.size(); i++) + { if (LenghtLine(P[i], Center) > R) return false; } @@ -84,7 +90,8 @@ bool PointInCircle(const std::vector &P, const Point &Center, double R) { * \param [in] P vector of points * \returns radius of the circle */ -double circle(const std::vector &P) { +double circle(const std::vector &P) +{ double minR = INFINITY; double R; Point C; @@ -96,7 +103,8 @@ double circle(const std::vector &P) { // for every subsequent point in the list for (size_t j = i + 1; j < P.size(); j++) // for every subsequent point in the list - for (size_t k = j + 1; k < P.size(); k++) { + for (size_t k = j + 1; k < P.size(); k++) + { // here, we now have picked three points from the given set of // points that we can use // viz., P[i], P[j] and P[k] @@ -121,10 +129,12 @@ double circle(const std::vector &P) { R = (LenghtLine(P[i], P[j]) * LenghtLine(P[j], P[k]) * LenghtLine(P[k], P[i])) / (4 * TriangleArea(P[i], P[j], P[k])); - if (!PointInCircle(P, C, R)) { + if (!PointInCircle(P, C, R)) + { continue; } - if (R <= minR) { + if (R <= minR) + { minR = R; minC = C; } @@ -133,15 +143,18 @@ double circle(const std::vector &P) { // for each point in the list for (size_t i = 0; i < P.size() - 1; i++) // for every subsequent point in the list - for (size_t j = i + 1; j < P.size(); j++) { + for (size_t j = i + 1; j < P.size(); j++) + { // check for diameterically opposite points C.x = (P[i].x + P[j].x) / 2; C.y = (P[i].y + P[j].y) / 2; R = LenghtLine(C, P[i]); - if (!PointInCircle(P, C, R)) { + if (!PointInCircle(P, C, R)) + { continue; } - if (R <= minR) { + if (R <= minR) + { minR = R; minC = C; } @@ -155,7 +168,8 @@ double circle(const std::vector &P) { * \n radius 3.318493136080724 * \n centre at (3.0454545454545454, 1.3181818181818181) */ -void test() { +void test() +{ std::vector Pv; Pv.push_back(Point(0, 0)); Pv.push_back(Point(5, 4)); @@ -170,7 +184,8 @@ void test() { * \n radius 1.4142135623730951 * \n centre at (1.0, 1.0) */ -void test2() { +void test2() +{ std::vector Pv; Pv.push_back(Point(0, 0)); Pv.push_back(Point(0, 2)); @@ -185,7 +200,8 @@ void test2() { * \n centre at (2.142857142857143, 1.7857142857142856) * @todo This test fails */ -void test3() { +void test3() +{ std::vector Pv; Pv.push_back(Point(0.5, 1)); Pv.push_back(Point(3.5, 3)); @@ -195,7 +211,8 @@ void test3() { } /** Main program */ -int main() { +int main() +{ test(); std::cout << std::endl; test2(); diff --git a/others/sparse_matrix.cpp b/others/sparse_matrix.cpp index a358f0da472..5662e065d85 100644 --- a/others/sparse_matrix.cpp +++ b/others/sparse_matrix.cpp @@ -6,7 +6,8 @@ #include /** main function */ -int main() { +int main() +{ int m, n; int counterZeros = 0; @@ -21,16 +22,20 @@ int main() { std::cout << "\n"; // reads the matrix from stdin - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { + for (int i = 0; i < m; i++) + { + for (int j = 0; j < n; j++) + { std::cout << "element? "; std::cin >> a[i][j]; } } // counts the zero's - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { + for (int i = 0; i < m; i++) + { + for (int j = 0; j < n; j++) + { if (a[i][j] == 0) counterZeros++; // Counting number of zeroes } diff --git a/others/spiral_print.cpp b/others/spiral_print.cpp index 02dc3183aee..da92e6937e5 100644 --- a/others/spiral_print.cpp +++ b/others/spiral_print.cpp @@ -9,10 +9,13 @@ * \param [in] r number of rows * \param [in] c number of columns */ -void genArray(int **a, int r, int c) { +void genArray(int **a, int r, int c) +{ int value = 1; - for (int i = 0; i < r; i++) { - for (int j = 0; j < c; j++) { + for (int i = 0; i < r; i++) + { + for (int j = 0; j < c; j++) + { a[i][j] = value; std::cout << a[i][j] << " "; value++; @@ -26,39 +29,47 @@ void genArray(int **a, int r, int c) { * \param [in] r number of rows * \param [in] c number of columns */ -void spiralPrint(int **a, int r, int c) { +void spiralPrint(int **a, int r, int c) +{ int startRow = 0, endRow = r - 1; int startCol = 0, endCol = c - 1; int cnt = 0; - while (startRow <= endRow && startCol <= endCol) { + while (startRow <= endRow && startCol <= endCol) + { /// Print start row - for (int i = startCol; i <= endCol; i++, cnt++) { + for (int i = startCol; i <= endCol; i++, cnt++) + { std::cout << a[startRow][i] << " "; } startRow++; /// Print the end col - for (int i = startRow; i <= endRow; i++, cnt++) { + for (int i = startRow; i <= endRow; i++, cnt++) + { std::cout << a[i][endCol] << " "; } endCol--; /// Print the end row - if (cnt == r * c) { + if (cnt == r * c) + { break; } - for (int i = endCol; i >= startCol; i--, cnt++) { + for (int i = endCol; i >= startCol; i--, cnt++) + { std::cout << a[endRow][i] << " "; } endRow--; /// Print the start Col - if (cnt == r * c) { + if (cnt == r * c) + { break; } - for (int i = endRow; i >= startRow; i--, cnt++) { + for (int i = endRow; i >= startRow; i--, cnt++) + { std::cout << a[i][startCol] << " "; } startCol++; @@ -66,7 +77,8 @@ void spiralPrint(int **a, int r, int c) { } /** main function */ -int main() { +int main() +{ int r, c; std::cin >> r >> c; int **a = new int *[r]; diff --git a/others/stairs_pattern.cpp b/others/stairs_pattern.cpp index a3b8b0a44d6..bfd90dd1014 100644 --- a/others/stairs_pattern.cpp +++ b/others/stairs_pattern.cpp @@ -14,18 +14,23 @@ where number of pairs line is given by user #include /** main function */ -int main() { +int main() +{ int l, st = 2, x, r, z, n, sp; std::cout << "enter Index "; std::cin >> x; z = x; - for (r = 1; r <= x; r++) { + for (r = 1; r <= x; r++) + { z = z - 1; - for (n = 1; n <= 2; n++) { - for (sp = 1; sp <= z; sp++) { + for (n = 1; n <= 2; n++) + { + for (sp = 1; sp <= z; sp++) + { std::cout << " "; } - for (l = 1; l <= st; l++) { + for (l = 1; l <= st; l++) + { std::cout << "*"; } std::cout << std::endl; diff --git a/others/tower_of_hanoi.cpp b/others/tower_of_hanoi.cpp index 323b2e424a5..3a832248f2e 100644 --- a/others/tower_of_hanoi.cpp +++ b/others/tower_of_hanoi.cpp @@ -8,7 +8,8 @@ /** * Define the state of tower */ -struct tower { +struct tower +{ //! Values in the tower int values[10]; //! top tower ID @@ -17,17 +18,21 @@ struct tower { /** Display the towers */ void show(const struct tower *const F, const struct tower *const T, - const struct tower *const U) { + const struct tower *const U) +{ std::cout << "\n\n\tF : "; - for (int i = 0; i < F->top; i++) { + for (int i = 0; i < F->top; i++) + { std::cout << F->values[i] << "\t"; } std::cout << "\n\tU : "; - for (int i = 0; i < U->top; i++) { + for (int i = 0; i < U->top; i++) + { std::cout << U->values[i] << "\t"; } std::cout << "\n\tT : "; - for (int i = 0; i < T->top; i++) { + for (int i = 0; i < T->top; i++) + { std::cout << T->values[i] << "\t"; } } @@ -36,7 +41,8 @@ void show(const struct tower *const F, const struct tower *const T, * \param [in,out] From tower to move disk *from* * \param [in,out] To tower to move disk *to* */ -void mov(tower *From, tower *To) { +void mov(tower *From, tower *To) +{ --From->top; To->values[To->top] = From->values[From->top]; ++To->top; @@ -49,11 +55,15 @@ void mov(tower *From, tower *To) { * \param [in,out] Using temporary tower for the puzzle * \param [in,out] To tower to move disk to */ -void TH(int n, tower *From, tower *Using, tower *To) { - if (n == 1) { +void TH(int n, tower *From, tower *Using, tower *To) +{ + if (n == 1) + { mov(From, To); show(From, To, Using); - } else { + } + else + { TH(n - 1, From, To, Using); mov(From, To); show(From, To, Using); @@ -62,7 +72,8 @@ void TH(int n, tower *From, tower *Using, tower *To) { } /** Main function */ -int main() { +int main() +{ struct tower F, U, T; F.top = 0; @@ -74,7 +85,8 @@ int main() { std::cout << "\nEnter number of discs : "; std::cin >> no; - for (int i = no; i > 0; i--) { + for (int i = no; i > 0; i--) + { F.values[F.top++] = i; } diff --git a/others/vector_important_functions.cpp b/others/vector_important_functions.cpp index d23ff9c978d..765f6a8e566 100644 --- a/others/vector_important_functions.cpp +++ b/others/vector_important_functions.cpp @@ -8,7 +8,8 @@ #include /** Main function */ -int main() { +int main() +{ // Initializing vector with array values int arr[] = {10, 20, 5, 23, 42, 15}; int n = sizeof(arr) / sizeof(arr[0]); diff --git a/probability/addition_rule.cpp b/probability/addition_rule.cpp index 7809514899c..0666b29e61a 100644 --- a/probability/addition_rule.cpp +++ b/probability/addition_rule.cpp @@ -11,7 +11,8 @@ * \parama [in] B probability of event B * \returns probability of A and B */ -double addition_rule_independent(double A, double B) { +double addition_rule_independent(double A, double B) +{ return (A + B) - (A * B); } @@ -22,12 +23,14 @@ double addition_rule_independent(double A, double B) { * \parama [in] B_given_A probability of event B condition A * \returns probability of A and B */ -double addition_rule_dependent(double A, double B, double B_given_A) { +double addition_rule_dependent(double A, double B, double B_given_A) +{ return (A + B) - (A * B_given_A); } /** Main function */ -int main() { +int main() +{ double A = 0.5; double B = 0.25; double B_given_A = 0.05; diff --git a/probability/bayes_theorem.cpp b/probability/bayes_theorem.cpp index aaa557a9456..632611fe5f1 100644 --- a/probability/bayes_theorem.cpp +++ b/probability/bayes_theorem.cpp @@ -11,19 +11,22 @@ /** returns P(A|B) */ -double bayes_AgivenB(double BgivenA, double A, double B) { +double bayes_AgivenB(double BgivenA, double A, double B) +{ return (BgivenA * A) / B; } /** returns P(B|A) */ -double bayes_BgivenA(double AgivenB, double A, double B) { +double bayes_BgivenA(double AgivenB, double A, double B) +{ return (AgivenB * B) / A; } /** Main function */ -int main() { +int main() +{ double A = 0.01; double B = 0.1; double BgivenA = 0.9; diff --git a/probability/binomial_dist.cpp b/probability/binomial_dist.cpp index 1f30c504800..4d2e90842c3 100644 --- a/probability/binomial_dist.cpp +++ b/probability/binomial_dist.cpp @@ -33,7 +33,8 @@ double binomial_variance(double n, double p) { return n * p * (1 - p); } * \param [in] p * \returns \f$\sigma = \sqrt{\sigma^2} = \sqrt{n\cdot p\cdot (1-p)}\f$ */ -double binomial_standard_deviation(double n, double p) { +double binomial_standard_deviation(double n, double p) +{ return std::sqrt(binomial_variance(n, p)); } @@ -44,15 +45,18 @@ double binomial_standard_deviation(double n, double p) { * \frac{n!}{r!(n-r)!} = \frac{n\times(n-1)\times(n-2)\times\cdots(n-r)}{r!} * \f$ */ -double nCr(double n, double r) { +double nCr(double n, double r) +{ double numerator = n; double denominator = r; - for (int i = n - 1; i >= ((n - r) + 1); i--) { + for (int i = n - 1; i >= ((n - r) + 1); i--) + { numerator *= i; } - for (int i = 1; i < r; i++) { + for (int i = 1; i < r; i++) + { denominator *= i; } @@ -62,7 +66,8 @@ double nCr(double n, double r) { /** calculates the probability of exactly x successes * \returns \f$\displaystyle P(n,p,x) = {n\choose x} p^x (1-p)^{n-x}\f$ */ -double binomial_x_successes(double n, double p, double x) { +double binomial_x_successes(double n, double p, double x) +{ return nCr(n, x) * std::pow(p, x) * std::pow(1 - p, n - x); } @@ -72,16 +77,19 @@ double binomial_x_successes(double n, double p, double x) { * =\sum_{i=x_0}^{x_1} {n\choose i} p^i (1-p)^{n-i}\f$ */ double binomial_range_successes(double n, double p, double lower_bound, - double upper_bound) { + double upper_bound) +{ double probability = 0; - for (int i = lower_bound; i <= upper_bound; i++) { + for (int i = lower_bound; i <= upper_bound; i++) + { probability += nCr(n, i) * std::pow(p, i) * std::pow(1 - p, n - i); } return probability; } /** main function */ -int main() { +int main() +{ std::cout << "expected value : " << binomial_expected(100, 0.5) << std::endl; diff --git a/probability/poisson_dist.cpp b/probability/poisson_dist.cpp index 6a2a377c3f0..428ee903f27 100644 --- a/probability/poisson_dist.cpp +++ b/probability/poisson_dist.cpp @@ -14,7 +14,8 @@ * calculate the events per unit time\n * e.g 5 dollars every 2 mins = 5 / 2 = 2.5 */ -double poisson_rate(double events, double timeframe) { +double poisson_rate(double events, double timeframe) +{ return events / timeframe; } @@ -27,13 +28,16 @@ double poisson_expected(double rate, double time) { return rate * time; } /** * Compute factorial of a given number */ -double fact(double x) { +double fact(double x) +{ double x_fact = x; - for (int i = x - 1; i > 0; i--) { + for (int i = x - 1; i > 0; i--) + { x_fact *= i; } - if (x_fact <= 0) { + if (x_fact <= 0) + { x_fact = 1; } return x_fact; @@ -43,7 +47,8 @@ double fact(double x) { * Find the probability of x successes in a Poisson dist. * \f[p(\mu,x) = \frac{\mu^x e^{-\mu}}{x!}\f] */ -double poisson_x_successes(double expected, double x) { +double poisson_x_successes(double expected, double x) +{ return (std::pow(expected, x) * std::exp(-expected)) / fact(x); } @@ -51,9 +56,11 @@ double poisson_x_successes(double expected, double x) { * probability of a success in range for Poisson dist (inclusive, inclusive) * \f[P = \sum_i p(\mu,i)\f] */ -double poisson_range_successes(double expected, double lower, double upper) { +double poisson_range_successes(double expected, double lower, double upper) +{ double probability = 0; - for (int i = lower; i <= upper; i++) { + for (int i = lower; i <= upper; i++) + { probability += poisson_x_successes(expected, i); } return probability; @@ -62,7 +69,8 @@ double poisson_range_successes(double expected, double lower, double upper) { /** * main function */ -int main() { +int main() +{ double rate, expected; rate = poisson_rate(3, 1); std::cout << "Poisson rate : " << rate << std::endl; diff --git a/range_queries/bit.cpp b/range_queries/bit.cpp index e5e36ed24da..19141b7f5e0 100644 --- a/range_queries/bit.cpp +++ b/range_queries/bit.cpp @@ -7,22 +7,18 @@ class Bit { int n; vector bit; - inline int offset(int x) - { - return (x & (-x)); - } + inline int offset(int x) { return (x & (-x)); } - public: - - Bit(vector& arr) - { - n = arr.size(); - bit.assign(n + 1, 0); - for (int i = 0; i < n; ++i) - { - update(i, arr[i]); - } + public: + Bit(vector& arr) + { + n = arr.size(); + bit.assign(n + 1, 0); + for (int i = 0; i < n; ++i) + { + update(i, arr[i]); } + } Bit(int x) { n = x; @@ -34,7 +30,7 @@ class Bit // Add val at id id++; while (id <= n) - { + { bit[id] += val; id += offset(id); } @@ -46,23 +42,20 @@ class Bit id++; int res = 0; while (id > 0) - { + { res += bit[id]; id -= offset(id); } return res; } - int sum_range(int l, int r) - { - return sum(r) - sum(l - 1); - } + int sum_range(int l, int r) { return sum(r) - sum(l - 1); } }; int main() { int n = 5; - vector arr = { 1, 2, 3, 4, 5 }; + vector arr = {1, 2, 3, 4, 5}; Bit x(arr); assert(x.sum_range(0, 0) == 1); @@ -72,5 +65,5 @@ int main() assert(x.sum_range(0, 0) == 6); assert(x.sum_range(0, 1) == 8); assert(x.sum_range(0, 2) == 11); - return 0; + return 0; } diff --git a/range_queries/fenwicktree.cpp b/range_queries/fenwicktree.cpp index a4d1a02de3c..d78cb0d48c8 100644 --- a/range_queries/fenwicktree.cpp +++ b/range_queries/fenwicktree.cpp @@ -1,4 +1,4 @@ -#include +#include using namespace std; /** @@ -6,47 +6,55 @@ using namespace std; * twos complement works good on this * also using ` x - (x & (x - 1)) ` */ -#define lowbit(x) (x & (-x) ) +#define lowbit(x) (x & (-x)) const int maxn = 1e5 + 7; int tree[maxn] = {0}, - range; // segement of [1...range], notice it must be less than `maxn` + range; // segement of [1...range], notice it must be less than `maxn` -void update(int x, int c) { - while(x <= range) { +void update(int x, int c) +{ + while (x <= range) + { tree[x] += c; x += lowbit(x); } } -int query(int x) { +int query(int x) +{ int ans = 0; - while(x) { + while (x) + { ans += tree[x]; x -= lowbit(x); } return ans; } -int query_segement(int l, int r) { - return query(r) - query(l - 1); -} +int query_segement(int l, int r) { return query(r) - query(l - 1); } -int main() { +int main() +{ cin >> range; - for(int i = 1; i <= range; i++) { + for (int i = 1; i <= range; i++) + { int num; cin >> num; update(i, num); } int q; cin >> q; - while(q--) { + while (q--) + { int op; cin >> op; - if(op == 0) { + if (op == 0) + { int l, r; cin >> l >> r; cout << query_segement(l, r) << endl; - } else { + } + else + { int x, c; cin >> x >> c; update(x, c); diff --git a/range_queries/mo.cpp b/range_queries/mo.cpp index 7172bd632ee..4cdcdf30dc5 100644 --- a/range_queries/mo.cpp +++ b/range_queries/mo.cpp @@ -5,73 +5,71 @@ int a[N], bucket[N], cnt[N]; int bucket_size; struct query { - int l, r, i; + int l, r, i; } q[N]; int ans = 0; void add(int index) { - cnt[a[index]]++; - if (cnt[a[index]] == 1) - ans++; + cnt[a[index]]++; + if (cnt[a[index]] == 1) + ans++; } void remove(int index) { - cnt[a[index]]--; - if (cnt[a[index]] == 0) - ans--; + cnt[a[index]]--; + if (cnt[a[index]] == 0) + ans--; } bool mycmp(query x, query y) { - if (x.l / bucket_size != y.l / bucket_size) - return x.l / bucket_size < y.l / bucket_size; - return x.r < y.r; + if (x.l / bucket_size != y.l / bucket_size) + return x.l / bucket_size < y.l / bucket_size; + return x.r < y.r; } int main() { - int n, t, i, j, k = 0; - scanf("%d", &n); - for (i = 0; i < n; i++) - scanf("%d", &a[i]); - bucket_size = ceil(sqrt(n)); - scanf("%d", &t); - for (i = 0; i < t; i++) - { - scanf("%d %d", &q[i].l, &q[i].r); - q[i].l--; - q[i].r--; - q[i].i = i; - } - sort(q, q + t, mycmp); - int left = 0, right = 0; - for (i = 0; i < t; i++) - { - int L = q[i].l, R = q[i].r; - while (left < L) - { - remove(left); - left++; - } - while (left > L) - { - add(left - 1); - left--; - } - while (right <= R) - { - add(right); - right++; - } - while (right > R + 1) - { - remove(right - 1); - right--; - } - bucket[q[i].i] = ans; - } - for (i = 0; i < t; i++) - printf("%d\n", bucket[i]); - return 0; + int n, t, i, j, k = 0; + scanf("%d", &n); + for (i = 0; i < n; i++) scanf("%d", &a[i]); + bucket_size = ceil(sqrt(n)); + scanf("%d", &t); + for (i = 0; i < t; i++) + { + scanf("%d %d", &q[i].l, &q[i].r); + q[i].l--; + q[i].r--; + q[i].i = i; + } + sort(q, q + t, mycmp); + int left = 0, right = 0; + for (i = 0; i < t; i++) + { + int L = q[i].l, R = q[i].r; + while (left < L) + { + remove(left); + left++; + } + while (left > L) + { + add(left - 1); + left--; + } + while (right <= R) + { + add(right); + right++; + } + while (right > R + 1) + { + remove(right - 1); + right--; + } + bucket[q[i].i] = ans; + } + for (i = 0; i < t; i++) printf("%d\n", bucket[i]); + return 0; } diff --git a/range_queries/segtree.cpp b/range_queries/segtree.cpp index ee81453e167..fb2bbab131b 100644 --- a/range_queries/segtree.cpp +++ b/range_queries/segtree.cpp @@ -1,92 +1,94 @@ //#include -#incldue +#incldue < iostream > #define MAX 4000000 using namespace std; typedef long long ll; void ConsTree(ll arr[], ll segtree[], ll low, ll high, ll pos) { - if (low == high) - { - segtree[pos] = arr[low]; - return; - } - ll mid = (low + high) / 2; - ConsTree(arr, segtree, low, mid, 2 * pos + 1); - ConsTree(arr, segtree, mid + 1, high, 2 * pos + 2); - segtree[pos] = segtree[2 * pos + 1] + segtree[2 * pos + 2]; + if (low == high) + { + segtree[pos] = arr[low]; + return; + } + ll mid = (low + high) / 2; + ConsTree(arr, segtree, low, mid, 2 * pos + 1); + ConsTree(arr, segtree, mid + 1, high, 2 * pos + 2); + segtree[pos] = segtree[2 * pos + 1] + segtree[2 * pos + 2]; } ll query(ll segtree[], ll lazy[], ll qlow, ll qhigh, ll low, ll high, ll pos) { - if (low > high) - return 0; - if (qlow > high || qhigh < low) - return 0; - if (lazy[pos] != 0) - { - segtree[pos] += lazy[pos] * (high - low + 1); - if (low != high) - { - lazy[2 * pos + 1] += lazy[pos]; - lazy[2 * pos + 2] += lazy[pos]; - } - lazy[pos] = 0; - } - if (qlow <= low && qhigh >= high) - return segtree[pos]; - ll mid = (low + high) / 2; - return query(segtree, lazy, qlow, qhigh, low, mid, 2 * pos + 1) + query(segtree, lazy, qlow, qhigh, mid + 1, high, 2 * pos + 2); + if (low > high) + return 0; + if (qlow > high || qhigh < low) + return 0; + if (lazy[pos] != 0) + { + segtree[pos] += lazy[pos] * (high - low + 1); + if (low != high) + { + lazy[2 * pos + 1] += lazy[pos]; + lazy[2 * pos + 2] += lazy[pos]; + } + lazy[pos] = 0; + } + if (qlow <= low && qhigh >= high) + return segtree[pos]; + ll mid = (low + high) / 2; + return query(segtree, lazy, qlow, qhigh, low, mid, 2 * pos + 1) + + query(segtree, lazy, qlow, qhigh, mid + 1, high, 2 * pos + 2); } -void update(ll segtree[], ll lazy[], ll start, ll end, ll delta, ll low, ll high, ll pos) +void update(ll segtree[], ll lazy[], ll start, ll end, ll delta, ll low, + ll high, ll pos) { - if (low > high) - return; - if (lazy[pos] != 0) - { - segtree[pos] += lazy[pos] * (high - low + 1); - if (low != high) - { - lazy[2 * pos + 1] += lazy[pos]; - lazy[2 * pos + 2] += lazy[pos]; - } - lazy[pos] = 0; - } - if (start > high || end < low) - return; - if (start <= low && end >= high) - { - segtree[pos] += delta * (high - low + 1); - if (low != high) - { - lazy[2 * pos + 1] += delta; - lazy[2 * pos + 2] += delta; - } - return; - } - ll mid = (low + high) / 2; - update(segtree, lazy, start, end, delta, low, mid, 2 * pos + 1); - update(segtree, lazy, start, end, delta, mid + 1, high, 2 * pos + 2); - segtree[pos] = segtree[2 * pos + 1] + segtree[2 * pos + 2]; + if (low > high) + return; + if (lazy[pos] != 0) + { + segtree[pos] += lazy[pos] * (high - low + 1); + if (low != high) + { + lazy[2 * pos + 1] += lazy[pos]; + lazy[2 * pos + 2] += lazy[pos]; + } + lazy[pos] = 0; + } + if (start > high || end < low) + return; + if (start <= low && end >= high) + { + segtree[pos] += delta * (high - low + 1); + if (low != high) + { + lazy[2 * pos + 1] += delta; + lazy[2 * pos + 2] += delta; + } + return; + } + ll mid = (low + high) / 2; + update(segtree, lazy, start, end, delta, low, mid, 2 * pos + 1); + update(segtree, lazy, start, end, delta, mid + 1, high, 2 * pos + 2); + segtree[pos] = segtree[2 * pos + 1] + segtree[2 * pos + 2]; } int main() { - ll n, c; - scanf("%lld %lld", &n, &c); - ll arr[n] = {0}, p, q, v, choice; - ll segtree[MAX], lazy[MAX] = {0}; - ConsTree(arr, segtree, 0, n - 1, 0); - while (c--) - { - scanf("%lld", &choice); - if (choice == 0) - { - scanf("%lld %lld %lld", &p, &q, &v); - update(segtree, lazy, p - 1, q - 1, v, 0, n - 1, 0); - } - else - { - scanf("%lld %lld", &p, &q); - printf("%lld\n", query(segtree, lazy, p - 1, q - 1, 0, n - 1, 0)); - } - } - return 0; + ll n, c; + scanf("%lld %lld", &n, &c); + ll arr[n] = {0}, p, q, v, choice; + ll segtree[MAX], lazy[MAX] = {0}; + ConsTree(arr, segtree, 0, n - 1, 0); + while (c--) + { + scanf("%lld", &choice); + if (choice == 0) + { + scanf("%lld %lld %lld", &p, &q, &v); + update(segtree, lazy, p - 1, q - 1, v, 0, n - 1, 0); + } + else + { + scanf("%lld %lld", &p, &q); + printf("%lld\n", query(segtree, lazy, p - 1, q - 1, 0, n - 1, 0)); + } + } + return 0; } diff --git a/search/binary_search.cpp b/search/binary_search.cpp index 66da31d7fca..ba0ce7644bf 100644 --- a/search/binary_search.cpp +++ b/search/binary_search.cpp @@ -12,10 +12,12 @@ * \returns index if T is found * \return -1 if T is not found */ -int binary_search(int a[], int r, int key) { +int binary_search(int a[], int r, int key) +{ int l = 0; - while (l <= r) { + while (l <= r) + { int m = l + (r - l) / 2; if (key == a[m]) return m; @@ -28,7 +30,8 @@ int binary_search(int a[], int r, int key) { } /** main function */ -int main(int argc, char const* argv[]) { +int main(int argc, char const* argv[]) +{ int n, key; std::cout << "Enter size of array: "; std::cin >> n; @@ -37,7 +40,8 @@ int main(int argc, char const* argv[]) { int* a = new int[n]; // this loop use for store value in Array - for (int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) + { std::cin >> a[i]; } diff --git a/search/exponential_search.cpp b/search/exponential_search.cpp index f57cbf96b51..276d032463b 100644 --- a/search/exponential_search.cpp +++ b/search/exponential_search.cpp @@ -31,10 +31,12 @@ * \returns `nullptr` if value not found */ template -inline Type* binary_s(Type* array, size_t size, Type key) { +inline Type* binary_s(Type* array, size_t size, Type key) +{ int32_t lower_index(0), upper_index(size - 1), middle_index; - while (lower_index <= upper_index) { + while (lower_index <= upper_index) + { middle_index = std::floor((lower_index + upper_index) / 2); if (*(array + middle_index) < key) @@ -56,10 +58,13 @@ inline Type* binary_s(Type* array, size_t size, Type key) { * * Auxiliary Space Complexity O(1) */ template -Type* struzik_search(Type* array, size_t size, Type key) { +Type* struzik_search(Type* array, size_t size, Type key) +{ uint32_t block_front(0), block_size = size == 0 ? 0 : 1; - while (block_front != block_size) { - if (*(array + block_size - 1) < key) { + while (block_front != block_size) + { + if (*(array + block_size - 1) < key) + { block_front = block_size; (block_size * 2 - 1 < size) ? (block_size *= 2) : block_size = size; continue; @@ -71,7 +76,8 @@ Type* struzik_search(Type* array, size_t size, Type key) { } /** Main function */ -int main() { +int main() +{ // TEST CASES int* sorted_array = new int[7]{7, 10, 15, 23, 70, 105, 203}; assert(struzik_search(sorted_array, 7, 0) == nullptr); diff --git a/search/hash_search.cpp b/search/hash_search.cpp index 6e4caffc30e..c417c114be4 100644 --- a/search/hash_search.cpp +++ b/search/hash_search.cpp @@ -26,7 +26,8 @@ int data[MAX] = {1, 10, 15, 5, 8, 7}; //!< test data /** * a one-way linked list */ -typedef struct list { +typedef struct list +{ int key; //!< key value for node struct list* next; //!< pointer to next link in the chain } node, /**< define node as one item list */ @@ -52,7 +53,8 @@ int h(int key) { return key % HASHMAX; } * \warning dynamic memory allocated to `n` never gets freed. * \todo fix memory leak */ -void create_list(int key) { // Construct hash table +void create_list(int key) +{ // Construct hash table link p, n; int index; n = (link)malloc(sizeof(node)); @@ -60,10 +62,13 @@ void create_list(int key) { // Construct hash table n->next = NULL; index = h(key); p = hashtab[index].next; - if (p != NULL) { + if (p != NULL) + { n->next = p; hashtab[index].next = n; - } else { + } + else + { hashtab[index].next = n; } } @@ -73,7 +78,8 @@ void create_list(int key) { // Construct hash table * (int key) function, then one-dimensional linear search. If found @return * element depth and number of searches If not found @return -1 */ -int hash_search(int key, int* counter) { // Hash lookup function +int hash_search(int key, int* counter) +{ // Hash lookup function link pointer; int index; @@ -83,7 +89,8 @@ int hash_search(int key, int* counter) { // Hash lookup function std::cout << "data[" << index << "]:"; - while (pointer != NULL) { + while (pointer != NULL) + { counter[0]++; std::cout << "data[" << pointer->key << "]:"; if (pointer->key == key) @@ -96,23 +103,27 @@ int hash_search(int key, int* counter) { // Hash lookup function } /** main function */ -int main() { +int main() +{ link p; int key, index, i, counter; // Key is the value to be found index = 0; // You can write the input mode here - while (index < MAX) { // Construct hash table + while (index < MAX) + { // Construct hash table create_list(data[index]); index++; } - for (i = 0; i < HASHMAX; i++) { // Output hash table + for (i = 0; i < HASHMAX; i++) + { // Output hash table std::cout << "hashtab [" << i << "]\n"; p = hashtab[i].next; - while (p != NULL) { + while (p != NULL) + { std::cout << "please int key:"; if (p->key > 0) std::cout << "[" << p->key << "]"; @@ -121,7 +132,8 @@ int main() { std::cout << std::endl; } - while (key != -1) { + while (key != -1) + { // You can write the input mode here // test key = 10 key = 10; diff --git a/search/interpolation_search.cpp b/search/interpolation_search.cpp index 4339dc3661e..0b356b119b5 100644 --- a/search/interpolation_search.cpp +++ b/search/interpolation_search.cpp @@ -12,11 +12,13 @@ * \returns index where the value is found * \returns 0 if not found */ -int interpolation_search(int arr[], int value, int len) { +int interpolation_search(int arr[], int value, int len) +{ int low = 0, high, mid; high = len - 1; - while (arr[low] <= value && arr[high] >= value) { + while (arr[low] <= value && arr[high] >= value) + { mid = (low + ((value - arr[low]) * (high - low)) / (arr[high] - arr[low])); if (arr[mid] > value) @@ -34,7 +36,8 @@ int interpolation_search(int arr[], int value, int len) { } /** main function */ -int main() { +int main() +{ int n, value, re; std::cout << "Enter the size of array(less than 100) : "; diff --git a/search/interpolation_search2.cpp b/search/interpolation_search2.cpp index 93fa6cd836e..9400c5f9674 100644 --- a/search/interpolation_search2.cpp +++ b/search/interpolation_search2.cpp @@ -12,10 +12,12 @@ * \returns index where the value is found * \returns -1 if not found */ -int InterpolationSearch(int A[], int n, int x) { +int InterpolationSearch(int A[], int n, int x) +{ int low = 0; int high = n - 1; - while (low <= high) { + while (low <= high) + { int mid = low + (((high - 1) * (x - A[low])) / (A[high] - A[low])); if (x == A[mid]) return mid; // Found x, return (exit) @@ -29,7 +31,8 @@ int InterpolationSearch(int A[], int n, int x) { } /** main function */ -int main() { +int main() +{ int A[] = {2, 4, 5, 7, 13, 14, 15, 23}; int x = 17; diff --git a/search/jump_search.cpp b/search/jump_search.cpp index f7b100a4e03..b854ac6f92d 100644 --- a/search/jump_search.cpp +++ b/search/jump_search.cpp @@ -9,14 +9,16 @@ /** jump search implementation */ -int jumpSearch(int arr[], int x, int n) { +int jumpSearch(int arr[], int x, int n) +{ // Finding block size to be jumped int step = std::sqrt(n); // Finding the block where element is // present (if it is present) int prev = 0; - while (arr[std::min(step, n) - 1] < x) { + while (arr[std::min(step, n) - 1] < x) + { prev = step; step += std::sqrt(n); if (prev >= n) @@ -25,7 +27,8 @@ int jumpSearch(int arr[], int x, int n) { // Doing a linear search for x in block // beginning with prev. - while (arr[prev] < x) { + while (arr[prev] < x) + { prev++; // If we reached next block or end of @@ -41,7 +44,8 @@ int jumpSearch(int arr[], int x, int n) { } // Driver program to test function -int main() { +int main() +{ int arr[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610}; int x = 55; int n = sizeof(arr) / sizeof(arr[0]); diff --git a/search/linear_search.cpp b/search/linear_search.cpp index 14250695112..b8fd798a73d 100644 --- a/search/linear_search.cpp +++ b/search/linear_search.cpp @@ -13,9 +13,12 @@ * \returns index where the key-value occurs in the array * \returns -1 if key-value not found */ -int LinearSearch(int *array, int size, int key) { - for (int i = 0; i < size; ++i) { - if (array[i] == key) { +int LinearSearch(int *array, int size, int key) +{ + for (int i = 0; i < size; ++i) + { + if (array[i] == key) + { return i; } } @@ -24,7 +27,8 @@ int LinearSearch(int *array, int size, int key) { } /** main function */ -int main() { +int main() +{ int size; std::cout << "\nEnter the size of the Array : "; std::cin >> size; @@ -34,7 +38,8 @@ int main() { // Input array std::cout << "\nEnter the Array of " << size << " numbers : "; - for (int i = 0; i < size; i++) { + for (int i = 0; i < size; i++) + { std::cin >> array[i]; } @@ -42,9 +47,12 @@ int main() { std::cin >> key; int index = LinearSearch(array, size, key); - if (index != -1) { + if (index != -1) + { std::cout << "\nNumber found at index : " << index; - } else { + } + else + { std::cout << "\nNot found"; } diff --git a/search/median_search.cpp b/search/median_search.cpp index 7379cad26e9..433ffc1f766 100644 --- a/search/median_search.cpp +++ b/search/median_search.cpp @@ -14,18 +14,25 @@ * @todo add documentation */ template -void comp(X x, std::vector *s1, std::vector *s2, - std::vector *s3) { - if (s1->size() >= x && s1->size() + s2->size() < x) { +void comp(X x, std::vector *s1, std::vector *s2, std::vector *s3) +{ + if (s1->size() >= x && s1->size() + s2->size() < x) + { std::cout << (*s2)[0] << " is the " << x + 1 << "th element from front"; - } else if (s1->size() > x) { + } + else if (s1->size() > x) + { std::sort(s1->begin(), s1->end()); std::cout << (*s1)[x] << " is the " << x + 1 << "th element from front"; - } else if (s1->size() + s2->size() <= x && s3->size() > x) { + } + else if (s1->size() + s2->size() <= x && s3->size() > x) + { std::sort(s3->begin(), s3->end()); std::cout << (*s3)[x - s1->size() - s2->size()] << " is the " << x + 1 << "th element from front"; - } else { + } + else + { std::cout << x + 1 << " is invalid location"; } } @@ -35,7 +42,8 @@ void comp(X x, std::vector *s1, std::vector *s2, /** * Main function */ -int main() { +int main() +{ std::vector v{25, 21, 98, 100, 76, 22, 43, 60, 89, 87}; std::vector s1; std::vector s2; @@ -54,14 +62,20 @@ int main() { std::cout << "\nmedian=" << median << std::endl; int avg1, avg2, avg3, sum1 = 0, sum2 = 0, sum3 = 0; - for (int i = 0; i < v.size(); i++) { // iterate through all numbers - if (v.back() == v[median]) { + for (int i = 0; i < v.size(); i++) + { // iterate through all numbers + if (v.back() == v[median]) + { avg1 = sum1 + v.back(); s2.push_back(v.back()); - } else if (v.back() < v[median]) { + } + else if (v.back() < v[median]) + { avg2 = sum2 + v.back(); s1.push_back(v.back()); - } else { + } + else + { avg3 = sum3 + v.back(); s3.push_back(v.back()); } diff --git a/search/ternary_search.cpp b/search/ternary_search.cpp index 73b89da7a2a..f1e2eccf061 100644 --- a/search/ternary_search.cpp +++ b/search/ternary_search.cpp @@ -45,10 +45,14 @@ void get_input() {} * \returns index where the target value was found * \returns -1 if target value not found */ -int it_ternary_search(int left, int right, int A[], int target) { - while (1) { - if (left < right) { - if (right - left < absolutePrecision) { +int it_ternary_search(int left, int right, int A[], int target) +{ + while (1) + { + if (left < right) + { + if (right - left < absolutePrecision) + { for (int i = left; i <= right; i++) if (A[i] == target) return i; @@ -71,7 +75,9 @@ int it_ternary_search(int left, int right, int A[], int target) { else left = oneThird + 1, right = twoThird - 1; - } else { + } + else + { return -1; } } @@ -87,9 +93,12 @@ int it_ternary_search(int left, int right, int A[], int target) { * \returns index where the target value was found * \returns -1 if target value not found */ -int rec_ternary_search(int left, int right, int A[], int target) { - if (left < right) { - if (right - left < absolutePrecision) { +int rec_ternary_search(int left, int right, int A[], int target) +{ + if (left < right) + { + if (right - left < absolutePrecision) + { for (int i = left; i <= right; i++) if (A[i] == target) return i; @@ -111,7 +120,9 @@ int rec_ternary_search(int left, int right, int A[], int target) { return rec_ternary_search(twoThird + 1, right, A, target); return rec_ternary_search(oneThird + 1, twoThird - 1, A, target); - } else { + } + else + { return -1; } } @@ -124,14 +135,16 @@ int rec_ternary_search(int left, int right, int A[], int target) { * \param[in] A array to search in * \param[in] target value to search for */ -void ternary_search(int N, int A[], int target) { +void ternary_search(int N, int A[], int target) +{ std::cout << it_ternary_search(0, N - 1, A, target) << '\t'; std::cout << rec_ternary_search(0, N - 1, A, target) << '\t'; std::cout << std::endl; } /** Main function */ -int main() { +int main() +{ int N = 21; int A[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 10}; get_input(); diff --git a/search/text_search.cpp b/search/text_search.cpp index ee66a506a8a..a228d23b216 100644 --- a/search/text_search.cpp +++ b/search/text_search.cpp @@ -12,7 +12,8 @@ /** Main function */ -int main() { +int main() +{ std::string paragraph; std::cout << "Please enter your paragraph: \n"; std::getline(std::cin, paragraph); @@ -20,18 +21,25 @@ int main() { std::cout << "\nThe size of your paragraph = " << paragraph.size() << " characters. \n\n"; - if (paragraph.empty()) { + if (paragraph.empty()) + { std::cout << "\nThe paragraph is empty" << std::endl; - } else { - while (true) { + } + else + { + while (true) + { std::string word; std::cout << "Please enter the word you are searching for: "; std::getline(std::cin, word); std::cout << "Hello, your word is " << word << "!\n"; - if (paragraph.find(word) == std::string::npos) { + if (paragraph.find(word) == std::string::npos) + { std::cout << word << " does not exist in the sentence" << std::endl; - } else { + } + else + { std::cout << "The word " << word << " is now found at location " << paragraph.find(word) << std::endl << std::endl; diff --git a/sorting/bead_sort.cpp b/sorting/bead_sort.cpp index a1a54c1e04a..0215fc7696e 100644 --- a/sorting/bead_sort.cpp +++ b/sorting/bead_sort.cpp @@ -5,11 +5,13 @@ #define BEAD(i, j) beads[i * max + j] // function to perform the above algorithm -void beadSort(int *a, int len) { +void beadSort(int *a, int len) +{ // Find the maximum element int max = a[0]; for (int i = 1; i < len; i++) - if (a[i] > max) max = a[i]; + if (a[i] > max) + max = a[i]; // allocating memory unsigned char *beads = new unsigned char[max * len]; @@ -19,10 +21,12 @@ void beadSort(int *a, int len) { for (int i = 0; i < len; i++) for (int j = 0; j < a[i]; j++) BEAD(i, j) = 1; - for (int j = 0; j < max; j++) { + for (int j = 0; j < max; j++) + { // count how many beads are on each post int sum = 0; - for (int i = 0; i < len; i++) { + for (int i = 0; i < len; i++) + { sum += BEAD(i, j); BEAD(i, j) = 0; } @@ -32,9 +36,11 @@ void beadSort(int *a, int len) { } // Put sorted values in array using beads - for (int i = 0; i < len; i++) { + for (int i = 0; i < len; i++) + { int j; - for (j = 0; j < max && BEAD(i, j); j++) { + for (j = 0; j < max && BEAD(i, j); j++) + { } a[i] = j; @@ -43,7 +49,8 @@ void beadSort(int *a, int len) { } // driver function to test the algorithm -int main() { +int main() +{ int a[] = {5, 3, 1, 7, 4, 1, 1, 20}; int len = sizeof(a) / sizeof(a[0]); diff --git a/sorting/bitonic_sort.cpp b/sorting/bitonic_sort.cpp index 4d098105649..7f47cbac6f5 100644 --- a/sorting/bitonic_sort.cpp +++ b/sorting/bitonic_sort.cpp @@ -9,16 +9,20 @@ /*The parameter dir indicates the sorting direction, ASCENDING or DESCENDING; if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are interchanged.*/ -void compAndSwap(int a[], int i, int j, int dir) { - if (dir == (a[i] > a[j])) std::swap(a[i], a[j]); +void compAndSwap(int a[], int i, int j, int dir) +{ + if (dir == (a[i] > a[j])) + std::swap(a[i], a[j]); } /*It recursively sorts a bitonic sequence in ascending order, if dir = 1, and in descending order otherwise (means dir=0). The sequence to be sorted starts at index position low, the parameter cnt is the number of elements to be sorted.*/ -void bitonicMerge(int a[], int low, int cnt, int dir) { - if (cnt > 1) { +void bitonicMerge(int a[], int low, int cnt, int dir) +{ + if (cnt > 1) + { int k = cnt / 2; for (int i = low; i < low + k; i++) compAndSwap(a, i, i + k, dir); bitonicMerge(a, low, k, dir); @@ -29,8 +33,10 @@ void bitonicMerge(int a[], int low, int cnt, int dir) { /* This function first produces a bitonic sequence by recursively sorting its two halves in opposite sorting orders, and then calls bitonicMerge to make them in the same order */ -void bitonicSort(int a[], int low, int cnt, int dir) { - if (cnt > 1) { +void bitonicSort(int a[], int low, int cnt, int dir) +{ + if (cnt > 1) + { int k = cnt / 2; // sort in ascending order since dir here is 1 @@ -50,7 +56,8 @@ void bitonicSort(int a[], int low, int cnt, int dir) { void sort(int a[], int N, int up) { bitonicSort(a, 0, N, up); } // Driver code -int main() { +int main() +{ int a[] = {3, 7, 4, 8, 6, 2, 1, 5}; int N = sizeof(a) / sizeof(a[0]); diff --git a/sorting/bubble_sort.cpp b/sorting/bubble_sort.cpp index c43e425fcd9..8d2a33dcd60 100644 --- a/sorting/bubble_sort.cpp +++ b/sorting/bubble_sort.cpp @@ -40,7 +40,8 @@ optimized bubble sort algorithm. It's right down there. #include #include -int main() { +int main() +{ int n; bool swap_check = true; std::cout << "Enter the amount of numbers to sort: "; @@ -50,16 +51,20 @@ int main() { int num; // Input - for (int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) + { std::cin >> num; numbers.push_back(num); } // Bubble Sorting - for (int i = 0; (i < n) && (swap_check); i++) { + for (int i = 0; (i < n) && (swap_check); i++) + { swap_check = false; - for (int j = 0; j < n - 1 - i; j++) { - if (numbers[j] > numbers[j + 1]) { + for (int j = 0; j < n - 1 - i; j++) + { + if (numbers[j] > numbers[j + 1]) + { swap_check = true; std::swap(numbers[j], numbers[j + 1]); // by changing swap location. @@ -72,10 +77,14 @@ int main() { // Output std::cout << "\nSorted Array : "; - for (int i = 0; i < numbers.size(); i++) { - if (i != numbers.size() - 1) { + for (int i = 0; i < numbers.size(); i++) + { + if (i != numbers.size() - 1) + { std::cout << numbers[i] << ", "; - } else { + } + else + { std::cout << numbers[i] << std::endl; } } diff --git a/sorting/bucket_sort.cpp b/sorting/bucket_sort.cpp index c43865281bc..ee945627c15 100644 --- a/sorting/bucket_sort.cpp +++ b/sorting/bucket_sort.cpp @@ -4,12 +4,14 @@ #include // Function to sort arr[] of size n using bucket sort -void bucketSort(float arr[], int n) { +void bucketSort(float arr[], int n) +{ // 1) Create n empty buckets std::vector *b = new std::vector[n]; // 2) Put array elements in different buckets - for (int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) + { int bi = n * arr[i]; // Index in bucket b[bi].push_back(arr[i]); } @@ -25,7 +27,8 @@ void bucketSort(float arr[], int n) { } /* Driver program to test above funtion */ -int main() { +int main() +{ float arr[] = {0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434}; int n = sizeof(arr) / sizeof(arr[0]); bucketSort(arr, n); diff --git a/sorting/cocktail_selection_sort.cpp b/sorting/cocktail_selection_sort.cpp index ab622999687..ef3d30752e6 100644 --- a/sorting/cocktail_selection_sort.cpp +++ b/sorting/cocktail_selection_sort.cpp @@ -9,27 +9,35 @@ // Iterative Version -void CocktailSelectionSort(std::vector *vec, int low, int high) { - while (low <= high) { +void CocktailSelectionSort(std::vector *vec, int low, int high) +{ + while (low <= high) + { int minimum = (*vec)[low]; int minimumindex = low; int maximum = (*vec)[high]; int maximumindex = high; - for (int i = low; i <= high; i++) { - if ((*vec)[i] >= maximum) { + for (int i = low; i <= high; i++) + { + if ((*vec)[i] >= maximum) + { maximum = (*vec)[i]; maximumindex = i; } - if ((*vec)[i] <= minimum) { + if ((*vec)[i] <= minimum) + { minimum = (*vec)[i]; minimumindex = i; } } - if (low != maximumindex || high != minimumindex) { + if (low != maximumindex || high != minimumindex) + { std::swap((*vec)[low], (*vec)[minimumindex]); std::swap((*vec)[high], (*vec)[maximumindex]); - } else { + } + else + { std::swap((*vec)[low], (*vec)[high]); } @@ -40,28 +48,36 @@ void CocktailSelectionSort(std::vector *vec, int low, int high) { // Recursive Version -void CocktailSelectionSort_v2(std::vector *vec, int low, int high) { - if (low >= high) return; +void CocktailSelectionSort_v2(std::vector *vec, int low, int high) +{ + if (low >= high) + return; int minimum = (*vec)[low]; int minimumindex = low; int maximum = (*vec)[high]; int maximumindex = high; - for (int i = low; i <= high; i++) { - if ((*vec)[i] >= maximum) { + for (int i = low; i <= high; i++) + { + if ((*vec)[i] >= maximum) + { maximum = (*vec)[i]; maximumindex = i; } - if ((*vec)[i] <= minimum) { + if ((*vec)[i] <= minimum) + { minimum = (*vec)[i]; minimumindex = i; } } - if (low != maximumindex || high != minimumindex) { + if (low != maximumindex || high != minimumindex) + { std::swap((*vec)[low], (*vec)[minimumindex]); std::swap((*vec)[high], (*vec)[maximumindex]); - } else { + } + else + { std::swap((*vec)[low], (*vec)[high]); } @@ -70,13 +86,15 @@ void CocktailSelectionSort_v2(std::vector *vec, int low, int high) { // main function, select any one of iterative or recursive version -int main() { +int main() +{ int n; std::cout << "Enter number of elements\n"; std::cin >> n; std::vector v(n); std::cout << "Enter all the elements\n"; - for (int i = 0; i < n; ++i) { + for (int i = 0; i < n; ++i) + { std::cin >> v[i]; } @@ -84,16 +102,22 @@ int main() { std::cout << "Enter method: \n\t0: iterative\n\t1: recursive:\t"; std::cin >> method; - if (method == 0) { + if (method == 0) + { CocktailSelectionSort(&v, 0, n - 1); - } else if (method == 1) { + } + else if (method == 1) + { CocktailSelectionSort_v2(&v, 0, n - 1); - } else { + } + else + { std::cerr << "Unknown method" << std::endl; return -1; } std::cout << "Sorted elements are\n"; - for (int i = 0; i < n; ++i) { + for (int i = 0; i < n; ++i) + { std::cout << v[i] << " "; } diff --git a/sorting/comb_sort.cpp b/sorting/comb_sort.cpp index 1b0a4d70633..d554ac75770 100644 --- a/sorting/comb_sort.cpp +++ b/sorting/comb_sort.cpp @@ -8,13 +8,15 @@ int a[100005]; int n; -int FindNextGap(int x) { +int FindNextGap(int x) +{ x = (x * 10) / 13; return std::max(1, x); } -void CombSort(int a[], int l, int r) { +void CombSort(int a[], int l, int r) +{ // Init gap int gap = n; @@ -22,15 +24,18 @@ void CombSort(int a[], int l, int r) { bool swapped = true; // Keep running until gap = 1 or none elements were swapped - while (gap != 1 || swapped) { + while (gap != 1 || swapped) + { // Find next gap gap = FindNextGap(gap); swapped = false; // Compare all elements with current gap - for (int i = l; i <= r - gap; ++i) { - if (a[i] > a[i + gap]) { + for (int i = l; i <= r - gap; ++i) + { + if (a[i] > a[i + gap]) + { std::swap(a[i], a[i + gap]); swapped = true; } @@ -38,7 +43,8 @@ void CombSort(int a[], int l, int r) { } } -int main() { +int main() +{ std::cin >> n; for (int i = 1; i <= n; ++i) std::cin >> a[i]; diff --git a/sorting/counting_sort.cpp b/sorting/counting_sort.cpp index bda37bbd8ca..9dadd48ccbb 100644 --- a/sorting/counting_sort.cpp +++ b/sorting/counting_sort.cpp @@ -3,64 +3,61 @@ using namespace std; int Max(int Arr[], int N) { - int max = Arr[0]; - for (int i = 1; i < N; i++) - if (Arr[i] > max) - max = Arr[i]; - return max; + int max = Arr[0]; + for (int i = 1; i < N; i++) + if (Arr[i] > max) + max = Arr[i]; + return max; } int Min(int Arr[], int N) { - int min = Arr[0]; - for (int i = 1; i < N; i++) - if (Arr[i] < min) - min = Arr[i]; - return min; + int min = Arr[0]; + for (int i = 1; i < N; i++) + if (Arr[i] < min) + min = Arr[i]; + return min; } void Print(int Arr[], int N) { - for (int i = 0; i < N; i++) - cout << Arr[i] << ", "; + for (int i = 0; i < N; i++) cout << Arr[i] << ", "; } int *Counting_Sort(int Arr[], int N) { + int max = Max(Arr, N); + int min = Min(Arr, N); + int *Sorted_Arr = new int[N]; - int max = Max(Arr, N); - int min = Min(Arr, N); - int *Sorted_Arr = new int[N]; + int *Count = new int[max - min + 1]; - int *Count = new int[max - min + 1]; + for (int i = 0; i < N; i++) Count[Arr[i] - min]++; - for (int i = 0; i < N; i++) - Count[Arr[i] - min]++; + for (int i = 1; i < (max - min + 1); i++) Count[i] += Count[i - 1]; - for (int i = 1; i < (max - min + 1); i++) - Count[i] += Count[i - 1]; + for (int i = N - 1; i >= 0; i--) + { + Sorted_Arr[Count[Arr[i] - min] - 1] = Arr[i]; + Count[Arr[i] - min]--; + } - for (int i = N - 1; i >= 0; i--) - { - Sorted_Arr[Count[Arr[i] - min] - 1] = Arr[i]; - Count[Arr[i] - min]--; - } - - return Sorted_Arr; + return Sorted_Arr; } int main() { - - int Arr[] = {47, 65, 20, 66, 25, 53, 64, 69, 72, 22, 74, 25, 53, 15, 42, 36, 4, 69, 86, 19}, N = 20; - int *Sorted_Arr; - - cout << "\n\tOrignal Array = "; - Print(Arr, N); - Sorted_Arr = Counting_Sort(Arr, N); - cout << "\n\t Sorted Array = "; - Print(Sorted_Arr, N); - cout << endl; - - return 0; + int Arr[] = {47, 65, 20, 66, 25, 53, 64, 69, 72, 22, + 74, 25, 53, 15, 42, 36, 4, 69, 86, 19}, + N = 20; + int *Sorted_Arr; + + cout << "\n\tOrignal Array = "; + Print(Arr, N); + Sorted_Arr = Counting_Sort(Arr, N); + cout << "\n\t Sorted Array = "; + Print(Sorted_Arr, N); + cout << endl; + + return 0; } diff --git a/sorting/counting_sort_string.cpp b/sorting/counting_sort_string.cpp index 6179e5d1111..77e8cdf89b0 100644 --- a/sorting/counting_sort_string.cpp +++ b/sorting/counting_sort_string.cpp @@ -5,18 +5,14 @@ using namespace std; void countSort(string arr) { - string output; int count[256], i; - for (int i = 0; i < 256; i++) - count[i] = 0; + for (int i = 0; i < 256; i++) count[i] = 0; - for (i = 0; arr[i]; ++i) - ++count[arr[i]]; + for (i = 0; arr[i]; ++i) ++count[arr[i]]; - for (i = 1; i <= 256; ++i) - count[i] += count[i - 1]; + for (i = 1; i <= 256; ++i) count[i] += count[i - 1]; for (i = 0; arr[i]; ++i) { @@ -24,8 +20,7 @@ void countSort(string arr) --count[arr[i]]; } - for (i = 0; arr[i]; ++i) - arr[i] = output[i]; + for (i = 0; arr[i]; ++i) arr[i] = output[i]; cout << "Sorted character array is " << arr; } diff --git a/sorting/heap_sort.cpp b/sorting/heap_sort.cpp index 9948bb82153..b9b62a5f649 100644 --- a/sorting/heap_sort.cpp +++ b/sorting/heap_sort.cpp @@ -1,7 +1,8 @@ #include #include -void heapify(int *a, int i, int n) { +void heapify(int *a, int i, int n) +{ int largest = i; const int l = 2 * i + 1; const int r = 2 * i + 2; @@ -12,31 +13,38 @@ void heapify(int *a, int i, int n) { if (r < n && a[r] > a[largest]) largest = r; - if (largest != i) { + if (largest != i) + { std::swap(a[i], a[largest]); heapify(a, n, largest); } } -void heapsort(int *a, int n) { - for (int i = n - 1; i >= 0; --i) { +void heapsort(int *a, int n) +{ + for (int i = n - 1; i >= 0; --i) + { std::swap(a[0], a[i]); heapify(a, 0, i); } } -void build_maxheap(int *a, int n) { - for (int i = n / 2 - 1; i >= 0; --i) { +void build_maxheap(int *a, int n) +{ + for (int i = n / 2 - 1; i >= 0; --i) + { heapify(a, i, n); } } -int main() { +int main() +{ int n; std::cout << "Enter number of elements of array\n"; std::cin >> n; int a[20]; - for (int i = 0; i < n; ++i) { + for (int i = 0; i < n; ++i) + { std::cout << "Enter Element " << i << std::endl; std::cin >> a[i]; } @@ -44,7 +52,8 @@ int main() { build_maxheap(a, n); heapsort(a, n); std::cout << "Sorted Output\n"; - for (int i = 0; i < n; ++i) { + for (int i = 0; i < n; ++i) + { std::cout << a[i] << std::endl; } diff --git a/sorting/insertion_sort.cpp b/sorting/insertion_sort.cpp index fe920ca5913..b96a44c475f 100644 --- a/sorting/insertion_sort.cpp +++ b/sorting/insertion_sort.cpp @@ -2,7 +2,8 @@ #include -int main() { +int main() +{ int n; std::cout << "\nEnter the length of your array : "; std::cin >> n; @@ -10,15 +11,18 @@ int main() { std::cout << "\nEnter any " << n << " Numbers for Unsorted Array : "; // Input - for (int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) + { std::cin >> Array[i]; } // Sorting - for (int i = 1; i < n; i++) { + for (int i = 1; i < n; i++) + { int temp = Array[i]; int j = i - 1; - while (j >= 0 && temp < Array[j]) { + while (j >= 0 && temp < Array[j]) + { Array[j + 1] = Array[j]; j--; } @@ -27,7 +31,8 @@ int main() { // Output std::cout << "\nSorted Array : "; - for (int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) + { std::cout << Array[i] << "\t"; } diff --git a/sorting/library_sort.cpp b/sorting/library_sort.cpp index 6f1ab6245aa..c0fa857e7df 100644 --- a/sorting/library_sort.cpp +++ b/sorting/library_sort.cpp @@ -1,15 +1,15 @@ #include #include -void librarySort(int *index, int n) { +void librarySort(int *index, int n) +{ int lib_size, index_pos, *gaps, // gaps *library[2]; // libraries bool target_lib, *numbered; - for (int i = 0; i < 2; i++) - library[i] = new int[n]; + for (int i = 0; i < 2; i++) library[i] = new int[n]; gaps = new int[n + 1]; numbered = new bool[n + 1]; @@ -19,7 +19,8 @@ void librarySort(int *index, int n) { target_lib = 0; library[target_lib][0] = index[0]; - while (index_pos < n) { + while (index_pos < n) + { // binary search int insert = std::distance( library[target_lib], @@ -28,19 +29,23 @@ void librarySort(int *index, int n) { // if there is no gap to insert a new index ... - if (numbered[insert] == true) { + if (numbered[insert] == true) + { int prov_size = 0, next_target_lib = !target_lib; // update library and clear gaps - for (int i = 0; i <= n; i++) { - if (numbered[i] == true) { + for (int i = 0; i <= n; i++) + { + if (numbered[i] == true) + { library[next_target_lib][prov_size] = gaps[i]; prov_size++; numbered[i] = false; } - if (i <= lib_size) { + if (i <= lib_size) + { library[next_target_lib][prov_size] = library[target_lib][i]; prov_size++; @@ -49,7 +54,9 @@ void librarySort(int *index, int n) { target_lib = next_target_lib; lib_size = prov_size - 1; - } else { + } + else + { numbered[insert] = true; gaps[insert] = index[index_pos]; index_pos++; @@ -57,14 +64,17 @@ void librarySort(int *index, int n) { } int index_pos_for_output = 0; - for (int i = 0; index_pos_for_output < n; i++) { - if (numbered[i] == true) { + for (int i = 0; index_pos_for_output < n; i++) + { + if (numbered[i] == true) + { // std::cout << gaps[i] << std::endl; index[index_pos_for_output] = gaps[i]; index_pos_for_output++; } - if (i < lib_size) { + if (i < lib_size) + { // std::cout << library[target_lib][i] << std::endl; index[index_pos_for_output] = library[target_lib][i]; index_pos_for_output++; @@ -72,15 +82,15 @@ void librarySort(int *index, int n) { } } -int main() { +int main() +{ // ---example-- int index_ex[] = {-6, 5, 9, 1, 9, 1, 0, 1, -8, 4, -12}; int n_ex = sizeof(index_ex) / sizeof(index_ex[0]); librarySort(index_ex, n_ex); std::cout << "sorted array :" << std::endl; - for (int i = 0; i < n_ex; i++) - std::cout << index_ex[i] << " "; + for (int i = 0; i < n_ex; i++) std::cout << index_ex[i] << " "; std::cout << std::endl; /* --output-- diff --git a/sorting/merge_sort.cpp b/sorting/merge_sort.cpp index 82ab869cd2c..1a394ded9a0 100644 --- a/sorting/merge_sort.cpp +++ b/sorting/merge_sort.cpp @@ -1,6 +1,7 @@ #include -void merge(int arr[], int l, int m, int r) { +void merge(int arr[], int l, int m, int r) +{ int i, j, k; int n1 = m - l + 1; int n2 = r - m; @@ -13,24 +14,30 @@ void merge(int arr[], int l, int m, int r) { i = 0; j = 0; k = l; - while (i < n1 && j < n2) { - if (L[i] <= R[j]) { + while (i < n1 && j < n2) + { + if (L[i] <= R[j]) + { arr[k] = L[i]; i++; - } else { + } + else + { arr[k] = R[j]; j++; } k++; } - while (i < n1) { + while (i < n1) + { arr[k] = L[i]; i++; k++; } - while (j < n2) { + while (j < n2) + { arr[k] = R[j]; j++; k++; @@ -40,8 +47,10 @@ void merge(int arr[], int l, int m, int r) { delete[] R; } -void mergeSort(int arr[], int l, int r) { - if (l < r) { +void mergeSort(int arr[], int l, int r) +{ + if (l < r) + { int m = l + (r - l) / 2; mergeSort(arr, l, m); @@ -51,12 +60,14 @@ void mergeSort(int arr[], int l, int r) { } } -void show(int A[], int size) { +void show(int A[], int size) +{ int i; for (i = 0; i < size; i++) std::cout << A[i] << "\n"; } -int main() { +int main() +{ int size; std::cout << "\nEnter the number of elements : "; @@ -66,7 +77,8 @@ int main() { std::cout << "\nEnter the unsorted elements : "; - for (int i = 0; i < size; ++i) { + for (int i = 0; i < size; ++i) + { std::cout << "\n"; std::cin >> arr[i]; } diff --git a/sorting/non_recursive_merge_sort.cpp b/sorting/non_recursive_merge_sort.cpp index 9d4e95f2fdd..9086ec0edcc 100644 --- a/sorting/non_recursive_merge_sort.cpp +++ b/sorting/non_recursive_merge_sort.cpp @@ -22,17 +22,20 @@ void merge(Iterator, Iterator, const Iterator, char[]); */ template void non_recursive_merge_sort(const Iterator first, const Iterator last, - const size_t n) { + const size_t n) +{ // create a buffer large enough to store all elements // dynamically allocated to comply with cpplint char* buffer = new char[n * sizeof(*first)]; // buffer size can be optimized to largest power of 2 less than n elements // divide the container into equally-sized segments whose length start at 1 // and keeps increasing by factors of 2 - for (size_t length(1); length < n; length <<= 1) { + for (size_t length(1); length < n; length <<= 1) + { // merge adjacent segments whose number is n / (length * 2) Iterator left(first); - for (size_t counter(n / (length << 1)); counter; --counter) { + for (size_t counter(n / (length << 1)); counter; --counter) + { Iterator right(left + length), end(right + length); merge(left, right, end, buffer); left = end; @@ -53,7 +56,8 @@ void non_recursive_merge_sort(const Iterator first, const Iterator last, * @param b points at the buffer */ template -void merge(Iterator l, Iterator r, const Iterator e, char b[]) { +void merge(Iterator l, Iterator r, const Iterator e, char b[]) +{ // create 2 pointers to point at the buffer auto p(reinterpret_cast*>(b)), c(p); // move the left part of the segment @@ -73,7 +77,8 @@ void merge(Iterator l, Iterator r, const Iterator e, char b[]) { * @param n the number of elements */ template -void non_recursive_merge_sort(const Iterator first, const size_t n) { +void non_recursive_merge_sort(const Iterator first, const size_t n) +{ non_recursive_merge_sort(first, first + n, n); } /// bottom-up merge sort which sorts elements in a non-decreasing order @@ -82,16 +87,19 @@ void non_recursive_merge_sort(const Iterator first, const size_t n) { * @param last points to 1-step past the last element */ template -void non_recursive_merge_sort(const Iterator first, const Iterator last) { +void non_recursive_merge_sort(const Iterator first, const Iterator last) +{ non_recursive_merge_sort(first, last, last - first); } -int main(int argc, char** argv) { +int main(int argc, char** argv) +{ int size; std::cout << "Enter the number of elements : "; std::cin >> size; int* arr = new int[size]; - for (int i = 0; i < size; ++i) { + for (int i = 0; i < size; ++i) + { std::cout << "arr[" << i << "] = "; std::cin >> arr[i]; } diff --git a/sorting/numeric_string_sort.cpp b/sorting/numeric_string_sort.cpp index 8b86bb29d51..358cc63e346 100644 --- a/sorting/numeric_string_sort.cpp +++ b/sorting/numeric_string_sort.cpp @@ -13,40 +13,48 @@ #include #include -bool NumericSort(std::string a, std::string b) { - while (a[0] == '0') { +bool NumericSort(std::string a, std::string b) +{ + while (a[0] == '0') + { a.erase(a.begin()); } - while (b[0] == '0') { + while (b[0] == '0') + { b.erase(b.begin()); } int n = a.length(); int m = b.length(); - if (n == m) return a < b; + if (n == m) + return a < b; return n < m; } -int main() { +int main() +{ int n; std::cout << "Enter number of elements to be sorted Numerically\n"; std::cin >> n; std::vector v(n); std::cout << "Enter the string of Numbers\n"; - for (int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) + { std::cin >> v[i]; } sort(v.begin(), v.end()); std::cout << "Elements sorted normally \n"; - for (int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) + { std::cout << v[i] << " "; } std::cout << "\n"; std::sort(v.begin(), v.end(), NumericSort); std::cout << "Elements sorted Numerically \n"; - for (int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) + { std::cout << v[i] << " "; } diff --git a/sorting/odd_even_sort.cpp b/sorting/odd_even_sort.cpp index 62842c1745a..274f3033b56 100644 --- a/sorting/odd_even_sort.cpp +++ b/sorting/odd_even_sort.cpp @@ -6,56 +6,55 @@ using namespace std; void oddEven(vector &arr, int size) { - bool sorted = false; - while (!sorted) - { - sorted = true; - for (int i = 1; i < size - 1; i += 2) //Odd - { - if (arr[i] > arr[i + 1]) - { - swap(arr[i], arr[i + 1]); - sorted = false; - } - } - - for (int i = 0; i < size - 1; i += 2) //Even - { - if (arr[i] > arr[i + 1]) - { - swap(arr[i], arr[i + 1]); - sorted = false; - } - } - } + bool sorted = false; + while (!sorted) + { + sorted = true; + for (int i = 1; i < size - 1; i += 2) // Odd + { + if (arr[i] > arr[i + 1]) + { + swap(arr[i], arr[i + 1]); + sorted = false; + } + } + + for (int i = 0; i < size - 1; i += 2) // Even + { + if (arr[i] > arr[i + 1]) + { + swap(arr[i], arr[i + 1]); + sorted = false; + } + } + } } void show(vector A, int size) { - int i; - for (i = 0; i < size; i++) - cout << A[i] << "\n"; + int i; + for (i = 0; i < size; i++) cout << A[i] << "\n"; } int main() { - int size, temp; - cout << "\nEnter the number of elements : "; - cin >> size; + int size, temp; + cout << "\nEnter the number of elements : "; + cin >> size; - vector arr; + vector arr; - cout << "\nEnter the unsorted elements : \n"; + cout << "\nEnter the unsorted elements : \n"; - for (int i = 0; i < size; ++i) - { - cin >> temp; - arr.push_back(temp); - } + for (int i = 0; i < size; ++i) + { + cin >> temp; + arr.push_back(temp); + } - oddEven(arr, size); + oddEven(arr, size); - cout << "Sorted array\n"; - show(arr, size); - return 0; + cout << "Sorted array\n"; + show(arr, size); + return 0; } diff --git a/sorting/quick_sort.cpp b/sorting/quick_sort.cpp index 1db6b014e07..8bb376b2439 100644 --- a/sorting/quick_sort.cpp +++ b/sorting/quick_sort.cpp @@ -33,14 +33,17 @@ * */ -int partition(int arr[], int low, int high) { +int partition(int arr[], int low, int high) +{ int pivot = arr[high]; // taking the last element as pivot int i = (low - 1); // Index of smaller element - for (int j = low; j < high; j++) { + for (int j = low; j < high; j++) + { // If current element is smaller than or // equal to pivot - if (arr[j] <= pivot) { + if (arr[j] <= pivot) + { i++; // increment index of smaller element int temp = arr[i]; arr[i] = arr[j]; @@ -59,8 +62,10 @@ int partition(int arr[], int low, int high) { * low --> Starting index, * high --> Ending index */ -void quickSort(int arr[], int low, int high) { - if (low < high) { +void quickSort(int arr[], int low, int high) +{ + if (low < high) + { int p = partition(arr, low, high); quickSort(arr, low, p - 1); quickSort(arr, p + 1, high); @@ -68,13 +73,15 @@ void quickSort(int arr[], int low, int high) { } // prints the array after sorting -void show(int arr[], int size) { +void show(int arr[], int size) +{ for (int i = 0; i < size; i++) std::cout << arr[i] << " "; std::cout << "\n"; } /** Driver program to test above functions */ -int main() { +int main() +{ int size; std::cout << "\nEnter the number of elements : "; @@ -84,7 +91,8 @@ int main() { std::cout << "\nEnter the unsorted elements : "; - for (int i = 0; i < size; ++i) { + for (int i = 0; i < size; ++i) + { std::cout << "\n"; std::cin >> arr[i]; } diff --git a/sorting/radix_sort.cpp b/sorting/radix_sort.cpp index a0fbfe99ee5..c3b5b1629a9 100644 --- a/sorting/radix_sort.cpp +++ b/sorting/radix_sort.cpp @@ -3,53 +3,66 @@ #include #include -void radixsort(int a[], int n) { +void radixsort(int a[], int n) +{ int count[10]; int* output = new int[n]; memset(output, 0, n * sizeof(*output)); memset(count, 0, sizeof(count)); int max = 0; - for (int i = 0; i < n; ++i) { - if (a[i] > max) { + for (int i = 0; i < n; ++i) + { + if (a[i] > max) + { max = a[i]; } } int maxdigits = 0; - while (max) { + while (max) + { maxdigits++; max /= 10; } - for (int j = 0; j < maxdigits; j++) { - for (int i = 0; i < n; i++) { + for (int j = 0; j < maxdigits; j++) + { + for (int i = 0; i < n; i++) + { int t = std::pow(10, j); count[(a[i] % (10 * t)) / t]++; } int k = 0; - for (int p = 0; p < 10; p++) { - for (int i = 0; i < n; i++) { + for (int p = 0; p < 10; p++) + { + for (int i = 0; i < n; i++) + { int t = std::pow(10, j); - if ((a[i] % (10 * t)) / t == p) { + if ((a[i] % (10 * t)) / t == p) + { output[k] = a[i]; k++; } } } memset(count, 0, sizeof(count)); - for (int i = 0; i < n; ++i) { + for (int i = 0; i < n; ++i) + { a[i] = output[i]; } } delete[] output; } -void print(int a[], int n) { - for (int i = 0; i < n; ++i) { +void print(int a[], int n) +{ + for (int i = 0; i < n; ++i) + { std::cout << a[i] << " "; } std::cout << std::endl; } -int main(int argc, char const* argv[]) { +int main(int argc, char const* argv[]) +{ int a[] = {170, 45, 75, 90, 802, 24, 2, 66}; int n = sizeof(a) / sizeof(a[0]); radixsort(a, n); diff --git a/sorting/selection_sort.cpp b/sorting/selection_sort.cpp index 5b8724141aa..7e8b0678ceb 100644 --- a/sorting/selection_sort.cpp +++ b/sorting/selection_sort.cpp @@ -1,39 +1,39 @@ -//Selection Sort +// Selection Sort #include using namespace std; int main() { - int Array[6]; - cout << "\nEnter any 6 Numbers for Unsorted Array : "; + int Array[6]; + cout << "\nEnter any 6 Numbers for Unsorted Array : "; - //Input - for (int i = 0; i < 6; i++) - { - cin >> Array[i]; - } + // Input + for (int i = 0; i < 6; i++) + { + cin >> Array[i]; + } - //Selection Sorting - for (int i = 0; i < 6; i++) - { - int min = i; - for (int j = i + 1; j < 6; j++) - { - if (Array[j] < Array[min]) - { - min = j; //Finding the smallest number in Array - } - } - int temp = Array[i]; - Array[i] = Array[min]; - Array[min] = temp; - } + // Selection Sorting + for (int i = 0; i < 6; i++) + { + int min = i; + for (int j = i + 1; j < 6; j++) + { + if (Array[j] < Array[min]) + { + min = j; // Finding the smallest number in Array + } + } + int temp = Array[i]; + Array[i] = Array[min]; + Array[min] = temp; + } - //Output - cout << "\nSorted Array : "; - for (int i = 0; i < 6; i++) - { - cout << Array[i] << "\t"; - } + // Output + cout << "\nSorted Array : "; + for (int i = 0; i < 6; i++) + { + cout << Array[i] << "\t"; + } } diff --git a/sorting/shell_sort.cpp b/sorting/shell_sort.cpp index eb701478d4e..af783eb24ba 100644 --- a/sorting/shell_sort.cpp +++ b/sorting/shell_sort.cpp @@ -1,23 +1,31 @@ #include -int main() { +int main() +{ int size = 10; int* array = new int[size]; // Input std::cout << "\nHow many numbers do want to enter in unsorted array : "; std::cin >> size; std::cout << "\nEnter the numbers for unsorted array : "; - for (int i = 0; i < size; i++) { + for (int i = 0; i < size; i++) + { std::cin >> array[i]; } // Sorting - for (int i = size / 2; i > 0; i = i / 2) { - for (int j = i; j < size; j++) { - for (int k = j - i; k >= 0; k = k - i) { - if (array[k] < array[k + i]) { + for (int i = size / 2; i > 0; i = i / 2) + { + for (int j = i; j < size; j++) + { + for (int k = j - i; k >= 0; k = k - i) + { + if (array[k] < array[k + i]) + { break; - } else { + } + else + { int temp = array[k + i]; array[k + i] = array[k]; array[k] = temp; @@ -28,7 +36,8 @@ int main() { // Output std::cout << "\nSorted array : "; - for (int i = 0; i < size; ++i) { + for (int i = 0; i < size; ++i) + { std::cout << array[i] << "\t"; } diff --git a/sorting/shell_sort2.cpp b/sorting/shell_sort2.cpp index 1268c7a50e7..dee8cecd779 100644 --- a/sorting/shell_sort2.cpp +++ b/sorting/shell_sort2.cpp @@ -6,100 +6,113 @@ // for std::swap #include -template void show_data(T *arr, size_t LEN) { - size_t i; +template +void show_data(T *arr, size_t LEN) +{ + size_t i; - for (i = 0; i < LEN; i++) - std::cout << arr[i] << ", "; - std::cout << std::endl; + for (i = 0; i < LEN; i++) std::cout << arr[i] << ", "; + std::cout << std::endl; } -template void show_data(T (&arr)[N]) { show_data(arr, N); } +template +void show_data(T (&arr)[N]) +{ + show_data(arr, N); +} /** * Optimized algorithm - takes half the time by utilizing * Mar **/ -template void shell_sort(T *arr, size_t LEN) { - const unsigned int gaps[] = {701, 301, 132, 57, 23, 10, 4, 1}; - const unsigned int gap_len = 8; - size_t i, j, g; - - for (g = 0; g < gap_len; g++) { - unsigned int gap = gaps[g]; - for (i = gap; i < LEN; i++) { - T tmp = arr[i]; - - for (j = i; j >= gap && (arr[j - gap] - tmp) > 0; j -= gap) - arr[j] = arr[j - gap]; - - arr[j] = tmp; +template +void shell_sort(T *arr, size_t LEN) +{ + const unsigned int gaps[] = {701, 301, 132, 57, 23, 10, 4, 1}; + const unsigned int gap_len = 8; + size_t i, j, g; + + for (g = 0; g < gap_len; g++) + { + unsigned int gap = gaps[g]; + for (i = gap; i < LEN; i++) + { + T tmp = arr[i]; + + for (j = i; j >= gap && (arr[j - gap] - tmp) > 0; j -= gap) + arr[j] = arr[j - gap]; + + arr[j] = tmp; + } } - } } -template void shell_sort(T (&arr)[N]) { - shell_sort(arr, N); +template +void shell_sort(T (&arr)[N]) +{ + shell_sort(arr, N); } /** * function to compare sorting using cstdlib's qsort **/ -int compare(const void *a, const void *b) { - int arg1 = *static_cast(a); - int arg2 = *static_cast(b); - - if (arg1 < arg2) - return -1; - if (arg1 > arg2) - return 1; - return 0; - - // return (arg1 > arg2) - (arg1 < arg2); // possible shortcut - // return arg1 - arg2; // erroneous shortcut (fails if INT_MIN is present) +int compare(const void *a, const void *b) +{ + int arg1 = *static_cast(a); + int arg2 = *static_cast(b); + + if (arg1 < arg2) + return -1; + if (arg1 > arg2) + return 1; + return 0; + + // return (arg1 > arg2) - (arg1 < arg2); // possible shortcut + // return arg1 - arg2; // erroneous shortcut (fails if INT_MIN is present) } -int main(int argc, char *argv[]) { - int i, NUM_DATA; - - if (argc == 2) - NUM_DATA = atoi(argv[1]); - else - NUM_DATA = 200; - - // int array = new int[NUM_DATA]; - int *data = new int[NUM_DATA]; - int *data2 = new int[NUM_DATA]; - // int array2 = new int[NUM_DATA]; - int range = 1800; - - std::srand(time(NULL)); - for (i = 0; i < NUM_DATA; i++) - data[i] = data2[i] = (std::rand() % range) - (range >> 1); - - std::cout << "Unsorted original data: " << std::endl; - show_data(data, NUM_DATA); - std::clock_t start = std::clock(); - shell_sort(data, NUM_DATA); - std::clock_t end = std::clock(); - - std::cout << std::endl - << "Data Sorted using custom implementation: " << std::endl; - show_data(data, NUM_DATA); - - double elapsed_time = (end - start) * 1.f / CLOCKS_PER_SEC; - std::cout << "Time spent sorting: " << elapsed_time << "s\n" << std::endl; - - start = std::clock(); - qsort(data2, NUM_DATA, sizeof(data2[0]), compare); - end = std::clock(); - std::cout << "Data Sorted using cstdlib qsort: " << std::endl; - show_data(data2, NUM_DATA); - - elapsed_time = (end - start) * 1.f / CLOCKS_PER_SEC; - std::cout << "Time spent sorting: " << elapsed_time << "s\n" << std::endl; - - free(data); - free(data2); - return 0; +int main(int argc, char *argv[]) +{ + int i, NUM_DATA; + + if (argc == 2) + NUM_DATA = atoi(argv[1]); + else + NUM_DATA = 200; + + // int array = new int[NUM_DATA]; + int *data = new int[NUM_DATA]; + int *data2 = new int[NUM_DATA]; + // int array2 = new int[NUM_DATA]; + int range = 1800; + + std::srand(time(NULL)); + for (i = 0; i < NUM_DATA; i++) + data[i] = data2[i] = (std::rand() % range) - (range >> 1); + + std::cout << "Unsorted original data: " << std::endl; + show_data(data, NUM_DATA); + std::clock_t start = std::clock(); + shell_sort(data, NUM_DATA); + std::clock_t end = std::clock(); + + std::cout << std::endl + << "Data Sorted using custom implementation: " << std::endl; + show_data(data, NUM_DATA); + + double elapsed_time = (end - start) * 1.f / CLOCKS_PER_SEC; + std::cout << "Time spent sorting: " << elapsed_time << "s\n" << std::endl; + + start = std::clock(); + qsort(data2, NUM_DATA, sizeof(data2[0]), compare); + end = std::clock(); + std::cout << "Data Sorted using cstdlib qsort: " << std::endl; + show_data(data2, NUM_DATA); + + elapsed_time = (end - start) * 1.f / CLOCKS_PER_SEC; + std::cout << "Time spent sorting: " << elapsed_time << "s\n" << std::endl; + + free(data); + free(data2); + return 0; } diff --git a/sorting/slow_sort.cpp b/sorting/slow_sort.cpp index b2627d12f3a..e4f175af6f8 100644 --- a/sorting/slow_sort.cpp +++ b/sorting/slow_sort.cpp @@ -10,14 +10,17 @@ #include -void SlowSort(int a[], int i, int j) { - if (i >= j) return; +void SlowSort(int a[], int i, int j) +{ + if (i >= j) + return; int m = i + (j - i) / 2; // midpoint, implemented this way to avoid // overflow int temp; SlowSort(a, i, m); SlowSort(a, m + 1, j); - if (a[j] < a[m]) { + if (a[j] < a[m]) + { temp = a[j]; // swapping a[j] & a[m] a[j] = a[m]; a[m] = temp; @@ -27,7 +30,8 @@ void SlowSort(int a[], int i, int j) { // Sample Main function -int main() { +int main() +{ int size; std::cout << "\nEnter the number of elements : "; @@ -37,7 +41,8 @@ int main() { std::cout << "\nEnter the unsorted elements : "; - for (int i = 0; i < size; ++i) { + for (int i = 0; i < size; ++i) + { std::cout << "\n"; std::cin >> arr[i]; } @@ -46,7 +51,8 @@ int main() { std::cout << "Sorted array\n"; - for (int i = 0; i < size; ++i) { + for (int i = 0; i < size; ++i) + { std::cout << arr[i] << " "; } diff --git a/sorting/swap_sort.cpp b/sorting/swap_sort.cpp index 2e59e2fb3bf..7d391d8a193 100644 --- a/sorting/swap_sort.cpp +++ b/sorting/swap_sort.cpp @@ -6,12 +6,14 @@ // Function returns the minimum number of swaps // required to sort the array -int minSwaps(int arr[], int n) { +int minSwaps(int arr[], int n) +{ // Create an array of pairs where first // element is array element and second element // is position of first element std::pair *arrPos = new std::pair[n]; - for (int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) + { arrPos[i].first = arr[i]; arrPos[i].second = i; } @@ -29,16 +31,19 @@ int minSwaps(int arr[], int n) { int ans = 0; // Traverse array elements - for (int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) + { // already swapped and corrected or // already present at correct pos - if (vis[i] || arrPos[i].second == i) continue; + if (vis[i] || arrPos[i].second == i) + continue; // find out the number of node in // this cycle and add in ans int cycle_size = 0; int j = i; - while (!vis[j]) { + while (!vis[j]) + { vis[j] = 1; // move to next node @@ -47,7 +52,8 @@ int minSwaps(int arr[], int n) { } // Update answer by adding current cycle. - if (cycle_size > 0) { + if (cycle_size > 0) + { ans += (cycle_size - 1); } } @@ -59,7 +65,8 @@ int minSwaps(int arr[], int n) { } // program to test -int main() { +int main() +{ int arr[] = {6, 7, 8, 1, 2, 3, 9, 12}; int n = (sizeof(arr) / sizeof(int)); std::cout << minSwaps(arr, n); diff --git a/sorting/tim_sort.cpp b/sorting/tim_sort.cpp index 94f5aa230b3..9645a60b168 100644 --- a/sorting/tim_sort.cpp +++ b/sorting/tim_sort.cpp @@ -6,11 +6,14 @@ const int RUN = 32; // this function sorts array from left index to to right index which is of size // atmost RUN -void insertionSort(int arr[], int left, int right) { - for (int i = left + 1; i <= right; i++) { +void insertionSort(int arr[], int left, int right) +{ + for (int i = left + 1; i <= right; i++) + { int temp = arr[i]; int j = i - 1; - while (arr[j] > temp && j >= left) { + while (arr[j] > temp && j >= left) + { arr[j + 1] = arr[j]; j--; } @@ -19,7 +22,8 @@ void insertionSort(int arr[], int left, int right) { } // merge function merges the sorted runs -void merge(int arr[], int l, int m, int r) { +void merge(int arr[], int l, int m, int r) +{ // original array is broken in two parts, left and right array int len1 = m - l + 1, len2 = r - m; int *left = new int[len1], *right = new int[len2]; @@ -31,11 +35,15 @@ void merge(int arr[], int l, int m, int r) { int k = l; // after comparing, we merge those two array in larger sub array - while (i < len1 && j < len2) { - if (left[i] <= right[j]) { + while (i < len1 && j < len2) + { + if (left[i] <= right[j]) + { arr[k] = left[i]; i++; - } else { + } + else + { arr[k] = right[j]; j++; } @@ -43,14 +51,16 @@ void merge(int arr[], int l, int m, int r) { } // copy remaining elements of left, if any - while (i < len1) { + while (i < len1) + { arr[k] = left[i]; k++; i++; } // copy remaining element of right, if any - while (j < len2) { + while (j < len2) + { arr[k] = right[j]; k++; j++; @@ -60,18 +70,21 @@ void merge(int arr[], int l, int m, int r) { } // iterative Timsort function to sort the array[0...n-1] (similar to merge sort) -void timSort(int arr[], int n) { +void timSort(int arr[], int n) +{ // Sort individual subarrays of size RUN for (int i = 0; i < n; i += RUN) insertionSort(arr, i, std::min((i + 31), (n - 1))); // start merging from size RUN (or 32). It will merge to form size 64, then // 128, 256 and so on .... - for (int size = RUN; size < n; size = 2 * size) { + for (int size = RUN; size < n; size = 2 * size) + { // pick starting point of left sub array. We are going to merge // arr[left..left+size-1] and arr[left+size, left+2*size-1] After every // merge, we increase left by 2*size - for (int left = 0; left < n; left += 2 * size) { + for (int left = 0; left < n; left += 2 * size) + { // find ending point of left sub array // mid+1 is starting point of right sub array int mid = left + size - 1; @@ -84,13 +97,15 @@ void timSort(int arr[], int n) { } // utility function to print the Array -void printArray(int arr[], int n) { +void printArray(int arr[], int n) +{ for (int i = 0; i < n; i++) printf("%d ", arr[i]); std::cout << std::endl; } // Driver program to test above function -int main() { +int main() +{ int arr[] = {5, 21, 7, 23, 19}; int n = sizeof(arr) / sizeof(arr[0]); printf("Given Array is\n"); diff --git a/strings/brute_force_string_searching.cpp b/strings/brute_force_string_searching.cpp index 9a2b5327a35..5f6116e1b74 100644 --- a/strings/brute_force_string_searching.cpp +++ b/strings/brute_force_string_searching.cpp @@ -17,14 +17,18 @@ * @return Index where the pattern starts in the text * @return -1 if the pattern was not found. */ -int brute_force(const std::string &text, const std::string &pattern) { +int brute_force(const std::string &text, const std::string &pattern) +{ size_t pat_l = pattern.length(); size_t txt_l = text.length(); int index = -1; - if (pat_l <= txt_l) { - for (size_t i = 0; i < txt_l - pat_l + 1; i++) { + if (pat_l <= txt_l) + { + for (size_t i = 0; i < txt_l - pat_l + 1; i++) + { std::string s = text.substr(i, pat_l); - if (s == pattern) { + if (s == pattern) + { index = i; break; } @@ -40,8 +44,10 @@ const std::vector> test_set = { {"bba", "bb", "0"}, {"bbca", "c", "2"}, {"ab", "b", "1"}}; /** Main function */ -int main() { - for (size_t i = 0; i < test_set.size(); i++) { +int main() +{ + for (size_t i = 0; i < test_set.size(); i++) + { int output = brute_force(test_set[i][0], test_set[i][1]); if (std::to_string(output) == test_set[i][2]) diff --git a/strings/knuth_morris_pratt.cpp b/strings/knuth_morris_pratt.cpp index b83cab96632..29e6ef834e2 100644 --- a/strings/knuth_morris_pratt.cpp +++ b/strings/knuth_morris_pratt.cpp @@ -26,14 +26,17 @@ * \param[in] pattern text for which to create the partial match table * \returns the partial match table as a vector array */ -std::vector getFailureArray(const std::string &pattern) { +std::vector getFailureArray(const std::string &pattern) +{ int pattern_length = pattern.size(); std::vector failure(pattern_length + 1); failure[0] = -1; int j = -1; - for (int i = 0; i < pattern_length; i++) { - while (j != -1 && pattern[j] != pattern[i]) { + for (int i = 0; i < pattern_length; i++) + { + while (j != -1 && pattern[j] != pattern[i]) + { j = failure[j]; } j++; @@ -49,13 +52,16 @@ std::vector getFailureArray(const std::string &pattern) { * \returns `true` if pattern was found * \returns `false` if pattern was not found */ -bool kmp(const std::string &pattern, const std::string &text) { +bool kmp(const std::string &pattern, const std::string &text) +{ int text_length = text.size(), pattern_length = pattern.size(); std::vector failure = getFailureArray(pattern); int k = 0; - for (int j = 0; j < text_length; j++) { - while (k != -1 && pattern[k] != text[j]) { + for (int j = 0; j < text_length; j++) + { + while (k != -1 && pattern[k] != text[j]) + { k = failure[k]; } k++; @@ -66,21 +72,28 @@ bool kmp(const std::string &pattern, const std::string &text) { } /** Main function */ -int main() { +int main() +{ std::string text = "alskfjaldsabc1abc1abc12k23adsfabcabc"; std::string pattern = "abc1abc12l"; - if (kmp(pattern, text) == true) { + if (kmp(pattern, text) == true) + { std::cout << "Found" << std::endl; - } else { + } + else + { std::cout << "Not Found" << std::endl; } text = "abcabc"; pattern = "bca"; - if (kmp(pattern, text) == true) { + if (kmp(pattern, text) == true) + { std::cout << "Found" << std::endl; - } else { + } + else + { std::cout << "Not Found" << std::endl; } diff --git a/strings/rabin_karp.cpp b/strings/rabin_karp.cpp index 018ff56324f..5baaaf61574 100644 --- a/strings/rabin_karp.cpp +++ b/strings/rabin_karp.cpp @@ -21,9 +21,11 @@ * \param[in] n length of substring to hash * \returns hash integer */ -int64_t create_hash(const std::string& s, int n) { +int64_t create_hash(const std::string& s, int n) +{ int64_t result = 0; - for (int i = 0; i < n; ++i) { + for (int i = 0; i < n; ++i) + { result += (int64_t)(s[i] * (int64_t)pow(PRIME, i)); } return result; @@ -39,7 +41,8 @@ int64_t create_hash(const std::string& s, int n) { * \returns new hash integer */ int64_t recalculate_hash(const std::string& s, int old_index, int new_index, - int64_t old_hash, int patLength) { + int64_t old_hash, int patLength) +{ int64_t new_hash = old_hash - s[old_index]; new_hash /= PRIME; new_hash += (int64_t)(s[new_index] * (int64_t)pow(PRIME, patLength - 1)); @@ -57,12 +60,16 @@ int64_t recalculate_hash(const std::string& s, int old_index, int new_index, * @note can this be replaced by std::string::compare? */ bool check_if_equal(const std::string& str1, const std::string& str2, - int start1, int end1, int start2, int end2) { - if (end1 - start1 != end2 - start2) { + int start1, int end1, int start2, int end2) +{ + if (end1 - start1 != end2 - start2) + { return false; } - while (start1 <= end1 && start2 <= end2) { - if (str1[start1] != str2[start2]) { + while (start1 <= end1 && start2 <= end2) + { + if (str1[start1] != str2[start2]) + { return false; } start1++; @@ -79,16 +86,19 @@ bool check_if_equal(const std::string& str1, const std::string& str2, * @return -1 if pattern not found */ -int rabin_karp(const std::string& str, const std::string& pat) { +int rabin_karp(const std::string& str, const std::string& pat) +{ int64_t pat_hash = create_hash(pat, pat.size()); int64_t str_hash = create_hash(str, pat.size()); - for (int i = 0; i <= str.size() - pat.size(); ++i) { + for (int i = 0; i <= str.size() - pat.size(); ++i) + { if (pat_hash == str_hash && - check_if_equal(str, pat, i, i + pat.size() - 1, 0, - pat.size() - 1)) { + check_if_equal(str, pat, i, i + pat.size() - 1, 0, pat.size() - 1)) + { return i; } - if (i < str.size() - pat.size()) { + if (i < str.size() - pat.size()) + { str_hash = recalculate_hash(str, i, i + pat.size(), str_hash, pat.size()); } @@ -97,7 +107,8 @@ int rabin_karp(const std::string& str, const std::string& pat) { } /** Main function */ -int main(void) { +int main(void) +{ assert(rabin_karp("helloWorld", "world") == -1); assert(rabin_karp("helloWorld", "World") == 5); assert(rabin_karp("this_is_c++", "c++") == 8); From 7e634c2cb34442e73892a6764dc601f25008f7c4 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 19:30:10 -0400 Subject: [PATCH 269/433] remove allman break before braces --- .github/workflows/clang-format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index a8d61e423f1..94cd125bb38 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -50,7 +50,7 @@ jobs: git commit -am "formatting source-code for $GITHUB_SHA" || true env: line1: "{ BasedOnStyle: Google, UseTab: Never," - line2: "IndentWidth: 4, TabWidth: 4, BreakBeforeBraces: Allman," + line2: "IndentWidth: 4, TabWidth: 4" line3: "AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: false," line4: "ColumnLimit: 80, AccessModifierOffset: -3 }" - name: Git Push From 5c40942257209da5889985da12be758b10269317 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 29 May 2020 23:30:37 +0000 Subject: [PATCH 270/433] updating DIRECTORY.md --- DIRECTORY.md | 96 ++++++++++++++++++++++++++-------------------------- 1 file changed, 48 insertions(+), 48 deletions(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index d90326050d7..33453868571 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -18,10 +18,10 @@ * [Successive Approximation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/successive_approximation.cpp) ## Data Structure - * [Avltree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/AVLtree.cpp) - * [Binary Search Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Binary%20Search%20Tree.cpp) - * [Binaryheap](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Binaryheap.cpp) - * [Circular Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/circular_Queue_using_Linked_List.cpp) + * [Avltree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/avltree.cpp) + * [Binary Search Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/binary_search_tree.cpp) + * [Binaryheap](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/binaryheap.cpp) + * [Circular Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/circular_queue_using_linked_list.cpp) * Cll * [Cll](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/cll/cll.cpp) * [Cll](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/cll/cll.h) @@ -29,73 +29,73 @@ * [Disjoint Set](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/disjoint_set.cpp) * [Doubly Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/doubly_linked_list.cpp) * [Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/linked_list.cpp) - * [Linkedlist Implentation Usingarray](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/linkedList_implentation_usingArray.cpp) - * [List Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/List%20Array.cpp) - * [Morrisinorder](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/MorrisInorder.cpp) - * [Queue Using Array2](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Queue%20Using%20Array2.cpp) - * [Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Queue%20Using%20Linked%20List.cpp) + * [Linkedlist Implentation Usingarray](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/linkedlist_implentation_usingarray.cpp) + * [List Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/list_array.cpp) + * [Morrisinorder](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/morrisinorder.cpp) * Queue * [Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue/queue.cpp) * [Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue/queue.h) * [Test Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue/test_queue.cpp) * [Queue Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue_using_array.cpp) + * [Queue Using Array2](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue_using_array2.cpp) + * [Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue_using_linked_list.cpp) * [Queue Using Linkedlist](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue_using_linkedlist.cpp) - * [Stack Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Stack%20Using%20Array.cpp) - * [Stack Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Stack%20Using%20Linked%20List.cpp) + * [Stack Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stack_using_array.cpp) + * [Stack Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stack_using_linked_list.cpp) * Stk * [Main](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/main.cpp) * [Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/stack.cpp) * [Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/stack.h) * [Test Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/test_stack.cpp) - * [Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Tree.cpp) + * [Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/tree.cpp) * [Trie Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/trie_tree.cpp) ## Dynamic Programming - * [0-1 Knapsack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/0-1%20Knapsack.cpp) + * [0 1 Knapsack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/0_1_knapsack.cpp) * [Armstrong Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/armstrong_number.cpp) - * [Bellman-Ford](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Bellman-Ford.cpp) - * [Catalan-Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Catalan-Numbers.cpp) - * [Coin-Change](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Coin-Change.cpp) - * [Cut Rod](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Cut%20Rod.cpp) - * [Edit Distance](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Edit%20Distance.cpp) - * [Egg-Dropping-Puzzle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Egg-Dropping-Puzzle.cpp) - * [Fibonacci Bottom Up](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Fibonacci_Bottom_Up.cpp) - * [Fibonacci Top Down](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Fibonacci_Top_Down.cpp) - * [Floyd-Warshall](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Floyd-Warshall.cpp) + * [Bellman Ford](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/bellman_ford.cpp) + * [Catalan Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/catalan_numbers.cpp) + * [Coin Change](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/coin_change.cpp) + * [Cut Rod](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/cut_rod.cpp) + * [Edit Distance](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/edit_distance.cpp) + * [Egg Dropping Puzzle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/egg_dropping_puzzle.cpp) + * [Fibonacci Bottom Up](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/fibonacci_bottom_up.cpp) + * [Fibonacci Top Down](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/fibonacci_top_down.cpp) + * [Floyd Warshall](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/floyd_warshall.cpp) * [Kadane](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/kadane.cpp) - * [Longest Common Subsequence](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Longest%20Common%20Subsequence.cpp) - * [Longest Increasing Subsequence (Nlogn)](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Longest%20Increasing%20Subsequence%20(nlogn).cpp) - * [Longest Increasing Subsequence](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Longest%20Increasing%20Subsequence.cpp) * [Longest Common String](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/longest_common_string.cpp) - * [Matrix-Chain-Multiplication](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Matrix-Chain-Multiplication.cpp) + * [Longest Common Subsequence](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/longest_common_subsequence.cpp) + * [Longest Increasing Subsequence](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/longest_increasing_subsequence.cpp) + * [Longest Increasing Subsequence (Nlogn)](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/longest_increasing_subsequence_(nlogn).cpp) + * [Matrix Chain Multiplication](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/matrix_chain_multiplication.cpp) * [Searching Of Element In Dynamic Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/searching_of_element_in_dynamic_array.cpp) * [Tree Height](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/tree_height.cpp) ## Graph - * [Bfs](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/BFS.cpp) + * [Bfs](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/bfs.cpp) * [Bridge Finding With Tarjan Algorithm](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/bridge_finding_with_tarjan_algorithm.cpp) * [Connected Components](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/connected_components.cpp) * [Connected Components With Dsu](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/connected_components_with_dsu.cpp) - * [Dfs](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/DFS.cpp) + * [Dfs](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/dfs.cpp) * [Dfs With Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/DFS_with_stack.cc) - * [Dijkstra](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/Dijkstra.cpp) + * [Dijkstra](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/dijkstra.cpp) * [Kosaraju](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/kosaraju.cpp) - * [Kruskal](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/Kruskal.cpp) + * [Kruskal](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/kruskal.cpp) * [Lca](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/lca.cpp) * [Max Flow With Ford Fulkerson And Edmond Karp Algo](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/max_flow_with_ford_fulkerson_and_edmond_karp_algo.cpp) * [Prim](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/prim.cpp) - * [Topological-Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/Topological-Sort.cpp) + * [Topological Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/topological_sort.cpp) * [Topological Sort By Kahns Algo](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/topological_sort_by_kahns_algo.cpp) ## Greedy Algorithms - * [Dijkstra](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/Dijkstra.cpp) + * [Dijkstra](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/dijkstra.cpp) * [Huffman](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/huffman.cpp) - * [Knapsack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/Knapsack.cpp) - * [Kruskals Minimum Spanning Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/Kruskals%20Minimum%20Spanning%20Tree.cpp) - * [Prims Minimum Spanning Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/Prims%20Minimum%20Spanning%20Tree.cpp) + * [Knapsack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/knapsack.cpp) + * [Kruskals Minimum Spanning Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/kruskals_minimum_spanning_tree.cpp) + * [Prims Minimum Spanning Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/prims_minimum_spanning_tree.cpp) ## Hashing - * [Chaining](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/Chaining.cpp) + * [Chaining](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/chaining.cpp) * [Double Hash Hash Table](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/double_hash_hash_table.cpp) * [Linear Probing Hash Table](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/linear_probing_hash_table.cpp) * [Quadratic Probing Hash Table](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/quadratic_probing_hash_table.cpp) @@ -126,15 +126,15 @@ * [String Fibonacci](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/string_fibonacci.cpp) ## Operations On Datastructures - * [Array Left Rotation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Array%20Left%20Rotation.cpp) - * [Array Right Rotation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Array%20Right%20Rotation.cpp) - * [Circular Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Circular%20Linked%20List.cpp) - * [Circular Queue Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Circular%20Queue%20Using%20Array.cpp) + * [Array Left Rotation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/array_left_rotation.cpp) + * [Array Right Rotation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/array_right_rotation.cpp) + * [Circular Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/circular_linked_list.cpp) + * [Circular Queue Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/circular_queue_using_array.cpp) * [Get Size Of Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/get_size_of_linked_list.cpp) - * [Intersection Of 2 Arrays](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Intersection_of_2_arrays.cpp) - * [Reverse A Linked List Using Recusion](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Reverse%20a%20Linked%20List%20using%20Recusion.cpp) - * [Selectionsortlinkedlist](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/selectionSortLinkedList.cpp) - * [Union Of 2 Arrays](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Union_of_2_arrays.cpp) + * [Intersection Of 2 Arrays](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/intersection_of_2_arrays.cpp) + * [Reverse A Linked List Using Recusion](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/reverse_a_linked_list_using_recusion.cpp) + * [Selectionsortlinkedlist](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/selectionsortlinkedlist.cpp) + * [Union Of 2 Arrays](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/union_of_2_arrays.cpp) ## Others * [Buzz Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/buzz_number.cpp) @@ -163,9 +163,9 @@ ## Range Queries * [Bit](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/bit.cpp) - * [Fenwicktree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/FenwickTree.cpp) - * [Mo](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/MO.cpp) - * [Segtree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/segTree.cpp) + * [Fenwicktree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/fenwicktree.cpp) + * [Mo](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/mo.cpp) + * [Segtree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/segtree.cpp) ## Search * [Binary Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/binary_search.cpp) @@ -186,7 +186,7 @@ * [Bucket Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/bucket_sort.cpp) * [Cocktail Selection Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/cocktail_selection_sort.cpp) * [Comb Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/comb_sort.cpp) - * [Counting Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Counting_Sort.cpp) + * [Counting Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/counting_sort.cpp) * [Counting Sort String](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/counting_sort_string.cpp) * [Heap Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/heap_sort.cpp) * [Insertion Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/insertion_sort.cpp) From daca1b5715dc069e8f956b6256eeb0fc25713bca Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 19:31:48 -0400 Subject: [PATCH 271/433] added missing comma lost in previous commit --- .github/workflows/clang-format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 94cd125bb38..191e121cd68 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -50,7 +50,7 @@ jobs: git commit -am "formatting source-code for $GITHUB_SHA" || true env: line1: "{ BasedOnStyle: Google, UseTab: Never," - line2: "IndentWidth: 4, TabWidth: 4" + line2: "IndentWidth: 4, TabWidth: 4, " line3: "AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: false," line4: "ColumnLimit: 80, AccessModifierOffset: -3 }" - name: Git Push From e9d29caf6b30ef54d2599e397eb0b309c2c70cf2 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 21:23:17 -0400 Subject: [PATCH 272/433] orchestrate all workflows --- .github/workflows/ccpp.yml | 23 ----- .github/workflows/clang-format.yml | 96 +++++++++++++++++++- .github/workflows/cpplint.yml | 13 --- .github/workflows/cpplint_modified_files.yml | 66 -------------- .github/workflows/update_directory_md.yml | 68 -------------- 5 files changed, 94 insertions(+), 172 deletions(-) delete mode 100644 .github/workflows/ccpp.yml delete mode 100644 .github/workflows/cpplint.yml delete mode 100644 .github/workflows/cpplint_modified_files.yml delete mode 100644 .github/workflows/update_directory_md.yml diff --git a/.github/workflows/ccpp.yml b/.github/workflows/ccpp.yml deleted file mode 100644 index 34085cdecb0..00000000000 --- a/.github/workflows/ccpp.yml +++ /dev/null @@ -1,23 +0,0 @@ -name: C/C++ CI - -on: [push] -# push: -# branches: [ master ] -# pull_request: -# branches: [ master ] - -jobs: - build: - runs-on: ${{ matrix.os }} - strategy: - matrix: - os: [ubuntu-latest, windows-latest, macOS-latest] - - steps: - - uses: actions/checkout@master - with: - submodules: true - - name: configure - run: cmake -B ./build -S . - - name: build - run: cmake --build build diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 191e121cd68..092564fc408 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -1,4 +1,4 @@ -name: Code Formatting +name: Long CI Workflow on: [push] # push: @@ -7,7 +7,8 @@ on: [push] # branches: [ master ] jobs: - build: + code_format: + name: Code Formatter runs-on: ubuntu-latest steps: - name: requirements @@ -55,3 +56,94 @@ jobs: line4: "ColumnLimit: 80, AccessModifierOffset: -3 }" - name: Git Push run: git pull && git push + + update_directory_md: + name: Update Directory.md + needs: code_format + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-python@v1 + - name: update_directory_md + shell: python + run: | + import os + from typing import Iterator + + URL_BASE = "https://github.com/TheAlgorithms/C-Plus-Plus/blob/master" + g_output = [] + + + def good_filepaths(top_dir: str = ".") -> Iterator[str]: + cpp_exts = tuple(".c .c++ .cc .cpp .cu .cuh .cxx .h .h++ .hh .hpp .hxx".split()) + for dirpath, dirnames, filenames in os.walk(top_dir): + dirnames[:] = [d for d in dirnames if d[0] not in "._"] + for filename in filenames: + if os.path.splitext(filename)[1].lower() in cpp_exts: + yield os.path.join(dirpath, filename).lstrip("./") + + + def md_prefix(i): + return f"{i * ' '}*" if i else "\n##" + + + def print_path(old_path: str, new_path: str) -> str: + global g_output + old_parts = old_path.split(os.sep) + for i, new_part in enumerate(new_path.split(os.sep)): + if i + 1 > len(old_parts) or old_parts[i] != new_part: + if new_part: + g_output.append(f"{md_prefix(i)} {new_part.replace('_', ' ').title()}") + return new_path + + + def build_directory_md(top_dir: str = ".") -> str: + global g_output + old_path = "" + for filepath in sorted(good_filepaths(), key=str.lower): + filepath, filename = os.path.split(filepath) + if filepath != old_path: + old_path = print_path(old_path, filepath) + indent = (filepath.count(os.sep) + 1) if filepath else 0 + url = "/".join((URL_BASE, filepath, filename)).replace(" ", "%20") + filename = os.path.splitext(filename.replace("_", " ").title())[0] + g_output.append(f"{md_prefix(indent)} [{filename}]({url})") + return "\n".join(g_output) + + + with open("DIRECTORY.md", "w") as out_file: + out_file.write(build_directory_md(".") + "\n") + - name: Update DIRECTORY.md + run: | + cat DIRECTORY.md + git config --global user.name github-actions + git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' + git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY + git add DIRECTORY.md + git commit -am "updating DIRECTORY.md" || true + git push --force origin HEAD:$GITHUB_REF || true + + cpplint: + name: CPPLINT + needs: code_format + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + - uses: actions/setup-python@v1 + - run: pip install cpplint + - run: cpplint --filter=-legal --recursive . + + build: + runs-on: ${{ matrix.os }} + needs: [cpplint, update_directory_md] + strategy: + matrix: + os: [ubuntu-latest, windows-latest, macOS-latest] + steps: + - uses: actions/checkout@master + with: + submodules: true + - name: configure + run: cmake -B ./build -S . + - name: build + run: cmake --build build diff --git a/.github/workflows/cpplint.yml b/.github/workflows/cpplint.yml deleted file mode 100644 index a6999e1f25c..00000000000 --- a/.github/workflows/cpplint.yml +++ /dev/null @@ -1,13 +0,0 @@ -name: cpplint -on: [push, pull_request] -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v1 - - uses: actions/setup-python@v1 - - run: pip install cpplint - # - run: cpplint --filter= # print out all cpplint rules - - run: cpplint --recursive . || true # all issues to be fixed - # TODO: Remove each filter one at a time and fix those failures - - run: cpplint --filter=-build,-legal,-readability,-runtime,-whitespace --recursive . diff --git a/.github/workflows/cpplint_modified_files.yml b/.github/workflows/cpplint_modified_files.yml deleted file mode 100644 index a5aa6a65263..00000000000 --- a/.github/workflows/cpplint_modified_files.yml +++ /dev/null @@ -1,66 +0,0 @@ -# GitHub Action that enables a repo to achieve gradual compliance with cpplint by -# linting only those files that have been added or modified (vs. origin/master). -# 1. runs cpplint only on those files that have been modified vs. origin/master. -# 2. compiles with g++ only those files that have been modified vs. origin/master. -# 3. other optional filepath verifications may be commented out at the end of this file. -# From: https://github.com/cpplint/GitHub-Action-for-cpplint - -name: cpplint_modified_files -on: [push, pull_request] -jobs: - cpplint_modified_files: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v1 # v2 is broken for git diff - - uses: actions/setup-python@v1 - - run: python -m pip install cpplint - - run: git remote -v - - run: git branch - - run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - - run: git diff --diff-filter=dr --name-only origin/master > git_diff.txt - - name: cpplint_modified_files - shell: python - run: | - import os - import subprocess - import sys - - print("Python {}.{}.{}".format(*sys.version_info)) # Python 3.8 - with open("git_diff.txt") as in_file: - modified_files = sorted(in_file.read().splitlines()) - print("{} files were modified.".format(len(modified_files))) - - cpp_exts = tuple(".c .c++ .cc .cpp .cu .cuh .cxx .h .h++ .hh .hpp .hxx".split()) - cpp_files = [file for file in modified_files if file.lower().endswith(cpp_exts)] - print(f"{len(cpp_files)} C++ files were modified.") - if not cpp_files: - sys.exit(0) - - print("cpplint:") - for cpp_file in cpp_files: - subprocess.run(["cpplint", "--filter=-legal/copyright", cpp_file], check=True, text=True) - - print("g++:") - # compile_exts = tuple(".c .c++ .cc .cpp .cu .cxx".split()) - # compile_files = [file for file in cpp_files if file.lower().endswith(compile_exts)] - for cpp_file in cpp_files: - subprocess.run(["g++", cpp_file], check=True, text=True) - - upper_files = [file for file in cpp_files if file != file.lower()] - if upper_files: - print(f"{len(upper_files)} files contain uppercase characters:") - print("\n".join(upper_files) + "\n") - - space_files = [file for file in cpp_files if " " in file or "-" in file] - if space_files: - print(f"{len(space_files)} files contain space or dash characters:") - print("\n".join(space_files) + "\n") - - nodir_files = [file for file in cpp_files if file.count(os.sep) != 1] - if nodir_files: - print(f"{len(nodir_files)} files are not in one and only one directory:") - print("\n".join(nodir_files) + "\n") - - bad_files = len(upper_files + space_files + nodir_files) - if bad_files: - sys.exit(bad_files) diff --git a/.github/workflows/update_directory_md.yml b/.github/workflows/update_directory_md.yml deleted file mode 100644 index 1d63374b0a8..00000000000 --- a/.github/workflows/update_directory_md.yml +++ /dev/null @@ -1,68 +0,0 @@ -# This GitHub Action updates the DIRECTORY.md file (if needed) when doing a git push -name: update_directory_md -on: [push] -jobs: - update_directory_md: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - uses: actions/setup-python@v1 - - name: update_directory_md - shell: python - run: | - import os - from typing import Iterator - - URL_BASE = "https://github.com/TheAlgorithms/C-Plus-Plus/blob/master" - g_output = [] - - - def good_filepaths(top_dir: str = ".") -> Iterator[str]: - cpp_exts = tuple(".c .c++ .cc .cpp .cu .cuh .cxx .h .h++ .hh .hpp .hxx".split()) - for dirpath, dirnames, filenames in os.walk(top_dir): - dirnames[:] = [d for d in dirnames if d[0] not in "._"] - for filename in filenames: - if os.path.splitext(filename)[1].lower() in cpp_exts: - yield os.path.join(dirpath, filename).lstrip("./") - - - def md_prefix(i): - return f"{i * ' '}*" if i else "\n##" - - - def print_path(old_path: str, new_path: str) -> str: - global g_output - old_parts = old_path.split(os.sep) - for i, new_part in enumerate(new_path.split(os.sep)): - if i + 1 > len(old_parts) or old_parts[i] != new_part: - if new_part: - g_output.append(f"{md_prefix(i)} {new_part.replace('_', ' ').title()}") - return new_path - - - def build_directory_md(top_dir: str = ".") -> str: - global g_output - old_path = "" - for filepath in sorted(good_filepaths(), key=str.lower): - filepath, filename = os.path.split(filepath) - if filepath != old_path: - old_path = print_path(old_path, filepath) - indent = (filepath.count(os.sep) + 1) if filepath else 0 - url = "/".join((URL_BASE, filepath, filename)).replace(" ", "%20") - filename = os.path.splitext(filename.replace("_", " ").title())[0] - g_output.append(f"{md_prefix(indent)} [{filename}]({url})") - return "\n".join(g_output) - - - with open("DIRECTORY.md", "w") as out_file: - out_file.write(build_directory_md(".") + "\n") - - - name: Update DIRECTORY.md - run: | - cat DIRECTORY.md - git config --global user.name github-actions - git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' - git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - git add DIRECTORY.md - git commit -am "updating DIRECTORY.md" || true - git push --force origin HEAD:$GITHUB_REF || true From 3496cf3fa19276cd2ae89a92d11944660c717bda Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 21:25:19 -0400 Subject: [PATCH 273/433] fix yml indentation --- .github/workflows/clang-format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 092564fc408..57961b614b1 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -127,7 +127,7 @@ jobs: name: CPPLINT needs: code_format runs-on: ubuntu-latest - steps: + steps: - uses: actions/checkout@v1 - uses: actions/setup-python@v1 - run: pip install cpplint From bc615f5bb9e1ba987ff87982664b690fb11aae86 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 21:38:46 -0400 Subject: [PATCH 274/433] force push format changes, add title to DIRECTORY.md --- .github/workflows/clang-format.yml | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 57961b614b1..ecccb114998 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -55,7 +55,7 @@ jobs: line3: "AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: false," line4: "ColumnLimit: 80, AccessModifierOffset: -3 }" - name: Git Push - run: git pull && git push + run: git push --force origin HEAD:$GITHUB_REF || true update_directory_md: name: Update Directory.md @@ -64,7 +64,7 @@ jobs: steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v1 - - name: update_directory_md + - name: Update DIRECTORY.md shell: python run: | import os @@ -73,7 +73,6 @@ jobs: URL_BASE = "https://github.com/TheAlgorithms/C-Plus-Plus/blob/master" g_output = [] - def good_filepaths(top_dir: str = ".") -> Iterator[str]: cpp_exts = tuple(".c .c++ .cc .cpp .cu .cuh .cxx .h .h++ .hh .hpp .hxx".split()) for dirpath, dirnames, filenames in os.walk(top_dir): @@ -82,11 +81,9 @@ jobs: if os.path.splitext(filename)[1].lower() in cpp_exts: yield os.path.join(dirpath, filename).lstrip("./") - def md_prefix(i): return f"{i * ' '}*" if i else "\n##" - def print_path(old_path: str, new_path: str) -> str: global g_output old_parts = old_path.split(os.sep) @@ -96,7 +93,6 @@ jobs: g_output.append(f"{md_prefix(i)} {new_part.replace('_', ' ').title()}") return new_path - def build_directory_md(top_dir: str = ".") -> str: global g_output old_path = "" @@ -108,8 +104,7 @@ jobs: url = "/".join((URL_BASE, filepath, filename)).replace(" ", "%20") filename = os.path.splitext(filename.replace("_", " ").title())[0] g_output.append(f"{md_prefix(indent)} [{filename}]({url})") - return "\n".join(g_output) - + return "# List of all files\n" + "\n".join(g_output) with open("DIRECTORY.md", "w") as out_file: out_file.write(build_directory_md(".") + "\n") @@ -134,6 +129,7 @@ jobs: - run: cpplint --filter=-legal --recursive . build: + name: Compile checks runs-on: ${{ matrix.os }} needs: [cpplint, update_directory_md] strategy: From 40af5a53a934a63bc5360f7f853572f0db1047cb Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 21:42:32 -0400 Subject: [PATCH 275/433] pull before proceeding --- .github/workflows/clang-format.yml | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index ecccb114998..15a6ae64737 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -64,6 +64,8 @@ jobs: steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v1 + - name: pull latest commit + run: git pull - name: Update DIRECTORY.md shell: python run: | @@ -125,7 +127,9 @@ jobs: steps: - uses: actions/checkout@v1 - uses: actions/setup-python@v1 - - run: pip install cpplint + - run: | + pip install cpplint + git pull - run: cpplint --filter=-legal --recursive . build: @@ -139,6 +143,8 @@ jobs: - uses: actions/checkout@master with: submodules: true + - name: git pull + run: git pull - name: configure run: cmake -B ./build -S . - name: build From 388d06c8eecff6685b08bebbfc33020782495962 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 21:46:28 -0400 Subject: [PATCH 276/433] reorganize pull commands --- .github/workflows/clang-format.yml | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 15a6ae64737..0cfa72e59fa 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -127,9 +127,8 @@ jobs: steps: - uses: actions/checkout@v1 - uses: actions/setup-python@v1 - - run: | - pip install cpplint - git pull + - run: pip install cpplint + - run: git pull - run: cpplint --filter=-legal --recursive . build: @@ -143,9 +142,6 @@ jobs: - uses: actions/checkout@master with: submodules: true - - name: git pull - run: git pull - - name: configure - run: cmake -B ./build -S . - - name: build - run: cmake --build build + - run: git pull + - run: cmake -B ./build -S . + - run: cmake --build build From 03d7fa8b67435b5c98135f250804f057b31f7822 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 21:50:07 -0400 Subject: [PATCH 277/433] use master branches for actions --- .github/workflows/clang-format.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 0cfa72e59fa..df40c4e2843 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -1,4 +1,4 @@ -name: Long CI Workflow +name: Awesome CI Workflow on: [push] # push: @@ -125,8 +125,8 @@ jobs: needs: code_format runs-on: ubuntu-latest steps: - - uses: actions/checkout@v1 - - uses: actions/setup-python@v1 + - uses: actions/checkout@master + - uses: actions/setup-python@master - run: pip install cpplint - run: git pull - run: cpplint --filter=-legal --recursive . From b285d09d6a219f7ed22f57f403672e037f379eb8 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 22:20:34 -0400 Subject: [PATCH 278/433] rename .cc files to .cpp --- .github/workflows/clang-format.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index df40c4e2843..121309d1e2f 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -26,7 +26,7 @@ jobs: - name: Filename Formatter run: | IFS=$'\n' - for fname in `find . -type f -name '*.cpp' -o -name '*.h'` + for fname in `find . -type f -name '*.cpp' -o -name '*.cc' -o -name '*.h'` do echo "${fname}" new_fname=`echo ${fname} | tr ' ' '_'` @@ -35,6 +35,8 @@ jobs: echo " ${new_fname}" new_fname=`echo ${new_fname} | tr '-' '_'` echo " ${new_fname}" + new_fname=${new_fname/.cc/.cpp} + echo " ${new_fname}" if [ ${fname} != ${new_fname} ] then echo " ${fname} --> ${new_fname}" From 231d5c48586f41050407a4a0b58e0aff5393ad11 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 23:15:28 -0400 Subject: [PATCH 279/433] added class destructor to clean up dynamic memory allocation --- dynamic_programming/floyd_warshall.cpp | 47 ++++++++++++-------------- 1 file changed, 22 insertions(+), 25 deletions(-) diff --git a/dynamic_programming/floyd_warshall.cpp b/dynamic_programming/floyd_warshall.cpp index e3b0c66d3b6..d193ebbd589 100644 --- a/dynamic_programming/floyd_warshall.cpp +++ b/dynamic_programming/floyd_warshall.cpp @@ -1,44 +1,44 @@ -#include -#include +#include #include +#include -using namespace std; +using std::cin; +using std::cout; +using std::endl; // Wrapper class for storing a graph -class Graph -{ +class Graph { public: int vertexNum; int **edges; // Constructs a graph with V vertices and E edges - Graph(int V) - { + Graph(int V) { this->vertexNum = V; - this->edges = (int **)malloc(V * sizeof(int *)); - for (int i = 0; i < V; i++) - { - this->edges[i] = (int *)malloc(V * sizeof(int)); + this->edges = new int *[V]; + for (int i = 0; i < V; i++) { + this->edges[i] = new int[V]; for (int j = 0; j < V; j++) this->edges[i][j] = INT_MAX; this->edges[i][i] = 0; } } + ~Graph() { + for (int i = 0; i < vertexNum; i++) delete[] edges[i]; + delete[] edges; + } + // Adds the given edge to the graph - void addEdge(int src, int dst, int weight) - { + void addEdge(int src, int dst, int weight) { this->edges[src][dst] = weight; } }; // Utility function to print distances -void print(int dist[], int V) -{ +void print(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++) - { + for (int i = 0; i < V; i++) { + for (int j = 0; j < V; j++) { if (dist[i * V + j] != INT_MAX) cout << dist[i * V + j] << "\t"; else @@ -51,8 +51,7 @@ 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) -{ +void FloydWarshall(Graph graph) { int V = graph.vertexNum; int dist[V][V]; @@ -85,8 +84,7 @@ void FloydWarshall(Graph graph) } // Driver Function -int main() -{ +int main() { int V, E; int src, dst, weight; cout << "Enter number of vertices: "; @@ -94,8 +92,7 @@ int main() cout << "Enter number of edges: "; cin >> E; Graph G(V); - for (int i = 0; i < E; i++) - { + for (int i = 0; i < E; i++) { cout << "\nEdge " << i + 1 << "\nEnter source: "; cin >> src; cout << "Enter destination: "; From b8a97780a70f86cd1527ac503e5c14466d24dbe0 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 23:42:29 -0400 Subject: [PATCH 280/433] rename to awesome workflow --- .github/workflows/{clang-format.yml => awesome_forkflow.yml} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .github/workflows/{clang-format.yml => awesome_forkflow.yml} (100%) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/awesome_forkflow.yml similarity index 100% rename from .github/workflows/clang-format.yml rename to .github/workflows/awesome_forkflow.yml From cac95058297004870981c7e88948079f39e53696 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 23:48:29 -0400 Subject: [PATCH 281/433] commented whole repo cpplint - added modified files lint check --- .github/workflows/awesome_forkflow.yml | 77 +++++++++++++++++++++++--- 1 file changed, 69 insertions(+), 8 deletions(-) diff --git a/.github/workflows/awesome_forkflow.yml b/.github/workflows/awesome_forkflow.yml index 121309d1e2f..07bfb99dc2f 100644 --- a/.github/workflows/awesome_forkflow.yml +++ b/.github/workflows/awesome_forkflow.yml @@ -122,21 +122,82 @@ jobs: git commit -am "updating DIRECTORY.md" || true git push --force origin HEAD:$GITHUB_REF || true - cpplint: - name: CPPLINT - needs: code_format + # cpplint: + # name: CPPLINT + # needs: code_format + # runs-on: ubuntu-latest + # steps: + # - uses: actions/checkout@master + # - uses: actions/setup-python@master + # - run: pip install cpplint + # - run: git pull + # - run: cpplint --filter=-legal --recursive . + + cpplint_modified_files: runs-on: ubuntu-latest + needs: code_format + name: CPPLINT steps: - - uses: actions/checkout@master - - uses: actions/setup-python@master - - run: pip install cpplint + - uses: actions/checkout@v1 # v2 is broken for git diff + - uses: actions/setup-python@v1 + - run: python -m pip install cpplint + - run: git remote -v + - run: git branch + - run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - run: git pull - - run: cpplint --filter=-legal --recursive . + - run: git diff --diff-filter=dr --name-only origin/master > git_diff.txt + - name: cpplint_modified_files + shell: python + run: | + import os + import subprocess + import sys + + print("Python {}.{}.{}".format(*sys.version_info)) # Python 3.8 + with open("git_diff.txt") as in_file: + modified_files = sorted(in_file.read().splitlines()) + print("{} files were modified.".format(len(modified_files))) + + cpp_exts = tuple(".c .c++ .cc .cpp .cu .cuh .cxx .h .h++ .hh .hpp .hxx".split()) + cpp_files = [file for file in modified_files if file.lower().endswith(cpp_exts)] + print(f"{len(cpp_files)} C++ files were modified.") + if not cpp_files: + sys.exit(0) + + print("cpplint:") + for cpp_file in cpp_files: + subprocess.run(["cpplint", "--filter=-legal/copyright", cpp_file], check=True, text=True) + + print("g++:") + # compile_exts = tuple(".c .c++ .cc .cpp .cu .cxx".split()) + # compile_files = [file for file in cpp_files if file.lower().endswith(compile_exts)] + for cpp_file in cpp_files: + subprocess.run(["g++", cpp_file], check=True, text=True) + + upper_files = [file for file in cpp_files if file != file.lower()] + if upper_files: + print(f"{len(upper_files)} files contain uppercase characters:") + print("\n".join(upper_files) + "\n") + + space_files = [file for file in cpp_files if " " in file or "-" in file] + if space_files: + print(f"{len(space_files)} files contain space or dash characters:") + print("\n".join(space_files) + "\n") + + nodir_files = [file for file in cpp_files if file.count(os.sep) != 1] + if nodir_files: + print(f"{len(nodir_files)} files are not in one and only one directory:") + print("\n".join(nodir_files) + "\n") + + bad_files = len(upper_files + space_files + nodir_files) + if bad_files: + sys.exit(bad_files) + build: name: Compile checks runs-on: ${{ matrix.os }} - needs: [cpplint, update_directory_md] + needs: [cpplint, update_directory_md, cpplint_modified_files] strategy: matrix: os: [ubuntu-latest, windows-latest, macOS-latest] From 5a737a725df4e46210e0bf31ad3c7d21944ebee6 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 23:50:46 -0400 Subject: [PATCH 282/433] removed need for cpplint --- .github/workflows/awesome_forkflow.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/awesome_forkflow.yml b/.github/workflows/awesome_forkflow.yml index 07bfb99dc2f..acd53f13cc0 100644 --- a/.github/workflows/awesome_forkflow.yml +++ b/.github/workflows/awesome_forkflow.yml @@ -132,7 +132,7 @@ jobs: # - run: pip install cpplint # - run: git pull # - run: cpplint --filter=-legal --recursive . - + cpplint_modified_files: runs-on: ubuntu-latest needs: code_format @@ -197,7 +197,8 @@ jobs: build: name: Compile checks runs-on: ${{ matrix.os }} - needs: [cpplint, update_directory_md, cpplint_modified_files] + # needs: [cpplint, update_directory_md, cpplint_modified_files] + needs: [update_directory_md, cpplint_modified_files] strategy: matrix: os: [ubuntu-latest, windows-latest, macOS-latest] From 2bf0c00e90adac5f3b1e0fca9711a7f1b1cee73a Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 23:53:00 -0400 Subject: [PATCH 283/433] attempt to use actions/checkout@master --- .github/workflows/awesome_forkflow.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/awesome_forkflow.yml b/.github/workflows/awesome_forkflow.yml index acd53f13cc0..8d79e4b7189 100644 --- a/.github/workflows/awesome_forkflow.yml +++ b/.github/workflows/awesome_forkflow.yml @@ -138,8 +138,8 @@ jobs: needs: code_format name: CPPLINT steps: - - uses: actions/checkout@v1 # v2 is broken for git diff - - uses: actions/setup-python@v1 + - uses: actions/checkout@master # v2 is broken for git diff + - uses: actions/setup-python@master - run: python -m pip install cpplint - run: git remote -v - run: git branch From 153fb7b8a572aaf4561ac3d22d47e89480f11318 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 30 May 2020 00:01:27 -0400 Subject: [PATCH 284/433] temporary: no dependency on cpplint --- .github/workflows/awesome_forkflow.yml | 4 ++-- backtracking/knight_tour.cpp | 25 ++++++++++--------------- 2 files changed, 12 insertions(+), 17 deletions(-) diff --git a/.github/workflows/awesome_forkflow.yml b/.github/workflows/awesome_forkflow.yml index 8d79e4b7189..11e585deec0 100644 --- a/.github/workflows/awesome_forkflow.yml +++ b/.github/workflows/awesome_forkflow.yml @@ -146,6 +146,7 @@ jobs: - run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - run: git pull - run: git diff --diff-filter=dr --name-only origin/master > git_diff.txt + - run: echo "Files changed-- `cat diff.txt`" - name: cpplint_modified_files shell: python run: | @@ -193,12 +194,11 @@ jobs: if bad_files: sys.exit(bad_files) - build: name: Compile checks runs-on: ${{ matrix.os }} # needs: [cpplint, update_directory_md, cpplint_modified_files] - needs: [update_directory_md, cpplint_modified_files] + needs: [update_directory_md] strategy: matrix: os: [ubuntu-latest, windows-latest, macOS-latest] diff --git a/backtracking/knight_tour.cpp b/backtracking/knight_tour.cpp index 72b900376e0..c97523be77f 100644 --- a/backtracking/knight_tour.cpp +++ b/backtracking/knight_tour.cpp @@ -9,25 +9,23 @@ square (so that it could tour the board again immediately, following the same path), the tour is closed; otherwise, it is open. **/ -using namespace std; -bool issafe(int x, int y, int sol[n][n]) -{ +using std::cin; +using std::cout; + +bool issafe(int x, int y, int sol[n][n]) { return (x < n && x >= 0 && y < n && y >= 0 && sol[x][y] == -1); } -bool solve(int x, int y, int mov, int sol[n][n], int xmov[n], int ymov[n]) -{ +bool solve(int x, int y, int mov, int sol[n][n], int xmov[n], int ymov[n]) { int k, xnext, ynext; if (mov == n * n) return true; - for (k = 0; k < 8; k++) - { + for (k = 0; k < 8; k++) { xnext = x + xmov[k]; ynext = y + ymov[k]; - if (issafe(xnext, ynext, sol)) - { + if (issafe(xnext, ynext, sol)) { sol[xnext][ynext] = mov; if (solve(xnext, ynext, mov + 1, sol, xmov, ymov) == true) @@ -38,8 +36,7 @@ bool solve(int x, int y, int mov, int sol[n][n], int xmov[n], int ymov[n]) } return false; } -int main() -{ +int main() { // initialize(); int sol[n][n]; @@ -54,10 +51,8 @@ int main() bool flag = solve(0, 0, 1, sol, xmov, ymov); if (flag == false) cout << "solution doesnot exist \n"; - else - { - for (i = 0; i < n; i++) - { + else { + for (i = 0; i < n; i++) { for (j = 0; j < n; j++) cout << sol[i][j] << " "; cout << "\n"; } From 92fe9495ecefbdc8e3f70666a7a3c8a5c8cc40c1 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 30 May 2020 04:02:05 +0000 Subject: [PATCH 285/433] formatting filenames 153fb7b8a572aaf4561ac3d22d47e89480f11318 --- graph/{DFS_with_stack.cc => dfs_with_stack.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename graph/{DFS_with_stack.cc => dfs_with_stack.cpp} (100%) diff --git a/graph/DFS_with_stack.cc b/graph/dfs_with_stack.cpp similarity index 100% rename from graph/DFS_with_stack.cc rename to graph/dfs_with_stack.cpp From 8a2de9842baf9d6a4728de2267cb93bdcab81800 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 30 May 2020 04:02:09 +0000 Subject: [PATCH 286/433] formatting source-code for 153fb7b8a572aaf4561ac3d22d47e89480f11318 --- backtracking/graph_coloring.cpp | 21 ++-- backtracking/minimax.cpp | 6 +- backtracking/n_queens.cpp | 24 ++-- .../n_queens_all_solution_optimised.cpp | 58 +++------ backtracking/nqueen_print_all_solutions.cpp | 36 ++---- backtracking/rat_maze.cpp | 31 ++--- backtracking/sudoku_solve.cpp | 57 +++------ .../bisection_method.cpp | 29 ++--- .../false_position.cpp | 25 ++-- .../gaussian_elimination.cpp | 33 ++--- .../newton_raphson_method.cpp | 12 +- .../ordinary_least_squares_regressor.cpp | 112 ++++++----------- .../successive_approximation.cpp | 9 +- data_structure/avltree.cpp | 50 +++----- data_structure/binary_search_tree.cpp | 119 ++++++------------ data_structure/binaryheap.cpp | 42 +++---- .../circular_queue_using_linked_list.cpp | 34 ++--- data_structure/cll/cll.cpp | 67 ++++------ data_structure/cll/cll.h | 6 +- data_structure/cll/main_cll.cpp | 3 +- data_structure/disjoint_set.cpp | 44 +++---- data_structure/doubly_linked_list.cpp | 82 ++++-------- data_structure/linked_list.cpp | 72 ++++------- .../linkedlist_implentation_usingarray.cpp | 30 ++--- data_structure/list_array.cpp | 95 +++++--------- data_structure/morrisinorder.cpp | 44 +++---- data_structure/queue/queue.cpp | 42 ++----- data_structure/queue/queue.h | 6 +- data_structure/queue/test_queue.cpp | 3 +- data_structure/queue_using_array.cpp | 69 +++------- data_structure/queue_using_array2.cpp | 45 +++---- data_structure/queue_using_linked_list.cpp | 45 +++---- data_structure/queue_using_linkedlist.cpp | 39 ++---- data_structure/stack_using_array.cpp | 47 +++---- data_structure/stack_using_linked_list.cpp | 39 ++---- data_structure/stk/main.cpp | 16 +-- data_structure/stk/stack.cpp | 44 +++---- data_structure/stk/stack.h | 6 +- data_structure/stk/test_stack.cpp | 3 +- data_structure/tree.cpp | 53 +++----- data_structure/trie_tree.cpp | 44 +++---- dynamic_programming/0_1_knapsack.cpp | 18 +-- dynamic_programming/armstrong_number.cpp | 6 +- dynamic_programming/bellman_ford.cpp | 39 ++---- dynamic_programming/catalan_numbers.cpp | 12 +- dynamic_programming/coin_change.cpp | 12 +- dynamic_programming/cut_rod.cpp | 12 +- dynamic_programming/edit_distance.cpp | 15 +-- dynamic_programming/egg_dropping_puzzle.cpp | 21 ++-- dynamic_programming/fibonacci_bottom_up.cpp | 9 +- dynamic_programming/fibonacci_top_down.cpp | 12 +- dynamic_programming/kadane.cpp | 12 +- dynamic_programming/longest_common_string.cpp | 18 +-- .../longest_common_subsequence.cpp | 52 +++----- .../longest_increasing_subsequence.cpp | 21 ++-- ...longest_increasing_subsequence_(nlogn).cpp | 21 ++-- .../matrix_chain_multiplication.cpp | 12 +- .../searching_of_element_in_dynamic_array.cpp | 12 +- dynamic_programming/tree_height.cpp | 15 +-- graph/bfs.cpp | 33 ++--- .../bridge_finding_with_tarjan_algorithm.cpp | 30 ++--- graph/connected_components.cpp | 30 ++--- graph/connected_components_with_dsu.cpp | 24 ++-- graph/dfs.cpp | 15 +-- graph/dfs_with_stack.cpp | 20 ++- graph/dijkstra.cpp | 18 +-- graph/kosaraju.cpp | 42 +++---- graph/kruskal.cpp | 54 +++----- graph/lca.cpp | 66 ++++------ ...th_ford_fulkerson_and_edmond_karp_algo.cpp | 55 +++----- graph/prim.cpp | 15 +-- graph/topological_sort.cpp | 21 ++-- graph/topological_sort_by_kahns_algo.cpp | 36 ++---- greedy_algorithms/dijkstra.cpp | 61 +++------ greedy_algorithms/huffman.cpp | 18 +-- greedy_algorithms/knapsack.cpp | 34 ++--- .../kruskals_minimum_spanning_tree.cpp | 15 +-- .../prims_minimum_spanning_tree.cpp | 39 ++---- hashing/chaining.cpp | 50 +++----- hashing/double_hash_hash_table.cpp | 102 +++++---------- hashing/linear_probing_hash_table.cpp | 99 +++++---------- hashing/quadratic_probing_hash_table.cpp | 105 +++++----------- math/binary_exponent.cpp | 36 ++---- math/double_factorial.cpp | 12 +- math/eulers_totient_function.cpp | 22 ++-- math/extended_euclid_algorithm.cpp | 22 ++-- math/factorial.cpp | 6 +- math/fast_power.cpp | 15 +-- math/fibonacci.cpp | 6 +- math/fibonacci_fast.cpp | 9 +- math/fibonacci_large.cpp | 16 +-- math/gcd_iterative_euclidean.cpp | 29 ++--- math/gcd_of_n_numbers.cpp | 9 +- math/gcd_recursive_euclidean.cpp | 19 +-- math/large_factorial.cpp | 34 ++--- math/large_number.h | 94 +++++--------- .../modular_inverse_fermat_little_theorem.cpp | 35 ++---- math/number_of_positive_divisors.cpp | 31 ++--- math/power_for_huge_numbers.cpp | 21 ++-- math/prime_factorization.cpp | 30 ++--- math/prime_numbers.cpp | 12 +- math/primes_up_to_billion.cpp | 12 +- math/sieve_of_eratosthenes.cpp | 30 ++--- math/sqrt_double.cpp | 22 ++-- math/string_fibonacci.cpp | 34 ++--- .../array_left_rotation.cpp | 22 ++-- .../array_right_rotation.cpp | 19 +-- .../circular_linked_list.cpp | 49 +++----- .../circular_queue_using_array.cpp | 42 ++----- .../get_size_of_linked_list.cpp | 15 +-- .../intersection_of_2_arrays.cpp | 9 +- .../reverse_a_linked_list_using_recusion.cpp | 35 ++---- .../selectionsortlinkedlist.cpp | 46 +++---- .../union_of_2_arrays.cpp | 9 +- others/buzz_number.cpp | 6 +- others/decimal_to_binary.cpp | 15 +-- others/decimal_to_hexadecimal.cpp | 6 +- others/decimal_to_roman_numeral.cpp | 12 +- others/fast_interger_input.cpp | 9 +- others/happy_number.cpp | 14 +-- others/matrix_exponentiation.cpp | 49 +++----- others/palindrome_of_number.cpp | 3 +- others/paranthesis_matching.cpp | 30 ++--- others/pascal_triangle.cpp | 27 ++-- others/primality_test.cpp | 9 +- others/smallest_circle.cpp | 51 +++----- others/sparse_matrix.cpp | 15 +-- others/spiral_print.cpp | 36 ++---- others/stairs_pattern.cpp | 15 +-- others/tower_of_hanoi.cpp | 34 ++--- others/vector_important_functions.cpp | 3 +- probability/addition_rule.cpp | 9 +- probability/bayes_theorem.cpp | 9 +- probability/binomial_dist.cpp | 24 ++-- probability/poisson_dist.cpp | 24 ++-- range_queries/bit.cpp | 27 ++-- range_queries/fenwicktree.cpp | 28 ++--- range_queries/mo.cpp | 33 ++--- range_queries/segtree.cpp | 43 +++---- search/binary_search.cpp | 12 +- search/exponential_search.cpp | 18 +-- search/hash_search.cpp | 34 ++--- search/interpolation_search.cpp | 9 +- search/interpolation_search2.cpp | 9 +- search/jump_search.cpp | 12 +- search/linear_search.cpp | 22 ++-- search/median_search.cpp | 36 ++---- search/ternary_search.cpp | 35 ++---- search/text_search.cpp | 20 +-- sorting/bead_sort.cpp | 18 +-- sorting/bitonic_sort.cpp | 18 +-- sorting/bubble_sort.cpp | 25 ++-- sorting/bucket_sort.cpp | 9 +- sorting/cocktail_selection_sort.cpp | 61 +++------ sorting/comb_sort.cpp | 18 +-- sorting/counting_sort.cpp | 18 +-- sorting/counting_sort_string.cpp | 9 +- sorting/heap_sort.cpp | 27 ++-- sorting/insertion_sort.cpp | 15 +-- sorting/library_sort.cpp | 34 ++--- sorting/merge_sort.cpp | 34 ++--- sorting/non_recursive_merge_sort.cpp | 24 ++-- sorting/numeric_string_sort.cpp | 21 ++-- sorting/odd_even_sort.cpp | 21 ++-- sorting/quick_sort.cpp | 24 ++-- sorting/radix_sort.cpp | 39 ++---- sorting/selection_sort.cpp | 18 +-- sorting/shell_sort.cpp | 25 ++-- sorting/shell_sort2.cpp | 24 ++-- sorting/slow_sort.cpp | 15 +-- sorting/swap_sort.cpp | 18 +-- sorting/tim_sort.cpp | 43 +++---- strings/brute_force_string_searching.cpp | 18 +-- strings/knuth_morris_pratt.cpp | 35 ++---- strings/rabin_karp.cpp | 37 ++---- 175 files changed, 1671 insertions(+), 3460 deletions(-) diff --git a/backtracking/graph_coloring.cpp b/backtracking/graph_coloring.cpp index 5d0049902ca..19a983019e6 100644 --- a/backtracking/graph_coloring.cpp +++ b/backtracking/graph_coloring.cpp @@ -7,8 +7,7 @@ void printSolution(int color[]); /* A utility function to check if the current color assignment is safe for vertex v */ -bool isSafe(int v, bool graph[V][V], int color[], int c) -{ +bool isSafe(int v, bool graph[V][V], int color[], int c) { for (int i = 0; i < V; i++) if (graph[v][i] && c == color[i]) return false; @@ -16,22 +15,18 @@ bool isSafe(int v, bool graph[V][V], int color[], int c) } /* A recursive utility function to solve m coloring problem */ -void graphColoring(bool graph[V][V], int m, int color[], int v) -{ +void graphColoring(bool graph[V][V], int m, int color[], int v) { /* base case: If all vertices are assigned a color then return true */ - if (v == V) - { + if (v == V) { printSolution(color); return; } /* Consider this vertex v and try different colors */ - for (int c = 1; c <= m; c++) - { + for (int c = 1; c <= m; c++) { /* Check if assignment of color c to v is fine*/ - if (isSafe(v, graph, color, c)) - { + if (isSafe(v, graph, color, c)) { color[v] = c; /* recur to assign colors to rest of the vertices */ @@ -45,16 +40,14 @@ void graphColoring(bool graph[V][V], int m, int color[], int v) } /* A utility function to print solution */ -void printSolution(int color[]) -{ +void printSolution(int color[]) { printf(" Following are the assigned colors \n"); for (int i = 0; i < V; i++) printf(" %d ", color[i]); printf("\n"); } // driver program to test above function -int main() -{ +int main() { /* Create following graph and test whether it is 3 colorable (3)---(2) | / | diff --git a/backtracking/minimax.cpp b/backtracking/minimax.cpp index 110e9e7ed31..4e46a5fb232 100644 --- a/backtracking/minimax.cpp +++ b/backtracking/minimax.cpp @@ -9,8 +9,7 @@ using std::min; using std::vector; int minimax(int depth, int node_index, bool is_max, vector scores, - int height) -{ + int height) { if (depth == height) return scores[node_index]; @@ -20,8 +19,7 @@ int minimax(int depth, int node_index, bool is_max, vector scores, return is_max ? max(v1, v2) : min(v1, v2); } -int main() -{ +int main() { vector scores = {90, 23, 6, 33, 21, 65, 123, 34423}; int height = log2(scores.size()); diff --git a/backtracking/n_queens.cpp b/backtracking/n_queens.cpp index 45d6f436cb5..8aab5df7b9c 100644 --- a/backtracking/n_queens.cpp +++ b/backtracking/n_queens.cpp @@ -2,18 +2,15 @@ #define N 4 using namespace std; -void printSolution(int board[N][N]) -{ +void printSolution(int board[N][N]) { cout << "\n"; - for (int i = 0; i < N; i++) - { + for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) cout << "" << board[i][j]; cout << "\n"; } } -bool isSafe(int board[N][N], int row, int col) -{ +bool isSafe(int board[N][N], int row, int col) { int i, j; /* Check this row on left side */ @@ -34,22 +31,18 @@ bool isSafe(int board[N][N], int row, int col) return true; } -void solveNQ(int board[N][N], int col) -{ - if (col >= N) - { +void solveNQ(int board[N][N], int col) { + if (col >= N) { printSolution(board); return; } /* Consider this column and try placing this queen in all rows one by one */ - for (int i = 0; i < N; i++) - { + for (int i = 0; i < N; i++) { /* Check if queen can be placed on board[i][col] */ - if (isSafe(board, i, col)) - { + if (isSafe(board, i, col)) { /* Place this queen in board[i][col] */ // cout<<"\n"<= stop; var--) -void PrintSol(int Board[n][n]) -{ - inc_loop(i, 0, n - 1) - { +void PrintSol(int Board[n][n]) { + inc_loop(i, 0, n - 1) { inc_loop(j, 0, n - 1) std::cout << Board[i][j] << " "; std::cout << std::endl; } std::cout << std::endl; - if (n % 2 == 0 || (n % 2 == 1 && Board[n / 2 + 1][0] != 1)) - { - inc_loop(i, 0, n - 1) - { + if (n % 2 == 0 || (n % 2 == 1 && Board[n / 2 + 1][0] != 1)) { + inc_loop(i, 0, n - 1) { dec_loop(j, n - 1, 0) std::cout << Board[i][j] << " "; std::cout << std::endl; } @@ -21,40 +17,32 @@ void PrintSol(int Board[n][n]) } } -bool CanIMove(int Board[n][n], int row, int col) -{ +bool CanIMove(int Board[n][n], int row, int col) { /// check in the row - inc_loop(i, 0, col - 1) - { + inc_loop(i, 0, col - 1) { if (Board[row][i] == 1) return false; } /// check the first diagonal - for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) - { + for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) { if (Board[i][j] == 1) return false; } /// check the second diagonal - for (int i = row, j = col; i <= n - 1 && j >= 0; i++, j--) - { + for (int i = row, j = col; i <= n - 1 && j >= 0; i++, j--) { if (Board[i][j] == 1) return false; } return true; } -void NQueenSol(int Board[n][n], int col) -{ - if (col >= n) - { +void NQueenSol(int Board[n][n], int col) { + if (col >= n) { PrintSol(Board); return; } - inc_loop(i, 0, n - 1) - { - if (CanIMove(Board, i, col)) - { + inc_loop(i, 0, n - 1) { + if (CanIMove(Board, i, col)) { Board[i][col] = 1; NQueenSol(Board, col + 1); Board[i][col] = 0; @@ -62,27 +50,19 @@ void NQueenSol(int Board[n][n], int col) } } -int main() -{ +int main() { int Board[n][n] = {0}; - if (n % 2 == 0) - { - inc_loop(i, 0, n / 2 - 1) - { - if (CanIMove(Board, i, 0)) - { + if (n % 2 == 0) { + inc_loop(i, 0, n / 2 - 1) { + if (CanIMove(Board, i, 0)) { Board[i][0] = 1; NQueenSol(Board, 1); Board[i][0] = 0; } } - } - else - { - inc_loop(i, 0, n / 2) - { - if (CanIMove(Board, i, 0)) - { + } else { + inc_loop(i, 0, n / 2) { + if (CanIMove(Board, i, 0)) { Board[i][0] = 1; NQueenSol(Board, 1); Board[i][0] = 0; diff --git a/backtracking/nqueen_print_all_solutions.cpp b/backtracking/nqueen_print_all_solutions.cpp index d3d50998dfe..e6736da1e74 100644 --- a/backtracking/nqueen_print_all_solutions.cpp +++ b/backtracking/nqueen_print_all_solutions.cpp @@ -1,12 +1,9 @@ #include #define n 4 -void PrintSol(int Board[n][n]) -{ - for (int i = 0; i < n; i++) - { - for (int j = 0; j < n; j++) - { +void PrintSol(int Board[n][n]) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { std::cout << Board[i][j] << " "; } std::cout << std::endl; @@ -14,40 +11,32 @@ void PrintSol(int Board[n][n]) std::cout << std::endl; } -bool CanIMove(int Board[n][n], int row, int col) -{ +bool CanIMove(int Board[n][n], int row, int col) { /// check in the row - for (int i = 0; i < col; i++) - { + for (int i = 0; i < col; i++) { if (Board[row][i] == 1) return false; } /// check the first diagonal - for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) - { + for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) { if (Board[i][j] == 1) return false; } /// check the second diagonal - for (int i = row, j = col; i <= n - 1 && j >= 0; i++, j--) - { + for (int i = row, j = col; i <= n - 1 && j >= 0; i++, j--) { if (Board[i][j] == 1) return false; } return true; } -void NQueenSol(int Board[n][n], int col) -{ - if (col >= n) - { +void NQueenSol(int Board[n][n], int col) { + if (col >= n) { PrintSol(Board); return; } - for (int i = 0; i < n; i++) - { - if (CanIMove(Board, i, col)) - { + for (int i = 0; i < n; i++) { + if (CanIMove(Board, i, col)) { Board[i][col] = 1; NQueenSol(Board, col + 1); Board[i][col] = 0; @@ -55,8 +44,7 @@ void NQueenSol(int Board[n][n], int col) } } -int main() -{ +int main() { int Board[n][n] = {0}; NQueenSol(Board, 0); } diff --git a/backtracking/rat_maze.cpp b/backtracking/rat_maze.cpp index 5454a6c82d3..fb3be4451d3 100644 --- a/backtracking/rat_maze.cpp +++ b/backtracking/rat_maze.cpp @@ -12,36 +12,28 @@ using namespace std; int solveMaze(int currposrow, int currposcol, int maze[size][size], - int soln[size][size]) -{ - if ((currposrow == size - 1) && (currposcol == size - 1)) - { + int soln[size][size]) { + if ((currposrow == size - 1) && (currposcol == size - 1)) { soln[currposrow][currposcol] = 1; - for (int i = 0; i < size; ++i) - { - for (int j = 0; j < size; ++j) - { + for (int i = 0; i < size; ++i) { + for (int j = 0; j < size; ++j) { cout << soln[i][j]; } cout << endl; } return 1; - } - else - { + } else { soln[currposrow][currposcol] = 1; // if there exist a solution by moving one step ahead in a collumn if ((currposcol < size - 1) && maze[currposrow][currposcol + 1] == 1 && - solveMaze(currposrow, currposcol + 1, maze, soln)) - { + solveMaze(currposrow, currposcol + 1, maze, soln)) { return 1; } // if there exists a solution by moving one step ahead in a row if ((currposrow < size - 1) && maze[currposrow + 1][currposcol] == 1 && - solveMaze(currposrow + 1, currposcol, maze, soln)) - { + solveMaze(currposrow + 1, currposcol, maze, soln)) { return 1; } @@ -51,17 +43,14 @@ int solveMaze(int currposrow, int currposcol, int maze[size][size], } } -int main(int argc, char const *argv[]) -{ +int main(int argc, char const *argv[]) { int maze[size][size] = { {1, 0, 1, 0}, {1, 0, 1, 1}, {1, 0, 0, 1}, {1, 1, 1, 1}}; int soln[size][size]; - for (int i = 0; i < size; ++i) - { - for (int j = 0; j < size; ++j) - { + for (int i = 0; i < size; ++i) { + for (int j = 0; j < size; ++j) { soln[i][j] = 0; } } diff --git a/backtracking/sudoku_solve.cpp b/backtracking/sudoku_solve.cpp index c980408411e..b712b6ec7a4 100644 --- a/backtracking/sudoku_solve.cpp +++ b/backtracking/sudoku_solve.cpp @@ -3,13 +3,10 @@ using namespace std; /// N=9; int n = 9; -bool isPossible(int mat[][9], int i, int j, int no) -{ +bool isPossible(int mat[][9], int i, int j, int no) { /// Row or col nahin hona chahiye - for (int x = 0; x < n; x++) - { - if (mat[x][j] == no || mat[i][x] == no) - { + for (int x = 0; x < n; x++) { + if (mat[x][j] == no || mat[i][x] == no) { return false; } } @@ -18,12 +15,9 @@ bool isPossible(int mat[][9], int i, int j, int no) int sx = (i / 3) * 3; int sy = (j / 3) * 3; - for (int x = sx; x < sx + 3; x++) - { - for (int y = sy; y < sy + 3; y++) - { - if (mat[x][y] == no) - { + for (int x = sx; x < sx + 3; x++) { + for (int y = sy; y < sy + 3; y++) { + if (mat[x][y] == no) { return false; } } @@ -31,58 +25,46 @@ bool isPossible(int mat[][9], int i, int j, int no) return true; } -void printMat(int mat[][9]) -{ - for (int i = 0; i < n; i++) - { - for (int j = 0; j < n; j++) - { +void printMat(int mat[][9]) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { cout << mat[i][j] << " "; - if ((j + 1) % 3 == 0) - { + if ((j + 1) % 3 == 0) { cout << '\t'; } } - if ((i + 1) % 3 == 0) - { + if ((i + 1) % 3 == 0) { cout << endl; } cout << endl; } } -bool solveSudoku(int mat[][9], int i, int j) -{ +bool solveSudoku(int mat[][9], int i, int j) { /// Base Case - if (i == 9) - { + if (i == 9) { /// Solve kr chuke hain for 9 rows already printMat(mat); return true; } /// Crossed the last Cell in the row - if (j == 9) - { + if (j == 9) { return solveSudoku(mat, i + 1, 0); } /// Blue Cell - Skip - if (mat[i][j] != 0) - { + if (mat[i][j] != 0) { return solveSudoku(mat, i, j + 1); } /// White Cell /// Try to place every possible no - for (int no = 1; no <= 9; no++) - { - if (isPossible(mat, i, j, no)) - { + for (int no = 1; no <= 9; no++) { + if (isPossible(mat, i, j, no)) { /// Place the no - assuming solution aa jayega mat[i][j] = no; bool aageKiSolveHui = solveSudoku(mat, i, j + 1); - if (aageKiSolveHui) - { + if (aageKiSolveHui) { return true; } /// Nahin solve hui @@ -94,8 +76,7 @@ bool solveSudoku(int mat[][9], int i, int j) return false; } -int main() -{ +int main() { int mat[9][9] = {{5, 3, 0, 0, 7, 0, 0, 0, 0}, {6, 0, 0, 1, 9, 5, 0, 0, 0}, {0, 9, 8, 0, 0, 0, 0, 6, 0}, {8, 0, 0, 0, 6, 0, 0, 0, 3}, {4, 0, 0, 8, 0, 3, 0, 0, 1}, {7, 0, 0, 0, 2, 0, 0, 0, 6}, diff --git a/computer_oriented_statistical_methods/bisection_method.cpp b/computer_oriented_statistical_methods/bisection_method.cpp index ea0a5e931c5..c93c529d248 100644 --- a/computer_oriented_statistical_methods/bisection_method.cpp +++ b/computer_oriented_statistical_methods/bisection_method.cpp @@ -23,36 +23,29 @@ /** define \f$f(x)\f$ to find root for */ -static double eq(double i) -{ +static double eq(double i) { return (std::pow(i, 3) - (4 * i) - 9); // original equation } /** get the sign of any given number */ template -int sgn(T val) -{ +int sgn(T val) { return (T(0) < val) - (val < T(0)); } /** main function */ -int main() -{ +int main() { double a = -1, b = 1, x, z; int i; // loop to find initial intervals a, b - for (int i = 0; i < MAX_ITERATIONS; i++) - { + for (int i = 0; i < MAX_ITERATIONS; i++) { z = eq(a); x = eq(b); - if (sgn(z) == sgn(x)) - { // same signs, increase interval + if (sgn(z) == sgn(x)) { // same signs, increase interval b++; a--; - } - else - { // if opposite signs, we got our interval + } else { // if opposite signs, we got our interval break; } } @@ -61,19 +54,15 @@ int main() std::cout << "\nSecond initial: " << b; // start iterations - for (i = 0; i < MAX_ITERATIONS; i++) - { + for (i = 0; i < MAX_ITERATIONS; i++) { x = (a + b) / 2; z = eq(x); std::cout << "\n\nz: " << z << "\t[" << a << " , " << b << " | Bisect: " << x << "]"; - if (z < 0) - { + if (z < 0) { a = x; - } - else - { + } else { b = x; } diff --git a/computer_oriented_statistical_methods/false_position.cpp b/computer_oriented_statistical_methods/false_position.cpp index 6bdc0cf6798..aebd154bb07 100644 --- a/computer_oriented_statistical_methods/false_position.cpp +++ b/computer_oriented_statistical_methods/false_position.cpp @@ -25,36 +25,29 @@ /** define \f$f(x)\f$ to find root for */ -static double eq(double i) -{ +static double eq(double i) { return (std::pow(i, 3) - (4 * i) - 9); // origial equation } /** get the sign of any given number */ template -int sgn(T val) -{ +int sgn(T val) { return (T(0) < val) - (val < T(0)); } /** main function */ -int main() -{ +int main() { double a = -1, b = 1, x, z, m, n, c; int i; // loop to find initial intervals a, b - for (int i = 0; i < MAX_ITERATIONS; i++) - { + for (int i = 0; i < MAX_ITERATIONS; i++) { z = eq(a); x = eq(b); - if (sgn(z) == sgn(x)) - { // same signs, increase interval + if (sgn(z) == sgn(x)) { // same signs, increase interval b++; a--; - } - else - { // if opposite signs, we got our interval + } else { // if opposite signs, we got our interval break; } } @@ -62,8 +55,7 @@ int main() std::cout << "\nFirst initial: " << a; std::cout << "\nSecond initial: " << b; - for (i = 0; i < MAX_ITERATIONS; i++) - { + for (i = 0; i < MAX_ITERATIONS; i++) { m = eq(a); n = eq(b); @@ -72,8 +64,7 @@ int main() a = c; z = eq(c); - if (std::abs(z) < EPSILON) - { // stoping criteria + if (std::abs(z) < EPSILON) { // stoping criteria break; } } diff --git a/computer_oriented_statistical_methods/gaussian_elimination.cpp b/computer_oriented_statistical_methods/gaussian_elimination.cpp index 01cb578b2ca..60b5648ec84 100644 --- a/computer_oriented_statistical_methods/gaussian_elimination.cpp +++ b/computer_oriented_statistical_methods/gaussian_elimination.cpp @@ -6,8 +6,7 @@ #include /** Main function */ -int main() -{ +int main() { int mat_size, i, j, step; std::cout << "Matrix size: "; @@ -15,8 +14,7 @@ int main() // create a 2D matrix by dynamic memory allocation double **mat = new double *[mat_size + 1], **x = new double *[mat_size]; - for (i = 0; i <= mat_size; i++) - { + for (i = 0; i <= mat_size; i++) { mat[i] = new double[mat_size + 1]; if (i < mat_size) x[i] = new double[mat_size + 1]; @@ -24,20 +22,16 @@ int main() // get the matrix elements from user std::cout << std::endl << "Enter value of the matrix: " << std::endl; - for (i = 0; i < mat_size; i++) - { - for (j = 0; j <= mat_size; j++) - { + for (i = 0; i < mat_size; i++) { + for (j = 0; j <= mat_size; j++) { std::cin >> mat[i][j]; // Enter (mat_size*mat_size) value of the matrix. } } // perform Gaussian elimination - for (step = 0; step < mat_size - 1; step++) - { - for (i = step; i < mat_size - 1; i++) - { + for (step = 0; step < mat_size - 1; step++) { + for (i = step; i < mat_size - 1; i++) { double a = (mat[i + 1][step] / mat[step][step]); for (j = step; j <= mat_size; j++) @@ -47,10 +41,8 @@ int main() std::cout << std::endl << "Matrix using Gaussian Elimination method: " << std::endl; - for (i = 0; i < mat_size; i++) - { - for (j = 0; j <= mat_size; j++) - { + for (i = 0; i < mat_size; i++) { + for (j = 0; j <= mat_size; j++) { x[i][j] = mat[i][j]; std::cout << mat[i][j] << " "; } @@ -58,11 +50,9 @@ int main() } std::cout << std::endl << "Value of the Gaussian Elimination method: " << std::endl; - for (i = mat_size - 1; i >= 0; i--) - { + for (i = mat_size - 1; i >= 0; i--) { double sum = 0; - for (j = mat_size - 1; j > i; j--) - { + for (j = mat_size - 1; j > i; j--) { x[i][j] = x[j][j] * x[i][j]; sum = x[i][j] + sum; } @@ -74,8 +64,7 @@ int main() std::cout << "x" << i << "= " << x[i][i] << std::endl; } - for (i = 0; i <= mat_size; i++) - { + for (i = 0; i <= mat_size; i++) { delete[] mat[i]; if (i < mat_size) delete[] x[i]; diff --git a/computer_oriented_statistical_methods/newton_raphson_method.cpp b/computer_oriented_statistical_methods/newton_raphson_method.cpp index a93774b9167..318363a3922 100644 --- a/computer_oriented_statistical_methods/newton_raphson_method.cpp +++ b/computer_oriented_statistical_methods/newton_raphson_method.cpp @@ -21,21 +21,18 @@ /** define \f$f(x)\f$ to find root for */ -static double eq(double i) -{ +static double eq(double i) { return (std::pow(i, 3) - (4 * i) - 9); // original equation } /** define the derivative function \f$f'(x)\f$ */ -static double eq_der(double i) -{ +static double eq_der(double i) { return ((3 * std::pow(i, 2)) - 4); // derivative of equation } /** Main function */ -int main() -{ +int main() { std::srand(std::time(nullptr)); // initialize randomizer double z, c = std::rand() % 100, m, n; @@ -44,8 +41,7 @@ int main() std::cout << "\nInitial approximation: " << c; // start iterations - for (i = 0; i < MAX_ITERATIONS; i++) - { + for (i = 0; i < MAX_ITERATIONS; i++) { m = eq(c); n = eq_der(c); diff --git a/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp b/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp index c3fe8be0399..de02b27bba7 100644 --- a/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp +++ b/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp @@ -16,13 +16,11 @@ */ template std::ostream &operator<<(std::ostream &out, - std::vector> const &v) -{ + std::vector> const &v) { const int width = 10; const char separator = ' '; - for (size_t row = 0; row < v.size(); row++) - { + for (size_t row = 0; row < v.size(); row++) { for (size_t col = 0; col < v[row].size(); col++) out << std::left << std::setw(width) << std::setfill(separator) << v[row][col]; @@ -36,8 +34,7 @@ std::ostream &operator<<(std::ostream &out, * operator to print a vector */ template -std::ostream &operator<<(std::ostream &out, std::vector const &v) -{ +std::ostream &operator<<(std::ostream &out, std::vector const &v) { const int width = 15; const char separator = ' '; @@ -53,8 +50,7 @@ std::ostream &operator<<(std::ostream &out, std::vector const &v) * \returns 1 if true, 0 if false */ template -inline bool is_square(std::vector> const &A) -{ +inline bool is_square(std::vector> const &A) { // Assuming A is square matrix size_t N = A.size(); for (size_t i = 0; i < N; i++) @@ -72,8 +68,7 @@ inline bool is_square(std::vector> const &A) **/ template std::vector> operator*(std::vector> const &A, - std::vector> const &B) -{ + std::vector> const &B) { // Number of rows in A size_t N_A = A.size(); // Number of columns in B @@ -81,18 +76,15 @@ std::vector> operator*(std::vector> const &A, std::vector> result(N_A); - if (A[0].size() != B.size()) - { + if (A[0].size() != B.size()) { std::cerr << "Number of columns in A != Number of rows in B (" << A[0].size() << ", " << B.size() << ")" << std::endl; return result; } - for (size_t row = 0; row < N_A; row++) - { + for (size_t row = 0; row < N_A; row++) { std::vector v(N_B); - for (size_t col = 0; col < N_B; col++) - { + for (size_t col = 0; col < N_B; col++) { v[col] = static_cast(0); for (size_t j = 0; j < B.size(); j++) v[col] += A[row][j] * B[j][col]; @@ -109,22 +101,19 @@ std::vector> operator*(std::vector> const &A, */ template std::vector operator*(std::vector> const &A, - std::vector const &B) -{ + std::vector const &B) { // Number of rows in A size_t N_A = A.size(); std::vector result(N_A); - if (A[0].size() != B.size()) - { + if (A[0].size() != B.size()) { std::cerr << "Number of columns in A != Number of rows in B (" << A[0].size() << ", " << B.size() << ")" << std::endl; return result; } - for (size_t row = 0; row < N_A; row++) - { + for (size_t row = 0; row < N_A; row++) { result[row] = static_cast(0); for (size_t j = 0; j < B.size(); j++) result[row] += A[row][j] * B[j]; } @@ -137,15 +126,13 @@ std::vector operator*(std::vector> const &A, * \returns resultant vector */ template -std::vector operator*(float const scalar, std::vector const &A) -{ +std::vector operator*(float const scalar, std::vector const &A) { // Number of rows in A size_t N_A = A.size(); std::vector result(N_A); - for (size_t row = 0; row < N_A; row++) - { + for (size_t row = 0; row < N_A; row++) { result[row] += A[row] * static_cast(scalar); } @@ -157,8 +144,7 @@ std::vector operator*(float const scalar, std::vector const &A) * \returns resultant vector */ template -std::vector operator*(std::vector const &A, float const scalar) -{ +std::vector operator*(std::vector const &A, float const scalar) { // Number of rows in A size_t N_A = A.size(); @@ -175,8 +161,7 @@ std::vector operator*(std::vector const &A, float const scalar) * \returns resultant vector */ template -std::vector operator/(std::vector const &A, float const scalar) -{ +std::vector operator/(std::vector const &A, float const scalar) { return (1.f / scalar) * A; } @@ -185,15 +170,13 @@ std::vector operator/(std::vector const &A, float const scalar) * \returns resultant vector */ template -std::vector operator-(std::vector const &A, std::vector const &B) -{ +std::vector operator-(std::vector const &A, std::vector const &B) { // Number of rows in A size_t N = A.size(); std::vector result(N); - if (B.size() != N) - { + if (B.size() != N) { std::cerr << "Vector dimensions shouldbe identical!" << std::endl; return A; } @@ -208,15 +191,13 @@ std::vector operator-(std::vector const &A, std::vector const &B) * \returns resultant vector */ template -std::vector operator+(std::vector const &A, std::vector const &B) -{ +std::vector operator+(std::vector const &A, std::vector const &B) { // Number of rows in A size_t N = A.size(); std::vector result(N); - if (B.size() != N) - { + if (B.size() != N) { std::cerr << "Vector dimensions shouldbe identical!" << std::endl; return A; } @@ -233,30 +214,26 @@ std::vector operator+(std::vector const &A, std::vector const &B) **/ template std::vector> get_inverse( - std::vector> const &A) -{ + std::vector> const &A) { // Assuming A is square matrix size_t N = A.size(); std::vector> inverse(N); - for (size_t row = 0; row < N; row++) - { + for (size_t row = 0; row < N; row++) { // preallocatae a resultant identity matrix inverse[row] = std::vector(N); for (size_t col = 0; col < N; col++) inverse[row][col] = (row == col) ? 1.f : 0.f; } - if (!is_square(A)) - { + if (!is_square(A)) { std::cerr << "A must be a square matrix!" << std::endl; return inverse; } // preallocatae a temporary matrix identical to A std::vector> temp(N); - for (size_t row = 0; row < N; row++) - { + for (size_t row = 0; row < N; row++) { std::vector v(N); for (size_t col = 0; col < N; col++) v[col] = static_cast(A[row][col]); @@ -264,27 +241,22 @@ std::vector> get_inverse( } // start transformations - for (size_t row = 0; row < N; row++) - { - for (size_t row2 = row; row2 < N && temp[row][row] == 0; row2++) - { + for (size_t row = 0; row < N; row++) { + for (size_t row2 = row; row2 < N && temp[row][row] == 0; row2++) { // this to ensure diagonal elements are not 0 temp[row] = temp[row] + temp[row2]; inverse[row] = inverse[row] + inverse[row2]; } - for (size_t col2 = row; col2 < N && temp[row][row] == 0; col2++) - { + for (size_t col2 = row; col2 < N && temp[row][row] == 0; col2++) { // this to further ensure diagonal elements are not 0 - for (size_t row2 = 0; row2 < N; row2++) - { + for (size_t row2 = 0; row2 < N; row2++) { temp[row2][row] = temp[row2][row] + temp[row2][col2]; inverse[row2][row] = inverse[row2][row] + inverse[row2][col2]; } } - if (temp[row][row] == 0) - { + if (temp[row][row] == 0) { // Probably a low-rank matrix and hence singular std::cerr << "Low-rank matrix, no inverse!" << std::endl; return inverse; @@ -295,8 +267,7 @@ std::vector> get_inverse( temp[row] = temp[row] / divisor; inverse[row] = inverse[row] / divisor; // Row transformations - for (size_t row2 = 0; row2 < N; row2++) - { + for (size_t row2 = 0; row2 < N; row2++) { if (row2 == row) continue; float factor = temp[row2][row]; @@ -313,12 +284,11 @@ std::vector> get_inverse( * \returns resultant matrix **/ template -std::vector> get_transpose(std::vector> const &A) -{ +std::vector> get_transpose( + std::vector> const &A) { std::vector> result(A[0].size()); - for (size_t row = 0; row < A[0].size(); row++) - { + for (size_t row = 0; row < A[0].size(); row++) { std::vector v(A.size()); for (size_t col = 0; col < A.size(); col++) v[col] = A[col][row]; @@ -336,8 +306,7 @@ std::vector> get_transpose(std::vector> const &A) */ template std::vector fit_OLS_regressor(std::vector> const &X, - std::vector const &Y) -{ + std::vector const &Y) { // NxF std::vector> X2 = X; for (size_t i = 0; i < X2.size(); i++) @@ -368,12 +337,10 @@ std::vector fit_OLS_regressor(std::vector> const &X, template std::vector predict_OLS_regressor(std::vector> const &X, std::vector const &beta /**< */ -) -{ +) { std::vector result(X.size()); - for (size_t rows = 0; rows < X.size(); rows++) - { + for (size_t rows = 0; rows < X.size(); rows++) { // -> start with constant term result[rows] = beta[X[0].size()]; for (size_t cols = 0; cols < X[0].size(); cols++) @@ -386,8 +353,7 @@ std::vector predict_OLS_regressor(std::vector> const &X, /** * main function */ -int main() -{ +int main() { size_t N, F; std::cout << "Enter number of features: "; @@ -404,8 +370,7 @@ int main() << "Enter training data. Per sample, provide features ad one output." << std::endl; - for (size_t rows = 0; rows < N; rows++) - { + for (size_t rows = 0; rows < N; rows++) { std::vector v(F); std::cout << "Sample# " << rows + 1 << ": "; for (size_t cols = 0; cols < F; cols++) @@ -426,8 +391,7 @@ int main() std::vector> data2(T); // vector Y2(T); - for (size_t rows = 0; rows < T; rows++) - { + for (size_t rows = 0; rows < T; rows++) { std::cout << "Sample# " << rows + 1 << ": "; std::vector v(F); for (size_t cols = 0; cols < F; cols++) std::cin >> v[cols]; diff --git a/computer_oriented_statistical_methods/successive_approximation.cpp b/computer_oriented_statistical_methods/successive_approximation.cpp index 137933591f9..351382f2418 100644 --- a/computer_oriented_statistical_methods/successive_approximation.cpp +++ b/computer_oriented_statistical_methods/successive_approximation.cpp @@ -17,13 +17,11 @@ static float eq(float y) { return (3 * y) - cos(y) - 2; } static float eqd(float y) { return 0.5 * (cos(y) + 2); } /** Main function */ -int main() -{ +int main() { float y, x1, x2, x3, sum, s, a, f1, f2, gd; int i, n; - for (i = 0; i < 10; i++) - { + for (i = 0; i < 10; i++) { sum = eq(y); std::cout << "value of equation at " << i << " " << sum << "\n"; y++; @@ -33,8 +31,7 @@ int main() std::cout << "enter the no iteration to perform->\n"; std::cin >> n; - for (i = 0; i <= n; i++) - { + for (i = 0; i <= n; i++) { x2 = eqd(x1); std::cout << "\nenter the x2->" << x2; x1 = x2; diff --git a/data_structure/avltree.cpp b/data_structure/avltree.cpp index dc96ad97760..f38133c050b 100644 --- a/data_structure/avltree.cpp +++ b/data_structure/avltree.cpp @@ -3,8 +3,7 @@ using namespace std; -typedef struct node -{ +typedef struct node { int data; int height; struct node *left; @@ -15,8 +14,7 @@ int max(int a, int b) { return a > b ? a : b; } // Returns a new Node -node *createNode(int data) -{ +node *createNode(int data) { node *nn = new node(); nn->data = data; nn->height = 0; @@ -27,8 +25,7 @@ node *createNode(int data) // Returns height of tree -int height(node *root) -{ +int height(node *root) { if (root == NULL) return 0; return 1 + max(height(root->left), height(root->right)); @@ -40,8 +37,7 @@ int getBalance(node *root) { return height(root->left) - height(root->right); } // Returns Node after Right Rotation -node *rightRotate(node *root) -{ +node *rightRotate(node *root) { node *t = root->left; node *u = t->right; t->right = root; @@ -51,8 +47,7 @@ node *rightRotate(node *root) // Returns Node after Left Rotation -node *leftRotate(node *root) -{ +node *leftRotate(node *root) { node *t = root->right; node *u = t->left; t->left = root; @@ -62,8 +57,7 @@ node *leftRotate(node *root) // Returns node with minimum value in the tree -node *minValue(node *root) -{ +node *minValue(node *root) { if (root->left == NULL) return root; return minValue(root->left); @@ -71,8 +65,7 @@ node *minValue(node *root) // Balanced Insertion -node *insert(node *root, int item) -{ +node *insert(node *root, int item) { node *nn = createNode(item); if (root == NULL) return nn; @@ -81,14 +74,11 @@ node *insert(node *root, int item) else root->right = insert(root->right, item); int b = getBalance(root); - if (b > 1) - { + if (b > 1) { if (getBalance(root->left) < 0) root->left = leftRotate(root->left); // Left-Right Case return rightRotate(root); // Left-Left Case - } - else if (b < -1) - { + } else if (b < -1) { if (getBalance(root->right) > 0) root->right = rightRotate(root->right); // Right-Left Case return leftRotate(root); // Right-Right Case @@ -98,8 +88,7 @@ node *insert(node *root, int item) // Balanced Deletion -node *deleteNode(node *root, int key) -{ +node *deleteNode(node *root, int key) { if (root == NULL) return root; if (key < root->data) @@ -107,18 +96,14 @@ node *deleteNode(node *root, int key) else if (key > root->data) root->right = deleteNode(root->right, key); - else - { + else { // Node to be deleted is leaf node or have only one Child - if (!root->right) - { + if (!root->right) { node *temp = root->left; delete (root); root = NULL; return temp; - } - else if (!root->left) - { + } else if (!root->left) { node *temp = root->right; delete (root); root = NULL; @@ -135,12 +120,10 @@ node *deleteNode(node *root, int key) // LevelOrder (Breadth First Search) -void levelOrder(node *root) -{ +void levelOrder(node *root) { queue q; q.push(root); - while (!q.empty()) - { + while (!q.empty()) { root = q.front(); cout << root->data << " "; q.pop(); @@ -151,8 +134,7 @@ void levelOrder(node *root) } } -int main() -{ +int main() { // Testing AVL Tree node *root = NULL; int i; diff --git a/data_structure/binary_search_tree.cpp b/data_structure/binary_search_tree.cpp index ea9df12d377..c3a74f385e1 100644 --- a/data_structure/binary_search_tree.cpp +++ b/data_structure/binary_search_tree.cpp @@ -1,15 +1,13 @@ #include using namespace std; -struct node -{ +struct node { int val; node *left; node *right; }; -struct queue -{ +struct queue { node *t[100]; int front; int rear; @@ -21,107 +19,71 @@ void enqueue(node *n) { q.t[q.rear++] = n; } node *dequeue() { return (q.t[q.front++]); } -void Insert(node *n, int x) -{ - if (x < n->val) - { - if (n->left == NULL) - { +void Insert(node *n, int x) { + if (x < n->val) { + if (n->left == NULL) { node *temp = new node; temp->val = x; temp->left = NULL; temp->right = NULL; n->left = temp; - } - else - { + } else { Insert(n->left, x); } - } - else - { - if (n->right == NULL) - { + } else { + if (n->right == NULL) { node *temp = new node; temp->val = x; temp->left = NULL; temp->right = NULL; n->left = temp; - } - else - { + } else { Insert(n->right, x); } } } -int findMaxInLeftST(node *n) -{ - while (n->right != NULL) - { +int findMaxInLeftST(node *n) { + while (n->right != NULL) { n = n->right; } return n->val; } -void Remove(node *p, node *n, int x) -{ - if (n->val == x) - { - if (n->right == NULL && n->left == NULL) - { - if (x < p->val) - { +void Remove(node *p, node *n, int x) { + if (n->val == x) { + if (n->right == NULL && n->left == NULL) { + if (x < p->val) { p->right = NULL; - } - else - { + } else { p->left = NULL; } - } - else if (n->right == NULL) - { - if (x < p->val) - { + } else if (n->right == NULL) { + if (x < p->val) { p->right = n->left; - } - else - { + } else { p->left = n->left; } - } - else if (n->left == NULL) - { - if (x < p->val) - { + } else if (n->left == NULL) { + if (x < p->val) { p->right = n->right; - } - else - { + } else { p->left = n->right; } - } - else - { + } else { int y = findMaxInLeftST(n->left); n->val = y; Remove(n, n->right, y); } - } - else if (x < n->val) - { + } else if (x < n->val) { Remove(n, n->left, x); - } - else - { + } else { Remove(n, n->right, x); } } -void BFT(node *n) -{ - if (n != NULL) - { +void BFT(node *n) { + if (n != NULL) { cout << n->val << " "; enqueue(n->left); enqueue(n->right); @@ -129,38 +91,31 @@ void BFT(node *n) } } -void Pre(node *n) -{ - if (n != NULL) - { +void Pre(node *n) { + if (n != NULL) { cout << n->val << " "; Pre(n->left); Pre(n->right); } } -void In(node *n) -{ - if (n != NULL) - { +void In(node *n) { + if (n != NULL) { In(n->left); cout << n->val << " "; In(n->right); } } -void Post(node *n) -{ - if (n != NULL) - { +void Post(node *n) { + if (n != NULL) { Post(n->left); Post(n->right); cout << n->val << " "; } } -int main() -{ +int main() { q.front = 0; q.rear = 0; int value; @@ -171,8 +126,7 @@ int main() root->val = value; root->left = NULL; root->right = NULL; - do - { + do { cout << "\n1. Insert"; cout << "\n2. Delete"; cout << "\n3. Breadth First"; @@ -183,8 +137,7 @@ int main() cout << "\nEnter Your Choice : "; cin >> ch; int x; - switch (ch) - { + switch (ch) { case 1: cout << "\nEnter the value to be Inserted : "; cin >> x; diff --git a/data_structure/binaryheap.cpp b/data_structure/binaryheap.cpp index b2fc7d99cb4..a31d8767457 100644 --- a/data_structure/binaryheap.cpp +++ b/data_structure/binaryheap.cpp @@ -7,8 +7,7 @@ using namespace std; void swap(int *x, int *y); // A class for Min Heap -class MinHeap -{ +class MinHeap { int *harr; // pointer to array of elements in heap int capacity; // maximum possible size of min heap int heap_size; // Current number of elements in min heap @@ -44,18 +43,15 @@ class MinHeap }; // Constructor: Builds a heap from a given array a[] of given size -MinHeap::MinHeap(int cap) -{ +MinHeap::MinHeap(int cap) { heap_size = 0; capacity = cap; harr = new int[cap]; } // Inserts a new key 'k' -void MinHeap::insertKey(int k) -{ - if (heap_size == capacity) - { +void MinHeap::insertKey(int k) { + if (heap_size == capacity) { cout << "\nOverflow: Could not insertKey\n"; return; } @@ -66,8 +62,7 @@ void MinHeap::insertKey(int k) harr[i] = k; // Fix the min heap property if it is violated - while (i != 0 && harr[parent(i)] > harr[i]) - { + while (i != 0 && harr[parent(i)] > harr[i]) { swap(&harr[i], &harr[parent(i)]); i = parent(i); } @@ -75,23 +70,19 @@ void MinHeap::insertKey(int k) // Decreases value of key at index 'i' to new_val. It is assumed that // new_val is smaller than harr[i]. -void MinHeap::decreaseKey(int i, int new_val) -{ +void MinHeap::decreaseKey(int i, int new_val) { harr[i] = new_val; - while (i != 0 && harr[parent(i)] > harr[i]) - { + while (i != 0 && harr[parent(i)] > harr[i]) { swap(&harr[i], &harr[parent(i)]); i = parent(i); } } // Method to remove minimum element (or root) from min heap -int MinHeap::extractMin() -{ +int MinHeap::extractMin() { if (heap_size <= 0) return INT_MAX; - if (heap_size == 1) - { + if (heap_size == 1) { heap_size--; return harr[0]; } @@ -107,16 +98,14 @@ int MinHeap::extractMin() // This function deletes key at index i. It first reduced value to minus // infinite, then calls extractMin() -void MinHeap::deleteKey(int i) -{ +void MinHeap::deleteKey(int i) { decreaseKey(i, INT_MIN); extractMin(); } // A recursive method to heapify a subtree with the root at given index // This method assumes that the subtrees are already heapified -void MinHeap::MinHeapify(int i) -{ +void MinHeap::MinHeapify(int i) { int l = left(i); int r = right(i); int smallest = i; @@ -124,24 +113,21 @@ void MinHeap::MinHeapify(int i) smallest = l; if (r < heap_size && harr[r] < harr[smallest]) smallest = r; - if (smallest != i) - { + if (smallest != i) { swap(&harr[i], &harr[smallest]); MinHeapify(smallest); } } // A utility function to swap two elements -void swap(int *x, int *y) -{ +void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } // Driver program to test above functions -int main() -{ +int main() { MinHeap h(11); h.insertKey(3); h.insertKey(2); diff --git a/data_structure/circular_queue_using_linked_list.cpp b/data_structure/circular_queue_using_linked_list.cpp index d871244483b..b6a471044a9 100644 --- a/data_structure/circular_queue_using_linked_list.cpp +++ b/data_structure/circular_queue_using_linked_list.cpp @@ -1,24 +1,20 @@ #include using namespace std; -struct node -{ +struct node { int data; struct node *next; }; -class Queue -{ +class Queue { node *front; node *rear; public: - Queue() - { + Queue() { front = NULL; rear = NULL; } - void createNode(int val) - { + void createNode(int val) { node *ptr; node *nn; nn = new node; @@ -28,14 +24,10 @@ class Queue front = nn; rear = nn; } - void enqueue(int val) - { - if (front == NULL || rear == NULL) - { + void enqueue(int val) { + if (front == NULL || rear == NULL) { createNode(val); - } - else - { + } else { node *ptr; node *nn; ptr = front; @@ -46,19 +38,16 @@ class Queue rear = nn; } } - void dequeue() - { + void dequeue() { node *n; n = front; front = front->next; delete (n); } - void traverse() - { + void traverse() { node *ptr; ptr = front; - do - { + do { cout << ptr->data << " "; ptr = ptr->next; } while (ptr != rear->next); @@ -66,8 +55,7 @@ class Queue cout << endl; } }; -int main(void) -{ +int main(void) { Queue q; q.enqueue(10); q.enqueue(20); diff --git a/data_structure/cll/cll.cpp b/data_structure/cll/cll.cpp index e9fcfc40b3e..42bc9067e20 100644 --- a/data_structure/cll/cll.cpp +++ b/data_structure/cll/cll.cpp @@ -5,25 +5,22 @@ using namespace std; /* Constructor */ -cll::cll() -{ +cll::cll() { head = NULL; total = 0; } -cll::~cll() { /* Desstructure, no need to fill */ } +cll::~cll() { /* Desstructure, no need to fill */ +} /* Display a list. and total element */ -void cll::display() -{ +void cll::display() { if (head == NULL) cout << "List is empty !" << endl; - else - { + else { cout << "CLL list: "; node *current = head; - for (int i = 0; i < total; i++) - { + for (int i = 0; i < total; i++) { cout << current->data << " -> "; current = current->next; } @@ -33,22 +30,17 @@ void cll::display() } /* List insert a new value at head in list */ -void cll::insert_front(int new_data) -{ +void cll::insert_front(int new_data) { node *newNode; newNode = new node; newNode->data = new_data; newNode->next = NULL; - if (head == NULL) - { + if (head == NULL) { head = newNode; head->next = head; - } - else - { + } else { node *current = head; - while (current->next != head) - { + while (current->next != head) { current = current->next; } newNode->next = head; @@ -59,22 +51,17 @@ void cll::insert_front(int new_data) } /* List insert a new value at head in list */ -void cll::insert_tail(int new_data) -{ +void cll::insert_tail(int new_data) { node *newNode; newNode = new node; newNode->data = new_data; newNode->next = NULL; - if (head == NULL) - { + if (head == NULL) { head = newNode; head->next = head; - } - else - { + } else { node *current = head; - while (current->next != head) - { + while (current->next != head) { current = current->next; } current->next = newNode; @@ -88,18 +75,13 @@ int cll::get_size() { return total; } /* Return true if the requested item (sent in as an argument) is in the list, otherwise return false */ -bool cll::find_item(int item_to_find) -{ - if (head == NULL) - { +bool cll::find_item(int item_to_find) { + if (head == NULL) { cout << "List is empty !" << endl; return false; - } - else - { + } else { node *current = head; - while (current->next != head) - { + while (current->next != head) { if (current->data == item_to_find) return true; current = current->next; @@ -113,17 +95,12 @@ int cll::operator*() { return head->data; } /* Overload the pre-increment operator. The iterator is advanced to the next node. */ -void cll::operator++() -{ - if (head == NULL) - { +void cll::operator++() { + if (head == NULL) { cout << "List is empty !" << endl; - } - else - { + } else { node *current = head; - while (current->next != head) - { + while (current->next != head) { current = current->next; } current->next = head->next; diff --git a/data_structure/cll/cll.h b/data_structure/cll/cll.h index 89a9fe1991e..a1a9b4d925d 100644 --- a/data_structure/cll/cll.h +++ b/data_structure/cll/cll.h @@ -9,14 +9,12 @@ #ifndef CLL_H #define CLL_H /*The data structure is a linear linked list of integers */ -struct node -{ +struct node { int data; node* next; }; -class cll -{ +class cll { public: cll(); /* Construct without parameter */ ~cll(); diff --git a/data_structure/cll/main_cll.cpp b/data_structure/cll/main_cll.cpp index 3876f0393e9..0b6bfd3edef 100644 --- a/data_structure/cll/main_cll.cpp +++ b/data_structure/cll/main_cll.cpp @@ -1,8 +1,7 @@ #include "cll.h" using namespace std; -int main() -{ +int main() { /* Test CLL */ cout << "----------- Test construct -----------" << endl; cll list1; diff --git a/data_structure/disjoint_set.cpp b/data_structure/disjoint_set.cpp index 8d27b704fd0..dd70e4cea1d 100644 --- a/data_structure/disjoint_set.cpp +++ b/data_structure/disjoint_set.cpp @@ -7,20 +7,16 @@ using std::vector; vector root, rnk; -void CreateSet(int n) -{ +void CreateSet(int n) { root = vector(n + 1); rnk = vector(n + 1, 1); - for (int i = 1; i <= n; ++i) - { + for (int i = 1; i <= n; ++i) { root[i] = i; } } -int Find(int x) -{ - if (root[x] == x) - { +int Find(int x) { + if (root[x] == x) { return x; } return root[x] = Find(root[x]); @@ -28,50 +24,38 @@ int Find(int x) bool InSameUnion(int x, int y) { return Find(x) == Find(y); } -void Union(int x, int y) -{ +void Union(int x, int y) { int a = Find(x), b = Find(y); - if (a != b) - { - if (rnk[a] < rnk[b]) - { + if (a != b) { + if (rnk[a] < rnk[b]) { root[a] = b; - } - else if (rnk[a] > rnk[b]) - { + } else if (rnk[a] > rnk[b]) { root[b] = a; - } - else - { + } else { root[a] = b; ++rnk[b]; } } } -int main() -{ +int main() { // tests CreateSet & Find int n = 100; CreateSet(n); - for (int i = 1; i <= 100; ++i) - { - if (root[i] != i) - { + for (int i = 1; i <= 100; ++i) { + if (root[i] != i) { cout << "Fail" << endl; break; } } // tests InSameUnion & Union cout << "1 and 2 are initially not in the same subset" << endl; - if (InSameUnion(1, 2)) - { + if (InSameUnion(1, 2)) { cout << "Fail" << endl; } Union(1, 2); cout << "1 and 2 are now in the same subset" << endl; - if (!InSameUnion(1, 2)) - { + if (!InSameUnion(1, 2)) { cout << "Fail" << endl; } return 0; diff --git a/data_structure/doubly_linked_list.cpp b/data_structure/doubly_linked_list.cpp index 4907c125d74..30cc257d84f 100644 --- a/data_structure/doubly_linked_list.cpp +++ b/data_structure/doubly_linked_list.cpp @@ -2,15 +2,13 @@ #include #include -struct node -{ +struct node { int val; node *prev; node *next; } * start; -class double_linked_list -{ +class double_linked_list { public: double_linked_list() { start = NULL; } void insert(int x); @@ -20,13 +18,10 @@ class double_linked_list void reverseShow(); }; -void double_linked_list::insert(int x) -{ +void double_linked_list::insert(int x) { node *t = start; - if (start != NULL) - { - while (t->next != NULL) - { + if (start != NULL) { + while (t->next != NULL) { t = t->next; } node *n = new node; @@ -34,9 +29,7 @@ void double_linked_list::insert(int x) n->prev = t; n->val = x; n->next = NULL; - } - else - { + } else { node *n = new node; n->val = x; n->prev = NULL; @@ -45,91 +38,69 @@ void double_linked_list::insert(int x) } } -void double_linked_list::remove(int x) -{ +void double_linked_list::remove(int x) { node *t = start; - while (t != NULL && t->val != x) - { + while (t != NULL && t->val != x) { t = t->next; } - if (t == NULL) - { + if (t == NULL) { return; } - if (t->prev == NULL) - { - if (t->next == NULL) - { + if (t->prev == NULL) { + if (t->next == NULL) { start = NULL; - } - else - { + } else { start = t->next; start->prev = NULL; } - } - else if (t->next == NULL) - { + } else if (t->next == NULL) { t->prev->next = NULL; - } - else - { + } else { t->prev->next = t->next; t->next->prev = t->prev; } delete t; } -void double_linked_list::search(int x) -{ +void double_linked_list::search(int x) { node *t = start; int found = 0; - while (t != NULL) - { - if (t->val == x) - { + while (t != NULL) { + if (t->val == x) { std::cout << "\nFound"; found = 1; break; } t = t->next; } - if (found == 0) - { + if (found == 0) { std::cout << "\nNot Found"; } } -void double_linked_list::show() -{ +void double_linked_list::show() { node *t = start; - while (t != NULL) - { + while (t != NULL) { std::cout << t->val << "\t"; t = t->next; } } -void double_linked_list::reverseShow() -{ +void double_linked_list::reverseShow() { node *t = start; - while (t != NULL && t->next != NULL) - { + while (t != NULL && t->next != NULL) { t = t->next; } - while (t != NULL) - { + while (t != NULL) { std::cout << t->val << "\t"; t = t->prev; } } -int main() -{ +int main() { int choice, x; double_linked_list ob; - do - { + do { std::cout << "\n1. Insert"; std::cout << "\n2. Delete"; std::cout << "\n3. Search"; @@ -137,8 +108,7 @@ int main() std::cout << "\n5. Reverse print"; std::cout << "\n\nEnter you choice : "; std::cin >> choice; - switch (choice) - { + switch (choice) { case 1: std::cout << "\nEnter the element to be inserted : "; std::cin >> x; diff --git a/data_structure/linked_list.cpp b/data_structure/linked_list.cpp index f639bb16ce7..8eb6e586d5a 100644 --- a/data_structure/linked_list.cpp +++ b/data_structure/linked_list.cpp @@ -1,42 +1,32 @@ #include -struct node -{ +struct node { int val; node *next; }; node *start; -void insert(int x) -{ +void insert(int x) { node *t = start; node *n = new node; n->val = x; n->next = NULL; - if (start != NULL) - { - while (t->next != NULL) - { + if (start != NULL) { + while (t->next != NULL) { t = t->next; } t->next = n; - } - else - { + } else { start = n; } } -void remove(int x) -{ - if (start == NULL) - { +void remove(int x) { + if (start == NULL) { std::cout << "\nLinked List is empty\n"; return; - } - else if (start->val == x) - { + } else if (start->val == x) { node *temp = start; start = start->next; delete temp; @@ -45,14 +35,12 @@ void remove(int x) node *temp = start, *parent = start; - while (temp != NULL && temp->val != x) - { + while (temp != NULL && temp->val != x) { parent = temp; temp = temp->next; } - if (temp == NULL) - { + if (temp == NULL) { std::cout << std::endl << x << " not found in list\n"; return; } @@ -61,44 +49,35 @@ void remove(int x) delete temp; } -void search(int x) -{ +void search(int x) { node *t = start; int found = 0; - while (t != NULL) - { - if (t->val == x) - { + while (t != NULL) { + if (t->val == x) { std::cout << "\nFound"; found = 1; break; } t = t->next; } - if (found == 0) - { + if (found == 0) { std::cout << "\nNot Found"; } } -void show() -{ +void show() { node *t = start; - while (t != NULL) - { + while (t != NULL) { std::cout << t->val << "\t"; t = t->next; } } -void reverse() -{ +void reverse() { node *first = start; - if (first != NULL) - { + if (first != NULL) { node *second = first->next; - while (second != NULL) - { + while (second != NULL) { node *tem = second->next; second->next = first; first = second; @@ -106,18 +85,14 @@ void reverse() } start->next = NULL; start = first; - } - else - { + } else { std::cout << "\nEmpty list"; } } -int main() -{ +int main() { int choice, x; - do - { + do { std::cout << "\n1. Insert"; std::cout << "\n2. Delete"; std::cout << "\n3. Search"; @@ -126,8 +101,7 @@ int main() std::cout << "\n0. Exit"; std::cout << "\n\nEnter you choice : "; std::cin >> choice; - switch (choice) - { + switch (choice) { case 1: std::cout << "\nEnter the element to be inserted : "; std::cin >> x; diff --git a/data_structure/linkedlist_implentation_usingarray.cpp b/data_structure/linkedlist_implentation_usingarray.cpp index 168124f003b..a078bef1692 100644 --- a/data_structure/linkedlist_implentation_usingarray.cpp +++ b/data_structure/linkedlist_implentation_usingarray.cpp @@ -7,18 +7,15 @@ #include using namespace std; -struct Node -{ +struct Node { int data; int next; }; Node AvailArray[100]; // array that will act as nodes of a linked list. int head = -1; int avail = 0; -void initialise_list() -{ - for (int i = 0; i <= 98; i++) - { +void initialise_list() { + for (int i = 0; i <= 98; i++) { AvailArray[i].next = i + 1; } AvailArray[99].next = -1; // indicating the end of the linked list. @@ -50,12 +47,10 @@ void insertAtTheBeginning(int data) // The function will insert the given data head = newNode; } -void insertAtTheEnd(int data) -{ +void insertAtTheEnd(int data) { int newNode = getnode(); int temp = head; - while (AvailArray[temp].next != -1) - { + while (AvailArray[temp].next != -1) { temp = AvailArray[temp].next; } // temp is now pointing to the end node. @@ -64,11 +59,9 @@ void insertAtTheEnd(int data) AvailArray[temp].next = newNode; } -void display() -{ +void display() { int temp = head; - while (temp != -1) - { + while (temp != -1) { cout << AvailArray[temp].data << "->"; temp = AvailArray[temp].next; } @@ -76,20 +69,17 @@ void display() ; } -int main() -{ +int main() { initialise_list(); int x, y, z; - for (;;) - { + for (;;) { cout << "1. Insert At The Beginning" << endl; cout << "2. Insert At The End" << endl; cout << "3. Display" << endl; cout << "4.Exit" << endl; cout << "Enter Your choice" << endl; cin >> z; - switch (z) - { + switch (z) { case 1: cout << "Enter the number you want to enter" << endl; cin >> x; diff --git a/data_structure/list_array.cpp b/data_structure/list_array.cpp index f572b77b461..c796ffef91c 100644 --- a/data_structure/list_array.cpp +++ b/data_structure/list_array.cpp @@ -1,16 +1,13 @@ #include using namespace std; -struct list -{ +struct list { int data[50]; int top = 0; bool isSorted = false; - int BinarySearch(int *array, int first, int last, int x) - { - if (last < first) - { + int BinarySearch(int *array, int first, int last, int x) { + if (last < first) { return -1; } int mid = (first + last) / 2; @@ -22,12 +19,9 @@ struct list return (BinarySearch(array, mid + 1, last, x)); } - int LinarSearch(int *array, int x) - { - for (int i = 0; i < top; i++) - { - if (array[i] == x) - { + int LinarSearch(int *array, int x) { + for (int i = 0; i < top; i++) { + if (array[i] == x) { return i; } } @@ -35,41 +29,31 @@ struct list return -1; } - int Search(int x) - { + int Search(int x) { int pos = -1; - if (isSorted) - { + if (isSorted) { pos = BinarySearch(data, 0, top - 1, x); } - else - { + else { pos = LinarSearch(data, x); } - if (pos != -1) - { + if (pos != -1) { cout << "\nElement found at position : " << pos; - } - else - { + } else { cout << "\nElement not found"; } return pos; } - void Sort() - { + void Sort() { int i, j, pos; - for (i = 0; i < top; i++) - { + for (i = 0; i < top; i++) { int min = data[i]; - for (j = i + 1; j < top; j++) - { - if (data[j] < min) - { + for (j = i + 1; j < top; j++) { + if (data[j] < min) { pos = j; min = data[pos]; } @@ -82,40 +66,30 @@ struct list isSorted = true; } - void insert(int x) - { - if (!isSorted) - { - if (top == 49) - { + void insert(int x) { + if (!isSorted) { + if (top == 49) { cout << "\nOverflow"; - } - else - { + } else { data[top] = x; top++; } } - else - { + else { int pos = 0; - for (int i = 0; i < top - 1; i++) - { - if (data[i] <= x && x <= data[i + 1]) - { + for (int i = 0; i < top - 1; i++) { + if (data[i] <= x && x <= data[i + 1]) { pos = i + 1; break; } } - if (pos == 0) - { + if (pos == 0) { pos = top - 1; } - for (int i = top; i > pos; i--) - { + for (int i = top; i > pos; i--) { data[i] = data[i - 1]; } top++; @@ -123,33 +97,27 @@ struct list } } - void Remove(int x) - { + void Remove(int x) { int pos = Search(x); cout << "\n" << data[pos] << " deleted"; - for (int i = pos; i < top; i++) - { + for (int i = pos; i < top; i++) { data[i] = data[i + 1]; } top--; } - void Show() - { - for (int i = 0; i < top; i++) - { + void Show() { + for (int i = 0; i < top; i++) { cout << data[i] << "\t"; } } }; -int main() -{ +int main() { list L; int choice; int x; - do - { + do { cout << "\n1.Insert"; cout << "\n2.Delete"; cout << "\n3.Search"; @@ -157,8 +125,7 @@ int main() cout << "\n5.Print"; cout << "\n\nEnter Your Choice : "; cin >> choice; - switch (choice) - { + switch (choice) { case 1: cout << "\nEnter the element to be inserted : "; cin >> x; diff --git a/data_structure/morrisinorder.cpp b/data_structure/morrisinorder.cpp index 58f267907f2..f1f9e068c9f 100644 --- a/data_structure/morrisinorder.cpp +++ b/data_structure/morrisinorder.cpp @@ -7,39 +7,32 @@ using namespace std; -struct Btree -{ +struct Btree { int data; struct Btree *left; // Pointer to left subtree struct Btree *right; // Pointer to right subtree }; -void insert(Btree **root, int d) -{ +void insert(Btree **root, int d) { Btree *nn = new Btree(); // Creating new node nn->data = d; nn->left = NULL; nn->right = NULL; - if (*root == NULL) - { + if (*root == NULL) { *root = nn; return; - } - else - { + } else { queue q; // Adding root node to queue q.push(*root); - while (!q.empty()) - { + while (!q.empty()) { Btree *node = q.front(); // Removing parent node from queue q.pop(); if (node->left) // Adding left child of removed node to queue q.push(node->left); - else - { + else { // Adding new node if no left child is present node->left = nn; return; @@ -47,8 +40,7 @@ void insert(Btree **root, int d) if (node->right) // Adding right child of removed node to queue q.push(node->right); - else - { + else { // Adding new node if no right child is present node->right = nn; return; @@ -57,36 +49,29 @@ void insert(Btree **root, int d) } } -void morrisInorder(Btree *root) -{ +void morrisInorder(Btree *root) { Btree *curr = root; Btree *temp; - while (curr) - { - if (curr->left == NULL) - { + while (curr) { + if (curr->left == NULL) { cout << curr->data << " "; // If left of current node is NULL then curr is shifted to right curr = curr->right; - } - else - { + } else { // Left of current node is stored in temp temp = curr->left; // Moving to extreme right of temp while (temp->right && temp->right != curr) temp = temp->right; // If extreme right is null it is made to point to currrent node // (will be used for backtracking) - if (temp->right == NULL) - { + if (temp->right == NULL) { temp->right = curr; // current node is made to point its left subtree curr = curr->left; } // If extreme right already points to currrent node it it set to // null - else if (temp->right == curr) - { + else if (temp->right == curr) { cout << curr->data << " "; temp->right = NULL; // current node is made to point its right subtree @@ -96,8 +81,7 @@ void morrisInorder(Btree *root) } } -int main() -{ +int main() { // Testing morrisInorder funtion Btree *root = NULL; int i; diff --git a/data_structure/queue/queue.cpp b/data_structure/queue/queue.cpp index e8ff8966c3e..a7055bb14f2 100644 --- a/data_structure/queue/queue.cpp +++ b/data_structure/queue/queue.cpp @@ -6,8 +6,7 @@ using namespace std; /* Default constructor*/ template -queue::queue() -{ +queue::queue() { queueFront = NULL; queueRear = NULL; size = 0; @@ -15,18 +14,14 @@ queue::queue() /* Destructor */ template -queue::~queue() -{ -} +queue::~queue() {} /* Display for testing */ template -void queue::display() -{ +void queue::display() { node *current = queueFront; cout << "Front --> "; - while (current != NULL) - { + while (current != NULL) { cout << current->data << " "; current = current->next; } @@ -36,33 +31,27 @@ void queue::display() /* Determine whether the queue is empty */ template -bool queue::isEmptyQueue() -{ +bool queue::isEmptyQueue() { return (queueFront == NULL); } /* Clear queue */ template -void queue::clear() -{ +void queue::clear() { queueFront = NULL; } /* Add new item to the queue */ template -void queue::enQueue(Kind item) -{ +void queue::enQueue(Kind item) { node *newNode; newNode = new node; newNode->data = item; newNode->next = NULL; - if (queueFront == NULL) - { + if (queueFront == NULL) { queueFront = newNode; queueRear = newNode; - } - else - { + } else { queueRear->next = newNode; queueRear = queueRear->next; } @@ -71,26 +60,21 @@ void queue::enQueue(Kind item) /* Return the top element of the queue */ template -Kind queue::front() -{ +Kind queue::front() { assert(queueFront != NULL); return queueFront->data; } /* Remove the element of the queue */ template -void queue::deQueue() -{ +void queue::deQueue() { node *temp; - if (!isEmptyQueue()) - { + if (!isEmptyQueue()) { temp = queueFront; queueFront = queueFront->next; delete temp; size--; - } - else - { + } else { cout << "Queue is empty !" << endl; } } diff --git a/data_structure/queue/queue.h b/data_structure/queue/queue.h index 7e9c44559ca..d1305fc815f 100644 --- a/data_structure/queue/queue.h +++ b/data_structure/queue/queue.h @@ -4,16 +4,14 @@ /* Definition of the node */ template -struct node -{ +struct node { Kind data; node *next; }; /* Definition of the queue class */ template -class queue -{ +class queue { public: void display(); /* Show queue */ queue(); /* Default constructor*/ diff --git a/data_structure/queue/test_queue.cpp b/data_structure/queue/test_queue.cpp index d9308adcb3f..7f0923f78a6 100644 --- a/data_structure/queue/test_queue.cpp +++ b/data_structure/queue/test_queue.cpp @@ -5,8 +5,7 @@ using namespace std; -int main() -{ +int main() { queue q; cout << "---------------------- Test construct ----------------------" << endl; diff --git a/data_structure/queue_using_array.cpp b/data_structure/queue_using_array.cpp index c7fbf1ef716..a887c99fc7f 100644 --- a/data_structure/queue_using_array.cpp +++ b/data_structure/queue_using_array.cpp @@ -10,15 +10,13 @@ #define MAXSIZE 10 -class Queue_Array -{ +class Queue_Array { int front; int rear; int size; public: - Queue_Array() - { + Queue_Array() { front = -1; rear = -1; size = MAXSIZE; @@ -29,59 +27,42 @@ class Queue_Array void display(); }; -void Queue_Array::enqueue(int ele) -{ - if (rear == size - 1) - { +void Queue_Array::enqueue(int ele) { + if (rear == size - 1) { std::cout << "\nStack is full"; - } - else if (front == -1 && rear == -1) - { + } else if (front == -1 && rear == -1) { front = rear = 0; arr[rear] = ele; - } - else if (rear < size) - { + } else if (rear < size) { rear++; arr[rear] = ele; } } -int Queue_Array::dequeue() -{ +int Queue_Array::dequeue() { int d; - if (front == -1) - { + if (front == -1) { std::cout << "\nstack is empty "; return 0; - } - else if (front == rear) - { + } else if (front == rear) { d = arr[front]; front = rear = -1; - } - else - { + } else { d = arr[front++]; } return d; } -void Queue_Array::display() -{ - if (front == -1) - { +void Queue_Array::display() { + if (front == -1) { std::cout << "\nStack is empty"; - } - else - { + } else { for (int i = front; i <= rear; i++) std::cout << arr[i] << " "; } } -int main() -{ +int main() { int op, data; Queue_Array ob; @@ -90,31 +71,21 @@ int main() std::cout << "\n2. dequeue(Deletion)"; std::cout << "\n3. Display"; std::cout << "\n4. Exit"; - while (1) - { + while (1) { std::cout << "\nEnter your choice "; std::cin >> op; - if (op == 1) - { + if (op == 1) { std::cout << "Enter data "; std::cin >> data; ob.enqueue(data); - } - else if (op == 2) - { + } else if (op == 2) { data = ob.dequeue(); std::cout << "\ndequeue element is:\t" << data; - } - else if (op == 3) - { + } else if (op == 3) { ob.display(); - } - else if (op == 4) - { + } else if (op == 4) { exit(0); - } - else - { + } else { std::cout << "\nWrong choice "; } } diff --git a/data_structure/queue_using_array2.cpp b/data_structure/queue_using_array2.cpp index 7e1ada725a4..13f7d8e17f8 100644 --- a/data_structure/queue_using_array2.cpp +++ b/data_structure/queue_using_array2.cpp @@ -5,30 +5,22 @@ int queue[10]; int front = 0; int rear = 0; -void Enque(int x) -{ - if (rear == 10) - { +void Enque(int x) { + if (rear == 10) { cout << "\nOverflow"; - } - else - { + } else { queue[rear++] = x; } } -void Deque() -{ - if (front == rear) - { +void Deque() { + if (front == rear) { cout << "\nUnderflow"; } - else - { + else { cout << "\n" << queue[front++] << " deleted"; - for (int i = front; i < rear; i++) - { + for (int i = front; i < rear; i++) { queue[i - front] = queue[i]; } rear = rear - front; @@ -36,36 +28,27 @@ void Deque() } } -void show() -{ - for (int i = front; i < rear; i++) - { +void show() { + for (int i = front; i < rear; i++) { cout << queue[i] << "\t"; } } -int main() -{ +int main() { int ch, x; - do - { + do { cout << "\n1. Enque"; cout << "\n2. Deque"; cout << "\n3. Print"; cout << "\nEnter Your Choice : "; cin >> ch; - if (ch == 1) - { + if (ch == 1) { cout << "\nInsert : "; cin >> x; Enque(x); - } - else if (ch == 2) - { + } else if (ch == 2) { Deque(); - } - else if (ch == 3) - { + } else if (ch == 3) { show(); } } while (ch != 0); diff --git a/data_structure/queue_using_linked_list.cpp b/data_structure/queue_using_linked_list.cpp index 9ddbdaa423e..7b44d240c74 100644 --- a/data_structure/queue_using_linked_list.cpp +++ b/data_structure/queue_using_linked_list.cpp @@ -1,18 +1,15 @@ #include using namespace std; -struct node -{ +struct node { int val; node *next; }; node *front, *rear; -void Enque(int x) -{ - if (rear == NULL) - { +void Enque(int x) { + if (rear == NULL) { node *n = new node; n->val = x; n->next = NULL; @@ -20,8 +17,7 @@ void Enque(int x) front = n; } - else - { + else { node *n = new node; n->val = x; n->next = NULL; @@ -30,14 +26,10 @@ void Enque(int x) } } -void Deque() -{ - if (rear == NULL && front == NULL) - { +void Deque() { + if (rear == NULL && front == NULL) { cout << "\nUnderflow"; - } - else - { + } else { node *t = front; cout << "\n" << t->val << " deleted"; front = front->next; @@ -47,38 +39,29 @@ void Deque() } } -void show() -{ +void show() { node *t = front; - while (t != NULL) - { + while (t != NULL) { cout << t->val << "\t"; t = t->next; } } -int main() -{ +int main() { int ch, x; - do - { + do { cout << "\n1. Enque"; cout << "\n2. Deque"; cout << "\n3. Print"; cout << "\nEnter Your Choice : "; cin >> ch; - if (ch == 1) - { + if (ch == 1) { cout << "\nInsert : "; cin >> x; Enque(x); - } - else if (ch == 2) - { + } else if (ch == 2) { Deque(); - } - else if (ch == 3) - { + } else if (ch == 3) { show(); } } while (ch != 0); diff --git a/data_structure/queue_using_linkedlist.cpp b/data_structure/queue_using_linkedlist.cpp index 21ff0cfcfd0..f1bf18123f9 100644 --- a/data_structure/queue_using_linkedlist.cpp +++ b/data_structure/queue_using_linkedlist.cpp @@ -3,13 +3,11 @@ */ #include -struct linkedlist -{ +struct linkedlist { int data; linkedlist *next; }; -class stack_linkedList -{ +class stack_linkedList { public: linkedlist *front; linkedlist *rear; @@ -19,28 +17,24 @@ class stack_linkedList int dequeue(); void display(); }; -void stack_linkedList::enqueue(int ele) -{ +void stack_linkedList::enqueue(int ele) { linkedlist *temp = new linkedlist(); temp->data = ele; temp->next = NULL; if (front == NULL) front = rear = temp; - else - { + else { rear->next = temp; rear = temp; } } -int stack_linkedList::dequeue() -{ +int stack_linkedList::dequeue() { linkedlist *temp; int ele; if (front == NULL) std::cout << "\nStack is empty"; - else - { + else { temp = front; ele = temp->data; if (front == rear) // if length of queue is 1; @@ -50,25 +44,21 @@ int stack_linkedList::dequeue() } return ele; } -void stack_linkedList::display() -{ +void stack_linkedList::display() { if (front == NULL) std::cout << "\nStack is empty"; - else - { + else { linkedlist *temp; temp = front; - while (temp != NULL) - { + while (temp != NULL) { std::cout << temp->data << " "; temp = temp->next; } } } -int main() -{ +int main() { int op, data; stack_linkedList ob; std::cout << "\n1. enqueue(Insertion) "; @@ -76,17 +66,14 @@ int main() std::cout << "\n3. Display"; std::cout << "\n4. Exit"; - while (1) - { + while (1) { std::cout << "\nEnter your choice "; std::cin >> op; - if (op == 1) - { + if (op == 1) { std::cout << "Enter data "; std::cin >> data; ob.enqueue(data); - } - else if (op == 2) + } else if (op == 2) data = ob.dequeue(); else if (op == 3) ob.display(); diff --git a/data_structure/stack_using_array.cpp b/data_structure/stack_using_array.cpp index dd0709ff27a..5dd7ac98e82 100644 --- a/data_structure/stack_using_array.cpp +++ b/data_structure/stack_using_array.cpp @@ -4,69 +4,50 @@ using namespace std; int *stack; int top = 0, size; -void push(int x) -{ - if (top == size) - { +void push(int x) { + if (top == size) { cout << "\nOverflow"; - } - else - { + } else { stack[top++] = x; } } -void pop() -{ - if (top == 0) - { +void pop() { + if (top == 0) { cout << "\nUnderflow"; - } - else - { + } else { cout << "\n" << stack[--top] << " deleted"; } } -void show() -{ - for (int i = 0; i < top; i++) - { +void show() { + for (int i = 0; i < top; i++) { cout << stack[i] << "\n"; } } void topmost() { cout << "\nTopmost element: " << stack[top - 1]; } -int main() -{ +int main() { cout << "\nEnter Size of stack : "; cin >> size; stack = new int[size]; int ch, x; - do - { + do { cout << "\n1. Push"; cout << "\n2. Pop"; cout << "\n3. Print"; cout << "\n4. Print topmost element:"; cout << "\nEnter Your Choice : "; cin >> ch; - if (ch == 1) - { + if (ch == 1) { cout << "\nInsert : "; cin >> x; push(x); - } - else if (ch == 2) - { + } else if (ch == 2) { pop(); - } - else if (ch == 3) - { + } else if (ch == 3) { show(); - } - else if (ch == 4) - { + } else if (ch == 4) { topmost(); } } while (ch != 0); diff --git a/data_structure/stack_using_linked_list.cpp b/data_structure/stack_using_linked_list.cpp index 89a15fe39c9..ae53fe95ad3 100644 --- a/data_structure/stack_using_linked_list.cpp +++ b/data_structure/stack_using_linked_list.cpp @@ -1,30 +1,24 @@ #include using namespace std; -struct node -{ +struct node { int val; node *next; }; node *top; -void push(int x) -{ +void push(int x) { node *n = new node; n->val = x; n->next = top; top = n; } -void pop() -{ - if (top == NULL) - { +void pop() { + if (top == NULL) { cout << "\nUnderflow"; - } - else - { + } else { node *t = top; cout << "\n" << t->val << " deleted"; top = top->next; @@ -32,38 +26,29 @@ void pop() } } -void show() -{ +void show() { node *t = top; - while (t != NULL) - { + while (t != NULL) { cout << t->val << "\n"; t = t->next; } } -int main() -{ +int main() { int ch, x; - do - { + do { cout << "\n1. Push"; cout << "\n2. Pop"; cout << "\n3. Print"; cout << "\nEnter Your Choice : "; cin >> ch; - if (ch == 1) - { + if (ch == 1) { cout << "\nInsert : "; cin >> x; push(x); - } - else if (ch == 2) - { + } else if (ch == 2) { pop(); - } - else if (ch == 3) - { + } else if (ch == 3) { show(); } } while (ch != 0); diff --git a/data_structure/stk/main.cpp b/data_structure/stk/main.cpp index ceac2ac8a4a..44b7984e028 100644 --- a/data_structure/stk/main.cpp +++ b/data_structure/stk/main.cpp @@ -19,8 +19,7 @@ using namespace std; -int main(int argc, char* argv[]) -{ +int main(int argc, char* argv[]) { double GPA; double highestGPA; string name; @@ -35,24 +34,19 @@ int main(int argc, char* argv[]) infile >> GPA >> name; highestGPA = GPA; - while (infile) - { - if (GPA > highestGPA) - { + while (infile) { + if (GPA > highestGPA) { stk.clear(); stk.push(name); highestGPA = GPA; - } - else if (GPA == highestGPA) - { + } else if (GPA == highestGPA) { stk.push(name); } infile >> GPA >> name; } cout << "Highest GPA: " << highestGPA << endl; cout << "Students the highest GPA are: " << endl; - while (!stk.isEmptyStack()) - { + while (!stk.isEmptyStack()) { cout << stk.top() << endl; stk.pop(); } diff --git a/data_structure/stk/stack.cpp b/data_structure/stk/stack.cpp index 9f92efbd58b..bfa8a353e8d 100644 --- a/data_structure/stk/stack.cpp +++ b/data_structure/stk/stack.cpp @@ -6,26 +6,21 @@ using namespace std; /* Default constructor*/ template -stack::stack() -{ +stack::stack() { stackTop = NULL; size = 0; } /* Destructor */ template -stack::~stack() -{ -} +stack::~stack() {} /* Display for testing */ template -void stack::display() -{ +void stack::display() { node *current = stackTop; cout << "Top --> "; - while (current != NULL) - { + while (current != NULL) { cout << current->data << " "; current = current->next; } @@ -35,22 +30,19 @@ void stack::display() /* Determine whether the stack is empty */ template -bool stack::isEmptyStack() -{ +bool stack::isEmptyStack() { return (stackTop == NULL); } /* Clear stack */ template -void stack::clear() -{ +void stack::clear() { stackTop = NULL; } /* Add new item to the stack */ template -void stack::push(Type item) -{ +void stack::push(Type item) { node *newNode; newNode = new node; newNode->data = item; @@ -61,42 +53,35 @@ void stack::push(Type item) /* Return the top element of the stack */ template -Type stack::top() -{ +Type stack::top() { assert(stackTop != NULL); return stackTop->data; } /* Remove the top element of the stack */ template -void stack::pop() -{ +void stack::pop() { node *temp; - if (!isEmptyStack()) - { + if (!isEmptyStack()) { temp = stackTop; stackTop = stackTop->next; delete temp; size--; - } - else - { + } else { cout << "Stack is empty !" << endl; } } /* Operator "=" */ template -stack stack::operator=(stack &otherStack) -{ +stack stack::operator=(stack &otherStack) { node *newNode, *current, *last; if (stackTop != NULL) /* If stack is no empty, make it empty */ stackTop = NULL; if (otherStack.stackTop == NULL) stackTop = NULL; - else - { + else { current = otherStack.stackTop; stackTop = new node; stackTop->data = current->data; @@ -104,8 +89,7 @@ stack stack::operator=(stack &otherStack) last = stackTop; current = current->next; /* Copy the remaining stack */ - while (current != NULL) - { + while (current != NULL) { newNode = new node; newNode->data = current->data; newNode->next = NULL; diff --git a/data_structure/stk/stack.h b/data_structure/stk/stack.h index 39b455ac0f4..da7788b73b0 100644 --- a/data_structure/stk/stack.h +++ b/data_structure/stk/stack.h @@ -4,16 +4,14 @@ /* Definition of the node */ template -struct node -{ +struct node { Type data; node *next; }; /* Definition of the stack class */ template -class stack -{ +class stack { public: void display(); /* Show stack */ stack(); /* Default constructor*/ diff --git a/data_structure/stk/test_stack.cpp b/data_structure/stk/test_stack.cpp index 8839fdfa350..098027dfd8c 100644 --- a/data_structure/stk/test_stack.cpp +++ b/data_structure/stk/test_stack.cpp @@ -4,8 +4,7 @@ using namespace std; -int main() -{ +int main() { stack stk; cout << "---------------------- Test construct ----------------------" << endl; diff --git a/data_structure/tree.cpp b/data_structure/tree.cpp index 92d139b72f8..f46c31ff22a 100644 --- a/data_structure/tree.cpp +++ b/data_structure/tree.cpp @@ -2,17 +2,14 @@ #include using namespace std; -struct node -{ +struct node { int val; node *left; node *right; }; -void CreateTree(node *curr, node *n, int x, char pos) -{ - if (n != NULL) - { +void CreateTree(node *curr, node *n, int x, char pos) { + if (n != NULL) { char ch; cout << "\nLeft or Right of " << n->val << " : "; cin >> ch; @@ -20,32 +17,25 @@ void CreateTree(node *curr, node *n, int x, char pos) CreateTree(n, n->left, x, ch); else if (ch == 'r') CreateTree(n, n->right, x, ch); - } - else - { + } else { node *t = new node; t->val = x; t->left = NULL; t->right = NULL; - if (pos == 'l') - { + if (pos == 'l') { curr->left = t; - } - else if (pos == 'r') - { + } else if (pos == 'r') { curr->right = t; } } } -void BFT(node *n) -{ +void BFT(node *n) { list queue; queue.push_back(n); - while (!queue.empty()) - { + while (!queue.empty()) { n = queue.front(); cout << n->val << " "; queue.pop_front(); @@ -57,38 +47,31 @@ void BFT(node *n) } } -void Pre(node *n) -{ - if (n != NULL) - { +void Pre(node *n) { + if (n != NULL) { cout << n->val << " "; Pre(n->left); Pre(n->right); } } -void In(node *n) -{ - if (n != NULL) - { +void In(node *n) { + if (n != NULL) { In(n->left); cout << n->val << " "; In(n->right); } } -void Post(node *n) -{ - if (n != NULL) - { +void Post(node *n) { + if (n != NULL) { Post(n->left); Post(n->right); cout << n->val << " "; } } -int main() -{ +int main() { int value; int ch; node *root = new node; @@ -97,8 +80,7 @@ int main() root->val = value; root->left = NULL; root->right = NULL; - do - { + do { cout << "\n1. Insert"; cout << "\n2. Breadth First"; cout << "\n3. Preorder Depth First"; @@ -107,8 +89,7 @@ int main() cout << "\nEnter Your Choice : "; cin >> ch; - switch (ch) - { + switch (ch) { case 1: int x; char pos; diff --git a/data_structure/trie_tree.cpp b/data_structure/trie_tree.cpp index d34dd2dbc29..66b67fbc0cb 100644 --- a/data_structure/trie_tree.cpp +++ b/data_structure/trie_tree.cpp @@ -5,15 +5,13 @@ #include // structure definition -typedef struct trie -{ +typedef struct trie { struct trie* arr[26]; bool isEndofWord; } trie; // create a new node for trie -trie* createNode() -{ +trie* createNode() { trie* nn = new trie(); for (int i = 0; i < 26; i++) nn->arr[i] = NULL; nn->isEndofWord = false; @@ -21,17 +19,12 @@ trie* createNode() } // insert string into the trie -void insert(trie* root, std::string str) -{ - for (int i = 0; i < str.length(); i++) - { +void insert(trie* root, std::string str) { + for (int i = 0; i < str.length(); i++) { int j = str[i] - 'a'; - if (root->arr[j]) - { + if (root->arr[j]) { root = root->arr[j]; - } - else - { + } else { root->arr[j] = createNode(); root = root->arr[j]; } @@ -40,10 +33,8 @@ void insert(trie* root, std::string str) } // search a string exists inside the trie -bool search(trie* root, std::string str, int index) -{ - if (index == str.length()) - { +bool search(trie* root, std::string str, int index) { + if (index == str.length()) { if (!root->isEndofWord) return false; return true; @@ -59,10 +50,8 @@ removes the string if it is not a prefix of any other string, if it is then just sets the endofword to false, else removes the given string */ -bool deleteString(trie* root, std::string str, int index) -{ - if (index == str.length()) - { +bool deleteString(trie* root, std::string str, int index) { + if (index == str.length()) { if (!root->isEndofWord) return false; root->isEndofWord = false; @@ -73,15 +62,11 @@ bool deleteString(trie* root, std::string str, int index) if (!root->arr[j]) return false; bool var = deleteString(root, str, index + 1); - if (var) - { + if (var) { root->arr[j] = NULL; - if (root->isEndofWord) - { + if (root->isEndofWord) { return false; - } - else - { + } else { int i; for (i = 0; i < 26; i++) if (root->arr[i]) @@ -91,8 +76,7 @@ bool deleteString(trie* root, std::string str, int index) } } -int main() -{ +int main() { trie* root = createNode(); insert(root, "hello"); insert(root, "world"); diff --git a/dynamic_programming/0_1_knapsack.cpp b/dynamic_programming/0_1_knapsack.cpp index 0ce40ca0a99..7ea0c04c626 100644 --- a/dynamic_programming/0_1_knapsack.cpp +++ b/dynamic_programming/0_1_knapsack.cpp @@ -28,13 +28,10 @@ using namespace std; // } //} -int Knapsack(int capacity, int n, int weight[], int value[]) -{ +int Knapsack(int capacity, int n, int weight[], int value[]) { int res[20][20]; - for (int i = 0; i < n + 1; ++i) - { - for (int j = 0; j < capacity + 1; ++j) - { + for (int i = 0; i < n + 1; ++i) { + for (int j = 0; j < capacity + 1; ++j) { if (i == 0 || j == 0) res[i][j] = 0; else if (weight[i - 1] <= j) @@ -48,20 +45,17 @@ int Knapsack(int capacity, int n, int weight[], int value[]) // cout<<"\n"; return res[n][capacity]; } -int main() -{ +int main() { int n; cout << "Enter number of items: "; cin >> n; int weight[n], value[n]; cout << "Enter weights: "; - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { cin >> weight[i]; } cout << "Enter values: "; - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { cin >> value[i]; } int capacity; diff --git a/dynamic_programming/armstrong_number.cpp b/dynamic_programming/armstrong_number.cpp index 218d6365d1a..270a705f7b4 100644 --- a/dynamic_programming/armstrong_number.cpp +++ b/dynamic_programming/armstrong_number.cpp @@ -4,14 +4,12 @@ using std::cin; using std::cout; -int main() -{ +int main() { int n, k, d, s = 0; cout << "Enter a number:"; cin >> n; k = n; - while (k != 0) - { + while (k != 0) { d = k % 10; s += d * d * d; k /= 10; diff --git a/dynamic_programming/bellman_ford.cpp b/dynamic_programming/bellman_ford.cpp index 85d3bff0619..c96f3fd8eea 100644 --- a/dynamic_programming/bellman_ford.cpp +++ b/dynamic_programming/bellman_ford.cpp @@ -4,33 +4,28 @@ using namespace std; // Wrapper class for storing an edge -class Edge -{ +class Edge { public: int src, dst, weight; }; // Wrapper class for storing a graph -class Graph -{ +class Graph { public: int vertexNum, edgeNum; Edge *edges; // Constructs a graph with V vertices and E edges - Graph(int V, int E) - { + Graph(int V, int E) { this->vertexNum = V; this->edgeNum = E; this->edges = (Edge *)malloc(E * sizeof(Edge)); } // Adds the given edge to the graph - void addEdge(int src, int dst, int weight) - { + void addEdge(int src, int dst, int weight) { static int edgeInd = 0; - if (edgeInd < this->edgeNum) - { + if (edgeInd < this->edgeNum) { Edge newEdge; newEdge.src = src; newEdge.dst = dst; @@ -41,11 +36,9 @@ class Graph }; // Utility function to print distances -void print(int dist[], int V) -{ +void print(int dist[], int V) { cout << "\nVertex Distance" << endl; - for (int i = 0; i < V; i++) - { + for (int i = 0; i < V; i++) { if (dist[i] != INT_MAX) cout << i << "\t" << dist[i] << endl; else @@ -56,8 +49,7 @@ void print(int dist[], int V) // The main function that finds the shortest path from given source // to all other vertices using Bellman-Ford.It also detects negative // weight cycle -void BellmanFord(Graph graph, int src) -{ +void BellmanFord(Graph graph, int src) { int V = graph.vertexNum; int E = graph.edgeNum; int dist[V]; @@ -70,8 +62,7 @@ void BellmanFord(Graph graph, int src) // Calculate shortest path distance from source to all edges // A path can contain maximum (|V|-1) edges for (int i = 0; i <= V - 1; i++) - for (int j = 0; j < E; j++) - { + for (int j = 0; j < E; j++) { int u = graph.edges[j].src; int v = graph.edges[j].dst; int w = graph.edges[j].weight; @@ -81,14 +72,12 @@ void BellmanFord(Graph graph, int src) } // Iterate inner loop once more to check for negative cycle - for (int j = 0; j < E; j++) - { + for (int j = 0; j < E; j++) { int u = graph.edges[j].src; int v = graph.edges[j].dst; int w = graph.edges[j].weight; - if (dist[u] != INT_MAX && dist[u] + w < dist[v]) - { + if (dist[u] != INT_MAX && dist[u] + w < dist[v]) { cout << "Graph contains negative weight cycle. Hence, shortest " "distance not guaranteed." << endl; @@ -102,8 +91,7 @@ void BellmanFord(Graph graph, int src) } // Driver Function -int main() -{ +int main() { int V, E, gsrc; int src, dst, weight; cout << "Enter number of vertices: "; @@ -111,8 +99,7 @@ int main() cout << "Enter number of edges: "; cin >> E; Graph G(V, E); - for (int i = 0; i < E; i++) - { + for (int i = 0; i < E; i++) { cout << "\nEdge " << i + 1 << "\nEnter source: "; cin >> src; cout << "Enter destination: "; diff --git a/dynamic_programming/catalan_numbers.cpp b/dynamic_programming/catalan_numbers.cpp index 0107b9f20f8..f5edaa916eb 100644 --- a/dynamic_programming/catalan_numbers.cpp +++ b/dynamic_programming/catalan_numbers.cpp @@ -11,8 +11,7 @@ using namespace std; int *cat; // global array to hold catalan numbers -unsigned long int catalan_dp(int n) -{ +unsigned long int catalan_dp(int n) { /** Using the tabulation technique in dynamic programming, this function computes the first `n+1` Catalan numbers @@ -29,8 +28,7 @@ unsigned long int catalan_dp(int n) cat[0] = cat[1] = 1; // Compute the remaining numbers from index 2 to index n, using tabulation - for (int i = 2; i <= n; i++) - { + for (int i = 2; i <= n; i++) { cat[i] = 0; for (int j = 0; j < i; j++) cat[i] += cat[j] * cat[i - j - 1]; // applying the definition here @@ -40,8 +38,7 @@ unsigned long int catalan_dp(int n) return cat[n]; } -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { int n; cout << "Enter n: "; cin >> n; @@ -49,8 +46,7 @@ int main(int argc, char *argv[]) cat = new int[n + 1]; cout << "Catalan numbers from 0 to " << n << " are:\n"; - for (int i = 0; i <= n; i++) - { + for (int i = 0; i <= n; i++) { cout << "catalan (" << i << ") = " << catalan_dp(i) << endl; // NOTE: Since `cat` is a global array, calling `catalan_dp` // repeatedly will not recompute the the values already computed diff --git a/dynamic_programming/coin_change.cpp b/dynamic_programming/coin_change.cpp index f43d4fa18d0..8c8fc3dfb68 100644 --- a/dynamic_programming/coin_change.cpp +++ b/dynamic_programming/coin_change.cpp @@ -3,8 +3,7 @@ using namespace std; // Function to find the Minimum number of coins required to get Sum S -int findMinCoins(int arr[], int n, int N) -{ +int findMinCoins(int arr[], int n, int N) { // dp[i] = no of coins required to get a total of i int dp[N + 1]; @@ -12,15 +11,13 @@ int findMinCoins(int arr[], int n, int N) dp[0] = 0; - for (int i = 1; i <= N; i++) - { + for (int i = 1; i <= N; i++) { // initialize minimum number of coins needed to infinity dp[i] = INT_MAX; int res = INT_MAX; // do for each coin - for (int c = 0; c < n; c++) - { + for (int c = 0; c < n; c++) { if (i - arr[c] >= 0) // check if coins doesn't become negative by including it res = dp[i - arr[c]]; @@ -36,8 +33,7 @@ int findMinCoins(int arr[], int n, int N) return dp[N]; } -int main() -{ +int main() { // No of Coins We Have int arr[] = {1, 2, 3, 4}; int n = sizeof(arr) / sizeof(arr[0]); diff --git a/dynamic_programming/cut_rod.cpp b/dynamic_programming/cut_rod.cpp index 3df0a9fbe6d..136c78dbbab 100644 --- a/dynamic_programming/cut_rod.cpp +++ b/dynamic_programming/cut_rod.cpp @@ -5,23 +5,19 @@ the pieces.*/ #include using namespace std; -int cutrod(int p[], int n) -{ +int cutrod(int p[], int n) { int r[n + 1]; r[0] = 0; - for (int j = 0; j < n; j++) - { + for (int j = 0; j < n; j++) { int q = INT_MIN; - for (int i = 0; i <= j; i++) - { + for (int i = 0; i <= j; i++) { q = max(q, p[i] + r[j - i]); } r[j + 1] = q; } return r[n]; } -int main() -{ +int main() { int price[] = {1, 5, 8, 9, 10, 17, 17, 20, 24, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50}; cout << cutrod(price, 30); diff --git a/dynamic_programming/edit_distance.cpp b/dynamic_programming/edit_distance.cpp index da613b23832..889b080cb93 100644 --- a/dynamic_programming/edit_distance.cpp +++ b/dynamic_programming/edit_distance.cpp @@ -22,8 +22,7 @@ int min(int x, int y, int z) { return min(min(x, y), z); } * str1 to str2. * O(3^m) */ -int editDist(string str1, string str2, int m, int n) -{ +int editDist(string str1, string str2, int m, int n) { if (m == 0) return n; if (n == 0) @@ -45,16 +44,13 @@ int editDist(string str1, string str2, int m, int n) /* A DP based program * O(m x n) */ -int editDistDP(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]; // Fill d[][] in bottom up manner - for (int i = 0; i <= m; i++) - { - for (int j = 0; j <= n; j++) - { + for (int i = 0; i <= m; i++) { + for (int j = 0; j <= n; j++) { // If str1 empty. Then add all of str2 if (i == 0) dp[i][j] = j; @@ -78,8 +74,7 @@ int editDistDP(string str1, string str2, int m, int n) return dp[m][n]; } -int main() -{ +int main() { string str1 = "sunday"; string str2 = "saturday"; diff --git a/dynamic_programming/egg_dropping_puzzle.cpp b/dynamic_programming/egg_dropping_puzzle.cpp index 79de4cc22fd..7a769ea472e 100644 --- a/dynamic_programming/egg_dropping_puzzle.cpp +++ b/dynamic_programming/egg_dropping_puzzle.cpp @@ -6,30 +6,24 @@ #include using namespace std; -int eggDrop(int n, int k) -{ +int eggDrop(int n, int k) { int eggFloor[n + 1][k + 1]; int result; - for (int i = 1; i <= n; i++) - { + for (int i = 1; i <= n; i++) { eggFloor[i][1] = 1; // n eggs..1 Floor eggFloor[i][0] = 0; // n eggs..0 Floor } // Only one egg available - for (int j = 1; j <= k; j++) - { + for (int j = 1; j <= k; j++) { eggFloor[1][j] = j; } - for (int i = 2; i <= n; i++) - { - for (int j = 2; j <= k; j++) - { + for (int i = 2; i <= n; i++) { + for (int j = 2; j <= k; j++) { eggFloor[i][j] = INT_MAX; - for (int x = 1; x <= j; x++) - { + for (int x = 1; x <= j; x++) { // 1+max(eggBreak[one less egg, lower floors], // eggDoesntBreak[same # of eggs, upper floors]); result = 1 + max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]); @@ -42,8 +36,7 @@ int eggDrop(int n, int k) return eggFloor[n][k]; } -int main() -{ +int main() { int n, k; cout << "Enter number of eggs and floors: "; cin >> n >> k; diff --git a/dynamic_programming/fibonacci_bottom_up.cpp b/dynamic_programming/fibonacci_bottom_up.cpp index 3a9669fa9c1..555f15282f4 100644 --- a/dynamic_programming/fibonacci_bottom_up.cpp +++ b/dynamic_programming/fibonacci_bottom_up.cpp @@ -1,20 +1,17 @@ #include using namespace std; -int fib(int n) -{ +int fib(int n) { int res[3]; res[0] = 0; res[1] = 1; - for (int i = 2; i <= n; i++) - { + for (int i = 2; i <= n; i++) { res[2] = res[1] + res[0]; res[0] = res[1]; res[1] = res[2]; } return res[1]; } -int main(int argc, char const *argv[]) -{ +int main(int argc, char const *argv[]) { int n; cout << "Enter n: "; cin >> n; diff --git a/dynamic_programming/fibonacci_top_down.cpp b/dynamic_programming/fibonacci_top_down.cpp index 3ac3fdb40a0..3c0c9a1a323 100644 --- a/dynamic_programming/fibonacci_top_down.cpp +++ b/dynamic_programming/fibonacci_top_down.cpp @@ -1,10 +1,8 @@ #include using namespace std; int arr[1000000]; -int fib(int n) -{ - if (arr[n] == -1) - { +int fib(int n) { + if (arr[n] == -1) { if (n <= 1) arr[n] = n; else @@ -12,13 +10,11 @@ int fib(int n) } return arr[n]; } -int main(int argc, char const *argv[]) -{ +int main(int argc, char const *argv[]) { int n; cout << "Enter n: "; cin >> n; - for (int i = 0; i < n + 1; ++i) - { + for (int i = 0; i < n + 1; ++i) { arr[i] = -1; } cout << "Fibonacci number is " << fib(n) << endl; diff --git a/dynamic_programming/kadane.cpp b/dynamic_programming/kadane.cpp index 31d17ae9e92..b5272756bcf 100644 --- a/dynamic_programming/kadane.cpp +++ b/dynamic_programming/kadane.cpp @@ -1,12 +1,10 @@ #include #include -int maxSubArraySum(int a[], int size) -{ +int maxSubArraySum(int a[], int size) { int max_so_far = INT_MIN, max_ending_here = 0; - for (int i = 0; i < size; i++) - { + 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; @@ -17,14 +15,12 @@ int maxSubArraySum(int a[], int size) return max_so_far; } -int main() -{ +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++) - { + for (i = 0; i < n; i++) { std::cin >> a[i]; } int max_sum = maxSubArraySum(a, n); diff --git a/dynamic_programming/longest_common_string.cpp b/dynamic_programming/longest_common_string.cpp index e33489cb1da..81fa8a0026a 100644 --- a/dynamic_programming/longest_common_string.cpp +++ b/dynamic_programming/longest_common_string.cpp @@ -3,8 +3,7 @@ using namespace std; int max(int a, int b) { return (a > b) ? a : b; } -int main() -{ +int main() { char str1[] = "DEFBCD"; char str2[] = "ABDEFJ"; int i, j, k; @@ -13,10 +12,8 @@ int main() // cout< ma) - { + for (i = 0; i < m; i++) { + for (j = 0; j < n; j++) { + if (a[i][j] > ma) { ma = a[i][j]; indi = i; indj = j; diff --git a/dynamic_programming/longest_common_subsequence.cpp b/dynamic_programming/longest_common_subsequence.cpp index 7973bb05e6d..662c26ad2c3 100644 --- a/dynamic_programming/longest_common_subsequence.cpp +++ b/dynamic_programming/longest_common_subsequence.cpp @@ -2,69 +2,50 @@ #include using namespace std; -void Print(int trace[20][20], int m, int n, string a) -{ - if (m == 0 || n == 0) - { +void Print(int trace[20][20], int m, int n, string a) { + if (m == 0 || n == 0) { return; } - if (trace[m][n] == 1) - { + if (trace[m][n] == 1) { Print(trace, m - 1, n - 1, a); cout << a[m - 1]; - } - else if (trace[m][n] == 2) - { + } else if (trace[m][n] == 2) { Print(trace, m - 1, n, a); - } - else if (trace[m][n] == 3) - { + } else if (trace[m][n] == 3) { Print(trace, m, n - 1, a); } } -int lcs(string a, string b) -{ +int lcs(string a, string b) { int m = a.length(), n = b.length(); int res[m + 1][n + 1]; int trace[20][20]; // fills up the arrays with zeros. - for (int i = 0; i < m + 1; i++) - { - for (int j = 0; j < n + 1; j++) - { + for (int i = 0; i < m + 1; i++) { + for (int j = 0; j < n + 1; j++) { res[i][j] = 0; trace[i][j] = 0; } } - for (int i = 0; i < m + 1; ++i) - { - for (int j = 0; j < n + 1; ++j) - { - if (i == 0 || j == 0) - { + for (int i = 0; i < m + 1; ++i) { + for (int j = 0; j < n + 1; ++j) { + if (i == 0 || j == 0) { res[i][j] = 0; trace[i][j] = 0; } - else if (a[i - 1] == b[j - 1]) - { + else if (a[i - 1] == b[j - 1]) { res[i][j] = 1 + res[i - 1][j - 1]; trace[i][j] = 1; // 1 means trace the matrix in upper left // diagonal direction. - } - else - { - if (res[i - 1][j] > res[i][j - 1]) - { + } else { + if (res[i - 1][j] > res[i][j - 1]) { res[i][j] = res[i - 1][j]; trace[i][j] = 2; // 2 means trace the matrix in upwards direction. - } - else - { + } else { res[i][j] = res[i][j - 1]; trace[i][j] = 3; // means trace the matrix in left direction. @@ -76,8 +57,7 @@ int lcs(string a, string b) return res[m][n]; } -int main() -{ +int main() { string a, b; cin >> a >> b; cout << lcs(a, b); diff --git a/dynamic_programming/longest_increasing_subsequence.cpp b/dynamic_programming/longest_increasing_subsequence.cpp index 573db34a58f..b6a798aa050 100644 --- a/dynamic_programming/longest_increasing_subsequence.cpp +++ b/dynamic_programming/longest_increasing_subsequence.cpp @@ -1,37 +1,30 @@ // Program to calculate length of longest increasing subsequence in an array #include using namespace std; -int LIS(int a[], int n) -{ +int LIS(int a[], int n) { int lis[n]; - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { lis[i] = 1; } - for (int i = 0; i < n; ++i) - { - for (int j = 0; j < i; ++j) - { + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { if (a[i] > a[j] && lis[i] < lis[j] + 1) lis[i] = lis[j] + 1; } } int res = 0; - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { res = max(res, lis[i]); } return res; } -int main(int argc, char const *argv[]) -{ +int main(int argc, char const *argv[]) { int n; cout << "Enter size of array: "; cin >> n; int a[n]; cout << "Enter array elements: "; - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { cin >> a[i]; } cout << LIS(a, n) << endl; diff --git a/dynamic_programming/longest_increasing_subsequence_(nlogn).cpp b/dynamic_programming/longest_increasing_subsequence_(nlogn).cpp index 2471b701f38..5bc72345c23 100644 --- a/dynamic_programming/longest_increasing_subsequence_(nlogn).cpp +++ b/dynamic_programming/longest_increasing_subsequence_(nlogn).cpp @@ -5,24 +5,19 @@ #include using namespace std; -int LIS(int arr[], int n) -{ +int LIS(int arr[], int n) { set active; // The current built LIS. active.insert(arr[0]); // Loop through every element. - for (int i = 1; i < n; ++i) - { + for (int i = 1; i < n; ++i) { auto get = active.lower_bound(arr[i]); - if (get == active.end()) - { + if (get == active.end()) { active.insert(arr[i]); } // current element is the greatest so LIS increases by 1. - else - { + else { int val = *get; // we find the position where arr[i] will be in the // LIS. If it is in the LIS already we do nothing - if (val > arr[i]) - { + if (val > arr[i]) { // else we remove the bigger element and add a smaller element // (which is arr[i]) and continue; active.erase(get); @@ -32,15 +27,13 @@ int LIS(int arr[], int n) } return active.size(); // size of the LIS. } -int main(int argc, char const* argv[]) -{ +int main(int argc, char const* argv[]) { int n; cout << "Enter size of array: "; cin >> n; int a[n]; cout << "Enter array elements: "; - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { cin >> a[i]; } cout << LIS(a, n) << endl; diff --git a/dynamic_programming/matrix_chain_multiplication.cpp b/dynamic_programming/matrix_chain_multiplication.cpp index 378edcc7f2d..7d6647c5257 100644 --- a/dynamic_programming/matrix_chain_multiplication.cpp +++ b/dynamic_programming/matrix_chain_multiplication.cpp @@ -9,8 +9,7 @@ int dp[MAX][MAX]; // Function to find the most efficient way to multiply the given sequence of // matrices -int MatrixChainMultiplication(int dim[], int i, int j) -{ +int MatrixChainMultiplication(int dim[], int i, int j) { // base case: one matrix if (j <= i + 1) return 0; @@ -21,13 +20,11 @@ int MatrixChainMultiplication(int dim[], int i, int j) // if dp[i][j] is not calculated (calculate it!!) - if (dp[i][j] == 0) - { + if (dp[i][j] == 0) { // take the minimum over each possible position at which the // sequence of matrices can be split - for (int k = i + 1; k <= j - 1; k++) - { + for (int k = i + 1; k <= j - 1; k++) { // recur for M[i+1]..M[k] to get a i x k matrix int cost = MatrixChainMultiplication(dim, i, k); @@ -48,8 +45,7 @@ int MatrixChainMultiplication(int dim[], int i, int j) } // main function -int main() -{ +int main() { // Matrix i has Dimensions dim[i-1] & dim[i] for i=1..n // input is 10 x 30 matrix, 30 x 5 matrix, 5 x 60 matrix int dim[] = {10, 30, 5, 60}; diff --git a/dynamic_programming/searching_of_element_in_dynamic_array.cpp b/dynamic_programming/searching_of_element_in_dynamic_array.cpp index 3dea46bf4b6..7792a514908 100644 --- a/dynamic_programming/searching_of_element_in_dynamic_array.cpp +++ b/dynamic_programming/searching_of_element_in_dynamic_array.cpp @@ -35,8 +35,7 @@ // this is main fuction // *** -int main() -{ +int main() { int64_t r, mr = 0, x, q, i, z; std::cout << "Enter Number of array you want to Store :"; std::cin >> x; @@ -50,8 +49,7 @@ int main() int** ar = new int*[x](); // this for loop is use for entering different variable size array // *** - for (r = 0; r < x; r++) - { + for (r = 0; r < x; r++) { std::cout << "Enter number of element in " << r + 1 << " rows :"; std::cin >> mr; // creating a 1D array @@ -59,8 +57,7 @@ int main() std::cout << "Enter the element of Array "; // this for loop is use for storing values in array // *** - for (i = 0; i < mr; i++) - { + for (i = 0; i < mr; i++) { // entering the value of rows in array in Horizontal std::cin >> ac[i]; } @@ -69,8 +66,7 @@ int main() } // this for loop is use for display result of querry // *** - for (z = 0; z < q; z++) - { + for (z = 0; z < q; z++) { int64_t r1 = 0, q1 = 0; std::cout << "enter the number of row which element you want to find :"; std::cin >> r1; diff --git a/dynamic_programming/tree_height.cpp b/dynamic_programming/tree_height.cpp index 1530dfe7e4f..480b951c8ea 100644 --- a/dynamic_programming/tree_height.cpp +++ b/dynamic_programming/tree_height.cpp @@ -29,14 +29,11 @@ std::vector adj[MAX]; std::vector visited; std::vector dp; -void depth_first_search(int u) -{ +void depth_first_search(int u) { visited[u] = true; int child_height = 1; - for (int v : adj[u]) - { - if (!visited[v]) - { + for (int v : adj[u]) { + if (!visited[v]) { depth_first_search(v); // select maximum sub-tree height from all children. @@ -47,8 +44,7 @@ void depth_first_search(int u) dp[u] = child_height; } -int main() -{ +int main() { // number of nodes int number_of_nodes; std::cout << "Enter number of nodes of the tree : " << std::endl; @@ -58,8 +54,7 @@ int main() int u, v; // Tree contains exactly n-1 edges where n denotes the number of nodes. std::cout << "Enter edges of the tree : " << std::endl; - for (int i = 0; i < number_of_nodes - 1; i++) - { + for (int i = 0; i < number_of_nodes - 1; i++) { std::cin >> u >> v; // undirected tree u -> v and v -> u. adj[u].push_back(v); diff --git a/graph/bfs.cpp b/graph/bfs.cpp index f5d372134cd..3acee8f806f 100644 --- a/graph/bfs.cpp +++ b/graph/bfs.cpp @@ -1,7 +1,6 @@ #include using namespace std; -class graph -{ +class graph { int v; list *adj; @@ -11,56 +10,46 @@ class graph void printgraph(); void bfs(int s); }; -graph::graph(int v) -{ +graph::graph(int v) { this->v = v; this->adj = new list[v]; } -void graph::addedge(int src, int dest) -{ +void graph::addedge(int src, int dest) { src--; dest--; adj[src].push_back(dest); // adj[dest].push_back(src); } -void graph::printgraph() -{ - for (int i = 0; i < this->v; i++) - { +void graph::printgraph() { + for (int i = 0; i < this->v; i++) { cout << "Adjacency list of vertex " << i + 1 << " is \n"; list::iterator it; - for (it = adj[i].begin(); it != adj[i].end(); ++it) - { + for (it = adj[i].begin(); it != adj[i].end(); ++it) { cout << *it + 1 << " "; } cout << endl; } } -void graph::bfs(int s) -{ +void graph::bfs(int s) { bool *visited = new bool[this->v + 1]; memset(visited, false, sizeof(bool) * (this->v + 1)); visited[s] = true; list q; q.push_back(s); list::iterator it; - while (!q.empty()) - { + while (!q.empty()) { int u = q.front(); cout << u << " "; q.pop_front(); - for (it = adj[u].begin(); it != adj[u].end(); ++it) - { - if (visited[*it] == false) - { + for (it = adj[u].begin(); it != adj[u].end(); ++it) { + if (visited[*it] == false) { visited[*it] = true; q.push_back(*it); } } } } -int main() -{ +int main() { graph g(4); g.addedge(1, 2); g.addedge(2, 3); diff --git a/graph/bridge_finding_with_tarjan_algorithm.cpp b/graph/bridge_finding_with_tarjan_algorithm.cpp index a283a7c916e..eec176af58f 100644 --- a/graph/bridge_finding_with_tarjan_algorithm.cpp +++ b/graph/bridge_finding_with_tarjan_algorithm.cpp @@ -10,28 +10,22 @@ using std::cout; using std::min; using std::vector; -class Solution -{ +class Solution { vector> graph; vector in_time, out_time; int timer; vector> bridge; vector visited; - void dfs(int current_node, int parent) - { + void dfs(int current_node, int parent) { visited.at(current_node) = true; in_time[current_node] = out_time[current_node] = timer++; - for (auto& itr : graph[current_node]) - { - if (itr == parent) - { + for (auto& itr : graph[current_node]) { + if (itr == parent) { continue; } - if (!visited[itr]) - { + if (!visited[itr]) { dfs(itr, current_node); - if (out_time[itr] > in_time[current_node]) - { + if (out_time[itr] > in_time[current_node]) { bridge.push_back({itr, current_node}); } } @@ -41,15 +35,13 @@ class Solution public: vector> search_bridges(int n, - const vector>& connections) - { + const vector>& connections) { timer = 0; graph.resize(n); in_time.assign(n, 0); visited.assign(n, false); out_time.assign(n, 0); - for (auto& itr : connections) - { + for (auto& itr : connections) { graph.at(itr[0]).push_back(itr[1]); graph.at(itr[1]).push_back(itr[0]); } @@ -57,8 +49,7 @@ class Solution return bridge; } }; -int main(void) -{ +int main(void) { Solution s1; int number_of_node = 5; vector> node; @@ -81,8 +72,7 @@ int main(void) */ vector> bridges = s1.search_bridges(number_of_node, node); cout << bridges.size() << " bridges found!\n"; - for (auto& itr : bridges) - { + for (auto& itr : bridges) { cout << itr[0] << " --> " << itr[1] << '\n'; } return 0; diff --git a/graph/connected_components.cpp b/graph/connected_components.cpp index f78ef011e90..0bfb8bbdb98 100644 --- a/graph/connected_components.cpp +++ b/graph/connected_components.cpp @@ -3,8 +3,7 @@ using std::vector; -class graph -{ +class graph { private: vector> adj; int connected_components; @@ -14,48 +13,39 @@ class graph public: explicit graph(int n) : adj(n, vector()) { connected_components = 0; } void addEdge(int, int); - int getConnectedComponents() - { + int getConnectedComponents() { depth_first_search(); return connected_components; } }; -void graph::addEdge(int u, int v) -{ +void graph::addEdge(int u, int v) { adj[u - 1].push_back(v - 1); adj[v - 1].push_back(u - 1); } -void graph::depth_first_search() -{ +void graph::depth_first_search() { int n = adj.size(); vector visited(n, false); - for (int i = 0; i < n; i++) - { - if (!visited[i]) - { + for (int i = 0; i < n; i++) { + if (!visited[i]) { explore(i, visited); connected_components++; } } } -void graph::explore(int u, vector &visited) -{ +void graph::explore(int u, vector &visited) { visited[u] = true; - for (auto v : adj[u]) - { - if (!visited[v]) - { + for (auto v : adj[u]) { + if (!visited[v]) { explore(v, visited); } } } -int main() -{ +int main() { graph g(4); g.addEdge(1, 2); g.addEdge(3, 2); diff --git a/graph/connected_components_with_dsu.cpp b/graph/connected_components_with_dsu.cpp index 07fda5d2740..aa03bef8f11 100644 --- a/graph/connected_components_with_dsu.cpp +++ b/graph/connected_components_with_dsu.cpp @@ -5,28 +5,23 @@ int N; // denotes number of nodes; std::vector parent; std::vector siz; -void make_set() -{ // function the initialize every node as it's own parent - for (int i = 1; i <= N; i++) - { +void make_set() { // function the initialize every node as it's own parent + for (int i = 1; i <= N; i++) { parent[i] = i; siz[i] = 1; } } // To find the component where following node belongs to -int find_set(int v) -{ +int find_set(int v) { if (v == parent[v]) return v; return parent[v] = find_set(parent[v]); } -void union_sets(int a, int b) -{ // To join 2 components to belong to one +void union_sets(int a, int b) { // To join 2 components to belong to one a = find_set(a); b = find_set(b); - if (a != b) - { + if (a != b) { if (siz[a] < siz[b]) std::swap(a, b); parent[b] = a; @@ -34,8 +29,7 @@ void union_sets(int a, int b) } } -int no_of_connected_components() -{ // To find total no of connected components +int no_of_connected_components() { // To find total no of connected components std::set temp; // temp set to count number of connected components for (int i = 1; i <= N; i++) temp.insert(find_set(i)); return temp.size(); @@ -43,16 +37,14 @@ int no_of_connected_components() // All critical/corner cases have been taken care of. // Input your required values: (not hardcoded) -int main() -{ +int main() { std::cin >> N; parent.resize(N + 1); siz.resize(N + 1); make_set(); int edges; std::cin >> edges; // no of edges in the graph - while (edges--) - { + while (edges--) { int node_a, node_b; std::cin >> node_a >> node_b; union_sets(node_a, node_b); diff --git a/graph/dfs.cpp b/graph/dfs.cpp index 7c7ec776135..2d38c872507 100644 --- a/graph/dfs.cpp +++ b/graph/dfs.cpp @@ -1,28 +1,23 @@ #include using namespace std; int v = 4; -void DFSUtil_(int graph[4][4], bool visited[], int s) -{ +void DFSUtil_(int graph[4][4], bool visited[], int s) { visited[s] = true; cout << s << " "; - for (int i = 0; i < v; i++) - { - if (graph[s][i] == 1 && visited[i] == false) - { + for (int i = 0; i < v; i++) { + if (graph[s][i] == 1 && visited[i] == false) { DFSUtil_(graph, visited, i); } } } -void DFS_(int graph[4][4], int s) -{ +void DFS_(int graph[4][4], int s) { bool visited[v]; memset(visited, 0, sizeof(visited)); DFSUtil_(graph, visited, s); } -int main() -{ +int main() { int graph[4][4] = {{0, 1, 1, 0}, {0, 0, 1, 0}, {1, 0, 0, 1}, {0, 0, 0, 1}}; cout << "DFS: "; DFS_(graph, 2); diff --git a/graph/dfs_with_stack.cpp b/graph/dfs_with_stack.cpp index cc67c75098e..193f3f291e5 100644 --- a/graph/dfs_with_stack.cpp +++ b/graph/dfs_with_stack.cpp @@ -11,8 +11,7 @@ using namespace std; int checked[999] = {WHITE}; -void dfs(const list lista[], int start) -{ +void dfs(const list lista[], int start) { stack stack; int checked[999] = {WHITE}; @@ -20,33 +19,28 @@ void dfs(const list lista[], int start) stack.push(start); checked[start] = GREY; - while (!stack.empty()) - { + while (!stack.empty()) { int act = stack.top(); stack.pop(); - if (checked[act] == GREY) - { + if (checked[act] == GREY) { cout << act << ' '; - for (auto it = lista[act].begin(); it != lista[act].end(); ++it) - { + for (auto it = lista[act].begin(); it != lista[act].end(); ++it) { stack.push(*it); if (checked[*it] != BLACK) checked[*it] = GREY; } - checked[act] = BLACK; //nodo controllato + checked[act] = BLACK; // nodo controllato } } } -int main() -{ +int main() { int u, w; int n; cin >> n; list lista[INF]; - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { cin >> u >> w; lista[u].push_back(w); } diff --git a/graph/dijkstra.cpp b/graph/dijkstra.cpp index f2551093516..650f0cd51cb 100644 --- a/graph/dijkstra.cpp +++ b/graph/dijkstra.cpp @@ -6,8 +6,7 @@ using namespace std; #define INF 10000010 vector> graph[5 * 100001]; int dis[5 * 100001]; -int dij(vector> *v, int s, int *dis) -{ +int dij(vector> *v, int s, int *dis) { priority_queue, vector>, greater>> pq; @@ -15,28 +14,23 @@ int dij(vector> *v, int s, int *dis) pq.push(make_pair(0, s)); dis[s] = 0; int u; - while (!pq.empty()) - { + while (!pq.empty()) { u = (pq.top()).second; pq.pop(); for (vector>::iterator it = v[u].begin(); - it != v[u].end(); it++) - { - if (dis[u] + it->first < dis[it->second]) - { + it != v[u].end(); it++) { + if (dis[u] + it->first < dis[it->second]) { dis[it->second] = dis[u] + it->first; pq.push(make_pair(dis[it->second], it->second)); } } } } -int main() -{ +int main() { int m, n, l, x, y, s; // n--> number of nodes , m --> number of edges cin >> n >> m; - for (int i = 0; i < m; i++) - { + for (int i = 0; i < m; i++) { // input edges. scanf("%d%d%d", &x, &y, &l); graph[x].push_back(make_pair(l, y)); diff --git a/graph/kosaraju.cpp b/graph/kosaraju.cpp index 0efa291bc67..00c9d7ca022 100644 --- a/graph/kosaraju.cpp +++ b/graph/kosaraju.cpp @@ -13,10 +13,8 @@ using namespace std; * @param V : vertices * @return void **/ -void print(vector a[], int V) -{ - for (int i = 0; i < V; i++) - { +void print(vector a[], int V) { + for (int i = 0; i < V; i++) { if (!a[i].empty()) cout << "i=" << i << "-->"; for (int j = 0; j < a[i].size(); j++) cout << a[i][j] << " "; @@ -33,11 +31,9 @@ void print(vector a[], int V) * @param adj[] : array of vectors to represent graph * @return void **/ -void push_vertex(int v, stack &st, bool vis[], vector adj[]) -{ +void push_vertex(int v, stack &st, bool vis[], vector adj[]) { vis[v] = true; - for (auto i = adj[v].begin(); i != adj[v].end(); i++) - { + for (auto i = adj[v].begin(); i != adj[v].end(); i++) { if (vis[*i] == false) push_vertex(*i, st, vis, adj); } @@ -51,12 +47,10 @@ void push_vertex(int v, stack &st, bool vis[], vector adj[]) * @param grev[] : graph with reversed edges * @return void **/ -void dfs(int v, bool vis[], vector grev[]) -{ +void dfs(int v, bool vis[], vector grev[]) { vis[v] = true; // cout<0)) i.e. it returns the count of (number of) strongly connected components (SCCs) in the graph. (variable 'count_scc' within function) **/ -int kosaraju(int V, vector adj[]) -{ +int kosaraju(int V, vector adj[]) { bool vis[V] = {}; stack st; - for (int v = 0; v < V; v++) - { + for (int v = 0; v < V; v++) { if (vis[v] == false) push_vertex(v, st, vis, adj); } // making new graph (grev) with reverse edges as in adj[]: vector grev[V]; - for (int i = 0; i < V + 1; i++) - { - for (auto j = adj[i].begin(); j != adj[i].end(); j++) - { + for (int i = 0; i < V + 1; i++) { + for (auto j = adj[i].begin(); j != adj[i].end(); j++) { grev[*j].push_back(i); } } @@ -95,12 +85,10 @@ int kosaraju(int V, vector adj[]) // reinitialise visited to 0 for (int i = 0; i < V; i++) vis[i] = false; int count_scc = 0; - while (!st.empty()) - { + while (!st.empty()) { int t = st.top(); st.pop(); - if (vis[t] == false) - { + if (vis[t] == false) { dfs(t, vis, grev); count_scc++; } @@ -112,12 +100,10 @@ int kosaraju(int V, vector adj[]) // All critical/corner cases have been taken care of. // Input your required values: (not hardcoded) -int main() -{ +int main() { int t; cin >> t; - while (t--) - { + while (t--) { int a, b; // a->number of nodes, b->directed edges. cin >> a >> b; int m, n; diff --git a/graph/kruskal.cpp b/graph/kruskal.cpp index 6bffd5cd92d..b7b83066879 100644 --- a/graph/kruskal.cpp +++ b/graph/kruskal.cpp @@ -24,47 +24,39 @@ typedef long long ll; cin.tie(NULL); \ cout.tie(NULL); using namespace std; -void in(int &x) -{ +void in(int &x) { register int c = gc(); x = 0; int neg = 0; for (; ((c < 48 || c > 57) && c != '-'); c = gc()) ; - if (c == '-') - { + if (c == '-') { neg = 1; c = gc(); } - for (; c > 47 && c < 58; c = gc()) - { + for (; c > 47 && c < 58; c = gc()) { x = (x << 1) + (x << 3) + c - 48; } if (neg) x = -x; } -void out(int n) -{ +void out(int n) { int N = n, rev, count = 0; rev = N; - if (N == 0) - { + if (N == 0) { pc('0'); return; } - while ((rev % 10) == 0) - { + while ((rev % 10) == 0) { count++; rev /= 10; } rev = 0; - while (N != 0) - { + while (N != 0) { rev = (rev << 3) + (rev << 1) + N % 10; N /= 10; } - while (rev != 0) - { + while (rev != 0) { pc(rev % 10 + '0'); rev /= 10; } @@ -72,53 +64,43 @@ void out(int n) } ll parent[mx], arr[mx], node, edge; vector>> v; -void initial() -{ +void initial() { int i; rep(i, node + edge) parent[i] = i; } -int root(int i) -{ - while (parent[i] != i) - { +int root(int i) { + while (parent[i] != i) { parent[i] = parent[parent[i]]; i = parent[i]; } return i; } -void join(int x, int y) -{ +void join(int x, int y) { int root_x = root(x); // Disjoint set union by rank int root_y = root(y); parent[root_x] = root_y; } -ll kruskal() -{ +ll kruskal() { ll mincost = 0, i, x, y; - rep(i, edge) - { + rep(i, edge) { x = v[i].second.first; y = v[i].second.second; - if (root(x) != root(y)) - { + if (root(x) != root(y)) { mincost += v[i].first; join(x, y); } } return mincost; } -int main() -{ +int main() { fast; - while (1) - { + while (1) { int i, j, from, to, cost, totalcost = 0; cin >> node >> edge; // Enter the nodes and edges if (node == 0 && edge == 0) break; // Enter 0 0 to break out initial(); // Initialise the parent array - rep(i, edge) - { + rep(i, edge) { cin >> from >> to >> cost; v.pb(mp(cost, mp(from, to))); totalcost += cost; diff --git a/graph/lca.cpp b/graph/lca.cpp index 743fb31edba..c05cf7b9b92 100644 --- a/graph/lca.cpp +++ b/graph/lca.cpp @@ -7,19 +7,16 @@ using namespace std; // Resource : https://cp-algorithms.com/graph/lca_binary_lifting.html const int N = 1005; const int LG = log2(N) + 1; -struct lca -{ +struct lca { int n; vector adj[N]; // Graph int up[LG][N]; // build this table int level[N]; // get the levels of all of them - lca(int n_) : n(n_) - { + lca(int n_) : n(n_) { memset(up, -1, sizeof(up)); memset(level, 0, sizeof(level)); - for (int i = 0; i < n - 1; ++i) - { + for (int i = 0; i < n - 1; ++i) { int a, b; cin >> a >> b; a--; @@ -31,77 +28,59 @@ struct lca dfs(0, -1); build(); } - void verify() - { - for (int i = 0; i < n; ++i) - { + void verify() { + for (int i = 0; i < n; ++i) { cout << i << " : level: " << level[i] << endl; } cout << endl; - for (int i = 0; i < LG; ++i) - { + for (int i = 0; i < LG; ++i) { cout << "Power:" << i << ": "; - for (int j = 0; j < n; ++j) - { + for (int j = 0; j < n; ++j) { cout << up[i][j] << " "; } cout << endl; } } - void build() - { - for (int i = 1; i < LG; ++i) - { - for (int j = 0; j < n; ++j) - { - if (up[i - 1][j] != -1) - { + void build() { + for (int i = 1; i < LG; ++i) { + for (int j = 0; j < n; ++j) { + if (up[i - 1][j] != -1) { up[i][j] = up[i - 1][up[i - 1][j]]; } } } } - void dfs(int node, int par) - { + void dfs(int node, int par) { up[0][node] = par; - for (auto i : adj[node]) - { - if (i != par) - { + for (auto i : adj[node]) { + if (i != par) { level[i] = level[node] + 1; dfs(i, node); } } } - int query(int u, int v) - { + int query(int u, int v) { u--; v--; - if (level[v] > level[u]) - { + if (level[v] > level[u]) { swap(u, v); } // u is at the bottom. int dist = level[u] - level[v]; // Go up this much distance - for (int i = LG - 1; i >= 0; --i) - { - if (dist & (1 << i)) - { + for (int i = LG - 1; i >= 0; --i) { + if (dist & (1 << i)) { u = up[i][u]; } } - if (u == v) - { + if (u == v) { return u; } assert(level[u] == level[v]); - for (int i = LG - 1; i >= 0; --i) - { - if (up[i][u] != up[i][v]) - { + for (int i = LG - 1; i >= 0; --i) { + if (up[i][u] != up[i][v]) { u = up[i][u]; v = up[i][v]; } @@ -111,8 +90,7 @@ struct lca } }; -int main() -{ +int main() { int n; // number of nodes in the tree. lca l(n); // will take the input in the format given // n-1 edges of the form diff --git a/graph/max_flow_with_ford_fulkerson_and_edmond_karp_algo.cpp b/graph/max_flow_with_ford_fulkerson_and_edmond_karp_algo.cpp index f02a48e01b1..cbd6bc15c60 100644 --- a/graph/max_flow_with_ford_fulkerson_and_edmond_karp_algo.cpp +++ b/graph/max_flow_with_ford_fulkerson_and_edmond_karp_algo.cpp @@ -15,8 +15,7 @@ #include // std::max capacity of node in graph const int MAXN = 505; -class Graph -{ +class Graph { int residual_capacity[MAXN][MAXN]; int capacity[MAXN][MAXN]; // used while checking the flow of edge int total_nodes; @@ -25,26 +24,21 @@ class Graph std::vector > edge_participated; std::bitset visited; int max_flow = 0; - bool bfs(int source, int sink) - { // to find the augmented - path + bool bfs(int source, int sink) { // to find the augmented - path memset(parent, -1, sizeof(parent)); visited.reset(); std::queue q; q.push(source); bool is_path_found = false; - while (q.empty() == false && is_path_found == false) - { + while (q.empty() == false && is_path_found == false) { int current_node = q.front(); visited.set(current_node); q.pop(); - for (int i = 0; i < total_nodes; ++i) - { - if (residual_capacity[current_node][i] > 0 && !visited[i]) - { + for (int i = 0; i < total_nodes; ++i) { + if (residual_capacity[current_node][i] > 0 && !visited[i]) { visited.set(i); parent[i] = current_node; - if (i == sink) - { + if (i == sink) { return true; } q.push(i); @@ -56,32 +50,26 @@ class Graph public: Graph() { memset(residual_capacity, 0, sizeof(residual_capacity)); } - void set_graph(void) - { + void set_graph(void) { std::cin >> total_nodes >> total_edges >> source >> sink; - for (int start, destination, capacity_, i = 0; i < total_edges; ++i) - { + for (int start, destination, capacity_, i = 0; i < total_edges; ++i) { std::cin >> start >> destination >> capacity_; residual_capacity[start][destination] = capacity_; capacity[start][destination] = capacity_; } } - void ford_fulkerson(void) - { - while (bfs(source, sink)) - { + void ford_fulkerson(void) { + while (bfs(source, sink)) { int current_node = sink; int flow = std::numeric_limits::max(); - while (current_node != source) - { + while (current_node != source) { int parent_ = parent[current_node]; flow = std::min(flow, residual_capacity[parent_][current_node]); current_node = parent_; } current_node = sink; max_flow += flow; - while (current_node != source) - { + while (current_node != source) { int parent_ = parent[current_node]; residual_capacity[parent_][current_node] -= flow; residual_capacity[current_node][parent_] += flow; @@ -89,14 +77,11 @@ class Graph } } } - void print_flow_info(void) - { - for (int i = 0; i < total_nodes; ++i) - { - for (int j = 0; j < total_nodes; ++j) - { - if (capacity[i][j] && residual_capacity[i][j] < capacity[i][j]) - { + void print_flow_info(void) { + for (int i = 0; i < total_nodes; ++i) { + for (int j = 0; j < total_nodes; ++j) { + if (capacity[i][j] && + residual_capacity[i][j] < capacity[i][j]) { edge_participated.push_back(std::make_tuple( i, j, capacity[i][j] - residual_capacity[i][j])); } @@ -106,8 +91,7 @@ class Graph << "\nEdge present in flow: " << edge_participated.size() << '\n'; std::cout << "\nSource\tDestination\tCapacity\total_nodes"; - for (auto& edge_data : edge_participated) - { + for (auto& edge_data : edge_participated) { int source, destination, capacity_; std::tie(source, destination, capacity_) = edge_data; std::cout << source << "\t" << destination << "\t\t" << capacity_ @@ -115,8 +99,7 @@ class Graph } } }; -int main(void) -{ +int main(void) { /* Input Graph: (for testing ) 4 5 0 3 diff --git a/graph/prim.cpp b/graph/prim.cpp index 8332bdb367d..5cc70bd395b 100644 --- a/graph/prim.cpp +++ b/graph/prim.cpp @@ -9,8 +9,7 @@ typedef std::pair PII; bool marked[MAX]; std::vector adj[MAX]; -int prim(int x) -{ +int prim(int x) { // priority queue to maintain edges with respect to weights std::priority_queue, std::greater > Q; int y; @@ -18,8 +17,7 @@ int prim(int x) PII p; Q.push(std::make_pair(0, x)); - while (!Q.empty()) - { + while (!Q.empty()) { // Select the edge with minimum weight p = Q.top(); Q.pop(); @@ -29,8 +27,7 @@ int prim(int x) continue; minimumCost += p.first; marked[x] = true; - for (int i = 0; i < adj[x].size(); ++i) - { + for (int i = 0; i < adj[x].size(); ++i) { y = adj[x][i].second; if (marked[y] == false) Q.push(adj[x][i]); @@ -39,8 +36,7 @@ int prim(int x) return minimumCost; } -int main() -{ +int main() { int nodes, edges, x, y; int weight, minimumCost; @@ -49,8 +45,7 @@ int main() return 0; // Edges with their nodes & weight - for (int i = 0; i < edges; ++i) - { + for (int i = 0; i < edges; ++i) { std::cin >> x >> y >> weight; adj[x].push_back(std::make_pair(weight, y)); adj[y].push_back(std::make_pair(weight, x)); diff --git a/graph/topological_sort.cpp b/graph/topological_sort.cpp index d863c69933f..9e6c8917b59 100644 --- a/graph/topological_sort.cpp +++ b/graph/topological_sort.cpp @@ -8,44 +8,37 @@ vector> G; vector visited; vector ans; -void dfs(int v) -{ +void dfs(int v) { visited[v] = true; - for (int u : G[v]) - { + for (int u : G[v]) { if (!visited[u]) dfs(u); } ans.push_back(v); } -void topological_sort() -{ +void topological_sort() { visited.assign(n, false); ans.clear(); - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { if (!visited[i]) dfs(i); } reverse(ans.begin(), ans.end()); } -int main() -{ +int main() { cout << "Enter the number of vertices and the number of directed edges\n"; cin >> n >> m; int x, y; G.resize(n, vector()); - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { cin >> x >> y; x--, y--; // to convert 1-indexed to 0-indexed G[x].push_back(y); } topological_sort(); cout << "Topological Order : \n"; - for (int v : ans) - { + for (int v : ans) { cout << v + 1 << ' '; // converting zero based indexing back to one based. } diff --git a/graph/topological_sort_by_kahns_algo.cpp b/graph/topological_sort_by_kahns_algo.cpp index b56ae565140..57ee01b237d 100644 --- a/graph/topological_sort_by_kahns_algo.cpp +++ b/graph/topological_sort_by_kahns_algo.cpp @@ -6,8 +6,7 @@ int *topoSortKahn(int N, std::vector adj[]); -int main() -{ +int main() { int nodes, edges; std::cin >> edges >> nodes; if (edges == 0 || nodes == 0) @@ -20,36 +19,29 @@ int main() // 6 6 // 5 0 5 2 2 3 4 0 4 1 1 3 - for (int i = 0; i < edges; i++) - { + for (int i = 0; i < edges; i++) { std::cin >> u >> v; graph[u].push_back(v); } int *topo = topoSortKahn(nodes, graph); // topologically sorted nodes - for (int i = 0; i < nodes; i++) - { + for (int i = 0; i < nodes; i++) { std::cout << topo[i] << " "; } } -int *topoSortKahn(int V, std::vector adj[]) -{ +int *topoSortKahn(int V, std::vector adj[]) { std::vector vis(V + 1, false); std::vector deg(V + 1, 0); - for (int i = 0; i < V; i++) - { - for (int j = 0; j < adj[i].size(); j++) - { + for (int i = 0; i < V; i++) { + for (int j = 0; j < adj[i].size(); j++) { deg[adj[i][j]]++; } } std::queue q; - for (int i = 0; i < V; i++) - { - if (deg[i] == 0) - { + for (int i = 0; i < V; i++) { + if (deg[i] == 0) { q.push(i); vis[i] = true; } @@ -57,19 +49,15 @@ int *topoSortKahn(int V, std::vector adj[]) int *arr = new int[V + 1]; memset(arr, 0, V + 1); int count = 0; - while (!q.empty()) - { + while (!q.empty()) { int cur = q.front(); q.pop(); arr[count] = cur; count++; - for (int i = 0; i < adj[cur].size(); i++) - { - if (!vis[adj[cur][i]]) - { + for (int i = 0; i < adj[cur].size(); i++) { + if (!vis[adj[cur][i]]) { deg[adj[cur][i]]--; - if (deg[adj[cur][i]] == 0) - { + if (deg[adj[cur][i]] == 0) { q.push(adj[cur][i]); vis[adj[cur][i]] = true; } diff --git a/greedy_algorithms/dijkstra.cpp b/greedy_algorithms/dijkstra.cpp index b87b4ab109c..e4450379c5d 100644 --- a/greedy_algorithms/dijkstra.cpp +++ b/greedy_algorithms/dijkstra.cpp @@ -4,27 +4,22 @@ using namespace std; // Wrapper class for storing a graph -class Graph -{ +class Graph { public: int vertexNum; int **edges; // Constructs a graph with V vertices and E edges - Graph(const int V) - { + Graph(const int V) { // initializes the array edges. this->edges = new int *[V]; - for (int i = 0; i < V; i++) - { + for (int i = 0; i < V; i++) { edges[i] = new int[V]; } // fills the array with zeros. - for (int i = 0; i < V; i++) - { - for (int j = 0; j < V; j++) - { + for (int i = 0; i < V; i++) { + for (int j = 0; j < V; j++) { edges[i][j] = 0; } } @@ -33,19 +28,15 @@ class Graph } // Adds the given edge to the graph - void addEdge(int src, int dst, int weight) - { + void addEdge(int src, int dst, int weight) { this->edges[src][dst] = weight; } }; // Utility function to find minimum distance vertex in mdist -int minDistance(int mdist[], bool vset[], int V) -{ +int minDistance(int mdist[], bool vset[], int V) { int minVal = INT_MAX, minInd = 0; - for (int i = 0; i < V; i++) - { - if (!vset[i] && (mdist[i] < minVal)) - { + for (int i = 0; i < V; i++) { + if (!vset[i] && (mdist[i] < minVal)) { minVal = mdist[i]; minInd = i; } @@ -55,11 +46,9 @@ int minDistance(int mdist[], bool vset[], int V) } // Utility function to print distances -void print(int dist[], int V) -{ +void print(int dist[], int V) { cout << "\nVertex Distance" << endl; - for (int i = 0; i < V; i++) - { + for (int i = 0; i < V; i++) { if (dist[i] < INT_MAX) cout << i << "\t" << dist[i] << endl; else @@ -70,16 +59,14 @@ void print(int dist[], int V) // The main function that finds the shortest path from given source // to all other vertices using Dijkstra's Algorithm.It doesn't work on negative // weights -void Dijkstra(Graph graph, int src) -{ +void Dijkstra(Graph graph, int src) { int V = graph.vertexNum; int mdist[V]; // Stores updated distances to vertex bool vset[V]; // vset[i] is true if the vertex i included // in the shortest path tree // Initialise mdist and vset. Set distance of source as zero - for (int i = 0; i < V; i++) - { + for (int i = 0; i < V; i++) { mdist[i] = INT_MAX; vset[i] = false; } @@ -87,17 +74,14 @@ void Dijkstra(Graph graph, int src) mdist[src] = 0; // iterate to find shortest path - for (int count = 0; count < V - 1; count++) - { + for (int count = 0; count < V - 1; count++) { int u = minDistance(mdist, vset, V); vset[u] = true; - for (int v = 0; v < V; v++) - { + for (int v = 0; v < V; v++) { if (!vset[v] && graph.edges[u][v] && - mdist[u] + graph.edges[u][v] < mdist[v]) - { + mdist[u] + graph.edges[u][v] < mdist[v]) { mdist[v] = mdist[u] + graph.edges[u][v]; } } @@ -107,8 +91,7 @@ void Dijkstra(Graph graph, int src) } // Driver Function -int main() -{ +int main() { int V, E, gsrc; int src, dst, weight; cout << "Enter number of vertices: "; @@ -116,8 +99,7 @@ int main() cout << "Enter number of edges: "; cin >> E; Graph G(V); - for (int i = 0; i < E; i++) - { + for (int i = 0; i < E; i++) { cout << "\nEdge " << i + 1 << "\nEnter source: "; cin >> src; cout << "Enter destination: "; @@ -126,12 +108,9 @@ int main() cin >> weight; // makes sure source and destionation are in the proper bounds. - if (src >= 0 && src < V && dst >= 0 && dst < V) - { + if (src >= 0 && src < V && dst >= 0 && dst < V) { G.addEdge(src, dst, weight); - } - else - { + } else { cout << "source and/or destination out of bounds" << endl; i--; continue; diff --git a/greedy_algorithms/huffman.cpp b/greedy_algorithms/huffman.cpp index bf3d9ff9a69..21c8295f3dd 100644 --- a/greedy_algorithms/huffman.cpp +++ b/greedy_algorithms/huffman.cpp @@ -4,8 +4,7 @@ using namespace std; // A Huffman tree node -struct MinHeapNode -{ +struct MinHeapNode { // One of the input characters char data; @@ -26,8 +25,7 @@ struct MinHeapNode // For comparison of // two heap nodes (needed in min heap) -struct compare -{ +struct compare { bool operator()(MinHeapNode* l, MinHeapNode* r) { @@ -37,8 +35,7 @@ struct compare // Prints huffman codes from // the root of Huffman Tree. -void printCodes(struct MinHeapNode* root, string str) -{ +void printCodes(struct MinHeapNode* root, string str) { if (!root) return; @@ -51,8 +48,7 @@ void printCodes(struct MinHeapNode* root, string str) // The main function that builds a Huffman Tree and // print codes by traversing the built Huffman Tree -void HuffmanCodes(char data[], int freq[], int size) -{ +void HuffmanCodes(char data[], int freq[], int size) { struct MinHeapNode *left, *right, *top; // Create a min heap & inserts all characters of data[] @@ -62,8 +58,7 @@ void HuffmanCodes(char data[], int freq[], int size) minHeap.push(new MinHeapNode(data[i], freq[i])); // Iterate while size of heap doesn't become 1 - while (minHeap.size() != 1) - { + while (minHeap.size() != 1) { // Extract the two minimum // freq items from min heap left = minHeap.top(); @@ -93,8 +88,7 @@ void HuffmanCodes(char data[], int freq[], int size) } // Driver program to test above functions -int main() -{ +int main() { char arr[] = {'a', 'b', 'c', 'd', 'e', 'f'}; int freq[] = {5, 9, 12, 13, 16, 45}; diff --git a/greedy_algorithms/knapsack.cpp b/greedy_algorithms/knapsack.cpp index 81fd879de02..74be4fee0e0 100644 --- a/greedy_algorithms/knapsack.cpp +++ b/greedy_algorithms/knapsack.cpp @@ -1,25 +1,21 @@ #include using namespace std; -struct Item -{ +struct Item { int weight; int profit; }; float profitPerUnit(Item x) { return (float)x.profit / (float)x.weight; } -int partition(Item arr[], int low, int high) -{ +int partition(Item arr[], int low, int high) { Item pivot = arr[high]; // pivot int i = (low - 1); // Index of smaller element - for (int j = low; j < high; j++) - { + for (int j = low; j < high; j++) { // If current element is smaller than or // equal to pivot - if (profitPerUnit(arr[j]) <= profitPerUnit(pivot)) - { + if (profitPerUnit(arr[j]) <= profitPerUnit(pivot)) { i++; // increment index of smaller element Item temp = arr[i]; arr[i] = arr[j]; @@ -32,10 +28,8 @@ int partition(Item arr[], int low, int high) return (i + 1); } -void quickSort(Item arr[], int low, int high) -{ - if (low < high) - { +void quickSort(Item arr[], int low, int high) { + if (low < high) { int p = partition(arr, low, high); quickSort(arr, low, p - 1); @@ -43,8 +37,7 @@ void quickSort(Item arr[], int low, int high) } } -int main() -{ +int main() { cout << "\nEnter the capacity of the knapsack : "; float capacity; cin >> capacity; @@ -52,8 +45,7 @@ int main() int n; cin >> n; Item itemArray[n]; - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { cout << "\nEnter the weight and profit of item " << i + 1 << " : "; cin >> itemArray[i].weight; cin >> itemArray[i].profit; @@ -65,17 +57,13 @@ int main() float maxProfit = 0; int i = n; - while (capacity > 0 && --i >= 0) - { - if (capacity >= itemArray[i].weight) - { + while (capacity > 0 && --i >= 0) { + if (capacity >= itemArray[i].weight) { maxProfit += itemArray[i].profit; capacity -= itemArray[i].weight; cout << "\n\t" << itemArray[i].weight << "\t" << itemArray[i].profit; - } - else - { + } else { maxProfit += profitPerUnit(itemArray[i]) * capacity; cout << "\n\t" << capacity << "\t" << profitPerUnit(itemArray[i]) * capacity; diff --git a/greedy_algorithms/kruskals_minimum_spanning_tree.cpp b/greedy_algorithms/kruskals_minimum_spanning_tree.cpp index feeaf0102d1..9f35e86ac1f 100644 --- a/greedy_algorithms/kruskals_minimum_spanning_tree.cpp +++ b/greedy_algorithms/kruskals_minimum_spanning_tree.cpp @@ -11,16 +11,12 @@ int graph[V][V] = {{0, 4, 1, 4, INFINITY, INFINITY}, {INFINITY, 3, 1, 5, 0, INFINITY}, {INFINITY, INFINITY, INFINITY, 7, INFINITY, 0}}; -void findMinimumEdge() -{ - for (int i = 0; i < V; i++) - { +void findMinimumEdge() { + for (int i = 0; i < V; i++) { int min = INFINITY; int minIndex = 0; - for (int j = 0; j < V; j++) - { - if (graph[i][j] != 0 && graph[i][j] < min) - { + for (int j = 0; j < V; j++) { + if (graph[i][j] != 0 && graph[i][j] < min) { min = graph[i][j]; minIndex = j; } @@ -29,8 +25,7 @@ void findMinimumEdge() } } -int main() -{ +int main() { findMinimumEdge(); return 0; } diff --git a/greedy_algorithms/prims_minimum_spanning_tree.cpp b/greedy_algorithms/prims_minimum_spanning_tree.cpp index c1d3df66947..c804c176d8b 100644 --- a/greedy_algorithms/prims_minimum_spanning_tree.cpp +++ b/greedy_algorithms/prims_minimum_spanning_tree.cpp @@ -6,8 +6,7 @@ using namespace std; int graph[V][V] = {{0, 5, 1, 2}, {5, 0, 3, 3}, {1, 3, 0, 4}, {2, 3, 4, 0}}; -struct mst -{ +struct mst { bool visited; int key; int near; @@ -15,10 +14,8 @@ struct mst mst MST_Array[V]; -void initilize() -{ - for (int i = 0; i < V; i++) - { +void initilize() { + for (int i = 0; i < V; i++) { MST_Array[i].visited = false; MST_Array[i].key = INFINITY; // considering INFINITY as inifinity MST_Array[i].near = i; @@ -27,17 +24,13 @@ void initilize() MST_Array[0].key = 0; } -void updateNear() -{ - for (int v = 0; v < V; v++) - { +void updateNear() { + for (int v = 0; v < V; v++) { int min = INFINITY; int minIndex = 0; - for (int i = 0; i < V; i++) - { + for (int i = 0; i < V; i++) { if (MST_Array[i].key < min && MST_Array[i].visited == false && - MST_Array[i].key != INFINITY) - { + MST_Array[i].key != INFINITY) { min = MST_Array[i].key; minIndex = i; } @@ -45,12 +38,9 @@ void updateNear() MST_Array[minIndex].visited = true; - for (int i = 0; i < V; i++) - { - if (graph[minIndex][i] != 0 && graph[minIndex][i] < INFINITY) - { - if (graph[minIndex][i] < MST_Array[i].key) - { + for (int i = 0; i < V; i++) { + if (graph[minIndex][i] != 0 && graph[minIndex][i] < INFINITY) { + if (graph[minIndex][i] < MST_Array[i].key) { MST_Array[i].key = graph[minIndex][i]; MST_Array[i].near = minIndex; } @@ -59,17 +49,14 @@ void updateNear() } } -void show() -{ - for (int i = 0; i < V; i++) - { +void show() { + for (int i = 0; i < V; i++) { cout << i << " - " << MST_Array[i].near << "\t" << graph[i][MST_Array[i].near] << "\n"; } } -int main() -{ +int main() { initilize(); updateNear(); show(); diff --git a/hashing/chaining.cpp b/hashing/chaining.cpp index ae46aea59dc..6afd2d13b2c 100644 --- a/hashing/chaining.cpp +++ b/hashing/chaining.cpp @@ -2,51 +2,39 @@ #include using namespace std; -struct Node -{ +struct Node { int data; struct Node *next; } * head[100], *curr; -void init() -{ +void init() { for (int i = 0; i < 100; i++) head[i] = NULL; } -void add(int x, int h) -{ +void add(int x, int h) { struct Node *temp = new Node; temp->data = x; temp->next = NULL; - if (!head[h]) - { + if (!head[h]) { head[h] = temp; curr = head[h]; - } - else - { + } else { curr = head[h]; while (curr->next) curr = curr->next; curr->next = temp; } } -void display(int mod) -{ +void display(int mod) { struct Node *temp; int i; - for (i = 0; i < mod; i++) - { - if (!head[i]) - { + for (i = 0; i < mod; i++) { + if (!head[i]) { cout << "Key " << i << " is empty" << endl; - } - else - { + } else { cout << "Key " << i << " has values = "; temp = head[i]; - while (temp->next) - { + while (temp->next) { cout << temp->data << " "; temp = temp->next; } @@ -58,19 +46,16 @@ void display(int mod) int hash(int x, int mod) { return x % mod; } -void find(int x, int h) -{ +void find(int x, int h) { struct Node *temp = head[h]; - if (!head[h]) - { + if (!head[h]) { cout << "Element not found"; return; } while (temp->data != x && temp->next) temp = temp->next; if (temp->next) cout << "Element found"; - else - { + else { if (temp->data == x) cout << "Element found"; else @@ -78,15 +63,13 @@ void find(int x, int h) } } -int main(void) -{ +int main(void) { init(); int c, x, mod, h; cout << "Enter the size of Hash Table. = "; cin >> mod; bool loop = true; - while (loop) - { + while (loop) { cout << endl; cout << "PLEASE CHOOSE -" << endl; cout << "1. Add element." << endl; @@ -95,8 +78,7 @@ int main(void) cout << "4. Display Hash table." << endl; cout << "5. Exit." << endl; cin >> c; - switch (c) - { + switch (c) { case 1: cout << "Enter element to add = "; cin >> x; diff --git a/hashing/double_hash_hash_table.cpp b/hashing/double_hash_hash_table.cpp index 842f383c5a1..7ee2757ded9 100644 --- a/hashing/double_hash_hash_table.cpp +++ b/hashing/double_hash_hash_table.cpp @@ -25,55 +25,44 @@ int size; bool rehashing; // Node that holds key -struct Entry -{ +struct Entry { explicit Entry(int key = notPresent) : key(key) {} int key; }; // Hash a key -int hashFxn(int key) -{ +int hashFxn(int key) { std::hash hash; return hash(key); } // Used for second hash function -int otherHashFxn(int key) -{ +int otherHashFxn(int key) { std::hash hash; return 1 + (7 - (hash(key) % 7)); } // Performs double hashing to resolve collisions -int doubleHash(int key, bool searching) -{ +int doubleHash(int key, bool searching) { int hash = static_cast(fabs(hashFxn(key))); int i = 0; Entry entry; - do - { + do { int index = static_cast(fabs((hash + (i * otherHashFxn(key))))) % totalSize; entry = table[index]; - if (searching) - { - if (entry.key == notPresent) - { + if (searching) { + if (entry.key == notPresent) { return notPresent; } - if (searchingProber(entry, key)) - { + if (searchingProber(entry, key)) { cout << "Found key!" << endl; return index; } cout << "Found tombstone or equal hash, checking next" << endl; i++; - } - else - { - if (putProber(entry, key)) - { + } else { + if (putProber(entry, key)) { if (!rehashing) cout << "Spot found!" << endl; return index; @@ -87,8 +76,7 @@ int doubleHash(int key, bool searching) << ")" << endl; i++; } - if (i == totalSize * 100) - { + if (i == totalSize * 100) { cout << "DoubleHash probe failed" << endl; return notPresent; } @@ -97,38 +85,28 @@ int doubleHash(int key, bool searching) } // Finds empty spot -bool putProber(Entry entry, int key) -{ - if (entry.key == notPresent || entry.key == tomb) - { +bool putProber(Entry entry, int key) { + if (entry.key == notPresent || entry.key == tomb) { return true; } return false; } // Looks for a matching key -bool searchingProber(Entry entry, int key) -{ +bool searchingProber(Entry entry, int key) { if (entry.key == key) return true; return false; } // Displays the table -void display() -{ - for (int i = 0; i < totalSize; i++) - { - if (table[i].key == notPresent) - { +void display() { + for (int i = 0; i < totalSize; i++) { + if (table[i].key == notPresent) { cout << " Empty "; - } - else if (table[i].key == tomb) - { + } else if (table[i].key == tomb) { cout << " Tomb "; - } - else - { + } else { cout << " "; cout << table[i].key; cout << " "; @@ -138,8 +116,7 @@ void display() } // Rehashes the table into a bigger table -void rehash() -{ +void rehash() { // Necessary so wall of add info isn't printed all at once rehashing = true; int oldSize = totalSize; @@ -147,10 +124,8 @@ void rehash() // Really this should use the next prime number greater than totalSize * 2 table = new Entry[totalSize * 2]; totalSize *= 2; - for (int i = 0; i < oldSize; i++) - { - if (oldTable[i].key != -1 && oldTable[i].key != notPresent) - { + for (int i = 0; i < oldSize; i++) { + if (oldTable[i].key != -1 && oldTable[i].key != notPresent) { size--; // Size stays the same (add increments size) add(oldTable[i].key); } @@ -161,25 +136,21 @@ void rehash() } // Checks for load factor here -void add(int key) -{ +void add(int key) { Entry* entry = new Entry(); entry->key = key; int index = doubleHash(key, false); table[index] = *entry; // Load factor greater than 0.5 causes resizing - if (++size / static_cast(totalSize) >= 0.5) - { + if (++size / static_cast(totalSize) >= 0.5) { rehash(); } } // Removes key. Leaves tombstone upon removal. -void remove(int key) -{ +void remove(int key) { int index = doubleHash(key, true); - if (index == notPresent) - { + if (index == notPresent) { cout << "key not found" << endl; } table[index].key = tomb; @@ -188,8 +159,7 @@ void remove(int key) } // Information about the adding process -void addInfo(int key) -{ +void addInfo(int key) { cout << "Initial table: "; display(); cout << endl; @@ -202,8 +172,7 @@ void addInfo(int key) } // Information about removal process -void removalInfo(int key) -{ +void removalInfo(int key) { cout << "Initial table: "; display(); cout << endl; @@ -216,15 +185,13 @@ void removalInfo(int key) } // I/O -int main(void) -{ +int main(void) { int cmd, hash, key; cout << "Enter the initial size of Hash Table. = "; cin >> totalSize; table = new Entry[totalSize]; bool loop = true; - while (loop) - { + while (loop) { system("pause"); cout << endl; cout << "PLEASE CHOOSE -" << endl; @@ -235,8 +202,7 @@ int main(void) cout << "5. Display Hash table." << endl; cout << "6. Exit." << endl; cin >> cmd; - switch (cmd) - { + switch (cmd) { case 1: cout << "Enter key to add = "; cin >> key; @@ -247,13 +213,11 @@ int main(void) cin >> key; removalInfo(key); break; - case 3: - { + case 3: { cout << "Enter key to search = "; cin >> key; Entry entry = table[doubleHash(key, true)]; - if (entry.key == notPresent) - { + if (entry.key == notPresent) { cout << "Key not present"; } break; diff --git a/hashing/linear_probing_hash_table.cpp b/hashing/linear_probing_hash_table.cpp index 0d4b5b0e1f3..393504c1d09 100644 --- a/hashing/linear_probing_hash_table.cpp +++ b/hashing/linear_probing_hash_table.cpp @@ -25,47 +25,37 @@ int size; bool rehashing; // Node that holds key -struct Entry -{ +struct Entry { explicit Entry(int key = notPresent) : key(key) {} int key; }; // Hash a key -int hashFxn(int key) -{ +int hashFxn(int key) { std::hash hash; return hash(key); } // Performs linear probing to resolve collisions -int linearProbe(int key, bool searching) -{ +int linearProbe(int key, bool searching) { int hash = static_cast(fabs(hashFxn(key))); int i = 0; Entry entry; - do - { + do { int index = static_cast(fabs((hash + i) % totalSize)); entry = table[index]; - if (searching) - { - if (entry.key == notPresent) - { + if (searching) { + if (entry.key == notPresent) { return notPresent; } - if (searchingProber(entry, key)) - { + if (searchingProber(entry, key)) { cout << "Found key!" << endl; return index; } cout << "Found tombstone or equal hash, checking next" << endl; i++; - } - else - { - if (putProber(entry, key)) - { + } else { + if (putProber(entry, key)) { if (!rehashing) cout << "Spot found!" << endl; return index; @@ -74,8 +64,7 @@ int linearProbe(int key, bool searching) cout << "Spot taken, looking at next" << endl; i++; } - if (i == totalSize) - { + if (i == totalSize) { cout << "Linear probe failed" << endl; return notPresent; } @@ -84,38 +73,28 @@ int linearProbe(int key, bool searching) } // Finds empty spot -bool putProber(Entry entry, int key) -{ - if (entry.key == notPresent || entry.key == tomb) - { +bool putProber(Entry entry, int key) { + if (entry.key == notPresent || entry.key == tomb) { return true; } return false; } // Looks for a matching key -bool searchingProber(Entry entry, int key) -{ +bool searchingProber(Entry entry, int key) { if (entry.key == key) return true; return false; } // Displays the table -void display() -{ - for (int i = 0; i < totalSize; i++) - { - if (table[i].key == notPresent) - { +void display() { + for (int i = 0; i < totalSize; i++) { + if (table[i].key == notPresent) { cout << " Empty "; - } - else if (table[i].key == tomb) - { + } else if (table[i].key == tomb) { cout << " Tomb "; - } - else - { + } else { cout << " "; cout << table[i].key; cout << " "; @@ -125,8 +104,7 @@ void display() } // Rehashes the table into a bigger table -void rehash() -{ +void rehash() { // Necessary so wall of add info isn't printed all at once rehashing = true; int oldSize = totalSize; @@ -134,10 +112,8 @@ void rehash() // Really this should use the next prime number greater than totalSize * 2 table = new Entry[totalSize * 2]; totalSize *= 2; - for (int i = 0; i < oldSize; i++) - { - if (oldTable[i].key != -1 && oldTable[i].key != notPresent) - { + for (int i = 0; i < oldSize; i++) { + if (oldTable[i].key != -1 && oldTable[i].key != notPresent) { size--; // Size stays the same (add increments size) add(oldTable[i].key); } @@ -148,25 +124,21 @@ void rehash() } // Adds entry using linear probing. Checks for load factor here -void add(int key) -{ +void add(int key) { Entry* entry = new Entry(); entry->key = key; int index = linearProbe(key, false); table[index] = *entry; // Load factor greater than 0.5 causes resizing - if (++size / static_cast(totalSize) >= 0.5) - { + if (++size / static_cast(totalSize) >= 0.5) { rehash(); } } // Removes key. Leaves tombstone upon removal. -void remove(int key) -{ +void remove(int key) { int index = linearProbe(key, true); - if (index == notPresent) - { + if (index == notPresent) { cout << "key not found" << endl; } cout << "Removal Successful, leaving tomb" << endl; @@ -175,8 +147,7 @@ void remove(int key) } // Information about the adding process -void addInfo(int key) -{ +void addInfo(int key) { cout << "Initial table: "; display(); cout << endl; @@ -189,8 +160,7 @@ void addInfo(int key) } // Information about removal process -void removalInfo(int key) -{ +void removalInfo(int key) { cout << "Initial table: "; display(); cout << endl; @@ -203,15 +173,13 @@ void removalInfo(int key) } // I/O -int main(void) -{ +int main(void) { int cmd, hash, key; cout << "Enter the initial size of Hash Table. = "; cin >> totalSize; table = new Entry[totalSize]; bool loop = true; - while (loop) - { + while (loop) { system("pause"); cout << endl; cout << "PLEASE CHOOSE -" << endl; @@ -222,8 +190,7 @@ int main(void) cout << "5. Display Hash table." << endl; cout << "6. Exit." << endl; cin >> cmd; - switch (cmd) - { + switch (cmd) { case 1: cout << "Enter key to add = "; cin >> key; @@ -234,13 +201,11 @@ int main(void) cin >> key; removalInfo(key); break; - case 3: - { + case 3: { cout << "Enter key to search = "; cin >> key; Entry entry = table[linearProbe(key, true)]; - if (entry.key == notPresent) - { + if (entry.key == notPresent) { cout << "Key not present"; } break; diff --git a/hashing/quadratic_probing_hash_table.cpp b/hashing/quadratic_probing_hash_table.cpp index b549d057d80..971c2182dd5 100644 --- a/hashing/quadratic_probing_hash_table.cpp +++ b/hashing/quadratic_probing_hash_table.cpp @@ -26,54 +26,43 @@ int size; bool rehashing; // Node that holds key -struct Entry -{ +struct Entry { explicit Entry(int key = notPresent) : key(key) {} int key; }; // Hash a key -int hashFxn(int key) -{ +int hashFxn(int key) { std::hash hash; return hash(key); } // Performs quadratic probing to resolve collisions -int quadraticProbe(int key, bool searching) -{ +int quadraticProbe(int key, bool searching) { int hash = static_cast(fabs(hashFxn(key))); int i = 0; Entry entry; - do - { + do { int index = std::round(fabs( (hash + static_cast(std::round(std::pow(i, 2)))) % totalSize)); entry = table[index]; - if (searching) - { - if (entry.key == notPresent) - { + if (searching) { + if (entry.key == notPresent) { return notPresent; } - if (searchingProber(entry, key)) - { + if (searchingProber(entry, key)) { cout << "Found key!" << endl; return index; } cout << "Found tombstone or equal hash, checking next" << endl; i++; - } - else - { - if (putProber(entry, key)) - { + } else { + if (putProber(entry, key)) { if (!rehashing) cout << "Spot found!" << endl; return index; } - if (!rehashing) - { + if (!rehashing) { cout << "Spot taken, looking at next (next index = " << std::round(fabs((hash + static_cast(std::round( std::pow(i + 1, 2)))) % @@ -82,8 +71,7 @@ int quadraticProbe(int key, bool searching) } i++; } - if (i == totalSize * 100) - { + if (i == totalSize * 100) { cout << "Quadratic probe failed (infinite loop)" << endl; return notPresent; } @@ -92,26 +80,22 @@ int quadraticProbe(int key, bool searching) } // Finds empty spot -bool putProber(Entry entry, int key) -{ - if (entry.key == notPresent || entry.key == tomb) - { +bool putProber(Entry entry, int key) { + if (entry.key == notPresent || entry.key == tomb) { return true; } return false; } // Looks for a matching key -bool searchingProber(Entry entry, int key) -{ +bool searchingProber(Entry entry, int key) { if (entry.key == key) return true; return false; } // Helper -Entry find(int key) -{ +Entry find(int key) { int index = quadraticProbe(key, true); if (index == notPresent) return Entry(); @@ -119,20 +103,13 @@ Entry find(int key) } // Displays the table -void display() -{ - for (int i = 0; i < totalSize; i++) - { - if (table[i].key == notPresent) - { +void display() { + for (int i = 0; i < totalSize; i++) { + if (table[i].key == notPresent) { cout << " Empty "; - } - else if (table[i].key == tomb) - { + } else if (table[i].key == tomb) { cout << " Tomb "; - } - else - { + } else { cout << " "; cout << table[i].key; cout << " "; @@ -142,8 +119,7 @@ void display() } // Rehashes the table into a bigger table -void rehash() -{ +void rehash() { // Necessary so wall of add info isn't printed all at once rehashing = true; int oldSize = totalSize; @@ -151,10 +127,8 @@ void rehash() // Really this should use the next prime number greater than totalSize * 2 table = new Entry[totalSize * 2]; totalSize *= 2; - for (int i = 0; i < oldSize; i++) - { - if (oldTable[i].key != -1 && oldTable[i].key != notPresent) - { + for (int i = 0; i < oldSize; i++) { + if (oldTable[i].key != -1 && oldTable[i].key != notPresent) { size--; // Size stays the same (add increments size) add(oldTable[i].key); } @@ -165,25 +139,21 @@ void rehash() } // Checks for load factor here -void add(int key) -{ +void add(int key) { Entry* entry = new Entry(); entry->key = key; int index = quadraticProbe(key, false); table[index] = *entry; // Load factor greater than 0.5 causes resizing - if (++size / static_cast(totalSize) >= 0.5) - { + if (++size / static_cast(totalSize) >= 0.5) { rehash(); } } // Removes key. Leaves tombstone upon removal. -void remove(int key) -{ +void remove(int key) { int index = quadraticProbe(key, true); - if (index == notPresent) - { + if (index == notPresent) { cout << "key not found" << endl; } table[index].key = tomb; @@ -192,8 +162,7 @@ void remove(int key) } // Information about the adding process -void addInfo(int key) -{ +void addInfo(int key) { cout << "Initial table: "; display(); cout << endl; @@ -206,8 +175,7 @@ void addInfo(int key) } // Information about removal process -void removalInfo(int key) -{ +void removalInfo(int key) { cout << "Initial table: "; display(); cout << endl; @@ -220,15 +188,13 @@ void removalInfo(int key) } // I/O -int main(void) -{ +int main(void) { int cmd, hash, key; cout << "Enter the initial size of Hash Table. = "; cin >> totalSize; table = new Entry[totalSize]; bool loop = true; - while (loop) - { + while (loop) { system("pause"); cout << endl; cout << "PLEASE CHOOSE -" << endl; @@ -239,8 +205,7 @@ int main(void) cout << "5. Display Hash table." << endl; cout << "6. Exit." << endl; cin >> cmd; - switch (cmd) - { + switch (cmd) { case 1: cout << "Enter key to add = "; cin >> key; @@ -251,13 +216,11 @@ int main(void) cin >> key; removalInfo(key); break; - case 3: - { + case 3: { cout << "Enter key to search = "; cin >> key; Entry entry = table[quadraticProbe(key, true)]; - if (entry.key == notPresent) - { + if (entry.key == notPresent) { cout << "Key not present"; } break; diff --git a/math/binary_exponent.cpp b/math/binary_exponent.cpp index 7bf3a34a1f4..05e6f33f7ae 100644 --- a/math/binary_exponent.cpp +++ b/math/binary_exponent.cpp @@ -25,32 +25,24 @@ /// Recursive function to calculate exponent in \f$O(\log(n))\f$ using binary /// exponent. -int binExpo(int a, int b) -{ - if (b == 0) - { +int binExpo(int a, int b) { + if (b == 0) { return 1; } int res = binExpo(a, b / 2); - if (b % 2) - { + if (b % 2) { return res * res * a; - } - else - { + } else { return res * res; } } /// Iterative function to calculate exponent in \f$O(\log(n))\f$ using binary /// exponent. -int binExpo_alt(int a, int b) -{ +int binExpo_alt(int a, int b) { int res = 1; - while (b > 0) - { - if (b % 2) - { + while (b > 0) { + if (b % 2) { res = res * a; } a = a * a; @@ -60,21 +52,15 @@ int binExpo_alt(int a, int b) } /// Main function -int main() -{ +int main() { int a, b; /// Give two numbers a, b std::cin >> a >> b; - if (a == 0 && b == 0) - { + if (a == 0 && b == 0) { std::cout << "Math error" << std::endl; - } - else if (b < 0) - { + } else if (b < 0) { std::cout << "Exponent must be positive !!" << std::endl; - } - else - { + } else { int resRecurse = binExpo(a, b); /// int resIterate = binExpo_alt(a, b); diff --git a/math/double_factorial.cpp b/math/double_factorial.cpp index 4909ad48967..8e5ffcefa04 100644 --- a/math/double_factorial.cpp +++ b/math/double_factorial.cpp @@ -13,11 +13,9 @@ /** Compute double factorial using iterative method */ -uint64_t double_factorial_iterative(uint64_t n) -{ +uint64_t double_factorial_iterative(uint64_t n) { uint64_t res = 1; - for (uint64_t i = n;; i -= 2) - { + for (uint64_t i = n;; i -= 2) { if (i == 0 || i == 1) return res; res *= i; @@ -28,16 +26,14 @@ uint64_t double_factorial_iterative(uint64_t n) /** Compute double factorial using resursive method. *
Recursion can be costly for large numbers. */ -uint64_t double_factorial_recursive(uint64_t n) -{ +uint64_t double_factorial_recursive(uint64_t n) { if (n <= 1) return 1; return n * double_factorial_recursive(n - 2); } /// main function -int main() -{ +int main() { uint64_t n; std::cin >> n; assert(n >= 0); diff --git a/math/eulers_totient_function.cpp b/math/eulers_totient_function.cpp index 283516b4230..8283ab04503 100644 --- a/math/eulers_totient_function.cpp +++ b/math/eulers_totient_function.cpp @@ -29,15 +29,11 @@ /** Function to caculate Euler's totient phi */ -uint64_t phiFunction(uint64_t n) -{ +uint64_t phiFunction(uint64_t n) { uint64_t result = n; - for (uint64_t i = 2; i * i <= n; i++) - { - if (n % i == 0) - { - while (n % i == 0) - { + for (uint64_t i = 2; i * i <= n; i++) { + if (n % i == 0) { + while (n % i == 0) { n /= i; } result -= result / i; @@ -49,15 +45,11 @@ uint64_t phiFunction(uint64_t n) } /// Main function -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { uint64_t n; - if (argc < 2) - { + if (argc < 2) { std::cout << "Enter the number: "; - } - else - { + } else { n = strtoull(argv[1], nullptr, 10); } std::cin >> n; diff --git a/math/extended_euclid_algorithm.cpp b/math/extended_euclid_algorithm.cpp index 8a79e0c7803..9fdc9692ef1 100644 --- a/math/extended_euclid_algorithm.cpp +++ b/math/extended_euclid_algorithm.cpp @@ -21,8 +21,7 @@ * @param[in] quotient unsigned */ template -inline void update_step(T *r, T *r0, const T2 quotient) -{ +inline void update_step(T *r, T *r0, const T2 quotient) { T temp = *r; *r = *r0 - (quotient * temp); *r0 = temp; @@ -39,8 +38,7 @@ inline void update_step(T *r, T *r0, const T2 quotient) * @param[out] y signed */ template -void extendedEuclid_1(T1 A, T1 B, T1 *GCD, T2 *x, T2 *y) -{ +void extendedEuclid_1(T1 A, T1 B, T1 *GCD, T2 *x, T2 *y) { if (B > A) std::swap(A, B); // Ensure that A >= B @@ -48,8 +46,7 @@ void extendedEuclid_1(T1 A, T1 B, T1 *GCD, T2 *x, T2 *y) T2 t = 1, t0 = 0; T1 r = B, r0 = A; - while (r != 0) - { + while (r != 0) { T1 quotient = r0 / r; update_step(&r, &r0, quotient); update_step(&s, &s0, quotient); @@ -70,19 +67,15 @@ void extendedEuclid_1(T1 A, T1 B, T1 *GCD, T2 *x, T2 *y) * @param[in,out] y signed */ template -void extendedEuclid(T A, T B, T *GCD, T2 *x, T2 *y) -{ +void extendedEuclid(T A, T B, T *GCD, T2 *x, T2 *y) { if (B > A) std::swap(A, B); // Ensure that A >= B - if (B == 0) - { + if (B == 0) { *GCD = A; *x = 1; *y = 0; - } - else - { + } else { extendedEuclid(B, A % B, GCD, x, y); T2 temp = *x; *x = *y; @@ -91,8 +84,7 @@ void extendedEuclid(T A, T B, T *GCD, T2 *x, T2 *y) } /// Main function -int main() -{ +int main() { uint32_t a, b, gcd; int32_t x, y; std::cin >> a >> b; diff --git a/math/factorial.cpp b/math/factorial.cpp index 7f50544e257..353f0b16bc7 100644 --- a/math/factorial.cpp +++ b/math/factorial.cpp @@ -5,16 +5,14 @@ #include /** function to find factorial of given number */ -unsigned int factorial(unsigned int n) -{ +unsigned int factorial(unsigned int n) { if (n == 0) return 1; return n * factorial(n - 1); } /** Main function */ -int main() -{ +int main() { int num = 5; std::cout << "Factorial of " << num << " is " << factorial(num) << std::endl; diff --git a/math/fast_power.cpp b/math/fast_power.cpp index 8a0525ac17b..c5621cd4ecc 100644 --- a/math/fast_power.cpp +++ b/math/fast_power.cpp @@ -23,8 +23,7 @@ * algorithm implementation for \f$a^b\f$ */ template -double fast_power_recursive(T a, T b) -{ +double fast_power_recursive(T a, T b) { // negative power. a^b = 1 / (a^-b) if (b < 0) return 1.0 / fast_power_recursive(a, -b); @@ -48,15 +47,13 @@ double fast_power_recursive(T a, T b) It still calculates in \f$O(\log N)\f$ */ template -double fast_power_linear(T a, T b) -{ +double fast_power_linear(T a, T b) { // negative power. a^b = 1 / (a^-b) if (b < 0) return 1.0 / fast_power_linear(a, -b); double result = 1; - while (b) - { + while (b) { if (b & 1) result = result * a; a = a * a; @@ -68,14 +65,12 @@ double fast_power_linear(T a, T b) /** * Main function */ -int main() -{ +int main() { std::srand(std::time(nullptr)); std::ios_base::sync_with_stdio(false); std::cout << "Testing..." << std::endl; - for (int i = 0; i < 20; i++) - { + for (int i = 0; i < 20; i++) { int a = std::rand() % 20 - 10; int b = std::rand() % 20 - 10; std::cout << std::endl << "Calculating " << a << "^" << b << std::endl; diff --git a/math/fibonacci.cpp b/math/fibonacci.cpp index 5a219bbf9fc..e15cfc0ccff 100644 --- a/math/fibonacci.cpp +++ b/math/fibonacci.cpp @@ -14,8 +14,7 @@ /** * Recursively compute sequences */ -int fibonacci(unsigned int n) -{ +int fibonacci(unsigned int n) { /* If the input is 0 or 1 just return the same This will set the first 2 values of the sequence */ if (n <= 1) @@ -26,8 +25,7 @@ int fibonacci(unsigned int n) } /// Main function -int main() -{ +int main() { int n; std::cin >> n; assert(n >= 0); diff --git a/math/fibonacci_fast.cpp b/math/fibonacci_fast.cpp index 3b3a3ca3840..08cced35105 100644 --- a/math/fibonacci_fast.cpp +++ b/math/fibonacci_fast.cpp @@ -26,8 +26,7 @@ const uint64_t MAX = 93; uint64_t f[MAX] = {0}; /** Algorithm */ -uint64_t fib(uint64_t n) -{ +uint64_t fib(uint64_t n) { if (n == 0) return 0; if (n == 1 || n == 2) @@ -44,11 +43,9 @@ uint64_t fib(uint64_t n) } /** Main function */ -int main() -{ +int main() { // Main Function - for (uint64_t i = 1; i < 93; i++) - { + for (uint64_t i = 1; i < 93; i++) { std::cout << i << " th fibonacci number is " << fib(i) << std::endl; } return 0; diff --git a/math/fibonacci_large.cpp b/math/fibonacci_large.cpp index edc513750fc..d9dbff79968 100644 --- a/math/fibonacci_large.cpp +++ b/math/fibonacci_large.cpp @@ -20,13 +20,11 @@ * \f[f(n)=f(n-1)+f(n-2)\f] * and returns the result as a large_number type. */ -large_number fib(uint64_t n) -{ +large_number fib(uint64_t n) { large_number f0(1); large_number f1(1); - do - { + do { large_number f2 = f1; f1 += f0; f0 = f2; @@ -36,15 +34,11 @@ large_number fib(uint64_t n) return f1; } -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { uint64_t N; - if (argc == 2) - { + if (argc == 2) { N = strtoull(argv[1], NULL, 10); - } - else - { + } else { std::cout << "Enter N: "; std::cin >> N; } diff --git a/math/gcd_iterative_euclidean.cpp b/math/gcd_iterative_euclidean.cpp index e832605d7d0..2c0651ad7ca 100644 --- a/math/gcd_iterative_euclidean.cpp +++ b/math/gcd_iterative_euclidean.cpp @@ -12,34 +12,27 @@ /** * algorithm */ -int gcd(int num1, int num2) -{ - if (num1 <= 0 | num2 <= 0) - { +int gcd(int num1, int num2) { + if (num1 <= 0 | num2 <= 0) { throw std::domain_error("Euclidean algorithm domain is for ints > 0"); } - if (num1 == num2) - { + if (num1 == num2) { return num1; } int base_num = 0; int previous_remainder = 1; - if (num1 > num2) - { + if (num1 > num2) { base_num = num1; previous_remainder = num2; - } - else - { + } else { base_num = num2; previous_remainder = num1; } - while ((base_num % previous_remainder) != 0) - { + while ((base_num % previous_remainder) != 0) { int old_base = base_num; base_num = previous_remainder; previous_remainder = old_base % previous_remainder; @@ -51,15 +44,11 @@ int gcd(int num1, int num2) /** * Main function */ -int main() -{ +int main() { std::cout << "gcd of 120,7 is " << (gcd(120, 7)) << std::endl; - try - { + try { std::cout << "gcd of -120,10 is " << gcd(-120, 10) << std::endl; - } - catch (const std::domain_error &e) - { + } catch (const std::domain_error &e) { std::cout << "Error handling was successful" << std::endl; } std::cout << "gcd of 312,221 is " << (gcd(312, 221)) << std::endl; diff --git a/math/gcd_of_n_numbers.cpp b/math/gcd_of_n_numbers.cpp index cd81e602531..92968ff1265 100644 --- a/math/gcd_of_n_numbers.cpp +++ b/math/gcd_of_n_numbers.cpp @@ -12,12 +12,10 @@ * @param[in] a array of integers to compute GCD for * @param[in] n number of integers in array `a` */ -int gcd(int *a, int n) -{ +int gcd(int *a, int n) { int j = 1; // to access all elements of the array starting from 1 int gcd = a[0]; - while (j < n) - { + while (j < n) { if (a[j] % gcd == 0) // value of gcd is as needed so far j++; // so we check for next element else @@ -27,8 +25,7 @@ int gcd(int *a, int n) } /** Main function */ -int main() -{ +int main() { int n; std::cout << "Enter value of n:" << std::endl; std::cin >> n; diff --git a/math/gcd_recursive_euclidean.cpp b/math/gcd_recursive_euclidean.cpp index d16fb11908b..2a3d2183c4e 100644 --- a/math/gcd_recursive_euclidean.cpp +++ b/math/gcd_recursive_euclidean.cpp @@ -11,15 +11,12 @@ /** * algorithm */ -int gcd(int num1, int num2) -{ - if (num1 <= 0 | num2 <= 0) - { +int gcd(int num1, int num2) { + if (num1 <= 0 | num2 <= 0) { throw std::domain_error("Euclidean algorithm domain is for ints > 0"); } - if (num1 == num2) - { + if (num1 == num2) { return num1; } @@ -42,15 +39,11 @@ int gcd(int num1, int num2) /** * Main function */ -int main() -{ +int main() { std::cout << "gcd of 120,7 is " << (gcd(120, 7)) << std::endl; - try - { + try { std::cout << "gcd of -120,10 is " << gcd(-120, 10) << std::endl; - } - catch (const std::domain_error &e) - { + } catch (const std::domain_error &e) { std::cout << "Error handling was successful" << std::endl; } std::cout << "gcd of 312,221 is " << (gcd(312, 221)) << std::endl; diff --git a/math/large_factorial.cpp b/math/large_factorial.cpp index 0a54f620bb6..1027f41abf8 100644 --- a/math/large_factorial.cpp +++ b/math/large_factorial.cpp @@ -13,8 +13,7 @@ /** Test implementation for 10! Result must be 3628800. * @returns True if test pass else False */ -bool test1() -{ +bool test1() { std::cout << "---- Check 1\t"; unsigned int i, number = 10; large_number result; @@ -24,18 +23,15 @@ bool test1() const char *known_reslt = "3628800"; /* check 1 */ - if (strlen(known_reslt) != result.num_digits()) - { + if (strlen(known_reslt) != result.num_digits()) { std::cerr << "Result lengths dont match! " << strlen(known_reslt) << " != " << result.num_digits() << std::endl; return false; } const size_t N = result.num_digits(); - for (i = 0; i < N; i++) - { - if (known_reslt[i] != result.digit_char(i)) - { + for (i = 0; i < N; i++) { + if (known_reslt[i] != result.digit_char(i)) { std::cerr << i << "^th digit mismatch! " << known_reslt[i] << " != " << result.digit_char(i) << std::endl; return false; @@ -54,8 +50,7 @@ bool test1() * ``` * @returns True if test pass else False */ -bool test2() -{ +bool test2() { std::cout << "---- Check 2\t"; unsigned int i, number = 100; large_number result; @@ -68,18 +63,15 @@ bool test2() "000000000000000000"; /* check 1 */ - if (strlen(known_reslt) != result.num_digits()) - { + if (strlen(known_reslt) != result.num_digits()) { std::cerr << "Result lengths dont match! " << strlen(known_reslt) << " != " << result.num_digits() << std::endl; return false; } const size_t N = result.num_digits(); - for (i = 0; i < N; i++) - { - if (known_reslt[i] != result.digit_char(i)) - { + for (i = 0; i < N; i++) { + if (known_reslt[i] != result.digit_char(i)) { std::cerr << i << "^th digit mismatch! " << known_reslt[i] << " != " << result.digit_char(i) << std::endl; return false; @@ -93,16 +85,12 @@ bool test2() /** * Main program **/ -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { int number, i; - if (argc == 2) - { + if (argc == 2) { number = atoi(argv[1]); - } - else - { + } else { std::cout << "Enter the value of n(n starts from 0 ): "; std::cin >> number; } diff --git a/math/large_number.h b/math/large_number.h index 88e3ba8020d..c1a3665e4d1 100644 --- a/math/large_number.h +++ b/math/large_number.h @@ -20,8 +20,7 @@ * digit to the number, perform multiplication of * large number with long unsigned integers. **/ -class large_number -{ +class large_number { public: /**< initializer with value = 1 */ large_number() { _digits.push_back(1); } @@ -36,11 +35,9 @@ class large_number // } /**< initializer from an integer */ - explicit large_number(int n) - { + explicit large_number(int n) { int carry = n; - do - { + do { add_digit(carry % 10); carry /= 10; } while (carry != 0); @@ -53,10 +50,8 @@ class large_number explicit large_number(std::vector &vec) : _digits(vec) {} /**< initializer from a string */ - explicit large_number(char const *number_str) - { - for (size_t i = strlen(number_str); i > 0; i--) - { + explicit large_number(char const *number_str) { + for (size_t i = strlen(number_str); i > 0; i--) { unsigned char a = number_str[i - 1] - '0'; if (a >= 0 && a <= 9) _digits.push_back(a); @@ -66,55 +61,48 @@ class large_number /** * Function to check implementation **/ - static bool test() - { + static bool test() { std::cout << "------ Checking `large_number` class implementations\t" << std::endl; large_number a(40); // 1. test multiplication a *= 10; - if (a != large_number(400)) - { + if (a != large_number(400)) { std::cerr << "\tFailed 1/6 (" << a << "!=400)" << std::endl; return false; } std::cout << "\tPassed 1/6..."; // 2. test compound addition with integer a += 120; - if (a != large_number(520)) - { + if (a != large_number(520)) { std::cerr << "\tFailed 2/6 (" << a << "!=520)" << std::endl; return false; } std::cout << "\tPassed 2/6..."; // 3. test compound multiplication again a *= 10; - if (a != large_number(5200)) - { + if (a != large_number(5200)) { std::cerr << "\tFailed 3/6 (" << a << "!=5200)" << std::endl; return false; } std::cout << "\tPassed 3/6..."; // 4. test increment (prefix) ++a; - if (a != large_number(5201)) - { + if (a != large_number(5201)) { std::cerr << "\tFailed 4/6 (" << a << "!=5201)" << std::endl; return false; } std::cout << "\tPassed 4/6..."; // 5. test increment (postfix) a++; - if (a != large_number(5202)) - { + if (a != large_number(5202)) { std::cerr << "\tFailed 5/6 (" << a << "!=5202)" << std::endl; return false; } std::cout << "\tPassed 5/6..."; // 6. test addition with another large number a = a + large_number("7000000000000000000000000000000"); - if (a != large_number("7000000000000000000000000005202")) - { + if (a != large_number("7000000000000000000000000005202")) { std::cerr << "\tFailed 6/6 (" << a << "!=7000000000000000000000000005202)" << std::endl; return false; @@ -126,10 +114,8 @@ class large_number /** * add a digit at MSB to the large number **/ - void add_digit(unsigned int value) - { - if (value > 9) - { + void add_digit(unsigned int value) { + if (value > 9) { std::cerr << "digit > 9!!\n"; exit(EXIT_FAILURE); } @@ -149,16 +135,14 @@ class large_number **/ inline unsigned char &operator[](size_t n) { return this->_digits[n]; } - inline const unsigned char &operator[](size_t n) const - { + inline const unsigned char &operator[](size_t n) const { return this->_digits[n]; } /** * operator overload to compare two numbers **/ - friend std::ostream &operator<<(std::ostream &out, const large_number &a) - { + friend std::ostream &operator<<(std::ostream &out, const large_number &a) { for (size_t i = a.num_digits(); i > 0; i--) out << static_cast(a[i - 1]); return out; @@ -167,8 +151,7 @@ class large_number /** * operator overload to compare two numbers **/ - friend bool operator==(large_number const &a, large_number const &b) - { + friend bool operator==(large_number const &a, large_number const &b) { size_t N = a.num_digits(); if (N != b.num_digits()) return false; @@ -181,16 +164,14 @@ class large_number /** * operator overload to compare two numbers **/ - friend bool operator!=(large_number const &a, large_number const &b) - { + friend bool operator!=(large_number const &a, large_number const &b) { return !(a == b); } /** * operator overload to increment (prefix) **/ - large_number &operator++() - { + large_number &operator++() { (*this) += 1; return *this; } @@ -198,8 +179,7 @@ class large_number /** * operator overload to increment (postfix) **/ - large_number &operator++(int) - { + large_number &operator++(int) { static large_number tmp(_digits); ++(*this); return tmp; @@ -208,15 +188,13 @@ class large_number /** * operator overload to add **/ - large_number &operator+=(large_number n) - { + large_number &operator+=(large_number n) { // if adding with another large_number large_number *b = reinterpret_cast(&n); const size_t max_L = std::max(this->num_digits(), b->num_digits()); unsigned int carry = 0; size_t i; - for (i = 0; i < max_L || carry != 0; i++) - { + for (i = 0; i < max_L || carry != 0; i++) { if (i < b->num_digits()) carry += (*b)[i]; if (i < this->num_digits()) @@ -238,8 +216,7 @@ class large_number * operator overload to perform addition **/ template - friend large_number &operator+(const large_number &a, const T &b) - { + friend large_number &operator+(const large_number &a, const T &b) { static large_number c = a; c += b; return c; @@ -248,8 +225,7 @@ class large_number /** * assignment operator **/ - large_number &operator=(const large_number &b) - { + large_number &operator=(const large_number &b) { this->_digits = b._digits; return *this; } @@ -258,8 +234,7 @@ class large_number * operator overload to increment **/ template - large_number &operator*=(const T n) - { + large_number &operator*=(const T n) { static_assert(std::is_integral::value, "Must be integer addition unsigned integer types."); this->multiply(n); @@ -269,8 +244,7 @@ class large_number /** * returns i^th digit as an ASCII character **/ - const char digit_char(size_t i) const - { + const char digit_char(size_t i) const { return _digits[num_digits() - i - 1] + '0'; } @@ -280,8 +254,7 @@ class large_number * store the result in the same large number **/ template - void multiply(const T n) - { + void multiply(const T n) { static_assert(std::is_integral::value, "Can only have integer types."); // assert(!(std::is_signed::value)); //, "Implemented only for @@ -289,24 +262,19 @@ class large_number size_t i; uint64_t carry = 0, temp; - for (i = 0; i < this->num_digits(); i++) - { + for (i = 0; i < this->num_digits(); i++) { temp = (*this)[i] * n; temp += carry; - if (temp < 10) - { + if (temp < 10) { carry = 0; - } - else - { + } else { carry = temp / 10; temp = temp % 10; } (*this)[i] = temp; } - while (carry != 0) - { + while (carry != 0) { this->add_digit(carry % 10); carry /= 10; } diff --git a/math/modular_inverse_fermat_little_theorem.cpp b/math/modular_inverse_fermat_little_theorem.cpp index 6895cafbbf9..7550e14bf23 100644 --- a/math/modular_inverse_fermat_little_theorem.cpp +++ b/math/modular_inverse_fermat_little_theorem.cpp @@ -49,14 +49,11 @@ /** Recursive function to calculate exponent in \f$O(\log n)\f$ using binary * exponent. */ -int64_t binExpo(int64_t a, int64_t b, int64_t m) -{ +int64_t binExpo(int64_t a, int64_t b, int64_t m) { a %= m; int64_t res = 1; - while (b > 0) - { - if (b % 2) - { + while (b > 0) { + if (b % 2) { res = res * a % m; } a = a * a % m; @@ -68,18 +65,12 @@ int64_t binExpo(int64_t a, int64_t b, int64_t m) /** Prime check in \f$O(\sqrt{m})\f$ time. */ -bool isPrime(int64_t m) -{ - if (m <= 1) - { +bool isPrime(int64_t m) { + if (m <= 1) { return false; - } - else - { - for (int64_t i = 2; i * i <= m; i++) - { - if (m % i == 0) - { + } else { + for (int64_t i = 2; i * i <= m; i++) { + if (m % i == 0) { return false; } } @@ -90,21 +81,17 @@ bool isPrime(int64_t m) /** * Main function */ -int main() -{ +int main() { int64_t a, m; // Take input of a and m. std::cout << "Computing ((a^(-1))%(m)) using Fermat's Little Theorem"; std::cout << std::endl << std::endl; std::cout << "Give input 'a' and 'm' space separated : "; std::cin >> a >> m; - if (isPrime(m)) - { + if (isPrime(m)) { std::cout << "The modular inverse of a with mod m is (a^(m-2)) : "; std::cout << binExpo(a, m - 2, m) << std::endl; - } - else - { + } else { std::cout << "m must be a prime number."; std::cout << std::endl; } diff --git a/math/number_of_positive_divisors.cpp b/math/number_of_positive_divisors.cpp index beb4599439e..f157f7b4161 100644 --- a/math/number_of_positive_divisors.cpp +++ b/math/number_of_positive_divisors.cpp @@ -31,31 +31,25 @@ respectively. /** * Algorithm */ -int number_of_positive_divisors(int n) -{ +int number_of_positive_divisors(int n) { std::vector prime_exponent_count; - for (int i = 2; i * i <= n; i++) - { + for (int i = 2; i * i <= n; i++) { int prime_count = 0; - while (n % i == 0) - { + while (n % i == 0) { prime_count += 1; n /= i; } - if (prime_count != 0) - { + if (prime_count != 0) { prime_exponent_count.push_back(prime_count); } } - if (n > 1) - { + if (n > 1) { prime_exponent_count.push_back(1); } int divisors_count = 1; - for (int i = 0; i < prime_exponent_count.size(); i++) - { + for (int i = 0; i < prime_exponent_count.size(); i++) { divisors_count = divisors_count * (prime_exponent_count[i] + 1); } @@ -65,20 +59,15 @@ int number_of_positive_divisors(int n) /** * Main function */ -int main() -{ +int main() { int n; std::cin >> n; - if (n < 0) - { + if (n < 0) { n = -n; } - if (n == 0) - { + if (n == 0) { std::cout << "All non-zero numbers are divisors of 0 !" << std::endl; - } - else - { + } else { std::cout << "Number of positive divisors is : "; std::cout << number_of_positive_divisors(n) << std::endl; } diff --git a/math/power_for_huge_numbers.cpp b/math/power_for_huge_numbers.cpp index 1f969f89d10..301767d666e 100644 --- a/math/power_for_huge_numbers.cpp +++ b/math/power_for_huge_numbers.cpp @@ -22,15 +22,13 @@ * @param res large number representation using array * @param res_size number of digits in `res` */ -int multiply(int x, int res[], int res_size) -{ +int multiply(int x, int res[], int res_size) { // Initialize carry int carry = 0; // One by one multiply n with // individual digits of res[] - for (int i = 0; i < res_size; i++) - { + for (int i = 0; i < res_size; i++) { int prod = res[i] * x + carry; // Store last digit of @@ -43,8 +41,7 @@ int multiply(int x, int res[], int res_size) // Put carry in res and // increase result size - while (carry) - { + while (carry) { res[res_size] = carry % 10; carry = carry / 10; res_size++; @@ -56,11 +53,9 @@ int multiply(int x, int res[], int res_size) * @param x base * @param n exponent */ -void power(int x, int n) -{ +void power(int x, int n) { // printing value "1" for power = 0 - if (n == 0) - { + if (n == 0) { std::cout << "1"; return; } @@ -70,8 +65,7 @@ void power(int x, int n) int temp = x; // Initialize result - while (temp != 0) - { + while (temp != 0) { res[res_size++] = temp % 10; temp = temp / 10; } @@ -85,8 +79,7 @@ void power(int x, int n) } /** Main function */ -int main() -{ +int main() { int exponent, base; std::cout << "Enter base "; std::cin >> base; diff --git a/math/prime_factorization.cpp b/math/prime_factorization.cpp index c650497e2d1..001c2c3c360 100644 --- a/math/prime_factorization.cpp +++ b/math/prime_factorization.cpp @@ -20,43 +20,35 @@ std::vector> factors; /** Calculating prime number upto a given range */ -void SieveOfEratosthenes(int N) -{ +void SieveOfEratosthenes(int N) { // initializes the array isprime memset(isprime, true, sizeof isprime); - for (int i = 2; i <= N; i++) - { - if (isprime[i]) - { + for (int i = 2; i <= N; i++) { + if (isprime[i]) { for (int j = 2 * i; j <= N; j += i) isprime[j] = false; } } - for (int i = 2; i <= N; i++) - { + for (int i = 2; i <= N; i++) { if (isprime[i]) prime_numbers.push_back(i); } } /** Prime factorization of a number */ -void prime_factorization(int num) -{ +void prime_factorization(int num) { int number = num; - for (int i = 0; prime_numbers[i] <= num; i++) - { + for (int i = 0; prime_numbers[i] <= num; i++) { int count = 0; // termination condition - if (number == 1) - { + if (number == 1) { break; } - while (number % prime_numbers[i] == 0) - { + while (number % prime_numbers[i] == 0) { count++; number = number / prime_numbers[i]; } @@ -67,8 +59,7 @@ void prime_factorization(int num) } /** Main program */ -int main() -{ +int main() { int num; std::cout << "\t\tComputes the prime factorization\n\n"; std::cout << "Type in a number: "; @@ -79,8 +70,7 @@ int main() prime_factorization(num); // Prime factors with their powers in the given number in new line - for (auto it : factors) - { + for (auto it : factors) { std::cout << it.first << " " << it.second << std::endl; } diff --git a/math/prime_numbers.cpp b/math/prime_numbers.cpp index b3a52a1042d..4dd54f13657 100644 --- a/math/prime_numbers.cpp +++ b/math/prime_numbers.cpp @@ -9,15 +9,12 @@ /** Generate an increasingly large number of primes * and store in a list */ -std::vector primes(int max) -{ +std::vector primes(int max) { max++; std::vector res; std::vector numbers(max, false); - for (int i = 2; i < max; i++) - { - if (!numbers[i]) - { + for (int i = 2; i < max; i++) { + if (!numbers[i]) { for (int j = i; j < max; j += i) numbers[j] = true; res.push_back(i); } @@ -26,8 +23,7 @@ std::vector primes(int max) } /** main function */ -int main() -{ +int main() { std::cout << "Calculate primes up to:\n>> "; int n; std::cin >> n; diff --git a/math/primes_up_to_billion.cpp b/math/primes_up_to_billion.cpp index 6c02b9089f0..4fb79a15e7c 100644 --- a/math/primes_up_to_billion.cpp +++ b/math/primes_up_to_billion.cpp @@ -10,15 +10,12 @@ char prime[100000000]; /** Perform Sieve algorithm */ -void Sieve(int64_t n) -{ +void Sieve(int64_t n) { memset(prime, '1', sizeof(prime)); // intitize '1' to every index prime[0] = '0'; // 0 is not prime prime[1] = '0'; // 1 is not prime - for (int p = 2; p * p <= n; p++) - { - if (prime[p] == '1') - { + for (int p = 2; p * p <= n; p++) { + if (prime[p] == '1') { for (int i = p * p; i <= n; i += p) prime[i] = '0'; // set all multiples of p to false } @@ -26,8 +23,7 @@ void Sieve(int64_t n) } /** Main function */ -int main() -{ +int main() { Sieve(100000000); int64_t n; std::cin >> n; // 10006187 diff --git a/math/sieve_of_eratosthenes.cpp b/math/sieve_of_eratosthenes.cpp index 90ad8bc40b2..d8fa705313e 100644 --- a/math/sieve_of_eratosthenes.cpp +++ b/math/sieve_of_eratosthenes.cpp @@ -22,16 +22,12 @@ bool isprime[MAX]; * This is the function that finds the primes and eliminates * the multiples. */ -void sieve(uint32_t N) -{ +void sieve(uint32_t N) { isprime[0] = false; isprime[1] = false; - for (uint32_t i = 2; i <= N; i++) - { - if (isprime[i]) - { - for (uint32_t j = (i << 1); j <= N; j += i) - { + for (uint32_t i = 2; i <= N; i++) { + if (isprime[i]) { + for (uint32_t j = (i << 1); j <= N; j += i) { isprime[j] = false; } } @@ -41,12 +37,9 @@ void sieve(uint32_t N) /** * This function prints out the primes to STDOUT */ -void print(uint32_t N) -{ - for (uint32_t i = 1; i <= N; i++) - { - if (isprime[i]) - { +void print(uint32_t N) { + for (uint32_t i = 1; i <= N; i++) { + if (isprime[i]) { std::cout << i << ' '; } } @@ -56,17 +49,14 @@ void print(uint32_t N) /** * Initialize the array */ -void init() -{ - for (uint32_t i = 1; i < MAX; i++) - { +void init() { + for (uint32_t i = 1; i < MAX; i++) { isprime[i] = true; } } /** main function */ -int main() -{ +int main() { uint32_t N = 100; init(); sieve(N); diff --git a/math/sqrt_double.cpp b/math/sqrt_double.cpp index ffc83998ab5..1521b500a19 100644 --- a/math/sqrt_double.cpp +++ b/math/sqrt_double.cpp @@ -13,10 +13,8 @@ /** Bisection method implemented for the function \f$x^2-a=0\f$ * whose roots are \f$\pm\sqrt{a}\f$ and only the positive root is returned. */ -double Sqrt(double a) -{ - if (a > 0 && a < 1) - { +double Sqrt(double a) { + if (a > 0 && a < 1) { return 1 / Sqrt(1 / a); } double l = 0, r = a; @@ -26,17 +24,12 @@ double Sqrt(double a) double epsilon = 1e-12; */ double epsilon = 1e-12; - while (l <= r) - { + while (l <= r) { double mid = (l + r) / 2; - if (mid * mid > a) - { + if (mid * mid > a) { r = mid; - } - else - { - if (a - mid * mid < epsilon) - { + } else { + if (a - mid * mid < epsilon) { return mid; } l = mid; @@ -46,8 +39,7 @@ double Sqrt(double a) } /** main function */ -int main() -{ +int main() { double n{}; std::cin >> n; assert(n >= 0); diff --git a/math/string_fibonacci.cpp b/math/string_fibonacci.cpp index 401b04d2da8..eb9b6d7e1a7 100644 --- a/math/string_fibonacci.cpp +++ b/math/string_fibonacci.cpp @@ -21,50 +21,41 @@ * \param [in] b second number in string to add * \returns sum as a std::string */ -std::string add(std::string a, std::string b) -{ +std::string add(std::string a, std::string b) { std::string temp = ""; // carry flag int carry = 0; // fills up with zeros - while (a.length() < b.length()) - { + while (a.length() < b.length()) { a = "0" + a; } // fills up with zeros - while (b.length() < a.length()) - { + while (b.length() < a.length()) { b = "0" + b; } // adds the numbers a and b - for (int i = a.length() - 1; i >= 0; i--) - { + for (int i = a.length() - 1; i >= 0; i--) { char val = static_cast(((a[i] - 48) + (b[i] - 48)) + 48 + carry); - if (val > 57) - { + if (val > 57) { carry = 1; val -= 10; - } - else - { + } else { carry = 0; } temp = val + temp; } // processes the carry flag - if (carry == 1) - { + if (carry == 1) { temp = "1" + temp; } // removes leading zeros. - while (temp[0] == '0' && temp.length() > 1) - { + while (temp[0] == '0' && temp.length() > 1) { temp = temp.substr(1); } @@ -74,13 +65,11 @@ std::string add(std::string a, std::string b) /** Fibonacci iterator * \param [in] n n^th Fibonacci number */ -void fib_Accurate(uint64_t n) -{ +void fib_Accurate(uint64_t n) { std::string tmp = ""; std::string fibMinus1 = "1"; std::string fibMinus2 = "0"; - for (uint64_t i = 0; i < n; i++) - { + for (uint64_t i = 0; i < n; i++) { tmp = add(fibMinus1, fibMinus2); fibMinus2 = fibMinus1; fibMinus1 = tmp; @@ -89,8 +78,7 @@ void fib_Accurate(uint64_t n) } /** main function */ -int main() -{ +int main() { int n; std::cout << "Enter whatever number N you want to find the fibonacci of\n"; std::cin >> n; diff --git a/operations_on_datastructures/array_left_rotation.cpp b/operations_on_datastructures/array_left_rotation.cpp index 444738360a5..7b8f7f279ad 100644 --- a/operations_on_datastructures/array_left_rotation.cpp +++ b/operations_on_datastructures/array_left_rotation.cpp @@ -1,7 +1,6 @@ #include using namespace std; -int main() -{ +int main() { int n, k; cout << "Enter size of array=\t"; cin >> n; @@ -9,29 +8,22 @@ int main() cin >> k; int a[n]; cout << "Enter elements of array=\t"; - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { cin >> a[i]; } int temp = 0; - for (int i = 0; i < k; i++) - { + for (int i = 0; i < k; i++) { temp = a[0]; - for (int j = 0; j < n; j++) - { - if (j == n - 1) - { + for (int j = 0; j < n; j++) { + if (j == n - 1) { a[n - 1] = temp; - } - else - { + } else { a[j] = a[j + 1]; } } } cout << "Your rotated array is=\t"; - for (int j = 0; j < n; j++) - { + for (int j = 0; j < n; j++) { cout << a[j] << " "; } getchar(); diff --git a/operations_on_datastructures/array_right_rotation.cpp b/operations_on_datastructures/array_right_rotation.cpp index 5077d2d74cb..8b01a2003dd 100644 --- a/operations_on_datastructures/array_right_rotation.cpp +++ b/operations_on_datastructures/array_right_rotation.cpp @@ -1,7 +1,6 @@ #include using namespace std; -int main() -{ +int main() { int n, k; cout << "Enter size of array=\t"; cin >> n; @@ -11,24 +10,18 @@ int main() cout << "Enter elements of array=\t"; for (int i = 0; i < n; i++) cin >> a[i]; int temp = 0; - for (int i = 0; i < k; i++) - { + for (int i = 0; i < k; i++) { temp = a[n - 1]; - for (int j = n - 1; j >= 0; j--) - { - if (j == 0) - { + for (int j = n - 1; j >= 0; j--) { + if (j == 0) { a[j] = temp; - } - else - { + } else { a[j] = a[j - 1]; } } } cout << "Your rotated array is=\t"; - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { cout << a[i] << " "; } } diff --git a/operations_on_datastructures/circular_linked_list.cpp b/operations_on_datastructures/circular_linked_list.cpp index 2fddd3b7b6d..1119bb5e7f3 100644 --- a/operations_on_datastructures/circular_linked_list.cpp +++ b/operations_on_datastructures/circular_linked_list.cpp @@ -1,31 +1,25 @@ #include using namespace std; -struct node -{ +struct node { int val; node *next; }; node *start; -void insert(int x) -{ +void insert(int x) { node *t = start; - if (start != NULL) - { - while (t->next != start) - { + if (start != NULL) { + while (t->next != start) { t = t->next; } node *n = new node; t->next = n; n->val = x; n->next = start; - } - else - { + } else { node *n = new node; n->val = x; start = n; @@ -33,12 +27,10 @@ void insert(int x) } } -void remove(int x) -{ +void remove(int x) { node *t = start; node *p; - while (t->val != x) - { + while (t->val != x) { p = t; t = t->next; } @@ -46,49 +38,40 @@ void remove(int x) delete t; } -void search(int x) -{ +void search(int x) { node *t = start; int found = 0; - while (t->next != start) - { - if (t->val == x) - { + while (t->next != start) { + if (t->val == x) { cout << "\nFound"; found = 1; break; } t = t->next; } - if (found == 0) - { + if (found == 0) { cout << "\nNot Found"; } } -void show() -{ +void show() { node *t = start; - do - { + do { cout << t->val << "\t"; t = t->next; } while (t != start); } -int main() -{ +int main() { int choice, x; - do - { + do { cout << "\n1. Insert"; cout << "\n2. Delete"; cout << "\n3. Search"; cout << "\n4. Print"; cout << "\n\nEnter you choice : "; cin >> choice; - switch (choice) - { + switch (choice) { case 1: cout << "\nEnter the element to be inserted : "; cin >> x; diff --git a/operations_on_datastructures/circular_queue_using_array.cpp b/operations_on_datastructures/circular_queue_using_array.cpp index cf6e39dd597..e0e049611da 100644 --- a/operations_on_datastructures/circular_queue_using_array.cpp +++ b/operations_on_datastructures/circular_queue_using_array.cpp @@ -6,65 +6,49 @@ int front = 0; int rear = 0; int count = 0; -void Enque(int x) -{ - if (count == 10) - { +void Enque(int x) { + if (count == 10) { cout << "\nOverflow"; - } - else - { + } else { queue[rear] = x; rear = (rear + 1) % 10; count++; } } -void Deque() -{ - if (front == rear) - { +void Deque() { + if (front == rear) { cout << "\nUnderflow"; } - else - { + else { cout << "\n" << queue[front] << " deleted"; front = (front + 1) % 10; count--; } } -void show() -{ - for (int i = 0; i < count; i++) - { +void show() { + for (int i = 0; i < count; i++) { cout << queue[(i + front) % 10] << "\t"; } } -int main() -{ +int main() { int ch, x; - do - { + do { cout << "\n1. Enque"; cout << "\n2. Deque"; cout << "\n3. Print"; cout << "\nEnter Your Choice : "; cin >> ch; - if (ch == 1) - { + if (ch == 1) { cout << "\nInsert : "; cin >> x; Enque(x); - } - else if (ch == 2) - { + } else if (ch == 2) { Deque(); - } - else if (ch == 3) - { + } else if (ch == 3) { show(); } } while (ch != 0); diff --git a/operations_on_datastructures/get_size_of_linked_list.cpp b/operations_on_datastructures/get_size_of_linked_list.cpp index 0f22967c293..84f8db07fb8 100644 --- a/operations_on_datastructures/get_size_of_linked_list.cpp +++ b/operations_on_datastructures/get_size_of_linked_list.cpp @@ -1,7 +1,6 @@ #include -class Node -{ +class Node { public: int val; Node *next; @@ -9,23 +8,19 @@ class Node Node(int v, Node *n) : val(v), next(n) {} // Default constructor for Node }; -int getSize(Node *root) -{ - if (root == NULL) - { +int getSize(Node *root) { + if (root == NULL) { return 0; } // Each node will return 1 so the total adds up to be the size return 1 + getSize(root->next); } -int main() -{ +int main() { Node *myList = new Node(0, NULL); // Initializes the LinkedList Node *temp = myList; // Creates a linked lists of total size 10, numbered 1 - 10 - for (int i = 1; i < 10; i++) - { + for (int i = 1; i < 10; i++) { temp->next = new Node(i, NULL); temp = temp->next; } diff --git a/operations_on_datastructures/intersection_of_2_arrays.cpp b/operations_on_datastructures/intersection_of_2_arrays.cpp index df83c9f2139..8a3b27edfef 100644 --- a/operations_on_datastructures/intersection_of_2_arrays.cpp +++ b/operations_on_datastructures/intersection_of_2_arrays.cpp @@ -1,6 +1,5 @@ #include -int main() -{ +int main() { int i, j, m, n; cout << "Enter size of array 1:"; cin >> m; @@ -13,14 +12,12 @@ int main() for (i = 0; i < n; i++) cin >> b[i]; i = 0; j = 0; - while ((i < m) && (j < n)) - { + while ((i < m) && (j < n)) { if (a[i] < b[j]) i++; else if (a[i] > b[j]) j++; - else - { + else { cout << a[i++] << " "; j++; } diff --git a/operations_on_datastructures/reverse_a_linked_list_using_recusion.cpp b/operations_on_datastructures/reverse_a_linked_list_using_recusion.cpp index 4fe6d291523..b9540d951a5 100644 --- a/operations_on_datastructures/reverse_a_linked_list_using_recusion.cpp +++ b/operations_on_datastructures/reverse_a_linked_list_using_recusion.cpp @@ -1,30 +1,24 @@ #include using namespace std; -struct node -{ +struct node { int val; node *next; }; node *start; -void insert(int x) -{ +void insert(int x) { node *t = start; - if (start != NULL) - { - while (t->next != NULL) - { + if (start != NULL) { + while (t->next != NULL) { t = t->next; } node *n = new node; t->next = n; n->val = x; n->next = NULL; - } - else - { + } else { node *n = new node; n->val = x; n->next = NULL; @@ -32,35 +26,28 @@ void insert(int x) } } -void reverse(node *p, node *q) -{ - if (q->next == NULL) - { +void reverse(node *p, node *q) { + if (q->next == NULL) { q->next = p; p->next = NULL; start = q; return; - } - else - { + } else { reverse(q, q->next); q->next = p; p->next = NULL; } } -void show() -{ +void show() { node *t = start; - while (t != NULL) - { + while (t != NULL) { cout << t->val << "\t"; t = t->next; } } -int main() -{ +int main() { insert(1); insert(2); insert(3); diff --git a/operations_on_datastructures/selectionsortlinkedlist.cpp b/operations_on_datastructures/selectionsortlinkedlist.cpp index 550928d01d6..0e8e80def7c 100644 --- a/operations_on_datastructures/selectionsortlinkedlist.cpp +++ b/operations_on_datastructures/selectionsortlinkedlist.cpp @@ -2,24 +2,20 @@ using namespace std; // node defined -class node -{ +class node { public: int data; node *link; - node(int d) - { + node(int d) { data = d; link = NULL; } }; // printing the linked list -void print(node *head) -{ +void print(node *head) { node *current = head; - while (current != NULL) - { + while (current != NULL) { cout << current->data << " "; current = current->link; } @@ -27,18 +23,15 @@ void print(node *head) } // creating the linked list with 'n' nodes -node *createlist(int n) -{ +node *createlist(int n) { node *head = NULL; node *t = NULL; - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { node *temp = NULL; int num; cin >> num; temp = new node(num); - if (head == NULL) - { + if (head == NULL) { head = temp; t = temp; continue; @@ -51,8 +44,7 @@ node *createlist(int n) } // performing selection sort on the linked list in an iterative manner -void my_selection_sort_linked_list(node *&head) -{ +void my_selection_sort_linked_list(node *&head) { node *min = head; // throughout the algorithm 'min' is used to denote the // node with min value out of all the nodes left for // scanning while scanning if we find a node 'X' with @@ -61,7 +53,7 @@ void my_selection_sort_linked_list(node *&head) node *current = min->link; // 'current' refers to the current node we are scanning node *previous = min; //'previous' refers to the node that is previous to - //the current node + // the current node node *temp = NULL; // 'temp' in this algo is used to point to the last node of the // sorted part of the linked list. @@ -102,8 +94,8 @@ void my_selection_sort_linked_list(node *&head) current->link = previous; min = current; current = previous->link; - } - else // if the 'previous' is not pointing to the 'min' node + } else // if the 'previous' is not pointing to the 'min' + // node { // Update the pointers head = current; // update the head pointer with the @@ -113,8 +105,8 @@ void my_selection_sort_linked_list(node *&head) min = current; current = previous->link; } - } - else // if 'temp' is not NULL, i.e., its not the 1st iteration + } else // if 'temp' is not NULL, i.e., its not the 1st + // iteration { temp->link = current; previous->link = current->link; @@ -122,9 +114,8 @@ void my_selection_sort_linked_list(node *&head) min = current; current = previous->link; } - } - else // if the current node is greater than min, just move the - // previous and the current pointer a step further + } else // if the current node is greater than min, just move the + // previous and the current pointer a step further { previous = previous->link; current = current->link; @@ -132,8 +123,8 @@ void my_selection_sort_linked_list(node *&head) } // update the pointers. Set 'temp' to the last node in the sorted part. - // Make 'min' move a step further so that 'min' points to the 1st node of - // the unsorted part start the iteration again + // Make 'min' move a step further so that 'min' points to the 1st node + // of the unsorted part start the iteration again temp = min; min = min->link; previous = min; @@ -163,8 +154,7 @@ void my_selection_sort_linked_list(node *&head) // original list is : 5 3 4 1 -2 -4 // sorted list is : -4 -2 1 3 4 5 -int main() -{ +int main() { node *head = NULL; int n; cout << "enter the no. of nodes : "; // taking input from user about the diff --git a/operations_on_datastructures/union_of_2_arrays.cpp b/operations_on_datastructures/union_of_2_arrays.cpp index 45845f341e8..cdacf1d2e7e 100644 --- a/operations_on_datastructures/union_of_2_arrays.cpp +++ b/operations_on_datastructures/union_of_2_arrays.cpp @@ -1,6 +1,5 @@ #include -int main() -{ +int main() { int m, n, i = 0, j = 0; cout << "Enter size of both arrays:"; cin >> m >> n; @@ -12,14 +11,12 @@ int main() for (i = 0; i < n; i++) cin >> b[i]; i = 0; j = 0; - while ((i < m) && (j < n)) - { + while ((i < m) && (j < n)) { if (a[i] < b[j]) cout << a[i++] << " "; else if (a[i] > b[j]) cout << b[j++] << " "; - else - { + else { cout << a[i++]; j++; } diff --git a/others/buzz_number.cpp b/others/buzz_number.cpp index 712b79401c5..ed9fc5f2888 100644 --- a/others/buzz_number.cpp +++ b/others/buzz_number.cpp @@ -6,12 +6,10 @@ #include /** main function */ -int main() -{ +int main() { int n, t; std::cin >> t; - while (t--) - { + while (t--) { std::cin >> n; if ((n % 7 == 0) || (n % 10 == 7)) std::cout << n << " is a buzz number" << std::endl; diff --git a/others/decimal_to_binary.cpp b/others/decimal_to_binary.cpp index 32616944f2d..11ce064a538 100644 --- a/others/decimal_to_binary.cpp +++ b/others/decimal_to_binary.cpp @@ -8,12 +8,10 @@ * This method converts the bit representation and stores it as a decimal * number. */ -void method1(int number) -{ +void method1(int number) { int remainder, binary = 0, var = 1; - do - { + do { remainder = number % 2; number = number / 2; binary = binary + (remainder * var); @@ -26,13 +24,11 @@ void method1(int number) * This method stores each bit value from LSB to MSB and then prints them back * from MSB to LSB */ -void method2(int number) -{ +void method2(int number) { int num_bits = 0; char bit_string[50]; - do - { + do { bool bit = number & 0x01; // get last bit if (bit) bit_string[num_bits++] = '1'; @@ -47,8 +43,7 @@ void method2(int number) std::cout << std::endl; } -int main() -{ +int main() { int number; std::cout << "Enter a number:"; std::cin >> number; diff --git a/others/decimal_to_hexadecimal.cpp b/others/decimal_to_hexadecimal.cpp index f0a521db6f7..a3e544f49f8 100644 --- a/others/decimal_to_hexadecimal.cpp +++ b/others/decimal_to_hexadecimal.cpp @@ -8,8 +8,7 @@ /** * Main program */ -int main(void) -{ +int main(void) { int valueToConvert = 0; // Holds user input int hexArray[8]; // Contains hex values backwards int i = 0; // counter @@ -20,8 +19,7 @@ int main(void) std::cin >> valueToConvert; // Stores value into valueToConvert via user input - while (valueToConvert > 15) - { // Dec to Hex Algorithm + while (valueToConvert > 15) { // Dec to Hex Algorithm hexArray[i++] = valueToConvert % 16; // Gets remainder valueToConvert /= 16; // valueToConvert >>= 4; // This will divide by 2^4=16 and is faster diff --git a/others/decimal_to_roman_numeral.cpp b/others/decimal_to_roman_numeral.cpp index fbcbaa2322b..ad4aa32c5ad 100644 --- a/others/decimal_to_roman_numeral.cpp +++ b/others/decimal_to_roman_numeral.cpp @@ -12,8 +12,7 @@ /** This functions fills a string with character c, n times and returns it * @note This can probably be replace by `memcpy` function. */ -std::string fill(char c, int n) -{ +std::string fill(char c, int n) { std::string s = ""; while (n--) s += c; return s; @@ -22,8 +21,7 @@ std::string fill(char c, int n) /** to convert to lowercase Roman Numeral * the function works recursively */ -std::string tolowerRoman(int n) -{ +std::string tolowerRoman(int n) { if (n < 4) return fill('i', n); if (n < 6) @@ -57,8 +55,7 @@ std::string tolowerRoman(int n) /** to convert to uppercase Roman Numeral * the function works recursively */ -std::string toupperRoman(int n) -{ +std::string toupperRoman(int n) { if (n < 4) return fill('I', n); if (n < 6) @@ -90,8 +87,7 @@ std::string toupperRoman(int n) } /** main function */ -int main() -{ +int main() { int n; std::cout << "\t\tRoman numbers converter\n\n"; std::cout << "Type in decimal number between 0 up to 4000 (exclusive): "; diff --git a/others/fast_interger_input.cpp b/others/fast_interger_input.cpp index a71e807dd89..87963c9ad88 100644 --- a/others/fast_interger_input.cpp +++ b/others/fast_interger_input.cpp @@ -8,8 +8,7 @@ /** Function to read the number from stdin. The function reads input until a non * numeric character is entered. */ -void fastinput(int *number) -{ +void fastinput(int *number) { // variable to indicate sign of input integer bool negative = false; register int c; @@ -17,8 +16,7 @@ void fastinput(int *number) // extract current character from buffer c = std::getchar(); - if (c == '-') - { + if (c == '-') { // number is negative negative = true; @@ -38,8 +36,7 @@ void fastinput(int *number) } /** Main function */ -int main() -{ +int main() { int number; fastinput(&number); std::cout << number << std::endl; diff --git a/others/happy_number.cpp b/others/happy_number.cpp index 494891e3b4e..b1debaa54db 100644 --- a/others/happy_number.cpp +++ b/others/happy_number.cpp @@ -11,13 +11,10 @@ * \returns true if happy else false */ template -bool is_happy(T n) -{ - T s = 0; // stores sum of digits - while (n > 9) - { // while number is > 9, there are more than 1 digit - while (n != 0) - { // get digit +bool is_happy(T n) { + T s = 0; // stores sum of digits + while (n > 9) { // while number is > 9, there are more than 1 digit + while (n != 0) { // get digit T d = n % 10; s += d; n /= 10; @@ -29,8 +26,7 @@ bool is_happy(T n) } /** Main function */ -int main() -{ +int main() { int n; std::cout << "Enter a number:"; std::cin >> n; diff --git a/others/matrix_exponentiation.cpp b/others/matrix_exponentiation.cpp index 78daca8ec74..d44d225937c 100644 --- a/others/matrix_exponentiation.cpp +++ b/others/matrix_exponentiation.cpp @@ -58,15 +58,11 @@ vector a, b, c; * \result matrix of dimension (m\f$\times\f$q) */ vector> multiply(const vector> &A, - const vector> &B) -{ + const vector> &B) { vector> C(k + 1, vector(k + 1)); - for (ll i = 1; i <= k; i++) - { - for (ll j = 1; j <= k; j++) - { - for (ll z = 1; z <= k; z++) - { + for (ll i = 1; i <= k; i++) { + for (ll j = 1; j <= k; j++) { + for (ll z = 1; z <= k; z++) { C[i][j] = (C[i][j] + (A[i][z] * B[z][j]) % MOD) % MOD; } } @@ -80,16 +76,12 @@ vector> multiply(const vector> &A, * \param [in] p exponent * \return matrix of same dimension as A */ -vector> power(const vector> &A, ll p) -{ +vector> power(const vector> &A, ll p) { if (p == 1) return A; - if (p % 2 == 1) - { + if (p % 2 == 1) { return multiply(A, power(A, p - 1)); - } - else - { + } else { vector> X = power(A, p / 2); return multiply(X, X); } @@ -99,8 +91,7 @@ vector> power(const vector> &A, ll p) * \param[in] n \f$n^\text{th}\f$ Fibonacci number * \return \f$n^\text{th}\f$ Fibonacci number */ -ll ans(ll n) -{ +ll ans(ll n) { if (n == 0) return 0; if (n <= k) @@ -111,12 +102,9 @@ ll ans(ll n) // Transpose matrix vector> T(k + 1, vector(k + 1)); - for (ll i = 1; i <= k; i++) - { - for (ll j = 1; j <= k; j++) - { - if (i < k) - { + for (ll i = 1; i <= k; i++) { + for (ll j = 1; j <= k; j++) { + if (i < k) { if (j == i + 1) T[i][j] = 1; else @@ -131,31 +119,26 @@ ll ans(ll n) // T*F1 ll res = 0; - for (ll i = 1; i <= k; i++) - { + for (ll i = 1; i <= k; i++) { res = (res + (T[1][i] * F1[i]) % MOD) % MOD; } return res; } /** Main function */ -int main() -{ +int main() { cin.tie(0); cout.tie(0); ll t; cin >> t; ll i, j, x; - while (t--) - { + while (t--) { cin >> k; - for (i = 0; i < k; i++) - { + for (i = 0; i < k; i++) { cin >> x; b.pb(x); } - for (i = 0; i < k; i++) - { + for (i = 0; i < k; i++) { cin >> x; c.pb(x); } diff --git a/others/palindrome_of_number.cpp b/others/palindrome_of_number.cpp index d6ed3fc7080..66401ff966a 100644 --- a/others/palindrome_of_number.cpp +++ b/others/palindrome_of_number.cpp @@ -16,8 +16,7 @@ #endif /** Main function */ -int main() -{ +int main() { int num; std::cout << "Enter number = "; std::cin >> num; diff --git a/others/paranthesis_matching.cpp b/others/paranthesis_matching.cpp index 95a9e11003d..2a6358d94e7 100644 --- a/others/paranthesis_matching.cpp +++ b/others/paranthesis_matching.cpp @@ -33,10 +33,8 @@ char pop() { return stack[top--]; } /** return opening paranthesis corresponding to the close paranthesis * @param[in] ch closed paranthesis character */ -char opening(char ch) -{ - switch (ch) - { +char opening(char ch) { + switch (ch) { case '}': return '{'; case ']': @@ -49,37 +47,27 @@ char opening(char ch) return '\0'; } -int main() -{ +int main() { std::string exp; int valid = 1, i = 0; std::cout << "Enter The Expression : "; std::cin >> exp; - while (valid == 1 && i < exp.length()) - { - if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[' || exp[i] == '<') - { + while (valid == 1 && i < exp.length()) { + if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[' || exp[i] == '<') { push(exp[i]); - } - else if (top >= 0 && stack[top] == opening(exp[i])) - { + } else if (top >= 0 && stack[top] == opening(exp[i])) { pop(); - } - else - { + } else { valid = 0; } i++; } // makes sure the stack is empty after processsing (above) - if (valid == 1 && top == -1) - { + if (valid == 1 && top == -1) { std::cout << "\nCorrect Expression"; - } - else - { + } else { std::cout << "\nWrong Expression"; } diff --git a/others/pascal_triangle.cpp b/others/pascal_triangle.cpp index 814b9a14244..4ea58f3f1e4 100644 --- a/others/pascal_triangle.cpp +++ b/others/pascal_triangle.cpp @@ -15,12 +15,9 @@ * \param [in] arr 2D-array containing Pascal numbers * \param [in] n depth of Pascal triangle to print */ -void show_pascal(int **arr, int n) -{ - for (int i = 0; i < n; ++i) - { - for (int j = 0; j < n + i; ++j) - { +void show_pascal(int **arr, int n) { + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n + i; ++j) { if (arr[i][j] == 0) std::cout << std::setw(4) << " "; else @@ -36,12 +33,9 @@ void show_pascal(int **arr, int n) * \param [in] n depth of Pascal triangle to print * \result arr pointer returned */ -int **pascal_triangle(int **arr, int n) -{ - for (int i = 0; i < n; ++i) - { - for (int j = n - i - 1; j < n + i; ++j) - { +int **pascal_triangle(int **arr, int n) { + for (int i = 0; i < n; ++i) { + for (int j = n - i - 1; j < n + i; ++j) { if (j == n - i - 1 || j == n + i - 1) arr[i][j] = 1; // The edge of the Pascal triangle goes in 1 else @@ -55,8 +49,7 @@ int **pascal_triangle(int **arr, int n) /** * main function */ -int main() -{ +int main() { int n = 0; std::cout << "Set Pascal's Triangle Height" << std::endl; @@ -64,8 +57,7 @@ int main() // memory allocation (Assign two-dimensional array to store Pascal triangle) int **arr = new int *[n]; - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { arr[i] = new int[2 * n - 1]; memset(arr[i], 0, sizeof(int) * (2 * n - 1)); } @@ -74,8 +66,7 @@ int main() show_pascal(arr, n); // deallocation - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { delete[] arr[i]; } delete[] arr; diff --git a/others/primality_test.cpp b/others/primality_test.cpp index 16700ec4a80..faec6589cff 100644 --- a/others/primality_test.cpp +++ b/others/primality_test.cpp @@ -15,14 +15,12 @@ * \param[in] number number to check * \returns true if prime else false */ -bool IsPrime(int number) -{ +bool IsPrime(int number) { if (((!(number & 1)) && number != 2) || (number < 2) || (number % 3 == 0 && number != 3)) return false; - for (int k = 1; 36 * k * k - 12 * k < number; ++k) - { + for (int k = 1; 36 * k * k - 12 * k < number; ++k) { if ((number % (6 * k + 1) == 0) || (number % (6 * k - 1) == 0)) return false; } @@ -30,8 +28,7 @@ bool IsPrime(int number) } /** main function */ -int main() -{ +int main() { // Main Function std::cout << "Enter the value of n to check if Prime\n"; int n; diff --git a/others/smallest_circle.cpp b/others/smallest_circle.cpp index 5842a33c8ae..9ee4353eb4e 100644 --- a/others/smallest_circle.cpp +++ b/others/smallest_circle.cpp @@ -12,8 +12,7 @@ #include /** Define a point */ -struct Point -{ +struct Point { double x, /**< abscissa */ y; /**< ordinate */ @@ -21,8 +20,7 @@ struct Point * \param [in] a absicca (default = 0.0) * \param [in] b ordinate (default = 0.0) */ - explicit Point(double a = 0.f, double b = 0.f) - { + explicit Point(double a = 0.f, double b = 0.f) { x = a; y = b; } @@ -36,8 +34,7 @@ struct Point * \param [in] B point B * \return ditance */ -double LenghtLine(const Point &A, const Point &B) -{ +double LenghtLine(const Point &A, const Point &B) { double dx = B.x - A.x; double dy = B.y - A.y; return std::sqrt((dx * dx) + (dy * dy)); @@ -54,8 +51,7 @@ double LenghtLine(const Point &A, const Point &B) * \param [in] C vertex C * \returns area of triangle */ -double TriangleArea(const Point &A, const Point &B, const Point &C) -{ +double TriangleArea(const Point &A, const Point &B, const Point &C) { double a = LenghtLine(A, B); double b = LenghtLine(B, C); double c = LenghtLine(C, A); @@ -73,10 +69,8 @@ double TriangleArea(const Point &A, const Point &B, const Point &C) * \returns True if P lies on or within the circle * \returns False if P lies outside the circle */ -bool PointInCircle(const std::vector &P, const Point &Center, double R) -{ - for (size_t i = 0; i < P.size(); i++) - { +bool PointInCircle(const std::vector &P, const Point &Center, double R) { + for (size_t i = 0; i < P.size(); i++) { if (LenghtLine(P[i], Center) > R) return false; } @@ -90,8 +84,7 @@ bool PointInCircle(const std::vector &P, const Point &Center, double R) * \param [in] P vector of points * \returns radius of the circle */ -double circle(const std::vector &P) -{ +double circle(const std::vector &P) { double minR = INFINITY; double R; Point C; @@ -103,8 +96,7 @@ double circle(const std::vector &P) // for every subsequent point in the list for (size_t j = i + 1; j < P.size(); j++) // for every subsequent point in the list - for (size_t k = j + 1; k < P.size(); k++) - { + for (size_t k = j + 1; k < P.size(); k++) { // here, we now have picked three points from the given set of // points that we can use // viz., P[i], P[j] and P[k] @@ -129,12 +121,10 @@ double circle(const std::vector &P) R = (LenghtLine(P[i], P[j]) * LenghtLine(P[j], P[k]) * LenghtLine(P[k], P[i])) / (4 * TriangleArea(P[i], P[j], P[k])); - if (!PointInCircle(P, C, R)) - { + if (!PointInCircle(P, C, R)) { continue; } - if (R <= minR) - { + if (R <= minR) { minR = R; minC = C; } @@ -143,18 +133,15 @@ double circle(const std::vector &P) // for each point in the list for (size_t i = 0; i < P.size() - 1; i++) // for every subsequent point in the list - for (size_t j = i + 1; j < P.size(); j++) - { + for (size_t j = i + 1; j < P.size(); j++) { // check for diameterically opposite points C.x = (P[i].x + P[j].x) / 2; C.y = (P[i].y + P[j].y) / 2; R = LenghtLine(C, P[i]); - if (!PointInCircle(P, C, R)) - { + if (!PointInCircle(P, C, R)) { continue; } - if (R <= minR) - { + if (R <= minR) { minR = R; minC = C; } @@ -168,8 +155,7 @@ double circle(const std::vector &P) * \n radius 3.318493136080724 * \n centre at (3.0454545454545454, 1.3181818181818181) */ -void test() -{ +void test() { std::vector Pv; Pv.push_back(Point(0, 0)); Pv.push_back(Point(5, 4)); @@ -184,8 +170,7 @@ void test() * \n radius 1.4142135623730951 * \n centre at (1.0, 1.0) */ -void test2() -{ +void test2() { std::vector Pv; Pv.push_back(Point(0, 0)); Pv.push_back(Point(0, 2)); @@ -200,8 +185,7 @@ void test2() * \n centre at (2.142857142857143, 1.7857142857142856) * @todo This test fails */ -void test3() -{ +void test3() { std::vector Pv; Pv.push_back(Point(0.5, 1)); Pv.push_back(Point(3.5, 3)); @@ -211,8 +195,7 @@ void test3() } /** Main program */ -int main() -{ +int main() { test(); std::cout << std::endl; test2(); diff --git a/others/sparse_matrix.cpp b/others/sparse_matrix.cpp index 5662e065d85..a358f0da472 100644 --- a/others/sparse_matrix.cpp +++ b/others/sparse_matrix.cpp @@ -6,8 +6,7 @@ #include /** main function */ -int main() -{ +int main() { int m, n; int counterZeros = 0; @@ -22,20 +21,16 @@ int main() std::cout << "\n"; // reads the matrix from stdin - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { std::cout << "element? "; std::cin >> a[i][j]; } } // counts the zero's - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { if (a[i][j] == 0) counterZeros++; // Counting number of zeroes } diff --git a/others/spiral_print.cpp b/others/spiral_print.cpp index da92e6937e5..02dc3183aee 100644 --- a/others/spiral_print.cpp +++ b/others/spiral_print.cpp @@ -9,13 +9,10 @@ * \param [in] r number of rows * \param [in] c number of columns */ -void genArray(int **a, int r, int c) -{ +void genArray(int **a, int r, int c) { int value = 1; - for (int i = 0; i < r; i++) - { - for (int j = 0; j < c; j++) - { + for (int i = 0; i < r; i++) { + for (int j = 0; j < c; j++) { a[i][j] = value; std::cout << a[i][j] << " "; value++; @@ -29,47 +26,39 @@ void genArray(int **a, int r, int c) * \param [in] r number of rows * \param [in] c number of columns */ -void spiralPrint(int **a, int r, int c) -{ +void spiralPrint(int **a, int r, int c) { int startRow = 0, endRow = r - 1; int startCol = 0, endCol = c - 1; int cnt = 0; - while (startRow <= endRow && startCol <= endCol) - { + while (startRow <= endRow && startCol <= endCol) { /// Print start row - for (int i = startCol; i <= endCol; i++, cnt++) - { + for (int i = startCol; i <= endCol; i++, cnt++) { std::cout << a[startRow][i] << " "; } startRow++; /// Print the end col - for (int i = startRow; i <= endRow; i++, cnt++) - { + for (int i = startRow; i <= endRow; i++, cnt++) { std::cout << a[i][endCol] << " "; } endCol--; /// Print the end row - if (cnt == r * c) - { + if (cnt == r * c) { break; } - for (int i = endCol; i >= startCol; i--, cnt++) - { + for (int i = endCol; i >= startCol; i--, cnt++) { std::cout << a[endRow][i] << " "; } endRow--; /// Print the start Col - if (cnt == r * c) - { + if (cnt == r * c) { break; } - for (int i = endRow; i >= startRow; i--, cnt++) - { + for (int i = endRow; i >= startRow; i--, cnt++) { std::cout << a[i][startCol] << " "; } startCol++; @@ -77,8 +66,7 @@ void spiralPrint(int **a, int r, int c) } /** main function */ -int main() -{ +int main() { int r, c; std::cin >> r >> c; int **a = new int *[r]; diff --git a/others/stairs_pattern.cpp b/others/stairs_pattern.cpp index bfd90dd1014..a3b8b0a44d6 100644 --- a/others/stairs_pattern.cpp +++ b/others/stairs_pattern.cpp @@ -14,23 +14,18 @@ where number of pairs line is given by user #include /** main function */ -int main() -{ +int main() { int l, st = 2, x, r, z, n, sp; std::cout << "enter Index "; std::cin >> x; z = x; - for (r = 1; r <= x; r++) - { + for (r = 1; r <= x; r++) { z = z - 1; - for (n = 1; n <= 2; n++) - { - for (sp = 1; sp <= z; sp++) - { + for (n = 1; n <= 2; n++) { + for (sp = 1; sp <= z; sp++) { std::cout << " "; } - for (l = 1; l <= st; l++) - { + for (l = 1; l <= st; l++) { std::cout << "*"; } std::cout << std::endl; diff --git a/others/tower_of_hanoi.cpp b/others/tower_of_hanoi.cpp index 3a832248f2e..323b2e424a5 100644 --- a/others/tower_of_hanoi.cpp +++ b/others/tower_of_hanoi.cpp @@ -8,8 +8,7 @@ /** * Define the state of tower */ -struct tower -{ +struct tower { //! Values in the tower int values[10]; //! top tower ID @@ -18,21 +17,17 @@ struct tower /** Display the towers */ void show(const struct tower *const F, const struct tower *const T, - const struct tower *const U) -{ + const struct tower *const U) { std::cout << "\n\n\tF : "; - for (int i = 0; i < F->top; i++) - { + for (int i = 0; i < F->top; i++) { std::cout << F->values[i] << "\t"; } std::cout << "\n\tU : "; - for (int i = 0; i < U->top; i++) - { + for (int i = 0; i < U->top; i++) { std::cout << U->values[i] << "\t"; } std::cout << "\n\tT : "; - for (int i = 0; i < T->top; i++) - { + for (int i = 0; i < T->top; i++) { std::cout << T->values[i] << "\t"; } } @@ -41,8 +36,7 @@ void show(const struct tower *const F, const struct tower *const T, * \param [in,out] From tower to move disk *from* * \param [in,out] To tower to move disk *to* */ -void mov(tower *From, tower *To) -{ +void mov(tower *From, tower *To) { --From->top; To->values[To->top] = From->values[From->top]; ++To->top; @@ -55,15 +49,11 @@ void mov(tower *From, tower *To) * \param [in,out] Using temporary tower for the puzzle * \param [in,out] To tower to move disk to */ -void TH(int n, tower *From, tower *Using, tower *To) -{ - if (n == 1) - { +void TH(int n, tower *From, tower *Using, tower *To) { + if (n == 1) { mov(From, To); show(From, To, Using); - } - else - { + } else { TH(n - 1, From, To, Using); mov(From, To); show(From, To, Using); @@ -72,8 +62,7 @@ void TH(int n, tower *From, tower *Using, tower *To) } /** Main function */ -int main() -{ +int main() { struct tower F, U, T; F.top = 0; @@ -85,8 +74,7 @@ int main() std::cout << "\nEnter number of discs : "; std::cin >> no; - for (int i = no; i > 0; i--) - { + for (int i = no; i > 0; i--) { F.values[F.top++] = i; } diff --git a/others/vector_important_functions.cpp b/others/vector_important_functions.cpp index 765f6a8e566..d23ff9c978d 100644 --- a/others/vector_important_functions.cpp +++ b/others/vector_important_functions.cpp @@ -8,8 +8,7 @@ #include /** Main function */ -int main() -{ +int main() { // Initializing vector with array values int arr[] = {10, 20, 5, 23, 42, 15}; int n = sizeof(arr) / sizeof(arr[0]); diff --git a/probability/addition_rule.cpp b/probability/addition_rule.cpp index 0666b29e61a..7809514899c 100644 --- a/probability/addition_rule.cpp +++ b/probability/addition_rule.cpp @@ -11,8 +11,7 @@ * \parama [in] B probability of event B * \returns probability of A and B */ -double addition_rule_independent(double A, double B) -{ +double addition_rule_independent(double A, double B) { return (A + B) - (A * B); } @@ -23,14 +22,12 @@ double addition_rule_independent(double A, double B) * \parama [in] B_given_A probability of event B condition A * \returns probability of A and B */ -double addition_rule_dependent(double A, double B, double B_given_A) -{ +double addition_rule_dependent(double A, double B, double B_given_A) { return (A + B) - (A * B_given_A); } /** Main function */ -int main() -{ +int main() { double A = 0.5; double B = 0.25; double B_given_A = 0.05; diff --git a/probability/bayes_theorem.cpp b/probability/bayes_theorem.cpp index 632611fe5f1..aaa557a9456 100644 --- a/probability/bayes_theorem.cpp +++ b/probability/bayes_theorem.cpp @@ -11,22 +11,19 @@ /** returns P(A|B) */ -double bayes_AgivenB(double BgivenA, double A, double B) -{ +double bayes_AgivenB(double BgivenA, double A, double B) { return (BgivenA * A) / B; } /** returns P(B|A) */ -double bayes_BgivenA(double AgivenB, double A, double B) -{ +double bayes_BgivenA(double AgivenB, double A, double B) { return (AgivenB * B) / A; } /** Main function */ -int main() -{ +int main() { double A = 0.01; double B = 0.1; double BgivenA = 0.9; diff --git a/probability/binomial_dist.cpp b/probability/binomial_dist.cpp index 4d2e90842c3..1f30c504800 100644 --- a/probability/binomial_dist.cpp +++ b/probability/binomial_dist.cpp @@ -33,8 +33,7 @@ double binomial_variance(double n, double p) { return n * p * (1 - p); } * \param [in] p * \returns \f$\sigma = \sqrt{\sigma^2} = \sqrt{n\cdot p\cdot (1-p)}\f$ */ -double binomial_standard_deviation(double n, double p) -{ +double binomial_standard_deviation(double n, double p) { return std::sqrt(binomial_variance(n, p)); } @@ -45,18 +44,15 @@ double binomial_standard_deviation(double n, double p) * \frac{n!}{r!(n-r)!} = \frac{n\times(n-1)\times(n-2)\times\cdots(n-r)}{r!} * \f$ */ -double nCr(double n, double r) -{ +double nCr(double n, double r) { double numerator = n; double denominator = r; - for (int i = n - 1; i >= ((n - r) + 1); i--) - { + for (int i = n - 1; i >= ((n - r) + 1); i--) { numerator *= i; } - for (int i = 1; i < r; i++) - { + for (int i = 1; i < r; i++) { denominator *= i; } @@ -66,8 +62,7 @@ double nCr(double n, double r) /** calculates the probability of exactly x successes * \returns \f$\displaystyle P(n,p,x) = {n\choose x} p^x (1-p)^{n-x}\f$ */ -double binomial_x_successes(double n, double p, double x) -{ +double binomial_x_successes(double n, double p, double x) { return nCr(n, x) * std::pow(p, x) * std::pow(1 - p, n - x); } @@ -77,19 +72,16 @@ double binomial_x_successes(double n, double p, double x) * =\sum_{i=x_0}^{x_1} {n\choose i} p^i (1-p)^{n-i}\f$ */ double binomial_range_successes(double n, double p, double lower_bound, - double upper_bound) -{ + double upper_bound) { double probability = 0; - for (int i = lower_bound; i <= upper_bound; i++) - { + for (int i = lower_bound; i <= upper_bound; i++) { probability += nCr(n, i) * std::pow(p, i) * std::pow(1 - p, n - i); } return probability; } /** main function */ -int main() -{ +int main() { std::cout << "expected value : " << binomial_expected(100, 0.5) << std::endl; diff --git a/probability/poisson_dist.cpp b/probability/poisson_dist.cpp index 428ee903f27..6a2a377c3f0 100644 --- a/probability/poisson_dist.cpp +++ b/probability/poisson_dist.cpp @@ -14,8 +14,7 @@ * calculate the events per unit time\n * e.g 5 dollars every 2 mins = 5 / 2 = 2.5 */ -double poisson_rate(double events, double timeframe) -{ +double poisson_rate(double events, double timeframe) { return events / timeframe; } @@ -28,16 +27,13 @@ double poisson_expected(double rate, double time) { return rate * time; } /** * Compute factorial of a given number */ -double fact(double x) -{ +double fact(double x) { double x_fact = x; - for (int i = x - 1; i > 0; i--) - { + for (int i = x - 1; i > 0; i--) { x_fact *= i; } - if (x_fact <= 0) - { + if (x_fact <= 0) { x_fact = 1; } return x_fact; @@ -47,8 +43,7 @@ double fact(double x) * Find the probability of x successes in a Poisson dist. * \f[p(\mu,x) = \frac{\mu^x e^{-\mu}}{x!}\f] */ -double poisson_x_successes(double expected, double x) -{ +double poisson_x_successes(double expected, double x) { return (std::pow(expected, x) * std::exp(-expected)) / fact(x); } @@ -56,11 +51,9 @@ double poisson_x_successes(double expected, double x) * probability of a success in range for Poisson dist (inclusive, inclusive) * \f[P = \sum_i p(\mu,i)\f] */ -double poisson_range_successes(double expected, double lower, double upper) -{ +double poisson_range_successes(double expected, double lower, double upper) { double probability = 0; - for (int i = lower; i <= upper; i++) - { + for (int i = lower; i <= upper; i++) { probability += poisson_x_successes(expected, i); } return probability; @@ -69,8 +62,7 @@ double poisson_range_successes(double expected, double lower, double upper) /** * main function */ -int main() -{ +int main() { double rate, expected; rate = poisson_rate(3, 1); std::cout << "Poisson rate : " << rate << std::endl; diff --git a/range_queries/bit.cpp b/range_queries/bit.cpp index 19141b7f5e0..a1878705b44 100644 --- a/range_queries/bit.cpp +++ b/range_queries/bit.cpp @@ -3,46 +3,38 @@ using namespace std; -class Bit -{ +class Bit { int n; vector bit; inline int offset(int x) { return (x & (-x)); } public: - Bit(vector& arr) - { + Bit(vector& arr) { n = arr.size(); bit.assign(n + 1, 0); - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { update(i, arr[i]); } } - Bit(int x) - { + Bit(int x) { n = x; bit.assign(n + 1, 0); } - void update(int id, int val) - { + void update(int id, int val) { // Add val at id id++; - while (id <= n) - { + while (id <= n) { bit[id] += val; id += offset(id); } } - int sum(int id) - { + int sum(int id) { // Get prefix sum upto id. id++; int res = 0; - while (id > 0) - { + while (id > 0) { res += bit[id]; id -= offset(id); } @@ -52,8 +44,7 @@ class Bit int sum_range(int l, int r) { return sum(r) - sum(l - 1); } }; -int main() -{ +int main() { int n = 5; vector arr = {1, 2, 3, 4, 5}; Bit x(arr); diff --git a/range_queries/fenwicktree.cpp b/range_queries/fenwicktree.cpp index d78cb0d48c8..fb7cbaac4f8 100644 --- a/range_queries/fenwicktree.cpp +++ b/range_queries/fenwicktree.cpp @@ -12,19 +12,15 @@ const int maxn = 1e5 + 7; int tree[maxn] = {0}, range; // segement of [1...range], notice it must be less than `maxn` -void update(int x, int c) -{ - while (x <= range) - { +void update(int x, int c) { + while (x <= range) { tree[x] += c; x += lowbit(x); } } -int query(int x) -{ +int query(int x) { int ans = 0; - while (x) - { + while (x) { ans += tree[x]; x -= lowbit(x); } @@ -32,29 +28,23 @@ int query(int x) } int query_segement(int l, int r) { return query(r) - query(l - 1); } -int main() -{ +int main() { cin >> range; - for (int i = 1; i <= range; i++) - { + for (int i = 1; i <= range; i++) { int num; cin >> num; update(i, num); } int q; cin >> q; - while (q--) - { + while (q--) { int op; cin >> op; - if (op == 0) - { + if (op == 0) { int l, r; cin >> l >> r; cout << query_segement(l, r) << endl; - } - else - { + } else { int x, c; cin >> x >> c; update(x, c); diff --git a/range_queries/mo.cpp b/range_queries/mo.cpp index 4cdcdf30dc5..d281ef077ee 100644 --- a/range_queries/mo.cpp +++ b/range_queries/mo.cpp @@ -3,41 +3,35 @@ using namespace std; const int N = 1e6 + 5; int a[N], bucket[N], cnt[N]; int bucket_size; -struct query -{ +struct query { int l, r, i; } q[N]; int ans = 0; -void add(int index) -{ +void add(int index) { cnt[a[index]]++; if (cnt[a[index]] == 1) ans++; } -void remove(int index) -{ +void remove(int index) { cnt[a[index]]--; if (cnt[a[index]] == 0) ans--; } -bool mycmp(query x, query y) -{ +bool mycmp(query x, query y) { if (x.l / bucket_size != y.l / bucket_size) return x.l / bucket_size < y.l / bucket_size; return x.r < y.r; } -int main() -{ +int main() { int n, t, i, j, k = 0; scanf("%d", &n); for (i = 0; i < n; i++) scanf("%d", &a[i]); bucket_size = ceil(sqrt(n)); scanf("%d", &t); - for (i = 0; i < t; i++) - { + for (i = 0; i < t; i++) { scanf("%d %d", &q[i].l, &q[i].r); q[i].l--; q[i].r--; @@ -45,26 +39,21 @@ int main() } sort(q, q + t, mycmp); int left = 0, right = 0; - for (i = 0; i < t; i++) - { + for (i = 0; i < t; i++) { int L = q[i].l, R = q[i].r; - while (left < L) - { + while (left < L) { remove(left); left++; } - while (left > L) - { + while (left > L) { add(left - 1); left--; } - while (right <= R) - { + while (right <= R) { add(right); right++; } - while (right > R + 1) - { + while (right > R + 1) { remove(right - 1); right--; } diff --git a/range_queries/segtree.cpp b/range_queries/segtree.cpp index fb2bbab131b..602b3fd9567 100644 --- a/range_queries/segtree.cpp +++ b/range_queries/segtree.cpp @@ -3,10 +3,8 @@ #define MAX 4000000 using namespace std; typedef long long ll; -void ConsTree(ll arr[], ll segtree[], ll low, ll high, ll pos) -{ - if (low == high) - { +void ConsTree(ll arr[], ll segtree[], ll low, ll high, ll pos) { + if (low == high) { segtree[pos] = arr[low]; return; } @@ -15,17 +13,14 @@ void ConsTree(ll arr[], ll segtree[], ll low, ll high, ll pos) ConsTree(arr, segtree, mid + 1, high, 2 * pos + 2); segtree[pos] = segtree[2 * pos + 1] + segtree[2 * pos + 2]; } -ll query(ll segtree[], ll lazy[], ll qlow, ll qhigh, ll low, ll high, ll pos) -{ +ll query(ll segtree[], ll lazy[], ll qlow, ll qhigh, ll low, ll high, ll pos) { if (low > high) return 0; if (qlow > high || qhigh < low) return 0; - if (lazy[pos] != 0) - { + if (lazy[pos] != 0) { segtree[pos] += lazy[pos] * (high - low + 1); - if (low != high) - { + if (low != high) { lazy[2 * pos + 1] += lazy[pos]; lazy[2 * pos + 2] += lazy[pos]; } @@ -38,15 +33,12 @@ ll query(ll segtree[], ll lazy[], ll qlow, ll qhigh, ll low, ll high, ll pos) query(segtree, lazy, qlow, qhigh, mid + 1, high, 2 * pos + 2); } void update(ll segtree[], ll lazy[], ll start, ll end, ll delta, ll low, - ll high, ll pos) -{ + ll high, ll pos) { if (low > high) return; - if (lazy[pos] != 0) - { + if (lazy[pos] != 0) { segtree[pos] += lazy[pos] * (high - low + 1); - if (low != high) - { + if (low != high) { lazy[2 * pos + 1] += lazy[pos]; lazy[2 * pos + 2] += lazy[pos]; } @@ -54,11 +46,9 @@ void update(ll segtree[], ll lazy[], ll start, ll end, ll delta, ll low, } if (start > high || end < low) return; - if (start <= low && end >= high) - { + if (start <= low && end >= high) { segtree[pos] += delta * (high - low + 1); - if (low != high) - { + if (low != high) { lazy[2 * pos + 1] += delta; lazy[2 * pos + 2] += delta; } @@ -69,23 +59,18 @@ void update(ll segtree[], ll lazy[], ll start, ll end, ll delta, ll low, update(segtree, lazy, start, end, delta, mid + 1, high, 2 * pos + 2); segtree[pos] = segtree[2 * pos + 1] + segtree[2 * pos + 2]; } -int main() -{ +int main() { ll n, c; scanf("%lld %lld", &n, &c); ll arr[n] = {0}, p, q, v, choice; ll segtree[MAX], lazy[MAX] = {0}; ConsTree(arr, segtree, 0, n - 1, 0); - while (c--) - { + while (c--) { scanf("%lld", &choice); - if (choice == 0) - { + if (choice == 0) { scanf("%lld %lld %lld", &p, &q, &v); update(segtree, lazy, p - 1, q - 1, v, 0, n - 1, 0); - } - else - { + } else { scanf("%lld %lld", &p, &q); printf("%lld\n", query(segtree, lazy, p - 1, q - 1, 0, n - 1, 0)); } diff --git a/search/binary_search.cpp b/search/binary_search.cpp index ba0ce7644bf..66da31d7fca 100644 --- a/search/binary_search.cpp +++ b/search/binary_search.cpp @@ -12,12 +12,10 @@ * \returns index if T is found * \return -1 if T is not found */ -int binary_search(int a[], int r, int key) -{ +int binary_search(int a[], int r, int key) { int l = 0; - while (l <= r) - { + while (l <= r) { int m = l + (r - l) / 2; if (key == a[m]) return m; @@ -30,8 +28,7 @@ int binary_search(int a[], int r, int key) } /** main function */ -int main(int argc, char const* argv[]) -{ +int main(int argc, char const* argv[]) { int n, key; std::cout << "Enter size of array: "; std::cin >> n; @@ -40,8 +37,7 @@ int main(int argc, char const* argv[]) int* a = new int[n]; // this loop use for store value in Array - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { std::cin >> a[i]; } diff --git a/search/exponential_search.cpp b/search/exponential_search.cpp index 276d032463b..f57cbf96b51 100644 --- a/search/exponential_search.cpp +++ b/search/exponential_search.cpp @@ -31,12 +31,10 @@ * \returns `nullptr` if value not found */ template -inline Type* binary_s(Type* array, size_t size, Type key) -{ +inline Type* binary_s(Type* array, size_t size, Type key) { int32_t lower_index(0), upper_index(size - 1), middle_index; - while (lower_index <= upper_index) - { + while (lower_index <= upper_index) { middle_index = std::floor((lower_index + upper_index) / 2); if (*(array + middle_index) < key) @@ -58,13 +56,10 @@ inline Type* binary_s(Type* array, size_t size, Type key) * * Auxiliary Space Complexity O(1) */ template -Type* struzik_search(Type* array, size_t size, Type key) -{ +Type* struzik_search(Type* array, size_t size, Type key) { uint32_t block_front(0), block_size = size == 0 ? 0 : 1; - while (block_front != block_size) - { - if (*(array + block_size - 1) < key) - { + while (block_front != block_size) { + if (*(array + block_size - 1) < key) { block_front = block_size; (block_size * 2 - 1 < size) ? (block_size *= 2) : block_size = size; continue; @@ -76,8 +71,7 @@ Type* struzik_search(Type* array, size_t size, Type key) } /** Main function */ -int main() -{ +int main() { // TEST CASES int* sorted_array = new int[7]{7, 10, 15, 23, 70, 105, 203}; assert(struzik_search(sorted_array, 7, 0) == nullptr); diff --git a/search/hash_search.cpp b/search/hash_search.cpp index c417c114be4..6e4caffc30e 100644 --- a/search/hash_search.cpp +++ b/search/hash_search.cpp @@ -26,8 +26,7 @@ int data[MAX] = {1, 10, 15, 5, 8, 7}; //!< test data /** * a one-way linked list */ -typedef struct list -{ +typedef struct list { int key; //!< key value for node struct list* next; //!< pointer to next link in the chain } node, /**< define node as one item list */ @@ -53,8 +52,7 @@ int h(int key) { return key % HASHMAX; } * \warning dynamic memory allocated to `n` never gets freed. * \todo fix memory leak */ -void create_list(int key) -{ // Construct hash table +void create_list(int key) { // Construct hash table link p, n; int index; n = (link)malloc(sizeof(node)); @@ -62,13 +60,10 @@ void create_list(int key) n->next = NULL; index = h(key); p = hashtab[index].next; - if (p != NULL) - { + if (p != NULL) { n->next = p; hashtab[index].next = n; - } - else - { + } else { hashtab[index].next = n; } } @@ -78,8 +73,7 @@ void create_list(int key) * (int key) function, then one-dimensional linear search. If found @return * element depth and number of searches If not found @return -1 */ -int hash_search(int key, int* counter) -{ // Hash lookup function +int hash_search(int key, int* counter) { // Hash lookup function link pointer; int index; @@ -89,8 +83,7 @@ int hash_search(int key, int* counter) std::cout << "data[" << index << "]:"; - while (pointer != NULL) - { + while (pointer != NULL) { counter[0]++; std::cout << "data[" << pointer->key << "]:"; if (pointer->key == key) @@ -103,27 +96,23 @@ int hash_search(int key, int* counter) } /** main function */ -int main() -{ +int main() { link p; int key, index, i, counter; // Key is the value to be found index = 0; // You can write the input mode here - while (index < MAX) - { // Construct hash table + while (index < MAX) { // Construct hash table create_list(data[index]); index++; } - for (i = 0; i < HASHMAX; i++) - { // Output hash table + for (i = 0; i < HASHMAX; i++) { // Output hash table std::cout << "hashtab [" << i << "]\n"; p = hashtab[i].next; - while (p != NULL) - { + while (p != NULL) { std::cout << "please int key:"; if (p->key > 0) std::cout << "[" << p->key << "]"; @@ -132,8 +121,7 @@ int main() std::cout << std::endl; } - while (key != -1) - { + while (key != -1) { // You can write the input mode here // test key = 10 key = 10; diff --git a/search/interpolation_search.cpp b/search/interpolation_search.cpp index 0b356b119b5..4339dc3661e 100644 --- a/search/interpolation_search.cpp +++ b/search/interpolation_search.cpp @@ -12,13 +12,11 @@ * \returns index where the value is found * \returns 0 if not found */ -int interpolation_search(int arr[], int value, int len) -{ +int interpolation_search(int arr[], int value, int len) { int low = 0, high, mid; high = len - 1; - while (arr[low] <= value && arr[high] >= value) - { + while (arr[low] <= value && arr[high] >= value) { mid = (low + ((value - arr[low]) * (high - low)) / (arr[high] - arr[low])); if (arr[mid] > value) @@ -36,8 +34,7 @@ int interpolation_search(int arr[], int value, int len) } /** main function */ -int main() -{ +int main() { int n, value, re; std::cout << "Enter the size of array(less than 100) : "; diff --git a/search/interpolation_search2.cpp b/search/interpolation_search2.cpp index 9400c5f9674..93fa6cd836e 100644 --- a/search/interpolation_search2.cpp +++ b/search/interpolation_search2.cpp @@ -12,12 +12,10 @@ * \returns index where the value is found * \returns -1 if not found */ -int InterpolationSearch(int A[], int n, int x) -{ +int InterpolationSearch(int A[], int n, int x) { int low = 0; int high = n - 1; - while (low <= high) - { + while (low <= high) { int mid = low + (((high - 1) * (x - A[low])) / (A[high] - A[low])); if (x == A[mid]) return mid; // Found x, return (exit) @@ -31,8 +29,7 @@ int InterpolationSearch(int A[], int n, int x) } /** main function */ -int main() -{ +int main() { int A[] = {2, 4, 5, 7, 13, 14, 15, 23}; int x = 17; diff --git a/search/jump_search.cpp b/search/jump_search.cpp index b854ac6f92d..f7b100a4e03 100644 --- a/search/jump_search.cpp +++ b/search/jump_search.cpp @@ -9,16 +9,14 @@ /** jump search implementation */ -int jumpSearch(int arr[], int x, int n) -{ +int jumpSearch(int arr[], int x, int n) { // Finding block size to be jumped int step = std::sqrt(n); // Finding the block where element is // present (if it is present) int prev = 0; - while (arr[std::min(step, n) - 1] < x) - { + while (arr[std::min(step, n) - 1] < x) { prev = step; step += std::sqrt(n); if (prev >= n) @@ -27,8 +25,7 @@ int jumpSearch(int arr[], int x, int n) // Doing a linear search for x in block // beginning with prev. - while (arr[prev] < x) - { + while (arr[prev] < x) { prev++; // If we reached next block or end of @@ -44,8 +41,7 @@ int jumpSearch(int arr[], int x, int n) } // Driver program to test function -int main() -{ +int main() { int arr[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610}; int x = 55; int n = sizeof(arr) / sizeof(arr[0]); diff --git a/search/linear_search.cpp b/search/linear_search.cpp index b8fd798a73d..14250695112 100644 --- a/search/linear_search.cpp +++ b/search/linear_search.cpp @@ -13,12 +13,9 @@ * \returns index where the key-value occurs in the array * \returns -1 if key-value not found */ -int LinearSearch(int *array, int size, int key) -{ - for (int i = 0; i < size; ++i) - { - if (array[i] == key) - { +int LinearSearch(int *array, int size, int key) { + for (int i = 0; i < size; ++i) { + if (array[i] == key) { return i; } } @@ -27,8 +24,7 @@ int LinearSearch(int *array, int size, int key) } /** main function */ -int main() -{ +int main() { int size; std::cout << "\nEnter the size of the Array : "; std::cin >> size; @@ -38,8 +34,7 @@ int main() // Input array std::cout << "\nEnter the Array of " << size << " numbers : "; - for (int i = 0; i < size; i++) - { + for (int i = 0; i < size; i++) { std::cin >> array[i]; } @@ -47,12 +42,9 @@ int main() std::cin >> key; int index = LinearSearch(array, size, key); - if (index != -1) - { + if (index != -1) { std::cout << "\nNumber found at index : " << index; - } - else - { + } else { std::cout << "\nNot found"; } diff --git a/search/median_search.cpp b/search/median_search.cpp index 433ffc1f766..7379cad26e9 100644 --- a/search/median_search.cpp +++ b/search/median_search.cpp @@ -14,25 +14,18 @@ * @todo add documentation */ template -void comp(X x, std::vector *s1, std::vector *s2, std::vector *s3) -{ - if (s1->size() >= x && s1->size() + s2->size() < x) - { +void comp(X x, std::vector *s1, std::vector *s2, + std::vector *s3) { + if (s1->size() >= x && s1->size() + s2->size() < x) { std::cout << (*s2)[0] << " is the " << x + 1 << "th element from front"; - } - else if (s1->size() > x) - { + } else if (s1->size() > x) { std::sort(s1->begin(), s1->end()); std::cout << (*s1)[x] << " is the " << x + 1 << "th element from front"; - } - else if (s1->size() + s2->size() <= x && s3->size() > x) - { + } else if (s1->size() + s2->size() <= x && s3->size() > x) { std::sort(s3->begin(), s3->end()); std::cout << (*s3)[x - s1->size() - s2->size()] << " is the " << x + 1 << "th element from front"; - } - else - { + } else { std::cout << x + 1 << " is invalid location"; } } @@ -42,8 +35,7 @@ void comp(X x, std::vector *s1, std::vector *s2, std::vector *s3) /** * Main function */ -int main() -{ +int main() { std::vector v{25, 21, 98, 100, 76, 22, 43, 60, 89, 87}; std::vector s1; std::vector s2; @@ -62,20 +54,14 @@ int main() std::cout << "\nmedian=" << median << std::endl; int avg1, avg2, avg3, sum1 = 0, sum2 = 0, sum3 = 0; - for (int i = 0; i < v.size(); i++) - { // iterate through all numbers - if (v.back() == v[median]) - { + for (int i = 0; i < v.size(); i++) { // iterate through all numbers + if (v.back() == v[median]) { avg1 = sum1 + v.back(); s2.push_back(v.back()); - } - else if (v.back() < v[median]) - { + } else if (v.back() < v[median]) { avg2 = sum2 + v.back(); s1.push_back(v.back()); - } - else - { + } else { avg3 = sum3 + v.back(); s3.push_back(v.back()); } diff --git a/search/ternary_search.cpp b/search/ternary_search.cpp index f1e2eccf061..73b89da7a2a 100644 --- a/search/ternary_search.cpp +++ b/search/ternary_search.cpp @@ -45,14 +45,10 @@ void get_input() {} * \returns index where the target value was found * \returns -1 if target value not found */ -int it_ternary_search(int left, int right, int A[], int target) -{ - while (1) - { - if (left < right) - { - if (right - left < absolutePrecision) - { +int it_ternary_search(int left, int right, int A[], int target) { + while (1) { + if (left < right) { + if (right - left < absolutePrecision) { for (int i = left; i <= right; i++) if (A[i] == target) return i; @@ -75,9 +71,7 @@ int it_ternary_search(int left, int right, int A[], int target) else left = oneThird + 1, right = twoThird - 1; - } - else - { + } else { return -1; } } @@ -93,12 +87,9 @@ int it_ternary_search(int left, int right, int A[], int target) * \returns index where the target value was found * \returns -1 if target value not found */ -int rec_ternary_search(int left, int right, int A[], int target) -{ - if (left < right) - { - if (right - left < absolutePrecision) - { +int rec_ternary_search(int left, int right, int A[], int target) { + if (left < right) { + if (right - left < absolutePrecision) { for (int i = left; i <= right; i++) if (A[i] == target) return i; @@ -120,9 +111,7 @@ int rec_ternary_search(int left, int right, int A[], int target) return rec_ternary_search(twoThird + 1, right, A, target); return rec_ternary_search(oneThird + 1, twoThird - 1, A, target); - } - else - { + } else { return -1; } } @@ -135,16 +124,14 @@ int rec_ternary_search(int left, int right, int A[], int target) * \param[in] A array to search in * \param[in] target value to search for */ -void ternary_search(int N, int A[], int target) -{ +void ternary_search(int N, int A[], int target) { std::cout << it_ternary_search(0, N - 1, A, target) << '\t'; std::cout << rec_ternary_search(0, N - 1, A, target) << '\t'; std::cout << std::endl; } /** Main function */ -int main() -{ +int main() { int N = 21; int A[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 10}; get_input(); diff --git a/search/text_search.cpp b/search/text_search.cpp index a228d23b216..ee66a506a8a 100644 --- a/search/text_search.cpp +++ b/search/text_search.cpp @@ -12,8 +12,7 @@ /** Main function */ -int main() -{ +int main() { std::string paragraph; std::cout << "Please enter your paragraph: \n"; std::getline(std::cin, paragraph); @@ -21,25 +20,18 @@ int main() std::cout << "\nThe size of your paragraph = " << paragraph.size() << " characters. \n\n"; - if (paragraph.empty()) - { + if (paragraph.empty()) { std::cout << "\nThe paragraph is empty" << std::endl; - } - else - { - while (true) - { + } else { + while (true) { std::string word; std::cout << "Please enter the word you are searching for: "; std::getline(std::cin, word); std::cout << "Hello, your word is " << word << "!\n"; - if (paragraph.find(word) == std::string::npos) - { + if (paragraph.find(word) == std::string::npos) { std::cout << word << " does not exist in the sentence" << std::endl; - } - else - { + } else { std::cout << "The word " << word << " is now found at location " << paragraph.find(word) << std::endl << std::endl; diff --git a/sorting/bead_sort.cpp b/sorting/bead_sort.cpp index 0215fc7696e..f3276bfcd9f 100644 --- a/sorting/bead_sort.cpp +++ b/sorting/bead_sort.cpp @@ -5,8 +5,7 @@ #define BEAD(i, j) beads[i * max + j] // function to perform the above algorithm -void beadSort(int *a, int len) -{ +void beadSort(int *a, int len) { // Find the maximum element int max = a[0]; for (int i = 1; i < len; i++) @@ -21,12 +20,10 @@ void beadSort(int *a, int len) for (int i = 0; i < len; i++) for (int j = 0; j < a[i]; j++) BEAD(i, j) = 1; - for (int j = 0; j < max; j++) - { + for (int j = 0; j < max; j++) { // count how many beads are on each post int sum = 0; - for (int i = 0; i < len; i++) - { + for (int i = 0; i < len; i++) { sum += BEAD(i, j); BEAD(i, j) = 0; } @@ -36,11 +33,9 @@ void beadSort(int *a, int len) } // Put sorted values in array using beads - for (int i = 0; i < len; i++) - { + for (int i = 0; i < len; i++) { int j; - for (j = 0; j < max && BEAD(i, j); j++) - { + for (j = 0; j < max && BEAD(i, j); j++) { } a[i] = j; @@ -49,8 +44,7 @@ void beadSort(int *a, int len) } // driver function to test the algorithm -int main() -{ +int main() { int a[] = {5, 3, 1, 7, 4, 1, 1, 20}; int len = sizeof(a) / sizeof(a[0]); diff --git a/sorting/bitonic_sort.cpp b/sorting/bitonic_sort.cpp index 7f47cbac6f5..0fbb995acfd 100644 --- a/sorting/bitonic_sort.cpp +++ b/sorting/bitonic_sort.cpp @@ -9,8 +9,7 @@ /*The parameter dir indicates the sorting direction, ASCENDING or DESCENDING; if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are interchanged.*/ -void compAndSwap(int a[], int i, int j, int dir) -{ +void compAndSwap(int a[], int i, int j, int dir) { if (dir == (a[i] > a[j])) std::swap(a[i], a[j]); } @@ -19,10 +18,8 @@ void compAndSwap(int a[], int i, int j, int dir) if dir = 1, and in descending order otherwise (means dir=0). The sequence to be sorted starts at index position low, the parameter cnt is the number of elements to be sorted.*/ -void bitonicMerge(int a[], int low, int cnt, int dir) -{ - if (cnt > 1) - { +void bitonicMerge(int a[], int low, int cnt, int dir) { + if (cnt > 1) { int k = cnt / 2; for (int i = low; i < low + k; i++) compAndSwap(a, i, i + k, dir); bitonicMerge(a, low, k, dir); @@ -33,10 +30,8 @@ void bitonicMerge(int a[], int low, int cnt, int dir) /* This function first produces a bitonic sequence by recursively sorting its two halves in opposite sorting orders, and then calls bitonicMerge to make them in the same order */ -void bitonicSort(int a[], int low, int cnt, int dir) -{ - if (cnt > 1) - { +void bitonicSort(int a[], int low, int cnt, int dir) { + if (cnt > 1) { int k = cnt / 2; // sort in ascending order since dir here is 1 @@ -56,8 +51,7 @@ void bitonicSort(int a[], int low, int cnt, int dir) void sort(int a[], int N, int up) { bitonicSort(a, 0, N, up); } // Driver code -int main() -{ +int main() { int a[] = {3, 7, 4, 8, 6, 2, 1, 5}; int N = sizeof(a) / sizeof(a[0]); diff --git a/sorting/bubble_sort.cpp b/sorting/bubble_sort.cpp index 8d2a33dcd60..c43e425fcd9 100644 --- a/sorting/bubble_sort.cpp +++ b/sorting/bubble_sort.cpp @@ -40,8 +40,7 @@ optimized bubble sort algorithm. It's right down there. #include #include -int main() -{ +int main() { int n; bool swap_check = true; std::cout << "Enter the amount of numbers to sort: "; @@ -51,20 +50,16 @@ int main() int num; // Input - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { std::cin >> num; numbers.push_back(num); } // Bubble Sorting - for (int i = 0; (i < n) && (swap_check); i++) - { + for (int i = 0; (i < n) && (swap_check); i++) { swap_check = false; - for (int j = 0; j < n - 1 - i; j++) - { - if (numbers[j] > numbers[j + 1]) - { + for (int j = 0; j < n - 1 - i; j++) { + if (numbers[j] > numbers[j + 1]) { swap_check = true; std::swap(numbers[j], numbers[j + 1]); // by changing swap location. @@ -77,14 +72,10 @@ int main() // Output std::cout << "\nSorted Array : "; - for (int i = 0; i < numbers.size(); i++) - { - if (i != numbers.size() - 1) - { + for (int i = 0; i < numbers.size(); i++) { + if (i != numbers.size() - 1) { std::cout << numbers[i] << ", "; - } - else - { + } else { std::cout << numbers[i] << std::endl; } } diff --git a/sorting/bucket_sort.cpp b/sorting/bucket_sort.cpp index ee945627c15..c43865281bc 100644 --- a/sorting/bucket_sort.cpp +++ b/sorting/bucket_sort.cpp @@ -4,14 +4,12 @@ #include // Function to sort arr[] of size n using bucket sort -void bucketSort(float arr[], int n) -{ +void bucketSort(float arr[], int n) { // 1) Create n empty buckets std::vector *b = new std::vector[n]; // 2) Put array elements in different buckets - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { int bi = n * arr[i]; // Index in bucket b[bi].push_back(arr[i]); } @@ -27,8 +25,7 @@ void bucketSort(float arr[], int n) } /* Driver program to test above funtion */ -int main() -{ +int main() { float arr[] = {0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434}; int n = sizeof(arr) / sizeof(arr[0]); bucketSort(arr, n); diff --git a/sorting/cocktail_selection_sort.cpp b/sorting/cocktail_selection_sort.cpp index ef3d30752e6..157acafcecb 100644 --- a/sorting/cocktail_selection_sort.cpp +++ b/sorting/cocktail_selection_sort.cpp @@ -9,35 +9,27 @@ // Iterative Version -void CocktailSelectionSort(std::vector *vec, int low, int high) -{ - while (low <= high) - { +void CocktailSelectionSort(std::vector *vec, int low, int high) { + while (low <= high) { int minimum = (*vec)[low]; int minimumindex = low; int maximum = (*vec)[high]; int maximumindex = high; - for (int i = low; i <= high; i++) - { - if ((*vec)[i] >= maximum) - { + for (int i = low; i <= high; i++) { + if ((*vec)[i] >= maximum) { maximum = (*vec)[i]; maximumindex = i; } - if ((*vec)[i] <= minimum) - { + if ((*vec)[i] <= minimum) { minimum = (*vec)[i]; minimumindex = i; } } - if (low != maximumindex || high != minimumindex) - { + if (low != maximumindex || high != minimumindex) { std::swap((*vec)[low], (*vec)[minimumindex]); std::swap((*vec)[high], (*vec)[maximumindex]); - } - else - { + } else { std::swap((*vec)[low], (*vec)[high]); } @@ -48,8 +40,7 @@ void CocktailSelectionSort(std::vector *vec, int low, int high) // Recursive Version -void CocktailSelectionSort_v2(std::vector *vec, int low, int high) -{ +void CocktailSelectionSort_v2(std::vector *vec, int low, int high) { if (low >= high) return; @@ -58,26 +49,20 @@ void CocktailSelectionSort_v2(std::vector *vec, int low, int high) int maximum = (*vec)[high]; int maximumindex = high; - for (int i = low; i <= high; i++) - { - if ((*vec)[i] >= maximum) - { + for (int i = low; i <= high; i++) { + if ((*vec)[i] >= maximum) { maximum = (*vec)[i]; maximumindex = i; } - if ((*vec)[i] <= minimum) - { + if ((*vec)[i] <= minimum) { minimum = (*vec)[i]; minimumindex = i; } } - if (low != maximumindex || high != minimumindex) - { + if (low != maximumindex || high != minimumindex) { std::swap((*vec)[low], (*vec)[minimumindex]); std::swap((*vec)[high], (*vec)[maximumindex]); - } - else - { + } else { std::swap((*vec)[low], (*vec)[high]); } @@ -86,15 +71,13 @@ void CocktailSelectionSort_v2(std::vector *vec, int low, int high) // main function, select any one of iterative or recursive version -int main() -{ +int main() { int n; std::cout << "Enter number of elements\n"; std::cin >> n; std::vector v(n); std::cout << "Enter all the elements\n"; - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { std::cin >> v[i]; } @@ -102,22 +85,16 @@ int main() std::cout << "Enter method: \n\t0: iterative\n\t1: recursive:\t"; std::cin >> method; - if (method == 0) - { + if (method == 0) { CocktailSelectionSort(&v, 0, n - 1); - } - else if (method == 1) - { + } else if (method == 1) { CocktailSelectionSort_v2(&v, 0, n - 1); - } - else - { + } else { std::cerr << "Unknown method" << std::endl; return -1; } std::cout << "Sorted elements are\n"; - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { std::cout << v[i] << " "; } diff --git a/sorting/comb_sort.cpp b/sorting/comb_sort.cpp index d554ac75770..1b0a4d70633 100644 --- a/sorting/comb_sort.cpp +++ b/sorting/comb_sort.cpp @@ -8,15 +8,13 @@ int a[100005]; int n; -int FindNextGap(int x) -{ +int FindNextGap(int x) { x = (x * 10) / 13; return std::max(1, x); } -void CombSort(int a[], int l, int r) -{ +void CombSort(int a[], int l, int r) { // Init gap int gap = n; @@ -24,18 +22,15 @@ void CombSort(int a[], int l, int r) bool swapped = true; // Keep running until gap = 1 or none elements were swapped - while (gap != 1 || swapped) - { + while (gap != 1 || swapped) { // Find next gap gap = FindNextGap(gap); swapped = false; // Compare all elements with current gap - for (int i = l; i <= r - gap; ++i) - { - if (a[i] > a[i + gap]) - { + for (int i = l; i <= r - gap; ++i) { + if (a[i] > a[i + gap]) { std::swap(a[i], a[i + gap]); swapped = true; } @@ -43,8 +38,7 @@ void CombSort(int a[], int l, int r) } } -int main() -{ +int main() { std::cin >> n; for (int i = 1; i <= n; ++i) std::cin >> a[i]; diff --git a/sorting/counting_sort.cpp b/sorting/counting_sort.cpp index 9dadd48ccbb..1fbfc0fa3a3 100644 --- a/sorting/counting_sort.cpp +++ b/sorting/counting_sort.cpp @@ -1,8 +1,7 @@ #include using namespace std; -int Max(int Arr[], int N) -{ +int Max(int Arr[], int N) { int max = Arr[0]; for (int i = 1; i < N; i++) if (Arr[i] > max) @@ -10,8 +9,7 @@ int Max(int Arr[], int N) return max; } -int Min(int Arr[], int N) -{ +int Min(int Arr[], int N) { int min = Arr[0]; for (int i = 1; i < N; i++) if (Arr[i] < min) @@ -19,13 +17,11 @@ int Min(int Arr[], int N) return min; } -void Print(int Arr[], int N) -{ +void Print(int Arr[], int N) { for (int i = 0; i < N; i++) cout << Arr[i] << ", "; } -int *Counting_Sort(int Arr[], int N) -{ +int *Counting_Sort(int Arr[], int N) { int max = Max(Arr, N); int min = Min(Arr, N); int *Sorted_Arr = new int[N]; @@ -36,8 +32,7 @@ int *Counting_Sort(int Arr[], int N) for (int i = 1; i < (max - min + 1); i++) Count[i] += Count[i - 1]; - for (int i = N - 1; i >= 0; i--) - { + for (int i = N - 1; i >= 0; i--) { Sorted_Arr[Count[Arr[i] - min] - 1] = Arr[i]; Count[Arr[i] - min]--; } @@ -45,8 +40,7 @@ int *Counting_Sort(int Arr[], int N) return Sorted_Arr; } -int main() -{ +int main() { int Arr[] = {47, 65, 20, 66, 25, 53, 64, 69, 72, 22, 74, 25, 53, 15, 42, 36, 4, 69, 86, 19}, N = 20; diff --git a/sorting/counting_sort_string.cpp b/sorting/counting_sort_string.cpp index 77e8cdf89b0..977f3484dc7 100644 --- a/sorting/counting_sort_string.cpp +++ b/sorting/counting_sort_string.cpp @@ -3,8 +3,7 @@ using namespace std; -void countSort(string arr) -{ +void countSort(string arr) { string output; int count[256], i; @@ -14,8 +13,7 @@ void countSort(string arr) for (i = 1; i <= 256; ++i) count[i] += count[i - 1]; - for (i = 0; arr[i]; ++i) - { + for (i = 0; arr[i]; ++i) { output[count[arr[i]] - 1] = arr[i]; --count[arr[i]]; } @@ -25,8 +23,7 @@ void countSort(string arr) cout << "Sorted character array is " << arr; } -int main() -{ +int main() { string arr; cin >> arr; diff --git a/sorting/heap_sort.cpp b/sorting/heap_sort.cpp index b9b62a5f649..9948bb82153 100644 --- a/sorting/heap_sort.cpp +++ b/sorting/heap_sort.cpp @@ -1,8 +1,7 @@ #include #include -void heapify(int *a, int i, int n) -{ +void heapify(int *a, int i, int n) { int largest = i; const int l = 2 * i + 1; const int r = 2 * i + 2; @@ -13,38 +12,31 @@ void heapify(int *a, int i, int n) if (r < n && a[r] > a[largest]) largest = r; - if (largest != i) - { + if (largest != i) { std::swap(a[i], a[largest]); heapify(a, n, largest); } } -void heapsort(int *a, int n) -{ - for (int i = n - 1; i >= 0; --i) - { +void heapsort(int *a, int n) { + for (int i = n - 1; i >= 0; --i) { std::swap(a[0], a[i]); heapify(a, 0, i); } } -void build_maxheap(int *a, int n) -{ - for (int i = n / 2 - 1; i >= 0; --i) - { +void build_maxheap(int *a, int n) { + for (int i = n / 2 - 1; i >= 0; --i) { heapify(a, i, n); } } -int main() -{ +int main() { int n; std::cout << "Enter number of elements of array\n"; std::cin >> n; int a[20]; - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { std::cout << "Enter Element " << i << std::endl; std::cin >> a[i]; } @@ -52,8 +44,7 @@ int main() build_maxheap(a, n); heapsort(a, n); std::cout << "Sorted Output\n"; - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { std::cout << a[i] << std::endl; } diff --git a/sorting/insertion_sort.cpp b/sorting/insertion_sort.cpp index b96a44c475f..fe920ca5913 100644 --- a/sorting/insertion_sort.cpp +++ b/sorting/insertion_sort.cpp @@ -2,8 +2,7 @@ #include -int main() -{ +int main() { int n; std::cout << "\nEnter the length of your array : "; std::cin >> n; @@ -11,18 +10,15 @@ int main() std::cout << "\nEnter any " << n << " Numbers for Unsorted Array : "; // Input - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { std::cin >> Array[i]; } // Sorting - for (int i = 1; i < n; i++) - { + for (int i = 1; i < n; i++) { int temp = Array[i]; int j = i - 1; - while (j >= 0 && temp < Array[j]) - { + while (j >= 0 && temp < Array[j]) { Array[j + 1] = Array[j]; j--; } @@ -31,8 +27,7 @@ int main() // Output std::cout << "\nSorted Array : "; - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { std::cout << Array[i] << "\t"; } diff --git a/sorting/library_sort.cpp b/sorting/library_sort.cpp index c0fa857e7df..c9cba88d8c4 100644 --- a/sorting/library_sort.cpp +++ b/sorting/library_sort.cpp @@ -1,8 +1,7 @@ #include #include -void librarySort(int *index, int n) -{ +void librarySort(int *index, int n) { int lib_size, index_pos, *gaps, // gaps *library[2]; // libraries @@ -19,8 +18,7 @@ void librarySort(int *index, int n) target_lib = 0; library[target_lib][0] = index[0]; - while (index_pos < n) - { + while (index_pos < n) { // binary search int insert = std::distance( library[target_lib], @@ -29,23 +27,19 @@ void librarySort(int *index, int n) // if there is no gap to insert a new index ... - if (numbered[insert] == true) - { + if (numbered[insert] == true) { int prov_size = 0, next_target_lib = !target_lib; // update library and clear gaps - for (int i = 0; i <= n; i++) - { - if (numbered[i] == true) - { + for (int i = 0; i <= n; i++) { + if (numbered[i] == true) { library[next_target_lib][prov_size] = gaps[i]; prov_size++; numbered[i] = false; } - if (i <= lib_size) - { + if (i <= lib_size) { library[next_target_lib][prov_size] = library[target_lib][i]; prov_size++; @@ -54,9 +48,7 @@ void librarySort(int *index, int n) target_lib = next_target_lib; lib_size = prov_size - 1; - } - else - { + } else { numbered[insert] = true; gaps[insert] = index[index_pos]; index_pos++; @@ -64,17 +56,14 @@ void librarySort(int *index, int n) } int index_pos_for_output = 0; - for (int i = 0; index_pos_for_output < n; i++) - { - if (numbered[i] == true) - { + for (int i = 0; index_pos_for_output < n; i++) { + if (numbered[i] == true) { // std::cout << gaps[i] << std::endl; index[index_pos_for_output] = gaps[i]; index_pos_for_output++; } - if (i < lib_size) - { + if (i < lib_size) { // std::cout << library[target_lib][i] << std::endl; index[index_pos_for_output] = library[target_lib][i]; index_pos_for_output++; @@ -82,8 +71,7 @@ void librarySort(int *index, int n) } } -int main() -{ +int main() { // ---example-- int index_ex[] = {-6, 5, 9, 1, 9, 1, 0, 1, -8, 4, -12}; int n_ex = sizeof(index_ex) / sizeof(index_ex[0]); diff --git a/sorting/merge_sort.cpp b/sorting/merge_sort.cpp index 1a394ded9a0..82ab869cd2c 100644 --- a/sorting/merge_sort.cpp +++ b/sorting/merge_sort.cpp @@ -1,7 +1,6 @@ #include -void merge(int arr[], int l, int m, int r) -{ +void merge(int arr[], int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; @@ -14,30 +13,24 @@ void merge(int arr[], int l, int m, int r) i = 0; j = 0; k = l; - while (i < n1 && j < n2) - { - if (L[i] <= R[j]) - { + while (i < n1 && j < n2) { + if (L[i] <= R[j]) { arr[k] = L[i]; i++; - } - else - { + } else { arr[k] = R[j]; j++; } k++; } - while (i < n1) - { + while (i < n1) { arr[k] = L[i]; i++; k++; } - while (j < n2) - { + while (j < n2) { arr[k] = R[j]; j++; k++; @@ -47,10 +40,8 @@ void merge(int arr[], int l, int m, int r) delete[] R; } -void mergeSort(int arr[], int l, int r) -{ - if (l < r) - { +void mergeSort(int arr[], int l, int r) { + if (l < r) { int m = l + (r - l) / 2; mergeSort(arr, l, m); @@ -60,14 +51,12 @@ void mergeSort(int arr[], int l, int r) } } -void show(int A[], int size) -{ +void show(int A[], int size) { int i; for (i = 0; i < size; i++) std::cout << A[i] << "\n"; } -int main() -{ +int main() { int size; std::cout << "\nEnter the number of elements : "; @@ -77,8 +66,7 @@ int main() std::cout << "\nEnter the unsorted elements : "; - for (int i = 0; i < size; ++i) - { + for (int i = 0; i < size; ++i) { std::cout << "\n"; std::cin >> arr[i]; } diff --git a/sorting/non_recursive_merge_sort.cpp b/sorting/non_recursive_merge_sort.cpp index 9086ec0edcc..9d4e95f2fdd 100644 --- a/sorting/non_recursive_merge_sort.cpp +++ b/sorting/non_recursive_merge_sort.cpp @@ -22,20 +22,17 @@ void merge(Iterator, Iterator, const Iterator, char[]); */ template void non_recursive_merge_sort(const Iterator first, const Iterator last, - const size_t n) -{ + const size_t n) { // create a buffer large enough to store all elements // dynamically allocated to comply with cpplint char* buffer = new char[n * sizeof(*first)]; // buffer size can be optimized to largest power of 2 less than n elements // divide the container into equally-sized segments whose length start at 1 // and keeps increasing by factors of 2 - for (size_t length(1); length < n; length <<= 1) - { + for (size_t length(1); length < n; length <<= 1) { // merge adjacent segments whose number is n / (length * 2) Iterator left(first); - for (size_t counter(n / (length << 1)); counter; --counter) - { + for (size_t counter(n / (length << 1)); counter; --counter) { Iterator right(left + length), end(right + length); merge(left, right, end, buffer); left = end; @@ -56,8 +53,7 @@ void non_recursive_merge_sort(const Iterator first, const Iterator last, * @param b points at the buffer */ template -void merge(Iterator l, Iterator r, const Iterator e, char b[]) -{ +void merge(Iterator l, Iterator r, const Iterator e, char b[]) { // create 2 pointers to point at the buffer auto p(reinterpret_cast*>(b)), c(p); // move the left part of the segment @@ -77,8 +73,7 @@ void merge(Iterator l, Iterator r, const Iterator e, char b[]) * @param n the number of elements */ template -void non_recursive_merge_sort(const Iterator first, const size_t n) -{ +void non_recursive_merge_sort(const Iterator first, const size_t n) { non_recursive_merge_sort(first, first + n, n); } /// bottom-up merge sort which sorts elements in a non-decreasing order @@ -87,19 +82,16 @@ void non_recursive_merge_sort(const Iterator first, const size_t n) * @param last points to 1-step past the last element */ template -void non_recursive_merge_sort(const Iterator first, const Iterator last) -{ +void non_recursive_merge_sort(const Iterator first, const Iterator last) { non_recursive_merge_sort(first, last, last - first); } -int main(int argc, char** argv) -{ +int main(int argc, char** argv) { int size; std::cout << "Enter the number of elements : "; std::cin >> size; int* arr = new int[size]; - for (int i = 0; i < size; ++i) - { + for (int i = 0; i < size; ++i) { std::cout << "arr[" << i << "] = "; std::cin >> arr[i]; } diff --git a/sorting/numeric_string_sort.cpp b/sorting/numeric_string_sort.cpp index 358cc63e346..04a12e71af4 100644 --- a/sorting/numeric_string_sort.cpp +++ b/sorting/numeric_string_sort.cpp @@ -13,14 +13,11 @@ #include #include -bool NumericSort(std::string a, std::string b) -{ - while (a[0] == '0') - { +bool NumericSort(std::string a, std::string b) { + while (a[0] == '0') { a.erase(a.begin()); } - while (b[0] == '0') - { + while (b[0] == '0') { b.erase(b.begin()); } int n = a.length(); @@ -30,31 +27,27 @@ bool NumericSort(std::string a, std::string b) return n < m; } -int main() -{ +int main() { int n; std::cout << "Enter number of elements to be sorted Numerically\n"; std::cin >> n; std::vector v(n); std::cout << "Enter the string of Numbers\n"; - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { std::cin >> v[i]; } sort(v.begin(), v.end()); std::cout << "Elements sorted normally \n"; - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { std::cout << v[i] << " "; } std::cout << "\n"; std::sort(v.begin(), v.end(), NumericSort); std::cout << "Elements sorted Numerically \n"; - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { std::cout << v[i] << " "; } diff --git a/sorting/odd_even_sort.cpp b/sorting/odd_even_sort.cpp index 274f3033b56..25f2a371228 100644 --- a/sorting/odd_even_sort.cpp +++ b/sorting/odd_even_sort.cpp @@ -4,16 +4,13 @@ using namespace std; -void oddEven(vector &arr, int size) -{ +void oddEven(vector &arr, int size) { bool sorted = false; - while (!sorted) - { + while (!sorted) { sorted = true; for (int i = 1; i < size - 1; i += 2) // Odd { - if (arr[i] > arr[i + 1]) - { + if (arr[i] > arr[i + 1]) { swap(arr[i], arr[i + 1]); sorted = false; } @@ -21,8 +18,7 @@ void oddEven(vector &arr, int size) for (int i = 0; i < size - 1; i += 2) // Even { - if (arr[i] > arr[i + 1]) - { + if (arr[i] > arr[i + 1]) { swap(arr[i], arr[i + 1]); sorted = false; } @@ -30,14 +26,12 @@ void oddEven(vector &arr, int size) } } -void show(vector A, int size) -{ +void show(vector A, int size) { int i; for (i = 0; i < size; i++) cout << A[i] << "\n"; } -int main() -{ +int main() { int size, temp; cout << "\nEnter the number of elements : "; cin >> size; @@ -46,8 +40,7 @@ int main() cout << "\nEnter the unsorted elements : \n"; - for (int i = 0; i < size; ++i) - { + for (int i = 0; i < size; ++i) { cin >> temp; arr.push_back(temp); } diff --git a/sorting/quick_sort.cpp b/sorting/quick_sort.cpp index 8bb376b2439..1db6b014e07 100644 --- a/sorting/quick_sort.cpp +++ b/sorting/quick_sort.cpp @@ -33,17 +33,14 @@ * */ -int partition(int arr[], int low, int high) -{ +int partition(int arr[], int low, int high) { int pivot = arr[high]; // taking the last element as pivot int i = (low - 1); // Index of smaller element - for (int j = low; j < high; j++) - { + for (int j = low; j < high; j++) { // If current element is smaller than or // equal to pivot - if (arr[j] <= pivot) - { + if (arr[j] <= pivot) { i++; // increment index of smaller element int temp = arr[i]; arr[i] = arr[j]; @@ -62,10 +59,8 @@ int partition(int arr[], int low, int high) * low --> Starting index, * high --> Ending index */ -void quickSort(int arr[], int low, int high) -{ - if (low < high) - { +void quickSort(int arr[], int low, int high) { + if (low < high) { int p = partition(arr, low, high); quickSort(arr, low, p - 1); quickSort(arr, p + 1, high); @@ -73,15 +68,13 @@ void quickSort(int arr[], int low, int high) } // prints the array after sorting -void show(int arr[], int size) -{ +void show(int arr[], int size) { for (int i = 0; i < size; i++) std::cout << arr[i] << " "; std::cout << "\n"; } /** Driver program to test above functions */ -int main() -{ +int main() { int size; std::cout << "\nEnter the number of elements : "; @@ -91,8 +84,7 @@ int main() std::cout << "\nEnter the unsorted elements : "; - for (int i = 0; i < size; ++i) - { + for (int i = 0; i < size; ++i) { std::cout << "\n"; std::cin >> arr[i]; } diff --git a/sorting/radix_sort.cpp b/sorting/radix_sort.cpp index c3b5b1629a9..a0fbfe99ee5 100644 --- a/sorting/radix_sort.cpp +++ b/sorting/radix_sort.cpp @@ -3,66 +3,53 @@ #include #include -void radixsort(int a[], int n) -{ +void radixsort(int a[], int n) { int count[10]; int* output = new int[n]; memset(output, 0, n * sizeof(*output)); memset(count, 0, sizeof(count)); int max = 0; - for (int i = 0; i < n; ++i) - { - if (a[i] > max) - { + for (int i = 0; i < n; ++i) { + if (a[i] > max) { max = a[i]; } } int maxdigits = 0; - while (max) - { + while (max) { maxdigits++; max /= 10; } - for (int j = 0; j < maxdigits; j++) - { - for (int i = 0; i < n; i++) - { + for (int j = 0; j < maxdigits; j++) { + for (int i = 0; i < n; i++) { int t = std::pow(10, j); count[(a[i] % (10 * t)) / t]++; } int k = 0; - for (int p = 0; p < 10; p++) - { - for (int i = 0; i < n; i++) - { + for (int p = 0; p < 10; p++) { + for (int i = 0; i < n; i++) { int t = std::pow(10, j); - if ((a[i] % (10 * t)) / t == p) - { + if ((a[i] % (10 * t)) / t == p) { output[k] = a[i]; k++; } } } memset(count, 0, sizeof(count)); - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { a[i] = output[i]; } } delete[] output; } -void print(int a[], int n) -{ - for (int i = 0; i < n; ++i) - { +void print(int a[], int n) { + for (int i = 0; i < n; ++i) { std::cout << a[i] << " "; } std::cout << std::endl; } -int main(int argc, char const* argv[]) -{ +int main(int argc, char const* argv[]) { int a[] = {170, 45, 75, 90, 802, 24, 2, 66}; int n = sizeof(a) / sizeof(a[0]); radixsort(a, n); diff --git a/sorting/selection_sort.cpp b/sorting/selection_sort.cpp index 7e8b0678ceb..3854f52e6c4 100644 --- a/sorting/selection_sort.cpp +++ b/sorting/selection_sort.cpp @@ -3,25 +3,20 @@ #include using namespace std; -int main() -{ +int main() { int Array[6]; cout << "\nEnter any 6 Numbers for Unsorted Array : "; // Input - for (int i = 0; i < 6; i++) - { + for (int i = 0; i < 6; i++) { cin >> Array[i]; } // Selection Sorting - for (int i = 0; i < 6; i++) - { + for (int i = 0; i < 6; i++) { int min = i; - for (int j = i + 1; j < 6; j++) - { - if (Array[j] < Array[min]) - { + for (int j = i + 1; j < 6; j++) { + if (Array[j] < Array[min]) { min = j; // Finding the smallest number in Array } } @@ -32,8 +27,7 @@ int main() // Output cout << "\nSorted Array : "; - for (int i = 0; i < 6; i++) - { + for (int i = 0; i < 6; i++) { cout << Array[i] << "\t"; } } diff --git a/sorting/shell_sort.cpp b/sorting/shell_sort.cpp index af783eb24ba..eb701478d4e 100644 --- a/sorting/shell_sort.cpp +++ b/sorting/shell_sort.cpp @@ -1,31 +1,23 @@ #include -int main() -{ +int main() { int size = 10; int* array = new int[size]; // Input std::cout << "\nHow many numbers do want to enter in unsorted array : "; std::cin >> size; std::cout << "\nEnter the numbers for unsorted array : "; - for (int i = 0; i < size; i++) - { + for (int i = 0; i < size; i++) { std::cin >> array[i]; } // Sorting - for (int i = size / 2; i > 0; i = i / 2) - { - for (int j = i; j < size; j++) - { - for (int k = j - i; k >= 0; k = k - i) - { - if (array[k] < array[k + i]) - { + for (int i = size / 2; i > 0; i = i / 2) { + for (int j = i; j < size; j++) { + for (int k = j - i; k >= 0; k = k - i) { + if (array[k] < array[k + i]) { break; - } - else - { + } else { int temp = array[k + i]; array[k + i] = array[k]; array[k] = temp; @@ -36,8 +28,7 @@ int main() // Output std::cout << "\nSorted array : "; - for (int i = 0; i < size; ++i) - { + for (int i = 0; i < size; ++i) { std::cout << array[i] << "\t"; } diff --git a/sorting/shell_sort2.cpp b/sorting/shell_sort2.cpp index dee8cecd779..59f204818b1 100644 --- a/sorting/shell_sort2.cpp +++ b/sorting/shell_sort2.cpp @@ -7,8 +7,7 @@ #include template -void show_data(T *arr, size_t LEN) -{ +void show_data(T *arr, size_t LEN) { size_t i; for (i = 0; i < LEN; i++) std::cout << arr[i] << ", "; @@ -16,8 +15,7 @@ void show_data(T *arr, size_t LEN) } template -void show_data(T (&arr)[N]) -{ +void show_data(T (&arr)[N]) { show_data(arr, N); } @@ -26,17 +24,14 @@ void show_data(T (&arr)[N]) * Mar **/ template -void shell_sort(T *arr, size_t LEN) -{ +void shell_sort(T *arr, size_t LEN) { const unsigned int gaps[] = {701, 301, 132, 57, 23, 10, 4, 1}; const unsigned int gap_len = 8; size_t i, j, g; - for (g = 0; g < gap_len; g++) - { + for (g = 0; g < gap_len; g++) { unsigned int gap = gaps[g]; - for (i = gap; i < LEN; i++) - { + for (i = gap; i < LEN; i++) { T tmp = arr[i]; for (j = i; j >= gap && (arr[j - gap] - tmp) > 0; j -= gap) @@ -48,16 +43,14 @@ void shell_sort(T *arr, size_t LEN) } template -void shell_sort(T (&arr)[N]) -{ +void shell_sort(T (&arr)[N]) { shell_sort(arr, N); } /** * function to compare sorting using cstdlib's qsort **/ -int compare(const void *a, const void *b) -{ +int compare(const void *a, const void *b) { int arg1 = *static_cast(a); int arg2 = *static_cast(b); @@ -71,8 +64,7 @@ int compare(const void *a, const void *b) // return arg1 - arg2; // erroneous shortcut (fails if INT_MIN is present) } -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { int i, NUM_DATA; if (argc == 2) diff --git a/sorting/slow_sort.cpp b/sorting/slow_sort.cpp index e4f175af6f8..a3e64dba03c 100644 --- a/sorting/slow_sort.cpp +++ b/sorting/slow_sort.cpp @@ -10,8 +10,7 @@ #include -void SlowSort(int a[], int i, int j) -{ +void SlowSort(int a[], int i, int j) { if (i >= j) return; int m = i + (j - i) / 2; // midpoint, implemented this way to avoid @@ -19,8 +18,7 @@ void SlowSort(int a[], int i, int j) int temp; SlowSort(a, i, m); SlowSort(a, m + 1, j); - if (a[j] < a[m]) - { + if (a[j] < a[m]) { temp = a[j]; // swapping a[j] & a[m] a[j] = a[m]; a[m] = temp; @@ -30,8 +28,7 @@ void SlowSort(int a[], int i, int j) // Sample Main function -int main() -{ +int main() { int size; std::cout << "\nEnter the number of elements : "; @@ -41,8 +38,7 @@ int main() std::cout << "\nEnter the unsorted elements : "; - for (int i = 0; i < size; ++i) - { + for (int i = 0; i < size; ++i) { std::cout << "\n"; std::cin >> arr[i]; } @@ -51,8 +47,7 @@ int main() std::cout << "Sorted array\n"; - for (int i = 0; i < size; ++i) - { + for (int i = 0; i < size; ++i) { std::cout << arr[i] << " "; } diff --git a/sorting/swap_sort.cpp b/sorting/swap_sort.cpp index 7d391d8a193..4cdaa57b348 100644 --- a/sorting/swap_sort.cpp +++ b/sorting/swap_sort.cpp @@ -6,14 +6,12 @@ // Function returns the minimum number of swaps // required to sort the array -int minSwaps(int arr[], int n) -{ +int minSwaps(int arr[], int n) { // Create an array of pairs where first // element is array element and second element // is position of first element std::pair *arrPos = new std::pair[n]; - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { arrPos[i].first = arr[i]; arrPos[i].second = i; } @@ -31,8 +29,7 @@ int minSwaps(int arr[], int n) int ans = 0; // Traverse array elements - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { // already swapped and corrected or // already present at correct pos if (vis[i] || arrPos[i].second == i) @@ -42,8 +39,7 @@ int minSwaps(int arr[], int n) // this cycle and add in ans int cycle_size = 0; int j = i; - while (!vis[j]) - { + while (!vis[j]) { vis[j] = 1; // move to next node @@ -52,8 +48,7 @@ int minSwaps(int arr[], int n) } // Update answer by adding current cycle. - if (cycle_size > 0) - { + if (cycle_size > 0) { ans += (cycle_size - 1); } } @@ -65,8 +60,7 @@ int minSwaps(int arr[], int n) } // program to test -int main() -{ +int main() { int arr[] = {6, 7, 8, 1, 2, 3, 9, 12}; int n = (sizeof(arr) / sizeof(int)); std::cout << minSwaps(arr, n); diff --git a/sorting/tim_sort.cpp b/sorting/tim_sort.cpp index 9645a60b168..94f5aa230b3 100644 --- a/sorting/tim_sort.cpp +++ b/sorting/tim_sort.cpp @@ -6,14 +6,11 @@ const int RUN = 32; // this function sorts array from left index to to right index which is of size // atmost RUN -void insertionSort(int arr[], int left, int right) -{ - for (int i = left + 1; i <= right; i++) - { +void insertionSort(int arr[], int left, int right) { + for (int i = left + 1; i <= right; i++) { int temp = arr[i]; int j = i - 1; - while (arr[j] > temp && j >= left) - { + while (arr[j] > temp && j >= left) { arr[j + 1] = arr[j]; j--; } @@ -22,8 +19,7 @@ void insertionSort(int arr[], int left, int right) } // merge function merges the sorted runs -void merge(int arr[], int l, int m, int r) -{ +void merge(int arr[], int l, int m, int r) { // original array is broken in two parts, left and right array int len1 = m - l + 1, len2 = r - m; int *left = new int[len1], *right = new int[len2]; @@ -35,15 +31,11 @@ void merge(int arr[], int l, int m, int r) int k = l; // after comparing, we merge those two array in larger sub array - while (i < len1 && j < len2) - { - if (left[i] <= right[j]) - { + while (i < len1 && j < len2) { + if (left[i] <= right[j]) { arr[k] = left[i]; i++; - } - else - { + } else { arr[k] = right[j]; j++; } @@ -51,16 +43,14 @@ void merge(int arr[], int l, int m, int r) } // copy remaining elements of left, if any - while (i < len1) - { + while (i < len1) { arr[k] = left[i]; k++; i++; } // copy remaining element of right, if any - while (j < len2) - { + while (j < len2) { arr[k] = right[j]; k++; j++; @@ -70,21 +60,18 @@ void merge(int arr[], int l, int m, int r) } // iterative Timsort function to sort the array[0...n-1] (similar to merge sort) -void timSort(int arr[], int n) -{ +void timSort(int arr[], int n) { // Sort individual subarrays of size RUN for (int i = 0; i < n; i += RUN) insertionSort(arr, i, std::min((i + 31), (n - 1))); // start merging from size RUN (or 32). It will merge to form size 64, then // 128, 256 and so on .... - for (int size = RUN; size < n; size = 2 * size) - { + for (int size = RUN; size < n; size = 2 * size) { // pick starting point of left sub array. We are going to merge // arr[left..left+size-1] and arr[left+size, left+2*size-1] After every // merge, we increase left by 2*size - for (int left = 0; left < n; left += 2 * size) - { + for (int left = 0; left < n; left += 2 * size) { // find ending point of left sub array // mid+1 is starting point of right sub array int mid = left + size - 1; @@ -97,15 +84,13 @@ void timSort(int arr[], int n) } // utility function to print the Array -void printArray(int arr[], int n) -{ +void printArray(int arr[], int n) { for (int i = 0; i < n; i++) printf("%d ", arr[i]); std::cout << std::endl; } // Driver program to test above function -int main() -{ +int main() { int arr[] = {5, 21, 7, 23, 19}; int n = sizeof(arr) / sizeof(arr[0]); printf("Given Array is\n"); diff --git a/strings/brute_force_string_searching.cpp b/strings/brute_force_string_searching.cpp index 5f6116e1b74..9a2b5327a35 100644 --- a/strings/brute_force_string_searching.cpp +++ b/strings/brute_force_string_searching.cpp @@ -17,18 +17,14 @@ * @return Index where the pattern starts in the text * @return -1 if the pattern was not found. */ -int brute_force(const std::string &text, const std::string &pattern) -{ +int brute_force(const std::string &text, const std::string &pattern) { size_t pat_l = pattern.length(); size_t txt_l = text.length(); int index = -1; - if (pat_l <= txt_l) - { - for (size_t i = 0; i < txt_l - pat_l + 1; i++) - { + if (pat_l <= txt_l) { + for (size_t i = 0; i < txt_l - pat_l + 1; i++) { std::string s = text.substr(i, pat_l); - if (s == pattern) - { + if (s == pattern) { index = i; break; } @@ -44,10 +40,8 @@ const std::vector> test_set = { {"bba", "bb", "0"}, {"bbca", "c", "2"}, {"ab", "b", "1"}}; /** Main function */ -int main() -{ - for (size_t i = 0; i < test_set.size(); i++) - { +int main() { + for (size_t i = 0; i < test_set.size(); i++) { int output = brute_force(test_set[i][0], test_set[i][1]); if (std::to_string(output) == test_set[i][2]) diff --git a/strings/knuth_morris_pratt.cpp b/strings/knuth_morris_pratt.cpp index 29e6ef834e2..b83cab96632 100644 --- a/strings/knuth_morris_pratt.cpp +++ b/strings/knuth_morris_pratt.cpp @@ -26,17 +26,14 @@ * \param[in] pattern text for which to create the partial match table * \returns the partial match table as a vector array */ -std::vector getFailureArray(const std::string &pattern) -{ +std::vector getFailureArray(const std::string &pattern) { int pattern_length = pattern.size(); std::vector failure(pattern_length + 1); failure[0] = -1; int j = -1; - for (int i = 0; i < pattern_length; i++) - { - while (j != -1 && pattern[j] != pattern[i]) - { + for (int i = 0; i < pattern_length; i++) { + while (j != -1 && pattern[j] != pattern[i]) { j = failure[j]; } j++; @@ -52,16 +49,13 @@ std::vector getFailureArray(const std::string &pattern) * \returns `true` if pattern was found * \returns `false` if pattern was not found */ -bool kmp(const std::string &pattern, const std::string &text) -{ +bool kmp(const std::string &pattern, const std::string &text) { int text_length = text.size(), pattern_length = pattern.size(); std::vector failure = getFailureArray(pattern); int k = 0; - for (int j = 0; j < text_length; j++) - { - while (k != -1 && pattern[k] != text[j]) - { + for (int j = 0; j < text_length; j++) { + while (k != -1 && pattern[k] != text[j]) { k = failure[k]; } k++; @@ -72,28 +66,21 @@ bool kmp(const std::string &pattern, const std::string &text) } /** Main function */ -int main() -{ +int main() { std::string text = "alskfjaldsabc1abc1abc12k23adsfabcabc"; std::string pattern = "abc1abc12l"; - if (kmp(pattern, text) == true) - { + if (kmp(pattern, text) == true) { std::cout << "Found" << std::endl; - } - else - { + } else { std::cout << "Not Found" << std::endl; } text = "abcabc"; pattern = "bca"; - if (kmp(pattern, text) == true) - { + if (kmp(pattern, text) == true) { std::cout << "Found" << std::endl; - } - else - { + } else { std::cout << "Not Found" << std::endl; } diff --git a/strings/rabin_karp.cpp b/strings/rabin_karp.cpp index 5baaaf61574..018ff56324f 100644 --- a/strings/rabin_karp.cpp +++ b/strings/rabin_karp.cpp @@ -21,11 +21,9 @@ * \param[in] n length of substring to hash * \returns hash integer */ -int64_t create_hash(const std::string& s, int n) -{ +int64_t create_hash(const std::string& s, int n) { int64_t result = 0; - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { result += (int64_t)(s[i] * (int64_t)pow(PRIME, i)); } return result; @@ -41,8 +39,7 @@ int64_t create_hash(const std::string& s, int n) * \returns new hash integer */ int64_t recalculate_hash(const std::string& s, int old_index, int new_index, - int64_t old_hash, int patLength) -{ + int64_t old_hash, int patLength) { int64_t new_hash = old_hash - s[old_index]; new_hash /= PRIME; new_hash += (int64_t)(s[new_index] * (int64_t)pow(PRIME, patLength - 1)); @@ -60,16 +57,12 @@ int64_t recalculate_hash(const std::string& s, int old_index, int new_index, * @note can this be replaced by std::string::compare? */ bool check_if_equal(const std::string& str1, const std::string& str2, - int start1, int end1, int start2, int end2) -{ - if (end1 - start1 != end2 - start2) - { + int start1, int end1, int start2, int end2) { + if (end1 - start1 != end2 - start2) { return false; } - while (start1 <= end1 && start2 <= end2) - { - if (str1[start1] != str2[start2]) - { + while (start1 <= end1 && start2 <= end2) { + if (str1[start1] != str2[start2]) { return false; } start1++; @@ -86,19 +79,16 @@ bool check_if_equal(const std::string& str1, const std::string& str2, * @return -1 if pattern not found */ -int rabin_karp(const std::string& str, const std::string& pat) -{ +int rabin_karp(const std::string& str, const std::string& pat) { int64_t pat_hash = create_hash(pat, pat.size()); int64_t str_hash = create_hash(str, pat.size()); - for (int i = 0; i <= str.size() - pat.size(); ++i) - { + for (int i = 0; i <= str.size() - pat.size(); ++i) { if (pat_hash == str_hash && - check_if_equal(str, pat, i, i + pat.size() - 1, 0, pat.size() - 1)) - { + check_if_equal(str, pat, i, i + pat.size() - 1, 0, + pat.size() - 1)) { return i; } - if (i < str.size() - pat.size()) - { + if (i < str.size() - pat.size()) { str_hash = recalculate_hash(str, i, i + pat.size(), str_hash, pat.size()); } @@ -107,8 +97,7 @@ int rabin_karp(const std::string& str, const std::string& pat) } /** Main function */ -int main(void) -{ +int main(void) { assert(rabin_karp("helloWorld", "world") == -1); assert(rabin_karp("helloWorld", "World") == 5); assert(rabin_karp("this_is_c++", "c++") == 8); From 3ab76459cd1e792636d7b55787ea30423efa038a Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 30 May 2020 04:02:28 +0000 Subject: [PATCH 287/433] updating DIRECTORY.md --- DIRECTORY.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index 33453868571..21f1a0c6102 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -1,3 +1,4 @@ +# List of all files ## Backtracking * [Graph Coloring](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/graph_coloring.cpp) @@ -77,7 +78,7 @@ * [Connected Components](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/connected_components.cpp) * [Connected Components With Dsu](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/connected_components_with_dsu.cpp) * [Dfs](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/dfs.cpp) - * [Dfs With Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/DFS_with_stack.cc) + * [Dfs With Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/dfs_with_stack.cpp) * [Dijkstra](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/dijkstra.cpp) * [Kosaraju](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/kosaraju.cpp) * [Kruskal](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/kruskal.cpp) From 642c7b7cb1de14efa2be031213139593ad5df212 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 30 May 2020 00:08:33 -0400 Subject: [PATCH 288/433] fix diff filename --- .github/workflows/awesome_forkflow.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/awesome_forkflow.yml b/.github/workflows/awesome_forkflow.yml index 11e585deec0..05094bdd1b9 100644 --- a/.github/workflows/awesome_forkflow.yml +++ b/.github/workflows/awesome_forkflow.yml @@ -146,7 +146,7 @@ jobs: - run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - run: git pull - run: git diff --diff-filter=dr --name-only origin/master > git_diff.txt - - run: echo "Files changed-- `cat diff.txt`" + - run: echo "Files changed-- `cat git_diff.txt`" - name: cpplint_modified_files shell: python run: | From b596b7e42d2a370d7acc6b33a768cc9097c141b2 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 30 May 2020 09:35:27 -0400 Subject: [PATCH 289/433] added comments to the code --- math/realtime_stats.cpp | 171 +++++++++++++++++++++++----------------- 1 file changed, 100 insertions(+), 71 deletions(-) diff --git a/math/realtime_stats.cpp b/math/realtime_stats.cpp index e1b8cfaa1cb..f853b827493 100644 --- a/math/realtime_stats.cpp +++ b/math/realtime_stats.cpp @@ -1,3 +1,11 @@ +/** + * \file + * \brief Compute statistics for data entered in rreal-time + * + * This algorithm is really beneficial to compute statistics on data read in + * realtime. For example, devices reading biometrics data. The algorithm is + * simple enough to be easily implemented in an embedded system. + */ #include #include @@ -8,31 +16,39 @@ template class stats_computer1 { public: - void new_val(T x) { - if (n == 0) K = x; - n++; - T tmp = x - K; - Ex += tmp; - Ex2 += tmp * tmp; - } - - double mean() const { return K + Ex / n; } - - double variance() const { return (Ex2 - (Ex * Ex) / n) / (n - 1); } - - double std() const { return std::sqrt(this->variance()); } - - friend std::istream &operator>>(std::istream &input, stats_computer1 &stat) { - T val; - input >> val; - stat.new_val(val); - return input; - } + /** Constructor + * \param[in] x new data sample + */ + void new_val(T x) { + if (n == 0) K = x; + n++; + T tmp = x - K; + Ex += tmp; + Ex2 += tmp * tmp; + } + + /** return sample mean computed till last sample */ + double mean() const { return K + Ex / n; } + + /** return data variance computed till last sample */ + double variance() const { return (Ex2 - (Ex * Ex) / n) / (n - 1); } + + /** return sample standard deviation computed till last sample */ + double std() const { return std::sqrt(this->variance()); } + + /** short-hand operator to read new sample from input stream */ + friend std::istream &operator>>(std::istream &input, + stats_computer1 &stat) { + T val; + input >> val; + stat.new_val(val); + return input; + } private: - unsigned int n = 0; - double Ex, Ex2; - T K; + unsigned int n = 0; + double Ex, Ex2; + T K; }; /** @@ -42,57 +58,70 @@ class stats_computer1 { template class stats_computer2 { public: - void new_val(T x) { - n++; - double delta = x - mu; - mu += delta / n; - double delta2 = x - mu; - M += delta * delta2; - } - - double mean() const { return mu; } - - double variance() const { return M / n; } - - double std() const { return std::sqrt(this->variance()); } - - friend std::istream &operator>>(std::istream &input, stats_computer2 &stat) { - T val; - input >> val; - stat.new_val(val); - return input; - } + /** Constructor + * \param[in] x new data sample + */ + void new_val(T x) { + n++; + double delta = x - mu; + mu += delta / n; + double delta2 = x - mu; + M += delta * delta2; + } + + /** return sample mean computed till last sample */ + double mean() const { return mu; } + + /** return data variance computed till last sample */ + double variance() const { return M / n; } + + /** return sample standard deviation computed till last sample */ + double std() const { return std::sqrt(this->variance()); } + + /** short-hand operator to read new sample from input stream */ + friend std::istream &operator>>(std::istream &input, + stats_computer2 &stat) { + T val; + input >> val; + stat.new_val(val); + return input; + } private: - unsigned int n = 0; - double mu = 0, var = 0, M = 0; + unsigned int n = 0; + double mu = 0, var = 0, M = 0; }; +/** Main function */ int main(int argc, char **argv) { - std::cout << "Enter data. Any non-numeric data will terminate the data input." - << std::endl; - - stats_computer1 stats1; - stats_computer2 stats2; - - while (1) { - double val; - std::cout << "Enter number: "; - std::cin >> val; - if (std::cin.fail()) // check for failure to read input. Happens for - // non-numeric data - break; - stats1.new_val(val); - stats2.new_val(val); - std::cout << "\tMethod 1:" - << "\tMean: " << stats1.mean() - << "\t Variance: " << stats1.variance() - << "\t Std: " << stats1.std() << std::endl; - std::cout << "\tMethod 2:" - << "\tMean: " << stats2.mean() - << "\t Variance: " << stats2.variance() - << "\t Std: " << stats2.std() << std::endl; - } - - return 0; + std::cout + << "Enter data. Any non-numeric data will terminate the data input." + << std::endl; + + stats_computer1 stats1; + stats_computer2 stats2; + + while (1) { + double val; + std::cout << "Enter number: "; + std::cin >> val; + + // check for failure to read input. Happens for + // non-numeric data + if (std::cin.fail()) break; + + stats1.new_val(val); + stats2.new_val(val); + + std::cout << "\tMethod 1:" + << "\tMean: " << stats1.mean() + << "\t Variance: " << stats1.variance() + << "\t Std: " << stats1.std() << std::endl; + std::cout << "\tMethod 2:" + << "\tMean: " << stats2.mean() + << "\t Variance: " << stats2.variance() + << "\t Std: " << stats2.std() << std::endl; + } + + return 0; } From 72f53da5a912e10e4bf0c85b96128c1c0e0e0770 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 30 May 2020 11:00:08 -0400 Subject: [PATCH 290/433] added test case --- math/realtime_stats.cpp | 64 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 58 insertions(+), 6 deletions(-) diff --git a/math/realtime_stats.cpp b/math/realtime_stats.cpp index f853b827493..d2b55a3cd65 100644 --- a/math/realtime_stats.cpp +++ b/math/realtime_stats.cpp @@ -6,13 +6,16 @@ * realtime. For example, devices reading biometrics data. The algorithm is * simple enough to be easily implemented in an embedded system. */ +#include #include #include /** * continuous mean and variance computance using - * first value as an approximation for the mean - **/ + * first value as an approximation for the mean. + * If the first number is much far form the mean, the algorithm becomes very + * inaccurate to compute variance and standard deviation. + */ template class stats_computer1 { public: @@ -36,7 +39,9 @@ class stats_computer1 { /** return sample standard deviation computed till last sample */ double std() const { return std::sqrt(this->variance()); } - /** short-hand operator to read new sample from input stream */ + /** short-hand operator to read new sample from input stream + * \n e.g.: `std::cin >> stats1;` + */ friend std::istream &operator>>(std::istream &input, stats_computer1 &stat) { T val; @@ -53,8 +58,8 @@ class stats_computer1 { /** * continuous mean and variance computance using - * Welford's algorithm - **/ + * Welford's algorithm (very accurate) + */ template class stats_computer2 { public: @@ -78,7 +83,9 @@ class stats_computer2 { /** return sample standard deviation computed till last sample */ double std() const { return std::sqrt(this->variance()); } - /** short-hand operator to read new sample from input stream */ + /** short-hand operator to read new sample from input stream + * \n e.g.: `std::cin >> stats1;` + */ friend std::istream &operator>>(std::istream &input, stats_computer2 &stat) { T val; @@ -92,8 +99,53 @@ class stats_computer2 { double mu = 0, var = 0, M = 0; }; +/** Test the algorithm implementation + * \param[in] test_data array of data to test the algorithms + */ +void test_function(const float *test_data, const int number_of_samples) { + float mean = 0.f, variance = 0.f; + + stats_computer1 stats01; + stats_computer2 stats02; + + for (int i = 0; i < number_of_samples; i++) { + stats01.new_val(test_data[i]); + stats02.new_val(test_data[i]); + mean += test_data[i]; + } + + mean /= number_of_samples; + + for (int i = 0; i < number_of_samples; i++) { + float temp = test_data[i] - mean; + variance += temp * temp; + } + variance /= number_of_samples; + + std::cout << "<<<<<<<< Test Function >>>>>>>>" << std::endl + << "Expected: Mean: " << mean << "\t Variance: " << variance + << std::endl; + std::cout << "\tMethod 1:" + << "\tMean: " << stats01.mean() + << "\t Variance: " << stats01.variance() + << "\t Std: " << stats01.std() << std::endl; + std::cout << "\tMethod 2:" + << "\tMean: " << stats02.mean() + << "\t Variance: " << stats02.variance() + << "\t Std: " << stats02.std() << std::endl; + + assert(std::abs(stats01.mean() - mean) < 0.01); + assert(std::abs(stats02.mean() - mean) < 0.01); + assert(std::abs(stats02.variance() - variance) < 0.01); + + std::cout << "(Tests passed)" << std::endl; +} + /** Main function */ int main(int argc, char **argv) { + const float test_data1[] = {3, 4, 5, -1.4, -3.6, 1.9, 1.}; + test_function(test_data1, sizeof(test_data1) / sizeof(test_data1[0])); + std::cout << "Enter data. Any non-numeric data will terminate the data input." << std::endl; From 227c4557928722dd138737315ed9cefb9a62443c Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 30 May 2020 17:16:07 +0000 Subject: [PATCH 291/433] formatting source-code for a850308fbada18c0d4b6f9a9cac5c34fc064cbae --- math/realtime_stats.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/math/realtime_stats.cpp b/math/realtime_stats.cpp index d2b55a3cd65..2fbfc9bd58e 100644 --- a/math/realtime_stats.cpp +++ b/math/realtime_stats.cpp @@ -23,7 +23,8 @@ class stats_computer1 { * \param[in] x new data sample */ void new_val(T x) { - if (n == 0) K = x; + if (n == 0) + K = x; n++; T tmp = x - K; Ex += tmp; @@ -160,7 +161,8 @@ int main(int argc, char **argv) { // check for failure to read input. Happens for // non-numeric data - if (std::cin.fail()) break; + if (std::cin.fail()) + break; stats1.new_val(val); stats2.new_val(val); From 704e114bd29b0a4436cf9742ed98c419aee17db9 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 30 May 2020 17:16:34 +0000 Subject: [PATCH 292/433] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 21f1a0c6102..919fae16532 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -122,6 +122,7 @@ * [Prime Factorization](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/prime_factorization.cpp) * [Prime Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/prime_numbers.cpp) * [Primes Up To Billion](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/primes_up_to_billion.cpp) + * [Realtime Stats](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/realtime_stats.cpp) * [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/sieve_of_eratosthenes.cpp) * [Sqrt Double](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/sqrt_double.cpp) * [String Fibonacci](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/string_fibonacci.cpp) From 3bb7120927878c154f002f8437f24baf656d92e6 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 30 May 2020 21:23:51 -0400 Subject: [PATCH 293/433] added machine learning folder --- CMakeLists.txt | 1 + machine_learning/CMakeLists.txt | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) create mode 100644 machine_learning/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index 95c09d8e2e8..5030f3bb1bf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -59,6 +59,7 @@ add_subdirectory(search) add_subdirectory(strings) add_subdirectory(sorting) add_subdirectory(probability) +add_subdirectory(machine_learning) add_subdirectory(computer_oriented_statistical_methods) if(USE_OPENMP) diff --git a/machine_learning/CMakeLists.txt b/machine_learning/CMakeLists.txt new file mode 100644 index 00000000000..e6d8a9af405 --- /dev/null +++ b/machine_learning/CMakeLists.txt @@ -0,0 +1,18 @@ +# If necessary, use the RELATIVE flag, otherwise each source file may be listed +# with full pathname. RELATIVE may makes it easier to extract an executable name +# automatically. +file( GLOB APP_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp ) +# file( GLOB APP_SOURCES ${CMAKE_SOURCE_DIR}/*.c ) +# AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR} APP_SOURCES) +foreach( testsourcefile ${APP_SOURCES} ) + # I used a simple string replace, to cut off .cpp. + string( REPLACE ".cpp" "" testname ${testsourcefile} ) + add_executable( ${testname} ${testsourcefile} ) + + set_target_properties(${testname} PROPERTIES LINKER_LANGUAGE CXX) + if(OpenMP_CXX_FOUND) + target_link_libraries(${testname} OpenMP::OpenMP_CXX) + endif() + install(TARGETS ${testname} DESTINATION "bin/machine_learning") + +endforeach( testsourcefile ${APP_SOURCES} ) From c52952c0f64e925fa943df2c2657b879b8f25500 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 30 May 2020 21:25:37 -0400 Subject: [PATCH 294/433] added adaline algorithm --- machine_learning/adaline_learning.cpp | 267 ++++++++++++++++++++++++++ 1 file changed, 267 insertions(+) create mode 100644 machine_learning/adaline_learning.cpp diff --git a/machine_learning/adaline_learning.cpp b/machine_learning/adaline_learning.cpp new file mode 100644 index 00000000000..b298139848d --- /dev/null +++ b/machine_learning/adaline_learning.cpp @@ -0,0 +1,267 @@ +/** + * \file + * \brief [Adaptive Linear Neuron + * (ADALINE)](https://en.wikipedia.org/wiki/ADALINE) implementation + * + * + * [source](https://commons.wikimedia.org/wiki/File:Adaline_flow_chart.gif) + * ADALINE is one of the first and simplest single layer artificial neural + * network. The algorithm essentially implements a linear function + * \f[ f\left(x_0,x_1,x_2,\ldots\right) = + * \sum_j x_jw_j+\theta + * \f] + * where \f$x_j\f$ are the input features of a sample, \f$w_j\f$ are the + * coefficients of the linear function and \f$\theta\f$ is a constant. If we + * know the \f$w_j\f$, then for any given set of features, \f$y\f$ can be + * computed. Computing the \f$w_j\f$ is a supervised learning algorithm wherein + * a set of features and their corresponding outputs are given and weights are + * computed using stochastic gradient descent method. + */ + +#include +#include +#include +#include +#include + +#define MAX_ITER 500 // INT_MAX ///< Maximum number of iterations to learn + +class adaline { + public: + /** + * Default constructor + * \param[in] num_features number of features present + * \param[in] eta learning rate (optional, default=0.1) + * \param[in] convergence accuracy (optional, default=\f$1\times10^{-5}\f$) + */ + adaline(int num_features, const double eta = 0.01f, + const double accuracy = 1e-5) + : eta(eta), accuracy(accuracy) { + if (eta <= 0) { + std::cerr << "learning rate should be positive and nonzero" + << std::endl; + std::exit(EXIT_FAILURE); + } + + weights = std::vector( + num_features + + 1); // additional weight is for the constant bias term + + // initialize with random weights in the range [-50, 49] + for (int i = 0; i < weights.size(); i++) + weights[i] = (static_cast(std::rand() % 100) - 50); + } + + /** + * Operator to print the weights of the model + */ + friend std::ostream &operator<<(std::ostream &out, const adaline &ada) { + out << "<"; + for (int i = 0; i < ada.weights.size(); i++) { + out << ada.weights[i]; + if (i < ada.weights.size() - 1) + out << ", "; + } + out << ">"; + return out; + } + + /** + * predict the output of the model for given set of features + * \param[in] x input vector + * \returns model prediction output + */ + int predict(const std::vector &x) { + if (!check_size_match(x)) + return 0; + + double y = weights.back(); // assign bias value + + for (int i = 0; i < x.size(); i++) y += x[i] * weights[i]; + + return y >= 0 ? 1 : -1; // quantizer: apply ADALINE threshold function + } + + /** + * Update the weights of the model using supervised learning for one feature + * vector + * \param[in] x feature vector + * \param[in] y known output value + * \returns correction factor + */ + double fit(const std::vector &x, const int &y) { + if (!check_size_match(x)) + return 0; + + /* output of the model with current weights */ + int p = predict(x); + int prediction_error = y - p; // error in estimation + double correction_factor = eta * prediction_error; + + /* update each weight, the last weight is the bias term */ + for (int i = 0; i < x.size(); i++) { + weights[i] += correction_factor * x[i]; + } + weights[x.size()] += correction_factor; // update bias + + return correction_factor; + } + + /** + * Update the weights of the model using supervised learning for an array of + * vectors. + * \param[in] X array of feature vector + * \param[in] y known output value for each feature vector + */ + template + void fit(std::vector const (&X)[N], const int *y) { + double avg_pred_error = 1.f; + + int iter; + for (iter = 0; (iter < MAX_ITER) && (avg_pred_error > accuracy); + iter++) { + avg_pred_error = 0.f; + + // perform fit for each sample + for (int i = 0; i < N; i++) { + double err = fit(X[i], y[i]); + avg_pred_error += std::abs(err); + } + avg_pred_error /= N; + + // Print updates every 200th iteration + // if (iter % 100 == 0) + std::cout << "\tIter " << iter << ": Training weights: " << *this + << "\tAvg error: " << avg_pred_error << std::endl; + } + + if (iter < MAX_ITER) + + std::cout << "Converged after " << iter << " iterations." + << std::endl; + else + std::cout << "Did not converge after " << iter << " iterations." + << std::endl; + } + + private: + /** + * convenient function to check if input feature vector size matches the + * model weights size + * \param[in] x fecture vector to check + * \returns `true` size matches + * \returns `false` size does not match + */ + bool check_size_match(const std::vector &x) { + if (x.size() != (weights.size() - 1)) { + std::cerr << __func__ << ": " + << "Number of features in x does not match the feature " + "dimension in model!" + << std::endl; + return false; + } + return true; + } + + const double eta; ///< learning rate of the algorithm + const double accuracy; ///< model fit convergence accuracy + std::vector weights; ///< weights of the neural network +}; + +/** + * test function to predict points in a 2D coordinate system above the line + * \f$x=y\f$ as +1 and others as -1. + * Note that each point is defined by 2 values or 2 features. + * \param[in] eta learning rate (optional, default=0.01) + */ +void test1(double eta = 0.01) { + adaline ada(2, eta); // 2 features + + const int N = 10; // number of sample points + + std::vector X[N] = {{0, 1}, {1, -2}, {2, 3}, {3, -1}, + {4, 1}, {6, -5}, {-7, -3}, {-8, 5}, + {-9, 2}, {-10, -15}}; + int y[] = {1, -1, 1, -1, -1, -1, 1, 1, 1, -1}; // corresponding y-values + + std::cout << "------- Test 1 -------" << std::endl; + std::cout << "Model before fit: " << ada << std::endl; + + ada.fit(X, y); + std::cout << "Model after fit: " << ada << std::endl; + + int predict = ada.predict({5, -3}); + std::cout << "Predict for x=(5,-3): " << predict; + assert(predict == -1); + std::cout << " ...passed" << std::endl; + + predict = ada.predict({5, 8}); + std::cout << "Predict for x=(5,8): " << predict; + assert(predict == 1); + std::cout << " ...passed" << std::endl; +} + +/** + * test function to predict points in a 2D coordinate system above the line + * \f$x+y=-1\f$ as +1 and others as -1. + * Note that each point is defined by 2 values or 2 features. + * The function will create random sample points for training and test purposes. + * \param[in] eta learning rate (optional, default=0.01) + */ +void test2(double eta = 0.01) { + adaline ada(2, eta); // 2 features + + const int N = 50; // number of sample points + + std::vector X[N]; + int Y[N]; // corresponding y-values + + int range = 500; // sample points range + int range2 = range >> 1; + for (int i = 0; i < N; i++) { + double x0 = ((std::rand() % range) - range2) / 100.f; + double x1 = ((std::rand() % range) - range2) / 100.f; + X[i] = {x0, x1}; + Y[i] = (x0 + x1) > -1 ? 1 : -1; + } + + std::cout << "------- Test 1 -------" << std::endl; + std::cout << "Model before fit: " << ada << std::endl; + + ada.fit(X, Y); + std::cout << "Model after fit: " << ada << std::endl; + + int N_test_cases = 5; + for (int i = 0; i < N_test_cases; i++) { + double x0 = ((std::rand() % range) - range2) / 100.f; + double x1 = ((std::rand() % range) - range2) / 100.f; + + int predict = ada.predict({x0, x1}); + + std::cout << "Predict for x=(" << x0 << "," << x1 << "): " << predict; + + int expected_val = (x0 + x1) > -1 ? 1 : -1; + assert(predict == expected_val); + std::cout << " ...passed" << std::endl; + } +} + +/** Main function */ +int main(int argc, char **argv) { + std::srand(std::time(nullptr)); // initialize random number generator + + double eta = 0.2; // default value of eta + if (argc == 2) // read eta value from commandline argument if present + eta = strtof(argv[1], nullptr); + + test1(eta); + + std::cout << "Press ENTER to continue..." << std::endl; + std::cin.get(); + + test2(eta); + + return 0; +} From 7d069167d67adaeeaab251258774d1b97b0c5e01 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 31 May 2020 01:27:56 +0000 Subject: [PATCH 295/433] updating DIRECTORY.md --- DIRECTORY.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 919fae16532..79589f90cb0 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -101,6 +101,9 @@ * [Linear Probing Hash Table](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/linear_probing_hash_table.cpp) * [Quadratic Probing Hash Table](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/quadratic_probing_hash_table.cpp) +## Machine Learning + * [Adaline Learning](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/machine_learning/adaline_learning.cpp) + ## Math * [Binary Exponent](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/binary_exponent.cpp) * [Double Factorial](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/double_factorial.cpp) From 4025aa92e5d1b84fe3b8fe31206c99d63f205e52 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 30 May 2020 21:36:17 -0400 Subject: [PATCH 296/433] fixed issue [LWG2192](https://cplusplus.github.io/LWG/issue2192) for std::abs on MacOS --- machine_learning/adaline_learning.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/machine_learning/adaline_learning.cpp b/machine_learning/adaline_learning.cpp index b298139848d..29eccd88613 100644 --- a/machine_learning/adaline_learning.cpp +++ b/machine_learning/adaline_learning.cpp @@ -22,6 +22,7 @@ #include #include +#include #include #include #include From f8925e482216aecd152bc898653ee9ab82213cf3 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 30 May 2020 21:46:28 -0400 Subject: [PATCH 297/433] add cmath for same bug: [LWG2192](https://cplusplus.github.io/LWG/issue2192) for std::abs on MacOS --- machine_learning/adaline_learning.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/machine_learning/adaline_learning.cpp b/machine_learning/adaline_learning.cpp index 29eccd88613..871c7807454 100644 --- a/machine_learning/adaline_learning.cpp +++ b/machine_learning/adaline_learning.cpp @@ -22,10 +22,11 @@ #include #include -#include #include #include #include +#include +#include #define MAX_ITER 500 // INT_MAX ///< Maximum number of iterations to learn From 1c05a58cea3b5697e79fd865bcd06f2c4d3f948c Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 31 May 2020 01:47:10 +0000 Subject: [PATCH 298/433] formatting source-code for f8925e482216aecd152bc898653ee9ab82213cf3 --- machine_learning/adaline_learning.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/machine_learning/adaline_learning.cpp b/machine_learning/adaline_learning.cpp index 871c7807454..a58b59ccaa6 100644 --- a/machine_learning/adaline_learning.cpp +++ b/machine_learning/adaline_learning.cpp @@ -22,11 +22,11 @@ #include #include +#include +#include #include #include #include -#include -#include #define MAX_ITER 500 // INT_MAX ///< Maximum number of iterations to learn From f94a3305943d4cf00e4531857279b8032d0e9489 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 31 May 2020 06:41:26 -0400 Subject: [PATCH 299/433] use STL's inner_product --- machine_learning/adaline_learning.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/machine_learning/adaline_learning.cpp b/machine_learning/adaline_learning.cpp index a58b59ccaa6..f271289e334 100644 --- a/machine_learning/adaline_learning.cpp +++ b/machine_learning/adaline_learning.cpp @@ -27,6 +27,7 @@ #include #include #include +#include #define MAX_ITER 500 // INT_MAX ///< Maximum number of iterations to learn @@ -81,7 +82,8 @@ class adaline { double y = weights.back(); // assign bias value - for (int i = 0; i < x.size(); i++) y += x[i] * weights[i]; + // for (int i = 0; i < x.size(); i++) y += x[i] * weights[i]; + y = std::inner_product(x.begin(), x.end(), weights.begin(), y); return y >= 0 ? 1 : -1; // quantizer: apply ADALINE threshold function } @@ -229,7 +231,7 @@ void test2(double eta = 0.01) { Y[i] = (x0 + x1) > -1 ? 1 : -1; } - std::cout << "------- Test 1 -------" << std::endl; + std::cout << "------- Test 2 -------" << std::endl; std::cout << "Model before fit: " << ada << std::endl; ada.fit(X, Y); From 8d7d0c585272f1ffd98c2ab94c6583343a18289a Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 31 May 2020 10:42:21 +0000 Subject: [PATCH 300/433] formatting source-code for f94a3305943d4cf00e4531857279b8032d0e9489 --- machine_learning/adaline_learning.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/machine_learning/adaline_learning.cpp b/machine_learning/adaline_learning.cpp index f271289e334..6d0167a54b0 100644 --- a/machine_learning/adaline_learning.cpp +++ b/machine_learning/adaline_learning.cpp @@ -26,8 +26,8 @@ #include #include #include -#include #include +#include #define MAX_ITER 500 // INT_MAX ///< Maximum number of iterations to learn From a07c46c089812eac504cb1e2dc2684e754b37307 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 31 May 2020 07:33:50 -0400 Subject: [PATCH 301/433] added range comments --- machine_learning/adaline_learning.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/machine_learning/adaline_learning.cpp b/machine_learning/adaline_learning.cpp index 6d0167a54b0..7503413788c 100644 --- a/machine_learning/adaline_learning.cpp +++ b/machine_learning/adaline_learning.cpp @@ -222,8 +222,10 @@ void test2(double eta = 0.01) { std::vector X[N]; int Y[N]; // corresponding y-values - int range = 500; // sample points range - int range2 = range >> 1; + // generate sample points in the interval + // [-range2/100 , (range2-1)/100] + int range = 500; // sample points full-range + int range2 = range >> 1; // sample points half-range for (int i = 0; i < N; i++) { double x0 = ((std::rand() % range) - range2) / 100.f; double x1 = ((std::rand() % range) - range2) / 100.f; From 6536a791edd7a4f7a51b281bcebffe92fc5d2241 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 31 May 2020 07:48:53 -0400 Subject: [PATCH 302/433] define activation function --- machine_learning/adaline_learning.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/machine_learning/adaline_learning.cpp b/machine_learning/adaline_learning.cpp index 7503413788c..18c79ecbb08 100644 --- a/machine_learning/adaline_learning.cpp +++ b/machine_learning/adaline_learning.cpp @@ -85,7 +85,7 @@ class adaline { // for (int i = 0; i < x.size(); i++) y += x[i] * weights[i]; y = std::inner_product(x.begin(), x.end(), weights.begin(), y); - return y >= 0 ? 1 : -1; // quantizer: apply ADALINE threshold function + return activation(y); // quantizer: apply ADALINE threshold function } /** @@ -150,6 +150,8 @@ class adaline { << std::endl; } + friend int activation(double x) { return x > 0 ? 1 : -1; } + private: /** * convenient function to check if input feature vector size matches the From 9ded2c120c654718d9371307fc2841d19d00073e Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 31 May 2020 07:49:29 -0400 Subject: [PATCH 303/433] use equal initial weights --- machine_learning/adaline_learning.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/machine_learning/adaline_learning.cpp b/machine_learning/adaline_learning.cpp index 18c79ecbb08..6bfa2671dc3 100644 --- a/machine_learning/adaline_learning.cpp +++ b/machine_learning/adaline_learning.cpp @@ -53,8 +53,8 @@ class adaline { 1); // additional weight is for the constant bias term // initialize with random weights in the range [-50, 49] - for (int i = 0; i < weights.size(); i++) - weights[i] = (static_cast(std::rand() % 100) - 50); + for (int i = 0; i < weights.size(); i++) weights[i] = 1.f; + // weights[i] = (static_cast(std::rand() % 100) - 50); } /** From 14068efe18995a9373563896e36e3ff6bd1e7498 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 31 May 2020 07:49:47 -0400 Subject: [PATCH 304/433] change test2 function to predict --- machine_learning/adaline_learning.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/machine_learning/adaline_learning.cpp b/machine_learning/adaline_learning.cpp index 6bfa2671dc3..73a8f463372 100644 --- a/machine_learning/adaline_learning.cpp +++ b/machine_learning/adaline_learning.cpp @@ -211,7 +211,7 @@ void test1(double eta = 0.01) { /** * test function to predict points in a 2D coordinate system above the line - * \f$x+y=-1\f$ as +1 and others as -1. + * \f$x+3y=-1\f$ as +1 and others as -1. * Note that each point is defined by 2 values or 2 features. * The function will create random sample points for training and test purposes. * \param[in] eta learning rate (optional, default=0.01) From 0e285920aa9bd03fbd3220c7b13022e21cd649e6 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 31 May 2020 07:53:19 -0400 Subject: [PATCH 305/433] activation function not friend --- machine_learning/adaline_learning.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/machine_learning/adaline_learning.cpp b/machine_learning/adaline_learning.cpp index 73a8f463372..278376fea8f 100644 --- a/machine_learning/adaline_learning.cpp +++ b/machine_learning/adaline_learning.cpp @@ -150,7 +150,7 @@ class adaline { << std::endl; } - friend int activation(double x) { return x > 0 ? 1 : -1; } + int activation(double x) { return x > 0 ? 1 : -1; } private: /** From b1c6556475a43bac092f0529239fbb429e83f647 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 31 May 2020 08:08:26 -0400 Subject: [PATCH 306/433] previous commit correction --- machine_learning/adaline_learning.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/machine_learning/adaline_learning.cpp b/machine_learning/adaline_learning.cpp index 278376fea8f..ec0dd27c80e 100644 --- a/machine_learning/adaline_learning.cpp +++ b/machine_learning/adaline_learning.cpp @@ -232,7 +232,7 @@ void test2(double eta = 0.01) { double x0 = ((std::rand() % range) - range2) / 100.f; double x1 = ((std::rand() % range) - range2) / 100.f; X[i] = {x0, x1}; - Y[i] = (x0 + x1) > -1 ? 1 : -1; + Y[i] = (x0 + 3. * x1) > -1 ? 1 : -1; } std::cout << "------- Test 2 -------" << std::endl; From 2d44fb1e76ed8d336a98b74ebe36476e30c81d15 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 31 May 2020 08:09:05 -0400 Subject: [PATCH 307/433] added option for predict function to return value before applying activation function as optional argument --- machine_learning/adaline_learning.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/machine_learning/adaline_learning.cpp b/machine_learning/adaline_learning.cpp index ec0dd27c80e..562958d647e 100644 --- a/machine_learning/adaline_learning.cpp +++ b/machine_learning/adaline_learning.cpp @@ -74,9 +74,11 @@ class adaline { /** * predict the output of the model for given set of features * \param[in] x input vector + * \param[out] out optional argument to return neuron output before applying + * activation function (optional, `nullptr` to ignore) * \returns model prediction output */ - int predict(const std::vector &x) { + int predict(const std::vector &x, double *out = nullptr) { if (!check_size_match(x)) return 0; @@ -85,6 +87,9 @@ class adaline { // for (int i = 0; i < x.size(); i++) y += x[i] * weights[i]; y = std::inner_product(x.begin(), x.end(), weights.begin(), y); + if (out != nullptr) // if out variable is provided + *out = y; + return activation(y); // quantizer: apply ADALINE threshold function } From 5e6c37444526008480ef2d9934e0792b04a98d53 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 31 May 2020 08:10:33 -0400 Subject: [PATCH 308/433] added test case to classify points lying within a sphere --- machine_learning/adaline_learning.cpp | 59 ++++++++++++++++++++++++++- 1 file changed, 57 insertions(+), 2 deletions(-) diff --git a/machine_learning/adaline_learning.cpp b/machine_learning/adaline_learning.cpp index 562958d647e..a484e27aa55 100644 --- a/machine_learning/adaline_learning.cpp +++ b/machine_learning/adaline_learning.cpp @@ -255,7 +255,57 @@ void test2(double eta = 0.01) { std::cout << "Predict for x=(" << x0 << "," << x1 << "): " << predict; - int expected_val = (x0 + x1) > -1 ? 1 : -1; + int expected_val = (x0 + 3. * x1) > -1 ? 1 : -1; + assert(predict == expected_val); + std::cout << " ...passed" << std::endl; + } +} + +/** + * test function to predict points in a 3D coordinate system lying within the + * sphere of radius 1 and centre at origin as +1 and others as -1. Note that + * each point is defined by 3 values but we use 6 features. The function will + * create random sample points for training and test purposes. + * \param[in] eta learning rate (optional, default=0.01) + */ +void test3(double eta = 0.01) { + adaline ada(6, eta); // 2 features + + const int N = 100; // number of sample points + + std::vector X[N]; + int Y[N]; // corresponding y-values + + // generate sample points in the interval + // [-range2/100 , (range2-1)/100] + int range = 200; // sample points full-range + int range2 = range >> 1; // sample points half-range + for (int i = 0; i < N; i++) { + double x0 = ((std::rand() % range) - range2) / 100.f; + double x1 = ((std::rand() % range) - range2) / 100.f; + double x2 = ((std::rand() % range) - range2) / 100.f; + X[i] = {x0, x1, x2, x0 * x0, x1 * x1, x2 * x2}; + Y[i] = ((x0 * x0) + (x1 * x1) + (x2 * x2)) <= 1.f ? 1 : -1; + } + + std::cout << "------- Test 3 -------" << std::endl; + std::cout << "Model before fit: " << ada << std::endl; + + ada.fit(X, Y); + std::cout << "Model after fit: " << ada << std::endl; + + int N_test_cases = 5; + for (int i = 0; i < N_test_cases; i++) { + double x0 = ((std::rand() % range) - range2) / 100.f; + double x1 = ((std::rand() % range) - range2) / 100.f; + double x2 = ((std::rand() % range) - range2) / 100.f; + + int predict = ada.predict({x0, x1, x2, x0 * x0, x1 * x1, x2 * x2}); + + std::cout << "Predict for x=(" << x0 << "," << x1 << "," << x2 + << "): " << predict; + + int expected_val = ((x0 * x0) + (x1 * x1) + (x2 * x2)) <= 1.f ? 1 : -1; assert(predict == expected_val); std::cout << " ...passed" << std::endl; } @@ -265,7 +315,7 @@ void test2(double eta = 0.01) { int main(int argc, char **argv) { std::srand(std::time(nullptr)); // initialize random number generator - double eta = 0.2; // default value of eta + double eta = 0.1; // default value of eta if (argc == 2) // read eta value from commandline argument if present eta = strtof(argv[1], nullptr); @@ -276,5 +326,10 @@ int main(int argc, char **argv) { test2(eta); + std::cout << "Press ENTER to continue..." << std::endl; + std::cin.get(); + + test3(eta); + return 0; } From 82f3fff6721fe00ce4282fc5ff30838055a545bd Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 31 May 2020 09:22:46 -0400 Subject: [PATCH 309/433] improve documentation for adaline --- machine_learning/adaline_learning.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/machine_learning/adaline_learning.cpp b/machine_learning/adaline_learning.cpp index a484e27aa55..055c3b776e2 100644 --- a/machine_learning/adaline_learning.cpp +++ b/machine_learning/adaline_learning.cpp @@ -266,6 +266,10 @@ void test2(double eta = 0.01) { * sphere of radius 1 and centre at origin as +1 and others as -1. Note that * each point is defined by 3 values but we use 6 features. The function will * create random sample points for training and test purposes. + * The sphere centred at origin and radius 1 is defined as: + * \f$x^2+y^2+z^2=r^2=1\f$ and if the \f$r^2<1\f$, point lies within the sphere + * else, outside. + * * \param[in] eta learning rate (optional, default=0.01) */ void test3(double eta = 0.01) { From 1ffb26165ff2aa8c5bd71e3184f2591adbfbe19b Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 31 May 2020 13:23:01 +0000 Subject: [PATCH 310/433] formatting source-code for 15ec4c3aba4fb41b81ed2b44b7154a4f7b45a898 --- geometry/line_segment_intersection.cpp | 60 +++++++++++++------------- 1 file changed, 31 insertions(+), 29 deletions(-) diff --git a/geometry/line_segment_intersection.cpp b/geometry/line_segment_intersection.cpp index 0b5b858d747..f386c5623d6 100644 --- a/geometry/line_segment_intersection.cpp +++ b/geometry/line_segment_intersection.cpp @@ -20,57 +20,59 @@ struct Point { */ struct SegmentIntersection { inline bool intersect(Point first_point, Point second_point, - Point third_point, Point forth_point) { + Point third_point, Point forth_point) { int direction1 = direction(third_point, forth_point, first_point); int direction2 = direction(third_point, forth_point, second_point); int direction3 = direction(first_point, second_point, third_point); int direction4 = direction(first_point, second_point, forth_point); - if ((direction1 < 0 || direction2 > 0) && (direction3 < 0 || - direction4 > 0)) + if ((direction1 < 0 || direction2 > 0) && + (direction3 < 0 || direction4 > 0)) return true; - else if (direction1 == 0 && on_segment(third_point, forth_point, - first_point)) + else if (direction1 == 0 && + on_segment(third_point, forth_point, first_point)) return true; - else if (direction2 == 0 && on_segment(third_point, forth_point, - second_point)) + else if (direction2 == 0 && + on_segment(third_point, forth_point, second_point)) return true; - else if (direction3 == 0 && on_segment(first_point, second_point, - third_point)) + else if (direction3 == 0 && + on_segment(first_point, second_point, third_point)) return true; - else if (direction3 == 0 && on_segment(first_point, second_point, - forth_point)) + else if (direction3 == 0 && + on_segment(first_point, second_point, forth_point)) return true; else return false; } - /** - * We will find direction of line here respect to @first_point. - * Here @second_point and @third_point is first and second points - * of the line respectively. we want a method to determine which way a - * given angle these three points turns. If returned number is negative, - * then the angle is counter-clockwise. That means the line is going to - * right to left. We will fount angle as clockwise if the method returns - * positive number. - */ + /** + * We will find direction of line here respect to @first_point. + * Here @second_point and @third_point is first and second points + * of the line respectively. we want a method to determine which way a + * given angle these three points turns. If returned number is negative, + * then the angle is counter-clockwise. That means the line is going to + * right to left. We will fount angle as clockwise if the method returns + * positive number. + */ inline int direction(Point first_point, Point second_point, - Point third_point) { - return ((third_point.x-first_point.x)*(second_point.y-first_point.y))- - ((second_point.x-first_point.x) * (third_point.y-first_point.y)); + Point third_point) { + return ((third_point.x - first_point.x) * + (second_point.y - first_point.y)) - + ((second_point.x - first_point.x) * + (third_point.y - first_point.y)); } - /** - * This method determines whether a point known to be colinear - * with a segment lies on that segment. - */ + /** + * This method determines whether a point known to be colinear + * with a segment lies on that segment. + */ inline bool on_segment(Point first_point, Point second_point, - Point third_point) { + Point third_point) { if (std::min(first_point.x, second_point.x) <= third_point.x && third_point.x <= std::max(first_point.x, second_point.x) && std::min(first_point.y, second_point.y) <= third_point.y && @@ -96,6 +98,6 @@ int main() { std::cin >> forth_point.x >> forth_point.y; printf("%d", segment.intersect(first_point, second_point, third_point, - forth_point)); + forth_point)); std::cout << std::endl; } From 6b759eb9524a2adc8ca731bdb91416c86b0a6aa2 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 31 May 2020 09:46:48 -0400 Subject: [PATCH 311/433] added cmake to geometry folder --- CMakeLists.txt | 1 + geometry/CMakeLists.txt | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) create mode 100644 geometry/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index 5030f3bb1bf..46a03364962 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -58,6 +58,7 @@ add_subdirectory(others) add_subdirectory(search) add_subdirectory(strings) add_subdirectory(sorting) +add_subdirectory(geometry) add_subdirectory(probability) add_subdirectory(machine_learning) add_subdirectory(computer_oriented_statistical_methods) diff --git a/geometry/CMakeLists.txt b/geometry/CMakeLists.txt new file mode 100644 index 00000000000..72655169aab --- /dev/null +++ b/geometry/CMakeLists.txt @@ -0,0 +1,18 @@ +# If necessary, use the RELATIVE flag, otherwise each source file may be listed +# with full pathname. RELATIVE may makes it easier to extract an executable name +# automatically. +file( GLOB APP_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp ) +# file( GLOB APP_SOURCES ${CMAKE_SOURCE_DIR}/*.c ) +# AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR} APP_SOURCES) +foreach( testsourcefile ${APP_SOURCES} ) + # I used a simple string replace, to cut off .cpp. + string( REPLACE ".cpp" "" testname ${testsourcefile} ) + add_executable( ${testname} ${testsourcefile} ) + + set_target_properties(${testname} PROPERTIES LINKER_LANGUAGE CXX) + if(OpenMP_CXX_FOUND) + target_link_libraries(${testname} OpenMP::OpenMP_CXX) + endif() + install(TARGETS ${testname} DESTINATION "bin/geometry") + +endforeach( testsourcefile ${APP_SOURCES} ) From e9e5588fe77462df4998c61f9cf87244abd0302d Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 31 May 2020 09:48:57 -0400 Subject: [PATCH 312/433] added algorithm include for std::max --- geometry/line_segment_intersection.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/geometry/line_segment_intersection.cpp b/geometry/line_segment_intersection.cpp index f386c5623d6..d523ae0a413 100644 --- a/geometry/line_segment_intersection.cpp +++ b/geometry/line_segment_intersection.cpp @@ -3,6 +3,7 @@ * @brief check whether two line segments intersect each other * or not. */ +#include #include /** From 579620271f30a68d2f74e36dd3cb36daa06b99a7 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 31 May 2020 23:00:38 -0400 Subject: [PATCH 313/433] add namespace - machine_learning --- machine_learning/adaline_learning.cpp | 269 +++++++++++++------------- 1 file changed, 139 insertions(+), 130 deletions(-) diff --git a/machine_learning/adaline_learning.cpp b/machine_learning/adaline_learning.cpp index 055c3b776e2..de5378c19ce 100644 --- a/machine_learning/adaline_learning.cpp +++ b/machine_learning/adaline_learning.cpp @@ -31,155 +31,164 @@ #define MAX_ITER 500 // INT_MAX ///< Maximum number of iterations to learn -class adaline { - public: - /** - * Default constructor - * \param[in] num_features number of features present - * \param[in] eta learning rate (optional, default=0.1) - * \param[in] convergence accuracy (optional, default=\f$1\times10^{-5}\f$) - */ - adaline(int num_features, const double eta = 0.01f, - const double accuracy = 1e-5) - : eta(eta), accuracy(accuracy) { - if (eta <= 0) { - std::cerr << "learning rate should be positive and nonzero" - << std::endl; - std::exit(EXIT_FAILURE); - } - - weights = std::vector( - num_features + - 1); // additional weight is for the constant bias term +/** \namespace machine_learning + * \brief Machine learning algorithms + */ +namespace machine_learning { + class adaline { + public: + /** + * Default constructor + * \param[in] num_features number of features present + * \param[in] eta learning rate (optional, default=0.1) + * \param[in] convergence accuracy (optional, + * default=\f$1\times10^{-5}\f$) + */ + adaline(int num_features, const double eta = 0.01f, + const double accuracy = 1e-5) + : eta(eta), accuracy(accuracy) { + if (eta <= 0) { + std::cerr << "learning rate should be positive and nonzero" + << std::endl; + std::exit(EXIT_FAILURE); + } - // initialize with random weights in the range [-50, 49] - for (int i = 0; i < weights.size(); i++) weights[i] = 1.f; - // weights[i] = (static_cast(std::rand() % 100) - 50); - } + weights = std::vector( + num_features + + 1); // additional weight is for the constant bias term - /** - * Operator to print the weights of the model - */ - friend std::ostream &operator<<(std::ostream &out, const adaline &ada) { - out << "<"; - for (int i = 0; i < ada.weights.size(); i++) { - out << ada.weights[i]; - if (i < ada.weights.size() - 1) - out << ", "; + // initialize with random weights in the range [-50, 49] + for (int i = 0; i < weights.size(); i++) weights[i] = 1.f; + // weights[i] = (static_cast(std::rand() % 100) - 50); } - out << ">"; - return out; - } - /** - * predict the output of the model for given set of features - * \param[in] x input vector - * \param[out] out optional argument to return neuron output before applying - * activation function (optional, `nullptr` to ignore) - * \returns model prediction output - */ - int predict(const std::vector &x, double *out = nullptr) { - if (!check_size_match(x)) - return 0; + /** + * Operator to print the weights of the model + */ + friend std::ostream &operator<<(std::ostream &out, const adaline &ada) { + out << "<"; + for (int i = 0; i < ada.weights.size(); i++) { + out << ada.weights[i]; + if (i < ada.weights.size() - 1) + out << ", "; + } + out << ">"; + return out; + } - double y = weights.back(); // assign bias value + /** + * predict the output of the model for given set of features + * \param[in] x input vector + * \param[out] out optional argument to return neuron output before + * applying activation function (optional, `nullptr` to ignore) \returns + * model prediction output + */ + int predict(const std::vector &x, double *out = nullptr) { + if (!check_size_match(x)) + return 0; - // for (int i = 0; i < x.size(); i++) y += x[i] * weights[i]; - y = std::inner_product(x.begin(), x.end(), weights.begin(), y); + double y = weights.back(); // assign bias value - if (out != nullptr) // if out variable is provided - *out = y; + // for (int i = 0; i < x.size(); i++) y += x[i] * weights[i]; + y = std::inner_product(x.begin(), x.end(), weights.begin(), y); - return activation(y); // quantizer: apply ADALINE threshold function - } + if (out != nullptr) // if out variable is provided + *out = y; - /** - * Update the weights of the model using supervised learning for one feature - * vector - * \param[in] x feature vector - * \param[in] y known output value - * \returns correction factor - */ - double fit(const std::vector &x, const int &y) { - if (!check_size_match(x)) - return 0; - - /* output of the model with current weights */ - int p = predict(x); - int prediction_error = y - p; // error in estimation - double correction_factor = eta * prediction_error; - - /* update each weight, the last weight is the bias term */ - for (int i = 0; i < x.size(); i++) { - weights[i] += correction_factor * x[i]; + return activation( + y); // quantizer: apply ADALINE threshold function } - weights[x.size()] += correction_factor; // update bias - return correction_factor; - } - - /** - * Update the weights of the model using supervised learning for an array of - * vectors. - * \param[in] X array of feature vector - * \param[in] y known output value for each feature vector - */ - template - void fit(std::vector const (&X)[N], const int *y) { - double avg_pred_error = 1.f; - - int iter; - for (iter = 0; (iter < MAX_ITER) && (avg_pred_error > accuracy); - iter++) { - avg_pred_error = 0.f; - - // perform fit for each sample - for (int i = 0; i < N; i++) { - double err = fit(X[i], y[i]); - avg_pred_error += std::abs(err); + /** + * Update the weights of the model using supervised learning for one + * feature vector \param[in] x feature vector \param[in] y known output + * value \returns correction factor + */ + double fit(const std::vector &x, const int &y) { + if (!check_size_match(x)) + return 0; + + /* output of the model with current weights */ + int p = predict(x); + int prediction_error = y - p; // error in estimation + double correction_factor = eta * prediction_error; + + /* update each weight, the last weight is the bias term */ + for (int i = 0; i < x.size(); i++) { + weights[i] += correction_factor * x[i]; } - avg_pred_error /= N; + weights[x.size()] += correction_factor; // update bias - // Print updates every 200th iteration - // if (iter % 100 == 0) - std::cout << "\tIter " << iter << ": Training weights: " << *this - << "\tAvg error: " << avg_pred_error << std::endl; + return correction_factor; } - if (iter < MAX_ITER) + /** + * Update the weights of the model using supervised learning for an + * array of vectors. \param[in] X array of feature vector \param[in] y + * known output value for each feature vector + */ + template + void fit(std::vector const (&X)[N], const int *y) { + double avg_pred_error = 1.f; + + int iter; + for (iter = 0; (iter < MAX_ITER) && (avg_pred_error > accuracy); + iter++) { + avg_pred_error = 0.f; + + // perform fit for each sample + for (int i = 0; i < N; i++) { + double err = fit(X[i], y[i]); + avg_pred_error += std::abs(err); + } + avg_pred_error /= N; + + // Print updates every 200th iteration + // if (iter % 100 == 0) + std::cout << "\tIter " << iter + << ": Training weights: " << *this + << "\tAvg error: " << avg_pred_error << std::endl; + } - std::cout << "Converged after " << iter << " iterations." - << std::endl; - else - std::cout << "Did not converge after " << iter << " iterations." - << std::endl; - } + if (iter < MAX_ITER) - int activation(double x) { return x > 0 ? 1 : -1; } - - private: - /** - * convenient function to check if input feature vector size matches the - * model weights size - * \param[in] x fecture vector to check - * \returns `true` size matches - * \returns `false` size does not match - */ - bool check_size_match(const std::vector &x) { - if (x.size() != (weights.size() - 1)) { - std::cerr << __func__ << ": " - << "Number of features in x does not match the feature " - "dimension in model!" - << std::endl; - return false; + std::cout << "Converged after " << iter << " iterations." + << std::endl; + else + std::cout << "Did not converge after " << iter << " iterations." + << std::endl; } - return true; - } - const double eta; ///< learning rate of the algorithm - const double accuracy; ///< model fit convergence accuracy - std::vector weights; ///< weights of the neural network -}; + int activation(double x) { return x > 0 ? 1 : -1; } + + private: + /** + * convenient function to check if input feature vector size matches the + * model weights size + * \param[in] x fecture vector to check + * \returns `true` size matches + * \returns `false` size does not match + */ + bool check_size_match(const std::vector &x) { + if (x.size() != (weights.size() - 1)) { + std::cerr + << __func__ << ": " + << "Number of features in x does not match the feature " + "dimension in model!" + << std::endl; + return false; + } + return true; + } + + const double eta; ///< learning rate of the algorithm + const double accuracy; ///< model fit convergence accuracy + std::vector weights; ///< weights of the neural network + }; + +} // namespace machine_learning + +using machine_learning::adaline; /** * test function to predict points in a 2D coordinate system above the line From 1125c85b3f5bfcb371f87a690aab277ade4a6998 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 31 May 2020 23:00:49 -0400 Subject: [PATCH 314/433] add namespace - statistics --- math/realtime_stats.cpp | 179 +++++++++++++++++++++------------------- 1 file changed, 95 insertions(+), 84 deletions(-) diff --git a/math/realtime_stats.cpp b/math/realtime_stats.cpp index 2fbfc9bd58e..03c8163318d 100644 --- a/math/realtime_stats.cpp +++ b/math/realtime_stats.cpp @@ -11,94 +11,105 @@ #include /** - * continuous mean and variance computance using - * first value as an approximation for the mean. - * If the first number is much far form the mean, the algorithm becomes very - * inaccurate to compute variance and standard deviation. + * \namespace statistics + * \brief Statistical algorithms */ -template -class stats_computer1 { - public: - /** Constructor - * \param[in] x new data sample - */ - void new_val(T x) { - if (n == 0) - K = x; - n++; - T tmp = x - K; - Ex += tmp; - Ex2 += tmp * tmp; - } - - /** return sample mean computed till last sample */ - double mean() const { return K + Ex / n; } - - /** return data variance computed till last sample */ - double variance() const { return (Ex2 - (Ex * Ex) / n) / (n - 1); } - - /** return sample standard deviation computed till last sample */ - double std() const { return std::sqrt(this->variance()); } - - /** short-hand operator to read new sample from input stream - * \n e.g.: `std::cin >> stats1;` - */ - friend std::istream &operator>>(std::istream &input, - stats_computer1 &stat) { - T val; - input >> val; - stat.new_val(val); - return input; - } - - private: - unsigned int n = 0; - double Ex, Ex2; - T K; -}; +namespace statistics { -/** - * continuous mean and variance computance using - * Welford's algorithm (very accurate) - */ -template -class stats_computer2 { - public: - /** Constructor - * \param[in] x new data sample + /** + * continuous mean and variance computance using + * first value as an approximation for the mean. + * If the first number is much far form the mean, the algorithm becomes very + * inaccurate to compute variance and standard deviation. */ - void new_val(T x) { - n++; - double delta = x - mu; - mu += delta / n; - double delta2 = x - mu; - M += delta * delta2; - } - - /** return sample mean computed till last sample */ - double mean() const { return mu; } - - /** return data variance computed till last sample */ - double variance() const { return M / n; } - - /** return sample standard deviation computed till last sample */ - double std() const { return std::sqrt(this->variance()); } - - /** short-hand operator to read new sample from input stream - * \n e.g.: `std::cin >> stats1;` + template + class stats_computer1 { + public: + /** Constructor + * \param[in] x new data sample + */ + void new_val(T x) { + if (n == 0) + K = x; + n++; + T tmp = x - K; + Ex += tmp; + Ex2 += tmp * tmp; + } + + /** return sample mean computed till last sample */ + double mean() const { return K + Ex / n; } + + /** return data variance computed till last sample */ + double variance() const { return (Ex2 - (Ex * Ex) / n) / (n - 1); } + + /** return sample standard deviation computed till last sample */ + double std() const { return std::sqrt(this->variance()); } + + /** short-hand operator to read new sample from input stream + * \n e.g.: `std::cin >> stats1;` + */ + friend std::istream &operator>>(std::istream &input, + stats_computer1 &stat) { + T val; + input >> val; + stat.new_val(val); + return input; + } + + private: + unsigned int n = 0; + double Ex, Ex2; + T K; + }; + + /** + * continuous mean and variance computance using + * Welford's algorithm (very accurate) */ - friend std::istream &operator>>(std::istream &input, - stats_computer2 &stat) { - T val; - input >> val; - stat.new_val(val); - return input; - } - - private: - unsigned int n = 0; - double mu = 0, var = 0, M = 0; -}; + template + class stats_computer2 { + public: + /** Constructor + * \param[in] x new data sample + */ + void new_val(T x) { + n++; + double delta = x - mu; + mu += delta / n; + double delta2 = x - mu; + M += delta * delta2; + } + + /** return sample mean computed till last sample */ + double mean() const { return mu; } + + /** return data variance computed till last sample */ + double variance() const { return M / n; } + + /** return sample standard deviation computed till last sample */ + double std() const { return std::sqrt(this->variance()); } + + /** short-hand operator to read new sample from input stream + * \n e.g.: `std::cin >> stats1;` + */ + friend std::istream &operator>>(std::istream &input, + stats_computer2 &stat) { + T val; + input >> val; + stat.new_val(val); + return input; + } + + private: + unsigned int n = 0; + double mu = 0, var = 0, M = 0; + }; + +} // namespace statistics + +using statistics::stats_computer1; +using statistics::stats_computer2; /** Test the algorithm implementation * \param[in] test_data array of data to test the algorithms From c2c4681554ee38484a28d34f27bc6e0df7971035 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 31 May 2020 23:00:59 -0400 Subject: [PATCH 315/433] add namespace - sorting --- sorting/shell_sort2.cpp | 74 ++++++++++++++++++++++++++--------------- 1 file changed, 47 insertions(+), 27 deletions(-) diff --git a/sorting/shell_sort2.cpp b/sorting/shell_sort2.cpp index 59f204818b1..c8af7e1de3f 100644 --- a/sorting/shell_sort2.cpp +++ b/sorting/shell_sort2.cpp @@ -1,11 +1,17 @@ +/** + * \file + * \brief [Shell sort](https://en.wikipedia.org/wiki/Shell_sort) algorithm + */ #include #include #include #include +#include // for std::swap -// for std::swap -#include - +/** pretty print array + * \param[in] arr array to print + * \param[in] LEN length of array to print + */ template void show_data(T *arr, size_t LEN) { size_t i; @@ -14,38 +20,52 @@ void show_data(T *arr, size_t LEN) { std::cout << std::endl; } +/** pretty print array + * \param[in] arr array to print + * \param[in] N length of array to print + */ template void show_data(T (&arr)[N]) { show_data(arr, N); } -/** - * Optimized algorithm - takes half the time by utilizing - * Mar - **/ -template -void shell_sort(T *arr, size_t LEN) { - const unsigned int gaps[] = {701, 301, 132, 57, 23, 10, 4, 1}; - const unsigned int gap_len = 8; - size_t i, j, g; - - for (g = 0; g < gap_len; g++) { - unsigned int gap = gaps[g]; - for (i = gap; i < LEN; i++) { - T tmp = arr[i]; - - for (j = i; j >= gap && (arr[j - gap] - tmp) > 0; j -= gap) - arr[j] = arr[j - gap]; - - arr[j] = tmp; +/** \namespace sorting + * \brief Sorting algorithms + */ +namespace sorting { + /** + * Optimized algorithm - takes half the time by utilizing + * Mar + **/ + template + void shell_sort(T *arr, size_t LEN) { + const unsigned int gaps[] = {701, 301, 132, 57, 23, 10, 4, 1}; + const unsigned int gap_len = 8; + size_t i, j, g; + + for (g = 0; g < gap_len; g++) { + unsigned int gap = gaps[g]; + for (i = gap; i < LEN; i++) { + T tmp = arr[i]; + + for (j = i; j >= gap && (arr[j - gap] - tmp) > 0; j -= gap) + arr[j] = arr[j - gap]; + + arr[j] = tmp; + } } } -} -template -void shell_sort(T (&arr)[N]) { - shell_sort(arr, N); -} + /** function overload - when input array is of a known length array type + */ + template + void shell_sort(T (&arr)[N]) { + shell_sort(arr, N); + } + +} // namespace sorting + +using sorting::shell_sort; /** * function to compare sorting using cstdlib's qsort From 5a2615c54e021b3578536f596415c9cef4e6fdc3 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 31 May 2020 23:08:57 -0400 Subject: [PATCH 316/433] added sorting algos to namespace sorting --- sorting/non_recursive_merge_sort.cpp | 156 ++++++++++++++------------- sorting/quick_sort.cpp | 77 ++++++------- 2 files changed, 122 insertions(+), 111 deletions(-) diff --git a/sorting/non_recursive_merge_sort.cpp b/sorting/non_recursive_merge_sort.cpp index 9d4e95f2fdd..c8c245b7d4c 100644 --- a/sorting/non_recursive_merge_sort.cpp +++ b/sorting/non_recursive_merge_sort.cpp @@ -8,83 +8,89 @@ #include #include // for std::move & std::remove_reference_t -template -void merge(Iterator, Iterator, const Iterator, char[]); -/// bottom-up merge sort which sorts elements in a non-decreasing order -/** - * sorts elements non-recursively by breaking them into small segments, merging - * adjacent segments into larger sorted segments, then increasing the sizes of - * segments by factors of 2 and repeating the same process. - * best-case = worst-case = O(n log(n)) - * @param first points to the first element - * @param last points to 1-step past the last element - * @param n the number of elements - */ -template -void non_recursive_merge_sort(const Iterator first, const Iterator last, - const size_t n) { - // create a buffer large enough to store all elements - // dynamically allocated to comply with cpplint - char* buffer = new char[n * sizeof(*first)]; - // buffer size can be optimized to largest power of 2 less than n elements - // divide the container into equally-sized segments whose length start at 1 - // and keeps increasing by factors of 2 - for (size_t length(1); length < n; length <<= 1) { - // merge adjacent segments whose number is n / (length * 2) - Iterator left(first); - for (size_t counter(n / (length << 1)); counter; --counter) { - Iterator right(left + length), end(right + length); - merge(left, right, end, buffer); - left = end; +namespace sorting { + template + void merge(Iterator, Iterator, const Iterator, char[]); + /// bottom-up merge sort which sorts elements in a non-decreasing order + /** + * sorts elements non-recursively by breaking them into small segments, + * merging adjacent segments into larger sorted segments, then increasing + * the sizes of segments by factors of 2 and repeating the same process. + * best-case = worst-case = O(n log(n)) + * @param first points to the first element + * @param last points to 1-step past the last element + * @param n the number of elements + */ + template + void non_recursive_merge_sort(const Iterator first, const Iterator last, + const size_t n) { + // create a buffer large enough to store all elements + // dynamically allocated to comply with cpplint + char* buffer = new char[n * sizeof(*first)]; + // buffer size can be optimized to largest power of 2 less than n + // elements divide the container into equally-sized segments whose + // length start at 1 and keeps increasing by factors of 2 + for (size_t length(1); length < n; length <<= 1) { + // merge adjacent segments whose number is n / (length * 2) + Iterator left(first); + for (size_t counter(n / (length << 1)); counter; --counter) { + Iterator right(left + length), end(right + length); + merge(left, right, end, buffer); + left = end; + } + // if the number of remaining elements (n * 2 % length) is longer + // than a segment, merge the remaining elements + if ((n & ((length << 1) - 1)) > length) + merge(left, left + length, last, buffer); } - // if the number of remaining elements (n * 2 % length) is longer - // than a segment, merge the remaining elements - if ((n & ((length << 1) - 1)) > length) - merge(left, left + length, last, buffer); + delete[] buffer; } - delete[] buffer; -} -/// merges 2 sorted adjacent segments into a larger sorted segment -/** - * best-case = worst-case = O(n) - * @param l points to the left part - * @param r points to the right part, end of left part - * @param e points to end of right part - * @param b points at the buffer - */ -template -void merge(Iterator l, Iterator r, const Iterator e, char b[]) { - // create 2 pointers to point at the buffer - auto p(reinterpret_cast*>(b)), c(p); - // move the left part of the segment - for (Iterator t(l); r != t; ++t) *p++ = std::move(*t); - // while neither the buffer nor the right part has been exhausted - // move the smallest element of the two back to the container - while (e != r && c != p) *l++ = std::move(*r < *c ? *r++ : *c++); - // notice only one of the two following loops will be executed - // while the right part hasn't bee exhausted, move it back - while (e != r) *l++ = std::move(*r++); - // while the buffer hasn't bee exhausted, move it back - while (c != p) *l++ = std::move(*c++); -} -/// bottom-up merge sort which sorts elements in a non-decreasing order -/** - * @param first points to the first element - * @param n the number of elements - */ -template -void non_recursive_merge_sort(const Iterator first, const size_t n) { - non_recursive_merge_sort(first, first + n, n); -} -/// bottom-up merge sort which sorts elements in a non-decreasing order -/** - * @param first points to the first element - * @param last points to 1-step past the last element - */ -template -void non_recursive_merge_sort(const Iterator first, const Iterator last) { - non_recursive_merge_sort(first, last, last - first); -} + /// merges 2 sorted adjacent segments into a larger sorted segment + /** + * best-case = worst-case = O(n) + * @param l points to the left part + * @param r points to the right part, end of left part + * @param e points to end of right part + * @param b points at the buffer + */ + template + void merge(Iterator l, Iterator r, const Iterator e, char b[]) { + // create 2 pointers to point at the buffer + auto p(reinterpret_cast*>(b)), + c(p); + // move the left part of the segment + for (Iterator t(l); r != t; ++t) *p++ = std::move(*t); + // while neither the buffer nor the right part has been exhausted + // move the smallest element of the two back to the container + while (e != r && c != p) *l++ = std::move(*r < *c ? *r++ : *c++); + // notice only one of the two following loops will be executed + // while the right part hasn't bee exhausted, move it back + while (e != r) *l++ = std::move(*r++); + // while the buffer hasn't bee exhausted, move it back + while (c != p) *l++ = std::move(*c++); + } + /// bottom-up merge sort which sorts elements in a non-decreasing order + /** + * @param first points to the first element + * @param n the number of elements + */ + template + void non_recursive_merge_sort(const Iterator first, const size_t n) { + non_recursive_merge_sort(first, first + n, n); + } + /// bottom-up merge sort which sorts elements in a non-decreasing order + /** + * @param first points to the first element + * @param last points to 1-step past the last element + */ + template + void non_recursive_merge_sort(const Iterator first, const Iterator last) { + non_recursive_merge_sort(first, last, last - first); + } + +} // namespace sorting + +using sorting::non_recursive_merge_sort; int main(int argc, char** argv) { int size; diff --git a/sorting/quick_sort.cpp b/sorting/quick_sort.cpp index 1db6b014e07..78268cf7360 100644 --- a/sorting/quick_sort.cpp +++ b/sorting/quick_sort.cpp @@ -24,48 +24,53 @@ #include #include -/** - * This function takes last element as pivot, places - * the pivot element at its correct position in sorted - * array, and places all smaller (smaller than pivot) - * to left of pivot and all greater elements to right - * of pivot - * - */ +namespace sorting { + /** + * This function takes last element as pivot, places + * the pivot element at its correct position in sorted + * array, and places all smaller (smaller than pivot) + * to left of pivot and all greater elements to right + * of pivot + * + */ -int partition(int arr[], int low, int high) { - int pivot = arr[high]; // taking the last element as pivot - int i = (low - 1); // Index of smaller element + int partition(int arr[], int low, int high) { + int pivot = arr[high]; // taking the last element as pivot + int i = (low - 1); // Index of smaller element - for (int j = low; j < high; j++) { - // If current element is smaller than or - // equal to pivot - if (arr[j] <= pivot) { - i++; // increment index of smaller element - int temp = arr[i]; - arr[i] = arr[j]; - arr[j] = temp; + for (int j = low; j < high; j++) { + // If current element is smaller than or + // equal to pivot + if (arr[j] <= pivot) { + i++; // increment index of smaller element + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } } + int temp = arr[i + 1]; + arr[i + 1] = arr[high]; + arr[high] = temp; + return (i + 1); } - int temp = arr[i + 1]; - arr[i + 1] = arr[high]; - arr[high] = temp; - return (i + 1); -} -/** - * The main function that implements QuickSort - * arr[] --> Array to be sorted, - * low --> Starting index, - * high --> Ending index - */ -void quickSort(int arr[], int low, int high) { - if (low < high) { - int p = partition(arr, low, high); - quickSort(arr, low, p - 1); - quickSort(arr, p + 1, high); + /** + * The main function that implements QuickSort + * arr[] --> Array to be sorted, + * low --> Starting index, + * high --> Ending index + */ + void quickSort(int arr[], int low, int high) { + if (low < high) { + int p = partition(arr, low, high); + quickSort(arr, low, p - 1); + quickSort(arr, p + 1, high); + } } -} + +} // namespace sorting + +using sorting::quickSort; // prints the array after sorting void show(int arr[], int size) { From fd695305150777981dc2a1f256aa2be444e4f108 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 31 May 2020 23:09:10 -0400 Subject: [PATCH 317/433] added namespace string_search --- strings/brute_force_string_searching.cpp | 42 ++++--- strings/knuth_morris_pratt.cpp | 78 ++++++------ strings/rabin_karp.cpp | 146 ++++++++++++----------- 3 files changed, 140 insertions(+), 126 deletions(-) diff --git a/strings/brute_force_string_searching.cpp b/strings/brute_force_string_searching.cpp index 9a2b5327a35..fc2f543c0bd 100644 --- a/strings/brute_force_string_searching.cpp +++ b/strings/brute_force_string_searching.cpp @@ -10,28 +10,32 @@ #endif #include -/** - * Find a pattern in a string by comparing the pattern to every substring. - * @param text Any string that might contain the pattern. - * @param pattern String that we are searching for. - * @return Index where the pattern starts in the text - * @return -1 if the pattern was not found. - */ -int brute_force(const std::string &text, const std::string &pattern) { - size_t pat_l = pattern.length(); - size_t txt_l = text.length(); - int index = -1; - if (pat_l <= txt_l) { - for (size_t i = 0; i < txt_l - pat_l + 1; i++) { - std::string s = text.substr(i, pat_l); - if (s == pattern) { - index = i; - break; +namespace string_search { + /** + * Find a pattern in a string by comparing the pattern to every substring. + * @param text Any string that might contain the pattern. + * @param pattern String that we are searching for. + * @return Index where the pattern starts in the text + * @return -1 if the pattern was not found. + */ + int brute_force(const std::string &text, const std::string &pattern) { + size_t pat_l = pattern.length(); + size_t txt_l = text.length(); + int index = -1; + if (pat_l <= txt_l) { + for (size_t i = 0; i < txt_l - pat_l + 1; i++) { + std::string s = text.substr(i, pat_l); + if (s == pattern) { + index = i; + break; + } } } + return index; } - return index; -} +} // namespace string_search + +using string_search::brute_force; /** set of test cases */ const std::vector> test_set = { diff --git a/strings/knuth_morris_pratt.cpp b/strings/knuth_morris_pratt.cpp index b83cab96632..ee569cccc4b 100644 --- a/strings/knuth_morris_pratt.cpp +++ b/strings/knuth_morris_pratt.cpp @@ -20,50 +20,54 @@ #endif #include -/** - * Generate the partial match table aka failure function for a pattern to - * search. - * \param[in] pattern text for which to create the partial match table - * \returns the partial match table as a vector array - */ -std::vector getFailureArray(const std::string &pattern) { - int pattern_length = pattern.size(); - std::vector failure(pattern_length + 1); - failure[0] = -1; - int j = -1; +namespace string_search { + /** + * Generate the partial match table aka failure function for a pattern to + * search. + * \param[in] pattern text for which to create the partial match table + * \returns the partial match table as a vector array + */ + std::vector getFailureArray(const std::string &pattern) { + int pattern_length = pattern.size(); + std::vector failure(pattern_length + 1); + failure[0] = -1; + int j = -1; - for (int i = 0; i < pattern_length; i++) { - while (j != -1 && pattern[j] != pattern[i]) { - j = failure[j]; + for (int i = 0; i < pattern_length; i++) { + while (j != -1 && pattern[j] != pattern[i]) { + j = failure[j]; + } + j++; + failure[i + 1] = j; } - j++; - failure[i + 1] = j; + return failure; } - return failure; -} -/** - * KMP algorithm to find a pattern in a text - * \param[in] pattern string pattern to search - * \param[in] text text in which to search - * \returns `true` if pattern was found - * \returns `false` if pattern was not found - */ -bool kmp(const std::string &pattern, const std::string &text) { - int text_length = text.size(), pattern_length = pattern.size(); - std::vector failure = getFailureArray(pattern); + /** + * KMP algorithm to find a pattern in a text + * \param[in] pattern string pattern to search + * \param[in] text text in which to search + * \returns `true` if pattern was found + * \returns `false` if pattern was not found + */ + bool kmp(const std::string &pattern, const std::string &text) { + int text_length = text.size(), pattern_length = pattern.size(); + std::vector failure = getFailureArray(pattern); - int k = 0; - for (int j = 0; j < text_length; j++) { - while (k != -1 && pattern[k] != text[j]) { - k = failure[k]; + int k = 0; + for (int j = 0; j < text_length; j++) { + while (k != -1 && pattern[k] != text[j]) { + k = failure[k]; + } + k++; + if (k == pattern_length) + return true; } - k++; - if (k == pattern_length) - return true; + return false; } - return false; -} +} // namespace string_search + +using string_search::kmp; /** Main function */ int main() { diff --git a/strings/rabin_karp.cpp b/strings/rabin_karp.cpp index 018ff56324f..6d1f4e7de4b 100644 --- a/strings/rabin_karp.cpp +++ b/strings/rabin_karp.cpp @@ -15,86 +15,92 @@ #define PRIME 5 ///< Prime modulus for hash functions -/** - * convert a string to an intger - called as hashing function - * \param[in] s source of string to hash - * \param[in] n length of substring to hash - * \returns hash integer - */ -int64_t create_hash(const std::string& s, int n) { - int64_t result = 0; - for (int i = 0; i < n; ++i) { - result += (int64_t)(s[i] * (int64_t)pow(PRIME, i)); +namespace string_search { + /** + * convert a string to an intger - called as hashing function + * \param[in] s source of string to hash + * \param[in] n length of substring to hash + * \returns hash integer + */ + int64_t create_hash(const std::string& s, int n) { + int64_t result = 0; + for (int i = 0; i < n; ++i) { + result += (int64_t)(s[i] * (int64_t)pow(PRIME, i)); + } + return result; } - return result; -} - -/** - * re-hash a string using known existing hash - * \param[in] s source of string to hash - * \param[in] old_index previous index of string - * \param[in] new_index new index of string - * \param[in] old_hash previous hash of substring - * \param[in] patLength length of substring to hash - * \returns new hash integer - */ -int64_t recalculate_hash(const std::string& s, int old_index, int new_index, - int64_t old_hash, int patLength) { - int64_t new_hash = old_hash - s[old_index]; - new_hash /= PRIME; - new_hash += (int64_t)(s[new_index] * (int64_t)pow(PRIME, patLength - 1)); - return new_hash; -} -/** - * compare if two sub-strings are equal - * \param[in] str1 string pattern to search - * \param[in] str2 text in which to search - * \param[in] start1,end1 start and end indices for substring in str1 - * \param[in] start2,end2 start and end indices for substring in str2 - * \returns `true` if pattern was found - * \returns `false` if pattern was not found - * @note can this be replaced by std::string::compare? - */ -bool check_if_equal(const std::string& str1, const std::string& str2, - int start1, int end1, int start2, int end2) { - if (end1 - start1 != end2 - start2) { - return false; + /** + * re-hash a string using known existing hash + * \param[in] s source of string to hash + * \param[in] old_index previous index of string + * \param[in] new_index new index of string + * \param[in] old_hash previous hash of substring + * \param[in] patLength length of substring to hash + * \returns new hash integer + */ + int64_t recalculate_hash(const std::string& s, int old_index, int new_index, + int64_t old_hash, int patLength) { + int64_t new_hash = old_hash - s[old_index]; + new_hash /= PRIME; + new_hash += + (int64_t)(s[new_index] * (int64_t)pow(PRIME, patLength - 1)); + return new_hash; } - while (start1 <= end1 && start2 <= end2) { - if (str1[start1] != str2[start2]) { + + /** + * compare if two sub-strings are equal + * \param[in] str1 string pattern to search + * \param[in] str2 text in which to search + * \param[in] start1,end1 start and end indices for substring in str1 + * \param[in] start2,end2 start and end indices for substring in str2 + * \returns `true` if pattern was found + * \returns `false` if pattern was not found + * @note can this be replaced by std::string::compare? + */ + bool check_if_equal(const std::string& str1, const std::string& str2, + int start1, int end1, int start2, int end2) { + if (end1 - start1 != end2 - start2) { return false; } - start1++; - start2++; + while (start1 <= end1 && start2 <= end2) { + if (str1[start1] != str2[start2]) { + return false; + } + start1++; + start2++; + } + return true; } - return true; -} -/** - * Perform string pattern search using Rabin-Karp algorithm - * @param[in] str string to search in - * @param[in] pat pattern to search for - * @return index of first occurrence of pattern - * @return -1 if pattern not found - */ + /** + * Perform string pattern search using Rabin-Karp algorithm + * @param[in] str string to search in + * @param[in] pat pattern to search for + * @return index of first occurrence of pattern + * @return -1 if pattern not found + */ -int rabin_karp(const std::string& str, const std::string& pat) { - int64_t pat_hash = create_hash(pat, pat.size()); - int64_t str_hash = create_hash(str, pat.size()); - for (int i = 0; i <= str.size() - pat.size(); ++i) { - if (pat_hash == str_hash && - check_if_equal(str, pat, i, i + pat.size() - 1, 0, - pat.size() - 1)) { - return i; - } - if (i < str.size() - pat.size()) { - str_hash = - recalculate_hash(str, i, i + pat.size(), str_hash, pat.size()); + int rabin_karp(const std::string& str, const std::string& pat) { + int64_t pat_hash = create_hash(pat, pat.size()); + int64_t str_hash = create_hash(str, pat.size()); + for (int i = 0; i <= str.size() - pat.size(); ++i) { + if (pat_hash == str_hash && + check_if_equal(str, pat, i, i + pat.size() - 1, 0, + pat.size() - 1)) { + return i; + } + if (i < str.size() - pat.size()) { + str_hash = recalculate_hash(str, i, i + pat.size(), str_hash, + pat.size()); + } } + return -1; // return -1 if given pattern not found } - return -1; // return -1 if given pattern not found -} + +} // namespace string_search + +using string_search::rabin_karp; /** Main function */ int main(void) { From 4fe430d75fe7711223b7fb82d6fb6a0d60341678 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 1 Jun 2020 03:10:34 +0000 Subject: [PATCH 318/433] formatting source-code for fd695305150777981dc2a1f256aa2be444e4f108 --- machine_learning/adaline_learning.cpp | 259 +++++++++++------------ math/realtime_stats.cpp | 174 +++++++-------- sorting/non_recursive_merge_sort.cpp | 151 +++++++------ sorting/quick_sort.cpp | 72 +++---- sorting/shell_sort2.cpp | 52 ++--- strings/brute_force_string_searching.cpp | 38 ++-- strings/knuth_morris_pratt.cpp | 74 +++---- strings/rabin_karp.cpp | 141 ++++++------ 8 files changed, 478 insertions(+), 483 deletions(-) diff --git a/machine_learning/adaline_learning.cpp b/machine_learning/adaline_learning.cpp index de5378c19ce..077b9408e57 100644 --- a/machine_learning/adaline_learning.cpp +++ b/machine_learning/adaline_learning.cpp @@ -35,156 +35,153 @@ * \brief Machine learning algorithms */ namespace machine_learning { - class adaline { - public: - /** - * Default constructor - * \param[in] num_features number of features present - * \param[in] eta learning rate (optional, default=0.1) - * \param[in] convergence accuracy (optional, - * default=\f$1\times10^{-5}\f$) - */ - adaline(int num_features, const double eta = 0.01f, - const double accuracy = 1e-5) - : eta(eta), accuracy(accuracy) { - if (eta <= 0) { - std::cerr << "learning rate should be positive and nonzero" - << std::endl; - std::exit(EXIT_FAILURE); - } +class adaline { + public: + /** + * Default constructor + * \param[in] num_features number of features present + * \param[in] eta learning rate (optional, default=0.1) + * \param[in] convergence accuracy (optional, + * default=\f$1\times10^{-5}\f$) + */ + adaline(int num_features, const double eta = 0.01f, + const double accuracy = 1e-5) + : eta(eta), accuracy(accuracy) { + if (eta <= 0) { + std::cerr << "learning rate should be positive and nonzero" + << std::endl; + std::exit(EXIT_FAILURE); + } - weights = std::vector( - num_features + - 1); // additional weight is for the constant bias term + weights = std::vector( + num_features + + 1); // additional weight is for the constant bias term - // initialize with random weights in the range [-50, 49] - for (int i = 0; i < weights.size(); i++) weights[i] = 1.f; - // weights[i] = (static_cast(std::rand() % 100) - 50); - } + // initialize with random weights in the range [-50, 49] + for (int i = 0; i < weights.size(); i++) weights[i] = 1.f; + // weights[i] = (static_cast(std::rand() % 100) - 50); + } - /** - * Operator to print the weights of the model - */ - friend std::ostream &operator<<(std::ostream &out, const adaline &ada) { - out << "<"; - for (int i = 0; i < ada.weights.size(); i++) { - out << ada.weights[i]; - if (i < ada.weights.size() - 1) - out << ", "; - } - out << ">"; - return out; + /** + * Operator to print the weights of the model + */ + friend std::ostream &operator<<(std::ostream &out, const adaline &ada) { + out << "<"; + for (int i = 0; i < ada.weights.size(); i++) { + out << ada.weights[i]; + if (i < ada.weights.size() - 1) + out << ", "; } + out << ">"; + return out; + } - /** - * predict the output of the model for given set of features - * \param[in] x input vector - * \param[out] out optional argument to return neuron output before - * applying activation function (optional, `nullptr` to ignore) \returns - * model prediction output - */ - int predict(const std::vector &x, double *out = nullptr) { - if (!check_size_match(x)) - return 0; + /** + * predict the output of the model for given set of features + * \param[in] x input vector + * \param[out] out optional argument to return neuron output before + * applying activation function (optional, `nullptr` to ignore) \returns + * model prediction output + */ + int predict(const std::vector &x, double *out = nullptr) { + if (!check_size_match(x)) + return 0; - double y = weights.back(); // assign bias value + double y = weights.back(); // assign bias value - // for (int i = 0; i < x.size(); i++) y += x[i] * weights[i]; - y = std::inner_product(x.begin(), x.end(), weights.begin(), y); + // for (int i = 0; i < x.size(); i++) y += x[i] * weights[i]; + y = std::inner_product(x.begin(), x.end(), weights.begin(), y); - if (out != nullptr) // if out variable is provided - *out = y; + if (out != nullptr) // if out variable is provided + *out = y; + + return activation(y); // quantizer: apply ADALINE threshold function + } - return activation( - y); // quantizer: apply ADALINE threshold function + /** + * Update the weights of the model using supervised learning for one + * feature vector \param[in] x feature vector \param[in] y known output + * value \returns correction factor + */ + double fit(const std::vector &x, const int &y) { + if (!check_size_match(x)) + return 0; + + /* output of the model with current weights */ + int p = predict(x); + int prediction_error = y - p; // error in estimation + double correction_factor = eta * prediction_error; + + /* update each weight, the last weight is the bias term */ + for (int i = 0; i < x.size(); i++) { + weights[i] += correction_factor * x[i]; } + weights[x.size()] += correction_factor; // update bias - /** - * Update the weights of the model using supervised learning for one - * feature vector \param[in] x feature vector \param[in] y known output - * value \returns correction factor - */ - double fit(const std::vector &x, const int &y) { - if (!check_size_match(x)) - return 0; - - /* output of the model with current weights */ - int p = predict(x); - int prediction_error = y - p; // error in estimation - double correction_factor = eta * prediction_error; - - /* update each weight, the last weight is the bias term */ - for (int i = 0; i < x.size(); i++) { - weights[i] += correction_factor * x[i]; + return correction_factor; + } + + /** + * Update the weights of the model using supervised learning for an + * array of vectors. \param[in] X array of feature vector \param[in] y + * known output value for each feature vector + */ + template + void fit(std::vector const (&X)[N], const int *y) { + double avg_pred_error = 1.f; + + int iter; + for (iter = 0; (iter < MAX_ITER) && (avg_pred_error > accuracy); + iter++) { + avg_pred_error = 0.f; + + // perform fit for each sample + for (int i = 0; i < N; i++) { + double err = fit(X[i], y[i]); + avg_pred_error += std::abs(err); } - weights[x.size()] += correction_factor; // update bias + avg_pred_error /= N; - return correction_factor; + // Print updates every 200th iteration + // if (iter % 100 == 0) + std::cout << "\tIter " << iter << ": Training weights: " << *this + << "\tAvg error: " << avg_pred_error << std::endl; } - /** - * Update the weights of the model using supervised learning for an - * array of vectors. \param[in] X array of feature vector \param[in] y - * known output value for each feature vector - */ - template - void fit(std::vector const (&X)[N], const int *y) { - double avg_pred_error = 1.f; - - int iter; - for (iter = 0; (iter < MAX_ITER) && (avg_pred_error > accuracy); - iter++) { - avg_pred_error = 0.f; - - // perform fit for each sample - for (int i = 0; i < N; i++) { - double err = fit(X[i], y[i]); - avg_pred_error += std::abs(err); - } - avg_pred_error /= N; - - // Print updates every 200th iteration - // if (iter % 100 == 0) - std::cout << "\tIter " << iter - << ": Training weights: " << *this - << "\tAvg error: " << avg_pred_error << std::endl; - } - - if (iter < MAX_ITER) + if (iter < MAX_ITER) - std::cout << "Converged after " << iter << " iterations." - << std::endl; - else - std::cout << "Did not converge after " << iter << " iterations." - << std::endl; - } + std::cout << "Converged after " << iter << " iterations." + << std::endl; + else + std::cout << "Did not converge after " << iter << " iterations." + << std::endl; + } - int activation(double x) { return x > 0 ? 1 : -1; } - - private: - /** - * convenient function to check if input feature vector size matches the - * model weights size - * \param[in] x fecture vector to check - * \returns `true` size matches - * \returns `false` size does not match - */ - bool check_size_match(const std::vector &x) { - if (x.size() != (weights.size() - 1)) { - std::cerr - << __func__ << ": " - << "Number of features in x does not match the feature " - "dimension in model!" - << std::endl; - return false; - } - return true; + int activation(double x) { return x > 0 ? 1 : -1; } + + private: + /** + * convenient function to check if input feature vector size matches the + * model weights size + * \param[in] x fecture vector to check + * \returns `true` size matches + * \returns `false` size does not match + */ + bool check_size_match(const std::vector &x) { + if (x.size() != (weights.size() - 1)) { + std::cerr << __func__ << ": " + << "Number of features in x does not match the feature " + "dimension in model!" + << std::endl; + return false; } + return true; + } - const double eta; ///< learning rate of the algorithm - const double accuracy; ///< model fit convergence accuracy - std::vector weights; ///< weights of the neural network - }; + const double eta; ///< learning rate of the algorithm + const double accuracy; ///< model fit convergence accuracy + std::vector weights; ///< weights of the neural network +}; } // namespace machine_learning diff --git a/math/realtime_stats.cpp b/math/realtime_stats.cpp index 03c8163318d..26b92362513 100644 --- a/math/realtime_stats.cpp +++ b/math/realtime_stats.cpp @@ -16,95 +16,95 @@ */ namespace statistics { - /** - * continuous mean and variance computance using - * first value as an approximation for the mean. - * If the first number is much far form the mean, the algorithm becomes very - * inaccurate to compute variance and standard deviation. +/** + * continuous mean and variance computance using + * first value as an approximation for the mean. + * If the first number is much far form the mean, the algorithm becomes very + * inaccurate to compute variance and standard deviation. + */ +template +class stats_computer1 { + public: + /** Constructor + * \param[in] x new data sample */ - template - class stats_computer1 { - public: - /** Constructor - * \param[in] x new data sample - */ - void new_val(T x) { - if (n == 0) - K = x; - n++; - T tmp = x - K; - Ex += tmp; - Ex2 += tmp * tmp; - } - - /** return sample mean computed till last sample */ - double mean() const { return K + Ex / n; } - - /** return data variance computed till last sample */ - double variance() const { return (Ex2 - (Ex * Ex) / n) / (n - 1); } - - /** return sample standard deviation computed till last sample */ - double std() const { return std::sqrt(this->variance()); } - - /** short-hand operator to read new sample from input stream - * \n e.g.: `std::cin >> stats1;` - */ - friend std::istream &operator>>(std::istream &input, - stats_computer1 &stat) { - T val; - input >> val; - stat.new_val(val); - return input; - } - - private: - unsigned int n = 0; - double Ex, Ex2; - T K; - }; - - /** - * continuous mean and variance computance using - * Welford's algorithm (very accurate) + void new_val(T x) { + if (n == 0) + K = x; + n++; + T tmp = x - K; + Ex += tmp; + Ex2 += tmp * tmp; + } + + /** return sample mean computed till last sample */ + double mean() const { return K + Ex / n; } + + /** return data variance computed till last sample */ + double variance() const { return (Ex2 - (Ex * Ex) / n) / (n - 1); } + + /** return sample standard deviation computed till last sample */ + double std() const { return std::sqrt(this->variance()); } + + /** short-hand operator to read new sample from input stream + * \n e.g.: `std::cin >> stats1;` */ - template - class stats_computer2 { - public: - /** Constructor - * \param[in] x new data sample - */ - void new_val(T x) { - n++; - double delta = x - mu; - mu += delta / n; - double delta2 = x - mu; - M += delta * delta2; - } - - /** return sample mean computed till last sample */ - double mean() const { return mu; } - - /** return data variance computed till last sample */ - double variance() const { return M / n; } - - /** return sample standard deviation computed till last sample */ - double std() const { return std::sqrt(this->variance()); } - - /** short-hand operator to read new sample from input stream - * \n e.g.: `std::cin >> stats1;` - */ - friend std::istream &operator>>(std::istream &input, - stats_computer2 &stat) { - T val; - input >> val; - stat.new_val(val); - return input; - } - - private: - unsigned int n = 0; - double mu = 0, var = 0, M = 0; - }; + friend std::istream &operator>>(std::istream &input, + stats_computer1 &stat) { + T val; + input >> val; + stat.new_val(val); + return input; + } + + private: + unsigned int n = 0; + double Ex, Ex2; + T K; +}; + +/** + * continuous mean and variance computance using + * Welford's algorithm (very accurate) + */ +template +class stats_computer2 { + public: + /** Constructor + * \param[in] x new data sample + */ + void new_val(T x) { + n++; + double delta = x - mu; + mu += delta / n; + double delta2 = x - mu; + M += delta * delta2; + } + + /** return sample mean computed till last sample */ + double mean() const { return mu; } + + /** return data variance computed till last sample */ + double variance() const { return M / n; } + + /** return sample standard deviation computed till last sample */ + double std() const { return std::sqrt(this->variance()); } + + /** short-hand operator to read new sample from input stream + * \n e.g.: `std::cin >> stats1;` + */ + friend std::istream &operator>>(std::istream &input, + stats_computer2 &stat) { + T val; + input >> val; + stat.new_val(val); + return input; + } + + private: + unsigned int n = 0; + double mu = 0, var = 0, M = 0; +}; } // namespace statistics diff --git a/sorting/non_recursive_merge_sort.cpp b/sorting/non_recursive_merge_sort.cpp index c8c245b7d4c..b99b931080b 100644 --- a/sorting/non_recursive_merge_sort.cpp +++ b/sorting/non_recursive_merge_sort.cpp @@ -9,84 +9,83 @@ #include // for std::move & std::remove_reference_t namespace sorting { - template - void merge(Iterator, Iterator, const Iterator, char[]); - /// bottom-up merge sort which sorts elements in a non-decreasing order - /** - * sorts elements non-recursively by breaking them into small segments, - * merging adjacent segments into larger sorted segments, then increasing - * the sizes of segments by factors of 2 and repeating the same process. - * best-case = worst-case = O(n log(n)) - * @param first points to the first element - * @param last points to 1-step past the last element - * @param n the number of elements - */ - template - void non_recursive_merge_sort(const Iterator first, const Iterator last, - const size_t n) { - // create a buffer large enough to store all elements - // dynamically allocated to comply with cpplint - char* buffer = new char[n * sizeof(*first)]; - // buffer size can be optimized to largest power of 2 less than n - // elements divide the container into equally-sized segments whose - // length start at 1 and keeps increasing by factors of 2 - for (size_t length(1); length < n; length <<= 1) { - // merge adjacent segments whose number is n / (length * 2) - Iterator left(first); - for (size_t counter(n / (length << 1)); counter; --counter) { - Iterator right(left + length), end(right + length); - merge(left, right, end, buffer); - left = end; - } - // if the number of remaining elements (n * 2 % length) is longer - // than a segment, merge the remaining elements - if ((n & ((length << 1) - 1)) > length) - merge(left, left + length, last, buffer); +template +void merge(Iterator, Iterator, const Iterator, char[]); +/// bottom-up merge sort which sorts elements in a non-decreasing order +/** + * sorts elements non-recursively by breaking them into small segments, + * merging adjacent segments into larger sorted segments, then increasing + * the sizes of segments by factors of 2 and repeating the same process. + * best-case = worst-case = O(n log(n)) + * @param first points to the first element + * @param last points to 1-step past the last element + * @param n the number of elements + */ +template +void non_recursive_merge_sort(const Iterator first, const Iterator last, + const size_t n) { + // create a buffer large enough to store all elements + // dynamically allocated to comply with cpplint + char* buffer = new char[n * sizeof(*first)]; + // buffer size can be optimized to largest power of 2 less than n + // elements divide the container into equally-sized segments whose + // length start at 1 and keeps increasing by factors of 2 + for (size_t length(1); length < n; length <<= 1) { + // merge adjacent segments whose number is n / (length * 2) + Iterator left(first); + for (size_t counter(n / (length << 1)); counter; --counter) { + Iterator right(left + length), end(right + length); + merge(left, right, end, buffer); + left = end; } - delete[] buffer; - } - /// merges 2 sorted adjacent segments into a larger sorted segment - /** - * best-case = worst-case = O(n) - * @param l points to the left part - * @param r points to the right part, end of left part - * @param e points to end of right part - * @param b points at the buffer - */ - template - void merge(Iterator l, Iterator r, const Iterator e, char b[]) { - // create 2 pointers to point at the buffer - auto p(reinterpret_cast*>(b)), - c(p); - // move the left part of the segment - for (Iterator t(l); r != t; ++t) *p++ = std::move(*t); - // while neither the buffer nor the right part has been exhausted - // move the smallest element of the two back to the container - while (e != r && c != p) *l++ = std::move(*r < *c ? *r++ : *c++); - // notice only one of the two following loops will be executed - // while the right part hasn't bee exhausted, move it back - while (e != r) *l++ = std::move(*r++); - // while the buffer hasn't bee exhausted, move it back - while (c != p) *l++ = std::move(*c++); - } - /// bottom-up merge sort which sorts elements in a non-decreasing order - /** - * @param first points to the first element - * @param n the number of elements - */ - template - void non_recursive_merge_sort(const Iterator first, const size_t n) { - non_recursive_merge_sort(first, first + n, n); - } - /// bottom-up merge sort which sorts elements in a non-decreasing order - /** - * @param first points to the first element - * @param last points to 1-step past the last element - */ - template - void non_recursive_merge_sort(const Iterator first, const Iterator last) { - non_recursive_merge_sort(first, last, last - first); + // if the number of remaining elements (n * 2 % length) is longer + // than a segment, merge the remaining elements + if ((n & ((length << 1) - 1)) > length) + merge(left, left + length, last, buffer); } + delete[] buffer; +} +/// merges 2 sorted adjacent segments into a larger sorted segment +/** + * best-case = worst-case = O(n) + * @param l points to the left part + * @param r points to the right part, end of left part + * @param e points to end of right part + * @param b points at the buffer + */ +template +void merge(Iterator l, Iterator r, const Iterator e, char b[]) { + // create 2 pointers to point at the buffer + auto p(reinterpret_cast*>(b)), c(p); + // move the left part of the segment + for (Iterator t(l); r != t; ++t) *p++ = std::move(*t); + // while neither the buffer nor the right part has been exhausted + // move the smallest element of the two back to the container + while (e != r && c != p) *l++ = std::move(*r < *c ? *r++ : *c++); + // notice only one of the two following loops will be executed + // while the right part hasn't bee exhausted, move it back + while (e != r) *l++ = std::move(*r++); + // while the buffer hasn't bee exhausted, move it back + while (c != p) *l++ = std::move(*c++); +} +/// bottom-up merge sort which sorts elements in a non-decreasing order +/** + * @param first points to the first element + * @param n the number of elements + */ +template +void non_recursive_merge_sort(const Iterator first, const size_t n) { + non_recursive_merge_sort(first, first + n, n); +} +/// bottom-up merge sort which sorts elements in a non-decreasing order +/** + * @param first points to the first element + * @param last points to 1-step past the last element + */ +template +void non_recursive_merge_sort(const Iterator first, const Iterator last) { + non_recursive_merge_sort(first, last, last - first); +} } // namespace sorting diff --git a/sorting/quick_sort.cpp b/sorting/quick_sort.cpp index 78268cf7360..5d102dc8842 100644 --- a/sorting/quick_sort.cpp +++ b/sorting/quick_sort.cpp @@ -25,48 +25,48 @@ #include namespace sorting { - /** - * This function takes last element as pivot, places - * the pivot element at its correct position in sorted - * array, and places all smaller (smaller than pivot) - * to left of pivot and all greater elements to right - * of pivot - * - */ +/** + * This function takes last element as pivot, places + * the pivot element at its correct position in sorted + * array, and places all smaller (smaller than pivot) + * to left of pivot and all greater elements to right + * of pivot + * + */ - int partition(int arr[], int low, int high) { - int pivot = arr[high]; // taking the last element as pivot - int i = (low - 1); // Index of smaller element +int partition(int arr[], int low, int high) { + int pivot = arr[high]; // taking the last element as pivot + int i = (low - 1); // Index of smaller element - for (int j = low; j < high; j++) { - // If current element is smaller than or - // equal to pivot - if (arr[j] <= pivot) { - i++; // increment index of smaller element - int temp = arr[i]; - arr[i] = arr[j]; - arr[j] = temp; - } + for (int j = low; j < high; j++) { + // If current element is smaller than or + // equal to pivot + if (arr[j] <= pivot) { + i++; // increment index of smaller element + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; } - int temp = arr[i + 1]; - arr[i + 1] = arr[high]; - arr[high] = temp; - return (i + 1); } + int temp = arr[i + 1]; + arr[i + 1] = arr[high]; + arr[high] = temp; + return (i + 1); +} - /** - * The main function that implements QuickSort - * arr[] --> Array to be sorted, - * low --> Starting index, - * high --> Ending index - */ - void quickSort(int arr[], int low, int high) { - if (low < high) { - int p = partition(arr, low, high); - quickSort(arr, low, p - 1); - quickSort(arr, p + 1, high); - } +/** + * The main function that implements QuickSort + * arr[] --> Array to be sorted, + * low --> Starting index, + * high --> Ending index + */ +void quickSort(int arr[], int low, int high) { + if (low < high) { + int p = partition(arr, low, high); + quickSort(arr, low, p - 1); + quickSort(arr, p + 1, high); } +} } // namespace sorting diff --git a/sorting/shell_sort2.cpp b/sorting/shell_sort2.cpp index c8af7e1de3f..85186e75228 100644 --- a/sorting/shell_sort2.cpp +++ b/sorting/shell_sort2.cpp @@ -33,35 +33,35 @@ void show_data(T (&arr)[N]) { * \brief Sorting algorithms */ namespace sorting { - /** - * Optimized algorithm - takes half the time by utilizing - * Mar - **/ - template - void shell_sort(T *arr, size_t LEN) { - const unsigned int gaps[] = {701, 301, 132, 57, 23, 10, 4, 1}; - const unsigned int gap_len = 8; - size_t i, j, g; - - for (g = 0; g < gap_len; g++) { - unsigned int gap = gaps[g]; - for (i = gap; i < LEN; i++) { - T tmp = arr[i]; - - for (j = i; j >= gap && (arr[j - gap] - tmp) > 0; j -= gap) - arr[j] = arr[j - gap]; - - arr[j] = tmp; - } +/** + * Optimized algorithm - takes half the time by utilizing + * Mar + **/ +template +void shell_sort(T *arr, size_t LEN) { + const unsigned int gaps[] = {701, 301, 132, 57, 23, 10, 4, 1}; + const unsigned int gap_len = 8; + size_t i, j, g; + + for (g = 0; g < gap_len; g++) { + unsigned int gap = gaps[g]; + for (i = gap; i < LEN; i++) { + T tmp = arr[i]; + + for (j = i; j >= gap && (arr[j - gap] - tmp) > 0; j -= gap) + arr[j] = arr[j - gap]; + + arr[j] = tmp; } } +} - /** function overload - when input array is of a known length array type - */ - template - void shell_sort(T (&arr)[N]) { - shell_sort(arr, N); - } +/** function overload - when input array is of a known length array type + */ +template +void shell_sort(T (&arr)[N]) { + shell_sort(arr, N); +} } // namespace sorting diff --git a/strings/brute_force_string_searching.cpp b/strings/brute_force_string_searching.cpp index fc2f543c0bd..fd5244b3795 100644 --- a/strings/brute_force_string_searching.cpp +++ b/strings/brute_force_string_searching.cpp @@ -11,28 +11,28 @@ #include namespace string_search { - /** - * Find a pattern in a string by comparing the pattern to every substring. - * @param text Any string that might contain the pattern. - * @param pattern String that we are searching for. - * @return Index where the pattern starts in the text - * @return -1 if the pattern was not found. - */ - int brute_force(const std::string &text, const std::string &pattern) { - size_t pat_l = pattern.length(); - size_t txt_l = text.length(); - int index = -1; - if (pat_l <= txt_l) { - for (size_t i = 0; i < txt_l - pat_l + 1; i++) { - std::string s = text.substr(i, pat_l); - if (s == pattern) { - index = i; - break; - } +/** + * Find a pattern in a string by comparing the pattern to every substring. + * @param text Any string that might contain the pattern. + * @param pattern String that we are searching for. + * @return Index where the pattern starts in the text + * @return -1 if the pattern was not found. + */ +int brute_force(const std::string &text, const std::string &pattern) { + size_t pat_l = pattern.length(); + size_t txt_l = text.length(); + int index = -1; + if (pat_l <= txt_l) { + for (size_t i = 0; i < txt_l - pat_l + 1; i++) { + std::string s = text.substr(i, pat_l); + if (s == pattern) { + index = i; + break; } } - return index; } + return index; +} } // namespace string_search using string_search::brute_force; diff --git a/strings/knuth_morris_pratt.cpp b/strings/knuth_morris_pratt.cpp index ee569cccc4b..d116ddcff61 100644 --- a/strings/knuth_morris_pratt.cpp +++ b/strings/knuth_morris_pratt.cpp @@ -21,50 +21,50 @@ #include namespace string_search { - /** - * Generate the partial match table aka failure function for a pattern to - * search. - * \param[in] pattern text for which to create the partial match table - * \returns the partial match table as a vector array - */ - std::vector getFailureArray(const std::string &pattern) { - int pattern_length = pattern.size(); - std::vector failure(pattern_length + 1); - failure[0] = -1; - int j = -1; +/** + * Generate the partial match table aka failure function for a pattern to + * search. + * \param[in] pattern text for which to create the partial match table + * \returns the partial match table as a vector array + */ +std::vector getFailureArray(const std::string &pattern) { + int pattern_length = pattern.size(); + std::vector failure(pattern_length + 1); + failure[0] = -1; + int j = -1; - for (int i = 0; i < pattern_length; i++) { - while (j != -1 && pattern[j] != pattern[i]) { - j = failure[j]; - } - j++; - failure[i + 1] = j; + for (int i = 0; i < pattern_length; i++) { + while (j != -1 && pattern[j] != pattern[i]) { + j = failure[j]; } - return failure; + j++; + failure[i + 1] = j; } + return failure; +} - /** - * KMP algorithm to find a pattern in a text - * \param[in] pattern string pattern to search - * \param[in] text text in which to search - * \returns `true` if pattern was found - * \returns `false` if pattern was not found - */ - bool kmp(const std::string &pattern, const std::string &text) { - int text_length = text.size(), pattern_length = pattern.size(); - std::vector failure = getFailureArray(pattern); +/** + * KMP algorithm to find a pattern in a text + * \param[in] pattern string pattern to search + * \param[in] text text in which to search + * \returns `true` if pattern was found + * \returns `false` if pattern was not found + */ +bool kmp(const std::string &pattern, const std::string &text) { + int text_length = text.size(), pattern_length = pattern.size(); + std::vector failure = getFailureArray(pattern); - int k = 0; - for (int j = 0; j < text_length; j++) { - while (k != -1 && pattern[k] != text[j]) { - k = failure[k]; - } - k++; - if (k == pattern_length) - return true; + int k = 0; + for (int j = 0; j < text_length; j++) { + while (k != -1 && pattern[k] != text[j]) { + k = failure[k]; } - return false; + k++; + if (k == pattern_length) + return true; } + return false; +} } // namespace string_search using string_search::kmp; diff --git a/strings/rabin_karp.cpp b/strings/rabin_karp.cpp index 6d1f4e7de4b..91e104188cc 100644 --- a/strings/rabin_karp.cpp +++ b/strings/rabin_karp.cpp @@ -16,87 +16,86 @@ #define PRIME 5 ///< Prime modulus for hash functions namespace string_search { - /** - * convert a string to an intger - called as hashing function - * \param[in] s source of string to hash - * \param[in] n length of substring to hash - * \returns hash integer - */ - int64_t create_hash(const std::string& s, int n) { - int64_t result = 0; - for (int i = 0; i < n; ++i) { - result += (int64_t)(s[i] * (int64_t)pow(PRIME, i)); - } - return result; +/** + * convert a string to an intger - called as hashing function + * \param[in] s source of string to hash + * \param[in] n length of substring to hash + * \returns hash integer + */ +int64_t create_hash(const std::string& s, int n) { + int64_t result = 0; + for (int i = 0; i < n; ++i) { + result += (int64_t)(s[i] * (int64_t)pow(PRIME, i)); } + return result; +} - /** - * re-hash a string using known existing hash - * \param[in] s source of string to hash - * \param[in] old_index previous index of string - * \param[in] new_index new index of string - * \param[in] old_hash previous hash of substring - * \param[in] patLength length of substring to hash - * \returns new hash integer - */ - int64_t recalculate_hash(const std::string& s, int old_index, int new_index, - int64_t old_hash, int patLength) { - int64_t new_hash = old_hash - s[old_index]; - new_hash /= PRIME; - new_hash += - (int64_t)(s[new_index] * (int64_t)pow(PRIME, patLength - 1)); - return new_hash; - } +/** + * re-hash a string using known existing hash + * \param[in] s source of string to hash + * \param[in] old_index previous index of string + * \param[in] new_index new index of string + * \param[in] old_hash previous hash of substring + * \param[in] patLength length of substring to hash + * \returns new hash integer + */ +int64_t recalculate_hash(const std::string& s, int old_index, int new_index, + int64_t old_hash, int patLength) { + int64_t new_hash = old_hash - s[old_index]; + new_hash /= PRIME; + new_hash += (int64_t)(s[new_index] * (int64_t)pow(PRIME, patLength - 1)); + return new_hash; +} - /** - * compare if two sub-strings are equal - * \param[in] str1 string pattern to search - * \param[in] str2 text in which to search - * \param[in] start1,end1 start and end indices for substring in str1 - * \param[in] start2,end2 start and end indices for substring in str2 - * \returns `true` if pattern was found - * \returns `false` if pattern was not found - * @note can this be replaced by std::string::compare? - */ - bool check_if_equal(const std::string& str1, const std::string& str2, - int start1, int end1, int start2, int end2) { - if (end1 - start1 != end2 - start2) { +/** + * compare if two sub-strings are equal + * \param[in] str1 string pattern to search + * \param[in] str2 text in which to search + * \param[in] start1,end1 start and end indices for substring in str1 + * \param[in] start2,end2 start and end indices for substring in str2 + * \returns `true` if pattern was found + * \returns `false` if pattern was not found + * @note can this be replaced by std::string::compare? + */ +bool check_if_equal(const std::string& str1, const std::string& str2, + int start1, int end1, int start2, int end2) { + if (end1 - start1 != end2 - start2) { + return false; + } + while (start1 <= end1 && start2 <= end2) { + if (str1[start1] != str2[start2]) { return false; } - while (start1 <= end1 && start2 <= end2) { - if (str1[start1] != str2[start2]) { - return false; - } - start1++; - start2++; - } - return true; + start1++; + start2++; } + return true; +} - /** - * Perform string pattern search using Rabin-Karp algorithm - * @param[in] str string to search in - * @param[in] pat pattern to search for - * @return index of first occurrence of pattern - * @return -1 if pattern not found - */ +/** + * Perform string pattern search using Rabin-Karp algorithm + * @param[in] str string to search in + * @param[in] pat pattern to search for + * @return index of first occurrence of pattern + * @return -1 if pattern not found + */ - int rabin_karp(const std::string& str, const std::string& pat) { - int64_t pat_hash = create_hash(pat, pat.size()); - int64_t str_hash = create_hash(str, pat.size()); - for (int i = 0; i <= str.size() - pat.size(); ++i) { - if (pat_hash == str_hash && - check_if_equal(str, pat, i, i + pat.size() - 1, 0, - pat.size() - 1)) { - return i; - } - if (i < str.size() - pat.size()) { - str_hash = recalculate_hash(str, i, i + pat.size(), str_hash, - pat.size()); - } +int rabin_karp(const std::string& str, const std::string& pat) { + int64_t pat_hash = create_hash(pat, pat.size()); + int64_t str_hash = create_hash(str, pat.size()); + for (int i = 0; i <= str.size() - pat.size(); ++i) { + if (pat_hash == str_hash && + check_if_equal(str, pat, i, i + pat.size() - 1, 0, + pat.size() - 1)) { + return i; + } + if (i < str.size() - pat.size()) { + str_hash = + recalculate_hash(str, i, i + pat.size(), str_hash, pat.size()); } - return -1; // return -1 if given pattern not found } + return -1; // return -1 if given pattern not found +} } // namespace string_search From e7cd34e02f61324a11c65ad112d34b258fb5af12 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 31 May 2020 23:30:56 -0400 Subject: [PATCH 319/433] added documentation to string_search namespace --- strings/knuth_morris_pratt.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/strings/knuth_morris_pratt.cpp b/strings/knuth_morris_pratt.cpp index d116ddcff61..d53948d98d1 100644 --- a/strings/knuth_morris_pratt.cpp +++ b/strings/knuth_morris_pratt.cpp @@ -20,6 +20,9 @@ #endif #include +/** \namespace string_search + * \brief String search algorithms + */ namespace string_search { /** * Generate the partial match table aka failure function for a pattern to From 09af5e3c0e6ff6575ee747c89f480c7f85945546 Mon Sep 17 00:00:00 2001 From: Anmol3299 Date: Tue, 2 Jun 2020 21:36:31 +0530 Subject: [PATCH 320/433] feat: Add BFS and DFS algorithms to check for cycle in a directed graph --- graph/cycle_check_directed_graph.cpp | 322 +++++++++++++++++++++++++++ 1 file changed, 322 insertions(+) create mode 100644 graph/cycle_check_directed_graph.cpp diff --git a/graph/cycle_check_directed_graph.cpp b/graph/cycle_check_directed_graph.cpp new file mode 100644 index 00000000000..0cf5ac28ece --- /dev/null +++ b/graph/cycle_check_directed_graph.cpp @@ -0,0 +1,322 @@ +/** + * Copyright 2020 + * @file cycle_check_directed graph.cpp + * + * @brief BFS and DFS algorithms to check for cycle in a directed graph. + * + * @author Anmol3299 + * contact: mittalanmol22@gmail.com + * + */ + +#include // for std::cout +#include // for std::queue +#include // for throwing errors +#include // for std::remove_reference_t +#include // for std::unordered_map +#include // for std::move +#include // for std::vector + +/** + * Implementation of non-weighted directed edge of a graph. + * + * The source vertex of the edge is labelled "src" and destination vertex is + * labelled "dest". + */ +struct Edge { + unsigned int src; + unsigned int dest; + + Edge() = delete; + ~Edge() = default; + Edge(Edge&&) = default; + Edge& operator=(Edge&&) = default; + Edge(Edge const&) = default; + Edge& operator=(Edge const&) = default; + + /** Set the source and destination of the vertex. + * + * @param source is the source vertex of the edge. + * @param destination is the destination vertex of the edge. + */ + Edge(unsigned int const& source, unsigned int const& destination) + : src(source), dest(destination) {} +}; + +using AdjList = std::unordered_map>; + +/** + * Implementation of graph class. + * + * The graph will be represented using Adjacency List representation. + * This class contains 2 data members "m_vertices" & "m_adjList" used to + * represent the number of vertices and adjacency list of the graph + * respectively. The vertices are labelled 0 - (m_vertices - 1). + */ +class Graph { + public: + Graph() : m_vertices(0), m_adjList({}) {} + ~Graph() = default; + Graph(Graph&&) = default; + Graph& operator=(Graph&&) = default; + Graph(Graph const&) = default; + Graph& operator=(Graph const&) = default; + + /** Create a graph from vertices and adjacency list. + * + * @param vertices specify the number of vertices the graph would contain. + * @param adjList is the adjacency list representation of graph. + */ + Graph(unsigned int const& vertices, AdjList const& adjList) + : m_vertices(vertices), m_adjList(adjList) {} + + /** Create a graph from vertices and adjacency list. + * + * @param vertices specify the number of vertices the graph would contain. + * @param adjList is the adjacency list representation of graph. + */ + Graph(unsigned int const& vertices, AdjList&& adjList) + : m_vertices(std::move(vertices)), m_adjList(std::move(adjList)) {} + + /** Create a graph from vertices and a set of edges. + * + * Adjacency list of the graph would be created from the set of edges. If + * the source or destination of any edge has a value greater or equal to + * number of vertices, then it would throw a range_error. + * + * @param vertices specify the number of vertices the graph would contain. + * @param edges is a vector of edges. + */ + Graph(unsigned int const& vertices, std::vector const& edges) + : m_vertices(vertices) { + for (auto const& edge : edges) { + if (edge.src >= vertices || edge.dest >= vertices) { + throw std::range_error( + "Either src or dest of edge out of range"); + } + m_adjList[edge.src].emplace_back(edge.dest); + } + } + + /** Create a graph from vertices and a set of edges. + * + * Adjacency list of the graph would be created from the set of edges. If + * the source or destination of any edge has a value greater or equal to + * number of vertices, then it would throw a range_error. + * + * @param vertices specify the number of vertices the graph would contain. + * @param edges is a vector of edges. + */ + Graph(unsigned int const& vertices, std::vector&& edges) + : m_vertices(vertices) { + for (auto&& edge : std::move(edges)) { + if (edge.src >= vertices || edge.dest >= vertices) { + throw std::range_error( + "Either src or dest of edge out of range"); + } + m_adjList[edge.src].emplace_back(std::move(edge.dest)); + } + } + + /** Return a const reference of the adjacency list. + * + * @return const reference to the adjacency list + */ + std::remove_reference_t const& getAdjList() const { + return m_adjList; + } + + /** + * @return number of vertices in the graph. + */ + std::remove_reference_t const& getVertices() const { + return m_vertices; + } + + /** Add vertices in the graph. + * + * @param num is the number of vertices to be added. It adds 1 vertex by + * default. + * + */ + void addVertices(unsigned int num = 1) { m_vertices += num; } + + /** Add an edge in the graph. + * + * @param edge that needs to be added. + */ + void addEdge(Edge const& edge) { + if (edge.src >= m_vertices || edge.dest >= m_vertices) { + throw std::range_error("Either src or dest of edge out of range"); + } + m_adjList[edge.src].emplace_back(edge.dest); + } + + /** Add an Edge in the graph + * + * @param source is source vertex of the edge. + * @param destination is the destination vertex of the edge. + */ + void addEdge(unsigned int const& source, unsigned int const& destination) { + if (source >= m_vertices || destination >= m_vertices) { + throw std::range_error( + "Either source or destination of edge out of range"); + } + m_adjList[source].emplace_back(destination); + } + + private: + unsigned int m_vertices; + AdjList m_adjList; +}; + +class CycleCheck { + private: + enum nodeStates : uint8_t { not_visited = 0, in_stack, visited }; + + /** Helper function of "isCyclicDFS". + * + * @param adjList is the adjacency list representation of some graph. + * @param state is the state of the nodes of the graph. + * @param node is the node being evaluated. + * + * @return true if graph has a cycle, else false. + */ + static bool isCyclicDFSHelper(AdjList const& adjList, + std::vector& state, + unsigned int node) { + // Add node "in_stack" state. + state[node] = in_stack; + + // If the node has children, then recursively visit all children of the + // node. + if (auto const& it = adjList.find(node); it != adjList.end()) { + for (auto child : it->second) { + // If state of child node is "not_visited", evaluate that child + // for presence of cycle. + if (auto state_of_child = state[child]; + state_of_child == not_visited) { + if (isCyclicDFSHelper(adjList, state, child)) { + return true; + } + } else if (state_of_child == in_stack) { + // If child node was "in_stack", then that means that there + // is a cycle in the graph. Return true for presence of the + // cycle. + return true; + } + } + } + + // Current node has been evaluated for the presence of cycle and had no + // cycle. Mark current node as "visited". + state[node] = visited; + // Return that current node didn't result in any cycles. + return false; + } + + public: + /** Driver function to check if a graph has a cycle. + * + * This function uses DFS to check for cycle in the graph. + * + * @param graph which needs to be evaluated for the presence of cycle. + * @return true if a cycle is detected, else false. + */ + static bool isCyclicDFS(Graph const& graph) { + /** State of the node. + * + * It is a vector of "nodeStates" which represents the state node is in. + * It can take only 3 values: "not_visited", "in_stack", and "visited". + * + * Initially, all nodes are in "not_visited" state. + */ + std::vector state(graph.getVertices(), not_visited); + + // Start visiting each node. + for (auto node = 0; node < graph.getVertices(); node++) { + // If a node is not visited, only then check for presence of cycle. + // There is no need to check for presence of cycle for a visited + // node as it has already been checked for presence of cycle. + if (state[node] == not_visited) { + // Check for cycle. + if (isCyclicDFSHelper(graph.getAdjList(), state, node)) { + return true; + } + } + } + + // All nodes have been safely traversed, that means there is no cycle in + // the graph. Return false. + return false; + } + + /** Check if a graph has cycle or not. + * + * This function uses BFS to check if a graph is cyclic or not. + * + * @param graph which needs to be evaluated for the presence of cycle. + * @return true if a cycle is detected, else false. + */ + static bool isCyclicBFS(Graph const& graph) { + AdjList graphAjdList = graph.getAdjList(); + + std::vector indegree(graph.getVertices(), 0); + // Calculate the indegree i.e. the number of incident edges to the node. + for (auto const& [parent, children] : graphAjdList) { + for (auto const& child : children) { + indegree[child]++; + } + } + + std::queue can_be_solved; + for (auto node = 0; node < graph.getVertices(); node++) { + // If a node doesn't have any input edges, then that node will + // definately not result in a cycle and can be visited safely. + if (!indegree[node]) { + can_be_solved.emplace(node); + } + } + + // Vertices that need to be traversed. + auto remain = graph.getVertices(); + // While there are safe nodes that we can visit. + while (!can_be_solved.empty()) { + auto front = can_be_solved.front(); + // Visit the node. + can_be_solved.pop(); + // Decrease number of nodes that need to be traversed. + remain--; + + // Visit all the children of the visited node. + if (auto it = graphAjdList.find(front); it != graphAjdList.end()) { + for (auto child : it->second) { + // Check if we can visited the node safely. + if (--indegree[child] == 0) { + // if node can be visited safely, then add that node to + // the visit queue. + can_be_solved.emplace(child); + } + } + } + } + + // If there are still nodes that we can't visit, then it means that + // there is a cycle and return true, else return false. + return !(remain == 0); + } +}; + +/** + * Main function. + */ +int main() { + // Instantiate the graph. + Graph g(7, {{0, 1}, {1, 2}, {2, 0}, {2, 5}, {3, 5}}); + // Check for cycle using BFS method. + std::cout << CycleCheck::isCyclicBFS(g) << '\n'; + + // Check for cycle using DFS method. + std::cout << CycleCheck::isCyclicDFS(g) << '\n'; + return 0; +} From c1fadaaeb39d52f0c64e53240b531daaaf355729 Mon Sep 17 00:00:00 2001 From: Anmol3299 Date: Wed, 3 Jun 2020 18:17:05 +0530 Subject: [PATCH 321/433] Remove const references for input of simple types Reason: overhead on access --- graph/cycle_check_directed_graph.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/graph/cycle_check_directed_graph.cpp b/graph/cycle_check_directed_graph.cpp index 0cf5ac28ece..ba31b15c41e 100644 --- a/graph/cycle_check_directed_graph.cpp +++ b/graph/cycle_check_directed_graph.cpp @@ -39,7 +39,7 @@ struct Edge { * @param source is the source vertex of the edge. * @param destination is the destination vertex of the edge. */ - Edge(unsigned int const& source, unsigned int const& destination) + Edge(unsigned int source, unsigned int destination) : src(source), dest(destination) {} }; @@ -67,7 +67,7 @@ class Graph { * @param vertices specify the number of vertices the graph would contain. * @param adjList is the adjacency list representation of graph. */ - Graph(unsigned int const& vertices, AdjList const& adjList) + Graph(unsigned int vertices, AdjList const& adjList) : m_vertices(vertices), m_adjList(adjList) {} /** Create a graph from vertices and adjacency list. @@ -75,7 +75,7 @@ class Graph { * @param vertices specify the number of vertices the graph would contain. * @param adjList is the adjacency list representation of graph. */ - Graph(unsigned int const& vertices, AdjList&& adjList) + Graph(unsigned int vertices, AdjList&& adjList) : m_vertices(std::move(vertices)), m_adjList(std::move(adjList)) {} /** Create a graph from vertices and a set of edges. @@ -87,7 +87,7 @@ class Graph { * @param vertices specify the number of vertices the graph would contain. * @param edges is a vector of edges. */ - Graph(unsigned int const& vertices, std::vector const& edges) + Graph(unsigned int vertices, std::vector const& edges) : m_vertices(vertices) { for (auto const& edge : edges) { if (edge.src >= vertices || edge.dest >= vertices) { @@ -107,7 +107,7 @@ class Graph { * @param vertices specify the number of vertices the graph would contain. * @param edges is a vector of edges. */ - Graph(unsigned int const& vertices, std::vector&& edges) + Graph(unsigned int vertices, std::vector&& edges) : m_vertices(vertices) { for (auto&& edge : std::move(edges)) { if (edge.src >= vertices || edge.dest >= vertices) { @@ -157,7 +157,7 @@ class Graph { * @param source is source vertex of the edge. * @param destination is the destination vertex of the edge. */ - void addEdge(unsigned int const& source, unsigned int const& destination) { + void addEdge(unsigned int source, unsigned int destination) { if (source >= m_vertices || destination >= m_vertices) { throw std::range_error( "Either source or destination of edge out of range"); From a3df421e36d4d6da66c1d116d184b7007e30ea57 Mon Sep 17 00:00:00 2001 From: Anmol3299 Date: Wed, 3 Jun 2020 18:53:01 +0530 Subject: [PATCH 322/433] fix bad code sorry for force push --- graph/cycle_check_directed_graph.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/graph/cycle_check_directed_graph.cpp b/graph/cycle_check_directed_graph.cpp index ba31b15c41e..0aebd3c2e37 100644 --- a/graph/cycle_check_directed_graph.cpp +++ b/graph/cycle_check_directed_graph.cpp @@ -109,7 +109,7 @@ class Graph { */ Graph(unsigned int vertices, std::vector&& edges) : m_vertices(vertices) { - for (auto&& edge : std::move(edges)) { + for (auto&& edge : edges) { if (edge.src >= vertices || edge.dest >= vertices) { throw std::range_error( "Either src or dest of edge out of range"); From a77dafba6466222040c268851279f6ce1de2f558 Mon Sep 17 00:00:00 2001 From: Anmol3299 Date: Wed, 3 Jun 2020 19:40:51 +0530 Subject: [PATCH 323/433] Use pointer instead of the non-const reference because apparently google says so. --- graph/cycle_check_directed_graph.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/graph/cycle_check_directed_graph.cpp b/graph/cycle_check_directed_graph.cpp index 0aebd3c2e37..cfc5f2b02fe 100644 --- a/graph/cycle_check_directed_graph.cpp +++ b/graph/cycle_check_directed_graph.cpp @@ -183,10 +183,10 @@ class CycleCheck { * @return true if graph has a cycle, else false. */ static bool isCyclicDFSHelper(AdjList const& adjList, - std::vector& state, + std::vector* state, unsigned int node) { // Add node "in_stack" state. - state[node] = in_stack; + (*state)[node] = in_stack; // If the node has children, then recursively visit all children of the // node. @@ -194,7 +194,7 @@ class CycleCheck { for (auto child : it->second) { // If state of child node is "not_visited", evaluate that child // for presence of cycle. - if (auto state_of_child = state[child]; + if (auto state_of_child = (*state)[child]; state_of_child == not_visited) { if (isCyclicDFSHelper(adjList, state, child)) { return true; @@ -210,7 +210,7 @@ class CycleCheck { // Current node has been evaluated for the presence of cycle and had no // cycle. Mark current node as "visited". - state[node] = visited; + (*state)[node] = visited; // Return that current node didn't result in any cycles. return false; } @@ -240,7 +240,7 @@ class CycleCheck { // node as it has already been checked for presence of cycle. if (state[node] == not_visited) { // Check for cycle. - if (isCyclicDFSHelper(graph.getAdjList(), state, node)) { + if (isCyclicDFSHelper(graph.getAdjList(), &state, node)) { return true; } } From 8f04ffe3fb36334f3be63c40104db34c8df6ca24 Mon Sep 17 00:00:00 2001 From: Anmol3299 Date: Wed, 3 Jun 2020 20:33:38 +0530 Subject: [PATCH 324/433] Remove a useless and possibly bad Graph constuctor overload --- graph/cycle_check_directed_graph.cpp | 20 -------------------- 1 file changed, 20 deletions(-) diff --git a/graph/cycle_check_directed_graph.cpp b/graph/cycle_check_directed_graph.cpp index cfc5f2b02fe..4a619850dd4 100644 --- a/graph/cycle_check_directed_graph.cpp +++ b/graph/cycle_check_directed_graph.cpp @@ -98,26 +98,6 @@ class Graph { } } - /** Create a graph from vertices and a set of edges. - * - * Adjacency list of the graph would be created from the set of edges. If - * the source or destination of any edge has a value greater or equal to - * number of vertices, then it would throw a range_error. - * - * @param vertices specify the number of vertices the graph would contain. - * @param edges is a vector of edges. - */ - Graph(unsigned int vertices, std::vector&& edges) - : m_vertices(vertices) { - for (auto&& edge : edges) { - if (edge.src >= vertices || edge.dest >= vertices) { - throw std::range_error( - "Either src or dest of edge out of range"); - } - m_adjList[edge.src].emplace_back(std::move(edge.dest)); - } - } - /** Return a const reference of the adjacency list. * * @return const reference to the adjacency list From 9d8736e79e435ef7c0208bbdb91e99fa56bd681d Mon Sep 17 00:00:00 2001 From: Anmol3299 Date: Wed, 3 Jun 2020 20:40:09 +0530 Subject: [PATCH 325/433] Explicitely specify type of vector during graph instantiation --- graph/cycle_check_directed_graph.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/graph/cycle_check_directed_graph.cpp b/graph/cycle_check_directed_graph.cpp index 4a619850dd4..0f7b84cd303 100644 --- a/graph/cycle_check_directed_graph.cpp +++ b/graph/cycle_check_directed_graph.cpp @@ -292,7 +292,7 @@ class CycleCheck { */ int main() { // Instantiate the graph. - Graph g(7, {{0, 1}, {1, 2}, {2, 0}, {2, 5}, {3, 5}}); + Graph g(7, std::vector{{0, 1}, {1, 2}, {2, 0}, {2, 5}, {3, 5}}); // Check for cycle using BFS method. std::cout << CycleCheck::isCyclicBFS(g) << '\n'; From 6ebd88391f77c8fa7e5b2ef64cac303b8f4652d1 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Wed, 3 Jun 2020 15:39:21 +0000 Subject: [PATCH 326/433] updating DIRECTORY.md --- DIRECTORY.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 31146ab3d34..12e22361db0 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -49,6 +49,7 @@ * [Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/stack.h) * [Test Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/test_stack.cpp) * [Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/tree.cpp) + * [Trie Modern](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/trie_modern.cpp) * [Trie Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/trie_tree.cpp) ## Dynamic Programming @@ -80,6 +81,7 @@ * [Bridge Finding With Tarjan Algorithm](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/bridge_finding_with_tarjan_algorithm.cpp) * [Connected Components](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/connected_components.cpp) * [Connected Components With Dsu](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/connected_components_with_dsu.cpp) + * [Cycle Check Directed Graph](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/cycle_check_directed_graph.cpp) * [Dfs](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/dfs.cpp) * [Dfs With Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/dfs_with_stack.cpp) * [Dijkstra](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/dijkstra.cpp) From c476105881708d3fc90024c3386700ba7f66f89f Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Wed, 3 Jun 2020 21:40:28 -0400 Subject: [PATCH 327/433] find openMP before adding subdirectories --- CMakeLists.txt | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 46a03364962..d304c776f7f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.3) +cmake_minimum_required(VERSION 3.9) project(Algorithms_in_C++ LANGUAGES CXX VERSION 1.0.0 @@ -53,6 +53,15 @@ if(DOXYGEN_FOUND) ) endif() +if(USE_OPENMP) + find_package(OpenMP) + if (OpenMP_CXX_FOUND) + message(STATUS "Building with OpenMP Multithreading.") + else() + message(STATUS "No OpenMP found, no multithreading.") + endif() +endif() + add_subdirectory(math) add_subdirectory(others) add_subdirectory(search) @@ -63,15 +72,6 @@ add_subdirectory(probability) add_subdirectory(machine_learning) add_subdirectory(computer_oriented_statistical_methods) -if(USE_OPENMP) - find_package(OpenMP) - if (OpenMP_CXX_FOUND) - message(STATUS "Building with OpenMP Multithreading.") - else() - message(STATUS "No OpenMP found, no multithreading.") - endif() -endif() - set(CPACK_PROJECT_NAME ${PROJECT_NAME}) set(CPACK_PROJECT_VERSION ${PROJECT_VERSION}) include(CPack) From 65def005b8a33d9366515a121532fedbe3b1825d Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Wed, 3 Jun 2020 21:59:18 -0400 Subject: [PATCH 328/433] added kohonen self organizing map --- machine_learning/kohonen_som_trace.cpp | 428 +++++++++++++++++++++++++ 1 file changed, 428 insertions(+) create mode 100644 machine_learning/kohonen_som_trace.cpp diff --git a/machine_learning/kohonen_som_trace.cpp b/machine_learning/kohonen_som_trace.cpp new file mode 100644 index 00000000000..fd8c503cd0c --- /dev/null +++ b/machine_learning/kohonen_som_trace.cpp @@ -0,0 +1,428 @@ +/** + * \file + * \brief [Kohonen self organizing + * map](https://en.wikipedia.org/wiki/Self-organizing_map) (data tracing) + * + * This example implements a powerful self organizing map algorithm. + * The algorithm creates a connected network of weights that closely + * follows the given data points. This this creates a chain of nodes that + * resembles the given input shape. + * + * \note This C++ version of the program is considerable slower than its [C + * counterpart](https://github.com/kvedala/C/blob/master/machine_learning/kohonen_som_trace.c) + * \note The compiled code is much slower when compiled with MS Visual C++ 2019 + * than with GCC on windows + */ +#define _USE_MATH_DEFINES // required for MS Visual C++ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _OPENMP // check if OpenMP based parallellization is available +#include +#endif + +/** + * Helper function to generate a random number in a given interval. + * \n Steps: + * 1. `r1 = rand() % 100` gets a random number between 0 and 99 + * 2. `r2 = r1 / 100` converts random number to be between 0 and 0.99 + * 3. scale and offset the random number to given range of \f$[a,b]\f$ + * + * \param[in] a lower limit + * \param[in] b upper limit + * \returns random number in the range \f$[a,b]\f$ + */ +double _random(double a, double b) { + return ((b - a) * (std::rand() % 100) / 100.f) + a; +} + +/** + * Save a given n-dimensional data martix to file. + * + * \param[in] fname filename to save in (gets overwriten without confirmation) + * \param[in] X matrix to save + * \returns 0 if all ok + * \returns -1 if file creation failed + */ +int save_nd_data(const char *fname, + const std::vector> &X) { + size_t num_points = X.size(); // number of rows + size_t num_features = X[0].size(); // number of columns + + std::ofstream fp; + fp.open(fname); + if (!fp.is_open()) { + // error with opening file to write + std::cerr << "Error opening file " << fname << "\n"; + return -1; + } + + // for each point in the array + for (int i = 0; i < num_points; i++) { + // for each feature in the array + for (int j = 0; j < num_features; j++) { + fp << X[i][j]; // print the feature value + if (j < num_features - 1) // if not the last feature + fp << ","; // suffix comma + } + if (i < num_points - 1) // if not the last row + fp << "\n"; // start a new line + } + + fp.close(); + return 0; +} + +/** + * Update weights of the SOM using Kohonen algorithm + * + * \param[in] X data point + * \param[in,out] W weights matrix + * \param[in,out] D temporary vector to store distances + * \param[in] alpha learning rate \f$0<\alpha\le1\f$ + * \param[in] R neighborhood range + */ +void update_weights(const std::valarray &x, + std::vector> *W, + std::valarray *D, double alpha, int R) { + int j, k; + int num_out = W->size(); // number of SOM output nodes + int num_features = x.size(); // number of data features + +#ifdef _OPENMP +#pragma omp for +#endif + // step 1: for each output point + for (j = 0; j < num_out; j++) { + // compute Euclidian distance of each output + // point from the current sample + (*D)[j] = (((*W)[j] - x) * ((*W)[j] - x)).sum(); + } + + // step 2: get closest node i.e., node with snallest Euclidian distance to + // the current pattern + auto result = std::min_element(std::begin(*D), std::end(*D)); + double d_min = *result; + int d_min_idx = std::distance(std::begin(*D), result); + + // step 3a: get the neighborhood range + int from_node = std::max(0, d_min_idx - R); + int to_node = std::min(num_out, d_min_idx + R + 1); + + // step 3b: update the weights of nodes in the + // neighborhood +#ifdef _OPENMP +#pragma omp for +#endif + for (j = from_node; j < to_node; j++) + // update weights of nodes in the neighborhood + (*W)[j] += alpha * (x - (*W)[j]); +} + +/** + * Apply incremental algorithm with updating neighborhood and learning rates + * on all samples in the given datset. + * + * \param[in] X data set + * \param[in,out] W weights matrix + * \param[in] D temporary vector to store distances + * \param[in] alpha_min terminal value of alpha + */ +void kohonen_som_tracer(const std::vector> &X, + std::vector> *W, + double alpha_min) { + int num_samples = X.size(); // number of rows + int num_features = X[0].size(); // number of columns + int num_out = W->size(); // number of rows + int R = num_out >> 2, iter = 0; + double alpha = 1.f; + + std::valarray D(num_out); + + // Loop alpha from 1 to slpha_min + for (; alpha > alpha_min; alpha -= 0.01, iter++) { + // Loop for each sample pattern in the data set + for (int sample = 0; sample < num_samples; sample++) { + // update weights for the current input pattern sample + update_weights(X[sample], W, &D, alpha, R); + } + + // every 10th iteration, reduce the neighborhood range + if (iter % 10 == 0 && R > 1) + R--; + } +} + +/** Creates a random set of points distributed *near* the circumference + * of a circle and trains an SOM that finds that circular pattern. The + * generating function is + * \f{eqnarray*}{ \f} + * + * \param[out] data matrix to store data in + */ +void test_circle(std::vector> *data) { + const int N = data->size(); + const double R = 0.75, dr = 0.3; + double a_t = 0., b_t = 2.f * M_PI; // theta random between 0 and 2*pi + double a_r = R - dr, b_r = R + dr; // radius random between R-dr and R+dr + int i; + +#ifdef _OPENMP +#pragma omp for +#endif + for (i = 0; i < N; i++) { + double r = _random(a_r, b_r); // random radius + double theta = _random(a_t, b_t); // random theta + data[0][i][0] = r * cos(theta); // convert from polar to cartesian + data[0][i][1] = r * sin(theta); + } +} + +/** Test that creates a random set of points distributed *near* the + * circumference of a circle and trains an SOM that finds that circular pattern. + * The following [CSV](https://en.wikipedia.org/wiki/Comma-separated_values) + * files are created to validate the execution: + * * `test1.csv`: random test samples points with a circular pattern + * * `w11.csv`: initial random map + * * `w12.csv`: trained SOM map + * + * The outputs can be readily plotted in [gnuplot](https:://gnuplot.info) using + * the following snippet + * ```gnuplot + * set datafile separator ',' + * plot "test1.csv" title "original", \ + * "w11.csv" title "w1", \ + * "w12.csv" title "w2" + * ``` + * ![Sample execution + * output](https://raw.githubusercontent.com/kvedala/C/docs/images/machine_learning/kohonen/test1.svg) + */ +void test1() { + int j, N = 500; + int features = 2; + int num_out = 50; + std::vector> X(N); + std::vector> W(num_out); + for (int i = 0; i < std::max(num_out, N); i++) { + // loop till max(N, num_out) + if (i < N) // only add new arrays if i < N + X[i] = std::valarray(features); + if (i < num_out) { // only add new arrays if i < num_out + W[i] = std::valarray(features); + +#ifdef _OPENMP +#pragma omp for +#endif + for (j = 0; j < features; j++) + // preallocate with random initial weights + W[i][j] = _random(-1, 1); + } + } + + test_circle(&X); // create test data around circumference of a circle + save_nd_data("test1.csv", X); // save test data points + save_nd_data("w11.csv", W); // save initial random weights + kohonen_som_tracer(X, &W, 0.1); // train the SOM + save_nd_data("w12.csv", W); // save the resultant weights +} + +/** Creates a random set of points distributed *near* the locus + * of the [Lamniscate of + * Gerono](https://en.wikipedia.org/wiki/Lemniscate_of_Gerono) and trains an SOM + * that finds that circular pattern. + * \param[out] data matrix to store data in + */ +void test_lamniscate(std::vector> *data) { + const int N = data->size(); + const double dr = 0.2; + int i; + +#ifdef _OPENMP +#pragma omp for +#endif + for (i = 0; i < N; i++) { + double dx = _random(-dr, dr); // random change in x + double dy = _random(-dr, dr); // random change in y + double theta = _random(0, M_PI); // random theta + data[0][i][0] = dx + cos(theta); // convert from polar to cartesian + data[0][i][1] = dy + sin(2. * theta) / 2.f; + } +} + +/** Test that creates a random set of points distributed *near* the locus + * of the [Lamniscate of + * Gerono](https://en.wikipedia.org/wiki/Lemniscate_of_Gerono) and trains an SOM + * that finds that circular pattern. The following + * [CSV](https://en.wikipedia.org/wiki/Comma-separated_values) files are created + * to validate the execution: + * * `test2.csv`: random test samples points with a lamniscate pattern + * * `w21.csv`: initial random map + * * `w22.csv`: trained SOM map + * + * The outputs can be readily plotted in [gnuplot](https:://gnuplot.info) using + * the following snippet + * ```gnuplot + * set datafile separator ',' + * plot "test2.csv" title "original", \ + * "w21.csv" title "w1", \ + * "w22.csv" title "w2" + * ``` + * ![Sample execution + * output](https://raw.githubusercontent.com/kvedala/C/docs/images/machine_learning/kohonen/test2.svg) + */ +void test2() { + int j, N = 500; + int features = 2; + int num_out = 20; + std::vector> X(N); + std::vector> W(num_out); + for (int i = 0; i < std::max(num_out, N); i++) { + // loop till max(N, num_out) + if (i < N) // only add new arrays if i < N + X[i] = std::valarray(features); + if (i < num_out) { // only add new arrays if i < num_out + W[i] = std::valarray(features); + +#ifdef _OPENMP +#pragma omp for +#endif + for (j = 0; j < features; j++) + // preallocate with random initial weights + W[i][j] = _random(-1, 1); + } + } + + test_lamniscate(&X); // create test data around the lamniscate + save_nd_data("test2.csv", X); // save test data points + save_nd_data("w21.csv", W); // save initial random weights + kohonen_som_tracer(X, &W, 0.01); // train the SOM + save_nd_data("w22.csv", W); // save the resultant weights +} + +/** Creates a random set of points distributed *near* the locus + * of the [Lamniscate of + * Gerono](https://en.wikipedia.org/wiki/Lemniscate_of_Gerono) and trains an SOM + * that finds that circular pattern. + * \param[out] data matrix to store data in + */ +void test_3d_classes(std::vector> *data) { + const int N = data->size(); + const double R = 0.1; // radius of cluster + int i; + const int num_classes = 8; + const double centres[][3] = { + // centres of each class cluster + {.5, .5, .5}, // centre of class 0 + {.5, .5, -.5}, // centre of class 1 + {.5, -.5, .5}, // centre of class 2 + {.5, -.5, -.5}, // centre of class 3 + {-.5, .5, .5}, // centre of class 4 + {-.5, .5, -.5}, // centre of class 5 + {-.5, -.5, .5}, // centre of class 6 + {-.5, -.5, -.5} // centre of class 7 + }; + +#ifdef _OPENMP +#pragma omp for +#endif + for (i = 0; i < N; i++) { + int cls = + std::rand() % num_classes; // select a random class for the point + + // create random coordinates (x,y,z) around the centre of the class + data[0][i][0] = _random(centres[cls][0] - R, centres[cls][0] + R); + data[0][i][1] = _random(centres[cls][1] - R, centres[cls][1] + R); + data[0][i][2] = _random(centres[cls][2] - R, centres[cls][2] + R); + + /* The follosing can also be used + for (int j = 0; j < 3; j++) + data[0][i][j] = _random(centres[cls][j] - R, centres[cls][j] + R); + */ + } +} + +/** Test that creates a random set of points distributed in six clusters in + * 3D space. The following + * [CSV](https://en.wikipedia.org/wiki/Comma-separated_values) files are created + * to validate the execution: + * * `test3.csv`: random test samples points with a circular pattern + * * `w31.csv`: initial random map + * * `w32.csv`: trained SOM map + * + * The outputs can be readily plotted in [gnuplot](https:://gnuplot.info) using + * the following snippet + * ```gnuplot + * set datafile separator ',' + * plot "test3.csv" title "original", \ + * "w31.csv" title "w1", \ + * "w32.csv" title "w2" + * ``` + * ![Sample execution + * output](https://raw.githubusercontent.com/kvedala/C/docs/images/machine_learning/kohonen/test3.svg) + */ +void test3() { + int j, N = 200; + int features = 3; + int num_out = 20; + std::vector> X(N); + std::vector> W(num_out); + for (int i = 0; i < std::max(num_out, N); i++) { + // loop till max(N, num_out) + if (i < N) // only add new arrays if i < N + X[i] = std::valarray(features); + if (i < num_out) { // only add new arrays if i < num_out + W[i] = std::valarray(features); + +#ifdef _OPENMP +#pragma omp for +#endif + for (j = 0; j < features; j++) + // preallocate with random initial weights + W[i][j] = _random(-1, 1); + } + } + + test_3d_classes(&X); // create test data around the lamniscate + save_nd_data("test3.csv", X); // save test data points + save_nd_data("w31.csv", W); // save initial random weights + kohonen_som_tracer(X, &W, 0.01); // train the SOM + save_nd_data("w32.csv", W); // save the resultant weights +} + +/** Main function */ +int main(int argc, char **argv) { +#ifdef _OPENMP + std::cout << "Using OpenMP based parallelization\n"; +#else + std::cout << "NOT using OpenMP based parallelization\n"; +#endif + + auto start_clk = std::chrono::steady_clock::now(); + test1(); + auto end_clk = std::chrono::steady_clock::now(); + std::chrono::duration time_diff = end_clk - start_clk; + std::cout << "Test 1 completed in " << time_diff.count() << " sec\n"; + + start_clk = std::chrono::steady_clock::now(); + test2(); + end_clk = std::chrono::steady_clock::now(); + time_diff = end_clk - start_clk; + std::cout << "Test 2 completed in " << time_diff.count() << " sec\n"; + + start_clk = std::chrono::steady_clock::now(); + test3(); + end_clk = std::chrono::steady_clock::now(); + time_diff = end_clk - start_clk; + std::cout << "Test 3 completed in " << time_diff.count() << " sec\n"; + + std::cout + << "(Note: Calculated times include: creating test sets, training " + "model and writing files to disk.)\n\n"; + return 0; +} From c6f12f290fea02f0332e7fcc430279d3d1e10748 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 4 Jun 2020 02:01:35 +0000 Subject: [PATCH 329/433] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 31146ab3d34..5507717efb9 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -106,6 +106,7 @@ ## Machine Learning * [Adaline Learning](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/machine_learning/adaline_learning.cpp) + * [Kohonen Som Trace](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/machine_learning/kohonen_som_trace.cpp) ## Math * [Binary Exponent](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/binary_exponent.cpp) From aea585284abfc089394f371e070480cbdc1e273e Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Wed, 3 Jun 2020 22:02:20 -0400 Subject: [PATCH 330/433] remove older files and folders from gh-pages before adding new files --- .github/workflows/gh-pages.yml | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml index 700d1a3f7a8..881ea1c3375 100644 --- a/.github/workflows/gh-pages.yml +++ b/.github/workflows/gh-pages.yml @@ -1,6 +1,6 @@ name: Doxygen CI -on: +on: push: branches: [master] @@ -25,10 +25,12 @@ jobs: clean: false - name: Move & Commit files run: | - cp -rp ./build/html/* . && rm -rf ./build && ls -lah git config --global user.name github-actions git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - git add * + rm -rf d* && rm *.html && rm *.svg && rm *.map && rm *.md5 && rm *.png && rm *.js && rm *.css + git add . + cp -rp ./build/html/* . && rm -rf ./build && ls -lah + git add . git commit -m "Documentation for $GITHUB_SHA" || true git push --force || true From 1085bf43012ab269fb29141f2b7afbbbe274e81e Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Wed, 3 Jun 2020 22:13:46 -0400 Subject: [PATCH 331/433] remove chronos library due to inacceptability by cpplint --- machine_learning/kohonen_som_trace.cpp | 36 ++++++++++++++++---------- 1 file changed, 23 insertions(+), 13 deletions(-) diff --git a/machine_learning/kohonen_som_trace.cpp b/machine_learning/kohonen_som_trace.cpp index fd8c503cd0c..1c45e7b3f2f 100644 --- a/machine_learning/kohonen_som_trace.cpp +++ b/machine_learning/kohonen_som_trace.cpp @@ -15,7 +15,6 @@ */ #define _USE_MATH_DEFINES // required for MS Visual C++ #include -#include #include #include #include @@ -395,6 +394,17 @@ void test3() { save_nd_data("w32.csv", W); // save the resultant weights } +/** + * Convert clock cycle difference to time in seconds + * + * \param[in] start_t start clock + * \param[in] end_t end clock + * \returns time difference in seconds + */ +double get_clock_diff(clock_t start_t, clock_t end_t) { + return (double)(end_t - start_t) / (double)CLOCKS_PER_SEC; +} + /** Main function */ int main(int argc, char **argv) { #ifdef _OPENMP @@ -403,23 +413,23 @@ int main(int argc, char **argv) { std::cout << "NOT using OpenMP based parallelization\n"; #endif - auto start_clk = std::chrono::steady_clock::now(); + std::clock_t start_clk = std::clock(); test1(); - auto end_clk = std::chrono::steady_clock::now(); - std::chrono::duration time_diff = end_clk - start_clk; - std::cout << "Test 1 completed in " << time_diff.count() << " sec\n"; + auto end_clk = std::clock(); + std::cout << "Test 1 completed in " << get_clock_diff(start_clk, end_clk) + << " sec\n"; - start_clk = std::chrono::steady_clock::now(); + start_clk = std::clock(); test2(); - end_clk = std::chrono::steady_clock::now(); - time_diff = end_clk - start_clk; - std::cout << "Test 2 completed in " << time_diff.count() << " sec\n"; + end_clk = std::clock(); + std::cout << "Test 2 completed in " << get_clock_diff(start_clk, end_clk) + << " sec\n"; - start_clk = std::chrono::steady_clock::now(); + start_clk = std::clock(); test3(); - end_clk = std::chrono::steady_clock::now(); - time_diff = end_clk - start_clk; - std::cout << "Test 3 completed in " << time_diff.count() << " sec\n"; + end_clk = std::clock(); + std::cout << "Test 3 completed in " << get_clock_diff(start_clk, end_clk) + << " sec\n"; std::cout << "(Note: Calculated times include: creating test sets, training " From c8a2b1d5b20300e34686a65ffd70919bc660cc5f Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Wed, 3 Jun 2020 22:16:14 -0400 Subject: [PATCH 332/433] use c++ specific static_cast instead --- machine_learning/kohonen_som_trace.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/machine_learning/kohonen_som_trace.cpp b/machine_learning/kohonen_som_trace.cpp index 1c45e7b3f2f..61d3245ec77 100644 --- a/machine_learning/kohonen_som_trace.cpp +++ b/machine_learning/kohonen_som_trace.cpp @@ -402,7 +402,7 @@ void test3() { * \returns time difference in seconds */ double get_clock_diff(clock_t start_t, clock_t end_t) { - return (double)(end_t - start_t) / (double)CLOCKS_PER_SEC; + return static_cast(end_t - start_t) / CLOCKS_PER_SEC; } /** Main function */ From 503593e68e9bc7993cd92292bd3a81e794fbad04 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Wed, 3 Jun 2020 23:03:25 -0400 Subject: [PATCH 333/433] initialize radom number generator --- machine_learning/kohonen_som_trace.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/machine_learning/kohonen_som_trace.cpp b/machine_learning/kohonen_som_trace.cpp index 61d3245ec77..83a65287d56 100644 --- a/machine_learning/kohonen_som_trace.cpp +++ b/machine_learning/kohonen_som_trace.cpp @@ -413,6 +413,8 @@ int main(int argc, char **argv) { std::cout << "NOT using OpenMP based parallelization\n"; #endif + std::srand(std::time(nullptr)); + std::clock_t start_clk = std::clock(); test1(); auto end_clk = std::clock(); From ebeaebe30ddc1854d39f3d3677b9cbd7d1be4e64 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Wed, 3 Jun 2020 23:03:53 -0400 Subject: [PATCH 334/433] updated image links with those from CPP repository --- machine_learning/kohonen_som_trace.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/machine_learning/kohonen_som_trace.cpp b/machine_learning/kohonen_som_trace.cpp index 83a65287d56..f2da7d1831f 100644 --- a/machine_learning/kohonen_som_trace.cpp +++ b/machine_learning/kohonen_som_trace.cpp @@ -200,7 +200,7 @@ void test_circle(std::vector> *data) { * "w12.csv" title "w2" * ``` * ![Sample execution - * output](https://raw.githubusercontent.com/kvedala/C/docs/images/machine_learning/kohonen/test1.svg) + * output](https://raw.githubusercontent.com/kvedala/C-Plus-Plus/docs/images/machine_learning/kohonen/test1.svg) */ void test1() { int j, N = 500; @@ -273,7 +273,7 @@ void test_lamniscate(std::vector> *data) { * "w22.csv" title "w2" * ``` * ![Sample execution - * output](https://raw.githubusercontent.com/kvedala/C/docs/images/machine_learning/kohonen/test2.svg) + * output](https://raw.githubusercontent.com/kvedala/C-Plus-Plus/docs/images/machine_learning/kohonen/test2.svg) */ void test2() { int j, N = 500; @@ -363,7 +363,7 @@ void test_3d_classes(std::vector> *data) { * "w32.csv" title "w2" * ``` * ![Sample execution - * output](https://raw.githubusercontent.com/kvedala/C/docs/images/machine_learning/kohonen/test3.svg) + * output](https://raw.githubusercontent.com/kvedala/C-Plus-Plus/docs/images/machine_learning/kohonen/test3.svg) */ void test3() { int j, N = 200; From 1116ab2babd2ff5fecfe449d4b50d8f932476707 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 07:41:08 -0400 Subject: [PATCH 335/433] rename computer.... folder to numerical methods --- CMakeLists.txt | 2 +- .../CMakeLists.txt | 2 +- .../bisection_method.cpp | 0 .../false_position.cpp | 0 .../gaussian_elimination.cpp | 0 .../newton_raphson_method.cpp | 0 .../ordinary_least_squares_regressor.cpp | 0 .../successive_approximation.cpp | 0 8 files changed, 2 insertions(+), 2 deletions(-) rename {computer_oriented_statistical_methods => numerical_methods}/CMakeLists.txt (91%) rename {computer_oriented_statistical_methods => numerical_methods}/bisection_method.cpp (100%) rename {computer_oriented_statistical_methods => numerical_methods}/false_position.cpp (100%) rename {computer_oriented_statistical_methods => numerical_methods}/gaussian_elimination.cpp (100%) rename {computer_oriented_statistical_methods => numerical_methods}/newton_raphson_method.cpp (100%) rename {computer_oriented_statistical_methods => numerical_methods}/ordinary_least_squares_regressor.cpp (100%) rename {computer_oriented_statistical_methods => numerical_methods}/successive_approximation.cpp (100%) diff --git a/CMakeLists.txt b/CMakeLists.txt index d304c776f7f..430be40d6fb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -70,7 +70,7 @@ add_subdirectory(sorting) add_subdirectory(geometry) add_subdirectory(probability) add_subdirectory(machine_learning) -add_subdirectory(computer_oriented_statistical_methods) +add_subdirectory(numerical_methods) set(CPACK_PROJECT_NAME ${PROJECT_NAME}) set(CPACK_PROJECT_VERSION ${PROJECT_VERSION}) diff --git a/computer_oriented_statistical_methods/CMakeLists.txt b/numerical_methods/CMakeLists.txt similarity index 91% rename from computer_oriented_statistical_methods/CMakeLists.txt rename to numerical_methods/CMakeLists.txt index acff1ed1c5c..fc4c343de30 100644 --- a/computer_oriented_statistical_methods/CMakeLists.txt +++ b/numerical_methods/CMakeLists.txt @@ -13,6 +13,6 @@ foreach( testsourcefile ${APP_SOURCES} ) if(OpenMP_CXX_FOUND) target_link_libraries(${testname} OpenMP::OpenMP_CXX) endif() - install(TARGETS ${testname} DESTINATION "bin/stats") + install(TARGETS ${testname} DESTINATION "bin/numerical_methods") endforeach( testsourcefile ${APP_SOURCES} ) diff --git a/computer_oriented_statistical_methods/bisection_method.cpp b/numerical_methods/bisection_method.cpp similarity index 100% rename from computer_oriented_statistical_methods/bisection_method.cpp rename to numerical_methods/bisection_method.cpp diff --git a/computer_oriented_statistical_methods/false_position.cpp b/numerical_methods/false_position.cpp similarity index 100% rename from computer_oriented_statistical_methods/false_position.cpp rename to numerical_methods/false_position.cpp diff --git a/computer_oriented_statistical_methods/gaussian_elimination.cpp b/numerical_methods/gaussian_elimination.cpp similarity index 100% rename from computer_oriented_statistical_methods/gaussian_elimination.cpp rename to numerical_methods/gaussian_elimination.cpp diff --git a/computer_oriented_statistical_methods/newton_raphson_method.cpp b/numerical_methods/newton_raphson_method.cpp similarity index 100% rename from computer_oriented_statistical_methods/newton_raphson_method.cpp rename to numerical_methods/newton_raphson_method.cpp diff --git a/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp b/numerical_methods/ordinary_least_squares_regressor.cpp similarity index 100% rename from computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp rename to numerical_methods/ordinary_least_squares_regressor.cpp diff --git a/computer_oriented_statistical_methods/successive_approximation.cpp b/numerical_methods/successive_approximation.cpp similarity index 100% rename from computer_oriented_statistical_methods/successive_approximation.cpp rename to numerical_methods/successive_approximation.cpp From eb977ba9d2220d94344d75e3ece98f8e746c35e2 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 11:32:57 -0400 Subject: [PATCH 336/433] added durand kerner method for root computation for arbitrarily large polynomials --- numerical_methods/durand_kerner_roots.cpp | 226 ++++++++++++++++++++++ 1 file changed, 226 insertions(+) create mode 100644 numerical_methods/durand_kerner_roots.cpp diff --git a/numerical_methods/durand_kerner_roots.cpp b/numerical_methods/durand_kerner_roots.cpp new file mode 100644 index 00000000000..42ed474e01c --- /dev/null +++ b/numerical_methods/durand_kerner_roots.cpp @@ -0,0 +1,226 @@ +/** + * @file + * Compute riots of any given polynomial. + * + * Test the algorithm online: + * https://gist.github.com/kvedala/27f1b0b6502af935f6917673ec43bcd7 + * + * Try the highly unstable Wilkinson's polynomial: + * ``` + * ./numerical_methods/durand_kerner_roots 1 -210 20615 -1256850 53327946 + * -1672280820 40171771630 -756111184500 11310276995381 -135585182899530 + * 1307535010540395 -10142299865511450 63030812099294896 -311333643161390640 + * 1206647803780373360 -3599979517947607200 8037811822645051776 + * -12870931245150988800 13803759753640704000 -8752948036761600000 + * 2432902008176640000 + * ``` + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _OPENMP +#include +#endif + +#define ACCURACY 1e-10 /**< maximum accuracy limit */ + +/** + * Evaluate the value of a polynomial with given coefficients + * \param[in] coeffs coefficients of the polynomial + * \param[in] degree degree of polynomial + * \param[in] x point at which to evaluate the polynomial + * \returns \f$f(x)\f$ + **/ +std::complex poly_function(const std::valarray &coeffs, + std::complex x) { + double real = 0.f, imag = 0.f; + int n; + +#ifdef _OPENMP +#pragma omp parallel for reduction(+ : real, imag) +#endif + for (n = 0; n < coeffs.size(); n++) { + std::complex tmp = + coeffs[n] * std::pow(x, coeffs.size() - n - 1); + real += tmp.real(); + imag += tmp.imag(); + } + + return std::complex(real, imag); +} + +/** + * create a textual form of complex number + * \param[in] x point at which to evaluate the polynomial + * \returns pointer to converted string + */ +const char *complex_str(const std::complex &x) { + static char msg[50]; + + sprintf(msg, "% 7.04g%+7.04gj", x.real(), x.imag()); + + return msg; +} + +/** + * check for termination condition + * \param[in] delta point at which to evaluate the polynomial + * \returns `false` if termination not reached + * \returns `true` if termination reached + */ +bool check_termination(long double delta) { + static long double past_delta = INFINITY; + if (std::abs(past_delta - delta) <= ACCURACY || delta < ACCURACY) + return true; + past_delta = delta; + return false; +} + +/*** + * Main function. + * The comandline input arguments are taken as coeffiecients of a polynomial. + * For example, this command + * ```sh + * ./durand_kerner_roots 1 0 -4 + * ``` + * will find roots of the polynomial \f$1\cdot x^2 + 0\cdot x^1 + (-4)=0\f$ + **/ +int main(int argc, char **argv) { + unsigned int degree = 0; + unsigned int n, i; + + if (argc < 2) { + std::cout + << "Please pass the coefficients of the polynomial as commandline " + "arguments.\n"; + return 0; + } + + degree = argc - 1; // detected polynomial degree + std::valarray coeffs(degree); // create coefficiencts array + + /* initialize random seed: */ + std::srand(std::time(nullptr)); + +#if defined(DEBUG) || !defined(NDEBUG) + /* + * store intermediate values to a CSV file + */ + std::ofstream log_file; + log_file.open("durand_kerner.log.csv"); + if (!log_file.is_open()) { + perror("Unable to create a storage log file!"); + return EXIT_FAILURE; + } + log_file << "iter#,"; +#endif + + // number of roots = degree - 1 + std::valarray> s0(degree - 1); + + std::cout << "Computing the roots for:\n\t"; + for (n = 0; n < degree; n++) { + coeffs[n] = strtod(argv[n + 1], nullptr); + if (n < degree - 1 && coeffs[n] != 0) + std::cout << "(" << coeffs[n] << ") x^" << degree - n - 1 << " + ,"; + else if (coeffs[n] != 0) + std::cout << "(" << coeffs[n] << ") x^" << degree - n - 1 + << " = 0\n"; + + /* initialize root approximations with random values */ + if (n < degree - 1) { + s0[n] = std::complex(std::rand() % 100, std::rand() % 100); + s0[n] -= 50.f; + s0[n] /= 50.f; +#if defined(DEBUG) || !defined(NDEBUG) + log_file << "root_" << n << ","; +#endif + } + } + + // numerical errors less when the first coefficient is "1" + // hence, we normalize the first coefficient + coeffs /= coeffs[0]; + +#if defined(DEBUG) || !defined(NDEBUG) + log_file << "avg. correction"; + log_file << "\n0,"; + for (n = 0; n < degree - 1; n++) log_file << complex_str(s0[n]) << ","; +#endif + + double tol_condition = 1; + unsigned long iter = 0; + + clock_t end_time, start_time = clock(); + while (!check_termination(tol_condition) && iter < INT_MAX) { + std::complex delta = 0; + tol_condition = 0; + iter++; + +#if defined(DEBUG) || !defined(NDEBUG) + log_file << "\n" << iter << ","; +#endif + + for (n = 0; n < degree - 1; n++) { + std::complex numerator, denominator; + numerator = poly_function(coeffs, s0[n]); + denominator = 1.0; + for (i = 0; i < degree - 1; i++) + if (i != n) + denominator *= s0[n] - s0[i]; + + delta = numerator / denominator; + + if (std::isnan(std::abs(delta)) || std::isinf(std::abs(delta))) { + std::cerr << "\n\nOverflow/underrun error - got value = " + << std::abs(delta); + goto end; + } + + s0[n] -= delta; + + tol_condition = std::max(tol_condition, std::abs(std::abs(delta))); + +#if defined(DEBUG) || !defined(NDEBUG) + log_file << complex_str(s0[n]) << ","; +#endif + } + // tol_condition /= (degree - 1); + +#if defined(DEBUG) || !defined(NDEBUG) + if (iter % 500 == 0) { + std::cout << "Iter: " << iter << "\t"; + for (n = 0; n < degree - 1; n++) + std::cout << "\t" << complex_str(s0[n]); + std::cout << "\t\tabsolute average change: " << tol_condition + << "\n"; + } + + log_file << tol_condition; +#endif + } +end: + + end_time = clock(); + +#if defined(DEBUG) || !defined(NDEBUG) + log_file.close(); +#endif + + std::cout << "\nIterations: " << iter << "\n"; + for (n = 0; n < degree - 1; n++) + std::cout << "\t" << complex_str(s0[n]) << "\n"; + std::cout << "absolute average change: " << tol_condition << "\n"; + std::cout << "Time taken: " + << (end_time - start_time) / (double)CLOCKS_PER_SEC << " sec\n"; + + return 0; +} \ No newline at end of file From bbd578d4a15c818b35c5d901433cc72c7baaa2a1 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 11:38:34 -0400 Subject: [PATCH 337/433] fixed additional comma --- numerical_methods/durand_kerner_roots.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/numerical_methods/durand_kerner_roots.cpp b/numerical_methods/durand_kerner_roots.cpp index 42ed474e01c..dd746ad7cd6 100644 --- a/numerical_methods/durand_kerner_roots.cpp +++ b/numerical_methods/durand_kerner_roots.cpp @@ -130,7 +130,7 @@ int main(int argc, char **argv) { for (n = 0; n < degree; n++) { coeffs[n] = strtod(argv[n + 1], nullptr); if (n < degree - 1 && coeffs[n] != 0) - std::cout << "(" << coeffs[n] << ") x^" << degree - n - 1 << " + ,"; + std::cout << "(" << coeffs[n] << ") x^" << degree - n - 1 << " + "; else if (coeffs[n] != 0) std::cout << "(" << coeffs[n] << ") x^" << degree - n - 1 << " = 0\n"; From 355d84dba91c17d453f54e4c78ae65c8ac2c1d15 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 11:46:30 -0400 Subject: [PATCH 338/433] fix cpplint errors --- numerical_methods/durand_kerner_roots.cpp | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/numerical_methods/durand_kerner_roots.cpp b/numerical_methods/durand_kerner_roots.cpp index dd746ad7cd6..030364d27f9 100644 --- a/numerical_methods/durand_kerner_roots.cpp +++ b/numerical_methods/durand_kerner_roots.cpp @@ -63,9 +63,10 @@ std::complex poly_function(const std::valarray &coeffs, * \returns pointer to converted string */ const char *complex_str(const std::complex &x) { - static char msg[50]; +#define MAX_BUFF_SIZE 50 + static char msg[MAX_BUFF_SIZE]; - sprintf(msg, "% 7.04g%+7.04gj", x.real(), x.imag()); + std::snprintf(msg, MAX_BUFF_SIZE, "% 7.04g%+7.04gj", x.real(), x.imag()); return msg; } @@ -148,7 +149,10 @@ int main(int argc, char **argv) { // numerical errors less when the first coefficient is "1" // hence, we normalize the first coefficient - coeffs /= coeffs[0]; + { + double tmp = coeffs[0]; + coeffs /= tmp; + } #if defined(DEBUG) || !defined(NDEBUG) log_file << "avg. correction"; @@ -157,7 +161,7 @@ int main(int argc, char **argv) { #endif double tol_condition = 1; - unsigned long iter = 0; + uint32_t iter = 0; clock_t end_time, start_time = clock(); while (!check_termination(tol_condition) && iter < INT_MAX) { @@ -220,7 +224,8 @@ int main(int argc, char **argv) { std::cout << "\t" << complex_str(s0[n]) << "\n"; std::cout << "absolute average change: " << tol_condition << "\n"; std::cout << "Time taken: " - << (end_time - start_time) / (double)CLOCKS_PER_SEC << " sec\n"; + << static_cast(end_time - start_time) / CLOCKS_PER_SEC + << " sec\n"; return 0; -} \ No newline at end of file +} From 7a4ca60754d102ceaba06de43273cc7f7ca7680f Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 4 Jun 2020 15:47:37 +0000 Subject: [PATCH 339/433] updating DIRECTORY.md --- DIRECTORY.md | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index 5507717efb9..3bca579f628 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -10,14 +10,6 @@ * [Rat Maze](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/rat_maze.cpp) * [Sudoku Solve](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/sudoku_solve.cpp) -## Computer Oriented Statistical Methods - * [Bisection Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/bisection_method.cpp) - * [False Position](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/false_position.cpp) - * [Gaussian Elimination](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/gaussian_elimination.cpp) - * [Newton Raphson Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/newton_raphson_method.cpp) - * [Ordinary Least Squares Regressor](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp) - * [Successive Approximation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/successive_approximation.cpp) - ## Data Structure * [Avltree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/avltree.cpp) * [Binary Search Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/binary_search_tree.cpp) @@ -134,6 +126,15 @@ * [Sqrt Double](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/sqrt_double.cpp) * [String Fibonacci](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/string_fibonacci.cpp) +## Numerical Methods + * [Bisection Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/bisection_method.cpp) + * [Durand Kerner Roots](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/durand_kerner_roots.cpp) + * [False Position](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/false_position.cpp) + * [Gaussian Elimination](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/gaussian_elimination.cpp) + * [Newton Raphson Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/newton_raphson_method.cpp) + * [Ordinary Least Squares Regressor](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/ordinary_least_squares_regressor.cpp) + * [Successive Approximation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/successive_approximation.cpp) + ## Operations On Datastructures * [Array Left Rotation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/array_left_rotation.cpp) * [Array Right Rotation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/array_right_rotation.cpp) From 4d548fe29eb2cd37e40926b1d296aad1f447712b Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 12:14:26 -0400 Subject: [PATCH 340/433] convert to function module --- numerical_methods/durand_kerner_roots.cpp | 162 +++++++++++----------- 1 file changed, 81 insertions(+), 81 deletions(-) diff --git a/numerical_methods/durand_kerner_roots.cpp b/numerical_methods/durand_kerner_roots.cpp index 030364d27f9..e407a573490 100644 --- a/numerical_methods/durand_kerner_roots.cpp +++ b/numerical_methods/durand_kerner_roots.cpp @@ -85,6 +85,83 @@ bool check_termination(long double delta) { return false; } +std::pair durand_kerner_algo( + const std::valarray &coeffs, + std::valarray> *roots, bool write_log = false) { + double tol_condition = 1; + uint32_t iter = 0; + int i, n, degree = coeffs.size(); + std::ofstream log_file; + + if (write_log) { + /* + * store intermediate values to a CSV file + */ + log_file.open("durand_kerner.log.csv"); + if (!log_file.is_open()) { + perror("Unable to create a storage log file!"); + std::exit(EXIT_FAILURE); + } + log_file << "iter#,"; + + for (n = 0; n < degree - 1; n++) log_file << "root_" << n << ","; + + log_file << "avg. correction"; + log_file << "\n0,"; + for (n = 0; n < degree - 1; n++) + log_file << complex_str((*roots)[n]) << ","; + } + + while (!check_termination(tol_condition) && iter < INT_MAX) { + std::complex delta = 0; + tol_condition = 0; + iter++; + + if (log_file.is_open()) + log_file << "\n" << iter << ","; + + for (n = 0; n < degree - 1; n++) { + std::complex numerator, denominator; + numerator = poly_function(coeffs, (*roots)[n]); + denominator = 1.0; + for (i = 0; i < degree - 1; i++) + if (i != n) + denominator *= (*roots)[n] - (*roots)[i]; + + delta = numerator / denominator; + + if (std::isnan(std::abs(delta)) || std::isinf(std::abs(delta))) { + std::cerr << "\n\nOverflow/underrun error - got value = " + << std::abs(delta); + return std::pair(iter, tol_condition); + } + + (*roots)[n] -= delta; + + tol_condition = std::max(tol_condition, std::abs(std::abs(delta))); + + if (log_file.is_open()) + log_file << complex_str((*roots)[n]) << ","; + } + // tol_condition /= (degree - 1); + +#if defined(DEBUG) || !defined(NDEBUG) + if (iter % 500 == 0) { + std::cout << "Iter: " << iter << "\t"; + for (n = 0; n < degree - 1; n++) + std::cout << "\t" << complex_str((*roots)[n]); + std::cout << "\t\tabsolute average change: " << tol_condition + << "\n"; + } +#endif + + if (log_file.is_open()) + log_file << tol_condition; + } + + return std::pair(iter, tol_condition); +} + /*** * Main function. * The comandline input arguments are taken as coeffiecients of a polynomial. @@ -96,7 +173,7 @@ bool check_termination(long double delta) { **/ int main(int argc, char **argv) { unsigned int degree = 0; - unsigned int n, i; + unsigned int n; if (argc < 2) { std::cout @@ -111,19 +188,6 @@ int main(int argc, char **argv) { /* initialize random seed: */ std::srand(std::time(nullptr)); -#if defined(DEBUG) || !defined(NDEBUG) - /* - * store intermediate values to a CSV file - */ - std::ofstream log_file; - log_file.open("durand_kerner.log.csv"); - if (!log_file.is_open()) { - perror("Unable to create a storage log file!"); - return EXIT_FAILURE; - } - log_file << "iter#,"; -#endif - // number of roots = degree - 1 std::valarray> s0(degree - 1); @@ -141,9 +205,6 @@ int main(int argc, char **argv) { s0[n] = std::complex(std::rand() % 100, std::rand() % 100); s0[n] -= 50.f; s0[n] /= 50.f; -#if defined(DEBUG) || !defined(NDEBUG) - log_file << "root_" << n << ","; -#endif } } @@ -154,75 +215,14 @@ int main(int argc, char **argv) { coeffs /= tmp; } -#if defined(DEBUG) || !defined(NDEBUG) - log_file << "avg. correction"; - log_file << "\n0,"; - for (n = 0; n < degree - 1; n++) log_file << complex_str(s0[n]) << ","; -#endif - - double tol_condition = 1; - uint32_t iter = 0; - clock_t end_time, start_time = clock(); - while (!check_termination(tol_condition) && iter < INT_MAX) { - std::complex delta = 0; - tol_condition = 0; - iter++; - -#if defined(DEBUG) || !defined(NDEBUG) - log_file << "\n" << iter << ","; -#endif - - for (n = 0; n < degree - 1; n++) { - std::complex numerator, denominator; - numerator = poly_function(coeffs, s0[n]); - denominator = 1.0; - for (i = 0; i < degree - 1; i++) - if (i != n) - denominator *= s0[n] - s0[i]; - - delta = numerator / denominator; - - if (std::isnan(std::abs(delta)) || std::isinf(std::abs(delta))) { - std::cerr << "\n\nOverflow/underrun error - got value = " - << std::abs(delta); - goto end; - } - - s0[n] -= delta; - - tol_condition = std::max(tol_condition, std::abs(std::abs(delta))); - -#if defined(DEBUG) || !defined(NDEBUG) - log_file << complex_str(s0[n]) << ","; -#endif - } - // tol_condition /= (degree - 1); - -#if defined(DEBUG) || !defined(NDEBUG) - if (iter % 500 == 0) { - std::cout << "Iter: " << iter << "\t"; - for (n = 0; n < degree - 1; n++) - std::cout << "\t" << complex_str(s0[n]); - std::cout << "\t\tabsolute average change: " << tol_condition - << "\n"; - } - - log_file << tol_condition; -#endif - } -end: - + auto result = durand_kerner_algo(coeffs, &s0, true); end_time = clock(); -#if defined(DEBUG) || !defined(NDEBUG) - log_file.close(); -#endif - - std::cout << "\nIterations: " << iter << "\n"; + std::cout << "\nIterations: " << result.first << "\n"; for (n = 0; n < degree - 1; n++) std::cout << "\t" << complex_str(s0[n]) << "\n"; - std::cout << "absolute average change: " << tol_condition << "\n"; + std::cout << "absolute average change: " << result.second << "\n"; std::cout << "Time taken: " << static_cast(end_time - start_time) / CLOCKS_PER_SEC << " sec\n"; From 4b68a888eb2aa38a241a208d13b25169a2933b90 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 12:34:52 -0400 Subject: [PATCH 341/433] update documentation --- numerical_methods/durand_kerner_roots.cpp | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/numerical_methods/durand_kerner_roots.cpp b/numerical_methods/durand_kerner_roots.cpp index e407a573490..424319329f1 100644 --- a/numerical_methods/durand_kerner_roots.cpp +++ b/numerical_methods/durand_kerner_roots.cpp @@ -1,6 +1,8 @@ /** * @file - * Compute riots of any given polynomial. + * \brief Compute all possible approximate roots of any given polynomial using + * [Durand Kerner + * algorithm](https://en.wikipedia.org/wiki/Durand%E2%80%93Kerner_method) * * Test the algorithm online: * https://gist.github.com/kvedala/27f1b0b6502af935f6917673ec43bcd7 @@ -85,6 +87,16 @@ bool check_termination(long double delta) { return false; } +/** + * Implements Durand Kerner iterative algorithm to compute all roots of a + * polynomial. + * + * \param[in] coeffs coefficients of the polynomial + * \param[out] roots the computed roots of the polynomial + * \param[in] write_log flag whether to save the log file (default = `false`) + * \returns pair of values - number of iterations taken and final accuracy + * achieved + */ std::pair durand_kerner_algo( const std::valarray &coeffs, std::valarray> *roots, bool write_log = false) { From 4e75c6d1eac51fe2731a59eb11e099b9a8e9eb99 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 12:35:13 -0400 Subject: [PATCH 342/433] move openmp to main loop --- numerical_methods/durand_kerner_roots.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/numerical_methods/durand_kerner_roots.cpp b/numerical_methods/durand_kerner_roots.cpp index 424319329f1..a714e8f1b29 100644 --- a/numerical_methods/durand_kerner_roots.cpp +++ b/numerical_methods/durand_kerner_roots.cpp @@ -46,9 +46,9 @@ std::complex poly_function(const std::valarray &coeffs, double real = 0.f, imag = 0.f; int n; -#ifdef _OPENMP -#pragma omp parallel for reduction(+ : real, imag) -#endif + // #ifdef _OPENMP + // #pragma omp parallel for reduction(+ : real, imag) + // #endif for (n = 0; n < coeffs.size(); n++) { std::complex tmp = coeffs[n] * std::pow(x, coeffs.size() - n - 1); @@ -132,6 +132,9 @@ std::pair durand_kerner_algo( if (log_file.is_open()) log_file << "\n" << iter << ","; +#ifdef _OPENMP +#pragma omp for +#endif for (n = 0; n < degree - 1; n++) { std::complex numerator, denominator; numerator = poly_function(coeffs, (*roots)[n]); From 29ed37d67e65ccf4e02b7b48bd4b41c02a04f800 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 13:15:28 -0400 Subject: [PATCH 343/433] added two test cases --- numerical_methods/durand_kerner_roots.cpp | 82 ++++++++++++++++++++--- 1 file changed, 71 insertions(+), 11 deletions(-) diff --git a/numerical_methods/durand_kerner_roots.cpp b/numerical_methods/durand_kerner_roots.cpp index a714e8f1b29..b49a2cef6c1 100644 --- a/numerical_methods/durand_kerner_roots.cpp +++ b/numerical_methods/durand_kerner_roots.cpp @@ -19,14 +19,13 @@ */ #include -#include +#include #include #include #include #include #include #include -#include #include #ifdef _OPENMP #include @@ -37,7 +36,6 @@ /** * Evaluate the value of a polynomial with given coefficients * \param[in] coeffs coefficients of the polynomial - * \param[in] degree degree of polynomial * \param[in] x point at which to evaluate the polynomial * \returns \f$f(x)\f$ **/ @@ -177,27 +175,89 @@ std::pair durand_kerner_algo( return std::pair(iter, tol_condition); } +/** + * Self test the algorithm by checking the roots for \f$x^2+4=0\f$ to which the + * roots are \f$0 \pm 2i\f$ + */ +void test1() { + const std::valarray coeffs = {1, 0, 4}; // x^2 - 2 = 0 + std::valarray> roots = { + std::complex(-100., 100.), + std::complex(100., -100.) // initial approximate roots + }; + std::valarray> expected = { + std::complex(0., 2.), + std::complex(0., -2.) // known expected roots + }; + + auto result = durand_kerner_algo(coeffs, &roots, false); + + for (int i = 0; i < roots.size(); i++) { + // check if approximations are have < 0.1% error with one of the + // expected roots + bool err1 = false; + for (int j = 0; j < roots.size(); j++) + err1 |= std::abs(std::abs(roots[i] - expected[j])) < 1e-3; + assert(err1); + } + + std::cout << "Test 1 passed! - " << result.first << " iterations, " + << result.second << " accuracy" + << "\n"; +} + +/** + * Self test the algorithm by checking the roots for \f$0.015625x^3-1=0\f$ to + * which the roots are \f$(4+0i),\,(-2\pm3.464i)\f$ + */ +void test2() { + const std::valarray coeffs = {// 0.015625 x^3 - 1 = 0 + 1. / 64., 0., 0., -1.}; + std::valarray> roots = { + std::complex(-100., 100.), std::complex(-101., 101.), + std::complex(2., -2.) // initial approximate roots + }; + std::valarray> expected = { + std::complex(4., 0.), std::complex(-2., 3.46410162), + std::complex(-2., -3.46410162) // known expected roots + }; + + auto result = durand_kerner_algo(coeffs, &roots, false); + + for (int i = 0; i < roots.size(); i++) { + // check if approximations are have < 0.1% error with one of the + // expected roots + bool err1 = false; + for (int j = 0; j < roots.size(); j++) + err1 |= std::abs(std::abs(roots[i] - expected[j])) < 1e-3; + assert(err1); + } + std::cout << "Test 2 passed! - " << result.first << " iterations, " + << result.second << " accuracy" + << "\n"; +} + /*** * Main function. - * The comandline input arguments are taken as coeffiecients of a polynomial. - * For example, this command + * The comandline input arguments are taken as coeffiecients of a + *polynomial. For example, this command * ```sh * ./durand_kerner_roots 1 0 -4 * ``` * will find roots of the polynomial \f$1\cdot x^2 + 0\cdot x^1 + (-4)=0\f$ **/ int main(int argc, char **argv) { - unsigned int degree = 0; - unsigned int n; + test1(); + test2(); if (argc < 2) { - std::cout - << "Please pass the coefficients of the polynomial as commandline " - "arguments.\n"; + std::cout << "Please pass the coefficients of the polynomial as " + "commandline " + "arguments.\n"; return 0; } - degree = argc - 1; // detected polynomial degree + int n, degree = argc - 1; // detected polynomial degree std::valarray coeffs(degree); // create coefficiencts array /* initialize random seed: */ From 3b37d06d2a3ed215ff896da75a5204cf5dfa9ddf Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 13:37:34 -0400 Subject: [PATCH 344/433] use INT16_MAX --- numerical_methods/durand_kerner_roots.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/numerical_methods/durand_kerner_roots.cpp b/numerical_methods/durand_kerner_roots.cpp index b49a2cef6c1..90789fd4d83 100644 --- a/numerical_methods/durand_kerner_roots.cpp +++ b/numerical_methods/durand_kerner_roots.cpp @@ -100,7 +100,7 @@ std::pair durand_kerner_algo( std::valarray> *roots, bool write_log = false) { double tol_condition = 1; uint32_t iter = 0; - int i, n, degree = coeffs.size(); + int i, n; std::ofstream log_file; if (write_log) { @@ -114,15 +114,15 @@ std::pair durand_kerner_algo( } log_file << "iter#,"; - for (n = 0; n < degree - 1; n++) log_file << "root_" << n << ","; + for (n = 0; n < roots->size(); n++) log_file << "root_" << n << ","; log_file << "avg. correction"; log_file << "\n0,"; - for (n = 0; n < degree - 1; n++) + for (n = 0; n < roots->size(); n++) log_file << complex_str((*roots)[n]) << ","; } - while (!check_termination(tol_condition) && iter < INT_MAX) { + while (!check_termination(tol_condition) && iter < INT16_MAX) { std::complex delta = 0; tol_condition = 0; iter++; @@ -133,11 +133,11 @@ std::pair durand_kerner_algo( #ifdef _OPENMP #pragma omp for #endif - for (n = 0; n < degree - 1; n++) { + for (n = 0; n < roots->size(); n++) { std::complex numerator, denominator; numerator = poly_function(coeffs, (*roots)[n]); denominator = 1.0; - for (i = 0; i < degree - 1; i++) + for (i = 0; i < roots->size(); i++) if (i != n) denominator *= (*roots)[n] - (*roots)[i]; @@ -161,7 +161,7 @@ std::pair durand_kerner_algo( #if defined(DEBUG) || !defined(NDEBUG) if (iter % 500 == 0) { std::cout << "Iter: " << iter << "\t"; - for (n = 0; n < degree - 1; n++) + for (n = 0; n < roots->size(); n++) std::cout << "\t" << complex_str((*roots)[n]); std::cout << "\t\tabsolute average change: " << tol_condition << "\n"; From 5e34779d9506abf0ac3ac1cae44c586b7e8906b3 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 13:57:57 -0400 Subject: [PATCH 345/433] remove return statement from omp-for loop and use "break" --- numerical_methods/durand_kerner_roots.cpp | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/numerical_methods/durand_kerner_roots.cpp b/numerical_methods/durand_kerner_roots.cpp index 90789fd4d83..a970829cac8 100644 --- a/numerical_methods/durand_kerner_roots.cpp +++ b/numerical_methods/durand_kerner_roots.cpp @@ -122,10 +122,13 @@ std::pair durand_kerner_algo( log_file << complex_str((*roots)[n]) << ","; } - while (!check_termination(tol_condition) && iter < INT16_MAX) { + bool break_loop = false; + while (!check_termination(tol_condition) && iter < INT16_MAX && + !break_loop) { std::complex delta = 0; tol_condition = 0; iter++; + break_loop = false; if (log_file.is_open()) log_file << "\n" << iter << ","; @@ -146,9 +149,13 @@ std::pair durand_kerner_algo( if (std::isnan(std::abs(delta)) || std::isinf(std::abs(delta))) { std::cerr << "\n\nOverflow/underrun error - got value = " << std::abs(delta); - return std::pair(iter, tol_condition); + // return std::pair(iter, tol_condition); + break_loop = true; } + if (break_loop) + break; + (*roots)[n] -= delta; tol_condition = std::max(tol_condition, std::abs(std::abs(delta))); @@ -158,6 +165,9 @@ std::pair durand_kerner_algo( } // tol_condition /= (degree - 1); + if (break_loop) + break; + #if defined(DEBUG) || !defined(NDEBUG) if (iter % 500 == 0) { std::cout << "Iter: " << iter << "\t"; From 586ac1aee190bb21d2115811fefc9f9c867f2c46 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 13:59:24 -0400 Subject: [PATCH 346/433] run tests when no input is provided and skip tests when input polynomial is provided --- numerical_methods/durand_kerner_roots.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/numerical_methods/durand_kerner_roots.cpp b/numerical_methods/durand_kerner_roots.cpp index a970829cac8..13e79dbd963 100644 --- a/numerical_methods/durand_kerner_roots.cpp +++ b/numerical_methods/durand_kerner_roots.cpp @@ -257,10 +257,9 @@ void test2() { * will find roots of the polynomial \f$1\cdot x^2 + 0\cdot x^1 + (-4)=0\f$ **/ int main(int argc, char **argv) { - test1(); - test2(); - if (argc < 2) { + test1(); // run tests when no input is provided + test2(); // and skip tests when input polynomial is provided std::cout << "Please pass the coefficients of the polynomial as " "commandline " "arguments.\n"; From 0e5d841e0a18c897685a383a6e1b31bf7f56832c Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 14:02:18 -0400 Subject: [PATCH 347/433] while loop cannot have break - replaced with continue and check is present in the main while condition --- numerical_methods/durand_kerner_roots.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/numerical_methods/durand_kerner_roots.cpp b/numerical_methods/durand_kerner_roots.cpp index 13e79dbd963..dd6a10f22f7 100644 --- a/numerical_methods/durand_kerner_roots.cpp +++ b/numerical_methods/durand_kerner_roots.cpp @@ -166,7 +166,7 @@ std::pair durand_kerner_algo( // tol_condition /= (degree - 1); if (break_loop) - break; + continue; #if defined(DEBUG) || !defined(NDEBUG) if (iter % 500 == 0) { From 89f33a49ba2bf70e4189c484a60eea59a2d5b286 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 14:14:46 -0400 Subject: [PATCH 348/433] (1) break while loop (2) skip runs on break_loop instead of hard-break --- numerical_methods/durand_kerner_roots.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/numerical_methods/durand_kerner_roots.cpp b/numerical_methods/durand_kerner_roots.cpp index dd6a10f22f7..01fd4ebaf44 100644 --- a/numerical_methods/durand_kerner_roots.cpp +++ b/numerical_methods/durand_kerner_roots.cpp @@ -134,9 +134,12 @@ std::pair durand_kerner_algo( log_file << "\n" << iter << ","; #ifdef _OPENMP -#pragma omp for +#pragma omp parallel for shared(break_loop) #endif for (n = 0; n < roots->size(); n++) { + if (break_loop) + continue; + std::complex numerator, denominator; numerator = poly_function(coeffs, (*roots)[n]); denominator = 1.0; @@ -153,9 +156,6 @@ std::pair durand_kerner_algo( break_loop = true; } - if (break_loop) - break; - (*roots)[n] -= delta; tol_condition = std::max(tol_condition, std::abs(std::abs(delta))); @@ -166,7 +166,7 @@ std::pair durand_kerner_algo( // tol_condition /= (degree - 1); if (break_loop) - continue; + break; #if defined(DEBUG) || !defined(NDEBUG) if (iter % 500 == 0) { From b7d05eab9e99988e2a85612c27d87d0d8740fd1a Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 14:14:59 -0400 Subject: [PATCH 349/433] add documentation images --- numerical_methods/durand_kerner_roots.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/numerical_methods/durand_kerner_roots.cpp b/numerical_methods/durand_kerner_roots.cpp index 01fd4ebaf44..2a8d8b5e7b6 100644 --- a/numerical_methods/durand_kerner_roots.cpp +++ b/numerical_methods/durand_kerner_roots.cpp @@ -16,6 +16,12 @@ * -12870931245150988800 13803759753640704000 -8752948036761600000 * 2432902008176640000 * ``` + * Sample implementation results to compute approximate roots of the equation + * \f$x^4-1=0\f$:\n + * ![Error + * evolution](https://raw.githubusercontent.com/kvedala/C-Plus-Plus/docs/images/numerical_methods/durand_kerner_error.svg) + * ![Roots + * evolution](https://raw.githubusercontent.com/kvedala/C-Plus-Plus/docs/images/numerical_methods/durand_kerner_roots.svg) */ #include From 42f78bbe1998bac1f9b5bd8554462ba647a17141 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 15:20:31 -0400 Subject: [PATCH 350/433] use long double for errors and tolerance checks --- numerical_methods/durand_kerner_roots.cpp | 44 ++++++++++++++--------- 1 file changed, 28 insertions(+), 16 deletions(-) diff --git a/numerical_methods/durand_kerner_roots.cpp b/numerical_methods/durand_kerner_roots.cpp index 2a8d8b5e7b6..5d5b65bf520 100644 --- a/numerical_methods/durand_kerner_roots.cpp +++ b/numerical_methods/durand_kerner_roots.cpp @@ -104,7 +104,7 @@ bool check_termination(long double delta) { std::pair durand_kerner_algo( const std::valarray &coeffs, std::valarray> *roots, bool write_log = false) { - double tol_condition = 1; + long double tol_condition = 1; uint32_t iter = 0; int i, n; std::ofstream log_file; @@ -153,11 +153,11 @@ std::pair durand_kerner_algo( if (i != n) denominator *= (*roots)[n] - (*roots)[i]; - delta = numerator / denominator; + std::complex delta = numerator / denominator; if (std::isnan(std::abs(delta)) || std::isinf(std::abs(delta))) { std::cerr << "\n\nOverflow/underrun error - got value = " - << std::abs(delta); + << std::abs(delta) << "\n"; // return std::pair(iter, tol_condition); break_loop = true; } @@ -188,7 +188,7 @@ std::pair durand_kerner_algo( log_file << tol_condition; } - return std::pair(iter, tol_condition); + return std::pair(iter, tol_condition); } /** @@ -197,15 +197,19 @@ std::pair durand_kerner_algo( */ void test1() { const std::valarray coeffs = {1, 0, 4}; // x^2 - 2 = 0 - std::valarray> roots = { - std::complex(-100., 100.), - std::complex(100., -100.) // initial approximate roots - }; + std::valarray> roots(2); std::valarray> expected = { std::complex(0., 2.), std::complex(0., -2.) // known expected roots }; + /* initialize root approximations with random values */ + for (int n = 0; n < roots.size(); n++) { + roots[n] = std::complex(std::rand() % 100, std::rand() % 100); + roots[n] -= 50.f; + roots[n] /= 25.f; + } + auto result = durand_kerner_algo(coeffs, &roots, false); for (int i = 0; i < roots.size(); i++) { @@ -229,17 +233,24 @@ void test1() { void test2() { const std::valarray coeffs = {// 0.015625 x^3 - 1 = 0 1. / 64., 0., 0., -1.}; - std::valarray> roots = { - std::complex(-100., 100.), std::complex(-101., 101.), - std::complex(2., -2.) // initial approximate roots - }; - std::valarray> expected = { + std::valarray> roots(3); + const std::valarray> expected = { std::complex(4., 0.), std::complex(-2., 3.46410162), std::complex(-2., -3.46410162) // known expected roots }; + /* initialize root approximations with random values */ + for (int n = 0; n < roots.size(); n++) { + roots[n] = std::complex(std::rand() % 100, std::rand() % 100); + roots[n] -= 50.f; + roots[n] /= 25.f; + } + auto result = durand_kerner_algo(coeffs, &roots, false); + for (int n = 0; n < roots.size(); n++) + std::cout << "\t" << complex_str(roots[n]) << "\n"; + for (int i = 0; i < roots.size(); i++) { // check if approximations are have < 0.1% error with one of the // expected roots @@ -248,6 +259,7 @@ void test2() { err1 |= std::abs(std::abs(roots[i] - expected[j])) < 1e-3; assert(err1); } + std::cout << "Test 2 passed! - " << result.first << " iterations, " << result.second << " accuracy" << "\n"; @@ -263,6 +275,9 @@ void test2() { * will find roots of the polynomial \f$1\cdot x^2 + 0\cdot x^1 + (-4)=0\f$ **/ int main(int argc, char **argv) { + /* initialize random seed: */ + std::srand(std::time(nullptr)); + if (argc < 2) { test1(); // run tests when no input is provided test2(); // and skip tests when input polynomial is provided @@ -275,9 +290,6 @@ int main(int argc, char **argv) { int n, degree = argc - 1; // detected polynomial degree std::valarray coeffs(degree); // create coefficiencts array - /* initialize random seed: */ - std::srand(std::time(nullptr)); - // number of roots = degree - 1 std::valarray> s0(degree - 1); From 645321c38fa65bf98a0e9d52f14b5f2834ed7f87 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 15:21:09 -0400 Subject: [PATCH 351/433] make iterator variable i local to threads --- numerical_methods/durand_kerner_roots.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/numerical_methods/durand_kerner_roots.cpp b/numerical_methods/durand_kerner_roots.cpp index 5d5b65bf520..395797bfcfe 100644 --- a/numerical_methods/durand_kerner_roots.cpp +++ b/numerical_methods/durand_kerner_roots.cpp @@ -106,7 +106,7 @@ std::pair durand_kerner_algo( std::valarray> *roots, bool write_log = false) { long double tol_condition = 1; uint32_t iter = 0; - int i, n; + int n; std::ofstream log_file; if (write_log) { @@ -149,7 +149,7 @@ std::pair durand_kerner_algo( std::complex numerator, denominator; numerator = poly_function(coeffs, (*roots)[n]); denominator = 1.0; - for (i = 0; i < roots->size(); i++) + for (int i = 0; i < roots->size(); i++) if (i != n) denominator *= (*roots)[n] - (*roots)[i]; From e4f53974989b7317ade3e85c2c4d9d6b0e62c203 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 15:21:45 -0400 Subject: [PATCH 352/433] add critical secions to omp threads --- numerical_methods/durand_kerner_roots.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/numerical_methods/durand_kerner_roots.cpp b/numerical_methods/durand_kerner_roots.cpp index 395797bfcfe..e92c8d6b93e 100644 --- a/numerical_methods/durand_kerner_roots.cpp +++ b/numerical_methods/durand_kerner_roots.cpp @@ -140,7 +140,7 @@ std::pair durand_kerner_algo( log_file << "\n" << iter << ","; #ifdef _OPENMP -#pragma omp parallel for shared(break_loop) +#pragma omp parallel for shared(break_loop, tol_condition) #endif for (n = 0; n < roots->size(); n++) { if (break_loop) @@ -164,9 +164,15 @@ std::pair durand_kerner_algo( (*roots)[n] -= delta; +#ifdef _OPENMP +#pragma omp critical +#endif tol_condition = std::max(tol_condition, std::abs(std::abs(delta))); if (log_file.is_open()) +#ifdef _OPENMP +#pragma omp critical +#endif log_file << complex_str((*roots)[n]) << ","; } // tol_condition /= (degree - 1); @@ -248,9 +254,6 @@ void test2() { auto result = durand_kerner_algo(coeffs, &roots, false); - for (int n = 0; n < roots.size(); n++) - std::cout << "\t" << complex_str(roots[n]) << "\n"; - for (int i = 0; i < roots.size(); i++) { // check if approximations are have < 0.1% error with one of the // expected roots From 7f82722c849222a05fb6051eeb6ef0793467b8cf Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 15:39:33 -0400 Subject: [PATCH 353/433] bugfix: move file writing outside of the parallel loop othersie, there is no gurantee of the order of roots written to file --- numerical_methods/durand_kerner_roots.cpp | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/numerical_methods/durand_kerner_roots.cpp b/numerical_methods/durand_kerner_roots.cpp index e92c8d6b93e..70288d2c586 100644 --- a/numerical_methods/durand_kerner_roots.cpp +++ b/numerical_methods/durand_kerner_roots.cpp @@ -20,6 +20,7 @@ * \f$x^4-1=0\f$:\n * ![Error * evolution](https://raw.githubusercontent.com/kvedala/C-Plus-Plus/docs/images/numerical_methods/durand_kerner_error.svg) + * * ![Roots * evolution](https://raw.githubusercontent.com/kvedala/C-Plus-Plus/docs/images/numerical_methods/durand_kerner_roots.svg) */ @@ -168,18 +169,16 @@ std::pair durand_kerner_algo( #pragma omp critical #endif tol_condition = std::max(tol_condition, std::abs(std::abs(delta))); - - if (log_file.is_open()) -#ifdef _OPENMP -#pragma omp critical -#endif - log_file << complex_str((*roots)[n]) << ","; } // tol_condition /= (degree - 1); if (break_loop) break; + if (log_file.is_open()) + for (n = 0; n < roots->size(); n++) + log_file << complex_str((*roots)[n]) << ","; + #if defined(DEBUG) || !defined(NDEBUG) if (iter % 500 == 0) { std::cout << "Iter: " << iter << "\t"; From 495bffcd72c199b78c893660494f7c6cbc150a08 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 16:15:10 -0400 Subject: [PATCH 354/433] rename folder to data_structures --- {data_structure => data_structures}/avltree.cpp | 0 {data_structure => data_structures}/binary_search_tree.cpp | 0 {data_structure => data_structures}/binaryheap.cpp | 0 .../circular_queue_using_linked_list.cpp | 0 {data_structure => data_structures}/cll/cll.cpp | 0 {data_structure => data_structures}/cll/cll.h | 0 {data_structure => data_structures}/cll/main_cll.cpp | 0 {data_structure => data_structures}/cll/makefile | 0 {data_structure => data_structures}/disjoint_set.cpp | 0 {data_structure => data_structures}/doubly_linked_list.cpp | 0 {data_structure => data_structures}/linked_list.cpp | 0 .../linkedlist_implentation_usingarray.cpp | 0 {data_structure => data_structures}/list_array.cpp | 0 {data_structure => data_structures}/morrisinorder.cpp | 0 {data_structure => data_structures}/queue/makefile | 0 {data_structure => data_structures}/queue/queue.cpp | 0 {data_structure => data_structures}/queue/queue.h | 0 {data_structure => data_structures}/queue/test_queue.cpp | 0 {data_structure => data_structures}/queue_using_array.cpp | 0 {data_structure => data_structures}/queue_using_array2.cpp | 0 {data_structure => data_structures}/queue_using_linked_list.cpp | 0 {data_structure => data_structures}/queue_using_linkedlist.cpp | 0 {data_structure => data_structures}/stack_using_array.cpp | 0 {data_structure => data_structures}/stack_using_linked_list.cpp | 0 {data_structure => data_structures}/stk/main.cpp | 0 {data_structure => data_structures}/stk/makefile | 0 {data_structure => data_structures}/stk/stack.cpp | 0 {data_structure => data_structures}/stk/stack.h | 0 {data_structure => data_structures}/stk/student.txt | 0 {data_structure => data_structures}/stk/test_stack.cpp | 0 {data_structure => data_structures}/tree.cpp | 0 {data_structure => data_structures}/trie_tree.cpp | 0 32 files changed, 0 insertions(+), 0 deletions(-) rename {data_structure => data_structures}/avltree.cpp (100%) rename {data_structure => data_structures}/binary_search_tree.cpp (100%) rename {data_structure => data_structures}/binaryheap.cpp (100%) rename {data_structure => data_structures}/circular_queue_using_linked_list.cpp (100%) rename {data_structure => data_structures}/cll/cll.cpp (100%) rename {data_structure => data_structures}/cll/cll.h (100%) rename {data_structure => data_structures}/cll/main_cll.cpp (100%) rename {data_structure => data_structures}/cll/makefile (100%) rename {data_structure => data_structures}/disjoint_set.cpp (100%) rename {data_structure => data_structures}/doubly_linked_list.cpp (100%) rename {data_structure => data_structures}/linked_list.cpp (100%) rename {data_structure => data_structures}/linkedlist_implentation_usingarray.cpp (100%) rename {data_structure => data_structures}/list_array.cpp (100%) rename {data_structure => data_structures}/morrisinorder.cpp (100%) rename {data_structure => data_structures}/queue/makefile (100%) rename {data_structure => data_structures}/queue/queue.cpp (100%) rename {data_structure => data_structures}/queue/queue.h (100%) rename {data_structure => data_structures}/queue/test_queue.cpp (100%) rename {data_structure => data_structures}/queue_using_array.cpp (100%) rename {data_structure => data_structures}/queue_using_array2.cpp (100%) rename {data_structure => data_structures}/queue_using_linked_list.cpp (100%) rename {data_structure => data_structures}/queue_using_linkedlist.cpp (100%) rename {data_structure => data_structures}/stack_using_array.cpp (100%) rename {data_structure => data_structures}/stack_using_linked_list.cpp (100%) rename {data_structure => data_structures}/stk/main.cpp (100%) rename {data_structure => data_structures}/stk/makefile (100%) rename {data_structure => data_structures}/stk/stack.cpp (100%) rename {data_structure => data_structures}/stk/stack.h (100%) rename {data_structure => data_structures}/stk/student.txt (100%) rename {data_structure => data_structures}/stk/test_stack.cpp (100%) rename {data_structure => data_structures}/tree.cpp (100%) rename {data_structure => data_structures}/trie_tree.cpp (100%) diff --git a/data_structure/avltree.cpp b/data_structures/avltree.cpp similarity index 100% rename from data_structure/avltree.cpp rename to data_structures/avltree.cpp diff --git a/data_structure/binary_search_tree.cpp b/data_structures/binary_search_tree.cpp similarity index 100% rename from data_structure/binary_search_tree.cpp rename to data_structures/binary_search_tree.cpp diff --git a/data_structure/binaryheap.cpp b/data_structures/binaryheap.cpp similarity index 100% rename from data_structure/binaryheap.cpp rename to data_structures/binaryheap.cpp diff --git a/data_structure/circular_queue_using_linked_list.cpp b/data_structures/circular_queue_using_linked_list.cpp similarity index 100% rename from data_structure/circular_queue_using_linked_list.cpp rename to data_structures/circular_queue_using_linked_list.cpp diff --git a/data_structure/cll/cll.cpp b/data_structures/cll/cll.cpp similarity index 100% rename from data_structure/cll/cll.cpp rename to data_structures/cll/cll.cpp diff --git a/data_structure/cll/cll.h b/data_structures/cll/cll.h similarity index 100% rename from data_structure/cll/cll.h rename to data_structures/cll/cll.h diff --git a/data_structure/cll/main_cll.cpp b/data_structures/cll/main_cll.cpp similarity index 100% rename from data_structure/cll/main_cll.cpp rename to data_structures/cll/main_cll.cpp diff --git a/data_structure/cll/makefile b/data_structures/cll/makefile similarity index 100% rename from data_structure/cll/makefile rename to data_structures/cll/makefile diff --git a/data_structure/disjoint_set.cpp b/data_structures/disjoint_set.cpp similarity index 100% rename from data_structure/disjoint_set.cpp rename to data_structures/disjoint_set.cpp diff --git a/data_structure/doubly_linked_list.cpp b/data_structures/doubly_linked_list.cpp similarity index 100% rename from data_structure/doubly_linked_list.cpp rename to data_structures/doubly_linked_list.cpp diff --git a/data_structure/linked_list.cpp b/data_structures/linked_list.cpp similarity index 100% rename from data_structure/linked_list.cpp rename to data_structures/linked_list.cpp diff --git a/data_structure/linkedlist_implentation_usingarray.cpp b/data_structures/linkedlist_implentation_usingarray.cpp similarity index 100% rename from data_structure/linkedlist_implentation_usingarray.cpp rename to data_structures/linkedlist_implentation_usingarray.cpp diff --git a/data_structure/list_array.cpp b/data_structures/list_array.cpp similarity index 100% rename from data_structure/list_array.cpp rename to data_structures/list_array.cpp diff --git a/data_structure/morrisinorder.cpp b/data_structures/morrisinorder.cpp similarity index 100% rename from data_structure/morrisinorder.cpp rename to data_structures/morrisinorder.cpp diff --git a/data_structure/queue/makefile b/data_structures/queue/makefile similarity index 100% rename from data_structure/queue/makefile rename to data_structures/queue/makefile diff --git a/data_structure/queue/queue.cpp b/data_structures/queue/queue.cpp similarity index 100% rename from data_structure/queue/queue.cpp rename to data_structures/queue/queue.cpp diff --git a/data_structure/queue/queue.h b/data_structures/queue/queue.h similarity index 100% rename from data_structure/queue/queue.h rename to data_structures/queue/queue.h diff --git a/data_structure/queue/test_queue.cpp b/data_structures/queue/test_queue.cpp similarity index 100% rename from data_structure/queue/test_queue.cpp rename to data_structures/queue/test_queue.cpp diff --git a/data_structure/queue_using_array.cpp b/data_structures/queue_using_array.cpp similarity index 100% rename from data_structure/queue_using_array.cpp rename to data_structures/queue_using_array.cpp diff --git a/data_structure/queue_using_array2.cpp b/data_structures/queue_using_array2.cpp similarity index 100% rename from data_structure/queue_using_array2.cpp rename to data_structures/queue_using_array2.cpp diff --git a/data_structure/queue_using_linked_list.cpp b/data_structures/queue_using_linked_list.cpp similarity index 100% rename from data_structure/queue_using_linked_list.cpp rename to data_structures/queue_using_linked_list.cpp diff --git a/data_structure/queue_using_linkedlist.cpp b/data_structures/queue_using_linkedlist.cpp similarity index 100% rename from data_structure/queue_using_linkedlist.cpp rename to data_structures/queue_using_linkedlist.cpp diff --git a/data_structure/stack_using_array.cpp b/data_structures/stack_using_array.cpp similarity index 100% rename from data_structure/stack_using_array.cpp rename to data_structures/stack_using_array.cpp diff --git a/data_structure/stack_using_linked_list.cpp b/data_structures/stack_using_linked_list.cpp similarity index 100% rename from data_structure/stack_using_linked_list.cpp rename to data_structures/stack_using_linked_list.cpp diff --git a/data_structure/stk/main.cpp b/data_structures/stk/main.cpp similarity index 100% rename from data_structure/stk/main.cpp rename to data_structures/stk/main.cpp diff --git a/data_structure/stk/makefile b/data_structures/stk/makefile similarity index 100% rename from data_structure/stk/makefile rename to data_structures/stk/makefile diff --git a/data_structure/stk/stack.cpp b/data_structures/stk/stack.cpp similarity index 100% rename from data_structure/stk/stack.cpp rename to data_structures/stk/stack.cpp diff --git a/data_structure/stk/stack.h b/data_structures/stk/stack.h similarity index 100% rename from data_structure/stk/stack.h rename to data_structures/stk/stack.h diff --git a/data_structure/stk/student.txt b/data_structures/stk/student.txt similarity index 100% rename from data_structure/stk/student.txt rename to data_structures/stk/student.txt diff --git a/data_structure/stk/test_stack.cpp b/data_structures/stk/test_stack.cpp similarity index 100% rename from data_structure/stk/test_stack.cpp rename to data_structures/stk/test_stack.cpp diff --git a/data_structure/tree.cpp b/data_structures/tree.cpp similarity index 100% rename from data_structure/tree.cpp rename to data_structures/tree.cpp diff --git a/data_structure/trie_tree.cpp b/data_structures/trie_tree.cpp similarity index 100% rename from data_structure/trie_tree.cpp rename to data_structures/trie_tree.cpp From 014bdc5ba8032575446655c9f2a9c6bf17987b86 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 4 Jun 2020 20:17:55 +0000 Subject: [PATCH 355/433] updating DIRECTORY.md --- DIRECTORY.md | 78 +++++++++++++++++++++++++++------------------------- 1 file changed, 41 insertions(+), 37 deletions(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index 12e22361db0..da4ad36ab3e 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -10,47 +10,41 @@ * [Rat Maze](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/rat_maze.cpp) * [Sudoku Solve](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/sudoku_solve.cpp) -## Computer Oriented Statistical Methods - * [Bisection Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/bisection_method.cpp) - * [False Position](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/false_position.cpp) - * [Gaussian Elimination](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/gaussian_elimination.cpp) - * [Newton Raphson Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/newton_raphson_method.cpp) - * [Ordinary Least Squares Regressor](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp) - * [Successive Approximation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/successive_approximation.cpp) - ## Data Structure - * [Avltree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/avltree.cpp) - * [Binary Search Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/binary_search_tree.cpp) - * [Binaryheap](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/binaryheap.cpp) - * [Circular Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/circular_queue_using_linked_list.cpp) + * [Trie Modern](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/trie_modern.cpp) + +## Data Structures + * [Avltree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/avltree.cpp) + * [Binary Search Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/binary_search_tree.cpp) + * [Binaryheap](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/binaryheap.cpp) + * [Circular Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/circular_queue_using_linked_list.cpp) * Cll - * [Cll](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/cll/cll.cpp) - * [Cll](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/cll/cll.h) - * [Main Cll](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/cll/main_cll.cpp) - * [Disjoint Set](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/disjoint_set.cpp) - * [Doubly Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/doubly_linked_list.cpp) - * [Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/linked_list.cpp) - * [Linkedlist Implentation Usingarray](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/linkedlist_implentation_usingarray.cpp) - * [List Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/list_array.cpp) - * [Morrisinorder](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/morrisinorder.cpp) + * [Cll](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/cll/cll.cpp) + * [Cll](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/cll/cll.h) + * [Main Cll](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/cll/main_cll.cpp) + * [Disjoint Set](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/disjoint_set.cpp) + * [Doubly Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/doubly_linked_list.cpp) + * [Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/linked_list.cpp) + * [Linkedlist Implentation Usingarray](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/linkedlist_implentation_usingarray.cpp) + * [List Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/list_array.cpp) + * [Morrisinorder](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/morrisinorder.cpp) * Queue - * [Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue/queue.cpp) - * [Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue/queue.h) - * [Test Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue/test_queue.cpp) - * [Queue Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue_using_array.cpp) - * [Queue Using Array2](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue_using_array2.cpp) - * [Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue_using_linked_list.cpp) - * [Queue Using Linkedlist](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue_using_linkedlist.cpp) - * [Stack Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stack_using_array.cpp) - * [Stack Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stack_using_linked_list.cpp) + * [Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/queue/queue.cpp) + * [Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/queue/queue.h) + * [Test Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/queue/test_queue.cpp) + * [Queue Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/queue_using_array.cpp) + * [Queue Using Array2](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/queue_using_array2.cpp) + * [Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/queue_using_linked_list.cpp) + * [Queue Using Linkedlist](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/queue_using_linkedlist.cpp) + * [Stack Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/stack_using_array.cpp) + * [Stack Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/stack_using_linked_list.cpp) * Stk - * [Main](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/main.cpp) - * [Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/stack.cpp) - * [Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/stack.h) - * [Test Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/test_stack.cpp) - * [Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/tree.cpp) - * [Trie Modern](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/trie_modern.cpp) - * [Trie Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/trie_tree.cpp) + * [Main](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/stk/main.cpp) + * [Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/stk/stack.cpp) + * [Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/stk/stack.h) + * [Test Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/stk/test_stack.cpp) + * [Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/tree.cpp) + * [Trie Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/trie_tree.cpp) ## Dynamic Programming * [0 1 Knapsack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/0_1_knapsack.cpp) @@ -108,6 +102,7 @@ ## Machine Learning * [Adaline Learning](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/machine_learning/adaline_learning.cpp) + * [Kohonen Som Trace](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/machine_learning/kohonen_som_trace.cpp) ## Math * [Binary Exponent](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/binary_exponent.cpp) @@ -135,6 +130,15 @@ * [Sqrt Double](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/sqrt_double.cpp) * [String Fibonacci](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/string_fibonacci.cpp) +## Numerical Methods + * [Bisection Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/bisection_method.cpp) + * [Durand Kerner Roots](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/durand_kerner_roots.cpp) + * [False Position](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/false_position.cpp) + * [Gaussian Elimination](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/gaussian_elimination.cpp) + * [Newton Raphson Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/newton_raphson_method.cpp) + * [Ordinary Least Squares Regressor](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/ordinary_least_squares_regressor.cpp) + * [Successive Approximation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/successive_approximation.cpp) + ## Operations On Datastructures * [Array Left Rotation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/array_left_rotation.cpp) * [Array Right Rotation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/array_right_rotation.cpp) From 7c8559947576fa614237a46cd240e1517377e8d3 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 16:20:19 -0400 Subject: [PATCH 356/433] fix ambiguous symbol `size` --- data_structures/stack_using_array.cpp | 37 +++++++++++++-------------- 1 file changed, 18 insertions(+), 19 deletions(-) diff --git a/data_structures/stack_using_array.cpp b/data_structures/stack_using_array.cpp index 5dd7ac98e82..36be9eb3919 100644 --- a/data_structures/stack_using_array.cpp +++ b/data_structures/stack_using_array.cpp @@ -1,12 +1,11 @@ #include -using namespace std; int *stack; -int top = 0, size; +int top = 0, stack_size; void push(int x) { - if (top == size) { - cout << "\nOverflow"; + if (top == stack_size) { + std::cout << "\nOverflow"; } else { stack[top++] = x; } @@ -14,34 +13,34 @@ void push(int x) { void pop() { if (top == 0) { - cout << "\nUnderflow"; + std::cout << "\nUnderflow"; } else { - cout << "\n" << stack[--top] << " deleted"; + std::cout << "\n" << stack[--top] << " deleted"; } } void show() { for (int i = 0; i < top; i++) { - cout << stack[i] << "\n"; + std::cout << stack[i] << "\n"; } } -void topmost() { cout << "\nTopmost element: " << stack[top - 1]; } +void topmost() { std::cout << "\nTopmost element: " << stack[top - 1]; } int main() { - cout << "\nEnter Size of stack : "; - cin >> size; - stack = new int[size]; + std::cout << "\nEnter stack_size of stack : "; + std::cin >> stack_size; + stack = new int[stack_size]; int ch, x; do { - cout << "\n1. Push"; - cout << "\n2. Pop"; - cout << "\n3. Print"; - cout << "\n4. Print topmost element:"; - cout << "\nEnter Your Choice : "; - cin >> ch; + std::cout << "\n1. Push"; + std::cout << "\n2. Pop"; + std::cout << "\n3. Print"; + std::cout << "\n4. Print topmost element:"; + std::cout << "\nEnter Your Choice : "; + std::cin >> ch; if (ch == 1) { - cout << "\nInsert : "; - cin >> x; + std::cout << "\nInsert : "; + std::cin >> x; push(x); } else if (ch == 2) { pop(); From 8960edaed13c8602ee00208e06a080db6aee1917 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 16:25:27 -0400 Subject: [PATCH 357/433] add data_structures to cmake --- CMakeLists.txt | 1 + data_structures/CMakeLists.txt | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) create mode 100644 data_structures/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index 430be40d6fb..6437b270fdd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -69,6 +69,7 @@ add_subdirectory(strings) add_subdirectory(sorting) add_subdirectory(geometry) add_subdirectory(probability) +add_subdirectory(data_structures) add_subdirectory(machine_learning) add_subdirectory(numerical_methods) diff --git a/data_structures/CMakeLists.txt b/data_structures/CMakeLists.txt new file mode 100644 index 00000000000..7840c834939 --- /dev/null +++ b/data_structures/CMakeLists.txt @@ -0,0 +1,18 @@ +# If necessary, use the RELATIVE flag, otherwise each source file may be listed +# with full pathname. RELATIVE may makes it easier to extract an executable name +# automatically. +file( GLOB APP_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp ) +# file( GLOB APP_SOURCES ${CMAKE_SOURCE_DIR}/*.c ) +# AUX_SOURCE_DIRECTORY(${CMAKE_CURRENT_SOURCE_DIR} APP_SOURCES) +foreach( testsourcefile ${APP_SOURCES} ) + # I used a simple string replace, to cut off .cpp. + string( REPLACE ".cpp" "" testname ${testsourcefile} ) + add_executable( ${testname} ${testsourcefile} ) + + set_target_properties(${testname} PROPERTIES LINKER_LANGUAGE CXX) + if(OpenMP_CXX_FOUND) + target_link_libraries(${testname} OpenMP::OpenMP_CXX) + endif() + install(TARGETS ${testname} DESTINATION "bin/data_structures") + +endforeach( testsourcefile ${APP_SOURCES} ) From 4d0c02389bd23526abdc001cbaace144d13b3c67 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 20:34:38 -0400 Subject: [PATCH 358/433] docs: enable tree view, add timestamp in footer, try clang assistaed parsing --- CMakeLists.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 430be40d6fb..f812d2c9aa2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -25,13 +25,16 @@ if(DOXYGEN_FOUND) set(DOXYGEN_GENERATE_MAN NO) set(DOXYGEN_USE_MATHJAX YES) set(DOXYGEN_GENERATE_HTML YES) + set(DOXYGEN_HTML_TIMESTAMP YES) set(DOXYGEN_EXTRACT_STATIC YES) set(DOXYGEN_INLINE_SOURCES YES) set(DOXYGEN_CREATE_SUBDIRS YES) set(DOXYGEN_EXTRACT_PRIVATE YES) set(DOCYGEN_GENERATE_TREEVIEW YES) set(DOXYGEN_STRIP_CODE_COMMENTS NO) + set(DOXYGEN_GENERATE_TREEVIEW YES) set(DOXYGEN_BUILTIN_STL_SUPPORT YES) + set(DOXYGEN_CLANG_ASSISTED_PARSING YES) set(DOXYGEN_FILE_PATTERNS *.cpp *.h *.hpp *.md) set(DOXYGEN_MATHJAX_EXTENSIONS TeX/AMSmath TeX/AMSsymbols) set(DOXYGEN_TAGFILES "doc/cppreference-doxygen-web.tag.xml=http://en.cppreference.com/w/") From 9b61ef94b768239ed045332bf32fc7d63486d531 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 21:33:08 -0400 Subject: [PATCH 359/433] doxygen - open links in external window --- CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 6437b270fdd..7195f7fa9f2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -31,6 +31,7 @@ if(DOXYGEN_FOUND) set(DOXYGEN_EXTRACT_PRIVATE YES) set(DOCYGEN_GENERATE_TREEVIEW YES) set(DOXYGEN_STRIP_CODE_COMMENTS NO) + set(DOXYGEN_EXT_LINKS_IN_WINDOW YES) set(DOXYGEN_BUILTIN_STL_SUPPORT YES) set(DOXYGEN_FILE_PATTERNS *.cpp *.h *.hpp *.md) set(DOXYGEN_MATHJAX_EXTENSIONS TeX/AMSmath TeX/AMSsymbols) From d0e0a07f16770180a26ae9e59505f30eac185c6a Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 21:33:33 -0400 Subject: [PATCH 360/433] remove invalid parameter from function docs --- machine_learning/kohonen_som_trace.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/machine_learning/kohonen_som_trace.cpp b/machine_learning/kohonen_som_trace.cpp index f2da7d1831f..4929eaef3af 100644 --- a/machine_learning/kohonen_som_trace.cpp +++ b/machine_learning/kohonen_som_trace.cpp @@ -130,7 +130,6 @@ void update_weights(const std::valarray &x, * * \param[in] X data set * \param[in,out] W weights matrix - * \param[in] D temporary vector to store distances * \param[in] alpha_min terminal value of alpha */ void kohonen_som_tracer(const std::vector> &X, From 82a6ea06e670f601072f5fd62d4cec14d3727ad3 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 21:34:05 -0400 Subject: [PATCH 361/433] use HTML5 img tag to resize images --- numerical_methods/durand_kerner_roots.cpp | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/numerical_methods/durand_kerner_roots.cpp b/numerical_methods/durand_kerner_roots.cpp index 70288d2c586..5d9baa9324c 100644 --- a/numerical_methods/durand_kerner_roots.cpp +++ b/numerical_methods/durand_kerner_roots.cpp @@ -18,11 +18,14 @@ * ``` * Sample implementation results to compute approximate roots of the equation * \f$x^4-1=0\f$:\n - * ![Error - * evolution](https://raw.githubusercontent.com/kvedala/C-Plus-Plus/docs/images/numerical_methods/durand_kerner_error.svg) - * - * ![Roots - * evolution](https://raw.githubusercontent.com/kvedala/C-Plus-Plus/docs/images/numerical_methods/durand_kerner_roots.svg) + * Error evolution during root approximations computed every
+ * iteration. Roots evolution - shows the initial approximation of the
+ * roots and their convergence to a final approximation along with the iterative
+ * approximations */ #include @@ -52,7 +55,7 @@ std::complex poly_function(const std::valarray &coeffs, int n; // #ifdef _OPENMP - // #pragma omp parallel for reduction(+ : real, imag) + // #pragma omp target teams distribute reduction(+ : real, imag) // #endif for (n = 0; n < coeffs.size(); n++) { std::complex tmp = @@ -132,7 +135,6 @@ std::pair durand_kerner_algo( bool break_loop = false; while (!check_termination(tol_condition) && iter < INT16_MAX && !break_loop) { - std::complex delta = 0; tol_condition = 0; iter++; break_loop = false; From 6635c0a1af46d506aa7cfbff0af6f4bfd4e7b2b7 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 22:50:58 -0400 Subject: [PATCH 362/433] move file to proper folder --- {data_structure => data_structures}/trie_modern.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {data_structure => data_structures}/trie_modern.cpp (100%) diff --git a/data_structure/trie_modern.cpp b/data_structures/trie_modern.cpp similarity index 100% rename from data_structure/trie_modern.cpp rename to data_structures/trie_modern.cpp From aacaf9828c61bb0246fe0933ab8ade82128b8346 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 23:15:43 -0400 Subject: [PATCH 363/433] fix documentations and cpplint --- data_structures/avltree.cpp | 53 +++++---- data_structures/binary_search_tree.cpp | 83 +++++++------- data_structures/binaryheap.cpp | 78 ++++++------- .../circular_queue_using_linked_list.cpp | 6 +- .../linkedlist_implentation_usingarray.cpp | 104 ++++++++++-------- data_structures/trie_modern.cpp | 9 +- 6 files changed, 174 insertions(+), 159 deletions(-) diff --git a/data_structures/avltree.cpp b/data_structures/avltree.cpp index f38133c050b..836f0f6677c 100644 --- a/data_structures/avltree.cpp +++ b/data_structures/avltree.cpp @@ -1,8 +1,15 @@ +/** + * \file + * \brief A simple tree implementation using nodes + * + * \todo update code to use C++ STL library features and OO structure + * \warning This program is a poor implementation and does not utilize any of + * the C++ STL features. + */ +#include #include #include -using namespace std; - typedef struct node { int data; int height; @@ -10,10 +17,7 @@ typedef struct node { struct node *right; } node; -int max(int a, int b) { return a > b ? a : b; } - -// Returns a new Node - +/** Create and return a new Node */ node *createNode(int data) { node *nn = new node(); nn->data = data; @@ -23,20 +27,17 @@ node *createNode(int data) { return nn; } -// Returns height of tree - +/** Returns height of tree */ int height(node *root) { if (root == NULL) return 0; - return 1 + max(height(root->left), height(root->right)); + return 1 + std::max(height(root->left), height(root->right)); } -// Returns difference between height of left and right subtree - +/** Returns difference between height of left and right subtree */ int getBalance(node *root) { return height(root->left) - height(root->right); } -// Returns Node after Right Rotation - +/** Returns Node after Right Rotation */ node *rightRotate(node *root) { node *t = root->left; node *u = t->right; @@ -45,8 +46,7 @@ node *rightRotate(node *root) { return t; } -// Returns Node after Left Rotation - +/** Returns Node after Left Rotation */ node *leftRotate(node *root) { node *t = root->right; node *u = t->left; @@ -55,16 +55,14 @@ node *leftRotate(node *root) { return t; } -// Returns node with minimum value in the tree - +/** Returns node with minimum value in the tree */ node *minValue(node *root) { if (root->left == NULL) return root; return minValue(root->left); } -// Balanced Insertion - +/** Balanced Insertion */ node *insert(node *root, int item) { node *nn = createNode(item); if (root == NULL) @@ -86,8 +84,7 @@ node *insert(node *root, int item) { return root; } -// Balanced Deletion - +/** Balanced Deletion */ node *deleteNode(node *root, int key) { if (root == NULL) return root; @@ -118,14 +115,13 @@ node *deleteNode(node *root, int key) { return root; } -// LevelOrder (Breadth First Search) - +/** LevelOrder (Breadth First Search) */ void levelOrder(node *root) { - queue q; + std::queue q; q.push(root); while (!q.empty()) { root = q.front(); - cout << root->data << " "; + std::cout << root->data << " "; q.pop(); if (root->left) q.push(root->left); @@ -134,18 +130,19 @@ void levelOrder(node *root) { } } +/** Main function */ int main() { // Testing AVL Tree node *root = NULL; int i; for (i = 1; i <= 7; i++) root = insert(root, i); - cout << "LevelOrder: "; + std::cout << "LevelOrder: "; levelOrder(root); root = deleteNode(root, 1); // Deleting key with value 1 - cout << "\nLevelOrder: "; + std::cout << "\nLevelOrder: "; levelOrder(root); root = deleteNode(root, 4); // Deletin key with value 4 - cout << "\nLevelOrder: "; + std::cout << "\nLevelOrder: "; levelOrder(root); return 0; } diff --git a/data_structures/binary_search_tree.cpp b/data_structures/binary_search_tree.cpp index c3a74f385e1..ebcf2754e47 100644 --- a/data_structures/binary_search_tree.cpp +++ b/data_structures/binary_search_tree.cpp @@ -1,5 +1,12 @@ +/** + * \file + * \brief A simple tree implementation using structured nodes + * + * \todo update code to use C++ STL library features and OO structure + * \warning This program is a poor implementation - C style - and does not + * utilize any of the C++ STL features. + */ #include -using namespace std; struct node { int val; @@ -84,7 +91,7 @@ void Remove(node *p, node *n, int x) { void BFT(node *n) { if (n != NULL) { - cout << n->val << " "; + std::cout << n->val << " "; enqueue(n->left); enqueue(n->right); BFT(dequeue()); @@ -93,7 +100,7 @@ void BFT(node *n) { void Pre(node *n) { if (n != NULL) { - cout << n->val << " "; + std::cout << n->val << " "; Pre(n->left); Pre(n->right); } @@ -102,7 +109,7 @@ void Pre(node *n) { void In(node *n) { if (n != NULL) { In(n->left); - cout << n->val << " "; + std::cout << n->val << " "; In(n->right); } } @@ -111,7 +118,7 @@ void Post(node *n) { if (n != NULL) { Post(n->left); Post(n->right); - cout << n->val << " "; + std::cout << n->val << " "; } } @@ -121,45 +128,47 @@ int main() { int value; int ch; node *root = new node; - cout << "\nEnter the value of root node :"; - cin >> value; + std::cout << "\nEnter the value of root node :"; + std::cin >> value; root->val = value; root->left = NULL; root->right = NULL; do { - cout << "\n1. Insert"; - cout << "\n2. Delete"; - cout << "\n3. Breadth First"; - cout << "\n4. Preorder Depth First"; - cout << "\n5. Inorder Depth First"; - cout << "\n6. Postorder Depth First"; + std::cout << "\n1. Insert" + << "\n2. Delete" + << "\n3. Breadth First" + << "\n4. Preorder Depth First" + << "\n5. Inorder Depth First" + << "\n6. Postorder Depth First"; - cout << "\nEnter Your Choice : "; - cin >> ch; + std::cout << "\nEnter Your Choice : "; + std::cin >> ch; int x; switch (ch) { - case 1: - cout << "\nEnter the value to be Inserted : "; - cin >> x; - Insert(root, x); - break; - case 2: - cout << "\nEnter the value to be Deleted : "; - cin >> x; - Remove(root, root, x); - break; - case 3: - BFT(root); - break; - case 4: - Pre(root); - break; - case 5: - In(root); - break; - case 6: - Post(root); - break; + case 1: + std::cout << "\nEnter the value to be Inserted : "; + std::cin >> x; + Insert(root, x); + break; + case 2: + std::cout << "\nEnter the value to be Deleted : "; + std::cin >> x; + Remove(root, root, x); + break; + case 3: + BFT(root); + break; + case 4: + Pre(root); + break; + case 5: + In(root); + break; + case 6: + Post(root); + break; } } while (ch != 0); + + return 0; } diff --git a/data_structures/binaryheap.cpp b/data_structures/binaryheap.cpp index a31d8767457..72e56e91ad3 100644 --- a/data_structures/binaryheap.cpp +++ b/data_structures/binaryheap.cpp @@ -1,48 +1,52 @@ -// A C++ program to demonstrate common Binary Heap Operations +/** + * \file + * \brief A C++ program to demonstrate common Binary Heap Operations + */ #include #include -using namespace std; +#include -// Prototype of a utility function to swap two integers -void swap(int *x, int *y); - -// A class for Min Heap +/** A class for Min Heap */ class MinHeap { - int *harr; // pointer to array of elements in heap - int capacity; // maximum possible size of min heap - int heap_size; // Current number of elements in min heap + int *harr; ///< pointer to array of elements in heap + int capacity; ///< maximum possible size of min heap + int heap_size; ///< Current number of elements in min heap + public: - // Constructor + /** Constructor + * \param[in] capacity initial heap capacity + */ MinHeap(int capacity); - // to heapify a subtree with the root at given index + /** to heapify a subtree with the root at given index + */ void MinHeapify(int); int parent(int i) { return (i - 1) / 2; } - // to get index of left child of node at index i + /** to get index of left child of node at index i */ int left(int i) { return (2 * i + 1); } - // to get index of right child of node at index i + /** to get index of right child of node at index i */ int right(int i) { return (2 * i + 2); } - // to extract the root which is the minimum element + /** to extract the root which is the minimum element */ int extractMin(); - // Decreases key value of key at index i to new_val + /** Decreases key value of key at index i to new_val */ void decreaseKey(int i, int new_val); - // Returns the minimum key (key at root) from min heap + /** Returns the minimum key (key at root) from min heap */ int getMin() { return harr[0]; } - // Deletes a key stored at index i + /** Deletes a key stored at index i */ void deleteKey(int i); - // Inserts a new key 'k' + /** Inserts a new key 'k' */ void insertKey(int k); }; -// Constructor: Builds a heap from a given array a[] of given size +/** Constructor: Builds a heap from a given array a[] of given size */ MinHeap::MinHeap(int cap) { heap_size = 0; capacity = cap; @@ -52,7 +56,7 @@ MinHeap::MinHeap(int cap) { // Inserts a new key 'k' void MinHeap::insertKey(int k) { if (heap_size == capacity) { - cout << "\nOverflow: Could not insertKey\n"; + std::cout << "\nOverflow: Could not insertKey\n"; return; } @@ -63,17 +67,18 @@ void MinHeap::insertKey(int k) { // Fix the min heap property if it is violated while (i != 0 && harr[parent(i)] > harr[i]) { - swap(&harr[i], &harr[parent(i)]); + std::swap(harr[i], harr[parent(i)]); i = parent(i); } } -// Decreases value of key at index 'i' to new_val. It is assumed that -// new_val is smaller than harr[i]. +/** Decreases value of key at index 'i' to new_val. It is assumed that new_val + * is smaller than harr[i]. + */ void MinHeap::decreaseKey(int i, int new_val) { harr[i] = new_val; while (i != 0 && harr[parent(i)] > harr[i]) { - swap(&harr[i], &harr[parent(i)]); + std::swap(harr[i], harr[parent(i)]); i = parent(i); } } @@ -96,15 +101,17 @@ int MinHeap::extractMin() { return root; } -// This function deletes key at index i. It first reduced value to minus -// infinite, then calls extractMin() +/** This function deletes key at index i. It first reduced value to minus + * infinite, then calls extractMin() + */ void MinHeap::deleteKey(int i) { decreaseKey(i, INT_MIN); extractMin(); } -// A recursive method to heapify a subtree with the root at given index -// This method assumes that the subtrees are already heapified +/** A recursive method to heapify a subtree with the root at given index + * This method assumes that the subtrees are already heapified + */ void MinHeap::MinHeapify(int i) { int l = left(i); int r = right(i); @@ -114,18 +121,11 @@ void MinHeap::MinHeapify(int i) { if (r < heap_size && harr[r] < harr[smallest]) smallest = r; if (smallest != i) { - swap(&harr[i], &harr[smallest]); + std::swap(harr[i], harr[smallest]); MinHeapify(smallest); } } -// A utility function to swap two elements -void swap(int *x, int *y) { - int temp = *x; - *x = *y; - *y = temp; -} - // Driver program to test above functions int main() { MinHeap h(11); @@ -136,9 +136,9 @@ int main() { h.insertKey(5); h.insertKey(4); h.insertKey(45); - cout << h.extractMin() << " "; - cout << h.getMin() << " "; + std::cout << h.extractMin() << " "; + std::cout << h.getMin() << " "; h.decreaseKey(2, 1); - cout << h.getMin(); + std::cout << h.getMin(); return 0; } diff --git a/data_structures/circular_queue_using_linked_list.cpp b/data_structures/circular_queue_using_linked_list.cpp index b6a471044a9..5d6484ce396 100644 --- a/data_structures/circular_queue_using_linked_list.cpp +++ b/data_structures/circular_queue_using_linked_list.cpp @@ -1,5 +1,4 @@ #include -using namespace std; struct node { int data; @@ -48,11 +47,10 @@ class Queue { node *ptr; ptr = front; do { - cout << ptr->data << " "; + std::cout << ptr->data << " "; ptr = ptr->next; } while (ptr != rear->next); - cout << front->data; - cout << endl; + std::cout << front->data << std::endl; } }; int main(void) { diff --git a/data_structures/linkedlist_implentation_usingarray.cpp b/data_structures/linkedlist_implentation_usingarray.cpp index a078bef1692..837d9f65b43 100644 --- a/data_structures/linkedlist_implentation_usingarray.cpp +++ b/data_structures/linkedlist_implentation_usingarray.cpp @@ -1,17 +1,23 @@ -/* The difference between the pointer implementation of linked list and array - implementation of linked list: - 1. The NULL is represented by -1; - 2. Limited size. (in the following case it is 100 nodes at max). But we can - reuse the nodes that are to be deleted by again linking it bacj to the list. -*/ +/** + * \file + * \brief Linked list implementation using Arrays + * + * The difference between the pointer implementation of linked list and array + * implementation of linked list: + * 1. The NULL is represented by -1; + * 2. Limited size. (in the following case it is 100 nodes at max). But we can + * reuse the nodes that are to be deleted by again linking it bacj to the list. + */ #include -using namespace std; + struct Node { int data; int next; }; -Node AvailArray[100]; // array that will act as nodes of a linked list. + +Node AvailArray[100]; ///< array that will act as nodes of a linked list. + int head = -1; int avail = 0; void initialise_list() { @@ -21,26 +27,27 @@ void initialise_list() { AvailArray[99].next = -1; // indicating the end of the linked list. } -int getnode() // This will return the index of the first free node present in - // the avail list -{ +/** This will return the index of the first free node present in the avail list + */ +int getnode() { int NodeIndexToBeReturned = avail; avail = AvailArray[avail].next; return NodeIndexToBeReturned; } -void freeNode( - int nodeToBeDeleted) // This function when called will delete the node with - // the index presented as an argument, and will put - // back that node into the array. -{ +/** This function when called will delete the node with + * the index presented as an argument, and will put + * back that node into the array. + */ +void freeNode(int nodeToBeDeleted) { AvailArray[nodeToBeDeleted].next = avail; avail = nodeToBeDeleted; } -void insertAtTheBeginning(int data) // The function will insert the given data - // into the front of the linked list. -{ +/** The function will insert the given data + * into the front of the linked list. + */ +void insertAtTheBeginning(int data) { int newNode = getnode(); AvailArray[newNode].data = data; AvailArray[newNode].next = head; @@ -62,43 +69,46 @@ void insertAtTheEnd(int data) { void display() { int temp = head; while (temp != -1) { - cout << AvailArray[temp].data << "->"; + std::cout << AvailArray[temp].data << "->"; temp = AvailArray[temp].next; } - cout << "-1" << endl; - ; + std::cout << "-1" << std::endl; } +/** Main function */ int main() { initialise_list(); int x, y, z; for (;;) { - cout << "1. Insert At The Beginning" << endl; - cout << "2. Insert At The End" << endl; - cout << "3. Display" << endl; - cout << "4.Exit" << endl; - cout << "Enter Your choice" << endl; - cin >> z; + std::cout << "1. Insert At The Beginning" << std::endl; + std::cout << "2. Insert At The End" << std::endl; + std::cout << "3. Display" << std::endl; + std::cout << "4.Exit" << std::endl; + std::cout << "Enter Your choice" << std::endl; + std::cin >> z; switch (z) { - case 1: - cout << "Enter the number you want to enter" << endl; - cin >> x; - insertAtTheBeginning(x); - break; - case 2: - cout << "Enter the number you want to enter" << endl; - cin >> y; - insertAtTheEnd(y); - break; - case 3: - cout << "The linked list contains the following element in order" - << endl; - display(); - break; - case 4: - exit(0); - default: - cout << "The entered choice is not correct" << endl; + case 1: + std::cout << "Enter the number you want to enter" << std::endl; + std::cin >> x; + insertAtTheBeginning(x); + break; + case 2: + std::cout << "Enter the number you want to enter" << std::endl; + std::cin >> y; + insertAtTheEnd(y); + break; + case 3: + std::cout + << "The linked list contains the following element in order" + << std::endl; + display(); + break; + case 4: + return 0; + default: + std::cout << "The entered choice is not correct" << std::endl; } } + + return 0; } diff --git a/data_structures/trie_modern.cpp b/data_structures/trie_modern.cpp index 218c90b68b5..c2eba30e053 100644 --- a/data_structures/trie_modern.cpp +++ b/data_structures/trie_modern.cpp @@ -1,8 +1,8 @@ /** - * Copyright 2020 @author Anmol3299 * @file * - * A basic implementation of trie class to store only lower-case strings. + * Copyright 2020 @author Anmol3299 + * \brief A basic implementation of trie class to store only lower-case strings. */ #include // for io operations #include // for std::shared_ptr<> @@ -35,7 +35,8 @@ class Trie { * Function to check if a node has some children which can form words. * @param node whose character array of pointers need to be checked for * children. - * @return if a child is found, it returns @ true, else it returns @ false. + * @return `true` if a child is found + * @return `false` if a child is not found */ inline static bool hasChildren(std::shared_ptr node) { for (size_t i = 0; i < ALPHABETS; i++) { @@ -98,7 +99,7 @@ class Trie { } public: - // constructor to initialise the root of the trie. + /// constructor to initialise the root of the trie. Trie() : m_root(std::make_shared()) {} /** From 0a99574e8612397875c61add736c7d83f1e6e99b Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 5 Jun 2020 03:16:32 +0000 Subject: [PATCH 364/433] formatting source-code for aacaf9828c61bb0246fe0933ab8ade82128b8346 --- data_structures/binary_search_tree.cpp | 44 +++++++++---------- .../linkedlist_implentation_usingarray.cpp | 40 ++++++++--------- 2 files changed, 42 insertions(+), 42 deletions(-) diff --git a/data_structures/binary_search_tree.cpp b/data_structures/binary_search_tree.cpp index ebcf2754e47..947bb53d843 100644 --- a/data_structures/binary_search_tree.cpp +++ b/data_structures/binary_search_tree.cpp @@ -145,28 +145,28 @@ int main() { std::cin >> ch; int x; switch (ch) { - case 1: - std::cout << "\nEnter the value to be Inserted : "; - std::cin >> x; - Insert(root, x); - break; - case 2: - std::cout << "\nEnter the value to be Deleted : "; - std::cin >> x; - Remove(root, root, x); - break; - case 3: - BFT(root); - break; - case 4: - Pre(root); - break; - case 5: - In(root); - break; - case 6: - Post(root); - break; + case 1: + std::cout << "\nEnter the value to be Inserted : "; + std::cin >> x; + Insert(root, x); + break; + case 2: + std::cout << "\nEnter the value to be Deleted : "; + std::cin >> x; + Remove(root, root, x); + break; + case 3: + BFT(root); + break; + case 4: + Pre(root); + break; + case 5: + In(root); + break; + case 6: + Post(root); + break; } } while (ch != 0); diff --git a/data_structures/linkedlist_implentation_usingarray.cpp b/data_structures/linkedlist_implentation_usingarray.cpp index 837d9f65b43..75d400d72ea 100644 --- a/data_structures/linkedlist_implentation_usingarray.cpp +++ b/data_structures/linkedlist_implentation_usingarray.cpp @@ -87,26 +87,26 @@ int main() { std::cout << "Enter Your choice" << std::endl; std::cin >> z; switch (z) { - case 1: - std::cout << "Enter the number you want to enter" << std::endl; - std::cin >> x; - insertAtTheBeginning(x); - break; - case 2: - std::cout << "Enter the number you want to enter" << std::endl; - std::cin >> y; - insertAtTheEnd(y); - break; - case 3: - std::cout - << "The linked list contains the following element in order" - << std::endl; - display(); - break; - case 4: - return 0; - default: - std::cout << "The entered choice is not correct" << std::endl; + case 1: + std::cout << "Enter the number you want to enter" << std::endl; + std::cin >> x; + insertAtTheBeginning(x); + break; + case 2: + std::cout << "Enter the number you want to enter" << std::endl; + std::cin >> y; + insertAtTheEnd(y); + break; + case 3: + std::cout + << "The linked list contains the following element in order" + << std::endl; + display(); + break; + case 4: + return 0; + default: + std::cout << "The entered choice is not correct" << std::endl; } } From ee7390525fadd148c148db825940f31fd378e59e Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 5 Jun 2020 03:16:55 +0000 Subject: [PATCH 365/433] updating DIRECTORY.md --- DIRECTORY.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index da4ad36ab3e..bdfa2c95135 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -10,9 +10,6 @@ * [Rat Maze](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/rat_maze.cpp) * [Sudoku Solve](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/sudoku_solve.cpp) -## Data Structure - * [Trie Modern](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/trie_modern.cpp) - ## Data Structures * [Avltree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/avltree.cpp) * [Binary Search Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/binary_search_tree.cpp) @@ -44,6 +41,7 @@ * [Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/stk/stack.h) * [Test Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/stk/test_stack.cpp) * [Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/tree.cpp) + * [Trie Modern](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/trie_modern.cpp) * [Trie Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/trie_tree.cpp) ## Dynamic Programming From 281a0afa57b7cb6f238a8a56788da32673a11156 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 23:20:40 -0400 Subject: [PATCH 366/433] cpplint: add braces for multiple statement if --- numerical_methods/durand_kerner_roots.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/numerical_methods/durand_kerner_roots.cpp b/numerical_methods/durand_kerner_roots.cpp index 5d9baa9324c..80464412a6c 100644 --- a/numerical_methods/durand_kerner_roots.cpp +++ b/numerical_methods/durand_kerner_roots.cpp @@ -177,9 +177,10 @@ std::pair durand_kerner_algo( if (break_loop) break; - if (log_file.is_open()) + if (log_file.is_open()) { for (n = 0; n < roots->size(); n++) log_file << complex_str((*roots)[n]) << ","; + } #if defined(DEBUG) || !defined(NDEBUG) if (iter % 500 == 0) { From 8f05353bd54f2f44a7bb5bbabe3fb21da497e031 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 4 Jun 2020 23:24:58 -0400 Subject: [PATCH 367/433] add explicit link to badges --- README.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index df39ee55415..8dd6a92df30 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,10 @@ # The Algorithms - C++ # {#mainpage} -[![contributions welcome](https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square)](https://github.com/kvedala/C-Plus-Plus/blob/master/CONTRIBUTION.md)  +![contributions welcome](https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square)] ![GitHub repo size](https://img.shields.io/github/repo-size/kvedala/C-Plus-Plus?color=red&style=flat-square) ![GitHub closed pull requests](https://img.shields.io/github/issues-pr-closed/kvedala/C-Plus-Plus?color=green&style=flat-square) -![Doxygen CI](https://github.com/kvedala/C-Plus-Plus/workflows/Doxygen%20CI/badge.svg) -![cpplint](https://github.com/kvedala/C-Plus-Plus/workflows/cpplint_modified_files/badge.svg) -![C/C++ CI](https://github.com/kvedala/C-Plus-Plus/workflows/C/C++%20CI/badge.svg) +![Doxygen CI](https://github.com/kvedala/C-Plus-Plus/workflows/Doxygen%20CI/badge.svg) +![Awesome CI](https://github.com/kvedala/C-Plus-Plus/workflows/Awesome%20CI%20Workflow/badge.svg) [Online Documentation](https://kvedala.github.io/C-Plus-Plus). @@ -15,4 +14,4 @@ Click on [Files menu](https://kvedala.github.io/C-Plus-Plus/files.html) to see t The implementations are for learning purpose. They may be less efficient than the implementation in the standard library. ### Contribute Guidelines -Read our [Contribution Guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTION.md) before you contribute. +Read our [Contribution Guidelines](https://github.com/kvedala/C-Plus-Plus/blob/master/CONTRIBUTION.md) before you contribute. From 70bb8c81be4c482fd1d7a62a7aae2250bc12e735 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 5 Jun 2020 09:11:26 -0400 Subject: [PATCH 368/433] remove duplicate line Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- CMakeLists.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 25e8dc4a4d6..957be35f588 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -30,7 +30,6 @@ if(DOXYGEN_FOUND) set(DOXYGEN_INLINE_SOURCES YES) set(DOXYGEN_CREATE_SUBDIRS YES) set(DOXYGEN_EXTRACT_PRIVATE YES) - set(DOCYGEN_GENERATE_TREEVIEW YES) set(DOXYGEN_GENERATE_TREEVIEW YES) set(DOXYGEN_STRIP_CODE_COMMENTS NO) set(DOXYGEN_EXT_LINKS_IN_WINDOW YES) From 9511fe3dbf37d366bf34b45129344394a51f5af4 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 5 Jun 2020 20:22:49 -0400 Subject: [PATCH 369/433] remove namespace indentation --- .vscode/settings.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 0a257500b52..2487eb6d313 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -64,8 +64,8 @@ "valarray": "cpp", "algorithm": "cpp" }, - "C_Cpp.clang_format_style": "{ BasedOnStyle: Google, UseTab: Never, IndentWidth: 4, TabWidth: 4, AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: true, ColumnLimit: 80, AccessModifierOffset: -3, NamespaceIndentation: All }", + "C_Cpp.clang_format_style": "{ BasedOnStyle: Google, UseTab: Never, IndentWidth: 4, TabWidth: 4, AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: true, ColumnLimit: 80, AccessModifierOffset: -3 }", "editor.formatOnSave": true, "editor.formatOnType": true, "editor.formatOnPaste": true -} +} \ No newline at end of file From 172cd7be7dc537e69bfebb2c3c153730512bcce8 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 5 Jun 2020 20:26:16 -0400 Subject: [PATCH 370/433] remove file associations in settings --- .vscode/settings.json | 65 ------------------------------------------- 1 file changed, 65 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 2487eb6d313..6d75a13905d 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,69 +1,4 @@ { - "files.associations": { - "array": "cpp", - "atomic": "cpp", - "*.tcc": "cpp", - "bitset": "cpp", - "cctype": "cpp", - "cfenv": "cpp", - "chrono": "cpp", - "cinttypes": "cpp", - "clocale": "cpp", - "cmath": "cpp", - "codecvt": "cpp", - "complex": "cpp", - "condition_variable": "cpp", - "csetjmp": "cpp", - "csignal": "cpp", - "cstdarg": "cpp", - "cstddef": "cpp", - "cstdint": "cpp", - "cstdio": "cpp", - "cstdlib": "cpp", - "cstring": "cpp", - "ctime": "cpp", - "cuchar": "cpp", - "cwchar": "cpp", - "cwctype": "cpp", - "deque": "cpp", - "forward_list": "cpp", - "list": "cpp", - "unordered_map": "cpp", - "unordered_set": "cpp", - "vector": "cpp", - "exception": "cpp", - "fstream": "cpp", - "functional": "cpp", - "future": "cpp", - "initializer_list": "cpp", - "iomanip": "cpp", - "iosfwd": "cpp", - "iostream": "cpp", - "istream": "cpp", - "limits": "cpp", - "memory": "cpp", - "mutex": "cpp", - "new": "cpp", - "numeric": "cpp", - "optional": "cpp", - "ostream": "cpp", - "ratio": "cpp", - "scoped_allocator": "cpp", - "shared_mutex": "cpp", - "sstream": "cpp", - "stdexcept": "cpp", - "streambuf": "cpp", - "string_view": "cpp", - "system_error": "cpp", - "thread": "cpp", - "type_traits": "cpp", - "tuple": "cpp", - "typeindex": "cpp", - "typeinfo": "cpp", - "utility": "cpp", - "valarray": "cpp", - "algorithm": "cpp" - }, "C_Cpp.clang_format_style": "{ BasedOnStyle: Google, UseTab: Never, IndentWidth: 4, TabWidth: 4, AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: true, ColumnLimit: 80, AccessModifierOffset: -3 }", "editor.formatOnSave": true, "editor.formatOnType": true, From 43362d3b501168a8b6e356e0525c84cdad57e14f Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 5 Jun 2020 20:26:34 -0400 Subject: [PATCH 371/433] add author name --- machine_learning/adaline_learning.cpp | 2 ++ machine_learning/kohonen_som_trace.cpp | 2 ++ math/fibonacci_fast.cpp | 1 + math/fibonacci_large.cpp | 1 + math/large_factorial.cpp | 1 + math/large_number.h | 1 + math/realtime_stats.cpp | 1 + math/sqrt_double.cpp | 4 ++-- numerical_methods/durand_kerner_roots.cpp | 1 + numerical_methods/newton_raphson_method.cpp | 4 +++- numerical_methods/ordinary_least_squares_regressor.cpp | 1 + sorting/shell_sort2.cpp | 1 + 12 files changed, 17 insertions(+), 3 deletions(-) diff --git a/machine_learning/adaline_learning.cpp b/machine_learning/adaline_learning.cpp index 077b9408e57..eafeca826d3 100644 --- a/machine_learning/adaline_learning.cpp +++ b/machine_learning/adaline_learning.cpp @@ -3,6 +3,8 @@ * \brief [Adaptive Linear Neuron * (ADALINE)](https://en.wikipedia.org/wiki/ADALINE) implementation * + * \author [Krishna Vedala](https://github.com/kvedala) + * * diff --git a/machine_learning/kohonen_som_trace.cpp b/machine_learning/kohonen_som_trace.cpp index 4929eaef3af..31e9421bf92 100644 --- a/machine_learning/kohonen_som_trace.cpp +++ b/machine_learning/kohonen_som_trace.cpp @@ -8,6 +8,8 @@ * follows the given data points. This this creates a chain of nodes that * resembles the given input shape. * + * \author [Krishna Vedala](https://github.com/kvedala) + * * \note This C++ version of the program is considerable slower than its [C * counterpart](https://github.com/kvedala/C/blob/master/machine_learning/kohonen_som_trace.c) * \note The compiled code is much slower when compiled with MS Visual C++ 2019 diff --git a/math/fibonacci_fast.cpp b/math/fibonacci_fast.cpp index 08cced35105..8fdb20058aa 100644 --- a/math/fibonacci_fast.cpp +++ b/math/fibonacci_fast.cpp @@ -11,6 +11,7 @@ * found if we have already found n/2th or (n+1)/2th fibonacci It is a property * of fibonacci similar to matrix exponentiation. * + * \author [Krishna Vedala](https://github.com/kvedala) * @see fibonacci_large.cpp, fibonacci.cpp, string_fibonacci.cpp */ diff --git a/math/fibonacci_large.cpp b/math/fibonacci_large.cpp index d9dbff79968..e4f4e5eaf1b 100644 --- a/math/fibonacci_large.cpp +++ b/math/fibonacci_large.cpp @@ -7,6 +7,7 @@ * Took 0.608246 seconds to compute 50,000^th Fibonacci * number that contains 10450 digits! * + * \author [Krishna Vedala](https://github.com/kvedala) * @see fibonacci.cpp, fibonacci_fast.cpp, string_fibonacci.cpp */ diff --git a/math/large_factorial.cpp b/math/large_factorial.cpp index 1027f41abf8..20c677cdcc4 100644 --- a/math/large_factorial.cpp +++ b/math/large_factorial.cpp @@ -2,6 +2,7 @@ * @file * @brief Compute factorial of any arbitratily large number/ * + * \author [Krishna Vedala](https://github.com/kvedala) * @see factorial.cpp */ #include diff --git a/math/large_number.h b/math/large_number.h index c1a3665e4d1..bffb764d036 100644 --- a/math/large_number.h +++ b/math/large_number.h @@ -2,6 +2,7 @@ * @file * @brief Library to perform arithmatic operations on arbitrarily large * numbers. + * \author [Krishna Vedala](https://github.com/kvedala) */ #ifndef MATH_LARGE_NUMBER_H_ diff --git a/math/realtime_stats.cpp b/math/realtime_stats.cpp index 26b92362513..5f353ac4db0 100644 --- a/math/realtime_stats.cpp +++ b/math/realtime_stats.cpp @@ -5,6 +5,7 @@ * This algorithm is really beneficial to compute statistics on data read in * realtime. For example, devices reading biometrics data. The algorithm is * simple enough to be easily implemented in an embedded system. + * \author [Krishna Vedala](https://github.com/kvedala) */ #include #include diff --git a/math/sqrt_double.cpp b/math/sqrt_double.cpp index 1521b500a19..c4beec9d8c6 100644 --- a/math/sqrt_double.cpp +++ b/math/sqrt_double.cpp @@ -1,7 +1,7 @@ /** * @file - * @brief Calculate the square root of any positive number in \f$O(\log N)\f$ - * time, with precision fixed using [bisection + * @brief Calculate the square root of any positive real number in \f$O(\log + * N)\f$ time, with precision fixed using [bisection * method](https://en.wikipedia.org/wiki/Bisection_method) of root-finding. * * @see Can be implemented using faster and better algorithms like diff --git a/numerical_methods/durand_kerner_roots.cpp b/numerical_methods/durand_kerner_roots.cpp index 80464412a6c..89714114340 100644 --- a/numerical_methods/durand_kerner_roots.cpp +++ b/numerical_methods/durand_kerner_roots.cpp @@ -3,6 +3,7 @@ * \brief Compute all possible approximate roots of any given polynomial using * [Durand Kerner * algorithm](https://en.wikipedia.org/wiki/Durand%E2%80%93Kerner_method) + * \author [Krishna Vedala](https://github.com/kvedala) * * Test the algorithm online: * https://gist.github.com/kvedala/27f1b0b6502af935f6917673ec43bcd7 diff --git a/numerical_methods/newton_raphson_method.cpp b/numerical_methods/newton_raphson_method.cpp index 318363a3922..d086123ca15 100644 --- a/numerical_methods/newton_raphson_method.cpp +++ b/numerical_methods/newton_raphson_method.cpp @@ -1,13 +1,15 @@ /** * \file * \brief Solve the equation \f$f(x)=0\f$ using [Newton-Raphson - * method](https://en.wikipedia.org/wiki/Newton%27s_method) + * method](https://en.wikipedia.org/wiki/Newton%27s_method) for both real and + * complex solutions * * The \f$(i+1)^\text{th}\f$ approximation is given by: * \f[ * x_{i+1} = x_i - \frac{f(x_i)}{f'(x_i)} * \f] * + * \author [Krishna Vedala](https://github.com/kvedala) * \see bisection_method.cpp, false_position.cpp */ #include diff --git a/numerical_methods/ordinary_least_squares_regressor.cpp b/numerical_methods/ordinary_least_squares_regressor.cpp index de02b27bba7..43979d0ead6 100644 --- a/numerical_methods/ordinary_least_squares_regressor.cpp +++ b/numerical_methods/ordinary_least_squares_regressor.cpp @@ -3,6 +3,7 @@ * \brief Linear regression example using [Ordinary least * squares](https://en.wikipedia.org/wiki/Ordinary_least_squares) * + * \author [Krishna Vedala](https://github.com/kvedala) * Program that gets the number of data samples and number of features per * sample along with output per sample. It applies OLS regression to compute * the regression output for additional test data samples. diff --git a/sorting/shell_sort2.cpp b/sorting/shell_sort2.cpp index 85186e75228..96ef25580b1 100644 --- a/sorting/shell_sort2.cpp +++ b/sorting/shell_sort2.cpp @@ -1,6 +1,7 @@ /** * \file * \brief [Shell sort](https://en.wikipedia.org/wiki/Shell_sort) algorithm + * \author [Krishna Vedala](https://github.com/kvedala) */ #include #include From ff6cb07b9cdfd6988bb1d75217671d0e0b52a49b Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 5 Jun 2020 21:55:12 -0400 Subject: [PATCH 372/433] enable cmake in subfolders of data_structures --- data_structures/CMakeLists.txt | 4 ++++ data_structures/cll/CMakeLists.txt | 5 +++++ data_structures/cll/makefile | 11 ----------- data_structures/queue/CMakeLists.txt | 5 +++++ data_structures/queue/makefile | 11 ----------- data_structures/stk/CMakeLists.txt | 11 +++++++++++ 6 files changed, 25 insertions(+), 22 deletions(-) create mode 100644 data_structures/cll/CMakeLists.txt delete mode 100644 data_structures/cll/makefile create mode 100644 data_structures/queue/CMakeLists.txt delete mode 100644 data_structures/queue/makefile create mode 100644 data_structures/stk/CMakeLists.txt diff --git a/data_structures/CMakeLists.txt b/data_structures/CMakeLists.txt index 7840c834939..fab3c564275 100644 --- a/data_structures/CMakeLists.txt +++ b/data_structures/CMakeLists.txt @@ -16,3 +16,7 @@ foreach( testsourcefile ${APP_SOURCES} ) install(TARGETS ${testname} DESTINATION "bin/data_structures") endforeach( testsourcefile ${APP_SOURCES} ) + +add_subdirectory(cll) +add_subdirectory(queue) +add_subdirectory(stk) diff --git a/data_structures/cll/CMakeLists.txt b/data_structures/cll/CMakeLists.txt new file mode 100644 index 00000000000..cb18eb3475f --- /dev/null +++ b/data_structures/cll/CMakeLists.txt @@ -0,0 +1,5 @@ +add_executable( cll + cll.cpp + main_cll.cpp +) +install(TARGETS cll DESTINATION "bin/data_structures") diff --git a/data_structures/cll/makefile b/data_structures/cll/makefile deleted file mode 100644 index 0f8734eabbc..00000000000 --- a/data_structures/cll/makefile +++ /dev/null @@ -1,11 +0,0 @@ -CC= g++ -CFLAGS = -c -Wall - -all: cll -cll.o: cll.cpp main_cll.cpp - $(CC) $(CFLAGS) cll.cpp main_cll.cpp -cll: cll.o - $(CC) main_cll.o cll.o -o cll - -clean: - rm *o cll diff --git a/data_structures/queue/CMakeLists.txt b/data_structures/queue/CMakeLists.txt new file mode 100644 index 00000000000..969936730e7 --- /dev/null +++ b/data_structures/queue/CMakeLists.txt @@ -0,0 +1,5 @@ +add_executable( test_queue + queue.cpp + test_queue.cpp +) +install(TARGETS test_queue DESTINATION "bin/data_structures") diff --git a/data_structures/queue/makefile b/data_structures/queue/makefile deleted file mode 100644 index 42090980475..00000000000 --- a/data_structures/queue/makefile +++ /dev/null @@ -1,11 +0,0 @@ -CC= g++ -CFLAGS = -c -Wall - -all: test_queue -queue.o: queue.cpp - $(CC) $(CFLAGS) queue.cpp -test_queue: queue.o - $(CC) test_queue.cpp queue.o -o queue - -clean: - rm *o queue diff --git a/data_structures/stk/CMakeLists.txt b/data_structures/stk/CMakeLists.txt new file mode 100644 index 00000000000..c348ca85379 --- /dev/null +++ b/data_structures/stk/CMakeLists.txt @@ -0,0 +1,11 @@ +add_executable( stack + stack.cpp + main.cpp +) +add_executable( test_stack + stack.cpp + test_stack.cpp +) +install(TARGETS stack DESTINATION "bin/data_structures") +install(TARGETS test_stack DESTINATION "bin/data_structures") +install(FILES students.txt DESTINATION "bin/data_structures") From 30cf80c35dcd63c26278c94ac309095dd5d6cfe0 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 6 Jun 2020 10:44:02 -0400 Subject: [PATCH 373/433] create and link object file --- data_structures/stk/CMakeLists.txt | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/data_structures/stk/CMakeLists.txt b/data_structures/stk/CMakeLists.txt index c348ca85379..30149ec0633 100644 --- a/data_structures/stk/CMakeLists.txt +++ b/data_structures/stk/CMakeLists.txt @@ -1,11 +1,15 @@ +add_library(libstack OBJECT stack.h stack.cpp) add_executable( stack - stack.cpp main.cpp ) -add_executable( test_stack - stack.cpp +target_link_libraries(stack PUBLIC libstack) +# set_target_properties(stack PROPERTIES LINKER_LANGUAGE CXX) + +add_executable( test_stack test_stack.cpp ) +target_link_libraries(test_stack PUBLIC libstack) + install(TARGETS stack DESTINATION "bin/data_structures") install(TARGETS test_stack DESTINATION "bin/data_structures") install(FILES students.txt DESTINATION "bin/data_structures") From 36510f1fdc0bd92bf89159c1b112c8286d38a3c6 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 6 Jun 2020 12:16:45 -0400 Subject: [PATCH 374/433] cpp lint fixes and instantiate template classes --- data_structures/stk/main.cpp | 23 ++++++-------- data_structures/stk/makefile | 13 -------- data_structures/stk/stack.cpp | 32 +++++++++++-------- data_structures/stk/stack.h | 8 ++--- data_structures/stk/test_stack.cpp | 50 ++++++++++++++++-------------- 5 files changed, 59 insertions(+), 67 deletions(-) delete mode 100644 data_structures/stk/makefile diff --git a/data_structures/stk/main.cpp b/data_structures/stk/main.cpp index 44b7984e028..11215ac4b0f 100644 --- a/data_structures/stk/main.cpp +++ b/data_structures/stk/main.cpp @@ -8,29 +8,26 @@ * ./main student.txt ************************************************************ * */ -#include +#include #include #include #include #include -#include "stack.cpp" #include "stack.h" -using namespace std; - int main(int argc, char* argv[]) { double GPA; double highestGPA; - string name; + std::string name; assert(argc == 2); - ifstream infile; - stack stk; + std::ifstream infile; + stack stk; infile.open(argv[1]); - cout << fixed << showpoint; - cout << setprecision(2); + std::cout << std::fixed << std::showpoint; + std::cout << std::setprecision(2); infile >> GPA >> name; highestGPA = GPA; @@ -44,12 +41,12 @@ int main(int argc, char* argv[]) { } infile >> GPA >> name; } - cout << "Highest GPA: " << highestGPA << endl; - cout << "Students the highest GPA are: " << endl; + std::cout << "Highest GPA: " << highestGPA << std::endl; + std::cout << "Students the highest GPA are: " << std::endl; while (!stk.isEmptyStack()) { - cout << stk.top() << endl; + std::cout << stk.top() << std::endl; stk.pop(); } - cout << endl; + std::cout << std::endl; return 0; } diff --git a/data_structures/stk/makefile b/data_structures/stk/makefile deleted file mode 100644 index e965d2044a6..00000000000 --- a/data_structures/stk/makefile +++ /dev/null @@ -1,13 +0,0 @@ -CC= g++ -CFLAGS = -c -Wall - -all: main test_stack -stack.o: stack.cpp - $(CC) $(CFLAGS) stack.cpp -test_stack: stack.o - $(CC) test_stack.cpp stack.o -o stk -main: stack.o - $(CC) main.cpp stack.o -o main - -clean: - rm *o stk main diff --git a/data_structures/stk/stack.cpp b/data_structures/stk/stack.cpp index bfa8a353e8d..23aa3c05af3 100644 --- a/data_structures/stk/stack.cpp +++ b/data_structures/stk/stack.cpp @@ -1,8 +1,7 @@ -#include "stack.h" -#include -#include +#include "./stack.h" -using namespace std; +#include +#include /* Default constructor*/ template @@ -19,13 +18,13 @@ stack::~stack() {} template void stack::display() { node *current = stackTop; - cout << "Top --> "; + std::cout << "Top --> "; while (current != NULL) { - cout << current->data << " "; + std::cout << current->data << " "; current = current->next; } - cout << endl; - cout << "Size of stack: " << size << endl; + std::cout << std::endl; + std::cout << "Size of stack: " << size << std::endl; } /* Determine whether the stack is empty */ @@ -68,20 +67,22 @@ void stack::pop() { delete temp; size--; } else { - cout << "Stack is empty !" << endl; + std::cout << "Stack is empty !" << std::endl; } } /* Operator "=" */ template -stack stack::operator=(stack &otherStack) { +stack &stack::operator=(const stack &otherStack) { node *newNode, *current, *last; - if (stackTop != NULL) /* If stack is no empty, make it empty */ + /* If stack is no empty, make it empty */ + if (stackTop != NULL) { stackTop = NULL; - if (otherStack.stackTop == NULL) + } + if (otherStack.stackTop == NULL) { stackTop = NULL; - else { + } else { current = otherStack.stackTop; stackTop = new node; stackTop->data = current->data; @@ -101,3 +102,8 @@ stack stack::operator=(stack &otherStack) { size = otherStack.size; return *this; } + +#include +/** force instantiate to export the type class */ +template class stack; +template class stack; diff --git a/data_structures/stk/stack.h b/data_structures/stk/stack.h index da7788b73b0..e038440a187 100644 --- a/data_structures/stk/stack.h +++ b/data_structures/stk/stack.h @@ -1,6 +1,6 @@ /* This class specifies the basic operation on a stack as a linked list */ -#ifndef STACK_H -#define STACK_H +#ifndef DATA_STRUCTURES_STK_STACK_H_ +#define DATA_STRUCTURES_STK_STACK_H_ /* Definition of the node */ template @@ -22,11 +22,11 @@ class stack { void pop(); /* Remove the top element of the stack */ void clear(); - stack operator=(stack &otherStack); + stack &operator=(const stack &otherStack); // Overload "=" the assignment operator. private: node *stackTop; /* Pointer to the stack */ int size; }; -#endif +#endif // DATA_STRUCTURES_STK_STACK_H_ diff --git a/data_structures/stk/test_stack.cpp b/data_structures/stk/test_stack.cpp index 098027dfd8c..aa636916f8e 100644 --- a/data_structures/stk/test_stack.cpp +++ b/data_structures/stk/test_stack.cpp @@ -1,56 +1,58 @@ #include -#include "stack.cpp" -#include "stack.h" -using namespace std; +#include "./stack.h" int main() { stack stk; - cout << "---------------------- Test construct ----------------------" - << endl; + std::cout << "---------------------- Test construct ----------------------" + << std::endl; stk.display(); - cout << "---------------------- Test isEmptyStack ----------------------" - << endl; + std::cout + << "---------------------- Test isEmptyStack ----------------------" + << std::endl; if (stk.isEmptyStack()) - cout << "PASS" << endl; + std::cout << "PASS" << std::endl; else - cout << "FAIL" << endl; - cout << "---------------------- Test push ----------------------" << endl; - cout << "After pushing 10 20 30 40 into stack: " << endl; + std::cout << "FAIL" << std::endl; + std::cout << "---------------------- Test push ----------------------" + << std::endl; + std::cout << "After pushing 10 20 30 40 into stack: " << std::endl; stk.push(10); stk.push(20); stk.push(30); stk.push(40); stk.display(); - cout << "---------------------- Test top ----------------------" << endl; + std::cout << "---------------------- Test top ----------------------" + << std::endl; int value = stk.top(); if (value == 40) - cout << "PASS" << endl; + std::cout << "PASS" << std::endl; else - cout << "FAIL" << endl; - cout << "---------------------- Test pop ----------------------" << endl; + std::cout << "FAIL" << std::endl; + std::cout << "---------------------- Test pop ----------------------" + << std::endl; stk.display(); stk.pop(); stk.pop(); - cout << "After popping 2 times: " << endl; + std::cout << "After popping 2 times: " << std::endl; stk.display(); - cout << "---------------------- Test overload = operator " - "----------------------" - << endl; + std::cout << "---------------------- Test overload = operator " + "----------------------" + << std::endl; stack stk1; - cout << "stk current: " << endl; + std::cout << "stk current: " << std::endl; stk.display(); - cout << endl << "Assign stk1 = stk " << endl; + std::cout << std::endl << "Assign stk1 = stk " << std::endl; stk1 = stk; stk1.display(); - cout << endl << "After pushing 8 9 10 into stk1:" << endl; + std::cout << std::endl << "After pushing 8 9 10 into stk1:" << std::endl; stk1.push(8); stk1.push(9); stk1.push(10); stk1.display(); - cout << endl << "stk current: " << endl; + std::cout << std::endl << "stk current: " << std::endl; stk.display(); - cout << "Assign back stk = stk1:" << endl; + std::cout << "Assign back stk = stk1:" << std::endl; stk = stk1; stk.display(); return 0; From cf8920852e6af313f490a583af05d2b564722abb Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 6 Jun 2020 12:25:51 -0400 Subject: [PATCH 375/433] cpp lint fixes and instantiate template classes Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- data_structures/queue/CMakeLists.txt | 4 ++- data_structures/queue/queue.cpp | 21 ++++++++------- data_structures/queue/queue.h | 28 +++++++++---------- data_structures/queue/test_queue.cpp | 40 ++++++++++++++-------------- data_structures/stk/main.cpp | 2 +- 5 files changed, 50 insertions(+), 45 deletions(-) diff --git a/data_structures/queue/CMakeLists.txt b/data_structures/queue/CMakeLists.txt index 969936730e7..434d3bb45db 100644 --- a/data_structures/queue/CMakeLists.txt +++ b/data_structures/queue/CMakeLists.txt @@ -1,5 +1,7 @@ +add_library(libqueue OBJECT queue.h queue.cpp) add_executable( test_queue - queue.cpp test_queue.cpp ) +target_link_libraries(test_queue PUBLIC libqueue) + install(TARGETS test_queue DESTINATION "bin/data_structures") diff --git a/data_structures/queue/queue.cpp b/data_structures/queue/queue.cpp index a7055bb14f2..9d5f9b9df20 100644 --- a/data_structures/queue/queue.cpp +++ b/data_structures/queue/queue.cpp @@ -1,8 +1,7 @@ -#include "queue.h" -#include -#include +#include "./queue.h" -using namespace std; +#include +#include /* Default constructor*/ template @@ -20,13 +19,13 @@ queue::~queue() {} template void queue::display() { node *current = queueFront; - cout << "Front --> "; + std::cout << "Front --> "; while (current != NULL) { - cout << current->data << " "; + std::cout << current->data << " "; current = current->next; } - cout << endl; - cout << "Size of queue: " << size << endl; + std::cout << std::endl; + std::cout << "Size of queue: " << size << std::endl; } /* Determine whether the queue is empty */ @@ -75,6 +74,10 @@ void queue::deQueue() { delete temp; size--; } else { - cout << "Queue is empty !" << endl; + std::cout << "Queue is empty !" << std::endl; } } + +#include +/** force instantiate to export the type class */ +template class queue; diff --git a/data_structures/queue/queue.h b/data_structures/queue/queue.h index d1305fc815f..d55ee386492 100644 --- a/data_structures/queue/queue.h +++ b/data_structures/queue/queue.h @@ -1,31 +1,31 @@ /* This class specifies the basic operation on a queue as a linked list */ -#ifndef QUEUE_H -#define QUEUE_H +#ifndef DATA_STRUCTURES_QUEUE_QUEUE_H_ +#define DATA_STRUCTURES_QUEUE_QUEUE_H_ -/* Definition of the node */ +/** Definition of the node */ template struct node { Kind data; node *next; }; -/* Definition of the queue class */ +/** Definition of the queue class */ template class queue { public: - void display(); /* Show queue */ - queue(); /* Default constructor*/ - ~queue(); /* Destructor */ - bool isEmptyQueue(); /* Determine whether the queue is empty */ - void enQueue(Kind item); /* Add new item to the queue */ - Kind front(); /* Return the first element of the queue */ - void deQueue(); /* Remove the top element of the queue */ + void display(); /**< Show queue */ + queue(); /**< Default constructor*/ + ~queue(); /**< Destructor */ + bool isEmptyQueue(); /**< Determine whether the queue is empty */ + void enQueue(Kind item); /**< Add new item to the queue */ + Kind front(); /**< Return the first element of the queue */ + void deQueue(); /**< Remove the top element of the queue */ void clear(); private: - node *queueFront; /* Pointer to the front of the queue */ - node *queueRear; /* Pointer to the rear of the queue */ + node *queueFront; /**< Pointer to the front of the queue */ + node *queueRear; /**< Pointer to the rear of the queue */ int size; }; -#endif +#endif // DATA_STRUCTURES_QUEUE_QUEUE_H_ diff --git a/data_structures/queue/test_queue.cpp b/data_structures/queue/test_queue.cpp index 7f0923f78a6..387ccf2f795 100644 --- a/data_structures/queue/test_queue.cpp +++ b/data_structures/queue/test_queue.cpp @@ -1,41 +1,41 @@ #include #include -#include "queue.cpp" -#include "queue.h" -using namespace std; +#include "./queue.h" int main() { - queue q; - cout << "---------------------- Test construct ----------------------" - << endl; + queue q; + std::cout << "---------------------- Test construct ----------------------" + << std::endl; q.display(); - cout << "---------------------- Test isEmptyQueue ----------------------" - << endl; + std::cout + << "---------------------- Test isEmptyQueue ----------------------" + << std::endl; if (q.isEmptyQueue()) - cout << "PASS" << endl; + std::cout << "PASS" << std::endl; else - cout << "FAIL" << endl; - cout << "---------------------- Test enQueue ----------------------" - << endl; - cout << "After Hai, Jeff, Tom, Jkingston go into queue: " << endl; + std::cout << "FAIL" << std::endl; + std::cout << "---------------------- Test enQueue ----------------------" + << std::endl; + std::cout << "After Hai, Jeff, Tom, Jkingston go into queue: " << std::endl; q.enQueue("Hai"); q.enQueue("Jeff"); q.enQueue("Tom"); q.enQueue("Jkingston"); q.display(); - cout << "---------------------- Test front ----------------------" << endl; - string value = q.front(); + std::cout << "---------------------- Test front ----------------------" + << std::endl; + std::string value = q.front(); if (value == "Hai") - cout << "PASS" << endl; + std::cout << "PASS" << std::endl; else - cout << "FAIL" << endl; - cout << "---------------------- Test deQueue ----------------------" - << endl; + std::cout << "FAIL" << std::endl; + std::cout << "---------------------- Test deQueue ----------------------" + << std::endl; q.display(); q.deQueue(); q.deQueue(); - cout << "After Hai, Jeff left the queue: " << endl; + std::cout << "After Hai, Jeff left the queue: " << std::endl; q.display(); return 0; } diff --git a/data_structures/stk/main.cpp b/data_structures/stk/main.cpp index 11215ac4b0f..a6048c4c938 100644 --- a/data_structures/stk/main.cpp +++ b/data_structures/stk/main.cpp @@ -14,7 +14,7 @@ #include #include -#include "stack.h" +#include "./stack.h" int main(int argc, char* argv[]) { double GPA; From e7b7d453b24b74afc9fc165f03f8fcd598415349 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 6 Jun 2020 12:31:34 -0400 Subject: [PATCH 376/433] cpplint - ignore `build/include` Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- .github/workflows/awesome_forkflow.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/awesome_forkflow.yml b/.github/workflows/awesome_forkflow.yml index 05094bdd1b9..088d9829cc9 100644 --- a/.github/workflows/awesome_forkflow.yml +++ b/.github/workflows/awesome_forkflow.yml @@ -167,7 +167,7 @@ jobs: print("cpplint:") for cpp_file in cpp_files: - subprocess.run(["cpplint", "--filter=-legal/copyright", cpp_file], check=True, text=True) + subprocess.run(["cpplint", "--filter=-legal/copyright,-build/include", cpp_file], check=True, text=True) print("g++:") # compile_exts = tuple(".c .c++ .cc .cpp .cu .cxx".split()) From f1af8c150ae7ee82374d72f38e8abd35d59b3531 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 6 Jun 2020 12:35:35 -0400 Subject: [PATCH 377/433] disable redundant gcc compilation in cpplint workflow Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- .github/workflows/awesome_forkflow.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/awesome_forkflow.yml b/.github/workflows/awesome_forkflow.yml index 088d9829cc9..93b630d056d 100644 --- a/.github/workflows/awesome_forkflow.yml +++ b/.github/workflows/awesome_forkflow.yml @@ -169,11 +169,11 @@ jobs: for cpp_file in cpp_files: subprocess.run(["cpplint", "--filter=-legal/copyright,-build/include", cpp_file], check=True, text=True) - print("g++:") + # print("g++:") # compile_exts = tuple(".c .c++ .cc .cpp .cu .cxx".split()) # compile_files = [file for file in cpp_files if file.lower().endswith(compile_exts)] - for cpp_file in cpp_files: - subprocess.run(["g++", cpp_file], check=True, text=True) + # for cpp_file in cpp_files: + # subprocess.run(["g++", cpp_file], check=True, text=True) upper_files = [file for file in cpp_files if file != file.lower()] if upper_files: From 57a951173aae83805ffae1d5af48ac2cb316eb71 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 6 Jun 2020 12:56:10 -0400 Subject: [PATCH 378/433] template header files contain function codes as well and removed redundant subfolders Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- data_structures/CMakeLists.txt | 2 - data_structures/queue.h | 88 ++++++++++++++ data_structures/queue/CMakeLists.txt | 7 -- data_structures/queue/queue.cpp | 83 ------------- data_structures/queue/queue.h | 31 ----- data_structures/stack.h | 111 ++++++++++++++++++ data_structures/stk/CMakeLists.txt | 15 --- data_structures/stk/stack.cpp | 109 ----------------- data_structures/stk/stack.h | 32 ----- data_structures/{stk => }/student.txt | 0 data_structures/{queue => }/test_queue.cpp | 0 data_structures/{stk => }/test_stack.cpp | 0 .../{stk/main.cpp => test_stack_students.cpp} | 0 13 files changed, 199 insertions(+), 279 deletions(-) create mode 100644 data_structures/queue.h delete mode 100644 data_structures/queue/CMakeLists.txt delete mode 100644 data_structures/queue/queue.cpp delete mode 100644 data_structures/queue/queue.h create mode 100644 data_structures/stack.h delete mode 100644 data_structures/stk/CMakeLists.txt delete mode 100644 data_structures/stk/stack.cpp delete mode 100644 data_structures/stk/stack.h rename data_structures/{stk => }/student.txt (100%) rename data_structures/{queue => }/test_queue.cpp (100%) rename data_structures/{stk => }/test_stack.cpp (100%) rename data_structures/{stk/main.cpp => test_stack_students.cpp} (100%) diff --git a/data_structures/CMakeLists.txt b/data_structures/CMakeLists.txt index fab3c564275..6c0555148be 100644 --- a/data_structures/CMakeLists.txt +++ b/data_structures/CMakeLists.txt @@ -18,5 +18,3 @@ foreach( testsourcefile ${APP_SOURCES} ) endforeach( testsourcefile ${APP_SOURCES} ) add_subdirectory(cll) -add_subdirectory(queue) -add_subdirectory(stk) diff --git a/data_structures/queue.h b/data_structures/queue.h new file mode 100644 index 00000000000..ed97a1e8dd9 --- /dev/null +++ b/data_structures/queue.h @@ -0,0 +1,88 @@ +/* This class specifies the basic operation on a queue as a linked list */ +#ifndef DATA_STRUCTURES_QUEUE_QUEUE_H_ +#define DATA_STRUCTURES_QUEUE_QUEUE_H_ + +#include +#include + +/** Definition of the node */ +template +struct node { + Kind data; + node *next; +}; + +/** Definition of the queue class */ +template +class queue { + public: + /** Show queue */ + void display() { + node *current = queueFront; + std::cout << "Front --> "; + while (current != NULL) { + std::cout << current->data << " "; + current = current->next; + } + std::cout << std::endl; + std::cout << "Size of queue: " << size << std::endl; + }; + + /** Default constructor*/ + queue() { + queueFront = NULL; + queueRear = NULL; + size = 0; + }; + + /** Destructor */ + ~queue(){}; + + /** Determine whether the queue is empty */ + bool isEmptyQueue() { return (queueFront == NULL); }; + + /** Add new item to the queue */ + void enQueue(Kind item) { + node *newNode; + newNode = new node; + newNode->data = item; + newNode->next = NULL; + if (queueFront == NULL) { + queueFront = newNode; + queueRear = newNode; + } else { + queueRear->next = newNode; + queueRear = queueRear->next; + } + size++; + }; + + /** Return the first element of the queue */ + Kind front() { + assert(queueFront != NULL); + return queueFront->data; + }; + + /** Remove the top element of the queue */ + void deQueue() { + node *temp; + if (!isEmptyQueue()) { + temp = queueFront; + queueFront = queueFront->next; + delete temp; + size--; + } else { + std::cout << "Queue is empty !" << std::endl; + } + }; + + /** Clear queue */ + void clear() { queueFront = NULL; }; + + private: + node *queueFront; /**< Pointer to the front of the queue */ + node *queueRear; /**< Pointer to the rear of the queue */ + int size; +}; + +#endif // DATA_STRUCTURES_QUEUE_QUEUE_H_ diff --git a/data_structures/queue/CMakeLists.txt b/data_structures/queue/CMakeLists.txt deleted file mode 100644 index 434d3bb45db..00000000000 --- a/data_structures/queue/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -add_library(libqueue OBJECT queue.h queue.cpp) -add_executable( test_queue - test_queue.cpp -) -target_link_libraries(test_queue PUBLIC libqueue) - -install(TARGETS test_queue DESTINATION "bin/data_structures") diff --git a/data_structures/queue/queue.cpp b/data_structures/queue/queue.cpp deleted file mode 100644 index 9d5f9b9df20..00000000000 --- a/data_structures/queue/queue.cpp +++ /dev/null @@ -1,83 +0,0 @@ -#include "./queue.h" - -#include -#include - -/* Default constructor*/ -template -queue::queue() { - queueFront = NULL; - queueRear = NULL; - size = 0; -} - -/* Destructor */ -template -queue::~queue() {} - -/* Display for testing */ -template -void queue::display() { - node *current = queueFront; - std::cout << "Front --> "; - while (current != NULL) { - std::cout << current->data << " "; - current = current->next; - } - std::cout << std::endl; - std::cout << "Size of queue: " << size << std::endl; -} - -/* Determine whether the queue is empty */ -template -bool queue::isEmptyQueue() { - return (queueFront == NULL); -} - -/* Clear queue */ -template -void queue::clear() { - queueFront = NULL; -} - -/* Add new item to the queue */ -template -void queue::enQueue(Kind item) { - node *newNode; - newNode = new node; - newNode->data = item; - newNode->next = NULL; - if (queueFront == NULL) { - queueFront = newNode; - queueRear = newNode; - } else { - queueRear->next = newNode; - queueRear = queueRear->next; - } - size++; -} - -/* Return the top element of the queue */ -template -Kind queue::front() { - assert(queueFront != NULL); - return queueFront->data; -} - -/* Remove the element of the queue */ -template -void queue::deQueue() { - node *temp; - if (!isEmptyQueue()) { - temp = queueFront; - queueFront = queueFront->next; - delete temp; - size--; - } else { - std::cout << "Queue is empty !" << std::endl; - } -} - -#include -/** force instantiate to export the type class */ -template class queue; diff --git a/data_structures/queue/queue.h b/data_structures/queue/queue.h deleted file mode 100644 index d55ee386492..00000000000 --- a/data_structures/queue/queue.h +++ /dev/null @@ -1,31 +0,0 @@ -/* This class specifies the basic operation on a queue as a linked list */ -#ifndef DATA_STRUCTURES_QUEUE_QUEUE_H_ -#define DATA_STRUCTURES_QUEUE_QUEUE_H_ - -/** Definition of the node */ -template -struct node { - Kind data; - node *next; -}; - -/** Definition of the queue class */ -template -class queue { - public: - void display(); /**< Show queue */ - queue(); /**< Default constructor*/ - ~queue(); /**< Destructor */ - bool isEmptyQueue(); /**< Determine whether the queue is empty */ - void enQueue(Kind item); /**< Add new item to the queue */ - Kind front(); /**< Return the first element of the queue */ - void deQueue(); /**< Remove the top element of the queue */ - void clear(); - - private: - node *queueFront; /**< Pointer to the front of the queue */ - node *queueRear; /**< Pointer to the rear of the queue */ - int size; -}; - -#endif // DATA_STRUCTURES_QUEUE_QUEUE_H_ diff --git a/data_structures/stack.h b/data_structures/stack.h new file mode 100644 index 00000000000..7b50e1f67a7 --- /dev/null +++ b/data_structures/stack.h @@ -0,0 +1,111 @@ +/* This class specifies the basic operation on a stack as a linked list */ +#ifndef DATA_STRUCTURES_STK_STACK_H_ +#define DATA_STRUCTURES_STK_STACK_H_ + +#include +#include + +/* Definition of the node */ +template +struct node { + Type data; + node *next; +}; + +/* Definition of the stack class */ +template +class stack { + public: + /** Show stack */ + void display() { + node *current = stackTop; + std::cout << "Top --> "; + while (current != NULL) { + std::cout << current->data << " "; + current = current->next; + } + std::cout << std::endl; + std::cout << "Size of stack: " << size << std::endl; + }; + + /** Default constructor*/ + stack() { + stackTop = NULL; + size = 0; + }; + + /** Destructor */ + ~stack(){}; + + /** Determine whether the stack is empty */ + bool isEmptyStack() { return (stackTop == NULL); }; + + /** Add new item to the stack */ + void push(Type item) { + node *newNode; + newNode = new node; + newNode->data = item; + newNode->next = stackTop; + stackTop = newNode; + size++; + }; + + /** Return the top element of the stack */ + Type top() { + assert(stackTop != NULL); + return stackTop->data; + }; + + /** Remove the top element of the stack */ + void pop() { + node *temp; + if (!isEmptyStack()) { + temp = stackTop; + stackTop = stackTop->next; + delete temp; + size--; + } else { + std::cout << "Stack is empty !" << std::endl; + } + }; + + /** Clear stack */ + void clear() { stackTop = NULL; }; + + /** Overload "=" the assignment operator */ + stack &operator=(const stack &otherStack) { + node *newNode, *current, *last; + + /* If stack is no empty, make it empty */ + if (stackTop != NULL) { + stackTop = NULL; + } + if (otherStack.stackTop == NULL) { + stackTop = NULL; + } else { + current = otherStack.stackTop; + stackTop = new node; + stackTop->data = current->data; + stackTop->next = NULL; + last = stackTop; + current = current->next; + /* Copy the remaining stack */ + while (current != NULL) { + newNode = new node; + newNode->data = current->data; + newNode->next = NULL; + last->next = newNode; + last = newNode; + current = current->next; + } + } + size = otherStack.size; + return *this; + }; + + private: + node *stackTop; /**< Pointer to the stack */ + int size; +}; + +#endif // DATA_STRUCTURES_STK_STACK_H_ diff --git a/data_structures/stk/CMakeLists.txt b/data_structures/stk/CMakeLists.txt deleted file mode 100644 index 30149ec0633..00000000000 --- a/data_structures/stk/CMakeLists.txt +++ /dev/null @@ -1,15 +0,0 @@ -add_library(libstack OBJECT stack.h stack.cpp) -add_executable( stack - main.cpp -) -target_link_libraries(stack PUBLIC libstack) -# set_target_properties(stack PROPERTIES LINKER_LANGUAGE CXX) - -add_executable( test_stack - test_stack.cpp -) -target_link_libraries(test_stack PUBLIC libstack) - -install(TARGETS stack DESTINATION "bin/data_structures") -install(TARGETS test_stack DESTINATION "bin/data_structures") -install(FILES students.txt DESTINATION "bin/data_structures") diff --git a/data_structures/stk/stack.cpp b/data_structures/stk/stack.cpp deleted file mode 100644 index 23aa3c05af3..00000000000 --- a/data_structures/stk/stack.cpp +++ /dev/null @@ -1,109 +0,0 @@ -#include "./stack.h" - -#include -#include - -/* Default constructor*/ -template -stack::stack() { - stackTop = NULL; - size = 0; -} - -/* Destructor */ -template -stack::~stack() {} - -/* Display for testing */ -template -void stack::display() { - node *current = stackTop; - std::cout << "Top --> "; - while (current != NULL) { - std::cout << current->data << " "; - current = current->next; - } - std::cout << std::endl; - std::cout << "Size of stack: " << size << std::endl; -} - -/* Determine whether the stack is empty */ -template -bool stack::isEmptyStack() { - return (stackTop == NULL); -} - -/* Clear stack */ -template -void stack::clear() { - stackTop = NULL; -} - -/* Add new item to the stack */ -template -void stack::push(Type item) { - node *newNode; - newNode = new node; - newNode->data = item; - newNode->next = stackTop; - stackTop = newNode; - size++; -} - -/* Return the top element of the stack */ -template -Type stack::top() { - assert(stackTop != NULL); - return stackTop->data; -} - -/* Remove the top element of the stack */ -template -void stack::pop() { - node *temp; - if (!isEmptyStack()) { - temp = stackTop; - stackTop = stackTop->next; - delete temp; - size--; - } else { - std::cout << "Stack is empty !" << std::endl; - } -} - -/* Operator "=" */ -template -stack &stack::operator=(const stack &otherStack) { - node *newNode, *current, *last; - - /* If stack is no empty, make it empty */ - if (stackTop != NULL) { - stackTop = NULL; - } - if (otherStack.stackTop == NULL) { - stackTop = NULL; - } else { - current = otherStack.stackTop; - stackTop = new node; - stackTop->data = current->data; - stackTop->next = NULL; - last = stackTop; - current = current->next; - /* Copy the remaining stack */ - while (current != NULL) { - newNode = new node; - newNode->data = current->data; - newNode->next = NULL; - last->next = newNode; - last = newNode; - current = current->next; - } - } - size = otherStack.size; - return *this; -} - -#include -/** force instantiate to export the type class */ -template class stack; -template class stack; diff --git a/data_structures/stk/stack.h b/data_structures/stk/stack.h deleted file mode 100644 index e038440a187..00000000000 --- a/data_structures/stk/stack.h +++ /dev/null @@ -1,32 +0,0 @@ -/* This class specifies the basic operation on a stack as a linked list */ -#ifndef DATA_STRUCTURES_STK_STACK_H_ -#define DATA_STRUCTURES_STK_STACK_H_ - -/* Definition of the node */ -template -struct node { - Type data; - node *next; -}; - -/* Definition of the stack class */ -template -class stack { - public: - void display(); /* Show stack */ - stack(); /* Default constructor*/ - ~stack(); /* Destructor */ - bool isEmptyStack(); /* Determine whether the stack is empty */ - void push(Type item); /* Add new item to the stack */ - Type top(); /* Return the top element of the stack */ - void pop(); /* Remove the top element of the stack */ - void clear(); - - stack &operator=(const stack &otherStack); - // Overload "=" the assignment operator. - private: - node *stackTop; /* Pointer to the stack */ - int size; -}; - -#endif // DATA_STRUCTURES_STK_STACK_H_ diff --git a/data_structures/stk/student.txt b/data_structures/student.txt similarity index 100% rename from data_structures/stk/student.txt rename to data_structures/student.txt diff --git a/data_structures/queue/test_queue.cpp b/data_structures/test_queue.cpp similarity index 100% rename from data_structures/queue/test_queue.cpp rename to data_structures/test_queue.cpp diff --git a/data_structures/stk/test_stack.cpp b/data_structures/test_stack.cpp similarity index 100% rename from data_structures/stk/test_stack.cpp rename to data_structures/test_stack.cpp diff --git a/data_structures/stk/main.cpp b/data_structures/test_stack_students.cpp similarity index 100% rename from data_structures/stk/main.cpp rename to data_structures/test_stack_students.cpp From d97f7c15f6c1709631102f0b97e4fab7c52cf9b0 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 6 Jun 2020 16:57:19 +0000 Subject: [PATCH 379/433] updating DIRECTORY.md --- DIRECTORY.md | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index bdfa2c95135..31093341af6 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -25,21 +25,17 @@ * [Linkedlist Implentation Usingarray](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/linkedlist_implentation_usingarray.cpp) * [List Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/list_array.cpp) * [Morrisinorder](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/morrisinorder.cpp) - * Queue - * [Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/queue/queue.cpp) - * [Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/queue/queue.h) - * [Test Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/queue/test_queue.cpp) + * [Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/queue.h) * [Queue Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/queue_using_array.cpp) * [Queue Using Array2](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/queue_using_array2.cpp) * [Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/queue_using_linked_list.cpp) * [Queue Using Linkedlist](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/queue_using_linkedlist.cpp) + * [Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/stack.h) * [Stack Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/stack_using_array.cpp) * [Stack Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/stack_using_linked_list.cpp) - * Stk - * [Main](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/stk/main.cpp) - * [Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/stk/stack.cpp) - * [Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/stk/stack.h) - * [Test Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/stk/test_stack.cpp) + * [Test Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/test_queue.cpp) + * [Test Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/test_stack.cpp) + * [Test Stack Students](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/test_stack_students.cpp) * [Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/tree.cpp) * [Trie Modern](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/trie_modern.cpp) * [Trie Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/trie_tree.cpp) From b3f0b75a08106a107f49f259451e2940fd1bfa9b Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 6 Jun 2020 13:02:36 -0400 Subject: [PATCH 380/433] remove semicolons after functions in a class Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- data_structures/queue.h | 16 ++++++++-------- data_structures/stack.h | 16 ++++++++-------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/data_structures/queue.h b/data_structures/queue.h index ed97a1e8dd9..dd53da7d052 100644 --- a/data_structures/queue.h +++ b/data_structures/queue.h @@ -26,20 +26,20 @@ class queue { } std::cout << std::endl; std::cout << "Size of queue: " << size << std::endl; - }; + } /** Default constructor*/ queue() { queueFront = NULL; queueRear = NULL; size = 0; - }; + } /** Destructor */ - ~queue(){}; + ~queue() {} /** Determine whether the queue is empty */ - bool isEmptyQueue() { return (queueFront == NULL); }; + bool isEmptyQueue() { return (queueFront == NULL); } /** Add new item to the queue */ void enQueue(Kind item) { @@ -55,13 +55,13 @@ class queue { queueRear = queueRear->next; } size++; - }; + } /** Return the first element of the queue */ Kind front() { assert(queueFront != NULL); return queueFront->data; - }; + } /** Remove the top element of the queue */ void deQueue() { @@ -74,10 +74,10 @@ class queue { } else { std::cout << "Queue is empty !" << std::endl; } - }; + } /** Clear queue */ - void clear() { queueFront = NULL; }; + void clear() { queueFront = NULL; } private: node *queueFront; /**< Pointer to the front of the queue */ diff --git a/data_structures/stack.h b/data_structures/stack.h index 7b50e1f67a7..8278a3d007a 100644 --- a/data_structures/stack.h +++ b/data_structures/stack.h @@ -26,16 +26,16 @@ class stack { } std::cout << std::endl; std::cout << "Size of stack: " << size << std::endl; - }; + } /** Default constructor*/ stack() { stackTop = NULL; size = 0; - }; + } /** Destructor */ - ~stack(){}; + ~stack() {} /** Determine whether the stack is empty */ bool isEmptyStack() { return (stackTop == NULL); }; @@ -48,13 +48,13 @@ class stack { newNode->next = stackTop; stackTop = newNode; size++; - }; + } /** Return the top element of the stack */ Type top() { assert(stackTop != NULL); return stackTop->data; - }; + } /** Remove the top element of the stack */ void pop() { @@ -67,10 +67,10 @@ class stack { } else { std::cout << "Stack is empty !" << std::endl; } - }; + } /** Clear stack */ - void clear() { stackTop = NULL; }; + void clear() { stackTop = NULL; } /** Overload "=" the assignment operator */ stack &operator=(const stack &otherStack) { @@ -101,7 +101,7 @@ class stack { } size = otherStack.size; return *this; - }; + } private: node *stackTop; /**< Pointer to the stack */ From 8a2bef9c20946bc70f8a97c76b837426adfbb903 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 6 Jun 2020 13:36:04 -0400 Subject: [PATCH 381/433] cpplint header guard style Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- data_structures/queue.h | 6 +++--- data_structures/stack.h | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/data_structures/queue.h b/data_structures/queue.h index dd53da7d052..3cb55174118 100644 --- a/data_structures/queue.h +++ b/data_structures/queue.h @@ -1,6 +1,6 @@ /* This class specifies the basic operation on a queue as a linked list */ -#ifndef DATA_STRUCTURES_QUEUE_QUEUE_H_ -#define DATA_STRUCTURES_QUEUE_QUEUE_H_ +#ifndef DATA_STRUCTURES_QUEUE_H_ +#define DATA_STRUCTURES_QUEUE_H_ #include #include @@ -85,4 +85,4 @@ class queue { int size; }; -#endif // DATA_STRUCTURES_QUEUE_QUEUE_H_ +#endif // DATA_STRUCTURES_QUEUE_H_ diff --git a/data_structures/stack.h b/data_structures/stack.h index 8278a3d007a..a27d2462b35 100644 --- a/data_structures/stack.h +++ b/data_structures/stack.h @@ -1,6 +1,6 @@ /* This class specifies the basic operation on a stack as a linked list */ -#ifndef DATA_STRUCTURES_STK_STACK_H_ -#define DATA_STRUCTURES_STK_STACK_H_ +#ifndef DATA_STRUCTURES_STACK_H_ +#define DATA_STRUCTURES_STACK_H_ #include #include @@ -108,4 +108,4 @@ class stack { int size; }; -#endif // DATA_STRUCTURES_STK_STACK_H_ +#endif // DATA_STRUCTURES_STACK_H_ From 869245dff526feaa588b65799570648b76a54518 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 6 Jun 2020 13:37:55 -0400 Subject: [PATCH 382/433] remove semilon Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- data_structures/stack.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data_structures/stack.h b/data_structures/stack.h index a27d2462b35..f4b8992e706 100644 --- a/data_structures/stack.h +++ b/data_structures/stack.h @@ -38,7 +38,7 @@ class stack { ~stack() {} /** Determine whether the stack is empty */ - bool isEmptyStack() { return (stackTop == NULL); }; + bool isEmptyStack() { return (stackTop == NULL); } /** Add new item to the stack */ void push(Type item) { From bde4be222777837b47b30949a3393be85dc05dea Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Mon, 8 Jun 2020 10:36:18 -0400 Subject: [PATCH 383/433] added LU decomposition algorithm Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- numerical_methods/lu_decompose.cpp | 126 +++++++++++++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 numerical_methods/lu_decompose.cpp diff --git a/numerical_methods/lu_decompose.cpp b/numerical_methods/lu_decompose.cpp new file mode 100644 index 00000000000..37a011e40b5 --- /dev/null +++ b/numerical_methods/lu_decompose.cpp @@ -0,0 +1,126 @@ +/** + * \file + * \brief [LU decomposition](https://en.wikipedia.org/wiki/LU_decompositon) of a + * square matrix + * \author [Krishna Vedala](https://github.com/kvedala) + */ +#include +#include +#include +#include +#ifdef _OPENMP +#include +#endif + +/** Perform LU decomposition on matrix + * \param[in] A matrix to decompose + * \param[out] L output L matrix + * \param[out] U output U matrix + * \returns 0 if no errors + * \returns negative if error occurred + */ +int lu_decomposition(const std::vector> &A, + std::vector> *L, + std::vector> *U) { + int row, col, j; + int mat_size = A.size(); + + if (mat_size != A[0].size()) { + // check matrix is a square matrix + std::cerr << "Not a square matrix!\n"; + return -1; + } + + // regularize each row + for (row = 0; row < mat_size; row++) { + // Upper triangular matrix +#ifdef _OPENMP +#pragma omp for +#endif + for (col = row; col < mat_size; col++) { + // Summation of L[i,j] * U[j,k] + double lu_sum = 0.; + for (j = 0; j < row; j++) lu_sum += L[0][row][j] * U[0][j][col]; + + // Evaluate U[i,k] + U[0][row][col] = A[row][col] - lu_sum; + } + + // Lower triangular matrix +#ifdef _OPENMP +#pragma omp for +#endif + for (col = row; col < mat_size; col++) { + if (row == col) { + L[0][row][col] = 1.; + continue; + } + + // Summation of L[i,j] * U[j,k] + double lu_sum = 0.; + for (j = 0; j < row; j++) lu_sum += L[0][col][j] * U[0][j][row]; + + // Evaluate U[i,k] + L[0][col][row] = (A[col][row] - lu_sum) / U[0][row][row]; + } + } + + return 0; +} + +/** + * operator to print a matrix + */ +template +std::ostream &operator<<(std::ostream &out, + std::vector> const &v) { + const int width = 10; + const char separator = ' '; + + for (size_t row = 0; row < v.size(); row++) { + for (size_t col = 0; col < v[row].size(); col++) + out << std::left << std::setw(width) << std::setfill(separator) + << v[row][col]; + out << std::endl; + } + + return out; +} + +/** Main function */ +int main(int argc, char **argv) { + int mat_size = 3; // default matrix size + const int range = 50; + const int range2 = range >> 1; + + if (argc == 2) + mat_size = atoi(argv[1]); + + std::srand(std::time(NULL)); // random number initializer + + /* Create a square matrix with random values */ + std::vector> A(mat_size); + std::vector> L(mat_size); // output + std::vector> U(mat_size); // output + for (int i = 0; i < mat_size; i++) { + // calloc so that all valeus are '0' by default + A[i] = std::vector(mat_size); + L[i] = std::vector(mat_size); + U[i] = std::vector(mat_size); + for (int j = 0; j < mat_size; j++) + /* create random values in the limits [-range2, range-1] */ + A[i][j] = static_cast(rand() % range - range2); + } + + std::clock_t start_t = std::clock(); + lu_decomposition(A, &L, &U); + std::clock_t end_t = std::clock(); + std::cout << "Time taken: " + << static_cast(end_t - start_t) / CLOCKS_PER_SEC << "\n"; + + std::cout << "A = \n" << A << "\n"; + std::cout << "L = \n" << L << "\n"; + std::cout << "U = \n" << U << "\n"; + + return 0; +} From acc50fcab73fd613566ea8fc89a54ff2e6879e08 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Mon, 8 Jun 2020 19:35:14 -0400 Subject: [PATCH 384/433] added QR decomposition algorithm Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- numerical_methods/qr_decompose.h | 210 +++++++++++++++++++++++++ numerical_methods/qr_decomposition.cpp | 58 +++++++ 2 files changed, 268 insertions(+) create mode 100644 numerical_methods/qr_decompose.h create mode 100644 numerical_methods/qr_decomposition.cpp diff --git a/numerical_methods/qr_decompose.h b/numerical_methods/qr_decompose.h new file mode 100644 index 00000000000..c9c3691449f --- /dev/null +++ b/numerical_methods/qr_decompose.h @@ -0,0 +1,210 @@ +/** + * @file + * \brief Library functions to compute [QR + * decomposition](https://en.wikipedia.org/wiki/QR_decomposition) of a given + * matrix. + * \author [Krishna Vedala](https://github.com/kvedala) + */ + +#ifndef NUMERICAL_METHODS_QR_DECOMPOSE_H_ +#define NUMERICAL_METHODS_QR_DECOMPOSE_H_ + +#include +#include +#include +#include +#include +#include +#include +#ifdef _OPENMP +#include +#endif + +/** \namespace qr_algorithm + * \brief Functions to compute [QR + * decomposition](https://en.wikipedia.org/wiki/QR_decomposition) of any + * rectangular matrix + */ +namespace qr_algorithm { +/** + * operator to print a matrix + */ +template +std::ostream &operator<<(std::ostream &out, + std::valarray> const &v) { + const int width = 12; + const char separator = ' '; + + out.precision(4); + for (size_t row = 0; row < v.size(); row++) { + for (size_t col = 0; col < v[row].size(); col++) + out << std::right << std::setw(width) << std::setfill(separator) + << v[row][col]; + out << std::endl; + } + + return out; +} + +/** + * operator to print a vector + */ +template +std::ostream &operator<<(std::ostream &out, std::valarray const &v) { + const int width = 10; + const char separator = ' '; + + out.precision(4); + for (size_t row = 0; row < v.size(); row++) { + out << std::right << std::setw(width) << std::setfill(separator) + << v[row]; + } + + return out; +} + +/** + * Compute dot product of two vectors of equal lengths + * + * If \f$\vec{a}=\left[a_0,a_1,a_2,...,a_L\right]\f$ and + * \f$\vec{b}=\left[b_0,b_1,b_1,...,b_L\right]\f$ then + * \f$\vec{a}\cdot\vec{b}=\displaystyle\sum_{i=0}^L a_i\times b_i\f$ + * + * \returns \f$\vec{a}\cdot\vec{b}\f$ + */ +template +inline double vector_dot(const std::valarray &a, const std::valarray &b) { + return (a * b).sum(); + // could also use following + // return std::inner_product(std::begin(a), std::end(a), std::begin(b), + // 0.f); +} + +/** + * Compute magnitude of vector. + * + * If \f$\vec{a}=\left[a_0,a_1,a_2,...,a_L\right]\f$ then + * \f$\left|\vec{a}\right|=\sqrt{\displaystyle\sum_{i=0}^L a_i^2}\f$ + * + * \returns \f$\left|\vec{a}\right|\f$ + */ +template +inline double vector_mag(const std::valarray &a) { + double dot = vector_dot(a, a); + return std::sqrt(dot); +} + +/** + * Compute projection of vector \f$\vec{a}\f$ on \f$\vec{b}\f$ defined as + * \f[\text{proj}_\vec{b}\vec{a}=\frac{\vec{a}\cdot\vec{b}}{\left|\vec{b}\right|^2}\vec{b}\f] + * + * \returns NULL if error, otherwise pointer to output + */ +template +std::valarray vector_proj(const std::valarray &a, + const std::valarray &b) { + double num = vector_dot(a, b); + double deno = vector_dot(b, b); + + /*! check for division by zero using machine epsilon */ + if (deno <= std::numeric_limits::epsilon()) { + std::cerr << "[" << __func__ << "] Possible division by zero\n"; + return a; // return vector a back + } + + double scalar = num / deno; + + return b * scalar; +} + +/** + * Decompose matrix \f$A\f$ using [Gram-Schmidt + *process](https://en.wikipedia.org/wiki/QR_decomposition). + * + * \f{eqnarray*}{ + * \text{given that}\quad A &=& + *\left[\mathbf{a}_1,\mathbf{a}_2,\ldots,\mathbf{a}_{N-1},\right]\\ + * \text{where}\quad\mathbf{a}_i &=& + * \left[a_{0i},a_{1i},a_{2i},\ldots,a_{(M-1)i}\right]^T\quad\ldots\mbox{(column + * vectors)}\\ + * \text{then}\quad\mathbf{u}_i &=& \mathbf{a}_i + *-\sum_{j=0}^{i-1}\text{proj}_{\mathbf{u}_j}\mathbf{a}_i\\ + * \mathbf{e}_i &=&\frac{\mathbf{u}_i}{\left|\mathbf{u}_i\right|}\\ + * Q &=& \begin{bmatrix}\mathbf{e}_0 & \mathbf{e}_1 & \mathbf{e}_2 & \dots & + * \mathbf{e}_{N-1}\end{bmatrix}\\ + * R &=& \begin{bmatrix}\langle\mathbf{e}_0\,,\mathbf{a}_0\rangle & + * \langle\mathbf{e}_1\,,\mathbf{a}_1\rangle & + * \langle\mathbf{e}_2\,,\mathbf{a}_2\rangle & \dots \\ + * 0 & \langle\mathbf{e}_1\,,\mathbf{a}_1\rangle & + * \langle\mathbf{e}_2\,,\mathbf{a}_2\rangle & \dots\\ + * 0 & 0 & \langle\mathbf{e}_2\,,\mathbf{a}_2\rangle & + * \dots\\ \vdots & \vdots & \vdots & \ddots + * \end{bmatrix}\\ + * \f} + */ +template +void qr_decompose( + const std::valarray> &A, /**< input matrix to decompose */ + std::valarray> *Q, /**< output decomposed matrix */ + std::valarray> *R /**< output decomposed matrix */ +) { + std::size_t ROWS = A.size(); // number of rows of A + std::size_t COLUMNS = A[0].size(); // number of columns of A + std::valarray col_vector(ROWS); + std::valarray col_vector2(ROWS); + std::valarray tmp_vector(ROWS); + + for (int i = 0; i < COLUMNS; i++) { + /* for each column => R is a square matrix of NxN */ + int j; + R[0][i] = 0.; /* make R upper triangular */ + + /* get corresponding Q vector */ +#ifdef _OPENMP +// parallelize on threads +#pragma omp for +#endif + for (j = 0; j < ROWS; j++) { + tmp_vector[j] = A[j][i]; /* accumulator for uk */ + col_vector[j] = A[j][i]; + } + for (j = 0; j < i; j++) { + for (int k = 0; k < ROWS; k++) { + col_vector2[k] = Q[0][k][j]; + } + col_vector2 = vector_proj(col_vector, col_vector2); + tmp_vector -= col_vector2; + } + + double mag = vector_mag(tmp_vector); + +#ifdef _OPENMP +// parallelize on threads +#pragma omp for +#endif + for (j = 0; j < ROWS; j++) Q[0][j][i] = tmp_vector[j] / mag; + + /* compute upper triangular values of R */ +#ifdef _OPENMP +// parallelize on threads +#pragma omp for +#endif + for (int kk = 0; kk < ROWS; kk++) { + col_vector[kk] = Q[0][kk][i]; + } + +#ifdef _OPENMP +// parallelize on threads +#pragma omp for +#endif + for (int k = i; k < COLUMNS; k++) { + for (int kk = 0; kk < ROWS; kk++) { + col_vector2[kk] = A[kk][k]; + } + R[0][i][k] = (col_vector * col_vector2).sum(); + } + } +} +} // namespace qr_algorithm + +#endif // NUMERICAL_METHODS_QR_DECOMPOSE_H_ diff --git a/numerical_methods/qr_decomposition.cpp b/numerical_methods/qr_decomposition.cpp new file mode 100644 index 00000000000..237a5c94642 --- /dev/null +++ b/numerical_methods/qr_decomposition.cpp @@ -0,0 +1,58 @@ +/** + * @file + * \brief Program to compute the [QR + * decomposition](https://en.wikipedia.org/wiki/QR_decomposition) of a given + * matrix. + * \author [Krishna Vedala](https://github.com/kvedala) + */ + +#include +#include +#include +#include +#include + +#include "./qr_decompose.h" + +using qr_algorithm::qr_decompose; +using qr_algorithm::operator<<; + +/** + * main function + */ +int main(void) { + unsigned int ROWS, COLUMNS; + + std::cout << "Enter the number of rows and columns: "; + std::cin >> ROWS >> COLUMNS; + + std::cout << "Enter matrix elements row-wise:\n"; + + std::valarray> A(ROWS); + std::valarray> Q(ROWS); + std::valarray> R(COLUMNS); + for (int i = 0; i < std::max(ROWS, COLUMNS); i++) { + if (i < ROWS) { + A[i] = std::valarray(COLUMNS); + Q[i] = std::valarray(COLUMNS); + } + if (i < COLUMNS) { + R[i] = std::valarray(COLUMNS); + } + } + + for (int i = 0; i < ROWS; i++) + for (int j = 0; j < COLUMNS; j++) std::cin >> A[i][j]; + + std::cout << A << "\n"; + + clock_t t1 = clock(); + qr_decompose(A, &Q, &R); + double dtime = static_cast(clock() - t1) / CLOCKS_PER_SEC; + + std::cout << Q << "\n"; + std::cout << R << "\n"; + std::cout << "Time taken to compute: " << dtime << " sec\n "; + + return 0; +} From 9ac06027348f97cd2ab1c285848604eaac674df5 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Mon, 8 Jun 2020 19:35:49 -0400 Subject: [PATCH 385/433] use QR decomposition to find eigen values Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- numerical_methods/qr_eigen_values.cpp | 267 ++++++++++++++++++++++++++ 1 file changed, 267 insertions(+) create mode 100644 numerical_methods/qr_eigen_values.cpp diff --git a/numerical_methods/qr_eigen_values.cpp b/numerical_methods/qr_eigen_values.cpp new file mode 100644 index 00000000000..95ace03a79d --- /dev/null +++ b/numerical_methods/qr_eigen_values.cpp @@ -0,0 +1,267 @@ +/** + * @file + * \brief Compute real eigen values and eigen vectors of a symmetric matrix + * using [QR decomposition](https://en.wikipedia.org/wiki/QR_decomposition) + * method. + * \author [Krishna Vedala](https://github.com/kvedala) + */ +#include +#include +#include +#include +#include +#ifdef _OPENMP +#include +#endif + +#include "./qr_decompose.h" +using qr_algorithm::operator<<; + +#define LIMS 9 /**< limit of range of matrix values */ + +/** + * create a symmetric square matrix of given size with random elements. A + * symmetric square matrix will *always* have real eigen values. + * + * \param[out] A matrix to create (must be pre-allocated in memory) + */ +void create_matrix(std::valarray> *A) { + int i, j, tmp, lim2 = LIMS >> 1; + int N = A->size(); + std::srand(std::time(nullptr)); + +#ifdef _OPENMP +#pragma omp for +#endif + for (i = 0; i < N; i++) { + A[0][i][i] = (std::rand() % LIMS) - lim2; + for (j = i + 1; j < N; j++) { + tmp = (std::rand() % LIMS) - lim2; + A[0][i][j] = tmp; // summetrically distribute random values + A[0][j][i] = tmp; + } + } +} + +/** + * Perform multiplication of two matrices. + * * R2 must be equal to C1 + * * Resultant matrix size should be R1xC2 + * \param[in] A first matrix to multiply + * \param[in] B second matrix to multiply + * \param[out] OUT output matrix (must be pre-allocated) + * \returns pointer to resultant matrix + */ +void mat_mul(const std::valarray> &A, + const std::valarray> &B, + std::valarray> *OUT) { + int R1 = A.size(); + int C1 = A[0].size(); + int R2 = B.size(); + int C2 = B[0].size(); + if (C1 != R2) { + perror("Matrix dimensions mismatch!"); + return; + } + + for (int i = 0; i < R1; i++) { + for (int j = 0; j < C2; j++) { + OUT[0][i][j] = 0.f; + for (int k = 0; k < C1; k++) { + OUT[0][i][j] += A[i][k] * B[k][j]; + } + } + } +} + +namespace qr_algorithm { +/** Compute eigen values + * \param[in,out] A matric to compute eigen values for \note This matrix gets + * modified + * \param[in] print_intermediates (optional) whether to print intermediate A, Q + * and R matrices (default = `false`) + */ +std::valarray eigen_values(std::valarray> *A, + bool print_intermediates = false) { + int rows = A->size(); + int columns = rows; + int counter = 0, num_eigs = rows - 1; + double last_eig = 0; + + std::valarray> Q(rows); + std::valarray> R(columns); + + /* number of eigen values = matrix size */ + std::valarray eigen_vals(rows); + for (int i = 0; i < rows; i++) { + Q[i] = std::valarray(columns); + R[i] = std::valarray(columns); + } + + /* continue till all eigen values are found */ + while (num_eigs > 0) { + /* iterate with QR decomposition */ + while (std::abs(A[0][num_eigs][num_eigs - 1]) > + std::numeric_limits::epsilon()) { + // initial approximation = last diagonal element + last_eig = A[0][num_eigs][num_eigs]; + for (int i = 0; i < rows; i++) { + A[0][i][i] -= last_eig; /* A - cI */ + } + + qr_decompose(*A, &Q, &R); + + if (print_intermediates) { + std::cout << *A << "\n"; + std::cout << Q << "\n"; + std::cout << R << "\n"; + printf("-------------------- %d ---------------------\n", + ++counter); + } + + // new approximation A' = R * Q + mat_mul(R, Q, A); + + for (int i = 0; i < rows; i++) { + A[0][i][i] += last_eig; /* A + cI */ + } + } + + /* store the converged eigen value */ + eigen_vals[num_eigs] = last_eig; + // A[0][num_eigs][num_eigs]; + if (print_intermediates) { + std::cout << "========================\n"; + std::cout << "Eigen value: " << last_eig << ",\n"; + std::cout << "========================\n"; + } + + num_eigs--; + rows--; + columns--; + } + eigen_vals[0] = A[0][0][0]; + + if (print_intermediates) { + std::cout << Q << "\n"; + std::cout << R << "\n"; + } + + return eigen_vals; +} + +} // namespace qr_algorithm + +/** + * test function to compute eigen values of a 2x2 matrix + * \f[\begin{bmatrix} + * 5 & 7\\ + * 7 & 11 + * \end{bmatrix}\f] + * which are approximately, {15.56158, 0.384227} + */ +void test1() { + std::valarray> X = {{5, 7}, {7, 11}}; + double y[] = {15.56158, 0.384227}; // corresponding y-values + + std::cout << "------- Test 1 -------" << std::endl; + std::valarray eig_vals = qr_algorithm::eigen_values(&X); + + for (int i = 0; i < 2; i++) { + std::cout << i + 1 << "/2 Checking for " << y[i] << " --> "; + bool result = false; + for (int j = 0; j < 2 && !result; j++) { + if (std::abs(y[i] - eig_vals[j]) < 0.1) { + result = true; + std::cout << "(" << eig_vals[j] << ") "; + } + } + assert(result); // ensure that i^th expected eigen value was computed + std::cout << "found\n"; + } + std::cout << "Test 1 Passed\n\n"; +} + +/** + * test function to compute eigen values of a 2x2 matrix + * \f[\begin{bmatrix} + * -4& 4& 2& 0& -3\\ + * 4& -4& 4& -3& -1\\ + * 2& 4& 4& 3& -3\\ + * 0& -3& 3& -1&-1\\ + * -3& -1& -3& -3& 0 + * \end{bmatrix}\f] + * which are approximately, {9.27648, -9.26948, 2.0181, -1.03516, -5.98994} + */ +void test2() { + std::valarray> X = {{-4, 4, 2, 0, -3}, + {4, -4, 4, -3, -1}, + {2, 4, 4, 3, -3}, + {0, -3, 3, -1, -3}, + {-3, -1, -3, -3, 0}}; + double y[] = {9.27648, -9.26948, 2.0181, -1.03516, + -5.98994}; // corresponding y-values + + std::cout << "------- Test 2 -------" << std::endl; + std::valarray eig_vals = qr_algorithm::eigen_values(&X); + + std::cout << X << "\n" + << "Eigen values: " << eig_vals << "\n"; + + for (int i = 0; i < 5; i++) { + std::cout << i + 1 << "/5 Checking for " << y[i] << " --> "; + bool result = false; + for (int j = 0; j < 5 && !result; j++) { + if (std::abs(y[i] - eig_vals[j]) < 0.1) { + result = true; + std::cout << "(" << eig_vals[j] << ") "; + } + } + assert(result); // ensure that i^th expected eigen value was computed + std::cout << "found\n"; + } + std::cout << "Test 2 Passed\n\n"; +} + +/** + * main function + */ +int main(int argc, char **argv) { + int mat_size = 5; + if (argc == 2) + mat_size = atoi(argv[1]); + else { // if invalid input argument is given run tests + test1(); + test2(); + std::cout << "Usage: ./qr_eigen_values [mat_size]\n"; + return 0; + } + + if (mat_size < 2) { + fprintf(stderr, "Matrix size should be > 2\n"); + return -1; + } + + int i, rows = mat_size, columns = mat_size; + + std::valarray> A(rows); + + for (int i = 0; i < rows; i++) { + A[i] = std::valarray(columns); + } + + /* create a random matrix */ + create_matrix(&A); + + std::cout << A << "\n"; + + clock_t t1 = clock(); + std::valarray eigen_vals = qr_algorithm::eigen_values(&A); + double dtime = static_cast(clock() - t1) / CLOCKS_PER_SEC; + + std::cout << "Eigen vals: "; + for (i = 0; i < mat_size; i++) std::cout << eigen_vals[i] << "\t"; + std::cout << "\nTime taken to compute: " << dtime << " sec\n"; + + return 0; +} From 3772fb017728bc40a3d0d54006a78b2b2dc97032 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 8 Jun 2020 23:39:03 +0000 Subject: [PATCH 386/433] updating DIRECTORY.md --- DIRECTORY.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 31093341af6..45143d3a1d2 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -129,8 +129,12 @@ * [Durand Kerner Roots](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/durand_kerner_roots.cpp) * [False Position](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/false_position.cpp) * [Gaussian Elimination](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/gaussian_elimination.cpp) + * [Lu Decompose](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/lu_decompose.cpp) * [Newton Raphson Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/newton_raphson_method.cpp) * [Ordinary Least Squares Regressor](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/ordinary_least_squares_regressor.cpp) + * [Qr Decompose](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/qr_decompose.h) + * [Qr Decomposition](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/qr_decomposition.cpp) + * [Qr Eigen Values](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/qr_eigen_values.cpp) * [Successive Approximation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/successive_approximation.cpp) ## Operations On Datastructures From f3fb413a1370d543197fcac61132c6e5ea116a69 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Mon, 8 Jun 2020 19:47:30 -0400 Subject: [PATCH 387/433] use std::rand for thread safety Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- numerical_methods/lu_decompose.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/numerical_methods/lu_decompose.cpp b/numerical_methods/lu_decompose.cpp index 37a011e40b5..a0a2d00ab2a 100644 --- a/numerical_methods/lu_decompose.cpp +++ b/numerical_methods/lu_decompose.cpp @@ -109,7 +109,7 @@ int main(int argc, char **argv) { U[i] = std::vector(mat_size); for (int j = 0; j < mat_size; j++) /* create random values in the limits [-range2, range-1] */ - A[i][j] = static_cast(rand() % range - range2); + A[i][j] = static_cast(std::rand() % range - range2); } std::clock_t start_t = std::clock(); From 37728bf1332bee42086672944495ccaecd7915f9 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Mon, 8 Jun 2020 19:48:17 -0400 Subject: [PATCH 388/433] move srand to main() Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- numerical_methods/qr_eigen_values.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/numerical_methods/qr_eigen_values.cpp b/numerical_methods/qr_eigen_values.cpp index 95ace03a79d..4ced8591a2f 100644 --- a/numerical_methods/qr_eigen_values.cpp +++ b/numerical_methods/qr_eigen_values.cpp @@ -28,7 +28,6 @@ using qr_algorithm::operator<<; void create_matrix(std::valarray> *A) { int i, j, tmp, lim2 = LIMS >> 1; int N = A->size(); - std::srand(std::time(nullptr)); #ifdef _OPENMP #pragma omp for @@ -242,6 +241,9 @@ int main(int argc, char **argv) { return -1; } + // initialize random number generator + std::srand(std::time(nullptr)); + int i, rows = mat_size, columns = mat_size; std::valarray> A(rows); From f40165837d764848c2aeff35ba8774d8993807f1 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Mon, 8 Jun 2020 19:50:37 -0400 Subject: [PATCH 389/433] cpplint braces correction Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- numerical_methods/qr_eigen_values.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/numerical_methods/qr_eigen_values.cpp b/numerical_methods/qr_eigen_values.cpp index 4ced8591a2f..991453775e5 100644 --- a/numerical_methods/qr_eigen_values.cpp +++ b/numerical_methods/qr_eigen_values.cpp @@ -227,9 +227,9 @@ void test2() { */ int main(int argc, char **argv) { int mat_size = 5; - if (argc == 2) + if (argc == 2) { mat_size = atoi(argv[1]); - else { // if invalid input argument is given run tests + } else { // if invalid input argument is given run tests test1(); test2(); std::cout << "Usage: ./qr_eigen_values [mat_size]\n"; From 28410ec389e7315fb6d7042408d785c65a7065f5 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Mon, 8 Jun 2020 20:18:44 -0400 Subject: [PATCH 390/433] updated eigen value documentation Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- numerical_methods/qr_eigen_values.cpp | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/numerical_methods/qr_eigen_values.cpp b/numerical_methods/qr_eigen_values.cpp index 991453775e5..f55a1bff391 100644 --- a/numerical_methods/qr_eigen_values.cpp +++ b/numerical_methods/qr_eigen_values.cpp @@ -74,9 +74,24 @@ void mat_mul(const std::valarray> &A, } namespace qr_algorithm { -/** Compute eigen values - * \param[in,out] A matric to compute eigen values for \note This matrix gets - * modified +/** Compute eigen values using iterative shifted QR decomposition algorithm as + * follows: + * 1. Use last diagonal element of A as eigen value approximation \f$c\f$ + * 2. Shift diagonals of matrix \f$A' = A + cI\f$ + * 3. Decompose matrix \f$A'=QR\f$ + * 4. Compute next approximation \f$A'_1 = RQ \f$ + * 5. Shift diagonals back \f$A_1 = A'_1 - cI\f$ + * 6. Termination condition check: last element below diagonal is almost 0 + * 1. If not 0, go back to step 1 with the new approximation \f$A_1\f$ + * 2. If 0, continue to step 7 + * 7. Save last known \f$c\f$ as the eigen value. + * 8. Are all eigen values found? + * 1. If not, remove last row and column of \f$A_1\f$ and go back to step 1. + * 2. If yes, stop. + * + * \note The matrix \f$A\f$ gets modified + * + * \param[in,out] A matrix to compute eigen values for * \param[in] print_intermediates (optional) whether to print intermediate A, Q * and R matrices (default = `false`) */ From 0ef8ec6e9435f48ecad9e5fb648a63119a7e0eca Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Mon, 8 Jun 2020 20:21:56 -0400 Subject: [PATCH 391/433] fix matrix shift doc Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- numerical_methods/qr_eigen_values.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/numerical_methods/qr_eigen_values.cpp b/numerical_methods/qr_eigen_values.cpp index f55a1bff391..581e02e4ea2 100644 --- a/numerical_methods/qr_eigen_values.cpp +++ b/numerical_methods/qr_eigen_values.cpp @@ -77,10 +77,10 @@ namespace qr_algorithm { /** Compute eigen values using iterative shifted QR decomposition algorithm as * follows: * 1. Use last diagonal element of A as eigen value approximation \f$c\f$ - * 2. Shift diagonals of matrix \f$A' = A + cI\f$ + * 2. Shift diagonals of matrix \f$A' = A - cI\f$ * 3. Decompose matrix \f$A'=QR\f$ * 4. Compute next approximation \f$A'_1 = RQ \f$ - * 5. Shift diagonals back \f$A_1 = A'_1 - cI\f$ + * 5. Shift diagonals back \f$A_1 = A'_1 + cI\f$ * 6. Termination condition check: last element below diagonal is almost 0 * 1. If not 0, go back to step 1 with the new approximation \f$A_1\f$ * 2. If 0, continue to step 7 From 40e882f69a7dfe8f258d430f0ce124389cca0e24 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Tue, 9 Jun 2020 10:08:23 -0400 Subject: [PATCH 392/433] rename CONTRIBUTION.md to CONTRIBUTING.md #836 --- .github/pull_request_template.md | 6 +++--- CONTRIBUTION.md => CONTRIBUTING.md | 0 README.md | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) rename CONTRIBUTION.md => CONTRIBUTING.md (100%) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index efaaf3765d4..ef1f9ad0320 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -3,17 +3,17 @@ Thank you for your Pull Request. Please provide a description above and review the requirements below. -Contributors guide: https://github.com/TheAlgorithms/C-Plus-Plus/CONTRIBUTION.md +Contributors guide: https://github.com/TheAlgorithms/C-Plus-Plus/CONTRIBUTING.md --> #### Checklist - [ ] Added description of change -- [ ] Added file name matches [File name guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTION.md#New-File-Name-guidelines) +- [ ] Added file name matches [File name guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTING.md#New-File-Name-guidelines) - [ ] Added tests and example, test must pass - [ ] Relevant documentation/comments is changed or added -- [ ] PR title follows semantic [commit guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTION.md#Commit-Guidelines) +- [ ] PR title follows semantic [commit guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTING.md#Commit-Guidelines) - [ ] Search previous suggestions before making a new one, as yours may be a duplicate. - [ ] Sort by alphabetical order - [ ] I acknowledge that all my contributions will be made under the project's license. diff --git a/CONTRIBUTION.md b/CONTRIBUTING.md similarity index 100% rename from CONTRIBUTION.md rename to CONTRIBUTING.md diff --git a/README.md b/README.md index 8dd6a92df30..453a546fda8 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # The Algorithms - C++ # {#mainpage} -![contributions welcome](https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square)] +![contributions welcome](https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square)] ![GitHub repo size](https://img.shields.io/github/repo-size/kvedala/C-Plus-Plus?color=red&style=flat-square) ![GitHub closed pull requests](https://img.shields.io/github/issues-pr-closed/kvedala/C-Plus-Plus?color=green&style=flat-square) ![Doxygen CI](https://github.com/kvedala/C-Plus-Plus/workflows/Doxygen%20CI/badge.svg) @@ -14,4 +14,4 @@ Click on [Files menu](https://kvedala.github.io/C-Plus-Plus/files.html) to see t The implementations are for learning purpose. They may be less efficient than the implementation in the standard library. ### Contribute Guidelines -Read our [Contribution Guidelines](https://github.com/kvedala/C-Plus-Plus/blob/master/CONTRIBUTION.md) before you contribute. +Read our [Contribution Guidelines](https://github.com/kvedala/C-Plus-Plus/blob/master/CONTRIBUTING.md) before you contribute. From f32091d6909821902eda715c5b007b6bbaf2878b Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Tue, 9 Jun 2020 10:25:49 -0400 Subject: [PATCH 393/433] remove 'sort alphabetical order' check --- .github/pull_request_template.md | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index ef1f9ad0320..83bacbca40e 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -15,7 +15,6 @@ Contributors guide: https://github.com/TheAlgorithms/C-Plus-Plus/CONTRIBUTING.md - [ ] Relevant documentation/comments is changed or added - [ ] PR title follows semantic [commit guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTING.md#Commit-Guidelines) - [ ] Search previous suggestions before making a new one, as yours may be a duplicate. -- [ ] Sort by alphabetical order - [ ] I acknowledge that all my contributions will be made under the project's license. Notes: \ No newline at end of file From eff0b7abe9103759be41e2fc56e1d7bc61cc3756 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Tue, 9 Jun 2020 10:26:12 -0400 Subject: [PATCH 394/433] added documentation check --- .github/pull_request_template.md | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 83bacbca40e..f8135639907 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -12,6 +12,7 @@ Contributors guide: https://github.com/TheAlgorithms/C-Plus-Plus/CONTRIBUTING.md - [ ] Added description of change - [ ] Added file name matches [File name guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTING.md#New-File-Name-guidelines) - [ ] Added tests and example, test must pass +- [ ] Added documentation so that the program is self-explanatory and educational - [Doxygen guidelines](https://www.doxygen.nl/manual/docblocks.html) - [ ] Relevant documentation/comments is changed or added - [ ] PR title follows semantic [commit guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTING.md#Commit-Guidelines) - [ ] Search previous suggestions before making a new one, as yours may be a duplicate. From 3dda8a9e5b96a54b4564c338e331bfe238e5cc0d Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Tue, 9 Jun 2020 10:56:44 -0400 Subject: [PATCH 395/433] remove extra paranthesis --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 453a546fda8..276f4f8470b 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # The Algorithms - C++ # {#mainpage} -![contributions welcome](https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square)] +![contributions welcome](https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square) ![GitHub repo size](https://img.shields.io/github/repo-size/kvedala/C-Plus-Plus?color=red&style=flat-square) ![GitHub closed pull requests](https://img.shields.io/github/issues-pr-closed/kvedala/C-Plus-Plus?color=green&style=flat-square) ![Doxygen CI](https://github.com/kvedala/C-Plus-Plus/workflows/Doxygen%20CI/badge.svg) From 167132fe94c409c3873776f2f485cf441ac8eb2e Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Tue, 9 Jun 2020 14:24:55 -0400 Subject: [PATCH 396/433] added gitpod --- .gitpod.yml | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .gitpod.yml diff --git a/.gitpod.yml b/.gitpod.yml new file mode 100644 index 00000000000..c0720dcb5a4 --- /dev/null +++ b/.gitpod.yml @@ -0,0 +1,6 @@ +tasks: +- init: > + pip install cpplint + cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON && + cmake --build build -t all + \ No newline at end of file From 7337fe6bbb69bbde6ea2cd1b53ef558f323b8334 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Tue, 9 Jun 2020 14:28:55 -0400 Subject: [PATCH 397/433] added gitpod link from README --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 276f4f8470b..37f823f7f82 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,6 @@ # The Algorithms - C++ # {#mainpage} - +[![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/TheAlgorithms/C-Plus-Plus) +[![Gitter chat](https://img.shields.io/badge/Chat-Gitter-ff69b4.svg?label=Chat&logo=gitter&style=flat-square)](https://gitter.im/TheAlgorithms) ![contributions welcome](https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square) ![GitHub repo size](https://img.shields.io/github/repo-size/kvedala/C-Plus-Plus?color=red&style=flat-square) ![GitHub closed pull requests](https://img.shields.io/github/issues-pr-closed/kvedala/C-Plus-Plus?color=green&style=flat-square) From 8d7942fff669bc7d8b72c8de4fdaf69c75da8b1b Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Tue, 9 Jun 2020 17:27:17 -0400 Subject: [PATCH 398/433] attempt to add vscode gitpod extensions --- .gitpod.yml | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/.gitpod.yml b/.gitpod.yml index c0720dcb5a4..e6d4e7ea3dc 100644 --- a/.gitpod.yml +++ b/.gitpod.yml @@ -1,6 +1,9 @@ tasks: -- init: > - pip install cpplint - cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON && - cmake --build build -t all - \ No newline at end of file + - init: > + pip install cpplint + cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON && + cmake --build build -t all +vscode: + extensions: + - twxs.cmake@0.0.17 + -ms-vscode.cpptools@0.28.3 \ No newline at end of file From 9ab3e0b945f4a4d403206a1e1e76162407731f0b Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Tue, 9 Jun 2020 17:31:42 -0400 Subject: [PATCH 399/433] update gitpod extensions --- .gitpod.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.gitpod.yml b/.gitpod.yml index e6d4e7ea3dc..8fba6806f61 100644 --- a/.gitpod.yml +++ b/.gitpod.yml @@ -5,5 +5,5 @@ tasks: cmake --build build -t all vscode: extensions: - - twxs.cmake@0.0.17 - -ms-vscode.cpptools@0.28.3 \ No newline at end of file + - ms-vscode.cpptools@0.28.3:mjRj37VUK0nY2ZeDXzxOJA== + - twxs.cmake@0.0.17:9s7m9CWOr6i6NZ7CNNF4kw== \ No newline at end of file From ebd04b3ba3540cc61877c021582001d0d05697c4 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Tue, 9 Jun 2020 17:42:09 -0400 Subject: [PATCH 400/433] add gitpod extensions cmake-tools and git-graph --- .gitpod.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.gitpod.yml b/.gitpod.yml index 8fba6806f61..57cfd4f5f65 100644 --- a/.gitpod.yml +++ b/.gitpod.yml @@ -6,4 +6,6 @@ tasks: vscode: extensions: - ms-vscode.cpptools@0.28.3:mjRj37VUK0nY2ZeDXzxOJA== - - twxs.cmake@0.0.17:9s7m9CWOr6i6NZ7CNNF4kw== \ No newline at end of file + - twxs.cmake@0.0.17:9s7m9CWOr6i6NZ7CNNF4kw== + - ms-vscode.cmake-tools@1.4.0:eP3hU/MFme+CcSL21Klk1w== + - mhutchie.git-graph@1.23.0:TM9ShNmBn94aUJMJusCJlg== \ No newline at end of file From 8309630a9ac9d64d67736d29fc44d650cf780c5b Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Tue, 9 Jun 2020 17:47:05 -0400 Subject: [PATCH 401/433] remove gitpod init and add commands --- .gitpod.yml | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/.gitpod.yml b/.gitpod.yml index 57cfd4f5f65..7067ce3ce70 100644 --- a/.gitpod.yml +++ b/.gitpod.yml @@ -1,8 +1,9 @@ tasks: - - init: > - pip install cpplint - cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON && - cmake --build build -t all + - command: pip install cpplint + name: Install CPPLINT + - command: cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON + name: Configure project + vscode: extensions: - ms-vscode.cpptools@0.28.3:mjRj37VUK0nY2ZeDXzxOJA== From e9a4b2c96eaa320fd22ba5ef6ad87e6f6c894995 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Tue, 9 Jun 2020 17:58:51 -0400 Subject: [PATCH 402/433] use init to one time install doxygen, graphviz, cpplint --- .gitpod.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitpod.yml b/.gitpod.yml index 7067ce3ce70..1dac3536f6b 100644 --- a/.gitpod.yml +++ b/.gitpod.yml @@ -1,5 +1,5 @@ tasks: - - command: pip install cpplint + - init: sudo apt -qq update && sudo apt -qq install doxygen graphviz && pip install cpplint name: Install CPPLINT - command: cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON name: Configure project From 5cc9e6c611a79377037ccf328e2e0ef069f79e39 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Tue, 9 Jun 2020 18:08:08 -0400 Subject: [PATCH 403/433] use gitpod dockerfile --- .gitpod.dockerfile | 8 ++++++++ .gitpod.yml | 5 +++-- 2 files changed, 11 insertions(+), 2 deletions(-) create mode 100644 .gitpod.dockerfile diff --git a/.gitpod.dockerfile b/.gitpod.dockerfile new file mode 100644 index 00000000000..d0c93123a1e --- /dev/null +++ b/.gitpod.dockerfile @@ -0,0 +1,8 @@ +FROM gitpod/workspace-full + +RUN sudo apt-get update \ + && sudo apt-get install -y \ + doxygen \ + graphviz \ + && pip install cpplint \ + && sudo rm -rf /var/lib/apt/lists/* diff --git a/.gitpod.yml b/.gitpod.yml index 1dac3536f6b..0b0b227d58d 100644 --- a/.gitpod.yml +++ b/.gitpod.yml @@ -1,6 +1,7 @@ +image: + file: .gitpod.dockerfile + tasks: - - init: sudo apt -qq update && sudo apt -qq install doxygen graphviz && pip install cpplint - name: Install CPPLINT - command: cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON name: Configure project From e54c6f663e3853a473187d019a5a1134ae5e16d9 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Tue, 9 Jun 2020 18:27:18 -0400 Subject: [PATCH 404/433] add ninja build system to docker --- .gitpod.dockerfile | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitpod.dockerfile b/.gitpod.dockerfile index d0c93123a1e..6d6a4e895f4 100644 --- a/.gitpod.dockerfile +++ b/.gitpod.dockerfile @@ -4,5 +4,6 @@ RUN sudo apt-get update \ && sudo apt-get install -y \ doxygen \ graphviz \ + ninja-build \ && pip install cpplint \ && sudo rm -rf /var/lib/apt/lists/* From de118604f2bf638f77eb0c994836855b2274c77d Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Tue, 9 Jun 2020 18:40:40 -0400 Subject: [PATCH 405/433] remove configure task --- .gitpod.yml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.gitpod.yml b/.gitpod.yml index 0b0b227d58d..6f977563a7f 100644 --- a/.gitpod.yml +++ b/.gitpod.yml @@ -1,10 +1,6 @@ image: file: .gitpod.dockerfile -tasks: - - command: cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON - name: Configure project - vscode: extensions: - ms-vscode.cpptools@0.28.3:mjRj37VUK0nY2ZeDXzxOJA== From d95d24d1714770debe2a40ffb3c9d140f1ca371f Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Tue, 9 Jun 2020 19:43:56 -0400 Subject: [PATCH 406/433] add github prebuild specs to gitpod --- .gitpod.yml | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/.gitpod.yml b/.gitpod.yml index 6f977563a7f..bdce4619d1c 100644 --- a/.gitpod.yml +++ b/.gitpod.yml @@ -1,9 +1,17 @@ image: file: .gitpod.dockerfile +github: + prebuilds: + addBadge: true + addComment: true + addCheck: false + master: true + pullRequestsFromForks: true + vscode: extensions: - ms-vscode.cpptools@0.28.3:mjRj37VUK0nY2ZeDXzxOJA== - twxs.cmake@0.0.17:9s7m9CWOr6i6NZ7CNNF4kw== - ms-vscode.cmake-tools@1.4.0:eP3hU/MFme+CcSL21Klk1w== - - mhutchie.git-graph@1.23.0:TM9ShNmBn94aUJMJusCJlg== \ No newline at end of file + - mhutchie.git-graph@1.23.0:TM9ShNmBn94aUJMJusCJlg== From 5ce038218837b752532fa8db7fbd522b44ff2bad Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Tue, 9 Jun 2020 19:47:50 -0400 Subject: [PATCH 407/433] disable gitpod addcommit --- .gitpod.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitpod.yml b/.gitpod.yml index bdce4619d1c..40750258c2a 100644 --- a/.gitpod.yml +++ b/.gitpod.yml @@ -4,7 +4,7 @@ image: github: prebuilds: addBadge: true - addComment: true + addComment: false addCheck: false master: true pullRequestsFromForks: true From a240f242c8c70690595c2a33670fadad0469164b Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Wed, 10 Jun 2020 09:52:56 -0400 Subject: [PATCH 408/433] update documentation for kohonen_som --- machine_learning/kohonen_som_trace.cpp | 33 ++++++++++++++++++++------ 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/machine_learning/kohonen_som_trace.cpp b/machine_learning/kohonen_som_trace.cpp index 31e9421bf92..1a39ce58a55 100644 --- a/machine_learning/kohonen_som_trace.cpp +++ b/machine_learning/kohonen_som_trace.cpp @@ -162,7 +162,12 @@ void kohonen_som_tracer(const std::vector> &X, /** Creates a random set of points distributed *near* the circumference * of a circle and trains an SOM that finds that circular pattern. The * generating function is - * \f{eqnarray*}{ \f} + * \f{eqnarray*}{ + * r &\in& [1-\delta r, 1+\delta r)\\ + * \theta &\in& [0, 2\pi)\\ + * x &=& r\cos\theta\\ + * y &=& r\sin\theta + * \f} * * \param[out] data matrix to store data in */ @@ -234,8 +239,15 @@ void test1() { /** Creates a random set of points distributed *near* the locus * of the [Lamniscate of - * Gerono](https://en.wikipedia.org/wiki/Lemniscate_of_Gerono) and trains an SOM - * that finds that circular pattern. + * Gerono](https://en.wikipedia.org/wiki/Lemniscate_of_Gerono). + * \f{eqnarray*}{ + * \delta r &=& 0.2\\ + * \delta x &\in& [-\delta r, \delta r)\\ + * \delta y &\in& [-\delta r, \delta r)\\ + * \theta &\in& [0, \pi)\\ + * x &=& \delta x + \cos\theta\\ + * y &=& \delta y + \frac{\sin(2\theta)}{2} + * \f} * \param[out] data matrix to store data in */ void test_lamniscate(std::vector> *data) { @@ -305,10 +317,17 @@ void test2() { save_nd_data("w22.csv", W); // save the resultant weights } -/** Creates a random set of points distributed *near* the locus - * of the [Lamniscate of - * Gerono](https://en.wikipedia.org/wiki/Lemniscate_of_Gerono) and trains an SOM - * that finds that circular pattern. +/** Creates a random set of points distributed in six clusters in + * 3D space with centroids at the points + * * \f${0.5, 0.5, 0.5}\f$ + * * \f${0.5, 0.5, -0.5}\f$ + * * \f${0.5, -0.5, 0.5}\f$ + * * \f${0.5, -0.5, -0.5}\f$ + * * \f${-0.5, 0.5, 0.5}\f$ + * * \f${-0.5, 0.5, -0.5}\f$ + * * \f${-0.5, -0.5, 0.5}\f$ + * * \f${-0.5, -0.5, -0.5}\f$ + * * \param[out] data matrix to store data in */ void test_3d_classes(std::vector> *data) { From 4699bda90a679325ef940f29b48c036feadf222e Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 11 Jun 2020 08:20:04 -0400 Subject: [PATCH 409/433] added ode solve using forward euler method --- numerical_methods/ode_forward_euler.cpp | 207 ++++++++++++++++++++++++ 1 file changed, 207 insertions(+) create mode 100644 numerical_methods/ode_forward_euler.cpp diff --git a/numerical_methods/ode_forward_euler.cpp b/numerical_methods/ode_forward_euler.cpp new file mode 100644 index 00000000000..e289d96e736 --- /dev/null +++ b/numerical_methods/ode_forward_euler.cpp @@ -0,0 +1,207 @@ +/** + * \file + * \authors [Krishna Vedala](https://github.com/kvedala) + * \brief Solve a multivariable first order [ordinary differential equation + * (ODEs)](https://en.wikipedia.org/wiki/Ordinary_differential_equation) using + * [forward Euler + * method](https://en.wikipedia.org/wiki/Numerical_methods_for_ordinary_differential_equations#Euler_method) + * + * \details + * The ODE being solved is: + * \f{eqnarray*}{ + * \dot{u} &=& v\\ + * \dot{v} &=& -\omega^2 u\\ + * \omega &=& 1\\ + * [x_0, u_0, v_0] &=& [0,1,0]\qquad\ldots\text{(initial values)} + * \f} + * The exact solution for the above problem is: + * \f{eqnarray*}{ + * u(x) &=& \cos(x)\\ + * v(x) &=& -\sin(x)\\ + * \f} + * The computation results are stored to a text file `forward_euler.csv` and the + * exact soltuion results in `exact.csv` for comparison. + * Implementation solution + * + * To implement [Van der Pol + * oscillator](https://en.wikipedia.org/wiki/Van_der_Pol_oscillator), change the + * ::problem function to: + * ```cpp + * const double mu = 2.0; + * dy[0] = y[1]; + * dy[1] = mu * (1.f - y[0] * y[0]) * y[1] - y[0]; + * ``` + * \see ode_midpoint_euler.cpp, ode_semi_implicit_euler.cpp + */ + +#include +#include +#include +#include +#include + +/** + * @brief Problem statement for a system with first-order differential + * equations. Updates the system differential variables. + * \note This function can be updated to and ode of any order. + * + * @param[in] x independent variable(s) + * @param[in,out] y dependent variable(s) + * @param[in,out] dy first-derivative of dependent variable(s) + */ +void problem(const double &x, std::valarray *y, + std::valarray *dy) { + const double omega = 1.F; // some const for the problem + dy[0][0] = y[0][1]; // x dot + dy[0][1] = -omega * omega * y[0][0]; // y dot +} + +/** + * @brief Exact solution of the problem. Used for solution comparison. + * + * @param[in] x independent variable + * @param[in,out] y dependent variable + */ +void exact_solution(const double &x, std::valarray *y) { + y[0][0] = std::cos(x); + y[0][1] = -std::sin(x); +} + +/** \addtogroup ode Ordinary Differential Equations + * @{ + */ +/** + * @brief Compute next step approximation using the forward-Euler + * method. @f[y_{n+1}=y_n + dx\cdot f\left(x_n,y_n\right)@f] + * @param[in] dx step size + * @param[in] x take \f$x_n\f$ and compute \f$x_{n+1}\f$ + * @param[in,out] y take \f$y_n\f$ and compute \f$y_{n+1}\f$ + * @param[in,out] dy compute \f$f\left(x_n,y_n\right)\f$ + */ +void forward_euler_step(const double dx, const double &x, + std::valarray *y, std::valarray *dy) { + problem(x, y, dy); + y[0] += dy[0] * dx; +} + +/** + * @brief Compute approximation using the forward-Euler + * method in the given limits. + * @param[in] dx step size + * @param[in] x0 initial value of independent variable + * @param[in] x_max final value of independent variable + * @param[in,out] y take \f$y_n\f$ and compute \f$y_{n+1}\f$ + * @param[in] save_to_file flag to save results to a CSV file (1) or not (0) + * @returns time taken for computation in seconds + */ +double forward_euler(double dx, double x0, double x_max, + std::valarray *y, bool save_to_file = false) { + std::valarray dy = y[0]; + + std::ofstream fp; + if (save_to_file) { + fp.open("forward_euler.csv", std::ofstream::out); + if (!fp.is_open()) { + std::perror("Error! "); + } + } + + std::size_t L = y->size(); + + /* start integration */ + std::clock_t t1 = std::clock(); + double x = x0; + do // iterate for each step of independent variable + { + if (save_to_file && fp.is_open()) { + // write to file + fp << x << ","; + for (int i = 0; i < L - 1; i++) { + fp << y[0][i] << ","; + } + fp << y[0][L - 1] << "\n"; + } + + forward_euler_step(dx, x, y, &dy); // perform integration + x += dx; // update step + } while (x <= x_max); // till upper limit of independent variable + /* end of integration */ + std::clock_t t2 = std::clock(); + + if (fp.is_open()) + fp.close(); + + return static_cast(t2 - t1) / CLOCKS_PER_SEC; +} + +/** @} */ + +/** + * Function to compute and save exact solution for comparison + * + * \param [in] X0 initial value of independent variable + * \param [in] X_MAX final value of independent variable + * \param [in] step_size independent variable step size + * \param [in] Y0 initial values of dependent variables + */ +void save_exact_solution(const double &X0, const double &X_MAX, + const double &step_size, + const std::valarray &Y0) { + double x = X0; + std::valarray y = Y0; + + std::ofstream fp("exact.csv", std::ostream::out); + if (!fp.is_open()) { + std::perror("Error! "); + return; + } + std::cout << "Finding exact solution\n"; + + std::clock_t t1 = std::clock(); + do { + fp << x << ","; + for (int i = 0; i < y.size() - 1; i++) { + fp << y[i] << ","; + } + fp << y[y.size() - 1] << "\n"; + + exact_solution(x, &y); + + x += step_size; + } while (x <= X_MAX); + + std::clock_t t2 = std::clock(); + double total_time = static_cast(t2 - t1) / CLOCKS_PER_SEC; + std::cout << "\tTime = " << total_time << " ms\n"; + + fp.close(); +} + +/** + * Main Function + */ +int main(int argc, char *argv[]) { + double X0 = 0.f; /* initial value of x0 */ + double X_MAX = 10.F; /* upper limit of integration */ + std::valarray Y0 = {1.f, 0.f}; /* initial value Y = y(x = x_0) */ + double step_size; + + if (argc == 1) { + std::cout << "\nEnter the step size: "; + std::cin >> step_size; + } else { + // use commandline argument as independent variable step size + step_size = std::atof(argv[1]); + } + + // get approximate solution + double total_time = forward_euler(step_size, X0, X_MAX, &Y0, true); + std::cout << "\tTime = " << total_time << " ms\n"; + + /* compute exact solution for comparion */ + save_exact_solution(X0, X_MAX, step_size, Y0); + + return 0; +} From 3f4b60ea07c9fee6b6119a1638d5b5ba3455d063 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 11 Jun 2020 08:30:59 -0400 Subject: [PATCH 410/433] added mid-point euler ode solver --- numerical_methods/ode_midpoint_euler.cpp | 215 +++++++++++++++++++++++ 1 file changed, 215 insertions(+) create mode 100644 numerical_methods/ode_midpoint_euler.cpp diff --git a/numerical_methods/ode_midpoint_euler.cpp b/numerical_methods/ode_midpoint_euler.cpp new file mode 100644 index 00000000000..20aaf01f84b --- /dev/null +++ b/numerical_methods/ode_midpoint_euler.cpp @@ -0,0 +1,215 @@ +/** + * \file + * \authors [Krishna Vedala](https://github.com/kvedala) + * \brief Solve a multivariable first order [ordinary differential equation + * (ODEs)](https://en.wikipedia.org/wiki/Ordinary_differential_equation) using + * [midpoint Euler + * method](https://en.wikipedia.org/wiki/Midpoint_method) + * + * \details + * The ODE being solved is: + * \f{eqnarray*}{ + * \dot{u} &=& v\\ + * \dot{v} &=& -\omega^2 u\\ + * \omega &=& 1\\ + * [x_0, u_0, v_0] &=& [0,1,0]\qquad\ldots\text{(initial values)} + * \f} + * The exact solution for the above problem is: + * \f{eqnarray*}{ + * u(x) &=& \cos(x)\\ + * v(x) &=& -\sin(x)\\ + * \f} + * The computation results are stored to a text file `midpoint_euler.csv` and + * the exact soltuion results in `exact.csv` for comparison. Implementation solution + * + * To implement [Van der Pol + * oscillator](https://en.wikipedia.org/wiki/Van_der_Pol_oscillator), change the + * ::problem function to: + * ```cpp + * const double mu = 2.0; + * dy[0] = y[1]; + * dy[1] = mu * (1.f - y[0] * y[0]) * y[1] - y[0]; + * ``` + * \see ode_midpoint_euler.cpp, ode_semi_implicit_euler.cpp + */ + +#include +#include +#include +#include +#include + +/** + * @brief Problem statement for a system with first-order differential + * equations. Updates the system differential variables. + * \note This function can be updated to and ode of any order. + * + * @param[in] x independent variable(s) + * @param[in,out] y dependent variable(s) + * @param[in,out] dy first-derivative of dependent variable(s) + */ +void problem(const double &x, std::valarray *y, + std::valarray *dy) { + const double omega = 1.F; // some const for the problem + dy[0][0] = y[0][1]; // x dot + dy[0][1] = -omega * omega * y[0][0]; // y dot +} + +/** + * @brief Exact solution of the problem. Used for solution comparison. + * + * @param[in] x independent variable + * @param[in,out] y dependent variable + */ +void exact_solution(const double &x, std::valarray *y) { + y[0][0] = std::cos(x); + y[0][1] = -std::sin(x); +} + +/** \addtogroup ode Ordinary Differential Equations + * @{ + */ +/** + * @brief Compute next step approximation using the midpoint-Euler + * method. @f[y_{n+1}=y_n + dx\cdot f\left(x_n,y_n\right)@f] + * @param[in] dx step size + * @param[in] x take \f$x_n\f$ and compute \f$x_{n+1}\f$ + * @param[in,out] y take \f$y_n\f$ and compute \f$y_{n+1}\f$ + * @param[in,out] dy compute \f$f\left(x_n,y_n\right)\f$ + */ +void midpoint_euler_step(const double dx, const double &x, + std::valarray *y, std::valarray *dy) { + problem(x, y, dy); + y[0] += dy[0] * dx; + + problem(x, y, dy); + double tmp_x = x + 0.5 * dx; + + std::valarray tmp_y = y[0] + dy[0] * (0.5 * dx); + + problem(tmp_x, &tmp_y, dy); + + y[0] += dy[0] * dx; +} + +/** + * @brief Compute approximation using the midpoint-Euler + * method in the given limits. + * @param[in] dx step size + * @param[in] x0 initial value of independent variable + * @param[in] x_max final value of independent variable + * @param[in,out] y take \f$y_n\f$ and compute \f$y_{n+1}\f$ + * @param[in] save_to_file flag to save results to a CSV file (1) or not (0) + * @returns time taken for computation in seconds + */ +double midpoint_euler(double dx, double x0, double x_max, + std::valarray *y, bool save_to_file = false) { + std::valarray dy = y[0]; + + std::ofstream fp; + if (save_to_file) { + fp.open("midpoint_euler.csv", std::ofstream::out); + if (!fp.is_open()) { + std::perror("Error! "); + } + } + + std::size_t L = y->size(); + + /* start integration */ + std::clock_t t1 = std::clock(); + double x = x0; + do // iterate for each step of independent variable + { + if (save_to_file && fp.is_open()) { + // write to file + fp << x << ","; + for (int i = 0; i < L - 1; i++) { + fp << y[0][i] << ","; + } + fp << y[0][L - 1] << "\n"; + } + + midpoint_euler_step(dx, x, y, &dy); // perform integration + x += dx; // update step + } while (x <= x_max); // till upper limit of independent variable + /* end of integration */ + std::clock_t t2 = std::clock(); + + if (fp.is_open()) + fp.close(); + + return static_cast(t2 - t1) / CLOCKS_PER_SEC; +} + +/** @} */ + +/** + * Function to compute and save exact solution for comparison + * + * \param [in] X0 initial value of independent variable + * \param [in] X_MAX final value of independent variable + * \param [in] step_size independent variable step size + * \param [in] Y0 initial values of dependent variables + */ +void save_exact_solution(const double &X0, const double &X_MAX, + const double &step_size, + const std::valarray &Y0) { + double x = X0; + std::valarray y = Y0; + + std::ofstream fp("exact.csv", std::ostream::out); + if (!fp.is_open()) { + std::perror("Error! "); + return; + } + std::cout << "Finding exact solution\n"; + + std::clock_t t1 = std::clock(); + do { + fp << x << ","; + for (int i = 0; i < y.size() - 1; i++) { + fp << y[i] << ","; + } + fp << y[y.size() - 1] << "\n"; + + exact_solution(x, &y); + + x += step_size; + } while (x <= X_MAX); + + std::clock_t t2 = std::clock(); + double total_time = static_cast(t2 - t1) / CLOCKS_PER_SEC; + std::cout << "\tTime = " << total_time << " ms\n"; + + fp.close(); +} + +/** + * Main Function + */ +int main(int argc, char *argv[]) { + double X0 = 0.f; /* initial value of x0 */ + double X_MAX = 10.F; /* upper limit of integration */ + std::valarray Y0 = {1.f, 0.f}; /* initial value Y = y(x = x_0) */ + double step_size; + + if (argc == 1) { + std::cout << "\nEnter the step size: "; + std::cin >> step_size; + } else { + // use commandline argument as independent variable step size + step_size = std::atof(argv[1]); + } + + // get approximate solution + double total_time = midpoint_euler(step_size, X0, X_MAX, &Y0, true); + std::cout << "\tTime = " << total_time << " ms\n"; + + /* compute exact solution for comparion */ + save_exact_solution(X0, X_MAX, step_size, Y0); + + return 0; +} From 5a46e432195fda5a488de3cb472bff3a19c157fd Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 11 Jun 2020 08:46:20 -0400 Subject: [PATCH 411/433] fixed itegration step equation --- numerical_methods/ode_midpoint_euler.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/numerical_methods/ode_midpoint_euler.cpp b/numerical_methods/ode_midpoint_euler.cpp index 20aaf01f84b..4b7c47a8809 100644 --- a/numerical_methods/ode_midpoint_euler.cpp +++ b/numerical_methods/ode_midpoint_euler.cpp @@ -32,7 +32,7 @@ * dy[0] = y[1]; * dy[1] = mu * (1.f - y[0] * y[0]) * y[1] - y[0]; * ``` - * \see ode_midpoint_euler.cpp, ode_semi_implicit_euler.cpp + * \see ode_forward_euler.cpp, ode_semi_implicit_euler.cpp */ #include @@ -73,7 +73,10 @@ void exact_solution(const double &x, std::valarray *y) { */ /** * @brief Compute next step approximation using the midpoint-Euler - * method. @f[y_{n+1}=y_n + dx\cdot f\left(x_n,y_n\right)@f] + * method. + * @f[y_{n+1} = y_n + dx\, f\left(x_n+\frac{1}{2}dx, + * y_n + \frac{1}{2}dx\,f\left(x_n,y_n\right)\right)@f] + * * @param[in] dx step size * @param[in] x take \f$x_n\f$ and compute \f$x_{n+1}\f$ * @param[in,out] y take \f$y_n\f$ and compute \f$y_{n+1}\f$ @@ -81,9 +84,6 @@ void exact_solution(const double &x, std::valarray *y) { */ void midpoint_euler_step(const double dx, const double &x, std::valarray *y, std::valarray *dy) { - problem(x, y, dy); - y[0] += dy[0] * dx; - problem(x, y, dy); double tmp_x = x + 0.5 * dx; From 6b83dd2fbe503947c381e0644f79d8aee2715fcb Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 11 Jun 2020 08:46:47 -0400 Subject: [PATCH 412/433] added semi-implicit euler ODE solver --- numerical_methods/ode_semi_implicit_euler.cpp | 214 ++++++++++++++++++ 1 file changed, 214 insertions(+) create mode 100644 numerical_methods/ode_semi_implicit_euler.cpp diff --git a/numerical_methods/ode_semi_implicit_euler.cpp b/numerical_methods/ode_semi_implicit_euler.cpp new file mode 100644 index 00000000000..45be225307a --- /dev/null +++ b/numerical_methods/ode_semi_implicit_euler.cpp @@ -0,0 +1,214 @@ +/** + * \file + * \authors [Krishna Vedala](https://github.com/kvedala) + * \brief Solve a multivariable first order [ordinary differential equation + * (ODEs)](https://en.wikipedia.org/wiki/Ordinary_differential_equation) using + * [semi implicit Euler + * method](https://en.wikipedia.org/wiki/Semi-implicit_Euler_method) + * + * \details + * The ODE being solved is: + * \f{eqnarray*}{ + * \dot{u} &=& v\\ + * \dot{v} &=& -\omega^2 u\\ + * \omega &=& 1\\ + * [x_0, u_0, v_0] &=& [0,1,0]\qquad\ldots\text{(initial values)} + * \f} + * The exact solution for the above problem is: + * \f{eqnarray*}{ + * u(x) &=& \cos(x)\\ + * v(x) &=& -\sin(x)\\ + * \f} + * The computation results are stored to a text file `semi_implicit_euler.csv` + * and the exact soltuion results in `exact.csv` for comparison. Implementation solution + * + * To implement [Van der Pol + * oscillator](https://en.wikipedia.org/wiki/Van_der_Pol_oscillator), change the + * ::problem function to: + * ```cpp + * const double mu = 2.0; + * dy[0] = y[1]; + * dy[1] = mu * (1.f - y[0] * y[0]) * y[1] - y[0]; + * ``` + * \see ode_midpoint_euler.cpp, ode_forward_euler.cpp + */ + +#include +#include +#include +#include +#include + +/** + * @brief Problem statement for a system with first-order differential + * equations. Updates the system differential variables. + * \note This function can be updated to and ode of any order. + * + * @param[in] x independent variable(s) + * @param[in,out] y dependent variable(s) + * @param[in,out] dy first-derivative of dependent variable(s) + */ +void problem(const double &x, std::valarray *y, + std::valarray *dy) { + const double omega = 1.F; // some const for the problem + dy[0][0] = y[0][1]; // x dot + dy[0][1] = -omega * omega * y[0][0]; // y dot +} + +/** + * @brief Exact solution of the problem. Used for solution comparison. + * + * @param[in] x independent variable + * @param[in,out] y dependent variable + */ +void exact_solution(const double &x, std::valarray *y) { + y[0][0] = std::cos(x); + y[0][1] = -std::sin(x); +} + +/** \addtogroup ode Ordinary Differential Equations + * @{ + */ +/** + * @brief Compute next step approximation using the semi-implicit-Euler + * method. @f[y_{n+1}=y_n + dx\cdot f\left(x_n,y_n\right)@f] + * @param[in] dx step size + * @param[in] x take \f$x_n\f$ and compute \f$x_{n+1}\f$ + * @param[in,out] y take \f$y_n\f$ and compute \f$y_{n+1}\f$ + * @param[in,out] dy compute \f$f\left(x_n,y_n\right)\f$ + */ +void semi_implicit_euler_step(const double dx, const double &x, + std::valarray *y, + std::valarray *dy) { + problem(x, y, dy); + double tmp_x = x + 0.5 * dx; + + std::valarray tmp_y = y[0] + dy[0] * (0.5 * dx); + + problem(tmp_x, &tmp_y, dy); + + y[0] += dy[0] * dx; +} + +/** + * @brief Compute approximation using the semi-implicit-Euler + * method in the given limits. + * @param[in] dx step size + * @param[in] x0 initial value of independent variable + * @param[in] x_max final value of independent variable + * @param[in,out] y take \f$y_n\f$ and compute \f$y_{n+1}\f$ + * @param[in] save_to_file flag to save results to a CSV file (1) or not (0) + * @returns time taken for computation in seconds + */ +double semi_implicit_euler(double dx, double x0, double x_max, + std::valarray *y, + bool save_to_file = false) { + std::valarray dy = y[0]; + + std::ofstream fp; + if (save_to_file) { + fp.open("semi_implicit_euler.csv", std::ofstream::out); + if (!fp.is_open()) { + std::perror("Error! "); + } + } + + std::size_t L = y->size(); + + /* start integration */ + std::clock_t t1 = std::clock(); + double x = x0; + do // iterate for each step of independent variable + { + if (save_to_file && fp.is_open()) { + // write to file + fp << x << ","; + for (int i = 0; i < L - 1; i++) { + fp << y[0][i] << ","; + } + fp << y[0][L - 1] << "\n"; + } + + semi_implicit_euler_step(dx, x, y, &dy); // perform integration + x += dx; // update step + } while (x <= x_max); // till upper limit of independent variable + /* end of integration */ + std::clock_t t2 = std::clock(); + + if (fp.is_open()) + fp.close(); + + return static_cast(t2 - t1) / CLOCKS_PER_SEC; +} + +/** @} */ + +/** + * Function to compute and save exact solution for comparison + * + * \param [in] X0 initial value of independent variable + * \param [in] X_MAX final value of independent variable + * \param [in] step_size independent variable step size + * \param [in] Y0 initial values of dependent variables + */ +void save_exact_solution(const double &X0, const double &X_MAX, + const double &step_size, + const std::valarray &Y0) { + double x = X0; + std::valarray y = Y0; + + std::ofstream fp("exact.csv", std::ostream::out); + if (!fp.is_open()) { + std::perror("Error! "); + return; + } + std::cout << "Finding exact solution\n"; + + std::clock_t t1 = std::clock(); + do { + fp << x << ","; + for (int i = 0; i < y.size() - 1; i++) { + fp << y[i] << ","; + } + fp << y[y.size() - 1] << "\n"; + + exact_solution(x, &y); + + x += step_size; + } while (x <= X_MAX); + + std::clock_t t2 = std::clock(); + double total_time = static_cast(t2 - t1) / CLOCKS_PER_SEC; + std::cout << "\tTime = " << total_time << " ms\n"; + + fp.close(); +} + +/** + * Main Function + */ +int main(int argc, char *argv[]) { + double X0 = 0.f; /* initial value of x0 */ + double X_MAX = 10.F; /* upper limit of integration */ + std::valarray Y0 = {1.f, 0.f}; /* initial value Y = y(x = x_0) */ + double step_size; + + if (argc == 1) { + std::cout << "\nEnter the step size: "; + std::cin >> step_size; + } else { + // use commandline argument as independent variable step size + step_size = std::atof(argv[1]); + } + + // get approximate solution + double total_time = semi_implicit_euler(step_size, X0, X_MAX, &Y0, true); + std::cout << "\tTime = " << total_time << " ms\n"; + + /* compute exact solution for comparion */ + save_exact_solution(X0, X_MAX, step_size, Y0); + + return 0; +} From ad1633a83e9a618148e39ebc91fde4982eaa3616 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 11 Jun 2020 12:54:15 +0000 Subject: [PATCH 413/433] updating DIRECTORY.md --- DIRECTORY.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 45143d3a1d2..03f29508b2f 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -131,6 +131,9 @@ * [Gaussian Elimination](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/gaussian_elimination.cpp) * [Lu Decompose](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/lu_decompose.cpp) * [Newton Raphson Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/newton_raphson_method.cpp) + * [Ode Forward Euler](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/ode_forward_euler.cpp) + * [Ode Midpoint Euler](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/ode_midpoint_euler.cpp) + * [Ode Semi Implicit Euler](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/ode_semi_implicit_euler.cpp) * [Ordinary Least Squares Regressor](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/ordinary_least_squares_regressor.cpp) * [Qr Decompose](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/qr_decompose.h) * [Qr Decomposition](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/qr_decomposition.cpp) From 4e055869e36f9764d5d760e9365b7e45d8f2e5e5 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 11 Jun 2020 08:58:55 -0400 Subject: [PATCH 414/433] fix cpplint issues - lines 117 and 124 --- numerical_methods/ode_forward_euler.cpp | 4 ++-- numerical_methods/ode_midpoint_euler.cpp | 3 +-- numerical_methods/ode_semi_implicit_euler.cpp | 3 +-- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/numerical_methods/ode_forward_euler.cpp b/numerical_methods/ode_forward_euler.cpp index e289d96e736..12b1c959dff 100644 --- a/numerical_methods/ode_forward_euler.cpp +++ b/numerical_methods/ode_forward_euler.cpp @@ -113,8 +113,8 @@ double forward_euler(double dx, double x0, double x_max, /* start integration */ std::clock_t t1 = std::clock(); double x = x0; - do // iterate for each step of independent variable - { + + do { // iterate for each step of independent variable if (save_to_file && fp.is_open()) { // write to file fp << x << ","; diff --git a/numerical_methods/ode_midpoint_euler.cpp b/numerical_methods/ode_midpoint_euler.cpp index 4b7c47a8809..4d1137b3ebf 100644 --- a/numerical_methods/ode_midpoint_euler.cpp +++ b/numerical_methods/ode_midpoint_euler.cpp @@ -121,8 +121,7 @@ double midpoint_euler(double dx, double x0, double x_max, /* start integration */ std::clock_t t1 = std::clock(); double x = x0; - do // iterate for each step of independent variable - { + do { // iterate for each step of independent variable if (save_to_file && fp.is_open()) { // write to file fp << x << ","; diff --git a/numerical_methods/ode_semi_implicit_euler.cpp b/numerical_methods/ode_semi_implicit_euler.cpp index 45be225307a..0d57cbfb0d9 100644 --- a/numerical_methods/ode_semi_implicit_euler.cpp +++ b/numerical_methods/ode_semi_implicit_euler.cpp @@ -120,8 +120,7 @@ double semi_implicit_euler(double dx, double x0, double x_max, /* start integration */ std::clock_t t1 = std::clock(); double x = x0; - do // iterate for each step of independent variable - { + do { // iterate for each step of independent variable if (save_to_file && fp.is_open()) { // write to file fp << x << ","; From bd42ae5d86cbb43c4d17cf7f84908143c0ea1d24 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 11 Jun 2020 09:10:00 -0400 Subject: [PATCH 415/433] added documentation to ode group --- numerical_methods/ode_forward_euler.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/numerical_methods/ode_forward_euler.cpp b/numerical_methods/ode_forward_euler.cpp index 12b1c959dff..37800e3f28f 100644 --- a/numerical_methods/ode_forward_euler.cpp +++ b/numerical_methods/ode_forward_euler.cpp @@ -70,6 +70,9 @@ void exact_solution(const double &x, std::valarray *y) { } /** \addtogroup ode Ordinary Differential Equations + * Integration functions for implementations with solving [ordinary differential + * equations](https://en.wikipedia.org/wiki/Ordinary_differential_equation) + * (ODEs) of any order and and any number of independent variables. * @{ */ /** From 11689f4312b56a56fcd5deba4abc7b220f6a7766 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 11 Jun 2020 12:28:19 -0400 Subject: [PATCH 416/433] corrected semi-implicit euler function --- numerical_methods/ode_semi_implicit_euler.cpp | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/numerical_methods/ode_semi_implicit_euler.cpp b/numerical_methods/ode_semi_implicit_euler.cpp index 0d57cbfb0d9..e5f25dc3bce 100644 --- a/numerical_methods/ode_semi_implicit_euler.cpp +++ b/numerical_methods/ode_semi_implicit_euler.cpp @@ -82,14 +82,12 @@ void exact_solution(const double &x, std::valarray *y) { void semi_implicit_euler_step(const double dx, const double &x, std::valarray *y, std::valarray *dy) { - problem(x, y, dy); - double tmp_x = x + 0.5 * dx; + problem(x, y, dy); // update dy once + y[0][0] += dx * dy[0][0]; // update y0 + problem(x, y, dy); // update dy once more - std::valarray tmp_y = y[0] + dy[0] * (0.5 * dx); - - problem(tmp_x, &tmp_y, dy); - - y[0] += dy[0] * dx; + dy[0][0] = 0.f; // ignore y0 + y[0] += dy[0] * dx; // update remaining using new dy } /** From 77518ee175ba8e07dafa4549a2ae2f0180c76aa6 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 12 Jun 2020 11:17:59 -0400 Subject: [PATCH 417/433] updated docs and test cases better structure --- sorting/shell_sort2.cpp | 147 ++++++++++++++++++++++++++++++++++------ 1 file changed, 125 insertions(+), 22 deletions(-) diff --git a/sorting/shell_sort2.cpp b/sorting/shell_sort2.cpp index 96ef25580b1..6d9230ed1bc 100644 --- a/sorting/shell_sort2.cpp +++ b/sorting/shell_sort2.cpp @@ -3,11 +3,12 @@ * \brief [Shell sort](https://en.wikipedia.org/wiki/Shell_sort) algorithm * \author [Krishna Vedala](https://github.com/kvedala) */ -#include +#include #include #include #include #include // for std::swap +#include /** pretty print array * \param[in] arr array to print @@ -17,7 +18,9 @@ template void show_data(T *arr, size_t LEN) { size_t i; - for (i = 0; i < LEN; i++) std::cout << arr[i] << ", "; + for (i = 0; i < LEN; i++) { + std::cout << arr[i] << ", "; + } std::cout << std::endl; } @@ -25,7 +28,7 @@ void show_data(T *arr, size_t LEN) { * \param[in] arr array to print * \param[in] N length of array to print */ -template +template void show_data(T (&arr)[N]) { show_data(arr, N); } @@ -38,7 +41,7 @@ namespace sorting { * Optimized algorithm - takes half the time by utilizing * Mar **/ -template +template void shell_sort(T *arr, size_t LEN) { const unsigned int gaps[] = {701, 301, 132, 57, 23, 10, 4, 1}; const unsigned int gap_len = 8; @@ -49,8 +52,9 @@ void shell_sort(T *arr, size_t LEN) { for (i = gap; i < LEN; i++) { T tmp = arr[i]; - for (j = i; j >= gap && (arr[j - gap] - tmp) > 0; j -= gap) + for (j = i; j >= gap && (arr[j - gap] - tmp) > 0; j -= gap) { arr[j] = arr[j - gap]; + } arr[j] = tmp; } @@ -59,11 +63,19 @@ void shell_sort(T *arr, size_t LEN) { /** function overload - when input array is of a known length array type */ -template +template void shell_sort(T (&arr)[N]) { shell_sort(arr, N); } +/** function overload - when input array is of type std::vector, + * simply send the data content and the data length to the above function. + */ +template +void shell_sort(std::vector *arr) { + shell_sort(arr->data(), arr->size()); +} + } // namespace sorting using sorting::shell_sort; @@ -71,9 +83,10 @@ using sorting::shell_sort; /** * function to compare sorting using cstdlib's qsort **/ +template int compare(const void *a, const void *b) { - int arg1 = *static_cast(a); - int arg2 = *static_cast(b); + T arg1 = *static_cast(a); + T arg2 = *static_cast(b); if (arg1 < arg2) return -1; @@ -85,7 +98,106 @@ int compare(const void *a, const void *b) { // return arg1 - arg2; // erroneous shortcut (fails if INT_MIN is present) } +/** + * Test implementation of shell_sort on integer arrays by comparing results + * against std::qsort. + */ +void test_int(const int NUM_DATA) { + // int array = new int[NUM_DATA]; + int *data = new int[NUM_DATA]; + int *data2 = new int[NUM_DATA]; + // int array2 = new int[NUM_DATA]; + int range = 1800; + + for (int i = 0; i < NUM_DATA; i++) + data[i] = data2[i] = (std::rand() % range) - (range >> 1); + + /* sort using our implementation */ + std::clock_t start = std::clock(); + shell_sort(data, NUM_DATA); + std::clock_t end = std::clock(); + double elapsed_time = static_cast(end - start) / CLOCKS_PER_SEC; + std::cout << "Time spent sorting using shell_sort2: " << elapsed_time + << "s\n"; + + /* sort using std::qsort */ + start = std::clock(); + std::qsort(data2, NUM_DATA, sizeof(data2[0]), compare); + end = std::clock(); + + elapsed_time = static_cast(end - start) / CLOCKS_PER_SEC; + std::cout << "Time spent sorting using std::qsort: " << elapsed_time + << "s\n"; + + for (int i = 0; i < NUM_DATA; i++) { + assert(data[i] == data2[i]); // ensure that our sorting results match + // the standard results + } + + free(data); + free(data2); +} + +/** + * Test implementation of shell_sort on float arrays by comparing results + * against std::qsort. + */ +void test_f(const int NUM_DATA) { + // int array = new int[NUM_DATA]; + float *data = new float[NUM_DATA]; + float *data2 = new float[NUM_DATA]; + // int array2 = new int[NUM_DATA]; + int range = 1000; + + for (int i = 0; i < NUM_DATA; i++) { + data[i] = data2[i] = ((std::rand() % range) - (range >> 1)) / 100.; + } + + /* sort using our implementation */ + std::clock_t start = std::clock(); + shell_sort(data, NUM_DATA); + std::clock_t end = std::clock(); + double elapsed_time = static_cast(end - start) / CLOCKS_PER_SEC; + std::cout << "Time spent sorting using shell_sort2: " << elapsed_time + << "s\n"; + + /* sort using std::qsort */ + start = std::clock(); + std::qsort(data2, NUM_DATA, sizeof(data2[0]), compare); + end = std::clock(); + + elapsed_time = static_cast(end - start) / CLOCKS_PER_SEC; + std::cout << "Time spent sorting using std::qsort: " << elapsed_time + << "s\n"; + + for (int i = 0; i < NUM_DATA; i++) { + assert(data[i] == data2[i]); // ensure that our sorting results match + // the standard results + } + + free(data); + free(data2); +} + +/** Main function */ int main(int argc, char *argv[]) { + // initialize random number generator - once per program + std::srand(std::time(NULL)); + + test_int(100); // test with sorting random array of 100 values + std::cout << "Test 1 - 100 int values - passed. \n"; + test_int(1000); // test with sorting random array of 1000 values + std::cout << "Test 2 - 1000 int values - passed.\n"; + test_int(10000); // test with sorting random array of 10000 values + std::cout << "Test 3 - 10000 int values - passed.\n"; + + test_f(100); // test with sorting random array of 100 values + std::cout << "Test 1 - 100 float values - passed. \n"; + test_f(1000); // test with sorting random array of 1000 values + std::cout << "Test 2 - 1000 float values - passed.\n"; + test_f(10000); // test with sorting random array of 10000 values + std::cout << "Test 3 - 10000 float values - passed.\n"; + int i, NUM_DATA; if (argc == 2) @@ -95,18 +207,19 @@ int main(int argc, char *argv[]) { // int array = new int[NUM_DATA]; int *data = new int[NUM_DATA]; - int *data2 = new int[NUM_DATA]; // int array2 = new int[NUM_DATA]; int range = 1800; std::srand(time(NULL)); - for (i = 0; i < NUM_DATA; i++) - data[i] = data2[i] = (std::rand() % range) - (range >> 1); + for (i = 0; i < NUM_DATA; i++) { + // allocate random numbers in the given range + data[i] = (std::rand() % range) - (range >> 1); + } std::cout << "Unsorted original data: " << std::endl; show_data(data, NUM_DATA); std::clock_t start = std::clock(); - shell_sort(data, NUM_DATA); + shell_sort(data, NUM_DATA); // perform sorting std::clock_t end = std::clock(); std::cout << std::endl @@ -116,16 +229,6 @@ int main(int argc, char *argv[]) { double elapsed_time = (end - start) * 1.f / CLOCKS_PER_SEC; std::cout << "Time spent sorting: " << elapsed_time << "s\n" << std::endl; - start = std::clock(); - qsort(data2, NUM_DATA, sizeof(data2[0]), compare); - end = std::clock(); - std::cout << "Data Sorted using cstdlib qsort: " << std::endl; - show_data(data2, NUM_DATA); - - elapsed_time = (end - start) * 1.f / CLOCKS_PER_SEC; - std::cout << "Time spent sorting: " << elapsed_time << "s\n" << std::endl; - free(data); - free(data2); return 0; } From e2996cecf37c56c08413254a54ad043ab1cda1d1 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 12 Jun 2020 12:45:07 -0400 Subject: [PATCH 418/433] replace `free` with `delete` operator --- sorting/shell_sort2.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/sorting/shell_sort2.cpp b/sorting/shell_sort2.cpp index 6d9230ed1bc..5db773aca91 100644 --- a/sorting/shell_sort2.cpp +++ b/sorting/shell_sort2.cpp @@ -134,8 +134,8 @@ void test_int(const int NUM_DATA) { // the standard results } - free(data); - free(data2); + delete[] data; + delete[] data2; } /** @@ -175,8 +175,8 @@ void test_f(const int NUM_DATA) { // the standard results } - free(data); - free(data2); + delete[] data; + delete[] data2; } /** Main function */ @@ -229,6 +229,6 @@ int main(int argc, char *argv[]) { double elapsed_time = (end - start) * 1.f / CLOCKS_PER_SEC; std::cout << "Time spent sorting: " << elapsed_time << "s\n" << std::endl; - free(data); + delete[] data; return 0; } From cdb9766f7a4d3313a7d4aa140268e7b57d16c7a1 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 14 Jun 2020 14:18:23 +0000 Subject: [PATCH 419/433] formatting source-code for f55ab50cf26d176fe56bdaffa6f0ce8023c03c18 --- math/check_prime.cpp | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/math/check_prime.cpp b/math/check_prime.cpp index e517d774e8f..3287dfdee65 100644 --- a/math/check_prime.cpp +++ b/math/check_prime.cpp @@ -1,22 +1,24 @@ /** * Copyright 2020 @author omkarlanghe * - * @file + * @file * A simple program to check if the given number if prime or not. - * + * * @brief * Reduced all possibilities of a number which cannot be prime. - * Eg: No even number, except 2 can be a prime number, hence we will increment our loop with i+2 jumping on all odd numbers only. - * If number is <= 1 or if it is even except 2, break the loop and return false telling number is not prime. + * Eg: No even number, except 2 can be a prime number, hence we will increment + * our loop with i+2 jumping on all odd numbers only. If number is <= 1 or if it + * is even except 2, break the loop and return false telling number is not + * prime. */ -#include #include - /** +#include +/** * Function to check if the given number is prime or not. * @param num number to be checked. * @return if number is prime, it returns @ true, else it returns @ false. */ -template +template bool is_prime(T num) { bool result = true; if (num <= 1) { @@ -27,7 +29,7 @@ bool is_prime(T num) { return 0; } if (num >= 3) { - for (T i = 3 ; (i*i) < (num) ; i = (i + 2)) { + for (T i = 3; (i * i) < (num); i = (i + 2)) { if ((num % i) == 0) { result = false; break; @@ -42,16 +44,13 @@ bool is_prime(T num) { */ int main() { int num; - std::cout << "Enter the number to check if it is prime or not" << - std::endl; + std::cout << "Enter the number to check if it is prime or not" << std::endl; std::cin >> num; bool result = is_prime(num); if (result) { - std::cout << num << " is a prime number" << - std::endl; + std::cout << num << " is a prime number" << std::endl; } else { - std::cout << num << " is not a prime number" << - std::endl; + std::cout << num << " is not a prime number" << std::endl; } assert(is_prime(50) == false); assert(is_prime(115249) == true); From 1bf5a19a5d4fff798617d56888b5181e4b895925 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 14 Jun 2020 14:18:39 +0000 Subject: [PATCH 420/433] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index dbd5d0002b8..7b26a7a5ff9 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -114,6 +114,7 @@ * [Gcd Recursive Euclidean](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/gcd_recursive_euclidean.cpp) * [Large Factorial](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/large_factorial.cpp) * [Large Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/large_number.h) + * [Least Common Multiple](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/least_common_multiple.cpp) * [Modular Inverse Fermat Little Theorem](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/modular_inverse_fermat_little_theorem.cpp) * [Number Of Positive Divisors](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/number_of_positive_divisors.cpp) * [Power For Huge Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/power_for_huge_numbers.cpp) From 3c1449e09ffb51a8c71c3d5516669883c4515325 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 14 Jun 2020 10:24:37 -0400 Subject: [PATCH 421/433] main function must return --- math/check_prime.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/math/check_prime.cpp b/math/check_prime.cpp index 3287dfdee65..ea4e6d52d27 100644 --- a/math/check_prime.cpp +++ b/math/check_prime.cpp @@ -43,6 +43,10 @@ bool is_prime(T num) { * Main function */ int main() { + // perform self-test + assert(is_prime(50) == false); + assert(is_prime(115249) == true); + int num; std::cout << "Enter the number to check if it is prime or not" << std::endl; std::cin >> num; @@ -52,6 +56,6 @@ int main() { } else { std::cout << num << " is not a prime number" << std::endl; } - assert(is_prime(50) == false); - assert(is_prime(115249) == true); + + return 0; } From 3229e109f608f013518a7825d615dc609b0f8705 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Mon, 15 Jun 2020 16:59:58 -0400 Subject: [PATCH 422/433] added machine learning group --- machine_learning/adaline_learning.cpp | 5 +++++ machine_learning/kohonen_som_trace.cpp | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/machine_learning/adaline_learning.cpp b/machine_learning/adaline_learning.cpp index eafeca826d3..488aae7710f 100644 --- a/machine_learning/adaline_learning.cpp +++ b/machine_learning/adaline_learning.cpp @@ -1,4 +1,6 @@ /** + * \addtogroup machine_learning Machine Learning Algorithms + * @{ * \file * \brief [Adaptive Linear Neuron * (ADALINE)](https://en.wikipedia.org/wiki/ADALINE) implementation @@ -345,3 +347,6 @@ int main(int argc, char **argv) { return 0; } + +/** @} + */ diff --git a/machine_learning/kohonen_som_trace.cpp b/machine_learning/kohonen_som_trace.cpp index 1a39ce58a55..112d7c33711 100644 --- a/machine_learning/kohonen_som_trace.cpp +++ b/machine_learning/kohonen_som_trace.cpp @@ -1,4 +1,6 @@ /** + * \addtogroup machine_learning Machine Learning Algorithms + * @{ * \file * \brief [Kohonen self organizing * map](https://en.wikipedia.org/wiki/Self-organizing_map) (data tracing) @@ -14,6 +16,7 @@ * counterpart](https://github.com/kvedala/C/blob/master/machine_learning/kohonen_som_trace.c) * \note The compiled code is much slower when compiled with MS Visual C++ 2019 * than with GCC on windows + * \see kohonen_som_topology.cpp */ #define _USE_MATH_DEFINES // required for MS Visual C++ #include @@ -458,3 +461,5 @@ int main(int argc, char **argv) { "model and writing files to disk.)\n\n"; return 0; } + +/** @} */ From 16a440b7067dea36565919a22ca12799745c5206 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Mon, 15 Jun 2020 17:02:02 -0400 Subject: [PATCH 423/433] added kohonen som topology algorithm --- machine_learning/kohonen_som_topology.cpp | 596 ++++++++++++++++++++++ 1 file changed, 596 insertions(+) create mode 100644 machine_learning/kohonen_som_topology.cpp diff --git a/machine_learning/kohonen_som_topology.cpp b/machine_learning/kohonen_som_topology.cpp new file mode 100644 index 00000000000..cbc139a8a8b --- /dev/null +++ b/machine_learning/kohonen_som_topology.cpp @@ -0,0 +1,596 @@ +/** + * \addtogroup machine_learning Machine Learning Algorithms + * @{ + * \file + * \author [Krishna Vedala](https://github.com/kvedala) + * \brief [Kohonen self organizing + * map](https://en.wikipedia.org/wiki/Self-organizing_map) (topological map) + * + * This example implements a powerful unsupervised learning algorithm called as + * a self organizing map. The algorithm creates a connected network of weights + * that closely follows the given data points. This thus creates a topological + * map of the given data i.e., it maintains the relationship between varipus + * data points in a much higher dimesional space by creating an equivalent in a + * 2-dimensional space. + * Trained topological maps for the test cases in the program + * \note This C++ version of the program is considerable slower than its [C + * counterpart](https://github.com/kvedala/C/blob/master/machine_learning/kohonen_som_trace.c) + * \note The compiled code is much slower when compiled with MS Visual C++ 2019 + * than with GCC on windows + * \see kohonen_som_trace.cpp + */ +#define _USE_MATH_DEFINES // required for MS Visual C++ +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _OPENMP // check if OpenMP based parallellization is available +#include +#endif + +/** + * Helper function to generate a random number in a given interval. + * \n Steps: + * 1. `r1 = rand() % 100` gets a random number between 0 and 99 + * 2. `r2 = r1 / 100` converts random number to be between 0 and 0.99 + * 3. scale and offset the random number to given range of \f$[a,b]\f$ + * + * \param[in] a lower limit + * \param[in] b upper limit + * \returns random number in the range \f$[a,b]\f$ + */ +double _random(double a, double b) { + return ((b - a) * (std::rand() % 100) / 100.f) + a; +} + +/** + * Save a given n-dimensional data martix to file. + * + * \param[in] fname filename to save in (gets overwriten without confirmation) + * \param[in] X matrix to save + * \returns 0 if all ok + * \returns -1 if file creation failed + */ +int save_2d_data(const char *fname, + const std::vector> &X) { + size_t num_points = X.size(); // number of rows + size_t num_features = X[0].size(); // number of columns + + std::ofstream fp; + fp.open(fname); + if (!fp.is_open()) { + // error with opening file to write + std::cerr << "Error opening file " << fname << "\n"; + return -1; + } + + // for each point in the array + for (int i = 0; i < num_points; i++) { + // for each feature in the array + for (int j = 0; j < num_features; j++) { + fp << X[i][j]; // print the feature value + if (j < num_features - 1) // if not the last feature + fp << ","; // suffix comma + } + if (i < num_points - 1) // if not the last row + fp << "\n"; // start a new line + } + + fp.close(); + return 0; +} + +/** + * Get minimum value and index of the value in a matrix + * \param[in] X matrix to search + * \param[in] N number of points in the vector + * \param[out] val minimum value found + * \param[out] idx_x x-index where minimum value was found + * \param[out] idx_y y-index where minimum value was found + */ +void get_min_2d(const std::vector> &X, double *val, + int *x_idx, int *y_idx) { + val[0] = INFINITY; // initial min value + int N = X.size(); + + for (int i = 0; i < N; i++) // traverse each x-index + { + auto result = std::min_element(std::begin(X[i]), std::end(X[i])); + double d_min = *result; + int j = std::distance(std::begin(X[i]), result); + + if (d_min < val[0]) // if a lower value is found + { // save the value and its index + x_idx[0] = i; + y_idx[0] = j; + val[0] = d_min; + } + } +} + +/** \namespace machine_learning + * \brief Machine learning algorithms + */ +namespace machine_learning { +#define MIN_DISTANCE 1e-4 ///< Minimum average distance of image nodes + +/** + * Create the distance matrix or + * [U-matrix](https://en.wikipedia.org/wiki/U-matrix) from the trained + * 3D weiths matrix and save to disk. + * + * \param [in] fname filename to save in (gets overwriten without + * confirmation) + * \param [in] W model matrix to save + * \returns 0 if all ok + * \returns -1 if file creation failed + */ +int save_u_matrix(const char *fname, + const std::vector>> &W) { + std::ofstream fp(fname); + if (!fp) { // error with fopen + char msg[120]; + std::sprintf(msg, "File error (%s): ", fname); + std::perror(msg); + return -1; + } + + // neighborhood range + unsigned int R = 1; + + for (int i = 0; i < W.size(); i++) { // for each x + for (int j = 0; j < W[0].size(); j++) { // for each y + double distance = 0.f; + + int from_x = std::max(0, i - R); + int to_x = std::min(W.size(), i + R + 1); + int from_y = std::max(0, j - R); + int to_y = std::min(W[0].size(), j + R + 1); + int l, m; +#ifdef _OPENMP +#pragma omp parallel for reduction(+ : distance) +#endif + for (l = from_x; l < to_x; l++) { // scan neighborhoor in x + for (m = from_y; m < to_y; m++) { // scan neighborhood in y + auto d = W[i][j] - W[l][m]; + double d2 = std::pow(d, 2).sum(); + distance += std::sqrt(d2); + // distance += d2; + } + } + + distance /= R * R; // mean distance from neighbors + fp << distance; // print the mean separation + if (j < W[0].size() - 1) { // if not the last column + fp << ','; // suffix comma + } + } + if (i < W.size() - 1) // if not the last row + fp << '\n'; // start a new line + } + + fp.close(); + return 0; +} + +/** + * Update weights of the SOM using Kohonen algorithm + * + * \param[in] X data point - N features + * \param[in,out] W weights matrix - PxQxN + * \param[in,out] D temporary vector to store distances PxQ + * \param[in] alpha learning rate \f$0<\alpha\le1\f$ + * \param[in] R neighborhood range + * \returns minimum distance of sample and trained weights + */ +double update_weights(const std::valarray &X, + std::vector>> *W, + std::vector> *D, double alpha, + int R) { + int x, y; + int num_out_x = int(W->size()); // number of SOM output nodes - in X + int num_out_y = int(W[0][0].size()); // number of SOM output nodes - in Y + int num_features = int(W[0][0][0].size()); // number of features = in Z + double d_min = 0.f; + +#ifdef _OPENMP +#pragma omp for +#endif + // step 1: for each output point + for (x = 0; x < num_out_x; x++) { + for (y = 0; y < num_out_y; y++) { + (*D)[x][y] = 0.f; + // compute Euclidian distance of each output + // point from the current sample + auto d = ((*W)[x][y] - X); + (*D)[x][y] = (d * d).sum(); + (*D)[x][y] = std::sqrt((*D)[x][y]); + } + } + + // step 2: get closest node i.e., node with snallest Euclidian distance + // to the current pattern + int d_min_x, d_min_y; + get_min_2d(*D, &d_min, &d_min_x, &d_min_y); + + // step 3a: get the neighborhood range + int from_x = std::max(0, d_min_x - R); + int to_x = std::min(num_out_x, d_min_x + R + 1); + int from_y = std::max(0, d_min_y - R); + int to_y = std::min(num_out_y, d_min_y + R + 1); + + // step 3b: update the weights of nodes in the + // neighborhood +#ifdef _OPENMP +#pragma omp for +#endif + for (x = from_x; x < to_x; x++) { + for (y = from_y; y < to_y; y++) { + /* you can enable the following normalization if needed. + personally, I found it detrimental to convergence */ + // const double s2pi = sqrt(2.f * M_PI); + // double normalize = 1.f / (alpha * s2pi); + + /* apply scaling inversely proportional to distance from the + current node */ + double d2 = + (d_min_x - x) * (d_min_x - x) + (d_min_y - y) * (d_min_y - y); + double scale_factor = std::exp(-d2 / (2.f * alpha * alpha)); + + (*W)[x][y] += (X - (*W)[x][y]) * alpha * scale_factor; + } + } + return d_min; +} + +/** + * Apply incremental algorithm with updating neighborhood and learning + * rates on all samples in the given datset. + * + * \param[in] X data set + * \param[in,out] W weights matrix + * \param[in] alpha_min terminal value of alpha + */ +void kohonen_som(const std::vector> &X, + std::vector>> *W, + double alpha_min) { + int num_samples = X.size(); // number of rows + int num_features = X[0].size(); // number of columns + int num_out = W->size(); // output matrix size + int R = num_out >> 2, iter = 0; + double alpha = 1.f; + + std::vector> D(num_out); + for (int i = 0; i < num_out; i++) D[i] = std::valarray(num_out); + + double dmin = 1.f; // average minimum distance of all samples + double past_dmin = 1.f; // average minimum distance of all samples + double dmin_ratio = 1.f; // change per step + + // Loop alpha from 1 to slpha_min + for (; alpha > 0 && dmin_ratio > 1e-5; alpha -= 1e-4, iter++) { + // Loop for each sample pattern in the data set + for (int sample = 0; sample < num_samples; sample++) { + // update weights for the current input pattern sample + dmin += update_weights(X[sample], W, &D, alpha, R); + } + + // every 100th iteration, reduce the neighborhood range + if (iter % 300 == 0 && R > 1) + R--; + + dmin /= num_samples; + + // termination condition variable -> % change in minimum distance + dmin_ratio = (past_dmin - dmin) / past_dmin; + if (dmin_ratio < 0) + dmin_ratio = 1.f; + past_dmin = dmin; + + std::cout << "iter: " << iter << "\t alpha: " << alpha << "\t R: " << R + << "\t d_min: " << dmin_ratio << "\r"; + } + + std::cout << "\n"; +} + +} // namespace machine_learning + +using machine_learning::kohonen_som; +using machine_learning::save_u_matrix; + +/** Creates a random set of points distributed in four clusters in + * 3D space with centroids at the points + * * \f$(0,5, 0.5, 0.5)\f$ + * * \f$(0,5,-0.5, -0.5)\f$ + * * \f$(-0,5, 0.5, 0.5)\f$ + * * \f$(-0,5,-0.5, -0.5)\f$ + * + * \param[out] data matrix to store data in + */ +void test_2d_classes(std::vector> *data) { + const int N = data->size(); + const double R = 0.3; // radius of cluster + int i; + const int num_classes = 4; + const double centres[][2] = { + // centres of each class cluster + {.5, .5}, // centre of class 1 + {.5, -.5}, // centre of class 2 + {-.5, .5}, // centre of class 3 + {-.5, -.5} // centre of class 4 + }; + +#ifdef _OPENMP +#pragma omp for +#endif + for (i = 0; i < N; i++) { + // select a random class for the point + int cls = std::rand() % num_classes; + + // create random coordinates (x,y,z) around the centre of the class + data[0][i][0] = _random(centres[cls][0] - R, centres[cls][0] + R); + data[0][i][1] = _random(centres[cls][1] - R, centres[cls][1] + R); + + /* The follosing can also be used + for (int j = 0; j < 2; j++) + data[i][j] = _random(centres[class][j] - R, centres[class][j] + R); + */ + } +} + +/** Test that creates a random set of points distributed in four clusters in + * circumference of a circle and trains an SOM that finds that circular pattern. + * The following [CSV](https://en.wikipedia.org/wiki/Comma-separated_values) + * files are created to validate the execution: + * * `test1.csv`: random test samples points with a circular pattern + * * `w11.csv`: initial random map + * * `w12.csv`: trained SOM map + */ +void test1() { + int j, N = 300; + int features = 2; + int num_out = 30; + std::vector> X(N); + std::vector>> W(num_out); + for (int i = 0; i < std::max(num_out, N); i++) { + // loop till max(N, num_out) + if (i < N) // only add new arrays if i < N + X[i] = std::valarray(features); + if (i < num_out) { // only add new arrays if i < num_out + W[i] = std::vector>(num_out); + for (int k = 0; k < num_out; k++) { + W[i][k] = std::valarray(features); +#ifdef _OPENMP +#pragma omp for +#endif + for (j = 0; j < features; j++) + // preallocate with random initial weights + W[i][k][j] = _random(-10, 10); + } + } + } + + test_2d_classes(&X); // create test data around circumference of a circle + save_2d_data("test1.csv", X); // save test data points + save_u_matrix("w11.csv", W); // save initial random weights + kohonen_som(X, &W, 1e-4); // train the SOM + save_u_matrix("w12.csv", W); // save the resultant weights +} + +/** Creates a random set of points distributed in four clusters in + * 3D space with centroids at the points + * * \f$(0,5, 0.5, 0.5)\f$ + * * \f$(0,5,-0.5, -0.5)\f$ + * * \f$(-0,5, 0.5, 0.5)\f$ + * * \f$(-0,5,-0.5, -0.5)\f$ + * + * \param[out] data matrix to store data in + */ +void test_3d_classes1(std::vector> *data) { + const int N = data->size(); + const double R = 0.3; // radius of cluster + int i; + const int num_classes = 4; + const double centres[][3] = { + // centres of each class cluster + {.5, .5, .5}, // centre of class 1 + {.5, -.5, -.5}, // centre of class 2 + {-.5, .5, .5}, // centre of class 3 + {-.5, -.5 - .5} // centre of class 4 + }; + +#ifdef _OPENMP +#pragma omp for +#endif + for (i = 0; i < N; i++) { + // select a random class for the point + int cls = std::rand() % num_classes; + + // create random coordinates (x,y,z) around the centre of the class + data[0][i][0] = _random(centres[cls][0] - R, centres[cls][0] + R); + data[0][i][1] = _random(centres[cls][1] - R, centres[cls][1] + R); + data[0][i][2] = _random(centres[cls][2] - R, centres[cls][2] + R); + + /* The follosing can also be used + for (int j = 0; j < 3; j++) + data[i][j] = _random(centres[class][j] - R, centres[class][j] + R); + */ + } +} + +/** Test that creates a random set of points distributed in 4 clusters in + * 3D space and trains an SOM that finds the topological pattern. The following + * [CSV](https://en.wikipedia.org/wiki/Comma-separated_values) files are created + * to validate the execution: + * * `test2.csv`: random test samples points with a lamniscate pattern + * * `w21.csv`: initial random map + * * `w22.csv`: trained SOM map + */ +void test2() { + int j, N = 300; + int features = 3; + int num_out = 30; + std::vector> X(N); + std::vector>> W(num_out); + for (int i = 0; i < std::max(num_out, N); i++) { + // loop till max(N, num_out) + if (i < N) // only add new arrays if i < N + X[i] = std::valarray(features); + if (i < num_out) { // only add new arrays if i < num_out + W[i] = std::vector>(num_out); + for (int k = 0; k < num_out; k++) { + W[i][k] = std::valarray(features); +#ifdef _OPENMP +#pragma omp for +#endif + for (j = 0; j < features; j++) + // preallocate with random initial weights + W[i][k][j] = _random(-10, 10); + } + } + } + + test_3d_classes1(&X); // create test data around circumference of a circle + save_2d_data("test2.csv", X); // save test data points + save_u_matrix("w21.csv", W); // save initial random weights + kohonen_som(X, &W, 1e-4); // train the SOM + save_u_matrix("w22.csv", W); // save the resultant weights +} + +/** Creates a random set of points distributed in four clusters in + * 3D space with centroids at the points + * * \f$(0,5, 0.5, 0.5)\f$ + * * \f$(0,5,-0.5, -0.5)\f$ + * * \f$(-0,5, 0.5, 0.5)\f$ + * * \f$(-0,5,-0.5, -0.5)\f$ + * + * \param[out] data matrix to store data in + */ +void test_3d_classes2(std::vector> *data) { + const int N = data->size(); + const double R = 0.2; // radius of cluster + int i; + const int num_classes = 8; + const double centres[][3] = { + // centres of each class cluster + {.5, .5, .5}, // centre of class 1 + {.5, .5, -.5}, // centre of class 2 + {.5, -.5, .5}, // centre of class 3 + {.5, -.5, -.5}, // centre of class 4 + {-.5, .5, .5}, // centre of class 5 + {-.5, .5, -.5}, // centre of class 6 + {-.5, -.5, .5}, // centre of class 7 + {-.5, -.5, -.5} // centre of class 8 + }; + +#ifdef _OPENMP +#pragma omp for +#endif + for (i = 0; i < N; i++) { + // select a random class for the point + int cls = std::rand() % num_classes; + + // create random coordinates (x,y,z) around the centre of the class + data[0][i][0] = _random(centres[cls][0] - R, centres[cls][0] + R); + data[0][i][1] = _random(centres[cls][1] - R, centres[cls][1] + R); + data[0][i][2] = _random(centres[cls][2] - R, centres[cls][2] + R); + + /* The follosing can also be used + for (int j = 0; j < 3; j++) + data[i][j] = _random(centres[class][j] - R, centres[class][j] + R); + */ + } +} + +/** Test that creates a random set of points distributed in eight clusters in + * 3D space and trains an SOM that finds the topological pattern. The following + * [CSV](https://en.wikipedia.org/wiki/Comma-separated_values) files are created + * to validate the execution: + * * `test3.csv`: random test samples points with a circular pattern + * * `w31.csv`: initial random map + * * `w32.csv`: trained SOM map + */ +void test3() { + int j, N = 500; + int features = 3; + int num_out = 30; + std::vector> X(N); + std::vector>> W(num_out); + for (int i = 0; i < std::max(num_out, N); i++) { + // loop till max(N, num_out) + if (i < N) // only add new arrays if i < N + X[i] = std::valarray(features); + if (i < num_out) { // only add new arrays if i < num_out + W[i] = std::vector>(num_out); + for (int k = 0; k < num_out; k++) { + W[i][k] = std::valarray(features); +#ifdef _OPENMP +#pragma omp for +#endif + for (j = 0; j < features; j++) + // preallocate with random initial weights + W[i][k][j] = _random(-10, 10); + } + } + } + + test_3d_classes2(&X); // create test data around circumference of a circle + save_2d_data("test3.csv", X); // save test data points + save_u_matrix("w31.csv", W); // save initial random weights + kohonen_som(X, &W, 1e-4); // train the SOM + save_u_matrix("w32.csv", W); // save the resultant weights +} + +/** + * Convert clock cycle difference to time in seconds + * + * \param[in] start_t start clock + * \param[in] end_t end clock + * \returns time difference in seconds + */ +double get_clock_diff(clock_t start_t, clock_t end_t) { + return static_cast(end_t - start_t) / CLOCKS_PER_SEC; +} + +/** Main function */ +int main(int argc, char **argv) { +#ifdef _OPENMP + std::cout << "Using OpenMP based parallelization\n"; +#else + std::cout << "NOT using OpenMP based parallelization\n"; +#endif + + std::srand(std::time(nullptr)); + + std::clock_t start_clk = std::clock(); + test1(); + auto end_clk = std::clock(); + std::cout << "Test 1 completed in " << get_clock_diff(start_clk, end_clk) + << " sec\n"; + + start_clk = std::clock(); + test2(); + end_clk = std::clock(); + std::cout << "Test 2 completed in " << get_clock_diff(start_clk, end_clk) + << " sec\n"; + + start_clk = std::clock(); + test3(); + end_clk = std::clock(); + std::cout << "Test 3 completed in " << get_clock_diff(start_clk, end_clk) + << " sec\n"; + + std::cout + << "(Note: Calculated times include: creating test sets, training " + "model and writing files to disk.)\n\n"; + return 0; +} + +/** @} */ From a2ff0ceb651d192d54ab31fa96b3643d77116e5f Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Mon, 15 Jun 2020 17:13:26 -0400 Subject: [PATCH 424/433] fix graph image path --- machine_learning/kohonen_som_topology.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/machine_learning/kohonen_som_topology.cpp b/machine_learning/kohonen_som_topology.cpp index cbc139a8a8b..2be1a48b86f 100644 --- a/machine_learning/kohonen_som_topology.cpp +++ b/machine_learning/kohonen_som_topology.cpp @@ -13,7 +13,7 @@ * data points in a much higher dimesional space by creating an equivalent in a * 2-dimensional space. * Trained topological maps for the test cases in the program * \note This C++ version of the program is considerable slower than its [C * counterpart](https://github.com/kvedala/C/blob/master/machine_learning/kohonen_som_trace.c) From 8064f157f73558033db0fa97a475d725739b257b Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 15 Jun 2020 21:15:01 +0000 Subject: [PATCH 425/433] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 7b26a7a5ff9..071ee8b9594 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -96,6 +96,7 @@ ## Machine Learning * [Adaline Learning](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/machine_learning/adaline_learning.cpp) + * [Kohonen Som Topology](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/machine_learning/kohonen_som_topology.cpp) * [Kohonen Som Trace](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/machine_learning/kohonen_som_trace.cpp) ## Math From d003d49f69e5f501937cee3bc86ef24a72bf77fa Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Mon, 15 Jun 2020 17:23:38 -0400 Subject: [PATCH 426/433] fix braces --- machine_learning/kohonen_som_topology.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/machine_learning/kohonen_som_topology.cpp b/machine_learning/kohonen_som_topology.cpp index 2be1a48b86f..960d98f58f4 100644 --- a/machine_learning/kohonen_som_topology.cpp +++ b/machine_learning/kohonen_som_topology.cpp @@ -99,14 +99,13 @@ void get_min_2d(const std::vector> &X, double *val, val[0] = INFINITY; // initial min value int N = X.size(); - for (int i = 0; i < N; i++) // traverse each x-index - { + for (int i = 0; i < N; i++) { // traverse each x-index auto result = std::min_element(std::begin(X[i]), std::end(X[i])); double d_min = *result; int j = std::distance(std::begin(X[i]), result); - if (d_min < val[0]) // if a lower value is found - { // save the value and its index + if (d_min < val[0]) { // if a lower value is found + // save the value and its index x_idx[0] = i; y_idx[0] = j; val[0] = d_min; From 8bc35c0eda44f2ef9ba2a601a8f5aaf3581d1c1b Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Mon, 15 Jun 2020 17:40:35 -0400 Subject: [PATCH 427/433] use snprintf instead of sprintf --- machine_learning/kohonen_som_topology.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/machine_learning/kohonen_som_topology.cpp b/machine_learning/kohonen_som_topology.cpp index 960d98f58f4..86f69968ef2 100644 --- a/machine_learning/kohonen_som_topology.cpp +++ b/machine_learning/kohonen_som_topology.cpp @@ -119,6 +119,8 @@ void get_min_2d(const std::vector> &X, double *val, namespace machine_learning { #define MIN_DISTANCE 1e-4 ///< Minimum average distance of image nodes +#define buffer_size 120 ///< temporary string buffer size + /** * Create the distance matrix or * [U-matrix](https://en.wikipedia.org/wiki/U-matrix) from the trained @@ -134,8 +136,8 @@ int save_u_matrix(const char *fname, const std::vector>> &W) { std::ofstream fp(fname); if (!fp) { // error with fopen - char msg[120]; - std::sprintf(msg, "File error (%s): ", fname); + char msg[buffer_size]; + std::snprintf(msg, buffer_size, "File error (%s): ", fname); std::perror(msg); return -1; } From 6949570ed6c2b4cb33ec667d5e75fd84c04166e3 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Mon, 15 Jun 2020 17:41:10 -0400 Subject: [PATCH 428/433] use static_cast --- machine_learning/kohonen_som_topology.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/machine_learning/kohonen_som_topology.cpp b/machine_learning/kohonen_som_topology.cpp index 86f69968ef2..c2f628c2b90 100644 --- a/machine_learning/kohonen_som_topology.cpp +++ b/machine_learning/kohonen_som_topology.cpp @@ -195,9 +195,9 @@ double update_weights(const std::valarray &X, std::vector> *D, double alpha, int R) { int x, y; - int num_out_x = int(W->size()); // number of SOM output nodes - in X - int num_out_y = int(W[0][0].size()); // number of SOM output nodes - in Y - int num_features = int(W[0][0][0].size()); // number of features = in Z + int num_out_x = static_cast(W->size()); // output nodes - in X + int num_out_y = static_cast(W[0][0].size()); // output nodes - in Y + int num_features = static_cast(W[0][0][0].size()); // features = in Z double d_min = 0.f; #ifdef _OPENMP From 97af01292ef6ad302dfb6813d2342d9b1cc16648 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Mon, 15 Jun 2020 18:28:01 -0400 Subject: [PATCH 429/433] hardcode character buffer size --- machine_learning/kohonen_som_topology.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/machine_learning/kohonen_som_topology.cpp b/machine_learning/kohonen_som_topology.cpp index c2f628c2b90..8fe3eaaeb98 100644 --- a/machine_learning/kohonen_som_topology.cpp +++ b/machine_learning/kohonen_som_topology.cpp @@ -119,8 +119,6 @@ void get_min_2d(const std::vector> &X, double *val, namespace machine_learning { #define MIN_DISTANCE 1e-4 ///< Minimum average distance of image nodes -#define buffer_size 120 ///< temporary string buffer size - /** * Create the distance matrix or * [U-matrix](https://en.wikipedia.org/wiki/U-matrix) from the trained @@ -136,8 +134,8 @@ int save_u_matrix(const char *fname, const std::vector>> &W) { std::ofstream fp(fname); if (!fp) { // error with fopen - char msg[buffer_size]; - std::snprintf(msg, buffer_size, "File error (%s): ", fname); + char msg[120]; + std::snprintf(msg, sizeof(msg), "File error (%s): ", fname); std::perror(msg); return -1; } From 634fb88532515cf2911fad32524e7a9cc5a58753 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Mon, 15 Jun 2020 18:54:42 -0400 Subject: [PATCH 430/433] fix machine learning groups in documentation --- machine_learning/adaline_learning.cpp | 5 ++--- machine_learning/kohonen_som_topology.cpp | 4 ++-- machine_learning/kohonen_som_trace.cpp | 11 +++++++++-- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/machine_learning/adaline_learning.cpp b/machine_learning/adaline_learning.cpp index 488aae7710f..1e25d3ba168 100644 --- a/machine_learning/adaline_learning.cpp +++ b/machine_learning/adaline_learning.cpp @@ -191,6 +191,8 @@ class adaline { using machine_learning::adaline; +/** @} */ + /** * test function to predict points in a 2D coordinate system above the line * \f$x=y\f$ as +1 and others as -1. @@ -347,6 +349,3 @@ int main(int argc, char **argv) { return 0; } - -/** @} - */ diff --git a/machine_learning/kohonen_som_topology.cpp b/machine_learning/kohonen_som_topology.cpp index 8fe3eaaeb98..abb05e8ec3d 100644 --- a/machine_learning/kohonen_som_topology.cpp +++ b/machine_learning/kohonen_som_topology.cpp @@ -304,6 +304,8 @@ void kohonen_som(const std::vector> &X, using machine_learning::kohonen_som; using machine_learning::save_u_matrix; +/** @} */ + /** Creates a random set of points distributed in four clusters in * 3D space with centroids at the points * * \f$(0,5, 0.5, 0.5)\f$ @@ -591,5 +593,3 @@ int main(int argc, char **argv) { "model and writing files to disk.)\n\n"; return 0; } - -/** @} */ diff --git a/machine_learning/kohonen_som_trace.cpp b/machine_learning/kohonen_som_trace.cpp index 112d7c33711..68c922742d2 100644 --- a/machine_learning/kohonen_som_trace.cpp +++ b/machine_learning/kohonen_som_trace.cpp @@ -83,6 +83,11 @@ int save_nd_data(const char *fname, return 0; } +/** \namespace machine_learning + * \brief Machine learning algorithms + */ +namespace machine_learning { + /** * Update weights of the SOM using Kohonen algorithm * @@ -162,6 +167,10 @@ void kohonen_som_tracer(const std::vector> &X, } } +} // namespace machine_learning + +/** @} */ + /** Creates a random set of points distributed *near* the circumference * of a circle and trains an SOM that finds that circular pattern. The * generating function is @@ -461,5 +470,3 @@ int main(int argc, char **argv) { "model and writing files to disk.)\n\n"; return 0; } - -/** @} */ From b5cb86f31c5f76d9de9109478b83913efdd8bfc4 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Mon, 15 Jun 2020 18:59:10 -0400 Subject: [PATCH 431/433] fix missing namespace function --- machine_learning/kohonen_som_trace.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/machine_learning/kohonen_som_trace.cpp b/machine_learning/kohonen_som_trace.cpp index 68c922742d2..6969161001e 100644 --- a/machine_learning/kohonen_som_trace.cpp +++ b/machine_learning/kohonen_som_trace.cpp @@ -171,6 +171,8 @@ void kohonen_som_tracer(const std::vector> &X, /** @} */ +using machine_learning::kohonen_som_tracer; + /** Creates a random set of points distributed *near* the circumference * of a circle and trains an SOM that finds that circular pattern. The * generating function is From 15c20f94b0541c3f5b9169624d02d39391814e22 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 19 Jun 2020 10:57:29 -0400 Subject: [PATCH 432/433] replace kvedala fork references to TheAlgorithms --- README.md | 16 ++++++++-------- machine_learning/kohonen_som_topology.cpp | 2 +- machine_learning/kohonen_som_trace.cpp | 6 +++--- numerical_methods/durand_kerner_roots.cpp | 4 ++-- numerical_methods/ode_forward_euler.cpp | 2 +- numerical_methods/ode_midpoint_euler.cpp | 2 +- numerical_methods/ode_semi_implicit_euler.cpp | 2 +- 7 files changed, 17 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 37f823f7f82..8734158b7d7 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,18 @@ # The Algorithms - C++ # {#mainpage} [![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/TheAlgorithms/C-Plus-Plus) [![Gitter chat](https://img.shields.io/badge/Chat-Gitter-ff69b4.svg?label=Chat&logo=gitter&style=flat-square)](https://gitter.im/TheAlgorithms) -![contributions welcome](https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square) -![GitHub repo size](https://img.shields.io/github/repo-size/kvedala/C-Plus-Plus?color=red&style=flat-square) -![GitHub closed pull requests](https://img.shields.io/github/issues-pr-closed/kvedala/C-Plus-Plus?color=green&style=flat-square) -![Doxygen CI](https://github.com/kvedala/C-Plus-Plus/workflows/Doxygen%20CI/badge.svg) -![Awesome CI](https://github.com/kvedala/C-Plus-Plus/workflows/Awesome%20CI%20Workflow/badge.svg) +![contributions welcome](https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square) +![GitHub repo size](https://img.shields.io/github/repo-size/TheAlgorithms/C-Plus-Plus?color=red&style=flat-square) +![GitHub closed pull requests](https://img.shields.io/github/issues-pr-closed/TheAlgorithms/C-Plus-Plus?color=green&style=flat-square) +![Doxygen CI](https://github.com/TheAlgorithms/C-Plus-Plus/workflows/Doxygen%20CI/badge.svg) +![Awesome CI](https://github.com/TheAlgorithms/C-Plus-Plus/workflows/Awesome%20CI%20Workflow/badge.svg) -[Online Documentation](https://kvedala.github.io/C-Plus-Plus). +[Online Documentation](https://TheAlgorithms.github.io/C-Plus-Plus). -Click on [Files menu](https://kvedala.github.io/C-Plus-Plus/files.html) to see the list of all the files documented with the code. +Click on [Files menu](https://TheAlgorithms.github.io/C-Plus-Plus/files.html) to see the list of all the files documented with the code. ### Algorithms implemented in C++ (for education) The implementations are for learning purpose. They may be less efficient than the implementation in the standard library. ### Contribute Guidelines -Read our [Contribution Guidelines](https://github.com/kvedala/C-Plus-Plus/blob/master/CONTRIBUTING.md) before you contribute. +Read our [Contribution Guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTING.md) before you contribute. diff --git a/machine_learning/kohonen_som_topology.cpp b/machine_learning/kohonen_som_topology.cpp index abb05e8ec3d..25c58e26072 100644 --- a/machine_learning/kohonen_som_topology.cpp +++ b/machine_learning/kohonen_som_topology.cpp @@ -13,7 +13,7 @@ * data points in a much higher dimesional space by creating an equivalent in a * 2-dimensional space. * Trained topological maps for the test cases in the program * \note This C++ version of the program is considerable slower than its [C * counterpart](https://github.com/kvedala/C/blob/master/machine_learning/kohonen_som_trace.c) diff --git a/machine_learning/kohonen_som_trace.cpp b/machine_learning/kohonen_som_trace.cpp index 6969161001e..273a2a57c6c 100644 --- a/machine_learning/kohonen_som_trace.cpp +++ b/machine_learning/kohonen_som_trace.cpp @@ -220,7 +220,7 @@ void test_circle(std::vector> *data) { * "w12.csv" title "w2" * ``` * ![Sample execution - * output](https://raw.githubusercontent.com/kvedala/C-Plus-Plus/docs/images/machine_learning/kohonen/test1.svg) + * output](https://raw.githubusercontent.com/TheAlgorithms/C-Plus-Plus/docs/images/machine_learning/kohonen/test1.svg) */ void test1() { int j, N = 500; @@ -300,7 +300,7 @@ void test_lamniscate(std::vector> *data) { * "w22.csv" title "w2" * ``` * ![Sample execution - * output](https://raw.githubusercontent.com/kvedala/C-Plus-Plus/docs/images/machine_learning/kohonen/test2.svg) + * output](https://raw.githubusercontent.com/TheAlgorithms/C-Plus-Plus/docs/images/machine_learning/kohonen/test2.svg) */ void test2() { int j, N = 500; @@ -397,7 +397,7 @@ void test_3d_classes(std::vector> *data) { * "w32.csv" title "w2" * ``` * ![Sample execution - * output](https://raw.githubusercontent.com/kvedala/C-Plus-Plus/docs/images/machine_learning/kohonen/test3.svg) + * output](https://raw.githubusercontent.com/TheAlgorithms/C-Plus-Plus/docs/images/machine_learning/kohonen/test3.svg) */ void test3() { int j, N = 200; diff --git a/numerical_methods/durand_kerner_roots.cpp b/numerical_methods/durand_kerner_roots.cpp index 89714114340..9bf0619b829 100644 --- a/numerical_methods/durand_kerner_roots.cpp +++ b/numerical_methods/durand_kerner_roots.cpp @@ -20,10 +20,10 @@ * Sample implementation results to compute approximate roots of the equation * \f$x^4-1=0\f$:\n * Error evolution during root approximations computed every
  * iteration. Roots evolution - shows the initial approximation of the
  * roots and their convergence to a final approximation along with the iterative
  * approximations diff --git a/numerical_methods/ode_forward_euler.cpp b/numerical_methods/ode_forward_euler.cpp index 37800e3f28f..a4455c57acd 100644 --- a/numerical_methods/ode_forward_euler.cpp +++ b/numerical_methods/ode_forward_euler.cpp @@ -22,7 +22,7 @@ * The computation results are stored to a text file `forward_euler.csv` and the * exact soltuion results in `exact.csv` for comparison. * Implementation solution * * To implement [Van der Pol diff --git a/numerical_methods/ode_midpoint_euler.cpp b/numerical_methods/ode_midpoint_euler.cpp index 4d1137b3ebf..50cf4e4c6c4 100644 --- a/numerical_methods/ode_midpoint_euler.cpp +++ b/numerical_methods/ode_midpoint_euler.cpp @@ -21,7 +21,7 @@ * \f} * The computation results are stored to a text file `midpoint_euler.csv` and * the exact soltuion results in `exact.csv` for comparison. Implementation solution * * To implement [Van der Pol diff --git a/numerical_methods/ode_semi_implicit_euler.cpp b/numerical_methods/ode_semi_implicit_euler.cpp index e5f25dc3bce..01904ac1684 100644 --- a/numerical_methods/ode_semi_implicit_euler.cpp +++ b/numerical_methods/ode_semi_implicit_euler.cpp @@ -21,7 +21,7 @@ * \f} * The computation results are stored to a text file `semi_implicit_euler.csv` * and the exact soltuion results in `exact.csv` for comparison. Implementation solution * * To implement [Van der Pol From db430a95b3223d1db89684a43c6f471424075eb9 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 19 Jun 2020 12:01:14 -0400 Subject: [PATCH 433/433] fix bug in counting_sort --- sorting/counting_sort_string.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sorting/counting_sort_string.cpp b/sorting/counting_sort_string.cpp index 977f3484dc7..69d80c18a32 100644 --- a/sorting/counting_sort_string.cpp +++ b/sorting/counting_sort_string.cpp @@ -11,7 +11,7 @@ void countSort(string arr) { for (i = 0; arr[i]; ++i) ++count[arr[i]]; - for (i = 1; i <= 256; ++i) count[i] += count[i - 1]; + for (i = 1; i < 256; ++i) count[i] += count[i - 1]; for (i = 0; arr[i]; ++i) { output[count[arr[i]] - 1] = arr[i];