In some variable called a, I want to store the contents of a pair of brackets from a variable called equation. I have an array called opening which marks the index of the opening brackets.
let equation = '2(x(4-5x)(4-x)) 10'
let opening = [9,3,1,0]
let a = ''
Attempt 1
for(let x = equation[opening[0]]; x != ')'; x ) {
a = x;
}
this lead to an infinite loop.
Attempt 2
for(let x = equation[opening[0]]; x < equation.length; x ) {
if (x == ')') {break;}
a = x;
}
this did not lead to an infinite loop but the variable a remained an empty string.
I want the result to be a = ‘4-x’
CodePudding user response:
Put the a = x in the brackets before break
CodePudding user response:
Alright. This was fun enough that I wrote an HTML page with JavaScript...
https://highdex.net/parse_eq.htm
You can view the source and see all the code, but in case I ever take that page down, I'll put just the JavaScript function in here too...
//this function takes an equation and breaks it into parts based on parentheses.
//it returns an array of the parts, where and equation like "4 * (8 - 1) / 4" would come back like...
// index 0: "4 * [1] / 4"
// index 1: "8 - 1"
//Any number shown in brackets is a reference to the index that holds what goes in that place, so you can rebuild the equation if you want.
function parseEquation(srcEq) {
let parts = [""];
let nextIndex = 0; //holds the next index we'll use inside those brackets
let currentIndex = 0; //holds the current index we're adding characters to
let backToArray = [0]; //holds the index that we need to go back to when the parentheses close
let srcLen = srcEq.length;
for (let i = 0; i < srcLen; i ) {
let currentChar = srcEq[i];
if (currentChar == "(") { //in this case we need to put the placeholder into the current index that references the next index, and then bump up the current index
if (parts.length -1 < currentIndex) {
parts.push("");
}
nextIndex ;
parts[currentIndex] = "[" nextIndex "]";
backToArray.push(currentIndex);
currentIndex = nextIndex;
}
else if (currentChar == ")") { //in this case we need to drop the current char back down a level
currentIndex = backToArray.pop();
}
else { //in this case we just add the current character to the current array at the current index
if (parts.length -1 < currentIndex) {
parts.push("");
}
parts[currentIndex] = currentChar;
}
}
return parts;
}