Algorithms_in_C++ 1.0.0
Set of algorithms implemented in C++.
Loading...
Searching...
No Matches
CONTRIBUTION GUIDELINES

Before contributing

Welcome to TheAlgorithms/C-Plus-Plus! Before submitting pull requests, please make sure that you have read the whole guidelines. If you have any doubts about this contribution guide, please open an issue or ask on our Discord server, and clearly state your concerns.

Contributing

Maintainer/reviewer

Please check the reviewer code file for maintainers and reviewers.

Contributor

Being a contributor at The Algorithms, we request you to follow the points mentioned below:

  • You did your own work.
    • No plagiarism is allowed. Any plagiarized work will not be merged.
  • Your work will be distributed under the MIT License once your pull request has been merged.
  • Please follow the repository guidelines and standards mentioned below.

New implementation New implementations are welcome!

You can add new algorithms or data structures that are not present in the repository or that can improve the old implementations (documentation, improving test cases, removing bugs, or in any other reasonable sense)

Issues Please avoid opening issues asking to be "assigned” to a particular algorithm. This merely creates unnecessary noise for maintainers. Instead, please submit your implementation in a pull request, and it will be evaluated by project maintainers. @subsection autotoc_md26 Making Changes @subsubsection autotoc_md27 Code - Please use the directory structure of the repository. - Make sure the file extensions are <tt>*.hpp</tt>, <tt>*.h</tt> or <tt>*.cpp</tt>. - Don't use **<tt>bits/stdc++.h</tt>** because this is quite Linux-specific and slows down the compilation process. - Organize your code using **<tt>struct</tt>**, **<tt>class</tt>**, and/or **<tt>namespace</tt>** keywords. - If an implementation of the algorithm already exists, please refer to the @ref "file-name-guidelines" "file-name section below". - You can suggest reasonable changes to existing algorithms. - 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 <a href="https://cmake.org/" target="_blank" ><strong>CMake</strong></a> on all the pull requests, so please be sure that your code passes before submitting. - Please conform to <a href="https://www.doxygen.nl/manual/docblocks.html" target="_blank" >Doxygen</a> standards and document the code as much as possible. This not only facilitates the readers but also generates the correct info on the website. - <strong>Be consistent in the use of these guidelines.</strong> @subsubsection autotoc_md28 Documentation - Make sure you put useful comments in your code. Do not comment on obvious things. - 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 must not contain grammatical errors. - Do not update <a href="https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/README.md" target="_blank" ><tt>README.md</tt></a> along with other changes. First, create an issue and then link to that issue in your pull request to suggest specific changes required to <a href="https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/README.md" target="_blank" ><tt>README.md</tt></a>. - The repository follows <a href="https://www.doxygen.nl/manual/docblocks.html" target="_blank" >Doxygen</a> standards and auto-generates the <a href="https://thealgorithms.github.io/C-Plus-Plus" target="_blank" >repository website</a>. Please ensure the code is documented in this structure. A sample implementation is given below. @subsubsection autotoc_md29 Test - Make sure to add examples and test cases in your <tt>main()</tt> function. - If you find an 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 <tt>test()</tt> functions that will invoke the algorithm implementation on random test data with the expected output. Use the <tt>assert()</tt> function to confirm that the tests will pass. Requires including the <tt>cassert</tt> library. - Test cases should fully verify that your program works as expected. Rather than asking the user for input, it's best to make sure the given output is the correct output. @paragraph autotoc_md30 Self-test examples 1. <a href="https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/quick_sort.cpp#L137" target="_blank" >Quick sort</a> testing (complex). @icode{cpp} // Let's make sure the array of numbers is ordered after calling the function. std::vector<uint64_t> arr = {5, 3, 8, 12, 14, 16, 28, 96, 2, 5977}; std::vector<uint64_t> arr_sorted = sorting::quick_sort::quick_sort( arr, 0, int(std::end(arr) - std::begin(arr)) - 1); assert(std::is_sorted(std::begin(arr_sorted), std::end(arr_sorted))); @endicode 2. <a href="https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/subset_sum.cpp#L58" target="_blank" >Subset Sum</a> testing (medium). @icode{cpp} std::vector<int32_t> array1 = {-7, -3, -2, 5, 8}; // input array assert(backtracking::subset_sum::number_of_subsets(0, array1) == 2); // first argument in subset_sum function is the required sum and // second is the input array @endicode 3. Small C++ program that showcases and explains the use of tests. @icode{cpp} #include <iostream> /// for IO operations #include <vector> /// for std::vector #include <cassert> /// for assert /** * @brief Verifies if the given array * contains the given number on it. * @tparam T the type of array (e.g., `int`, `float`, etc.) * @param arr the array to be used for checking * @param number the number to check if it's inside the array * @return false if the number was NOT found in the array * @return true if the number WAS found in the array */ template <typename T> bool is_number_on_array(const std::vector<T> &arr, const int &number) { for (int i = 0; i < sizeof(arr) / sizeof(int); i++) { if (arr[i] == number) { return true; } else { // Number not in the current index, keep searching. } } return false; } /** * @brief Self-test implementations * @returns void */ static void tests() { std::vector<int> arr = { 9, 14, 21, 98, 67 }; assert(is_number_on_array(arr, 9) == true); assert(is_number_on_array(arr, 4) == false); assert(is_number_on_array(arr, 98) == true); assert(is_number_on_array(arr, 512) == false); std::cout << "All tests have successfully passed!
"; } /** * @brief Main function * @returns 0 on exit */ int main() { tests(); // run self-test implementations return 0; } @endicode @subsubsection autotoc_md31 Typical structure of a program @icode{cpp} /** * @file * @brief Add one-line description here. Should contain a Wikipedia * link or another source explaining the algorithm/implementation. * @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 <cassert> /// for assert #include /// for `some function here` /** * @namespace * @brief <namespace description> */ namespace name { /** * @brief Class documentation */ class class_name { private: int variable; ///< short info of this variable char *message; ///< short info public: // other members should be also documented as below } /** * @brief 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<class T> bool func(int param1, T param2) { // function statements here if (/*something bad*/) { return false; } return true; } } // namespace name /** * @brief Self-test implementations * @returns void */ static void test() { /* descriptions of the following test */ assert(func(...) == ...); // this ensures that the algorithm works as expected // can have multiple checks // this lets the user know that the tests have passed std::cout << "All tests have successfully passed!
"; } /** * @brief Main function * @param argc commandline argument count (ignored) * @param argv commandline array of arguments (ignored) * @returns 0 on exit */ int main(int argc, char *argv[]) { test(); // run self-test implementations // code here return 0; } @endicode @subsubsection autotoc_md32 File Name guidelines - Use lowercase words with <tt>"_"</tt> as a separator - For instance @icode{markdown} MyNewCppClass.CPP is incorrect my_new_cpp_class.cpp is correct format @endicode - It will be used to dynamically create a directory of files and implementation. - File name validation will run on Docker to ensure validity. - If an implementation of the algorithm already exists and your version is different from that implemented, please use incremental numeric digit as a suffix. For example: if <tt>median_search.cpp</tt> already exists in the <tt>search</tt> folder, and you are contributing a new implementation, the filename should be <tt>median_search2.cpp</tt>. For a third implementation, <tt>median_search3.cpp</tt>, and so on. @subsubsection autotoc_md33 Directory guidelines - We recommend adding files to existing directories as much as possible. - Use lowercase words with <tt>"_"</tt> as separator ( no spaces or <tt>"-"</tt> allowed ) - For instance @icode{markdown} SomeNew Fancy-Category is incorrect some_new_fancy_category is correct @endicode - Filepaths will be used to dynamically create a directory of our algorithms. - Filepath validation will run on GitHub Actions to ensure compliance. @paragraph autotoc_md34 Integrating CMake in a new directory In case a new directory is 100% required, <tt>CMakeLists.txt</tt> file in the root directory needs to be updated, and a new <tt>CMakeLists.txt</tt> file needs to be created within the new directory. An example of how your new <tt>CMakeLists.txt</tt> file should look like. Note that if there are any extra libraries/setup required, you must include that in this file as well. @icode{cmake} # If necessary, use the RELATIVE flag, otherwise each source file may be listed # with full pathname. The RELATIVE flag makes it easier to extract an executable's name # automatically. file( GLOB APP_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp ) foreach( testsourcefile ${APP_SOURCES} ) string( REPLACE ".cpp" "" testname ${testsourcefile} ) # File type. Example: `.cpp` 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/<foldername>") # Folder name. Do NOT include `<>` endforeach( testsourcefile ${APP_SOURCES} ) @endicode The <tt>CMakeLists.txt</tt> file in the root directory should be updated to include the new directory.\ Include your new directory after the last subdirectory. Example: @icode{cmake} ... add_subdirectory(divide_and_conquer) add_subdirectory(<foldername>) @endicode @subsubsection autotoc_md35 Commit Guidelines - It is recommended to keep your changes grouped logically within individual commits. Maintainers find it easier to understand changes that are logically spilled across multiple commits. Try to modify just one or two files in the same directory. Pull requests that span multiple directories are often rejected. @icode{bash} git add file_xyz.cpp git commit -m "your message" @endicode Examples of commit messages with semantic prefixes: @icode{markdown} fix: xyz algorithm bug feat: add xyx algorithm, class xyz test: add test for xyz algorithm docs: add comments and explanation to xyz algorithm/improve contributing guidelines chore: update Gitpod badge @endicode Common prefixes: - fix: A bug fix - feat: A new feature - docs: Documentation changes - test: Correct existing tests or add new ones - chore: Miscellaneous changes that do not match any of the above. @subsection autotoc_md36 Pull Requests - Checkout our <a href="https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/.github/pull_request_template.md" target="_blank" >pull request template</a> @subsubsection autotoc_md37 Building Locally Before submitting a pull request, build the code locally or using the convenient <a href="https://gitpod.io/#https://github.com/TheAlgorithms/C-Plus-Plus" target="_blank" ><img src="https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod" alt="Gitpod Ready-to-Code"/></a> service. @icode{bash} cmake -B build -S . @endicode @subsubsection autotoc_md38 Static Code Analyzer We use <a href="https://clang.llvm.org/extra/clang-tidy/" target="_blank" ><tt>clang-tidy</tt></a> as a static code analyzer with a configuration in <a href="https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/.clang-tidy" target="_blank" ><tt>.clang-tidy</tt></a>. @icode{bash} clang-tidy --fix --quiet -p build subfolder/file_to_check.cpp -- @endicode @subsubsection autotoc_md39 Code Formatter <a href="https://clang.llvm.org/docs/ClangFormat.html" target="_blank" ><tt>clang-format</tt></a> is used for code formatting. - Installation (only needs to be installed once.) - Mac (using home-brew): <tt>brew install clang-format</tt> - Mac (using macports): <tt>sudo port install clang-10 +analyzer</tt> - Windows (MSYS2 64-bit): <tt>pacman -S mingw-w64-x86_64-clang-tools-extra</tt> - Linux (Debian): <tt>sudo apt-get install clang-format-10 clang-tidy-10</tt> - Running (all platforms): <tt>clang-format -i -style="file" my_file.cpp</tt> @subsubsection autotoc_md40 GitHub Actions - Enable GitHub Actions on your fork of the repository. After enabling, it will execute <tt>clang-tidy</tt> and <tt>clang-format</tt> after every push (not a commit). - Click on the tab "Actions", then click on the big green button to enable it. <img src="https://user-images.githubusercontent.com/51391473/94609466-6e925100-0264-11eb-9d6f-3706190eab2b.png" alt="GitHub Actions"/>

  • The result can create another commit if the actions made any changes on your behalf.
  • Hence, it is better to wait and check the results of GitHub Actions after every push.
  • Run git pull in your local clone if these actions made many changes to avoid merge conflicts.

Most importantly,

  • Happy coding!