🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉
Avatar of bkhl

bkhl's solution

to Matching Brackets in the D Track

Published at Aug 25 2019 · 0 comments
Instructions
Test suite
Solution

Given a string containing brackets [], braces {}, parentheses (), or any combination thereof, verify that any and all pairs are matched and nested correctly.

Getting Started

Make sure you have read D page on exercism.io. This covers the basic information on setting up the development environment expected by the exercises.

Passing the Tests

Get the first test compiling, linking and passing by following the three rules of test-driven development. Create just enough structure by declaring namespaces, functions, classes, etc., to satisfy any compiler errors and get the test to fail. Then write just enough code to get the test to pass. Once you've done that, uncomment the next test by moving the following line past the next test.

static if (all_tests_enabled)

This may result in compile errors as new constructs may be invoked that you haven't yet declared or defined. Again, fix the compile errors minimally to get a failing test, then change the code minimally to pass the test, refactor your implementation for readability and expressiveness and then go on to the next test.

Try to use standard D facilities in preference to writing your own low-level algorithms or facilities by hand. DRefLanguage and DReference are references to the D language and D standard library.

Source

Ginna Baker

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

matching_brackets.d

module matching_brackets;

unittest
{
    immutable int allTestsEnabled = 0;

    // Paired square brackets
    assert(isPaired("[]"));

    static if (allTestsEnabled)
    {
        // Empty string
        assert(isPaired(""));

        // Unpaired brackets
        assert(!isPaired("[["));

        // Wrong ordered brackets
        assert(!isPaired("}{"));

        // Wrong closing bracket
        assert(!isPaired("{]"));

        // Paired with whitespace
        assert(isPaired("{ }"));

        // Partially paired brackets
        assert(!isPaired("{[])"));

        // Simple nested brackets
        assert(isPaired("{[]}"));

        // Several paired brackets
        assert(isPaired("{}[]"));

        // Paired and nested brackets
        assert(isPaired("([{}({}[])])"));

        // Unopened closing brackets
        assert(!isPaired("{[)][]}"));

        // Unpaired and nested brackets
        assert(!isPaired("([{])"));

        // Paired and wrong nested brackets
        assert(!isPaired("[({]})"));

        // Paired and incomplete brackets
        assert(!isPaired("{}["));

        // Too many closing brackets
        assert(!isPaired("[]]"));

        // Math expression
        assert(isPaired("(((185 + 223.85) * 15) - 543)/2"));

        // Complex latex expression
        assert(isPaired(
                "\\left(\\begin{array}{cc} \\frac{1}{3} & x\\\\ \\mathrm{e}^{x} &... x^2 \\end{array}\\right)"));
    }
}
module matching_brackets;

import std.meta : aliasSeqOf;

immutable leftBrackets = "([{";
immutable rightBrackets = ")]}";

immutable bracketAliasSeq = aliasSeqOf!(leftBrackets ~ rightBrackets);
immutable leftBracketAliasSeq = aliasSeqOf!(leftBrackets);

bool isPaired(string input)
{
    import std.algorithm.comparison : among;
    import std.algorithm.iteration : filter;
    import std.range : empty;
    import std.string : indexOf;

    dchar[] stack;

    foreach (character; input.filter!(c => c.among(bracketAliasSeq)))
    {
        if (character.among(leftBracketAliasSeq))
            stack.assumeSafeAppend ~= rightBrackets[leftBrackets.indexOf(character)];
        else if (stack.empty)
            return false;
        else if (character == stack[$ - 1])
            stack.length = stack.length - 1;
        else
            return false;
    }

    return stack.empty;
}

unittest
{
    // Paired square brackets
    assert(isPaired("[]"));

    // Empty string
    assert(isPaired(""));

    // Unpaired brackets
    assert(!isPaired("[["));

    // Wrong ordered brackets
    assert(!isPaired("}{"));

    // Wrong closing bracket
    assert(!isPaired("{]"));

    // Paired with whitespace
    assert(isPaired("{ }"));

    // Partially paired brackets
    assert(!isPaired("{[])"));

    // Simple nested brackets
    assert(isPaired("{[]}"));

    // Several paired brackets
    assert(isPaired("{}[]"));

    // Paired and nested brackets
    assert(isPaired("([{}({}[])])"));

    // Unopened closing brackets
    assert(!isPaired("{[)][]}"));

    // Unpaired and nested brackets
    assert(!isPaired("([{])"));

    // Paired and wrong nested brackets
    assert(!isPaired("[({]})"));

    // Paired and incomplete brackets
    assert(!isPaired("{}["));

    // Too many closing brackets
    assert(!isPaired("[]]"));

    // Math expression
    assert(isPaired("(((185 + 223.85) * 15) - 543)/2"));

    // Complex latex expression
    assert(isPaired(
            "\\left(\\begin{array}{cc} \\frac{1}{3} & x\\\\ \\mathrm{e}^{x} &... x^2 \\end{array}\\right)"));
}

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?