简体   繁体   English

在Java中,如何使用特定数量的随机值初始化2d数组。

[英]In Java how can I initialize a 2d array with a specific amount of random values.

I'm making a simulation game where there are doodlebugs and ants and as the simulation goes on the doodlebugs try to eat the ants. 我正在制作一个模拟游戏,里面有涂鸦虫和蚂蚁,随着模拟的进行,涂鸦虫会尝试吃掉蚂蚁。 The issue I am running into is initializing the 2d array I've created. 我遇到的问题是初始化我创建的2d数组。 I need 100 ants and 5 doodlebugs to randomly be placed on the grid. 我需要100只蚂蚁和5个Doodlebug才能随机放置在网格上。 I've randomized the grid but just as a whole so I get a random amount of ants and doodlebugs. 我已经将网格随机化了,但是总体上如此,所以我得到了随机数量的蚂蚁和Doodlebug。 I'm also working with a smaller array just util I get this working. 我也正在使用较小的数组,直到我可以正常工作。 Any help would be much appreciated. 任何帮助将非常感激。

 Random rand = new Random(); 
int[][] cells = new int[10][10];

public void display() {

    for(int i=0; i<10; i++) {
        for(int j=0; j<10; j++) {
            cells[i][j] = (int) (Math.random()*3);

            if(cells[i][j] == 2) { // 2 = ants; 
                cells[i][j] = 4;
            }
            if(cells[i][j] == 1) { // 1 = doodlebugs 
                cells[i][j] = 3;
            }
            if(cells[i][j] == 0) {
                cells[i][j] = 0;
            }
        System.out.print(cells[i][j]);  
        }
        System.out.println();
    }
}

You created a 10x10 array, which means it has 100 positions, which means all positions should be occupied by ants? 您创建了一个10x10的数组,这意味着它有100个位置,这意味着所有位置都应该被蚂蚁占据吗? (because you told you need 100 ants - unless the same position can have more than 1 insect). (因为您告诉过您需要100只蚂蚁-除非同一个位置可以有1只以上的昆虫)。


Anyway, I think you're doing an "inverse" logic. 无论如何,我认为您正在执行“逆向”逻辑。 Think about what should be random and what should not. 考虑什么应该是随机的,什么不应该是随机的。 You're looping the entire array and calling random() to know what insect must be placed in each position, so you have no control on how many of each insect will be created. 您要遍历整个数组并调用random()来知道必须在每个位置放置哪种昆虫,因此您无法控制将要创建多少只昆虫。

If you need an exact number of ants and doodlebugs, those are fixed - you don't call random() to know if it's an ant or a dooblebug, you already know how many of them you need. 如果您需要确切数量的蚂蚁和Doodlebug,它们是固定的 -您无需调用random()即可知道它是蚂蚁还是or虫,您已经知道需要多少。 What must be random is their positions , so you should call random() to get the row and column positions, not the insect type. 它们的位置必须是随机的,因此应调用random()以获得行和列的位置,而不是昆虫的类型。

First of all, I'd create some classes to represent the insects and the cell: 首先,我将创建一些类来代表昆虫和细胞:

// enum type, better than "magic numbers"
public enum Insect {
    ANT,
    DOODLEBUG;
}

public class Cell {

    // the insect placed in this cell
    private Insect insect;

    public Cell() {
        // cell starts without any insect
        this.insect = null;
    }

    public Insect getInsect() {
        return insect;
    }

    public void setInsect(Insect insect) {
        this.insect = insect;
    }

    // check if cell already has an insect
    public boolean isOccupied() {
        return this.insect != null;
    }
}

Then I initialize the board: 然后,我初始化板:

int size = 10; // assuming a square
Cell[][] cells = new Cell[size][size];
// fill with empty cells
for (int i = 0; i < cells.length; i++) {
    for (int j = 0; j < cells[i].length; j++) {
        cells[i][j] = new Cell();
    }
}

And then I fill it with the insects: 然后我用昆虫填充它:

// how many ants? Just an example, change the value according to your needs
int nAnts = 8;
// how many doodlebugs? Just an example, change the value according to your needs
int nBugs = 2;

Random rand = new Random();

// place the ants
for (int i = 0; i < nAnts; i++) {
    int row, column;
    // get a random position that's not occupied
    do {
        row = rand.nextInt(size);
        column = rand.nextInt(size);
    } while (cells[row][column].isOccupied());

    // fill with ant
    cells[row][column].setInsect(Insect.ANT);
}

// place the doodlebugs
for (int i = 0; i < nBugs; i++) {
    int row, column;
    // get a random position that's not occupied
    do {
        row = rand.nextInt(size);
        column = rand.nextInt(size);
    } while (cells[row][column].isOccupied());

    // fill with doodlebug
    cells[row][column].setInsect(Insect.DOODLEBUG);
}

The for loops placing insects are a bit repetitive so you could also refactor them to a method. 放置昆虫的for循环有些重复,因此您也可以将它们重构为一种方法。

I also assumed that cells is a square, but if it's not, just create 2 variables for the number of rows and columns and change the code accordingly - the logic is the same, though. 我还假设cells是一个正方形,但是如果不是,则只需为行和列的数量创建2个变量,并相应地更改代码-尽管逻辑相同。

A simple way to do this would be to create one for loop that loops the same number of times as the maximum number of things you want (in this case, ants and doodlebugs). 一种简单的方法是创建一个for循环,该循环的循环次数与所需的最大事物数(在本例中为ant和doodlebug)相同。 In each iteration of the for loop, you can generate random coordinates for the thing. 在for循环的每次迭代中,您可以为事物生成随机坐标。 This equates to two for loops, one for ants and one for doodlebugs. 这相当于两个for循环,一个for蚂蚁,一个for doodlebug。

for (int i = 0; i < desiredNumOfAnts; i++)
{
     int randX = rand.nextInt(cells[i].length); // this generates a random X coordinate, up to the length of the current row
     int randY = rand.nextInt(cells.length); // this generates a random Y coordinate, according to the height of the array

     /* using these coordinates, insert a new ant into the cells */
}

See if you can figure out how to do the rest of this yourself! 看看您是否能自己解决剩下的事情!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM