Array Operations

Given Some string s, and a vector of strings enlisting instructions..

Ex.

``````    string main = "abc";
vector<string> cmds =
{
"00L", // -> zbc
"22L", // -> zbb
"02R", // -> acc
};``````
• The first instruction tells us to take the substring at (0,0), and increment all the characters in that substring to the left by 1. (so its really decrementing it)

• The second instruction tells us to take the subtring at (2,2), and

• The third instruction tells us to take the substring at (0,2), and increment all the characters to the right by 1.

You get the idea. Notice that the substring only changes, and the remainder of the string is unaffected. Also, each instructions builts of the changes from the previous instruction.

``````void decrement_str(string &s) {
for (int j = 0; j < s.length(); j++) {
if (s[j] == 'a')
s[j] = 'z';
else s[j]--;
}
}

void increment_str(string &s) {
for (int j = 0; j < s.length(); j++) {
if (s[j] == 'z')
s[j] = 'a';
else s[j]++;
}
}

string rollingString(string s, vector < string > operations) {

string sub = "";
for (int i = 0; i < operations.size(); i++) {
string ith_op = operations[i];
int i1 = ith_op[0] - '0';
int i2 = ith_op[1] - '0';
if (i1 == i2) {
sub = s[i1]; // or i2
}
else sub = string(s.begin() + i1, s.begin() + i2 + 1);

if      (ith_op[2] == 'L') decrement_str(sub);
else if (ith_op[2] == 'R') increment_str(sub);

string front = string(s.begin(), s.begin() + i1);
string end = string(s.begin() + i2 + 1, s.end());
s = front + sub + end;
}

return s;
}

int main()
{
string main = "abc";
vector<string> cmds =
{
"00L", // -> zbc
"22L", // -> zbb
"02R", // -> acc
};

cout << rollingString(main, cmds) << endl;
}``````

Last updated