APL (Dyalog Classic), 27 bytes
{(⍺⊥⍺|(⍺⊤⍵)-⊢)¨1-1↓4⌽,⍳3 3}
{
}
is a function with arguments ⍺
(the dimensions h w
) and ⍵
(the index i
)
⍳3 3
is a matrix of all 2-digit ternary numbers: 0 0
, 0 1
, ..., 2 2
,
enlists the matrix as a vector
1↓4⌽
removes the centre element 1 1
by rotating 4 to the left (4⌽
) and dropping one (1↓
)
1-
subtracts from 1, giving all 8 neighbour offsets
(
)¨
applies the function train in parentheses to each offset
⍺⊤⍵
is the base-⍺
encoding of ⍵
- the coordinates of ⍵
in the matrix
(⍺⊤⍵)-⊢
subtracts the current offset, giving the coordinates of a neighbour
⍺|
is mod a
to wrap around coordinates and stay within the matrix
⍺⊥
decodes from base ⍺