aboutsummaryrefslogtreecommitdiff
path: root/challenge-101/tyler-wardhaugh/python/ch-2.py
diff options
context:
space:
mode:
authorMohammad S Anwar <Mohammad.Anwar@yahoo.com>2021-02-26 05:30:27 +0000
committerGitHub <noreply@github.com>2021-02-26 05:30:27 +0000
commite3f222baca9d7a3e745a5f38b2a80f910c2c8844 (patch)
tree3ec736fbee9bb91dee801e0aa7064b5e584ed425 /challenge-101/tyler-wardhaugh/python/ch-2.py
parentd0797a82194198d2e17e0c867b6f71e143499a51 (diff)
parent7ee7cb632f67d902f69df08aa3df56224a68dacd (diff)
downloadperlweeklychallenge-club-e3f222baca9d7a3e745a5f38b2a80f910c2c8844.tar.gz
perlweeklychallenge-club-e3f222baca9d7a3e745a5f38b2a80f910c2c8844.tar.bz2
perlweeklychallenge-club-e3f222baca9d7a3e745a5f38b2a80f910c2c8844.zip
Merge pull request #3619 from tylerw/tw/challenge-101
Challenge 101
Diffstat (limited to 'challenge-101/tyler-wardhaugh/python/ch-2.py')
-rwxr-xr-xchallenge-101/tyler-wardhaugh/python/ch-2.py41
1 files changed, 41 insertions, 0 deletions
diff --git a/challenge-101/tyler-wardhaugh/python/ch-2.py b/challenge-101/tyler-wardhaugh/python/ch-2.py
new file mode 100755
index 0000000000..2f38f93038
--- /dev/null
+++ b/challenge-101/tyler-wardhaugh/python/ch-2.py
@@ -0,0 +1,41 @@
+#!/usr/bin/env python3
+"""Challenge 101, Task 2"""
+
+import sys
+
+
+DEFAULT_INPUT = [[0, 1], [1, 0], [2, 2]]
+
+
+def contains_origin(triangle):
+ """Determine if the triangle formed by the given three points cover the (0,0)
+ origin on a 2D plane, using the Barycentric Coordinate Sytem method from
+ https://totologic.blogspot.com/2014/01/accurate-point-in-triangle-test.html"""
+ (x1, y1), (x2, y2), (x3, y3) = triangle
+
+ denominator = (y2 - y3) * (x1 - x3) + (x3 - x2) * (y1 - y3)
+ A = ((y2 - y3) * (0 - x3) + (x3 - x2) * (0 - y3)) / denominator
+ B = ((y3 - y1)*(0 - x3) + (x1 - x3)*(0 - y3)) / denominator
+ C = 1 - A - B
+
+ return all(0 <= x <= 1 for x in [A, B, C])
+
+
+def main(args=None):
+ """Run the task"""
+ if args is None:
+ args = sys.argv[1:]
+
+ triangle = None
+ if args:
+ import json
+ triangle = json.loads(args[0])
+ else:
+ triangle = DEFAULT_INPUT
+
+ result = 1 if contains_origin(triangle) else 0
+ print(result)
+
+
+if __name__ == '__main__':
+ sys.exit(main())