Jump to content

check for balanced parentheses


Gianni
 Share

Recommended Posts

This function will check for balanced parentheses in an expression
just a simple exercise for fun

(see

 

Edit: today (july 5 2015) I discovered that the original listing that was here was lost for some reason (maybe one of the many issues arose after forum upgrades) :(
I found a version of that function on my HD and I post again (hope it is the same version that was here before)

; https://gist.github.com/mycodeschool/7207410
;
Local $sExpr = "[{(1 + 3i)/((-1 - i)^2) + (-4 + i)(-4 - i)/(1 + i)}*{(1 + 3i)/((-1 - i)^2) + (-4 + i)(-4 - i)/(1 + i)}]"
MsgBox(0, "Parenthesis check", AreParanthesesBalanced($sExpr))
Exit

; --------------------------------------------------------
; Returns True if parenthesis in $sExpression are balanced
; --------------------------------------------------------
Func AreParanthesesBalanced($sExpression)
    Local $sStack = ""
    For $i = 1 To StringLen($sExpression)
        If StringInStr('({[', StringMid($sExpression, $i, 1)) Then ; opening parenthesis
            $sStack &= StringMid($sExpression, $i, 1)
        ElseIf StringInStr(')}]', StringMid($sExpression, $i, 1)) Then ; a closing parenthesis
            If Not StringLen($sStack) Or Not _ArePair(StringRight($sStack, 1), StringMid($sExpression, $i, 1)) Then
                Return False
            Else
                $sStack = StringLeft($sStack, StringLen($sStack) - 1)
            EndIf
        EndIf
    Next
    Return Not StringLen($sStack) ? True : False
    #cs
        ; alternative for old AutoIt versions
        ; without ternary operator

        If Not StringLen($sStack) Then
        Return True
        Else
        Return False
        EndIf
    #ce
EndFunc   ;==>AreParanthesesBalanced

Func _ArePair($sOpening, $sClosing)
    If ($sOpening = '(' And $sClosing = ')') Then Return True
    If ($sOpening = '{' And $sClosing = '}') Then Return True
    If ($sOpening = '[' And $sClosing = ']') Then Return True
    Return False
EndFunc   ;==>ArePair

 

Edited by Chimp
listing was disappeared. I post again

 

image.jpeg.9f1a974c98e9f77d824b358729b089b0.jpeg Chimp

small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

Link to comment
Share on other sites

  • Moderators

ConsoleWrite(_ArePair("(", ")") & ":" & _ArePair("<", ">") & ":" & _
_ArePair("{", "}") & ":" & _ArePair("[", "]") & @CRLF)
 
Func _ArePair($sOpening, $sClosing)
Return (StringRegExp($sOpening & $sClosing, "^(?:\(\)|\{\}|\[\])$") <> 0)
EndFunc   ;==>ArePair

Edit:

Does this do the same as well? (Less string functions):

Edit2: Fixed my logic error:

Global $gsExpr = "[{(1 + 3i)/((-1 - i)^2) + (-4 + i)(-4 - i)/(1 + i)}*{(1 + 3i)/((-1 - i)^2) + (-4 + i)(-4 - i)/(1 + i)}]"
MsgBox(0, "Parenthesis check", AreParanthesisBalanced($gsExpr) & @CRLF & @error & @CRLF & @extended)

Func AreParanthesisBalanced($sExpression)

    Local Const $aBalance[3][2] = [["(",")"],["{","}"],["[","]"]]
    Local $iExt
    For $i = 0 To UBound($aBalance) - 1 Step 2
        StringReplace($sExpression, $aBalance[$i][0], "", 0, 1)
        $iExt = @extended
        StringReplace($sExpression, $aBalance[$i][1], "", 0, 1)
        ; $i is the parenthesis value 1 for "(", 2 for "{", 3 for "["
        If @extended <> $iExt Then Return SetError(1, $i + 1, False)
    Next

    Return True
EndFunc
Edited by SmOke_N

Common sense plays a role in the basics of understanding AutoIt... If you're lacking in that, do us all a favor, and step away from the computer.

Link to comment
Share on other sites

ConsoleWrite(_ArePair("(", ")") & ":" & _ArePair("<", ">") & ":" & _
_ArePair("{", "}") & ":" & _ArePair("[", "]") & @CRLF)
 
Func _ArePair($sOpening, $sClosing)
Return (StringRegExp($sOpening & $sClosing, "^(?:\(\)|\{\}|\[\])$") <> 0)
EndFunc   ;==>ArePair

Edit:

Does this do the same as well? (Less string functions):

Edit2: Fixed my logic error:

Global $gsExpr = "[{(1 + 3i)/((-1 - i)^2) + (-4 + i)(-4 - i)/(1 + i)}*{(1 + 3i)/((-1 - i)^2) + (-4 + i)(-4 - i)/(1 + i)}]"
MsgBox(0, "Parenthesis check", AreParanthesisBalanced($gsExpr) & @CRLF & @error & @CRLF & @extended)

Func AreParanthesisBalanced($sExpression)

    Local Const $aBalance[3][2] = [["(",")"],["{","}"],["[","]"]]
    Local $iExt
    For $i = 0 To UBound($aBalance) - 1 Step 2
        StringReplace($sExpression, $aBalance[$i][0], "", 0, 1)
        $iExt = @extended
        StringReplace($sExpression, $aBalance[$i][1], "", 0, 1)
        ; $i is the parenthesis value 1 for "(", 2 for "{", 3 for "["
        If @extended <> $iExt Then Return SetError(1, $i + 1, False)
    Next

    Return True
EndFunc

 

This approach is not correct

try to check this expression for example "1+1)("

your function will return True (but it isn't). The parenthesis are not correctly closed

 

image.jpeg.9f1a974c98e9f77d824b358729b089b0.jpeg Chimp

small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

Link to comment
Share on other sites

and a stab with array functions..

#include <Array.au3>

Local $sExpr = "[{(1 + 3i)/((-1 - i)^2) + (-4 + i)(-4 - i)/(1 + i)}*{(1 + 3i)/((-1 - i)^2) + (-4 + i)(-4 - i)/(1 + i)}]"
;~ Local $sExpr = "1+1)("


$aExpr = stringsplit($sExpr , "" , 3)

For $i = ubound($aExpr) - 1 to 0 step - 1
    If $aExpr[$i] <> "(" AND $aExpr[$i] <> ")" Then _ArrayDelete($aExpr , $i)
Next

For $i = ubound($aExpr) - 1 to 0 step - 2
    If $aExpr[$i] = ")" Then
        $aFound = _ArrayFindAll($aExpr , "(")
        IF @ERROR Then msgbox(0, '' , "unbalanced")
        _ArrayDelete($aExpr , $i)
        _ArrayDelete($aExpr, $aFound[ubound($aFound) - 1])
    EndIf
Next

If ubound($aExpr) <> 0 Then
    msgbox (0, '' , "unbalanced")
Else
    msgbox (0, '' , "balanced")
Endif

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Link to comment
Share on other sites

You can use recursive regulare expressions.

Func AreParanthesisBalanced ($string)
    Static $parenthesis = "(?:\((?P>brackets)\))"
    Static $brace = "(?:\{(?P>brackets)\})"
    Static $bracket = "(?:\[(?P>brackets)\])"
    Static $nonBracket = "(?:[^(){}\[\]])"
    Static $brackets = "(?<brackets>(" & $parenthesis & "|" & $brace & "|" & $bracket & "|" & $nonBracket & ")*)"
    Static $regex = "^" & $brackets & "$"
    Return StringRegExp ($string, $regex)
EndFunc
Link to comment
Share on other sites

 

and a stab with array functions..

#include <Array.au3>

Local $sExpr = "[{(1 + 3i)/((-1 - i)^2) + (-4 + i)(-4 - i)/(1 + i)}*{(1 + 3i)/((-1 - i)^2) + (-4 + i)(-4 - i)/(1 + i)}]"
;~ Local $sExpr = "1+1)("


$aExpr = stringsplit($sExpr , "" , 3)

For $i = ubound($aExpr) - 1 to 0 step - 1
    If $aExpr[$i] <> "(" AND $aExpr[$i] <> ")" Then _ArrayDelete($aExpr , $i)
Next

For $i = ubound($aExpr) - 1 to 0 step - 2
    If $aExpr[$i] = ")" Then
        $aFound = _ArrayFindAll($aExpr , "(")
        IF @ERROR Then msgbox(0, '' , "unbalanced")
        _ArrayDelete($aExpr , $i)
        _ArrayDelete($aExpr, $aFound[ubound($aFound) - 1])
    EndIf
Next

If ubound($aExpr) <> 0 Then
    msgbox (0, '' , "unbalanced")
Else
    msgbox (0, '' , "balanced")
Endif

 

your stab it should manage not only parentheses

but also square brackets and braces

Nice shot BTW

Edited by Chimp

 

image.jpeg.9f1a974c98e9f77d824b358729b089b0.jpeg Chimp

small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

Link to comment
Share on other sites

You can use recursive regulare expressions.

Func AreParanthesisBalanced ($string)
    Static $parenthesis = "(?:\((?P>brackets)\))"
    Static $brace = "(?:\{(?P>brackets)\})"
    Static $bracket = "(?:\[(?P>brackets)\])"
    Static $nonBracket = "(?:[^(){}\[\]])"
    Static $brackets = "(?<brackets>(" & $parenthesis & "|" & $brace & "|" & $bracket & "|" & $nonBracket & ")*)"
    Static $regex = "^" & $brackets & "$"
    Return StringRegExp ($string, $regex)
EndFunc

 

HAAAAAA!!   :blink:

..... no comments .....

Edited by Chimp

 

image.jpeg.9f1a974c98e9f77d824b358729b089b0.jpeg Chimp

small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

Link to comment
Share on other sites

  • Moderators

Neat, first I've seen the copy method on here.

Common sense plays a role in the basics of understanding AutoIt... If you're lacking in that, do us all a favor, and step away from the computer.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...