Menu
CoddyTech

What To Buy

Part of the Fundamentals section of Coddy's GDScript journey. Lesson 92 of 92.

challenge icon

Challenge

Medium

The program reads three lines of input, and the given code already stores them:

  1. prices: the price of each item, as an array of whole numbers
  2. items: the name of each item, in the same order
  3. budget_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: 2

Try 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

Practice on your own: Online GDScript compiler