Skip to content

Instantly share code, notes, and snippets.

@antvconst
Created November 17, 2016 21:45
Show Gist options
  • Save antvconst/e7f13cd453e39cae8c47cc370ee29db9 to your computer and use it in GitHub Desktop.
Save antvconst/e7f13cd453e39cae8c47cc370ee29db9 to your computer and use it in GitHub Desktop.
#include <string>
#include <vector>
#include <iostream>
using namespace std;
struct str_pair {
string u, v;
};
void shift_numeration(vector<string>& v, int k) {
for (int i = 0; i < v.size(); ++i) {
string s = v.at(i);
if ((s.at(0) == '>') || (s.at(0) == '&'))
v.at(i) = s.at(0) + to_string(stoi(s.substr(1)) + k);
}
}
bool remove_parentheses(string& s) {
if ((s.at(0) == '(') && (s.at(s.length()-1) == ')')) {
s = s.substr(1, s.length()-2);
return true;
}
else
return false;
}
int last_top_level(string s, char op) {
int pos = -1;
int braces_open = 0;
for (int i = 0; i < s.length(); ++i) {
char c = s.at(i);
if (c == '(')
braces_open++;
else if (c == ')')
braces_open--;
else if ((c == op) && (braces_open == 0))
pos = i;
}
return pos;
}
str_pair unfold(string s, char op) {
int pos = last_top_level(s, op);
return str_pair {
s.substr(0, pos),
s.substr(pos+1)
};
}
vector<string> parse(string s) {
str_pair p;
vector<string> v;
if (last_top_level(s, ';') != -1) {
p = unfold(s, ';');
remove_parentheses(p.u);
remove_parentheses(p.v);
vector<string> l = parse(p.u);
vector<string> r = parse(p.v);
int n_l = l.size();
int n_r = r.size();
v.push_back(">" + to_string(n_l + 3)); // set jump to second subarray
shift_numeration(l, 1); // shift left subarray by one
v.insert(v.end(), l.begin(), l.end( )); // insert the left subarray
shift_numeration(r, n_l+2); // shift the numeration of right subarray
v.push_back("&" + to_string(n_l + n_r + 3)); // set jump past second subarray
v.insert(v.end(), r.begin(), r.end()); // insert the right subarray
}
else if (last_top_level(s, ',') != -1) {
p = unfold(s, ',');
bool u_par = remove_parentheses(p.u);
bool v_par = remove_parentheses(p.v);
vector<string> l = parse(p.u);
vector<string> r = parse(p.v);
if (u_par)
shift_numeration(l, 1);
if (v_par)
shift_numeration(r, 1);
v.insert(v.end(), l.begin(), l.end());
v.insert(v.end(), r.begin(), r.end());
}
else {
v.push_back(s);
}
return v;
}
int main() {
string s = "A,(a;B),b;C;D";
vector<string> t = parse(s);
for (int i = 0; i < t.size(); ++i) {
cout << i+1 << ". " << t.at(i) << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment