File size: 1,340 Bytes
a4da721
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import re

def parse_multiplications(text):
    # Find all valid mul(X,Y) patterns where X and Y are 1-3 digit numbers
    pattern = r'mul\((\d{1,3}),(\d{1,3})\)'
    matches = re.finditer(pattern, text)
    total = 0
    
    for match in matches:
        x, y = int(match.group(1)), int(match.group(2))
        total += x * y
    
    return total

def parse_with_conditionals(text):
    # Find all instructions in order
    mul_pattern = r'mul\((\d{1,3}),(\d{1,3})\)'
    do_pattern = r'do\(\)'
    dont_pattern = r'don\'t\(\)'
    
    # Combine all patterns
    all_patterns = f'({mul_pattern}|{do_pattern}|{dont_pattern})'
    matches = re.finditer(all_patterns, text)
    
    enabled = True
    total = 0
    
    for match in matches:
        full_match = match.group(0)
        if full_match == 'do()':
            enabled = True
        elif full_match == "don't()":
            enabled = False
        else:
            # It's a multiplication
            if enabled:
                x = int(match.group(2))
                y = int(match.group(3))
                total += x * y
    
    return total

# Read input file
with open('./input.txt', 'r') as file:
    content = file.read()

# Part 1
result1 = parse_multiplications(content)
print(str(result1))

# Part 2
result2 = parse_with_conditionals(content)
print(str(result2))