View Single Post
fysiks
Veteran Member
Join Date: Sep 2007
Location: Flatland, USA
Old 12-21-2011 , 16:54   Re: [AMXX] Calculator
Reply With Quote #20

Quote:
Originally Posted by Sylwester View Post
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 
errcodeerror[32]
    
pPattern regex_compile(szPatternerrcodeerrorcharsmax(error))
}

public 
cmdSay(id)
{
    static 
szArg[63], err
    read_args
(szArgcharsmax(szArg))
    
remove_quotes(szArg)
    
    if( 
regex_match_c(szArgpPatternerr) == )
    {
        
format(szArgcharsmax(szArg), "%s = %d"szArgmathEvaluateEquation(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], toplen
    len 
strlen(question)
    for(new 
ii<leni++){
        switch(
question[i]){
            case 
'0'..'9'stack[top] = stack[top]*10+question[i]-'0'
            
case '+','-','/','*','x':{
                while(
top && (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.
__________________

Last edited by fysiks; 12-21-2011 at 16:58.
fysiks is offline