...or Toroidal Moore Neighbourhoods
Given positive integers h
, w
and a non-negative integer i
, return all of the indices surrounding i
.
You are to assume a matrix consisting of h
rows of w
elements, numbered from lowest, in the top left-hand corner, to highest, in the bottom right-hand corner, and return, in any reasonable format, a list of the indices that would surround the index, i
. This matrix is a torus (an infinite map that wraps around each edge).
For example, inputs h=4
and w=4
, would result in the matrix:
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
but more specifically:
15 12 13 14 15 12
3 0 1 2 3 0
7 4 5 6 7 4
11 8 9 10 11 8
15 12 13 14 15 12
3 0 1 2 3 0
so that if i
was 0
, you'd need to return 15, 12, 13, 3, 1, 7, 4, 5
(0-based).
Examples
0-based:
h w i Expected result
4 4 5 0, 1, 2, 4, 6, 8, 9, 10
4 4 0 15, 12, 13, 3, 1, 7, 4, 5
4 5 1 15, 16, 17, 0, 2, 5, 6, 7
1 3 2 1, 2, 0, 1, 0, 1, 2, 0
1 1 0 0, 0, 0, 0, 0, 0, 0, 0
1-based:
h w i Expected result
4 4 6 1, 2, 3, 5, 7, 9, 10, 11
4 4 1 16, 13, 14, 4, 2, 8, 5, 6
4 5 2 16, 17, 18, 1, 3, 6, 7, 8
1 3 3 2, 3, 1, 2, 1, 2, 3, 1
1 1 1 1, 1, 1, 1, 1, 1, 1, 1
Rules
- Your answer may be 0 or 1-indexed, your choice, please specify.
- You can assume that
i < h * w
(ori <= h * w
for 1-indexed answers). - You can assume that
i >= 0
(ori > 0
for 1-indexed answers). - The order of the returned values is not important as long as just the eight desired values are included.
- Standard loopholes are forbidden.
- This is code-golf so the shortest answer, in each language, wins!
Thanks to @Conor O'Brien for the more technical sounding title and @ngm for more test cases!