From 51ddc83531d6153d2a1613c26d350f1afe688f74 Mon Sep 17 00:00:00 2001 From: nooneknows <157999171+nooneknowspeter@users.noreply.github.com> Date: Sat, 15 Aug 2026 23:02:30 -0400 Subject: [PATCH 1/6] style: treefmt --- exercises/00_intro/01_intro.cpp | 31 ++- exercises/00_intro/02_intro.cpp | 12 +- exercises/01_variables/01_variables.cpp | 14 +- exercises/01_variables/02_variables.cpp | 14 +- exercises/01_variables/03_variables.cpp | 20 +- exercises/01_variables/04_variables.cpp | 9 +- exercises/01_variables/05_variables.cpp | 18 +- exercises/02_functions/01_functions.cpp | 23 +-- exercises/02_functions/02_functions.cpp | 11 +- exercises/02_functions/03_functions.cpp | 62 +++--- exercises/02_functions/04_functions.cpp | 65 +++--- exercises/02_functions/05_functions.cpp | 10 +- exercises/02_functions/06_functions.cpp | 29 +-- exercises/02_functions/07_functions.cpp | 48 ++--- exercises/02_functions/08_functions.cpp | 36 ++-- exercises/02_functions/09_functions.cpp | 27 +-- exercises/02_functions/10_functions.cpp | 28 ++- exercises/03_control-flow/01_control-flow.cpp | 84 +++----- exercises/03_control-flow/02_control-flow.cpp | 80 ++++---- exercises/03_control-flow/03_control-flow.cpp | 78 ++++--- exercises/03_control-flow/04_control-flow.cpp | 83 ++++---- exercises/04_primitives/01_primitives.cpp | 16 +- exercises/04_primitives/02_primitives.cpp | 45 ++--- exercises/04_primitives/03_primitives.cpp | 50 ++--- .../05_type-coercion/01_type-coercion.cpp | 57 ++---- .../05_type-coercion/02_type-coercion.cpp | 41 ++-- .../05_type-coercion/03_type-coercion.cpp | 30 +-- exercises/06_strings/01_strings.cpp | 90 ++++----- exercises/06_strings/02_strings.cpp | 82 ++++---- exercises/06_strings/03_strings.cpp | 88 ++++---- exercises/06_strings/04_strings.cpp | 75 +++---- exercises/07_containers/01_containers.cpp | 71 +++---- exercises/07_containers/02_containers.cpp | 63 +++--- exercises/07_containers/03_containers.cpp | 69 +++---- exercises/07_containers/04_containers.cpp | 62 +++--- exercises/07_containers/05_containers.cpp | 79 ++++---- exercises/07_containers/06_containers.cpp | 109 +++++----- exercises/08_headers/01_headers.cpp | 14 +- exercises/08_headers/src/math_utils.cpp | 5 +- exercises/09_structs/01_structs.cpp | 38 ++-- exercises/10_enums/01_enums.cpp | 57 +++--- exercises/11_classes/01_classes.cpp | 47 ++--- exercises/12_generics/01_generics.cpp | 57 +++--- exercises/12_generics/02_generics.cpp | 82 +++----- exercises/12_generics/03_generics.cpp | 63 +++--- exercises/13_exceptions/01_exceptions.cpp | 42 ++-- exercises/14_memory/01_memory.cpp | 44 ++-- exercises/15_threads/01_threads.cpp | 42 ++-- .../16_preprocessors/01_preprocessors.cpp | 20 +- .../01_bit-manipulation.cpp | 44 ++-- .../extras_cpp-history/01_cpp-history.cpp | 26 +-- .../extras_development/01_development.cpp | 5 +- exercises/extras_networking/01_networking.cpp | 5 +- solutions/00_intro/01_intro.cpp | 28 ++- solutions/00_intro/02_intro.cpp | 12 +- solutions/01_variables/01_variables.cpp | 24 +-- solutions/01_variables/02_variables.cpp | 14 +- solutions/01_variables/03_variables.cpp | 20 +- solutions/01_variables/04_variables.cpp | 38 ++-- solutions/01_variables/05_variables.cpp | 18 +- solutions/02_functions/01_functions.cpp | 46 ++--- solutions/02_functions/02_functions.cpp | 47 +++-- solutions/02_functions/03_functions.cpp | 62 +++--- solutions/02_functions/04_functions.cpp | 65 +++--- solutions/02_functions/05_functions.cpp | 10 +- solutions/02_functions/06_functions.cpp | 29 +-- solutions/02_functions/07_functions.cpp | 57 +++--- solutions/02_functions/08_functions.cpp | 36 ++-- solutions/02_functions/09_functions.cpp | 45 ++--- solutions/02_functions/10_functions.cpp | 30 ++- solutions/03_control-flow/01_control-flow.cpp | 80 +++----- solutions/03_control-flow/02_control-flow.cpp | 82 ++++---- solutions/03_control-flow/03_control-flow.cpp | 78 ++++--- solutions/03_control-flow/04_control-flow.cpp | 83 ++++---- solutions/04_primitives/01_primitives.cpp | 16 +- solutions/04_primitives/02_primitives.cpp | 45 ++--- solutions/04_primitives/03_primitives.cpp | 46 ++--- .../05_type-coercion/01_type-coercion.cpp | 57 ++---- .../05_type-coercion/02_type-coercion.cpp | 41 ++-- .../05_type-coercion/03_type-coercion.cpp | 30 +-- solutions/06_strings/01_strings.cpp | 90 ++++----- solutions/06_strings/02_strings.cpp | 82 ++++---- solutions/06_strings/03_strings.cpp | 88 ++++---- solutions/06_strings/04_strings.cpp | 71 +++---- solutions/07_containers/01_containers.cpp | 71 +++---- solutions/07_containers/02_containers.cpp | 63 +++--- solutions/07_containers/03_containers.cpp | 69 +++---- solutions/07_containers/04_containers.cpp | 62 +++--- solutions/07_containers/05_containers.cpp | 79 ++++---- solutions/07_containers/06_containers.cpp | 109 +++++----- solutions/08_headers/01_headers.cpp | 14 +- solutions/08_headers/src/math_utils.cpp | 5 +- solutions/09_structs/01_structs.cpp | 38 ++-- solutions/10_enums/01_enums.cpp | 58 +++--- solutions/11_classes/01_classes.cpp | 43 ++-- solutions/12_generics/01_generics.cpp | 57 +++--- solutions/12_generics/02_generics.cpp | 82 +++----- solutions/12_generics/03_generics.cpp | 52 +++-- solutions/13_exceptions/01_exceptions.cpp | 42 ++-- solutions/14_memory/01_memory.cpp | 44 ++-- solutions/15_threads/01_threads.cpp | 42 ++-- .../16_preprocessors/01_preprocessors.cpp | 20 +- .../01_bit-manipulation.cpp | 44 ++-- .../extras_cpp-history/01_cpp-history.cpp | 26 +-- .../extras_development/01_development.cpp | 5 +- solutions/extras_networking/01_networking.cpp | 5 +- src/include/ascii.hpp | 75 +++---- src/include/exercise_iterator.hpp | 34 ++-- src/include/exercise_runner.hpp | 21 +- src/include/file_watcher.hpp | 24 +-- src/include/patch_system.hpp | 21 +- src/include/tui.hpp | 61 +++--- src/include/util.hpp | 21 +- src/tests/test.cpp | 21 +- src/tests/test_exercise_iterator.cpp | 190 +++++++++--------- src/tests/test_tui.cpp | 24 +-- 116 files changed, 2269 insertions(+), 3123 deletions(-) mode change 100755 => 100644 exercises/00_intro/01_intro.cpp mode change 100755 => 100644 exercises/00_intro/02_intro.cpp diff --git a/exercises/00_intro/01_intro.cpp b/exercises/00_intro/01_intro.cpp old mode 100755 new mode 100644 index adba383..3eacaee --- a/exercises/00_intro/01_intro.cpp +++ b/exercises/00_intro/01_intro.cpp @@ -4,23 +4,20 @@ #include -void splashScreen() -{ - std::cout << " _ _ \n"; - std::cout << " | (_) \n"; - std::cout << " ___ _ __ _ __ | |_ _ __ __ _ ___ \n"; - std::cout << " / __| '_ \\| '_ \\| | | '_ \\ / _` / __|\n"; - std::cout << "| (__| |_) | |_) | | | | | | (_| \\__ \\\n"; - std::cout << " \\___| .__/| .__/|_|_|_| |_|\\__, |___/\n"; - std::cout << " | | | | __/ | \n"; - std::cout << " |_| |_| |___/ \n"; - std::cout << " \n"; +void splashScreen() { + std::cout << " _ _ \n"; + std::cout << " | (_) \n"; + std::cout << " ___ _ __ _ __ | |_ _ __ __ _ ___ \n"; + std::cout << " / __| '_ \\| '_ \\| | | '_ \\ / _` / __|\n"; + std::cout << "| (__| |_) | |_) | | | | | | (_| \\__ \\\n"; + std::cout << " \\___| .__/| .__/|_|_|_| |_|\\__, |___/\n"; + std::cout << " | | | | __/ | \n"; + std::cout << " |_| |_| |___/ \n"; + std::cout << " \n"; } -int main() -{ - - // TODO: call the proper function - spalshscreen(); - return 0; +int main() { + // TODO: call the proper function + spalshscreen(); + return 0; } diff --git a/exercises/00_intro/02_intro.cpp b/exercises/00_intro/02_intro.cpp old mode 100755 new mode 100644 index 427c9c8..cb205c3 --- a/exercises/00_intro/02_intro.cpp +++ b/exercises/00_intro/02_intro.cpp @@ -18,13 +18,9 @@ #include -void message() -{ - // TODO: Fix the line of code to print "Hello World!" to the console. - std::_ << "Hello World!"; +void message() { + // TODO: Fix the line of code to print "Hello World!" to the console. + std::_ << "Hello World!"; } -int main() -{ - message(); -} +int main() { message(); } diff --git a/exercises/01_variables/01_variables.cpp b/exercises/01_variables/01_variables.cpp index 3fdf19e..e840faa 100644 --- a/exercises/01_variables/01_variables.cpp +++ b/exercises/01_variables/01_variables.cpp @@ -19,15 +19,11 @@ // TODO: Add the missing module for printing -void variables01() -{ - // TODO: Add the missing keyword - int x{5}; +void variables01() { + // TODO: Add the missing keyword + int x{5}; - std::cout << x; + std::cout << x; } -int main() -{ - variables01(); -} +int main() { variables01(); } diff --git a/exercises/01_variables/02_variables.cpp b/exercises/01_variables/02_variables.cpp index 10d644f..5b05317 100644 --- a/exercises/01_variables/02_variables.cpp +++ b/exercises/01_variables/02_variables.cpp @@ -3,15 +3,11 @@ // #include -void variables02() -{ - // TODO: Add the missing keyword - x{5}; +void variables02() { + // TODO: Add the missing keyword + x{5}; - std::cout << x; + std::cout << x; } -int main() -{ - variables02(); -} +int main() { variables02(); } diff --git a/exercises/01_variables/03_variables.cpp b/exercises/01_variables/03_variables.cpp index 48c364c..e7ad44c 100644 --- a/exercises/01_variables/03_variables.cpp +++ b/exercises/01_variables/03_variables.cpp @@ -14,18 +14,16 @@ #include #include -void variables03() -{ - // TODO: Declare a constant variable with a value and then print it out to stdout. - int FOO{5}; +void variables03() { + // TODO: Declare a constant variable with a value and then print it out to + // stdout. + int FOO{5}; - std::cout << FOO; + std::cout << FOO; - static_assert(std::is_const_v, - "The variable must be a constant."); // NOTE: Ignore this line of code. + static_assert( + std::is_const_v, + "The variable must be a constant."); // NOTE: Ignore this line of code. } -int main() -{ - variables03(); -} +int main() { variables03(); } diff --git a/exercises/01_variables/04_variables.cpp b/exercises/01_variables/04_variables.cpp index 3020657..b790d0f 100644 --- a/exercises/01_variables/04_variables.cpp +++ b/exercises/01_variables/04_variables.cpp @@ -4,11 +4,6 @@ // TODO: Add the missing variable type. x; -void variables04() -{ -} +void variables04() {} -int main() -{ - variables04(); -} +int main() { variables04(); } diff --git a/exercises/01_variables/05_variables.cpp b/exercises/01_variables/05_variables.cpp index a6477f3..63cb5f0 100644 --- a/exercises/01_variables/05_variables.cpp +++ b/exercises/01_variables/05_variables.cpp @@ -6,16 +6,14 @@ // Datatypes can be "inferred" by using the "auto" keyword. #include -int main() -{ - // TODO: Infer the datatype using the "auto" keyword. - // Assign a "truthy" value to compile. - doesAutoWork{true}; +int main() { + // TODO: Infer the datatype using the "auto" keyword. + // Assign a "truthy" value to compile. + doesAutoWork{true}; - std::cout << "doesAutoWork? -> " << doesAutoWork; + std::cout << "doesAutoWork? -> " << doesAutoWork; - if (!doesAutoWork) - { - return 1; - } + if (!doesAutoWork) { + return 1; + } } diff --git a/exercises/02_functions/01_functions.cpp b/exercises/02_functions/01_functions.cpp index c006e51..5a8f0c8 100644 --- a/exercises/02_functions/01_functions.cpp +++ b/exercises/02_functions/01_functions.cpp @@ -8,22 +8,17 @@ #include #include -int function01(int x) -{ - int y{x + 1}; +int function01(int x) { + int y{x + 1}; - // TODO: Return the value of y. - y; + // TODO: Return the value of y. + y; } -TEST_CASE("Functions Function01") -{ - REQUIRE(function01(0) == 1); - REQUIRE(function01(1) == 2); - REQUIRE(function01(2) == 3); +TEST_CASE("Functions Function01") { + REQUIRE(function01(0) == 1); + REQUIRE(function01(1) == 2); + REQUIRE(function01(2) == 3); } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } diff --git a/exercises/02_functions/02_functions.cpp b/exercises/02_functions/02_functions.cpp index 8c09189..f9c5627 100644 --- a/exercises/02_functions/02_functions.cpp +++ b/exercises/02_functions/02_functions.cpp @@ -4,12 +4,9 @@ // https://www.learncpp.com/cpp-tutorial/void-functions-non-value-returning-functions/ // -void function02() -{ -} +void function02() {} -int main() -{ - // TODO: Call the function. - _(); +int main() { + // TODO: Call the function. + _(); } diff --git a/exercises/02_functions/03_functions.cpp b/exercises/02_functions/03_functions.cpp index ed4d5ff..0ae617b 100644 --- a/exercises/02_functions/03_functions.cpp +++ b/exercises/02_functions/03_functions.cpp @@ -24,49 +24,41 @@ // TODO: Add the function datatype and name. // Add two parameters, one that takes in a boolean and the other a float. -voidFunction(bool isTruthy, float randomValue) -{ - try - { - - if (typeid(isTruthy).name() != typeid(bool).name()) - { - throw std::runtime_error("The first parameter is not a boolean.\n"); - } - - if (typeid(randomValue).name() != typeid(float).name()) - { - throw std::runtime_error("The second parameter is not a float.\n"); - } +voidFunction(bool isTruthy, float randomValue) { + try { + if (typeid(isTruthy).name() != typeid(bool).name()) { + throw std::runtime_error("The first parameter is not a boolean.\n"); } - catch (const std::exception &e) - { - std::cout << e.what(); + + if (typeid(randomValue).name() != typeid(float).name()) { + throw std::runtime_error("The second parameter is not a float.\n"); } + } catch (const std::exception& e) { + std::cout << e.what(); + } - // TODO: Implement the additional required logic. - // NOTE: Use the test case as reference. - std::cout << "This is a void function!"; + // TODO: Implement the additional required logic. + // NOTE: Use the test case as reference. + std::cout << "This is a void function!"; } -int main(int argc, char **argv) -{ - // TODO: Call the function and pass in the approriate arguments. - voidFunction(true, 5); +int main(int argc, char** argv) { + // TODO: Call the function and pass in the approriate arguments. + voidFunction(true, 5); - std::cout << "\n\n" << "Testing output begins here\n--------------------------" << "\n"; - return Catch::Session().run(argc, argv); + std::cout << "\n\n" + << "Testing output begins here\n--------------------------" << "\n"; + return Catch::Session().run(argc, argv); } -TEST_CASE("Functions Functions03") -{ - std::stringstream buffer; - std::streambuf *old = std::cout.rdbuf(buffer.rdbuf()); +TEST_CASE("Functions Functions03") { + std::stringstream buffer; + std::streambuf* old = std::cout.rdbuf(buffer.rdbuf()); - // TODO: Call the function and pass in the approriate arguments. - voidFunction(true, 5); + // TODO: Call the function and pass in the approriate arguments. + voidFunction(true, 5); - std::cout.rdbuf(old); - std::string output{buffer.str()}; - REQUIRE(output == "This is a void function!"); + std::cout.rdbuf(old); + std::string output{buffer.str()}; + REQUIRE(output == "This is a void function!"); } diff --git a/exercises/02_functions/04_functions.cpp b/exercises/02_functions/04_functions.cpp index a10db22..388140b 100644 --- a/exercises/02_functions/04_functions.cpp +++ b/exercises/02_functions/04_functions.cpp @@ -5,45 +5,50 @@ // It is the entry point to any and every application/project/piece of software. // // The main() function returns an integer, but some of the exercises you noticed -// that some of them don't return any integer, just like a void function omitting -// the "return" keyword. The main function allows this, it implicitly handles -// the returned value. -// -// However, in the previous cases you may have encountered booleans. When booleans -// are printed to stdout, they appear to be different than "true" and "false", 1 and 0 respectively. -// More on booleans in upcoming exercises. -// -// The main() function does not return a boolean value, it just returns an integer. -// A main() function returning 0 returns "0 errors". Any value other the 0 means an error. -// Explicitly returning 0; { return 0; } is considered good practice in C++ development. -// -// The parameters in the main(int argc, char *argv[]) function are the program's/application's arguments. -// | | -// | can also be char **argv, -// | are arguments as an array of -// | string slices or string literals +// that some of them don't return any integer, just like a void function +// omitting the "return" keyword. The main function allows this, it implicitly +// handles the returned value. +// +// However, in the previous cases you may have encountered booleans. When +// booleans are printed to stdout, they appear to be different than "true" and +// "false", 1 and 0 respectively. More on booleans in upcoming exercises. +// +// The main() function does not return a boolean value, it just returns an +// integer. A main() function returning 0 returns "0 errors". Any value other +// the 0 means an error. Explicitly returning 0; { return 0; } is considered +// good practice in C++ development. +// +// The parameters in the main(int argc, char *argv[]) function are the +// program's/application's arguments. +// | +//| | can also be char **argv, | +//are arguments as an array of | string +//slices or string literals // | -// number of arguments passed into the main function; -// used for iterating the argument array +// number +//of arguments passed into the main function; used for iterating the argument +//array // -// When a compiled program is called, the name of the program or the program executable is the first argument. -// In programs/applications, especially CLI programs that use arguments; ./program arg1 arg2, are also passed to the +// When a compiled program is called, the name of the program or the program +// executable is the first argument. In programs/applications, especially CLI +// programs that use arguments; ./program arg1 arg2, are also passed to the // main() function. // -// You can compile this specific exercise using "zig build exercises -- ./exercises/path/to/exercise/file", -// ensure you pass in the correct path of this file. The binary will be in ./zig-out/bin/cpplings_exercise -// Run it and experiment with the arguments. +// You can compile this specific exercise using "zig build exercises -- +// ./exercises/path/to/exercise/file", ensure you pass in the correct path of +// this file. The binary will be in ./zig-out/bin/cpplings_exercise Run it and +// experiment with the arguments. // -// We also recommend coming back to this exercise and try out the concepts that you will learn in the upcoming -// exercises. +// We also recommend coming back to this exercise and try out the concepts that +// you will learn in the upcoming exercises. // // https://www.learncpp.com/cpp-tutorial/statements-and-the-structure-of-a-program/ // https://www.learncpp.com/cpp-tutorial/command-line-arguments/ #include -int main(int argc, char *argv[]) -{ - // TODO: Print out the argc and argv. - std::_ << "Number of arguments: " << argc << "\n" << "Arguments: " << *argv << std::endl; +int main(int argc, char* argv[]) { + // TODO: Print out the argc and argv. + std::_ << "Number of arguments: " << argc << "\n" + << "Arguments: " << *argv << std::endl; } diff --git a/exercises/02_functions/05_functions.cpp b/exercises/02_functions/05_functions.cpp index 8122f72..6a4e260 100644 --- a/exercises/02_functions/05_functions.cpp +++ b/exercises/02_functions/05_functions.cpp @@ -5,13 +5,7 @@ int add(int x, int y); -int main() -{ - add(1, 2); -} +int main() { add(1, 2); } // TODO: Fix the function to fix the compile error. -float add(int x, int y) -{ - return x + y; -} +float add(int x, int y) { return x + y; } diff --git a/exercises/02_functions/06_functions.cpp b/exercises/02_functions/06_functions.cpp index 7bbe5e9..18ebd7c 100644 --- a/exercises/02_functions/06_functions.cpp +++ b/exercises/02_functions/06_functions.cpp @@ -13,31 +13,18 @@ // TODO: Implement the add function for integers. // NOTE: Use the test cases as reference. -int add(int x, int y) -{ - return x + y; -} +int add(int x, int y) { return x + y; } // TODO: Implement the add function for floats. -add(float x, float y) -{ - return x + y; -} +add(float x, float y) { return x + y; } // TODO: Implement the add function for doubles. -double add(double x, double y) -{ - return x + y; -} +double add(double x, double y) { return x + y; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Functions Functions06") -{ - REQUIRE(add(1, 1) == 2); - REQUIRE(add(5.0f, 5.0f) == 10.0f); - REQUIRE(add(100.555555, 100.555555) == 201.11111); +TEST_CASE("Functions Functions06") { + REQUIRE(add(1, 1) == 2); + REQUIRE(add(5.0f, 5.0f) == 10.0f); + REQUIRE(add(100.555555, 100.555555) == 201.11111); } diff --git a/exercises/02_functions/07_functions.cpp b/exercises/02_functions/07_functions.cpp index 7063962..84a41ca 100644 --- a/exercises/02_functions/07_functions.cpp +++ b/exercises/02_functions/07_functions.cpp @@ -11,41 +11,33 @@ // TODO: Implement the recursive fibonacci function. // NOTE: Use the test case as reference. -fibonacci(int n) -{ - if (n == 0 || n == 1) - { - return n; - } - - return fibonacci(n - 1) + fibonacci(n - 2); -} +fibonacci(int n) { + if (n == 0 || n == 1) { + return n; + } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); + return fibonacci(n - 1) + fibonacci(n - 2); } -TEST_CASE("Functions Functions07") -{ - std::stringstream buffer; - std::streambuf *old = std::cout.rdbuf(buffer.rdbuf()); +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } - for (int n = 0; n <= 10; ++n) - { - if (n == 10) - { - std::cout << fibonacci(n) << ",..." << std::endl; - continue; - } +TEST_CASE("Functions Functions07") { + std::stringstream buffer; + std::streambuf* old = std::cout.rdbuf(buffer.rdbuf()); - std::cout << fibonacci(n) << ", "; + for (int n = 0; n <= 10; ++n) { + if (n == 10) { + std::cout << fibonacci(n) << ",..." << std::endl; + continue; } - std::cout.rdbuf(old); - std::string output{buffer.str()}; + std::cout << fibonacci(n) << ", "; + } + + std::cout.rdbuf(old); + std::string output{buffer.str()}; - REQUIRE(output == "0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,...\n"); + REQUIRE(output == "0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,...\n"); - std::cout << "\n" << output << "\n"; + std::cout << "\n" << output << "\n"; } diff --git a/exercises/02_functions/08_functions.cpp b/exercises/02_functions/08_functions.cpp index f68eff5..e23766a 100644 --- a/exercises/02_functions/08_functions.cpp +++ b/exercises/02_functions/08_functions.cpp @@ -6,7 +6,8 @@ // // Lambda syntax: [capture clause](parameters) -> return_type { body } // -// - Capture clause []: specifies which variables from the enclosing scope to capture +// - Capture clause []: specifies which variables from the enclosing scope to +// capture // - Parameters (): like regular function parameters // - Return type ->: can be omitted for type inference // - Body {}: the actual code @@ -32,27 +33,22 @@ auto isEven = [](int n) -> _ { return n % 2 == 0; }; // Use the 'auto' keyword for the return type inference. auto doubleIt = [](int n) { return n * 2; }; -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Functions Functions08") -{ - REQUIRE(isEven(2)); - REQUIRE(isEven(4)); - REQUIRE_FALSE(isEven(3)); - REQUIRE_FALSE(isEven(5)); +TEST_CASE("Functions Functions08") { + REQUIRE(isEven(2)); + REQUIRE(isEven(4)); + REQUIRE_FALSE(isEven(3)); + REQUIRE_FALSE(isEven(5)); - REQUIRE(doubleIt(5) == 10); - REQUIRE(doubleIt(0) == 0); - REQUIRE(doubleIt(-3) == -6); + REQUIRE(doubleIt(5) == 10); + REQUIRE(doubleIt(0) == 0); + REQUIRE(doubleIt(-3) == -6); } -TEST_CASE("Functions Functions08_Capture") -{ - // TODO: Create a lambda that captures 'multiplier' by value. - const int multiplier = 3; - auto multiplyByGlobal = [=](int n) { return n * multiplier; }; - REQUIRE(multiplyByGlobal(4) == 12); +TEST_CASE("Functions Functions08_Capture") { + // TODO: Create a lambda that captures 'multiplier' by value. + const int multiplier = 3; + auto multiplyByGlobal = [=](int n) { return n * multiplier; }; + REQUIRE(multiplyByGlobal(4) == 12); } diff --git a/exercises/02_functions/09_functions.cpp b/exercises/02_functions/09_functions.cpp index bffbe1e..eef2b9c 100644 --- a/exercises/02_functions/09_functions.cpp +++ b/exercises/02_functions/09_functions.cpp @@ -9,31 +9,26 @@ #include // C-style variable arguments using va_list. -// Note: This approach is NOT type-safe. Prefer variadic templates (exercise 10). +// Note: This approach is NOT type-safe. Prefer variadic templates (exercise +// 10). // TODO: Implement sumInts using va_list. // The first argument (count) specifies how many integers follow. // Use va_start, va_arg, and va_end macros from . -int sumInts(int count, ...) -{ - // TODO: Implement this function +int sumInts(int count, ...) { + // TODO: Implement this function } // TODO (optional): Implement printFormatted using va_list. // Uses printf-style format string with variable arguments. -void printFormatted(const char *format, ...) -{ - // Hint: Use vprintf instead of printf for va_list +void printFormatted(const char* format, ...) { + // Hint: Use vprintf instead of printf for va_list } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Functions Functions09") -{ - REQUIRE(sumInts(3, 1, 2, 3) == 6); - REQUIRE(sumInts(5, 1, 2, 3, 4, 5) == 15); - REQUIRE(sumInts(1, 42) == 42); +TEST_CASE("Functions Functions09") { + REQUIRE(sumInts(3, 1, 2, 3) == 6); + REQUIRE(sumInts(5, 1, 2, 3, 4, 5) == 15); + REQUIRE(sumInts(1, 42) == 42); } diff --git a/exercises/02_functions/10_functions.cpp b/exercises/02_functions/10_functions.cpp index be7b4be..b4a29a3 100644 --- a/exercises/02_functions/10_functions.cpp +++ b/exercises/02_functions/10_functions.cpp @@ -34,28 +34,24 @@ // - Undefined behavior if types don't match // Base case: single argument - just return it. -template T sum(T value) -{ - return value; +template +T sum(T value) { + return value; } // TODO: Implement the recursive case for sum. // The function should add the first argument to the sum of the rest. // Hint: Use template parameter packs (typename... Args) and recursion. -template T sum(T first, Args... args) -{ - // TODO: Return first + sum(args...) +template +T sum(T first, Args... args) { + // TODO: Return first + sum(args...) } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Functions Functions10") -{ - REQUIRE(sum(1, 2, 3) == 6); - REQUIRE(sum(1, 2, 3, 4, 5) == 15); - REQUIRE(sum(10) == 10); - REQUIRE(sum(1.5, 2.5, 3.0) == 7.0); +TEST_CASE("Functions Functions10") { + REQUIRE(sum(1, 2, 3) == 6); + REQUIRE(sum(1, 2, 3, 4, 5) == 15); + REQUIRE(sum(10) == 10); + REQUIRE(sum(1.5, 2.5, 3.0) == 7.0); } diff --git a/exercises/03_control-flow/01_control-flow.cpp b/exercises/03_control-flow/01_control-flow.cpp index e61f0d1..4ec023b 100644 --- a/exercises/03_control-flow/01_control-flow.cpp +++ b/exercises/03_control-flow/01_control-flow.cpp @@ -24,62 +24,42 @@ // - 70-79: return 'C' // - 60-69: return 'D' // - below 60: return 'F' -char getGrade(int score) -{ - if (score = 90) - { - return 'A'; - } - else if (score >= 80) - { - return 'B'; - } - else if (score >= 70) - { - return 'C'; - } - else if (score >= 60) - { - return 'D'; - } - else - { - return 'F'; - } +char getGrade(int score) { + if (score = 90) { + return 'A'; + } else if (score >= 80) { + return 'B'; + } else if (score >= 70) { + return 'C'; + } else if (score >= 60) { + return 'D'; + } else { + return 'F'; + } } -// TODO: Implement a function that checks if a number is positive, negative, or zero. -// Return 1 for positive, -1 for negative, 0 for zero. -int checkNumber(int num) -{ - if (num > 0) - { - return 1; - } - else if (num < 0) - { - return -1; - } - else - { - return 0; - } +// TODO: Implement a function that checks if a number is positive, negative, or +// zero. Return 1 for positive, -1 for negative, 0 for zero. +int checkNumber(int num) { + if (num > 0) { + return 1; + } else if (num < 0) { + return -1; + } else { + return 0; + } } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("ControlFlow ControlFlow01") -{ - REQUIRE(getGrade(95) == 'A'); - REQUIRE(getGrade(85) == 'B'); - REQUIRE(getGrade(75) == 'C'); - REQUIRE(getGrade(65) == 'D'); - REQUIRE(getGrade(55) == 'F'); +TEST_CASE("ControlFlow ControlFlow01") { + REQUIRE(getGrade(95) == 'A'); + REQUIRE(getGrade(85) == 'B'); + REQUIRE(getGrade(75) == 'C'); + REQUIRE(getGrade(65) == 'D'); + REQUIRE(getGrade(55) == 'F'); - REQUIRE(checkNumber(5) == 1); - REQUIRE(checkNumber(-3) == -1); - REQUIRE(checkNumber(0) == 0); + REQUIRE(checkNumber(5) == 1); + REQUIRE(checkNumber(-3) == -1); + REQUIRE(checkNumber(0) == 0); } diff --git a/exercises/03_control-flow/02_control-flow.cpp b/exercises/03_control-flow/02_control-flow.cpp index 860730b..b758f74 100644 --- a/exercises/03_control-flow/02_control-flow.cpp +++ b/exercises/03_control-flow/02_control-flow.cpp @@ -30,78 +30,70 @@ // January: 31, February: 28, March: 31, April: 30, // May: 31, June: 30, July: 31, August: 31, // September: 30, October: 31, November: 30, December: 31 -int getDaysInMonth(int month) -{ - switch (month) - { +int getDaysInMonth(int month) { + switch (month) { case 1 return 31; case 2: - return 28; + return 28; case 3: - return 31; + return 31; case 4: - return 30; + return 30; case 5: - return 31; + return 31; case 6: - return 30; + return 30; case 7: - return 31; + return 31; case 8: - return 31; + return 31; case 9: - return 30; + return 30; case 10: - return 31; + return 31; case 11: - return 30; + return 30; case 12: - return 31; + return 31; default: - return -1; - } + return -1; + } } // TODO: Implement a function that returns the day of the week as a string. // Use a switch statement. // 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", // 5: "Friday", 6: "Saturday", 7: "Sunday" -const char *getDayOfWeek(int day) -{ - switch (day) - { +const char* getDayOfWeek(int day) { + switch (day) { case 1: - return "Monday"; + return "Monday"; case 2: - return "Tuesday"; + return "Tuesday"; case 3: - return "Wednesday"; + return "Wednesday"; case 4: - return "Thursday"; + return "Thursday"; case 5: - return "Friday"; + return "Friday"; case 6: - return "Saturday"; + return "Saturday"; case 7: - return "Sunday"; + return "Sunday"; default: - return "Invalid"; - } + return "Invalid"; + } } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("ControlFlow ControlFlow02") -{ - REQUIRE(getDaysInMonth(1) == 31); - REQUIRE(getDaysInMonth(2) == 28); - REQUIRE(getDaysInMonth(4) == 30); - REQUIRE(getDaysInMonth(12) == 31); - REQUIRE(getDaysInMonth(0) == -1); +TEST_CASE("ControlFlow ControlFlow02") { + REQUIRE(getDaysInMonth(1) == 31); + REQUIRE(getDaysInMonth(2) == 28); + REQUIRE(getDaysInMonth(4) == 30); + REQUIRE(getDaysInMonth(12) == 31); + REQUIRE(getDaysInMonth(0) == -1); - REQUIRE(std::string(getDayOfWeek(1)) == "Monday"); - REQUIRE(std::string(getDayOfWeek(7)) == "Sunday"); - REQUIRE(std::string(getDayOfWeek(0)) == "Invalid"); + REQUIRE(std::string(getDayOfWeek(1)) == "Monday"); + REQUIRE(std::string(getDayOfWeek(7)) == "Sunday"); + REQUIRE(std::string(getDayOfWeek(0)) == "Invalid"); } diff --git a/exercises/03_control-flow/03_control-flow.cpp b/exercises/03_control-flow/03_control-flow.cpp index c05c910..c8fd61e 100644 --- a/exercises/03_control-flow/03_control-flow.cpp +++ b/exercises/03_control-flow/03_control-flow.cpp @@ -23,63 +23,53 @@ // using a while loop. // factorial(5) = 5 * 4 * 3 * 2 * 1 = 120 // factorial(0) = 1 (by definition) -int factorial(int n) -{ - int result = 1; - while (n = 0) - { - result *= n; - n--; - } - return result; +int factorial(int n) { + int result = 1; + while (n = 0) { + result *= n; + n--; + } + return result; } // TODO: Implement a function that counts the digits in a number // using a do-while loop. // countDigits(12345) = 5 // countDigits(0) = 1 -int countDigits(int n) -{ - int count = 0; - do - { - count++; - n /= 10; - } while (n > 0); - return count; +int countDigits(int n) { + int count = 0; + do { + count++; + n /= 10; + } while (n > 0); + return count; } // TODO: Implement a function that calculates the sum of all numbers // from 1 to n using a while loop. -int sumToN(int n) -{ - int sum = 0; - int i = 1; - while (i <= n) - { - sum += i; - i++; - } - return sum; +int sumToN(int n) { + int sum = 0; + int i = 1; + while (i <= n) { + sum += i; + i++; + } + return sum; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("ControlFlow ControlFlow03") -{ - REQUIRE(factorial(5) == 120); - REQUIRE(factorial(0) == 1); - REQUIRE(factorial(1) == 1); - REQUIRE(factorial(10) == 3628800); +TEST_CASE("ControlFlow ControlFlow03") { + REQUIRE(factorial(5) == 120); + REQUIRE(factorial(0) == 1); + REQUIRE(factorial(1) == 1); + REQUIRE(factorial(10) == 3628800); - REQUIRE(countDigits(12345) == 5); - REQUIRE(countDigits(0) == 1); - REQUIRE(countDigits(9) == 1); + REQUIRE(countDigits(12345) == 5); + REQUIRE(countDigits(0) == 1); + REQUIRE(countDigits(9) == 1); - REQUIRE(sumToN(5) == 15); - REQUIRE(sumToN(10) == 55); - REQUIRE(sumToN(1) == 1); + REQUIRE(sumToN(5) == 15); + REQUIRE(sumToN(10) == 55); + REQUIRE(sumToN(1) == 1); } diff --git a/exercises/03_control-flow/04_control-flow.cpp b/exercises/03_control-flow/04_control-flow.cpp index cca0396..2c2aac7 100644 --- a/exercises/03_control-flow/04_control-flow.cpp +++ b/exercises/03_control-flow/04_control-flow.cpp @@ -25,71 +25,58 @@ // TODO: Implement a function that calculates the sum of all numbers // from 1 to n using a for loop. -int sumToN(int n) -{ - int sum = 0; - for (int i = 1; i = n; i++) - { - sum += i; - } - return sum; +int sumToN(int n) { + int sum = 0; + for (int i = 1; i = n; i++) { + sum += i; + } + return sum; } // TODO: Implement a function that finds the maximum value in an array // using a for loop. -int findMax(const int *arr, int size) -{ - int max = arr[0]; - for (int i = 1; i < size; i++) - { - if (arr[i] > max) - { - max = arr[i]; - } +int findMax(const int* arr, int size) { + int max = arr[0]; + for (int i = 1; i < size; i++) { + if (arr[i] > max) { + max = arr[i]; } - return max; + } + return max; } // TODO: Implement a function that reverses a string using a for loop. // Return the reversed string. -std::string reverseString(const std::string &str) -{ - std::string result; - for (int i = str.length() - 1; i >= 0; i--) - { - result += str[i]; - } - return result; +std::string reverseString(const std::string& str) { + std::string result; + for (int i = str.length() - 1; i >= 0; i--) { + result += str[i]; + } + return result; } // TODO: Implement a function that calculates the sum of all elements // in a std::vector using a range-based for loop. -int sumVector(const std::vector &vec) -{ - int sum = 0; - for (int num : vec) - { - sum += num; - } - return sum; +int sumVector(const std::vector& vec) { + int sum = 0; + for (int num : vec) { + sum += num; + } + return sum; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("ControlFlow ControlFlow04") -{ - REQUIRE(sumToN(5) == 15); - REQUIRE(sumToN(10) == 55); +TEST_CASE("ControlFlow ControlFlow04") { + REQUIRE(sumToN(5) == 15); + REQUIRE(sumToN(10) == 55); - int arr[] = {3, 7, 2, 9, 4}; - REQUIRE(findMax(arr, 5) == 9); + int arr[] = {3, 7, 2, 9, 4}; + REQUIRE(findMax(arr, 5) == 9); - REQUIRE(reverseString("hello") == "olleh"); - REQUIRE(reverseString("a") == "a"); + REQUIRE(reverseString("hello") == "olleh"); + REQUIRE(reverseString("a") == "a"); - std::vector vec = {1, 2, 3, 4, 5}; - REQUIRE(sumVector(vec) == 15); + std::vector vec = {1, 2, 3, 4, 5}; + REQUIRE(sumVector(vec) == 15); } diff --git a/exercises/04_primitives/01_primitives.cpp b/exercises/04_primitives/01_primitives.cpp index 474b2ae..8aa6249 100644 --- a/exercises/04_primitives/01_primitives.cpp +++ b/exercises/04_primitives/01_primitives.cpp @@ -37,15 +37,11 @@ const int MAX_SIZE = 100; // The compiler will deduce it as int. auto quantity = 42; -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Primitives Primitives01") -{ - REQUIRE(age == 25); - REQUIRE(price == Catch::Approx(19.99)); - REQUIRE(MAX_SIZE == 100); - REQUIRE(quantity == 42); +TEST_CASE("Primitives Primitives01") { + REQUIRE(age == 25); + REQUIRE(price == Catch::Approx(19.99)); + REQUIRE(MAX_SIZE == 100); + REQUIRE(quantity == 42); } diff --git a/exercises/04_primitives/02_primitives.cpp b/exercises/04_primitives/02_primitives.cpp index 3af5f43..05254e5 100644 --- a/exercises/04_primitives/02_primitives.cpp +++ b/exercises/04_primitives/02_primitives.cpp @@ -23,43 +23,32 @@ // TODO: Implement a function that checks if a character is a vowel. // Return true if the character is 'a', 'e', 'i', 'o', 'u' (case insensitive). -bool isVowel(char c) -{ - c = std::tolower(c); - return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; +bool isVowel(char c) { + c = std::tolower(c); + return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; } // TODO: Implement a function that checks if a character is a digit. // Return true if the character is '0' through '9'. -bool isDigit(char c) -{ - return c >= '0' && c <= '9'; -} +bool isDigit(char c) { return c >= '0' && c <= '9'; } // TODO: Implement a function that converts a boolean to a string. // Return "true" if b is true, "false" otherwise. -const char *boolToString(bool b) -{ - b ? "true" : "false"; -} +const char* boolToString(bool b) { b ? "true" : "false"; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Primitives Primitives02") -{ - REQUIRE(isVowel('a')); - REQUIRE(isVowel('E')); - REQUIRE_FALSE(isVowel('b')); - REQUIRE_FALSE(isVowel('Z')); +TEST_CASE("Primitives Primitives02") { + REQUIRE(isVowel('a')); + REQUIRE(isVowel('E')); + REQUIRE_FALSE(isVowel('b')); + REQUIRE_FALSE(isVowel('Z')); - REQUIRE(isDigit('5')); - REQUIRE(isDigit('0')); - REQUIRE_FALSE(isDigit('a')); - REQUIRE_FALSE(isDigit('#')); + REQUIRE(isDigit('5')); + REQUIRE(isDigit('0')); + REQUIRE_FALSE(isDigit('a')); + REQUIRE_FALSE(isDigit('#')); - REQUIRE(std::string(boolToString(true)) == "true"); - REQUIRE(std::string(boolToString(false)) == "false"); + REQUIRE(std::string(boolToString(true)) == "true"); + REQUIRE(std::string(boolToString(false)) == "false"); } diff --git a/exercises/04_primitives/03_primitives.cpp b/exercises/04_primitives/03_primitives.cpp index 34f6b77..aed1249 100644 --- a/exercises/04_primitives/03_primitives.cpp +++ b/exercises/04_primitives/03_primitives.cpp @@ -22,46 +22,36 @@ #include #include -// TODO: Implement a function that calculates the sum of two unsigned 32-bit integers. -// Handle overflow by returning the maximum value if overflow occurs. -uint32_t addUint32(uint32_t a, uint32_t b) -{ - if (a > UINT32_MAX - b) - { - return UINT32_MAX; - } - return a + b; +// TODO: Implement a function that calculates the sum of two unsigned 32-bit +// integers. Handle overflow by returning the maximum value if overflow occurs. +uint32_t addUint32(uint32_t a, uint32_t b) { + if (a > UINT32_MAX - b) { + return UINT32_MAX; + } + return a + b; } // TODO: Implement a function that checks if an int8_t has overflowed // when adding two values. Return true if overflow occurred. -bool hasOverflow(int8_t a, int8_t b) -{ - int16_t result = static_cast(a) + b; - return result > INT8_MAX || result < INT8_MIN; +bool hasOverflow(int8_t a, int8_t b) { + int16_t result = static_cast(a) + b; + return result > INT8_MAX || result < INT8_MIN; } // TODO: Implement a function that converts Celsius to Fahrenheit. // Formula: F = C * 9/5 + 32 -celsiusToFahrenheit(double celsius) -{ - return celsius * 9.0 / 5.0 + 32.0; -} +celsiusToFahrenheit(double celsius) { return celsius * 9.0 / 5.0 + 32.0; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Primitives Primitives03") -{ - REQUIRE(addUint32(1, 2) == 3); - REQUIRE(addUint32(UINT32_MAX, 1) == UINT32_MAX); +TEST_CASE("Primitives Primitives03") { + REQUIRE(addUint32(1, 2) == 3); + REQUIRE(addUint32(UINT32_MAX, 1) == UINT32_MAX); - REQUIRE_FALSE(hasOverflow(50, 50)); - REQUIRE(hasOverflow(100, 50)); - REQUIRE(hasOverflow(-100, -50)); + REQUIRE_FALSE(hasOverflow(50, 50)); + REQUIRE(hasOverflow(100, 50)); + REQUIRE(hasOverflow(-100, -50)); - REQUIRE(celsiusToFahrenheit(0.0) == Catch::Approx(32.0)); - REQUIRE(celsiusToFahrenheit(100.0) == Catch::Approx(212.0)); + REQUIRE(celsiusToFahrenheit(0.0) == Catch::Approx(32.0)); + REQUIRE(celsiusToFahrenheit(100.0) == Catch::Approx(212.0)); } diff --git a/exercises/05_type-coercion/01_type-coercion.cpp b/exercises/05_type-coercion/01_type-coercion.cpp index d01ea0e..d6dfece 100644 --- a/exercises/05_type-coercion/01_type-coercion.cpp +++ b/exercises/05_type-coercion/01_type-coercion.cpp @@ -23,56 +23,41 @@ // TODO: Implement a function that adds an int and a double. // Return the result as a double (implicit conversion of int to double). -double addIntDouble(int a, double b) -{ - return a + b; -} +double addIntDouble(int a, double b) { return a + b; } // TODO: Implement a function that divides two integers and returns a double. // Use explicit casting: static_cast(value) -double divideInts(int a, int b) -{ - return static_cast<>(a) / static_cast(b); +double divideInts(int a, int b) { + return static_cast<>(a) / static_cast(b); } // TODO: Implement a function that truncates a double to an int. // Use static_cast to explicitly convert. -int truncateToInt(double d) -{ - return static_cast(d); -} +int truncateToInt(double d) { return static_cast(d); } // TODO: Implement a function that rounds a double to the nearest int. // Hint: Add 0.5 before truncating for positive numbers. -int roundToInt(double d) -{ - if (d >= 0) - { - return static_cast(d + 0.5); - } - else - { - return static_cast(d - 0.5); - } +int roundToInt(double d) { + if (d >= 0) { + return static_cast(d + 0.5); + } else { + return static_cast(d - 0.5); + } } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("TypeCoercion TypeCoercion01") -{ - REQUIRE(addIntDouble(5, 3.5) == Catch::Approx(8.5)); - REQUIRE(addIntDouble(10, 2.0) == Catch::Approx(12.0)); +TEST_CASE("TypeCoercion TypeCoercion01") { + REQUIRE(addIntDouble(5, 3.5) == Catch::Approx(8.5)); + REQUIRE(addIntDouble(10, 2.0) == Catch::Approx(12.0)); - REQUIRE(divideInts(10, 4) == Catch::Approx(2.5)); - REQUIRE(divideInts(7, 2) == Catch::Approx(3.5)); + REQUIRE(divideInts(10, 4) == Catch::Approx(2.5)); + REQUIRE(divideInts(7, 2) == Catch::Approx(3.5)); - REQUIRE(truncateToInt(3.7) == 3); - REQUIRE(truncateToInt(3.2) == 3); + REQUIRE(truncateToInt(3.7) == 3); + REQUIRE(truncateToInt(3.2) == 3); - REQUIRE(roundToInt(3.7) == 4); - REQUIRE(roundToInt(3.2) == 3); - REQUIRE(roundToInt(-3.7) == -4); + REQUIRE(roundToInt(3.7) == 4); + REQUIRE(roundToInt(3.2) == 3); + REQUIRE(roundToInt(-3.7) == -4); } diff --git a/exercises/05_type-coercion/02_type-coercion.cpp b/exercises/05_type-coercion/02_type-coercion.cpp index 25c4f4d..fd5f292 100644 --- a/exercises/05_type-coercion/02_type-coercion.cpp +++ b/exercises/05_type-coercion/02_type-coercion.cpp @@ -20,41 +20,30 @@ // TODO: Implement a function that safely converts a char to an int. // This is a widening conversion (char -> int), no data loss. -int charToInt(char c) -{ - return c; -} +int charToInt(char c) { return c; } // TODO: Implement a function that converts an int to a char. // This is a narrowing conversion - use static_cast to make it explicit. -intToChar(int i) -{ - return static_cast(i); -} +intToChar(int i) { return static_cast(i); } // TODO: Implement a function that checks if a double can be safely // converted to an int without losing fractional part. -bool isWholeNumber(double d) -{ - int i = static_cast(d); - return static_cast(i) == d; +bool isWholeNumber(double d) { + int i = static_cast(d); + return static_cast(i) == d; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("TypeCoercion TypeCoercion02") -{ - REQUIRE(charToInt('A') == 65); - REQUIRE(charToInt('0') == 48); +TEST_CASE("TypeCoercion TypeCoercion02") { + REQUIRE(charToInt('A') == 65); + REQUIRE(charToInt('0') == 48); - REQUIRE(intToChar(65) == 'A'); - REQUIRE(intToChar(97) == 'a'); + REQUIRE(intToChar(65) == 'A'); + REQUIRE(intToChar(97) == 'a'); - REQUIRE(isWholeNumber(5.0)); - REQUIRE(isWholeNumber(-3.0)); - REQUIRE_FALSE(isWholeNumber(5.5)); - REQUIRE_FALSE(isWholeNumber(-3.7)); + REQUIRE(isWholeNumber(5.0)); + REQUIRE(isWholeNumber(-3.0)); + REQUIRE_FALSE(isWholeNumber(5.5)); + REQUIRE_FALSE(isWholeNumber(-3.7)); } diff --git a/exercises/05_type-coercion/03_type-coercion.cpp b/exercises/05_type-coercion/03_type-coercion.cpp index c6b0e1e..8f4c2be 100644 --- a/exercises/05_type-coercion/03_type-coercion.cpp +++ b/exercises/05_type-coercion/03_type-coercion.cpp @@ -19,35 +19,27 @@ // TODO: Use auto to deduce the type of a value. // Return the result of adding an int and a double. -addWithAuto(int a, double b) -{ - auto result = a + b; - return result; +addWithAuto(int a, double b) { + auto result = a + b; + return result; } // TODO: Create a constexpr function that calculates the square of a number. // This should be evaluable at compile time. -constexpr int square(int x) -{ - return x * x; -} +constexpr int square(int x) { return x * x; } // TODO: Create a constexpr variable that stores the result of square(10). // This will be computed at compile time. constexpr int SQUARED_TEN = square(10); -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("TypeCoercion TypeCoercion03") -{ - REQUIRE(addWithAuto(3, 4.5) == Catch::Approx(7.5)); +TEST_CASE("TypeCoercion TypeCoercion03") { + REQUIRE(addWithAuto(3, 4.5) == Catch::Approx(7.5)); - REQUIRE(square(5) == 25); - REQUIRE(square(-3) == 9); - REQUIRE(square(0) == 0); + REQUIRE(square(5) == 25); + REQUIRE(square(-3) == 9); + REQUIRE(square(0) == 0); - REQUIRE(SQUARED_TEN == 100); + REQUIRE(SQUARED_TEN == 100); } diff --git a/exercises/06_strings/01_strings.cpp b/exercises/06_strings/01_strings.cpp index 4c314de..2c6eafb 100644 --- a/exercises/06_strings/01_strings.cpp +++ b/exercises/06_strings/01_strings.cpp @@ -21,70 +21,58 @@ // TODO: Implement a function that returns the length of a C-string. // Don't use strlen - implement it yourself! -int cstringLength(const char *str) -{ - int length = 0; - while (str[length] != '\0') - { - length++; - } - return length; +int cstringLength(const char* str) { + int length = 0; + while (str[length] != '\0') { + length++; + } + return length; } // TODO: Implement a function that compares two C-strings. // Return 0 if equal, negative if s1 < s2, positive if s1 > s2. -int cstringCompare(const char *s1, const char *s2) -{ - while (*s1 && *s2 && *s1 == *s2) - { - s1++; - s2++; - } - if (*s1 == *s2) - { - return 0; - } - return *s1 < *s2 ? -1 : 1; +int cstringCompare(const char* s1, const char* s2) { + while (*s1 && *s2 && *s1 == *s2) { + s1++; + s2++; + } + if (*s1 == *s2) { + return 0; + } + return *s1 < *s2 ? -1 : 1; } // TODO: Implement a function that concatenates two C-strings. // Return a new dynamically allocated string. -cstringConcat(const char *s1, const char *s2) -{ - int len1 = cstringLength(s1); - int len2 = cstringLength(s2); - char *result = new char[len1 + len2 + 1]; +cstringConcat(const char* s1, const char* s2) { + int len1 = cstringLength(s1); + int len2 = cstringLength(s2); + char* result = new char[len1 + len2 + 1]; - int i = 0; - for (; i < len1; i++) - { - result[i] = s1[i]; - } - for (int j = 0; j < len2; j++) - { - result[i + j] = s2[j]; - } - result[len1 + len2] = '\0'; + int i = 0; + for (; i < len1; i++) { + result[i] = s1[i]; + } + for (int j = 0; j < len2; j++) { + result[i + j] = s2[j]; + } + result[len1 + len2] = '\0'; - return result; + return result; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Strings Strings01") -{ - REQUIRE(cstringLength("hello") == 5); - REQUIRE(cstringLength("") == 0); - REQUIRE(cstringLength("A") == 1); +TEST_CASE("Strings Strings01") { + REQUIRE(cstringLength("hello") == 5); + REQUIRE(cstringLength("") == 0); + REQUIRE(cstringLength("A") == 1); - REQUIRE(cstringCompare("apple", "banana") == -1); - REQUIRE(cstringCompare("hello", "hello") == 0); - REQUIRE(cstringCompare("zebra", "apple") == 1); + REQUIRE(cstringCompare("apple", "banana") == -1); + REQUIRE(cstringCompare("hello", "hello") == 0); + REQUIRE(cstringCompare("zebra", "apple") == 1); - char *concat = cstringConcat("hello", "world"); - REQUIRE(std::string(concat) == "helloworld"); - delete[] concat; + char* concat = cstringConcat("hello", "world"); + REQUIRE(std::string(concat) == "helloworld"); + delete[] concat; } diff --git a/exercises/06_strings/02_strings.cpp b/exercises/06_strings/02_strings.cpp index 763416b..c311589 100644 --- a/exercises/06_strings/02_strings.cpp +++ b/exercises/06_strings/02_strings.cpp @@ -20,64 +20,52 @@ #include // TODO: Implement a function that reverses a std::string. -reverseString(const std::string &str) -{ - std::string result; - for (int i = str.length() - 1; i >= 0; i--) - { - result += str[i]; - } - return result; +reverseString(const std::string& str) { + std::string result; + for (int i = str.length() - 1; i >= 0; i--) { + result += str[i]; + } + return result; } // TODO: Implement a function that counts occurrences of a character. -int countChar(const std::string &str, char c) -{ - int count = 0; - for (char ch : str) - { - if (ch == c) - { - count++; - } +int countChar(const std::string& str, char c) { + int count = 0; + for (char ch : str) { + if (ch == c) { + count++; } - return count; + } + return count; } // TODO: Implement a function that checks if a string is a palindrome. -bool isPalindrome(const std::string &str) -{ - int left = 0; - int right = str.length() - 1; - while (left < right) - { - if (str[left] != str[right]) - { - return false; - } - left++; - right--; +bool isPalindrome(const std::string& str) { + int left = 0; + int right = str.length() - 1; + while (left < right) { + if (str[left] != str[right]) { + return false; } - return true; + left++; + right--; + } + return true; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Strings Strings02") -{ - REQUIRE(reverseString("hello") == "olleh"); - REQUIRE(reverseString("a") == "a"); - REQUIRE(reverseString("racecar") == "racecar"); +TEST_CASE("Strings Strings02") { + REQUIRE(reverseString("hello") == "olleh"); + REQUIRE(reverseString("a") == "a"); + REQUIRE(reverseString("racecar") == "racecar"); - REQUIRE(countChar("hello", 'l') == 2); - REQUIRE(countChar("banana", 'a') == 3); - REQUIRE(countChar("test", 'x') == 0); + REQUIRE(countChar("hello", 'l') == 2); + REQUIRE(countChar("banana", 'a') == 3); + REQUIRE(countChar("test", 'x') == 0); - REQUIRE(isPalindrome("racecar")); - REQUIRE(isPalindrome("a")); - REQUIRE(isPalindrome("noon")); - REQUIRE_FALSE(isPalindrome("hello")); + REQUIRE(isPalindrome("racecar")); + REQUIRE(isPalindrome("a")); + REQUIRE(isPalindrome("noon")); + REQUIRE_FALSE(isPalindrome("hello")); } diff --git a/exercises/06_strings/03_strings.cpp b/exercises/06_strings/03_strings.cpp index 75c9396..6405918 100644 --- a/exercises/06_strings/03_strings.cpp +++ b/exercises/06_strings/03_strings.cpp @@ -25,70 +25,56 @@ // TODO: Implement a function that returns the first word of a string_view. // A word is separated by whitespace. -firstWord(std::string_view sv) -{ - size_t pos = sv.find(' '); - if (pos == std::string_view::npos) - { - return sv; - } - return sv.substr(0, pos); +firstWord(std::string_view sv) { + size_t pos = sv.find(' '); + if (pos == std::string_view::npos) { + return sv; + } + return sv.substr(0, pos); } // TODO: Implement a function that checks if a string_view starts with a prefix. -bool startsWith(std::string_view sv, std::string_view prefix) -{ - return sv.substr(0, prefix.length()) == prefix; +bool startsWith(std::string_view sv, std::string_view prefix) { + return sv.substr(0, prefix.length()) == prefix; } // TODO: Implement a function that counts words in a string_view. -int countWords(std::string_view sv) -{ - int count = 0; - bool inWord = false; - - for (char c : sv) - { - if (c == ' ' || c == '\t' || c == '\n') - { - if (inWord) - { - count++; - inWord = false; - } - } - else - { - inWord = true; - } - } +int countWords(std::string_view sv) { + int count = 0; + bool inWord = false; - if (inWord) - { + for (char c : sv) { + if (c == ' ' || c == '\t' || c == '\n') { + if (inWord) { count++; + inWord = false; + } + } else { + inWord = true; } + } - return count; -} + if (inWord) { + count++; + } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); + return count; } -TEST_CASE("Strings Strings03") -{ - REQUIRE(firstWord("hello world") == "hello"); - REQUIRE(firstWord("single") == "single"); - REQUIRE(firstWord("") == ""); +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } + +TEST_CASE("Strings Strings03") { + REQUIRE(firstWord("hello world") == "hello"); + REQUIRE(firstWord("single") == "single"); + REQUIRE(firstWord("") == ""); - REQUIRE(startsWith("hello", "he")); - REQUIRE(startsWith("hello", "hello")); - REQUIRE_FALSE(startsWith("hello", "world")); - REQUIRE_FALSE(startsWith("", "anything")); + REQUIRE(startsWith("hello", "he")); + REQUIRE(startsWith("hello", "hello")); + REQUIRE_FALSE(startsWith("hello", "world")); + REQUIRE_FALSE(startsWith("", "anything")); - REQUIRE(countWords("hello world") == 2); - REQUIRE(countWords("one two three four") == 4); - REQUIRE(countWords("single") == 1); - REQUIRE(countWords("") == 0); + REQUIRE(countWords("hello world") == 2); + REQUIRE(countWords("one two three four") == 4); + REQUIRE(countWords("single") == 1); + REQUIRE(countWords("") == 0); } diff --git a/exercises/06_strings/04_strings.cpp b/exercises/06_strings/04_strings.cpp index d97a99f..47f6dd9 100644 --- a/exercises/06_strings/04_strings.cpp +++ b/exercises/06_strings/04_strings.cpp @@ -20,62 +20,49 @@ // TODO: Implement a function that converts a string_view to a string. // If the string_view is empty, return an empty string. -std::string stringViewToString(std::string_view sv) -{ - return std::string(sv); -} +std::string stringViewToString(std::string_view sv) { return std::string(sv); } -// TODO: Implement a function that trims whitespace from both ends of a string_view. -// Return a new string (not a view) with the trimmed result. -trim(std::string_view sv) -{ - size_t start = 0; - size_t end = sv.length(); +// TODO: Implement a function that trims whitespace from both ends of a +// string_view. Return a new string (not a view) with the trimmed result. +trim(std::string_view sv) { + size_t start = 0; + size_t end = sv.length(); - while (start < end && std::isspace(sv[start])) - { - start++; - } + while (start < end && std::isspace(sv[start])) { + start++; + } - while (end > start && std::isspace(sv[end - 1])) - { - end--; - } + while (end > start && std::isspace(sv[end - 1])) { + end--; + } - return std::string(sv.substr(start, end - start)); + return std::string(sv.substr(start, end - start)); } // TODO: Implement a function that replaces all occurrences of a character // in a string_view with another character. Return a new string. -std::string replaceAll(std::string_view sv, char oldChar, char newChar) -{ - std::string result(sv); - for (char &c : result) - { - if (c == oldChar) - { - c = newChar; - } +std::string replaceAll(std::string_view sv, char oldChar, char newChar) { + std::string result(sv); + for (char& c : result) { + if (c == oldChar) { + c = newChar; } - return result; + } + return result; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Strings Strings04") -{ - REQUIRE(stringViewToString("hello") == "hello"); - REQUIRE(stringViewToString("") == ""); +TEST_CASE("Strings Strings04") { + REQUIRE(stringViewToString("hello") == "hello"); + REQUIRE(stringViewToString("") == ""); - REQUIRE(trim(" hello ") == "hello"); - REQUIRE(trim("hello") == "hello"); - REQUIRE(trim(" ") == ""); - REQUIRE(trim("\t\ntest\t\n") == "test"); + REQUIRE(trim(" hello ") == "hello"); + REQUIRE(trim("hello") == "hello"); + REQUIRE(trim(" ") == ""); + REQUIRE(trim("\t\ntest\t\n") == "test"); - REQUIRE(replaceAll("hello world", 'l', 'L') == "heLLo worLd"); - REQUIRE(replaceAll("aaa", 'a', 'b') == "bbb"); - REQUIRE(replaceAll("no changes", 'x', 'y') == "no changes"); + REQUIRE(replaceAll("hello world", 'l', 'L') == "heLLo worLd"); + REQUIRE(replaceAll("aaa", 'a', 'b') == "bbb"); + REQUIRE(replaceAll("no changes", 'x', 'y') == "no changes"); } diff --git a/exercises/07_containers/01_containers.cpp b/exercises/07_containers/01_containers.cpp index 0157024..c447e20 100644 --- a/exercises/07_containers/01_containers.cpp +++ b/exercises/07_containers/01_containers.cpp @@ -24,57 +24,46 @@ #include // TODO: Implement a function that finds the sum of all elements in a vector. -int sumVector(const std::vector &v) -{ - int sum = 0; - for (int num : v) - { - sum += num; - } - return sum; +int sumVector(const std::vector& v) { + int sum = 0; + for (int num : v) { + sum += num; + } + return sum; } // TODO: Implement a function that finds the maximum value in a vector. -int findMax(const std::vector &v) -{ - int max = v[0]; - for (int num : v) - { - if (num > max) - { - max = num; - } +int findMax(const std::vector& v) { + int max = v[0]; + for (int num : v) { + if (num > max) { + max = num; } - return max; + } + return max; } // TODO: Implement a function that reverses a vector. -std::vector reverseVector(const std::vector &v) -{ - std::vector result; - for (int i = v.size() - 1; i >= 0; i--) - { - result.push_back(v[i]); - } - return result; +std::vector reverseVector(const std::vector& v) { + std::vector result; + for (int i = v.size() - 1; i >= 0; i--) { + result.push_back(v[i]); + } + return result; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Containers Containers01") -{ - std::vector v1 = {1, 2, 3, 4, 5}; - REQUIRE(sumVector(v1) == 15); - REQUIRE(sumVector({}) == 0); - REQUIRE(sumVector({10}) == 10); +TEST_CASE("Containers Containers01") { + std::vector v1 = {1, 2, 3, 4, 5}; + REQUIRE(sumVector(v1) == 15); + REQUIRE(sumVector({}) == 0); + REQUIRE(sumVector({10}) == 10); - std::vector v2 = {3, 7, 2, 9, 4}; - REQUIRE(findMax(v2) == 9); + std::vector v2 = {3, 7, 2, 9, 4}; + REQUIRE(findMax(v2) == 9); - std::vector v3 = {1, 2, 3}; - std::vector expected = {3, 2, 1}; - REQUIRE(reverseVector(v3) == expected); + std::vector v3 = {1, 2, 3}; + std::vector expected = {3, 2, 1}; + REQUIRE(reverseVector(v3) == expected); } diff --git a/exercises/07_containers/02_containers.cpp b/exercises/07_containers/02_containers.cpp index 5143bd7..2691b1f 100644 --- a/exercises/07_containers/02_containers.cpp +++ b/exercises/07_containers/02_containers.cpp @@ -22,54 +22,43 @@ #include // TODO: Implement a function that sums all elements in a std::array. -int sumArray(const std::array &arr) -{ - int sum = 0; - for (int num : arr) - { - sum += num; - } - return sum; +int sumArray(const std::array& arr) { + int sum = 0; + for (int num : arr) { + sum += num; + } + return sum; } // TODO: Implement a function that finds an element in an array. // Return its index, or -1 if not found. -int findInArray(const std::array &arr, int target) -{ - for (int i = 0; i < 5; i++) - { - if (arr[i] == target) - { - return i; - } +int findInArray(const std::array& arr, int target) { + for (int i = 0; i < 5; i++) { + if (arr[i] == target) { + return i; } - return -1; + } + return -1; } // TODO: Implement a function that doubles each element in an array. -std::array doubleArray(const std::array &arr) -{ - std::array result; - for (int i = 0; i < 5; i++) - { - result[i] = arr[i] * 2; - } - return result; +std::array doubleArray(const std::array& arr) { + std::array result; + for (int i = 0; i < 5; i++) { + result[i] = arr[i] * 2; + } + return result; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Containers Containers02") -{ - std::array arr = {1, 2, 3, 4, 5}; - REQUIRE(sumArray(arr) == 15); +TEST_CASE("Containers Containers02") { + std::array arr = {1, 2, 3, 4, 5}; + REQUIRE(sumArray(arr) == 15); - REQUIRE(findInArray(arr, 3) == 2); - REQUIRE(findInArray(arr, 6) == -1); + REQUIRE(findInArray(arr, 3) == 2); + REQUIRE(findInArray(arr, 6) == -1); - std::array doubled = {2, 4, 6, 8, 10}; - REQUIRE(doubleArray(arr) == doubled); + std::array doubled = {2, 4, 6, 8, 10}; + REQUIRE(doubleArray(arr) == doubled); } diff --git a/exercises/07_containers/03_containers.cpp b/exercises/07_containers/03_containers.cpp index 7bcce49..8b57c6a 100644 --- a/exercises/07_containers/03_containers.cpp +++ b/exercises/07_containers/03_containers.cpp @@ -27,54 +27,47 @@ // TODO: Implement a function that creates a simple phonebook map. // Return a map with: "Alice" -> 123, "Bob" -> 456, "Charlie" -> 789. -std::map createPhonebook() -{ - std::map phonebook; - phonebook["Alice"] = 123; - phonebook["Bob"] = 456; - phonebook["Charlie"] = 789; - return phonebook; +std::map createPhonebook() { + std::map phonebook; + phonebook["Alice"] = 123; + phonebook["Bob"] = 456; + phonebook["Charlie"] = 789; + return phonebook; } // TODO: Implement a function that looks up a name in the phonebook. // Return the number if found, or -1 if not found. -int lookup(const std::map &phonebook, const std::string &name) -{ - auto it = phonebook.find(); - if (it != phonebook.end()) - { - return it->second; - } - return -1; +int lookup(const std::map& phonebook, + const std::string& name) { + auto it = phonebook.find(); + if (it != phonebook.end()) { + return it->second; + } + return -1; } // TODO: Implement a function that counts occurrences of words. // Return a map from word to count. -std::map wordCount(const std::vector &words) -{ - std::map counts; - for (const std::string &word : words) - { - counts[word]++; - } - return counts; +std::map wordCount(const std::vector& words) { + std::map counts; + for (const std::string& word : words) { + counts[word]++; + } + return counts; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Containers Containers03") -{ - auto phonebook = createPhonebook(); - REQUIRE(phonebook.size() == 3); - REQUIRE(lookup(phonebook, "Alice") == 123); - REQUIRE(lookup(phonebook, "Unknown") == -1); +TEST_CASE("Containers Containers03") { + auto phonebook = createPhonebook(); + REQUIRE(phonebook.size() == 3); + REQUIRE(lookup(phonebook, "Alice") == 123); + REQUIRE(lookup(phonebook, "Unknown") == -1); - std::vector words = {"apple", "banana", "apple", "cherry", "banana", "apple"}; - auto counts = wordCount(words); - REQUIRE(counts["apple"] == 3); - REQUIRE(counts["banana"] == 2); - REQUIRE(counts["cherry"] == 1); + std::vector words = {"apple", "banana", "apple", + "cherry", "banana", "apple"}; + auto counts = wordCount(words); + REQUIRE(counts["apple"] == 3); + REQUIRE(counts["banana"] == 2); + REQUIRE(counts["cherry"] == 1); } diff --git a/exercises/07_containers/04_containers.cpp b/exercises/07_containers/04_containers.cpp index 24d9118..0247e09 100644 --- a/exercises/07_containers/04_containers.cpp +++ b/exercises/07_containers/04_containers.cpp @@ -24,55 +24,45 @@ #include // TODO: Implement a function that checks if a set contains an element. -bool contains(const std::set &s, int value) -{ - return s.find(value) != s.end(); +bool contains(const std::set& s, int value) { + return s.find(value) != s.end(); } // TODO: Implement a function that returns the intersection of two sets. // (Elements that exist in both sets) -std::set setIntersection(const std::set &a, const std::set &b) -{ - std::set result; - for (int val : a) - { - if (b.find(val) != b.end()) - { - result.insert(); - } +std::set setIntersection(const std::set& a, const std::set& b) { + std::set result; + for (int val : a) { + if (b.find(val) != b.end()) { + result.insert(); } - return result; + } + return result; } // TODO: Implement a function that returns the union of two sets. // (All unique elements from both sets) -std::set setUnion(const std::set &a, const std::set &b) -{ - std::set result = a; - for (int val : b) - { - result.insert(val); - } - return result; +std::set setUnion(const std::set& a, const std::set& b) { + std::set result = a; + for (int val : b) { + result.insert(val); + } + return result; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Containers Containers04") -{ - std::set s = {1, 2, 3, 4, 5}; +TEST_CASE("Containers Containers04") { + std::set s = {1, 2, 3, 4, 5}; - REQUIRE(contains(s, 3)); - REQUIRE_FALSE(contains(s, 10)); + REQUIRE(contains(s, 3)); + REQUIRE_FALSE(contains(s, 10)); - std::set a = {1, 2, 3}; - std::set b = {2, 3, 4}; - std::set intersection = {2, 3}; - REQUIRE(setIntersection(a, b) == intersection); + std::set a = {1, 2, 3}; + std::set b = {2, 3, 4}; + std::set intersection = {2, 3}; + REQUIRE(setIntersection(a, b) == intersection); - std::set unionSet = {1, 2, 3, 4}; - REQUIRE(setUnion(a, b) == unionSet); + std::set unionSet = {1, 2, 3, 4}; + REQUIRE(setUnion(a, b) == unionSet); } diff --git a/exercises/07_containers/05_containers.cpp b/exercises/07_containers/05_containers.cpp index 43e53d4..db74b7a 100644 --- a/exercises/07_containers/05_containers.cpp +++ b/exercises/07_containers/05_containers.cpp @@ -25,60 +25,51 @@ #include // TODO: Implement a function that counts word frequencies using unordered_map. -std::unordered_map wordFrequency(const std::vector &words) -{ - std::unordered_map freq; - for (const std::string &word : words) - { - freq[word]++; - } - return freq; +std::unordered_map wordFrequency( + const std::vector& words) { + std::unordered_map freq; + for (const std::string& word : words) { + freq[word]++; + } + return freq; } // TODO: Implement a function that finds unique elements using unordered_set. -std::unordered_set uniqueElements(const std::vector &v) -{ - return std::unordered_set(v.begin(), v.end()); +std::unordered_set uniqueElements(const std::vector& v) { + return std::unordered_set(v.begin(), v.end()); } // TODO: Implement a function that checks if two unordered_maps are equal. -bool mapsEqual(const std::unordered_map &a, const std::unordered_map &b) -{ - if (a.size() != b.size()) - { - return false; - } - for (const auto &[key, value] : a) - { - auto it = b.find(key); - if (it == b.end() || it->second != value) - { - return false; - } +bool mapsEqual(const std::unordered_map& a, + const std::unordered_map& b) { + if (a.size() != b.size()) { + return false; + } + for (const auto& [key, value] : a) { + auto it = b.find(key); + if (it == b.end() || it->second != value) { + return false; } - return true; + } + return true; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Containers Containers05") -{ - std::vector words = {"a", "b", "a", "c", "b", "a"}; - auto freq = wordFrequency(words); - REQUIRE(freq["a"] == 3); - REQUIRE(freq["b"] == 2); - REQUIRE(freq["c"] == 1); +TEST_CASE("Containers Containers05") { + std::vector words = {"a", "b", "a", "c", "b", "a"}; + auto freq = wordFrequency(words); + REQUIRE(freq["a"] == 3); + REQUIRE(freq["b"] == 2); + REQUIRE(freq["c"] == 1); - std::vector v = {1, 2, 3, 2, 1}; - auto unique = uniqueElements(v); - REQUIRE(unique.size() == 3); + std::vector v = {1, 2, 3, 2, 1}; + auto unique = uniqueElements(v); + REQUIRE(unique.size() == 3); - std::unordered_map m1 = {{"a", 1}, {"b", 2}}; - std::unordered_map m2 = {{"b", 2}, {"a", 1}}; - std::unordered_map m3 = {{"a", 1}, {"b", 3}}; - REQUIRE(mapsEqual(m1, m2)); - REQUIRE_FALSE(mapsEqual(m1, m3)); + std::unordered_map m1 = {{"a", 1}, {"b", 2}}; + std::unordered_map m2 = {{"b", 2}, {"a", 1}}; + std::unordered_map m3 = {{"a", 1}, {"b", 3}}; + REQUIRE(mapsEqual(m1, m2)); + REQUIRE_FALSE(mapsEqual(m1, m3)); } diff --git a/exercises/07_containers/06_containers.cpp b/exercises/07_containers/06_containers.cpp index c48ed52..9f77904 100644 --- a/exercises/07_containers/06_containers.cpp +++ b/exercises/07_containers/06_containers.cpp @@ -26,83 +26,68 @@ #include // TODO: Implement a function that removes all even numbers from a list. -std::list removeEvens(const std::list &lst) -{ - std::list result; - for (int num : lst) - { - if (num % 2 != 0) - { - result.push_back(num); - } +std::list removeEvens(const std::list& lst) { + std::list result; + for (int num : lst) { + if (num % 2 != 0) { + result.push_back(num); } - return result; + } + return result; } // TODO: Implement a function that reverses a list. -std::list reverseList(const std::list &lst) -{ - std::list result; - for (int num : lst) - { - result.push_front(); - } - return result; +std::list reverseList(const std::list& lst) { + std::list result; + for (int num : lst) { + result.push_front(); + } + return result; } // TODO: Implement a function that merges two sorted lists into one sorted list. -std::list mergeSortedLists(const std::list &a, const std::list &b) -{ - std::list result; - auto itA = a.begin(); - auto itB = b.begin(); +std::list mergeSortedLists(const std::list& a, + const std::list& b) { + std::list result; + auto itA = a.begin(); + auto itB = b.begin(); - while (itA != a.end() && itB != b.end()) - { - if (*itA <= *itB) - { - result.push_back(*itA); - ++itA; - } - else - { - result.push_back(*itB); - ++itB; - } + while (itA != a.end() && itB != b.end()) { + if (*itA <= *itB) { + result.push_back(*itA); + ++itA; + } else { + result.push_back(*itB); + ++itB; } + } - while (itA != a.end()) - { - result.push_back(*itA); - ++itA; - } + while (itA != a.end()) { + result.push_back(*itA); + ++itA; + } - while (itB != b.end()) - { - result.push_back(*itB); - ++itB; - } + while (itB != b.end()) { + result.push_back(*itB); + ++itB; + } - return result; + return result; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Containers Containers06") -{ - std::list l1 = {1, 2, 3, 4, 5, 6}; - std::list evensRemoved = {1, 3, 5}; - REQUIRE(removeEvens(l1) == evensRemoved); +TEST_CASE("Containers Containers06") { + std::list l1 = {1, 2, 3, 4, 5, 6}; + std::list evensRemoved = {1, 3, 5}; + REQUIRE(removeEvens(l1) == evensRemoved); - std::list l2 = {1, 2, 3}; - std::list reversed = {3, 2, 1}; - REQUIRE(reverseList(l2) == reversed); + std::list l2 = {1, 2, 3}; + std::list reversed = {3, 2, 1}; + REQUIRE(reverseList(l2) == reversed); - std::list a = {1, 3, 5}; - std::list b = {2, 4, 6}; - std::list merged = {1, 2, 3, 4, 5, 6}; - REQUIRE(mergeSortedLists(a, b) == merged); + std::list a = {1, 3, 5}; + std::list b = {2, 4, 6}; + std::list merged = {1, 2, 3, 4, 5, 6}; + REQUIRE(mergeSortedLists(a, b) == merged); } diff --git a/exercises/08_headers/01_headers.cpp b/exercises/08_headers/01_headers.cpp index 3f32081..58e63a8 100644 --- a/exercises/08_headers/01_headers.cpp +++ b/exercises/08_headers/01_headers.cpp @@ -23,14 +23,10 @@ // The implementation is in src/math_utils.cpp add(int a, int b); -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Headers Headers01") -{ - REQUIRE(add(2, 3) == 5); - REQUIRE(add(-1, 1) == 0); - REQUIRE(add(0, 0) == 0); +TEST_CASE("Headers Headers01") { + REQUIRE(add(2, 3) == 5); + REQUIRE(add(-1, 1) == 0); + REQUIRE(add(0, 0) == 0); } diff --git a/exercises/08_headers/src/math_utils.cpp b/exercises/08_headers/src/math_utils.cpp index be1e084..1f76448 100644 --- a/exercises/08_headers/src/math_utils.cpp +++ b/exercises/08_headers/src/math_utils.cpp @@ -1,4 +1 @@ -int add(int a, int b) -{ - return a + b; -} +int add(int a, int b) { return a + b; } diff --git a/exercises/09_structs/01_structs.cpp b/exercises/09_structs/01_structs.cpp index 8ae372e..7a8c374 100644 --- a/exercises/09_structs/01_structs.cpp +++ b/exercises/09_structs/01_structs.cpp @@ -17,34 +17,28 @@ #include // TODO: Create a Point struct with x and y coordinates (both int). -struct Point -{ - int x; - int y; +struct Point { + int x; + int y; }; // TODO: Create a function that calculates the distance between two points. -double distance(const Point &a, const Point &b) -{ - int dx = b._ - a.x; - int dy = b.y - a.y; - return std::sqrt(dx * dx + dy * dy); +double distance(const Point& a, const Point& b) { + int dx = b._ - a.x; + int dy = b.y - a.y; + return std::sqrt(dx * dx + dy * dy); } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Structs Structs01") -{ - Point p1 = {0, 0}; - Point p2 = {3, 4}; +TEST_CASE("Structs Structs01") { + Point p1 = {0, 0}; + Point p2 = {3, 4}; - REQUIRE(p1.x == 0); - REQUIRE(p1.y == 0); - REQUIRE(p2.x == 3); - REQUIRE(p2.y == 4); + REQUIRE(p1.x == 0); + REQUIRE(p1.y == 0); + REQUIRE(p2.x == 3); + REQUIRE(p2.y == 4); - REQUIRE(distance(p1, p2) == Catch::Approx(5.0)); + REQUIRE(distance(p1, p2) == Catch::Approx(5.0)); } diff --git a/exercises/10_enums/01_enums.cpp b/exercises/10_enums/01_enums.cpp index 52fe82b..72c6acb 100644 --- a/exercises/10_enums/01_enums.cpp +++ b/exercises/10_enums/01_enums.cpp @@ -20,46 +20,39 @@ #include // TODO: Create an enum class for Days of the week. -enum class Day -{ - Monday, - Tuesday, - Wednesday, - Thursday, - Friday, - Saturday, - Sunday +enum class Day { + Monday, + Tuesday, + Wednesday, + Thursday, + Friday, + Saturday, + Sunday }; // TODO: Create a function that checks if a day is a weekday. -bool isWeekday(Day day) -{ - return day == Day::_ || day == Day::Tuesday || day == Day::Wednesday || day == Day::Thursday || day == Day::Friday; +bool isWeekday(Day day) { + return day == Day::_ || day == Day::Tuesday || day == Day::Wednesday || + day == Day::Thursday || day == Day::Friday; } // TODO: Create a function that returns the next day. -Day nextDay(Day day) -{ - int next = static_cast(day) + 1; - if (next > static_cast(Day::Sunday)) - { - next = static_cast(Day::Monday); - } - return static_cast(next); +Day nextDay(Day day) { + int next = static_cast(day) + 1; + if (next > static_cast(Day::Sunday)) { + next = static_cast(Day::Monday); + } + return static_cast(next); } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Enums Enums01") -{ - REQUIRE(isWeekday(Day::Monday)); - REQUIRE(isWeekday(Day::Friday)); - REQUIRE_FALSE(isWeekday(Day::Saturday)); - REQUIRE_FALSE(isWeekday(Day::Sunday)); +TEST_CASE("Enums Enums01") { + REQUIRE(isWeekday(Day::Monday)); + REQUIRE(isWeekday(Day::Friday)); + REQUIRE_FALSE(isWeekday(Day::Saturday)); + REQUIRE_FALSE(isWeekday(Day::Sunday)); - REQUIRE(nextDay(Day::Monday) == Day::Tuesday); - REQUIRE(nextDay(Day::Sunday) == Day::Monday); + REQUIRE(nextDay(Day::Monday) == Day::Tuesday); + REQUIRE(nextDay(Day::Sunday) == Day::Monday); } diff --git a/exercises/11_classes/01_classes.cpp b/exercises/11_classes/01_classes.cpp index 3d20803..c2a2e1b 100644 --- a/exercises/11_classes/01_classes.cpp +++ b/exercises/11_classes/01_classes.cpp @@ -25,39 +25,26 @@ // - A public constructor that initializes count to 0 // - A public increment() method // - A public getCount() const method -class Counter -{ - int count; - - Counter() : count(0) - { - } - - void increment() - { - count++; - } - - int getCount() const - { - return count; - } +class Counter { + int count; + + Counter() : count(0) {} + + void increment() { count++; } + + int getCount() const { return count; } }; -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Classes Classes01") -{ - Counter c; - REQUIRE(c.getCount() == 0); +TEST_CASE("Classes Classes01") { + Counter c; + REQUIRE(c.getCount() == 0); - c.increment(); - REQUIRE(c.getCount() == 1); + c.increment(); + REQUIRE(c.getCount() == 1); - c.increment(); - c.increment(); - REQUIRE(c.getCount() == 3); + c.increment(); + c.increment(); + REQUIRE(c.getCount() == 3); } diff --git a/exercises/12_generics/01_generics.cpp b/exercises/12_generics/01_generics.cpp index 8954928..af51a59 100644 --- a/exercises/12_generics/01_generics.cpp +++ b/exercises/12_generics/01_generics.cpp @@ -17,46 +17,41 @@ // TODO: Implement a template function that returns the maximum of two values. // Use if-else or the ternary operator. -template maximum(T a, T b) -{ - return (a > b) ? a : b; +template +maximum(T a, T b) { + return (a > b) ? a : b; } // TODO: Implement a template function that swaps two values. -template void swap(T &a, T &b) -{ - T temp = a; - a = b; - b = temp; +template +void swap(T& a, T& b) { + T temp = a; + a = b; + b = temp; } // TODO: Implement a template function that returns the absolute value. -template T absolute(T value) -{ - if (value < T{}) - { - return -value; - } - return value; +template +T absolute(T value) { + if (value < T{}) { + return -value; + } + return value; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Generics Generics01") -{ - REQUIRE(maximum(5, 10) == 10); - REQUIRE(maximum(3.14, 2.71) == 3.14); - REQUIRE(maximum('a', 'z') == 'z'); +TEST_CASE("Generics Generics01") { + REQUIRE(maximum(5, 10) == 10); + REQUIRE(maximum(3.14, 2.71) == 3.14); + REQUIRE(maximum('a', 'z') == 'z'); - int x = 5, y = 10; - swap(x, y); - REQUIRE(x == 10); - REQUIRE(y == 5); + int x = 5, y = 10; + swap(x, y); + REQUIRE(x == 10); + REQUIRE(y == 5); - REQUIRE(absolute(-5) == 5); - REQUIRE(absolute(5) == 5); - REQUIRE(absolute(-3.14) == 3.14); + REQUIRE(absolute(-5) == 5); + REQUIRE(absolute(5) == 5); + REQUIRE(absolute(-3.14) == 3.14); } diff --git a/exercises/12_generics/02_generics.cpp b/exercises/12_generics/02_generics.cpp index 6a4ad77..dda262a 100644 --- a/exercises/12_generics/02_generics.cpp +++ b/exercises/12_generics/02_generics.cpp @@ -18,70 +18,48 @@ #include // TODO: Implement a simple Pair class template with getFirst() and getSecond(). -template class Pair -{ - public: - T first; - U second; +template +class Pair { + public: + T first; + U second; - Pair(T f, U s) : first(f), second(s) - { - } + Pair(T f, U s) : first(f), second(s) {} - getFirst() const - { - return first; - } - U getSecond() const - { - return second; - } + getFirst() const { return first; } + U getSecond() const { return second; } }; // TODO: Implement a Box class template that holds a single value. // Include a method to get the value and check if it's empty. -template class Box -{ - T value; - bool hasValue; +template +class Box { + T value; + bool hasValue; - public: - Box() : hasValue(false) - { - } - Box(T v) : value(v), hasValue(true) - { - } + public: + Box() : hasValue(false) {} + Box(T v) : value(v), hasValue(true) {} - bool isEmpty() const - { - return !hasValue; - } - T getValue() const - { - return value; - } + bool isEmpty() const { return !hasValue; } + T getValue() const { return value; } }; -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Generics Generics02") -{ - Pair p(42, "hello"); - REQUIRE(p.getFirst() == 42); - REQUIRE(p.getSecond() == "hello"); +TEST_CASE("Generics Generics02") { + Pair p(42, "hello"); + REQUIRE(p.getFirst() == 42); + REQUIRE(p.getSecond() == "hello"); - Pair p2(3.14, 'c'); - REQUIRE(p2.getFirst() == Catch::Approx(3.14)); - REQUIRE(p2.getSecond() == 'c'); + Pair p2(3.14, 'c'); + REQUIRE(p2.getFirst() == Catch::Approx(3.14)); + REQUIRE(p2.getSecond() == 'c'); - Box emptyBox; - REQUIRE(emptyBox.isEmpty()); + Box emptyBox; + REQUIRE(emptyBox.isEmpty()); - Box fullBox(42); - REQUIRE_FALSE(fullBox.isEmpty()); - REQUIRE(fullBox.getValue() == 42); + Box fullBox(42); + REQUIRE_FALSE(fullBox.isEmpty()); + REQUIRE(fullBox.getValue() == 42); } diff --git a/exercises/12_generics/03_generics.cpp b/exercises/12_generics/03_generics.cpp index 91bac54..2aeeea7 100644 --- a/exercises/12_generics/03_generics.cpp +++ b/exercises/12_generics/03_generics.cpp @@ -7,8 +7,10 @@ // Four forms: // 1. Unary left fold: (... op pack) -> ((pack1 op pack2) op ...) op packN // 2. Unary right fold: (pack op ...) -> pack1 op (pack2 op (... op packN)) -// 3. Binary left fold: (init op ... op pack) -> ((init op pack1) op ...) op packN -// 4. Binary right fold: (pack op ... op init) -> pack1 op (... op (packN op init)) +// 3. Binary left fold: (init op ... op pack) -> ((init op pack1) op ...) op +// packN +// 4. Binary right fold: (pack op ... op init) -> pack1 op (... op (packN op +// init)) // // Common use cases: // - (... + args) : sum all arguments @@ -24,52 +26,45 @@ // TODO: Implement sum using a unary left fold expression. // (... + args) adds all arguments together. -template auto sum(Args... args) -{ - return (+args); +template +auto sum(Args... args) { + return (+args); } // TODO: Implement printAll using a unary left fold. // Print all arguments separated by spaces. -void printValue(int value) -{ - std::cout << value << " "; -} +void printValue(int value) { std::cout << value << " "; } -template void printAll(T first, Args... args) -{ - std::cout << first << " "; - (..., (std::cout << args << " ")); +template +void printAll(T first, Args... args) { + std::cout << first << " "; + (..., (std::cout << args << " ")); } // TODO: Implement a function that returns true if all arguments are positive. -template bool allPositive(Args... args) -{ - return (... && (args > 0)); +template +bool allPositive(Args... args) { + return (... && (args > 0)); } // TODO: Implement a function that returns the logical OR of all arguments. -template bool anyTrue(Args... args) -{ - return (... || args); +template +bool anyTrue(Args... args) { + return (... || args); } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Generics Generics03") -{ - REQUIRE(sum(1, 2, 3, 4, 5) == 15); - REQUIRE(sum(1) == 1); - REQUIRE(sum(1.5, 2.5, 3.0) == 7.0); +TEST_CASE("Generics Generics03") { + REQUIRE(sum(1, 2, 3, 4, 5) == 15); + REQUIRE(sum(1) == 1); + REQUIRE(sum(1.5, 2.5, 3.0) == 7.0); - REQUIRE(allPositive(1, 2, 3)); - REQUIRE_FALSE(allPositive(1, -2, 3)); - REQUIRE(allPositive(5)); + REQUIRE(allPositive(1, 2, 3)); + REQUIRE_FALSE(allPositive(1, -2, 3)); + REQUIRE(allPositive(5)); - REQUIRE(anyTrue(false, true, false)); - REQUIRE_FALSE(anyTrue(false, false, false)); - REQUIRE(anyTrue(true)); + REQUIRE(anyTrue(false, true, false)); + REQUIRE_FALSE(anyTrue(false, false, false)); + REQUIRE(anyTrue(true)); } diff --git a/exercises/13_exceptions/01_exceptions.cpp b/exercises/13_exceptions/01_exceptions.cpp index c28ffa6..f2857ae 100644 --- a/exercises/13_exceptions/01_exceptions.cpp +++ b/exercises/13_exceptions/01_exceptions.cpp @@ -22,37 +22,29 @@ // TODO: Implement a function that divides two numbers. // Throw std::runtime_error if dividing by zero. -double divide(double a, double b) -{ - if (b == 0.0) - { - throw runtime_error("Division by zero"); - } - return a / b; +double divide(double a, double b) { + if (b == 0.0) { + throw runtime_error("Division by zero"); + } + return a / b; } // TODO: Implement a function that returns the element at index in an array. // Throw std::out_of_range if index is out of bounds. -int getElement(const int *arr, int size, int index) -{ - if (index < 0 || index >= size) - { - throw std::out_of_range("Index out of bounds"); - } - return arr[index]; +int getElement(const int* arr, int size, int index) { + if (index < 0 || index >= size) { + throw std::out_of_range("Index out of bounds"); + } + return arr[index]; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Exceptions Exceptions01") -{ - REQUIRE(divide(10.0, 2.0) == Catch::Approx(5.0)); - REQUIRE(divide(7.0, 3.0) == Catch::Approx(2.3333333333333335)); +TEST_CASE("Exceptions Exceptions01") { + REQUIRE(divide(10.0, 2.0) == Catch::Approx(5.0)); + REQUIRE(divide(7.0, 3.0) == Catch::Approx(2.3333333333333335)); - int arr[] = {1, 2, 3, 4, 5}; - REQUIRE(getElement(arr, 5, 0) == 1); - REQUIRE(getElement(arr, 5, 4) == 5); + int arr[] = {1, 2, 3, 4, 5}; + REQUIRE(getElement(arr, 5, 0) == 1); + REQUIRE(getElement(arr, 5, 4) == 5); } diff --git a/exercises/14_memory/01_memory.cpp b/exercises/14_memory/01_memory.cpp index 3b8aa13..850a30c 100644 --- a/exercises/14_memory/01_memory.cpp +++ b/exercises/14_memory/01_memory.cpp @@ -20,40 +20,28 @@ #include // TODO: Create a function that returns a unique_ptr to an int with value 42. -std::_ createValue() -{ - return std::make_unique(42); -} +std::_ createValue() { return std::make_unique(42); } -// TODO: Create a function that takes ownership of a unique_ptr and returns its value. -int extractValue(std::unique_ptr ptr) -{ - return *ptr; -} +// TODO: Create a function that takes ownership of a unique_ptr and returns its +// value. +int extractValue(std::unique_ptr ptr) { return *ptr; } // TODO: Use shared_ptr to share ownership of a value. -std::shared_ptr createShared() -{ - return std::make_shared(100); -} +std::shared_ptr createShared() { return std::make_shared(100); } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Memory Memory01") -{ - auto ptr = createValue(); - REQUIRE(*ptr == 42); +TEST_CASE("Memory Memory01") { + auto ptr = createValue(); + REQUIRE(*ptr == 42); - auto ptr2 = createValue(); - REQUIRE(extractValue(std::move(ptr2)) == 42); + auto ptr2 = createValue(); + REQUIRE(extractValue(std::move(ptr2)) == 42); - auto shared = createShared(); - REQUIRE(*shared == 100); - REQUIRE(shared.use_count() == 1); + auto shared = createShared(); + REQUIRE(*shared == 100); + REQUIRE(shared.use_count() == 1); - auto shared2 = shared; - REQUIRE(shared.use_count() == 2); + auto shared2 = shared; + REQUIRE(shared.use_count() == 2); } diff --git a/exercises/15_threads/01_threads.cpp b/exercises/15_threads/01_threads.cpp index f2675f4..b0f17f7 100644 --- a/exercises/15_threads/01_threads.cpp +++ b/exercises/15_threads/01_threads.cpp @@ -27,38 +27,30 @@ int counter = 0; // TODO: Implement a function that increments the counter safely. // Use a mutex to protect the shared resource. -void incrementSafely() -{ - std::_ lock(mtx); - counter++; +void incrementSafely() { + std::_ lock(mtx); + counter++; } // TODO: Implement a function that returns the current counter value. -int getCounter() -{ - std::lock_guard lock(mtx); - return counter; +int getCounter() { + std::lock_guard lock(mtx); + return counter; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Threads Threads01") -{ - counter = 0; +TEST_CASE("Threads Threads01") { + counter = 0; - std::vector threads; - for (int i = 0; i < 10; i++) - { - threads.push_back(std::thread(incrementSafely)); - } + std::vector threads; + for (int i = 0; i < 10; i++) { + threads.push_back(std::thread(incrementSafely)); + } - for (auto &t : threads) - { - t.join(); - } + for (auto& t : threads) { + t.join(); + } - REQUIRE(getCounter() == 10); + REQUIRE(getCounter() == 10); } diff --git a/exercises/16_preprocessors/01_preprocessors.cpp b/exercises/16_preprocessors/01_preprocessors.cpp index 96ec93f..fbc921d 100644 --- a/exercises/16_preprocessors/01_preprocessors.cpp +++ b/exercises/16_preprocessors/01_preprocessors.cpp @@ -27,19 +27,15 @@ // TODO: Define a macro IS_EVEN that returns true if a number is even. #define IS_EVEN(x) ((x) % 2 == 0) -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Preprocessors Preprocessors01") -{ - REQUIRE(SQUARE(5) == 25); - REQUIRE(SQUARE(-3) == 9); +TEST_CASE("Preprocessors Preprocessors01") { + REQUIRE(SQUARE(5) == 25); + REQUIRE(SQUARE(-3) == 9); - REQUIRE(MAX(3, 5) == 5); - REQUIRE(MAX(10, 2) == 10); + REQUIRE(MAX(3, 5) == 5); + REQUIRE(MAX(10, 2) == 10); - REQUIRE(IS_EVEN(4)); - REQUIRE_FALSE(IS_EVEN(5)); + REQUIRE(IS_EVEN(4)); + REQUIRE_FALSE(IS_EVEN(5)); } diff --git a/exercises/17_bit-manipulation/01_bit-manipulation.cpp b/exercises/17_bit-manipulation/01_bit-manipulation.cpp index 2a9b4d2..dc942c0 100644 --- a/exercises/17_bit-manipulation/01_bit-manipulation.cpp +++ b/exercises/17_bit-manipulation/01_bit-manipulation.cpp @@ -22,45 +22,29 @@ #include // TODO: Implement a function that sets the nth bit of a number. -setBit(int num, int n) -{ - return num | (1 << n); -} +setBit(int num, int n) { return num | (1 << n); } // TODO: Implement a function that clears the nth bit of a number. -int clearBit(int num, int n) -{ - return num & ~(1 << n); -} +int clearBit(int num, int n) { return num & ~(1 << n); } // TODO: Implement a function that toggles the nth bit of a number. -int toggleBit(int num, int n) -{ - return num ^ (1 << n); -} +int toggleBit(int num, int n) { return num ^ (1 << n); } // TODO: Implement a function that checks if the nth bit is set. -bool isBitSet(int num, int n) -{ - return (num & (1 << n)) != 0; -} +bool isBitSet(int num, int n) { return (num & (1 << n)) != 0; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("BitManipulation BitManipulation01") -{ - REQUIRE(setBit(0, 0) == 1); - REQUIRE(setBit(4, 1) == 6); +TEST_CASE("BitManipulation BitManipulation01") { + REQUIRE(setBit(0, 0) == 1); + REQUIRE(setBit(4, 1) == 6); - REQUIRE(clearBit(7, 0) == 6); - REQUIRE(clearBit(8, 3) == 0); + REQUIRE(clearBit(7, 0) == 6); + REQUIRE(clearBit(8, 3) == 0); - REQUIRE(toggleBit(5, 0) == 4); - REQUIRE(toggleBit(4, 0) == 5); + REQUIRE(toggleBit(5, 0) == 4); + REQUIRE(toggleBit(4, 0) == 5); - REQUIRE(isBitSet(5, 0)); - REQUIRE_FALSE(isBitSet(5, 1)); + REQUIRE(isBitSet(5, 0)); + REQUIRE_FALSE(isBitSet(5, 1)); } diff --git a/exercises/extras_cpp-history/01_cpp-history.cpp b/exercises/extras_cpp-history/01_cpp-history.cpp index 9633273..aaee4e6 100644 --- a/exercises/extras_cpp-history/01_cpp-history.cpp +++ b/exercises/extras_cpp-history/01_cpp-history.cpp @@ -14,21 +14,17 @@ #include #include -int main() -{ - // TODO: Make this variable "truthy" to compile. - // NOTE: Please read the comments above. - bool hasRead{false}; +int main() { + // TODO: Make this variable "truthy" to compile. + // NOTE: Please read the comments above. + bool hasRead{false}; - try - { - if (!hasRead) - { - throw runtime_error("Please view the code of this exercise before proceeding."); - } - } - catch (std::exception &e) - { - std::cout << e.what(); + try { + if (!hasRead) { + throw runtime_error( + "Please view the code of this exercise before proceeding."); } + } catch (std::exception& e) { + std::cout << e.what(); + } } diff --git a/exercises/extras_development/01_development.cpp b/exercises/extras_development/01_development.cpp index 3be1c80..16b7289 100644 --- a/exercises/extras_development/01_development.cpp +++ b/exercises/extras_development/01_development.cpp @@ -3,7 +3,4 @@ // #include -int main() -{ - std::cout << "Coming soon!" << std::endl; -} +int main() { std::cout << "Coming soon!" << std::endl; } diff --git a/exercises/extras_networking/01_networking.cpp b/exercises/extras_networking/01_networking.cpp index 3be1c80..16b7289 100644 --- a/exercises/extras_networking/01_networking.cpp +++ b/exercises/extras_networking/01_networking.cpp @@ -3,7 +3,4 @@ // #include -int main() -{ - std::cout << "Coming soon!" << std::endl; -} +int main() { std::cout << "Coming soon!" << std::endl; } diff --git a/solutions/00_intro/01_intro.cpp b/solutions/00_intro/01_intro.cpp index c0669c2..b4b9a5b 100644 --- a/solutions/00_intro/01_intro.cpp +++ b/solutions/00_intro/01_intro.cpp @@ -4,21 +4,19 @@ #include -void splashScreen() -{ - std::cout << " _ _ \n"; - std::cout << " | (_) \n"; - std::cout << " ___ _ __ _ __ | |_ _ __ __ _ ___ \n"; - std::cout << " / __| '_ \\| '_ \\| | | '_ \\ / _` / __|\n"; - std::cout << "| (__| |_) | |_) | | | | | | (_| \\__ \\\n"; - std::cout << " \\___| .__/| .__/|_|_|_| |_|\\__, |___/\n"; - std::cout << " | | | | __/ | \n"; - std::cout << " |_| |_| |___/ \n"; - std::cout << " \n"; +void splashScreen() { + std::cout << " _ _ \n"; + std::cout << " | (_) \n"; + std::cout << " ___ _ __ _ __ | |_ _ __ __ _ ___ \n"; + std::cout << " / __| '_ \\| '_ \\| | | '_ \\ / _` / __|\n"; + std::cout << "| (__| |_) | |_) | | | | | | (_| \\__ \\\n"; + std::cout << " \\___| .__/| .__/|_|_|_| |_|\\__, |___/\n"; + std::cout << " | | | | __/ | \n"; + std::cout << " |_| |_| |___/ \n"; + std::cout << " \n"; } -int main() -{ - splashScreen(); - return 0; +int main() { + splashScreen(); + return 0; } diff --git a/solutions/00_intro/02_intro.cpp b/solutions/00_intro/02_intro.cpp index 725fe31..ffadfb4 100644 --- a/solutions/00_intro/02_intro.cpp +++ b/solutions/00_intro/02_intro.cpp @@ -18,13 +18,9 @@ #include -void message() -{ - // TODO: Fix the line of code to print "Hello World!" to the console. - std::cout << "Hello World!"; +void message() { + // TODO: Fix the line of code to print "Hello World!" to the console. + std::cout << "Hello World!"; } -int main() -{ - message(); -} +int main() { message(); } diff --git a/solutions/01_variables/01_variables.cpp b/solutions/01_variables/01_variables.cpp index 3352b70..f598c3b 100644 --- a/solutions/01_variables/01_variables.cpp +++ b/solutions/01_variables/01_variables.cpp @@ -16,7 +16,8 @@ // // In C++, variables can be named whatever using different conventions unlike // certain languages like Rust or Python where they must be named in snake_case. -// In C/C++, variables are often named using the camelCase or snake_case convention. +// In C/C++, variables are often named using the camelCase or snake_case +// convention. // // https://www.learncpp.com/cpp-tutorial/introduction-to-objects-and-variables/ // https://www.learncpp.com/cpp-tutorial/variable-assignment-and-initialization/ @@ -27,19 +28,16 @@ // TODO: Add the missing module for printing #include -void variables01() -{ - // TODO: Assign an integer to a variable named "x" using direct list initialization. - int x{5}; +void variables01() { + // TODO: Assign an integer to a variable named "x" using direct list + // initialization. + int x{5}; - // TODO: Assign an integer to a variable named "y" using the classic way. - int y = 10; + // TODO: Assign an integer to a variable named "y" using the classic way. + int y = 10; - std::cout << "direct list initialization -> " << "x{" << x << "}" << "\n"; - std::cout << "classic way -> " << "y" << "=" << y; + std::cout << "direct list initialization -> " << "x{" << x << "}" << "\n"; + std::cout << "classic way -> " << "y" << "=" << y; } -int main() -{ - variables01(); -} +int main() { variables01(); } diff --git a/solutions/01_variables/02_variables.cpp b/solutions/01_variables/02_variables.cpp index fa4da2d..513f6e3 100644 --- a/solutions/01_variables/02_variables.cpp +++ b/solutions/01_variables/02_variables.cpp @@ -10,15 +10,11 @@ #include -void variables02() -{ - // TODO: Add a missing type and value. - int x{5}; +void variables02() { + // TODO: Add a missing type and value. + int x{5}; - std::cout << "x=" << x; + std::cout << "x=" << x; } -int main() -{ - variables02(); -} +int main() { variables02(); } diff --git a/solutions/01_variables/03_variables.cpp b/solutions/01_variables/03_variables.cpp index a41c2c2..b76ce1c 100644 --- a/solutions/01_variables/03_variables.cpp +++ b/solutions/01_variables/03_variables.cpp @@ -14,18 +14,16 @@ #include #include -void variables03() -{ - // TODO: Declare a constant variable with a value and then print it out to stdout. - const int FOO{5}; +void variables03() { + // TODO: Declare a constant variable with a value and then print it out to + // stdout. + const int FOO{5}; - std::cout << FOO; + std::cout << FOO; - static_assert(std::is_const_v, - "The variable must be a constant."); // NOTE: Ignore this line of code. + static_assert( + std::is_const_v, + "The variable must be a constant."); // NOTE: Ignore this line of code. } -int main() -{ - variables03(); -} +int main() { variables03(); } diff --git a/solutions/01_variables/04_variables.cpp b/solutions/01_variables/04_variables.cpp index 96cf905..69178d4 100644 --- a/solutions/01_variables/04_variables.cpp +++ b/solutions/01_variables/04_variables.cpp @@ -7,32 +7,30 @@ #include #include -void variables04() -{ - // TODO: Change the line below to fix the compiler error. - // NOTE: Use the test case as reference. - int baz{5}; +void variables04() { + // TODO: Change the line below to fix the compiler error. + // NOTE: Use the test case as reference. + int baz{5}; - // TODO: Also print out the value of baz to stdout in a sentence "baz=5". - std::cout << "baz=" << baz; + // TODO: Also print out the value of baz to stdout in a sentence "baz=5". + std::cout << "baz=" << baz; } -int main(int argc, char **argv) -{ - variables04(); +int main(int argc, char** argv) { + variables04(); - std::cout << "\n\n" << "Testing output begins here\n--------------------------" << "\n"; - return Catch::Session().run(argc, argv); + std::cout << "\n\n" + << "Testing output begins here\n--------------------------" << "\n"; + return Catch::Session().run(argc, argv); } -TEST_CASE("Variables Variables04") -{ - std::stringstream buffer; - std::streambuf *old = std::cout.rdbuf(buffer.rdbuf()); +TEST_CASE("Variables Variables04") { + std::stringstream buffer; + std::streambuf* old = std::cout.rdbuf(buffer.rdbuf()); - variables04(); + variables04(); - std::cout.rdbuf(old); - std::string output{buffer.str()}; - REQUIRE(output == "baz=5"); + std::cout.rdbuf(old); + std::string output{buffer.str()}; + REQUIRE(output == "baz=5"); } diff --git a/solutions/01_variables/05_variables.cpp b/solutions/01_variables/05_variables.cpp index c73cb55..07139f2 100644 --- a/solutions/01_variables/05_variables.cpp +++ b/solutions/01_variables/05_variables.cpp @@ -6,16 +6,14 @@ // Datatypes can be "inferred" by using the "auto" keyword. #include -int main() -{ - // TODO: Infer the datatype using the "auto" keyword. - // Assign a "truthy" value to compile. - auto doesAutoWork{true}; +int main() { + // TODO: Infer the datatype using the "auto" keyword. + // Assign a "truthy" value to compile. + auto doesAutoWork{true}; - std::cout << "doesAutoWork? -> " << doesAutoWork; + std::cout << "doesAutoWork? -> " << doesAutoWork; - if (!doesAutoWork) - { - return 1; - } + if (!doesAutoWork) { + return 1; + } } diff --git a/solutions/02_functions/01_functions.cpp b/solutions/02_functions/01_functions.cpp index 2a4b28f..0d3f18b 100644 --- a/solutions/02_functions/01_functions.cpp +++ b/solutions/02_functions/01_functions.cpp @@ -3,21 +3,22 @@ // // Evey programmer knows that functions are resuable pieces of code. // -// Each function is called and assigned/"pushed" on to the stack (fragment of memory). -// Read more about the stack here: https://en.wikipedia.org/wiki/Stack-based_memory_allocation/ +// Each function is called and assigned/"pushed" on to the stack (fragment of +// memory). Read more about the stack here: +// https://en.wikipedia.org/wiki/Stack-based_memory_allocation/ // // A C++ function includes: // - The functions signature: int f(int x) // | | | -// | | parameter list (parameter datatype parameter name, ...) -// | | -// | function name +// | | parameter list (parameter datatype +// parameter name, ...) | | | function name // | // function return type // // - Function clause/body: // { -> function scope beginning -// return x; -> return (depends on function return type; will be explained in an upcoming exercise) +// return x; -> return (depends on function +//return type; will be explained in an upcoming exercise) // } -> function scope ending // // Functions are normally named using the camelCase convention. @@ -31,28 +32,27 @@ #include // TODO: Create the function signature. -// Add the function return type, name "f" and a parameter "x" with an int datatype. -int f(int x) -{ - int y{x + 1}; +// Add the function return type, name "f" and a parameter "x" with an int +// datatype. +int f(int x) { + int y{x + 1}; - std::cout << "x: " << x << " " << "y: " << y << std::endl; + std::cout << "x: " << x << " " << "y: " << y << std::endl; - return y; + return y; } -int main(int argc, char **argv) -{ - // TODO: Call the function and pass in an appropriate parameter. - f(10); +int main(int argc, char** argv) { + // TODO: Call the function and pass in an appropriate parameter. + f(10); - std::cout << "\n\n" << "Testing output begins here\n--------------------------" << "\n"; - return Catch::Session().run(argc, argv); + std::cout << "\n\n" + << "Testing output begins here\n--------------------------" << "\n"; + return Catch::Session().run(argc, argv); } -TEST_CASE("Functions Function01") -{ - REQUIRE(f(0) == 1); - REQUIRE(f(1) == 2); - REQUIRE(f(2) == 3); +TEST_CASE("Functions Function01") { + REQUIRE(f(0) == 1); + REQUIRE(f(1) == 2); + REQUIRE(f(2) == 3); }; diff --git a/solutions/02_functions/02_functions.cpp b/solutions/02_functions/02_functions.cpp index a61c908..af44975 100644 --- a/solutions/02_functions/02_functions.cpp +++ b/solutions/02_functions/02_functions.cpp @@ -14,37 +14,36 @@ #include // TODO: Add the missing keyword. -// NOTE: Use the rest of the code as reference to determine which datatype needs to be returned. -int bar() -{ - // TODO: Change the line below to fix the compiler error. - // NOTE: Use the test case as reference. - int baz{5}; +// NOTE: Use the rest of the code as reference to determine which datatype needs +// to be returned. +int bar() { + // TODO: Change the line below to fix the compiler error. + // NOTE: Use the test case as reference. + int baz{5}; - // TODO: Also print out the value of baz to stdout in a sentence "baz=5". - std::cout << "baz=" << baz; + // TODO: Also print out the value of baz to stdout in a sentence "baz=5". + std::cout << "baz=" << baz; - return baz; + return baz; } -int main(int argc, char **argv) -{ - // TODO: call the bar function - bar(); +int main(int argc, char** argv) { + // TODO: call the bar function + bar(); - std::cout << "\n\n" << "Testing output begins here\n--------------------------" << "\n"; - return Catch::Session().run(argc, argv); + std::cout << "\n\n" + << "Testing output begins here\n--------------------------" << "\n"; + return Catch::Session().run(argc, argv); } -TEST_CASE("Variables Variables04") -{ - std::stringstream buffer; - std::streambuf *old = std::cout.rdbuf(buffer.rdbuf()); +TEST_CASE("Variables Variables04") { + std::stringstream buffer; + std::streambuf* old = std::cout.rdbuf(buffer.rdbuf()); - bar(); + bar(); - std::cout.rdbuf(old); - std::string output{buffer.str()}; - REQUIRE(bar() == 5); - REQUIRE(output == "baz=5"); + std::cout.rdbuf(old); + std::string output{buffer.str()}; + REQUIRE(bar() == 5); + REQUIRE(output == "baz=5"); } diff --git a/solutions/02_functions/03_functions.cpp b/solutions/02_functions/03_functions.cpp index b136a1c..2884c0a 100644 --- a/solutions/02_functions/03_functions.cpp +++ b/solutions/02_functions/03_functions.cpp @@ -24,49 +24,41 @@ // TODO: Add the function datatype and name. // Add two parameters, one that takes in a boolean and the other a float. -void voidFunction(bool isTruthy, float randomValue) -{ - try - { - - if (typeid(isTruthy).name() != typeid(bool).name()) - { - throw std::runtime_error("The first parameter is not a boolean.\n"); - } - - if (typeid(randomValue).name() != typeid(float).name()) - { - throw std::runtime_error("The second parameter is not a float.\n"); - } +void voidFunction(bool isTruthy, float randomValue) { + try { + if (typeid(isTruthy).name() != typeid(bool).name()) { + throw std::runtime_error("The first parameter is not a boolean.\n"); } - catch (const std::exception &e) - { - std::cout << e.what(); + + if (typeid(randomValue).name() != typeid(float).name()) { + throw std::runtime_error("The second parameter is not a float.\n"); } + } catch (const std::exception& e) { + std::cout << e.what(); + } - // TODO: Implement the additional required logic. - // NOTE: Use the test case as reference. - std::cout << "This is a void function!"; + // TODO: Implement the additional required logic. + // NOTE: Use the test case as reference. + std::cout << "This is a void function!"; } -int main(int argc, char **argv) -{ - // TODO: Call the function and pass in the approriate arguments. - voidFunction(true, 5); +int main(int argc, char** argv) { + // TODO: Call the function and pass in the approriate arguments. + voidFunction(true, 5); - std::cout << "\n\n" << "Testing output begins here\n--------------------------" << "\n"; - return Catch::Session().run(argc, argv); + std::cout << "\n\n" + << "Testing output begins here\n--------------------------" << "\n"; + return Catch::Session().run(argc, argv); } -TEST_CASE("Functions Functions03") -{ - std::stringstream buffer; - std::streambuf *old = std::cout.rdbuf(buffer.rdbuf()); +TEST_CASE("Functions Functions03") { + std::stringstream buffer; + std::streambuf* old = std::cout.rdbuf(buffer.rdbuf()); - // TODO: Call the function and pass in the approriate arguments. - voidFunction(true, 5); + // TODO: Call the function and pass in the approriate arguments. + voidFunction(true, 5); - std::cout.rdbuf(old); - std::string output{buffer.str()}; - REQUIRE(output == "This is a void function!"); + std::cout.rdbuf(old); + std::string output{buffer.str()}; + REQUIRE(output == "This is a void function!"); } diff --git a/solutions/02_functions/04_functions.cpp b/solutions/02_functions/04_functions.cpp index 4f06f76..49955f2 100644 --- a/solutions/02_functions/04_functions.cpp +++ b/solutions/02_functions/04_functions.cpp @@ -5,45 +5,50 @@ // It is the entry point to any and every application/project/piece of software. // // The main() function returns an integer, but some of the exercises you noticed -// that some of them don't return any integer, just like a void function omitting -// the "return" keyword. The main function allows this, it implicitly handles -// the returned value. -// -// However, in the previous cases you may have encountered booleans. When booleans -// are printed to stdout, they appear to be different than "true" and "false", 1 and 0 respectively. -// More on booleans in upcoming exercises. -// -// The main() function does not return a boolean value, it just returns an integer. -// A main() function returning 0 returns "0 errors". Any value other the 0 means an error. -// Explicitly returning 0; { return 0; } is considered good practice in C++ development. -// -// The parameters in the main(int argc, char *argv[]) function are the program's/application's arguments. -// | | -// | can also be char **argv, -// | are arguments as an array of -// | string slices or string literals +// that some of them don't return any integer, just like a void function +// omitting the "return" keyword. The main function allows this, it implicitly +// handles the returned value. +// +// However, in the previous cases you may have encountered booleans. When +// booleans are printed to stdout, they appear to be different than "true" and +// "false", 1 and 0 respectively. More on booleans in upcoming exercises. +// +// The main() function does not return a boolean value, it just returns an +// integer. A main() function returning 0 returns "0 errors". Any value other +// the 0 means an error. Explicitly returning 0; { return 0; } is considered +// good practice in C++ development. +// +// The parameters in the main(int argc, char *argv[]) function are the +// program's/application's arguments. +// | +//| | can also be char **argv, | +//are arguments as an array of | string +//slices or string literals // | -// number of arguments passed into the main function; -// used for iterating the argument array +// number +//of arguments passed into the main function; used for iterating the argument +//array // -// When a compiled program is called, the name of the program or the program executable is the first argument. -// In programs/applications, especially CLI programs that use arguments; ./program arg1 arg2, are also passed to the +// When a compiled program is called, the name of the program or the program +// executable is the first argument. In programs/applications, especially CLI +// programs that use arguments; ./program arg1 arg2, are also passed to the // main() function. // -// You can compile this specific exercise using "zig build exercises -- ./exercises/path/to/exercise/file", -// ensure you pass in the correct path of this file. The binary will be in ./zig-out/bin/cpplings_exercise -// Run it and experiment with the arguments. +// You can compile this specific exercise using "zig build exercises -- +// ./exercises/path/to/exercise/file", ensure you pass in the correct path of +// this file. The binary will be in ./zig-out/bin/cpplings_exercise Run it and +// experiment with the arguments. // -// We also recommend coming back to this exercise and try out the concepts that you will learn in the upcoming -// exercises. +// We also recommend coming back to this exercise and try out the concepts that +// you will learn in the upcoming exercises. // // https://www.learncpp.com/cpp-tutorial/statements-and-the-structure-of-a-program/ // https://www.learncpp.com/cpp-tutorial/command-line-arguments/ #include -int main(int argc, char *argv[]) -{ - // TODO: Print out the argc and argv. - std::cout << "Number of arguments: " << argc << "\n" << "Arguments: " << *argv << std::endl; +int main(int argc, char* argv[]) { + // TODO: Print out the argc and argv. + std::cout << "Number of arguments: " << argc << "\n" + << "Arguments: " << *argv << std::endl; } diff --git a/solutions/02_functions/05_functions.cpp b/solutions/02_functions/05_functions.cpp index 8c489cd..f56d655 100644 --- a/solutions/02_functions/05_functions.cpp +++ b/solutions/02_functions/05_functions.cpp @@ -5,13 +5,7 @@ int add(int x, int y); -int main() -{ - add(1, 2); -} +int main() { add(1, 2); } // TODO: Fix the function to fix the compile error. -int add(int x, int y) -{ - return x + y; -} +int add(int x, int y) { return x + y; } diff --git a/solutions/02_functions/06_functions.cpp b/solutions/02_functions/06_functions.cpp index 07fa2f2..468ddff 100644 --- a/solutions/02_functions/06_functions.cpp +++ b/solutions/02_functions/06_functions.cpp @@ -21,33 +21,20 @@ #include // A function that adds two integers. -int add(int x, int y) -{ - return x + y; -} +int add(int x, int y) { return x + y; } // A function that adds two floats. // The compiler knows this is different from add(int, int) // because the parameter types are different. -float add(float x, float y) -{ - return x + y; -} +float add(float x, float y) { return x + y; } // A function that adds two doubles. -double add(double x, double y) -{ - return x + y; -} +double add(double x, double y) { return x + y; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Functions Functions06") -{ - REQUIRE(add(1, 1) == 2); - REQUIRE(add(5.0f, 5.0f) == 10.0f); - REQUIRE(add(100.555555, 100.555555) == 201.11111); +TEST_CASE("Functions Functions06") { + REQUIRE(add(1, 1) == 2); + REQUIRE(add(5.0f, 5.0f) == 10.0f); + REQUIRE(add(100.555555, 100.555555) == 201.11111); } diff --git a/solutions/02_functions/07_functions.cpp b/solutions/02_functions/07_functions.cpp index 8bae0e1..641576b 100644 --- a/solutions/02_functions/07_functions.cpp +++ b/solutions/02_functions/07_functions.cpp @@ -11,7 +11,8 @@ // // Every recursive function needs: // 1. A base case (when to stop) - here: n == 0 or n == 1 -// 2. A recursive case (call itself with modified argument) - here: f(n-1) + f(n-2) +// 2. A recursive case (call itself with modified argument) - here: f(n-1) + +// f(n-2) // // Warning: This naive fibonacci implementation is inefficient for large n // because it recalculates the same values many times. @@ -28,43 +29,35 @@ // The recursive fibonacci function. // Base case: when n is 0 or 1, return n itself. // Recursive case: return the sum of the previous two fibonacci numbers. -int fibonacci(int n) -{ - // Base case: fibonacci(0) = 0, fibonacci(1) = 1 - if (n == 0 || n == 1) - { - return n; - } - - // Recursive case: f(n) = f(n-1) + f(n-2) - return fibonacci(n - 1) + fibonacci(n - 2); +int fibonacci(int n) { + // Base case: fibonacci(0) = 0, fibonacci(1) = 1 + if (n == 0 || n == 1) { + return n; + } + + // Recursive case: f(n) = f(n-1) + f(n-2) + return fibonacci(n - 1) + fibonacci(n - 2); } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Functions Functions07") -{ - std::stringstream buffer; - std::streambuf *old = std::cout.rdbuf(buffer.rdbuf()); +TEST_CASE("Functions Functions07") { + std::stringstream buffer; + std::streambuf* old = std::cout.rdbuf(buffer.rdbuf()); - for (int n = 0; n <= 10; ++n) - { - if (n == 10) - { - std::cout << fibonacci(n) << ",..." << std::endl; - continue; - } - - std::cout << fibonacci(n) << ", "; + for (int n = 0; n <= 10; ++n) { + if (n == 10) { + std::cout << fibonacci(n) << ",..." << std::endl; + continue; } - std::cout.rdbuf(old); - std::string output{buffer.str()}; + std::cout << fibonacci(n) << ", "; + } + + std::cout.rdbuf(old); + std::string output{buffer.str()}; - REQUIRE(output == "0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,...\n"); + REQUIRE(output == "0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,...\n"); - std::cout << "\n" << output << "\n"; + std::cout << "\n" << output << "\n"; } diff --git a/solutions/02_functions/08_functions.cpp b/solutions/02_functions/08_functions.cpp index 327b0c4..535cc78 100644 --- a/solutions/02_functions/08_functions.cpp +++ b/solutions/02_functions/08_functions.cpp @@ -6,7 +6,8 @@ // // Lambda syntax: [capture clause](parameters) -> return_type { body } // -// - Capture clause []: specifies which variables from the enclosing scope to capture +// - Capture clause []: specifies which variables from the enclosing scope to +// capture // - Parameters (): like regular function parameters // - Return type ->: can be omitted for type inference // - Body {}: the actual code @@ -37,27 +38,22 @@ auto isEven = [](int n) -> bool { return n % 2 == 0; }; // Return type is inferred as int. auto doubleIt = [](int n) { return n * 2; }; -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Functions Functions08") -{ - REQUIRE(isEven(2)); - REQUIRE(isEven(4)); - REQUIRE_FALSE(isEven(3)); - REQUIRE_FALSE(isEven(5)); +TEST_CASE("Functions Functions08") { + REQUIRE(isEven(2)); + REQUIRE(isEven(4)); + REQUIRE_FALSE(isEven(3)); + REQUIRE_FALSE(isEven(5)); - REQUIRE(doubleIt(5) == 10); - REQUIRE(doubleIt(0) == 0); - REQUIRE(doubleIt(-3) == -6); + REQUIRE(doubleIt(5) == 10); + REQUIRE(doubleIt(0) == 0); + REQUIRE(doubleIt(-3) == -6); } -TEST_CASE("Functions Functions08_Capture") -{ - // Lambda with capture by value [=]. - const int multiplier = 3; - auto multiplyByGlobal = [=](int n) { return n * multiplier; }; - REQUIRE(multiplyByGlobal(4) == 12); +TEST_CASE("Functions Functions08_Capture") { + // Lambda with capture by value [=]. + const int multiplier = 3; + auto multiplyByGlobal = [=](int n) { return n * multiplier; }; + REQUIRE(multiplyByGlobal(4) == 12); } diff --git a/solutions/02_functions/09_functions.cpp b/solutions/02_functions/09_functions.cpp index 08decd1..c107f37 100644 --- a/solutions/02_functions/09_functions.cpp +++ b/solutions/02_functions/09_functions.cpp @@ -25,39 +25,32 @@ // Calculates the sum of integers using va_list. // The first argument specifies how many integers follow. -int sumInts(int count, ...) -{ - va_list args; - va_start(args, count); +int sumInts(int count, ...) { + va_list args; + va_start(args, count); - int sum = 0; - for (int i = 0; i < count; i++) - { - sum += va_arg(args, int); - } + int sum = 0; + for (int i = 0; i < count; i++) { + sum += va_arg(args, int); + } - va_end(args); - return sum; + va_end(args); + return sum; } // Prints formatted output using va_list. // Uses printf-style format string with variable arguments. -void printFormatted(const char *format, ...) -{ - va_list args; - va_start(args, format); - vprintf(format, args); - va_end(args); +void printFormatted(const char* format, ...) { + va_list args; + va_start(args, format); + vprintf(format, args); + va_end(args); } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Functions Functions09") -{ - REQUIRE(sumInts(3, 1, 2, 3) == 6); - REQUIRE(sumInts(5, 1, 2, 3, 4, 5) == 15); - REQUIRE(sumInts(1, 42) == 42); +TEST_CASE("Functions Functions09") { + REQUIRE(sumInts(3, 1, 2, 3) == 6); + REQUIRE(sumInts(5, 1, 2, 3, 4, 5) == 15); + REQUIRE(sumInts(1, 42) == 42); } diff --git a/solutions/02_functions/10_functions.cpp b/solutions/02_functions/10_functions.cpp index 55535cf..ab64faa 100644 --- a/solutions/02_functions/10_functions.cpp +++ b/solutions/02_functions/10_functions.cpp @@ -34,29 +34,25 @@ // Base case: single argument - just return it // This terminates the recursion. -template T sum(T value) -{ - return value; +template +T sum(T value) { + return value; } // Recursive case: add first argument to sum of rest // typename... Args is a template parameter pack (holds types) // Args... args is a function parameter pack (holds values) -template T sum(T first, Args... args) -{ - // Recursively call sum with remaining arguments - return first + sum(args...); +template +T sum(T first, Args... args) { + // Recursively call sum with remaining arguments + return first + sum(args...); } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Functions Functions10") -{ - REQUIRE(sum(1, 2, 3) == 6); - REQUIRE(sum(1, 2, 3, 4, 5) == 15); - REQUIRE(sum(10) == 10); - REQUIRE(sum(1.5, 2.5, 3.0) == 7.0); +TEST_CASE("Functions Functions10") { + REQUIRE(sum(1, 2, 3) == 6); + REQUIRE(sum(1, 2, 3, 4, 5) == 15); + REQUIRE(sum(10) == 10); + REQUIRE(sum(1.5, 2.5, 3.0) == 7.0); } diff --git a/solutions/03_control-flow/01_control-flow.cpp b/solutions/03_control-flow/01_control-flow.cpp index b0d8a44..fd809ce 100644 --- a/solutions/03_control-flow/01_control-flow.cpp +++ b/solutions/03_control-flow/01_control-flow.cpp @@ -25,62 +25,42 @@ #include // Returns a grade letter based on the numeric score. -char getGrade(int score) -{ - if (score >= 90) - { - return 'A'; - } - else if (score >= 80) - { - return 'B'; - } - else if (score >= 70) - { - return 'C'; - } - else if (score >= 60) - { - return 'D'; - } - else - { - return 'F'; - } +char getGrade(int score) { + if (score >= 90) { + return 'A'; + } else if (score >= 80) { + return 'B'; + } else if (score >= 70) { + return 'C'; + } else if (score >= 60) { + return 'D'; + } else { + return 'F'; + } } // Checks if a number is positive, negative, or zero. // Returns 1 for positive, -1 for negative, 0 for zero. -int checkNumber(int num) -{ - if (num > 0) - { - return 1; - } - else if (num < 0) - { - return -1; - } - else - { - return 0; - } +int checkNumber(int num) { + if (num > 0) { + return 1; + } else if (num < 0) { + return -1; + } else { + return 0; + } } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("ControlFlow ControlFlow01") -{ - REQUIRE(getGrade(95) == 'A'); - REQUIRE(getGrade(85) == 'B'); - REQUIRE(getGrade(75) == 'C'); - REQUIRE(getGrade(65) == 'D'); - REQUIRE(getGrade(55) == 'F'); +TEST_CASE("ControlFlow ControlFlow01") { + REQUIRE(getGrade(95) == 'A'); + REQUIRE(getGrade(85) == 'B'); + REQUIRE(getGrade(75) == 'C'); + REQUIRE(getGrade(65) == 'D'); + REQUIRE(getGrade(55) == 'F'); - REQUIRE(checkNumber(5) == 1); - REQUIRE(checkNumber(-3) == -1); - REQUIRE(checkNumber(0) == 0); + REQUIRE(checkNumber(5) == 1); + REQUIRE(checkNumber(-3) == -1); + REQUIRE(checkNumber(0) == 0); } diff --git a/solutions/03_control-flow/02_control-flow.cpp b/solutions/03_control-flow/02_control-flow.cpp index d0971b4..2304acf 100644 --- a/solutions/03_control-flow/02_control-flow.cpp +++ b/solutions/03_control-flow/02_control-flow.cpp @@ -22,78 +22,70 @@ // Returns the number of days in a given month. // Uses switch for cleaner code than if-else chains. -int getDaysInMonth(int month) -{ - switch (month) - { +int getDaysInMonth(int month) { + switch (month) { case 1: - return 31; + return 31; case 2: - return 28; + return 28; case 3: - return 31; + return 31; case 4: - return 30; + return 30; case 5: - return 31; + return 31; case 6: - return 30; + return 30; case 7: - return 31; + return 31; case 8: - return 31; + return 31; case 9: - return 30; + return 30; case 10: - return 31; + return 31; case 11: - return 30; + return 30; case 12: - return 31; + return 31; default: - return -1; - } + return -1; + } } // Returns the name of a day of the week. // 1 = Monday, 2 = Tuesday, etc. -const char *getDayOfWeek(int day) -{ - switch (day) - { +const char* getDayOfWeek(int day) { + switch (day) { case 1: - return "Monday"; + return "Monday"; case 2: - return "Tuesday"; + return "Tuesday"; case 3: - return "Wednesday"; + return "Wednesday"; case 4: - return "Thursday"; + return "Thursday"; case 5: - return "Friday"; + return "Friday"; case 6: - return "Saturday"; + return "Saturday"; case 7: - return "Sunday"; + return "Sunday"; default: - return "Invalid"; - } + return "Invalid"; + } } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("ControlFlow ControlFlow02") -{ - REQUIRE(getDaysInMonth(1) == 31); - REQUIRE(getDaysInMonth(2) == 28); - REQUIRE(getDaysInMonth(4) == 30); - REQUIRE(getDaysInMonth(12) == 31); - REQUIRE(getDaysInMonth(0) == -1); +TEST_CASE("ControlFlow ControlFlow02") { + REQUIRE(getDaysInMonth(1) == 31); + REQUIRE(getDaysInMonth(2) == 28); + REQUIRE(getDaysInMonth(4) == 30); + REQUIRE(getDaysInMonth(12) == 31); + REQUIRE(getDaysInMonth(0) == -1); - REQUIRE(std::string(getDayOfWeek(1)) == "Monday"); - REQUIRE(std::string(getDayOfWeek(7)) == "Sunday"); - REQUIRE(std::string(getDayOfWeek(0)) == "Invalid"); + REQUIRE(std::string(getDayOfWeek(1)) == "Monday"); + REQUIRE(std::string(getDayOfWeek(7)) == "Sunday"); + REQUIRE(std::string(getDayOfWeek(0)) == "Invalid"); } diff --git a/solutions/03_control-flow/03_control-flow.cpp b/solutions/03_control-flow/03_control-flow.cpp index b35937f..b4f8dc7 100644 --- a/solutions/03_control-flow/03_control-flow.cpp +++ b/solutions/03_control-flow/03_control-flow.cpp @@ -25,60 +25,50 @@ // Calculates factorial using a while loop. // factorial(5) = 5 * 4 * 3 * 2 * 1 = 120 // factorial(0) = 1 (by mathematical definition) -int factorial(int n) -{ - int result = 1; - while (n > 0) - { - result *= n; - n--; - } - return result; +int factorial(int n) { + int result = 1; + while (n > 0) { + result *= n; + n--; + } + return result; } // Counts the number of digits in a number using do-while. // do-while is perfect here because numbers always have at least 1 digit. -int countDigits(int n) -{ - int count = 0; - do - { - count++; - n /= 10; - } while (n > 0); - return count; +int countDigits(int n) { + int count = 0; + do { + count++; + n /= 10; + } while (n > 0); + return count; } // Calculates the sum of all integers from 1 to n. -int sumToN(int n) -{ - int sum = 0; - int i = 1; - while (i <= n) - { - sum += i; - i++; - } - return sum; +int sumToN(int n) { + int sum = 0; + int i = 1; + while (i <= n) { + sum += i; + i++; + } + return sum; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("ControlFlow ControlFlow03") -{ - REQUIRE(factorial(5) == 120); - REQUIRE(factorial(0) == 1); - REQUIRE(factorial(1) == 1); - REQUIRE(factorial(10) == 3628800); +TEST_CASE("ControlFlow ControlFlow03") { + REQUIRE(factorial(5) == 120); + REQUIRE(factorial(0) == 1); + REQUIRE(factorial(1) == 1); + REQUIRE(factorial(10) == 3628800); - REQUIRE(countDigits(12345) == 5); - REQUIRE(countDigits(0) == 1); - REQUIRE(countDigits(9) == 1); + REQUIRE(countDigits(12345) == 5); + REQUIRE(countDigits(0) == 1); + REQUIRE(countDigits(9) == 1); - REQUIRE(sumToN(5) == 15); - REQUIRE(sumToN(10) == 55); - REQUIRE(sumToN(1) == 1); + REQUIRE(sumToN(5) == 15); + REQUIRE(sumToN(10) == 55); + REQUIRE(sumToN(1) == 1); } diff --git a/solutions/03_control-flow/04_control-flow.cpp b/solutions/03_control-flow/04_control-flow.cpp index 0e24233..e567523 100644 --- a/solutions/03_control-flow/04_control-flow.cpp +++ b/solutions/03_control-flow/04_control-flow.cpp @@ -28,68 +28,55 @@ #include // Calculates sum of integers from 1 to n using a for loop. -int sumToN(int n) -{ - int sum = 0; - for (int i = 1; i <= n; i++) - { - sum += i; - } - return sum; +int sumToN(int n) { + int sum = 0; + for (int i = 1; i <= n; i++) { + sum += i; + } + return sum; } // Finds the maximum value in an array. -int findMax(const int *arr, int size) -{ - int max = arr[0]; - for (int i = 1; i < size; i++) - { - if (arr[i] > max) - { - max = arr[i]; - } +int findMax(const int* arr, int size) { + int max = arr[0]; + for (int i = 1; i < size; i++) { + if (arr[i] > max) { + max = arr[i]; } - return max; + } + return max; } // Reverses a string using a for loop. -std::string reverseString(const std::string &str) -{ - std::string result; - for (int i = str.length() - 1; i >= 0; i--) - { - result += str[i]; - } - return result; +std::string reverseString(const std::string& str) { + std::string result; + for (int i = str.length() - 1; i >= 0; i--) { + result += str[i]; + } + return result; } // Sums all elements in a vector using range-based for. -int sumVector(const std::vector &vec) -{ - int sum = 0; - for (int num : vec) - { - sum += num; - } - return sum; +int sumVector(const std::vector& vec) { + int sum = 0; + for (int num : vec) { + sum += num; + } + return sum; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("ControlFlow ControlFlow04") -{ - REQUIRE(sumToN(5) == 15); - REQUIRE(sumToN(10) == 55); +TEST_CASE("ControlFlow ControlFlow04") { + REQUIRE(sumToN(5) == 15); + REQUIRE(sumToN(10) == 55); - int arr[] = {3, 7, 2, 9, 4}; - REQUIRE(findMax(arr, 5) == 9); + int arr[] = {3, 7, 2, 9, 4}; + REQUIRE(findMax(arr, 5) == 9); - REQUIRE(reverseString("hello") == "olleh"); - REQUIRE(reverseString("a") == "a"); + REQUIRE(reverseString("hello") == "olleh"); + REQUIRE(reverseString("a") == "a"); - std::vector vec = {1, 2, 3, 4, 5}; - REQUIRE(sumVector(vec) == 15); + std::vector vec = {1, 2, 3, 4, 5}; + REQUIRE(sumVector(vec) == 15); } diff --git a/solutions/04_primitives/01_primitives.cpp b/solutions/04_primitives/01_primitives.cpp index 6365e95..5f59577 100644 --- a/solutions/04_primitives/01_primitives.cpp +++ b/solutions/04_primitives/01_primitives.cpp @@ -43,15 +43,11 @@ const int MAX_SIZE = 100; // Auto-deduced integer (compiler sees 42 and deduces int). auto quantity = 42; -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Primitives Primitives01") -{ - REQUIRE(age == 25); - REQUIRE(price == Catch::Approx(19.99)); - REQUIRE(MAX_SIZE == 100); - REQUIRE(quantity == 42); +TEST_CASE("Primitives Primitives01") { + REQUIRE(age == 25); + REQUIRE(price == Catch::Approx(19.99)); + REQUIRE(MAX_SIZE == 100); + REQUIRE(quantity == 42); } diff --git a/solutions/04_primitives/02_primitives.cpp b/solutions/04_primitives/02_primitives.cpp index 79c1b9c..a5cc540 100644 --- a/solutions/04_primitives/02_primitives.cpp +++ b/solutions/04_primitives/02_primitives.cpp @@ -27,41 +27,30 @@ #include // Checks if a character is a vowel (case-insensitive). -bool isVowel(char c) -{ - c = std::tolower(c); - return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; +bool isVowel(char c) { + c = std::tolower(c); + return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; } // Checks if a character is a digit ('0' through '9'). -bool isDigit(char c) -{ - return c >= '0' && c <= '9'; -} +bool isDigit(char c) { return c >= '0' && c <= '9'; } // Converts a boolean to a string. -const char *boolToString(bool b) -{ - return b ? "true" : "false"; -} +const char* boolToString(bool b) { return b ? "true" : "false"; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Primitives Primitives02") -{ - REQUIRE(isVowel('a')); - REQUIRE(isVowel('E')); - REQUIRE_FALSE(isVowel('b')); - REQUIRE_FALSE(isVowel('Z')); +TEST_CASE("Primitives Primitives02") { + REQUIRE(isVowel('a')); + REQUIRE(isVowel('E')); + REQUIRE_FALSE(isVowel('b')); + REQUIRE_FALSE(isVowel('Z')); - REQUIRE(isDigit('5')); - REQUIRE(isDigit('0')); - REQUIRE_FALSE(isDigit('a')); - REQUIRE_FALSE(isDigit('#')); + REQUIRE(isDigit('5')); + REQUIRE(isDigit('0')); + REQUIRE_FALSE(isDigit('a')); + REQUIRE_FALSE(isDigit('#')); - REQUIRE(std::string(boolToString(true)) == "true"); - REQUIRE(std::string(boolToString(false)) == "false"); + REQUIRE(std::string(boolToString(true)) == "true"); + REQUIRE(std::string(boolToString(false)) == "false"); } diff --git a/solutions/04_primitives/03_primitives.cpp b/solutions/04_primitives/03_primitives.cpp index 24bf8fb..04d0551 100644 --- a/solutions/04_primitives/03_primitives.cpp +++ b/solutions/04_primitives/03_primitives.cpp @@ -31,42 +31,34 @@ #include // Adds two uint32_t values with overflow detection. -uint32_t addUint32(uint32_t a, uint32_t b) -{ - if (a > UINT32_MAX - b) - { - return UINT32_MAX; - } - return a + b; +uint32_t addUint32(uint32_t a, uint32_t b) { + if (a > UINT32_MAX - b) { + return UINT32_MAX; + } + return a + b; } // Checks if adding two int8_t values would overflow. -bool hasOverflow(int8_t a, int8_t b) -{ - int16_t result = static_cast(a) + b; - return result > INT8_MAX || result < INT8_MIN; +bool hasOverflow(int8_t a, int8_t b) { + int16_t result = static_cast(a) + b; + return result > INT8_MAX || result < INT8_MIN; } // Converts Celsius to Fahrenheit. -double celsiusToFahrenheit(double celsius) -{ - return celsius * 9.0 / 5.0 + 32.0; +double celsiusToFahrenheit(double celsius) { + return celsius * 9.0 / 5.0 + 32.0; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Primitives Primitives03") -{ - REQUIRE(addUint32(1, 2) == 3); - REQUIRE(addUint32(UINT32_MAX, 1) == UINT32_MAX); +TEST_CASE("Primitives Primitives03") { + REQUIRE(addUint32(1, 2) == 3); + REQUIRE(addUint32(UINT32_MAX, 1) == UINT32_MAX); - REQUIRE_FALSE(hasOverflow(50, 50)); - REQUIRE(hasOverflow(100, 50)); - REQUIRE(hasOverflow(-100, -50)); + REQUIRE_FALSE(hasOverflow(50, 50)); + REQUIRE(hasOverflow(100, 50)); + REQUIRE(hasOverflow(-100, -50)); - REQUIRE(celsiusToFahrenheit(0.0) == Catch::Approx(32.0)); - REQUIRE(celsiusToFahrenheit(100.0) == Catch::Approx(212.0)); + REQUIRE(celsiusToFahrenheit(0.0) == Catch::Approx(32.0)); + REQUIRE(celsiusToFahrenheit(100.0) == Catch::Approx(212.0)); } diff --git a/solutions/05_type-coercion/01_type-coercion.cpp b/solutions/05_type-coercion/01_type-coercion.cpp index 7dffe6d..4cb3d96 100644 --- a/solutions/05_type-coercion/01_type-coercion.cpp +++ b/solutions/05_type-coercion/01_type-coercion.cpp @@ -27,54 +27,39 @@ // Adds an int and a double. // The int is implicitly converted to double for the addition. -double addIntDouble(int a, double b) -{ - return a + b; -} +double addIntDouble(int a, double b) { return a + b; } // Divides two integers and returns a double. // Must explicitly cast to prevent integer division. -double divideInts(int a, int b) -{ - return static_cast(a) / static_cast(b); +double divideInts(int a, int b) { + return static_cast(a) / static_cast(b); } // Truncates a double to an int (rounds toward zero). -int truncateToInt(double d) -{ - return static_cast(d); -} +int truncateToInt(double d) { return static_cast(d); } // Rounds a double to the nearest integer. -int roundToInt(double d) -{ - if (d >= 0) - { - return static_cast(d + 0.5); - } - else - { - return static_cast(d - 0.5); - } +int roundToInt(double d) { + if (d >= 0) { + return static_cast(d + 0.5); + } else { + return static_cast(d - 0.5); + } } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("TypeCoercion TypeCoercion01") -{ - REQUIRE(addIntDouble(5, 3.5) == Catch::Approx(8.5)); - REQUIRE(addIntDouble(10, 2.0) == Catch::Approx(12.0)); +TEST_CASE("TypeCoercion TypeCoercion01") { + REQUIRE(addIntDouble(5, 3.5) == Catch::Approx(8.5)); + REQUIRE(addIntDouble(10, 2.0) == Catch::Approx(12.0)); - REQUIRE(divideInts(10, 4) == Catch::Approx(2.5)); - REQUIRE(divideInts(7, 2) == Catch::Approx(3.5)); + REQUIRE(divideInts(10, 4) == Catch::Approx(2.5)); + REQUIRE(divideInts(7, 2) == Catch::Approx(3.5)); - REQUIRE(truncateToInt(3.7) == 3); - REQUIRE(truncateToInt(3.2) == 3); + REQUIRE(truncateToInt(3.7) == 3); + REQUIRE(truncateToInt(3.2) == 3); - REQUIRE(roundToInt(3.7) == 4); - REQUIRE(roundToInt(3.2) == 3); - REQUIRE(roundToInt(-3.7) == -4); + REQUIRE(roundToInt(3.7) == 4); + REQUIRE(roundToInt(3.2) == 3); + REQUIRE(roundToInt(-3.7) == -4); } diff --git a/solutions/05_type-coercion/02_type-coercion.cpp b/solutions/05_type-coercion/02_type-coercion.cpp index 1f7d6e9..95bc0d9 100644 --- a/solutions/05_type-coercion/02_type-coercion.cpp +++ b/solutions/05_type-coercion/02_type-coercion.cpp @@ -23,39 +23,28 @@ #include // Converts char to int (widening, always safe). -int charToInt(char c) -{ - return c; -} +int charToInt(char c) { return c; } // Converts int to char (narrowing, may lose data). -char intToChar(int i) -{ - return static_cast(i); -} +char intToChar(int i) { return static_cast(i); } // Checks if a double represents a whole number. -bool isWholeNumber(double d) -{ - int i = static_cast(d); - return static_cast(i) == d; +bool isWholeNumber(double d) { + int i = static_cast(d); + return static_cast(i) == d; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("TypeCoercion TypeCoercion02") -{ - REQUIRE(charToInt('A') == 65); - REQUIRE(charToInt('0') == 48); +TEST_CASE("TypeCoercion TypeCoercion02") { + REQUIRE(charToInt('A') == 65); + REQUIRE(charToInt('0') == 48); - REQUIRE(intToChar(65) == 'A'); - REQUIRE(intToChar(97) == 'a'); + REQUIRE(intToChar(65) == 'A'); + REQUIRE(intToChar(97) == 'a'); - REQUIRE(isWholeNumber(5.0)); - REQUIRE(isWholeNumber(-3.0)); - REQUIRE_FALSE(isWholeNumber(5.5)); - REQUIRE_FALSE(isWholeNumber(-3.7)); + REQUIRE(isWholeNumber(5.0)); + REQUIRE(isWholeNumber(-3.0)); + REQUIRE_FALSE(isWholeNumber(5.5)); + REQUIRE_FALSE(isWholeNumber(-3.7)); } diff --git a/solutions/05_type-coercion/03_type-coercion.cpp b/solutions/05_type-coercion/03_type-coercion.cpp index 2259d10..829ccbd 100644 --- a/solutions/05_type-coercion/03_type-coercion.cpp +++ b/solutions/05_type-coercion/03_type-coercion.cpp @@ -26,33 +26,25 @@ // Adds values and returns the result. // Type is deduced as double (the wider type). -auto addWithAuto(int a, double b) -{ - auto result = a + b; - return result; +auto addWithAuto(int a, double b) { + auto result = a + b; + return result; } // Calculates the square of an integer at compile time. -constexpr int square(int x) -{ - return x * x; -} +constexpr int square(int x) { return x * x; } // Compile-time constant (computed during compilation). constexpr int SQUARED_TEN = square(10); -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("TypeCoercion TypeCoercion03") -{ - REQUIRE(addWithAuto(3, 4.5) == Catch::Approx(7.5)); +TEST_CASE("TypeCoercion TypeCoercion03") { + REQUIRE(addWithAuto(3, 4.5) == Catch::Approx(7.5)); - REQUIRE(square(5) == 25); - REQUIRE(square(-3) == 9); - REQUIRE(square(0) == 0); + REQUIRE(square(5) == 25); + REQUIRE(square(-3) == 9); + REQUIRE(square(0) == 0); - REQUIRE(SQUARED_TEN == 100); + REQUIRE(SQUARED_TEN == 100); } diff --git a/solutions/06_strings/01_strings.cpp b/solutions/06_strings/01_strings.cpp index ed3c78c..8ba5e4b 100644 --- a/solutions/06_strings/01_strings.cpp +++ b/solutions/06_strings/01_strings.cpp @@ -28,69 +28,57 @@ #include // Returns the length of a C-string (manual implementation). -int cstringLength(const char *str) -{ - int length = 0; - while (str[length] != '\0') - { - length++; - } - return length; +int cstringLength(const char* str) { + int length = 0; + while (str[length] != '\0') { + length++; + } + return length; } // Compares two C-strings lexicographically. // Returns: 0 if equal, negative if s1 < s2, positive if s1 > s2. -int cstringCompare(const char *s1, const char *s2) -{ - while (*s1 && *s2 && *s1 == *s2) - { - s1++; - s2++; - } - if (*s1 == *s2) - { - return 0; - } - return *s1 < *s2 ? -1 : 1; +int cstringCompare(const char* s1, const char* s2) { + while (*s1 && *s2 && *s1 == *s2) { + s1++; + s2++; + } + if (*s1 == *s2) { + return 0; + } + return *s1 < *s2 ? -1 : 1; } // Concatenates two C-strings and returns a new dynamically allocated string. -char *cstringConcat(const char *s1, const char *s2) -{ - int len1 = cstringLength(s1); - int len2 = cstringLength(s2); - char *result = new char[len1 + len2 + 1]; +char* cstringConcat(const char* s1, const char* s2) { + int len1 = cstringLength(s1); + int len2 = cstringLength(s2); + char* result = new char[len1 + len2 + 1]; - int i = 0; - for (; i < len1; i++) - { - result[i] = s1[i]; - } - for (int j = 0; j < len2; j++) - { - result[i + j] = s2[j]; - } - result[len1 + len2] = '\0'; + int i = 0; + for (; i < len1; i++) { + result[i] = s1[i]; + } + for (int j = 0; j < len2; j++) { + result[i + j] = s2[j]; + } + result[len1 + len2] = '\0'; - return result; + return result; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Strings Strings01") -{ - REQUIRE(cstringLength("hello") == 5); - REQUIRE(cstringLength("") == 0); - REQUIRE(cstringLength("A") == 1); +TEST_CASE("Strings Strings01") { + REQUIRE(cstringLength("hello") == 5); + REQUIRE(cstringLength("") == 0); + REQUIRE(cstringLength("A") == 1); - REQUIRE(cstringCompare("apple", "banana") == -1); - REQUIRE(cstringCompare("hello", "hello") == 0); - REQUIRE(cstringCompare("zebra", "apple") == 1); + REQUIRE(cstringCompare("apple", "banana") == -1); + REQUIRE(cstringCompare("hello", "hello") == 0); + REQUIRE(cstringCompare("zebra", "apple") == 1); - char *concat = cstringConcat("hello", "world"); - REQUIRE(std::string(concat) == "helloworld"); - delete[] concat; + char* concat = cstringConcat("hello", "world"); + REQUIRE(std::string(concat) == "helloworld"); + delete[] concat; } diff --git a/solutions/06_strings/02_strings.cpp b/solutions/06_strings/02_strings.cpp index 5e84f40..7090493 100644 --- a/solutions/06_strings/02_strings.cpp +++ b/solutions/06_strings/02_strings.cpp @@ -30,64 +30,52 @@ #include // Reverses a std::string. -std::string reverseString(const std::string &str) -{ - std::string result; - for (int i = str.length() - 1; i >= 0; i--) - { - result += str[i]; - } - return result; +std::string reverseString(const std::string& str) { + std::string result; + for (int i = str.length() - 1; i >= 0; i--) { + result += str[i]; + } + return result; } // Counts occurrences of a character in a string. -int countChar(const std::string &str, char c) -{ - int count = 0; - for (char ch : str) - { - if (ch == c) - { - count++; - } +int countChar(const std::string& str, char c) { + int count = 0; + for (char ch : str) { + if (ch == c) { + count++; } - return count; + } + return count; } // Checks if a string is a palindrome (reads same forwards and backwards). -bool isPalindrome(const std::string &str) -{ - int left = 0; - int right = str.length() - 1; - while (left < right) - { - if (str[left] != str[right]) - { - return false; - } - left++; - right--; +bool isPalindrome(const std::string& str) { + int left = 0; + int right = str.length() - 1; + while (left < right) { + if (str[left] != str[right]) { + return false; } - return true; + left++; + right--; + } + return true; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Strings Strings02") -{ - REQUIRE(reverseString("hello") == "olleh"); - REQUIRE(reverseString("a") == "a"); - REQUIRE(reverseString("racecar") == "racecar"); +TEST_CASE("Strings Strings02") { + REQUIRE(reverseString("hello") == "olleh"); + REQUIRE(reverseString("a") == "a"); + REQUIRE(reverseString("racecar") == "racecar"); - REQUIRE(countChar("hello", 'l') == 2); - REQUIRE(countChar("banana", 'a') == 3); - REQUIRE(countChar("test", 'x') == 0); + REQUIRE(countChar("hello", 'l') == 2); + REQUIRE(countChar("banana", 'a') == 3); + REQUIRE(countChar("test", 'x') == 0); - REQUIRE(isPalindrome("racecar")); - REQUIRE(isPalindrome("a")); - REQUIRE(isPalindrome("noon")); - REQUIRE_FALSE(isPalindrome("hello")); + REQUIRE(isPalindrome("racecar")); + REQUIRE(isPalindrome("a")); + REQUIRE(isPalindrome("noon")); + REQUIRE_FALSE(isPalindrome("hello")); } diff --git a/solutions/06_strings/03_strings.cpp b/solutions/06_strings/03_strings.cpp index 8a99fba..16bbea9 100644 --- a/solutions/06_strings/03_strings.cpp +++ b/solutions/06_strings/03_strings.cpp @@ -36,70 +36,56 @@ #include // Returns the first word (characters before first space). -std::string_view firstWord(std::string_view sv) -{ - size_t pos = sv.find(' '); - if (pos == std::string_view::npos) - { - return sv; - } - return sv.substr(0, pos); +std::string_view firstWord(std::string_view sv) { + size_t pos = sv.find(' '); + if (pos == std::string_view::npos) { + return sv; + } + return sv.substr(0, pos); } // Checks if a string_view starts with a given prefix. -bool startsWith(std::string_view sv, std::string_view prefix) -{ - return sv.substr(0, prefix.length()) == prefix; +bool startsWith(std::string_view sv, std::string_view prefix) { + return sv.substr(0, prefix.length()) == prefix; } // Counts the number of words (separated by whitespace). -int countWords(std::string_view sv) -{ - int count = 0; - bool inWord = false; - - for (char c : sv) - { - if (c == ' ' || c == '\t' || c == '\n') - { - if (inWord) - { - count++; - inWord = false; - } - } - else - { - inWord = true; - } - } +int countWords(std::string_view sv) { + int count = 0; + bool inWord = false; - if (inWord) - { + for (char c : sv) { + if (c == ' ' || c == '\t' || c == '\n') { + if (inWord) { count++; + inWord = false; + } + } else { + inWord = true; } + } - return count; -} + if (inWord) { + count++; + } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); + return count; } -TEST_CASE("Strings Strings03") -{ - REQUIRE(firstWord("hello world") == "hello"); - REQUIRE(firstWord("single") == "single"); - REQUIRE(firstWord("") == ""); +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } + +TEST_CASE("Strings Strings03") { + REQUIRE(firstWord("hello world") == "hello"); + REQUIRE(firstWord("single") == "single"); + REQUIRE(firstWord("") == ""); - REQUIRE(startsWith("hello", "he")); - REQUIRE(startsWith("hello", "hello")); - REQUIRE_FALSE(startsWith("hello", "world")); - REQUIRE_FALSE(startsWith("", "anything")); + REQUIRE(startsWith("hello", "he")); + REQUIRE(startsWith("hello", "hello")); + REQUIRE_FALSE(startsWith("hello", "world")); + REQUIRE_FALSE(startsWith("", "anything")); - REQUIRE(countWords("hello world") == 2); - REQUIRE(countWords("one two three four") == 4); - REQUIRE(countWords("single") == 1); - REQUIRE(countWords("") == 0); + REQUIRE(countWords("hello world") == 2); + REQUIRE(countWords("one two three four") == 4); + REQUIRE(countWords("single") == 1); + REQUIRE(countWords("") == 0); } diff --git a/solutions/06_strings/04_strings.cpp b/solutions/06_strings/04_strings.cpp index 8423eba..4eca8c4 100644 --- a/solutions/06_strings/04_strings.cpp +++ b/solutions/06_strings/04_strings.cpp @@ -27,62 +27,49 @@ #include // Converts a string_view to std::string (creates a copy). -std::string stringViewToString(std::string_view sv) -{ - return std::string(sv); -} +std::string stringViewToString(std::string_view sv) { return std::string(sv); } // Trims whitespace from both ends of a string_view. // Returns a new string with trimmed content. -std::string trim(std::string_view sv) -{ - size_t start = 0; - size_t end = sv.length(); +std::string trim(std::string_view sv) { + size_t start = 0; + size_t end = sv.length(); - while (start < end && std::isspace(sv[start])) - { - start++; - } + while (start < end && std::isspace(sv[start])) { + start++; + } - while (end > start && std::isspace(sv[end - 1])) - { - end--; - } + while (end > start && std::isspace(sv[end - 1])) { + end--; + } - return std::string(sv.substr(start, end - start)); + return std::string(sv.substr(start, end - start)); } // Replaces all occurrences of a character with another character. // Returns a new string. -std::string replaceAll(std::string_view sv, char oldChar, char newChar) -{ - std::string result(sv); - for (char &c : result) - { - if (c == oldChar) - { - c = newChar; - } +std::string replaceAll(std::string_view sv, char oldChar, char newChar) { + std::string result(sv); + for (char& c : result) { + if (c == oldChar) { + c = newChar; } - return result; + } + return result; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Strings Strings04") -{ - REQUIRE(stringViewToString("hello") == "hello"); - REQUIRE(stringViewToString("") == ""); +TEST_CASE("Strings Strings04") { + REQUIRE(stringViewToString("hello") == "hello"); + REQUIRE(stringViewToString("") == ""); - REQUIRE(trim(" hello ") == "hello"); - REQUIRE(trim("hello") == "hello"); - REQUIRE(trim(" ") == ""); - REQUIRE(trim("\t\ntest\t\n") == "test"); + REQUIRE(trim(" hello ") == "hello"); + REQUIRE(trim("hello") == "hello"); + REQUIRE(trim(" ") == ""); + REQUIRE(trim("\t\ntest\t\n") == "test"); - REQUIRE(replaceAll("hello world", 'l', 'L') == "heLLo worLd"); - REQUIRE(replaceAll("aaa", 'a', 'b') == "bbb"); - REQUIRE(replaceAll("no changes", 'x', 'y') == "no changes"); + REQUIRE(replaceAll("hello world", 'l', 'L') == "heLLo worLd"); + REQUIRE(replaceAll("aaa", 'a', 'b') == "bbb"); + REQUIRE(replaceAll("no changes", 'x', 'y') == "no changes"); } diff --git a/solutions/07_containers/01_containers.cpp b/solutions/07_containers/01_containers.cpp index 996f213..4c6c678 100644 --- a/solutions/07_containers/01_containers.cpp +++ b/solutions/07_containers/01_containers.cpp @@ -30,57 +30,46 @@ #include // Returns the sum of all elements in a vector. -int sumVector(const std::vector &v) -{ - int sum = 0; - for (int num : v) - { - sum += num; - } - return sum; +int sumVector(const std::vector& v) { + int sum = 0; + for (int num : v) { + sum += num; + } + return sum; } // Finds the maximum value in a vector. -int findMax(const std::vector &v) -{ - int max = v[0]; - for (int num : v) - { - if (num > max) - { - max = num; - } +int findMax(const std::vector& v) { + int max = v[0]; + for (int num : v) { + if (num > max) { + max = num; } - return max; + } + return max; } // Reverses a vector. -std::vector reverseVector(const std::vector &v) -{ - std::vector result; - for (int i = v.size() - 1; i >= 0; i--) - { - result.push_back(v[i]); - } - return result; +std::vector reverseVector(const std::vector& v) { + std::vector result; + for (int i = v.size() - 1; i >= 0; i--) { + result.push_back(v[i]); + } + return result; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Containers Containers01") -{ - std::vector v1 = {1, 2, 3, 4, 5}; - REQUIRE(sumVector(v1) == 15); - REQUIRE(sumVector({}) == 0); - REQUIRE(sumVector({10}) == 10); +TEST_CASE("Containers Containers01") { + std::vector v1 = {1, 2, 3, 4, 5}; + REQUIRE(sumVector(v1) == 15); + REQUIRE(sumVector({}) == 0); + REQUIRE(sumVector({10}) == 10); - std::vector v2 = {3, 7, 2, 9, 4}; - REQUIRE(findMax(v2) == 9); + std::vector v2 = {3, 7, 2, 9, 4}; + REQUIRE(findMax(v2) == 9); - std::vector v3 = {1, 2, 3}; - std::vector expected = {3, 2, 1}; - REQUIRE(reverseVector(v3) == expected); + std::vector v3 = {1, 2, 3}; + std::vector expected = {3, 2, 1}; + REQUIRE(reverseVector(v3) == expected); } diff --git a/solutions/07_containers/02_containers.cpp b/solutions/07_containers/02_containers.cpp index f8e8361..9875c51 100644 --- a/solutions/07_containers/02_containers.cpp +++ b/solutions/07_containers/02_containers.cpp @@ -29,54 +29,43 @@ #include // Sums all elements in a std::array. -int sumArray(const std::array &arr) -{ - int sum = 0; - for (int num : arr) - { - sum += num; - } - return sum; +int sumArray(const std::array& arr) { + int sum = 0; + for (int num : arr) { + sum += num; + } + return sum; } // Finds an element in the array. // Returns its index, or -1 if not found. -int findInArray(const std::array &arr, int target) -{ - for (int i = 0; i < 5; i++) - { - if (arr[i] == target) - { - return i; - } +int findInArray(const std::array& arr, int target) { + for (int i = 0; i < 5; i++) { + if (arr[i] == target) { + return i; } - return -1; + } + return -1; } // Doubles each element in the array. -std::array doubleArray(const std::array &arr) -{ - std::array result; - for (int i = 0; i < 5; i++) - { - result[i] = arr[i] * 2; - } - return result; +std::array doubleArray(const std::array& arr) { + std::array result; + for (int i = 0; i < 5; i++) { + result[i] = arr[i] * 2; + } + return result; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Containers Containers02") -{ - std::array arr = {1, 2, 3, 4, 5}; - REQUIRE(sumArray(arr) == 15); +TEST_CASE("Containers Containers02") { + std::array arr = {1, 2, 3, 4, 5}; + REQUIRE(sumArray(arr) == 15); - REQUIRE(findInArray(arr, 3) == 2); - REQUIRE(findInArray(arr, 6) == -1); + REQUIRE(findInArray(arr, 3) == 2); + REQUIRE(findInArray(arr, 6) == -1); - std::array doubled = {2, 4, 6, 8, 10}; - REQUIRE(doubleArray(arr) == doubled); + std::array doubled = {2, 4, 6, 8, 10}; + REQUIRE(doubleArray(arr) == doubled); } diff --git a/solutions/07_containers/03_containers.cpp b/solutions/07_containers/03_containers.cpp index bf64fc1..81104b3 100644 --- a/solutions/07_containers/03_containers.cpp +++ b/solutions/07_containers/03_containers.cpp @@ -32,52 +32,45 @@ #include // Creates a simple phonebook. -std::map createPhonebook() -{ - std::map phonebook; - phonebook["Alice"] = 123; - phonebook["Bob"] = 456; - phonebook["Charlie"] = 789; - return phonebook; +std::map createPhonebook() { + std::map phonebook; + phonebook["Alice"] = 123; + phonebook["Bob"] = 456; + phonebook["Charlie"] = 789; + return phonebook; } // Looks up a name in the phonebook. -int lookup(const std::map &phonebook, const std::string &name) -{ - auto it = phonebook.find(name); - if (it != phonebook.end()) - { - return it->second; - } - return -1; +int lookup(const std::map& phonebook, + const std::string& name) { + auto it = phonebook.find(name); + if (it != phonebook.end()) { + return it->second; + } + return -1; } // Counts word occurrences using a map. -std::map wordCount(const std::vector &words) -{ - std::map counts; - for (const std::string &word : words) - { - counts[word]++; - } - return counts; +std::map wordCount(const std::vector& words) { + std::map counts; + for (const std::string& word : words) { + counts[word]++; + } + return counts; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Containers Containers03") -{ - auto phonebook = createPhonebook(); - REQUIRE(phonebook.size() == 3); - REQUIRE(lookup(phonebook, "Alice") == 123); - REQUIRE(lookup(phonebook, "Unknown") == -1); +TEST_CASE("Containers Containers03") { + auto phonebook = createPhonebook(); + REQUIRE(phonebook.size() == 3); + REQUIRE(lookup(phonebook, "Alice") == 123); + REQUIRE(lookup(phonebook, "Unknown") == -1); - std::vector words = {"apple", "banana", "apple", "cherry", "banana", "apple"}; - auto counts = wordCount(words); - REQUIRE(counts["apple"] == 3); - REQUIRE(counts["banana"] == 2); - REQUIRE(counts["cherry"] == 1); + std::vector words = {"apple", "banana", "apple", + "cherry", "banana", "apple"}; + auto counts = wordCount(words); + REQUIRE(counts["apple"] == 3); + REQUIRE(counts["banana"] == 2); + REQUIRE(counts["cherry"] == 1); } diff --git a/solutions/07_containers/04_containers.cpp b/solutions/07_containers/04_containers.cpp index cd5d3a1..ec195c2 100644 --- a/solutions/07_containers/04_containers.cpp +++ b/solutions/07_containers/04_containers.cpp @@ -29,53 +29,43 @@ #include // Checks if a set contains a value. -bool contains(const std::set &s, int value) -{ - return s.find(value) != s.end(); +bool contains(const std::set& s, int value) { + return s.find(value) != s.end(); } // Returns the intersection of two sets (elements in both). -std::set setIntersection(const std::set &a, const std::set &b) -{ - std::set result; - for (int val : a) - { - if (b.find(val) != b.end()) - { - result.insert(val); - } +std::set setIntersection(const std::set& a, const std::set& b) { + std::set result; + for (int val : a) { + if (b.find(val) != b.end()) { + result.insert(val); } - return result; + } + return result; } // Returns the union of two sets (all unique elements). -std::set setUnion(const std::set &a, const std::set &b) -{ - std::set result = a; - for (int val : b) - { - result.insert(val); - } - return result; +std::set setUnion(const std::set& a, const std::set& b) { + std::set result = a; + for (int val : b) { + result.insert(val); + } + return result; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Containers Containers04") -{ - std::set s = {1, 2, 3, 4, 5}; +TEST_CASE("Containers Containers04") { + std::set s = {1, 2, 3, 4, 5}; - REQUIRE(contains(s, 3)); - REQUIRE_FALSE(contains(s, 10)); + REQUIRE(contains(s, 3)); + REQUIRE_FALSE(contains(s, 10)); - std::set a = {1, 2, 3}; - std::set b = {2, 3, 4}; - std::set intersection = {2, 3}; - REQUIRE(setIntersection(a, b) == intersection); + std::set a = {1, 2, 3}; + std::set b = {2, 3, 4}; + std::set intersection = {2, 3}; + REQUIRE(setIntersection(a, b) == intersection); - std::set unionSet = {1, 2, 3, 4}; - REQUIRE(setUnion(a, b) == unionSet); + std::set unionSet = {1, 2, 3, 4}; + REQUIRE(setUnion(a, b) == unionSet); } diff --git a/solutions/07_containers/05_containers.cpp b/solutions/07_containers/05_containers.cpp index be6703a..42b2541 100644 --- a/solutions/07_containers/05_containers.cpp +++ b/solutions/07_containers/05_containers.cpp @@ -31,60 +31,51 @@ #include // Counts word frequencies using unordered_map. -std::unordered_map wordFrequency(const std::vector &words) -{ - std::unordered_map freq; - for (const std::string &word : words) - { - freq[word]++; - } - return freq; +std::unordered_map wordFrequency( + const std::vector& words) { + std::unordered_map freq; + for (const std::string& word : words) { + freq[word]++; + } + return freq; } // Returns unique elements from a vector using unordered_set. -std::unordered_set uniqueElements(const std::vector &v) -{ - return std::unordered_set(v.begin(), v.end()); +std::unordered_set uniqueElements(const std::vector& v) { + return std::unordered_set(v.begin(), v.end()); } // Checks if two unordered_maps have the same key-value pairs. -bool mapsEqual(const std::unordered_map &a, const std::unordered_map &b) -{ - if (a.size() != b.size()) - { - return false; - } - for (const auto &[key, value] : a) - { - auto it = b.find(key); - if (it == b.end() || it->second != value) - { - return false; - } +bool mapsEqual(const std::unordered_map& a, + const std::unordered_map& b) { + if (a.size() != b.size()) { + return false; + } + for (const auto& [key, value] : a) { + auto it = b.find(key); + if (it == b.end() || it->second != value) { + return false; } - return true; + } + return true; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Containers Containers05") -{ - std::vector words = {"a", "b", "a", "c", "b", "a"}; - auto freq = wordFrequency(words); - REQUIRE(freq["a"] == 3); - REQUIRE(freq["b"] == 2); - REQUIRE(freq["c"] == 1); +TEST_CASE("Containers Containers05") { + std::vector words = {"a", "b", "a", "c", "b", "a"}; + auto freq = wordFrequency(words); + REQUIRE(freq["a"] == 3); + REQUIRE(freq["b"] == 2); + REQUIRE(freq["c"] == 1); - std::vector v = {1, 2, 3, 2, 1}; - auto unique = uniqueElements(v); - REQUIRE(unique.size() == 3); + std::vector v = {1, 2, 3, 2, 1}; + auto unique = uniqueElements(v); + REQUIRE(unique.size() == 3); - std::unordered_map m1 = {{"a", 1}, {"b", 2}}; - std::unordered_map m2 = {{"b", 2}, {"a", 1}}; - std::unordered_map m3 = {{"a", 1}, {"b", 3}}; - REQUIRE(mapsEqual(m1, m2)); - REQUIRE_FALSE(mapsEqual(m1, m3)); + std::unordered_map m1 = {{"a", 1}, {"b", 2}}; + std::unordered_map m2 = {{"b", 2}, {"a", 1}}; + std::unordered_map m3 = {{"a", 1}, {"b", 3}}; + REQUIRE(mapsEqual(m1, m2)); + REQUIRE_FALSE(mapsEqual(m1, m3)); } diff --git a/solutions/07_containers/06_containers.cpp b/solutions/07_containers/06_containers.cpp index ae1ba73..47d9f69 100644 --- a/solutions/07_containers/06_containers.cpp +++ b/solutions/07_containers/06_containers.cpp @@ -33,83 +33,68 @@ #include // Removes all even numbers from a list. -std::list removeEvens(const std::list &lst) -{ - std::list result; - for (int num : lst) - { - if (num % 2 != 0) - { - result.push_back(num); - } +std::list removeEvens(const std::list& lst) { + std::list result; + for (int num : lst) { + if (num % 2 != 0) { + result.push_back(num); } - return result; + } + return result; } // Reverses a list. -std::list reverseList(const std::list &lst) -{ - std::list result; - for (int num : lst) - { - result.push_front(num); - } - return result; +std::list reverseList(const std::list& lst) { + std::list result; + for (int num : lst) { + result.push_front(num); + } + return result; } // Merges two sorted lists into one sorted list. -std::list mergeSortedLists(const std::list &a, const std::list &b) -{ - std::list result; - auto itA = a.begin(); - auto itB = b.begin(); +std::list mergeSortedLists(const std::list& a, + const std::list& b) { + std::list result; + auto itA = a.begin(); + auto itB = b.begin(); - while (itA != a.end() && itB != b.end()) - { - if (*itA <= *itB) - { - result.push_back(*itA); - ++itA; - } - else - { - result.push_back(*itB); - ++itB; - } + while (itA != a.end() && itB != b.end()) { + if (*itA <= *itB) { + result.push_back(*itA); + ++itA; + } else { + result.push_back(*itB); + ++itB; } + } - while (itA != a.end()) - { - result.push_back(*itA); - ++itA; - } + while (itA != a.end()) { + result.push_back(*itA); + ++itA; + } - while (itB != b.end()) - { - result.push_back(*itB); - ++itB; - } + while (itB != b.end()) { + result.push_back(*itB); + ++itB; + } - return result; + return result; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Containers Containers06") -{ - std::list l1 = {1, 2, 3, 4, 5, 6}; - std::list evensRemoved = {1, 3, 5}; - REQUIRE(removeEvens(l1) == evensRemoved); +TEST_CASE("Containers Containers06") { + std::list l1 = {1, 2, 3, 4, 5, 6}; + std::list evensRemoved = {1, 3, 5}; + REQUIRE(removeEvens(l1) == evensRemoved); - std::list l2 = {1, 2, 3}; - std::list reversed = {3, 2, 1}; - REQUIRE(reverseList(l2) == reversed); + std::list l2 = {1, 2, 3}; + std::list reversed = {3, 2, 1}; + REQUIRE(reverseList(l2) == reversed); - std::list a = {1, 3, 5}; - std::list b = {2, 4, 6}; - std::list merged = {1, 2, 3, 4, 5, 6}; - REQUIRE(mergeSortedLists(a, b) == merged); + std::list a = {1, 3, 5}; + std::list b = {2, 4, 6}; + std::list merged = {1, 2, 3, 4, 5, 6}; + REQUIRE(mergeSortedLists(a, b) == merged); } diff --git a/solutions/08_headers/01_headers.cpp b/solutions/08_headers/01_headers.cpp index d8c2815..7913b2c 100644 --- a/solutions/08_headers/01_headers.cpp +++ b/solutions/08_headers/01_headers.cpp @@ -23,14 +23,10 @@ // The implementation is in src/math_utils.cpp int add(int a, int b); -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Headers Headers01") -{ - REQUIRE(add(2, 3) == 5); - REQUIRE(add(-1, 1) == 0); - REQUIRE(add(0, 0) == 0); +TEST_CASE("Headers Headers01") { + REQUIRE(add(2, 3) == 5); + REQUIRE(add(-1, 1) == 0); + REQUIRE(add(0, 0) == 0); } diff --git a/solutions/08_headers/src/math_utils.cpp b/solutions/08_headers/src/math_utils.cpp index be1e084..1f76448 100644 --- a/solutions/08_headers/src/math_utils.cpp +++ b/solutions/08_headers/src/math_utils.cpp @@ -1,4 +1 @@ -int add(int a, int b) -{ - return a + b; -} +int add(int a, int b) { return a + b; } diff --git a/solutions/09_structs/01_structs.cpp b/solutions/09_structs/01_structs.cpp index de29bf4..531e35c 100644 --- a/solutions/09_structs/01_structs.cpp +++ b/solutions/09_structs/01_structs.cpp @@ -17,34 +17,28 @@ #include // TODO: Create a Point struct with x and y coordinates (both int). -struct Point -{ - int x; - int y; +struct Point { + int x; + int y; }; // TODO: Create a function that calculates the distance between two points. -double distance(const Point &a, const Point &b) -{ - int dx = b.x - a.x; - int dy = b.y - a.y; - return std::sqrt(dx * dx + dy * dy); +double distance(const Point& a, const Point& b) { + int dx = b.x - a.x; + int dy = b.y - a.y; + return std::sqrt(dx * dx + dy * dy); } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Structs Structs01") -{ - Point p1 = {0, 0}; - Point p2 = {3, 4}; +TEST_CASE("Structs Structs01") { + Point p1 = {0, 0}; + Point p2 = {3, 4}; - REQUIRE(p1.x == 0); - REQUIRE(p1.y == 0); - REQUIRE(p2.x == 3); - REQUIRE(p2.y == 4); + REQUIRE(p1.x == 0); + REQUIRE(p1.y == 0); + REQUIRE(p2.x == 3); + REQUIRE(p2.y == 4); - REQUIRE(distance(p1, p2) == Catch::Approx(5.0)); + REQUIRE(distance(p1, p2) == Catch::Approx(5.0)); } diff --git a/solutions/10_enums/01_enums.cpp b/solutions/10_enums/01_enums.cpp index 66cb983..3ae0091 100644 --- a/solutions/10_enums/01_enums.cpp +++ b/solutions/10_enums/01_enums.cpp @@ -20,47 +20,39 @@ #include // TODO: Create an enum class for Days of the week. -enum class Day -{ - Monday, - Tuesday, - Wednesday, - Thursday, - Friday, - Saturday, - Sunday +enum class Day { + Monday, + Tuesday, + Wednesday, + Thursday, + Friday, + Saturday, + Sunday }; // TODO: Create a function that checks if a day is a weekday. -bool isWeekday(Day day) -{ - return day == Day::Monday || day == Day::Tuesday || day == Day::Wednesday || day == Day::Thursday || - day == Day::Friday; +bool isWeekday(Day day) { + return day == Day::Monday || day == Day::Tuesday || day == Day::Wednesday || + day == Day::Thursday || day == Day::Friday; } // TODO: Create a function that returns the next day. -Day nextDay(Day day) -{ - int next = static_cast(day) + 1; - if (next > static_cast(Day::Sunday)) - { - next = static_cast(Day::Monday); - } - return static_cast(next); +Day nextDay(Day day) { + int next = static_cast(day) + 1; + if (next > static_cast(Day::Sunday)) { + next = static_cast(Day::Monday); + } + return static_cast(next); } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Enums Enums01") -{ - REQUIRE(isWeekday(Day::Monday)); - REQUIRE(isWeekday(Day::Friday)); - REQUIRE_FALSE(isWeekday(Day::Saturday)); - REQUIRE_FALSE(isWeekday(Day::Sunday)); +TEST_CASE("Enums Enums01") { + REQUIRE(isWeekday(Day::Monday)); + REQUIRE(isWeekday(Day::Friday)); + REQUIRE_FALSE(isWeekday(Day::Saturday)); + REQUIRE_FALSE(isWeekday(Day::Sunday)); - REQUIRE(nextDay(Day::Monday) == Day::Tuesday); - REQUIRE(nextDay(Day::Sunday) == Day::Monday); + REQUIRE(nextDay(Day::Monday) == Day::Tuesday); + REQUIRE(nextDay(Day::Sunday) == Day::Monday); } diff --git a/solutions/11_classes/01_classes.cpp b/solutions/11_classes/01_classes.cpp index 36fbe83..a2cf0b7 100644 --- a/solutions/11_classes/01_classes.cpp +++ b/solutions/11_classes/01_classes.cpp @@ -25,40 +25,27 @@ // - A public constructor that initializes count to 0 // - A public increment() method // - A public getCount() const method -class Counter -{ - int count; +class Counter { + int count; - public: - Counter() : count(0) - { - } + public: + Counter() : count(0) {} - void increment() - { - count++; - } + void increment() { count++; } - int getCount() const - { - return count; - } + int getCount() const { return count; } }; -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Classes Classes01") -{ - Counter c; - REQUIRE(c.getCount() == 0); +TEST_CASE("Classes Classes01") { + Counter c; + REQUIRE(c.getCount() == 0); - c.increment(); - REQUIRE(c.getCount() == 1); + c.increment(); + REQUIRE(c.getCount() == 1); - c.increment(); - c.increment(); - REQUIRE(c.getCount() == 3); + c.increment(); + c.increment(); + REQUIRE(c.getCount() == 3); } diff --git a/solutions/12_generics/01_generics.cpp b/solutions/12_generics/01_generics.cpp index 216fab9..32b380a 100644 --- a/solutions/12_generics/01_generics.cpp +++ b/solutions/12_generics/01_generics.cpp @@ -25,46 +25,41 @@ #include // Returns the maximum of two values. -template T maximum(T a, T b) -{ - return (a > b) ? a : b; +template +T maximum(T a, T b) { + return (a > b) ? a : b; } // Swaps two values. -template void swap(T &a, T &b) -{ - T temp = a; - a = b; - b = temp; +template +void swap(T& a, T& b) { + T temp = a; + a = b; + b = temp; } // Returns the absolute value of a number. -template T absolute(T value) -{ - if (value < T{}) - { - return -value; - } - return value; +template +T absolute(T value) { + if (value < T{}) { + return -value; + } + return value; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Generics Generics01") -{ - REQUIRE(maximum(5, 10) == 10); - REQUIRE(maximum(3.14, 2.71) == 3.14); - REQUIRE(maximum('a', 'z') == 'z'); +TEST_CASE("Generics Generics01") { + REQUIRE(maximum(5, 10) == 10); + REQUIRE(maximum(3.14, 2.71) == 3.14); + REQUIRE(maximum('a', 'z') == 'z'); - int x = 5, y = 10; - swap(x, y); - REQUIRE(x == 10); - REQUIRE(y == 5); + int x = 5, y = 10; + swap(x, y); + REQUIRE(x == 10); + REQUIRE(y == 5); - REQUIRE(absolute(-5) == 5); - REQUIRE(absolute(5) == 5); - REQUIRE(absolute(-3.14) == 3.14); + REQUIRE(absolute(-5) == 5); + REQUIRE(absolute(5) == 5); + REQUIRE(absolute(-3.14) == 3.14); } diff --git a/solutions/12_generics/02_generics.cpp b/solutions/12_generics/02_generics.cpp index 1a4ae8e..25546e0 100644 --- a/solutions/12_generics/02_generics.cpp +++ b/solutions/12_generics/02_generics.cpp @@ -26,69 +26,47 @@ #include // A simple generic pair class. -template class Pair -{ - public: - T first; - U second; +template +class Pair { + public: + T first; + U second; - Pair(T f, U s) : first(f), second(s) - { - } + Pair(T f, U s) : first(f), second(s) {} - T getFirst() const - { - return first; - } - U getSecond() const - { - return second; - } + T getFirst() const { return first; } + U getSecond() const { return second; } }; // A generic box that may or may not contain a value. -template class Box -{ - T value; - bool hasValue; +template +class Box { + T value; + bool hasValue; - public: - Box() : hasValue(false) - { - } - Box(T v) : value(v), hasValue(true) - { - } + public: + Box() : hasValue(false) {} + Box(T v) : value(v), hasValue(true) {} - bool isEmpty() const - { - return !hasValue; - } - T getValue() const - { - return value; - } + bool isEmpty() const { return !hasValue; } + T getValue() const { return value; } }; -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Generics Generics02") -{ - Pair p(42, "hello"); - REQUIRE(p.getFirst() == 42); - REQUIRE(p.getSecond() == "hello"); +TEST_CASE("Generics Generics02") { + Pair p(42, "hello"); + REQUIRE(p.getFirst() == 42); + REQUIRE(p.getSecond() == "hello"); - Pair p2(3.14, 'c'); - REQUIRE(p2.getFirst() == Catch::Approx(3.14)); - REQUIRE(p2.getSecond() == 'c'); + Pair p2(3.14, 'c'); + REQUIRE(p2.getFirst() == Catch::Approx(3.14)); + REQUIRE(p2.getSecond() == 'c'); - Box emptyBox; - REQUIRE(emptyBox.isEmpty()); + Box emptyBox; + REQUIRE(emptyBox.isEmpty()); - Box fullBox(42); - REQUIRE_FALSE(fullBox.isEmpty()); - REQUIRE(fullBox.getValue() == 42); + Box fullBox(42); + REQUIRE_FALSE(fullBox.isEmpty()); + REQUIRE(fullBox.getValue() == 42); } diff --git a/solutions/12_generics/03_generics.cpp b/solutions/12_generics/03_generics.cpp index 73f549e..158697d 100644 --- a/solutions/12_generics/03_generics.cpp +++ b/solutions/12_generics/03_generics.cpp @@ -31,47 +31,43 @@ #include // Sums all arguments using unary left fold. -template auto sum(Args... args) -{ - return (... + args); +template +auto sum(Args... args) { + return (... + args); } // Prints all arguments using comma fold. // The comma operator evaluates left, then right, returns right. -template void printAll(T first, Args... args) -{ - std::cout << first << " "; - (..., (std::cout << args << " ")); +template +void printAll(T first, Args... args) { + std::cout << first << " "; + (..., (std::cout << args << " ")); } // Returns true if ALL arguments are positive (logical AND fold). -template bool allPositive(Args... args) -{ - return (... && (args > 0)); +template +bool allPositive(Args... args) { + return (... && (args > 0)); } // Returns true if ANY argument is true (logical OR fold). -template bool anyTrue(Args... args) -{ - return (... || args); +template +bool anyTrue(Args... args) { + return (... || args); } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Generics Generics03") -{ - REQUIRE(sum(1, 2, 3, 4, 5) == 15); - REQUIRE(sum(1) == 1); - REQUIRE(sum(1.5, 2.5, 3.0) == 7.0); +TEST_CASE("Generics Generics03") { + REQUIRE(sum(1, 2, 3, 4, 5) == 15); + REQUIRE(sum(1) == 1); + REQUIRE(sum(1.5, 2.5, 3.0) == 7.0); - REQUIRE(allPositive(1, 2, 3)); - REQUIRE_FALSE(allPositive(1, -2, 3)); - REQUIRE(allPositive(5)); + REQUIRE(allPositive(1, 2, 3)); + REQUIRE_FALSE(allPositive(1, -2, 3)); + REQUIRE(allPositive(5)); - REQUIRE(anyTrue(false, true, false)); - REQUIRE_FALSE(anyTrue(false, false, false)); - REQUIRE(anyTrue(true)); + REQUIRE(anyTrue(false, true, false)); + REQUIRE_FALSE(anyTrue(false, false, false)); + REQUIRE(anyTrue(true)); } diff --git a/solutions/13_exceptions/01_exceptions.cpp b/solutions/13_exceptions/01_exceptions.cpp index 190eae5..e4942c9 100644 --- a/solutions/13_exceptions/01_exceptions.cpp +++ b/solutions/13_exceptions/01_exceptions.cpp @@ -22,37 +22,29 @@ // TODO: Implement a function that divides two numbers. // Throw std::runtime_error if dividing by zero. -double divide(double a, double b) -{ - if (b == 0.0) - { - throw std::runtime_error("Division by zero"); - } - return a / b; +double divide(double a, double b) { + if (b == 0.0) { + throw std::runtime_error("Division by zero"); + } + return a / b; } // TODO: Implement a function that returns the element at index in an array. // Throw std::out_of_range if index is out of bounds. -int getElement(const int *arr, int size, int index) -{ - if (index < 0 || index >= size) - { - throw std::out_of_range("Index out of bounds"); - } - return arr[index]; +int getElement(const int* arr, int size, int index) { + if (index < 0 || index >= size) { + throw std::out_of_range("Index out of bounds"); + } + return arr[index]; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Exceptions Exceptions01") -{ - REQUIRE(divide(10.0, 2.0) == Catch::Approx(5.0)); - REQUIRE(divide(7.0, 3.0) == Catch::Approx(2.3333333333333335)); +TEST_CASE("Exceptions Exceptions01") { + REQUIRE(divide(10.0, 2.0) == Catch::Approx(5.0)); + REQUIRE(divide(7.0, 3.0) == Catch::Approx(2.3333333333333335)); - int arr[] = {1, 2, 3, 4, 5}; - REQUIRE(getElement(arr, 5, 0) == 1); - REQUIRE(getElement(arr, 5, 4) == 5); + int arr[] = {1, 2, 3, 4, 5}; + REQUIRE(getElement(arr, 5, 0) == 1); + REQUIRE(getElement(arr, 5, 4) == 5); } diff --git a/solutions/14_memory/01_memory.cpp b/solutions/14_memory/01_memory.cpp index 54ebbee..6915f98 100644 --- a/solutions/14_memory/01_memory.cpp +++ b/solutions/14_memory/01_memory.cpp @@ -20,40 +20,28 @@ #include // TODO: Create a function that returns a unique_ptr to an int with value 42. -std::unique_ptr createValue() -{ - return std::make_unique(42); -} +std::unique_ptr createValue() { return std::make_unique(42); } -// TODO: Create a function that takes ownership of a unique_ptr and returns its value. -int extractValue(std::unique_ptr ptr) -{ - return *ptr; -} +// TODO: Create a function that takes ownership of a unique_ptr and returns its +// value. +int extractValue(std::unique_ptr ptr) { return *ptr; } // TODO: Use shared_ptr to share ownership of a value. -std::shared_ptr createShared() -{ - return std::make_shared(100); -} +std::shared_ptr createShared() { return std::make_shared(100); } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Memory Memory01") -{ - auto ptr = createValue(); - REQUIRE(*ptr == 42); +TEST_CASE("Memory Memory01") { + auto ptr = createValue(); + REQUIRE(*ptr == 42); - auto ptr2 = createValue(); - REQUIRE(extractValue(std::move(ptr2)) == 42); + auto ptr2 = createValue(); + REQUIRE(extractValue(std::move(ptr2)) == 42); - auto shared = createShared(); - REQUIRE(*shared == 100); - REQUIRE(shared.use_count() == 1); + auto shared = createShared(); + REQUIRE(*shared == 100); + REQUIRE(shared.use_count() == 1); - auto shared2 = shared; - REQUIRE(shared.use_count() == 2); + auto shared2 = shared; + REQUIRE(shared.use_count() == 2); } diff --git a/solutions/15_threads/01_threads.cpp b/solutions/15_threads/01_threads.cpp index 46bb4b6..f04ce0d 100644 --- a/solutions/15_threads/01_threads.cpp +++ b/solutions/15_threads/01_threads.cpp @@ -27,38 +27,30 @@ int counter = 0; // TODO: Implement a function that increments the counter safely. // Use a mutex to protect the shared resource. -void incrementSafely() -{ - std::lock_guard lock(mtx); - counter++; +void incrementSafely() { + std::lock_guard lock(mtx); + counter++; } // TODO: Implement a function that returns the current counter value. -int getCounter() -{ - std::lock_guard lock(mtx); - return counter; +int getCounter() { + std::lock_guard lock(mtx); + return counter; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Threads Threads01") -{ - counter = 0; +TEST_CASE("Threads Threads01") { + counter = 0; - std::vector threads; - for (int i = 0; i < 10; i++) - { - threads.push_back(std::thread(incrementSafely)); - } + std::vector threads; + for (int i = 0; i < 10; i++) { + threads.push_back(std::thread(incrementSafely)); + } - for (auto &t : threads) - { - t.join(); - } + for (auto& t : threads) { + t.join(); + } - REQUIRE(getCounter() == 10); + REQUIRE(getCounter() == 10); } diff --git a/solutions/16_preprocessors/01_preprocessors.cpp b/solutions/16_preprocessors/01_preprocessors.cpp index 5893e1c..bdce988 100644 --- a/solutions/16_preprocessors/01_preprocessors.cpp +++ b/solutions/16_preprocessors/01_preprocessors.cpp @@ -29,19 +29,15 @@ // TODO: Define a macro IS_EVEN that returns true if a number is even. #define IS_EVEN(x) ((x) % 2 == 0) -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("Preprocessors Preprocessors01") -{ - REQUIRE(SQUARE(5) == 25); - REQUIRE(SQUARE(-3) == 9); +TEST_CASE("Preprocessors Preprocessors01") { + REQUIRE(SQUARE(5) == 25); + REQUIRE(SQUARE(-3) == 9); - REQUIRE(MAX(3, 5) == 5); - REQUIRE(MAX(10, 2) == 10); + REQUIRE(MAX(3, 5) == 5); + REQUIRE(MAX(10, 2) == 10); - REQUIRE(IS_EVEN(4)); - REQUIRE_FALSE(IS_EVEN(5)); + REQUIRE(IS_EVEN(4)); + REQUIRE_FALSE(IS_EVEN(5)); } diff --git a/solutions/17_bit-manipulation/01_bit-manipulation.cpp b/solutions/17_bit-manipulation/01_bit-manipulation.cpp index d7e9eaa..1a45a90 100644 --- a/solutions/17_bit-manipulation/01_bit-manipulation.cpp +++ b/solutions/17_bit-manipulation/01_bit-manipulation.cpp @@ -22,45 +22,29 @@ #include // TODO: Implement a function that sets the nth bit of a number. -int setBit(int num, int n) -{ - return num | (1 << n); -} +int setBit(int num, int n) { return num | (1 << n); } // TODO: Implement a function that clears the nth bit of a number. -int clearBit(int num, int n) -{ - return num & ~(1 << n); -} +int clearBit(int num, int n) { return num & ~(1 << n); } // TODO: Implement a function that toggles the nth bit of a number. -int toggleBit(int num, int n) -{ - return num ^ (1 << n); -} +int toggleBit(int num, int n) { return num ^ (1 << n); } // TODO: Implement a function that checks if the nth bit is set. -bool isBitSet(int num, int n) -{ - return (num & (1 << n)) != 0; -} +bool isBitSet(int num, int n) { return (num & (1 << n)) != 0; } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } -TEST_CASE("BitManipulation BitManipulation01") -{ - REQUIRE(setBit(0, 0) == 1); - REQUIRE(setBit(4, 1) == 6); +TEST_CASE("BitManipulation BitManipulation01") { + REQUIRE(setBit(0, 0) == 1); + REQUIRE(setBit(4, 1) == 6); - REQUIRE(clearBit(7, 0) == 6); - REQUIRE(clearBit(8, 3) == 0); + REQUIRE(clearBit(7, 0) == 6); + REQUIRE(clearBit(8, 3) == 0); - REQUIRE(toggleBit(5, 0) == 4); - REQUIRE(toggleBit(4, 0) == 5); + REQUIRE(toggleBit(5, 0) == 4); + REQUIRE(toggleBit(4, 0) == 5); - REQUIRE(isBitSet(5, 0)); - REQUIRE_FALSE(isBitSet(5, 1)); + REQUIRE(isBitSet(5, 0)); + REQUIRE_FALSE(isBitSet(5, 1)); } diff --git a/solutions/extras_cpp-history/01_cpp-history.cpp b/solutions/extras_cpp-history/01_cpp-history.cpp index e4828b9..3838766 100644 --- a/solutions/extras_cpp-history/01_cpp-history.cpp +++ b/solutions/extras_cpp-history/01_cpp-history.cpp @@ -14,21 +14,17 @@ #include #include -int main() -{ - // TODO: Make this variable "truthy" to compile. - // NOTE: Please read the comments above. - bool hasRead{false}; +int main() { + // TODO: Make this variable "truthy" to compile. + // NOTE: Please read the comments above. + bool hasRead{false}; - try - { - if (!hasRead) - { - throw std::runtime_error("Please view the code of this exercise before proceeding."); - } - } - catch (std::exception &e) - { - std::cout << e.what(); + try { + if (!hasRead) { + throw std::runtime_error( + "Please view the code of this exercise before proceeding."); } + } catch (std::exception& e) { + std::cout << e.what(); + } } diff --git a/solutions/extras_development/01_development.cpp b/solutions/extras_development/01_development.cpp index 3be1c80..16b7289 100644 --- a/solutions/extras_development/01_development.cpp +++ b/solutions/extras_development/01_development.cpp @@ -3,7 +3,4 @@ // #include -int main() -{ - std::cout << "Coming soon!" << std::endl; -} +int main() { std::cout << "Coming soon!" << std::endl; } diff --git a/solutions/extras_networking/01_networking.cpp b/solutions/extras_networking/01_networking.cpp index 3be1c80..16b7289 100644 --- a/solutions/extras_networking/01_networking.cpp +++ b/solutions/extras_networking/01_networking.cpp @@ -3,7 +3,4 @@ // #include -int main() -{ - std::cout << "Coming soon!" << std::endl; -} +int main() { std::cout << "Coming soon!" << std::endl; } diff --git a/src/include/ascii.hpp b/src/include/ascii.hpp index efb7ba5..a3291d7 100644 --- a/src/include/ascii.hpp +++ b/src/include/ascii.hpp @@ -2,8 +2,7 @@ #include -namespace ASCII -{ +namespace ASCII { inline const std::string ART = R"( _ _ @@ -26,51 +25,43 @@ even after you already figured it out. Press Enter to get started. )"; -struct Cursor -{ - struct Clear - { - static constexpr std::string BEHIND_CURSOR = "\x1b[0J"; - static constexpr std::string INFRONT_CURSOR = "\x1b[1J"; - static constexpr std::string ALL = "\x1b[2J"; - static constexpr std::string SCROLLBACK = "\x1b[3J"; - }; +struct Cursor { + struct Clear { + static constexpr std::string BEHIND_CURSOR = "\x1b[0J"; + static constexpr std::string INFRONT_CURSOR = "\x1b[1J"; + static constexpr std::string ALL = "\x1b[2J"; + static constexpr std::string SCROLLBACK = "\x1b[3J"; + }; - struct Position - { - static constexpr std::string HOME = "\x1b[H"; - }; + struct Position { + static constexpr std::string HOME = "\x1b[H"; + }; }; -struct Styles -{ - static constexpr std::string BOLD = "\x1B[1m"; - static constexpr std::string UNDERLINE = "\x1B[4m"; - static constexpr std::string CLEAR_STYLE = "\x1B[0m"; +struct Styles { + static constexpr std::string BOLD = "\x1B[1m"; + static constexpr std::string UNDERLINE = "\x1B[4m"; + static constexpr std::string CLEAR_STYLE = "\x1B[0m"; }; -struct Colors -{ +struct Colors { + struct Foreground { + static constexpr std::string BLACK = "\x1b[30m"; + static constexpr std::string WHITE = "\x1b[37m"; + static constexpr std::string RED = "\x1b[31m"; + static constexpr std::string GREEN = "\x1b[32m"; + static constexpr std::string BLUE = "\x1b[34m"; + static constexpr std::string YELLOW = "\x1b[33m"; + }; - struct Foreground - { - static constexpr std::string BLACK = "\x1b[30m"; - static constexpr std::string WHITE = "\x1b[37m"; - static constexpr std::string RED = "\x1b[31m"; - static constexpr std::string GREEN = "\x1b[32m"; - static constexpr std::string BLUE = "\x1b[34m"; - static constexpr std::string YELLOW = "\x1b[33m"; - }; - - struct Background - { - static constexpr std::string BLACK = "\x1b[40m"; - static constexpr std::string WHITE = "\x1b[47m"; - static constexpr std::string RED = "\x1b[41m"; - static constexpr std::string GREEN = "\x1b[42m"; - static constexpr std::string BLUE = "\x1b[44m"; - static constexpr std::string YELLOW = "\x1b[43m"; - }; + struct Background { + static constexpr std::string BLACK = "\x1b[40m"; + static constexpr std::string WHITE = "\x1b[47m"; + static constexpr std::string RED = "\x1b[41m"; + static constexpr std::string GREEN = "\x1b[42m"; + static constexpr std::string BLUE = "\x1b[44m"; + static constexpr std::string YELLOW = "\x1b[43m"; + }; }; -}; // namespace ASCII +}; // namespace ASCII diff --git a/src/include/exercise_iterator.hpp b/src/include/exercise_iterator.hpp index d79cc79..e3905e3 100644 --- a/src/include/exercise_iterator.hpp +++ b/src/include/exercise_iterator.hpp @@ -5,32 +5,28 @@ #include #include -struct ExerciseIterator -{ - ExerciseIterator() = default; - ~ExerciseIterator() = default; +struct ExerciseIterator { + ExerciseIterator() = default; + ~ExerciseIterator() = default; - ExerciseIterator(const ExerciseIterator &) = delete; - ExerciseIterator(ExerciseIterator &&) = default; + ExerciseIterator(const ExerciseIterator&) = delete; + ExerciseIterator(ExerciseIterator&&) = default; - ExerciseIterator &operator=(const ExerciseIterator &) = delete; - ExerciseIterator &operator=(ExerciseIterator &&) = default; + ExerciseIterator& operator=(const ExerciseIterator&) = delete; + ExerciseIterator& operator=(ExerciseIterator&&) = default; - static std::unique_ptr getInstance(); + static std::unique_ptr getInstance(); - enum class ExerciseDirectories - { - Exercises, - Solutions - }; + enum class ExerciseDirectories { Exercises, Solutions }; - static std::expected getExerciseDirectory(ExerciseDirectories directory); + static std::expected getExerciseDirectory( + ExerciseDirectories directory); - void scanForExercises(ExerciseDirectories directory); + void scanForExercises(ExerciseDirectories directory); - std::expected previous(); + std::expected previous(); - std::expected next(); + std::expected next(); - void reset(); + void reset(); }; diff --git a/src/include/exercise_runner.hpp b/src/include/exercise_runner.hpp index 52a8f85..4cba0d7 100644 --- a/src/include/exercise_runner.hpp +++ b/src/include/exercise_runner.hpp @@ -3,20 +3,19 @@ #include #include -struct ExerciseRunner -{ - ExerciseRunner() = default; - ~ExerciseRunner() = default; +struct ExerciseRunner { + ExerciseRunner() = default; + ~ExerciseRunner() = default; - ExerciseRunner(const ExerciseRunner &) = delete; - ExerciseRunner(ExerciseRunner &&) = default; + ExerciseRunner(const ExerciseRunner&) = delete; + ExerciseRunner(ExerciseRunner&&) = default; - ExerciseRunner &operator=(const ExerciseRunner &) = delete; - ExerciseRunner &operator=(ExerciseRunner &&) = default; + ExerciseRunner& operator=(const ExerciseRunner&) = delete; + ExerciseRunner& operator=(ExerciseRunner&&) = default; - void compileCurrentExercise(); + void compileCurrentExercise(); - void compileAllExercises(); + void compileAllExercises(); - static std::unique_ptr getInstance(); + static std::unique_ptr getInstance(); }; diff --git a/src/include/file_watcher.hpp b/src/include/file_watcher.hpp index eb01747..4bcfdc1 100644 --- a/src/include/file_watcher.hpp +++ b/src/include/file_watcher.hpp @@ -4,21 +4,21 @@ #include #include -struct FileWatcher -{ - FileWatcher() = default; - ~FileWatcher() = default; +struct FileWatcher { + FileWatcher() = default; + ~FileWatcher() = default; - FileWatcher(const FileWatcher &) = delete; - FileWatcher(FileWatcher &&) = default; + FileWatcher(const FileWatcher&) = delete; + FileWatcher(FileWatcher&&) = default; - FileWatcher &operator=(const FileWatcher &) = delete; - FileWatcher &operator=(FileWatcher &&) = default; + FileWatcher& operator=(const FileWatcher&) = delete; + FileWatcher& operator=(FileWatcher&&) = default; - static std::unique_ptr getInstance(); + static std::unique_ptr getInstance(); - void watch(std::stop_token s_token, const std::uint16_t poll_ms); + void watch(std::stop_token s_token, const std::uint16_t poll_ms); - private: - [[maybe_unused]] std::filesystem::file_time_type m_current_exercise_prev_mod_time; + private: + [[maybe_unused]] std::filesystem::file_time_type + m_current_exercise_prev_mod_time; }; diff --git a/src/include/patch_system.hpp b/src/include/patch_system.hpp index 9299976..6a31a3e 100644 --- a/src/include/patch_system.hpp +++ b/src/include/patch_system.hpp @@ -3,20 +3,19 @@ #include #include -struct PatchSystem -{ - static std::unique_ptr getInstance(); +struct PatchSystem { + static std::unique_ptr getInstance(); - PatchSystem() = default; - ~PatchSystem() = default; + PatchSystem() = default; + ~PatchSystem() = default; - PatchSystem(const PatchSystem &) = delete; - PatchSystem(PatchSystem &&) = default; + PatchSystem(const PatchSystem&) = delete; + PatchSystem(PatchSystem&&) = default; - PatchSystem &operator=(const PatchSystem &) = delete; - PatchSystem &operator=(PatchSystem &&) = default; + PatchSystem& operator=(const PatchSystem&) = delete; + PatchSystem& operator=(PatchSystem&&) = default; - static void generatePatches(); + static void generatePatches(); - static void patch(std::filesystem::path exercise_file_path); + static void patch(std::filesystem::path exercise_file_path); }; diff --git a/src/include/tui.hpp b/src/include/tui.hpp index bc6a325..ce813b0 100644 --- a/src/include/tui.hpp +++ b/src/include/tui.hpp @@ -1,6 +1,5 @@ #pragma once -#include "include/exercise_iterator.hpp" #include #include #include @@ -10,21 +9,21 @@ #include #include -namespace TUI -{ - -enum class Commands -{ - ListExercises, - ShowHint, - NextExercise, - PreviousExercise, - CompileAll, - Refresh, - Draw, - Clear, - Reset, - Quit, +#include "include/exercise_iterator.hpp" + +namespace TUI { + +enum class Commands { + ListExercises, + ShowHint, + NextExercise, + PreviousExercise, + CompileAll, + Refresh, + Draw, + Clear, + Reset, + Quit, }; extern std::unique_ptr> p_commands_queue; @@ -32,24 +31,24 @@ extern std::unique_ptr> p_commands_queue; inline std::mutex mutex_state; inline std::condition_variable cv_state; -struct State final -{ - std::atomic is_running = true; - std::atomic new_user = true; - std::filesystem::path exercises_dir_path; - std::vector list_of_exercises; - std::filesystem::path current_exercise; - std::atomic current_exercise_index = 0; - std::atomic is_current_exercise_compiling = false; - std::atomic did_current_exercise_compile = false; - std::vector completed_exercises; - std::string current_exercise_stdout; - std::string current_exercise_stderr; +struct State final { + std::atomic is_running = true; + std::atomic new_user = true; + std::filesystem::path exercises_dir_path; + std::vector list_of_exercises; + std::filesystem::path current_exercise; + std::atomic current_exercise_index = 0; + std::atomic is_current_exercise_compiling = false; + std::atomic did_current_exercise_compile = false; + std::vector completed_exercises; + std::string current_exercise_stdout; + std::string current_exercise_stderr; }; extern std::unique_ptr p_state; -void run(ExerciseIterator::ExerciseDirectories directory = ExerciseIterator::ExerciseDirectories::Exercises); +void run(ExerciseIterator::ExerciseDirectories directory = + ExerciseIterator::ExerciseDirectories::Exercises); void draw(); -} // namespace TUI +} // namespace TUI diff --git a/src/include/util.hpp b/src/include/util.hpp index 5646792..87ba4f1 100644 --- a/src/include/util.hpp +++ b/src/include/util.hpp @@ -5,21 +5,22 @@ #include #include -namespace util -{ +namespace util { [[nodiscard("process output must be used")]] -inline std::future getProcessResult(boost::asio::readable_pipe &process_pipe, - boost::system::error_code error_code) +inline std::future getProcessResult( + boost::asio::readable_pipe& process_pipe, + boost::system::error_code error_code) { - return std::async(std::launch::async, [&] { - std::string result; + return std::async(std::launch::async, [&] { + std::string result; - boost::asio::read(process_pipe, boost::asio::dynamic_buffer(result), error_code); + boost::asio::read(process_pipe, boost::asio::dynamic_buffer(result), + error_code); - return result; - }); + return result; + }); } -} // namespace util +} // namespace util diff --git a/src/tests/test.cpp b/src/tests/test.cpp index e22abc1..94c8140 100644 --- a/src/tests/test.cpp +++ b/src/tests/test.cpp @@ -4,20 +4,15 @@ #include #include -unsigned int Factorial(unsigned int number) -{ - return number <= 1 ? number : Factorial(number - 1) * number; +unsigned int Factorial(unsigned int number) { + return number <= 1 ? number : Factorial(number - 1) * number; } -TEST_CASE("Factorials are computed", "[factorial]") -{ - REQUIRE(Factorial(1) == 1); - REQUIRE(Factorial(2) == 2); - REQUIRE(Factorial(3) == 6); - REQUIRE(Factorial(10) == 3628800); +TEST_CASE("Factorials are computed", "[factorial]") { + REQUIRE(Factorial(1) == 1); + REQUIRE(Factorial(2) == 2); + REQUIRE(Factorial(3) == 6); + REQUIRE(Factorial(10) == 3628800); } -int main(int argc, char *argv[]) -{ - return Catch::Session().run(argc, argv); -} +int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); } diff --git a/src/tests/test_exercise_iterator.cpp b/src/tests/test_exercise_iterator.cpp index e851da8..9863c5d 100644 --- a/src/tests/test_exercise_iterator.cpp +++ b/src/tests/test_exercise_iterator.cpp @@ -1,5 +1,3 @@ -#include "include/exercise_iterator.hpp" -#include "include/tui.hpp" #include #include #include @@ -7,128 +5,126 @@ #include #include -namespace -{ - -void bootstrap(std::size_t count) -{ - TUI::p_state = std::make_unique(); - TUI::p_commands_queue = std::make_unique>(); - for (auto i{0uz}; i < count; ++i) - { - TUI::p_state->list_of_exercises.emplace_back(std::format("exercises/0{}/0{}.cpp", i, i)); - } - TUI::p_state->current_exercise = TUI::p_state->list_of_exercises.front(); +#include "include/exercise_iterator.hpp" +#include "include/tui.hpp" + +namespace { + +void bootstrap(std::size_t count) { + TUI::p_state = std::make_unique(); + TUI::p_commands_queue = std::make_unique>(); + for (auto i{0uz}; i < count; ++i) { + TUI::p_state->list_of_exercises.emplace_back( + std::format("exercises/0{}/0{}.cpp", i, i)); + } + TUI::p_state->current_exercise = TUI::p_state->list_of_exercises.front(); } -std::unique_ptr scan() -{ - bootstrap(1); - auto iterator{ExerciseIterator::getInstance()}; - iterator->scanForExercises(ExerciseIterator::ExerciseDirectories::Exercises); - return iterator; +std::unique_ptr scan() { + bootstrap(1); + auto iterator{ExerciseIterator::getInstance()}; + iterator->scanForExercises(ExerciseIterator::ExerciseDirectories::Exercises); + return iterator; } -} // namespace +} // namespace -TEST_CASE("getExerciseDirectory resolves exercises and solutions", "[iterator]") -{ - using enum ExerciseIterator::ExerciseDirectories; - auto exercises{ExerciseIterator::getExerciseDirectory(Exercises)}; - auto solutions{ExerciseIterator::getExerciseDirectory(Solutions)}; +TEST_CASE("getExerciseDirectory resolves exercises and solutions", + "[iterator]") { + using enum ExerciseIterator::ExerciseDirectories; + auto exercises{ExerciseIterator::getExerciseDirectory(Exercises)}; + auto solutions{ExerciseIterator::getExerciseDirectory(Solutions)}; - REQUIRE(exercises.has_value()); - REQUIRE(solutions.has_value()); + REQUIRE(exercises.has_value()); + REQUIRE(solutions.has_value()); - REQUIRE(exercises.value() == std::filesystem::current_path() / "exercises"); - REQUIRE(solutions.value() == std::filesystem::current_path() / "solutions"); - REQUIRE(std::filesystem::exists(exercises.value())); - REQUIRE(std::filesystem::exists(solutions.value())); + REQUIRE(exercises.value() == std::filesystem::current_path() / "exercises"); + REQUIRE(solutions.value() == std::filesystem::current_path() / "solutions"); + REQUIRE(std::filesystem::exists(exercises.value())); + REQUIRE(std::filesystem::exists(solutions.value())); } -TEST_CASE("scanForExercises collects sorted, filtered exercises", "[iterator]") -{ - scan(); - auto &list{TUI::p_state->list_of_exercises}; - - REQUIRE_FALSE(list.empty()); - REQUIRE(std::is_sorted(list.begin(), list.end())); - REQUIRE(TUI::p_state->current_exercise == list.front()); - REQUIRE(TUI::p_state->exercises_dir_path == std::filesystem::current_path() / "exercises"); - - for (auto const &entry : list) - { - auto ext{entry.extension()}; - REQUIRE_FALSE(ext == std::filesystem::path(".md")); - REQUIRE_FALSE(ext == std::filesystem::path(".patch")); - REQUIRE_FALSE(ext == std::filesystem::path(".rej")); - REQUIRE_FALSE(entry.string().contains("src")); - REQUIRE_FALSE(entry.string().contains("include")); - } +TEST_CASE("scanForExercises collects sorted, filtered exercises", + "[iterator]") { + scan(); + auto& list{TUI::p_state->list_of_exercises}; + + REQUIRE_FALSE(list.empty()); + REQUIRE(std::is_sorted(list.begin(), list.end())); + REQUIRE(TUI::p_state->current_exercise == list.front()); + REQUIRE(TUI::p_state->exercises_dir_path == + std::filesystem::current_path() / "exercises"); + + for (auto const& entry : list) { + auto ext{entry.extension()}; + REQUIRE_FALSE(ext == std::filesystem::path(".md")); + REQUIRE_FALSE(ext == std::filesystem::path(".patch")); + REQUIRE_FALSE(ext == std::filesystem::path(".rej")); + REQUIRE_FALSE(entry.string().contains("src")); + REQUIRE_FALSE(entry.string().contains("include")); + } } -TEST_CASE("next advances once current exercise compiled", "[iterator]") -{ - bootstrap(2); - auto iterator{ExerciseIterator::getInstance()}; - auto first{TUI::p_state->current_exercise}; - TUI::p_state->did_current_exercise_compile = true; +TEST_CASE("next advances once current exercise compiled", "[iterator]") { + bootstrap(2); + auto iterator{ExerciseIterator::getInstance()}; + auto first{TUI::p_state->current_exercise}; + TUI::p_state->did_current_exercise_compile = true; - iterator->next(); + iterator->next(); - REQUIRE(TUI::p_state->current_exercise_index.load() == 1); - REQUIRE(TUI::p_state->current_exercise == TUI::p_state->list_of_exercises.at(1)); - REQUIRE(TUI::p_state->completed_exercises.size() == 1); - REQUIRE(TUI::p_state->completed_exercises.at(0) == first); + REQUIRE(TUI::p_state->current_exercise_index.load() == 1); + REQUIRE(TUI::p_state->current_exercise == + TUI::p_state->list_of_exercises.at(1)); + REQUIRE(TUI::p_state->completed_exercises.size() == 1); + REQUIRE(TUI::p_state->completed_exercises.at(0) == first); } -TEST_CASE("next is a no-op when current exercise failed to compile", "[iterator]") -{ - bootstrap(2); - auto iterator{ExerciseIterator::getInstance()}; +TEST_CASE("next is a no-op when current exercise failed to compile", + "[iterator]") { + bootstrap(2); + auto iterator{ExerciseIterator::getInstance()}; - iterator->next(); + iterator->next(); - REQUIRE(TUI::p_state->current_exercise_index.load() == 0); - REQUIRE(TUI::p_state->completed_exercises.empty()); + REQUIRE(TUI::p_state->current_exercise_index.load() == 0); + REQUIRE(TUI::p_state->completed_exercises.empty()); } -TEST_CASE("next is a no-op past the last exercise", "[iterator]") -{ - bootstrap(2); - auto iterator{ExerciseIterator::getInstance()}; - auto last_index{TUI::p_state->list_of_exercises.size()}; - TUI::p_state->current_exercise_index = static_cast(last_index); - TUI::p_state->current_exercise = TUI::p_state->list_of_exercises.back(); - TUI::p_state->did_current_exercise_compile = true; +TEST_CASE("next is a no-op past the last exercise", "[iterator]") { + bootstrap(2); + auto iterator{ExerciseIterator::getInstance()}; + auto last_index{TUI::p_state->list_of_exercises.size()}; + TUI::p_state->current_exercise_index = static_cast(last_index); + TUI::p_state->current_exercise = TUI::p_state->list_of_exercises.back(); + TUI::p_state->did_current_exercise_compile = true; - iterator->next(); + iterator->next(); - REQUIRE(TUI::p_state->current_exercise_index.load() == last_index); - REQUIRE(TUI::p_state->completed_exercises.empty()); + REQUIRE(TUI::p_state->current_exercise_index.load() == last_index); + REQUIRE(TUI::p_state->completed_exercises.empty()); } -TEST_CASE("previous moves back and restores completed", "[iterator]") -{ - bootstrap(2); - auto iterator{ExerciseIterator::getInstance()}; - TUI::p_state->did_current_exercise_compile = true; - iterator->next(); +TEST_CASE("previous moves back and restores completed", "[iterator]") { + bootstrap(2); + auto iterator{ExerciseIterator::getInstance()}; + TUI::p_state->did_current_exercise_compile = true; + iterator->next(); - iterator->previous(); + iterator->previous(); - REQUIRE(TUI::p_state->current_exercise_index.load() == 0); - REQUIRE(TUI::p_state->current_exercise == TUI::p_state->list_of_exercises.at(0)); - REQUIRE(TUI::p_state->completed_exercises.empty()); + REQUIRE(TUI::p_state->current_exercise_index.load() == 0); + REQUIRE(TUI::p_state->current_exercise == + TUI::p_state->list_of_exercises.at(0)); + REQUIRE(TUI::p_state->completed_exercises.empty()); } -TEST_CASE("previous is a no-op at the first exercise", "[iterator]") -{ - bootstrap(2); - auto iterator{ExerciseIterator::getInstance()}; +TEST_CASE("previous is a no-op at the first exercise", "[iterator]") { + bootstrap(2); + auto iterator{ExerciseIterator::getInstance()}; - iterator->previous(); + iterator->previous(); - REQUIRE(TUI::p_state->current_exercise_index.load() == 0); - REQUIRE(TUI::p_state->completed_exercises.empty()); + REQUIRE(TUI::p_state->current_exercise_index.load() == 0); + REQUIRE(TUI::p_state->completed_exercises.empty()); } diff --git a/src/tests/test_tui.cpp b/src/tests/test_tui.cpp index 274f446..1192eb4 100644 --- a/src/tests/test_tui.cpp +++ b/src/tests/test_tui.cpp @@ -1,15 +1,15 @@ -#include "include/tui.hpp" #include -TEST_CASE("State has sane defaults", "[tui]") -{ - TUI::State state; - REQUIRE(state.is_running.load()); - REQUIRE(state.new_user.load()); - REQUIRE(state.current_exercise_index.load() == 0); - REQUIRE_FALSE(state.is_current_exercise_compiling.load()); - REQUIRE_FALSE(state.did_current_exercise_compile.load()); - REQUIRE(state.list_of_exercises.empty()); - REQUIRE(state.completed_exercises.empty()); - REQUIRE(state.current_exercise.empty()); +#include "include/tui.hpp" + +TEST_CASE("State has sane defaults", "[tui]") { + TUI::State state; + REQUIRE(state.is_running.load()); + REQUIRE(state.new_user.load()); + REQUIRE(state.current_exercise_index.load() == 0); + REQUIRE_FALSE(state.is_current_exercise_compiling.load()); + REQUIRE_FALSE(state.did_current_exercise_compile.load()); + REQUIRE(state.list_of_exercises.empty()); + REQUIRE(state.completed_exercises.empty()); + REQUIRE(state.current_exercise.empty()); } From ff6927c7bc8faa2b31223c1a3db228c9c83fcce3 Mon Sep 17 00:00:00 2001 From: HumHad <58117805+Humam-Hamdan@users.noreply.github.com> Date: Sun, 16 Aug 2026 05:19:25 +0200 Subject: [PATCH 2/6] update includes with relative pathing to not have any problem with includes after this --- src/exercise_iterator.cpp | 6 +++--- src/exercise_runner.cpp | 6 +++--- src/file_watcher.cpp | 4 ++-- src/include/tui.hpp | 2 +- src/main.cpp | 8 ++++---- src/patch_system.cpp | 14 +++++++------- src/tests/test_exercise_iterator.cpp | 4 ++-- src/tests/test_tui.cpp | 2 +- src/tui.cpp | 10 +++++----- 9 files changed, 28 insertions(+), 28 deletions(-) diff --git a/src/exercise_iterator.cpp b/src/exercise_iterator.cpp index fa09bd4..924dc46 100644 --- a/src/exercise_iterator.cpp +++ b/src/exercise_iterator.cpp @@ -1,4 +1,4 @@ -#include "include/exercise_iterator.hpp" +#include "./include/exercise_iterator.hpp" #include #include @@ -13,8 +13,8 @@ #include #include -#include "include/patch_system.hpp" -#include "include/tui.hpp" +#include "./include/patch_system.hpp" +#include "./include/tui.hpp" using namespace jal; diff --git a/src/exercise_runner.cpp b/src/exercise_runner.cpp index eb1ffc2..dfc704c 100644 --- a/src/exercise_runner.cpp +++ b/src/exercise_runner.cpp @@ -1,4 +1,4 @@ -#include "include/exercise_runner.hpp" +#include "./include/exercise_runner.hpp" #include #include @@ -16,8 +16,8 @@ #include #include -#include "include/tui.hpp" -#include "include/util.hpp" +#include "./include/tui.hpp" +#include "./include/util.hpp" using namespace jal; diff --git a/src/file_watcher.cpp b/src/file_watcher.cpp index 7694d19..2176f81 100644 --- a/src/file_watcher.cpp +++ b/src/file_watcher.cpp @@ -1,4 +1,4 @@ -#include "include/file_watcher.hpp" +#include "./include/file_watcher.hpp" #include #include @@ -8,7 +8,7 @@ #include #include -#include "include/tui.hpp" +#include "./include/tui.hpp" using namespace jal; diff --git a/src/include/tui.hpp b/src/include/tui.hpp index ce813b0..4179a18 100644 --- a/src/include/tui.hpp +++ b/src/include/tui.hpp @@ -9,7 +9,7 @@ #include #include -#include "include/exercise_iterator.hpp" +#include "../include/exercise_iterator.hpp" namespace TUI { diff --git a/src/main.cpp b/src/main.cpp index 3d8678e..c4bab0a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -5,10 +5,10 @@ #include #include -#include "include/ascii.hpp" -#include "include/exercise_iterator.hpp" -#include "include/patch_system.hpp" -#include "include/tui.hpp" +#include "./include/ascii.hpp" +#include "./include/exercise_iterator.hpp" +#include "./include/patch_system.hpp" +#include "./include/tui.hpp" using namespace jal; diff --git a/src/patch_system.cpp b/src/patch_system.cpp index 33c7b11..f730b4b 100644 --- a/src/patch_system.cpp +++ b/src/patch_system.cpp @@ -1,4 +1,4 @@ -#include "include/patch_system.hpp" +#include "./include/patch_system.hpp" #include #include @@ -15,12 +15,12 @@ #include #include -#include "boost/asio/io_context.hpp" -#include "boost/asio/readable_pipe.hpp" -#include "include/ascii.hpp" -#include "include/exercise_iterator.hpp" -#include "include/tui.hpp" -#include "include/util.hpp" +#include "../lib/boost/asio/io_context.hpp" +#include "../lib/boost/asio/readable_pipe.hpp" +#include "./include/ascii.hpp" +#include "./include/exercise_iterator.hpp" +#include "./include/tui.hpp" +#include "./include/util.hpp" using namespace jal; diff --git a/src/tests/test_exercise_iterator.cpp b/src/tests/test_exercise_iterator.cpp index 9863c5d..0a48b14 100644 --- a/src/tests/test_exercise_iterator.cpp +++ b/src/tests/test_exercise_iterator.cpp @@ -5,8 +5,8 @@ #include #include -#include "include/exercise_iterator.hpp" -#include "include/tui.hpp" +#include "../include/exercise_iterator.hpp" +#include "../include/tui.hpp" namespace { diff --git a/src/tests/test_tui.cpp b/src/tests/test_tui.cpp index 1192eb4..73e90e8 100644 --- a/src/tests/test_tui.cpp +++ b/src/tests/test_tui.cpp @@ -1,6 +1,6 @@ #include -#include "include/tui.hpp" +#include "../include/tui.hpp" TEST_CASE("State has sane defaults", "[tui]") { TUI::State state; diff --git a/src/tui.cpp b/src/tui.cpp index 89061d7..6dd692f 100644 --- a/src/tui.cpp +++ b/src/tui.cpp @@ -1,4 +1,4 @@ -#include "include/tui.hpp" +#include "./include/tui.hpp" #include #include @@ -13,10 +13,10 @@ #include #include -#include "include/ascii.hpp" -#include "include/exercise_iterator.hpp" -#include "include/exercise_runner.hpp" -#include "include/file_watcher.hpp" +#include "./include/ascii.hpp" +#include "./include/exercise_iterator.hpp" +#include "./include/exercise_runner.hpp" +#include "./include/file_watcher.hpp" using namespace jal; From bfc9134da1aa33a2e8ea1fb0db0973cb73adada5 Mon Sep 17 00:00:00 2001 From: HumHad <58117805+Humam-Hamdan@users.noreply.github.com> Date: Sun, 16 Aug 2026 05:22:40 +0200 Subject: [PATCH 3/6] lib/compile_flagz update --- lib/compile_flagz | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/compile_flagz b/lib/compile_flagz index de42b5a..d9e122c 160000 --- a/lib/compile_flagz +++ b/lib/compile_flagz @@ -1 +1 @@ -Subproject commit de42b5af02e65d326c5cb5701cd49c57cd9bd11e +Subproject commit d9e122c8ef5bab45ebf5c7f771b9a8f5893bed22 From 277fd828f3ef1b5bd5b04a09d38103a1ac716eb2 Mon Sep 17 00:00:00 2001 From: HumHad <58117805+Humam-Hamdan@users.noreply.github.com> Date: Sun, 16 Aug 2026 05:25:06 +0200 Subject: [PATCH 4/6] fix previous error in patch_system includes --- src/patch_system.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/patch_system.cpp b/src/patch_system.cpp index f730b4b..780b286 100644 --- a/src/patch_system.cpp +++ b/src/patch_system.cpp @@ -15,12 +15,12 @@ #include #include -#include "../lib/boost/asio/io_context.hpp" -#include "../lib/boost/asio/readable_pipe.hpp" #include "./include/ascii.hpp" #include "./include/exercise_iterator.hpp" #include "./include/tui.hpp" #include "./include/util.hpp" +#include "boost/asio/io_context.hpp" +#include "boost/asio/readable_pipe.hpp" using namespace jal; From f156346dc30418c5744ca44ea59d9d34932dcb74 Mon Sep 17 00:00:00 2001 From: Humam <58117805+Humam-Hamdan@users.noreply.github.com> Date: Sun, 16 Aug 2026 16:18:04 +0200 Subject: [PATCH 5/6] Delete build_and_test.yaml workflow Removed the entire build and test workflow configuration. --- .github/workflows/build_and_test.yaml | 23 ----------------------- 1 file changed, 23 deletions(-) diff --git a/.github/workflows/build_and_test.yaml b/.github/workflows/build_and_test.yaml index 86ae1d1..8b13789 100644 --- a/.github/workflows/build_and_test.yaml +++ b/.github/workflows/build_and_test.yaml @@ -1,24 +1 @@ -name: Build -on: - push: - branches: - - "**" - pull_request: - branches: - - "**" - -jobs: - format: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: cachix/install-nix-action@v31 - - - name: build - run: | - nix develop --impure -c zig build - - - name: tests - run: | - nix develop --impure -c zig build run -Dtests From 21e5ce9a2e594137bd8e54ed7b13917b744470cd Mon Sep 17 00:00:00 2001 From: Humam <58117805+Humam-Hamdan@users.noreply.github.com> Date: Sun, 16 Aug 2026 16:18:32 +0200 Subject: [PATCH 6/6] Delete .github/workflows directory --- .github/workflows/build_and_test.yaml | 1 - .github/workflows/docker-publish-image.yaml | 96 --------------------- .github/workflows/static-analysis.yaml | 23 ----- 3 files changed, 120 deletions(-) delete mode 100644 .github/workflows/build_and_test.yaml delete mode 100644 .github/workflows/docker-publish-image.yaml delete mode 100644 .github/workflows/static-analysis.yaml diff --git a/.github/workflows/build_and_test.yaml b/.github/workflows/build_and_test.yaml deleted file mode 100644 index 8b13789..0000000 --- a/.github/workflows/build_and_test.yaml +++ /dev/null @@ -1 +0,0 @@ - diff --git a/.github/workflows/docker-publish-image.yaml b/.github/workflows/docker-publish-image.yaml deleted file mode 100644 index 4d30a7f..0000000 --- a/.github/workflows/docker-publish-image.yaml +++ /dev/null @@ -1,96 +0,0 @@ -name: Docker - -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. - -on: - schedule: - - cron: "31 17 * * *" - push: - branches: ["main"] - # Publish semver tags as releases. - tags: ["v*.*.*"] - pull_request: - branches: ["main"] - -env: - # Use docker.io for Docker Hub if empty - REGISTRY: ghcr.io - # github.repository as / - IMAGE_NAME: ${{ github.repository }} - -jobs: - build: - runs-on: ubuntu-latest - permissions: - contents: read - packages: write - # This is used to complete the identity challenge - # with sigstore/fulcio when running outside of PRs. - id-token: write - - steps: - - name: Checkout repository - uses: actions/checkout@v4 - - # Install the cosign tool except on PR - # https://github.com/sigstore/cosign-installer - - name: Install cosign - if: github.event_name != 'pull_request' - uses: sigstore/cosign-installer@59acb6260d9c0ba8f4a2f9d9b48431a222b68e20 #v3.5.0 - with: - cosign-release: "v2.2.4" - - # Set up BuildKit Docker container builder to be able to build - # multi-platform images and export cache - # https://github.com/docker/setup-buildx-action - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@f95db51fddba0c2d1ec667646a06c2ce06100226 # v3.0.0 - - # Login against a Docker registry except on PR - # https://github.com/docker/login-action - - name: Log into registry ${{ env.REGISTRY }} - if: github.event_name != 'pull_request' - uses: docker/login-action@343f7c4344506bcbf9b4de18042ae17996df046d # v3.0.0 - with: - registry: ${{ env.REGISTRY }} - username: ${{ github.actor }} - password: ${{ secrets.DOCKER_PUBLISH_IMAGE }} - - # Extract metadata (tags, labels) for Docker - # https://github.com/docker/metadata-action - - name: Extract Docker metadata - id: meta - uses: docker/metadata-action@96383f45573cb7f253c731d3b3ab81c87ef81934 # v5.0.0 - with: - images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} - - # Build and push Docker image with Buildx (don't push on PR) - # https://github.com/docker/build-push-action - - name: Build and push Docker image - id: build-and-push - uses: docker/build-push-action@0565240e2d4ab88bba5387d719585280857ece09 # v5.0.0 - with: - context: . - push: ${{ github.event_name != 'pull_request' }} - tags: ${{ steps.meta.outputs.tags }} - labels: ${{ steps.meta.outputs.labels }} - cache-from: type=gha - cache-to: type=gha,mode=max - - # Sign the resulting Docker image digest except on PRs. - # This will only write to the public Rekor transparency log when the Docker - # repository is public to avoid leaking data. If you would like to publish - # transparency data even for private images, pass --force to cosign below. - # https://github.com/sigstore/cosign - - name: Sign the published Docker image - if: ${{ github.event_name != 'pull_request' }} - env: - # https://docs.github.com/en/actions/security-guides/security-hardening-for-github-actions#using-an-intermediate-environment-variable - TAGS: ${{ steps.meta.outputs.tags }} - DIGEST: ${{ steps.build-and-push.outputs.digest }} - # This step uses the identity token to provision an ephemeral certificate - # against the sigstore community Fulcio instance. - run: echo "${TAGS}" | xargs -I {} cosign sign --yes {}@"${DIGEST}" diff --git a/.github/workflows/static-analysis.yaml b/.github/workflows/static-analysis.yaml deleted file mode 100644 index 811b713..0000000 --- a/.github/workflows/static-analysis.yaml +++ /dev/null @@ -1,23 +0,0 @@ -name: Static Analysis - -on: - push: - branches: - - "**" - pull_request: - branches: - - "**" -jobs: - format: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: cachix/install-nix-action@v31 - - - name: lint - run: | - nix develop --impure -c treefmt --ci --config-file treefmt.lint.toml - - - name: format - run: | - nix develop --impure -c treefmt --ci