diff --git a/days/03/part1.py b/days/03/part1.py new file mode 100644 index 0000000..842a85d --- /dev/null +++ b/days/03/part1.py @@ -0,0 +1,47 @@ +with open("data/input.txt", "r") as f: + data = f.read() + +table = [ + [item for item in row] + for row in data.split("\n") +] + +symbols = "&~\"#'{([-|`_\\^`])}@)]=+}$£%*!§/:;,?<>" + + +parts = [] + +positions = set() + +for i in range(len(table)): + for j in range(len(table[i])): + letter = table[i][j] + if letter in symbols: + found = False + for dx in [-1, 0, 1]: + for dy in [-1, 0, 1]: + y = i + dx + x = j + dy + if x >= 0 and x < len(table[i]) and y >= 0 and y <= len(table): + number = "" + digit = table[y][x] + if digit != "." and digit.isdigit(): + number = digit + found = True + # Extend right + shift = 1 + idx = x + shift + while idx >= 0 and idx < len(table[y]) and table[y][idx] != "." and table[y][idx].isdigit(): + number = number + table[y][idx] + idx += shift + position = (y, idx) + # Extend left + shift = -1 + idx = x + shift + while idx >= 0 and idx < len(table[y]) and table[y][idx] != "." and table[y][idx].isdigit(): + number = table[y][idx] + number + idx += shift + if position not in positions: + positions.add(position) + parts.append(int(number)) +print(sum(parts)) diff --git a/days/03/part2.py b/days/03/part2.py new file mode 100644 index 0000000..ffb623c --- /dev/null +++ b/days/03/part2.py @@ -0,0 +1,51 @@ +import numpy as np + +with open("data/input.txt", "r") as f: + data = f.read() + +table = [ + [item for item in row] + for row in data.split("\n") +] + +symbols = "&~\"#'{([-|`_\\^`])}@)]=+}$£%*!§/:;,?<>" + + +gears = [] + + +for i in range(len(table)): + for j in range(len(table[i])): + letter = table[i][j] + if letter == "*": + gear_numbers = [] + positions = set() + for dx in [-1, 0, 1]: + for dy in [-1, 0, 1]: + y = i + dx + x = j + dy + if x >= 0 and x < len(table[i]) and y >= 0 and y <= len(table): + number = "" + digit = table[y][x] + if digit != "." and digit.isdigit(): + number = digit + found = True + # Extend right + shift = 1 + idx = x + shift + while idx >= 0 and idx < len(table[y]) and table[y][idx] != "." and table[y][idx].isdigit(): + number = number + table[y][idx] + idx += shift + position = (y, idx) + # Extend left + shift = -1 + idx = x + shift + while idx >= 0 and idx < len(table[y]) and table[y][idx] != "." and table[y][idx].isdigit(): + number = table[y][idx] + number + idx += shift + if position not in positions: + positions.add(position) + gear_numbers.append(int(number)) + if len(gear_numbers) == 2: + gears.append(np.prod(gear_numbers)) +print(sum(gears))