Task:

 Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. 
 Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.


Examples

   (empty)      OK
   []           OK   
   [][]         OK   
   [[][]]       OK 
   ][         NOT OK
   ][][       NOT OK
   []][[]     NOT OK



' 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