Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions include/design_a_simple_automaton/automaton.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#ifndef CPP_KATAS_AUTOMATON_H
#define CPP_KATAS_AUTOMATON_H

#include <vector>

class Automaton {
public:
Automaton();

bool read_commands(const std::vector<char> &commands);
};

#endif //CPP_KATAS_AUTOMATON_H
68 changes: 68 additions & 0 deletions src/design_a_simple_automaton/automaton.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
#include <vector>

/**
* https://www.codewars.com/kata/5268acac0d3f019add000203/train/cpp
*/
class Automaton {
public:
Automaton();

bool read_commands(const std::vector<char> &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<char> &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();
}
16 changes: 16 additions & 0 deletions test/design_a_simple_automaton/automaton_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#include <igloo/igloo_alt.h>
#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));
}
};