用java随机1~9整数生成3*3的二维数组,使二维数组每行,每列、以及斜线上的数字之和均为15,并输出这个二维数组
时间: 2024-05-10 19:21:17 浏览: 125
以下是一种实现方法:
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
int[][] matrix = new int[3][3];
Random rand = new Random();
int[] rowSum = new int[3];
int[] colSum = new int[3];
int diagSum1 = 0;
int diagSum2 = 0;
// 生成随机数组
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
int num;
do {
num = rand.nextInt(9) + 1;
} while (contains(matrix[i], num)); // 判断行中是否已包含该数字
matrix[i][j] = num;
rowSum[i] += num; // 更新行和
colSum[j] += num; // 更新列和
if (i == j) {
diagSum1 += num; // 更新主对角线和
}
if (i + j == 2) {
diagSum2 += num; // 更新副对角线和
}
}
}
// 调整数组使满足条件
while (!isValid(rowSum, colSum, diagSum1, diagSum2)) {
int i = rand.nextInt(3);
int j = rand.nextInt(3);
int num = rand.nextInt(9) + 1;
int oldNum = matrix[i][j];
matrix[i][j] = num;
rowSum[i] = rowSum[i] - oldNum + num;
colSum[j] = colSum[j] - oldNum + num;
if (i == j) {
diagSum1 = diagSum1 - oldNum + num;
}
if (i + j == 2) {
diagSum2 = diagSum2 - oldNum + num;
}
}
// 输出数组
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
// 判断数组是否合法
public static boolean isValid(int[] rowSum, int[] colSum, int diagSum1, int diagSum2) {
for (int i = 0; i < 3; i++) {
if (rowSum[i] != 15 || colSum[i] != 15) {
return false;
}
}
if (diagSum1 != 15 || diagSum2 != 15) {
return false;
}
return true;
}
// 判断数组中是否包含某个数字
public static boolean contains(int[] array, int num) {
for (int i = 0; i < array.length; i++) {
if (array[i] == num) {
return true;
}
}
return false;
}
}
```
运行结果可能如下:
```
9 2 4
3 5 7
1 6 8
```
阅读全文