Last active
August 29, 2015 14:01
-
-
Save HabaCo/11dab65f5bfa8db67055 to your computer and use it in GitHub Desktop.
魔術方塊
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* ========== 魔術方塊 ========== */ | |
| public class Homework3 { | |
| public static void main(String[] args) { | |
| int size = 5; // 可指定任意奇數 | |
| int[][] array = new int[size][size]; | |
| int count=1; | |
| int i=size-1,j=size/2; // 數字 1 的初始位置 | |
| array[i][j] = count++; // 將 1 放入初始位置 | |
| while(count<=size*size){ | |
| /** -------------------------------------- | |
| i % 最大值 -> 避免超過最大值 | |
| 令 最大值 = 5; | |
| eg.若 i = 5 則 i % 5 = 0 -> 回到第0個 | |
| == j 同理 | |
| -----------------------------------------*/ | |
| if (array[(i+1)%size][(j+1)%size]!=0) // 若下一個位置非空白(已有數字) | |
| i=(i+size-1)%size; // i 往上移一格 : (i+size-1) % size 避免上移超過頂端 | |
| else { | |
| i=(i+1)%size; | |
| j=(j+1)%size; | |
| } | |
| array[i][j] = count++; // 將目前第 n 個數放入陣列並使 n+1 | |
| } | |
| for (i=0; i<size; i++){ | |
| for (j=0; j<size; j++){ | |
| System.out.print(array[i][j]+" "); | |
| if (array[i][j]<10) System.out.print(" "); | |
| } | |
| System.out.println(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment