如何将显式值随机分配给java中的2 d数组

时间:2017-08-31 17:05:37

标签: java multidimensional-array

我需要设置{0,.5,1,2,5}并随机填充nxm矩阵的值,我想我可以使用此代码

public static void main(String[] args) {
    //create the grid
    final int rowWidth = 10;
    final int colHeight = 10;

    Random rand = new Random();

    int [][] board = new int [rowWidth][colHeight];

        //fill the grid
        for (int[] board1 : board) {
            for (int col = 0; col < board1.length; col++) {
                board1[col] = rand.nextInt(5);
            }
        }

        //display output
        for (int[] board1 : board) {
            for (int j = 0; j < board1.length; j++) {
                System.out.print(board1[j] + " ");
            }
            System.out.println();

然后将每个数字{0,1,2,3,4}映射到{0,.5,1,2,5},然后重新绘制矩阵....是否有更好的方法来做到这一点...如何从一开始就用指定的数字随机填充矩阵?

1 个答案:

答案 0 :(得分:0)

你可以保持一个包含可能值的数组,然后从该数组中随机选择一个:

final int rowWidth = 10;
final int colHeight = 10;
final double[] possibleValues = {0.0, 0.5, 1.0, 2.0 ,5.0};

Random rand = new Random();

double[][] board = new double[rowWidth][colHeight];

for (double[] board1 : board) {
    for (int col = 0; col < board1.length; col++) {
        board1[col] = possibleValues[rand.nextInt(possibleValues.length)];
    }
}