Avatar of davearonson

davearonson's solution

to Matching Brackets in the Elixir Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

Bracket Push

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

Running tests

Execute the tests with:

$ elixir bracket_push_test.exs

Pending tests

In the test suites, all but the first test have been skipped.

Once you get a test passing, you can unskip the next one by commenting out the relevant @tag :pending with a # symbol.

For example:

# @tag :pending
test "shouting" do
  assert Bob.hey("WATCH OUT!") == "Whoa, chill out!"
end

Or, you can enable all the tests by commenting out the ExUnit.configure line in the test suite.

# ExUnit.configure exclude: :pending, trace: true

For more detailed information about the Elixir track, please see the help page.

Source

Ginna Baker

Submitting Incomplete Solutions

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

bracket_push_test.exs

if !System.get_env("EXERCISM_TEST_EXAMPLES") do
  Code.load_file("bracket_push.exs", __DIR__)
end

ExUnit.start()
ExUnit.configure(exclude: :pending, trace: true)

defmodule BracketPushTest do
  use ExUnit.Case

  # @tag :pending
  test "paired square brackets" do
    assert BracketPush.check_brackets("[]")
  end

  @tag :pending
  test "empty string" do
    assert BracketPush.check_brackets("")
  end

  @tag :pending
  test "unpaired brackets" do
    refute BracketPush.check_brackets("[[")
  end

  @tag :pending
  test "wrong ordered brackets" do
    refute BracketPush.check_brackets("}{")
  end

  @tag :pending
  test "wrong closing bracket" do
    refute BracketPush.check_brackets("{]")
  end

  @tag :pending
  test "paired with whitespace" do
    assert BracketPush.check_brackets("{ }")
  end

  @tag :pending
  test "simple nested brackets" do
    assert BracketPush.check_brackets("{[]}")
  end

  @tag :pending
  test "several paired brackets" do
    assert BracketPush.check_brackets("{}[]")
  end

  @tag :pending
  test "paired and nested brackets" do
    assert BracketPush.check_brackets("([{}({}[])])")
  end

  @tag :pending
  test "unopened closing brackets" do
    refute BracketPush.check_brackets("{[)][]}")
  end

  @tag :pending
  test "unpaired and nested brackets" do
    refute BracketPush.check_brackets("([{])")
  end

  @tag :pending
  test "paired and wrong nested brackets" do
    refute BracketPush.check_brackets("[({]})")
  end

  @tag :pending
  test "math expression" do
    assert BracketPush.check_brackets("(((185 + 223.85) * 15) - 543)/2")
  end

  @tag :pending
  test "complex latex expression" do
    assert BracketPush.check_brackets(
             "\\left(\\begin{array}{cc} \\frac{1}{3} & x\\\\ \\mathrm{e}^{x} &... x^2 \\end{array}\\right)"
           )
  end
end
defmodule BracketPush do
  @doc """
  Checks that all the brackets and braces in the string are matched correctly, and nested correctly
  """
  @spec check_brackets(String.t) :: boolean
  def check_brackets(str) do
    do_check_brackets [],
                      (str |> String.split("", trim: true)
                           |> Enum.filter(&is_bracket?/1))
  end

  defp do_check_brackets(stack, []), do: Enum.empty? stack

  defp do_check_brackets([], [next_char | rest]) do
    do_check_brackets [next_char], rest
  end

  defp do_check_brackets([prior_char | more_stack],
                         [this_char  | more_chars]) do
    cond do
      is_match?(prior_char, this_char) ->
        do_check_brackets more_stack, more_chars
      is_opener?(prior_char) && is_closer?(this_char) ->
        false
      true ->
        do_check_brackets [this_char | [prior_char | more_stack]], more_chars
    end
  end

  @openers  "([{"
  @closers  "}])"  # does not need to align with openers; we sort when needed
  @brackets "#{@openers}#{@closers}"
  @pairs    @brackets |> String.split("", trim: true)
                      |> Enum.sort
                      |> Enum.chunk(2)
                      |> Enum.map(&Enum.join/1)

  defp is_bracket?(char), do: String.contains?(@brackets, char)

  defp is_match?(prior_char, this_char) do
    Enum.member?(@pairs, "#{prior_char}#{this_char}")
  end

  defp is_opener?(char), do: String.contains?(@openers, char)

  defp is_closer?(char), do: String.contains?(@closers, char)

end

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?