I made a cross multiplication thing which was massive! Totally not worth it, but it did teach me a little about string manipulation. But why have the computer solve it like we, humans, solve it, when computers so soo good at arithmetic?
Here is a simple math equation solver using Lua, brute forcing the answer!
Code:
local function solve(s)
local n
local checks = {}
local env = setmetatable({ math = math }, {
__index = math
})
for d = 1,10000 do
for i = -10000,10000 do
if(not checks[tostring(i/d)])then
checks[tostring(i/d)] = true
n = setfenv(loadstring("return "..((s:gsub("x", i/d)):gsub("=", "=="))), env)()
if(n)then
return d~=1 and "x = "..i.."/"..d or "x = "..i
end
end
end
end
end
print(solve("2*x = x+4")) -- x = 4
Examples of how to use:
print(solve("2+x = 4")) --> x = 2
print(solve("x = 3.14")) --> x = 157/50
print(solve("x+5 = x*5")) --> x = 5/4
print(solve("(x+5)/20 = 120")) --> x = 2395
print(solve("math.sin(x+5) = math.sin(10)")) --> x = 5
It's just sorta cool. I don't wanna solve equations anymore, teachers!