Solution to a recursive problem (code kata)

Source code

// str is the string that's been built so far.
// limit is the total number of bracket pairs
//
// e.g. initial call: brackets('', 3)
function brackets(str, limit)
{
    // rules
    //
    // if brackets in str balance (includes empty str), must
    //   have open bracket
    // if all open bracket used, must have close bracket 
    // otherwise, can have either bracket

    if (str.length == 2 * limit)
    {
        return str;
    }

    var open = close = 0;

    for (i = 0; i < str.length; i++)
    {
        if (str[i] == '(')
        {
            open++;
        }
        else if (str[i] == ')')
        {
            close++;
        }
    }

    if (open == close)
    {
        return brackets(str + '(', limit);
    }
    else if (open == limit)
    {
        return brackets(str + ')', limit);
    }
    else
    {
        return new Array(brackets(str + '(', limit),
                         brackets(str + ')', limit));
    }

Tweet

Comments

Fri 12 Dec 2014 11:27

much does cialis cost

much does cialis cost said:

I am regular visitor, how are you everybody?

This post posted at this website is really

fastidious.

Sat 13 Dec 2014 18:02

canada cialis generic

canada cialis generic said:

Hi there, You have done a fantastic job. I’ll certainly digg it and personally

suggest to my friends. I’m sure they will be benefited from this

web site.

Tue 16 Dec 2014 13:57

buying cialis online canada

buying cialis online canada said:

My brother suggested I may like this website. He was totally right.

This submit truly made my day. You can not believe just how so much time I had spent for this info!

Thanks!

Tue 16 Dec 2014 19:09

cialis generic pharmacy

cialis generic pharmacy said:

When someone writes an piece of writing he/she maintains the plan of a

user in his/her brain that how a user can understand it. Therefore that’s why this post is amazing.

Thanks!

Thu 18 Dec 2014 09:35

canadian cialis

canadian cialis said:

You really make it appear really easy along with your presentation however I find this matter to be really something that I believe I’d never understand.

It seems too complex and very extensive for me. I’m taking a look ahead

to your next publish, I will attempt to get the cling of it!

Leave a comment