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



 
print "Supplied examples"
for i =1 to 7
    read test$
    print "The string '"; test$; "' is "; validString$( test$)
next i
print
data "", "[]", "][","[][]","][][","[[][]]","[]][[]"
 
print "Random generated examples"
for example =1 to 10
    test$ =generate$( int( 1 +10 *rnd(1)))
    print "The string '"; test$; "' is "; validString$( test$)
next example
end
 
function validString$( in$)
    if left$( in$, 1) <>"[" and len( test$) <>0 then
        validString$ ="not OK. Opens wrongly."
        exit function
    end if
    paired =0
    for i =1 to len( in$)
        c$ =mid$( in$, i, 1)
        if c$ ="[" then paired =paired +1
        if c$ ="]" then paired =paired -1
        if paired <0 then
            exit for
        end if
    next i
    if ( lBr =rBr) and ( paired >=0) then validString$ ="OK." else validString$ ="not OK. Unbalanced."
end function
 
function generate$( N)
    lBr =0
    rBr =0
    '   choose at random until N of one type generated
    while ( lBr <N) and ( rBr <N)
        select case int( 1.5 +rnd( 1))
            case 1
                lBr =lBr +1
                generate$ =generate$ +"["
            case 2
                rBr =rBr +1
                generate$ =generate$ +"]"
        end select
    wend
    '   now pad with the remaining other brackets
    if lBr =N then
        generate$ =generate$ +string$( N -rBr, "]")
    else
        generate$ =generate$ +string$( N -lBr, "[")
    end if
end function
 
function string$( n, c$)
    for i =1 to n
        op$ =op$ +c$
    next i
    string$ =op$
end function
 
end
 