summaryrefslogtreecommitdiff
path: root/algorithms/magic_coxeter.c
blob: 17d24f6be4016c3f238db3bc285fe7cfb5460510 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <stdio.h>
#include <stdlib.h>
#include <math.h>


void
magic(unsigned int n)
{
  int m[n*n];

  unsigned int i;
  for (i=0; i<n*n; i++) {
    m[i] = 0;
  }

  int z, pos=n/2, npos;
  for (z=1; z<=n*n; z++) {
    m[pos] = z;
    if(pos%n == 0) {
      if(pos == 0) {
        npos = n*n-1;
      } else {
        npos = pos-1;
      }
    } else {
      if(pos-n-1 < 0) {
        npos = (n*n-1) - abs(n-pos);
      } else {
        npos = pos-n-1;
      }
    }
    if(m[npos] != 0) {
      npos = pos+n;
    }
    pos = npos;
  }

  unsigned int j;
  for(j=0; j<n*n; j++) {
    printf("\t%d\t",m[j]);
    if((j+1)%n==0 && j!=0) {
      printf("\n");
    }
  }
}

int
main(int argc, char **argv)
{
  if(argc!=2) {
    printf("Usage: %s <n>\n", argv[0]);
    exit(1);
  }
  int n = atoi(argv[1]);
  if(n%2==0) {
    printf("n has to be odd\n");
    exit(1);
  }
  magic(n);

  return 0;
}