Avatar of Ric0chet

Ric0chet's solution

to Acronym in the Scala Track

Published at Oct 14 2019 · 1 comment
Instructions
Test suite
Solution

Convert a phrase to its acronym.

Techies love their TLA (Three Letter Acronyms)!

Help generate some jargon by writing a program that converts a long name like Portable Network Graphics to its acronym (PNG).

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

Julien Vanier https://github.com/monkbroc

Submitting Incomplete Solutions

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

AcronymTest.scala

import org.scalatest.{Matchers, FunSuite}

/** @version 1.6.0 */
class AcronymTest extends FunSuite with Matchers {

  test("basic") {
    Acronym.abbreviate("Portable Network Graphics") should be ("PNG")
  }

  test("lowercase words") {
    pending
    Acronym.abbreviate("Ruby on Rails") should be ("ROR")
  }

  test("punctuation") {
    pending
    Acronym.abbreviate("First In, First Out") should be ("FIFO")
  }

  test("all caps word") {
    pending
    Acronym.abbreviate("GNU Image Manipulation Program") should be ("GIMP")
  }

  test("punctuation without whitespace") {
    pending
    Acronym.abbreviate("Complementary metal-oxide semiconductor") should be ("CMOS")
  }

  test("very long abbreviation") {
    pending
    Acronym.abbreviate("Rolling On The Floor Laughing So Hard That My Dogs Came Over And Licked Me") should be ("ROTFLSHTMDCOALM")
  }

  test("consecutive delimiters") {
    pending
    Acronym.abbreviate("Something - I made up from thin air") should be ("SIMUFTA")
  }

  test("apostrophes") {
    pending
    Acronym.abbreviate("Halley's Comet") should be ("HC")
  }
}
//  10-14-19

object Acronym {
  def abbreviate(phrase: String): String =
    usingMapping(phrase)
//    usingFolding(phrase)

  // 41 ms
  private def usingMapping(phrase: String): String =
    phrase.split("[- ]")
      .filterNot { _.isEmpty }
      .map { _(0).toUpper }  // faster than { _.head.toUpper }
      .mkString("")

  // 40 ms
  private def usingFolding(phrase: String): String =
    phrase.split("[- ]").foldLeft("") { (acc, word) =>
      if (!word.isEmpty) acc + word(0).toUpper
      else acc
    }

}

Community comments

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

I also found (on this machine, at least) word(0) is measurably faster than word.head, possibly due to traversal.

Ric0chet's Reflection

Includes two solutions for benchmark comparison (mapping vs. folding). Both are lambda expressions with essentially identical times.