Given an N-dimensional orthogonal (non-ragged) array of non-negative integers, and an indication of which dimensions to reverse, return the array but reversed along those dimensions. The indication may be given as a Boolean list of length N or a list of a subset of the first N dimensions indexed from 0 or 1.
Please state your input formats. Code explanations are much appreciated.
Walked-through example
We are given the 2-layer 3-row 4-column 3D-array
[[[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9,10,11,12]],
[[13,14,15,16],
[17,18,19,20],
[21,22,23,24]]]
and one of
[true,false,true]
(Boolean list)
[0,2]
(0-indexed list)
[1,3]
(1-indexed list)
We need to reverse order of the first and last dimensions, that is the layers and the elements of the rows (the columns), but not the rows of each layer. First (the actual order you do this in does not matter) we reverse the order of the layers:
[[[13,14,15,16],
[17,18,19,20],
[21,22,23,24]],
[[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9,10,11,12]]]
and then we reverse the order of the elements of each row:
[[[16,15,14,13],
[20,19,18,17],
[24,23,22,21]],
[[ 4, 3, 2, 1],
[ 8, 7, 6, 5],
[12,11,10, 9]]]
Test cases
[[[1,2,3,4],[5,6,7,8],[9,10,11,12]],[[13,14,15,16],[17,18,19,20],[21,22,23,24]]]
[true,false,true]
/[0,2]
/[1,3]
↓
[[[16,15,14,13],[20,19,18,17],[24,23,22,21]],[[4,3,2,1],[8,7,6,5],[12,11,10,9]]]
[[1,2,3],[4,5,6]]
[true,false]
/[0]
/[1]
↓
[[4,5,6],[1,2,3]]
[[1],[4]]
[true,false]
/[0]
/[1]
↓
[[4],[1]]
[[7]]
[true,true]
/[0,1]
/[1,2]
↓
[[7]]
[1,2,3,4,5,6,7]
[true]
/[0]
/[1]
↓
[7,6,5,4,3,2,1]
[]
[true]
/[0]
/[1]
↓
[]
[[],[]]
[false,false]
/[]
/[]
↓
[[],[]]
[[[[3,1,4,1],[5,9,2,6]],[[5,3,5,8],[9,7,9,3]]],[[[2,3,8,4],[6,2,6,4]],[[3,3,8,3],[2,7,9,5]]]]
[true,false,true,true]
/[0,2,3]
/[1,3,4]
↓
[[[[4,6,2,6],[4,8,3,2]],[[5,9,7,2],[3,8,3,3]]],[[[6,2,9,5],[1,4,1,3]],[[3,9,7,9],[8,5,3,5]]]]
[[[[3,1,4,1],[5,9,2,6]],[[5,3,5,8],[9,7,9,3]]],[[[2,3,8,4],[6,2,6,4]],[[3,3,8,3],[2,7,9,5]]]]
[false,true,false,false]
/[1]
/[2]
↓
[[[[5,3,5,8],[9,7,9,3]],[[3,1,4,1],[5,9,2,6]]],[[[3,3,8,3],[2,7,9,5]],[[2,3,8,4],[6,2,6,4]]]]
[[[[3,1,4,1],[5,9,2,6]],[[5,3,5,8],[9,7,9,3]]],[[[2,3,8,4],[6,2,6,4]],[[3,3,8,3],[2,7,9,5]]]]
[false,false,false,false]
/[]
/[]
↓
[[[[3,1,4,1],[5,9,2,6]],[[5,3,5,8],[9,7,9,3]]],[[[2,3,8,4],[6,2,6,4]],[[3,3,8,3],[2,7,9,5]]]]
reverse
works on arbitrary arrays but only cares about the first level), generics, or recursive classes (type / object classes depending on functional or OOP, but similar use-case). The latter two are usually far more verbose. \$\endgroup\$