Sha256: d2185ba81f4b91f8990e4b60429a69bc961f6cd95c22722102466565234a5864

Contents?: true

Size: 1.38 KB

Versions: 140

Compression:

Stored size: 1.38 KB

Contents

object BookStore {
  private val bookPrice = 8
  private val discounts =
    Map((1, 0.0),
      (2, 5.0),
      (3, 10.0),
      (4, 20.0),
      (5, 25.0))

  def total(books: List[Int]): Double = total(books, 0)

  private def total(books: List[Int], acc: Double): Double = {
    if (books.isEmpty) {
      acc
    } else {
      val bookNums = books.distinct

      (1 to bookNums.size).foldLeft(Double.MaxValue)((minPrice, groupSize) => {
        val itemsToRemove = bookNums.take(groupSize)
        val remainingBooks = getRemainingBooks(books, itemsToRemove)
        val price = total(remainingBooks, acc + groupCost(groupSize))
        scala.math.min(price, minPrice)
      })
    }
  }

  private def groupCost(groupSize: Int): Double = {
    discounts get groupSize match {
      case Some(discount) => bookPrice * groupSize * (100.0 - discount) / 100.0
      case _ => bookPrice * groupSize
    }
  }

  private def getRemainingBooks(books: List[Int], itemsToRemove: List[Int]): List[Int] = {
    var remainingBooks = books

    for (item <- itemsToRemove) {
      remainingBooks = removeFirst(remainingBooks)(_ == item)
    }

    remainingBooks
  }

  // drops the first item in the passed in list that matches the predicate.
  private def removeFirst[T](list: List[T])(pred: (T) => Boolean): List[T] = {
    val (before, atAndAfter) = list span (x => !pred(x))
    before ::: atAndAfter.drop(1)
  }
}

Version data entries

140 entries across 140 versions & 1 rubygems

Version Path
trackler-2.2.1.105 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.104 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.103 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.102 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.101 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.100 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.99 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.98 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.97 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.96 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.95 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.94 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.93 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.92 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.91 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.90 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.89 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.88 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.87 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.86 tracks/scala/exercises/book-store/example.scala