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

Leave a comment