Skip to content

Instantly share code, notes, and snippets.

@johnwalker
Last active December 26, 2015 17:09
Show Gist options
  • Save johnwalker/7185032 to your computer and use it in GitHub Desktop.
Save johnwalker/7185032 to your computer and use it in GitHub Desktop.
IEEExtreme 2013
#include <algorithm>
#include <functional>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <map>
#include <stack>
#include <vector>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
struct underflow{};
struct overflow{};
int add(int first, int second)
{
if(first + second > 65535)
return 65535;
else
return first + second;
}
int subtract(int first, int second)
{
if(first > second)
return 0;
else
return second - first;
}
int mand(int first, int second)
{
return (first & second);
}
int mor(int first, int second)
{
return first | second;
}
int mxor(int first, int second)
{
return first xor second;
}
int bnot(int u)
{
return (~u - 0xFFFF0000);
}
map<string, function<int(int,int)>> binaryMap;
map<string, function<int(int)>> unaryMap;
int operatorP(string word)
{
if(binaryMap.find(word) != binaryMap.end())
return 2;
if(unaryMap.find(word) != unaryMap.end())
return 1;
return 0;
}
int main()
{
stack<string> tokens;
binaryMap["+"] = add;
binaryMap["-"] = subtract;
binaryMap["&"] = mand;
binaryMap["|"] = mor;
binaryMap["X"] = mxor;
unaryMap["~"] = bnot;
string sentence;
getline(cin, sentence);
vector<string> words;
words.push_back("");
for(int i = 0; i < sentence.length(); i++)
{
if(sentence[i] == '\n')
break;
if(sentence[i] == ' ')
{
words.push_back("");
}
else
{
words.back() += sentence[i];
}
}
stack<string> wordsStack;
stringstream ss;
stringstream sss;
try
{
for(auto tWord = words.begin(); tWord != words.end(); tWord++)
{
int numberConsume;
if(numberConsume = operatorP(tWord->c_str()))
{
if(numberConsume > wordsStack.size())
{
throw exception();
}
if(numberConsume == 1)
{
int val1 = atoi(wordsStack.top().c_str());
ss.clear();
ss << wordsStack.top();
ss >> val1;
wordsStack.pop();
wordsStack.push(to_string(unaryMap[*tWord](val1)));
}
else
{
int val1;
ss.clear();
ss << wordsStack.top();
ss >> val1;
wordsStack.pop();
int val2;
ss.clear();
ss << wordsStack.top();
ss >> val2;
wordsStack.pop();
wordsStack.push(to_string(binaryMap[*tWord](val1, val2)));
}
}
else
{
int s;
sss.clear();
sss << hex << *tWord;
sss >> s;
wordsStack.push(to_string(s));
}
}
if(wordsStack.size() > 1)
cout << "ERROR" << endl;
else
cout << uppercase << setfill('0') << setw(4) << hex << atoi(wordsStack.top().c_str()) << endl;
}
catch(underflow& und)
{
cout << "0000" << endl;
}
catch(overflow& und)
{
cout << "FFFF" << endl;
}
catch(exception& e)
{
cout << "ERROR" << endl;
}
return 0;
}
@johnwalker
Copy link
Author

A lot of the exceptions aren't used because the problem was open to interpretation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment