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.1.0.48 tracks/scala/exercises/book-store/example.scala
trackler-2.1.0.47 tracks/scala/exercises/book-store/example.scala
trackler-2.1.0.46 tracks/scala/exercises/book-store/example.scala
trackler-2.1.0.45 tracks/scala/exercises/book-store/example.scala
trackler-2.1.0.44 tracks/scala/exercises/book-store/example.scala
trackler-2.1.0.43 tracks/scala/exercises/book-store/example.scala
trackler-2.1.0.42 tracks/scala/exercises/book-store/example.scala
trackler-2.1.0.41 tracks/scala/exercises/book-store/example.scala
trackler-2.1.0.40 tracks/scala/exercises/book-store/example.scala
trackler-2.1.0.39 tracks/scala/exercises/book-store/example.scala
trackler-2.1.0.38 tracks/scala/exercises/book-store/example.scala
trackler-2.1.0.37 tracks/scala/exercises/book-store/example.scala
trackler-2.1.0.36 tracks/scala/exercises/book-store/example.scala
trackler-2.1.0.34 tracks/scala/exercises/book-store/example.scala
trackler-2.1.0.33 tracks/scala/exercises/book-store/example.scala
trackler-2.1.0.32 tracks/scala/exercises/book-store/example.scala
trackler-2.1.0.31 tracks/scala/exercises/book-store/example.scala
trackler-2.1.0.30 tracks/scala/exercises/book-store/example.scala
trackler-2.1.0.29 tracks/scala/exercises/book-store/example.scala
trackler-2.1.0.28 tracks/scala/exercises/book-store/example.scala