---
# System prepended metadata

title: Lecture 27 Setup/Prep
tags: [Setup]

---

---
tags: Setup
---

# Lecture 27 Setup/Prep

We're going to try the optimization from last class on a problem that involves searching for an optimal solution within a constrained setting.

## Prep

Familiarize yourself with the following problem:

Imagine that a cafe offers multiple flavors of sweets (be they macarons, burfi, mochi, etc). Here's a sample ordering of flavors within the display case:

| Chocolate | Strawberry | Vanilla | Pistachio | Raspberry |
| -------- | -------- | -------- | ------- | ------ |

The shop owner has an odd quirk: they won't sell adjacent flavors in the same order. For example, a customer could *not* get both a strawberry and vanilla sweet from this cafe.

Users of a restaurant-review site have rated the various flavors based on tastiness. The flavors in the display case above have ratings (scale 1-20) of 3, 10, 12, 16, and 4, respectively.

You are going to this cafe for the first time, and want to maximize the total (summed) rating for the sweets that you purchase.

- which combinations of flavors could you purchase under the no-adjacent-flavor rule?
- which would give the highest total rating?
- how might you search for the highest total rating without naively generating all possible combinations and searching through the list?

::: spoiler The code (when we are ready for it)
``` =java
class Macaron(val ratings: Array[Int]) {
  // The input is the array of ratings -- this is part of
  // the original data, not the array that we create
  // to optimize performance

  /**
   * Finds the optimal rating sublist of the Macarons.
   *
   * @param i - an int between 0 and the number of Macarons minus 1
   * @return the max total rating that can be achieved using Macarons up to index i
   */
  def maxRec(i: Int): Int =
    if (i == 0)
      this.ratings(0)
    else if (i == 1)
      if (this.ratings(0) > this.ratings(1))
        this.ratings(0)
      else this.ratings(1)
    else {
      val twoAgo = maxRec(i - 2)
      val oneAgo = maxRec(i - 1)
      if (oneAgo > (twoAgo + this.ratings(i)))
        oneAgo
      else twoAgo + this.ratings(i)
    }

  def maxRating = maxRec(ratings.size-1)
}

object Main extends App {
  // val ratings = HashMap("Chocolate" -> 3, "Strawberry" -> 10, "Vanilla" -> 12, "Pistachio" -> 16, "Raspberry" -> 4)
  print(new Macaron(Array(3, 10, 12, 16, 4)).maxRating + " should be 26")
  ```
:::