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...
(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...
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...
Write a program fragment (not a complete program) which will perform the following task: The int...
Write a program fragment (not a complete program) which will perform the following task: The int variable m currently contains the number of minutes a basketball player played in their last game. Use an IF statement(s) to print out an appropriate message based on the following: If m is from 35 to 48, print the message "very tired" If m is from 10 to 34, print the message "little tired" If m is from 1 to 9, print the message...
   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
C++ program, I'm a beginner so please make sure keep it simple Write a program to...
C++ program, I'm a beginner so please make sure keep it simple Write a program to read the input file, shown below and write out the output file shown below. Use only string objects and string functions to process the data. Do not use c-string functions or stringstream (or istringstream or ostringstream) class objects for your solution. Input File.txt: Cincinnati 27, Buffalo 24 Detroit 31, Cleveland 17 Kansas City 24, Oakland 7 Carolina 35, Minnesota 10 Pittsburgh 19, NY Jets...
I'm trying to write a program that reads 3 heights of kids and puts them in...
I'm trying to write a program that reads 3 heights of kids and puts them in ascending order using if and else statements but i'm having trouble #include<stdio.h> int main() { int k1,k2,k3; printf("Enter height of kid #1 >"); scanf("%d",&k1); printf("Enter height of kid #2 >"); scanf("%d",&k2); printf("Enter height of kid #3 >"); scanf("%d",&k3); if(k3>k2>k1) { printf("In ascending order %d %d %d",k3,k2,k1); } else if(k3>k1>k2) { printf("In ascending order %d %d %d",k3,k1,k2); } else if(k2>k3>k1) { printf("In ascending order %d...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT