Recap - Sum Nested Array
Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 59 of 78.
Challenge
EasyWrite a recursive function named sum_nested that takes an array nested_array. Its elements are whole numbers or other arrays, which can hold more numbers and arrays, at any depth.
The function returns the sum of every number in it, at every level.
To tell the two kinds of elements apart, use is Array: element is Array is true when element is an array.
For example, sum_nested([1, [2, 3], [4, [5, 6]], 7]) returns 28. An empty array sums to 0.
The tests call sum_nested() themselves. Do not call it, and do not print anything.
Try it yourself
func sum_nested(nested_array: Array):
var total := 0
for element in nested_array:
if element is Array:
# Add the sum of this inner array to total
pass
else:
# Add the number to total
pass
return total
All lessons in Logic & Flow
1Strings In Depth
String MethodsSearching in StringsReplace and TrimSplit and JoinRecap - Username Check4Dictionaries Part 2
Nested DictionariesArrays of DictionariesMerging DictionariesCopying DictionariesRecap - Frequency Counter10Advanced Functions
Returning Multiple ValuesLambda Functions Part 1Lambda Functions Part 2Recap - Lambda SortRecursive Functions Part 1Recursive Functions Part 2Recap - Sum Nested Array2Advanced Decision Making
Match With VariablesMatch GuardsArray PatternsDictionary PatternsMembership ChecksRecap - Command Parser5Contact Book Application
Display MenuAdd Contact8Student Records Manager
Project OverviewAdd Student3Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysJagged ArraysCommon 2D Array PatternsRecap - Game Board6Sets with Dictionaries
What is a Set?Dictionary as a SetAdding and RemovingUnion and IntersectionSet DifferenceRecap - Remove Duplicates9Advanced Data Aggregation
Summing ValuesFinding Minimum and MaximumCustom SortingRecap - Dictionary SorterPractice on your own: Online GDScript compiler