Balanced brackets: Difference between revisions

Content added Content deleted
m (Re-ordered Tcl<>Python)
Line 85: Line 85:
Debug Balanced("[[][]]") ; #true
Debug Balanced("[[][]]") ; #true
Debug Balanced("[]][[]") ; #false</lang>
Debug Balanced("[]][[]") ; #false</lang>

=={{header|Tcl}}==
{{incomplete|Tcl|Strings are not generated.}}
<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}}==
=={{header|Python}}==
Line 143: Line 115:
'[[[]][]][][]][[]' is not balanced
'[[[]][]][][]][[]' is not balanced
'[[[[[][[[]][]]]]]]' is balanced</lang>
'[[[[[][[[]][]]]]]]' is balanced</lang>

=={{header|Tcl}}==
{{incomplete|Tcl|Strings are not generated.}}
<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>