2017年9月25日 星期一

JAVA-魔方陣


import java.util.*;

public class magic_square {

 public static void main(String[] args) {
  boolean number = false;
  int x = 0;
  do {
   try {
    System.out.print("Please input a odd number and number >= 3: ");
    Scanner sc = new Scanner(System.in);
    x = sc.nextInt();
   }
   catch (Exception e) {
   }
   if (x >= 3 && x % 2 != 0) {
    break;
   }
  } while (!number);
  int[][] arsq = new int[x][x];
  arsq[0][x/2] = 1;
  int sum = x * x;
  int count = 2;
  int a = x-1;
  int b = x/2 + 1;
  arsq[a][b] = count;
  int a_ne = a - 1;
  int b_ne = b + 1;
  do {
   count++;
   if (a_ne < 0) {
    if (b_ne > (x-1)) {
     a_ne += 2;
     b_ne -= 1;
    }
    else {
     a_ne = x-1;
    }
   }
   if (b_ne > (x-1)) {
    b_ne = 0;
   }
   if (arsq[a_ne][b_ne] != 0) {
    a_ne += 2;
    b_ne -= 1;
    arsq[a_ne][b_ne] = count;
   }
   else {
    arsq[a_ne][b_ne] = count;
   }
   a_ne -= 1;
   b_ne += 1;
  } while (count < sum);
  if (sum > 10) {
   for (int i = 0; i <= (x-1); i++) {
    for (int j = 0; j <= (x-1); j++) {
     System.out.printf("%03d ", arsq[i][j]);
    }
    System.out.println();
   }
  }
  else {
   for (int i = 0; i <= (x-1); i++) {
    for (int j = 0; j <= (x-1); j++) {
     System.out.print(arsq[i][j] + " ");
    }
    System.out.println();
   }
  }
 }
}

沒有留言:

張貼留言