How to find an unreachable state in C? Observe text file below. It is a state ma
ID: 3723788 • Letter: H
Question
How to find an unreachable state in C? Observe text file below. It is a state machine. First column of each row is current state and second column is next state if input is 0. If input is 1 go to column 3. So if youre at C and enter 0 you go to A.
A B C
B A A
C A D
D D C
Now my program lets you change the second and third column and so you can end up in a situation where you have an unreachable state like below
A B C
B A A
C A B
D D C
So if youre not in D state you can never reach it. Now i need to write code so that on a certain command it will identify all unreachable states. Can you help me please?
Explanation / Answer
//here I have considered input in the form of 3x4 matrix,but you can change it to the number of row manually,
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int main(){
vector< vector<char> > states;
for(int i=0;i<4;i++)
{
vector<char> row;
for(int j=0;j<3;j++)
{
char a;
cin>>a;
row.push_back(a);
}
states.push_back(row);
}
set<char> reached_states;
set<char> all_states;
set<char> unreachable;
for(int i=0;i<states.size();i++)
{
for(int j=1;j<states[0].size();j++){
if(states[i][0]!=states[i][j])
{
reached_states.insert(states[i][j]);
}
all_states.insert(states[i][0]);
all_states.insert(states[i][j]);
}
}
set <char> :: iterator itr;
cout << " The set of all states is : ";
for (itr = all_states.begin(); itr != all_states.end(); ++itr)
{
cout << ' ' << *itr;
}
cout << endl;
cout << " The set reached_states is : ";
for (itr = reached_states.begin(); itr != reached_states.end(); ++itr)
{
cout << ' ' << *itr;
}
cout << endl;
set_difference (all_states.begin(), all_states.end(), reached_states.begin(), reached_states.end(), inserter(unreachable, unreachable.end()));
cout << " The set unreachable states is : ";
for (itr = unreachable.begin(); itr != unreachable.end(); ++itr)
{
cout << ' ' << *itr;
}
cout << endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.