Pagini recente » Cod sursa (job #2847230) | Cod sursa (job #378774) | Cod sursa (job #372710) | Cod sursa (job #1688399) | Cod sursa (job #2445062)
#include <iostream>
#include<string>
#include<stack>
#include<fstream>
using namespace std;
ofstream out("bool.out");
enum class type
{
value,
operation
};
bool variables[27];
enum class operation
{
AND,
OR,
NOT
};
int precedence(operation op)
{
if(op==operation::NOT)
return 3;
if(op==operation::AND)
{
return 2;
}
if(op==operation::OR)
return 1;
return 0;
}
type get_type(const string&to_get)
{
if(to_get=="OR"||to_get=="AND" ||to_get=="NOT")
{
return type::operation;
}
else if(to_get=="TRUE"||to_get=="FALSE")
{
return type::value;
}
}
bool apply_operation(bool a,bool b,operation op)
{
switch(op)
{
case operation::AND:
return a&&b;
case operation::OR:
return a||b;
default:
return false;
}
}
string get_next_string(unsigned&cursor,const string&source)
{
string result;
while(cursor<source.length() &&std::isalpha(source[cursor]))
{
result+=source[cursor++];
}
cursor--;
return result;
}
bool get_value(const string&value)
{
if(value=="TRUE" ||value=="FALSE")
{
if(value=="TRUE")
return true;
return false;
}
else
return variables[value[0]-'A'];
}
operation get_operation(const string&value)
{
if(value=="AND")
return operation::AND;
if(value=="OR")
return operation::OR;
if(value=="NOT")
return operation::NOT;
}
void apply_last_ops(stack<bool>&values,stack<operation>&ops)
{
int val2 = values.top();
values.pop();
int val1 = values.top();
values.pop();
operation op = ops.top();
ops.pop();
values.push(apply_operation(val1, val2, op));
}
bool solve(unsigned&cursor,const string&to_solve)
{
stack<bool>values;
stack<operation> operations;
bool nt=true;
string aux;
while(cursor<to_solve.length() &&to_solve[cursor]!=')')
{
char here=to_solve[cursor];
if(std::isalpha(here))//if its a letter
{
aux=get_next_string(cursor,to_solve);
type t=get_type(aux);
if(t==type::operation)
{
operation op=get_operation(aux);
if(op==operation::NOT)
{
nt=!nt;
}
else
{
while(!operations.empty() && precedence(operations.top())
>= precedence(op))
{
apply_last_ops(values,operations);
}
operations.push(op);
nt=true;
}
}
else
{
if(nt)
values.push(get_value(aux));
else
values.push(!get_value(aux));
}
}
else if(here=='(')
{
cursor++;
bool value=solve(cursor,to_solve);
if(nt)
values.push(value);
else
values.push(!value);
}
cursor++;
}
while(operations.size())
apply_last_ops(values,operations);
return values.top();
}
void solveexp(string&to_solve)
{
unsigned cursor=0;
out<<solve(cursor,to_solve);
}
void solve_prb()
{
string a,b,c;
ifstream in("bool.in");
std::getline(in,a);
std::getline(in,b);
std::getline(in,c);
for(int i=0; i<c.length(); i++)
{
variables[c[i]-'A']=!variables[c[i]-'A'];
solveexp(a);
}
}
int main()
{
unsigned a=0;
solve_prb();
return 0;
}