Skip to content

Commit 1ff6334

Browse files
authored
Solve 'Design a Simple Automaton (Finite State Machine)' kata (#8)
* Setup kata * Solve 'Design a Simple Automaton (Finite State Machine)' kata
1 parent 41ac136 commit 1ff6334

File tree

3 files changed

+97
-0
lines changed

3 files changed

+97
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
#ifndef CPP_KATAS_AUTOMATON_H
2+
#define CPP_KATAS_AUTOMATON_H
3+
4+
#include <vector>
5+
6+
class Automaton {
7+
public:
8+
Automaton();
9+
10+
bool read_commands(const std::vector<char> &commands);
11+
};
12+
13+
#endif //CPP_KATAS_AUTOMATON_H
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
#include <vector>
2+
3+
/**
4+
* https://www.codewars.com/kata/5268acac0d3f019add000203/train/cpp
5+
*/
6+
class Automaton {
7+
public:
8+
Automaton();
9+
10+
bool read_commands(const std::vector<char> &commands);
11+
};
12+
13+
Automaton::Automaton() = default;
14+
15+
class State {
16+
public:
17+
virtual State *transition(char command) = 0;
18+
19+
virtual bool is_final() {
20+
return false;
21+
}
22+
};
23+
24+
class Q1 : public State {
25+
State *transition(char command) override;
26+
};
27+
28+
class Q2 : public State {
29+
State *transition(char command) override;
30+
31+
bool is_final() override {
32+
return true;
33+
}
34+
};
35+
36+
class Q3 : public State {
37+
State *transition(char command) override;
38+
};
39+
40+
bool Automaton::read_commands(const std::vector<char> &commands) {
41+
State *state = new Q1();
42+
43+
for (const char &command: commands) {
44+
state = state->transition(command);
45+
}
46+
47+
return state->is_final();
48+
}
49+
50+
State *Q1::transition(char command) {
51+
if (command == '1') {
52+
return new Q2();
53+
}
54+
55+
return this;
56+
}
57+
58+
State *Q2::transition(char c) {
59+
if (c == '0') {
60+
return new Q3();
61+
}
62+
63+
return this;
64+
}
65+
66+
State *Q3::transition(char c) {
67+
return new Q2();
68+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
#include <igloo/igloo_alt.h>
2+
#include "design_a_simple_automaton/automaton.h"
3+
4+
using namespace igloo;
5+
6+
Describe(BasicTests) {
7+
It(Test1) {
8+
auto automata = Automaton();
9+
Assert::That(automata.read_commands({'1'}), Equals(true));
10+
}
11+
12+
It(Test2) {
13+
auto automata = Automaton();
14+
Assert::That(automata.read_commands({'1', '0', '0', '1'}), Equals(true));
15+
}
16+
};

0 commit comments

Comments
 (0)