Home > Enterprise >  Counting adjacent -1s in a 2d array without checking positions that are out of bounds (Minesweeper)
Counting adjacent -1s in a 2d array without checking positions that are out of bounds (Minesweeper)

Time:02-22

I am in the process of writing a program that works like Minesweeper. This is done in a 10x10 2d-array, and since I'm working with constraints, I can only write this using a 2d-array. However, I am getting a logical error with my count() method. The count() method returns the number of -1s found in the grid surrounding the input position (input position is what I'd make row and column in main(), for example, (5, 5). It also must not check a position outside the bounds of the 2d array. Here is a visual of what the output of count() should look like.

I also have to use count() with setCounts(). setCounts() goes through the entire 2d array, skips any position that is a -1, and calls the count() method, setting the current position to the value the count() method returns.

    public int count(int row, int col)
    {
        int value = 0;
        for(int r = -1; r < 2; r  )
        {
            for(int c = -1; c < 2; c  )
            {
                if(c == 0 && r == 0)
                    continue;
                
                int newR = row   c;
                int newC = col   c;

                if(newR < 0 || newR >= array.length && newC < 0 || newC >= array[0].length)
                    continue;
    
                if(array[newR][newC] == -1)
                    value  ;
            }
        }
        return value;
    }

    public void setCounts()
    {
        for(int r = 0; r < array.length; r  )
        {
            for(int c = 0; c < array[r].length; c  )
            {
                if(array[r][c] != -1)
                    array[r][c] = count(r, c);
                String formatted = String.format("-", array[r][c]);
                System.out.print(formatted   " ");
            }
                System.out.println();
        }
    }   

The problem is that:

  1. The count() method is incorrectly counting adjacent -1s surrounding any position I put in main()
  2. setCounts() goes out of bounds after printing a random number of rows

I am certain that it has to do with this block of code:

if(newR < 0 || newR >= array.length && newC < 0 || newC >= array[0].length)
                    continue;
    
                if(array[newR][newC] == -1)
                    value  ;

When I printed newR and newC in the loop after continue, the loop is randomly adding more numbers to a row/column combo with no direct pattern for the entire output when count() was called in setCounts():

00
11
11
00
11
 0 01
12
12
01
12
 0 02
13
13
02
13
 0 03
14
14
03
14
 3 04
15
15
04
15
 0 -1 -1 -1 -1 09
09
 0 
-1 00
...

So taking the print statements out, I get this as an output:

0 -1 -1 0 -1 -1 -1 0 0 0 
0 0 0 0 0 0 -1 0 0 0 
0 -1 0 -1 0 0 0 0 0 0 
0 0 -1 0 0 0 0 0 -1 0 
-1 0 0 0 -1 0 0 0 0 0 
0 0 0 -1 0 0 0 -1 0 0 
0 0 0 0 0 0 -1 0 -1 0 
0 0 0 0 -1 -1 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
there are 0 -1s
-----------
 3  3  0 -1  3  3  0 -1  0  0 

/* Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 10
    at Grid3.count(Grid3.java:44)
    at Grid3.setCounts(Grid3.java:58)
    at Grid3.main(Grid3.java:86) */

The first array is the array I make with Grid's constructor. The second array that the program is trying to print is being done when setCounts() is called.

I was thinking that changing it to:

if(newR < 0 || newR >= array.length)
                    continue;
                    
                if(newC < 0 || newC >= array[0].length)
                    continue;
    
                if(array[newR][newC] == -1)
                    value  ;

would work: and it does, but not logically. It gets rid of the ArrayIndexOutOfBoundsException error, but logically does not work since it doesn't count adjacent -1's right. It also seems to be adding more numbers randomly to any row/column combo. I put the position as (5, 5) in main() and one time I ran the code, it counted 6 -1s but there are only 3 -1s in the position I put:

-1 0 0 0 0 -1 0 -1 0 0 
0 0 0 0 -1 -1 0 0 0 0 
0 -1 0 0 0 0 0 0 0 0 
0 -1 0 -1 -1 0 0 -1 -1 0 
0 0 0 -1 -1 -1 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
-1 0 0 0 0 0 -1 0 0 0 
0 -1 0 0 0 -1 0 0 0 0 
0 -1 0 0 -1 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
there are 6 -1s

And for setCounts(), it printed a full 10x10 2d array but does not count -1s properly either. For the position (0, 0) (in this case, the 3 at the top left corner of the output shown below), that position should actually have a value of 2 since there are only 2 adjacent -1s, but it actually counts 3.

 3  0  0  0  0  0 -1  0  0  0 
