Given the coordinates of any hexagon in the image below, I want to return the 6 sets coordinates of the adjacent hexagons. What is the best approach to this? I have figured out that the coordinates adjacent to (x,y) consist of all combinations of x-1,x,x 1,y-1,y,y 1 but I'm not sure the best way to approach this programmatically.
CodePudding user response:
The coordinates adjacent to (x,y) are not all combinations of those expressions because there are 9 such combinations and only 6 adjacent hexes ((1, 1), (-1, -1) and (0, 0) are not adjacent to (0, 0)).
An R function to list the correct coords needn't be any more complicated than this:
adjacent_coords = function(x) {
list(c(x[1], x[2] 1),
c(x[1] 1, x[2]),
c(x[1] 1, x[2]-1),
c(x[1], x[2]-1),
c(x[1]-1, x[2]),
c(x[1]-1, x[2] 1))
}
adjacent_coords(c(1, -1))
[[1]]
[1] 1 0
[[2]]
[1] 2 -1
[[3]]
[1] 2 -2
[[4]]
[1] 1 -2
[[5]]
[1] 0 -1
[[6]]
[1] 0 0
CodePudding user response:
something like this?
library(tibble)
neighbours <- function(x,y) {
center <- c(x,y)
n1 <- c(x, y 1)
n2 <- c(x 1, y)
n3 <- c(x 1, y - 1)
n4 <- c(x, y - 1)
n5 <- c(x - 1, y)
n6 <- c(x - 1, y 1)
return(tibble::lst(center, n1, n2, n3, n4, n5, n6))
}
neighbours(1,1)
$center
[1] 1 1
$n1
[1] 1 2
$n2
[1] 2 1
$n3
[1] 2 0
$n4
[1] 1 0
$n5
[1] 0 1
$n6
[1] 0 2