【问题标题】:How to place a string in a randomly-chosen locations in a 2D array如何将字符串放置在二维数组中随机选择的位置
【发布时间】:2012-03-01 08:16:23
【问题描述】:

我正在学习 Java 并从事基于网格的 guessingGame 项目,但我的 loadtargetGrid() 方法遇到了一些困难。

我有一个名为 Grid 的二维字符串数组,我想在六个随机选择的网格位置放置六个符号“X”。我不想对其他位置做任何事情,默认情况下将它们保留为 null。

    public class Grid
{
public static final int ROWS      = 5;      // number of rows
public static final int COLUMNS   = 5;      // number of columns
public static final int NUMBER_OF_TARGETS = 6; // number of targets in the grid

private String[][] grid;                // the grid itself, a 2-D array of String
private Random random;                  // random number generator

//Constructor
public Grid()
{
    grid = new String[ROWS][COLUMNS];
    random = new Random();
}

//method
public void loadTargetGrid()
{
      int counter = 0;
      while(counter < NUMBER_OF_TARGETS){
           int randRow = random.nextInt(ROWS - 1);
           int randColumn = random.nextInt(COLUMNS - 1);
           grid[randRow][randColumn] = "X";
           ++ counter;
      }
}

这就是我目前所拥有的。我尝试使用带计数器的 while 循环在 6 个随机位置放置“X”。它可以编译,但我不确定这是否有效,我不知道如何检查我的代码是否正确。

【问题讨论】:

  • 您不想从 ROWS 和 COLUMNS 中减去 1。 nextInt 方法已经将结果限制为 0 到 ROWS-1 或 0 到 COLUMNS-1。您收到的任何一个答案都可以让您避免重复的位置。
  • 没错!我以为 nextInt(int n) 方法会从 0 到 n 值,但 n 值是排他性的。谢谢

标签: java arrays random


【解决方案1】:

您可能无法将所有 6 个目标都放在网格上,因为您可能会两次获得同一个位置。试试这个:

int counter = 0;
while(counter < NUMBER_OF_TARGETS){
    int randRow = random.nextInt(ROWS - 1);
    int randColumn = random.nextInt(COLUMNS - 1);
    if (grid[randRow][randColumn] == null) {
        grid[randRow][randColumn] = "X";
        ++ counter;
    }
}

【讨论】:

    【解决方案2】:

    如果您多次获得相同的随机选择坐标,您将不会得到 NUMBER_OF_TARGETS 个不同的位置。您可以尝试类似

    int randRow, randColumn;
    do {
      randRow = random.nextInt(ROWS);
      randColumn = random.nextInt(COLUMNS);
    } while (grid[randRow][randColumn] != null);
    grid[randRow][randColumn] = "X";
    

    【讨论】:

    • 谢谢!我还没有学习 do..while 的东西,但我会研究一下。
    • ROWS - 1 和 COLUMNS - 1 不正确。 (我意识到你从 OP 复制了这些)。 nextInt(n) 的约定是它返回一个半开范围 [0..n) 内的 int。
    猜你喜欢
    • 1970-01-01
    • 2019-08-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    相关资源
    最近更新 更多