Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- pastebin get bs4QNDyS solve
- local strins = function(str,ins,pos)
- return str:sub(1,pos-1)..tostring(ins)..str:sub(pos)
- end
- --syntax:
- --solve(sting leftside, string rightside, string variablename, number maxiterations)
- solve = function(left,right,varname,maxIterations) -- left part of equation, right part of equation. got it memorized?
- local step, output, flips, diff, olddiff = 2^64, 0, 0
- varname = varname or "x"
- maxIterations = tonumber(maxIterations) or 2^16
- local try = function()
- local Ls,L = pcall( function() return loadstring("return "..left:gsub("[%+%-]"..varname,function(s) return strins(s," ",2) end):gsub(varname,"("..output..")"))() end )
- local Rs,R = pcall( function() return loadstring("return "..right:gsub("[%+%-]"..varname,function(s) return strins(s," ",2) end):gsub(varname,"("..output..")"))() end )
- assert(type(L) == "number", "malformed equation (LEFT)")
- assert(type(R) == "number", "malformed equation (RIGHT)")
- return L - R, L, R
- end
- assert(type(left) == "string", "left equation must be string")
- assert(type(right) == "string", "right equation must be string")
- assert(type(varname) == "string", "variable name must be string")
- assert(type(maxIterations) == "number", "max iterations must be number")
- for a = 1, maxIterations do
- olddiff = diff or 0
- diff = try()
- if diff == 0 then
- return output, true
- else
- if math.abs(diff) > math.abs(olddiff) then
- if a == 1 then
- step = step * -1
- else
- step = step * -0.5
- end
- flips = flips + 1
- end
- output = output + step
- end
- end
- if (flips <= 1) then
- return math.huge%1, false --not a number, false
- else
- return output, false
- end
- end
- --syntax:
- --strsolve(string equation, string variablename)
- strsolve = function(equation,variable)
- assert(type(equation) == "string", "equation must be string")
- variable = variable or "x"
- assert(equation:find("="), "malformed equation (NO '=')")
- equation = equation:gsub("%d+["..variable.."]",function(str)
- return str:sub( 1,str:find(variable)-1 ).."*"..variable
- end):gsub("%)%(","%)%*%("):gsub("[%d("..variable..")]%(",function(s) return strins(s,"*",2) end)
- return solve(equation:sub(1,equation:find("=")-1),equation:sub(equation:find("=")+1),variable)
- end
- local tArg = {...}
- if tArg[1] then
- print(strsolve(table.concat(tArg,""),"x"),"")
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement