Essays/MagicSquare

From J Wiki
Jump to navigation Jump to search

A magic square is a table whose rows, columns, and diagonals sum to the same number.
A magic square with an odd number of columns can be created by the verb

magic =: i:@-:@<: ([ |."0 1&.|: |."0 1) i.@,~

The verb ismagic will produce 1 if a square is magic:

ismagic =: (-: 1&|.) @ (+/ , +/"1 , +/@((<0 1)&(|: ,. (|: |.))))

Examples:

   magic 3
7 0 5
2 4 6
3 8 1
   ismagic magic 3
1



Contributed by Henry Rich.