Avatar of janluke

janluke's solution

to Minesweeper in the Java Track

Published at Oct 12 2019 · 0 comments
Instructions
Test suite
Solution

Add the numbers to a minesweeper board.

Minesweeper is a popular game where the user has to find the mines using numeric hints that indicate how many mines are directly adjacent (horizontally, vertically, diagonally) to a square.

In this exercise you have to create some code that counts the number of mines adjacent to a square and transforms boards like this (where * indicates a mine):

+-----+
| * * |
|  *  |
|  *  |
|     |
+-----+

into this:

+-----+
|1*3*1|
|13*31|
| 2*2 |
| 111 |
+-----+

Setup

Go through the setup instructions for Java to install the necessary dependencies:

https://exercism.io/tracks/java/installation

Running the tests

You can run all the tests for an exercise by entering the following in your terminal:

$ gradle test

Use gradlew.bat if you're on Windows

In the test suites all tests but the first have been skipped.

Once you get a test passing, you can enable the next one by removing the @Ignore("Remove to run test") annotation.

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

MinesweeperBoardTest.java

import org.junit.Ignore;
import org.junit.Test;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static org.junit.Assert.assertEquals;

public class MinesweeperBoardTest {

    @Test
    public void testInputBoardWithNoRowsAndNoColumns() {
        List<String> inputBoard = Collections.emptyList();
        List<String> expectedNumberedBoard = Collections.emptyList();
        List<String> actualNumberedBoard = new MinesweeperBoard(inputBoard).withNumbers();

        assertEquals(expectedNumberedBoard, actualNumberedBoard);
    }

    @Ignore("Remove to run test")
    @Test
    public void testInputBoardWithOneRowAndNoColumns() {
        List<String> inputBoard = Collections.singletonList("");
        List<String> expectedNumberedBoard = Collections.singletonList("");
        List<String> actualNumberedBoard = new MinesweeperBoard(inputBoard).withNumbers();

        assertEquals(expectedNumberedBoard, actualNumberedBoard);
    }

    @Ignore("Remove to run test")
    @Test
    public void testInputBoardWithNoMines() {
        List<String> inputBoard = Arrays.asList(
                "   ",
                "   ",
                "   "
        );

        List<String> expectedNumberedBoard = Arrays.asList(
                "   ",
                "   ",
                "   "
        );

        List<String> actualNumberedBoard = new MinesweeperBoard(inputBoard).withNumbers();

        assertEquals(expectedNumberedBoard, actualNumberedBoard);
    }

    @Ignore("Remove to run test")
    @Test
    public void testInputBoardWithOnlyMines() {
        List<String> inputBoard = Arrays.asList(
                "***",
                "***",
                "***"
        );

        List<String> expectedNumberedBoard = Arrays.asList(
                "***",
                "***",
                "***"
        );

        List<String> actualNumberedBoard = new MinesweeperBoard(inputBoard).withNumbers();

        assertEquals(expectedNumberedBoard, actualNumberedBoard);
    }

    @Ignore("Remove to run test")
    @Test
    public void testInputBoardWithSingleMineAtCenter() {
        List<String> inputBoard = Arrays.asList(
                "   ",
                " * ",
                "   "
        );

        List<String> expectedNumberedBoard = Arrays.asList(
                "111",
                "1*1",
                "111"
        );

        List<String> actualNumberedBoard = new MinesweeperBoard(inputBoard).withNumbers();

        assertEquals(expectedNumberedBoard, actualNumberedBoard);
    }

    @Ignore("Remove to run test")
    @Test
    public void testInputBoardWithMinesAroundPerimeter() {
        List<String> inputBoard = Arrays.asList(
                "***",
                "* *",
                "***"
        );

        List<String> expectedNumberedBoard = Arrays.asList(
                "***",
                "*8*",
                "***"
        );

        List<String> actualNumberedBoard = new MinesweeperBoard(inputBoard).withNumbers();

        assertEquals(expectedNumberedBoard, actualNumberedBoard);
    }

    @Ignore("Remove to run test")
    @Test
    public void testInputBoardWithSingleRowAndTwoMines() {
        List<String> inputBoard = Collections.singletonList(
                " * * "
        );

        List<String> expectedNumberedBoard = Collections.singletonList(
                "1*2*1"
        );

        List<String> actualNumberedBoard = new MinesweeperBoard(inputBoard).withNumbers();

        assertEquals(expectedNumberedBoard, actualNumberedBoard);
    }

