From 9d50931fe92b7c484904c5b93b45a8dc60abc4e7 Mon Sep 17 00:00:00 2001 From: Kees van Kempen Date: Thu, 19 Dec 2024 00:40:02 +0100 Subject: [PATCH] 2024(4): fixed the first puzzle! --- 2024/4/puzzle1.py | 46 ++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 40 insertions(+), 6 deletions(-) diff --git a/2024/4/puzzle1.py b/2024/4/puzzle1.py index 58689bc..95e3c49 100644 --- a/2024/4/puzzle1.py +++ b/2024/4/puzzle1.py @@ -31,7 +31,7 @@ def rotate(list_2d): substring += list_2d[x][y] x += 1 y += 1 - diagonal_list.append(substring) + diagonal_list.append(substring) # Reverse diagonal_list = diagonal_list[::-1] @@ -45,7 +45,39 @@ def rotate(list_2d): substring += list_2d[x][y] x += 1 y += 1 - diagonal_list.append(substring) + diagonal_list.append(substring) + + return diagonal_list + +def rotate_neg(list_2d): + x_max, y_max = len(list_2d), len(list_2d[0]) + diagonal_list = [] + + # Diagonals starting from (0,0), for the first row. + for i in range(x_max): + substring = "" + x = x_max - 1 - i + y = 0 + while x >= 0 and y < y_max: + #print(x, x_max, y, y_max) + substring += list_2d[x][y] + x -= 1 + y += 1 + diagonal_list.append(substring) + + # Reverse + diagonal_list = diagonal_list[::-1] + + # Diagonals starting from (0,1), for the first column. + for j in range(1, y_max): + substring = "" + x = x_max - 1 + y = j + while x >= 0 and y < len(list_2d[x]): + substring += list_2d[x][y] + x -= 1 + y += 1 + diagonal_list.append(substring) return diagonal_list @@ -53,24 +85,26 @@ if __name__ == "__main__": result = 0 with open("input", "r") as fp: - # Skip last line as it is empty + # Skip last line as it is empty. full_string = fp.read().split("\n")[:-1] for line in full_string: result += scan_line(line) result += scan_line(line[::-1]) + # Transpose for vertical hits. for line in transpose(full_string): result += scan_line(line) result += scan_line(line[::-1]) + # Rotate 45 degrees to one side for diagonals. diagonal_list = rotate(full_string) for line in diagonal_list: result += scan_line(line) result += scan_line(line[::-1]) - # TODO: Transposion after rotating is ill-defined. - for line in rotate(transpose(full_string)): + diagonal_list = rotate_neg(full_string) + # Rotate the other way round. + for line in diagonal_list: result += scan_line(line) result += scan_line(line[::-1]) - #transposed_file = print(f"The sum of all horizontal XMAS's equals {result}.")