RosettaCodeData/Task/Balanced-brackets/XPL0/balanced-brackets.xpl0

27 lines
836 B
Plaintext

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
");
]