3
votes

I have this two dimensional array of objects

private Cell[,] mapCells = new Cell[10, 10];

and I want to check if a key value pair with the coordinates x = m and y = n exists in my array.

I go for this

        bool cellExists = index.x >= 0 && // check left
              index.y >= 0 && // check bottom
              index.x < mapCells.GetLength(0) && // check right
              index.y < mapCells.GetLength(1); // check top

So with this bool I check if the cell would be on the map or outside.

Is there a more elegant way to check this?


EDIT:

When checking this I get a movement direction like

  Vector2 dir = new Vector2(/* this can be
     (0,1) // up
     (0,-1) // down
     (-1,0) // left
     (1,0) // right
  */);

So I know which direction is given.

When I move right I don't need to check the left side I think.

3
I think, it's good enoughBacks
How do you define more elegant? It´s fairly opinion-based, isn´t it?HimBromBeere
@HimBromBeere: I think he means shorter or faster. I see not much possibilities in either direction.PMF
I edited my question maybe the new information will helppeterHasemann
I'm voting to close this question as off-topic because it´s a review asking for improvement to working code and thus should go to codereview.stackexchange.com.HimBromBeere

3 Answers

3
votes

Well, you could hide it behind the extension method to make it looks more elegant.

public static class Extensions
{
    public static bool IsExist(this Cell[,] mapCells, Cell index)
    {
        bool cellExists = index.x >= 0 &&
               index.y >= 0 &&
               index.x < mapCells.GetLength(0) &&
               index.y < mapCells.GetLength(1);

        return cellExists;
    }
}

Call it like this

mapCells.IsExist(index);
1
votes

No, there's no other way to test this. The only optimization I can think of would be to cache the size, but you're not gaining much there.

0
votes

Depends on what you mean by "elegant". You could do this (off the top of my head):

bool cellExists = Math.Min(mapCells.GetLength(0) - 1, Math.Abs(x)) == x 
                && Math.Min(mapCells.GetLength(1) - 1, Math.Abs(y)) == y

The idea is to first getting the absolute value of x or y, and then check if the minimum of that and the axis upper value results in x or y. If it does, you're good.

It's shorter, but readability is questionable. And I doubt it is any faster than your original solution.