Question

In: Computer Science

Hey! I'm stuck with this task from the Princeton course on Coursera. Write a program Minesweeper.java...

Hey! I'm stuck with this task from the Princeton course on Coursera.

Write a program Minesweeper.java that takes three integer command-line arguments m, n, and k and prints an m-by-n grid of cells with k mines, using asterisks for mines and integers for the neighboring mine counts (with two space characters between each cell). To do so,
Generate an m-by-n grid of cells, with exactly k of the mn cells containing mines, uniformly at random.
For each cell not containing a mine, count the number of neighboring mines (above, below, left, right, or diagonal).

I don't really know how to place the mines randomly in the two dimensional array that is the grid, nor how to count the number of neighbouring mines. I've been stuck for days now. Could someone help?

Solutions

Expert Solution

Hello here is the code for the above problem. Hope it helps. I have added comments for better understanding. If you are satisfied with the answer, do consider upvoting!

Minesweeper.java

import java.util.Random;
import java.util.Scanner;

public class Minesweeper {
  
   //returns true if the point is within bounds and has arr has '*' as value at that x,y.
   public static boolean issafe(char arr[][],int x,int y,int n,int m)
   {
       return x>=1 && x<=n && y>=1 && y<=m && arr[x][y] == '*';
   }
  
   //finds number of neighbours which are '*'.
   public static int findNeighbours(char arr[][],int x,int y,int n,int m)
   {
       int count = 0;
       if(issafe(arr,x-1,y,n,m))
           count++;
       if(issafe(arr,x-1,y+1,n,m))
           count++;
       if(issafe(arr,x,y+1,n,m))
           count++;
       if(issafe(arr,x+1,y+1,n,m))
           count++;
       if(issafe(arr,x+1,y,n,m))
           count++;
       if(issafe(arr,x+1,y-1,n,m))
           count++;
       if(issafe(arr,x,y-1,n,m))
           count++;
       if(issafe(arr,x-1,y-1,n,m))
           count++;
       return count;
   }
   public static void main(String[] args) {
       //using reader to take n,m,k as input;
       Scanner reader = new Scanner(System.in);
       //used to generate random numbers.
       Random r = new Random();
      
       System.out.println("Enter n");
       int n = reader.nextInt();
      
       System.out.println("Enter m");
       int m = reader.nextInt();
      
       System.out.println("Enter k");
       int k = reader.nextInt();
      
       //defining 2-d matrix arr[1-n][1-m];
       char arr[][] = new char[n+1][m+1];
       int tmp = k;
       int row_num = r.nextInt(n) + 1;
       int column_num = r.nextInt(m) + 1;
      
       //generating k mines randomly.
       while(tmp>0)
       {
           //keep generating row and column numbers till the time we have
           //a position which does not contain '*'.
           while(arr[row_num][column_num]=='*')
           {
               //generates random number between [1-n].
               row_num = r.nextInt(n)+1;
               //generates random number between [1-m].
               column_num = r.nextInt(m)+1;
           }
           //setting generated position as '*'.
           arr[row_num][column_num] = '*';
           tmp--;
       }
       for(int i=1;i<=n;i++)
       {
           for(int j=1;j<=m;j++)
           {
               if(arr[i][j]!='*')
               {
                   //function returns the number of neighbours which are '*';
                   int count = findNeighbours(arr,i,j,n,m);
                   //converts the number to char value. Ex: 2 is converted to '2';
                   arr[i][j] = (char)(count+48);
               }
           }
       }
      
       //printing the resulting 2-d matrix.
       System.out.println("Final result:");
       for(int i=1;i<=n;i++)
       {
           for(int j=1;j<=m;j++)
           {
               System.out.print(arr[i][j]+" ");
           }
           System.out.println();
       }
   }

}

OUTPUT:


Related Solutions

