Problem overview
The function rowSums receives grid, a [][]int, and returns a slice with the sum of each row, in the same order as the rows. The output has one number per row.
For [[1, 2, 3], [4, 5, 6]] the answer is [6 15], since 1 + 2 + 3 = 6 and 4 + 5 + 6 = 15. For [[-1, -2], [-3, -4], [5, 5]] it is [-3 -7 10], and for the one-column grid [[3], [1], [4]] it is [3 1 4].
Approach: one inner total per row
Summing a whole grid needs one running total. Here every row needs its own. The outer loop visits the rows. For each row, a fresh total starts at 0, an inner loop adds that row's values to it, and when the inner loop finishes the total is appended to the result. Because rows are processed from top to bottom and each sum is appended once, the sums come out in row order.
The important detail is where the total is created. It belongs inside the outer loop, so each row starts from 0 and one row's numbers never leak into the next sum.
On the first example, sums is empty at the start, becomes [6] after the first row and [6 15] after the second. That final slice is the result.
Step by step
- Create
sumsas an empty[]intwith:=. It collects one sum per row. - Loop over the rows with
for _, row := range grid. - Create
totalat 0 inside that loop. It holds the current row's sum. - Loop over the row's values with
for _, value := range row. - Add
valuetototal. - After the inner loop, append
totaltosumsand assign the result back tosums. At this point the whole row has been added. - Return
sumsafter the outer loop. Returning inside it would send back only the first row's sum.
The solution in Go
func rowSums(grid [][]int) []int {
sums := []int{}
for _, row := range grid {
total := 0
for _, value := range row {
total += value
}
sums = append(sums, total)
}
return sums
}
Go details:
appendreturns a slice, sosums = append(sums, total)must assign the result back. The slice may move to a larger array as it grows.- Scope.
totalis declared inside the outer loop's body, so it is created anew on every turn and is invisible after the loop ends.sumsis declared outside, so it survives all the turns. - Printing.
fmt.Printlnshows a slice of ints as[6 15], with spaces and no commas. - The empty slice literal
[]int{}is ready forappend. Anilslice would work withappendtoo.
Edge cases and common mistakes
- Declaring
totaloutside the outer loop. The total then keeps growing across rows. With the declaration moved up,[[1, 2, 3], [4, 5, 6]]returns[6 21]instead of[6 15]: the second sum includes the first row. - Appending inside the inner loop. That would add one entry per cell instead of one per row.
- One value per row.
[[3], [1], [4]]gives[3 1 4]: each inner loop runs once. - Negative values. Rows of negative numbers give negative sums, as in
-3and-7above. - Forgetting to assign the result of
append. The compiler rejects anappendwhose result is unused.
Testing
[[1, 2, 3], [4, 5, 6]]gives[6 15].[[-1, -2], [-3, -4], [5, 5]]gives[-3 -7 10].[[3], [1], [4]]gives[3 1 4].
