Working in R.
The goal is that by handing R a set of 8 numerical values that I get back TRUE or FALSE according to whether the line segment defined by the first 4 values intersects with the line segment defined by the final 4 values.
The input is in the form (x1,x2,y1,y2) for the first line segment and the same for the second line segment. This is a peculiarity of the storage system. The actual points of the line segment are (x1,y1) and (x2,y2)
So, for example:
do_line_segments_intersect(0,2,0,2,0,2,2,0)
should return TRUE because the line segment from (0,0) to (2,2) intersects the line segment from (0,2) to (2,0)
and
do_line_segments_intersect(-1,0,0,-1,0,1,0,1)
should return FALSE because the line segment from (-1,0) to (0,-1) does not intersect with the line segment from (0,0) to (1,1)
Here's the code that I'm using.
find_line_equation <- function(x1,x2,y1,y2)
{
A <- y1 - y2
B <- x2 - x1
C = A*x1 + B*y1
return_list = list(A,B,C)
return(return_list)
}
find_the_intersection_point <- function(list_1, list_2)
{
coefficient_matrix = matrix(c(list_1[1], list_1[2], list_2[1],list_2[2]), nrow = 2, ncol = 2, byrow = TRUE)
coefficient_matrix <- as.numeric(coefficient_matrix)
coefficient_matrix = matrix(coefficient_matrix, nrow =2, ncol = 2, byrow = FALSE)
RHS_matrix = matrix(c(list_1[3], list_2[3]), nrow = 2, ncol = 1, byrow = FALSE)
RHS_matrix <- as.numeric(RHS_matrix)
RHS_matrix = matrix(RHS_matrix, nrow =2, ncol = 1, byrow = FALSE)
inverse_coefficient_matrix = solve(coefficient_matrix)
solution = inverse_coefficient_matrix %*% RHS_matrix
return(solution)
}
do_line_segments_intersect <- function(ax1,ax2,ay1,ay2,bx1,bx2,by1,by2)
{
a_coefficients <- find_line_equation(ax1,ax2,ay1,ay2)
b_coefficients <- find_line_equation(bx1,bx2,by1,by2)
intersection_point <- find_the_intersection_point(a_coefficients, b_coefficients)
#find the boundaries of the line segments. This will let us check that our intersection is within the boundaries.
max_x <- max(ax1,ax2)
min_x <- min(ax1,ax2)
max_y <- max(ay1,ay2)
min_y <- min(ay1,ay2)
#Is the intersection within the boundaries?
if(findInterval(intersection_point[1],c(min_x,max_x)) && findInterval(intersection_point[2],c(min_y,max_y)))
{
print("true1")
} else {
print("false1")
}
}
I know the code is not complete. My comparison to the max and min values should include all of the points (hence, coordinate values) rather than just half of them. And ultimately I want to return the actual boolean value rather than just a text string indicating what the value is.
The issue I'm having is the following:
If I run the code step by step on the input coordinates (-1,0,0,-1) for a_coefficients and (0,1,0,1) for b_coefficients and then run each line one-by-one then the final result is the "false" that I'm expecting.
However, if I call the function with the input like this
do_line_segments_intersect(-1,0,0,-1,0,1,0,1)
then R returns "true".
Aucun commentaire:
Enregistrer un commentaire