Inspired by this Stack Overflow question.
The challenge
Input
An array of square matrices containing non-negative integers.
Output
A square matrix built from the input matrices as follows.
Let \$N \times N\$ be the size of each input matrix, and \$P\$ the number of input matrices.
For clarity, consider the following example input matrices (\$N=2\$, \$P=3\$):
3 5
4 10
6 8
12 11
2 0
9 1
- Start with the first input matrix.
- Shift the second input matrix N−1 steps down and N−1 steps right, so that its upper-left entry coincides with the lower-right entry of the previous one.
Imagine the second, shifted matrix as if it were stacked on top of the first. Sum the two values at the coincident entry. Write the other values, and fill the remaining entries with
0
to get a \$(2N-1)\times(2N-1)\$ matrix. With the example input, the result so far is3 5 0 4 16 8 0 12 11
For each remaining input matrix, stagger it so that its upper-left coincides with the lower-right of the accumulated result matrix so far. In the example, including the third input matrix gives
3 5 0 0 4 16 8 0 0 12 13 0 0 0 9 1
The ouput is the \$((N−1)P+1)\times((N−1)P+1)\$ matrix obtained after including the last input matrix.
Additional rules and clarifications
- \$N\$ and \$P\$ are positive integers.
- You can optionally take \$N\$ and \$P\$ as additional inputs.
- Input and output can be taken by any reasonable means. Their format is flexible as usual.
- Programs or functions are allowed, in any programming language. Standard loopholes are forbidden.
- Shortest code in bytes wins.
Test cases:
In each case, input matrices are shown first, then the output.
\$N=2\$, \$P=3\$:
3 5 4 10 6 8 12 11 2 0 9 1 3 5 0 0 4 16 8 0 0 12 13 0 0 0 9 1
\$N=2\$, \$P=1\$:
3 5 4 10 3 5 4 10
\$N=1\$, \$P=4\$:
4 7 23 5 39
\$N=3\$, \$P=2\$:
11 11 8 6 8 12 11 0 4 4 1 13 9 19 11 13 4 2 11 11 8 0 0 6 8 12 0 0 11 0 8 1 13 0 0 9 19 11 0 0 13 4 2
\$N=2\$, \$P=4\$:
14 13 10 0 13 20 21 3 9 22 0 8 17 3 19 16 14 13 0 0 0 10 13 20 0 0 0 21 12 22 0 0 0 0 25 3 0 0 0 19 16