Home > Software design >  How to randomly update a selected element in a 2D array?
How to randomly update a selected element in a 2D array?

Time:11-11

So I am trying to assign a variable called lesserMonster, which is assigned to 1. I have a four-by-four array that prints all 0 and I want my code to randomly select one of the 0 in the four-by-four and replace it with the lesserMonster varible. Any clues?

So this method generates the four-by-four array:

public static void setup(int dungeon[][]){
        int lesserMonster = 2;
        int drangon = 1;
        //makes the dungeon.
        for(int i = 0; i < dungeon.length; i  ){
            for(int j = 0; j < dungeon[i].length; j  ){
                dungeon[i][j] = 0;
            }
        }
        pDungeon(dungeon);
    }

and the pDungeon array prints it:

public static void pDungeon(int dungeon[][]){
        for(int i = 0; i < dungeon.length; i  ){
            for(int j = 0; j < dungeon.length; j  ){
                System.out.print(dungeon[i][j]   " ");
            }
            System.out.println();
        }
    }

CodePudding user response:

This is a javascript solution, but should give you the basic idea;

const arrayRows = 4;
const arrayCols = 4;

const row = Math.floor(Math.random() * arrayRows);
const col = Math.floor(Math.random() * arrayCols);

dungeon[col][row] = lesserMonster;

CodePudding user response:

You can randomly select a row and a column to place your monster, for example:

int row = ThreadLocalRandom.current().nextInt(dungeon.length);
int column = ThreadLocalRandom.current().nextInt(dungeon[row].length);
dungeon[row][column] = lesserMonster;

Also, I would suggest to make lesserMonster and dragon static final fields of your class so you can access them from other methods. And in your pDungeon method it's better to use the same loop over j which you use in setup method:

for (int j = 0; j < dungeon[i].length; j  )

Right now you have j < dungeon.length which assumes the dungeon has a square shape.

  • Related