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.45 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.44 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.43 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.42 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.41 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.40 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.39 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.38 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.37 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.36 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.35 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.34 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.33 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.32 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.31 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.30 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.29 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.28 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.27 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.26 tracks/scala/exercises/book-store/example.scala