File size: 1,902 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
54
55
56
57
58
59
60
61
62
63
64
65
def mix_and_prune(secret, value):
    secret = secret ^ value  # XOR mixing
    return secret % 16777216  # pruning

def next_secret(secret):
    # Step 1: multiply by 64
    result = mix_and_prune(secret, secret * 64)
    
    # Step 2: divide by 32
    result = mix_and_prune(result, result // 32)
    
    # Step 3: multiply by 2048
    result = mix_and_prune(result, result * 2048)
    
    return result

def generate_sequence(initial, count):
    sequence = [initial]
    current = initial
    for _ in range(count):
        current = next_secret(current)
        sequence.append(current)
    return sequence

def get_price_changes(sequence):
    prices = [x % 10 for x in sequence]  # Get last digit
    changes = []
    for i in range(1, len(prices)):
        changes.append(prices[i] - prices[i-1])
    return changes, prices

def find_sequence_value(initial, target_changes):
    sequence = generate_sequence(initial, 2000)
    changes, prices = get_price_changes(sequence)
    
    # Look for the target sequence
    for i in range(len(changes) - 3):
        if changes[i:i+4] == target_changes:
            return prices[i+4]  # Return price at the end of sequence
    return 0

# Read input
with open("input.txt") as f:
    initial_numbers = [int(x.strip()) for x in f.readlines()]

# Part 1
result1 = sum(generate_sequence(n, 2000)[-1] for n in initial_numbers)
print(str(result1))

# Part 2
# Generate all possible sequences of 4 changes (-9 to 9 each)
best_sequence = None
max_bananas = 0

for a in range(-9, 10):
    for b in range(-9, 10):
        for c in range(-9, 10):
            for d in range(-9, 10):
                sequence = [a, b, c, d]
                total = sum(find_sequence_value(n, sequence) for n in initial_numbers)
                if total > max_bananas:
                    max_bananas = total
                    best_sequence = sequence

print(str(max_bananas))