Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Anyone know the answer to this great code excercise?

I came across this code excercise for Javascript:

Given an array of strings containing three types of braces: round (), square [] and curly {} Your task is to write a function that checks whether the braces in each string are correctly matched. Prints 1 to standard output (console.log) if the braces in each string are matched and 0 if they're not (one result per line)

Note that your function will receive the following arguments: expressions

which is an array of strings containing braces

Data constraints: the length of the array will not exceed 100 the length of any string will not exceed 5000

Efficiency constraints: Your function is expected to print the result in less than 2 seconds

Input: expressions: [ ")(){}", "[]({})", "([])", "{()[]}", "([)]" ] Output: 0 1 1 1 0

1 Answer

Hi Mike, this is indeed a great exercise, I like it, It's at least for me challenging. I actually think the best way to approach this, to solve this is using a regular expression which would check each pattern. I've tried to create a regular expression on my own that would match some others similar cases, to create a generic solution, but I failed to do that... :( Quite frustrating, even If I've been learning Regex lately, I'm not yet good with it :/.

So I finally created a regular expression which validates all the datas you showed in the example you give, which is not really the right solution I guess...

Here is the js fiddle

var infoToParse = [ ")(){}", "[]({})", "([])", "{()[]}", "([)]" ]; //Output: 0 1 1 1 0


function checkBraces(infoToParse) {
    var tabChars = infoToParse;
    for(var individual in tabChars){
        if(tabChars[individual].match(/\[]\({}\)|\(\[]\)|{\(\)\[]}/g)){
         console.log(1);   
        }else{
         console.log(0);   
        }
    }
}

checkBraces(infoToParse);

I'm going to follow that post and hope to see a better solution. From where this exercise comes from please ?

Thanks for replying geoffrey. Good answer, I was thinking regex as well. I got it from a github code challenge but the answer was done in ruby there. https://github.com/sealocal/code-challenges/blob/master/check_for_matched_braces.rb