Home > Enterprise >  how do i populating an array with certain values in random spots JAVA
how do i populating an array with certain values in random spots JAVA

Time:10-18

public static void main(String[] args) {
        int castleTiles[][] = new int[8][8];

        for(int i = 0; i < castleTiles.length; i  ) {
            for(int j = 0; j < castleTiles[i].length; j  ) {
                castleTiles[i][j] = 0;
            }
        }




    for(int i = 0; i < castleTiles.length; i  ) {
        for(int j = 0; j < castleTiles[i].length; j  ) {
            System.out.printf("=", castleTiles[i][j]);
        }
        System.out.println();
    }


}

I need to insert the number 1 5 times in 5 random different spots in the array and the number 2 once at a random spot in the array

CodePudding user response:

enter image description here

 import java.util.Random;
    
    public class HelloWorld{
    
         public static void main(String[] args) {
            int castleTiles[][] = new int[8][8];
    
            for(int i = 0; i < castleTiles.length; i  ) {
                for(int j = 0; j < castleTiles[i].length; j  ) {
                    castleTiles[i][j] = 0;
                }
            }
    
    
    
    Random rn = new Random();
    
    for(int i =0; i < 5; i  )
    {
        int x = rn.nextInt(7)   0;
        int y = rn.nextInt(7)   0;
        castleTiles[x][y] = 1;
    }
    
        int x = rn.nextInt(7)   0;
        int y = rn.nextInt(7)   0;
        castleTiles[x][y] = 2;
    
    
    
        for(int i = 0; i < castleTiles.length; i  ) {
            for(int j = 0; j < castleTiles[i].length; j  ) {
                System.out.printf("=", castleTiles[i][j]);
            }
            System.out.println();
        }
    
    
    }
    }

CodePudding user response:

First, there's no need to set 0 to castleTiles array upon its creation, int arrays are filled with 0 by default.

Next, it may be better to create an array/list of the spot values to be added to the tile (e.g. {1, 1, 1, 1, 1, 2}).

And the last, when populating the array, we should check if we put the spot into an empty cell:

int castleTiles[][] = new int[8][8];

int[] spots = {1, 1, 1, 1, 1, 2};

Random random = new Random();
for (int s : spots) {
    while (true) {
        int r = random.nextInt(64);
        int x = r / 8;
        int y = r % 8;
        if (castleTiles[x][y] == 0) {
            castleTiles[x][y] = s;
            break;
        }
    }
}

After displaying . instead of 0 the casteTiles may look as follows:

for(int i = 0; i < castleTiles.length; i  ) {
    for(int j = 0; j < castleTiles[i].length; j  ) {
        System.out.print("  "   (castleTiles[i][j] == 0 ? "." : Integer.toString(castleTiles[i][j])));
    }
    System.out.println();
}
  .  .  .  .  .  .  .  1
  .  .  .  .  .  2  .  .
  .  .  1  .  .  .  .  .
  .  .  .  .  .  .  .  .
  1  .  1  .  .  .  .  .
  .  .  .  .  .  .  .  .
  .  1  .  .  .  .  .  .
  .  .  .  .  .  .  .  .
  • Related