c++ - Navigating an Array with Column Boundaries -
let's there square 2 dimensional array of n x n, represented 1 dimension array. let array 5x5, below, , values in array not significant.
std::vector< int > array { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4 };
if there 5 rows , 5 columns in array, how can 1 detect if on edge of row? instance, if on index of 9 on 4th row, how can know can go left without changing rows, going right advance next row? how can 1 access cell's neighbors respect edges? index of 9 on 4th row not have right neighbor.
the way can think of how current index, in case is
int index = row * num_cols + col
and perhaps use modulus (index % 5 == 0) determine if on edge. not determine if can go left or right.
your formula
int index = row * num_cols + col;
going or down equivalent adding / subtracting num_cols
.
is correct. reverse of is
int row = index / num_cols; int col = index % num_cols;
you know you're on left edge when (index % num_cols) == 0
.
you know you're on right edge when (index % num_cols) == num_cols-1
.
Comments
Post a Comment