The Weekly Challenge 333

Collinear Points & Zero Duplication!

Original Challenge Link

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

Task 2: Duplicate Zeros

"Double the Nothing: Shift and Trim!"

Given an array of integers, duplicate each zero by shifting remaining elements to the right. Elements beyond the original length are discarded.

The Strategy: Build a result array. For each element: if zero, push two zeros (if space allows); otherwise push the element. Stop when the result reaches the original array length.
Perl Implementation
sub duplicate_zeros {
    my (@ints) = @_;
    my @result;
    foreach my $num (@ints) {
        if ( $num == 0 ) {
            push @result, 0 if @result < @ints;
            push @result, 0 if @result < @ints;
        }
        else {
            push @result, $num if @result < @ints;
        }
    }
    return @result;
}
Python Implementation
def duplicate_zeros(ints: list[int]) -> list[int]:
    """Duplicate zeros and shift right, truncating to original length."""
    result: list[int] = []
    for num in ints:
        if num == 0:
            if len(result) < len(ints):
                result.append(0)
            if len(result) < len(ints):
                result.append(0)
        else:
            if len(result) < len(ints):
                result.append(num)
    return result