Given a multi-dimensional rectangular array of non-negative integers, pad it with the minimal number of zeroes so that only zeroes are "touching the edges" of the array, in every dimension.
The output must remain rectangular, have the same number of dimensions as the input, and be no smaller than the input.
Example
For the input:
[[1, 3, 0],
[2, 6, 7],
[4, 0, 2],
[0, 0, 0]]
Here is the array again with the elements which are "touching the edge" highlighted:
[[1, 3, 0],
[2, 6, 7],
[4, 0, 2],
[0, 0, 0]]
The expected output is:
[[0, 0, 0, 0, 0],
[0, 1, 3, 0, 0],
[0, 2, 6, 7, 0],
[0, 4, 0, 2, 0],
[0, 0, 0, 0, 0]]
Notice that:
- In the first row, even though there was already a zero on the right, we still had to add an extra zero on the right to keep the array properly rectangular
- The bottom row was already all zeroes, so no extra row needed to be added there
For the 1-dimensional array [3, 4, 9, 0, 0]
, the edges are [3, 4, 9, 0, 0]
.
For this 3-dimensional array:
[[[4, 0, 4, 1],
[0, 0, 5, 8],
[6, 0, 0, 0],
[0, 3, 7, 0]],
[[4, 9, 8, 5],
[0, 6, 4, 0],
[0, 0, 0, 3],
[0, 9, 6, 1]],
[[0, 4, 7, 9],
[0, 2, 0, 6],
[0, 0, 0, 0],
[7, 0, 3, 0]],
[[0, 5, 3, 5],
[0, 0, 0, 0],
[6, 5, 3, 0],
[4, 6, 0, 8]]]
the edges are:
[[[4, 0, 4, 1],
[0, 0, 5, 8],
[6, 0, 0, 0],
[0, 3, 7, 0]],
[[4, 9, 8, 5],
[0, 6, 4, 0],
[0, 0, 0, 3],
[0, 9, 6, 1]],
[[0, 4, 7, 9],
[0, 2, 0, 6],
[0, 0, 0, 0],
[7, 0, 3, 0]],
[[0, 5, 3, 5],
[0, 0, 0, 0],
[6, 5, 3, 0],
[4, 6, 0, 8]]]
Imagine each inner 2-dimensional array as a cross-section of a 3-dimensional box. The only elements which are not touching the edges are the ones on the inside of the box.
Specification
"Touching the edges" is a hopefully fairly intuitive concept, but here is a specification:
Let's use the same example input array as above; its shape is 4, 3
.
Using one-based indexing, we can index any element of the array using two integers in the ranges \$ [1, 4] \$ and \$ [1, 3] \$.
The elements which are touching the edge are those with coordinates of the form 1, y
, 4, y
, x, 1
, or x, 3
.
So, formally, we can say, for an element to be "touching the edge", at least one part of its multidimensional indices is either 1 (the minimum possible coordinate), or the maximum possible coordinate (which is the size of the array in the respective dimension).
Rules
- You do not need to handle empty arrays, e.g.
[]
or[[[], [], []], [[], [], []]]
- You may use any standard I/O method
- Standard loopholes are forbidden
- This is code-golf, so the shortest code in bytes wins
Test cases
Input | Output |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
[0,0,1,0]
->[0,1,0]
instead of[0,0,1,0]
\$\endgroup\$