From d1823d5399623e94702d000c6e707e7d56119bb0 Mon Sep 17 00:00:00 2001 From: Vincent Date: Wed, 6 Mar 2024 14:43:10 +0000 Subject: [PATCH] refactor: improve the fibonacci command --- README.md | 5 +++-- include/fibonacci_command.h | 29 +++++++++++++++-------------- 2 files changed, 18 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index bf85cb7..8eace75 100644 --- a/README.md +++ b/README.md @@ -19,9 +19,10 @@ aiming to craft C++ plugins for the Bedrock Dedicated Servers using Endstone. ``` cpp-plugin-template/ ├── include/ # Header files for the plugin -│ └── endstone_cpp_plugin.h # Header for the EndstoneCppPlugin class +│ ├── example_plugin.h # Header for the ExamplePlugin class +│ └── fibonacci_command.h # Header for the FibonacciCommand class ├── src/ # Source files for the plugin -│ └── endstone_cpp_plugin.cpp # Implementation for the EndstoneCppPlugin class +│ └── example_plugin.cpp # Implementation for the ExamplePlugin class ├── .clang-format # Configuration for Clang format rules ├── .gitignore # Git ignore rules ├── CMakeLists.txt # CMake configuration for building the plugin diff --git a/include/fibonacci_command.h b/include/fibonacci_command.h index b3eaf2a..8abbc9e 100644 --- a/include/fibonacci_command.h +++ b/include/fibonacci_command.h @@ -5,13 +5,13 @@ #include "endstone/command/command.h" #include "endstone/command/command_executor.h" -#include // for std::ostringstream +#include class FibonacciCommand : public endstone::Command { public: FibonacciCommand() : Command("fibonacci") { - setDescription("A simple command that prints out the fibonacci series for n <= 20"); + setDescription("A simple command that writes the Fibonacci series up to n."); setAliases("fib"); setUsages("/fibonacci "); } @@ -23,23 +23,24 @@ class FibonacciCommandExecutor : public endstone::CommandExecutor { const std::vector &args) override { int n = std::stoi(args[0]); - if (n > 0 && n <= 20) { - int t1 = 1, t2 = 1, next; - std::ostringstream os; - for (int i = 1; i <= n; ++i) { - if (i > 1) { - os << ", "; + if (n > 0) { + int a = 0, b = 1; + std::string result; + while (a < n) { + if (!result.empty()) { + result += ", "; } - os << t1; - next = t1 + t2; - t1 = t2; - t2 = next; + + result += std::to_string(a); + int temp = b; + b = a + b; + a = temp; } - sender.sendMessage("Fibonacci Series (n = {}): {}", n, os.str()); + sender.sendMessage("Fibonacci series up to {}: {}", n, result); return true; } else { - sender.sendErrorMessage("'n' must be greater than 0 and less than or equal to 20."); + sender.sendErrorMessage("'n' must be an integer greater than 0."); return false; } }