The weekly challenge 293 - Task 2: Boomerang
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-293/#TASK2 3 # 4 # Task 2: Boomerang 5 # ================= 6 # 7 # You are given an array of points, (x, y). 8 # 9 # Write a script to find out if the given points are a boomerang. 10 # 11 ### A boomerang is a set of three points that are all distinct and not in a 12 ### straight line. 13 # 14 ## Example 1 15 ## 16 ## Input: @points = ( [1, 1], [2, 3], [3,2] ) 17 ## Output: true 18 # 19 ## Example 2 20 ## 21 ## Input: @points = ( [1, 1], [2, 2], [3, 3] ) 22 ## Output: false 23 # 24 ## Example 3 25 ## 26 ## Input: @points = ( [1, 1], [1, 2], [2, 3] ) 27 ## Output: true 28 # 29 ## Example 4 30 ## 31 ## Input: @points = ( [1, 1], [1, 2], [1, 3] ) 32 ## Output: false 33 # 34 ## Example 5 35 ## 36 ## Input: @points = ( [1, 1], [2, 1], [3, 1] ) 37 ## Output: false 38 # 39 ## Example 6 40 ## 41 ## Input: @points = ( [0, 0], [2, 3], [4, 5] ) 42 ## Output: true 43 # 44 ############################################################ 45 ## 46 ## discussion 47 ## 48 ############################################################ 49 # 50 # 3 points are in a straight line if from the first point, 51 # delta y / delta x stays the same to both other points. 52 # (In other words, the slope is constant) 53 54 use strict; 55 use warnings; 56 57 boomerang( [1, 1], [2, 3], [3, 2] ); 58 boomerang( [1, 1], [2, 2], [3, 3] ); 59 boomerang( [1, 1], [1, 2], [2, 3] ); 60 boomerang( [1, 1], [1, 2], [1, 3] ); 61 boomerang( [1, 1], [2, 1], [3, 1] ); 62 boomerang( [0, 0], [2, 3], [4, 5] ); 63 64 sub boomerang { 65 my @points = @_; 66 print "Input: (" . join(", ", map { "[$_->[0], $_->[1]]" } @points ) . ")\n"; 67 if( $points[0]->[0] == $points[1]->[0] ) { 68 if($points[0]->[0] == $points[2]->[0]) { 69 # slope from first to second point is == slope from first to third point 70 return print "Output: false\n"; 71 } else { 72 # slope from first to second point is != slope from first to third point 73 return print "Output: true\n"; 74 } 75 } elsif ( $points[0]->[0] == $points[2]->[0] ) { 76 # slope from first to second point is != slope from first to third point 77 return print "Output: true\n"; 78 } 79 if(slope($points[0], $points[1]) == slope($points[0], $points[2]) ) { 80 print "Output: false\n"; 81 } else { 82 print "Output: true\n"; 83 } 84 } 85 86 87 sub slope { 88 my ($x, $y) = @_; 89 my $slope = ($y->[1] - $x->[1]) / ($y->[0] - $x->[0]); 90 return $slope; 91 } 92