Thursday, June 21, 2012

Magic Square



public class Magic {
      private int size = 3;

      public static void main(String[] args) {
            Magic magic = new Magic(1);
            magic.magic(1);
      }

      public Magic (int size) {
            setSize(2 * size + 1);
      }
     
      public void magic(int num) {
            int limit = getLimit();
            int current = getSize() / 2;

            int[] a = new int[limit];
            a[current] = num;
            int next = 0;

            for (int i = num + 1; i < num + limit; i++) {
                  next = next(current);
                  if (a[next] == 0) {
                        a[next] = i;
                  } else {
                        next = down(current);
                        a[next] = i;
                  }
                  current = next;
            }
            display(a);
      }
     
      public void display(int[] a){
            for(int i=0; i
                  if(i%getSize()==0){
                        System.out.println();
                  }
                  System.out.printf("%5d", a[i]);
            }
                 
      }

      public int next(int i) {
            return right(up(i));
      }

      public int up(int i) {
            i = i - getSize();
            if (i < 0) {
                  i += getLimit();
            }
            return i;
      }

      public int down(int i) {
            i = i + getSize();
            if (i > getLimit()) {
                  i -= getLimit();
            }
            return i;
      }

      public int right(int i) {
            i = i + 1;
            if (i % getSize() == 0) {
                  i = i - getSize();
            }
            return i;
      }

      public int left(int i) {
            if (i % getSize() == 0) {
                  i = i + getSize() - 1;
            } else {
                  i = i - 1;
            }
            return i;
      }

      public int getSize() {
            return size;
      }

      public void setSize(int size) {
            this.size = size;
      }

      public int getLimit() {
            return getSize() * getSize();
      }
}

No comments:

Post a Comment