DEV Community

Discussion on: Daily Challenge #51 - Valid Curly Braces

Collapse
 
ynndvn profile image
La blatte • Edited

Here we go!

f=a=>{c=0;i=0;while(i<a.length&&c>=0){c+=a[i]=='{'?1:-1;++i}return !c}

Read character by character, add 1 to a counter if the character is an opening bracket, subtract 1 if it is a closing one. If the counter EVER gets negative (hence, if we get in an "open close close" situation) of if it is positive on the last iteration (hence, if we get in an "open open close" situation), we consider the chain as invalid.

f("{{{}{}}}")
true
f("{{")
false
f("{}}")
false
f("")
true
f("}{")
false
Collapse
 
alfredosalzillo profile image
Alfredo Salzillo

Why you post the uglified code?

Collapse
 
ynndvn profile image
La blatte

I just try to find a really short working solution, hence the uglified code! That's why I try to explain it as much as I can after that

Thread Thread
 
aminnairi profile image
Amin

I think that these kind of challenges prior more the algorithm part than the gulfing part. Since ES6, JavaScript has became a good language for gulfing but sometimes self explanatory code is better than gulfed one.

Its a matter of taste I guess.

Thread Thread
 
ynndvn profile image
La blatte

Exactly! As a matter of fact, I prefer Alfredo Salzillo's solution as it is a clear and pretty oneliner. On these challenges I try to come up with solutions different than a straight-forward approach (and tend to golf it too), which I couldn't manage to do on this one. That explains the ugly part of the solution I provided, which is kinda disappointing!