Problem
Given a n x m two-dimensional array numbers, a start index start, and an end index end, write a function solution that returns the sum of all elements within the range from start to end by row traversal.
Row traversal refers to traversing a two-dimensional array in a horizontal direction row by row.
start and end are defined as follows:
start = [sx,sy](sxis the starting row,syis the starting column)end = [ex,ey](exis the ending row,eyis the ending column)
For example, given the following numbers, start, and end:
numbers = [
[1,2,3],
[4,5,6],
[7,8,9]
]
start = [1,1]
end = [2,0]
The sum of the elements from (1,1) to (2,0) in numbers is calculated as:
numbers[1][1] + numbers[1][2] + numbers[2][0] = 5 + 6 + 7 = 18.
Constraints
- The dimensions of
numbers(nandm) are between 1 and 50 inclusive. - Each element
numbers[i][j]is a natural number between 1 and 100 inclusive. - The row indices of the range satisfy
0 ≤ sx ≤ ex < n. - The column indices of the range satisfy
0 ≤ sy, ey < m. Additionally, ifsx == ex, thensy ≤ ey.
Test Case
| Test Case Number | numbers | start | end | return |
|---|---|---|---|---|
| 1 | [[1,2,3],[4,5,6],[7,8,9]] | [1,1] | [2,0] | 18 |
| 2 | [[10,20],[30,40]] | [0,0] | [1,1] | 100 |
| 3 | [[5]] | [0,0] | [0,0] | 5 |
Explanation for Test Case 1
- For
numbers=[[1,2,3],[4,5,6],[7,8,9]],start=[1,1], andend=[2,0]:- The row traversal path is
numbers[1][1] → numbers[1][2] → numbers[2][0]. - The sum of these elements is
5 + 6 + 7 = 18. - The function returns
18.
- The row traversal path is
Explanation for Test Case 2
- For
numbers=[[10,20],[30,40]],start=[0,0], andend=[1,1]:- The row traversal path is
numbers[0][0] → numbers[0][1] → numbers[1][0] → numbers[1][1]. - The sum of these elements is
10 + 20 + 30 + 40 = 100. - The function returns
100.
- The row traversal path is
Explanation for Test Case 3
- For
numbers=[[5]],start=[0,0], andend=[0,0]:- The row traversal path includes only the single element
numbers[0][0]. - The sum of this element is
5. - The function returns
5.
- The row traversal path includes only the single element