Search code examples
scala

How to perform calculation based on ratio condition in scala


I'm attempting to learn scala and came across a problem to solve. I have an input which is a map of items: Map(Apples -> 3, Soup -> 2, Bread -> 2). I'm finding the last bit of the problem a bit tricky.

How do I calculate the total cost of bread, given that it's normal price is 0.8 but for every 2 soups, 1 bread cost 0.5.

So for example:

val prices: Map[String, Double] = Map(
    "Soup" -> 0.65,
    "Bread" -> 0.80,
    "Milk" -> 1.30,
    "Apples" -> 1.00
)

itemCounts = Map(Apples -> 3, Soup -> 2, Bread -> 2) // the input

applesTotal = 3 // (1*3)
soupTotal = 1.3 // (0.65*2)
breadTotal = 1.3 // (0.8 + (0.5*1)) - given that for every 2 soups 1 bread cost 0.5
total = 5.6

So far my code is:

    // Get bread discount
    val soupCount = itemCounts.getOrElse("Soup", 0)
    val breadCount = itemCounts.getOrElse("Bread", 0)

    val breadPrice = prices.getOrElse("Bread", 0.0)
    val breadDiscount = 0.5

    // Where I need to adjust the code
    if (soupCount / breadCount.toDouble == 2.0/1.0) {
      val breadPrice = prices.getOrElse("Bread", 0.0)
      val adjustedBreadPrice = breadPrice + 0.5
      println(s"The cost of bread is: ${breadCount * adjustedBreadPrice}")
    }

I thought I could try and do this by checking if the ratio of soup:bread is 2:1 but this doesn't seem to be the right way forward. Because if there is 4 soups and 3 breads, that is not getting covered by the condition and the correct value would be 4.4 - (0.65 x 4 + (0.5 x 2) + 0.8)


Solution

    1. How much total bread?
      val bread = itemCounts.getOrElse("Bread", 0)
      
    2. What part of it is discounted?
      val discounted = itemCounts.getOrElse("Soup", 0).map(_ /2) min bread
      
    3. What's left?
      val remaining = (bread - discounted) max 0
      
    4. What's the total price?
      val breadPrice = remaining * prices.getOrElse("Bread", 0) + discounted*0.5