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



% This program needs the random number generator from
% "misc.lib" that comes with PCLU.
 
shuffle = proc [T: type] (a: array[t]) 
    aT = array[t]
    for i: int in int$from_to_by(aT$size(a)-1,0,-1) do
        x: int := aT$low(a) + i
        y: int := aT$low(a) + random$next(i+1)
        temp: T := a[x]
        a[x] := a[y]
        a[y] := temp
    end
end shuffle
 
brackets = proc (n: int) returns (string)
    br: array[char] := array[char]$[]
    for i: int in int$from_to(1,2*n) do
        if i<=n then array[char]$addh(br, '[')
        else array[char]$addh(br, ']')
        end
    end
    shuffle[char](br)
    return(string$ac2s(br))
end brackets
 
balanced = proc (br: string) returns (bool)
    depth: int := 0
    for c: char in string$chars(br) do
        if     c='[' then depth := depth + 1
        elseif c=']' then depth := depth - 1
        end
        if depth<0 then return(false) end
    end
    return(depth = 0)
end balanced
 
start_up = proc ()
    po: stream := stream$primary_output()
    d: date := now()
    random$seed(d.second + 60*(d.minute + 60*d.hour))
 
    for size: int in int$from_to(0, 10) do
        b: string := brackets(size)
        stream$puts(po, "\"" || b || "\": ")
        if balanced(b) then
            stream$putl(po, "balanced")
        else
            stream$putl(po, "not balanced")
        end
    end
end start_up