Byte Heist Home Leaderboard
Join the Heist (with Github)
Solve View

Equation Solver 3

I need some code to do my homework for me. Each equation can be simplified to a linear one. Print out the value of x satisfying the equation.

Each equation will be on a separate line.

My teacher allows a tolerance of 1e-4 because she knows how hard it can be to do correct rounding in base 10 when your floating-point numbers are internally represented in base 2.

Judge

(async function*(context: Context): Challenge {
    const decimalPlaceRegex = /(?<=\.[1-9]*)0+$|\.0+$/;
    
    yield* context.runTestCases([
        [' 1*x = 1.2', '1.2'],
        ['3*x+ #2*(1-x+(2*x)/2)-4= 1*x+7', '4.5'],
        ['(1 - (1 - (1 - x*2))) = 9999.9', '-4999.45'],
        ['2 * 3 * 4 * x = 3 * 5 * 13', '8.125'],
        ['(2 + 2*x)/#2 = 3 * x', '0.5'],
        ['123 = 1000*x', '0.123'],
        ['10*x = 1', '0.1'],
        ['10*x = 2', '0.2'],
        ['10*x = 3', '0.3'],
        ['10*x-4 = 0', '0.4'],
        ['10*x-13=0', '1.3'],
        ['10*x = 5', '0.5'],
        ['10*x = 6', '0.6'],
        [' 1*x*x + 1.5 - 3*x*x = 1*x - 4*x*x/#2', '1.5'],
        ['100*x = 314', '3.14'],
        ['(x-x)*(4*x)*(58/2)= 1*x-0.1', '0.1'],
        ['(10*x-1)/(#1*#2*#3*#4*#5*#6*#7*#8*#9)= 1*#10', '362880.1'],
        ['#5*( 1*x- 1*x+ 1*x- 1*x+ 1*x)=8', '1.6'],
        ['(1 - (2 - (1 - x*4))) = 999.9', '-249.975'],
        ['4*x + 5 = 2*x + 2', '-1.5']
    ].flatMap(
        ([key, value]) => {
            let multiple = Math.random()*10+0.1;
            multiple -= multiple % 0.01;
            let addition = Math.random()*10 + 0.1;
            addition -= addition % 0.001;
            return [
                [key.replace(/#| 1\*/g,""), value],
                [
                    key.replace(/(?<!#)\d+(\.\d+)?/g,k=>((+k) * multiple)
						.toFixed(3)
						.replace(decimalPlaceRegex,'')
					).replace(/#/g,""),
                    value
                ],
                [
                    key.replace(
						/(=|$)/g, i=>'+'+addition
							.toFixed(3)
							.replace(decimalPlaceRegex, '')+i
					).replace(/#| 1\*/g,""),
                    value
                ]
            ] as [string, string][]
        }
    ), {
        compareFunction: (a,b)=>Math.abs(+a - +b) < 0.0001
    });
    
    return context.noFailures();
})

Example Code

input = require("fs").readFileSync(0).toString();
for(equation of input.split("\n"))
{
	[lhs, rhs] = equation.split("=");
	y0 = eval(lhs.replace(/x/g, 0)) - eval(rhs.replace(/x/g, 0));
	y1 = eval(lhs.replace(/x/g, 1)) - eval(rhs.replace(/x/g, 1));
	console.log(y0 / (y0 - y1));
}