Home > other >  Java: checkin whether array have 0 and where;
Java: checkin whether array have 0 and where;

Time:12-15

I'm building an 2048 in java, and I'm trying to check which places in array are free ( free = which haves 0) in order to pass this free spaces col and row into list . Right now I have a grid like this, and I need somehow to check all values and find which places are free.

How array looks like:

Grid size is 4 x 4
   1   2   3   4   
  ================
 1| 0 | 0 | 0 | 0 | 
   -- --- --- --
 2| 0 | 0 | 0 | 0 | 
   -- --- --- --
 3| 0 | 0 | 0 | 0 | 
   -- --- --- --
 4| 0 | 0 | 0 | 0 | 
  ================

This Is only what I have for checking right now

 public static void addNewNum(int[][]grid) {
        List freeSpace = new ArrayList();
        for(int row=0; row< grid.length; row  )  {
            for(int col=0; col< grid[row].length; col  ) {
                if (grid[row][col] ==0) {
                    freeSpace.add(col);
                    freeSpace.add(row);
        }
        
        
    }

    

CodePudding user response:

If you must pass the values to a list then you need to define an appropriate class:

public final class Coordinate{

    private final int row;
    private final int col;
  
    public Coordinate(final int row, final int col){

        this.row = row;
        this.col = col;
    }

    public int getRow(){

        return row;
    }

    public int getCol(){

        return col;
    }
}

Then change your list definition to:

List<Coordinate> freeSpace = new ArrayList<>();

Then to add a free space coordinate:

freeSpace.add(new Coordinate(row,col));

Thus, your addNewNum method would now look as follows:

public static void addNewNum(int[][]grid) {
    List<Coordinate> freeSpace = new ArrayList<>();
    for(int row=0; row< grid.length; row  )  {
        for(int col=0; col< grid[row].length; col  ) {
            if (grid[row][col] ==0) {
                freeSpace.add(new Coordinate(row,col));
            }
    
    
}
  • Related