Piyush 14937
Piyush 14937
Write a program to
simulate an FA that accepts
public:
DFA(int startState) : startState(startState) {}
toProcess.push({dfa1.getStartState(), dfa2.getStartState()});
visited.insert({dfa1.getStartState(), dfa2.getStartState()});
stateMapping[{dfa1.getStartState(), dfa2.getStartState()}] = 0;
while (!toProcess.empty()) {
auto [state1, state2] = toProcess.front();
toProcess.pop();
int combinedState = stateMapping[{state1, state2}];
if (dfa1.isAcceptedState(state1) ||
dfa2.isAcceptedState(state2)) {
result.addAcceptState(combinedState);
}
result.addTransition(combinedState, symbol,
stateMapping[nextCombinedState]);
if (visited.find(nextCombinedState) == visited.end()) {
visited.insert(nextCombinedState);
toProcess.push(nextCombinedState);
}
}
}
}
return result;
}
DFA dfa2(0);
dfa2.addAcceptState(2);
dfa2.addTransition(0,'a',1);
dfa2.addTransition(1,'a',2);
string input;
cout<<"Enter input string : ";
cin>>input;
if(simulateDFA(unionResult,input)){
cout<<"STRING IS ACCEPTED";
}else{
cout<<"STRING IS REJECTED";
}
return 0;
}
b. Intersection of the
languages L1 and L2
#include<bits/stdc++.h>
using namespace std;
// Code by PIYUSH
struct pair_hash {
template <class T1, class T2>
std::size_t operator()(const std::pair<T1, T2>& p) const {
return std::hash<T1>()(p.first) ^ (std::hash<T2>()(p.second)
<< 1);
}
};
class DFA {
private:
int startState;
unordered_set<int> acceptStates;
unordered_map<int, unordered_map<char, int>> transitions;
public:
DFA(int startState) : startState(startState) {}
void addAcceptState(int state) {
acceptStates.insert(state);
}
queue<StatePair> toProcess;
unordered_map<StatePair, int, pair_hash> stateMapping;
int stateCounter = 0;
toProcess.push({dfa1.getStartState(), dfa2.getStartState()});
stateMapping[{dfa1.getStartState(), dfa2.getStartState()}] =
stateCounter++;
while (!toProcess.empty()) {
auto [state1, state2] = toProcess.front();
toProcess.pop();
int combinedState = stateMapping[{state1, state2}];
if (stateMapping.find(nextCombinedState) ==
stateMapping.end()) {
stateMapping[nextCombinedState] = stateCounter++;
toProcess.push(nextCombinedState);
}
result.addTransition(combinedState, symbol,
stateMapping[nextCombinedState]);
}
}
}
return result;
}
int main() {
DFA dfa1(0);
dfa1.addAcceptState(2);
dfa1.addTransition(0, 'a', 1);
dfa1.addTransition(1, 'b', 2);
DFA dfa2(0);
dfa2.addAcceptState(2);
dfa2.addTransition(0, 'a', 1);
dfa2.addTransition(1, 'a', 2);
string input;
cout << "Enter input string: ";
cin >> input;
if (simulateDFA(intersectionDFAResult, input))
cout << "STRING IS ACCEPTED" << endl;
else
cout << "STRING IS REJECTED" << endl;
return 0;
}