[英]How to create a random matrix with all of its elements appear twice
我想生成一个元素范围为 1 到 8 的 4x4 矩阵。我知道 4x4 矩阵应该包含 16 个元素,这就是为什么我想让范围 (1-8) 在矩阵中出现两次,使所有元素使用随机 function 出现两次。
但是当我使用随机function时,我不知道如何控制一个数字的出现次数。 使用随机 function 创建矩阵会使数字只出现一次或两次以上。
请帮助我实现我想要的 output。到目前为止,这是我的代码:
int[][] mat = new int[4][4];
Random r = new Random();
for(int i = 0; i < 4; i++){
for(int j = 0; j < 4; j++){
mat[i][j] = r.nextInt(8);
}
}
for(int i=0; i<4; i++){
System.out.println(Arrays.toString(mat[i]));
}
每次我创建一个矩阵时,我都希望元素从 1 到 8,并且数字像这样出现两次,但随机出现。 就像我每次运行代码一样,模式应该会改变。
预计 output:
[8,7,4,6]
[5,4,1,3]
[8,1,2,2]
[5,3,6,7]
您可以将包含 1-8 个元素的数组打乱两次以获得 4x4 矩阵。 randomizeArray function 使用 random() function 每次随机打乱数组。
import java.util.*;
class test{
public static void main(String args[]){
int[][] mat = new int[4][4];
int[] data = {1,2,3,4,5,6,7,8};
data = randomizeArray(data);
// randomize array the first time for rows 1 and 2 of the 4x4 matrix
for(int i = 0 ; i < 4; i++){
if(i==2){data=randomizeArray(data);};
// randomize array the second time for rows 3 and 4 of the 4x4 matrix
for(int j = 0; j < 4; j++)
{
mat[i][j] = data[(i%2)*4+j];
}
}
for(int i=0; i<4; i++){
System.out.println(Arrays.toString(mat[i]));
}
}
public static int[] randomizeArray(int[] data) {
Random r = new Random();
for(int i = 0; i < data.length; i++){
int randomIndexSwap = r.nextInt(data.length);
int temp = data[randomIndexSwap];
data[randomIndexSwap] = data[i];
data[i] = temp;
}
return data;
}
}
这是一种创建随机矩阵的方法,其中所有元素都出现两次
import java.util.Random;
public class MatrixGenerator {
public static void main(String[] args) {
// Set the size of the matrix
int rows = 5;
int cols = 5;
// Create a random number generator
Random rand = new Random();
// Create the matrix
int[][] matrix = new int[rows][cols];
// Fill the matrix with random numbers
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// Generate a random number and store it in the matrix
int randomNumber = rand.nextInt();
matrix[i][j] = randomNumber;
// Store the same random number in another location in the matrix
// This will cause all elements to appear twice in the matrix
matrix[j][i] = randomNumber;
}
}
// Print the matrix to the console
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
在这段代码中,我们首先设置矩阵中的行数和列数。 然后我们创建一个 Random object,我们将使用它来生成随机数。
接下来,我们创建矩阵并使用嵌套循环用随机数填充它。 对于矩阵中的每个元素,我们生成一个随机数并将其存储在元素的位置。 然后我们将相同的随机数存储在对角线另一侧元素的相应位置。 这会导致所有元素在矩阵中出现两次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.