2

The problem I met is I have to visit all the eight neighbors of an element [i, j] in a 2D array.

However, considering the error of array out of bound, I have to do a lot of if else statement on [i-1, j] or [i+1, j]...It's kind of verbose to me.

So I wonder if there is any efficient way to implement this kind of problem in Go?
Like error-catching system?

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
xxx222
  • 2,980
  • 5
  • 34
  • 53
  • 3
    Go is a verbose language. It's only 4 or 8 accesses depending if you're taking those diagonally neighboring items. Just write it out in a clean straight forward conditional structure. It's still a 20-30 line function, that's not really a big deal. – evanmcdonnal Oct 17 '15 at 23:24
  • 1
    I think you're approaching the problem wrong, you should know the bounds, maybe if you share some code someone can help better. – OneOfOne Oct 18 '15 at 06:31
  • The only efficient way of doing it is by minimizing the amount of required bounds checks. But I guess that you have already figured this out. Now how to do it entirely depends on your use case. Do you scan the whole array in a loop (cellular automaton)? Or are you checking elements at random? Sharing some code would definitely help. – wldsvc Oct 19 '15 at 01:05

1 Answers1

0

The general solution would follow the pseudo-code presented here.
See for a Go example this yucchiy/minesweeper field.go#GetNeighbors(x, y int).

It depends if you can enrich your data structure with an actual Array object composed of Fields, each one knowing its neighbor. Then "visiting neighbor elements in a 2-D array" become asking a Field for the list of Fields which are its neighbor.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250