Recap - Custom List
Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 34 of 65.
Challenge
MediumWrite CustomList in custom_list.gd, a class that wraps a private Array _items and offers what a list needs through methods and virtual methods:
_init(items = [])stores a copy ofitems, so later changes to the Array passed in do not reach the list.append(item)adds an item at the end.pop_back()removes and returns the last item, or returnsnullwhen the list is empty.get_at(index)returns the item, ornullwhen the index is outside0tosize() - 1.set_at(index, value)replaces the item and returnstrue, or returnsfalsefor an index outside the list.size(),has(item)andclear()work like the Array methods with the same names.concat(other)takes the place of the+operator: it returns a newCustomListwith this list's items followed by the items ofother, and changes neither list._to_string()returns the items the way an Array prints them, such as[3, 1, 4]._iter_init(),_iter_next()and_iter_get()let aforloop go through the items.
The supplied code reads the starting numbers (one line, separated by spaces, possibly empty), creates the list, appends 99 to the Array it passed in and prints the list. Then it reads the number of commands and runs one per line: append N, pop, get I, set I N, has N, size, sum (a for loop over the list), clear and concat N N .... For this input:
3 1 4
8
append 1
get 2
get 9
set 0 5
has 4
sum
pop
concat 9 2it prints:
[3, 1, 4]
[3, 1, 4, 1]
Item 2: 4
No item at 9
[5, 1, 4, 1]
Has 4: true
Sum: 11
Popped 1
[5, 1, 4] + [9, 2] = [5, 1, 4, 9, 2]Your code goes in custom_list.gd. main.gd holds the supplied input/output code and cannot be edited.
Try it yourself
extends Node
func _ready():
# Supplied input/output code: keep it as it is
var numbers := to_numbers(OS.read_string_from_stdin().split(" ", false))
var list := CustomList.new(numbers)
# The list must keep its own copy
numbers.append(99)
print(list)
var count := int(OS.read_string_from_stdin())
for i in count:
var parts := OS.read_string_from_stdin().split(" ", false)
match parts[0]:
"append":
list.append(int(parts[1]))
print(list)
"pop":
var item = list.pop_back()
print("Empty" if item == null else "Popped %d" % item)
"get":
var item = list.get_at(int(parts[1]))
print(("No item at " + parts[1]) if item == null else "Item %s: %d" % [parts[1], item])
"set":
if list.set_at(int(parts[1]), int(parts[2])):
print(list)
else:
print("No item at " + parts[1])
"has":
print("Has %s: %s" % [parts[1], list.has(int(parts[1]))])
"size":
print("Size: %d" % list.size())
"sum":
var total := 0
for item in list:
total += item
print("Sum: %d" % total)
"clear":
list.clear()
print(list)
"concat":
var other := CustomList.new(to_numbers(parts.slice(1)))
print("%s + %s = %s" % [list, other, list.concat(other)])
func to_numbers(words: PackedStringArray) -> Array:
var result := []
for word in words:
result.append(int(word))
return result
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe self KeywordMethodsPropertiesConstructor (_init)Recap - Simple Calculator4Polymorphism
Method Overriding RevisitedDuck TypingAbstract Classes and MethodsInterface DesignRecap - Shape Calculator2Class Properties
Instance vs Static VariablesStatic FunctionsProperty SettersProperty GettersPrivate by ConventionRecap - Bank Account Manager5Encapsulation
Public and Private MembersValidation with SettersInformation HidingRead-Only PropertiesRecap - Student Records System8Advanced OOP Concepts
Composition vs InheritanceInner ClassesNodes as ComponentsRefCounted vs NodeEnums in Classes11Project: Library Management
Project OverviewBook and User Classes3Inheritance
Basic InheritanceThe super KeywordMethod OverridingInheritance ChainsType Checks with isRecap - Employee Hierarchy6Special Methods
Virtual Methods IntroductionThe _to_string MethodCustom IteratorsRecap - Custom List9Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy PatternPractice on your own: Online GDScript compiler