Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array with negative indexes

I have an array which I'm using to store map data for a game I'm working on.

MyMapType[,,] map; 

The reason I'm using a fixed array instead of a Collection is because fixed arrays work very much faster.

Now my problem is, I'd like to have support for negative z levels in the game. So I'd like to be able to access a negative index.

If this is not possible, I thought of a pair of other solutions.

I was thinking as a possible solution to have ground-level as some arbitrary number (say 10), and anything less than 10 could be considered negative. But wouldn't this make the array 10 times larger for nothing if its not in use?

Another solution I considered was to 'roll my own' where you have a Dictionary of 2D arrays, with the Z level held in the List as the index. But this is a lot more work and I'm not sure if its slow or not.

So to summarise - any way of creating an array which supports a negative index? And if there's not - is there a clean way of 'emulating' such behaviour without sacrificing too much CPU time or RAM - noting that these are game maps which could end up large AND need to be accessed constantly.

like image 326
Haedrian Avatar asked Dec 11 '22 16:12

Haedrian


2 Answers

replace your arrays with a class:

class MyArray {
    private MyMapType[] myArray = new myMapType[size]
    MyMapType this[index] {
       get{return myArray[index + offset];}
    }

}

you can set the size and the offset in the constructor or even change it at will.

Building on this example here is another version:

class MyArray {
    private MyMapType[] positives = new myMapType[size]
    private MyMapType[] negatives = new myMapType[size-1]
    MyMapType this[index] {
       get{return index >= 0 ? positives[index] : negateves[1-index];}
    }

}

It does not change the fact that you need to set the size for both of them. Honestly I like the first one better

like image 99
mfeingold Avatar answered Dec 14 '22 07:12

mfeingold


If you want "negative" indexes C# 8 now supports it.

var words = new string[]
{
                // index from start    index from end
    "The",      // 0                   ^9
    "quick",    // 1                   ^8
    "brown",    // 2                   ^7
    "fox",      // 3                   ^6
    "jumps",    // 4                   ^5
    "over",     // 5                   ^4
    "the",      // 6                   ^3
    "lazy",     // 7                   ^2
    "dog"       // 8                   ^1
};              // 9 (or words.Length) ^0

So the to call the negative one would be like this

words[^1]

See this link

So in your case the middle element could be the zero Z

like image 23
A_kat Avatar answered Dec 14 '22 06:12

A_kat