// Question 3(a): Convert the regular expression r = *(a(a|bb)*) into NFA using Thompson’s construction.
#include <iostream>
#include <vector>
#include <string>
// Structure to represent a state in NFA
struct State {
int id;
std::vector<std::pair<char, int>> transitions; // pair of input symbol and next state id
bool isFinal;
State(int identifier) : id(identifier), isFinal(false) {}
};
// Function to create NFA for the regular expression *(a(a|bb)*)
int main() {
std::vector<State> nfa;
// Create states
// State 0: Start state
nfa.emplace_back(0);
// State 1: After '*'
nfa.emplace_back(1);
// State 2: After 'a'
nfa.emplace_back(2);
// State 3: Start of (a|bb)
nfa.emplace_back(3);
// State 4: After 'a' in (a|bb)
nfa.emplace_back(4);
// State 5: After first 'b' in 'bb'
nfa.emplace_back(5);
// State 6: After second 'b' in 'bb'
nfa.emplace_back(6);
// State 7: Final state
nfa.emplace_back(7);
// Define transitions
// State 0 ε -> State 1
nfa[0].transitions.emplace_back('\0', 1);
// State 1 ε -> State 2
nfa[1].transitions.emplace_back('\0', 2);
// State 2 'a' -> State 3
nfa[2].transitions.emplace_back('a', 3);
// State 3 ε -> State 4 (for 'a') and State 5 (for 'bb')
nfa[3].transitions.emplace_back('\0', 4);
nfa[3].transitions.emplace_back('\0', 5);
// State 4 'a' -> State 7
nfa[4].transitions.emplace_back('a', 7);
// State 5 'b' -> State 6
nfa[5].transitions.emplace_back('b', 6);
// State 6 'b' -> State 7
nfa[6].transitions.emplace_back('b', 7);
// State 7 ε -> State 1 (loop for '*')
nfa[7].transitions.emplace_back('\0', 1);
// Set final state
nfa[7].isFinal = true;
// Display NFA
for (const auto& state : nfa) {
std::cout << "State " << state.id;
if (state.isFinal) std::cout << " (Final)";
std::cout << " transitions: ";
for (const auto& [symbol, nextState] : state.transitions) {
if (symbol == '\0') std::cout << "ε->" << nextState << " ";
else std::cout << symbol << "->" << nextState << " ";
}
std::cout << std::endl;
}
return 0;
}
Explanation:
- States: Each state is represented with a unique ID. State 0 is the start state, and state 7 is the final state.
- Transitions:
- ε-transitions (
'\0') are used for operations like Kleene star * and alternation |.
- The transition from state 3 splits into two paths for
a and bb.
- The loop for Kleene star is created by connecting the final state back to state 1.