Skip to content
loading...

re: Daily Challenge #187 - Most Sales VIEW POST

FULL DISCUSSION
 

Scala

object MostSales {
  private implicit val order = Ordering.Int.reverse

  private val total = (x: ((Int, Int), String)) => x match {
    case ((a, p), n) => (n, a * p)
  }

  def findHighest (names: Seq[String], amounts: Seq[Int], prices: Seq[Int]): Seq[String] = {
    val sorted = amounts zip prices zip names map total sortBy (_._2)
    val result = sorted takeWhile (_._2 == sorted.head._2)
    result map (_._1)
  }
}

And some tests

import org.scalatest._

class MostSalesTest extends FunSuite {
  import MostSales._

  test("Case 1") {
    val products = List("Computer", "Cell Phones", "Vacuum Cleaner")
    val amounts = List(3, 24, 8)
    val prices = List(199, 299, 399)

    val result = findHighest(products, amounts, prices)
    assert(result == List("Cell Phones"))
  }

  test("Case 2") {
    val products = List("Cell Phones", "Vacuum Cleaner", "Computer", "Autos", "Gold", "Fishing Rods", "Lego", " Speakers")
    val amounts = List(0, 12, 24, 17, 19, 23, 120, 8)
    val prices = List(9, 24, 29, 31, 51, 8, 120, 14)

    val result = findHighest(products, amounts, prices)
    assert(result == List("Lego"))
  }

  test("Returns multiple results") {
    val products = List("Computer", "Cell Phones", "Vacuum Cleaner")
    val amounts = List(3, 2, 6)
    val prices = List(200, 299, 100)

    val result = findHighest(products, amounts, prices)
    assert(result == List("Computer", "Vacuum Cleaner"))
  }
}
code of conduct - report abuse