【问题标题】:Fill array with zero in random places在随机位置用零填充数组
【发布时间】:2021-12-12 10:53:10
【问题描述】:

所以,我要做的是在随机位置用零填充 2D 数组特定次数。假设它必须是 90 个位置的数组中的 20 个零。到目前为止我所做的是声明一个二维数组并用随机数填充它。我的下一个想法是简单地选择随机位置并用零替换它们。知道我该怎么做吗?

int[][] myboard = new int[9][9];
    for (int i = 0; i < myboard.length; i++) {
        for (int j = 0; j < myboard[i].length; j++) {
            myboard[i][j] = (int) (Math.random() * 10);
        }
    }

【问题讨论】:

  • 您知道如何循环多次,您知道如何获取特定范围内的随机数,您知道如何使用数字访问数组中的单元格...我不确定您是什么'在问。

标签: java arrays multidimensional-array


【解决方案1】:

这是实现目标的一种相当简单的方法,但它应该可以完成工作。所以你需要得到每一行的长度。完成后,您可以调用一个函数,该函数将为您提供某个起点和行长之间的随机数。这是一些代码示例,向您展示我的意思:

import java.util.concurrent.ThreadLocalRandom;
import java.util.Arrays;


public class Example {
    
    public static void main(String []args) {
        int[][] myboard = new int[9][9];
        
        for (int i = 0; i < myboard.length; i++) {
        for (int j = 0; j < myboard[i].length; j++) {
                // fill the row with random vals
                myboard[i][j] = GetRandomNumber(0, myboard[i].length);
            }
            // sneak as much zeros as your heart content
            int random = GetRandomNumber(0, myboard[i].length);
            myboard[i][random] = 0;
        }
        
        System.out.println(Arrays.deepToString(myboard));
    }
     
    private static int GetRandomNumber(int min, int max) {
        /*
            min is the start point
            max is the curr row len
        */
        return ThreadLocalRandom.current().nextInt(min, max);
    }
}
 

【讨论】:

    【解决方案2】:

    伪代码如下所示:

    while (num_zeros_filled < 20):
       row = random()%total_rows
       col = random()%total_cols
       if (arr[row][col] == 0): # already filled in with 0
           continue
       else:
           arr[row][col] = 0
           num_zeros_filled += 1
    
    

    然而,如果只生成那些已经用 0 填充的单元格,理论上这可能会花费无限时间。更好的方法是将二维数组映射到一维数组,然后仅采样从那些还没有被 0 填充的单元格中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-04
      • 2011-01-23
      • 1970-01-01
      • 2013-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多