Anonymous user
Balanced brackets: Difference between revisions
m
Re-ordered Tcl<>Python
m (Re-ordered Tcl<>Python) |
|||
Line 85:
Debug Balanced("[[][]]") ; #true
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}}==
Line 143 ⟶ 115:
'[[[]][]][][]][[]' is not balanced
'[[[[[][[[]][]]]]]]' 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>
|