Row Summaries
Part of the Logic & Flow section of Coddy's Kotlin journey. Lesson 18 of 63.
Keep one result per row by resetting the row accumulator inside the outer loop. A summary for an empty row is still useful: a sum of zero preserves the correspondence between input rows and output positions.
Inside main:
val rows = listOf(listOf(2, 3), emptyList(), listOf(4))
val sums = mutableListOf<Int>()
for (row in rows) sums.add(row.sum())
println(sums)There is one sum for each row, including zero for the empty row.
A row summary preserves one output position per input row.
Challenge
MediumComplete rowTotals with parameters grid: List<List<Int>>. Return the sum of each row in input order. An empty row has sum zero.
Unless stricter bounds are stated above, collections contain at most 100 elements at each level, and integer arguments and integer collection values are between -1000 and 1000. Text supplied for parsing can include invalid or out-of-range representations as described.
Return a value of type List<Int>. Keep the supplied input/output code. It reads scalar arguments one per line; a list starts with its count followed by its elements, and a map starts with its entry count followed by each key and value. Nested lists repeat the count-and-elements format for each row. The supplied main prints the return value followed by one newline. Lists use Kotlin's standard bracketed format; print no additional labels.
Try it yourself
fun rowTotals(grid: List<List<Int>>): List<Int> {
// Write your solution here.
return emptyList()
}
fun main() {
val gridCount = readln().toInt()
val grid = mutableListOf<List<Int>>()
for (i0 in 0 until gridCount) {
val gridItemCount = readln().toInt()
val gridItem = mutableListOf<Int>()
for (i1 in 0 until gridItemCount) {
val gridItemItem = readln().toInt()
gridItem.add(gridItemItem)
}
grid.add(gridItem)
}
println(rowTotals(grid))
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
4Nested Collections
Lists of ListsTraversing RowsRow SummariesFlattening Nested ListsRecap - Seating Rows7Collection Pipelines
Transforming with MapFiltering ValuesTesting Collection RulesAccumulating with FoldRecap - Approved Totals5Project - Contact Book
Save ContactsFind ContactsPractice on your own: Kotlin playground