Part 1
In this puzzle, we are given a series of integer threeples and are asked if they could belong to a triangle. The only way 3 side lengths do not form a triangle is if one side is larger or equal to the sum of the two other sides. So we write a function to check this condition:
def is_triangle(side_1, side_2, side_3):
if side_1 >= side_2 + side_3:
return False
if side_2 >= side_1 + side_3:
return False
if side_3 >= side_1 + side_2:
return False
return True
We then iterate over all sides and count the number of valid triangles for the answer.
Part 2
In part 2, we are given the same list of integers, but are asked to iterate the list vertically in groups of 3. So starting with the first column of the first three lines, then the next three lines and so on until the end of the column. We then continue with column 2 and 3 from top to bottom.
The function to check for triangles can be reused, we just have to modify the iteration. Since we do not care about the order in which we check the triangles, we iterate over all columns simultaneously.
for i in range(len(lines) // 3):
for col in range(3):
if is_triangle(lines[3*i][col], lines[3*i+1][col], lines[3*i+2][col]):
num_triangles += 1
No comments:
Post a Comment