用Java写循环位移方阵,使用一维数组储存,可以指定移位方向和移动位数,使用表格显示计算结果
时间: 2024-03-05 18:54:55 浏览: 122
好的,我可以为您提供一个Java程序来实现循环位移方阵。以下是代码和解释:
```java
import java.util.Arrays;
public class CircularShiftMatrix {
public static void main(String[] args) {
int size = 4; // 方阵大小
int shift = 2; // 移动位数
int[] matrix = new int[size * size]; // 一维数组储存方阵
// 初始化方阵
for (int i = 0; i < size * size; i++) {
matrix[i] = i + 1;
}
// 按指定移位方向和移动位数移动方阵
switch ("左") { // 指定移位方向,这里为左移
case "上":
matrix = shiftUp(matrix, size, shift);
break;
case "下":
matrix = shiftDown(matrix, size, shift);
break;
case "左":
matrix = shiftLeft(matrix, size, shift);
break;
case "右":
matrix = shiftRight(matrix, size, shift);
break;
}
// 显示计算结果
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print(matrix[i * size + j] + "\t");
}
System.out.println();
}
}
// 左移
public static int[] shiftLeft(int[] matrix, int size, int shift) {
int[] result = Arrays.copyOf(matrix, matrix.length);
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
int index = i * size + j;
int row = index / size;
int col = index % size;
int newRow = row;
int newCol = (col - shift + size) % size;
result[newRow * size + newCol] = matrix[index];
}
}
return result;
}
// 右移
public static int[] shiftRight(int[] matrix, int size, int shift) {
int[] result = Arrays.copyOf(matrix, matrix.length);
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
int index = i * size + j;
int row = index / size;
int col = index % size;
int newRow = row;
int newCol = (col + shift) % size;
result[newRow * size + newCol] = matrix[index];
}
}
return result;
}
// 上移
public static int[] shiftUp(int[] matrix, int size, int shift) {
int[] result = Arrays.copyOf(matrix, matrix.length);
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
int index = i * size + j;
int row = index / size;
int col = index % size;
int newRow = (row - shift + size) % size;
int newCol = col;
result[newRow * size + newCol] = matrix[index];
}
}
return result;
}
// 下移
public static int[] shiftDown(int[] matrix, int size, int shift) {
int[] result = Arrays.copyOf(matrix, matrix.length);
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
int index = i * size + j;
int row = index / size;
int col = index % size;
int newRow = (row + shift) % size;
int newCol = col;
result[newRow * size + newCol] = matrix[index];
}
}
return result;
}
}
```
这个程序实现了循环位移方阵的四个方向的移动。您可以通过修改代码中的`size`和`shift`值来改变方阵大小和移动位数,通过修改`switch`语句中的指定移位方向来改变移动方向。程序输出的是以表格形式显示的计算结果。
阅读全文