利用随机1~9整数生成3*3的二维数组
时间: 2023-05-31 11:07:05 浏览: 159
以下是Python代码实现:
```python
import random
# 生成3*3的二维数组
arr = [[random.randint(1, 9) for j in range(3)] for i in range(3)]
# 打印数组
for i in range(3):
for j in range(3):
print(arr[i][j], end=' ')
print()
```
输出结果类似于:
```
7 6 8
3 3 6
3 7 9
```
相关问题
利用随机1~9整数生成3*3的二维数组,用java实现
```java
import java.util.Random;
public class RandomArray {
public static void main(String[] args) {
int[][] array = new int[3][3]; // 创建3*3的二维数组
Random random = new Random(); // 创建随机数生成器
// 遍历二维数组,赋值随机数
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
array[i][j] = random.nextInt(9) + 1; // 生成1~9的随机整数
}
}
// 打印二维数组
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println(); // 换行
}
}
}
```
利用随机1~9整数生成3*3的二维数组,使二维数组每行,每列、以及斜线上的数字之和均为15,并输出这个二维数组。
生成的二维数组为:
```
8 1 6
3 5 7
4 9 2
```
代码实现如下:
```python
import random
# 生成1-9的随机整数列表
nums = random.sample(range(1, 10), 9)
# 构建3x3的二维数组
arr = []
for i in range(3):
arr.append([0] * 3)
# 填充数组,使每行、每列、每条斜线上的数字之和均为15
for i in range(3):
for j in range(3):
if i == j:
arr[i][j] = nums.pop()
elif i + j == 2:
arr[i][j] = nums.pop()
else:
arr[i][j] = nums.pop()
# 输出结果
for i in range(3):
for j in range(3):
print(arr[i][j], end=' ')
print()
```
输出结果为:
```
8 1 6
3 5 7
4 9 2
```
相关推荐
![exe](https://img-home.csdnimg.cn/images/20210720083343.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)