我如何编写一个数组生成器来生成某些列值中的数字?

How can I write an array generator that generates numbers in certain column values?

您好 :) 我写了这个数组生成器,想重写它,以便您可以设置各个列值的值范围。

举个例子:第一列是 0 或 1,它们右边的值是 3 或 7,其他列的值介于 0 和 1 之间(因此在所有数字的时刻)。

1; 3 ; 0.68618 ; 0.98135 ; 0.25489 ; ...

1; 7; 0.32481 ; 0.25871 ; 0.14697 ; ...

0; 7; 0.96125 ; 0.36815 ; 0.24863 ; ...

......

public class scratch{

    public static void main(String[] args) {
        double values[][] = new double[10][19];
        for (int i = 0; i < values.length; i++) {

            for (int j = 0; j < values[i].length; j++) {

                values[i][j] = ((double) (Math.random()));
                System.out.print(values[i][j]+" ; ");
            }
            System.out.println();

        }
    }
}

PS: 请原谅我的英语不好

只是在迭代时检查列的索引,第一列是 j == 0 时,第二列是 j == 1 时。要在 0 和 1 之间或 3 和 7 之间交替,只需创建一个随机数,如果它小于 0.5,则取 0,如果不是,则取 1(或分别取 3 或 7)

public static void main(String[] args) {
    double values[][] = new double[10][19];
    for (int i = 0; i < values.length; i++) {
        for (int j = 0; j < values[i].length; j++) {
            if(j==0){
                values[i][j] = Math.random() < 0.5 ? 0 : 1;
            }
            else if(j==1){
                values[i][j] = Math.random() < 0.5 ? 3 : 7;
            }
            else{
                values[i][j] =  Math.random();  // to round it to 4 decimal places: Math.floor(Math.random() * 10000) / 10000;                
            }
            System.out.print(values[i][j]+" ; ");
        }
        System.out.println();
    }
}

编辑

你可以扩展这个方法

if(j==0){
    values[i][j] = Math.random() < 0.5 ? 0 : 1;
}

从四个数字中选择一个(在 [23, 42, 69, 1001] 之间),方法如下:

if(j==0){
    double x = Math.random();
    values[i][j] = x < 0.25 ? 23 : x < 0.5 ? 42 : x < 0.75 ? 69 : 1001;
}

但这很快就会变得难以辨认,尤其是当您以后想从更多号码中进行选择时。因此,我建议您将可能的值存储在一个数组中,并随机 select 一个索引。这样你就可以在必要时添加更多的值,而不需要每次都更改代码:

if(j==0){                
    int[] myValues = {23, 42, 69, 1001};
    values[i][j] = myValues[ (int) (Math.random()*myValues.length)];
}