开发者

Coordinate calculation problem!

I am using a single-dimensional array to simulate a two-dimensional array, due to the performance increase of doing so.

开发者_开发知识库

The formular for finding the index of where to place the item is the following, when the height of the array is 30 items, and the width of the array is 20 items.

offset = x * 30 + y

Given this same information, how would I convert an offset back into positions? I know it's possible. I just can't think of how to do it.


int x = offset / 30;
int y = offset % 30;


You can use division and modulo to do so.

I don't know what you're using this for of course, but please consider that readability by far outweighs performance. Rule of thumb: ONLY optimize if there actually is a speed issue present.

In fact if you are worried about performance, then reconsider the spacial locality of your array. If you are to run a loop through all elements then in your case do it by columns, not rows. As you have organized your array in that direction.

I would've done it by rows (readability and maintainability in mind):

offset = y * 20 + x
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