Skip to content

Instantly share code, notes, and snippets.

@Yanpas
Created February 2, 2016 23:17
Show Gist options
  • Save Yanpas/f5c5f1359a384c3174de to your computer and use it in GitHub Desktop.
Save Yanpas/f5c5f1359a384c3174de to your computer and use it in GitHub Desktop.
bracket placer (Break point on line 60)
#include <iostream>
int lsearch(std::string s, size_t pos) //pos from
{
int bc=0;
while(pos>0)
{
if(s[pos]== ')') bc++;
if(s[pos]== '(') bc--;
if(bc<0) return lsearch(s,pos-1);
if(bc==0 && s[pos]==' ') return pos+1;
pos--;
}
return 0;
}
int rsearch(std::string s, int pos)
{
int bc=0;
pos=s.find(" ",pos+1)+1;
while(pos<(int)s.size() && pos > 0)
{
if(s[pos]== '(') bc++;
if(s[pos]== ')') bc--;
if(bc<0) return rsearch(s,s.find(" ",pos+2));
if(bc==0 && s[pos]==' ') return pos;
pos++;
}
return (int)s.size();
}
std::string addParentheses(std::string s) {
//not
int tp = -1;
while (tp < (int)s.size())
{
tp = s.find("not ", tp+1);
if (tp==-1) break;
s.insert(tp, "(");
int cb = s.find(" ",tp+5);
if (cb==-1) cb = s.size();
s.insert(cb, ")");
tp++;
}
tp = -1;
while (tp < (int)s.size())
{
tp = s.find("and ", tp+1);
if (tp==-1) break;
s.insert(rsearch(s, tp), ")");
s.insert(lsearch(s, tp-2), "(");
tp++;
}
tp = -1;
while (tp < (int)s.size())
{
tp = s.find("or ", tp+1);
if (tp==-1) break;
s.insert(rsearch(s, tp), ")");
s.insert(lsearch(s, tp-2), "(");
tp++;
}
return s;
}
int main()
{
//std::cout << addParentheses("a and b or c") << std::endl;
//std::cout << addParentheses("(a and b) or not c") << std::endl;
std::cout << addParentheses("A and (B or not C) or D") << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment