#!/usr/bin/perl use strict; use warnings; my $match45 = isCorrectPath (0, 0, 10, 10); for my $pair ([0, 0], [-1, 0], [-4, 0], [5, 5], [1, 5]) { if ($match45->(@$pair)) { print "Match 45 for @$pair\n"; } else { print "Fail 45 for @$pair\n"; } } my $match0 = isCorrectPath (0, 0, 10, 0); for my $pair ([0, 0], [0, -1], [0, -4], [5, 5], [100, 2]) { if ($match0->(@$pair)) { print "Match 0 for @$pair\n"; } else { print "Fail 0 for @$pair\n"; } } my $match90 = isCorrectPath (0, 0, 0, 10); for my $pair ([0, 0], [-1, -0], [-4, 0], [5, 5], [2, 100]) { if ($match90->(@$pair)) { print "Match 90 for @$pair\n"; } else { print "Fail 90 for @$pair\n"; } } sub isCorrectPath { my ($x1, $y1, $x2, $y2) = @_; my $difx = ($x2 - $x1); my $slope = $difx ? ($y2 - $y1) / $difx : undef; return sub { my ($x, $y) = @_; my $xmin = ($x - $x1); return abs($x - $x1) < 3 # Vertical line: allow 3 units either side if !defined $slope; return abs($y - $y1) < 3 # Horizontal line: allow 3 units either side if !$slope; return abs(($slope * ($x - $x1)) - ($y - $y1)) < 3; }; } #### Match 45 for 0 0 Match 45 for -1 0 Fail 45 for -4 0 Match 45 for 5 5 Fail 45 for 1 5 Match 0 for 0 0 Match 0 for 0 -1 Fail 0 for 0 -4 Fail 0 for 5 5 Match 0 for 100 2 Match 90 for 0 0 Match 90 for -1 0 Fail 90 for -4 0 Fail 90 for 5 5 Match 90 for 2 100