diff --git a/Questions/Day 3.py b/Questions/Day 3.py index ae5c4dc..6fc734e 100644 --- a/Questions/Day 3.py +++ b/Questions/Day 3.py @@ -10,7 +10,6 @@ def question_1(data: list[str]): symbols = get_symbols(new_data) # Get all number positions number_positions = get_number_positions(new_data) - # print(number_positions) # Convert to numpy matrix data = np.array(new_data) @@ -21,11 +20,12 @@ def question_1(data: list[str]): for j, value in enumerate(data[i]): if value in symbols: - j_interval = (max(0,j-1), min(j+1, 139)) - i_interval = (max(0,i-1), min(i+1, 139)) + j_interval = (j-1, j+1) + i_interval = (i-1, i+1) for number in number_positions: if (number[3] >= i_interval[0] and number[3] <= i_interval[1]) and (number[2] >= j_interval[0] and number[1] <= j_interval[1]): found_numbers.append(number) + print(f"Around character {value} on line {i} I found the following number {number[0]}") for number in set(found_numbers): sum += int(number[0]) @@ -36,6 +36,29 @@ def question_1(data: list[str]): def question_2(data: list[str]): sum = 0 + + # Convert strings to lists of characters + new_data = reformat_data(data) + # Get all number positions + number_positions = get_number_positions(new_data) + # Convert to numpy matrix + data = np.array(new_data) + + # We assume that no value is next to multiple symbols + # Go through each symbol and sum their adjacent values + for i in range(len(data)): + for j, value in enumerate(data[i]): + if value == "*": + found_numbers = [] + + j_interval = (j-1, j+1) + i_interval = (i-1, i+1) + + for number in number_positions: + if (number[3] >= i_interval[0] and number[3] <= i_interval[1]) and (number[2] >= j_interval[0] and number[1] <= j_interval[1]): + found_numbers.append(number) + if len(found_numbers) == 2: + sum += int(found_numbers[0][0]) * int(found_numbers[1][0]) print(f"Answer to question 2 is: {sum}") @@ -67,7 +90,7 @@ def get_symbols(data): for string in data: total_lists += string present_set = set(total_lists) - remove_set = {".", "1", "2", "3", "4", "5", "6", "7", "8", "9"} + remove_set = {".", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"} symbol_set = present_set.difference(remove_set) return symbol_set @@ -80,5 +103,5 @@ def reformat_data(data): if __name__ == "__main__": filepath = "Data/day3.txt" data = load_data(filepath) - question_1(data) - # question_2(data) \ No newline at end of file + # question_1(data) + question_2(data) \ No newline at end of file