aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAbigail <abigail@abigail.be>2021-02-24 01:57:22 +0100
committerAbigail <abigail@abigail.be>2021-02-24 01:57:22 +0100
commit0160915bd273e56b782576ce40a6c202883afb7b (patch)
tree3d27047346c93d9d06ce9c26b635bd9517028fa5
parentd518140907d832caabf1830dd17776aedfba0af2 (diff)
downloadperlweeklychallenge-club-0160915bd273e56b782576ce40a6c202883afb7b.tar.gz
perlweeklychallenge-club-0160915bd273e56b782576ce40a6c202883afb7b.tar.bz2
perlweeklychallenge-club-0160915bd273e56b782576ce40a6c202883afb7b.zip
AWK solution from week 101, part 2
-rw-r--r--challenge-101/abigail/README.md3
-rw-r--r--challenge-101/abigail/awk/ch-2.awk45
2 files changed, 47 insertions, 1 deletions
diff --git a/challenge-101/abigail/README.md b/challenge-101/abigail/README.md
index da150e755c..8fa0cc8907 100644
--- a/challenge-101/abigail/README.md
+++ b/challenge-101/abigail/README.md
@@ -99,6 +99,7 @@ Output: 1 because (0,0) is on the edge connecting B and C.
~~~~
### Solutions
-* [Perl](perl/ch-1.pl)
+* [AWK](awk/ch-2.awk)
+* [Perl](perl/ch-2.pl)
### Blog
diff --git a/challenge-101/abigail/awk/ch-2.awk b/challenge-101/abigail/awk/ch-2.awk
new file mode 100644
index 0000000000..d8d3bc561b
--- /dev/null
+++ b/challenge-101/abigail/awk/ch-2.awk
@@ -0,0 +1,45 @@
+#!/usr/bin/awk
+
+#
+# See ../README.md
+#
+
+#
+# Run as: awk -f ch-2.awk < 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.
+#
+function side (x1, y1, x2, y2) {
+ return (y2 - y1) * x2 - (x2 - x1) * y2
+}
+
+{
+ # x1 y1 x2 y2 x3 y3
+ # $1 $2 $3 $4 $5 $6
+ #
+ # 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($3, $4, $5, $6)
+ s2 = side($5, $6, $1, $2)
+ s3 = side($1, $2, $3, $4)
+
+ #
+ # 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.
+ #
+ print (s1 <= 0 && s2 <= 0 && s3 <= 0 ||
+ s1 >= 0 && s2 >= 0 && s3 >= 0 ? 1 : 0)
+}