Domien
Domien

Reputation: 405

Compact manner to check if array contains particular element

I currently have following code:

    int[][] legalForBlack = {{0,1},{1,0},{2,3},{3,2}};
    for (int x=0;x<boardSize;x++) {
        for (int y=0;y<boardSize;y++) {
            if (x,y) in legalForBlack
                methodA()
            else
                methodB()
        }
    }

Of course this code won't compile. I am looking for a fancy and compact way to check when (x,y) are in the given list. I can do this with 4 if-statements or a loop, but this is not a proper way imo. I am looking for something that does this in constant time.

EDIT:

I think I found a way. What do you think of this?

int[][] legalForBlack = {{0,1},{1,0},{2,3},{3,2}}; // keep in order!
    int cur = 0;
    for (int x=0;x<boardSize;x++) {
        for (int y=0;y<boardSize;y++) {
            int[] buffer = legalForBlack[cur];
            if (x==buffer[0] && y==buffer[1]) {
                cur++;
                methodA();
            } else {
                methodB();
            }
        }
    }

Upvotes: 1

Views: 96

Answers (3)

Adnan Isajbegovic
Adnan Isajbegovic

Reputation: 2297

Heres pseudocode for arrays:

input data in array
find x with for to match first column (legalForBlack[i][0])
   if x matches  legalForBlack[i][0] check if legalForBlack[i][1] matches y
   if yes, count it

But there is a better way, when you just want to check if they are in array. Create object Pair with variable x and y, create equals() and hashCode() functions to have unique for each pair (like get hashCode from string xy), place all inputs in Set and then check if given Pair(x,y) is in Set.

Upvotes: 2

Cristian Udrea
Cristian Udrea

Reputation: 76

I have an alternative solution for your question. Judging from your code, I assume that you are writing something chess-related and your list of legalForBlack is a series of coordinates that the player is allowed to move to. Best way IMO would be to code each square on the board with an index (0 to maximum 63) and store all of these in a Map of type <Integer, Coordinate>, where Coordinate has int x and int y. If you don't have any particular use for the coordinates, you can also skip and convert your Map to a simple Array of allowed-squares. This would only require you to check whether a given value is in your allowed-square list. I hope this gives you a better approach to your problem. Good luck!

Upvotes: 2

Zircon
Zircon

Reputation: 4707

boolean isLegal = false;
for(int[] coord: legalForBlack)
    if(Arrays.equals(coord, someXYArray)) {
        isLegal = true;
        break; //Credit to Adnan Isajbegovic
    }
if(isLegal) 
    methodA();
else 
    methodB();

Upvotes: 2

Related Questions