-1 -1  0  3  0  0  0 -1  0  0 
-1  3  6  3 -1  0  3  0  3  0 
 0  3  0 -1 -1 -1  0 -1  0  0 
 3  0  0  0 -1  3  6  3  3  0 
 3 -1  0  0  0  3  0 -1 -1  0 
-1 -1  3  0  0  0  0  3  3  3 
 0  6  6  0  3  0  0  0 -1  0 
 0  0 -1 -1  0 -1  0  0  0  3 
 0  0  0  3  3  0  3  0  0  0 

Here is a full output:

0 0 0 0 0 0 -1 0 0 0 
0 -1 0 0 -1 0 0 0 0 0 
0 -1 0 0 0 -1 0 0 0 0 
0 0 -1 -1 -1 0 0 -1 0 0 
0 0 0 0 0 -1 -1 0 -1 0 
-1 0 0 -1 0 -1 0 0 0 0 
0 0 0 0 0 0 0 0 -1 0 
0 -1 0 0 0 0 0 0 -1 0 
0 0 0 0 0 0 -1 0 -1 0 
0 0 0 0 0 0 0 0 0 0 
there are 2 -1's
-----------
 3  0  0  3  0  0 -1  0  0  0 
 3 -1  0  0 -1  0  0  3  0  0 
 0 -1  6  3  0 -1  3  0  0  0 
 0  0 -1 -1 -1  3  3 -1  0  0 
 0  0  3  3  6 -1 -1  0 -1  0 
-1  0  0 -1  0 -1  3  6  0  3 
 3  3  0  0  3  0  3  3 -1  0 
 0 -1  0  0  0  3  0  3 -1  3 
 0  0  3  0  0  0 -1  0 -1  3 
 0  0  0  0  0  0  0  3  0  3 

I cannot figure out what I'm doing wrong. I need count() to properly count adjacent -1s given a position. If it doesn't count adjacent -1s properly, then setCounts() will not logically work. What should I change in either or both methods so that it properly and logically works? Here is my code so far.

public class Grid
{
    private int [][] array;
    private int max;

    public Grid(int max)
    {
        array = new int[10][10];
        this.max = max;
        setRandom();
    }

    public void setRandom()
    {
        int i = 0;
        while(i < max)
        {
            int r = (int)(Math.random() * 9)   0;
            int c = (int)(Math.random() * 9)   0;
            if(array[r][c] != -1)
                {
                    array[r][c] = -1;
                    i  ;
                }
        }
    }

    public int count(int row, int col)
    {
        int value = 0;
        for(int r = -1; r < 2; r  )
        {
            for(int c = -1; c < 2; c  )
            {
                if(c == 0 && r == 0)
                    continue;
                
                int newR = row   c;
                int newC = col   c;

                if(newR < 0 || newR >= array.length && newC < 0 || newC >= array[0].length)
                    continue;
    
                if(array[newR][newC] == -1)
                    value  ;
            }
        }
        return value;
    }

    public void setCounts()
    {
        for(int r = 0; r < array.length; r  )
        {
            for(int c = 0; c < array[r].length; c  )
            {
                if(array[r][c] != -1)
                    array[r][c] = count(r, c);
                String formatted = String.format("-", array[r][c]);
                System.out.print(formatted   " ");
            }
                System.out.println();
        }
    }   

    public void print()
    {
        for(int r = 0; r < array.length; r  )
        {
            for(int c = 0; c < array[r].length; c  )
            {
                System.out.print(array[r][c]   " ");
            }
                System.out.println();
        }
    }


    public static void main(String[] args)  // printing grid
    {
        Grid first = new Grid(20);
        int count = first.count(5, 5);
        first.print();
        System.out.println("there are "   count   " -1s");
        System.out.println("-----------");
        first.setCounts();
    }
}

CodePudding user response:

It might be easier to not use a 2d-array. Or at least, you might want to store an object representing each cell rather than just an int. This way, you could implement the logic for figuring out the neighboring cells for a particular cell within the Cell-Class.

Here is an example (using a map instead of an array):

public class Grid {

  public final int width, height;
  private final Map<Coordinate, Cell> cells;

  public Grid(int width, int height) {
    this.width = width;
    this.height = height;
    this.cells = IntStream.range(0, width).boxed()
            .flatMap(column ->
                    IntStream.range(0, height).boxed()
                            .map(row -> new Coordinate(row, column))
            )
            .map(Cell::new)
            .collect(Collectors.toMap(Cell::getCoordinate, Function.identity()));
  }

  public Cell get(int row, int col) {
    return this.cells.get(new Coordinate(row, col));
  }

