Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementation of array with negative indices

Tags:

arrays

c#

I am making a game with a world that extends infinitely in every direction. This means that you can be at position X:50, Y:50 or X:-50, Y:-50. But... I can't really do that with a normal C# List...

All the ideas I've come up with seem to be too complicated/inefficient to work...

like image 581
Entity Avatar asked Aug 06 '12 23:08

Entity


People also ask

Can arrays have negative indices?

We can access the elements of an array by going through their indexes. But no programming language allows us to use a negative index value such as -4. Python programming language supports negative indexing of arrays, something which is not available in arrays in most other programming languages.

Can we have negative indexes in array in C++?

That means that you can have a pointer to the middle element of an array, and use it with a positive or negative index, and it's simple arithmetic. That is, negative indexes here will be out of bounds of the array, and will lead to undefined behavior.

Is it possible to have negative index in an array in Java?

Java subscript index starts with 0. No negative index can be used. If at all used then java will throw Array Index out of bounds Exception.

Which Cannot accept negative indexes?

substr deals with a starting offset and a length. It makes sense to me that substring does not allow a negative index, because there really isn't a such thing as a negative index (the characters in a string are indexed from 0 to n, a "negative index" would be out of bounds).


1 Answers

The easiest way to implement infinite grid is using a sparse matrix with a dictionary with an x,y pair as the key and the data you want to store as the values. This is fast, easy to implement, and memory friendly if your grid is sparse.

Another way is a linked grid (similar to linked list, but with pointers to 4 directions), or a tile-based approach to reduce the overhead of linked grid (a tile is a linked grid of NxN arrays). Implementation of tiles is quite complicated, but is a good tradeoff between memory and performance for very dense grids.

But my personal favorite approach is to use the even-odd transformation. So odd indices are positive, while even numbers are negative. To transform from virtual index to the physical index, you use the formula p = abs(v * 2) - (v > 0 ? 1 : 0) and to convert physical to virtual index you do v = (p % 2 == 1 ? +1 : -1) * ((2*p + 3) / 4). This relation arises because there is one to one and onto relation (bijection) between natural numbers and integers (0 <-> 0), (1 <-> 1), (2 <-> -1), (3 <-> 2), (4 <-> -2), (5 <-> 3), (6 <-> -3), .... This approach is fast, simple and elegant, but not very great memory wise when you have very sparse grid with items extremely far from the center line.

like image 158
Lie Ryan Avatar answered Oct 04 '22 17:10

Lie Ryan