Home > Enterprise >  iterating backward in a row within a 2d array
iterating backward in a row within a 2d array

Time:11-14

Hey hope someone could help me with this one my pronlem is that i have a 2d int array in java it looks like this:

enter image description here

i would need the index of the last 2 in row 0.. i already tried to iterate backward with an inverse for each loop but that just mirrored the whole array what i would need is just the index number.. in this case it should be row 0 col 3...

i also tried to do it in a while loop but it also doesnt print the right walue and i dont know why.. it only print 2 ..

int x = ans.length;
        int y = ans[0].length;
        System.out.println(x);
        System.out.println(y);
        while(y - 1>= 0 ) {
            System.out.println("In");
            y--;
            if(ans[0][y] != 0) {
                x = ans[0][y];
                System.out.println(x);

CodePudding user response:

You dont need to iterate backward or inverse:

public class StackOveFlow {

   
    static int[][] matrix = {
            {2,2,0,2,0,0},
            {0,2,2,2,2,2},
            {2,2,2,2,2,0},
            {0,2,2,0,0,0},
            {2,2,2,0,1,1}
        };
    public static void main(String[] args) {
        // TODO code application logic here
        int rowToSearch = 0;
        int integerToFind = 2;
        int lastOccurance = findLastOccurrance(rowToSearch,integerToFind);
        if(lastOccurance>-1)
            System.out.println("Found last "   integerToFind   " in row "   rowToSearch   " at column = "   lastOccurance);
        else
            System.out.println("NOT FOUND");
       
       
    }
    public static int findLastOccurrance(int row, int intToFind)
    {
        int index = -1;
        for(int column = 0; column < 6;column  )
            if(matrix[row][column]==intToFind)
                index = column;
        
        return index;
    }
}

Iterating reverse will be useful if you have large array.. Backward iteration can done with minute changes for loop.

  • Related