Balanced brackets: Difference between revisions
Content added Content deleted
m (ββES6 Functional: Added semi-colon preferred by JSHint after 'use strict') |
(Added FreeBASIC) |
||
Line 2,416: | Line 2,416: | ||
end program balanced_brackets |
end program balanced_brackets |
||
</lang> |
</lang> |
||
=={{header|FreeBASIC}}== |
|||
<lang freebasic>' FB 1.05.0 Win64 |
|||
Function isBalanced(s As String) As Boolean |
|||
If s = "" Then Return True |
|||
Dim countLeft As Integer = 0 '' counts number of left brackets so far unmatched |
|||
Dim c As String |
|||
For i As Integer = 1 To Len(s) |
|||
c = Mid(s, i, 1) |
|||
If c = "[" Then |
|||
countLeft += 1 |
|||
ElseIf countLeft > 0 Then |
|||
countLeft -= 1 |
|||
Else |
|||
Return False |
|||
End If |
|||
Next |
|||
Return countLeft = 0 |
|||
End Function |
|||
' checking examples in task description |
|||
Dim brackets(1 To 7) As String = {"", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]"} |
|||
For i As Integer = 1 To 7 |
|||
Print IIf(brackets(i) <> "", brackets(i), "(empty)"); Tab(10); IIf(isBalanced(brackets(i)), "OK", "NOT OK") |
|||
Next |
|||
' checking 7 random strings of brackets of length 8 say |
|||
Randomize |
|||
Dim r As Integer '' 0 will signify "[" and 1 will signify "]" |
|||
Dim s As String |
|||
For i As Integer = 1 To 7 |
|||
s = Space(8) |
|||
For j As Integer = 1 To 8 |
|||
r = Int(Rnd * 2) |
|||
If r = 0 Then |
|||
Mid(s, j) = "[" |
|||
Else |
|||
Mid(s, j) = "]" |
|||
End If |
|||
Next j |
|||
Print s; Tab(10); IIf(isBalanced(s), "OK", "NOT OK") |
|||
Next i |
|||
Print |
|||
Print "Press any key to quit" |
|||
Sleep</lang> |
|||
Sample output (last 7 lines random) : |
|||
{{out}} |
|||
<pre> |
|||
(empty) OK |
|||
[] OK |
|||
][ NOT OK |
|||
[][] OK |
|||
][][ NOT OK |
|||
[[][]] OK |
|||
[]][[] NOT OK |
|||
][]][[[[ NOT OK |
|||
[]][][]] NOT OK |
|||
][][[[]] NOT OK |
|||
[[[[]]]] OK |
|||
[][[[[][ NOT OK |
|||
][[[]][] NOT OK |
|||
[][[[[][ NOT OK |
|||
</pre> |
|||
=={{header|GAP}}== |
=={{header|GAP}}== |