31 lines
1.2 KiB
TypeScript
31 lines
1.2 KiB
TypeScript
function solveEquation(equation: string): string {
|
|
let [a, b, c, sign, left, hasC] = [0, 0, 0, 1, 1, false];
|
|
for (let z of equation) {
|
|
switch (z) {
|
|
case 'x':
|
|
[a, c, hasC] = [a + (hasC ? sign * left * c : sign * left), 0, false];
|
|
break;
|
|
case '+':
|
|
[b, c, sign, hasC] = [b + sign * left * c, 0, 1, false];
|
|
break;
|
|
case '-':
|
|
[b, c, sign, hasC] = [b + sign * left * c, 0, -1, false];
|
|
break;
|
|
case '=':
|
|
[b, c, sign, left, hasC] = [b + sign * left * c, 0, 1, -1, false];
|
|
break;
|
|
default:
|
|
[c, hasC] = [c * 10 + Number(z), true];
|
|
break;
|
|
}
|
|
}
|
|
b += sign * left * c;
|
|
return a === 0 ? b === 0 ? "Infinite solutions" : "No solution" : "x=" + -b / a;
|
|
}
|
|
|
|
console.assert(solveEquation("x+5-3+x=6+x-2") === "x=2");
|
|
console.assert(solveEquation("x=x") === "Infinite solutions");
|
|
console.assert(solveEquation("2x=x") === "x=0");
|
|
console.assert(solveEquation("0x=0") === "Infinite solutions");
|
|
console.assert(solveEquation("0=0x") === "Infinite solutions");
|