Task 1: Straight Line
"Collinear Check: Do Points Form a Line?"
Given a list of coordinates, determine whether they all lie on a straight line.
The Strategy: Use the cross product to avoid floating-point division. Points (x1,y1), (x2,y2), (x3,y3) are collinear when (y2-y1)*(x3-x1) == (y3-y1)*(x2-x1). Check this property for all points against the first two.
Perl Implementation
sub is_straight_line {
my (@points) = @_;
return 1 if @points < 2;
return 1 if all { $_->[0] == $points[0][0] } @points;
my $dx1 = $points[1][0] - $points[0][0];
my $dy1 = $points[1][1] - $points[0][1];
return all {
my $dx2 = $_->[0] - $points[0][0];
my $dy2 = $_->[1] - $points[0][1];
$dy1 * $dx2 == $dy2 * $dx1;
} @points[ 2 .. $#points ];
}
Python Implementation
def is_straight_line(points: list[list[int]]) -> bool:
"""Check if all points are collinear."""
if len(points) < 2:
return True
if all(p[0] == points[0][0] for p in points):
return True
dx1 = points[1][0] - points[0][0]
dy1 = points[1][1] - points[0][1]
for p in points[2:]:
dx2 = p[0] - points[0][0]
dy2 = p[1] - points[0][1]
if dy1 * dx2 != dy2 * dx1:
return False
return True