Problem overview
The function gridSum receives grid, a slice of rows where each row is a slice of integers, and returns the sum of every number in it. Every row has the same number of values, and the numbers can be negative.
For [[1, 2, 3], [4, 5, 6]] the first row adds up to 6 and the second to 15, so the answer is 21. For [[-3, 4], [5, -6]] the answer is 0, and for [[7]] it is 7.
Approach: visit every cell once
A grid in Go has the type [][]int: a slice whose elements are themselves slices of int. To touch every number you need two loops. The outer loop takes one row at a time. The inner loop takes the values of that row one at a time. Together they visit each cell exactly once, so adding each value to a running total gives the sum of the whole grid.
The order of the visits does not matter for a sum, so there is no need to think about rows and columns separately. Later lessons use the same two loops but need to know where a value sits.
Step by step
- Create
totalwith:=and start it at 0. It holds the sum of the numbers added so far. - Loop over the rows:
for _, row := range grid. Eachrowis a[]int. The index is not needed, so_discards it. - Loop over the values of the row:
for _, value := range row. For every row, this inner loop finishes all of its values before the outer loop moves on. - Add the value:
total += value. - Return
totalafter both loops. Returning inside a loop would add only part of the grid.
The solution in Go
func gridSum(grid [][]int) int {
total := 0
for _, row := range grid {
for _, value := range row {
total += value
}
}
return total
}
Go details:
- Two indexes give one value. For
g := [][]int{{1, 2, 3}, {4, 5, 6}},len(g)is 2 rows,len(g[0])is 3 columns, andg[1][2]is 6: row 1, then column 2 of that row. rangecopies the value.valueis a copy of each element, which is fine for reading numbers. Assigning to it would not change the grid.:=declares and infers the type.total := 0makestotalanint, the same type as the grid's values.+=is shorthand fortotal = total + value.
Edge cases and common mistakes
- Negative numbers need no special handling. They simply make the total smaller, which is why
[[-3, 4], [5, -6]]gives 0. - A single cell.
[[7]]has one row with one value, so both loops run once and the result is 7. - Resetting the total inside a loop. If
total := 0sat inside the outer loop, each row would start over and the function would return only the last row's sum. - Returning too early. A
returninside the loops would stop after the first cell. - Using one loop. A single loop over
gridwould give rows, not numbers, andtotal += rowwould not compile because a[]intcannot be added to anint.
Testing
[[1, 2, 3], [4, 5, 6]]gives21.[[-3, 4], [5, -6]]gives0.[[7]]gives7.
