RosettaCodeData/Task/Balanced-brackets/Pluto/balanced-brackets.pluto

37 lines
983 B
Plaintext

local function is_balanced(s)
if s == "" then
return true
end
local counter_left = 0 -- number of left brackets so far unmatched
for i = 1, #s do
local c = s[i]
if c == "[" then
counter_left += 1
elseif counter_left > 0 do
counter_left -= 1
else
return false
end
end
return counter_left == 0
end
print("Checking examples in task description:")
local brackets = {"", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]"}
for brackets as b do
local res = is_balanced(b)
local bb = (b != "") ? b : "(empty)"
print(string.format("%-8s %s", bb, res ? "OK" : "NOT OK"))
end
print("\nChecking 7 random strings of brackets of length 8:")
math.randomseed(os.time())
for i = 1, 7 do
local b = ""
for j = 1, 8 do
b ..= (math.random(0, 1) == 0) ? "[" : "]"
end
local res = is_balanced(b)
print(string.format("%s %s", b, res ? "OK" : "NOT OK"))
end