Hey, I'm stuck on this assignment for AP Comp Sci Java. I don't know how to...
Hey, I'm stuck on this assignment for AP Comp Sci Java. I don't know how to start. An array of String objects, words, has been properly declared and initialized. Each element of words contains a String consisting of lowercase letters (a–z). Write a code segment that uses an enhanced for loop to print all elements of words that end with "ing". As an example, if words contains {"ten", "fading", "post", "card", "thunder", "hinge", "trailing", "batting"}, then the following output should...
MIPS Program I'm trying to write a program that will take in two numbers from the...
MIPS Program I'm trying to write a program that will take in two numbers from the user and output the sum at the end. However, I keep getting very wrong answers. For example, I add 2 and 2 and get 268501000. Help would be appreciated. .data #starts data use userIn1:    .word 4 #sets aside space for input    userIn2:    .word 4 #sets aside space for input total:    .word 4 #sets space aside for input    request:   ...
I'm trying to write a feet to meters and centimeters program and I'm looking for a...
I'm trying to write a feet to meters and centimeters program and I'm looking for a little help so I can see how close I got. It should do the following: Write a convertToMetric class that has the following field: standard - holds a double, standard length value in feet. The class should have the following methods: Constructor - that accepts a length in feet (as a double) and stores it in the standard field. setStandard - accepts a standard...
(PLEASE SHOW STEPS TO SOLUTIONS. I'M GETTING STUCK IN MY PROCESS AND NOT SURE WHERE I'M...
(PLEASE SHOW STEPS TO SOLUTIONS. I'M GETTING STUCK IN MY PROCESS AND NOT SURE WHERE I'M GOING WRONG AND WHAT TO DO NEXT.) Skycell, a major European cell phone manufacturer, is making production plans for the coming year. Skycell has worked with its customers (the service providers) to come up with forecasts of monthly requirements (in thousands of phones) as shown in the table below (e.g., demand in Jan. is 1,000,000 units.) Manufacturing is primarily an assembly operation, and capacity...
Hello, I stuck doing c++ program The program will be recieved from the user as input...
Hello, I stuck doing c++ program The program will be recieved from the user as input name of an input file and and output.file. then read in a list of name, id# and score from input file (inputFile.txt) and initilized the array of struct. find the student with the higher score and output the students info in the output file obtain the sum of all score and output the resurl in output file. prompt the user for a name to...
Write a MATLAB program to simulate the Stuck in the Mud game, The following link contains...
Write a MATLAB program to simulate the Stuck in the Mud game, The following link contains the detail game description: https://www.activityvillage.co.uk/stuck-in-the-mud , with additional features that can: • Use five (5) 6-sided dice to automatically play the Stuck in the Mud game against a player. • Greet the player when the game starts. • Let the player to choose the number of rounds to play. Take care of the user input to ensure the program will not crash with inputs...
*****I'm using excel spreadsheet so I'm stuck on how to find a least square straight line...
*****I'm using excel spreadsheet so I'm stuck on how to find a least square straight line after linearizing the relationship. I do not have mini lab. I'm using excel.. The following are the average distances of the planets in the solar system from the sun. Planet No Planet Distance (millions of miles) 1 Pluto 47.163 2 Venus 67.235 3 Earth 92.960 4 Mars 141.61 5 Asteroids 313.00 6 Jupiter 483.60 7 Saturn 886.70 8 Uranus 1783.0 9 Neptune 2794.0 10...
   an unlimited maternal deduction applies when there is an outright Bisquick I'm stuck to a...
   an unlimited maternal deduction applies when there is an outright Bisquick I'm stuck to a longtime companion US citizen spouse surviving spouse who was a non US citizen or all of the above
Write a testing program (not sort.c from task 2) that contains a stack buffer overflow vulnerability....
Write a testing program (not sort.c from task 2) that contains a stack buffer overflow vulnerability. Show what the stack layout looks like and explain how to exploit it. In particular, please include in your diagram: (1) The order of parameters (if applicable), return address, saved registers (if applicable), and local variable(s), (2) their sizes in bytes, (3) size of the overflowing buffer to reach return address, and (4) the overflow direction in the stack (5) What locations within the...
Solve following tasks using MIPS Task Write a program that gets a number from user and...
Solve following tasks using MIPS Task Write a program that gets a number from user and displays “Even”, or “Odd. (If-else) Write a program that input a number from user displays each digit separately. For example if input is 3986, output is  6, 8, 9 ,3. (Loop) Write a program that converts a decimal number to binary. (Loop) Hint for Task 1 and Task 3.     Use, div $tdivident,$tdivider and mfhi $tdestination instructions. For example, Div $t1,$t2 will divide $t1...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT