Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
compare by angle solution in Clear category for Similar Triangles by stefancelmare
from typing import List, Tuple
import math
import collections
Coords = List[Tuple[int, int]]
# returns square of distance b/w two points
def lengthSquare(X, Y):
xDiff = X[0] - Y[0]
yDiff = X[1] - Y[1]
return xDiff * xDiff + yDiff * yDiff
def getAngle(A, B, C):
# Square of lengths be a2, b2, c2
a2 = lengthSquare(B, C)
b2 = lengthSquare(A, C)
c2 = lengthSquare(A, B)
# length of sides be a, b, c
a = math.sqrt(a2);
b = math.sqrt(b2);
c = math.sqrt(c2);
# From Cosine law
alpha = math.acos((b2 + c2 - a2) /
(2 * b * c));
betta = math.acos((a2 + c2 - b2) /
(2 * a * c));
gamma = math.acos((a2 + b2 - c2) /
(2 * a * b));
# Converting to degree
alpha = alpha * 180 / math.pi;
betta = betta * 180 / math.pi;
gamma = gamma * 180 / math.pi;
# printing all the angles
print("alpha : %f" %(alpha))
print("betta : %f" %(betta))
print("gamma : %f" %(gamma))
return alpha, betta, gamma
def similar_triangles(coords_1: Coords, coords_2: Coords) -> bool:
angles_1 = getAngle(coords_1[0], coords_1[1], coords_1[2]);
angles_2 = getAngle(coords_2[0], coords_2[1], coords_2[2]);
if(collections.Counter(list(angles_1)) == collections.Counter(list(angles_2))):
return True;
return False
if __name__ == '__main__':
print("Example:")
print(similar_triangles([[-4,4],[2,5],[-2,4]],[[-5,-9],[-5,-3],[-8,9]]))
# These "asserts" are used for self-checking and not for an auto-testing
assert similar_triangles([(0, 0), (1, 2), (2, 0)], [(3, 0), (4, 2), (5, 0)]) is True, 'basic'
assert similar_triangles([(0, 0), (1, 2), (2, 0)], [(3, 0), (4, 3), (5, 0)]) is False, 'different #1'
assert similar_triangles([(0, 0), (1, 2), (2, 0)], [(2, 0), (4, 4), (6, 0)]) is True, 'scaling'
assert similar_triangles([(0, 0), (0, 3), (2, 0)], [(3, 0), (5, 3), (5, 0)]) is True, 'reflection'
assert similar_triangles([(1, 0), (1, 2), (2, 0)], [(3, 0), (5, 4), (5, 0)]) is True, 'scaling and reflection'
assert similar_triangles([(1, 0), (1, 3), (2, 0)], [(3, 0), (5, 5), (5, 0)]) is False, 'different #2'
print("Coding complete? Click 'Check' to earn cool rewards!")
Jan. 12, 2021