TheAlgorithms-Python
82 строки · 2.3 Кб
1"""
2Three distinct points are plotted at random on a Cartesian plane,
3for which -1000 ≤ x, y ≤ 1000, such that a triangle is formed.
4
5Consider the following two triangles:
6
7A(-340,495), B(-153,-910), C(835,-947)
8
9X(-175,41), Y(-421,-714), Z(574,-645)
10
11It can be verified that triangle ABC contains the origin, whereas
12triangle XYZ does not.
13
14Using triangles.txt (right click and 'Save Link/Target As...'), a 27K text
15file containing the coordinates of one thousand "random" triangles, find
16the number of triangles for which the interior contains the origin.
17
18NOTE: The first two examples in the file represent the triangles in the
19example given above.
20"""
21
22from __future__ import annotations
23
24from pathlib import Path
25
26
27def vector_product(point1: tuple[int, int], point2: tuple[int, int]) -> int:
28"""
29Return the 2-d vector product of two vectors.
30>>> vector_product((1, 2), (-5, 0))
3110
32>>> vector_product((3, 1), (6, 10))
3324
34"""
35return point1[0] * point2[1] - point1[1] * point2[0]
36
37
38def contains_origin(x1: int, y1: int, x2: int, y2: int, x3: int, y3: int) -> bool:
39"""
40Check if the triangle given by the points A(x1, y1), B(x2, y2), C(x3, y3)
41contains the origin.
42>>> contains_origin(-340, 495, -153, -910, 835, -947)
43True
44>>> contains_origin(-175, 41, -421, -714, 574, -645)
45False
46"""
47point_a: tuple[int, int] = (x1, y1)
48point_a_to_b: tuple[int, int] = (x2 - x1, y2 - y1)
49point_a_to_c: tuple[int, int] = (x3 - x1, y3 - y1)
50a: float = -vector_product(point_a, point_a_to_b) / vector_product(
51point_a_to_c, point_a_to_b
52)
53b: float = +vector_product(point_a, point_a_to_c) / vector_product(
54point_a_to_c, point_a_to_b
55)
56
57return a > 0 and b > 0 and a + b < 1
58
59
60def solution(filename: str = "p102_triangles.txt") -> int:
61"""
62Find the number of triangles whose interior contains the origin.
63>>> solution("test_triangles.txt")
641
65"""
66data: str = Path(__file__).parent.joinpath(filename).read_text(encoding="utf-8")
67
68triangles: list[list[int]] = []
69for line in data.strip().split("\n"):
70triangles.append([int(number) for number in line.split(",")])
71
72ret: int = 0
73triangle: list[int]
74
75for triangle in triangles:
76ret += contains_origin(*triangle)
77
78return ret
79
80
81if __name__ == "__main__":
82print(f"{solution() = }")
83