    @Ignore("Remove to run test")
    @Test
    public void testInputBoardWithSingleRowAndTwoMinesAtEdges() {
        List<String> inputBoard = Collections.singletonList(
                "*   *"
        );

        List<String> expectedNumberedBoard = Collections.singletonList(
                "*1 1*"
        );

        List<String> actualNumberedBoard = new MinesweeperBoard(inputBoard).withNumbers();

        assertEquals(expectedNumberedBoard, actualNumberedBoard);
    }

    @Ignore("Remove to run test")
    @Test
    public void testInputBoardWithSingleColumnAndTwoMines() {
        List<String> inputBoard = Arrays.asList(
                " ",
                "*",
                " ",
                "*",
                " "
        );

        List<String> expectedNumberedBoard = Arrays.asList(
                "1",
                "*",
                "2",
                "*",
                "1"
        );

        List<String> actualNumberedBoard = new MinesweeperBoard(inputBoard).withNumbers();

        assertEquals(expectedNumberedBoard, actualNumberedBoard);
    }

    @Ignore("Remove to run test")
    @Test
    public void testInputBoardWithSingleColumnAndTwoMinesAtEdges() {
        List<String> inputBoard = Arrays.asList(
                "*",
                " ",
                " ",
                " ",
                "*"
        );

        List<String> expectedNumberedBoard = Arrays.asList(
                "*",
                "1",
                " ",
                "1",
                "*"
        );

        List<String> actualNumberedBoard = new MinesweeperBoard(inputBoard).withNumbers();

        assertEquals(expectedNumberedBoard, actualNumberedBoard);
    }

    @Ignore("Remove to run test")
    @Test
    public void testInputBoardWithMinesInCross() {
        List<String> inputBoard = Arrays.asList(
                "  *  ",
                "  *  ",
                "*****",
                "  *  ",
                "  *  "
        );

        List<String> expectedNumberedBoard = Arrays.asList(
                " 2*2 ",
                "25*52",
                "*****",
                "25*52",
                " 2*2 "
        );

        List<String> actualNumberedBoard = new MinesweeperBoard(inputBoard).withNumbers();

        assertEquals(expectedNumberedBoard, actualNumberedBoard);
    }

    @Ignore("Remove to run test")
    @Test
    public void testLargeInputBoard() {
        List<String> inputBoard = Arrays.asList(
                " *  * ",
                "  *   ",
                "    * ",
                "   * *",
                " *  * ",
                "      "
        );

        List<String> expectedNumberedBoard = Arrays.asList(
                "1*22*1",
                "12*322",
                " 123*2",
                "112*4*",
                "1*22*2",
                "111111"
        );

        List<String> actualNumberedBoard = new MinesweeperBoard(inputBoard).withNumbers();

        assertEquals(expectedNumberedBoard, actualNumberedBoard);
    }

}
import java.util.*;
import java.util.stream.Collectors;


class MinesweeperBoard {

    private List<String> boardWithNumbers;

    MinesweeperBoard(List<String> board) {
        boardWithNumbers = generateBoardWithNumbers(board);
    }

    static List<String> generateBoardWithNumbers(List<String> board) {
        int numRows = board.size();
        if (numRows == 0)
            return new ArrayList<>(0); 
        int numCols = board.get(0).length();
        
        // Copy the board into the matrix
        char[][] matrix = new char[numRows][numCols];
        for (int i = 0; i < numRows; i++) 
            for (int j = 0; j < numCols; j++) 
                matrix[i][j] = board.get(i).charAt(j);

        // For each '*' in board, increment neighbors cells in matrix
        for (int i=0; i<numRows; i++) {
            String boardRow = board.get(i);
            
            // Range of row indexes for current cell neighborhood
            int rowStart = Math.max(i-1, 0);        // inclusive
            int rowEnd = Math.min(i+2, numRows);    // exclusive

            for (int j = 0; j < numCols; j++) {
                char cell = boardRow.charAt(j);
                if (cell != '*') 
                    continue;

                // Range of column indexes for current cell neighborhood
                int colStart = Math.max(j-1, 0);        // inclusive
                int colEnd = Math.min(j+2, numCols);    // exclusive
                
                for (int r=rowStart; r<rowEnd; r++) {
                    for (int c=colStart; c<colEnd; c++) {
                        char neighboor = matrix[r][c];
                        if (neighboor == '*')
                            continue;
                        if (neighboor == ' ')
                            matrix[r][c] = '1';
                        else 
                            matrix[r][c]++;
                    }
                }
            }
        }
        
        // Convert the matrix to List<String>
        return Arrays.stream(matrix)
            .map(String::valueOf)
            .collect(Collectors.toList());
    }

    List<String> withNumbers() {
        return boardWithNumbers;
    }

}

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?