woonie

Magic.java

Jan 24th, 2012
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.48 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class Magic {
  4.  
  5.     public static void makeSquare(int n, int[][] anArray){
  6.  
  7.         int total, middle, start, end, currentX, currentY, i, j, k;
  8.         total = n * n;
  9.         middle = ((n + 1) / 2) - 1;
  10.         start = 0;
  11.         end = n - 1;
  12.         currentX = start;
  13.         currentY = middle;
  14.        
  15.         for (i = 1; i < total + 1; i++){
  16.             int a, b;
  17.             anArray[currentX][currentY] = i;
  18.            
  19.             if (currentX == 0 && currentY == end){
  20.                 currentX = currentX + 1;
  21.             }
  22.             else if (currentX == 0) {
  23.                 a = end;
  24.                 b = currentY + 1;
  25.                 if (anArray[a][b] != 0){
  26.                     currentX = currentX + 1;
  27.                 } else {
  28.                     currentX = a;
  29.                     currentY = b;
  30.                 }
  31.             }
  32.             else if (currentY == end){
  33.                 a = currentX - 1;
  34.                 b = start;
  35.                 if (anArray[a][b] != 0){
  36.                     currentX = currentX + 1;
  37.                 } else {
  38.                     currentX = a;
  39.                     currentY = b;
  40.                 }
  41.             } else {
  42.                 a = currentX - 1;
  43.                 b = currentY + 1;
  44.                 if (anArray[a][b] != 0){
  45.                     currentX = currentX + 1;
  46.                 } else {
  47.                     currentX = a;
  48.                     currentY = b;
  49.                 }
  50.             }
  51.         }
  52.         for (j = 0; j < end + 1; j++){
  53.             for (k = 0; k < end + 1; k++){
  54.                 System.out.print(anArray[j][k]);
  55.                 if (k < end){
  56.                     System.out.print(" ");
  57.                 }
  58.             }
  59.             if (j < end){
  60.                 System.out.println("");
  61.             }
  62.         }
  63.     }
  64.     public static void main(String[] args) {
  65.         Scanner myScanner = new Scanner(System.in);
  66.        
  67.         int check;
  68.         check = myScanner.nextInt();
  69.        
  70.         int[][] anArray;
  71.         anArray = new int[check][check];
  72.  
  73.         makeSquare(check, anArray);
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment