Problem overview
You get a grid of integers and return the sum of every number in it. A grid is a table made of rows. Every row has the same number of values, one for each column, and rows and columns are counted from 0. In Kotlin the lesson's grid is an Array<IntArray>: an array whose elements are IntArray rows.
For the grid with rows [1, 2, 3] and [4, 5, 6] the first row adds up to 6 and the second to 15, so the answer is 21. For rows [-3, 4] and [5, -6] the sum is 0, because negative numbers simply make the total smaller. A grid with the single row [7] gives 7.
Approach
A row is a list of numbers you already know how to add up with a loop. A grid is a list of rows. So use a loop inside a loop: the outer one takes each row, and the inner one takes each value of that row. Together they visit every cell exactly once, and one running total collects them all.
Step by step
- Create
var total = 0. Nothing has been added yet, and it is avarbecause it changes. - Write
for (row in grid). Each element of anArray<IntArray>is anIntArray, sorowis one whole row. - Inside it, write
for (value in row). For each row, this loop visits all of its values before the outer loop moves on to the next row. - In the inner loop,
total += value. Negative values are added like any other, which lowers the total. - After both loops,
return total. Returning inside a loop would stop after part of the grid.
To picture it, follow the first example. The outer loop takes the row [1, 2, 3], and the inner loop adds 1, 2 and 3, so the total is 6. The outer loop then takes [4, 5, 6], and the inner loop adds 4, 5 and 6 on top of that 6. The final total is 21. The total never restarts between rows, which is what makes it a sum of the whole grid.
The solution in Kotlin
class Solution {
fun gridSum(grid: Array<IntArray>): Int {
var total = 0
for (row in grid) {
for (value in row) {
total += value
}
}
return total
}
}
Some Kotlin details:
for (row in grid)loops over the elements themselves, not over indexes. You don't need to know how many rows or columns the grid has.Array<IntArray>is an array of arrays.grid.sizeis the number of rows, andgrid[0].sizeis the number of columns when all rows have equal length.total += valueis shorthand fortotal = total + value.Intholds 32 bits and wraps on overflow without warning. Here at most 100 values between -1000 and 1000 are added, so the total stays tiny.
Edge cases and common mistakes
- Resetting the total. Putting
var total = 0inside the outer loop would restart the sum for every row, and the function would only see the last row's sum. - Returning too early. A
returninside either loop ends the function early. - One cell. A grid like
[[7]]works with no special case: each loop runs once. - Negative numbers. No special handling is needed. Start the total at 0, not at some "smallest value" guess.
Testing
- Rows
[1, 2, 3]and[4, 5, 6]give 21. - Rows
[-3, 4]and[5, -6]give 0. - The single row
[7]gives 7.
