diff --git a/include/design_a_simple_automaton/automaton.h b/include/design_a_simple_automaton/automaton.h new file mode 100644 index 0000000..bfe2723 --- /dev/null +++ b/include/design_a_simple_automaton/automaton.h @@ -0,0 +1,13 @@ +#ifndef CPP_KATAS_AUTOMATON_H +#define CPP_KATAS_AUTOMATON_H + +#include + +class Automaton { +public: + Automaton(); + + bool read_commands(const std::vector &commands); +}; + +#endif //CPP_KATAS_AUTOMATON_H diff --git a/src/design_a_simple_automaton/automaton.cpp b/src/design_a_simple_automaton/automaton.cpp new file mode 100644 index 0000000..79bea50 --- /dev/null +++ b/src/design_a_simple_automaton/automaton.cpp @@ -0,0 +1,68 @@ +#include + +/** + * https://www.codewars.com/kata/5268acac0d3f019add000203/train/cpp + */ +class Automaton { +public: + Automaton(); + + bool read_commands(const std::vector &commands); +}; + +Automaton::Automaton() = default; + +class State { +public: + virtual State *transition(char command) = 0; + + virtual bool is_final() { + return false; + } +}; + +class Q1 : public State { + State *transition(char command) override; +}; + +class Q2 : public State { + State *transition(char command) override; + + bool is_final() override { + return true; + } +}; + +class Q3 : public State { + State *transition(char command) override; +}; + +bool Automaton::read_commands(const std::vector &commands) { + State *state = new Q1(); + + for (const char &command: commands) { + state = state->transition(command); + } + + return state->is_final(); +} + +State *Q1::transition(char command) { + if (command == '1') { + return new Q2(); + } + + return this; +} + +State *Q2::transition(char c) { + if (c == '0') { + return new Q3(); + } + + return this; +} + +State *Q3::transition(char c) { + return new Q2(); +} diff --git a/test/design_a_simple_automaton/automaton_test.cpp b/test/design_a_simple_automaton/automaton_test.cpp new file mode 100644 index 0000000..6eaa515 --- /dev/null +++ b/test/design_a_simple_automaton/automaton_test.cpp @@ -0,0 +1,16 @@ +#include +#include "design_a_simple_automaton/automaton.h" + +using namespace igloo; + +Describe(BasicTests) { + It(Test1) { + auto automata = Automaton(); + Assert::That(automata.read_commands({'1'}), Equals(true)); + } + + It(Test2) { + auto automata = Automaton(); + Assert::That(automata.read_commands({'1', '0', '0', '1'}), Equals(true)); + } +};