Jump to content

Balanced brackets: Difference between revisions

→‎Tcl: Added implementation
(→‎{{header|PureBasic}}: Marked incomplete as strings are not generated)
(→‎Tcl: Added implementation)
Line 70:
Debug Balanced("[[][]]") ; #true
Debug Balanced("[]][[]") ; #false</lang>
 
=={{header|Tcl}}==
<lang tcl>proc balanced s {
set n 0
foreach c [split $s ""] {
# Everything unmatched is ignored, which is what we want
switch -exact -- $c {
"\[" {incr n}
"\]" {if {[incr n -1] < 0} {return false}}
}
}
expr {!$n}
}</lang>
Demonstration code:
<lang tcl>foreach s {"" "[]" "][" "[][]" "][][" "[[][]]" "[]][[]"} {
puts "$s\t-> [expr {[balanced $s] ? {OK} : {NOT OK}}]"
}</lang>
Output:
<pre>
-> OK
[] -> OK
][ -> NOT OK
[][] -> OK
][][ -> NOT OK
[[][]] -> OK
[]][[] -> NOT OK
</pre>
 
=={{header|Python}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.