23
0
Challenge:
Given a square input matrix A, pad the matrix with one row and one column on all four sides.
- The value of each element in the top and bottom row should be the sum of the elements in each corresponding column.
- The value of each element in the left and right column should be the sum of the elements in each corresponding row.
- The value of the elements in the top left, and bottom right corner should be the sum of the elements on the diagonal
- The value of the elements in the top right, and bottom left corner should be the sum of the elements in the anti-diagonal.
Example:
A =
1 5 3
3 2 4
2 5 5
Output:
8 6 12 12 7
9 1 5 3 9
9 3 2 4 9
12 2 5 5 12
7 6 12 12 8
Explanation:
The top left and bottom right elements are the sum of the diagonal 1+2+5=8. The top right and bottom left elements are the sum of the anti-diagonal 2+2+3=7.
The top and bottom row (except the corners) are the sum of each of the columns in A: 1+3+2=6, 5+2+5=12 and 3+4+5=12. Similarly, the left and right column (except the corners) are the sum of each of the rows of A: 1+5+3=9, 3+2+4=9 and 2+5+5=12.
Input:
- A non-empty square matrix, with non-negative integers.
- Optional format
Output:
- The matrix padded as explained above
- Optional format, but it must be the same as the input format
Test cases:
Use the submissions in this challenge if you want to convert the input format to a more suitable one (for instance [[1, 5],[0, 2]]
).
0
----------------
0 0 0
0 0 0
0 0 0
1 5
0 2
----------------
3 1 7 5
6 1 5 6
2 0 2 2
5 1 7 3
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
----------------
65 65 65 65 65 65 65
65 17 24 1 8 15 65
65 23 5 7 14 16 65
65 4 6 13 20 22 65
65 10 12 19 21 3 65
65 11 18 25 2 9 65
65 65 65 65 65 65 65
15 1 2 12
4 10 9 7
8 6 5 11
3 13 14 0
----------------
30 30 30 30 30 30
30 15 1 2 12 30
30 4 10 9 7 30
30 8 6 5 11 30
30 3 13 14 0 30
30 30 30 30 30 30
This is code-golf, so the shortest solution in each language wins. Explanations are highly encouraged.
2Is that to check magic squares? – mdahmoune – 2017-07-04T12:19:37.617
Just checking is quite a bit easier, but it's indeed easy to see if a square is magic this way, yes :-) – Stewie Griffin – 2017-07-04T12:33:15.463