diff options
| author | Abigail <abigail@abigail.be> | 2021-02-24 18:38:10 +0100 |
|---|---|---|
| committer | Abigail <abigail@abigail.be> | 2021-02-24 18:38:10 +0100 |
| commit | bb123a18ffd0376c3a306f0cbd6b5746bbf4956b (patch) | |
| tree | b6385c5b3d405bdedcd7a85e71997c83723bd413 /challenge-101 | |
| parent | 22ed8206ae15baebbaa9732c5124d538135beae6 (diff) | |
| download | perlweeklychallenge-club-bb123a18ffd0376c3a306f0cbd6b5746bbf4956b.tar.gz perlweeklychallenge-club-bb123a18ffd0376c3a306f0cbd6b5746bbf4956b.tar.bz2 perlweeklychallenge-club-bb123a18ffd0376c3a306f0cbd6b5746bbf4956b.zip | |
Ruby solution for week 101, part 2
Diffstat (limited to 'challenge-101')
| -rw-r--r-- | challenge-101/abigail/README.md | 1 | ||||
| -rw-r--r-- | challenge-101/abigail/ruby/ch-2.rb | 48 |
2 files changed, 49 insertions, 0 deletions
diff --git a/challenge-101/abigail/README.md b/challenge-101/abigail/README.md index a6488bf50a..7707028ada 100644 --- a/challenge-101/abigail/README.md +++ b/challenge-101/abigail/README.md @@ -106,5 +106,6 @@ Output: 1 because (0,0) is on the edge connecting B and C. * [Node.js](node/ch-2.js) * [Perl](perl/ch-2.pl) * [Python](python/ch-2.py) +* [Ruby](ruby/ch-2.rb) ### Blog diff --git a/challenge-101/abigail/ruby/ch-2.rb b/challenge-101/abigail/ruby/ch-2.rb new file mode 100644 index 0000000000..8c5a2d542f --- /dev/null +++ b/challenge-101/abigail/ruby/ch-2.rb @@ -0,0 +1,48 @@ +#!/usr/bin/ruby + +# +# See ../README.md +# + +# +# Run as: ruby ch-2.rb < input-file +# + +# +# See https://stackoverflow.com/questions/2049582/ +# + +# +# This determines on which side of the line through (x1, y1) and +# (x2, y2) the origin lies. If > 0, then the origin lies to the left +# of the line, if < 0, the origin lies to the right of the line, if +# = 0, the origin lies on the line. +# +def side (x1, y1, x2, y2) + return (y2 - y1) * x2 - (x2 - x1) * y2 +end + +ARGF . each_line do |_| + # + # Parse input. We need an explicit conversion from string to float + # + x1, y1, x2, y2, x3, y3 = _ . split . map {|_| _ . to_f} + + # + # Determine where the origin is relative to the three lines + # through the vertices of the triangle. Note we have to go + # in a specific order through the points. (Either clock wise, + # or counter clockwise, as long as we're consistent). + # + s1 = side x2, y2, x3, y3 + s2 = side x3, y3, x1, y1 + s3 = side x1, y1, x2, y2 + + # + # If the origin either lies to the left (or on) each of the + # lines, or to the right (or on) each of the lines, the origin + # lies inside the triangle. If not, it does not. + # + puts s1 <= 0 && s2 <= 0 && s3 <= 0 || + s1 >= 0 && s2 >= 0 && s3 >= 0 ? 1 : 0 +end |
