Menu
Coddy logo textTech

What To Buy

Part of the Fundamentals section of Coddy's Swift journey — lesson 86 of 86.

challenge icon

Challenge

Easy
Write a function whatToBuy that takes itemNames, itemPrices, and budget and returns an array of item names that can be purchased within the budget.

Iterate through the items in order. For each item, check if adding its price to your running total would stay within budget. If so, add the item name to your shopping list and update the total. If an item would exceed the budget, skip it and continue checking the remaining items.

Logic:

  1. Start with a running total of 0.0 and an empty result array
  2. Loop through each item by index
  3. If the running total plus the current item's price is less than or equal to the budget, add the item name to the result and update the running total
  4. If adding the item would exceed the budget, skip it and continue to the next item
  5. Return the array of affordable item names

Parameters:

  • itemNames ([String]): Array of item names
  • itemPrices ([Double]): Array of corresponding prices (same length as itemNames)
  • budget (Double): The maximum amount that can be spent

Returns: An array of item names that can be afforded within the budget, in the order they appear ([String])

Example:

// itemNames: ["Apple", "Bread", "Milk"]
// itemPrices: [2.0, 3.5, 4.0]
// budget: 6.0
// Result: ["Apple", "Bread"]
// (Apple costs 2.0, Bread costs 3.5, total is 5.5 which is within budget)
// (Milk would make total 9.5, which exceeds 6.0, so it's skipped)

Try it yourself

func whatToBuy(itemNames: [String], itemPrices: [Double], budget: Double) -> [String] {
    // Write code here
}

All lessons in Fundamentals