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



BEGIN
    INTEGER U;
    U := ININT;
    BEGIN
 
        TEXT PROCEDURE GENERATE(N); INTEGER N;
        BEGIN
            INTEGER R;
            TEXT T;
            T :- NOTEXT;
            WHILE N > 0 DO BEGIN
                R := RANDINT(1,2,U);
                T :- T & (IF R = 1 THEN "[" ELSE "]");
                N := N - 1;
            END;
            GENERATE :- T;
        END GENERATE;
 
        BOOLEAN PROCEDURE BALANCED(T); TEXT T;
        BEGIN
            INTEGER LEVEL;
            CHARACTER BRACE;
            BOOLEAN DONE;
            T.SETPOS(1);
            WHILE T.MORE AND NOT DONE DO BEGIN
                BRACE := T.GETCHAR;
                IF BRACE = '[' THEN LEVEL := LEVEL + 1;
                IF BRACE = ']' THEN LEVEL := LEVEL - 1;
                IF LEVEL < 0 THEN DONE := TRUE;
            END;
            BALANCED := LEVEL = 0;
        END BALANCED;
 
        INTEGER I,M;
        TEXT T;
        FOR I := 1 STEP 1 UNTIL 40 DO BEGIN
            M := RANDINT(0,10,U);
            T :- GENERATE(M);
            IF BALANCED(T) THEN OUTTEXT("    ") ELSE OUTTEXT(" NOT");
            OUTTEXT(" BALANCED: ");
            OUTTEXT(T);
            OUTIMAGE;
        END;
 
    END;
END