|
Post by Josh on May 14, 2017 17:48:11 GMT
BracketsIn this puzzle, you will be given the string "()()(()())())(()". You must output true if the brackets are correctly paired and nested. If they are not, you must output false. With this string, your program should output false as they are not correctly paired and nested. Your solution must work with any string, therefore your solution must not be hardcoded. The string will only contain brackets.
Feel free to golf your solution. If you do so, please make sure that you tell us the amount of characters in your solution. Make sure that you tell us the language that your program is written in regardless.
Good luck!
|
|
|
Post by Bit on May 14, 2017 20:04:14 GMT
RBX.Lua, non-golfed. Also ignores anything that isn't a ( or ), just for convenience.
ParensArrangedProperly=function(st) local st=st if not st or typeof(st)~="string" then error("Please supply a string.",2) end --Make sure we are working with a string! st=st:gsub("[^%(%)]","") --We just want the following: "(",")". Anything else is removed. if #st<1 then error("Supplied string does not contain atleast one valid character.",2) --Make sure it is long 'nuff. end local state=0 --0=good,1=opened,-1=closed, must be 0 in order to be valid. for i=1,#st do --Pattern applied already, so who needs to do anything but search for each character. local c=st:sub(i,i) if c=="(" then if state>=0 then state=state+1 end elseif c==")" then if state<=0 then return false --Attempted to close too early. else state=state-1 end end end if state>0 then return false --Forgot to close end return true --All good. end print(ParensArrangedProperly("()()(()())())(()")) -->false
|
|
|
Post by Josh on May 14, 2017 20:46:26 GMT
Looks good Bit, thanks for the contribution.
|
|
chimmihc
New Member
Veteran
Posts: 8
ROBLOX Username: chimmihc
|
Post by chimmihc on May 14, 2017 22:03:41 GMT
Lua.
local function matched(str) local found = 0
for ch in str:gmatch("[()]") do if ch == '(' then found = found + 1 else if found == 0 then return false end
found = found - 1 end end
return found == 0 end
print(matched("()()(()())())(()"))
|
|
|
Post by Josh on May 14, 2017 22:10:33 GMT
|
|
|
Post by disillusions on May 15, 2017 9:18:34 GMT
lua golfed I guess
Edit: misunderstood the task a little bit, this only works for direct "()" pairs
function c(t)for i=1,#t,2 do if t:sub(i,i+1)~='()'then return false end end return true end
|
|
|
Post by goulstem on May 16, 2017 21:42:19 GMT
Lua, 85 chars.
function m(s)a=0;for i=1,#s do b=s:sub(i,i)a=b=="("and a+1 or a-1 end return a==0 end
print(m("(()())")); -->true
print(m("((((")); --> false
|
|
|
Post by AxonMega on Jun 27, 2017 12:00:12 GMT
def m(s)l=0;s.each_char{|c|l+=if c=="(";1 else -1 end;if l>0;false end};l==0 end
Ruby, 80 characters. Ruby is turning out to be great for code golf.
|
|