首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Java中,如何使用特定数量的随机值初始化2d数组。

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

Stack Overflow用户
提问于 2018-03-12 17:50:26
回答 1查看 271关注 0票数 0

我正在制作一个模拟游戏,游戏中有涂鸦虫和蚂蚁,随着模拟的进行,涂鸦虫试图吃掉蚂蚁。我遇到的问题是初始化我创建的2d数组。我需要100只蚂蚁和5只涂鸦虫随机地放在网格上。我已经把网格随机化了,但是作为一个整体,我得到了随机数量的蚂蚁和涂鸦虫。我也在处理一个更小的数组任何帮助都将不胜感激。

代码语言:javascript
复制
 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();
    }
}
EN

回答 1

Stack Overflow用户

发布于 2018-03-12 18:14:01

一个简单的方法是创建一个for循环,循环次数与您想要的最大次数相同(在本例中是蚂蚁和涂鸦虫)。在for循环的每一次迭代中,您都可以生成事物的随机坐标。这相当于两个循环,一个用于蚂蚁,另一个用于涂鸦。

代码语言:javascript
复制
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 */
}

看看你能不能自己弄明白怎么做剩下的事!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49241538

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档