gpt4 book ai didi

java - 旋转用整数 0-15 初始化的 4x4 数组的指定行的方法?

转载 作者:太空宇宙 更新时间:2023-11-04 12:44:12 24 4
gpt4 key购买 nike

基本上我有一个 2D 谜题,它表示为 4x4 整数数组。数组用整数 0..15 初始化我必须实现该方法:

public static void play(int[][] puzzle)

方法应该将一个 4x4 整数数组作为参数,该数组代表打乱后的谜题。该方法应使用重复执行以下操作的循环来实现:1.打印拼图的当前状态2.要求玩家输入旋转命令3.执行玩家请求的轮换一旦拼图回到原来的未打乱状态,循环就应该终止,这意味着它必须按照数字 0 到 15 的顺序回到原来的拼图。

发生这种情况时,程序应该显示一条祝贺消息。

该程序应包括用户输入验证。

只要用户输入无效,程序就应该打印警告 Invalid input!如果用户输入采用行或列旋转这两个命令之一的形式,则该输入有效。

拼图的模板是:

public class Puzzle {

public static final int N = 4;
public static final int NUMBER_OF_ROTATIONS = 5;

public static void main(String[] args) {
int[][] puzzle = new int[N][N];
reset(puzzle);
test(puzzle);
reset(puzzle);
scramble(puzzle);
System.out.println("### Testing puzzle game play\n");
play(puzzle);
}

public static void print(int[][] puzzle) {
for (int[] row : puzzle) {
for (int elem : row) {
System.out.printf("%4d", elem);
}
System.out.println();
}
System.out.println();
}

public static void test(int[][] puzzle) {
System.out.println("### Testing reset method\n");
print(puzzle);
System.out.println("### Testing rotate methods\n");
print(puzzle);
for (int i = 0; i < N; i++) {
System.out.println("### rotateColumn(" + i + ")\n");
rotateColumn(puzzle, i);
print(puzzle);
System.out.println("### rotateRow(" + i + ")\n");
rotateRow(puzzle, i);
print(puzzle);
}
reset(puzzle);
System.out.println("### Testing random rotations\n");
print(puzzle);
for (int i = 0; i < 5; i++){
randomRotation(puzzle);
print(puzzle);
}
}

public static void reset(int[][] puzzle) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
puzzle[i][j] = i * N + j;
}
}

public static void scramble(int[][] puzzle) {
for (int i = 0; i < NUMBER_OF_ROTATIONS; i++) {
randomRotation(puzzle);
}
}




public static void rotateRow(int[][] arr, int row) {
for (int i= arr.length-1; i>0; i--) {
int r= (int) (Math.random() * (i+1)); int[] c = arr[i];
arr [i] = arr[r];
arr[r] = c;
}


}


// TODO: Implement method as specified in assignment brief

public static void rotateColumn(int[][] arr, int column) {
}


// TODO: Implement method as specified in assignment brief

public static void randomRotation(int[][] puzzle) {
}

// TODO: Implement method as specified in assignment brief

static void play(int[][] puzzle) {
}

}

正如您所看到的,我尝试实现旋转行方法,但是在运行它之后,整个数组而不是指定的行被更改。有人可以告诉我我做错了什么吗?谢谢你:)。

最佳答案

试试这个:

public static void rotateRow(int[][] arr, int row) {
int newCurrent = arr[row][arr.length - 1];
int nextCurrent;
for (int currentIndex = 0; currentIndex < arr.length; currentIndex++) {
nextCurrent = arr[row][currentIndex];
arr[row][currentIndex] = newCurrent;
newCurrent = nextCurrent;
}
}

我对其进行了测试,据我所知,它效果很好。

关于java - 旋转用整数 0-15 初始化的 4x4 数组的指定行的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36505028/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com