  public class Cell {
    private final Coordinate coordinate;
    private final boolean isMine;

    public Cell(Coordinate coordinate, boolean isMine) {
        this.coordinate = coordinate;
        this.isMine = isMine;
    }

    public Cell(Coordinate coordinate) {
        this(coordinate, new Random().nextBoolean());
    }

    public Coordinate getCoordinate() {
        return coordinate;
    }

    public List<Cell> getNeighbours() {
        int leftNeighbourColumnIdx = coordinate.column - 1;
        int topNeighbourRowIdx = coordinate.row - 1;
        return IntStream.range(leftNeighbourColumnIdx, leftNeighbourColumnIdx   3).boxed()
                .flatMap(column -> IntStream.range(topNeighbourRowIdx, topNeighbourRowIdx   3).boxed().map(row -> new Coordinate(row, column)))
                .map(Grid.this.cells::get)
                .filter(Objects::nonNull)
                .filter(c -> !c.equals(this))
                .collect(Collectors.toList());
    }

    public int countNeighbouringMines() {
        return (int) getNeighbours().stream()
                .filter(cell -> cell.isMine)
                .count();
    }
  }

  public static class Coordinate {
    private final int row, column;

    public Coordinate(int row, int column) {
        this.row = row;
        this.column = column;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Coordinate that = (Coordinate) o;
        return row == that.row && column == that.column;
    }

    @Override
    public int hashCode() {
        return Objects.hash(row, column);
    }
  }


  public static void main(String[] args) {
    final var grid = new Grid(10, 10);
    for (int row = 0; row < grid.height; row  ) {
        for (int col = 0; col < grid.width; col  ) {
            final var cell = grid.get(row, col);
            System.out.print(cell.isMine ? "x" : "o");
            System.out.print(" ");
        }
        System.out.println();
    }

    System.out.printf("mines around (5,5): %d%n", grid.get(5, 5).countNeighbouringMines());
  }

}

Edit: same example as above but with a 2d-array instead of a map

public class Grid {

    public final int width, height;
    private final Cell[][] cells;

    public Grid(int width, int height) {
        this.width = width;
        this.height = height;
        cells = new Cell[width][height];

        IntStream.range(0, width)
                .forEach(column -> IntStream.range(0, height)
                        .forEach(row -> cells[column][row] = new Cell(column, row))
                );
    }

    public Cell get(int row, int col) {
        final var column = col < 0 || col >= this.cells.length ? null : this.cells[col];
        return row < 0 || column == null || row >= column.length ? null : column[row];
    }

    public class Cell {
        private final int column, row;
        private final boolean isMine;

        public Cell(int column, int row, boolean isMine) {
            this.column = column;
            this.row = row;
            this.isMine = isMine;
        }

        public Cell(int column, int row) {
            this(column, row, new Random().nextBoolean());
        }

        public List<Cell> getNeighbours() {
            int leftNeighbourColumnIdx = column - 1;
            int topNeighbourRowIdx = row - 1;
            return IntStream.range(leftNeighbourColumnIdx, leftNeighbourColumnIdx   3).boxed()
                    .flatMap(column -> IntStream.range(topNeighbourRowIdx, topNeighbourRowIdx   3).boxed()
                            .map(row -> Grid.this.get(row, column)))
                    .filter(Objects::nonNull)
                    .filter(c -> !c.equals(this))
                    .collect(Collectors.toList());
        }

        public int countNeighbouringMines() {
            return (int) getNeighbours().stream()
                    .filter(cell -> cell.isMine)
                    .count();
        }
    }


    public static void main(String[] args) {
        final var grid = new Grid(10, 10);
        for (int row = 0; row < grid.height; row  ) {
            for (int col = 0; col < grid.width; col  ) {
                final var cell = grid.get(row, col);
                System.out.print(cell.isMine ? "x" : "o");
                System.out.print(" ");
            }
            System.out.println();
        }

        System.out.printf("mines around (5,5): %d%n", grid.get(5, 5).countNeighbouringMines());
    }
}

The idea is, that the get(int row, int col) method in Grid returns either a Cell object or null if row or cell are invalid -- but it never fails (throws an exception). Every cell can then use this method to try to get all its neighbours (getNeighbours()). The cell doesn't need to worry, if the row/column it asks for is valid or not -- this will be handled by get(int row, int col). It just needs to filter out all null values (those coordinates were invalid) and itself.

With getNeighbours(), you have a list with all the neighboring cells. If you filter out all cells which have no mines - you get a list of neighbours with mines on them -- and then you just need to count them.

  • Related