The Weekly Challenge 027

Intersection of Two Lines and Historical Values

Solutions on GitHub

Task 1: Intersection of Two Straight Lines

Write a script to find the intersection of two straight lines. The coordinates of the endpoints are given as (a, b) to (c, d) for Line 1 and (p, q) to (r, s) for Line 2.

Example Output

Input Line 1: (0, 0) to (2, 0) Input Line 2: (-4, -5) to (8, 1) Output: Intersection: (6, 0)

Logic

Compute the determinant det = (a - c)*(q - s) - (b - d)*(p - r). If det == 0, the lines are parallel or collinear and have no unique intersection point. Otherwise, we solve for the point (px, py) using the 2D line intersection formula.

Perl Solution

ch-1.pl

sub get_intersection ( $a, $b, $c, $d, $p, $q, $r, $s ) { my $det = ( $a - $c ) * ( $q - $s ) - ( $b - $d ) * ( $p - $r ); return undef if $det == 0; my $term1 = $a * $d - $b * $c; my $term2 = $p * $s - $q * $r; my $px = ( $term1 * ( $p - $r ) - ( $a - $c ) * $term2 ) / $det; my $py = ( $term1 * ( $q - $s ) - ( $b - $d ) * $term2 ) / $det; return [ $px, $py ]; }

Python Solution

ch-1.py

def get_intersection( a: float, b: float, c: float, d: float, p: float, q: float, r: float, s: float, ) -> tuple[float, float] | None: """Calculate the intersection point of two infinitely long 2D lines.""" det = (a - c) * (q - s) - (b - d) * (p - r) if det == 0: return None term1 = a * d - b * c term2 = p * s - q * r px = (term1 * (p - r) - (a - c) * term2) / det py = (term1 * (q - s) - (b - d) * term2) / det return (px, py)

Task 2: Historical Values

Write a script that allows you to capture and display historical values of a variable as it changes over time.

Example Output

Operations: $x = 10; $x = 20; $x -= 5; History: 10, 20, 15

Logic

Implement an object class (HistoricalVar) that encapsulates a value and an internal list recording every assignment or modification in chronological order.

Perl Solution

ch-2.pl

package HistoricalVar { sub new ( $class, $initial_value = undef ) { my $self = { value => $initial_value, history => defined $initial_value ? [$initial_value] : [], }; return bless $self, $class; } sub set ( $self, $val ) { $self->{value} = $val; push @{ $self->{history} }, $val; return $val; } sub get ($self) { return $self->{value}; } sub history ($self) { return @{ $self->{history} }; } }

Python Solution

ch-2.py

class HistoricalVar(Generic[T]): """A wrapper for a variable that records every assigned value in history.""" def __init__(self, initial_value: T | None = None) -> None: self._history: list[T] = [] if initial_value is not None: self.set(initial_value) def set(self, value: T) -> T: self._history.append(value) return value def get(self) -> T | None: return self._history[-1] if self._history else None @property def history(self) -> list[T]: return list(self._history)