简体   繁体   English

创建对称的二维数组

[英]Creating a symmetrical 2D array

I've been racking my brains over something that must be incredibly simple, as I've not seen it answered anywhere (or I'm very bad at searching). 我一直在思考一些必须非常简单的事情,因为我没有看到它在任何地方都可以回答(或者我很不擅长搜索)。

I want to create a symmetrical 2D array, filled with random numbers from 1 to 100 inclusive... here is what I've got so far 我想创建一个对称的2D数组,填充从1到100(含1和100)之间的随机数...这是到目前为止的结果

int n = 3; int n = 3; int rangeOfWeights = 100; int rangeOfWeights = 100;

    double[][] array = new double[n][n];
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++) {
            array[i][j] = rand.nextInt((rangeOfWeights)+1);         
        }
    }

At the moment, this is giving results like: 目前,结果如下:

44 45 32 
9 31 53 
25 48 74 

when actually the kind of result I want is: 实际上我想要的结果是:

0 34 32
34 0 23
32 23 0

As you defined, you're trying to create a 2D array where array[i][j] == array[j][i] . 如您所定义,您尝试创建2D数组,其中array[i][j] == array[j][i] You could a pair of nested loops where one iterates up to the array's size and the other up to the outer array's counter, and in each iteration set the value of the two symmetrical values: 您可以使用一对嵌套循环,其中一个循环迭代到数组的大小,另一个迭代到外部数组的计数器,并在每次迭代中设置两个对称值的值:

double[][] array = new double[n][n];
for(int i = 0; i < n; i++) {
    for(int j = 0; j < i; j++) {
        int value = rand.nextInt((rangeOfWeights)+1);         
        array[i][j] = value;
        array[j][i] = value;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM