This is a simpler variant of my previous challenge Don't touch the walls!, as suggested by Jonah.
Given a multi-dimensional rectangular array of integers between 0 and 9, output all the elements which are "touching the edges".
Output is very flexible: it can be in any order, and may be flattened or partially nested, but must contain every edge element the correct number of times, and may not contain any others.
Specification
"Touching the edges" is a hopefully fairly intuitive concept, but here is a specification:
Let's use this array, with shape 4, 3
.
[[1, 3, 0],
[2, 6, 7],
[4, 0, 2],
[0, 0, 0]]
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).
Here is the same array with the elements which are "touching the edge" highlighted:
[[1, 3, 0],
[2, 6, 7],
[4, 0, 2],
[0, 0, 0]]
The output could be anything like:
1 3 0 2 7 4 2 0 0 0
[1, 2, 4, 0, [0, 0, [2, 7, 0], [3]]]
[[[[[[4]]]]], [[[0, 0, 0, 0]]], [[2, 2]], [1, 7, 3]]
For the 1-dimensional array [3, 4, 9, 0, 0]
, the edges are [3, 4, 9, 0, 0]
, so the output is [3, 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]]]
The output is something like:
[4, 0, 4, 1, 0, 0, 5, 8, 6, 0, 0, 0, 0, 3, 7, 0, 4, 9, 8, 5, 0, 0, 0, 3, 0, 9, 6, 1, 0, 4, 7, 9, 0, 6, 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.
Note that arrays which have one of their dimensions as only 1, such as [4]
or [[3, 6, 5]]
, may need to be treated with care. Their respective outputs should be [4]
and [3, 6, 5]
.
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
[5]
or[[[5]]]
. If we are supposed to handle these it would make a good test case. \$\endgroup\$