Avatar of nilvon9wo

nilvon9wo's solution

to Matching Brackets in the Scala Track

Published at Oct 19 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.

The Scala exercises assume an SBT project scheme. The exercise solution source should be placed within the exercise directory/src/main/scala. The exercise unit tests can be found within the exercise directory/src/test/scala.

To run the tests simply run the command sbt test in the exercise directory.

Please see the learning and installation pages if you need any help.

Source

Ginna Baker

Submitting Incomplete Solutions

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

MatchingBracketsTest.scala

import org.scalatest.{Matchers, FunSuite}

/** @version 1.3.0 */
class MatchingBracketsTest extends FunSuite with Matchers {

  test("paired square brackets") {
    MatchingBrackets.isPaired("[]") should be(true)
  }

  test("empty string") {
    pending
    MatchingBrackets.isPaired("") should be(true)
  }

  test("unpaired brackets") {
    pending
    MatchingBrackets.isPaired("[[") should be(false)
  }

  test("wrong ordered brackets") {
    pending
    MatchingBrackets.isPaired("}{") should be(false)
  }

  test("wrong closing bracket") {
    pending
    MatchingBrackets.isPaired("{]") should be(false)
  }

  test("paired with whitespace") {
    pending
    MatchingBrackets.isPaired("{ }") should be(true)
  }

  test("partially paired brackets") {
    pending
    MatchingBrackets.isPaired("{[])") should be(false)
  }

  test("simple nested brackets") {
    pending
    MatchingBrackets.isPaired("{[]}") should be(true)
  }

  test("several paired brackets") {
    pending
    MatchingBrackets.isPaired("{}[]") should be(true)
  }

  test("paired and nested brackets") {
    pending
    MatchingBrackets.isPaired("([{}({}[])])") should be(true)
  }

  test("unopened closing brackets") {
    pending
    MatchingBrackets.isPaired("{[)][]}") should be(false)
  }

  test("unpaired and nested brackets") {
    pending
    MatchingBrackets.isPaired("([{])") should be(false)
  }

  test("paired and wrong nested brackets") {
    pending
    MatchingBrackets.isPaired("[({]})") should be(false)
  }

  test("math expression") {
    pending
    MatchingBrackets.isPaired("(((185 + 223.85) * 15) - 543)/2") should be(true)
  }

  test("complex latex expression") {
    pending
    MatchingBrackets.isPaired(
      """\left(\begin{array}{cc} \frac{1}{3} & x\ \mathrm{e}^{x} &... x^2 \end{array}\right)""") should be(
      true)
  }
}
import CharacterRole.CharacterRole

import scala.collection.immutable.HashMap

object MatchingBrackets {
  val closersByOpeners: HashMap[Char, Char] = HashMap(
    '[' -> ']',
    '{' -> '}',
    '(' -> ')',
  )
  val all_openers: Set[Char] = closersByOpeners.keySet
  val all_closers: Set[Char] = closersByOpeners.values.toSet

  @scala.annotation.tailrec
  def isPaired(string: String = "", openers: List[Char] = Nil): Boolean
  = this.evaluateFirstCharacter(string) match {
    case CharacterRole.None =>
      openers.isEmpty

    case CharacterRole.Opener =>
      this.isPaired(string.substring(1), string.charAt(0) :: openers)

    case CharacterRole.Closer =>
      if (openers.nonEmpty && isMatchingHead(string, openers)) {
        isPaired(string.substring(1), openers.tail)
      }
      else {
        false
      }

    case CharacterRole.Other =>
      this.isPaired(string.substring(1), openers)
  }

  private def evaluateFirstCharacter(string: String): CharacterRole
  = if (string.isBlank) {
    CharacterRole.None
  } else {
    evaluateFirstCharacter(string.charAt(0))
  }

  private def evaluateFirstCharacter(character: Character): CharacterRole
  = Cond(Seq(
    ( { () => this.all_openers.contains(character) }, { () => CharacterRole.Opener }),

    ( { () => this.all_closers.contains(character) }, { () => CharacterRole.Closer }),

    ( { () => true }, { () => CharacterRole.Other })
  ))

  private def isMatchingHead(string: String, openers: List[Char]): Boolean = {
    string.charAt(0) == this.closersByOpeners.getOrElse(openers.head, "")
  }
}

object CharacterRole extends Enumeration {
  type CharacterRole = Value
  val Opener, Closer, Other, None = Value
}

object Cond {
  def apply(clauses: Seq[(() => Boolean, () => CharacterRole)]): CharacterRole = {
    clauses find (_._1()) map (_._2()) getOrElse CharacterRole.None
  }
}

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?