The task is to write a function that returns all its neighbors for an element. Diagonal elements are not considered neighbors.
In general, the problem is solved, but if the elements fall outside the matrix, the compiler generates runtime error: index out of range [-1] . Now I'm thinking of making a condition that excludes data outside the matrix. Can you tell me how such a condition would look like? I've already tried something like: if element = -1, then remove element from response. But it doesn't work.
package main
import "fmt"
func Input(y, x int) []int {
matrix := [][]int{
[]int{0, 2, 3},
[]int{2, 3, 1},
[]int{8, 7, 4},
[]int{3, 2, 1},
}
k := []int{matrix[y+1][x], matrix[y-1][x], matrix[y][x+1], matrix[y][x-1]}
for _, z := range k {
if z == -1 { //error
return append(k[z:], k[:z-1]...)
}
}
return k
}
func main() {
fmt.Println(Input(0, 0))
}