1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
#include <iostream> #include <string> #include <unordered_map> #include <vector> class LSystem { public: LSystem(const std::string& axiom, const std::unordered_map<char, std::string>& rules) : currentString(axiom), productionRules(rules) {} void generate(int iterations) { for (int i = 0; i < iterations; ++i) { std::string nextString; for (char ch : currentString) { if (productionRules.find(ch) != productionRules.end()) { nextString += productionRules.at(ch); } else { nextString += ch; } } currentString = nextString; } } void display() const { std::cout << "L-System string: " << currentString << "\n"; } private: std::string currentString; std::unordered_map<char, std::string> productionRules; }; int main() { // Define the axiom and production rules for the L-System std::string axiom = "F"; std::unordered_map<char, std::string> rules = { {'F', "F+F-F-F+F"} }; // Create an LSystem object LSystem lSystem(axiom, rules); // Generate the L-System string for a number of iterations int iterations = 4; lSystem.generate(iterations); // Display the generated L-System string lSystem.display(); return 0; } |
Explanation
- LSystem Class:
- Attributes:
currentString
: Holds the current state of the L-System string.productionRules
: A map of production rules where each character maps to its replacement string.
- Methods:
LSystem(const std::string& axiom, const std::unordered_map<char, std::string>& rules)
: Constructor initializes the L-System with an axiom and production rules.void generate(int iterations)
: Generates the L-System string for a given number of iterations. It replaces each character incurrentString
with its corresponding production rule.void display() const
: Displays the current L-System string.
- Attributes:
- main Function:
- Defines the axiom (“F”) and production rules (e.g., “F” → “F+F-F-F+F”).
- Creates an
LSystem
object with the specified axiom and rules. - Generates the L-System string for a number of iterations (e.g., 4).
- Displays the final L-System string.