From 69f9210c172ec88e17907cbf63b4dc6218530077 Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Wed, 27 May 2020 18:17:28 +0530 Subject: [PATCH 001/271] Added documentation --- sorting/Quick Sort.cpp | 67 ------------------------------------------ sorting/quick_sort.cpp | 22 ++++++++++++-- 2 files changed, 19 insertions(+), 70 deletions(-) delete mode 100644 sorting/Quick Sort.cpp diff --git a/sorting/Quick Sort.cpp b/sorting/Quick Sort.cpp deleted file mode 100644 index 0b807898f..000000000 --- a/sorting/Quick Sort.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/* 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 - - 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); -} - -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); - } -} - -void show(int arr[], int size) -{ - for (int i = 0; i < size; i++) - cout << arr[i] << "\n"; -} - -// Driver program to test above functions -int main() -{ - int size; - cout << "\nEnter the number of elements : "; - - cin >> size; - - int arr[size]; - - cout << "\nEnter the unsorted elements : "; - - for (int i = 0; i < size; ++i) - { - cout << "\n"; - cin >> arr[i]; - } - quickSort(arr, 0, size); - cout << "Sorted array\n"; - show(arr, size); - return 0; -} diff --git a/sorting/quick_sort.cpp b/sorting/quick_sort.cpp index 12ee66456..5a568014d 100644 --- a/sorting/quick_sort.cpp +++ b/sorting/quick_sort.cpp @@ -1,16 +1,33 @@ -/* +/** * * copyright The Algorithms * Author - * Correction - ayaankhan98 * + * Implementation Details - + * Quick Sort is a divide and conquer algorithm. It picks and element as + * pivot and partition the given array around the picked pivot. There + * are many different versions of quickSort that pick pivot in different + * ways. + * + * 1. Always pick the first element as pivot + * 2. Always pick the last element as pivot (implemented below) + * 3. Pick a random element as pivot + * 4. Pick median as pivot + * + * The key process in quickSort is partition(). Target of partition is, + * given an array and an element x(say) of array as pivot, put x at it's + * correct position in sorted array and put all smaller elements (samller + * than x) before x, and put all greater elements (greater than x) after + * x. All this should be done in linear time + * */ #include #include int partition(int arr[], int low, int high) { - int pivot = arr[high]; // pivot + 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++) { @@ -44,7 +61,6 @@ void show(int arr[], int size) { } // Driver program to test above functions - int main() { int size; std::cout << "\nEnter the number of elements : "; From c1764bd1970031f153fa0f5f2456565706b31d94 Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Wed, 27 May 2020 18:43:57 +0530 Subject: [PATCH 002/271] Added breif comments on functions --- sorting/quick_sort.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/sorting/quick_sort.cpp b/sorting/quick_sort.cpp index 5a568014d..965d117cc 100644 --- a/sorting/quick_sort.cpp +++ b/sorting/quick_sort.cpp @@ -26,6 +26,12 @@ #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 */ + 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 @@ -46,6 +52,10 @@ int partition(int arr[], int low, int high) { 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); @@ -54,6 +64,7 @@ void quickSort(int arr[], int low, int high) { } } +// prints the array after sorting void show(int arr[], int size) { for (int i = 0; i < size; i++) std::cout << arr[i] << " "; From 50d6a14b2a40eb5185bc1858951e14441519e954 Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Wed, 27 May 2020 18:48:22 +0530 Subject: [PATCH 003/271] modified comment block --- sorting/quick_sort.cpp | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/sorting/quick_sort.cpp b/sorting/quick_sort.cpp index 965d117cc..08db9c92e 100644 --- a/sorting/quick_sort.cpp +++ b/sorting/quick_sort.cpp @@ -26,11 +26,14 @@ #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 */ +/** + * 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 @@ -52,10 +55,12 @@ int partition(int arr[], int low, int high) { return (i + 1); } -/* 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); From fb1d69fb1410b092ba66cf53fd473a1473f50d3d Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Wed, 27 May 2020 18:51:05 +0530 Subject: [PATCH 004/271] further improved comment blocks --- sorting/quick_sort.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/sorting/quick_sort.cpp b/sorting/quick_sort.cpp index 08db9c92e..d067fa068 100644 --- a/sorting/quick_sort.cpp +++ b/sorting/quick_sort.cpp @@ -27,13 +27,13 @@ #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 From 326b3037b4d97d2624fef320d190a93aa71266c5 Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Wed, 27 May 2020 22:39:19 +0530 Subject: [PATCH 005/271] free dynamically allocated memory --- sorting/quick_sort.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/sorting/quick_sort.cpp b/sorting/quick_sort.cpp index d067fa068..e09ad184c 100644 --- a/sorting/quick_sort.cpp +++ b/sorting/quick_sort.cpp @@ -89,5 +89,6 @@ int main() { quickSort(arr, 0, size-1); std::cout << "Sorted array : "; show(arr, size); + delete [] arr; return 0; } From 1b5dee74c049857179b6da63c3696123b6684f28 Mon Sep 17 00:00:00 2001 From: Taj Date: Fri, 12 Jun 2020 23:47:32 +0100 Subject: [PATCH 006/271] feat: Added a function for finding the least common multiple (#840) * feat: Added a function for finding the least common multiple * feat: Miller-Rabin Primality Test (probabilistic) * Added test assertions * Mistakenly worked on a different branch * Doxygen comments * Comments changed --- math/least_common_multiple.cpp | 70 ++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 math/least_common_multiple.cpp diff --git a/math/least_common_multiple.cpp b/math/least_common_multiple.cpp new file mode 100644 index 000000000..741945716 --- /dev/null +++ b/math/least_common_multiple.cpp @@ -0,0 +1,70 @@ +/** + * Copyright 2020 @author tjgurwara99 + * @file + * + * A basic implementation of LCM function + */ + +#include +#include + +/** + * Function for finding greatest common divisor of two numbers. + * @params two integers x and y whose gcd we want to find. + * @return greatest common divisor of x and y. + */ +unsigned int gcd(unsigned int x, unsigned int y) { + if (x == 0) { + return y; + } + if (y == 0) { + return x; + } + if (x == y) { + return x; + } + if (x > y) { + // The following is valid because we have checked whether y == 0 + + int temp = x / y; + return gcd(y, x - temp * y); + } + // Again the following is valid because we have checked whether x == 0 + + int temp = y / x; + return gcd(x, y - temp * x); +} + +/** + * Function for finding the least common multiple of two numbers. + * @params integer x and y whose lcm we want to find. + * @return lcm of x and y using the relation x * y = gcd(x, y) * lcm(x, y) + */ +unsigned int lcm(unsigned int x, unsigned int y) { return x * y / gcd(x, y); } + +/** + * Function for testing the lcm() functions with some assert statements. + */ +void tests() { + // First test on lcm(5,10) == 10 + assert(((void)"LCM of 5 and 10 is 10 but lcm function gives a different " + "result.\n", + lcm(5, 10) == 10)); + std::cout << "First assertion passes: LCM of 5 and 10 is " << lcm(5, 10) + << std::endl; + + // Second test on lcm(2,3) == 6 as 2 and 3 are coprime (prime in fact) + assert(((void)"LCM of 2 and 3 is 6 but lcm function gives a different " + "result.\n", + lcm(2, 3) == 6)); + std::cout << "Second assertion passes: LCM of 2 and 3 is " << lcm(2, 3) + << std::endl; +} + +/** + * Main function + */ +int main() { + tests(); + return 0; +} From 282973453271a1df7d953e270b4ed96205457521 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 12 Jun 2020 22:47:55 +0000 Subject: [PATCH 007/271] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 5eb085bc0..f8ad585d5 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -115,6 +115,7 @@ * [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) + * [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 026557115ca9063b547996846f0d6e813fd90602 Mon Sep 17 00:00:00 2001 From: Omkar Langhe Date: Sat, 13 Jun 2020 21:15:37 +0530 Subject: [PATCH 008/271] Adding algorithm to check if number is prime or not. (#834) * Optimized algorithm to check if number is prime or not. * logic to check if given number is prime or not. * logic to check if given number is prime or not. * logic to check if given number is prime or not. * logic to check if given number is prime or not. * Included appropriate comments as per standards. * variable name renamed to num * added @file and @brief in comment. Also added template and variable name changed from is_prime to result * added @file and @brief in comment. Also added template and variable name changed from is_prime to result * added template parameter T type in loop --- math/check_prime.cpp | 58 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 math/check_prime.cpp diff --git a/math/check_prime.cpp b/math/check_prime.cpp new file mode 100644 index 000000000..e517d774e --- /dev/null +++ b/math/check_prime.cpp @@ -0,0 +1,58 @@ +/** + * Copyright 2020 @author omkarlanghe + * + * @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. + */ +#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 +bool is_prime(T num) { + bool result = true; + if (num <= 1) { + return 0; + } else if (num == 2) { + return 1; + } else if ((num & 1) == 0) { + return 0; + } + if (num >= 3) { + for (T i = 3 ; (i*i) < (num) ; i = (i + 2)) { + if ((num % i) == 0) { + result = false; + break; + } + } + } + return (result); +} + +/** + * Main function + */ +int main() { + int num; + 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; + } else { + std::cout << num << " is not a prime number" << + std::endl; + } + assert(is_prime(50) == false); + assert(is_prime(115249) == true); +} From 70a2aeedc369fbbc7313b768e0f5e9c673bcd86f Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 13 Jun 2020 15:45:53 +0000 Subject: [PATCH 009/271] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index f8ad585d5..1575561b8 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -107,6 +107,7 @@ ## Math * [Binary Exponent](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/binary_exponent.cpp) + * [Check Prime](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/check_prime.cpp) * [Double Factorial](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/double_factorial.cpp) * [Eulers Totient Function](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/eulers_totient_function.cpp) * [Extended Euclid Algorithm](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/extended_euclid_algorithm.cpp) From de4578c1a47d9c03eb96aa863ed109bec80933f5 Mon Sep 17 00:00:00 2001 From: Neeraj C Date: Mon, 15 Jun 2020 22:11:20 +0530 Subject: [PATCH 010/271] feat: add sum of digits --- math/sum_of_digits.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 math/sum_of_digits.cpp diff --git a/math/sum_of_digits.cpp b/math/sum_of_digits.cpp new file mode 100644 index 000000000..d3e7d3291 --- /dev/null +++ b/math/sum_of_digits.cpp @@ -0,0 +1,28 @@ +/** + * A simple C++ Program to find the Sum of Digits of input integer. + */ +#include + +/** + * Function to find the sum of the digits of an integer. + * @param num The integer. + * @return Sum of the digits of the integer. + */ +int sum_of_digits(int num) { + int sum = 0; + while (num > 0) { + sum = sum + (num % 10); + num = num / 10; + } + return sum; +} + +int main() { + int num; + std::cin >> num; + if (num < 0) { + num = -1 * num; + } + std::cout << sum_of_digits(num); + return 0; +} \ No newline at end of file From d86a9b56df77b0b6544c2d40fb1482c41a779dc3 Mon Sep 17 00:00:00 2001 From: Neeraj C Date: Mon, 15 Jun 2020 23:17:50 +0530 Subject: [PATCH 011/271] fix: sum of digits bug --- math/sum_of_digits.cpp | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/math/sum_of_digits.cpp b/math/sum_of_digits.cpp index d3e7d3291..b259e48da 100644 --- a/math/sum_of_digits.cpp +++ b/math/sum_of_digits.cpp @@ -1,7 +1,11 @@ /** - * A simple C++ Program to find the Sum of Digits of input integer. + * Copyright 2020 @author iamnambiar + * + * @file + * A C++ Program to find the Sum of Digits of input integer. */ #include +#include /** * Function to find the sum of the digits of an integer. @@ -9,6 +13,9 @@ * @return Sum of the digits of the integer. */ int sum_of_digits(int num) { + if (num < 0) { + num = -1 * num; + } int sum = 0; while (num > 0) { sum = sum + (num % 10); @@ -17,12 +24,18 @@ int sum_of_digits(int num) { return sum; } -int main() { - int num; - std::cin >> num; - if (num < 0) { - num = -1 * num; +/** + * Test function. + */ +void test() { + int test_case_1 = sum_of_digits(119765); + int test_case_2 = sum_of_digits(-12256); + assert(test_case_1 == 29); + assert(test_case_2 == 16); } - std::cout << sum_of_digits(num); + +int main() { + test(); + std::cout << "Success."; return 0; -} \ No newline at end of file +} From 2191ef4881f6b3a94b9f26189b320fb27ef06692 Mon Sep 17 00:00:00 2001 From: Neeraj C Date: Mon, 15 Jun 2020 23:26:58 +0530 Subject: [PATCH 012/271] fix: whitespace issue in sum_of_digits --- math/sum_of_digits.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/math/sum_of_digits.cpp b/math/sum_of_digits.cpp index b259e48da..cf8c28360 100644 --- a/math/sum_of_digits.cpp +++ b/math/sum_of_digits.cpp @@ -27,7 +27,7 @@ int sum_of_digits(int num) { /** * Test function. */ -void test() { +void test() { int test_case_1 = sum_of_digits(119765); int test_case_2 = sum_of_digits(-12256); assert(test_case_1 == 29); From 12f0ec3c45fc2789be69a8a579b0eee92e356412 Mon Sep 17 00:00:00 2001 From: Neeraj C Date: Tue, 16 Jun 2020 08:03:14 +0530 Subject: [PATCH 013/271] test: add two test functions --- math/sum_of_digits.cpp | 40 +++++++++++++++++++++++++++++++++++----- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/math/sum_of_digits.cpp b/math/sum_of_digits.cpp index cf8c28360..460bff691 100644 --- a/math/sum_of_digits.cpp +++ b/math/sum_of_digits.cpp @@ -11,8 +11,17 @@ * Function to find the sum of the digits of an integer. * @param num The integer. * @return Sum of the digits of the integer. + * + * \detail + * First the algorithm check whether the num is negative or positive, + * if it is negative, then we neglect the negative sign. + * Next, the algorithm extract the last digit of num by dividing by 10 + * and extracting the remainder and this is added to the sum. + * The number is then divided by 10 to remove the last digit. + * This loop continues until num becomes 0. */ int sum_of_digits(int num) { + // If num is negative then negative sign is neglected. if (num < 0) { num = -1 * num; } @@ -25,17 +34,38 @@ int sum_of_digits(int num) { } /** - * Test function. + * Function for testing the sum_of_digits() function with a + * first test case of 119765 and assert statement. */ -void test() { +void test1() { int test_case_1 = sum_of_digits(119765); - int test_case_2 = sum_of_digits(-12256); assert(test_case_1 == 29); - assert(test_case_2 == 16); } +/** + * Function for testing the sum_of_digits() function with a + * second test case of -12256 and assert statement. + */ +void test2() { + int test_case_2 = sum_of_digits(-12256); + assert(test_case_2 == 16); + } +/** + * Function for testing the sum_of_digits() with + * all the test cases. + */ +void test() { + //First test. + test1(); + //Second test. + test2(); + } + +/** + * Main Function +*/ int main() { test(); - std::cout << "Success."; + std::cout << "Success." << std::endl; return 0; } From 05aa382a168b817145e6a956096fe88dac147e95 Mon Sep 17 00:00:00 2001 From: Neeraj C Date: Tue, 16 Jun 2020 08:05:06 +0530 Subject: [PATCH 014/271] docs: comment space fix --- math/sum_of_digits.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/math/sum_of_digits.cpp b/math/sum_of_digits.cpp index 460bff691..42f0b5e82 100644 --- a/math/sum_of_digits.cpp +++ b/math/sum_of_digits.cpp @@ -55,9 +55,9 @@ void test2() { * all the test cases. */ void test() { - //First test. + // First test. test1(); - //Second test. + // Second test. test2(); } From d9e3053fade7b68a9fd61b72b5a2b0db72cd98a3 Mon Sep 17 00:00:00 2001 From: Neeraj C Date: Thu, 18 Jun 2020 11:04:27 +0530 Subject: [PATCH 015/271] fix: formatting code style. --- math/sum_of_digits.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/math/sum_of_digits.cpp b/math/sum_of_digits.cpp index 42f0b5e82..bcb6d7956 100644 --- a/math/sum_of_digits.cpp +++ b/math/sum_of_digits.cpp @@ -40,7 +40,7 @@ int sum_of_digits(int num) { void test1() { int test_case_1 = sum_of_digits(119765); assert(test_case_1 == 29); - } +} /** * Function for testing the sum_of_digits() function with a @@ -49,7 +49,8 @@ void test1() { void test2() { int test_case_2 = sum_of_digits(-12256); assert(test_case_2 == 16); - } +} + /** * Function for testing the sum_of_digits() with * all the test cases. @@ -59,7 +60,7 @@ void test() { test1(); // Second test. test2(); - } +} /** * Main Function From aaa08b0150acc987a47f87b26d64dbbdf96945ac Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 19 Jun 2020 12:04:56 -0400 Subject: [PATCH 016/271] Major rework to improve code quality and add automation checks (#805) * delete secant method - it is identical to regula falsi * document + improvize root finding algorithms * attempt to document gaussian elimination * added file brief * commented doxygen-mainpage, added files-list link * corrected files list link path * files-list link correction - this time works :) * document successive approximations * cleaner equation * updating DIRECTORY.md * documented kmp string search * document brute force string search * document rabin-karp string search * fixed mainpage readme * doxygen v1.8.18 will suppress out the #minipage in the markdown * cpplint correction for header guard style * github action to auto format source code per cpplint standard * updated setting to add 1 space before `private` and `public` keywords * auto rename files and auto format code * added missing "run" for step * corrected asignmemt operation * fixed trim and assign syntax * added git move for renaming bad filenames * added missing pipe for trim * added missing space * use old and new fnames * store old fname using echo * move files only if there is a change in filename * put old filenames in quotes * use double quote for old filename * escape double quotes * remove old_fname * try escape characters and echo" * add file-type to find * cleanup echo * ensure all trim variables are also in quotes * try escape -quote again * remove second escpe quote * use single quote for first check * use carets instead of quotes * put variables in brackets * remove -e from echo * add debug echos * try print0 flag * find command with while instead of for-loop * find command using IFS instead * :tada: IFS fix worked - escaped quotes for git mv * protetc each word in git mv .. * filename exists in lower cases - renamed * :tada: git push enabled * updating DIRECTORY.md * git pull & then push * formatting filenames d7af6fdc8cb08578de6980d412e6e1caca1a1bcf * formatting source-code for d7af6fdc8cb08578de6980d412e6e1caca1a1bcf * remove allman break before braces * updating DIRECTORY.md * added missing comma lost in previous commit * orchestrate all workflows * fix yml indentation * force push format changes, add title to DIRECTORY.md * pull before proceeding * reorganize pull commands * use master branches for actions * rename .cc files to .cpp * added class destructor to clean up dynamic memory allocation * rename to awesome workflow * commented whole repo cpplint - added modified files lint check * removed need for cpplint * attempt to use actions/checkout@master * temporary: no dependency on cpplint * formatting filenames 153fb7b8a572aaf4561ac3d22d47e89480f11318 * formatting source-code for 153fb7b8a572aaf4561ac3d22d47e89480f11318 * updating DIRECTORY.md * fix diff filename * added comments to the code * added test case * formatting source-code for a850308fbada18c0d4b6f9a9cac5c34fc064cbae * updating DIRECTORY.md * added machine learning folder * added adaline algorithm * updating DIRECTORY.md * fixed issue [LWG2192](https://cplusplus.github.io/LWG/issue2192) for std::abs on MacOS * add cmath for same bug: [LWG2192](https://cplusplus.github.io/LWG/issue2192) for std::abs on MacOS * formatting source-code for f8925e482216aecd152bc898653ee9ab82213cf3 * use STL's inner_product * formatting source-code for f94a3305943d4cf00e4531857279b8032d0e9489 * added range comments * define activation function * use equal initial weights * change test2 function to predict * activation function not friend * previous commit correction * added option for predict function to return value before applying activation function as optional argument * added test case to classify points lying within a sphere * improve documentation for adaline * formatting source-code for 15ec4c3aba4fb41b81ed2b44b7154a4f7b45a898 * added cmake to geometry folder * added algorithm include for std::max * add namespace - machine_learning * add namespace - statistics * add namespace - sorting * added sorting algos to namespace sorting * added namespace string_search * formatting source-code for fd695305150777981dc2a1f256aa2be444e4f108 * added documentation to string_search namespace * feat: Add BFS and DFS algorithms to check for cycle in a directed graph * Remove const references for input of simple types Reason: overhead on access * fix bad code sorry for force push * Use pointer instead of the non-const reference because apparently google says so. * Remove a useless and possibly bad Graph constuctor overload * Explicitely specify type of vector during graph instantiation * updating DIRECTORY.md * find openMP before adding subdirectories * added kohonen self organizing map * updating DIRECTORY.md * remove older files and folders from gh-pages before adding new files * remove chronos library due to inacceptability by cpplint * use c++ specific static_cast instead * initialize radom number generator * updated image links with those from CPP repository * rename computer.... folder to numerical methods * added durand kerner method for root computation for arbitrarily large polynomials * fixed additional comma * fix cpplint errors * updating DIRECTORY.md * convert to function module * update documentation * move openmp to main loop * added two test cases * use INT16_MAX * remove return statement from omp-for loop and use "break" * run tests when no input is provided and skip tests when input polynomial is provided * while loop cannot have break - replaced with continue and check is present in the main while condition * (1) break while loop (2) skip runs on break_loop instead of hard-break * add documentation images * use long double for errors and tolerance checks * make iterator variable i local to threads * add critical secions to omp threads * bugfix: move file writing outside of the parallel loop othersie, there is no gurantee of the order of roots written to file * rename folder to data_structures * updating DIRECTORY.md * fix ambiguous symbol `size` * add data_structures to cmake * docs: enable tree view, add timestamp in footer, try clang assistaed parsing * doxygen - open links in external window * remove invalid parameter from function docs * use HTML5 img tag to resize images * move file to proper folder * fix documentations and cpplint * formatting source-code for aacaf9828c61bb0246fe0933ab8ade82128b8346 * updating DIRECTORY.md * cpplint: add braces for multiple statement if * add explicit link to badges * remove duplicate line Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * remove namespace indentation * remove file associations in settings * add author name * enable cmake in subfolders of data_structures * create and link object file * cpp lint fixes and instantiate template classes * cpp lint fixes and instantiate template classes Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * cpplint - ignore `build/include` Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * disable redundant gcc compilation in cpplint workflow Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * template header files contain function codes as well and removed redundant subfolders Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * updating DIRECTORY.md * remove semicolons after functions in a class Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * cpplint header guard style Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * remove semilon Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * added LU decomposition algorithm Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * added QR decomposition algorithm Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * use QR decomposition to find eigen values Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * updating DIRECTORY.md * use std::rand for thread safety Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * move srand to main() Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * cpplint braces correction Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * updated eigen value documentation Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * fix matrix shift doc Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * rename CONTRIBUTION.md to CONTRIBUTING.md #836 * remove 'sort alphabetical order' check * added documentation check * remove extra paranthesis * added gitpod * added gitpod link from README * attempt to add vscode gitpod extensions * update gitpod extensions * add gitpod extensions cmake-tools and git-graph * remove gitpod init and add commands * use init to one time install doxygen, graphviz, cpplint * use gitpod dockerfile * add ninja build system to docker * remove configure task * add github prebuild specs to gitpod * disable gitpod addcommit * update documentation for kohonen_som * added ode solve using forward euler method * added mid-point euler ode solver * fixed itegration step equation * added semi-implicit euler ODE solver * updating DIRECTORY.md * fix cpplint issues - lines 117 and 124 * added documentation to ode group * corrected semi-implicit euler function * updated docs and test cases better structure * replace `free` with `delete` operator * formatting source-code for f55ab50cf26d176fe56bdaffa6f0ce8023c03c18 * updating DIRECTORY.md * main function must return * added machine learning group * added kohonen som topology algorithm * fix graph image path * updating DIRECTORY.md * fix braces * use snprintf instead of sprintf * use static_cast * hardcode character buffer size * fix machine learning groups in documentation * fix missing namespace function * replace kvedala fork references to TheAlgorithms * fix bug in counting_sort Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Anmol3299 --- .github/pull_request_template.md | 8 +- .github/workflows/awesome_forkflow.yml | 211 + .github/workflows/cpplint.yml | 13 - .github/workflows/cpplint_modified_files.yml | 64 - .github/workflows/gh-pages.yml | 36 + .../sorting_non_recursive_merge_sort.yml | 24 - .github/workflows/update_directory_md.yml | 68 - .gitignore | 2 + .gitpod.dockerfile | 9 + .gitpod.yml | 17 + .vscode/settings.json | 69 +- CMakeLists.txt | 81 + CONTRIBUTION.md => CONTRIBUTING.md | 0 DIRECTORY.md | 244 +- README.md | 16 +- backtracking/graph_coloring.cpp | 29 +- backtracking/knight_tour.cpp | 80 +- backtracking/minimax.cpp | 2 +- backtracking/n_queens.cpp | 36 +- .../n_queens_all_solution_optimised.cpp | 26 +- backtracking/rat_maze.cpp | 103 +- backtracking/sudoku_solve.cpp | 98 +- .../Bisection_method.CPP | 53 - .../Gaussian_elimination.cpp | 63 - .../Newton_Raphson.CPP | 53 - .../Secant_method.CPP | 49 - .../false-position.cpp | 35 - .../ordinary_least_squares_regressor.cpp | 349 - .../successive_approximation.CPP | 37 - data_structure/AVLtree.cpp | 176 - data_structure/Binary Search Tree.cpp | 218 - data_structure/Binaryheap.cpp | 158 - data_structure/List Array.cpp | 188 - data_structure/MorrisInorder.cpp | 108 - data_structure/Queue Using Array.cpp | 75 - data_structure/Stack Using Array.cpp | 79 - data_structure/Stack Using Linked List.cpp | 73 - data_structure/cll/cll.h | 45 - data_structure/cll/main_cll.cpp | 44 - data_structure/cll/makefile | 11 - data_structure/disjoint_set.cpp | 64 - data_structure/doubly_linked_list.cpp | 138 - .../linkedList_implentation_usingArray.cpp | 106 - data_structure/linked_list.cpp | 135 - data_structure/queue/makefile | 11 - data_structure/queue/queue.cpp | 90 - data_structure/queue/queue.h | 34 - data_structure/queue/test_queue.cpp | 38 - data_structure/queue_using_linkedlist.cpp | 98 - data_structure/stk/makefile | 13 - data_structure/stk/stack.cpp | 114 - data_structure/stk/stack.h | 35 - data_structure/stk/test_stack.cpp | 54 - data_structure/trie_tree.cpp | 90 - data_structures/CMakeLists.txt | 20 + data_structures/avltree.cpp | 148 + data_structures/binary_search_tree.cpp | 174 + data_structures/binaryheap.cpp | 144 + .../circular_queue_using_linked_list.cpp | 42 +- data_structures/cll/CMakeLists.txt | 5 + .../cll/cll.cpp | 65 +- data_structures/cll/cll.h | 43 + data_structures/cll/main_cll.cpp | 43 + data_structures/disjoint_set.cpp | 62 + data_structures/doubly_linked_list.cpp | 136 + data_structures/linked_list.cpp | 134 + .../linkedlist_implentation_usingarray.cpp | 114 + data_structures/list_array.cpp | 153 + data_structures/morrisinorder.cpp | 92 + data_structures/queue.h | 88 + .../queue_using_array.cpp | 3 +- data_structures/queue_using_array2.cpp | 57 + .../queue_using_linked_list.cpp | 49 +- data_structures/queue_using_linkedlist.cpp | 86 + data_structures/stack.h | 111 + data_structures/stack_using_array.cpp | 55 + data_structures/stack_using_linked_list.cpp | 57 + .../stk => data_structures}/student.txt | 0 data_structures/test_queue.cpp | 41 + data_structures/test_stack.cpp | 59 + .../test_stack_students.cpp | 31 +- .../Tree.cpp => data_structures/tree.cpp | 71 +- .../trie_modern.cpp | 9 +- data_structures/trie_tree.cpp | 87 + doc/cppreference-doxygen-web.tag.xml | 35489 ++++++++++++++++ dynamic_programming/0-1 Knapsack.cpp | 71 - dynamic_programming/0_1_knapsack.cpp | 66 + dynamic_programming/Bellman-Ford.cpp | 128 - dynamic_programming/Coin-Change.cpp | 50 - dynamic_programming/Cut Rod.cpp | 28 - dynamic_programming/Fibonacci_Bottom_Up.cpp | 24 - dynamic_programming/Fibonacci_Top_Down.cpp | 26 - dynamic_programming/Floyd-Warshall.cpp | 112 - .../Longest Common Subsequence.cpp | 82 - ...Longest Increasing Subsequence (nlogn).cpp | 46 - .../Longest Increasing Subsequence.cpp | 39 - .../Matrix-Chain-Multiplication.cpp | 62 - dynamic_programming/armstrong_number.cpp | 28 +- dynamic_programming/bellman_ford.cpp | 116 + ...atalan-Numbers.cpp => catalan_numbers.cpp} | 16 +- dynamic_programming/coin_change.cpp | 48 + dynamic_programming/cut_rod.cpp | 25 + .../{Edit Distance.cpp => edit_distance.cpp} | 49 +- ...ing-Puzzle.cpp => egg_dropping_puzzle.cpp} | 31 +- dynamic_programming/fibonacci_bottom_up.cpp | 21 + dynamic_programming/fibonacci_top_down.cpp | 22 + dynamic_programming/floyd_warshall.cpp | 107 + dynamic_programming/kadane.cpp | 5 +- dynamic_programming/longest_common_string.cpp | 80 +- .../longest_common_subsequence.cpp | 65 + .../longest_increasing_subsequence.cpp | 32 + ...longest_increasing_subsequence_(nlogn).cpp | 41 + .../matrix_chain_multiplication.cpp | 61 + .../searching_of_element_in_dynamic_array.cpp | 68 +- dynamic_programming/tree_height.cpp | 26 +- geometry/CMakeLists.txt | 18 + geometry/line_segment_intersection.cpp | 61 +- graph/BFS.cpp | 73 - graph/DFS.cpp | 31 - graph/Kruskal.cpp | 135 - graph/Topological-Sort.cpp | 53 - graph/bfs.cpp | 62 + .../bridge_finding_with_tarjan_algorithm.cpp | 34 +- graph/connected_components.cpp | 49 +- graph/connected_components_with_dsu.cpp | 5 +- graph/cycle_check_directed_graph.cpp | 302 + graph/dfs.cpp | 26 + .../{DFS_with_stack.cc => dfs_with_stack.cpp} | 20 +- graph/{Dijkstra.cpp => dijkstra.cpp} | 33 +- graph/kosaraju.cpp | 165 +- graph/kruskal.cpp | 115 + graph/lca.cpp | 76 +- ...th_ford_fulkerson_and_edmond_karp_algo.cpp | 45 +- graph/prim.cpp | 18 +- graph/topological_sort.cpp | 47 + graph/topological_sort_by_kahns_algo.cpp | 16 +- greedy_algorithms/Knapsack.cpp | 92 - .../Kruskals Minimum Spanning Tree.cpp | 37 - .../Prims Minimum Spanning Tree.cpp | 79 - .../{Dijkstra.cpp => dijkstra.cpp} | 93 +- greedy_algorithms/huffman.cpp | 207 +- greedy_algorithms/knapsack.cpp | 78 + .../kruskals_minimum_spanning_tree.cpp | 31 + .../prims_minimum_spanning_tree.cpp | 64 + hashing/Chaining.cpp | 140 - hashing/chaining.cpp | 116 + hashing/double_hash_hash_table.cpp | 44 +- hashing/linear_probing_hash_table.cpp | 33 +- hashing/quadratic_probing_hash_table.cpp | 47 +- machine_learning/CMakeLists.txt | 18 + machine_learning/adaline_learning.cpp | 351 + machine_learning/kohonen_som_topology.cpp | 595 + machine_learning/kohonen_som_trace.cpp | 474 + math/CMakeLists.txt | 18 + math/README.md | 1 + math/binary_exponent.cpp | 59 +- math/check_prime.cpp | 35 +- math/double_factorial.cpp | 49 +- math/eulers_totient_function.cpp | 65 +- math/extended_euclid_algorithm.cpp | 102 +- math/factorial.cpp | 11 +- math/fast_power.cpp | 74 +- math/fibonacci.cpp | 26 +- math/fibonacci_fast.cpp | 53 + math/fibonacci_large.cpp | 85 + ...lidean.cpp => gcd_iterative_euclidean.cpp} | 18 +- math/gcd_of_n_numbers.cpp | 41 + math/gcd_recursive_euclidean.cpp | 52 + math/greatest_common_divisor.cpp | 27 - math/large_factorial.cpp | 118 + math/large_number.h | 288 + .../modular_inverse_fermat_little_theorem.cpp | 81 +- math/number_of_positive_divisors.cpp | 46 +- math/power_for_huge_numbers.cpp | 147 +- math/prime_factorization.cpp | 73 +- math/prime_numbers.cpp | 15 +- ...p_to_10^8.cpp => primes_up_to_billion.cpp} | 17 +- math/realtime_stats.cpp | 193 + math/sieve_of_eratosthenes.cpp | 74 +- math/sqrt_double.cpp | 50 +- math/string_fibonacci.cpp | 89 + numerical_methods/CMakeLists.txt | 18 + numerical_methods/bisection_method.cpp | 75 + numerical_methods/durand_kerner_roots.cpp | 339 + numerical_methods/false_position.cpp | 74 + numerical_methods/gaussian_elimination.cpp | 76 + numerical_methods/lu_decompose.cpp | 126 + numerical_methods/newton_raphson_method.cpp | 59 + numerical_methods/ode_forward_euler.cpp | 210 + numerical_methods/ode_midpoint_euler.cpp | 214 + numerical_methods/ode_semi_implicit_euler.cpp | 211 + .../ordinary_least_squares_regressor.cpp | 406 + numerical_methods/qr_decompose.h | 210 + numerical_methods/qr_decomposition.cpp | 58 + numerical_methods/qr_eigen_values.cpp | 284 + .../successive_approximation.cpp | 40 + .../Array Left Rotation.cpp | 39 - .../Circular Linked List.cpp | 114 - .../Circular Queue Using Array.cpp | 74 - .../Intersection_of_2_arrays.cpp | 31 - .../Reverse a Linked List using Recusion.cpp | 76 - .../Union_of_2_arrays.cpp | 34 - .../array_left_rotation.cpp | 31 + ... Rotation.cpp => array_right_rotation.cpp} | 22 +- .../circular_linked_list.cpp | 97 + .../circular_queue_using_array.cpp | 57 + .../intersection_of_2_arrays.cpp | 26 + .../reverse_a_linked_list_using_recusion.cpp | 63 + .../selectionSortLinkedList.cpp | 159 - .../selectionsortlinkedlist.cpp | 172 + .../union_of_2_arrays.cpp | 27 + others/Buzz_number.cpp | 17 - others/CMakeLists.txt | 18 + others/Decimal To Binary.cpp | 25 - others/Decimal To Hexadecimal .cpp | 28 - others/GCD_of_n_numbers.cpp | 23 - others/Palindromeofnumber.cpp | 23 - others/Paranthesis Matching.cpp | 76 - others/Primality Test.cpp | 32 - others/Sparse matrix.cpp | 41 - others/Strassen Matrix Multiplication.cpp | 56 - others/String Fibonacci.cpp | 83 - others/Tower of Hanoi.cpp | 73 - others/buzz_number.cpp | 20 + others/decimal_to_binary.cpp | 55 + others/decimal_to_hexadecimal.cpp | 34 + ...meral.cpp => decimal_to_roman_numeral.cpp} | 69 +- others/fast_interger_input.cpp | 20 +- others/fibonacci.cpp | 42 - others/happy_number.cpp | 57 +- others/matrix_exponentiation.cpp | 76 +- others/measure_time_elapsed.cpp | 19 - others/palindrome_of_number.cpp | 35 + others/paranthesis_matching.cpp | 75 + others/pascal_triangle.cpp | 118 +- others/primality_test.cpp | 42 + others/sieve_of_Eratosthenes.cpp | 60 - others/smallest-circle.cpp | 121 - others/smallest_circle.cpp | 205 + others/sparse_matrix.cpp | 48 + others/spiral_print.cpp | 83 +- others/stairs_pattern.cpp | 60 +- others/tower_of_hanoi.cpp | 85 + others/vector_important_functions.cpp | 60 +- probability/CMakeLists.txt | 18 + probability/addition_rule.cpp | 30 +- probability/bayes_theorem.cpp | 26 +- probability/binomial_dist.cpp | 103 +- probability/poisson_dist.cpp | 61 +- range_queries/MO.cpp | 77 - range_queries/bit.cpp | 52 +- .../{FenwickTree.cpp => fenwicktree.cpp} | 20 +- range_queries/mo.cpp | 64 + range_queries/segTree.cpp | 92 - range_queries/segtree.cpp | 79 + search/CMakeLists.txt | 18 + search/Interpolation Search.cpp | 31 - search/Linear Search.cpp | 47 - search/binary_search.cpp | 58 +- search/exponential_search.cpp | 126 +- search/hash_search.cpp | 147 +- search/interpolation_search.cpp | 89 +- search/interpolation_search2.cpp | 46 + search/jump_search.cpp | 37 +- search/linear_search.cpp | 53 + search/median_search.cpp | 126 +- search/searching.cpp | 40 - search/ternary_search.cpp | 206 +- search/text_search.cpp | 42 + sorting/BeadSort.cpp | 63 - sorting/BitonicSort.cpp | 76 - sorting/Bubble Sort.cpp | 83 - sorting/CMakeLists.txt | 20 + sorting/CocktailSelectionSort.cpp | 109 - sorting/Counting_Sort.cpp | 66 - sorting/Insertion Sort.cpp | 40 - sorting/Merge Sort.cpp | 93 - sorting/NumericStringSort.cpp | 62 - sorting/OddEven Sort.cpp | 61 - sorting/Radix Sort.cpp | 68 - sorting/Selection Sort.cpp | 39 - sorting/Shell Sort.cpp | 45 - sorting/Slow Sort.cpp | 57 - sorting/bead_sort.cpp | 56 + sorting/bitonic_sort.cpp | 64 + sorting/bubble_sort.cpp | 83 + sorting/bucketSort.cpp | 42 - sorting/bucket_sort.cpp | 36 + sorting/cocktail_selection_sort.cpp | 102 + sorting/comb_sort.cpp | 49 + sorting/combsort.cpp | 59 - sorting/counting_sort.cpp | 57 + ...ortString.cpp => counting_sort_string.cpp} | 22 +- sorting/doxy.txt | 374 - sorting/insertion_sort.cpp | 36 + sorting/library_sort.cpp | 6 +- sorting/makefile | 11 - sorting/merge_sort.cpp | 81 + sorting/non_recursive_merge_sort.cpp | 65 +- sorting/numeric_string_sort.cpp | 55 + sorting/odd_even_sort.cpp | 53 + sorting/quick_sort.cpp | 57 +- sorting/radix_sort.cpp | 58 + sorting/selection_sort.cpp | 33 + sorting/shell_sort.cpp | 37 + sorting/shell_sort2.cpp | 234 + sorting/slow_sort.cpp | 56 + sorting/swap_sort.cpp | 4 +- sorting/{Tim Sort.cpp => tim_sort.cpp} | 110 +- strings/CMakeLists.txt | 18 + strings/brute_force_string_searching.cpp | 93 +- strings/knuth_morris_pratt.cpp | 127 +- strings/rabin_karp.cpp | 113 +- 313 files changed, 49332 insertions(+), 9833 deletions(-) create mode 100644 .github/workflows/awesome_forkflow.yml delete mode 100644 .github/workflows/cpplint.yml delete mode 100644 .github/workflows/cpplint_modified_files.yml create mode 100644 .github/workflows/gh-pages.yml delete mode 100644 .github/workflows/sorting_non_recursive_merge_sort.yml delete mode 100644 .github/workflows/update_directory_md.yml create mode 100644 .gitpod.dockerfile create mode 100644 .gitpod.yml create mode 100644 CMakeLists.txt rename CONTRIBUTION.md => CONTRIBUTING.md (100%) delete mode 100644 computer_oriented_statistical_methods/Bisection_method.CPP delete mode 100644 computer_oriented_statistical_methods/Gaussian_elimination.cpp delete mode 100644 computer_oriented_statistical_methods/Newton_Raphson.CPP delete mode 100644 computer_oriented_statistical_methods/Secant_method.CPP delete mode 100644 computer_oriented_statistical_methods/false-position.cpp delete mode 100644 computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp delete mode 100644 computer_oriented_statistical_methods/successive_approximation.CPP delete mode 100644 data_structure/AVLtree.cpp delete mode 100644 data_structure/Binary Search Tree.cpp delete mode 100644 data_structure/Binaryheap.cpp delete mode 100644 data_structure/List Array.cpp delete mode 100644 data_structure/MorrisInorder.cpp delete mode 100644 data_structure/Queue Using Array.cpp delete mode 100644 data_structure/Stack Using Array.cpp delete mode 100644 data_structure/Stack Using Linked List.cpp delete mode 100644 data_structure/cll/cll.h delete mode 100644 data_structure/cll/main_cll.cpp delete mode 100644 data_structure/cll/makefile delete mode 100644 data_structure/disjoint_set.cpp delete mode 100644 data_structure/doubly_linked_list.cpp delete mode 100644 data_structure/linkedList_implentation_usingArray.cpp delete mode 100644 data_structure/linked_list.cpp delete mode 100644 data_structure/queue/makefile delete mode 100644 data_structure/queue/queue.cpp delete mode 100644 data_structure/queue/queue.h delete mode 100644 data_structure/queue/test_queue.cpp delete mode 100644 data_structure/queue_using_linkedlist.cpp delete mode 100644 data_structure/stk/makefile delete mode 100644 data_structure/stk/stack.cpp delete mode 100644 data_structure/stk/stack.h delete mode 100644 data_structure/stk/test_stack.cpp delete mode 100644 data_structure/trie_tree.cpp create mode 100644 data_structures/CMakeLists.txt create mode 100644 data_structures/avltree.cpp create mode 100644 data_structures/binary_search_tree.cpp create mode 100644 data_structures/binaryheap.cpp rename data_structure/circular_Queue_using_Linked_List.cpp => data_structures/circular_queue_using_linked_list.cpp (70%) create mode 100644 data_structures/cll/CMakeLists.txt rename {data_structure => data_structures}/cll/cll.cpp (68%) create mode 100644 data_structures/cll/cll.h create mode 100644 data_structures/cll/main_cll.cpp create mode 100644 data_structures/disjoint_set.cpp create mode 100644 data_structures/doubly_linked_list.cpp create mode 100644 data_structures/linked_list.cpp create mode 100644 data_structures/linkedlist_implentation_usingarray.cpp create mode 100644 data_structures/list_array.cpp create mode 100644 data_structures/morrisinorder.cpp create mode 100644 data_structures/queue.h rename {data_structure => data_structures}/queue_using_array.cpp (95%) create mode 100644 data_structures/queue_using_array2.cpp rename data_structure/Queue Using Linked List.cpp => data_structures/queue_using_linked_list.cpp (69%) create mode 100644 data_structures/queue_using_linkedlist.cpp create mode 100644 data_structures/stack.h create mode 100644 data_structures/stack_using_array.cpp create mode 100644 data_structures/stack_using_linked_list.cpp rename {data_structure/stk => data_structures}/student.txt (100%) create mode 100644 data_structures/test_queue.cpp create mode 100644 data_structures/test_stack.cpp rename data_structure/stk/main.cpp => data_structures/test_stack_students.cpp (67%) rename data_structure/Tree.cpp => data_structures/tree.cpp (72%) rename {data_structure => data_structures}/trie_modern.cpp (96%) create mode 100644 data_structures/trie_tree.cpp create mode 100644 doc/cppreference-doxygen-web.tag.xml delete mode 100644 dynamic_programming/0-1 Knapsack.cpp create mode 100644 dynamic_programming/0_1_knapsack.cpp delete mode 100644 dynamic_programming/Bellman-Ford.cpp delete mode 100644 dynamic_programming/Coin-Change.cpp delete mode 100644 dynamic_programming/Cut Rod.cpp delete mode 100644 dynamic_programming/Fibonacci_Bottom_Up.cpp delete mode 100644 dynamic_programming/Fibonacci_Top_Down.cpp delete mode 100644 dynamic_programming/Floyd-Warshall.cpp delete mode 100644 dynamic_programming/Longest Common Subsequence.cpp delete mode 100644 dynamic_programming/Longest Increasing Subsequence (nlogn).cpp delete mode 100644 dynamic_programming/Longest Increasing Subsequence.cpp delete mode 100644 dynamic_programming/Matrix-Chain-Multiplication.cpp create mode 100644 dynamic_programming/bellman_ford.cpp rename dynamic_programming/{Catalan-Numbers.cpp => catalan_numbers.cpp} (85%) create mode 100644 dynamic_programming/coin_change.cpp create mode 100644 dynamic_programming/cut_rod.cpp rename dynamic_programming/{Edit Distance.cpp => edit_distance.cpp} (60%) rename dynamic_programming/{Egg-Dropping-Puzzle.cpp => egg_dropping_puzzle.cpp} (63%) create mode 100644 dynamic_programming/fibonacci_bottom_up.cpp create mode 100644 dynamic_programming/fibonacci_top_down.cpp create mode 100644 dynamic_programming/floyd_warshall.cpp create mode 100644 dynamic_programming/longest_common_subsequence.cpp create mode 100644 dynamic_programming/longest_increasing_subsequence.cpp create mode 100644 dynamic_programming/longest_increasing_subsequence_(nlogn).cpp create mode 100644 dynamic_programming/matrix_chain_multiplication.cpp create mode 100644 geometry/CMakeLists.txt delete mode 100644 graph/BFS.cpp delete mode 100644 graph/DFS.cpp delete mode 100644 graph/Kruskal.cpp delete mode 100644 graph/Topological-Sort.cpp create mode 100644 graph/bfs.cpp create mode 100644 graph/cycle_check_directed_graph.cpp create mode 100644 graph/dfs.cpp rename graph/{DFS_with_stack.cc => dfs_with_stack.cpp} (74%) rename graph/{Dijkstra.cpp => dijkstra.cpp} (67%) create mode 100644 graph/kruskal.cpp create mode 100644 graph/topological_sort.cpp delete mode 100644 greedy_algorithms/Knapsack.cpp delete mode 100644 greedy_algorithms/Kruskals Minimum Spanning Tree.cpp delete mode 100644 greedy_algorithms/Prims Minimum Spanning Tree.cpp rename greedy_algorithms/{Dijkstra.cpp => dijkstra.cpp} (53%) create mode 100644 greedy_algorithms/knapsack.cpp create mode 100644 greedy_algorithms/kruskals_minimum_spanning_tree.cpp create mode 100644 greedy_algorithms/prims_minimum_spanning_tree.cpp delete mode 100644 hashing/Chaining.cpp create mode 100644 hashing/chaining.cpp create mode 100644 machine_learning/CMakeLists.txt create mode 100644 machine_learning/adaline_learning.cpp create mode 100644 machine_learning/kohonen_som_topology.cpp create mode 100644 machine_learning/kohonen_som_trace.cpp create mode 100644 math/CMakeLists.txt create mode 100644 math/fibonacci_fast.cpp create mode 100644 math/fibonacci_large.cpp rename math/{greatest_common_divisor_euclidean.cpp => gcd_iterative_euclidean.cpp} (79%) create mode 100644 math/gcd_of_n_numbers.cpp create mode 100644 math/gcd_recursive_euclidean.cpp delete mode 100644 math/greatest_common_divisor.cpp create mode 100644 math/large_factorial.cpp create mode 100644 math/large_number.h rename math/{primes_up_to_10^8.cpp => primes_up_to_billion.cpp} (59%) create mode 100644 math/realtime_stats.cpp create mode 100644 math/string_fibonacci.cpp create mode 100644 numerical_methods/CMakeLists.txt create mode 100644 numerical_methods/bisection_method.cpp create mode 100644 numerical_methods/durand_kerner_roots.cpp create mode 100644 numerical_methods/false_position.cpp create mode 100644 numerical_methods/gaussian_elimination.cpp create mode 100644 numerical_methods/lu_decompose.cpp create mode 100644 numerical_methods/newton_raphson_method.cpp create mode 100644 numerical_methods/ode_forward_euler.cpp create mode 100644 numerical_methods/ode_midpoint_euler.cpp create mode 100644 numerical_methods/ode_semi_implicit_euler.cpp create mode 100644 numerical_methods/ordinary_least_squares_regressor.cpp create mode 100644 numerical_methods/qr_decompose.h create mode 100644 numerical_methods/qr_decomposition.cpp create mode 100644 numerical_methods/qr_eigen_values.cpp create mode 100644 numerical_methods/successive_approximation.cpp delete mode 100644 operations_on_datastructures/Array Left Rotation.cpp delete mode 100644 operations_on_datastructures/Circular Linked List.cpp delete mode 100644 operations_on_datastructures/Circular Queue Using Array.cpp delete mode 100644 operations_on_datastructures/Intersection_of_2_arrays.cpp delete mode 100644 operations_on_datastructures/Reverse a Linked List using Recusion.cpp delete mode 100644 operations_on_datastructures/Union_of_2_arrays.cpp create mode 100644 operations_on_datastructures/array_left_rotation.cpp rename operations_on_datastructures/{Array Right Rotation.cpp => array_right_rotation.cpp} (62%) create mode 100644 operations_on_datastructures/circular_linked_list.cpp create mode 100644 operations_on_datastructures/circular_queue_using_array.cpp create mode 100644 operations_on_datastructures/intersection_of_2_arrays.cpp create mode 100644 operations_on_datastructures/reverse_a_linked_list_using_recusion.cpp delete mode 100644 operations_on_datastructures/selectionSortLinkedList.cpp create mode 100644 operations_on_datastructures/selectionsortlinkedlist.cpp create mode 100644 operations_on_datastructures/union_of_2_arrays.cpp delete mode 100644 others/Buzz_number.cpp create mode 100644 others/CMakeLists.txt delete mode 100644 others/Decimal To Binary.cpp delete mode 100644 others/Decimal To Hexadecimal .cpp delete mode 100644 others/GCD_of_n_numbers.cpp delete mode 100644 others/Palindromeofnumber.cpp delete mode 100644 others/Paranthesis Matching.cpp delete mode 100644 others/Primality Test.cpp delete mode 100644 others/Sparse matrix.cpp delete mode 100644 others/Strassen Matrix Multiplication.cpp delete mode 100644 others/String Fibonacci.cpp delete mode 100644 others/Tower of Hanoi.cpp create mode 100644 others/buzz_number.cpp create mode 100644 others/decimal_to_binary.cpp create mode 100644 others/decimal_to_hexadecimal.cpp rename others/{Decimal to Roman Numeral.cpp => decimal_to_roman_numeral.cpp} (54%) delete mode 100644 others/fibonacci.cpp delete mode 100644 others/measure_time_elapsed.cpp create mode 100644 others/palindrome_of_number.cpp create mode 100644 others/paranthesis_matching.cpp create mode 100644 others/primality_test.cpp delete mode 100644 others/sieve_of_Eratosthenes.cpp delete mode 100644 others/smallest-circle.cpp create mode 100644 others/smallest_circle.cpp create mode 100644 others/sparse_matrix.cpp create mode 100644 others/tower_of_hanoi.cpp create mode 100644 probability/CMakeLists.txt delete mode 100644 range_queries/MO.cpp rename range_queries/{FenwickTree.cpp => fenwicktree.cpp} (70%) create mode 100644 range_queries/mo.cpp delete mode 100644 range_queries/segTree.cpp create mode 100644 range_queries/segtree.cpp create mode 100644 search/CMakeLists.txt delete mode 100644 search/Interpolation Search.cpp delete mode 100644 search/Linear Search.cpp create mode 100644 search/interpolation_search2.cpp create mode 100644 search/linear_search.cpp delete mode 100644 search/searching.cpp create mode 100644 search/text_search.cpp delete mode 100644 sorting/BeadSort.cpp delete mode 100644 sorting/BitonicSort.cpp delete mode 100644 sorting/Bubble Sort.cpp create mode 100644 sorting/CMakeLists.txt delete mode 100644 sorting/CocktailSelectionSort.cpp delete mode 100644 sorting/Counting_Sort.cpp delete mode 100644 sorting/Insertion Sort.cpp delete mode 100644 sorting/Merge Sort.cpp delete mode 100644 sorting/NumericStringSort.cpp delete mode 100644 sorting/OddEven Sort.cpp delete mode 100644 sorting/Radix Sort.cpp delete mode 100644 sorting/Selection Sort.cpp delete mode 100644 sorting/Shell Sort.cpp delete mode 100644 sorting/Slow Sort.cpp create mode 100644 sorting/bead_sort.cpp create mode 100644 sorting/bitonic_sort.cpp create mode 100644 sorting/bubble_sort.cpp delete mode 100644 sorting/bucketSort.cpp create mode 100644 sorting/bucket_sort.cpp create mode 100644 sorting/cocktail_selection_sort.cpp create mode 100644 sorting/comb_sort.cpp delete mode 100644 sorting/combsort.cpp create mode 100644 sorting/counting_sort.cpp rename sorting/{CountingSortString.cpp => counting_sort_string.cpp} (50%) delete mode 100644 sorting/doxy.txt create mode 100644 sorting/insertion_sort.cpp delete mode 100644 sorting/makefile create mode 100644 sorting/merge_sort.cpp create mode 100644 sorting/numeric_string_sort.cpp create mode 100644 sorting/odd_even_sort.cpp create mode 100644 sorting/radix_sort.cpp create mode 100644 sorting/selection_sort.cpp create mode 100644 sorting/shell_sort.cpp create mode 100644 sorting/shell_sort2.cpp create mode 100644 sorting/slow_sort.cpp rename sorting/{Tim Sort.cpp => tim_sort.cpp} (55%) create mode 100644 strings/CMakeLists.txt diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index efaaf3765..f81356399 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -3,19 +3,19 @@ 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 +- [ ] 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/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. Notes: \ No newline at end of file diff --git a/.github/workflows/awesome_forkflow.yml b/.github/workflows/awesome_forkflow.yml new file mode 100644 index 000000000..93b630d05 --- /dev/null +++ b/.github/workflows/awesome_forkflow.yml @@ -0,0 +1,211 @@ +name: Awesome CI Workflow + +on: [push] +# push: +# branches: [ master ] +# pull_request: +# branches: [ master ] + +jobs: + code_format: + name: Code Formatter + 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: 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 + run: | + IFS=$'\n' + for fname in `find . -type f -name '*.cpp' -o -name '*.cc' -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}" + 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}" + git "mv" "${fname}" ${new_fname} + fi + 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, " + line3: "AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: false," + line4: "ColumnLimit: 80, AccessModifierOffset: -3 }" + - name: Git Push + run: git push --force origin HEAD:$GITHUB_REF || true + + 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: pull latest commit + run: git pull + - 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 "# List of all files\n" + "\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@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 # v2 is broken for git diff + - uses: actions/setup-python@master + - 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: git diff --diff-filter=dr --name-only origin/master > git_diff.txt + - run: echo "Files changed-- `cat 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,-build/include", 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, cpplint_modified_files] + needs: [update_directory_md] + strategy: + matrix: + os: [ubuntu-latest, windows-latest, macOS-latest] + steps: + - uses: actions/checkout@master + with: + submodules: true + - run: git pull + - run: cmake -B ./build -S . + - run: cmake --build build diff --git a/.github/workflows/cpplint.yml b/.github/workflows/cpplint.yml deleted file mode 100644 index a6999e1f2..000000000 --- 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 07a32ece9..000000000 --- a/.github/workflows/cpplint_modified_files.yml +++ /dev/null @@ -1,64 +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:") - subprocess.run(["cpplint", "--filter=-legal/copyright"] + cpp_files, 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)] - subprocess.run(["g++"] + cpp_files, 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/gh-pages.yml b/.github/workflows/gh-pages.yml new file mode 100644 index 000000000..881ea1c33 --- /dev/null +++ b/.github/workflows/gh-pages.yml @@ -0,0 +1,36 @@ +name: Doxygen CI + +on: + push: + branches: [master] + +jobs: + build: + runs-on: macos-latest + steps: + - uses: actions/checkout@master + with: + submodules: true + - name: Install requirements + run: | + brew install graphviz ninja doxygen + - 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: | + 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 + 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 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 add9efd5d..000000000 --- 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 diff --git a/.github/workflows/update_directory_md.yml b/.github/workflows/update_directory_md.yml deleted file mode 100644 index 1d63374b0..000000000 --- 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 diff --git a/.gitignore b/.gitignore index ed3934e45..5275088d0 100644 --- a/.gitignore +++ b/.gitignore @@ -33,3 +33,5 @@ a.out *.out *.app + +build/ diff --git a/.gitpod.dockerfile b/.gitpod.dockerfile new file mode 100644 index 000000000..6d6a4e895 --- /dev/null +++ b/.gitpod.dockerfile @@ -0,0 +1,9 @@ +FROM gitpod/workspace-full + +RUN sudo apt-get update \ + && sudo apt-get install -y \ + doxygen \ + graphviz \ + ninja-build \ + && pip install cpplint \ + && sudo rm -rf /var/lib/apt/lists/* diff --git a/.gitpod.yml b/.gitpod.yml new file mode 100644 index 000000000..40750258c --- /dev/null +++ b/.gitpod.yml @@ -0,0 +1,17 @@ +image: + file: .gitpod.dockerfile + +github: + prebuilds: + addBadge: true + addComment: false + 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== diff --git a/.vscode/settings.json b/.vscode/settings.json index 0ab2708d0..6d75a1390 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,71 +1,6 @@ { - "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, 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: -3 }", "editor.formatOnSave": true, "editor.formatOnType": true, "editor.formatOnPaste": true -} +} \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 000000000..957be35f5 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,81 @@ +cmake_minimum_required(VERSION 3.9) +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") + +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) +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_HTML_TIMESTAMP YES) + set(DOXYGEN_EXTRACT_STATIC YES) + set(DOXYGEN_INLINE_SOURCES YES) + set(DOXYGEN_CREATE_SUBDIRS YES) + set(DOXYGEN_EXTRACT_PRIVATE YES) + set(DOXYGEN_GENERATE_TREEVIEW YES) + set(DOXYGEN_STRIP_CODE_COMMENTS NO) + set(DOXYGEN_EXT_LINKS_IN_WINDOW YES) + set(DOXYGEN_BUILTIN_STL_SUPPORT YES) + set(DOXYGEN_CLANG_ASSISTED_PARSING YES) + set(DOXYGEN_FILE_PATTERNS *.cpp *.h *.hpp *.md) + 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) + 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) + 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() + +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) +add_subdirectory(strings) +add_subdirectory(sorting) +add_subdirectory(geometry) +add_subdirectory(probability) +add_subdirectory(data_structures) +add_subdirectory(machine_learning) +add_subdirectory(numerical_methods) + +set(CPACK_PROJECT_NAME ${PROJECT_NAME}) +set(CPACK_PROJECT_VERSION ${PROJECT_VERSION}) +include(CPack) diff --git a/CONTRIBUTION.md b/CONTRIBUTING.md similarity index 100% rename from CONTRIBUTION.md rename to CONTRIBUTING.md diff --git a/DIRECTORY.md b/DIRECTORY.md index 1575561b8..071ee8b95 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) @@ -9,67 +10,54 @@ * [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](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/Newton_Raphson.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 - * [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) +## 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%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 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) - * [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 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) - * 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) + * [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](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) + * [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) ## 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) @@ -77,34 +65,40 @@ * [Line Segment Intersection](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/geometry/line_segment_intersection.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 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) + * [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) * [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) +## 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 * [Binary Exponent](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/binary_exponent.cpp) * [Check Prime](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/check_prime.cpp) @@ -114,52 +108,69 @@ * [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) + * [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) * [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) * [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) + * [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) + +## 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) + * [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) + * [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 - * [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) - * [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) + * [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](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/fibonacci.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) + * [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%20Test.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) + * [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) + * [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) + * [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 @@ -170,45 +181,46 @@ ## 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) * [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) + * [Text Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/text_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) - * [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) + * [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) + * [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) + * [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%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) - * [Slow Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Slow%20Sort.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_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) diff --git a/README.md b/README.md index a3077cdc5..8734158b7 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,18 @@ -# The Algorithms - C++ -[![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)  +# 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/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) -### All algorithms implemented in C++ (for education) +[Online Documentation](https://TheAlgorithms.github.io/C-Plus-Plus). + +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/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTION.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/backtracking/graph_coloring.cpp b/backtracking/graph_coloring.cpp index cadc6d5ec..19a983019 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,17 +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]); + 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) | / | @@ -69,12 +61,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 fbb8a6f96..c97523be7 100644 --- a/backtracking/knight_tour.cpp +++ b/backtracking/knight_tour.cpp @@ -1,68 +1,60 @@ #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]) -{ - return (x=0 && y=0 && sol[x][y]==-1); +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]) -{ - int k,xnext,ynext; +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) + if (mov == n * n) return true; - for(k=0;k<8;k++) - { - xnext=x+xmov[k]; - ynext=y+ymov[k]; + for (k = 0; k < 8; 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(); +int main() { + // initialize(); int sol[n][n]; - int i,j; - for(i=0;i scores, } int main() { - vector scores = { 90, 23, 6, 33, 21, 65, 123, 34423 }; + 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 472aaa2fe..8aab5df7b 100644 --- a/backtracking/n_queens.cpp +++ b/backtracking/n_queens.cpp @@ -2,19 +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 j = 0; j < N; j++) - cout << "" << board[i][j]; + 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 */ @@ -35,23 +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"< #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--) +#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] << " "; + 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; @@ -21,7 +19,7 @@ void PrintSol(int Board[n][n]) { 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; } @@ -43,7 +41,7 @@ void NQueenSol(int Board[n][n], int col) { PrintSol(Board); return; } - inc_loop(i, 0, n-1) { + inc_loop(i, 0, n - 1) { if (CanIMove(Board, i, col)) { Board[i][col] = 1; NQueenSol(Board, col + 1); @@ -54,8 +52,8 @@ void NQueenSol(int Board[n][n], int col) { int main() { int Board[n][n] = {0}; - if (n%2 == 0) { - inc_loop(i, 0, n/2-1) { + if (n % 2 == 0) { + inc_loop(i, 0, n / 2 - 1) { if (CanIMove(Board, i, 0)) { Board[i][0] = 1; NQueenSol(Board, 1); @@ -63,7 +61,7 @@ int main() { } } } else { - inc_loop(i, 0, n/2) { + inc_loop(i, 0, n / 2) { if (CanIMove(Board, i, 0)) { Board[i][0] = 1; NQueenSol(Board, 1); diff --git a/backtracking/rat_maze.cpp b/backtracking/rat_maze.cpp index 307b5c7b0..fb3be4451 100644 --- a/backtracking/rat_maze.cpp +++ b/backtracking/rat_maze.cpp @@ -1,73 +1,62 @@ /* - 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]) -{ - 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; +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 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 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]; + 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 6a01fd395..b712b6ec7 100644 --- a/backtracking/sudoku_solve.cpp +++ b/backtracking/sudoku_solve.cpp @@ -1,15 +1,12 @@ #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 - for (int x = 0; x < n; x++) - { - if (mat[x][j] == no || mat[i][x] == 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) { 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,83 +25,63 @@ 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) -{ - ///Base Case - if (i == 9) - { - ///Solve kr chuke hain for 9 rows already +bool solveSudoku(int mat[][9], int i, int j) { + /// Base Case + 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) - { + /// Crossed the last Cell in the row + if (j == 9) { return solveSudoku(mat, i + 1, 0); } - ///Blue Cell - Skip - if (mat[i][j] != 0) - { + /// Blue Cell - Skip + 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)) - { - ///Place the no - assuming solution aa jayega + /// 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 mat[i][j] = no; bool aageKiSolveHui = solveSudoku(mat, i, j + 1); - if (aageKiSolveHui) - { + 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 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}}; printMat(mat); cout << "Solution " << endl; diff --git a/computer_oriented_statistical_methods/Bisection_method.CPP b/computer_oriented_statistical_methods/Bisection_method.CPP deleted file mode 100644 index 717987321..000000000 --- a/computer_oriented_statistical_methods/Bisection_method.CPP +++ /dev/null @@ -1,53 +0,0 @@ -#include -#include -#include - -float eq(float i) -{ - return (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; - } - } - -START: - - 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 << "]"; - - if (z < 0) - { - a = x; - } - else - { - b = x; - } - - if (z > 0 && z < 0.0009) // stoping criteria - { - goto END; - } - } - -END: - cout << "\n\nRoot: " << x; - getch(); -} diff --git a/computer_oriented_statistical_methods/Gaussian_elimination.cpp b/computer_oriented_statistical_methods/Gaussian_elimination.cpp deleted file mode 100644 index 58e634505..000000000 --- a/computer_oriented_statistical_methods/Gaussian_elimination.cpp +++ /dev/null @@ -1,63 +0,0 @@ -#include -using namespace std; - -int main() -{ - int mat_size, i, j, step; - - cout << "Matrix size: "; - 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. - } - } - - 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++) - mat[i + 1][j] = mat[i + 1][j] - (a * mat[step][j]); - } - } - - cout << endl - << "Matrix using Gaussian Elimination method: " << 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] << " "; - } - cout << endl; - } - cout << endl - << "Value of the Gaussian Elimination method: " << endl; - for (i = mat_size - 1; i >= 0; i--) - { - double sum = 0; - for (j = mat_size - 1; j > i; j--) - { - x[i][j] = x[j][j] * x[i][j]; - sum = x[i][j] + sum; - } - if (x[i][i] == 0) - x[i][i] = 0; - else - x[i][i] = (x[i][mat_size] - sum) / (x[i][i]); - - cout << "x" << i << "= " << x[i][i] << endl; - } - 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 183a78daf..000000000 --- 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 deleted file mode 100644 index b897e9184..000000000 --- a/computer_oriented_statistical_methods/Secant_method.CPP +++ /dev/null @@ -1,49 +0,0 @@ -#include -#include -#include - -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; - } - } - -START: - - 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; - - z = eq(c); - if (z > 0 && z < 0.09) // stoping criteria - { - goto END; - } - } - -END: - cout << "\n\nRoot: " << c; - getch(); -} diff --git a/computer_oriented_statistical_methods/false-position.cpp b/computer_oriented_statistical_methods/false-position.cpp deleted file mode 100644 index 5e15e92cc..000000000 --- a/computer_oriented_statistical_methods/false-position.cpp +++ /dev/null @@ -1,35 +0,0 @@ -#include -#include -#include -float eq(float i) { - return (pow(i, 3) - (4 * i) - 9); // origial equation -} -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; - goto START; - } - } - 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); - c = ((a * n) - (b * m)) / (n - m); - a = c; - z = eq(c); - if (z > 0 && z < 0.09) { // stoping criteria - goto END; - } - } - END: - std::cout << "\n\nRoot: " << c; - system("pause"); -} diff --git a/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp b/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp deleted file mode 100644 index f50ccf1b1..000000000 --- a/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp +++ /dev/null @@ -1,349 +0,0 @@ -/** - * 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 - -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; -} - -template -std::ostream &operator<<(std::ostream &out, std::vector const &v) { - 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]; - - return out; -} - -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; -} - -/** - * matrix multiplication - **/ -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(); - - 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]; - } - result[row] = v; - } - - return result; -} - -template -std::vector operator*(std::vector> const &A, - 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()) { - 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]; - } - - return result; -} - -template -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++) { - result[row] += A[row] * static_cast(scalar); - } - - return result; -} - -template -std::vector operator*(std::vector const &A, float const scalar) { - // 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++) - result[row] = A[row] * static_cast(scalar); - - return result; -} - -template -std::vector operator/(std::vector const &A, float const scalar) { - return (1.f / scalar) * A; -} - -template -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) { - std::cerr << "Vector dimensions shouldbe identical!" << std::endl; - return A; - } - - for (size_t row = 0; row < N; row++) - result[row] = A[row] - B[row]; - - return result; -} - -template -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) { - std::cerr << "Vector dimensions shouldbe identical!" << std::endl; - return A; - } - - for (size_t row = 0; row < N; row++) - result[row] = A[row] + B[row]; - - return result; -} - -/** - * Get matrix inverse using Row-trasnformations - **/ -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]; - } - - 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; -} - -/** - * matrix transpose - **/ -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; -} - -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; -} - -/** - * Given data and OLS model coeffficients, predict - * regression estimates - **/ -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; -} - -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; -} diff --git a/computer_oriented_statistical_methods/successive_approximation.CPP b/computer_oriented_statistical_methods/successive_approximation.CPP deleted file mode 100644 index b42ab8f8c..000000000 --- a/computer_oriented_statistical_methods/successive_approximation.CPP +++ /dev/null @@ -1,37 +0,0 @@ -#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; - - 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; - - for (i = 0; i <= n; i++) - { - x2 = eqd(x1); - cout << "\nenter the x2->" << x2; - x1 = x2; - } - getch(); -} \ No newline at end of file diff --git a/data_structure/AVLtree.cpp b/data_structure/AVLtree.cpp deleted file mode 100644 index db6b9e0d4..000000000 --- a/data_structure/AVLtree.cpp +++ /dev/null @@ -1,176 +0,0 @@ -#include -#include - -using namespace std; - -typedef struct node -{ - int data; - int height; - struct node *left; - struct node *right; -} node; - -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; -} - -// Returns height of tree - -int height(node *root) -{ - 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); -} - -// 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; -} - -// 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; -} - -// Returns node with minimum value in the tree - -node *minValue(node *root) -{ - 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; -} - -// 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; -} - -// 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); - } -} - -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; -} diff --git a/data_structure/Binary Search Tree.cpp b/data_structure/Binary Search Tree.cpp deleted file mode 100644 index 32a65517c..000000000 --- a/data_structure/Binary Search Tree.cpp +++ /dev/null @@ -1,218 +0,0 @@ -#include -using namespace std; - -struct node -{ - int val; - node *left; - node *right; -}; - -struct queue -{ - node *t[100]; - int front; - int rear; -}; - -queue q; - -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) - { - 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; -} - -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); - } -} - -void BFT(node *n) -{ - 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); - } -} - -void In(node *n) -{ - 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 << " "; - } -} - -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"; - - 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 deleted file mode 100644 index 31129a823..000000000 --- a/data_structure/Binaryheap.cpp +++ /dev/null @@ -1,158 +0,0 @@ -// A C++ program to demonstrate common Binary Heap Operations -#include -#include -using namespace std; - -// Prototype of a utility function to swap two integers -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: - // Constructor - MinHeap(int capacity); - - // 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 - int left(int i) { return (2 * i + 1); } - - // 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 - int extractMin(); - - // 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 - int getMin() { return harr[0]; } - - // Deletes a key stored at index i - void deleteKey(int i); - - // Inserts a new key 'k' - void insertKey(int k); -}; - -// Constructor: Builds a heap from a given array a[] of given size -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) - { - cout << "\nOverflow: Could not insertKey\n"; - return; - } - - // First insert the new key at the end - heap_size++; - int i = heap_size - 1; - harr[i] = k; - - // Fix the min heap property if it is violated - while (i != 0 && harr[parent(i)] > harr[i]) - { - 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]. -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)]); - i = parent(i); - } -} - -// Method to remove minimum element (or root) from min heap -int MinHeap::extractMin() -{ - if (heap_size <= 0) - return INT_MAX; - if (heap_size == 1) - { - heap_size--; - return harr[0]; - } - - // Store the minimum value, and remove it from heap - int root = harr[0]; - harr[0] = harr[heap_size - 1]; - heap_size--; - MinHeapify(0); - - return root; -} - -// 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 -void MinHeap::MinHeapify(int i) -{ - int l = left(i); - int r = right(i); - int smallest = i; - if (l < heap_size && harr[l] < harr[i]) - smallest = l; - if (r < heap_size && harr[r] < harr[smallest]) - smallest = r; - if (smallest != i) - { - 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); - h.insertKey(3); - h.insertKey(2); - h.deleteKey(1); - h.insertKey(15); - h.insertKey(5); - h.insertKey(4); - h.insertKey(45); - cout << h.extractMin() << " "; - cout << h.getMin() << " "; - h.decreaseKey(2, 1); - cout << h.getMin(); - return 0; -} diff --git a/data_structure/List Array.cpp b/data_structure/List Array.cpp deleted file mode 100644 index de984876b..000000000 --- a/data_structure/List Array.cpp +++ /dev/null @@ -1,188 +0,0 @@ -#include -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 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; -} diff --git a/data_structure/MorrisInorder.cpp b/data_structure/MorrisInorder.cpp deleted file mode 100644 index d3a2e9fd7..000000000 --- a/data_structure/MorrisInorder.cpp +++ /dev/null @@ -1,108 +0,0 @@ -#include -#include - -/************************** - @author shrutisheoran -**************************/ - -using namespace std; - -struct Btree -{ - 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; - } - } - } -} - -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; - } - } - } -} - -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; -} diff --git a/data_structure/Queue Using Array.cpp b/data_structure/Queue Using Array.cpp deleted file mode 100644 index 3b79d06fc..000000000 --- a/data_structure/Queue Using Array.cpp +++ /dev/null @@ -1,75 +0,0 @@ -#include -using namespace std; - -int queue[10]; -int front = 0; -int rear = 0; - -void Enque(int x) -{ - if (rear == 10) - { - cout << "\nOverflow"; - } - else - { - queue[rear++] = x; - } -} - -void Deque() -{ - 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; - } -} - -void show() -{ - 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); - - return 0; -} diff --git a/data_structure/Stack Using Array.cpp b/data_structure/Stack Using Array.cpp deleted file mode 100644 index af1d57c46..000000000 --- a/data_structure/Stack Using Array.cpp +++ /dev/null @@ -1,79 +0,0 @@ -#include -using namespace std; - -int *stack; -int top = 0, size; - -void push(int x) -{ - if (top == size) - { - cout << "\nOverflow"; - } - else - { - stack[top++] = x; - } -} - -void pop() -{ - if (top == 0) - { - cout << "\nUnderflow"; - } - else - { - cout << "\n" - << stack[--top] << " deleted"; - } -} - -void show() -{ - for (int i = 0; i < top; i++) - { - cout << stack[i] << "\n"; - } -} - -void topmost() -{ - cout << "\nTopmost element: " << stack[top - 1]; -} -int main() -{ - cout << "\nEnter Size of stack : "; - cin >> size; - stack = new int[size]; - int ch, x; - do - { - cout << "\n1. Push"; - cout << "\n2. Pop"; - cout << "\n3. Print"; - cout << "\n4. Print topmost element:"; - cout << "\nEnter Your Choice : "; - cin >> ch; - if (ch == 1) - { - cout << "\nInsert : "; - cin >> x; - push(x); - } - else if (ch == 2) - { - pop(); - } - else if (ch == 3) - { - show(); - } - else if (ch == 4) - { - topmost(); - } - } while (ch != 0); - - return 0; -} diff --git a/data_structure/Stack Using Linked List.cpp b/data_structure/Stack Using Linked List.cpp deleted file mode 100644 index 6925cf10c..000000000 --- a/data_structure/Stack Using Linked List.cpp +++ /dev/null @@ -1,73 +0,0 @@ -#include -using namespace std; - -struct node -{ - int val; - node *next; -}; - -node *top; - -void push(int x) -{ - 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; - } -} - -void show() -{ - 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); - - return 0; -} diff --git a/data_structure/cll/cll.h b/data_structure/cll/cll.h deleted file mode 100644 index ae71dcd01..000000000 --- a/data_structure/cll/cll.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Simple data structure CLL (Cicular Linear Linked List) - * */ -#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; -}; - -class cll -{ - 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 */ - - /****************************************************** - * 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 */ -}; -#endif diff --git a/data_structure/cll/main_cll.cpp b/data_structure/cll/main_cll.cpp deleted file mode 100644 index 15388b822..000000000 --- a/data_structure/cll/main_cll.cpp +++ /dev/null @@ -1,44 +0,0 @@ -#include "cll.h" -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: "< -#include - -using std::cout; -using std::endl; -using std::vector; - -vector 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; - } -} - -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); -} - -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; - } - } - // 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; -} diff --git a/data_structure/doubly_linked_list.cpp b/data_structure/doubly_linked_list.cpp deleted file mode 100644 index 4fc38abfc..000000000 --- a/data_structure/doubly_linked_list.cpp +++ /dev/null @@ -1,138 +0,0 @@ -#include -#include -#include - -struct node { - int val; - node *prev; - node *next; -}*start; - -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(); -}; - -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; - } -} - -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; - } - 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; - } - 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::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; -} diff --git a/data_structure/linkedList_implentation_usingArray.cpp b/data_structure/linkedList_implentation_usingArray.cpp deleted file mode 100644 index 6f8205f27..000000000 --- a/data_structure/linkedList_implentation_usingArray.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/* The difference between the pointer implementation of linked list and array implementation of linked list: - 1. The NULL is represented by -1; - 2. Limited size. (in the following case it is 100 nodes at max). But we can reuse the nodes that are to be deleted by again linking it bacj to the list. -*/ - -#include -using namespace std; -struct Node -{ - int data; - int next; -}; -Node AvailArray[100]; //array that will act as nodes of a linked list. -int head = -1; -int avail = 0; -void initialise_list() -{ - for (int i = 0; i <= 98; i++) - { - AvailArray[i].next = i + 1; - } - AvailArray[99].next = -1; //indicating the end of the linked list. -} - -int getnode() //This will return the index of the first free node present in the avail list -{ - int NodeIndexToBeReturned = avail; - avail = AvailArray[avail].next; - return NodeIndexToBeReturned; -} - -void freeNode(int nodeToBeDeleted) //This function when called will delete the node with the index presented as an argument, and will put back that node into the array. -{ - AvailArray[nodeToBeDeleted].next = avail; - avail = nodeToBeDeleted; -} - -void insertAtTheBeginning(int data) //The function will insert the given data into the front of the linked list. -{ - int newNode = getnode(); - AvailArray[newNode].data = data; - AvailArray[newNode].next = head; - head = newNode; -} - -void insertAtTheEnd(int data) -{ - int newNode = getnode(); - int temp = head; - while (AvailArray[temp].next != -1) - { - temp = AvailArray[temp].next; - } - //temp is now pointing to the end node. - AvailArray[newNode].data = data; - AvailArray[newNode].next = -1; - AvailArray[temp].next = newNode; -} - -void display() -{ - int temp = head; - while (temp != -1) - { - cout << AvailArray[temp].data << "->"; - temp = AvailArray[temp].next; - } - cout << "-1" << endl; - ; -} - -int main() -{ - initialise_list(); - int x, y, z; - for (;;) - { - cout << "1. Insert At The Beginning" << endl; - cout << "2. Insert At The End" << endl; - cout << "3. Display" << endl; - cout << "4.Exit" << endl; - cout << "Enter Your choice" << endl; - cin >> z; - switch (z) - { - case 1: - cout << "Enter the number you want to enter" << endl; - cin >> x; - insertAtTheBeginning(x); - break; - case 2: - cout << "Enter the number you want to enter" << endl; - cin >> y; - insertAtTheEnd(y); - break; - case 3: - cout << "The linked list contains the following element in order" << endl; - display(); - break; - case 4: - exit(0); - default: - cout << "The entered choice is not correct" << endl; - } - } -} diff --git a/data_structure/linked_list.cpp b/data_structure/linked_list.cpp deleted file mode 100644 index 64cad14f9..000000000 --- a/data_structure/linked_list.cpp +++ /dev/null @@ -1,135 +0,0 @@ -#include - -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 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; - - 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; - } - - 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 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"; - } -} - -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; -} diff --git a/data_structure/queue/makefile b/data_structure/queue/makefile deleted file mode 100644 index 420909804..000000000 --- a/data_structure/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_structure/queue/queue.cpp b/data_structure/queue/queue.cpp deleted file mode 100644 index 728adfc18..000000000 --- a/data_structure/queue/queue.cpp +++ /dev/null @@ -1,90 +0,0 @@ -#include -#include -#include "queue.h" - -using namespace std; - -/* 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; - cout << "Front --> "; - while(current != NULL) { - cout<data<< " "; - current = current -> next; - } - cout < -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 { - cout << "Queue is empty !" << endl; - } -} - diff --git a/data_structure/queue/queue.h b/data_structure/queue/queue.h deleted file mode 100644 index 715def1ef..000000000 --- a/data_structure/queue/queue.h +++ /dev/null @@ -1,34 +0,0 @@ -/* This class specifies the basic operation on a queue as a linked list */ -#ifndef QUEUE_H -#define 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 - diff --git a/data_structure/queue/test_queue.cpp b/data_structure/queue/test_queue.cpp deleted file mode 100644 index caf80318c..000000000 --- a/data_structure/queue/test_queue.cpp +++ /dev/null @@ -1,38 +0,0 @@ -#include -#include -#include "queue.h" -#include "queue.cpp" - -using namespace std; - -int main() -{ - queue q; - cout << "---------------------- Test construct ----------------------" << endl; - q.display(); - cout << "---------------------- Test isEmptyQueue ----------------------" << endl; - if(q.isEmptyQueue()) - cout << "PASS" < - - -struct linkedlist{ - int data; - linkedlist *next; - -}; -class stack_linkedList{ - public: - linkedlist *front; - linkedlist *rear; - - 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; - - if(front==NULL) - front=rear=temp; - else{ - rear->next=temp; - rear=temp; - } -} -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); - } - return ele; -} -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; - } - } -} - -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<<"Enter data "; - std::cin>>data; - ob.enqueue(data); - } - else if(op==2) - data=ob.dequeue(); - else if(op==3) - ob.display(); - else if(op==4) - exit(0); - else - std::cout<<"\nWrong choice "; - - } - return 0; -} diff --git a/data_structure/stk/makefile b/data_structure/stk/makefile deleted file mode 100644 index e965d2044..000000000 --- a/data_structure/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_structure/stk/stack.cpp b/data_structure/stk/stack.cpp deleted file mode 100644 index 1e87d7c14..000000000 --- a/data_structure/stk/stack.cpp +++ /dev/null @@ -1,114 +0,0 @@ -#include -#include -#include "stack.h" - -using namespace std; - -/* Default constructor*/ -template -stack::stack() -{ - stackTop = NULL; - size = 0; -} - -/* Destructor */ -template -stack::~stack() -{ -} - -/* Display for testing */ -template -void stack::display() -{ - node *current = stackTop; - cout << "Top --> "; - while(current != NULL) { - cout<data<< " "; - current = current -> next; - } - cout < -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 { - cout << "Stack is empty !" << endl; - } -} - -/* Operator "=" */ -template -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 { - 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; -} diff --git a/data_structure/stk/stack.h b/data_structure/stk/stack.h deleted file mode 100644 index a93669482..000000000 --- a/data_structure/stk/stack.h +++ /dev/null @@ -1,35 +0,0 @@ -/* This class specifies the basic operation on a stack as a linked list */ -#ifndef STACK_H -#define 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=(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 deleted file mode 100644 index 4703fc906..000000000 --- a/data_structure/stk/test_stack.cpp +++ /dev/null @@ -1,54 +0,0 @@ -#include -#include "stack.h" -#include "stack.cpp" - -using namespace std; - -int main() -{ - stack stk; - cout << "---------------------- Test construct ----------------------" << endl; - stk.display(); - cout << "---------------------- Test isEmptyStack ----------------------" << endl; - if(stk.isEmptyStack()) - cout << "PASS" < stk1; - cout << "stk current: "<< endl; - stk.display(); - cout << endl << "Assign stk1 = stk "<< endl; - stk1 = stk; - stk1.display(); - cout << endl<< "After pushing 8 9 10 into stk1:" < -#include - -#include -#include - -// structure definition -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; - return nn; -} - -// insert string into the trie -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]; - } - } - 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) - return false; - return true; - } - int j = str[index] - 'a'; - if (!root -> arr[j]) - return false; - 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 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++) - return false; - return true; - } - int j = str[index] - 'a'; - if (!root -> arr[j]) - return false; - bool - var = deleteString(root, str, index + 1); - if (var) { - root -> arr[j] = NULL; - if (root -> isEndofWord) { - return false; - } else { - int i; - for (i = 0; i < 26; i++) - if (root -> arr[i]) - return false; - return true; - } - } -} - -int main() { - trie * root = createNode(); - insert(root, "hello"); - insert(root, "world"); - int a = search(root, "hello", 0); - int b = search(root, "word", 0); - printf("%d %d ", a, b); - return 0; -} diff --git a/data_structures/CMakeLists.txt b/data_structures/CMakeLists.txt new file mode 100644 index 000000000..6c0555148 --- /dev/null +++ b/data_structures/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) + if(OpenMP_CXX_FOUND) + target_link_libraries(${testname} OpenMP::OpenMP_CXX) + endif() + install(TARGETS ${testname} DESTINATION "bin/data_structures") + +endforeach( testsourcefile ${APP_SOURCES} ) + +add_subdirectory(cll) diff --git a/data_structures/avltree.cpp b/data_structures/avltree.cpp new file mode 100644 index 000000000..836f0f667 --- /dev/null +++ b/data_structures/avltree.cpp @@ -0,0 +1,148 @@ +/** + * \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 + +typedef struct node { + int data; + int height; + struct node *left; + struct node *right; +} node; + +/** Create and return 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; +} + +/** Returns height of tree */ +int height(node *root) { + if (root == NULL) + return 0; + return 1 + std::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); } + +/** 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; +} + +/** 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; +} + +/** Returns node with minimum value in the tree */ +node *minValue(node *root) { + 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; +} + +/** 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; +} + +/** LevelOrder (Breadth First Search) */ +void levelOrder(node *root) { + std::queue q; + q.push(root); + while (!q.empty()) { + root = q.front(); + std::cout << root->data << " "; + q.pop(); + if (root->left) + q.push(root->left); + if (root->right) + q.push(root->right); + } +} + +/** Main function */ +int main() { + // Testing AVL Tree + node *root = NULL; + int i; + for (i = 1; i <= 7; i++) root = insert(root, i); + std::cout << "LevelOrder: "; + levelOrder(root); + root = deleteNode(root, 1); // Deleting key with value 1 + std::cout << "\nLevelOrder: "; + levelOrder(root); + root = deleteNode(root, 4); // Deletin key with value 4 + std::cout << "\nLevelOrder: "; + levelOrder(root); + return 0; +} diff --git a/data_structures/binary_search_tree.cpp b/data_structures/binary_search_tree.cpp new file mode 100644 index 000000000..947bb53d8 --- /dev/null +++ b/data_structures/binary_search_tree.cpp @@ -0,0 +1,174 @@ +/** + * \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 + +struct node { + int val; + node *left; + node *right; +}; + +struct queue { + node *t[100]; + int front; + int rear; +}; + +queue q; + +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) { + 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; +} + +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); + } +} + +void BFT(node *n) { + if (n != NULL) { + std::cout << n->val << " "; + enqueue(n->left); + enqueue(n->right); + BFT(dequeue()); + } +} + +void Pre(node *n) { + if (n != NULL) { + std::cout << n->val << " "; + Pre(n->left); + Pre(n->right); + } +} + +void In(node *n) { + if (n != NULL) { + In(n->left); + std::cout << n->val << " "; + In(n->right); + } +} + +void Post(node *n) { + if (n != NULL) { + Post(n->left); + Post(n->right); + std::cout << n->val << " "; + } +} + +int main() { + q.front = 0; + q.rear = 0; + int value; + int ch; + node *root = new node; + std::cout << "\nEnter the value of root node :"; + std::cin >> value; + root->val = value; + root->left = NULL; + root->right = NULL; + do { + std::cout << "\n1. Insert" + << "\n2. Delete" + << "\n3. Breadth First" + << "\n4. Preorder Depth First" + << "\n5. Inorder Depth First" + << "\n6. Postorder Depth First"; + + std::cout << "\nEnter Your Choice : "; + 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; + } + } while (ch != 0); + + return 0; +} diff --git a/data_structures/binaryheap.cpp b/data_structures/binaryheap.cpp new file mode 100644 index 000000000..72e56e91a --- /dev/null +++ b/data_structures/binaryheap.cpp @@ -0,0 +1,144 @@ +/** + * \file + * \brief A C++ program to demonstrate common Binary Heap Operations + */ +#include +#include +#include + +/** 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: + /** Constructor + * \param[in] capacity initial heap capacity + */ + MinHeap(int capacity); + + /** 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 */ + int left(int i) { return (2 * i + 1); } + + /** 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 */ + int extractMin(); + + /** 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 */ + int getMin() { return harr[0]; } + + /** Deletes a key stored at index i */ + void deleteKey(int i); + + /** Inserts a new key 'k' */ + void insertKey(int k); +}; + +/** Constructor: Builds a heap from a given array a[] of given size */ +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) { + std::cout << "\nOverflow: Could not insertKey\n"; + return; + } + + // First insert the new key at the end + heap_size++; + int i = heap_size - 1; + harr[i] = k; + + // Fix the min heap property if it is violated + while (i != 0 && harr[parent(i)] > harr[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]. + */ +void MinHeap::decreaseKey(int i, int new_val) { + harr[i] = new_val; + while (i != 0 && harr[parent(i)] > harr[i]) { + std::swap(harr[i], harr[parent(i)]); + i = parent(i); + } +} + +// Method to remove minimum element (or root) from min heap +int MinHeap::extractMin() { + if (heap_size <= 0) + return INT_MAX; + if (heap_size == 1) { + heap_size--; + return harr[0]; + } + + // Store the minimum value, and remove it from heap + int root = harr[0]; + harr[0] = harr[heap_size - 1]; + heap_size--; + MinHeapify(0); + + return root; +} + +/** 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 + */ +void MinHeap::MinHeapify(int i) { + int l = left(i); + int r = right(i); + int smallest = i; + if (l < heap_size && harr[l] < harr[i]) + smallest = l; + if (r < heap_size && harr[r] < harr[smallest]) + smallest = r; + if (smallest != i) { + std::swap(harr[i], harr[smallest]); + MinHeapify(smallest); + } +} + +// Driver program to test above functions +int main() { + MinHeap h(11); + h.insertKey(3); + h.insertKey(2); + h.deleteKey(1); + h.insertKey(15); + h.insertKey(5); + h.insertKey(4); + h.insertKey(45); + std::cout << h.extractMin() << " "; + std::cout << h.getMin() << " "; + h.decreaseKey(2, 1); + std::cout << h.getMin(); + return 0; +} diff --git a/data_structure/circular_Queue_using_Linked_List.cpp b/data_structures/circular_queue_using_linked_list.cpp similarity index 70% rename from data_structure/circular_Queue_using_Linked_List.cpp rename to data_structures/circular_queue_using_linked_list.cpp index 4b1ec476c..5d6484ce3 100644 --- a/data_structure/circular_Queue_using_Linked_List.cpp +++ b/data_structures/circular_queue_using_linked_list.cpp @@ -1,24 +1,19 @@ #include -using namespace std; -struct node -{ +struct node { int data; struct node *next; }; -class Queue -{ +class Queue { node *front; node *rear; -public: - Queue() - { + public: + Queue() { front = NULL; rear = NULL; } - void createNode(int val) - { + void createNode(int val) { node *ptr; node *nn; nn = new node; @@ -28,14 +23,10 @@ public: 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,28 +37,23 @@ public: rear = nn; } } - void dequeue() - { + void dequeue() { node *n; n = front; front = front->next; delete (n); } - void traverse() - { + void traverse() { node *ptr; ptr = front; - do - { - cout << ptr->data << " "; + do { + 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) -{ +int main(void) { Queue q; q.enqueue(10); q.enqueue(20); diff --git a/data_structures/cll/CMakeLists.txt b/data_structures/cll/CMakeLists.txt new file mode 100644 index 000000000..cb18eb347 --- /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_structure/cll/cll.cpp b/data_structures/cll/cll.cpp similarity index 68% rename from data_structure/cll/cll.cpp rename to data_structures/cll/cll.cpp index efc068f3c..42bc9067e 100644 --- a/data_structure/cll/cll.cpp +++ b/data_structures/cll/cll.cpp @@ -5,49 +5,42 @@ 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; + 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; + head->next = head; } else { node *current = head; - while (current -> next != head) { + while (current->next != head) { current = current->next; } newNode->next = head; @@ -58,18 +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; + head->next = head; } else { node *current = head; - while (current -> next != head) { + while (current->next != head) { current = current->next; } current->next = newNode; @@ -79,22 +71,17 @@ 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) -{ +bool cll::find_item(int item_to_find) { if (head == NULL) { cout << "List is empty !" << endl; return false; } 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 +91,20 @@ 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++() -{ +void cll::operator++() { if (head == NULL) { cout << "List is empty !" << endl; } 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_structures/cll/cll.h b/data_structures/cll/cll.h new file mode 100644 index 000000000..a1a9b4d92 --- /dev/null +++ b/data_structures/cll/cll.h @@ -0,0 +1,43 @@ +/* + * Simple data structure CLL (Cicular Linear Linked List) + * */ +#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; +}; + +class cll { + 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 */ + + /****************************************************** + * 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 */ +}; +#endif diff --git a/data_structures/cll/main_cll.cpp b/data_structures/cll/main_cll.cpp new file mode 100644 index 000000000..0b6bfd3ed --- /dev/null +++ b/data_structures/cll/main_cll.cpp @@ -0,0 +1,43 @@ +#include "cll.h" +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: " << endl; + list1.display(); + cout << "After insert 10 3 7 at front: " << endl; + list1.insert_front(10); + list1.insert_front(3); + list1.insert_front(7); + list1.display(); + cout << "----------- Test insert tail -----------" << endl; + cout << "After insert 18 19 20 at tail: " << endl; + list1.insert_tail(18); + list1.insert_tail(19); + list1.insert_tail(20); + list1.display(); + cout << "----------- Test find item -----------" << endl; + if (list1.find_item(10)) + cout << "PASS" << endl; + else + cout << "FAIL" << endl; + if (!list1.find_item(30)) + cout << "PASS" << endl; + else + cout << "FAIL" << endl; + cout << "----------- Test * operator -----------" << endl; + int value = *list1; + cout << "Value at *list1: " << value << endl; + cout << "----------- Test ++ operator -----------" << endl; + list1.display(); + ++list1; + cout << "After ++list1: " << endl; + list1.display(); + + return 0; +} diff --git a/data_structures/disjoint_set.cpp b/data_structures/disjoint_set.cpp new file mode 100644 index 000000000..dd70e4cea --- /dev/null +++ b/data_structures/disjoint_set.cpp @@ -0,0 +1,62 @@ +#include +#include + +using std::cout; +using std::endl; +using std::vector; + +vector 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; + } +} + +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); } + +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; + } + } + // 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; +} diff --git a/data_structures/doubly_linked_list.cpp b/data_structures/doubly_linked_list.cpp new file mode 100644 index 000000000..30cc257d8 --- /dev/null +++ b/data_structures/doubly_linked_list.cpp @@ -0,0 +1,136 @@ +#include +#include +#include + +struct node { + int val; + node *prev; + node *next; +} * start; + +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(); +}; + +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; + } +} + +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; + } + 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; + } + 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::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; +} diff --git a/data_structures/linked_list.cpp b/data_structures/linked_list.cpp new file mode 100644 index 000000000..8eb6e586d --- /dev/null +++ b/data_structures/linked_list.cpp @@ -0,0 +1,134 @@ +#include + +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 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; + + 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; + } + + 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 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"; + } +} + +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; +} diff --git a/data_structures/linkedlist_implentation_usingarray.cpp b/data_structures/linkedlist_implentation_usingarray.cpp new file mode 100644 index 000000000..75d400d72 --- /dev/null +++ b/data_structures/linkedlist_implentation_usingarray.cpp @@ -0,0 +1,114 @@ +/** + * \file + * \brief Linked list implementation using Arrays + * + * The difference between the pointer implementation of linked list and array + * implementation of linked list: + * 1. The NULL is represented by -1; + * 2. Limited size. (in the following case it is 100 nodes at max). But we can + * reuse the nodes that are to be deleted by again linking it bacj to the list. + */ + +#include + +struct Node { + int data; + int next; +}; + +Node AvailArray[100]; ///< array that will act as nodes of a linked list. + +int head = -1; +int avail = 0; +void initialise_list() { + for (int i = 0; i <= 98; i++) { + AvailArray[i].next = i + 1; + } + AvailArray[99].next = -1; // indicating the end of the linked list. +} + +/** This will return the index of the first free node present in the avail list + */ +int getnode() { + int NodeIndexToBeReturned = avail; + avail = AvailArray[avail].next; + return NodeIndexToBeReturned; +} + +/** This function when called will delete the node with + * the index presented as an argument, and will put + * back that node into the array. + */ +void freeNode(int nodeToBeDeleted) { + AvailArray[nodeToBeDeleted].next = avail; + avail = nodeToBeDeleted; +} + +/** The function will insert the given data + * into the front of the linked list. + */ +void insertAtTheBeginning(int data) { + int newNode = getnode(); + AvailArray[newNode].data = data; + AvailArray[newNode].next = head; + head = newNode; +} + +void insertAtTheEnd(int data) { + int newNode = getnode(); + int temp = head; + while (AvailArray[temp].next != -1) { + temp = AvailArray[temp].next; + } + // temp is now pointing to the end node. + AvailArray[newNode].data = data; + AvailArray[newNode].next = -1; + AvailArray[temp].next = newNode; +} + +void display() { + int temp = head; + while (temp != -1) { + std::cout << AvailArray[temp].data << "->"; + temp = AvailArray[temp].next; + } + std::cout << "-1" << std::endl; +} + +/** Main function */ +int main() { + initialise_list(); + int x, y, z; + for (;;) { + std::cout << "1. Insert At The Beginning" << std::endl; + std::cout << "2. Insert At The End" << std::endl; + std::cout << "3. Display" << std::endl; + std::cout << "4.Exit" << std::endl; + std::cout << "Enter Your choice" << std::endl; + std::cin >> z; + switch (z) { + case 1: + std::cout << "Enter the number you want to enter" << std::endl; + std::cin >> x; + insertAtTheBeginning(x); + break; + case 2: + std::cout << "Enter the number you want to enter" << std::endl; + std::cin >> y; + insertAtTheEnd(y); + break; + case 3: + std::cout + << "The linked list contains the following element in order" + << std::endl; + display(); + break; + case 4: + return 0; + default: + std::cout << "The entered choice is not correct" << std::endl; + } + } + + return 0; +} diff --git a/data_structures/list_array.cpp b/data_structures/list_array.cpp new file mode 100644 index 000000000..c796ffef9 --- /dev/null +++ b/data_structures/list_array.cpp @@ -0,0 +1,153 @@ +#include +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 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; +} diff --git a/data_structures/morrisinorder.cpp b/data_structures/morrisinorder.cpp new file mode 100644 index 000000000..f1f9e068c --- /dev/null +++ b/data_structures/morrisinorder.cpp @@ -0,0 +1,92 @@ +#include +#include + +/************************** + @author shrutisheoran +**************************/ + +using namespace std; + +struct Btree { + 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; + } + } + } +} + +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; + } + } + } +} + +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; +} diff --git a/data_structures/queue.h b/data_structures/queue.h new file mode 100644 index 000000000..3cb551741 --- /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_H_ +#define DATA_STRUCTURES_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_H_ diff --git a/data_structure/queue_using_array.cpp b/data_structures/queue_using_array.cpp similarity index 95% rename from data_structure/queue_using_array.cpp rename to data_structures/queue_using_array.cpp index ccd6e3cd6..a887c99fc 100644 --- a/data_structure/queue_using_array.cpp +++ b/data_structures/queue_using_array.cpp @@ -58,8 +58,7 @@ void Queue_Array::display() { if (front == -1) { std::cout << "\nStack is empty"; } else { - for (int i = front; i <= rear; i++) - std::cout << arr[i] << " "; + for (int i = front; i <= rear; i++) std::cout << arr[i] << " "; } } diff --git a/data_structures/queue_using_array2.cpp b/data_structures/queue_using_array2.cpp new file mode 100644 index 000000000..13f7d8e17 --- /dev/null +++ b/data_structures/queue_using_array2.cpp @@ -0,0 +1,57 @@ +#include +using namespace std; + +int queue[10]; +int front = 0; +int rear = 0; + +void Enque(int x) { + if (rear == 10) { + cout << "\nOverflow"; + } else { + queue[rear++] = x; + } +} + +void Deque() { + 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; + } +} + +void show() { + 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); + + return 0; +} diff --git a/data_structure/Queue Using Linked List.cpp b/data_structures/queue_using_linked_list.cpp similarity index 69% rename from data_structure/Queue Using Linked List.cpp rename to data_structures/queue_using_linked_list.cpp index 39d7a9ae3..7b44d240c 100644 --- a/data_structure/Queue Using Linked List.cpp +++ b/data_structures/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,9 +17,7 @@ void Enque(int x) front = n; } - else - { - + else { node *n = new node; n->val = x; n->next = NULL; @@ -31,17 +26,12 @@ 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"; + cout << "\n" << t->val << " deleted"; front = front->next; delete t; if (front == NULL) @@ -49,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_structures/queue_using_linkedlist.cpp b/data_structures/queue_using_linkedlist.cpp new file mode 100644 index 000000000..f1bf18123 --- /dev/null +++ b/data_structures/queue_using_linkedlist.cpp @@ -0,0 +1,86 @@ +/* + Write a program to implement Queue using linkedlist. +*/ +#include + +struct linkedlist { + int data; + linkedlist *next; +}; +class stack_linkedList { + public: + linkedlist *front; + linkedlist *rear; + + 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; + + if (front == NULL) + front = rear = temp; + else { + rear->next = temp; + rear = temp; + } +} +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); + } + return ele; +} +void stack_linkedList::display() { + if (front == NULL) + std::cout << "\nStack is empty"; + + else { + linkedlist *temp; + temp = front; + while (temp != NULL) { + std::cout << temp->data << " "; + temp = temp->next; + } + } +} + +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 << "Enter data "; + std::cin >> data; + ob.enqueue(data); + } else if (op == 2) + data = ob.dequeue(); + else if (op == 3) + ob.display(); + else if (op == 4) + exit(0); + else + std::cout << "\nWrong choice "; + } + return 0; +} diff --git a/data_structures/stack.h b/data_structures/stack.h new file mode 100644 index 000000000..f4b8992e7 --- /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_STACK_H_ +#define DATA_STRUCTURES_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_STACK_H_ diff --git a/data_structures/stack_using_array.cpp b/data_structures/stack_using_array.cpp new file mode 100644 index 000000000..36be9eb39 --- /dev/null +++ b/data_structures/stack_using_array.cpp @@ -0,0 +1,55 @@ +#include + +int *stack; +int top = 0, stack_size; + +void push(int x) { + if (top == stack_size) { + std::cout << "\nOverflow"; + } else { + stack[top++] = x; + } +} + +void pop() { + if (top == 0) { + std::cout << "\nUnderflow"; + } else { + std::cout << "\n" << stack[--top] << " deleted"; + } +} + +void show() { + for (int i = 0; i < top; i++) { + std::cout << stack[i] << "\n"; + } +} + +void topmost() { std::cout << "\nTopmost element: " << stack[top - 1]; } +int main() { + std::cout << "\nEnter stack_size of stack : "; + std::cin >> stack_size; + stack = new int[stack_size]; + int ch, x; + do { + std::cout << "\n1. Push"; + std::cout << "\n2. Pop"; + std::cout << "\n3. Print"; + std::cout << "\n4. Print topmost element:"; + std::cout << "\nEnter Your Choice : "; + std::cin >> ch; + if (ch == 1) { + std::cout << "\nInsert : "; + std::cin >> x; + push(x); + } else if (ch == 2) { + pop(); + } else if (ch == 3) { + show(); + } else if (ch == 4) { + topmost(); + } + } while (ch != 0); + + return 0; +} diff --git a/data_structures/stack_using_linked_list.cpp b/data_structures/stack_using_linked_list.cpp new file mode 100644 index 000000000..ae53fe95a --- /dev/null +++ b/data_structures/stack_using_linked_list.cpp @@ -0,0 +1,57 @@ +#include +using namespace std; + +struct node { + int val; + node *next; +}; + +node *top; + +void push(int x) { + 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; + } +} + +void show() { + 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); + + return 0; +} diff --git a/data_structure/stk/student.txt b/data_structures/student.txt similarity index 100% rename from data_structure/stk/student.txt rename to data_structures/student.txt diff --git a/data_structures/test_queue.cpp b/data_structures/test_queue.cpp new file mode 100644 index 000000000..387ccf2f7 --- /dev/null +++ b/data_structures/test_queue.cpp @@ -0,0 +1,41 @@ +#include +#include + +#include "./queue.h" + +int main() { + queue q; + std::cout << "---------------------- Test construct ----------------------" + << std::endl; + q.display(); + std::cout + << "---------------------- Test isEmptyQueue ----------------------" + << std::endl; + if (q.isEmptyQueue()) + std::cout << "PASS" << std::endl; + else + 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(); + std::cout << "---------------------- Test front ----------------------" + << std::endl; + std::string value = q.front(); + if (value == "Hai") + std::cout << "PASS" << std::endl; + else + std::cout << "FAIL" << std::endl; + std::cout << "---------------------- Test deQueue ----------------------" + << std::endl; + q.display(); + q.deQueue(); + q.deQueue(); + std::cout << "After Hai, Jeff left the queue: " << std::endl; + q.display(); + return 0; +} diff --git a/data_structures/test_stack.cpp b/data_structures/test_stack.cpp new file mode 100644 index 000000000..aa636916f --- /dev/null +++ b/data_structures/test_stack.cpp @@ -0,0 +1,59 @@ +#include + +#include "./stack.h" + +int main() { + stack stk; + std::cout << "---------------------- Test construct ----------------------" + << std::endl; + stk.display(); + std::cout + << "---------------------- Test isEmptyStack ----------------------" + << std::endl; + if (stk.isEmptyStack()) + std::cout << "PASS" << std::endl; + else + 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(); + std::cout << "---------------------- Test top ----------------------" + << std::endl; + int value = stk.top(); + if (value == 40) + std::cout << "PASS" << std::endl; + else + std::cout << "FAIL" << std::endl; + std::cout << "---------------------- Test pop ----------------------" + << std::endl; + stk.display(); + stk.pop(); + stk.pop(); + std::cout << "After popping 2 times: " << std::endl; + stk.display(); + std::cout << "---------------------- Test overload = operator " + "----------------------" + << std::endl; + stack stk1; + std::cout << "stk current: " << std::endl; + stk.display(); + std::cout << std::endl << "Assign stk1 = stk " << std::endl; + stk1 = stk; + stk1.display(); + std::cout << std::endl << "After pushing 8 9 10 into stk1:" << std::endl; + stk1.push(8); + stk1.push(9); + stk1.push(10); + stk1.display(); + std::cout << std::endl << "stk current: " << std::endl; + stk.display(); + std::cout << "Assign back stk = stk1:" << std::endl; + stk = stk1; + stk.display(); + return 0; +} diff --git a/data_structure/stk/main.cpp b/data_structures/test_stack_students.cpp similarity index 67% rename from data_structure/stk/main.cpp rename to data_structures/test_stack_students.cpp index 2d6bbec56..a6048c4c9 100644 --- a/data_structure/stk/main.cpp +++ b/data_structures/test_stack_students.cpp @@ -8,29 +8,26 @@ * ./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; + 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 < 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; - if (ch == 'l') - CreateTree(n, n->left, x, ch); - else if (ch == 'r') - CreateTree(n, n->right, x, ch); - } - else - { + 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 { 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) -{ - list queue; +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(); - 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); } } -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_modern.cpp b/data_structures/trie_modern.cpp similarity index 96% rename from data_structure/trie_modern.cpp rename to data_structures/trie_modern.cpp index 218c90b68..c2eba30e0 100644 --- a/data_structure/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()) {} /** diff --git a/data_structures/trie_tree.cpp b/data_structures/trie_tree.cpp new file mode 100644 index 000000000..66b67fbc0 --- /dev/null +++ b/data_structures/trie_tree.cpp @@ -0,0 +1,87 @@ +#include +#include + +#include +#include + +// structure definition +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; + return nn; +} + +// insert string into the trie +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]; + } + } + 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) + return false; + return true; + } + int j = str[index] - 'a'; + if (!root->arr[j]) + return false; + 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 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++) return false; + return true; + } + int j = str[index] - 'a'; + if (!root->arr[j]) + return false; + bool var = deleteString(root, str, index + 1); + if (var) { + root->arr[j] = NULL; + if (root->isEndofWord) { + return false; + } else { + int i; + for (i = 0; i < 26; i++) + if (root->arr[i]) + return false; + return true; + } + } +} + +int main() { + trie* root = createNode(); + insert(root, "hello"); + insert(root, "world"); + int a = search(root, "hello", 0); + int b = search(root, "word", 0); + printf("%d %d ", a, b); + return 0; +} diff --git a/doc/cppreference-doxygen-web.tag.xml b/doc/cppreference-doxygen-web.tag.xml new file mode 100644 index 000000000..ea8388b8b --- /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 + + diff --git a/dynamic_programming/0-1 Knapsack.cpp b/dynamic_programming/0-1 Knapsack.cpp deleted file mode 100644 index 9348372b2..000000000 --- a/dynamic_programming/0-1 Knapsack.cpp +++ /dev/null @@ -1,71 +0,0 @@ -//0-1 Knapsack problem - Dynamic programming -//#include -#include -using namespace std; - -//void Print(int res[20][20], int i, int j, int capacity) -//{ -// if(i==0 || j==0) -// { -// return; -// } -// if(res[i-1][j]==res[i][j-1]) -// { -// if(i<=capacity) -// { -// cout<res[i][j-1]) -// { -// Print(res, i-1,j, capacity); -// } -// else if(res[i][j-1]>res[i-1][j]) -// { -// Print(res, i,j-1, capacity); -// } -//} - -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 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; -} diff --git a/dynamic_programming/0_1_knapsack.cpp b/dynamic_programming/0_1_knapsack.cpp new file mode 100644 index 000000000..7ea0c04c6 --- /dev/null +++ b/dynamic_programming/0_1_knapsack.cpp @@ -0,0 +1,66 @@ +// 0-1 Knapsack problem - Dynamic programming +//#include +#include +using namespace std; + +// void Print(int res[20][20], int i, int j, int capacity) +//{ +// if(i==0 || j==0) +// { +// return; +// } +// if(res[i-1][j]==res[i][j-1]) +// { +// if(i<=capacity) +// { +// cout<res[i][j-1]) +// { +// Print(res, i-1,j, capacity); +// } +// else if(res[i][j-1]>res[i-1][j]) +// { +// Print(res, i,j-1, capacity); +// } +//} + +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 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; +} diff --git a/dynamic_programming/Bellman-Ford.cpp b/dynamic_programming/Bellman-Ford.cpp deleted file mode 100644 index 7c36d96df..000000000 --- a/dynamic_programming/Bellman-Ford.cpp +++ /dev/null @@ -1,128 +0,0 @@ -#include -#include - -using namespace std; - -//Wrapper class for storing an edge -class Edge -{ -public: - int src, dst, weight; -}; - -//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; - } - } -}; - -//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; - } -} - -//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; -} - -//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; -} diff --git a/dynamic_programming/Coin-Change.cpp b/dynamic_programming/Coin-Change.cpp deleted file mode 100644 index c8acad48e..000000000 --- a/dynamic_programming/Coin-Change.cpp +++ /dev/null @@ -1,50 +0,0 @@ -#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]; -} - -int main() -{ - // No of Coins We Have - int arr[] = {1, 2, 3, 4}; - int n = sizeof(arr) / sizeof(arr[0]); - - // Total Change Required - int N = 15; - - cout << "Minimum Number of Coins Required " << findMinCoins(arr, n, N) << "\n"; - - return 0; -} \ No newline at end of file diff --git a/dynamic_programming/Cut Rod.cpp b/dynamic_programming/Cut Rod.cpp deleted file mode 100644 index afca3dced..000000000 --- a/dynamic_programming/Cut Rod.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/*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 -using namespace std; -int cutrod(int p[], int n) -{ - int r[n + 1]; - r[0] = 0; - for (int j = 0; j < n; j++) - { - int q = INT_MIN; - 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 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/Fibonacci_Bottom_Up.cpp b/dynamic_programming/Fibonacci_Bottom_Up.cpp deleted file mode 100644 index ab5b5b41f..000000000 --- a/dynamic_programming/Fibonacci_Bottom_Up.cpp +++ /dev/null @@ -1,24 +0,0 @@ -#include -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 main(int argc, char const *argv[]) -{ - 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 deleted file mode 100644 index 9d76366f7..000000000 --- a/dynamic_programming/Fibonacci_Top_Down.cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include -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]; -} -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; -} \ No newline at end of file diff --git a/dynamic_programming/Floyd-Warshall.cpp b/dynamic_programming/Floyd-Warshall.cpp deleted file mode 100644 index 93ccff62f..000000000 --- a/dynamic_programming/Floyd-Warshall.cpp +++ /dev/null @@ -1,112 +0,0 @@ -#include -#include -#include - -using namespace std; - -//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; - } -}; - -//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; - } -} - -//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]; - - //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 - - 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 - - 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]; - - print(dist1d, V); -} - -//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; -} diff --git a/dynamic_programming/Longest Common Subsequence.cpp b/dynamic_programming/Longest Common Subsequence.cpp deleted file mode 100644 index af50720b4..000000000 --- a/dynamic_programming/Longest Common Subsequence.cpp +++ /dev/null @@ -1,82 +0,0 @@ -//Longest common subsequence - Dynamic Programming -#include -using namespace std; - -void Print(int trace[20][20], int m, int n, string a) -{ - if (m == 0 || n == 0) - { - return; - } - if (trace[m][n] == 1) - { - Print(trace, m - 1, n - 1, a); - cout << a[m - 1]; - } - else if (trace[m][n] == 2) - { - Print(trace, m - 1, n, a); - } - else if (trace[m][n] == 3) - { - Print(trace, m, n - 1, a); - } -} - -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++) - { - 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) - { - res[i][j] = 0; - trace[i][j] = 0; - } - - 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]) - { - res[i][j] = res[i - 1][j]; - 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. - } - } - } - } - Print(trace, m, n, a); - return res[m][n]; -} - -int main() -{ - string a, b; - cin >> a >> b; - cout << lcs(a, b); - return 0; -} diff --git a/dynamic_programming/Longest Increasing Subsequence (nlogn).cpp b/dynamic_programming/Longest Increasing Subsequence (nlogn).cpp deleted file mode 100644 index 5ee24e6a7..000000000 --- a/dynamic_programming/Longest Increasing Subsequence (nlogn).cpp +++ /dev/null @@ -1,46 +0,0 @@ -//Program to calculate length of longest increasing subsequence in an array -// in O(n log n) -// tested on : https://cses.fi/problemset/task/1145/ - -#include - -using namespace std; -int LIS(int arr[], int n) -{ - set < int > 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. - 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]) - { - // 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. -} -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; -} diff --git a/dynamic_programming/Longest Increasing Subsequence.cpp b/dynamic_programming/Longest Increasing Subsequence.cpp deleted file mode 100644 index 49c54a941..000000000 --- a/dynamic_programming/Longest Increasing Subsequence.cpp +++ /dev/null @@ -1,39 +0,0 @@ -//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 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; -} \ No newline at end of file diff --git a/dynamic_programming/Matrix-Chain-Multiplication.cpp b/dynamic_programming/Matrix-Chain-Multiplication.cpp deleted file mode 100644 index 1e885bd7e..000000000 --- a/dynamic_programming/Matrix-Chain-Multiplication.cpp +++ /dev/null @@ -1,62 +0,0 @@ -#include -#include -using namespace std; - -#define MAX 10 - -// 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 -int MatrixChainMultiplication(int dim[], int i, int j) -{ - // 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; - - // 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 - - 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); - - // 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; - } - - // 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]); - - // Function Calling: MatrixChainMultiplications(dimensions_array, starting, ending); - - cout << "Minimum cost is " << MatrixChainMultiplication(dim, 0, n - 1) << "\n"; - - return 0; -} \ No newline at end of file diff --git a/dynamic_programming/armstrong_number.cpp b/dynamic_programming/armstrong_number.cpp index 4dba89a27..270a705f7 100644 --- a/dynamic_programming/armstrong_number.cpp +++ b/dynamic_programming/armstrong_number.cpp @@ -1,21 +1,21 @@ // 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 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 new file mode 100644 index 000000000..c96f3fd8e --- /dev/null +++ b/dynamic_programming/bellman_ford.cpp @@ -0,0 +1,116 @@ +#include +#include + +using namespace std; + +// Wrapper class for storing an edge +class Edge { + public: + int src, dst, weight; +}; + +// 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; + } + } +}; + +// 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; + } +} + +// 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; +} + +// 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; +} diff --git a/dynamic_programming/Catalan-Numbers.cpp b/dynamic_programming/catalan_numbers.cpp similarity index 85% rename from dynamic_programming/Catalan-Numbers.cpp rename to dynamic_programming/catalan_numbers.cpp index 4d73cd51a..f5edaa916 100644 --- a/dynamic_programming/Catalan-Numbers.cpp +++ b/dynamic_programming/catalan_numbers.cpp @@ -9,10 +9,9 @@ #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) -{ +unsigned long int catalan_dp(int n) { /** Using the tabulation technique in dynamic programming, this function computes the first `n+1` Catalan numbers @@ -29,19 +28,17 @@ 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 + cat[i] += cat[j] * cat[i - j - 1]; // applying the definition here } // Return the result 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 new file mode 100644 index 000000000..8c8fc3dfb --- /dev/null +++ b/dynamic_programming/coin_change.cpp @@ -0,0 +1,48 @@ +#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]; +} + +int main() { + // No of Coins We Have + int arr[] = {1, 2, 3, 4}; + int n = sizeof(arr) / sizeof(arr[0]); + + // Total Change Required + int N = 15; + + cout << "Minimum Number of Coins Required " << findMinCoins(arr, n, N) + << "\n"; + + return 0; +} \ No newline at end of file diff --git a/dynamic_programming/cut_rod.cpp b/dynamic_programming/cut_rod.cpp new file mode 100644 index 000000000..136c78dbb --- /dev/null +++ b/dynamic_programming/cut_rod.cpp @@ -0,0 +1,25 @@ +/*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 +using namespace std; +int cutrod(int p[], int n) { + int r[n + 1]; + r[0] = 0; + for (int j = 0; j < n; j++) { + int q = INT_MIN; + 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 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 similarity index 60% rename from dynamic_programming/Edit Distance.cpp rename to dynamic_programming/edit_distance.cpp index 996d3272c..889b080cb 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,31 +15,27 @@ #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 * 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) 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)); @@ -48,33 +44,29 @@ 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) -{ - - //Create Table for SubProblems +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++) - { - //If str1 empty. Then add all of str2 + // 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 (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 ); } } @@ -82,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 similarity index 63% rename from dynamic_programming/Egg-Dropping-Puzzle.cpp rename to dynamic_programming/egg_dropping_puzzle.cpp index a441f29cb..7a769ea47 100644 --- a/dynamic_programming/Egg-Dropping-Puzzle.cpp +++ b/dynamic_programming/egg_dropping_puzzle.cpp @@ -1,35 +1,29 @@ -/* 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) -{ +int eggDrop(int n, int k) { int eggFloor[n + 1][k + 1]; int result; - for (int i = 1; i <= n; i++) - { - eggFloor[i][1] = 1; //n eggs..1 Floor - eggFloor[i][0] = 0; //n eggs..0 Floor + 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 new file mode 100644 index 000000000..555f15282 --- /dev/null +++ b/dynamic_programming/fibonacci_bottom_up.cpp @@ -0,0 +1,21 @@ +#include +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 main(int argc, char const *argv[]) { + 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 new file mode 100644 index 000000000..3c0c9a1a3 --- /dev/null +++ b/dynamic_programming/fibonacci_top_down.cpp @@ -0,0 +1,22 @@ +#include +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]; +} +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; +} \ No newline at end of file diff --git a/dynamic_programming/floyd_warshall.cpp b/dynamic_programming/floyd_warshall.cpp new file mode 100644 index 000000000..d193ebbd5 --- /dev/null +++ b/dynamic_programming/floyd_warshall.cpp @@ -0,0 +1,107 @@ +#include +#include +#include + +using std::cin; +using std::cout; +using std::endl; + +// 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 = 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) { + this->edges[src][dst] = weight; + } +}; + +// 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; + } +} + +// 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]; + + // 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 + + 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 + + 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]; + + print(dist1d, V); +} + +// 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; +} diff --git a/dynamic_programming/kadane.cpp b/dynamic_programming/kadane.cpp index bf2aa76ac..b5272756b 100644 --- a/dynamic_programming/kadane.cpp +++ b/dynamic_programming/kadane.cpp @@ -1,5 +1,5 @@ -#include -#include +#include +#include int maxSubArraySum(int a[], int size) { int max_so_far = INT_MIN, max_ending_here = 0; @@ -15,7 +15,6 @@ int maxSubArraySum(int a[], int size) { return max_so_far; } - int main() { int n, i; std::cout << "Enter the number of elements \n"; diff --git a/dynamic_programming/longest_common_string.cpp b/dynamic_programming/longest_common_string.cpp index c1e89d6db..81fa8a002 100644 --- a/dynamic_programming/longest_common_string.cpp +++ b/dynamic_programming/longest_common_string.cpp @@ -1,65 +1,53 @@ #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) - { - ma=a[i][j]; - indi=i; - indj=j; + for(j=0;j ma) { + ma = a[i][j]; + indi = i; + indj = j; } } } - cout< +using namespace std; + +void Print(int trace[20][20], int m, int n, string a) { + if (m == 0 || n == 0) { + return; + } + if (trace[m][n] == 1) { + Print(trace, m - 1, n - 1, a); + cout << a[m - 1]; + } else if (trace[m][n] == 2) { + Print(trace, m - 1, n, a); + } else if (trace[m][n] == 3) { + Print(trace, m, n - 1, a); + } +} + +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++) { + 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) { + res[i][j] = 0; + trace[i][j] = 0; + } + + 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]) { + res[i][j] = res[i - 1][j]; + 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. + } + } + } + } + Print(trace, m, n, a); + return res[m][n]; +} + +int main() { + string a, b; + cin >> a >> b; + cout << lcs(a, b); + return 0; +} diff --git a/dynamic_programming/longest_increasing_subsequence.cpp b/dynamic_programming/longest_increasing_subsequence.cpp new file mode 100644 index 000000000..b6a798aa0 --- /dev/null +++ b/dynamic_programming/longest_increasing_subsequence.cpp @@ -0,0 +1,32 @@ +// 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 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; +} \ No newline at end of file diff --git a/dynamic_programming/longest_increasing_subsequence_(nlogn).cpp b/dynamic_programming/longest_increasing_subsequence_(nlogn).cpp new file mode 100644 index 000000000..5bc72345c --- /dev/null +++ b/dynamic_programming/longest_increasing_subsequence_(nlogn).cpp @@ -0,0 +1,41 @@ +// Program to calculate length of longest increasing subsequence in an array +// in O(n log n) +// tested on : https://cses.fi/problemset/task/1145/ + +#include + +using namespace std; +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) { + 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. + 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]) { + // 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. +} +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; +} diff --git a/dynamic_programming/matrix_chain_multiplication.cpp b/dynamic_programming/matrix_chain_multiplication.cpp new file mode 100644 index 000000000..7d6647c52 --- /dev/null +++ b/dynamic_programming/matrix_chain_multiplication.cpp @@ -0,0 +1,61 @@ +#include +#include +using namespace std; + +#define MAX 10 + +// 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 +int MatrixChainMultiplication(int dim[], int i, int j) { + // 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; + + // 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 + + 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); + + // 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; + } + + // 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]); + + // Function Calling: MatrixChainMultiplications(dimensions_array, starting, + // ending); + + cout << "Minimum cost is " << MatrixChainMultiplication(dim, 0, n - 1) + << "\n"; + + 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 9ee48dded..7792a5149 100644 --- a/dynamic_programming/searching_of_element_in_dynamic_array.cpp +++ b/dynamic_programming/searching_of_element_in_dynamic_array.cpp @@ -1,36 +1,36 @@ /* -*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 @@ -46,7 +46,7 @@ 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++) { @@ -75,6 +75,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. @@ -37,7 +37,7 @@ void depth_first_search(int u) { 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. @@ -61,9 +61,9 @@ int main() { 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/geometry/CMakeLists.txt b/geometry/CMakeLists.txt new file mode 100644 index 000000000..72655169a --- /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} ) diff --git a/geometry/line_segment_intersection.cpp b/geometry/line_segment_intersection.cpp index 0b5b858d7..d523ae0a4 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 /** @@ -20,57 +21,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 +99,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; } diff --git a/graph/BFS.cpp b/graph/BFS.cpp deleted file mode 100644 index e4e12886b..000000000 --- a/graph/BFS.cpp +++ /dev/null @@ -1,73 +0,0 @@ -#include -using namespace std; -class graph -{ - int v; - list *adj; - -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]; -} -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++) - { - 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); - } - } - } -} -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; -} diff --git a/graph/DFS.cpp b/graph/DFS.cpp deleted file mode 100644 index 656711ac8..000000000 --- a/graph/DFS.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include -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); - } - } -} - -void DFS_(int graph[4][4], int 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; -} \ No newline at end of file diff --git a/graph/Kruskal.cpp b/graph/Kruskal.cpp deleted file mode 100644 index 21b04ce49..000000000 --- a/graph/Kruskal.cpp +++ /dev/null @@ -1,135 +0,0 @@ -#include -//#include -//using namespace boost::multiprecision; -const int mx = 1e6 + 5; -const long int inf = 2e9; -typedef long long ll; -#define rep(i, n) for (i = 0; i < n; i++) -#define repp(i, a, b) for (i = a; i <= b; i++) -#define pii pair -#define vpii vector -#define vi vector -#define vll vector -#define r(x) scanf("%d", &x) -#define rs(s) scanf("%s", s) -#define gc getchar_unlocked -#define pc putchar_unlocked -#define mp make_pair -#define pb push_back -#define lb lower_bound -#define ub upper_bound -#define endl "\n" -#define fast \ - ios_base::sync_with_stdio(false); \ - cin.tie(NULL); \ - cout.tie(NULL); -using namespace std; -void in(int &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'); -} -ll parent[mx], arr[mx], node, edge; -vector>> v; -void initial() -{ - 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; -} -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 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< -#include -#include -using namespace std; - -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); -} - -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()); -} -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; -} diff --git a/graph/bfs.cpp b/graph/bfs.cpp new file mode 100644 index 000000000..3acee8f80 --- /dev/null +++ b/graph/bfs.cpp @@ -0,0 +1,62 @@ +#include +using namespace std; +class graph { + int v; + list *adj; + + 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]; +} +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++) { + 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); + } + } + } +} +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; +} diff --git a/graph/bridge_finding_with_tarjan_algorithm.cpp b/graph/bridge_finding_with_tarjan_algorithm.cpp index ca124f512..eec176af5 100644 --- a/graph/bridge_finding_with_tarjan_algorithm.cpp +++ b/graph/bridge_finding_with_tarjan_algorithm.cpp @@ -4,27 +4,27 @@ * 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; +using std::vector; class Solution { - vector < vector < int > > graph; - vectorin_time , out_time; + 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] ) { + for (auto& itr : graph[current_node]) { if (itr == parent) { continue; } if (!visited[itr]) { - dfs(itr , current_node); + dfs(itr, current_node); if (out_time[itr] > in_time[current_node]) { bridge.push_back({itr, current_node}); } @@ -34,14 +34,14 @@ 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]); } @@ -52,7 +52,7 @@ class Solution { 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 +66,13 @@ 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 9c22cc35e..0bfb8bbdb 100644 --- a/graph/connected_components.cpp +++ b/graph/connected_components.cpp @@ -8,48 +8,47 @@ class graph { 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; + 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); + 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); + 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); + 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; + 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 2c5c6dab5..aa03bef8f 100644 --- a/graph/connected_components_with_dsu.cpp +++ b/graph/connected_components_with_dsu.cpp @@ -1,6 +1,6 @@ #include -#include #include +#include int N; // denotes number of nodes; std::vector parent; @@ -31,8 +31,7 @@ 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 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(); } diff --git a/graph/cycle_check_directed_graph.cpp b/graph/cycle_check_directed_graph.cpp new file mode 100644 index 000000000..0f7b84cd3 --- /dev/null +++ b/graph/cycle_check_directed_graph.cpp @@ -0,0 +1,302 @@ +/** + * Copyright 2020 + * @file cycle_check_directed graph.cpp + * + * @brief BFS and DFS algorithms to check for cycle in a directed graph. + * + * @author Anmol3299 + * contact: mittalanmol22@gmail.com + * + */ + +#include // for std::cout +#include // for std::queue +#include // for throwing errors +#include // for std::remove_reference_t +#include // for std::unordered_map +#include // for std::move +#include // for std::vector + +/** + * Implementation of non-weighted directed edge of a graph. + * + * The source vertex of the edge is labelled "src" and destination vertex is + * labelled "dest". + */ +struct Edge { + unsigned int src; + unsigned int dest; + + Edge() = delete; + ~Edge() = default; + Edge(Edge&&) = default; + Edge& operator=(Edge&&) = default; + Edge(Edge const&) = default; + Edge& operator=(Edge const&) = default; + + /** Set the source and destination of the vertex. + * + * @param source is the source vertex of the edge. + * @param destination is the destination vertex of the edge. + */ + Edge(unsigned int source, unsigned int destination) + : src(source), dest(destination) {} +}; + +using AdjList = std::unordered_map>; + +/** + * Implementation of graph class. + * + * The graph will be represented using Adjacency List representation. + * This class contains 2 data members "m_vertices" & "m_adjList" used to + * represent the number of vertices and adjacency list of the graph + * respectively. The vertices are labelled 0 - (m_vertices - 1). + */ +class Graph { + public: + Graph() : m_vertices(0), m_adjList({}) {} + ~Graph() = default; + Graph(Graph&&) = default; + Graph& operator=(Graph&&) = default; + Graph(Graph const&) = default; + Graph& operator=(Graph const&) = default; + + /** Create a graph from vertices and adjacency list. + * + * @param vertices specify the number of vertices the graph would contain. + * @param adjList is the adjacency list representation of graph. + */ + Graph(unsigned int vertices, AdjList const& adjList) + : m_vertices(vertices), m_adjList(adjList) {} + + /** Create a graph from vertices and adjacency list. + * + * @param vertices specify the number of vertices the graph would contain. + * @param adjList is the adjacency list representation of graph. + */ + Graph(unsigned int vertices, AdjList&& adjList) + : m_vertices(std::move(vertices)), m_adjList(std::move(adjList)) {} + + /** Create a graph from vertices and a set of edges. + * + * Adjacency list of the graph would be created from the set of edges. If + * the source or destination of any edge has a value greater or equal to + * number of vertices, then it would throw a range_error. + * + * @param vertices specify the number of vertices the graph would contain. + * @param edges is a vector of edges. + */ + Graph(unsigned int vertices, std::vector const& edges) + : m_vertices(vertices) { + for (auto const& edge : edges) { + if (edge.src >= vertices || edge.dest >= vertices) { + throw std::range_error( + "Either src or dest of edge out of range"); + } + m_adjList[edge.src].emplace_back(edge.dest); + } + } + + /** Return a const reference of the adjacency list. + * + * @return const reference to the adjacency list + */ + std::remove_reference_t const& getAdjList() const { + return m_adjList; + } + + /** + * @return number of vertices in the graph. + */ + std::remove_reference_t const& getVertices() const { + return m_vertices; + } + + /** Add vertices in the graph. + * + * @param num is the number of vertices to be added. It adds 1 vertex by + * default. + * + */ + void addVertices(unsigned int num = 1) { m_vertices += num; } + + /** Add an edge in the graph. + * + * @param edge that needs to be added. + */ + void addEdge(Edge const& edge) { + if (edge.src >= m_vertices || edge.dest >= m_vertices) { + throw std::range_error("Either src or dest of edge out of range"); + } + m_adjList[edge.src].emplace_back(edge.dest); + } + + /** Add an Edge in the graph + * + * @param source is source vertex of the edge. + * @param destination is the destination vertex of the edge. + */ + void addEdge(unsigned int source, unsigned int destination) { + if (source >= m_vertices || destination >= m_vertices) { + throw std::range_error( + "Either source or destination of edge out of range"); + } + m_adjList[source].emplace_back(destination); + } + + private: + unsigned int m_vertices; + AdjList m_adjList; +}; + +class CycleCheck { + private: + enum nodeStates : uint8_t { not_visited = 0, in_stack, visited }; + + /** Helper function of "isCyclicDFS". + * + * @param adjList is the adjacency list representation of some graph. + * @param state is the state of the nodes of the graph. + * @param node is the node being evaluated. + * + * @return true if graph has a cycle, else false. + */ + static bool isCyclicDFSHelper(AdjList const& adjList, + std::vector* state, + unsigned int node) { + // Add node "in_stack" state. + (*state)[node] = in_stack; + + // If the node has children, then recursively visit all children of the + // node. + if (auto const& it = adjList.find(node); it != adjList.end()) { + for (auto child : it->second) { + // If state of child node is "not_visited", evaluate that child + // for presence of cycle. + if (auto state_of_child = (*state)[child]; + state_of_child == not_visited) { + if (isCyclicDFSHelper(adjList, state, child)) { + return true; + } + } else if (state_of_child == in_stack) { + // If child node was "in_stack", then that means that there + // is a cycle in the graph. Return true for presence of the + // cycle. + return true; + } + } + } + + // Current node has been evaluated for the presence of cycle and had no + // cycle. Mark current node as "visited". + (*state)[node] = visited; + // Return that current node didn't result in any cycles. + return false; + } + + public: + /** Driver function to check if a graph has a cycle. + * + * This function uses DFS to check for cycle in the graph. + * + * @param graph which needs to be evaluated for the presence of cycle. + * @return true if a cycle is detected, else false. + */ + static bool isCyclicDFS(Graph const& graph) { + /** State of the node. + * + * It is a vector of "nodeStates" which represents the state node is in. + * It can take only 3 values: "not_visited", "in_stack", and "visited". + * + * Initially, all nodes are in "not_visited" state. + */ + std::vector state(graph.getVertices(), not_visited); + + // Start visiting each node. + for (auto node = 0; node < graph.getVertices(); node++) { + // If a node is not visited, only then check for presence of cycle. + // There is no need to check for presence of cycle for a visited + // node as it has already been checked for presence of cycle. + if (state[node] == not_visited) { + // Check for cycle. + if (isCyclicDFSHelper(graph.getAdjList(), &state, node)) { + return true; + } + } + } + + // All nodes have been safely traversed, that means there is no cycle in + // the graph. Return false. + return false; + } + + /** Check if a graph has cycle or not. + * + * This function uses BFS to check if a graph is cyclic or not. + * + * @param graph which needs to be evaluated for the presence of cycle. + * @return true if a cycle is detected, else false. + */ + static bool isCyclicBFS(Graph const& graph) { + AdjList graphAjdList = graph.getAdjList(); + + std::vector indegree(graph.getVertices(), 0); + // Calculate the indegree i.e. the number of incident edges to the node. + for (auto const& [parent, children] : graphAjdList) { + for (auto const& child : children) { + indegree[child]++; + } + } + + std::queue can_be_solved; + for (auto node = 0; node < graph.getVertices(); node++) { + // If a node doesn't have any input edges, then that node will + // definately not result in a cycle and can be visited safely. + if (!indegree[node]) { + can_be_solved.emplace(node); + } + } + + // Vertices that need to be traversed. + auto remain = graph.getVertices(); + // While there are safe nodes that we can visit. + while (!can_be_solved.empty()) { + auto front = can_be_solved.front(); + // Visit the node. + can_be_solved.pop(); + // Decrease number of nodes that need to be traversed. + remain--; + + // Visit all the children of the visited node. + if (auto it = graphAjdList.find(front); it != graphAjdList.end()) { + for (auto child : it->second) { + // Check if we can visited the node safely. + if (--indegree[child] == 0) { + // if node can be visited safely, then add that node to + // the visit queue. + can_be_solved.emplace(child); + } + } + } + } + + // If there are still nodes that we can't visit, then it means that + // there is a cycle and return true, else return false. + return !(remain == 0); + } +}; + +/** + * Main function. + */ +int main() { + // Instantiate the graph. + Graph g(7, std::vector{{0, 1}, {1, 2}, {2, 0}, {2, 5}, {3, 5}}); + // Check for cycle using BFS method. + std::cout << CycleCheck::isCyclicBFS(g) << '\n'; + + // Check for cycle using DFS method. + std::cout << CycleCheck::isCyclicDFS(g) << '\n'; + return 0; +} diff --git a/graph/dfs.cpp b/graph/dfs.cpp new file mode 100644 index 000000000..2d38c8725 --- /dev/null +++ b/graph/dfs.cpp @@ -0,0 +1,26 @@ +#include +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); + } + } +} + +void DFS_(int graph[4][4], int 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; +} \ No newline at end of file diff --git a/graph/DFS_with_stack.cc b/graph/dfs_with_stack.cpp similarity index 74% rename from graph/DFS_with_stack.cc rename to graph/dfs_with_stack.cpp index cc67c7509..193f3f291 100644 --- a/graph/DFS_with_stack.cc +++ 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 similarity index 67% rename from graph/Dijkstra.cpp rename to graph/dijkstra.cpp index b3ee44c41..650f0cd51 100644 --- a/graph/Dijkstra.cpp +++ b/graph/dijkstra.cpp @@ -1,49 +1,46 @@ -#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; +int dij(vector> *v, int s, int *dis) { + priority_queue, vector>, + greater>> + pq; // source distance to zero. 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]) - { + for (vector>::iterator it = v[u].begin(); + 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)); - 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 2e66f131f..00c9d7ca0 100644 --- a/graph/kosaraju.cpp +++ b/graph/kosaraju.cpp @@ -1,134 +1,121 @@ -/* 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) -{ - for(int i=0;i"; - for(int j=0;j 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] << " "; + 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[]) -{ - vis[v]=true; - for(auto i=adj[v].begin();i!=adj[v].end();i++) - { - if(vis[*i]==false) - push_vertex(*i,st,vis,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++) { + 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[]) -{ - vis[v]=true; + * //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; // 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]={}; +int kosaraju(int V, vector adj[]) { + 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; +} +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'); +} +ll parent[mx], arr[mx], node, edge; +vector>> v; +void initial() { + 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; +} +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 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< 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) - { + 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,10 +90,9 @@ struct lca } }; -int main() -{ - int n; // number of nodes in the tree. - lca l(n); // will take the input in the format given +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 // 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 ee394d9f0..cbd6bc15c 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,15 +4,15 @@ * 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 { @@ -21,13 +21,13 @@ class Graph { 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 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) { @@ -49,9 +49,7 @@ class Graph { } public: - Graph() { - memset(residual_capacity, 0, sizeof(residual_capacity)); - } + 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) { @@ -71,7 +69,7 @@ class Graph { } 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; @@ -83,23 +81,21 @@ class Graph { 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])); + 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'; } } }; @@ -119,4 +115,3 @@ int main(void) { graph.print_flow_info(); return 0; } - diff --git a/graph/prim.cpp b/graph/prim.cpp index 2923b5b25..5cc70bd39 100644 --- a/graph/prim.cpp +++ b/graph/prim.cpp @@ -1,22 +1,22 @@ // 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) { // 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)); + Q.push(std::make_pair(0, x)); while (!Q.empty()) { // Select the edge with minimum weight p = Q.top(); @@ -40,19 +40,19 @@ 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) { 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 new file mode 100644 index 000000000..9e6c8917b --- /dev/null +++ b/graph/topological_sort.cpp @@ -0,0 +1,47 @@ +#include +#include +#include +using namespace std; + +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); +} + +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()); +} +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; +} diff --git a/graph/topological_sort_by_kahns_algo.cpp b/graph/topological_sort_by_kahns_algo.cpp index eda2a74bc..57ee01b23 100644 --- a/graph/topological_sort_by_kahns_algo.cpp +++ b/graph/topological_sort_by_kahns_algo.cpp @@ -1,8 +1,8 @@ #include #include #include -#include #include +#include int *topoSortKahn(int N, std::vector adj[]); @@ -13,7 +13,7 @@ int main() { return 0; int u, v; - std::vectorgraph[nodes]; + std::vector graph[nodes]; // create graph // example // 6 6 @@ -31,23 +31,23 @@ int main() { } } -int* topoSortKahn(int V, std::vector adj[]) { - std::vectorvis(V+1, false); - std::vectordeg(V+1, 0); +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; + 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()) { int cur = q.front(); diff --git a/greedy_algorithms/Knapsack.cpp b/greedy_algorithms/Knapsack.cpp deleted file mode 100644 index 2135bd1eb..000000000 --- a/greedy_algorithms/Knapsack.cpp +++ /dev/null @@ -1,92 +0,0 @@ -#include -using namespace std; - -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) -{ - 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); -} - -void quickSort(Item arr[], int low, int high) -{ - if (low < high) - { - - int p = partition(arr, low, 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; - } - - quickSort(itemArray, 0, n - 1); - - // 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; - } - } - - cout << "\nMax Profit : " << maxProfit; - - return 0; -} diff --git a/greedy_algorithms/Kruskals Minimum Spanning Tree.cpp b/greedy_algorithms/Kruskals Minimum Spanning Tree.cpp deleted file mode 100644 index 951d4a88a..000000000 --- a/greedy_algorithms/Kruskals Minimum Spanning Tree.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include -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}}; - -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"; - } -} - -int main() -{ - findMinimumEdge(); - return 0; -} diff --git a/greedy_algorithms/Prims Minimum Spanning Tree.cpp b/greedy_algorithms/Prims Minimum Spanning Tree.cpp deleted file mode 100644 index 769ca64e4..000000000 --- a/greedy_algorithms/Prims Minimum Spanning Tree.cpp +++ /dev/null @@ -1,79 +0,0 @@ -#include -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}}; - -struct mst -{ - 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; - } - - 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; - } - } - - 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; - } - } - } - } -} - -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() -{ - initilize(); - updateNear(); - show(); - return 0; -} diff --git a/greedy_algorithms/Dijkstra.cpp b/greedy_algorithms/dijkstra.cpp similarity index 53% rename from greedy_algorithms/Dijkstra.cpp rename to greedy_algorithms/dijkstra.cpp index 0c7fffc8c..e4450379c 100644 --- a/greedy_algorithms/Dijkstra.cpp +++ b/greedy_algorithms/dijkstra.cpp @@ -1,31 +1,25 @@ -#include #include +#include using namespace std; -//Wrapper class for storing a graph -class Graph -{ -public: +// Wrapper class for storing a graph +class Graph { + public: int vertexNum; int **edges; - //Constructs a graph with V vertices and E edges - Graph(const int V) - { - + // 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++) - { + 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,20 +27,16 @@ public: this->vertexNum = V; } - //Adds the given edge to the graph - void addEdge(int src, int dst, int weight) - { + // 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 -int minDistance(int mdist[], bool vset[], int V) -{ +// Utility function to find minimum distance vertex in mdist +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,12 +45,10 @@ int minDistance(int mdist[], bool vset[], int V) return minInd; } -//Utility function to print distances -void print(int dist[], int V) -{ +// Utility function to print distances +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 @@ -68,36 +56,32 @@ 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) -{ +// 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 - for (int i = 0; i < V; i++) - { + // Initialise mdist and vset. Set distance of source as zero + for (int i = 0; i < V; i++) { mdist[i] = INT_MAX; vset[i] = false; } mdist[src] = 0; - //iterate to find shortest path - for (int count = 0; count < V - 1; count++) - { + // iterate to find shortest path + for (int count = 0; count < V - 1; count++) { int u = minDistance(mdist, vset, V); vset[u] = true; - for (int v = 0; v < V; v++) - { - if (!vset[v] && graph.edges[u][v] && mdist[u] + graph.edges[u][v] < mdist[v]) - { + for (int v = 0; v < V; 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,9 +90,8 @@ void Dijkstra(Graph graph, int src) print(mdist, V); } -//Driver Function -int main() -{ +// Driver Function +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 253d8d0b5..21c8295f3 100644 --- a/greedy_algorithms/huffman.cpp +++ b/greedy_algorithms/huffman.cpp @@ -1,109 +1,100 @@ -// 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 new file mode 100644 index 000000000..74be4fee0 --- /dev/null +++ b/greedy_algorithms/knapsack.cpp @@ -0,0 +1,78 @@ +#include +using namespace std; + +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) { + 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); +} + +void quickSort(Item arr[], int low, int high) { + if (low < high) { + int p = partition(arr, low, 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; + } + + quickSort(itemArray, 0, n - 1); + + // 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; + } + } + + cout << "\nMax Profit : " << maxProfit; + + return 0; +} diff --git a/greedy_algorithms/kruskals_minimum_spanning_tree.cpp b/greedy_algorithms/kruskals_minimum_spanning_tree.cpp new file mode 100644 index 000000000..9f35e86ac --- /dev/null +++ b/greedy_algorithms/kruskals_minimum_spanning_tree.cpp @@ -0,0 +1,31 @@ +#include +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}}; + +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"; + } +} + +int main() { + findMinimumEdge(); + return 0; +} diff --git a/greedy_algorithms/prims_minimum_spanning_tree.cpp b/greedy_algorithms/prims_minimum_spanning_tree.cpp new file mode 100644 index 000000000..c804c176d --- /dev/null +++ b/greedy_algorithms/prims_minimum_spanning_tree.cpp @@ -0,0 +1,64 @@ +#include +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}}; + +struct mst { + 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; + } + + 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; + } + } + + 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; + } + } + } + } +} + +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() { + initilize(); + updateNear(); + show(); + return 0; +} diff --git a/hashing/Chaining.cpp b/hashing/Chaining.cpp deleted file mode 100644 index 55aa8961c..000000000 --- a/hashing/Chaining.cpp +++ /dev/null @@ -1,140 +0,0 @@ -#include -#include -using namespace std; - -struct Node -{ - int data; - struct Node *next; -} * head[100], *curr; - -void init() -{ - 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; - } -} - -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; - } - } -} - -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"; - } -} - -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; -} \ No newline at end of file diff --git a/hashing/chaining.cpp b/hashing/chaining.cpp new file mode 100644 index 000000000..6afd2d13b --- /dev/null +++ b/hashing/chaining.cpp @@ -0,0 +1,116 @@ +#include +#include +using namespace std; + +struct Node { + int data; + struct Node *next; +} * head[100], *curr; + +void init() { + 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; + } +} + +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; + } + } +} + +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"; + } +} + +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; +} \ No newline at end of file diff --git a/hashing/double_hash_hash_table.cpp b/hashing/double_hash_hash_table.cpp index 6030b7ff3..7ee2757de 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 @@ -48,8 +48,8 @@ int doubleHash(int key, bool searching) { int i = 0; Entry entry; do { - int index = static_cast(fabs((hash + - (i * otherHashFxn(key))))) % totalSize; + int index = static_cast(fabs((hash + (i * otherHashFxn(key))))) % + totalSize; entry = table[index]; if (searching) { if (entry.key == notPresent) { @@ -63,12 +63,17 @@ int doubleHash(int key, bool searching) { i++; } else { if (putProber(entry, key)) { - if (!rehashing) cout << "Spot found!" << endl; + 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) { @@ -89,7 +94,8 @@ bool putProber(Entry entry, int key) { // Looks for a matching key bool searchingProber(Entry entry, int key) { - if (entry.key == key) return true; + if (entry.key == key) + return true; return false; } @@ -131,12 +137,12 @@ void rehash() { // Checks for load factor here void add(int key) { - Entry * entry = new Entry(); + 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(); } } @@ -157,8 +163,8 @@ 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,8 +176,8 @@ 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: "; diff --git a/hashing/linear_probing_hash_table.cpp b/hashing/linear_probing_hash_table.cpp index b00eb8641..393504c1d 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 @@ -56,10 +56,12 @@ int linearProbe(int key, bool searching) { i++; } else { if (putProber(entry, key)) { - if (!rehashing) cout << "Spot found!" << endl; + 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) { @@ -80,7 +82,8 @@ bool putProber(Entry entry, int key) { // Looks for a matching key bool searchingProber(Entry entry, int key) { - if (entry.key == key) return true; + if (entry.key == key) + return true; return false; } @@ -122,12 +125,12 @@ void rehash() { // Adds entry using linear probing. Checks for load factor here void add(int key) { - Entry * entry = new Entry(); + 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(); } } @@ -148,8 +151,8 @@ 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: "; @@ -161,8 +164,8 @@ 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: "; diff --git a/hashing/quadratic_probing_hash_table.cpp b/hashing/quadratic_probing_hash_table.cpp index 44e2e3b9f..971c2182d 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 @@ -43,8 +43,8 @@ int quadraticProbe(int key, bool searching) { int i = 0; Entry entry; do { - int index = std::round(fabs((hash + - static_cast(std::round(std::pow(i, 2)))) % totalSize)); + int index = std::round(fabs( + (hash + static_cast(std::round(std::pow(i, 2)))) % totalSize)); entry = table[index]; if (searching) { if (entry.key == notPresent) { @@ -58,13 +58,16 @@ int quadraticProbe(int key, bool searching) { i++; } else { if (putProber(entry, key)) { - if (!rehashing) cout << "Spot found!" << endl; + 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; + cout << "Spot taken, looking at next (next index = " + << std::round(fabs((hash + static_cast(std::round( + std::pow(i + 1, 2)))) % + totalSize)) + << endl; } i++; } @@ -86,14 +89,16 @@ bool putProber(Entry entry, int key) { // Looks for a matching key bool searchingProber(Entry entry, int key) { - if (entry.key == key) return true; + if (entry.key == key) + return true; return false; } // Helper Entry find(int key) { int index = quadraticProbe(key, true); - if (index == notPresent) return Entry(); + if (index == notPresent) + return Entry(); return table[index]; } @@ -135,12 +140,12 @@ void rehash() { // Checks for load factor here void add(int key) { - Entry * entry = new Entry(); + 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(); } } @@ -161,8 +166,8 @@ 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: "; @@ -174,8 +179,8 @@ 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: "; diff --git a/machine_learning/CMakeLists.txt b/machine_learning/CMakeLists.txt new file mode 100644 index 000000000..e6d8a9af4 --- /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} ) diff --git a/machine_learning/adaline_learning.cpp b/machine_learning/adaline_learning.cpp new file mode 100644 index 000000000..1e25d3ba1 --- /dev/null +++ b/machine_learning/adaline_learning.cpp @@ -0,0 +1,351 @@ +/** + * \addtogroup machine_learning Machine Learning Algorithms + * @{ + * \file + * \brief [Adaptive Linear Neuron + * (ADALINE)](https://en.wikipedia.org/wiki/ADALINE) implementation + * + * \author [Krishna Vedala](https://github.com/kvedala) + * + * + * [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 +#include +#include +#include + +#define MAX_ITER 500 // INT_MAX ///< Maximum number of iterations to learn + +/** \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); + } + + 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); + } + + /** + * 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; + + 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); + + if (out != nullptr) // if out variable is provided + *out = y; + + 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 + + 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; + } + + 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 + * \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+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) + */ +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 + + // 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; + X[i] = {x0, x1}; + Y[i] = (x0 + 3. * x1) > -1 ? 1 : -1; + } + + std::cout << "------- Test 2 -------" << 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 + 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. + * 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) { + 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; + } +} + +/** Main function */ +int main(int argc, char **argv) { + std::srand(std::time(nullptr)); // initialize random number generator + + double eta = 0.1; // 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); + + std::cout << "Press ENTER to continue..." << std::endl; + std::cin.get(); + + test3(eta); + + return 0; +} diff --git a/machine_learning/kohonen_som_topology.cpp b/machine_learning/kohonen_som_topology.cpp new file mode 100644 index 000000000..25c58e260 --- /dev/null +++ b/machine_learning/kohonen_som_topology.cpp @@ -0,0 +1,595 @@ +/** + * \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::snprintf(msg, sizeof(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 = 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 +#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; +} diff --git a/machine_learning/kohonen_som_trace.cpp b/machine_learning/kohonen_som_trace.cpp new file mode 100644 index 000000000..273a2a57c --- /dev/null +++ b/machine_learning/kohonen_som_trace.cpp @@ -0,0 +1,474 @@ +/** + * \addtogroup machine_learning Machine Learning Algorithms + * @{ + * \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. + * + * \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 + * than with GCC on windows + * \see kohonen_som_topology.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_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; +} + +/** \namespace machine_learning + * \brief Machine learning algorithms + */ +namespace machine_learning { + +/** + * 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] 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--; + } +} + +} // namespace machine_learning + +/** @} */ + +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 + * \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 + */ +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/TheAlgorithms/C-Plus-Plus/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). + * \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) { + 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/TheAlgorithms/C-Plus-Plus/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 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) { + 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/TheAlgorithms/C-Plus-Plus/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 +} + +/** + * 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; +} diff --git a/math/CMakeLists.txt b/math/CMakeLists.txt new file mode 100644 index 000000000..2b70b2d31 --- /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/math/README.md b/math/README.md index 4ac39c878..d7b862f9f 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. diff --git a/math/binary_exponent.cpp b/math/binary_exponent.cpp index b4551da25..05e6f33f7 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$. + */ -/// Recursive function to calculate exponent in O(log(n)) using binary exponent. +#include + +/// 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 diff --git a/math/check_prime.cpp b/math/check_prime.cpp index e517d774e..ea4e6d52d 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; @@ -41,18 +43,19 @@ 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::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); + + return 0; } diff --git a/math/double_factorial.cpp b/math/double_factorial.cpp index 7b0d1d970..8e5ffcefa 100644 --- a/math/double_factorial.cpp +++ b/math/double_factorial.cpp @@ -1,28 +1,41 @@ -#include +/** + * @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 + * \f$n!!\f$ + */ + #include +#include -/* 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 !! */ - +/** 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 -= 2) { + if (i == 0 || i == 1) + return res; + res *= i; + } + return res; } -/* 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); } diff --git a/math/eulers_totient_function.cpp b/math/eulers_totient_function.cpp index 31ced5a51..8283ab045 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; @@ -30,12 +39,20 @@ int phiFunction(int n) { result -= result / i; } } - if (n > 1) result -= result / n; + if (n > 1) + result -= result / 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; } diff --git a/math/extended_euclid_algorithm.cpp b/math/extended_euclid_algorithm.cpp index 3db14802f..9fdc9692e 100644 --- a/math/extended_euclid_algorithm.cpp +++ b/math/extended_euclid_algorithm.cpp @@ -1,28 +1,96 @@ +/** + * @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. -int d, x, y; -void extendedEuclid(int A, int 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 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; +} + +/** + * 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 + 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); } } +/// Main function 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; + extendedEuclid_1(a, b, &gcd, &x, &y); + std::cout << gcd << " " << x << " " << y << std::endl; return 0; } diff --git a/math/factorial.cpp b/math/factorial.cpp index 8b13eb52d..353f0b16b 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) diff --git a/math/fast_power.cpp b/math/fast_power.cpp index 4f6e02081..c5621cd4e 100644 --- a/math/fast_power.cpp +++ b/math/fast_power.cpp @@ -1,29 +1,40 @@ -#include -#include -#include +/** + * @file + * @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 #include +#include +#include +#include +#include -/* - Program that computes a^b in O(logN) 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. -*/ - -double fast_power_recursive(int64_t a, int64_t b) { +/** + * algorithm implementation for \f$a^b\f$ + */ +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); + 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. - int64_t result; + double result; if ((b & 1) == 0) // case1 result = bottom * bottom; else // case2 @@ -31,49 +42,52 @@ double fast_power_recursive(int64_t a, int64_t b) { return result; } -/* +/** Same algorithm with little different formula. - It still calculates in O(logN) + It still calculates in \f$O(\log N)\f$ */ -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); double result = 1; while (b) { - if (b & 1) result = result * a; + if (b & 1) + result = result * a; a = a * a; b = b >> 1; } return result; } +/** + * Main function + */ 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; } diff --git a/math/fibonacci.cpp b/math/fibonacci.cpp index 1c07cd93f..e15cfc0cc 100644 --- a/math/fibonacci.cpp +++ b/math/fibonacci.cpp @@ -1,22 +1,30 @@ -#include +/** + * @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] + * + * @see fibonacci_large.cpp, fibonacci_fast.cpp, string_fibonacci.cpp + */ #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, ... */ - -int fibonacci(uint n) { +/** + * 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 */ 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); } +/// Main function int main() { int n; std::cin >> n; diff --git a/math/fibonacci_fast.cpp b/math/fibonacci_fast.cpp new file mode 100644 index 000000000..8fdb20058 --- /dev/null +++ b/math/fibonacci_fast.cpp @@ -0,0 +1,53 @@ +/** + * @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. + * + * \author [Krishna Vedala](https://github.com/kvedala) + * @see fibonacci_large.cpp, fibonacci.cpp, string_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 (f[n]) + return f[n]; + + 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); + 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) << std::endl; + } + return 0; +} diff --git a/math/fibonacci_large.cpp b/math/fibonacci_large.cpp new file mode 100644 index 000000000..e4f4e5eaf --- /dev/null +++ b/math/fibonacci_large.cpp @@ -0,0 +1,85 @@ +/** + * @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! + * + * \author [Krishna Vedala](https://github.com/kvedala) + * @see fibonacci.cpp, fibonacci_fast.cpp, string_fibonacci.cpp + */ + +#include +#include +#include + +#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); + + do { + large_number f2 = f1; + f1 += f0; + f0 = f2; + n--; + } while (n > 2); // since we start from 2 + + return f1; +} + +int main(int argc, char *argv[]) { + uint64_t N; + if (argc == 2) { + N = strtoull(argv[1], NULL, 10); + } else { + std::cout << "Enter N: "; + std::cin >> N; + } + + clock_t start_time = std::clock(); + large_number result = fib(N); + 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: " << std::scientific << time_taken << " s" + << std::endl; + + N = 5000; + 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; + + return 0; +} diff --git a/math/greatest_common_divisor_euclidean.cpp b/math/gcd_iterative_euclidean.cpp similarity index 79% rename from math/greatest_common_divisor_euclidean.cpp rename to math/gcd_iterative_euclidean.cpp index c4812e45b..2c0651ad7 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, gcd_of_n_numbers.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_of_n_numbers.cpp b/math/gcd_of_n_numbers.cpp new file mode 100644 index 000000000..92968ff12 --- /dev/null +++ b/math/gcd_of_n_numbers.cpp @@ -0,0 +1,41 @@ +/** + * @file + * @brief This program aims at calculating the GCD of n numbers by division + * method + * + * @see gcd_iterative_euclidean.cpp, gcd_recursive_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; + std::cout << "Enter the n numbers:" << std::endl; + for (i = 0; i < n; i++) std::cin >> a[i]; + + std::cout << "GCD of entered n numbers:" << gcd(a, n) << std::endl; + + delete[] a; + return 0; +} diff --git a/math/gcd_recursive_euclidean.cpp b/math/gcd_recursive_euclidean.cpp new file mode 100644 index 000000000..2a3d2183c --- /dev/null +++ b/math/gcd_recursive_euclidean.cpp @@ -0,0 +1,52 @@ +/** + * @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, gcd_of_n_numbers.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 5601c4be9..000000000 --- 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; -} diff --git a/math/large_factorial.cpp b/math/large_factorial.cpp new file mode 100644 index 000000000..20c677cdc --- /dev/null +++ b/math/large_factorial.cpp @@ -0,0 +1,118 @@ +/** + * @file + * @brief Compute factorial of any arbitratily large number/ + * + * \author [Krishna Vedala](https://github.com/kvedala) + * @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; + large_number result; + 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()) { + 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)) { + std::cerr << i << "^th digit mismatch! " << known_reslt[i] + << " != " << result.digit_char(i) << std::endl; + return false; + } + } + + std::cout << "Passed!" << std::endl; + 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; + large_number result; + for (i = 2; i <= number; i++) /* Multiply every number from 2 thru N */ + result *= i; + + const char *known_reslt = + "9332621544394415268169923885626670049071596826438162146859296389521759" + "9993229915608941463976156518286253697920827223758251185210916864000000" + "000000000000000000"; + + /* check 1 */ + 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)) { + std::cerr << i << "^th digit mismatch! " << known_reslt[i] + << " != " << result.digit_char(i) << std::endl; + return false; + } + } + + std::cout << "Passed!" << std::endl; + return true; +} + +/** + * Main program + **/ +int main(int argc, char *argv[]) { + int number, i; + + if (argc == 2) { + number = atoi(argv[1]); + } else { + std::cout << "Enter the value of n(n starts from 0 ): "; + std::cin >> number; + } + + large_number result; + + std::clock_t start_time = std::clock(); + for (i = 2; i <= number; i++) /* Multiply every number from 2 thru N */ + result *= i; + 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(); + result.test(); + + return 0; +} diff --git a/math/large_number.h b/math/large_number.h new file mode 100644 index 000000000..bffb764d0 --- /dev/null +++ b/math/large_number.h @@ -0,0 +1,288 @@ +/** + * @file + * @brief Library to perform arithmatic operations on arbitrarily large + * numbers. + * \author [Krishna Vedala](https://github.com/kvedala) + */ + +#ifndef MATH_LARGE_NUMBER_H_ +#define MATH_LARGE_NUMBER_H_ +#include +#include +#include +#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: + /**< 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(int n) { + int carry = n; + do { + add_digit(carry % 10); + carry /= 10; + } while (carry != 0); + } + + /**< initializer from another large_number */ + large_number(const large_number &a) : _digits(a._digits) {} + + /**< initializer from a vector */ + 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--) { + 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; + } + + /** + * 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 << static_cast(a[i - 1]); + return out; + } + + /** + * 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 bool operator!=(large_number const &a, large_number const &b) { + return !(a == b); + } + + /** + * operator overload to increment (prefix) + **/ + large_number &operator++() { + (*this) += 1; + return *this; + } + + /** + * operator overload to increment (postfix) + **/ + large_number &operator++(int) { + static large_number tmp(_digits); + ++(*this); + return tmp; + } + + /** + * 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) { + static large_number c = a; + c += b; + return c; + } + + /** + * 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; + } + + /** + * 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; + 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; + } + } + + std::vector + _digits; /**< where individual digits are stored */ +}; + +#endif // MATH_LARGE_NUMBER_H_ diff --git a/math/modular_inverse_fermat_little_theorem.cpp b/math/modular_inverse_fermat_little_theorem.cpp index 965c21298..7550e14bf 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; diff --git a/math/number_of_positive_divisors.cpp b/math/number_of_positive_divisors.cpp index 48ab63c36..f157f7b41 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; diff --git a/math/power_for_huge_numbers.cpp b/math/power_for_huge_numbers.cpp index bf9374228..301767d66 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) -{ +/** 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; + } - //printing value "1" for power = 0 - if (n == 0) - { - 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; + std::cout << "Enter base "; + std::cin >> base; + std::cout << "Enter exponent "; + std::cin >> exponent; + power(base, exponent); + return 0; } diff --git a/math/prime_factorization.cpp b/math/prime_factorization.cpp index 822cad332..001c2c3c3 100644 --- a/math/prime_factorization.cpp +++ b/math/prime_factorization.cpp @@ -1,80 +1,77 @@ +/** + * @file + * @brief Prime factorization of positive integers + */ +#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) -{ +/** list of prime numbers */ +std::vector prime_numbers; + +/** list of prime factor-pairs */ +std::vector> factors; + +/** Calculating prime number upto a given range + */ +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++) - { + 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) -{ - +/** Prime factorization of a number */ +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)); + factors.push_back(std::make_pair(prime_numbers[i], count)); } } -/* - I added a simple UI. -*/ -int main() -{ +/** Main program */ +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); prime_factorization(num); // Prime factors with their powers in the given number in new line - for (auto it : factors) - { - cout << it.first << " " << it.second << endl; + for (auto it : factors) { + std::cout << it.first << " " << it.second << std::endl; } return 0; diff --git a/math/prime_numbers.cpp b/math/prime_numbers.cpp index 7264ff528..4dd54f136 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_10^8.cpp b/math/primes_up_to_billion.cpp similarity index 59% rename from math/primes_up_to_10^8.cpp rename to math/primes_up_to_billion.cpp index db9b56cab..4fb79a15e 100644 --- a/math/primes_up_to_10^8.cpp +++ b/math/primes_up_to_billion.cpp @@ -1,12 +1,19 @@ -#include +/** + * @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 - 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 +22,7 @@ void Sieve(int64_t n) { } } - +/** Main function */ int main() { Sieve(100000000); int64_t n; @@ -24,4 +31,6 @@ int main() { std::cout << "YES\n"; else std::cout << "NO\n"; + + return 0; } diff --git a/math/realtime_stats.cpp b/math/realtime_stats.cpp new file mode 100644 index 000000000..5f353ac4d --- /dev/null +++ b/math/realtime_stats.cpp @@ -0,0 +1,193 @@ +/** + * \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. + * \author [Krishna Vedala](https://github.com/kvedala) + */ +#include +#include +#include + +/** + * \namespace statistics + * \brief Statistical algorithms + */ +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. + */ +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) + */ +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 + */ +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; + + 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; +} diff --git a/math/sieve_of_eratosthenes.cpp b/math/sieve_of_eratosthenes.cpp index e600e480d..d8fa70531 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; } diff --git a/math/sqrt_double.cpp b/math/sqrt_double.cpp index 5a0fd1c88..c4beec9d8 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 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 + * 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); } diff --git a/math/string_fibonacci.cpp b/math/string_fibonacci.cpp new file mode 100644 index 000000000..eb9b6d7e1 --- /dev/null +++ b/math/string_fibonacci.cpp @@ -0,0 +1,89 @@ +/** + * @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 +#ifdef _MSC_VER +#include // use this for MS Visual C +#else +#include // otherwise +#endif + +/** + * 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 (a.length() < b.length()) { + a = "0" + a; + } + + // fills up with zeros + 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 = static_cast(((a[i] - 48) + (b[i] - 48)) + 48 + carry); + if (val > 57) { + carry = 1; + val -= 10; + } else { + carry = 0; + } + temp = val + temp; + } + + // processes the carry flag + if (carry == 1) { + temp = "1" + temp; + } + + // removes leading zeros. + while (temp[0] == '0' && temp.length() > 1) { + temp = temp.substr(1); + } + + return temp; +} + +/** Fibonacci iterator + * \param [in] n n^th Fibonacci number + */ +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++) { + tmp = add(fibMinus1, fibMinus2); + fibMinus2 = fibMinus1; + fibMinus1 = tmp; + } + std::cout << fibMinus2; +} + +/** main function */ +int main() { + int 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; +} diff --git a/numerical_methods/CMakeLists.txt b/numerical_methods/CMakeLists.txt new file mode 100644 index 000000000..fc4c343de --- /dev/null +++ b/numerical_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/numerical_methods") + +endforeach( testsourcefile ${APP_SOURCES} ) diff --git a/numerical_methods/bisection_method.cpp b/numerical_methods/bisection_method.cpp new file mode 100644 index 000000000..c93c529d2 --- /dev/null +++ b/numerical_methods/bisection_method.cpp @@ -0,0 +1,75 @@ +/** + * \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 + +#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() { + double a = -1, b = 1, x, z; + 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; + } + } + + std::cout << "\nFirst initial: " << a; + std::cout << "\nSecond initial: " << b; + + // start iterations + 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) { + a = x; + } else { + b = x; + } + + if (std::abs(z) < EPSILON) // stoping criteria + break; + } + + std::cout << "\n\nRoot: " << x << "\t\tSteps: " << i << std::endl; + return 0; +} diff --git a/numerical_methods/durand_kerner_roots.cpp b/numerical_methods/durand_kerner_roots.cpp new file mode 100644 index 000000000..9bf0619b8 --- /dev/null +++ b/numerical_methods/durand_kerner_roots.cpp @@ -0,0 +1,339 @@ +/** + * @file + * \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 + * + * 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 + * ``` + * 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 + */ + +#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] 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 target teams distribute 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) { +#define MAX_BUFF_SIZE 50 + static char msg[MAX_BUFF_SIZE]; + + std::snprintf(msg, MAX_BUFF_SIZE, "% 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; +} + +/** + * 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) { + long double tol_condition = 1; + uint32_t iter = 0; + int n; + 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 < roots->size(); n++) log_file << "root_" << n << ","; + + log_file << "avg. correction"; + log_file << "\n0,"; + for (n = 0; n < roots->size(); n++) + log_file << complex_str((*roots)[n]) << ","; + } + + bool break_loop = false; + while (!check_termination(tol_condition) && iter < INT16_MAX && + !break_loop) { + tol_condition = 0; + iter++; + break_loop = false; + + if (log_file.is_open()) + log_file << "\n" << iter << ","; + +#ifdef _OPENMP +#pragma omp parallel for shared(break_loop, tol_condition) +#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; + for (int i = 0; i < roots->size(); i++) + if (i != n) + denominator *= (*roots)[n] - (*roots)[i]; + + 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) << "\n"; + // return std::pair(iter, tol_condition); + break_loop = true; + } + + (*roots)[n] -= delta; + +#ifdef _OPENMP +#pragma omp critical +#endif + tol_condition = std::max(tol_condition, std::abs(std::abs(delta))); + } + // 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"; + for (n = 0; n < roots->size(); 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); +} + +/** + * 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(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++) { + // 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(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 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 + * ```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) { + /* 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 + std::cout << "Please pass the coefficients of the polynomial as " + "commandline " + "arguments.\n"; + return 0; + } + + int n, degree = argc - 1; // detected polynomial degree + std::valarray coeffs(degree); // create coefficiencts array + + // 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; + } + } + + // numerical errors less when the first coefficient is "1" + // hence, we normalize the first coefficient + { + double tmp = coeffs[0]; + coeffs /= tmp; + } + + clock_t end_time, start_time = clock(); + auto result = durand_kerner_algo(coeffs, &s0, true); + end_time = clock(); + + 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: " << result.second << "\n"; + std::cout << "Time taken: " + << static_cast(end_time - start_time) / CLOCKS_PER_SEC + << " sec\n"; + + return 0; +} diff --git a/numerical_methods/false_position.cpp b/numerical_methods/false_position.cpp new file mode 100644 index 000000000..aebd154bb --- /dev/null +++ b/numerical_methods/false_position.cpp @@ -0,0 +1,74 @@ +/** + * \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 + +#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() { + 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; + } + } + + std::cout << "\nFirst initial: " << a; + std::cout << "\nSecond initial: " << b; + + 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 (std::abs(z) < EPSILON) { // stoping criteria + break; + } + } + + std::cout << "\n\nRoot: " << c << "\t\tSteps: " << i << std::endl; + return 0; +} diff --git a/numerical_methods/gaussian_elimination.cpp b/numerical_methods/gaussian_elimination.cpp new file mode 100644 index 000000000..60b5648ec --- /dev/null +++ b/numerical_methods/gaussian_elimination.cpp @@ -0,0 +1,76 @@ +/** + * \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]; + } + + // 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++) { + 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++) { + double a = (mat[i + 1][step] / mat[step][step]); + + for (j = step; j <= mat_size; j++) + mat[i + 1][j] = mat[i + 1][j] - (a * mat[step][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]; + std::cout << mat[i][j] << " "; + } + std::cout << std::endl; + } + 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--) { + x[i][j] = x[j][j] * x[i][j]; + sum = x[i][j] + sum; + } + if (x[i][i] == 0) + x[i][i] = 0; + else + x[i][i] = (x[i][mat_size] - sum) / (x[i][i]); + + 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; +} diff --git a/numerical_methods/lu_decompose.cpp b/numerical_methods/lu_decompose.cpp new file mode 100644 index 000000000..a0a2d00ab --- /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(std::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; +} diff --git a/numerical_methods/newton_raphson_method.cpp b/numerical_methods/newton_raphson_method.cpp new file mode 100644 index 000000000..d086123ca --- /dev/null +++ b/numerical_methods/newton_raphson_method.cpp @@ -0,0 +1,59 @@ +/** + * \file + * \brief Solve the equation \f$f(x)=0\f$ using [Newton-Raphson + * 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 +#include +#include +#include + +#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 +} + +/** 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() { + std::srand(std::time(nullptr)); // initialize randomizer + + double z, c = std::rand() % 100, m, n; + int i; + + std::cout << "\nInitial approximation: " << c; + + // start iterations + for (i = 0; i < MAX_ITERATIONS; i++) { + m = eq(c); + n = eq_der(c); + + z = c - (m / n); + c = z; + + if (std::abs(m) < EPSILON) // stoping criteria + break; + } + + std::cout << "\n\nRoot: " << z << "\t\tSteps: " << i << std::endl; + return 0; +} diff --git a/numerical_methods/ode_forward_euler.cpp b/numerical_methods/ode_forward_euler.cpp new file mode 100644 index 000000000..a4455c57a --- /dev/null +++ b/numerical_methods/ode_forward_euler.cpp @@ -0,0 +1,210 @@ +/** + * \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 + * 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. + * @{ + */ +/** + * @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; +} diff --git a/numerical_methods/ode_midpoint_euler.cpp b/numerical_methods/ode_midpoint_euler.cpp new file mode 100644 index 000000000..50cf4e4c6 --- /dev/null +++ b/numerical_methods/ode_midpoint_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 + * [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_forward_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\, 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$ + * @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); + 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; +} diff --git a/numerical_methods/ode_semi_implicit_euler.cpp b/numerical_methods/ode_semi_implicit_euler.cpp new file mode 100644 index 000000000..01904ac16 --- /dev/null +++ b/numerical_methods/ode_semi_implicit_euler.cpp @@ -0,0 +1,211 @@ +/** + * \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); // update dy once + y[0][0] += dx * dy[0][0]; // update y0 + problem(x, y, dy); // update dy once more + + dy[0][0] = 0.f; // ignore y0 + y[0] += dy[0] * dx; // update remaining using new dy +} + +/** + * @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; +} diff --git a/numerical_methods/ordinary_least_squares_regressor.cpp b/numerical_methods/ordinary_least_squares_regressor.cpp new file mode 100644 index 000000000..43979d0ea --- /dev/null +++ b/numerical_methods/ordinary_least_squares_regressor.cpp @@ -0,0 +1,406 @@ +/** + * @file + * \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. + */ +#include // for print formatting +#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; + } + + 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 = ' '; + + for (size_t row = 0; row < v.size(); row++) + out << std::left << std::setw(width) << std::setfill(separator) + << v[row]; + + 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; +} + +/** + * 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(); + + 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]; + } + result[row] = v; + } + + 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(); + + 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++) { + result[row] = static_cast(0); + for (size_t j = 0; j < B.size(); j++) result[row] += A[row][j] * B[j]; + } + + 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(); + + std::vector result(N_A); + + for (size_t row = 0; row < N_A; row++) { + result[row] += A[row] * static_cast(scalar); + } + + 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(); + + std::vector result(N_A); + + for (size_t row = 0; row < N_A; row++) + result[row] = A[row] * static_cast(scalar); + + 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; +} + +/** + * 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(); + + std::vector result(N); + + 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]; + + 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(); + + std::vector result(N); + + 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]; + + return result; +} + +/** + * 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]; + } + + 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; +} + +/** + * 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; +} + +/** + * 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 + */ +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; +} + +/** + * Given data and OLS model coeffficients, predict + * 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 beta 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; +} + +/** + * 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; +} diff --git a/numerical_methods/qr_decompose.h b/numerical_methods/qr_decompose.h new file mode 100644 index 000000000..c9c369144 --- /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 000000000..237a5c946 --- /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; +} diff --git a/numerical_methods/qr_eigen_values.cpp b/numerical_methods/qr_eigen_values.cpp new file mode 100644 index 000000000..581e02e4e --- /dev/null +++ b/numerical_methods/qr_eigen_values.cpp @@ -0,0 +1,284 @@ +/** + * @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(); + +#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 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`) + */ +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; + } + + // initialize random number generator + std::srand(std::time(nullptr)); + + 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; +} diff --git a/numerical_methods/successive_approximation.cpp b/numerical_methods/successive_approximation.cpp new file mode 100644 index 000000000..351382f24 --- /dev/null +++ b/numerical_methods/successive_approximation.cpp @@ -0,0 +1,40 @@ +/** + * \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; + + 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/operations_on_datastructures/Array Left Rotation.cpp b/operations_on_datastructures/Array Left Rotation.cpp deleted file mode 100644 index 9eb5d4e50..000000000 --- a/operations_on_datastructures/Array Left Rotation.cpp +++ /dev/null @@ -1,39 +0,0 @@ -#include -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; -} diff --git a/operations_on_datastructures/Circular Linked List.cpp b/operations_on_datastructures/Circular Linked List.cpp deleted file mode 100644 index d360f6cd7..000000000 --- a/operations_on_datastructures/Circular Linked List.cpp +++ /dev/null @@ -1,114 +0,0 @@ -#include -using namespace std; - -struct node -{ - int val; - node *next; -}; - -node *start; - -void insert(int x) -{ - 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; - } -} - -void remove(int x) -{ - 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"; - } -} - -void show() -{ - 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); - - return 0; -} diff --git a/operations_on_datastructures/Circular Queue Using Array.cpp b/operations_on_datastructures/Circular Queue Using Array.cpp deleted file mode 100644 index 36d7e22c3..000000000 --- a/operations_on_datastructures/Circular Queue Using Array.cpp +++ /dev/null @@ -1,74 +0,0 @@ -#include -using namespace std; - -int queue[10]; -int front = 0; -int rear = 0; -int count = 0; - -void Enque(int x) -{ - if (count == 10) - { - cout << "\nOverflow"; - } - else - { - queue[rear] = x; - rear = (rear + 1) % 10; - count++; - } -} - -void Deque() -{ - if (front == rear) - { - cout << "\nUnderflow"; - } - - 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"; - } -} - -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); - - return 0; -} diff --git a/operations_on_datastructures/Intersection_of_2_arrays.cpp b/operations_on_datastructures/Intersection_of_2_arrays.cpp deleted file mode 100644 index 05652811f..000000000 --- a/operations_on_datastructures/Intersection_of_2_arrays.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#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 - { - cout << a[i++] << " "; - j++; - } - } - 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 deleted file mode 100644 index 0908080cc..000000000 --- a/operations_on_datastructures/Reverse a Linked List using Recusion.cpp +++ /dev/null @@ -1,76 +0,0 @@ -#include -using namespace std; - -struct node -{ - 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; - } -} - -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; - } -} - -void show() -{ - 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); - - reverse(start, start->next); - - show(); - - return 0; -} diff --git a/operations_on_datastructures/Union_of_2_arrays.cpp b/operations_on_datastructures/Union_of_2_arrays.cpp deleted file mode 100644 index aaaeb8378..000000000 --- a/operations_on_datastructures/Union_of_2_arrays.cpp +++ /dev/null @@ -1,34 +0,0 @@ -#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 - { - cout << a[i++]; - j++; - } - } - while (i < m) - cout << a[i++] << " "; - while (j < n) - cout << b[j++] << " "; - return 0; -} diff --git a/operations_on_datastructures/array_left_rotation.cpp b/operations_on_datastructures/array_left_rotation.cpp new file mode 100644 index 000000000..7b8f7f279 --- /dev/null +++ b/operations_on_datastructures/array_left_rotation.cpp @@ -0,0 +1,31 @@ +#include +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; +} diff --git a/operations_on_datastructures/Array Right Rotation.cpp b/operations_on_datastructures/array_right_rotation.cpp similarity index 62% rename from operations_on_datastructures/Array Right Rotation.cpp rename to operations_on_datastructures/array_right_rotation.cpp index 81875766c..8b01a2003 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; @@ -9,27 +8,20 @@ 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++) - { + 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 new file mode 100644 index 000000000..1119bb5e7 --- /dev/null +++ b/operations_on_datastructures/circular_linked_list.cpp @@ -0,0 +1,97 @@ +#include +using namespace std; + +struct node { + int val; + node *next; +}; + +node *start; + +void insert(int x) { + 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; + } +} + +void remove(int x) { + 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"; + } +} + +void show() { + 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); + + return 0; +} diff --git a/operations_on_datastructures/circular_queue_using_array.cpp b/operations_on_datastructures/circular_queue_using_array.cpp new file mode 100644 index 000000000..e0e049611 --- /dev/null +++ b/operations_on_datastructures/circular_queue_using_array.cpp @@ -0,0 +1,57 @@ +#include +using namespace std; + +int queue[10]; +int front = 0; +int rear = 0; +int count = 0; + +void Enque(int x) { + if (count == 10) { + cout << "\nOverflow"; + } else { + queue[rear] = x; + rear = (rear + 1) % 10; + count++; + } +} + +void Deque() { + if (front == rear) { + cout << "\nUnderflow"; + } + + 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"; + } +} + +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); + + return 0; +} diff --git a/operations_on_datastructures/intersection_of_2_arrays.cpp b/operations_on_datastructures/intersection_of_2_arrays.cpp new file mode 100644 index 000000000..8a3b27edf --- /dev/null +++ b/operations_on_datastructures/intersection_of_2_arrays.cpp @@ -0,0 +1,26 @@ +#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 { + cout << a[i++] << " "; + j++; + } + } + 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 new file mode 100644 index 000000000..b9540d951 --- /dev/null +++ b/operations_on_datastructures/reverse_a_linked_list_using_recusion.cpp @@ -0,0 +1,63 @@ +#include +using namespace std; + +struct node { + 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; + } +} + +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; + } +} + +void show() { + 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); + + reverse(start, start->next); + + show(); + + return 0; +} diff --git a/operations_on_datastructures/selectionSortLinkedList.cpp b/operations_on_datastructures/selectionSortLinkedList.cpp deleted file mode 100644 index 52363ceff..000000000 --- a/operations_on_datastructures/selectionSortLinkedList.cpp +++ /dev/null @@ -1,159 +0,0 @@ -#include -using namespace std; - -//node defined -class node -{ -public: - int data; - node *link; - node(int d) - { - data = d; - link = NULL; - } -}; - -//printing the linked list -void print(node *head) -{ - node *current = head; - while (current != NULL) - { - cout << current->data << " "; - current = current->link; - } - cout << endl; -} - -//creating the linked list with 'n' nodes -node *createlist(int n) -{ - node *head = NULL; - node *t = NULL; - for (int i = 0; i < n; i++) - { - node *temp = NULL; - int num; - cin >> num; - temp = new node(num); - if (head == NULL) - { - head = temp; - t = temp; - continue; - } - if (t->link == NULL) - t->link = temp; - t = temp; - } - return head; -} - -//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 - - 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 - - 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 (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 - { - //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 - { - //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 - { - temp->link = current; - previous->link = current->link; - current->link = min; - 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 - { - 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 - temp = min; - min = min->link; - previous = min; - current = min->link; - } -} - -// Test cases: - -// enter the no. of nodes : 5 -// 8 9 3 1 4 -// original list is : 8 9 3 1 4 -// sorted list is : 1 3 4 8 9 - -// enter the no. of nodes : 3 -// -1 -2 -3 -// original list is : -1 -2 -3 -// sorted list is : -3 -2 -1 - -// enter the no. of nodes : 8 -// 8 7 6 5 4 3 2 1 -// original list is : 8 7 6 5 4 3 2 1 -// sorted list is : 1 2 3 4 5 6 7 8 - -// enter the no. of nodes : 6 -// 5 3 4 1 -2 -4 -// original list is : 5 3 4 1 -2 -4 -// sorted list is : -4 -2 1 3 4 5 - -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 - cin >> n; - if (n == 0) - return 0; - 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 - cout << "sorted list is : "; - print(head); //printing the sorted linked list - return 0; -} \ No newline at end of file diff --git a/operations_on_datastructures/selectionsortlinkedlist.cpp b/operations_on_datastructures/selectionsortlinkedlist.cpp new file mode 100644 index 000000000..0e8e80def --- /dev/null +++ b/operations_on_datastructures/selectionsortlinkedlist.cpp @@ -0,0 +1,172 @@ +#include +using namespace std; + +// node defined +class node { + public: + int data; + node *link; + node(int d) { + data = d; + link = NULL; + } +}; + +// printing the linked list +void print(node *head) { + node *current = head; + while (current != NULL) { + cout << current->data << " "; + current = current->link; + } + cout << endl; +} + +// creating the linked list with 'n' nodes +node *createlist(int n) { + node *head = NULL; + node *t = NULL; + for (int i = 0; i < n; i++) { + node *temp = NULL; + int num; + cin >> num; + temp = new node(num); + if (head == NULL) { + head = temp; + t = temp; + continue; + } + if (t->link == NULL) + t->link = temp; + t = temp; + } + return head; +} + +// 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 + + 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 + + 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 (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 + { + // 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 + { + // 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 + { + temp->link = current; + previous->link = current->link; + current->link = min; + 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 + { + 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 + temp = min; + min = min->link; + previous = min; + current = min->link; + } +} + +// Test cases: + +// enter the no. of nodes : 5 +// 8 9 3 1 4 +// original list is : 8 9 3 1 4 +// sorted list is : 1 3 4 8 9 + +// enter the no. of nodes : 3 +// -1 -2 -3 +// original list is : -1 -2 -3 +// sorted list is : -3 -2 -1 + +// enter the no. of nodes : 8 +// 8 7 6 5 4 3 2 1 +// original list is : 8 7 6 5 4 3 2 1 +// sorted list is : 1 2 3 4 5 6 7 8 + +// enter the no. of nodes : 6 +// 5 3 4 1 -2 -4 +// original list is : 5 3 4 1 -2 -4 +// sorted list is : -4 -2 1 3 4 5 + +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 + cin >> n; + if (n == 0) + return 0; + 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 + cout << "sorted list is : "; + 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 new file mode 100644 index 000000000..cdacf1d2e --- /dev/null +++ b/operations_on_datastructures/union_of_2_arrays.cpp @@ -0,0 +1,27 @@ +#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 { + cout << a[i++]; + j++; + } + } + 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 deleted file mode 100644 index f31038aad..000000000 --- a/others/Buzz_number.cpp +++ /dev/null @@ -1,17 +0,0 @@ -//A buzz number is a number that is either divisble 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; -} diff --git a/others/CMakeLists.txt b/others/CMakeLists.txt new file mode 100644 index 000000000..f049b5f2d --- /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} ) diff --git a/others/Decimal To Binary.cpp b/others/Decimal To Binary.cpp deleted file mode 100644 index 4e2119ebc..000000000 --- a/others/Decimal To Binary.cpp +++ /dev/null @@ -1,25 +0,0 @@ -// This function convert decimal to binary number -// -#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; -} diff --git a/others/Decimal To Hexadecimal .cpp b/others/Decimal To Hexadecimal .cpp deleted file mode 100644 index 705f21ba4..000000000 --- a/others/Decimal To Hexadecimal .cpp +++ /dev/null @@ -1,28 +0,0 @@ -#include - -using namespace std; - -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 - - while (valueToConvert > 15) - { //Dec to Hex Algorithm - hexArray[i++] = valueToConvert % 16; //Gets remainder - valueToConvert /= 16; - } - hexArray[i] = valueToConvert; //Gets last value - - cout << "Hex Value: "; - while (i >= 0) - cout << HexValues[hexArray[i--]]; - - cout << endl; - return 0; -} diff --git a/others/GCD_of_n_numbers.cpp b/others/GCD_of_n_numbers.cpp deleted file mode 100644 index 8158052f8..000000000 --- a/others/GCD_of_n_numbers.cpp +++ /dev/null @@ -1,23 +0,0 @@ -//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; -} diff --git a/others/Palindromeofnumber.cpp b/others/Palindromeofnumber.cpp deleted file mode 100644 index 647803997..000000000 --- a/others/Palindromeofnumber.cpp +++ /dev/null @@ -1,23 +0,0 @@ -#include -#include - -using namespace std; - -int main() -{ - int num; - cout << "Enter number = "; - cin >> num; - - string s1 = to_string(num); - string s2 = s1; - - reverse(s1.begin(), s1.end()); - - if (s1 == s2) - cout << "true"; - else - cout << "false"; - - return 0; -} diff --git a/others/Paranthesis Matching.cpp b/others/Paranthesis Matching.cpp deleted file mode 100644 index d2bb4d39c..000000000 --- a/others/Paranthesis Matching.cpp +++ /dev/null @@ -1,76 +0,0 @@ -#include -#include - -using namespace std; - -#define MAX 100 - -// -------------- stack -------------- - -char stack[MAX]; -int top = -1; - -void push(char ch) -{ - stack[++top] = ch; -} - -char pop() -{ - return stack[top--]; -} - -// -------------- end stack ----------- - -char opening(char ch) -{ - switch (ch) - { - case '}': - return '{'; - case ']': - return '['; - case ')': - return '('; - case '>': - return '<'; - } -} - -int main() -{ - - string exp; - int valid = 1, i = 0; - cout << "Enter The Expression : "; - 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++; - } - - // makes sure the stack is empty after processsing (above) - if (valid == 1 && top == -1) - { - cout << "\nCorrect Expression"; - } - else - { - cout << "\nWrong Expression"; - } - - return 0; -} diff --git a/others/Primality Test.cpp b/others/Primality Test.cpp deleted file mode 100644 index ce8fc1706..000000000 --- a/others/Primality Test.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#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. - -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; -} - -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; - - return 0; -} diff --git a/others/Sparse matrix.cpp b/others/Sparse matrix.cpp deleted file mode 100644 index 1861163f1..000000000 --- a/others/Sparse matrix.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/*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.*/ -#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"; - - // 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]; - } - } - - // 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"; -} diff --git a/others/Strassen Matrix Multiplication.cpp b/others/Strassen Matrix Multiplication.cpp deleted file mode 100644 index 85b627763..000000000 --- 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 diff --git a/others/String Fibonacci.cpp b/others/String Fibonacci.cpp deleted file mode 100644 index e5475eec9..000000000 --- a/others/String Fibonacci.cpp +++ /dev/null @@ -1,83 +0,0 @@ -//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 - -#include -#include - -using namespace std; - -string add(string a, string b) -{ - string temp = ""; - - // carry flag - int carry = 0; - - // fills up with zeros - while ((int)a.length() < (int)b.length()) - { - a = "0" + a; - } - - // fills up with zeros - 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--) - { - char val = (char)(((a[i] - 48) + (b[i] - 48)) + 48 + carry); - if (val > 57) - { - carry = 1; - val -= 10; - } - else - { - carry = 0; - } - temp = val + temp; - } - - // processes the carry flag - if (carry == 1) - { - temp = "1" + temp; - } - - // removes leading zeros. - 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++) - { - tmp = add(fibMinus1, fibMinus2); - fibMinus2 = fibMinus1; - fibMinus1 = tmp; - } - cout << fibMinus2; -} - -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"; - fib_Accurate(n); - - return 0; -} diff --git a/others/Tower of Hanoi.cpp b/others/Tower of Hanoi.cpp deleted file mode 100644 index 5783d6a98..000000000 --- a/others/Tower of Hanoi.cpp +++ /dev/null @@ -1,73 +0,0 @@ -#include -using namespace std; - -struct tower -{ - int values[10]; - 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"; - } -} - -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); - } -} - -int main() -{ - F.top = 0; - U.top = 0; - T.top = 0; - - int no; - - cout << "\nEnter number of discs : "; - cin >> no; - - for (int i = no; i > 0; i--) - { - F.values[F.top++] = i; - }; - - show(); - TH(no, F, U, T); - - return 0; -} diff --git a/others/buzz_number.cpp b/others/buzz_number.cpp new file mode 100644 index 000000000..ed9fc5f28 --- /dev/null +++ b/others/buzz_number.cpp @@ -0,0 +1,20 @@ +/** + * @file + * @brief A buzz number is a number that is either divisible by 7 or has last + * digit as 7. + */ +#include + +/** 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; +} diff --git a/others/decimal_to_binary.cpp b/others/decimal_to_binary.cpp new file mode 100644 index 000000000..11ce064a5 --- /dev/null +++ b/others/decimal_to_binary.cpp @@ -0,0 +1,55 @@ +/** + * @file + * @brief Function to convert decimal number to binary representation + */ +#include + +/** + * 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; +} diff --git a/others/decimal_to_hexadecimal.cpp b/others/decimal_to_hexadecimal.cpp new file mode 100644 index 000000000..a3e544f49 --- /dev/null +++ b/others/decimal_to_hexadecimal.cpp @@ -0,0 +1,34 @@ +/** + * @file + * @brief Convert decimal number to hexadecimal representation + */ + +#include + +/** + * 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"; + + 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; + // valueToConvert >>= 4; // This will divide by 2^4=16 and is faster + } + hexArray[i] = valueToConvert; // Gets last value + + std::cout << "Hex Value: "; + while (i >= 0) std::cout << HexValues[hexArray[i--]]; + + std::cout << std::endl; + return 0; +} diff --git a/others/Decimal to Roman Numeral.cpp b/others/decimal_to_roman_numeral.cpp similarity index 54% rename from others/Decimal to Roman Numeral.cpp rename to others/decimal_to_roman_numeral.cpp index 0372e8003..ad4aa32c5 100644 --- a/others/Decimal to Roman Numeral.cpp +++ b/others/decimal_to_roman_numeral.cpp @@ -1,31 +1,33 @@ -//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) -{ +/** 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 string("v") + fill('i', n - 5); + return std::string("v") + fill('i', n - 5); if (n < 11) return fill('i', 10 - n) + "x"; if (n < 40) @@ -33,7 +35,7 @@ string tolowerRoman(int n) 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); + 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) @@ -41,7 +43,8 @@ string tolowerRoman(int n) 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); + 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) @@ -49,16 +52,16 @@ string tolowerRoman(int n) return "?"; } -//to convert to uppercase Roman Numeral -// the function works recursively -string toupperRoman(int n) -{ +/** 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 string("V") + fill('I', n - 5); + return std::string("V") + fill('I', n - 5); if (n < 11) return fill('I', 10 - n) + "X"; if (n < 40) @@ -66,7 +69,7 @@ string toupperRoman(int n) 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); + 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) @@ -74,7 +77,8 @@ string toupperRoman(int n) 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); + 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) @@ -82,16 +86,13 @@ string toupperRoman(int n) 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; } diff --git a/others/fast_interger_input.cpp b/others/fast_interger_input.cpp index 3358fc8bb..87963c9ad 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,7 +27,7 @@ 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 @@ -27,10 +35,10 @@ void fastinput(int *number) { *(number) *= -1; } -// Function Call +/** Main function */ int main() { int number; fastinput(&number); - std::cout << number << "\n"; + std::cout << number << std::endl; return 0; } diff --git a/others/fibonacci.cpp b/others/fibonacci.cpp deleted file mode 100644 index 87ccda6d3..000000000 --- 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/happy_number.cpp b/others/happy_number.cpp index 7d25a1bbd..b1debaa54 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 +/** + * @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 -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; } diff --git a/others/matrix_exponentiation.cpp b/others/matrix_exponentiation.cpp index 25c411dda..d44d22593 100644 --- a/others/matrix_exponentiation.cpp +++ b/others/matrix_exponentiation.cpp @@ -1,38 +1,64 @@ -/* -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. */ #include +#include + 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++) { @@ -44,8 +70,13 @@ vector> multiply(vector> A, vector> B) { return C; } -// computing power of a matrix -vector> power(vector> A, ll p) { +/** 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) { @@ -56,7 +87,10 @@ 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; @@ -64,8 +98,7 @@ ll ans(ll n) { 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)); @@ -92,8 +125,7 @@ ll ans(ll n) { return res; } -// 1 1 2 3 5 - +/** Main function */ int main() { cin.tie(0); cout.tie(0); diff --git a/others/measure_time_elapsed.cpp b/others/measure_time_elapsed.cpp deleted file mode 100644 index d0830ab79..000000000 --- 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; -} diff --git a/others/palindrome_of_number.cpp b/others/palindrome_of_number.cpp new file mode 100644 index 000000000..66401ff96 --- /dev/null +++ b/others/palindrome_of_number.cpp @@ -0,0 +1,35 @@ +/** + * @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 + +#ifdef _MSC_VER +// Required to compile std::toString function using MSVC +#include +#else +#include +#endif + +/** Main function */ +int main() { + int num; + std::cout << "Enter number = "; + std::cin >> num; + + std::string s1 = std::to_string(num); // convert number to string + std::string s2 = s1; + + std::reverse(s1.begin(), s1.end()); // reverse the string + + if (s1 == s2) // check if reverse and original string are identical + std::cout << "true"; + else + std::cout << "false"; + + return 0; +} diff --git a/others/paranthesis_matching.cpp b/others/paranthesis_matching.cpp new file mode 100644 index 000000000..2a6358d94 --- /dev/null +++ b/others/paranthesis_matching.cpp @@ -0,0 +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 +#ifdef _MSC_VER +#include // Visual Studio C requires this include +#else +#include +#endif + +/** check number */ +#define MAX 100 + +//! @{-------------- stack -------------- +//! global stack +char stack[MAX]; + +//! pointer to track stack index +int top = -1; + +//! push byte to stack variable +void push(char ch) { stack[++top] = ch; } + +//! pop a byte out of stack variable +char pop() { return stack[top--]; } + +//! @}-------------- end stack ----------- + +/** 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() { + 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++; + } + + // 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; +} diff --git a/others/pascal_triangle.cpp b/others/pascal_triangle.cpp index 101100018..4ea58f3f1 100644 --- a/others/pascal_triangle.cpp +++ b/others/pascal_triangle.cpp @@ -1,63 +1,75 @@ -#include +/** + * @file + * @brief Pascal's triangle implementation + */ +#ifdef _MSC_VER +#include // required for Visual C +#else +#include +#endif +#include +#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; - } +/** + * 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) { + 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 + std::cout << std::setw(4) << 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]; - } - } +/** + * 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) { + 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; + return arr; } -int main() -{ - int n = 0; +/** + * main function + */ +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); + std::cout << "Set Pascal's Triangle Height" << std::endl; + std::cin >> n; - //deallocation - for (int i = 0; i < n; ++i) - { - delete[] arr[i]; - } - delete[] arr; + // 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)); + } - return 0; + 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 new file mode 100644 index 000000000..faec6589c --- /dev/null +++ b/others/primality_test.cpp @@ -0,0 +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 + +/** 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; + + 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; +} + +/** 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; +} diff --git a/others/sieve_of_Eratosthenes.cpp b/others/sieve_of_Eratosthenes.cpp deleted file mode 100644 index e87ad4983..000000000 --- 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); -} diff --git a/others/smallest-circle.cpp b/others/smallest-circle.cpp deleted file mode 100644 index 48437cd86..000000000 --- a/others/smallest-circle.cpp +++ /dev/null @@ -1,121 +0,0 @@ -#include -#include -#include - -using namespace std; - -struct Point -{ - double x, y; - 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))); -} - -double TriangleArea(Point A, Point B, 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)); -} - -bool PointInCircle(vector &P, 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) -{ - 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; - } - } - for (size_t i = 0; i < P.size() - 1; i++) - 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)) - { - continue; - } - if (R <= minR) - { - minR = R; - minC = C; - } - } - cout << minC.x << " " << minC.y << endl; - return minR; -} - -void test() -{ - 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; -} - -void test2() -{ - 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; -} - -void test3() -{ - 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; -} -int main() -{ - test(); - cout << endl; - test2(); - cout << endl; - test3(); - return 0; -} diff --git a/others/smallest_circle.cpp b/others/smallest_circle.cpp new file mode 100644 index 000000000..9ee4353eb --- /dev/null +++ b/others/smallest_circle.cpp @@ -0,0 +1,205 @@ +/** + * @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 + +/** Define a point */ +struct Point { + double x, /**< abscissa */ + y; /**< ordinate */ + + /** construct a 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) { + x = a; + y = b; + } +}; + +/** 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)); +} + +/** + * 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 std::sqrt(p * (p - a) * (p - b) * (p - c)); +} + +/** + * 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; +} + +/** + * 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 = INFINITY; + double R; + 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++) + // 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 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]); + if (!PointInCircle(P, C, R)) { + continue; + } + if (R <= minR) { + minR = R; + minC = C; + } + } + std::cout << minC.x << " " << minC.y << std::endl; + return minR; +} + +/** Test case: result should be: + * \n Circle with + * \n radius 3.318493136080724 + * \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(3, -2)); + 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) + */ +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::cout << circle(Pv) << std::endl; +} + +/** Test case: result should be: + * \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; +} + +/** Main program */ +int main() { + test(); + std::cout << std::endl; + test2(); + std::cout << std::endl; + test3(); + return 0; +} diff --git a/others/sparse_matrix.cpp b/others/sparse_matrix.cpp new file mode 100644 index 000000000..a358f0da4 --- /dev/null +++ b/others/sparse_matrix.cpp @@ -0,0 +1,48 @@ +/** @file + * A sparse matrix is a matrix which has number of zeroes greater than + * \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; + + std::cout << "Enter dimensions of matrix (seperated with space): "; + std::cin >> m; + std::cin >> 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"; + + // 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 + } + } + + // 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"; + + for (int i = 0; i < m; i++) delete[] a[i]; + delete[] a; + return 0; +} diff --git a/others/spiral_print.cpp b/others/spiral_print.cpp index e6e6899ef..02dc3183a 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; } diff --git a/others/stairs_pattern.cpp b/others/stairs_pattern.cpp index 281446a2f..a3b8b0a44 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; -}} diff --git a/others/tower_of_hanoi.cpp b/others/tower_of_hanoi.cpp new file mode 100644 index 000000000..323b2e424 --- /dev/null +++ b/others/tower_of_hanoi.cpp @@ -0,0 +1,85 @@ +/** + * @file + * @brief Solve the [Tower of + * Hanoi](https://en.wikipedia.org/wiki/Tower_of_Hanoi) problem. + */ +#include + +/** + * Define the state of tower + */ +struct tower { + //! Values in the tower + int values[10]; + //! top tower ID + int top; +}; + +/** Display the towers */ +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"; + } + 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"; + } +} + +/** 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; +} + +/** + * 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(From, To, Using); + } else { + TH(n - 1, From, To, Using); + mov(From, To); + 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; + + int no; + + std::cout << "\nEnter number of discs : "; + std::cin >> no; + + for (int i = no; i > 0; i--) { + F.values[F.top++] = i; + } + + show(&F, &T, &U); + TH(no, &F, &U, &T); + + return 0; +} diff --git a/others/vector_important_functions.cpp b/others/vector_important_functions.cpp index e0a70eeda..d23ff9c97 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 -// 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; } diff --git a/probability/bayes_theorem.cpp b/probability/bayes_theorem.cpp index d30be6c9a..aaa557a94 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; diff --git a/probability/binomial_dist.cpp b/probability/binomial_dist.cpp index b21a3e0fc..1f30c5048 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 +/** 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; } -// 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 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 : " - < +/** + * @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 : " - < -using namespace std; -const int N = 1e6 + 5; -int a[N], bucket[N], cnt[N]; -int bucket_size; -struct query -{ - int l, r, i; -} q[N]; -int ans = 0; - -void add(int index) -{ - cnt[a[index]]++; - if (cnt[a[index]] == 1) - ans++; -} -void remove(int index) -{ - 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; -} - -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; -} diff --git a/range_queries/bit.cpp b/range_queries/bit.cpp index e5e36ed24..a1878705b 100644 --- a/range_queries/bit.cpp +++ b/range_queries/bit.cpp @@ -3,66 +3,50 @@ using namespace std; -class Bit -{ +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) - { + } + 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); } 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 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 +56,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 similarity index 70% rename from range_queries/FenwickTree.cpp rename to range_queries/fenwicktree.cpp index a4d1a02de..fb7cbaac4 100644 --- a/range_queries/FenwickTree.cpp +++ b/range_queries/fenwicktree.cpp @@ -1,4 +1,4 @@ -#include +#include using namespace std; /** @@ -6,43 +6,41 @@ 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) { + while (x <= range) { tree[x] += c; x += lowbit(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() { 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; diff --git a/range_queries/mo.cpp b/range_queries/mo.cpp new file mode 100644 index 000000000..d281ef077 --- /dev/null +++ b/range_queries/mo.cpp @@ -0,0 +1,64 @@ +#include +using namespace std; +const int N = 1e6 + 5; +int a[N], bucket[N], cnt[N]; +int bucket_size; +struct query { + int l, r, i; +} q[N]; +int ans = 0; + +void add(int index) { + cnt[a[index]]++; + if (cnt[a[index]] == 1) + ans++; +} +void remove(int index) { + 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; +} + +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; +} diff --git a/range_queries/segTree.cpp b/range_queries/segTree.cpp deleted file mode 100644 index ee81453e1..000000000 --- a/range_queries/segTree.cpp +++ /dev/null @@ -1,92 +0,0 @@ -//#include -#incldue -#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]; -} -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); -} -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]; -} -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; -} diff --git a/range_queries/segtree.cpp b/range_queries/segtree.cpp new file mode 100644 index 000000000..602b3fd95 --- /dev/null +++ b/range_queries/segtree.cpp @@ -0,0 +1,79 @@ +//#include +#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]; +} +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); +} +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]; +} +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; +} diff --git a/search/CMakeLists.txt b/search/CMakeLists.txt new file mode 100644 index 000000000..5fd1ae591 --- /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/Interpolation Search.cpp b/search/Interpolation Search.cpp deleted file mode 100644 index f52ce4f4f..000000000 --- a/search/Interpolation Search.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include -int InterpolationSearch(int A[], int n, int x) -{ - int low = 0; - int high = n - 1; - 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) - else if (x < A[mid]) - high = mid - 1; // X lies before mid - else - low = mid + 1; // x lies after mid - } - return -1; -} - -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; - 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. diff --git a/search/Linear Search.cpp b/search/Linear Search.cpp deleted file mode 100644 index 97e820437..000000000 --- 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/binary_search.cpp b/search/binary_search.cpp index 9933c9816..66da31d7f 100644 --- a/search/binary_search.cpp +++ b/search/binary_search.cpp @@ -1,34 +1,56 @@ +/** + * @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; } diff --git a/search/exponential_search.cpp b/search/exponential_search.cpp index b8343fa02..f57cbf96b 100644 --- a/search/exponential_search.cpp +++ b/search/exponential_search.cpp @@ -1,56 +1,84 @@ -// Copyright 2020 Divide-et-impera-11 -#include +/** + * \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 -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; +#ifdef _MSC_VER +#include // use for MS Visual C++ +#else +#include // for all other compilers +#endif + +/** 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) + 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 -// 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. */ -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) { + +/** 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; + 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; } + +/** Main function */ 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 + delete[] sorted_array; + return 0; } diff --git a/search/hash_search.cpp b/search/hash_search.cpp index 94d87b58a..6e4caffc3 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; } diff --git a/search/interpolation_search.cpp b/search/interpolation_search.cpp index afa9e7c50..4339dc366 100644 --- a/search/interpolation_search.cpp +++ b/search/interpolation_search.cpp @@ -1,36 +1,61 @@ -#include +/** + * \file + * \brief [Interpolation + * search](https://en.wikipedia.org/wiki/Interpolation_search) algorithm + */ +#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; +/** 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 -1; } +/** 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 == -1) + 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; +} diff --git a/search/interpolation_search2.cpp b/search/interpolation_search2.cpp new file mode 100644 index 000000000..93fa6cd83 --- /dev/null +++ b/search/interpolation_search2.cpp @@ -0,0 +1,46 @@ +/** + * \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; + 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) + else if (x < A[mid]) + high = mid - 1; // X lies before mid + 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; + + ///< 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 << " is at " << index << std::endl; +} + +// 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 0ee7e4e00..f7b100a4e 100644 --- a/search/jump_search.cpp +++ b/search/jump_search.cpp @@ -1,33 +1,36 @@ -// C++ program to implement Jump Search +/** + * \file + * \brief C++ program to implement [Jump + * Search](https://en.wikipedia.org/wiki/Jump_search) + */ +#include +#include +#include -#include -using namespace std; - -int jumpSearch(int arr[], int x, int n) -{ +/** jump search implementation + */ +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); + 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)) + if (prev == std::min(step, n)) return -1; } // If element is found @@ -38,10 +41,8 @@ int jumpSearch(int arr[], int x, int n) } // 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 +50,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 000000000..142506951 --- /dev/null +++ b/search/linear_search.cpp @@ -0,0 +1,53 @@ +/** + * \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) { + return i; + } + } + + return -1; +} + +/** main function */ +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 be95b599f..7379cad26 100644 --- a/search/median_search.cpp +++ b/search/median_search.cpp @@ -1,72 +1,78 @@ -#include -#include -#include -#include -#include -#include -#include -using namespace std; -vectorv; -vectors1; -vectors2; -vectors3; +/** + * \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 + +/** + * @todo add documentation + */ 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< *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"; } } -int main() -{ - for(int i=0;i<1000;i++) - { - v.push_back(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, &s1, &s2, &s3); + return 0; } +/// } diff --git a/search/searching.cpp b/search/searching.cpp deleted file mode 100644 index 6a9dcac7d..000000000 --- a/search/searching.cpp +++ /dev/null @@ -1,40 +0,0 @@ -#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"; - - 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; - } - system("pause"); - } - } -} diff --git a/search/ternary_search.cpp b/search/ternary_search.cpp index 4cb8d19d9..73b89da7a 100644 --- a/search/ternary_search.cpp +++ b/search/ternary_search.cpp @@ -1,128 +1,140 @@ -/* +/** + * \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 -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. - * + */ +#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: 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; + + 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; + } + } } -/* - * This is the iterative 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. + * \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; +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 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 (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; - } - - 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; - } } -/* - * 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 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 (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. + * \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) -{ - 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; +/** 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; } diff --git a/search/text_search.cpp b/search/text_search.cpp new file mode 100644 index 000000000..ee66a506a --- /dev/null +++ b/search/text_search.cpp @@ -0,0 +1,42 @@ +/** + * \file + * \brief Search for words in a long textual paragraph. + */ +#include +#include +#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"; + 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()) { + 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; + } + std::cin.get(); + } + } +} diff --git a/sorting/BeadSort.cpp b/sorting/BeadSort.cpp deleted file mode 100644 index c8e27b250..000000000 --- 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 6ad2489d2..000000000 --- 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 b160ac479..000000000 --- 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/CMakeLists.txt b/sorting/CMakeLists.txt new file mode 100644 index 000000000..00877bb61 --- /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/sorting") + +endforeach( testsourcefile ${APP_SOURCES} ) diff --git a/sorting/CocktailSelectionSort.cpp b/sorting/CocktailSelectionSort.cpp deleted file mode 100644 index cac6a3618..000000000 --- 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/Counting_Sort.cpp b/sorting/Counting_Sort.cpp deleted file mode 100644 index bda37bbd8..000000000 --- a/sorting/Counting_Sort.cpp +++ /dev/null @@ -1,66 +0,0 @@ -#include -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 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; -} - -void Print(int Arr[], int N) -{ - 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 *Count = new int[max - min + 1]; - - 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 = N - 1; i >= 0; i--) - { - Sorted_Arr[Count[Arr[i] - min] - 1] = Arr[i]; - Count[Arr[i] - min]--; - } - - 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; -} diff --git a/sorting/Insertion Sort.cpp b/sorting/Insertion Sort.cpp deleted file mode 100644 index 2563acaf8..000000000 --- a/sorting/Insertion Sort.cpp +++ /dev/null @@ -1,40 +0,0 @@ -//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 : "; - - //Input - for (int i = 0; i < n; i++) - { - 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; - } - - //Output - cout << "\nSorted Array : "; - for (int i = 0; i < n; i++) - { - cout << Array[i] << "\t"; - } - return 0; -} diff --git a/sorting/Merge Sort.cpp b/sorting/Merge Sort.cpp deleted file mode 100644 index b8edc8851..000000000 --- a/sorting/Merge Sort.cpp +++ /dev/null @@ -1,93 +0,0 @@ -#include -using namespace std; - -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]; - - 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]) - { - arr[k] = L[i]; - i++; - } - else - { - arr[k] = R[j]; - j++; - } - k++; - } - - while (i < n1) - { - arr[k] = L[i]; - i++; - k++; - } - - while (j < n2) - { - arr[k] = R[j]; - j++; - k++; - } -} - -void mergeSort(int arr[], int l, int r) -{ - if (l < r) - { - - int m = l + (r - l) / 2; - - mergeSort(arr, l, m); - mergeSort(arr, m + 1, r); - - merge(arr, l, m, r); - } -} - -void show(int A[], int size) -{ - int i; - for (i = 0; i < size; i++) - cout << A[i] << "\n"; -} - -int main() -{ - int size; - cout << "\nEnter the number of elements : "; - - cin >> size; - - int arr[size]; - - cout << "\nEnter the unsorted elements : "; - - for (int i = 0; i < size; ++i) - { - cout << "\n"; - cin >> arr[i]; - } - - mergeSort(arr, 0, size); - - cout << "Sorted array\n"; - show(arr, size); - return 0; -} diff --git a/sorting/NumericStringSort.cpp b/sorting/NumericStringSort.cpp deleted file mode 100644 index 02f6964ba..000000000 --- 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/OddEven Sort.cpp b/sorting/OddEven Sort.cpp deleted file mode 100644 index 62842c174..000000000 --- a/sorting/OddEven Sort.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/* C++ implementation Odd Even Sort */ -#include -#include - -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; - } - } - } -} - -void show(vector A, int size) -{ - 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; - - vector arr; - - cout << "\nEnter the unsorted elements : \n"; - - for (int i = 0; i < size; ++i) - { - cin >> temp; - arr.push_back(temp); - } - - oddEven(arr, size); - - cout << "Sorted array\n"; - show(arr, size); - return 0; -} diff --git a/sorting/Radix Sort.cpp b/sorting/Radix Sort.cpp deleted file mode 100644 index 09c91bb22..000000000 --- a/sorting/Radix Sort.cpp +++ /dev/null @@ -1,68 +0,0 @@ -#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]; - } - } -} -void print(int a[], int n) -{ - for (int i = 0; i < n; ++i) - { - cout << a[i] << " "; - } - cout << 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; -} \ No newline at end of file diff --git a/sorting/Selection Sort.cpp b/sorting/Selection Sort.cpp deleted file mode 100644 index 5b8724141..000000000 --- a/sorting/Selection Sort.cpp +++ /dev/null @@ -1,39 +0,0 @@ -//Selection Sort - -#include -using namespace std; - -int main() -{ - int Array[6]; - cout << "\nEnter any 6 Numbers for Unsorted Array : "; - - //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; - } - - //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 deleted file mode 100644 index b08c7ffd8..000000000 --- a/sorting/Shell Sort.cpp +++ /dev/null @@ -1,45 +0,0 @@ -#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]; - } - - // 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; -} diff --git a/sorting/Slow Sort.cpp b/sorting/Slow Sort.cpp deleted file mode 100644 index f8f7e74b8..000000000 --- a/sorting/Slow Sort.cpp +++ /dev/null @@ -1,57 +0,0 @@ -//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); -} - -//Sample Main function - -int main() -{ - int size; - cout << "\nEnter the number of elements : "; - - cin >> size; - - int arr[size]; - - cout << "\nEnter the unsorted elements : "; - - for (int i = 0; i < size; ++i) - { - cout << "\n"; - cin >> arr[i]; - } - - SlowSort(arr, 0, size); - - cout << "Sorted array\n"; - - for (int i = 0; i < size; ++i) - { - cout << arr[i] << " "; - } - return 0; -} diff --git a/sorting/bead_sort.cpp b/sorting/bead_sort.cpp new file mode 100644 index 000000000..f3276bfcd --- /dev/null +++ b/sorting/bead_sort.cpp @@ -0,0 +1,56 @@ +// 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 = new unsigned char[max * len]; + memset(beads, 0, max * len); + + // 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; + } + delete[] beads; +} + +// 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 000000000..0fbb995ac --- /dev/null +++ b/sorting/bitonic_sort.cpp @@ -0,0 +1,64 @@ +// 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 000000000..c43e425fc --- /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; + bool swap_check = true; + 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); i++) { + swap_check = false; + 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. + // 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/bucketSort.cpp deleted file mode 100644 index 0ffbf8e4c..000000000 --- a/sorting/bucketSort.cpp +++ /dev/null @@ -1,42 +0,0 @@ -// C++ program to sort an array using bucket sort -#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]; - - // 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()); - - // 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); - - cout << "Sorted array is \n"; - for (int i = 0; i < n; i++) - cout << arr[i] << " "; - return 0; -} diff --git a/sorting/bucket_sort.cpp b/sorting/bucket_sort.cpp new file mode 100644 index 000000000..c43865281 --- /dev/null +++ b/sorting/bucket_sort.cpp @@ -0,0 +1,36 @@ +// C++ program to sort an array using bucket sort +#include +#include +#include + +// Function to sort arr[] of size n using bucket sort +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++) { + 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++) 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]; + delete[] b; +} + +/* 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); + + std::cout << "Sorted array is \n"; + for (int i = 0; i < n; i++) std::cout << arr[i] << " "; + return 0; +} diff --git a/sorting/cocktail_selection_sort.cpp b/sorting/cocktail_selection_sort.cpp new file mode 100644 index 000000000..157acafce --- /dev/null +++ b/sorting/cocktail_selection_sort.cpp @@ -0,0 +1,102 @@ +// 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/comb_sort.cpp b/sorting/comb_sort.cpp new file mode 100644 index 000000000..1b0a4d706 --- /dev/null +++ b/sorting/comb_sort.cpp @@ -0,0 +1,49 @@ +// 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 +#include + +int a[100005]; +int n; + +int FindNextGap(int x) { + x = (x * 10) / 13; + + return std::max(1, x); +} + +void CombSort(int a[], int l, int r) { + // Init gap + int gap = n; + + // 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 + 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]) { + std::swap(a[i], a[i + gap]); + swapped = true; + } + } + } +} + +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) std::cout << a[i] << ' '; + return 0; +} diff --git a/sorting/combsort.cpp b/sorting/combsort.cpp deleted file mode 100644 index 2209c96fc..000000000 --- a/sorting/combsort.cpp +++ /dev/null @@ -1,59 +0,0 @@ -//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) -{ - x = (x * 10) / 13; - - return max(1, x); -} - -void CombSort(int a[], int l, int r) -{ - //Init gap - int gap = n; - - //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 - 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]); - swapped = true; - } - } - } -} - -int main() -{ - cin >> n; - for (int i = 1; i <= n; ++i) - cin >> a[i]; - - CombSort(a, 1, n); - - for (int i = 1; i <= n; ++i) - cout << a[i] << ' '; - return 0; -} diff --git a/sorting/counting_sort.cpp b/sorting/counting_sort.cpp new file mode 100644 index 000000000..1fbfc0fa3 --- /dev/null +++ b/sorting/counting_sort.cpp @@ -0,0 +1,57 @@ +#include +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 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; +} + +void Print(int Arr[], int N) { + 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 *Count = new int[max - min + 1]; + + 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 = N - 1; i >= 0; i--) { + Sorted_Arr[Count[Arr[i] - min] - 1] = Arr[i]; + Count[Arr[i] - min]--; + } + + 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; +} diff --git a/sorting/CountingSortString.cpp b/sorting/counting_sort_string.cpp similarity index 50% rename from sorting/CountingSortString.cpp rename to sorting/counting_sort_string.cpp index 6179e5d11..69d80c18a 100644 --- a/sorting/CountingSortString.cpp +++ b/sorting/counting_sort_string.cpp @@ -3,35 +3,27 @@ using namespace std; -void countSort(string arr) -{ - +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) - { + for (i = 0; arr[i]; ++i) { output[count[arr[i]] - 1] = arr[i]; --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; } -int main() -{ +int main() { string arr; cin >> arr; diff --git a/sorting/doxy.txt b/sorting/doxy.txt deleted file mode 100644 index 68079276e..000000000 --- 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 new file mode 100644 index 000000000..fe920ca59 --- /dev/null +++ b/sorting/insertion_sort.cpp @@ -0,0 +1,36 @@ +// Insertion Sort + +#include + +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++) { + 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; + } + + // 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/library_sort.cpp b/sorting/library_sort.cpp index 6f1ab6245..c9cba88d8 100644 --- a/sorting/library_sort.cpp +++ b/sorting/library_sort.cpp @@ -8,8 +8,7 @@ void librarySort(int *index, int n) { 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]; @@ -79,8 +78,7 @@ int main() { 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/makefile b/sorting/makefile deleted file mode 100644 index 21d3186c6..000000000 --- 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 new file mode 100644 index 000000000..82ab869cd --- /dev/null +++ b/sorting/merge_sort.cpp @@ -0,0 +1,81 @@ +#include + +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 = 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]; + + i = 0; + j = 0; + k = l; + while (i < n1 && j < n2) { + if (L[i] <= R[j]) { + arr[k] = L[i]; + i++; + } else { + arr[k] = R[j]; + j++; + } + k++; + } + + while (i < n1) { + arr[k] = L[i]; + i++; + k++; + } + + while (j < n2) { + arr[k] = R[j]; + j++; + k++; + } + + 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); + mergeSort(arr, m + 1, r); + + merge(arr, l, m, r); + } +} + +void show(int A[], int size) { + int i; + for (i = 0; i < size; i++) std::cout << A[i] << "\n"; +} + +int main() { + int size; + std::cout << "\nEnter the number of elements : "; + + std::cin >> size; + + int *arr = new int[size]; + + std::cout << "\nEnter the unsorted elements : "; + + for (int i = 0; i < size; ++i) { + std::cout << "\n"; + std::cin >> arr[i]; + } + + mergeSort(arr, 0, size); + + std::cout << "Sorted array\n"; + show(arr, size); + + delete[] arr; + return 0; +} diff --git a/sorting/non_recursive_merge_sort.cpp b/sorting/non_recursive_merge_sort.cpp index c6ca56376..b99b93108 100644 --- a/sorting/non_recursive_merge_sort.cpp +++ b/sorting/non_recursive_merge_sort.cpp @@ -5,28 +5,31 @@ * A generic implementation of non-recursive merge sort. */ #include // for size_t +#include #include // for std::move & std::remove_reference_t -template + +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. + * 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 + */ +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 + 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); @@ -49,32 +52,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,25 +81,21 @@ 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); } -/** - * @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) { + +} // namespace sorting + +using sorting::non_recursive_merge_sort; + +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 000000000..04a12e71a --- /dev/null +++ b/sorting/numeric_string_sort.cpp @@ -0,0 +1,55 @@ +// 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/odd_even_sort.cpp b/sorting/odd_even_sort.cpp new file mode 100644 index 000000000..25f2a3712 --- /dev/null +++ b/sorting/odd_even_sort.cpp @@ -0,0 +1,53 @@ +/* C++ implementation Odd Even Sort */ +#include +#include + +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; + } + } + } +} + +void show(vector A, int size) { + 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; + + vector arr; + + cout << "\nEnter the unsorted elements : \n"; + + for (int i = 0; i < size; ++i) { + cin >> temp; + arr.push_back(temp); + } + + oddEven(arr, size); + + cout << "Sorted array\n"; + show(arr, size); + return 0; +} diff --git a/sorting/quick_sort.cpp b/sorting/quick_sort.cpp index d067fa068..5d102dc88 100644 --- a/sorting/quick_sort.cpp +++ b/sorting/quick_sort.cpp @@ -1,8 +1,6 @@ /** - * - * 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 @@ -26,24 +24,25 @@ #include #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 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 + i++; // increment index of smaller element int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; @@ -55,12 +54,12 @@ int partition(int arr[], int low, int high) { return (i + 1); } -/** - * 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); @@ -69,25 +68,35 @@ void quickSort(int arr[], int low, int high) { } } +} // namespace sorting + +using sorting::quickSort; + // 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"; } -// Driver program to test above functions +/** Driver program to test above functions */ int main() { int size; std::cout << "\nEnter the number of elements : "; + std::cin >> size; + int *arr = new int[size]; + std::cout << "\nEnter the unsorted elements : "; + for (int i = 0; i < size; ++i) { - std::cin >> arr[i]; + std::cout << "\n"; + std::cin >> arr[i]; } - quickSort(arr, 0, size-1); - std::cout << "Sorted array : "; + quickSort(arr, 0, size); + std::cout << "Sorted array\n"; show(arr, size); + + delete[] arr; return 0; } diff --git a/sorting/radix_sort.cpp b/sorting/radix_sort.cpp new file mode 100644 index 000000000..a0fbfe99e --- /dev/null +++ b/sorting/radix_sort.cpp @@ -0,0 +1,58 @@ +#include +#include +#include +#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) { + 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; +} diff --git a/sorting/selection_sort.cpp b/sorting/selection_sort.cpp new file mode 100644 index 000000000..3854f52e6 --- /dev/null +++ b/sorting/selection_sort.cpp @@ -0,0 +1,33 @@ +// Selection Sort + +#include +using namespace std; + +int main() { + int Array[6]; + cout << "\nEnter any 6 Numbers for Unsorted Array : "; + + // 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; + } + + // 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 new file mode 100644 index 000000000..eb701478d --- /dev/null +++ b/sorting/shell_sort.cpp @@ -0,0 +1,37 @@ +#include + +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; + } + } + } + } + + // 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/shell_sort2.cpp b/sorting/shell_sort2.cpp new file mode 100644 index 000000000..5db773aca --- /dev/null +++ b/sorting/shell_sort2.cpp @@ -0,0 +1,234 @@ +/** + * \file + * \brief [Shell sort](https://en.wikipedia.org/wiki/Shell_sort) algorithm + * \author [Krishna Vedala](https://github.com/kvedala) + */ +#include +#include +#include +#include +#include // 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; + + for (i = 0; i < LEN; i++) { + std::cout << arr[i] << ", "; + } + 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); +} + +/** \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; + } + } +} + +/** 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 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; + +/** + * function to compare sorting using cstdlib's qsort + **/ +template +int compare(const void *a, const void *b) { + T arg1 = *static_cast(a); + T 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) +} + +/** + * 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 + } + + delete[] data; + delete[] 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 + } + + delete[] data; + delete[] 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) + NUM_DATA = atoi(argv[1]); + else + NUM_DATA = 200; + + // int array = new int[NUM_DATA]; + int *data = new int[NUM_DATA]; + // int array2 = new int[NUM_DATA]; + int range = 1800; + + std::srand(time(NULL)); + 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); // perform sorting + 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; + + delete[] data; + return 0; +} diff --git a/sorting/slow_sort.cpp b/sorting/slow_sort.cpp new file mode 100644 index 000000000..a3e64dba0 --- /dev/null +++ b/sorting/slow_sort.cpp @@ -0,0 +1,56 @@ +// 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 + +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 + +int main() { + int size; + std::cout << "\nEnter the number of elements : "; + + std::cin >> size; + + int *arr = new int[size]; + + std::cout << "\nEnter the unsorted elements : "; + + for (int i = 0; i < size; ++i) { + std::cout << "\n"; + std::cin >> arr[i]; + } + + SlowSort(arr, 0, size); + + std::cout << "Sorted array\n"; + + for (int i = 0; i < size; ++i) { + std::cout << arr[i] << " "; + } + + delete[] arr; + return 0; +} diff --git a/sorting/swap_sort.cpp b/sorting/swap_sort.cpp index a4ab1e57b..4cdaa57b3 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; @@ -53,6 +53,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 similarity index 55% rename from sorting/Tim Sort.cpp rename to sorting/tim_sort.cpp index 14d3a04d0..94f5aa230 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; diff --git a/strings/CMakeLists.txt b/strings/CMakeLists.txt new file mode 100644 index 000000000..3c15695cc --- /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} ) diff --git a/strings/brute_force_string_searching.cpp b/strings/brute_force_string_searching.cpp index 3288b36b0..fd5244b37 100644 --- a/strings/brute_force_string_searching.cpp +++ b/strings/brute_force_string_searching.cpp @@ -1,52 +1,57 @@ -#include -#include -#include - -using std::string; - -int brute_force(string text, string pattern); -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"} -}; - -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"; - else - 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. +/** + * @file + * @brief String pattern search - brute force */ +#include +#ifdef _MSC_VER +#include // use this for MS Visucal C++ +#else +#include +#endif +#include -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; +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; } +} // namespace string_search + +using string_search::brute_force; + +/** 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"}}; + +/** 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"; + else + std::cout << "failure\n"; + } + return 0; +} diff --git a/strings/knuth_morris_pratt.cpp b/strings/knuth_morris_pratt.cpp index f6f1169d3..d53948d98 100644 --- a/strings/knuth_morris_pratt.cpp +++ b/strings/knuth_morris_pratt.cpp @@ -1,64 +1,95 @@ -/* - 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 + +/** \namespace string_search + * \brief String search algorithms + */ +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]; } 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; } +} // namespace string_search -int main() -{ - - string text="alskfjaldsabc1abc1abc12k23adsfabcabc"; - string pattern="abc1abc12l"; - if(kmp(pattern,text)==true){ - cout<<"Found"< -#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) { +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)); + 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 +72,40 @@ 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 } +} // namespace string_search + +using string_search::rabin_karp; + +/** 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 02243638037e770a25a259ba8710ca060770ffff Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 19 Jun 2020 16:10:22 +0000 Subject: [PATCH 017/271] formatting source-code for f541be97244b89a9279a46ca1c33c75865127c7e --- sorting/quick_sort.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sorting/quick_sort.cpp b/sorting/quick_sort.cpp index 76c2a7184..ff66b4cf2 100644 --- a/sorting/quick_sort.cpp +++ b/sorting/quick_sort.cpp @@ -96,6 +96,6 @@ int main() { quickSort(arr, 0, size); std::cout << "Sorted array\n"; show(arr, size); - delete [] arr; + delete[] arr; return 0; } From 69f7c9c6e1657caaa351ef9e259d1b5bfa25befd Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 20 Jun 2020 07:27:41 -0400 Subject: [PATCH 018/271] [fix] Enable CI for pull_requests (#864) * rename awesome workflow * added new PR workflow - only cpplint and compilation * simple doc add * rename PR workflow * removed cpplint dependency * try v1 checkout * remove pr specific CI * remove dependency to perform git pull * remove blank line * remove checkout@master and use v1 * remove hyphen * remove misplaced with statement * remove redundant git pull * try git pull from origin for compile check * remove git pull altogehter * use setup-python-v2 --- ...some_forkflow.yml => awesome_workflow.yml} | 62 +++++-------------- 1 file changed, 15 insertions(+), 47 deletions(-) rename .github/workflows/{awesome_forkflow.yml => awesome_workflow.yml} (82%) diff --git a/.github/workflows/awesome_forkflow.yml b/.github/workflows/awesome_workflow.yml similarity index 82% rename from .github/workflows/awesome_forkflow.yml rename to .github/workflows/awesome_workflow.yml index 93b630d05..f8feb1d3e 100644 --- a/.github/workflows/awesome_forkflow.yml +++ b/.github/workflows/awesome_workflow.yml @@ -1,23 +1,22 @@ name: Awesome CI Workflow -on: [push] +on: [push, pull_request] # push: # branches: [ master ] # pull_request: # branches: [ master ] jobs: - code_format: + MainSequence: name: Code Formatter runs-on: ubuntu-latest steps: + - uses: actions/checkout@v1 # v2 is broken for git diff + - uses: actions/setup-python@v2 - name: requirements run: | sudo apt -qq -y update - sudo apt -qq install clang-format - - uses: actions/checkout@master - with: - submodules: true + sudo apt -qq install clang-format - name: Setup Git Specs run: | git config --global user.name github-actions @@ -56,18 +55,7 @@ jobs: line2: "IndentWidth: 4, TabWidth: 4, " line3: "AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: false," line4: "ColumnLimit: 80, AccessModifierOffset: -3 }" - - name: Git Push - run: git push --force origin HEAD:$GITHUB_REF || true - - 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: pull latest commit - run: git pull + - name: Update DIRECTORY.md shell: python run: | @@ -121,32 +109,14 @@ jobs: 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@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 # v2 is broken for git diff - - uses: actions/setup-python@master - - 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: git diff --diff-filter=dr --name-only origin/master > git_diff.txt - - run: echo "Files changed-- `cat git_diff.txt`" + - name: Install CPPLINT + run: | + python -m pip install cpplint + git remote -v + git branch + git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY + git diff --diff-filter=dr --name-only origin/master > git_diff.txt + echo "Files changed-- `cat git_diff.txt`" - name: cpplint_modified_files shell: python run: | @@ -197,8 +167,7 @@ jobs: build: name: Compile checks runs-on: ${{ matrix.os }} - # needs: [cpplint, update_directory_md, cpplint_modified_files] - needs: [update_directory_md] + needs: [MainSequence] strategy: matrix: os: [ubuntu-latest, windows-latest, macOS-latest] @@ -206,6 +175,5 @@ jobs: - uses: actions/checkout@master with: submodules: true - - run: git pull - run: cmake -B ./build -S . - run: cmake --build build From 405c4ee2549d8425e413c1b86e6efb3e0515da26 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 19 Jun 2020 18:10:57 -0400 Subject: [PATCH 019/271] update image and details section of documentation --- machine_learning/adaline_learning.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/machine_learning/adaline_learning.cpp b/machine_learning/adaline_learning.cpp index 1e25d3ba1..a8426ac4e 100644 --- a/machine_learning/adaline_learning.cpp +++ b/machine_learning/adaline_learning.cpp @@ -7,10 +7,12 @@ * * \author [Krishna Vedala](https://github.com/kvedala) * - * - * [source](https://commons.wikimedia.org/wiki/File:Adaline_flow_chart.gif) + * alt="Structure of an ADALINE network. Source: Wikipedia" + * style="width:200px; float:right;"> + * * 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) = From ba2f1ed12d85d03f5d47ec4f75be99648ad1f9e3 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 19 Jun 2020 18:12:35 -0400 Subject: [PATCH 020/271] update documentation --- machine_learning/kohonen_som_topology.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/machine_learning/kohonen_som_topology.cpp b/machine_learning/kohonen_som_topology.cpp index 25c58e260..016fe6d1e 100644 --- a/machine_learning/kohonen_som_topology.cpp +++ b/machine_learning/kohonen_som_topology.cpp @@ -3,9 +3,11 @@ * @{ * \file * \author [Krishna Vedala](https://github.com/kvedala) + * * \brief [Kohonen self organizing * map](https://en.wikipedia.org/wiki/Self-organizing_map) (topological map) * + * \details * 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 @@ -21,7 +23,7 @@ * than with GCC on windows * \see kohonen_som_trace.cpp */ -#define _USE_MATH_DEFINES // required for MS Visual C++ +#define _USE_MATH_DEFINES //< required for MS Visual C++ #include #include #include From 2ad1b72f6c4ea0b63e01e3fa83924095789b43dd Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 19 Jun 2020 18:17:16 -0400 Subject: [PATCH 021/271] make epsilon equal system epsilon --- numerical_methods/newton_raphson_method.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/numerical_methods/newton_raphson_method.cpp b/numerical_methods/newton_raphson_method.cpp index d086123ca..45560e323 100644 --- a/numerical_methods/newton_raphson_method.cpp +++ b/numerical_methods/newton_raphson_method.cpp @@ -18,7 +18,7 @@ #include #define EPSILON \ - 1e-6 // std::numeric_limits::epsilon() ///< system accuracy limit + 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 From 5111c2cf599ab3fbd89b97cd190f34814a03f60f Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 19 Jun 2020 18:19:20 -0400 Subject: [PATCH 022/271] set author after program details --- numerical_methods/ordinary_least_squares_regressor.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/numerical_methods/ordinary_least_squares_regressor.cpp b/numerical_methods/ordinary_least_squares_regressor.cpp index 43979d0ea..bbd75a742 100644 --- a/numerical_methods/ordinary_least_squares_regressor.cpp +++ b/numerical_methods/ordinary_least_squares_regressor.cpp @@ -3,10 +3,11 @@ * \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. + * + * \author [Krishna Vedala](https://github.com/kvedala) */ #include // for print formatting #include From 00fab77412da2ad4304faa8227e7ccce8ee8139d Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 19 Jun 2020 18:26:15 -0400 Subject: [PATCH 023/271] set epsilon to 1e-10 and update documentation --- numerical_methods/newton_raphson_method.cpp | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/numerical_methods/newton_raphson_method.cpp b/numerical_methods/newton_raphson_method.cpp index 45560e323..7597f1b8a 100644 --- a/numerical_methods/newton_raphson_method.cpp +++ b/numerical_methods/newton_raphson_method.cpp @@ -17,17 +17,24 @@ #include #include -#define EPSILON \ - std::numeric_limits::epsilon() ///< system accuracy limit -#define MAX_ITERATIONS 50000 ///< Maximum number of iterations to check +#define EPSILON 1e-10 ///< system accuracy limit +#define MAX_ITERATIONS INT16_MAX ///< Maximum number of iterations to check -/** define \f$f(x)\f$ to find root for +/** define \f$f(x)\f$ to find root for. + * Currently defined as: + * \f[ + * f(x) = x^3 - 4x - 9 + * \f] */ static double eq(double i) { return (std::pow(i, 3) - (4 * i) - 9); // original equation } /** define the derivative function \f$f'(x)\f$ + * For the current problem, it is: + * \f[ + * f'(x) = 3x^2 - 4 + * \f] */ static double eq_der(double i) { return ((3 * std::pow(i, 2)) - 4); // derivative of equation From f7a8b7a85f3b227e8ebb7f865e211be9b3a0a61c Mon Sep 17 00:00:00 2001 From: Neeraj C <35414531+iamnambiar@users.noreply.github.com> Date: Sat, 20 Jun 2020 21:09:43 +0530 Subject: [PATCH 024/271] Update math/sum_of_digits.cpp Co-authored-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- math/sum_of_digits.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/math/sum_of_digits.cpp b/math/sum_of_digits.cpp index bcb6d7956..d5a705c48 100644 --- a/math/sum_of_digits.cpp +++ b/math/sum_of_digits.cpp @@ -2,7 +2,7 @@ * Copyright 2020 @author iamnambiar * * @file - * A C++ Program to find the Sum of Digits of input integer. + * \brief A C++ Program to find the Sum of Digits of input integer. */ #include #include From edc17ec9e85ad5d2d371990009aa796de21eff06 Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Sat, 20 Jun 2020 23:04:56 +0530 Subject: [PATCH 025/271] Fixed Bug in sorting/merge_sort.cpp (#872) * formatting source-code for 72c365dcd34d9776fac3e2b58b41891b3619b02e * Fixed Bug [munmap_chunck() core dumped] * formatting source-code for b06bbf4dc6c46a3284d7852bb570438384eef4ef * fixed line spacing * fixed line spacing * fixed documentation * closed the paranthesis of line 3 * formatting source-code for 8233eda8894f46785f288e72c639d201852f6096 Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> --- sorting/merge_sort.cpp | 76 +++++++++++++++++++++++++++++++----------- 1 file changed, 56 insertions(+), 20 deletions(-) diff --git a/sorting/merge_sort.cpp b/sorting/merge_sort.cpp index 82ab869cd..fc6d66af5 100644 --- a/sorting/merge_sort.cpp +++ b/sorting/merge_sort.cpp @@ -1,6 +1,36 @@ +/** + * \addtogroup sorting Sorting Algorithms + * @{ + * \file + * \brief [Merege Sort Algorithm + * (MEREGE SORT)](https://en.wikipedia.org/wiki/Merge_sort) implementation + * + * \author [Ayaan Khan](http://github.com/ayaankhan98) + * + * \details + * Merge Sort is an efficient, general purpose, comparison + * based sorting algorithm. + * Merge Sort is a divide and conquer algorithm + * + */ #include -void merge(int arr[], int l, int m, int r) { +/** + * + * The merge() function is used for merging two halves. + * The merge(arr, l, m, r) is key process that assumes that + * arr[l..m] and arr[m+1..r] are sorted and merges the two + * sorted sub-arrays into one. + * + * @param arr - array with two halves arr[l...m] and arr[m+1...l] + * @param l - left index or start index of first half array + * @param m - right index or end index of first half array + * + * (The second array starts form m+1 and goes till l) + * + * @param l - end index or right index of second half array + */ +void merge(int *arr, int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; @@ -40,42 +70,48 @@ void merge(int arr[], int l, int m, int r) { delete[] R; } -void mergeSort(int arr[], int l, int r) { +/** + * Merge sort is a divide and conquer algorithm, it divides the + * input array into two halves and calls itself for the two halves + * and then calls merge() to merge the two halves + * + * @param arr - array to be sorted + * @param l - left index or start index of array + * @param r - right index or end index of array + * + */ +void mergeSort(int *arr, int l, int r) { if (l < r) { int m = l + (r - l) / 2; - mergeSort(arr, l, m); mergeSort(arr, m + 1, r); - merge(arr, l, m, r); } } -void show(int A[], int size) { - int i; - for (i = 0; i < size; i++) std::cout << A[i] << "\n"; +/** + * Utility function used to print the array after + * sorting + */ +void show(int *arr, int size) { + for (int i = 0; i < size; i++) std::cout << arr[i] << " "; + std::cout << "\n"; } +/** Main function */ int main() { int size; - std::cout << "\nEnter the number of elements : "; - + std::cout << "Enter the number of elements : "; std::cin >> size; - int *arr = new int[size]; - - std::cout << "\nEnter the unsorted elements : "; - + std::cout << "Enter the unsorted elements : "; for (int i = 0; i < size; ++i) { - std::cout << "\n"; std::cin >> arr[i]; } - - mergeSort(arr, 0, size); - - std::cout << "Sorted array\n"; - show(arr, size); - + mergeSort(arr, 0, size - 1); + std::cout << "Sorted array : "; + show(arr, size - 1); delete[] arr; return 0; } +/** @} */ From 4eee4ee7dabfca9835618f471a0e8671a2237b51 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 20 Jun 2020 22:16:37 -0400 Subject: [PATCH 026/271] enable AlignConsecutiveMacros --- .vscode/settings.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 6d75a1390..245be1a04 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,5 +1,5 @@ { - "C_Cpp.clang_format_style": "{ BasedOnStyle: Google, UseTab: Never, IndentWidth: 4, TabWidth: 4, AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: true, ColumnLimit: 80, AccessModifierOffset: -3 }", + "C_Cpp.clang_format_style": "{ BasedOnStyle: Google, UseTab: Never, IndentWidth: 4, TabWidth: 4, AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: true, ColumnLimit: 80, AccessModifierOffset: -3, AlignConsecutiveMacros: true }", "editor.formatOnSave": true, "editor.formatOnType": true, "editor.formatOnPaste": true From b5e25f44cfcc251f3e47c24bdebb455f2fd601bd Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 21 Jun 2020 00:09:09 -0400 Subject: [PATCH 027/271] added minima algorithm using golden section search --- numerical_methods/golden_search_extrema.cpp | 128 ++++++++++++++++++++ 1 file changed, 128 insertions(+) create mode 100644 numerical_methods/golden_search_extrema.cpp diff --git a/numerical_methods/golden_search_extrema.cpp b/numerical_methods/golden_search_extrema.cpp new file mode 100644 index 000000000..2d4611561 --- /dev/null +++ b/numerical_methods/golden_search_extrema.cpp @@ -0,0 +1,128 @@ +/** + * \file + * \brief Find extrema of a univariate real function in a given interval using + * [golden section search + * algorithm](https://en.wikipedia.org/wiki/Golden-section_search). + * + * \author [Krishna Vedala](https://github.com/kvedala) + */ +#define _USE_MATH_DEFINES //< required for MS Visual C++ +#include +#include +#include +#include +#include +#include + +#define EPSILON 1e-7 ///< solution accuracy limit +#define M_GOLDEN_RATIO \ + static_cast(1.618033988749894848204586834) ///< golden ratio value + +/** + * @brief Get the minima of a function in the given interval. To get the maxima, + * simply negate the function. + * + * @param f function to get minima for + * @param lim_a lower limit of search window + * @param lim_b upper limit of search window + * @return local minima found in the interval + */ +double get_minima(const std::function &f, double lim_a, + double lim_b) { + double c, d; + double prev_mean, mean = std::numeric_limits::infinity(); + + do { + prev_mean = mean; + + c = lim_b - (lim_b - lim_a) / M_GOLDEN_RATIO; + d = lim_a + (lim_b - lim_a) / M_GOLDEN_RATIO; + + if (f(c) < f(d)) { + lim_b = d; + } else { + lim_a = c; + } + + mean = (lim_a + lim_b) * 0.5f; + } while (std::abs(mean - prev_mean) > EPSILON); + + return mean; +} + +/** + * @brief Test function to find minima for the function + * \f$f(x)= (x-2)^2\f$ + * in the interval \f$[1,5]\f$ + * \n Expected result = 2 + */ +void test1() { + // define the function to minimize as a lambda function + std::function f1 = [](double x) { + return (x - 2) * (x - 2); + }; + + std::cout << "Test 1.... "; + + double minima = get_minima(f1, 1, 5); + + std::cout << minima << "..."; + + assert(std::abs(minima - 2) < EPSILON); + std::cout << "passed\n"; +} + +/** + * @brief Test function to find *maxima* for the function + * \f$f(x)= x^{\frac{1}{x}}\f$ + * in the interval \f$[-2,10]\f$ + * \n Expected result: \f$e\approx 2.71828182845904509\f$ + */ +void test2() { + // define the function to maximize as a lambda function + // since we are maximixing, we negated the function return value + std::function func = [](double x) { + return -std::pow(x, 1.f / x); + }; + + std::cout << "Test 2.... "; + + double minima = get_minima(func, -2, 10); + + std::cout << minima << " (" << M_E << ")..."; + + assert(std::abs(minima - M_E) < EPSILON); + std::cout << "passed\n"; +} + +/** + * @brief Test function to find *maxima* for the function + * \f$f(x)= \cos x\f$ + * in the interval \f$[0,12]\f$ + * \n Expected result: \f$\pi\approx 3.14159265358979312\f$ + */ +void test3() { + // define the function to maximize as a lambda function + // since we are maximixing, we negated the function return value + std::function func = [](double x) { return std::cos(x); }; + + std::cout << "Test 3.... "; + + double minima = get_minima(func, 0, 12); + + std::cout << minima << " (" << M_PI << ")..."; + + assert(std::abs(minima - M_PI) < EPSILON); + std::cout << "passed\n"; +} + +/** Main function */ +int main() { + std::cout.precision(18); + + test1(); + test2(); + test3(); + + return 0; +} From 33b8169f41b429b70f97fef40a484ed6e4dbda26 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 21 Jun 2020 04:10:37 +0000 Subject: [PATCH 028/271] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 071ee8b95..1ba34af53 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -132,6 +132,7 @@ * [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) + * [Golden Search Extrema](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/golden_search_extrema.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) From bf2b70313181cc31ce42a2807078df2770e8357f Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 21 Jun 2020 00:18:34 -0400 Subject: [PATCH 029/271] remove redundant header includes --- numerical_methods/golden_search_extrema.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/numerical_methods/golden_search_extrema.cpp b/numerical_methods/golden_search_extrema.cpp index 2d4611561..538c53961 100644 --- a/numerical_methods/golden_search_extrema.cpp +++ b/numerical_methods/golden_search_extrema.cpp @@ -9,10 +9,8 @@ #define _USE_MATH_DEFINES //< required for MS Visual C++ #include #include -#include #include #include -#include #define EPSILON 1e-7 ///< solution accuracy limit #define M_GOLDEN_RATIO \ From d8e76eda6f3d4091c0b61579a10bce895d7c16a8 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 21 Jun 2020 00:21:54 -0400 Subject: [PATCH 030/271] added limits header file --- numerical_methods/golden_search_extrema.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/numerical_methods/golden_search_extrema.cpp b/numerical_methods/golden_search_extrema.cpp index 538c53961..5a327c1ef 100644 --- a/numerical_methods/golden_search_extrema.cpp +++ b/numerical_methods/golden_search_extrema.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #define EPSILON 1e-7 ///< solution accuracy limit #define M_GOLDEN_RATIO \ From de70c5d864e0ccae223b0a7f96ebfe548049e37e Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Sun, 21 Jun 2020 21:28:00 +0530 Subject: [PATCH 031/271] [Bug Fix] of sorting/heapsort.cpp (#873) * formatting source-code for 72c365dcd34d9776fac3e2b58b41891b3619b02e * Fixed Bug [munmap_chunck() core dumped] * formatting source-code for b06bbf4dc6c46a3284d7852bb570438384eef4ef * fixed line spacing * fixed line spacing * fixed documentation * closed the paranthesis of line 3 * formatting source-code for 8233eda8894f46785f288e72c639d201852f6096 * Bug Fix heap sort [Fresh Implementation] * formatting source-code for e464ddac3688834ce46c59bada5ad3fddbfa2254 * Bug Fix heap sort [Fresh Implementation] * formatting source-code for 803981c831b36bf940d3fa2a901340cb0029717b * switched to normal functions from lambda * formatting source-code for ced5dcd6c4db53ece27d22ecd1dd1c1fcce6afb0 * Added template and test cases * formatting source-code for 7c8617fa46d41481c68ae2ae9d4f6a89ca42a4ff * fixed docs * fixed line spacing in tests * fix docs Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> --- sorting/heap_sort.cpp | 137 ++++++++++++++++++++++++++++++++---------- 1 file changed, 104 insertions(+), 33 deletions(-) diff --git a/sorting/heap_sort.cpp b/sorting/heap_sort.cpp index 9948bb821..ef9f87094 100644 --- a/sorting/heap_sort.cpp +++ b/sorting/heap_sort.cpp @@ -1,52 +1,123 @@ +/** + * \file + * \brief [Heap Sort Algorithm + * (heap sort)](https://en.wikipedia.org/wiki/Heapsort) implementation + * + * \author [Ayaan Khan](http://github.com/ayaankhan98) + * + * \details + * Heap-sort is a comparison-based sorting algorithm. + * Heap-sort can be thought of as an improved selection sort: + * like selection sort, heap sort divides its input into a sorted + * and an unsorted region, and it iteratively shrinks the unsorted + * region by extracting the largest element from it and inserting + * it into the sorted region. Unlike selection sort, + * heap sort does not waste time with a linear-time scan of the + * unsorted region; rather, heap sort maintains the unsorted region + * in a heap data structure to more quickly find the largest element + * in each step. + * + * Time Complexity - \f$O(n \log(n))\f$ + * + */ #include +#include #include -void heapify(int *a, int i, int n) { - int largest = i; - const int l = 2 * i + 1; - const int r = 2 * i + 2; +/** + * + * Utility Lambda function to print the array after + * sorting. + * + * @param arr array to be printed + * @param sz size of array + * + */ +template +void printArray(T *arr, int sz) { + for (int i = 0; i < sz; i++) std::cout << arr[i] << " "; + std::cout << "\n"; +} - if (l < n && a[l] > a[largest]) +/** + * + * \addtogroup sorting Sorting Algorithm + * @{ + * + * The heapify procedure can be thought of as building a heap from + * the bottom up by successively sifting downward to establish the + * heap property. + * + * @param arr array to be sorted + * @param n size of array + * @param i node position in Binary Tress or element position in + * Array to be compared with it's childern + * + */ +template +void heapify(T *arr, int n, int i) { + int largest = i; + int l = 2 * i + 1; + int r = 2 * i + 2; + + if (l < n && arr[l] > arr[largest]) largest = l; - if (r < n && a[r] > a[largest]) + if (r < n && arr[r] > arr[largest]) largest = r; if (largest != i) { - std::swap(a[i], a[largest]); - heapify(a, n, largest); + std::swap(arr[i], arr[largest]); + heapify(arr, n, largest); } } -void heapsort(int *a, int n) { - for (int i = n - 1; i >= 0; --i) { - std::swap(a[0], a[i]); - heapify(a, 0, i); +/** + * Utilizes heapify procedure to sort + * the array + * + * @param arr array to be sorted + * @param n size of array + * + */ +template +void heapSort(T *arr, int n) { + for (int i = n - 1; i >= 0; i--) heapify(arr, n, i); + + for (int i = n - 1; i >= 0; i--) { + std::swap(arr[0], arr[i]); + heapify(arr, i, 0); } } -void build_maxheap(int *a, int n) { - for (int i = n / 2 - 1; i >= 0; --i) { - heapify(a, i, n); - } +/** + * + * @} + * Test cases to test the program + * + */ +void test() { + std::cout << "Test 1\n"; + int arr[] = {-10, 78, -1, -6, 7, 4, 94, 5, 99, 0}; + int sz = sizeof(arr) / sizeof(arr[0]); // sz - size of array + printArray(arr, sz); // displaying the array before sorting + heapSort(arr, sz); // calling heapsort to sort the array + printArray(arr, sz); // display array after sorting + assert(std::is_sorted(arr, arr + sz)); + std::cout << "Test 1 Passed\n========================\n"; + + std::cout << "Test 2\n"; + double arr2[] = {4.5, -3.6, 7.6, 0, 12.9}; + sz = sizeof(arr2) / sizeof(arr2[0]); + printArray(arr2, sz); + heapSort(arr2, sz); + printArray(arr2, sz); + assert(std::is_sorted(arr2, arr2 + sz)); + std::cout << "Test 2 passed\n"; } +/** Main function */ 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) { - std::cout << "Enter Element " << i << std::endl; - std::cin >> a[i]; - } - - build_maxheap(a, n); - heapsort(a, n); - std::cout << "Sorted Output\n"; - for (int i = 0; i < n; ++i) { - std::cout << a[i] << std::endl; - } - - std::getchar(); + test(); + return 0; } From a48d05fb6223cedde57fa487fb79ee51651d5985 Mon Sep 17 00:00:00 2001 From: Taj Date: Sun, 21 Jun 2020 18:40:57 +0100 Subject: [PATCH 032/271] feat: Added a probabilistic Miller-Rabin Primality Test (#845) * feat: Added a probabilitic Miller-Rabin Primality test * docs: Documentation Changes * fix: Issue with the assert call * docs: grammatical error * docs: corrected the copyright comment * docs: Fixed some documentation issues. * docs: fix latex issues * docs and fix: Fixed documentation issues and vector by const reference and iterator over const reference. * docs: fixed latex documentation issue. * docs: spelling errors * docs: spelling error fixed --- math/miller_rabin.cpp | 183 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 183 insertions(+) create mode 100644 math/miller_rabin.cpp diff --git a/math/miller_rabin.cpp b/math/miller_rabin.cpp new file mode 100644 index 000000000..654f99820 --- /dev/null +++ b/math/miller_rabin.cpp @@ -0,0 +1,183 @@ +/** + * Copyright 2020 @author tjgurwara99 + * @file + * + * A basic implementation of Miller-Rabin primality test. + */ + +#include +#include +#include +#include + +/** + * Function to give a binary representation of a number in reverse order + * @param num integer number that we want to convert + * @return result vector of the number input in reverse binary + */ +template std::vector reverse_binary(T num) { + std::vector result; + T temp = num; + while (temp > 0) { + result.push_back(temp % 2); + temp = temp / 2; + } + return result; +} + +/** + * Function for modular exponentiation. + * This function is an efficient modular exponentiation function. + * It can be used with any big integer library such as Boost multiprecision + * to give result any modular exponentiation problem relatively quickly. + * @param base number being raised to a power as integer + * @param rev_binary_exponent reverse binary of the power the base is being + * raised to + * @param mod modulo + * @return r the modular exponentiation of \f$a^{n} \equiv r \mod{m}\f$ where + * \f$n\f$ is the base 10 representation of rev_binary_exponent and \f$m = mod \f$ + * parameter. + */ +template +T modular_exponentiation(T base, const std::vector &rev_binary_exponent, + T mod) { + if (mod == 1) + return 0; + T b = 1; + if (rev_binary_exponent.size() == 0) + return b; + T A = base; + if (rev_binary_exponent[0] == 1) + b = base; + + for (typename std::vector::const_iterator it = + rev_binary_exponent.cbegin() + 1; + it != rev_binary_exponent.cend(); ++it) { + A = A * A % mod; + if (*it == 1) + b = A * b % mod; + } + return b; +} + +/** Function for testing the conditions that are satisfied when a number is + * prime. + * @param d number such that \f$d \cdot 2^r = n - 1\f$ where \f$n = num\f$ + * parameter and \f$r \geq 1\f$ + * @param num number being tested for primality. + * @return 'false' if n is composite + * @return 'true' if n is (probably) prime. + */ +template bool miller_test(T d, T num) { + // random number seed + std::random_device rd_seed; + // random number generator + std::mt19937 gen(rd_seed()); + // Uniformly distributed range [2, num - 2] for random numbers + std::uniform_int_distribution<> distribution(2, num - 2); + // Random number generated in the range [2, num -2]. + T random = distribution(gen); + // vector for reverse binary of the power + std::vector power = reverse_binary(d); + // x = random ^ d % num + T x = modular_exponentiation(random, power, num); + // miller conditions + if (x == 1 || x == num - 1) { + return true; + } + + while (d != num - 1) { + x = (x * x) % num; + d *= 2; + if (x == 1) { + return false; + } + if (x == num - 1) { + return true; + } + } + return false; +} + +/** + * Function that test (probabilistically) whether a given number is a prime + * based on the Miller-Rabin Primality Test. + * @param num number to be tested for primality. + * @param repeats number of repetitions for the test to increase probability of + * correct result. + * @return 'false' if num is composite + * @return 'true' if num is (probably) prime + * + * \detail + * First we check whether the num input is less than 4, if so we can determine + * whether this is a prime or composite by checking for 2 and 3. + * Next we check whether this num is odd (as all primes greater than 2 are odd). + * Next we write our num in the following format \f$num = 2^r \cdot d + 1\f$. After + * finding r and d for our input num, we use for loop repeat number of times + * inside which we check the miller conditions using the function miller_test. + * If miller_test returns false then the number is composite + * After the loop finishes completely without issuing a false return call, + * we can conclude that this number is probably prime. + */ +template bool miller_rabin_primality_test(T num, T repeats) { + if (num <= 4) { + // If num == 2 or num == 3 then prime + if (num == 2 || num == 3) { + return true; + } else { + return false; + } + } + // If num is even then not prime + if (num % 2 == 0) { + return false; + } + // Finding d and r in num = 2^r * d + 1 + T d = num - 1, r = 0; + while (d % 2 == 0) { + d = d / 2; + r++; + } + + for (T i = 0; i < repeats; ++i) { + if (!miller_test(d, num)) { + return false; + } + } + return true; +} + +/** + * Functions for testing the miller_rabin_primality_test() function with some + * assert statements. + */ +void tests() { + // First test on 2 + assert(((void)"2 is prime but function says otherwise.\n", + miller_rabin_primality_test(2, 1) == true)); + std::cout << "First test passes." << std::endl; + // Second test on 5 + assert(((void)"5 should be prime but the function says otherwise.\n", + miller_rabin_primality_test(5, 3) == true)); + std::cout << "Second test passes." << std::endl; + // Third test on 23 + assert(((void)"23 should be prime but the function says otherwise.\n", + miller_rabin_primality_test(23, 3) == true)); + std::cout << "Third test passes." << std::endl; + // Fourth test on 16 + assert(((void)"16 is not a prime but the function says otherwise.\n", + miller_rabin_primality_test(16, 3) == false)); + std::cout << "Fourth test passes." << std::endl; + // Fifth test on 27 + assert(((void)"27 is not a prime but the function says otherwise.\n", + miller_rabin_primality_test(27, 3) == false)); + std::cout << "Fifth test passes." << std::endl; +} + +/** + * Main function + */ +int main() { + tests(); + return 0; +} From bbe1ff12860dc0beb5cc0c4d732c77b61962cdbf Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 21 Jun 2020 17:42:09 +0000 Subject: [PATCH 033/271] formatting source-code for a48d05fb6223cedde57fa487fb79ee51651d5985 --- math/miller_rabin.cpp | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/math/miller_rabin.cpp b/math/miller_rabin.cpp index 654f99820..ec24ddb3e 100644 --- a/math/miller_rabin.cpp +++ b/math/miller_rabin.cpp @@ -15,7 +15,8 @@ * @param num integer number that we want to convert * @return result vector of the number input in reverse binary */ -template std::vector reverse_binary(T num) { +template +std::vector reverse_binary(T num) { std::vector result; T temp = num; while (temp > 0) { @@ -35,8 +36,8 @@ template std::vector reverse_binary(T num) { * raised to * @param mod modulo * @return r the modular exponentiation of \f$a^{n} \equiv r \mod{m}\f$ where - * \f$n\f$ is the base 10 representation of rev_binary_exponent and \f$m = mod \f$ - * parameter. + * \f$n\f$ is the base 10 representation of rev_binary_exponent and \f$m = mod + * \f$ parameter. */ template T modular_exponentiation(T base, const std::vector &rev_binary_exponent, @@ -68,7 +69,8 @@ T modular_exponentiation(T base, const std::vector &rev_binary_exponent, * @return 'false' if n is composite * @return 'true' if n is (probably) prime. */ -template bool miller_test(T d, T num) { +template +bool miller_test(T d, T num) { // random number seed std::random_device rd_seed; // random number generator @@ -112,14 +114,15 @@ template bool miller_test(T d, T num) { * First we check whether the num input is less than 4, if so we can determine * whether this is a prime or composite by checking for 2 and 3. * Next we check whether this num is odd (as all primes greater than 2 are odd). - * Next we write our num in the following format \f$num = 2^r \cdot d + 1\f$. After - * finding r and d for our input num, we use for loop repeat number of times - * inside which we check the miller conditions using the function miller_test. - * If miller_test returns false then the number is composite - * After the loop finishes completely without issuing a false return call, - * we can conclude that this number is probably prime. + * Next we write our num in the following format \f$num = 2^r \cdot d + 1\f$. + * After finding r and d for our input num, we use for loop repeat number of + * times inside which we check the miller conditions using the function + * miller_test. If miller_test returns false then the number is composite After + * the loop finishes completely without issuing a false return call, we can + * conclude that this number is probably prime. */ -template bool miller_rabin_primality_test(T num, T repeats) { +template +bool miller_rabin_primality_test(T num, T repeats) { if (num <= 4) { // If num == 2 or num == 3 then prime if (num == 2 || num == 3) { From 0f5e880376239db1a12be4ed0900e99794a828fc Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 21 Jun 2020 17:42:10 +0000 Subject: [PATCH 034/271] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 071ee8b95..9cb6abcfa 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -116,6 +116,7 @@ * [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) + * [Miller Rabin](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/miller_rabin.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 d9fc87896213c3fb562fb6fadb68821310f5ced7 Mon Sep 17 00:00:00 2001 From: matgrz1993 Date: Sun, 21 Jun 2020 21:41:08 +0200 Subject: [PATCH 035/271] fix: Remove FenwickTree (#856) * Remove FenwickTree FenwickTree is the same Data Structure as Binary Indexed Tree located in file "range_queries/bit.cpp" so it could be removed. * Fix cpplint errors * docs: Update documentation * docs: Update FenwickTree documentation * updating DIRECTORY.md Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> --- DIRECTORY.md | 3 +- range_queries/bit.cpp | 60 ------------------------- range_queries/fenwick_tree.cpp | 82 ++++++++++++++++++++++++++++++++++ range_queries/fenwicktree.cpp | 54 ---------------------- 4 files changed, 83 insertions(+), 116 deletions(-) delete mode 100644 range_queries/bit.cpp create mode 100644 range_queries/fenwick_tree.cpp delete mode 100644 range_queries/fenwicktree.cpp diff --git a/DIRECTORY.md b/DIRECTORY.md index 9cb6abcfa..4989050df 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -181,8 +181,7 @@ * [Poisson Dist](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/probability/poisson_dist.cpp) ## 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) + * [Fenwick Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/fenwick_tree.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) diff --git a/range_queries/bit.cpp b/range_queries/bit.cpp deleted file mode 100644 index a1878705b..000000000 --- a/range_queries/bit.cpp +++ /dev/null @@ -1,60 +0,0 @@ -// Binary Indexed Tree. -#include - -using namespace std; - -class Bit { - int n; - vector bit; - 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]); - } - } - Bit(int x) { - n = x; - bit.assign(n + 1, 0); - } - - void update(int id, int val) { - // Add val at id - id++; - while (id <= n) { - bit[id] += val; - id += offset(id); - } - } - - int sum(int id) { - // Get prefix sum upto id. - 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 main() { - int n = 5; - vector arr = {1, 2, 3, 4, 5}; - Bit x(arr); - - assert(x.sum_range(0, 0) == 1); - assert(x.sum_range(0, 1) == 3); - assert(x.sum_range(0, 2) == 6); - x.update(0, 6); - assert(x.sum_range(0, 0) == 6); - assert(x.sum_range(0, 1) == 8); - assert(x.sum_range(0, 2) == 11); - return 0; -} diff --git a/range_queries/fenwick_tree.cpp b/range_queries/fenwick_tree.cpp new file mode 100644 index 000000000..a2498dc6a --- /dev/null +++ b/range_queries/fenwick_tree.cpp @@ -0,0 +1,82 @@ +/** + * @file + * @brief Fenwick tree + * + * A Fenwick tree or binary indexed tree is a data structure + * that can efficiently update elements and calculate + * prefix sums in a table of numbers. + */ +#include +#include +#include + +/** + * n --> No. of elements present in input array. + * bit[0..n] --> Array that represents Binary Indexed Tree. + */ +class FenwickTree { + int n; + std::vector bit; + + /** Returns the highest power of two which is not more than x */ + inline int offset(int x) { return (x & (-x)); } + + public: + /** Constructor + * \param[in] arr --> Input array for which prefix sum is evaluated. + */ + explicit FenwickTree(const std::vector& arr) { + n = arr.size(); + bit.assign(n + 1, 0); + for (int i = 0; i < n; ++i) { + update(i, arr[i]); + } + } + + /** Constructor + * \param[in] x --> Size of array that represents Binary Indexed Tree. + */ + explicit FenwickTree(int x) { + n = x; + bit.assign(n + 1, 0); + } + + /** Add val at id */ + void update(int id, int val) { + id++; + while (id <= n) { + bit[id] += val; + id += offset(id); + } + } + + /** Get prefix sum upto id */ + int sum(int id) { + id++; + int res = 0; + while (id > 0) { + res += bit[id]; + id -= offset(id); + } + return res; + } + + /** Returns the prefix sum in range from l to r */ + int sum_range(int l, int r) { return sum(r) - sum(l - 1); } +}; + +/** Main function */ +int main() { + int n = 5; + std::vector arr = {1, 2, 3, 4, 5}; + FenwickTree fenwick_tree(arr); + + assert(fenwick_tree.sum_range(0, 0) == 1); + assert(fenwick_tree.sum_range(0, 1) == 3); + assert(fenwick_tree.sum_range(0, 2) == 6); + fenwick_tree.update(0, 6); + assert(fenwick_tree.sum_range(0, 0) == 6); + assert(fenwick_tree.sum_range(0, 1) == 8); + assert(fenwick_tree.sum_range(0, 2) == 11); + return 0; +} diff --git a/range_queries/fenwicktree.cpp b/range_queries/fenwicktree.cpp deleted file mode 100644 index fb7cbaac4..000000000 --- a/range_queries/fenwicktree.cpp +++ /dev/null @@ -1,54 +0,0 @@ -#include -using namespace std; - -/** - * ` lowbit(x) ` aims to find the last 1 in binary of a positive number - * twos complement works good on this - * also using ` x - (x & (x - 1)) ` - */ -#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` - -void update(int x, int c) { - while (x <= range) { - tree[x] += c; - x += lowbit(x); - } -} -int query(int x) { - int ans = 0; - while (x) { - ans += tree[x]; - x -= lowbit(x); - } - return ans; -} -int query_segement(int l, int r) { return query(r) - query(l - 1); } - -int main() { - cin >> range; - for (int i = 1; i <= range; i++) { - int num; - cin >> num; - update(i, num); - } - int q; - cin >> q; - while (q--) { - int op; - cin >> op; - if (op == 0) { - int l, r; - cin >> l >> r; - cout << query_segement(l, r) << endl; - } else { - int x, c; - cin >> x >> c; - update(x, c); - } - } - return 0; -} From 00dda54f4f1f52ad497747a2316309cc2d0cbf05 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 21 Jun 2020 17:12:18 -0400 Subject: [PATCH 036/271] ensure search window is increasing and greater than tolerance --- numerical_methods/golden_search_extrema.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/numerical_methods/golden_search_extrema.cpp b/numerical_methods/golden_search_extrema.cpp index 5a327c1ef..5d84c5572 100644 --- a/numerical_methods/golden_search_extrema.cpp +++ b/numerical_methods/golden_search_extrema.cpp @@ -31,6 +31,14 @@ double get_minima(const std::function &f, double lim_a, double c, d; double prev_mean, mean = std::numeric_limits::infinity(); + // ensure that lim_a < lim_b + if (lim_a > lim_b) { + std::swap(lim_a, lim_b); + } else if (std::abs(lim_a - lim_b) <= EPSILON) { + std::cerr << "Search range must be greater than " << EPSILON << "\n"; + return lim_a; + } + do { prev_mean = mean; From 9c186095a806e293e3da3c6fdf3562b864789f0a Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 21 Jun 2020 17:31:53 -0400 Subject: [PATCH 037/271] print number of steps taken for convergence --- numerical_methods/golden_search_extrema.cpp | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/numerical_methods/golden_search_extrema.cpp b/numerical_methods/golden_search_extrema.cpp index 5d84c5572..44e8e2c12 100644 --- a/numerical_methods/golden_search_extrema.cpp +++ b/numerical_methods/golden_search_extrema.cpp @@ -28,6 +28,7 @@ */ double get_minima(const std::function &f, double lim_a, double lim_b) { + uint32_t iters = 0; double c, d; double prev_mean, mean = std::numeric_limits::infinity(); @@ -51,10 +52,12 @@ double get_minima(const std::function &f, double lim_a, lim_a = c; } - mean = (lim_a + lim_b) * 0.5f; + mean = (lim_a + lim_b) / 2.f; + iters++; } while (std::abs(mean - prev_mean) > EPSILON); - return mean; + std::cout << " (iters: " << iters << ") "; + return prev_mean; } /** @@ -115,7 +118,7 @@ void test3() { std::cout << "Test 3.... "; - double minima = get_minima(func, 0, 12); + double minima = get_minima(func, -4, 12); std::cout << minima << " (" << M_PI << ")..."; @@ -127,6 +130,9 @@ void test3() { int main() { std::cout.precision(18); + std::cout << "Computations performed with machine epsilon: " << EPSILON + << "\n"; + test1(); test2(); test3(); From 21e93919f3255103d0442733eec0952b3b9c75d2 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 21 Jun 2020 17:50:04 -0400 Subject: [PATCH 038/271] limit print precision to 9 decimals --- numerical_methods/golden_search_extrema.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/numerical_methods/golden_search_extrema.cpp b/numerical_methods/golden_search_extrema.cpp index 44e8e2c12..41bf9c8d3 100644 --- a/numerical_methods/golden_search_extrema.cpp +++ b/numerical_methods/golden_search_extrema.cpp @@ -128,7 +128,7 @@ void test3() { /** Main function */ int main() { - std::cout.precision(18); + std::cout.precision(9); std::cout << "Computations performed with machine epsilon: " << EPSILON << "\n"; From e71ee9ccb0aa58aeb10fff22d5c48e2e65fe44bb Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 21 Jun 2020 18:30:31 -0400 Subject: [PATCH 039/271] better documentation of algorithm --- numerical_methods/golden_search_extrema.cpp | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/numerical_methods/golden_search_extrema.cpp b/numerical_methods/golden_search_extrema.cpp index 41bf9c8d3..0969544e5 100644 --- a/numerical_methods/golden_search_extrema.cpp +++ b/numerical_methods/golden_search_extrema.cpp @@ -14,12 +14,11 @@ #include #define EPSILON 1e-7 ///< solution accuracy limit -#define M_GOLDEN_RATIO \ - static_cast(1.618033988749894848204586834) ///< golden ratio value /** * @brief Get the minima of a function in the given interval. To get the maxima, - * simply negate the function. + * simply negate the function. The golden ratio used here is:\f[ + * k=\frac{3-\sqrt{5}}{2} \approx 0.381966\ldots\f] * * @param f function to get minima for * @param lim_a lower limit of search window @@ -32,6 +31,9 @@ double get_minima(const std::function &f, double lim_a, double c, d; double prev_mean, mean = std::numeric_limits::infinity(); + // golden ratio value + const double M_GOLDEN_RATIO = (1.f + std::sqrt(5.f)) / 2.f; + // ensure that lim_a < lim_b if (lim_a > lim_b) { std::swap(lim_a, lim_b); @@ -43,18 +45,24 @@ double get_minima(const std::function &f, double lim_a, do { prev_mean = mean; - c = lim_b - (lim_b - lim_a) / M_GOLDEN_RATIO; - d = lim_a + (lim_b - lim_a) / M_GOLDEN_RATIO; + // compute the section ratio width + double ratio = (lim_b - lim_a) / M_GOLDEN_RATIO; + c = lim_b - ratio; // right-side section start + d = lim_a + ratio; // left-side section end if (f(c) < f(d)) { + // select left section lim_b = d; } else { + // selct right section lim_a = c; } mean = (lim_a + lim_b) / 2.f; iters++; - } while (std::abs(mean - prev_mean) > EPSILON); + + // continue till the interval width is greater than sqrt(system epsilon) + } while (std::abs(lim_a - lim_b) > EPSILON); std::cout << " (iters: " << iters << ") "; return prev_mean; From 744da70bbf744c77579edd9540ce9d757106dbe4 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 21 Jun 2020 22:28:50 -0400 Subject: [PATCH 040/271] added see-also reference to brents method --- numerical_methods/golden_search_extrema.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/numerical_methods/golden_search_extrema.cpp b/numerical_methods/golden_search_extrema.cpp index 0969544e5..1ca47949f 100644 --- a/numerical_methods/golden_search_extrema.cpp +++ b/numerical_methods/golden_search_extrema.cpp @@ -4,6 +4,7 @@ * [golden section search * algorithm](https://en.wikipedia.org/wiki/Golden-section_search). * + * \see brent_method_extrema.cpp * \author [Krishna Vedala](https://github.com/kvedala) */ #define _USE_MATH_DEFINES //< required for MS Visual C++ From db0fc17efbb13a9c66dfa46f5c9f737047696cbc Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 21 Jun 2020 22:30:23 -0400 Subject: [PATCH 041/271] feat: added brent's mthod to find extrema of a unimodal real function with real variables Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- numerical_methods/brent_method_extrema.cpp | 215 +++++++++++++++++++++ 1 file changed, 215 insertions(+) create mode 100644 numerical_methods/brent_method_extrema.cpp diff --git a/numerical_methods/brent_method_extrema.cpp b/numerical_methods/brent_method_extrema.cpp new file mode 100644 index 000000000..941c3b694 --- /dev/null +++ b/numerical_methods/brent_method_extrema.cpp @@ -0,0 +1,215 @@ +/** + * \file + * \brief Find real extrema of a univariate real function in a given interval + * using [Brent's method](https://en.wikipedia.org/wiki/Brent%27s_method). + * + * Refer the algorithm discoverer's publication + * [online](https://maths-people.anu.edu.au/~brent/pd/rpb011i.pdf) and also + * associated book: + * > R. P. Brent, Algorithms for Minimization without + * > Derivatives, Prentice-Hall, Englewood Cliffs, New Jersey, 1973 + * + * \see golden_search_extrema.cpp + * + * \author [Krishna Vedala](https://github.com/kvedala) + */ +#define _USE_MATH_DEFINES //< required for MS Visual C++ +#include +#include +#include +#include +#include + +#define EPSILON \ + std::sqrt( \ + std::numeric_limits::epsilon()) ///< system accuracy limit + +/** + * @brief Get the real root of a function in the given interval. + * + * @param f function to get root for + * @param lim_a lower limit of search window + * @param lim_b upper limit of search window + * @return root found in the interval + */ +double get_minima(const std::function &f, double lim_a, + double lim_b) { + uint32_t iters = 0; + + if (lim_a > lim_b) { + std::swap(lim_a, lim_b); + } else if (std::abs(lim_a - lim_b) <= EPSILON) { + std::cerr << "Search range must be greater than " << EPSILON << "\n"; + return lim_a; + } + + // golden ratio value + const double M_GOLDEN_RATIO = (3.f - std::sqrt(5.f)) / 2.f; + + double v = lim_a + M_GOLDEN_RATIO * (lim_b - lim_a); + double u, w = v, x = v; + double fu, fv = f(v); + double fw = fv, fx = fv; + + double mid_point = (lim_a + lim_b) / 2.f; + double p = 0, q = 0, r = 0; + + double d, e = 0; + double tolerance, tolerance2; + + do { + mid_point = (lim_a + lim_b) / 2.f; + tolerance = EPSILON * std::abs(x); + tolerance2 = 2 * tolerance; + + if (std::abs(e) > tolerance2) { + // fit parabola + r = (x - w) * (fx - fv); + q = (x - v) * (fx - fw); + p = (x - v) * q - (x - w) * r; + q = 2.f * (q - r); + if (q > 0) + p = -p; + else + q = -q; + r = e; + e = d; + } + + if (std::abs(p) < std::abs(0.5 * q * r) && p < q * (lim_b - x)) { + // parabolic interpolation step + d = p / q; + u = x + d; + if (u - lim_a < tolerance2 || lim_b - u < tolerance2) + d = x < mid_point ? tolerance : -tolerance; + } else { + // golden section interpolation step + e = (x < mid_point ? lim_b : lim_a) - x; + d = M_GOLDEN_RATIO * e; + } + + // evaluate not too close to x + if (std::abs(d) >= tolerance) + u = d; + else if (d > 0) + u = tolerance; + else + u = -tolerance; + u += x; + fu = f(u); + + // update variables + if (fu <= fx) { + if (u < x) + lim_b = x; + else + lim_a = x; + v = w; + fv = fw; + w = x; + fw = fx; + x = u; + fx = fu; + } else { + if (u < x) + lim_a = u; + else + lim_b = u; + if (fu <= fw || x == w) { + v = w; + fv = fw; + w = u; + fw = fu; + } else if (fu <= fv || v == x || v == w) { + v = u; + fv = fu; + } + } + + iters++; + } while (std::abs(x - mid_point) > (tolerance - (lim_b - lim_a) / 2.f)); + + std::cout << " (iters: " << iters << ") "; + + return x; +} + +/** + * @brief Test function to find root for the function + * \f$f(x)= (x-2)^2\f$ + * in the interval \f$[1,5]\f$ + * \n Expected result = 2 + */ +void test1() { + // define the function to minimize as a lambda function + std::function f1 = [](double x) { + return (x - 2) * (x - 2); + }; + + std::cout << "Test 1.... "; + + double minima = get_minima(f1, -1, 5); + + std::cout << minima << "..."; + + assert(std::abs(minima - 2) < EPSILON * 2); + std::cout << "passed\n"; +} + +/** + * @brief Test function to find root for the function + * \f$f(x)= x^{\frac{1}{x}}\f$ + * in the interval \f$[-2,10]\f$ + * \n Expected result: \f$e\approx 2.71828182845904509\f$ + */ +void test2() { + // define the function to maximize as a lambda function + // since we are maximixing, we negated the function return value + std::function func = [](double x) { + return -std::pow(x, 1.f / x); + }; + + std::cout << "Test 2.... "; + + double minima = get_minima(func, -2, 5); + + std::cout << minima << " (" << M_E << ")..."; + + assert(std::abs(minima - M_E) < EPSILON * 2); + std::cout << "passed\n"; +} + +/** + * @brief Test function to find *maxima* for the function + * \f$f(x)= \cos x\f$ + * in the interval \f$[0,12]\f$ + * \n Expected result: \f$\pi\approx 3.14159265358979312\f$ + */ +void test3() { + // define the function to maximize as a lambda function + // since we are maximixing, we negated the function return value + std::function func = [](double x) { return std::cos(x); }; + + std::cout << "Test 3.... "; + + double minima = get_minima(func, -4, 12); + + std::cout << minima << " (" << M_PI << ")..."; + + assert(std::abs(minima - M_PI) < EPSILON * 2); + std::cout << "passed\n"; +} + +/** Main function */ +int main() { + std::cout.precision(18); + + std::cout << "Computations performed with machine epsilon: " << EPSILON + << "\n"; + + test1(); + test2(); + test3(); + + return 0; +} From 1c4026bca1e3fb0e4e1083c06f71653a0c59933c Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 22 Jun 2020 02:31:55 +0000 Subject: [PATCH 042/271] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 071ee8b95..55a97657c 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -129,6 +129,7 @@ ## Numerical Methods * [Bisection Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/bisection_method.cpp) + * [Brent Method Extrema](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/brent_method_extrema.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) From 957fe5c6ce1479342001fc141f5bbec0f60bfaff Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 21 Jun 2020 23:05:36 -0400 Subject: [PATCH 043/271] fixed doc for #define --- numerical_methods/brent_method_extrema.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/numerical_methods/brent_method_extrema.cpp b/numerical_methods/brent_method_extrema.cpp index 941c3b694..10b53b882 100644 --- a/numerical_methods/brent_method_extrema.cpp +++ b/numerical_methods/brent_method_extrema.cpp @@ -13,7 +13,7 @@ * * \author [Krishna Vedala](https://github.com/kvedala) */ -#define _USE_MATH_DEFINES //< required for MS Visual C++ +#define _USE_MATH_DEFINES ///< required for MS Visual C++ #include #include #include From ef957bae98dde4bed07186c72ab75083db53763f Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 21 Jun 2020 23:08:53 -0400 Subject: [PATCH 044/271] removed scaling during assert checks --- numerical_methods/brent_method_extrema.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/numerical_methods/brent_method_extrema.cpp b/numerical_methods/brent_method_extrema.cpp index 10b53b882..654a69451 100644 --- a/numerical_methods/brent_method_extrema.cpp +++ b/numerical_methods/brent_method_extrema.cpp @@ -152,7 +152,7 @@ void test1() { std::cout << minima << "..."; - assert(std::abs(minima - 2) < EPSILON * 2); + assert(std::abs(minima - 2) < EPSILON); std::cout << "passed\n"; } @@ -175,7 +175,7 @@ void test2() { std::cout << minima << " (" << M_E << ")..."; - assert(std::abs(minima - M_E) < EPSILON * 2); + assert(std::abs(minima - M_E) < EPSILON); std::cout << "passed\n"; } @@ -196,7 +196,7 @@ void test3() { std::cout << minima << " (" << M_PI << ")..."; - assert(std::abs(minima - M_PI) < EPSILON * 2); + assert(std::abs(minima - M_PI) < EPSILON); std::cout << "passed\n"; } From c563fc66947f424edea5ca55149bccbfee444701 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 22 Jun 2020 12:05:13 +0000 Subject: [PATCH 045/271] formatting source-code for 9bc80876e81aeb73c9490417f19cc1d91e60e0d1 --- math/sum_of_digits.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/math/sum_of_digits.cpp b/math/sum_of_digits.cpp index d5a705c48..cc2595e01 100644 --- a/math/sum_of_digits.cpp +++ b/math/sum_of_digits.cpp @@ -1,24 +1,24 @@ /** * Copyright 2020 @author iamnambiar - * + * * @file * \brief A C++ Program to find the Sum of Digits of input integer. */ -#include #include +#include /** * Function to find the sum of the digits of an integer. * @param num The integer. * @return Sum of the digits of the integer. - * + * * \detail * First the algorithm check whether the num is negative or positive, * if it is negative, then we neglect the negative sign. - * Next, the algorithm extract the last digit of num by dividing by 10 + * Next, the algorithm extract the last digit of num by dividing by 10 * and extracting the remainder and this is added to the sum. * The number is then divided by 10 to remove the last digit. - * This loop continues until num becomes 0. + * This loop continues until num becomes 0. */ int sum_of_digits(int num) { // If num is negative then negative sign is neglected. @@ -52,7 +52,7 @@ void test2() { } /** - * Function for testing the sum_of_digits() with + * Function for testing the sum_of_digits() with * all the test cases. */ void test() { @@ -64,7 +64,7 @@ void test() { /** * Main Function -*/ + */ int main() { test(); std::cout << "Success." << std::endl; From 58d5f3ea114d6a9336e67d9eef0ea3649000083c Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 22 Jun 2020 12:05:14 +0000 Subject: [PATCH 046/271] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 4989050df..a24342e3b 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -127,6 +127,7 @@ * [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) + * [Sum Of Digits](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/sum_of_digits.cpp) ## Numerical Methods * [Bisection Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/bisection_method.cpp) From bebb76e5570a4c496f29fb424f7044df07193074 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Mon, 22 Jun 2020 16:19:17 -0400 Subject: [PATCH 047/271] make 'a' signed --- math/large_number.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/math/large_number.h b/math/large_number.h index bffb764d0..51f8cc528 100644 --- a/math/large_number.h +++ b/math/large_number.h @@ -53,7 +53,7 @@ class large_number { /**< 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'; + char a = number_str[i - 1] - '0'; if (a >= 0 && a <= 9) _digits.push_back(a); } From 8862859c18a1017be49d8f960f77abd18c75f9b0 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Mon, 22 Jun 2020 16:19:59 -0400 Subject: [PATCH 048/271] remove const identifier --- math/large_number.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/math/large_number.h b/math/large_number.h index 51f8cc528..521199862 100644 --- a/math/large_number.h +++ b/math/large_number.h @@ -127,7 +127,7 @@ class large_number { /** * Get number of digits in the number **/ - const size_t num_digits() const { return _digits.size(); } + size_t num_digits() const { return _digits.size(); } /** * operator over load to access the From fb82e9050d7708fa0c3b30e5d96c95c21ff520f5 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Mon, 22 Jun 2020 16:20:27 -0400 Subject: [PATCH 049/271] remove const identifier for function --- math/large_number.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/math/large_number.h b/math/large_number.h index 521199862..57154f57b 100644 --- a/math/large_number.h +++ b/math/large_number.h @@ -245,7 +245,7 @@ class large_number { /** * returns i^th digit as an ASCII character **/ - const char digit_char(size_t i) const { + char digit_char(size_t i) const { return _digits[num_digits() - i - 1] + '0'; } From 8736dce71a47f44c5fc62d32287245c4f0e1d790 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Mon, 22 Jun 2020 16:21:57 -0400 Subject: [PATCH 050/271] make multiplication 64-bit --- math/large_number.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/math/large_number.h b/math/large_number.h index 57154f57b..421d8c303 100644 --- a/math/large_number.h +++ b/math/large_number.h @@ -264,7 +264,7 @@ class large_number { size_t i; uint64_t carry = 0, temp; for (i = 0; i < this->num_digits(); i++) { - temp = (*this)[i] * n; + temp = static_cast((*this)[i]) * n; temp += carry; if (temp < 10) { carry = 0; From fce7e22d8f142c1ad9b73317c64c489ae0eba802 Mon Sep 17 00:00:00 2001 From: liushubin lwx470335 Date: Tue, 23 Jun 2020 09:06:00 +0800 Subject: [PATCH 051/271] =?UTF-8?q?binary=20search=20tree=20insert?= =?UTF-8?q?=EF=BC=88=EF=BC=89=20function=20modify=E3=80=82=20insert=20the?= =?UTF-8?q?=20greater=20value=20to=20right=EF=BC=8Csmaller=20value=20to=20?= =?UTF-8?q?left=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- data_structures/binary_search_tree.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data_structures/binary_search_tree.cpp b/data_structures/binary_search_tree.cpp index 947bb53d8..3cc7d09fb 100644 --- a/data_structures/binary_search_tree.cpp +++ b/data_structures/binary_search_tree.cpp @@ -43,7 +43,7 @@ void Insert(node *n, int x) { temp->val = x; temp->left = NULL; temp->right = NULL; - n->left = temp; + n->right = temp; } else { Insert(n->right, x); } From 1158e626cb8fe76d6b3de9fdd7bd39672e62460a Mon Sep 17 00:00:00 2001 From: Tajmeet Singh Date: Tue, 23 Jun 2020 14:29:48 +0100 Subject: [PATCH 052/271] feat: Added a class implemetation of complex numbers along with implementation of all (most) binary operations involved with complex numbers. --- math/complex_numbers.cpp | 183 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 183 insertions(+) create mode 100644 math/complex_numbers.cpp diff --git a/math/complex_numbers.cpp b/math/complex_numbers.cpp new file mode 100644 index 000000000..8d778d735 --- /dev/null +++ b/math/complex_numbers.cpp @@ -0,0 +1,183 @@ +/** + * Copyright 2020 @author tjgurwara99 + * @file + * + * A basic implementation of Complex Number field as a class with operators overloaded to accommodate (mathematical) field operations. + */ + +#include +#include +#include + +/** + * Class Complex to represent complex numbers as a field. + */ +class Complex { + // The real value of the complex number + double re; + // The imaginary value of the complex number + double im; + + public: + /** + * Complex Constructor which initialises the complex number which takes two arguments. + * @param x The real value of the complex number. + * @param y The imaginary value of the complex number. + */ + Complex(double x, double y) { + this->re = x; + this->im = y; + } + + /** + * Complex Constructor which initialises the complex number with no arguments. + */ + Complex() { + Complex(0.0,0.0); + } + + /** + * Member function (getter) to access the class' re value. + */ + double real() const { + return this->re; + } + + /** + * Member function (getter) to access the class' im value. + */ + double imag() const { + return this->im; + } + + /** + * Member function to which gives the absolute value (modulus) of our complex number + * @return \f$ \sqrt{z \dot \bar{z} \f$ where \f$ z \f$ is our complex number. + */ + double abs() const { + return std::sqrt(this->re*this->re + this->im*this->im); + } + + /** + * Operator overload to be able to add two complex numbers. + * @param other The other number that is added to the current number. + * @return result current number plus other number + */ + Complex operator+(const Complex& other) { + Complex result(this->re + other.re, this->im + other.im); + return result; + } + + /** + * Operator overload to be able to subtract two complex numbers. + * @param other The other number being subtracted from the current number. + * @return result current number subtract other number + */ + Complex operator-(const Complex& other) { + Complex result(this->re - other.re, this->im - other.im); + return result; + } + + /** + * Operator overload to be able to multiple two complex numbers. + * @param other The other number to multiply the current number to. + * @return result current number times other number. + */ + Complex operator*(const Complex& other) { + Complex result(this->re * other.re - this->im * other.im, + this->re * other.im + this->im * other.re); + return result; + } + + /** + * Operator overload of the BITWISE NOT which gives us the conjugate of our complex number. + * NOTE: This is overloading the BITWISE operator but its not a BITWISE operation in this definition. + * @return result The conjugate of our complex number. + */ + Complex operator~() const { + Complex result(this->re, -(this->im)); + return result; + } + + /** + * Operator overload to be able to divide two complex numbers. This function would throw an exception if the other number is zero. + * @param other The other number we divide our number by. + * @return result Current number divided by other number. + */ + Complex operator/(const Complex& other) { + Complex result = *this * ~other; + double denominator = other.abs() * other.abs(); + if (denominator != 0) { + result = Complex(result.real() / denominator, result.imag() / denominator); + return result; + } + else { + throw std::invalid_argument("Undefined Value"); + } + } +}; + +/** + * Logical Equal overload for our Complex class. + * @param a Left hand side of our expression + * @param b Right hand side of our expression + * @return 'True' If real and imaginary parts of a and b are same + * @return 'False' Otherwise. + */ +bool operator==(const Complex& a, const Complex& b) { + double del_real = a.real() - b.real(); + double del_imag = a.imag() - b.imag(); + return ((del_real <= 1e-15 && del_real >= - 1e-15 ) && (del_imag <= 1e-15 && del_imag >= - 1e-15)); +} + +/** + * Overloaded insersion operator to accommodate the printing of our complex number in their standard form. + * @param os The console stream + * @param num The complex number. + */ +std::ostream& operator<<(std::ostream& os, const Complex& num) { + os << num.real(); + if (num.imag() < 0) { + os << " - " << -num.imag(); + } + else { + os << " + " << num.imag(); + } + os << "i"; + return os; +} + +/** + * Tests Function + */ +void tests() { + Complex num1(1,1), num2(1,1); + // Test for addition + assert(((void)"1 + 1i + 1 + 1i is equal to 2 + 2i but the addition doesn't add up \n", + (num1 + num2) == Complex(2,2))); + std::cout << "First test passes." << std::endl; + // Test for subtraction + assert(((void)"1 + 1i - 1 - 1i is equal to 0 but the program says otherwise. \n", + (num1 - num2) == Complex(0,0))); + std::cout << "Second test passes." << std::endl; + // Test for multiplication + assert(((void)"(1 + 1i) * (1 + 1i) is equal to 2i but the program says otherwise. \n", + (num1 * num2) == Complex(0,2))); + std::cout << "Third test passes." << std::endl; + // Test for division + assert(((void)"(1 + 1i) / (1 + 1i) is equal to 1 but the program says otherwise.\n", + (num1 / num2) == Complex(1,0))); + std::cout << "Fourth test passes." << std::endl; + // Test for conjugates + assert(((void)"(1 + 1i) has a conjugate which is equal to (1 - 1i) but the program says otherwise.\n", + ~num1 == Complex(1,-1))); + std::cout << "Fifth test passes." << std::endl; + +} +/** + * Main function + */ +int main() { + tests(); + return 0; +} From f4fa366da501e41cac6bd274df4a02fc345d0c3b Mon Sep 17 00:00:00 2001 From: Tajmeet Singh Date: Tue, 23 Jun 2020 14:32:08 +0100 Subject: [PATCH 053/271] docs: Fixed some clangformat issues with the documentation --- math/complex_numbers.cpp | 98 +++++++++++++++++++++------------------- 1 file changed, 52 insertions(+), 46 deletions(-) diff --git a/math/complex_numbers.cpp b/math/complex_numbers.cpp index 8d778d735..9a381b125 100644 --- a/math/complex_numbers.cpp +++ b/math/complex_numbers.cpp @@ -2,11 +2,12 @@ * Copyright 2020 @author tjgurwara99 * @file * - * A basic implementation of Complex Number field as a class with operators overloaded to accommodate (mathematical) field operations. + * A basic implementation of Complex Number field as a class with operators + * overloaded to accommodate (mathematical) field operations. */ -#include #include +#include #include /** @@ -18,9 +19,10 @@ class Complex { // The imaginary value of the complex number double im; - public: + public: /** - * Complex Constructor which initialises the complex number which takes two arguments. + * Complex Constructor which initialises the complex number which takes two + * arguments. * @param x The real value of the complex number. * @param y The imaginary value of the complex number. */ @@ -28,34 +30,31 @@ class Complex { this->re = x; this->im = y; } - + /** - * Complex Constructor which initialises the complex number with no arguments. + * Complex Constructor which initialises the complex number with no + * arguments. */ - Complex() { - Complex(0.0,0.0); - } + Complex() { Complex(0.0, 0.0); } /** * Member function (getter) to access the class' re value. */ - double real() const { - return this->re; - } + double real() const { return this->re; } /** * Member function (getter) to access the class' im value. */ - double imag() const { - return this->im; - } + double imag() const { return this->im; } /** - * Member function to which gives the absolute value (modulus) of our complex number - * @return \f$ \sqrt{z \dot \bar{z} \f$ where \f$ z \f$ is our complex number. + * Member function to which gives the absolute value (modulus) of our + * complex number + * @return \f$ \sqrt{z \dot \bar{z}} \f$ where \f$ z \f$ is our complex + * number. */ double abs() const { - return std::sqrt(this->re*this->re + this->im*this->im); + return std::sqrt(this->re * this->re + this->im * this->im); } /** @@ -63,7 +62,7 @@ class Complex { * @param other The other number that is added to the current number. * @return result current number plus other number */ - Complex operator+(const Complex& other) { + Complex operator+(const Complex &other) { Complex result(this->re + other.re, this->im + other.im); return result; } @@ -73,7 +72,7 @@ class Complex { * @param other The other number being subtracted from the current number. * @return result current number subtract other number */ - Complex operator-(const Complex& other) { + Complex operator-(const Complex &other) { Complex result(this->re - other.re, this->im - other.im); return result; } @@ -83,15 +82,16 @@ class Complex { * @param other The other number to multiply the current number to. * @return result current number times other number. */ - Complex operator*(const Complex& other) { + Complex operator*(const Complex &other) { Complex result(this->re * other.re - this->im * other.im, this->re * other.im + this->im * other.re); return result; } /** - * Operator overload of the BITWISE NOT which gives us the conjugate of our complex number. - * NOTE: This is overloading the BITWISE operator but its not a BITWISE operation in this definition. + * Operator overload of the BITWISE NOT which gives us the conjugate of our + * complex number. NOTE: This is overloading the BITWISE operator but its + * not a BITWISE operation in this definition. * @return result The conjugate of our complex number. */ Complex operator~() const { @@ -100,18 +100,19 @@ class Complex { } /** - * Operator overload to be able to divide two complex numbers. This function would throw an exception if the other number is zero. + * Operator overload to be able to divide two complex numbers. This function + * would throw an exception if the other number is zero. * @param other The other number we divide our number by. * @return result Current number divided by other number. */ - Complex operator/(const Complex& other) { + Complex operator/(const Complex &other) { Complex result = *this * ~other; double denominator = other.abs() * other.abs(); if (denominator != 0) { - result = Complex(result.real() / denominator, result.imag() / denominator); + result = Complex(result.real() / denominator, + result.imag() / denominator); return result; - } - else { + } else { throw std::invalid_argument("Undefined Value"); } } @@ -124,23 +125,24 @@ class Complex { * @return 'True' If real and imaginary parts of a and b are same * @return 'False' Otherwise. */ -bool operator==(const Complex& a, const Complex& b) { +bool operator==(const Complex &a, const Complex &b) { double del_real = a.real() - b.real(); double del_imag = a.imag() - b.imag(); - return ((del_real <= 1e-15 && del_real >= - 1e-15 ) && (del_imag <= 1e-15 && del_imag >= - 1e-15)); + return ((del_real <= 1e-15 && del_real >= -1e-15) && + (del_imag <= 1e-15 && del_imag >= -1e-15)); } /** - * Overloaded insersion operator to accommodate the printing of our complex number in their standard form. + * Overloaded insersion operator to accommodate the printing of our complex + * number in their standard form. * @param os The console stream * @param num The complex number. */ -std::ostream& operator<<(std::ostream& os, const Complex& num) { +std::ostream &operator<<(std::ostream &os, const Complex &num) { os << num.real(); if (num.imag() < 0) { os << " - " << -num.imag(); - } - else { + } else { os << " + " << num.imag(); } os << "i"; @@ -151,28 +153,32 @@ std::ostream& operator<<(std::ostream& os, const Complex& num) { * Tests Function */ void tests() { - Complex num1(1,1), num2(1,1); + Complex num1(1, 1), num2(1, 1); // Test for addition - assert(((void)"1 + 1i + 1 + 1i is equal to 2 + 2i but the addition doesn't add up \n", - (num1 + num2) == Complex(2,2))); + assert(((void)"1 + 1i + 1 + 1i is equal to 2 + 2i but the addition doesn't " + "add up \n", + (num1 + num2) == Complex(2, 2))); std::cout << "First test passes." << std::endl; // Test for subtraction - assert(((void)"1 + 1i - 1 - 1i is equal to 0 but the program says otherwise. \n", - (num1 - num2) == Complex(0,0))); + assert(((void)"1 + 1i - 1 - 1i is equal to 0 but the program says " + "otherwise. \n", + (num1 - num2) == Complex(0, 0))); std::cout << "Second test passes." << std::endl; // Test for multiplication - assert(((void)"(1 + 1i) * (1 + 1i) is equal to 2i but the program says otherwise. \n", - (num1 * num2) == Complex(0,2))); + assert(((void)"(1 + 1i) * (1 + 1i) is equal to 2i but the program says " + "otherwise. \n", + (num1 * num2) == Complex(0, 2))); std::cout << "Third test passes." << std::endl; // Test for division - assert(((void)"(1 + 1i) / (1 + 1i) is equal to 1 but the program says otherwise.\n", - (num1 / num2) == Complex(1,0))); + assert(((void)"(1 + 1i) / (1 + 1i) is equal to 1 but the program says " + "otherwise.\n", + (num1 / num2) == Complex(1, 0))); std::cout << "Fourth test passes." << std::endl; // Test for conjugates - assert(((void)"(1 + 1i) has a conjugate which is equal to (1 - 1i) but the program says otherwise.\n", - ~num1 == Complex(1,-1))); + assert(((void)"(1 + 1i) has a conjugate which is equal to (1 - 1i) but the " + "program says otherwise.\n", + ~num1 == Complex(1, -1))); std::cout << "Fifth test passes." << std::endl; - } /** * Main function From 8969047d3ff8fe6f08966f0a465b239a4fdc16a0 Mon Sep 17 00:00:00 2001 From: Tajmeet Singh Date: Tue, 23 Jun 2020 14:41:46 +0100 Subject: [PATCH 054/271] fix: Added missing header --- math/complex_numbers.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/math/complex_numbers.cpp b/math/complex_numbers.cpp index 9a381b125..4505b5677 100644 --- a/math/complex_numbers.cpp +++ b/math/complex_numbers.cpp @@ -9,6 +9,7 @@ #include #include #include +#include /** * Class Complex to represent complex numbers as a field. From 626ab310955b5417675b0487a8d4f79f1786d355 Mon Sep 17 00:00:00 2001 From: Tajmeet Singh Date: Tue, 23 Jun 2020 14:53:09 +0100 Subject: [PATCH 055/271] fix: incorrect constructor delegation --- math/complex_numbers.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/math/complex_numbers.cpp b/math/complex_numbers.cpp index 4505b5677..10e50b22a 100644 --- a/math/complex_numbers.cpp +++ b/math/complex_numbers.cpp @@ -36,7 +36,10 @@ class Complex { * Complex Constructor which initialises the complex number with no * arguments. */ - Complex() { Complex(0.0, 0.0); } + Complex() { + this->re = 0.0; + this.im = 0.0; + } /** * Member function (getter) to access the class' re value. From c419e1f7882298fb98567898f82482fd2cd4c29a Mon Sep 17 00:00:00 2001 From: Tajmeet Singh Date: Tue, 23 Jun 2020 14:54:10 +0100 Subject: [PATCH 056/271] fix: arrow operator instead of dot --- math/complex_numbers.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/math/complex_numbers.cpp b/math/complex_numbers.cpp index 10e50b22a..189d0b831 100644 --- a/math/complex_numbers.cpp +++ b/math/complex_numbers.cpp @@ -38,7 +38,7 @@ class Complex { */ Complex() { this->re = 0.0; - this.im = 0.0; + this->im = 0.0; } /** From 1708de2296204efd863e485068a96078ce76f5af Mon Sep 17 00:00:00 2001 From: Tajmeet Singh Date: Tue, 23 Jun 2020 16:23:49 +0100 Subject: [PATCH 057/271] fix: fixed all pull request suggestions --- math/complex_numbers.cpp | 88 +++++++++++++++++++++++++++++----------- 1 file changed, 64 insertions(+), 24 deletions(-) diff --git a/math/complex_numbers.cpp b/math/complex_numbers.cpp index 189d0b831..4ae5c493b 100644 --- a/math/complex_numbers.cpp +++ b/math/complex_numbers.cpp @@ -6,10 +6,11 @@ * overloaded to accommodate (mathematical) field operations. */ +#include #include +#include #include #include -#include /** * Class Complex to represent complex numbers as a field. @@ -27,19 +28,13 @@ class Complex { * @param x The real value of the complex number. * @param y The imaginary value of the complex number. */ - Complex(double x, double y) { - this->re = x; - this->im = y; - } + explicit Complex(double x = 0.f, double y = 0.f) : re(x), im(y) { ; } /** - * Complex Constructor which initialises the complex number with no - * arguments. + * Copy Constructor + * @param other The other number to equate our number to. */ - Complex() { - this->re = 0.0; - this->im = 0.0; - } + Complex(const Complex &other) : re(other.real()), im(other.imag()) { ; } /** * Member function (getter) to access the class' re value. @@ -61,6 +56,26 @@ class Complex { return std::sqrt(this->re * this->re + this->im * this->im); } + /** + * Member function which gives the argument of our complex number. + * @return Argument of our Complex number. + */ + double arg() const { + if (this->re > 0) { + return std::atan(this->im / this->re); + } else if (this->re < 0 && this->im >= 0) { + return std::atan(this->im / this->re) + M_PI; + } else if (this->re < 0 && this->im < 0) { + return std::atan(this->im / this->re) - M_PI; + } else if (this->re == 0 && this->im > 0) { + return M_PI / 2; + } else if (this->re == 0 && this->im < 0) { + return -M_PI / 2; + } else { + throw std::invalid_argument("Undefined Value"); + } + } + /** * Operator overload to be able to add two complex numbers. * @param other The other number that is added to the current number. @@ -111,7 +126,8 @@ class Complex { */ Complex operator/(const Complex &other) { Complex result = *this * ~other; - double denominator = other.abs() * other.abs(); + double denominator = + other.real() * other.real() + other.imag() * other.imag(); if (denominator != 0) { result = Complex(result.real() / denominator, result.imag() / denominator); @@ -120,6 +136,16 @@ class Complex { throw std::invalid_argument("Undefined Value"); } } + + /** + * Operator overload to be able to copy RHS instance of Complex to LHS + * instance of Complex + */ + const Complex &operator=(const Complex &other) { + this->re = other.real(); + this->im = other.imag(); + return *this; + } }; /** @@ -130,10 +156,7 @@ class Complex { * @return 'False' Otherwise. */ bool operator==(const Complex &a, const Complex &b) { - double del_real = a.real() - b.real(); - double del_imag = a.imag() - b.imag(); - return ((del_real <= 1e-15 && del_real >= -1e-15) && - (del_imag <= 1e-15 && del_imag >= -1e-15)); + return a.real() == b.real() && a.imag() == b.imag(); } /** @@ -143,13 +166,13 @@ bool operator==(const Complex &a, const Complex &b) { * @param num The complex number. */ std::ostream &operator<<(std::ostream &os, const Complex &num) { - os << num.real(); + os << "(" << num.real(); if (num.imag() < 0) { os << " - " << -num.imag(); } else { os << " + " << num.imag(); } - os << "i"; + os << "i)"; return os; } @@ -158,32 +181,49 @@ std::ostream &operator<<(std::ostream &os, const Complex &num) { */ void tests() { Complex num1(1, 1), num2(1, 1); + std::complex cnum1(1, 1), cnum2(1, 1); // Test for addition assert(((void)"1 + 1i + 1 + 1i is equal to 2 + 2i but the addition doesn't " "add up \n", - (num1 + num2) == Complex(2, 2))); + ((num1 + num2).real() == (cnum1 + cnum2).real() && + (num1 + num2).imag() == (cnum1 + cnum2).imag()))); std::cout << "First test passes." << std::endl; // Test for subtraction assert(((void)"1 + 1i - 1 - 1i is equal to 0 but the program says " "otherwise. \n", - (num1 - num2) == Complex(0, 0))); + ((num1 - num2).real() == (cnum1 - cnum2).real() && + (num1 - num2).imag() == (cnum1 - cnum2).imag()))); std::cout << "Second test passes." << std::endl; // Test for multiplication assert(((void)"(1 + 1i) * (1 + 1i) is equal to 2i but the program says " "otherwise. \n", - (num1 * num2) == Complex(0, 2))); + ((num1 * num2).real() == (cnum1 * cnum2).real() && + (num1 * num2).imag() == (cnum1 * cnum2).imag()))); std::cout << "Third test passes." << std::endl; // Test for division assert(((void)"(1 + 1i) / (1 + 1i) is equal to 1 but the program says " "otherwise.\n", - (num1 / num2) == Complex(1, 0))); + ((num1 / num2).real() == (cnum1 / cnum2).real() && + (num1 / num2).imag() == (cnum1 / cnum2).imag()))); std::cout << "Fourth test passes." << std::endl; // Test for conjugates assert(((void)"(1 + 1i) has a conjugate which is equal to (1 - 1i) but the " "program says otherwise.\n", - ~num1 == Complex(1, -1))); - std::cout << "Fifth test passes." << std::endl; + ((~num1).real() == std::conj(cnum1).real() && + (~num1).imag() == std::conj(cnum1).imag()))); + std::cout << "Fifth test passes.\n"; + // Test for Argument of our complex number + assert(((void)"(1 + 1i) has argument PI / 4 but the program differs from " + "the std::complex result.\n", + (num1.arg() == std::arg(cnum1)))); + std::cout << "Sixth test passes.\n"; + // Test for absolute value of our complex number + assert(((void)"(1 + 1i) has absolute value sqrt(2) but the program differs " + "from the std::complex result. \n", + (num1.abs() == std::abs(cnum1)))); + std::cout << "Seventh test passes.\n"; } + /** * Main function */ From 52f918a4ffb11aec4fbc4b22d026e2e0a39b867d Mon Sep 17 00:00:00 2001 From: Tajmeet Singh Date: Tue, 23 Jun 2020 16:33:54 +0100 Subject: [PATCH 058/271] fix: Fixed issue with Windows CI test - M_PI doesn't work on Windows CI --- math/complex_numbers.cpp | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/math/complex_numbers.cpp b/math/complex_numbers.cpp index 4ae5c493b..9d6ede15d 100644 --- a/math/complex_numbers.cpp +++ b/math/complex_numbers.cpp @@ -12,6 +12,11 @@ #include #include +/** + * Global constant for pi to work with Windows environment + */ +const double pi = 3.14159265358979323846; + /** * Class Complex to represent complex numbers as a field. */ @@ -64,13 +69,13 @@ class Complex { if (this->re > 0) { return std::atan(this->im / this->re); } else if (this->re < 0 && this->im >= 0) { - return std::atan(this->im / this->re) + M_PI; + return std::atan(this->im / this->re) + pi; } else if (this->re < 0 && this->im < 0) { - return std::atan(this->im / this->re) - M_PI; + return std::atan(this->im / this->re) - pi; } else if (this->re == 0 && this->im > 0) { - return M_PI / 2; + return pi / 2; } else if (this->re == 0 && this->im < 0) { - return -M_PI / 2; + return -pi / 2; } else { throw std::invalid_argument("Undefined Value"); } From 2fe7e4add0d4939d6553552d0714ec99d93f1683 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Tue, 23 Jun 2020 11:43:28 -0400 Subject: [PATCH 059/271] fix function return + add docs --- data_structures/list_array.cpp | 75 +++++++++++++++++++--------------- 1 file changed, 41 insertions(+), 34 deletions(-) diff --git a/data_structures/list_array.cpp b/data_structures/list_array.cpp index c796ffef9..4c6855a51 100644 --- a/data_structures/list_array.cpp +++ b/data_structures/list_array.cpp @@ -1,5 +1,9 @@ +/** + * @file list_array.cpp + * @todo Add documentation + * @warning The sorting algorithm is erroneous + */ #include -using namespace std; struct list { int data[50]; @@ -17,6 +21,9 @@ struct list { return (BinarySearch(array, first, mid - 1, x)); else if (x > array[mid]) return (BinarySearch(array, mid + 1, last, x)); + + std::cerr << __func__ << ":" << __LINE__ << ": Undefined condition\n"; + return -1; } int LinarSearch(int *array, int x) { @@ -41,9 +48,9 @@ struct list { } if (pos != -1) { - cout << "\nElement found at position : " << pos; + std::cout << "\nElement found at position : " << pos; } else { - cout << "\nElement not found"; + std::cout << "\nElement not found"; } return pos; } @@ -69,7 +76,7 @@ struct list { void insert(int x) { if (!isSorted) { if (top == 49) { - cout << "\nOverflow"; + std::cout << "\nOverflow"; } else { data[top] = x; top++; @@ -99,7 +106,7 @@ struct list { void Remove(int x) { int pos = Search(x); - cout << "\n" << data[pos] << " deleted"; + std::cout << "\n" << data[pos] << " deleted"; for (int i = pos; i < top; i++) { data[i] = data[i + 1]; } @@ -108,7 +115,7 @@ struct list { void Show() { for (int i = 0; i < top; i++) { - cout << data[i] << "\t"; + std::cout << data[i] << "\t"; } } }; @@ -118,35 +125,35 @@ int main() { 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; + std::cout << "\n1.Insert"; + std::cout << "\n2.Delete"; + std::cout << "\n3.Search"; + std::cout << "\n4.Sort"; + std::cout << "\n5.Print"; + std::cout << "\n\nEnter Your Choice : "; + std::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; + case 1: + std::cout << "\nEnter the element to be inserted : "; + std::cin >> x; + L.insert(x); + break; + case 2: + std::cout << "\nEnter the element to be removed : "; + std::cin >> x; + L.Remove(x); + break; + case 3: + std::cout << "\nEnter the element to be searched : "; + std::cin >> x; + L.Search(x); + break; + case 4: + L.Sort(); + break; + case 5: + L.Show(); + break; } } while (choice != 0); return 0; From 497ede21e0d29aa2a8b856289dfa24dec3751dc2 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Tue, 23 Jun 2020 11:45:16 -0400 Subject: [PATCH 060/271] fix function return --- data_structures/trie_tree.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/data_structures/trie_tree.cpp b/data_structures/trie_tree.cpp index 66b67fbc0..a613ebd8f 100644 --- a/data_structures/trie_tree.cpp +++ b/data_structures/trie_tree.cpp @@ -74,6 +74,10 @@ bool deleteString(trie* root, std::string str, int index) { return true; } } + + /* should not return here */ + std::cout << __func__ << ":" << __LINE__ << "Should not reach this line\n"; + return false; } int main() { From 56cb22cd444aa1c24dffbbdd2356945dc873d362 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 23 Jun 2020 15:46:52 +0000 Subject: [PATCH 061/271] formatting source-code for 497ede21e0d29aa2a8b856289dfa24dec3751dc2 --- data_structures/list_array.cpp | 42 +++++++++++++++++----------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/data_structures/list_array.cpp b/data_structures/list_array.cpp index 4c6855a51..c49e17e06 100644 --- a/data_structures/list_array.cpp +++ b/data_structures/list_array.cpp @@ -133,27 +133,27 @@ int main() { std::cout << "\n\nEnter Your Choice : "; std::cin >> choice; switch (choice) { - case 1: - std::cout << "\nEnter the element to be inserted : "; - std::cin >> x; - L.insert(x); - break; - case 2: - std::cout << "\nEnter the element to be removed : "; - std::cin >> x; - L.Remove(x); - break; - case 3: - std::cout << "\nEnter the element to be searched : "; - std::cin >> x; - L.Search(x); - break; - case 4: - L.Sort(); - break; - case 5: - L.Show(); - break; + case 1: + std::cout << "\nEnter the element to be inserted : "; + std::cin >> x; + L.insert(x); + break; + case 2: + std::cout << "\nEnter the element to be removed : "; + std::cin >> x; + L.Remove(x); + break; + case 3: + std::cout << "\nEnter the element to be searched : "; + std::cin >> x; + L.Search(x); + break; + case 4: + L.Sort(); + break; + case 5: + L.Show(); + break; } } while (choice != 0); return 0; From 8575e21e73d5286b1c05cbe8b70f77997f0b0a2f Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Tue, 23 Jun 2020 11:50:12 -0400 Subject: [PATCH 062/271] fix lint errors --- data_structures/list_array.cpp | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/data_structures/list_array.cpp b/data_structures/list_array.cpp index c49e17e06..24b04867b 100644 --- a/data_structures/list_array.cpp +++ b/data_structures/list_array.cpp @@ -41,9 +41,7 @@ struct list { if (isSorted) { pos = BinarySearch(data, 0, top - 1, x); - } - - else { + } else { pos = LinarSearch(data, x); } @@ -81,9 +79,7 @@ struct list { data[top] = x; top++; } - } - - else { + } else { int pos = 0; for (int i = 0; i < top - 1; i++) { From b9658104cb024a1044f2b621566dadf9a184f8a2 Mon Sep 17 00:00:00 2001 From: Tajmeet Singh Date: Tue, 23 Jun 2020 17:56:53 +0100 Subject: [PATCH 063/271] fix: Taken onboard some suggested changes --- math/complex_numbers.cpp | 70 ++++++++++++++++++++-------------------- 1 file changed, 35 insertions(+), 35 deletions(-) diff --git a/math/complex_numbers.cpp b/math/complex_numbers.cpp index 9d6ede15d..03dfe1069 100644 --- a/math/complex_numbers.cpp +++ b/math/complex_numbers.cpp @@ -12,11 +12,6 @@ #include #include -/** - * Global constant for pi to work with Windows environment - */ -const double pi = 3.14159265358979323846; - /** * Class Complex to represent complex numbers as a field. */ @@ -30,8 +25,8 @@ class Complex { /** * Complex Constructor which initialises the complex number which takes two * arguments. - * @param x The real value of the complex number. - * @param y The imaginary value of the complex number. + * @param x The real value of the complex number (optional). + * @param y The imaginary value of the complex number (optional). */ explicit Complex(double x = 0.f, double y = 0.f) : re(x), im(y) { ; } @@ -63,23 +58,9 @@ class Complex { /** * Member function which gives the argument of our complex number. - * @return Argument of our Complex number. + * @return Argument of our Complex number in radians. */ - double arg() const { - if (this->re > 0) { - return std::atan(this->im / this->re); - } else if (this->re < 0 && this->im >= 0) { - return std::atan(this->im / this->re) + pi; - } else if (this->re < 0 && this->im < 0) { - return std::atan(this->im / this->re) - pi; - } else if (this->re == 0 && this->im > 0) { - return pi / 2; - } else if (this->re == 0 && this->im < 0) { - return -pi / 2; - } else { - throw std::invalid_argument("Undefined Value"); - } - } + double arg() const { return atan2(this->im, this->re); } /** * Operator overload to be able to add two complex numbers. @@ -181,41 +162,60 @@ std::ostream &operator<<(std::ostream &os, const Complex &num) { return os; } +/** + * Function to get random numbers to generate our complex numbers for test + */ +double get_rand() { return (std::rand() % 100 - 50) / 100.f; } + /** * Tests Function */ void tests() { - Complex num1(1, 1), num2(1, 1); - std::complex cnum1(1, 1), cnum2(1, 1); + std::srand(std::time(nullptr)); + double x1 = get_rand(), y1 = get_rand(), x2 = get_rand(), y2 = get_rand(); + Complex num1(x1, y1), num2(x2, y2); + std::complex cnum1(x1, y1), cnum2(x2, y2); + Complex result; + std::complex expected; // Test for addition + result = num1 + num2; + expected = cnum1 + cnum2; assert(((void)"1 + 1i + 1 + 1i is equal to 2 + 2i but the addition doesn't " "add up \n", - ((num1 + num2).real() == (cnum1 + cnum2).real() && - (num1 + num2).imag() == (cnum1 + cnum2).imag()))); + (result.real() == expected.real() && + result.imag() == expected.imag()))); std::cout << "First test passes." << std::endl; // Test for subtraction + result = num1 - num2; + expected = cnum1 - cnum2; assert(((void)"1 + 1i - 1 - 1i is equal to 0 but the program says " "otherwise. \n", - ((num1 - num2).real() == (cnum1 - cnum2).real() && - (num1 - num2).imag() == (cnum1 - cnum2).imag()))); + (result.real() == expected.real() && + result.imag() == expected.imag()))); std::cout << "Second test passes." << std::endl; // Test for multiplication + result = num1 * num2; + expected = cnum1 * cnum2; assert(((void)"(1 + 1i) * (1 + 1i) is equal to 2i but the program says " "otherwise. \n", - ((num1 * num2).real() == (cnum1 * cnum2).real() && - (num1 * num2).imag() == (cnum1 * cnum2).imag()))); + (result.real() == expected.real() && + result.imag() == expected.imag()))); std::cout << "Third test passes." << std::endl; // Test for division + result = num1 / num2; + expected = cnum1 / cnum2; assert(((void)"(1 + 1i) / (1 + 1i) is equal to 1 but the program says " "otherwise.\n", - ((num1 / num2).real() == (cnum1 / cnum2).real() && - (num1 / num2).imag() == (cnum1 / cnum2).imag()))); + (result.real() == expected.real() && + result.imag() == expected.imag()))); std::cout << "Fourth test passes." << std::endl; // Test for conjugates + result = ~num1; + expected = std::conj(cnum1); assert(((void)"(1 + 1i) has a conjugate which is equal to (1 - 1i) but the " "program says otherwise.\n", - ((~num1).real() == std::conj(cnum1).real() && - (~num1).imag() == std::conj(cnum1).imag()))); + (result.real() == expected.real() && + result.imag() == expected.imag()))); std::cout << "Fifth test passes.\n"; // Test for Argument of our complex number assert(((void)"(1 + 1i) has argument PI / 4 but the program differs from " From 907b8298309d898b6d3b967a9ba5b3fc62a6afe8 Mon Sep 17 00:00:00 2001 From: Tajmeet Singh Date: Tue, 23 Jun 2020 18:00:53 +0100 Subject: [PATCH 064/271] docs: copyright message --- math/complex_numbers.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/math/complex_numbers.cpp b/math/complex_numbers.cpp index 03dfe1069..b2353d785 100644 --- a/math/complex_numbers.cpp +++ b/math/complex_numbers.cpp @@ -1,5 +1,5 @@ /** - * Copyright 2020 @author tjgurwara99 + * @author tjgurwara99 * @file * * A basic implementation of Complex Number field as a class with operators From ce81700380e656ce6ec8898c7e87e3669ec9e5c3 Mon Sep 17 00:00:00 2001 From: Tajmeet Singh Date: Tue, 23 Jun 2020 18:04:42 +0100 Subject: [PATCH 065/271] fix: added missing header for std::time --- math/complex_numbers.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/math/complex_numbers.cpp b/math/complex_numbers.cpp index b2353d785..43b1d5fda 100644 --- a/math/complex_numbers.cpp +++ b/math/complex_numbers.cpp @@ -11,6 +11,7 @@ #include #include #include +#include /** * Class Complex to represent complex numbers as a field. From 61084adbd3b73aa5312836aa1836188dc24881f8 Mon Sep 17 00:00:00 2001 From: Tajmeet Singh Date: Tue, 23 Jun 2020 18:16:26 +0100 Subject: [PATCH 066/271] fix: fixed forgotten namespace --- math/complex_numbers.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/math/complex_numbers.cpp b/math/complex_numbers.cpp index 43b1d5fda..9168c08aa 100644 --- a/math/complex_numbers.cpp +++ b/math/complex_numbers.cpp @@ -61,7 +61,7 @@ class Complex { * Member function which gives the argument of our complex number. * @return Argument of our Complex number in radians. */ - double arg() const { return atan2(this->im, this->re); } + double arg() const { return std::atan2(this->im, this->re); } /** * Operator overload to be able to add two complex numbers. From 2aec4efdd3839cd513218b1738d13e6a324c18fe Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Tue, 23 Jun 2020 23:50:45 +0530 Subject: [PATCH 067/271] fix: integer overflow due to multiplication fixed (#886) * formatting source-code for 72c365dcd34d9776fac3e2b58b41891b3619b02e * Fixed Bug [munmap_chunck() core dumped] * formatting source-code for b06bbf4dc6c46a3284d7852bb570438384eef4ef * fixed line spacing * fixed line spacing * fixed documentation * closed the paranthesis of line 3 * formatting source-code for 8233eda8894f46785f288e72c639d201852f6096 * Bug Fix heap sort [Fresh Implementation] * formatting source-code for e464ddac3688834ce46c59bada5ad3fddbfa2254 * Bug Fix heap sort [Fresh Implementation] * formatting source-code for 803981c831b36bf940d3fa2a901340cb0029717b * switched to normal functions from lambda * formatting source-code for ced5dcd6c4db53ece27d22ecd1dd1c1fcce6afb0 * Added template and test cases * formatting source-code for 7c8617fa46d41481c68ae2ae9d4f6a89ca42a4ff * fixed docs * fixed line spacing in tests * fix docs * Multiplication result may overflow 'int' before it is converted to 'long'. * fixed cpplint long -> int64 * fixed compiler error Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> --- math/primes_up_to_billion.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/math/primes_up_to_billion.cpp b/math/primes_up_to_billion.cpp index 4fb79a15e..b7377cea5 100644 --- a/math/primes_up_to_billion.cpp +++ b/math/primes_up_to_billion.cpp @@ -14,9 +14,9 @@ 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++) { + for (int64_t p = 2; p * p <= n; p++) { if (prime[p] == '1') { - for (int i = p * p; i <= n; i += p) + for (int64_t i = p * p; i <= n; i += p) prime[i] = '0'; // set all multiples of p to false } } From bcd5df725d83e06ae2fb69b0ccacbef5c56e454b Mon Sep 17 00:00:00 2001 From: Tajmeet Singh Date: Tue, 23 Jun 2020 19:23:15 +0100 Subject: [PATCH 068/271] feat: added polar form initialisation to our Complex class --- math/complex_numbers.cpp | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/math/complex_numbers.cpp b/math/complex_numbers.cpp index 9168c08aa..35e11ba1d 100644 --- a/math/complex_numbers.cpp +++ b/math/complex_numbers.cpp @@ -9,9 +9,9 @@ #include #include #include +#include #include #include -#include /** * Class Complex to represent complex numbers as a field. @@ -26,10 +26,22 @@ class Complex { /** * Complex Constructor which initialises the complex number which takes two * arguments. - * @param x The real value of the complex number (optional). - * @param y The imaginary value of the complex number (optional). + * @param x If the third parameter is 'true' then this x is the absolute + * value of the complex number, if the third parameter is 'false' then this + * x is the real value of the complex number (optional). + * @param y If the third parameter is 'true' then this y is the argument of + * the complex number, if the third parameter is 'false' then this y is the + * imaginary value of the complex number (optional). + * @param is_polar 'false' by default. If we want to initialise our complex + * number using polar form then set this to true, otherwise set it to false + * to use initialiser which initialises real and imaginary values using the + * first two parameters (optional). */ - explicit Complex(double x = 0.f, double y = 0.f) : re(x), im(y) { ; } + explicit Complex(double x = 0.f, double y = 0.f, bool is_polar = false) + : re(is_polar ? x * std::cos(y) : x), + im(is_polar ? x * std::sin(y) : y) { + ; + } /** * Copy Constructor From 95320b38a4a2aefaf0eb6b757438560b36d272f4 Mon Sep 17 00:00:00 2001 From: Tajmeet Singh Date: Tue, 23 Jun 2020 19:29:11 +0100 Subject: [PATCH 069/271] fix: cpplint issues --- math/complex_numbers.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/math/complex_numbers.cpp b/math/complex_numbers.cpp index 35e11ba1d..a4ee69829 100644 --- a/math/complex_numbers.cpp +++ b/math/complex_numbers.cpp @@ -22,7 +22,7 @@ class Complex { // The imaginary value of the complex number double im; - public: + public: /** * Complex Constructor which initialises the complex number which takes two * arguments. @@ -39,9 +39,7 @@ class Complex { */ explicit Complex(double x = 0.f, double y = 0.f, bool is_polar = false) : re(is_polar ? x * std::cos(y) : x), - im(is_polar ? x * std::sin(y) : y) { - ; - } + im(is_polar ? x * std::sin(y) : y) { ; } /** * Copy Constructor From 9048e19184c3df765465c150ec7fa89151c41cd5 Mon Sep 17 00:00:00 2001 From: Tajmeet Singh Date: Tue, 23 Jun 2020 19:32:05 +0100 Subject: [PATCH 070/271] fix: cpplint issues --- math/complex_numbers.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/math/complex_numbers.cpp b/math/complex_numbers.cpp index a4ee69829..30edf4964 100644 --- a/math/complex_numbers.cpp +++ b/math/complex_numbers.cpp @@ -39,13 +39,13 @@ class Complex { */ explicit Complex(double x = 0.f, double y = 0.f, bool is_polar = false) : re(is_polar ? x * std::cos(y) : x), - im(is_polar ? x * std::sin(y) : y) { ; } + im(is_polar ? x * std::sin(y) : y) {} /** * Copy Constructor * @param other The other number to equate our number to. */ - Complex(const Complex &other) : re(other.real()), im(other.imag()) { ; } + Complex(const Complex &other) : re(other.real()), im(other.imag()) {} /** * Member function (getter) to access the class' re value. From 75d8ee7cf07ee546e5f9fdbfad904060840fa607 Mon Sep 17 00:00:00 2001 From: Tajmeet Singh Date: Tue, 23 Jun 2020 19:43:56 +0100 Subject: [PATCH 071/271] fix: Readability issues --- math/complex_numbers.cpp | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/math/complex_numbers.cpp b/math/complex_numbers.cpp index 30edf4964..8b24c6d3c 100644 --- a/math/complex_numbers.cpp +++ b/math/complex_numbers.cpp @@ -37,9 +37,16 @@ class Complex { * to use initialiser which initialises real and imaginary values using the * first two parameters (optional). */ - explicit Complex(double x = 0.f, double y = 0.f, bool is_polar = false) - : re(is_polar ? x * std::cos(y) : x), - im(is_polar ? x * std::sin(y) : y) {} + explicit Complex(double x = 0.f, double y = 0.f, bool is_polar = false) { + if (!is_polar) { + re = x; + im = y; + return; + } + + re = x * std::cos(y); + im = x * std::sin(y); + } /** * Copy Constructor From 7393d88811c7ddb58d73db3fd554eb1fd414f298 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 23 Jun 2020 19:02:47 +0000 Subject: [PATCH 072/271] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 080e5f5d8..eb75ce3e5 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -102,6 +102,7 @@ ## Math * [Binary Exponent](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/binary_exponent.cpp) * [Check Prime](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/check_prime.cpp) + * [Complex Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/complex_numbers.cpp) * [Double Factorial](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/double_factorial.cpp) * [Eulers Totient Function](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/eulers_totient_function.cpp) * [Extended Euclid Algorithm](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/extended_euclid_algorithm.cpp) From 46e07288ba5b259ae2fa7b32c289b0305ef2def0 Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Sat, 20 Jun 2020 21:00:52 +0530 Subject: [PATCH 073/271] Fixed Bug [munmap_chunck() core dumped] --- sorting/merge_sort.cpp | 49 +++++++++++++++++++++--------------------- 1 file changed, 25 insertions(+), 24 deletions(-) diff --git a/sorting/merge_sort.cpp b/sorting/merge_sort.cpp index fc6d66af5..d6f099cea 100644 --- a/sorting/merge_sort.cpp +++ b/sorting/merge_sort.cpp @@ -1,36 +1,37 @@ /** * \addtogroup sorting Sorting Algorithms - * @{ + * @file{ * \file - * \brief [Merege Sort Algorithm + * \breif [Merege Sort Algorithm * (MEREGE SORT)](https://en.wikipedia.org/wiki/Merge_sort) implementation * - * \author [Ayaan Khan](http://github.com/ayaankhan98) + * \author [Ayaan Khan] (http://github.com/ayaankhan98) * - * \details * Merge Sort is an efficient, general purpose, comparison * based sorting algorithm. * Merge Sort is a divide and conquer algorithm - * + * */ + #include /** * - * The merge() function is used for merging two halves. - * The merge(arr, l, m, r) is key process that assumes that - * arr[l..m] and arr[m+1..r] are sorted and merges the two + * The merge() function is used for merging two halves. + * The merge(arr, l, m, r) is key process that assumes that + * arr[l..m] and arr[m+1..r] are sorted and merges the two * sorted sub-arrays into one. * - * @param arr - array with two halves arr[l...m] and arr[m+1...l] - * @param l - left index or start index of first half array - * @param m - right index or end index of first half array - * + * @param arr[] is the array with two halves one is arr[l...m] and + * other is arr[m+1...l] + * @param l is the left index of first half array + * @param m is the end index of right index of first half array + * * (The second array starts form m+1 and goes till l) - * - * @param l - end index or right index of second half array + * + * @param l is the end index of right index of second half array */ -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; @@ -75,12 +76,12 @@ void merge(int *arr, int l, int m, int r) { * input array into two halves and calls itself for the two halves * and then calls merge() to merge the two halves * - * @param arr - array to be sorted - * @param l - left index or start index of array - * @param r - right index or end index of array + * @param arr[] the array which is to be sorted + * @param l define the left index of array + * @param r defines the right index of array * */ -void mergeSort(int *arr, int l, int r) { +void mergeSort(int arr[], int l, int r) { if (l < r) { int m = l + (r - l) / 2; mergeSort(arr, l, m); @@ -90,11 +91,11 @@ void mergeSort(int *arr, int l, int r) { } /** - * Utility function used to print the array after + * A simple utility function used to print the array after * sorting */ -void show(int *arr, int size) { - for (int i = 0; i < size; i++) std::cout << arr[i] << " "; +void show(int arr[], int size) { + for (int i = 0; i < size; i++) std::cout << arr[i] << " "; std::cout << "\n"; } @@ -108,9 +109,9 @@ int main() { for (int i = 0; i < size; ++i) { std::cin >> arr[i]; } - mergeSort(arr, 0, size - 1); + mergeSort(arr, 0, size-1); std::cout << "Sorted array : "; - show(arr, size - 1); + show(arr, size-1); delete[] arr; return 0; } From 5e63bede6fc40e1e5a07abea8d36748200332b27 Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Sat, 20 Jun 2020 21:02:50 +0530 Subject: [PATCH 074/271] fixed line spacing --- sorting/merge_sort.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/sorting/merge_sort.cpp b/sorting/merge_sort.cpp index d6f099cea..87d1cd78d 100644 --- a/sorting/merge_sort.cpp +++ b/sorting/merge_sort.cpp @@ -12,7 +12,6 @@ * Merge Sort is a divide and conquer algorithm * */ - #include /** From b1d2ad1dfc033a0070479a6f680be3bf876dd03e Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 20 Jun 2020 15:31:59 +0000 Subject: [PATCH 075/271] formatting source-code for b06bbf4dc6c46a3284d7852bb570438384eef4ef --- sorting/merge_sort.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/sorting/merge_sort.cpp b/sorting/merge_sort.cpp index 87d1cd78d..716c7c64d 100644 --- a/sorting/merge_sort.cpp +++ b/sorting/merge_sort.cpp @@ -10,24 +10,24 @@ * Merge Sort is an efficient, general purpose, comparison * based sorting algorithm. * Merge Sort is a divide and conquer algorithm - * + * */ #include /** * - * The merge() function is used for merging two halves. - * The merge(arr, l, m, r) is key process that assumes that - * arr[l..m] and arr[m+1..r] are sorted and merges the two + * The merge() function is used for merging two halves. + * The merge(arr, l, m, r) is key process that assumes that + * arr[l..m] and arr[m+1..r] are sorted and merges the two * sorted sub-arrays into one. * * @param arr[] is the array with two halves one is arr[l...m] and * other is arr[m+1...l] * @param l is the left index of first half array * @param m is the end index of right index of first half array - * + * * (The second array starts form m+1 and goes till l) - * + * * @param l is the end index of right index of second half array */ void merge(int arr[], int l, int m, int r) { @@ -94,7 +94,7 @@ void mergeSort(int arr[], int l, int r) { * 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"; } @@ -108,9 +108,9 @@ int main() { for (int i = 0; i < size; ++i) { std::cin >> arr[i]; } - mergeSort(arr, 0, size-1); + mergeSort(arr, 0, size - 1); std::cout << "Sorted array : "; - show(arr, size-1); + show(arr, size - 1); delete[] arr; return 0; } From 0a09c1e382acef49ebbeaf1ad810e0455ea08206 Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Sat, 20 Jun 2020 21:05:19 +0530 Subject: [PATCH 076/271] fixed line spacing --- sorting/merge_sort.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/sorting/merge_sort.cpp b/sorting/merge_sort.cpp index 716c7c64d..34600d06a 100644 --- a/sorting/merge_sort.cpp +++ b/sorting/merge_sort.cpp @@ -7,6 +7,7 @@ * * \author [Ayaan Khan] (http://github.com/ayaankhan98) * + * \details * Merge Sort is an efficient, general purpose, comparison * based sorting algorithm. * Merge Sort is a divide and conquer algorithm From 99ca279ff6555fd9ef25b1c87d710a3b3bb4300b Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Sat, 20 Jun 2020 21:41:25 +0530 Subject: [PATCH 077/271] fixed documentation --- sorting/merge_sort.cpp | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/sorting/merge_sort.cpp b/sorting/merge_sort.cpp index 34600d06a..fc6d66af5 100644 --- a/sorting/merge_sort.cpp +++ b/sorting/merge_sort.cpp @@ -1,11 +1,11 @@ /** * \addtogroup sorting Sorting Algorithms - * @file{ + * @{ * \file - * \breif [Merege Sort Algorithm + * \brief [Merege Sort Algorithm * (MEREGE SORT)](https://en.wikipedia.org/wiki/Merge_sort) implementation * - * \author [Ayaan Khan] (http://github.com/ayaankhan98) + * \author [Ayaan Khan](http://github.com/ayaankhan98) * * \details * Merge Sort is an efficient, general purpose, comparison @@ -22,16 +22,15 @@ * arr[l..m] and arr[m+1..r] are sorted and merges the two * sorted sub-arrays into one. * - * @param arr[] is the array with two halves one is arr[l...m] and - * other is arr[m+1...l] - * @param l is the left index of first half array - * @param m is the end index of right index of first half array + * @param arr - array with two halves arr[l...m] and arr[m+1...l] + * @param l - left index or start index of first half array + * @param m - right index or end index of first half array * * (The second array starts form m+1 and goes till l) * - * @param l is the end index of right index of second half array + * @param l - end index or right index of second half array */ -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; @@ -76,12 +75,12 @@ void merge(int arr[], int l, int m, int r) { * input array into two halves and calls itself for the two halves * and then calls merge() to merge the two halves * - * @param arr[] the array which is to be sorted - * @param l define the left index of array - * @param r defines the right index of array + * @param arr - array to be sorted + * @param l - left index or start index of array + * @param r - right index or end index of array * */ -void mergeSort(int arr[], int l, int r) { +void mergeSort(int *arr, int l, int r) { if (l < r) { int m = l + (r - l) / 2; mergeSort(arr, l, m); @@ -91,10 +90,10 @@ void mergeSort(int arr[], int l, int r) { } /** - * A simple utility function used to print the array after + * Utility function used to print 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"; } From 4afe371ba535a837ac67c9a43fae094d5a6949c8 Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Sat, 20 Jun 2020 22:50:49 +0530 Subject: [PATCH 078/271] closed the paranthesis of line 3 --- sorting/merge_sort.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sorting/merge_sort.cpp b/sorting/merge_sort.cpp index fc6d66af5..ce87c8b5c 100644 --- a/sorting/merge_sort.cpp +++ b/sorting/merge_sort.cpp @@ -114,4 +114,4 @@ int main() { delete[] arr; return 0; } -/** @} */ +/** @} */ From 5c77f1ebe0d8dcefaf472b90b7a5f3ffd82137c8 Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Sun, 21 Jun 2020 00:03:36 +0530 Subject: [PATCH 079/271] Bug Fix heap sort [Fresh Implementation] --- sorting/heap_sort.cpp | 110 ++++++++++++++++-------------------------- 1 file changed, 41 insertions(+), 69 deletions(-) diff --git a/sorting/heap_sort.cpp b/sorting/heap_sort.cpp index ef9f87094..405e4641d 100644 --- a/sorting/heap_sort.cpp +++ b/sorting/heap_sort.cpp @@ -1,31 +1,31 @@ /** + * \addtogroup sorting Sorting Algorithm + * @{ * \file * \brief [Heap Sort Algorithm - * (heap sort)](https://en.wikipedia.org/wiki/Heapsort) implementation + * (HEAP SORT)](https://en.wikipedia.org/wiki/Heapsort) implementation * * \author [Ayaan Khan](http://github.com/ayaankhan98) * * \details - * Heap-sort is a comparison-based sorting algorithm. - * Heap-sort can be thought of as an improved selection sort: - * like selection sort, heap sort divides its input into a sorted - * and an unsorted region, and it iteratively shrinks the unsorted - * region by extracting the largest element from it and inserting - * it into the sorted region. Unlike selection sort, - * heap sort does not waste time with a linear-time scan of the - * unsorted region; rather, heap sort maintains the unsorted region - * in a heap data structure to more quickly find the largest element + * heapsort is a comparison-based sorting algorithm. + * Heapsort can be thought of as an improved selection sort: + * like selection sort, heapsort divides its input into a sorted + * and an unsorted region, and it iteratively shrinks the unsorted + * region by extracting the largest element from it and inserting + * it into the sorted region. Unlike selection sort, + * heapsort does not waste time with a linear-time scan of the + * unsorted region; rather, heap sort maintains the unsorted region + * in a heap data structure to more quickly find the largest element * in each step. - * - * Time Complexity - \f$O(n \log(n))\f$ + * + * Time Complexity - O(nlog(n)) * */ -#include -#include #include /** - * + * * Utility Lambda function to print the array after * sorting. * @@ -33,32 +33,25 @@ * @param sz size of array * */ -template -void printArray(T *arr, int sz) { - for (int i = 0; i < sz; i++) std::cout << arr[i] << " "; +auto printArray = [] (int *arr, int sz) { + for (int i = 0 ; i < sz ; i++) + std::cout << arr[i] <<" "; std::cout << "\n"; -} +}; /** * - * \addtogroup sorting Sorting Algorithm - * @{ - * - * The heapify procedure can be thought of as building a heap from - * the bottom up by successively sifting downward to establish the - * heap property. - * - * @param arr array to be sorted - * @param n size of array - * @param i node position in Binary Tress or element position in - * Array to be compared with it's childern - * + * The heapify procedure can be thought of as building a heap from + * the bottom up by successively sifting downward to establish the + * heap property. + * + * @param arr array be to sorted + * @param */ -template -void heapify(T *arr, int n, int i) { +void(*heapify)(int *arr, int n, int i) = [] (int *arr, int n, int i) { int largest = i; - int l = 2 * i + 1; - int r = 2 * i + 2; + int l = 2*i + 1; + int r = 2*i + 2; if (l < n && arr[l] > arr[largest]) largest = l; @@ -70,54 +63,33 @@ void heapify(T *arr, int n, int i) { std::swap(arr[i], arr[largest]); heapify(arr, n, largest); } -} +}; /** - * Utilizes heapify procedure to sort + * heapSort lambda function utilizes heapify procedure to sort * the array * * @param arr array to be sorted * @param n size of array * */ -template -void heapSort(T *arr, int n) { - for (int i = n - 1; i >= 0; i--) heapify(arr, n, i); +auto heapSort = [] (int *arr, int n) { + for (int i = n-1 ; i >= 0; i--) + heapify(arr, n, i); - for (int i = n - 1; i >= 0; i--) { + for (int i = n-1 ; i >= 0; i--) { std::swap(arr[0], arr[i]); heapify(arr, i, 0); } -} - -/** - * - * @} - * Test cases to test the program - * - */ -void test() { - std::cout << "Test 1\n"; - int arr[] = {-10, 78, -1, -6, 7, 4, 94, 5, 99, 0}; - int sz = sizeof(arr) / sizeof(arr[0]); // sz - size of array - printArray(arr, sz); // displaying the array before sorting - heapSort(arr, sz); // calling heapsort to sort the array - printArray(arr, sz); // display array after sorting - assert(std::is_sorted(arr, arr + sz)); - std::cout << "Test 1 Passed\n========================\n"; - - std::cout << "Test 2\n"; - double arr2[] = {4.5, -3.6, 7.6, 0, 12.9}; - sz = sizeof(arr2) / sizeof(arr2[0]); - printArray(arr2, sz); - heapSort(arr2, sz); - printArray(arr2, sz); - assert(std::is_sorted(arr2, arr2 + sz)); - std::cout << "Test 2 passed\n"; -} +}; /** Main function */ int main() { - test(); + int arr[] = {-10, 78, -1, -6, 7, 4, 94, 5, 99, 0}; + int sz = sizeof(arr) / sizeof(arr[0]); // sz - size of array + printArray(arr, sz); // displaying the array before sorting + heapSort(arr, sz); // calling heapsort to sort the array + printArray(arr, sz); // display array after sorting return 0; } +/** @} */ From 549daeebfdabef2e1732568d554e4cc9d5feb08f Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 20 Jun 2020 17:21:37 +0000 Subject: [PATCH 080/271] formatting source-code for 8233eda8894f46785f288e72c639d201852f6096 --- sorting/merge_sort.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sorting/merge_sort.cpp b/sorting/merge_sort.cpp index ce87c8b5c..fc6d66af5 100644 --- a/sorting/merge_sort.cpp +++ b/sorting/merge_sort.cpp @@ -114,4 +114,4 @@ int main() { delete[] arr; return 0; } -/** @} */ +/** @} */ From 38db7fdec0d7254cb559ac89a19fa884d5cd0052 Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Sun, 21 Jun 2020 00:06:04 +0530 Subject: [PATCH 081/271] Bug Fix heap sort [Fresh Implementation] --- sorting/heap_sort.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/sorting/heap_sort.cpp b/sorting/heap_sort.cpp index 405e4641d..09c4d3193 100644 --- a/sorting/heap_sort.cpp +++ b/sorting/heap_sort.cpp @@ -44,9 +44,7 @@ auto printArray = [] (int *arr, int sz) { * The heapify procedure can be thought of as building a heap from * the bottom up by successively sifting downward to establish the * heap property. - * - * @param arr array be to sorted - * @param + * */ void(*heapify)(int *arr, int n, int i) = [] (int *arr, int n, int i) { int largest = i; From 11728ee231858c31f4398633d69a48dc5b0bba22 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 20 Jun 2020 18:34:51 +0000 Subject: [PATCH 082/271] formatting source-code for e464ddac3688834ce46c59bada5ad3fddbfa2254 --- sorting/heap_sort.cpp | 52 +++++++++++++++++++++---------------------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/sorting/heap_sort.cpp b/sorting/heap_sort.cpp index 09c4d3193..ae50e1cfb 100644 --- a/sorting/heap_sort.cpp +++ b/sorting/heap_sort.cpp @@ -8,24 +8,24 @@ * \author [Ayaan Khan](http://github.com/ayaankhan98) * * \details - * heapsort is a comparison-based sorting algorithm. - * Heapsort can be thought of as an improved selection sort: - * like selection sort, heapsort divides its input into a sorted - * and an unsorted region, and it iteratively shrinks the unsorted - * region by extracting the largest element from it and inserting - * it into the sorted region. Unlike selection sort, - * heapsort does not waste time with a linear-time scan of the - * unsorted region; rather, heap sort maintains the unsorted region - * in a heap data structure to more quickly find the largest element + * heapsort is a comparison-based sorting algorithm. + * Heapsort can be thought of as an improved selection sort: + * like selection sort, heapsort divides its input into a sorted + * and an unsorted region, and it iteratively shrinks the unsorted + * region by extracting the largest element from it and inserting + * it into the sorted region. Unlike selection sort, + * heapsort does not waste time with a linear-time scan of the + * unsorted region; rather, heap sort maintains the unsorted region + * in a heap data structure to more quickly find the largest element * in each step. - * + * * Time Complexity - O(nlog(n)) * */ #include /** - * + * * Utility Lambda function to print the array after * sorting. * @@ -33,23 +33,24 @@ * @param sz size of array * */ -auto printArray = [] (int *arr, int sz) { - for (int i = 0 ; i < sz ; i++) - std::cout << arr[i] <<" "; +auto printArray = [](int *arr, int sz) { + for (int i = 0; i < sz; i++) std::cout << arr[i] << " "; std::cout << "\n"; }; /** * - * The heapify procedure can be thought of as building a heap from - * the bottom up by successively sifting downward to establish the - * heap property. - * + * The heapify procedure can be thought of as building a heap from + * the bottom up by successively sifting downward to establish the + * heap property. + * + * @param arr array be to sorted + * @param */ -void(*heapify)(int *arr, int n, int i) = [] (int *arr, int n, int i) { +void (*heapify)(int *arr, int n, int i) = [](int *arr, int n, int i) { int largest = i; - int l = 2*i + 1; - int r = 2*i + 2; + int l = 2 * i + 1; + int r = 2 * i + 2; if (l < n && arr[l] > arr[largest]) largest = l; @@ -71,11 +72,10 @@ void(*heapify)(int *arr, int n, int i) = [] (int *arr, int n, int i) { * @param n size of array * */ -auto heapSort = [] (int *arr, int n) { - for (int i = n-1 ; i >= 0; i--) - heapify(arr, n, i); +auto heapSort = [](int *arr, int n) { + for (int i = n - 1; i >= 0; i--) heapify(arr, n, i); - for (int i = n-1 ; i >= 0; i--) { + for (int i = n - 1; i >= 0; i--) { std::swap(arr[0], arr[i]); heapify(arr, i, 0); } @@ -86,7 +86,7 @@ int main() { int arr[] = {-10, 78, -1, -6, 7, 4, 94, 5, 99, 0}; int sz = sizeof(arr) / sizeof(arr[0]); // sz - size of array printArray(arr, sz); // displaying the array before sorting - heapSort(arr, sz); // calling heapsort to sort the array + heapSort(arr, sz); // calling heapsort to sort the array printArray(arr, sz); // display array after sorting return 0; } From 86bd671c669c35b704162927401d2a7c98d3b57e Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Sun, 21 Jun 2020 17:06:17 +0530 Subject: [PATCH 083/271] switched to normal functions from lambda --- sorting/heap_sort.cpp | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/sorting/heap_sort.cpp b/sorting/heap_sort.cpp index ae50e1cfb..6cdb17f4a 100644 --- a/sorting/heap_sort.cpp +++ b/sorting/heap_sort.cpp @@ -33,10 +33,10 @@ * @param sz size of array * */ -auto printArray = [](int *arr, int sz) { +void printArray(int *arr, int sz) { for (int i = 0; i < sz; i++) std::cout << arr[i] << " "; std::cout << "\n"; -}; +} /** * @@ -44,10 +44,13 @@ auto printArray = [](int *arr, int sz) { * the bottom up by successively sifting downward to establish the * heap property. * - * @param arr array be to sorted - * @param + * @param arr array to be sorted + * @param n size of array + * @param i node position in Binary Tress or element position in + * Array to be compared with it's childern + * */ -void (*heapify)(int *arr, int n, int i) = [](int *arr, int n, int i) { +void heapify(int *arr, int n, int i) { int largest = i; int l = 2 * i + 1; int r = 2 * i + 2; @@ -62,7 +65,7 @@ void (*heapify)(int *arr, int n, int i) = [](int *arr, int n, int i) { std::swap(arr[i], arr[largest]); heapify(arr, n, largest); } -}; +} /** * heapSort lambda function utilizes heapify procedure to sort @@ -72,14 +75,14 @@ void (*heapify)(int *arr, int n, int i) = [](int *arr, int n, int i) { * @param n size of array * */ -auto heapSort = [](int *arr, int n) { +void heapSort(int *arr, int n) { for (int i = n - 1; i >= 0; i--) heapify(arr, n, i); for (int i = n - 1; i >= 0; i--) { std::swap(arr[0], arr[i]); heapify(arr, i, 0); } -}; +} /** Main function */ int main() { From 2a41d916b05681932021d4130f19af21097f385b Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Sun, 21 Jun 2020 17:38:42 +0530 Subject: [PATCH 084/271] Added template and test cases --- sorting/heap_sort.cpp | 31 +++++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/sorting/heap_sort.cpp b/sorting/heap_sort.cpp index 6cdb17f4a..5eaded62a 100644 --- a/sorting/heap_sort.cpp +++ b/sorting/heap_sort.cpp @@ -23,6 +23,8 @@ * */ #include +#include +#include /** * @@ -33,7 +35,8 @@ * @param sz size of array * */ -void printArray(int *arr, int sz) { +template +void printArray(T *arr, int sz) { for (int i = 0; i < sz; i++) std::cout << arr[i] << " "; std::cout << "\n"; } @@ -50,7 +53,8 @@ void printArray(int *arr, int sz) { * Array to be compared with it's childern * */ -void heapify(int *arr, int n, int i) { +template +void heapify(T *arr, int n, int i) { int largest = i; int l = 2 * i + 1; int r = 2 * i + 2; @@ -75,7 +79,8 @@ void heapify(int *arr, int n, int i) { * @param n size of array * */ -void heapSort(int *arr, int n) { +template +void heapSort(T *arr, int n) { for (int i = n - 1; i >= 0; i--) heapify(arr, n, i); for (int i = n - 1; i >= 0; i--) { @@ -84,13 +89,27 @@ void heapSort(int *arr, int n) { } } -/** Main function */ -int main() { +void test() { + std::cout << "Test 1\n"; int arr[] = {-10, 78, -1, -6, 7, 4, 94, 5, 99, 0}; int sz = sizeof(arr) / sizeof(arr[0]); // sz - size of array printArray(arr, sz); // displaying the array before sorting heapSort(arr, sz); // calling heapsort to sort the array printArray(arr, sz); // display array after sorting - return 0; + assert(std::is_sorted(arr, arr+sz)); + std::cout << "Test 1 Passed\n========================\n"; + std::cout << "Test 2\n"; + double arr2[] = {4.5, -3.6, 7.6, 0, 12.9}; + sz = sizeof(arr2) / sizeof(arr2[0]); + printArray(arr2, sz); + heapSort(arr2, sz); + printArray(arr2, sz); + assert(std::is_sorted(arr2, arr2+sz)); + std::cout << "Test 2 passed\n"; +} +/** Main function */ +int main() { + test(); + return 0; } /** @} */ From 6d88c992ed34db27b9f804e159a1a6e4cc9e59c1 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 21 Jun 2020 11:37:08 +0000 Subject: [PATCH 085/271] formatting source-code for ced5dcd6c4db53ece27d22ecd1dd1c1fcce6afb0 --- sorting/heap_sort.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sorting/heap_sort.cpp b/sorting/heap_sort.cpp index 5eaded62a..42bfc43b2 100644 --- a/sorting/heap_sort.cpp +++ b/sorting/heap_sort.cpp @@ -48,8 +48,8 @@ void printArray(T *arr, int sz) { * heap property. * * @param arr array to be sorted - * @param n size of array - * @param i node position in Binary Tress or element position in + * @param n size of array + * @param i node position in Binary Tress or element position in * Array to be compared with it's childern * */ From 555f4fb98f1a2646c36683362e4f72a6e40c1740 Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Sun, 21 Jun 2020 17:41:39 +0530 Subject: [PATCH 086/271] fixed docs --- sorting/heap_sort.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sorting/heap_sort.cpp b/sorting/heap_sort.cpp index 42bfc43b2..0945c9a92 100644 --- a/sorting/heap_sort.cpp +++ b/sorting/heap_sort.cpp @@ -89,6 +89,7 @@ void heapSort(T *arr, int n) { } } +/** Test cases to test the program */ void test() { std::cout << "Test 1\n"; int arr[] = {-10, 78, -1, -6, 7, 4, 94, 5, 99, 0}; @@ -107,6 +108,7 @@ void test() { assert(std::is_sorted(arr2, arr2+sz)); std::cout << "Test 2 passed\n"; } + /** Main function */ int main() { test(); From a56e54ca15249a322d2dd98ab83652c20e0753f1 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 21 Jun 2020 12:09:45 +0000 Subject: [PATCH 087/271] formatting source-code for 7c8617fa46d41481c68ae2ae9d4f6a89ca42a4ff --- sorting/heap_sort.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/sorting/heap_sort.cpp b/sorting/heap_sort.cpp index 0945c9a92..52edddf17 100644 --- a/sorting/heap_sort.cpp +++ b/sorting/heap_sort.cpp @@ -22,9 +22,9 @@ * Time Complexity - O(nlog(n)) * */ -#include #include #include +#include /** * @@ -97,7 +97,7 @@ void test() { printArray(arr, sz); // displaying the array before sorting heapSort(arr, sz); // calling heapsort to sort the array printArray(arr, sz); // display array after sorting - assert(std::is_sorted(arr, arr+sz)); + assert(std::is_sorted(arr, arr + sz)); std::cout << "Test 1 Passed\n========================\n"; std::cout << "Test 2\n"; double arr2[] = {4.5, -3.6, 7.6, 0, 12.9}; @@ -105,13 +105,13 @@ void test() { printArray(arr2, sz); heapSort(arr2, sz); printArray(arr2, sz); - assert(std::is_sorted(arr2, arr2+sz)); + assert(std::is_sorted(arr2, arr2 + sz)); std::cout << "Test 2 passed\n"; } /** Main function */ int main() { - test(); - return 0; + test(); + return 0; } /** @} */ From f0ab9a0d3870ab65b054503d77cdf5188d4fdeab Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Sun, 21 Jun 2020 17:50:07 +0530 Subject: [PATCH 088/271] fixed line spacing in tests --- sorting/heap_sort.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/sorting/heap_sort.cpp b/sorting/heap_sort.cpp index 52edddf17..6445f0f32 100644 --- a/sorting/heap_sort.cpp +++ b/sorting/heap_sort.cpp @@ -99,6 +99,7 @@ void test() { printArray(arr, sz); // display array after sorting assert(std::is_sorted(arr, arr + sz)); std::cout << "Test 1 Passed\n========================\n"; + std::cout << "Test 2\n"; double arr2[] = {4.5, -3.6, 7.6, 0, 12.9}; sz = sizeof(arr2) / sizeof(arr2[0]); From 7f4077505567f3d8c8ea275c9c7b402111769653 Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Sun, 21 Jun 2020 19:50:51 +0530 Subject: [PATCH 089/271] fix docs --- sorting/heap_sort.cpp | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/sorting/heap_sort.cpp b/sorting/heap_sort.cpp index 6445f0f32..ef9f87094 100644 --- a/sorting/heap_sort.cpp +++ b/sorting/heap_sort.cpp @@ -1,25 +1,23 @@ /** - * \addtogroup sorting Sorting Algorithm - * @{ * \file * \brief [Heap Sort Algorithm - * (HEAP SORT)](https://en.wikipedia.org/wiki/Heapsort) implementation + * (heap sort)](https://en.wikipedia.org/wiki/Heapsort) implementation * * \author [Ayaan Khan](http://github.com/ayaankhan98) * * \details - * heapsort is a comparison-based sorting algorithm. - * Heapsort can be thought of as an improved selection sort: - * like selection sort, heapsort divides its input into a sorted + * Heap-sort is a comparison-based sorting algorithm. + * Heap-sort can be thought of as an improved selection sort: + * like selection sort, heap sort divides its input into a sorted * and an unsorted region, and it iteratively shrinks the unsorted * region by extracting the largest element from it and inserting * it into the sorted region. Unlike selection sort, - * heapsort does not waste time with a linear-time scan of the + * heap sort does not waste time with a linear-time scan of the * unsorted region; rather, heap sort maintains the unsorted region * in a heap data structure to more quickly find the largest element * in each step. * - * Time Complexity - O(nlog(n)) + * Time Complexity - \f$O(n \log(n))\f$ * */ #include @@ -42,6 +40,9 @@ void printArray(T *arr, int sz) { } /** + * + * \addtogroup sorting Sorting Algorithm + * @{ * * The heapify procedure can be thought of as building a heap from * the bottom up by successively sifting downward to establish the @@ -72,7 +73,7 @@ void heapify(T *arr, int n, int i) { } /** - * heapSort lambda function utilizes heapify procedure to sort + * Utilizes heapify procedure to sort * the array * * @param arr array to be sorted @@ -89,7 +90,12 @@ void heapSort(T *arr, int n) { } } -/** Test cases to test the program */ +/** + * + * @} + * Test cases to test the program + * + */ void test() { std::cout << "Test 1\n"; int arr[] = {-10, 78, -1, -6, 7, 4, 94, 5, 99, 0}; @@ -115,4 +121,3 @@ int main() { test(); return 0; } -/** @} */ From c344d8f6f155cca62c183327a0ccaa6e541a4bea Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Tue, 23 Jun 2020 22:58:44 +0530 Subject: [PATCH 090/271] Multiplication result may overflow 'int' before it is converted to 'long'. --- math/primes_up_to_billion.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/math/primes_up_to_billion.cpp b/math/primes_up_to_billion.cpp index b7377cea5..af6d34ff3 100644 --- a/math/primes_up_to_billion.cpp +++ b/math/primes_up_to_billion.cpp @@ -14,9 +14,9 @@ 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 (int64_t p = 2; p * p <= n; p++) { + for (long p = 2; p * p <= n; p++) { if (prime[p] == '1') { - for (int64_t i = p * p; i <= n; i += p) + for (long i = p * p; i <= n; i += p) prime[i] = '0'; // set all multiples of p to false } } From fa92a18c2e777da1b0361415d16e0fd88ae115bd Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Tue, 23 Jun 2020 23:28:13 +0530 Subject: [PATCH 091/271] fixed cpplint long -> int64 --- math/primes_up_to_billion.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/math/primes_up_to_billion.cpp b/math/primes_up_to_billion.cpp index af6d34ff3..f13a8312b 100644 --- a/math/primes_up_to_billion.cpp +++ b/math/primes_up_to_billion.cpp @@ -14,9 +14,9 @@ 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 (long p = 2; p * p <= n; p++) { + for (int64 p = 2; p * p <= n; p++) { if (prime[p] == '1') { - for (long i = p * p; i <= n; i += p) + for (int64 i = p * p; i <= n; i += p) prime[i] = '0'; // set all multiples of p to false } } From 886cb520f02f8f358ff6247b3262b822b8c6b300 Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Tue, 23 Jun 2020 23:36:14 +0530 Subject: [PATCH 092/271] fixed compiler error --- math/primes_up_to_billion.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/math/primes_up_to_billion.cpp b/math/primes_up_to_billion.cpp index f13a8312b..b7377cea5 100644 --- a/math/primes_up_to_billion.cpp +++ b/math/primes_up_to_billion.cpp @@ -14,9 +14,9 @@ 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 (int64 p = 2; p * p <= n; p++) { + for (int64_t p = 2; p * p <= n; p++) { if (prime[p] == '1') { - for (int64 i = p * p; i <= n; i += p) + for (int64_t i = p * p; i <= n; i += p) prime[i] = '0'; // set all multiples of p to false } } From 8252816dcc6799c14fb40c6f6bf206013be3add0 Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Wed, 24 Jun 2020 00:12:36 +0530 Subject: [PATCH 093/271] fixed Code quality and added docs --- data_structures/disjoint_set.cpp | 62 +++++++++++++++++++++++++++++--- 1 file changed, 57 insertions(+), 5 deletions(-) diff --git a/data_structures/disjoint_set.cpp b/data_structures/disjoint_set.cpp index dd70e4cea..b7bcf3c58 100644 --- a/data_structures/disjoint_set.cpp +++ b/data_structures/disjoint_set.cpp @@ -1,3 +1,24 @@ +/** + * + * \file + * \brief [Disjoint Sets Data Structure + * (Disjoint Sets)](https://en.wikipedia.org/wiki/Disjoint-set_data_structure) + * + * \author + * + * \details + * A disjoint set data structure (also called union find or merge find set) + * is a data structure that tracks a set of elements partitioned into a number + * of disjoint (non-overlapping) subsets. + * Some situations where disjoint sets can be used are- + * to find connected components of a graph, kruskal's algorithm for finding + * Minimum Spanning Tree etc. + * There are two operation which we perform on disjoint sets - + * 1) Union + * 2) Find + * + */ + #include #include @@ -5,16 +26,30 @@ using std::cout; using std::endl; using std::vector; -vector root, rnk; +vector root, rank; +/** + * + * Function to create a set + * @param n number of element + * + */ void CreateSet(int n) { root = vector(n + 1); - rnk = vector(n + 1, 1); + rank = vector(n + 1, 1); for (int i = 1; i <= n; ++i) { root[i] = i; } } +/** + * + * Find operation takes a number x and returns the set to which this number + * belongs to. + * @param x element of some set + * @return set to which x belongs to + * + */ int Find(int x) { if (root[x] == x) { return x; @@ -22,22 +57,39 @@ int Find(int x) { return root[x] = Find(root[x]); } +/** + * + * A utility function to check if x and y are from same set or not + * @param x element of some set + * @param y element of some set + * + */ bool InSameUnion(int x, int y) { return Find(x) == Find(y); } +/** + * + * Union operation combines two disjoint sets to make a single set + * in this union function we pass two elements and check if they are + * from different sets then combine those sets + * @param x element of some set + * @param y element of some set + * + */ void Union(int x, int y) { int a = Find(x), b = Find(y); if (a != b) { - if (rnk[a] < rnk[b]) { + if (rank[a] < rank[b]) { root[a] = b; - } else if (rnk[a] > rnk[b]) { + } else if (rank[a] > rank[b]) { root[b] = a; } else { root[a] = b; - ++rnk[b]; + ++rank[b]; } } } +/** Main function */ int main() { // tests CreateSet & Find int n = 100; From 866c23e19e733884a790de28c251c4c580bf2dc3 Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Wed, 24 Jun 2020 00:25:52 +0530 Subject: [PATCH 094/271] Added author name --- data_structures/disjoint_set.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data_structures/disjoint_set.cpp b/data_structures/disjoint_set.cpp index b7bcf3c58..eebb650bf 100644 --- a/data_structures/disjoint_set.cpp +++ b/data_structures/disjoint_set.cpp @@ -4,7 +4,7 @@ * \brief [Disjoint Sets Data Structure * (Disjoint Sets)](https://en.wikipedia.org/wiki/Disjoint-set_data_structure) * - * \author + * \author [leoyang429](https://github.com/leoyang429) * * \details * A disjoint set data structure (also called union find or merge find set) From 2802dca89557750840cb89b988ce83934091e2d3 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 23 Jun 2020 18:43:35 +0000 Subject: [PATCH 095/271] formatting source-code for a887dc59ed8e790d479773e0ce5e24c6db110afb --- data_structures/disjoint_set.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/data_structures/disjoint_set.cpp b/data_structures/disjoint_set.cpp index eebb650bf..bd4599603 100644 --- a/data_structures/disjoint_set.cpp +++ b/data_structures/disjoint_set.cpp @@ -28,8 +28,8 @@ using std::vector; vector root, rank; -/** - * +/** + * * Function to create a set * @param n number of element * @@ -57,7 +57,7 @@ int Find(int x) { return root[x] = Find(root[x]); } -/** +/** * * A utility function to check if x and y are from same set or not * @param x element of some set From 91c9c96cf486331bbe00f206b5391911d438001a Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Wed, 24 Jun 2020 00:57:31 +0530 Subject: [PATCH 096/271] code quality fix deallocate resorces --- data_structures/binaryheap.cpp | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/data_structures/binaryheap.cpp b/data_structures/binaryheap.cpp index 72e56e91a..2396f2e51 100644 --- a/data_structures/binaryheap.cpp +++ b/data_structures/binaryheap.cpp @@ -13,10 +13,14 @@ class MinHeap { int heap_size; ///< Current number of elements in min heap public: - /** Constructor + /** Constructor: Builds a heap from a given array a[] of given size * \param[in] capacity initial heap capacity */ - MinHeap(int capacity); + explicit MinHeap(int cap) { + heap_size = 0; + capacity = cap; + harr = new int[cap]; + } /** to heapify a subtree with the root at given index */ @@ -44,14 +48,12 @@ class MinHeap { /** Inserts a new key 'k' */ void insertKey(int k); + + ~MinHeap() { + delete [] harr; + } }; -/** Constructor: Builds a heap from a given array a[] of given size */ -MinHeap::MinHeap(int cap) { - heap_size = 0; - capacity = cap; - harr = new int[cap]; -} // Inserts a new key 'k' void MinHeap::insertKey(int k) { From 6882b545c75136f82b5294eda0a2333b6c03ca16 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 23 Jun 2020 19:29:12 +0000 Subject: [PATCH 097/271] formatting source-code for 91c9c96cf486331bbe00f206b5391911d438001a --- data_structures/binaryheap.cpp | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/data_structures/binaryheap.cpp b/data_structures/binaryheap.cpp index 2396f2e51..c3a1f5cf6 100644 --- a/data_structures/binaryheap.cpp +++ b/data_structures/binaryheap.cpp @@ -13,13 +13,13 @@ class MinHeap { int heap_size; ///< Current number of elements in min heap public: - /** Constructor: Builds a heap from a given array a[] of given size + /** Constructor: Builds a heap from a given array a[] of given size * \param[in] capacity initial heap capacity */ explicit MinHeap(int cap) { - heap_size = 0; - capacity = cap; - harr = new int[cap]; + heap_size = 0; + capacity = cap; + harr = new int[cap]; } /** to heapify a subtree with the root at given index @@ -49,12 +49,9 @@ class MinHeap { /** Inserts a new key 'k' */ void insertKey(int k); - ~MinHeap() { - delete [] harr; - } + ~MinHeap() { delete[] harr; } }; - // Inserts a new key 'k' void MinHeap::insertKey(int k) { if (heap_size == capacity) { From 1d7a73ea583c27eaa39ed90793db698e6997b6a7 Mon Sep 17 00:00:00 2001 From: Neeraj C <35414531+iamnambiar@users.noreply.github.com> Date: Wed, 24 Jun 2020 01:03:42 +0530 Subject: [PATCH 098/271] feat: add check_amicable_pair.cpp (#879) * feat: add check_amicable_pair.cpp * fix: space between else and brace. * fix: spaces between tokens * fix: removed sqrt and test func combined to single * docs: removed wiki link Co-authored-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * docs: add markdown syntax for wikipedia link Co-authored-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * docs: change brief to details in comment Line 7 Co-authored-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * docs: typo fixed Co-authored-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * docs: removed extra line Co-authored-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * docs: removed copyright Co-authored-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * docs: add author name Co-authored-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * fix: shortened the code in is_amicable() Co-authored-by: David Leal * fix: changed is_amicable to are_amicable * docs: cleared unwanted line Co-authored-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Co-authored-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Co-authored-by: David Leal --- math/check_amicable_pair.cpp | 70 ++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 math/check_amicable_pair.cpp diff --git a/math/check_amicable_pair.cpp b/math/check_amicable_pair.cpp new file mode 100644 index 000000000..83a5d7364 --- /dev/null +++ b/math/check_amicable_pair.cpp @@ -0,0 +1,70 @@ +/** + * + * @file + * \brief A C++ Program to check whether a pair of number is [amicable pair](https://en.wikipedia.org/wiki/Amicable_numbers) or not. + * + * \details + * Amicable Pair are two positive integers such that sum of the proper divisor + * of each number is equal to the other number. + * @author iamnambiar + */ +#include +#include + +/** + * Function to calculate the sum of all the proper divisor + * of an integer. + * @param num First number. + * @return Sum of the proper divisor of the number. + */ +int sum_of_divisor(int num) { + // Variable to store the sum of all proper divisors. + int sum = 0; + // Below loop condition helps to reduce Time complexity by a factor of square root of the number. + for (int div = 2; div * div <= num; ++div) { + // Check 'div' is divisor of 'num'. + if (num % div == 0) { + // If both divisor are same, add once to 'sum' + if (div == (num / div)) { + sum += div; + } else { + // If both divisor are not the same, add both to 'sum'. + sum += (div + (num / div)); + } + } + } + return sum + 1; +} + +/** + * Function to check whether the pair is amicable or not. + * @param x First number. + * @param y Second number. + * @return `true` if the pair is amicable + * @return `false` if the pair is not amicable + */ +bool are_amicable(int x, int y) { + return (sum_of_divisor(x) == y) && (sum_of_divisor(y) == x); +} + +/** + * Function for testing the is_amicable() with + * all the test cases. + */ +void test() { + // are_amicable(220, 284) returns true. + assert(are_amicable(220, 284) == true); + // are_amicable(6232, 6368) returns true. + assert(are_amicable(6368, 6232) == true); + // are_amicable(458, 232) returns false. + assert(are_amicable(458, 232) == false); +} + +/** + * Main Function +*/ +int main() { + test(); + std::cout << "Assertion Success." << std::endl; + return 0; +} From 2d4a1dd19fd6835c63bb533aedcf3ab807fa889a Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 23 Jun 2020 19:34:19 +0000 Subject: [PATCH 099/271] formatting source-code for 1d7a73ea583c27eaa39ed90793db698e6997b6a7 --- math/check_amicable_pair.cpp | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/math/check_amicable_pair.cpp b/math/check_amicable_pair.cpp index 83a5d7364..4f1255d19 100644 --- a/math/check_amicable_pair.cpp +++ b/math/check_amicable_pair.cpp @@ -1,18 +1,19 @@ /** - * + * * @file - * \brief A C++ Program to check whether a pair of number is [amicable pair](https://en.wikipedia.org/wiki/Amicable_numbers) or not. - * + * \brief A C++ Program to check whether a pair of number is [amicable + * pair](https://en.wikipedia.org/wiki/Amicable_numbers) or not. + * * \details - * Amicable Pair are two positive integers such that sum of the proper divisor + * Amicable Pair are two positive integers such that sum of the proper divisor * of each number is equal to the other number. * @author iamnambiar */ -#include #include +#include /** - * Function to calculate the sum of all the proper divisor + * Function to calculate the sum of all the proper divisor * of an integer. * @param num First number. * @return Sum of the proper divisor of the number. @@ -20,7 +21,8 @@ int sum_of_divisor(int num) { // Variable to store the sum of all proper divisors. int sum = 0; - // Below loop condition helps to reduce Time complexity by a factor of square root of the number. + // Below loop condition helps to reduce Time complexity by a factor of + // square root of the number. for (int div = 2; div * div <= num; ++div) { // Check 'div' is divisor of 'num'. if (num % div == 0) { @@ -48,7 +50,7 @@ bool are_amicable(int x, int y) { } /** - * Function for testing the is_amicable() with + * Function for testing the is_amicable() with * all the test cases. */ void test() { @@ -62,7 +64,7 @@ void test() { /** * Main Function -*/ + */ int main() { test(); std::cout << "Assertion Success." << std::endl; From 26ffe8c6d7c30220b05af8071a3bbd0c4c6afb35 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 23 Jun 2020 19:34:19 +0000 Subject: [PATCH 100/271] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index eb75ce3e5..6e43ba3f2 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -101,6 +101,7 @@ ## Math * [Binary Exponent](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/binary_exponent.cpp) + * [Check Amicable Pair](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/check_amicable_pair.cpp) * [Check Prime](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/check_prime.cpp) * [Complex Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/complex_numbers.cpp) * [Double Factorial](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/double_factorial.cpp) From 2d0325699f9a832175dd376b66281bf284261c73 Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Wed, 24 Jun 2020 01:30:14 +0530 Subject: [PATCH 101/271] fixed code quality and added docs --- sorting/comb_sort.cpp | 83 ++++++++++++++++++++++++++++++------------- 1 file changed, 58 insertions(+), 25 deletions(-) diff --git a/sorting/comb_sort.cpp b/sorting/comb_sort.cpp index 1b0a4d706..7e62c04ff 100644 --- a/sorting/comb_sort.cpp +++ b/sorting/comb_sort.cpp @@ -1,49 +1,82 @@ -// 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) +/** + * + * \file + * \brief [Comb Sort Algorithm + * (Comb Sort)](https://en.wikipedia.org/wiki/Comb_sort) + * + * \author + * + * \details + * - A better version of bubble sort algorithm + * - Bubble sort compares adjacent values whereas comb sort uses gap larger + * than 1 + * - Best case Time complexity O(n) + * Worst case Time complexity O(n^2) + * + */ #include #include -int a[100005]; -int n; +/** + * + * Find the next gap by shrinking the current gap by shrink factor of 1.3 + * @param gap current gap + * @return new gap + * + */ +int FindNextGap(int gap) { + gap = (gap * 10) / 13; -int FindNextGap(int x) { - x = (x * 10) / 13; - - return std::max(1, x); + return std::max(1, gap); } -void CombSort(int a[], int l, int r) { - // Init gap - int gap = n; +/** Function to sort array + * + * @param arr array to be sorted + * @param l start index of array + * @param r end index of array + * + */ +void CombSort(int *arr, int l, int r) { + /** + * + * initial gap will be maximum and the maximum possible value is + * the size of the array that is n and which is equal to r in this + * case so to avoid passing an extra parameter n that is the size of + * the array we are using r to initialize the initial gap. + * + */ + int gap = r; - // 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 + /// Keep running until gap = 1 or none elements were swapped while (gap != 1 || swapped) { - // Find next gap + /// Find next gap gap = FindNextGap(gap); swapped = false; - // Compare all elements with current gap + /// Compare all elements with current gap for (int i = l; i <= r - gap; ++i) { - if (a[i] > a[i + gap]) { - std::swap(a[i], a[i + gap]); + if (arr[i] > arr[i + gap]) { + std::swap(arr[i], arr[i + gap]); swapped = true; } } } } +/** Main function */ 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) std::cout << a[i] << ' '; - return 0; + int n; + std::cin >> n; + int *arr = new int[n]; + for (int i = 0; i < n; ++i) std::cin >> arr[i]; + CombSort(arr, 0, n); + for (int i = 0; i < n; ++i) std::cout << arr[i] << ' '; + delete [] arr; + return 0; } From 33b5033adcb1e5551dfd3c6ca33ffe597316301b Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 23 Jun 2020 20:01:26 +0000 Subject: [PATCH 102/271] formatting source-code for f030a69288662f1d282a9d724501990830c5bda7 --- sorting/comb_sort.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/sorting/comb_sort.cpp b/sorting/comb_sort.cpp index 7e62c04ff..d44269814 100644 --- a/sorting/comb_sort.cpp +++ b/sorting/comb_sort.cpp @@ -71,12 +71,12 @@ void CombSort(int *arr, int l, int r) { /** Main function */ int main() { - int n; - std::cin >> n; - int *arr = new int[n]; - for (int i = 0; i < n; ++i) std::cin >> arr[i]; - CombSort(arr, 0, n); - for (int i = 0; i < n; ++i) std::cout << arr[i] << ' '; - delete [] arr; - return 0; + int n; + std::cin >> n; + int *arr = new int[n]; + for (int i = 0; i < n; ++i) std::cin >> arr[i]; + CombSort(arr, 0, n); + for (int i = 0; i < n; ++i) std::cout << arr[i] << ' '; + delete[] arr; + return 0; } From 0356a9cdf30b0f3ecdf5632e73e9f8a00a924253 Mon Sep 17 00:00:00 2001 From: Panquesito7 Date: Tue, 23 Jun 2020 14:35:13 -0500 Subject: [PATCH 103/271] fix: Various LGTM fixes --- data_structures/binary_search_tree.cpp | 12 ++++++------ math/realtime_stats.cpp | 2 +- sorting/bead_sort.cpp | 2 +- sorting/comb_sort.cpp | 6 +++--- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/data_structures/binary_search_tree.cpp b/data_structures/binary_search_tree.cpp index 3cc7d09fb..86057c6c5 100644 --- a/data_structures/binary_search_tree.cpp +++ b/data_structures/binary_search_tree.cpp @@ -14,17 +14,17 @@ struct node { node *right; }; -struct queue { +struct Queue { node *t[100]; int front; int rear; }; -queue q; +Queue queue; -void enqueue(node *n) { q.t[q.rear++] = n; } +void enqueue(node *n) { queue.t[queue.rear++] = n; } -node *dequeue() { return (q.t[q.front++]); } +node *dequeue() { return (queue.t[queue.front++]); } void Insert(node *n, int x) { if (x < n->val) { @@ -123,8 +123,8 @@ void Post(node *n) { } int main() { - q.front = 0; - q.rear = 0; + queue.front = 0; + queue.rear = 0; int value; int ch; node *root = new node; diff --git a/math/realtime_stats.cpp b/math/realtime_stats.cpp index 5f353ac4d..672acfa03 100644 --- a/math/realtime_stats.cpp +++ b/math/realtime_stats.cpp @@ -35,7 +35,7 @@ class stats_computer1 { n++; T tmp = x - K; Ex += tmp; - Ex2 += tmp * tmp; + Ex2 += static_cast(tmp) * tmp; } /** return sample mean computed till last sample */ diff --git a/sorting/bead_sort.cpp b/sorting/bead_sort.cpp index f3276bfcd..4745987d9 100644 --- a/sorting/bead_sort.cpp +++ b/sorting/bead_sort.cpp @@ -14,7 +14,7 @@ void beadSort(int *a, int len) { // allocating memory unsigned char *beads = new unsigned char[max * len]; - memset(beads, 0, max * len); + memset(beads, 0, static_cast(max) * len); // mark the beads for (int i = 0; i < len; i++) diff --git a/sorting/comb_sort.cpp b/sorting/comb_sort.cpp index 1b0a4d706..ab0b456dd 100644 --- a/sorting/comb_sort.cpp +++ b/sorting/comb_sort.cpp @@ -14,7 +14,7 @@ int FindNextGap(int x) { return std::max(1, x); } -void CombSort(int a[], int l, int r) { +void CombSort(int b[], int l, int r) { // Init gap int gap = n; @@ -30,8 +30,8 @@ void CombSort(int a[], int l, int r) { // Compare all elements with current gap for (int i = l; i <= r - gap; ++i) { - if (a[i] > a[i + gap]) { - std::swap(a[i], a[i + gap]); + if (b[i] > b[i + gap]) { + std::swap(b[i], b[i + gap]); swapped = true; } } From 92d2bf012ab4687bb973cc52d146740bf72ef9a3 Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Wed, 24 Jun 2020 01:49:33 +0530 Subject: [PATCH 104/271] Added tests for comb_sort.cpp --- sorting/comb_sort.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/sorting/comb_sort.cpp b/sorting/comb_sort.cpp index 7e62c04ff..00b12fcb2 100644 --- a/sorting/comb_sort.cpp +++ b/sorting/comb_sort.cpp @@ -17,6 +17,7 @@ #include #include +#include /** * @@ -69,8 +70,26 @@ void CombSort(int *arr, int l, int r) { } } +void tests() { + /// Test 1 + int arr1[10] = {34, 56, 6, 23, 76, 34, 76, 343, 4, 76}; + CombSort(arr1, 0, 10); + assert(std::is_sorted(arr1, arr1 + 10)); + std::cout << "Test 1 passed\n"; + + /// Test 2 + int arr2[8] = {-6, 56, -45, 56, 0, -1, 8, 8}; + CombSort(arr2, 0, 8); + assert(std::is_sorted(arr2, arr2 + 8)); + std::cout << "Test 2 Passed\n"; +} + /** Main function */ int main() { + /// Running predefined tests + tests(); + + /// For user interaction int n; std::cin >> n; int *arr = new int[n]; From 48a163e51ab53a73c9edbb02633e6a3673865cea Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 23 Jun 2020 20:22:30 +0000 Subject: [PATCH 105/271] formatting source-code for 3a7a266ada62816c9602bfd9d5b632b80a169617 --- sorting/comb_sort.cpp | 44 +++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/sorting/comb_sort.cpp b/sorting/comb_sort.cpp index 00b12fcb2..e99ae9514 100644 --- a/sorting/comb_sort.cpp +++ b/sorting/comb_sort.cpp @@ -16,8 +16,8 @@ */ #include -#include #include +#include /** * @@ -71,31 +71,31 @@ void CombSort(int *arr, int l, int r) { } void tests() { - /// Test 1 - int arr1[10] = {34, 56, 6, 23, 76, 34, 76, 343, 4, 76}; - CombSort(arr1, 0, 10); - assert(std::is_sorted(arr1, arr1 + 10)); - std::cout << "Test 1 passed\n"; + /// Test 1 + int arr1[10] = {34, 56, 6, 23, 76, 34, 76, 343, 4, 76}; + CombSort(arr1, 0, 10); + assert(std::is_sorted(arr1, arr1 + 10)); + std::cout << "Test 1 passed\n"; - /// Test 2 - int arr2[8] = {-6, 56, -45, 56, 0, -1, 8, 8}; - CombSort(arr2, 0, 8); - assert(std::is_sorted(arr2, arr2 + 8)); - std::cout << "Test 2 Passed\n"; + /// Test 2 + int arr2[8] = {-6, 56, -45, 56, 0, -1, 8, 8}; + CombSort(arr2, 0, 8); + assert(std::is_sorted(arr2, arr2 + 8)); + std::cout << "Test 2 Passed\n"; } /** Main function */ int main() { - /// Running predefined tests - tests(); + /// Running predefined tests + tests(); - /// For user interaction - int n; - std::cin >> n; - int *arr = new int[n]; - for (int i = 0; i < n; ++i) std::cin >> arr[i]; - CombSort(arr, 0, n); - for (int i = 0; i < n; ++i) std::cout << arr[i] << ' '; - delete [] arr; - return 0; + /// For user interaction + int n; + std::cin >> n; + int *arr = new int[n]; + for (int i = 0; i < n; ++i) std::cin >> arr[i]; + CombSort(arr, 0, n); + for (int i = 0; i < n; ++i) std::cout << arr[i] << ' '; + delete[] arr; + return 0; } From 0767af4a0d20f22c9bb22e569aa9d24ea5a09f5a Mon Sep 17 00:00:00 2001 From: Panquesito7 Date: Tue, 23 Jun 2020 15:26:55 -0500 Subject: [PATCH 106/271] fix: Revert `comb_sort` changes --- sorting/comb_sort.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/sorting/comb_sort.cpp b/sorting/comb_sort.cpp index ab0b456dd..1b0a4d706 100644 --- a/sorting/comb_sort.cpp +++ b/sorting/comb_sort.cpp @@ -14,7 +14,7 @@ int FindNextGap(int x) { return std::max(1, x); } -void CombSort(int b[], int l, int r) { +void CombSort(int a[], int l, int r) { // Init gap int gap = n; @@ -30,8 +30,8 @@ void CombSort(int b[], int l, int r) { // Compare all elements with current gap for (int i = l; i <= r - gap; ++i) { - if (b[i] > b[i + gap]) { - std::swap(b[i], b[i + gap]); + if (a[i] > a[i + gap]) { + std::swap(a[i], a[i + gap]); swapped = true; } } From 2464d438f9a3a579fd3ed97589d4ccb9c353c509 Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Wed, 24 Jun 2020 02:06:52 +0530 Subject: [PATCH 107/271] deleted line 27 --- data_structures/binaryheap.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/data_structures/binaryheap.cpp b/data_structures/binaryheap.cpp index c3a1f5cf6..21da4845b 100644 --- a/data_structures/binaryheap.cpp +++ b/data_structures/binaryheap.cpp @@ -24,7 +24,6 @@ class MinHeap { /** to heapify a subtree with the root at given index */ - void MinHeapify(int); int parent(int i) { return (i - 1) / 2; } From 62aafd1c5079260b649e6cae5f8133d9e8287b36 Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Wed, 24 Jun 2020 02:22:20 +0530 Subject: [PATCH 108/271] reverted line 27 --- data_structures/binaryheap.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/data_structures/binaryheap.cpp b/data_structures/binaryheap.cpp index 21da4845b..483bd7c02 100644 --- a/data_structures/binaryheap.cpp +++ b/data_structures/binaryheap.cpp @@ -22,8 +22,8 @@ class MinHeap { harr = new int[cap]; } - /** 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; } From 48b7773b37fe13792eed229e12aa54bec7d1ce5a Mon Sep 17 00:00:00 2001 From: Panquesito7 Date: Tue, 23 Jun 2020 16:34:53 -0500 Subject: [PATCH 109/271] fix: Various LGTM fixes --- data_structures/stack_using_array.cpp | 14 +++++++------- data_structures/stack_using_linked_list.cpp | 14 +++++++------- math/fibonacci_fast.cpp | 12 ++++++------ others/paranthesis_matching.cpp | 10 +++++----- 4 files changed, 25 insertions(+), 25 deletions(-) diff --git a/data_structures/stack_using_array.cpp b/data_structures/stack_using_array.cpp index 36be9eb39..ab2d7d7dd 100644 --- a/data_structures/stack_using_array.cpp +++ b/data_structures/stack_using_array.cpp @@ -1,31 +1,31 @@ #include int *stack; -int top = 0, stack_size; +int top_var = 0, stack_size; void push(int x) { - if (top == stack_size) { + if (top_var == stack_size) { std::cout << "\nOverflow"; } else { - stack[top++] = x; + stack[top_var++] = x; } } void pop() { - if (top == 0) { + if (top_var == 0) { std::cout << "\nUnderflow"; } else { - std::cout << "\n" << stack[--top] << " deleted"; + std::cout << "\n" << stack[--top_var] << " deleted"; } } void show() { - for (int i = 0; i < top; i++) { + for (int i = 0; i < top_var; i++) { std::cout << stack[i] << "\n"; } } -void topmost() { std::cout << "\nTopmost element: " << stack[top - 1]; } +void topmost() { std::cout << "\nTopmost element: " << stack[top_var - 1]; } int main() { std::cout << "\nEnter stack_size of stack : "; std::cin >> stack_size; diff --git a/data_structures/stack_using_linked_list.cpp b/data_structures/stack_using_linked_list.cpp index ae53fe95a..05f0d3d6a 100644 --- a/data_structures/stack_using_linked_list.cpp +++ b/data_structures/stack_using_linked_list.cpp @@ -6,28 +6,28 @@ struct node { node *next; }; -node *top; +node *top_var; void push(int x) { node *n = new node; n->val = x; - n->next = top; - top = n; + n->next = top_var; + top_var = n; } void pop() { - if (top == NULL) { + if (top_var == NULL) { cout << "\nUnderflow"; } else { - node *t = top; + node *t = top_var; cout << "\n" << t->val << " deleted"; - top = top->next; + top_var = top_var->next; delete t; } } void show() { - node *t = top; + node *t = top_var; while (t != NULL) { cout << t->val << "\n"; t = t->next; diff --git a/math/fibonacci_fast.cpp b/math/fibonacci_fast.cpp index 8fdb20058..80e9108ea 100644 --- a/math/fibonacci_fast.cpp +++ b/math/fibonacci_fast.cpp @@ -24,23 +24,23 @@ const uint64_t MAX = 93; /** Array of computed fibonacci numbers */ -uint64_t f[MAX] = {0}; +uint64_t numbers[MAX] = {0}; /** Algorithm */ uint64_t fib(uint64_t n) { if (n == 0) return 0; if (n == 1 || n == 2) - return (f[n] = 1); + return (numbers[n] = 1); - if (f[n]) - return f[n]; + if (numbers[n]) + return numbers[n]; 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)) + numbers[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]; + return numbers[n]; } /** Main function */ diff --git a/others/paranthesis_matching.cpp b/others/paranthesis_matching.cpp index 2a6358d94..0a1a9e474 100644 --- a/others/paranthesis_matching.cpp +++ b/others/paranthesis_matching.cpp @@ -20,13 +20,13 @@ char stack[MAX]; //! pointer to track stack index -int top = -1; +int top_var = -1; //! push byte to stack variable -void push(char ch) { stack[++top] = ch; } +void push(char ch) { stack[++top_var] = ch; } //! pop a byte out of stack variable -char pop() { return stack[top--]; } +char pop() { return stack[top_var--]; } //! @}-------------- end stack ----------- @@ -56,7 +56,7 @@ int main() { 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_var >= 0 && stack[top_var] == opening(exp[i])) { pop(); } else { valid = 0; @@ -65,7 +65,7 @@ int main() { } // makes sure the stack is empty after processsing (above) - if (valid == 1 && top == -1) { + if (valid == 1 && top_var == -1) { std::cout << "\nCorrect Expression"; } else { std::cout << "\nWrong Expression"; From cdacbf1998fd060c08897c687f8f695ff27559fa Mon Sep 17 00:00:00 2001 From: Panquesito7 Date: Tue, 23 Jun 2020 16:37:46 -0500 Subject: [PATCH 110/271] fix: Remove namespace --- data_structures/stack_using_linked_list.cpp | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/data_structures/stack_using_linked_list.cpp b/data_structures/stack_using_linked_list.cpp index 05f0d3d6a..3dcf03f8a 100644 --- a/data_structures/stack_using_linked_list.cpp +++ b/data_structures/stack_using_linked_list.cpp @@ -1,5 +1,4 @@ #include -using namespace std; struct node { int val; @@ -17,10 +16,10 @@ void push(int x) { void pop() { if (top_var == NULL) { - cout << "\nUnderflow"; + std::cout << "\nUnderflow"; } else { node *t = top_var; - cout << "\n" << t->val << " deleted"; + std::cout << "\n" << t->val << " deleted"; top_var = top_var->next; delete t; } @@ -29,7 +28,7 @@ void pop() { void show() { node *t = top_var; while (t != NULL) { - cout << t->val << "\n"; + std::cout << t->val << "\n"; t = t->next; } } @@ -37,14 +36,14 @@ void show() { int main() { int ch, x; do { - cout << "\n1. Push"; - cout << "\n2. Pop"; - cout << "\n3. Print"; - cout << "\nEnter Your Choice : "; - cin >> ch; + std::cout << "\n1. Push"; + std::cout << "\n2. Pop"; + std::cout << "\n3. Print"; + 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 a6c3667f308cc27c3b97beafe0123885d38114a2 Mon Sep 17 00:00:00 2001 From: Panquesito7 Date: Tue, 23 Jun 2020 17:38:17 -0500 Subject: [PATCH 111/271] fix: Release allocated memory --- data_structures/stack_using_array.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/data_structures/stack_using_array.cpp b/data_structures/stack_using_array.cpp index ab2d7d7dd..6702f2d59 100644 --- a/data_structures/stack_using_array.cpp +++ b/data_structures/stack_using_array.cpp @@ -51,5 +51,7 @@ int main() { } } while (ch != 0); + delete stack; + return 0; } From 957a05bd0cd7e21017e13f57be3998ae1cdd7b73 Mon Sep 17 00:00:00 2001 From: Panquesito7 Date: Tue, 23 Jun 2020 17:39:29 -0500 Subject: [PATCH 112/271] fix: Convert global variables to local --- math/fibonacci_fast.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/math/fibonacci_fast.cpp b/math/fibonacci_fast.cpp index 80e9108ea..dba8b9dc0 100644 --- a/math/fibonacci_fast.cpp +++ b/math/fibonacci_fast.cpp @@ -19,15 +19,15 @@ #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 numbers[MAX] = {0}; - /** Algorithm */ uint64_t fib(uint64_t n) { + // maximum number that can be computed - The result after 93 cannot be stored + // in a `uint64_t` data type. + static const uint64_t MAX = 93; + + // Array of computed fibonacci numbers */ + static uint64_t numbers[MAX] = {0}; + if (n == 0) return 0; if (n == 1 || n == 2) From cea644bdc31710e1544623934e8ca8646fc9a97d Mon Sep 17 00:00:00 2001 From: Panquesito7 Date: Tue, 23 Jun 2020 17:52:04 -0500 Subject: [PATCH 113/271] fix: Use delete[] operator --- data_structures/stack_using_array.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data_structures/stack_using_array.cpp b/data_structures/stack_using_array.cpp index 6702f2d59..b78e08e37 100644 --- a/data_structures/stack_using_array.cpp +++ b/data_structures/stack_using_array.cpp @@ -51,7 +51,7 @@ int main() { } } while (ch != 0); - delete stack; + delete[] stack; return 0; } From da18b9049898dc061e3cb2e5b73f173a90bf19d4 Mon Sep 17 00:00:00 2001 From: Panquesito7 Date: Tue, 23 Jun 2020 17:53:20 -0500 Subject: [PATCH 114/271] fix: Use #define --- math/fibonacci_fast.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/math/fibonacci_fast.cpp b/math/fibonacci_fast.cpp index dba8b9dc0..fa81f9561 100644 --- a/math/fibonacci_fast.cpp +++ b/math/fibonacci_fast.cpp @@ -19,12 +19,15 @@ #include #include +/** + * maximum number that can be computed - The result after 93 cannot be stored + * in a `uint64_t` data type. + */ + +#define MAX 93 + /** Algorithm */ uint64_t fib(uint64_t n) { - // maximum number that can be computed - The result after 93 cannot be stored - // in a `uint64_t` data type. - static const uint64_t MAX = 93; - // Array of computed fibonacci numbers */ static uint64_t numbers[MAX] = {0}; From 01c52789111c8853db3812a36b139e4670431eed Mon Sep 17 00:00:00 2001 From: Panquesito7 Date: Tue, 23 Jun 2020 18:22:21 -0500 Subject: [PATCH 115/271] fix: fibonacci_fast.cpp fixes --- math/fibonacci_fast.cpp | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/math/fibonacci_fast.cpp b/math/fibonacci_fast.cpp index fa81f9561..be68bab70 100644 --- a/math/fibonacci_fast.cpp +++ b/math/fibonacci_fast.cpp @@ -28,22 +28,20 @@ /** Algorithm */ uint64_t fib(uint64_t n) { - // Array of computed fibonacci numbers */ - static uint64_t numbers[MAX] = {0}; + static uint64_t f1 = 1, f2 = 1; // using static keyword will retain the values of f1 and f2 for the next function call. - if (n == 0) + if (n <= 2) + return f2; + if (n >= 93) { + std::err << "Cannot compute for n>93 due to limit of 64-bit integers\n"; return 0; - if (n == 1 || n == 2) - return (numbers[n] = 1); + } - if (numbers[n]) - return numbers[n]; + uint64_t temp = f2; // we do not need temp to be static + f2 += f1; + f1 = temp; - uint64_t k = (n % 2 != 0) ? (n + 1) / 2 : n / 2; - - numbers[n] = (n % 2 != 0) ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) - : (2 * fib(k - 1) + fib(k)) * fib(k); - return numbers[n]; + return f2; } /** Main function */ From 52b9b0bb98ad730822fc07834e2f06afeaebe8f4 Mon Sep 17 00:00:00 2001 From: Panquesito7 Date: Tue, 23 Jun 2020 18:23:37 -0500 Subject: [PATCH 116/271] docs: Change variable name --- data_structures/stack_using_array.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/data_structures/stack_using_array.cpp b/data_structures/stack_using_array.cpp index b78e08e37..22b397ba8 100644 --- a/data_structures/stack_using_array.cpp +++ b/data_structures/stack_using_array.cpp @@ -1,31 +1,31 @@ #include int *stack; -int top_var = 0, stack_size; +int stack_idx = 0, stack_size; void push(int x) { - if (top_var == stack_size) { + if (stack_idx == stack_size) { std::cout << "\nOverflow"; } else { - stack[top_var++] = x; + stack[stack_idx++] = x; } } void pop() { - if (top_var == 0) { + if (stack_idx == 0) { std::cout << "\nUnderflow"; } else { - std::cout << "\n" << stack[--top_var] << " deleted"; + std::cout << "\n" << stack[--stack_idx] << " deleted"; } } void show() { - for (int i = 0; i < top_var; i++) { + for (int i = 0; i < stack_idx; i++) { std::cout << stack[i] << "\n"; } } -void topmost() { std::cout << "\nTopmost element: " << stack[top_var - 1]; } +void topmost() { std::cout << "\nTopmost element: " << stack[stack_idx - 1]; } int main() { std::cout << "\nEnter stack_size of stack : "; std::cin >> stack_size; From f05aadf3b8fddae08331fa127f7e75a6ab44e37a Mon Sep 17 00:00:00 2001 From: Panquesito7 Date: Tue, 23 Jun 2020 18:26:47 -0500 Subject: [PATCH 117/271] fix: Wrong function name --- 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 be68bab70..e7582df73 100644 --- a/math/fibonacci_fast.cpp +++ b/math/fibonacci_fast.cpp @@ -33,7 +33,7 @@ uint64_t fib(uint64_t n) { if (n <= 2) return f2; if (n >= 93) { - std::err << "Cannot compute for n>93 due to limit of 64-bit integers\n"; + std::cerr << "Cannot compute for n>93 due to limit of 64-bit integers\n"; return 0; } From b6fdaa63eb5f14c1a8d18aef476707baccd72ee6 Mon Sep 17 00:00:00 2001 From: Panquesito7 Date: Tue, 23 Jun 2020 18:45:56 -0500 Subject: [PATCH 118/271] docs: Change variable names --- data_structures/stack_using_linked_list.cpp | 14 +++++++------- others/paranthesis_matching.cpp | 10 +++++----- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/data_structures/stack_using_linked_list.cpp b/data_structures/stack_using_linked_list.cpp index 3dcf03f8a..315b4e3b9 100644 --- a/data_structures/stack_using_linked_list.cpp +++ b/data_structures/stack_using_linked_list.cpp @@ -5,28 +5,28 @@ struct node { node *next; }; -node *top_var; +node *stack_idx; void push(int x) { node *n = new node; n->val = x; - n->next = top_var; - top_var = n; + n->next = stack_idx; + stack_idx = n; } void pop() { - if (top_var == NULL) { + if (stack_idx == NULL) { std::cout << "\nUnderflow"; } else { - node *t = top_var; + node *t = stack_idx; std::cout << "\n" << t->val << " deleted"; - top_var = top_var->next; + stack_idx = stack_idx->next; delete t; } } void show() { - node *t = top_var; + node *t = stack_idx; while (t != NULL) { std::cout << t->val << "\n"; t = t->next; diff --git a/others/paranthesis_matching.cpp b/others/paranthesis_matching.cpp index 0a1a9e474..d9c52c813 100644 --- a/others/paranthesis_matching.cpp +++ b/others/paranthesis_matching.cpp @@ -20,13 +20,13 @@ char stack[MAX]; //! pointer to track stack index -int top_var = -1; +int stack_idx = -1; //! push byte to stack variable -void push(char ch) { stack[++top_var] = ch; } +void push(char ch) { stack[++stack_idx] = ch; } //! pop a byte out of stack variable -char pop() { return stack[top_var--]; } +char pop() { return stack[stack_idx--]; } //! @}-------------- end stack ----------- @@ -56,7 +56,7 @@ int main() { while (valid == 1 && i < exp.length()) { if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[' || exp[i] == '<') { push(exp[i]); - } else if (top_var >= 0 && stack[top_var] == opening(exp[i])) { + } else if (stack_idx >= 0 && stack[stack_idx] == opening(exp[i])) { pop(); } else { valid = 0; @@ -65,7 +65,7 @@ int main() { } // makes sure the stack is empty after processsing (above) - if (valid == 1 && top_var == -1) { + if (valid == 1 && stack_idx == -1) { std::cout << "\nCorrect Expression"; } else { std::cout << "\nWrong Expression"; From e0fa86816aee2c41d21a2716c0ef913c5ad1ec3e Mon Sep 17 00:00:00 2001 From: Panquesito7 Date: Tue, 23 Jun 2020 18:50:14 -0500 Subject: [PATCH 119/271] fix: Variable name --- data_structures/stack_using_linked_list.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/data_structures/stack_using_linked_list.cpp b/data_structures/stack_using_linked_list.cpp index 315b4e3b9..3dcf03f8a 100644 --- a/data_structures/stack_using_linked_list.cpp +++ b/data_structures/stack_using_linked_list.cpp @@ -5,28 +5,28 @@ struct node { node *next; }; -node *stack_idx; +node *top_var; void push(int x) { node *n = new node; n->val = x; - n->next = stack_idx; - stack_idx = n; + n->next = top_var; + top_var = n; } void pop() { - if (stack_idx == NULL) { + if (top_var == NULL) { std::cout << "\nUnderflow"; } else { - node *t = stack_idx; + node *t = top_var; std::cout << "\n" << t->val << " deleted"; - stack_idx = stack_idx->next; + top_var = top_var->next; delete t; } } void show() { - node *t = stack_idx; + node *t = top_var; while (t != NULL) { std::cout << t->val << "\n"; t = t->next; From 95890fdb6642ba584c28368126344a44aa69e2f2 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Wed, 24 Jun 2020 10:26:55 -0400 Subject: [PATCH 120/271] create copy constructor --- data_structures/stack.h | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/data_structures/stack.h b/data_structures/stack.h index f4b8992e7..3957b4d8d 100644 --- a/data_structures/stack.h +++ b/data_structures/stack.h @@ -34,6 +34,36 @@ class stack { size = 0; } + /** Copy constructor*/ + explicit stack(const stack &other) { + 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; + } + /** Destructor */ ~stack() {} From 94a494edf59a99ec0457e7fa264e7d17b4c5c6ce Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Wed, 24 Jun 2020 10:27:23 -0400 Subject: [PATCH 121/271] replace NULL with nullptr --- data_structures/stack.h | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/data_structures/stack.h b/data_structures/stack.h index 3957b4d8d..31a5abe34 100644 --- a/data_structures/stack.h +++ b/data_structures/stack.h @@ -20,7 +20,7 @@ class stack { void display() { node *current = stackTop; std::cout << "Top --> "; - while (current != NULL) { + while (current != nullptr) { std::cout << current->data << " "; current = current->next; } @@ -30,7 +30,7 @@ class stack { /** Default constructor*/ stack() { - stackTop = NULL; + stackTop = nullptr; size = 0; } @@ -39,23 +39,23 @@ class stack { node *newNode, *current, *last; /* If stack is no empty, make it empty */ - if (stackTop != NULL) { - stackTop = NULL; + if (stackTop != nullptr) { + stackTop = nullptr; } - if (otherStack.stackTop == NULL) { - stackTop = NULL; + if (otherStack.stackTop == nullptr) { + stackTop = nullptr; } else { current = otherStack.stackTop; stackTop = new node; stackTop->data = current->data; - stackTop->next = NULL; + stackTop->next = nullptr; last = stackTop; current = current->next; /* Copy the remaining stack */ - while (current != NULL) { + while (current != nullptr) { newNode = new node; newNode->data = current->data; - newNode->next = NULL; + newNode->next = nullptr; last->next = newNode; last = newNode; current = current->next; @@ -68,7 +68,7 @@ class stack { ~stack() {} /** Determine whether the stack is empty */ - bool isEmptyStack() { return (stackTop == NULL); } + bool isEmptyStack() { return (stackTop == nullptr); } /** Add new item to the stack */ void push(Type item) { @@ -82,7 +82,7 @@ class stack { /** Return the top element of the stack */ Type top() { - assert(stackTop != NULL); + assert(stackTop != nullptr); return stackTop->data; } @@ -100,30 +100,30 @@ class stack { } /** Clear stack */ - void clear() { stackTop = NULL; } + void clear() { stackTop = nullptr; } /** 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 (stackTop != nullptr) { + stackTop = nullptr; } - if (otherStack.stackTop == NULL) { - stackTop = NULL; + if (otherStack.stackTop == nullptr) { + stackTop = nullptr; } else { current = otherStack.stackTop; stackTop = new node; stackTop->data = current->data; - stackTop->next = NULL; + stackTop->next = nullptr; last = stackTop; current = current->next; /* Copy the remaining stack */ - while (current != NULL) { + while (current != nullptr) { newNode = new node; newNode->data = current->data; - newNode->next = NULL; + newNode->next = nullptr; last->next = newNode; last = newNode; current = current->next; From 631b50cede4ad0cc5ad350f88c2cc01280d54101 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Wed, 24 Jun 2020 10:37:15 -0400 Subject: [PATCH 122/271] update documetnation --- data_structures/stack.h | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/data_structures/stack.h b/data_structures/stack.h index 31a5abe34..429e0265f 100644 --- a/data_structures/stack.h +++ b/data_structures/stack.h @@ -1,18 +1,27 @@ -/* This class specifies the basic operation on a stack as a linked list */ +/** + * @file stack.h + * @author danghai + * @brief This class specifies the basic operation on a stack as a linked list + **/ #ifndef DATA_STRUCTURES_STACK_H_ #define DATA_STRUCTURES_STACK_H_ #include #include -/* Definition of the node */ +/** Definition of the node as a linked-list + * \tparam Type type of data nodes of the linked list should contain + */ template struct node { - Type data; - node *next; + Type data; ///< data at current node + node *next; ///< pointer to the next ::node instance }; -/* Definition of the stack class */ +/** Definition of the stack class + * \tparam Type type of data nodes of the linked list in the stack should + * contain + */ template class stack { public: @@ -135,7 +144,7 @@ class stack { private: node *stackTop; /**< Pointer to the stack */ - int size; + int size; ///< size of stack }; #endif // DATA_STRUCTURES_STACK_H_ From 9b01676b338ee75d6a2eb06574ed660d0ac9c5ea Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Wed, 24 Jun 2020 10:48:18 -0400 Subject: [PATCH 123/271] fixed function argument --- 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 429e0265f..483648046 100644 --- a/data_structures/stack.h +++ b/data_structures/stack.h @@ -44,7 +44,7 @@ class stack { } /** Copy constructor*/ - explicit stack(const stack &other) { + explicit stack(const stack &otherStack) { node *newNode, *current, *last; /* If stack is no empty, make it empty */ From 5e3307620c8a092a982610fa8f7ced49c7ce06f5 Mon Sep 17 00:00:00 2001 From: Neeraj C Date: Wed, 24 Jun 2020 20:46:23 +0530 Subject: [PATCH 124/271] feat: create math/armstrong_number.cpp --- math/armstrong_number.cpp | 77 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 math/armstrong_number.cpp diff --git a/math/armstrong_number.cpp b/math/armstrong_number.cpp new file mode 100644 index 000000000..0b5f01cd1 --- /dev/null +++ b/math/armstrong_number.cpp @@ -0,0 +1,77 @@ +/** + * @file + * \brief A C++ program to check whether a number is armstrong number or not. + * + * \details + * Armstrong number or [Narcissistic number](https://en.wikipedia.org/wiki/Narcissistic_number) + * is a number that is the sum of its own digits raised to the power of the number of digits. + * @author iamnambiar +*/ +#include +#include +#include + +/** + * Function to calculate the total number of digits in the number. + * @param num Number + * @return Total number of digits. + */ +int number_of_digits(int num) { + int total_digits = 0; + while (num > 0) { + num = num / 10; + ++total_digits; + } + return total_digits; +} + +/** + * Function to check whether the number is armstrong number or not. + * @param num Number + * @return `true` if the number is armstrong. + * @return `false` if the number is not armstrong. + */ +bool is_armstrong(int number) { + // If the number is less than 0, then it is not a armstrong number. + if (number < 0) { + return false; + } + int sum = 0; + int temp = number; + // Finding the total number of digits in the number + int total_digits = number_of_digits(number); + while (temp > 0) { + int rem = temp % 10; + // Finding each digit raised to the power total digit and add it to the total sum + sum = sum + pow(rem, total_digits); + temp = temp / 10; + } + return number == sum; +} + +/** + * Function for testing the is_amicable() with + * all the test cases. + */ +void test() { + // is_armstrong(370) returns true. + assert(is_armstrong(370) == true); + // is_armstrong(225) returns false. + assert(is_armstrong(225) == false); + // is_armstrong(-23) returns false. + assert(is_armstrong(-23) == false); + // is_armstrong(153) returns true. + assert(is_armstrong(153) == true); + // is_armstrong(0) returns true. + assert(is_armstrong(0) == true); + // is_armstrong(12) returns false. + assert(is_armstrong(12) == false); +} + +/** + * Main Function +*/ +int main() { + test(); + return 0; +} From 5b3e30a937e488b3de38673134db136cb1e19759 Mon Sep 17 00:00:00 2001 From: Neeraj C <35414531+iamnambiar@users.noreply.github.com> Date: Wed, 24 Jun 2020 20:52:32 +0530 Subject: [PATCH 125/271] docs: typo fixed --- math/armstrong_number.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/math/armstrong_number.cpp b/math/armstrong_number.cpp index 0b5f01cd1..166c98c07 100644 --- a/math/armstrong_number.cpp +++ b/math/armstrong_number.cpp @@ -50,8 +50,8 @@ bool is_armstrong(int number) { } /** - * Function for testing the is_amicable() with - * all the test cases. + * Function for testing the is_armstrong() function + * with all the test cases. */ void test() { // is_armstrong(370) returns true. From c7ff9d66f1e7c18b43e51d183f1299b25293ac55 Mon Sep 17 00:00:00 2001 From: Panquesito7 Date: Wed, 24 Jun 2020 12:12:30 -0500 Subject: [PATCH 126/271] feat: Add exit option --- data_structures/stack_using_array.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/data_structures/stack_using_array.cpp b/data_structures/stack_using_array.cpp index 22b397ba8..0c0813d5e 100644 --- a/data_structures/stack_using_array.cpp +++ b/data_structures/stack_using_array.cpp @@ -32,6 +32,7 @@ int main() { stack = new int[stack_size]; int ch, x; do { + std::cout << "\n0. Exit"; std::cout << "\n1. Push"; std::cout << "\n2. Pop"; std::cout << "\n3. Print"; From 4c6b3b86c1f191339770039b8c7f377a5a18fc4e Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Wed, 24 Jun 2020 17:14:57 +0000 Subject: [PATCH 127/271] formatting source-code for c7ff9d66f1e7c18b43e51d183f1299b25293ac55 --- math/fibonacci_fast.cpp | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/math/fibonacci_fast.cpp b/math/fibonacci_fast.cpp index e7582df73..0948276a0 100644 --- a/math/fibonacci_fast.cpp +++ b/math/fibonacci_fast.cpp @@ -19,7 +19,7 @@ #include #include -/** +/** * maximum number that can be computed - The result after 93 cannot be stored * in a `uint64_t` data type. */ @@ -28,16 +28,19 @@ /** Algorithm */ uint64_t fib(uint64_t n) { - static uint64_t f1 = 1, f2 = 1; // using static keyword will retain the values of f1 and f2 for the next function call. - + static uint64_t f1 = 1, + f2 = 1; // using static keyword will retain the values of + // f1 and f2 for the next function call. + if (n <= 2) return f2; if (n >= 93) { - std::cerr << "Cannot compute for n>93 due to limit of 64-bit integers\n"; + std::cerr + << "Cannot compute for n>93 due to limit of 64-bit integers\n"; return 0; } - uint64_t temp = f2; // we do not need temp to be static + uint64_t temp = f2; // we do not need temp to be static f2 += f1; f1 = temp; From f1ab19bb33f01b85a2082213dc6ae8c7ab4f22c6 Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Thu, 25 Jun 2020 03:39:12 +0530 Subject: [PATCH 128/271] fix: minor docs issue --- sorting/heap_sort.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sorting/heap_sort.cpp b/sorting/heap_sort.cpp index ef9f87094..d91cdb14f 100644 --- a/sorting/heap_sort.cpp +++ b/sorting/heap_sort.cpp @@ -26,7 +26,7 @@ /** * - * Utility Lambda function to print the array after + * Utility function to print the array after * sorting. * * @param arr array to be printed From a190674131ea47919edb5987e3d713b2a9b0c0d1 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Wed, 24 Jun 2020 18:27:01 -0400 Subject: [PATCH 129/271] fix errors in matrix_exponentiation --- others/matrix_exponentiation.cpp | 55 +++++++++++++++----------------- 1 file changed, 26 insertions(+), 29 deletions(-) diff --git a/others/matrix_exponentiation.cpp b/others/matrix_exponentiation.cpp index d44d22593..d646b3977 100644 --- a/others/matrix_exponentiation.cpp +++ b/others/matrix_exponentiation.cpp @@ -36,21 +36,18 @@ using std::vector; #define endl std::endl /*! shorthand definition for `int64_t` */ -#define pb push_back +#define pb push_back #define MOD 1000000007 -/** returns absolute value */ -inline ll ab(ll x) { return x > 0LL ? x : -x; } - -/** global variable k +/** global variable mat_size * @todo @stepfencurryxiao add documetnation */ -ll k; +ll mat_size; -/** global vector variables +/** global vector variables used in the ::ans function. * @todo @stepfencurryxiao add documetnation */ -vector a, b, c; +vector fib_b, fib_c; /** To multiply 2 matrices * \param [in] A matrix 1 of size (m\f$\times\f$n) @@ -59,10 +56,10 @@ vector a, b, c; */ 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++) { - for (ll z = 1; z <= k; z++) { + vector> C(mat_size + 1, vector(mat_size + 1)); + for (ll i = 1; i <= mat_size; i++) { + for (ll j = 1; j <= mat_size; j++) { + for (ll z = 1; z <= mat_size; z++) { C[i][j] = (C[i][j] + (A[i][z] * B[z][j]) % MOD) % MOD; } } @@ -94,24 +91,24 @@ vector> power(const vector> &A, ll p) { ll ans(ll n) { if (n == 0) return 0; - if (n <= k) - return b[n - 1]; + if (n <= mat_size) + return fib_b[n - 1]; // F1 - vector F1(k + 1); - for (ll i = 1; i <= k; i++) F1[i] = b[i - 1]; + vector F1(mat_size + 1); + for (ll i = 1; i <= mat_size; i++) F1[i] = fib_b[i - 1]; // 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) { + vector> T(mat_size + 1, vector(mat_size + 1)); + for (ll i = 1; i <= mat_size; i++) { + for (ll j = 1; j <= mat_size; j++) { + if (i < mat_size) { if (j == i + 1) T[i][j] = 1; else T[i][j] = 0; continue; } - T[i][j] = c[k - j]; + T[i][j] = fib_c[mat_size - j]; } } // T^n-1 @@ -119,7 +116,7 @@ ll ans(ll n) { // T*F1 ll res = 0; - for (ll i = 1; i <= k; i++) { + for (ll i = 1; i <= mat_size; i++) { res = (res + (T[1][i] * F1[i]) % MOD) % MOD; } return res; @@ -133,19 +130,19 @@ int main() { cin >> t; ll i, j, x; while (t--) { - cin >> k; - for (i = 0; i < k; i++) { + cin >> mat_size; + for (i = 0; i < mat_size; i++) { cin >> x; - b.pb(x); + fib_b.pb(x); } - for (i = 0; i < k; i++) { + for (i = 0; i < mat_size; i++) { cin >> x; - c.pb(x); + fib_c.pb(x); } cin >> x; cout << ans(x) << endl; - b.clear(); - c.clear(); + fib_b.clear(); + fib_c.clear(); } return 0; } From ef5f33083405e4d7f54650173f8aa9fcf9ff9fe7 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Wed, 24 Jun 2020 22:28:10 +0000 Subject: [PATCH 130/271] formatting source-code for a190674131ea47919edb5987e3d713b2a9b0c0d1 --- others/matrix_exponentiation.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/others/matrix_exponentiation.cpp b/others/matrix_exponentiation.cpp index d646b3977..bde7f521b 100644 --- a/others/matrix_exponentiation.cpp +++ b/others/matrix_exponentiation.cpp @@ -36,7 +36,7 @@ using std::vector; #define endl std::endl /*! shorthand definition for `int64_t` */ -#define pb push_back +#define pb push_back #define MOD 1000000007 /** global variable mat_size From e6ab38c2fdd803ebc241cce2aeb7a28161ac259a Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Thu, 25 Jun 2020 04:13:49 +0530 Subject: [PATCH 131/271] Added docs --- graph/connected_components.cpp | 71 +++++++++++++++++++++++++++++++++- 1 file changed, 70 insertions(+), 1 deletion(-) diff --git a/graph/connected_components.cpp b/graph/connected_components.cpp index 0bfb8bbdb..ab35f7587 100644 --- a/graph/connected_components.cpp +++ b/graph/connected_components.cpp @@ -1,29 +1,86 @@ +/** + * + * \file + * \brief [Connected Components + * (Connected Components)](https://en.wikipedia.org/wiki/Component_(graph_theory)) + * + * \author [Ayaan Khan](http://github.com/ayaankhan98) + * + * \details + * A graph is a collection of nodes also called vertices and these vertices + * are connected by edges. A connected component in a graph refers to a set of + * vertices which are reachable form one another. + * + * Example - Here is graph with 3 connected components + * + * 3 9 6 8 + * / \ / / \ / \ + * 2---4 2 7 3 7 + * + * first second third + * component component component + * + */ + +#include #include #include using std::vector; +/** + * Class for representing graph as a adjacency list. + */ class graph { private: + /** \brief adj stores adjacency list representation of graph */ vector> adj; + + /** \brief keep track of connected components */ int connected_components; + + /** \brief Utility function to perform depth first search on graph */ void depth_first_search(); + + /** \brief Utility function that explores given vertex in graph */ void explore(int, vector &); public: + /** + * \brief Constructor that intiliazes the graph on creation and set + * the connected components to 0 + */ explicit graph(int n) : adj(n, vector()) { connected_components = 0; } + + /** \brief Function to add a edge between two nodes or vertices of graph */ void addEdge(int, int); + + /** + * \brief Function the calculates the connected compoents in the graph + * by performing the depth first search on graph + * + * @return connected_components total connected components in graph + */ int getConnectedComponents() { depth_first_search(); return connected_components; } }; +/** + * \brief Function that add edge between two nodes or vertices of graph + * + * @param u any node or vertex of graph + * @param v any node or vertex of graph + */ void graph::addEdge(int u, int v) { adj[u - 1].push_back(v - 1); adj[v - 1].push_back(u - 1); } +/** + * \brief Function that perfoms depth first search algorithm on graph + */ void graph::depth_first_search() { int n = adj.size(); vector visited(n, false); @@ -35,7 +92,13 @@ void graph::depth_first_search() { } } } - +/** + * \brief Utility function for depth first seach algorithm + * this function explores the vertex which is passed into. + * + * @param u vertex or node to be explored + * @param visited already visited vertex + */ void graph::explore(int u, vector &visited) { visited[u] = true; for (auto v : adj[u]) { @@ -45,10 +108,16 @@ void graph::explore(int u, vector &visited) { } } +/** Main function */ int main() { + /// creating a graph with 4 vertex graph g(4); + + /// Adding edges between vertices g.addEdge(1, 2); g.addEdge(3, 2); + + /// printing the connected components std::cout << g.getConnectedComponents(); return 0; } From 6980792eff787eb58023042f4103be4af3f5ab14 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Wed, 24 Jun 2020 22:44:37 +0000 Subject: [PATCH 132/271] formatting source-code for e6ab38c2fdd803ebc241cce2aeb7a28161ac259a --- graph/connected_components.cpp | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/graph/connected_components.cpp b/graph/connected_components.cpp index ab35f7587..efff4e4c7 100644 --- a/graph/connected_components.cpp +++ b/graph/connected_components.cpp @@ -2,7 +2,8 @@ * * \file * \brief [Connected Components - * (Connected Components)](https://en.wikipedia.org/wiki/Component_(graph_theory)) + * (Connected + * Components)](https://en.wikipedia.org/wiki/Component_(graph_theory)) * * \author [Ayaan Khan](http://github.com/ayaankhan98) * @@ -33,7 +34,7 @@ using std::vector; */ class graph { private: - /** \brief adj stores adjacency list representation of graph */ + /** \brief adj stores adjacency list representation of graph */ vector> adj; /** \brief keep track of connected components */ @@ -46,16 +47,16 @@ class graph { void explore(int, vector &); public: - /** + /** * \brief Constructor that intiliazes the graph on creation and set * the connected components to 0 */ explicit graph(int n) : adj(n, vector()) { connected_components = 0; } - + /** \brief Function to add a edge between two nodes or vertices of graph */ void addEdge(int, int); - /** + /** * \brief Function the calculates the connected compoents in the graph * by performing the depth first search on graph * @@ -110,14 +111,14 @@ void graph::explore(int u, vector &visited) { /** Main function */ int main() { - /// creating a graph with 4 vertex + /// creating a graph with 4 vertex graph g(4); - /// Adding edges between vertices + /// Adding edges between vertices g.addEdge(1, 2); g.addEdge(3, 2); - /// printing the connected components + /// printing the connected components std::cout << g.getConnectedComponents(); return 0; } From 9c75856235a9cae35ae9833633ef37d65714bdef Mon Sep 17 00:00:00 2001 From: Neeraj C <35414531+iamnambiar@users.noreply.github.com> Date: Thu, 25 Jun 2020 07:59:39 +0530 Subject: [PATCH 133/271] docs: clean the comment Co-authored-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- math/armstrong_number.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/math/armstrong_number.cpp b/math/armstrong_number.cpp index 166c98c07..3b7e67cc5 100644 --- a/math/armstrong_number.cpp +++ b/math/armstrong_number.cpp @@ -1,6 +1,6 @@ /** * @file - * \brief A C++ program to check whether a number is armstrong number or not. + * \brief Program to check if a number is an [Armstrong/Narcissistic number](https://en.wikipedia.org/wiki/Narcissistic_number) in decimal system. * * \details * Armstrong number or [Narcissistic number](https://en.wikipedia.org/wiki/Narcissistic_number) From 06ca2a69532bb1bc17173d14804a2329450fe2e8 Mon Sep 17 00:00:00 2001 From: Neeraj C <35414531+iamnambiar@users.noreply.github.com> Date: Thu, 25 Jun 2020 08:00:37 +0530 Subject: [PATCH 134/271] fix: spaces between include and header file Co-authored-by: David Leal --- math/armstrong_number.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/math/armstrong_number.cpp b/math/armstrong_number.cpp index 3b7e67cc5..f8c7510e8 100644 --- a/math/armstrong_number.cpp +++ b/math/armstrong_number.cpp @@ -7,9 +7,9 @@ * is a number that is the sum of its own digits raised to the power of the number of digits. * @author iamnambiar */ -#include -#include -#include +#include +#include +#include /** * Function to calculate the total number of digits in the number. From 06f425493b1567a7394d533dda525b4d64583be9 Mon Sep 17 00:00:00 2001 From: Neeraj C <35414531+iamnambiar@users.noreply.github.com> Date: Thu, 25 Jun 2020 10:59:44 +0530 Subject: [PATCH 135/271] fix: changed to std::pow Co-authored-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- math/armstrong_number.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/math/armstrong_number.cpp b/math/armstrong_number.cpp index f8c7510e8..db8eb0fb7 100644 --- a/math/armstrong_number.cpp +++ b/math/armstrong_number.cpp @@ -43,7 +43,7 @@ bool is_armstrong(int number) { while (temp > 0) { int rem = temp % 10; // Finding each digit raised to the power total digit and add it to the total sum - sum = sum + pow(rem, total_digits); + sum = sum + std::pow(rem, total_digits); temp = temp / 10; } return number == sum; From 64bb640391f0d60bed8f87356ac86a487a94aac9 Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Thu, 25 Jun 2020 13:02:12 +0530 Subject: [PATCH 136/271] Wrapped example in

---
 graph/connected_components.cpp | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/graph/connected_components.cpp b/graph/connected_components.cpp
index ab35f7587..18c99cf45 100644
--- a/graph/connected_components.cpp
+++ b/graph/connected_components.cpp
@@ -11,6 +11,7 @@
  * are connected by edges. A connected component in a graph refers to a set of
  * vertices which are reachable form one another.
  *
+ * 
  * Example - Here is graph with 3 connected components
  *
  *      3   9           6               8
@@ -19,6 +20,7 @@
  *
  *    first          second           third
  *    component      component        component
+ * 
* */ From 351a1b712a982f72396559be40e7dd37d9b6db2c Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 25 Jun 2020 09:51:24 +0000 Subject: [PATCH 137/271] formatting source-code for ca70c3097e51f7a3845cabf3a140d3a1fb2f3cb3 --- math/armstrong_number.cpp | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/math/armstrong_number.cpp b/math/armstrong_number.cpp index db8eb0fb7..426de327b 100644 --- a/math/armstrong_number.cpp +++ b/math/armstrong_number.cpp @@ -1,15 +1,17 @@ /** * @file - * \brief Program to check if a number is an [Armstrong/Narcissistic number](https://en.wikipedia.org/wiki/Narcissistic_number) in decimal system. - * + * \brief Program to check if a number is an [Armstrong/Narcissistic + * number](https://en.wikipedia.org/wiki/Narcissistic_number) in decimal system. + * * \details - * Armstrong number or [Narcissistic number](https://en.wikipedia.org/wiki/Narcissistic_number) - * is a number that is the sum of its own digits raised to the power of the number of digits. + * Armstrong number or [Narcissistic + * number](https://en.wikipedia.org/wiki/Narcissistic_number) is a number that + * is the sum of its own digits raised to the power of the number of digits. * @author iamnambiar -*/ + */ #include -#include #include +#include /** * Function to calculate the total number of digits in the number. @@ -42,7 +44,8 @@ bool is_armstrong(int number) { int total_digits = number_of_digits(number); while (temp > 0) { int rem = temp % 10; - // Finding each digit raised to the power total digit and add it to the total sum + // Finding each digit raised to the power total digit and add it to the + // total sum sum = sum + std::pow(rem, total_digits); temp = temp / 10; } @@ -50,7 +53,7 @@ bool is_armstrong(int number) { } /** - * Function for testing the is_armstrong() function + * Function for testing the is_armstrong() function * with all the test cases. */ void test() { @@ -70,7 +73,7 @@ void test() { /** * Main Function -*/ + */ int main() { test(); return 0; From 21093365cd2b3ac8ba4e081329a4eb24827e42d0 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 25 Jun 2020 09:51:24 +0000 Subject: [PATCH 138/271] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 6e43ba3f2..257b4160d 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -100,6 +100,7 @@ * [Kohonen Som Trace](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/machine_learning/kohonen_som_trace.cpp) ## Math + * [Armstrong Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/armstrong_number.cpp) * [Binary Exponent](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/binary_exponent.cpp) * [Check Amicable Pair](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/check_amicable_pair.cpp) * [Check Prime](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/check_prime.cpp) From 05789603ab82ac5e00e2e5d415509719066687c8 Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Thu, 25 Jun 2020 15:49:30 +0530 Subject: [PATCH 139/271] fix: repeated sentences --- graph/connected_components.cpp | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/graph/connected_components.cpp b/graph/connected_components.cpp index ec7ef19e6..e53dbf424 100644 --- a/graph/connected_components.cpp +++ b/graph/connected_components.cpp @@ -1,9 +1,9 @@ /** * * \file - * \brief [Connected Components - * (Connected - * Components)](https://en.wikipedia.org/wiki/Component_(graph_theory)) + * \brief [Graph Connected Components + * (Connected Components)] + * (https://en.wikipedia.org/wiki/Component_(graph_theory)) * * \author [Ayaan Khan](http://github.com/ayaankhan98) * @@ -42,10 +42,7 @@ class graph { /** \brief keep track of connected components */ int connected_components; - /** \brief Utility function to perform depth first search on graph */ void depth_first_search(); - - /** \brief Utility function that explores given vertex in graph */ void explore(int, vector &); public: @@ -55,7 +52,6 @@ class graph { */ explicit graph(int n) : adj(n, vector()) { connected_components = 0; } - /** \brief Function to add a edge between two nodes or vertices of graph */ void addEdge(int, int); /** From 5939792a9dbef599055b3cc88e9835e6065ce2f2 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 25 Jun 2020 09:14:21 -0400 Subject: [PATCH 140/271] fix self-tests and unsigned comparision to zero refer #897 and https://lgtm.com/projects/g/TheAlgorithms/C-Plus-Plus/rev/pr-f6e7cda8faf908e87511f30e782190233bdee68c --- math/double_factorial.cpp | 35 +++++++++++++++++++++++++++++------ 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/math/double_factorial.cpp b/math/double_factorial.cpp index 8e5ffcefa..1d1f7dae4 100644 --- a/math/double_factorial.cpp +++ b/math/double_factorial.cpp @@ -32,10 +32,33 @@ uint64_t double_factorial_recursive(uint64_t n) { 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); +/** Wrapper to run tests using both recursive and iterative implementations. + * The checks are only valid in debug builds due to the use of `assert()` + * statements. + * \param [in] n number to check double factorial for + * \param [in] expected expected result + */ +void test(uint64_t n, uint64_t expected) { + assert(double_factorial_iterative(n) == expected); + assert(double_factorial_recursive(n) == expected); } + +/** + * Test implementations + */ +void tests() { + std::cout << "Test 1:\t n=5\t..."; + test(5, 15); + std::cout << "passed\n"; + + std::cout << "Test 2:\t n=15\t..."; + test(15, 2027025); + std::cout << "passed\n"; + + std::cout << "Test 3:\t n=0\t..."; + test(0, 1); + std::cout << "passed\n"; +} + +/// main function +int main() { tests(); } From d8b121b1191fed37442a52873692af36091f3c16 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 25 Jun 2020 09:26:20 -0400 Subject: [PATCH 141/271] disable timestamps in footer of html docs --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 957be35f5..adb1c740a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -25,7 +25,7 @@ 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_HTML_TIMESTAMP YES) set(DOXYGEN_EXTRACT_STATIC YES) set(DOXYGEN_INLINE_SOURCES YES) set(DOXYGEN_CREATE_SUBDIRS YES) From 66eb05e0daf68fdc43e0da3bf4a7b56038191b45 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 25 Jun 2020 09:59:36 -0400 Subject: [PATCH 142/271] added wiki link in file brieff --- 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 1d1f7dae4..a400ae147 100644 --- a/math/double_factorial.cpp +++ b/math/double_factorial.cpp @@ -1,8 +1,9 @@ /** * @file - * @brief Compute double factorial: \f$n!!\f$ + * @brief Compute [double + * factorial](https://en.wikipedia.org/wiki/Double_factorial): \f$n!!\f$ * - * Double factorial of a non-negative integer n, is defined as the product of + * 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 * \f$n!!\f$ From 2c61414a838611dc19ce6296164133d642b185fa Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 25 Jun 2020 13:38:11 -0400 Subject: [PATCH 143/271] split lu_decomposition to a header file and templated the function --- numerical_methods/lu_decompose.cpp | 74 +++------------------------- numerical_methods/lu_decomposition.h | 65 ++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 66 deletions(-) create mode 100644 numerical_methods/lu_decomposition.h diff --git a/numerical_methods/lu_decompose.cpp b/numerical_methods/lu_decompose.cpp index a0a2d00ab..2ce5fb653 100644 --- a/numerical_methods/lu_decompose.cpp +++ b/numerical_methods/lu_decompose.cpp @@ -7,73 +7,15 @@ #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; -} +#include "./lu_decomposition.h" /** * operator to print a matrix */ template std::ostream &operator<<(std::ostream &out, - std::vector> const &v) { + std::vector> const &v) { const int width = 10; const char separator = ' '; @@ -99,14 +41,14 @@ int main(int argc, char **argv) { 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 + std::vector> A(mat_size, + std::valarray(mat_size)); + std::vector> L( + mat_size, std::valarray(mat_size)); // output + std::vector> U( + mat_size, std::valarray(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(std::rand() % range - range2); diff --git a/numerical_methods/lu_decomposition.h b/numerical_methods/lu_decomposition.h new file mode 100644 index 000000000..9cb881ba9 --- /dev/null +++ b/numerical_methods/lu_decomposition.h @@ -0,0 +1,65 @@ +#pragma once + +#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 + */ +template +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; +} From e1b1c71e7cca268c9fbad41d2d6b315ff63b9756 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 25 Jun 2020 14:40:47 -0400 Subject: [PATCH 144/271] Apply suggestions from code review Co-authored-by: David Leal --- math/double_factorial.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/math/double_factorial.cpp b/math/double_factorial.cpp index a400ae147..db22cc672 100644 --- a/math/double_factorial.cpp +++ b/math/double_factorial.cpp @@ -61,5 +61,10 @@ void tests() { std::cout << "passed\n"; } -/// main function -int main() { tests(); } +/** + * Main function + */ +int main() { + tests(); + return 0; +} From b1620ff2f57036bbd81faf57d09268d7b368c1a3 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 25 Jun 2020 18:41:27 +0000 Subject: [PATCH 145/271] formatting source-code for e1b1c71e7cca268c9fbad41d2d6b315ff63b9756 --- math/double_factorial.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/math/double_factorial.cpp b/math/double_factorial.cpp index db22cc672..72feda60c 100644 --- a/math/double_factorial.cpp +++ b/math/double_factorial.cpp @@ -61,7 +61,7 @@ void tests() { std::cout << "passed\n"; } -/** +/** * Main function */ int main() { From e22f56c90628fa02017a43f581384a0c06551821 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 25 Jun 2020 18:43:00 +0000 Subject: [PATCH 146/271] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 257b4160d..679e6f7d8 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -140,6 +140,7 @@ * [Gaussian Elimination](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/gaussian_elimination.cpp) * [Golden Search Extrema](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/golden_search_extrema.cpp) * [Lu Decompose](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/lu_decompose.cpp) + * [Lu Decomposition](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/lu_decomposition.h) * [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) From f29c14032a73160444f5be4df03a2c03ca4acbb5 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 25 Jun 2020 14:51:54 -0400 Subject: [PATCH 147/271] added determinant computation using LU decomposition --- numerical_methods/lu_decomposition.h | 34 ++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/numerical_methods/lu_decomposition.h b/numerical_methods/lu_decomposition.h index 9cb881ba9..42c29e4f2 100644 --- a/numerical_methods/lu_decomposition.h +++ b/numerical_methods/lu_decomposition.h @@ -36,7 +36,9 @@ int lu_decomposition(const std::vector> &A, 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]; + 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; @@ -54,7 +56,9 @@ int lu_decomposition(const std::vector> &A, // 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]; + 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]; @@ -63,3 +67,29 @@ int lu_decomposition(const std::vector> &A, return 0; } + +/** + * @brief Compute determinant of an NxN square matrix using LU decomposition. + * Using LU decomposition, the determinant is given by the product of diagonal + * elements of matrices L and U. + * + * @tparam T datatype of input matrix - int, unsigned int, double, etc + * @param A input square matrix + * @return determinant of matrix A + */ +template +double determinant_lu(const std::vector> &A) { + std::vector> L(A.size(), + std::valarray(A.size())); + std::vector> U(A.size(), + std::valarray(A.size())); + + if (lu_decomposition(A, &L, &U) < 0) + return 0; + + double result = 1.f; + for (size_t i = 0; i < A.size(); i++) { + result *= L[i][i] * U[i][i]; + } + return result; +} From c1b0635f993c72fa32de11bc4df73b7dc77509b8 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 25 Jun 2020 15:03:12 -0400 Subject: [PATCH 148/271] create and added matrix type --- numerical_methods/lu_decomposition.h | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/numerical_methods/lu_decomposition.h b/numerical_methods/lu_decomposition.h index 42c29e4f2..22af249a5 100644 --- a/numerical_methods/lu_decomposition.h +++ b/numerical_methods/lu_decomposition.h @@ -7,6 +7,10 @@ #include #endif +/** Define matrix type as a `std::vector` of `std::valarray` */ +template +using matrix = std::vector>; + /** Perform LU decomposition on matrix * \param[in] A matrix to decompose * \param[out] L output L matrix @@ -15,9 +19,7 @@ * \returns negative if error occurred */ template -int lu_decomposition(const std::vector> &A, - std::vector> *L, - std::vector> *U) { +int lu_decomposition(const matrix &A, matrix *L, matrix *U) { int row, col, j; int mat_size = A.size(); @@ -78,11 +80,9 @@ int lu_decomposition(const std::vector> &A, * @return determinant of matrix A */ template -double determinant_lu(const std::vector> &A) { - std::vector> L(A.size(), - std::valarray(A.size())); - std::vector> U(A.size(), - std::valarray(A.size())); +double determinant_lu(const matrix &A) { + matrix L(A.size(), std::valarray(A.size())); + matrix U(A.size(), std::valarray(A.size())); if (lu_decomposition(A, &L, &U) < 0) return 0; From 84cf0da2bbf3dc7c1dd0dd8ff916317208068cef Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 25 Jun 2020 15:03:57 -0400 Subject: [PATCH 149/271] automated self-test of LU decomposition using sample case and determinant checks --- numerical_methods/lu_decompose.cpp | 52 +++++++++++++++++++++--------- 1 file changed, 37 insertions(+), 15 deletions(-) diff --git a/numerical_methods/lu_decompose.cpp b/numerical_methods/lu_decompose.cpp index 2ce5fb653..b27fed2ee 100644 --- a/numerical_methods/lu_decompose.cpp +++ b/numerical_methods/lu_decompose.cpp @@ -4,6 +4,7 @@ * square matrix * \author [Krishna Vedala](https://github.com/kvedala) */ +#include #include #include #include @@ -14,8 +15,7 @@ * operator to print a matrix */ template -std::ostream &operator<<(std::ostream &out, - std::vector> const &v) { +std::ostream &operator<<(std::ostream &out, matrix const &v) { const int width = 10; const char separator = ' '; @@ -29,24 +29,19 @@ std::ostream &operator<<(std::ostream &out, return out; } -/** Main function */ -int main(int argc, char **argv) { +/** + * Test LU decomposition + * \todo better ways to self-check a matrix output? + */ +void test1() { 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::valarray(mat_size)); - std::vector> L( - mat_size, std::valarray(mat_size)); // output - std::vector> U( - mat_size, std::valarray(mat_size)); // output + matrix A(mat_size, std::valarray(mat_size)); + matrix L(mat_size, std::valarray(mat_size)); // output + matrix U(mat_size, std::valarray(mat_size)); // output for (int i = 0; i < mat_size; i++) { // calloc so that all valeus are '0' by default for (int j = 0; j < mat_size; j++) @@ -63,6 +58,33 @@ int main(int argc, char **argv) { std::cout << "A = \n" << A << "\n"; std::cout << "L = \n" << L << "\n"; std::cout << "U = \n" << U << "\n"; +} +/** + * @brief Test determinant computation using LU decomposition + */ +void test2() { + std::cout << "Determinant test 1..."; + matrix A1({{1, 2, 3}, {4, 9, 6}, {7, 8, 9}}); + assert(determinant_lu(A1) == -48); + std::cout << "passed\n"; + + std::cout << "Determinant test 2..."; + matrix A2({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}); + assert(determinant_lu(A2) == 0); + std::cout << "passed\n"; + + std::cout << "Determinant test 3..."; + matrix A3({{1.2, 2.3, 3.4}, {4.5, 5.6, 6.7}, {7.8, 8.9, 9.0}}); + assert(determinant_lu(A3) == 3.63); + std::cout << "passed\n"; +} + +/** Main function */ +int main(int argc, char **argv) { + std::srand(std::time(NULL)); // random number initializer + + test1(); + test2(); return 0; } From 68dd9b1235f1d2a33d0a873a33ff55846bc8a4f6 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 25 Jun 2020 15:22:02 -0400 Subject: [PATCH 150/271] added file documentation --- numerical_methods/lu_decomposition.h | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/numerical_methods/lu_decomposition.h b/numerical_methods/lu_decomposition.h index 22af249a5..4999fc40f 100644 --- a/numerical_methods/lu_decomposition.h +++ b/numerical_methods/lu_decomposition.h @@ -1,3 +1,10 @@ +/** + * @file lu_decomposition.h + * @author [Krishna Vedala](https://github.com/kvedala) + * @brief Functions associated with [LU + * Decomposition](https://en.wikipedia.org/wiki/LU_decomposition) + * of a square matrix. + */ #pragma once #include From 0429b5dd888030ce9b0c069875491aac1261660e Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 25 Jun 2020 18:01:41 -0400 Subject: [PATCH 151/271] fix documentation --- numerical_methods/lu_decompose.cpp | 2 +- numerical_methods/lu_decomposition.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/numerical_methods/lu_decompose.cpp b/numerical_methods/lu_decompose.cpp index b27fed2ee..66f1a8551 100644 --- a/numerical_methods/lu_decompose.cpp +++ b/numerical_methods/lu_decompose.cpp @@ -61,7 +61,7 @@ void test1() { } /** - * @brief Test determinant computation using LU decomposition + * Test determinant computation using LU decomposition */ void test2() { std::cout << "Determinant test 1..."; diff --git a/numerical_methods/lu_decomposition.h b/numerical_methods/lu_decomposition.h index 4999fc40f..402fe6e3b 100644 --- a/numerical_methods/lu_decomposition.h +++ b/numerical_methods/lu_decomposition.h @@ -78,7 +78,7 @@ int lu_decomposition(const matrix &A, matrix *L, matrix *U) { } /** - * @brief Compute determinant of an NxN square matrix using LU decomposition. + * Compute determinant of an NxN square matrix using LU decomposition. * Using LU decomposition, the determinant is given by the product of diagonal * elements of matrices L and U. * From b964f9af009a35018059a4bc08653774b71ee61a Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Fri, 26 Jun 2020 17:04:19 +0530 Subject: [PATCH 152/271] fix: minor typo --- numerical_methods/ordinary_least_squares_regressor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/numerical_methods/ordinary_least_squares_regressor.cpp b/numerical_methods/ordinary_least_squares_regressor.cpp index bbd75a742..832d6edf7 100644 --- a/numerical_methods/ordinary_least_squares_regressor.cpp +++ b/numerical_methods/ordinary_least_squares_regressor.cpp @@ -369,7 +369,7 @@ int main() { std::vector Y(N); std::cout - << "Enter training data. Per sample, provide features ad one output." + << "Enter training data. Per sample, provide features and one output." << std::endl; for (size_t rows = 0; rows < N; rows++) { From 11a6542bf2704de3cbba22843fa8322e87569cc0 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 26 Jun 2020 08:04:01 -0400 Subject: [PATCH 153/271] added test cases --- .../ordinary_least_squares_regressor.cpp | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/numerical_methods/ordinary_least_squares_regressor.cpp b/numerical_methods/ordinary_least_squares_regressor.cpp index bbd75a742..d36a84042 100644 --- a/numerical_methods/ordinary_least_squares_regressor.cpp +++ b/numerical_methods/ordinary_least_squares_regressor.cpp @@ -9,6 +9,7 @@ * * \author [Krishna Vedala](https://github.com/kvedala) */ +#include #include // for print formatting #include #include @@ -352,10 +353,48 @@ std::vector predict_OLS_regressor(std::vector> const &X, return result; } +/** Self test checks */ +void test() { + int F = 3, N = 5; + + // test function = x^2 -5 + std::cout << "Test 1 (quadratic function)...."; + std::vector> data1( + {{-5, 25, -125}, {-1, 1, -1}, {0, 0, 0}, {1, 1, 1}, {6, 36, 216}}); + std::vector Y1({20, -4, -5, -4, 31}); + std::vector beta1 = fit_OLS_regressor(data1, Y1); + std::vector> test1( + {{-2, 4, -8}, {2, 4, 8}, {-10, 100, -1000}, {10, 100, 1000}}); + std::vector expected1({-1, -1, 95, 95}); + std::vector out1 = predict_OLS_regressor(test1, beta1); + for (size_t rows = 0; rows < out1.size(); rows++) + assert(std::abs(out1[rows] - expected1[rows]) < 0.01); // accuracy + std::cout << "passed\n"; + + // test function = x^3 + x^2 - 100 + std::cout << "Test 2 (cubic function)...."; + std::vector> data2( + {{-5, 25, -125}, {-1, 1, -1}, {0, 0, 0}, {1, 1, 1}, {6, 36, 216}}); + std::vector Y2({-200, -100, -100, 98, 152}); + std::vector beta2 = fit_OLS_regressor(data2, Y2); + std::vector> test2( + {{-2, 4, -8}, {2, 4, 8}, {-10, 100, -1000}, {10, 100, 1000}}); + std::vector expected2({-104, -88, -1000, 1000}); + std::vector out2 = predict_OLS_regressor(test2, beta2); + for (size_t rows = 0; rows < out2.size(); rows++) + assert(std::abs(out2[rows] - expected2[rows]) < 0.01); // accuracy + std::cout << "passed\n"; + + std::cout << std::endl; // ensure test results are displayed on screen + // (flush stdout) +} + /** * main function */ int main() { + test(); + size_t N, F; std::cout << "Enter number of features: "; From 6d127e3adfbbb0f64abb94d1800fa5f5c66ec3cc Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 26 Jun 2020 08:09:34 -0400 Subject: [PATCH 154/271] added inline documentation --- .../ordinary_least_squares_regressor.cpp | 22 +++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/numerical_methods/ordinary_least_squares_regressor.cpp b/numerical_methods/ordinary_least_squares_regressor.cpp index d36a84042..614fdab9a 100644 --- a/numerical_methods/ordinary_least_squares_regressor.cpp +++ b/numerical_methods/ordinary_least_squares_regressor.cpp @@ -357,32 +357,46 @@ std::vector predict_OLS_regressor(std::vector> const &X, void test() { int F = 3, N = 5; - // test function = x^2 -5 + /* test function = x^2 -5 */ std::cout << "Test 1 (quadratic function)...."; + // create training data set with features = x, x^2, x^3 std::vector> data1( {{-5, 25, -125}, {-1, 1, -1}, {0, 0, 0}, {1, 1, 1}, {6, 36, 216}}); + // create corresponding outputs std::vector Y1({20, -4, -5, -4, 31}); + // perform regression modelling std::vector beta1 = fit_OLS_regressor(data1, Y1); + // create test data set with same features = x, x^2, x^3 std::vector> test1( {{-2, 4, -8}, {2, 4, 8}, {-10, 100, -1000}, {10, 100, 1000}}); + // expected regression outputs std::vector expected1({-1, -1, 95, 95}); + // predicted regression outputs std::vector out1 = predict_OLS_regressor(test1, beta1); + // compare predicted results are within +-0.01 limit of expected for (size_t rows = 0; rows < out1.size(); rows++) - assert(std::abs(out1[rows] - expected1[rows]) < 0.01); // accuracy + assert(std::abs(out1[rows] - expected1[rows]) < 0.01); std::cout << "passed\n"; - // test function = x^3 + x^2 - 100 + /* test function = x^3 + x^2 - 100 */ std::cout << "Test 2 (cubic function)...."; + // create training data set with features = x, x^2, x^3 std::vector> data2( {{-5, 25, -125}, {-1, 1, -1}, {0, 0, 0}, {1, 1, 1}, {6, 36, 216}}); + // create corresponding outputs std::vector Y2({-200, -100, -100, 98, 152}); + // perform regression modelling std::vector beta2 = fit_OLS_regressor(data2, Y2); + // create test data set with same features = x, x^2, x^3 std::vector> test2( {{-2, 4, -8}, {2, 4, 8}, {-10, 100, -1000}, {10, 100, 1000}}); + // expected regression outputs std::vector expected2({-104, -88, -1000, 1000}); + // predicted regression outputs std::vector out2 = predict_OLS_regressor(test2, beta2); + // compare predicted results are within +-0.01 limit of expected for (size_t rows = 0; rows < out2.size(); rows++) - assert(std::abs(out2[rows] - expected2[rows]) < 0.01); // accuracy + assert(std::abs(out2[rows] - expected2[rows]) < 0.01); std::cout << "passed\n"; std::cout << std::endl; // ensure test results are displayed on screen From 0d2a58409e3c9c4a1c77878555b93c8de36c1a01 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 26 Jun 2020 08:14:50 -0400 Subject: [PATCH 155/271] include cstdlib for std::abs() --- numerical_methods/ordinary_least_squares_regressor.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/numerical_methods/ordinary_least_squares_regressor.cpp b/numerical_methods/ordinary_least_squares_regressor.cpp index 614fdab9a..4761a6d96 100644 --- a/numerical_methods/ordinary_least_squares_regressor.cpp +++ b/numerical_methods/ordinary_least_squares_regressor.cpp @@ -10,6 +10,7 @@ * \author [Krishna Vedala](https://github.com/kvedala) */ #include +#include // for std::abs #include // for print formatting #include #include From 7ff384e59b5741b2b1d0ff981efa10ed891b5350 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 26 Jun 2020 08:20:53 -0400 Subject: [PATCH 156/271] replace cstdlib with cmath for float overload of std::abs() --- numerical_methods/ordinary_least_squares_regressor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/numerical_methods/ordinary_least_squares_regressor.cpp b/numerical_methods/ordinary_least_squares_regressor.cpp index 4761a6d96..7482d84da 100644 --- a/numerical_methods/ordinary_least_squares_regressor.cpp +++ b/numerical_methods/ordinary_least_squares_regressor.cpp @@ -10,7 +10,7 @@ * \author [Krishna Vedala](https://github.com/kvedala) */ #include -#include // for std::abs +#include // for std::abs #include // for print formatting #include #include From 9a8b6ddd2ee2854032245a348298a33fdaf8202d Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 26 Jun 2020 08:22:12 -0400 Subject: [PATCH 157/271] typo correction from #910 --- numerical_methods/ordinary_least_squares_regressor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/numerical_methods/ordinary_least_squares_regressor.cpp b/numerical_methods/ordinary_least_squares_regressor.cpp index 7482d84da..dcbbcf8c7 100644 --- a/numerical_methods/ordinary_least_squares_regressor.cpp +++ b/numerical_methods/ordinary_least_squares_regressor.cpp @@ -423,7 +423,7 @@ int main() { std::vector Y(N); std::cout - << "Enter training data. Per sample, provide features ad one output." + << "Enter training data. Per sample, provide features and one output." << std::endl; for (size_t rows = 0; rows < N; rows++) { From 0690a140ecfbe55583186169577aab3b2cd16103 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 26 Jun 2020 09:03:20 -0400 Subject: [PATCH 158/271] move OLS regressor to machine learning folder --- .../ordinary_least_squares_regressor.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {numerical_methods => machine_learning}/ordinary_least_squares_regressor.cpp (100%) diff --git a/numerical_methods/ordinary_least_squares_regressor.cpp b/machine_learning/ordinary_least_squares_regressor.cpp similarity index 100% rename from numerical_methods/ordinary_least_squares_regressor.cpp rename to machine_learning/ordinary_least_squares_regressor.cpp From dcd0d6b47864468cd9645e22e206e5b59bea4c6f Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 26 Jun 2020 13:04:18 +0000 Subject: [PATCH 159/271] updating DIRECTORY.md --- DIRECTORY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index 679e6f7d8..d678276bc 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -98,6 +98,7 @@ * [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) + * [Ordinary Least Squares Regressor](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/machine_learning/ordinary_least_squares_regressor.cpp) ## Math * [Armstrong Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/armstrong_number.cpp) @@ -145,7 +146,6 @@ * [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) * [Qr Eigen Values](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/numerical_methods/qr_eigen_values.cpp) From 052c3fbca87802cc8ab95f5deb08bd94badab4fa Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 26 Jun 2020 10:37:56 -0400 Subject: [PATCH 160/271] use better test function names to avoid conflict --- machine_learning/ordinary_least_squares_regressor.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/machine_learning/ordinary_least_squares_regressor.cpp b/machine_learning/ordinary_least_squares_regressor.cpp index dcbbcf8c7..54d100300 100644 --- a/machine_learning/ordinary_least_squares_regressor.cpp +++ b/machine_learning/ordinary_least_squares_regressor.cpp @@ -355,7 +355,7 @@ std::vector predict_OLS_regressor(std::vector> const &X, } /** Self test checks */ -void test() { +void ols_test() { int F = 3, N = 5; /* test function = x^2 -5 */ @@ -408,7 +408,7 @@ void test() { * main function */ int main() { - test(); + ols_test(); size_t N, F; From b9c1f6bf363aa6e34fcaa664adafef3158ce7841 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 26 Jun 2020 10:53:42 -0400 Subject: [PATCH 161/271] use better test data variable names to avoid conflict --- machine_learning/ordinary_least_squares_regressor.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/machine_learning/ordinary_least_squares_regressor.cpp b/machine_learning/ordinary_least_squares_regressor.cpp index 54d100300..896504e20 100644 --- a/machine_learning/ordinary_least_squares_regressor.cpp +++ b/machine_learning/ordinary_least_squares_regressor.cpp @@ -368,12 +368,12 @@ void ols_test() { // perform regression modelling std::vector beta1 = fit_OLS_regressor(data1, Y1); // create test data set with same features = x, x^2, x^3 - std::vector> test1( + std::vector> test_data1( {{-2, 4, -8}, {2, 4, 8}, {-10, 100, -1000}, {10, 100, 1000}}); // expected regression outputs std::vector expected1({-1, -1, 95, 95}); // predicted regression outputs - std::vector out1 = predict_OLS_regressor(test1, beta1); + std::vector out1 = predict_OLS_regressor(test_data1, beta1); // compare predicted results are within +-0.01 limit of expected for (size_t rows = 0; rows < out1.size(); rows++) assert(std::abs(out1[rows] - expected1[rows]) < 0.01); @@ -389,12 +389,12 @@ void ols_test() { // perform regression modelling std::vector beta2 = fit_OLS_regressor(data2, Y2); // create test data set with same features = x, x^2, x^3 - std::vector> test2( + std::vector> test_data2( {{-2, 4, -8}, {2, 4, 8}, {-10, 100, -1000}, {10, 100, 1000}}); // expected regression outputs std::vector expected2({-104, -88, -1000, 1000}); // predicted regression outputs - std::vector out2 = predict_OLS_regressor(test2, beta2); + std::vector out2 = predict_OLS_regressor(test_data2, beta2); // compare predicted results are within +-0.01 limit of expected for (size_t rows = 0; rows < out2.size(); rows++) assert(std::abs(out2[rows] - expected2[rows]) < 0.01); From 9379ae1a6c0731780c0b5260a553051ab5a46d82 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 26 Jun 2020 13:46:46 -0400 Subject: [PATCH 162/271] added LGTM status --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8734158b7..a6cde5f50 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # 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) +[![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) [![Language grade: C/C++](https://img.shields.io/lgtm/grade/cpp/g/TheAlgorithms/C-Plus-Plus.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/TheAlgorithms/C-Plus-Plus/context:cpp) [![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/TheAlgorithms/C-Plus-Plus?color=red&style=flat-square) From b3d85cd8e158bb6482735101762f6f73d6348e74 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 26 Jun 2020 14:23:25 -0400 Subject: [PATCH 163/271] add LGTM status + remove HTML tags and use Markdown syntax Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index a6cde5f50..53320a5b1 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,12 @@ # 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) [![Language grade: C/C++](https://img.shields.io/lgtm/grade/cpp/g/TheAlgorithms/C-Plus-Plus.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/TheAlgorithms/C-Plus-Plus/context:cpp) [![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) +[![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/CONTRIBUTING.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/TheAlgorithms/C-Plus-Plus/workflows/Doxygen%20CI/badge.svg) -![Awesome CI](https://github.com/TheAlgorithms/C-Plus-Plus/workflows/Awesome%20CI%20Workflow/badge.svg) +[![Doxygen CI](https://github.com/TheAlgorithms/C-Plus-Plus/workflows/Doxygen%20CI/badge.svg)]("https://TheAlgorithms.github.io/C-Plus-Plus") +[![Awesome CI](https://github.com/TheAlgorithms/C-Plus-Plus/workflows/Awesome%20CI%20Workflow/badge.svg)]("https://github.com/TheAlgorithms/C-Plus-Plus/actions?query=workflow%3A%22Awesome+CI+Workflow%22") [Online Documentation](https://TheAlgorithms.github.io/C-Plus-Plus). From c5933c8525452c300ef961881bf883646db359dc Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 26 Jun 2020 14:29:10 -0400 Subject: [PATCH 164/271] updated project summary description Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- README.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 53320a5b1..aa0f96e80 100644 --- a/README.md +++ b/README.md @@ -8,12 +8,15 @@ [![Doxygen CI](https://github.com/TheAlgorithms/C-Plus-Plus/workflows/Doxygen%20CI/badge.svg)]("https://TheAlgorithms.github.io/C-Plus-Plus") [![Awesome CI](https://github.com/TheAlgorithms/C-Plus-Plus/workflows/Awesome%20CI%20Workflow/badge.svg)]("https://github.com/TheAlgorithms/C-Plus-Plus/actions?query=workflow%3A%22Awesome+CI+Workflow%22") -[Online Documentation](https://TheAlgorithms.github.io/C-Plus-Plus). +## Algorithms implemented in C++ (for education) +The repository is a collection of implementation of a variety of algorithms implemented in C++. These algorithms span a variety of topics from computer science, mathematics and statistics, data science, machine learning, engineering, etc.. The implementations are meant to be a learning resource for educators and students. Hence, one may find more than one implementation for the same algorithm with different optimizations and different strategies used that would be documented therein. + +## Documentation + +[Online Documentation](https://TheAlgorithms.github.io/C-Plus-Plus) is generated from the repository source codes directly. The documentation contains all resources including source code snippets, details on execution of the programs, diagrammatic representation of program flow, and links to external resources where necessary. The documentation also introduces interactive source code with links to documentation for C++ STL library functions used. 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. +## Contributions -### Contribute Guidelines -Read our [Contribution Guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTING.md) before you contribute. +As a community developed and community maintained repository, we welcome new un-plagiarized contributions. Read our [Contribution Guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTING.md) before you contribute. From aa16f4d113c028be73c9871d554b95e233ede32d Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 26 Jun 2020 14:29:45 -0400 Subject: [PATCH 165/271] added features description Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- README.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/README.md b/README.md index aa0f96e80..bb8d32dcb 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,16 @@ The repository is a collection of implementation of a variety of algorithms implemented in C++. These algorithms span a variety of topics from computer science, mathematics and statistics, data science, machine learning, engineering, etc.. The implementations are meant to be a learning resource for educators and students. Hence, one may find more than one implementation for the same algorithm with different optimizations and different strategies used that would be documented therein. +## Features + +* The repository provides implementations of various algorithms in one of the most fundamental general purpose languages - [C++](https://en.wikipedia.org/wiki/C%2B%2B). +* Well documented source code with detailed explanations provide a valuable resource for educators and students alike. +* Each source code is atomic using [STL classes](https://en.wikipedia.org/wiki/Standard_Template_Library) and _no external libraries_ are required for their compilation and execution. Thus the fundamentals of the algorithms can be studied in much depth. +* Source codes are [compiled and tested](https://github.com/TheAlgorithms/C-Plus-Plus/actions?query=workflow%3A%22Awesome+CI+Workflow%22) for every commit on the latest versions of three major operating systems Windows, MacOS and Ubuntu (Linux) using MSVC 16 2019, AppleClang 11.0 and GNU 7.5.0 respectively. +* Strict adherence [C++11](https://en.wikipedia.org/wiki/C%2B%2B11) standard ensures portability of code to embedded systems as well like ESP32, ARM Cortex, etc with little to no changes. +* Self-checks within programs ensure correct implementations with confidence. +* Modular implementations and OpenSource licensing enable the functions to be utilized conveniently in other applications. + ## Documentation [Online Documentation](https://TheAlgorithms.github.io/C-Plus-Plus) is generated from the repository source codes directly. The documentation contains all resources including source code snippets, details on execution of the programs, diagrammatic representation of program flow, and links to external resources where necessary. The documentation also introduces interactive source code with links to documentation for C++ STL library functions used. From 54dcadf07d5e7810655172fb9ed9f3b94e714c2a Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 26 Jun 2020 14:38:03 -0400 Subject: [PATCH 166/271] fix contributions description Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bb8d32dcb..f711c58b8 100644 --- a/README.md +++ b/README.md @@ -29,4 +29,4 @@ Click on [Files menu](https://TheAlgorithms.github.io/C-Plus-Plus/files.html) to ## Contributions -As a community developed and community maintained repository, we welcome new un-plagiarized contributions. Read our [Contribution Guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTING.md) before you contribute. +As a community developed and community maintained repository, we welcome new un-plagiarized quality contributions. Please read our [Contribution Guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTING.md). From a9c005da70569a168ffaf17ddd3ee286a6bd31dd Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 26 Jun 2020 14:49:05 -0400 Subject: [PATCH 167/271] overview + comment why mainpage Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f711c58b8..0dfb173bf 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ # 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) [![Language grade: C/C++](https://img.shields.io/lgtm/grade/cpp/g/TheAlgorithms/C-Plus-Plus.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/TheAlgorithms/C-Plus-Plus/context:cpp) [![Gitter chat](https://img.shields.io/badge/Chat-Gitter-ff69b4.svg?label=Chat&logo=gitter&style=flat-square)](https://gitter.im/TheAlgorithms) @@ -8,7 +9,7 @@ [![Doxygen CI](https://github.com/TheAlgorithms/C-Plus-Plus/workflows/Doxygen%20CI/badge.svg)]("https://TheAlgorithms.github.io/C-Plus-Plus") [![Awesome CI](https://github.com/TheAlgorithms/C-Plus-Plus/workflows/Awesome%20CI%20Workflow/badge.svg)]("https://github.com/TheAlgorithms/C-Plus-Plus/actions?query=workflow%3A%22Awesome+CI+Workflow%22") -## Algorithms implemented in C++ (for education) +## Overview The repository is a collection of implementation of a variety of algorithms implemented in C++. These algorithms span a variety of topics from computer science, mathematics and statistics, data science, machine learning, engineering, etc.. The implementations are meant to be a learning resource for educators and students. Hence, one may find more than one implementation for the same algorithm with different optimizations and different strategies used that would be documented therein. @@ -18,7 +19,7 @@ The repository is a collection of implementation of a variety of algorithms impl * Well documented source code with detailed explanations provide a valuable resource for educators and students alike. * Each source code is atomic using [STL classes](https://en.wikipedia.org/wiki/Standard_Template_Library) and _no external libraries_ are required for their compilation and execution. Thus the fundamentals of the algorithms can be studied in much depth. * Source codes are [compiled and tested](https://github.com/TheAlgorithms/C-Plus-Plus/actions?query=workflow%3A%22Awesome+CI+Workflow%22) for every commit on the latest versions of three major operating systems Windows, MacOS and Ubuntu (Linux) using MSVC 16 2019, AppleClang 11.0 and GNU 7.5.0 respectively. -* Strict adherence [C++11](https://en.wikipedia.org/wiki/C%2B%2B11) standard ensures portability of code to embedded systems as well like ESP32, ARM Cortex, etc with little to no changes. +* Strict adherence to [C++11](https://en.wikipedia.org/wiki/C%2B%2B11) standard ensures portability of code to embedded systems as well like ESP32, ARM Cortex, etc with little to no changes. * Self-checks within programs ensure correct implementations with confidence. * Modular implementations and OpenSource licensing enable the functions to be utilized conveniently in other applications. From 8f72445a6dcce05be377bcaf31495385c0f1baf4 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 26 Jun 2020 20:14:36 -0400 Subject: [PATCH 168/271] minor punctuations --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0dfb173bf..e5755c3a5 100644 --- a/README.md +++ b/README.md @@ -18,8 +18,8 @@ The repository is a collection of implementation of a variety of algorithms impl * The repository provides implementations of various algorithms in one of the most fundamental general purpose languages - [C++](https://en.wikipedia.org/wiki/C%2B%2B). * Well documented source code with detailed explanations provide a valuable resource for educators and students alike. * Each source code is atomic using [STL classes](https://en.wikipedia.org/wiki/Standard_Template_Library) and _no external libraries_ are required for their compilation and execution. Thus the fundamentals of the algorithms can be studied in much depth. -* Source codes are [compiled and tested](https://github.com/TheAlgorithms/C-Plus-Plus/actions?query=workflow%3A%22Awesome+CI+Workflow%22) for every commit on the latest versions of three major operating systems Windows, MacOS and Ubuntu (Linux) using MSVC 16 2019, AppleClang 11.0 and GNU 7.5.0 respectively. -* Strict adherence to [C++11](https://en.wikipedia.org/wiki/C%2B%2B11) standard ensures portability of code to embedded systems as well like ESP32, ARM Cortex, etc with little to no changes. +* Source codes are [compiled and tested](https://github.com/TheAlgorithms/C-Plus-Plus/actions?query=workflow%3A%22Awesome+CI+Workflow%22) for every commit on the latest versions of three major operating systems viz., Windows, MacOS and Ubuntu (Linux) using MSVC 16 2019, AppleClang 11.0 and GNU 7.5.0 respectively. +* Strict adherence to [C++11](https://en.wikipedia.org/wiki/C%2B%2B11) standard ensures portability of code to embedded systems as well like ESP32, ARM Cortex, etc. with little to no changes. * Self-checks within programs ensure correct implementations with confidence. * Modular implementations and OpenSource licensing enable the functions to be utilized conveniently in other applications. From 0f42f8f96ca404a90ef9b9a24293782c00f8505e Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 26 Jun 2020 20:20:43 -0400 Subject: [PATCH 169/271] apply suggestions by reviewers --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e5755c3a5..e99ec1311 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ ## Overview -The repository is a collection of implementation of a variety of algorithms implemented in C++. These algorithms span a variety of topics from computer science, mathematics and statistics, data science, machine learning, engineering, etc.. The implementations are meant to be a learning resource for educators and students. Hence, one may find more than one implementation for the same algorithm with different optimizations and different strategies used that would be documented therein. +The repository is a collection of implementation of a variety of algorithms implemented in C++. These algorithms span a variety of topics from computer science, mathematics and statistics, data science, machine learning, engineering, etc.. The implementations and the associated documentation are meant to provide a learning resource for educators and students. Hence, one may find more than one implementation for the same objective but using a different algorithm strategies and optimizations. ## Features @@ -30,4 +30,4 @@ Click on [Files menu](https://TheAlgorithms.github.io/C-Plus-Plus/files.html) to ## Contributions -As a community developed and community maintained repository, we welcome new un-plagiarized quality contributions. Please read our [Contribution Guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTING.md). +As a community developed and maintained repository, we welcome new un-plagiarized quality contributions. Please read our [Contribution Guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTING.md). From 7218eeb5b8440499d4ce477255486fd788ecc91d Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 26 Jun 2020 20:36:03 -0400 Subject: [PATCH 170/271] initial cipher folder commit --- ciphers/CMakeLists.txt | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 ciphers/CMakeLists.txt diff --git a/ciphers/CMakeLists.txt b/ciphers/CMakeLists.txt new file mode 100644 index 000000000..1efde3087 --- /dev/null +++ b/ciphers/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/ciphers") + +endforeach( testsourcefile ${APP_SOURCES} ) From db28999ca3f01f0bf779875ccf7295d354ff8ade Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 26 Jun 2020 20:36:46 -0400 Subject: [PATCH 171/271] initial hill-cipher commit - does not execute corectly --- ciphers/hill_cipher.cpp | 411 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 411 insertions(+) create mode 100644 ciphers/hill_cipher.cpp diff --git a/ciphers/hill_cipher.cpp b/ciphers/hill_cipher.cpp new file mode 100644 index 000000000..10fed923d --- /dev/null +++ b/ciphers/hill_cipher.cpp @@ -0,0 +1,411 @@ +/** + * @file hill_cipher.cpp + * @author [Krishna Vedala](https://github.com/kvedala) + * @brief Implementation of [Hill + * cipher](https://en.wikipedia.org/wiki/Hill_cipher) algorithm. + * + * Program to generate the encryption-decryption key and perform encryption and + * decryption of ASCII text. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _OPENMP +#include +#endif + +#include "../numerical_methods/lu_decomposition.h" + +/** + * operator to print a matrix + */ +template +static std::ostream &operator<<(std::ostream &out, matrix const &v) { + const int width = 15; + 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; +} + +/** \namespace ciphers + * \brief Algorithms for encryption and decryption + */ +namespace ciphers { +/** dictionary of characters that can be encrypted and decrypted */ +static const std::string STRKEY = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~!@#$%^&" + "*()_+`-=[]{}|;':\",./<>?\\\r\n "; + +/** + * @brief Implementation of [Hill + * Cipher](https://en.wikipedia.org/wiki/Hill_cipher) algorithm + */ +class HillCipher { + private: + /** + * @brief Function to generate a random integer in a given interval + * + * @param a lower limit of interval + * @param b upper limit of interval + * @tparam T type of output + * @return random integer in the interval \f$[a,b)\f$ + */ + template + static const T2 rand_range(T1 a, T1 b) { + // generate random number between 0 and 1 + long double r = static_cast(std::rand()) / RAND_MAX; + + // scale and return random number as integer + return static_cast(r * (b - a) + a); + } + + /** + * @brief Function overload to fill a matrix with random integers in a given + * interval + * + * @param M pointer to matrix to be filled with random numbers + * @param a lower limit of interval + * @param b upper limit of interval + * @tparam T1 type of input range + * @tparam T2 type of matrix + * @return determinant of generated random matrix + */ + template + static const double rand_range(matrix *M, T1 a, T1 b) { + for (size_t i = 0; i < M->size(); i++) { + for (size_t j = 0; j < M[0][0].size(); j++) { + M[0][i][j] = rand_range(a, b); + } + } + + return determinant_lu(*M); + } + + /** + * @brief Compute + * [GCD](https://en.wikipedia.org/wiki/Greatest_common_divisor) of two + * integers using Euler's algorithm + * + * @param a first number + * @param b second number + * @return GCD of \f$a\f$ and \f$b\f$ + */ + template + static const T gcd(T a, T b) { + if (b > a) // ensure always a < b + std::swap(a, b); + + while (b != 0) { + T tmp = b; + b = a % b; + a = tmp; + } + + return a; + } + + /** + * @brief helper function to perform vector multiplication with encryption + * or decryption matrix + * + * @param vector vector to multiply + * @param key encryption or decryption key matrix + * @return corresponding encrypted or decrypted text + */ + static const std::valarray mat_mul( + const std::valarray &vector, const matrix &key) { + std::valarray out(vector); // make a copy + + for (size_t i = 0; i < key.size(); i++) { + int tmp = 0; + for (size_t j = 0; j < vector.size(); j++) { + tmp += key[i][j] * vector[j]; + } + out[i] = static_cast(tmp % STRKEY.length()); + } + + return out; + } + + /** + * @brief Convenience function to perform block cipher operations. The + * operations are identical for both encryption and decryption. + * + * @param text input text to encrypt or decrypt + * @param key key for encryption or decryption + * @return encrypted/decrypted output + */ + static const std::string codec(const std::string &text, + const matrix &key) { + size_t text_len = text.length(); + size_t key_len = key.size(); + + // length of output string must be a multiple of key_len + // create output string and initialize with '\0' character + size_t L2 = text_len % key_len == 0 + ? text_len + : text_len + key_len - (text_len % key_len); + std::string coded_text(L2, '\0'); + + // temporary array for batch processing + std::valarray batch_int(key_len); + for (size_t i = 0; i < L2 - key_len + 1; i += key_len) { + for (size_t j = 0; j < key_len; j++) { + batch_int[j] = static_cast( + STRKEY.find(text[i + j])); // get index of character in key + } + + batch_int = mat_mul(batch_int, key); + + for (size_t j = 0; j < key_len; j++) { + coded_text[i + j] = + STRKEY[batch_int[j]]; // get character at key + } + } + + return coded_text; + } + + /** + * Get matrix inverse using Row-transformations. Given matrix must + * be a square and non-singular. + * \returns inverse matrix + **/ + template + static matrix get_inverse(matrix const &A) { + // Assuming A is square matrix + size_t N = A.size(); + + matrix inverse(N, std::valarray(N)); + for (size_t row = 0; row < N; row++) { + for (size_t col = 0; col < N; col++) { + // create identity matrix + inverse[row][col] = (row == col) ? 1.f : 0.f; + } + } + + if (A.size() != A[0].size()) { + std::cerr << "A must be a square matrix!" << std::endl; + return inverse; + } + + // preallocate a temporary matrix identical to A + matrix temp(N, std::valarray(N)); + for (size_t row = 0; row < N; row++) { + for (size_t col = 0; col < N; col++) + temp[row][col] = static_cast(A[row][col]); + } + + // 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 + double divisor = 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; + double factor = temp[row2][row]; + temp[row2] = temp[row2] - factor * temp[row]; + inverse[row2] = inverse[row2] - factor * inverse[row]; + } + } + + return inverse; + } + + static int modulo(int a, int b) { + int ret = a % b; + if (ret < 0) + ret += b; + return ret; + } + + public: + /** + * @brief Generate encryption matrix of a given size. Larger size matrices + * are difficult to generate but provide more security. + * + * @param size size of matrix (typically \f$\text{size}\le10\f$) + * @return Encryption martix + */ + static matrix generate_encryption_key(size_t size) { + matrix encrypt_key(size, std::valarray(size)); + int mat_determinant = -1; // because matrix has only ints, the + // determinant will also be an int + + int L = static_cast(STRKEY.length()); + + double dd; + do { + dd = rand_range(&encrypt_key, 0, L); + mat_determinant = static_cast(dd); + + if (mat_determinant < 0) + mat_determinant = (mat_determinant % L) + L; + } while (dd <= 0.1 || // while singular or ill-defined + !std::isfinite(dd) || // while determinant is not finite + gcd(mat_determinant, L) != 1); // while no common factors + // std::cout << + + return encrypt_key; + } + + /** + * @brief Generate decryption matrix from an encryption matrix key. + * + * @param encrypt_key encryption key for which to create a decrypt key + * @return Decryption martix + */ + static matrix generate_decryption_key(matrix const &encrypt_key) { + size_t size = encrypt_key.size(); + int L = static_cast(STRKEY.length()); + + matrix decrypt_key(size, std::valarray(size)); + int det_encrypt = static_cast(determinant_lu(encrypt_key)); + + int mat_determinant = det_encrypt < 0 ? det_encrypt % L : det_encrypt; + + matrix tmp_inverse = get_inverse(encrypt_key); + double d2 = determinant_lu(decrypt_key); + + // find co-prime factor for inversion + int det_inv = -1; + for (int i = 0; i < L; i++) { + if (modulo(mat_determinant * i, L) == 1) { + det_inv = i; + break; + } + } + + if (det_inv == -1) { + std::cerr << "Could not find a co-prime for inversion\n"; + std::exit(EXIT_FAILURE); + } + + mat_determinant = det_inv * det_encrypt; + + // perform modular inverse of encryption matrix + int i; +#ifdef _OPENMP +#pragma parallel omp for private(i) +#endif + for (i = 0; i < size; i++) { + for (int j = 0; j < size; j++) { + int temp = std::round(tmp_inverse[i][j] * mat_determinant); + decrypt_key[i][j] = modulo(temp, L); + } + } + return decrypt_key; + } + + /** + * @brief Generate encryption and decryption key pair + * + * @param size size of matrix key (typically \f$\text{size}\le10\f$) + * @return std::pair, matrix> encryption and decryption + * keys as a pair + */ + static std::pair, matrix> generate_keys(size_t size) { + matrix encrypt_key = generate_encryption_key(size); + matrix decrypt_key = generate_decryption_key(encrypt_key); + double det2 = determinant_lu(decrypt_key); + while (det2 < 0.1) { + encrypt_key = generate_encryption_key(size); + decrypt_key = generate_decryption_key(encrypt_key); + det2 = determinant_lu(decrypt_key); + } + return std::make_pair(encrypt_key, decrypt_key); + } + + /** + * @brief Encrypt a given text using a given key + * + * @param text string to encrypt + * @param encrypt_key key for encryption + * @return encrypted text + */ + static const std::string encrypt_text(const std::string &text, + const matrix &encrypt_key) { + return codec(text, encrypt_key); + } + + /** + * @brief Decrypt a given text using a given key + * + * @param text string to decrypt + * @param decrypt_key key for decryption + * @return decrypted text + */ + static const std::string decrypt_text(const std::string &text, + const matrix &decrypt_key) { + return codec(text, decrypt_key); + } +}; + +} // namespace ciphers + +/** Main function */ +int main() { + std::srand(std::time(nullptr)); + + std::cout << "Key dictionary: (" << ciphers::STRKEY.length() << ")\n\t" + << ciphers::STRKEY << "\n"; + + std::string text = "This is a simple text with numb3r5 and exclamat!0n."; + // std::string text = "Hello world!"; + std::cout << "Original text:\n\t" << text << std::endl; + + std::pair, matrix> p = + ciphers::HillCipher::generate_keys(5); + matrix ekey = p.first; + matrix dkey = p.second; + // matrix ekey = {{22, 28, 25}, {5, 26, 15}, {14, 18, 9}}; + // std::cout << "Encryption key: \n" << ekey; + std::string gibberish = ciphers::HillCipher::encrypt_text(text, ekey); + std::cout << "Encrypted text:\n\t" << gibberish << std::endl; + + // matrix dkey = ciphers::HillCipher::generate_decryption_key(ekey); + // std::cout << "Decryption key: \n" << dkey; + std::string txt_back = ciphers::HillCipher::decrypt_text(gibberish, dkey); + std::cout << "Reconstruct text:\n\t" << txt_back << std::endl; + + assert(txt_back == text); + + return 0; +} From 0b57b895439bb6c7539851f5ef42c2b2195bedf8 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 27 Jun 2020 00:37:39 +0000 Subject: [PATCH 172/271] updating DIRECTORY.md --- DIRECTORY.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 679e6f7d8..a3c66cd96 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -10,6 +10,9 @@ * [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) +## Ciphers + * [Hill Cipher](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/ciphers/hill_cipher.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) From bade62d0633965f4816b2022717eaf597a6981b6 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 26 Jun 2020 21:44:02 -0400 Subject: [PATCH 173/271] working hill cipher --- ciphers/hill_cipher.cpp | 80 ++++++++++++++++++++++++++++++++--------- 1 file changed, 63 insertions(+), 17 deletions(-) diff --git a/ciphers/hill_cipher.cpp b/ciphers/hill_cipher.cpp index 10fed923d..59ce73705 100644 --- a/ciphers/hill_cipher.cpp +++ b/ciphers/hill_cipher.cpp @@ -5,15 +5,31 @@ * cipher](https://en.wikipedia.org/wiki/Hill_cipher) algorithm. * * Program to generate the encryption-decryption key and perform encryption and - * decryption of ASCII text. + * decryption of ASCII text using the famous block cipher algorithm. This is a + * powerful encryption algorithm that is relatively easy to implement with a + * given key. The strength of the algorithm depends on the size of the block + * encryption matrix key; the bigger the matrix, the stronger the encryption and + * more difficult to break it. However, the important requirement for the matrix + * is that: + * 1. matrix should be invertible - all inversion conditions should be satisfied + * and + * 2. its determinant must not have any common factors with the length of + * character set + * Due to this restriction, most implementations only implement with small 3x3 + * encryption keys and a small subset of ASCII alphabets. + * + * In the current implementation, I present to you an implementation for + * generating larger encryption keys (I have attempted upto 10x10) and an ASCII + * character set of 97 printable characters. Hence, a typical ASCII text file + * could be easily encrypted with the module. */ #include #include +#include #include #include #include -#include #include #include #ifdef _OPENMP @@ -45,7 +61,7 @@ static std::ostream &operator<<(std::ostream &out, matrix const &v) { */ namespace ciphers { /** dictionary of characters that can be encrypted and decrypted */ -static const std::string STRKEY = +static const char *STRKEY = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~!@#$%^&" "*()_+`-=[]{}|;':\",./<>?\\\r\n "; @@ -129,17 +145,41 @@ class HillCipher { const std::valarray &vector, const matrix &key) { std::valarray out(vector); // make a copy + size_t L = std::strlen(STRKEY); + for (size_t i = 0; i < key.size(); i++) { int tmp = 0; for (size_t j = 0; j < vector.size(); j++) { tmp += key[i][j] * vector[j]; } - out[i] = static_cast(tmp % STRKEY.length()); + out[i] = static_cast(tmp % L); } return out; } + /** + * @brief Get the character at a given index in the ::STRKEY + * + * @param idx index value + * @return character at the index + */ + static inline char get_idx_char(const uint8_t idx) { return STRKEY[idx]; } + + /** + * @brief Get the index of a character in the ::STRKEY + * + * @param ch character to search + * @return index of character + */ + static inline uint8_t get_char_idx(const char ch) { + size_t L = std::strlen(STRKEY); + + for (uint8_t idx = 0; idx < L; idx++) + if (STRKEY[idx] == ch) + return idx; + } + /** * @brief Convenience function to perform block cipher operations. The * operations are identical for both encryption and decryption. @@ -164,8 +204,7 @@ class HillCipher { std::valarray batch_int(key_len); for (size_t i = 0; i < L2 - key_len + 1; i += key_len) { for (size_t j = 0; j < key_len; j++) { - batch_int[j] = static_cast( - STRKEY.find(text[i + j])); // get index of character in key + batch_int[j] = get_char_idx(text[i + j]); } batch_int = mat_mul(batch_int, key); @@ -259,26 +298,33 @@ class HillCipher { public: /** * @brief Generate encryption matrix of a given size. Larger size matrices - * are difficult to generate but provide more security. + * are difficult to generate but provide more security. Important conditions + * are: + * 1. matrix should be invertible + * 2. determinant must not have any common factors with the length of + * character key * * @param size size of matrix (typically \f$\text{size}\le10\f$) * @return Encryption martix */ static matrix generate_encryption_key(size_t size) { matrix encrypt_key(size, std::valarray(size)); + matrix min_mat = encrypt_key; int mat_determinant = -1; // because matrix has only ints, the // determinant will also be an int - - int L = static_cast(STRKEY.length()); + int L = std::strlen(STRKEY); double dd; do { - dd = rand_range(&encrypt_key, 0, L); + // keeping the random number range smaller generates better + // defined matrices with more ease of cracking + dd = rand_range(&encrypt_key, 0, 10); mat_determinant = static_cast(dd); if (mat_determinant < 0) - mat_determinant = (mat_determinant % L) + L; - } while (dd <= 0.1 || // while singular or ill-defined + mat_determinant = (mat_determinant % L); + } while (std::abs(dd) > 1e3 || // while ill-defined + dd < 0.1 || // while singular !std::isfinite(dd) || // while determinant is not finite gcd(mat_determinant, L) != 1); // while no common factors // std::cout << @@ -294,7 +340,7 @@ class HillCipher { */ static matrix generate_decryption_key(matrix const &encrypt_key) { size_t size = encrypt_key.size(); - int L = static_cast(STRKEY.length()); + int L = std::strlen(STRKEY); matrix decrypt_key(size, std::valarray(size)); int det_encrypt = static_cast(determinant_lu(encrypt_key)); @@ -384,7 +430,7 @@ class HillCipher { int main() { std::srand(std::time(nullptr)); - std::cout << "Key dictionary: (" << ciphers::STRKEY.length() << ")\n\t" + std::cout << "Key dictionary: (" << std::strlen(ciphers::STRKEY) << ")\n\t" << ciphers::STRKEY << "\n"; std::string text = "This is a simple text with numb3r5 and exclamat!0n."; @@ -392,16 +438,16 @@ int main() { std::cout << "Original text:\n\t" << text << std::endl; std::pair, matrix> p = - ciphers::HillCipher::generate_keys(5); + ciphers::HillCipher::generate_keys(8); matrix ekey = p.first; matrix dkey = p.second; // matrix ekey = {{22, 28, 25}, {5, 26, 15}, {14, 18, 9}}; - // std::cout << "Encryption key: \n" << ekey; + std::cout << "Encryption key: \n" << ekey; std::string gibberish = ciphers::HillCipher::encrypt_text(text, ekey); std::cout << "Encrypted text:\n\t" << gibberish << std::endl; // matrix dkey = ciphers::HillCipher::generate_decryption_key(ekey); - // std::cout << "Decryption key: \n" << dkey; + std::cout << "Decryption key: \n" << dkey; std::string txt_back = ciphers::HillCipher::decrypt_text(gibberish, dkey); std::cout << "Reconstruct text:\n\t" << txt_back << std::endl; From f932aed5d2aebc4fe1febcdb8a3583a505ac72b4 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 26 Jun 2020 22:02:21 -0400 Subject: [PATCH 174/271] more docs + more control on matrix creation --- ciphers/hill_cipher.cpp | 38 +++++++++++++++++++++++++++++--------- 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/ciphers/hill_cipher.cpp b/ciphers/hill_cipher.cpp index 59ce73705..f1382f57e 100644 --- a/ciphers/hill_cipher.cpp +++ b/ciphers/hill_cipher.cpp @@ -30,6 +30,7 @@ #include #include #include +#include #include #include #ifdef _OPENMP @@ -98,6 +99,12 @@ class HillCipher { * @tparam T1 type of input range * @tparam T2 type of matrix * @return determinant of generated random matrix + * + * @warning There will need to be a balance between the matrix size and the + * range of random numbers. If the matrix is large, the range of random + * numbers must be small to have a well defined keys. Or if the matrix is + * smaller, the random numbers range can be larger. For an 8x8 matrix, range + * should be no more than \f$[0,10]\f$ */ template static const double rand_range(matrix *M, T1 a, T1 b) { @@ -303,11 +310,18 @@ class HillCipher { * 1. matrix should be invertible * 2. determinant must not have any common factors with the length of * character key + * There is no head-fast way to generate hte matrix under the given + * numerical restrictions of the machine but the conditions added achieve + * the goals. Bigger the matrix, greater is the probability of the matrix + * being ill-defined. * * @param size size of matrix (typically \f$\text{size}\le10\f$) + * @param limit1 lower limit of range of random elements (default=0) + * @param limit2 upper limit of range of random elements (default=10) * @return Encryption martix */ - static matrix generate_encryption_key(size_t size) { + static matrix generate_encryption_key(size_t size, int limit1 = 0, + int limit2 = 10) { matrix encrypt_key(size, std::valarray(size)); matrix min_mat = encrypt_key; int mat_determinant = -1; // because matrix has only ints, the @@ -318,7 +332,7 @@ class HillCipher { do { // keeping the random number range smaller generates better // defined matrices with more ease of cracking - dd = rand_range(&encrypt_key, 0, 10); + dd = rand_range(&encrypt_key, limit1, limit2); mat_determinant = static_cast(dd); if (mat_determinant < 0) @@ -384,15 +398,21 @@ class HillCipher { * @brief Generate encryption and decryption key pair * * @param size size of matrix key (typically \f$\text{size}\le10\f$) + * @param limit1 lower limit of range of random elements (default=0) + * @param limit2 upper limit of range of random elements (default=10) * @return std::pair, matrix> encryption and decryption * keys as a pair + * + * @see ::generate_encryption_key */ - static std::pair, matrix> generate_keys(size_t size) { + static std::pair, matrix> generate_keys(size_t size, + int limit1 = 0, + int limit2 = 10) { matrix encrypt_key = generate_encryption_key(size); matrix decrypt_key = generate_decryption_key(encrypt_key); double det2 = determinant_lu(decrypt_key); - while (det2 < 0.1) { - encrypt_key = generate_encryption_key(size); + while (std::abs(det2) < 0.1 || std::abs(det2) > 1e3) { + encrypt_key = generate_encryption_key(size, limit1, limit2); decrypt_key = generate_decryption_key(encrypt_key); det2 = determinant_lu(decrypt_key); } @@ -438,20 +458,20 @@ int main() { std::cout << "Original text:\n\t" << text << std::endl; std::pair, matrix> p = - ciphers::HillCipher::generate_keys(8); + ciphers::HillCipher::generate_keys(10, 0, 5); matrix ekey = p.first; matrix dkey = p.second; // matrix ekey = {{22, 28, 25}, {5, 26, 15}, {14, 18, 9}}; - std::cout << "Encryption key: \n" << ekey; + // std::cout << "Encryption key: \n" << ekey; std::string gibberish = ciphers::HillCipher::encrypt_text(text, ekey); std::cout << "Encrypted text:\n\t" << gibberish << std::endl; // matrix dkey = ciphers::HillCipher::generate_decryption_key(ekey); - std::cout << "Decryption key: \n" << dkey; + // std::cout << "Decryption key: \n" << dkey; std::string txt_back = ciphers::HillCipher::decrypt_text(gibberish, dkey); std::cout << "Reconstruct text:\n\t" << txt_back << std::endl; - assert(txt_back == text); + assert((txt_back == text) == true); return 0; } From fc489f7f4514eee705c76e84d908f7b83669840c Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 26 Jun 2020 23:42:16 -0400 Subject: [PATCH 175/271] test2 + refinements --- ciphers/hill_cipher.cpp | 88 +++++++++++++++++++++++++++++++---------- 1 file changed, 68 insertions(+), 20 deletions(-) diff --git a/ciphers/hill_cipher.cpp b/ciphers/hill_cipher.cpp index f1382f57e..cdcd795d4 100644 --- a/ciphers/hill_cipher.cpp +++ b/ciphers/hill_cipher.cpp @@ -1,6 +1,5 @@ /** * @file hill_cipher.cpp - * @author [Krishna Vedala](https://github.com/kvedala) * @brief Implementation of [Hill * cipher](https://en.wikipedia.org/wiki/Hill_cipher) algorithm. * @@ -21,7 +20,14 @@ * In the current implementation, I present to you an implementation for * generating larger encryption keys (I have attempted upto 10x10) and an ASCII * character set of 97 printable characters. Hence, a typical ASCII text file - * could be easily encrypted with the module. + * could be easily encrypted with the module. The larger character set increases + * the modulo of cipher and hence the matrix determinants can get very large + * very quickly rendering them ill-defined. + * + * \note This program uses determinant computation using LU decomposition from + * the file lu_decomposition.h + * + * @author [Krishna Vedala](https://github.com/kvedala) */ #include @@ -31,8 +37,6 @@ #include #include #include -#include -#include #ifdef _OPENMP #include #endif @@ -64,7 +68,7 @@ namespace ciphers { /** dictionary of characters that can be encrypted and decrypted */ static const char *STRKEY = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~!@#$%^&" - "*()_+`-=[]{}|;':\",./<>?\\\r\n "; + "*()_+`-=[]{}|;':\",./<>?\\\r\n \0"; /** * @brief Implementation of [Hill @@ -182,9 +186,13 @@ class HillCipher { static inline uint8_t get_char_idx(const char ch) { size_t L = std::strlen(STRKEY); - for (uint8_t idx = 0; idx < L; idx++) + for (uint8_t idx = 0; idx <= L; idx++) if (STRKEY[idx] == ch) return idx; + + std::cerr << __func__ << ":" << __LINE__ << ": (" << ch + << ") Should not reach here!\n"; + return 0; } /** @@ -208,8 +216,12 @@ class HillCipher { std::string coded_text(L2, '\0'); // temporary array for batch processing - std::valarray batch_int(key_len); - for (size_t i = 0; i < L2 - key_len + 1; i += key_len) { + int i; +#ifdef _OPENMP +#pragma parallel omp for private(i) +#endif + for (i = 0; i < L2 - key_len + 1; i += key_len) { + std::valarray batch_int(key_len); for (size_t j = 0; j < key_len; j++) { batch_int[j] = get_char_idx(text[i + j]); } @@ -338,7 +350,7 @@ class HillCipher { if (mat_determinant < 0) mat_determinant = (mat_determinant % L); } while (std::abs(dd) > 1e3 || // while ill-defined - dd < 0.1 || // while singular + std::abs(dd) < 0.1 || // while singular !std::isfinite(dd) || // while determinant is not finite gcd(mat_determinant, L) != 1); // while no common factors // std::cout << @@ -446,21 +458,21 @@ class HillCipher { } // namespace ciphers -/** Main function */ -int main() { - std::srand(std::time(nullptr)); - - std::cout << "Key dictionary: (" << std::strlen(ciphers::STRKEY) << ")\n\t" - << ciphers::STRKEY << "\n"; - - std::string text = "This is a simple text with numb3r5 and exclamat!0n."; +/** + * @brief Self test 1 - using 3x3 randomly generated key + * + * @param text string to encrypt and decrypt + */ +void test1(const std::string &text) { // std::string text = "Hello world!"; - std::cout << "Original text:\n\t" << text << std::endl; + std::cout << "======Test 1 (3x3 key) ======\nOriginal text:\n\t" << text + << std::endl; std::pair, matrix> p = - ciphers::HillCipher::generate_keys(10, 0, 5); + ciphers::HillCipher::generate_keys(3, 0, 100); matrix ekey = p.first; matrix dkey = p.second; + // matrix ekey = {{22, 28, 25}, {5, 26, 15}, {14, 18, 9}}; // std::cout << "Encryption key: \n" << ekey; std::string gibberish = ciphers::HillCipher::encrypt_text(text, ekey); @@ -471,7 +483,43 @@ int main() { std::string txt_back = ciphers::HillCipher::decrypt_text(gibberish, dkey); std::cout << "Reconstruct text:\n\t" << txt_back << std::endl; - assert((txt_back == text) == true); + assert(txt_back == text); +} + +/** + * @brief Self test 2 - using 8x8 randomly generated key + * + * @param text string to encrypt and decrypt + */ +void test2(const std::string &text) { + // std::string text = "Hello world!"; + std::cout << "======Test 2 (8x8 key) ======\nOriginal text:\n\t" << text + << std::endl; + + std::pair, matrix> p = + ciphers::HillCipher::generate_keys(8, 0, 10); + matrix ekey = p.first; + matrix dkey = p.second; + + std::string gibberish = ciphers::HillCipher::encrypt_text(text, ekey); + std::cout << "Encrypted text:\n\t" << gibberish << std::endl; + + std::string txt_back = ciphers::HillCipher::decrypt_text(gibberish, dkey); + std::cout << "Reconstruct text:\n\t" << txt_back << std::endl; + + assert(text.compare(0, text.length() - 1, txt_back) == 0); +} + +/** Main function */ +int main() { + std::srand(std::time(nullptr)); + std::cout << "Key dictionary: (" << std::strlen(ciphers::STRKEY) << ")\n\t" + << ciphers::STRKEY << "\n"; + + std::string text = "This is a simple text with numb3r5 and exclamat!0n."; + + test1(text); + test2(text); return 0; } From 541f762deb37990d8c38bd50e76b95f12464adb8 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 27 Jun 2020 14:43:11 -0400 Subject: [PATCH 176/271] working algorithm --- ciphers/hill_cipher.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/ciphers/hill_cipher.cpp b/ciphers/hill_cipher.cpp index cdcd795d4..4c8c87d26 100644 --- a/ciphers/hill_cipher.cpp +++ b/ciphers/hill_cipher.cpp @@ -484,6 +484,7 @@ void test1(const std::string &text) { std::cout << "Reconstruct text:\n\t" << txt_back << std::endl; assert(txt_back == text); + std::cout << "Passed :)\n"; } /** @@ -497,7 +498,7 @@ void test2(const std::string &text) { << std::endl; std::pair, matrix> p = - ciphers::HillCipher::generate_keys(8, 0, 10); + ciphers::HillCipher::generate_keys(8, 0, 5); matrix ekey = p.first; matrix dkey = p.second; @@ -507,7 +508,8 @@ void test2(const std::string &text) { std::string txt_back = ciphers::HillCipher::decrypt_text(gibberish, dkey); std::cout << "Reconstruct text:\n\t" << txt_back << std::endl; - assert(text.compare(0, text.length() - 1, txt_back) == 0); + assert(txt_back.compare(0, text.size(), text) == 0); + std::cout << "Passed :)\n"; } /** Main function */ From e8849dc36f149906220d7108c4fded29c2ce5f58 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 27 Jun 2020 15:45:48 -0400 Subject: [PATCH 177/271] save keys to file + more docs --- ciphers/hill_cipher.cpp | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/ciphers/hill_cipher.cpp b/ciphers/hill_cipher.cpp index 4c8c87d26..45315e088 100644 --- a/ciphers/hill_cipher.cpp +++ b/ciphers/hill_cipher.cpp @@ -26,6 +26,9 @@ * * \note This program uses determinant computation using LU decomposition from * the file lu_decomposition.h + * \note The matrix generation algorithm is very rudimentary and does not + * guarantee an invertible modulus matrix. \todo Better matrix generation + * algorithm. * * @author [Krishna Vedala](https://github.com/kvedala) */ @@ -34,6 +37,7 @@ #include #include #include +#include #include #include #include @@ -350,7 +354,7 @@ class HillCipher { if (mat_determinant < 0) mat_determinant = (mat_determinant % L); } while (std::abs(dd) > 1e3 || // while ill-defined - std::abs(dd) < 0.1 || // while singular + dd < 0.1 || // while singular or negative determinant !std::isfinite(dd) || // while determinant is not finite gcd(mat_determinant, L) != 1); // while no common factors // std::cout << @@ -483,6 +487,12 @@ void test1(const std::string &text) { std::string txt_back = ciphers::HillCipher::decrypt_text(gibberish, dkey); std::cout << "Reconstruct text:\n\t" << txt_back << std::endl; + std::ofstream out_file("hill_cipher_test1.txt"); + out_file << "Block size: " << ekey.size() << "\n"; + out_file << "Encryption Key:\n" << ekey; + out_file << "\nDecryption Key:\n" << dkey; + out_file.close(); + assert(txt_back == text); std::cout << "Passed :)\n"; } @@ -498,7 +508,7 @@ void test2(const std::string &text) { << std::endl; std::pair, matrix> p = - ciphers::HillCipher::generate_keys(8, 0, 5); + ciphers::HillCipher::generate_keys(8, 0, 3); matrix ekey = p.first; matrix dkey = p.second; @@ -508,6 +518,12 @@ void test2(const std::string &text) { std::string txt_back = ciphers::HillCipher::decrypt_text(gibberish, dkey); std::cout << "Reconstruct text:\n\t" << txt_back << std::endl; + std::ofstream out_file("hill_cipher_test2.txt"); + out_file << "Block size: " << ekey.size() << "\n"; + out_file << "Encryption Key:\n" << ekey; + out_file << "\nDecryption Key:\n" << dkey; + out_file.close(); + assert(txt_back.compare(0, text.size(), text) == 0); std::cout << "Passed :)\n"; } From 25c2b82e51b3311998973168e2a9b9c0a3f643c7 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 27 Jun 2020 15:49:46 -0400 Subject: [PATCH 178/271] include ciphers folder in cmake compilation Signed-off-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index adb1c740a..712c3db42 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -68,6 +68,7 @@ endif() add_subdirectory(math) add_subdirectory(others) add_subdirectory(search) +add_subdirectory(ciphers) add_subdirectory(strings) add_subdirectory(sorting) add_subdirectory(geometry) From 12799c561691ca8d15cd3454bae1d427f5dc6feb Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 27 Jun 2020 16:00:12 -0400 Subject: [PATCH 179/271] fix lgtm errors --- ciphers/hill_cipher.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ciphers/hill_cipher.cpp b/ciphers/hill_cipher.cpp index 45315e088..1fef0f32e 100644 --- a/ciphers/hill_cipher.cpp +++ b/ciphers/hill_cipher.cpp @@ -115,7 +115,7 @@ class HillCipher { * should be no more than \f$[0,10]\f$ */ template - static const double rand_range(matrix *M, T1 a, T1 b) { + static double rand_range(matrix *M, T1 a, T1 b) { for (size_t i = 0; i < M->size(); i++) { for (size_t j = 0; j < M[0][0].size(); j++) { M[0][i][j] = rand_range(a, b); @@ -190,7 +190,7 @@ class HillCipher { static inline uint8_t get_char_idx(const char ch) { size_t L = std::strlen(STRKEY); - for (uint8_t idx = 0; idx <= L; idx++) + for (size_t idx = 0; idx <= L; idx++) if (STRKEY[idx] == ch) return idx; From 988df1ba59a9895dfab2293d63bca5b400f16847 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 27 Jun 2020 16:59:31 -0400 Subject: [PATCH 180/271] added licenses - #911 --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index e99ec1311..9b79c11ef 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ ## Overview -The repository is a collection of implementation of a variety of algorithms implemented in C++. These algorithms span a variety of topics from computer science, mathematics and statistics, data science, machine learning, engineering, etc.. The implementations and the associated documentation are meant to provide a learning resource for educators and students. Hence, one may find more than one implementation for the same objective but using a different algorithm strategies and optimizations. +The repository is a collection of open-source implementation of a variety of algorithms implemented in C++ and licensed under [MIT License](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/LICENSE). These algorithms span a variety of topics from computer science, mathematics and statistics, data science, machine learning, engineering, etc.. The implementations and the associated documentation are meant to provide a learning resource for educators and students. Hence, one may find more than one implementation for the same objective but using a different algorithm strategies and optimizations. ## Features @@ -28,6 +28,9 @@ The repository is a collection of implementation of a variety of algorithms impl [Online Documentation](https://TheAlgorithms.github.io/C-Plus-Plus) is generated from the repository source codes directly. The documentation contains all resources including source code snippets, details on execution of the programs, diagrammatic representation of program flow, and links to external resources where necessary. The documentation also introduces interactive source code with links to documentation for C++ STL library functions used. 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. +[Documentation of Algorithms in C++](https://thealgorithms.github.io/C-Plus-Plus) by [The Algorithms Contributors](https://github.com/TheAlgorithms) is licensed under [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/?ref=chooser-v1)
+Creative Commons LicenseCredit must be given to you, the creatorAdaptations must be shared under the same terms + ## Contributions As a community developed and maintained repository, we welcome new un-plagiarized quality contributions. Please read our [Contribution Guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTING.md). From 2d67ce3f52c3924b258667d4148905922054eb80 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 27 Jun 2020 17:06:10 -0400 Subject: [PATCH 181/271] fix article `the` --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9b79c11ef..1d4186d5d 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ ## Overview -The repository is a collection of open-source implementation of a variety of algorithms implemented in C++ and licensed under [MIT License](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/LICENSE). These algorithms span a variety of topics from computer science, mathematics and statistics, data science, machine learning, engineering, etc.. The implementations and the associated documentation are meant to provide a learning resource for educators and students. Hence, one may find more than one implementation for the same objective but using a different algorithm strategies and optimizations. +The repository is a collection of open-source implementation of a variety of algorithms implemented in C++ and licensed under [MIT License](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/LICENSE). The algorithms span a variety of topics from computer science, mathematics and statistics, data science, machine learning, engineering, etc.. The implementations and the associated documentation are meant to provide a learning resource for educators and students. Hence, one may find more than one implementation for the same objective but using a different algorithm strategies and optimizations. ## Features From 998c1ce9be4deb4ae7d6098524ead0748c48c2c7 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 27 Jun 2020 17:06:59 -0400 Subject: [PATCH 182/271] remove closed pull-requests info graphic --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 1d4186d5d..9db8e85ba 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,6 @@ [![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)]("https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTING.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/TheAlgorithms/C-Plus-Plus/workflows/Doxygen%20CI/badge.svg)]("https://TheAlgorithms.github.io/C-Plus-Plus") [![Awesome CI](https://github.com/TheAlgorithms/C-Plus-Plus/workflows/Awesome%20CI%20Workflow/badge.svg)]("https://github.com/TheAlgorithms/C-Plus-Plus/actions?query=workflow%3A%22Awesome+CI+Workflow%22") From 695851b2888e143d15eaab00172f38a1eca7f841 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 27 Jun 2020 17:11:19 -0400 Subject: [PATCH 183/271] fix alternatie text for 'by' icon --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9db8e85ba..417d5769f 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ The repository is a collection of open-source implementation of a variety of alg 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. [Documentation of Algorithms in C++](https://thealgorithms.github.io/C-Plus-Plus) by [The Algorithms Contributors](https://github.com/TheAlgorithms) is licensed under [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/?ref=chooser-v1)
-Creative Commons LicenseCredit must be given to you, the creatorAdaptations must be shared under the same terms +Creative Commons LicenseCredit must be given to the creatorAdaptations must be shared under the same terms ## Contributions From de828baa8deed53c9547ea8b2c4d78637039fd75 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 27 Jun 2020 21:13:48 -0400 Subject: [PATCH 184/271] removed incorrect quotes from links --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 417d5769f..f499f06e7 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,13 @@ # 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) [![Language grade: C/C++](https://img.shields.io/lgtm/grade/cpp/g/TheAlgorithms/C-Plus-Plus.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/TheAlgorithms/C-Plus-Plus/context:cpp) +[![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) +[![Language grade: C/C++](https://img.shields.io/lgtm/grade/cpp/g/TheAlgorithms/C-Plus-Plus.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/TheAlgorithms/C-Plus-Plus/context:cpp) [![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)]("https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTING.md") +[![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/CONTRIBUTING.md) ![GitHub repo size](https://img.shields.io/github/repo-size/TheAlgorithms/C-Plus-Plus?color=red&style=flat-square) -[![Doxygen CI](https://github.com/TheAlgorithms/C-Plus-Plus/workflows/Doxygen%20CI/badge.svg)]("https://TheAlgorithms.github.io/C-Plus-Plus") -[![Awesome CI](https://github.com/TheAlgorithms/C-Plus-Plus/workflows/Awesome%20CI%20Workflow/badge.svg)]("https://github.com/TheAlgorithms/C-Plus-Plus/actions?query=workflow%3A%22Awesome+CI+Workflow%22") +[![Doxygen CI](https://github.com/TheAlgorithms/C-Plus-Plus/workflows/Doxygen%20CI/badge.svg)](https://TheAlgorithms.github.io/C-Plus-Plus) +[![Awesome CI](https://github.com/TheAlgorithms/C-Plus-Plus/workflows/Awesome%20CI%20Workflow/badge.svg)](https://github.com/TheAlgorithms/C-Plus-Plus/actions?query=workflow%3A%22Awesome+CI+Workflow%22) ## Overview From f87bc251b918cd4674f50ac55185588ceaab078f Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 28 Jun 2020 09:14:41 -0400 Subject: [PATCH 185/271] fix link to contributors --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f499f06e7..d19ac813d 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ The repository is a collection of open-source implementation of a variety of alg [Online Documentation](https://TheAlgorithms.github.io/C-Plus-Plus) is generated from the repository source codes directly. The documentation contains all resources including source code snippets, details on execution of the programs, diagrammatic representation of program flow, and links to external resources where necessary. The documentation also introduces interactive source code with links to documentation for C++ STL library functions used. 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. -[Documentation of Algorithms in C++](https://thealgorithms.github.io/C-Plus-Plus) by [The Algorithms Contributors](https://github.com/TheAlgorithms) is licensed under [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/?ref=chooser-v1)
+[Documentation of Algorithms in C++](https://thealgorithms.github.io/C-Plus-Plus) by [The Algorithms Contributors](https://github.com/TheAlgorithms/C-Plus-Plus/graphs/contributors) is licensed under [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/?ref=chooser-v1)
Creative Commons LicenseCredit must be given to the creatorAdaptations must be shared under the same terms ## Contributions From 97023e1b1cf26e79ad72174d353636d6f9fe0c43 Mon Sep 17 00:00:00 2001 From: Tajmeet Singh Date: Mon, 29 Jun 2020 15:27:44 +0100 Subject: [PATCH 186/271] docs: fixed some documentation issues --- math/complex_numbers.cpp | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/math/complex_numbers.cpp b/math/complex_numbers.cpp index 8b24c6d3c..c75b06ac1 100644 --- a/math/complex_numbers.cpp +++ b/math/complex_numbers.cpp @@ -1,8 +1,9 @@ /** * @author tjgurwara99 * @file - * - * A basic implementation of Complex Number field as a class with operators + * + * \brief An implementation of Complex Number as Objects + * \details A basic implementation of Complex Number field as a class with operators * overloaded to accommodate (mathematical) field operations. */ @@ -14,7 +15,7 @@ #include /** - * Class Complex to represent complex numbers as a field. + * \brief Class Complex to represent complex numbers as a field. */ class Complex { // The real value of the complex number @@ -24,8 +25,10 @@ class Complex { public: /** - * Complex Constructor which initialises the complex number which takes two - * arguments. + * \brief Complex Constructor which initialises our complex number. + * \details + * Complex Constructor which initialises the complex number which takes + * three arguments. * @param x If the third parameter is 'true' then this x is the absolute * value of the complex number, if the third parameter is 'false' then this * x is the real value of the complex number (optional). @@ -49,25 +52,28 @@ class Complex { } /** - * Copy Constructor + * \brief Copy Constructor * @param other The other number to equate our number to. */ Complex(const Complex &other) : re(other.real()), im(other.imag()) {} /** + * \brief Member function to get real value of our complex number. * Member function (getter) to access the class' re value. */ double real() const { return this->re; } /** + * \brief Member function to get imaginary value of our complex number. * Member function (getter) to access the class' im value. */ double imag() const { return this->im; } /** + * \brief Member function to give the modulus of our complex number. * Member function to which gives the absolute value (modulus) of our * complex number - * @return \f$ \sqrt{z \dot \bar{z}} \f$ where \f$ z \f$ is our complex + * @return \f$ \sqrt{z \dot \overline{z}} \f$ where \f$ z \f$ is our complex * number. */ double abs() const { @@ -75,12 +81,13 @@ class Complex { } /** - * Member function which gives the argument of our complex number. + * \brief Member function to give the argument of our complex number. * @return Argument of our Complex number in radians. */ double arg() const { return std::atan2(this->im, this->re); } /** + * \brief Operator overload of '+' on Complex class. * Operator overload to be able to add two complex numbers. * @param other The other number that is added to the current number. * @return result current number plus other number @@ -91,6 +98,7 @@ class Complex { } /** + * \brief Operator overload of '-' on Complex class. * Operator overload to be able to subtract two complex numbers. * @param other The other number being subtracted from the current number. * @return result current number subtract other number @@ -101,6 +109,7 @@ class Complex { } /** + * \brief Operator overload of '*' on Complex class. * Operator overload to be able to multiple two complex numbers. * @param other The other number to multiply the current number to. * @return result current number times other number. @@ -112,6 +121,7 @@ class Complex { } /** + * \brief Operator overload of '~' on Complex class. * Operator overload of the BITWISE NOT which gives us the conjugate of our * complex number. NOTE: This is overloading the BITWISE operator but its * not a BITWISE operation in this definition. @@ -123,6 +133,7 @@ class Complex { } /** + * \brief Operator overload of '/' on Complex class. * Operator overload to be able to divide two complex numbers. This function * would throw an exception if the other number is zero. * @param other The other number we divide our number by. @@ -142,6 +153,7 @@ class Complex { } /** + * \brief Operator overload of '=' on Complex class. * Operator overload to be able to copy RHS instance of Complex to LHS * instance of Complex */ @@ -153,6 +165,7 @@ class Complex { }; /** + * \brief Operator overload of '==' on Complex class. * Logical Equal overload for our Complex class. * @param a Left hand side of our expression * @param b Right hand side of our expression @@ -164,6 +177,7 @@ bool operator==(const Complex &a, const Complex &b) { } /** + * \brief Operator overload of '<<' of ostream for Complex class. * Overloaded insersion operator to accommodate the printing of our complex * number in their standard form. * @param os The console stream @@ -181,7 +195,7 @@ std::ostream &operator<<(std::ostream &os, const Complex &num) { } /** - * Function to get random numbers to generate our complex numbers for test + * \brief Function to get random numbers to generate our complex numbers for test */ double get_rand() { return (std::rand() % 100 - 50) / 100.f; } From 1dfbdde3c62dfcd67d4769dcc8c16904527f8b22 Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Wed, 1 Jul 2020 03:28:12 +0530 Subject: [PATCH 187/271] resolve merge conflicts --- numerical_methods/ordinary_least_squares_regressor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/numerical_methods/ordinary_least_squares_regressor.cpp b/numerical_methods/ordinary_least_squares_regressor.cpp index 832d6edf7..bbd75a742 100644 --- a/numerical_methods/ordinary_least_squares_regressor.cpp +++ b/numerical_methods/ordinary_least_squares_regressor.cpp @@ -369,7 +369,7 @@ int main() { std::vector Y(N); std::cout - << "Enter training data. Per sample, provide features and one output." + << "Enter training data. Per sample, provide features ad one output." << std::endl; for (size_t rows = 0; rows < N; rows++) { From d3324aaf34b4fde750192ee9259b62835676a0cf Mon Sep 17 00:00:00 2001 From: Ayaan Khan Date: Wed, 1 Jul 2020 03:54:01 +0530 Subject: [PATCH 188/271] Fix: code quality and Docs --- sorting/insertion_sort.cpp | 103 ++++++++++++++++++++++++++++--------- 1 file changed, 80 insertions(+), 23 deletions(-) diff --git a/sorting/insertion_sort.cpp b/sorting/insertion_sort.cpp index fe920ca59..180330a60 100644 --- a/sorting/insertion_sort.cpp +++ b/sorting/insertion_sort.cpp @@ -1,36 +1,93 @@ -// Insertion Sort +/** + * + * \file + * \brief [Insertion Sort Algorithm + * (Insertion Sort)](https://en.wikipedia.org/wiki/Insertion_sort) + * + * \author + * + * \details + * Insertion sort is a simple sorting algorithm that builds the final + * sorted array one at a time. It is much less efficient compared to + * other sorting algorithms like heap sort, merge sort or quick sort. + * However it has several advantages such as + *
+ * 1 - easy to implement
+ * 2 - For small set of data it is quite efficient
+ * 3 - More efficient that other Quadratic complexity algorithms like
+ *     Selection sort or bubble sort.
+ * 4 - It's stable that is it does not change the relative order of
+ *     elements with equal keys
+ * 5 - Works on hand means it can sort the array or list as it receives.
+ * 
+ * + * It is based on the same idea that people use to sort the playing cards in + * their hands. + * the algorithms goes in the manner that we start iterating over the array + * of elements as soon as we find a unsorted element that is a misplaced + * element we place it at a sorted position. + * + * Suppose initially we have + *
+ * 4 3 2 5 1
+ * 
+ * we start traversing from 4 till we reach 1
+ * when we reach at 3 we find that it is misplaced so we take 3 and place
+ * it at a correct position thus the array will become
+ * 
+ * 3 4 2 5 1
+ *
+ * in the next iteration we are at 2 we find that this is also misplaced so
+ * we place it at the correct sorted position thus the array in this iteration
+ * becomes
+ *
+ * 2 3 4 5 1
+ *
+ * we does not do anything with 5 and move on to the next iteration and select
+ * 1 which is misplaced and place it at correct position. Thus, we have
+ *
+ * 1 2 3 4 5
+ * 
+ * + */ #include -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++) { - std::cin >> Array[i]; - } - - // Sorting +/** \brief + * Insertion Sort Function + * + * @param arr Array to be sorted + * @param n Size of Array + * + */ +void insertionSort(int *arr, int n) { for (int i = 1; i < n; i++) { - int temp = Array[i]; + int temp = arr[i]; int j = i - 1; - while (j >= 0 && temp < Array[j]) { - Array[j + 1] = Array[j]; + while (j >= 0 && temp < arr[j]) { + arr[j + 1] = arr[j]; j--; } - Array[j + 1] = temp; + arr[j + 1] = temp; } +} + +/** Main Function */ +int main() { + int n; + std::cout << "Enter the length of your array : "; + std::cin >> n; + int *arr = new int[n]; + std::cout << "Enter any " << n << " Numbers for Unsorted Array : "; + + for (int i = 0; i < n; i++) std::cin >> arr[i]; + + insertionSort(arr, n); - // Output std::cout << "\nSorted Array : "; - for (int i = 0; i < n; i++) { - std::cout << Array[i] << "\t"; - } + for (int i = 0; i < n; i++) std::cout << arr[i] << " "; - delete[] Array; + std::cout << std::endl; + delete[] arr; return 0; } From d64f17f94c9278fd072e2e2a3477646bd9d5e5bf Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 30 Jun 2020 22:26:08 +0000 Subject: [PATCH 189/271] formatting source-code for 9217b4d8a880915d0a53b2408f38325f4b864e79 --- sorting/insertion_sort.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/sorting/insertion_sort.cpp b/sorting/insertion_sort.cpp index 180330a60..12c1ead69 100644 --- a/sorting/insertion_sort.cpp +++ b/sorting/insertion_sort.cpp @@ -26,15 +26,15 @@ * the algorithms goes in the manner that we start iterating over the array * of elements as soon as we find a unsorted element that is a misplaced * element we place it at a sorted position. - * + * * Suppose initially we have *
  * 4 3 2 5 1
- * 
+ *
  * we start traversing from 4 till we reach 1
  * when we reach at 3 we find that it is misplaced so we take 3 and place
  * it at a correct position thus the array will become
- * 
+ *
  * 3 4 2 5 1
  *
  * in the next iteration we are at 2 we find that this is also misplaced so
@@ -55,7 +55,7 @@
 
 /** \brief
  * Insertion Sort Function
- * 
+ *
  * @param arr Array to be sorted
  * @param n Size of Array
  *
@@ -80,12 +80,12 @@ int main() {
     int *arr = new int[n];
     std::cout << "Enter any " << n << " Numbers for Unsorted Array : ";
 
-    for (int i = 0; i < n; i++)  std::cin >> arr[i];
+    for (int i = 0; i < n; i++) std::cin >> arr[i];
 
     insertionSort(arr, n);
 
     std::cout << "\nSorted Array : ";
-    for (int i = 0; i < n; i++)  std::cout << arr[i] << " ";
+    for (int i = 0; i < n; i++) std::cout << arr[i] << " ";
 
     std::cout << std::endl;
     delete[] arr;

From 8179fbfdec72dda8ea795ad1198525e41dd12740 Mon Sep 17 00:00:00 2001
From: Ayaan Khan 
Date: Wed, 1 Jul 2020 04:03:13 +0530
Subject: [PATCH 190/271] test cases added

---
 sorting/insertion_sort.cpp | 43 +++++++++++++++++++++++++++-----------
 1 file changed, 31 insertions(+), 12 deletions(-)

diff --git a/sorting/insertion_sort.cpp b/sorting/insertion_sort.cpp
index 180330a60..cc3216c1e 100644
--- a/sorting/insertion_sort.cpp
+++ b/sorting/insertion_sort.cpp
@@ -52,6 +52,8 @@
  */
 
 #include 
+#include 
+#include 
 
 /** \brief
  * Insertion Sort Function
@@ -72,22 +74,39 @@ void insertionSort(int *arr, int n) {
     }
 }
 
+/** Test Cases to test algorithm */
+void tests() {
+  int arr1[10] = { 78, 34, 35, 6, 34, 56, 3, 56, 2, 4};
+  insertionSort(arr1, 10);
+  assert(std::is_sorted(arr1, arr1 + 10));
+  std::cout << "Test 1 Passed" << std::endl;
+
+  int arr2[5] = {5, -3, 7, -2, 1};
+  insertionSort(arr2, 5);
+  assert(std::is_sorted(arr2, arr2 + 5));
+  std::cout << "Test 2 Passed" << std::endl;
+}
+
 /** Main Function */
 int main() {
-    int n;
-    std::cout << "Enter the length of your array : ";
-    std::cin >> n;
-    int *arr = new int[n];
-    std::cout << "Enter any " << n << " Numbers for Unsorted Array : ";
+  /// Running predefined tests to test algorithm
+  tests();
 
-    for (int i = 0; i < n; i++)  std::cin >> arr[i];
+  /// For user insteraction
+  int n;
+  std::cout << "Enter the length of your array : ";
+  std::cin >> n;
+  int *arr = new int[n];
+  std::cout << "Enter any " << n << " Numbers for Unsorted Array : ";
 
-    insertionSort(arr, n);
+  for (int i = 0; i < n; i++)  std::cin >> arr[i];
 
-    std::cout << "\nSorted Array : ";
-    for (int i = 0; i < n; i++)  std::cout << arr[i] << " ";
+  insertionSort(arr, n);
 
-    std::cout << std::endl;
-    delete[] arr;
-    return 0;
+  std::cout << "\nSorted Array : ";
+  for (int i = 0; i < n; i++)  std::cout << arr[i] << " ";
+
+  std::cout << std::endl;
+  delete[] arr;
+  return 0;
 }

From 3e1edca0242d83280bd9088a8ea20839cfa7c8c6 Mon Sep 17 00:00:00 2001
From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Date: Tue, 30 Jun 2020 22:35:45 +0000
Subject: [PATCH 191/271] formatting source-code for
 efcccd0148923a03eea0fe95c3e27c38e2d9c46d

---
 sorting/insertion_sort.cpp | 48 +++++++++++++++++++-------------------
 1 file changed, 24 insertions(+), 24 deletions(-)

diff --git a/sorting/insertion_sort.cpp b/sorting/insertion_sort.cpp
index 5b20eef47..877e98f27 100644
--- a/sorting/insertion_sort.cpp
+++ b/sorting/insertion_sort.cpp
@@ -51,9 +51,9 @@
  *
  */
 
-#include 
 #include 
 #include 
+#include 
 
 /** \brief
  * Insertion Sort Function
@@ -76,37 +76,37 @@ void insertionSort(int *arr, int n) {
 
 /** Test Cases to test algorithm */
 void tests() {
-  int arr1[10] = { 78, 34, 35, 6, 34, 56, 3, 56, 2, 4};
-  insertionSort(arr1, 10);
-  assert(std::is_sorted(arr1, arr1 + 10));
-  std::cout << "Test 1 Passed" << std::endl;
+    int arr1[10] = {78, 34, 35, 6, 34, 56, 3, 56, 2, 4};
+    insertionSort(arr1, 10);
+    assert(std::is_sorted(arr1, arr1 + 10));
+    std::cout << "Test 1 Passed" << std::endl;
 
-  int arr2[5] = {5, -3, 7, -2, 1};
-  insertionSort(arr2, 5);
-  assert(std::is_sorted(arr2, arr2 + 5));
-  std::cout << "Test 2 Passed" << std::endl;
+    int arr2[5] = {5, -3, 7, -2, 1};
+    insertionSort(arr2, 5);
+    assert(std::is_sorted(arr2, arr2 + 5));
+    std::cout << "Test 2 Passed" << std::endl;
 }
 
 /** Main Function */
 int main() {
-  /// Running predefined tests to test algorithm
-  tests();
+    /// Running predefined tests to test algorithm
+    tests();
 
-  /// For user insteraction
-  int n;
-  std::cout << "Enter the length of your array : ";
-  std::cin >> n;
-  int *arr = new int[n];
-  std::cout << "Enter any " << n << " Numbers for Unsorted Array : ";
+    /// For user insteraction
+    int n;
+    std::cout << "Enter the length of your array : ";
+    std::cin >> n;
+    int *arr = new int[n];
+    std::cout << "Enter any " << n << " Numbers for Unsorted Array : ";
 
-  for (int i = 0; i < n; i++)  std::cin >> arr[i];
+    for (int i = 0; i < n; i++) std::cin >> arr[i];
 
-  insertionSort(arr, n);
+    insertionSort(arr, n);
 
-  std::cout << "\nSorted Array : ";
-  for (int i = 0; i < n; i++)  std::cout << arr[i] << " ";
+    std::cout << "\nSorted Array : ";
+    for (int i = 0; i < n; i++) std::cout << arr[i] << " ";
 
-  std::cout << std::endl;
-  delete[] arr;
-  return 0;
+    std::cout << std::endl;
+    delete[] arr;
+    return 0;
 }

From dd0a07f18ae5d2e5d78bb657861a131408a7c642 Mon Sep 17 00:00:00 2001
From: Ayaan Khan 
Date: Wed, 1 Jul 2020 15:38:55 +0530
Subject: [PATCH 192/271] loop formating fix

---
 sorting/insertion_sort.cpp | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)

diff --git a/sorting/insertion_sort.cpp b/sorting/insertion_sort.cpp
index 5b20eef47..07cb7375f 100644
--- a/sorting/insertion_sort.cpp
+++ b/sorting/insertion_sort.cpp
@@ -99,12 +99,16 @@ int main() {
   int *arr = new int[n];
   std::cout << "Enter any " << n << " Numbers for Unsorted Array : ";
 
-  for (int i = 0; i < n; i++)  std::cin >> arr[i];
+  for (int i = 0; i < n; i++) {
+    std::cin >> arr[i];
+  }
 
   insertionSort(arr, n);
 
   std::cout << "\nSorted Array : ";
-  for (int i = 0; i < n; i++)  std::cout << arr[i] << " ";
+  for (int i = 0; i < n; i++) {
+    std::cout << arr[i] << " ";
+  }
 
   std::cout << std::endl;
   delete[] arr;

From e4c62d28fec2822c7f4857414e5bf76bdc5cf611 Mon Sep 17 00:00:00 2001
From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Date: Wed, 1 Jul 2020 10:10:51 +0000
Subject: [PATCH 193/271] formatting source-code for
 7af31e32a22952a70682a926866c1ff1bab72b99

---
 sorting/insertion_sort.cpp | 14 +++++++-------
 1 file changed, 7 insertions(+), 7 deletions(-)

diff --git a/sorting/insertion_sort.cpp b/sorting/insertion_sort.cpp
index ceac13903..39298eb45 100644
--- a/sorting/insertion_sort.cpp
+++ b/sorting/insertion_sort.cpp
@@ -99,16 +99,16 @@ int main() {
     int *arr = new int[n];
     std::cout << "Enter any " << n << " Numbers for Unsorted Array : ";
 
-  for (int i = 0; i < n; i++) {
-    std::cin >> arr[i];
-  }
+    for (int i = 0; i < n; i++) {
+        std::cin >> arr[i];
+    }
 
     insertionSort(arr, n);
 
-  std::cout << "\nSorted Array : ";
-  for (int i = 0; i < n; i++) {
-    std::cout << arr[i] << " ";
-  }
+    std::cout << "\nSorted Array : ";
+    for (int i = 0; i < n; i++) {
+        std::cout << arr[i] << " ";
+    }
 
     std::cout << std::endl;
     delete[] arr;

From f586ca1b6493fe5ace0d0bff7de8d7eb50fe5714 Mon Sep 17 00:00:00 2001
From: Tajmeet Singh 
Date: Wed, 1 Jul 2020 14:56:51 +0100
Subject: [PATCH 194/271] docs: fix

---
 math/complex_numbers.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/math/complex_numbers.cpp b/math/complex_numbers.cpp
index c75b06ac1..50fd684d5 100644
--- a/math/complex_numbers.cpp
+++ b/math/complex_numbers.cpp
@@ -73,7 +73,7 @@ class Complex {
      * \brief Member function to give the modulus of our complex number.
      * Member function to which gives the absolute value (modulus) of our
      * complex number
-     * @return \f$ \sqrt{z \dot \overline{z}} \f$ where \f$ z \f$ is our complex
+     * @return \f$ \sqrt{z \bar{z}} \f$ where \f$ z \f$ is our complex
      * number.
      */
     double abs() const {

From 957b57cf60267d0018a3901bbf9ae20b6054c57f Mon Sep 17 00:00:00 2001
From: Krishna Vedala <7001608+kvedala@users.noreply.github.com>
Date: Wed, 1 Jul 2020 10:10:51 -0400
Subject: [PATCH 195/271] fix issues from #929

---
 sorting/insertion_sort.cpp | 106 +++++++++++++++++++++++--------------
 1 file changed, 67 insertions(+), 39 deletions(-)

diff --git a/sorting/insertion_sort.cpp b/sorting/insertion_sort.cpp
index 39298eb45..4bfce9ce6 100644
--- a/sorting/insertion_sort.cpp
+++ b/sorting/insertion_sort.cpp
@@ -4,22 +4,18 @@
  * \brief [Insertion Sort Algorithm
  * (Insertion Sort)](https://en.wikipedia.org/wiki/Insertion_sort)
  *
- * \author
- *
  * \details
  * Insertion sort is a simple sorting algorithm that builds the final
  * sorted array one at a time. It is much less efficient compared to
  * other sorting algorithms like heap sort, merge sort or quick sort.
  * However it has several advantages such as
- * 
- * 1 - easy to implement
- * 2 - For small set of data it is quite efficient
- * 3 - More efficient that other Quadratic complexity algorithms like
- *     Selection sort or bubble sort.
- * 4 - It's stable that is it does not change the relative order of
- *     elements with equal keys
- * 5 - Works on hand means it can sort the array or list as it receives.
- * 
+ * 1. easy to implement + * 2. For small set of data it is quite efficient + * 3. More efficient that other Quadratic complexity algorithms like + * Selection sort or bubble sort. + * 4. It's stable that is it does not change the relative order of + * elements with equal keys + * 5. Works on hand means it can sort the array or list as it receives. * * It is based on the same idea that people use to sort the playing cards in * their hands. @@ -27,44 +23,41 @@ * of elements as soon as we find a unsorted element that is a misplaced * element we place it at a sorted position. * - * Suppose initially we have - *
- * 4 3 2 5 1
- *
- * we start traversing from 4 till we reach 1
+ * Execution example steps:
+ * 1. Suppose initially we have
+ * 
4 3 2 5 1
+ * 2. We start traversing from 4 till we reach 1 * when we reach at 3 we find that it is misplaced so we take 3 and place * it at a correct position thus the array will become - * - * 3 4 2 5 1 - * - * in the next iteration we are at 2 we find that this is also misplaced so + *
3 4 2 5 1
+ * 3. In the next iteration we are at 2 we find that this is also misplaced so * we place it at the correct sorted position thus the array in this iteration * becomes - * - * 2 3 4 5 1 - * - * we does not do anything with 5 and move on to the next iteration and select - * 1 which is misplaced and place it at correct position. Thus, we have - * - * 1 2 3 4 5 - *
- * + *
2 3 4 5 1
+ * 4. we does not do anything with 5 and move on to the next iteration and + * select 1 which is misplaced and place it at correct position. Thus, we have + *
1 2 3 4 5
*/ #include #include #include +#include +/** \namespace sorting + * \brief Sorting algorithms + */ +namespace sorting { /** \brief * Insertion Sort Function * * @param arr Array to be sorted * @param n Size of Array - * */ -void insertionSort(int *arr, int n) { +template +void insertionSort(T *arr, int n) { for (int i = 1; i < n; i++) { - int temp = arr[i]; + T temp = arr[i]; int j = i - 1; while (j >= 0 && temp < arr[j]) { arr[j + 1] = arr[j]; @@ -74,17 +67,48 @@ void insertionSort(int *arr, int n) { } } +template +void insertionSort(std::vector *arr) { + size_t n = arr->size(); + + for (size_t i = 1; i < n; i++) { + T temp = arr[0][i]; + int32_t j = i - 1; + while (j >= 0 && temp < arr[0][j]) { + arr[0][j + 1] = arr[0][j]; + j--; + } + arr[0][j + 1] = temp; + } +} + +} // namespace sorting + /** Test Cases to test algorithm */ void tests() { int arr1[10] = {78, 34, 35, 6, 34, 56, 3, 56, 2, 4}; - insertionSort(arr1, 10); + std::cout << "Test 1... "; + sorting::insertionSort(arr1, 10); assert(std::is_sorted(arr1, arr1 + 10)); - std::cout << "Test 1 Passed" << std::endl; + std::cout << "passed" << std::endl; int arr2[5] = {5, -3, 7, -2, 1}; - insertionSort(arr2, 5); + std::cout << "Test 2... "; + sorting::insertionSort(arr2, 5); assert(std::is_sorted(arr2, arr2 + 5)); - std::cout << "Test 2 Passed" << std::endl; + std::cout << "passed" << std::endl; + + float arr3[5] = {5.6, -3.1, -3.0, -2.1, 1.8}; + std::cout << "Test 3... "; + sorting::insertionSort(arr3, 5); + assert(std::is_sorted(arr3, arr3 + 5)); + std::cout << "passed" << std::endl; + + std::vector arr4({5.6, -3.1, -3.0, -2.1, 1.8}); + std::cout << "Test 4... "; + sorting::insertionSort(&arr4); + assert(std::is_sorted(std::begin(arr4), std::end(arr4))); + std::cout << "passed" << std::endl; } /** Main Function */ @@ -93,9 +117,13 @@ int main() { tests(); /// For user insteraction - int n; - std::cout << "Enter the length of your array : "; + size_t n; + std::cout << "Enter the length of your array (0 to exit): "; std::cin >> n; + if (n == 0) { + return 0; + } + int *arr = new int[n]; std::cout << "Enter any " << n << " Numbers for Unsorted Array : "; @@ -103,7 +131,7 @@ int main() { std::cin >> arr[i]; } - insertionSort(arr, n); + sorting::insertionSort(arr, n); std::cout << "\nSorted Array : "; for (int i = 0; i < n; i++) { From 9b799c93cb9977c66363958b9f5157841d51a768 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Wed, 1 Jul 2020 10:19:18 -0400 Subject: [PATCH 196/271] added documentation for new function --- sorting/insertion_sort.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/sorting/insertion_sort.cpp b/sorting/insertion_sort.cpp index 4bfce9ce6..32315a87a 100644 --- a/sorting/insertion_sort.cpp +++ b/sorting/insertion_sort.cpp @@ -51,7 +51,7 @@ namespace sorting { /** \brief * Insertion Sort Function * - * @param arr Array to be sorted + * @param [in,out] arr Array to be sorted * @param n Size of Array */ template @@ -67,6 +67,10 @@ void insertionSort(T *arr, int n) { } } +/** Insertion Sort Function + * + * @param [in,out] arr pointer to array to be sorted + */ template void insertionSort(std::vector *arr) { size_t n = arr->size(); From 69b5c8395a1d392ba6d1011e8aed1be74cfcf54b Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Wed, 1 Jul 2020 10:36:08 -0400 Subject: [PATCH 197/271] better rendering of example steps --- sorting/insertion_sort.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/sorting/insertion_sort.cpp b/sorting/insertion_sort.cpp index 32315a87a..b6a8f72ac 100644 --- a/sorting/insertion_sort.cpp +++ b/sorting/insertion_sort.cpp @@ -23,20 +23,20 @@ * of elements as soon as we find a unsorted element that is a misplaced * element we place it at a sorted position. * - * Execution example steps: + * Example execution steps: * 1. Suppose initially we have - *
4 3 2 5 1
+ * \f{bmatrix}{4 &3 &2 &5 &1\f} * 2. We start traversing from 4 till we reach 1 * when we reach at 3 we find that it is misplaced so we take 3 and place * it at a correct position thus the array will become - *
3 4 2 5 1
+ * \f{bmatrix}{3 &4 &2 &5 &1\f} * 3. In the next iteration we are at 2 we find that this is also misplaced so * we place it at the correct sorted position thus the array in this iteration * becomes - *
2 3 4 5 1
+ * \f{bmatrix}{2 &3 &4 &5 &1\f} * 4. we does not do anything with 5 and move on to the next iteration and * select 1 which is misplaced and place it at correct position. Thus, we have - *
1 2 3 4 5
+ * \f{bmatrix}{1 &2 &3 &4 &5\f} */ #include From fed7dd1c13d75a736b90260a1d39355732b4e8e5 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Wed, 1 Jul 2020 12:37:54 -0400 Subject: [PATCH 198/271] improved self-tests --- sorting/insertion_sort.cpp | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/sorting/insertion_sort.cpp b/sorting/insertion_sort.cpp index b6a8f72ac..34a55d21a 100644 --- a/sorting/insertion_sort.cpp +++ b/sorting/insertion_sort.cpp @@ -51,6 +51,7 @@ namespace sorting { /** \brief * Insertion Sort Function * + * @tparam T type of array * @param [in,out] arr Array to be sorted * @param n Size of Array */ @@ -69,6 +70,7 @@ void insertionSort(T *arr, int n) { /** Insertion Sort Function * + * @tparam T type of array * @param [in,out] arr pointer to array to be sorted */ template @@ -88,6 +90,21 @@ void insertionSort(std::vector *arr) { } // namespace sorting +/** + * @brief Create a random array objecthelper function to create a random array + * + * @tparam T type of array + * @param arr array to fill (must be pre-allocated) + * @param N number of array elements + */ +template +static void create_random_array(T *arr, int N) { + while (N--) { + double r = (std::rand() % 10000 - 5000) / 100.f; + arr[N] = static_cast(r); + } +} + /** Test Cases to test algorithm */ void tests() { int arr1[10] = {78, 34, 35, 6, 34, 56, 3, 56, 2, 4}; @@ -113,6 +130,20 @@ void tests() { sorting::insertionSort(&arr4); assert(std::is_sorted(std::begin(arr4), std::end(arr4))); std::cout << "passed" << std::endl; + + int arr5[50]; + std::cout << "Test 5... "; + create_random_array(arr5, 50); + sorting::insertionSort(arr5, 50); + assert(std::is_sorted(arr5, arr5 + 50)); + std::cout << "passed" << std::endl; + + float arr6[50]; + std::cout << "Test 6... "; + create_random_array(arr6, 50); + sorting::insertionSort(arr6, 50); + assert(std::is_sorted(arr6, arr6 + 50)); + std::cout << "passed" << std::endl; } /** Main Function */ From 84fd1cb0d01f2d7a33f07adecf8fc4b6088a4fe6 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Wed, 1 Jul 2020 13:04:54 -0400 Subject: [PATCH 199/271] small case 'e' Co-authored-by: Ayaan Khan --- sorting/insertion_sort.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sorting/insertion_sort.cpp b/sorting/insertion_sort.cpp index 34a55d21a..efa60e584 100644 --- a/sorting/insertion_sort.cpp +++ b/sorting/insertion_sort.cpp @@ -9,7 +9,7 @@ * sorted array one at a time. It is much less efficient compared to * other sorting algorithms like heap sort, merge sort or quick sort. * However it has several advantages such as - * 1. easy to implement + * 1. Easy to implement * 2. For small set of data it is quite efficient * 3. More efficient that other Quadratic complexity algorithms like * Selection sort or bubble sort. From 4045bcddf3752d5b2d8efac6ce132c79ff53c7e7 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Wed, 1 Jul 2020 13:05:52 -0400 Subject: [PATCH 200/271] verb correction --- sorting/insertion_sort.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sorting/insertion_sort.cpp b/sorting/insertion_sort.cpp index efa60e584..beb828005 100644 --- a/sorting/insertion_sort.cpp +++ b/sorting/insertion_sort.cpp @@ -34,7 +34,7 @@ * we place it at the correct sorted position thus the array in this iteration * becomes * \f{bmatrix}{2 &3 &4 &5 &1\f} - * 4. we does not do anything with 5 and move on to the next iteration and + * 4. we do not do anything with 5 and move on to the next iteration and * select 1 which is misplaced and place it at correct position. Thus, we have * \f{bmatrix}{1 &2 &3 &4 &5\f} */ From 390ee8428e7f69a609f682c7ddede7279ae187e7 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Wed, 1 Jul 2020 13:08:41 -0400 Subject: [PATCH 201/271] fix to upper case --- sorting/insertion_sort.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sorting/insertion_sort.cpp b/sorting/insertion_sort.cpp index beb828005..c9bac4bf7 100644 --- a/sorting/insertion_sort.cpp +++ b/sorting/insertion_sort.cpp @@ -34,7 +34,7 @@ * we place it at the correct sorted position thus the array in this iteration * becomes * \f{bmatrix}{2 &3 &4 &5 &1\f} - * 4. we do not do anything with 5 and move on to the next iteration and + * 4. We do not do anything with 5 and move on to the next iteration and * select 1 which is misplaced and place it at correct position. Thus, we have * \f{bmatrix}{1 &2 &3 &4 &5\f} */ From 5baf1ad89fee29b5b394bcfe4eafc2327613eaff Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 2 Jul 2020 12:48:35 +0000 Subject: [PATCH 202/271] formatting source-code for 247301c5b5f1c61c015fd2f852832651dc443c2e --- math/complex_numbers.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/math/complex_numbers.cpp b/math/complex_numbers.cpp index 50fd684d5..f89238649 100644 --- a/math/complex_numbers.cpp +++ b/math/complex_numbers.cpp @@ -1,10 +1,10 @@ /** * @author tjgurwara99 * @file - * + * * \brief An implementation of Complex Number as Objects - * \details A basic implementation of Complex Number field as a class with operators - * overloaded to accommodate (mathematical) field operations. + * \details A basic implementation of Complex Number field as a class with + * operators overloaded to accommodate (mathematical) field operations. */ #include @@ -195,7 +195,8 @@ std::ostream &operator<<(std::ostream &os, const Complex &num) { } /** - * \brief Function to get random numbers to generate our complex numbers for test + * \brief Function to get random numbers to generate our complex numbers for + * test */ double get_rand() { return (std::rand() % 100 - 50) / 100.f; } From d11e8cb40a11415ac82888033977d23d52b3c8b5 Mon Sep 17 00:00:00 2001 From: enqidu Date: Tue, 7 Jul 2020 13:30:42 +0400 Subject: [PATCH 203/271] added skip_list.cpp --- data_structures/skip_list.cpp | 185 ++++++++++++++++++++++++++++++++++ 1 file changed, 185 insertions(+) create mode 100644 data_structures/skip_list.cpp diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp new file mode 100644 index 000000000..8b6ec1f70 --- /dev/null +++ b/data_structures/skip_list.cpp @@ -0,0 +1,185 @@ +/** + * A skip list is a data structure that is used for storing a sorted list of items with a + * help of hierarchy of linked lists that connect increasingly sparse subsequences of the items + * + * References used: GeeksForGeeks, https://iq.opengenus.org/skip-list/ Pseudo Code, https://ideone.com/XnXIFl from CodeForces. +*/ + +#include +#include +#include +#include +using namespace std; + +#define MAXLVL 2 +#define P 0.5 + + +/** + * Node structure [Key][Node*, Node*...] +*/ +class Node { +public: + int key; + void* value; + /*Forward Array*/ + vector forward; + Node(int key, int level, void* value); +}; + + +Node::Node(int key, int level, void* value) { + this->key = key; + + /*Initialization of forward vector*/ + for (int i = 0; i < sizeof(Node*)*(level+1); i++){ + forward.push_back(NULL); + } +}; + +// Class for Skip list +class SkipList { + int level; + Node *header; +public: + SkipList(); + int randomLevel(); + void insertElement(int, void*); + void deleteElement(int); + void* searchElement(int); + void displayList(); +}; + +SkipList::SkipList() { + level = 0; + /* Header initialization*/ + header = new Node(-1, MAXLVL, NULL); +}; + + +/** + * Returns random level for skip list; +*/ +int SkipList::randomLevel() { + int lvl = 0; + while(rand()%2 < P && lvl < MAXLVL) lvl++; + return lvl; +}; + + +// Insert given key in skip list +void SkipList::insertElement(int key, void* value) { + printf("Inserting %d key ... ", key); + Node *x = header; + Node *update[MAXLVL+1]; + memset(update, 0, sizeof(Node*)*(MAXLVL+1)); + + + for(int i = level; i >= 0; i--) { + while(x->forward[i] != NULL && x->forward[i]->key < key) x = x->forward[i]; + update[i] = x; + } + + x = x->forward[0]; + + bool doesnt_exist = (x == NULL || x->key != key); + if (doesnt_exist) { + int rlevel = randomLevel(); + + if(rlevel > level) { + for(int i=level+1;iforward[i] = update[i]->forward[i]; + update[i]->forward[i] = n; + } + printf(" Inserted\n"); + } else { + printf("Exists\n"); + } +}; + +// Delete element from skip list +void SkipList::deleteElement(int key) +{ + Node *x = header; + + Node *update[MAXLVL+1]; + memset(update, 0, sizeof(Node*)*(MAXLVL+1)); + + for(int i = level; i >= 0; i--) { + while(x->forward[i] != NULL && x->forward[i]->key < key) x = x->forward[i]; + update[i] = x; + } + + x = x->forward[0]; + + bool doesnt_exist = (x == NULL || x->key != key); + + if(!doesnt_exist) { + for(int i=0;i<=level;i++) { + if(update[i]->forward[i] != x) break; + update[i]->forward[i] = x->forward[i]; + } + /*Remove empty levels*/ + while(level>0 && header->forward[level] == 0) level--; + printf("Deleted\n"); + } else { + printf("Doesnt Exists\n"); + } +}; + + +/** + * Searching element in skip list structure +*/ +void* SkipList::searchElement(int key) { + Node *x = header; + printf("Searching for %d\n", key); + + for(int i = level; i >= 0; i--) { + while(x->forward[i] && x->forward[i]->key < key) x = x->forward[i]; + } + + x = x->forward[0]; + if(x && x->key == key){ + printf("FOUND\n"); + return x->value; + } else { + printf("NOT FOUND\n"); + return NULL; + } +}; + +// Display skip list level wise +void SkipList::displayList() { + printf("----SKIP LIST STRUCTURE----\n"); + for(int i=0; i <= level; i++) { + Node *node = header->forward[i]; + printf("Level %d: ", i); + while(node != NULL) { + printf("%d ", node->key); + node = node->forward[i]; + } + printf("\n"); + } +}; + +int main() +{ + srand((unsigned)time(0)); + + SkipList lst; + + for (int j = 0; j < (1 << (MAXLVL+1)); j++){ + int k = (rand() % (1 << (MAXLVL+1) + 1)); + lst.insertElement(k, &j); + } + + lst.displayList(); +} \ No newline at end of file From ec04afc54fccb6ff4c2f5fe32833e0116ac174b3 Mon Sep 17 00:00:00 2001 From: enqidu Date: Tue, 7 Jul 2020 13:34:13 +0400 Subject: [PATCH 204/271] added skip-list --- data_structures/skip_list.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index 8b6ec1f70..31e6d06f4 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -2,7 +2,7 @@ * A skip list is a data structure that is used for storing a sorted list of items with a * help of hierarchy of linked lists that connect increasingly sparse subsequences of the items * - * References used: GeeksForGeeks, https://iq.opengenus.org/skip-list/ Pseudo Code, https://ideone.com/XnXIFl from CodeForces. + * References used: GeeksForGeeks skip list code, https://iq.opengenus.org/skip-list/ Pseudo Code. */ #include @@ -104,7 +104,7 @@ void SkipList::insertElement(int key, void* value) { } }; -// Delete element from skip list + void SkipList::deleteElement(int key) { Node *x = header; From 94338f527bcd26191ed9136722cb7fba985c4233 Mon Sep 17 00:00:00 2001 From: enqidu Date: Tue, 7 Jul 2020 13:43:27 +0400 Subject: [PATCH 205/271] skip_list --- data_structures/skip_list.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index 31e6d06f4..603d1f2c3 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -9,10 +9,12 @@ #include #include #include -using namespace std; #define MAXLVL 2 #define P 0.5 + +using std::endl; +using std::vector; /** From 2c6b8c3bf74d2875def9d296e8bac7adcf45ecbe Mon Sep 17 00:00:00 2001 From: enqidu Date: Tue, 7 Jul 2020 13:46:52 +0400 Subject: [PATCH 206/271] skip_list --- data_structures/skip_list.cpp | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index 603d1f2c3..bae1a7bbe 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -27,7 +27,7 @@ public: /*Forward Array*/ vector forward; Node(int key, int level, void* value); -}; +} Node::Node(int key, int level, void* value) { @@ -37,7 +37,7 @@ Node::Node(int key, int level, void* value) { for (int i = 0; i < sizeof(Node*)*(level+1); i++){ forward.push_back(NULL); } -}; +} // Class for Skip list class SkipList { @@ -50,14 +50,13 @@ public: void deleteElement(int); void* searchElement(int); void displayList(); -}; +} SkipList::SkipList() { level = 0; /* Header initialization*/ header = new Node(-1, MAXLVL, NULL); -}; - +} /** * Returns random level for skip list; @@ -66,7 +65,7 @@ int SkipList::randomLevel() { int lvl = 0; while(rand()%2 < P && lvl < MAXLVL) lvl++; return lvl; -}; +} // Insert given key in skip list @@ -104,8 +103,7 @@ void SkipList::insertElement(int key, void* value) { } else { printf("Exists\n"); } -}; - +} void SkipList::deleteElement(int key) { @@ -134,7 +132,7 @@ void SkipList::deleteElement(int key) } else { printf("Doesnt Exists\n"); } -}; +} /** @@ -156,7 +154,7 @@ void* SkipList::searchElement(int key) { printf("NOT FOUND\n"); return NULL; } -}; +} // Display skip list level wise void SkipList::displayList() { @@ -170,10 +168,9 @@ void SkipList::displayList() { } printf("\n"); } -}; +} -int main() -{ +int main() { srand((unsigned)time(0)); SkipList lst; @@ -184,4 +181,5 @@ int main() } lst.displayList(); + return 0; } \ No newline at end of file From f13964cab2546754e08e61eda061a260473eb7e5 Mon Sep 17 00:00:00 2001 From: enqidu Date: Tue, 7 Jul 2020 14:04:44 +0400 Subject: [PATCH 207/271] skip-list --- data_structures/skip_list.cpp | 33 ++++++++++++++++++--------------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index bae1a7bbe..19fdc6276 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -9,12 +9,12 @@ #include #include #include +// using namespace std; +using std::vector; +using std::endl; #define MAXLVL 2 #define P 0.5 - -using std::endl; -using std::vector; /** @@ -27,7 +27,7 @@ public: /*Forward Array*/ vector forward; Node(int key, int level, void* value); -} +}; Node::Node(int key, int level, void* value) { @@ -37,7 +37,7 @@ Node::Node(int key, int level, void* value) { for (int i = 0; i < sizeof(Node*)*(level+1); i++){ forward.push_back(NULL); } -} +}; // Class for Skip list class SkipList { @@ -50,13 +50,14 @@ public: void deleteElement(int); void* searchElement(int); void displayList(); -} +}; SkipList::SkipList() { level = 0; /* Header initialization*/ header = new Node(-1, MAXLVL, NULL); -} +}; + /** * Returns random level for skip list; @@ -65,7 +66,7 @@ int SkipList::randomLevel() { int lvl = 0; while(rand()%2 < P && lvl < MAXLVL) lvl++; return lvl; -} +}; // Insert given key in skip list @@ -103,7 +104,8 @@ void SkipList::insertElement(int key, void* value) { } else { printf("Exists\n"); } -} +}; + void SkipList::deleteElement(int key) { @@ -132,7 +134,7 @@ void SkipList::deleteElement(int key) } else { printf("Doesnt Exists\n"); } -} +}; /** @@ -154,7 +156,7 @@ void* SkipList::searchElement(int key) { printf("NOT FOUND\n"); return NULL; } -} +}; // Display skip list level wise void SkipList::displayList() { @@ -168,9 +170,10 @@ void SkipList::displayList() { } printf("\n"); } -} +}; -int main() { +int main() +{ srand((unsigned)time(0)); SkipList lst; @@ -181,5 +184,5 @@ int main() { } lst.displayList(); - return 0; -} \ No newline at end of file + +} From 2fb95a2bf3ba4dd411dd1123a412e28e4ae9560a Mon Sep 17 00:00:00 2001 From: enqidu Date: Tue, 7 Jul 2020 14:29:08 +0400 Subject: [PATCH 208/271] skip_list --- data_structures/skip_list.cpp | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index 19fdc6276..723958866 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -37,7 +37,7 @@ Node::Node(int key, int level, void* value) { for (int i = 0; i < sizeof(Node*)*(level+1); i++){ forward.push_back(NULL); } -}; +} // Class for Skip list class SkipList { @@ -50,13 +50,13 @@ public: void deleteElement(int); void* searchElement(int); void displayList(); -}; +}; SkipList::SkipList() { level = 0; /* Header initialization*/ header = new Node(-1, MAXLVL, NULL); -}; +} /** @@ -64,9 +64,10 @@ SkipList::SkipList() { */ int SkipList::randomLevel() { int lvl = 0; - while(rand()%2 < P && lvl < MAXLVL) lvl++; + thread_local unsigned int seed = time(NULL); + while(rand_r(&seed)%2 < P && lvl < MAXLVL) lvl++; return lvl; -}; +} // Insert given key in skip list @@ -104,7 +105,7 @@ void SkipList::insertElement(int key, void* value) { } else { printf("Exists\n"); } -}; +} void SkipList::deleteElement(int key) @@ -134,7 +135,7 @@ void SkipList::deleteElement(int key) } else { printf("Doesnt Exists\n"); } -}; +} /** @@ -156,7 +157,7 @@ void* SkipList::searchElement(int key) { printf("NOT FOUND\n"); return NULL; } -}; +} // Display skip list level wise void SkipList::displayList() { @@ -170,16 +171,17 @@ void SkipList::displayList() { } printf("\n"); } -}; +} int main() { - srand((unsigned)time(0)); + thread_local unsigned int seed = time(NULL); + SkipList lst; for (int j = 0; j < (1 << (MAXLVL+1)); j++){ - int k = (rand() % (1 << (MAXLVL+1) + 1)); + int k = (rand_r(&seed) % (1 << (MAXLVL+1) + 1)); lst.insertElement(k, &j); } From 2c3d72b102c48b6c4329f5b89b45a546da11eeac Mon Sep 17 00:00:00 2001 From: sprintyaf Date: Tue, 7 Jul 2020 14:38:58 +0400 Subject: [PATCH 209/271] Added fibonacci search --- search/fibonacci_search.cpp | 61 +++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 search/fibonacci_search.cpp diff --git a/search/fibonacci_search.cpp b/search/fibonacci_search.cpp new file mode 100644 index 000000000..29f10c370 --- /dev/null +++ b/search/fibonacci_search.cpp @@ -0,0 +1,61 @@ +#include +#include + +/* +Input: a sorted array and a value +Output: if the array contains the value, returns its index (index of its first occurence) + else returns -1 +*/ + +int fibonacchi_search(std::vector arr, int value){ + int last = 0, current = 1, offset = -1, index; + int length = arr.size(); + int next = last + current; + + while(next < length){ + last = current; + current = next; + next = last + current; + } + + while(next > 1){ + index = std::min(offset + last, length-1); + if(arr[index] < value){ + next = current; + current = last; + last = next - current; + offset = index; + } else if(arr[index] > value){ + next = last; + current = current - last; + last = next - current; + } else { + return index; + } + } + if(current && !arr.empty() && arr[offset+1] == value){ + return offset+1; + } + return -1; +} + +int main() { + int size, value; + std::cout << "Enter size of a sorted array: " << std::endl; + std::cin >> size; + std::cout << "Enter array elements: " << std::endl; + + std::vector arr(size); + for(int i = 0; i < size; i++){ + std::cin >> arr[i]; + } + std::cout << "Enter the value you're looking for: " << std::endl; + std::cin >> value; + int index = fibonacchi_search(arr, value); + if(index != -1){ + std::cout << "Index of the given value is " << index << std::endl; + } else { + std::cout << "Array does not contain the value" << std::endl; + } + return 0; +} From 420915fa0ddff92b6be4922f540c651136f9f6a6 Mon Sep 17 00:00:00 2001 From: enqidu Date: Tue, 7 Jul 2020 14:48:30 +0400 Subject: [PATCH 210/271] skip_list --- data_structures/skip_list.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index 723958866..550a5c9d3 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -9,6 +9,8 @@ #include #include #include +#include +#include // using namespace std; using std::vector; using std::endl; @@ -58,6 +60,8 @@ SkipList::SkipList() { header = new Node(-1, MAXLVL, NULL); } + + /** * Returns random level for skip list; @@ -187,4 +191,6 @@ int main() lst.displayList(); + + } From 910180ff214ae669eb0a9ec6a923a7d00755d746 Mon Sep 17 00:00:00 2001 From: enqidu Date: Tue, 7 Jul 2020 14:54:44 +0400 Subject: [PATCH 211/271] skip_list --- data_structures/skip_list.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index 550a5c9d3..3b4ba500f 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -11,6 +11,8 @@ #include #include #include +#include + // using namespace std; using std::vector; using std::endl; From 363f43c942879a2ee92253588896fb3c81c8780a Mon Sep 17 00:00:00 2001 From: sprintyaf Date: Tue, 7 Jul 2020 14:57:57 +0400 Subject: [PATCH 212/271] min function implemented --- search/fibonacci_search.cpp | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/search/fibonacci_search.cpp b/search/fibonacci_search.cpp index 29f10c370..af3858e74 100644 --- a/search/fibonacci_search.cpp +++ b/search/fibonacci_search.cpp @@ -7,7 +7,15 @@ Output: if the array contains the value, returns its index (index of its first o else returns -1 */ -int fibonacchi_search(std::vector arr, int value){ +int min(int first, int second){ + if(first > second){ + return first; + } else { + return second; + } +} + +int fibonacci_search(std::vector arr, int value){ int last = 0, current = 1, offset = -1, index; int length = arr.size(); int next = last + current; @@ -19,7 +27,7 @@ int fibonacchi_search(std::vector arr, int value){ } while(next > 1){ - index = std::min(offset + last, length-1); + index = min(offset + last, length-1); if(arr[index] < value){ next = current; current = last; @@ -51,7 +59,7 @@ int main() { } std::cout << "Enter the value you're looking for: " << std::endl; std::cin >> value; - int index = fibonacchi_search(arr, value); + int index = fibonacci_search(arr, value); if(index != -1){ std::cout << "Index of the given value is " << index << std::endl; } else { From 1002126449a0599630df669397aa49a1586e3e90 Mon Sep 17 00:00:00 2001 From: sprintyaf Date: Tue, 7 Jul 2020 15:05:07 +0400 Subject: [PATCH 213/271] min function corrected --- search/fibonacci_search.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/search/fibonacci_search.cpp b/search/fibonacci_search.cpp index af3858e74..0bf33c494 100644 --- a/search/fibonacci_search.cpp +++ b/search/fibonacci_search.cpp @@ -8,7 +8,7 @@ Output: if the array contains the value, returns its index (index of its first o */ int min(int first, int second){ - if(first > second){ + if(first < second){ return first; } else { return second; From 8e99383dbf8f373fc7a99fd2db8187f3f88441f4 Mon Sep 17 00:00:00 2001 From: enqidu Date: Tue, 7 Jul 2020 15:13:01 +0400 Subject: [PATCH 214/271] skip_list --- data_structures/skip_list.cpp | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index 3b4ba500f..fe5820b43 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -70,8 +70,7 @@ SkipList::SkipList() { */ int SkipList::randomLevel() { int lvl = 0; - thread_local unsigned int seed = time(NULL); - while(rand_r(&seed)%2 < P && lvl < MAXLVL) lvl++; + while((float)rand()/RAND_MAX < P && lvl < MAXLVL) lvl++; return lvl; } @@ -181,13 +180,12 @@ void SkipList::displayList() { int main() { - thread_local unsigned int seed = time(NULL); + srand((unsigned)time(0)); - SkipList lst; for (int j = 0; j < (1 << (MAXLVL+1)); j++){ - int k = (rand_r(&seed) % (1 << (MAXLVL+1) + 1)); + int k = (rand()% (1 << (MAXLVL+1) + 1)); lst.insertElement(k, &j); } From 2fc0d5bffeaff3845fd8b3ca774b0f9f50cc2299 Mon Sep 17 00:00:00 2001 From: enqidu Date: Tue, 7 Jul 2020 16:40:47 +0400 Subject: [PATCH 215/271] skip-list corrected --- data_structures/skip_list.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index fe5820b43..69836e13a 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -180,12 +180,12 @@ void SkipList::displayList() { int main() { - srand((unsigned)time(0)); + std::srand(time(nullptr)); SkipList lst; for (int j = 0; j < (1 << (MAXLVL+1)); j++){ - int k = (rand()% (1 << (MAXLVL+1) + 1)); + int k = (std::rand()% (1 << (MAXLVL+1) + 1)); lst.insertElement(k, &j); } From ba65d559c5912861bad589e7832becdf321bc01f Mon Sep 17 00:00:00 2001 From: enqidu Date: Tue, 7 Jul 2020 16:51:47 +0400 Subject: [PATCH 216/271] skip-list documentation-polish --- data_structures/skip_list.cpp | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index 69836e13a..988165db3 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -70,14 +70,14 @@ SkipList::SkipList() { */ int SkipList::randomLevel() { int lvl = 0; - while((float)rand()/RAND_MAX < P && lvl < MAXLVL) lvl++; + while(static_cast(rand())/RAND_MAX < P && lvl < MAXLVL) lvl++; return lvl; } // Insert given key in skip list void SkipList::insertElement(int key, void* value) { - printf("Inserting %d key ... ", key); + std::cout << "Inserting" << key << "..."; Node *x = header; Node *update[MAXLVL+1]; memset(update, 0, sizeof(Node*)*(MAXLVL+1)); @@ -106,13 +106,14 @@ void SkipList::insertElement(int key, void* value) { n->forward[i] = update[i]->forward[i]; update[i]->forward[i] = n; } - printf(" Inserted\n"); + std::cout << "Inserted" << endl; + } else { - printf("Exists\n"); + std::cout << "Exists" << endl; } } - + /**Delete document by key*/ void SkipList::deleteElement(int key) { Node *x = header; @@ -136,9 +137,9 @@ void SkipList::deleteElement(int key) } /*Remove empty levels*/ while(level>0 && header->forward[level] == 0) level--; - printf("Deleted\n"); + std::cout << "Deleted" << endl; } else { - printf("Doesnt Exists\n"); + std::cout << "Doesn't exist" << endl; } } @@ -148,7 +149,7 @@ void SkipList::deleteElement(int key) */ void* SkipList::searchElement(int key) { Node *x = header; - printf("Searching for %d\n", key); + std::cout << "Searching for " + key << endl; for(int i = level; i >= 0; i--) { while(x->forward[i] && x->forward[i]->key < key) x = x->forward[i]; @@ -156,25 +157,25 @@ void* SkipList::searchElement(int key) { x = x->forward[0]; if(x && x->key == key){ - printf("FOUND\n"); + std::cout << "Found" << endl; return x->value; } else { - printf("NOT FOUND\n"); + std::cout << "Not Found" << endl; return NULL; } } // Display skip list level wise void SkipList::displayList() { - printf("----SKIP LIST STRUCTURE----\n"); + std::cout << "Displaying list:\n" << endl; for(int i=0; i <= level; i++) { Node *node = header->forward[i]; - printf("Level %d: ", i); + std::cout << "Level " << (i) << ": "; while(node != NULL) { - printf("%d ", node->key); + std::cout << node->key << " "; node = node->forward[i]; } - printf("\n"); + std::cout << endl; } } From 5068ddc14d093c2434edcb359fca0d3594dff86c Mon Sep 17 00:00:00 2001 From: enqidu Date: Tue, 7 Jul 2020 16:55:52 +0400 Subject: [PATCH 217/271] skip-list documentation-polish --- data_structures/skip_list.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index 988165db3..d2ba820f4 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -70,7 +70,7 @@ SkipList::SkipList() { */ int SkipList::randomLevel() { int lvl = 0; - while(static_cast(rand())/RAND_MAX < P && lvl < MAXLVL) lvl++; + while(static_cast(std::rand())/RAND_MAX < P && lvl < MAXLVL) lvl++; return lvl; } From dcdebae395ae9edbf40461b8a1cd31659ad20526 Mon Sep 17 00:00:00 2001 From: enqidu Date: Tue, 7 Jul 2020 17:24:13 +0400 Subject: [PATCH 218/271] skip-list documentation-polish --- data_structures/skip_list.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index d2ba820f4..782486632 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -54,7 +54,10 @@ public: void deleteElement(int); void* searchElement(int); void displayList(); + ~SkipList(); }; + + SkipList::SkipList() { level = 0; @@ -63,6 +66,18 @@ SkipList::SkipList() { } +SkipList::~SkipList(){ + delete header; + for(int i=0; i <= level; i++) { + Node *node = header->forward[i]; + Node* temp; + while(node != NULL) { + temp = node; + node = node->forward[i]; + delete temp; + } + } +} /** From 86c6af46e865d78e9a41256414690ded7916efb3 Mon Sep 17 00:00:00 2001 From: sprintyaf Date: Tue, 7 Jul 2020 17:27:45 +0400 Subject: [PATCH 219/271] doxygen documentation and tests added --- search/fibonacci_search.cpp | 140 +++++++++++++++++++++++++++++------- 1 file changed, 116 insertions(+), 24 deletions(-) diff --git a/search/fibonacci_search.cpp b/search/fibonacci_search.cpp index 0bf33c494..2a3ba7207 100644 --- a/search/fibonacci_search.cpp +++ b/search/fibonacci_search.cpp @@ -1,12 +1,19 @@ +/** + * Copyright 2020 @author sprintyaf + * @file + * @brief [Fibonacci search + * algorithm](https://en.wikipedia.org/wiki/Fibonacci_search_technique) + */ + #include -#include +#include // for std::vector class +#include // for assert -/* -Input: a sorted array and a value -Output: if the array contains the value, returns its index (index of its first occurence) - else returns -1 -*/ + +/** + * Returns minimum of the two numbers + */ int min(int first, int second){ if(first < second){ return first; @@ -15,7 +22,12 @@ int min(int first, int second){ } } -int fibonacci_search(std::vector arr, int value){ +/** + * Input: a sorted array and a value + * Output: if the array contains the value, returns its index + * else returns -1 + */ +int fibonacci_search(std::vector &arr, int value){ int last = 0, current = 1, offset = -1, index; int length = arr.size(); int next = last + current; @@ -47,23 +59,103 @@ int fibonacci_search(std::vector arr, int value){ return -1; } -int main() { - int size, value; - std::cout << "Enter size of a sorted array: " << std::endl; - std::cin >> size; - std::cout << "Enter array elements: " << std::endl; +/** + * Tests where given value occurs only once + */ +bool one_occurence_test(){ + // declarations + int value, index; + bool passed = true; + std::vector arr; + // last element + arr = {1, 2, 3}; + value = 3; + index = fibonacci_search(arr, value); + passed = passed && (index == 2); + // first element + value = 1; + index = fibonacci_search(arr, value); + passed = passed && (index == 0); + // somewhere in the middle element + arr = {1, 3, 5, 7}; + value = 3; + index = fibonacci_search(arr, value); + passed = passed && (index == 1); + // arr size is 1 + arr = {10}; + value = 10; + index = fibonacci_search(arr, value); + passed = passed && (index == 0); - std::vector arr(size); - for(int i = 0; i < size; i++){ - std::cin >> arr[i]; - } - std::cout << "Enter the value you're looking for: " << std::endl; - std::cin >> value; - int index = fibonacci_search(arr, value); - if(index != -1){ - std::cout << "Index of the given value is " << index << std::endl; - } else { - std::cout << "Array does not contain the value" << std::endl; - } + return passed; +} + +/** + * Tests where given value occurs more than once + */ +bool many_occurence_test(){ + // declarations + int value, index; + bool passed = true; + std::vector arr; + // last element + arr = {1, 1, 10, 10}; + value = 10; + index = fibonacci_search(arr, value); + passed = passed && (index == 2 || index == 3); + // first element + value = 1; + index = fibonacci_search(arr, value); + passed = passed && (index == 0 || index == 1); + // somewhere in the middle element + arr = {1, 3, 3, 7}; + value = 3; + index = fibonacci_search(arr, value); + passed = passed && (index == 1 || index == 2); + // all elements are the same + arr = {10, 10, 10}; + value = 10; + index = fibonacci_search(arr, value); + passed = passed && (index >= 0 && index <= 2); + + return passed; +} + +/** + * Tests where the array doesn't contain given value + */ +bool no_occurence_test(){ + // declarations + int value, index; + bool passed = true; + std::vector arr; + // many elements + arr = {1, 2, 4, 5}; + value = 3; + index = fibonacci_search(arr, value); + passed = passed && (index == -1); + // one element + arr = {1}; + value = 2; + index = fibonacci_search(arr, value); + passed = passed && (index == -1); + // empty array + arr.clear(); + value = 10; + index = fibonacci_search(arr, value); + passed = passed && (index == -1); + + return passed; +} + + +/** + * Main Function + * testing the algorithm + */ +int main() { + assert(one_occurence_test()); + assert(many_occurence_test()); + assert(no_occurence_test()); return 0; } From 8e53f4da833c4e5410a74e26dce8b15cb46b41a0 Mon Sep 17 00:00:00 2001 From: sprintyaf Date: Tue, 7 Jul 2020 17:54:55 +0400 Subject: [PATCH 220/271] converted from vector to array --- search/fibonacci_search.cpp | 65 ++++++++++++++++++++----------------- 1 file changed, 35 insertions(+), 30 deletions(-) diff --git a/search/fibonacci_search.cpp b/search/fibonacci_search.cpp index 2a3ba7207..5cdc93ae9 100644 --- a/search/fibonacci_search.cpp +++ b/search/fibonacci_search.cpp @@ -23,13 +23,12 @@ int min(int first, int second){ } /** - * Input: a sorted array and a value + * Input: a sorted array, a value we're looking for and size of the array * Output: if the array contains the value, returns its index * else returns -1 */ -int fibonacci_search(std::vector &arr, int value){ +int fibonacci_search(int *arr, int value, int length){ int last = 0, current = 1, offset = -1, index; - int length = arr.size(); int next = last + current; while(next < length){ @@ -53,7 +52,7 @@ int fibonacci_search(std::vector &arr, int value){ return index; } } - if(current && !arr.empty() && arr[offset+1] == value){ + if(current && (length > 0) && arr[offset+1] == value){ return offset+1; } return -1; @@ -64,27 +63,29 @@ int fibonacci_search(std::vector &arr, int value){ */ bool one_occurence_test(){ // declarations - int value, index; + int value, index, length; bool passed = true; - std::vector arr; // last element - arr = {1, 2, 3}; + length = 3; + int arr1[length] = {1, 2, 3}; value = 3; - index = fibonacci_search(arr, value); + index = fibonacci_search(arr1, value, length); passed = passed && (index == 2); // first element value = 1; - index = fibonacci_search(arr, value); + index = fibonacci_search(arr1, value, length); passed = passed && (index == 0); // somewhere in the middle element - arr = {1, 3, 5, 7}; + length = 4; + int arr2[length] = {1, 3, 5, 7}; value = 3; - index = fibonacci_search(arr, value); + index = fibonacci_search(arr2, value, length); passed = passed && (index == 1); // arr size is 1 - arr = {10}; + length = 1; + int arr3[length] = {10}; value = 10; - index = fibonacci_search(arr, value); + index = fibonacci_search(arr3, value, length); passed = passed && (index == 0); return passed; @@ -95,27 +96,29 @@ bool one_occurence_test(){ */ bool many_occurence_test(){ // declarations - int value, index; + int value, index, length; bool passed = true; - std::vector arr; // last element - arr = {1, 1, 10, 10}; + length = 4; + int arr1[length] = {1, 1, 10, 10}; value = 10; - index = fibonacci_search(arr, value); + index = fibonacci_search(arr1, value, length); passed = passed && (index == 2 || index == 3); // first element value = 1; - index = fibonacci_search(arr, value); + index = fibonacci_search(arr1, value, length); passed = passed && (index == 0 || index == 1); // somewhere in the middle element - arr = {1, 3, 3, 7}; + length = 4; + int arr2[length] = {1, 3, 3, 7}; value = 3; - index = fibonacci_search(arr, value); + index = fibonacci_search(arr2, value, length); passed = passed && (index == 1 || index == 2); // all elements are the same - arr = {10, 10, 10}; + length = 3; + int arr3[length] = {10, 10, 10}; value = 10; - index = fibonacci_search(arr, value); + index = fibonacci_search(arr3, value, length); passed = passed && (index >= 0 && index <= 2); return passed; @@ -126,23 +129,25 @@ bool many_occurence_test(){ */ bool no_occurence_test(){ // declarations - int value, index; + int value, index, length; bool passed = true; - std::vector arr; // many elements - arr = {1, 2, 4, 5}; + length = 4; + int arr1[length] = {1, 2, 4, 5}; value = 3; - index = fibonacci_search(arr, value); + index = fibonacci_search(arr1, value, length); passed = passed && (index == -1); // one element - arr = {1}; + length = 1; + int arr2[length] = {1}; value = 2; - index = fibonacci_search(arr, value); + index = fibonacci_search(arr2, value, length); passed = passed && (index == -1); // empty array - arr.clear(); + length = 0; + int arr3[length]; value = 10; - index = fibonacci_search(arr, value); + index = fibonacci_search(arr3, value, length); passed = passed && (index == -1); return passed; From 4b3749ed49d863bbfd2090c56151586962c7b78d Mon Sep 17 00:00:00 2001 From: sprintyaf Date: Tue, 7 Jul 2020 17:59:49 +0400 Subject: [PATCH 221/271] variable-length arrays fixed --- search/fibonacci_search.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/search/fibonacci_search.cpp b/search/fibonacci_search.cpp index 5cdc93ae9..f8525a6b4 100644 --- a/search/fibonacci_search.cpp +++ b/search/fibonacci_search.cpp @@ -67,7 +67,7 @@ bool one_occurence_test(){ bool passed = true; // last element length = 3; - int arr1[length] = {1, 2, 3}; + int arr1[3] = {1, 2, 3}; value = 3; index = fibonacci_search(arr1, value, length); passed = passed && (index == 2); @@ -77,13 +77,13 @@ bool one_occurence_test(){ passed = passed && (index == 0); // somewhere in the middle element length = 4; - int arr2[length] = {1, 3, 5, 7}; + int arr2[4] = {1, 3, 5, 7}; value = 3; index = fibonacci_search(arr2, value, length); passed = passed && (index == 1); // arr size is 1 length = 1; - int arr3[length] = {10}; + int arr3[1] = {10}; value = 10; index = fibonacci_search(arr3, value, length); passed = passed && (index == 0); @@ -100,7 +100,7 @@ bool many_occurence_test(){ bool passed = true; // last element length = 4; - int arr1[length] = {1, 1, 10, 10}; + int arr1[4] = {1, 1, 10, 10}; value = 10; index = fibonacci_search(arr1, value, length); passed = passed && (index == 2 || index == 3); @@ -110,13 +110,13 @@ bool many_occurence_test(){ passed = passed && (index == 0 || index == 1); // somewhere in the middle element length = 4; - int arr2[length] = {1, 3, 3, 7}; + int arr2[4] = {1, 3, 3, 7}; value = 3; index = fibonacci_search(arr2, value, length); passed = passed && (index == 1 || index == 2); // all elements are the same length = 3; - int arr3[length] = {10, 10, 10}; + int arr3[3] = {10, 10, 10}; value = 10; index = fibonacci_search(arr3, value, length); passed = passed && (index >= 0 && index <= 2); @@ -133,19 +133,19 @@ bool no_occurence_test(){ bool passed = true; // many elements length = 4; - int arr1[length] = {1, 2, 4, 5}; + int arr1[4] = {1, 2, 4, 5}; value = 3; index = fibonacci_search(arr1, value, length); passed = passed && (index == -1); // one element length = 1; - int arr2[length] = {1}; + int arr2[1] = {1}; value = 2; index = fibonacci_search(arr2, value, length); passed = passed && (index == -1); // empty array length = 0; - int arr3[length]; + int arr3[10] = {}; value = 10; index = fibonacci_search(arr3, value, length); passed = passed && (index == -1); From f7ab869d90db9666592980e87ce3465f76de2aaf Mon Sep 17 00:00:00 2001 From: enqidu Date: Tue, 7 Jul 2020 18:16:38 +0400 Subject: [PATCH 222/271] skip list update --- data_structures/skip_list.cpp | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index 782486632..480e9dedf 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -7,25 +7,22 @@ #include #include -#include #include #include #include -#include // using namespace std; using std::vector; using std::endl; -#define MAXLVL 2 -#define P 0.5 +#define MAXLVL 2 ///< maximum level of skip list +#define P 0.5 ///< current probability for "coin toss" /** * Node structure [Key][Node*, Node*...] */ -class Node { -public: +struct Node { int key; void* value; /*Forward Array*/ @@ -38,7 +35,7 @@ Node::Node(int key, int level, void* value) { this->key = key; /*Initialization of forward vector*/ - for (int i = 0; i < sizeof(Node*)*(level+1); i++){ + for (int i = 0; i < (level+1); i++){ forward.push_back(NULL); } } @@ -67,7 +64,6 @@ SkipList::SkipList() { SkipList::~SkipList(){ - delete header; for(int i=0; i <= level; i++) { Node *node = header->forward[i]; Node* temp; @@ -77,6 +73,7 @@ SkipList::~SkipList(){ delete temp; } } + delete header; } @@ -201,12 +198,10 @@ int main() SkipList lst; for (int j = 0; j < (1 << (MAXLVL+1)); j++){ - int k = (std::rand()% (1 << (MAXLVL+1) + 1)); + int k = (std::rand()%( 1 << (MAXLVL+2)) + 1); lst.insertElement(k, &j); } lst.displayList(); - - } From fd8affb59d86b90f244adcd3ccb49dc2b1acf09a Mon Sep 17 00:00:00 2001 From: enqidu Date: Tue, 7 Jul 2020 18:20:21 +0400 Subject: [PATCH 223/271] skip_list --- data_structures/skip_list.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index 480e9dedf..9d829349e 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -9,7 +9,7 @@ #include #include #include -#include +#include // using namespace std; using std::vector; From 4cebe7c68270e5474e1b0a3c65355157a741b23b Mon Sep 17 00:00:00 2001 From: enqidu Date: Tue, 7 Jul 2020 18:21:12 +0400 Subject: [PATCH 224/271] skip_list --- data_structures/skip_list.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index 9d829349e..180d9c32d 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -193,7 +193,7 @@ void SkipList::displayList() { int main() { - std::srand(time(nullptr)); + std::srand(std::time(nullptr)); SkipList lst; From ac0d11977d0b8fcc3396855bed490bfc690b2ad4 Mon Sep 17 00:00:00 2001 From: enqidu Date: Tue, 7 Jul 2020 19:17:37 +0400 Subject: [PATCH 225/271] skip_list --- data_structures/skip_list.cpp | 66 ++++++++++++++++++++++------------- 1 file changed, 41 insertions(+), 25 deletions(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index 180d9c32d..c41d3c2e1 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -2,7 +2,7 @@ * A skip list is a data structure that is used for storing a sorted list of items with a * help of hierarchy of linked lists that connect increasingly sparse subsequences of the items * - * References used: GeeksForGeeks skip list code, https://iq.opengenus.org/skip-list/ Pseudo Code. + * References used: GeeksForGeeks skip list code, https://iq.opengenus.org/skip-list/ Code and PseudoCode. */ #include @@ -15,28 +15,31 @@ using std::vector; using std::endl; -#define MAXLVL 2 ///< maximum level of skip list -#define P 0.5 ///< current probability for "coin toss" +#define MAX_LEVEL 2 ///< maximum level of skip list +#define PROBABILITY 0.5 ///< current probability for "coin toss" /** * Node structure [Key][Node*, Node*...] */ struct Node { - int key; + int key; + /* pointer of value */ void* value; /*Forward Array*/ vector forward; Node(int key, int level, void* value); }; - +/** + * Creates node with provided key, level and value; +*/ Node::Node(int key, int level, void* value) { this->key = key; /*Initialization of forward vector*/ for (int i = 0; i < (level+1); i++){ - forward.push_back(NULL); + forward.push_back(nullptr); } } @@ -55,11 +58,13 @@ public: }; - +/**\ + * Skeep List constructor; +*/ SkipList::SkipList() { level = 0; /* Header initialization*/ - header = new Node(-1, MAXLVL, NULL); + header = new Node(-1, MAX_LEVEL, nullptr); } @@ -67,7 +72,7 @@ SkipList::~SkipList(){ for(int i=0; i <= level; i++) { Node *node = header->forward[i]; Node* temp; - while(node != NULL) { + while(node != nullptr) { temp = node; node = node->forward[i]; delete temp; @@ -82,27 +87,31 @@ SkipList::~SkipList(){ */ int SkipList::randomLevel() { int lvl = 0; - while(static_cast(std::rand())/RAND_MAX < P && lvl < MAXLVL) lvl++; + while(static_cast(std::rand())/RAND_MAX < PROBABILITY && lvl < MAX_LEVEL) lvl++; return lvl; } -// Insert given key in skip list + +/** + * Inserts elements with given key and value; + * It's level is computed by randomLevel() function. +*/ void SkipList::insertElement(int key, void* value) { std::cout << "Inserting" << key << "..."; Node *x = header; - Node *update[MAXLVL+1]; - memset(update, 0, sizeof(Node*)*(MAXLVL+1)); + Node *update[MAX_LEVEL+1]; + memset(update, 0, sizeof(Node*)*(MAX_LEVEL+1)); for(int i = level; i >= 0; i--) { - while(x->forward[i] != NULL && x->forward[i]->key < key) x = x->forward[i]; + while(x->forward[i] != nullptr && x->forward[i]->key < key) x = x->forward[i]; update[i] = x; } x = x->forward[0]; - bool doesnt_exist = (x == NULL || x->key != key); + bool doesnt_exist = (x == nullptr || x->key != key); if (doesnt_exist) { int rlevel = randomLevel(); @@ -130,17 +139,17 @@ void SkipList::deleteElement(int key) { Node *x = header; - Node *update[MAXLVL+1]; - memset(update, 0, sizeof(Node*)*(MAXLVL+1)); + Node *update[MAX_LEVEL+1]; + memset(update, 0, sizeof(Node*)*(MAX_LEVEL+1)); for(int i = level; i >= 0; i--) { - while(x->forward[i] != NULL && x->forward[i]->key < key) x = x->forward[i]; + while(x->forward[i] != nullptr && x->forward[i]->key < key) x = x->forward[i]; update[i] = x; } x = x->forward[0]; - bool doesnt_exist = (x == NULL || x->key != key); + bool doesnt_exist = (x == nullptr || x->key != key); if(!doesnt_exist) { for(int i=0;i<=level;i++) { @@ -173,32 +182,39 @@ void* SkipList::searchElement(int key) { return x->value; } else { std::cout << "Not Found" << endl; - return NULL; + return nullptr; } } -// Display skip list level wise +/** + * Display skip list level wise + */ void SkipList::displayList() { std::cout << "Displaying list:\n" << endl; for(int i=0; i <= level; i++) { Node *node = header->forward[i]; std::cout << "Level " << (i) << ": "; - while(node != NULL) { + while(node != nullptr) { std::cout << node->key << " "; node = node->forward[i]; } std::cout << endl; } } - + + +/** + * Main function: + * Creates and inserts random 2^[number of levels] elements into the skip lists and than displays it + */ int main() { std::srand(std::time(nullptr)); SkipList lst; - for (int j = 0; j < (1 << (MAXLVL+1)); j++){ - int k = (std::rand()%( 1 << (MAXLVL+2)) + 1); + for (int j = 0; j < (1 << (MAX_LEVEL+1)); j++){ + int k = (std::rand()%( 1 << (MAX_LEVEL+2)) + 1); lst.insertElement(k, &j); } From d5b897d40e3354e64c6c1bb1bf91435a2bb769b4 Mon Sep 17 00:00:00 2001 From: enqidu Date: Tue, 7 Jul 2020 19:22:32 +0400 Subject: [PATCH 226/271] improve --- data_structures/skip_list.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index c41d3c2e1..5881f5d27 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -7,8 +7,7 @@ #include #include -#include -#include +#include #include // using namespace std; From ea57ad29cd350a265be297a49bc8c65c8dfcc825 Mon Sep 17 00:00:00 2001 From: enqidu Date: Tue, 7 Jul 2020 19:55:47 +0400 Subject: [PATCH 227/271] improve --- data_structures/skip_list.cpp | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index 5881f5d27..eb8e5cd87 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -23,26 +23,28 @@ using std::endl; */ struct Node { int key; - /* pointer of value */ + //pointer of value void* value; - /*Forward Array*/ + //Forward Array vector forward; Node(int key, int level, void* value); }; /** - * Creates node with provided key, level and value; + * Creates node with provided key, level and value */ Node::Node(int key, int level, void* value) { this->key = key; - /*Initialization of forward vector*/ + //Initialization of forward vector for (int i = 0; i < (level+1); i++){ forward.push_back(nullptr); } } -// Class for Skip list +/** + * SkipList class +*/ class SkipList { int level; Node *header; @@ -57,12 +59,12 @@ public: }; -/**\ - * Skeep List constructor; +/** + * Skeep List constructor */ SkipList::SkipList() { level = 0; - /* Header initialization*/ + // Header initialization header = new Node(-1, MAX_LEVEL, nullptr); } @@ -117,7 +119,7 @@ void SkipList::insertElement(int key, void* value) { if(rlevel > level) { for(int i=level+1;i Date: Tue, 7 Jul 2020 19:58:10 +0400 Subject: [PATCH 228/271] improve --- data_structures/skip_list.cpp | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index eb8e5cd87..25a9aae2a 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -1,4 +1,4 @@ -/** +/* * A skip list is a data structure that is used for storing a sorted list of items with a * help of hierarchy of linked lists that connect increasingly sparse subsequences of the items * @@ -18,7 +18,7 @@ using std::endl; #define PROBABILITY 0.5 ///< current probability for "coin toss" -/** +/* * Node structure [Key][Node*, Node*...] */ struct Node { @@ -30,7 +30,7 @@ struct Node { Node(int key, int level, void* value); }; -/** +/* * Creates node with provided key, level and value */ Node::Node(int key, int level, void* value) { @@ -42,7 +42,7 @@ Node::Node(int key, int level, void* value) { } } -/** +/* * SkipList class */ class SkipList { @@ -59,7 +59,7 @@ public: }; -/** +/* * Skeep List constructor */ SkipList::SkipList() { @@ -83,7 +83,7 @@ SkipList::~SkipList(){ } -/** +/* * Returns random level for skip list; */ int SkipList::randomLevel() { @@ -94,7 +94,7 @@ int SkipList::randomLevel() { -/** +/* * Inserts elements with given key and value; * It's level is computed by randomLevel() function. */ @@ -135,7 +135,9 @@ void SkipList::insertElement(int key, void* value) { } } - /**Delete document by key*/ +/* + * Delete document by key +*/ void SkipList::deleteElement(int key) { Node *x = header; @@ -166,7 +168,7 @@ void SkipList::deleteElement(int key) } -/** +/* * Searching element in skip list structure */ void* SkipList::searchElement(int key) { @@ -187,7 +189,7 @@ void* SkipList::searchElement(int key) { } } -/** +/* * Display skip list level wise */ void SkipList::displayList() { @@ -204,7 +206,7 @@ void SkipList::displayList() { } -/** +/* * Main function: * Creates and inserts random 2^[number of levels] elements into the skip lists and than displays it */ From 662841bac7e69b6414ab09ed9871b63de7b6b65d Mon Sep 17 00:00:00 2001 From: enqidu Date: Tue, 7 Jul 2020 19:59:54 +0400 Subject: [PATCH 229/271] improve --- data_structures/skip_list.cpp | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index 25a9aae2a..729ce1d80 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -18,7 +18,7 @@ using std::endl; #define PROBABILITY 0.5 ///< current probability for "coin toss" -/* +/** * Node structure [Key][Node*, Node*...] */ struct Node { @@ -30,7 +30,7 @@ struct Node { Node(int key, int level, void* value); }; -/* +/** * Creates node with provided key, level and value */ Node::Node(int key, int level, void* value) { @@ -42,7 +42,7 @@ Node::Node(int key, int level, void* value) { } } -/* +/** * SkipList class */ class SkipList { @@ -59,7 +59,7 @@ public: }; -/* +/** * Skeep List constructor */ SkipList::SkipList() { @@ -68,7 +68,9 @@ SkipList::SkipList() { header = new Node(-1, MAX_LEVEL, nullptr); } - +/** + * Destructor for skiplist class +*/ SkipList::~SkipList(){ for(int i=0; i <= level; i++) { Node *node = header->forward[i]; @@ -83,7 +85,7 @@ SkipList::~SkipList(){ } -/* +/** * Returns random level for skip list; */ int SkipList::randomLevel() { @@ -94,7 +96,7 @@ int SkipList::randomLevel() { -/* +/** * Inserts elements with given key and value; * It's level is computed by randomLevel() function. */ @@ -135,7 +137,7 @@ void SkipList::insertElement(int key, void* value) { } } -/* +/** * Delete document by key */ void SkipList::deleteElement(int key) @@ -168,7 +170,7 @@ void SkipList::deleteElement(int key) } -/* +/** * Searching element in skip list structure */ void* SkipList::searchElement(int key) { @@ -206,7 +208,7 @@ void SkipList::displayList() { } -/* +/** * Main function: * Creates and inserts random 2^[number of levels] elements into the skip lists and than displays it */ From 45b21f287116aaffd52fe8b40a9d5104a5ab31e7 Mon Sep 17 00:00:00 2001 From: enqidu Date: Tue, 7 Jul 2020 20:29:37 +0400 Subject: [PATCH 230/271] improve --- data_structures/skip_list.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index 729ce1d80..1fc9f3e0e 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -1,4 +1,4 @@ -/* +/** * A skip list is a data structure that is used for storing a sorted list of items with a * help of hierarchy of linked lists that connect increasingly sparse subsequences of the items * From 8216a3267fb35d471b38b657c9e4aca7a819f5e6 Mon Sep 17 00:00:00 2001 From: sprintyaf Date: Tue, 7 Jul 2020 20:38:40 +0400 Subject: [PATCH 231/271] randomized tests, documentation, back to vector --- search/fibonacci_search.cpp | 161 ++++++++++++------------------------ 1 file changed, 54 insertions(+), 107 deletions(-) diff --git a/search/fibonacci_search.cpp b/search/fibonacci_search.cpp index f8525a6b4..e2796b0ba 100644 --- a/search/fibonacci_search.cpp +++ b/search/fibonacci_search.cpp @@ -1,6 +1,6 @@ /** * Copyright 2020 @author sprintyaf - * @file + * @file fibonacci_search.cpp * @brief [Fibonacci search * algorithm](https://en.wikipedia.org/wiki/Fibonacci_search_technique) */ @@ -8,27 +8,21 @@ #include #include // for std::vector class #include // for assert +#include // for random numbers +#include // for sorting /** - * Returns minimum of the two numbers + * @brief using fibonacci search algorithm finds an index of a given element in a sorted array + * + * @param arr sorted array + * @param value value that we're looking for + * @returns if the array contains the value, returns an index of the element. otherwise -1. */ -int min(int first, int second){ - if(first < second){ - return first; - } else { - return second; - } -} - -/** - * Input: a sorted array, a value we're looking for and size of the array - * Output: if the array contains the value, returns its index - * else returns -1 - */ -int fibonacci_search(int *arr, int value, int length){ +int fibonacci_search(const std::vector &arr, int value){ int last = 0, current = 1, offset = -1, index; + int length = arr.size(); int next = last + current; while(next < length){ @@ -38,7 +32,7 @@ int fibonacci_search(int *arr, int value, int length){ } while(next > 1){ - index = min(offset + last, length-1); + index = std::min(offset + last, length-1); if(arr[index] < value){ next = current; current = last; @@ -52,115 +46,68 @@ int fibonacci_search(int *arr, int value, int length){ return index; } } - if(current && (length > 0) && arr[offset+1] == value){ + if(current && !arr.empty() && arr[offset+1] == value){ return offset+1; } return -1; } /** - * Tests where given value occurs only once - */ -bool one_occurence_test(){ - // declarations - int value, index, length; + * @brief random tests for checking performance when an array doesn't contain an element +*/ +bool no_occurence_tests(){ bool passed = true; - // last element - length = 3; - int arr1[3] = {1, 2, 3}; - value = 3; - index = fibonacci_search(arr1, value, length); - passed = passed && (index == 2); - // first element - value = 1; - index = fibonacci_search(arr1, value, length); - passed = passed && (index == 0); - // somewhere in the middle element - length = 4; - int arr2[4] = {1, 3, 5, 7}; - value = 3; - index = fibonacci_search(arr2, value, length); - passed = passed && (index == 1); - // arr size is 1 - length = 1; - int arr3[1] = {10}; - value = 10; - index = fibonacci_search(arr3, value, length); - passed = passed && (index == 0); - + int rand_num, rand_value, index, num_tests = 1000; + std::vector arr; + while(num_tests--){ + arr.clear(); + for(int i = 0; i < 100; i++){ + rand_num = rand() % 1000; + arr.push_back(rand_num); + } + rand_value = rand() % 1000; + while(std::find(arr.begin(), arr.end(), rand_value) != arr.end()){ + std::remove(arr.begin(), arr.end(), rand_value); + } + sort(arr.begin(), arr.end()); + index = fibonacci_search(arr, rand_value); + passed = passed && (index == -1); + } return passed; } /** - * Tests where given value occurs more than once - */ -bool many_occurence_test(){ - // declarations - int value, index, length; + * @brief random tests which cover cases when we have one, multiple or zero occurences of the value we're looking for +*/ +bool random_tests(){ bool passed = true; - // last element - length = 4; - int arr1[4] = {1, 1, 10, 10}; - value = 10; - index = fibonacci_search(arr1, value, length); - passed = passed && (index == 2 || index == 3); - // first element - value = 1; - index = fibonacci_search(arr1, value, length); - passed = passed && (index == 0 || index == 1); - // somewhere in the middle element - length = 4; - int arr2[4] = {1, 3, 3, 7}; - value = 3; - index = fibonacci_search(arr2, value, length); - passed = passed && (index == 1 || index == 2); - // all elements are the same - length = 3; - int arr3[3] = {10, 10, 10}; - value = 10; - index = fibonacci_search(arr3, value, length); - passed = passed && (index >= 0 && index <= 2); - + int rand_num, rand_value, index, real_value, num_tests = 10000; + std::vector arr; + while(num_tests--){ + arr.clear(); + for(int i = 0; i < 100; i++){ + rand_num = rand() % 1000; + arr.push_back(rand_num); + } + rand_value = rand() % 1000; + sort(arr.begin(), arr.end()); + index = fibonacci_search(arr, rand_value); + if(index != -1){ + real_value = arr[index]; + passed = passed && (real_value == rand_value); + } else { + passed = passed && (std::find(arr.begin(), arr.end(), rand_value) == arr.end()); + } + } return passed; } -/** - * Tests where the array doesn't contain given value - */ -bool no_occurence_test(){ - // declarations - int value, index, length; - bool passed = true; - // many elements - length = 4; - int arr1[4] = {1, 2, 4, 5}; - value = 3; - index = fibonacci_search(arr1, value, length); - passed = passed && (index == -1); - // one element - length = 1; - int arr2[1] = {1}; - value = 2; - index = fibonacci_search(arr2, value, length); - passed = passed && (index == -1); - // empty array - length = 0; - int arr3[10] = {}; - value = 10; - index = fibonacci_search(arr3, value, length); - passed = passed && (index == -1); - - return passed; -} - - /** * Main Function * testing the algorithm */ int main() { - assert(one_occurence_test()); - assert(many_occurence_test()); - assert(no_occurence_test()); + assert(no_occurence_tests()); + assert(random_tests()); return 0; } From cf6b77a7dce59afb35cb62a8bb6bc780ad958ec5 Mon Sep 17 00:00:00 2001 From: sprintyaf Date: Tue, 7 Jul 2020 20:45:03 +0400 Subject: [PATCH 232/271] rand fixed --- search/fibonacci_search.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/search/fibonacci_search.cpp b/search/fibonacci_search.cpp index e2796b0ba..067d8e636 100644 --- a/search/fibonacci_search.cpp +++ b/search/fibonacci_search.cpp @@ -62,10 +62,10 @@ bool no_occurence_tests(){ while(num_tests--){ arr.clear(); for(int i = 0; i < 100; i++){ - rand_num = rand() % 1000; + rand_num = std::rand() % 1000; arr.push_back(rand_num); } - rand_value = rand() % 1000; + rand_value = std::rand() % 1000; while(std::find(arr.begin(), arr.end(), rand_value) != arr.end()){ std::remove(arr.begin(), arr.end(), rand_value); } @@ -86,11 +86,11 @@ bool random_tests(){ while(num_tests--){ arr.clear(); for(int i = 0; i < 100; i++){ - rand_num = rand() % 1000; + rand_num = std::rand() % 1000; arr.push_back(rand_num); } - rand_value = rand() % 1000; - sort(arr.begin(), arr.end()); + rand_value = std::rand() % 1000; + std::sort(arr.begin(), arr.end()); index = fibonacci_search(arr, rand_value); if(index != -1){ real_value = arr[index]; From 644524337a9112491b59d87df3890d276078007d Mon Sep 17 00:00:00 2001 From: sprintyaf Date: Tue, 7 Jul 2020 22:53:12 +0400 Subject: [PATCH 233/271] copyright removed --- search/fibonacci_search.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/search/fibonacci_search.cpp b/search/fibonacci_search.cpp index 067d8e636..dd1b06f11 100644 --- a/search/fibonacci_search.cpp +++ b/search/fibonacci_search.cpp @@ -1,5 +1,5 @@ /** - * Copyright 2020 @author sprintyaf + * @author sprintyaf * @file fibonacci_search.cpp * @brief [Fibonacci search * algorithm](https://en.wikipedia.org/wiki/Fibonacci_search_technique) From 0e9585d080b8789ead0886adcac318671175543f Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Wed, 8 Jul 2020 12:30:13 -0400 Subject: [PATCH 234/271] remove Copyright from docs --- data_structures/trie_modern.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data_structures/trie_modern.cpp b/data_structures/trie_modern.cpp index c2eba30e0..470af07a4 100644 --- a/data_structures/trie_modern.cpp +++ b/data_structures/trie_modern.cpp @@ -1,7 +1,7 @@ /** * @file * - * Copyright 2020 @author Anmol3299 + * @author Anmol3299 * \brief A basic implementation of trie class to store only lower-case strings. */ #include // for io operations From 59a8b3d4a295e7af34437151e0f50c973eb7e77d Mon Sep 17 00:00:00 2001 From: enqidu Date: Wed, 8 Jul 2020 20:43:52 +0400 Subject: [PATCH 235/271] Update data_structures/skip_list.cpp Co-authored-by: David Leal --- data_structures/skip_list.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index 1fc9f3e0e..62ae51ea9 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -210,7 +210,8 @@ void SkipList::displayList() { /** * Main function: - * Creates and inserts random 2^[number of levels] elements into the skip lists and than displays it + * Creates and inserts random 2^[number of levels] + * elements into the skip lists and than displays it */ int main() { From a5ca794aa4e27e6fb5d9c6e591449458ee5b8fe4 Mon Sep 17 00:00:00 2001 From: enqidu Date: Wed, 8 Jul 2020 20:46:50 +0400 Subject: [PATCH 236/271] sk --- data_structures/skip_list.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index 1fc9f3e0e..b7aab7882 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -10,7 +10,6 @@ #include #include -// using namespace std; using std::vector; using std::endl; @@ -23,9 +22,9 @@ using std::endl; */ struct Node { int key; - //pointer of value + // pointer of value void* value; - //Forward Array + // Forward Array vector forward; Node(int key, int level, void* value); }; From bba0db36ec5aa125fa4acdb35191e8348aaa670b Mon Sep 17 00:00:00 2001 From: enqidu Date: Wed, 8 Jul 2020 20:47:43 +0400 Subject: [PATCH 237/271] sk --- data_structures/skip_list.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index 3e13ee696..922c5a1e3 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -120,7 +120,7 @@ void SkipList::insertElement(int key, void* value) { if(rlevel > level) { for(int i=level+1;iforward[i] != x) break; update[i]->forward[i] = x->forward[i]; } - /*Remove empty levels*/ + /* Remove empty levels*/ while(level>0 && header->forward[level] == 0) level--; std::cout << "Deleted" << endl; } else { From 497d627ebde140b14dde08e25d98b7049886601d Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Thu, 9 Jul 2020 18:15:05 -0400 Subject: [PATCH 238/271] [improvement] updated contribution guidelines (#945) * updated contribution guidelines * fix case --- CONTRIBUTING.md | 87 +++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 77 insertions(+), 10 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9f0205bfd..35d875d43 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -28,8 +28,85 @@ We are very happy that you consider implementing algorithms and data structures - Strictly use snake_case (underscore_separated) in filenames. - If you have added or modified code, please make sure the code compiles before submitting. - Our automated testing runs [__cpplint__](https://github.com/cpplint/cpplint) on all pull requests so please be sure that your code passes before submitting. +- Please conform to [doxygen](https://www.doxygen.nl/manual/docblocks.html) standard and document the code as much as possible. This not only facilitates the readers but also generates the correct info on website. - **Be consistent in use of these guidelines.** +#### Documentation +- Make sure you put useful comments in your code. Do not comment things that are obvious. +- Please avoid creating new directories if at all possible. Try to fit your work into the existing directory structure. If you want to create a new directory, then please check if a similar category has been recently suggested or created by other pull requests. +- If you have modified/added documentation, please ensure that your language is concise and contains no grammar errors. +- Do not update README.md along with other changes, first create an issue and then link to that issue in your pull request to suggest specific changes required to README.md +- The repository follows [Doxygen](https://www.doxygen.nl/manual/docblocks.html) standards and auto-generates the [repo website](https://thealgorithms.github.io/C-Plus-Plus). Please ensure the code is documented in this structure. Sample implementation is given below. + +#### Test +- Make sure to add examples and test cases in your main() function. +- If you find any algorithm or document without tests, please feel free to create a pull request or issue describing suggested changes. +- Please try to add one or more `test()` functions that will invoke the algorithm implementation on random test data with expected output. Use `assert()` function to confirm that the tests will pass. + +#### Typical structure of a program: +```cpp +/** + * @file + * @brief Add one line description here + * @details + * This is a multi line + * description containing links, references, + * math equations, etc + * @author [Name](https://github.com/handle) + * @see related_file.cpp, another_file.cpp + */ + +#include + +/** + * @namespace + */ +namespace name { + +/** + * Class documentation + */ +class cls_name{ + private: + int var1; ///< short info of this variable + char *msg; ///< short info + + public: + // other members also documented as below +} + +/** + * Function documentation + * @tparam T this is a one-line info about T + * @param param1 on-line info about param1 + * @param param2 on-line info about param2 + * @returns `true` if ... + * @returns `false` if ... + */ +template +bool func(int param1, T param2) { + // function statements here + if(/*something bad*/) + return false; + + return true; +} + +/** Test function */ +void test() { + /* some statements */ + assert(func(...) == ...); // this ensures that the algorithm works as expected + + // can have multiple checks +} + +/** Main function */ +int main(int argc, char *argv[]) { + // code here + return 0; +} +``` + #### New File Name guidelines - Use lowercase words with ``"_"`` as separator - For instance @@ -70,16 +147,6 @@ Common prefixes: - docs: Documentation changes - test: Correct existing tests or add new ones -#### Documentation -- Make sure you put useful comments in your code. Do not comment things that are obvious. -- Please avoid creating new directories if at all possible. Try to fit your work into the existing directory structure. If you want to create a new directory, then please check if a similar category has been recently suggested or created by other pull requests. -- If you have modified/added documentation, please ensure that your language is concise and contains no grammar errors. -- Do not update README.md along with other changes, first create an issue and then link to that issue in your pull request to suggest specific changes required to README.md - -#### Test -- Make sure to add examples and test cases in your main() function. -- If you find any algorithm or document without tests, please feel free to create a pull request or issue describing suggested changes. - ### Pull Requests - Checkout our [pull request template](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/.github/pull_request_template.md) From bf2dac6de238cabf81092ca76176c91596771543 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 10 Jul 2020 10:43:05 -0400 Subject: [PATCH 239/271] enable gitpod for all branches --- .gitpod.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitpod.yml b/.gitpod.yml index 40750258c..ece107997 100644 --- a/.gitpod.yml +++ b/.gitpod.yml @@ -7,6 +7,7 @@ github: addComment: false addCheck: false master: true + branches: true pullRequestsFromForks: true vscode: From ebd13a7e241df3a3963f6fc728bd37c826291927 Mon Sep 17 00:00:00 2001 From: Rajiv Ranjan Singh Date: Fri, 10 Jul 2020 20:32:59 +0530 Subject: [PATCH 240/271] Improved sieve_of_eratosthenes.cpp (#933) * Update sieve_of_eratosthenes.cpp * removed unwanted spaces * removed init function Co-authored-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- math/sieve_of_eratosthenes.cpp | 49 +++++++++++++++------------------- 1 file changed, 21 insertions(+), 28 deletions(-) diff --git a/math/sieve_of_eratosthenes.cpp b/math/sieve_of_eratosthenes.cpp index d8fa70531..e30bc1891 100644 --- a/math/sieve_of_eratosthenes.cpp +++ b/math/sieve_of_eratosthenes.cpp @@ -10,25 +10,21 @@ * @see primes_up_to_billion.cpp prime_numbers.cpp */ -#include - -/** Maximum number of primes */ -#define MAX 10000000 - -/** array to store the primes */ -bool isprime[MAX]; +#include // for io operations /** * This is the function that finds the primes and eliminates * the multiples. + * @param N number of primes to check + * @param [out] isprime a boolean array of size `N` identifying if `i`^th number is prime or not */ -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; +void sieve(uint32_t N, bool *isprime) { + isprime[0] = true; + isprime[1] = true; + for (uint32_t i = 2; i * i <= N; i++) { + if (!isprime[i]) { + for (uint32_t j = (i << 1); j <= N; j = j + i) { + isprime[j] = true; } } } @@ -36,10 +32,12 @@ void sieve(uint32_t N) { /** * This function prints out the primes to STDOUT + * @param N number of primes to check + * @param [in] isprime a boolean array of size `N` identifying if `i`^th number is prime or not */ -void print(uint32_t N) { - for (uint32_t i = 1; i <= N; i++) { - if (isprime[i]) { +void print(uint32_t N, const bool *isprime) { + for (uint32_t i = 2; i <= N; i++) { + if (!isprime[i]) { std::cout << i << ' '; } } @@ -47,19 +45,14 @@ void print(uint32_t N) { } /** - * Initialize the array + * Main function */ -void init() { - for (uint32_t i = 1; i < MAX; i++) { - isprime[i] = true; - } -} - -/** main function */ int main() { uint32_t N = 100; - init(); - sieve(N); - print(N); + bool *isprime = new bool[N]; + sieve(N, isprime); + print(N, isprime); + delete[] isprime; + return 0; } From 58099884dd626ba94602fa00351d8e6c5f49c9e9 Mon Sep 17 00:00:00 2001 From: sprintyaf Date: Fri, 10 Jul 2020 19:13:16 +0400 Subject: [PATCH 241/271] comments added --- search/fibonacci_search.cpp | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/search/fibonacci_search.cpp b/search/fibonacci_search.cpp index dd1b06f11..be181a47d 100644 --- a/search/fibonacci_search.cpp +++ b/search/fibonacci_search.cpp @@ -21,34 +21,48 @@ * @returns if the array contains the value, returns an index of the element. otherwise -1. */ int fibonacci_search(const std::vector &arr, int value){ - int last = 0, current = 1, offset = -1, index; - int length = arr.size(); - int next = last + current; + // initialize last and current members of Fibonacci sequence + int last = 0, current = 1; + int length = arr.size(); // array size + // next member of Fibonacci sequence which is "last" + "current" + int next = last + current; + // "next" will store the smallest Fibonacci number greater or equal to "length" while(next < length){ last = current; current = next; next = last + current; } + // "offset" is the end of eliminated range from front + int offset = -1, index; + // while loop until there are elements left to consider. + // when "next" becomes 1, last is equal to 0, so search is done, + // because arr[offset] will already be eliminated while(next > 1){ + // check if "last" is valid location index = std::min(offset + last, length-1); + // if value is greater than the value at "index", eliminate the subarray from offset to index if(arr[index] < value){ next = current; current = last; last = next - current; offset = index; + // if value is less than the value at "index", eliminate the subarray after index+1 } else if(arr[index] > value){ next = last; current = current - last; last = next - current; + // element is found } else { return index; } } + // comparing the last element if(current && !arr.empty() && arr[offset+1] == value){ return offset+1; } + // value was not found, return -1 return -1; } From 02d947777befbf0ed7a3d3f85e7474579cf01cf0 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 10 Jul 2020 11:32:37 -0400 Subject: [PATCH 242/271] [enhancement] Replace cpplint with clang-tidy (#943) * test commit for using clang-tidy instead of cpplint * add suffix -- to clang-tidy & commit * fixes to git commit * commenting redundant clang-format as clang-tidy will take care of that * add clang-tidy config file * use clang-tidy config file * test dump config to ensure config is read correctly * move test to top * test passed, removing test code Test link: https://github.com/TheAlgorithms/C-Plus-Plus/pull/943/checks?check_run_id=851231578 * fix clang-tidy config * set clang-tidy standard to c++11 * provide clang-tidy with compilation details * fix build path argument & Use clang-9 (cherry picked from commit 5eddf0cd9536f328a6a3485b5ed59705618a1433) * Merge commit '433568f9fa7c3e7f1b2e0c86c1864e92ad2668c8' * Use clang-9 * fix subprocess.STDOUT * remove pipe for stdout * bumot o clang-tidy-10 * Revert "Merge commit '433568f9fa7c3e7f1b2e0c86c1864e92ad2668c8'" This reverts commit 2a7462056a58fc9f5eda1ab8e723df2f28f34c2c. * add docs --- .clang-tidy | 6 ++++ .github/workflows/awesome_workflow.yml | 46 +++++++++++--------------- 2 files changed, 25 insertions(+), 27 deletions(-) create mode 100644 .clang-tidy diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 000000000..02bb3916f --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,6 @@ +--- +Checks: '-*,google-*,cppcoreguidelines-*,-cppcoreguidelines-avoid-magic-numbers,-cppcoreguidelines-pro-bounds-*,openmp-*,performance-*,portability-*,modernize-*,-modernize-use-trailing-*' +WarningsAsErrors: '' +HeaderFilterRegex: '' +AnalyzeTemporaryDtors: false +FormatStyle: '{ BasedOnStyle: Google, UseTab: Never, IndentWidth: 4, TabWidth: 4, AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: true, ColumnLimit: 80, AccessModifierOffset: -3, AlignConsecutiveMacros: true }' diff --git a/.github/workflows/awesome_workflow.yml b/.github/workflows/awesome_workflow.yml index f8feb1d3e..2e0792e17 100644 --- a/.github/workflows/awesome_workflow.yml +++ b/.github/workflows/awesome_workflow.yml @@ -16,7 +16,9 @@ jobs: - name: requirements run: | sudo apt -qq -y update - sudo apt -qq install clang-format + sudo apt -qq install clang-tidy-10 + # checks are passing with less errors when used with this version. + # The default installs v6.0 which did not work out well in my tests - name: Setup Git Specs run: | git config --global user.name github-actions @@ -43,18 +45,6 @@ jobs: fi 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, " - line3: "AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: false," - line4: "ColumnLimit: 80, AccessModifierOffset: -3 }" - name: Update DIRECTORY.md shell: python @@ -100,24 +90,21 @@ jobs: with open("DIRECTORY.md", "w") as out_file: out_file.write(build_directory_md(".") + "\n") - - name: Update DIRECTORY.md + - name: Commit DIRECTORY.md + run: git commit -m "updating DIRECTORY.md" DIRECTORY.md || true + - name: Get file changes 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 - - name: Install CPPLINT - run: | - python -m pip install cpplint git remote -v git branch git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY git diff --diff-filter=dr --name-only origin/master > git_diff.txt echo "Files changed-- `cat git_diff.txt`" - - name: cpplint_modified_files + - name: Configure for static lint checks + # compiling first gives clang-tidy access to all the header files and settings used to compile the programs. + # This will check for macros, if any, on linux and not for Windows. But the use of portability checks should + # be able to catch any errors for other platforms. + run: cmake -B build -S . -DCMAKE_EXPORT_COMPILE_COMMANDS=ON + - name: Lint modified files shell: python run: | import os @@ -135,9 +122,9 @@ jobs: if not cpp_files: sys.exit(0) - print("cpplint:") for cpp_file in cpp_files: - subprocess.run(["cpplint", "--filter=-legal/copyright,-build/include", cpp_file], check=True, text=True) + subprocess.run(["clang-tidy-10", "--fix", "-p=build", cpp_file, "--"], + check=True, text=True, stderr=subprocess.STDOUT) # print("g++:") # compile_exts = tuple(".c .c++ .cc .cpp .cu .cxx".split()) @@ -163,6 +150,11 @@ jobs: bad_files = len(upper_files + space_files + nodir_files) if bad_files: sys.exit(bad_files) + - name: Commit and push changes + run: | + git diff DIRECTORY.md + git commit -am "clang-tidy fixes for $GITHUB_SHA" || true + git push --force origin HEAD:$GITHUB_REF || true build: name: Compile checks From ab1ddb364f3116e08bd52f6424f5cfbaca484157 Mon Sep 17 00:00:00 2001 From: enqidu Date: Fri, 10 Jul 2020 20:39:33 +0400 Subject: [PATCH 243/271] documentation --- data_structures/skip_list.cpp | 34 ++++++++++++++++++++++++---------- 1 file changed, 24 insertions(+), 10 deletions(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index 922c5a1e3..dc9b06776 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -13,8 +13,8 @@ using std::vector; using std::endl; -#define MAX_LEVEL 2 ///< maximum level of skip list -#define PROBABILITY 0.5 ///< current probability for "coin toss" +#define MAX_LEVEL 2 ///< Maximum level of skip list +#define PROBABILITY 0.5 ///< Current probability for "coin toss" /** @@ -24,13 +24,18 @@ struct Node { int key; // pointer of value void* value; - // Forward Array + // Forward Array points to the neighbour (right) + // nodes of the given one in all levels vector forward; + // Constructor of the node Node(int key, int level, void* value); }; /** * Creates node with provided key, level and value + * @param key is number that is used for comparision + * @param level is the maximum level node's going to added + * */ Node::Node(int key, int level, void* value) { this->key = key; @@ -42,10 +47,12 @@ Node::Node(int key, int level, void* value) { } /** - * SkipList class + * SkipList class implementation with basic methods */ class SkipList { + // Maximum level of the skiplist int level; + // Pointer to the header node Node *header; public: SkipList(); @@ -59,7 +66,8 @@ public: /** - * Skeep List constructor + * Skeep List constructor. Initializes header, start + * Node for searching in the list */ SkipList::SkipList() { level = 0; @@ -85,7 +93,9 @@ SkipList::~SkipList(){ /** - * Returns random level for skip list; + * Returns random level of the skip list. + * Every higher level is 2 times less likely. + * @return lvl: random level for skip list; */ int SkipList::randomLevel() { int lvl = 0; @@ -98,6 +108,8 @@ int SkipList::randomLevel() { /** * Inserts elements with given key and value; * It's level is computed by randomLevel() function. + * @param key is number that is used for comparision + * @param value pointer to a value, that can be any type */ void SkipList::insertElement(int key, void* value) { std::cout << "Inserting" << key << "..."; @@ -137,10 +149,10 @@ void SkipList::insertElement(int key, void* value) { } /** - * Delete document by key + * Deletes an element by key and prints if has been removed successfully + * @param key is number that is used for comparision. */ -void SkipList::deleteElement(int key) -{ +void SkipList::deleteElement(int key) { Node *x = header; Node *update[MAX_LEVEL+1]; @@ -171,6 +183,8 @@ void SkipList::deleteElement(int key) /** * Searching element in skip list structure + * @param key is number that is used for comparision + * @return pointer to the value of the node */ void* SkipList::searchElement(int key) { Node *x = header; @@ -191,7 +205,7 @@ void* SkipList::searchElement(int key) { } /* - * Display skip list level wise + * Display skip list level */ void SkipList::displayList() { std::cout << "Displaying list:\n" << endl; From d59005678d7b2f294df26c088842ab3e44f85f31 Mon Sep 17 00:00:00 2001 From: enqidu Date: Fri, 10 Jul 2020 20:40:00 +0400 Subject: [PATCH 244/271] documentation --- data_structures/skip_list.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index dc9b06776..80717050a 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -35,7 +35,6 @@ struct Node { * Creates node with provided key, level and value * @param key is number that is used for comparision * @param level is the maximum level node's going to added - * */ Node::Node(int key, int level, void* value) { this->key = key; From 05bb23ca27046c7bb4954d1317ea8108b4c2cd9d Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 10 Jul 2020 12:47:37 -0400 Subject: [PATCH 245/271] [enhancement] New Graphics implementation with algorithm for spirograph (#936) * added spirograph program * add graphics forlder to cmake * updating DIRECTORY.md * enable VNC for GUI programs on gitpod * fix cpplint error * fix macro definitions for correct documentation * fix filename in docs * move include from namespace to global * download and build freeglut if not available * install opengl libraries for build check * fix syntax error * fix quotes * install mesa-utils instead * use markepplace tool instead of installing * fix syntax * undo changes to github actions * OpenGL not mandatory * add private option to compile definition * fix: corrected to compile definitions instead of options * use the macro USE_GLUT * compile FREEGLUT as a subdirectory. this maintains a consistency * build freeglut_static when GLUT library not available * provide keyboard control * clang-tidy fixes for cb284bddb2a361370d08fe6926036947236bd4c5 Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> --- .gitpod.dockerfile | 14 +- CMakeLists.txt | 51 ++++---- DIRECTORY.md | 3 + graphics/CMakeLists.txt | 83 ++++++++++++ graphics/spirograph.cpp | 284 ++++++++++++++++++++++++++++++++++++++++ 5 files changed, 406 insertions(+), 29 deletions(-) create mode 100644 graphics/CMakeLists.txt create mode 100644 graphics/spirograph.cpp diff --git a/.gitpod.dockerfile b/.gitpod.dockerfile index 6d6a4e895..53d336f81 100644 --- a/.gitpod.dockerfile +++ b/.gitpod.dockerfile @@ -1,9 +1,9 @@ -FROM gitpod/workspace-full +FROM gitpod/workspace-full-vnc RUN sudo apt-get update \ - && sudo apt-get install -y \ - doxygen \ - graphviz \ - ninja-build \ - && pip install cpplint \ - && sudo rm -rf /var/lib/apt/lists/* + && sudo apt-get install -y \ + doxygen \ + graphviz \ + ninja-build \ + && pip install cpplint \ + && sudo rm -rf /var/lib/apt/lists/* diff --git a/CMakeLists.txt b/CMakeLists.txt index 712c3db42..d7fa88559 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -17,7 +17,28 @@ if(MSVC) endif(MSVC) option(USE_OPENMP "flag to use OpenMP for multithreading" ON) - +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) +add_subdirectory(ciphers) +add_subdirectory(strings) +add_subdirectory(sorting) +add_subdirectory(geometry) +add_subdirectory(graphics) +add_subdirectory(probability) +add_subdirectory(data_structures) +add_subdirectory(machine_learning) +add_subdirectory(numerical_methods) + cmake_policy(SET CMP0054 NEW) cmake_policy(SET CMP0057 NEW) find_package(Doxygen OPTIONAL_COMPONENTS dot dia) @@ -34,6 +55,7 @@ if(DOXYGEN_FOUND) set(DOXYGEN_STRIP_CODE_COMMENTS NO) set(DOXYGEN_EXT_LINKS_IN_WINDOW YES) set(DOXYGEN_BUILTIN_STL_SUPPORT YES) + set(DOXYGEN_ENABLE_PREPROCESSING YES) set(DOXYGEN_CLANG_ASSISTED_PARSING YES) set(DOXYGEN_FILE_PATTERNS *.cpp *.h *.hpp *.md) set(DOXYGEN_MATHJAX_EXTENSIONS TeX/AMSmath TeX/AMSsymbols) @@ -48,6 +70,12 @@ if(DOXYGEN_FOUND) set(DOXYGEN_INTERACTIVE_SVG YES) set(DOXYGEN_DOT_IMAGE_FORMAT "svg") endif() + if(OPENMP_FOUND) + set(DOXYGEN_PREDEFINED "_OPENMP=1") + endif() + if(GLUT_FOUND) + set(DOXYGEN_PREDEFINED ${DOXYGEN_PREDEFINED} "GLUT_FOUND=1") + endif() doxygen_add_docs( doc @@ -56,27 +84,6 @@ 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) -add_subdirectory(ciphers) -add_subdirectory(strings) -add_subdirectory(sorting) -add_subdirectory(geometry) -add_subdirectory(probability) -add_subdirectory(data_structures) -add_subdirectory(machine_learning) -add_subdirectory(numerical_methods) - set(CPACK_PROJECT_NAME ${PROJECT_NAME}) set(CPACK_PROJECT_VERSION ${PROJECT_VERSION}) include(CPack) diff --git a/DIRECTORY.md b/DIRECTORY.md index f53d2f7ab..0f7e9a053 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -84,6 +84,9 @@ * [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) +## Graphics + * [Spirograph](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graphics/spirograph.cpp) + ## Greedy Algorithms * [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) diff --git a/graphics/CMakeLists.txt b/graphics/CMakeLists.txt new file mode 100644 index 000000000..2ea6ca230 --- /dev/null +++ b/graphics/CMakeLists.txt @@ -0,0 +1,83 @@ +find_package(OpenGL) +if(OpenGL_FOUND) + find_package(GLUT) + if(NOT GLUT_FOUND) + message("FreeGLUT library will be downloaded and built.") + include(ExternalProject) + ExternalProject_Add ( + FREEGLUT-PRJ + URL https://sourceforge.net/projects/freeglut/files/freeglut/3.2.1/freeglut-3.2.1.tar.gz + URL_MD5 cd5c670c1086358598a6d4a9d166949d + CMAKE_GENERATOR ${CMAKE_GENERATOR} + CMAKE_GENERATOR_TOOLSET ${CMAKE_GENERATOR_TOOLSET} + CMAKE_GENERATOR_PLATFORM ${CMAKE_GENERATOR_PLATFORM} + CMAKE_ARGS -DCMAKE_BUILD_TYPE=Release + -DFREEGLUT_BUILD_SHARED_LIBS=OFF + -DFREEGLUT_BUILD_STATIC_LIBS=ON + -DFREEGLUT_BUILD_DEMOS=OFF + PREFIX ${CMAKE_CURRENT_BINARY_DIR}/freeglut + # BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}/freeglut-build + # BUILD_IN_SOURCE ON + # UPDATE_COMMAND "" + INSTALL_COMMAND "" + # CONFIGURE_COMMAND "" + # BUILD_COMMAND "" + ) + ExternalProject_Get_Property(FREEGLUT-PRJ SOURCE_DIR) + ExternalProject_Get_Property(FREEGLUT-PRJ BINARY_DIR) + set(FREEGLUT_BIN_DIR ${BINARY_DIR}) + set(FREEGLUT_SRC_DIR ${SOURCE_DIR}) + # add_library(libfreeglut STATIC IMPORTED) + # set_target_properties(libfreeglut PROPERTIES IMPORTED_LOCATION ${FREEGLUT_BIN_DIR}) + + # set(FREEGLUT_BUILD_DEMOS OFF CACHE BOOL "") + # set(FREEGLUT_BUILD_SHARED_LIBS OFF CACHE BOOL "") + # set(FREEGLUT_BUILD_STATIC_LIBS ON CACHE BOOL "") + # add_subdirectory(${FREEGLUT_SRC_DIR} ${FREEGLUT_BIN_DIR} EXCLUDE_FROM_ALL) + # add_subdirectory(${BINARY_DIR}) + # find_package(FreeGLUT) + endif(NOT GLUT_FOUND) +else(OpenGL_FOUND) + message(WARNING "OPENGL not found. Will not build graphical outputs.") +endif(OpenGL_FOUND) + +# 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} PRIVATE OpenMP::OpenMP_CXX) + endif() + + if(OpenGL_FOUND) + if(NOT GLUT_FOUND) + add_dependencies(${testname} FREEGLUT-PRJ) + target_compile_definitions(${testname} PRIVATE FREEGLUT_STATIC) + target_include_directories(${testname} PRIVATE ${FREEGLUT_SRC_DIR}/include) + target_link_directories(${testname} PRIVATE ${FREEGLUT_BIN_DIR}/lib) + target_link_libraries(${testname} PRIVATE OpenGL::GL) + target_link_libraries(${testname} INTERFACE FREEGLUT-PRJ) + # target_include_directories(${testname} PRIVATE ${FREEGLUT_INCLUDE_DIRS}) + # target_link_libraries(${testname} INTERFACE freeglut_static) + else() + target_include_directories(${testname} PRIVATE ${GLUT_INCLUDE_DIRS}) + target_link_libraries(${testname} PRIVATE OpenGL::GL ${GLUT_LIBRARIES}) + endif() + target_compile_definitions(${testname} PRIVATE USE_GLUT) + endif(OpenGL_FOUND) + + if(APPLE) + target_compile_options(${testname} PRIVATE -Wno-deprecated) + endif(APPLE) + + install(TARGETS ${testname} DESTINATION "bin/graphics") + +endforeach( testsourcefile ${APP_SOURCES} ) diff --git a/graphics/spirograph.cpp b/graphics/spirograph.cpp new file mode 100644 index 000000000..84c17c4db --- /dev/null +++ b/graphics/spirograph.cpp @@ -0,0 +1,284 @@ +/** + * @file + * @author [Krishna Vedala](https://github.com/kvedala) + * @brief Implementation of + * [Spirograph](https://en.wikipedia.org/wiki/Spirograph) + * + * @details + * Implementation of the program is based on the geometry shown in the figure + * below: + * + * Spirograph geometry from Wikipedia + */ +#ifdef USE_GLUT +#ifdef __APPLE__ +#include // include path on Macs is different +#else +#include +#endif // __APPLE__ +#endif +#define _USE_MATH_DEFINES /**< required for MSVC compiler */ +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _OPENMP +#include +#endif + +/** + * @namespace spirograph Functions related to spirograph.cpp + */ +namespace spirograph { +/** Generate spirograph curve into arrays `x` and `y` such that the i^th point + * in 2D is represented by `(x[i],y[i])`. The generating function is given by: + * \f{eqnarray*}{ + * x &=& R\left[ (1-k) \cos (t) + l\cdot k\cdot\cos \left(\frac{1-k}{k}t\right) + * \right]\\ + * y &=& R\left[ (1-k) \sin (t) - l\cdot k\cdot\sin \left(\frac{1-k}{k}t\right) + * \right] \f} + * where + * * \f$R\f$ is the scaling parameter that we will consider \f$=1\f$ + * * \f$l=\frac{\rho}{r}\f$ is the relative distance of marker from the centre + * of inner circle and \f$0\le l\le1\f$ + * * \f$\rho\f$ is physical distance of marker from centre of inner circle + * * \f$r\f$ is the radius of inner circle + * * \f$k=\frac{r}{R}\f$ is the ratio of radius of inner circle to outer circle + * and \f$0 +void spirograph(std::array, N> *points, double l, + double k, double rot) { + double dt = rot * 2.f * M_PI / N; + double R = 1.f; + const double k1 = 1.f - k; + int32_t step = 0; + +#ifdef _OPENMP +#pragma omp for +#endif + for (step = 0; step < N; step++) { + double t = dt * step; + double first = R * (k1 * std::cos(t) + l * k * std::cos(k1 * t / k)); + double second = R * (k1 * std::sin(t) - l * k * std::sin(k1 * t / k)); + points[0][step].first = first; + points[0][step].second = second; + } +} + +/** + * @brief Test function to save resulting points to a CSV file. + * + */ +void test() { + const size_t N = 500; + double l = 0.3, k = 0.75, rot = 10.; + std::stringstream fname; + fname << std::setw(3) << "spirograph_" << l << "_" << k << "_" << rot + << ".csv"; + std::ofstream fp(fname.str()); + if (!fp.is_open()) { + perror(fname.str().c_str()); + exit(EXIT_FAILURE); + } + + std::array, N> points; + + spirograph(&points, l, k, rot); + + for (size_t i = 0; i < N; i++) { + fp << points[i].first << "," << points[i].first; + if (i < N - 1) { + fp << '\n'; + } + } + + fp.close(); +} + +#ifdef USE_GLUT +static bool paused = 0; /**< flag to set pause/unpause animation */ +static const int animation_speed = 25; /**< animation delate in ms */ + +static const double step = 0.01; /**< animation step size */ +static double l_ratio = step * 10; /**< the l-ratio defined in docs */ +static double k_ratio = step; /**< the k-ratio defined in docs */ +static const double num_rot = 20.; /**< number of rotations to simulate */ + +/** A wrapper that is not available in all GLUT implementations. + */ +static inline void glutBitmapString(void *font, char *message) { + for (char *ch = message; *ch != '\0'; ch++) glutBitmapCharacter(font, *ch); +} + +/** + * @brief Function to graph (x,y) points on the OpenGL graphics window. + * + * @tparam N number of points = size of array + * @param [in] points Array of 2D points represented as std::pair + * @param l the relative distance of marker from the centre of + * inner circle and \f$0\le l\le1\f$ to display info + * @param k the ratio of radius of inner circle to outer circle and \f$0 +void display_graph(const std::array, N> &points, + double l, double k) { + glClearColor(1.0f, 1.0f, 1.0f, + 0.0f); // Set background color to white and opaque + glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer (background) + + glBegin(GL_LINES); // draw line segments + glColor3f(0.f, 0.f, 1.f); // blue + glPointSize(2.f); // point size in pixels + + for (size_t i = 1; i < N; i++) { + glVertex2f(points[i - 1].first, points[i - 1].second); // line from + glVertex2f(points[i].first, points[i].second); // line to + } + glEnd(); + + glColor3f(0.f, 0.f, 0.f); + std::stringstream buffer; + buffer << std::setw(3) << "l = " << l; + glRasterPos2f(-.85, .85); + glutBitmapString(GLUT_BITMAP_TIMES_ROMAN_24, + const_cast(buffer.str().c_str())); + buffer.str(""); + buffer.clear(); + buffer << std::setw(3) << "k = " << k; + glRasterPos2f(-.85, .70); + glutBitmapString(GLUT_BITMAP_TIMES_ROMAN_24, + const_cast(buffer.str().c_str())); + + glutSwapBuffers(); +} + +/** + * @brief Test function with animation + * + */ +void test2() { + const size_t N = 5000; // number of samples + + static bool direction1 = true; // increment if true, otherwise decrement + static bool direction2 = true; // increment if true, otherwise decrement + + std::array, N> points; + + spirograph(&points, l_ratio, k_ratio, num_rot); + display_graph(points, l_ratio, k_ratio); + + if (paused) + // if paused, do not update l_ratio and k_ratio + return; + + if (direction1) { // increment k_ratio + if (k_ratio >= (1.f - step)) // maximum limit + direction1 = false; // reverse direction of k_ratio + else + k_ratio += step; + } else { // decrement k_ratio + if (k_ratio <= step) { // minimum limit + direction1 = true; // reverse direction of k_ratio + + if (direction2) { // increment l_ratio + if (l_ratio >= (1.f - step)) // max limit of l_ratio + direction2 = false; // reverse direction of l_ratio + else + l_ratio += step; + } else { // decrement l_ratio + if (l_ratio <= step) // minimum limit of l_ratio + direction2 = true; // reverse direction of l_ratio + else + l_ratio -= step; + } + } else { // no min limit of k_ratio + k_ratio -= step; + } + } +} + +/** + * @brief GLUT timer callback function to add animation delay. + */ +void timer_cb(int t) { + glutTimerFunc(animation_speed, timer_cb, 0); + glutPostRedisplay(); +} + +/** + * @brief Keypress event call back function. + * + * @param key ID of the key pressed + * @param x mouse pointer position at event + * @param y mouse pointer position at event + */ +void keyboard_cb(unsigned char key, int x, int y) { + switch (key) { + case ' ': // spacebar toggles pause + paused = !paused; // toggle + break; + case GLUT_KEY_UP: + case '+': // up arrow key + k_ratio += step; + break; + case GLUT_KEY_DOWN: + case '_': // down arrow key + k_ratio -= step; + break; + case GLUT_KEY_RIGHT: + case '=': // left arrow key + l_ratio += step; + break; + case GLUT_KEY_LEFT: + case '-': // right arrow key + l_ratio -= step; + break; + case 0x1B: // escape key exits + exit(EXIT_SUCCESS); + default: + return; + } +} +#endif +} // namespace spirograph + +/** Main function */ +int main(int argc, char **argv) { + spirograph::test(); + +#ifdef USE_GLUT + glutInit(&argc, argv); + glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE); + glutCreateWindow("Spirograph"); + glutInitWindowSize(400, 400); + // glutIdleFunc(glutPostRedisplay); + glutTimerFunc(spirograph::animation_speed, spirograph::timer_cb, 0); + glutKeyboardFunc(spirograph::keyboard_cb); + glutDisplayFunc(spirograph::test2); + glutMainLoop(); +#endif + + return 0; +} From a90dcc5f66126049e91e0fa3835a55f6afb7d9fe Mon Sep 17 00:00:00 2001 From: enqidu Date: Fri, 10 Jul 2020 21:10:21 +0400 Subject: [PATCH 246/271] parameters --- data_structures/skip_list.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index 80717050a..37839dfdb 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -1,8 +1,12 @@ /** + * @file skip_list.cpp + * @brief data struccture for fast searching and insertion (O(log(n))) + * @details * A skip list is a data structure that is used for storing a sorted list of items with a - * help of hierarchy of linked lists that connect increasingly sparse subsequences of the items + * help of hierarchy of linked lists that connect increasingly sparse subsequences of the items * - * References used: GeeksForGeeks skip list code, https://iq.opengenus.org/skip-list/ Code and PseudoCode. + * References used: GeeksForGeeks skip list code, https://iq.opengenus.org/skip-list/ PseudoCode and Code + * . */ #include From 2fecf67a365b9329036d623467dde998903ead98 Mon Sep 17 00:00:00 2001 From: enqidu Date: Fri, 10 Jul 2020 21:11:20 +0400 Subject: [PATCH 247/271] parameters --- data_structures/skip_list.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index 37839dfdb..6159506a0 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -6,6 +6,7 @@ * help of hierarchy of linked lists that connect increasingly sparse subsequences of the items * * References used: GeeksForGeeks skip list code, https://iq.opengenus.org/skip-list/ PseudoCode and Code + * @author enqidu * . */ From b1b3b310a403398d279cbe6c619d109068fe11e1 Mon Sep 17 00:00:00 2001 From: enqidu Date: Fri, 10 Jul 2020 21:27:22 +0400 Subject: [PATCH 248/271] Update data_structures/skip_list.cpp Co-authored-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- data_structures/skip_list.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index 6159506a0..515c6d138 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -5,7 +5,7 @@ * A skip list is a data structure that is used for storing a sorted list of items with a * help of hierarchy of linked lists that connect increasingly sparse subsequences of the items * - * References used: GeeksForGeeks skip list code, https://iq.opengenus.org/skip-list/ PseudoCode and Code + * References used: [GeeksForGeek](https://www.geeksforgeeks.org/skip-list/), [OpenGenus](https://iq.opengenus.org/skip-list) for PseudoCode and Code * @author enqidu * . */ From 5d225aba874d4b74021c1865f62148517a869f30 Mon Sep 17 00:00:00 2001 From: enqidu Date: Fri, 10 Jul 2020 21:27:35 +0400 Subject: [PATCH 249/271] Update data_structures/skip_list.cpp Co-authored-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- data_structures/skip_list.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index 515c6d138..cefd23403 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -6,7 +6,7 @@ * help of hierarchy of linked lists that connect increasingly sparse subsequences of the items * * References used: [GeeksForGeek](https://www.geeksforgeeks.org/skip-list/), [OpenGenus](https://iq.opengenus.org/skip-list) for PseudoCode and Code - * @author enqidu + * @author [enqidu](https://github.com/enqidu) * . */ From af49a02ed85b944d88c13393c0ecd2cd30f5a0d7 Mon Sep 17 00:00:00 2001 From: enqidu Date: Fri, 10 Jul 2020 21:27:51 +0400 Subject: [PATCH 250/271] Update data_structures/skip_list.cpp Co-authored-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> --- data_structures/skip_list.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index cefd23403..6e6d78e13 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -1,6 +1,6 @@ /** * @file skip_list.cpp - * @brief data struccture for fast searching and insertion (O(log(n))) + * @brief Data structure for fast searching and insertion in \f$O(\log n)\f$ time * @details * A skip list is a data structure that is used for storing a sorted list of items with a * help of hierarchy of linked lists that connect increasingly sparse subsequences of the items From 5fcf15019e3873bf11386193748388e28c30b684 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 10 Jul 2020 16:41:13 -0400 Subject: [PATCH 251/271] added clang-analyzer checks --- .clang-tidy | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.clang-tidy b/.clang-tidy index 02bb3916f..1412b563a 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,5 +1,5 @@ --- -Checks: '-*,google-*,cppcoreguidelines-*,-cppcoreguidelines-avoid-magic-numbers,-cppcoreguidelines-pro-bounds-*,openmp-*,performance-*,portability-*,modernize-*,-modernize-use-trailing-*' +Checks: '-*,google-*,clang-analyzer-*,cppcoreguidelines-*,-cppcoreguidelines-avoid-magic-numbers,-cppcoreguidelines-pro-bounds-*,openmp-*,performance-*,portability-*,modernize-*,-modernize-use-trailing-*' WarningsAsErrors: '' HeaderFilterRegex: '' AnalyzeTemporaryDtors: false From 1fbd0d59ac276e8ca1e6c8f93995b3470c92cbb4 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 10 Jul 2020 21:38:04 +0000 Subject: [PATCH 252/271] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 0f7e9a053..bc007bc5f 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -201,6 +201,7 @@ ## Search * [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) + * [Fibonacci Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/fibonacci_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_search.cpp) * [Interpolation Search2](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/interpolation_search2.cpp) From bade26eccaf25c0c0b854c6b76e0588835ccc686 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 10 Jul 2020 18:25:13 -0400 Subject: [PATCH 253/271] disable rand error --- .clang-tidy | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.clang-tidy b/.clang-tidy index 1412b563a..d7dc7996d 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,5 +1,5 @@ --- -Checks: '-*,google-*,clang-analyzer-*,cppcoreguidelines-*,-cppcoreguidelines-avoid-magic-numbers,-cppcoreguidelines-pro-bounds-*,openmp-*,performance-*,portability-*,modernize-*,-modernize-use-trailing-*' +Checks: '-*,google-*,clang-analyzer-*,-clang-analyzer-security.insecureAPI.rand,cppcoreguidelines-*,-cppcoreguidelines-avoid-magic-numbers,-cppcoreguidelines-pro-bounds-*,openmp-*,performance-*,portability-*,modernize-*,-modernize-use-trailing-*' WarningsAsErrors: '' HeaderFilterRegex: '' AnalyzeTemporaryDtors: false From 229334cce6028ad80e30f269ef2220f508f68f54 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 10 Jul 2020 18:37:35 -0400 Subject: [PATCH 254/271] treat clang-tidy warnings as errors --- .clang-tidy | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.clang-tidy b/.clang-tidy index d7dc7996d..610c6b28f 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,6 +1,6 @@ --- Checks: '-*,google-*,clang-analyzer-*,-clang-analyzer-security.insecureAPI.rand,cppcoreguidelines-*,-cppcoreguidelines-avoid-magic-numbers,-cppcoreguidelines-pro-bounds-*,openmp-*,performance-*,portability-*,modernize-*,-modernize-use-trailing-*' -WarningsAsErrors: '' +WarningsAsErrors: '*' HeaderFilterRegex: '' AnalyzeTemporaryDtors: false FormatStyle: '{ BasedOnStyle: Google, UseTab: Never, IndentWidth: 4, TabWidth: 4, AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: true, ColumnLimit: 80, AccessModifierOffset: -3, AlignConsecutiveMacros: true }' From 389d50ea1421b6a15dd0b47476a2bd5dfb392425 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 10 Jul 2020 19:05:42 -0400 Subject: [PATCH 255/271] disable all insecureAPI errors --- .clang-tidy | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.clang-tidy b/.clang-tidy index 610c6b28f..95431d6da 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,5 +1,5 @@ --- -Checks: '-*,google-*,clang-analyzer-*,-clang-analyzer-security.insecureAPI.rand,cppcoreguidelines-*,-cppcoreguidelines-avoid-magic-numbers,-cppcoreguidelines-pro-bounds-*,openmp-*,performance-*,portability-*,modernize-*,-modernize-use-trailing-*' +Checks: '-*,google-*,clang-analyzer-*,-clang-analyzer-security.insecureAPI.*,cppcoreguidelines-*,-cppcoreguidelines-avoid-magic-numbers,-cppcoreguidelines-pro-bounds-*,openmp-*,performance-*,portability-*,modernize-*,-modernize-use-trailing-*' WarningsAsErrors: '*' HeaderFilterRegex: '' AnalyzeTemporaryDtors: false From 9a5a62cf127444de0372d275f7c8810501784b65 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 10 Jul 2020 21:47:39 -0400 Subject: [PATCH 256/271] pass multiple files --- .github/workflows/awesome_workflow.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/awesome_workflow.yml b/.github/workflows/awesome_workflow.yml index 2e0792e17..97f705877 100644 --- a/.github/workflows/awesome_workflow.yml +++ b/.github/workflows/awesome_workflow.yml @@ -122,9 +122,11 @@ jobs: if not cpp_files: sys.exit(0) - for cpp_file in cpp_files: - subprocess.run(["clang-tidy-10", "--fix", "-p=build", cpp_file, "--"], + subprocess.run(["clang-tidy-10", "--fix", "-p=build", *cpp_files, "--"], check=True, text=True, stderr=subprocess.STDOUT) + # for cpp_file in cpp_files: + # subprocess.run(["clang-tidy-10", "--fix", "-p=build", cpp_file, "--"], + # check=True, text=True, stderr=subprocess.STDOUT) # print("g++:") # compile_exts = tuple(".c .c++ .cc .cpp .cu .cxx".split()) From 523475b18367d573ae21bd8ae8b45ce8fb565e6b Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 10 Jul 2020 21:58:22 -0400 Subject: [PATCH 257/271] mark all warnings as errors except those that are fixable by clang-tidy --- .clang-tidy | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.clang-tidy b/.clang-tidy index 95431d6da..272502837 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,6 +1,6 @@ --- Checks: '-*,google-*,clang-analyzer-*,-clang-analyzer-security.insecureAPI.*,cppcoreguidelines-*,-cppcoreguidelines-avoid-magic-numbers,-cppcoreguidelines-pro-bounds-*,openmp-*,performance-*,portability-*,modernize-*,-modernize-use-trailing-*' -WarningsAsErrors: '*' +WarningsAsErrors: '*,-google-readability-*,-google-explicit-constructor,-modernize-*,modernize-avoid-c-arrays,-google-explicit-constructor,-performance-move-const-arg,-performance-noexcept-move-constructor,-cppcoreguidelines-init-variables,-cppcoreguidelines-pro-*' HeaderFilterRegex: '' AnalyzeTemporaryDtors: false FormatStyle: '{ BasedOnStyle: Google, UseTab: Never, IndentWidth: 4, TabWidth: 4, AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: true, ColumnLimit: 80, AccessModifierOffset: -3, AlignConsecutiveMacros: true }' From dc6f32297567a9888eeb8ed24d26ded0ce5d1f43 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 10 Jul 2020 22:00:57 -0400 Subject: [PATCH 258/271] test commit --- numerical_methods/brent_method_extrema.cpp | 5 ++--- numerical_methods/durand_kerner_roots.cpp | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/numerical_methods/brent_method_extrema.cpp b/numerical_methods/brent_method_extrema.cpp index 654a69451..399be5b38 100644 --- a/numerical_methods/brent_method_extrema.cpp +++ b/numerical_methods/brent_method_extrema.cpp @@ -180,14 +180,13 @@ void test2() { } /** - * @brief Test function to find *maxima* for the function + * @brief Test function to find *minima* for the function * \f$f(x)= \cos x\f$ * in the interval \f$[0,12]\f$ * \n Expected result: \f$\pi\approx 3.14159265358979312\f$ */ void test3() { - // define the function to maximize as a lambda function - // since we are maximixing, we negated the function return value + // define the function to minimize as a lambda function std::function func = [](double x) { return std::cos(x); }; std::cout << "Test 3.... "; diff --git a/numerical_methods/durand_kerner_roots.cpp b/numerical_methods/durand_kerner_roots.cpp index 9bf0619b8..23419d1ed 100644 --- a/numerical_methods/durand_kerner_roots.cpp +++ b/numerical_methods/durand_kerner_roots.cpp @@ -212,7 +212,7 @@ void test1() { std::complex(0., -2.) // known expected roots }; - /* initialize root approximations with random values */ + /* 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; From 2ca13dd45a5a99e6677149ad4020c03e0e63d646 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 10 Jul 2020 22:16:14 -0400 Subject: [PATCH 259/271] Revert "test commit" This reverts commit dc6f32297567a9888eeb8ed24d26ded0ce5d1f43. --- numerical_methods/brent_method_extrema.cpp | 5 +++-- numerical_methods/durand_kerner_roots.cpp | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/numerical_methods/brent_method_extrema.cpp b/numerical_methods/brent_method_extrema.cpp index 399be5b38..654a69451 100644 --- a/numerical_methods/brent_method_extrema.cpp +++ b/numerical_methods/brent_method_extrema.cpp @@ -180,13 +180,14 @@ void test2() { } /** - * @brief Test function to find *minima* for the function + * @brief Test function to find *maxima* for the function * \f$f(x)= \cos x\f$ * in the interval \f$[0,12]\f$ * \n Expected result: \f$\pi\approx 3.14159265358979312\f$ */ void test3() { - // define the function to minimize as a lambda function + // define the function to maximize as a lambda function + // since we are maximixing, we negated the function return value std::function func = [](double x) { return std::cos(x); }; std::cout << "Test 3.... "; diff --git a/numerical_methods/durand_kerner_roots.cpp b/numerical_methods/durand_kerner_roots.cpp index 23419d1ed..9bf0619b8 100644 --- a/numerical_methods/durand_kerner_roots.cpp +++ b/numerical_methods/durand_kerner_roots.cpp @@ -212,7 +212,7 @@ void test1() { std::complex(0., -2.) // known expected roots }; - /* Initialize root approximations with random values */ + /* 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; From d34bede6f4e2d94e5b7d2073d26cd11ac7f1352a Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 11 Jul 2020 09:11:31 -0400 Subject: [PATCH 260/271] disable error on cppcoreguidelines-owning-memory see https://clang.llvm.org/extra/clang-tidy/checks/cppcoreguidelines-owning-memory.html for details --- .clang-tidy | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.clang-tidy b/.clang-tidy index 272502837..381337977 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,6 +1,6 @@ --- Checks: '-*,google-*,clang-analyzer-*,-clang-analyzer-security.insecureAPI.*,cppcoreguidelines-*,-cppcoreguidelines-avoid-magic-numbers,-cppcoreguidelines-pro-bounds-*,openmp-*,performance-*,portability-*,modernize-*,-modernize-use-trailing-*' -WarningsAsErrors: '*,-google-readability-*,-google-explicit-constructor,-modernize-*,modernize-avoid-c-arrays,-google-explicit-constructor,-performance-move-const-arg,-performance-noexcept-move-constructor,-cppcoreguidelines-init-variables,-cppcoreguidelines-pro-*' +WarningsAsErrors: '*,-google-readability-*,-google-explicit-constructor,-modernize-*,modernize-avoid-c-arrays,-google-explicit-constructor,-performance-move-const-arg,-performance-noexcept-move-constructor,-cppcoreguidelines-init-variables,-cppcoreguidelines-pro-*,-cppcoreguidelines-owning-memory' HeaderFilterRegex: '' AnalyzeTemporaryDtors: false FormatStyle: '{ BasedOnStyle: Google, UseTab: Never, IndentWidth: 4, TabWidth: 4, AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: true, ColumnLimit: 80, AccessModifierOffset: -3, AlignConsecutiveMacros: true }' From 4e12f03c6cbfa42d7f77d06edd08e39cfb901f4b Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 11 Jul 2020 15:09:00 -0400 Subject: [PATCH 261/271] disable move error + enforce c++11 for clang-tidy --- .clang-tidy | 2 +- .github/workflows/awesome_workflow.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index 381337977..113d688e7 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,6 +1,6 @@ --- Checks: '-*,google-*,clang-analyzer-*,-clang-analyzer-security.insecureAPI.*,cppcoreguidelines-*,-cppcoreguidelines-avoid-magic-numbers,-cppcoreguidelines-pro-bounds-*,openmp-*,performance-*,portability-*,modernize-*,-modernize-use-trailing-*' -WarningsAsErrors: '*,-google-readability-*,-google-explicit-constructor,-modernize-*,modernize-avoid-c-arrays,-google-explicit-constructor,-performance-move-const-arg,-performance-noexcept-move-constructor,-cppcoreguidelines-init-variables,-cppcoreguidelines-pro-*,-cppcoreguidelines-owning-memory' +WarningsAsErrors: '*,-google-readability-*,-google-explicit-constructor,-modernize-*,modernize-avoid-c-arrays,-performance-move-const-arg,-performance-noexcept-move-constructor,-cppcoreguidelines-init-variables,-cppcoreguidelines-pro-*,-cppcoreguidelines-owning-memory,-clang-analyzer-cplusplus.Move' HeaderFilterRegex: '' AnalyzeTemporaryDtors: false FormatStyle: '{ BasedOnStyle: Google, UseTab: Never, IndentWidth: 4, TabWidth: 4, AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: true, ColumnLimit: 80, AccessModifierOffset: -3, AlignConsecutiveMacros: true }' diff --git a/.github/workflows/awesome_workflow.yml b/.github/workflows/awesome_workflow.yml index 97f705877..4906a60d8 100644 --- a/.github/workflows/awesome_workflow.yml +++ b/.github/workflows/awesome_workflow.yml @@ -122,7 +122,7 @@ jobs: if not cpp_files: sys.exit(0) - subprocess.run(["clang-tidy-10", "--fix", "-p=build", *cpp_files, "--"], + subprocess.run(["clang-tidy-10", "--fix", "-p=build", "--extra-args=-std=c++11", *cpp_files, "--"], check=True, text=True, stderr=subprocess.STDOUT) # for cpp_file in cpp_files: # subprocess.run(["clang-tidy-10", "--fix", "-p=build", cpp_file, "--"], From 1f32b4e412862d65c819efac7716625915160fc7 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 12 Jul 2020 07:24:57 -0400 Subject: [PATCH 262/271] Fix command syntax (#949) --- .github/workflows/awesome_workflow.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/awesome_workflow.yml b/.github/workflows/awesome_workflow.yml index 4906a60d8..9cff1c48d 100644 --- a/.github/workflows/awesome_workflow.yml +++ b/.github/workflows/awesome_workflow.yml @@ -122,7 +122,7 @@ jobs: if not cpp_files: sys.exit(0) - subprocess.run(["clang-tidy-10", "--fix", "-p=build", "--extra-args=-std=c++11", *cpp_files, "--"], + subprocess.run(["clang-tidy-10", "--fix", "-p=build", "--extra-arg=-std=c++11", *cpp_files, "--"], check=True, text=True, stderr=subprocess.STDOUT) # for cpp_file in cpp_files: # subprocess.run(["clang-tidy-10", "--fix", "-p=build", cpp_file, "--"], From a707d710b58e5921d7f7131932f48f7e7860e7bd Mon Sep 17 00:00:00 2001 From: enqidu Date: Sun, 12 Jul 2020 19:24:46 +0400 Subject: [PATCH 263/271] update --- data_structures/skip_list.cpp | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index 6159506a0..f0a17815a 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -26,12 +26,9 @@ using std::endl; * Node structure [Key][Node*, Node*...] */ struct Node { - int key; - // pointer of value - void* value; - // Forward Array points to the neighbour (right) - // nodes of the given one in all levels - vector forward; + int key; ///< key integer + void* value; ///< pointer of value + vector forward; ///< nodes of the given one in all levels // Constructor of the node Node(int key, int level, void* value); }; @@ -54,10 +51,8 @@ Node::Node(int key, int level, void* value) { * SkipList class implementation with basic methods */ class SkipList { - // Maximum level of the skiplist - int level; - // Pointer to the header node - Node *header; + int level; ///< Maximum level of the skiplist + Node *header; ///< Pointer to the header node public: SkipList(); int randomLevel(); From f970ce361cd1f17e289068a1e36c19eb362db1a0 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 12 Jul 2020 17:00:27 -0400 Subject: [PATCH 264/271] tidied up code based on error reports by clang-tidy --- data_structures/skip_list.cpp | 422 +++++++++++++++++----------------- 1 file changed, 208 insertions(+), 214 deletions(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index 373b93dad..d7982f866 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -1,241 +1,235 @@ /** * @file skip_list.cpp - * @brief Data structure for fast searching and insertion in \f$O(\log n)\f$ time + * @brief Data structure for fast searching and insertion in \f$O(\log n)\f$ + * time * @details - * A skip list is a data structure that is used for storing a sorted list of items with a - * help of hierarchy of linked lists that connect increasingly sparse subsequences of the items - * - * References used: [GeeksForGeek](https://www.geeksforgeeks.org/skip-list/), [OpenGenus](https://iq.opengenus.org/skip-list) for PseudoCode and Code + * A skip list is a data structure that is used for storing a sorted list of + * items with a help of hierarchy of linked lists that connect increasingly + * sparse subsequences of the items + * + * References used: [GeeksForGeek](https://www.geeksforgeeks.org/skip-list/), + * [OpenGenus](https://iq.opengenus.org/skip-list) for PseudoCode and Code * @author [enqidu](https://github.com/enqidu) - * . -*/ + * @author [Krishna Vedala](https://github.com/kvedala) + */ -#include -#include +#include #include -#include +#include +#include +#include +#include -using std::vector; -using std::endl; - -#define MAX_LEVEL 2 ///< Maximum level of skip list -#define PROBABILITY 0.5 ///< Current probability for "coin toss" - +/** \namespace data_structure + * \brief Data-structure algorithms + */ +namespace data_structure { +constexpr int MAX_LEVEL = 2; ///< Maximum level of skip list +constexpr float PROBABILITY = 0.5; ///< Current probability for "coin toss" /** * Node structure [Key][Node*, Node*...] -*/ -struct Node { - int key; ///< key integer - void* value; ///< pointer of value - vector forward; ///< nodes of the given one in all levels - // Constructor of the node - Node(int key, int level, void* value); + */ +struct Node { + int key; ///< key integer + void* value; ///< pointer of value + std::vector> + forward; ///< nodes of the given one in all levels + + /** + * Creates node with provided key, level and value + * @param key is number that is used for comparision + * @param level is the maximum level node's going to added + */ + Node(int key, int level, void* value = nullptr) : key(key) { + // Initialization of forward vector + for (int i = 0; i < (level + 1); i++) { + forward.push_back(nullptr); + } + } }; -/** - * Creates node with provided key, level and value - * @param key is number that is used for comparision - * @param level is the maximum level node's going to added -*/ -Node::Node(int key, int level, void* value) { - this->key = key; - - //Initialization of forward vector - for (int i = 0; i < (level+1); i++){ - forward.push_back(nullptr); - } -} - /** * SkipList class implementation with basic methods -*/ -class SkipList { - int level; ///< Maximum level of the skiplist - Node *header; ///< Pointer to the header node -public: - SkipList(); - int randomLevel(); - void insertElement(int, void*); - void deleteElement(int); - void* searchElement(int); - void displayList(); - ~SkipList(); + */ +class SkipList { + int level; ///< Maximum level of the skiplist + std::shared_ptr header; ///< Pointer to the header node + + public: + /** + * Skip List constructor. Initializes header, start + * Node for searching in the list + */ + SkipList() { + level = 0; + // Header initialization + header = std::shared_ptr(new Node(-1, MAX_LEVEL)); + } + + /** + * Destructor for skiplist class + */ + ~SkipList() { + for (int i = 0; i <= level; i++) { + std::shared_ptr node = header->forward[i]; + std::shared_ptr temp; + while (node != nullptr) { + temp = node; + node = node->forward[i]; + temp.reset(); + } + } + header.reset(); + } + + /** + * Returns random level of the skip list. + * Every higher level is 2 times less likely. + * @return random level for skip list + */ + int randomLevel() { + int lvl = 0; + while (static_cast(std::rand() / RAND_MAX) < PROBABILITY && + lvl < MAX_LEVEL) + lvl++; + return lvl; + } + + /** + * Inserts elements with given key and value; + * It's level is computed by randomLevel() function. + * @param key is number that is used for comparision + * @param value pointer to a value, that can be any type + */ + void insertElement(int key, void* value) { + std::cout << "Inserting" << key << "..."; + std::shared_ptr x = header; + std::array, MAX_LEVEL + 1> update; + update.fill(nullptr); + + for (int i = level; i >= 0; i--) { + while (x->forward[i] != nullptr && x->forward[i]->key < key) + x = x->forward[i]; + update[i] = x; + } + + x = x->forward[0]; + + bool doesnt_exist = (x == nullptr || x->key != key); + if (doesnt_exist) { + int rlevel = randomLevel(); + + if (rlevel > level) { + for (int i = level + 1; i < rlevel + 1; i++) update[i] = header; + + // Update current level + level = rlevel; + } + + std::shared_ptr n = + std::shared_ptr(new Node(key, rlevel, value)); + for (int i = 0; i <= rlevel; i++) { + n->forward[i] = update[i]->forward[i]; + update[i]->forward[i] = n; + } + std::cout << "Inserted" << std::endl; + + } else { + std::cout << "Exists" << std::endl; + } + } + + /** + * Deletes an element by key and prints if has been removed successfully + * @param key is number that is used for comparision. + */ + void deleteElement(int key) { + std::shared_ptr x = header; + + std::array, MAX_LEVEL + 1> update; + update.fill(nullptr); + + for (int i = level; i >= 0; i--) { + while (x->forward[i] != nullptr && x->forward[i]->key < key) + x = x->forward[i]; + update[i] = x; + } + + x = x->forward[0]; + + bool doesnt_exist = (x == nullptr || x->key != key); + + if (!doesnt_exist) { + for (int i = 0; i <= level; i++) { + if (update[i]->forward[i] != x) + break; + update[i]->forward[i] = x->forward[i]; + } + /* Remove empty levels*/ + while (level > 0 && header->forward[level] == nullptr) level--; + std::cout << "Deleted" << std::endl; + } else { + std::cout << "Doesn't exist" << std::endl; + } + } + + /** + * Searching element in skip list structure + * @param key is number that is used for comparision + * @return pointer to the value of the node + */ + void* searchElement(int key) { + std::shared_ptr x = header; + std::cout << "Searching for " << key << std::endl; + + for (int i = level; i >= 0; i--) { + while (x->forward[i] && x->forward[i]->key < key) x = x->forward[i]; + } + + x = x->forward[0]; + if (x && x->key == key) { + std::cout << "Found" << std::endl; + return x->value; + } else { + std::cout << "Not Found" << std::endl; + return nullptr; + } + } + + /* + * Display skip list level + */ + void displayList() { + std::cout << "Displaying list:\n" << std::endl; + for (int i = 0; i <= level; i++) { + std::shared_ptr node = header->forward[i]; + std::cout << "Level " << (i) << ": "; + while (node != nullptr) { + std::cout << node->key << " "; + node = node->forward[i]; + } + std::cout << std::endl; + } + } }; - -/** - * Skeep List constructor. Initializes header, start - * Node for searching in the list -*/ -SkipList::SkipList() { - level = 0; - // Header initialization - header = new Node(-1, MAX_LEVEL, nullptr); -} - -/** - * Destructor for skiplist class -*/ -SkipList::~SkipList(){ - for(int i=0; i <= level; i++) { - Node *node = header->forward[i]; - Node* temp; - while(node != nullptr) { - temp = node; - node = node->forward[i]; - delete temp; - } - } - delete header; -} - - -/** - * Returns random level of the skip list. - * Every higher level is 2 times less likely. - * @return lvl: random level for skip list; -*/ -int SkipList::randomLevel() { - int lvl = 0; - while(static_cast(std::rand())/RAND_MAX < PROBABILITY && lvl < MAX_LEVEL) lvl++; - return lvl; -} - - - -/** - * Inserts elements with given key and value; - * It's level is computed by randomLevel() function. - * @param key is number that is used for comparision - * @param value pointer to a value, that can be any type -*/ -void SkipList::insertElement(int key, void* value) { - std::cout << "Inserting" << key << "..."; - Node *x = header; - Node *update[MAX_LEVEL+1]; - memset(update, 0, sizeof(Node*)*(MAX_LEVEL+1)); - - - for(int i = level; i >= 0; i--) { - while(x->forward[i] != nullptr && x->forward[i]->key < key) x = x->forward[i]; - update[i] = x; - } - - x = x->forward[0]; - - bool doesnt_exist = (x == nullptr || x->key != key); - if (doesnt_exist) { - int rlevel = randomLevel(); - - if(rlevel > level) { - for(int i=level+1;iforward[i] = update[i]->forward[i]; - update[i]->forward[i] = n; - } - std::cout << "Inserted" << endl; - - } else { - std::cout << "Exists" << endl; - } -} - -/** - * Deletes an element by key and prints if has been removed successfully - * @param key is number that is used for comparision. -*/ -void SkipList::deleteElement(int key) { - Node *x = header; - - Node *update[MAX_LEVEL+1]; - memset(update, 0, sizeof(Node*)*(MAX_LEVEL+1)); - - for(int i = level; i >= 0; i--) { - while(x->forward[i] != nullptr && x->forward[i]->key < key) x = x->forward[i]; - update[i] = x; - } - - x = x->forward[0]; - - bool doesnt_exist = (x == nullptr || x->key != key); - - if(!doesnt_exist) { - for(int i=0;i<=level;i++) { - if(update[i]->forward[i] != x) break; - update[i]->forward[i] = x->forward[i]; - } - /* Remove empty levels*/ - while(level>0 && header->forward[level] == 0) level--; - std::cout << "Deleted" << endl; - } else { - std::cout << "Doesn't exist" << endl; - } -} - - -/** - * Searching element in skip list structure - * @param key is number that is used for comparision - * @return pointer to the value of the node -*/ -void* SkipList::searchElement(int key) { - Node *x = header; - std::cout << "Searching for " + key << endl; - - for(int i = level; i >= 0; i--) { - while(x->forward[i] && x->forward[i]->key < key) x = x->forward[i]; - } - - x = x->forward[0]; - if(x && x->key == key){ - std::cout << "Found" << endl; - return x->value; - } else { - std::cout << "Not Found" << endl; - return nullptr; - } -} - -/* - * Display skip list level - */ -void SkipList::displayList() { - std::cout << "Displaying list:\n" << endl; - for(int i=0; i <= level; i++) { - Node *node = header->forward[i]; - std::cout << "Level " << (i) << ": "; - while(node != nullptr) { - std::cout << node->key << " "; - node = node->forward[i]; - } - std::cout << endl; - } -} - +} // namespace data_structure /** * Main function: * Creates and inserts random 2^[number of levels] * elements into the skip lists and than displays it - */ -int main() -{ + */ +int main() { std::srand(std::time(nullptr)); - SkipList lst; + data_structure::SkipList lst; - for (int j = 0; j < (1 << (MAX_LEVEL+1)); j++){ - int k = (std::rand()%( 1 << (MAX_LEVEL+2)) + 1); - lst.insertElement(k, &j); + for (int j = 0; j < (1 << (data_structure::MAX_LEVEL + 1)); j++) { + int k = (std::rand() % (1 << (data_structure::MAX_LEVEL + 2)) + 1); + lst.insertElement(k, &j); } lst.displayList(); - -} +} From c15c962f02d284f50b7a62b4af92fe2ef696a7a1 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 12 Jul 2020 17:04:09 -0400 Subject: [PATCH 265/271] since we are using smart pointers, an explicit destructor is not required --- data_structures/skip_list.cpp | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index d7982f866..2cb78b8c8 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -67,22 +67,6 @@ class SkipList { header = std::shared_ptr(new Node(-1, MAX_LEVEL)); } - /** - * Destructor for skiplist class - */ - ~SkipList() { - for (int i = 0; i <= level; i++) { - std::shared_ptr node = header->forward[i]; - std::shared_ptr temp; - while (node != nullptr) { - temp = node; - node = node->forward[i]; - temp.reset(); - } - } - header.reset(); - } - /** * Returns random level of the skip list. * Every higher level is 2 times less likely. From 47f5ad9aaf0f497afec0bdcbb0138c344b9364e8 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sun, 12 Jul 2020 17:47:57 -0400 Subject: [PATCH 266/271] fix randomlevel float conversion --- data_structures/skip_list.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index 2cb78b8c8..b1b24ea20 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -41,7 +41,7 @@ struct Node { * @param key is number that is used for comparision * @param level is the maximum level node's going to added */ - Node(int key, int level, void* value = nullptr) : key(key) { + Node(int key, int level, void* value = nullptr) : key(key), value(value) { // Initialization of forward vector for (int i = 0; i < (level + 1); i++) { forward.push_back(nullptr); @@ -74,7 +74,7 @@ class SkipList { */ int randomLevel() { int lvl = 0; - while (static_cast(std::rand() / RAND_MAX) < PROBABILITY && + while (static_cast(std::rand()) / RAND_MAX < PROBABILITY && lvl < MAX_LEVEL) lvl++; return lvl; @@ -185,7 +185,7 @@ class SkipList { * Display skip list level */ void displayList() { - std::cout << "Displaying list:\n" << std::endl; + std::cout << "Displaying list:\n"; for (int i = 0; i <= level; i++) { std::shared_ptr node = header->forward[i]; std::cout << "Level " << (i) << ": "; From 8ab9a2ae939b915f0da7d5daacb03eec2aed91c1 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Mon, 13 Jul 2020 07:52:38 -0400 Subject: [PATCH 267/271] [cpp fixes] tidied up code based on error reports by clang-tidy (#950) * tidied up code based on error reports by clang-tidy * added doc for activation function --- machine_learning/adaline_learning.cpp | 107 ++++++++------ machine_learning/kohonen_som_topology.cpp | 130 ++++++++++-------- machine_learning/kohonen_som_trace.cpp | 88 +++++++----- .../ordinary_least_squares_regressor.cpp | 48 ++++--- numerical_methods/newton_raphson_method.cpp | 11 +- numerical_methods/ode_forward_euler.cpp | 31 +++-- 6 files changed, 243 insertions(+), 172 deletions(-) diff --git a/machine_learning/adaline_learning.cpp b/machine_learning/adaline_learning.cpp index a8426ac4e..6da839a9d 100644 --- a/machine_learning/adaline_learning.cpp +++ b/machine_learning/adaline_learning.cpp @@ -26,6 +26,7 @@ * computed using stochastic gradient descent method. */ +#include #include #include #include @@ -35,7 +36,8 @@ #include #include -#define MAX_ITER 500 // INT_MAX ///< Maximum number of iterations to learn +/** Maximum number of iterations to learn */ +constexpr int MAX_ITER = 500; // INT_MAX /** \namespace machine_learning * \brief Machine learning algorithms @@ -50,8 +52,8 @@ class adaline { * \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) + explicit 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" @@ -64,7 +66,7 @@ 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] = 1.f; + for (double &weight : weights) weight = 1.f; // weights[i] = (static_cast(std::rand() % 100) - 50); } @@ -75,8 +77,9 @@ class adaline { out << "<"; for (int i = 0; i < ada.weights.size(); i++) { out << ada.weights[i]; - if (i < ada.weights.size() - 1) + if (i < ada.weights.size() - 1) { out << ", "; + } } out << ">"; return out; @@ -90,28 +93,33 @@ class adaline { * model prediction output */ int predict(const std::vector &x, double *out = nullptr) { - if (!check_size_match(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]; y = std::inner_product(x.begin(), x.end(), weights.begin(), y); - if (out != nullptr) // if out variable is provided + if (out != nullptr) { // if out variable is provided *out = y; + } 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 + * 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)) + if (!check_size_match(x)) { return 0; + } /* output of the model with current weights */ int p = predict(x); @@ -129,21 +137,23 @@ class adaline { /** * 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 + * 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) { + template + void fit(std::array, N> const &X, + std::array const &Y) { double avg_pred_error = 1.f; - int iter; + int iter = 0; 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]); + double err = fit(X[i], Y[i]); avg_pred_error += std::abs(err); } avg_pred_error /= N; @@ -154,15 +164,25 @@ class adaline { << "\tAvg error: " << avg_pred_error << std::endl; } - if (iter < MAX_ITER) - + if (iter < MAX_ITER) { std::cout << "Converged after " << iter << " iterations." << std::endl; - else + } else { std::cout << "Did not converge after " << iter << " iterations." << std::endl; + } } + /** Defines activation function as Heaviside's step function. + * \f[ + * f(x) = \begin{cases} + * -1 & \forall x \le 0\\ + * 1 & \forall x > 0 + * \end{cases} + * \f] + * @param x input value to apply activation on + * @return activation output + */ int activation(double x) { return x > 0 ? 1 : -1; } private: @@ -206,15 +226,19 @@ void test1(double eta = 0.01) { 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::array, N> X = { + std::vector({0, 1}), std::vector({1, -2}), + std::vector({2, 3}), std::vector({3, -1}), + std::vector({4, 1}), std::vector({6, -5}), + std::vector({-7, -3}), std::vector({-8, 5}), + std::vector({-9, 2}), std::vector({-10, -15})}; + std::array 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); + ada.fit(X, y); std::cout << "Model after fit: " << ada << std::endl; int predict = ada.predict({5, -3}); @@ -240,17 +264,17 @@ void test2(double eta = 0.01) { const int N = 50; // number of sample points - std::vector X[N]; - int Y[N]; // corresponding y-values + std::array, N> X; + std::array Y{}; // corresponding y-values // 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; - X[i] = {x0, x1}; + double x0 = (static_cast(std::rand() % range) - range2) / 100.f; + double x1 = (static_cast(std::rand() % range) - range2) / 100.f; + X[i] = std::vector({x0, x1}); Y[i] = (x0 + 3. * x1) > -1 ? 1 : -1; } @@ -262,8 +286,8 @@ void test2(double eta = 0.01) { 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 x0 = (static_cast(std::rand() % range) - range2) / 100.f; + double x1 = (static_cast(std::rand() % range) - range2) / 100.f; int predict = ada.predict({x0, x1}); @@ -291,18 +315,18 @@ void test3(double eta = 0.01) { const int N = 100; // number of sample points - std::vector X[N]; - int Y[N]; // corresponding y-values + std::array, N> X; + std::array Y{}; // 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}; + double x0 = (static_cast(std::rand() % range) - range2) / 100.f; + double x1 = (static_cast(std::rand() % range) - range2) / 100.f; + double x2 = (static_cast(std::rand() % range) - range2) / 100.f; + X[i] = std::vector({x0, x1, x2, x0 * x0, x1 * x1, x2 * x2}); Y[i] = ((x0 * x0) + (x1 * x1) + (x2 * x2)) <= 1.f ? 1 : -1; } @@ -314,9 +338,9 @@ void test3(double eta = 0.01) { 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; + double x0 = (static_cast(std::rand() % range) - range2) / 100.f; + double x1 = (static_cast(std::rand() % range) - range2) / 100.f; + double x2 = (static_cast(std::rand() % range) - range2) / 100.f; int predict = ada.predict({x0, x1, x2, x0 * x0, x1 * x1, x2 * x2}); @@ -334,8 +358,9 @@ int main(int argc, char **argv) { std::srand(std::time(nullptr)); // initialize random number generator double eta = 0.1; // default value of eta - if (argc == 2) // read eta value from commandline argument if present + if (argc == 2) { // read eta value from commandline argument if present eta = strtof(argv[1], nullptr); + } test1(eta); diff --git a/machine_learning/kohonen_som_topology.cpp b/machine_learning/kohonen_som_topology.cpp index 016fe6d1e..cccc9faa3 100644 --- a/machine_learning/kohonen_som_topology.cpp +++ b/machine_learning/kohonen_som_topology.cpp @@ -25,8 +25,11 @@ */ #define _USE_MATH_DEFINES //< required for MS Visual C++ #include +#include +#include #include #include +#include #include #include #include @@ -68,7 +71,8 @@ int save_2d_data(const char *fname, fp.open(fname); if (!fp.is_open()) { // error with opening file to write - std::cerr << "Error opening file " << fname << "\n"; + std::cerr << "Error opening file " << fname << ": " + << std::strerror(errno) << "\n"; return -1; } @@ -76,12 +80,14 @@ int save_2d_data(const char *fname, 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 + 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 } - if (i < num_points - 1) // if not the last row - fp << "\n"; // start a new line } fp.close(); @@ -99,12 +105,12 @@ int save_2d_data(const char *fname, 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(); + size_t 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); + std::ptrdiff_t 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 @@ -119,7 +125,8 @@ void get_min_2d(const std::vector> &X, double *val, * \brief Machine learning algorithms */ namespace machine_learning { -#define MIN_DISTANCE 1e-4 ///< Minimum average distance of image nodes +/** Minimum average distance of image nodes */ +constexpr double MIN_DISTANCE = 1e-4; /** * Create the distance matrix or @@ -136,9 +143,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::snprintf(msg, sizeof(msg), "File error (%s): ", fname); - std::perror(msg); + std::cerr << "File error (" << fname << "): " << std::strerror(errno) + << std::endl; return -1; } @@ -153,7 +159,7 @@ int save_u_matrix(const char *fname, 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; + int l = 0, m = 0; #ifdef _OPENMP #pragma omp parallel for reduction(+ : distance) #endif @@ -172,8 +178,9 @@ int save_u_matrix(const char *fname, fp << ','; // suffix comma } } - if (i < W.size() - 1) // if not the last row - fp << '\n'; // start a new line + if (i < W.size() - 1) { // if not the last row + fp << '\n'; // start a new line + } } fp.close(); @@ -194,10 +201,11 @@ double update_weights(const std::valarray &X, std::vector>> *W, std::vector> *D, double alpha, int R) { - int x, y; + int x = 0, y = 0; 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 + // int num_features = static_cast(W[0][0][0].size()); // features = + // in Z double d_min = 0.f; #ifdef _OPENMP @@ -217,7 +225,7 @@ double update_weights(const std::valarray &X, // step 2: get closest node i.e., node with snallest Euclidian distance // to the current pattern - int d_min_x, d_min_y; + int d_min_x = 0, d_min_y = 0; get_min_2d(*D, &d_min, &d_min_x, &d_min_y); // step 3a: get the neighborhood range @@ -261,10 +269,10 @@ double update_weights(const std::valarray &X, 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; + size_t num_samples = X.size(); // number of rows + // size_t num_features = X[0].size(); // number of columns + size_t num_out = W->size(); // output matrix size + size_t R = num_out >> 2, iter = 0; double alpha = 1.f; std::vector> D(num_out); @@ -283,15 +291,17 @@ void kohonen_som(const std::vector> &X, } // every 100th iteration, reduce the neighborhood range - if (iter % 300 == 0 && R > 1) + 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) + if (dmin_ratio < 0) { dmin_ratio = 1.f; + } past_dmin = dmin; std::cout << "iter: " << iter << "\t alpha: " << alpha << "\t R: " << R @@ -320,14 +330,14 @@ using machine_learning::save_u_matrix; void test_2d_classes(std::vector> *data) { const int N = data->size(); const double R = 0.3; // radius of cluster - int i; + int i = 0; const int num_classes = 4; - const double centres[][2] = { + std::array, num_classes> centres = { // 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 + std::array({.5, .5}), // centre of class 1 + std::array({.5, -.5}), // centre of class 2 + std::array({-.5, .5}), // centre of class 3 + std::array({-.5, -.5}) // centre of class 4 }; #ifdef _OPENMP @@ -357,15 +367,16 @@ void test_2d_classes(std::vector> *data) { * * `w12.csv`: trained SOM map */ void test1() { - int j, N = 300; + int j = 0, 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 + 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++) { @@ -373,9 +384,10 @@ void test1() { #ifdef _OPENMP #pragma omp for #endif - for (j = 0; j < features; j++) + for (j = 0; j < features; j++) { // preallocate with random initial weights W[i][k][j] = _random(-10, 10); + } } } } @@ -397,16 +409,16 @@ void test1() { * \param[out] data matrix to store data in */ void test_3d_classes1(std::vector> *data) { - const int N = data->size(); + const size_t N = data->size(); const double R = 0.3; // radius of cluster - int i; + int i = 0; const int num_classes = 4; - const double centres[][3] = { + const std::array, num_classes> centres = { // 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 + std::array({.5, .5, .5}), // centre of class 1 + std::array({.5, -.5, -.5}), // centre of class 2 + std::array({-.5, .5, .5}), // centre of class 3 + std::array({-.5, -.5 - .5}) // centre of class 4 }; #ifdef _OPENMP @@ -437,15 +449,16 @@ void test_3d_classes1(std::vector> *data) { * * `w22.csv`: trained SOM map */ void test2() { - int j, N = 300; + int j = 0, 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 + 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++) { @@ -453,9 +466,10 @@ void test2() { #ifdef _OPENMP #pragma omp for #endif - for (j = 0; j < features; j++) + for (j = 0; j < features; j++) { // preallocate with random initial weights W[i][k][j] = _random(-10, 10); + } } } } @@ -477,20 +491,20 @@ void test2() { * \param[out] data matrix to store data in */ void test_3d_classes2(std::vector> *data) { - const int N = data->size(); + const size_t N = data->size(); const double R = 0.2; // radius of cluster - int i; + int i = 0; const int num_classes = 8; - const double centres[][3] = { + const std::array, num_classes> centres = { // 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 + std::array({.5, .5, .5}), // centre of class 1 + std::array({.5, .5, -.5}), // centre of class 2 + std::array({.5, -.5, .5}), // centre of class 3 + std::array({.5, -.5, -.5}), // centre of class 4 + std::array({-.5, .5, .5}), // centre of class 5 + std::array({-.5, .5, -.5}), // centre of class 6 + std::array({-.5, -.5, .5}), // centre of class 7 + std::array({-.5, -.5, -.5}) // centre of class 8 }; #ifdef _OPENMP @@ -521,15 +535,16 @@ void test_3d_classes2(std::vector> *data) { * * `w32.csv`: trained SOM map */ void test3() { - int j, N = 500; + int j = 0, 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 + 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++) { @@ -537,9 +552,10 @@ void test3() { #ifdef _OPENMP #pragma omp for #endif - for (j = 0; j < features; j++) + for (j = 0; j < features; j++) { // preallocate with random initial weights W[i][k][j] = _random(-10, 10); + } } } } diff --git a/machine_learning/kohonen_som_trace.cpp b/machine_learning/kohonen_som_trace.cpp index 273a2a57c..63a0c02c6 100644 --- a/machine_learning/kohonen_som_trace.cpp +++ b/machine_learning/kohonen_som_trace.cpp @@ -20,6 +20,7 @@ */ #define _USE_MATH_DEFINES // required for MS Visual C++ #include +#include #include #include #include @@ -71,12 +72,14 @@ int save_nd_data(const char *fname, 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 + 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 } - if (i < num_points - 1) // if not the last row - fp << "\n"; // start a new line } fp.close(); @@ -100,9 +103,9 @@ namespace machine_learning { 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 + int j = 0, k = 0; + int num_out = W->size(); // number of SOM output nodes + // int num_features = x.size(); // number of data features #ifdef _OPENMP #pragma omp for @@ -117,7 +120,7 @@ void update_weights(const std::valarray &x, // 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; + // double d_min = *result; int d_min_idx = std::distance(std::begin(*D), result); // step 3a: get the neighborhood range @@ -129,9 +132,10 @@ void update_weights(const std::valarray &x, #ifdef _OPENMP #pragma omp for #endif - for (j = from_node; j < to_node; j++) + for (j = from_node; j < to_node; j++) { // update weights of nodes in the neighborhood (*W)[j] += alpha * (x - (*W)[j]); + } } /** @@ -145,16 +149,16 @@ void update_weights(const std::valarray &x, 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 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++) { + do { // 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 @@ -162,9 +166,13 @@ void kohonen_som_tracer(const std::vector> &X, } // every 10th iteration, reduce the neighborhood range - if (iter % 10 == 0 && R > 1) + if (iter % 10 == 0 && R > 1) { R--; - } + } + + alpha -= 0.01; + iter++; + } while (alpha > alpha_min); } } // namespace machine_learning @@ -190,7 +198,7 @@ void test_circle(std::vector> *data) { 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; + int i = 0; #ifdef _OPENMP #pragma omp for @@ -223,24 +231,26 @@ void test_circle(std::vector> *data) { * output](https://raw.githubusercontent.com/TheAlgorithms/C-Plus-Plus/docs/images/machine_learning/kohonen/test1.svg) */ void test1() { - int j, N = 500; + int j = 0, 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 + 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++) + for (j = 0; j < features; j++) { // preallocate with random initial weights W[i][j] = _random(-1, 1); + } } } @@ -267,7 +277,7 @@ void test1() { void test_lamniscate(std::vector> *data) { const int N = data->size(); const double dr = 0.2; - int i; + int i = 0; #ifdef _OPENMP #pragma omp for @@ -303,24 +313,26 @@ void test_lamniscate(std::vector> *data) { * output](https://raw.githubusercontent.com/TheAlgorithms/C-Plus-Plus/docs/images/machine_learning/kohonen/test2.svg) */ void test2() { - int j, N = 500; + int j = 0, 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 + 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++) + for (j = 0; j < features; j++) { // preallocate with random initial weights W[i][j] = _random(-1, 1); + } } } @@ -347,18 +359,18 @@ void test2() { void test_3d_classes(std::vector> *data) { const int N = data->size(); const double R = 0.1; // radius of cluster - int i; + int i = 0; const int num_classes = 8; - const double centres[][3] = { + const std::array, num_classes> centres = { // 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 + std::array({.5, .5, .5}), // centre of class 0 + std::array({.5, .5, -.5}), // centre of class 1 + std::array({.5, -.5, .5}), // centre of class 2 + std::array({.5, -.5, -.5}), // centre of class 3 + std::array({-.5, .5, .5}), // centre of class 4 + std::array({-.5, .5, -.5}), // centre of class 5 + std::array({-.5, -.5, .5}), // centre of class 6 + std::array({-.5, -.5, -.5}) // centre of class 7 }; #ifdef _OPENMP @@ -400,24 +412,26 @@ void test_3d_classes(std::vector> *data) { * output](https://raw.githubusercontent.com/TheAlgorithms/C-Plus-Plus/docs/images/machine_learning/kohonen/test3.svg) */ void test3() { - int j, N = 200; + int j = 0, 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 + 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++) + for (j = 0; j < features; j++) { // preallocate with random initial weights W[i][j] = _random(-1, 1); + } } } diff --git a/machine_learning/ordinary_least_squares_regressor.cpp b/machine_learning/ordinary_least_squares_regressor.cpp index 896504e20..0c865761b 100644 --- a/machine_learning/ordinary_least_squares_regressor.cpp +++ b/machine_learning/ordinary_least_squares_regressor.cpp @@ -25,9 +25,10 @@ std::ostream &operator<<(std::ostream &out, const char separator = ' '; for (size_t row = 0; row < v.size(); row++) { - for (size_t col = 0; col < v[row].size(); col++) + 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; } @@ -42,9 +43,10 @@ std::ostream &operator<<(std::ostream &out, std::vector const &v) { const int width = 15; const char separator = ' '; - for (size_t row = 0; row < v.size(); row++) + for (size_t row = 0; row < v.size(); row++) { out << std::left << std::setw(width) << std::setfill(separator) << v[row]; + } return out; } @@ -57,9 +59,11 @@ 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) + for (size_t i = 0; i < N; i++) { + if (A[i].size() != N) { return false; + } + } return true; } @@ -90,8 +94,9 @@ std::vector> operator*(std::vector> const &A, 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++) + for (size_t j = 0; j < B.size(); j++) { v[col] += A[row][j] * B[j][col]; + } } result[row] = v; } @@ -154,8 +159,9 @@ std::vector operator*(std::vector const &A, float const scalar) { 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); + } return result; } @@ -226,8 +232,9 @@ std::vector> get_inverse( 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++) + for (size_t col = 0; col < N; col++) { inverse[row][col] = (row == col) ? 1.f : 0.f; + } } if (!is_square(A)) { @@ -239,8 +246,9 @@ std::vector> get_inverse( std::vector> temp(N); for (size_t row = 0; row < N; row++) { std::vector v(N); - for (size_t col = 0; col < N; col++) + for (size_t col = 0; col < N; col++) { v[col] = static_cast(A[row][col]); + } temp[row] = v; } @@ -267,13 +275,14 @@ std::vector> get_inverse( } // set diagonal to 1 - float divisor = static_cast(temp[row][row]); + auto 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) + if (row2 == row) { continue; + } float factor = temp[row2][row]; temp[row2] = temp[row2] - factor * temp[row]; inverse[row2] = inverse[row2] - factor * inverse[row]; @@ -313,9 +322,10 @@ 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++) + 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) @@ -347,8 +357,9 @@ std::vector predict_OLS_regressor(std::vector> const &X, 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++) + for (size_t cols = 0; cols < X[0].size(); cols++) { result[rows] += beta[cols] * X[rows][cols]; + } } // Nx1 return result; @@ -375,8 +386,9 @@ void ols_test() { // predicted regression outputs std::vector out1 = predict_OLS_regressor(test_data1, beta1); // compare predicted results are within +-0.01 limit of expected - for (size_t rows = 0; rows < out1.size(); rows++) + for (size_t rows = 0; rows < out1.size(); rows++) { assert(std::abs(out1[rows] - expected1[rows]) < 0.01); + } std::cout << "passed\n"; /* test function = x^3 + x^2 - 100 */ @@ -396,8 +408,9 @@ void ols_test() { // predicted regression outputs std::vector out2 = predict_OLS_regressor(test_data2, beta2); // compare predicted results are within +-0.01 limit of expected - for (size_t rows = 0; rows < out2.size(); rows++) + for (size_t rows = 0; rows < out2.size(); rows++) { assert(std::abs(out2[rows] - expected2[rows]) < 0.01); + } std::cout << "passed\n"; std::cout << std::endl; // ensure test results are displayed on screen @@ -410,7 +423,7 @@ void ols_test() { int main() { ols_test(); - size_t N, F; + size_t N = 0, F = 0; std::cout << "Enter number of features: "; // number of features = columns @@ -429,9 +442,10 @@ int main() { 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++) + 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]; @@ -440,7 +454,7 @@ int main() { std::vector beta = fit_OLS_regressor(data, Y); std::cout << std::endl << std::endl << "beta:" << beta << std::endl; - size_t T; + size_t T = 0; std::cout << "Enter number of test samples: "; // number of test sample inputs std::cin >> T; diff --git a/numerical_methods/newton_raphson_method.cpp b/numerical_methods/newton_raphson_method.cpp index 7597f1b8a..17147e0be 100644 --- a/numerical_methods/newton_raphson_method.cpp +++ b/numerical_methods/newton_raphson_method.cpp @@ -17,8 +17,8 @@ #include #include -#define EPSILON 1e-10 ///< system accuracy limit -#define MAX_ITERATIONS INT16_MAX ///< Maximum number of iterations to check +constexpr double EPSILON = 1e-10; ///< system accuracy limit +constexpr int16_t MAX_ITERATIONS = INT16_MAX; ///< Maximum number of iterations /** define \f$f(x)\f$ to find root for. * Currently defined as: @@ -44,8 +44,8 @@ static double eq_der(double i) { int main() { std::srand(std::time(nullptr)); // initialize randomizer - double z, c = std::rand() % 100, m, n; - int i; + double z = NAN, c = std::rand() % 100, m = NAN, n = NAN; + int i = 0; std::cout << "\nInitial approximation: " << c; @@ -57,8 +57,9 @@ int main() { z = c - (m / n); c = z; - if (std::abs(m) < EPSILON) // stoping criteria + if (std::abs(m) < EPSILON) { // stoping criteria break; + } } std::cout << "\n\nRoot: " << z << "\t\tSteps: " << i << std::endl; diff --git a/numerical_methods/ode_forward_euler.cpp b/numerical_methods/ode_forward_euler.cpp index a4455c57a..5e4dda31b 100644 --- a/numerical_methods/ode_forward_euler.cpp +++ b/numerical_methods/ode_forward_euler.cpp @@ -54,8 +54,8 @@ 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 + (*dy)[0] = (*y)[1]; // x dot // NOLINT + (*dy)[1] = -omega * omega * (*y)[0]; // y dot // NOLINT } /** @@ -83,10 +83,10 @@ void exact_solution(const double &x, std::valarray *y) { * @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, +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; + *y += *dy * dx; } /** @@ -101,7 +101,7 @@ void forward_euler_step(const double dx, const double &x, */ double forward_euler(double dx, double x0, double x_max, std::valarray *y, bool save_to_file = false) { - std::valarray dy = y[0]; + std::valarray dy = *y; std::ofstream fp; if (save_to_file) { @@ -122,9 +122,9 @@ double forward_euler(double dx, double x0, double x_max, // write to file fp << x << ","; for (int i = 0; i < L - 1; i++) { - fp << y[0][i] << ","; + fp << y[0][i] << ","; // NOLINT } - fp << y[0][L - 1] << "\n"; + fp << y[0][L - 1] << "\n"; // NOLINT } forward_euler_step(dx, x, y, &dy); // perform integration @@ -133,8 +133,9 @@ double forward_euler(double dx, double x0, double x_max, /* end of integration */ std::clock_t t2 = std::clock(); - if (fp.is_open()) + if (fp.is_open()) { fp.close(); + } return static_cast(t2 - t1) / CLOCKS_PER_SEC; } @@ -153,7 +154,7 @@ 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::valarray y(Y0); std::ofstream fp("exact.csv", std::ostream::out); if (!fp.is_open()) { @@ -166,9 +167,9 @@ void save_exact_solution(const double &X0, const double &X_MAX, do { fp << x << ","; for (int i = 0; i < y.size() - 1; i++) { - fp << y[i] << ","; + fp << y[i] << ","; // NOLINT } - fp << y[y.size() - 1] << "\n"; + fp << y[y.size() - 1] << "\n"; // NOLINT exact_solution(x, &y); @@ -186,10 +187,10 @@ void save_exact_solution(const double &X0, const double &X_MAX, * 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; + 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 = NAN; if (argc == 1) { std::cout << "\nEnter the step size: "; From dc4a72c4181ee000cfdfede684c089adbc3a0774 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Mon, 13 Jul 2020 08:07:10 -0400 Subject: [PATCH 268/271] fix doc comment block --- data_structures/skip_list.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index b1b24ea20..39dda5ce6 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -181,7 +181,7 @@ class SkipList { } } - /* + /** * Display skip list level */ void displayList() { From eefe46688deb4197d14a7d123135037c7888a304 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Mon, 13 Jul 2020 08:07:44 -0400 Subject: [PATCH 269/271] main function must return --- data_structures/skip_list.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/data_structures/skip_list.cpp b/data_structures/skip_list.cpp index 39dda5ce6..cc679a31c 100644 --- a/data_structures/skip_list.cpp +++ b/data_structures/skip_list.cpp @@ -216,4 +216,6 @@ int main() { } lst.displayList(); + + return 0; } From 076d156302cc93101eb56958c1cbd9d5829a4251 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 13 Jul 2020 13:34:13 +0000 Subject: [PATCH 270/271] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index bc007bc5f..57a1b1c13 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -33,6 +33,7 @@ * [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) + * [Skip List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structures/skip_list.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) From cac5fbe4aad104140f792a4a4ae72cc6084e2041 Mon Sep 17 00:00:00 2001 From: Deep Raval Date: Sat, 18 Jul 2020 03:57:40 +0530 Subject: [PATCH 271/271] feat: add Bogo Sort (#952) * Added Bogo Sort * Changed code according to guidelines * Added Comments and example * Improved code quality * Added range based loop and included cassert * Changed Vectors to Array * Added const to vector arg and now returning sorted array * Changed vector to array and changed description format * Added namespace sorting, Function description and tests * Update sorting/Bogo_Sort.cpp Co-authored-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> * Replaced Shuffle with std::random_shuffle * Renamed filename to smallercase, Added shuffle for ref and updated bracket styling * Added missing ')' * updating DIRECTORY.md * Added spaces in single line comments * Added Spaces * Update sorting/bogo_sort.cpp Co-authored-by: David Leal Co-authored-by: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: David Leal --- DIRECTORY.md | 1 + sorting/bogo_sort.cpp | 115 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 116 insertions(+) create mode 100644 sorting/bogo_sort.cpp diff --git a/DIRECTORY.md b/DIRECTORY.md index 57a1b1c13..cd47fe955 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -215,6 +215,7 @@ ## Sorting * [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) + * [Bogo Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/bogo_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) diff --git a/sorting/bogo_sort.cpp b/sorting/bogo_sort.cpp new file mode 100644 index 000000000..a7dfd8496 --- /dev/null +++ b/sorting/bogo_sort.cpp @@ -0,0 +1,115 @@ +/** + * @file + * @brief Implementation of [Bogosort algorithm](https://en.wikipedia.org/wiki/Bogosort) + * + * @details + * In computer science, bogosort (also known as permutation sort, stupid sort, slowsort, + * shotgun sort, random sort, monkey sort, bobosort or shuffle sort) is a highly inefficient + * sorting algorithm based on the generate and test paradigm. Two versions of this algorithm + * exist: a deterministic version that enumerates all permutations until it hits a sorted one, + * and a randomized version that randomly permutes its input.Randomized version is implemented here. + * + * Algorithm - + * + * Shuffle the array untill array is sorted. + * + */ +#include +#include +#include +#include + + +/** + * @namespace sorting + * @brief Sorting algorithms + */ +namespace sorting { +/** + * Function to shuffle the elements of an array. (for reference) + * @tparam T typename of the array + * @tparam N length of array + * @param arr array to shuffle + * @returns new array with elements shuffled from a given array + */ +template +std::array shuffle (std::array arr) { + for (int i = 0; i < N; i++) { + // Swaps i'th index with random index (less than array size) + std::swap(arr[i], arr[std::rand() % N]); + } + return arr; +} +/** + * Implement randomized Bogosort algorithm and sort the elements of a given array. + * @tparam T typename of the array + * @tparam N length of array + * @param arr array to sort + * @returns new array with elements sorted from a given array + */ +template +std::array randomized_bogosort (std::array arr) { + // Untill array is not sorted + while (!std::is_sorted(arr.begin(), arr.end())) { + std::random_shuffle(arr.begin(), arr.end());// Shuffle the array + } + return arr; +} + +} // namespace sorting + +/** + * Function to display array on screen + * @tparam T typename of the array + * @tparam N length of array + * @param arr array to display + */ +template +void show_array (const std::array &arr) { + for (int x : arr) { + std::cout << x << ' '; + } + std::cout << '\n'; +} + +/** + * Function to test above algorithm + */ +void test() { + // Test 1 + std::array arr1; + for (int &x : arr1) { + x = std::rand() % 100; + } + std::cout << "Original Array : "; + show_array(arr1); + arr1 = sorting::randomized_bogosort(arr1); + std::cout << "Sorted Array : "; + show_array(arr1); + assert(std::is_sorted(arr1.begin(), arr1.end())); + // Test 2 + std::array arr2; + for (int &x : arr2) { + x = std::rand() % 100; + } + std::cout << "Original Array : "; + show_array(arr2); + arr2 = sorting::randomized_bogosort(arr2); + std::cout << "Sorted Array : "; + show_array(arr2); + assert(std::is_sorted(arr2.begin(), arr2.end())); +} + +/** Driver Code */ +int main() { + // Testing + test(); + // Example Usage + std::array arr = {3, 7, 10, 4, 1}; // Defining array which we want to sort + std::cout << "Original Array : "; + show_array(arr); + arr = sorting::randomized_bogosort(arr); // Callling bogo sort on it + std::cout << "Sorted Array : "; + show_array(arr); // Printing sorted array + return 0; +}