在二维数组的随机位置放置一个数字

3
我有一个二维数组,它有5行5列。我想在这个2D数组中的8个随机位置(选择一个随机行和列)放置字符'1'。
我的做法是调用Random类并生成0到4之间的数字(对于数组的5个位置),然后我有两个for循环运行8次(对于我想要的8个随机位置),一个循环遍历行,另一个循环遍历列。
这是我目前所拥有的代码:
char[][] battleship = new char[5][5];
//I didn't include this but I have a for loop that populates all the rows and columns with a char of '0'
        Random random = new Random();
        int randomNum = random.nextInt(4);

        for (int i = 0; i < 8; i++)
        {
              for (int o = 0; o < 8; o++)
        {

            battleship[randomNum][randomNum] = '1';

        }
        }

我遇到的问题是“1”不是随机地分布在8个位置上,而是连续地出现在5个位置上。
如何纠正这个问题?
下面是输出的示例:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0
“1”没有随机分布在8个位置上。
我做错了什么?

1
我不会对你的实际问题发表评论,因为下面有几个有效的解决方案,但你应该让你的for循环计数和数组大小匹配。现在你的“battleship”数组有25个元素,但你正在尝试循环遍历64个元素。 - mittmemo
1
我不相信发布的代码能够创建一个具有那些内容的数组。 - Andy Turner
1
根据您发布的代码,您应该有一个“1”。您如何打印数组?您对它有更多的操作吗? - Guy
3个回答

4

如果嵌套循环每次运行8次,那么它将迭代64次。然而,你不需要使用嵌套循环来做到这一点。其中一种简单的方法是使用while循环,并在分配完8个随机点之前依次分配这8个点:

int occupiedSpots = 0;
Random random = new Random();

while(occupiedSpots < 8){
    int x = random.nextInt(array.length);
    int y = random.nextInt(array[0].length);
    if(battleship[x][y] == 0){
        battleship[x][y] = 1;
        occupiedSpots++;
    }
}

同时确保在每次迭代中生成新的随机数,否则将始终使用相同的随机值。

使用while循环还可以确保8个位置都在不同的位置上。如果您只是使用for循环实现而没有检查,有可能某些位置会落在同一位置两次。


3

您在循环之前获得了一个随机数,因此它不会改变。基本上,randomNum 变量只被滚动和赋值了一次 - 您应该多次调用 nextInt 方法。请尝试以下代码:

    for (int i = 0; i < 8; i++) {
        int randomX = random.nextInt(battleship.length);
        int randomY = random.nextInt(battleship[randomX].length);
        battleship[randomX][randomY] = '1';
    }

请注意,这并没有解决碰撞的问题 - 你可能会不幸地多次得到相同的位置而只填充1-7个位置。
nextInt(int)的文档中可以看到: 返回一个伪随机、均匀分布的int值,介于0(包括)和指定值(不包括)之间,从此随机数生成器的序列中提取。

1
是的,但这并不能解释连续的1。 - user3437460
打印方法出错了,我猜测是这个原因。 - Czyzby
实际上,这段代码存在一些问题。random.nextInt(4)将生成0-3之间的随机值。但是OP有5行5列。另一个问题是可能在同一位置上获得多个1。 - user3437460
@user3437460 没错,我专注于解决生成多个随机值的问题,并复制了一些原始代码。 - Czyzby

0
我会采取不同的方法。如果你假装你的5x5 2D数组实际上是一个长的25元素一维数组,那么你需要做的基本上就是产生8个介于0和25之间的不同数字。
你的代码也不能保证8个随机数都不同。
试试这个:
    // Initialize random number array
    int[] positions = new int[25];
    for (int i = 0; i < 25; i++) {
        positions[i] = i;
    }

    char[][] battleship = new char[5][5];

    // Fill the battleship field
    for (int i = 0; i < 8; i++) {
        int random = (int)(Math.random() * (25 - i - 1));
        int position = positions[random];
        positions[random] = positions[25 - i - 1];
        int row = position / 5;
        int col = position % 5;
        battleship[row][col] = '1';
    }

    // Show the field
    for (int row = 0; row < 5; row++) {
        for (int col = 0; col < 5; col++) {
            System.out.print(battleship[row][col] + " ");
        }
        System.out.println();
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接