RosettaCodeData/Task/Balanced-brackets/Liberty-BASIC/balanced-brackets.basic

63 lines
1.5 KiB
Plaintext

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