Skip to content
loading...

re: Daily Challenge #137 - Help the Bookseller VIEW POST

TOP OF THREAD FULL DISCUSSION
re: Scala object Bookstore { case class Book(code: String, val quantity: Int) { val category = code.head } case class Category(code: Char,...
 

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 " - "
  }
}
code of conduct - report abuse