A magic square is an   N×N  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   and   both diagonals are equal to the same sum   (which is called the magic number or magic constant).

A magic square of doubly even order has a size that is a multiple of four   (e.g.     4, 8, 12).

This means that the subsquares also have an even size, which plays a role in the construction.



1
2
62
61
60
59
7
8


9
10
54
53
52
51
15
16


48
47
19
20
21
22
42
41


40
39
27
28
29
30
34
33


32
31
35
36
37
38
26
25


24
23
43
44
45
46
18
17


49
50
14
13
12
11
55
56


57
58
6
5
4
3
63
64



Task
Create a magic square of   8 × 8.



Related tasks
 Magic squares of odd order
 Magic squares of singly even order



See also

 Doubly Even Magic Squares (1728.org)


def double_even_magic_square(n)
  raise ArgumentError, "Need multiple of four" if n%4 > 0
  block_size, max = n/4, n*n
  pre_pat = [true, false, false, true,
             false, true, true, false]
  pre_pat += pre_pat.reverse
  pattern = pre_pat.flat_map{|b| [b] * block_size} * block_size
  flat_ar = pattern.each_with_index.map{|yes, num| yes ? num+1 : max-num}
  flat_ar.each_slice(n).to_a
end
 
def to_string(square)
  n = square.size
  fmt = "%#{(n*n).to_s.size + 1}d" * n
  square.inject(""){|str,row| str << fmt % row << "\n"}
end
 
puts to_string(double_even_magic_square(8))