What To Buy
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 92 of 92.
Challenge
MediumThe program reads three lines of input, and the given code already stores them:
prices: the price of each item, as an array of whole numbersitems: the name of each item, in the same orderbudget_per_item: the most you can spend on one item
Go through the items. When the price of an item is at most budget_per_item, append its name to affordable_items and add its price to total_needed. Otherwise, add 1 to cant_afford.
The given print() lines show the result. For the inputs 10,25,5,15, hammer,saw,nails,brush and 12, the output is:
Can buy: ["hammer", "nails"]
Total budget needed: 15
Can't afford: 2Try it yourself
extends Node
func _ready():
var prices: Array[int] = []
for price in OS.read_string_from_stdin().split(","):
prices.append(int(price))
var items := OS.read_string_from_stdin().split(",")
var budget_per_item := int(OS.read_string_from_stdin())
var affordable_items: Array[String] = []
var cant_afford := 0
var total_needed := 0
# Write your code below
print("Can buy: ", affordable_items)
print("Total budget needed: ", total_needed)
print("Can't afford: ", cant_afford)
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsInteger DivisionModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators10Functions
Declare a FunctionArgumentsReturnReturn TypesRecap - Sigma FunctionRecap - Validation FunctionDefault Values5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary OperatorPractice on your own: Online GDScript compiler