0

Hello so am trying to create a 2D array of int with random number of rows and columns and a random starting and ending points using java to apply the A* algorithm on it. When i add {S} and {E} to define the tow points and print it there are numbers outside of the 2D array printed.

   `Random rand = new Random();
int min = 2, max = 10; 
    // a random number of rows and columns  
int a = (int)(Math.random() * (max - min + 1)) + min;
    // the location of the starting point.  
int row_start = rand.nextInt(a);
int col_start = rand.nextInt(a);
    // the location of the ending point.
int row_end = rand.nextInt(a);
int col_end = rand.nextInt(a);
    
int [][] M = new int [a][a];
public void create() {
    //empty: 0; grass: 1; sand: 2; water: 3; wall: 4.
    for (int i = 0; i < a; i++) {
        for (int j = 0; j < a; j++) {
            M[i][j] =   rand.nextInt(5);
        }
    }
    
    for (int i = 0; i < a; i++) {
        for (int j = 0; j < a; j++) {
            System.out.print(" " +M[i][j] + "\t");
            if(row_start == i && col_start == j) {
                System.out.print("{S}" + "\t");
            }
            if(row_end == i && col_end == j) {
                System.out.print("{E}" + "\t");
            }
        }
        System.out.print("\n");
    }

}`

the output looks like this:

 1   0   4   0  
 2  {S}  1   2   2  
 4   4  {E}  0   3  
 2   0   3   3  

the 2 and 3 shouldn't appear there.

1
  • Don't System.out.print(" " +M[i][j] + "\t"); when printing {S} or {E} ?? You can use if/else if/else. Commented Feb 10, 2023 at 14:58

1 Answer 1

1

The problem is that you always print m[i][j].

What you need is to only print m[i][j] when i and j are not S and E positions. When i and j are S and E positions, print S or E. Otherwise, print m[i][j].

            if(row_start == i && col_start == j) {
                System.out.print("{S}" + "\t");
            } else if(row_end == i && col_end == j) {
                System.out.print("{E}" + "\t");
            } else {
                System.out.print(" " +M[i][j] + "\t");
            }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.