简体   繁体   中英

How to check if a pair of values exist on a 2-dimensional array in java

I have a 2d array of that form:

int[][] moves ;
moves = new int[][]{{1, 2}, {1, -2}, {2, 1}, {2, -1}, {-1, 2},
            {-1, -2}, {-2, 1}, {-2, -1}};

and i want to check programmaticaly if a pair of values {j,k} exist on my 2d array moves .

for(int i = 0; i < 8; i++)
    {
        if(moves[i][0] == j && moves[i][1] == k)
        {
            //Executable code
        }
    }

With java 8 you would write this one liner:

int[][] moves ;
moves = new int[][]{{1, 2}, {1, -2}, {2, 1}, {2, -1}, {-1, 2},
        {-1, -2}, {-2, 1}, {-2, -1}};

int [] t= {2,1};
boolean found = Arrays.stream(moves).anyMatch(m->Arrays.equals(m,t));

You can do it with an enhanced for loop:

boolean exists = false;
for (int[] move : moves) {
    if (move[0] == i && move[1] == j) {
        exists = true;
        break;
    }
}

At the end of the loop variable exists is set to true if a pair {i, j} exists in the moves array; otherwise, exists remains false .

for (int x = 0; x < moves.length; ++x) {
    if (moves[x] != j) {
        continue;
    }

    for (int y = 0; y < moves[x].length; ++y) {
        if (moves[x][y] == k) {
            return true;
        }
    }
}

return false;
    int[][] moves;
    moves = new int[][] { { 1, 2 }, { 1, -2 }, { 2, 1 }, { 2, -1 }, { -1, 2 }, { -1, -2 }, { -2, 1 }, { -2, -1 } };
    int n = 1;
    int m = 2;
    boolean found = false;
    for (int i = 0; i < moves.length; i++) {
        for (int j = 0; j < moves[0].length; j++) {
            if (moves[i][j] == n) {
                if (j < 1 && moves[i][j + 1] == m) {
                    found = true;
                    break;
                }
            }
        }
    }
    if (found) {
        System.out.println(String.format("[%d , %d] found", n, m));
    } else {
        System.out.println(String.format("[%d , %d] not found", n, m));
    }
int[][] moves ;
moves = new int[][]{{1, 2}, {1, -2}, {2, 1}, {2, -1}, {-1, 2},
            {-1, -2}, {-2, 1}, {-2, -1}};

for(int j = 0; j < moves.length; j++){
    for(int k = 0; k < moves[j].length; k++){
        if(moves[j][k] != 0){
            System.out.println("Exist");
        }
    }
}

If you want to check for specific index change moves[j][k] to your desired index. Or if you want to compare two values,

Change:

if(moves[j][k] != 0){

To:

if(moves[j] == 44 && moves[k] == 44){

If you want to return true or false rather than printing something you can use:

return true;

Or If you want to return values in specific index rather than printing something you can use:

return moves[j][k];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM