basics · beginner · ~15 min

Index a flattened matrix

Convert 2-D indices to a 1-D offset (r*cols + c).

Challenge

A 2-D matrix stored in a flat 1-D array — read one element by its row and column.

Task

A rows x cols matrix is stored row-major in a flat array m (row 0 first, then row 1, and so on). Implement int flat_get(const int *m, int cols, int r, int c) that returns the element at row r, column c. The offset of (r, c) in the flat array is r*cols + c. No main — the grader calls it.

Input

A flat array m, the column count int cols, and the target indices int r and int c (both in range).

Output

Returns the element at (r, c), as an int.

Example

m = {1,2,3, 4,5,6}   (2 rows x 3 cols)
flat_get(m, 3, 0, 0)   ->   1
flat_get(m, 3, 1, 2)   ->   6
flat_get(m, 3, 0, 2)   ->   3

Edge cases

  • Indices are always valid; no bounds check required.

Input format

A flat array m, the column count int cols, and indices int r, int c.

Output format

The element at (r, c), as an int.

Constraints

Row-major layout; offset is r*cols + c.

Starter code

int flat_get(const int *m, int cols, int r, int c) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.