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



include c:\cxpl\codes;       \intrinsic code declarations
 
int     N, I, C, Nest;
char    Str;
[\Generate a string with N open brackets and N close brackets in arbitrary order
N:= IntIn(0);                           \get number of brackets/2 from keyboard
Str:= Reserve(2*N);
for I:= 0 to 2*N-1 do Str(I):= ^[;
C:= 0;                                  \initialize count of "]"
repeat  I:= Ran(2*N);                   \change N random locations to "]"
        if Str(I) # ^] then [Str(I):= ^]; C:= C+1];
until   C>=N;
 
\Determine whether string consists of nested pairs of open/close brackets
I:= 0;  C:= 0;  Nest:= false;
while I<2*N do
        [if Str(I) = ^[ then C:= C+1 else C:= C-1;
        if C<0 then Nest:= true;
        ChOut(0,Str(I));
        I:= I+1;
        ];
ChOut(0,9\tab\);
if Nest then Text(0,"NOT ");
Text(0,"OK
");
]