Spaces:
Running
Running
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)) |