diff --git a/2024/day7/main.py b/2024/day7/main.py index e726aa5..5835876 100644 --- a/2024/day7/main.py +++ b/2024/day7/main.py @@ -1,6 +1,6 @@ import re -with open('input.text', 'r') as file: +with open('test.text', 'r') as file: data: list[str] = file.readlines() @@ -16,18 +16,17 @@ class Equation: tokens: list[str] = re.findall('\d+|\+|\*', eq) r = None - add = True + op = lambda x,y: x + y for token in tokens: if not r and token.isnumeric(): r = int(token) elif token == '+': - add = True + op = lambda x,y: x + y elif token == '*': - add = False - elif add: - r += int(token) - elif not add: - r *= int(token) + op = lambda x,y: x * y + else: + r = op(r, int(token)) + return r == self.result @@ -43,6 +42,46 @@ class Equation: return self.is_valid(s1) or self.is_valid(s2) else: return self.is_valid_eq(s) + + def is_valid2(self, s: str | None) -> bool: + if s == None: + s = '' + for c in self.constants: + s += (str(c) + ' ') + return self.is_valid2(s[:-1]) + elif ' ' in s: + s1 = s.replace(' ', '+', 1) + s2 = s.replace(' ', '*', 1) + + # We do the || operator right here + if s.count(' ') >= 1: + tokens: list[str] = re.findall('\d+|\+|\*| ', s) + space_i = tokens.index(' ') + + new_num = tokens[space_i - 1].strip() + tokens[space_i + 1].strip() + new_tokens = tokens[:space_i - 1] + new_i = len(new_tokens) + new_tokens.append(new_num) + new_tokens.extend(tokens[space_i + 2:]) + s3 = '' + print(new_tokens) + for i, token in enumerate(new_tokens): + if token == ' ': + continue + if i > new_i - 1: + s3 += (token + ' ') + else: + s3 += token + + print(s) + print(s3) + # exit() + + return self.is_valid2(s1) or self.is_valid2(s2) or self.is_valid2(s3[:-1]) + else: + return self.is_valid2(s1) or self.is_valid2(s2) + else: + return self.is_valid_eq(s) equations: list[Equation] = [] @@ -63,4 +102,10 @@ for equation in equations: print(f'Part 1: {total}') +# Part 2 +total = 0 +for equation in equations: + if equation.is_valid2(None): + total += equation.result +print(f'Part 2: {total}') diff --git a/2024/day7/test.text b/2024/day7/test.text index 87b8b25..9bd7043 100644 --- a/2024/day7/test.text +++ b/2024/day7/test.text @@ -1,9 +1 @@ -190: 10 19 -3267: 81 40 27 -83: 17 5 -156: 15 6 -7290: 6 8 6 15 -161011: 16 10 13 -192: 17 8 14 -21037: 9 7 18 13 -292: 11 6 16 20 \ No newline at end of file +7290: 6 8 6 15 \ No newline at end of file