简体   繁体   English

一维数组元素的最近邻运算

[英]Nearest Neighbor Operation on 1D array elements

I have 2D array and want to convert it into 1D array. 我有2D数组,并希望将其转换为1D数组。

The 2D array is: 2D阵列是:

1   2   3   4
5   6   7   8
9   10  11  12
13  14  15  16

to 1D array: 到一维数组:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

How do I access nearest neighbor of the element number 6 in 1D array, so that I can get the same result when I access in 2D array, such as 如何在1D数组中访问元素编号6的最近邻居,以便在访问2D数组时获得相同的结果,例如

1   2   3   
5   6   7   
9   10  11

in C++? 在C ++中?

If you have a 2D array that is M items long by N items tall, you need a 1D array that has M*N elements. 如果你有一个2D项目,其中M项目长N项目高,你需要一个具有M*N元素的一维数组。

When trying to find the neighbors of element x : 当试图找到元素x的邻居时:

left(x) = (x - 1) % M
right(x) = (x + 1) % M
above(x) = (x - M) % (M * N)
below(x) = (x + M) % (M * N)

Note that the above solution makes the bottom and top of your array adjacent, as well as the right edge and left edge. 请注意,上述解决方案使阵列的底部和顶部相邻,以及右边缘和左边缘。 To get rid of that, simply omit the modular math and detect when your index has moved past the right / left / top / bottom edges. 要摆脱这种情况,只需省略模块化数学并检测索引何时移过右/左/上/下边缘。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM