用java输出循环位移方阵,生成随机数序列,使用一维数组存储,将元素序列输出成循环位移方阵,指定位移方向和移动位数
时间: 2023-05-25 21:05:57 浏览: 74
以下是Java代码实现:
```java
import java.util.Random;
public class CircularShiftMatrix {
public static void main(String[] args) {
int n = 10; // 方阵大小为 10 * 10
int[] arr = generateRandomArray(n * n); // 生成随机数序列
printArray(arr); // 输出随机数序列
int k = 5; // 循环移动 5 位
String direction = "left"; // 指定向左移动
int[][] matrix = generateCircularShiftMatrix(arr, n, k, direction); // 生成循环位移方阵
printMatrix(matrix); // 输出循环位移方阵
}
// 生成随机数序列
public static int[] generateRandomArray(int n) {
int[] arr = new int[n];
Random random = new Random();
for (int i = 0; i < n; i++) {
arr[i] = random.nextInt(100);
}
return arr;
}
// 输出一维数组
public static void printArray(int[] arr) {
int n = (int) Math.sqrt(arr.length);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.printf("%-5d", arr[i * n + j]);
}
System.out.println();
}
System.out.println();
}
// 生成循环位移方阵
public static int[][] generateCircularShiftMatrix(int[] arr, int n, int k, String direction) {
int[][] matrix = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = arr[i * n + j];
}
}
if (direction.equals("left")) { // 向左移动 k 位
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = matrix[i][(j + k) % n];
}
}
} else if (direction.equals("right")) { // 向右移动 k 位
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = matrix[i][(j + n - k) % n];
}
}
}
return matrix;
}
// 输出二维数组
public static void printMatrix(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.printf("%-5d", matrix[i][j]);
}
System.out.println();
}
}
}
```
输出结果为:
```
29 56 76 46 49 51 62 96 55 91
91 95 43 21 57 61 61 70 92 77
4 85 94 97 12 59 77 17 29 58
94 87 27 78 72 34 6 50 62 97
58 45 97 83 48 0 32 7 98 43
8 61 61 42 4 25 37 59 40 88
38 5 60 64 91 77 89 62 1 59
56 11 37 47 81 12 50 45 3 73
15 79 51 55 87 96 91 34 2 13
80 96 16 34 17 0 62 13 26 73
51 62 96 55 91 29 56 76 46 49
61 61 70 92 77 91 95 43 21 57
59 77 17 29 58 4 85 94 97 12
34 6 50 62 97 94 87 27 78 72
0 32 7 98 43 58 45 97 83 48
25 37 59 40 88 8 61 61 42 4
77 89 62 1 59 38 5 60 64 91
12 50 45 3 73 56 11 37 47 81
96 91 34 2 13 15 79 51 55 87
0 62 13 26 73 80 96 16 34 17
```