diff --git a/2024/4/README.md b/2024/4/README.md index 418d087..9c55164 100644 --- a/2024/4/README.md +++ b/2024/4/README.md @@ -72,3 +72,8 @@ M.M.M.M.M. In this example, an X-MAS appears 9 times. Flip the word search from the instructions back over to the word search side and try again. How many times does an X-MAS appear? + + +Your puzzle answer was 1960. + +Both parts of this puzzle are complete! They provide two gold stars: ** diff --git a/2024/4/puzzle2.py b/2024/4/puzzle2.py new file mode 100644 index 0000000..e85f4e7 --- /dev/null +++ b/2024/4/puzzle2.py @@ -0,0 +1,30 @@ +verbose = False + +def x_mas_at(M, i: int, j: int) -> bool: + # NOTE: Checking i and j are not on the boundary is wise. + + top_left = \ + M[i - 1][j - 1] == "M" and M[i + 1][j + 1] == "S" or \ + M[i - 1][j - 1] == "S" and M[i + 1][j + 1] == "M" + top_right = \ + M[i + 1][j - 1] == "M" and M[i - 1][j + 1] == "S" or \ + M[i + 1][j - 1] == "S" and M[i - 1][j + 1] == "M" + + return top_left and top_right + +if __name__ == "__main__": + result = 0 + + with open("input", "r") as fp: + # Skip last line as it is empty. + full_string = fp.read().split("\n")[:-1] + + x_mas_count = 0 + + for i in range(1, len(full_string) - 1): + for j in range(1, len(full_string[0]) - 1): + if full_string[i][j] == "A": + if x_mas_at(full_string, i, j): + x_mas_count += 1 + + print(f"The sum of all horizontal X-MASs equals {x_mas_count}.")