Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class Magic {
- public static void makeSquare(int n, int[][] anArray){
- int total, middle, start, end, currentX, currentY, i, j, k;
- total = n * n;
- middle = ((n + 1) / 2) - 1;
- start = 0;
- end = n - 1;
- currentX = start;
- currentY = middle;
- for (i = 1; i < total + 1; i++){
- int a, b;
- anArray[currentX][currentY] = i;
- if (currentX == 0 && currentY == end){
- currentX = currentX + 1;
- }
- else if (currentX == 0) {
- a = end;
- b = currentY + 1;
- if (anArray[a][b] != 0){
- currentX = currentX + 1;
- } else {
- currentX = a;
- currentY = b;
- }
- }
- else if (currentY == end){
- a = currentX - 1;
- b = start;
- if (anArray[a][b] != 0){
- currentX = currentX + 1;
- } else {
- currentX = a;
- currentY = b;
- }
- } else {
- a = currentX - 1;
- b = currentY + 1;
- if (anArray[a][b] != 0){
- currentX = currentX + 1;
- } else {
- currentX = a;
- currentY = b;
- }
- }
- }
- for (j = 0; j < end + 1; j++){
- for (k = 0; k < end + 1; k++){
- System.out.print(anArray[j][k]);
- if (k < end){
- System.out.print(" ");
- }
- }
- if (j < end){
- System.out.println("");
- }
- }
- }
- public static void main(String[] args) {
- Scanner myScanner = new Scanner(System.in);
- int check;
- check = myScanner.nextInt();
- int[][] anArray;
- anArray = new int[check][check];
- makeSquare(check, anArray);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment