Quote:
Originally Posted by Sylwester
You should check this: http://forums.alliedmods.net/showthr...55#post1612755
It can solve any valid equation and you don't need to put spaces between operators and values.
Also in my opinion you should remove required ! (just check if what player said is valid equation) and instead of blocking say you could edit it and add at the end in green color " = <result>".
|
PHP Code:
#include <amxmodx>
#include <regex>
new Regex:pPattern
new szPattern[] = "[^^0-9\+\-\*\/\s]"
public plugin_init()
{
register_plugin("Chat Math", "0.1", "Fysiks")
register_clcmd("say", "cmdSay")
new errcode, error[32]
pPattern = regex_compile(szPattern, errcode, error, charsmax(error))
}
public cmdSay(id)
{
static szArg[63], err
read_args(szArg, charsmax(szArg))
remove_quotes(szArg)
if( regex_match_c(szArg, pPattern, err) == 0 )
{
format(szArg, charsmax(szArg), "%s = %d", szArg, mathEvaluateEquation(szArg))
engclient_cmd(id, "say", szArg)
return PLUGIN_HANDLED
}
return PLUGIN_CONTINUE
}
// This algorithm by Sylwester
// http://forums.alliedmods.net/showpost.php?p=1612755&postcount=2
public mathEvaluateEquation(question[])
{
static stack[6], top, len
len = strlen(question)
for(new i; i<len; i++){
switch(question[i]){
case '0'..'9': stack[top] = stack[top]*10+question[i]-'0'
case '+','-','/','*','x':{
while(top > 0 && (stack[top-1] == '*' || stack[top-1] == 'x' || stack[top-1] == '/' || question[i] == '+' || question[i] == '-')){
switch(stack[top-1]){
case '+': stack[top-2] += stack[top]
case '-': stack[top-2] -= stack[top]
case '/': stack[top-2] /= stack[top]
case '*','x': stack[top-2] *= stack[top]
}
top -= 2
}
stack[++top] = question[i]
stack[++top] = 0
}
}
}
while(top>0){
switch(stack[top-1]){
case '+': stack[top-2] += stack[top]
case '-': stack[top-2] -= stack[top]
case '/': stack[top-2] /= stack[top]
case '*','x': stack[top-2] *= stack[top]
}
top -= 2
}
return stack[top]
}
It only does integer math though.
__________________