What To Buy
Part of the Fundamentals section of Coddy's Swift journey — lesson 86 of 86.
Challenge
EasyWrite 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:
- Start with a running total of
0.0and an empty result array - Loop through each item by index
- 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
- If adding the item would exceed the budget, skip it and continue to the next item
- Return the array of affordable item names
Parameters:
itemNames([String]): Array of item namesitemPrices([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
4Operators Part 1
Arithmetic OperatorsModulo OperatorCompound AssignmentRecap - Simple MathComparison Operators7Basic IO
Print FunctionString InterpolationReadLine InputType ConversionRecap - Till 120Recap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesArgument LabelsRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Sequences
Iterating Over ElementsThe Enumerated MethodIterating Over Strings P1Iterating Over Strings P22Variables
Let vs VarType AnnotationsNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator8Bill Split Calculator
Welcome MessageGetting Input3Optionals
What Are OptionalsUnwrapping With If LetGuard LetNil Coalescing OperatorRecap - Safe Unwrapping9Loops
For-In LoopWhile LoopRepeat-While LoopBreakContinueRecap - FactorialRanges In LoopsNested LoopRecap - Dynamic Input