To verify that the polygon is regular, you need the distance from all points, including the "last" point of your polygon to the "first" - in the code examples below, if you do not "close" the polygon, you will get an incorrect result in the first case.
And in this case you do not need the apply
function. dist
already gives you the distance between all the points, so what you need is to get the diagonal from the bottom (or top) of the matrix that returns you.
And as @Joao noted, the condition of equal sides is necessary, but not sufficient for the polygon to be regular. All your angles need to be identical too. One way to verify this, since the sides are the same, is to verify that the center of the polygon is equidistant from all points. The updated code is below.
verifica_lados_iguais <- function(poligono) {
no_vertices <- nrow(poligono)
poligono_fechado <- rbind(poligono, poligono[1])
distancias <- diag(as.matrix(dist(poligono_fechado))[1:no_vertices, 2:(no_vertices + 1)])
lados_iguais <- all(distancias == distancias[1])
}
verifica_equidistancia_centro <- function(poligono) {
c <- apply(poligono, 2, sum) / nrow(poligono)
dist_centro <- apply(poligono, 1, function(p) sqrt((c[1] - p[1])^2 + (c[2] - p[2])^2))
equidistanteCentro <- all((abs(dist_centro - dist_centro[1]) < 0.00001))
}
verifica_regular <- function(poligono) {
regular <- verifica_lados_iguais(poligono) &&
verifica_equidistancia_centro(poligono)
}
print(quadrilatero <- matrix(c(0, 0, 0, 5, 5, 5, 2, 1), ncol = 2, byrow = TRUE))
print(verifica_regular(quadrilatero))
print(quadrado <- matrix(c(0, 0, 0, 5, 5, 5, 5, 0), ncol = 2, byrow = TRUE))
print(verifica_regular(quadrado))
print(losango <- matrix(c(0, 0, 2, 1, 4, 0, 2, -1), ncol = 2, byrow = TRUE))
print(verifica_regular(losango))