DEV Community

loading...

Discussion on: Daily Challenge #137 - Help the Bookseller

Collapse
avalander profile image
Avalander

I was under a strong sleep deprivation when I wrote that solution, I think it can be done in a simpler way:

object Bookstore2 {
  type Book = (Char, Int)

  def parseBook (s: String): Book = {
    val Array(c, q) = s.split(' ')
    (c.head, q.toInt)
  }

  def countBooks (books: Seq[Book]): Int = {
    (books map (_._2)).sum
  }

  def solve (cat: Seq[String], stock: Seq[String]): String = {
    val stocklist = stock map parseBook groupBy (_._1) mapValues countBooks
    val cats = for {
      c <- cat
      q = stocklist.getOrElse(c.head, 0)
    } yield s"($c : $q)"
    cats mkString " - "
  }
}