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.85 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.84 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.83 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.82 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.81 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.80 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.79 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.78 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.77 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.76 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.75 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.74 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.73 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.72 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.71 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.70 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.69 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.68 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.67 tracks/scala/exercises/book-store/example.scala
trackler-2.2.1.66 tracks/scala/exercises/book-store/example.scala