Skip to content

Instantly share code, notes, and snippets.

@TrigonaMinima
Last active September 7, 2015 21:46
Show Gist options
  • Save TrigonaMinima/2012bc88397241ee713b to your computer and use it in GitHub Desktop.
Save TrigonaMinima/2012bc88397241ee713b to your computer and use it in GitHub Desktop.
Compiler Lab
// Deterministic Finite Automata
# include <iostream>
# include <fstream>
# include <vector>
# include <sstream>
# include <string>
# include <map>
using namespace std;
// Creates the dfa type of data structure.
// start symbol, no. of states, no. of inputs, table.
struct dfa
{
string start;
vector<string> states, inputs, final;
map< string, map<string, string> > table;
};
// Prints the vector.
void print_vector(vector<string> v)
{
int size = v.size(), i=0;
while(i != size)
{
cout << v[i] << " ";
i++;
}
cout << endl;
}
// Genrates the transition table kind of dictionary.
dfa gen_table(vector<string> v)
{
dfa inp;
int size = v.size(), isize;
// Start symbol
inp.start = v[0];
// cout << inp.start << endl;
// All states extracted.
stringstream ss1(v[1]);
string temp;
while (ss1 >> temp)
inp.states.push_back(temp);
// print_vector(inp.states);
// All final states extracted.
stringstream ss2(v[2]);
while (ss2 >> temp)
inp.final.push_back(temp);
// print_vector(inp.inputs);
// All inputs extracted.
stringstream ss3(v[3]);
while (ss3 >> temp)
inp.inputs.push_back(temp);
isize = inp.inputs.size();
// print_vector(inp.inputs);
// Creates the table.
for(int i=4; i<size; i++)
{
if(v[i] == "")
break;
map<string, string> row;
vector<string> rows;
stringstream ss(v[i]);
while (ss >> temp)
rows.push_back(temp);
print_vector(rows);
for(int j=0; j<isize; j++)
row[inp.inputs[j]] = rows[j];
inp.table[inp.states[i-4]] = row;
}
return inp;
}
// Checks the validity of the user input
int check_validity(dfa inp, string input)
{
int size = input.size(), i = 0, flag = 1, size1 = 0;
string current = inp.start;
string output;
bool exists;
cout << "\n --------------- ------- ------------ " << endl;
cout << "| Current State | Input | Next State |" << endl;
cout << " --------------- ------- ------------ " << endl;
do
{
exists = inp.table[current].find(string(1, input[i])) == inp.table[current].end();
if(!exists)
{
cout << "|\t" << current << "\t| "<< input[i] << " | ";
output = inp.table[current][string(1, input[i])];
if (output == "-1")
{
cout << "\nInput symbol \"" << input[i] << "\" at state "
<< current << " is not recognized!!";
flag = 0;
break;
}
current = output;
cout << current << " |\n";
i++;
if(i == size)
cout << " --------------- ------- ------------ " << endl;
size1 = inp.final.size();
for (int k = 0; k < size1; ++k)
{
if (current == inp.final[k])
flag = 1;
else
flag = 0;
}
}
else
{
cout << " --------------- ------- ------------ " << endl;
cout << "\nInput symbol \"" << input[i] << "\" at state \""
<< current << "\" is not recognized!!" << endl;
flag = 0;
break;
}
}
while(i != size);
return flag;
}
int main()
{
vector<string> data; // stores file data
string s;
dfa inp;
// read input file
ifstream f("input.txt");
while(f)
{
getline(f, s);
data.push_back(s);
}
f.close();
// create an in-memory dict/table
inp = gen_table(data);
// take a string as input
cout << "Enter the string to check: ";
getline(cin, s);
// Check the validity of the string & display the output.
if (check_validity(inp, s))
cout << "\nString accepted!!\n";
else
cout << "\nString not accepted!!\n";
return 0;
}
q1
q1 q2
q2
0 1
q2 q1
q1 q2
// Mealy Machine
# include <iostream>
# include <fstream>
# include <vector>
# include <sstream>
# include <string>
# include <map>
using namespace std;
// Creates the mealy type of data structure.
// start symbol, no. of states, no. of inputs, table.
struct mealy
{
string start;
vector<string> states, inputs;
map< string, map<string, map<string, string> > > table;
};
// Prints the vector.
void print_vector(vector<string> v)
{
int size = v.size(), i=0;
while(i != size)
{
cout << v[i] << " ";
i++;
}
cout << endl;
}
// Genrates the transition table kind of dictionary.
mealy gen_table(vector<string> v)
{
mealy inp;
int size = v.size(), isize;
// Start symbol
inp.start = v[0];
// cout << inp.start << endl;
// All states extracted.
stringstream ss1(v[1]);
string temp;
while (ss1 >> temp)
inp.states.push_back(temp);
// print_vector(inp.states);
// All inputs extracted.
stringstream ss2(v[2]);
while (ss2 >> temp)
inp.inputs.push_back(temp);
isize = inp.inputs.size();
// print_vector(inp.inputs);
// Creates the table.
for(int i=3; i<size; i++)
{
if(v[i] == "")
break;
map<string, map<string, string> > row;
vector<string> rows;
stringstream ss(v[i]);
while (ss >> temp)
rows.push_back(temp);
// print_vector(rows);
for(int j=0; j<isize; j++)
{
map<string, string> element;
element["out"] = rows[j*2];
element["state"] = rows[j*2+1];
row[inp.inputs[j]] = element;
}
inp.table[inp.states[i-3]] = row;
}
return inp;
}
// Checks the validity of the user input
void check_validity(mealy inp, string input)
{
int size = input.size(), i=0;
string current = inp.start;
string output;
bool exists;
cout << "\n --------------- ------- -------- ------------ " << endl;
cout << "| Current State | Input | Output | Next State |" << endl;
cout << " --------------- ------- -------- ------------ " << endl;
do
{
exists = inp.table[current].find(string(1, input[i])) == inp.table[current].end();
if(!exists)
{
cout << "|\t" << current << "\t| "<< input[i] << " | ";
output = inp.table[current][string(1, input[i])]["out"];
if (output == "-1")
{
cout << "\nInput symbol \"" << input[i] << "\" at state "
<< current << " is not recognized!!";
break;
}
current = inp.table[current][string(1, input[i])]["state"];
cout << output << " | " << current << " |\n";
i++;
if(i == size)
cout << " --------------- ------- -------- ------------ " << endl;
}
else
{
cout << " --------------- ------- -------- ------------ " << endl;
cout << "\nInput symbol \"" << input[i] << "\" at state \""
<< current << "\" is not recognized!!" << endl;
break;
}
}
while(i != size);
}
int main()
{
vector<string> data; // stores file data
string s;
mealy inp;
// read input file
ifstream f("input.txt");
while(f)
{
getline(f, s);
data.push_back(s);
}
f.close();
// create an in-memory dict/table
inp = gen_table(data);
// take a string as input
cout << "Enter the string to check: ";
getline(cin, s);
// Check the validity of the string & display the output.
check_validity(inp, s);
return 0;
}
q1
q1 q2 q3
0 1
0 q2 1 q3
0 q2 -1 -1
1 q2 0 q3
// Moore Machine
# include <iostream>
# include <fstream>
# include <vector>
# include <sstream>
# include <string>
# include <map>
using namespace std;
// Creates the moore type of data structure.
// start symbol, no. of states, no. of inputs, table.
struct moore
{
string start;
vector<string> states, inputs;
map<string, string> state_outputs;
map< string, map<string, map<string, string> > > table;
};
// Prints the vector.
void print_vector(vector<string> v)
{
int size = v.size(), i=0;
while(i != size)
{
cout << v[i] << " ";
i++;
}
cout << endl;
}
// Genrates the transition table kind of dictionary.
moore gen_table(vector<string> v)
{
moore inp;
int size = v.size(), isize, i = 0;
// Start symbol
inp.start = v[0];
// cout << inp.start << endl;
// All states extracted.
stringstream ss1(v[1]);
string temp;
while (ss1 >> temp)
inp.states.push_back(temp);
// print_vector(inp.states);
// All states' outputs extracted.
stringstream ss2(v[2]);
while (ss2 >> temp)
{
inp.state_outputs[inp.states[i]] = temp;
// inp.states.push_back(temp);
i++;
}
// print_vector(inp.states);
// All inputs extracted.
stringstream ss3(v[3]);
while (ss3 >> temp)
inp.inputs.push_back(temp);
isize = inp.inputs.size();
// print_vector(inp.inputs);
// Creates the table.
for(int i=4; i<size; i++)
{
if(v[i] == "")
break;
map<string, map<string, string> > row;
vector<string> rows;
stringstream ss(v[i]);
while (ss >> temp)
rows.push_back(temp);
print_vector(rows);
for(int j=0; j<isize; j++)
{
map<string, string> element;
element["out"] = rows[isize];
element["state"] = rows[j];
row[inp.inputs[j]] = element;
}
inp.table[inp.states[i-4]] = row;
}
return inp;
}
// Checks the validity of the user input
void check_validity(moore inp, string input)
{
int size = input.size(), i=0;
string current = inp.start;
string output;
bool exists;
cout << "\n --------------- ------- ------------ -------- " << endl;
cout << "| Current State | Input | Next State | Output |" << endl;
cout << " --------------- ------- ------------ -------- " << endl;
do
{
exists = inp.table[current].find(string(1, input[i])) == inp.table[current].end();
if(!exists)
{
cout << "|\t" << current << "\t| "<< input[i] << " | ";
current = inp.table[current][string(1, input[i])]["state"];
output = inp.state_outputs[current];
cout << current << " | " << output << " |\n";
i++;
if(i == size)
cout << " --------------- ------- ------------ -------- " << endl;
}
else
{
cout << " --------------- ------- ------------ -------- " << endl;
cout << "\nInput symbol \"" << input[i] << "\" at state \""
<< current << "\" is not recognized!!" << endl;
break;
}
}
while(i != size);
}
int main()
{
vector<string> data; // stores file data
string s;
moore inp;
// read input file
ifstream f("input.txt");
while(f)
{
getline(f, s);
data.push_back(s);
}
f.close();
// create an in-memory dict/table
inp = gen_table(data);
// take a string as input
cout << "Enter the string to check: ";
getline(cin, s);
// Check the validity of the string & display the output.
check_validity(inp, s);
return 0;
}
q0
q0 q1 q2
1 0 1
0 1
q0 q2 1
q1 q1 0
q1 q0 1
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <set>
#include <sstream>
#include <cstdlib>
using namespace std;
void getFinalStates(string line, vector<int>& final){
string cell;
istringstream line_stream(line);
while(getline(line_stream, cell, ',')){
final.push_back((int)(cell[0] - 48));
}
}
void makeTransition(string line, vector< vector< vector<int> > >& transition){
vector< vector<int> >row;
vector<int> one;
for (int i=0; i<line.length(); i++) {
//cout<<"Line length: "<<line.length()<<endl;
if(line[i] != ' ') {
if(line[i] == '-') {
one.push_back(-1);
//cout<<"Pushing: "<<one[one.size()-1]<<endl;
i++;
} else if(line[i] != ',') {
one.push_back((int)(line[i]-48));
//cout<<"Pushing: "<<one[one.size()-1]<<endl;
}
if(i == line.length()-1) {
row.push_back(one);
}
} else {
row.push_back(one);
one.clear();
}
}
transition.push_back(row);
}
int main() {
int start;
string line;
vector<int> final;
vector< vector< vector<int> > > transition;
vector<int> dfaStates;
ifstream input("nfa.txt");
getline(input, line);
start = (int)(line[0] - 48);
cout << "Initial State : " << start << endl;
getline(input, line);
getFinalStates(line, final);
cout << "Final State(s) : ";
for (int i = 0; i < final.size(); ++i){
cout << final[i] << " ";
}
cout << endl;
while(getline(input, line)){
makeTransition(line, transition);
}
// Print matrix
cout<<"Matrix:"<<endl;
for (int i=0; i<transition.size(); i++) {
vector< vector<int> > row = transition[i];
for (int j=0; j<row.size(); j++) {
vector<int> one = row[j];
for (int k=0; k<one.size(); k++) {
cout<<one[k]<<",";
}
cout<<" ";
}
cout<<endl;
}
cout << "Enter input string : ";
cin >> line;
dfaStates.push_back(start);
for (int i = 0; i < line.length(); ++i){
int curr_in = (int)(line[i] - 48);
vector<int> next;
for (int j = 0; j < dfaStates.size(); ++j){
int curr_state = dfaStates[j];
for (int k = 0; k < 4; ++k){
int next_state = transition[curr_state][curr_in][k];
if(next_state == -1){
cout << "Not accepted";
exit(-1);
}
next.push_back(next_state);
}
}
dfaStates = next;
}
set<int> dfaStatesSet(dfaStates.begin(), dfaStates.end());
set<int> finalStates(final.begin(), final.end());
vector<int> intersection;
set_intersection(dfaStatesSet.begin(), dfaStatesSet.end(),finalStates.begin(), finalStates.end(),back_inserter(intersection));
if (intersection.size() > 0) {
cout << "Input Accepted";
} else {
cout << "Input NOT Accepted";
}
input.close();
return 0;
}
// Deterministic Finite Automata
// Incomplete
# include <iostream>
# include <fstream>
# include <vector>
# include <sstream>
# include <string>
# include <map>
# include <set>
using namespace std;
// Creates the dfa type of data structure.
// start symbol, no. of states, no. of inputs, table.
struct nfa
{
string start;
vector<string> states, inputs, final;
map< string, map<string, set<string> > > table;
};
struct dfa
{
string start;
vector<string> states, inputs, final;
map< string, map<string, string > > table;
};
// Prints the vector.
void print_vector(vector<string> v)
{
int size = v.size(), i=0;
while(i != size)
{
cout << v[i] << " ";
i++;
}
cout << endl;
}
// Genrates the transition table kind of dictionary.
dfa gen_table(vector<string> v)
{
dfa inp;
int size = v.size(), isize;
// Start symbol
inp.start = v[0];
// cout << inp.start << endl;
// All states extracted.
stringstream ss1(v[1]);
string temp;
while (ss1 >> temp)
inp.states.push_back(temp);
// print_vector(inp.states);
// All final states extracted.
stringstream ss2(v[2]);
while (ss2 >> temp)
inp.final.push_back(temp);
// print_vector(inp.inputs);
// All inputs extracted.
stringstream ss3(v[3]);
while (ss3 >> temp)
inp.inputs.push_back(temp);
isize = inp.inputs.size();
// print_vector(inp.inputs);
// Creates the table.
for(int i = 4; i < size; i++)
{
if(v[i] == "")
break;
map<string, set<string> > row;
vector<string> rows;
stringstream ss(v[i]);
while (ss >> temp)
rows.push_back(temp);
print_vector(rows);
for(int j=0; j<isize; j++)
{
set<string> nfa_state;
istringstream line_stream(rows[j]);
while(getline(line_stream, temp, ','))
nfa_state.insert(temp);
row[inp.inputs[j]] = nfa_state;
}
inp.table[inp.states[i-4]] = row;
}
return inp;
}
string join( const set<string>& st, const char* const sep)
{
switch (st.size())
{
case 0:
return "";
case 1:
return st[0];
default:
std::ostringstream os;
std::copy(st.begin(), st.end()-1, std::ostream_iterator<std::string>(os, separator));
os << *st.rbegin();
return os.str();
}
}
dfa conversion(nfa automata)
{
dfa converted;
converted.start = automata.start;
converted.states = automata.states;
converted.inputs = automata.inputs;
converted.final = automata.final;
for (it_type i = automata.table.begin(); i != automata.table.end(); i++)
{
for (it_type j = i->second.begin(); j != i->second.end(); j++)
{
map<string, string> temp;
set<string> new_state;
string state = join(j->second);
temp[j->first] = state;
converted[state][j->first] = set_union()
}
converted.table[i->first] =
}
}
// Checks the validity of the user input
// int check_validity(dfa inp, string input)
// {
// int size = input.size(), i = 0, flag = 1, size1 = 0;
// string current = inp.start;
// string output;
// bool exists;
// cout << "\n --------------- ------- ------------ " << endl;
// cout << "| Current State | Input | Next State |" << endl;
// cout << " --------------- ------- ------------ " << endl;
// do
// {
// exists = inp.table[current].find(string(1, input[i])) == inp.table[current].end();
// if(!exists)
// {
// cout << "|\t" << current << "\t| "<< input[i] << " | ";
// output = inp.table[current][string(1, input[i])];
// if (output == "-1")
// {
// cout << "\nInput symbol \"" << input[i] << "\" at state "
// << current << " is not recognized!!";
// flag = 0;
// break;
// }
// current = output;
// cout << current << " |\n";
// i++;
// if(i == size)
// cout << " --------------- ------- ------------ " << endl;
// size1 = inp.final.size();
// for (int k = 0; k < size1; ++k)
// {
// if (current == inp.final[k])
// flag = 1;
// else
// flag = 0;
// }
// }
// else
// {
// cout << " --------------- ------- ------------ " << endl;
// cout << "\nInput symbol \"" << input[i] << "\" at state \""
// << current << "\" is not recognized!!" << endl;
// flag = 0;
// break;
// }
// }
// while(i != size);
// return flag;
// }
int main()
{
vector<string> data; // stores file data
string s;
nfa inp;
dfa automata;
// read input file
ifstream f("input.txt");
while(f)
{
getline(f, s);
data.push_back(s);
}
f.close();
// create an in-memory dict/table
inp = gen_table(data);
// Converts the nfa to dfa
automata = conversion(inp);
// take a string as input
cout << "Enter the string to check: ";
getline(cin, s);
// Check the validity of the string & display the output.
// if (check_validity(inp, s))
// cout << "\nString accepted!!\n";
// else
// cout << "\nString not accepted!!\n";
return 0;
}
p
p q
q
0 1
p p,q
-1 -1
0
1,3
0 1,3
2 1
2,3 -1
0 2
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
#define MAX_ROWS 5
#define MAX_COLS 5
/*
INPUT FILE FORMAT:
1/0 0/1
1/1 0/0
*/
#define INPUT_FILE "input.txt"
int state_matrix[MAX_ROWS][MAX_COLS];
int output_matrix[MAX_ROWS][MAX_COLS];
////////////////////////////////////////////////////////////////////
void print_arr(int arr[], int size) {
for (int i = 0; i < size; ++i) {
cout << arr[i] << " ";
}
cout << endl;
}
void print_matrix(int mat[][MAX_COLS], int rows, int cols) {
for (int i = 0; i < rows; ++i) {
print_arr(mat[i], cols);
}
cout << endl;
}
////////////////////////////////////////////////////////////////////
// Read file and fill matrices
void read_file() {
ifstream file(INPUT_FILE);
if (!file.is_open()) {
cerr << "Couldn't open input file: " << INPUT_FILE;
}
string line;
int i = 0;
while (getline(file, line)) {
string cell;
istringstream line_stream(line);
int j = 0;
while(getline(line_stream, cell, ' ')) {
// Cell is of the form 'state/output'
// We store it by converting to int
state_matrix[i][j] = cell[0] - 48;
output_matrix[i][j] = cell[2] - 48;
j++;
}
i++;
}
}
int main(int argc, char const *argv[])
{
read_file();
// Initial State
int cur_state = 0;
// Current Output
int cur_output = 0;
// Input String
string input;
cout << "Enter input string: ";
cin >> input;
cout << endl;
// Header
cout << "Output: " << endl << endl;
cout << "S - O" << endl;
cout << "-----" << endl;
int length = input.length();
for (int i = 0; i < length; ++i)
{
// Convert char '1'/'0' to int 1/0
int cur_input = int(input[i]) - 48;
cur_state = state_matrix[cur_state][cur_input];
cur_output = output_matrix[cur_state][cur_input];
cout << cur_state << " - " << cur_output << endl;
}
return 0;
}
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
#define MAX_ROWS 5
#define MAX_COLS 5
/*
INPUT FILE FORMAT:
states, output
0 2, 1
1 1, 0
1 0, 1
*/
#define INPUT_FILE "input.txt"
int state_matrix[MAX_ROWS][MAX_COLS];
int output[MAX_ROWS];
////////////////////////////////////////////////////////////////////
void print_arr(int arr[], int size) {
for (int i = 0; i < size; ++i) {
cout << arr[i] << " ";
}
cout << endl;
}
void print_matrix(int mat[][MAX_COLS], int rows, int cols) {
for (int i = 0; i < rows; ++i) {
print_arr(mat[i], cols);
}
cout << endl;
}
////////////////////////////////////////////////////////////////////
// Read file and fill matrices
void read_file() {
ifstream file(INPUT_FILE);
if (!file.is_open()) {
cerr << "Couldn't open input file: " << INPUT_FILE;
}
string line;
int i = 0;
while (getline(file, line)) {
string cell;
// Remove the last three characters from the line; for eg: ', 2'
istringstream line_stream(line.substr(0, line.length() - 3));
int j = 0;
while(getline(line_stream, cell, ' ')) {
// Cell is of the form 'state'
// We store it by converting to int
state_matrix[i][j] = cell[0] - 48;
j++;
}
// The last character contains the output of that state
output[i] = line[line.length() - 1] - 48;
i++;
}
}
int main(int argc, char const *argv[])
{
read_file();
// print_matrix(state_matrix, 3, 2);
// print_arr(output, 3);
// Initial State
int cur_state = 0;
// Current Output
int cur_output = 0;
// Input String
string input;
cout << "Enter input string: ";
cin >> input;
cout << endl;
// Header
cout << "Output: " << endl << endl;
cout << "I - S - O" << endl;
cout << "---------" << endl;
// Print intial values
// cout << "-" << " - " << cur_state << " - " << cur_output << endl;
// cout << "---------" << endl;
int length = input.length();
for (int i = 0; i < length; ++i)
{
// Convert char '1'/'0' to int 1/0
int cur_input = int(input[i]) - 48;
cur_state = state_matrix[cur_state][cur_input];
cur_output = output[cur_state];
cout << cur_input << " - " << cur_state << " - " << cur_output << endl;
}
return 0;
}
0 2, 1
1 0, 0
2 1, 1
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
void getFinalStates(string line, vector<int>& final){
string cell;
istringstream line_stream(line);
while(getline(line_stream, cell, ',')){
final.push_back((int)(cell[0] - 48));
}
}
void makeTransition(string line, vector<vector<int> >& transition, int& col){
vector<int> r;
for (int i = 0; i < line.length(); ++i){
if(line[i] == '-'){
r.push_back(-1);
i += 2;
}
else if(line[i] != ' '){
r.push_back((line[i] - 48));
}
}
transition.push_back(r);
col++;
}
int main(){
string line;
ifstream input("dfa.txt");
int start, col;
vector<int> final;
vector<vector<int> > transition;
getline(input, line);
start = (int)(line[0] - 48);
cout << "Initial State : " << start << endl;
getline(input, line);
getFinalStates(line, final);
cout << "Final State(s) : ";
for (int i = 0; i < final.size(); ++i){
cout << final[i] << " ";
}
cout << endl;
col = 0;
while(getline(input, line)){
makeTransition(line, transition, col);
}
cout << endl << "Transition Table" << endl;
for (int i = 0; i < transition.size(); ++i){
vector<int> r = transition[i];
for (int j = 0; j < r.size(); ++j){
cout << r[j] << " ";
}
cout << endl;
}
//cout << col;
cout << "Enter String : ";
cin >> line;
int prev = start;
int curr;
int flag = 1, reached = 0;
for (int i = 0; i < line.length(); ++i){
curr = (line[i] - 48);
if(curr >= col){
flag = 0;
break;
}
else if(transition[prev][curr] == -1){
flag = 0;
break;
}
prev = transition[prev][curr];
}
if(flag == 0){
cout << "Not Accepted" << endl;
}
else{
for (int i = 0; i < final.size(); ++i){
if(final[i] == prev){
reached = 1;
}
}
if(reached){
cout << "Accepted" << endl;
}
else{
cout << "Not Accepted" << endl;
}
}
return 0;
}
0
2,3
0 1
2 1
3 1
0 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment