[英]Method to rotate the specified row of a 4x4 array initialised with integers 0-15?
基本上我有一個2D拼圖,表示為4x4整數數組。 數組初始化為整數0..15我必須實現方法:
public static void play(int[][] puzzle)
方法應該將4x4整數數組作為其參數,該數組表示拼圖被加擾后的拼圖。 該方法應該使用重復的循環來實現:1。打印拼圖的當前狀態2.要求玩家輸入旋轉命令3.執行玩家請求的旋轉一旦拼圖重新進入其中,循環應該終止原始未加擾狀態,這意味着它必須按照數字0到15的順序返回到原始拼圖。
發生這種情況時,程序應顯示祝賀消息。
該程序應包括用戶輸入驗證。
每當用戶輸入無效時,程序應該打印警告無效輸入! 如果用戶輸入采用行或列旋轉兩個命令之一的形式,則用戶輸入有效。
拼圖的模板是:
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;
}
}
我測試了它,據我所知,它的效果很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.