Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program Minesweeper.java that takes 2 integers from the user m and n, an

ID: 3815355 • Letter: W

Question

Write a program Minesweeper.java that takes 2 integers from the user m and n, and produces an m-by-n boolean array where each entry is occupied with probability 0.25. In the minesweeper game, occupied cells represent bombs and empty cells represent safe cells. Print the array using an asterisk for bombs and a period for safe cells. Then, replace each safe square with the number of neighboring bombs (above, below, left, right, or diagonal) and print the solution.

*

*

.

.

.

.

.

.

.

.

.

*

.

.

.

*

*

1

0

0

3

3

2

0

0

1

*

1

0

0

Try to write your code so that you have as few special cases as possible to deal with, by using an

(m+2)-by-(n+2) boolean array.

*

*

.

.

.

.

.

.

.

.

.

*

.

.

.

*

*

1

0

0

3

3

2

0

0

1

*

1

0

0

Explanation / Answer

public class Minesweeper {
public static void main(String[] args) {
int m = Integer.parseInt(args[0]);
int n = Integer.parseInt(args[1]);
double p = Double.parseDouble(args[2]);
boolean[][] bombs = new boolean[m+2][n+2];
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
bombs[i][j] = (Math.random() < p);
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++)
if (bombs[i][j]) System.out.print("* ");
else System.out.print(". ");
System.out.println();
}
int[][] sol = new int[m+2][n+2];
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
for (int ii = i - 1; ii <= i + 1; ii++)
for (int jj = j - 1; jj <= j + 1; jj++)
if (bombs[ii][jj]) sol[i][j]++;
System.out.println();
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (bombs[i][j]) System.out.print("* ");
else
System.out.print(sol[i][j] + " ");
}
System.out.println();
}

}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote