20
...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!
3May we return a 3-by-3 matrix of neighbours? – Adám – 2018-07-18T13:25:28.637
@Adám I would prefer the list to not include the center cell if possible. But appreciate there are already answers. Is it easy enough to filter this out? – Dom Hastings – 2018-07-18T15:35:51.790
Does order matter? – Robert Fraser – 2018-07-18T15:47:24.560
@RobertFraser Order is not important. I'll add that to the rules. – Dom Hastings – 2018-07-18T15:48:05.190
@DomHastings I interpret that comment as: it is not allowed to return a 3 by 3 matrix or include the center cell? – JungHwan Min – 2018-07-18T15:55:50.210
@DomHastings Your last test case has the center included. – Adám – 2018-07-18T16:10:56.143
@DomHastings Allow or prohibit — there is no prefer ;-) – Adám – 2018-07-18T16:20:19.357
@Adám I will go for deny in that case. I believe all test cases only return 8 entries? But please correct me if not! I made the original version on mobile and messed up some cuts/pastes! – Dom Hastings – 2018-07-18T17:40:53.237
@JungHwanMin Correct, I've confirmed that in the rules too. – Dom Hastings – 2018-07-18T17:41:36.510