包裹二维网格索引



我有这个函数,我在python原型导航网格索引。它在python中工作得很好,但由于模运算符处理负数的方式,它在c++中就失效了。谁能建议一个修改,使它工作?

当坐标nxny为负时,函数失败。

int wrap_grid(int index, int x, int y, int nx, int ny) {
//first calculate positon on row by adding nx -
//assuming an infinite grid of indices (no limits or wrap)
int a = (index + (y * nx));
//then wrap around the width (x) of the row
int b = a % (x * y);
//now do column, calculate the bottom index of the column
int start = b - b % y;
//and the top index
int limit = b - b % y + y;
//now wrap the ny value around the columns
return start + (b + ny) % (limit - start);
}

EDIT: To explain function arguments

index是矩形网格的索引,如下所示:

col3

你只需要一个mod函数,只会给你非负值。直接的方法如下所示(为了清晰起见,先移动一下代码)。

#include <tuple>
#include <iostream>
int grid_coords_to_index(int cols, int rows, int x, int y) {
// wrap the coordinates...
int column = x % cols;
column = column >= 0 ? column : column + cols;
int row = y % rows;
row = row >= 0 ? row : row + rows;
int bottom_of_column_index = column * rows;
return bottom_of_column_index + row;
}
std::tuple<int,int> index_to_grid_coords(int cols, int rows, int index) {
// TODO: handle negatives correctly here too, if we cannot 
// assume indices are positive.
return { index / rows, index % rows };
}
int wrap_grid(int initial_index, int cols, int rows, int x_offset, int y_offset) {
auto [x, y] = index_to_grid_coords(cols, rows, initial_index);
return grid_coords_to_index(cols, rows, x + x_offset, y + y_offset);
}
int main()
{  
/*
5   11  17
4   10  16
3   9   15
2   8   14
1   7   13
0   6   12
index 9 is (1,3) so two to the left and one down should be 14 given wrapping
*/
std::cout << wrap_grid(9, 3, 6, -2, -1) << "n";
}