Skip to content

10. Pure Magic

In this problem, you’re asked to enter your own APL function, without giving it any arguments. Your function will be checked by the APL Challenge system using several tests to see whether it is correct.

Remember from problem 2 that the rows and columns of a matrix are called its axes. The function (transpose) allows you to exchange and combine those axes.

When the right argument is a matrix, the left argument has to be one of the following three lists:

  1. 1 1 will give you the diagonal from the top left to the bottom right
  2. 1 2 will leave the matrix as it is
  3. 2 1 will flip the matrix over its diagonal, exchanging the rows and columns (hence its symbol, ; a half-circle being reflected in a diagonal mirror)

For example:

      1 1 ⍉ [1 2
             3 4]
1 4
      1 2 ⍉ [1 2
             3 4]
1 2
3 4
      2 1 ⍉ [1 2
             3 4]
1 3
2 4

A magic square is a square matrix in which all rows, columns, and diagonals (there are two; top-left to bottom-right and top-right to bottom-left) have the same sum.

Use everything that you’ve learnt so far to write a function that takes a square matrix and gives 1 if it is a magic square, 0 otherwise:

      {answer} [2 7 6
                9 5 1
                4 3 8]
1

      {answer} [1 2
                3 4]
0

      {answer} [2 3 5 8
                5 8 2 3
                4 1 7 6
                7 6 4 1]
1