2

I'm trying to make a 2D matrix dynamic system which identifies whether there is an "object" at X,Y coordinates (true), or not (false).

Simplified example code:

var coords = [[]]; // Matrix is over 10,000 x 10,000
var objectX = 76;
var objectY = 54;

coords[objectX][objectY] = true;

//Check to see if there is an object @ coordinates
if(coords[100][65] == false || coords[100][65] === undefined)
{
    //There is no object @ 100 x 65
}
else
{
    //Object detected @ 100 x 65
}

But it seems I can't do it this way, since I think I have to start from [0][0], [0][1], [0][2], ... , ect; or something..

Also, matrix is too large to define via putting it in a loop. I can't have it loading for hours.

I won't mind keeping an array segment 'undefined', as I treat it as false in my code.

How can I accomplish this?

2
  • [[]] just creates a nested empty array. You need to create other arrays manually. And then use coords[inLimit1][inLimit2] = Anything; Commented Feb 28, 2016 at 12:55
  • This is a very weird way for keeping track of things. Is it for display purposes? Commented Feb 28, 2016 at 12:59

1 Answer 1

3

You need to make sure the first dimension array exists before you address the second dimension:

if (coords[objectX] === undefined) coords[objectX] = [];
coords[objectX][objectY] = true;

If upfront you know you actually need an element for each X,Y position (which will consume more memory), then initialise the matrix first with a loop:

for (var objectX=0; objectX <= maxX; objectX++) {
    coords[objectX] = [];
    for (var objectY=0; objectY <= maxY; objectY++) {
        coords[objectX][objectY] = false;
    }
}

Depending on your needs, you might get better memory usage and performance if you would use a different structure:

var coords = [];
coords[objectX * (maxX + 1) + objectY] = true;

Or if you do not know the range of X nor Y:

coords = {}; // object whose properties will be X,Y strings:
coords[objectX + ',' + objectY] = true;
Sign up to request clarification or add additional context in comments.

1 Comment

You're welcome. I added some alternatives as well, ... they may be of interest.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.