I solved the following problem:
You will be given a mathematical string and your task will be to remove all braces as follows:
solve("x-(y+z)") = "x-y-z"` solve("x-(y-z)") = "x-y+z"` solve("u-(v-w-(x+y))-z") = "u-v+w+x+y-z"` solve("x-(-y-z)") = "x+y+z"`
There are no spaces in the expression. Only two operators are given: "+" or "-".
This is the solution I came up with:
function removeAt(s, index) {
if (index === s.length - 1) {
return s.slice(0, -1)
}
return s.slice(0, index) + s.slice(index + 1);
}
function insertAt(s, index, str) {
return s.slice(0, index) + str + s.slice(index);
}
function replaceAt(s, index, chr) {
if (index > s.length - 1) return s;
return s.slice(0, index) + chr + s.slice(index + 1);
}
function reverseSigns(s, start, end) {
for (var i = start; i < end; i++) {
if (s[i] === '-') {
s = replaceAt(s, i, '+');
} else if (s[i] === '+') {
s = replaceAt(s, i, '-');
}
}
return s;
}
function solve(s) {
//Get the position of the parenthesis
var Close = 0, Open = -1;
while (s[Close] !== ')' && Close < s.length) {
if (s[Close] === '(') {
Open = Close;
}
Close++;
}
//Check to see if there is any parenthesis
if (Open !== -1) {
//Insert sign before if there is none
if (s[Open + 1] !== '+' && s[Open + 1] !== '-') {
s = insertAt(s, Open + 1, '+');
//'Close' parenthesis has changed --> +1 right
Close++;
}
//Check to see if a sign has to be replaced
if (s[Open - 1] === '-') {
s = reverseSigns(s, Open + 1, Close - 1);
}
//Remove the parenthesis
s = removeAt(s, Close);
s = removeAt(s, Open);
//Remove the sign before paranthesis
if (s[Open - 1] === '-' || s[Open - 1] === '+') {
s = removeAt(s, Open - 1);
}
//Recursive call
return solve(s);
//return s;
}
//Remove unnecessary +
if (s[0] === '+') {
s = removeAt(s, 0);
}
return s;
}
I was wondering if my code could be improved.
a+(x-y)
. You can take that into account and explicitly state whether you exclude such possibility based on examples which do not contain it, or you handle it correctly. \$\endgroup\$