From 468c4f1452eb759980d3b93a96c2bee38f7b239d Mon Sep 17 00:00:00 2001 From: Duane Powell Date: Tue, 24 Sep 2019 14:18:04 -0500 Subject: Commit solutions for perl weekly challenge 027 --- challenge-027/duane-powell/perl5/ch-1.pl | 62 +++++++++++++++++++++++++++++++ challenge-027/duane-powell/perl5/ch-2.pl | 63 ++++++++++++++++++++++++++++++++ 2 files changed, 125 insertions(+) create mode 100755 challenge-027/duane-powell/perl5/ch-1.pl create mode 100755 challenge-027/duane-powell/perl5/ch-2.pl diff --git a/challenge-027/duane-powell/perl5/ch-1.pl b/challenge-027/duane-powell/perl5/ch-1.pl new file mode 100755 index 0000000000..7f04eda6b6 --- /dev/null +++ b/challenge-027/duane-powell/perl5/ch-1.pl @@ -0,0 +1,62 @@ +#!/usr/bin/perl +use Modern::Perl; +use List::Util qw[min max]; + +# Write a script to find the intersection of two straight lines. The co-ordinates of the two lines should be provided as command line parameter + +usage() unless @ARGV == 8; +my ($a,$b,$c,$d,$p,$q,$r,$s) = @ARGV; +my ($x1,$y1,$z1,$x2,$y2,$z2); + +$x1 = $a-$c; +$y1 = $d-$b; +$z1 = ($x1 * $b) + ($y1 * $a); +$x2 = $p-$r; +$y2 = $s-$q; +$z2 = ($x2 * $q) + ($y2 * $p); +my $determinant = ($x2*$y1) - ($x1*$y2); + +if ($determinant == 0) { + say "Line segments ($a,$b)($c,$d) and ($p,$q)($r,$s) are parallel"; + exit; +} +my $x = ($x2 * $z1 - $x1 * $z2)/$determinant; +my $y = ($y1 * $z2 - $y2 * $z1)/$determinant; +my $intersect = ($x >= min($a,$c)) && ($x <= max($p,$r)) && ($y >= min($b,$d)) && ($y <= max($q,$s)); + +if ($intersect) { + say "Intersection of line segments ($a,$b)($c,$d) and ($p,$q)($r,$s) is ($x,$y)"; +} else { + say "Line segments ($a,$b)($c,$d) and ($p,$q)($r,$s) do not intersect"; + say "Extended segment would intersect at ($x,$y)"; +} +exit; + +sub usage { + print <new(); +sleep 1; +$h->set(1); +$h->get_history(); +sleep 1; +$h->set(1); +sleep 1; +$h->set(11); +sleep 1; +$h->set(111); +sleep 1; +$h->set(11); +sleep 1; +$h->set(1); +$h->get_history(); +exit; + +package Historical; +sub new { + my $class = shift; + my $now = time; + my $self = { + x => 0, + x_history => {$now => 0}, + }; + return bless $self, $class; +} +sub set { + my $self = shift; + my $next = shift; + if ($self->{x} != $next) { + $self->{x} = $next; + my $now = time; + $self->{x_history}{$now} = $next; + } +} +sub get_history { + my $self = shift; + say "History of x is:"; + foreach (sort (keys %{ $self->{x_history} })) { + say "$_ => ", $self->{x_history}{$_}; + } +} + +__END__ + +./ch-2.pl +History of x is: +1569256589 => 0 +1569256590 => 1 +History of x is: +1569256589 => 0 +1569256590 => 1 +1569256592 => 11 +1569256593 => 111 +1569256594 => 11 +1569256595 => 1 + -- cgit